Welcome to mirror list, hosted at ThFree Co, Russian Federation.

git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CMakeLists.txt246
-rw-r--r--GNUmakefile95
-rw-r--r--SConstruct13
-rwxr-xr-xbuild_files/build_environment/prepare_release_env.sh1483
-rw-r--r--build_files/buildbot/config/user-config-glibc211-i686.py145
-rw-r--r--build_files/buildbot/config/user-config-glibc211-x86_64.py144
-rw-r--r--build_files/buildbot/config/user-config-glibc27-i686.py (renamed from build_files/buildbot/config/user-config-i686.py)11
-rw-r--r--build_files/buildbot/config/user-config-glibc27-x86_64.py (renamed from build_files/buildbot/config/user-config-x86_64.py)8
-rw-r--r--build_files/buildbot/config/user-config-player-glibc211-i686.py112
-rw-r--r--build_files/buildbot/config/user-config-player-glibc211-x86_64.py112
-rw-r--r--build_files/buildbot/config/user-config-player-glibc27-i686.py (renamed from build_files/buildbot/config/user-config-player-i686.py)8
-rw-r--r--build_files/buildbot/config/user-config-player-glibc27-x86_64.py (renamed from build_files/buildbot/config/user-config-player-x86_64.py)8
-rw-r--r--build_files/buildbot/master.cfg61
-rw-r--r--build_files/buildbot/master_unpack.py2
-rw-r--r--build_files/buildbot/slave_compile.py18
-rw-r--r--build_files/buildbot/slave_pack.py20
-rw-r--r--build_files/cmake/clang_array_check.py353
-rw-r--r--build_files/cmake/cmake_consistency_check_config.py2
-rwxr-xr-xbuild_files/cmake/cmake_qtcreator_project.py8
-rw-r--r--build_files/cmake/cmake_static_check_clang_array.py77
-rw-r--r--build_files/cmake/cmake_static_check_cppcheck.py3
-rw-r--r--build_files/cmake/cmake_static_check_smatch.py3
-rw-r--r--build_files/cmake/cmake_static_check_sparse.py3
-rw-r--r--build_files/cmake/cmake_static_check_splint.py3
-rw-r--r--build_files/cmake/config/blender_lite.cmake3
-rw-r--r--build_files/cmake/macros.cmake8
-rwxr-xr-xbuild_files/cmake/project_info.py12
-rw-r--r--build_files/cmake/project_source_info.py26
-rw-r--r--build_files/package_spec/rpm/blender.spec.in1
-rw-r--r--build_files/scons/config/linux-config.py2
-rw-r--r--build_files/scons/config/win32-mingw-config.py6
-rw-r--r--build_files/scons/config/win64-mingw-config.py4
-rw-r--r--build_files/scons/tools/Blender.py24
-rw-r--r--build_files/scons/tools/btools.py36
-rw-r--r--doc/guides/interface_API.txt16
-rw-r--r--doc/manpage/blender.14
-rw-r--r--doc/python_api/examples/bpy.types.Operator.4.py4
-rw-r--r--doc/python_api/examples/bpy.types.Operator.5.py4
-rw-r--r--doc/python_api/rst/bge.constraints.rst8
-rw-r--r--doc/python_api/rst/bge.logic.rst6
-rw-r--r--doc/python_api/rst/bge.texture.rst23
-rw-r--r--doc/python_api/rst/bge.types.rst121
-rw-r--r--doc/python_api/rst/change_log.rst1499
-rw-r--r--doc/python_api/rst/info_overview.rst2
-rw-r--r--doc/python_api/rst/info_quickstart.rst20
-rw-r--r--doc/python_api/sphinx_changelog_gen.py13
-rw-r--r--doc/python_api/sphinx_doc_gen.py147
-rw-r--r--extern/Eigen3/Eigen/Cholesky7
-rw-r--r--extern/Eigen3/Eigen/CholmodSupport45
-rw-r--r--extern/Eigen3/Eigen/Core60
-rw-r--r--extern/Eigen3/Eigen/Eigen2Support46
-rw-r--r--extern/Eigen3/Eigen/Eigenvalues10
-rw-r--r--extern/Eigen3/Eigen/Geometry4
-rw-r--r--extern/Eigen3/Eigen/Householder4
-rw-r--r--extern/Eigen3/Eigen/IterativeLinearSolvers40
-rw-r--r--extern/Eigen3/Eigen/Jacobi4
-rw-r--r--extern/Eigen3/Eigen/LU7
-rw-r--r--extern/Eigen3/Eigen/LeastSquares4
-rw-r--r--extern/Eigen3/Eigen/OrderingMethods23
-rw-r--r--extern/Eigen3/Eigen/PaStiXSupport46
-rw-r--r--extern/Eigen3/Eigen/PardisoSupport30
-rw-r--r--extern/Eigen3/Eigen/QR8
-rw-r--r--extern/Eigen3/Eigen/SVD7
-rw-r--r--extern/Eigen3/Eigen/Sparse66
-rw-r--r--extern/Eigen3/Eigen/SparseCholesky30
-rw-r--r--extern/Eigen3/Eigen/SparseCore66
-rw-r--r--extern/Eigen3/Eigen/StdDeque21
-rw-r--r--extern/Eigen3/Eigen/StdList21
-rw-r--r--extern/Eigen3/Eigen/StdVector21
-rw-r--r--extern/Eigen3/Eigen/SuperLUSupport59
-rw-r--r--extern/Eigen3/Eigen/UmfPackSupport36
-rw-r--r--extern/Eigen3/Eigen/src/Cholesky/LDLT.h172
-rw-r--r--extern/Eigen3/Eigen/src/Cholesky/LLT.h172
-rw-r--r--extern/Eigen3/Eigen/src/Cholesky/LLT_MKL.h102
-rw-r--r--extern/Eigen3/Eigen/src/CholmodSupport/CholmodSupport.h579
-rw-r--r--extern/Eigen3/Eigen/src/Core/Array.h24
-rw-r--r--extern/Eigen3/Eigen/src/Core/ArrayBase.h31
-rw-r--r--extern/Eigen3/Eigen/src/Core/ArrayWrapper.h53
-rw-r--r--extern/Eigen3/Eigen/src/Core/Assign.h132
-rw-r--r--extern/Eigen3/Eigen/src/Core/Assign_MKL.h224
-rw-r--r--extern/Eigen3/Eigen/src/Core/BandMatrix.h26
-rw-r--r--extern/Eigen3/Eigen/src/Core/Block.h46
-rw-r--r--extern/Eigen3/Eigen/src/Core/BooleanRedux.h37
-rw-r--r--extern/Eigen3/Eigen/src/Core/CommaInitializer.h25
-rw-r--r--extern/Eigen3/Eigen/src/Core/CwiseBinaryOp.h29
-rw-r--r--extern/Eigen3/Eigen/src/Core/CwiseNullaryOp.h49
-rw-r--r--extern/Eigen3/Eigen/src/Core/CwiseUnaryOp.h27
-rw-r--r--extern/Eigen3/Eigen/src/Core/CwiseUnaryView.h27
-rw-r--r--extern/Eigen3/Eigen/src/Core/DenseBase.h28
-rw-r--r--extern/Eigen3/Eigen/src/Core/DenseCoeffsBase.h33
-rw-r--r--extern/Eigen3/Eigen/src/Core/DenseStorage.h47
-rw-r--r--extern/Eigen3/Eigen/src/Core/Diagonal.h59
-rw-r--r--extern/Eigen3/Eigen/src/Core/DiagonalMatrix.h31
-rw-r--r--extern/Eigen3/Eigen/src/Core/DiagonalProduct.h28
-rw-r--r--extern/Eigen3/Eigen/src/Core/Dot.h33
-rw-r--r--extern/Eigen3/Eigen/src/Core/EigenBase.h24
-rw-r--r--extern/Eigen3/Eigen/src/Core/Flagged.h25
-rw-r--r--extern/Eigen3/Eigen/src/Core/ForceAlignedAccess.h25
-rw-r--r--extern/Eigen3/Eigen/src/Core/Functors.h115
-rw-r--r--extern/Eigen3/Eigen/src/Core/Fuzzy.h29
-rw-r--r--extern/Eigen3/Eigen/src/Core/GeneralProduct.h613
-rw-r--r--extern/Eigen3/Eigen/src/Core/GenericPacketMath.h27
-rw-r--r--extern/Eigen3/Eigen/src/Core/GlobalFunctions.h48
-rw-r--r--extern/Eigen3/Eigen/src/Core/IO.h27
-rw-r--r--extern/Eigen3/Eigen/src/Core/Map.h25
-rw-r--r--extern/Eigen3/Eigen/src/Core/MapBase.h23
-rw-r--r--extern/Eigen3/Eigen/src/Core/MathFunctions.h41
-rw-r--r--extern/Eigen3/Eigen/src/Core/Matrix.h44
-rw-r--r--extern/Eigen3/Eigen/src/Core/MatrixBase.h36
-rw-r--r--extern/Eigen3/Eigen/src/Core/NestByValue.h25
-rw-r--r--extern/Eigen3/Eigen/src/Core/NoAlias.h25
-rw-r--r--extern/Eigen3/Eigen/src/Core/NumTraits.h41
-rw-r--r--extern/Eigen3/Eigen/src/Core/PermutationMatrix.h31
-rw-r--r--extern/Eigen3/Eigen/src/Core/PlainObjectBase.h103
-rw-r--r--extern/Eigen3/Eigen/src/Core/Product.h643
-rw-r--r--extern/Eigen3/Eigen/src/Core/ProductBase.h32
-rw-r--r--extern/Eigen3/Eigen/src/Core/Random.h25
-rw-r--r--extern/Eigen3/Eigen/src/Core/Redux.h64
-rw-r--r--extern/Eigen3/Eigen/src/Core/Replicate.h33
-rw-r--r--extern/Eigen3/Eigen/src/Core/ReturnByValue.h25
-rw-r--r--extern/Eigen3/Eigen/src/Core/Reverse.h32
-rw-r--r--extern/Eigen3/Eigen/src/Core/Select.h46
-rw-r--r--extern/Eigen3/Eigen/src/Core/SelfAdjointView.h41
-rw-r--r--extern/Eigen3/Eigen/src/Core/SelfCwiseBinaryOp.h35
-rw-r--r--extern/Eigen3/Eigen/src/Core/SolveTriangular.h47
-rw-r--r--extern/Eigen3/Eigen/src/Core/StableNorm.h31
-rw-r--r--extern/Eigen3/Eigen/src/Core/Stride.h25
-rw-r--r--extern/Eigen3/Eigen/src/Core/Swap.h36
-rw-r--r--extern/Eigen3/Eigen/src/Core/Transpose.h31
-rw-r--r--extern/Eigen3/Eigen/src/Core/Transpositions.h27
-rw-r--r--extern/Eigen3/Eigen/src/Core/TriangularMatrix.h57
-rw-r--r--extern/Eigen3/Eigen/src/Core/VectorBlock.h24
-rw-r--r--extern/Eigen3/Eigen/src/Core/VectorwiseOp.h109
-rw-r--r--extern/Eigen3/Eigen/src/Core/Visitor.h31
-rw-r--r--extern/Eigen3/Eigen/src/Core/arch/AltiVec/Complex.h27
-rw-r--r--extern/Eigen3/Eigen/src/Core/arch/AltiVec/PacketMath.h29
-rw-r--r--extern/Eigen3/Eigen/src/Core/arch/Default/Settings.h21
-rw-r--r--extern/Eigen3/Eigen/src/Core/arch/NEON/Complex.h25
-rw-r--r--extern/Eigen3/Eigen/src/Core/arch/NEON/PacketMath.h28
-rw-r--r--extern/Eigen3/Eigen/src/Core/arch/SSE/Complex.h31
-rw-r--r--extern/Eigen3/Eigen/src/Core/arch/SSE/MathFunctions.h29
-rw-r--r--extern/Eigen3/Eigen/src/Core/arch/SSE/PacketMath.h52
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/CoeffBasedProduct.h63
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/GeneralBlockPanelKernel.h275
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrix.h43
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular.h41
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular_MKL.h146
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrix_MKL.h118
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector.h41
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector_MKL.h131
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/Parallelizer.h47
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix.h29
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix_MKL.h295
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector.h50
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector_MKL.h114
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/SelfadjointProduct.h31
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/SelfadjointRank2Update.h29
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix.h112
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix_MKL.h309
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector.h101
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector_MKL.h247
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/TriangularSolverMatrix.h114
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/TriangularSolverMatrix_MKL.h155
-rw-r--r--extern/Eigen3/Eigen/src/Core/products/TriangularSolverVector.h25
-rw-r--r--extern/Eigen3/Eigen/src/Core/util/BlasUtil.h47
-rw-r--r--extern/Eigen3/Eigen/src/Core/util/Constants.h78
-rw-r--r--extern/Eigen3/Eigen/src/Core/util/DisableStupidWarnings.h4
-rw-r--r--extern/Eigen3/Eigen/src/Core/util/ForwardDeclarations.h27
-rw-r--r--extern/Eigen3/Eigen/src/Core/util/MKL_support.h109
-rw-r--r--extern/Eigen3/Eigen/src/Core/util/Macros.h44
-rw-r--r--extern/Eigen3/Eigen/src/Core/util/Memory.h105
-rw-r--r--extern/Eigen3/Eigen/src/Core/util/Meta.h42
-rw-r--r--extern/Eigen3/Eigen/src/Core/util/NonMPL2.h3
-rw-r--r--extern/Eigen3/Eigen/src/Core/util/StaticAssert.h45
-rw-r--r--extern/Eigen3/Eigen/src/Core/util/XprHelper.h60
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Block.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Cwise.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/CwiseOperators.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AlignedBox.h33
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Geometry/All.h2
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AngleAxis.h24
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Hyperplane.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Geometry/ParametrizedLine.h24
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Quaternion.h43
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Rotation2D.h24
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Geometry/RotationBase.h31
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Scaling.h24
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Transform.h24
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Translation.h24
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/LU.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Lazy.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/LeastSquares.h24
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Macros.h21
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/MathFunctions.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Memory.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Meta.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/Minor.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/QR.h24
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/SVD.h27
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/TriangularSolver.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigen2Support/VectorBlock.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/ComplexEigenSolver.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur.h72
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur_MKL.h94
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/EigenSolver.h32
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/EigenvaluesCommon.h31
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h26
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h27
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h25
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/RealSchur.h92
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/RealSchur_MKL.h83
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver.h327
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver_MKL.h92
-rw-r--r--extern/Eigen3/Eigen/src/Eigenvalues/Tridiagonalization.h33
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/AlignedBox.h67
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/AngleAxis.h27
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/EulerAngles.h24
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/Homogeneous.h39
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/Hyperplane.h25
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/OrthoMethods.h39
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/ParametrizedLine.h67
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/Quaternion.h77
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/Rotation2D.h27
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/RotationBase.h37
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/Scaling.h40
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/Transform.h115
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/Translation.h31
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/Umeyama.h25
-rw-r--r--extern/Eigen3/Eigen/src/Geometry/arch/Geometry_SSE.h31
-rw-r--r--extern/Eigen3/Eigen/src/Householder/BlockHouseholder.h27
-rw-r--r--extern/Eigen3/Eigen/src/Householder/Householder.h73
-rw-r--r--extern/Eigen3/Eigen/src/Householder/HouseholderSequence.h74
-rw-r--r--extern/Eigen3/Eigen/src/IterativeLinearSolvers/BasicPreconditioners.h149
-rw-r--r--extern/Eigen3/Eigen/src/IterativeLinearSolvers/BiCGSTAB.h254
-rw-r--r--extern/Eigen3/Eigen/src/IterativeLinearSolvers/ConjugateGradient.h251
-rw-r--r--extern/Eigen3/Eigen/src/IterativeLinearSolvers/IncompleteLUT.h466
-rw-r--r--extern/Eigen3/Eigen/src/IterativeLinearSolvers/IterativeSolverBase.h254
-rw-r--r--extern/Eigen3/Eigen/src/Jacobi/Jacobi.h32
-rw-r--r--extern/Eigen3/Eigen/src/LU/Determinant.h25
-rw-r--r--extern/Eigen3/Eigen/src/LU/FullPivLU.h26
-rw-r--r--extern/Eigen3/Eigen/src/LU/Inverse.h27
-rw-r--r--extern/Eigen3/Eigen/src/LU/PartialPivLU.h25
-rw-r--r--extern/Eigen3/Eigen/src/LU/PartialPivLU_MKL.h85
-rw-r--r--extern/Eigen3/Eigen/src/LU/arch/Inverse_SSE.h27
-rw-r--r--extern/Eigen3/Eigen/src/OrderingMethods/Amd.h439
-rw-r--r--extern/Eigen3/Eigen/src/PaStiXSupport/PaStiXSupport.h742
-rw-r--r--extern/Eigen3/Eigen/src/PardisoSupport/PardisoSupport.h614
-rw-r--r--extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR.h24
-rw-r--r--extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR_MKL.h98
-rw-r--r--extern/Eigen3/Eigen/src/QR/FullPivHouseholderQR.h122
-rw-r--r--extern/Eigen3/Eigen/src/QR/HouseholderQR.h24
-rw-r--r--extern/Eigen3/Eigen/src/QR/HouseholderQR_MKL.h69
-rw-r--r--extern/Eigen3/Eigen/src/SVD/JacobiSVD.h294
-rw-r--r--extern/Eigen3/Eigen/src/SVD/JacobiSVD_MKL.h92
-rw-r--r--extern/Eigen3/Eigen/src/SVD/UpperBidiagonalization.h25
-rw-r--r--extern/Eigen3/Eigen/src/Sparse/DynamicSparseMatrix.h346
-rw-r--r--extern/Eigen3/Eigen/src/Sparse/SparseCwiseUnaryOp.h146
-rw-r--r--extern/Eigen3/Eigen/src/Sparse/SparseFuzzy.h41
-rw-r--r--extern/Eigen3/Eigen/src/Sparse/SparseMatrix.h651
-rw-r--r--extern/Eigen3/Eigen/src/Sparse/SparseSparseProduct.h401
-rw-r--r--extern/Eigen3/Eigen/src/Sparse/SparseTriangularView.h100
-rw-r--r--extern/Eigen3/Eigen/src/SparseCholesky/SimplicialCholesky.h873
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/AmbiVector.h (renamed from extern/Eigen3/Eigen/src/Sparse/AmbiVector.h)32
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/CompressedStorage.h (renamed from extern/Eigen3/Eigen/src/Sparse/CompressedStorage.h)36
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/ConservativeSparseSparseProduct.h245
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/CoreIterators.h (renamed from extern/Eigen3/Eigen/src/Sparse/CoreIterators.h)28
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/MappedSparseMatrix.h (renamed from extern/Eigen3/Eigen/src/Sparse/MappedSparseMatrix.h)88
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseAssign.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseAssign.h)0
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseBlock.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseBlock.h)212
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseCwiseBinaryOp.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseCwiseBinaryOp.h)87
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseCwiseUnaryOp.h163
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseDenseProduct.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseDenseProduct.h)147
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseDiagonalProduct.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseDiagonalProduct.h)25
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseDot.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseDot.h)41
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseFuzzy.h26
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseMatrix.h1116
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseMatrixBase.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseMatrixBase.h)434
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparsePermutation.h148
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseProduct.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseProduct.h)103
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseRedux.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseRedux.h)27
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseSelfAdjointView.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseSelfAdjointView.h)176
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseSparseProductWithPruning.h149
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseTranspose.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseTranspose.h)41
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseTriangularView.h164
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseUtil.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseUtil.h)105
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseVector.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseVector.h)205
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/SparseView.h (renamed from extern/Eigen3/Eigen/src/Sparse/SparseView.h)37
-rw-r--r--extern/Eigen3/Eigen/src/SparseCore/TriangularSolver.h (renamed from extern/Eigen3/Eigen/src/Sparse/TriangularSolver.h)69
-rw-r--r--extern/Eigen3/Eigen/src/StlSupport/StdDeque.h21
-rw-r--r--extern/Eigen3/Eigen/src/StlSupport/StdList.h21
-rw-r--r--extern/Eigen3/Eigen/src/StlSupport/StdVector.h21
-rw-r--r--extern/Eigen3/Eigen/src/StlSupport/details.h21
-rw-r--r--extern/Eigen3/Eigen/src/SuperLUSupport/SuperLUSupport.h1025
-rw-r--r--extern/Eigen3/Eigen/src/UmfPackSupport/UmfPackSupport.h431
-rw-r--r--extern/Eigen3/Eigen/src/misc/Image.h25
-rw-r--r--extern/Eigen3/Eigen/src/misc/Kernel.h25
-rw-r--r--extern/Eigen3/Eigen/src/misc/Solve.h27
-rw-r--r--extern/Eigen3/Eigen/src/misc/SparseSolve.h111
-rw-r--r--extern/Eigen3/Eigen/src/misc/blas.h658
-rw-r--r--extern/Eigen3/Eigen/src/plugins/ArrayCwiseBinaryOps.h56
-rw-r--r--extern/Eigen3/Eigen/src/plugins/BlockMethods.h21
-rw-r--r--extern/Eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h21
-rw-r--r--extern/Eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h21
-rw-r--r--extern/Eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h42
-rw-r--r--extern/Eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h21
-rw-r--r--extern/bullet2/patches/convex_hull.patch127
-rw-r--r--extern/bullet2/readme.txt4
-rw-r--r--extern/bullet2/src/Bullet-C-Api.h10
-rw-r--r--extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp59
-rw-r--r--extern/bullet2/src/LinearMath/btConvexHullComputer.cpp2
-rw-r--r--extern/bullet2/src/LinearMath/btConvexHullComputer.h1
-rw-r--r--extern/carve/CMakeLists.txt2
-rw-r--r--extern/libmv/CMakeLists.txt19
-rwxr-xr-xextern/libmv/bundle.sh6
-rw-r--r--extern/libmv/libmv-capi.cpp14
-rw-r--r--extern/libmv/libmv-capi.h17
-rw-r--r--extern/libmv/libmv/multiview/euclidean_resection.cc46
-rw-r--r--extern/libmv/libmv/multiview/euclidean_resection.h12
-rw-r--r--extern/libmv/libmv/multiview/fundamental.cc4
-rw-r--r--extern/libmv/libmv/multiview/homography.cc2
-rw-r--r--extern/libmv/libmv/numeric/levenberg_marquardt.h10
-rw-r--r--extern/libmv/libmv/simple_pipeline/detect.cc2
-rw-r--r--extern/libmv/libmv/simple_pipeline/initialize_reconstruction.cc1
-rw-r--r--extern/libmv/libmv/simple_pipeline/intersect.cc1
-rw-r--r--extern/libmv/libmv/simple_pipeline/pipeline.cc29
-rw-r--r--extern/libmv/libmv/simple_pipeline/pipeline.h12
-rw-r--r--extern/libmv/libmv/simple_pipeline/reconstruction.h11
-rw-r--r--extern/libmv/libmv/simple_pipeline/resect.cc21
-rw-r--r--extern/libmv/libmv/simple_pipeline/resect.h6
-rw-r--r--extern/libmv/libmv/tracking/track_region.cc213
-rw-r--r--extern/libmv/libmv/tracking/track_region.h6
-rw-r--r--extern/libmv/third_party/ceres/CMakeLists.txt50
-rw-r--r--extern/libmv/third_party/ceres/ChangeLog608
-rw-r--r--extern/libmv/third_party/ceres/SConscript6
-rwxr-xr-xextern/libmv/third_party/ceres/bundle.sh57
-rw-r--r--extern/libmv/third_party/ceres/files.txt22
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/autodiff_cost_function.h4
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/cost_function.h2
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/crs_matrix.h65
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/fpclassify.h88
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/internal/fixed_array.h3
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/internal/macros.h31
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/internal/manual_constructor.h71
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/internal/port.h6
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/iteration_callback.h36
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/jet.h163
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/loss_function.h79
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/numeric_diff_cost_function.h6
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/problem.h6
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/rotation.h62
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/solver.h229
-rw-r--r--extern/libmv/third_party/ceres/include/ceres/types.h68
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/array_utils.cc (renamed from extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt.h)54
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/array_utils.h65
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_evaluate_preparer.cc16
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_evaluate_preparer.h16
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_jacobi_preconditioner.cc9
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_jacobian_writer.cc5
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_random_access_dense_matrix.cc2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_random_access_dense_matrix.h2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_random_access_matrix.h2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_random_access_sparse_matrix.cc6
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_random_access_sparse_matrix.h8
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_sparse_matrix.cc8
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_sparse_matrix.h8
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/block_structure.cc2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/canonical_views_clustering.cc8
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/cgnr_solver.h2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/collections_port.h50
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/compressed_row_jacobian_writer.cc18
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/compressed_row_sparse_matrix.cc28
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/compressed_row_sparse_matrix.h28
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/conditioned_cost_function.cc4
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/conjugate_gradients_solver.cc20
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/conjugate_gradients_solver.h2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/corrector.cc2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/cxsparse.cc130
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/cxsparse.h90
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/dense_normal_cholesky_solver.cc86
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/dense_normal_cholesky_solver.h95
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/dense_qr_solver.cc4
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/dense_qr_solver.h4
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/dense_sparse_matrix.cc6
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/dense_sparse_matrix.h4
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/detect_structure.cc14
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/detect_structure.h2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/dogleg_strategy.cc691
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/dogleg_strategy.h163
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/evaluator.cc82
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/evaluator.h31
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/file.cc5
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/generate_eliminator_specialization.py186
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/gradient_checking_cost_function.cc10
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/graph.h2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/implicit_schur_complement.cc23
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/implicit_schur_complement.h10
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/iterative_schur_complement_solver.cc11
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt.cc574
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt_strategy.cc144
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt_strategy.h86
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/linear_least_squares_problems.cc101
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/linear_solver.cc30
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/linear_solver.h26
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/local_parameterization.cc5
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/loss_function.cc64
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/matrix_proto.h2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/minimizer.h68
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/mutex.h98
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/normal_prior.cc3
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/parameter_block.h19
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/partitioned_matrix_view.cc2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/polynomial_solver.cc184
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/polynomial_solver.h65
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/problem_impl.cc9
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/problem_impl.h2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/program.cc77
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/program.h21
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/program_evaluator.h84
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/random.h29
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/residual_block.cc7
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/residual_block_utils.cc41
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/residual_block_utils.h9
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/runtime_numeric_diff_cost_function.cc3
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/schur_complement_solver.cc159
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/schur_complement_solver.h38
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/schur_eliminator_impl.h38
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/schur_ordering.cc18
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/solver.cc52
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/solver_impl.cc296
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/solver_impl.h14
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/sparse_matrix.h2
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/sparse_normal_cholesky_solver.cc166
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/sparse_normal_cholesky_solver.h36
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/split.cc1
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/split.h21
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/stringprintf.cc1
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/stringprintf.h14
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/suitesparse.cc157
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/suitesparse.h82
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/triplet_sparse_matrix.cc10
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/triplet_sparse_matrix.h4
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/trust_region_minimizer.cc550
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/trust_region_minimizer.h67
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/trust_region_strategy.cc27
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/trust_region_strategy.h148
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/types.cc35
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/visibility.cc4
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/visibility_based_preconditioner.cc36
-rw-r--r--extern/libmv/third_party/ceres/internal/ceres/visibility_based_preconditioner.h14
-rw-r--r--extern/libmv/third_party/ceres/patches/collections_port.h.mingw.patch12
-rw-r--r--extern/libmv/third_party/ceres/patches/msvc_glog_fix.patch50
-rw-r--r--extern/libmv/third_party/ceres/patches/msvc_isfinite.patch15
-rw-r--r--extern/libmv/third_party/ceres/patches/no_previous_declaration_fix.patch199
-rw-r--r--extern/libmv/third_party/ceres/patches/series4
-rw-r--r--extern/recastnavigation/Recast/Source/RecastMeshDetail.cpp2
-rw-r--r--intern/CMakeLists.txt5
-rw-r--r--intern/SConscript5
-rw-r--r--intern/audaspace/CMakeLists.txt2
-rw-r--r--intern/audaspace/FX/AUD_ButterworthFactory.cpp10
-rw-r--r--intern/audaspace/FX/AUD_DelayReader.cpp4
-rw-r--r--intern/audaspace/FX/AUD_HighpassFactory.cpp4
-rw-r--r--intern/audaspace/FX/AUD_IIRFilterReader.cpp2
-rw-r--r--intern/audaspace/OpenAL/AUD_OpenALDevice.cpp323
-rw-r--r--intern/audaspace/Python/AUD_PyAPI.cpp132
-rw-r--r--intern/audaspace/Python/AUD_PyAPI.h8
-rw-r--r--intern/audaspace/fftw/AUD_BandPassFactory.h2
-rw-r--r--intern/audaspace/intern/AUD_AnimateableProperty.cpp14
-rw-r--r--intern/audaspace/intern/AUD_AnimateableProperty.h7
-rw-r--r--intern/audaspace/intern/AUD_C-API.cpp6
-rw-r--r--intern/audaspace/intern/AUD_ChannelMapperReader.cpp50
-rw-r--r--intern/audaspace/intern/AUD_IDevice.h3
-rw-r--r--intern/audaspace/intern/AUD_IFactory.h2
-rw-r--r--intern/audaspace/intern/AUD_ILockable.h21
-rw-r--r--intern/audaspace/intern/AUD_IReader.h2
-rw-r--r--intern/audaspace/intern/AUD_IWriter.h2
-rw-r--r--intern/audaspace/intern/AUD_MutexLock.h24
-rw-r--r--intern/audaspace/intern/AUD_PyInit.h4
-rw-r--r--intern/audaspace/intern/AUD_SequencerEntry.cpp53
-rw-r--r--intern/audaspace/intern/AUD_SequencerEntry.h7
-rw-r--r--intern/audaspace/intern/AUD_SequencerFactory.cpp33
-rw-r--r--intern/audaspace/intern/AUD_SequencerFactory.h7
-rw-r--r--intern/audaspace/intern/AUD_SequencerHandle.cpp8
-rw-r--r--intern/audaspace/intern/AUD_SequencerReader.cpp5
-rw-r--r--intern/audaspace/intern/AUD_SoftwareDevice.cpp91
-rw-r--r--intern/bsp/CMakeLists.txt5
-rw-r--r--intern/bsp/extern/CSG_BooleanOps.h8
-rw-r--r--intern/bsp/intern/BOP_CarveInterface.cpp12
-rw-r--r--intern/container/CMakeLists.txt5
-rw-r--r--intern/container/CTR_HashedPtr.h23
-rw-r--r--intern/container/CTR_List.h112
-rw-r--r--intern/container/CTR_Map.h84
-rw-r--r--intern/container/CTR_TaggedIndex.h15
-rw-r--r--intern/container/CTR_TaggedSetOps.h61
-rw-r--r--intern/container/CTR_UHeap.h307
-rw-r--r--intern/container/intern/CTR_List.cpp127
-rw-r--r--intern/cycles/CMakeLists.txt5
-rw-r--r--intern/cycles/SConscript2
-rw-r--r--intern/cycles/app/CMakeLists.txt3
-rw-r--r--intern/cycles/app/cycles_xml.cpp1
-rw-r--r--intern/cycles/blender/CMakeLists.txt2
-rw-r--r--intern/cycles/blender/addon/__init__.py10
-rw-r--r--intern/cycles/blender/addon/engine.py1
-rw-r--r--intern/cycles/blender/addon/enums.py1
-rw-r--r--intern/cycles/blender/addon/osl.py127
-rw-r--r--intern/cycles/blender/addon/properties.py39
-rw-r--r--intern/cycles/blender/addon/ui.py54
-rw-r--r--intern/cycles/blender/blender_camera.cpp55
-rw-r--r--intern/cycles/blender/blender_mesh.cpp189
-rw-r--r--intern/cycles/blender/blender_object.cpp67
-rw-r--r--intern/cycles/blender/blender_particles.cpp93
-rw-r--r--intern/cycles/blender/blender_python.cpp178
-rw-r--r--intern/cycles/blender/blender_session.cpp55
-rw-r--r--intern/cycles/blender/blender_shader.cpp126
-rw-r--r--intern/cycles/blender/blender_sync.cpp34
-rw-r--r--intern/cycles/blender/blender_sync.h5
-rw-r--r--intern/cycles/blender/blender_util.h53
-rw-r--r--intern/cycles/bvh/CMakeLists.txt4
-rw-r--r--intern/cycles/bvh/bvh_node.h2
-rw-r--r--intern/cycles/device/CMakeLists.txt4
-rw-r--r--intern/cycles/device/device.cpp26
-rw-r--r--intern/cycles/device/device.h9
-rw-r--r--intern/cycles/device/device_cpu.cpp43
-rw-r--r--intern/cycles/device/device_cuda.cpp31
-rw-r--r--intern/cycles/device/device_intern.h10
-rw-r--r--intern/cycles/device/device_multi.cpp18
-rw-r--r--intern/cycles/device/device_network.cpp8
-rw-r--r--intern/cycles/device/device_opencl.cpp22
-rw-r--r--intern/cycles/device/device_task.h1
-rw-r--r--intern/cycles/kernel/CMakeLists.txt39
-rw-r--r--intern/cycles/kernel/closure/bsdf.h (renamed from intern/cycles/kernel/svm/bsdf.h)6
-rw-r--r--intern/cycles/kernel/closure/bsdf_ashikhmin_velvet.h (renamed from intern/cycles/kernel/svm/bsdf_ashikhmin_velvet.h)50
-rw-r--r--intern/cycles/kernel/closure/bsdf_diffuse.h (renamed from intern/cycles/kernel/svm/bsdf_diffuse.h)68
-rw-r--r--intern/cycles/kernel/closure/bsdf_microfacet.h (renamed from intern/cycles/kernel/svm/bsdf_microfacet.h)176
-rw-r--r--intern/cycles/kernel/closure/bsdf_oren_nayar.h (renamed from intern/cycles/kernel/svm/bsdf_oren_nayar.h)37
-rw-r--r--intern/cycles/kernel/closure/bsdf_reflection.h (renamed from intern/cycles/kernel/svm/bsdf_reflection.h)31
-rw-r--r--intern/cycles/kernel/closure/bsdf_refraction.h (renamed from intern/cycles/kernel/svm/bsdf_refraction.h)27
-rw-r--r--intern/cycles/kernel/closure/bsdf_transparent.h (renamed from intern/cycles/kernel/svm/bsdf_transparent.h)21
-rw-r--r--intern/cycles/kernel/closure/bsdf_ward.h (renamed from intern/cycles/kernel/svm/bsdf_ward.h)73
-rw-r--r--intern/cycles/kernel/closure/bsdf_westin.h (renamed from intern/cycles/kernel/svm/bsdf_westin.h)87
-rw-r--r--intern/cycles/kernel/closure/emissive.h (renamed from intern/cycles/kernel/svm/emissive.h)12
-rw-r--r--intern/cycles/kernel/closure/volume.h (renamed from intern/cycles/kernel/svm/volume.h)20
-rw-r--r--intern/cycles/kernel/kernel_attribute.h2
-rw-r--r--intern/cycles/kernel/kernel_bvh.h173
-rw-r--r--intern/cycles/kernel/kernel_camera.h34
-rw-r--r--intern/cycles/kernel/kernel_displace.h3
-rw-r--r--intern/cycles/kernel/kernel_emission.h7
-rw-r--r--intern/cycles/kernel/kernel_light.h9
-rw-r--r--intern/cycles/kernel/kernel_mbvh.h394
-rw-r--r--intern/cycles/kernel/kernel_montecarlo.h19
-rw-r--r--intern/cycles/kernel/kernel_object.h132
-rw-r--r--intern/cycles/kernel/kernel_passes.h14
-rw-r--r--intern/cycles/kernel/kernel_path.h16
-rw-r--r--intern/cycles/kernel/kernel_qbvh.h413
-rw-r--r--intern/cycles/kernel/kernel_shader.h76
-rw-r--r--intern/cycles/kernel/kernel_triangle.h15
-rw-r--r--intern/cycles/kernel/kernel_types.h44
-rw-r--r--intern/cycles/kernel/osl/CMakeLists.txt19
-rw-r--r--intern/cycles/kernel/osl/background.cpp40
-rw-r--r--intern/cycles/kernel/osl/bsdf_ashikhmin_velvet.cpp179
-rw-r--r--intern/cycles/kernel/osl/bsdf_diffuse.cpp187
-rw-r--r--intern/cycles/kernel/osl/bsdf_microfacet.cpp542
-rw-r--r--intern/cycles/kernel/osl/bsdf_oren_nayar.cpp138
-rw-r--r--intern/cycles/kernel/osl/bsdf_phong.cpp277
-rw-r--r--intern/cycles/kernel/osl/bsdf_reflection.cpp109
-rw-r--r--intern/cycles/kernel/osl/bsdf_refraction.cpp121
-rw-r--r--intern/cycles/kernel/osl/bsdf_transparent.cpp98
-rw-r--r--intern/cycles/kernel/osl/bsdf_ward.cpp226
-rw-r--r--intern/cycles/kernel/osl/bsdf_westin.cpp243
-rw-r--r--intern/cycles/kernel/osl/bssrdf.cpp106
-rw-r--r--intern/cycles/kernel/osl/debug.cpp81
-rw-r--r--intern/cycles/kernel/osl/emissive.cpp50
-rw-r--r--intern/cycles/kernel/osl/nodes/node_object_info.osl33
-rw-r--r--intern/cycles/kernel/osl/nodes/node_voronoi_texture.osl81
-rw-r--r--intern/cycles/kernel/osl/osl_closures.cpp148
-rw-r--r--intern/cycles/kernel/osl/osl_closures.h173
-rw-r--r--intern/cycles/kernel/osl/osl_services.cpp299
-rw-r--r--intern/cycles/kernel/osl/osl_services.h3
-rw-r--r--intern/cycles/kernel/osl/osl_shader.cpp82
-rw-r--r--intern/cycles/kernel/osl/osl_shader.h3
-rw-r--r--intern/cycles/kernel/osl/vol_subsurface.cpp137
-rw-r--r--intern/cycles/kernel/shaders/CMakeLists.txt (renamed from intern/cycles/kernel/osl/nodes/CMakeLists.txt)13
-rw-r--r--intern/cycles/kernel/shaders/node_add_closure.osl (renamed from intern/cycles/kernel/osl/nodes/node_add_closure.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_attribute.osl (renamed from intern/cycles/kernel/osl/nodes/node_attribute.osl)4
-rw-r--r--intern/cycles/kernel/shaders/node_background.osl (renamed from intern/cycles/kernel/osl/nodes/node_background.osl)2
-rw-r--r--intern/cycles/kernel/shaders/node_brick_texture.osl (renamed from intern/cycles/kernel/osl/nodes/node_brick_texture.osl)21
-rw-r--r--intern/cycles/kernel/shaders/node_brightness.osl (renamed from intern/cycles/kernel/osl/nodes/node_brightness.osl)12
-rw-r--r--intern/cycles/kernel/shaders/node_bump.osl (renamed from intern/cycles/kernel/osl/nodes/node_bump.osl)21
-rw-r--r--intern/cycles/kernel/shaders/node_camera.osl (renamed from intern/cycles/kernel/osl/nodes/node_camera.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_checker_texture.osl (renamed from intern/cycles/kernel/osl/nodes/node_checker_texture.osl)12
-rw-r--r--intern/cycles/kernel/shaders/node_color.h (renamed from intern/cycles/kernel/osl/nodes/node_color.h)0
-rw-r--r--intern/cycles/kernel/shaders/node_combine_rgb.osl (renamed from intern/cycles/kernel/osl/nodes/node_combine_rgb.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_convert_from_color.osl (renamed from intern/cycles/kernel/osl/nodes/node_convert_from_color.osl)4
-rw-r--r--intern/cycles/kernel/shaders/node_convert_from_float.osl (renamed from intern/cycles/kernel/osl/nodes/node_convert_from_float.osl)2
-rw-r--r--intern/cycles/kernel/shaders/node_convert_from_int.osl36
-rw-r--r--intern/cycles/kernel/shaders/node_convert_from_normal.osl (renamed from intern/cycles/kernel/osl/nodes/node_convert_from_normal.osl)4
-rw-r--r--intern/cycles/kernel/shaders/node_convert_from_point.osl (renamed from intern/cycles/kernel/osl/nodes/node_convert_from_point.osl)4
-rw-r--r--intern/cycles/kernel/shaders/node_convert_from_vector.osl (renamed from intern/cycles/kernel/osl/nodes/node_convert_from_vector.osl)4
-rw-r--r--intern/cycles/kernel/shaders/node_diffuse_bsdf.osl (renamed from intern/cycles/kernel/osl/nodes/node_diffuse_bsdf.osl)2
-rw-r--r--intern/cycles/kernel/shaders/node_emission.osl (renamed from intern/cycles/kernel/osl/nodes/node_emission.osl)6
-rw-r--r--intern/cycles/kernel/shaders/node_environment_texture.osl (renamed from intern/cycles/kernel/osl/nodes/node_environment_texture.osl)2
-rw-r--r--intern/cycles/kernel/shaders/node_fresnel.h (renamed from intern/cycles/kernel/osl/nodes/node_fresnel.h)0
-rw-r--r--intern/cycles/kernel/shaders/node_fresnel.osl (renamed from intern/cycles/kernel/osl/nodes/node_fresnel.osl)2
-rw-r--r--intern/cycles/kernel/shaders/node_gamma.osl (renamed from intern/cycles/kernel/osl/nodes/node_gamma.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_geometry.osl (renamed from intern/cycles/kernel/osl/nodes/node_geometry.osl)28
-rw-r--r--intern/cycles/kernel/shaders/node_glass_bsdf.osl (renamed from intern/cycles/kernel/osl/nodes/node_glass_bsdf.osl)16
-rw-r--r--intern/cycles/kernel/shaders/node_glossy_bsdf.osl (renamed from intern/cycles/kernel/osl/nodes/node_glossy_bsdf.osl)12
-rw-r--r--intern/cycles/kernel/shaders/node_gradient_texture.osl (renamed from intern/cycles/kernel/osl/nodes/node_gradient_texture.osl)37
-rw-r--r--intern/cycles/kernel/shaders/node_holdout.osl (renamed from intern/cycles/kernel/osl/nodes/node_holdout.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_hsv.osl (renamed from intern/cycles/kernel/osl/nodes/node_hsv.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_image_texture.osl120
-rw-r--r--intern/cycles/kernel/shaders/node_invert.osl (renamed from intern/cycles/kernel/osl/nodes/node_invert.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_layer_weight.osl (renamed from intern/cycles/kernel/osl/nodes/node_blend_weight.osl)22
-rw-r--r--intern/cycles/kernel/shaders/node_light_falloff.osl46
-rw-r--r--intern/cycles/kernel/shaders/node_light_path.osl (renamed from intern/cycles/kernel/osl/nodes/node_light_path.osl)5
-rw-r--r--intern/cycles/kernel/shaders/node_magic_texture.osl (renamed from intern/cycles/kernel/osl/nodes/node_magic_texture.osl)113
-rw-r--r--intern/cycles/kernel/shaders/node_mapping.osl (renamed from intern/cycles/kernel/osl/nodes/node_mapping.osl)6
-rw-r--r--intern/cycles/kernel/shaders/node_math.osl (renamed from intern/cycles/kernel/osl/nodes/node_math.osl)46
-rw-r--r--intern/cycles/kernel/shaders/node_mix.osl (renamed from intern/cycles/kernel/osl/nodes/node_mix.osl)150
-rw-r--r--intern/cycles/kernel/shaders/node_mix_closure.osl (renamed from intern/cycles/kernel/osl/nodes/node_mix_closure.osl)2
-rw-r--r--intern/cycles/kernel/shaders/node_musgrave_texture.osl (renamed from intern/cycles/kernel/osl/nodes/node_musgrave_texture.osl)74
-rw-r--r--intern/cycles/kernel/shaders/node_noise_texture.osl (renamed from intern/cycles/kernel/osl/nodes/node_noise_texture.osl)6
-rw-r--r--intern/cycles/kernel/shaders/node_normal.osl (renamed from intern/cycles/kernel/osl/nodes/node_normal.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_object_info.osl32
-rw-r--r--intern/cycles/kernel/shaders/node_output_displacement.osl (renamed from intern/cycles/kernel/osl/nodes/node_output_displacement.osl)2
-rw-r--r--intern/cycles/kernel/shaders/node_output_surface.osl (renamed from intern/cycles/kernel/osl/nodes/node_output_surface.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_output_volume.osl (renamed from intern/cycles/kernel/osl/nodes/node_output_volume.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_particle_info.osl (renamed from intern/cycles/kernel/osl/nodes/node_particle_info.osl)17
-rw-r--r--intern/cycles/kernel/shaders/node_rgb_ramp.osl (renamed from intern/cycles/kernel/osl/nodes/node_image_texture.osl)25
-rw-r--r--intern/cycles/kernel/shaders/node_separate_rgb.osl (renamed from intern/cycles/kernel/osl/nodes/node_separate_rgb.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_set_normal.osl28
-rw-r--r--intern/cycles/kernel/shaders/node_sky_texture.osl (renamed from intern/cycles/kernel/osl/nodes/node_sky_texture.osl)70
-rw-r--r--intern/cycles/kernel/shaders/node_texture.h (renamed from intern/cycles/kernel/osl/nodes/node_texture.h)16
-rw-r--r--intern/cycles/kernel/shaders/node_texture_coordinate.osl (renamed from intern/cycles/kernel/osl/nodes/node_texture_coordinate.osl)37
-rw-r--r--intern/cycles/kernel/shaders/node_translucent_bsdf.osl (renamed from intern/cycles/kernel/osl/nodes/node_translucent_bsdf.osl)2
-rw-r--r--intern/cycles/kernel/shaders/node_transparent_bsdf.osl (renamed from intern/cycles/kernel/osl/nodes/node_transparent_bsdf.osl)2
-rw-r--r--intern/cycles/kernel/shaders/node_value.osl (renamed from intern/cycles/kernel/osl/nodes/node_value.osl)0
-rw-r--r--intern/cycles/kernel/shaders/node_vector_math.osl (renamed from intern/cycles/kernel/osl/nodes/node_vector_math.osl)16
-rw-r--r--intern/cycles/kernel/shaders/node_velvet_bsdf.osl (renamed from intern/cycles/kernel/osl/nodes/node_velvet_bsdf.osl)2
-rw-r--r--intern/cycles/kernel/shaders/node_voronoi_texture.osl48
-rw-r--r--intern/cycles/kernel/shaders/node_ward_bsdf.osl (renamed from intern/cycles/kernel/osl/nodes/node_ward_bsdf.osl)27
-rw-r--r--intern/cycles/kernel/shaders/node_wave_texture.osl (renamed from intern/cycles/kernel/osl/nodes/node_wave_texture.osl)14
-rw-r--r--intern/cycles/kernel/shaders/oslutil.h (renamed from intern/cycles/kernel/osl/nodes/oslutil.h)3
-rw-r--r--intern/cycles/kernel/shaders/stdosl.h (renamed from intern/cycles/kernel/osl/nodes/stdosl.h)71
-rw-r--r--intern/cycles/kernel/svm/svm.h34
-rw-r--r--intern/cycles/kernel/svm/svm_bsdf.h102
-rw-r--r--intern/cycles/kernel/svm/svm_closure.h113
-rw-r--r--intern/cycles/kernel/svm/svm_convert.h28
-rw-r--r--intern/cycles/kernel/svm/svm_displace.h26
-rw-r--r--intern/cycles/kernel/svm/svm_fresnel.h2
-rw-r--r--intern/cycles/kernel/svm/svm_geometry.h43
-rw-r--r--intern/cycles/kernel/svm/svm_hsv.h4
-rw-r--r--intern/cycles/kernel/svm/svm_image.h8
-rw-r--r--intern/cycles/kernel/svm/svm_noise.h2
-rw-r--r--intern/cycles/kernel/svm/svm_tex_coord.h24
-rw-r--r--intern/cycles/kernel/svm/svm_types.h23
-rw-r--r--intern/cycles/render/CMakeLists.txt4
-rw-r--r--intern/cycles/render/attribute.cpp2
-rw-r--r--intern/cycles/render/buffers.cpp15
-rw-r--r--intern/cycles/render/camera.cpp24
-rw-r--r--intern/cycles/render/camera.h1
-rw-r--r--intern/cycles/render/graph.cpp90
-rw-r--r--intern/cycles/render/graph.h3
-rw-r--r--intern/cycles/render/image.cpp42
-rw-r--r--intern/cycles/render/image.h5
-rw-r--r--intern/cycles/render/integrator.cpp2
-rw-r--r--intern/cycles/render/light.cpp5
-rw-r--r--intern/cycles/render/mesh.cpp18
-rw-r--r--intern/cycles/render/nodes.cpp223
-rw-r--r--intern/cycles/render/nodes.h23
-rw-r--r--intern/cycles/render/object.cpp38
-rw-r--r--intern/cycles/render/object.h5
-rw-r--r--intern/cycles/render/osl.cpp482
-rw-r--r--intern/cycles/render/osl.h36
-rw-r--r--intern/cycles/render/scene.cpp4
-rw-r--r--intern/cycles/render/scene.h2
-rw-r--r--intern/cycles/render/session.cpp148
-rw-r--r--intern/cycles/render/session.h28
-rw-r--r--intern/cycles/render/shader.cpp33
-rw-r--r--intern/cycles/render/shader.h17
-rw-r--r--intern/cycles/render/svm.cpp68
-rw-r--r--intern/cycles/render/tile.cpp133
-rw-r--r--intern/cycles/render/tile.h47
-rw-r--r--intern/cycles/subd/CMakeLists.txt5
-rw-r--r--intern/cycles/subd/subd_build.cpp2
-rw-r--r--intern/cycles/util/CMakeLists.txt4
-rw-r--r--intern/cycles/util/util_attribute.cpp2
-rw-r--r--intern/cycles/util/util_cuda.cpp15
-rw-r--r--intern/cycles/util/util_math.h27
-rw-r--r--intern/cycles/util/util_md5.h2
-rw-r--r--intern/cycles/util/util_path.cpp10
-rw-r--r--intern/cycles/util/util_path.h3
-rw-r--r--intern/cycles/util/util_progress.h40
-rw-r--r--intern/cycles/util/util_stats.h53
-rw-r--r--intern/cycles/util/util_task.cpp33
-rw-r--r--intern/cycles/util/util_task.h1
-rw-r--r--intern/cycles/util/util_thread.h4
-rw-r--r--intern/cycles/util/util_transform.cpp3
-rw-r--r--intern/cycles/util/util_transform.h45
-rw-r--r--intern/cycles/util/util_types.h1
-rw-r--r--intern/decimation/CMakeLists.txt63
-rw-r--r--intern/decimation/SConscript8
-rw-r--r--intern/decimation/extern/LOD_decimation.h117
-rw-r--r--intern/decimation/intern/LOD_DecimationClass.h118
-rw-r--r--intern/decimation/intern/LOD_EdgeCollapser.cpp410
-rw-r--r--intern/decimation/intern/LOD_EdgeCollapser.h117
-rw-r--r--intern/decimation/intern/LOD_ExternBufferEditor.h164
-rw-r--r--intern/decimation/intern/LOD_ExternNormalEditor.cpp264
-rw-r--r--intern/decimation/intern/LOD_ExternNormalEditor.h135
-rw-r--r--intern/decimation/intern/LOD_FaceNormalEditor.cpp291
-rw-r--r--intern/decimation/intern/LOD_FaceNormalEditor.h144
-rw-r--r--intern/decimation/intern/LOD_ManMesh2.cpp618
-rw-r--r--intern/decimation/intern/LOD_ManMesh2.h265
-rw-r--r--intern/decimation/intern/LOD_MeshBounds.h133
-rw-r--r--intern/decimation/intern/LOD_MeshPrimitives.cpp404
-rw-r--r--intern/decimation/intern/LOD_MeshPrimitives.h221
-rw-r--r--intern/decimation/intern/LOD_QSDecimator.cpp327
-rw-r--r--intern/decimation/intern/LOD_QSDecimator.h129
-rw-r--r--intern/decimation/intern/LOD_Quadric.h167
-rw-r--r--intern/decimation/intern/LOD_QuadricEditor.cpp279
-rw-r--r--intern/decimation/intern/LOD_QuadricEditor.h120
-rw-r--r--intern/decimation/intern/LOD_decimation.cpp155
-rw-r--r--intern/dualcon/CMakeLists.txt5
-rw-r--r--intern/dualcon/intern/Projections.cpp4
-rw-r--r--intern/dualcon/intern/dualcon_c_api.cpp2
-rw-r--r--intern/dualcon/intern/octree.cpp179
-rw-r--r--intern/dualcon/intern/octree.h299
-rw-r--r--intern/elbeem/intern/ntl_geometryshader.h2
-rw-r--r--intern/elbeem/intern/utilities.cpp2
-rw-r--r--intern/ffmpeg/ffmpeg_compat.h2
-rw-r--r--intern/ghost/GHOST_C-api.h3
-rw-r--r--intern/ghost/GHOST_IEventConsumer.h13
-rw-r--r--intern/ghost/GHOST_ISystem.h108
-rw-r--r--intern/ghost/GHOST_IWindow.h96
-rw-r--r--intern/ghost/GHOST_Rect.h69
-rw-r--r--intern/ghost/GHOST_Types.h4
-rw-r--r--intern/ghost/intern/GHOST_C-api.cpp14
-rw-r--r--intern/ghost/intern/GHOST_Debug.h4
-rw-r--r--intern/ghost/intern/GHOST_DisplayManagerCocoa.mm2
-rw-r--r--intern/ghost/intern/GHOST_DisplayManagerX11.cpp10
-rw-r--r--intern/ghost/intern/GHOST_EventDragnDrop.h14
-rw-r--r--intern/ghost/intern/GHOST_EventManager.cpp12
-rw-r--r--intern/ghost/intern/GHOST_NDOFManager.h2
-rw-r--r--intern/ghost/intern/GHOST_Rect.cpp2
-rw-r--r--intern/ghost/intern/GHOST_System.h2
-rw-r--r--intern/ghost/intern/GHOST_SystemCarbon.cpp2
-rw-r--r--intern/ghost/intern/GHOST_SystemCocoa.mm118
-rw-r--r--intern/ghost/intern/GHOST_SystemPaths.h4
-rw-r--r--intern/ghost/intern/GHOST_SystemWin32.cpp2
-rw-r--r--intern/ghost/intern/GHOST_SystemX11.cpp33
-rw-r--r--intern/ghost/intern/GHOST_SystemX11.h8
-rw-r--r--intern/ghost/intern/GHOST_TimerManager.cpp6
-rw-r--r--intern/ghost/intern/GHOST_Window.cpp10
-rw-r--r--intern/ghost/intern/GHOST_Window.h8
-rw-r--r--intern/ghost/intern/GHOST_WindowCocoa.mm40
-rw-r--r--intern/ghost/intern/GHOST_WindowManager.cpp4
-rw-r--r--intern/ghost/intern/GHOST_WindowWin32.cpp2
-rw-r--r--intern/ghost/intern/GHOST_WindowX11.cpp4
-rw-r--r--intern/ghost/test/multitest/EventToBuf.c21
-rw-r--r--intern/ghost/test/multitest/MultiTest.c5
-rw-r--r--intern/guardedalloc/test/simpletest/memtest.c9
-rw-r--r--intern/iksolver/intern/IK_QJacobianSolver.h4
-rw-r--r--intern/iksolver/intern/IK_QSegment.h4
-rw-r--r--intern/iksolver/intern/IK_QTask.h4
-rw-r--r--intern/iksolver/intern/IK_Solver.cpp6
-rw-r--r--intern/iksolver/intern/MT_ExpMap.h4
-rw-r--r--intern/iksolver/intern/TNT/cmat.h2
-rw-r--r--intern/iksolver/intern/TNT/vec.h2
-rw-r--r--intern/itasc/CMakeLists.txt398
-rw-r--r--intern/itasc/Scene.cpp2
-rw-r--r--intern/itasc/kdl/utilities/utility_io.cpp6
-rw-r--r--intern/memutil/MEM_CacheLimiter.h69
-rw-r--r--intern/memutil/MEM_CacheLimiterC-Api.h4
-rw-r--r--intern/memutil/MEM_SmartPtr.h6
-rw-r--r--intern/memutil/intern/MEM_CacheLimiterC-Api.cpp12
-rw-r--r--intern/mikktspace/mikktspace.c3
-rw-r--r--intern/opencolorio/CMakeLists.txt43
-rw-r--r--intern/opencolorio/SConscript10
-rw-r--r--intern/opencolorio/ocio_capi.h160
-rw-r--r--intern/opennl/CMakeLists.txt3
-rw-r--r--intern/opennl/SConscript5
-rw-r--r--intern/opennl/intern/opennl.c15
-rw-r--r--intern/opennl/superlu/get_perm_c.c52
-rw-r--r--intern/raskter/CMakeLists.txt3
-rw-r--r--intern/raskter/raskter.c1884
-rw-r--r--intern/raskter/raskter.h70
-rw-r--r--intern/raskter/raskter_kdtree.c836
-rw-r--r--intern/raskter/raskter_kdtree.h129
-rw-r--r--intern/raskter/raskter_mt.c290
-rw-r--r--intern/smoke/CMakeLists.txt4
-rw-r--r--intern/smoke/extern/smoke_API.h51
-rw-r--r--intern/smoke/intern/FLUID_3D.cpp515
-rw-r--r--intern/smoke/intern/FLUID_3D.h46
-rw-r--r--intern/smoke/intern/FLUID_3D_SOLVERS.cpp1
-rw-r--r--intern/smoke/intern/FLUID_3D_STATIC.cpp28
-rw-r--r--intern/smoke/intern/WTURBULENCE.cpp151
-rw-r--r--intern/smoke/intern/WTURBULENCE.h19
-rw-r--r--intern/smoke/intern/smoke_API.cpp378
-rw-r--r--intern/smoke/intern/spectrum.cpp426
-rw-r--r--intern/smoke/intern/spectrum.h6
-rw-r--r--intern/string/STR_String.h24
-rw-r--r--intern/string/intern/STR_String.cpp1
-rw-r--r--intern/utfconv/utfconv.h2
-rw-r--r--release/datafiles/blender_icons.pngbin227018 -> 228428 bytes
-rw-r--r--release/datafiles/colormanagement/config.ocio31
-rw-r--r--release/datafiles/prvicons.pngbin12311 -> 14130 bytes
-rw-r--r--release/datafiles/splash.pngbin109883 -> 212426 bytes
-rw-r--r--release/datafiles/startup.blendbin400648 -> 408072 bytes
-rw-r--r--release/scripts/modules/addon_utils.py11
-rw-r--r--release/scripts/modules/bl_i18n_utils/bl_process_msg.py74
-rwxr-xr-xrelease/scripts/modules/bl_i18n_utils/check_po.py6
-rwxr-xr-xrelease/scripts/modules/bl_i18n_utils/import_po_from_branches.py4
-rwxr-xr-xrelease/scripts/modules/bl_i18n_utils/rtl_preprocess.py37
-rw-r--r--release/scripts/modules/bl_i18n_utils/settings.py151
-rw-r--r--release/scripts/modules/bl_i18n_utils/spell_check_utils.py19
-rwxr-xr-xrelease/scripts/modules/bl_i18n_utils/update_branches.py17
-rwxr-xr-xrelease/scripts/modules/bl_i18n_utils/update_languages_menu.py148
-rwxr-xr-xrelease/scripts/modules/bl_i18n_utils/update_mo.py5
-rwxr-xr-xrelease/scripts/modules/bl_i18n_utils/update_pot.py59
-rwxr-xr-xrelease/scripts/modules/bl_i18n_utils/update_trunk.py66
-rw-r--r--release/scripts/modules/bl_i18n_utils/utils.py10
-rw-r--r--release/scripts/modules/bpy/path.py4
-rw-r--r--release/scripts/modules/bpy/utils.py5
-rw-r--r--release/scripts/modules/bpy_extras/mesh_utils.py2
-rw-r--r--release/scripts/modules/bpy_extras/object_utils.py13
-rw-r--r--release/scripts/modules/bpy_types.py8
-rw-r--r--release/scripts/modules/bpyml.py2
-rw-r--r--release/scripts/modules/console_python.py10
-rw-r--r--release/scripts/modules/console_shell.py4
-rw-r--r--release/scripts/modules/rna_info.py4
-rw-r--r--release/scripts/modules/rna_xml.py7
-rw-r--r--release/scripts/presets/interface_theme/back_to_black.xml1
-rw-r--r--release/scripts/presets/interface_theme/blender_24x.xml1
-rw-r--r--release/scripts/presets/interface_theme/elsyiun.xml3
-rw-r--r--release/scripts/presets/interface_theme/hexagon.xml1
-rw-r--r--release/scripts/presets/interface_theme/ubuntu_ambiance.xml219
-rw-r--r--release/scripts/presets/keyconfig/maya.py16
-rw-r--r--release/scripts/presets/tracking_settings/blurry_footage.py2
-rw-r--r--release/scripts/presets/tracking_settings/default.py2
-rw-r--r--release/scripts/presets/tracking_settings/fast_motion.py2
-rw-r--r--release/scripts/presets/tracking_settings/planar.py2
-rw-r--r--release/scripts/startup/bl_operators/add_mesh_torus.py14
-rw-r--r--release/scripts/startup/bl_operators/anim.py10
-rw-r--r--release/scripts/startup/bl_operators/clip.py14
-rw-r--r--release/scripts/startup/bl_operators/console.py2
-rw-r--r--release/scripts/startup/bl_operators/mesh.py2
-rw-r--r--release/scripts/startup/bl_operators/node.py42
-rw-r--r--release/scripts/startup/bl_operators/object.py12
-rw-r--r--release/scripts/startup/bl_operators/object_quick_effects.py67
-rw-r--r--release/scripts/startup/bl_operators/presets.py32
-rw-r--r--release/scripts/startup/bl_operators/screen_play_rendered_anim.py2
-rw-r--r--release/scripts/startup/bl_operators/wm.py35
-rw-r--r--release/scripts/startup/bl_ui/__init__.py13
-rw-r--r--release/scripts/startup/bl_ui/properties_animviz.py7
-rw-r--r--release/scripts/startup/bl_ui/properties_data_armature.py7
-rw-r--r--release/scripts/startup/bl_ui/properties_data_bone.py32
-rw-r--r--release/scripts/startup/bl_ui/properties_data_camera.py12
-rw-r--r--release/scripts/startup/bl_ui/properties_data_lamp.py2
-rw-r--r--release/scripts/startup/bl_ui/properties_data_mesh.py21
-rw-r--r--release/scripts/startup/bl_ui/properties_data_modifier.py45
-rw-r--r--release/scripts/startup/bl_ui/properties_game.py8
-rw-r--r--release/scripts/startup/bl_ui/properties_material.py2
-rw-r--r--release/scripts/startup/bl_ui/properties_object.py8
-rw-r--r--release/scripts/startup/bl_ui/properties_object_constraint.py5
-rw-r--r--release/scripts/startup/bl_ui/properties_particle.py33
-rw-r--r--release/scripts/startup/bl_ui/properties_physics_cloth.py10
-rw-r--r--release/scripts/startup/bl_ui/properties_physics_common.py8
-rw-r--r--release/scripts/startup/bl_ui/properties_physics_dynamicpaint.py9
-rw-r--r--release/scripts/startup/bl_ui/properties_physics_field.py15
-rw-r--r--release/scripts/startup/bl_ui/properties_physics_smoke.py181
-rw-r--r--release/scripts/startup/bl_ui/properties_physics_softbody.py8
-rw-r--r--release/scripts/startup/bl_ui/properties_render.py27
-rw-r--r--release/scripts/startup/bl_ui/properties_scene.py2
-rw-r--r--release/scripts/startup/bl_ui/properties_texture.py27
-rw-r--r--release/scripts/startup/bl_ui/space_clip.py52
-rw-r--r--release/scripts/startup/bl_ui/space_console.py2
-rw-r--r--release/scripts/startup/bl_ui/space_dopesheet.py8
-rw-r--r--release/scripts/startup/bl_ui/space_filebrowser.py1
-rw-r--r--release/scripts/startup/bl_ui/space_graph.py4
-rw-r--r--release/scripts/startup/bl_ui/space_info.py57
-rw-r--r--release/scripts/startup/bl_ui/space_logic.py5
-rw-r--r--release/scripts/startup/bl_ui/space_node.py8
-rw-r--r--release/scripts/startup/bl_ui/space_sequencer.py50
-rw-r--r--release/scripts/startup/bl_ui/space_text.py27
-rw-r--r--release/scripts/startup/bl_ui/space_time.py5
-rw-r--r--release/scripts/startup/bl_ui/space_userpref.py28
-rw-r--r--release/scripts/startup/bl_ui/space_userpref_keymap.py8
-rw-r--r--release/scripts/startup/bl_ui/space_view3d.py62
-rw-r--r--release/scripts/startup/bl_ui/space_view3d_toolbar.py21
-rw-r--r--release/scripts/startup/keyingsets_builtins.py4
-rw-r--r--release/scripts/templates/addon_add_object.py4
-rw-r--r--release/scripts/templates/script_stub.py11
-rw-r--r--release/scripts/templates/ui_panel.py59
-rw-r--r--release/scripts/templates/ui_panel_simple.py3
-rw-r--r--release/text/readme.html2
-rw-r--r--release/windows/contrib/vfapi/vfapi-plugin.c55
-rw-r--r--source/blender/CMakeLists.txt5
-rw-r--r--source/blender/avi/AVI_avi.h2
-rw-r--r--source/blender/avi/CMakeLists.txt20
-rw-r--r--source/blender/avi/intern/avi.c23
-rw-r--r--source/blender/avi/intern/avi_codecs.c (renamed from source/blender/avi/intern/codecs.c)8
-rw-r--r--source/blender/avi/intern/avi_endian.c (renamed from source/blender/avi/intern/endian.c)38
-rw-r--r--source/blender/avi/intern/avi_endian.h (renamed from source/blender/avi/intern/endian.h)12
-rw-r--r--source/blender/avi/intern/avi_mjpeg.c (renamed from source/blender/avi/intern/mjpeg.c)22
-rw-r--r--source/blender/avi/intern/avi_mjpeg.h (renamed from source/blender/avi/intern/mjpeg.h)5
-rw-r--r--source/blender/avi/intern/avi_options.c (renamed from source/blender/avi/intern/options.c)4
-rw-r--r--source/blender/avi/intern/avi_rgb.c (renamed from source/blender/avi/intern/avirgb.c)10
-rw-r--r--source/blender/avi/intern/avi_rgb.h (renamed from source/blender/avi/intern/avirgb.h)9
-rw-r--r--source/blender/avi/intern/avi_rgb32.c (renamed from source/blender/avi/intern/rgb32.c)9
-rw-r--r--source/blender/avi/intern/avi_rgb32.h (renamed from source/blender/avi/intern/rgb32.h)9
-rw-r--r--source/blender/blenfont/BLF_api.h1
-rw-r--r--source/blender/blenfont/BLF_translation.h9
-rw-r--r--source/blender/blenfont/CMakeLists.txt2
-rw-r--r--source/blender/blenfont/SConscript3
-rw-r--r--source/blender/blenfont/intern/blf.c118
-rw-r--r--source/blender/blenfont/intern/blf_font.c10
-rw-r--r--source/blender/blenfont/intern/blf_glyph.c2
-rw-r--r--source/blender/blenfont/intern/blf_lang.c339
-rw-r--r--source/blender/blenkernel/BKE_DerivedMesh.h16
-rw-r--r--source/blender/blenkernel/BKE_action.h2
-rw-r--r--source/blender/blenkernel/BKE_anim.h4
-rw-r--r--source/blender/blenkernel/BKE_armature.h11
-rw-r--r--source/blender/blenkernel/BKE_blender.h11
-rw-r--r--source/blender/blenkernel/BKE_bmesh.h4
-rw-r--r--source/blender/blenkernel/BKE_cdderivedmesh.h4
-rw-r--r--source/blender/blenkernel/BKE_colortools.h7
-rw-r--r--source/blender/blenkernel/BKE_curve.h4
-rw-r--r--source/blender/blenkernel/BKE_customdata.h16
-rw-r--r--source/blender/blenkernel/BKE_deform.h1
-rw-r--r--source/blender/blenkernel/BKE_global.h15
-rw-r--r--source/blender/blenkernel/BKE_gpencil.h4
-rw-r--r--source/blender/blenkernel/BKE_group.h4
-rw-r--r--source/blender/blenkernel/BKE_idprop.h29
-rw-r--r--source/blender/blenkernel/BKE_image.h3
-rw-r--r--source/blender/blenkernel/BKE_key.h52
-rw-r--r--source/blender/blenkernel/BKE_lattice.h2
-rw-r--r--source/blender/blenkernel/BKE_library.h1
-rw-r--r--source/blender/blenkernel/BKE_main.h2
-rw-r--r--source/blender/blenkernel/BKE_mball.h6
-rw-r--r--source/blender/blenkernel/BKE_mesh.h9
-rw-r--r--source/blender/blenkernel/BKE_modifier.h1
-rw-r--r--source/blender/blenkernel/BKE_multires.h3
-rw-r--r--source/blender/blenkernel/BKE_navmesh_conversion.h2
-rw-r--r--source/blender/blenkernel/BKE_node.h27
-rw-r--r--source/blender/blenkernel/BKE_object.h4
-rw-r--r--source/blender/blenkernel/BKE_paint.h1
-rw-r--r--source/blender/blenkernel/BKE_particle.h21
-rw-r--r--source/blender/blenkernel/BKE_pointcache.h2
-rw-r--r--source/blender/blenkernel/BKE_property.h27
-rw-r--r--source/blender/blenkernel/BKE_sca.h2
-rw-r--r--source/blender/blenkernel/BKE_scene.h8
-rw-r--r--source/blender/blenkernel/BKE_sequencer.h40
-rw-r--r--source/blender/blenkernel/BKE_smoke.h6
-rw-r--r--source/blender/blenkernel/BKE_subsurf.h8
-rw-r--r--source/blender/blenkernel/BKE_tracking.h4
-rw-r--r--source/blender/blenkernel/BKE_utildefines.h2
-rw-r--r--source/blender/blenkernel/CMakeLists.txt18
-rw-r--r--source/blender/blenkernel/SConscript2
-rw-r--r--source/blender/blenkernel/depsgraph_private.h2
-rw-r--r--source/blender/blenkernel/intern/CCGSubSurf.c6
-rw-r--r--source/blender/blenkernel/intern/DerivedMesh.c190
-rw-r--r--source/blender/blenkernel/intern/action.c489
-rw-r--r--source/blender/blenkernel/intern/anim.c119
-rw-r--r--source/blender/blenkernel/intern/anim_sys.c16
-rw-r--r--source/blender/blenkernel/intern/armature.c27
-rw-r--r--source/blender/blenkernel/intern/blender.c22
-rw-r--r--source/blender/blenkernel/intern/bmfont.c4
-rw-r--r--source/blender/blenkernel/intern/boids.c30
-rw-r--r--source/blender/blenkernel/intern/booleanops_mesh.c12
-rw-r--r--source/blender/blenkernel/intern/brush.c52
-rw-r--r--source/blender/blenkernel/intern/bullet.c2
-rw-r--r--source/blender/blenkernel/intern/bvhutils.c44
-rw-r--r--source/blender/blenkernel/intern/camera.c5
-rw-r--r--source/blender/blenkernel/intern/cdderivedmesh.c242
-rw-r--r--source/blender/blenkernel/intern/cloth.c41
-rw-r--r--source/blender/blenkernel/intern/collision.c31
-rw-r--r--source/blender/blenkernel/intern/colortools.c103
-rw-r--r--source/blender/blenkernel/intern/constraint.c169
-rw-r--r--source/blender/blenkernel/intern/context.c5
-rw-r--r--source/blender/blenkernel/intern/curve.c51
-rw-r--r--source/blender/blenkernel/intern/customdata.c279
-rw-r--r--source/blender/blenkernel/intern/deform.c24
-rw-r--r--source/blender/blenkernel/intern/depsgraph.c142
-rw-r--r--source/blender/blenkernel/intern/displist.c8
-rw-r--r--source/blender/blenkernel/intern/dynamicpaint.c97
-rw-r--r--source/blender/blenkernel/intern/editderivedmesh.c2
-rw-r--r--source/blender/blenkernel/intern/effect.c50
-rw-r--r--source/blender/blenkernel/intern/fcurve.c34
-rw-r--r--source/blender/blenkernel/intern/fluidsim.c36
-rw-r--r--source/blender/blenkernel/intern/fmodifier.c17
-rw-r--r--source/blender/blenkernel/intern/font.c30
-rw-r--r--source/blender/blenkernel/intern/gpencil.c14
-rw-r--r--source/blender/blenkernel/intern/group.c66
-rw-r--r--source/blender/blenkernel/intern/icons.c4
-rw-r--r--source/blender/blenkernel/intern/idprop.c123
-rw-r--r--source/blender/blenkernel/intern/image.c95
-rw-r--r--source/blender/blenkernel/intern/image_gen.c2
-rw-r--r--source/blender/blenkernel/intern/implicit.c153
-rw-r--r--source/blender/blenkernel/intern/ipo.c28
-rw-r--r--source/blender/blenkernel/intern/key.c121
-rw-r--r--source/blender/blenkernel/intern/lattice.c45
-rw-r--r--source/blender/blenkernel/intern/library.c24
-rw-r--r--source/blender/blenkernel/intern/mask.c43
-rw-r--r--source/blender/blenkernel/intern/mask_evaluate.c6
-rw-r--r--source/blender/blenkernel/intern/mask_rasterize.c36
-rw-r--r--source/blender/blenkernel/intern/material.c42
-rw-r--r--source/blender/blenkernel/intern/mball.c60
-rw-r--r--source/blender/blenkernel/intern/mesh.c112
-rw-r--r--source/blender/blenkernel/intern/mesh_validate.c11
-rw-r--r--source/blender/blenkernel/intern/modifier.c49
-rw-r--r--source/blender/blenkernel/intern/modifiers_bmesh.c32
-rw-r--r--source/blender/blenkernel/intern/movieclip.c74
-rw-r--r--source/blender/blenkernel/intern/multires.c32
-rw-r--r--source/blender/blenkernel/intern/navmesh_conversion.c338
-rw-r--r--source/blender/blenkernel/intern/nla.c14
-rw-r--r--source/blender/blenkernel/intern/node.c122
-rw-r--r--source/blender/blenkernel/intern/object.c266
-rw-r--r--source/blender/blenkernel/intern/ocean.c2
-rw-r--r--source/blender/blenkernel/intern/packedFile.c11
-rw-r--r--source/blender/blenkernel/intern/paint.c12
-rw-r--r--source/blender/blenkernel/intern/particle.c105
-rw-r--r--source/blender/blenkernel/intern/particle_system.c146
-rw-r--r--source/blender/blenkernel/intern/pointcache.c288
-rw-r--r--source/blender/blenkernel/intern/property.c65
-rw-r--r--source/blender/blenkernel/intern/report.c48
-rw-r--r--source/blender/blenkernel/intern/sca.c29
-rw-r--r--source/blender/blenkernel/intern/scene.c57
-rw-r--r--source/blender/blenkernel/intern/seqeffects.c24
-rw-r--r--source/blender/blenkernel/intern/sequencer.c158
-rw-r--r--source/blender/blenkernel/intern/shrinkwrap.c197
-rw-r--r--source/blender/blenkernel/intern/smoke.c3046
-rw-r--r--source/blender/blenkernel/intern/softbody.c58
-rw-r--r--source/blender/blenkernel/intern/sound.c7
-rw-r--r--source/blender/blenkernel/intern/subsurf_ccg.c68
-rw-r--r--source/blender/blenkernel/intern/text.c71
-rw-r--r--source/blender/blenkernel/intern/texture.c25
-rw-r--r--source/blender/blenkernel/intern/tracking.c130
-rw-r--r--source/blender/blenkernel/intern/unit.c4
-rw-r--r--source/blender/blenkernel/intern/world.c2
-rw-r--r--source/blender/blenkernel/intern/writeavi.c28
-rw-r--r--source/blender/blenkernel/intern/writeffmpeg.c27
-rw-r--r--source/blender/blenkernel/intern/writeframeserver.c8
-rw-r--r--source/blender/blenkernel/nla_private.h2
-rw-r--r--source/blender/blenlib/BLI_blenlib.h2
-rw-r--r--source/blender/blenlib/BLI_bpath.h2
-rw-r--r--source/blender/blenlib/BLI_dlrbTree.h4
-rw-r--r--source/blender/blenlib/BLI_dynstr.h7
-rw-r--r--source/blender/blenlib/BLI_endian_switch.h38
-rw-r--r--source/blender/blenlib/BLI_endian_switch_inline.h80
-rw-r--r--source/blender/blenlib/BLI_fileops.h2
-rw-r--r--source/blender/blenlib/BLI_fileops_types.h2
-rw-r--r--source/blender/blenlib/BLI_heap.h8
-rw-r--r--source/blender/blenlib/BLI_kdopbvh.h25
-rw-r--r--source/blender/blenlib/BLI_kdtree.h2
-rw-r--r--source/blender/blenlib/BLI_lasso.h6
-rw-r--r--source/blender/blenlib/BLI_math_base.h11
-rw-r--r--source/blender/blenlib/BLI_math_color.h2
-rw-r--r--source/blender/blenlib/BLI_math_geom.h39
-rw-r--r--source/blender/blenlib/BLI_math_matrix.h1
-rw-r--r--source/blender/blenlib/BLI_math_rotation.h4
-rw-r--r--source/blender/blenlib/BLI_math_vector.h9
-rw-r--r--source/blender/blenlib/BLI_pbvh.h4
-rw-r--r--source/blender/blenlib/BLI_quadric.h (renamed from intern/decimation/intern/LOD_MeshException.h)49
-rw-r--r--source/blender/blenlib/BLI_rand.h23
-rw-r--r--source/blender/blenlib/BLI_rect.h32
-rw-r--r--source/blender/blenlib/BLI_scanfill.h2
-rw-r--r--source/blender/blenlib/BLI_string.h26
-rw-r--r--source/blender/blenlib/BLI_string_utf8.h13
-rw-r--r--source/blender/blenlib/BLI_utildefines.h127
-rw-r--r--source/blender/blenlib/BLI_voronoi.h2
-rw-r--r--source/blender/blenlib/CMakeLists.txt4
-rw-r--r--source/blender/blenlib/PIL_time.h15
-rw-r--r--source/blender/blenlib/intern/BLI_ghash.c4
-rw-r--r--source/blender/blenlib/intern/BLI_heap.c137
-rw-r--r--source/blender/blenlib/intern/BLI_kdopbvh.c214
-rw-r--r--source/blender/blenlib/intern/BLI_kdtree.c10
-rw-r--r--source/blender/blenlib/intern/DLRB_tree.c4
-rw-r--r--source/blender/blenlib/intern/boxpack2d.c16
-rw-r--r--source/blender/blenlib/intern/bpath.c20
-rw-r--r--source/blender/blenlib/intern/edgehash.c2
-rw-r--r--source/blender/blenlib/intern/fileops.c60
-rw-r--r--source/blender/blenlib/intern/freetypefont.c29
-rw-r--r--source/blender/blenlib/intern/graph.c16
-rw-r--r--source/blender/blenlib/intern/lasso.c8
-rw-r--r--source/blender/blenlib/intern/listbase.c12
-rw-r--r--source/blender/blenlib/intern/math_base_inline.c18
-rw-r--r--source/blender/blenlib/intern/math_color_inline.c15
-rw-r--r--source/blender/blenlib/intern/math_geom.c143
-rw-r--r--source/blender/blenlib/intern/math_geom_inline.c20
-rw-r--r--source/blender/blenlib/intern/math_matrix.c126
-rw-r--r--source/blender/blenlib/intern/math_rotation.c61
-rw-r--r--source/blender/blenlib/intern/math_vector.c11
-rw-r--r--source/blender/blenlib/intern/math_vector_inline.c52
-rw-r--r--source/blender/blenlib/intern/noise.c13
-rw-r--r--source/blender/blenlib/intern/path_util.c18
-rw-r--r--source/blender/blenlib/intern/pbvh.c46
-rw-r--r--source/blender/blenlib/intern/quadric.c131
-rw-r--r--source/blender/blenlib/intern/rand.c72
-rw-r--r--source/blender/blenlib/intern/rct.c94
-rw-r--r--source/blender/blenlib/intern/scanfill.c12
-rw-r--r--source/blender/blenlib/intern/storage.c10
-rw-r--r--source/blender/blenlib/intern/string.c46
-rw-r--r--source/blender/blenlib/intern/string_cursor_utf8.c2
-rw-r--r--source/blender/blenlib/intern/string_utf8.c128
-rw-r--r--source/blender/blenlib/intern/time.c2
-rw-r--r--source/blender/blenlib/intern/uvproject.c2
-rw-r--r--source/blender/blenlib/intern/voronoi.c10
-rw-r--r--source/blender/blenlib/intern/voxel.c52
-rw-r--r--source/blender/blenlib/intern/winstuff.c4
-rw-r--r--source/blender/blenloader/CMakeLists.txt5
-rw-r--r--source/blender/blenloader/SConscript5
-rw-r--r--source/blender/blenloader/intern/readblenentry.c18
-rw-r--r--source/blender/blenloader/intern/readfile.c742
-rw-r--r--source/blender/blenloader/intern/runtime.c12
-rw-r--r--source/blender/blenloader/intern/versioning_250.c10
-rw-r--r--source/blender/blenloader/intern/versioning_legacy.c8
-rw-r--r--source/blender/blenloader/intern/writefile.c160
-rw-r--r--source/blender/bmesh/CMakeLists.txt20
-rw-r--r--source/blender/bmesh/SConscript11
-rw-r--r--source/blender/bmesh/bmesh.h1
-rw-r--r--source/blender/bmesh/bmesh_class.h5
-rw-r--r--source/blender/bmesh/intern/bmesh_construct.c13
-rw-r--r--source/blender/bmesh/intern/bmesh_core.c69
-rw-r--r--source/blender/bmesh/intern/bmesh_core.h4
-rw-r--r--source/blender/bmesh/intern/bmesh_decimate.h41
-rw-r--r--source/blender/bmesh/intern/bmesh_decimate_collapse.c949
-rw-r--r--source/blender/bmesh/intern/bmesh_decimate_dissolve.c243
-rw-r--r--source/blender/bmesh/intern/bmesh_decimate_unsubdivide.c344
-rw-r--r--source/blender/bmesh/intern/bmesh_inline.h6
-rw-r--r--source/blender/bmesh/intern/bmesh_interp.c19
-rw-r--r--source/blender/bmesh/intern/bmesh_iterators.c148
-rw-r--r--source/blender/bmesh/intern/bmesh_iterators.h14
-rw-r--r--source/blender/bmesh/intern/bmesh_marking.c5
-rw-r--r--source/blender/bmesh/intern/bmesh_mesh.c35
-rw-r--r--source/blender/bmesh/intern/bmesh_mesh_conv.c8
-rw-r--r--source/blender/bmesh/intern/bmesh_mods.c20
-rw-r--r--source/blender/bmesh/intern/bmesh_opdefines.c87
-rw-r--r--source/blender/bmesh/intern/bmesh_operator_api.h10
-rw-r--r--source/blender/bmesh/intern/bmesh_operators.c30
-rw-r--r--source/blender/bmesh/intern/bmesh_operators.h7
-rw-r--r--source/blender/bmesh/intern/bmesh_operators_private.h3
-rw-r--r--source/blender/bmesh/intern/bmesh_polygon.c12
-rw-r--r--source/blender/bmesh/intern/bmesh_queries.c120
-rw-r--r--source/blender/bmesh/intern/bmesh_queries.h4
-rw-r--r--source/blender/bmesh/intern/bmesh_walkers_impl.c9
-rw-r--r--source/blender/bmesh/operators/bmo_bevel.c10
-rw-r--r--source/blender/bmesh/operators/bmo_connect.c16
-rw-r--r--source/blender/bmesh/operators/bmo_create.c9
-rw-r--r--source/blender/bmesh/operators/bmo_dissolve.c177
-rw-r--r--source/blender/bmesh/operators/bmo_dupe.c2
-rw-r--r--source/blender/bmesh/operators/bmo_extrude.c126
-rw-r--r--source/blender/bmesh/operators/bmo_hull.c533
-rw-r--r--source/blender/bmesh/operators/bmo_join_triangles.c159
-rw-r--r--source/blender/bmesh/operators/bmo_primitive.c12
-rw-r--r--source/blender/bmesh/operators/bmo_removedoubles.c13
-rw-r--r--source/blender/bmesh/operators/bmo_similar.c614
-rw-r--r--source/blender/bmesh/operators/bmo_slide.c4
-rw-r--r--source/blender/bmesh/operators/bmo_smooth_laplacian.c619
-rw-r--r--source/blender/bmesh/operators/bmo_subdivide.c11
-rw-r--r--source/blender/bmesh/operators/bmo_symmetrize.c663
-rw-r--r--source/blender/bmesh/operators/bmo_unsubdivide.c59
-rw-r--r--source/blender/bmesh/operators/bmo_utils.c555
-rw-r--r--source/blender/bmesh/tools/BME_bevel.c11
-rw-r--r--source/blender/collada/AnimationExporter.cpp22
-rw-r--r--source/blender/collada/AnimationExporter.h19
-rw-r--r--source/blender/collada/AnimationImporter.cpp25
-rw-r--r--source/blender/collada/AnimationImporter.h2
-rw-r--r--source/blender/collada/ArmatureExporter.cpp2
-rw-r--r--source/blender/collada/ArmatureImporter.h2
-rw-r--r--source/blender/collada/CMakeLists.txt2
-rw-r--r--source/blender/collada/DocumentExporter.cpp36
-rw-r--r--source/blender/collada/DocumentExporter.h2
-rw-r--r--source/blender/collada/DocumentImporter.cpp14
-rw-r--r--source/blender/collada/DocumentImporter.h5
-rw-r--r--source/blender/collada/EffectExporter.cpp6
-rw-r--r--source/blender/collada/GeometryExporter.cpp10
-rw-r--r--source/blender/collada/ImageExporter.cpp4
-rw-r--r--source/blender/collada/MeshImporter.cpp12
-rw-r--r--source/blender/collada/MeshImporter.h26
-rw-r--r--source/blender/collada/SceneExporter.cpp6
-rw-r--r--source/blender/collada/collada.cpp1
-rw-r--r--source/blender/collada/collada_internal.h1
-rw-r--r--source/blender/collada/collada_utils.cpp5
-rw-r--r--source/blender/collada/collada_utils.h11
-rw-r--r--source/blender/compositor/CMakeLists.txt8
-rw-r--r--source/blender/compositor/intern/COM_Converter.cpp4
-rw-r--r--source/blender/compositor/intern/COM_ExecutionGroup.cpp10
-rw-r--r--source/blender/compositor/intern/COM_ExecutionSystem.cpp33
-rw-r--r--source/blender/compositor/intern/COM_ExecutionSystem.h5
-rw-r--r--source/blender/compositor/intern/COM_ExecutionSystemHelper.cpp7
-rw-r--r--source/blender/compositor/intern/COM_InputSocket.cpp11
-rw-r--r--source/blender/compositor/intern/COM_InputSocket.h18
-rw-r--r--source/blender/compositor/intern/COM_MemoryBuffer.cpp6
-rw-r--r--source/blender/compositor/intern/COM_Node.cpp10
-rw-r--r--source/blender/compositor/intern/COM_Node.h15
-rw-r--r--source/blender/compositor/intern/COM_NodeBase.h8
-rw-r--r--source/blender/compositor/intern/COM_NodeOperation.cpp10
-rw-r--r--source/blender/compositor/intern/COM_NodeOperation.h9
-rw-r--r--source/blender/compositor/intern/COM_OpenCLDevice.cpp2
-rw-r--r--source/blender/compositor/intern/COM_OutputSocket.cpp10
-rw-r--r--source/blender/compositor/intern/COM_OutputSocket.h5
-rw-r--r--source/blender/compositor/intern/COM_WorkScheduler.cpp13
-rw-r--r--source/blender/compositor/intern/COM_compositor.cpp6
-rw-r--r--source/blender/compositor/nodes/COM_ChannelMatteNode.h2
-rw-r--r--source/blender/compositor/nodes/COM_ChromaMatteNode.h2
-rw-r--r--source/blender/compositor/nodes/COM_ColorBalanceNode.h2
-rw-r--r--source/blender/compositor/nodes/COM_ColorMatteNode.h2
-rw-r--r--source/blender/compositor/nodes/COM_ColorRampNode.h2
-rw-r--r--source/blender/compositor/nodes/COM_ColorSpillNode.h2
-rw-r--r--source/blender/compositor/nodes/COM_ConvertAlphaNode.cpp2
-rw-r--r--source/blender/compositor/nodes/COM_CropNode.cpp2
-rw-r--r--source/blender/compositor/nodes/COM_DifferenceMatteNode.h2
-rw-r--r--source/blender/compositor/nodes/COM_DilateErodeNode.cpp4
-rw-r--r--source/blender/compositor/nodes/COM_DistanceMatteNode.h2
-rw-r--r--source/blender/compositor/nodes/COM_FilterNode.h6
-rw-r--r--source/blender/compositor/nodes/COM_HueSaturationValueNode.cpp2
-rw-r--r--source/blender/compositor/nodes/COM_KeyingNode.cpp2
-rw-r--r--source/blender/compositor/nodes/COM_LuminanceMatteNode.h6
-rw-r--r--source/blender/compositor/nodes/COM_MapValueNode.h6
-rw-r--r--source/blender/compositor/nodes/COM_MaskNode.h6
-rw-r--r--source/blender/compositor/nodes/COM_MovieClipNode.h6
-rw-r--r--source/blender/compositor/nodes/COM_MuteNode.cpp10
-rw-r--r--source/blender/compositor/nodes/COM_NormalNode.h2
-rw-r--r--source/blender/compositor/nodes/COM_PixelateNode.cpp48
-rw-r--r--source/blender/compositor/nodes/COM_PixelateNode.h38
-rw-r--r--source/blender/compositor/nodes/COM_SeparateRGBANode.cpp3
-rw-r--r--source/blender/compositor/nodes/COM_TransformNode.h6
-rw-r--r--source/blender/compositor/nodes/COM_ViewLevelsNode.cpp14
-rw-r--r--source/blender/compositor/nodes/COM_ViewerNode.cpp3
-rw-r--r--source/blender/compositor/operations/COM_BokehBlurOperation.h5
-rw-r--r--source/blender/compositor/operations/COM_ColorSpillOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.cpp4
-rw-r--r--source/blender/compositor/operations/COM_CropOperation.cpp46
-rw-r--r--source/blender/compositor/operations/COM_CropOperation.h2
-rw-r--r--source/blender/compositor/operations/COM_DespeckleOperation.h4
-rw-r--r--source/blender/compositor/operations/COM_DilateErodeOperation.cpp14
-rw-r--r--source/blender/compositor/operations/COM_DisplaceOperation.cpp4
-rw-r--r--source/blender/compositor/operations/COM_DisplaceSimpleOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_FastGaussianBlurOperation.cpp6
-rw-r--r--source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.cpp8
-rw-r--r--source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.cpp8
-rw-r--r--source/blender/compositor/operations/COM_GaussianBokehBlurOperation.cpp16
-rw-r--r--source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp14
-rw-r--r--source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp16
-rw-r--r--source/blender/compositor/operations/COM_GlareFogGlowOperation.cpp8
-rw-r--r--source/blender/compositor/operations/COM_GlareGhostOperation.cpp8
-rw-r--r--source/blender/compositor/operations/COM_GlareStreaksOperation.cpp8
-rw-r--r--source/blender/compositor/operations/COM_InpaintOperation.cpp8
-rw-r--r--source/blender/compositor/operations/COM_KeyingDespillOperation.cpp27
-rw-r--r--source/blender/compositor/operations/COM_KeyingOperation.cpp28
-rw-r--r--source/blender/compositor/operations/COM_MapUVOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_MaskOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_MathBaseOperation.h2
-rw-r--r--source/blender/compositor/operations/COM_MixBaseOperation.h2
-rw-r--r--source/blender/compositor/operations/COM_MixColorOperation.cpp9
-rw-r--r--source/blender/compositor/operations/COM_MixGlareOperation.cpp10
-rw-r--r--source/blender/compositor/operations/COM_MovieDistortionOperation.cpp17
-rw-r--r--source/blender/compositor/operations/COM_MovieDistortionOperation.h8
-rw-r--r--source/blender/compositor/operations/COM_OpenCLKernels.cl14
-rw-r--r--source/blender/compositor/operations/COM_OutputFileOperation.cpp13
-rw-r--r--source/blender/compositor/operations/COM_PixelateOperation.cpp49
-rw-r--r--source/blender/compositor/operations/COM_PixelateOperation.h68
-rw-r--r--source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.cpp4
-rw-r--r--source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp14
-rw-r--r--source/blender/compositor/operations/COM_TrackPositionOperation.h8
-rw-r--r--source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp12
-rw-r--r--source/blender/compositor/operations/COM_ViewerBaseOperation.cpp8
-rw-r--r--source/blender/compositor/operations/COM_ViewerOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_WriteBufferOperation.cpp3
-rw-r--r--source/blender/compositor/operations/COM_ZCombineOperation.cpp10
-rw-r--r--source/blender/datatoc/datatoc.c5
-rw-r--r--source/blender/editors/animation/anim_channels_defines.c92
-rw-r--r--source/blender/editors/animation/anim_channels_edit.c18
-rw-r--r--source/blender/editors/animation/anim_deps.c2
-rw-r--r--source/blender/editors/animation/anim_draw.c4
-rw-r--r--source/blender/editors/animation/anim_filter.c99
-rw-r--r--source/blender/editors/animation/anim_intern.h4
-rw-r--r--source/blender/editors/animation/anim_ipo_utils.c2
-rw-r--r--source/blender/editors/animation/anim_markers.c24
-rw-r--r--source/blender/editors/animation/anim_ops.c3
-rw-r--r--source/blender/editors/animation/drivers.c12
-rw-r--r--source/blender/editors/animation/fmodifier_ui.c50
-rw-r--r--source/blender/editors/animation/keyframes_draw.c8
-rw-r--r--source/blender/editors/animation/keyframes_edit.c8
-rw-r--r--source/blender/editors/animation/keyframes_general.c4
-rw-r--r--source/blender/editors/animation/keyframing.c204
-rw-r--r--source/blender/editors/animation/keyingsets.c22
-rw-r--r--source/blender/editors/armature/armature_ops.c4
-rw-r--r--source/blender/editors/armature/editarmature.c128
-rw-r--r--source/blender/editors/armature/editarmature_generate.c2
-rw-r--r--source/blender/editors/armature/editarmature_retarget.c40
-rw-r--r--source/blender/editors/armature/editarmature_sketch.c135
-rw-r--r--source/blender/editors/armature/meshlaplacian.c146
-rw-r--r--source/blender/editors/armature/poseSlide.c15
-rw-r--r--source/blender/editors/armature/poseUtils.c2
-rw-r--r--source/blender/editors/armature/poselib.c32
-rw-r--r--source/blender/editors/armature/poseobject.c150
-rw-r--r--source/blender/editors/armature/reeb.c50
-rw-r--r--source/blender/editors/armature/reeb.h2
-rw-r--r--source/blender/editors/curve/editcurve.c297
-rw-r--r--source/blender/editors/curve/editfont.c79
-rw-r--r--source/blender/editors/gpencil/drawgpencil.c65
-rw-r--r--source/blender/editors/gpencil/editaction_gpencil.c2
-rw-r--r--source/blender/editors/gpencil/gpencil_buttons.c8
-rw-r--r--source/blender/editors/gpencil/gpencil_edit.c24
-rw-r--r--source/blender/editors/gpencil/gpencil_paint.c205
-rw-r--r--source/blender/editors/gpencil/gpencil_undo.c2
-rw-r--r--source/blender/editors/include/ED_anim_api.h36
-rw-r--r--source/blender/editors/include/ED_armature.h15
-rw-r--r--source/blender/editors/include/ED_curve.h2
-rw-r--r--source/blender/editors/include/ED_keyframes_draw.h1
-rw-r--r--source/blender/editors/include/ED_mask.h4
-rw-r--r--source/blender/editors/include/ED_mball.h2
-rw-r--r--source/blender/editors/include/ED_mesh.h17
-rw-r--r--source/blender/editors/include/ED_object.h26
-rw-r--r--source/blender/editors/include/ED_particle.h2
-rw-r--r--source/blender/editors/include/ED_screen.h2
-rw-r--r--source/blender/editors/include/ED_screen_types.h2
-rw-r--r--source/blender/editors/include/ED_sculpt.h6
-rw-r--r--source/blender/editors/include/ED_view3d.h252
-rw-r--r--source/blender/editors/include/UI_icons.h9
-rw-r--r--source/blender/editors/include/UI_interface.h18
-rw-r--r--source/blender/editors/include/UI_view2d.h18
-rw-r--r--source/blender/editors/interface/interface.c238
-rw-r--r--source/blender/editors/interface/interface_draw.c120
-rw-r--r--source/blender/editors/interface/interface_handlers.c666
-rw-r--r--source/blender/editors/interface/interface_icons.c14
-rw-r--r--source/blender/editors/interface/interface_intern.h33
-rw-r--r--source/blender/editors/interface/interface_layout.c51
-rw-r--r--source/blender/editors/interface/interface_ops.c74
-rw-r--r--source/blender/editors/interface/interface_panel.c40
-rw-r--r--source/blender/editors/interface/interface_regions.c175
-rw-r--r--source/blender/editors/interface/interface_style.c14
-rw-r--r--source/blender/editors/interface/interface_templates.c153
-rw-r--r--source/blender/editors/interface/interface_widgets.c441
-rw-r--r--source/blender/editors/interface/resources.c60
-rw-r--r--source/blender/editors/interface/view2d.c171
-rw-r--r--source/blender/editors/interface/view2d_ops.c128
-rw-r--r--source/blender/editors/io/io_collada.c56
-rw-r--r--source/blender/editors/mask/CMakeLists.txt2
-rw-r--r--source/blender/editors/mask/mask_add.c28
-rw-r--r--source/blender/editors/mask/mask_draw.c103
-rw-r--r--source/blender/editors/mask/mask_edit.c6
-rw-r--r--source/blender/editors/mask/mask_intern.h3
-rw-r--r--source/blender/editors/mask/mask_ops.c22
-rw-r--r--source/blender/editors/mask/mask_select.c11
-rw-r--r--source/blender/editors/mesh/CMakeLists.txt9
-rw-r--r--source/blender/editors/mesh/SConscript8
-rw-r--r--source/blender/editors/mesh/editface.c18
-rw-r--r--source/blender/editors/mesh/editmesh_add.c196
-rw-r--r--source/blender/editors/mesh/editmesh_bvh.c13
-rw-r--r--source/blender/editors/mesh/editmesh_knife.c93
-rw-r--r--source/blender/editors/mesh/editmesh_loopcut.c22
-rw-r--r--source/blender/editors/mesh/editmesh_rip.c373
-rw-r--r--source/blender/editors/mesh/editmesh_select.c239
-rw-r--r--source/blender/editors/mesh/editmesh_slide.c48
-rw-r--r--source/blender/editors/mesh/editmesh_tools.c642
-rw-r--r--source/blender/editors/mesh/editmesh_utils.c42
-rw-r--r--source/blender/editors/mesh/mesh_data.c256
-rw-r--r--source/blender/editors/mesh/mesh_intern.h15
-rw-r--r--source/blender/editors/mesh/mesh_navmesh.c2
-rw-r--r--source/blender/editors/mesh/mesh_ops.c27
-rw-r--r--source/blender/editors/mesh/meshtools.c135
-rw-r--r--source/blender/editors/metaball/mball_edit.c84
-rw-r--r--source/blender/editors/object/object_add.c725
-rw-r--r--source/blender/editors/object/object_bake.c72
-rw-r--r--source/blender/editors/object/object_constraint.c203
-rw-r--r--source/blender/editors/object/object_edit.c72
-rw-r--r--source/blender/editors/object/object_group.c6
-rw-r--r--source/blender/editors/object/object_hook.c24
-rw-r--r--source/blender/editors/object/object_intern.h5
-rw-r--r--source/blender/editors/object/object_lattice.c282
-rw-r--r--source/blender/editors/object/object_modifier.c42
-rw-r--r--source/blender/editors/object/object_ops.c9
-rw-r--r--source/blender/editors/object/object_relations.c196
-rw-r--r--source/blender/editors/object/object_select.c16
-rw-r--r--source/blender/editors/object/object_shapekey.c30
-rw-r--r--source/blender/editors/object/object_transform.c70
-rw-r--r--source/blender/editors/object/object_vgroup.c635
-rw-r--r--source/blender/editors/physics/CMakeLists.txt5
-rw-r--r--source/blender/editors/physics/SConscript12
-rw-r--r--source/blender/editors/physics/dynamicpaint_ops.c65
-rw-r--r--source/blender/editors/physics/particle_boids.c2
-rw-r--r--source/blender/editors/physics/particle_edit.c204
-rw-r--r--source/blender/editors/physics/particle_object.c11
-rw-r--r--source/blender/editors/physics/physics_fluid.c49
-rw-r--r--source/blender/editors/physics/physics_ops.c2
-rw-r--r--source/blender/editors/physics/physics_pointcache.c6
-rw-r--r--source/blender/editors/render/render_internal.c30
-rw-r--r--source/blender/editors/render/render_opengl.c26
-rw-r--r--source/blender/editors/render/render_preview.c44
-rw-r--r--source/blender/editors/render/render_shading.c6
-rw-r--r--source/blender/editors/render/render_update.c53
-rw-r--r--source/blender/editors/render/render_view.c3
-rw-r--r--source/blender/editors/screen/area.c147
-rw-r--r--source/blender/editors/screen/glutil.c28
-rw-r--r--source/blender/editors/screen/screen_context.c4
-rw-r--r--source/blender/editors/screen/screen_edit.c27
-rw-r--r--source/blender/editors/screen/screen_ops.c189
-rw-r--r--source/blender/editors/screen/screendump.c14
-rw-r--r--source/blender/editors/sculpt_paint/CMakeLists.txt2
-rw-r--r--source/blender/editors/sculpt_paint/paint_cursor.c21
-rw-r--r--source/blender/editors/sculpt_paint/paint_hide.c6
-rw-r--r--source/blender/editors/sculpt_paint/paint_image.c142
-rw-r--r--source/blender/editors/sculpt_paint/paint_intern.h2
-rw-r--r--source/blender/editors/sculpt_paint/paint_mask.c7
-rw-r--r--source/blender/editors/sculpt_paint/paint_ops.c2
-rw-r--r--source/blender/editors/sculpt_paint/paint_stroke.c35
-rw-r--r--source/blender/editors/sculpt_paint/paint_undo.c12
-rw-r--r--source/blender/editors/sculpt_paint/paint_utils.c16
-rw-r--r--source/blender/editors/sculpt_paint/paint_vertex.c239
-rw-r--r--source/blender/editors/sculpt_paint/sculpt.c135
-rw-r--r--source/blender/editors/sculpt_paint/sculpt_intern.h6
-rw-r--r--source/blender/editors/sculpt_paint/sculpt_undo.c31
-rw-r--r--source/blender/editors/space_action/action_draw.c8
-rw-r--r--source/blender/editors/space_action/action_edit.c79
-rw-r--r--source/blender/editors/space_action/action_intern.h4
-rw-r--r--source/blender/editors/space_action/action_ops.c5
-rw-r--r--source/blender/editors/space_action/action_select.c17
-rw-r--r--source/blender/editors/space_action/space_action.c11
-rw-r--r--source/blender/editors/space_api/spacetypes.c4
-rw-r--r--source/blender/editors/space_buttons/buttons_context.c6
-rw-r--r--source/blender/editors/space_buttons/buttons_header.c2
-rw-r--r--source/blender/editors/space_buttons/buttons_ops.c4
-rw-r--r--source/blender/editors/space_buttons/space_buttons.c2
-rw-r--r--source/blender/editors/space_clip/CMakeLists.txt2
-rw-r--r--source/blender/editors/space_clip/clip_buttons.c2
-rw-r--r--source/blender/editors/space_clip/clip_dopesheet_draw.c2
-rw-r--r--source/blender/editors/space_clip/clip_draw.c27
-rw-r--r--source/blender/editors/space_clip/clip_editor.c15
-rw-r--r--source/blender/editors/space_clip/clip_graph_ops.c6
-rw-r--r--source/blender/editors/space_clip/clip_ops.c42
-rw-r--r--source/blender/editors/space_clip/space_clip.c24
-rw-r--r--source/blender/editors/space_clip/tracking_ops.c42
-rw-r--r--source/blender/editors/space_clip/tracking_select.c13
-rw-r--r--source/blender/editors/space_console/console_draw.c15
-rw-r--r--source/blender/editors/space_console/console_ops.c24
-rw-r--r--source/blender/editors/space_console/space_console.c10
-rw-r--r--source/blender/editors/space_file/file_draw.c18
-rw-r--r--source/blender/editors/space_file/file_intern.h1
-rw-r--r--source/blender/editors/space_file/file_ops.c102
-rw-r--r--source/blender/editors/space_file/file_panels.c37
-rw-r--r--source/blender/editors/space_file/filelist.c66
-rw-r--r--source/blender/editors/space_file/filesel.c23
-rw-r--r--source/blender/editors/space_file/fsmenu.c206
-rw-r--r--source/blender/editors/space_file/fsmenu.h9
-rw-r--r--source/blender/editors/space_file/space_file.c13
-rw-r--r--source/blender/editors/space_graph/graph_buttons.c51
-rw-r--r--source/blender/editors/space_graph/graph_draw.c48
-rw-r--r--source/blender/editors/space_graph/graph_edit.c94
-rw-r--r--source/blender/editors/space_graph/graph_intern.h2
-rw-r--r--source/blender/editors/space_graph/graph_ops.c7
-rw-r--r--source/blender/editors/space_graph/graph_select.c10
-rw-r--r--source/blender/editors/space_graph/space_graph.c4
-rw-r--r--source/blender/editors/space_image/image_buttons.c43
-rw-r--r--source/blender/editors/space_image/image_draw.c10
-rw-r--r--source/blender/editors/space_image/image_edit.c18
-rw-r--r--source/blender/editors/space_image/image_ops.c146
-rw-r--r--source/blender/editors/space_image/space_image.c27
-rw-r--r--source/blender/editors/space_info/info_draw.c2
-rw-r--r--source/blender/editors/space_info/info_ops.c8
-rw-r--r--source/blender/editors/space_info/info_report.c8
-rw-r--r--source/blender/editors/space_info/info_stats.c2
-rw-r--r--source/blender/editors/space_info/space_info.c10
-rw-r--r--source/blender/editors/space_info/textview.c8
-rw-r--r--source/blender/editors/space_logic/CMakeLists.txt4
-rw-r--r--source/blender/editors/space_logic/SConscript5
-rw-r--r--source/blender/editors/space_logic/logic_buttons.c32
-rw-r--r--source/blender/editors/space_logic/logic_ops.c6
-rw-r--r--source/blender/editors/space_logic/logic_window.c2809
-rw-r--r--source/blender/editors/space_logic/space_logic.c60
-rw-r--r--source/blender/editors/space_nla/nla_buttons.c11
-rw-r--r--source/blender/editors/space_nla/nla_channels.c2
-rw-r--r--source/blender/editors/space_nla/nla_draw.c16
-rw-r--r--source/blender/editors/space_nla/nla_edit.c33
-rw-r--r--source/blender/editors/space_nla/nla_ops.c2
-rw-r--r--source/blender/editors/space_nla/nla_select.c8
-rw-r--r--source/blender/editors/space_node/drawnode.c198
-rw-r--r--source/blender/editors/space_node/node_add.c183
-rw-r--r--source/blender/editors/space_node/node_draw.c45
-rw-r--r--source/blender/editors/space_node/node_edit.c130
-rw-r--r--source/blender/editors/space_node/node_group.c54
-rw-r--r--source/blender/editors/space_node/node_header.c12
-rw-r--r--source/blender/editors/space_node/node_intern.h2
-rw-r--r--source/blender/editors/space_node/node_ops.c4
-rw-r--r--source/blender/editors/space_node/node_relationships.c4
-rw-r--r--source/blender/editors/space_node/node_select.c10
-rw-r--r--source/blender/editors/space_node/node_templates.c16
-rw-r--r--source/blender/editors/space_node/node_view.c15
-rw-r--r--source/blender/editors/space_node/space_node.c17
-rw-r--r--source/blender/editors/space_outliner/outliner_draw.c52
-rw-r--r--source/blender/editors/space_outliner/outliner_edit.c36
-rw-r--r--source/blender/editors/space_outliner/outliner_select.c14
-rw-r--r--source/blender/editors/space_outliner/outliner_tools.c89
-rw-r--r--source/blender/editors/space_outliner/outliner_tree.c42
-rw-r--r--source/blender/editors/space_sequencer/CMakeLists.txt4
-rw-r--r--source/blender/editors/space_sequencer/SConscript7
-rw-r--r--source/blender/editors/space_sequencer/sequencer_add.c12
-rw-r--r--source/blender/editors/space_sequencer/sequencer_draw.c40
-rw-r--r--source/blender/editors/space_sequencer/sequencer_edit.c92
-rw-r--r--source/blender/editors/space_sequencer/sequencer_ops.c45
-rw-r--r--source/blender/editors/space_sequencer/sequencer_scopes.c24
-rw-r--r--source/blender/editors/space_sequencer/sequencer_select.c17
-rw-r--r--source/blender/editors/space_sequencer/sequencer_view.c2
-rw-r--r--source/blender/editors/space_sequencer/space_sequencer.c14
-rw-r--r--source/blender/editors/space_text/CMakeLists.txt4
-rw-r--r--source/blender/editors/space_text/SConscript3
-rw-r--r--source/blender/editors/space_text/space_text.c2
-rw-r--r--source/blender/editors/space_text/text_draw.c43
-rw-r--r--source/blender/editors/space_text/text_header.c5
-rw-r--r--source/blender/editors/space_text/text_ops.c55
-rw-r--r--source/blender/editors/space_text/text_python.c4
-rw-r--r--source/blender/editors/space_time/space_time.c1
-rw-r--r--source/blender/editors/space_time/time_ops.c2
-rw-r--r--source/blender/editors/space_userpref/space_userpref.c2
-rw-r--r--source/blender/editors/space_view3d/CMakeLists.txt2
-rw-r--r--source/blender/editors/space_view3d/drawanimviz.c24
-rw-r--r--source/blender/editors/space_view3d/drawarmature.c59
-rw-r--r--source/blender/editors/space_view3d/drawmesh.c27
-rw-r--r--source/blender/editors/space_view3d/drawobject.c638
-rw-r--r--source/blender/editors/space_view3d/drawvolume.c298
-rw-r--r--source/blender/editors/space_view3d/space_view3d.c19
-rw-r--r--source/blender/editors/space_view3d/view3d_buttons.c366
-rw-r--r--source/blender/editors/space_view3d/view3d_draw.c281
-rw-r--r--source/blender/editors/space_view3d/view3d_edit.c494
-rw-r--r--source/blender/editors/space_view3d/view3d_fly.c25
-rw-r--r--source/blender/editors/space_view3d/view3d_header.c29
-rw-r--r--source/blender/editors/space_view3d/view3d_intern.h21
-rw-r--r--source/blender/editors/space_view3d/view3d_iterators.c416
-rw-r--r--source/blender/editors/space_view3d/view3d_ops.c18
-rw-r--r--source/blender/editors/space_view3d/view3d_project.c493
-rw-r--r--source/blender/editors/space_view3d/view3d_select.c926
-rw-r--r--source/blender/editors/space_view3d/view3d_snap.c89
-rw-r--r--source/blender/editors/space_view3d/view3d_toolbar.c4
-rw-r--r--source/blender/editors/space_view3d/view3d_view.c458
-rw-r--r--source/blender/editors/transform/transform.c319
-rw-r--r--source/blender/editors/transform/transform.h2
-rw-r--r--source/blender/editors/transform/transform_constraints.c2
-rw-r--r--source/blender/editors/transform/transform_conversions.c226
-rw-r--r--source/blender/editors/transform/transform_generics.c51
-rw-r--r--source/blender/editors/transform/transform_manipulator.c4
-rw-r--r--source/blender/editors/transform/transform_ops.c22
-rw-r--r--source/blender/editors/transform/transform_orientations.c17
-rw-r--r--source/blender/editors/transform/transform_snap.c216
-rw-r--r--source/blender/editors/util/crazyspace.c2
-rw-r--r--source/blender/editors/util/editmode_undo.c4
-rw-r--r--source/blender/editors/util/numinput.c4
-rw-r--r--source/blender/editors/util/undo.c2
-rw-r--r--source/blender/editors/uvedit/uvedit_draw.c51
-rw-r--r--source/blender/editors/uvedit/uvedit_intern.h25
-rw-r--r--source/blender/editors/uvedit/uvedit_ops.c74
-rw-r--r--source/blender/editors/uvedit/uvedit_parametrizer.c12
-rw-r--r--source/blender/editors/uvedit/uvedit_smart_stitch.c84
-rw-r--r--source/blender/editors/uvedit/uvedit_unwrap_ops.c152
-rw-r--r--source/blender/gpu/GPU_buffers.h45
-rw-r--r--source/blender/gpu/GPU_draw.h6
-rw-r--r--source/blender/gpu/GPU_extensions.h4
-rw-r--r--source/blender/gpu/GPU_material.h2
-rw-r--r--source/blender/gpu/intern/gpu_buffers.c459
-rw-r--r--source/blender/gpu/intern/gpu_codegen.c29
-rw-r--r--source/blender/gpu/intern/gpu_codegen.h6
-rw-r--r--source/blender/gpu/intern/gpu_draw.c120
-rw-r--r--source/blender/gpu/intern/gpu_extensions.c20
-rw-r--r--source/blender/gpu/intern/gpu_material.c20
-rw-r--r--source/blender/gpu/shaders/gpu_shader_material.glsl16
-rw-r--r--source/blender/ikplugin/BIK_api.h5
-rw-r--r--source/blender/ikplugin/CMakeLists.txt4
-rw-r--r--source/blender/ikplugin/intern/ikplugin_api.h3
-rw-r--r--source/blender/ikplugin/intern/iksolver_plugin.h3
-rw-r--r--source/blender/ikplugin/intern/itasc_plugin.cpp10
-rw-r--r--source/blender/ikplugin/intern/itasc_plugin.h3
-rw-r--r--source/blender/imbuf/CMakeLists.txt28
-rw-r--r--source/blender/imbuf/IMB_colormanagement.h23
-rw-r--r--source/blender/imbuf/IMB_imbuf.h12
-rw-r--r--source/blender/imbuf/IMB_imbuf_types.h15
-rw-r--r--source/blender/imbuf/intern/IMB_anim.h4
-rw-r--r--source/blender/imbuf/intern/IMB_colormanagement_intern.h19
-rw-r--r--source/blender/imbuf/intern/IMB_filetype.h6
-rw-r--r--source/blender/imbuf/intern/IMB_indexer.h2
-rw-r--r--source/blender/imbuf/intern/allocimbuf.c2
-rw-r--r--source/blender/imbuf/intern/anim_movie.c24
-rw-r--r--source/blender/imbuf/intern/bmp.c2
-rw-r--r--source/blender/imbuf/intern/cineon/CMakeLists.txt14
-rw-r--r--source/blender/imbuf/intern/cineon/SConscript3
-rw-r--r--source/blender/imbuf/intern/cineon/cin_debug_stuff.h4
-rw-r--r--source/blender/imbuf/intern/cineon/cineon_dpx.c228
-rw-r--r--source/blender/imbuf/intern/cineon/cineonfile.h134
-rw-r--r--source/blender/imbuf/intern/cineon/cineonlib.c1007
-rw-r--r--source/blender/imbuf/intern/cineon/cineonlib.h150
-rw-r--r--source/blender/imbuf/intern/cineon/dpxfile.h128
-rw-r--r--source/blender/imbuf/intern/cineon/dpxlib.c978
-rw-r--r--source/blender/imbuf/intern/cineon/dpxlib.h162
-rw-r--r--source/blender/imbuf/intern/cineon/logImageCore.c1576
-rw-r--r--source/blender/imbuf/intern/cineon/logImageCore.h322
-rw-r--r--source/blender/imbuf/intern/cineon/logImageLib.c183
-rw-r--r--source/blender/imbuf/intern/cineon/logImageLib.h87
-rw-r--r--source/blender/imbuf/intern/cineon/logmemfile.c142
-rw-r--r--source/blender/imbuf/intern/cineon/logmemfile.h50
-rw-r--r--source/blender/imbuf/intern/colormanagement.c621
-rw-r--r--source/blender/imbuf/intern/dds/BlockDXT.cpp4
-rw-r--r--source/blender/imbuf/intern/dds/BlockDXT.h2
-rw-r--r--source/blender/imbuf/intern/dds/CMakeLists.txt14
-rw-r--r--source/blender/imbuf/intern/dds/Color.h2
-rw-r--r--source/blender/imbuf/intern/dds/ColorBlock.cpp2
-rw-r--r--source/blender/imbuf/intern/dds/ColorBlock.h2
-rw-r--r--source/blender/imbuf/intern/dds/Common.h6
-rw-r--r--source/blender/imbuf/intern/dds/DirectDrawSurface.cpp262
-rw-r--r--source/blender/imbuf/intern/dds/DirectDrawSurface.h4
-rw-r--r--source/blender/imbuf/intern/dds/FlipDXT.cpp255
-rw-r--r--source/blender/imbuf/intern/dds/FlipDXT.h32
-rw-r--r--source/blender/imbuf/intern/dds/Image.h2
-rw-r--r--source/blender/imbuf/intern/dds/PixelFormat.h64
-rw-r--r--source/blender/imbuf/intern/dds/SConscript2
-rw-r--r--source/blender/imbuf/intern/dds/Stream.h3
-rw-r--r--source/blender/imbuf/intern/dds/dds_api.cpp8
-rw-r--r--source/blender/imbuf/intern/divers.c48
-rw-r--r--source/blender/imbuf/intern/filetype.c4
-rw-r--r--source/blender/imbuf/intern/imageprocess.c40
-rw-r--r--source/blender/imbuf/intern/indexer.c39
-rw-r--r--source/blender/imbuf/intern/iris.c18
-rw-r--r--source/blender/imbuf/intern/jp2.c55
-rw-r--r--source/blender/imbuf/intern/jpeg.c4
-rw-r--r--source/blender/imbuf/intern/module.c3
-rw-r--r--source/blender/imbuf/intern/moviecache.c2
-rw-r--r--source/blender/imbuf/intern/openexr/CMakeLists.txt5
-rw-r--r--source/blender/imbuf/intern/openexr/openexr_api.cpp18
-rw-r--r--source/blender/imbuf/intern/png.c3
-rw-r--r--source/blender/imbuf/intern/radiance_hdr.c6
-rw-r--r--source/blender/imbuf/intern/readimage.c6
-rw-r--r--source/blender/imbuf/intern/rectop.c8
-rw-r--r--source/blender/imbuf/intern/scaling.c2
-rw-r--r--source/blender/imbuf/intern/targa.c4
-rw-r--r--source/blender/imbuf/intern/thumbs.c10
-rw-r--r--source/blender/imbuf/intern/thumbs_blend.c2
-rw-r--r--source/blender/imbuf/intern/tiff.c11
-rw-r--r--source/blender/imbuf/intern/util.c13
-rw-r--r--source/blender/makesdna/DNA_action_types.h7
-rw-r--r--source/blender/makesdna/DNA_actuator_types.h32
-rw-r--r--source/blender/makesdna/DNA_anim_types.h210
-rw-r--r--source/blender/makesdna/DNA_armature_types.h192
-rw-r--r--source/blender/makesdna/DNA_boid_types.h26
-rw-r--r--source/blender/makesdna/DNA_camera_types.h2
-rw-r--r--source/blender/makesdna/DNA_cloth_types.h2
-rw-r--r--source/blender/makesdna/DNA_constraint_types.h18
-rw-r--r--source/blender/makesdna/DNA_curve_types.h8
-rw-r--r--source/blender/makesdna/DNA_customdata_types.h10
-rw-r--r--source/blender/makesdna/DNA_defs.h3
-rw-r--r--source/blender/makesdna/DNA_dynamicpaint_types.h2
-rw-r--r--source/blender/makesdna/DNA_genfile.h6
-rw-r--r--source/blender/makesdna/DNA_gpencil_types.h12
-rw-r--r--source/blender/makesdna/DNA_image_types.h1
-rw-r--r--source/blender/makesdna/DNA_ipo_types.h4
-rw-r--r--source/blender/makesdna/DNA_key_types.h2
-rw-r--r--source/blender/makesdna/DNA_lamp_types.h2
-rw-r--r--source/blender/makesdna/DNA_mask_types.h2
-rw-r--r--source/blender/makesdna/DNA_material_types.h17
-rw-r--r--source/blender/makesdna/DNA_mesh_types.h5
-rw-r--r--source/blender/makesdna/DNA_meshdata_types.h8
-rw-r--r--source/blender/makesdna/DNA_meta_types.h2
-rw-r--r--source/blender/makesdna/DNA_modifier_types.h47
-rw-r--r--source/blender/makesdna/DNA_movieclip_types.h56
-rw-r--r--source/blender/makesdna/DNA_nla_types.h2
-rw-r--r--source/blender/makesdna/DNA_node_types.h22
-rw-r--r--source/blender/makesdna/DNA_object_force.h15
-rw-r--r--source/blender/makesdna/DNA_object_types.h20
-rw-r--r--source/blender/makesdna/DNA_packedFile_types.h10
-rw-r--r--source/blender/makesdna/DNA_scene_types.h51
-rw-r--r--source/blender/makesdna/DNA_sdna_types.h2
-rw-r--r--source/blender/makesdna/DNA_smoke_types.h111
-rw-r--r--source/blender/makesdna/DNA_space_types.h12
-rw-r--r--source/blender/makesdna/DNA_texture_types.h13
-rw-r--r--source/blender/makesdna/DNA_tracking_types.h162
-rw-r--r--source/blender/makesdna/DNA_userdef_types.h425
-rw-r--r--source/blender/makesdna/DNA_view2d_types.h2
-rw-r--r--source/blender/makesdna/DNA_view3d_types.h2
-rw-r--r--source/blender/makesdna/DNA_windowmanager_types.h2
-rw-r--r--source/blender/makesdna/DNA_world_types.h6
-rw-r--r--source/blender/makesdna/intern/dna_genfile.c4
-rw-r--r--source/blender/makesdna/intern/makesdna.c42
-rw-r--r--source/blender/makesrna/RNA_access.h11
-rw-r--r--source/blender/makesrna/RNA_enum_types.h1
-rw-r--r--source/blender/makesrna/RNA_types.h2
-rw-r--r--source/blender/makesrna/intern/makesrna.c886
-rw-r--r--source/blender/makesrna/intern/rna_ID.c18
-rw-r--r--source/blender/makesrna/intern/rna_access.c61
-rw-r--r--source/blender/makesrna/intern/rna_action.c113
-rw-r--r--source/blender/makesrna/intern/rna_action_api.c6
-rw-r--r--source/blender/makesrna/intern/rna_actuator.c9
-rw-r--r--source/blender/makesrna/intern/rna_actuator_api.c2
-rw-r--r--source/blender/makesrna/intern/rna_animation.c51
-rw-r--r--source/blender/makesrna/intern/rna_animation_api.c5
-rw-r--r--source/blender/makesrna/intern/rna_armature.c36
-rw-r--r--source/blender/makesrna/intern/rna_armature_api.c6
-rw-r--r--source/blender/makesrna/intern/rna_boid.c2
-rw-r--r--source/blender/makesrna/intern/rna_camera.c2
-rw-r--r--source/blender/makesrna/intern/rna_camera_api.c6
-rw-r--r--source/blender/makesrna/intern/rna_cloth.c12
-rw-r--r--source/blender/makesrna/intern/rna_color.c52
-rw-r--r--source/blender/makesrna/intern/rna_constraint.c9
-rw-r--r--source/blender/makesrna/intern/rna_controller.c4
-rw-r--r--source/blender/makesrna/intern/rna_controller_api.c2
-rw-r--r--source/blender/makesrna/intern/rna_curve.c53
-rw-r--r--source/blender/makesrna/intern/rna_define.c71
-rw-r--r--source/blender/makesrna/intern/rna_fcurve.c26
-rw-r--r--source/blender/makesrna/intern/rna_fcurve_api.c6
-rw-r--r--source/blender/makesrna/intern/rna_fluidsim.c2
-rw-r--r--source/blender/makesrna/intern/rna_gpencil.c349
-rw-r--r--source/blender/makesrna/intern/rna_group.c4
-rw-r--r--source/blender/makesrna/intern/rna_image.c28
-rw-r--r--source/blender/makesrna/intern/rna_image_api.c40
-rw-r--r--source/blender/makesrna/intern/rna_internal.h14
-rw-r--r--source/blender/makesrna/intern/rna_key.c6
-rw-r--r--source/blender/makesrna/intern/rna_lattice.c8
-rw-r--r--source/blender/makesrna/intern/rna_main.c2
-rw-r--r--source/blender/makesrna/intern/rna_main_api.c522
-rw-r--r--source/blender/makesrna/intern/rna_mask.c12
-rw-r--r--source/blender/makesrna/intern/rna_material.c46
-rw-r--r--source/blender/makesrna/intern/rna_material_api.c6
-rw-r--r--source/blender/makesrna/intern/rna_mesh.c48
-rw-r--r--source/blender/makesrna/intern/rna_mesh_api.c6
-rw-r--r--source/blender/makesrna/intern/rna_meta.c16
-rw-r--r--source/blender/makesrna/intern/rna_modifier.c168
-rw-r--r--source/blender/makesrna/intern/rna_movieclip.c11
-rw-r--r--source/blender/makesrna/intern/rna_nla.c28
-rw-r--r--source/blender/makesrna/intern/rna_nodetree.c347
-rw-r--r--source/blender/makesrna/intern/rna_nodetree_types.h7
-rw-r--r--source/blender/makesrna/intern/rna_object.c171
-rw-r--r--source/blender/makesrna/intern/rna_object_api.c60
-rw-r--r--source/blender/makesrna/intern/rna_object_force.c24
-rw-r--r--source/blender/makesrna/intern/rna_particle.c8
-rw-r--r--source/blender/makesrna/intern/rna_pose.c49
-rw-r--r--source/blender/makesrna/intern/rna_pose_api.c6
-rw-r--r--source/blender/makesrna/intern/rna_property.c4
-rw-r--r--source/blender/makesrna/intern/rna_render.c42
-rw-r--r--source/blender/makesrna/intern/rna_rna.c2
-rw-r--r--source/blender/makesrna/intern/rna_scene.c103
-rw-r--r--source/blender/makesrna/intern/rna_scene_api.c46
-rw-r--r--source/blender/makesrna/intern/rna_screen.c4
-rw-r--r--source/blender/makesrna/intern/rna_sculpt_paint.c23
-rw-r--r--source/blender/makesrna/intern/rna_sensor.c2
-rw-r--r--source/blender/makesrna/intern/rna_sensor_api.c2
-rw-r--r--source/blender/makesrna/intern/rna_sequencer.c35
-rw-r--r--source/blender/makesrna/intern/rna_sequencer_api.c74
-rw-r--r--source/blender/makesrna/intern/rna_smoke.c251
-rw-r--r--source/blender/makesrna/intern/rna_space.c85
-rw-r--r--source/blender/makesrna/intern/rna_speaker.c5
-rw-r--r--source/blender/makesrna/intern/rna_text_api.c2
-rw-r--r--source/blender/makesrna/intern/rna_texture.c6
-rw-r--r--source/blender/makesrna/intern/rna_texture_api.c14
-rw-r--r--source/blender/makesrna/intern/rna_tracking.c55
-rw-r--r--source/blender/makesrna/intern/rna_ui.c8
-rw-r--r--source/blender/makesrna/intern/rna_ui_api.c35
-rw-r--r--source/blender/makesrna/intern/rna_userdef.c100
-rw-r--r--source/blender/makesrna/intern/rna_wm.c63
-rw-r--r--source/blender/makesrna/intern/rna_wm_api.c57
-rwxr-xr-xsource/blender/makesrna/rna_cleanup/rna_cleaner.py12
-rw-r--r--source/blender/modifiers/CMakeLists.txt9
-rw-r--r--source/blender/modifiers/MOD_modifiertypes.h3
-rw-r--r--source/blender/modifiers/SConscript5
-rw-r--r--source/blender/modifiers/intern/MOD_armature.c8
-rw-r--r--source/blender/modifiers/intern/MOD_array.c62
-rw-r--r--source/blender/modifiers/intern/MOD_bevel.c82
-rw-r--r--source/blender/modifiers/intern/MOD_boolean.c48
-rw-r--r--source/blender/modifiers/intern/MOD_boolean_util.c4
-rw-r--r--source/blender/modifiers/intern/MOD_boolean_util.h2
-rw-r--r--source/blender/modifiers/intern/MOD_build.c44
-rw-r--r--source/blender/modifiers/intern/MOD_cloth.c4
-rw-r--r--source/blender/modifiers/intern/MOD_curve.c4
-rw-r--r--source/blender/modifiers/intern/MOD_decimate.c217
-rw-r--r--source/blender/modifiers/intern/MOD_dynamicpaint.c8
-rw-r--r--source/blender/modifiers/intern/MOD_edgesplit.c14
-rw-r--r--source/blender/modifiers/intern/MOD_explode.c59
-rw-r--r--source/blender/modifiers/intern/MOD_fluidsim_util.c2
-rw-r--r--source/blender/modifiers/intern/MOD_laplaciansmooth.c703
-rw-r--r--source/blender/modifiers/intern/MOD_lattice.c4
-rw-r--r--source/blender/modifiers/intern/MOD_mask.c6
-rw-r--r--source/blender/modifiers/intern/MOD_meshdeform.c54
-rw-r--r--source/blender/modifiers/intern/MOD_mirror.c3
-rw-r--r--source/blender/modifiers/intern/MOD_multires.c5
-rw-r--r--source/blender/modifiers/intern/MOD_ocean.c22
-rw-r--r--source/blender/modifiers/intern/MOD_particleinstance.c89
-rw-r--r--source/blender/modifiers/intern/MOD_particlesystem.c10
-rw-r--r--source/blender/modifiers/intern/MOD_remesh.c2
-rw-r--r--source/blender/modifiers/intern/MOD_screw.c20
-rw-r--r--source/blender/modifiers/intern/MOD_shapekey.c13
-rw-r--r--source/blender/modifiers/intern/MOD_shrinkwrap.c50
-rw-r--r--source/blender/modifiers/intern/MOD_simpledeform.c36
-rw-r--r--source/blender/modifiers/intern/MOD_skin.c58
-rw-r--r--source/blender/modifiers/intern/MOD_smoke.c59
-rw-r--r--source/blender/modifiers/intern/MOD_smooth.c2
-rw-r--r--source/blender/modifiers/intern/MOD_solidify.c27
-rw-r--r--source/blender/modifiers/intern/MOD_util.c5
-rw-r--r--source/blender/modifiers/intern/MOD_util.h12
-rw-r--r--source/blender/modifiers/intern/MOD_uvproject.c64
-rw-r--r--source/blender/modifiers/intern/MOD_warp.c50
-rw-r--r--source/blender/modifiers/intern/MOD_wave.c2
-rw-r--r--source/blender/modifiers/intern/MOD_weightvgedit.c10
-rw-r--r--source/blender/modifiers/intern/MOD_weightvgmix.c32
-rw-r--r--source/blender/modifiers/intern/MOD_weightvgproximity.c16
-rw-r--r--source/blender/nodes/CMakeLists.txt17
-rw-r--r--source/blender/nodes/NOD_composite.h6
-rw-r--r--source/blender/nodes/NOD_shader.h3
-rw-r--r--source/blender/nodes/composite/node_composite_tree.c12
-rw-r--r--source/blender/nodes/composite/node_composite_util.c142
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_alphaOver.c32
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_bilateralblur.c10
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_bokehimage.c2
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_boxmask.c10
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_brightness.c6
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_channelMatte.c6
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_chromaMatte.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_colorMatte.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_colorSpill.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_colorbalance.c8
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_colorcorrection.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_common.c150
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_composite.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_crop.c6
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_curves.c22
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_defocus.c12
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_despeckle.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_diffMatte.c6
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_dilate.c16
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_directionalblur.c2
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_displace.c8
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_distanceMatte.c10
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_doubleEdgeMask.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_ellipsemask.c10
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_filter.c44
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_flip.c6
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_gamma.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_glare.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_hueSatVal.c14
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_huecorrect.c14
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_idMask.c10
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_image.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_invert.c14
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_lensdist.c8
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_levels.c14
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_lummaMatte.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_mapUV.c6
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_mapValue.c10
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_math.c68
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_mixrgb.c6
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_normal.c8
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_normalize.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_pixelate.c57
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_premulkey.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_rgb.c2
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_rotate.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_sepcombHSVA.c16
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_sepcombRGBA.c10
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_sepcombYCCA.c34
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_sepcombYUVA.c16
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_setalpha.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_splitViewer.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_stabilize2d.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_switch.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_texture.c22
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_tonemap.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_translate.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_valToRgb.c8
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_value.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_viewer.c2
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_zcombine.c50
-rw-r--r--source/blender/nodes/intern/node_common.c195
-rw-r--r--source/blender/nodes/intern/node_common.h12
-rw-r--r--source/blender/nodes/intern/node_exec.c41
-rw-r--r--source/blender/nodes/intern/node_exec.h2
-rw-r--r--source/blender/nodes/intern/node_socket.c22
-rw-r--r--source/blender/nodes/intern/node_util.c17
-rw-r--r--source/blender/nodes/intern/node_util.h2
-rw-r--r--source/blender/nodes/shader/node_shader_tree.c5
-rw-r--r--source/blender/nodes/shader/node_shader_util.c16
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_add_shader.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_attribute.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_background.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_brightness.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bsdf_anisotropic.c18
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bsdf_diffuse.c10
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bsdf_glass.c10
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bsdf_glossy.c11
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bsdf_translucent.c10
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bsdf_transparent.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bsdf_velvet.c10
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bump.c68
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_camera.c6
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_common.c125
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_curves.c8
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_emission.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_fresnel.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_gamma.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_geom.c10
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_geometry.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_holdout.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_hueSatVal.c10
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_invert.c14
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_layer_weight.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_light_falloff.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_light_path.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_mapping.c16
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_material.c26
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_math.c92
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_mixRgb.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_mix_shader.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_normal.c6
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_object_info.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_output.c6
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_output_lamp.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_output_material.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_output_world.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_particle_info.c24
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_rgb.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_script.c85
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_sepcombRGB.c8
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_squeeze.c21
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_brick.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_checker.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_coord.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_environment.c23
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_gradient.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_image.c23
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_magic.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_musgrave.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_noise.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_sky.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_voronoi.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_wave.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_texture.c31
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_valToRgb.c10
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_value.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_vectMath.c56
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_volume_isotropic.c4
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_volume_transparent.c4
-rw-r--r--source/blender/nodes/texture/node_texture_tree.c30
-rw-r--r--source/blender/nodes/texture/node_texture_util.c24
-rw-r--r--source/blender/nodes/texture/node_texture_util.h6
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_at.c4
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_bricks.c6
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_checker.c6
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_common.c125
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_compose.c4
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_coord.c2
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_curves.c6
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_decompose.c4
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_distance.c6
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_hueSatVal.c14
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_image.c2
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_invert.c12
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_math.c18
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_mixRgb.c4
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_output.c6
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_proc.c30
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_rotate.c12
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_scale.c10
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_texture.c4
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_translate.c10
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_valToNor.c14
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_valToRgb.c8
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_viewer.c2
-rw-r--r--source/blender/opencl/CMakeLists.txt1
-rw-r--r--source/blender/opencl/intern/OCL_opencl.c8
-rw-r--r--source/blender/python/BPY_extern.h1
-rw-r--r--source/blender/python/bmesh/bmesh_py_types.c8
-rw-r--r--source/blender/python/bmesh/bmesh_py_types.h2
-rw-r--r--source/blender/python/bmesh/bmesh_py_types_customdata.c4
-rw-r--r--source/blender/python/bmesh/bmesh_py_types_meshdata.c2
-rw-r--r--source/blender/python/bmesh/bmesh_py_types_select.c4
-rw-r--r--source/blender/python/generic/idprop_py_api.c151
-rw-r--r--source/blender/python/generic/idprop_py_api.h11
-rw-r--r--source/blender/python/generic/py_capi_utils.c14
-rw-r--r--source/blender/python/generic/py_capi_utils.h2
-rw-r--r--source/blender/python/intern/CMakeLists.txt4
-rw-r--r--source/blender/python/intern/bpy.c4
-rw-r--r--source/blender/python/intern/bpy_app.c1
-rw-r--r--source/blender/python/intern/bpy_app.h2
-rw-r--r--source/blender/python/intern/bpy_app_ffmpeg.c4
-rw-r--r--source/blender/python/intern/bpy_app_ffmpeg.h2
-rw-r--r--source/blender/python/intern/bpy_app_handlers.c2
-rw-r--r--source/blender/python/intern/bpy_app_handlers.h2
-rw-r--r--source/blender/python/intern/bpy_driver.c2
-rw-r--r--source/blender/python/intern/bpy_driver.h2
-rw-r--r--source/blender/python/intern/bpy_interface.c65
-rw-r--r--source/blender/python/intern/bpy_props.c29
-rw-r--r--source/blender/python/intern/bpy_rna.c150
-rw-r--r--source/blender/python/intern/bpy_rna.h1
-rw-r--r--source/blender/python/intern/bpy_rna_anim.c3
-rw-r--r--source/blender/python/intern/bpy_rna_array.c5
-rw-r--r--source/blender/python/intern/bpy_traceback.h2
-rw-r--r--source/blender/python/intern/bpy_util.c23
-rw-r--r--source/blender/python/intern/gpu.h2
-rw-r--r--source/blender/python/mathutils/mathutils.c4
-rw-r--r--source/blender/python/mathutils/mathutils_Color.c144
-rw-r--r--source/blender/python/mathutils/mathutils_Color.h4
-rw-r--r--source/blender/python/mathutils/mathutils_Euler.c142
-rw-r--r--source/blender/python/mathutils/mathutils_Euler.h2
-rw-r--r--source/blender/python/mathutils/mathutils_Matrix.c177
-rw-r--r--source/blender/python/mathutils/mathutils_Quaternion.c162
-rw-r--r--source/blender/python/mathutils/mathutils_Quaternion.h2
-rw-r--r--source/blender/python/mathutils/mathutils_Vector.c18
-rw-r--r--source/blender/python/mathutils/mathutils_geometry.c10
-rw-r--r--source/blender/python/mathutils/mathutils_noise.c1
-rw-r--r--source/blender/python/mathutils/mathutils_noise.h2
-rw-r--r--source/blender/python/rna_dump.py4
-rw-r--r--source/blender/quicktime/apple/qtkit_export.m56
-rw-r--r--source/blender/quicktime/apple/qtkit_import.m71
-rw-r--r--source/blender/quicktime/apple/quicktime_export.c60
-rw-r--r--source/blender/quicktime/quicktime_export.h4
-rw-r--r--source/blender/quicktime/quicktime_import.h34
-rw-r--r--source/blender/render/extern/include/RE_engine.h7
-rw-r--r--source/blender/render/extern/include/RE_pipeline.h7
-rw-r--r--source/blender/render/extern/include/RE_render_ext.h7
-rw-r--r--source/blender/render/extern/include/RE_shader_ext.h11
-rw-r--r--source/blender/render/intern/include/envmap.h2
-rw-r--r--source/blender/render/intern/include/pointdensity.h2
-rw-r--r--source/blender/render/intern/include/rayobject.h2
-rw-r--r--source/blender/render/intern/include/render_result.h2
-rw-r--r--source/blender/render/intern/include/render_types.h7
-rw-r--r--source/blender/render/intern/include/rendercore.h5
-rw-r--r--source/blender/render/intern/include/renderdatabase.h4
-rw-r--r--source/blender/render/intern/include/shadbuf.h18
-rw-r--r--source/blender/render/intern/include/shading.h2
-rw-r--r--source/blender/render/intern/include/sunsky.h5
-rw-r--r--source/blender/render/intern/include/texture.h2
-rw-r--r--source/blender/render/intern/include/texture_ocean.h7
-rw-r--r--source/blender/render/intern/include/volume_precache.h4
-rw-r--r--source/blender/render/intern/raytrace/bvh.h2
-rw-r--r--source/blender/render/intern/raytrace/rayobject.cpp2
-rw-r--r--source/blender/render/intern/raytrace/rayobject_blibvh.cpp4
-rw-r--r--source/blender/render/intern/raytrace/rayobject_instance.cpp2
-rw-r--r--source/blender/render/intern/raytrace/rayobject_internal.h9
-rw-r--r--source/blender/render/intern/raytrace/rayobject_octree.cpp8
-rw-r--r--source/blender/render/intern/raytrace/rayobject_qbvh.cpp2
-rw-r--r--source/blender/render/intern/raytrace/rayobject_raycounter.cpp4
-rw-r--r--source/blender/render/intern/raytrace/rayobject_rtbuild.cpp46
-rw-r--r--source/blender/render/intern/raytrace/rayobject_rtbuild.h13
-rw-r--r--source/blender/render/intern/raytrace/rayobject_vbvh.cpp8
-rw-r--r--source/blender/render/intern/raytrace/reorganize.h20
-rw-r--r--source/blender/render/intern/raytrace/svbvh.h36
-rw-r--r--source/blender/render/intern/raytrace/vbvh.h2
-rw-r--r--source/blender/render/intern/source/convertblender.c256
-rw-r--r--source/blender/render/intern/source/envmap.c40
-rw-r--r--source/blender/render/intern/source/external_engine.c23
-rw-r--r--source/blender/render/intern/source/gammaCorrectionTables.c10
-rw-r--r--source/blender/render/intern/source/imagetexture.c149
-rw-r--r--source/blender/render/intern/source/initrender.c31
-rw-r--r--source/blender/render/intern/source/occlusion.c24
-rw-r--r--source/blender/render/intern/source/pipeline.c133
-rw-r--r--source/blender/render/intern/source/pixelshading.c4
-rw-r--r--source/blender/render/intern/source/pointdensity.c13
-rw-r--r--source/blender/render/intern/source/rayshade.c28
-rw-r--r--source/blender/render/intern/source/render_result.c20
-rw-r--r--source/blender/render/intern/source/render_texture.c399
-rw-r--r--source/blender/render/intern/source/rendercore.c148
-rw-r--r--source/blender/render/intern/source/renderdatabase.c77
-rw-r--r--source/blender/render/intern/source/shadbuf.c57
-rw-r--r--source/blender/render/intern/source/shadeinput.c221
-rw-r--r--source/blender/render/intern/source/shadeoutput.c85
-rw-r--r--source/blender/render/intern/source/sss.c10
-rw-r--r--source/blender/render/intern/source/strand.c14
-rw-r--r--source/blender/render/intern/source/sunsky.c11
-rw-r--r--source/blender/render/intern/source/texture_ocean.c2
-rw-r--r--source/blender/render/intern/source/volume_precache.c10
-rw-r--r--source/blender/render/intern/source/volumetric.c6
-rw-r--r--source/blender/render/intern/source/voxeldata.c171
-rw-r--r--source/blender/render/intern/source/zbuf.c56
-rw-r--r--source/blender/windowmanager/CMakeLists.txt2
-rw-r--r--source/blender/windowmanager/WM_api.h27
-rw-r--r--source/blender/windowmanager/WM_keymap.h6
-rw-r--r--source/blender/windowmanager/WM_types.h40
-rw-r--r--source/blender/windowmanager/intern/wm.c2
-rw-r--r--source/blender/windowmanager/intern/wm_cursors.c23
-rw-r--r--source/blender/windowmanager/intern/wm_dragdrop.c2
-rw-r--r--source/blender/windowmanager/intern/wm_event_system.c476
-rw-r--r--source/blender/windowmanager/intern/wm_files.c31
-rw-r--r--source/blender/windowmanager/intern/wm_gesture.c4
-rw-r--r--source/blender/windowmanager/intern/wm_init_exit.c26
-rw-r--r--source/blender/windowmanager/intern/wm_jobs.c25
-rw-r--r--source/blender/windowmanager/intern/wm_keymap.c75
-rw-r--r--source/blender/windowmanager/intern/wm_operators.c149
-rw-r--r--source/blender/windowmanager/intern/wm_playanim.c71
-rw-r--r--source/blender/windowmanager/intern/wm_subwindow.c20
-rw-r--r--source/blender/windowmanager/intern/wm_window.c30
-rw-r--r--source/blender/windowmanager/wm_event_system.h70
-rw-r--r--source/blender/windowmanager/wm_event_types.h3
-rw-r--r--source/blenderplayer/CMakeLists.txt5
-rw-r--r--source/blenderplayer/bad_level_call_stubs/stubs.c12
-rw-r--r--source/creator/CMakeLists.txt14
-rw-r--r--source/creator/creator.c1
-rw-r--r--source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp72
-rw-r--r--source/gameengine/BlenderRoutines/CMakeLists.txt4
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp36
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderCanvas.h10
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderGL.cpp4
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderGL.h7
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h11
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp6
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h3
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp7
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h3
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp35
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h47
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp6
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderSystem.h3
-rw-r--r--source/gameengine/CMakeLists.txt2
-rw-r--r--source/gameengine/Converter/BL_ActionActuator.cpp43
-rw-r--r--source/gameengine/Converter/BL_ActionActuator.h2
-rw-r--r--source/gameengine/Converter/BL_ArmatureActuator.cpp12
-rw-r--r--source/gameengine/Converter/BL_ArmatureActuator.h24
-rw-r--r--source/gameengine/Converter/BL_ArmatureChannel.cpp24
-rw-r--r--source/gameengine/Converter/BL_ArmatureChannel.h12
-rw-r--r--source/gameengine/Converter/BL_ArmatureConstraint.cpp16
-rw-r--r--source/gameengine/Converter/BL_ArmatureConstraint.h9
-rw-r--r--source/gameengine/Converter/BL_ArmatureObject.cpp21
-rw-r--r--source/gameengine/Converter/BL_ArmatureObject.h10
-rw-r--r--source/gameengine/Converter/BL_BlenderDataConversion.cpp180
-rw-r--r--source/gameengine/Converter/BL_BlenderDataConversion.h3
-rw-r--r--source/gameengine/Converter/BL_DeformableGameObject.h11
-rw-r--r--source/gameengine/Converter/BL_MeshDeformer.cpp41
-rw-r--r--source/gameengine/Converter/BL_MeshDeformer.h8
-rw-r--r--source/gameengine/Converter/BL_ModifierDeformer.cpp13
-rw-r--r--source/gameengine/Converter/BL_ModifierDeformer.h52
-rw-r--r--source/gameengine/Converter/BL_ShapeActionActuator.cpp8
-rw-r--r--source/gameengine/Converter/BL_ShapeActionActuator.h5
-rw-r--r--source/gameengine/Converter/BL_ShapeDeformer.cpp11
-rw-r--r--source/gameengine/Converter/BL_ShapeDeformer.h8
-rw-r--r--source/gameengine/Converter/BL_SkinDeformer.cpp23
-rw-r--r--source/gameengine/Converter/BL_SkinDeformer.h27
-rw-r--r--source/gameengine/Converter/BlenderWorldInfo.cpp6
-rw-r--r--source/gameengine/Converter/BlenderWorldInfo.h13
-rw-r--r--source/gameengine/Converter/CMakeLists.txt8
-rw-r--r--source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp4
-rw-r--r--source/gameengine/Converter/KX_BlenderScalarInterpolator.h5
-rw-r--r--source/gameengine/Converter/KX_BlenderSceneConverter.cpp57
-rw-r--r--source/gameengine/Converter/KX_BlenderSceneConverter.h13
-rw-r--r--source/gameengine/Converter/KX_ConvertActuators.cpp379
-rw-r--r--source/gameengine/Converter/KX_ConvertActuators.h22
-rw-r--r--source/gameengine/Converter/KX_ConvertControllers.cpp5
-rw-r--r--source/gameengine/Converter/KX_ConvertControllers.h4
-rw-r--r--source/gameengine/Converter/KX_ConvertProperties.cpp13
-rw-r--r--source/gameengine/Converter/KX_ConvertProperties.h3
-rw-r--r--source/gameengine/Converter/KX_ConvertSensors.cpp37
-rw-r--r--source/gameengine/Converter/KX_ConvertSensors.h3
-rw-r--r--source/gameengine/Converter/KX_IpoConvert.cpp17
-rw-r--r--source/gameengine/Converter/KX_IpoConvert.h3
-rw-r--r--source/gameengine/Converter/KX_SoftBodyDeformer.cpp4
-rw-r--r--source/gameengine/Converter/KX_SoftBodyDeformer.h6
-rw-r--r--source/gameengine/Expressions/BoolValue.cpp37
-rw-r--r--source/gameengine/Expressions/BoolValue.h5
-rw-r--r--source/gameengine/Expressions/ConstExpr.h3
-rw-r--r--source/gameengine/Expressions/EXP_C-Api.cpp4
-rw-r--r--source/gameengine/Expressions/EXP_C-Api.h5
-rw-r--r--source/gameengine/Expressions/EmptyValue.h3
-rw-r--r--source/gameengine/Expressions/ErrorValue.h3
-rw-r--r--source/gameengine/Expressions/Expression.h3
-rw-r--r--source/gameengine/Expressions/FloatValue.cpp238
-rw-r--r--source/gameengine/Expressions/FloatValue.h3
-rw-r--r--source/gameengine/Expressions/IdentifierExpr.h3
-rw-r--r--source/gameengine/Expressions/IfExpr.h11
-rw-r--r--source/gameengine/Expressions/InputParser.cpp180
-rw-r--r--source/gameengine/Expressions/IntValue.cpp273
-rw-r--r--source/gameengine/Expressions/IntValue.h3
-rw-r--r--source/gameengine/Expressions/KX_HashedPtr.h5
-rw-r--r--source/gameengine/Expressions/KX_Python.h3
-rw-r--r--source/gameengine/Expressions/ListValue.cpp128
-rw-r--r--source/gameengine/Expressions/ListValue.h4
-rw-r--r--source/gameengine/Expressions/Operator1Expr.h7
-rw-r--r--source/gameengine/Expressions/Operator2Expr.cpp6
-rw-r--r--source/gameengine/Expressions/Operator2Expr.h2
-rw-r--r--source/gameengine/Expressions/PyObjectPlus.cpp23
-rw-r--r--source/gameengine/Expressions/PyObjectPlus.h52
-rw-r--r--source/gameengine/Expressions/StringValue.cpp51
-rw-r--r--source/gameengine/Expressions/StringValue.h7
-rw-r--r--source/gameengine/Expressions/Value.cpp12
-rw-r--r--source/gameengine/Expressions/Value.h47
-rw-r--r--source/gameengine/Expressions/VectorValue.cpp55
-rw-r--r--source/gameengine/Expressions/VectorValue.h3
-rw-r--r--source/gameengine/Expressions/VoidValue.h1
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp56
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_Joystick.h2
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp46
-rw-r--r--source/gameengine/GameLogic/SCA_ANDController.h3
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorEventManager.h3
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorSensor.h4
-rw-r--r--source/gameengine/GameLogic/SCA_AlwaysEventManager.h3
-rw-r--r--source/gameengine/GameLogic/SCA_AlwaysSensor.cpp9
-rw-r--r--source/gameengine/GameLogic/SCA_AlwaysSensor.h3
-rw-r--r--source/gameengine/GameLogic/SCA_BasicEventManager.h3
-rw-r--r--source/gameengine/GameLogic/SCA_DelaySensor.cpp9
-rw-r--r--source/gameengine/GameLogic/SCA_DelaySensor.h3
-rw-r--r--source/gameengine/GameLogic/SCA_ExpressionController.h3
-rw-r--r--source/gameengine/GameLogic/SCA_IActuator.h3
-rw-r--r--source/gameengine/GameLogic/SCA_IController.cpp12
-rw-r--r--source/gameengine/GameLogic/SCA_IController.h5
-rw-r--r--source/gameengine/GameLogic/SCA_IInputDevice.cpp4
-rw-r--r--source/gameengine/GameLogic/SCA_IInputDevice.h32
-rw-r--r--source/gameengine/GameLogic/SCA_ILogicBrick.cpp8
-rw-r--r--source/gameengine/GameLogic/SCA_ILogicBrick.h7
-rw-r--r--source/gameengine/GameLogic/SCA_IObject.cpp2
-rw-r--r--source/gameengine/GameLogic/SCA_IObject.h7
-rw-r--r--source/gameengine/GameLogic/SCA_IScene.h3
-rw-r--r--source/gameengine/GameLogic/SCA_ISensor.cpp26
-rw-r--r--source/gameengine/GameLogic/SCA_ISensor.h5
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickSensor.cpp105
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickSensor.h10
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardManager.h5
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardSensor.cpp77
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardSensor.h7
-rw-r--r--source/gameengine/GameLogic/SCA_LogicManager.h7
-rw-r--r--source/gameengine/GameLogic/SCA_MouseManager.cpp8
-rw-r--r--source/gameengine/GameLogic/SCA_MouseManager.h5
-rw-r--r--source/gameengine/GameLogic/SCA_MouseSensor.cpp10
-rw-r--r--source/gameengine/GameLogic/SCA_MouseSensor.h3
-rw-r--r--source/gameengine/GameLogic/SCA_NANDController.h3
-rw-r--r--source/gameengine/GameLogic/SCA_NORController.h3
-rw-r--r--source/gameengine/GameLogic/SCA_ORController.h3
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyActuator.cpp2
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyActuator.h3
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyEventManager.h3
-rw-r--r--source/gameengine/GameLogic/SCA_PythonController.cpp129
-rw-r--r--source/gameengine/GameLogic/SCA_PythonController.h15
-rw-r--r--source/gameengine/GameLogic/SCA_PythonKeyboard.cpp8
-rw-r--r--source/gameengine/GameLogic/SCA_PythonKeyboard.h5
-rw-r--r--source/gameengine/GameLogic/SCA_PythonMouse.cpp12
-rw-r--r--source/gameengine/GameLogic/SCA_PythonMouse.h17
-rw-r--r--source/gameengine/GameLogic/SCA_RandomActuator.cpp77
-rw-r--r--source/gameengine/GameLogic/SCA_RandomActuator.h8
-rw-r--r--source/gameengine/GameLogic/SCA_RandomEventManager.h3
-rw-r--r--source/gameengine/GameLogic/SCA_RandomSensor.cpp6
-rw-r--r--source/gameengine/GameLogic/SCA_RandomSensor.h3
-rw-r--r--source/gameengine/GameLogic/SCA_TimeEventManager.cpp11
-rw-r--r--source/gameengine/GameLogic/SCA_TimeEventManager.h3
-rw-r--r--source/gameengine/GameLogic/SCA_XNORController.h3
-rw-r--r--source/gameengine/GameLogic/SCA_XORController.h3
-rw-r--r--source/gameengine/GamePlayer/CMakeLists.txt2
-rw-r--r--source/gameengine/GamePlayer/common/GPC_Canvas.cpp24
-rw-r--r--source/gameengine/GamePlayer/common/GPC_Canvas.h12
-rw-r--r--source/gameengine/GamePlayer/common/GPC_Engine.h3
-rw-r--r--source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h7
-rw-r--r--source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp6
-rw-r--r--source/gameengine/GamePlayer/common/GPC_MouseDevice.h7
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RawImage.cpp2
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RawImage.h3
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RawLoadDotBlendArray.cpp3
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RawLoadDotBlendArray.h3
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RawLogoArrays.cpp6
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RawLogoArrays.h3
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RenderTools.cpp35
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RenderTools.h7
-rw-r--r--source/gameengine/GamePlayer/common/GPC_System.h3
-rw-r--r--source/gameengine/GamePlayer/common/bmfont.cpp4
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_Application.cpp10
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_Canvas.h7
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp40
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h7
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_System.h5
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_ghost.cpp25
-rw-r--r--source/gameengine/Ketsji/BL_Action.cpp44
-rw-r--r--source/gameengine/Ketsji/BL_Action.h3
-rw-r--r--source/gameengine/Ketsji/BL_ActionManager.h3
-rw-r--r--source/gameengine/Ketsji/BL_BlenderShader.cpp6
-rw-r--r--source/gameengine/Ketsji/BL_BlenderShader.h2
-rw-r--r--source/gameengine/Ketsji/BL_Shader.cpp110
-rw-r--r--source/gameengine/Ketsji/BL_Shader.h4
-rw-r--r--source/gameengine/Ketsji/BL_Texture.cpp16
-rw-r--r--source/gameengine/Ketsji/BL_Texture.h2
-rw-r--r--source/gameengine/Ketsji/CMakeLists.txt6
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h3
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h3
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp6
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h7
-rw-r--r--source/gameengine/Ketsji/KX_ArmatureSensor.cpp6
-rw-r--r--source/gameengine/Ketsji/KX_ArmatureSensor.h4
-rw-r--r--source/gameengine/Ketsji/KX_BlenderMaterial.cpp36
-rw-r--r--source/gameengine/Ketsji/KX_BlenderMaterial.h10
-rw-r--r--source/gameengine/Ketsji/KX_BulletPhysicsController.cpp2
-rw-r--r--source/gameengine/Ketsji/KX_BulletPhysicsController.h3
-rw-r--r--source/gameengine/Ketsji/KX_Camera.cpp106
-rw-r--r--source/gameengine/Ketsji/KX_Camera.h13
-rw-r--r--source/gameengine/Ketsji/KX_CameraActuator.cpp46
-rw-r--r--source/gameengine/Ketsji/KX_CameraActuator.h5
-rw-r--r--source/gameengine/Ketsji/KX_CameraIpoSGController.h9
-rw-r--r--source/gameengine/Ketsji/KX_CharacterWrapper.cpp94
-rw-r--r--source/gameengine/Ketsji/KX_CharacterWrapper.h35
-rw-r--r--source/gameengine/Ketsji/KX_ClientObjectInfo.h3
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintActuator.cpp6
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintActuator.h5
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintWrapper.cpp10
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintWrapper.h5
-rw-r--r--source/gameengine/Ketsji/KX_ConvertPhysicsObject.h2
-rw-r--r--source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp9
-rw-r--r--source/gameengine/Ketsji/KX_Dome.cpp67
-rw-r--r--source/gameengine/Ketsji/KX_Dome.h2
-rw-r--r--source/gameengine/Ketsji/KX_EmptyObject.h3
-rw-r--r--source/gameengine/Ketsji/KX_FontObject.cpp16
-rw-r--r--source/gameengine/Ketsji/KX_FontObject.h2
-rw-r--r--source/gameengine/Ketsji/KX_GameObject.cpp415
-rw-r--r--source/gameengine/Ketsji/KX_GameObject.h137
-rw-r--r--source/gameengine/Ketsji/KX_IInterpolator.h2
-rw-r--r--source/gameengine/Ketsji/KX_IPOTransform.h4
-rw-r--r--source/gameengine/Ketsji/KX_IPO_SGController.cpp10
-rw-r--r--source/gameengine/Ketsji/KX_IPO_SGController.h4
-rw-r--r--source/gameengine/Ketsji/KX_IPhysicsController.h3
-rw-r--r--source/gameengine/Ketsji/KX_IScalarInterpolator.h2
-rw-r--r--source/gameengine/Ketsji/KX_ISceneConverter.h3
-rw-r--r--source/gameengine/Ketsji/KX_IpoActuator.cpp18
-rw-r--r--source/gameengine/Ketsji/KX_IpoActuator.h3
-rw-r--r--source/gameengine/Ketsji/KX_KetsjiEngine.cpp155
-rw-r--r--source/gameengine/Ketsji/KX_KetsjiEngine.h12
-rw-r--r--source/gameengine/Ketsji/KX_Light.cpp54
-rw-r--r--source/gameengine/Ketsji/KX_Light.h7
-rw-r--r--source/gameengine/Ketsji/KX_LightIpoSGController.h9
-rw-r--r--source/gameengine/Ketsji/KX_MaterialIpoController.h5
-rw-r--r--source/gameengine/Ketsji/KX_MeshProxy.cpp28
-rw-r--r--source/gameengine/Ketsji/KX_MeshProxy.h11
-rw-r--r--source/gameengine/Ketsji/KX_MotionState.h3
-rw-r--r--source/gameengine/Ketsji/KX_MouseFocusSensor.cpp60
-rw-r--r--source/gameengine/Ketsji/KX_MouseFocusSensor.h17
-rw-r--r--source/gameengine/Ketsji/KX_NavMeshObject.cpp22
-rw-r--r--source/gameengine/Ketsji/KX_NavMeshObject.h5
-rw-r--r--source/gameengine/Ketsji/KX_NearSensor.h5
-rw-r--r--source/gameengine/Ketsji/KX_ObColorIpoSGController.h3
-rw-r--r--source/gameengine/Ketsji/KX_ObjectActuator.cpp53
-rw-r--r--source/gameengine/Ketsji/KX_ObjectActuator.h5
-rw-r--r--source/gameengine/Ketsji/KX_ObstacleSimulation.cpp14
-rw-r--r--source/gameengine/Ketsji/KX_ObstacleSimulation.h8
-rw-r--r--source/gameengine/Ketsji/KX_ParentActuator.cpp6
-rw-r--r--source/gameengine/Ketsji/KX_ParentActuator.h7
-rw-r--r--source/gameengine/Ketsji/KX_PhysicsEngineEnums.h3
-rw-r--r--source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp8
-rw-r--r--source/gameengine/Ketsji/KX_PhysicsObjectWrapper.h5
-rw-r--r--source/gameengine/Ketsji/KX_PhysicsPropertiesobsolete.h3
-rw-r--r--source/gameengine/Ketsji/KX_PolyProxy.cpp42
-rw-r--r--source/gameengine/Ketsji/KX_PolyProxy.h25
-rw-r--r--source/gameengine/Ketsji/KX_PolygonMaterial.cpp34
-rw-r--r--source/gameengine/Ketsji/KX_PolygonMaterial.h9
-rw-r--r--source/gameengine/Ketsji/KX_PyConstraintBinding.cpp167
-rw-r--r--source/gameengine/Ketsji/KX_PyConstraintBinding.h5
-rw-r--r--source/gameengine/Ketsji/KX_PyMath.cpp34
-rw-r--r--source/gameengine/Ketsji/KX_PyMath.h22
-rw-r--r--source/gameengine/Ketsji/KX_PythonInit.cpp403
-rw-r--r--source/gameengine/Ketsji/KX_PythonInit.h17
-rw-r--r--source/gameengine/Ketsji/KX_PythonInitTypes.cpp14
-rw-r--r--source/gameengine/Ketsji/KX_PythonInitTypes.h6
-rw-r--r--source/gameengine/Ketsji/KX_PythonMain.cpp12
-rw-r--r--source/gameengine/Ketsji/KX_PythonMain.h11
-rw-r--r--source/gameengine/Ketsji/KX_PythonSeq.cpp56
-rw-r--r--source/gameengine/Ketsji/KX_PythonSeq.h8
-rw-r--r--source/gameengine/Ketsji/KX_RadarSensor.cpp4
-rw-r--r--source/gameengine/Ketsji/KX_RadarSensor.h3
-rw-r--r--source/gameengine/Ketsji/KX_RayCast.cpp6
-rw-r--r--source/gameengine/Ketsji/KX_RayEventManager.h3
-rw-r--r--source/gameengine/Ketsji/KX_RaySensor.cpp2
-rw-r--r--source/gameengine/Ketsji/KX_RaySensor.h7
-rw-r--r--source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp12
-rw-r--r--source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h13
-rw-r--r--source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp6
-rw-r--r--source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp2
-rw-r--r--source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h7
-rw-r--r--source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp6
-rw-r--r--source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h2
-rw-r--r--source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp16
-rw-r--r--source/gameengine/Ketsji/KX_SG_NodeRelationships.h12
-rw-r--r--source/gameengine/Ketsji/KX_Scene.cpp162
-rw-r--r--source/gameengine/Ketsji/KX_Scene.h43
-rw-r--r--source/gameengine/Ketsji/KX_SceneActuator.cpp4
-rw-r--r--source/gameengine/Ketsji/KX_SceneActuator.h5
-rw-r--r--source/gameengine/Ketsji/KX_SoundActuator.cpp37
-rw-r--r--source/gameengine/Ketsji/KX_SoundActuator.h17
-rw-r--r--source/gameengine/Ketsji/KX_SteeringActuator.cpp32
-rw-r--r--source/gameengine/Ketsji/KX_SteeringActuator.h17
-rw-r--r--source/gameengine/Ketsji/KX_TimeCategoryLogger.h7
-rw-r--r--source/gameengine/Ketsji/KX_TimeLogger.h9
-rw-r--r--source/gameengine/Ketsji/KX_TouchEventManager.h3
-rw-r--r--source/gameengine/Ketsji/KX_TouchSensor.cpp8
-rw-r--r--source/gameengine/Ketsji/KX_TouchSensor.h5
-rw-r--r--source/gameengine/Ketsji/KX_TrackToActuator.cpp20
-rw-r--r--source/gameengine/Ketsji/KX_TrackToActuator.h9
-rw-r--r--source/gameengine/Ketsji/KX_VehicleWrapper.cpp34
-rw-r--r--source/gameengine/Ketsji/KX_VehicleWrapper.h4
-rw-r--r--source/gameengine/Ketsji/KX_VertexProxy.cpp112
-rw-r--r--source/gameengine/Ketsji/KX_VertexProxy.h35
-rw-r--r--source/gameengine/Ketsji/KX_WorldInfo.h3
-rw-r--r--source/gameengine/Ketsji/KX_WorldIpoController.h9
-rw-r--r--source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h5
-rw-r--r--source/gameengine/Network/NG_NetworkDeviceInterface.h3
-rw-r--r--source/gameengine/Network/NG_NetworkMessage.h3
-rw-r--r--source/gameengine/Network/NG_NetworkObject.h3
-rw-r--r--source/gameengine/Network/NG_NetworkScene.h7
-rw-r--r--source/gameengine/Physics/Bullet/CMakeLists.txt2
-rw-r--r--source/gameengine/Physics/Bullet/CcdGraphicController.h4
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsController.cpp160
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsController.h6
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp202
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h13
-rw-r--r--source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h11
-rw-r--r--source/gameengine/Physics/common/CMakeLists.txt1
-rw-r--r--source/gameengine/Physics/common/PHY_DynamicTypes.h14
-rw-r--r--source/gameengine/Physics/common/PHY_ICharacter.h30
-rw-r--r--source/gameengine/Physics/common/PHY_IController.h5
-rw-r--r--source/gameengine/Physics/common/PHY_IGraphicController.h3
-rw-r--r--source/gameengine/Physics/common/PHY_IMotionState.h5
-rw-r--r--source/gameengine/Physics/common/PHY_IPhysicsController.h3
-rw-r--r--source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h11
-rw-r--r--source/gameengine/Physics/common/PHY_IVehicle.h2
-rw-r--r--source/gameengine/Physics/common/PHY_Pro.h3
-rw-r--r--source/gameengine/Rasterizer/RAS_2DFilterManager.cpp10
-rw-r--r--source/gameengine/Rasterizer/RAS_BucketManager.cpp21
-rw-r--r--source/gameengine/Rasterizer/RAS_BucketManager.h4
-rw-r--r--source/gameengine/Rasterizer/RAS_CameraData.h3
-rw-r--r--source/gameengine/Rasterizer/RAS_Deformer.h8
-rw-r--r--source/gameengine/Rasterizer/RAS_FramingManager.cpp14
-rw-r--r--source/gameengine/Rasterizer/RAS_FramingManager.h8
-rw-r--r--source/gameengine/Rasterizer/RAS_ICanvas.h10
-rw-r--r--source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp16
-rw-r--r--source/gameengine/Rasterizer/RAS_IPolygonMaterial.h3
-rw-r--r--source/gameengine/Rasterizer/RAS_IRasterizer.h10
-rw-r--r--source/gameengine/Rasterizer/RAS_IRenderTools.h35
-rw-r--r--source/gameengine/Rasterizer/RAS_LightObject.h3
-rw-r--r--source/gameengine/Rasterizer/RAS_MaterialBucket.cpp24
-rw-r--r--source/gameengine/Rasterizer/RAS_MaterialBucket.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_MeshObject.cpp6
-rw-r--r--source/gameengine/Rasterizer/RAS_MeshObject.h9
-rw-r--r--source/gameengine/Rasterizer/RAS_ObjectColor.h3
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp4
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp110
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h10
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp10
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h3
-rw-r--r--source/gameengine/Rasterizer/RAS_Polygon.cpp7
-rw-r--r--source/gameengine/Rasterizer/RAS_Rect.h3
-rw-r--r--source/gameengine/Rasterizer/RAS_TexMatrix.h3
-rw-r--r--source/gameengine/Rasterizer/RAS_TexVert.cpp2
-rw-r--r--source/gameengine/Rasterizer/RAS_TexVert.h3
-rw-r--r--source/gameengine/Rasterizer/RAS_texmatrix.cpp4
-rw-r--r--source/gameengine/SceneGraph/SG_Controller.h11
-rw-r--r--source/gameengine/SceneGraph/SG_DList.h3
-rw-r--r--source/gameengine/SceneGraph/SG_IObject.cpp2
-rw-r--r--source/gameengine/SceneGraph/SG_IObject.h11
-rw-r--r--source/gameengine/SceneGraph/SG_Node.cpp2
-rw-r--r--source/gameengine/SceneGraph/SG_Node.h21
-rw-r--r--source/gameengine/SceneGraph/SG_ParentRelation.h2
-rw-r--r--source/gameengine/SceneGraph/SG_QList.h3
-rw-r--r--source/gameengine/SceneGraph/SG_Spatial.cpp6
-rw-r--r--source/gameengine/SceneGraph/SG_Spatial.h15
-rw-r--r--source/gameengine/SceneGraph/SG_Tree.cpp2
-rw-r--r--source/gameengine/VideoTexture/BlendType.h13
-rw-r--r--source/gameengine/VideoTexture/FilterBase.cpp10
-rw-r--r--source/gameengine/VideoTexture/FilterBase.h16
-rw-r--r--source/gameengine/VideoTexture/FilterBlueScreen.cpp10
-rw-r--r--source/gameengine/VideoTexture/FilterColor.cpp12
-rw-r--r--source/gameengine/VideoTexture/FilterNormal.cpp10
-rw-r--r--source/gameengine/VideoTexture/FilterSource.h60
-rw-r--r--source/gameengine/VideoTexture/ImageBase.cpp108
-rw-r--r--source/gameengine/VideoTexture/ImageBase.h58
-rw-r--r--source/gameengine/VideoTexture/ImageBuff.cpp16
-rw-r--r--source/gameengine/VideoTexture/ImageMix.cpp6
-rw-r--r--source/gameengine/VideoTexture/ImageRender.cpp30
-rw-r--r--source/gameengine/VideoTexture/ImageViewport.cpp86
-rw-r--r--source/gameengine/VideoTexture/ImageViewport.h12
-rw-r--r--source/gameengine/VideoTexture/PyTypeList.cpp8
-rw-r--r--source/gameengine/VideoTexture/PyTypeList.h14
-rw-r--r--source/gameengine/VideoTexture/Texture.cpp36
-rw-r--r--source/gameengine/VideoTexture/Texture.h8
-rw-r--r--source/gameengine/VideoTexture/VideoBase.cpp29
-rw-r--r--source/gameengine/VideoTexture/VideoBase.h28
-rw-r--r--source/gameengine/VideoTexture/VideoFFmpeg.cpp30
-rw-r--r--source/gameengine/VideoTexture/VideoFFmpeg.h6
-rw-r--r--source/gameengine/VideoTexture/blendVideoTex.cpp20
-rw-r--r--source/tests/CMakeLists.txt8
-rw-r--r--source/tests/batch_import.py12
-rw-r--r--source/tests/bl_load_addons.py2
-rw-r--r--source/tests/bl_load_py_modules.py2
-rw-r--r--source/tests/bl_mesh_modifiers.py2
-rw-r--r--source/tests/bl_rna_wiki_reference.py50
-rw-r--r--source/tests/bl_run_operators.py108
-rw-r--r--source/tests/bl_test.py2
-rw-r--r--source/tests/rna_array.py12
2478 files changed, 80673 insertions, 56644 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 83e094b4375..b53c6f6b71f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -120,7 +120,7 @@ option(WITH_INTERNATIONAL "Enable I18N (International fonts and text)" ON)
option(WITH_PYTHON "Enable Embedded Python API (only disable for development)" ON)
option(WITH_PYTHON_SECURITY "Disables execution of scripts within blend files by default (recommend to leave off)" OFF)
mark_as_advanced(WITH_PYTHON) # dont want people disabling this unless they really know what they are doing.
-mark_as_advanced(WITH_PYTHON_SECURITY) # some distrobutions see this as a security issue, rather than have them patch it, make a build option.
+mark_as_advanced(WITH_PYTHON_SECURITY) # some distributions see this as a security issue, rather than have them patch it, make a build option.
option(WITH_PYTHON_SAFETY "Enable internal API error checking to track invalid data to prevent crash on access (at the expense of some effeciency, only enable for development)." OFF)
option(WITH_PYTHON_MODULE "Enable building as a python module which runs without a user interface, like running regular blender in background mode (experimental, only enable for development)" OFF)
@@ -186,12 +186,11 @@ unset(PLATFORM_DEFAULT)
# Modifiers
-option(WITH_MOD_FLUID "Enable Elbeem Modifier (Fluid Simulation)" ON)
-option(WITH_MOD_SMOKE "Enable Smoke Modifier (Smoke Simulation)" ON)
-option(WITH_MOD_DECIMATE "Enable Decimate Modifier" ON)
-option(WITH_MOD_BOOLEAN "Enable Boolean Modifier" ON)
-option(WITH_MOD_REMESH "Enable Remesh Modifier" ON)
-option(WITH_MOD_CLOTH_ELTOPO "Enable Experimental cloth solver" OFF)
+option(WITH_MOD_FLUID "Enable Elbeem Modifier (Fluid Simulation)" ON)
+option(WITH_MOD_SMOKE "Enable Smoke Modifier (Smoke Simulation)" ON)
+option(WITH_MOD_BOOLEAN "Enable Boolean Modifier" ON)
+option(WITH_MOD_REMESH "Enable Remesh Modifier" ON)
+option(WITH_MOD_CLOTH_ELTOPO "Enable Experimental cloth solver" OFF)
mark_as_advanced(WITH_MOD_CLOTH_ELTOPO)
option(WITH_MOD_OCEANSIM "Enable Ocean Modifier" OFF)
@@ -206,6 +205,7 @@ option(WITH_IMAGE_REDCODE "Enable RedCode Image Support" OFF)
option(WITH_IMAGE_FRAMESERVER "Enable image FrameServer Support for rendering" ON)
# Audio/Video format support
+option(WITH_CODEC_AVI "Enable Blenders own AVI file support (raw/jpeg)" ON)
option(WITH_CODEC_FFMPEG "Enable FFMPeg Support (http://ffmpeg.org)" OFF)
option(WITH_CODEC_SNDFILE "Enable libsndfile Support (http://www.mega-nerd.com/libsndfile)" OFF)
@@ -254,6 +254,9 @@ set(CYCLES_CUDA_BINARIES_ARCH sm_13 sm_20 sm_21 sm_30 CACHE STRING "CUDA archite
mark_as_advanced(CYCLES_CUDA_BINARIES_ARCH)
unset(PLATFORM_DEFAULT)
+# LLVM
+option(WITH_LLVM "Use LLVM" OFF)
+
# disable for now, but plan to support on all platforms eventually
option(WITH_MEM_JEMALLOC "Enable malloc replacement (http://www.canonware.com/jemalloc)" OFF)
mark_as_advanced(WITH_MEM_JEMALLOC)
@@ -293,11 +296,11 @@ if(APPLE)
if(${CMAKE_GENERATOR} MATCHES "Xcode")
- ##### workaround for actual official cmake incompatibility with xcode 4.3 #####
+ ##### workaround for actual official cmake incompatibility with xcode 4.3 #####
if(${XCODE_VERSION} MATCHES '') # cmake fails due looking for xcode in the wrong path, thus will be empty var
message("Official cmake does not yet support Xcode 4.3, get a patched version here: http://www.jensverwiebe.de/Blender/CMake%202.8-7patched.zip")
endif()
- ### end workaround for actual official cmake incompatibility with xcode 4.3 ###
+ ### end workaround for actual official cmake incompatibility with xcode 4.3 ###
if(${XCODE_VERSION} VERSION_EQUAL 4 OR ${XCODE_VERSION} VERSION_GREATER 4 AND ${XCODE_VERSION} VERSION_LESS 4.3)
# Xcode 4 defaults to the Apple LLVM Compiler.
@@ -316,6 +319,9 @@ if(APPLE)
option(WITH_COCOA "Use Cocoa framework instead of deprecated Carbon" ON)
option(USE_QTKIT "Use QtKit instead of Carbon quicktime (needed for having partial quicktime for 64bit)" OFF)
option(WITH_LIBS10.5 "Use 10.5 libs (needed for 64bit builds)" OFF)
+ if(CMAKE_OSX_ARCHITECTURES MATCHES x86_64)
+ set(USE_QTKIT ON CACHE BOOL "ON" FORCE) # no Quicktime in 64bit
+ endif()
endif()
@@ -371,13 +377,20 @@ if(WITH_CYCLES OR WITH_MOD_BOOLEAN)
set(WITH_BOOST ON)
endif()
-# don't store paths to libs for portable distrobution
+# auto enable llvm for cycles_osl
+if(WITH_CYCLES_OSL)
+ set(WITH_LLVM ON CACHE BOOL "ON" FORCE)
+endif()
+
+# don't store paths to libs for portable distribution
if(WITH_INSTALL_PORTABLE)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
endif()
if(WITH_GHOST_SDL OR WITH_HEADLESS)
set(WITH_GHOST_XDND OFF)
+ set(WITH_X11_XF86VMODE OFF)
+ set(WITH_X11_XINPUT OFF)
endif()
if(MINGW)
@@ -563,7 +576,14 @@ if(UNIX AND NOT APPLE)
endif()
mark_as_advanced(FFMPEG)
- set(FFMPEG_INCLUDE_DIRS ${FFMPEG}/include ${FFMPEG}/include/ffmpeg)
+
+ # lame, but until we have proper find module for ffmpeg
+ set(FFMPEG_INCLUDE_DIRS ${FFMPEG}/include)
+ if(EXISTS "${FFMPEG}/include/ffmpeg/")
+ list(APPEND FFMPEG_INCLUDE_DIRS "${FFMPEG}/include/ffmpeg")
+ endif()
+ # end lameness
+
mark_as_advanced(FFMPEG_LIBRARIES)
set(FFMPEG_LIBPATH ${FFMPEG}/lib)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__STDC_CONSTANT_MACROS")
@@ -691,6 +711,47 @@ if(UNIX AND NOT APPLE)
endif()
endif()
+ if(WITH_LLVM)
+ set(LLVM_DIRECTORY ${LIBDIR}/llvm CACHE PATH "Path to the LLVM installation")
+ set(LLVM_VERSION "3.0" CACHE STRING "Version of LLVM to use")
+ set(LLVM_STATIC YES)
+ if(LLVM_DIRECTORY)
+ set(LLVM_CONFIG "${LLVM_DIRECTORY}/bin/llvm-config")
+ else()
+ set(LLVM_CONFIG llvm-config)
+ endif()
+ execute_process(COMMAND ${LLVM_CONFIG} --version
+ OUTPUT_VARIABLE LLVM_VERSION
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ execute_process(COMMAND ${LLVM_CONFIG} --prefix
+ OUTPUT_VARIABLE LLVM_DIRECTORY
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ execute_process(COMMAND ${LLVM_CONFIG} --libdir
+ OUTPUT_VARIABLE LLVM_LIB_DIR
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ find_library(LLVM_LIBRARY
+ NAMES libLLVMAnalysis.a # first of a whole bunch of libs to get
+ PATHS ${LLVM_LIB_DIR})
+ message(STATUS "LLVM version = ${LLVM_VERSION}")
+ message(STATUS "LLVM dir = ${LLVM_DIRECTORY}")
+ message(STATUS "LLVM lib dir = ${LLVM_LIB_DIR}")
+
+ if(LLVM_LIBRARY AND LLVM_DIRECTORY AND LLVM_LIB_DIR)
+ if(LLVM_STATIC)
+ # if static LLVM libraries were requested, use llvm-config to generate
+ # the list of what libraries we need, and substitute that in the right
+ # way for LLVM_LIBRARY.
+ execute_process(COMMAND ${LLVM_CONFIG} --libfiles
+ OUTPUT_VARIABLE LLVM_LIBRARY
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ string(REPLACE " " ";" LLVM_LIBRARY ${LLVM_LIBRARY})
+ endif()
+ message(STATUS "LLVM library = ${LLVM_LIBRARY}")
+ else()
+ message(FATAL_ERROR "LLVM not found.")
+ endif()
+ endif()
+
if(WITH_CYCLES_OSL)
set(CYCLES_OSL ${LIBDIR}/osl CACHE PATH "Path to OpenShadingLanguage installation")
@@ -699,8 +760,9 @@ if(UNIX AND NOT APPLE)
find_library(OSL_LIB_EXEC NAMES oslexec PATHS ${CYCLES_OSL}/lib)
find_library(OSL_LIB_COMP NAMES oslcomp PATHS ${CYCLES_OSL}/lib)
find_library(OSL_LIB_QUERY NAMES oslquery PATHS ${CYCLES_OSL}/lib)
- # WARNING! depends on correct order of OSL libs linking
- list(APPEND OSL_LIBRARIES ${OSL_LIB_COMP} ${OSL_LIB_EXEC} ${OSL_LIB_QUERY})
+ # Note: --whole-archive is needed to force loading of all symbols in liboslexec,
+ # otherwise LLVM is missing the osl_allocate_closure_component function
+ list(APPEND OSL_LIBRARIES ${OSL_LIB_COMP} -Wl,--whole-archive ${OSL_LIB_EXEC} -Wl,--no-whole-archive ${OSL_LIB_QUERY})
find_path(OSL_INCLUDES OSL/oslclosure.h PATHS ${CYCLES_OSL}/include)
find_program(OSL_COMPILER NAMES oslc PATHS ${CYCLES_OSL}/bin)
@@ -712,8 +774,6 @@ if(UNIX AND NOT APPLE)
else()
message(STATUS "OSL not found")
endif()
-
- include_directories(${OSL_INCLUDES})
endif()
# OpenSuse needs lutil, ArchLinux not, for now keep, can avoid by using --as-needed
@@ -764,7 +824,7 @@ if(UNIX AND NOT APPLE)
elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(PLATFORM_CFLAGS "-pipe -fPIC -funsigned-char -fno-strict-aliasing")
# Solaris CC
- elseif(CMAKE_CXX_COMPILER_ID MATCHES "SunPro")
+ elseif(CMAKE_CXX_COMPILER_ID MATCHES "SunPro")
set(PLATFORM_CFLAGS "-pipe -features=extensions -fPIC -D__FUNCTION__=__func__")
# Intel C++ Compiler
@@ -798,7 +858,7 @@ elseif(WIN32)
if(CMAKE_COMPILER_IS_GNUCC)
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/mingw32)
- # Setup 64bit and 64bit windows systems
+ # Setup 64bit and 64bit windows systems
if(WITH_MINGW64)
message("Set 64 bit compiler for MinGW.")
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/mingw64)
@@ -881,8 +941,6 @@ elseif(WIN32)
else()
message(STATUS "OSL not found")
endif()
-
- include_directories(${OSL_INCLUDES})
endif()
if(MSVC)
@@ -926,7 +984,7 @@ elseif(WIN32)
if(WITH_MOD_CLOTH_ELTOPO)
set(LAPACK ${LIBDIR}/lapack)
# set(LAPACK_INCLUDE_DIR ${LAPACK}/include)
- set(LAPACK_LIBPATH ${LAPACK}/lib)
+ set(LAPACK_LIBPATH ${LAPACK}/lib)
set(LAPACK_LIBRARIES
${LIBDIR}/lapack/lib/libf2c.lib
${LIBDIR}/lapack/lib/clapack_nowrap.lib
@@ -1066,13 +1124,15 @@ elseif(WIN32)
else()
set(BOOST_LIBPATH ${BOOST}/lib)
set(BOOST_POSTFIX "vc90-mt-s-1_49.lib")
- set(BOOST_DEBUG_POSTFIX "vc90-mt-sgd-1_49.lib")
+ set(BOOST_DEBUG_POSTFIX "vc90-mt-sgd-1_49.lib")
endif()
set(BOOST_LIBRARIES
optimized libboost_date_time-${BOOST_POSTFIX} optimized libboost_filesystem-${BOOST_POSTFIX}
- optimized libboost_regex-${BOOST_POSTFIX} optimized libboost_system-${BOOST_POSTFIX} optimized libboost_thread-${BOOST_POSTFIX}
+ optimized libboost_regex-${BOOST_POSTFIX}
+ optimized libboost_system-${BOOST_POSTFIX} optimized libboost_thread-${BOOST_POSTFIX}
debug libboost_date_time-${BOOST_DEBUG_POSTFIX} debug libboost_filesystem-${BOOST_DEBUG_POSTFIX}
- debug libboost_regex-${BOOST_DEBUG_POSTFIX} debug libboost_system-${BOOST_DEBUG_POSTFIX} debug libboost_thread-${BOOST_DEBUG_POSTFIX})
+ debug libboost_regex-${BOOST_DEBUG_POSTFIX}
+ debug libboost_system-${BOOST_DEBUG_POSTFIX} debug libboost_thread-${BOOST_DEBUG_POSTFIX})
set(BOOST_DEFINITIONS "-DBOOST_ALL_NO_LIB")
endif()
@@ -1088,7 +1148,7 @@ elseif(WIN32)
set(OPENCOLORIO ${LIBDIR}/opencolorio)
set(OPENCOLORIO_INCLUDE_DIRS ${OPENCOLORIO}/include)
set(OPENCOLORIO_LIBRARIES OpenColorIO)
- set_lib_path(OPENCOLORIO_LIBPATH "opencolorio/lib")
+ set(OPENCOLORIO_LIBPATH ${LIBDIR}/opencolorio/lib)
set(OPENCOLORIO_DEFINITIONS)
endif()
@@ -1104,10 +1164,10 @@ elseif(WIN32)
set(PLATFORM_LINKFLAGS_DEBUG "/NODEFAULTLIB:libcmt.lib /NODEFAULTLIB:libc.lib")
# used in many places so include globally, like OpenGL
- blender_include_dirs("${PTHREADS_INCLUDE_DIRS}")
+ blender_include_dirs_sys("${PTHREADS_INCLUDE_DIRS}")
elseif(CMAKE_COMPILER_IS_GNUCC)
- # keep GCC specific stuff here
+ # keep GCC specific stuff here
set(PLATFORM_LINKLIBS "-lshell32 -lshfolder -lgdi32 -lmsvcrt -lwinmm -lmingw32 -lm -lws2_32 -lz -lstdc++ -lole32 -luuid -lwsock32 -lpsapi")
set(PLATFORM_CFLAGS "-pipe -funsigned-char -fno-strict-aliasing")
@@ -1243,14 +1303,16 @@ elseif(WIN32)
set(BOOST_POSTFIX "mgw47-mt-s-1_49")
set(BOOST_DEBUG_POSTFIX "mgw47-mt-sd-1_49")
else()
- set(BOOST_POSTFIX "mgw46-mt-s-1_47")
- set(BOOST_DEBUG_POSTFIX "mgw46-mt-sd-1_47")
- endif()
+ set(BOOST_POSTFIX "mgw46-mt-s-1_49")
+ set(BOOST_DEBUG_POSTFIX "mgw46-mt-sd-1_49")
+ endif()
set(BOOST_LIBRARIES
optimized boost_date_time-${BOOST_POSTFIX} boost_filesystem-${BOOST_POSTFIX}
- boost_regex-${BOOST_POSTFIX} boost_system-${BOOST_POSTFIX} boost_thread-${BOOST_POSTFIX}
+ boost_regex-${BOOST_POSTFIX}
+ boost_system-${BOOST_POSTFIX} boost_thread-${BOOST_POSTFIX}
debug boost_date_time-${BOOST_DEBUG_POSTFIX} boost_filesystem-${BOOST_DEBUG_POSTFIX}
- boost_regex-${BOOST_DEBUG_POSTFIX} boost_system-${BOOST_DEBUG_POSTFIX} boost_thread-${BOOST_DEBUG_POSTFIX})
+ boost_regex-${BOOST_DEBUG_POSTFIX}
+ boost_system-${BOOST_DEBUG_POSTFIX} boost_thread-${BOOST_DEBUG_POSTFIX})
set(BOOST_LIBPATH ${BOOST}/lib)
set(BOOST_DEFINITIONS "-DBOOST_ALL_NO_LIB -DBOOST_THREAD_USE_LIB ")
endif()
@@ -1274,7 +1336,7 @@ elseif(WIN32)
set(PLATFORM_LINKFLAGS "-Xlinker --stack=2097152")
## DISABLE - causes linking errors
- ## for re-distrobution, so users dont need mingw installed
+ ## for re-distribution, so users dont need mingw installed
# set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -static-libgcc -static-libstdc++")
endif()
@@ -1293,7 +1355,7 @@ elseif(APPLE)
set(OSX_SYSROOT_PREFIX /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform)
set(OSX_DEVELOPER_PREFIX /Developer/SDKs/MacOSX${OSX_SYSTEM}.sdk) # use guaranteed existing sdk
set(CMAKE_OSX_SYSROOT ${OSX_SYSROOT_PREFIX}/${OSX_DEVELOPER_PREFIX} CACHE PATH "" FORCE)
- endif()
+ endif()
if(WITH_LIBS10.5)
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/darwin-9.x.universal)
@@ -1386,6 +1448,7 @@ elseif(APPLE)
if(WITH_IMAGE_OPENEXR)
set(OPENEXR ${LIBDIR}/openexr)
+ set(OPENEXR_INCLUDE_DIR ${OPENEXR}/include)
set(OPENEXR_INCLUDE_DIRS ${OPENEXR}/include/OpenEXR)
set(OPENEXR_LIBRARIES Iex Half IlmImf Imath IlmThread)
set(OPENEXR_LIBPATH ${OPENEXR}/lib)
@@ -1512,7 +1575,7 @@ elseif(APPLE)
if(WITH_OPENIMAGEIO)
set(OPENIMAGEIO ${LIBDIR}/openimageio)
set(OPENIMAGEIO_INCLUDE_DIRS ${OPENIMAGEIO}/include)
- set(OPENIMAGEIO_LIBRARIES OpenImageIO ${PNG_LIBRARIES} ${JPEG_LIBRARIES} ${TIFF_LIBRARY} ${OPENEXR_LIBRARIES} ${ZLIB_LIBRARIES})
+ set(OPENIMAGEIO_LIBRARIES ${OPENIMAGEIO}/lib/libOpenImageIO.a ${PNG_LIBRARIES} ${JPEG_LIBRARIES} ${TIFF_LIBRARY} ${OPENEXR_LIBRARIES} ${ZLIB_LIBRARIES})
set(OPENIMAGEIO_LIBPATH ${OPENIMAGEIO}/lib ${JPEG_LIBPATH} ${PNG_LIBPATH} ${TIFF_LIBPATH} ${OPENEXR_LIBPATH} ${ZLIB_LIBPATH})
set(OPENIMAGEIO_DEFINITIONS "-DOIIO_STATIC_BUILD")
endif()
@@ -1525,6 +1588,47 @@ elseif(APPLE)
set(OPENCOLORIO_DEFINITIONS "-DOCIO_STATIC_BUILD")
endif()
+ if(WITH_LLVM)
+ set(LLVM_DIRECTORY ${LIBDIR}/llvm CACHE PATH "Path to the LLVM installation")
+ set(LLVM_VERSION "3.1" CACHE STRING "Version of LLVM to use")
+ set(LLVM_STATIC YES)
+ if(LLVM_DIRECTORY)
+ set(LLVM_CONFIG "${LLVM_DIRECTORY}/bin/llvm-config")
+ else()
+ set(LLVM_CONFIG llvm-config)
+ endif()
+ execute_process(COMMAND ${LLVM_CONFIG} --version
+ OUTPUT_VARIABLE LLVM_VERSION
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ execute_process(COMMAND ${LLVM_CONFIG} --prefix
+ OUTPUT_VARIABLE LLVM_DIRECTORY
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ execute_process(COMMAND ${LLVM_CONFIG} --libdir
+ OUTPUT_VARIABLE LLVM_LIB_DIR
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ find_library(LLVM_LIBRARY
+ NAMES libLLVMAnalysis.a # first of a whole bunch of libs to get
+ PATHS ${LLVM_LIB_DIR})
+ message(STATUS "LLVM version = ${LLVM_VERSION}")
+ message(STATUS "LLVM dir = ${LLVM_DIRECTORY}")
+ message(STATUS "LLVM lib dir = ${LLVM_LIB_DIR}")
+
+ if(LLVM_LIBRARY AND LLVM_DIRECTORY AND LLVM_LIB_DIR)
+ if(LLVM_STATIC)
+ # if static LLVM libraries were requested, use llvm-config to generate
+ # the list of what libraries we need, and substitute that in the right
+ # way for LLVM_LIBRARY.
+ execute_process(COMMAND ${LLVM_CONFIG} --libfiles
+ OUTPUT_VARIABLE LLVM_LIBRARY
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ string(REPLACE " " ";" LLVM_LIBRARY ${LLVM_LIBRARY})
+ endif()
+ message(STATUS "LLVM library = ${LLVM_LIBRARY}")
+ else()
+ message(FATAL_ERROR "LLVM not found.")
+ endif()
+ endif()
+
if(WITH_CYCLES_OSL)
set(CYCLES_OSL ${LIBDIR}/osl CACHE PATH "Path to OpenShadingLanguage installation")
@@ -1534,7 +1638,7 @@ elseif(APPLE)
find_library(OSL_LIB_COMP NAMES oslcomp PATHS ${CYCLES_OSL}/lib)
find_library(OSL_LIB_QUERY NAMES oslquery PATHS ${CYCLES_OSL}/lib)
# WARNING! depends on correct order of OSL libs linking
- list(APPEND OSL_LIBRARIES ${OSL_LIB_COMP} ${OSL_LIB_EXEC} ${OSL_LIB_QUERY})
+ list(APPEND OSL_LIBRARIES ${OSL_LIB_COMP} -force_load ${OSL_LIB_EXEC} ${OSL_LIB_QUERY})
find_path(OSL_INCLUDES OSL/oslclosure.h PATHS ${CYCLES_OSL}/include)
find_program(OSL_COMPILER NAMES oslc PATHS ${CYCLES_OSL}/bin)
@@ -1546,20 +1650,19 @@ elseif(APPLE)
else()
message(STATUS "OSL not found")
endif()
-
- include_directories(${OSL_INCLUDES})
endif()
set(EXETYPE MACOSX_BUNDLE)
set(CMAKE_C_FLAGS_DEBUG "-fno-strict-aliasing -g")
set(CMAKE_CXX_FLAGS_DEBUG "-fno-strict-aliasing -g")
- if(CMAKE_OSX_ARCHITECTURES MATCHES "i386")
- set(CMAKE_CXX_FLAGS_RELEASE "-O2 -mdynamic-no-pic -ftree-vectorize -msse -msse2 -fvariable-expansion-in-unroller")
- set(CMAKE_C_FLAGS_RELEASE "-O2 -mdynamic-no-pic -ftree-vectorize -msse -msse2 -fvariable-expansion-in-unroller")
- elseif(CMAKE_OSX_ARCHITECTURES MATCHES "x86_64")
- set(CMAKE_CXX_FLAGS_RELEASE "-O2 -mdynamic-no-pic -ftree-vectorize -msse -msse2 -msse3 -mssse3 -fvariable-expansion-in-unroller")
- set(CMAKE_C_FLAGS_RELEASE "-O2 -mdynamic-no-pic -ftree-vectorize -msse -msse2 -msse3 -mssse3 -fvariable-expansion-in-unroller")
+ if(CMAKE_OSX_ARCHITECTURES MATCHES "x86_64" OR CMAKE_OSX_ARCHITECTURES MATCHES "i386")
+ set(CMAKE_CXX_FLAGS_RELEASE "-O2 -mdynamic-no-pic -msse -msse2 -msse3 -mssse3")
+ set(CMAKE_C_FLAGS_RELEASE "-O2 -mdynamic-no-pic -msse -msse2 -msse3 -mssse3")
+ if(NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang")
+ set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -ftree-vectorize -fvariable-expansion-in-unroller")
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -ftree-vectorize -fvariable-expansion-in-unroller")
+ endif()
else()
set(CMAKE_C_FLAGS_RELEASE "-mdynamic-no-pic -fno-strict-aliasing")
set(CMAKE_CXX_FLAGS_RELEASE "-mdynamic-no-pic -fno-strict-aliasing")
@@ -1582,6 +1685,12 @@ if(WITH_CYCLES)
if(NOT WITH_BOOST)
message(FATAL_ERROR "Cycles reqires WITH_BOOST, the library may not have been found. Configure BOOST or disable WITH_CYCLES")
endif()
+
+ if(WITH_CYCLES_OSL)
+ if(NOT WITH_LLVM)
+ message(FATAL_ERROR "Cycles OSL reqires WITH_LLVM, the library may not have been found. Configure LLVM or disable WITH_CYCLES_OSL")
+ endif()
+ endif()
endif()
@@ -1725,9 +1834,17 @@ if(CMAKE_COMPILER_IS_GNUCC)
ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_POINTER_ARITH -Wpointer-arith)
ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_UNUSED_PARAMETER -Wunused-parameter)
ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_WRITE_STRINGS -Wwrite-strings)
+ ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_LOGICAL_OP -Wlogical-op)
+ ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_UNDEF -Wundef)
+ ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_INIT_SELF -Winit-self) # needs -Wuninitialized
+ ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_NO_NULL -Wnonnull) # C only
+ ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_MISSING_INCLUDE_DIRS -Wmissing-include-dirs)
+ ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_NO_DIV_BY_ZERO -Wno-div-by-zero)
- # # this causes too many warnings, disable
- # ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_UNDEFINED -Wundef)
+ # gcc 4.2 gives annoying warnings on every file with this
+ if ("${CMAKE_C_COMPILER_VERSION}" VERSION_GREATER "4.2")
+ ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_UNINITIALIZED -Wuninitialized)
+ endif()
# disable because it gives warnings for printf() & friends.
# ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_DOUBLE_PROMOTION -Wdouble-promotion -Wno-error=double-promotion)
@@ -1739,9 +1856,21 @@ if(CMAKE_COMPILER_IS_GNUCC)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_ALL -Wall)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_INVALID_OFFSETOF -Wno-invalid-offsetof)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_SIGN_COMPARE -Wno-sign-compare)
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_LOGICAL_OP -Wlogical-op)
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_INIT_SELF -Winit-self) # needs -Wuninitialized
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_MISSING_INCLUDE_DIRS -Wmissing-include-dirs)
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_DIV_BY_ZERO -Wno-div-by-zero)
+
+ # gcc 4.2 gives annoying warnings on every file with this
+ if ("${CMAKE_C_COMPILER_VERSION}" VERSION_GREATER "4.2")
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_UNINITIALIZED -Wuninitialized)
+ endif()
- # # this causes too many warnings, disable
- # ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_UNDEFINED -Wundef)
+ # causes too many warnings
+ if(NOT APPLE)
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_UNDEF -Wundef)
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_MISSING_DECLARATIONS -Wmissing-declarations)
+ endif()
# flags to undo strict flags
ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_DEPRECATED_DECLARATIONS -Wno-deprecated-declarations)
@@ -1760,13 +1889,15 @@ elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_NO_CHAR_SUBSCRIPTS -Wno-char-subscripts)
ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_STRICT_PROTOTYPES -Wstrict-prototypes)
ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_MISSING_PROTOTYPES -Wmissing-prototypes)
+ ADD_CHECK_C_COMPILER_FLAG(C_WARNINGS C_WARN_UNUSED_MACROS -Wunused-macros)
- ADD_CHECK_C_COMPILER_FLAG(CXX_WARNINGS C_WARN_ALL -Wall)
- ADD_CHECK_C_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_AUTOLOGICAL_COMPARE -Wno-tautological-compare)
- ADD_CHECK_C_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_UNKNOWN_PRAGMAS -Wno-unknown-pragmas)
- ADD_CHECK_C_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_CHAR_SUBSCRIPTS -Wno-char-subscripts)
- ADD_CHECK_C_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_OVERLOADED_VIRTUAL -Wno-overloaded-virtual) # we get a lot of these, if its a problem a dev needs to look into it.
- ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_INVALID_OFFSETOF -Wno-invalid-offsetof)
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_ALL -Wall)
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_AUTOLOGICAL_COMPARE -Wno-tautological-compare)
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_UNKNOWN_PRAGMAS -Wno-unknown-pragmas)
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_CHAR_SUBSCRIPTS -Wno-char-subscripts)
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_OVERLOADED_VIRTUAL -Wno-overloaded-virtual) # we get a lot of these, if its a problem a dev needs to look into it.
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_INVALID_OFFSETOF -Wno-invalid-offsetof)
+ ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_UNUSED_MACROS -Wunused-macros)
elseif(CMAKE_C_COMPILER_ID MATCHES "Intel")
@@ -1847,9 +1978,10 @@ if(WITH_PYTHON)
endif()
endif()
-
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${PLATFORM_CFLAGS} ${C_WARNINGS}")
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${PLATFORM_CFLAGS} ${CXX_WARNINGS}")
+# Include warnings first, so its possible to disable them with user defined flags
+# eg: -Wno-uninitialized
+set(CMAKE_C_FLAGS "${C_WARNINGS} ${CMAKE_C_FLAGS} ${PLATFORM_CFLAGS}")
+set(CMAKE_CXX_FLAGS "${CXX_WARNINGS} ${CMAKE_CXX_FLAGS} ${PLATFORM_CFLAGS}")
#-------------------------------------------------------------------------------
# Global Defines
@@ -1956,6 +2088,7 @@ if(FIRST_RUN)
info_cfg_option(WITH_OPENAL)
info_cfg_option(WITH_SDL)
info_cfg_option(WITH_JACK)
+ info_cfg_option(WITH_CODEC_AVI)
info_cfg_option(WITH_CODEC_FFMPEG)
info_cfg_option(WITH_CODEC_SNDFILE)
@@ -1972,7 +2105,6 @@ if(FIRST_RUN)
info_cfg_text("Modifiers:")
info_cfg_option(WITH_MOD_BOOLEAN)
info_cfg_option(WITH_MOD_REMESH)
- info_cfg_option(WITH_MOD_DECIMATE)
info_cfg_option(WITH_MOD_FLUID)
info_cfg_option(WITH_MOD_OCEANSIM)
diff --git a/GNUmakefile b/GNUmakefile
index 1f1de3f6b99..f8207787cbe 100644
--- a/GNUmakefile
+++ b/GNUmakefile
@@ -163,18 +163,27 @@ help:
@echo " * package_archive - build an archive package"
@echo ""
@echo "Testing Targets (not associated with building blender)"
- @echo " * test - run ctest, currently tests import/export, operator execution and that python modules load"
- @echo " * test_cmake - runs our own cmake file checker which detects errors in the cmake file list definitions"
- @echo " * test_pep8 - checks all python script are pep8 which are tagged to use the stricter formatting"
- @echo " * test_deprecated - checks for deprecation tags in our code which may need to be removed"
- @echo " * test_style - checks C/C++ conforms with blenders style guide: http://wiki.blender.org/index.php/Dev:Doc/CodeStyle"
+ @echo " * test - run ctest, currently tests import/export, operator execution and that python modules load"
+ @echo " * test_cmake - runs our own cmake file checker which detects errors in the cmake file list definitions"
+ @echo " * test_pep8 - checks all python script are pep8 which are tagged to use the stricter formatting"
+ @echo " * test_deprecated - checks for deprecation tags in our code which may need to be removed"
+ @echo " * test_style_c - checks C/C++ conforms with blenders style guide: http://wiki.blender.org/index.php/Dev:Doc/CodeStyle"
+ @echo " * test_style_c_qtc - same as test_style but outputs QtCreator tasks format"
+ @echo " * test_style_osl - checks OpenShadingLanguage conforms with blenders style guide: http://wiki.blender.org/index.php/Dev:Doc/CodeStyle"
+ @echo " * test_style_osl_qtc - checks OpenShadingLanguage conforms with blenders style guide: http://wiki.blender.org/index.php/Dev:Doc/CodeStyle"
@echo ""
@echo "Static Source Code Checking (not associated with building blender)"
- @echo " * check_cppcheck - run blender source through cppcheck (C & C++)"
- @echo " * check_splint - run blenders source through splint (C only)"
- @echo " * check_sparse - run blenders source through sparse (C only)"
- @echo " * check_spelling_c - check for spelling errors (C/C++ only)"
- @echo " * check_spelling_py - check for spelling errors (Python only)"
+ @echo " * check_cppcheck - run blender source through cppcheck (C & C++)"
+ @echo " * check_clang_array - run blender source through clang array checking script (C & C++)"
+ @echo " * check_splint - run blenders source through splint (C only)"
+ @echo " * check_sparse - run blenders source through sparse (C only)"
+ @echo " * check_smatch - run blenders source through smatch (C only)"
+ @echo " * check_spelling_c - check for spelling errors (OSL only)"
+ @echo " * check_spelling_osl - check for spelling errors (C/C++ only)"
+ @echo " * check_spelling_py - check for spelling errors (Python only)"
+ @echo ""
+ @echo "Utilities (not associated with building blender)"
+ @echo " * tbz - create a compressed svn export 'blender_archive.tar.bz2'"
@echo ""
@echo "Documentation Targets (not associated with building blender)"
@echo " * doc_py - generate sphinx python api docs"
@@ -205,31 +214,51 @@ test:
# run pep8 check check on scripts we distribute.
test_pep8:
- python3.2 source/tests/pep8.py > test_pep8.log 2>&1
+ python3 source/tests/pep8.py > test_pep8.log 2>&1
@echo "written: test_pep8.log"
# run some checks on our cmakefiles.
test_cmake:
- python3.2 build_files/cmake/cmake_consistency_check.py > test_cmake_consistency.log 2>&1
+ python3 build_files/cmake/cmake_consistency_check.py > test_cmake_consistency.log 2>&1
@echo "written: test_cmake_consistency.log"
# run deprecation tests, see if we have anything to remove.
test_deprecated:
- python3.2 source/tests/check_deprecated.py
+ python3 source/tests/check_deprecated.py
+
+test_style_c:
+ # run our own checks on C/C++ style
+ PYTHONIOENCODING=utf_8 python3 $(BLENDER_DIR)/source/tools/check_style_c.py $(BLENDER_DIR)/source/blender $(BLENDER_DIR)/source/creator --no-length-check
+
+test_style_c_qtc:
+ # run our own checks on C/C++ style
+ USE_QTC_TASK=1 \
+ PYTHONIOENCODING=utf_8 python3 $(BLENDER_DIR)/source/tools/check_style_c.py $(BLENDER_DIR)/source/blender $(BLENDER_DIR)/source/creator --no-length-check > \
+ test_style.tasks
+ @echo "written: test_style.tasks"
+
+
+test_style_osl:
+ # run our own checks on C/C++ style
+ PYTHONIOENCODING=utf_8 python3 $(BLENDER_DIR)/source/tools/check_style_c.py $(BLENDER_DIR)/intern/cycles/kernel/osl
+
-test_style:
+test_style_osl_qtc:
# run our own checks on C/C++ style
- PYTHONIOENCODING=utf_8 python3.2 $(BLENDER_DIR)/source/tools/check_style_c.py $(BLENDER_DIR)/source/blender $(BLENDER_DIR)/source/creator --no-length-check
+ USE_QTC_TASK=1 \
+ PYTHONIOENCODING=utf_8 python3 $(BLENDER_DIR)/source/tools/check_style_c.py $(BLENDER_DIR)/intern/cycles/kernel/osl > \
+ test_style.tasks
+ @echo "written: test_style.tasks"
# -----------------------------------------------------------------------------
# Project Files
#
project_qtcreator:
- python3.2 build_files/cmake/cmake_qtcreator_project.py $(BUILD_DIR)
+ python3 build_files/cmake/cmake_qtcreator_project.py $(BUILD_DIR)
project_netbeans:
- python3.2 build_files/cmake/cmake_netbeans_project.py $(BUILD_DIR)
+ python3 build_files/cmake/cmake_netbeans_project.py $(BUILD_DIR)
project_eclipse:
cmake -G"Eclipse CDT4 - Unix Makefiles" -H$(BLENDER_DIR) -B$(BUILD_DIR)
@@ -241,25 +270,43 @@ project_eclipse:
check_cppcheck:
$(CMAKE_CONFIG)
- cd $(BUILD_DIR) ; python3.2 $(BLENDER_DIR)/build_files/cmake/cmake_static_check_cppcheck.py
+ cd $(BUILD_DIR) ; python3 $(BLENDER_DIR)/build_files/cmake/cmake_static_check_cppcheck.py
+
+check_clang_array:
+ $(CMAKE_CONFIG)
+ cd $(BUILD_DIR) ; python3 $(BLENDER_DIR)/build_files/cmake/cmake_static_check_clang_array.py
check_splint:
$(CMAKE_CONFIG)
- cd $(BUILD_DIR) ; python3.2 $(BLENDER_DIR)/build_files/cmake/cmake_static_check_splint.py
+ cd $(BUILD_DIR) ; python3 $(BLENDER_DIR)/build_files/cmake/cmake_static_check_splint.py
check_sparse:
$(CMAKE_CONFIG)
- cd $(BUILD_DIR) ; python3.2 $(BLENDER_DIR)/build_files/cmake/cmake_static_check_sparse.py
+ cd $(BUILD_DIR) ; python3 $(BLENDER_DIR)/build_files/cmake/cmake_static_check_sparse.py
check_smatch:
$(CMAKE_CONFIG)
- cd $(BUILD_DIR) ; python3.2 $(BLENDER_DIR)/build_files/cmake/cmake_static_check_smatch.py
+ cd $(BUILD_DIR) ; python3 $(BLENDER_DIR)/build_files/cmake/cmake_static_check_smatch.py
check_spelling_py:
- cd $(BUILD_DIR) ; PYTHONIOENCODING=utf_8 python3.2 $(BLENDER_DIR)/source/tools/spell_check_source.py $(BLENDER_DIR)/release/scripts
+ cd $(BUILD_DIR) ; PYTHONIOENCODING=utf_8 python3 $(BLENDER_DIR)/source/tools/spell_check_source.py $(BLENDER_DIR)/release/scripts
check_spelling_c:
- cd $(BUILD_DIR) ; PYTHONIOENCODING=utf_8 python3.2 $(BLENDER_DIR)/source/tools/spell_check_source.py $(BLENDER_DIR)/source
+ cd $(BUILD_DIR) ; PYTHONIOENCODING=utf_8 python3 $(BLENDER_DIR)/source/tools/spell_check_source.py $(BLENDER_DIR)/source
+
+check_spelling_osl:
+ cd $(BUILD_DIR) ; PYTHONIOENCODING=utf_8 python3 $(BLENDER_DIR)/source/tools/spell_check_source.py $(BLENDER_DIR)/intern/cycles/kernel/osl
+
+# -----------------------------------------------------------------------------
+# Utilities
+#
+
+tbz:
+ svn export . blender_archive
+ tar cjf blender_archive.tar.bz2 blender_archive/
+ rm -rf blender_archive/
+ @echo "blender_archive.tar.bz2 written"
+
# -----------------------------------------------------------------------------
# Documentation
@@ -280,7 +327,7 @@ doc_dna:
@echo "docs written into: '$(BLENDER_DIR)/doc/blender_file_format/dna.html'"
doc_man:
- python3.2 doc/manpage/blender.1.py $(BUILD_DIR)/bin/blender
+ python3 doc/manpage/blender.1.py $(BUILD_DIR)/bin/blender
clean:
diff --git a/SConstruct b/SConstruct
index 517f507ec61..064ae0bc0b5 100644
--- a/SConstruct
+++ b/SConstruct
@@ -264,7 +264,6 @@ if 'blenderlite' in B.targets:
target_env_defs['WITH_BF_FLUID'] = False
target_env_defs['WITH_BF_OCEANSIM'] = False
target_env_defs['WITH_BF_SMOKE'] = False
- target_env_defs['WITH_BF_DECIMATE'] = False
target_env_defs['WITH_BF_BOOLEAN'] = False
target_env_defs['WITH_BF_REMESH'] = False
target_env_defs['WITH_BF_PYTHON'] = False
@@ -366,6 +365,7 @@ else:
# TODO, make optional
env['CPPFLAGS'].append('-DWITH_AUDASPACE')
+env['CPPFLAGS'].append('-DWITH_AVI')
# lastly we check for root_build_dir ( we should not do before, otherwise we might do wrong builddir
B.root_build_dir = env['BF_BUILDDIR']
@@ -871,9 +871,13 @@ if env['OURPLATFORM'] in ('win32-vc', 'win32-mingw', 'win64-vc', 'linuxcross'):
if env['WITH_BF_OIIO'] and env['OURPLATFORM'] != 'win32-mingw':
dllsources.append('${LCGDIR}/openimageio/bin/OpenImageIO.dll')
- if env['WITH_BF_OCIO'] and env['OURPLATFORM'] != 'win32-mingw':
- dllsources.append('${LCGDIR}/opencolorio/bin/OpenColorIO.dll')
+ if env['WITH_BF_OCIO']:
+ if not env['OURPLATFORM'] in ('win32-mingw', 'linuxcross'):
+ dllsources.append('${LCGDIR}/opencolorio/bin/OpenColorIO.dll')
+ else:
+ dllsources.append('${LCGDIR}/opencolorio/bin/libOpenColorIO.dll')
+
dllsources.append('#source/icons/blender.exe.manifest')
windlls = env.Install(dir=env['BF_INSTALLDIR'], source = dllsources)
@@ -903,6 +907,9 @@ if env['OURPLATFORM'] == 'win64-mingw':
if(env['WITH_BF_OPENMP']):
dllsources.append('${LCGDIR}/binaries/libgomp-1.dll')
+
+ if env['WITH_BF_OCIO']:
+ dllsources.append('${LCGDIR}/opencolorio/bin/libOpenColorIO.dll')
dllsources.append('${LCGDIR}/thumbhandler/lib/BlendThumb64.dll')
dllsources.append('${LCGDIR}/binaries/libgcc_s_sjlj-1.dll')
diff --git a/build_files/build_environment/prepare_release_env.sh b/build_files/build_environment/prepare_release_env.sh
new file mode 100755
index 00000000000..0bad1501540
--- /dev/null
+++ b/build_files/build_environment/prepare_release_env.sh
@@ -0,0 +1,1483 @@
+#!/bin/sh
+
+#
+# This script will prepare build environment with the same settings as release environment
+#
+# It will install two chroot environments:
+# - /home/buildbot_squeeze_i686
+# - /home/buildbot_squeeze_x86_64
+# which are used for 32bit and 64bit
+#
+# This sctipt will also create folder /home/sources where all dependent libraries sources are
+# downloading and compiling.
+#
+# Release builder scripts are stored in /home/sources/release-builder
+# See build_all.sh script for usage details
+#
+# This script was tested on debian squeeze and wheezy, should work on ubuntu as well
+# It wouldn't work on other distros
+#
+# TODO:
+# - It's still required manual copying of build configuration files to /home/sources/release-builder/config
+# - OSL is not set up yet
+#
+
+set -e
+
+NO_COLOR='\033[0m'
+EWHITE='\033[1;37m'
+ERED='\033[1;31m'
+
+CONFIRM="--i-really-do-know-what-im-doing"
+
+ERROR() {
+ echo ${ERED}${@}${NO_COLOR}
+}
+
+INFO() {
+ echo ${EWHITE}${@}${NO_COLOR}
+}
+
+if [ $# != 1 ]; then
+ ERROR "Usage: $0 $CONFIRM"
+ exit 1
+fi
+
+if [ "$1" != "$CONFIRM" ]; then
+ ERROR "Usage: $0 $CONFIRM"
+ exit 1
+fi
+
+DEBIAN_BRANCH="squeeze"
+DEBIAN_MIRROR="http://ftp.de.debian.org/debian"
+USER_ID=1000
+
+# For now it's always /home, so we can setup schroot to map /sources to the same
+# path at both host and chroot systems (which is currently needed for release building script)
+ENV_PATH="/home"
+
+AMD64_PATH="$ENV_PATH/buildbot_${DEBIAN_BRANCH}_x86_64"
+I686_PATH="$ENV_PATH/buildbot_${DEBIAN_BRANCH}_i686"
+SOURCES_PATH="$ENV_PATH/sources"
+
+THREADS=`cat /proc/cpuinfo | grep cores | uniq | sed -e "s/.*: *\(.*\)/\\1/"`
+
+# Force vpx be installed from the backports
+VPX_V="1.0.0-2~bpo60+1"
+
+BINUTILS_V="2.22"
+BINUTILS_FV="2.22-7.1"
+
+GCC_V="4.7_4.7.1"
+GCC_FV="4.7_4.7.1-7"
+
+OPENAL_V="1.14"
+
+DPKG_V="1.16.8"
+
+DEBHELPER_V="9"
+DEBHELPER_FV="9.20120909"
+
+JEMALLOC_V="3.1.0"
+SPNAV_V="0.2.2"
+FFMPEG_V="1.0"
+BOOST_V="1_51_0"
+PYTHON_V="3.3.0"
+PYTHIN_V_SHORT="3.3"
+OIIO_V="1.0.9"
+OCIO_V="1.0.7"
+MESA_V="8.0.5"
+
+CUDA_V="4.2.9"
+CUDA_DISTR="ubuntu10.04"
+CUDA_32="cudatoolkit_${CUDA_V}_linux_32_${CUDA_DISTR}.run"
+CUDA_64="cudatoolkit_${CUDA_V}_linux_64_${CUDA_DISTR}.run"
+
+INSTALL_RELEASE_BUILDER() {
+ SOURCES_PATH=$1
+
+ RB=$SOURCES_PATH/release-builder
+ if [ ! -d $RB ]; then
+ INFO "Installing release building scripts"
+
+ mkdir -p $RB
+
+ cat << EOF > $RB/Readme.txt
+This directory contains scrips needed for automated release archive preparation
+
+config/: storage of scons configs for different platforms
+
+build_all.sh: script asks version to add to archive name and revision to compile,
+ when script finished, there'll be 32 and 64 bit archives in current directory
+ better to run this script from this directory
+
+do_build_all.sh: uses environment variables set by build_all.sh script (or other scripts)
+ and launches compilation inside chroot environments
+
+chroot_compile.py: runs compilation process with giver parameters in chroots
+compile.py: script runs inside chroot environment and prepares archive
+
+blender-buildenv.tar.bz2: archive, received from Ken Hughes when i've been preparing
+ new environment to make it as close to old one as it's possible
+
+Hope all this would help you.
+
+-Sergey-
+EOF
+
+ cat << EOF > $RB/build_all.sh
+#!/bin/sh
+
+echo -n "version: "
+read version
+echo -n "svn revision (blank to latest, 0 to keep unchanged): "
+read revision
+
+export version
+export revision
+
+d=\`dirname \${0}\`
+\${d}/do_build_all.sh
+EOF
+ chmod +x $RB/build_all.sh
+
+ cat << EOF > $RB/build_all-test.sh
+#!/bin/sh
+
+d=\`dirname \${0}\`
+\${d}/do_build_all.sh
+EOF
+ chmod +x $RB/build_all-test.sh
+
+ cat << EOF > $RB/chroot-compile.py
+#!/usr/bin/env python
+
+import sys
+import os
+import platform
+
+from optparse import OptionParser
+
+# This could be passed through options, but does we actually need this?
+bl_source = '/home/sources/blender'
+build_dir = '/home/sources/blender-build/'
+install_dir = '/home/sources/blender-install/'
+with_player = True
+
+# Default config
+curr_arch = platform.architecture()[0]
+def_arch = 'x86_64' if curr_arch == '64bit' else 'i686'
+builder_dir = os.path.dirname(os.path.realpath(__file__))
+
+# XXX: bad thing!
+# builder_dir = builder_dir.replace("sources-new", "sources")
+
+def_cores = 1
+if hasattr(os, 'sysconf'):
+ if 'SC_NPROCESSORS_ONLN' in os.sysconf_names:
+ def_cores = os.sysconf('SC_NPROCESSORS_ONLN')
+
+# Per-architecture chroot name
+chroots = { 'i686': 'buildbot_squeeze_i686',
+ 'x86_64': 'buildbot_squeeze_x86_64'}
+
+# Parse command line
+op = OptionParser()
+op.add_option('--tag', default = None)
+op.add_option('--branch', default = None)
+op.add_option('--arch', default = def_arch)
+op.add_option('--cores', default = def_cores)
+op.add_option('--bl-version', default = 'UNDEFINED')
+op.add_option('--no-clean', default = False)
+(opts, args) = op.parse_args()
+
+if opts.arch not in chroots:
+ print('Error: No configured machine gound to build ' +
+ '{0} version' . format(opts.arch))
+ sys.exit(1)
+
+chroot = chroots[opts.arch]
+
+if opts.tag:
+ bl_source = '/home/sources/blender-tags/' + opts.tag
+elif opts.branch:
+ bl_source = '/home/sources/blender-branches/' + opts.branch
+
+if not os.path.isdir(bl_source):
+ print('Uname to find directory with sources: ' + bl_source)
+ sys.exit(1)
+
+print('Building {0} version, machine is {1}' . format(opts.bl_version, opts.arch))
+
+# Assume builder directory is binded to the same location in
+# chroot environments
+compiler = os.path.join(builder_dir, 'compile.py')
+
+cmd = 'schroot -c %s -d /home/sources/release-builder --' % (chroot)
+cmd += ' python %s' % (compiler)
+cmd += ' --bl-version=%s' % (opts.bl_version)
+cmd += ' --bl-source=%s' % (bl_source)
+cmd += ' --arch=%s' % (opts.arch)
+cmd += ' --build-dir=%s' % (build_dir)
+cmd += ' --install-dir=%s' % (install_dir)
+
+if opts.no_clean:
+ cmd += ' --no-clean=1'
+
+if with_player:
+ cmd += ' --with-player=1'
+
+#if opts.branch:
+# cmd += ' --use-new-ffmpeg=1'
+
+result = os.system(cmd)
+if result != 0:
+ print('compiler script exited with errcode: %s' % (result))
+ sys.exit(1)
+EOF
+ chmod +x $RB/chroot-compile.py
+
+ cat << EOF > $RB/compile.py
+#!/usr/bin/env python
+
+import platform
+import sys
+import os
+import shutil
+
+from optparse import OptionParser
+
+# Default config
+curr_arch = platform.architecture()[0]
+def_arch = 'x86_64' if curr_arch == '64bit' else 'i686'
+builder_dir = os.path.dirname(os.path.realpath(__file__))
+
+def_cores = 1
+if hasattr(os, 'sysconf'):
+ if 'SC_NPROCESSORS_ONLN' in os.sysconf_names:
+ def_cores = os.sysconf('SC_NPROCESSORS_ONLN')
+
+# Parse command line
+op = OptionParser()
+op.add_option('--arch', default = def_arch)
+op.add_option('--cores', default = def_cores)
+op.add_option('--no-clean', default = False)
+op.add_option('--bl-version', default = 'UNKNOWN')
+op.add_option('--bl-source', default = '')
+op.add_option('--config-dir', default = '')
+op.add_option('--build-dir', default = '')
+op.add_option('--install-dir', default = '')
+op.add_option('--with-player', default = False)
+#op.add_option('--use-new-ffmpeg', default = False)
+(opts, args) = op.parse_args()
+
+if opts.config_dir == '':
+ opts.config_dir = os.path.join(builder_dir, 'config')
+
+# Initial directory checking (could be problems with permissions)
+if not os.path.isdir(opts.bl_source):
+ print('Blender\'s source tree not found: %s' % (opts.bl_source))
+ sys.exit(1)
+
+if not os.path.isdir(opts.config_dir):
+ print('Directory with configuration files not found: %s' % (opts.config_dir))
+ sys.exit(1)
+
+if not os.path.isdir(os.path.dirname(opts.build_dir)):
+ print('Build directory can\'t be reached: %s' % (opts.build_dir))
+ sys.exit(1)
+
+if not os.path.isdir(os.path.dirname(opts.install_dir)):
+ print('Install directory can\'t be reached: %s' % (opts.install_dir))
+ sys.exit(1)
+
+# Detect glibc version
+libc = [name for name in os.listdir('/lib') if 'libc.so.' in name]
+if len(libc) == 0:
+ print('Could not find "/lib/libc.so.*": cannot determine glibc version')
+ sys.exit(-1)
+
+if len(libc) > 1:
+ print('warning: found more than one "/lib/libc.so.*": '+
+ 'using %s' % (libc[0]))
+
+glibc = 'glibc' + os.readlink('/lib/' + libc[0])[5:][:-3].replace('.', '')
+glibc = glibc[:8]
+
+# Full name for archive
+full_name = 'blender-%s-linux-%s-%s' % (opts.bl_version, glibc, opts.arch)
+build_dir = os.path.join(opts.build_dir, full_name)
+install_dir = os.path.join(opts.install_dir, full_name)
+scons = os.path.join(opts.bl_source, 'scons', 'scons.py')
+scons_cmd = 'python %s -C %s' % (scons, opts.bl_source)
+config = os.path.join(opts.config_dir, 'user-config-' + glibc + '-' + opts.arch + '.py')
+
+if not os.path.isfile(config):
+ print('Configuration file not found: %s' % (config))
+ sys.exit(1)
+
+# Clean build directory
+if not opts.no_clean:
+ print('Cleaning up build directory...')
+ os.system('%s BF_BUILDDIR=%s clean ' % (scons_cmd, build_dir))
+
+# Clean install directory
+if os.path.isdir(install_dir):
+ shutil.rmtree(install_dir)
+
+flags = ""
+
+# Switch to newer libraries if needed
+#if opts.use_new_ffmpeg:
+# print("Using new ffmpeg-0.8.1")
+# flags += " BF_FFMPEG='/home/sources/staticlibs/ffmpeg-0.8'"
+
+# Build blenderplayer first
+# (to be sure all stuff needed for blender would copied automatically)
+if opts.with_player:
+ player_config = os.path.join(opts.config_dir,
+ 'user-config-player-' + glibc + '-' + opts.arch + '.py')
+
+ if not os.path.isfile(player_config):
+ print('Player configuration file not found: %s' % (player_config))
+ sys.exit(1)
+
+ cmd = '%s -j %d blenderplayer ' % (scons_cmd, opts.cores + 1)
+ cmd += ' BF_BUILDDIR=%s' % (build_dir + '-player')
+ cmd += ' BF_INSTALLDIR=%s' % (install_dir)
+ cmd += ' BF_CONFIG=%s' % (player_config)
+ cmd += flags
+
+ result = os.system(cmd)
+ if result != 0:
+ print('Compilation failed, exit code is %d' % (result))
+ sys.exit(-1)
+
+# Build blender itself
+cmd = '%s -j %d blender ' % (scons_cmd, opts.cores + 1)
+cmd += ' BF_BUILDDIR=%s' % (build_dir)
+cmd += ' BF_INSTALLDIR=%s' % (install_dir)
+cmd += ' BF_CONFIG=%s' % (config)
+cmd += flags
+
+result = os.system(cmd)
+if result != 0:
+ print('Compilation failed, exit code is %d' % (result))
+ sys.exit(-1)
+
+blender = os.path.join(install_dir, 'blender')
+blenderplayer = blender + 'player'
+
+if not os.path.exists(blender):
+ print('scons completed successfully but blender executable missing')
+ sys.exit(1)
+
+if opts.with_player and not os.path.exists(blenderplayer):
+ print('scons completed successfully but blenderplayer executable missing')
+ sys.exit(1)
+
+# compile python modules
+#result = os.system('%s --background --python %s/source/tools/compile_scripts.py' % (blender, opts.bl_source))
+#if result != 0:
+# print('Python modules compilation failed, exit code is %d' % (result))
+# sys.exit(-1)
+
+print('build successful')
+
+os.system('strip -s %s %s' % (blender, blenderplayer))
+
+# Copy all texts needed for release
+release_texts = os.path.join(opts.bl_source, 'release', 'text', '*')
+release_txt = os.path.join(install_dir, 'release_%s.txt' % (opts.bl_version))
+
+os.system('cp -r %s %s' % (release_texts, install_dir))
+
+if os.path.exists(release_txt):
+ print 'RELEASE TEXT FOUND'
+else:
+ print 'WARNING! RELEASE TEXT NOT FOUND!'
+
+# TODO: copy plugins data when ready
+
+# Add software gl libraries and scripts
+mesa_arch = None
+
+if opts.arch == 'x86_64':
+ mesa_arch = 'mesalibs64.tar.bz2'
+elif opts.arch == 'i686':
+ mesa_arch = 'mesalibs32.tar.bz2'
+
+if mesa_arch is not None:
+ mesalibs = os.path.join(builder_dir, 'extra', mesa_arch)
+ software_gl = os.path.join(builder_dir, 'extra', 'blender-softwaregl')
+
+ os.system('tar -xpf %s -C %s' % (mesalibs, install_dir))
+ os.system('cp %s %s' % (software_gl, install_dir))
+ os.system('chmod 755 %s' % (os.path.join(install_dir, 'blender-softwaregl')))
+
+# Pack release archive
+print("Building Dynamic Tarball")
+os.system('tar -C %s -cjf %s.tar.bz2 %s ' % (opts.install_dir,
+ full_name, full_name))
+
+print('Done.')
+EOF
+ chmod +x $RB/compile.py
+
+ cat << EOF > $RB/do_build_al.sh
+#!/bin/sh
+
+SOURCES="/home/sources"
+
+#opts="--cores=1 "
+opts=""
+
+if [ "x\${tag}" != "x" ]; then
+ echo "Getting tagged source tree..."
+ d="\${SOURCES}/blender-tags/\${tag}"
+ opts="\${opts} --tag=\${tag}"
+ if [ ! -d \${d} ]; then
+ svn co https://svn.blender.org/svnroot/bf-blender/tags/\${tag}/blender/@\${revision} \${d}
+ else
+ svn up -r \${revision} \${d}
+ fi
+elif [ "x\${branch}" != "x" ]; then
+ echo "Getting branched source tree..."
+ d="\${SOURCES}/blender-branches/\${branch}"
+ opts="\${opts} --branch=\${branch}"
+ if [ ! -d \${d} ]; then
+ if [ "x\${revision}" != "x" ]; then
+ svn co https://svn.blender.org/svnroot/bf-blender/branches/\${branch}/@\${revision} \${d}
+ else
+ svn co https://svn.blender.org/svnroot/bf-blender/branches/\${branch}/ \${d}
+ fi
+ else
+ if [ "x\${revision}" != "x" ]; then
+ svn up -r \${revision} \${d}
+ else
+ svn up \${d}
+ fi
+ fi
+else
+ if [ "x\${revision}" != "x" ]; then
+ if [ "x\${revision}" != "x0" ]; then
+ svn up -r \${revision} \${SOURCES}/blender
+ else
+ svn up \${SOURCES}/blender
+ fi
+ fi
+fi
+
+if [ "x\${tag}" != "x" ]; then
+ b="\${SOURCES}/blender-tags/\${tag}"
+elif [ "x\${branch}" != "x" ]; then
+ b="\${SOURCES}/blender-branches/\${branch}"
+else
+ b="\${SOURCES}/blender"
+fi
+
+if [ "x\${addons_revision}" != "x" ]; then
+ d="\${b}/release/scripts/addons"
+
+ if [ "x\${addons_revision}" != "x0" ]; then
+ svn up -r \${addons_revision} \${d}
+ else
+ svn up \${d}
+ fi
+fi
+
+if [ "x\${locale_revision}" != "x" ]; then
+ d="\${b}/release/datafiles/locale"
+
+ if [ "x\${locale_revision}" != "x0" ]; then
+ svn up -r \${locale_revision} \${d}
+ else
+ svn up \${d}
+ fi
+fi
+
+if [ -z "\$version" ]; then
+ version=r\`/usr/bin/svnversion \$SOURCES/blender\`
+fi
+
+cd extra
+./update-libs.sh
+cd ..
+
+python chroot-compile.py \${opts} --arch=x86_64 --bl-version \${version} # --no-clean=1
+python chroot-compile.py \${opts} --arch=i686 --bl-version \${version} # --no-clean=1
+EOF
+ chmod +x $RB/do_build_al.sh
+
+ mkdir -p $RB/extra
+
+ cat << EOF > $RB/extra/blender-softwaregl
+#!/bin/sh
+
+BF_DIST_BIN=\`dirname "\$0"\`
+BF_PROGRAM="blender" # BF_PROGRAM=\`basename "\$0"\`-bin
+exitcode=0
+
+LD_LIBRARY_PATH=\${BF_DIST_BIN}/lib:\${LD_LIBRARY_PATH}
+
+if [ -n "\$LD_LIBRARYN32_PATH" ]; then
+ LD_LIBRARYN32_PATH=\${BF_DIST_BIN}/lib:\${LD_LIBRARYN32_PATH}
+fi
+if [ -n "\$LD_LIBRARYN64_PATH" ]; then
+ LD_LIBRARYN64_PATH=\${BF_DIST_BIN}/lib:\${LD_LIBRARYN64_PATH}
+fi
+if [ -n "\$LD_LIBRARY_PATH_64" ]; then
+ LD_LIBRARY_PATH_64=\${BF_DIST_BIN}/lib:\${LD_LIBRARY_PATH_64}
+fi
+
+# Workaround for half-transparent windows when compiz is enabled
+XLIB_SKIP_ARGB_VISUALS=1
+
+export LD_LIBRARY_PATH LD_LIBRARYN32_PATH LD_LIBRARYN64_PATH LD_LIBRARY_PATH_64 LD_PRELOAD XLIB_SKIP_ARGB_VISUALS
+
+"\$BF_DIST_BIN/\$BF_PROGRAM" \${1+"\$@"}
+exitcode=\$?
+exit \$exitcode
+EOF
+ chmod +x $RB/extra/blender-softwaregl
+
+ cat << EOF > $RB/extra/do_update-libs.sh
+#!/bin/sh
+
+BITS=\$1
+V="\`readlink /opt/lib/mesa | sed -r 's/mesa-//'\`"
+TMP=\`mktemp -d\`
+N="mesalibs\$1-\$V"
+
+if [ ! -f \$N.tar.bz2 ]; then
+ mkdir -p \$TMP/lib
+ cp -P /opt/lib/mesa/lib/libGL* \$TMP/lib
+ strip -s \$TMP/lib/*
+ tar -C \$TMP -cf \$N.tar lib
+ bzip2 \$N.tar
+
+ rm -f mesalibs\$BITS.tar,bz2
+ ln -s \$N.tar.bz2 mesalibs\$BITS.tar.bz2
+fi
+
+rm -rf \$TMP
+EOF
+ chmod +x $RB/extra/do_update-libs.sh
+
+ cat << EOF > $RB/extra/update-libs.sh
+#!/bin/sh
+
+P="/home/sources/release-builder/extra"
+CHROOT_PREFIX="buildbot_squeeze_"
+CHROOT32="\${CHROOT_PREFIX}i686"
+CHROOT64="\${CHROOT_PREFIX}x86_64"
+RUN32="schroot -c \$CHROOT32 -d \$P"
+RUN64="schroot -c \$CHROOT64 -d \$P"
+
+\$RUN64 ./do_update-libs.sh 64
+\$RUN32 ./do_update-libs.sh 32
+EOF
+ chmod +x $RB/extra/update-libs.sh
+
+ mkdir -p $RB/config
+ cp $SOURCES_PATH/blender/build_files/buildbot/config/* $RB/config
+
+ fi
+}
+
+INSTALL_SOURCES() {
+ SOURCES_PATH=$1
+
+ if [ ! -d "$SOURCES_PATH" ]; then
+ INFO "Creating sources directory"
+ mkdir -p "$SOURCES_PATH"
+ fi
+
+ if [ ! -d "$SOURCES_PATH/backport/binutils" ]; then
+ INFO "Downloading binutils"
+ mkdir -p "$SOURCES_PATH/backport/binutils"
+ wget -c $DEBIAN_MIRROR/pool/main/b/binutils/binutils_$BINUTILS_FV.diff.gz \
+ $DEBIAN_MIRROR/pool/main/b/binutils/binutils_$BINUTILS_FV.dsc \
+ $DEBIAN_MIRROR/pool/main/b/binutils/binutils_$BINUTILS_V.orig.tar.gz \
+ -P "$SOURCES_PATH/backport/binutils"
+ fi
+
+ if [ ! -d "$SOURCES_PATH/backport/gcc-4.7" ]; then
+ INFO "Downloading gcc-4.7"
+ mkdir -p "$SOURCES_PATH/backport/gcc-4.7"
+ wget -c $DEBIAN_MIRROR/pool/main/g/gcc-4.7/gcc-$GCC_FV.diff.gz \
+ $DEBIAN_MIRROR/pool/main/g/gcc-4.7/gcc-$GCC_FV.dsc \
+ $DEBIAN_MIRROR/pool/main/g/gcc-4.7/gcc-$GCC_V.orig.tar.gz \
+ -P "$SOURCES_PATH/backport/gcc-4.7"
+ fi
+
+ # JeMalloc
+ J="$SOURCES_PATH/packages/jemalloc-$JEMALLOC_V"
+ if [ ! -d "$J" ]; then
+ INFO "Downloading jemalloc-$JEMALLOC_V"
+ wget -c http://www.canonware.com/download/jemalloc/jemalloc-$JEMALLOC_V.tar.bz2 -P "$SOURCES_PATH/packages"
+ tar -C "$SOURCES_PATH/packages" -xf "$J.tar.bz2"
+ cat << EOF > "$J/0config.sh"
+#!/bin/sh
+
+./configure CC="gcc-4.7 -Wl,--as-needed" CXX="g++-4.7 -Wl,--as-needed" LDFLAGS="-pthread -static-libgcc" --prefix=/opt/lib/jemalloc-$JEMALLOC_V
+EOF
+ chmod +x "$J/0config.sh"
+ fi
+
+ # Spnav
+ S="$SOURCES_PATH/packages/libspnav-$SPNAV_V"
+ if [ ! -d "$S" ]; then
+ wget -c http://downloads.sourceforge.net/project/spacenav/spacenav%20library%20%28SDK%29/libspnav%200.2.2/libspnav-$SPNAV_V.tar.gz \
+ -P "$SOURCES_PATH/packages"
+ tar -C "$SOURCES_PATH/packages" -xf "$S.tar.gz"
+ cat << EOF > "$S/0config.sh"
+#!/bin/sh
+
+./configure --prefix=/opt/lib/libspnav-$SPNAV_V
+EOF
+ chmod +x "$S/0config.sh"
+ fi
+
+ # FFmpeg
+ F="$SOURCES_PATH/packages/ffmpeg-$FFMPEG_V"
+ if [ ! -d "$F" ]; then
+ INFO "Downloading FFmpeg-$FFMPEG_V"
+ wget -c http://ffmpeg.org/releases/ffmpeg-$FFMPEG_V.tar.bz2 -P "$SOURCES_PATH/packages"
+ tar -C "$SOURCES_PATH/packages" -xf "$F.tar.bz2"
+ cat << EOF > "$F/0config.sh"
+#!/bin/sh
+
+./configure \\
+ --cc="/usr/bin/gcc-4.7 -Wl,--as-needed" \\
+ --extra-ldflags="-pthread -static-libgcc" \\
+ --prefix=/opt/lib/ffmpeg-$FFMPEG_V \\
+ --enable-static \\
+ --enable-avfilter \\
+ --disable-vdpau \\
+ --disable-bzlib \\
+ --disable-libgsm \\
+ --enable-libschroedinger \\
+ --disable-libspeex \\
+ --enable-libtheora \\
+ --enable-libvorbis \\
+ --enable-pthreads \\
+ --enable-zlib \\
+ --enable-libvpx \\
+ --enable-stripping \\
+ --enable-runtime-cpudetect \\
+ --disable-vaapi \\
+ --enable-libopenjpeg \\
+ --disable-libfaac \\
+ --disable-nonfree \\
+ --enable-gpl \\
+ --disable-postproc \\
+ --disable-x11grab \\
+ --enable-libmp3lame \\
+ --disable-librtmp \\
+ --enable-libx264 \\
+ --enable-libxvid \\
+ --disable-libopencore-amrnb \\
+ --disable-libopencore-amrwb \\
+ --disable-libdc1394 \\
+ --disable-version3 \\
+ --disable-outdev=sdl \\
+ --disable-outdev=alsa \\
+ --disable-indev=sdl \\
+ --disable-indev=alsa \\
+ --disable-indev=jack \\
+ --disable-indev=lavfi
+
+# --enable-debug
+# --disable-optimizations
+# --disable-ffplay
+EOF
+ chmod +x "$F/0config.sh"
+ fi
+
+ # Boost
+ B="$SOURCES_PATH/packages/boost_$BOOST_V"
+ if [ ! -d "$B" ]; then
+ INFO "Downloading Boost-$BOOST_V"
+ b_d=`echo "$BOOST_V" | sed -r 's/_/./g'`
+ wget -c http://sourceforge.net/projects/boost/files/boost/$b_d/boost_$BOOST_V.tar.bz2/download -O "$B.tar.bz2"
+ tar -C "$SOURCES_PATH/packages" -xf "$B.tar.bz2"
+ fi
+
+ # Python
+ P="$SOURCES_PATH/packages/Python-$PYTHON_V"
+ if [ ! -d "$P" ]; then
+ INFO "Downloading Python-$PYTHON_V"
+ wget -c http://python.org/ftp/python/$PYTHON_V/Python-$PYTHON_V.tar.bz2 -P "$SOURCES_PATH/packages"
+ tar -C "$SOURCES_PATH/packages" -xf "$P.tar.bz2"
+ cat << EOF > "$P/0config.sh"
+#!/bin/sh
+
+# NOTE: this sounds strange, but make sure /dev/shm/ is writable by your user,
+# otherwise syncronization primitives wouldn't be included into python
+if [[ "`stat -c '%a' /dev/shm/`" != "777" ]]; then
+ echo "Error checking syncronization primitives"
+ exit 1
+fi
+
+./configure --prefix=/opt/lib/python-$PYTHON_V \\
+ --enable-ipv6 \\
+ --enable-loadable-sqlite-extensions \\
+ --with-dbmliborder=bdb \\
+ --with-wide-unicode \\
+ --with-computed-gotos \\
+ --with-pymalloc
+EOF
+ chmod +x "$P/0config.sh"
+ fi
+
+
+ # OpenImageIO
+ O="$SOURCES_PATH/packages/OpenImageIO-$OIIO_V"
+ if [ ! -d "$O" ]; then
+ INFO "Downloading OpenImageIO-$OIIO_V"
+ wget -c https://github.com/OpenImageIO/oiio/tarball/Release-$OIIO_V -O "$O.tar.gz"
+ tar -C "$SOURCES_PATH/packages" -xf "$O.tar.gz"
+ mv $SOURCES_PATH/packages/OpenImageIO-oiio* $O
+ mkdir $O/build
+ cat << EOF > "$O/build/prepare.sh"
+#!/bin/sh
+
+if file /bin/cp | grep -q '32-bit'; then
+ cflags="-fPIC -m32 -march=i686"
+else
+ cflags="-fPIC"
+fi
+
+cmake \\
+ -D CMAKE_BUILD_TYPE=Release \\
+ -D CMAKE_PREFIX_PATH=/opt/lib/oiio-$OIIO_V \\
+ -D CMAKE_INSTALL_PREFIX=/opt/lib/oiio-$OIIO_V \\
+ -D BUILDSTATIC=ON \\
+ -D USE_JASPER=OFF \\
+ -D CMAKE_CXX_FLAGS:STRING="\${cflags}" \\
+ -D CMAKE_C_FLAGS:STRING="\${cflags}" \\
+ -D CMAKE_EXE_LINKER_FLAGS='-lgcc_s -lgcc' \\
+ -D BOOST_ROOT=/opt/lib/boost \\
+ ../src
+EOF
+ chmod +x "$O/build/prepare.sh"
+ fi
+
+ # OpenColorIO
+ O="$SOURCES_PATH/packages/OpenColorIO-$OCIO_V"
+ if [ ! -d "$O" ]; then
+ INFO "Downloading OpenColorIO-$OCIO_V"
+ wget -c http://github.com/imageworks/OpenColorIO/tarball/v$OCIO_V -O "$O.tar.gz"
+ tar -C "$SOURCES_PATH/packages" -xf "$O.tar.gz"
+ mv $SOURCES_PATH/packages/imageworks-OpenColorIO* $O
+ mkdir $O/build
+ cat << EOF > "$O/build/prepare.sh"
+#!/bin/sh
+
+if file /bin/cp | grep -q '32-bit'; then
+ cflags="-fPIC -m32 -march=i686"
+else
+ cflags="-fPIC"
+fi
+
+cmake \\
+ -D CMAKE_BUILD_TYPE=Release \\
+ -D CMAKE_PREFIX_PATH=/opt/lib/ocio-1.0.7 \\
+ -D CMAKE_INSTALL_PREFIX=/opt/lib/ocio-1.0.7 \\
+ -D BUILDSTATIC=ON \\
+ -D CMAKE_CXX_FLAGS:STRING="\${cflags}" \\
+ -D CMAKE_C_FLAGS:STRING="\${cflags}" \\
+ -D CMAKE_EXE_LINKER_FLAGS='-lgcc_s -lgcc' \\
+ ..
+EOF
+
+ chmod +x "$O/build/prepare.sh"
+ fi
+
+ # Mesa
+ M="$SOURCES_PATH/packages/Mesa-$MESA_V"
+ if [ ! -d "$M" ]; then
+ INFO "Downloading Mesa-$MESA_V"
+ wget -c ftp://ftp.freedesktop.org/pub/mesa/$MESA_V/MesaLib-$MESA_V.tar.bz2 -P "$SOURCES_PATH/packages"
+ tar -C "$SOURCES_PATH/packages" -xf "$SOURCES_PATH/packages/MesaLib-$MESA_V.tar.bz2"
+ cat << EOF > "$M/0config.sh"
+#!/bin/sh
+
+OPTS="--with-driver=xlib \\
+ --disable-driglx-direct \\
+ --disable-egl \\
+ --enable-gallium-gbm=no \\
+ --enable-gallium-egl=no \\
+ --enable-gallium-llvm=no \\
+ --with-gallium-drivers=swrast \\
+ --with-dri-drivers=swrast \\
+ --prefix=/opt/lib/mesa-$MESA_V"
+
+if file /bin/cp | grep -q '32-bit'; then
+ ./configure CC="gcc-4.7 -Wl,--as-needed" CXX="g++-4.7 -Wl,--as-needed" LDFLAGS="-pthread -static-libgcc" \${OPTS} --enable-32-bit #--build=i486-linux-gnu
+else
+ ./configure CC="gcc-4.7 -Wl,--as-needed" CXX="g++-4.7 -Wl,--as-needed" LDFLAGS="-pthread -static-libgcc" \${OPTS}
+fi
+
+EOF
+ chmod +x "$M/0config.sh"
+ fi
+
+ # OpenAL
+ O="$SOURCES_PATH/packages/openal-soft-$OPENAL_V"
+ if [ ! -d "$O" ]; then
+ INFO "Downloading OpenAL-$OPENAL_V"
+ wget -c http://kcat.strangesoft.net/openal-releases/openal-soft-$OPENAL_V.tar.bz2 -P "$SOURCES_PATH/packages"
+ tar -C "$SOURCES_PATH/packages" -xf "$SOURCES_PATH/packages/openal-soft-$OPENAL_V.tar.bz2"
+ cat << EOF > "$O/build-openal.sh"
+#!/bin/sh
+
+DEB_CMAKE_OPTIONS="-DCMAKE_VERBOSE_MAKEFILE=ON \\
+ -DCMAKE_INSTALL_PREFIX=/opt/lib/openal-$OPENAL_V \\
+ -DCMAKE_BUILD_TYPE:String=Release \\
+ -DALSOFT_CONFIG=ON \\
+ -DLIBTYPE=STATIC .. "
+
+BUILD_TREE=./build-tree
+
+rm -rf "\${BUILD_TREE}"
+mkdir -p "\${BUILD_TREE}"
+cd "\${BUILD_TREE}"
+
+sh -c "cmake \`echo \$DEB_CMAKE_OPTIONS\`"
+make -j$THREADS
+make install
+EOF
+ chmod +x "$O/build-openal.sh"
+ fi
+
+ # OpenCollada
+ O="$SOURCES_PATH/packages/opencollada"
+ if [ ! -d "$O" ]; then
+ INFO "Checking out OpenCollada sources"
+ svn co http://opencollada.googlecode.com/svn/trunk $O
+
+ cat << EOF > "$O/build_all.sh"
+#!/bin/sh
+
+scons RELEASE=0 NOVALIDATION=1 XMLPARSER=libxmlnative PCRENATIVE=1 SHAREDLIB=0 -j ${THREADS} --clean
+scons RELEASE=1 NOVALIDATION=1 XMLPARSER=libxmlnative PCRENATIVE=1 SHAREDLIB=0 -j ${THREADS} --clean
+
+scons RELEASE=0 NOVALIDATION=1 XMLPARSER=libxmlnative PCRENATIVE=1 SHAREDLIB=0 -j ${THREADS}
+scons RELEASE=1 NOVALIDATION=1 XMLPARSER=libxmlnative PCRENATIVE=1 SHAREDLIB=0 -j ${THREADS}
+EOF
+
+ cat << EOF > "$O/prepare_lib-libxml.sh"
+#!/bin/bash
+
+src="./COLLADAStreamWriter/include
+./COLLADABaseUtils/include
+./COLLADABaseUtils/include/Math
+./COLLADAFramework/include
+./GeneratedSaxParser/include
+./COLLADASaxFrameworkLoader/include
+./COLLADASaxFrameworkLoader/include/generated14
+./COLLADASaxFrameworkLoader/include/generated15"
+
+if [ -z \$1 ]; then
+ arch="x86_64"
+else
+ arch=\$1
+fi
+
+libs="./GeneratedSaxParser/lib/posix/\${arch}/releaselibxml/libGeneratedSaxParser.a
+./Externals/MathMLSolver/lib/posix/\${arch}/release/libMathMLSolver.a
+./COLLADABaseUtils/lib/posix/\${arch}/release/libOpenCOLLADABaseUtils.a
+./COLLADAFramework/lib/posix/\${arch}/release/libOpenCOLLADAFramework.a
+./COLLADASaxFrameworkLoader/lib/posix/\${arch}/releaselibxmlNovalidation/libOpenCOLLADASaxFrameworkLoader.a
+./COLLADAStreamWriter/lib/posix/\${arch}/release/libOpenCOLLADAStreamWriter.a
+./Externals/UTF/lib/posix/\${arch}/release/libUTF.a
+./common/libBuffer/lib/posix/\${arch}/release/libbuffer.a
+./common/libftoa/lib/posix/\${arch}/release/libftoa.a"
+
+#./Externals/pcre/lib/posix/\${arch}/release/libpcre.a
+#./Externals/LibXML/lib/posix/\${arch}/release/libxml.a
+
+debug_libs="./GeneratedSaxParser/lib/posix/\${arch}/debuglibxml/libGeneratedSaxParser.a
+./Externals/MathMLSolver/lib/posix/\${arch}/debug/libMathMLSolver.a
+./COLLADABaseUtils/lib/posix/\${arch}/debug/libOpenCOLLADABaseUtils.a
+./COLLADAFramework/lib/posix/\${arch}/debug/libOpenCOLLADAFramework.a
+./COLLADASaxFrameworkLoader/lib/posix/\${arch}/debuglibxmlNovalidation/libOpenCOLLADASaxFrameworkLoader.a
+./COLLADAStreamWriter/lib/posix/\${arch}/debug/libOpenCOLLADAStreamWriter.a
+./Externals/UTF/lib/posix/\${arch}/debug/libUTF.a
+./common/libBuffer/lib/posix/\${arch}/debug/libbuffer.a
+./common/libftoa/lib/posix/\${arch}/debug/libftoa.a"
+
+#./Externals/pcre/lib/posix/\${arch}/debug/libpcre.a
+#./Externals/LibXML/lib/posix/\${arch}/debug/libxml.a
+
+d="opencollada-libxml"
+rm -rf \${d}
+mkdir -p \${d}/include
+
+for i in \${src}; do
+ mkdir -p \${d}/include/\${i}
+ cp \${i}/*.h \${d}/include/\${i}
+done
+
+mkdir \${d}/lib
+for i in \${libs}; do
+ echo "" > /dev/null
+ cp \${i} \${d}/lib
+done
+
+for i in \${debug_libs}; do
+ f=\`basename \${i}\`
+ o=\${f/\\.a/_d.a}
+ cp \${i} \${d}/lib/\${o}
+done
+
+rm -rf /opt/lib/opencollada
+mv \${d} /opt/lib/opencollada
+chown -R root:staff /opt/lib/opencollada
+EOF
+
+ chmod +x "$O/build_all.sh"
+ chmod +x "$O/prepare_lib-libxml.sh"
+ fi
+
+ # Blender
+ B="$SOURCES_PATH/blender"
+ if [ ! -d "$B" ]; then
+ INFO "Checking out Blender sources"
+ svn co https://svn.blender.org/svnroot/bf-blender/trunk/blender $B
+ fi
+
+ # CUDA Toolkit
+ C=$SOURCES_PATH/cudatoolkit
+ if [ ! -f "$C/$CUDA_32" ]; then
+ INFO "Downloading CUDA 32bit toolkit"
+ mkdir -p $C
+ wget -c http://developer.download.nvidia.com/compute/cuda/4_2/rel/toolkit/$CUDA_32 -P $C
+ fi
+
+ if [ ! -f "$C/$CUDA_64" ]; then
+ INFO "Downloading CUDA 64bit toolkit"
+ mkdir -p $C
+ wget -c http://developer.download.nvidia.com/compute/cuda/4_2/rel/toolkit/$CUDA_64 -P $C
+ fi
+
+ if [ ! -f $SOURCES_PATH/Readme.txt ]; then
+
+ cat << EOF > $SOURCES_PATH/Readme.txt
+This directory contains different things needed for Blender builds
+
+blender/: directory with blender's svnsnapshot
+
+blender-build/, blender-install/: build and install directories for
+ automated release creation
+
+buildbot-i686-slave/,
+buildbot-x86_64-slave/: buildbot slave environments for automated builds
+ (maybe it'll be better to move them to /home?)
+
+staticlibs/: set of static libs. Mostly needed to make static linking prioretized
+ under dynamic linking
+
+release-builder/: all stuff needed for release archives preparation
+
+Hope all this would help you.
+
+-Sergey-
+EOF
+ fi
+
+ INSTALL_RELEASE_BUILDER $SOURCES_PATH
+}
+
+DO_BACKPORT() {
+ CHROOT_ARCH=$1
+ CHROOT_PATH=$2
+
+ RUN="chroot $CHROOT_PATH"
+ P="/home/sources/backport"
+
+ # Backport fresh binutils
+ if [ `$RUN dpkg-query -W -f='${Version}\n' binutils | grep -c $BINUTILS_V` -eq "0" ]; then
+ INFO "Backporting binutils"
+ B="$P/binutils/binutils-$BINUTILS_V"
+ pkg="$P/binutils/binutils_${BINUTILS_FV}_amd64.deb"
+
+ if [ ! -d "$CHROOT_PATH/$B" ]; then
+ INFO "Unpacking binutils"
+ $RUN dpkg-source -x "$P/binutils/binutils_$BINUTILS_FV.dsc" "$B"
+ fi
+
+ if [ "$CHROOT_ARCH" = "i386" ]; then
+ pkg=`echo "$pkg" | sed -r 's/amd64/i386/g'`
+ fi
+
+ if [ ! -f "$CHROOT_PATH/$pkg" ]; then
+ INFO "Compiling binutils"
+ sed -ie 's/with_check := yes/with_check := no/' "$CHROOT_PATH/$B/debian/rules"
+ $RUN sh -c "cd '$B' && dpkg-buildpackage -rfakeroot -j$THREADS"
+ fi
+
+ INFO "Installing binutils"
+ $RUN dpkg -i "$pkg"
+
+ INFO "Cleaning binutils"
+ $RUN sh -c "cd '$B' && fakeroot debian/rules clean"
+ fi
+
+ # Install fresh gcc
+ if [ `$RUN dpkg-query -W -f='${Status}\n' gcc-4.7 2> /dev/null | grep -c installed` -eq "0" ]; then
+ INFO "Backporting gcc-4.7"
+ G="$P/gcc-4.7/gcc-$GCC_V"
+
+ pkg="cpp-4.7_4.7.1-7_amd64.deb gcc-4.7-base_4.7.1-7_amd64.deb \
+ libstdc++6-4.7-dev_4.7.1-7_amd64.deb libstdc++6_4.7.1-7_amd64.deb libgcc1_4.7.1-7_amd64.deb \
+ libgomp1_4.7.1-7_amd64.deb libitm1_4.7.1-7_amd64.deb libquadmath0_4.7.1-7_amd64.deb \
+ gcc-4.7_4.7.1-7_amd64.deb g++-4.7_4.7.1-7_amd64.deb"
+
+ if [ ! -d "$CHROOT_PATH/$G" ]; then
+ INFO "Unpacking gcc-4.7"
+ $RUN dpkg-source -x "$P/gcc-4.7/gcc-$GCC_FV.dsc" "$G"
+ fi
+
+ if [ "$CHROOT_ARCH" = "i386" ]; then
+ pkg=`echo "$pkg" | sed -r 's/amd64/i386/g'`
+ fi
+
+ ok=true
+ for x in `echo "$pkg"`; do
+ if [ ! -f "$CHROOT_PATH/$P/gcc-4.7/$x" ]; then
+ ok=false
+ break;
+ fi
+ done
+
+ if ! $ok; then
+ INFO "Compiling gcc-4.7"
+ sed -ie 's/#with_check := disabled by hand/with_check := disabled by hand/' "$CHROOT_PATH/$G/debian/rules.defs"
+ sed -ie 's/dpkg-dev (>= 1.16.0~ubuntu4)/dpkg-dev (>= 1.15.8)/' "$CHROOT_PATH/$G/debian/control"
+ sed -ie 's/doxygen (>= 1.7.2)/doxygen (>= 1.7.1)/' "$CHROOT_PATH/$G/debian/control"
+ sed -ie 's/libmpfr-dev (>= 3.0.0-9~)/libmpfr-dev (>= 3.0.0)/' "$CHROOT_PATH/$G/debian/control"
+ sed -ie 's/libc6-dev (>= 2.13-5)/libc6-dev (>= 2.11.3)/' "$CHROOT_PATH/$G/debian/control"
+ sed -ie 's/libgmp-dev (>= 2:5.0.1~)/libgmp3-dev (>= 2:4.3.2)/' "$CHROOT_PATH/$G/debian/control"
+ $RUN sh -c "cd '$G' && dpkg-buildpackage -rfakeroot"
+ fi
+
+ inst=""
+ for x in `echo "$pkg"`; do
+ inst="$inst $P/gcc-4.7/$x"
+ done
+
+ INFO "Installing gcc-4.7"
+ $RUN dpkg -i $inst
+
+ INFO "Cleaning gcc-4.7"
+ $RUN sh -c "cd '$G' && fakeroot debian/rules clean"
+ fi
+}
+
+DO_COMPILE() {
+ CHROOT_ARCH=$1
+ CHROOT_PATH=$2
+
+ RUN="chroot $CHROOT_PATH"
+ P="/home/sources/packages"
+ L="$CHROOT_PATH/opt/lib"
+
+ # JeMalloc
+ if [ ! -d "$L/jemalloc-$JEMALLOC_V" ]; then
+ INFO "Copmiling jemalloc-$JEMALLOC_V"
+ $RUN sh -c "cd '$P/jemalloc-$JEMALLOC_V' && ./0config.sh && make clean && make -j$THREADS && make install && make clean"
+
+ rm -f "$L/jemalloc"
+ ln -s "jemalloc-$JEMALLOC_V" "$L/jemalloc"
+ fi
+
+ # libspnav
+ if [ ! -d "$L/libspnav-$SPNAV_V" ]; then
+ INFO "Copmiling libspnav-$SPNAV_V"
+ mkdir -p "$L/libspnav-$SPNAV_V/lib"
+ mkdir -p "$L/libspnav-$SPNAV_V/include"
+ $RUN sh -c "cd '$P/libspnav-$SPNAV_V' && ./0config.sh && make clean && make -j$THREADS && make install && make clean"
+
+ rm -f "$L/libspnav"
+ ln -s "libspnav-$SPNAV_V" "$L/libspnav"
+ fi
+
+ # FFmpeg
+ if [ ! -d "$L/ffmpeg-$FFMPEG_V" ]; then
+ INFO "Copmiling ffmpeg-$FFMPEG_V"
+ $RUN sh -c "cd '$P/ffmpeg-$FFMPEG_V' && ./0config.sh && make clean && make -j$THREADS && make install && make clean"
+
+ rm -f "$L/ffmpeg"
+ ln -s "ffmpeg-$FFMPEG_V" "$L/ffmpeg"
+ fi
+
+ # Boost
+ V=`echo $BOOST_V | sed -r 's/_/./g'`
+ if [ ! -d "$L/boost-$V" ]; then
+ INFO "Copmiling boost-$V"
+ $RUN sh -c "cd '$P/boost_$BOOST_V' && ./bootstrap.sh && ./b2 --clean && ./b2 install --prefix='/opt/lib/boost-$V' && ./b2 --clean"
+
+ rm -f "$L/boost"
+ ln -s "boost-$V" "$L/boost"
+ fi
+
+ # OCIO
+ if [ ! -d "$L/ocio-$OCIO_V" ]; then
+ INFO "Copmiling ocio-$OCIO_V"
+ $RUN sh -c "cd '$P/OpenColorIO-$OCIO_V/build' && ./prepare.sh && make clean && make -j$THREADS && make install && make clean"
+
+ # Force linking against sttaic libs
+ rm -f $L/ocio-$OCIO_V/lib/*.so*
+
+ # Additional depencencies
+ cp $CHROOT_PATH/$P/OpenColorIO-$OCIO_V/build/ext/dist/lib/libtinyxml.a $L/ocio-$OCIO_V/lib
+ cp $CHROOT_PATH/$P/OpenColorIO-$OCIO_V/build/ext/dist/lib/libyaml-cpp.a $L/ocio-$OCIO_V/lib
+
+ rm -f "$L/ocio"
+ ln -s "ocio-$OCIO_V" "$L/ocio"
+ fi
+
+ # OIIO
+ if [ ! -d "$L/oiio-$OIIO_V" ]; then
+ INFO "Copmiling oiio-$OIIO_V"
+ $RUN sh -c "cd '$P/OpenImageIO-$OIIO_V/build' && ./prepare.sh && make clean && make -j$THREADS && make install && make clean"
+
+ rm -f "$L/oiio"
+ ln -s "oiio-$OIIO_V" "$L/oiio"
+ fi
+
+ # Python
+ if [ ! -d "$L/python-$PYTHON_V" ]; then
+ INFO "Copmiling Python-$PYTHON_V"
+
+ cat << EOF > $CHROOT_PATH/$P/Python-$PYTHON_V/Modules/Setup.local
+_md5 md5module.c
+
+_sha1 sha1module.c
+_sha256 sha256module.c
+_sha512 sha512module.c
+EOF
+
+ $RUN sh -c "cd '$P/Python-$PYTHON_V' && ./0config.sh && make clean && make -j$THREADS && make install && make clean"
+
+ rm -f "$L/python-$PYTHIN_V_SHORT"
+ ln -s "python-$PYTHON_V" "$L/python-$PYTHIN_V_SHORT"
+ fi
+
+ # Mesa
+ if [ ! -d "$L/mesa-$MESA_V" ]; then
+ INFO "Copmiling Mesa-$MESA_V"
+
+ $RUN sh -c "cd '$P/Mesa-$MESA_V' && ./0config.sh && make clean && make -j$THREADS && make install && make clean"
+
+ rm -f "$L/mesa"
+ ln -s "mesa-$MESA_V" "$L/mesa"
+ fi
+
+ # OpenAL
+ if [ ! -d "$L/openal-$OPENAL_V" ]; then
+ INFO "Copmiling openal-$OPENAL_V"
+
+ $RUN sh -c "cd '$P/openal-soft-$OPENAL_V' && ./build-openal.sh"
+
+ rm -f "$L/openal"
+ ln -s "openal-$OPENAL_V" "$L/openal"
+ fi
+
+ # OpenCollada
+ if [ ! -d "$L/opencollada" ]; then
+ INFO "Copmiling opencollada"
+
+ cat << EOF > "$CHROOT_PATH/$P/opencollada/collada.patch"
+Index: common/libBuffer/include/CommonBuffer.h
+===================================================================
+--- common/libBuffer/include/CommonBuffer.h (revision 876)
++++ common/libBuffer/include/CommonBuffer.h (working copy)
+@@ -12,6 +12,7 @@
+ #define __COMMON_BUFFER_H__
+
+ #include "CommonIBufferFlusher.h"
++#include "COLLADABUPlatform.h"
+
+ namespace Common
+ {
+Index: common/libBuffer/src/CommonLogFileBufferFlusher.cpp
+===================================================================
+--- common/libBuffer/src/CommonLogFileBufferFlusher.cpp (revision 876)
++++ common/libBuffer/src/CommonLogFileBufferFlusher.cpp (working copy)
+@@ -10,6 +10,34 @@
+
+ #include "CommonLogFileBufferFlusher.h"
+
++#include <stdio.h>
++#include <errno.h>
++
++#ifndef _WIN32
++FILE *_wfopen(const wchar_t *path, const char *mode)
++{
++ const wchar_t *src = path;
++ char *path_mbs;
++ int n;
++ FILE *file;
++
++ n = (int)wcsrtombs(NULL, &src, 0, NULL);
++
++ if (n < 0)
++ return NULL;
++
++ path_mbs = (char *)malloc(n + 1);
++ wcsrtombs(path_mbs, &path, n, NULL);
++ path_mbs[n] = 0;
++
++ file = fopen(path_mbs, mode);
++
++ free(path_mbs);
++
++ return file;
++}
++#endif
++
+ namespace Common
+ {
+ //--------------------------------------------------------------------
+@@ -35,7 +63,7 @@
+ #ifdef _WIN32
+ mError = (int)_wfopen_s( &stream, fileName, L"wb" );
+ #else
+- stream = _wfopen( fileName, L"wb" );
++ stream = _wfopen( fileName, "wb" );
+ mError = stream ? 0 : errno;
+ #endif
+ if ( !mError )
+@@ -65,7 +93,7 @@
+ #else
+ if ( mUseWideFileName )
+ {
+- stream = _wfopen( mWideFileName.c_str(), L"a" );
++ stream = _wfopen( mWideFileName.c_str(), "a" );
+ }
+ else
+ {
+Index: common/libBuffer/SConscript
+===================================================================
+--- common/libBuffer/SConscript (revision 876)
++++ common/libBuffer/SConscript (working copy)
+@@ -11,7 +11,7 @@
+ targetPath = outputDir + libName
+
+
+-incDirs = ['include/', '../libftoa/include']
++incDirs = ['include/', '../libftoa/include', '../../COLLADABaseUtils/include/', '../../Externals/UTF/include']
+
+
+ src = []
+EOF
+
+ # We're building in a chroot, architecture of host system would be used by scons
+ collada_arch="x86_64"
+
+ $RUN sh -c "cd '$P/opencollada' && svn revert . -R && cat collada.patch | patch -p0 && ./build_all.sh && ./prepare_lib-libxml.sh $collada_arch"
+ fi
+}
+
+ADD_REPO() {
+ CHROOT_PATH=$1
+ DESC=$2
+ REPO=$3
+ C="$CHROOT_PATH/etc/apt/sources.list"
+ RUN="chroot $CHROOT_PATH"
+
+ if [ `cat "$C" | grep -c "$REPO"` -eq "0" ]; then
+ INFO "Adding repo $DESC"
+ echo "" >> $C
+ echo "deb $REPO" >> $C
+ echo "deb-src $REPO" >> $C
+
+ INFO "Updating packages list"
+ $RUN apt-get update
+ fi
+}
+
+INSTALL_CHROOT() {
+ CHROOT_ARCH=$1
+ CHROOT_PATH=$2
+
+ RUN="chroot $CHROOT_PATH"
+
+ # Install fresh debian to a chroot
+ if [ ! -d "$CHROOT_PATH" ]; then
+
+ INFO "Installing Debian ${DEBIAN_BRANCH} to ${CHROOT_PATH}"
+ debootstrap --arch "${CHROOT_ARCH}" "${DEBIAN_BRANCH}" "${CHROOT_PATH}" "${DEBIAN_MIRROR}"
+ fi
+
+ # Configure users and groups
+
+ if [ `cat ${CHROOT_PATH}/etc/group | grep -c developers` -eq "0" ]; then
+ INFO "Creating gorup 'developers'"
+ $RUN groupadd -g 7001 developers
+ fi
+
+ if [ `mount | grep -c "$CHROOT_PATH/dev"` -eq "0" ]; then
+ INFO "Mounting devices from host system to chroot"
+
+ mount -t proc none $CHROOT_PATH/proc
+ mount -t auto -o bind /dev $CHROOT_PATH/dev
+ mount -t devpts -o mode=0620 none $CHROOT_PATH/dev/pts
+ fi
+
+ # Configure apt and install packages
+
+ if [ ! -f ${CHROOT_PATH}/etc/apt/apt.conf ]; then
+ INFO "Setting up apt to not use recommended packages (saves disk space)"
+
+ cat << EOF > "${CHROOT_PATH}/etc/apt/apt.conf"
+APT {
+ Default-Release "${DEBIAN_BRANCH}";
+ Install-Recommends "0";
+};
+EOF
+ fi
+
+ ADD_REPO $CHROOT_PATH "mirror.yandex.ru" "http://mirror.yandex.ru/debian-multimedia/ squeeze main non-free"
+ ADD_REPO $CHROOT_PATH "backports.debian.org" "http://backports.debian.org/debian-backports squeeze-backports main non-free"
+
+ $RUN apt-get upgrade
+
+ $RUN apt-get install -y --force-yes deb-multimedia-keyring libx264-dev libxvidcore4-dev libmp3lame-dev
+
+ if [ `$RUN dpkg-query -W -f='${Status}\n' locales | grep -c not-installed` -eq "1" ]; then
+ INFO "Configuring locales"
+ $RUN apt-get install -y locales
+ $RUN localedef -i en_US -f UTF-8 en_US.UTF-8
+ fi
+
+ INFO "Installing packages from repository"
+ $RUN apt-get install -y mc gcc g++ cmake python dpkg-dev build-essential autoconf bison \
+ flex gettext texinfo dejagnu quilt file lsb-release zlib1g-dev fakeroot debhelper \
+ g++-multilib libtool autoconf2.64 automake gawk lzma patchutils gperf sharutils \
+ libcloog-ppl-dev libmpc-dev libmpfr-dev libgmp3-dev autogen realpath chrpath doxygen \
+ graphviz gsfonts-x11 texlive-latex-base libelfg0-dev libx11-dev yasm libopenjpeg-dev \
+ libschroedinger-dev libtheora-dev libvorbis-dev libvpx-dev=$VPX_V \
+ libopenexr-dev libpng-dev libjpeg-dev libtiff-dev python-dev libbz2-dev libreadline-dev \
+ libsqlite3-dev liblzma-dev libncurses5-dev xutils-dev libxext-dev python-libxml2 \
+ libglu1-mesa-dev libfftw3-dev libfreetype6-dev libsdl1.2-dev libopenal-dev libjack-dev \
+ libxi-dev portaudio19-dev po4a subversion scons libpcre3-dev libexpat1-dev sudo \
+ expect
+
+ if [ $CHROOT_ARCH = "amd64" ]; then
+ $RUN apt-get install -y libc6-dev-i386 lib32gcc1
+ fi
+
+ # Configure sources directory
+ if [ ! -d "$CHROOT_PATH/home/sources" ]; then
+ INFO "Creating sources directory"
+ $RUN mkdir "/home/sources"
+ $RUN chmod 775 /home/sources
+ $RUN chown root:developers /home/sources
+ fi
+
+ # Bind directory from host system
+ if [ ! -d "$CHROOT_PATH/home/sources/backport" ]; then
+ INFO "Binding sources directory from host system to chroot"
+ mount -o bind "$SOURCES_PATH" "$CHROOT_PATH/home/sources"
+ fi
+
+ if [ "`$RUN getent passwd $USER_ID`" = "" ]; then
+ INFO "Adding default user to chroot"
+ login=`getent passwd $USER_ID | cut -d : -f 1`
+ $RUN useradd -d "/home/$login" -G developers,sudo -m -u $USER_ID "$login"
+ fi
+
+ # Backport packages
+ DO_BACKPORT "$CHROOT_ARCH" "$CHROOT_PATH"
+
+ # Set default compiler to gcc-4.7
+ if [ `readlink "$CHROOT_PATH/usr/bin/gcc"` != "gcc-4.7" ]; then
+ INFO "Setting gcc-4.7 as default compiler"
+ rm -f $CHROOT_PATH/usr/bin/gcc
+ rm -f $CHROOT_PATH/usr/bin/g++
+ ln -s gcc-4.7 $CHROOT_PATH/usr/bin/gcc
+ ln -s g++-4.7 $CHROOT_PATH/usr/bin/g++
+ fi
+
+ # Compile packages
+ DO_COMPILE "$CHROOT_ARCH" "$CHROOT_PATH"
+
+ # Install CUDA toolkit
+ if [ ! -d "$CHROOT_PATH/usr/local/cuda-$CUDA_V" ]; then
+ INFO "Installing CUDA toolkit"
+
+ if [ "$CHROOT_ARCH" = "amd64" ]; then
+ C="cudatoolkit_${CUDA_V}_linux_64_${CUDA_DISTR}.run"
+ else
+ C="cudatoolkit_${CUDA_V}_linux_32_${CUDA_DISTR}.run"
+ fi
+
+ rm -f $CHROOT_PATH/usr/local/cuda
+
+ chmod +x $CHROOT_PATH//home/sources/cudatoolkit/$C
+
+ $RUN /usr/bin/expect <<EOF
+ spawn /home/sources/cudatoolkit/$C
+ expect "Enter install path"
+ send "\n"
+ expect "Installation Complete"
+EOF
+
+ mv $CHROOT_PATH/usr/local/cuda $CHROOT_PATH/usr/local/cuda-$CUDA_V
+ ln -s cuda-$CUDA_V $CHROOT_PATH/usr/local/cuda
+ sudo ln -s /usr/bin/gcc-4.4 $CHROOT_PATH/usr/local/cuda/bin/gcc
+ fi
+
+ # Change permissions
+ INFO "Changing permissions on sources"
+ login=`$RUN getent passwd $USER_ID | cut -d : -f 1`
+ for x in /home/sources /opt/lib; do
+ $RUN chmod g+w -R $x
+ $RUN chown "$login:developers" -R $x
+ done
+}
+
+if ! which debootstrap > /dev/null 2>&1; then
+ ERROR "debootstrap command not found, can not create chroot environment"
+ ERROR "Use apt-get install debootstrap to install debootstrap"
+ exit 1
+fi
+
+if [ -z "$ENV_PATH" ]; then
+ ERROR "Incorrect environment directory is set"
+ exit 1
+fi
+
+INSTALL_SOURCES "$SOURCES_PATH"
+INSTALL_CHROOT amd64 "$AMD64_PATH"
+INSTALL_CHROOT i386 "$I686_PATH"
+
+INFO "Configurtion of build environment is completed!"
+echo "Add this lines to your /etc/fstab:"
+echo
+
+for x in $I686_PATH $AMD64_PATH; do
+ echo "none $x/proc proc auto 0 0"
+ echo "/dev $x/dev auto bind,auto 0 0"
+ echo "none $x/dev/pts devpts mode=0620,auto 0 0"
+ echo "/home/sources $x/home/sources auto bind,auto 0 0"
+ echo
+done
+
+echo "Add this lines to your /etc/schroot/schroot.conf:"
+echo
+login=`getent passwd $USER_ID | cut -d : -f 1`
+
+for x in $I686_PATH $AMD64_PATH; do
+ echo [`basename $x`]
+ echo "description=Linux buildbot environment"
+ echo "directory=$x"
+ echo "users=$login"
+ echo "root-groups=root"
+ echo
+done
diff --git a/build_files/buildbot/config/user-config-glibc211-i686.py b/build_files/buildbot/config/user-config-glibc211-i686.py
new file mode 100644
index 00000000000..23ab87a6ba3
--- /dev/null
+++ b/build_files/buildbot/config/user-config-glibc211-i686.py
@@ -0,0 +1,145 @@
+BF_BUILDDIR = '../blender-build/linux-glibc211-i686'
+BF_INSTALLDIR = '../blender-install/linux-glibc211-i686'
+BF_NUMJOBS = 2
+
+# Python configuration
+BF_PYTHON_VERSION = '3.3'
+BF_PYTHON_ABI_FLAGS = 'm'
+BF_PYTHON = '/opt/lib/python-3.3'
+
+WITH_BF_STATICPYTHON = True
+
+# OpenCollada configuration
+WITH_BF_COLLADA = True
+WITH_BF_STATICOPENCOLLADA=True
+BF_OPENCOLLADA = '/opt/lib/opencollada'
+BF_OPENCOLLADA_INC = '${BF_OPENCOLLADA}/include'
+BF_OPENCOLLADA_LIB_STATIC = '${BF_OPENCOLLADA}/lib/libOpenCOLLADAStreamWriter.a ' + \
+ '${BF_OPENCOLLADA}/lib/libOpenCOLLADASaxFrameworkLoader.a ' + \
+ '${BF_OPENCOLLADA}/lib/libOpenCOLLADAFramework.a ' + \
+ '${BF_OPENCOLLADA}/lib/libOpenCOLLADABaseUtils.a ' + \
+ '${BF_OPENCOLLADA}/lib/libGeneratedSaxParser.a ' + \
+ '${BF_OPENCOLLADA}/lib/libUTF.a ${BF_OPENCOLLADA}/lib/libMathMLSolver.a ' + \
+ '${BF_OPENCOLLADA}/lib/libbuffer.a ${BF_OPENCOLLADA}/lib/libftoa.a ' + \
+ '/usr/lib/libxml2.a /usr/lib/libexpat.a /usr/lib/libpcre.a'
+BF_OPENCOLLADA_LIBPATH = '${BF_OPENCOLLADA}/lib /home/sources/staticlibs/lib64'
+BF_PCRE_LIB = ''
+BF_EXPAT_LIB = ''
+
+# FFMPEG configuration
+WITH_BF_FFMPEG = True
+WITH_BF_STATICFFMPEG = True
+
+BF_FFMPEG = '/opt/lib/ffmpeg'
+BF_FFMPEG_LIBPATH = '${BF_FFMPEG}/lib'
+BF_FFMPEG_LIB_STATIC = '${BF_FFMPEG_LIBPATH}/libavformat.a ${BF_FFMPEG_LIBPATH}/libavdevice.a ' + \
+ '${BF_FFMPEG_LIBPATH}/libavfilter.a ${BF_FFMPEG_LIBPATH}/libavcodec.a ${BF_FFMPEG_LIBPATH}/libavutil.a ' + \
+ '${BF_FFMPEG_LIBPATH}/libswscale.a ${BF_FFMPEG_LIBPATH}/libswresample.a ' + \
+ '/usr/lib/libxvidcore.a /usr/lib/libx264.a /usr/lib/libmp3lame.a /usr/lib/libvpx.a /usr/lib/libvorbis.a ' + \
+ '/usr/lib/libogg.a /usr/lib/libvorbisenc.a /usr/lib/libtheora.a /usr/lib/libschroedinger-1.0.a ' + \
+ '/usr/lib/liborc-0.4.a'
+
+# Don't depend on system's libstdc++
+WITH_BF_STATICCXX = True
+BF_CXX_LIB_STATIC = '/usr/lib/gcc/i486-linux-gnu/4.7.1/libstdc++.a'
+
+WITH_BF_OPENAL = True
+WITH_BF_STATICOPENAL = True
+BF_OPENAL = '/opt/lib/openal'
+BF_OPENAL_LIB_STATIC = '/opt/lib/openal/lib/libopenal.a'
+
+WITH_BF_GETTEXT_STATIC = True
+
+WITH_BF_FREETYPE_STATIC = False
+
+WITH_BF_OPENEXR = True
+WITH_BF_STATICOPENEXR = True
+
+WITH_BF_TIFF = True
+WITH_BF_STATICTIFF = True
+BF_TIFF_LIB_STATIC = '${BF_TIFF}/lib/libtiff.a'
+
+WITH_BF_JPEG = True
+WITH_BF_STATICJPEG = True
+BF_JPEG_LIB_STATIC= '${BF_JPEG}/lib/libjpeg.a'
+
+WITH_BF_PNG = True
+WITH_BF_STATICPNG = True
+BF_PNG_LIB_STATIC = '${BF_PNG}/lib/libpng.a'
+
+WITH_BF_STATICLIBSAMPLERATE = True
+
+WITH_BF_ZLIB = True
+WITH_BF_STATICZLIB = True
+BF_ZLIB_LIB_STATIC = '${BF_ZLIB}/lib/libz.a'
+
+WITH_BF_SDL = True
+WITH_BF_OGG = True
+
+WITH_BF_OPENMP = True
+WITH_BF_STATICOPENMP = True
+BF_OPENMP_LIB_STATIC = '/usr/lib/gcc/i486-linux-gnu/4.7/libgomp.a'
+
+WITH_BF_GAMEENGINE = True
+WITH_BF_BULLET = True
+
+# Blender player (would be enabled in it's own config)
+WITH_BF_PLAYER = False
+
+# Use jemalloc memory manager
+WITH_BF_JEMALLOC = True
+WITH_BF_STATICJEMALLOC = True
+BF_JEMALLOC = '/opt/lib/jemalloc'
+BF_JEMALLOC_LIBPATH = '${BF_JEMALLOC}/lib'
+
+# Use 3d mouse library
+WITH_BF_3DMOUSE = True
+WITH_BF_STATIC3DMOUSE = True
+BF_3DMOUSE = '/opt/lib/libspnav'
+BF_3DMOUSE_LIBPATH = '${BF_3DMOUSE}/lib'
+
+# FFT
+WITH_BF_FFTW3 = True
+WITH_BF_STATICFFTW3 = True
+
+# JACK
+WITH_BF_JACK = True
+WITH_BF_STATICJACK = True
+BF_JACK_LIB_STATIC = '${BF_ZLIB}/lib/libjack.a'
+
+# Cycles
+WITH_BF_CYCLES = True
+WITH_BF_CYCLES_CUDA_BINARIES = True
+#BF_CYCLES_CUDA_BINARIES_ARCH = ['sm_13', 'sm_20', 'sm_21', 'sm_30']
+BF_CYCLES_CUDA_BINARIES_ARCH = ['sm_20', 'sm_21', 'sm_30']
+
+WITH_BF_OIIO = True
+WITH_BF_STATICOIIO = True
+BF_OIIO = '/opt/lib/oiio'
+BF_OIIO_INC = '${BF_OIIO}/include'
+BF_OIIO_LIB_STATIC = '${BF_OIIO_LIBPATH}/libOpenImageIO.a ${BF_OPENEXR}/lib/libIlmImf.a ${BF_JPEG}/lib/libjpeg.a'
+BF_OIIO_LIBPATH = '${BF_OIIO}/lib'
+
+# Color management
+WITH_BF_OCIO = True
+WITH_BF_STATICOCIO = True
+BF_OCIO = '/opt/lib/ocio'
+BF_OCIO_INC = '${BF_OCIO}/include'
+BF_OCIO_LIB_STATIC = '${BF_OCIO_LIBPATH}/libOpenColorIO.a ${BF_OCIO_LIBPATH}/libtinyxml.a ${BF_OCIO_LIBPATH}/libyaml-cpp.a'
+BF_OCIO_LIBPATH = '${BF_OCIO}/lib'
+
+WITH_BF_BOOST = True
+WITH_BF_STATICBOOST = True
+BF_BOOST = '/opt/lib/boost'
+BF_BOOST_INC = '${BF_BOOST}/include'
+BF_BOOST_LIB_STATIC = '${BF_BOOST_LIBPATH}/libboost_filesystem.a ${BF_BOOST_LIBPATH}/libboost_date_time.a ' + \
+ '${BF_BOOST_LIBPATH}/libboost_regex.a ${BF_BOOST_LIBPATH}/libboost_system.a ${BF_BOOST_LIBPATH}/libboost_thread.a'
+BF_BOOST_LIBPATH = '${BF_BOOST}/lib'
+
+# Ocean Simulation
+WITH_BF_OCEANSIM = True
+
+# Compilation and optimization
+BF_DEBUG = False
+REL_CCFLAGS = ['-O2', '-msse', '-msse2'] # C & C++
+PLATFORM_LINKFLAGS = ['-lrt']
diff --git a/build_files/buildbot/config/user-config-glibc211-x86_64.py b/build_files/buildbot/config/user-config-glibc211-x86_64.py
new file mode 100644
index 00000000000..84899cc3848
--- /dev/null
+++ b/build_files/buildbot/config/user-config-glibc211-x86_64.py
@@ -0,0 +1,144 @@
+BF_BUILDDIR = '../blender-build/linux-glibc211-x86_64'
+BF_INSTALLDIR = '../blender-install/linux-glibc211-x86_64'
+BF_NUMJOBS = 2
+
+# Python configuration
+BF_PYTHON_VERSION = '3.3'
+BF_PYTHON_ABI_FLAGS = 'm'
+BF_PYTHON = '/opt/lib/python-3.3'
+
+WITH_BF_STATICPYTHON = True
+
+# OpenCollada configuration
+WITH_BF_COLLADA = True
+WITH_BF_STATICOPENCOLLADA=True
+BF_OPENCOLLADA = '/opt/lib/opencollada'
+BF_OPENCOLLADA_INC = '${BF_OPENCOLLADA}/include'
+BF_OPENCOLLADA_LIB_STATIC = '${BF_OPENCOLLADA}/lib/libOpenCOLLADAStreamWriter.a ' + \
+ '${BF_OPENCOLLADA}/lib/libOpenCOLLADASaxFrameworkLoader.a ' + \
+ '${BF_OPENCOLLADA}/lib/libOpenCOLLADAFramework.a ' + \
+ '${BF_OPENCOLLADA}/lib/libOpenCOLLADABaseUtils.a ' + \
+ '${BF_OPENCOLLADA}/lib/libGeneratedSaxParser.a ' + \
+ '${BF_OPENCOLLADA}/lib/libUTF.a ${BF_OPENCOLLADA}/lib/libMathMLSolver.a ' + \
+ '${BF_OPENCOLLADA}/lib/libbuffer.a ${BF_OPENCOLLADA}/lib/libftoa.a ' + \
+ '/usr/lib/libxml2.a /usr/lib/libexpat.a /usr/lib/libpcre.a'
+BF_OPENCOLLADA_LIBPATH = '${BF_OPENCOLLADA}/lib /home/sources/staticlibs/lib64'
+BF_PCRE_LIB = ''
+BF_EXPAT_LIB = ''
+
+# FFMPEG configuration
+WITH_BF_FFMPEG = True
+WITH_BF_STATICFFMPEG = True
+
+BF_FFMPEG = '/opt/lib/ffmpeg'
+BF_FFMPEG_LIBPATH = '${BF_FFMPEG}/lib'
+BF_FFMPEG_LIB_STATIC = '${BF_FFMPEG_LIBPATH}/libavformat.a ${BF_FFMPEG_LIBPATH}/libavdevice.a ' + \
+ '${BF_FFMPEG_LIBPATH}/libavfilter.a ${BF_FFMPEG_LIBPATH}/libavcodec.a ${BF_FFMPEG_LIBPATH}/libavutil.a ' + \
+ '${BF_FFMPEG_LIBPATH}/libswscale.a ${BF_FFMPEG_LIBPATH}/libswresample.a ' + \
+ '/usr/lib/libxvidcore.a /usr/lib/libx264.a /usr/lib/libmp3lame.a /usr/lib/libvpx.a /usr/lib/libvorbis.a ' + \
+ '/usr/lib/libogg.a /usr/lib/libvorbisenc.a /usr/lib/libtheora.a /usr/lib/libschroedinger-1.0.a ' + \
+ '/usr/lib/liborc-0.4.a'
+
+# Don't depend on system's libstdc++
+WITH_BF_STATICCXX = True
+BF_CXX_LIB_STATIC = '/usr/lib/gcc/x86_64-linux-gnu/4.7.1/libstdc++.a'
+
+WITH_BF_OPENAL = True
+WITH_BF_STATICOPENAL = True
+BF_OPENAL = '/opt/lib/openal'
+BF_OPENAL_LIB_STATIC = '/opt/lib/openal/lib/libopenal.a'
+
+WITH_BF_GETTEXT_STATIC = True
+
+WITH_BF_FREETYPE_STATIC = False
+
+WITH_BF_OPENEXR = True
+WITH_BF_STATICOPENEXR = True
+
+WITH_BF_TIFF = True
+WITH_BF_STATICTIFF = True
+BF_TIFF_LIB_STATIC = '${BF_TIFF}/lib/libtiff.a'
+
+WITH_BF_JPEG = True
+WITH_BF_STATICJPEG = True
+BF_JPEG_LIB_STATIC= '${BF_JPEG}/lib/libjpeg.a'
+
+WITH_BF_PNG = True
+WITH_BF_STATICPNG = True
+BF_PNG_LIB_STATIC = '${BF_PNG}/lib/libpng.a'
+
+WITH_BF_STATICLIBSAMPLERATE = True
+
+WITH_BF_ZLIB = True
+WITH_BF_STATICZLIB = True
+BF_ZLIB_LIB_STATIC = '${BF_ZLIB}/lib/libz.a'
+
+WITH_BF_SDL = True
+WITH_BF_OGG = True
+
+WITH_BF_OPENMP = True
+WITH_BF_STATICOPENMP = True
+BF_OPENMP_LIB_STATIC = '/usr/lib/gcc/x86_64-linux-gnu/4.7/libgomp.a'
+
+WITH_BF_GAMEENGINE = True
+WITH_BF_BULLET = True
+
+# Blender player (would be enabled in it's own config)
+WITH_BF_PLAYER = False
+
+# Use jemalloc memory manager
+WITH_BF_JEMALLOC = True
+WITH_BF_STATICJEMALLOC = True
+BF_JEMALLOC = '/opt/lib/jemalloc'
+BF_JEMALLOC_LIBPATH = '${BF_JEMALLOC}/lib'
+
+# Use 3d mouse library
+WITH_BF_3DMOUSE = True
+WITH_BF_STATIC3DMOUSE = True
+BF_3DMOUSE = '/opt/lib/libspnav'
+BF_3DMOUSE_LIBPATH = '${BF_3DMOUSE}/lib'
+
+# FFT
+WITH_BF_FFTW3 = True
+WITH_BF_STATICFFTW3 = True
+
+# JACK
+WITH_BF_JACK = True
+WITH_BF_STATICJACK = True
+BF_JACK_LIB_STATIC = '${BF_ZLIB}/lib/libjack.a'
+
+# Cycles
+WITH_BF_CYCLES = True
+WITH_BF_CYCLES_CUDA_BINARIES = True
+BF_CYCLES_CUDA_BINARIES_ARCH = ['sm_13', 'sm_20', 'sm_21', 'sm_30']
+
+WITH_BF_OIIO = True
+WITH_BF_STATICOIIO = True
+BF_OIIO = '/opt/lib/oiio'
+BF_OIIO_INC = '${BF_OIIO}/include'
+BF_OIIO_LIB_STATIC = '${BF_OIIO_LIBPATH}/libOpenImageIO.a ${BF_OPENEXR}/lib/libIlmImf.a ${BF_JPEG}/lib/libjpeg.a'
+BF_OIIO_LIBPATH = '${BF_OIIO}/lib'
+
+# Color management
+WITH_BF_OCIO = True
+WITH_BF_STATICOCIO = True
+BF_OCIO = '/opt/lib/ocio'
+BF_OCIO_INC = '${BF_OCIO}/include'
+BF_OCIO_LIB_STATIC = '${BF_OCIO_LIBPATH}/libOpenColorIO.a ${BF_OCIO_LIBPATH}/libtinyxml.a ${BF_OCIO_LIBPATH}/libyaml-cpp.a'
+BF_OCIO_LIBPATH = '${BF_OCIO}/lib'
+
+WITH_BF_BOOST = True
+WITH_BF_STATICBOOST = True
+BF_BOOST = '/opt/lib/boost'
+BF_BOOST_INC = '${BF_BOOST}/include'
+BF_BOOST_LIB_STATIC = '${BF_BOOST_LIBPATH}/libboost_filesystem.a ${BF_BOOST_LIBPATH}/libboost_date_time.a ' + \
+ '${BF_BOOST_LIBPATH}/libboost_regex.a ${BF_BOOST_LIBPATH}/libboost_system.a ${BF_BOOST_LIBPATH}/libboost_thread.a'
+BF_BOOST_LIBPATH = '${BF_BOOST}/lib'
+
+# Ocean Simulation
+WITH_BF_OCEANSIM = True
+
+# Compilation and optimization
+BF_DEBUG = False
+REL_CCFLAGS = ['-O2', '-msse', '-msse2'] # C & C++
+PLATFORM_LINKFLAGS = ['-lrt']
diff --git a/build_files/buildbot/config/user-config-i686.py b/build_files/buildbot/config/user-config-glibc27-i686.py
index b07dd505369..04b83253678 100644
--- a/build_files/buildbot/config/user-config-i686.py
+++ b/build_files/buildbot/config/user-config-glibc27-i686.py
@@ -97,7 +97,8 @@ WITH_BF_JACK = True
# Cycles
WITH_BF_CYCLES = True
WITH_BF_CYCLES_CUDA_BINARIES = True
-BF_CYCLES_CUDA_BINARIES_ARCH = ['sm_13', 'sm_20', 'sm_21', 'sm_30']
+#BF_CYCLES_CUDA_BINARIES_ARCH = ['sm_13', 'sm_20', 'sm_21', 'sm_30']
+BF_CYCLES_CUDA_BINARIES_ARCH = ['sm_20', 'sm_21', 'sm_30']
WITH_BF_OIIO = True
WITH_BF_STATICOIIO = True
@@ -106,6 +107,14 @@ BF_OIIO_INC = '${BF_OIIO}/include'
BF_OIIO_LIB_STATIC = '${BF_OIIO_LIBPATH}/libOpenImageIO.a ${BF_OPENEXR}/lib/libIlmImf.a'
BF_OIIO_LIBPATH = '${BF_OIIO}/lib'
+# Color management
+WITH_BF_OCIO = True
+WITH_BF_STATICOCIO = True
+BF_OCIO = '/opt/ocio'
+BF_OCIO_INC = '${BF_OCIO}/include'
+BF_OCIO_LIB_STATIC = '${BF_OCIO_LIBPATH}/libOpenColorIO.a ${BF_OCIO_LIBPATH}/libtinyxml.a ${BF_OCIO_LIBPATH}/libyaml-cpp.a'
+BF_OCIO_LIBPATH = '${BF_OCIO}/lib'
+
WITH_BF_BOOST = True
WITH_BF_STATICBOOST = True
BF_BOOST = '/opt/boost'
diff --git a/build_files/buildbot/config/user-config-x86_64.py b/build_files/buildbot/config/user-config-glibc27-x86_64.py
index 5905a9c29dd..070e62b2f20 100644
--- a/build_files/buildbot/config/user-config-x86_64.py
+++ b/build_files/buildbot/config/user-config-glibc27-x86_64.py
@@ -106,6 +106,14 @@ BF_OIIO_INC = '${BF_OIIO}/include'
BF_OIIO_LIB_STATIC = '${BF_OIIO_LIBPATH}/libOpenImageIO.a ${BF_OPENEXR}/lib/libIlmImf.a'
BF_OIIO_LIBPATH = '${BF_OIIO}/lib'
+# Color management
+WITH_BF_OCIO = True
+WITH_BF_STATICOCIO = True
+BF_OCIO = '/opt/ocio'
+BF_OCIO_INC = '${BF_OCIO}/include'
+BF_OCIO_LIB_STATIC = '${BF_OCIO_LIBPATH}/libOpenColorIO.a ${BF_OCIO_LIBPATH}/libtinyxml.a ${BF_OCIO_LIBPATH}/libyaml-cpp.a'
+BF_OCIO_LIBPATH = '${BF_OCIO}/lib'
+
WITH_BF_BOOST = True
WITH_BF_STATICBOOST = True
BF_BOOST = '/opt/boost'
diff --git a/build_files/buildbot/config/user-config-player-glibc211-i686.py b/build_files/buildbot/config/user-config-player-glibc211-i686.py
new file mode 100644
index 00000000000..3ac061d934f
--- /dev/null
+++ b/build_files/buildbot/config/user-config-player-glibc211-i686.py
@@ -0,0 +1,112 @@
+BF_BUILDDIR = '../blender-build/linux-glibc211-i686'
+BF_INSTALLDIR = '../blender-install/linux-glibc211-i686'
+BF_NUMJOBS = 2
+
+# Python configuration
+BF_PYTHON_VERSION = '3.3'
+BF_PYTHON_ABI_FLAGS = 'm'
+BF_PYTHON = '/opt/lib/python-3.3'
+
+WITH_BF_STATICPYTHON = True
+
+# OpenCollada configuration
+WITH_BF_COLLADA = False
+
+# FFMPEG configuration
+WITH_BF_FFMPEG = True
+WITH_BF_STATICFFMPEG = True
+
+BF_FFMPEG = '/opt/lib/ffmpeg'
+BF_FFMPEG_LIBPATH = '${BF_FFMPEG}/lib'
+BF_FFMPEG_LIB_STATIC = '${BF_FFMPEG_LIBPATH}/libavformat.a ${BF_FFMPEG_LIBPATH}/libavdevice.a ' + \
+ '${BF_FFMPEG_LIBPATH}/libavfilter.a ${BF_FFMPEG_LIBPATH}/libavcodec.a ${BF_FFMPEG_LIBPATH}/libavutil.a ' + \
+ '${BF_FFMPEG_LIBPATH}/libswscale.a ${BF_FFMPEG_LIBPATH}/libswresample.a ' + \
+ '/usr/lib/libxvidcore.a /usr/lib/libx264.a /usr/lib/libmp3lame.a /usr/lib/libvpx.a /usr/lib/libvorbis.a ' + \
+ '/usr/lib/libogg.a /usr/lib/libvorbisenc.a /usr/lib/libtheora.a /usr/lib/libschroedinger-1.0.a ' + \
+ '/usr/lib/liborc-0.4.a'
+
+# Don't depend on system's libstdc++
+WITH_BF_STATICCXX = True
+BF_CXX_LIB_STATIC = '/usr/lib/gcc/i486-linux-gnu/4.7.1/libstdc++.a'
+
+WITH_BF_OPENAL = True
+WITH_BF_STATICOPENAL = True
+BF_OPENAL = '/opt/lib/openal'
+BF_OPENAL_LIB_STATIC = '/opt/lib/openal/lib/libopenal.a'
+
+WITH_BF_GETTEXT_STATIC = True
+
+WITH_BF_FREETYPE_STATIC = False
+
+WITH_BF_OPENEXR = True
+WITH_BF_STATICOPENEXR = True
+
+WITH_BF_TIFF = True
+WITH_BF_STATICTIFF = True
+BF_TIFF_LIB_STATIC = '${BF_TIFF}/lib/libtiff.a'
+
+WITH_BF_JPEG = True
+WITH_BF_STATICJPEG = True
+BF_JPEG_LIB_STATIC= '${BF_JPEG}/lib/libjpeg.a'
+
+WITH_BF_STATICLIBSAMPLERATE = True
+
+WITH_BF_PNG = True
+WITH_BF_STATICPNG = True
+BF_PNG_LIB_STATIC = '${BF_PNG}/lib/libpng.a'
+
+WITH_BF_ZLIB = True
+WITH_BF_STATICZLIB = True
+BF_ZLIB_LIB_STATIC = '${BF_ZLIB}/lib/libz.a'
+
+WITH_BF_SDL = True
+WITH_BF_OGG = False
+
+WITH_BF_OPENMP = True
+WITH_BF_STATICOPENMP = True
+BF_OPENMP_LIB_STATIC = '/usr/lib/gcc/i486-linux-gnu/4.7/libgomp.a'
+
+WITH_BF_GAMEENGINE = True
+WITH_BF_BULLET = True
+
+# Do not build blender when building blenderplayer
+WITH_BF_NOBLENDER = True
+WITH_BF_PLAYER = True
+
+# Use jemalloc memory manager
+WITH_BF_JEMALLOC = True
+WITH_BF_STATICJEMALLOC = True
+BF_JEMALLOC = '/opt/lib/jemalloc'
+BF_JEMALLOC_LIBPATH = '${BF_JEMALLOC}/lib'
+
+# Use 3d mouse library
+WITH_BF_3DMOUSE = True
+WITH_BF_STATIC3DMOUSE = True
+BF_3DMOUSE = '/opt/lib/libspnav'
+BF_3DMOUSE_LIBPATH = '${BF_3DMOUSE}/lib'
+
+# Color management
+WITH_BF_OCIO = True
+WITH_BF_STATICOCIO = True
+BF_OCIO = '/opt/lib/ocio'
+BF_OCIO_INC = '${BF_OCIO}/include'
+BF_OCIO_LIB_STATIC = '${BF_OCIO_LIBPATH}/libOpenColorIO.a ${BF_OCIO_LIBPATH}/libtinyxml.a ${BF_OCIO_LIBPATH}/libyaml-cpp.a'
+BF_OCIO_LIBPATH = '${BF_OCIO}/lib'
+
+# JACK
+WITH_BF_JACK = True
+WITH_BF_STATICJACK = True
+BF_JACK_LIB_STATIC = '${BF_ZLIB}/lib/libjack.a'
+
+# Motion Tracking
+WITH_BF_LIBMV = False
+
+# Ocean Simulation
+WITH_BF_FFTW3 = True
+WITH_BF_STATICFFTW3 = True
+WITH_BF_OCEANSIM = True
+
+# Compilation and optimization
+BF_DEBUG = False
+REL_CCFLAGS = ['-O2', '-msse', '-msse2'] # C & C++
+PLATFORM_LINKFLAGS = ['-lrt']
diff --git a/build_files/buildbot/config/user-config-player-glibc211-x86_64.py b/build_files/buildbot/config/user-config-player-glibc211-x86_64.py
new file mode 100644
index 00000000000..08d277edb7b
--- /dev/null
+++ b/build_files/buildbot/config/user-config-player-glibc211-x86_64.py
@@ -0,0 +1,112 @@
+BF_BUILDDIR = '../blender-build/linux-glibc211-x86_64'
+BF_INSTALLDIR = '../blender-install/linux-glibc211-x86_64'
+BF_NUMJOBS = 2
+
+# Python configuration
+BF_PYTHON_VERSION = '3.3'
+BF_PYTHON_ABI_FLAGS = 'm'
+BF_PYTHON = '/opt/lib/python-3.3'
+
+WITH_BF_STATICPYTHON = True
+
+# OpenCollada configuration
+WITH_BF_COLLADA = False
+
+# FFMPEG configuration
+WITH_BF_FFMPEG = True
+WITH_BF_STATICFFMPEG = True
+
+BF_FFMPEG = '/opt/lib/ffmpeg'
+BF_FFMPEG_LIBPATH = '${BF_FFMPEG}/lib'
+BF_FFMPEG_LIB_STATIC = '${BF_FFMPEG_LIBPATH}/libavformat.a ${BF_FFMPEG_LIBPATH}/libavdevice.a ' + \
+ '${BF_FFMPEG_LIBPATH}/libavfilter.a ${BF_FFMPEG_LIBPATH}/libavcodec.a ${BF_FFMPEG_LIBPATH}/libavutil.a ' + \
+ '${BF_FFMPEG_LIBPATH}/libswscale.a ${BF_FFMPEG_LIBPATH}/libswresample.a ' + \
+ '/usr/lib/libxvidcore.a /usr/lib/libx264.a /usr/lib/libmp3lame.a /usr/lib/libvpx.a /usr/lib/libvorbis.a ' + \
+ '/usr/lib/libogg.a /usr/lib/libvorbisenc.a /usr/lib/libtheora.a /usr/lib/libschroedinger-1.0.a ' + \
+ '/usr/lib/liborc-0.4.a'
+
+# Don't depend on system's libstdc++
+WITH_BF_STATICCXX = True
+BF_CXX_LIB_STATIC = '/usr/lib/gcc/x86_64-linux-gnu/4.7.1/libstdc++.a'
+
+WITH_BF_OPENAL = True
+WITH_BF_STATICOPENAL = True
+BF_OPENAL = '/opt/lib/openal'
+BF_OPENAL_LIB_STATIC = '/opt/lib/openal/lib/libopenal.a'
+
+WITH_BF_GETTEXT_STATIC = True
+
+WITH_BF_FREETYPE_STATIC = False
+
+WITH_BF_OPENEXR = True
+WITH_BF_STATICOPENEXR = True
+
+WITH_BF_TIFF = True
+WITH_BF_STATICTIFF = True
+BF_TIFF_LIB_STATIC = '${BF_TIFF}/lib/libtiff.a'
+
+WITH_BF_JPEG = True
+WITH_BF_STATICJPEG = True
+BF_JPEG_LIB_STATIC= '${BF_JPEG}/lib/libjpeg.a'
+
+WITH_BF_STATICLIBSAMPLERATE = True
+
+WITH_BF_PNG = True
+WITH_BF_STATICPNG = True
+BF_PNG_LIB_STATIC = '${BF_PNG}/lib/libpng.a'
+
+WITH_BF_ZLIB = True
+WITH_BF_STATICZLIB = True
+BF_ZLIB_LIB_STATIC = '${BF_ZLIB}/lib/libz.a'
+
+WITH_BF_SDL = True
+WITH_BF_OGG = False
+
+WITH_BF_OPENMP = True
+WITH_BF_STATICOPENMP = True
+BF_OPENMP_LIB_STATIC = '/usr/lib/gcc/x86_64-linux-gnu/4.7/libgomp.a'
+
+WITH_BF_GAMEENGINE = True
+WITH_BF_BULLET = True
+
+# Do not build blender when building blenderplayer
+WITH_BF_NOBLENDER = True
+WITH_BF_PLAYER = True
+
+# Use jemalloc memory manager
+WITH_BF_JEMALLOC = True
+WITH_BF_STATICJEMALLOC = True
+BF_JEMALLOC = '/opt/lib/jemalloc'
+BF_JEMALLOC_LIBPATH = '${BF_JEMALLOC}/lib'
+
+# Use 3d mouse library
+WITH_BF_3DMOUSE = True
+WITH_BF_STATIC3DMOUSE = True
+BF_3DMOUSE = '/opt/lib/libspnav'
+BF_3DMOUSE_LIBPATH = '${BF_3DMOUSE}/lib'
+
+# Color management
+WITH_BF_OCIO = True
+WITH_BF_STATICOCIO = True
+BF_OCIO = '/opt/lib/ocio'
+BF_OCIO_INC = '${BF_OCIO}/include'
+BF_OCIO_LIB_STATIC = '${BF_OCIO_LIBPATH}/libOpenColorIO.a ${BF_OCIO_LIBPATH}/libtinyxml.a ${BF_OCIO_LIBPATH}/libyaml-cpp.a'
+BF_OCIO_LIBPATH = '${BF_OCIO}/lib'
+
+# JACK
+WITH_BF_JACK = True
+WITH_BF_STATICJACK = True
+BF_JACK_LIB_STATIC = '${BF_ZLIB}/lib/libjack.a'
+
+# Motion Tracking
+WITH_BF_LIBMV = False
+
+# Ocean Simulation
+WITH_BF_FFTW3 = True
+WITH_BF_STATICFFTW3 = True
+WITH_BF_OCEANSIM = True
+
+# Compilation and optimization
+BF_DEBUG = False
+REL_CCFLAGS = ['-O2', '-msse', '-msse2'] # C & C++
+PLATFORM_LINKFLAGS = ['-lrt']
diff --git a/build_files/buildbot/config/user-config-player-i686.py b/build_files/buildbot/config/user-config-player-glibc27-i686.py
index 6c5c5f89ad4..e23fc70262f 100644
--- a/build_files/buildbot/config/user-config-player-i686.py
+++ b/build_files/buildbot/config/user-config-player-glibc27-i686.py
@@ -82,6 +82,14 @@ WITH_BF_STATIC3DMOUSE = True
BF_3DMOUSE = '/home/sources/staticlibs/spnav'
BF_3DMOUSE_LIBPATH = '${BF_3DMOUSE}/lib32'
+# Color management
+WITH_BF_OCIO = True
+WITH_BF_STATICOCIO = True
+BF_OCIO = '/opt/ocio'
+BF_OCIO_INC = '${BF_OCIO}/include'
+BF_OCIO_LIB_STATIC = '${BF_OCIO_LIBPATH}/libOpenColorIO.a ${BF_OCIO_LIBPATH}/libtinyxml.a ${BF_OCIO_LIBPATH}/libyaml-cpp.a'
+BF_OCIO_LIBPATH = '${BF_OCIO}/lib'
+
# JACK
WITH_BF_JACK = True
diff --git a/build_files/buildbot/config/user-config-player-x86_64.py b/build_files/buildbot/config/user-config-player-glibc27-x86_64.py
index 60c8060e78e..3c09603473e 100644
--- a/build_files/buildbot/config/user-config-player-x86_64.py
+++ b/build_files/buildbot/config/user-config-player-glibc27-x86_64.py
@@ -82,6 +82,14 @@ WITH_BF_STATIC3DMOUSE = True
BF_3DMOUSE = '/home/sources/staticlibs/spnav'
BF_3DMOUSE_LIBPATH = '${BF_3DMOUSE}/lib64'
+# Color management
+WITH_BF_OCIO = True
+WITH_BF_STATICOCIO = True
+BF_OCIO = '/opt/ocio'
+BF_OCIO_INC = '${BF_OCIO}/include'
+BF_OCIO_LIB_STATIC = '${BF_OCIO_LIBPATH}/libOpenColorIO.a ${BF_OCIO_LIBPATH}/libtinyxml.a ${BF_OCIO_LIBPATH}/libyaml-cpp.a'
+BF_OCIO_LIBPATH = '${BF_OCIO}/lib'
+
# JACK
WITH_BF_JACK = True
diff --git a/build_files/buildbot/master.cfg b/build_files/buildbot/master.cfg
index 066c133d335..e9deade6e99 100644
--- a/build_files/buildbot/master.cfg
+++ b/build_files/buildbot/master.cfg
@@ -53,7 +53,7 @@ c['builders'] = []
buildernames = []
-def add_builder(c, name, libdir, factory, branch=''):
+def add_builder(c, name, libdir, factory, branch='', rsync=False):
slavenames = []
for slave in master_private.slaves:
@@ -61,7 +61,7 @@ def add_builder(c, name, libdir, factory, branch=''):
slavenames.append(slave['name'])
if len(slavenames) > 0:
- f = factory(name, libdir, branch)
+ f = factory(name, libdir, branch, rsync)
c['builders'].append(BuilderConfig(name=name, slavenames=slavenames, factory=f, category='blender'))
buildernames.append(name)
@@ -74,15 +74,17 @@ def svn_step(branch=''):
else:
return SVN(baseURL='https://svn.blender.org/svnroot/bf-blender/%%BRANCH%%/blender', mode='update', defaultBranch='trunk', workdir='blender')
+def lib_svn_step(dir):
+ return SVN(name='lib svn', baseURL='https://svn.blender.org/svnroot/bf-blender/%%BRANCH%%/lib/' + dir, mode='update', defaultBranch='trunk', workdir='lib/' + dir)
-def lib_svn_step(libdir):
- return SVN(name='lib svn', baseURL='https://svn.blender.org/svnroot/bf-blender/%%BRANCH%%/lib/' + libdir, mode='update', defaultBranch='trunk', workdir='lib/' + libdir)
+def rsync_step(file_from, file_to):
+ return ShellCommand(name='rsync', command=['rsync', '-v', '-P', file_from, 'brecht@builder.blender.org:/data/buildbot-master/' + file_to], haltOnFailure=True, description=['rsync'])
# generic builder
-def generic_builder(idname, libdir='', branch=''):
- filename = 'buildbot_upload_' + idname + '.zip'
+def generic_builder(id, libdir='', branch='', rsync=False):
+ filename = 'buildbot_upload_' + id + '.zip'
compile_script = '../blender/build_files/buildbot/slave_compile.py'
test_script = '../blender/build_files/buildbot/slave_test.py'
pack_script = '../blender/build_files/buildbot/slave_pack.py'
@@ -93,10 +95,12 @@ def generic_builder(idname, libdir='', branch=''):
if libdir != '':
f.addStep(lib_svn_step(libdir))
- f.addStep(Compile(command=['python', compile_script, idname]))
- f.addStep(Test(command=['python', test_script, idname]))
- f.addStep(ShellCommand(name='package', command=['python', pack_script, idname, branch], description='packaging', descriptionDone='packaged'))
- if 'cmake' in idname:
+ f.addStep(Compile(command=['python', compile_script, id]))
+ f.addStep(Test(command=['python', test_script, id]))
+ f.addStep(ShellCommand(name='package', command=['python', pack_script, id, branch], description='packaging', descriptionDone='packaged'))
+ if rsync:
+ f.addStep(rsync_step('../install/buildbot_upload.zip', filename))
+ elif id.find('cmake') != -1:
f.addStep(FileUpload(name='upload', slavesrc='buildbot_upload.zip', masterdest=filename, maxsize=100 * 1024 * 1024))
else:
f.addStep(FileUpload(name='upload', slavesrc='buildbot_upload.zip', masterdest=filename, maxsize=100 * 1024 * 1024, workdir='install'))
@@ -105,20 +109,22 @@ def generic_builder(idname, libdir='', branch=''):
# builders
-add_builder(c, 'mac_x86_64_scons', 'darwin-9.x.universal', generic_builder)
-add_builder(c, 'salad_mac_x86_64_scons', 'darwin-9.x.universal', generic_builder, 'soc-2011-salad')
+add_builder(c, 'mac_x86_64_scons', '', generic_builder)
+#add_builder(c, 'salad_mac_x86_64_scons', 'darwin-9.x.universal', generic_builder, 'soc-2011-salad')
add_builder(c, 'mac_i386_scons', 'darwin-9.x.universal', generic_builder)
add_builder(c, 'mac_ppc_scons', 'darwin-9.x.universal', generic_builder)
#add_builder(c, 'linux_x86_64_cmake', '', generic_builder)
-add_builder(c, 'linux_i386_scons', '', generic_builder)
-add_builder(c, 'salad_linux_i386_scons', '', generic_builder, 'soc-2011-salad')
-add_builder(c, 'linux_x86_64_scons', '', generic_builder)
-add_builder(c, 'salad_linux_x86_64_scons', '', generic_builder, 'soc-2011-salad')
+add_builder(c, 'linux_glibc27_i386_scons', '', generic_builder)
+add_builder(c, 'linux_glibc211_i386_scons', '', generic_builder)
+#add_builder(c, 'salad_linux_i386_scons', '', generic_builder, 'soc-2011-salad')
+add_builder(c, 'linux_glibc27_x86_64_scons', '', generic_builder)
+add_builder(c, 'linux_glibc211_x86_64_scons', '', generic_builder)
+#add_builder(c, 'salad_linux_x86_64_scons', '', generic_builder, 'soc-2011-salad')
add_builder(c, 'win32_scons', 'windows', generic_builder)
-add_builder(c, 'salad_win32_scons', 'windows', generic_builder, 'soc-2011-salad')
+#add_builder(c, 'salad_win32_scons', 'windows', generic_builder, 'soc-2011-salad')
add_builder(c, 'win64_scons', 'win64', generic_builder)
-add_builder(c, 'mingw_win64_scons', 'mingw64', generic_builder)
add_builder(c, 'mingw_win32_scons', 'mingw32', generic_builder)
+add_builder(c, 'mingw_win64_scons', 'mingw64', generic_builder)
#add_builder(c, 'freebsd_i386_cmake', '', generic_builder)
#add_builder(c, 'freebsd_x86_64_cmake', '', generic_builder)
@@ -137,10 +143,19 @@ c['schedulers'] = []
# builderNames=buildernames,
# periodicBuildTimer=24*60*60))
-c['schedulers'].append(timed.Nightly(name='nightly',
- builderNames=buildernames,
- hour=3,
- minute=0))
+schedule_cycle = 4
+
+for i in range(0, schedule_cycle):
+ names = []
+ for j in range(0, len(buildernames)):
+ if j % schedule_cycle == i:
+ names += [buildernames[j]]
+
+ print(names)
+ c['schedulers'].append(timed.Nightly(name='nightly' + str(i),
+ builderNames=names,
+ hour=3+i,
+ minute=0))
# STATUS TARGETS
#
@@ -160,7 +175,7 @@ authz_cfg = authz.Authz(
forceBuild=True, # use this to test your slave once it is set up
forceAllBuilds=False,
pingBuilder=False,
- stopBuild=False,
+ stopBuild=True,
stopAllBuilds=False,
cancelPendingBuild=True,
)
diff --git a/build_files/buildbot/master_unpack.py b/build_files/buildbot/master_unpack.py
index f67bd294496..ecacf3bff6f 100644
--- a/build_files/buildbot/master_unpack.py
+++ b/build_files/buildbot/master_unpack.py
@@ -112,7 +112,7 @@ branch = get_branch(packagename)
if platform == '':
sys.stderr.write('Failed to detect platform ' +
- 'from package: %r\n' % packagename)
+ 'from package: %r\n' % packagename)
sys.exit(1)
# extract
diff --git a/build_files/buildbot/slave_compile.py b/build_files/buildbot/slave_compile.py
index eafdf0868cd..bedada93a5a 100644
--- a/build_files/buildbot/slave_compile.py
+++ b/build_files/buildbot/slave_compile.py
@@ -75,12 +75,18 @@ else:
config_dir = os.path.join(buildbot_dir, 'config')
configs = []
- if builder.endswith('linux_x86_64_scons'):
- configs = ['user-config-player-x86_64.py',
- 'user-config-x86_64.py']
- elif builder.endswith('linux_i386_scons'):
- configs = ['user-config-player-i686.py',
- 'user-config-i686.py']
+ if builder.endswith('linux_glibc27_x86_64_scons'):
+ configs = ['user-config-player-glibc27-x86_64.py',
+ 'user-config-glibc27-x86_64.py']
+ elif builder.endswith('linux_glibc27_i386_scons'):
+ configs = ['user-config-player-glibc27-i686.py',
+ 'user-config-glibc27-i686.py']
+ if builder.endswith('linux_glibc211_x86_64_scons'):
+ configs = ['user-config-player-glibc211-x86_64.py',
+ 'user-config-glibc211-x86_64.py']
+ elif builder.endswith('linux_glibc211_i386_scons'):
+ configs = ['user-config-player-glibc211-i686.py',
+ 'user-config-glibc211-i686.py']
for config in configs:
config_fpath = os.path.join(config_dir, config)
diff --git a/build_files/buildbot/slave_pack.py b/build_files/buildbot/slave_pack.py
index 654efd72876..b7775ef872f 100644
--- a/build_files/buildbot/slave_pack.py
+++ b/build_files/buildbot/slave_pack.py
@@ -50,18 +50,24 @@ if builder.find('scons') != -1:
install_dir = os.path.join('..', 'install', builder)
scons_options += ['WITH_BF_NOBLENDER=True', 'WITH_BF_PLAYER=False',
- 'BF_BUILDDIR=' + build_dir,
- 'BF_INSTALLDIR=' + install_dir,
- 'WITHOUT_BF_INSTALL=True']
+ 'BF_BUILDDIR=' + build_dir,
+ 'BF_INSTALLDIR=' + install_dir,
+ 'WITHOUT_BF_INSTALL=True']
config = None
bits = None
- if builder.endswith('linux_x86_64_scons'):
- config = 'user-config-x86_64.py'
+ if builder.endswith('linux_glibc27_x86_64_scons'):
+ config = 'user-config-glibc27-x86_64.py'
bits = 64
- elif builder.endswith('linux_i386_scons'):
- config = 'user-config-i686.py'
+ elif builder.endswith('linux_glibc27_i386_scons'):
+ config = 'user-config-glibc27-i686.py'
+ bits = 32
+ if builder.endswith('linux_glibc211_x86_64_scons'):
+ config = 'user-config-glibc211-x86_64.py'
+ bits = 64
+ elif builder.endswith('linux_glibc211_i386_scons'):
+ config = 'user-config-glibc211-i686.py'
bits = 32
if config is not None:
diff --git a/build_files/cmake/clang_array_check.py b/build_files/cmake/clang_array_check.py
new file mode 100644
index 00000000000..3070c27f769
--- /dev/null
+++ b/build_files/cmake/clang_array_check.py
@@ -0,0 +1,353 @@
+# ---
+# * Licensed under the Apache License, Version 2.0 (the "License");
+# * you may not use this file except in compliance with the License.
+# * You may obtain a copy of the License at
+# *
+# * http://www.apache.org/licenses/LICENSE-2.0
+# ---
+# by Campbell Barton
+
+"""
+Invocation:
+
+ export CLANG_BIND_DIR="/dsk/src/llvm/tools/clang/bindings/python"
+ export CLANG_LIB_DIR="/opt/llvm/lib"
+
+ python2 clang_array_check.py somefile.c -DSOME_DEFINE -I/some/include
+
+... defines and includes are optional
+
+"""
+
+# delay parsing functions until we need them
+USE_LAZY_INIT = True
+
+# -----------------------------------------------------------------------------
+# predefined function/arg sizes, handy sometimes, but not complete...
+
+defs_precalc = {
+ "glColor3bv": {0: 3},
+ "glColor4bv": {0: 4},
+
+ "glColor3ubv": {0: 3},
+ "glColor4ubv": {0: 4},
+
+ "glColor4usv": {0: 3},
+ "glColor4usv": {0: 4},
+
+ "glColor3fv": {0: 3},
+ "glColor4fv": {0: 4},
+
+ "glColor3dv": {0: 3},
+ "glColor4dv": {0: 4},
+
+ "glVertex2fv": {0: 2},
+ "glVertex3fv": {0: 3},
+ "glVertex4fv": {0: 4},
+
+ "glEvalCoord1fv": {0: 1},
+ "glEvalCoord1dv": {0: 1},
+ "glEvalCoord2fv": {0: 2},
+ "glEvalCoord2dv": {0: 2},
+
+ "glRasterPos2dv": {0: 2},
+ "glRasterPos3dv": {0: 3},
+ "glRasterPos4dv": {0: 4},
+
+ "glRasterPos2fv": {0: 2},
+ "glRasterPos3fv": {0: 3},
+ "glRasterPos4fv": {0: 4},
+
+ "glRasterPos2sv": {0: 2},
+ "glRasterPos3sv": {0: 3},
+ "glRasterPos4sv": {0: 4},
+
+ "glTexCoord2fv": {0: 2},
+ "glTexCoord3fv": {0: 3},
+ "glTexCoord4fv": {0: 4},
+
+ "glTexCoord2dv": {0: 2},
+ "glTexCoord3dv": {0: 3},
+ "glTexCoord4dv": {0: 4},
+
+ "glNormal3fv": {0: 3},
+ "glNormal3dv": {0: 3},
+ "glNormal3bv": {0: 3},
+ "glNormal3iv": {0: 3},
+ "glNormal3sv": {0: 3},
+}
+
+# -----------------------------------------------------------------------------
+
+import sys
+
+if 0:
+ # Examples with LLVM as the root dir: '/dsk/src/llvm'
+
+ # path containing 'clang/__init__.py'
+ CLANG_BIND_DIR = "/dsk/src/llvm/tools/clang/bindings/python"
+
+ # path containing libclang.so
+ CLANG_LIB_DIR = "/opt/llvm/lib"
+else:
+ import os
+ CLANG_BIND_DIR = os.environ.get("CLANG_BIND_DIR")
+ CLANG_LIB_DIR = os.environ.get("CLANG_LIB_DIR")
+
+ if CLANG_BIND_DIR is None:
+ print("$CLANG_BIND_DIR python binding dir not set")
+ if CLANG_LIB_DIR is None:
+ print("$CLANG_LIB_DIR clang lib dir not set")
+
+sys.path.append(CLANG_BIND_DIR)
+
+import clang
+import clang.cindex
+from clang.cindex import (CursorKind,
+ TypeKind,
+ TokenKind)
+
+clang.cindex.Config.set_library_path(CLANG_LIB_DIR)
+
+index = clang.cindex.Index.create()
+
+args = sys.argv[2:]
+# print(args)
+
+tu = index.parse(sys.argv[1], args)
+print('Translation unit: %s' % tu.spelling)
+
+# -----------------------------------------------------------------------------
+
+
+def function_parm_wash_tokens(parm):
+ # print(parm.kind)
+ assert parm.kind in (CursorKind.PARM_DECL,
+ CursorKind.VAR_DECL, # XXX, double check this
+ CursorKind.FIELD_DECL,
+ )
+
+ """
+ Return tolens without trailing commads and 'const'
+ """
+
+ tokens = [t for t in parm.get_tokens()]
+ if not tokens:
+ return tokens
+
+ #if tokens[-1].kind == To
+ # remove trailing char
+ if tokens[-1].kind == TokenKind.PUNCTUATION:
+ if tokens[-1].spelling in (",", ")", ";"):
+ tokens.pop()
+ #else:
+ # print(tokens[-1].spelling)
+
+ t_new = []
+ for t in tokens:
+ t_kind = t.kind
+ t_spelling = t.spelling
+ ok = True
+ if t_kind == TokenKind.KEYWORD:
+ if t_spelling in ("const", "restrict", "volatile"):
+ ok = False
+ elif t_spelling.startswith("__"):
+ ok = False # __restrict
+ elif t_kind in (TokenKind.COMMENT, ):
+ ok = False
+
+ # Use these
+ elif t_kind in (TokenKind.LITERAL,
+ TokenKind.PUNCTUATION,
+ TokenKind.IDENTIFIER):
+ # use but ignore
+ pass
+
+ else:
+ print("Unknown!", t_kind, t_spelling)
+
+ # if its OK we will add
+ if ok:
+ t_new.append(t)
+ return t_new
+
+
+def parm_size(node_child):
+ tokens = function_parm_wash_tokens(node_child)
+
+ # print(" ".join([t.spelling for t in tokens]))
+
+ # NOT PERFECT CODE, EXTRACT SIZE FROM TOKENS
+ if len(tokens) >= 3: # foo [ 1 ]
+ if ((tokens[-3].kind == TokenKind.PUNCTUATION and tokens[-3].spelling == "[") and
+ (tokens[-2].kind == TokenKind.LITERAL and tokens[-2].spelling.isdigit()) and
+ (tokens[-1].kind == TokenKind.PUNCTUATION and tokens[-1].spelling == "]")):
+ # ---
+ return int(tokens[-2].spelling)
+ return -1
+
+
+def function_get_arg_sizes(node):
+ # Return a dict if (index: size) items
+ # {arg_indx: arg_array_size, ... ]
+ arg_sizes = {}
+
+ if 1: # node.spelling == "BM_vert_create", for debugging
+ node_parms = [node_child for node_child in node.get_children()
+ if node_child.kind == CursorKind.PARM_DECL]
+
+ for i, node_child in enumerate(node_parms):
+
+ # print(node_child.kind, node_child.spelling)
+ #print(node_child.type.kind, node_child.spelling) # TypeKind.POINTER
+
+ if node_child.type.kind == TypeKind.POINTER:
+ pointee = node_child.type.get_pointee()
+ if pointee.is_pod():
+ size = parm_size(node_child)
+ if size != -1:
+ arg_sizes[i] = size
+
+ return arg_sizes
+
+
+# -----------------------------------------------------------------------------
+_defs = {}
+
+
+def lookup_function_size_def(func_id):
+ if USE_LAZY_INIT:
+ result = _defs.get(func_id, {})
+ if type(result) != dict:
+ result = _defs[func_id] = function_get_arg_sizes(result)
+ return result
+ else:
+ return _defs.get(func_id, {})
+
+# -----------------------------------------------------------------------------
+
+
+def file_check_arg_sizes(tu):
+
+ # main checking function
+ def validate_arg_size(node):
+ """
+ Loop over args and validate sizes for args we KNOW the size of.
+ """
+ assert node.kind == CursorKind.CALL_EXPR
+
+ if 0:
+ print("---",
+ " <~> ".join(
+ [" ".join([t.spelling for t in C.get_tokens()])
+ for C in node.get_children()]
+ ))
+ # print(node.location)
+
+ # first child is the function call, skip that.
+ children = list(node.get_children())
+
+ if not children:
+ return # XXX, look into this, happens on C++
+
+ func = children[0]
+
+ # get the func declaration!
+ # works but we can better scan for functions ahead of time.
+ if 0:
+ func_dec = func.get_definition()
+ if func_dec:
+ print("FD", " ".join([t.spelling for t in func_dec.get_tokens()]))
+ else:
+ # HRMP'f - why does this fail?
+ print("AA", " ".join([t.spelling for t in node.get_tokens()]))
+ else:
+ args_size_definition = () # dummy
+
+ # get the key
+ tok = list(func.get_tokens())
+ if tok:
+ func_id = tok[0].spelling
+ args_size_definition = lookup_function_size_def(func_id)
+
+ if not args_size_definition:
+ return
+
+ children = children[1:]
+ for i, node_child in enumerate(children):
+ children = list(node_child.get_children())
+
+ # skip if we dont have an index...
+ size_def = args_size_definition.get(i, -1)
+
+ if size_def == -1:
+ continue
+
+ #print([c.kind for c in children])
+ # print(" ".join([t.spelling for t in node_child.get_tokens()]))
+
+ if len(children) == 1:
+ arg = children[0]
+ if arg.kind in (CursorKind.DECL_REF_EXPR,
+ CursorKind.UNEXPOSED_EXPR):
+
+ if arg.type.kind == TypeKind.POINTER:
+ dec = arg.get_definition()
+ if dec:
+ size = parm_size(dec)
+
+ # size == 0 is for 'float *a'
+ if size != -1 and size != 0:
+
+ # nice print!
+ if 0:
+ print("".join([t.spelling for t in func.get_tokens()]),
+ i,
+ " ".join([t.spelling for t in dec.get_tokens()]))
+
+ # testing
+ # size_def = 100
+ if size < size_def and size != 1:
+ location = node.location
+ print("%s:%d:%d: argument %d is size %d, should be %d" %
+ (location.file,
+ location.line,
+ location.column,
+ i + 1, size, size_def
+ ))
+
+ # we dont really care what we are looking at, just scan entire file for
+ # function calls.
+
+ def recursive_func_call_check(node):
+ if node.kind == CursorKind.CALL_EXPR:
+ validate_arg_size(node)
+
+ for c in node.get_children():
+ recursive_func_call_check(c)
+
+ recursive_func_call_check(tu.cursor)
+
+
+# -- first pass, cache function definitions sizes
+
+# PRINT FUNC DEFINES
+def recursive_arg_sizes(node, ):
+ # print(node.kind, node.spelling)
+ if node.kind == CursorKind.FUNCTION_DECL:
+ if USE_LAZY_INIT:
+ args_sizes = node
+ else:
+ args_sizes = function_get_arg_sizes(node)
+ #if args_sizes:
+ # print(node.spelling, args_sizes)
+ _defs[node.spelling] = args_sizes
+ # print("adding", node.spelling)
+ for c in node.get_children():
+ recursive_arg_sizes(c)
+# cache function sizes
+recursive_arg_sizes(tu.cursor)
+_defs.update(defs_precalc)
+
+# --- second pass, check against def's
+file_check_arg_sizes(tu)
diff --git a/build_files/cmake/cmake_consistency_check_config.py b/build_files/cmake/cmake_consistency_check_config.py
index a6215b40ae8..6b82e224a32 100644
--- a/build_files/cmake/cmake_consistency_check_config.py
+++ b/build_files/cmake/cmake_consistency_check_config.py
@@ -2,11 +2,9 @@ import os
IGNORE = (
"/test/",
- "/decimate_glut_test/",
"/BSP_GhostTest/",
"/release/",
"/xembed/",
- "/decimation/intern/future/",
"/TerraplayNetwork/",
"/ik_glut_test/",
diff --git a/build_files/cmake/cmake_qtcreator_project.py b/build_files/cmake/cmake_qtcreator_project.py
index 32d20489e6a..83ea761e2d1 100755
--- a/build_files/cmake/cmake_qtcreator_project.py
+++ b/build_files/cmake/cmake_qtcreator_project.py
@@ -105,7 +105,13 @@ def create_qtc_project_main():
qtc_cfg = os.path.join(PROJECT_DIR, "%s.config" % FILE_NAME)
f = open(qtc_cfg, 'w')
- f.write("// ADD PREDEFINED MACROS HERE!\n")
+ f.write("// ADD PREDEFINED MACROS TO %s_custom.config!\n" % FILE_NAME)
+ qtc_custom_cfg = os.path.join(PROJECT_DIR, "%s_custom.config" % FILE_NAME)
+ if os.path.exists(qtc_custom_cfg):
+ fc = open(qtc_custom_cfg, 'r')
+ f.write(fc.read())
+ fc.close()
+ f.write("\n")
defines_final = [("#define %s %s" % (item[0], quote_define(item[1]))) for item in defines]
if sys.platform != "win32":
defines_final += cmake_compiler_defines()
diff --git a/build_files/cmake/cmake_static_check_clang_array.py b/build_files/cmake/cmake_static_check_clang_array.py
new file mode 100644
index 00000000000..941407170ff
--- /dev/null
+++ b/build_files/cmake/cmake_static_check_clang_array.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3.2
+
+# ***** BEGIN GPL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# Contributor(s): Campbell Barton
+#
+# ***** END GPL LICENSE BLOCK *****
+
+# <pep8 compliant>
+
+import project_source_info
+import subprocess
+import sys
+import os
+
+CHECKER_IGNORE_PREFIX = [
+ "extern",
+ "intern/moto",
+ "blender/intern/opennl",
+ ]
+
+CHECKER_BIN = "python2"
+
+CHECKER_ARGS = [
+ os.path.join(os.path.dirname(__file__), "clang_array_check.py"),
+ # not sure why this is needed, but it is.
+ "-I" + os.path.join(project_source_info.SOURCE_DIR, "extern", "glew", "include"),
+ ]
+
+
+def main():
+ source_info = project_source_info.build_info(ignore_prefix_list=CHECKER_IGNORE_PREFIX)
+
+ check_commands = []
+ for c, inc_dirs, defs in source_info:
+ cmd = ([CHECKER_BIN] +
+ CHECKER_ARGS +
+ [c] +
+ [("-I%s" % i) for i in inc_dirs] +
+ [("-D%s" % d) for d in defs]
+ )
+
+ check_commands.append((c, cmd))
+
+ process_functions = []
+
+ def my_process(i, c, cmd):
+ percent = 100.0 * (i / (len(check_commands) - 1))
+ percent_str = "[" + ("%.2f]" % percent).rjust(7) + " %:"
+
+ sys.stdout.flush()
+ sys.stdout.write("%s " % percent_str)
+
+ return subprocess.Popen(cmd)
+
+ for i, (c, cmd) in enumerate(check_commands):
+ process_functions.append((my_process, (i, c, cmd)))
+
+ project_source_info.queue_processes(process_functions)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/build_files/cmake/cmake_static_check_cppcheck.py b/build_files/cmake/cmake_static_check_cppcheck.py
index c340ca5c458..c458e8ede11 100644
--- a/build_files/cmake/cmake_static_check_cppcheck.py
+++ b/build_files/cmake/cmake_static_check_cppcheck.py
@@ -30,6 +30,7 @@ import os
CHECKER_IGNORE_PREFIX = [
"extern",
"intern/moto",
+ "blender/intern/opennl",
]
CHECKER_BIN = "cppcheck"
@@ -54,7 +55,7 @@ def main():
[c] +
[("-I%s" % i) for i in inc_dirs] +
[("-D%s" % d) for d in defs]
- )
+ )
check_commands.append((c, cmd))
diff --git a/build_files/cmake/cmake_static_check_smatch.py b/build_files/cmake/cmake_static_check_smatch.py
index 779945b030a..5681d2ae5ed 100644
--- a/build_files/cmake/cmake_static_check_smatch.py
+++ b/build_files/cmake/cmake_static_check_smatch.py
@@ -25,6 +25,7 @@
CHECKER_IGNORE_PREFIX = [
"extern",
"intern/moto",
+ "blender/intern/opennl",
]
CHECKER_BIN = "smatch"
@@ -49,7 +50,7 @@ def main():
[c] +
[("-I%s" % i) for i in inc_dirs] +
[("-D%s" % d) for d in defs]
- )
+ )
check_commands.append((c, cmd))
diff --git a/build_files/cmake/cmake_static_check_sparse.py b/build_files/cmake/cmake_static_check_sparse.py
index db1b14e7acb..4f4eb838dd5 100644
--- a/build_files/cmake/cmake_static_check_sparse.py
+++ b/build_files/cmake/cmake_static_check_sparse.py
@@ -25,6 +25,7 @@
CHECKER_IGNORE_PREFIX = [
"extern",
"intern/moto",
+ "blender/intern/opennl",
]
CHECKER_BIN = "sparse"
@@ -47,7 +48,7 @@ def main():
[c] +
[("-I%s" % i) for i in inc_dirs] +
[("-D%s" % d) for d in defs]
- )
+ )
check_commands.append((c, cmd))
diff --git a/build_files/cmake/cmake_static_check_splint.py b/build_files/cmake/cmake_static_check_splint.py
index f538fa612d0..7be28c01af8 100644
--- a/build_files/cmake/cmake_static_check_splint.py
+++ b/build_files/cmake/cmake_static_check_splint.py
@@ -25,6 +25,7 @@
CHECKER_IGNORE_PREFIX = [
"extern",
"intern/moto",
+ "blender/intern/opennl",
]
CHECKER_BIN = "splint"
@@ -79,7 +80,7 @@ def main():
[c] +
[("-I%s" % i) for i in inc_dirs] +
[("-D%s" % d) for d in defs]
- )
+ )
check_commands.append((c, cmd))
diff --git a/build_files/cmake/config/blender_lite.cmake b/build_files/cmake/config/blender_lite.cmake
index b834cd37a8a..e74d1adcb1b 100644
--- a/build_files/cmake/config/blender_lite.cmake
+++ b/build_files/cmake/config/blender_lite.cmake
@@ -10,6 +10,7 @@ set(WITH_SYSTEM_GLEW ON CACHE FORCE BOOL)
set(WITH_BUILDINFO OFF CACHE FORCE BOOL)
set(WITH_BULLET OFF CACHE FORCE BOOL)
+set(WITH_CODEC_AVI OFF CACHE FORCE BOOL)
set(WITH_CODEC_FFMPEG OFF CACHE FORCE BOOL)
set(WITH_CODEC_SNDFILE OFF CACHE FORCE BOOL)
set(WITH_CYCLES OFF CACHE FORCE BOOL)
@@ -34,7 +35,6 @@ set(WITH_JACK OFF CACHE FORCE BOOL)
set(WITH_LZMA OFF CACHE FORCE BOOL)
set(WITH_LZO OFF CACHE FORCE BOOL)
set(WITH_MOD_BOOLEAN OFF CACHE FORCE BOOL)
-set(WITH_MOD_DECIMATE OFF CACHE FORCE BOOL)
set(WITH_MOD_FLUID OFF CACHE FORCE BOOL)
set(WITH_MOD_REMESH OFF CACHE FORCE BOOL)
set(WITH_MOD_SMOKE OFF CACHE FORCE BOOL)
@@ -42,6 +42,7 @@ set(WITH_MOD_OCEANSIM OFF CACHE FORCE BOOL)
set(WITH_AUDASPACE OFF CACHE FORCE BOOL)
set(WITH_OPENAL OFF CACHE FORCE BOOL)
set(WITH_OPENCOLLADA OFF CACHE FORCE BOOL)
+set(WITH_OPENCOLORIO OFF CACHE FORCE BOOL)
set(WITH_OPENMP OFF CACHE FORCE BOOL)
set(WITH_PYTHON_INSTALL OFF CACHE FORCE BOOL)
set(WITH_RAYOPTIMIZATION OFF CACHE FORCE BOOL)
diff --git a/build_files/cmake/macros.cmake b/build_files/cmake/macros.cmake
index 43cfb31c03c..3c321cc60be 100644
--- a/build_files/cmake/macros.cmake
+++ b/build_files/cmake/macros.cmake
@@ -244,6 +244,9 @@ macro(SETUP_LIBDIRS)
link_directories(${PCRE_LIBPATH})
link_directories(${EXPAT_LIBPATH})
endif()
+ if(WITH_LLVM)
+ link_directories(${LLVM_LIB_DIR})
+ endif()
if(WITH_MEM_JEMALLOC)
link_directories(${JEMALLOC_LIBPATH})
endif()
@@ -382,6 +385,9 @@ macro(setup_liblinks
if(WITH_CYCLES_OSL)
target_link_libraries(${target} ${OSL_LIBRARIES})
endif()
+ if(WITH_LLVM)
+ target_link_libraries(${target} ${LLVM_LIBRARY})
+ endif()
if(WIN32 AND NOT UNIX)
target_link_libraries(${target} ${PTHREADS_LIBRARIES})
endif()
@@ -519,7 +525,7 @@ macro(remove_strict_flags_file
# TODO
endif()
- endforeach()
+ endforeach()
unset(_SOURCE)
diff --git a/build_files/cmake/project_info.py b/build_files/cmake/project_info.py
index a80ae623eb9..b154d578144 100755
--- a/build_files/cmake/project_info.py
+++ b/build_files/cmake/project_info.py
@@ -112,7 +112,7 @@ def is_glsl(filename):
def is_c(filename):
ext = splitext(filename)[1]
- return (ext in (".c", ".cpp", ".cxx", ".m", ".mm", ".rc", ".cc", ".inl"))
+ return (ext in {".c", ".cpp", ".cxx", ".m", ".mm", ".rc", ".cc", ".inl", ".osl"})
def is_c_any(filename):
@@ -133,12 +133,20 @@ def cmake_advanced_info():
""" Extracr includes and defines from cmake.
"""
+ make_exe = cmake_cache_var("CMAKE_MAKE_PROGRAM")
+ make_exe_basename = os.path.basename(make_exe)
+
def create_eclipse_project():
print("CMAKE_DIR %r" % CMAKE_DIR)
if sys.platform == "win32":
cmd = 'cmake "%s" -G"Eclipse CDT4 - MinGW Makefiles"' % CMAKE_DIR
else:
- cmd = 'cmake "%s" -G"Eclipse CDT4 - Unix Makefiles"' % CMAKE_DIR
+ if make_exe_basename.startswith("make"):
+ cmd = 'cmake "%s" -G"Eclipse CDT4 - Unix Makefiles"' % CMAKE_DIR
+ elif make_exe_basename.startswith("ninja"):
+ cmd = 'cmake "%s" -G"Eclipse CDT4 - Ninja"' % CMAKE_DIR
+ else:
+ raise Exception("Unknown make program %r" % make_exe)
os.system(cmd)
diff --git a/build_files/cmake/project_source_info.py b/build_files/cmake/project_source_info.py
index ed17ec5bac4..10bc36ba1a8 100644
--- a/build_files/cmake/project_source_info.py
+++ b/build_files/cmake/project_source_info.py
@@ -48,7 +48,7 @@ def is_c_header(filename):
def is_c(filename):
ext = os.path.splitext(filename)[1]
- return (ext in (".c", ".cpp", ".cxx", ".m", ".mm", ".rc", ".cc", ".inl"))
+ return (ext in {".c", ".cpp", ".cxx", ".m", ".mm", ".rc", ".cc", ".inl", ".osl"})
def is_c_any(filename):
@@ -82,10 +82,20 @@ def makefile_log():
import subprocess
import time
- print("running make with --dry-run ...")
- process = subprocess.Popen(["make", "--always-make", "--dry-run", "--keep-going", "VERBOSE=1"],
- stdout=subprocess.PIPE,
- )
+ # support both make and ninja
+ make_exe = cmake_cache_var("CMAKE_MAKE_PROGRAM")
+ make_exe_basename = os.path.basename(make_exe)
+
+ if make_exe_basename.startswith("make"):
+ print("running 'make' with --dry-run ...")
+ process = subprocess.Popen([make_exe, "--always-make", "--dry-run", "--keep-going", "VERBOSE=1"],
+ stdout=subprocess.PIPE,
+ )
+ elif make_exe_basename.startswith("ninja"):
+ print("running 'ninja' with -t commands ...")
+ process = subprocess.Popen([make_exe, "-t", "commands"],
+ stdout=subprocess.PIPE,
+ )
while process.poll():
time.sleep(1)
@@ -145,6 +155,12 @@ def build_info(use_c=True, use_cxx=True, ignore_prefix_list=None):
source.append((c, inc_dirs, defs))
+ # make relative includes absolute
+ # not totally essential but useful
+ for i, f in enumerate(inc_dirs):
+ if not os.path.isabs(f):
+ inc_dirs[i] = os.path.abspath(os.path.join(CMAKE_DIR, f))
+
# safety check that our includes are ok
for f in inc_dirs:
if not os.path.exists(f):
diff --git a/build_files/package_spec/rpm/blender.spec.in b/build_files/package_spec/rpm/blender.spec.in
index 85a689031a3..a95fce80103 100644
--- a/build_files/package_spec/rpm/blender.spec.in
+++ b/build_files/package_spec/rpm/blender.spec.in
@@ -76,6 +76,7 @@ fi || :
%defattr(-,root,root,-)
%{_bindir}/%{name}
%{_datadir}/%{name}/%{blender_api}/datafiles/fonts
+%{_datadir}/%{name}/%{blender_api}/datafiles/colormanagement
%{_datadir}/%{name}/%{blender_api}/scripts
%{_datadir}/icons/hicolor/*/apps/%{name}.*
%{_datadir}/applications/%{name}.desktop
diff --git a/build_files/scons/config/linux-config.py b/build_files/scons/config/linux-config.py
index 5c16baa2ee8..45f6602e4dd 100644
--- a/build_files/scons/config/linux-config.py
+++ b/build_files/scons/config/linux-config.py
@@ -239,7 +239,7 @@ WITH_BF_CYCLES = WITH_BF_OIIO and WITH_BF_BOOST
WITH_BF_CYCLES_CUDA_BINARIES = False
BF_CYCLES_CUDA_NVCC = '/usr/local/cuda/bin/nvcc'
-BF_CYCLES_CUDA_BINARIES_ARCH = ['sm_13', 'sm_20', 'sm_21']
+BF_CYCLES_CUDA_BINARIES_ARCH = ['sm_13', 'sm_20', 'sm_21', 'sm_30']
WITH_BF_OPENMP = True
diff --git a/build_files/scons/config/win32-mingw-config.py b/build_files/scons/config/win32-mingw-config.py
index 95b2329f426..0a72d87bb2a 100644
--- a/build_files/scons/config/win32-mingw-config.py
+++ b/build_files/scons/config/win32-mingw-config.py
@@ -159,7 +159,7 @@ BF_OIIO_INC = BF_OIIO + '/include'
BF_OIIO_LIB = 'OpenImageIO'
BF_OIIO_LIBPATH = BF_OIIO + '/lib'
-WITH_BF_OCIO = False
+WITH_BF_OCIO = True
BF_OCIO = LIBDIR + '/opencolorio'
BF_OCIO_INC = BF_OCIO + '/include'
BF_OCIO_LIB = 'OpenColorIO'
@@ -168,7 +168,7 @@ BF_OCIO_LIBPATH = BF_OCIO + '/lib'
WITH_BF_BOOST = True
BF_BOOST = LIBDIR + '/boost'
BF_BOOST_INC = BF_BOOST + '/include'
-BF_BOOST_LIB = 'boost_date_time-mgw46-mt-s-1_47 boost_filesystem-mgw46-mt-s-1_47 boost_regex-mgw46-mt-s-1_47 boost_system-mgw46-mt-s-1_47 boost_thread-mgw46-mt-s-1_47'
+BF_BOOST_LIB = 'boost_date_time-mgw46-mt-s-1_49 boost_filesystem-mgw46-mt-s-1_49 boost_regex-mgw46-mt-s-1_49 boost_system-mgw46-mt-s-1_49 boost_thread-mgw46-mt-s-1_49'
BF_BOOST_LIBPATH = BF_BOOST + '/lib'
#Ray trace optimization
@@ -201,7 +201,7 @@ LLIBS = ['-lshell32', '-lshfolder', '-lgdi32', '-lmsvcrt', '-lwinmm', '-lmingw32
PLATFORM_LINKFLAGS = ['-Xlinker', '--stack=2097152']
## DISABLED, causes linking errors!
-## for re-distrobution, so users dont need mingw installed
+## for re-distribution, so users dont need mingw installed
# PLATFORM_LINKFLAGS += ["-static-libgcc", "-static-libstdc++"]
BF_DEBUG = False
diff --git a/build_files/scons/config/win64-mingw-config.py b/build_files/scons/config/win64-mingw-config.py
index c2bf2df6d00..838822bbbcb 100644
--- a/build_files/scons/config/win64-mingw-config.py
+++ b/build_files/scons/config/win64-mingw-config.py
@@ -159,7 +159,7 @@ BF_OIIO_INC = '${BF_OIIO}/include'
BF_OIIO_LIB = 'OpenImageIO'
BF_OIIO_LIBPATH = '${BF_OIIO}/lib'
-WITH_BF_OCIO = False
+WITH_BF_OCIO = True
BF_OCIO = LIBDIR + '/opencolorio'
BF_OCIO_INC = '${BF_OCIO}/include'
BF_OCIO_LIB = 'OpenColorIO'
@@ -199,7 +199,7 @@ LLIBS = ['-lshell32', '-lshfolder', '-lgdi32', '-lmsvcrt', '-lwinmm', '-lmingw32
PLATFORM_LINKFLAGS = ['-Xlinker', '--stack=2097152']
## DISABLED, causes linking errors!
-## for re-distrobution, so users dont need mingw installed
+## for re-distribution, so users dont need mingw installed
# PLATFORM_LINKFLAGS += ["-static-libgcc", "-static-libstdc++"]
BF_DEBUG = False
diff --git a/build_files/scons/tools/Blender.py b/build_files/scons/tools/Blender.py
index 1e114a43ae0..eb646f27d53 100644
--- a/build_files/scons/tools/Blender.py
+++ b/build_files/scons/tools/Blender.py
@@ -136,6 +136,11 @@ def setup_staticlibs(lenv):
lenv['BF_ICONV_LIBPATH']
])
+ if lenv['WITH_BF_STATICJPEG']:
+ statlibs += Split(lenv['BF_JPEG_LIB_STATIC'])
+ if lenv['WITH_BF_STATICPNG']:
+ statlibs += Split(lenv['BF_PNG_LIB_STATIC'])
+
libincs += Split(lenv['BF_FREETYPE_LIBPATH'])
if lenv['WITH_BF_PYTHON']:
libincs += Split(lenv['BF_PYTHON_LIBPATH'])
@@ -143,6 +148,8 @@ def setup_staticlibs(lenv):
libincs += Split(lenv['BF_SDL_LIBPATH'])
if lenv['WITH_BF_JACK']:
libincs += Split(lenv['BF_JACK_LIBPATH'])
+ if lenv['WITH_BF_STATICJACK']:
+ statlibs += Split(lenv['BF_JACK_LIB_STATIC'])
if lenv['WITH_BF_SNDFILE']:
libincs += Split(lenv['BF_SNDFILE_LIBPATH'])
if lenv['WITH_BF_OPENEXR']:
@@ -194,10 +201,14 @@ def setup_staticlibs(lenv):
if lenv['OURPLATFORM'] not in ('win32-vc', 'win32-mingw', 'linuxcross', 'win64-vc', 'win64-mingw'):
libincs += Split(lenv['BF_PCRE_LIBPATH'])
libincs += Split(lenv['BF_EXPAT_LIBPATH'])
+ if lenv['WITH_BF_STATICOPENCOLLADA']:
+ statlibs += Split(lenv['BF_OPENCOLLADA_LIB_STATIC'])
if lenv['WITH_BF_OPENMP']:
if lenv['OURPLATFORM'] == 'linuxcross':
libincs += Split(lenv['BF_OPENMP_LIBPATH'])
+ if lenv['WITH_BF_STATICOPENMP']:
+ statlibs += Split(lenv['BF_OPENMP_LIB_STATIC'])
if lenv['WITH_BF_OIIO']:
libincs += Split(lenv['BF_OIIO_LIBPATH'])
@@ -246,7 +257,7 @@ def setup_syslibs(lenv):
if lenv['WITH_BF_OPENAL']:
if not lenv['WITH_BF_STATICOPENAL']:
syslibs += Split(lenv['BF_OPENAL_LIB'])
- if lenv['WITH_BF_OPENMP'] and lenv['CC'] != 'icc':
+ if lenv['WITH_BF_OPENMP'] and lenv['CC'] != 'icc' and not lenv['WITH_BF_STATICOPENMP']:
if lenv['CC'] == 'cl.exe':
syslibs += ['vcomp']
else:
@@ -271,7 +282,7 @@ def setup_syslibs(lenv):
syslibs += Split(lenv['BF_FFMPEG_LIB'])
if lenv['WITH_BF_OGG']:
syslibs += Split(lenv['BF_OGG_LIB'])
- if lenv['WITH_BF_JACK']:
+ if lenv['WITH_BF_JACK'] and not lenv['WITH_BF_STATICJACK']:
syslibs += Split(lenv['BF_JACK_LIB'])
if lenv['WITH_BF_SNDFILE'] and not lenv['WITH_BF_STATICSNDFILE']:
syslibs += Split(lenv['BF_SNDFILE_LIB'])
@@ -285,7 +296,7 @@ def setup_syslibs(lenv):
syslibs += Split(lenv['BF_OPENGL_LIB'])
if lenv['OURPLATFORM'] in ('win32-vc', 'win32-mingw','linuxcross', 'win64-vc', 'win64-mingw'):
syslibs += Split(lenv['BF_PTHREADS_LIB'])
- if lenv['WITH_BF_COLLADA']:
+ if lenv['WITH_BF_COLLADA'] and not lenv['WITH_BF_STATICOPENCOLLADA']:
syslibs.append(lenv['BF_PCRE_LIB'])
if lenv['BF_DEBUG'] and (lenv['OURPLATFORM'] != 'linux'):
syslibs += [colladalib+'_d' for colladalib in Split(lenv['BF_OPENCOLLADA_LIB'])]
@@ -305,8 +316,11 @@ def setup_syslibs(lenv):
if lenv['WITH_BF_BOOST'] and not lenv['WITH_BF_STATICBOOST']:
syslibs += Split(lenv['BF_BOOST_LIB'])
- syslibs += Split(lenv['BF_JPEG_LIB'])
- syslibs += Split(lenv['BF_PNG_LIB'])
+ if not lenv['WITH_BF_STATICJPEG']:
+ syslibs += Split(lenv['BF_JPEG_LIB'])
+
+ if not lenv['WITH_BF_STATICPNG']:
+ syslibs += Split(lenv['BF_PNG_LIB'])
syslibs += lenv['LLIBS']
diff --git a/build_files/scons/tools/btools.py b/build_files/scons/tools/btools.py
index 633492ba0ee..19652bb7851 100644
--- a/build_files/scons/tools/btools.py
+++ b/build_files/scons/tools/btools.py
@@ -99,7 +99,7 @@ def validate_arguments(args, bc):
'WITH_BF_PYTHON', 'WITH_BF_PYTHON_SAFETY', 'BF_PYTHON', 'BF_PYTHON_VERSION', 'BF_PYTHON_INC', 'BF_PYTHON_BINARY', 'BF_PYTHON_LIB', 'BF_PYTHON_LIBPATH', 'WITH_BF_STATICPYTHON', 'WITH_OSX_STATICPYTHON', 'BF_PYTHON_LIB_STATIC', 'BF_PYTHON_DLL', 'BF_PYTHON_ABI_FLAGS',
'WITH_BF_OPENAL', 'BF_OPENAL', 'BF_OPENAL_INC', 'BF_OPENAL_LIB', 'BF_OPENAL_LIBPATH', 'WITH_BF_STATICOPENAL', 'BF_OPENAL_LIB_STATIC',
'WITH_BF_SDL', 'BF_SDL', 'BF_SDL_INC', 'BF_SDL_LIB', 'BF_SDL_LIBPATH',
- 'WITH_BF_JACK', 'BF_JACK', 'BF_JACK_INC', 'BF_JACK_LIB', 'BF_JACK_LIBPATH',
+ 'WITH_BF_JACK', 'BF_JACK', 'BF_JACK_INC', 'BF_JACK_LIB', 'BF_JACK_LIBPATH', 'WITH_BF_STATICJACK', 'BF_JACK_LIB_STATIC',
'WITH_BF_SNDFILE', 'BF_SNDFILE', 'BF_SNDFILE_INC', 'BF_SNDFILE_LIB', 'BF_SNDFILE_LIBPATH', 'WITH_BF_STATICSNDFILE', 'BF_SNDFILE_LIB_STATIC',
'BF_PTHREADS', 'BF_PTHREADS_INC', 'BF_PTHREADS_LIB', 'BF_PTHREADS_LIBPATH',
'WITH_BF_OPENEXR', 'BF_OPENEXR', 'BF_OPENEXR_INC', 'BF_OPENEXR_LIB', 'BF_OPENEXR_LIBPATH', 'WITH_BF_STATICOPENEXR', 'BF_OPENEXR_LIB_STATIC',
@@ -109,10 +109,10 @@ def validate_arguments(args, bc):
'WITH_BF_OGG', 'BF_OGG', 'BF_OGG_LIB',
'WITH_BF_FRAMESERVER',
'WITH_BF_COMPOSITOR', 'WITH_BF_COMPOSITOR_LEGACY',
- 'WITH_BF_JPEG', 'BF_JPEG', 'BF_JPEG_INC', 'BF_JPEG_LIB', 'BF_JPEG_LIBPATH',
+ 'WITH_BF_JPEG', 'BF_JPEG', 'BF_JPEG_INC', 'BF_JPEG_LIB', 'BF_JPEG_LIBPATH', 'WITH_BF_STATICJPEG', 'BF_JPEG_LIB_STATIC',
'WITH_BF_OPENJPEG', 'BF_OPENJPEG', 'BF_OPENJPEG_INC', 'BF_OPENJPEG_LIB', 'BF_OPENJPEG_LIBPATH',
'WITH_BF_REDCODE', 'BF_REDCODE', 'BF_REDCODE_INC', 'BF_REDCODE_LIB', 'BF_REDCODE_LIBPATH',
- 'WITH_BF_PNG', 'BF_PNG', 'BF_PNG_INC', 'BF_PNG_LIB', 'BF_PNG_LIBPATH',
+ 'WITH_BF_PNG', 'BF_PNG', 'BF_PNG_INC', 'BF_PNG_LIB', 'BF_PNG_LIBPATH', 'WITH_BF_STATICPNG', 'BF_PNG_LIB_STATIC',
'WITH_BF_TIFF', 'BF_TIFF', 'BF_TIFF_INC', 'BF_TIFF_LIB', 'BF_TIFF_LIBPATH', 'WITH_BF_STATICTIFF', 'BF_TIFF_LIB_STATIC',
'WITH_BF_ZLIB', 'BF_ZLIB', 'BF_ZLIB_INC', 'BF_ZLIB_LIB', 'BF_ZLIB_LIBPATH', 'WITH_BF_STATICZLIB', 'BF_ZLIB_LIB_STATIC',
'WITH_BF_INTERNATIONAL',
@@ -127,6 +127,7 @@ def validate_arguments(args, bc):
'WITH_BF_FFTW3', 'BF_FFTW3', 'BF_FFTW3_INC', 'BF_FFTW3_LIB', 'BF_FFTW3_LIBPATH', 'WITH_BF_STATICFFTW3', 'BF_FFTW3_LIB_STATIC',
'WITH_BF_STATICOPENGL', 'BF_OPENGL', 'BF_OPENGL_INC', 'BF_OPENGL_LIB', 'BF_OPENGL_LIBPATH', 'BF_OPENGL_LIB_STATIC',
'WITH_BF_COLLADA', 'BF_COLLADA', 'BF_COLLADA_INC', 'BF_COLLADA_LIB', 'BF_OPENCOLLADA', 'BF_OPENCOLLADA_INC', 'BF_OPENCOLLADA_LIB', 'BF_OPENCOLLADA_LIBPATH', 'BF_PCRE', 'BF_PCRE_LIB', 'BF_PCRE_LIBPATH', 'BF_EXPAT', 'BF_EXPAT_LIB', 'BF_EXPAT_LIBPATH',
+ 'WITH_BF_STATICOPENCOLLADA', 'BF_OPENCOLLADA_LIB_STATIC',
'WITH_BF_PLAYER',
'WITH_BF_NOBLENDER',
'WITH_BF_BINRELOC',
@@ -137,7 +138,7 @@ def validate_arguments(args, bc):
'WITHOUT_BF_INSTALL',
'WITHOUT_BF_PYTHON_INSTALL', 'WITHOUT_BF_PYTHON_UNPACK', 'WITH_BF_PYTHON_INSTALL_NUMPY'
'WITHOUT_BF_OVERWRITE_INSTALL',
- 'WITH_BF_OPENMP', 'BF_OPENMP', 'BF_OPENMP_LIBPATH',
+ 'WITH_BF_OPENMP', 'BF_OPENMP', 'BF_OPENMP_LIBPATH', 'WITH_BF_STATICOPENMP', 'BF_OPENMP_STATIC_STATIC',
'WITH_GHOST_COCOA',
'WITH_GHOST_SDL',
'WITH_GHOST_XDND',
@@ -152,7 +153,6 @@ def validate_arguments(args, bc):
'WITH_BF_RAYOPTIMIZATION',
'BF_RAYOPTIMIZATION_SSE_FLAGS',
'WITH_BF_FLUID',
- 'WITH_BF_DECIMATE',
'WITH_BF_BOOLEAN',
'WITH_BF_REMESH',
'WITH_BF_OCEANSIM',
@@ -265,7 +265,6 @@ def read_opts(env, cfg, args):
('BF_PYTHON_ABI_FLAGS', 'Python ABI flags (suffix in library version: m, mu, etc)', ''),
(BoolVariable('WITH_BF_FLUID', 'Build with Fluid simulation (Elbeem)', True)),
- (BoolVariable('WITH_BF_DECIMATE', 'Build with decimate modifier', True)),
(BoolVariable('WITH_BF_BOOLEAN', 'Build with boolean modifier', True)),
(BoolVariable('WITH_BF_REMESH', 'Build with remesh modifier', True)),
(BoolVariable('WITH_BF_OCEANSIM', 'Build with ocean simulation', False)),
@@ -286,10 +285,12 @@ def read_opts(env, cfg, args):
('BF_SDL_LIBPATH', 'SDL library path', ''),
(BoolVariable('WITH_BF_JACK', 'Enable jack support if true', True)),
+ (BoolVariable('WITH_BF_STATICJACK', 'Staticly link to jack', False)),
('BF_JACK', 'jack base path', ''),
('BF_JACK_INC', 'jack include path', ''),
('BF_JACK_LIB', 'jack library', ''),
('BF_JACK_LIBPATH', 'jack library path', ''),
+ ('BF_JACK_LIB_STATIC', 'jack static library', ''),
(BoolVariable('WITH_BF_SNDFILE', 'Enable sndfile support if true', True)),
('BF_SNDFILE', 'sndfile base path', ''),
@@ -337,10 +338,12 @@ def read_opts(env, cfg, args):
('BF_OGG_LIB', 'OGG library', ''),
(BoolVariable('WITH_BF_JPEG', 'Use JPEG if true', True)),
+ (BoolVariable('WITH_BF_STATICJPEG', 'Staticly link to JPEG', False)),
('BF_JPEG', 'JPEG base path', ''),
('BF_JPEG_INC', 'JPEG include path', ''),
('BF_JPEG_LIB', 'JPEG library', ''),
('BF_JPEG_LIBPATH', 'JPEG library path', ''),
+ ('BF_JPEG_LIB_STATIC', 'JPEG static library', ''),
(BoolVariable('WITH_BF_OPENJPEG', 'Use OPENJPEG if true', False)),
('BF_OPENJPEG', 'OPENJPEG base path', ''),
@@ -355,10 +358,12 @@ def read_opts(env, cfg, args):
('BF_REDCODE_LIBPATH', 'REDCODE library path', ''),
(BoolVariable('WITH_BF_PNG', 'Use PNG if true', True)),
+ (BoolVariable('WITH_BF_STATICPNG', 'Staticly link to PNG', False)),
('BF_PNG', 'PNG base path', ''),
('BF_PNG_INC', 'PNG include path', ''),
('BF_PNG_LIB', 'PNG library', ''),
('BF_PNG_LIBPATH', 'PNG library path', ''),
+ ('BF_PNG_LIB_STATIC', 'PNG static library', ''),
(BoolVariable('WITH_BF_TIFF', 'Use TIFF if true', True)),
(BoolVariable('WITH_BF_STATICTIFF', 'Staticly link to TIFF', False)),
@@ -420,12 +425,14 @@ def read_opts(env, cfg, args):
('BF_FREETYPE_LIB_STATIC', 'Static Freetype library', ''),
(BoolVariable('WITH_BF_OPENMP', 'Use OpenMP if true', False)),
+ (BoolVariable('WITH_BF_STATICOPENMP', 'Staticly link to OpenMP', False)),
('BF_OPENMP', 'Base path to OpenMP (used when cross-compiling with older versions of WinGW)', ''),
('BF_OPENMP_INC', 'Path to OpenMP includes (used when cross-compiling with older versions of WinGW)', ''),
('BF_OPENMP_LIBPATH', 'Path to OpenMP libraries (used when cross-compiling with older versions of WinGW)', ''),
(BoolVariable('WITH_GHOST_COCOA', 'Use Cocoa-framework if true', False)),
(BoolVariable('WITH_GHOST_SDL', 'Enable building blender against SDL for windowing rather then the native APIs', False)),
(BoolVariable('USE_QTKIT', 'Use QTKIT if true', False)),
+ ('BF_OPENMP_LIB_STATIC', 'OpenMP static library', ''),
(BoolVariable('WITH_BF_QUICKTIME', 'Use QuickTime if true', False)),
('BF_QUICKTIME', 'QuickTime base path', ''),
@@ -450,6 +457,7 @@ def read_opts(env, cfg, args):
('BF_OPENGL_LINKFLAGS', 'OpenGL link flags', ''),
(BoolVariable('WITH_BF_COLLADA', 'Build COLLADA import/export module if true', False)),
+ (BoolVariable('WITH_BF_STATICOPENCOLLADA', 'Staticly link to OpenCollada', False)),
('BF_COLLADA', 'COLLADA base path', ''),
('BF_COLLADA_INC', 'COLLADA include path', ''),
('BF_COLLADA_LIB', 'COLLADA library', ''),
@@ -463,6 +471,7 @@ def read_opts(env, cfg, args):
('BF_EXPAT', 'Expat base path', ''),
('BF_EXPAT_LIB', 'Expat library', ''),
('BF_EXPAT_LIBPATH', 'Expat library path', ''),
+ ('BF_OPENCOLLADA_LIB_STATIC', 'OpenCollada static library', ''),
(BoolVariable('WITH_BF_JEMALLOC', 'Use jemalloc if true', False)),
(BoolVariable('WITH_BF_STATICJEMALLOC', 'Staticly link to jemalloc', False)),
@@ -541,7 +550,9 @@ def read_opts(env, cfg, args):
(BoolVariable('WITH_BF_LIBMV', 'Enable libmv structure from motion library', True)),
(BoolVariable('WITH_BF_COMPOSITOR', 'Enable the tile based nodal compositor', True)),
+ ) # end of opts.AddOptions()
+ localopts.AddVariables(
('BF_X264_CONFIG', 'configuration flags for x264', ''),
('BF_XVIDCORE_CONFIG', 'configuration flags for xvidcore', ''),
# (BoolVariable('WITH_BF_DOCS', 'Generate API documentation', False)),
@@ -559,9 +570,7 @@ def read_opts(env, cfg, args):
(BoolVariable('WITH_BF_CXX_GUARDEDALLOC', 'Enable GuardedAlloc for C++ memory allocation tracking.', False)),
('BUILDBOT_BRANCH', 'Buildbot branch name', ''),
- ) # end of opts.AddOptions()
- localopts.AddVariables(
(BoolVariable('WITH_BF_CYCLES', 'Build with the Cycles engine', True)),
(BoolVariable('WITH_BF_CYCLES_CUDA_BINARIES', 'Build with precompiled CUDA binaries', False)),
(BoolVariable('WITH_BF_CYCLES_CUDA_THREADED_COMPILE', 'Build several render kernels at once (using BF_NUMJOBS)', False)),
@@ -593,7 +602,7 @@ def read_opts(env, cfg, args):
('BF_BOOST_LIB_STATIC', 'Boost static library', ''),
(BoolVariable('WITH_GHOST_XDND', 'Build with drag-n-drop support on Linux platforms using XDND protocol', True)),
- (BoolVariable('WITH_BF_COMPOSITOR_LEGACY', 'Enable the legacy compositor', True))
+ (BoolVariable('WITH_BF_COMPOSITOR_LEGACY', 'Enable the legacy compositor', False))
) # end of opts.AddOptions()
return localopts
@@ -653,11 +662,16 @@ def buildslave(target=None, source=None, env=None):
if platform == 'linux':
import platform
+ if env['BF_INSTALLDIR'].find('glibc27') != -1:
+ glibc="glibc27"
+ elif env['BF_INSTALLDIR'].find('glibc211') != -1:
+ glibc="glibc211"
+
bitness = platform.architecture()[0]
if bitness == '64bit':
- platform = 'linux-glibc27-x86_64'
+ platform = 'linux-' + glibc + '-x86_64'
elif bitness == '32bit':
- platform = 'linux-glibc27-i686'
+ platform = 'linux-' + glibc + '-i686'
if platform == 'darwin':
platform = 'OSX-' + env['MACOSX_ARCHITECTURE']
diff --git a/doc/guides/interface_API.txt b/doc/guides/interface_API.txt
index 5f601dd3ebc..5f0fbc85ff8 100644
--- a/doc/guides/interface_API.txt
+++ b/doc/guides/interface_API.txt
@@ -50,7 +50,7 @@ Contents
- It works with only OpenGL calls, for the full 100%. This means that it has some quirks
built-in to work with all OS's and OpenGL versions. Especially frontbuffer drawing is
a continuous point of attention. Buttons can be drawn with any window matrix. However,
- errors can still occor when buttons are created in windows with non-standard glViewports.
+ errors can still occur when buttons are created in windows with non-standard glViewports.
- The code was written to replace the old 1.8 button system, but under high pressure. Quite
some button methods from the old system were copied for that reason.
@@ -95,7 +95,7 @@ blender/source/blender/src/toolbox.c (extra GUI elements built on top of this AP
All GUI elements are collected in uiBlocks, which in turn are linked together in a list that's
part of a Blender Area-window.
- uiBlock *block= uiNewBlock(&curarea->uiblocks, "stuff", UI_EMBOSSX, UI_HELV, curarea->win);
+ uiBlock *block = uiNewBlock(&curarea->uiblocks, "stuff", UI_EMBOSSX, UI_HELV, curarea->win);
The next code example makes a new block, and puts it in the list of blocks of the current active
Area:
@@ -221,7 +221,7 @@ void uiBlockSetButmFunc(uiBlock *block, void (*menufunc)(void *arg, int event),
void uiAutoBlock(uiBlock *block, float minx, float miny, float sizex, float sizey, UI_BLOCK_ROWS)
Sets the buttons in this block to automatically align, and fit within boundaries.
- Internally it allows multiple collums or rows as well. Only 'row order' has been implemented.
+ Internally it allows multiple colums or rows as well. Only 'row order' has been implemented.
The uiDefBut definitions don't need coordinates as input here, but instead:
- first value (x1) to indicate row number
- width and height values (if filled in) will be used to define a relative width/height.
@@ -346,7 +346,7 @@ type:
without returnvalues, the first item gets value 0 (incl. title!)
Example: "Do something %t| turn left %2| turn right %1| nothing %0"
-11. COL
+11. COLOR
A special button that only visualizes a RGB value
In 'retval' you can put a code, which is used to identify for sliders if it needs
redraws while using the sliders. Check button '5'.
@@ -363,7 +363,7 @@ uiBut *uiDefIconBut(uiBlock *block, int type, int retval, int icon,
float min, float max, float a1, float a2, char *tip)
Same syntax and types available as previous uiDefBut, but now with an icon code
- instead of a name. THe icons are numbered in resources.c
+ instead of a name. The icons are numbered in resources.c
uiBut *uiDefIconTextButF(uiBlock *block, int type, int retval, int icon, char *str,
short x1, short y1, short x2, short y2, float *poin,
@@ -397,9 +397,9 @@ void uiDefBlockBut(uiBlock *block, uiBlockFuncFP func, void *arg, char *str,
static uiBlock *info_file_importmenu(void *arg_unused)
{
uiBlock *block;
- short yco= 0, xco = 20;
+ short yco = 0, xco = 20;
- block= uiNewBlock(&curarea->uiblocks, "importmenu", UI_EMBOSSW, UI_HELV, G.curscreen->mainwin);
+ block = uiNewBlock(&curarea->uiblocks, "importmenu", UI_EMBOSSW, UI_HELV, G.curscreen->mainwin);
uiBlockSetXOfs(block, -40); // offset to parent button
/* flags are defines */
@@ -409,7 +409,7 @@ void uiDefBlockBut(uiBlock *block, uiBlockFuncFP func, void *arg, char *str,
uiDefButS(block, TOG|BIT|2, 0, "Two Sided", xco, yco-=20, 75, 19, &U.vrmlflag, 0.0, 0.0, 0, 0, "");
uiBlockSetDirection(block, UI_RIGHT);
- uiTextBoundsBlock(block, 50); // checks for fontsize
+ uiTextBoundsBlock(block, 50); /* checks for fontsize */
return block;
}
diff --git a/doc/manpage/blender.1 b/doc/manpage/blender.1
index c7a762f08c7..e7164fcb96b 100644
--- a/doc/manpage/blender.1
+++ b/doc/manpage/blender.1
@@ -1,4 +1,4 @@
-.TH "BLENDER" "1" "July 19, 2012" "Blender Blender 2\&.63 (sub 14)"
+.TH "BLENDER" "1" "October 04, 2012" "Blender Blender 2\&.64 (sub 0)"
.SH NAME
blender \- a 3D modelling and rendering package
@@ -15,7 +15,7 @@ Use Blender to create TV commercials, to make technical visualizations, business
http://www.blender.org
.SH OPTIONS
-Blender 2.63 (sub 14)
+Blender 2.64 (sub 0)
Usage: blender [args ...] [file] [args ...]
.br
.SS "Render Options:"
diff --git a/doc/python_api/examples/bpy.types.Operator.4.py b/doc/python_api/examples/bpy.types.Operator.4.py
index 861496c6d18..885ed857842 100644
--- a/doc/python_api/examples/bpy.types.Operator.4.py
+++ b/doc/python_api/examples/bpy.types.Operator.4.py
@@ -26,8 +26,8 @@ class CustomDrawOperator(bpy.types.Operator):
return {'FINISHED'}
def invoke(self, context, event):
- context.window_manager.fileselect_add(self)
- return {'RUNNING_MODAL'}
+ wm = context.window_manager
+ return wm.invoke_props_dialog(self)
def draw(self, context):
layout = self.layout
diff --git a/doc/python_api/examples/bpy.types.Operator.5.py b/doc/python_api/examples/bpy.types.Operator.5.py
index e123768431b..4a0abcb62c3 100644
--- a/doc/python_api/examples/bpy.types.Operator.5.py
+++ b/doc/python_api/examples/bpy.types.Operator.5.py
@@ -40,15 +40,17 @@ class ModalOperator(bpy.types.Operator):
elif event.type == 'LEFTMOUSE': # Confirm
return {'FINISHED'}
elif event.type in ('RIGHTMOUSE', 'ESC'): # Cancel
+ context.object.location.x = self.init_loc_x
return {'CANCELLED'}
return {'RUNNING_MODAL'}
def invoke(self, context, event):
+ self.init_loc_x = context.object.location.x
self.value = event.mouse_x
self.execute(context)
- print(context.window_manager.modal_handler_add(self))
+ context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
diff --git a/doc/python_api/rst/bge.constraints.rst b/doc/python_api/rst/bge.constraints.rst
index 83f2a6b4950..7757e11d41f 100644
--- a/doc/python_api/rst/bge.constraints.rst
+++ b/doc/python_api/rst/bge.constraints.rst
@@ -78,6 +78,14 @@ Physics Constraints (bge.constraints)
:return: a vehicle constraint object.
:rtype: :class:`bge.types.KX_VehicleWrapper`
+
+.. function:: getCharacter(gameobj)
+
+ :arg gameobj: The game object with the character physics.
+ :type gameobj: :class:`bge.types.KX_GameObject`
+
+ :return: character wrapper
+ :rtype: :class:`bge.types.KX_CharacterWrapper`
.. function:: removeConstraint(constraintId)
diff --git a/doc/python_api/rst/bge.logic.rst b/doc/python_api/rst/bge.logic.rst
index 0d1d0df88c3..260a86f7c59 100644
--- a/doc/python_api/rst/bge.logic.rst
+++ b/doc/python_api/rst/bge.logic.rst
@@ -2,9 +2,9 @@
Game Logic (bge.logic)
======================
-*****
-Intro
-*****
+************
+Introduction
+************
Module to access logic functions, imported automatically into the python controllers namespace.
diff --git a/doc/python_api/rst/bge.texture.rst b/doc/python_api/rst/bge.texture.rst
index 07d83f66bd4..0c9e9da0661 100644
--- a/doc/python_api/rst/bge.texture.rst
+++ b/doc/python_api/rst/bge.texture.rst
@@ -351,6 +351,15 @@ When the texture object is deleted, the new texture is deleted and the old textu
use whole viewport to render
+ .. attribute:: depth
+
+ use depth component of render as array of float - not suitable for texture source,
+ should only be used with bge.texture.imageToArray(mode='F')
+
+ .. attribute:: zbuff
+
+ use depth component of render as grey scale color - suitable for texture source
+
.. class:: ImageViewport()
Image source from viewport
@@ -399,6 +408,15 @@ When the texture object is deleted, the new texture is deleted and the old textu
use whole viewport to capture
+ .. attribute:: depth
+
+ use depth component of viewport as array of float - not suitable for texture source,
+ should only be used with bge.texture.imageToArray(mode='F')
+
+ .. attribute:: zbuff
+
+ use depth component of viewport as grey scale color - suitable for texture source
+
.. class:: Texture(gameObj)
Texture objects
@@ -518,13 +536,16 @@ When the texture object is deleted, the new texture is deleted and the old textu
0 to force a fixed 0 color channel and 1 to force a fixed 255 color channel.
Example: "BGR" will return 3 bytes per pixel with the Blue, Green and Red channels in that order.
"RGB1" will return 4 bytes per pixel with the Red, Green, Blue channels in that order and the alpha channel forced to 255.
+ A special mode "F" allows to return the image as an array of float. This mode should only be used to retrieve
+ the depth buffer of the ImageViewport and ImageRender object.
The default mode is "RGBA".
+
:type mode: string
:rtype: :class:`~bgl.buffer`
:return: A object representing the image as one dimensional array of bytes of size (pixel_size*width*height),
line by line starting from the bottom of the image. The pixel size and format is determined by the mode
- parameter.
+ parameter. For mode 'F', the array is a one dimensional array of float of size (width*height).
.. function:: materialID(object,name)
diff --git a/doc/python_api/rst/bge.types.rst b/doc/python_api/rst/bge.types.rst
index 31ae45b9bf0..fdaeb61173f 100644
--- a/doc/python_api/rst/bge.types.rst
+++ b/doc/python_api/rst/bge.types.rst
@@ -4,6 +4,33 @@ Game Types (bge.types)
.. module:: bge.types
+************
+Introduction
+************
+
+This module contains the classes that appear as instances in the Game Engine. A
+script must interact with these classes if it is to affect the behaviour of
+objects in a game.
+
+The following example would move an object (i.e. an instance of
+:class:`KX_GameObject`) one unit up.
+
+.. code-block:: python
+
+ # bge.types.SCA_PythonController
+ cont = bge.logic.getCurrentController()
+
+ # bge.types.KX_GameObject
+ obj = cont.owner
+ obj.worldPosition.z += 1
+
+To run the code, it could be placed in a Blender text block and executed with
+a :class:`SCA_PythonController` logic brick.
+
+*****
+Types
+*****
+
.. class:: PyObjectPlus
PyObjectPlus base class of most other types in the Game Engine.
@@ -306,7 +333,8 @@ Game Types (bge.types)
.. attribute:: useContinue
- The actions continue option, True or False. When True, the action will always play from where last left off, otherwise negative events to this actuator will reset it to its start frame.
+ The actions continue option, True or False. When True, the action will always play from where last left off,
+ otherwise negative events to this actuator will reset it to its start frame.
:type: boolean
@@ -852,7 +880,54 @@ Game Types (bge.types)
.. note::
- Calling ANY method or attribute on an object that has been removed from a scene will raise a SystemError, if an object may have been removed since last accessing it use the :data:`invalid` attribute to check.
+ Calling ANY method or attribute on an object that has been removed from a scene will raise a SystemError,
+ if an object may have been removed since last accessing it use the :data:`invalid` attribute to check.
+
+ KX_GameObject can be subclassed to extend functionality. For example:
+
+ .. code-block:: python
+
+ import bge
+
+ class CustomGameObject(bge.types.KX_GameObject):
+ RATE = 0.05
+
+ def __init__(self, old_owner):
+ # "old_owner" can just be ignored. At this point, "self" is
+ # already the object in the scene, and "old_owner" has been
+ # destroyed.
+
+ # New attributes can be defined - but we could also use a game
+ # property, like "self['rate']".
+ self.rate = CustomGameObject.RATE
+
+ def update(self):
+ self.worldPosition.z += self.rate
+
+ # switch direction
+ if self.worldPosition.z > 1.0:
+ self.rate = -CustomGameObject.RATE
+ elif self.worldPosition.z < 0.0:
+ self.rate = CustomGameObject.RATE
+
+ # Called first
+ def mutate(cont):
+ old_object = cont.owner
+ mutated_object = CustomGameObject(cont.owner)
+
+ # After calling the constructor above, references to the old object
+ # should not be used.
+ assert(old_object is not mutated_object)
+ assert(old_object.invalid)
+ assert(mutated_object is cont.owner)
+
+ # Called later - note we are now working with the mutated object.
+ def update(cont):
+ cont.owner.update()
+
+ When subclassing objects other than empties and meshes, the specific type
+ should be used - e.g. inherit from :class:`BL_ArmatureObject` when the object
+ to mutate is an armature.
.. attribute:: name
@@ -913,6 +988,24 @@ Game Types (bge.types)
The object's parent object. (read-only).
:type: :class:`KX_GameObject` or None
+
+ .. attribute:: group_children
+
+ Returns the list of group members if the object is a group object, otherwise None is returned.
+
+ :type: :class:`CListValue` of :class:`KX_GameObject` or None
+
+ .. attribute:: group_parent
+
+ Returns the group object that the object belongs to or None if the object is not part of a group.
+
+ :type: :class:`KX_GameObject` or None
+
+ .. attribute:: scene
+
+ The object's scene. (read-only).
+
+ :type: :class:`KX_Scene` or None
.. attribute:: visible
@@ -3371,6 +3464,26 @@ Game Types (bge.types)
:arg wheelIndex: the wheel index
:type wheelIndex: integer
+.. class:: KX_CharacterWrapper(PyObjectPlus)
+
+ A wrapper to expose character physics options.
+
+ .. attribute:: onGround
+
+ Whether or not the character is on the ground. (read-only)
+
+ :type: boolean
+
+ .. attribute:: gravity
+
+ The gravity value used for the character.
+
+ :type: float
+
+ .. method:: jump()
+
+ The character jumps based on it's jump speed.
+
.. class:: KX_VertexProxy(SCA_IObject)
A vertex holds position, UV, color and normal information.
@@ -4473,7 +4586,9 @@ Game Types (bge.types)
.. data:: KX_ACT_ARMATURE_RUN
- Just make sure the armature will be updated on the next graphic frame. This is the only persistent mode of the actuator: it executes automatically once per frame until stopped by a controller
+ Just make sure the armature will be updated on the next graphic frame.
+ This is the only persistent mode of the actuator:
+ it executes automatically once per frame until stopped by a controller
:value: 0
diff --git a/doc/python_api/rst/change_log.rst b/doc/python_api/rst/change_log.rst
index 4d8f9a5171e..c1f3c2e4267 100644
--- a/doc/python_api/rst/change_log.rst
+++ b/doc/python_api/rst/change_log.rst
@@ -2397,3 +2397,1502 @@ Removed
* **ffmpeg_packetsize**
* **ffmpeg_video_bitrate**
+2.62 to 2.63
+============
+
+bpy.types.ThemeView3D
+---------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ThemeView3D.camera`
+* :class:`bpy.types.ThemeView3D.empty`
+
+bpy.types.KeyingSet
+-------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.KeyingSet.bl_description`
+* :class:`bpy.types.KeyingSet.bl_idname`
+
+Renamed
+^^^^^^^
+
+* **name** -> :class:`bpy.types.KeyingSet.bl_label`
+
+bpy.types.BlendDataScenes
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.BlendDataScenes.tag`
+
+bpy.types.RenderEngine
+----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.RenderEngine.camera_override`
+
+bpy.types.BackgroundImage
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.BackgroundImage.show_on_foreground`
+
+bpy.types.CyclesRenderSettings
+------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CyclesRenderSettings.preview_active_layer`
+* :class:`bpy.types.CyclesRenderSettings.sample_clamp`
+
+bpy.types.ToolSettings
+----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ToolSettings.double_threshold`
+
+bpy.types.Image
+---------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Image.render_slot`
+
+bpy.types.MovieTrackingStabilization
+------------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.MovieTrackingStabilization.filter_type`
+
+bpy.types.DomainFluidSettings
+-----------------------------
+
+Removed
+^^^^^^^
+
+* **viscosity_preset**
+
+bpy.types.ParticleSettings
+--------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ParticleSettings.use_rotations`
+
+bpy.types.SceneGameData
+-----------------------
+
+Renamed
+^^^^^^^
+
+* **dome_tesselation** -> :class:`bpy.types.SceneGameData.dome_tessellation`
+
+bpy.types.RegionView3D
+----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.RegionView3D.update`
+
+bpy.types.Scene
+---------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Scene.active_layer`
+
+bpy.types.ShaderNodeTexEnvironment
+----------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ShaderNodeTexEnvironment.projection`
+
+bpy.types.UserPreferencesEdit
+-----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.UserPreferencesEdit.fcurve_unselected_alpha`
+
+bpy.types.MeshTextureFace
+-------------------------
+
+Removed
+^^^^^^^
+
+* **pin_uv**
+* **select_uv**
+
+bpy.types.Menu
+--------------
+
+Function Arguments
+^^^^^^^^^^^^^^^^^^
+
+* :class:`bpy.types.Menu.path_menu` (self, searchpaths, operator, props_default, filter_ext), *was (self, searchpaths, operator, props_default)*
+
+bpy.types.CompositorNodeDistanceMatte
+-------------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CompositorNodeDistanceMatte.channel`
+
+bpy.types.KeyingSetInfo
+-----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.KeyingSetInfo.bl_description`
+
+bpy.types.KeyingSets
+--------------------
+
+Function Arguments
+^^^^^^^^^^^^^^^^^^
+
+* :class:`bpy.types.KeyingSets.new` (idname, name), *was (name)*
+
+bpy.types.CompositorNodeOutputFile
+----------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CompositorNodeOutputFile.active_input`
+* :class:`bpy.types.CompositorNodeOutputFile.active_input_index`
+* :class:`bpy.types.CompositorNodeOutputFile.base_path`
+
+Removed
+^^^^^^^
+
+* **filepath**
+* **frame_end**
+* **frame_start**
+
+Renamed
+^^^^^^^
+
+* **image_settings** -> :class:`bpy.types.CompositorNodeOutputFile.format`
+
+bpy.types.CyclesCameraSettings
+------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CyclesCameraSettings.aperture_fstop`
+* :class:`bpy.types.CyclesCameraSettings.aperture_type`
+
+bpy.types.Struct
+----------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Struct.translation_context`
+
+bpy.types.ThemeSequenceEditor
+-----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ThemeSequenceEditor.movieclip_strip`
+* :class:`bpy.types.ThemeSequenceEditor.preview_back`
+
+bpy.types.TexMapping
+--------------------
+
+Renamed
+^^^^^^^
+
+* **location** -> :class:`bpy.types.TexMapping.translation`
+
+bpy.types.ArmatureActuator
+--------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ArmatureActuator.influence`
+
+bpy.types.ThemeTextEditor
+-------------------------
+
+Removed
+^^^^^^^
+
+* **scroll_bar**
+
+bpy.types.ThemeUserInterface
+----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ThemeUserInterface.wcol_tooltip`
+
+bpy.types.MeshEdge
+------------------
+
+Removed
+^^^^^^^
+
+* **is_fgon**
+
+bpy.types.Brush
+---------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Brush.sculpt_capabilities`
+
+Renamed
+^^^^^^^
+
+* **use_space_atten** -> :class:`bpy.types.Brush.use_space_attenuation`
+
+bpy.types.ShaderNodeMapping
+---------------------------
+
+Renamed
+^^^^^^^
+
+* **location** -> :class:`bpy.types.ShaderNodeMapping.translation`
+
+bpy.types.Mesh
+--------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Mesh.auto_texspace`
+* :class:`bpy.types.Mesh.calc_tessface`
+* :class:`bpy.types.Mesh.loops`
+* :class:`bpy.types.Mesh.polygons`
+* :class:`bpy.types.Mesh.tessface_uv_textures`
+* :class:`bpy.types.Mesh.tessface_vertex_colors`
+* :class:`bpy.types.Mesh.tessfaces`
+* :class:`bpy.types.Mesh.unit_test_compare`
+* :class:`bpy.types.Mesh.uv_layer_clone`
+* :class:`bpy.types.Mesh.uv_layer_clone_index`
+* :class:`bpy.types.Mesh.uv_layer_stencil`
+* :class:`bpy.types.Mesh.uv_layer_stencil_index`
+* :class:`bpy.types.Mesh.uv_layers`
+
+Removed
+^^^^^^^
+
+* **faces**
+* **layers_float**
+* **layers_string**
+
+Renamed
+^^^^^^^
+
+* **layers_int** -> :class:`bpy.types.Mesh.polygon_layers_float`
+* **layers_int** -> :class:`bpy.types.Mesh.polygon_layers_int`
+* **layers_int** -> :class:`bpy.types.Mesh.polygon_layers_string`
+
+Function Arguments
+^^^^^^^^^^^^^^^^^^
+
+* :class:`bpy.types.Mesh.update` (calc_edges, calc_tessface), *was (calc_edges)*
+
+bpy.types.Key
+-------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Key.eval_time`
+
+bpy.types.LatticeModifier
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.LatticeModifier.strength`
+
+bpy.types.UserPreferencesView
+-----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.UserPreferencesView.quit_dialog`
+
+
+2.63 to 2.64
+============
+
+bpy.types.CyclesLampSettings
+----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CyclesLampSettings.samples`
+
+bpy.types.Histogram
+-------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Histogram.show_line`
+
+bpy.types.ThemeView3D
+---------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ThemeView3D.bone_pose_active`
+* :class:`bpy.types.ThemeView3D.skin_root`
+
+bpy.types.GameObjectSettings
+----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.GameObjectSettings.fall_speed`
+* :class:`bpy.types.GameObjectSettings.jump_speed`
+* :class:`bpy.types.GameObjectSettings.step_height`
+
+
+bpy.types.BlendData
+-------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.BlendData.masks`
+
+
+bpy.types.TextureNodeMixRGB
+---------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.TextureNodeMixRGB.use_clamp`
+
+bpy.types.SmokeCollSettings
+---------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SmokeCollSettings.collision_type`
+
+bpy.types.CompositorNodes
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CompositorNodes.active`
+
+bpy.types.RenderEngine
+----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.RenderEngine.resolution_x`
+* :class:`bpy.types.RenderEngine.resolution_y`
+* :class:`bpy.types.RenderEngine.tile_x`
+* :class:`bpy.types.RenderEngine.tile_y`
+
+Function Arguments
+^^^^^^^^^^^^^^^^^^
+
+* :class:`bpy.types.RenderEngine.begin_result` (x, y, w, h, layer), *was (x, y, w, h)*
+* :class:`bpy.types.RenderEngine.end_result` (result, cancel), *was (result)*
+
+bpy.types.BackgroundImage
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.BackgroundImage.draw_depth`
+* :class:`bpy.types.BackgroundImage.frame_method`
+
+bpy.types.SmokeDomainSettings
+-----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SmokeDomainSettings.cell_size`
+* :class:`bpy.types.SmokeDomainSettings.density`
+* :class:`bpy.types.SmokeDomainSettings.domain_resolution`
+* :class:`bpy.types.SmokeDomainSettings.scale`
+* :class:`bpy.types.SmokeDomainSettings.start_point`
+
+bpy.types.CyclesRenderSettings
+------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CyclesRenderSettings.aa_samples`
+* :class:`bpy.types.CyclesRenderSettings.ao_samples`
+* :class:`bpy.types.CyclesRenderSettings.blur_glossy`
+* :class:`bpy.types.CyclesRenderSettings.diffuse_samples`
+* :class:`bpy.types.CyclesRenderSettings.glossy_samples`
+* :class:`bpy.types.CyclesRenderSettings.mesh_light_samples`
+* :class:`bpy.types.CyclesRenderSettings.preview_aa_samples`
+* :class:`bpy.types.CyclesRenderSettings.preview_start_resolution`
+* :class:`bpy.types.CyclesRenderSettings.progressive`
+* :class:`bpy.types.CyclesRenderSettings.transmission_samples`
+
+Removed
+^^^^^^^
+
+* **blur_caustics**
+* **debug_min_size**
+
+bpy.types.ActionGroup
+---------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ActionGroup.color_set`
+* :class:`bpy.types.ActionGroup.colors`
+
+Removed
+^^^^^^^
+
+* **custom_color**
+
+bpy.types.WipeSequence
+----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.WipeSequence.input_1`
+* :class:`bpy.types.WipeSequence.input_count`
+
+bpy.types.ToolSettings
+----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ToolSettings.snap_node_element`
+* :class:`bpy.types.ToolSettings.use_proportional_edit_mask`
+
+bpy.types.ThemeClipEditor
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ThemeClipEditor.space_list`
+* :class:`bpy.types.ThemeClipEditor.strips`
+* :class:`bpy.types.ThemeClipEditor.strips_selected`
+
+bpy.types.Image
+---------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Image.colorspace_settings`
+* :class:`bpy.types.Image.frame_duration`
+* :class:`bpy.types.Image.gl_touch`
+* :class:`bpy.types.Image.scale`
+* :class:`bpy.types.Image.view_as_render`
+
+
+bpy.types.ThemeDopeSheet
+------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ThemeDopeSheet.summary`
+
+bpy.types.MovieClipUser
+-----------------------
+
+Renamed
+^^^^^^^
+
+* **current_frame** -> :class:`bpy.types.MovieClipUser.frame_current`
+
+bpy.types.TransformSequence
+---------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.TransformSequence.input_1`
+* :class:`bpy.types.TransformSequence.input_count`
+
+bpy.types.ImageSequence
+-----------------------
+
+Removed
+^^^^^^^
+
+* **color_balance**
+* **use_color_balance**
+
+bpy.types.DupliObject
+---------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.DupliObject.index`
+* :class:`bpy.types.DupliObject.particle_index`
+
+bpy.types.RenderSettings
+------------------------
+
+Removed
+^^^^^^^
+
+* **use_color_management**
+* **use_radiosity**
+
+bpy.types.Curve
+---------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Curve.bevel_factor_end`
+* :class:`bpy.types.Curve.bevel_factor_start`
+
+bpy.types.MovieClip
+-------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.MovieClip.colorspace_settings`
+* :class:`bpy.types.MovieClip.frame_duration`
+* :class:`bpy.types.MovieClip.frame_offset`
+* :class:`bpy.types.MovieClip.frame_start`
+
+bpy.types.CompositorNodeTree
+----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CompositorNodeTree.chunk_size`
+* :class:`bpy.types.CompositorNodeTree.edit_quality`
+* :class:`bpy.types.CompositorNodeTree.render_quality`
+* :class:`bpy.types.CompositorNodeTree.two_pass`
+* :class:`bpy.types.CompositorNodeTree.use_opencl`
+
+bpy.types.SpaceUVEditor
+-----------------------
+
+Removed
+^^^^^^^
+
+* **cursor_location**
+* **pivot_point**
+
+bpy.types.RemeshModifier
+------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.RemeshModifier.use_smooth_shade`
+
+bpy.types.CurveMapping
+----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CurveMapping.update`
+
+bpy.types.CompositorNodeMixRGB
+------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CompositorNodeMixRGB.use_clamp`
+
+bpy.types.ParticleSettings
+--------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ParticleSettings.use_scale_dupli`
+
+bpy.types.SceneGameData
+-----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SceneGameData.deactivation_angular_threshold`
+* :class:`bpy.types.SceneGameData.deactivation_linear_threshold`
+* :class:`bpy.types.SceneGameData.deactivation_time`
+
+bpy.types.SoundSequence
+-----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SoundSequence.show_waveform`
+
+bpy.types.Scene
+---------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Scene.display_settings`
+* :class:`bpy.types.Scene.sequence_editor_clear`
+* :class:`bpy.types.Scene.sequence_editor_create`
+* :class:`bpy.types.Scene.sequencer_colorspace_settings`
+* :class:`bpy.types.Scene.view_settings`
+
+Removed
+^^^^^^^
+
+* **collada_export**
+
+bpy.types.Armature
+------------------
+
+Removed
+^^^^^^^
+
+* **use_deform_envelopes**
+* **use_deform_preserve_volume**
+* **use_deform_vertex_groups**
+
+bpy.types.MeshUVLoopLayer
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.MeshUVLoopLayer.name`
+
+bpy.types.CurveMap
+------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CurveMap.evaluate`
+
+bpy.types.ShaderNodeTexEnvironment
+----------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ShaderNodeTexEnvironment.image_user`
+
+bpy.types.SolidifyModifier
+--------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SolidifyModifier.use_flip_normals`
+
+bpy.types.TextureNodeMath
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.TextureNodeMath.use_clamp`
+
+bpy.types.SceneRenderLayer
+--------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SceneRenderLayer.layers_exclude`
+* :class:`bpy.types.SceneRenderLayer.samples`
+
+bpy.types.CompositorNodeViewer
+------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CompositorNodeViewer.center_x`
+* :class:`bpy.types.CompositorNodeViewer.center_y`
+* :class:`bpy.types.CompositorNodeViewer.tile_order`
+
+bpy.types.ClothCollisionSettings
+--------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ClothCollisionSettings.vertex_group_self_collisions`
+
+bpy.types.SpeedControlSequence
+------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SpeedControlSequence.input_1`
+* :class:`bpy.types.SpeedControlSequence.input_count`
+
+bpy.types.ActionConstraint
+--------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ActionConstraint.use_bone_object_action`
+
+bpy.types.CompositorNodeScale
+-----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CompositorNodeScale.frame_method`
+* :class:`bpy.types.CompositorNodeScale.offset_x`
+* :class:`bpy.types.CompositorNodeScale.offset_y`
+
+bpy.types.SpaceDopeSheetEditor
+------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SpaceDopeSheetEditor.show_group_colors`
+
+bpy.types.MetaSequence
+----------------------
+
+Removed
+^^^^^^^
+
+* **color_balance**
+* **use_color_balance**
+
+bpy.types.ShaderNodeMixRGB
+--------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ShaderNodeMixRGB.use_clamp`
+
+bpy.types.FollowTrackConstraint
+-------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.FollowTrackConstraint.frame_method`
+
+bpy.types.EffectSequence
+------------------------
+
+Removed
+^^^^^^^
+
+* **color_balance**
+* **use_color_balance**
+
+bpy.types.ThemeNLAEditor
+------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ThemeNLAEditor.active_action`
+* :class:`bpy.types.ThemeNLAEditor.active_action_unset`
+* :class:`bpy.types.ThemeNLAEditor.meta_strips`
+* :class:`bpy.types.ThemeNLAEditor.meta_strips_selected`
+* :class:`bpy.types.ThemeNLAEditor.sound_strips`
+* :class:`bpy.types.ThemeNLAEditor.sound_strips_selected`
+* :class:`bpy.types.ThemeNLAEditor.transition_strips`
+* :class:`bpy.types.ThemeNLAEditor.transition_strips_selected`
+* :class:`bpy.types.ThemeNLAEditor.tweak`
+* :class:`bpy.types.ThemeNLAEditor.tweak_duplicate`
+
+Removed
+^^^^^^^
+
+* **bars**
+* **bars_selected**
+
+bpy.types.SculptCapabilities
+----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SculptCapabilities.has_overlay`
+* :class:`bpy.types.SculptCapabilities.has_texture_angle`
+* :class:`bpy.types.SculptCapabilities.has_texture_angle_source`
+
+bpy.types.ImageFormatSettings
+-----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ImageFormatSettings.display_settings`
+* :class:`bpy.types.ImageFormatSettings.view_settings`
+
+
+bpy.types.Property
+------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Property.is_library_editable`
+
+bpy.types.MovieTrackingTrack
+----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.MovieTrackingTrack.grease_pencil`
+* :class:`bpy.types.MovieTrackingTrack.motion_model`
+* :class:`bpy.types.MovieTrackingTrack.use_alpha_preview`
+* :class:`bpy.types.MovieTrackingTrack.use_brute`
+* :class:`bpy.types.MovieTrackingTrack.use_mask`
+* :class:`bpy.types.MovieTrackingTrack.use_normalization`
+
+Removed
+^^^^^^^
+
+* **pattern_max**
+* **pattern_min**
+* **pyramid_levels**
+* **search_max**
+* **search_min**
+* **tracker**
+
+bpy.types.CompositorNodeBlur
+----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CompositorNodeBlur.use_variable_size`
+
+bpy.types.Object
+----------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Object.dm_info`
+* :class:`bpy.types.Object.is_deform_modified`
+* :class:`bpy.types.Object.layers_local_view`
+
+Renamed
+^^^^^^^
+
+* **animation_visualisation** -> :class:`bpy.types.Object.animation_visualization`
+
+bpy.types.UserPreferencesSystem
+-------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.UserPreferencesSystem.use_gpu_mipmap`
+
+Removed
+^^^^^^^
+
+* **compute_device**
+* **compute_device_type**
+
+bpy.types.Sequence
+------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Sequence.modifiers`
+* :class:`bpy.types.Sequence.use_linear_modifiers`
+
+Removed
+^^^^^^^
+
+* **input_1**
+* **input_2**
+* **input_3**
+* **input_count**
+* **waveform**
+
+bpy.types.ConsoleLine
+---------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ConsoleLine.type`
+
+bpy.types.Region
+----------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Region.view2d`
+* :class:`bpy.types.Region.x`
+* :class:`bpy.types.Region.y`
+
+bpy.types.SpaceClipEditor
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SpaceClipEditor.grease_pencil_source`
+* :class:`bpy.types.SpaceClipEditor.mask`
+* :class:`bpy.types.SpaceClipEditor.mask_draw_type`
+* :class:`bpy.types.SpaceClipEditor.pivot_point`
+* :class:`bpy.types.SpaceClipEditor.show_graph_hidden`
+* :class:`bpy.types.SpaceClipEditor.show_graph_only_selected`
+* :class:`bpy.types.SpaceClipEditor.show_mask_smooth`
+* :class:`bpy.types.SpaceClipEditor.show_seconds`
+
+bpy.types.NodeSocket
+--------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.NodeSocket.hide`
+* :class:`bpy.types.NodeSocket.is_linked`
+
+bpy.types.MovieClipSequence
+---------------------------
+
+Removed
+^^^^^^^
+
+* **color_balance**
+* **use_color_balance**
+
+bpy.types.Node
+--------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Node.color`
+* :class:`bpy.types.Node.hide`
+* :class:`bpy.types.Node.mute`
+* :class:`bpy.types.Node.select`
+* :class:`bpy.types.Node.show_options`
+* :class:`bpy.types.Node.show_preview`
+* :class:`bpy.types.Node.use_custom_color`
+
+bpy.types.SceneSequence
+-----------------------
+
+Removed
+^^^^^^^
+
+* **color_balance**
+* **use_color_balance**
+
+bpy.types.CompositorNodeOutputFile
+----------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CompositorNodeOutputFile.file_slots`
+* :class:`bpy.types.CompositorNodeOutputFile.layer_slots`
+
+Removed
+^^^^^^^
+
+* **active_input**
+
+bpy.types.ObjectBase
+--------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ObjectBase.layers_local_view`
+
+bpy.types.CyclesCameraSettings
+------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CyclesCameraSettings.fisheye_fov`
+* :class:`bpy.types.CyclesCameraSettings.fisheye_lens`
+* :class:`bpy.types.CyclesCameraSettings.panorama_type`
+
+bpy.types.CompositorNodeDefocus
+-------------------------------
+
+Removed
+^^^^^^^
+
+* **samples**
+
+bpy.types.KeyMapItems
+---------------------
+
+Function Arguments
+^^^^^^^^^^^^^^^^^^
+
+* :class:`bpy.types.KeyMapItems.new` (idname, type, value, any, shift, ctrl, alt, oskey, key_modifier, head), *was (idname, type, value, any, shift, ctrl, alt, oskey, key_modifier)*
+
+bpy.types.CollisionSettings
+---------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CollisionSettings.stickiness`
+
+Removed
+^^^^^^^
+
+* **stickness**
+
+bpy.types.GlowSequence
+----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.GlowSequence.input_1`
+* :class:`bpy.types.GlowSequence.input_count`
+
+bpy.types.MouseSensor
+---------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.MouseSensor.use_pulse`
+
+bpy.types.MovieSequence
+-----------------------
+
+Removed
+^^^^^^^
+
+* **color_balance**
+* **use_color_balance**
+
+bpy.types.Pose
+--------------
+
+Renamed
+^^^^^^^
+
+* **animation_visualisation** -> :class:`bpy.types.Pose.animation_visualization`
+
+bpy.types.ThemeSequenceEditor
+-----------------------------
+
+Removed
+^^^^^^^
+
+* **plugin_strip**
+
+bpy.types.IMAGE_UV_sculpt
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.IMAGE_UV_sculpt.prop_unified_weight`
+
+bpy.types.SpaceImageEditor
+--------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SpaceImageEditor.cursor_location`
+* :class:`bpy.types.SpaceImageEditor.mask`
+* :class:`bpy.types.SpaceImageEditor.mask_draw_type`
+* :class:`bpy.types.SpaceImageEditor.mode`
+* :class:`bpy.types.SpaceImageEditor.pivot_point`
+* :class:`bpy.types.SpaceImageEditor.show_mask_smooth`
+* :class:`bpy.types.SpaceImageEditor.show_maskedit`
+
+Removed
+^^^^^^^
+
+* **curve**
+* **use_grease_pencil**
+* **use_image_paint**
+
+bpy.types.UserPreferencesFilePaths
+----------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.UserPreferencesFilePaths.i18n_branches_directory`
+
+Removed
+^^^^^^^
+
+* **sequence_plugin_directory**
+* **texture_plugin_directory**
+
+bpy.types.CompositorNodeDilateErode
+-----------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CompositorNodeDilateErode.edge`
+* :class:`bpy.types.CompositorNodeDilateErode.falloff`
+* :class:`bpy.types.CompositorNodeDilateErode.type`
+
+bpy.types.ScrewModifier
+-----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ScrewModifier.use_smooth_shade`
+
+bpy.types.SpaceNodeEditor
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SpaceNodeEditor.cursor_location`
+* :class:`bpy.types.SpaceNodeEditor.edit_tree`
+* :class:`bpy.types.SpaceNodeEditor.show_highlight`
+* :class:`bpy.types.SpaceNodeEditor.use_hidden_preview`
+
+bpy.types.SpaceView3D
+---------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SpaceView3D.layers_local_view`
+* :class:`bpy.types.SpaceView3D.show_backface_culling`
+
+bpy.types.Area
+--------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Area.x`
+* :class:`bpy.types.Area.y`
+
+bpy.types.RenderLayer
+---------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.RenderLayer.layers_exclude`
+
+bpy.types.MovieTracking
+-----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.MovieTracking.dopesheet`
+
+bpy.types.MovieTrackingSettings
+-------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.MovieTrackingSettings.default_motion_model`
+* :class:`bpy.types.MovieTrackingSettings.use_default_brute`
+* :class:`bpy.types.MovieTrackingSettings.use_default_mask`
+* :class:`bpy.types.MovieTrackingSettings.use_default_normalization`
+* :class:`bpy.types.MovieTrackingSettings.use_tripod_solver`
+
+Removed
+^^^^^^^
+
+* **default_pyramid_levels**
+* **default_tracker**
+
+bpy.types.CompositorNodeIDMask
+------------------------------
+
+Renamed
+^^^^^^^
+
+* **use_smooth_mask** -> :class:`bpy.types.CompositorNodeIDMask.use_antialiasing`
+
+bpy.types.UserPreferencesInput
+------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.UserPreferencesInput.ndof_orbit_sensitivity`
+* :class:`bpy.types.UserPreferencesInput.ndof_view_rotate_method`
+
+bpy.types.Brush
+---------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Brush.mask_tool`
+* :class:`bpy.types.Brush.weight`
+
+bpy.types.SpaceSequenceEditor
+-----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SpaceSequenceEditor.overlay_type`
+
+Removed
+^^^^^^^
+
+* **use_grease_pencil**
+
+bpy.types.MovieTrackingMarkers
+------------------------------
+
+Function Arguments
+^^^^^^^^^^^^^^^^^^
+
+* :class:`bpy.types.MovieTrackingMarkers.find_frame` (frame, exact), *was (frame)*
+
+bpy.types.UILayout
+------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.UILayout.template_colormanaged_view_settings`
+* :class:`bpy.types.UILayout.template_colorspace_settings`
+
+Function Arguments
+^^^^^^^^^^^^^^^^^^
+
+* :class:`bpy.types.UILayout.template_image_settings` (image_settings, color_management), *was (image_settings)*
+
+bpy.types.ID
+------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ID.is_library_indirect`
+
+bpy.types.SpaceGraphEditor
+--------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.SpaceGraphEditor.show_group_colors`
+
+bpy.types.Mesh
+--------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Mesh.skin_vertices`
+
+Removed
+^^^^^^^
+
+* **sticky**
+
+bpy.types.ShaderNodes
+---------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ShaderNodes.active`
+
+bpy.types.ColorSequence
+-----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ColorSequence.input_count`
+
+bpy.types.ShaderNodeMath
+------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ShaderNodeMath.use_clamp`
+
+bpy.types.Paint
+---------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Paint.input_samples`
+
+bpy.types.ShaderNodeTexImage
+----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ShaderNodeTexImage.image_user`
+* :class:`bpy.types.ShaderNodeTexImage.projection`
+* :class:`bpy.types.ShaderNodeTexImage.projection_blend`
+
+bpy.types.UserPreferencesView
+-----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.UserPreferencesView.use_mouse_depth_cursor`
+
+Renamed
+^^^^^^^
+
+* **use_mouse_auto_depth** -> :class:`bpy.types.UserPreferencesView.use_mouse_depth_navigate`
+
+bpy.types.CompositorNodeMath
+----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CompositorNodeMath.use_clamp`
+
+bpy.types.Material
+------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.Material.use_uv_project`
+
+bpy.types.ThemeNodeEditor
+-------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.ThemeNodeEditor.frame_node`
+* :class:`bpy.types.ThemeNodeEditor.node_active`
+* :class:`bpy.types.ThemeNodeEditor.node_selected`
+
+bpy.types.Camera
+----------------
+
+Removed
+^^^^^^^
+
+* **use_panorama**
+
+bpy.types.UnifiedPaintSettings
+------------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.UnifiedPaintSettings.use_unified_weight`
+* :class:`bpy.types.UnifiedPaintSettings.weight`
+
+bpy.types.TextureNodes
+----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.TextureNodes.active`
+
+bpy.types.MovieTrackingMarker
+-----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.MovieTrackingMarker.pattern_bound_box`
+* :class:`bpy.types.MovieTrackingMarker.pattern_corners`
+* :class:`bpy.types.MovieTrackingMarker.search_max`
+* :class:`bpy.types.MovieTrackingMarker.search_min`
+
+bpy.types.CyclesWorldSettings
+-----------------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.CyclesWorldSettings.samples`
+
+bpy.types.LatticePoint
+----------------------
+
+Added
+^^^^^
+
+* :class:`bpy.types.LatticePoint.select`
diff --git a/doc/python_api/rst/info_overview.rst b/doc/python_api/rst/info_overview.rst
index 30c45213570..818eb692be9 100644
--- a/doc/python_api/rst/info_overview.rst
+++ b/doc/python_api/rst/info_overview.rst
@@ -71,7 +71,7 @@ The only difference between addons and built-in python modules is that addons mu
The user preferences addon listing uses **bl_info** to display information about each addon.
-`See Addons <http://wiki.blender.org/index.php/Dev:2.6/Py/Scripts/Guidelines/Addons>`_ for details on the **bl_info** dictionary.
+`See Addons <http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Guidelines/Addons>`_ for details on the **bl_info** dictionary.
Integration through Classes
diff --git a/doc/python_api/rst/info_quickstart.rst b/doc/python_api/rst/info_quickstart.rst
index 19ec8059aca..62ad4e9c4d8 100644
--- a/doc/python_api/rst/info_quickstart.rst
+++ b/doc/python_api/rst/info_quickstart.rst
@@ -2,8 +2,8 @@
Quickstart Introduction
***********************
-Intro
-=====
+Preface
+=======
This API is generally stable but some areas are still being added and improved.
@@ -58,6 +58,22 @@ A quick list of helpful things to know before starting:
* To examine further scripts distributed with Blender, see ``~/.blender/scripts/startup/bl_ui`` for the user interface and ``~/.blender/scripts/startup/bl_op`` for operators.
+Running Scripts
+---------------
+
+The two most common ways to execute python scripts are using the built-in text editor or entering commands in the python console.
+
+Both the **Text Editor** and **Python Console** are space types you can select from the view header.
+
+Rather then manually configuring your spaces for Python development, you may prefer to use the **Scripting** screen, included default with Blender, accessible from the top headers screen selector.
+
+From the text editor you can open ``.py`` files or paste then from the clipboard, then test using **Run Script**.
+
+The Python Console is typically used for typing in snippets and for testing to get immediate feedback, but can also have entire scripts pasted into it.
+
+Scripts can also run from the command line with Blender but to learn Blender/Python this isn't essential.
+
+
Key Concepts
============
diff --git a/doc/python_api/sphinx_changelog_gen.py b/doc/python_api/sphinx_changelog_gen.py
index 3ded1035123..afc253940d4 100644
--- a/doc/python_api/sphinx_changelog_gen.py
+++ b/doc/python_api/sphinx_changelog_gen.py
@@ -28,15 +28,15 @@ blender --background --python doc/python_api/sphinx_changelog_gen.py -- --dump
# create changelog
blender --background --python doc/python_api/sphinx_changelog_gen.py -- \
- --api_from blender_2_56_1.py \
- --api_to blender_2_57_0.py \
+ --api_from blender_2_63_0.py \
+ --api_to blender_2_64_0.py \
--api_out changes.rst
# Api comparison can also run without blender
-python doc/python_api/sphinx_changelog_gen.py \
- --api_from blender_api_2_56_6.py \
- --api_to blender_api_2_57.py \
+python doc/python_api/sphinx_changelog_gen.py -- \
+ --api_from blender_api_2_63_0.py \
+ --api_to blender_api_2_64_0.py \
--api_out changes.rst
# Save the latest API dump in this folder, renaming it with its revision.
@@ -307,6 +307,8 @@ def api_changelog(api_from, api_to, api_out):
fout.close()
+ print("Written: %r" % api_out)
+
def main():
import sys
@@ -347,6 +349,7 @@ def main():
args = parser.parse_args(argv) # In this example we wont use the args
if not argv:
+ print("No args given!")
parser.print_help()
return
diff --git a/doc/python_api/sphinx_doc_gen.py b/doc/python_api/sphinx_doc_gen.py
index 186f67b0df6..6f7d4f3582a 100644
--- a/doc/python_api/sphinx_doc_gen.py
+++ b/doc/python_api/sphinx_doc_gen.py
@@ -399,7 +399,7 @@ SPHINX_THEMES = {'bf': ['blender-org'], # , 'naiad',
available_themes = SPHINX_THEMES['bf'] + SPHINX_THEMES['sphinx']
if ARGS.sphinx_theme not in available_themes:
- print ("Please choose a theme among: %s" % ', '.join(available_themes))
+ print("Please choose a theme among: %s" % ', '.join(available_themes))
sys.exit()
if ARGS.sphinx_theme in SPHINX_THEMES['bf']:
@@ -910,6 +910,72 @@ def pymodule2sphinx(basepath, module_name, module, title):
file.close()
+# Changes in blender will force errors here
+context_type_map = {
+ "active_base": ("ObjectBase", False),
+ "active_bone": ("EditBone", False),
+ "active_object": ("Object", False),
+ "active_operator": ("Operator", False),
+ "active_pose_bone": ("PoseBone", False),
+ "active_node": ("Node", False),
+ "armature": ("Armature", False),
+ "bone": ("Bone", False),
+ "brush": ("Brush", False),
+ "camera": ("Camera", False),
+ "cloth": ("ClothModifier", False),
+ "collision": ("CollisionModifier", False),
+ "curve": ("Curve", False),
+ "dynamic_paint": ("DynamicPaintModifier", False),
+ "edit_bone": ("EditBone", False),
+ "edit_image": ("Image", False),
+ "edit_mask": ("Mask", False),
+ "edit_movieclip": ("MovieClip", False),
+ "edit_object": ("Object", False),
+ "edit_text": ("Text", False),
+ "editable_bones": ("EditBone", True),
+ "fluid": ("FluidSimulationModifier", False),
+ "image_paint_object": ("Object", False),
+ "lamp": ("Lamp", False),
+ "lattice": ("Lattice", False),
+ "material": ("Material", False),
+ "material_slot": ("MaterialSlot", False),
+ "mesh": ("Mesh", False),
+ "meta_ball": ("MetaBall", False),
+ "object": ("Object", False),
+ "particle_edit_object": ("Object", False),
+ "particle_settings": ("ParticleSettings", False),
+ "particle_system": ("ParticleSystem", False),
+ "particle_system_editable": ("ParticleSystem", False),
+ "pose_bone": ("PoseBone", False),
+ "scene": ("Scene", False),
+ "sculpt_object": ("Object", False),
+ "selectable_bases": ("ObjectBase", True),
+ "selectable_objects": ("Object", True),
+ "selected_bases": ("ObjectBase", True),
+ "selected_bones": ("EditBone", True),
+ "selected_editable_bases": ("ObjectBase", True),
+ "selected_editable_bones": ("EditBone", True),
+ "selected_editable_objects": ("Object", True),
+ "selected_editable_sequences": ("Sequence", True),
+ "selected_nodes": ("Node", True),
+ "selected_objects": ("Object", True),
+ "selected_pose_bones": ("PoseBone", True),
+ "selected_sequences": ("Sequence", True),
+ "sequences": ("Sequence", True),
+ "smoke": ("SmokeModifier", False),
+ "soft_body": ("SoftBodyModifier", False),
+ "speaker": ("Speaker", False),
+ "texture": ("Texture", False),
+ "texture_slot": ("MaterialTextureSlot", False),
+ "texture_user": ("ID", False),
+ "vertex_paint_object": ("Object", False),
+ "visible_bases": ("ObjectBase", True),
+ "visible_bones": ("EditBone", True),
+ "visible_objects": ("Object", True),
+ "visible_pose_bones": ("PoseBone", True),
+ "weight_paint_object": ("Object", False),
+ "world": ("World", False),
+}
def pycontext2sphinx(basepath):
# Only use once. very irregular
@@ -938,72 +1004,6 @@ def pycontext2sphinx(basepath):
"sequencer_context_dir",
)
- # Changes in blender will force errors here
- type_map = {
- "active_base": ("ObjectBase", False),
- "active_bone": ("Bone", False),
- "active_object": ("Object", False),
- "active_operator": ("Operator", False),
- "active_pose_bone": ("PoseBone", False),
- "active_node": ("Node", False),
- "armature": ("Armature", False),
- "bone": ("Bone", False),
- "brush": ("Brush", False),
- "camera": ("Camera", False),
- "cloth": ("ClothModifier", False),
- "collision": ("CollisionModifier", False),
- "curve": ("Curve", False),
- "dynamic_paint": ("DynamicPaintModifier", False),
- "edit_bone": ("EditBone", False),
- "edit_image": ("Image", False),
- "edit_mask": ("Mask", False),
- "edit_movieclip": ("MovieClip", False),
- "edit_object": ("Object", False),
- "edit_text": ("Text", False),
- "editable_bones": ("EditBone", True),
- "fluid": ("FluidSimulationModifier", False),
- "image_paint_object": ("Object", False),
- "lamp": ("Lamp", False),
- "lattice": ("Lattice", False),
- "material": ("Material", False),
- "material_slot": ("MaterialSlot", False),
- "mesh": ("Mesh", False),
- "meta_ball": ("MetaBall", False),
- "object": ("Object", False),
- "particle_edit_object": ("Object", False),
- "particle_settings": ("ParticleSettings", False),
- "particle_system": ("ParticleSystem", False),
- "particle_system_editable": ("ParticleSystem", False),
- "pose_bone": ("PoseBone", False),
- "scene": ("Scene", False),
- "sculpt_object": ("Object", False),
- "selectable_bases": ("ObjectBase", True),
- "selectable_objects": ("Object", True),
- "selected_bases": ("ObjectBase", True),
- "selected_bones": ("Bone", True),
- "selected_editable_bases": ("ObjectBase", True),
- "selected_editable_bones": ("Bone", True),
- "selected_editable_objects": ("Object", True),
- "selected_editable_sequences": ("Sequence", True),
- "selected_nodes": ("Node", True),
- "selected_objects": ("Object", True),
- "selected_pose_bones": ("PoseBone", True),
- "selected_sequences": ("Sequence", True),
- "sequences": ("Sequence", True),
- "smoke": ("SmokeModifier", False),
- "soft_body": ("SoftBodyModifier", False),
- "speaker": ("Speaker", False),
- "texture": ("Texture", False),
- "texture_slot": ("MaterialTextureSlot", False),
- "texture_user": ("ID", False),
- "vertex_paint_object": ("Object", False),
- "visible_bases": ("ObjectBase", True),
- "visible_bones": ("Object", True),
- "visible_objects": ("Object", True),
- "visible_pose_bones": ("PoseBone", True),
- "weight_paint_object": ("Object", False),
- "world": ("World", False),
- }
unique = set()
blend_cdll = ctypes.CDLL("")
@@ -1018,7 +1018,7 @@ def pycontext2sphinx(basepath):
while char_array[i] is not None:
member = ctypes.string_at(char_array[i]).decode(encoding="ascii")
fw(".. data:: %s\n\n" % member)
- member_type, is_seq = type_map[member]
+ member_type, is_seq = context_type_map[member]
fw(" :type: %s :class:`bpy.types.%s`\n\n" % ("sequence of " if is_seq else "", member_type))
unique.add(member)
i += 1
@@ -1026,8 +1026,8 @@ def pycontext2sphinx(basepath):
# generate typemap...
# for member in sorted(unique):
# print(' "%s": ("", False),' % member)
- if len(type_map) > len(unique):
- raise Exception("Some types are not used: %s" % str([member for member in type_map if member not in unique]))
+ if len(context_type_map) > len(unique):
+ raise Exception("Some types are not used: %s" % str([member for member in context_type_map if member not in unique]))
else:
pass # will have raised an error above
@@ -1314,6 +1314,13 @@ def pyrna2sphinx(basepath):
fw(".. hlist::\n")
fw(" :columns: 2\n\n")
+ # context does its own thing
+ # "active_base": ("ObjectBase", False),
+ for ref_attr, (ref_type, ref_is_seq) in sorted(context_type_map.items()):
+ if ref_type == struct_id:
+ fw(" * :mod:`bpy.context.%s`\n" % ref_attr)
+ del ref_attr, ref_type, ref_is_seq
+
for ref in struct.references:
ref_split = ref.split(".")
if len(ref_split) > 2:
diff --git a/extern/Eigen3/Eigen/Cholesky b/extern/Eigen3/Eigen/Cholesky
index 53f7bf911a4..f727f5d89c0 100644
--- a/extern/Eigen3/Eigen/Cholesky
+++ b/extern/Eigen3/Eigen/Cholesky
@@ -5,8 +5,6 @@
#include "src/Core/util/DisableStupidWarnings.h"
-namespace Eigen {
-
/** \defgroup Cholesky_Module Cholesky module
*
*
@@ -24,8 +22,9 @@ namespace Eigen {
#include "src/misc/Solve.h"
#include "src/Cholesky/LLT.h"
#include "src/Cholesky/LDLT.h"
-
-} // namespace Eigen
+#ifdef EIGEN_USE_LAPACKE
+#include "src/Cholesky/LLT_MKL.h"
+#endif
#include "src/Core/util/ReenableStupidWarnings.h"
diff --git a/extern/Eigen3/Eigen/CholmodSupport b/extern/Eigen3/Eigen/CholmodSupport
new file mode 100644
index 00000000000..745b884e74d
--- /dev/null
+++ b/extern/Eigen3/Eigen/CholmodSupport
@@ -0,0 +1,45 @@
+#ifndef EIGEN_CHOLMODSUPPORT_MODULE_H
+#define EIGEN_CHOLMODSUPPORT_MODULE_H
+
+#include "SparseCore"
+
+#include "src/Core/util/DisableStupidWarnings.h"
+
+extern "C" {
+ #include <cholmod.h>
+}
+
+/** \ingroup Support_modules
+ * \defgroup CholmodSupport_Module CholmodSupport module
+ *
+ * This module provides an interface to the Cholmod library which is part of the <a href="http://www.cise.ufl.edu/research/sparse/SuiteSparse/">suitesparse</a> package.
+ * It provides the two following main factorization classes:
+ * - class CholmodSupernodalLLT: a supernodal LLT Cholesky factorization.
+ * - class CholmodDecomposiiton: a general L(D)LT Cholesky factorization with automatic or explicit runtime selection of the underlying factorization method (supernodal or simplicial).
+ *
+ * For the sake of completeness, this module also propose the two following classes:
+ * - class CholmodSimplicialLLT
+ * - class CholmodSimplicialLDLT
+ * Note that these classes does not bring any particular advantage compared to the built-in
+ * SimplicialLLT and SimplicialLDLT factorization classes.
+ *
+ * \code
+ * #include <Eigen/CholmodSupport>
+ * \endcode
+ *
+ * In order to use this module, the cholmod headers must be accessible from the include paths, and your binary must be linked to the cholmod library and its dependencies.
+ * The dependencies depend on how cholmod has been compiled.
+ * For a cmake based project, you can use our FindCholmod.cmake module to help you in this task.
+ *
+ */
+
+#include "src/misc/Solve.h"
+#include "src/misc/SparseSolve.h"
+
+#include "src/CholmodSupport/CholmodSupport.h"
+
+
+#include "src/Core/util/ReenableStupidWarnings.h"
+
+#endif // EIGEN_CHOLMODSUPPORT_MODULE_H
+
diff --git a/extern/Eigen3/Eigen/Core b/extern/Eigen3/Eigen/Core
index a5025e37ead..d4801702261 100644
--- a/extern/Eigen3/Eigen/Core
+++ b/extern/Eigen3/Eigen/Core
@@ -4,24 +4,9 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2007-2011 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_CORE_H
#define EIGEN_CORE_H
@@ -34,6 +19,12 @@
// defined e.g. EIGEN_DONT_ALIGN) so it needs to be done before we do anything with vectorization.
#include "src/Core/util/Macros.h"
+#include <complex>
+
+// this include file manages BLAS and MKL related macros
+// and inclusion of their respective header files
+#include "src/Core/util/MKL_support.h"
+
// if alignment is disabled, then disable vectorization. Note: EIGEN_ALIGN is the proper check, it takes into
// account both the user's will (EIGEN_DONT_ALIGN) and our own platform checks
#if !EIGEN_ALIGN
@@ -136,7 +127,7 @@
#endif
// MSVC for windows mobile does not have the errno.h file
-#if !(defined(_MSC_VER) && defined(_WIN32_WCE))
+#if !(defined(_MSC_VER) && defined(_WIN32_WCE)) && !defined(__ARMCC_VERSION)
#define EIGEN_HAS_ERRNO
#endif
@@ -146,7 +137,6 @@
#include <cstddef>
#include <cstdlib>
#include <cmath>
-#include <complex>
#include <cassert>
#include <functional>
#include <iosfwd>
@@ -175,9 +165,6 @@
#include <new>
#endif
-// defined in bits/termios.h
-#undef B0
-
/** \brief Namespace containing all symbols from the %Eigen library. */
namespace Eigen {
@@ -201,6 +188,8 @@ inline static const char *SimdInstructionSetsInUse(void) {
#endif
}
+} // end namespace Eigen
+
#define STAGE10_FULL_EIGEN2_API 10
#define STAGE20_RESOLVE_API_CONFLICTS 20
#define STAGE30_FULL_EIGEN3_API 30
@@ -247,6 +236,10 @@ using std::ptrdiff_t;
* \endcode
*/
+/** \defgroup Support_modules Support modules [category]
+ * Category of modules which add support for external libraries.
+ */
+
#include "src/Core/util/Constants.h"
#include "src/Core/util/ForwardDeclarations.h"
#include "src/Core/util/Meta.h"
@@ -318,15 +311,15 @@ using std::ptrdiff_t;
#include "src/Core/CommaInitializer.h"
#include "src/Core/Flagged.h"
#include "src/Core/ProductBase.h"
-#include "src/Core/Product.h"
+#include "src/Core/GeneralProduct.h"
#include "src/Core/TriangularMatrix.h"
#include "src/Core/SelfAdjointView.h"
-#include "src/Core/SolveTriangular.h"
+#include "src/Core/products/GeneralBlockPanelKernel.h"
#include "src/Core/products/Parallelizer.h"
#include "src/Core/products/CoeffBasedProduct.h"
-#include "src/Core/products/GeneralBlockPanelKernel.h"
#include "src/Core/products/GeneralMatrixVector.h"
#include "src/Core/products/GeneralMatrixMatrix.h"
+#include "src/Core/SolveTriangular.h"
#include "src/Core/products/GeneralMatrixMatrixTriangular.h"
#include "src/Core/products/SelfadjointMatrixVector.h"
#include "src/Core/products/SelfadjointMatrixMatrix.h"
@@ -347,7 +340,20 @@ using std::ptrdiff_t;
#include "src/Core/ArrayBase.h"
#include "src/Core/ArrayWrapper.h"
-} // namespace Eigen
+#ifdef EIGEN_USE_BLAS
+#include "src/Core/products/GeneralMatrixMatrix_MKL.h"
+#include "src/Core/products/GeneralMatrixVector_MKL.h"
+#include "src/Core/products/GeneralMatrixMatrixTriangular_MKL.h"
+#include "src/Core/products/SelfadjointMatrixMatrix_MKL.h"
+#include "src/Core/products/SelfadjointMatrixVector_MKL.h"
+#include "src/Core/products/TriangularMatrixMatrix_MKL.h"
+#include "src/Core/products/TriangularMatrixVector_MKL.h"
+#include "src/Core/products/TriangularSolverMatrix_MKL.h"
+#endif // EIGEN_USE_BLAS
+
+#ifdef EIGEN_USE_MKL_VML
+#include "src/Core/Assign_MKL.h"
+#endif
#include "src/Core/GlobalFunctions.h"
diff --git a/extern/Eigen3/Eigen/Eigen2Support b/extern/Eigen3/Eigen/Eigen2Support
index d96592a8de9..36156d29a92 100644
--- a/extern/Eigen3/Eigen/Eigen2Support
+++ b/extern/Eigen3/Eigen/Eigen2Support
@@ -3,24 +3,9 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN2SUPPORT_H
#define EIGEN2SUPPORT_H
@@ -31,9 +16,8 @@
#include "src/Core/util/DisableStupidWarnings.h"
-namespace Eigen {
-
-/** \defgroup Eigen2Support_Module Eigen2 support module
+/** \ingroup Support_modules
+ * \defgroup Eigen2Support_Module Eigen2 support module
* This module provides a couple of deprecated functions improving the compatibility with Eigen2.
*
* To use it, define EIGEN2_SUPPORT before including any Eigen header
@@ -56,13 +40,29 @@ namespace Eigen {
#include "src/Eigen2Support/MathFunctions.h"
-} // namespace Eigen
-
#include "src/Core/util/ReenableStupidWarnings.h"
// Eigen2 used to include iostream
#include<iostream>
+#define EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, SizeSuffix) \
+using Eigen::Matrix##SizeSuffix##TypeSuffix; \
+using Eigen::Vector##SizeSuffix##TypeSuffix; \
+using Eigen::RowVector##SizeSuffix##TypeSuffix;
+
+#define EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(TypeSuffix) \
+EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 2) \
+EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 3) \
+EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 4) \
+EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, X) \
+
+#define EIGEN_USING_MATRIX_TYPEDEFS \
+EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(i) \
+EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(f) \
+EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(d) \
+EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(cf) \
+EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(cd)
+
#define USING_PART_OF_NAMESPACE_EIGEN \
EIGEN_USING_MATRIX_TYPEDEFS \
using Eigen::Matrix; \
diff --git a/extern/Eigen3/Eigen/Eigenvalues b/extern/Eigen3/Eigen/Eigenvalues
index 250c0f46652..af99ccd1fab 100644
--- a/extern/Eigen3/Eigen/Eigenvalues
+++ b/extern/Eigen3/Eigen/Eigenvalues
@@ -9,8 +9,7 @@
#include "Jacobi"
#include "Householder"
#include "LU"
-
-namespace Eigen {
+#include "Geometry"
/** \defgroup Eigenvalues_Module Eigenvalues module
*
@@ -35,8 +34,11 @@ namespace Eigen {
#include "src/Eigenvalues/ComplexSchur.h"
#include "src/Eigenvalues/ComplexEigenSolver.h"
#include "src/Eigenvalues/MatrixBaseEigenvalues.h"
-
-} // namespace Eigen
+#ifdef EIGEN_USE_LAPACKE
+#include "src/Eigenvalues/RealSchur_MKL.h"
+#include "src/Eigenvalues/ComplexSchur_MKL.h"
+#include "src/Eigenvalues/SelfAdjointEigenSolver_MKL.h"
+#endif
#include "src/Core/util/ReenableStupidWarnings.h"
diff --git a/extern/Eigen3/Eigen/Geometry b/extern/Eigen3/Eigen/Geometry
index 78277c0c560..efd9d4504cb 100644
--- a/extern/Eigen3/Eigen/Geometry
+++ b/extern/Eigen3/Eigen/Geometry
@@ -13,8 +13,6 @@
#define M_PI 3.14159265358979323846
#endif
-namespace Eigen {
-
/** \defgroup Geometry_Module Geometry module
*
*
@@ -58,8 +56,6 @@ namespace Eigen {
#include "src/Eigen2Support/Geometry/All.h"
#endif
-} // namespace Eigen
-
#include "src/Core/util/ReenableStupidWarnings.h"
#endif // EIGEN_GEOMETRY_MODULE_H
diff --git a/extern/Eigen3/Eigen/Householder b/extern/Eigen3/Eigen/Householder
index 6b86cf65c55..6e348db5c43 100644
--- a/extern/Eigen3/Eigen/Householder
+++ b/extern/Eigen3/Eigen/Householder
@@ -5,8 +5,6 @@
#include "src/Core/util/DisableStupidWarnings.h"
-namespace Eigen {
-
/** \defgroup Householder_Module Householder module
* This module provides Householder transformations.
*
@@ -19,8 +17,6 @@ namespace Eigen {
#include "src/Householder/HouseholderSequence.h"
#include "src/Householder/BlockHouseholder.h"
-} // namespace Eigen
-
#include "src/Core/util/ReenableStupidWarnings.h"
#endif // EIGEN_HOUSEHOLDER_MODULE_H
diff --git a/extern/Eigen3/Eigen/IterativeLinearSolvers b/extern/Eigen3/Eigen/IterativeLinearSolvers
new file mode 100644
index 00000000000..315c2dd1ee7
--- /dev/null
+++ b/extern/Eigen3/Eigen/IterativeLinearSolvers
@@ -0,0 +1,40 @@
+#ifndef EIGEN_ITERATIVELINEARSOLVERS_MODULE_H
+#define EIGEN_ITERATIVELINEARSOLVERS_MODULE_H
+
+#include "SparseCore"
+#include "OrderingMethods"
+
+#include "src/Core/util/DisableStupidWarnings.h"
+
+/** \ingroup Sparse_modules
+ * \defgroup IterativeLinearSolvers_Module IterativeLinearSolvers module
+ *
+ * This module currently provides iterative methods to solve problems of the form \c A \c x = \c b, where \c A is a squared matrix, usually very large and sparse.
+ * Those solvers are accessible via the following classes:
+ * - ConjugateGradient for selfadjoint (hermitian) matrices,
+ * - BiCGSTAB for general square matrices.
+ *
+ * These iterative solvers are associated with some preconditioners:
+ * - IdentityPreconditioner - not really useful
+ * - DiagonalPreconditioner - also called JAcobi preconditioner, work very well on diagonal dominant matrices.
+ * - IncompleteILUT - incomplete LU factorization with dual thresholding
+ *
+ * Such problems can also be solved using the direct sparse decomposition modules: SparseCholesky, CholmodSupport, UmfPackSupport, SuperLUSupport.
+ *
+ * \code
+ * #include <Eigen/IterativeLinearSolvers>
+ * \endcode
+ */
+
+#include "src/misc/Solve.h"
+#include "src/misc/SparseSolve.h"
+
+#include "src/IterativeLinearSolvers/IterativeSolverBase.h"
+#include "src/IterativeLinearSolvers/BasicPreconditioners.h"
+#include "src/IterativeLinearSolvers/ConjugateGradient.h"
+#include "src/IterativeLinearSolvers/BiCGSTAB.h"
+#include "src/IterativeLinearSolvers/IncompleteLUT.h"
+
+#include "src/Core/util/ReenableStupidWarnings.h"
+
+#endif // EIGEN_ITERATIVELINEARSOLVERS_MODULE_H
diff --git a/extern/Eigen3/Eigen/Jacobi b/extern/Eigen3/Eigen/Jacobi
index afa67681379..ba8a4dc36a5 100644
--- a/extern/Eigen3/Eigen/Jacobi
+++ b/extern/Eigen3/Eigen/Jacobi
@@ -5,8 +5,6 @@
#include "src/Core/util/DisableStupidWarnings.h"
-namespace Eigen {
-
/** \defgroup Jacobi_Module Jacobi module
* This module provides Jacobi and Givens rotations.
*
@@ -21,8 +19,6 @@ namespace Eigen {
#include "src/Jacobi/Jacobi.h"
-} // namespace Eigen
-
#include "src/Core/util/ReenableStupidWarnings.h"
#endif // EIGEN_JACOBI_MODULE_H
diff --git a/extern/Eigen3/Eigen/LU b/extern/Eigen3/Eigen/LU
index 226f88ca38a..db579550448 100644
--- a/extern/Eigen3/Eigen/LU
+++ b/extern/Eigen3/Eigen/LU
@@ -5,8 +5,6 @@
#include "src/Core/util/DisableStupidWarnings.h"
-namespace Eigen {
-
/** \defgroup LU_Module LU module
* This module includes %LU decomposition and related notions such as matrix inversion and determinant.
* This module defines the following MatrixBase methods:
@@ -23,6 +21,9 @@ namespace Eigen {
#include "src/misc/Image.h"
#include "src/LU/FullPivLU.h"
#include "src/LU/PartialPivLU.h"
+#ifdef EIGEN_USE_LAPACKE
+#include "src/LU/PartialPivLU_MKL.h"
+#endif
#include "src/LU/Determinant.h"
#include "src/LU/Inverse.h"
@@ -34,8 +35,6 @@ namespace Eigen {
#include "src/Eigen2Support/LU.h"
#endif
-} // namespace Eigen
-
#include "src/Core/util/ReenableStupidWarnings.h"
#endif // EIGEN_LU_MODULE_H
diff --git a/extern/Eigen3/Eigen/LeastSquares b/extern/Eigen3/Eigen/LeastSquares
index 93a6302dcd9..35137c25db0 100644
--- a/extern/Eigen3/Eigen/LeastSquares
+++ b/extern/Eigen3/Eigen/LeastSquares
@@ -15,8 +15,6 @@
#include "Eigenvalues"
#include "Geometry"
-namespace Eigen {
-
/** \defgroup LeastSquares_Module LeastSquares module
* This module provides linear regression and related features.
*
@@ -27,8 +25,6 @@ namespace Eigen {
#include "src/Eigen2Support/LeastSquares.h"
-} // namespace Eigen
-
#include "src/Core/util/ReenableStupidWarnings.h"
#endif // EIGEN2_SUPPORT
diff --git a/extern/Eigen3/Eigen/OrderingMethods b/extern/Eigen3/Eigen/OrderingMethods
new file mode 100644
index 00000000000..1e2d87452e5
--- /dev/null
+++ b/extern/Eigen3/Eigen/OrderingMethods
@@ -0,0 +1,23 @@
+#ifndef EIGEN_ORDERINGMETHODS_MODULE_H
+#define EIGEN_ORDERINGMETHODS_MODULE_H
+
+#include "SparseCore"
+
+#include "src/Core/util/DisableStupidWarnings.h"
+
+/** \ingroup Sparse_modules
+ * \defgroup OrderingMethods_Module OrderingMethods module
+ *
+ * This module is currently for internal use only.
+ *
+ *
+ * \code
+ * #include <Eigen/OrderingMethods>
+ * \endcode
+ */
+
+#include "src/OrderingMethods/Amd.h"
+
+#include "src/Core/util/ReenableStupidWarnings.h"
+
+#endif // EIGEN_ORDERINGMETHODS_MODULE_H
diff --git a/extern/Eigen3/Eigen/PaStiXSupport b/extern/Eigen3/Eigen/PaStiXSupport
new file mode 100644
index 00000000000..7c616ee5eac
--- /dev/null
+++ b/extern/Eigen3/Eigen/PaStiXSupport
@@ -0,0 +1,46 @@
+#ifndef EIGEN_PASTIXSUPPORT_MODULE_H
+#define EIGEN_PASTIXSUPPORT_MODULE_H
+
+#include "SparseCore"
+
+#include "src/Core/util/DisableStupidWarnings.h"
+
+#include <complex.h>
+extern "C" {
+#include <pastix_nompi.h>
+#include <pastix.h>
+}
+
+#ifdef complex
+#undef complex
+#endif
+
+/** \ingroup Support_modules
+ * \defgroup PaStiXSupport_Module PaStiXSupport module
+ *
+ * This module provides an interface to the <a href="http://pastix.gforge.inria.fr/">PaSTiX</a> library.
+ * PaSTiX is a general \b supernodal, \b parallel and \b opensource sparse solver.
+ * It provides the two following main factorization classes:
+ * - class PastixLLT : a supernodal, parallel LLt Cholesky factorization.
+ * - class PastixLDLT: a supernodal, parallel LDLt Cholesky factorization.
+ * - class PastixLU : a supernodal, parallel LU factorization (optimized for a symmetric pattern).
+ *
+ * \code
+ * #include <Eigen/PaStiXSupport>
+ * \endcode
+ *
+ * In order to use this module, the PaSTiX headers must be accessible from the include paths, and your binary must be linked to the PaSTiX library and its dependencies.
+ * The dependencies depend on how PaSTiX has been compiled.
+ * For a cmake based project, you can use our FindPaSTiX.cmake module to help you in this task.
+ *
+ */
+
+#include "src/misc/Solve.h"
+#include "src/misc/SparseSolve.h"
+
+#include "src/PaStiXSupport/PaStiXSupport.h"
+
+
+#include "src/Core/util/ReenableStupidWarnings.h"
+
+#endif // EIGEN_PASTIXSUPPORT_MODULE_H
diff --git a/extern/Eigen3/Eigen/PardisoSupport b/extern/Eigen3/Eigen/PardisoSupport
new file mode 100644
index 00000000000..99330ce7a7d
--- /dev/null
+++ b/extern/Eigen3/Eigen/PardisoSupport
@@ -0,0 +1,30 @@
+#ifndef EIGEN_PARDISOSUPPORT_MODULE_H
+#define EIGEN_PARDISOSUPPORT_MODULE_H
+
+#include "SparseCore"
+
+#include "src/Core/util/DisableStupidWarnings.h"
+
+#include <mkl_pardiso.h>
+
+#include <unsupported/Eigen/SparseExtra>
+
+/** \ingroup Support_modules
+ * \defgroup PardisoSupport_Module PardisoSupport module
+ *
+ * This module brings support for the Intel(R) MKL PARDISO direct sparse solvers.
+ *
+ * \code
+ * #include <Eigen/PardisoSupport>
+ * \endcode
+ *
+ * In order to use this module, the MKL headers must be accessible from the include paths, and your binary must be linked to the MKL library and its dependencies.
+ * See this \ref TopicUsingIntelMKL "page" for more information on MKL-Eigen integration.
+ *
+ */
+
+#include "src/PardisoSupport/PardisoSupport.h"
+
+#include "src/Core/util/ReenableStupidWarnings.h"
+
+#endif // EIGEN_PARDISOSUPPORT_MODULE_H
diff --git a/extern/Eigen3/Eigen/QR b/extern/Eigen3/Eigen/QR
index 97c1788ee30..ac5b0269354 100644
--- a/extern/Eigen3/Eigen/QR
+++ b/extern/Eigen3/Eigen/QR
@@ -9,8 +9,6 @@
#include "Jacobi"
#include "Householder"
-namespace Eigen {
-
/** \defgroup QR_Module QR module
*
*
@@ -28,13 +26,15 @@ namespace Eigen {
#include "src/QR/HouseholderQR.h"
#include "src/QR/FullPivHouseholderQR.h"
#include "src/QR/ColPivHouseholderQR.h"
+#ifdef EIGEN_USE_LAPACKE
+#include "src/QR/HouseholderQR_MKL.h"
+#include "src/QR/ColPivHouseholderQR_MKL.h"
+#endif
#ifdef EIGEN2_SUPPORT
#include "src/Eigen2Support/QR.h"
#endif
-} // namespace Eigen
-
#include "src/Core/util/ReenableStupidWarnings.h"
#ifdef EIGEN2_SUPPORT
diff --git a/extern/Eigen3/Eigen/SVD b/extern/Eigen3/Eigen/SVD
index 7c987a9dd36..fd310017ad1 100644
--- a/extern/Eigen3/Eigen/SVD
+++ b/extern/Eigen3/Eigen/SVD
@@ -7,8 +7,6 @@
#include "src/Core/util/DisableStupidWarnings.h"
-namespace Eigen {
-
/** \defgroup SVD_Module SVD module
*
*
@@ -24,14 +22,15 @@ namespace Eigen {
#include "src/misc/Solve.h"
#include "src/SVD/JacobiSVD.h"
+#if defined(EIGEN_USE_LAPACKE) && !defined(EIGEN_USE_LAPACKE_STRICT)
+#include "src/SVD/JacobiSVD_MKL.h"
+#endif
#include "src/SVD/UpperBidiagonalization.h"
#ifdef EIGEN2_SUPPORT
#include "src/Eigen2Support/SVD.h"
#endif
-} // namespace Eigen
-
#include "src/Core/util/ReenableStupidWarnings.h"
#endif // EIGEN_SVD_MODULE_H
diff --git a/extern/Eigen3/Eigen/Sparse b/extern/Eigen3/Eigen/Sparse
index 7425b3a412a..2d1757172eb 100644
--- a/extern/Eigen3/Eigen/Sparse
+++ b/extern/Eigen3/Eigen/Sparse
@@ -1,69 +1,23 @@
#ifndef EIGEN_SPARSE_MODULE_H
#define EIGEN_SPARSE_MODULE_H
-#include "Core"
-
-#include "src/Core/util/DisableStupidWarnings.h"
-
-#include <vector>
-#include <map>
-#include <cstdlib>
-#include <cstring>
-#include <algorithm>
-
-#ifdef EIGEN2_SUPPORT
-#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
-#endif
-
-#ifndef EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
-#error The sparse module API is not stable yet. To use it anyway, please define the EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET preprocessor token.
-#endif
-
-namespace Eigen {
-
-/** \defgroup Sparse_Module Sparse module
+/** \defgroup Sparse_modules Sparse modules
*
- *
- *
- * See the \ref TutorialSparse "Sparse tutorial"
+ * Meta-module including all related modules:
+ * - SparseCore
+ * - OrderingMethods
+ * - SparseCholesky
+ * - IterativeLinearSolvers
*
* \code
* #include <Eigen/Sparse>
* \endcode
*/
-/** The type used to identify a general sparse storage. */
-struct Sparse {};
-
-#include "src/Sparse/SparseUtil.h"
-#include "src/Sparse/SparseMatrixBase.h"
-#include "src/Sparse/CompressedStorage.h"
-#include "src/Sparse/AmbiVector.h"
-#include "src/Sparse/SparseMatrix.h"
-#include "src/Sparse/DynamicSparseMatrix.h"
-#include "src/Sparse/MappedSparseMatrix.h"
-#include "src/Sparse/SparseVector.h"
-#include "src/Sparse/CoreIterators.h"
-#include "src/Sparse/SparseBlock.h"
-#include "src/Sparse/SparseTranspose.h"
-#include "src/Sparse/SparseCwiseUnaryOp.h"
-#include "src/Sparse/SparseCwiseBinaryOp.h"
-#include "src/Sparse/SparseDot.h"
-#include "src/Sparse/SparseAssign.h"
-#include "src/Sparse/SparseRedux.h"
-#include "src/Sparse/SparseFuzzy.h"
-#include "src/Sparse/SparseProduct.h"
-#include "src/Sparse/SparseSparseProduct.h"
-#include "src/Sparse/SparseDenseProduct.h"
-#include "src/Sparse/SparseDiagonalProduct.h"
-#include "src/Sparse/SparseTriangularView.h"
-#include "src/Sparse/SparseSelfAdjointView.h"
-#include "src/Sparse/TriangularSolver.h"
-#include "src/Sparse/SparseView.h"
-
-} // namespace Eigen
-
-#include "src/Core/util/ReenableStupidWarnings.h"
+#include "SparseCore"
+#include "OrderingMethods"
+#include "SparseCholesky"
+#include "IterativeLinearSolvers"
#endif // EIGEN_SPARSE_MODULE_H
diff --git a/extern/Eigen3/Eigen/SparseCholesky b/extern/Eigen3/Eigen/SparseCholesky
new file mode 100644
index 00000000000..5f82742f7d8
--- /dev/null
+++ b/extern/Eigen3/Eigen/SparseCholesky
@@ -0,0 +1,30 @@
+#ifndef EIGEN_SPARSECHOLESKY_MODULE_H
+#define EIGEN_SPARSECHOLESKY_MODULE_H
+
+#include "SparseCore"
+
+#include "src/Core/util/DisableStupidWarnings.h"
+
+/** \ingroup Sparse_modules
+ * \defgroup SparseCholesky_Module SparseCholesky module
+ *
+ * This module currently provides two variants of the direct sparse Cholesky decomposition for selfadjoint (hermitian) matrices.
+ * Those decompositions are accessible via the following classes:
+ * - SimplicialLLt,
+ * - SimplicialLDLt
+ *
+ * Such problems can also be solved using the ConjugateGradient solver from the IterativeLinearSolvers module.
+ *
+ * \code
+ * #include <Eigen/SparseCholesky>
+ * \endcode
+ */
+
+#include "src/misc/Solve.h"
+#include "src/misc/SparseSolve.h"
+
+#include "src/SparseCholesky/SimplicialCholesky.h"
+
+#include "src/Core/util/ReenableStupidWarnings.h"
+
+#endif // EIGEN_SPARSECHOLESKY_MODULE_H
diff --git a/extern/Eigen3/Eigen/SparseCore b/extern/Eigen3/Eigen/SparseCore
new file mode 100644
index 00000000000..41d28c92824
--- /dev/null
+++ b/extern/Eigen3/Eigen/SparseCore
@@ -0,0 +1,66 @@
+#ifndef EIGEN_SPARSECORE_MODULE_H
+#define EIGEN_SPARSECORE_MODULE_H
+
+#include "Core"
+
+#include "src/Core/util/DisableStupidWarnings.h"
+
+#include <vector>
+#include <map>
+#include <cstdlib>
+#include <cstring>
+#include <algorithm>
+
+/** \ingroup Sparse_modules
+ * \defgroup SparseCore_Module SparseCore module
+ *
+ * This module provides a sparse matrix representation, and basic associatd matrix manipulations
+ * and operations.
+ *
+ * See the \ref TutorialSparse "Sparse tutorial"
+ *
+ * \code
+ * #include <Eigen/SparseCore>
+ * \endcode
+ *
+ * This module depends on: Core.
+ */
+
+namespace Eigen {
+
+/** The type used to identify a general sparse storage. */
+struct Sparse {};
+
+}
+
+#include "src/SparseCore/SparseUtil.h"
+#include "src/SparseCore/SparseMatrixBase.h"
+#include "src/SparseCore/CompressedStorage.h"
+#include "src/SparseCore/AmbiVector.h"
+#include "src/SparseCore/SparseMatrix.h"
+#include "src/SparseCore/MappedSparseMatrix.h"
+#include "src/SparseCore/SparseVector.h"
+#include "src/SparseCore/CoreIterators.h"
+#include "src/SparseCore/SparseBlock.h"
+#include "src/SparseCore/SparseTranspose.h"
+#include "src/SparseCore/SparseCwiseUnaryOp.h"
+#include "src/SparseCore/SparseCwiseBinaryOp.h"
+#include "src/SparseCore/SparseDot.h"
+#include "src/SparseCore/SparsePermutation.h"
+#include "src/SparseCore/SparseAssign.h"
+#include "src/SparseCore/SparseRedux.h"
+#include "src/SparseCore/SparseFuzzy.h"
+#include "src/SparseCore/ConservativeSparseSparseProduct.h"
+#include "src/SparseCore/SparseSparseProductWithPruning.h"
+#include "src/SparseCore/SparseProduct.h"
+#include "src/SparseCore/SparseDenseProduct.h"
+#include "src/SparseCore/SparseDiagonalProduct.h"
+#include "src/SparseCore/SparseTriangularView.h"
+#include "src/SparseCore/SparseSelfAdjointView.h"
+#include "src/SparseCore/TriangularSolver.h"
+#include "src/SparseCore/SparseView.h"
+
+#include "src/Core/util/ReenableStupidWarnings.h"
+
+#endif // EIGEN_SPARSECORE_MODULE_H
+
diff --git a/extern/Eigen3/Eigen/StdDeque b/extern/Eigen3/Eigen/StdDeque
index a4f96232d8c..f27234778f4 100644
--- a/extern/Eigen3/Eigen/StdDeque
+++ b/extern/Eigen3/Eigen/StdDeque
@@ -4,24 +4,9 @@
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Hauke Heibel <hauke.heibel@googlemail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STDDEQUE_MODULE_H
#define EIGEN_STDDEQUE_MODULE_H
diff --git a/extern/Eigen3/Eigen/StdList b/extern/Eigen3/Eigen/StdList
index d914ded4f93..225c1e18f8e 100644
--- a/extern/Eigen3/Eigen/StdList
+++ b/extern/Eigen3/Eigen/StdList
@@ -3,24 +3,9 @@
//
// Copyright (C) 2009 Hauke Heibel <hauke.heibel@googlemail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STDLIST_MODULE_H
#define EIGEN_STDLIST_MODULE_H
diff --git a/extern/Eigen3/Eigen/StdVector b/extern/Eigen3/Eigen/StdVector
index 3d8995e5aae..6b22627f6f6 100644
--- a/extern/Eigen3/Eigen/StdVector
+++ b/extern/Eigen3/Eigen/StdVector
@@ -4,24 +4,9 @@
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Hauke Heibel <hauke.heibel@googlemail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STDVECTOR_MODULE_H
#define EIGEN_STDVECTOR_MODULE_H
diff --git a/extern/Eigen3/Eigen/SuperLUSupport b/extern/Eigen3/Eigen/SuperLUSupport
new file mode 100644
index 00000000000..575e14fbc29
--- /dev/null
+++ b/extern/Eigen3/Eigen/SuperLUSupport
@@ -0,0 +1,59 @@
+#ifndef EIGEN_SUPERLUSUPPORT_MODULE_H
+#define EIGEN_SUPERLUSUPPORT_MODULE_H
+
+#include "SparseCore"
+
+#include "src/Core/util/DisableStupidWarnings.h"
+
+#ifdef EMPTY
+#define EIGEN_EMPTY_WAS_ALREADY_DEFINED
+#endif
+
+typedef int int_t;
+#include <slu_Cnames.h>
+#include <supermatrix.h>
+#include <slu_util.h>
+
+// slu_util.h defines a preprocessor token named EMPTY which is really polluting,
+// so we remove it in favor of a SUPERLU_EMPTY token.
+// If EMPTY was already defined then we don't undef it.
+
+#if defined(EIGEN_EMPTY_WAS_ALREADY_DEFINED)
+# undef EIGEN_EMPTY_WAS_ALREADY_DEFINED
+#elif defined(EMPTY)
+# undef EMPTY
+#endif
+
+#define SUPERLU_EMPTY (-1)
+
+namespace Eigen { struct SluMatrix; }
+
+/** \ingroup Support_modules
+ * \defgroup SuperLUSupport_Module SuperLUSupport module
+ *
+ * This module provides an interface to the <a href="http://crd-legacy.lbl.gov/~xiaoye/SuperLU/">SuperLU</a> library.
+ * It provides the following factorization class:
+ * - class SuperLU: a supernodal sequential LU factorization.
+ * - class SuperILU: a supernodal sequential incomplete LU factorization (to be used as a preconditioner for iterative methods).
+ *
+ * \warning When including this module, you have to use SUPERLU_EMPTY instead of EMPTY which is no longer defined because it is too polluting.
+ *
+ * \code
+ * #include <Eigen/SuperLUSupport>
+ * \endcode
+ *
+ * In order to use this module, the superlu headers must be accessible from the include paths, and your binary must be linked to the superlu library and its dependencies.
+ * The dependencies depend on how superlu has been compiled.
+ * For a cmake based project, you can use our FindSuperLU.cmake module to help you in this task.
+ *
+ */
+
+#include "src/misc/Solve.h"
+#include "src/misc/SparseSolve.h"
+
+#include "src/SuperLUSupport/SuperLUSupport.h"
+
+
+#include "src/Core/util/ReenableStupidWarnings.h"
+
+#endif // EIGEN_SUPERLUSUPPORT_MODULE_H
diff --git a/extern/Eigen3/Eigen/UmfPackSupport b/extern/Eigen3/Eigen/UmfPackSupport
new file mode 100644
index 00000000000..984f64a8419
--- /dev/null
+++ b/extern/Eigen3/Eigen/UmfPackSupport
@@ -0,0 +1,36 @@
+#ifndef EIGEN_UMFPACKSUPPORT_MODULE_H
+#define EIGEN_UMFPACKSUPPORT_MODULE_H
+
+#include "SparseCore"
+
+#include "src/Core/util/DisableStupidWarnings.h"
+
+extern "C" {
+#include <umfpack.h>
+}
+
+/** \ingroup Support_modules
+ * \defgroup UmfPackSupport_Module UmfPackSupport module
+ *
+ * This module provides an interface to the UmfPack library which is part of the <a href="http://www.cise.ufl.edu/research/sparse/SuiteSparse/">suitesparse</a> package.
+ * It provides the following factorization class:
+ * - class UmfPackLU: a multifrontal sequential LU factorization.
+ *
+ * \code
+ * #include <Eigen/UmfPackSupport>
+ * \endcode
+ *
+ * In order to use this module, the umfpack headers must be accessible from the include paths, and your binary must be linked to the umfpack library and its dependencies.
+ * The dependencies depend on how umfpack has been compiled.
+ * For a cmake based project, you can use our FindUmfPack.cmake module to help you in this task.
+ *
+ */
+
+#include "src/misc/Solve.h"
+#include "src/misc/SparseSolve.h"
+
+#include "src/UmfPackSupport/UmfPackSupport.h"
+
+#include "src/Core/util/ReenableStupidWarnings.h"
+
+#endif // EIGEN_UMFPACKSUPPORT_MODULE_H
diff --git a/extern/Eigen3/Eigen/src/Cholesky/LDLT.h b/extern/Eigen3/Eigen/src/Cholesky/LDLT.h
index a19e947a4c6..68e54b1d4ad 100644
--- a/extern/Eigen3/Eigen/src/Cholesky/LDLT.h
+++ b/extern/Eigen3/Eigen/src/Cholesky/LDLT.h
@@ -1,43 +1,33 @@
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
-// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
+// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Keir Mierle <mierle@gmail.com>
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
+// Copyright (C) 2011 Timothy E. Holy <tim.holy@gmail.com >
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_LDLT_H
#define EIGEN_LDLT_H
+namespace Eigen {
+
namespace internal {
template<typename MatrixType, int UpLo> struct LDLT_Traits;
}
-/** \ingroup cholesky_Module
+/** \ingroup Cholesky_Module
*
* \class LDLT
*
* \brief Robust Cholesky decomposition of a matrix with pivoting
*
* \param MatrixType the type of the matrix of which to compute the LDL^T Cholesky decomposition
+ * \param UpLo the triangular part that will be used for the decompositon: Lower (default) or Upper.
+ * The other triangular part won't be read.
*
* Perform a robust Cholesky decomposition of a positive semidefinite or negative semidefinite
* matrix \f$ A \f$ such that \f$ A = P^TLDL^*P \f$, where P is a permutation matrix, L
@@ -48,14 +38,10 @@ template<typename MatrixType, int UpLo> struct LDLT_Traits;
* on D also stabilizes the computation.
*
* Remember that Cholesky decompositions are not rank-revealing. Also, do not use a Cholesky
- * decomposition to determine whether a system of equations has a solution.
+ * decomposition to determine whether a system of equations has a solution.
*
* \sa MatrixBase::ldlt(), class LLT
*/
- /* THIS PART OF THE DOX IS CURRENTLY DISABLED BECAUSE INACCURATE BECAUSE OF BUG IN THE DECOMPOSITION CODE
- * Note that during the decomposition, only the upper triangular part of A is considered. Therefore,
- * the strict lower part does not have to store correct values.
- */
template<typename _MatrixType, int _UpLo> class LDLT
{
public:
@@ -98,6 +84,11 @@ template<typename _MatrixType, int _UpLo> class LDLT
m_isInitialized(false)
{}
+ /** \brief Constructor with decomposition
+ *
+ * This calculates the decomposition for the input \a matrix.
+ * \sa LDLT(Index size)
+ */
LDLT(const MatrixType& matrix)
: m_matrix(matrix.rows(), matrix.cols()),
m_transpositions(matrix.rows()),
@@ -107,6 +98,14 @@ template<typename _MatrixType, int _UpLo> class LDLT
compute(matrix);
}
+ /** Clear any existing decomposition
+ * \sa rankUpdate(w,sigma)
+ */
+ void setZero()
+ {
+ m_isInitialized = false;
+ }
+
/** \returns a view of the upper triangular matrix U */
inline typename Traits::MatrixU matrixU() const
{
@@ -130,14 +129,14 @@ template<typename _MatrixType, int _UpLo> class LDLT
}
/** \returns the coefficients of the diagonal matrix D */
- inline Diagonal<const MatrixType> vectorD(void) const
+ inline Diagonal<const MatrixType> vectorD() const
{
eigen_assert(m_isInitialized && "LDLT is not initialized.");
return m_matrix.diagonal();
}
/** \returns true if the matrix is positive (semidefinite) */
- inline bool isPositive(void) const
+ inline bool isPositive() const
{
eigen_assert(m_isInitialized && "LDLT is not initialized.");
return m_sign == 1;
@@ -196,6 +195,9 @@ template<typename _MatrixType, int _UpLo> class LDLT
LDLT& compute(const MatrixType& matrix);
+ template <typename Derived>
+ LDLT& rankUpdate(const MatrixBase<Derived>& w,RealScalar alpha=1);
+
/** \returns the internal LDLT decomposition matrix
*
* TODO: document the storage layout
@@ -211,6 +213,17 @@ template<typename _MatrixType, int _UpLo> class LDLT
inline Index rows() const { return m_matrix.rows(); }
inline Index cols() const { return m_matrix.cols(); }
+ /** \brief Reports whether previous computation was successful.
+ *
+ * \returns \c Success if computation was succesful,
+ * \c NumericalIssue if the matrix.appears to be negative.
+ */
+ ComputationInfo info() const
+ {
+ eigen_assert(m_isInitialized && "LDLT is not initialized.");
+ return Success;
+ }
+
protected:
/** \internal
@@ -249,7 +262,7 @@ template<> struct ldlt_inplace<Lower>
return true;
}
- RealScalar cutoff = 0, biggest_in_corner;
+ RealScalar cutoff(0), biggest_in_corner;
for (Index k = 0; k < size; ++k)
{
@@ -317,6 +330,61 @@ template<> struct ldlt_inplace<Lower>
return true;
}
+
+ // Reference for the algorithm: Davis and Hager, "Multiple Rank
+ // Modifications of a Sparse Cholesky Factorization" (Algorithm 1)
+ // Trivial rearrangements of their computations (Timothy E. Holy)
+ // allow their algorithm to work for rank-1 updates even if the
+ // original matrix is not of full rank.
+ // Here only rank-1 updates are implemented, to reduce the
+ // requirement for intermediate storage and improve accuracy
+ template<typename MatrixType, typename WDerived>
+ static bool updateInPlace(MatrixType& mat, MatrixBase<WDerived>& w, typename MatrixType::RealScalar sigma=1)
+ {
+ using internal::isfinite;
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef typename MatrixType::Index Index;
+
+ const Index size = mat.rows();
+ eigen_assert(mat.cols() == size && w.size()==size);
+
+ RealScalar alpha = 1;
+
+ // Apply the update
+ for (Index j = 0; j < size; j++)
+ {
+ // Check for termination due to an original decomposition of low-rank
+ if (!(isfinite)(alpha))
+ break;
+
+ // Update the diagonal terms
+ RealScalar dj = real(mat.coeff(j,j));
+ Scalar wj = w.coeff(j);
+ RealScalar swj2 = sigma*abs2(wj);
+ RealScalar gamma = dj*alpha + swj2;
+
+ mat.coeffRef(j,j) += swj2/alpha;
+ alpha += swj2/dj;
+
+
+ // Update the terms of L
+ Index rs = size-j-1;
+ w.tail(rs) -= wj * mat.col(j).tail(rs);
+ if(gamma != 0)
+ mat.col(j).tail(rs) += (sigma*conj(wj)/gamma)*w.tail(rs);
+ }
+ return true;
+ }
+
+ template<typename MatrixType, typename TranspositionType, typename Workspace, typename WType>
+ static bool update(MatrixType& mat, const TranspositionType& transpositions, Workspace& tmp, const WType& w, typename MatrixType::RealScalar sigma=1)
+ {
+ // Apply the permutation to the input w
+ tmp = transpositions * w;
+
+ return ldlt_inplace<Lower>::updateInPlace(mat,tmp,sigma);
+ }
};
template<> struct ldlt_inplace<Upper>
@@ -327,22 +395,29 @@ template<> struct ldlt_inplace<Upper>
Transpose<MatrixType> matt(mat);
return ldlt_inplace<Lower>::unblocked(matt, transpositions, temp, sign);
}
+
+ template<typename MatrixType, typename TranspositionType, typename Workspace, typename WType>
+ static EIGEN_STRONG_INLINE bool update(MatrixType& mat, TranspositionType& transpositions, Workspace& tmp, WType& w, typename MatrixType::RealScalar sigma=1)
+ {
+ Transpose<MatrixType> matt(mat);
+ return ldlt_inplace<Lower>::update(matt, transpositions, tmp, w.conjugate(), sigma);
+ }
};
template<typename MatrixType> struct LDLT_Traits<MatrixType,Lower>
{
typedef const TriangularView<const MatrixType, UnitLower> MatrixL;
typedef const TriangularView<const typename MatrixType::AdjointReturnType, UnitUpper> MatrixU;
- inline static MatrixL getL(const MatrixType& m) { return m; }
- inline static MatrixU getU(const MatrixType& m) { return m.adjoint(); }
+ static inline MatrixL getL(const MatrixType& m) { return m; }
+ static inline MatrixU getU(const MatrixType& m) { return m.adjoint(); }
};
template<typename MatrixType> struct LDLT_Traits<MatrixType,Upper>
{
typedef const TriangularView<const typename MatrixType::AdjointReturnType, UnitLower> MatrixL;
typedef const TriangularView<const MatrixType, UnitUpper> MatrixU;
- inline static MatrixL getL(const MatrixType& m) { return m.adjoint(); }
- inline static MatrixU getU(const MatrixType& m) { return m; }
+ static inline MatrixL getL(const MatrixType& m) { return m.adjoint(); }
+ static inline MatrixU getU(const MatrixType& m) { return m; }
};
} // end namespace internal
@@ -367,6 +442,37 @@ LDLT<MatrixType,_UpLo>& LDLT<MatrixType,_UpLo>::compute(const MatrixType& a)
return *this;
}
+/** Update the LDLT decomposition: given A = L D L^T, efficiently compute the decomposition of A + sigma w w^T.
+ * \param w a vector to be incorporated into the decomposition.
+ * \param sigma a scalar, +1 for updates and -1 for "downdates," which correspond to removing previously-added column vectors. Optional; default value is +1.
+ * \sa setZero()
+ */
+template<typename MatrixType, int _UpLo>
+template<typename Derived>
+LDLT<MatrixType,_UpLo>& LDLT<MatrixType,_UpLo>::rankUpdate(const MatrixBase<Derived>& w,typename NumTraits<typename MatrixType::Scalar>::Real sigma)
+{
+ const Index size = w.rows();
+ if (m_isInitialized)
+ {
+ eigen_assert(m_matrix.rows()==size);
+ }
+ else
+ {
+ m_matrix.resize(size,size);
+ m_matrix.setZero();
+ m_transpositions.resize(size);
+ for (Index i = 0; i < size; i++)
+ m_transpositions.coeffRef(i) = i;
+ m_temporary.resize(size);
+ m_sign = sigma>=0 ? 1 : -1;
+ m_isInitialized = true;
+ }
+
+ internal::ldlt_inplace<UpLo>::update(m_matrix, m_transpositions, m_temporary, w, sigma);
+
+ return *this;
+}
+
namespace internal {
template<typename _MatrixType, int _UpLo, typename Rhs>
struct solve_retval<LDLT<_MatrixType,_UpLo>, Rhs>
@@ -481,4 +587,6 @@ MatrixBase<Derived>::ldlt() const
return LDLT<PlainObject>(derived());
}
+} // end namespace Eigen
+
#endif // EIGEN_LDLT_H
diff --git a/extern/Eigen3/Eigen/src/Cholesky/LLT.h b/extern/Eigen3/Eigen/src/Cholesky/LLT.h
index 3bb76b5787f..41d14e532f1 100644
--- a/extern/Eigen3/Eigen/src/Cholesky/LLT.h
+++ b/extern/Eigen3/Eigen/src/Cholesky/LLT.h
@@ -3,39 +3,28 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_LLT_H
#define EIGEN_LLT_H
+namespace Eigen {
+
namespace internal{
template<typename MatrixType, int UpLo> struct LLT_Traits;
}
-/** \ingroup cholesky_Module
+/** \ingroup Cholesky_Module
*
* \class LLT
*
* \brief Standard Cholesky decomposition (LL^T) of a matrix and associated features
*
* \param MatrixType the type of the matrix of which we are computing the LL^T Cholesky decomposition
+ * \param UpLo the triangular part that will be used for the decompositon: Lower (default) or Upper.
+ * The other triangular part won't be read.
*
* This class performs a LL^T Cholesky decomposition of a symmetric, positive definite
* matrix A such that A = LL^* = U^*U, where L is lower triangular.
@@ -49,6 +38,9 @@ template<typename MatrixType, int UpLo> struct LLT_Traits;
* use LDLT instead for the semidefinite case. Also, do not use a Cholesky decomposition to determine whether a system of equations
* has a solution.
*
+ * Example: \include LLT_example.cpp
+ * Output: \verbinclude LLT_example.out
+ *
* \sa MatrixBase::llt(), class LDLT
*/
/* HEY THIS DOX IS DISABLED BECAUSE THERE's A BUG EITHER HERE OR IN LDLT ABOUT THAT (OR BOTH)
@@ -178,6 +170,9 @@ template<typename _MatrixType, int _UpLo> class LLT
inline Index rows() const { return m_matrix.rows(); }
inline Index cols() const { return m_matrix.cols(); }
+ template<typename VectorType>
+ LLT rankUpdate(const VectorType& vec, const RealScalar& sigma = 1);
+
protected:
/** \internal
* Used to compute and store L
@@ -190,16 +185,85 @@ template<typename _MatrixType, int _UpLo> class LLT
namespace internal {
-template<int UpLo> struct llt_inplace;
+template<typename Scalar, int UpLo> struct llt_inplace;
+
+template<typename MatrixType, typename VectorType>
+static typename MatrixType::Index llt_rank_update_lower(MatrixType& mat, const VectorType& vec, const typename MatrixType::RealScalar& sigma)
+{
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef typename MatrixType::Index Index;
+ typedef typename MatrixType::ColXpr ColXpr;
+ typedef typename internal::remove_all<ColXpr>::type ColXprCleaned;
+ typedef typename ColXprCleaned::SegmentReturnType ColXprSegment;
+ typedef Matrix<Scalar,Dynamic,1> TempVectorType;
+ typedef typename TempVectorType::SegmentReturnType TempVecSegment;
+
+ int n = mat.cols();
+ eigen_assert(mat.rows()==n && vec.size()==n);
+
+ TempVectorType temp;
+
+ if(sigma>0)
+ {
+ // This version is based on Givens rotations.
+ // It is faster than the other one below, but only works for updates,
+ // i.e., for sigma > 0
+ temp = sqrt(sigma) * vec;
+
+ for(int i=0; i<n; ++i)
+ {
+ JacobiRotation<Scalar> g;
+ g.makeGivens(mat(i,i), -temp(i), &mat(i,i));
+
+ int rs = n-i-1;
+ if(rs>0)
+ {
+ ColXprSegment x(mat.col(i).tail(rs));
+ TempVecSegment y(temp.tail(rs));
+ apply_rotation_in_the_plane(x, y, g);
+ }
+ }
+ }
+ else
+ {
+ temp = vec;
+ RealScalar beta = 1;
+ for(int j=0; j<n; ++j)
+ {
+ RealScalar Ljj = real(mat.coeff(j,j));
+ RealScalar dj = abs2(Ljj);
+ Scalar wj = temp.coeff(j);
+ RealScalar swj2 = sigma*abs2(wj);
+ RealScalar gamma = dj*beta + swj2;
+
+ RealScalar x = dj + swj2/beta;
+ if (x<=RealScalar(0))
+ return j;
+ RealScalar nLjj = sqrt(x);
+ mat.coeffRef(j,j) = nLjj;
+ beta += swj2/dj;
+
+ // Update the terms of L
+ Index rs = n-j-1;
+ if(rs)
+ {
+ temp.tail(rs) -= (wj/Ljj) * mat.col(j).tail(rs);
+ if(gamma != 0)
+ mat.col(j).tail(rs) = (nLjj/Ljj) * mat.col(j).tail(rs) + (nLjj * sigma*conj(wj)/gamma)*temp.tail(rs);
+ }
+ }
+ }
+ return -1;
+}
-template<> struct llt_inplace<Lower>
+template<typename Scalar> struct llt_inplace<Scalar, Lower>
{
+ typedef typename NumTraits<Scalar>::Real RealScalar;
template<typename MatrixType>
static typename MatrixType::Index unblocked(MatrixType& mat)
{
typedef typename MatrixType::Index Index;
- typedef typename MatrixType::Scalar Scalar;
- typedef typename MatrixType::RealScalar RealScalar;
eigen_assert(mat.rows()==mat.cols());
const Index size = mat.rows();
@@ -254,21 +318,35 @@ template<> struct llt_inplace<Lower>
}
return -1;
}
-};
-template<> struct llt_inplace<Upper>
+ template<typename MatrixType, typename VectorType>
+ static typename MatrixType::Index rankUpdate(MatrixType& mat, const VectorType& vec, const RealScalar& sigma)
+ {
+ return Eigen::internal::llt_rank_update_lower(mat, vec, sigma);
+ }
+};
+
+template<typename Scalar> struct llt_inplace<Scalar, Upper>
{
+ typedef typename NumTraits<Scalar>::Real RealScalar;
+
template<typename MatrixType>
static EIGEN_STRONG_INLINE typename MatrixType::Index unblocked(MatrixType& mat)
{
Transpose<MatrixType> matt(mat);
- return llt_inplace<Lower>::unblocked(matt);
+ return llt_inplace<Scalar, Lower>::unblocked(matt);
}
template<typename MatrixType>
static EIGEN_STRONG_INLINE typename MatrixType::Index blocked(MatrixType& mat)
{
Transpose<MatrixType> matt(mat);
- return llt_inplace<Lower>::blocked(matt);
+ return llt_inplace<Scalar, Lower>::blocked(matt);
+ }
+ template<typename MatrixType, typename VectorType>
+ static typename MatrixType::Index rankUpdate(MatrixType& mat, const VectorType& vec, const RealScalar& sigma)
+ {
+ Transpose<MatrixType> matt(mat);
+ return llt_inplace<Scalar, Lower>::rankUpdate(matt, vec.conjugate(), sigma);
}
};
@@ -276,33 +354,35 @@ template<typename MatrixType> struct LLT_Traits<MatrixType,Lower>
{
typedef const TriangularView<const MatrixType, Lower> MatrixL;
typedef const TriangularView<const typename MatrixType::AdjointReturnType, Upper> MatrixU;
- inline static MatrixL getL(const MatrixType& m) { return m; }
- inline static MatrixU getU(const MatrixType& m) { return m.adjoint(); }
+ static inline MatrixL getL(const MatrixType& m) { return m; }
+ static inline MatrixU getU(const MatrixType& m) { return m.adjoint(); }
static bool inplace_decomposition(MatrixType& m)
- { return llt_inplace<Lower>::blocked(m)==-1; }
+ { return llt_inplace<typename MatrixType::Scalar, Lower>::blocked(m)==-1; }
};
template<typename MatrixType> struct LLT_Traits<MatrixType,Upper>
{
typedef const TriangularView<const typename MatrixType::AdjointReturnType, Lower> MatrixL;
typedef const TriangularView<const MatrixType, Upper> MatrixU;
- inline static MatrixL getL(const MatrixType& m) { return m.adjoint(); }
- inline static MatrixU getU(const MatrixType& m) { return m; }
+ static inline MatrixL getL(const MatrixType& m) { return m.adjoint(); }
+ static inline MatrixU getU(const MatrixType& m) { return m; }
static bool inplace_decomposition(MatrixType& m)
- { return llt_inplace<Upper>::blocked(m)==-1; }
+ { return llt_inplace<typename MatrixType::Scalar, Upper>::blocked(m)==-1; }
};
} // end namespace internal
/** Computes / recomputes the Cholesky decomposition A = LL^* = U^*U of \a matrix
*
- *
* \returns a reference to *this
+ *
+ * Example: \include TutorialLinAlgComputeTwice.cpp
+ * Output: \verbinclude TutorialLinAlgComputeTwice.out
*/
template<typename MatrixType, int _UpLo>
LLT<MatrixType,_UpLo>& LLT<MatrixType,_UpLo>::compute(const MatrixType& a)
{
- assert(a.rows()==a.cols());
+ eigen_assert(a.rows()==a.cols());
const Index size = a.rows();
m_matrix.resize(size, size);
m_matrix = a;
@@ -314,6 +394,26 @@ LLT<MatrixType,_UpLo>& LLT<MatrixType,_UpLo>::compute(const MatrixType& a)
return *this;
}
+/** Performs a rank one update (or dowdate) of the current decomposition.
+ * If A = LL^* before the rank one update,
+ * then after it we have LL^* = A + sigma * v v^* where \a v must be a vector
+ * of same dimension.
+ */
+template<typename _MatrixType, int _UpLo>
+template<typename VectorType>
+LLT<_MatrixType,_UpLo> LLT<_MatrixType,_UpLo>::rankUpdate(const VectorType& v, const RealScalar& sigma)
+{
+ EIGEN_STATIC_ASSERT_VECTOR_ONLY(VectorType);
+ eigen_assert(v.size()==m_matrix.cols());
+ eigen_assert(m_isInitialized);
+ if(internal::llt_inplace<typename MatrixType::Scalar, UpLo>::rankUpdate(m_matrix,v,sigma)>=0)
+ m_info = NumericalIssue;
+ else
+ m_info = Success;
+
+ return *this;
+}
+
namespace internal {
template<typename _MatrixType, int UpLo, typename Rhs>
struct solve_retval<LLT<_MatrixType, UpLo>, Rhs>
@@ -383,4 +483,6 @@ SelfAdjointView<MatrixType, UpLo>::llt() const
return LLT<PlainObject,UpLo>(m_matrix);
}
+} // end namespace Eigen
+
#endif // EIGEN_LLT_H
diff --git a/extern/Eigen3/Eigen/src/Cholesky/LLT_MKL.h b/extern/Eigen3/Eigen/src/Cholesky/LLT_MKL.h
new file mode 100644
index 00000000000..64daa445cf7
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Cholesky/LLT_MKL.h
@@ -0,0 +1,102 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * LLt decomposition based on LAPACKE_?potrf function.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_LLT_MKL_H
+#define EIGEN_LLT_MKL_H
+
+#include "Eigen/src/Core/util/MKL_support.h"
+#include <iostream>
+
+namespace Eigen {
+
+namespace internal {
+
+template<typename Scalar> struct mkl_llt;
+
+#define EIGEN_MKL_LLT(EIGTYPE, MKLTYPE, MKLPREFIX) \
+template<> struct mkl_llt<EIGTYPE> \
+{ \
+ template<typename MatrixType> \
+ static inline typename MatrixType::Index potrf(MatrixType& m, char uplo) \
+ { \
+ lapack_int matrix_order; \
+ lapack_int size, lda, info, StorageOrder; \
+ EIGTYPE* a; \
+ eigen_assert(m.rows()==m.cols()); \
+ /* Set up parameters for ?potrf */ \
+ size = m.rows(); \
+ StorageOrder = MatrixType::Flags&RowMajorBit?RowMajor:ColMajor; \
+ matrix_order = StorageOrder==RowMajor ? LAPACK_ROW_MAJOR : LAPACK_COL_MAJOR; \
+ a = &(m.coeffRef(0,0)); \
+ lda = m.outerStride(); \
+\
+ info = LAPACKE_##MKLPREFIX##potrf( matrix_order, uplo, size, (MKLTYPE*)a, lda ); \
+ info = (info==0) ? Success : NumericalIssue; \
+ return info; \
+ } \
+}; \
+template<> struct llt_inplace<EIGTYPE, Lower> \
+{ \
+ template<typename MatrixType> \
+ static typename MatrixType::Index blocked(MatrixType& m) \
+ { \
+ return mkl_llt<EIGTYPE>::potrf(m, 'L'); \
+ } \
+ template<typename MatrixType, typename VectorType> \
+ static typename MatrixType::Index rankUpdate(MatrixType& mat, const VectorType& vec, const typename MatrixType::RealScalar& sigma) \
+ { return Eigen::internal::llt_rank_update_lower(mat, vec, sigma); } \
+}; \
+template<> struct llt_inplace<EIGTYPE, Upper> \
+{ \
+ template<typename MatrixType> \
+ static typename MatrixType::Index blocked(MatrixType& m) \
+ { \
+ return mkl_llt<EIGTYPE>::potrf(m, 'U'); \
+ } \
+ template<typename MatrixType, typename VectorType> \
+ static typename MatrixType::Index rankUpdate(MatrixType& mat, const VectorType& vec, const typename MatrixType::RealScalar& sigma) \
+ { \
+ Transpose<MatrixType> matt(mat); \
+ return llt_inplace<EIGTYPE, Lower>::rankUpdate(matt, vec.conjugate(), sigma); \
+ } \
+};
+
+EIGEN_MKL_LLT(double, double, d)
+EIGEN_MKL_LLT(float, float, s)
+EIGEN_MKL_LLT(dcomplex, MKL_Complex16, z)
+EIGEN_MKL_LLT(scomplex, MKL_Complex8, c)
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_LLT_MKL_H
diff --git a/extern/Eigen3/Eigen/src/CholmodSupport/CholmodSupport.h b/extern/Eigen3/Eigen/src/CholmodSupport/CholmodSupport.h
new file mode 100644
index 00000000000..37f142150ff
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/CholmodSupport/CholmodSupport.h
@@ -0,0 +1,579 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_CHOLMODSUPPORT_H
+#define EIGEN_CHOLMODSUPPORT_H
+
+namespace Eigen {
+
+namespace internal {
+
+template<typename Scalar, typename CholmodType>
+void cholmod_configure_matrix(CholmodType& mat)
+{
+ if (internal::is_same<Scalar,float>::value)
+ {
+ mat.xtype = CHOLMOD_REAL;
+ mat.dtype = CHOLMOD_SINGLE;
+ }
+ else if (internal::is_same<Scalar,double>::value)
+ {
+ mat.xtype = CHOLMOD_REAL;
+ mat.dtype = CHOLMOD_DOUBLE;
+ }
+ else if (internal::is_same<Scalar,std::complex<float> >::value)
+ {
+ mat.xtype = CHOLMOD_COMPLEX;
+ mat.dtype = CHOLMOD_SINGLE;
+ }
+ else if (internal::is_same<Scalar,std::complex<double> >::value)
+ {
+ mat.xtype = CHOLMOD_COMPLEX;
+ mat.dtype = CHOLMOD_DOUBLE;
+ }
+ else
+ {
+ eigen_assert(false && "Scalar type not supported by CHOLMOD");
+ }
+}
+
+} // namespace internal
+
+/** Wraps the Eigen sparse matrix \a mat into a Cholmod sparse matrix object.
+ * Note that the data are shared.
+ */
+template<typename _Scalar, int _Options, typename _Index>
+cholmod_sparse viewAsCholmod(SparseMatrix<_Scalar,_Options,_Index>& mat)
+{
+ typedef SparseMatrix<_Scalar,_Options,_Index> MatrixType;
+ cholmod_sparse res;
+ res.nzmax = mat.nonZeros();
+ res.nrow = mat.rows();;
+ res.ncol = mat.cols();
+ res.p = mat.outerIndexPtr();
+ res.i = mat.innerIndexPtr();
+ res.x = mat.valuePtr();
+ res.sorted = 1;
+ if(mat.isCompressed())
+ {
+ res.packed = 1;
+ }
+ else
+ {
+ res.packed = 0;
+ res.nz = mat.innerNonZeroPtr();
+ }
+
+ res.dtype = 0;
+ res.stype = -1;
+
+ if (internal::is_same<_Index,int>::value)
+ {
+ res.itype = CHOLMOD_INT;
+ }
+ else
+ {
+ eigen_assert(false && "Index type different than int is not supported yet");
+ }
+
+ // setup res.xtype
+ internal::cholmod_configure_matrix<_Scalar>(res);
+
+ res.stype = 0;
+
+ return res;
+}
+
+template<typename _Scalar, int _Options, typename _Index>
+const cholmod_sparse viewAsCholmod(const SparseMatrix<_Scalar,_Options,_Index>& mat)
+{
+ cholmod_sparse res = viewAsCholmod(mat.const_cast_derived());
+ return res;
+}
+
+/** Returns a view of the Eigen sparse matrix \a mat as Cholmod sparse matrix.
+ * The data are not copied but shared. */
+template<typename _Scalar, int _Options, typename _Index, unsigned int UpLo>
+cholmod_sparse viewAsCholmod(const SparseSelfAdjointView<SparseMatrix<_Scalar,_Options,_Index>, UpLo>& mat)
+{
+ cholmod_sparse res = viewAsCholmod(mat.matrix().const_cast_derived());
+
+ if(UpLo==Upper) res.stype = 1;
+ if(UpLo==Lower) res.stype = -1;
+
+ return res;
+}
+
+/** Returns a view of the Eigen \b dense matrix \a mat as Cholmod dense matrix.
+ * The data are not copied but shared. */
+template<typename Derived>
+cholmod_dense viewAsCholmod(MatrixBase<Derived>& mat)
+{
+ EIGEN_STATIC_ASSERT((internal::traits<Derived>::Flags&RowMajorBit)==0,THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES);
+ typedef typename Derived::Scalar Scalar;
+
+ cholmod_dense res;
+ res.nrow = mat.rows();
+ res.ncol = mat.cols();
+ res.nzmax = res.nrow * res.ncol;
+ res.d = Derived::IsVectorAtCompileTime ? mat.derived().size() : mat.derived().outerStride();
+ res.x = mat.derived().data();
+ res.z = 0;
+
+ internal::cholmod_configure_matrix<Scalar>(res);
+
+ return res;
+}
+
+/** Returns a view of the Cholmod sparse matrix \a cm as an Eigen sparse matrix.
+ * The data are not copied but shared. */
+template<typename Scalar, int Flags, typename Index>
+MappedSparseMatrix<Scalar,Flags,Index> viewAsEigen(cholmod_sparse& cm)
+{
+ return MappedSparseMatrix<Scalar,Flags,Index>
+ (cm.nrow, cm.ncol, reinterpret_cast<Index*>(cm.p)[cm.ncol],
+ reinterpret_cast<Index*>(cm.p), reinterpret_cast<Index*>(cm.i),reinterpret_cast<Scalar*>(cm.x) );
+}
+
+enum CholmodMode {
+ CholmodAuto, CholmodSimplicialLLt, CholmodSupernodalLLt, CholmodLDLt
+};
+
+
+/** \ingroup CholmodSupport_Module
+ * \class CholmodBase
+ * \brief The base class for the direct Cholesky factorization of Cholmod
+ * \sa class CholmodSupernodalLLT, class CholmodSimplicialLDLT, class CholmodSimplicialLLT
+ */
+template<typename _MatrixType, int _UpLo, typename Derived>
+class CholmodBase : internal::noncopyable
+{
+ public:
+ typedef _MatrixType MatrixType;
+ enum { UpLo = _UpLo };
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef MatrixType CholMatrixType;
+ typedef typename MatrixType::Index Index;
+
+ public:
+
+ CholmodBase()
+ : m_cholmodFactor(0), m_info(Success), m_isInitialized(false)
+ {
+ cholmod_start(&m_cholmod);
+ }
+
+ CholmodBase(const MatrixType& matrix)
+ : m_cholmodFactor(0), m_info(Success), m_isInitialized(false)
+ {
+ cholmod_start(&m_cholmod);
+ compute(matrix);
+ }
+
+ ~CholmodBase()
+ {
+ if(m_cholmodFactor)
+ cholmod_free_factor(&m_cholmodFactor, &m_cholmod);
+ cholmod_finish(&m_cholmod);
+ }
+
+ inline Index cols() const { return m_cholmodFactor->n; }
+ inline Index rows() const { return m_cholmodFactor->n; }
+
+ Derived& derived() { return *static_cast<Derived*>(this); }
+ const Derived& derived() const { return *static_cast<const Derived*>(this); }
+
+ /** \brief Reports whether previous computation was successful.
+ *
+ * \returns \c Success if computation was succesful,
+ * \c NumericalIssue if the matrix.appears to be negative.
+ */
+ ComputationInfo info() const
+ {
+ eigen_assert(m_isInitialized && "Decomposition is not initialized.");
+ return m_info;
+ }
+
+ /** Computes the sparse Cholesky decomposition of \a matrix */
+ Derived& compute(const MatrixType& matrix)
+ {
+ analyzePattern(matrix);
+ factorize(matrix);
+ return derived();
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs>
+ inline const internal::solve_retval<CholmodBase, Rhs>
+ solve(const MatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "LLT is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "CholmodDecomposition::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::solve_retval<CholmodBase, Rhs>(*this, b.derived());
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs>
+ inline const internal::sparse_solve_retval<CholmodBase, Rhs>
+ solve(const SparseMatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "LLT is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "CholmodDecomposition::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::sparse_solve_retval<CholmodBase, Rhs>(*this, b.derived());
+ }
+
+ /** Performs a symbolic decomposition on the sparcity of \a matrix.
+ *
+ * This function is particularly useful when solving for several problems having the same structure.
+ *
+ * \sa factorize()
+ */
+ void analyzePattern(const MatrixType& matrix)
+ {
+ if(m_cholmodFactor)
+ {
+ cholmod_free_factor(&m_cholmodFactor, &m_cholmod);
+ m_cholmodFactor = 0;
+ }
+ cholmod_sparse A = viewAsCholmod(matrix.template selfadjointView<UpLo>());
+ m_cholmodFactor = cholmod_analyze(&A, &m_cholmod);
+
+ this->m_isInitialized = true;
+ this->m_info = Success;
+ m_analysisIsOk = true;
+ m_factorizationIsOk = false;
+ }
+
+ /** Performs a numeric decomposition of \a matrix
+ *
+ * The given matrix must has the same sparcity than the matrix on which the symbolic decomposition has been performed.
+ *
+ * \sa analyzePattern()
+ */
+ void factorize(const MatrixType& matrix)
+ {
+ eigen_assert(m_analysisIsOk && "You must first call analyzePattern()");
+ cholmod_sparse A = viewAsCholmod(matrix.template selfadjointView<UpLo>());
+ cholmod_factorize(&A, m_cholmodFactor, &m_cholmod);
+
+ this->m_info = Success;
+ m_factorizationIsOk = true;
+ }
+
+ /** Returns a reference to the Cholmod's configuration structure to get a full control over the performed operations.
+ * See the Cholmod user guide for details. */
+ cholmod_common& cholmod() { return m_cholmod; }
+
+ #ifndef EIGEN_PARSED_BY_DOXYGEN
+ /** \internal */
+ template<typename Rhs,typename Dest>
+ void _solve(const MatrixBase<Rhs> &b, MatrixBase<Dest> &dest) const
+ {
+ eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()");
+ const Index size = m_cholmodFactor->n;
+ eigen_assert(size==b.rows());
+
+ // note: cd stands for Cholmod Dense
+ cholmod_dense b_cd = viewAsCholmod(b.const_cast_derived());
+ cholmod_dense* x_cd = cholmod_solve(CHOLMOD_A, m_cholmodFactor, &b_cd, &m_cholmod);
+ if(!x_cd)
+ {
+ this->m_info = NumericalIssue;
+ }
+ // TODO optimize this copy by swapping when possible (be carreful with alignment, etc.)
+ dest = Matrix<Scalar,Dest::RowsAtCompileTime,Dest::ColsAtCompileTime>::Map(reinterpret_cast<Scalar*>(x_cd->x),b.rows(),b.cols());
+ cholmod_free_dense(&x_cd, &m_cholmod);
+ }
+
+ /** \internal */
+ template<typename RhsScalar, int RhsOptions, typename RhsIndex, typename DestScalar, int DestOptions, typename DestIndex>
+ void _solve(const SparseMatrix<RhsScalar,RhsOptions,RhsIndex> &b, SparseMatrix<DestScalar,DestOptions,DestIndex> &dest) const
+ {
+ eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()");
+ const Index size = m_cholmodFactor->n;
+ eigen_assert(size==b.rows());
+
+ // note: cs stands for Cholmod Sparse
+ cholmod_sparse b_cs = viewAsCholmod(b);
+ cholmod_sparse* x_cs = cholmod_spsolve(CHOLMOD_A, m_cholmodFactor, &b_cs, &m_cholmod);
+ if(!x_cs)
+ {
+ this->m_info = NumericalIssue;
+ }
+ // TODO optimize this copy by swapping when possible (be carreful with alignment, etc.)
+ dest = viewAsEigen<DestScalar,DestOptions,DestIndex>(*x_cs);
+ cholmod_free_sparse(&x_cs, &m_cholmod);
+ }
+ #endif // EIGEN_PARSED_BY_DOXYGEN
+
+ template<typename Stream>
+ void dumpMemory(Stream& s)
+ {}
+
+ protected:
+ mutable cholmod_common m_cholmod;
+ cholmod_factor* m_cholmodFactor;
+ mutable ComputationInfo m_info;
+ bool m_isInitialized;
+ int m_factorizationIsOk;
+ int m_analysisIsOk;
+};
+
+/** \ingroup CholmodSupport_Module
+ * \class CholmodSimplicialLLT
+ * \brief A simplicial direct Cholesky (LLT) factorization and solver based on Cholmod
+ *
+ * This class allows to solve for A.X = B sparse linear problems via a simplicial LL^T Cholesky factorization
+ * using the Cholmod library.
+ * This simplicial variant is equivalent to Eigen's built-in SimplicialLLT class. Thefore, it has little practical interest.
+ * The sparse matrix A must be selfajoint and positive definite. The vectors or matrices
+ * X and B can be either dense or sparse.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower
+ * or Upper. Default is Lower.
+ *
+ * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed.
+ *
+ * \sa \ref TutorialSparseDirectSolvers, class CholmodSupernodalLLT, class SimplicialLLT
+ */
+template<typename _MatrixType, int _UpLo = Lower>
+class CholmodSimplicialLLT : public CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLLT<_MatrixType, _UpLo> >
+{
+ typedef CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLLT> Base;
+ using Base::m_cholmod;
+
+ public:
+
+ typedef _MatrixType MatrixType;
+
+ CholmodSimplicialLLT() : Base() { init(); }
+
+ CholmodSimplicialLLT(const MatrixType& matrix) : Base()
+ {
+ init();
+ compute(matrix);
+ }
+
+ ~CholmodSimplicialLLT() {}
+ protected:
+ void init()
+ {
+ m_cholmod.final_asis = 0;
+ m_cholmod.supernodal = CHOLMOD_SIMPLICIAL;
+ m_cholmod.final_ll = 1;
+ }
+};
+
+
+/** \ingroup CholmodSupport_Module
+ * \class CholmodSimplicialLDLT
+ * \brief A simplicial direct Cholesky (LDLT) factorization and solver based on Cholmod
+ *
+ * This class allows to solve for A.X = B sparse linear problems via a simplicial LDL^T Cholesky factorization
+ * using the Cholmod library.
+ * This simplicial variant is equivalent to Eigen's built-in SimplicialLDLT class. Thefore, it has little practical interest.
+ * The sparse matrix A must be selfajoint and positive definite. The vectors or matrices
+ * X and B can be either dense or sparse.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower
+ * or Upper. Default is Lower.
+ *
+ * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed.
+ *
+ * \sa \ref TutorialSparseDirectSolvers, class CholmodSupernodalLLT, class SimplicialLDLT
+ */
+template<typename _MatrixType, int _UpLo = Lower>
+class CholmodSimplicialLDLT : public CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLDLT<_MatrixType, _UpLo> >
+{
+ typedef CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLDLT> Base;
+ using Base::m_cholmod;
+
+ public:
+
+ typedef _MatrixType MatrixType;
+
+ CholmodSimplicialLDLT() : Base() { init(); }
+
+ CholmodSimplicialLDLT(const MatrixType& matrix) : Base()
+ {
+ init();
+ compute(matrix);
+ }
+
+ ~CholmodSimplicialLDLT() {}
+ protected:
+ void init()
+ {
+ m_cholmod.final_asis = 1;
+ m_cholmod.supernodal = CHOLMOD_SIMPLICIAL;
+ }
+};
+
+/** \ingroup CholmodSupport_Module
+ * \class CholmodSupernodalLLT
+ * \brief A supernodal Cholesky (LLT) factorization and solver based on Cholmod
+ *
+ * This class allows to solve for A.X = B sparse linear problems via a supernodal LL^T Cholesky factorization
+ * using the Cholmod library.
+ * This supernodal variant performs best on dense enough problems, e.g., 3D FEM, or very high order 2D FEM.
+ * The sparse matrix A must be selfajoint and positive definite. The vectors or matrices
+ * X and B can be either dense or sparse.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower
+ * or Upper. Default is Lower.
+ *
+ * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed.
+ *
+ * \sa \ref TutorialSparseDirectSolvers
+ */
+template<typename _MatrixType, int _UpLo = Lower>
+class CholmodSupernodalLLT : public CholmodBase<_MatrixType, _UpLo, CholmodSupernodalLLT<_MatrixType, _UpLo> >
+{
+ typedef CholmodBase<_MatrixType, _UpLo, CholmodSupernodalLLT> Base;
+ using Base::m_cholmod;
+
+ public:
+
+ typedef _MatrixType MatrixType;
+
+ CholmodSupernodalLLT() : Base() { init(); }
+
+ CholmodSupernodalLLT(const MatrixType& matrix) : Base()
+ {
+ init();
+ compute(matrix);
+ }
+
+ ~CholmodSupernodalLLT() {}
+ protected:
+ void init()
+ {
+ m_cholmod.final_asis = 1;
+ m_cholmod.supernodal = CHOLMOD_SUPERNODAL;
+ }
+};
+
+/** \ingroup CholmodSupport_Module
+ * \class CholmodDecomposition
+ * \brief A general Cholesky factorization and solver based on Cholmod
+ *
+ * This class allows to solve for A.X = B sparse linear problems via a LL^T or LDL^T Cholesky factorization
+ * using the Cholmod library. The sparse matrix A must be selfajoint and positive definite. The vectors or matrices
+ * X and B can be either dense or sparse.
+ *
+ * This variant permits to change the underlying Cholesky method at runtime.
+ * On the other hand, it does not provide access to the result of the factorization.
+ * The default is to let Cholmod automatically choose between a simplicial and supernodal factorization.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower
+ * or Upper. Default is Lower.
+ *
+ * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed.
+ *
+ * \sa \ref TutorialSparseDirectSolvers
+ */
+template<typename _MatrixType, int _UpLo = Lower>
+class CholmodDecomposition : public CholmodBase<_MatrixType, _UpLo, CholmodDecomposition<_MatrixType, _UpLo> >
+{
+ typedef CholmodBase<_MatrixType, _UpLo, CholmodDecomposition> Base;
+ using Base::m_cholmod;
+
+ public:
+
+ typedef _MatrixType MatrixType;
+
+ CholmodDecomposition() : Base() { init(); }
+
+ CholmodDecomposition(const MatrixType& matrix) : Base()
+ {
+ init();
+ compute(matrix);
+ }
+
+ ~CholmodDecomposition() {}
+
+ void setMode(CholmodMode mode)
+ {
+ switch(mode)
+ {
+ case CholmodAuto:
+ m_cholmod.final_asis = 1;
+ m_cholmod.supernodal = CHOLMOD_AUTO;
+ break;
+ case CholmodSimplicialLLt:
+ m_cholmod.final_asis = 0;
+ m_cholmod.supernodal = CHOLMOD_SIMPLICIAL;
+ m_cholmod.final_ll = 1;
+ break;
+ case CholmodSupernodalLLt:
+ m_cholmod.final_asis = 1;
+ m_cholmod.supernodal = CHOLMOD_SUPERNODAL;
+ break;
+ case CholmodLDLt:
+ m_cholmod.final_asis = 1;
+ m_cholmod.supernodal = CHOLMOD_SIMPLICIAL;
+ break;
+ default:
+ break;
+ }
+ }
+ protected:
+ void init()
+ {
+ m_cholmod.final_asis = 1;
+ m_cholmod.supernodal = CHOLMOD_AUTO;
+ }
+};
+
+namespace internal {
+
+template<typename _MatrixType, int _UpLo, typename Derived, typename Rhs>
+struct solve_retval<CholmodBase<_MatrixType,_UpLo,Derived>, Rhs>
+ : solve_retval_base<CholmodBase<_MatrixType,_UpLo,Derived>, Rhs>
+{
+ typedef CholmodBase<_MatrixType,_UpLo,Derived> Dec;
+ EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec()._solve(rhs(),dst);
+ }
+};
+
+template<typename _MatrixType, int _UpLo, typename Derived, typename Rhs>
+struct sparse_solve_retval<CholmodBase<_MatrixType,_UpLo,Derived>, Rhs>
+ : sparse_solve_retval_base<CholmodBase<_MatrixType,_UpLo,Derived>, Rhs>
+{
+ typedef CholmodBase<_MatrixType,_UpLo,Derived> Dec;
+ EIGEN_MAKE_SPARSE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec()._solve(rhs(),dst);
+ }
+};
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_CHOLMODSUPPORT_H
diff --git a/extern/Eigen3/Eigen/src/Core/Array.h b/extern/Eigen3/Eigen/src/Core/Array.h
index a11fb1b53d5..aaa38997838 100644
--- a/extern/Eigen3/Eigen/src/Core/Array.h
+++ b/extern/Eigen3/Eigen/src/Core/Array.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ARRAY_H
#define EIGEN_ARRAY_H
+namespace Eigen {
+
/** \class Array
* \ingroup Core_Module
*
@@ -316,5 +303,6 @@ EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(d) \
EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(cf) \
EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(cd)
+} // end namespace Eigen
#endif // EIGEN_ARRAY_H
diff --git a/extern/Eigen3/Eigen/src/Core/ArrayBase.h b/extern/Eigen3/Eigen/src/Core/ArrayBase.h
index 9399ac3d15c..004b117c933 100644
--- a/extern/Eigen3/Eigen/src/Core/ArrayBase.h
+++ b/extern/Eigen3/Eigen/src/Core/ArrayBase.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ARRAYBASE_H
#define EIGEN_ARRAYBASE_H
+namespace Eigen {
+
template<typename ExpressionType> class MatrixWrapper;
/** \class ArrayBase
@@ -159,7 +146,7 @@ template<typename Derived> class ArrayBase
/** \returns an \link MatrixBase Matrix \endlink expression of this array
* \sa MatrixBase::array() */
MatrixWrapper<Derived> matrix() { return derived(); }
- const MatrixWrapper<Derived> matrix() const { return derived(); }
+ const MatrixWrapper<const Derived> matrix() const { return derived(); }
// template<typename Dest>
// inline void evalTo(Dest& dst) const { dst = matrix(); }
@@ -174,10 +161,10 @@ template<typename Derived> class ArrayBase
protected:
// mixing arrays and matrices is not legal
template<typename OtherDerived> Derived& operator+=(const MatrixBase<OtherDerived>& )
- {EIGEN_STATIC_ASSERT(sizeof(typename OtherDerived::Scalar)==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES);}
+ {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;}
// mixing arrays and matrices is not legal
template<typename OtherDerived> Derived& operator-=(const MatrixBase<OtherDerived>& )
- {EIGEN_STATIC_ASSERT(sizeof(typename OtherDerived::Scalar)==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES);}
+ {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;}
};
/** replaces \c *this by \c *this - \a other.
@@ -236,4 +223,6 @@ ArrayBase<Derived>::operator/=(const ArrayBase<OtherDerived>& other)
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_ARRAYBASE_H
diff --git a/extern/Eigen3/Eigen/src/Core/ArrayWrapper.h b/extern/Eigen3/Eigen/src/Core/ArrayWrapper.h
index 07f082e1edc..87af7fda937 100644
--- a/extern/Eigen3/Eigen/src/Core/ArrayWrapper.h
+++ b/extern/Eigen3/Eigen/src/Core/ArrayWrapper.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ARRAYWRAPPER_H
#define EIGEN_ARRAYWRAPPER_H
+namespace Eigen {
+
/** \class ArrayWrapper
* \ingroup Core_Module
*
@@ -61,7 +48,7 @@ class ArrayWrapper : public ArrayBase<ArrayWrapper<ExpressionType> >
typedef typename internal::nested<ExpressionType>::type NestedExpressionType;
- inline ArrayWrapper(const ExpressionType& matrix) : m_expression(matrix) {}
+ inline ArrayWrapper(ExpressionType& matrix) : m_expression(matrix) {}
inline Index rows() const { return m_expression.rows(); }
inline Index cols() const { return m_expression.cols(); }
@@ -71,7 +58,7 @@ class ArrayWrapper : public ArrayBase<ArrayWrapper<ExpressionType> >
inline ScalarWithConstIfNotLvalue* data() { return m_expression.data(); }
inline const Scalar* data() const { return m_expression.data(); }
- inline const CoeffReturnType coeff(Index row, Index col) const
+ inline CoeffReturnType coeff(Index row, Index col) const
{
return m_expression.coeff(row, col);
}
@@ -86,7 +73,7 @@ class ArrayWrapper : public ArrayBase<ArrayWrapper<ExpressionType> >
return m_expression.const_cast_derived().coeffRef(row, col);
}
- inline const CoeffReturnType coeff(Index index) const
+ inline CoeffReturnType coeff(Index index) const
{
return m_expression.coeff(index);
}
@@ -128,8 +115,14 @@ class ArrayWrapper : public ArrayBase<ArrayWrapper<ExpressionType> >
template<typename Dest>
inline void evalTo(Dest& dst) const { dst = m_expression; }
+ const typename internal::remove_all<NestedExpressionType>::type&
+ nestedExpression() const
+ {
+ return m_expression;
+ }
+
protected:
- const NestedExpressionType m_expression;
+ NestedExpressionType m_expression;
};
/** \class MatrixWrapper
@@ -168,7 +161,7 @@ class MatrixWrapper : public MatrixBase<MatrixWrapper<ExpressionType> >
typedef typename internal::nested<ExpressionType>::type NestedExpressionType;
- inline MatrixWrapper(const ExpressionType& matrix) : m_expression(matrix) {}
+ inline MatrixWrapper(ExpressionType& matrix) : m_expression(matrix) {}
inline Index rows() const { return m_expression.rows(); }
inline Index cols() const { return m_expression.cols(); }
@@ -178,7 +171,7 @@ class MatrixWrapper : public MatrixBase<MatrixWrapper<ExpressionType> >
inline ScalarWithConstIfNotLvalue* data() { return m_expression.data(); }
inline const Scalar* data() const { return m_expression.data(); }
- inline const CoeffReturnType coeff(Index row, Index col) const
+ inline CoeffReturnType coeff(Index row, Index col) const
{
return m_expression.coeff(row, col);
}
@@ -193,7 +186,7 @@ class MatrixWrapper : public MatrixBase<MatrixWrapper<ExpressionType> >
return m_expression.derived().coeffRef(row, col);
}
- inline const CoeffReturnType coeff(Index index) const
+ inline CoeffReturnType coeff(Index index) const
{
return m_expression.coeff(index);
}
@@ -232,8 +225,16 @@ class MatrixWrapper : public MatrixBase<MatrixWrapper<ExpressionType> >
m_expression.const_cast_derived().template writePacket<LoadMode>(index, x);
}
+ const typename internal::remove_all<NestedExpressionType>::type&
+ nestedExpression() const
+ {
+ return m_expression;
+ }
+
protected:
- const NestedExpressionType m_expression;
+ NestedExpressionType m_expression;
};
+} // end namespace Eigen
+
#endif // EIGEN_ARRAYWRAPPER_H
diff --git a/extern/Eigen3/Eigen/src/Core/Assign.h b/extern/Eigen3/Eigen/src/Core/Assign.h
index 3a17152f043..cd29a88f0da 100644
--- a/extern/Eigen3/Eigen/src/Core/Assign.h
+++ b/extern/Eigen3/Eigen/src/Core/Assign.h
@@ -5,28 +5,15 @@
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ASSIGN_H
#define EIGEN_ASSIGN_H
+namespace Eigen {
+
namespace internal {
/***************************************************************************
@@ -152,7 +139,7 @@ struct assign_DefaultTraversal_CompleteUnrolling
inner = Index % Derived1::InnerSizeAtCompileTime
};
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src)
{
dst.copyCoeffByOuterInner(outer, inner, src);
assign_DefaultTraversal_CompleteUnrolling<Derived1, Derived2, Index+1, Stop>::run(dst, src);
@@ -162,13 +149,13 @@ struct assign_DefaultTraversal_CompleteUnrolling
template<typename Derived1, typename Derived2, int Stop>
struct assign_DefaultTraversal_CompleteUnrolling<Derived1, Derived2, Stop, Stop>
{
- EIGEN_STRONG_INLINE static void run(Derived1 &, const Derived2 &) {}
+ static EIGEN_STRONG_INLINE void run(Derived1 &, const Derived2 &) {}
};
template<typename Derived1, typename Derived2, int Index, int Stop>
struct assign_DefaultTraversal_InnerUnrolling
{
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src, int outer)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src, int outer)
{
dst.copyCoeffByOuterInner(outer, Index, src);
assign_DefaultTraversal_InnerUnrolling<Derived1, Derived2, Index+1, Stop>::run(dst, src, outer);
@@ -178,7 +165,7 @@ struct assign_DefaultTraversal_InnerUnrolling
template<typename Derived1, typename Derived2, int Stop>
struct assign_DefaultTraversal_InnerUnrolling<Derived1, Derived2, Stop, Stop>
{
- EIGEN_STRONG_INLINE static void run(Derived1 &, const Derived2 &, int) {}
+ static EIGEN_STRONG_INLINE void run(Derived1 &, const Derived2 &, int) {}
};
/***********************
@@ -188,7 +175,7 @@ struct assign_DefaultTraversal_InnerUnrolling<Derived1, Derived2, Stop, Stop>
template<typename Derived1, typename Derived2, int Index, int Stop>
struct assign_LinearTraversal_CompleteUnrolling
{
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src)
{
dst.copyCoeff(Index, src);
assign_LinearTraversal_CompleteUnrolling<Derived1, Derived2, Index+1, Stop>::run(dst, src);
@@ -198,7 +185,7 @@ struct assign_LinearTraversal_CompleteUnrolling
template<typename Derived1, typename Derived2, int Stop>
struct assign_LinearTraversal_CompleteUnrolling<Derived1, Derived2, Stop, Stop>
{
- EIGEN_STRONG_INLINE static void run(Derived1 &, const Derived2 &) {}
+ static EIGEN_STRONG_INLINE void run(Derived1 &, const Derived2 &) {}
};
/**************************
@@ -214,7 +201,7 @@ struct assign_innervec_CompleteUnrolling
JointAlignment = assign_traits<Derived1,Derived2>::JointAlignment
};
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src)
{
dst.template copyPacketByOuterInner<Derived2, Aligned, JointAlignment>(outer, inner, src);
assign_innervec_CompleteUnrolling<Derived1, Derived2,
@@ -225,13 +212,13 @@ struct assign_innervec_CompleteUnrolling
template<typename Derived1, typename Derived2, int Stop>
struct assign_innervec_CompleteUnrolling<Derived1, Derived2, Stop, Stop>
{
- EIGEN_STRONG_INLINE static void run(Derived1 &, const Derived2 &) {}
+ static EIGEN_STRONG_INLINE void run(Derived1 &, const Derived2 &) {}
};
template<typename Derived1, typename Derived2, int Index, int Stop>
struct assign_innervec_InnerUnrolling
{
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src, int outer)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src, int outer)
{
dst.template copyPacketByOuterInner<Derived2, Aligned, Aligned>(outer, Index, src);
assign_innervec_InnerUnrolling<Derived1, Derived2,
@@ -242,7 +229,7 @@ struct assign_innervec_InnerUnrolling
template<typename Derived1, typename Derived2, int Stop>
struct assign_innervec_InnerUnrolling<Derived1, Derived2, Stop, Stop>
{
- EIGEN_STRONG_INLINE static void run(Derived1 &, const Derived2 &, int) {}
+ static EIGEN_STRONG_INLINE void run(Derived1 &, const Derived2 &, int) {}
};
/***************************************************************************
@@ -251,24 +238,25 @@ struct assign_innervec_InnerUnrolling<Derived1, Derived2, Stop, Stop>
template<typename Derived1, typename Derived2,
int Traversal = assign_traits<Derived1, Derived2>::Traversal,
- int Unrolling = assign_traits<Derived1, Derived2>::Unrolling>
+ int Unrolling = assign_traits<Derived1, Derived2>::Unrolling,
+ int Version = Specialized>
struct assign_impl;
/************************
*** Default traversal ***
************************/
-template<typename Derived1, typename Derived2, int Unrolling>
-struct assign_impl<Derived1, Derived2, InvalidTraversal, Unrolling>
+template<typename Derived1, typename Derived2, int Unrolling, int Version>
+struct assign_impl<Derived1, Derived2, InvalidTraversal, Unrolling, Version>
{
- inline static void run(Derived1 &, const Derived2 &) { }
+ static inline void run(Derived1 &, const Derived2 &) { }
};
-template<typename Derived1, typename Derived2>
-struct assign_impl<Derived1, Derived2, DefaultTraversal, NoUnrolling>
+template<typename Derived1, typename Derived2, int Version>
+struct assign_impl<Derived1, Derived2, DefaultTraversal, NoUnrolling, Version>
{
typedef typename Derived1::Index Index;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
const Index innerSize = dst.innerSize();
const Index outerSize = dst.outerSize();
@@ -278,21 +266,21 @@ struct assign_impl<Derived1, Derived2, DefaultTraversal, NoUnrolling>
}
};
-template<typename Derived1, typename Derived2>
-struct assign_impl<Derived1, Derived2, DefaultTraversal, CompleteUnrolling>
+template<typename Derived1, typename Derived2, int Version>
+struct assign_impl<Derived1, Derived2, DefaultTraversal, CompleteUnrolling, Version>
{
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src)
{
assign_DefaultTraversal_CompleteUnrolling<Derived1, Derived2, 0, Derived1::SizeAtCompileTime>
::run(dst, src);
}
};
-template<typename Derived1, typename Derived2>
-struct assign_impl<Derived1, Derived2, DefaultTraversal, InnerUnrolling>
+template<typename Derived1, typename Derived2, int Version>
+struct assign_impl<Derived1, Derived2, DefaultTraversal, InnerUnrolling, Version>
{
typedef typename Derived1::Index Index;
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src)
{
const Index outerSize = dst.outerSize();
for(Index outer = 0; outer < outerSize; ++outer)
@@ -305,11 +293,11 @@ struct assign_impl<Derived1, Derived2, DefaultTraversal, InnerUnrolling>
*** Linear traversal ***
***********************/
-template<typename Derived1, typename Derived2>
-struct assign_impl<Derived1, Derived2, LinearTraversal, NoUnrolling>
+template<typename Derived1, typename Derived2, int Version>
+struct assign_impl<Derived1, Derived2, LinearTraversal, NoUnrolling, Version>
{
typedef typename Derived1::Index Index;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
const Index size = dst.size();
for(Index i = 0; i < size; ++i)
@@ -317,10 +305,10 @@ struct assign_impl<Derived1, Derived2, LinearTraversal, NoUnrolling>
}
};
-template<typename Derived1, typename Derived2>
-struct assign_impl<Derived1, Derived2, LinearTraversal, CompleteUnrolling>
+template<typename Derived1, typename Derived2, int Version>
+struct assign_impl<Derived1, Derived2, LinearTraversal, CompleteUnrolling, Version>
{
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src)
{
assign_LinearTraversal_CompleteUnrolling<Derived1, Derived2, 0, Derived1::SizeAtCompileTime>
::run(dst, src);
@@ -331,11 +319,11 @@ struct assign_impl<Derived1, Derived2, LinearTraversal, CompleteUnrolling>
*** Inner vectorization ***
**************************/
-template<typename Derived1, typename Derived2>
-struct assign_impl<Derived1, Derived2, InnerVectorizedTraversal, NoUnrolling>
+template<typename Derived1, typename Derived2, int Version>
+struct assign_impl<Derived1, Derived2, InnerVectorizedTraversal, NoUnrolling, Version>
{
typedef typename Derived1::Index Index;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
const Index innerSize = dst.innerSize();
const Index outerSize = dst.outerSize();
@@ -346,21 +334,21 @@ struct assign_impl<Derived1, Derived2, InnerVectorizedTraversal, NoUnrolling>
}
};
-template<typename Derived1, typename Derived2>
-struct assign_impl<Derived1, Derived2, InnerVectorizedTraversal, CompleteUnrolling>
+template<typename Derived1, typename Derived2, int Version>
+struct assign_impl<Derived1, Derived2, InnerVectorizedTraversal, CompleteUnrolling, Version>
{
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src)
{
assign_innervec_CompleteUnrolling<Derived1, Derived2, 0, Derived1::SizeAtCompileTime>
::run(dst, src);
}
};
-template<typename Derived1, typename Derived2>
-struct assign_impl<Derived1, Derived2, InnerVectorizedTraversal, InnerUnrolling>
+template<typename Derived1, typename Derived2, int Version>
+struct assign_impl<Derived1, Derived2, InnerVectorizedTraversal, InnerUnrolling, Version>
{
typedef typename Derived1::Index Index;
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src)
{
const Index outerSize = dst.outerSize();
for(Index outer = 0; outer < outerSize; ++outer)
@@ -398,11 +386,11 @@ struct unaligned_assign_impl<false>
}
};
-template<typename Derived1, typename Derived2>
-struct assign_impl<Derived1, Derived2, LinearVectorizedTraversal, NoUnrolling>
+template<typename Derived1, typename Derived2, int Version>
+struct assign_impl<Derived1, Derived2, LinearVectorizedTraversal, NoUnrolling, Version>
{
typedef typename Derived1::Index Index;
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src)
{
const Index size = dst.size();
typedef packet_traits<typename Derived1::Scalar> PacketTraits;
@@ -412,7 +400,7 @@ struct assign_impl<Derived1, Derived2, LinearVectorizedTraversal, NoUnrolling>
srcAlignment = assign_traits<Derived1,Derived2>::JointAlignment
};
const Index alignedStart = assign_traits<Derived1,Derived2>::DstIsAligned ? 0
- : first_aligned(&dst.coeffRef(0), size);
+ : internal::first_aligned(&dst.coeffRef(0), size);
const Index alignedEnd = alignedStart + ((size-alignedStart)/packetSize)*packetSize;
unaligned_assign_impl<assign_traits<Derived1,Derived2>::DstIsAligned!=0>::run(src,dst,0,alignedStart);
@@ -426,11 +414,11 @@ struct assign_impl<Derived1, Derived2, LinearVectorizedTraversal, NoUnrolling>
}
};
-template<typename Derived1, typename Derived2>
-struct assign_impl<Derived1, Derived2, LinearVectorizedTraversal, CompleteUnrolling>
+template<typename Derived1, typename Derived2, int Version>
+struct assign_impl<Derived1, Derived2, LinearVectorizedTraversal, CompleteUnrolling, Version>
{
typedef typename Derived1::Index Index;
- EIGEN_STRONG_INLINE static void run(Derived1 &dst, const Derived2 &src)
+ static EIGEN_STRONG_INLINE void run(Derived1 &dst, const Derived2 &src)
{
enum { size = Derived1::SizeAtCompileTime,
packetSize = packet_traits<typename Derived1::Scalar>::size,
@@ -445,11 +433,11 @@ struct assign_impl<Derived1, Derived2, LinearVectorizedTraversal, CompleteUnroll
*** Slice vectorization ***
***************************/
-template<typename Derived1, typename Derived2>
-struct assign_impl<Derived1, Derived2, SliceVectorizedTraversal, NoUnrolling>
+template<typename Derived1, typename Derived2, int Version>
+struct assign_impl<Derived1, Derived2, SliceVectorizedTraversal, NoUnrolling, Version>
{
typedef typename Derived1::Index Index;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
typedef packet_traits<typename Derived1::Scalar> PacketTraits;
enum {
@@ -463,7 +451,7 @@ struct assign_impl<Derived1, Derived2, SliceVectorizedTraversal, NoUnrolling>
const Index outerSize = dst.outerSize();
const Index alignedStep = alignable ? (packetSize - dst.outerStride() % packetSize) & packetAlignedMask : 0;
Index alignedStart = ((!alignable) || assign_traits<Derived1,Derived2>::DstIsAligned) ? 0
- : first_aligned(&dst.coeffRef(0,0), innerSize);
+ : internal::first_aligned(&dst.coeffRef(0,0), innerSize);
for(Index outer = 0; outer < outerSize; ++outer)
{
@@ -531,19 +519,19 @@ struct assign_selector;
template<typename Derived, typename OtherDerived>
struct assign_selector<Derived,OtherDerived,false,false> {
- EIGEN_STRONG_INLINE static Derived& run(Derived& dst, const OtherDerived& other) { return dst.lazyAssign(other.derived()); }
+ static EIGEN_STRONG_INLINE Derived& run(Derived& dst, const OtherDerived& other) { return dst.lazyAssign(other.derived()); }
};
template<typename Derived, typename OtherDerived>
struct assign_selector<Derived,OtherDerived,true,false> {
- EIGEN_STRONG_INLINE static Derived& run(Derived& dst, const OtherDerived& other) { return dst.lazyAssign(other.eval()); }
+ static EIGEN_STRONG_INLINE Derived& run(Derived& dst, const OtherDerived& other) { return dst.lazyAssign(other.eval()); }
};
template<typename Derived, typename OtherDerived>
struct assign_selector<Derived,OtherDerived,false,true> {
- EIGEN_STRONG_INLINE static Derived& run(Derived& dst, const OtherDerived& other) { return dst.lazyAssign(other.transpose()); }
+ static EIGEN_STRONG_INLINE Derived& run(Derived& dst, const OtherDerived& other) { return dst.lazyAssign(other.transpose()); }
};
template<typename Derived, typename OtherDerived>
struct assign_selector<Derived,OtherDerived,true,true> {
- EIGEN_STRONG_INLINE static Derived& run(Derived& dst, const OtherDerived& other) { return dst.lazyAssign(other.transpose().eval()); }
+ static EIGEN_STRONG_INLINE Derived& run(Derived& dst, const OtherDerived& other) { return dst.lazyAssign(other.transpose().eval()); }
};
} // end namespace internal
@@ -590,4 +578,6 @@ EIGEN_STRONG_INLINE Derived& MatrixBase<Derived>::operator=(const ReturnByValue<
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_ASSIGN_H
diff --git a/extern/Eigen3/Eigen/src/Core/Assign_MKL.h b/extern/Eigen3/Eigen/src/Core/Assign_MKL.h
new file mode 100644
index 00000000000..428c6367b92
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/Assign_MKL.h
@@ -0,0 +1,224 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * MKL VML support for coefficient-wise unary Eigen expressions like a=b.sin()
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_ASSIGN_VML_H
+#define EIGEN_ASSIGN_VML_H
+
+namespace Eigen {
+
+namespace internal {
+
+template<typename Op> struct vml_call
+{ enum { IsSupported = 0 }; };
+
+template<typename Dst, typename Src, typename UnaryOp>
+class vml_assign_traits
+{
+ private:
+ enum {
+ DstHasDirectAccess = Dst::Flags & DirectAccessBit,
+ SrcHasDirectAccess = Src::Flags & DirectAccessBit,
+
+ StorageOrdersAgree = (int(Dst::IsRowMajor) == int(Src::IsRowMajor)),
+ InnerSize = int(Dst::IsVectorAtCompileTime) ? int(Dst::SizeAtCompileTime)
+ : int(Dst::Flags)&RowMajorBit ? int(Dst::ColsAtCompileTime)
+ : int(Dst::RowsAtCompileTime),
+ InnerMaxSize = int(Dst::IsVectorAtCompileTime) ? int(Dst::MaxSizeAtCompileTime)
+ : int(Dst::Flags)&RowMajorBit ? int(Dst::MaxColsAtCompileTime)
+ : int(Dst::MaxRowsAtCompileTime),
+ MaxSizeAtCompileTime = Dst::SizeAtCompileTime,
+
+ MightEnableVml = vml_call<UnaryOp>::IsSupported && StorageOrdersAgree && DstHasDirectAccess && SrcHasDirectAccess
+ && Src::InnerStrideAtCompileTime==1 && Dst::InnerStrideAtCompileTime==1,
+ MightLinearize = MightEnableVml && (int(Dst::Flags) & int(Src::Flags) & LinearAccessBit),
+ VmlSize = MightLinearize ? MaxSizeAtCompileTime : InnerMaxSize,
+ LargeEnough = VmlSize==Dynamic || VmlSize>=EIGEN_MKL_VML_THRESHOLD,
+ MayEnableVml = MightEnableVml && LargeEnough,
+ MayLinearize = MayEnableVml && MightLinearize
+ };
+ public:
+ enum {
+ Traversal = MayLinearize ? LinearVectorizedTraversal
+ : MayEnableVml ? InnerVectorizedTraversal
+ : DefaultTraversal
+ };
+};
+
+template<typename Derived1, typename Derived2, typename UnaryOp, int Traversal, int Unrolling,
+ int VmlTraversal = vml_assign_traits<Derived1, Derived2, UnaryOp>::Traversal >
+struct vml_assign_impl
+ : assign_impl<Derived1, Eigen::CwiseUnaryOp<UnaryOp, Derived2>,Traversal,Unrolling,BuiltIn>
+{
+};
+
+template<typename Derived1, typename Derived2, typename UnaryOp, int Traversal, int Unrolling>
+struct vml_assign_impl<Derived1, Derived2, UnaryOp, Traversal, Unrolling, InnerVectorizedTraversal>
+{
+ typedef typename Derived1::Scalar Scalar;
+ typedef typename Derived1::Index Index;
+ static inline void run(Derived1& dst, const CwiseUnaryOp<UnaryOp, Derived2>& src)
+ {
+ // in case we want to (or have to) skip VML at runtime we can call:
+ // assign_impl<Derived1,Eigen::CwiseUnaryOp<UnaryOp, Derived2>,Traversal,Unrolling,BuiltIn>::run(dst,src);
+ const Index innerSize = dst.innerSize();
+ const Index outerSize = dst.outerSize();
+ for(Index outer = 0; outer < outerSize; ++outer) {
+ const Scalar *src_ptr = src.IsRowMajor ? &(src.nestedExpression().coeffRef(outer,0)) :
+ &(src.nestedExpression().coeffRef(0, outer));
+ Scalar *dst_ptr = dst.IsRowMajor ? &(dst.coeffRef(outer,0)) : &(dst.coeffRef(0, outer));
+ vml_call<UnaryOp>::run(src.functor(), innerSize, src_ptr, dst_ptr );
+ }
+ }
+};
+
+template<typename Derived1, typename Derived2, typename UnaryOp, int Traversal, int Unrolling>
+struct vml_assign_impl<Derived1, Derived2, UnaryOp, Traversal, Unrolling, LinearVectorizedTraversal>
+{
+ static inline void run(Derived1& dst, const CwiseUnaryOp<UnaryOp, Derived2>& src)
+ {
+ // in case we want to (or have to) skip VML at runtime we can call:
+ // assign_impl<Derived1,Eigen::CwiseUnaryOp<UnaryOp, Derived2>,Traversal,Unrolling,BuiltIn>::run(dst,src);
+ vml_call<UnaryOp>::run(src.functor(), dst.size(), src.nestedExpression().data(), dst.data() );
+ }
+};
+
+// Macroses
+
+#define EIGEN_MKL_VML_SPECIALIZE_ASSIGN(TRAVERSAL,UNROLLING) \
+ template<typename Derived1, typename Derived2, typename UnaryOp> \
+ struct assign_impl<Derived1, Eigen::CwiseUnaryOp<UnaryOp, Derived2>, TRAVERSAL, UNROLLING, Specialized> { \
+ static inline void run(Derived1 &dst, const Eigen::CwiseUnaryOp<UnaryOp, Derived2> &src) { \
+ vml_assign_impl<Derived1,Derived2,UnaryOp,TRAVERSAL,UNROLLING>::run(dst, src); \
+ } \
+ };
+
+EIGEN_MKL_VML_SPECIALIZE_ASSIGN(DefaultTraversal,NoUnrolling)
+EIGEN_MKL_VML_SPECIALIZE_ASSIGN(DefaultTraversal,CompleteUnrolling)
+EIGEN_MKL_VML_SPECIALIZE_ASSIGN(DefaultTraversal,InnerUnrolling)
+EIGEN_MKL_VML_SPECIALIZE_ASSIGN(LinearTraversal,NoUnrolling)
+EIGEN_MKL_VML_SPECIALIZE_ASSIGN(LinearTraversal,CompleteUnrolling)
+EIGEN_MKL_VML_SPECIALIZE_ASSIGN(InnerVectorizedTraversal,NoUnrolling)
+EIGEN_MKL_VML_SPECIALIZE_ASSIGN(InnerVectorizedTraversal,CompleteUnrolling)
+EIGEN_MKL_VML_SPECIALIZE_ASSIGN(InnerVectorizedTraversal,InnerUnrolling)
+EIGEN_MKL_VML_SPECIALIZE_ASSIGN(LinearVectorizedTraversal,CompleteUnrolling)
+EIGEN_MKL_VML_SPECIALIZE_ASSIGN(LinearVectorizedTraversal,NoUnrolling)
+EIGEN_MKL_VML_SPECIALIZE_ASSIGN(SliceVectorizedTraversal,NoUnrolling)
+
+
+#if !defined (EIGEN_FAST_MATH) || (EIGEN_FAST_MATH != 1)
+#define EIGEN_MKL_VML_MODE VML_HA
+#else
+#define EIGEN_MKL_VML_MODE VML_LA
+#endif
+
+#define EIGEN_MKL_VML_DECLARE_UNARY_CALL(EIGENOP, VMLOP, EIGENTYPE, VMLTYPE) \
+ template<> struct vml_call< scalar_##EIGENOP##_op<EIGENTYPE> > { \
+ enum { IsSupported = 1 }; \
+ static inline void run( const scalar_##EIGENOP##_op<EIGENTYPE>& /*func*/, \
+ int size, const EIGENTYPE* src, EIGENTYPE* dst) { \
+ VMLOP(size, (const VMLTYPE*)src, (VMLTYPE*)dst); \
+ } \
+ };
+
+#define EIGEN_MKL_VML_DECLARE_UNARY_CALL_LA(EIGENOP, VMLOP, EIGENTYPE, VMLTYPE) \
+ template<> struct vml_call< scalar_##EIGENOP##_op<EIGENTYPE> > { \
+ enum { IsSupported = 1 }; \
+ static inline void run( const scalar_##EIGENOP##_op<EIGENTYPE>& /*func*/, \
+ int size, const EIGENTYPE* src, EIGENTYPE* dst) { \
+ MKL_INT64 vmlMode = EIGEN_MKL_VML_MODE; \
+ VMLOP(size, (const VMLTYPE*)src, (VMLTYPE*)dst, vmlMode); \
+ } \
+ };
+
+#define EIGEN_MKL_VML_DECLARE_POW_CALL(EIGENOP, VMLOP, EIGENTYPE, VMLTYPE) \
+ template<> struct vml_call< scalar_##EIGENOP##_op<EIGENTYPE> > { \
+ enum { IsSupported = 1 }; \
+ static inline void run( const scalar_##EIGENOP##_op<EIGENTYPE>& func, \
+ int size, const EIGENTYPE* src, EIGENTYPE* dst) { \
+ EIGENTYPE exponent = func.m_exponent; \
+ MKL_INT64 vmlMode = EIGEN_MKL_VML_MODE; \
+ VMLOP(&size, (const VMLTYPE*)src, (const VMLTYPE*)&exponent, \
+ (VMLTYPE*)dst, &vmlMode); \
+ } \
+ };
+
+#define EIGEN_MKL_VML_DECLARE_UNARY_CALLS_REAL(EIGENOP, VMLOP) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALL(EIGENOP, vs##VMLOP, float, float) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALL(EIGENOP, vd##VMLOP, double, double)
+
+#define EIGEN_MKL_VML_DECLARE_UNARY_CALLS_COMPLEX(EIGENOP, VMLOP) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALL(EIGENOP, vc##VMLOP, scomplex, MKL_Complex8) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALL(EIGENOP, vz##VMLOP, dcomplex, MKL_Complex16)
+
+#define EIGEN_MKL_VML_DECLARE_UNARY_CALLS(EIGENOP, VMLOP) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALLS_REAL(EIGENOP, VMLOP) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALLS_COMPLEX(EIGENOP, VMLOP)
+
+
+#define EIGEN_MKL_VML_DECLARE_UNARY_CALLS_REAL_LA(EIGENOP, VMLOP) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALL_LA(EIGENOP, vms##VMLOP, float, float) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALL_LA(EIGENOP, vmd##VMLOP, double, double)
+
+#define EIGEN_MKL_VML_DECLARE_UNARY_CALLS_COMPLEX_LA(EIGENOP, VMLOP) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALL_LA(EIGENOP, vmc##VMLOP, scomplex, MKL_Complex8) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALL_LA(EIGENOP, vmz##VMLOP, dcomplex, MKL_Complex16)
+
+#define EIGEN_MKL_VML_DECLARE_UNARY_CALLS_LA(EIGENOP, VMLOP) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALLS_REAL_LA(EIGENOP, VMLOP) \
+ EIGEN_MKL_VML_DECLARE_UNARY_CALLS_COMPLEX_LA(EIGENOP, VMLOP)
+
+
+EIGEN_MKL_VML_DECLARE_UNARY_CALLS_LA(sin, Sin)
+EIGEN_MKL_VML_DECLARE_UNARY_CALLS_LA(asin, Asin)
+EIGEN_MKL_VML_DECLARE_UNARY_CALLS_LA(cos, Cos)
+EIGEN_MKL_VML_DECLARE_UNARY_CALLS_LA(acos, Acos)
+EIGEN_MKL_VML_DECLARE_UNARY_CALLS_LA(tan, Tan)
+//EIGEN_MKL_VML_DECLARE_UNARY_CALLS(abs, Abs)
+EIGEN_MKL_VML_DECLARE_UNARY_CALLS_LA(exp, Exp)
+EIGEN_MKL_VML_DECLARE_UNARY_CALLS_LA(log, Ln)
+EIGEN_MKL_VML_DECLARE_UNARY_CALLS_LA(sqrt, Sqrt)
+
+EIGEN_MKL_VML_DECLARE_UNARY_CALLS_REAL(square, Sqr)
+
+// The vm*powx functions are not avaibale in the windows version of MKL.
+#ifdef _WIN32
+EIGEN_MKL_VML_DECLARE_POW_CALL(pow, vmspowx_, float, float)
+EIGEN_MKL_VML_DECLARE_POW_CALL(pow, vmdpowx_, double, double)
+EIGEN_MKL_VML_DECLARE_POW_CALL(pow, vmcpowx_, scomplex, MKL_Complex8)
+EIGEN_MKL_VML_DECLARE_POW_CALL(pow, vmzpowx_, dcomplex, MKL_Complex16)
+#endif
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_ASSIGN_VML_H
diff --git a/extern/Eigen3/Eigen/src/Core/BandMatrix.h b/extern/Eigen3/Eigen/src/Core/BandMatrix.h
index 2570d7b559f..ffd7fe8b301 100644
--- a/extern/Eigen3/Eigen/src/Core/BandMatrix.h
+++ b/extern/Eigen3/Eigen/src/Core/BandMatrix.h
@@ -3,30 +3,16 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BANDMATRIX_H
#define EIGEN_BANDMATRIX_H
-namespace internal {
+namespace Eigen {
+namespace internal {
template<typename Derived>
class BandMatrixBase : public EigenBase<Derived>
@@ -343,4 +329,6 @@ class TridiagonalMatrix : public BandMatrix<Scalar,Size,Size,Options&SelfAdjoint
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_BANDMATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Core/Block.h b/extern/Eigen3/Eigen/src/Core/Block.h
index d470bc13400..5f29cb3d1b3 100644
--- a/extern/Eigen3/Eigen/src/Core/Block.h
+++ b/extern/Eigen3/Eigen/src/Core/Block.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BLOCK_H
#define EIGEN_BLOCK_H
+namespace Eigen {
+
/** \class Block
* \ingroup Core_Module
*
@@ -242,6 +229,21 @@ template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel, bool H
inline Index outerStride() const;
#endif
+ const typename internal::remove_all<typename XprType::Nested>::type& nestedExpression() const
+ {
+ return m_xpr;
+ }
+
+ Index startRow() const
+ {
+ return m_startRow.value();
+ }
+
+ Index startCol() const
+ {
+ return m_startCol.value();
+ }
+
protected:
const typename XprType::Nested m_xpr;
@@ -304,6 +306,11 @@ class Block<XprType,BlockRows,BlockCols, InnerPanel,true>
init();
}
+ const typename internal::remove_all<typename XprType::Nested>::type& nestedExpression() const
+ {
+ return m_xpr;
+ }
+
/** \sa MapBase::innerStride() */
inline Index innerStride() const
{
@@ -341,9 +348,10 @@ class Block<XprType,BlockRows,BlockCols, InnerPanel,true>
: m_xpr.innerStride();
}
- const typename XprType::Nested m_xpr;
+ typename XprType::Nested m_xpr;
Index m_outerStride;
};
+} // end namespace Eigen
#endif // EIGEN_BLOCK_H
diff --git a/extern/Eigen3/Eigen/src/Core/BooleanRedux.h b/extern/Eigen3/Eigen/src/Core/BooleanRedux.h
index 5c3444a57c9..57efd8e6953 100644
--- a/extern/Eigen3/Eigen/src/Core/BooleanRedux.h
+++ b/extern/Eigen3/Eigen/src/Core/BooleanRedux.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ALLANDANY_H
#define EIGEN_ALLANDANY_H
+namespace Eigen {
+
namespace internal {
template<typename Derived, int UnrollCount>
@@ -35,7 +22,7 @@ struct all_unroller
row = (UnrollCount-1) % Derived::RowsAtCompileTime
};
- inline static bool run(const Derived &mat)
+ static inline bool run(const Derived &mat)
{
return all_unroller<Derived, UnrollCount-1>::run(mat) && mat.coeff(row, col);
}
@@ -44,13 +31,13 @@ struct all_unroller
template<typename Derived>
struct all_unroller<Derived, 1>
{
- inline static bool run(const Derived &mat) { return mat.coeff(0, 0); }
+ static inline bool run(const Derived &mat) { return mat.coeff(0, 0); }
};
template<typename Derived>
struct all_unroller<Derived, Dynamic>
{
- inline static bool run(const Derived &) { return false; }
+ static inline bool run(const Derived &) { return false; }
};
template<typename Derived, int UnrollCount>
@@ -61,7 +48,7 @@ struct any_unroller
row = (UnrollCount-1) % Derived::RowsAtCompileTime
};
- inline static bool run(const Derived &mat)
+ static inline bool run(const Derived &mat)
{
return any_unroller<Derived, UnrollCount-1>::run(mat) || mat.coeff(row, col);
}
@@ -70,13 +57,13 @@ struct any_unroller
template<typename Derived>
struct any_unroller<Derived, 1>
{
- inline static bool run(const Derived &mat) { return mat.coeff(0, 0); }
+ static inline bool run(const Derived &mat) { return mat.coeff(0, 0); }
};
template<typename Derived>
struct any_unroller<Derived, Dynamic>
{
- inline static bool run(const Derived &) { return false; }
+ static inline bool run(const Derived &) { return false; }
};
} // end namespace internal
@@ -146,4 +133,6 @@ inline typename DenseBase<Derived>::Index DenseBase<Derived>::count() const
return derived().template cast<bool>().template cast<Index>().sum();
}
+} // end namespace Eigen
+
#endif // EIGEN_ALLANDANY_H
diff --git a/extern/Eigen3/Eigen/src/Core/CommaInitializer.h b/extern/Eigen3/Eigen/src/Core/CommaInitializer.h
index 92422bf2fa0..4adce64143c 100644
--- a/extern/Eigen3/Eigen/src/Core/CommaInitializer.h
+++ b/extern/Eigen3/Eigen/src/Core/CommaInitializer.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COMMAINITIALIZER_H
#define EIGEN_COMMAINITIALIZER_H
+namespace Eigen {
+
/** \class CommaInitializer
* \ingroup Core_Module
*
@@ -147,4 +134,6 @@ DenseBase<Derived>::operator<<(const DenseBase<OtherDerived>& other)
return CommaInitializer<Derived>(*static_cast<Derived *>(this), other);
}
+} // end namespace Eigen
+
#endif // EIGEN_COMMAINITIALIZER_H
diff --git a/extern/Eigen3/Eigen/src/Core/CwiseBinaryOp.h b/extern/Eigen3/Eigen/src/Core/CwiseBinaryOp.h
index 7386b2e1843..1b93af31b60 100644
--- a/extern/Eigen3/Eigen/src/Core/CwiseBinaryOp.h
+++ b/extern/Eigen3/Eigen/src/Core/CwiseBinaryOp.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_CWISE_BINARY_OP_H
#define EIGEN_CWISE_BINARY_OP_H
+namespace Eigen {
+
/** \class CwiseBinaryOp
* \ingroup Core_Module
*
@@ -167,8 +154,8 @@ class CwiseBinaryOp : internal::no_assignment_operator,
const BinaryOp& functor() const { return m_functor; }
protected:
- const LhsNested m_lhs;
- const RhsNested m_rhs;
+ LhsNested m_lhs;
+ RhsNested m_rhs;
const BinaryOp m_functor;
};
@@ -237,4 +224,6 @@ MatrixBase<Derived>::operator+=(const MatrixBase<OtherDerived>& other)
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_CWISE_BINARY_OP_H
diff --git a/extern/Eigen3/Eigen/src/Core/CwiseNullaryOp.h b/extern/Eigen3/Eigen/src/Core/CwiseNullaryOp.h
index c616e7ae13d..2635a62b07b 100644
--- a/extern/Eigen3/Eigen/src/Core/CwiseNullaryOp.h
+++ b/extern/Eigen3/Eigen/src/Core/CwiseNullaryOp.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_CWISE_NULLARY_OP_H
#define EIGEN_CWISE_NULLARY_OP_H
+namespace Eigen {
+
/** \class CwiseNullaryOp
* \ingroup Core_Module
*
@@ -101,6 +88,9 @@ class CwiseNullaryOp : internal::no_assignment_operator,
return m_functor.packetOp(index);
}
+ /** \returns the functor representing the nullary operation */
+ const NullaryOp& functor() const { return m_functor; }
+
protected:
const internal::variable_if_dynamic<Index, RowsAtCompileTime> m_rows;
const internal::variable_if_dynamic<Index, ColsAtCompileTime> m_cols;
@@ -238,6 +228,8 @@ DenseBase<Derived>::Constant(const Scalar& value)
* assumed to be a(0), a(1), ..., a(size). This assumption allows for better vectorization
* and yields faster code than the random access version.
*
+ * When size is set to 1, a vector of length 1 containing 'high' is returned.
+ *
* \only_for_vectors
*
* Example: \include DenseBase_LinSpaced_seq.cpp
@@ -270,6 +262,7 @@ DenseBase<Derived>::LinSpaced(Sequential_t, const Scalar& low, const Scalar& hig
* \brief Sets a linearly space vector.
*
* The function generates 'size' equally spaced values in the closed interval [low,high].
+ * When size is set to 1, a vector of length 1 containing 'high' is returned.
*
* \only_for_vectors
*
@@ -381,6 +374,7 @@ PlainObjectBase<Derived>::setConstant(Index rows, Index cols, const Scalar& valu
* \brief Sets a linearly space vector.
*
* The function generates 'size' equally spaced values in the closed interval [low,high].
+ * When size is set to 1, a vector of length 1 containing 'high' is returned.
*
* \only_for_vectors
*
@@ -396,6 +390,23 @@ EIGEN_STRONG_INLINE Derived& DenseBase<Derived>::setLinSpaced(Index size, const
return derived() = Derived::NullaryExpr(size, internal::linspaced_op<Scalar,false>(low,high,size));
}
+/**
+ * \brief Sets a linearly space vector.
+ *
+ * The function fill *this with equally spaced values in the closed interval [low,high].
+ * When size is set to 1, a vector of length 1 containing 'high' is returned.
+ *
+ * \only_for_vectors
+ *
+ * \sa setLinSpaced(Index, const Scalar&, const Scalar&), CwiseNullaryOp
+ */
+template<typename Derived>
+EIGEN_STRONG_INLINE Derived& DenseBase<Derived>::setLinSpaced(const Scalar& low, const Scalar& high)
+{
+ EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived)
+ return setLinSpaced(size(), low, high);
+}
+
// zero:
/** \returns an expression of a zero matrix.
@@ -848,4 +859,6 @@ template<typename Derived>
EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::BasisReturnType MatrixBase<Derived>::UnitW()
{ return Derived::Unit(3); }
+} // end namespace Eigen
+
#endif // EIGEN_CWISE_NULLARY_OP_H
diff --git a/extern/Eigen3/Eigen/src/Core/CwiseUnaryOp.h b/extern/Eigen3/Eigen/src/Core/CwiseUnaryOp.h
index 958571d64bf..063355ae521 100644
--- a/extern/Eigen3/Eigen/src/Core/CwiseUnaryOp.h
+++ b/extern/Eigen3/Eigen/src/Core/CwiseUnaryOp.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_CWISE_UNARY_OP_H
#define EIGEN_CWISE_UNARY_OP_H
+namespace Eigen {
+
/** \class CwiseUnaryOp
* \ingroup Core_Module
*
@@ -95,7 +82,7 @@ class CwiseUnaryOp : internal::no_assignment_operator,
nestedExpression() { return m_xpr.const_cast_derived(); }
protected:
- const typename XprType::Nested m_xpr;
+ typename XprType::Nested m_xpr;
const UnaryOp m_functor;
};
@@ -134,4 +121,6 @@ class CwiseUnaryOpImpl<UnaryOp,XprType,Dense>
}
};
+} // end namespace Eigen
+
#endif // EIGEN_CWISE_UNARY_OP_H
diff --git a/extern/Eigen3/Eigen/src/Core/CwiseUnaryView.h b/extern/Eigen3/Eigen/src/Core/CwiseUnaryView.h
index d24ef037314..66f73a9505b 100644
--- a/extern/Eigen3/Eigen/src/Core/CwiseUnaryView.h
+++ b/extern/Eigen3/Eigen/src/Core/CwiseUnaryView.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_CWISE_UNARY_VIEW_H
#define EIGEN_CWISE_UNARY_VIEW_H
+namespace Eigen {
+
/** \class CwiseUnaryView
* \ingroup Core_Module
*
@@ -97,7 +84,7 @@ class CwiseUnaryView : internal::no_assignment_operator,
protected:
// FIXME changed from MatrixType::Nested because of a weird compilation error with sun CC
- const typename internal::nested<MatrixType>::type m_matrix;
+ typename internal::nested<MatrixType>::type m_matrix;
ViewOp m_functor;
};
@@ -143,6 +130,6 @@ class CwiseUnaryViewImpl<ViewOp,MatrixType,Dense>
}
};
-
+} // end namespace Eigen
#endif // EIGEN_CWISE_UNARY_VIEW_H
diff --git a/extern/Eigen3/Eigen/src/Core/DenseBase.h b/extern/Eigen3/Eigen/src/Core/DenseBase.h
index 920904f243a..1cc0314ef0b 100644
--- a/extern/Eigen3/Eigen/src/Core/DenseBase.h
+++ b/extern/Eigen3/Eigen/src/Core/DenseBase.h
@@ -4,28 +4,15 @@
// Copyright (C) 2007-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DENSEBASE_H
#define EIGEN_DENSEBASE_H
+namespace Eigen {
+
/** \class DenseBase
* \ingroup Core_Module
*
@@ -376,12 +363,13 @@ template<typename Derived> class DenseBase
inline Derived& operator*=(const Scalar& other);
inline Derived& operator/=(const Scalar& other);
+ typedef typename internal::add_const_on_value_type<typename internal::eval<Derived>::type>::type EvalReturnType;
/** \returns the matrix or vector obtained by evaluating this expression.
*
* Notice that in the case of a plain matrix or vector (not an expression) this function just returns
* a const reference, in order to avoid a useless copy.
*/
- EIGEN_STRONG_INLINE const typename internal::eval<Derived>::type eval() const
+ EIGEN_STRONG_INLINE EvalReturnType eval() const
{
// Even though MSVC does not honor strong inlining when the return type
// is a dynamic matrix, we desperately need strong inlining for fixed
@@ -540,4 +528,6 @@ template<typename Derived> class DenseBase
template<typename OtherDerived> explicit DenseBase(const DenseBase<OtherDerived>&);
};
+} // end namespace Eigen
+
#endif // EIGEN_DENSEBASE_H
diff --git a/extern/Eigen3/Eigen/src/Core/DenseCoeffsBase.h b/extern/Eigen3/Eigen/src/Core/DenseCoeffsBase.h
index e45238fb584..72704c2d79f 100644
--- a/extern/Eigen3/Eigen/src/Core/DenseCoeffsBase.h
+++ b/extern/Eigen3/Eigen/src/Core/DenseCoeffsBase.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DENSECOEFFSBASE_H
#define EIGEN_DENSECOEFFSBASE_H
+namespace Eigen {
+
namespace internal {
template<typename T> struct add_const_on_value_type_if_arithmetic
{
@@ -710,16 +697,16 @@ namespace internal {
template<typename Derived, bool JustReturnZero>
struct first_aligned_impl
{
- inline static typename Derived::Index run(const Derived&)
+ static inline typename Derived::Index run(const Derived&)
{ return 0; }
};
template<typename Derived>
struct first_aligned_impl<Derived, false>
{
- inline static typename Derived::Index run(const Derived& m)
+ static inline typename Derived::Index run(const Derived& m)
{
- return first_aligned(&m.const_cast_derived().coeffRef(0,0), m.size());
+ return internal::first_aligned(&m.const_cast_derived().coeffRef(0,0), m.size());
}
};
@@ -729,7 +716,7 @@ struct first_aligned_impl<Derived, false>
* documentation.
*/
template<typename Derived>
-inline static typename Derived::Index first_aligned(const Derived& m)
+static inline typename Derived::Index first_aligned(const Derived& m)
{
return first_aligned_impl
<Derived, (Derived::Flags & AlignedBit) || !(Derived::Flags & DirectAccessBit)>
@@ -762,4 +749,6 @@ struct outer_stride_at_compile_time<Derived, false>
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_DENSECOEFFSBASE_H
diff --git a/extern/Eigen3/Eigen/src/Core/DenseStorage.h b/extern/Eigen3/Eigen/src/Core/DenseStorage.h
index 813053b00dd..1fc2daf2c40 100644
--- a/extern/Eigen3/Eigen/src/Core/DenseStorage.h
+++ b/extern/Eigen3/Eigen/src/Core/DenseStorage.h
@@ -5,24 +5,9 @@
// Copyright (C) 2006-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2010 Hauke Heibel <hauke.heibel@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MATRIXSTORAGE_H
#define EIGEN_MATRIXSTORAGE_H
@@ -33,6 +18,8 @@
#define EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN
#endif
+namespace Eigen {
+
namespace internal {
struct constructor_without_unaligned_array_assert {};
@@ -104,8 +91,8 @@ template<typename T, int Size, int _Rows, int _Cols, int _Options> class DenseSt
: m_data(internal::constructor_without_unaligned_array_assert()) {}
inline DenseStorage(DenseIndex,DenseIndex,DenseIndex) {}
inline void swap(DenseStorage& other) { std::swap(m_data,other.m_data); }
- inline static DenseIndex rows(void) {return _Rows;}
- inline static DenseIndex cols(void) {return _Cols;}
+ static inline DenseIndex rows(void) {return _Rows;}
+ static inline DenseIndex cols(void) {return _Cols;}
inline void conservativeResize(DenseIndex,DenseIndex,DenseIndex) {}
inline void resize(DenseIndex,DenseIndex,DenseIndex) {}
inline const T *data() const { return m_data.array; }
@@ -120,14 +107,24 @@ template<typename T, int _Rows, int _Cols, int _Options> class DenseStorage<T, 0
inline DenseStorage(internal::constructor_without_unaligned_array_assert) {}
inline DenseStorage(DenseIndex,DenseIndex,DenseIndex) {}
inline void swap(DenseStorage& ) {}
- inline static DenseIndex rows(void) {return _Rows;}
- inline static DenseIndex cols(void) {return _Cols;}
+ static inline DenseIndex rows(void) {return _Rows;}
+ static inline DenseIndex cols(void) {return _Cols;}
inline void conservativeResize(DenseIndex,DenseIndex,DenseIndex) {}
inline void resize(DenseIndex,DenseIndex,DenseIndex) {}
inline const T *data() const { return 0; }
inline T *data() { return 0; }
};
+// more specializations for null matrices; these are necessary to resolve ambiguities
+template<typename T, int _Options> class DenseStorage<T, 0, Dynamic, Dynamic, _Options>
+: public DenseStorage<T, 0, 0, 0, _Options> { };
+
+template<typename T, int _Rows, int _Options> class DenseStorage<T, 0, _Rows, Dynamic, _Options>
+: public DenseStorage<T, 0, 0, 0, _Options> { };
+
+template<typename T, int _Cols, int _Options> class DenseStorage<T, 0, Dynamic, _Cols, _Options>
+: public DenseStorage<T, 0, 0, 0, _Options> { };
+
// dynamic-size matrix with fixed-size storage
template<typename T, int Size, int _Options> class DenseStorage<T, Size, Dynamic, Dynamic, _Options>
{
@@ -241,7 +238,7 @@ template<typename T, int _Rows, int _Options> class DenseStorage<T, Dynamic, _Ro
{ EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN }
inline ~DenseStorage() { internal::conditional_aligned_delete_auto<T,(_Options&DontAlign)==0>(m_data, _Rows*m_cols); }
inline void swap(DenseStorage& other) { std::swap(m_data,other.m_data); std::swap(m_cols,other.m_cols); }
- inline static DenseIndex rows(void) {return _Rows;}
+ static inline DenseIndex rows(void) {return _Rows;}
inline DenseIndex cols(void) const {return m_cols;}
inline void conservativeResize(DenseIndex size, DenseIndex, DenseIndex cols)
{
@@ -278,7 +275,7 @@ template<typename T, int _Cols, int _Options> class DenseStorage<T, Dynamic, Dyn
inline ~DenseStorage() { internal::conditional_aligned_delete_auto<T,(_Options&DontAlign)==0>(m_data, _Cols*m_rows); }
inline void swap(DenseStorage& other) { std::swap(m_data,other.m_data); std::swap(m_rows,other.m_rows); }
inline DenseIndex rows(void) const {return m_rows;}
- inline static DenseIndex cols(void) {return _Cols;}
+ static inline DenseIndex cols(void) {return _Cols;}
inline void conservativeResize(DenseIndex size, DenseIndex rows, DenseIndex)
{
m_data = internal::conditional_aligned_realloc_new_auto<T,(_Options&DontAlign)==0>(m_data, size, m_rows*_Cols);
@@ -301,4 +298,6 @@ template<typename T, int _Cols, int _Options> class DenseStorage<T, Dynamic, Dyn
inline T *data() { return m_data; }
};
+} // end namespace Eigen
+
#endif // EIGEN_MATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Core/Diagonal.h b/extern/Eigen3/Eigen/src/Core/Diagonal.h
index 61d3b063a44..16261968a0f 100644
--- a/extern/Eigen3/Eigen/src/Core/Diagonal.h
+++ b/extern/Eigen3/Eigen/src/Core/Diagonal.h
@@ -2,29 +2,17 @@
// for linear algebra.
//
// Copyright (C) 2007-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
+// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DIAGONAL_H
#define EIGEN_DIAGONAL_H
+namespace Eigen {
+
/** \class Diagonal
* \ingroup Core_Module
*
@@ -53,16 +41,15 @@ struct traits<Diagonal<MatrixType,DiagIndex> >
typedef typename remove_reference<MatrixTypeNested>::type _MatrixTypeNested;
typedef typename MatrixType::StorageKind StorageKind;
enum {
- AbsDiagIndex = DiagIndex<0 ? -DiagIndex : DiagIndex, // only used if DiagIndex != Dynamic
- // FIXME these computations are broken in the case where the matrix is rectangular and DiagIndex!=0
RowsAtCompileTime = (int(DiagIndex) == Dynamic || int(MatrixType::SizeAtCompileTime) == Dynamic) ? Dynamic
- : (EIGEN_SIZE_MIN_PREFER_DYNAMIC(MatrixType::RowsAtCompileTime,
- MatrixType::ColsAtCompileTime) - AbsDiagIndex),
+ : (EIGEN_PLAIN_ENUM_MIN(MatrixType::RowsAtCompileTime - EIGEN_PLAIN_ENUM_MAX(-DiagIndex, 0),
+ MatrixType::ColsAtCompileTime - EIGEN_PLAIN_ENUM_MAX( DiagIndex, 0))),
ColsAtCompileTime = 1,
MaxRowsAtCompileTime = int(MatrixType::MaxSizeAtCompileTime) == Dynamic ? Dynamic
: DiagIndex == Dynamic ? EIGEN_SIZE_MIN_PREFER_FIXED(MatrixType::MaxRowsAtCompileTime,
- MatrixType::MaxColsAtCompileTime)
- : (EIGEN_SIZE_MIN_PREFER_FIXED(MatrixType::MaxRowsAtCompileTime, MatrixType::MaxColsAtCompileTime) - AbsDiagIndex),
+ MatrixType::MaxColsAtCompileTime)
+ : (EIGEN_PLAIN_ENUM_MIN(MatrixType::MaxRowsAtCompileTime - EIGEN_PLAIN_ENUM_MAX(-DiagIndex, 0),
+ MatrixType::MaxColsAtCompileTime - EIGEN_PLAIN_ENUM_MAX( DiagIndex, 0))),
MaxColsAtCompileTime = 1,
MaskLvalueBit = is_lvalue<MatrixType>::value ? LvalueBit : 0,
Flags = (unsigned int)_MatrixTypeNested::Flags & (HereditaryBits | LinearAccessBit | MaskLvalueBit | DirectAccessBit) & ~RowMajorBit,
@@ -101,6 +88,15 @@ template<typename MatrixType, int DiagIndex> class Diagonal
return 0;
}
+ typedef typename internal::conditional<
+ internal::is_lvalue<MatrixType>::value,
+ Scalar,
+ const Scalar
+ >::type ScalarWithConstIfNotLvalue;
+
+ inline ScalarWithConstIfNotLvalue* data() { return &(m_matrix.const_cast_derived().coeffRef(rowOffset(), colOffset())); }
+ inline const Scalar* data() const { return &(m_matrix.const_cast_derived().coeffRef(rowOffset(), colOffset())); }
+
inline Scalar& coeffRef(Index row, Index)
{
EIGEN_STATIC_ASSERT_LVALUE(MatrixType)
@@ -133,8 +129,19 @@ template<typename MatrixType, int DiagIndex> class Diagonal
return m_matrix.coeff(index+rowOffset(), index+colOffset());
}
+ const typename internal::remove_all<typename MatrixType::Nested>::type&
+ nestedExpression() const
+ {
+ return m_matrix;
+ }
+
+ int index() const
+ {
+ return m_index.value();
+ }
+
protected:
- const typename MatrixType::Nested m_matrix;
+ typename MatrixType::Nested m_matrix;
const internal::variable_if_dynamic<Index, DiagIndex> m_index;
private:
@@ -224,4 +231,6 @@ MatrixBase<Derived>::diagonal() const
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_DIAGONAL_H
diff --git a/extern/Eigen3/Eigen/src/Core/DiagonalMatrix.h b/extern/Eigen3/Eigen/src/Core/DiagonalMatrix.h
index f41a74bfae7..88190da684d 100644
--- a/extern/Eigen3/Eigen/src/Core/DiagonalMatrix.h
+++ b/extern/Eigen3/Eigen/src/Core/DiagonalMatrix.h
@@ -4,28 +4,15 @@
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2007-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DIAGONALMATRIX_H
#define EIGEN_DIAGONALMATRIX_H
+namespace Eigen {
+
#ifndef EIGEN_PARSED_BY_DOXYGEN
template<typename Derived>
class DiagonalBase : public EigenBase<Derived>
@@ -72,7 +59,7 @@ class DiagonalBase : public EigenBase<Derived>
const DiagonalProduct<MatrixDerived, Derived, OnTheLeft>
operator*(const MatrixBase<MatrixDerived> &matrix) const;
- inline const DiagonalWrapper<CwiseUnaryOp<internal::scalar_inverse_op<Scalar>, const DiagonalVectorType> >
+ inline const DiagonalWrapper<const CwiseUnaryOp<internal::scalar_inverse_op<Scalar>, const DiagonalVectorType> >
inverse() const
{
return diagonal().cwiseInverse();
@@ -251,13 +238,13 @@ class DiagonalWrapper
#endif
/** Constructor from expression of diagonal coefficients to wrap. */
- inline DiagonalWrapper(const DiagonalVectorType& diagonal) : m_diagonal(diagonal) {}
+ inline DiagonalWrapper(DiagonalVectorType& diagonal) : m_diagonal(diagonal) {}
/** \returns a const reference to the wrapped expression of diagonal coefficients. */
const DiagonalVectorType& diagonal() const { return m_diagonal; }
protected:
- const typename DiagonalVectorType::Nested m_diagonal;
+ typename DiagonalVectorType::Nested m_diagonal;
};
/** \returns a pseudo-expression of a diagonal matrix with *this as vector of diagonal coefficients
@@ -303,4 +290,6 @@ bool MatrixBase<Derived>::isDiagonal(RealScalar prec) const
return true;
}
+} // end namespace Eigen
+
#endif // EIGEN_DIAGONALMATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Core/DiagonalProduct.h b/extern/Eigen3/Eigen/src/Core/DiagonalProduct.h
index de0c6ed11b7..598c6b3e19a 100644
--- a/extern/Eigen3/Eigen/src/Core/DiagonalProduct.h
+++ b/extern/Eigen3/Eigen/src/Core/DiagonalProduct.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2007-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DIAGONALPRODUCT_H
#define EIGEN_DIAGONALPRODUCT_H
+namespace Eigen {
+
namespace internal {
template<typename MatrixType, typename DiagonalType, int ProductOrder>
struct traits<DiagonalProduct<MatrixType, DiagonalType, ProductOrder> >
@@ -107,8 +94,8 @@ class DiagonalProduct : internal::no_assignment_operator,
m_diagonal.diagonal().template packet<DiagonalVectorPacketLoadMode>(id));
}
- const typename MatrixType::Nested m_matrix;
- const typename DiagonalType::Nested m_diagonal;
+ typename MatrixType::Nested m_matrix;
+ typename DiagonalType::Nested m_diagonal;
};
/** \returns the diagonal matrix product of \c *this by the diagonal matrix \a diagonal.
@@ -131,5 +118,6 @@ DiagonalBase<DiagonalDerived>::operator*(const MatrixBase<MatrixDerived> &matrix
return DiagonalProduct<MatrixDerived, DiagonalDerived, OnTheLeft>(matrix.derived(), derived());
}
+} // end namespace Eigen
#endif // EIGEN_DIAGONALPRODUCT_H
diff --git a/extern/Eigen3/Eigen/src/Core/Dot.h b/extern/Eigen3/Eigen/src/Core/Dot.h
index 42da7849896..ae9274e36dd 100644
--- a/extern/Eigen3/Eigen/src/Core/Dot.h
+++ b/extern/Eigen3/Eigen/src/Core/Dot.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2006-2008, 2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DOT_H
#define EIGEN_DOT_H
+namespace Eigen {
+
namespace internal {
// helper function for dot(). The problem is that if we put that in the body of dot(), then upon calling dot
@@ -176,7 +163,7 @@ template<typename Derived, int p>
struct lpNorm_selector
{
typedef typename NumTraits<typename traits<Derived>::Scalar>::Real RealScalar;
- inline static RealScalar run(const MatrixBase<Derived>& m)
+ static inline RealScalar run(const MatrixBase<Derived>& m)
{
return pow(m.cwiseAbs().array().pow(p).sum(), RealScalar(1)/p);
}
@@ -185,7 +172,7 @@ struct lpNorm_selector
template<typename Derived>
struct lpNorm_selector<Derived, 1>
{
- inline static typename NumTraits<typename traits<Derived>::Scalar>::Real run(const MatrixBase<Derived>& m)
+ static inline typename NumTraits<typename traits<Derived>::Scalar>::Real run(const MatrixBase<Derived>& m)
{
return m.cwiseAbs().sum();
}
@@ -194,7 +181,7 @@ struct lpNorm_selector<Derived, 1>
template<typename Derived>
struct lpNorm_selector<Derived, 2>
{
- inline static typename NumTraits<typename traits<Derived>::Scalar>::Real run(const MatrixBase<Derived>& m)
+ static inline typename NumTraits<typename traits<Derived>::Scalar>::Real run(const MatrixBase<Derived>& m)
{
return m.norm();
}
@@ -203,7 +190,7 @@ struct lpNorm_selector<Derived, 2>
template<typename Derived>
struct lpNorm_selector<Derived, Infinity>
{
- inline static typename NumTraits<typename traits<Derived>::Scalar>::Real run(const MatrixBase<Derived>& m)
+ static inline typename NumTraits<typename traits<Derived>::Scalar>::Real run(const MatrixBase<Derived>& m)
{
return m.cwiseAbs().maxCoeff();
}
@@ -269,4 +256,6 @@ bool MatrixBase<Derived>::isUnitary(RealScalar prec) const
return true;
}
+} // end namespace Eigen
+
#endif // EIGEN_DOT_H
diff --git a/extern/Eigen3/Eigen/src/Core/EigenBase.h b/extern/Eigen3/Eigen/src/Core/EigenBase.h
index 0472539af33..0bbd28bec21 100644
--- a/extern/Eigen3/Eigen/src/Core/EigenBase.h
+++ b/extern/Eigen3/Eigen/src/Core/EigenBase.h
@@ -4,28 +4,14 @@
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_EIGENBASE_H
#define EIGEN_EIGENBASE_H
+namespace Eigen {
/** Common base class for all classes T such that MatrixBase has an operator=(T) and a constructor MatrixBase(T).
*
@@ -169,4 +155,6 @@ inline void MatrixBase<Derived>::applyOnTheLeft(const EigenBase<OtherDerived> &o
other.derived().applyThisOnTheLeft(derived());
}
+} // end namespace Eigen
+
#endif // EIGEN_EIGENBASE_H
diff --git a/extern/Eigen3/Eigen/src/Core/Flagged.h b/extern/Eigen3/Eigen/src/Core/Flagged.h
index 458213ab553..1f2955fc1de 100644
--- a/extern/Eigen3/Eigen/src/Core/Flagged.h
+++ b/extern/Eigen3/Eigen/src/Core/Flagged.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_FLAGGED_H
#define EIGEN_FLAGGED_H
+namespace Eigen {
+
/** \class Flagged
* \ingroup Core_Module
*
@@ -148,4 +135,6 @@ DenseBase<Derived>::flagged() const
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_FLAGGED_H
diff --git a/extern/Eigen3/Eigen/src/Core/ForceAlignedAccess.h b/extern/Eigen3/Eigen/src/Core/ForceAlignedAccess.h
index 11c1f8f709a..807c7a29346 100644
--- a/extern/Eigen3/Eigen/src/Core/ForceAlignedAccess.h
+++ b/extern/Eigen3/Eigen/src/Core/ForceAlignedAccess.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_FORCEALIGNEDACCESS_H
#define EIGEN_FORCEALIGNEDACCESS_H
+namespace Eigen {
+
/** \class ForceAlignedAccess
* \ingroup Core_Module
*
@@ -154,4 +141,6 @@ MatrixBase<Derived>::forceAlignedAccessIf()
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_FORCEALIGNEDACCESS_H
diff --git a/extern/Eigen3/Eigen/src/Core/Functors.h b/extern/Eigen3/Eigen/src/Core/Functors.h
index 54636e0d459..278c46c6b61 100644
--- a/extern/Eigen3/Eigen/src/Core/Functors.h
+++ b/extern/Eigen3/Eigen/src/Core/Functors.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_FUNCTORS_H
#define EIGEN_FUNCTORS_H
+namespace Eigen {
+
namespace internal {
// associative functors:
@@ -178,6 +165,18 @@ struct functor_traits<scalar_hypot_op<Scalar> > {
enum { Cost = 5 * NumTraits<Scalar>::MulCost, PacketAccess=0 };
};
+/** \internal
+ * \brief Template functor to compute the pow of two scalars
+ */
+template<typename Scalar, typename OtherScalar> struct scalar_binary_pow_op {
+ EIGEN_EMPTY_STRUCT_CTOR(scalar_binary_pow_op)
+ inline Scalar operator() (const Scalar& a, const OtherScalar& b) const { return internal::pow(a, b); }
+};
+template<typename Scalar, typename OtherScalar>
+struct functor_traits<scalar_binary_pow_op<Scalar,OtherScalar> > {
+ enum { Cost = 5 * NumTraits<Scalar>::MulCost, PacketAccess = false };
+};
+
// other binary functors:
/** \internal
@@ -220,6 +219,38 @@ struct functor_traits<scalar_quotient_op<Scalar> > {
};
};
+/** \internal
+ * \brief Template functor to compute the and of two booleans
+ *
+ * \sa class CwiseBinaryOp, ArrayBase::operator&&
+ */
+struct scalar_boolean_and_op {
+ EIGEN_EMPTY_STRUCT_CTOR(scalar_boolean_and_op)
+ EIGEN_STRONG_INLINE bool operator() (const bool& a, const bool& b) const { return a && b; }
+};
+template<> struct functor_traits<scalar_boolean_and_op> {
+ enum {
+ Cost = NumTraits<bool>::AddCost,
+ PacketAccess = false
+ };
+};
+
+/** \internal
+ * \brief Template functor to compute the or of two booleans
+ *
+ * \sa class CwiseBinaryOp, ArrayBase::operator||
+ */
+struct scalar_boolean_or_op {
+ EIGEN_EMPTY_STRUCT_CTOR(scalar_boolean_or_op)
+ EIGEN_STRONG_INLINE bool operator() (const bool& a, const bool& b) const { return a || b; }
+};
+template<> struct functor_traits<scalar_boolean_or_op> {
+ enum {
+ Cost = NumTraits<bool>::AddCost,
+ PacketAccess = false
+ };
+};
+
// unary functors:
/** \internal
@@ -249,7 +280,7 @@ struct functor_traits<scalar_opposite_op<Scalar> >
template<typename Scalar> struct scalar_abs_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_abs_op)
typedef typename NumTraits<Scalar>::Real result_type;
- EIGEN_STRONG_INLINE const result_type operator() (const Scalar& a) const { return abs(a); }
+ EIGEN_STRONG_INLINE const result_type operator() (const Scalar& a) const { return internal::abs(a); }
template<typename Packet>
EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a) const
{ return internal::pabs(a); }
@@ -271,7 +302,7 @@ struct functor_traits<scalar_abs_op<Scalar> >
template<typename Scalar> struct scalar_abs2_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_abs2_op)
typedef typename NumTraits<Scalar>::Real result_type;
- EIGEN_STRONG_INLINE const result_type operator() (const Scalar& a) const { return abs2(a); }
+ EIGEN_STRONG_INLINE const result_type operator() (const Scalar& a) const { return internal::abs2(a); }
template<typename Packet>
EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a) const
{ return internal::pmul(a,a); }
@@ -287,7 +318,7 @@ struct functor_traits<scalar_abs2_op<Scalar> >
*/
template<typename Scalar> struct scalar_conjugate_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_conjugate_op)
- EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a) const { return conj(a); }
+ EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a) const { return internal::conj(a); }
template<typename Packet>
EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a) const { return internal::pconj(a); }
};
@@ -324,7 +355,7 @@ template<typename Scalar>
struct scalar_real_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_real_op)
typedef typename NumTraits<Scalar>::Real result_type;
- EIGEN_STRONG_INLINE result_type operator() (const Scalar& a) const { return real(a); }
+ EIGEN_STRONG_INLINE result_type operator() (const Scalar& a) const { return internal::real(a); }
};
template<typename Scalar>
struct functor_traits<scalar_real_op<Scalar> >
@@ -339,7 +370,7 @@ template<typename Scalar>
struct scalar_imag_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_imag_op)
typedef typename NumTraits<Scalar>::Real result_type;
- EIGEN_STRONG_INLINE result_type operator() (const Scalar& a) const { return imag(a); }
+ EIGEN_STRONG_INLINE result_type operator() (const Scalar& a) const { return internal::imag(a); }
};
template<typename Scalar>
struct functor_traits<scalar_imag_op<Scalar> >
@@ -354,7 +385,7 @@ template<typename Scalar>
struct scalar_real_ref_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_real_ref_op)
typedef typename NumTraits<Scalar>::Real result_type;
- EIGEN_STRONG_INLINE result_type& operator() (const Scalar& a) const { return real_ref(*const_cast<Scalar*>(&a)); }
+ EIGEN_STRONG_INLINE result_type& operator() (const Scalar& a) const { return internal::real_ref(*const_cast<Scalar*>(&a)); }
};
template<typename Scalar>
struct functor_traits<scalar_real_ref_op<Scalar> >
@@ -369,7 +400,7 @@ template<typename Scalar>
struct scalar_imag_ref_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_imag_ref_op)
typedef typename NumTraits<Scalar>::Real result_type;
- EIGEN_STRONG_INLINE result_type& operator() (const Scalar& a) const { return imag_ref(*const_cast<Scalar*>(&a)); }
+ EIGEN_STRONG_INLINE result_type& operator() (const Scalar& a) const { return internal::imag_ref(*const_cast<Scalar*>(&a)); }
};
template<typename Scalar>
struct functor_traits<scalar_imag_ref_op<Scalar> >
@@ -383,7 +414,7 @@ struct functor_traits<scalar_imag_ref_op<Scalar> >
*/
template<typename Scalar> struct scalar_exp_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_exp_op)
- inline const Scalar operator() (const Scalar& a) const { return exp(a); }
+ inline const Scalar operator() (const Scalar& a) const { return internal::exp(a); }
typedef typename packet_traits<Scalar>::type Packet;
inline Packet packetOp(const Packet& a) const { return internal::pexp(a); }
};
@@ -399,7 +430,7 @@ struct functor_traits<scalar_exp_op<Scalar> >
*/
template<typename Scalar> struct scalar_log_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_log_op)
- inline const Scalar operator() (const Scalar& a) const { return log(a); }
+ inline const Scalar operator() (const Scalar& a) const { return internal::log(a); }
typedef typename packet_traits<Scalar>::type Packet;
inline Packet packetOp(const Packet& a) const { return internal::plog(a); }
};
@@ -584,7 +615,7 @@ template <typename Scalar, bool RandomAccess> struct functor_traits< linspaced_o
template <typename Scalar, bool RandomAccess> struct linspaced_op
{
typedef typename packet_traits<Scalar>::type Packet;
- linspaced_op(Scalar low, Scalar high, int num_steps) : impl(low, (high-low)/(num_steps-1)) {}
+ linspaced_op(Scalar low, Scalar high, int num_steps) : impl((num_steps==1 ? high : low), (num_steps==1 ? Scalar() : (high-low)/(num_steps-1))) {}
template<typename Index>
EIGEN_STRONG_INLINE const Scalar operator() (Index i) const { return impl(i); }
@@ -657,7 +688,7 @@ struct functor_traits<scalar_add_op<Scalar> >
*/
template<typename Scalar> struct scalar_sqrt_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_sqrt_op)
- inline const Scalar operator() (const Scalar& a) const { return sqrt(a); }
+ inline const Scalar operator() (const Scalar& a) const { return internal::sqrt(a); }
typedef typename packet_traits<Scalar>::type Packet;
inline Packet packetOp(const Packet& a) const { return internal::psqrt(a); }
};
@@ -675,7 +706,7 @@ struct functor_traits<scalar_sqrt_op<Scalar> >
*/
template<typename Scalar> struct scalar_cos_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_cos_op)
- inline Scalar operator() (const Scalar& a) const { return cos(a); }
+ inline Scalar operator() (const Scalar& a) const { return internal::cos(a); }
typedef typename packet_traits<Scalar>::type Packet;
inline Packet packetOp(const Packet& a) const { return internal::pcos(a); }
};
@@ -694,7 +725,7 @@ struct functor_traits<scalar_cos_op<Scalar> >
*/
template<typename Scalar> struct scalar_sin_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_sin_op)
- inline const Scalar operator() (const Scalar& a) const { return sin(a); }
+ inline const Scalar operator() (const Scalar& a) const { return internal::sin(a); }
typedef typename packet_traits<Scalar>::type Packet;
inline Packet packetOp(const Packet& a) const { return internal::psin(a); }
};
@@ -714,7 +745,7 @@ struct functor_traits<scalar_sin_op<Scalar> >
*/
template<typename Scalar> struct scalar_tan_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_tan_op)
- inline const Scalar operator() (const Scalar& a) const { return tan(a); }
+ inline const Scalar operator() (const Scalar& a) const { return internal::tan(a); }
typedef typename packet_traits<Scalar>::type Packet;
inline Packet packetOp(const Packet& a) const { return internal::ptan(a); }
};
@@ -733,7 +764,7 @@ struct functor_traits<scalar_tan_op<Scalar> >
*/
template<typename Scalar> struct scalar_acos_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_acos_op)
- inline const Scalar operator() (const Scalar& a) const { return acos(a); }
+ inline const Scalar operator() (const Scalar& a) const { return internal::acos(a); }
typedef typename packet_traits<Scalar>::type Packet;
inline Packet packetOp(const Packet& a) const { return internal::pacos(a); }
};
@@ -752,7 +783,7 @@ struct functor_traits<scalar_acos_op<Scalar> >
*/
template<typename Scalar> struct scalar_asin_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_asin_op)
- inline const Scalar operator() (const Scalar& a) const { return asin(a); }
+ inline const Scalar operator() (const Scalar& a) const { return internal::asin(a); }
typedef typename packet_traits<Scalar>::type Packet;
inline Packet packetOp(const Packet& a) const { return internal::pasin(a); }
};
@@ -782,6 +813,20 @@ struct functor_traits<scalar_pow_op<Scalar> >
{ enum { Cost = 5 * NumTraits<Scalar>::MulCost, PacketAccess = false }; };
/** \internal
+ * \brief Template functor to compute the quotient between a scalar and array entries.
+ * \sa class CwiseUnaryOp, Cwise::inverse()
+ */
+template<typename Scalar>
+struct scalar_inverse_mult_op {
+ scalar_inverse_mult_op(const Scalar& other) : m_other(other) {}
+ inline Scalar operator() (const Scalar& a) const { return m_other / a; }
+ template<typename Packet>
+ inline const Packet packetOp(const Packet& a) const
+ { return internal::pdiv(pset1<Packet>(m_other),a); }
+ Scalar m_other;
+};
+
+/** \internal
* \brief Template functor to compute the inverse of a scalar
* \sa class CwiseUnaryOp, Cwise::inverse()
*/
@@ -939,4 +984,6 @@ struct functor_traits<std::binary_compose<T0,T1,T2> >
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_FUNCTORS_H
diff --git a/extern/Eigen3/Eigen/src/Core/Fuzzy.h b/extern/Eigen3/Eigen/src/Core/Fuzzy.h
index d266eed0ac6..d74edcfdb9d 100644
--- a/extern/Eigen3/Eigen/src/Core/Fuzzy.h
+++ b/extern/Eigen3/Eigen/src/Core/Fuzzy.h
@@ -4,28 +4,15 @@
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_FUZZY_H
#define EIGEN_FUZZY_H
+namespace Eigen {
+
namespace internal
{
@@ -35,8 +22,8 @@ struct isApprox_selector
static bool run(const Derived& x, const OtherDerived& y, typename Derived::RealScalar prec)
{
using std::min;
- const typename internal::nested<Derived,2>::type nested(x);
- const typename internal::nested<OtherDerived,2>::type otherNested(y);
+ typename internal::nested<Derived,2>::type nested(x);
+ typename internal::nested<OtherDerived,2>::type otherNested(y);
return (nested - otherNested).cwiseAbs2().sum() <= prec * prec * (min)(nested.cwiseAbs2().sum(), otherNested.cwiseAbs2().sum());
}
};
@@ -158,4 +145,6 @@ bool DenseBase<Derived>::isMuchSmallerThan(
return internal::isMuchSmallerThan_object_selector<Derived, OtherDerived>::run(derived(), other.derived(), prec);
}
+} // end namespace Eigen
+
#endif // EIGEN_FUZZY_H
diff --git a/extern/Eigen3/Eigen/src/Core/GeneralProduct.h b/extern/Eigen3/Eigen/src/Core/GeneralProduct.h
new file mode 100644
index 00000000000..bfc2a67b12f
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/GeneralProduct.h
@@ -0,0 +1,613 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
+// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_GENERAL_PRODUCT_H
+#define EIGEN_GENERAL_PRODUCT_H
+
+namespace Eigen {
+
+/** \class GeneralProduct
+ * \ingroup Core_Module
+ *
+ * \brief Expression of the product of two general matrices or vectors
+ *
+ * \param LhsNested the type used to store the left-hand side
+ * \param RhsNested the type used to store the right-hand side
+ * \param ProductMode the type of the product
+ *
+ * This class represents an expression of the product of two general matrices.
+ * We call a general matrix, a dense matrix with full storage. For instance,
+ * This excludes triangular, selfadjoint, and sparse matrices.
+ * It is the return type of the operator* between general matrices. Its template
+ * arguments are determined automatically by ProductReturnType. Therefore,
+ * GeneralProduct should never be used direclty. To determine the result type of a
+ * function which involves a matrix product, use ProductReturnType::Type.
+ *
+ * \sa ProductReturnType, MatrixBase::operator*(const MatrixBase<OtherDerived>&)
+ */
+template<typename Lhs, typename Rhs, int ProductType = internal::product_type<Lhs,Rhs>::value>
+class GeneralProduct;
+
+enum {
+ Large = 2,
+ Small = 3
+};
+
+namespace internal {
+
+template<int Rows, int Cols, int Depth> struct product_type_selector;
+
+template<int Size, int MaxSize> struct product_size_category
+{
+ enum { is_large = MaxSize == Dynamic ||
+ Size >= EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD,
+ value = is_large ? Large
+ : Size == 1 ? 1
+ : Small
+ };
+};
+
+template<typename Lhs, typename Rhs> struct product_type
+{
+ typedef typename remove_all<Lhs>::type _Lhs;
+ typedef typename remove_all<Rhs>::type _Rhs;
+ enum {
+ MaxRows = _Lhs::MaxRowsAtCompileTime,
+ Rows = _Lhs::RowsAtCompileTime,
+ MaxCols = _Rhs::MaxColsAtCompileTime,
+ Cols = _Rhs::ColsAtCompileTime,
+ MaxDepth = EIGEN_SIZE_MIN_PREFER_FIXED(_Lhs::MaxColsAtCompileTime,
+ _Rhs::MaxRowsAtCompileTime),
+ Depth = EIGEN_SIZE_MIN_PREFER_FIXED(_Lhs::ColsAtCompileTime,
+ _Rhs::RowsAtCompileTime),
+ LargeThreshold = EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD
+ };
+
+ // the splitting into different lines of code here, introducing the _select enums and the typedef below,
+ // is to work around an internal compiler error with gcc 4.1 and 4.2.
+private:
+ enum {
+ rows_select = product_size_category<Rows,MaxRows>::value,
+ cols_select = product_size_category<Cols,MaxCols>::value,
+ depth_select = product_size_category<Depth,MaxDepth>::value
+ };
+ typedef product_type_selector<rows_select, cols_select, depth_select> selector;
+
+public:
+ enum {
+ value = selector::ret
+ };
+#ifdef EIGEN_DEBUG_PRODUCT
+ static void debug()
+ {
+ EIGEN_DEBUG_VAR(Rows);
+ EIGEN_DEBUG_VAR(Cols);
+ EIGEN_DEBUG_VAR(Depth);
+ EIGEN_DEBUG_VAR(rows_select);
+ EIGEN_DEBUG_VAR(cols_select);
+ EIGEN_DEBUG_VAR(depth_select);
+ EIGEN_DEBUG_VAR(value);
+ }
+#endif
+};
+
+
+/* The following allows to select the kind of product at compile time
+ * based on the three dimensions of the product.
+ * This is a compile time mapping from {1,Small,Large}^3 -> {product types} */
+// FIXME I'm not sure the current mapping is the ideal one.
+template<int M, int N> struct product_type_selector<M,N,1> { enum { ret = OuterProduct }; };
+template<int Depth> struct product_type_selector<1, 1, Depth> { enum { ret = InnerProduct }; };
+template<> struct product_type_selector<1, 1, 1> { enum { ret = InnerProduct }; };
+template<> struct product_type_selector<Small,1, Small> { enum { ret = CoeffBasedProductMode }; };
+template<> struct product_type_selector<1, Small,Small> { enum { ret = CoeffBasedProductMode }; };
+template<> struct product_type_selector<Small,Small,Small> { enum { ret = CoeffBasedProductMode }; };
+template<> struct product_type_selector<Small, Small, 1> { enum { ret = LazyCoeffBasedProductMode }; };
+template<> struct product_type_selector<Small, Large, 1> { enum { ret = LazyCoeffBasedProductMode }; };
+template<> struct product_type_selector<Large, Small, 1> { enum { ret = LazyCoeffBasedProductMode }; };
+template<> struct product_type_selector<1, Large,Small> { enum { ret = CoeffBasedProductMode }; };
+template<> struct product_type_selector<1, Large,Large> { enum { ret = GemvProduct }; };
+template<> struct product_type_selector<1, Small,Large> { enum { ret = CoeffBasedProductMode }; };
+template<> struct product_type_selector<Large,1, Small> { enum { ret = CoeffBasedProductMode }; };
+template<> struct product_type_selector<Large,1, Large> { enum { ret = GemvProduct }; };
+template<> struct product_type_selector<Small,1, Large> { enum { ret = CoeffBasedProductMode }; };
+template<> struct product_type_selector<Small,Small,Large> { enum { ret = GemmProduct }; };
+template<> struct product_type_selector<Large,Small,Large> { enum { ret = GemmProduct }; };
+template<> struct product_type_selector<Small,Large,Large> { enum { ret = GemmProduct }; };
+template<> struct product_type_selector<Large,Large,Large> { enum { ret = GemmProduct }; };
+template<> struct product_type_selector<Large,Small,Small> { enum { ret = GemmProduct }; };
+template<> struct product_type_selector<Small,Large,Small> { enum { ret = GemmProduct }; };
+template<> struct product_type_selector<Large,Large,Small> { enum { ret = GemmProduct }; };
+
+} // end namespace internal
+
+/** \class ProductReturnType
+ * \ingroup Core_Module
+ *
+ * \brief Helper class to get the correct and optimized returned type of operator*
+ *
+ * \param Lhs the type of the left-hand side
+ * \param Rhs the type of the right-hand side
+ * \param ProductMode the type of the product (determined automatically by internal::product_mode)
+ *
+ * This class defines the typename Type representing the optimized product expression
+ * between two matrix expressions. In practice, using ProductReturnType<Lhs,Rhs>::Type
+ * is the recommended way to define the result type of a function returning an expression
+ * which involve a matrix product. The class Product should never be
+ * used directly.
+ *
+ * \sa class Product, MatrixBase::operator*(const MatrixBase<OtherDerived>&)
+ */
+template<typename Lhs, typename Rhs, int ProductType>
+struct ProductReturnType
+{
+ // TODO use the nested type to reduce instanciations ????
+// typedef typename internal::nested<Lhs,Rhs::ColsAtCompileTime>::type LhsNested;
+// typedef typename internal::nested<Rhs,Lhs::RowsAtCompileTime>::type RhsNested;
+
+ typedef GeneralProduct<Lhs/*Nested*/, Rhs/*Nested*/, ProductType> Type;
+};
+
+template<typename Lhs, typename Rhs>
+struct ProductReturnType<Lhs,Rhs,CoeffBasedProductMode>
+{
+ typedef typename internal::nested<Lhs, Rhs::ColsAtCompileTime, typename internal::plain_matrix_type<Lhs>::type >::type LhsNested;
+ typedef typename internal::nested<Rhs, Lhs::RowsAtCompileTime, typename internal::plain_matrix_type<Rhs>::type >::type RhsNested;
+ typedef CoeffBasedProduct<LhsNested, RhsNested, EvalBeforeAssigningBit | EvalBeforeNestingBit> Type;
+};
+
+template<typename Lhs, typename Rhs>
+struct ProductReturnType<Lhs,Rhs,LazyCoeffBasedProductMode>
+{
+ typedef typename internal::nested<Lhs, Rhs::ColsAtCompileTime, typename internal::plain_matrix_type<Lhs>::type >::type LhsNested;
+ typedef typename internal::nested<Rhs, Lhs::RowsAtCompileTime, typename internal::plain_matrix_type<Rhs>::type >::type RhsNested;
+ typedef CoeffBasedProduct<LhsNested, RhsNested, NestByRefBit> Type;
+};
+
+// this is a workaround for sun CC
+template<typename Lhs, typename Rhs>
+struct LazyProductReturnType : public ProductReturnType<Lhs,Rhs,LazyCoeffBasedProductMode>
+{};
+
+/***********************************************************************
+* Implementation of Inner Vector Vector Product
+***********************************************************************/
+
+// FIXME : maybe the "inner product" could return a Scalar
+// instead of a 1x1 matrix ??
+// Pro: more natural for the user
+// Cons: this could be a problem if in a meta unrolled algorithm a matrix-matrix
+// product ends up to a row-vector times col-vector product... To tackle this use
+// case, we could have a specialization for Block<MatrixType,1,1> with: operator=(Scalar x);
+
+namespace internal {
+
+template<typename Lhs, typename Rhs>
+struct traits<GeneralProduct<Lhs,Rhs,InnerProduct> >
+ : traits<Matrix<typename scalar_product_traits<typename Lhs::Scalar, typename Rhs::Scalar>::ReturnType,1,1> >
+{};
+
+}
+
+template<typename Lhs, typename Rhs>
+class GeneralProduct<Lhs, Rhs, InnerProduct>
+ : internal::no_assignment_operator,
+ public Matrix<typename internal::scalar_product_traits<typename Lhs::Scalar, typename Rhs::Scalar>::ReturnType,1,1>
+{
+ typedef Matrix<typename internal::scalar_product_traits<typename Lhs::Scalar, typename Rhs::Scalar>::ReturnType,1,1> Base;
+ public:
+ GeneralProduct(const Lhs& lhs, const Rhs& rhs)
+ {
+ EIGEN_STATIC_ASSERT((internal::is_same<typename Lhs::RealScalar, typename Rhs::RealScalar>::value),
+ YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)
+
+ Base::coeffRef(0,0) = (lhs.transpose().cwiseProduct(rhs)).sum();
+ }
+
+ /** Convertion to scalar */
+ operator const typename Base::Scalar() const {
+ return Base::coeff(0,0);
+ }
+};
+
+/***********************************************************************
+* Implementation of Outer Vector Vector Product
+***********************************************************************/
+
+namespace internal {
+template<int StorageOrder> struct outer_product_selector;
+
+template<typename Lhs, typename Rhs>
+struct traits<GeneralProduct<Lhs,Rhs,OuterProduct> >
+ : traits<ProductBase<GeneralProduct<Lhs,Rhs,OuterProduct>, Lhs, Rhs> >
+{};
+
+}
+
+template<typename Lhs, typename Rhs>
+class GeneralProduct<Lhs, Rhs, OuterProduct>
+ : public ProductBase<GeneralProduct<Lhs,Rhs,OuterProduct>, Lhs, Rhs>
+{
+ public:
+ EIGEN_PRODUCT_PUBLIC_INTERFACE(GeneralProduct)
+
+ GeneralProduct(const Lhs& lhs, const Rhs& rhs) : Base(lhs,rhs)
+ {
+ EIGEN_STATIC_ASSERT((internal::is_same<typename Lhs::RealScalar, typename Rhs::RealScalar>::value),
+ YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)
+ }
+
+ template<typename Dest> void scaleAndAddTo(Dest& dest, Scalar alpha) const
+ {
+ internal::outer_product_selector<(int(Dest::Flags)&RowMajorBit) ? RowMajor : ColMajor>::run(*this, dest, alpha);
+ }
+};
+
+namespace internal {
+
+template<> struct outer_product_selector<ColMajor> {
+ template<typename ProductType, typename Dest>
+ static EIGEN_DONT_INLINE void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha) {
+ typedef typename Dest::Index Index;
+ // FIXME make sure lhs is sequentially stored
+ // FIXME not very good if rhs is real and lhs complex while alpha is real too
+ const Index cols = dest.cols();
+ for (Index j=0; j<cols; ++j)
+ dest.col(j) += (alpha * prod.rhs().coeff(j)) * prod.lhs();
+ }
+};
+
+template<> struct outer_product_selector<RowMajor> {
+ template<typename ProductType, typename Dest>
+ static EIGEN_DONT_INLINE void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha) {
+ typedef typename Dest::Index Index;
+ // FIXME make sure rhs is sequentially stored
+ // FIXME not very good if lhs is real and rhs complex while alpha is real too
+ const Index rows = dest.rows();
+ for (Index i=0; i<rows; ++i)
+ dest.row(i) += (alpha * prod.lhs().coeff(i)) * prod.rhs();
+ }
+};
+
+} // end namespace internal
+
+/***********************************************************************
+* Implementation of General Matrix Vector Product
+***********************************************************************/
+
+/* According to the shape/flags of the matrix we have to distinghish 3 different cases:
+ * 1 - the matrix is col-major, BLAS compatible and M is large => call fast BLAS-like colmajor routine
+ * 2 - the matrix is row-major, BLAS compatible and N is large => call fast BLAS-like rowmajor routine
+ * 3 - all other cases are handled using a simple loop along the outer-storage direction.
+ * Therefore we need a lower level meta selector.
+ * Furthermore, if the matrix is the rhs, then the product has to be transposed.
+ */
+namespace internal {
+
+template<typename Lhs, typename Rhs>
+struct traits<GeneralProduct<Lhs,Rhs,GemvProduct> >
+ : traits<ProductBase<GeneralProduct<Lhs,Rhs,GemvProduct>, Lhs, Rhs> >
+{};
+
+template<int Side, int StorageOrder, bool BlasCompatible>
+struct gemv_selector;
+
+} // end namespace internal
+
+template<typename Lhs, typename Rhs>
+class GeneralProduct<Lhs, Rhs, GemvProduct>
+ : public ProductBase<GeneralProduct<Lhs,Rhs,GemvProduct>, Lhs, Rhs>
+{
+ public:
+ EIGEN_PRODUCT_PUBLIC_INTERFACE(GeneralProduct)
+
+ typedef typename Lhs::Scalar LhsScalar;
+ typedef typename Rhs::Scalar RhsScalar;
+
+ GeneralProduct(const Lhs& lhs, const Rhs& rhs) : Base(lhs,rhs)
+ {
+// EIGEN_STATIC_ASSERT((internal::is_same<typename Lhs::Scalar, typename Rhs::Scalar>::value),
+// YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)
+ }
+
+ enum { Side = Lhs::IsVectorAtCompileTime ? OnTheLeft : OnTheRight };
+ typedef typename internal::conditional<int(Side)==OnTheRight,_LhsNested,_RhsNested>::type MatrixType;
+
+ template<typename Dest> void scaleAndAddTo(Dest& dst, Scalar alpha) const
+ {
+ eigen_assert(m_lhs.rows() == dst.rows() && m_rhs.cols() == dst.cols());
+ internal::gemv_selector<Side,(int(MatrixType::Flags)&RowMajorBit) ? RowMajor : ColMajor,
+ bool(internal::blas_traits<MatrixType>::HasUsableDirectAccess)>::run(*this, dst, alpha);
+ }
+};
+
+namespace internal {
+
+// The vector is on the left => transposition
+template<int StorageOrder, bool BlasCompatible>
+struct gemv_selector<OnTheLeft,StorageOrder,BlasCompatible>
+{
+ template<typename ProductType, typename Dest>
+ static void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha)
+ {
+ Transpose<Dest> destT(dest);
+ enum { OtherStorageOrder = StorageOrder == RowMajor ? ColMajor : RowMajor };
+ gemv_selector<OnTheRight,OtherStorageOrder,BlasCompatible>
+ ::run(GeneralProduct<Transpose<const typename ProductType::_RhsNested>,Transpose<const typename ProductType::_LhsNested>, GemvProduct>
+ (prod.rhs().transpose(), prod.lhs().transpose()), destT, alpha);
+ }
+};
+
+template<typename Scalar,int Size,int MaxSize,bool Cond> struct gemv_static_vector_if;
+
+template<typename Scalar,int Size,int MaxSize>
+struct gemv_static_vector_if<Scalar,Size,MaxSize,false>
+{
+ EIGEN_STRONG_INLINE Scalar* data() { eigen_internal_assert(false && "should never be called"); return 0; }
+};
+
+template<typename Scalar,int Size>
+struct gemv_static_vector_if<Scalar,Size,Dynamic,true>
+{
+ EIGEN_STRONG_INLINE Scalar* data() { return 0; }
+};
+
+template<typename Scalar,int Size,int MaxSize>
+struct gemv_static_vector_if<Scalar,Size,MaxSize,true>
+{
+ #if EIGEN_ALIGN_STATICALLY
+ internal::plain_array<Scalar,EIGEN_SIZE_MIN_PREFER_FIXED(Size,MaxSize),0> m_data;
+ EIGEN_STRONG_INLINE Scalar* data() { return m_data.array; }
+ #else
+ // Some architectures cannot align on the stack,
+ // => let's manually enforce alignment by allocating more data and return the address of the first aligned element.
+ enum {
+ ForceAlignment = internal::packet_traits<Scalar>::Vectorizable,
+ PacketSize = internal::packet_traits<Scalar>::size
+ };
+ internal::plain_array<Scalar,EIGEN_SIZE_MIN_PREFER_FIXED(Size,MaxSize)+(ForceAlignment?PacketSize:0),0> m_data;
+ EIGEN_STRONG_INLINE Scalar* data() {
+ return ForceAlignment
+ ? reinterpret_cast<Scalar*>((reinterpret_cast<size_t>(m_data.array) & ~(size_t(15))) + 16)
+ : m_data.array;
+ }
+ #endif
+};
+
+template<> struct gemv_selector<OnTheRight,ColMajor,true>
+{
+ template<typename ProductType, typename Dest>
+ static inline void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha)
+ {
+ typedef typename ProductType::Index Index;
+ typedef typename ProductType::LhsScalar LhsScalar;
+ typedef typename ProductType::RhsScalar RhsScalar;
+ typedef typename ProductType::Scalar ResScalar;
+ typedef typename ProductType::RealScalar RealScalar;
+ typedef typename ProductType::ActualLhsType ActualLhsType;
+ typedef typename ProductType::ActualRhsType ActualRhsType;
+ typedef typename ProductType::LhsBlasTraits LhsBlasTraits;
+ typedef typename ProductType::RhsBlasTraits RhsBlasTraits;
+ typedef Map<Matrix<ResScalar,Dynamic,1>, Aligned> MappedDest;
+
+ ActualLhsType actualLhs = LhsBlasTraits::extract(prod.lhs());
+ ActualRhsType actualRhs = RhsBlasTraits::extract(prod.rhs());
+
+ ResScalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(prod.lhs())
+ * RhsBlasTraits::extractScalarFactor(prod.rhs());
+
+ enum {
+ // FIXME find a way to allow an inner stride on the result if packet_traits<Scalar>::size==1
+ // on, the other hand it is good for the cache to pack the vector anyways...
+ EvalToDestAtCompileTime = Dest::InnerStrideAtCompileTime==1,
+ ComplexByReal = (NumTraits<LhsScalar>::IsComplex) && (!NumTraits<RhsScalar>::IsComplex),
+ MightCannotUseDest = (Dest::InnerStrideAtCompileTime!=1) || ComplexByReal
+ };
+
+ gemv_static_vector_if<ResScalar,Dest::SizeAtCompileTime,Dest::MaxSizeAtCompileTime,MightCannotUseDest> static_dest;
+
+ bool alphaIsCompatible = (!ComplexByReal) || (imag(actualAlpha)==RealScalar(0));
+ bool evalToDest = EvalToDestAtCompileTime && alphaIsCompatible;
+
+ RhsScalar compatibleAlpha = get_factor<ResScalar,RhsScalar>::run(actualAlpha);
+
+ ei_declare_aligned_stack_constructed_variable(ResScalar,actualDestPtr,dest.size(),
+ evalToDest ? dest.data() : static_dest.data());
+
+ if(!evalToDest)
+ {
+ #ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN
+ int size = dest.size();
+ EIGEN_DENSE_STORAGE_CTOR_PLUGIN
+ #endif
+ if(!alphaIsCompatible)
+ {
+ MappedDest(actualDestPtr, dest.size()).setZero();
+ compatibleAlpha = RhsScalar(1);
+ }
+ else
+ MappedDest(actualDestPtr, dest.size()) = dest;
+ }
+
+ general_matrix_vector_product
+ <Index,LhsScalar,ColMajor,LhsBlasTraits::NeedToConjugate,RhsScalar,RhsBlasTraits::NeedToConjugate>::run(
+ actualLhs.rows(), actualLhs.cols(),
+ actualLhs.data(), actualLhs.outerStride(),
+ actualRhs.data(), actualRhs.innerStride(),
+ actualDestPtr, 1,
+ compatibleAlpha);
+
+ if (!evalToDest)
+ {
+ if(!alphaIsCompatible)
+ dest += actualAlpha * MappedDest(actualDestPtr, dest.size());
+ else
+ dest = MappedDest(actualDestPtr, dest.size());
+ }
+ }
+};
+
+template<> struct gemv_selector<OnTheRight,RowMajor,true>
+{
+ template<typename ProductType, typename Dest>
+ static void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha)
+ {
+ typedef typename ProductType::LhsScalar LhsScalar;
+ typedef typename ProductType::RhsScalar RhsScalar;
+ typedef typename ProductType::Scalar ResScalar;
+ typedef typename ProductType::Index Index;
+ typedef typename ProductType::ActualLhsType ActualLhsType;
+ typedef typename ProductType::ActualRhsType ActualRhsType;
+ typedef typename ProductType::_ActualRhsType _ActualRhsType;
+ typedef typename ProductType::LhsBlasTraits LhsBlasTraits;
+ typedef typename ProductType::RhsBlasTraits RhsBlasTraits;
+
+ typename add_const<ActualLhsType>::type actualLhs = LhsBlasTraits::extract(prod.lhs());
+ typename add_const<ActualRhsType>::type actualRhs = RhsBlasTraits::extract(prod.rhs());
+
+ ResScalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(prod.lhs())
+ * RhsBlasTraits::extractScalarFactor(prod.rhs());
+
+ enum {
+ // FIXME find a way to allow an inner stride on the result if packet_traits<Scalar>::size==1
+ // on, the other hand it is good for the cache to pack the vector anyways...
+ DirectlyUseRhs = _ActualRhsType::InnerStrideAtCompileTime==1
+ };
+
+ gemv_static_vector_if<RhsScalar,_ActualRhsType::SizeAtCompileTime,_ActualRhsType::MaxSizeAtCompileTime,!DirectlyUseRhs> static_rhs;
+
+ ei_declare_aligned_stack_constructed_variable(RhsScalar,actualRhsPtr,actualRhs.size(),
+ DirectlyUseRhs ? const_cast<RhsScalar*>(actualRhs.data()) : static_rhs.data());
+
+ if(!DirectlyUseRhs)
+ {
+ #ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN
+ int size = actualRhs.size();
+ EIGEN_DENSE_STORAGE_CTOR_PLUGIN
+ #endif
+ Map<typename _ActualRhsType::PlainObject>(actualRhsPtr, actualRhs.size()) = actualRhs;
+ }
+
+ general_matrix_vector_product
+ <Index,LhsScalar,RowMajor,LhsBlasTraits::NeedToConjugate,RhsScalar,RhsBlasTraits::NeedToConjugate>::run(
+ actualLhs.rows(), actualLhs.cols(),
+ actualLhs.data(), actualLhs.outerStride(),
+ actualRhsPtr, 1,
+ dest.data(), dest.innerStride(),
+ actualAlpha);
+ }
+};
+
+template<> struct gemv_selector<OnTheRight,ColMajor,false>
+{
+ template<typename ProductType, typename Dest>
+ static void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha)
+ {
+ typedef typename Dest::Index Index;
+ // TODO makes sure dest is sequentially stored in memory, otherwise use a temp
+ const Index size = prod.rhs().rows();
+ for(Index k=0; k<size; ++k)
+ dest += (alpha*prod.rhs().coeff(k)) * prod.lhs().col(k);
+ }
+};
+
+template<> struct gemv_selector<OnTheRight,RowMajor,false>
+{
+ template<typename ProductType, typename Dest>
+ static void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha)
+ {
+ typedef typename Dest::Index Index;
+ // TODO makes sure rhs is sequentially stored in memory, otherwise use a temp
+ const Index rows = prod.rows();
+ for(Index i=0; i<rows; ++i)
+ dest.coeffRef(i) += alpha * (prod.lhs().row(i).cwiseProduct(prod.rhs().transpose())).sum();
+ }
+};
+
+} // end namespace internal
+
+/***************************************************************************
+* Implementation of matrix base methods
+***************************************************************************/
+
+/** \returns the matrix product of \c *this and \a other.
+ *
+ * \note If instead of the matrix product you want the coefficient-wise product, see Cwise::operator*().
+ *
+ * \sa lazyProduct(), operator*=(const MatrixBase&), Cwise::operator*()
+ */
+template<typename Derived>
+template<typename OtherDerived>
+inline const typename ProductReturnType<Derived, OtherDerived>::Type
+MatrixBase<Derived>::operator*(const MatrixBase<OtherDerived> &other) const
+{
+ // A note regarding the function declaration: In MSVC, this function will sometimes
+ // not be inlined since DenseStorage is an unwindable object for dynamic
+ // matrices and product types are holding a member to store the result.
+ // Thus it does not help tagging this function with EIGEN_STRONG_INLINE.
+ enum {
+ ProductIsValid = Derived::ColsAtCompileTime==Dynamic
+ || OtherDerived::RowsAtCompileTime==Dynamic
+ || int(Derived::ColsAtCompileTime)==int(OtherDerived::RowsAtCompileTime),
+ AreVectors = Derived::IsVectorAtCompileTime && OtherDerived::IsVectorAtCompileTime,
+ SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(Derived,OtherDerived)
+ };
+ // note to the lost user:
+ // * for a dot product use: v1.dot(v2)
+ // * for a coeff-wise product use: v1.cwiseProduct(v2)
+ EIGEN_STATIC_ASSERT(ProductIsValid || !(AreVectors && SameSizes),
+ INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS)
+ EIGEN_STATIC_ASSERT(ProductIsValid || !(SameSizes && !AreVectors),
+ INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION)
+ EIGEN_STATIC_ASSERT(ProductIsValid || SameSizes, INVALID_MATRIX_PRODUCT)
+#ifdef EIGEN_DEBUG_PRODUCT
+ internal::product_type<Derived,OtherDerived>::debug();
+#endif
+ return typename ProductReturnType<Derived,OtherDerived>::Type(derived(), other.derived());
+}
+
+/** \returns an expression of the matrix product of \c *this and \a other without implicit evaluation.
+ *
+ * The returned product will behave like any other expressions: the coefficients of the product will be
+ * computed once at a time as requested. This might be useful in some extremely rare cases when only
+ * a small and no coherent fraction of the result's coefficients have to be computed.
+ *
+ * \warning This version of the matrix product can be much much slower. So use it only if you know
+ * what you are doing and that you measured a true speed improvement.
+ *
+ * \sa operator*(const MatrixBase&)
+ */
+template<typename Derived>
+template<typename OtherDerived>
+const typename LazyProductReturnType<Derived,OtherDerived>::Type
+MatrixBase<Derived>::lazyProduct(const MatrixBase<OtherDerived> &other) const
+{
+ enum {
+ ProductIsValid = Derived::ColsAtCompileTime==Dynamic
+ || OtherDerived::RowsAtCompileTime==Dynamic
+ || int(Derived::ColsAtCompileTime)==int(OtherDerived::RowsAtCompileTime),
+ AreVectors = Derived::IsVectorAtCompileTime && OtherDerived::IsVectorAtCompileTime,
+ SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(Derived,OtherDerived)
+ };
+ // note to the lost user:
+ // * for a dot product use: v1.dot(v2)
+ // * for a coeff-wise product use: v1.cwiseProduct(v2)
+ EIGEN_STATIC_ASSERT(ProductIsValid || !(AreVectors && SameSizes),
+ INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS)
+ EIGEN_STATIC_ASSERT(ProductIsValid || !(SameSizes && !AreVectors),
+ INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION)
+ EIGEN_STATIC_ASSERT(ProductIsValid || SameSizes, INVALID_MATRIX_PRODUCT)
+
+ return typename LazyProductReturnType<Derived,OtherDerived>::Type(derived(), other.derived());
+}
+
+} // end namespace Eigen
+
+#endif // EIGEN_PRODUCT_H
diff --git a/extern/Eigen3/Eigen/src/Core/GenericPacketMath.h b/extern/Eigen3/Eigen/src/Core/GenericPacketMath.h
index 8ed83532712..858fb243ec8 100644
--- a/extern/Eigen3/Eigen/src/Core/GenericPacketMath.h
+++ b/extern/Eigen3/Eigen/src/Core/GenericPacketMath.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GENERIC_PACKET_MATH_H
#define EIGEN_GENERIC_PACKET_MATH_H
+namespace Eigen {
+
namespace internal {
/** \internal
@@ -312,7 +299,7 @@ template<int Offset,typename PacketType>
struct palign_impl
{
// by default data are aligned, so there is nothing to be done :)
- inline static void run(PacketType&, const PacketType&) {}
+ static inline void run(PacketType&, const PacketType&) {}
};
/** \internal update \a first using the concatenation of the \a Offset last elements
@@ -335,5 +322,7 @@ template<> inline std::complex<double> pmul(const std::complex<double>& a, const
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_GENERIC_PACKET_MATH_H
diff --git a/extern/Eigen3/Eigen/src/Core/GlobalFunctions.h b/extern/Eigen3/Eigen/src/Core/GlobalFunctions.h
index 144145a955c..e63726c4735 100644
--- a/extern/Eigen3/Eigen/src/Core/GlobalFunctions.h
+++ b/extern/Eigen3/Eigen/src/Core/GlobalFunctions.h
@@ -4,24 +4,9 @@
// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GLOBAL_FUNCTIONS_H
#define EIGEN_GLOBAL_FUNCTIONS_H
@@ -66,13 +51,36 @@ namespace std
template<typename Derived>
inline const Eigen::CwiseUnaryOp<Eigen::internal::scalar_pow_op<typename Derived::Scalar>, const Derived>
- pow(const Eigen::ArrayBase<Derived>& x, const typename Derived::Scalar& exponent) { \
- return x.derived().pow(exponent); \
+ pow(const Eigen::ArrayBase<Derived>& x, const typename Derived::Scalar& exponent) {
+ return x.derived().pow(exponent);
+ }
+
+ template<typename Derived>
+ inline const Eigen::CwiseBinaryOp<Eigen::internal::scalar_binary_pow_op<typename Derived::Scalar, typename Derived::Scalar>, const Derived, const Derived>
+ pow(const Eigen::ArrayBase<Derived>& x, const Eigen::ArrayBase<Derived>& exponents)
+ {
+ return Eigen::CwiseBinaryOp<Eigen::internal::scalar_binary_pow_op<typename Derived::Scalar, typename Derived::Scalar>, const Derived, const Derived>(
+ x.derived(),
+ exponents.derived()
+ );
}
}
namespace Eigen
{
+ /**
+ * \brief Component-wise division of a scalar by array elements.
+ **/
+ template <typename Derived>
+ inline const Eigen::CwiseUnaryOp<Eigen::internal::scalar_inverse_mult_op<typename Derived::Scalar>, const Derived>
+ operator/(typename Derived::Scalar s, const Eigen::ArrayBase<Derived>& a)
+ {
+ return Eigen::CwiseUnaryOp<Eigen::internal::scalar_inverse_mult_op<typename Derived::Scalar>, const Derived>(
+ a.derived(),
+ Eigen::internal::scalar_inverse_mult_op<typename Derived::Scalar>(s)
+ );
+ }
+
namespace internal
{
EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(real,scalar_real_op)
diff --git a/extern/Eigen3/Eigen/src/Core/IO.h b/extern/Eigen3/Eigen/src/Core/IO.h
index f3cfcdbf4a3..cc8e18a0076 100644
--- a/extern/Eigen3/Eigen/src/Core/IO.h
+++ b/extern/Eigen3/Eigen/src/Core/IO.h
@@ -4,28 +4,15 @@
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_IO_H
#define EIGEN_IO_H
+namespace Eigen {
+
enum { DontAlignCols = 1 };
enum { StreamPrecision = -1,
FullPrecision = -2 };
@@ -171,7 +158,7 @@ std::ostream & print_matrix(std::ostream & s, const Derived& _m, const IOFormat&
return s;
}
- const typename Derived::Nested m = _m;
+ typename Derived::Nested m = _m;
typedef typename Derived::Scalar Scalar;
typedef typename Derived::Index Index;
@@ -257,4 +244,6 @@ std::ostream & operator <<
return internal::print_matrix(s, m.eval(), EIGEN_DEFAULT_IO_FORMAT);
}
+} // end namespace Eigen
+
#endif // EIGEN_IO_H
diff --git a/extern/Eigen3/Eigen/src/Core/Map.h b/extern/Eigen3/Eigen/src/Core/Map.h
index 2bf80b3af3d..15a19226e29 100644
--- a/extern/Eigen3/Eigen/src/Core/Map.h
+++ b/extern/Eigen3/Eigen/src/Core/Map.h
@@ -4,28 +4,15 @@
// Copyright (C) 2007-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MAP_H
#define EIGEN_MAP_H
+namespace Eigen {
+
/** \class Map
* \ingroup Core_Module
*
@@ -200,4 +187,6 @@ inline Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>
this->_set_noalias(Eigen::Map<const Matrix>(data));
}
+} // end namespace Eigen
+
#endif // EIGEN_MAP_H
diff --git a/extern/Eigen3/Eigen/src/Core/MapBase.h b/extern/Eigen3/Eigen/src/Core/MapBase.h
index 9426e2d24dd..a388d61ea92 100644
--- a/extern/Eigen3/Eigen/src/Core/MapBase.h
+++ b/extern/Eigen3/Eigen/src/Core/MapBase.h
@@ -4,24 +4,9 @@
// Copyright (C) 2007-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MAPBASE_H
#define EIGEN_MAPBASE_H
@@ -30,6 +15,7 @@
EIGEN_STATIC_ASSERT((int(internal::traits<Derived>::Flags) & LinearAccessBit) || Derived::IsVectorAtCompileTime, \
YOU_ARE_TRYING_TO_USE_AN_INDEX_BASED_ACCESSOR_ON_AN_EXPRESSION_THAT_DOES_NOT_SUPPORT_THAT)
+namespace Eigen {
/** \class MapBase
* \ingroup Core_Module
@@ -251,5 +237,6 @@ template<typename Derived> class MapBase<Derived, WriteAccessors>
using Base::Base::operator=;
};
+} // end namespace Eigen
#endif // EIGEN_MAPBASE_H
diff --git a/extern/Eigen3/Eigen/src/Core/MathFunctions.h b/extern/Eigen3/Eigen/src/Core/MathFunctions.h
index 2b454db21e9..05e913f2fec 100644
--- a/extern/Eigen3/Eigen/src/Core/MathFunctions.h
+++ b/extern/Eigen3/Eigen/src/Core/MathFunctions.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MATHFUNCTIONS_H
#define EIGEN_MATHFUNCTIONS_H
+namespace Eigen {
+
namespace internal {
/** \internal \struct global_math_functions_filtering_base
@@ -309,8 +296,7 @@ struct abs2_impl<std::complex<RealScalar> >
{
static inline RealScalar run(const std::complex<RealScalar>& x)
{
- using std::norm;
- return norm(x);
+ return real(x)*real(x) + imag(x)*imag(x);
}
};
@@ -553,7 +539,7 @@ struct pow_default_impl<Scalar, true>
{
static inline Scalar run(Scalar x, Scalar y)
{
- Scalar res = 1;
+ Scalar res(1);
eigen_assert(!NumTraits<Scalar>::IsSigned || y >= 0);
if(y & 1) res *= x;
y >>= 1;
@@ -838,6 +824,19 @@ template<> struct scalar_fuzzy_impl<bool>
};
+/****************************************************************************
+* Special functions *
+****************************************************************************/
+
+// std::isfinite is non standard, so let's define our own version,
+// even though it is not very efficient.
+template<typename T> bool (isfinite)(const T& x)
+{
+ return x<NumTraits<T>::highest() && x>NumTraits<T>::lowest();
+}
+
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_MATHFUNCTIONS_H
diff --git a/extern/Eigen3/Eigen/src/Core/Matrix.h b/extern/Eigen3/Eigen/src/Core/Matrix.h
index 982c9256af0..99160b591b0 100644
--- a/extern/Eigen3/Eigen/src/Core/Matrix.h
+++ b/extern/Eigen3/Eigen/src/Core/Matrix.h
@@ -4,28 +4,15 @@
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MATRIX_H
#define EIGEN_MATRIX_H
+namespace Eigen {
+
/** \class Matrix
* \ingroup Core_Module
*
@@ -411,25 +398,8 @@ EIGEN_MAKE_TYPEDEFS_ALL_SIZES(std::complex<double>, cd)
#undef EIGEN_MAKE_TYPEDEFS_ALL_SIZES
#undef EIGEN_MAKE_TYPEDEFS
+#undef EIGEN_MAKE_FIXED_TYPEDEFS
-#undef EIGEN_MAKE_TYPEDEFS_LARGE
-
-#define EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, SizeSuffix) \
-using Eigen::Matrix##SizeSuffix##TypeSuffix; \
-using Eigen::Vector##SizeSuffix##TypeSuffix; \
-using Eigen::RowVector##SizeSuffix##TypeSuffix;
-
-#define EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(TypeSuffix) \
-EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 2) \
-EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 3) \
-EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 4) \
-EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, X) \
-
-#define EIGEN_USING_MATRIX_TYPEDEFS \
-EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(i) \
-EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(f) \
-EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(d) \
-EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(cf) \
-EIGEN_USING_MATRIX_TYPEDEFS_FOR_TYPE(cd)
+} // end namespace Eigen
#endif // EIGEN_MATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Core/MatrixBase.h b/extern/Eigen3/Eigen/src/Core/MatrixBase.h
index 62877bce09e..c1e0ed132cc 100644
--- a/extern/Eigen3/Eigen/src/Core/MatrixBase.h
+++ b/extern/Eigen3/Eigen/src/Core/MatrixBase.h
@@ -4,28 +4,15 @@
// Copyright (C) 2006-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MATRIXBASE_H
#define EIGEN_MATRIXBASE_H
+namespace Eigen {
+
/** \class MatrixBase
* \ingroup Core_Module
*
@@ -250,8 +237,7 @@ template<typename Derived> class MatrixBase
// huuuge hack. make Eigen2's matrix.part<Diagonal>() work in eigen3. Problem: Diagonal is now a class template instead
// of an integer constant. Solution: overload the part() method template wrt template parameters list.
- // Note: replacing next line by "template<template<typename T, int n> class U>" produces a mysterious error C2082 in MSVC.
- template<template<typename, int> class U>
+ template<template<typename T, int n> class U>
const DiagonalWrapper<ConstDiagonalReturnType> part() const
{ return diagonal().asDiagonal(); }
#endif // EIGEN2_SUPPORT
@@ -331,7 +317,7 @@ template<typename Derived> class MatrixBase
/** \returns an \link ArrayBase Array \endlink expression of this matrix
* \sa ArrayBase::matrix() */
ArrayWrapper<Derived> array() { return derived(); }
- const ArrayWrapper<Derived> array() const { return derived(); }
+ const ArrayWrapper<const Derived> array() const { return derived(); }
/////////// LU module ///////////
@@ -466,6 +452,8 @@ template<typename Derived> class MatrixBase
const MatrixFunctionReturnValue<Derived> sinh() const;
const MatrixFunctionReturnValue<Derived> cos() const;
const MatrixFunctionReturnValue<Derived> sin() const;
+ const MatrixSquareRootReturnValue<Derived> sqrt() const;
+ const MatrixLogarithmReturnValue<Derived> log() const;
#ifdef EIGEN2_SUPPORT
template<typename ProductDerived, typename Lhs, typename Rhs>
@@ -512,10 +500,12 @@ template<typename Derived> class MatrixBase
protected:
// mixing arrays and matrices is not legal
template<typename OtherDerived> Derived& operator+=(const ArrayBase<OtherDerived>& )
- {EIGEN_STATIC_ASSERT(sizeof(typename OtherDerived::Scalar)==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES);}
+ {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;}
// mixing arrays and matrices is not legal
template<typename OtherDerived> Derived& operator-=(const ArrayBase<OtherDerived>& )
- {EIGEN_STATIC_ASSERT(sizeof(typename OtherDerived::Scalar)==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES);}
+ {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;}
};
+} // end namespace Eigen
+
#endif // EIGEN_MATRIXBASE_H
diff --git a/extern/Eigen3/Eigen/src/Core/NestByValue.h b/extern/Eigen3/Eigen/src/Core/NestByValue.h
index a6104d2a426..a893b1761b5 100644
--- a/extern/Eigen3/Eigen/src/Core/NestByValue.h
+++ b/extern/Eigen3/Eigen/src/Core/NestByValue.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_NESTBYVALUE_H
#define EIGEN_NESTBYVALUE_H
+namespace Eigen {
+
/** \class NestByValue
* \ingroup Core_Module
*
@@ -119,4 +106,6 @@ DenseBase<Derived>::nestByValue() const
return NestByValue<Derived>(derived());
}
+} // end namespace Eigen
+
#endif // EIGEN_NESTBYVALUE_H
diff --git a/extern/Eigen3/Eigen/src/Core/NoAlias.h b/extern/Eigen3/Eigen/src/Core/NoAlias.h
index da64affcf9a..ecb3fa2850e 100644
--- a/extern/Eigen3/Eigen/src/Core/NoAlias.h
+++ b/extern/Eigen3/Eigen/src/Core/NoAlias.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_NOALIAS_H
#define EIGEN_NOALIAS_H
+namespace Eigen {
+
/** \class NoAlias
* \ingroup Core_Module
*
@@ -133,4 +120,6 @@ NoAlias<Derived,MatrixBase> MatrixBase<Derived>::noalias()
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_NOALIAS_H
diff --git a/extern/Eigen3/Eigen/src/Core/NumTraits.h b/extern/Eigen3/Eigen/src/Core/NumTraits.h
index 73ef05dfe7a..c94ef026b42 100644
--- a/extern/Eigen3/Eigen/src/Core/NumTraits.h
+++ b/extern/Eigen3/Eigen/src/Core/NumTraits.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_NUMTRAITS_H
#define EIGEN_NUMTRAITS_H
+namespace Eigen {
+
/** \class NumTraits
* \ingroup Core_Module
*
@@ -81,14 +68,14 @@ template<typename T> struct GenericNumTraits
>::type NonInteger;
typedef T Nested;
- inline static Real epsilon() { return std::numeric_limits<T>::epsilon(); }
- inline static Real dummy_precision()
+ static inline Real epsilon() { return std::numeric_limits<T>::epsilon(); }
+ static inline Real dummy_precision()
{
// make sure to override this for floating-point types
return Real(0);
}
- inline static T highest() { return (std::numeric_limits<T>::max)(); }
- inline static T lowest() { return IsInteger ? (std::numeric_limits<T>::min)() : (-(std::numeric_limits<T>::max)()); }
+ static inline T highest() { return (std::numeric_limits<T>::max)(); }
+ static inline T lowest() { return IsInteger ? (std::numeric_limits<T>::min)() : (-(std::numeric_limits<T>::max)()); }
#ifdef EIGEN2_SUPPORT
enum {
@@ -104,12 +91,12 @@ template<typename T> struct NumTraits : GenericNumTraits<T>
template<> struct NumTraits<float>
: GenericNumTraits<float>
{
- inline static float dummy_precision() { return 1e-5f; }
+ static inline float dummy_precision() { return 1e-5f; }
};
template<> struct NumTraits<double> : GenericNumTraits<double>
{
- inline static double dummy_precision() { return 1e-12; }
+ static inline double dummy_precision() { return 1e-12; }
};
template<> struct NumTraits<long double>
@@ -130,8 +117,8 @@ template<typename _Real> struct NumTraits<std::complex<_Real> >
MulCost = 4 * NumTraits<Real>::MulCost + 2 * NumTraits<Real>::AddCost
};
- inline static Real epsilon() { return NumTraits<Real>::epsilon(); }
- inline static Real dummy_precision() { return NumTraits<Real>::dummy_precision(); }
+ static inline Real epsilon() { return NumTraits<Real>::epsilon(); }
+ static inline Real dummy_precision() { return NumTraits<Real>::dummy_precision(); }
};
template<typename Scalar, int Rows, int Cols, int Options, int MaxRows, int MaxCols>
@@ -155,6 +142,6 @@ struct NumTraits<Array<Scalar, Rows, Cols, Options, MaxRows, MaxCols> >
};
};
-
+} // end namespace Eigen
#endif // EIGEN_NUMTRAITS_H
diff --git a/extern/Eigen3/Eigen/src/Core/PermutationMatrix.h b/extern/Eigen3/Eigen/src/Core/PermutationMatrix.h
index a064e053e51..bc29f814205 100644
--- a/extern/Eigen3/Eigen/src/Core/PermutationMatrix.h
+++ b/extern/Eigen3/Eigen/src/Core/PermutationMatrix.h
@@ -4,28 +4,15 @@
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2009-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PERMUTATIONMATRIX_H
#define EIGEN_PERMUTATIONMATRIX_H
+namespace Eigen {
+
template<int RowCol,typename IndicesType,typename MatrixType, typename StorageKind> class PermutedImpl;
/** \class PermutationBase
@@ -56,6 +43,8 @@ namespace internal {
template<typename PermutationType, typename MatrixType, int Side, bool Transposed=false>
struct permut_matrix_product_retval;
+template<typename PermutationType, typename MatrixType, int Side, bool Transposed=false>
+struct permut_sparsematrix_product_retval;
enum PermPermProduct_t {PermPermProduct};
} // end namespace internal
@@ -511,7 +500,7 @@ class PermutationWrapper : public PermutationBase<PermutationWrapper<_IndicesTyp
protected:
- const typename IndicesType::Nested m_indices;
+ typename IndicesType::Nested m_indices;
};
/** \returns the matrix with the permutation applied to the columns.
@@ -608,7 +597,7 @@ struct permut_matrix_product_retval
protected:
const PermutationType& m_permutation;
- const typename MatrixType::Nested m_matrix;
+ typename MatrixType::Nested m_matrix;
};
/* Template partial specialization for transposed/inverse permutations */
@@ -693,4 +682,6 @@ const PermutationWrapper<const Derived> MatrixBase<Derived>::asPermutation() con
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_PERMUTATIONMATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Core/PlainObjectBase.h b/extern/Eigen3/Eigen/src/Core/PlainObjectBase.h
index 612254e9da9..71c74309acc 100644
--- a/extern/Eigen3/Eigen/src/Core/PlainObjectBase.h
+++ b/extern/Eigen3/Eigen/src/Core/PlainObjectBase.h
@@ -4,24 +4,9 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DENSESTORAGEBASE_H
#define EIGEN_DENSESTORAGEBASE_H
@@ -32,6 +17,8 @@
# define EIGEN_INITIALIZE_BY_ZERO_IF_THAT_OPTION_IS_ENABLED
#endif
+namespace Eigen {
+
namespace internal {
template<typename Index>
@@ -47,13 +34,13 @@ EIGEN_ALWAYS_INLINE void check_rows_cols_for_overflow(Index rows, Index cols)
throw_std_bad_alloc();
}
-template <typename Derived, typename OtherDerived = Derived, bool IsVector = static_cast<bool>(Derived::IsVectorAtCompileTime)> struct conservative_resize_like_impl;
+template <typename Derived, typename OtherDerived = Derived, bool IsVector = bool(Derived::IsVectorAtCompileTime)> struct conservative_resize_like_impl;
template<typename MatrixTypeA, typename MatrixTypeB, bool SwapPointers> struct matrix_swap_impl;
} // end namespace internal
-/**
+/** \class PlainObjectBase
* \brief %Dense storage base class for matrices and arrays.
*
* This class can be extended with the help of the plugin mechanism described on the page
@@ -61,8 +48,29 @@ template<typename MatrixTypeA, typename MatrixTypeB, bool SwapPointers> struct m
*
* \sa \ref TopicClassHierarchy
*/
+#ifdef EIGEN_PARSED_BY_DOXYGEN
+namespace internal {
+
+// this is a warkaround to doxygen not being able to understand the inheritence logic
+// when it is hidden by the dense_xpr_base helper struct.
+template<typename Derived> struct dense_xpr_base_dispatcher_for_doxygen;// : public MatrixBase<Derived> {};
+/** This class is just a workaround for Doxygen and it does not not actually exist. */
+template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
+struct dense_xpr_base_dispatcher_for_doxygen<Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> >
+ : public MatrixBase<Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> > {};
+/** This class is just a workaround for Doxygen and it does not not actually exist. */
+template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
+struct dense_xpr_base_dispatcher_for_doxygen<Array<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> >
+ : public ArrayBase<Array<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> > {};
+
+} // namespace internal
+
+template<typename Derived>
+class PlainObjectBase : public internal::dense_xpr_base_dispatcher_for_doxygen<Derived>
+#else
template<typename Derived>
class PlainObjectBase : public internal::dense_xpr_base<Derived>::type
+#endif
{
public:
enum { Options = internal::traits<Derived>::Options };
@@ -443,68 +451,68 @@ class PlainObjectBase : public internal::dense_xpr_base<Derived>::type
* \see class Map
*/
//@{
- inline static ConstMapType Map(const Scalar* data)
+ static inline ConstMapType Map(const Scalar* data)
{ return ConstMapType(data); }
- inline static MapType Map(Scalar* data)
+ static inline MapType Map(Scalar* data)
{ return MapType(data); }
- inline static ConstMapType Map(const Scalar* data, Index size)
+ static inline ConstMapType Map(const Scalar* data, Index size)
{ return ConstMapType(data, size); }
- inline static MapType Map(Scalar* data, Index size)
+ static inline MapType Map(Scalar* data, Index size)
{ return MapType(data, size); }
- inline static ConstMapType Map(const Scalar* data, Index rows, Index cols)
+ static inline ConstMapType Map(const Scalar* data, Index rows, Index cols)
{ return ConstMapType(data, rows, cols); }
- inline static MapType Map(Scalar* data, Index rows, Index cols)
+ static inline MapType Map(Scalar* data, Index rows, Index cols)
{ return MapType(data, rows, cols); }
- inline static ConstAlignedMapType MapAligned(const Scalar* data)
+ static inline ConstAlignedMapType MapAligned(const Scalar* data)
{ return ConstAlignedMapType(data); }
- inline static AlignedMapType MapAligned(Scalar* data)
+ static inline AlignedMapType MapAligned(Scalar* data)
{ return AlignedMapType(data); }
- inline static ConstAlignedMapType MapAligned(const Scalar* data, Index size)
+ static inline ConstAlignedMapType MapAligned(const Scalar* data, Index size)
{ return ConstAlignedMapType(data, size); }
- inline static AlignedMapType MapAligned(Scalar* data, Index size)
+ static inline AlignedMapType MapAligned(Scalar* data, Index size)
{ return AlignedMapType(data, size); }
- inline static ConstAlignedMapType MapAligned(const Scalar* data, Index rows, Index cols)
+ static inline ConstAlignedMapType MapAligned(const Scalar* data, Index rows, Index cols)
{ return ConstAlignedMapType(data, rows, cols); }
- inline static AlignedMapType MapAligned(Scalar* data, Index rows, Index cols)
+ static inline AlignedMapType MapAligned(Scalar* data, Index rows, Index cols)
{ return AlignedMapType(data, rows, cols); }
template<int Outer, int Inner>
- inline static typename StridedConstMapType<Stride<Outer, Inner> >::type Map(const Scalar* data, const Stride<Outer, Inner>& stride)
+ static inline typename StridedConstMapType<Stride<Outer, Inner> >::type Map(const Scalar* data, const Stride<Outer, Inner>& stride)
{ return typename StridedConstMapType<Stride<Outer, Inner> >::type(data, stride); }
template<int Outer, int Inner>
- inline static typename StridedMapType<Stride<Outer, Inner> >::type Map(Scalar* data, const Stride<Outer, Inner>& stride)
+ static inline typename StridedMapType<Stride<Outer, Inner> >::type Map(Scalar* data, const Stride<Outer, Inner>& stride)
{ return typename StridedMapType<Stride<Outer, Inner> >::type(data, stride); }
template<int Outer, int Inner>
- inline static typename StridedConstMapType<Stride<Outer, Inner> >::type Map(const Scalar* data, Index size, const Stride<Outer, Inner>& stride)
+ static inline typename StridedConstMapType<Stride<Outer, Inner> >::type Map(const Scalar* data, Index size, const Stride<Outer, Inner>& stride)
{ return typename StridedConstMapType<Stride<Outer, Inner> >::type(data, size, stride); }
template<int Outer, int Inner>
- inline static typename StridedMapType<Stride<Outer, Inner> >::type Map(Scalar* data, Index size, const Stride<Outer, Inner>& stride)
+ static inline typename StridedMapType<Stride<Outer, Inner> >::type Map(Scalar* data, Index size, const Stride<Outer, Inner>& stride)
{ return typename StridedMapType<Stride<Outer, Inner> >::type(data, size, stride); }
template<int Outer, int Inner>
- inline static typename StridedConstMapType<Stride<Outer, Inner> >::type Map(const Scalar* data, Index rows, Index cols, const Stride<Outer, Inner>& stride)
+ static inline typename StridedConstMapType<Stride<Outer, Inner> >::type Map(const Scalar* data, Index rows, Index cols, const Stride<Outer, Inner>& stride)
{ return typename StridedConstMapType<Stride<Outer, Inner> >::type(data, rows, cols, stride); }
template<int Outer, int Inner>
- inline static typename StridedMapType<Stride<Outer, Inner> >::type Map(Scalar* data, Index rows, Index cols, const Stride<Outer, Inner>& stride)
+ static inline typename StridedMapType<Stride<Outer, Inner> >::type Map(Scalar* data, Index rows, Index cols, const Stride<Outer, Inner>& stride)
{ return typename StridedMapType<Stride<Outer, Inner> >::type(data, rows, cols, stride); }
template<int Outer, int Inner>
- inline static typename StridedConstAlignedMapType<Stride<Outer, Inner> >::type MapAligned(const Scalar* data, const Stride<Outer, Inner>& stride)
+ static inline typename StridedConstAlignedMapType<Stride<Outer, Inner> >::type MapAligned(const Scalar* data, const Stride<Outer, Inner>& stride)
{ return typename StridedConstAlignedMapType<Stride<Outer, Inner> >::type(data, stride); }
template<int Outer, int Inner>
- inline static typename StridedAlignedMapType<Stride<Outer, Inner> >::type MapAligned(Scalar* data, const Stride<Outer, Inner>& stride)
+ static inline typename StridedAlignedMapType<Stride<Outer, Inner> >::type MapAligned(Scalar* data, const Stride<Outer, Inner>& stride)
{ return typename StridedAlignedMapType<Stride<Outer, Inner> >::type(data, stride); }
template<int Outer, int Inner>
- inline static typename StridedConstAlignedMapType<Stride<Outer, Inner> >::type MapAligned(const Scalar* data, Index size, const Stride<Outer, Inner>& stride)
+ static inline typename StridedConstAlignedMapType<Stride<Outer, Inner> >::type MapAligned(const Scalar* data, Index size, const Stride<Outer, Inner>& stride)
{ return typename StridedConstAlignedMapType<Stride<Outer, Inner> >::type(data, size, stride); }
template<int Outer, int Inner>
- inline static typename StridedAlignedMapType<Stride<Outer, Inner> >::type MapAligned(Scalar* data, Index size, const Stride<Outer, Inner>& stride)
+ static inline typename StridedAlignedMapType<Stride<Outer, Inner> >::type MapAligned(Scalar* data, Index size, const Stride<Outer, Inner>& stride)
{ return typename StridedAlignedMapType<Stride<Outer, Inner> >::type(data, size, stride); }
template<int Outer, int Inner>
- inline static typename StridedConstAlignedMapType<Stride<Outer, Inner> >::type MapAligned(const Scalar* data, Index rows, Index cols, const Stride<Outer, Inner>& stride)
+ static inline typename StridedConstAlignedMapType<Stride<Outer, Inner> >::type MapAligned(const Scalar* data, Index rows, Index cols, const Stride<Outer, Inner>& stride)
{ return typename StridedConstAlignedMapType<Stride<Outer, Inner> >::type(data, rows, cols, stride); }
template<int Outer, int Inner>
- inline static typename StridedAlignedMapType<Stride<Outer, Inner> >::type MapAligned(Scalar* data, Index rows, Index cols, const Stride<Outer, Inner>& stride)
+ static inline typename StridedAlignedMapType<Stride<Outer, Inner> >::type MapAligned(Scalar* data, Index rows, Index cols, const Stride<Outer, Inner>& stride)
{ return typename StridedAlignedMapType<Stride<Outer, Inner> >::type(data, rows, cols, stride); }
//@}
@@ -594,6 +602,9 @@ class PlainObjectBase : public internal::dense_xpr_base<Derived>::type
template<typename T0, typename T1>
EIGEN_STRONG_INLINE void _init2(Index rows, Index cols, typename internal::enable_if<Base::SizeAtCompileTime!=2,T0>::type* = 0)
{
+ EIGEN_STATIC_ASSERT(bool(NumTraits<T0>::IsInteger) &&
+ bool(NumTraits<T1>::IsInteger),
+ FLOATING_POINT_ARGUMENT_PASSED__INTEGER_WAS_EXPECTED)
eigen_assert(rows >= 0 && (RowsAtCompileTime == Dynamic || RowsAtCompileTime == rows)
&& cols >= 0 && (ColsAtCompileTime == Dynamic || ColsAtCompileTime == cols));
internal::check_rows_cols_for_overflow(rows, cols);
@@ -623,7 +634,7 @@ class PlainObjectBase : public internal::dense_xpr_base<Derived>::type
public:
#ifndef EIGEN_PARSED_BY_DOXYGEN
- EIGEN_STRONG_INLINE static void _check_template_params()
+ static EIGEN_STRONG_INLINE void _check_template_params()
{
EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, (Options&RowMajor)==RowMajor)
&& EIGEN_IMPLIES(MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1, (Options&RowMajor)==0)
@@ -751,4 +762,6 @@ struct matrix_swap_impl<MatrixTypeA, MatrixTypeB, true>
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_DENSESTORAGEBASE_H
diff --git a/extern/Eigen3/Eigen/src/Core/Product.h b/extern/Eigen3/Eigen/src/Core/Product.h
index e2035b242b1..30aa8943b4c 100644
--- a/extern/Eigen3/Eigen/src/Core/Product.h
+++ b/extern/Eigen3/Eigen/src/Core/Product.h
@@ -1,625 +1,98 @@
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
-// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
-// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
+// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PRODUCT_H
#define EIGEN_PRODUCT_H
-/** \class GeneralProduct
+template<typename Lhs, typename Rhs> class Product;
+template<typename Lhs, typename Rhs, typename StorageKind> class ProductImpl;
+
+/** \class Product
* \ingroup Core_Module
*
- * \brief Expression of the product of two general matrices or vectors
+ * \brief Expression of the product of two arbitrary matrices or vectors
*
- * \param LhsNested the type used to store the left-hand side
- * \param RhsNested the type used to store the right-hand side
- * \param ProductMode the type of the product
+ * \param Lhs the type of the left-hand side expression
+ * \param Rhs the type of the right-hand side expression
*
- * This class represents an expression of the product of two general matrices.
- * We call a general matrix, a dense matrix with full storage. For instance,
- * This excludes triangular, selfadjoint, and sparse matrices.
- * It is the return type of the operator* between general matrices. Its template
- * arguments are determined automatically by ProductReturnType. Therefore,
- * GeneralProduct should never be used direclty. To determine the result type of a
- * function which involves a matrix product, use ProductReturnType::Type.
+ * This class represents an expression of the product of two arbitrary matrices.
*
- * \sa ProductReturnType, MatrixBase::operator*(const MatrixBase<OtherDerived>&)
*/
-template<typename Lhs, typename Rhs, int ProductType = internal::product_type<Lhs,Rhs>::value>
-class GeneralProduct;
-
-enum {
- Large = 2,
- Small = 3
-};
namespace internal {
-
-template<int Rows, int Cols, int Depth> struct product_type_selector;
-
-template<int Size, int MaxSize> struct product_size_category
-{
- enum { is_large = MaxSize == Dynamic ||
- Size >= EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD,
- value = is_large ? Large
- : Size == 1 ? 1
- : Small
- };
-};
-
-template<typename Lhs, typename Rhs> struct product_type
-{
- typedef typename remove_all<Lhs>::type _Lhs;
- typedef typename remove_all<Rhs>::type _Rhs;
- enum {
- MaxRows = _Lhs::MaxRowsAtCompileTime,
- Rows = _Lhs::RowsAtCompileTime,
- MaxCols = _Rhs::MaxColsAtCompileTime,
- Cols = _Rhs::ColsAtCompileTime,
- MaxDepth = EIGEN_SIZE_MIN_PREFER_FIXED(_Lhs::MaxColsAtCompileTime,
- _Rhs::MaxRowsAtCompileTime),
- Depth = EIGEN_SIZE_MIN_PREFER_FIXED(_Lhs::ColsAtCompileTime,
- _Rhs::RowsAtCompileTime),
- LargeThreshold = EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD
- };
-
- // the splitting into different lines of code here, introducing the _select enums and the typedef below,
- // is to work around an internal compiler error with gcc 4.1 and 4.2.
-private:
- enum {
- rows_select = product_size_category<Rows,MaxRows>::value,
- cols_select = product_size_category<Cols,MaxCols>::value,
- depth_select = product_size_category<Depth,MaxDepth>::value
- };
- typedef product_type_selector<rows_select, cols_select, depth_select> selector;
-
-public:
+template<typename Lhs, typename Rhs>
+struct traits<Product<Lhs, Rhs> >
+{
+ typedef MatrixXpr XprKind;
+ typedef typename remove_all<Lhs>::type LhsCleaned;
+ typedef typename remove_all<Rhs>::type RhsCleaned;
+ typedef typename scalar_product_traits<typename traits<LhsCleaned>::Scalar, typename traits<RhsCleaned>::Scalar>::ReturnType Scalar;
+ typedef typename promote_storage_type<typename traits<LhsCleaned>::StorageKind,
+ typename traits<RhsCleaned>::StorageKind>::ret StorageKind;
+ typedef typename promote_index_type<typename traits<LhsCleaned>::Index,
+ typename traits<RhsCleaned>::Index>::type Index;
enum {
- value = selector::ret
+ RowsAtCompileTime = LhsCleaned::RowsAtCompileTime,
+ ColsAtCompileTime = RhsCleaned::ColsAtCompileTime,
+ MaxRowsAtCompileTime = LhsCleaned::MaxRowsAtCompileTime,
+ MaxColsAtCompileTime = RhsCleaned::MaxColsAtCompileTime,
+ Flags = (MaxRowsAtCompileTime==1 ? RowMajorBit : 0), // TODO should be no storage order
+ CoeffReadCost = 0 // TODO CoeffReadCost should not be part of the expression traits
};
-#ifdef EIGEN_DEBUG_PRODUCT
- static void debug()
- {
- EIGEN_DEBUG_VAR(Rows);
- EIGEN_DEBUG_VAR(Cols);
- EIGEN_DEBUG_VAR(Depth);
- EIGEN_DEBUG_VAR(rows_select);
- EIGEN_DEBUG_VAR(cols_select);
- EIGEN_DEBUG_VAR(depth_select);
- EIGEN_DEBUG_VAR(value);
- }
-#endif
};
-
-
-/* The following allows to select the kind of product at compile time
- * based on the three dimensions of the product.
- * This is a compile time mapping from {1,Small,Large}^3 -> {product types} */
-// FIXME I'm not sure the current mapping is the ideal one.
-template<int M, int N> struct product_type_selector<M,N,1> { enum { ret = OuterProduct }; };
-template<int Depth> struct product_type_selector<1, 1, Depth> { enum { ret = InnerProduct }; };
-template<> struct product_type_selector<1, 1, 1> { enum { ret = InnerProduct }; };
-template<> struct product_type_selector<Small,1, Small> { enum { ret = CoeffBasedProductMode }; };
-template<> struct product_type_selector<1, Small,Small> { enum { ret = CoeffBasedProductMode }; };
-template<> struct product_type_selector<Small,Small,Small> { enum { ret = CoeffBasedProductMode }; };
-template<> struct product_type_selector<Small, Small, 1> { enum { ret = LazyCoeffBasedProductMode }; };
-template<> struct product_type_selector<Small, Large, 1> { enum { ret = LazyCoeffBasedProductMode }; };
-template<> struct product_type_selector<Large, Small, 1> { enum { ret = LazyCoeffBasedProductMode }; };
-template<> struct product_type_selector<1, Large,Small> { enum { ret = CoeffBasedProductMode }; };
-template<> struct product_type_selector<1, Large,Large> { enum { ret = GemvProduct }; };
-template<> struct product_type_selector<1, Small,Large> { enum { ret = CoeffBasedProductMode }; };
-template<> struct product_type_selector<Large,1, Small> { enum { ret = CoeffBasedProductMode }; };
-template<> struct product_type_selector<Large,1, Large> { enum { ret = GemvProduct }; };
-template<> struct product_type_selector<Small,1, Large> { enum { ret = CoeffBasedProductMode }; };
-template<> struct product_type_selector<Small,Small,Large> { enum { ret = GemmProduct }; };
-template<> struct product_type_selector<Large,Small,Large> { enum { ret = GemmProduct }; };
-template<> struct product_type_selector<Small,Large,Large> { enum { ret = GemmProduct }; };
-template<> struct product_type_selector<Large,Large,Large> { enum { ret = GemmProduct }; };
-template<> struct product_type_selector<Large,Small,Small> { enum { ret = GemmProduct }; };
-template<> struct product_type_selector<Small,Large,Small> { enum { ret = GemmProduct }; };
-template<> struct product_type_selector<Large,Large,Small> { enum { ret = GemmProduct }; };
-
} // end namespace internal
-/** \class ProductReturnType
- * \ingroup Core_Module
- *
- * \brief Helper class to get the correct and optimized returned type of operator*
- *
- * \param Lhs the type of the left-hand side
- * \param Rhs the type of the right-hand side
- * \param ProductMode the type of the product (determined automatically by internal::product_mode)
- *
- * This class defines the typename Type representing the optimized product expression
- * between two matrix expressions. In practice, using ProductReturnType<Lhs,Rhs>::Type
- * is the recommended way to define the result type of a function returning an expression
- * which involve a matrix product. The class Product should never be
- * used directly.
- *
- * \sa class Product, MatrixBase::operator*(const MatrixBase<OtherDerived>&)
- */
-template<typename Lhs, typename Rhs, int ProductType>
-struct ProductReturnType
-{
- // TODO use the nested type to reduce instanciations ????
-// typedef typename internal::nested<Lhs,Rhs::ColsAtCompileTime>::type LhsNested;
-// typedef typename internal::nested<Rhs,Lhs::RowsAtCompileTime>::type RhsNested;
-
- typedef GeneralProduct<Lhs/*Nested*/, Rhs/*Nested*/, ProductType> Type;
-};
-
-template<typename Lhs, typename Rhs>
-struct ProductReturnType<Lhs,Rhs,CoeffBasedProductMode>
-{
- typedef typename internal::nested<Lhs, Rhs::ColsAtCompileTime, typename internal::plain_matrix_type<Lhs>::type >::type LhsNested;
- typedef typename internal::nested<Rhs, Lhs::RowsAtCompileTime, typename internal::plain_matrix_type<Rhs>::type >::type RhsNested;
- typedef CoeffBasedProduct<LhsNested, RhsNested, EvalBeforeAssigningBit | EvalBeforeNestingBit> Type;
-};
-
-template<typename Lhs, typename Rhs>
-struct ProductReturnType<Lhs,Rhs,LazyCoeffBasedProductMode>
-{
- typedef typename internal::nested<Lhs, Rhs::ColsAtCompileTime, typename internal::plain_matrix_type<Lhs>::type >::type LhsNested;
- typedef typename internal::nested<Rhs, Lhs::RowsAtCompileTime, typename internal::plain_matrix_type<Rhs>::type >::type RhsNested;
- typedef CoeffBasedProduct<LhsNested, RhsNested, NestByRefBit> Type;
-};
-
-// this is a workaround for sun CC
-template<typename Lhs, typename Rhs>
-struct LazyProductReturnType : public ProductReturnType<Lhs,Rhs,LazyCoeffBasedProductMode>
-{};
-
-/***********************************************************************
-* Implementation of Inner Vector Vector Product
-***********************************************************************/
-
-// FIXME : maybe the "inner product" could return a Scalar
-// instead of a 1x1 matrix ??
-// Pro: more natural for the user
-// Cons: this could be a problem if in a meta unrolled algorithm a matrix-matrix
-// product ends up to a row-vector times col-vector product... To tackle this use
-// case, we could have a specialization for Block<MatrixType,1,1> with: operator=(Scalar x);
-
-namespace internal {
-
-template<typename Lhs, typename Rhs>
-struct traits<GeneralProduct<Lhs,Rhs,InnerProduct> >
- : traits<Matrix<typename scalar_product_traits<typename Lhs::Scalar, typename Rhs::Scalar>::ReturnType,1,1> >
-{};
-
-}
-
-template<typename Lhs, typename Rhs>
-class GeneralProduct<Lhs, Rhs, InnerProduct>
- : internal::no_assignment_operator,
- public Matrix<typename internal::scalar_product_traits<typename Lhs::Scalar, typename Rhs::Scalar>::ReturnType,1,1>
-{
- typedef Matrix<typename internal::scalar_product_traits<typename Lhs::Scalar, typename Rhs::Scalar>::ReturnType,1,1> Base;
- public:
- GeneralProduct(const Lhs& lhs, const Rhs& rhs)
- {
- EIGEN_STATIC_ASSERT((internal::is_same<typename Lhs::RealScalar, typename Rhs::RealScalar>::value),
- YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)
-
- Base::coeffRef(0,0) = (lhs.transpose().cwiseProduct(rhs)).sum();
- }
-
- /** Convertion to scalar */
- operator const typename Base::Scalar() const {
- return Base::coeff(0,0);
- }
-};
-
-/***********************************************************************
-* Implementation of Outer Vector Vector Product
-***********************************************************************/
-
-namespace internal {
-template<int StorageOrder> struct outer_product_selector;
-
-template<typename Lhs, typename Rhs>
-struct traits<GeneralProduct<Lhs,Rhs,OuterProduct> >
- : traits<ProductBase<GeneralProduct<Lhs,Rhs,OuterProduct>, Lhs, Rhs> >
-{};
-
-}
template<typename Lhs, typename Rhs>
-class GeneralProduct<Lhs, Rhs, OuterProduct>
- : public ProductBase<GeneralProduct<Lhs,Rhs,OuterProduct>, Lhs, Rhs>
+class Product : public ProductImpl<Lhs,Rhs,typename internal::promote_storage_type<typename internal::traits<Lhs>::StorageKind,
+ typename internal::traits<Rhs>::StorageKind>::ret>
{
public:
- EIGEN_PRODUCT_PUBLIC_INTERFACE(GeneralProduct)
-
- GeneralProduct(const Lhs& lhs, const Rhs& rhs) : Base(lhs,rhs)
+
+ typedef typename ProductImpl<
+ Lhs, Rhs,
+ typename internal::promote_storage_type<typename Lhs::StorageKind,
+ typename Rhs::StorageKind>::ret>::Base Base;
+ EIGEN_GENERIC_PUBLIC_INTERFACE(Product)
+
+ typedef typename Lhs::Nested LhsNested;
+ typedef typename Rhs::Nested RhsNested;
+ typedef typename internal::remove_all<LhsNested>::type LhsNestedCleaned;
+ typedef typename internal::remove_all<RhsNested>::type RhsNestedCleaned;
+
+ Product(const Lhs& lhs, const Rhs& rhs) : m_lhs(lhs), m_rhs(rhs)
{
- EIGEN_STATIC_ASSERT((internal::is_same<typename Lhs::RealScalar, typename Rhs::RealScalar>::value),
- YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)
+ eigen_assert(lhs.cols() == rhs.rows()
+ && "invalid matrix product"
+ && "if you wanted a coeff-wise or a dot product use the respective explicit functions");
}
- template<typename Dest> void scaleAndAddTo(Dest& dest, Scalar alpha) const
- {
- internal::outer_product_selector<(int(Dest::Flags)&RowMajorBit) ? RowMajor : ColMajor>::run(*this, dest, alpha);
- }
-};
+ inline Index rows() const { return m_lhs.rows(); }
+ inline Index cols() const { return m_rhs.cols(); }
-namespace internal {
+ const LhsNestedCleaned& lhs() const { return m_lhs; }
+ const RhsNestedCleaned& rhs() const { return m_rhs; }
-template<> struct outer_product_selector<ColMajor> {
- template<typename ProductType, typename Dest>
- static EIGEN_DONT_INLINE void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha) {
- typedef typename Dest::Index Index;
- // FIXME make sure lhs is sequentially stored
- // FIXME not very good if rhs is real and lhs complex while alpha is real too
- const Index cols = dest.cols();
- for (Index j=0; j<cols; ++j)
- dest.col(j) += (alpha * prod.rhs().coeff(j)) * prod.lhs();
- }
-};
+ protected:
-template<> struct outer_product_selector<RowMajor> {
- template<typename ProductType, typename Dest>
- static EIGEN_DONT_INLINE void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha) {
- typedef typename Dest::Index Index;
- // FIXME make sure rhs is sequentially stored
- // FIXME not very good if lhs is real and rhs complex while alpha is real too
- const Index rows = dest.rows();
- for (Index i=0; i<rows; ++i)
- dest.row(i) += (alpha * prod.lhs().coeff(i)) * prod.rhs();
- }
+ const LhsNested m_lhs;
+ const RhsNested m_rhs;
};
-} // end namespace internal
-
-/***********************************************************************
-* Implementation of General Matrix Vector Product
-***********************************************************************/
-
-/* According to the shape/flags of the matrix we have to distinghish 3 different cases:
- * 1 - the matrix is col-major, BLAS compatible and M is large => call fast BLAS-like colmajor routine
- * 2 - the matrix is row-major, BLAS compatible and N is large => call fast BLAS-like rowmajor routine
- * 3 - all other cases are handled using a simple loop along the outer-storage direction.
- * Therefore we need a lower level meta selector.
- * Furthermore, if the matrix is the rhs, then the product has to be transposed.
- */
-namespace internal {
-
-template<typename Lhs, typename Rhs>
-struct traits<GeneralProduct<Lhs,Rhs,GemvProduct> >
- : traits<ProductBase<GeneralProduct<Lhs,Rhs,GemvProduct>, Lhs, Rhs> >
-{};
-
-template<int Side, int StorageOrder, bool BlasCompatible>
-struct gemv_selector;
-
-} // end namespace internal
-
template<typename Lhs, typename Rhs>
-class GeneralProduct<Lhs, Rhs, GemvProduct>
- : public ProductBase<GeneralProduct<Lhs,Rhs,GemvProduct>, Lhs, Rhs>
+class ProductImpl<Lhs,Rhs,Dense> : public internal::dense_xpr_base<Product<Lhs,Rhs> >::type
{
+ typedef Product<Lhs, Rhs> Derived;
public:
- EIGEN_PRODUCT_PUBLIC_INTERFACE(GeneralProduct)
-
- typedef typename Lhs::Scalar LhsScalar;
- typedef typename Rhs::Scalar RhsScalar;
-
- GeneralProduct(const Lhs& lhs, const Rhs& rhs) : Base(lhs,rhs)
- {
-// EIGEN_STATIC_ASSERT((internal::is_same<typename Lhs::Scalar, typename Rhs::Scalar>::value),
-// YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)
- }
-
- enum { Side = Lhs::IsVectorAtCompileTime ? OnTheLeft : OnTheRight };
- typedef typename internal::conditional<int(Side)==OnTheRight,_LhsNested,_RhsNested>::type MatrixType;
-
- template<typename Dest> void scaleAndAddTo(Dest& dst, Scalar alpha) const
- {
- eigen_assert(m_lhs.rows() == dst.rows() && m_rhs.cols() == dst.cols());
- internal::gemv_selector<Side,(int(MatrixType::Flags)&RowMajorBit) ? RowMajor : ColMajor,
- bool(internal::blas_traits<MatrixType>::HasUsableDirectAccess)>::run(*this, dst, alpha);
- }
-};
-
-namespace internal {
-
-// The vector is on the left => transposition
-template<int StorageOrder, bool BlasCompatible>
-struct gemv_selector<OnTheLeft,StorageOrder,BlasCompatible>
-{
- template<typename ProductType, typename Dest>
- static void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha)
- {
- Transpose<Dest> destT(dest);
- enum { OtherStorageOrder = StorageOrder == RowMajor ? ColMajor : RowMajor };
- gemv_selector<OnTheRight,OtherStorageOrder,BlasCompatible>
- ::run(GeneralProduct<Transpose<const typename ProductType::_RhsNested>,Transpose<const typename ProductType::_LhsNested>, GemvProduct>
- (prod.rhs().transpose(), prod.lhs().transpose()), destT, alpha);
- }
-};
-
-template<typename Scalar,int Size,int MaxSize,bool Cond> struct gemv_static_vector_if;
-
-template<typename Scalar,int Size,int MaxSize>
-struct gemv_static_vector_if<Scalar,Size,MaxSize,false>
-{
- EIGEN_STRONG_INLINE Scalar* data() { eigen_internal_assert(false && "should never be called"); return 0; }
-};
-
-template<typename Scalar,int Size>
-struct gemv_static_vector_if<Scalar,Size,Dynamic,true>
-{
- EIGEN_STRONG_INLINE Scalar* data() { return 0; }
-};
-
-template<typename Scalar,int Size,int MaxSize>
-struct gemv_static_vector_if<Scalar,Size,MaxSize,true>
-{
- #if EIGEN_ALIGN_STATICALLY
- internal::plain_array<Scalar,EIGEN_SIZE_MIN_PREFER_FIXED(Size,MaxSize),0> m_data;
- EIGEN_STRONG_INLINE Scalar* data() { return m_data.array; }
- #else
- // Some architectures cannot align on the stack,
- // => let's manually enforce alignment by allocating more data and return the address of the first aligned element.
- enum {
- ForceAlignment = internal::packet_traits<Scalar>::Vectorizable,
- PacketSize = internal::packet_traits<Scalar>::size
- };
- internal::plain_array<Scalar,EIGEN_SIZE_MIN_PREFER_FIXED(Size,MaxSize)+(ForceAlignment?PacketSize:0),0> m_data;
- EIGEN_STRONG_INLINE Scalar* data() {
- return ForceAlignment
- ? reinterpret_cast<Scalar*>((reinterpret_cast<size_t>(m_data.array) & ~(size_t(15))) + 16)
- : m_data.array;
- }
- #endif
-};
-
-template<> struct gemv_selector<OnTheRight,ColMajor,true>
-{
- template<typename ProductType, typename Dest>
- static inline void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha)
- {
- typedef typename ProductType::Index Index;
- typedef typename ProductType::LhsScalar LhsScalar;
- typedef typename ProductType::RhsScalar RhsScalar;
- typedef typename ProductType::Scalar ResScalar;
- typedef typename ProductType::RealScalar RealScalar;
- typedef typename ProductType::ActualLhsType ActualLhsType;
- typedef typename ProductType::ActualRhsType ActualRhsType;
- typedef typename ProductType::LhsBlasTraits LhsBlasTraits;
- typedef typename ProductType::RhsBlasTraits RhsBlasTraits;
- typedef Map<Matrix<ResScalar,Dynamic,1>, Aligned> MappedDest;
-
- const ActualLhsType actualLhs = LhsBlasTraits::extract(prod.lhs());
- const ActualRhsType actualRhs = RhsBlasTraits::extract(prod.rhs());
-
- ResScalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(prod.lhs())
- * RhsBlasTraits::extractScalarFactor(prod.rhs());
-
- enum {
- // FIXME find a way to allow an inner stride on the result if packet_traits<Scalar>::size==1
- // on, the other hand it is good for the cache to pack the vector anyways...
- EvalToDestAtCompileTime = Dest::InnerStrideAtCompileTime==1,
- ComplexByReal = (NumTraits<LhsScalar>::IsComplex) && (!NumTraits<RhsScalar>::IsComplex),
- MightCannotUseDest = (Dest::InnerStrideAtCompileTime!=1) || ComplexByReal
- };
-
- gemv_static_vector_if<ResScalar,Dest::SizeAtCompileTime,Dest::MaxSizeAtCompileTime,MightCannotUseDest> static_dest;
-
- // this is written like this (i.e., with a ?:) to workaround an ICE with ICC 12
- bool alphaIsCompatible = (!ComplexByReal) ? true : (imag(actualAlpha)==RealScalar(0));
- bool evalToDest = EvalToDestAtCompileTime && alphaIsCompatible;
-
- RhsScalar compatibleAlpha = get_factor<ResScalar,RhsScalar>::run(actualAlpha);
-
- ei_declare_aligned_stack_constructed_variable(ResScalar,actualDestPtr,dest.size(),
- evalToDest ? dest.data() : static_dest.data());
-
- if(!evalToDest)
- {
- #ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN
- int size = dest.size();
- EIGEN_DENSE_STORAGE_CTOR_PLUGIN
- #endif
- if(!alphaIsCompatible)
- {
- MappedDest(actualDestPtr, dest.size()).setZero();
- compatibleAlpha = RhsScalar(1);
- }
- else
- MappedDest(actualDestPtr, dest.size()) = dest;
- }
- general_matrix_vector_product
- <Index,LhsScalar,ColMajor,LhsBlasTraits::NeedToConjugate,RhsScalar,RhsBlasTraits::NeedToConjugate>::run(
- actualLhs.rows(), actualLhs.cols(),
- &actualLhs.coeffRef(0,0), actualLhs.outerStride(),
- actualRhs.data(), actualRhs.innerStride(),
- actualDestPtr, 1,
- compatibleAlpha);
-
- if (!evalToDest)
- {
- if(!alphaIsCompatible)
- dest += actualAlpha * MappedDest(actualDestPtr, dest.size());
- else
- dest = MappedDest(actualDestPtr, dest.size());
- }
- }
-};
-
-template<> struct gemv_selector<OnTheRight,RowMajor,true>
-{
- template<typename ProductType, typename Dest>
- static void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha)
- {
- typedef typename ProductType::LhsScalar LhsScalar;
- typedef typename ProductType::RhsScalar RhsScalar;
- typedef typename ProductType::Scalar ResScalar;
- typedef typename ProductType::Index Index;
- typedef typename ProductType::ActualLhsType ActualLhsType;
- typedef typename ProductType::ActualRhsType ActualRhsType;
- typedef typename ProductType::_ActualRhsType _ActualRhsType;
- typedef typename ProductType::LhsBlasTraits LhsBlasTraits;
- typedef typename ProductType::RhsBlasTraits RhsBlasTraits;
-
- typename add_const<ActualLhsType>::type actualLhs = LhsBlasTraits::extract(prod.lhs());
- typename add_const<ActualRhsType>::type actualRhs = RhsBlasTraits::extract(prod.rhs());
-
- ResScalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(prod.lhs())
- * RhsBlasTraits::extractScalarFactor(prod.rhs());
-
- enum {
- // FIXME find a way to allow an inner stride on the result if packet_traits<Scalar>::size==1
- // on, the other hand it is good for the cache to pack the vector anyways...
- DirectlyUseRhs = _ActualRhsType::InnerStrideAtCompileTime==1
- };
-
- gemv_static_vector_if<RhsScalar,_ActualRhsType::SizeAtCompileTime,_ActualRhsType::MaxSizeAtCompileTime,!DirectlyUseRhs> static_rhs;
-
- ei_declare_aligned_stack_constructed_variable(RhsScalar,actualRhsPtr,actualRhs.size(),
- DirectlyUseRhs ? const_cast<RhsScalar*>(actualRhs.data()) : static_rhs.data());
-
- if(!DirectlyUseRhs)
- {
- #ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN
- int size = actualRhs.size();
- EIGEN_DENSE_STORAGE_CTOR_PLUGIN
- #endif
- Map<typename _ActualRhsType::PlainObject>(actualRhsPtr, actualRhs.size()) = actualRhs;
- }
-
- general_matrix_vector_product
- <Index,LhsScalar,RowMajor,LhsBlasTraits::NeedToConjugate,RhsScalar,RhsBlasTraits::NeedToConjugate>::run(
- actualLhs.rows(), actualLhs.cols(),
- &actualLhs.coeffRef(0,0), actualLhs.outerStride(),
- actualRhsPtr, 1,
- &dest.coeffRef(0,0), dest.innerStride(),
- actualAlpha);
- }
-};
-
-template<> struct gemv_selector<OnTheRight,ColMajor,false>
-{
- template<typename ProductType, typename Dest>
- static void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha)
- {
- typedef typename Dest::Index Index;
- // TODO makes sure dest is sequentially stored in memory, otherwise use a temp
- const Index size = prod.rhs().rows();
- for(Index k=0; k<size; ++k)
- dest += (alpha*prod.rhs().coeff(k)) * prod.lhs().col(k);
- }
-};
-
-template<> struct gemv_selector<OnTheRight,RowMajor,false>
-{
- template<typename ProductType, typename Dest>
- static void run(const ProductType& prod, Dest& dest, typename ProductType::Scalar alpha)
- {
- typedef typename Dest::Index Index;
- // TODO makes sure rhs is sequentially stored in memory, otherwise use a temp
- const Index rows = prod.rows();
- for(Index i=0; i<rows; ++i)
- dest.coeffRef(i) += alpha * (prod.lhs().row(i).cwiseProduct(prod.rhs().transpose())).sum();
- }
+ typedef typename internal::dense_xpr_base<Product<Lhs, Rhs> >::type Base;
+ EIGEN_DENSE_PUBLIC_INTERFACE(Derived)
};
-} // end namespace internal
-
-/***************************************************************************
-* Implementation of matrix base methods
-***************************************************************************/
-
-/** \returns the matrix product of \c *this and \a other.
- *
- * \note If instead of the matrix product you want the coefficient-wise product, see Cwise::operator*().
- *
- * \sa lazyProduct(), operator*=(const MatrixBase&), Cwise::operator*()
- */
-template<typename Derived>
-template<typename OtherDerived>
-inline const typename ProductReturnType<Derived,OtherDerived>::Type
-MatrixBase<Derived>::operator*(const MatrixBase<OtherDerived> &other) const
-{
- // A note regarding the function declaration: In MSVC, this function will sometimes
- // not be inlined since DenseStorage is an unwindable object for dynamic
- // matrices and product types are holding a member to store the result.
- // Thus it does not help tagging this function with EIGEN_STRONG_INLINE.
- enum {
- ProductIsValid = Derived::ColsAtCompileTime==Dynamic
- || OtherDerived::RowsAtCompileTime==Dynamic
- || int(Derived::ColsAtCompileTime)==int(OtherDerived::RowsAtCompileTime),
- AreVectors = Derived::IsVectorAtCompileTime && OtherDerived::IsVectorAtCompileTime,
- SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(Derived,OtherDerived)
- };
- // note to the lost user:
- // * for a dot product use: v1.dot(v2)
- // * for a coeff-wise product use: v1.cwiseProduct(v2)
- EIGEN_STATIC_ASSERT(ProductIsValid || !(AreVectors && SameSizes),
- INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS)
- EIGEN_STATIC_ASSERT(ProductIsValid || !(SameSizes && !AreVectors),
- INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION)
- EIGEN_STATIC_ASSERT(ProductIsValid || SameSizes, INVALID_MATRIX_PRODUCT)
-#ifdef EIGEN_DEBUG_PRODUCT
- internal::product_type<Derived,OtherDerived>::debug();
-#endif
- return typename ProductReturnType<Derived,OtherDerived>::Type(derived(), other.derived());
-}
-
-/** \returns an expression of the matrix product of \c *this and \a other without implicit evaluation.
- *
- * The returned product will behave like any other expressions: the coefficients of the product will be
- * computed once at a time as requested. This might be useful in some extremely rare cases when only
- * a small and no coherent fraction of the result's coefficients have to be computed.
- *
- * \warning This version of the matrix product can be much much slower. So use it only if you know
- * what you are doing and that you measured a true speed improvement.
- *
- * \sa operator*(const MatrixBase&)
- */
-template<typename Derived>
-template<typename OtherDerived>
-const typename LazyProductReturnType<Derived,OtherDerived>::Type
-MatrixBase<Derived>::lazyProduct(const MatrixBase<OtherDerived> &other) const
-{
- enum {
- ProductIsValid = Derived::ColsAtCompileTime==Dynamic
- || OtherDerived::RowsAtCompileTime==Dynamic
- || int(Derived::ColsAtCompileTime)==int(OtherDerived::RowsAtCompileTime),
- AreVectors = Derived::IsVectorAtCompileTime && OtherDerived::IsVectorAtCompileTime,
- SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(Derived,OtherDerived)
- };
- // note to the lost user:
- // * for a dot product use: v1.dot(v2)
- // * for a coeff-wise product use: v1.cwiseProduct(v2)
- EIGEN_STATIC_ASSERT(ProductIsValid || !(AreVectors && SameSizes),
- INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS)
- EIGEN_STATIC_ASSERT(ProductIsValid || !(SameSizes && !AreVectors),
- INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION)
- EIGEN_STATIC_ASSERT(ProductIsValid || SameSizes, INVALID_MATRIX_PRODUCT)
-
- return typename LazyProductReturnType<Derived,OtherDerived>::Type(derived(), other.derived());
-}
-
#endif // EIGEN_PRODUCT_H
diff --git a/extern/Eigen3/Eigen/src/Core/ProductBase.h b/extern/Eigen3/Eigen/src/Core/ProductBase.h
index 91975880fdc..ec12e5c9f6b 100644
--- a/extern/Eigen3/Eigen/src/Core/ProductBase.h
+++ b/extern/Eigen3/Eigen/src/Core/ProductBase.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PRODUCTBASE_H
#define EIGEN_PRODUCTBASE_H
+namespace Eigen {
+
/** \class ProductBase
* \ingroup Core_Module
*
@@ -115,10 +102,10 @@ class ProductBase : public MatrixBase<Derived>
inline void evalTo(Dest& dst) const { dst.setZero(); scaleAndAddTo(dst,Scalar(1)); }
template<typename Dest>
- inline void addTo(Dest& dst) const { scaleAndAddTo(dst,1); }
+ inline void addTo(Dest& dst) const { scaleAndAddTo(dst,Scalar(1)); }
template<typename Dest>
- inline void subTo(Dest& dst) const { scaleAndAddTo(dst,-1); }
+ inline void subTo(Dest& dst) const { scaleAndAddTo(dst,Scalar(-1)); }
template<typename Dest>
inline void scaleAndAddTo(Dest& dst,Scalar alpha) const { derived().scaleAndAddTo(dst,alpha); }
@@ -181,8 +168,8 @@ class ProductBase : public MatrixBase<Derived>
protected:
- const LhsNested m_lhs;
- const RhsNested m_rhs;
+ LhsNested m_lhs;
+ RhsNested m_rhs;
mutable PlainObject m_result;
};
@@ -286,5 +273,6 @@ Derived& MatrixBase<Derived>::lazyAssign(const ProductBase<ProductDerived, Lhs,R
return derived();
}
+} // end namespace Eigen
#endif // EIGEN_PRODUCTBASE_H
diff --git a/extern/Eigen3/Eigen/src/Core/Random.h b/extern/Eigen3/Eigen/src/Core/Random.h
index b7d90103a5b..a9f7f434666 100644
--- a/extern/Eigen3/Eigen/src/Core/Random.h
+++ b/extern/Eigen3/Eigen/src/Core/Random.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_RANDOM_H
#define EIGEN_RANDOM_H
+namespace Eigen {
+
namespace internal {
template<typename Scalar> struct scalar_random_op {
@@ -160,4 +147,6 @@ PlainObjectBase<Derived>::setRandom(Index rows, Index cols)
return setRandom();
}
+} // end namespace Eigen
+
#endif // EIGEN_RANDOM_H
diff --git a/extern/Eigen3/Eigen/src/Core/Redux.h b/extern/Eigen3/Eigen/src/Core/Redux.h
index f9f5a95d546..b7ce7c658a2 100644
--- a/extern/Eigen3/Eigen/src/Core/Redux.h
+++ b/extern/Eigen3/Eigen/src/Core/Redux.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_REDUX_H
#define EIGEN_REDUX_H
+namespace Eigen {
+
namespace internal {
// TODO
@@ -95,7 +82,7 @@ struct redux_novec_unroller
typedef typename Derived::Scalar Scalar;
- EIGEN_STRONG_INLINE static Scalar run(const Derived &mat, const Func& func)
+ static EIGEN_STRONG_INLINE Scalar run(const Derived &mat, const Func& func)
{
return func(redux_novec_unroller<Func, Derived, Start, HalfLength>::run(mat,func),
redux_novec_unroller<Func, Derived, Start+HalfLength, Length-HalfLength>::run(mat,func));
@@ -112,7 +99,7 @@ struct redux_novec_unroller<Func, Derived, Start, 1>
typedef typename Derived::Scalar Scalar;
- EIGEN_STRONG_INLINE static Scalar run(const Derived &mat, const Func&)
+ static EIGEN_STRONG_INLINE Scalar run(const Derived &mat, const Func&)
{
return mat.coeffByOuterInner(outer, inner);
}
@@ -125,7 +112,7 @@ template<typename Func, typename Derived, int Start>
struct redux_novec_unroller<Func, Derived, Start, 0>
{
typedef typename Derived::Scalar Scalar;
- EIGEN_STRONG_INLINE static Scalar run(const Derived&, const Func&) { return Scalar(); }
+ static EIGEN_STRONG_INLINE Scalar run(const Derived&, const Func&) { return Scalar(); }
};
/*** vectorization ***/
@@ -141,7 +128,7 @@ struct redux_vec_unroller
typedef typename Derived::Scalar Scalar;
typedef typename packet_traits<Scalar>::type PacketScalar;
- EIGEN_STRONG_INLINE static PacketScalar run(const Derived &mat, const Func& func)
+ static EIGEN_STRONG_INLINE PacketScalar run(const Derived &mat, const Func& func)
{
return func.packetOp(
redux_vec_unroller<Func, Derived, Start, HalfLength>::run(mat,func),
@@ -162,7 +149,7 @@ struct redux_vec_unroller<Func, Derived, Start, 1>
typedef typename Derived::Scalar Scalar;
typedef typename packet_traits<Scalar>::type PacketScalar;
- EIGEN_STRONG_INLINE static PacketScalar run(const Derived &mat, const Func&)
+ static EIGEN_STRONG_INLINE PacketScalar run(const Derived &mat, const Func&)
{
return mat.template packetByOuterInner<alignment>(outer, inner);
}
@@ -214,20 +201,33 @@ struct redux_impl<Func, Derived, LinearVectorizedTraversal, NoUnrolling>
const Index size = mat.size();
eigen_assert(size && "you are using an empty matrix");
const Index packetSize = packet_traits<Scalar>::size;
- const Index alignedStart = first_aligned(mat);
+ const Index alignedStart = internal::first_aligned(mat);
enum {
alignment = bool(Derived::Flags & DirectAccessBit) || bool(Derived::Flags & AlignedBit)
? Aligned : Unaligned
};
- const Index alignedSize = ((size-alignedStart)/packetSize)*packetSize;
- const Index alignedEnd = alignedStart + alignedSize;
+ const Index alignedSize2 = ((size-alignedStart)/(2*packetSize))*(2*packetSize);
+ const Index alignedSize = ((size-alignedStart)/(packetSize))*(packetSize);
+ const Index alignedEnd2 = alignedStart + alignedSize2;
+ const Index alignedEnd = alignedStart + alignedSize;
Scalar res;
if(alignedSize)
{
- PacketScalar packet_res = mat.template packet<alignment>(alignedStart);
- for(Index index = alignedStart + packetSize; index < alignedEnd; index += packetSize)
- packet_res = func.packetOp(packet_res, mat.template packet<alignment>(index));
- res = func.predux(packet_res);
+ PacketScalar packet_res0 = mat.template packet<alignment>(alignedStart);
+ if(alignedSize>packetSize) // we have at least two packets to partly unroll the loop
+ {
+ PacketScalar packet_res1 = mat.template packet<alignment>(alignedStart+packetSize);
+ for(Index index = alignedStart + 2*packetSize; index < alignedEnd2; index += 2*packetSize)
+ {
+ packet_res0 = func.packetOp(packet_res0, mat.template packet<alignment>(index));
+ packet_res1 = func.packetOp(packet_res1, mat.template packet<alignment>(index+packetSize));
+ }
+
+ packet_res0 = func.packetOp(packet_res0,packet_res1);
+ if(alignedEnd>alignedEnd2)
+ packet_res0 = func.packetOp(packet_res0, mat.template packet<alignment>(alignedEnd2));
+ }
+ res = func.predux(packet_res0);
for(Index index = 0; index < alignedStart; ++index)
res = func(res,mat.coeff(index));
@@ -296,7 +296,7 @@ struct redux_impl<Func, Derived, LinearVectorizedTraversal, CompleteUnrolling>
Size = Derived::SizeAtCompileTime,
VectorizedSize = (Size / PacketSize) * PacketSize
};
- EIGEN_STRONG_INLINE static Scalar run(const Derived& mat, const Func& func)
+ static EIGEN_STRONG_INLINE Scalar run(const Derived& mat, const Func& func)
{
eigen_assert(mat.rows()>0 && mat.cols()>0 && "you are using an empty matrix");
Scalar res = func.predux(redux_vec_unroller<Func, Derived, 0, Size / PacketSize>::run(mat,func));
@@ -401,4 +401,6 @@ MatrixBase<Derived>::trace() const
return derived().diagonal().sum();
}
+} // end namespace Eigen
+
#endif // EIGEN_REDUX_H
diff --git a/extern/Eigen3/Eigen/src/Core/Replicate.h b/extern/Eigen3/Eigen/src/Core/Replicate.h
index 4c171f8d580..b61fdc29e2f 100644
--- a/extern/Eigen3/Eigen/src/Core/Replicate.h
+++ b/extern/Eigen3/Eigen/src/Core/Replicate.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_REPLICATE_H
#define EIGEN_REPLICATE_H
+namespace Eigen {
+
/**
* \class Replicate
* \ingroup Core_Module
@@ -92,7 +79,7 @@ template<typename MatrixType,int RowFactor,int ColFactor> class Replicate
}
template<typename OriginalMatrixType>
- inline Replicate(const OriginalMatrixType& matrix, int rowFactor, int colFactor)
+ inline Replicate(const OriginalMatrixType& matrix, Index rowFactor, Index colFactor)
: m_matrix(matrix), m_rowFactor(rowFactor), m_colFactor(colFactor)
{
EIGEN_STATIC_ASSERT((internal::is_same<typename internal::remove_const<MatrixType>::type,OriginalMatrixType>::value),
@@ -127,9 +114,13 @@ template<typename MatrixType,int RowFactor,int ColFactor> class Replicate
return m_matrix.template packet<LoadMode>(actual_row, actual_col);
}
+ const _MatrixTypeNested& nestedExpression() const
+ {
+ return m_matrix;
+ }
protected:
- const MatrixTypeNested m_matrix;
+ MatrixTypeNested m_matrix;
const internal::variable_if_dynamic<Index, RowFactor> m_rowFactor;
const internal::variable_if_dynamic<Index, ColFactor> m_colFactor;
};
@@ -181,4 +172,6 @@ VectorwiseOp<ExpressionType,Direction>::replicate(Index factor) const
(_expression(),Direction==Vertical?factor:1,Direction==Horizontal?factor:1);
}
+} // end namespace Eigen
+
#endif // EIGEN_REPLICATE_H
diff --git a/extern/Eigen3/Eigen/src/Core/ReturnByValue.h b/extern/Eigen3/Eigen/src/Core/ReturnByValue.h
index 24c5a4e215d..613912ffa8c 100644
--- a/extern/Eigen3/Eigen/src/Core/ReturnByValue.h
+++ b/extern/Eigen3/Eigen/src/Core/ReturnByValue.h
@@ -4,28 +4,15 @@
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_RETURNBYVALUE_H
#define EIGEN_RETURNBYVALUE_H
+namespace Eigen {
+
/** \class ReturnByValue
* \ingroup Core_Module
*
@@ -96,4 +83,6 @@ Derived& DenseBase<Derived>::operator=(const ReturnByValue<OtherDerived>& other)
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_RETURNBYVALUE_H
diff --git a/extern/Eigen3/Eigen/src/Core/Reverse.h b/extern/Eigen3/Eigen/src/Core/Reverse.h
index 600744ae758..e30ae3d281b 100644
--- a/extern/Eigen3/Eigen/src/Core/Reverse.h
+++ b/extern/Eigen3/Eigen/src/Core/Reverse.h
@@ -5,28 +5,15 @@
// Copyright (C) 2009 Ricard Marxer <email@ricardmarxer.com>
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_REVERSE_H
#define EIGEN_REVERSE_H
+namespace Eigen {
+
/** \class Reverse
* \ingroup Core_Module
*
@@ -183,8 +170,14 @@ template<typename MatrixType, int Direction> class Reverse
m_matrix.const_cast_derived().template writePacket<LoadMode>(m_matrix.size() - index - PacketSize, internal::preverse(x));
}
+ const typename internal::remove_all<typename MatrixType::Nested>::type&
+ nestedExpression() const
+ {
+ return m_matrix;
+ }
+
protected:
- const typename MatrixType::Nested m_matrix;
+ typename MatrixType::Nested m_matrix;
};
/** \returns an expression of the reverse of *this.
@@ -226,5 +219,6 @@ inline void DenseBase<Derived>::reverseInPlace()
derived() = derived().reverse().eval();
}
+} // end namespace Eigen
#endif // EIGEN_REVERSE_H
diff --git a/extern/Eigen3/Eigen/src/Core/Select.h b/extern/Eigen3/Eigen/src/Core/Select.h
index d0cd66a261a..2bf6e91d0aa 100644
--- a/extern/Eigen3/Eigen/src/Core/Select.h
+++ b/extern/Eigen3/Eigen/src/Core/Select.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SELECT_H
#define EIGEN_SELECT_H
+namespace Eigen {
+
/** \class Select
* \ingroup Core_Module
*
@@ -101,10 +88,25 @@ class Select : internal::no_assignment_operator,
return m_else.coeff(i);
}
+ const ConditionMatrixType& conditionMatrix() const
+ {
+ return m_condition;
+ }
+
+ const ThenMatrixType& thenMatrix() const
+ {
+ return m_then;
+ }
+
+ const ElseMatrixType& elseMatrix() const
+ {
+ return m_else;
+ }
+
protected:
- const typename ConditionMatrixType::Nested m_condition;
- const typename ThenMatrixType::Nested m_then;
- const typename ElseMatrixType::Nested m_else;
+ typename ConditionMatrixType::Nested m_condition;
+ typename ThenMatrixType::Nested m_then;
+ typename ElseMatrixType::Nested m_else;
};
@@ -155,4 +157,6 @@ DenseBase<Derived>::select(typename ElseDerived::Scalar thenScalar,
derived(), ElseDerived::Constant(rows(),cols(),thenScalar), elseMatrix.derived());
}
+} // end namespace Eigen
+
#endif // EIGEN_SELECT_H
diff --git a/extern/Eigen3/Eigen/src/Core/SelfAdjointView.h b/extern/Eigen3/Eigen/src/Core/SelfAdjointView.h
index 4bb68755eee..82cc4da736a 100644
--- a/extern/Eigen3/Eigen/src/Core/SelfAdjointView.h
+++ b/extern/Eigen3/Eigen/src/Core/SelfAdjointView.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SELFADJOINTMATRIX_H
#define EIGEN_SELFADJOINTMATRIX_H
+namespace Eigen {
+
/** \class SelfAdjointView
* \ingroup Core_Module
*
@@ -82,7 +69,7 @@ template<typename MatrixType, unsigned int UpLo> class SelfAdjointView
};
typedef typename MatrixType::PlainObject PlainObject;
- inline SelfAdjointView(const MatrixType& matrix) : m_matrix(matrix)
+ inline SelfAdjointView(MatrixType& matrix) : m_matrix(matrix)
{}
inline Index rows() const { return m_matrix.rows(); }
@@ -199,7 +186,7 @@ template<typename MatrixType, unsigned int UpLo> class SelfAdjointView
#endif
protected:
- const MatrixTypeNested m_matrix;
+ MatrixTypeNested m_matrix;
};
@@ -222,7 +209,7 @@ struct triangular_assignment_selector<Derived1, Derived2, (SelfAdjoint|Upper), U
row = (UnrollCount-1) % Derived1::RowsAtCompileTime
};
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
triangular_assignment_selector<Derived1, Derived2, (SelfAdjoint|Upper), UnrollCount-1, ClearOpposite>::run(dst, src);
@@ -236,7 +223,7 @@ struct triangular_assignment_selector<Derived1, Derived2, (SelfAdjoint|Upper), U
template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, SelfAdjoint|Upper, 0, ClearOpposite>
{
- inline static void run(Derived1 &, const Derived2 &) {}
+ static inline void run(Derived1 &, const Derived2 &) {}
};
template<typename Derived1, typename Derived2, int UnrollCount, bool ClearOpposite>
@@ -247,7 +234,7 @@ struct triangular_assignment_selector<Derived1, Derived2, (SelfAdjoint|Lower), U
row = (UnrollCount-1) % Derived1::RowsAtCompileTime
};
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
triangular_assignment_selector<Derived1, Derived2, (SelfAdjoint|Lower), UnrollCount-1, ClearOpposite>::run(dst, src);
@@ -261,14 +248,14 @@ struct triangular_assignment_selector<Derived1, Derived2, (SelfAdjoint|Lower), U
template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, SelfAdjoint|Lower, 0, ClearOpposite>
{
- inline static void run(Derived1 &, const Derived2 &) {}
+ static inline void run(Derived1 &, const Derived2 &) {}
};
template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, SelfAdjoint|Upper, Dynamic, ClearOpposite>
{
typedef typename Derived1::Index Index;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
for(Index j = 0; j < dst.cols(); ++j)
{
@@ -285,7 +272,7 @@ struct triangular_assignment_selector<Derived1, Derived2, SelfAdjoint|Upper, Dyn
template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, SelfAdjoint|Lower, Dynamic, ClearOpposite>
{
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
typedef typename Derived1::Index Index;
for(Index i = 0; i < dst.rows(); ++i)
@@ -322,4 +309,6 @@ MatrixBase<Derived>::selfadjointView()
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_SELFADJOINTMATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Core/SelfCwiseBinaryOp.h b/extern/Eigen3/Eigen/src/Core/SelfCwiseBinaryOp.h
index 4e9ca88745d..0caf2bab1d8 100644
--- a/extern/Eigen3/Eigen/src/Core/SelfCwiseBinaryOp.h
+++ b/extern/Eigen3/Eigen/src/Core/SelfCwiseBinaryOp.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SELFCWISEBINARYOP_H
#define EIGEN_SELFCWISEBINARYOP_H
+namespace Eigen {
+
/** \class SelfCwiseBinaryOp
* \ingroup Core_Module
*
@@ -163,6 +150,16 @@ template<typename BinaryOp, typename Lhs, typename Rhs> class SelfCwiseBinaryOp
return Base::operator=(rhs);
}
+ Lhs& expression() const
+ {
+ return m_matrix;
+ }
+
+ const BinaryOp& functor() const
+ {
+ return m_functor;
+ }
+
protected:
Lhs& m_matrix;
const BinaryOp& m_functor;
@@ -192,4 +189,6 @@ inline Derived& DenseBase<Derived>::operator/=(const Scalar& other)
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_SELFCWISEBINARYOP_H
diff --git a/extern/Eigen3/Eigen/src/Core/SolveTriangular.h b/extern/Eigen3/Eigen/src/Core/SolveTriangular.h
index a23014a343f..ef17f288e29 100644
--- a/extern/Eigen3/Eigen/src/Core/SolveTriangular.h
+++ b/extern/Eigen3/Eigen/src/Core/SolveTriangular.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SOLVETRIANGULAR_H
#define EIGEN_SOLVETRIANGULAR_H
+namespace Eigen {
+
namespace internal {
// Forward declarations:
@@ -98,12 +85,22 @@ struct triangular_solver_selector<Lhs,Rhs,Side,Mode,NoUnrolling,Dynamic>
typedef typename Rhs::Index Index;
typedef blas_traits<Lhs> LhsProductTraits;
typedef typename LhsProductTraits::DirectLinearAccessType ActualLhsType;
+
static void run(const Lhs& lhs, Rhs& rhs)
{
- const ActualLhsType actualLhs = LhsProductTraits::extract(lhs);
+ typename internal::add_const_on_value_type<ActualLhsType>::type actualLhs = LhsProductTraits::extract(lhs);
+
+ const Index size = lhs.rows();
+ const Index othersize = Side==OnTheLeft? rhs.cols() : rhs.rows();
+
+ typedef internal::gemm_blocking_space<(Rhs::Flags&RowMajorBit) ? RowMajor : ColMajor,Scalar,Scalar,
+ Rhs::MaxRowsAtCompileTime, Rhs::MaxColsAtCompileTime, Lhs::MaxRowsAtCompileTime,4> BlockingType;
+
+ BlockingType blocking(rhs.rows(), rhs.cols(), size);
+
triangular_solve_matrix<Scalar,Index,Side,Mode,LhsProductTraits::NeedToConjugate,(int(Lhs::Flags) & RowMajorBit) ? RowMajor : ColMajor,
(Rhs::Flags&RowMajorBit) ? RowMajor : ColMajor>
- ::run(lhs.rows(), Side==OnTheLeft? rhs.cols() : rhs.rows(), &actualLhs.coeffRef(0,0), actualLhs.outerStride(), &rhs.coeffRef(0,0), rhs.outerStride());
+ ::run(size, othersize, &actualLhs.coeffRef(0,0), actualLhs.outerStride(), &rhs.coeffRef(0,0), rhs.outerStride(), blocking);
}
};
@@ -177,10 +174,8 @@ template<int Side, typename OtherDerived>
void TriangularView<MatrixType,Mode>::solveInPlace(const MatrixBase<OtherDerived>& _other) const
{
OtherDerived& other = _other.const_cast_derived();
- eigen_assert(cols() == rows());
- eigen_assert( (Side==OnTheLeft && cols() == other.rows()) || (Side==OnTheRight && cols() == other.cols()) );
- eigen_assert(!(Mode & ZeroDiag));
- eigen_assert((Mode & (Upper|Lower)) != 0);
+ eigen_assert( cols() == rows() && ((Side==OnTheLeft && cols() == other.rows()) || (Side==OnTheRight && cols() == other.cols())) );
+ eigen_assert((!(Mode & ZeroDiag)) && bool(Mode & (Upper|Lower)));
enum { copy = internal::traits<OtherDerived>::Flags & RowMajorBit && OtherDerived::IsVectorAtCompileTime };
typedef typename internal::conditional<copy,
@@ -255,9 +250,11 @@ template<int Side, typename TriangularType, typename Rhs> struct triangular_solv
protected:
const TriangularType& m_triangularMatrix;
- const typename Rhs::Nested m_rhs;
+ typename Rhs::Nested m_rhs;
};
} // namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_SOLVETRIANGULAR_H
diff --git a/extern/Eigen3/Eigen/src/Core/StableNorm.h b/extern/Eigen3/Eigen/src/Core/StableNorm.h
index f667272e4a4..d8bf7db70e4 100644
--- a/extern/Eigen3/Eigen/src/Core/StableNorm.h
+++ b/extern/Eigen3/Eigen/src/Core/StableNorm.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STABLENORM_H
#define EIGEN_STABLENORM_H
+namespace Eigen {
+
namespace internal {
template<typename ExpressionType, typename Scalar>
inline void stable_norm_kernel(const ExpressionType& bl, Scalar& ssq, Scalar& scale, Scalar& invScale)
@@ -58,9 +45,9 @@ MatrixBase<Derived>::stableNorm() const
{
using std::min;
const Index blockSize = 4096;
- RealScalar scale = 0;
- RealScalar invScale = 1;
- RealScalar ssq = 0; // sum of square
+ RealScalar scale(0);
+ RealScalar invScale(1);
+ RealScalar ssq(0); // sum of square
enum {
Alignment = (int(Flags)&DirectAccessBit) || (int(Flags)&AlignedBit) ? 1 : 0
};
@@ -187,4 +174,6 @@ MatrixBase<Derived>::hypotNorm() const
return this->cwiseAbs().redux(internal::scalar_hypot_op<RealScalar>());
}
+} // end namespace Eigen
+
#endif // EIGEN_STABLENORM_H
diff --git a/extern/Eigen3/Eigen/src/Core/Stride.h b/extern/Eigen3/Eigen/src/Core/Stride.h
index 0430f111627..1e3f5fe9fff 100644
--- a/extern/Eigen3/Eigen/src/Core/Stride.h
+++ b/extern/Eigen3/Eigen/src/Core/Stride.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STRIDE_H
#define EIGEN_STRIDE_H
+namespace Eigen {
+
/** \class Stride
* \ingroup Core_Module
*
@@ -116,4 +103,6 @@ class OuterStride : public Stride<Value, 0>
OuterStride(Index v) : Base(v,0) {}
};
+} // end namespace Eigen
+
#endif // EIGEN_STRIDE_H
diff --git a/extern/Eigen3/Eigen/src/Core/Swap.h b/extern/Eigen3/Eigen/src/Core/Swap.h
index 5fb03286675..fd73cf3ad7e 100644
--- a/extern/Eigen3/Eigen/src/Core/Swap.h
+++ b/extern/Eigen3/Eigen/src/Core/Swap.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SWAP_H
#define EIGEN_SWAP_H
+namespace Eigen {
+
/** \class SwapWrapper
* \ingroup Core_Module
*
@@ -52,6 +39,15 @@ template<typename ExpressionType> class SwapWrapper
inline Index cols() const { return m_expression.cols(); }
inline Index outerStride() const { return m_expression.outerStride(); }
inline Index innerStride() const { return m_expression.innerStride(); }
+
+ typedef typename internal::conditional<
+ internal::is_lvalue<ExpressionType>::value,
+ Scalar,
+ const Scalar
+ >::type ScalarWithConstIfNotLvalue;
+
+ inline ScalarWithConstIfNotLvalue* data() { return m_expression.data(); }
+ inline const Scalar* data() const { return m_expression.data(); }
inline Scalar& coeffRef(Index row, Index col)
{
@@ -119,8 +115,12 @@ template<typename ExpressionType> class SwapWrapper
_other.template writePacket<LoadMode>(index, tmp);
}
+ ExpressionType& expression() const { return m_expression; }
+
protected:
ExpressionType& m_expression;
};
+} // end namespace Eigen
+
#endif // EIGEN_SWAP_H
diff --git a/extern/Eigen3/Eigen/src/Core/Transpose.h b/extern/Eigen3/Eigen/src/Core/Transpose.h
index 3f7c7df6ee1..045a1cce671 100644
--- a/extern/Eigen3/Eigen/src/Core/Transpose.h
+++ b/extern/Eigen3/Eigen/src/Core/Transpose.h
@@ -4,28 +4,15 @@
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRANSPOSE_H
#define EIGEN_TRANSPOSE_H
+namespace Eigen {
+
/** \class Transpose
* \ingroup Core_Module
*
@@ -91,7 +78,7 @@ template<typename MatrixType> class Transpose
nestedExpression() { return m_matrix.const_cast_derived(); }
protected:
- const typename MatrixType::Nested m_matrix;
+ typename MatrixType::Nested m_matrix;
};
namespace internal {
@@ -152,12 +139,12 @@ template<typename MatrixType> class TransposeImpl<MatrixType,Dense>
return derived().nestedExpression().coeffRef(index);
}
- inline const CoeffReturnType coeff(Index row, Index col) const
+ inline CoeffReturnType coeff(Index row, Index col) const
{
return derived().nestedExpression().coeff(col, row);
}
- inline const CoeffReturnType coeff(Index index) const
+ inline CoeffReturnType coeff(Index index) const
{
return derived().nestedExpression().coeff(index);
}
@@ -422,4 +409,6 @@ void DenseBase<Derived>::checkTransposeAliasing(const OtherDerived& other) const
}
#endif
+} // end namespace Eigen
+
#endif // EIGEN_TRANSPOSE_H
diff --git a/extern/Eigen3/Eigen/src/Core/Transpositions.h b/extern/Eigen3/Eigen/src/Core/Transpositions.h
index 88fdfb2226f..2cd268a5fa0 100644
--- a/extern/Eigen3/Eigen/src/Core/Transpositions.h
+++ b/extern/Eigen3/Eigen/src/Core/Transpositions.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2010-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRANSPOSITIONS_H
#define EIGEN_TRANSPOSITIONS_H
+namespace Eigen {
+
/** \class Transpositions
* \ingroup Core_Module
*
@@ -404,7 +391,7 @@ struct transposition_matrix_product_retval
protected:
const TranspositionType& m_transpositions;
- const typename MatrixType::Nested m_matrix;
+ typename MatrixType::Nested m_matrix;
};
} // end namespace internal
@@ -444,4 +431,6 @@ class Transpose<TranspositionsBase<TranspositionsDerived> >
const TranspositionType& m_transpositions;
};
+} // end namespace Eigen
+
#endif // EIGEN_TRANSPOSITIONS_H
diff --git a/extern/Eigen3/Eigen/src/Core/TriangularMatrix.h b/extern/Eigen3/Eigen/src/Core/TriangularMatrix.h
index 033e81036f3..de9540063c2 100644
--- a/extern/Eigen3/Eigen/src/Core/TriangularMatrix.h
+++ b/extern/Eigen3/Eigen/src/Core/TriangularMatrix.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRIANGULARMATRIX_H
#define EIGEN_TRIANGULARMATRIX_H
+namespace Eigen {
+
namespace internal {
template<int Side, typename TriangularType, typename Rhs> struct triangular_solve_retval;
@@ -273,11 +260,8 @@ template<typename _MatrixType, unsigned int _Mode> class TriangularView
inline const TriangularView<MatrixConjugateReturnType,Mode> conjugate() const
{ return m_matrix.conjugate(); }
- /** \sa MatrixBase::adjoint() */
- inline TriangularView<typename MatrixType::AdjointReturnType,TransposeMode> adjoint()
- { return m_matrix.adjoint(); }
/** \sa MatrixBase::adjoint() const */
- inline const TriangularView<typename MatrixType::AdjointReturnType,TransposeMode> adjoint() const
+ inline const TriangularView<const typename MatrixType::AdjointReturnType,TransposeMode> adjoint() const
{ return m_matrix.adjoint(); }
/** \sa MatrixBase::transpose() */
@@ -288,11 +272,13 @@ template<typename _MatrixType, unsigned int _Mode> class TriangularView
}
/** \sa MatrixBase::transpose() const */
inline const TriangularView<Transpose<MatrixType>,TransposeMode> transpose() const
- { return m_matrix.transpose(); }
+ {
+ return m_matrix.transpose();
+ }
/** Efficient triangular matrix times vector/matrix product */
template<typename OtherDerived>
- TriangularProduct<Mode,true,MatrixType,false,OtherDerived,OtherDerived::IsVectorAtCompileTime>
+ TriangularProduct<Mode,true,MatrixType,false,OtherDerived, OtherDerived::IsVectorAtCompileTime>
operator*(const MatrixBase<OtherDerived>& rhs) const
{
return TriangularProduct
@@ -375,7 +361,8 @@ template<typename _MatrixType, unsigned int _Mode> class TriangularView
template<typename OtherDerived>
void swap(MatrixBase<OtherDerived> const & other)
{
- TriangularView<SwapWrapper<MatrixType>,Mode>(const_cast<MatrixType&>(m_matrix)).lazyAssign(other.derived());
+ SwapWrapper<MatrixType> swaper(const_cast<MatrixType&>(m_matrix));
+ TriangularView<SwapWrapper<MatrixType>,Mode>(swaper).lazyAssign(other.derived());
}
Scalar determinant() const
@@ -433,7 +420,7 @@ template<typename _MatrixType, unsigned int _Mode> class TriangularView
template<typename ProductDerived, typename Lhs, typename Rhs>
EIGEN_STRONG_INLINE TriangularView& assignProduct(const ProductBase<ProductDerived, Lhs,Rhs>& prod, const Scalar& alpha);
- const MatrixTypeNested m_matrix;
+ MatrixTypeNested m_matrix;
};
/***************************************************************************
@@ -452,7 +439,7 @@ struct triangular_assignment_selector
typedef typename Derived1::Scalar Scalar;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
triangular_assignment_selector<Derived1, Derived2, Mode, UnrollCount-1, ClearOpposite>::run(dst, src);
@@ -480,7 +467,7 @@ struct triangular_assignment_selector
template<typename Derived1, typename Derived2, unsigned int Mode, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, Mode, 0, ClearOpposite>
{
- inline static void run(Derived1 &, const Derived2 &) {}
+ static inline void run(Derived1 &, const Derived2 &) {}
};
template<typename Derived1, typename Derived2, bool ClearOpposite>
@@ -488,7 +475,7 @@ struct triangular_assignment_selector<Derived1, Derived2, Upper, Dynamic, ClearO
{
typedef typename Derived1::Index Index;
typedef typename Derived1::Scalar Scalar;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
for(Index j = 0; j < dst.cols(); ++j)
{
@@ -506,7 +493,7 @@ template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, Lower, Dynamic, ClearOpposite>
{
typedef typename Derived1::Index Index;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
for(Index j = 0; j < dst.cols(); ++j)
{
@@ -524,7 +511,7 @@ template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, StrictlyUpper, Dynamic, ClearOpposite>
{
typedef typename Derived1::Index Index;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
for(Index j = 0; j < dst.cols(); ++j)
{
@@ -542,7 +529,7 @@ template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, StrictlyLower, Dynamic, ClearOpposite>
{
typedef typename Derived1::Index Index;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
for(Index j = 0; j < dst.cols(); ++j)
{
@@ -560,7 +547,7 @@ template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, UnitUpper, Dynamic, ClearOpposite>
{
typedef typename Derived1::Index Index;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
for(Index j = 0; j < dst.cols(); ++j)
{
@@ -580,7 +567,7 @@ template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, UnitLower, Dynamic, ClearOpposite>
{
typedef typename Derived1::Index Index;
- inline static void run(Derived1 &dst, const Derived2 &src)
+ static inline void run(Derived1 &dst, const Derived2 &src)
{
for(Index j = 0; j < dst.cols(); ++j)
{
@@ -835,4 +822,6 @@ bool MatrixBase<Derived>::isLowerTriangular(RealScalar prec) const
return true;
}
+} // end namespace Eigen
+
#endif // EIGEN_TRIANGULARMATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Core/VectorBlock.h b/extern/Eigen3/Eigen/src/Core/VectorBlock.h
index 858e4c7865a..6f4effca055 100644
--- a/extern/Eigen3/Eigen/src/Core/VectorBlock.h
+++ b/extern/Eigen3/Eigen/src/Core/VectorBlock.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_VECTORBLOCK_H
#define EIGEN_VECTORBLOCK_H
+namespace Eigen {
+
/** \class VectorBlock
* \ingroup Core_Module
*
@@ -292,5 +279,6 @@ DenseBase<Derived>::tail() const
return typename ConstFixedSegmentReturnType<Size>::Type(derived(), size() - Size);
}
+} // end namespace Eigen
#endif // EIGEN_VECTORBLOCK_H
diff --git a/extern/Eigen3/Eigen/src/Core/VectorwiseOp.h b/extern/Eigen3/Eigen/src/Core/VectorwiseOp.h
index 20f6881575b..862c0f33608 100644
--- a/extern/Eigen3/Eigen/src/Core/VectorwiseOp.h
+++ b/extern/Eigen3/Eigen/src/Core/VectorwiseOp.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PARTIAL_REDUX_H
#define EIGEN_PARTIAL_REDUX_H
+namespace Eigen {
+
/** \class PartialReduxExpr
* \ingroup Core_Module
*
@@ -110,7 +97,7 @@ class PartialReduxExpr : internal::no_assignment_operator,
}
protected:
- const MatrixTypeNested m_matrix;
+ MatrixTypeNested m_matrix;
const MemberOp m_functor;
};
@@ -237,7 +224,10 @@ template<typename ExpressionType, int Direction> class VectorwiseOp
typename ExtendedType<OtherDerived>::Type
extendedTo(const DenseBase<OtherDerived>& other) const
{
- EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived);
+ EIGEN_STATIC_ASSERT(EIGEN_IMPLIES(Direction==Vertical, OtherDerived::MaxColsAtCompileTime==1),
+ YOU_PASSED_A_ROW_VECTOR_BUT_A_COLUMN_VECTOR_WAS_EXPECTED)
+ EIGEN_STATIC_ASSERT(EIGEN_IMPLIES(Direction==Horizontal, OtherDerived::MaxRowsAtCompileTime==1),
+ YOU_PASSED_A_COLUMN_VECTOR_BUT_A_ROW_VECTOR_WAS_EXPECTED)
return typename ExtendedType<OtherDerived>::Type
(other.derived(),
Direction==Vertical ? 1 : m_matrix.rows(),
@@ -418,10 +408,9 @@ template<typename ExpressionType, int Direction> class VectorwiseOp
ExpressionType& operator=(const DenseBase<OtherDerived>& other)
{
EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
+ EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived)
//eigen_assert((m_matrix.isNull()) == (other.isNull())); FIXME
- for(Index j=0; j<subVectors(); ++j)
- subVector(j) = other;
- return const_cast<ExpressionType&>(m_matrix);
+ return const_cast<ExpressionType&>(m_matrix = extendedTo(other.derived()));
}
/** Adds the vector \a other to each subvector of \c *this */
@@ -429,9 +418,8 @@ template<typename ExpressionType, int Direction> class VectorwiseOp
ExpressionType& operator+=(const DenseBase<OtherDerived>& other)
{
EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
- for(Index j=0; j<subVectors(); ++j)
- subVector(j) += other.derived();
- return const_cast<ExpressionType&>(m_matrix);
+ EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived)
+ return const_cast<ExpressionType&>(m_matrix += extendedTo(other.derived()));
}
/** Substracts the vector \a other to each subvector of \c *this */
@@ -439,8 +427,29 @@ template<typename ExpressionType, int Direction> class VectorwiseOp
ExpressionType& operator-=(const DenseBase<OtherDerived>& other)
{
EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
- for(Index j=0; j<subVectors(); ++j)
- subVector(j) -= other.derived();
+ EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived)
+ return const_cast<ExpressionType&>(m_matrix -= extendedTo(other.derived()));
+ }
+
+ /** Multiples each subvector of \c *this by the vector \a other */
+ template<typename OtherDerived>
+ ExpressionType& operator*=(const DenseBase<OtherDerived>& other)
+ {
+ EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
+ EIGEN_STATIC_ASSERT_ARRAYXPR(ExpressionType)
+ EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived)
+ m_matrix *= extendedTo(other.derived());
+ return const_cast<ExpressionType&>(m_matrix);
+ }
+
+ /** Divides each subvector of \c *this by the vector \a other */
+ template<typename OtherDerived>
+ ExpressionType& operator/=(const DenseBase<OtherDerived>& other)
+ {
+ EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
+ EIGEN_STATIC_ASSERT_ARRAYXPR(ExpressionType)
+ EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived)
+ m_matrix /= extendedTo(other.derived());
return const_cast<ExpressionType&>(m_matrix);
}
@@ -451,7 +460,8 @@ template<typename ExpressionType, int Direction> class VectorwiseOp
const typename ExtendedType<OtherDerived>::Type>
operator+(const DenseBase<OtherDerived>& other) const
{
- EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived);
+ EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
+ EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived)
return m_matrix + extendedTo(other.derived());
}
@@ -462,10 +472,39 @@ template<typename ExpressionType, int Direction> class VectorwiseOp
const typename ExtendedType<OtherDerived>::Type>
operator-(const DenseBase<OtherDerived>& other) const
{
- EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived);
+ EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
+ EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived)
return m_matrix - extendedTo(other.derived());
}
+ /** Returns the expression where each subvector is the product of the vector \a other
+ * by the corresponding subvector of \c *this */
+ template<typename OtherDerived> EIGEN_STRONG_INLINE
+ CwiseBinaryOp<internal::scalar_product_op<Scalar>,
+ const ExpressionTypeNestedCleaned,
+ const typename ExtendedType<OtherDerived>::Type>
+ operator*(const DenseBase<OtherDerived>& other) const
+ {
+ EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
+ EIGEN_STATIC_ASSERT_ARRAYXPR(ExpressionType)
+ EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived)
+ return m_matrix * extendedTo(other.derived());
+ }
+
+ /** Returns the expression where each subvector is the quotient of the corresponding
+ * subvector of \c *this by the vector \a other */
+ template<typename OtherDerived>
+ CwiseBinaryOp<internal::scalar_quotient_op<Scalar>,
+ const ExpressionTypeNestedCleaned,
+ const typename ExtendedType<OtherDerived>::Type>
+ operator/(const DenseBase<OtherDerived>& other) const
+ {
+ EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
+ EIGEN_STATIC_ASSERT_ARRAYXPR(ExpressionType)
+ EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived)
+ return m_matrix / extendedTo(other.derived());
+ }
+
/////////// Geometry module ///////////
#if EIGEN2_SUPPORT_STAGE > STAGE20_RESOLVE_API_CONFLICTS
@@ -509,7 +548,7 @@ template<typename ExpressionType, int Direction> class VectorwiseOp
* Example: \include MatrixBase_colwise.cpp
* Output: \verbinclude MatrixBase_colwise.out
*
- * \sa rowwise(), class VectorwiseOp
+ * \sa rowwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting
*/
template<typename Derived>
inline const typename DenseBase<Derived>::ConstColwiseReturnType
@@ -520,7 +559,7 @@ DenseBase<Derived>::colwise() const
/** \returns a writable VectorwiseOp wrapper of *this providing additional partial reduction operations
*
- * \sa rowwise(), class VectorwiseOp
+ * \sa rowwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting
*/
template<typename Derived>
inline typename DenseBase<Derived>::ColwiseReturnType
@@ -534,7 +573,7 @@ DenseBase<Derived>::colwise()
* Example: \include MatrixBase_rowwise.cpp
* Output: \verbinclude MatrixBase_rowwise.out
*
- * \sa colwise(), class VectorwiseOp
+ * \sa colwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting
*/
template<typename Derived>
inline const typename DenseBase<Derived>::ConstRowwiseReturnType
@@ -545,7 +584,7 @@ DenseBase<Derived>::rowwise() const
/** \returns a writable VectorwiseOp wrapper of *this providing additional partial reduction operations
*
- * \sa colwise(), class VectorwiseOp
+ * \sa colwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting
*/
template<typename Derived>
inline typename DenseBase<Derived>::RowwiseReturnType
@@ -554,4 +593,6 @@ DenseBase<Derived>::rowwise()
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_PARTIAL_REDUX_H
diff --git a/extern/Eigen3/Eigen/src/Core/Visitor.h b/extern/Eigen3/Eigen/src/Core/Visitor.h
index 378ebcba174..916bfd096a9 100644
--- a/extern/Eigen3/Eigen/src/Core/Visitor.h
+++ b/extern/Eigen3/Eigen/src/Core/Visitor.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_VISITOR_H
#define EIGEN_VISITOR_H
+namespace Eigen {
+
namespace internal {
template<typename Visitor, typename Derived, int UnrollCount>
@@ -35,7 +22,7 @@ struct visitor_impl
row = (UnrollCount-1) % Derived::RowsAtCompileTime
};
- inline static void run(const Derived &mat, Visitor& visitor)
+ static inline void run(const Derived &mat, Visitor& visitor)
{
visitor_impl<Visitor, Derived, UnrollCount-1>::run(mat, visitor);
visitor(mat.coeff(row, col), row, col);
@@ -45,7 +32,7 @@ struct visitor_impl
template<typename Visitor, typename Derived>
struct visitor_impl<Visitor, Derived, 1>
{
- inline static void run(const Derived &mat, Visitor& visitor)
+ static inline void run(const Derived &mat, Visitor& visitor)
{
return visitor.init(mat.coeff(0, 0), 0, 0);
}
@@ -55,7 +42,7 @@ template<typename Visitor, typename Derived>
struct visitor_impl<Visitor, Derived, Dynamic>
{
typedef typename Derived::Index Index;
- inline static void run(const Derived& mat, Visitor& visitor)
+ static inline void run(const Derived& mat, Visitor& visitor)
{
visitor.init(mat.coeff(0,0), 0, 0);
for(Index i = 1; i < mat.rows(); ++i)
@@ -245,4 +232,6 @@ DenseBase<Derived>::maxCoeff(IndexType* index) const
return maxVisitor.res;
}
+} // end namespace Eigen
+
#endif // EIGEN_VISITOR_H
diff --git a/extern/Eigen3/Eigen/src/Core/arch/AltiVec/Complex.h b/extern/Eigen3/Eigen/src/Core/arch/AltiVec/Complex.h
index f8adf1b6385..68d9a2bff8d 100644
--- a/extern/Eigen3/Eigen/src/Core/arch/AltiVec/Complex.h
+++ b/extern/Eigen3/Eigen/src/Core/arch/AltiVec/Complex.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COMPLEX_ALTIVEC_H
#define EIGEN_COMPLEX_ALTIVEC_H
+namespace Eigen {
+
namespace internal {
static Packet4ui p4ui_CONJ_XOR = vec_mergeh((Packet4ui)p4i_ZERO, (Packet4ui)p4f_ZERO_);//{ 0x00000000, 0x80000000, 0x00000000, 0x80000000 };
@@ -168,7 +155,7 @@ template<> EIGEN_STRONG_INLINE std::complex<float> predux_mul<Packet2cf>(const P
template<int Offset>
struct palign_impl<Offset,Packet2cf>
{
- EIGEN_STRONG_INLINE static void run(Packet2cf& first, const Packet2cf& second)
+ static EIGEN_STRONG_INLINE void run(Packet2cf& first, const Packet2cf& second)
{
if (Offset==1)
{
@@ -225,4 +212,6 @@ template<> EIGEN_STRONG_INLINE Packet2cf pcplxflip<Packet2cf>(const Packet2cf& x
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_COMPLEX_ALTIVEC_H
diff --git a/extern/Eigen3/Eigen/src/Core/arch/AltiVec/PacketMath.h b/extern/Eigen3/Eigen/src/Core/arch/AltiVec/PacketMath.h
index dc34ebbd660..75de1931198 100644
--- a/extern/Eigen3/Eigen/src/Core/arch/AltiVec/PacketMath.h
+++ b/extern/Eigen3/Eigen/src/Core/arch/AltiVec/PacketMath.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Konstantinos Margaritis <markos@codex.gr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PACKET_MATH_ALTIVEC_H
#define EIGEN_PACKET_MATH_ALTIVEC_H
+namespace Eigen {
+
namespace internal {
#ifndef EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD
@@ -487,7 +474,7 @@ template<> EIGEN_STRONG_INLINE int predux_max<Packet4i>(const Packet4i& a)
template<int Offset>
struct palign_impl<Offset,Packet4f>
{
- EIGEN_STRONG_INLINE static void run(Packet4f& first, const Packet4f& second)
+ static EIGEN_STRONG_INLINE void run(Packet4f& first, const Packet4f& second)
{
if (Offset!=0)
first = vec_sld(first, second, Offset*4);
@@ -497,7 +484,7 @@ struct palign_impl<Offset,Packet4f>
template<int Offset>
struct palign_impl<Offset,Packet4i>
{
- EIGEN_STRONG_INLINE static void run(Packet4i& first, const Packet4i& second)
+ static EIGEN_STRONG_INLINE void run(Packet4i& first, const Packet4i& second)
{
if (Offset!=0)
first = vec_sld(first, second, Offset*4);
@@ -506,4 +493,6 @@ struct palign_impl<Offset,Packet4i>
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_PACKET_MATH_ALTIVEC_H
diff --git a/extern/Eigen3/Eigen/src/Core/arch/Default/Settings.h b/extern/Eigen3/Eigen/src/Core/arch/Default/Settings.h
index 957adc8fe42..097373c84dc 100644
--- a/extern/Eigen3/Eigen/src/Core/arch/Default/Settings.h
+++ b/extern/Eigen3/Eigen/src/Core/arch/Default/Settings.h
@@ -4,24 +4,9 @@
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
/* All the parameters defined in this file can be specialized in the
diff --git a/extern/Eigen3/Eigen/src/Core/arch/NEON/Complex.h b/extern/Eigen3/Eigen/src/Core/arch/NEON/Complex.h
index 212887184c2..795b4be7303 100644
--- a/extern/Eigen3/Eigen/src/Core/arch/NEON/Complex.h
+++ b/extern/Eigen3/Eigen/src/Core/arch/NEON/Complex.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COMPLEX_NEON_H
#define EIGEN_COMPLEX_NEON_H
+namespace Eigen {
+
namespace internal {
static uint32x4_t p4ui_CONJ_XOR = EIGEN_INIT_NEON_PACKET4(0x00000000, 0x80000000, 0x00000000, 0x80000000);
@@ -267,4 +254,6 @@ template<> EIGEN_STRONG_INLINE Packet2cf pdiv<Packet2cf>(const Packet2cf& a, con
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_COMPLEX_NEON_H
diff --git a/extern/Eigen3/Eigen/src/Core/arch/NEON/PacketMath.h b/extern/Eigen3/Eigen/src/Core/arch/NEON/PacketMath.h
index 6c7cd159097..a20250f7c65 100644
--- a/extern/Eigen3/Eigen/src/Core/arch/NEON/PacketMath.h
+++ b/extern/Eigen3/Eigen/src/Core/arch/NEON/PacketMath.h
@@ -5,28 +5,15 @@
// Copyright (C) 2010 Konstantinos Margaritis <markos@codex.gr>
// Heavily based on Gael's SSE version.
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PACKET_MATH_NEON_H
#define EIGEN_PACKET_MATH_NEON_H
+namespace Eigen {
+
namespace internal {
#ifndef EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD
@@ -158,7 +145,8 @@ template<> EIGEN_STRONG_INLINE Packet4i pdiv<Packet4i>(const Packet4i& /*a*/, co
}
// for some weird raisons, it has to be overloaded for packet of integers
-template<> EIGEN_STRONG_INLINE Packet4i pmadd(const Packet4i& a, const Packet4i& b, const Packet4i& c) { return padd(pmul(a,b), c); }
+template<> EIGEN_STRONG_INLINE Packet4f pmadd(const Packet4f& a, const Packet4f& b, const Packet4f& c) { return vmlaq_f32(c,a,b); }
+template<> EIGEN_STRONG_INLINE Packet4i pmadd(const Packet4i& a, const Packet4i& b, const Packet4i& c) { return vmlaq_s32(c,a,b); }
template<> EIGEN_STRONG_INLINE Packet4f pmin<Packet4f>(const Packet4f& a, const Packet4f& b) { return vminq_f32(a,b); }
template<> EIGEN_STRONG_INLINE Packet4i pmin<Packet4i>(const Packet4i& a, const Packet4i& b) { return vminq_s32(a,b); }
@@ -431,4 +419,6 @@ PALIGN_NEON(3,Packet4i,vextq_s32)
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_PACKET_MATH_NEON_H
diff --git a/extern/Eigen3/Eigen/src/Core/arch/SSE/Complex.h b/extern/Eigen3/Eigen/src/Core/arch/SSE/Complex.h
index c352bb3e6cf..12df987754c 100644
--- a/extern/Eigen3/Eigen/src/Core/arch/SSE/Complex.h
+++ b/extern/Eigen3/Eigen/src/Core/arch/SSE/Complex.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COMPLEX_SSE_H
#define EIGEN_COMPLEX_SSE_H
+namespace Eigen {
+
namespace internal {
//---------- float ----------
@@ -102,7 +89,7 @@ template<> EIGEN_STRONG_INLINE Packet2cf pset1<Packet2cf>(const std::complex<flo
Packet2cf res;
#if EIGEN_GNUC_AT_MOST(4,2)
// workaround annoying "may be used uninitialized in this function" warning with gcc 4.2
- res.v = _mm_loadl_pi(_mm_set1_ps(0.0f), (const __m64*)&from);
+ res.v = _mm_loadl_pi(_mm_set1_ps(0.0f), reinterpret_cast<const __m64*>(&from));
#else
res.v = _mm_loadl_pi(res.v, (const __m64*)&from);
#endif
@@ -151,7 +138,7 @@ template<> EIGEN_STRONG_INLINE std::complex<float> predux_mul<Packet2cf>(const P
template<int Offset>
struct palign_impl<Offset,Packet2cf>
{
- EIGEN_STRONG_INLINE static void run(Packet2cf& first, const Packet2cf& second)
+ static EIGEN_STRONG_INLINE void run(Packet2cf& first, const Packet2cf& second)
{
if (Offset==1)
{
@@ -350,7 +337,7 @@ template<> EIGEN_STRONG_INLINE std::complex<double> predux_mul<Packet1cd>(const
template<int Offset>
struct palign_impl<Offset,Packet1cd>
{
- EIGEN_STRONG_INLINE static void run(Packet1cd& /*first*/, const Packet1cd& /*second*/)
+ static EIGEN_STRONG_INLINE void run(Packet1cd& /*first*/, const Packet1cd& /*second*/)
{
// FIXME is it sure we never have to align a Packet1cd?
// Even though a std::complex<double> has 16 bytes, it is not necessarily aligned on a 16 bytes boundary...
@@ -444,4 +431,6 @@ EIGEN_STRONG_INLINE Packet1cd pcplxflip/*<Packet1cd>*/(const Packet1cd& x)
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_COMPLEX_SSE_H
diff --git a/extern/Eigen3/Eigen/src/Core/arch/SSE/MathFunctions.h b/extern/Eigen3/Eigen/src/Core/arch/SSE/MathFunctions.h
index 9d56d82180b..3f41a4e2600 100644
--- a/extern/Eigen3/Eigen/src/Core/arch/SSE/MathFunctions.h
+++ b/extern/Eigen3/Eigen/src/Core/arch/SSE/MathFunctions.h
@@ -4,24 +4,9 @@
// Copyright (C) 2007 Julien Pommier
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
/* The sin, cos, exp, and log functions of this file come from
* Julien Pommier's sse math library: http://gruntthepeon.free.fr/ssemath/
@@ -30,6 +15,8 @@
#ifndef EIGEN_MATH_FUNCTIONS_SSE_H
#define EIGEN_MATH_FUNCTIONS_SSE_H
+namespace Eigen {
+
namespace internal {
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
@@ -121,7 +108,7 @@ Packet4f pexp<Packet4f>(const Packet4f& _x)
_EIGEN_DECLARE_CONST_Packet4i(0x7f, 0x7f);
- _EIGEN_DECLARE_CONST_Packet4f(exp_hi, 88.3762626647949f);
+ _EIGEN_DECLARE_CONST_Packet4f(exp_hi, 88.3762626647950f);
_EIGEN_DECLARE_CONST_Packet4f(exp_lo, -88.3762626647949f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_LOG2EF, 1.44269504088896341f);
@@ -168,7 +155,7 @@ Packet4f pexp<Packet4f>(const Packet4f& _x)
y = pmadd(y, z, x);
y = padd(y, p4f_1);
- /* build 2^n */
+ // build 2^n
emm0 = _mm_cvttps_epi32(fx);
emm0 = _mm_add_epi32(emm0, p4i_0x7f);
emm0 = _mm_slli_epi32(emm0, 23);
@@ -392,4 +379,6 @@ Packet4f psqrt<Packet4f>(const Packet4f& _x)
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_MATH_FUNCTIONS_SSE_H
diff --git a/extern/Eigen3/Eigen/src/Core/arch/SSE/PacketMath.h b/extern/Eigen3/Eigen/src/Core/arch/SSE/PacketMath.h
index 908e27368e8..10d9182190f 100644
--- a/extern/Eigen3/Eigen/src/Core/arch/SSE/PacketMath.h
+++ b/extern/Eigen3/Eigen/src/Core/arch/SSE/PacketMath.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PACKET_MATH_SSE_H
#define EIGEN_PACKET_MATH_SSE_H
+namespace Eigen {
+
namespace internal {
#ifndef EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD
@@ -110,9 +97,18 @@ template<> struct unpacket_traits<Packet4f> { typedef float type; enum {size=4}
template<> struct unpacket_traits<Packet2d> { typedef double type; enum {size=2}; };
template<> struct unpacket_traits<Packet4i> { typedef int type; enum {size=4}; };
+#if defined(_MSC_VER) && (_MSC_VER==1500)
+// Workaround MSVC 9 internal compiler error.
+// TODO: It has been detected with win64 builds (amd64), so let's check whether it also happens in 32bits+SSE mode
+// TODO: let's check whether there does not exist a better fix, like adding a pset0() function. (it crashed on pset1(0)).
+template<> EIGEN_STRONG_INLINE Packet4f pset1<Packet4f>(const float& from) { return _mm_set_ps(from,from,from,from); }
+template<> EIGEN_STRONG_INLINE Packet2d pset1<Packet2d>(const double& from) { return _mm_set_pd(from,from); }
+template<> EIGEN_STRONG_INLINE Packet4i pset1<Packet4i>(const int& from) { return _mm_set_epi32(from,from,from,from); }
+#else
template<> EIGEN_STRONG_INLINE Packet4f pset1<Packet4f>(const float& from) { return _mm_set1_ps(from); }
template<> EIGEN_STRONG_INLINE Packet2d pset1<Packet2d>(const double& from) { return _mm_set1_pd(from); }
template<> EIGEN_STRONG_INLINE Packet4i pset1<Packet4i>(const int& from) { return _mm_set1_epi32(from); }
+#endif
template<> EIGEN_STRONG_INLINE Packet4f plset<float>(const float& a) { return _mm_add_ps(pset1<Packet4f>(a), _mm_set_ps(3,2,1,0)); }
template<> EIGEN_STRONG_INLINE Packet2d plset<double>(const double& a) { return _mm_add_pd(pset1<Packet2d>(a),_mm_set_pd(1,0)); }
@@ -282,7 +278,7 @@ template<> EIGEN_STRONG_INLINE Packet4i ploadu<Packet4i>(const int* from)
template<> EIGEN_STRONG_INLINE Packet4f ploaddup<Packet4f>(const float* from)
{
- return vec4f_swizzle1(_mm_castpd_ps(_mm_load_sd((const double*)from)), 0, 0, 1, 1);
+ return vec4f_swizzle1(_mm_castpd_ps(_mm_load_sd(reinterpret_cast<const double*>(from))), 0, 0, 1, 1);
}
template<> EIGEN_STRONG_INLINE Packet2d ploaddup<Packet2d>(const double* from)
{ return pset1<Packet2d>(from[0]); }
@@ -302,8 +298,8 @@ template<> EIGEN_STRONG_INLINE void pstoreu<double>(double* to, const Packet2d&
_mm_storel_pd((to), from);
_mm_storeh_pd((to+1), from);
}
-template<> EIGEN_STRONG_INLINE void pstoreu<float>(float* to, const Packet4f& from) { EIGEN_DEBUG_UNALIGNED_STORE pstoreu((double*)to, _mm_castps_pd(from)); }
-template<> EIGEN_STRONG_INLINE void pstoreu<int>(int* to, const Packet4i& from) { EIGEN_DEBUG_UNALIGNED_STORE pstoreu((double*)to, _mm_castsi128_pd(from)); }
+template<> EIGEN_STRONG_INLINE void pstoreu<float>(float* to, const Packet4f& from) { EIGEN_DEBUG_UNALIGNED_STORE pstoreu(reinterpret_cast<double*>(to), _mm_castps_pd(from)); }
+template<> EIGEN_STRONG_INLINE void pstoreu<int>(int* to, const Packet4i& from) { EIGEN_DEBUG_UNALIGNED_STORE pstoreu(reinterpret_cast<double*>(to), _mm_castsi128_pd(from)); }
// some compilers might be tempted to perform multiple moves instead of using a vector path.
template<> EIGEN_STRONG_INLINE void pstore1<Packet4f>(float* to, const float& a)
@@ -541,7 +537,7 @@ template<> EIGEN_STRONG_INLINE int predux_max<Packet4i>(const Packet4i& a)
template<int Offset>
struct palign_impl<Offset,Packet4f>
{
- EIGEN_STRONG_INLINE static void run(Packet4f& first, const Packet4f& second)
+ static EIGEN_STRONG_INLINE void run(Packet4f& first, const Packet4f& second)
{
if (Offset!=0)
first = _mm_castsi128_ps(_mm_alignr_epi8(_mm_castps_si128(second), _mm_castps_si128(first), Offset*4));
@@ -551,7 +547,7 @@ struct palign_impl<Offset,Packet4f>
template<int Offset>
struct palign_impl<Offset,Packet4i>
{
- EIGEN_STRONG_INLINE static void run(Packet4i& first, const Packet4i& second)
+ static EIGEN_STRONG_INLINE void run(Packet4i& first, const Packet4i& second)
{
if (Offset!=0)
first = _mm_alignr_epi8(second,first, Offset*4);
@@ -561,7 +557,7 @@ struct palign_impl<Offset,Packet4i>
template<int Offset>
struct palign_impl<Offset,Packet2d>
{
- EIGEN_STRONG_INLINE static void run(Packet2d& first, const Packet2d& second)
+ static EIGEN_STRONG_INLINE void run(Packet2d& first, const Packet2d& second)
{
if (Offset==1)
first = _mm_castsi128_pd(_mm_alignr_epi8(_mm_castpd_si128(second), _mm_castpd_si128(first), 8));
@@ -572,7 +568,7 @@ struct palign_impl<Offset,Packet2d>
template<int Offset>
struct palign_impl<Offset,Packet4f>
{
- EIGEN_STRONG_INLINE static void run(Packet4f& first, const Packet4f& second)
+ static EIGEN_STRONG_INLINE void run(Packet4f& first, const Packet4f& second)
{
if (Offset==1)
{
@@ -595,7 +591,7 @@ struct palign_impl<Offset,Packet4f>
template<int Offset>
struct palign_impl<Offset,Packet4i>
{
- EIGEN_STRONG_INLINE static void run(Packet4i& first, const Packet4i& second)
+ static EIGEN_STRONG_INLINE void run(Packet4i& first, const Packet4i& second)
{
if (Offset==1)
{
@@ -618,7 +614,7 @@ struct palign_impl<Offset,Packet4i>
template<int Offset>
struct palign_impl<Offset,Packet2d>
{
- EIGEN_STRONG_INLINE static void run(Packet2d& first, const Packet2d& second)
+ static EIGEN_STRONG_INLINE void run(Packet2d& first, const Packet2d& second)
{
if (Offset==1)
{
@@ -631,4 +627,6 @@ struct palign_impl<Offset,Packet2d>
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_PACKET_MATH_SSE_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/CoeffBasedProduct.h b/extern/Eigen3/Eigen/src/Core/products/CoeffBasedProduct.h
index dc20f7e1e29..403d25fa9eb 100644
--- a/extern/Eigen3/Eigen/src/Core/products/CoeffBasedProduct.h
+++ b/extern/Eigen3/Eigen/src/Core/products/CoeffBasedProduct.h
@@ -4,28 +4,15 @@
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COEFFBASED_PRODUCT_H
#define EIGEN_COEFFBASED_PRODUCT_H
+namespace Eigen {
+
namespace internal {
/*********************************************************************************
@@ -224,8 +211,8 @@ class CoeffBasedProduct
{ return reinterpret_cast<const LazyCoeffBasedProductType&>(*this).diagonal(index); }
protected:
- const LhsNested m_lhs;
- const RhsNested m_rhs;
+ typename internal::add_const_on_value_type<LhsNested>::type m_lhs;
+ typename internal::add_const_on_value_type<RhsNested>::type m_rhs;
mutable PlainObject m_result;
};
@@ -252,7 +239,7 @@ template<int UnrollingIndex, typename Lhs, typename Rhs, typename RetScalar>
struct product_coeff_impl<DefaultTraversal, UnrollingIndex, Lhs, Rhs, RetScalar>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, RetScalar &res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, RetScalar &res)
{
product_coeff_impl<DefaultTraversal, UnrollingIndex-1, Lhs, Rhs, RetScalar>::run(row, col, lhs, rhs, res);
res += lhs.coeff(row, UnrollingIndex) * rhs.coeff(UnrollingIndex, col);
@@ -263,7 +250,7 @@ template<typename Lhs, typename Rhs, typename RetScalar>
struct product_coeff_impl<DefaultTraversal, 0, Lhs, Rhs, RetScalar>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, RetScalar &res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, RetScalar &res)
{
res = lhs.coeff(row, 0) * rhs.coeff(0, col);
}
@@ -273,7 +260,7 @@ template<typename Lhs, typename Rhs, typename RetScalar>
struct product_coeff_impl<DefaultTraversal, Dynamic, Lhs, Rhs, RetScalar>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, RetScalar& res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, RetScalar& res)
{
eigen_assert(lhs.cols()>0 && "you are using a non initialized matrix");
res = lhs.coeff(row, 0) * rhs.coeff(0, col);
@@ -291,7 +278,7 @@ struct product_coeff_vectorized_unroller
{
typedef typename Lhs::Index Index;
enum { PacketSize = packet_traits<typename Lhs::Scalar>::size };
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, typename Lhs::PacketScalar &pres)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, typename Lhs::PacketScalar &pres)
{
product_coeff_vectorized_unroller<UnrollingIndex-PacketSize, Lhs, Rhs, Packet>::run(row, col, lhs, rhs, pres);
pres = padd(pres, pmul( lhs.template packet<Aligned>(row, UnrollingIndex) , rhs.template packet<Aligned>(UnrollingIndex, col) ));
@@ -302,7 +289,7 @@ template<typename Lhs, typename Rhs, typename Packet>
struct product_coeff_vectorized_unroller<0, Lhs, Rhs, Packet>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, typename Lhs::PacketScalar &pres)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, typename Lhs::PacketScalar &pres)
{
pres = pmul(lhs.template packet<Aligned>(row, 0) , rhs.template packet<Aligned>(0, col));
}
@@ -314,7 +301,7 @@ struct product_coeff_impl<InnerVectorizedTraversal, UnrollingIndex, Lhs, Rhs, Re
typedef typename Lhs::PacketScalar Packet;
typedef typename Lhs::Index Index;
enum { PacketSize = packet_traits<typename Lhs::Scalar>::size };
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, RetScalar &res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, RetScalar &res)
{
Packet pres;
product_coeff_vectorized_unroller<UnrollingIndex+1-PacketSize, Lhs, Rhs, Packet>::run(row, col, lhs, rhs, pres);
@@ -327,7 +314,7 @@ template<typename Lhs, typename Rhs, int LhsRows = Lhs::RowsAtCompileTime, int R
struct product_coeff_vectorized_dyn_selector
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, typename Lhs::Scalar &res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, typename Lhs::Scalar &res)
{
res = lhs.row(row).transpose().cwiseProduct(rhs.col(col)).sum();
}
@@ -339,7 +326,7 @@ template<typename Lhs, typename Rhs, int RhsCols>
struct product_coeff_vectorized_dyn_selector<Lhs,Rhs,1,RhsCols>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index /*row*/, Index col, const Lhs& lhs, const Rhs& rhs, typename Lhs::Scalar &res)
+ static EIGEN_STRONG_INLINE void run(Index /*row*/, Index col, const Lhs& lhs, const Rhs& rhs, typename Lhs::Scalar &res)
{
res = lhs.transpose().cwiseProduct(rhs.col(col)).sum();
}
@@ -349,7 +336,7 @@ template<typename Lhs, typename Rhs, int LhsRows>
struct product_coeff_vectorized_dyn_selector<Lhs,Rhs,LhsRows,1>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index /*col*/, const Lhs& lhs, const Rhs& rhs, typename Lhs::Scalar &res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index /*col*/, const Lhs& lhs, const Rhs& rhs, typename Lhs::Scalar &res)
{
res = lhs.row(row).transpose().cwiseProduct(rhs).sum();
}
@@ -359,7 +346,7 @@ template<typename Lhs, typename Rhs>
struct product_coeff_vectorized_dyn_selector<Lhs,Rhs,1,1>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index /*row*/, Index /*col*/, const Lhs& lhs, const Rhs& rhs, typename Lhs::Scalar &res)
+ static EIGEN_STRONG_INLINE void run(Index /*row*/, Index /*col*/, const Lhs& lhs, const Rhs& rhs, typename Lhs::Scalar &res)
{
res = lhs.transpose().cwiseProduct(rhs).sum();
}
@@ -369,7 +356,7 @@ template<typename Lhs, typename Rhs, typename RetScalar>
struct product_coeff_impl<InnerVectorizedTraversal, Dynamic, Lhs, Rhs, RetScalar>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, typename Lhs::Scalar &res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, typename Lhs::Scalar &res)
{
product_coeff_vectorized_dyn_selector<Lhs,Rhs>::run(row, col, lhs, rhs, res);
}
@@ -383,7 +370,7 @@ template<int UnrollingIndex, typename Lhs, typename Rhs, typename Packet, int Lo
struct product_packet_impl<RowMajor, UnrollingIndex, Lhs, Rhs, Packet, LoadMode>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet &res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet &res)
{
product_packet_impl<RowMajor, UnrollingIndex-1, Lhs, Rhs, Packet, LoadMode>::run(row, col, lhs, rhs, res);
res = pmadd(pset1<Packet>(lhs.coeff(row, UnrollingIndex)), rhs.template packet<LoadMode>(UnrollingIndex, col), res);
@@ -394,7 +381,7 @@ template<int UnrollingIndex, typename Lhs, typename Rhs, typename Packet, int Lo
struct product_packet_impl<ColMajor, UnrollingIndex, Lhs, Rhs, Packet, LoadMode>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet &res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet &res)
{
product_packet_impl<ColMajor, UnrollingIndex-1, Lhs, Rhs, Packet, LoadMode>::run(row, col, lhs, rhs, res);
res = pmadd(lhs.template packet<LoadMode>(row, UnrollingIndex), pset1<Packet>(rhs.coeff(UnrollingIndex, col)), res);
@@ -405,7 +392,7 @@ template<typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct product_packet_impl<RowMajor, 0, Lhs, Rhs, Packet, LoadMode>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet &res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet &res)
{
res = pmul(pset1<Packet>(lhs.coeff(row, 0)),rhs.template packet<LoadMode>(0, col));
}
@@ -415,7 +402,7 @@ template<typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct product_packet_impl<ColMajor, 0, Lhs, Rhs, Packet, LoadMode>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet &res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet &res)
{
res = pmul(lhs.template packet<LoadMode>(row, 0), pset1<Packet>(rhs.coeff(0, col)));
}
@@ -425,7 +412,7 @@ template<typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct product_packet_impl<RowMajor, Dynamic, Lhs, Rhs, Packet, LoadMode>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet& res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet& res)
{
eigen_assert(lhs.cols()>0 && "you are using a non initialized matrix");
res = pmul(pset1<Packet>(lhs.coeff(row, 0)),rhs.template packet<LoadMode>(0, col));
@@ -438,7 +425,7 @@ template<typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct product_packet_impl<ColMajor, Dynamic, Lhs, Rhs, Packet, LoadMode>
{
typedef typename Lhs::Index Index;
- EIGEN_STRONG_INLINE static void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet& res)
+ static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Packet& res)
{
eigen_assert(lhs.cols()>0 && "you are using a non initialized matrix");
res = pmul(lhs.template packet<LoadMode>(row, 0), pset1<Packet>(rhs.coeff(0, col)));
@@ -449,4 +436,6 @@ struct product_packet_impl<ColMajor, Dynamic, Lhs, Rhs, Packet, LoadMode>
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_COEFFBASED_PRODUCT_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/GeneralBlockPanelKernel.h b/extern/Eigen3/Eigen/src/Core/products/GeneralBlockPanelKernel.h
index cd1c37c780e..5eb03c98ccf 100644
--- a/extern/Eigen3/Eigen/src/Core/products/GeneralBlockPanelKernel.h
+++ b/extern/Eigen3/Eigen/src/Core/products/GeneralBlockPanelKernel.h
@@ -3,34 +3,23 @@
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GENERAL_BLOCK_PANEL_H
#define EIGEN_GENERAL_BLOCK_PANEL_H
+namespace Eigen {
+
namespace internal {
template<typename _LhsScalar, typename _RhsScalar, bool _ConjLhs=false, bool _ConjRhs=false>
class gebp_traits;
-inline std::ptrdiff_t manage_caching_sizes_second_if_negative(std::ptrdiff_t a, std::ptrdiff_t b)
+
+/** \internal \returns b if a<=0, and returns a otherwise. */
+inline std::ptrdiff_t manage_caching_sizes_helper(std::ptrdiff_t a, std::ptrdiff_t b)
{
return a<=0 ? b : a;
}
@@ -38,9 +27,14 @@ inline std::ptrdiff_t manage_caching_sizes_second_if_negative(std::ptrdiff_t a,
/** \internal */
inline void manage_caching_sizes(Action action, std::ptrdiff_t* l1=0, std::ptrdiff_t* l2=0)
{
- static std::ptrdiff_t m_l1CacheSize = manage_caching_sizes_second_if_negative(queryL1CacheSize(),8 * 1024);
- static std::ptrdiff_t m_l2CacheSize = manage_caching_sizes_second_if_negative(queryTopLevelCacheSize(),1*1024*1024);
-
+ static std::ptrdiff_t m_l1CacheSize = 0;
+ static std::ptrdiff_t m_l2CacheSize = 0;
+ if(m_l2CacheSize==0)
+ {
+ m_l1CacheSize = manage_caching_sizes_helper(queryL1CacheSize(),8 * 1024);
+ m_l2CacheSize = manage_caching_sizes_helper(queryTopLevelCacheSize(),1*1024*1024);
+ }
+
if(action==SetAction)
{
// set the cpu cache size and cache all block sizes from a global cache size in byte
@@ -533,7 +527,7 @@ struct gebp_kernel
ResPacketSize = Traits::ResPacketSize
};
- EIGEN_FLATTEN_ATTRIB
+ EIGEN_DONT_INLINE EIGEN_FLATTEN_ATTRIB
void operator()(ResScalar* res, Index resStride, const LhsScalar* blockA, const RhsScalar* blockB, Index rows, Index depth, Index cols, ResScalar alpha,
Index strideA=-1, Index strideB=-1, Index offsetA=0, Index offsetB=0, RhsScalar* unpackedB = 0)
{
@@ -595,64 +589,64 @@ struct gebp_kernel
if(nr==2)
{
LhsPacket A0, A1;
- RhsPacket B0;
+ RhsPacket B_0;
RhsPacket T0;
EIGEN_ASM_COMMENT("mybegin2");
traits.loadLhs(&blA[0*LhsProgress], A0);
traits.loadLhs(&blA[1*LhsProgress], A1);
- traits.loadRhs(&blB[0*RhsProgress], B0);
- traits.madd(A0,B0,C0,T0);
- traits.madd(A1,B0,C4,B0);
- traits.loadRhs(&blB[1*RhsProgress], B0);
- traits.madd(A0,B0,C1,T0);
- traits.madd(A1,B0,C5,B0);
+ traits.loadRhs(&blB[0*RhsProgress], B_0);
+ traits.madd(A0,B_0,C0,T0);
+ traits.madd(A1,B_0,C4,B_0);
+ traits.loadRhs(&blB[1*RhsProgress], B_0);
+ traits.madd(A0,B_0,C1,T0);
+ traits.madd(A1,B_0,C5,B_0);
traits.loadLhs(&blA[2*LhsProgress], A0);
traits.loadLhs(&blA[3*LhsProgress], A1);
- traits.loadRhs(&blB[2*RhsProgress], B0);
- traits.madd(A0,B0,C0,T0);
- traits.madd(A1,B0,C4,B0);
- traits.loadRhs(&blB[3*RhsProgress], B0);
- traits.madd(A0,B0,C1,T0);
- traits.madd(A1,B0,C5,B0);
+ traits.loadRhs(&blB[2*RhsProgress], B_0);
+ traits.madd(A0,B_0,C0,T0);
+ traits.madd(A1,B_0,C4,B_0);
+ traits.loadRhs(&blB[3*RhsProgress], B_0);
+ traits.madd(A0,B_0,C1,T0);
+ traits.madd(A1,B_0,C5,B_0);
traits.loadLhs(&blA[4*LhsProgress], A0);
traits.loadLhs(&blA[5*LhsProgress], A1);
- traits.loadRhs(&blB[4*RhsProgress], B0);
- traits.madd(A0,B0,C0,T0);
- traits.madd(A1,B0,C4,B0);
- traits.loadRhs(&blB[5*RhsProgress], B0);
- traits.madd(A0,B0,C1,T0);
- traits.madd(A1,B0,C5,B0);
+ traits.loadRhs(&blB[4*RhsProgress], B_0);
+ traits.madd(A0,B_0,C0,T0);
+ traits.madd(A1,B_0,C4,B_0);
+ traits.loadRhs(&blB[5*RhsProgress], B_0);
+ traits.madd(A0,B_0,C1,T0);
+ traits.madd(A1,B_0,C5,B_0);
traits.loadLhs(&blA[6*LhsProgress], A0);
traits.loadLhs(&blA[7*LhsProgress], A1);
- traits.loadRhs(&blB[6*RhsProgress], B0);
- traits.madd(A0,B0,C0,T0);
- traits.madd(A1,B0,C4,B0);
- traits.loadRhs(&blB[7*RhsProgress], B0);
- traits.madd(A0,B0,C1,T0);
- traits.madd(A1,B0,C5,B0);
+ traits.loadRhs(&blB[6*RhsProgress], B_0);
+ traits.madd(A0,B_0,C0,T0);
+ traits.madd(A1,B_0,C4,B_0);
+ traits.loadRhs(&blB[7*RhsProgress], B_0);
+ traits.madd(A0,B_0,C1,T0);
+ traits.madd(A1,B_0,C5,B_0);
EIGEN_ASM_COMMENT("myend");
}
else
{
EIGEN_ASM_COMMENT("mybegin4");
LhsPacket A0, A1;
- RhsPacket B0, B1, B2, B3;
+ RhsPacket B_0, B1, B2, B3;
RhsPacket T0;
traits.loadLhs(&blA[0*LhsProgress], A0);
traits.loadLhs(&blA[1*LhsProgress], A1);
- traits.loadRhs(&blB[0*RhsProgress], B0);
+ traits.loadRhs(&blB[0*RhsProgress], B_0);
traits.loadRhs(&blB[1*RhsProgress], B1);
- traits.madd(A0,B0,C0,T0);
+ traits.madd(A0,B_0,C0,T0);
traits.loadRhs(&blB[2*RhsProgress], B2);
- traits.madd(A1,B0,C4,B0);
+ traits.madd(A1,B_0,C4,B_0);
traits.loadRhs(&blB[3*RhsProgress], B3);
- traits.loadRhs(&blB[4*RhsProgress], B0);
+ traits.loadRhs(&blB[4*RhsProgress], B_0);
traits.madd(A0,B1,C1,T0);
traits.madd(A1,B1,C5,B1);
traits.loadRhs(&blB[5*RhsProgress], B1);
@@ -664,9 +658,9 @@ EIGEN_ASM_COMMENT("mybegin4");
traits.madd(A1,B3,C7,B3);
traits.loadLhs(&blA[3*LhsProgress], A1);
traits.loadRhs(&blB[7*RhsProgress], B3);
- traits.madd(A0,B0,C0,T0);
- traits.madd(A1,B0,C4,B0);
- traits.loadRhs(&blB[8*RhsProgress], B0);
+ traits.madd(A0,B_0,C0,T0);
+ traits.madd(A1,B_0,C4,B_0);
+ traits.loadRhs(&blB[8*RhsProgress], B_0);
traits.madd(A0,B1,C1,T0);
traits.madd(A1,B1,C5,B1);
traits.loadRhs(&blB[9*RhsProgress], B1);
@@ -679,9 +673,9 @@ EIGEN_ASM_COMMENT("mybegin4");
traits.loadLhs(&blA[5*LhsProgress], A1);
traits.loadRhs(&blB[11*RhsProgress], B3);
- traits.madd(A0,B0,C0,T0);
- traits.madd(A1,B0,C4,B0);
- traits.loadRhs(&blB[12*RhsProgress], B0);
+ traits.madd(A0,B_0,C0,T0);
+ traits.madd(A1,B_0,C4,B_0);
+ traits.loadRhs(&blB[12*RhsProgress], B_0);
traits.madd(A0,B1,C1,T0);
traits.madd(A1,B1,C5,B1);
traits.loadRhs(&blB[13*RhsProgress], B1);
@@ -693,8 +687,8 @@ EIGEN_ASM_COMMENT("mybegin4");
traits.madd(A1,B3,C7,B3);
traits.loadLhs(&blA[7*LhsProgress], A1);
traits.loadRhs(&blB[15*RhsProgress], B3);
- traits.madd(A0,B0,C0,T0);
- traits.madd(A1,B0,C4,B0);
+ traits.madd(A0,B_0,C0,T0);
+ traits.madd(A1,B_0,C4,B_0);
traits.madd(A0,B1,C1,T0);
traits.madd(A1,B1,C5,B1);
traits.madd(A0,B2,C2,T0);
@@ -712,32 +706,32 @@ EIGEN_ASM_COMMENT("mybegin4");
if(nr==2)
{
LhsPacket A0, A1;
- RhsPacket B0;
+ RhsPacket B_0;
RhsPacket T0;
traits.loadLhs(&blA[0*LhsProgress], A0);
traits.loadLhs(&blA[1*LhsProgress], A1);
- traits.loadRhs(&blB[0*RhsProgress], B0);
- traits.madd(A0,B0,C0,T0);
- traits.madd(A1,B0,C4,B0);
- traits.loadRhs(&blB[1*RhsProgress], B0);
- traits.madd(A0,B0,C1,T0);
- traits.madd(A1,B0,C5,B0);
+ traits.loadRhs(&blB[0*RhsProgress], B_0);
+ traits.madd(A0,B_0,C0,T0);
+ traits.madd(A1,B_0,C4,B_0);
+ traits.loadRhs(&blB[1*RhsProgress], B_0);
+ traits.madd(A0,B_0,C1,T0);
+ traits.madd(A1,B_0,C5,B_0);
}
else
{
LhsPacket A0, A1;
- RhsPacket B0, B1, B2, B3;
+ RhsPacket B_0, B1, B2, B3;
RhsPacket T0;
traits.loadLhs(&blA[0*LhsProgress], A0);
traits.loadLhs(&blA[1*LhsProgress], A1);
- traits.loadRhs(&blB[0*RhsProgress], B0);
+ traits.loadRhs(&blB[0*RhsProgress], B_0);
traits.loadRhs(&blB[1*RhsProgress], B1);
- traits.madd(A0,B0,C0,T0);
+ traits.madd(A0,B_0,C0,T0);
traits.loadRhs(&blB[2*RhsProgress], B2);
- traits.madd(A1,B0,C4,B0);
+ traits.madd(A1,B_0,C4,B_0);
traits.loadRhs(&blB[3*RhsProgress], B3);
traits.madd(A0,B1,C1,T0);
traits.madd(A1,B1,C5,B1);
@@ -824,42 +818,42 @@ EIGEN_ASM_COMMENT("mybegin4");
if(nr==2)
{
LhsPacket A0;
- RhsPacket B0, B1;
+ RhsPacket B_0, B1;
traits.loadLhs(&blA[0*LhsProgress], A0);
- traits.loadRhs(&blB[0*RhsProgress], B0);
+ traits.loadRhs(&blB[0*RhsProgress], B_0);
traits.loadRhs(&blB[1*RhsProgress], B1);
- traits.madd(A0,B0,C0,B0);
- traits.loadRhs(&blB[2*RhsProgress], B0);
+ traits.madd(A0,B_0,C0,B_0);
+ traits.loadRhs(&blB[2*RhsProgress], B_0);
traits.madd(A0,B1,C1,B1);
traits.loadLhs(&blA[1*LhsProgress], A0);
traits.loadRhs(&blB[3*RhsProgress], B1);
- traits.madd(A0,B0,C0,B0);
- traits.loadRhs(&blB[4*RhsProgress], B0);
+ traits.madd(A0,B_0,C0,B_0);
+ traits.loadRhs(&blB[4*RhsProgress], B_0);
traits.madd(A0,B1,C1,B1);
traits.loadLhs(&blA[2*LhsProgress], A0);
traits.loadRhs(&blB[5*RhsProgress], B1);
- traits.madd(A0,B0,C0,B0);
- traits.loadRhs(&blB[6*RhsProgress], B0);
+ traits.madd(A0,B_0,C0,B_0);
+ traits.loadRhs(&blB[6*RhsProgress], B_0);
traits.madd(A0,B1,C1,B1);
traits.loadLhs(&blA[3*LhsProgress], A0);
traits.loadRhs(&blB[7*RhsProgress], B1);
- traits.madd(A0,B0,C0,B0);
+ traits.madd(A0,B_0,C0,B_0);
traits.madd(A0,B1,C1,B1);
}
else
{
LhsPacket A0;
- RhsPacket B0, B1, B2, B3;
+ RhsPacket B_0, B1, B2, B3;
traits.loadLhs(&blA[0*LhsProgress], A0);
- traits.loadRhs(&blB[0*RhsProgress], B0);
+ traits.loadRhs(&blB[0*RhsProgress], B_0);
traits.loadRhs(&blB[1*RhsProgress], B1);
- traits.madd(A0,B0,C0,B0);
+ traits.madd(A0,B_0,C0,B_0);
traits.loadRhs(&blB[2*RhsProgress], B2);
traits.loadRhs(&blB[3*RhsProgress], B3);
- traits.loadRhs(&blB[4*RhsProgress], B0);
+ traits.loadRhs(&blB[4*RhsProgress], B_0);
traits.madd(A0,B1,C1,B1);
traits.loadRhs(&blB[5*RhsProgress], B1);
traits.madd(A0,B2,C2,B2);
@@ -867,8 +861,8 @@ EIGEN_ASM_COMMENT("mybegin4");
traits.madd(A0,B3,C3,B3);
traits.loadLhs(&blA[1*LhsProgress], A0);
traits.loadRhs(&blB[7*RhsProgress], B3);
- traits.madd(A0,B0,C0,B0);
- traits.loadRhs(&blB[8*RhsProgress], B0);
+ traits.madd(A0,B_0,C0,B_0);
+ traits.loadRhs(&blB[8*RhsProgress], B_0);
traits.madd(A0,B1,C1,B1);
traits.loadRhs(&blB[9*RhsProgress], B1);
traits.madd(A0,B2,C2,B2);
@@ -877,8 +871,8 @@ EIGEN_ASM_COMMENT("mybegin4");
traits.loadLhs(&blA[2*LhsProgress], A0);
traits.loadRhs(&blB[11*RhsProgress], B3);
- traits.madd(A0,B0,C0,B0);
- traits.loadRhs(&blB[12*RhsProgress], B0);
+ traits.madd(A0,B_0,C0,B_0);
+ traits.loadRhs(&blB[12*RhsProgress], B_0);
traits.madd(A0,B1,C1,B1);
traits.loadRhs(&blB[13*RhsProgress], B1);
traits.madd(A0,B2,C2,B2);
@@ -887,7 +881,7 @@ EIGEN_ASM_COMMENT("mybegin4");
traits.loadLhs(&blA[3*LhsProgress], A0);
traits.loadRhs(&blB[15*RhsProgress], B3);
- traits.madd(A0,B0,C0,B0);
+ traits.madd(A0,B_0,C0,B_0);
traits.madd(A0,B1,C1,B1);
traits.madd(A0,B2,C2,B2);
traits.madd(A0,B3,C3,B3);
@@ -902,26 +896,26 @@ EIGEN_ASM_COMMENT("mybegin4");
if(nr==2)
{
LhsPacket A0;
- RhsPacket B0, B1;
+ RhsPacket B_0, B1;
traits.loadLhs(&blA[0*LhsProgress], A0);
- traits.loadRhs(&blB[0*RhsProgress], B0);
+ traits.loadRhs(&blB[0*RhsProgress], B_0);
traits.loadRhs(&blB[1*RhsProgress], B1);
- traits.madd(A0,B0,C0,B0);
+ traits.madd(A0,B_0,C0,B_0);
traits.madd(A0,B1,C1,B1);
}
else
{
LhsPacket A0;
- RhsPacket B0, B1, B2, B3;
+ RhsPacket B_0, B1, B2, B3;
traits.loadLhs(&blA[0*LhsProgress], A0);
- traits.loadRhs(&blB[0*RhsProgress], B0);
+ traits.loadRhs(&blB[0*RhsProgress], B_0);
traits.loadRhs(&blB[1*RhsProgress], B1);
traits.loadRhs(&blB[2*RhsProgress], B2);
traits.loadRhs(&blB[3*RhsProgress], B3);
- traits.madd(A0,B0,C0,B0);
+ traits.madd(A0,B_0,C0,B_0);
traits.madd(A0,B1,C1,B1);
traits.madd(A0,B2,C2,B2);
traits.madd(A0,B3,C3,B3);
@@ -968,26 +962,26 @@ EIGEN_ASM_COMMENT("mybegin4");
if(nr==2)
{
LhsScalar A0;
- RhsScalar B0, B1;
+ RhsScalar B_0, B1;
A0 = blA[k];
- B0 = blB[0];
+ B_0 = blB[0];
B1 = blB[1];
- MADD(cj,A0,B0,C0,B0);
+ MADD(cj,A0,B_0,C0,B_0);
MADD(cj,A0,B1,C1,B1);
}
else
{
LhsScalar A0;
- RhsScalar B0, B1, B2, B3;
+ RhsScalar B_0, B1, B2, B3;
A0 = blA[k];
- B0 = blB[0];
+ B_0 = blB[0];
B1 = blB[1];
B2 = blB[2];
B3 = blB[3];
- MADD(cj,A0,B0,C0,B0);
+ MADD(cj,A0,B_0,C0,B_0);
MADD(cj,A0,B1,C1,B1);
MADD(cj,A0,B2,C2,B2);
MADD(cj,A0,B3,C3,B3);
@@ -1024,14 +1018,14 @@ EIGEN_ASM_COMMENT("mybegin4");
for(Index k=0; k<depth; k++)
{
LhsPacket A0, A1;
- RhsPacket B0;
+ RhsPacket B_0;
RhsPacket T0;
traits.loadLhs(&blA[0*LhsProgress], A0);
traits.loadLhs(&blA[1*LhsProgress], A1);
- traits.loadRhs(&blB[0*RhsProgress], B0);
- traits.madd(A0,B0,C0,T0);
- traits.madd(A1,B0,C4,B0);
+ traits.loadRhs(&blB[0*RhsProgress], B_0);
+ traits.madd(A0,B_0,C0,T0);
+ traits.madd(A1,B_0,C4,B_0);
blB += RhsProgress;
blA += 2*LhsProgress;
@@ -1063,10 +1057,10 @@ EIGEN_ASM_COMMENT("mybegin4");
for(Index k=0; k<depth; k++)
{
LhsPacket A0;
- RhsPacket B0;
+ RhsPacket B_0;
traits.loadLhs(blA, A0);
- traits.loadRhs(blB, B0);
- traits.madd(A0, B0, C0, B0);
+ traits.loadRhs(blB, B_0);
+ traits.madd(A0, B_0, C0, B_0);
blB += RhsProgress;
blA += LhsProgress;
}
@@ -1088,8 +1082,8 @@ EIGEN_ASM_COMMENT("mybegin4");
for(Index k=0; k<depth; k++)
{
LhsScalar A0 = blA[k];
- RhsScalar B0 = blB[k];
- MADD(cj, A0, B0, C0, B0);
+ RhsScalar B_0 = blB[k];
+ MADD(cj, A0, B_0, C0, B_0);
}
res[(j2+0)*resStride + i] += alpha*C0;
}
@@ -1100,7 +1094,7 @@ EIGEN_ASM_COMMENT("mybegin4");
#undef CJMADD
// pack a block of the lhs
-// The travesal is as follow (mr==4):
+// The traversal is as follow (mr==4):
// 0 4 8 12 ...
// 1 5 9 13 ...
// 2 6 10 14 ...
@@ -1116,11 +1110,15 @@ EIGEN_ASM_COMMENT("mybegin4");
template<typename Scalar, typename Index, int Pack1, int Pack2, int StorageOrder, bool Conjugate, bool PanelMode>
struct gemm_pack_lhs
{
- void operator()(Scalar* blockA, const Scalar* EIGEN_RESTRICT _lhs, Index lhsStride, Index depth, Index rows,
+ EIGEN_DONT_INLINE void operator()(Scalar* blockA, const Scalar* EIGEN_RESTRICT _lhs, Index lhsStride, Index depth, Index rows,
Index stride=0, Index offset=0)
{
-// enum { PacketSize = packet_traits<Scalar>::size };
+ typedef typename packet_traits<Scalar>::type Packet;
+ enum { PacketSize = packet_traits<Scalar>::size };
+
+ EIGEN_ASM_COMMENT("EIGEN PRODUCT PACK LHS");
eigen_assert(((!PanelMode) && stride==0 && offset==0) || (PanelMode && stride>=depth && offset<=stride));
+ eigen_assert( (StorageOrder==RowMajor) || ((Pack1%PacketSize)==0 && Pack1<=4*PacketSize) );
conj_if<NumTraits<Scalar>::IsComplex && Conjugate> cj;
const_blas_data_mapper<Scalar, Index, StorageOrder> lhs(_lhs,lhsStride);
Index count = 0;
@@ -1128,9 +1126,44 @@ struct gemm_pack_lhs
for(Index i=0; i<peeled_mc; i+=Pack1)
{
if(PanelMode) count += Pack1 * offset;
- for(Index k=0; k<depth; k++)
- for(Index w=0; w<Pack1; w++)
- blockA[count++] = cj(lhs(i+w, k));
+
+ if(StorageOrder==ColMajor)
+ {
+ for(Index k=0; k<depth; k++)
+ {
+ Packet A, B, C, D;
+ if(Pack1>=1*PacketSize) A = ploadu<Packet>(&lhs(i+0*PacketSize, k));
+ if(Pack1>=2*PacketSize) B = ploadu<Packet>(&lhs(i+1*PacketSize, k));
+ if(Pack1>=3*PacketSize) C = ploadu<Packet>(&lhs(i+2*PacketSize, k));
+ if(Pack1>=4*PacketSize) D = ploadu<Packet>(&lhs(i+3*PacketSize, k));
+ if(Pack1>=1*PacketSize) { pstore(blockA+count, cj.pconj(A)); count+=PacketSize; }
+ if(Pack1>=2*PacketSize) { pstore(blockA+count, cj.pconj(B)); count+=PacketSize; }
+ if(Pack1>=3*PacketSize) { pstore(blockA+count, cj.pconj(C)); count+=PacketSize; }
+ if(Pack1>=4*PacketSize) { pstore(blockA+count, cj.pconj(D)); count+=PacketSize; }
+ }
+ }
+ else
+ {
+ for(Index k=0; k<depth; k++)
+ {
+ // TODO add a vectorized transpose here
+ Index w=0;
+ for(; w<Pack1-3; w+=4)
+ {
+ Scalar a(cj(lhs(i+w+0, k))),
+ b(cj(lhs(i+w+1, k))),
+ c(cj(lhs(i+w+2, k))),
+ d(cj(lhs(i+w+3, k)));
+ blockA[count++] = a;
+ blockA[count++] = b;
+ blockA[count++] = c;
+ blockA[count++] = d;
+ }
+ if(Pack1%4)
+ for(;w<Pack1;++w)
+ blockA[count++] = cj(lhs(i+w, k));
+ }
+ }
if(PanelMode) count += Pack1 * (stride-offset-depth);
}
if(rows-peeled_mc>=Pack2)
@@ -1164,9 +1197,10 @@ struct gemm_pack_rhs<Scalar, Index, nr, ColMajor, Conjugate, PanelMode>
{
typedef typename packet_traits<Scalar>::type Packet;
enum { PacketSize = packet_traits<Scalar>::size };
- void operator()(Scalar* blockB, const Scalar* rhs, Index rhsStride, Index depth, Index cols,
+ EIGEN_DONT_INLINE void operator()(Scalar* blockB, const Scalar* rhs, Index rhsStride, Index depth, Index cols,
Index stride=0, Index offset=0)
{
+ EIGEN_ASM_COMMENT("EIGEN PRODUCT PACK RHS COLMAJOR");
eigen_assert(((!PanelMode) && stride==0 && offset==0) || (PanelMode && stride>=depth && offset<=stride));
conj_if<NumTraits<Scalar>::IsComplex && Conjugate> cj;
Index packet_cols = (cols/nr) * nr;
@@ -1211,9 +1245,10 @@ template<typename Scalar, typename Index, int nr, bool Conjugate, bool PanelMode
struct gemm_pack_rhs<Scalar, Index, nr, RowMajor, Conjugate, PanelMode>
{
enum { PacketSize = packet_traits<Scalar>::size };
- void operator()(Scalar* blockB, const Scalar* rhs, Index rhsStride, Index depth, Index cols,
+ EIGEN_DONT_INLINE void operator()(Scalar* blockB, const Scalar* rhs, Index rhsStride, Index depth, Index cols,
Index stride=0, Index offset=0)
{
+ EIGEN_ASM_COMMENT("EIGEN PRODUCT PACK RHS ROWMAJOR");
eigen_assert(((!PanelMode) && stride==0 && offset==0) || (PanelMode && stride>=depth && offset<=stride));
conj_if<NumTraits<Scalar>::IsComplex && Conjugate> cj;
Index packet_cols = (cols/nr) * nr;
@@ -1279,4 +1314,6 @@ inline void setCpuCacheSizes(std::ptrdiff_t l1, std::ptrdiff_t l2)
internal::manage_caching_sizes(SetAction, &l1, &l2);
}
+} // end namespace Eigen
+
#endif // EIGEN_GENERAL_BLOCK_PANEL_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrix.h b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrix.h
index ae94a27953b..73a465ec5ee 100644
--- a/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrix.h
+++ b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrix.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GENERAL_MATRIX_MATRIX_H
#define EIGEN_GENERAL_MATRIX_MATRIX_H
+namespace Eigen {
+
namespace internal {
template<typename _LhsScalar, typename _RhsScalar> class level3_blocking;
@@ -77,7 +64,7 @@ static void run(Index rows, Index cols, Index depth,
typedef gebp_traits<LhsScalar,RhsScalar> Traits;
- Index kc = blocking.kc(); // cache block size along the K direction
+ Index kc = blocking.kc(); // cache block size along the K direction
Index mc = (std::min)(rows,blocking.mc()); // cache block size along the M direction
//Index nc = blocking.nc(); // cache block size along the N direction
@@ -247,7 +234,7 @@ struct gemm_functor
BlockingType& m_blocking;
};
-template<int StorageOrder, typename LhsScalar, typename RhsScalar, int MaxRows, int MaxCols, int MaxDepth,
+template<int StorageOrder, typename LhsScalar, typename RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor=1,
bool FiniteAtCompileTime = MaxRows!=Dynamic && MaxCols!=Dynamic && MaxDepth != Dynamic> class gemm_blocking_space;
template<typename _LhsScalar, typename _RhsScalar>
@@ -280,8 +267,8 @@ class level3_blocking
inline RhsScalar* blockW() { return m_blockW; }
};
-template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth>
-class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, true>
+template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor>
+class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, KcFactor, true>
: public level3_blocking<
typename conditional<StorageOrder==RowMajor,_RhsScalar,_LhsScalar>::type,
typename conditional<StorageOrder==RowMajor,_LhsScalar,_RhsScalar>::type>
@@ -322,8 +309,8 @@ class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, M
inline void allocateAll() {}
};
-template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth>
-class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, false>
+template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor>
+class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, KcFactor, false>
: public level3_blocking<
typename conditional<StorageOrder==RowMajor,_RhsScalar,_LhsScalar>::type,
typename conditional<StorageOrder==RowMajor,_LhsScalar,_RhsScalar>::type>
@@ -347,7 +334,7 @@ class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, M
this->m_nc = Transpose ? rows : cols;
this->m_kc = depth;
- computeProductBlockingSizes<LhsScalar,RhsScalar>(this->m_kc, this->m_mc, this->m_nc);
+ computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, this->m_mc, this->m_nc);
m_sizeA = this->m_mc * this->m_kc;
m_sizeB = this->m_kc * this->m_nc;
m_sizeW = this->m_kc*Traits::WorkSpaceFactor;
@@ -412,8 +399,8 @@ class GeneralProduct<Lhs, Rhs, GemmProduct>
{
eigen_assert(dst.rows()==m_lhs.rows() && dst.cols()==m_rhs.cols());
- const ActualLhsType lhs = LhsBlasTraits::extract(m_lhs);
- const ActualRhsType rhs = RhsBlasTraits::extract(m_rhs);
+ typename internal::add_const_on_value_type<ActualLhsType>::type lhs = LhsBlasTraits::extract(m_lhs);
+ typename internal::add_const_on_value_type<ActualRhsType>::type rhs = RhsBlasTraits::extract(m_rhs);
Scalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(m_lhs)
* RhsBlasTraits::extractScalarFactor(m_rhs);
@@ -436,4 +423,6 @@ class GeneralProduct<Lhs, Rhs, GemmProduct>
}
};
+} // end namespace Eigen
+
#endif // EIGEN_GENERAL_MATRIX_MATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular.h b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular.h
index 5043b64fe2e..432d3a9dc84 100644
--- a/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular.h
+++ b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GENERAL_MATRIX_MATRIX_TRIANGULAR_H
#define EIGEN_GENERAL_MATRIX_MATRIX_TRIANGULAR_H
+namespace Eigen {
+
namespace internal {
/**********************************************************************
@@ -42,14 +29,14 @@ struct tribb_kernel;
template <typename Index,
typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs,
typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs,
- int ResStorageOrder, int UpLo>
+ int ResStorageOrder, int UpLo, int Version = Specialized>
struct general_matrix_matrix_triangular_product;
// as usual if the result is row major => we transpose the product
template <typename Index, typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs,
- typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs, int UpLo>
-struct general_matrix_matrix_triangular_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,RowMajor,UpLo>
-{
+ typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs, int UpLo, int Version>
+struct general_matrix_matrix_triangular_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,RowMajor,UpLo,Version>
+{
typedef typename scalar_product_traits<LhsScalar, RhsScalar>::ReturnType ResScalar;
static EIGEN_STRONG_INLINE void run(Index size, Index depth,const LhsScalar* lhs, Index lhsStride,
const RhsScalar* rhs, Index rhsStride, ResScalar* res, Index resStride, ResScalar alpha)
@@ -63,8 +50,8 @@ struct general_matrix_matrix_triangular_product<Index,LhsScalar,LhsStorageOrder,
};
template <typename Index, typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs,
- typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs, int UpLo>
-struct general_matrix_matrix_triangular_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,ColMajor,UpLo>
+ typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs, int UpLo, int Version>
+struct general_matrix_matrix_triangular_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,ColMajor,UpLo,Version>
{
typedef typename scalar_product_traits<LhsScalar, RhsScalar>::ReturnType ResScalar;
static EIGEN_STRONG_INLINE void run(Index size, Index depth,const LhsScalar* _lhs, Index lhsStride,
@@ -201,13 +188,13 @@ TriangularView<MatrixType,UpLo>& TriangularView<MatrixType,UpLo>::assignProduct(
typedef internal::blas_traits<Lhs> LhsBlasTraits;
typedef typename LhsBlasTraits::DirectLinearAccessType ActualLhs;
typedef typename internal::remove_all<ActualLhs>::type _ActualLhs;
- const ActualLhs actualLhs = LhsBlasTraits::extract(prod.lhs());
+ typename internal::add_const_on_value_type<ActualLhs>::type actualLhs = LhsBlasTraits::extract(prod.lhs());
typedef typename internal::remove_all<typename ProductDerived::RhsNested>::type Rhs;
typedef internal::blas_traits<Rhs> RhsBlasTraits;
typedef typename RhsBlasTraits::DirectLinearAccessType ActualRhs;
typedef typename internal::remove_all<ActualRhs>::type _ActualRhs;
- const ActualRhs actualRhs = RhsBlasTraits::extract(prod.rhs());
+ typename internal::add_const_on_value_type<ActualRhs>::type actualRhs = RhsBlasTraits::extract(prod.rhs());
typename ProductDerived::Scalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(prod.lhs().derived()) * RhsBlasTraits::extractScalarFactor(prod.rhs().derived());
@@ -222,4 +209,6 @@ TriangularView<MatrixType,UpLo>& TriangularView<MatrixType,UpLo>::assignProduct(
return *this;
}
+} // end namespace Eigen
+
#endif // EIGEN_GENERAL_MATRIX_MATRIX_TRIANGULAR_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular_MKL.h b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular_MKL.h
new file mode 100644
index 00000000000..3deed068e39
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular_MKL.h
@@ -0,0 +1,146 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Level 3 BLAS SYRK/HERK implementation.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_GENERAL_MATRIX_MATRIX_TRIANGULAR_MKL_H
+#define EIGEN_GENERAL_MATRIX_MATRIX_TRIANGULAR_MKL_H
+
+namespace Eigen {
+
+namespace internal {
+
+template <typename Index, typename Scalar, int AStorageOrder, bool ConjugateA, int ResStorageOrder, int UpLo>
+struct general_matrix_matrix_rankupdate :
+ general_matrix_matrix_triangular_product<
+ Index,Scalar,AStorageOrder,ConjugateA,Scalar,AStorageOrder,ConjugateA,ResStorageOrder,UpLo,BuiltIn> {};
+
+
+// try to go to BLAS specialization
+#define EIGEN_MKL_RANKUPDATE_SPECIALIZE(Scalar) \
+template <typename Index, int LhsStorageOrder, bool ConjugateLhs, \
+ int RhsStorageOrder, bool ConjugateRhs, int UpLo> \
+struct general_matrix_matrix_triangular_product<Index,Scalar,LhsStorageOrder,ConjugateLhs, \
+ Scalar,RhsStorageOrder,ConjugateRhs,ColMajor,UpLo,Specialized> { \
+ static EIGEN_STRONG_INLINE void run(Index size, Index depth,const Scalar* lhs, Index lhsStride, \
+ const Scalar* rhs, Index rhsStride, Scalar* res, Index resStride, Scalar alpha) \
+ { \
+ if (lhs==rhs) { \
+ general_matrix_matrix_rankupdate<Index,Scalar,LhsStorageOrder,ConjugateLhs,ColMajor,UpLo> \
+ ::run(size,depth,lhs,lhsStride,rhs,rhsStride,res,resStride,alpha); \
+ } else { \
+ general_matrix_matrix_triangular_product<Index, \
+ Scalar, LhsStorageOrder, ConjugateLhs, \
+ Scalar, RhsStorageOrder, ConjugateRhs, \
+ ColMajor, UpLo, BuiltIn> \
+ ::run(size,depth,lhs,lhsStride,rhs,rhsStride,res,resStride,alpha); \
+ } \
+ } \
+};
+
+EIGEN_MKL_RANKUPDATE_SPECIALIZE(double)
+//EIGEN_MKL_RANKUPDATE_SPECIALIZE(dcomplex)
+EIGEN_MKL_RANKUPDATE_SPECIALIZE(float)
+//EIGEN_MKL_RANKUPDATE_SPECIALIZE(scomplex)
+
+// SYRK for float/double
+#define EIGEN_MKL_RANKUPDATE_R(EIGTYPE, MKLTYPE, MKLFUNC) \
+template <typename Index, int AStorageOrder, bool ConjugateA, int UpLo> \
+struct general_matrix_matrix_rankupdate<Index,EIGTYPE,AStorageOrder,ConjugateA,ColMajor,UpLo> { \
+ enum { \
+ IsLower = (UpLo&Lower) == Lower, \
+ LowUp = IsLower ? Lower : Upper, \
+ conjA = ((AStorageOrder==ColMajor) && ConjugateA) ? 1 : 0 \
+ }; \
+ static EIGEN_STRONG_INLINE void run(Index size, Index depth,const EIGTYPE* lhs, Index lhsStride, \
+ const EIGTYPE* rhs, Index rhsStride, EIGTYPE* res, Index resStride, EIGTYPE alpha) \
+ { \
+ /* typedef Matrix<EIGTYPE, Dynamic, Dynamic, RhsStorageOrder> MatrixRhs;*/ \
+\
+ MKL_INT lda=lhsStride, ldc=resStride, n=size, k=depth; \
+ char uplo=(IsLower) ? 'L' : 'U', trans=(AStorageOrder==RowMajor) ? 'T':'N'; \
+ MKLTYPE alpha_, beta_; \
+\
+/* Set alpha_ & beta_ */ \
+ assign_scalar_eig2mkl<MKLTYPE, EIGTYPE>(alpha_, alpha); \
+ assign_scalar_eig2mkl<MKLTYPE, EIGTYPE>(beta_, EIGTYPE(1)); \
+ MKLFUNC(&uplo, &trans, &n, &k, &alpha_, lhs, &lda, &beta_, res, &ldc); \
+ } \
+};
+
+// HERK for complex data
+#define EIGEN_MKL_RANKUPDATE_C(EIGTYPE, MKLTYPE, RTYPE, MKLFUNC) \
+template <typename Index, int AStorageOrder, bool ConjugateA, int UpLo> \
+struct general_matrix_matrix_rankupdate<Index,EIGTYPE,AStorageOrder,ConjugateA,ColMajor,UpLo> { \
+ enum { \
+ IsLower = (UpLo&Lower) == Lower, \
+ LowUp = IsLower ? Lower : Upper, \
+ conjA = (((AStorageOrder==ColMajor) && ConjugateA) || ((AStorageOrder==RowMajor) && !ConjugateA)) ? 1 : 0 \
+ }; \
+ static EIGEN_STRONG_INLINE void run(Index size, Index depth,const EIGTYPE* lhs, Index lhsStride, \
+ const EIGTYPE* rhs, Index rhsStride, EIGTYPE* res, Index resStride, EIGTYPE alpha) \
+ { \
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic, AStorageOrder> MatrixType; \
+\
+ MKL_INT lda=lhsStride, ldc=resStride, n=size, k=depth; \
+ char uplo=(IsLower) ? 'L' : 'U', trans=(AStorageOrder==RowMajor) ? 'C':'N'; \
+ RTYPE alpha_, beta_; \
+ const EIGTYPE* a_ptr; \
+\
+/* Set alpha_ & beta_ */ \
+/* assign_scalar_eig2mkl<MKLTYPE, EIGTYPE>(alpha_, alpha); */\
+/* assign_scalar_eig2mkl<MKLTYPE, EIGTYPE>(beta_, EIGTYPE(1));*/ \
+ alpha_ = alpha.real(); \
+ beta_ = 1.0; \
+/* Copy with conjugation in some cases*/ \
+ MatrixType a; \
+ if (conjA) { \
+ Map<const MatrixType, 0, OuterStride<> > mapA(lhs,n,k,OuterStride<>(lhsStride)); \
+ a = mapA.conjugate(); \
+ lda = a.outerStride(); \
+ a_ptr = a.data(); \
+ } else a_ptr=lhs; \
+ MKLFUNC(&uplo, &trans, &n, &k, &alpha_, (MKLTYPE*)a_ptr, &lda, &beta_, (MKLTYPE*)res, &ldc); \
+ } \
+};
+
+
+EIGEN_MKL_RANKUPDATE_R(double, double, dsyrk)
+EIGEN_MKL_RANKUPDATE_R(float, float, ssyrk)
+
+//EIGEN_MKL_RANKUPDATE_C(dcomplex, MKL_Complex16, double, zherk)
+//EIGEN_MKL_RANKUPDATE_C(scomplex, MKL_Complex8, double, cherk)
+
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_GENERAL_MATRIX_MATRIX_TRIANGULAR_MKL_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrix_MKL.h b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrix_MKL.h
new file mode 100644
index 00000000000..060af328ebe
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrix_MKL.h
@@ -0,0 +1,118 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * General matrix-matrix product functionality based on ?GEMM.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_GENERAL_MATRIX_MATRIX_MKL_H
+#define EIGEN_GENERAL_MATRIX_MATRIX_MKL_H
+
+namespace Eigen {
+
+namespace internal {
+
+/**********************************************************************
+* This file implements general matrix-matrix multiplication using BLAS
+* gemm function via partial specialization of
+* general_matrix_matrix_product::run(..) method for float, double,
+* std::complex<float> and std::complex<double> types
+**********************************************************************/
+
+// gemm specialization
+
+#define GEMM_SPECIALIZATION(EIGTYPE, EIGPREFIX, MKLTYPE, MKLPREFIX) \
+template< \
+ typename Index, \
+ int LhsStorageOrder, bool ConjugateLhs, \
+ int RhsStorageOrder, bool ConjugateRhs> \
+struct general_matrix_matrix_product<Index,EIGTYPE,LhsStorageOrder,ConjugateLhs,EIGTYPE,RhsStorageOrder,ConjugateRhs,ColMajor> \
+{ \
+static void run(Index rows, Index cols, Index depth, \
+ const EIGTYPE* _lhs, Index lhsStride, \
+ const EIGTYPE* _rhs, Index rhsStride, \
+ EIGTYPE* res, Index resStride, \
+ EIGTYPE alpha, \
+ level3_blocking<EIGTYPE, EIGTYPE>& /*blocking*/, \
+ GemmParallelInfo<Index>* /*info = 0*/) \
+{ \
+ using std::conj; \
+\
+ char transa, transb; \
+ MKL_INT m, n, k, lda, ldb, ldc; \
+ const EIGTYPE *a, *b; \
+ MKLTYPE alpha_, beta_; \
+ MatrixX##EIGPREFIX a_tmp, b_tmp; \
+ EIGTYPE myone(1);\
+\
+/* Set transpose options */ \
+ transa = (LhsStorageOrder==RowMajor) ? ((ConjugateLhs) ? 'C' : 'T') : 'N'; \
+ transb = (RhsStorageOrder==RowMajor) ? ((ConjugateRhs) ? 'C' : 'T') : 'N'; \
+\
+/* Set m, n, k */ \
+ m = (MKL_INT)rows; \
+ n = (MKL_INT)cols; \
+ k = (MKL_INT)depth; \
+\
+/* Set alpha_ & beta_ */ \
+ assign_scalar_eig2mkl(alpha_, alpha); \
+ assign_scalar_eig2mkl(beta_, myone); \
+\
+/* Set lda, ldb, ldc */ \
+ lda = (MKL_INT)lhsStride; \
+ ldb = (MKL_INT)rhsStride; \
+ ldc = (MKL_INT)resStride; \
+\
+/* Set a, b, c */ \
+ if ((LhsStorageOrder==ColMajor) && (ConjugateLhs)) { \
+ Map<const MatrixX##EIGPREFIX, 0, OuterStride<> > lhs(_lhs,m,k,OuterStride<>(lhsStride)); \
+ a_tmp = lhs.conjugate(); \
+ a = a_tmp.data(); \
+ lda = a_tmp.outerStride(); \
+ } else a = _lhs; \
+\
+ if ((RhsStorageOrder==ColMajor) && (ConjugateRhs)) { \
+ Map<const MatrixX##EIGPREFIX, 0, OuterStride<> > rhs(_rhs,k,n,OuterStride<>(rhsStride)); \
+ b_tmp = rhs.conjugate(); \
+ b = b_tmp.data(); \
+ ldb = b_tmp.outerStride(); \
+ } else b = _rhs; \
+\
+ MKLPREFIX##gemm(&transa, &transb, &m, &n, &k, &alpha_, (const MKLTYPE*)a, &lda, (const MKLTYPE*)b, &ldb, &beta_, (MKLTYPE*)res, &ldc); \
+}};
+
+GEMM_SPECIALIZATION(double, d, double, d)
+GEMM_SPECIALIZATION(float, f, float, s)
+GEMM_SPECIALIZATION(dcomplex, cd, MKL_Complex16, z)
+GEMM_SPECIALIZATION(scomplex, cf, MKL_Complex8, c)
+
+} // end namespase internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_GENERAL_MATRIX_MATRIX_MKL_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector.h b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector.h
index e0e2cbf8f62..ba1f73957db 100644
--- a/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector.h
+++ b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GENERAL_MATRIX_VECTOR_H
#define EIGEN_GENERAL_MATRIX_VECTOR_H
+namespace Eigen {
+
namespace internal {
/* Optimized col-major matrix * vector product:
@@ -40,8 +27,8 @@ namespace internal {
* |cplx |real |cplx | invalid, the caller has to do tmp: = A * B; C += alpha*tmp
* |cplx |real |real | optimal case, vectorization possible via real-cplx mul
*/
-template<typename Index, typename LhsScalar, bool ConjugateLhs, typename RhsScalar, bool ConjugateRhs>
-struct general_matrix_vector_product<Index,LhsScalar,ColMajor,ConjugateLhs,RhsScalar,ConjugateRhs>
+template<typename Index, typename LhsScalar, bool ConjugateLhs, typename RhsScalar, bool ConjugateRhs, int Version>
+struct general_matrix_vector_product<Index,LhsScalar,ColMajor,ConjugateLhs,RhsScalar,ConjugateRhs,Version>
{
typedef typename scalar_product_traits<LhsScalar, RhsScalar>::ReturnType ResScalar;
@@ -99,7 +86,7 @@ EIGEN_DONT_INLINE static void run(
// How many coeffs of the result do we have to skip to be aligned.
// Here we assume data are at least aligned on the base scalar type.
- Index alignedStart = first_aligned(res,size);
+ Index alignedStart = internal::first_aligned(res,size);
Index alignedSize = ResPacketSize>1 ? alignedStart + ((size-alignedStart) & ~ResPacketAlignedMask) : 0;
const Index peeledSize = peels>1 ? alignedStart + ((alignedSize-alignedStart) & ~PeelAlignedMask) : alignedStart;
@@ -109,7 +96,7 @@ EIGEN_DONT_INLINE static void run(
: FirstAligned;
// we cannot assume the first element is aligned because of sub-matrices
- const Index lhsAlignmentOffset = first_aligned(lhs,size);
+ const Index lhsAlignmentOffset = internal::first_aligned(lhs,size);
// find how many columns do we have to skip to be aligned with the result (if possible)
Index skipColumns = 0;
@@ -296,8 +283,8 @@ EIGEN_DONT_INLINE static void run(
* - alpha is always a complex (or converted to a complex)
* - no vectorization
*/
-template<typename Index, typename LhsScalar, bool ConjugateLhs, typename RhsScalar, bool ConjugateRhs>
-struct general_matrix_vector_product<Index,LhsScalar,RowMajor,ConjugateLhs,RhsScalar,ConjugateRhs>
+template<typename Index, typename LhsScalar, bool ConjugateLhs, typename RhsScalar, bool ConjugateRhs, int Version>
+struct general_matrix_vector_product<Index,LhsScalar,RowMajor,ConjugateLhs,RhsScalar,ConjugateRhs,Version>
{
typedef typename scalar_product_traits<LhsScalar, RhsScalar>::ReturnType ResScalar;
@@ -351,7 +338,7 @@ EIGEN_DONT_INLINE static void run(
// How many coeffs of the result do we have to skip to be aligned.
// Here we assume data are at least aligned on the base scalar type
// if that's not the case then vectorization is discarded, see below.
- Index alignedStart = first_aligned(rhs, depth);
+ Index alignedStart = internal::first_aligned(rhs, depth);
Index alignedSize = RhsPacketSize>1 ? alignedStart + ((depth-alignedStart) & ~RhsPacketAlignedMask) : 0;
const Index peeledSize = peels>1 ? alignedStart + ((alignedSize-alignedStart) & ~PeelAlignedMask) : alignedStart;
@@ -361,7 +348,7 @@ EIGEN_DONT_INLINE static void run(
: FirstAligned;
// we cannot assume the first element is aligned because of sub-matrices
- const Index lhsAlignmentOffset = first_aligned(lhs,depth);
+ const Index lhsAlignmentOffset = internal::first_aligned(lhs,depth);
// find how many rows do we have to skip to be aligned with rhs (if possible)
Index skipRows = 0;
@@ -556,4 +543,6 @@ EIGEN_DONT_INLINE static void run(
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_GENERAL_MATRIX_VECTOR_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector_MKL.h b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector_MKL.h
new file mode 100644
index 00000000000..e9de6af3ed1
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector_MKL.h
@@ -0,0 +1,131 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * General matrix-vector product functionality based on ?GEMV.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_GENERAL_MATRIX_VECTOR_MKL_H
+#define EIGEN_GENERAL_MATRIX_VECTOR_MKL_H
+
+namespace Eigen {
+
+namespace internal {
+
+/**********************************************************************
+* This file implements general matrix-vector multiplication using BLAS
+* gemv function via partial specialization of
+* general_matrix_vector_product::run(..) method for float, double,
+* std::complex<float> and std::complex<double> types
+**********************************************************************/
+
+// gemv specialization
+
+template<typename Index, typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs, typename RhsScalar, bool ConjugateRhs>
+struct general_matrix_vector_product_gemv :
+ general_matrix_vector_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,ConjugateRhs,BuiltIn> {};
+
+#define EIGEN_MKL_GEMV_SPECIALIZE(Scalar) \
+template<typename Index, bool ConjugateLhs, bool ConjugateRhs> \
+struct general_matrix_vector_product<Index,Scalar,ColMajor,ConjugateLhs,Scalar,ConjugateRhs,Specialized> { \
+static EIGEN_DONT_INLINE void run( \
+ Index rows, Index cols, \
+ const Scalar* lhs, Index lhsStride, \
+ const Scalar* rhs, Index rhsIncr, \
+ Scalar* res, Index resIncr, Scalar alpha) \
+{ \
+ if (ConjugateLhs) { \
+ general_matrix_vector_product<Index,Scalar,ColMajor,ConjugateLhs,Scalar,ConjugateRhs,BuiltIn>::run( \
+ rows, cols, lhs, lhsStride, rhs, rhsIncr, res, resIncr, alpha); \
+ } else { \
+ general_matrix_vector_product_gemv<Index,Scalar,ColMajor,ConjugateLhs,Scalar,ConjugateRhs>::run( \
+ rows, cols, lhs, lhsStride, rhs, rhsIncr, res, resIncr, alpha); \
+ } \
+} \
+}; \
+template<typename Index, bool ConjugateLhs, bool ConjugateRhs> \
+struct general_matrix_vector_product<Index,Scalar,RowMajor,ConjugateLhs,Scalar,ConjugateRhs,Specialized> { \
+static EIGEN_DONT_INLINE void run( \
+ Index rows, Index cols, \
+ const Scalar* lhs, Index lhsStride, \
+ const Scalar* rhs, Index rhsIncr, \
+ Scalar* res, Index resIncr, Scalar alpha) \
+{ \
+ general_matrix_vector_product_gemv<Index,Scalar,RowMajor,ConjugateLhs,Scalar,ConjugateRhs>::run( \
+ rows, cols, lhs, lhsStride, rhs, rhsIncr, res, resIncr, alpha); \
+} \
+}; \
+
+EIGEN_MKL_GEMV_SPECIALIZE(double)
+EIGEN_MKL_GEMV_SPECIALIZE(float)
+EIGEN_MKL_GEMV_SPECIALIZE(dcomplex)
+EIGEN_MKL_GEMV_SPECIALIZE(scomplex)
+
+#define EIGEN_MKL_GEMV_SPECIALIZATION(EIGTYPE,MKLTYPE,MKLPREFIX) \
+template<typename Index, int LhsStorageOrder, bool ConjugateLhs, bool ConjugateRhs> \
+struct general_matrix_vector_product_gemv<Index,EIGTYPE,LhsStorageOrder,ConjugateLhs,EIGTYPE,ConjugateRhs> \
+{ \
+typedef Matrix<EIGTYPE,Dynamic,1,ColMajor> GEMVVector;\
+\
+static EIGEN_DONT_INLINE void run( \
+ Index rows, Index cols, \
+ const EIGTYPE* lhs, Index lhsStride, \
+ const EIGTYPE* rhs, Index rhsIncr, \
+ EIGTYPE* res, Index resIncr, EIGTYPE alpha) \
+{ \
+ MKL_INT m=rows, n=cols, lda=lhsStride, incx=rhsIncr, incy=resIncr; \
+ MKLTYPE alpha_, beta_; \
+ const EIGTYPE *x_ptr, myone(1); \
+ char trans=(LhsStorageOrder==ColMajor) ? 'N' : (ConjugateLhs) ? 'C' : 'T'; \
+ if (LhsStorageOrder==RowMajor) { \
+ m=cols; \
+ n=rows; \
+ }\
+ assign_scalar_eig2mkl(alpha_, alpha); \
+ assign_scalar_eig2mkl(beta_, myone); \
+ GEMVVector x_tmp; \
+ if (ConjugateRhs) { \
+ Map<const GEMVVector, 0, InnerStride<> > map_x(rhs,cols,1,InnerStride<>(incx)); \
+ x_tmp=map_x.conjugate(); \
+ x_ptr=x_tmp.data(); \
+ incx=1; \
+ } else x_ptr=rhs; \
+ MKLPREFIX##gemv(&trans, &m, &n, &alpha_, (const MKLTYPE*)lhs, &lda, (const MKLTYPE*)x_ptr, &incx, &beta_, (MKLTYPE*)res, &incy); \
+}\
+};
+
+EIGEN_MKL_GEMV_SPECIALIZATION(double, double, d)
+EIGEN_MKL_GEMV_SPECIALIZATION(float, float, s)
+EIGEN_MKL_GEMV_SPECIALIZATION(dcomplex, MKL_Complex16, z)
+EIGEN_MKL_GEMV_SPECIALIZATION(scomplex, MKL_Complex8, c)
+
+} // end namespase internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_GENERAL_MATRIX_VECTOR_MKL_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/Parallelizer.h b/extern/Eigen3/Eigen/src/Core/products/Parallelizer.h
index ecdedc363ce..5c3e9b7ac15 100644
--- a/extern/Eigen3/Eigen/src/Core/products/Parallelizer.h
+++ b/extern/Eigen3/Eigen/src/Core/products/Parallelizer.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PARALLELIZER_H
#define EIGEN_PARALLELIZER_H
+namespace Eigen {
+
namespace internal {
/** \internal */
@@ -55,12 +42,23 @@ inline void manage_multi_threading(Action action, int* v)
}
}
+}
+
+/** Must be call first when calling Eigen from multiple threads */
+inline void initParallel()
+{
+ int nbt;
+ internal::manage_multi_threading(GetAction, &nbt);
+ std::ptrdiff_t l1, l2;
+ internal::manage_caching_sizes(GetAction, &l1, &l2);
+}
+
/** \returns the max number of threads reserved for Eigen
* \sa setNbThreads */
inline int nbThreads()
{
int ret;
- manage_multi_threading(GetAction, &ret);
+ internal::manage_multi_threading(GetAction, &ret);
return ret;
}
@@ -68,9 +66,11 @@ inline int nbThreads()
* \sa nbThreads */
inline void setNbThreads(int v)
{
- manage_multi_threading(SetAction, &v);
+ internal::manage_multi_threading(SetAction, &v);
}
+namespace internal {
+
template<typename Index> struct GemmParallelInfo
{
GemmParallelInfo() : sync(-1), users(0), rhs_start(0), rhs_length(0) {}
@@ -85,7 +85,9 @@ template<typename Index> struct GemmParallelInfo
template<bool Condition, typename Functor, typename Index>
void parallelize_gemm(const Functor& func, Index rows, Index cols, bool transpose)
{
-#ifndef EIGEN_HAS_OPENMP
+ // TODO when EIGEN_USE_BLAS is defined,
+ // we should still enable OMP for other scalar types
+#if !(defined (EIGEN_HAS_OPENMP)) || defined (EIGEN_USE_BLAS)
// FIXME the transpose variable is only needed to properly split
// the matrix product when multithreading is enabled. This is a temporary
// fix to support row-major destination matrices. This whole
@@ -117,6 +119,7 @@ void parallelize_gemm(const Functor& func, Index rows, Index cols, bool transpos
if(threads==1)
return func(0,rows, 0,cols);
+ Eigen::initParallel();
func.initParallelSession();
if(transpose)
@@ -151,4 +154,6 @@ void parallelize_gemm(const Functor& func, Index rows, Index cols, bool transpos
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_PARALLELIZER_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix.h b/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix.h
index ccd757cfaf8..48209636eed 100644
--- a/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix.h
+++ b/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SELFADJOINT_MATRIX_MATRIX_H
#define EIGEN_SELFADJOINT_MATRIX_MATRIX_H
+namespace Eigen {
+
namespace internal {
// pack a selfadjoint block diagonal for use with the gebp_kernel
@@ -400,8 +387,8 @@ struct SelfadjointProductMatrix<Lhs,LhsMode,false,Rhs,RhsMode,false>
{
eigen_assert(dst.rows()==m_lhs.rows() && dst.cols()==m_rhs.cols());
- const ActualLhsType lhs = LhsBlasTraits::extract(m_lhs);
- const ActualRhsType rhs = RhsBlasTraits::extract(m_rhs);
+ typename internal::add_const_on_value_type<ActualLhsType>::type lhs = LhsBlasTraits::extract(m_lhs);
+ typename internal::add_const_on_value_type<ActualRhsType>::type rhs = RhsBlasTraits::extract(m_rhs);
Scalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(m_lhs)
* RhsBlasTraits::extractScalarFactor(m_rhs);
@@ -424,4 +411,6 @@ struct SelfadjointProductMatrix<Lhs,LhsMode,false,Rhs,RhsMode,false>
}
};
+} // end namespace Eigen
+
#endif // EIGEN_SELFADJOINT_MATRIX_MATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix_MKL.h b/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix_MKL.h
new file mode 100644
index 00000000000..4e5c4125c01
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix_MKL.h
@@ -0,0 +1,295 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Self adjoint matrix * matrix product functionality based on ?SYMM/?HEMM.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_SELFADJOINT_MATRIX_MATRIX_MKL_H
+#define EIGEN_SELFADJOINT_MATRIX_MATRIX_MKL_H
+
+namespace Eigen {
+
+namespace internal {
+
+
+/* Optimized selfadjoint matrix * matrix (?SYMM/?HEMM) product */
+
+#define EIGEN_MKL_SYMM_L(EIGTYPE, MKLTYPE, EIGPREFIX, MKLPREFIX) \
+template <typename Index, \
+ int LhsStorageOrder, bool ConjugateLhs, \
+ int RhsStorageOrder, bool ConjugateRhs> \
+struct product_selfadjoint_matrix<EIGTYPE,Index,LhsStorageOrder,true,ConjugateLhs,RhsStorageOrder,false,ConjugateRhs,ColMajor> \
+{\
+\
+ static EIGEN_DONT_INLINE void run( \
+ Index rows, Index cols, \
+ const EIGTYPE* _lhs, Index lhsStride, \
+ const EIGTYPE* _rhs, Index rhsStride, \
+ EIGTYPE* res, Index resStride, \
+ EIGTYPE alpha) \
+ { \
+ char side='L', uplo='L'; \
+ MKL_INT m, n, lda, ldb, ldc; \
+ const EIGTYPE *a, *b; \
+ MKLTYPE alpha_, beta_; \
+ MatrixX##EIGPREFIX b_tmp; \
+ EIGTYPE myone(1);\
+\
+/* Set transpose options */ \
+/* Set m, n, k */ \
+ m = (MKL_INT)rows; \
+ n = (MKL_INT)cols; \
+\
+/* Set alpha_ & beta_ */ \
+ assign_scalar_eig2mkl(alpha_, alpha); \
+ assign_scalar_eig2mkl(beta_, myone); \
+\
+/* Set lda, ldb, ldc */ \
+ lda = (MKL_INT)lhsStride; \
+ ldb = (MKL_INT)rhsStride; \
+ ldc = (MKL_INT)resStride; \
+\
+/* Set a, b, c */ \
+ if (LhsStorageOrder==RowMajor) uplo='U'; \
+ a = _lhs; \
+\
+ if (RhsStorageOrder==RowMajor) { \
+ Map<const MatrixX##EIGPREFIX, 0, OuterStride<> > rhs(_rhs,n,m,OuterStride<>(rhsStride)); \
+ b_tmp = rhs.adjoint(); \
+ b = b_tmp.data(); \
+ ldb = b_tmp.outerStride(); \
+ } else b = _rhs; \
+\
+ MKLPREFIX##symm(&side, &uplo, &m, &n, &alpha_, (const MKLTYPE*)a, &lda, (const MKLTYPE*)b, &ldb, &beta_, (MKLTYPE*)res, &ldc); \
+\
+ } \
+};
+
+
+#define EIGEN_MKL_HEMM_L(EIGTYPE, MKLTYPE, EIGPREFIX, MKLPREFIX) \
+template <typename Index, \
+ int LhsStorageOrder, bool ConjugateLhs, \
+ int RhsStorageOrder, bool ConjugateRhs> \
+struct product_selfadjoint_matrix<EIGTYPE,Index,LhsStorageOrder,true,ConjugateLhs,RhsStorageOrder,false,ConjugateRhs,ColMajor> \
+{\
+ static EIGEN_DONT_INLINE void run( \
+ Index rows, Index cols, \
+ const EIGTYPE* _lhs, Index lhsStride, \
+ const EIGTYPE* _rhs, Index rhsStride, \
+ EIGTYPE* res, Index resStride, \
+ EIGTYPE alpha) \
+ { \
+ char side='L', uplo='L'; \
+ MKL_INT m, n, lda, ldb, ldc; \
+ const EIGTYPE *a, *b; \
+ MKLTYPE alpha_, beta_; \
+ MatrixX##EIGPREFIX b_tmp; \
+ Matrix<EIGTYPE, Dynamic, Dynamic, LhsStorageOrder> a_tmp; \
+ EIGTYPE myone(1); \
+\
+/* Set transpose options */ \
+/* Set m, n, k */ \
+ m = (MKL_INT)rows; \
+ n = (MKL_INT)cols; \
+\
+/* Set alpha_ & beta_ */ \
+ assign_scalar_eig2mkl(alpha_, alpha); \
+ assign_scalar_eig2mkl(beta_, myone); \
+\
+/* Set lda, ldb, ldc */ \
+ lda = (MKL_INT)lhsStride; \
+ ldb = (MKL_INT)rhsStride; \
+ ldc = (MKL_INT)resStride; \
+\
+/* Set a, b, c */ \
+ if (((LhsStorageOrder==ColMajor) && ConjugateLhs) || ((LhsStorageOrder==RowMajor) && (!ConjugateLhs))) { \
+ Map<const Matrix<EIGTYPE, Dynamic, Dynamic, LhsStorageOrder>, 0, OuterStride<> > lhs(_lhs,m,m,OuterStride<>(lhsStride)); \
+ a_tmp = lhs.conjugate(); \
+ a = a_tmp.data(); \
+ lda = a_tmp.outerStride(); \
+ } else a = _lhs; \
+ if (LhsStorageOrder==RowMajor) uplo='U'; \
+\
+ if (RhsStorageOrder==ColMajor && (!ConjugateRhs)) { \
+ b = _rhs; } \
+ else { \
+ if (RhsStorageOrder==ColMajor && ConjugateRhs) { \
+ Map<const MatrixX##EIGPREFIX, 0, OuterStride<> > rhs(_rhs,m,n,OuterStride<>(rhsStride)); \
+ b_tmp = rhs.conjugate(); \
+ } else \
+ if (ConjugateRhs) { \
+ Map<const MatrixX##EIGPREFIX, 0, OuterStride<> > rhs(_rhs,n,m,OuterStride<>(rhsStride)); \
+ b_tmp = rhs.adjoint(); \
+ } else { \
+ Map<const MatrixX##EIGPREFIX, 0, OuterStride<> > rhs(_rhs,n,m,OuterStride<>(rhsStride)); \
+ b_tmp = rhs.transpose(); \
+ } \
+ b = b_tmp.data(); \
+ ldb = b_tmp.outerStride(); \
+ } \
+\
+ MKLPREFIX##hemm(&side, &uplo, &m, &n, &alpha_, (const MKLTYPE*)a, &lda, (const MKLTYPE*)b, &ldb, &beta_, (MKLTYPE*)res, &ldc); \
+\
+ } \
+};
+
+EIGEN_MKL_SYMM_L(double, double, d, d)
+EIGEN_MKL_SYMM_L(float, float, f, s)
+EIGEN_MKL_HEMM_L(dcomplex, MKL_Complex16, cd, z)
+EIGEN_MKL_HEMM_L(scomplex, MKL_Complex8, cf, c)
+
+
+/* Optimized matrix * selfadjoint matrix (?SYMM/?HEMM) product */
+
+#define EIGEN_MKL_SYMM_R(EIGTYPE, MKLTYPE, EIGPREFIX, MKLPREFIX) \
+template <typename Index, \
+ int LhsStorageOrder, bool ConjugateLhs, \
+ int RhsStorageOrder, bool ConjugateRhs> \
+struct product_selfadjoint_matrix<EIGTYPE,Index,LhsStorageOrder,false,ConjugateLhs,RhsStorageOrder,true,ConjugateRhs,ColMajor> \
+{\
+\
+ static EIGEN_DONT_INLINE void run( \
+ Index rows, Index cols, \
+ const EIGTYPE* _lhs, Index lhsStride, \
+ const EIGTYPE* _rhs, Index rhsStride, \
+ EIGTYPE* res, Index resStride, \
+ EIGTYPE alpha) \
+ { \
+ char side='R', uplo='L'; \
+ MKL_INT m, n, lda, ldb, ldc; \
+ const EIGTYPE *a, *b; \
+ MKLTYPE alpha_, beta_; \
+ MatrixX##EIGPREFIX b_tmp; \
+ EIGTYPE myone(1);\
+\
+/* Set m, n, k */ \
+ m = (MKL_INT)rows; \
+ n = (MKL_INT)cols; \
+\
+/* Set alpha_ & beta_ */ \
+ assign_scalar_eig2mkl(alpha_, alpha); \
+ assign_scalar_eig2mkl(beta_, myone); \
+\
+/* Set lda, ldb, ldc */ \
+ lda = (MKL_INT)rhsStride; \
+ ldb = (MKL_INT)lhsStride; \
+ ldc = (MKL_INT)resStride; \
+\
+/* Set a, b, c */ \
+ if (RhsStorageOrder==RowMajor) uplo='U'; \
+ a = _rhs; \
+\
+ if (LhsStorageOrder==RowMajor) { \
+ Map<const MatrixX##EIGPREFIX, 0, OuterStride<> > lhs(_lhs,n,m,OuterStride<>(rhsStride)); \
+ b_tmp = lhs.adjoint(); \
+ b = b_tmp.data(); \
+ ldb = b_tmp.outerStride(); \
+ } else b = _lhs; \
+\
+ MKLPREFIX##symm(&side, &uplo, &m, &n, &alpha_, (const MKLTYPE*)a, &lda, (const MKLTYPE*)b, &ldb, &beta_, (MKLTYPE*)res, &ldc); \
+\
+ } \
+};
+
+
+#define EIGEN_MKL_HEMM_R(EIGTYPE, MKLTYPE, EIGPREFIX, MKLPREFIX) \
+template <typename Index, \
+ int LhsStorageOrder, bool ConjugateLhs, \
+ int RhsStorageOrder, bool ConjugateRhs> \
+struct product_selfadjoint_matrix<EIGTYPE,Index,LhsStorageOrder,false,ConjugateLhs,RhsStorageOrder,true,ConjugateRhs,ColMajor> \
+{\
+ static EIGEN_DONT_INLINE void run( \
+ Index rows, Index cols, \
+ const EIGTYPE* _lhs, Index lhsStride, \
+ const EIGTYPE* _rhs, Index rhsStride, \
+ EIGTYPE* res, Index resStride, \
+ EIGTYPE alpha) \
+ { \
+ char side='R', uplo='L'; \
+ MKL_INT m, n, lda, ldb, ldc; \
+ const EIGTYPE *a, *b; \
+ MKLTYPE alpha_, beta_; \
+ MatrixX##EIGPREFIX b_tmp; \
+ Matrix<EIGTYPE, Dynamic, Dynamic, RhsStorageOrder> a_tmp; \
+ EIGTYPE myone(1); \
+\
+/* Set m, n, k */ \
+ m = (MKL_INT)rows; \
+ n = (MKL_INT)cols; \
+\
+/* Set alpha_ & beta_ */ \
+ assign_scalar_eig2mkl(alpha_, alpha); \
+ assign_scalar_eig2mkl(beta_, myone); \
+\
+/* Set lda, ldb, ldc */ \
+ lda = (MKL_INT)rhsStride; \
+ ldb = (MKL_INT)lhsStride; \
+ ldc = (MKL_INT)resStride; \
+\
+/* Set a, b, c */ \
+ if (((RhsStorageOrder==ColMajor) && ConjugateRhs) || ((RhsStorageOrder==RowMajor) && (!ConjugateRhs))) { \
+ Map<const Matrix<EIGTYPE, Dynamic, Dynamic, RhsStorageOrder>, 0, OuterStride<> > rhs(_rhs,n,n,OuterStride<>(rhsStride)); \
+ a_tmp = rhs.conjugate(); \
+ a = a_tmp.data(); \
+ lda = a_tmp.outerStride(); \
+ } else a = _rhs; \
+ if (RhsStorageOrder==RowMajor) uplo='U'; \
+\
+ if (LhsStorageOrder==ColMajor && (!ConjugateLhs)) { \
+ b = _lhs; } \
+ else { \
+ if (LhsStorageOrder==ColMajor && ConjugateLhs) { \
+ Map<const MatrixX##EIGPREFIX, 0, OuterStride<> > lhs(_lhs,m,n,OuterStride<>(lhsStride)); \
+ b_tmp = lhs.conjugate(); \
+ } else \
+ if (ConjugateLhs) { \
+ Map<const MatrixX##EIGPREFIX, 0, OuterStride<> > lhs(_lhs,n,m,OuterStride<>(lhsStride)); \
+ b_tmp = lhs.adjoint(); \
+ } else { \
+ Map<const MatrixX##EIGPREFIX, 0, OuterStride<> > lhs(_lhs,n,m,OuterStride<>(lhsStride)); \
+ b_tmp = lhs.transpose(); \
+ } \
+ b = b_tmp.data(); \
+ ldb = b_tmp.outerStride(); \
+ } \
+\
+ MKLPREFIX##hemm(&side, &uplo, &m, &n, &alpha_, (const MKLTYPE*)a, &lda, (const MKLTYPE*)b, &ldb, &beta_, (MKLTYPE*)res, &ldc); \
+ } \
+};
+
+EIGEN_MKL_SYMM_R(double, double, d, d)
+EIGEN_MKL_SYMM_R(float, float, f, s)
+EIGEN_MKL_HEMM_R(dcomplex, MKL_Complex16, cd, z)
+EIGEN_MKL_HEMM_R(scomplex, MKL_Complex8, cf, c)
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_SELFADJOINT_MATRIX_MATRIX_MKL_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector.h b/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector.h
index d6121fc07bd..c3145c69a5f 100644
--- a/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector.h
+++ b/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SELFADJOINT_MATRIX_VECTOR_H
#define EIGEN_SELFADJOINT_MATRIX_VECTOR_H
+namespace Eigen {
+
namespace internal {
/* Optimized selfadjoint matrix * vector product:
@@ -32,8 +19,15 @@ namespace internal {
* the number of load/stores of the result by a factor 2 and to reduce
* the instruction dependency.
*/
-template<typename Scalar, typename Index, int StorageOrder, int UpLo, bool ConjugateLhs, bool ConjugateRhs>
-static EIGEN_DONT_INLINE void product_selfadjoint_vector(
+
+template<typename Scalar, typename Index, int StorageOrder, int UpLo, bool ConjugateLhs, bool ConjugateRhs, int Version=Specialized>
+struct selfadjoint_matrix_vector_product;
+
+template<typename Scalar, typename Index, int StorageOrder, int UpLo, bool ConjugateLhs, bool ConjugateRhs, int Version>
+struct selfadjoint_matrix_vector_product
+
+{
+static EIGEN_DONT_INLINE void run(
Index size,
const Scalar* lhs, Index lhsStride,
const Scalar* _rhs, Index rhsIncr,
@@ -85,14 +79,14 @@ static EIGEN_DONT_INLINE void product_selfadjoint_vector(
Scalar t1 = cjAlpha * rhs[j+1];
Packet ptmp1 = pset1<Packet>(t1);
- Scalar t2 = 0;
+ Scalar t2(0);
Packet ptmp2 = pset1<Packet>(t2);
- Scalar t3 = 0;
+ Scalar t3(0);
Packet ptmp3 = pset1<Packet>(t3);
size_t starti = FirstTriangular ? 0 : j+2;
size_t endi = FirstTriangular ? j : size;
- size_t alignedStart = (starti) + first_aligned(&res[starti], endi-starti);
+ size_t alignedStart = (starti) + internal::first_aligned(&res[starti], endi-starti);
size_t alignedEnd = alignedStart + ((endi-alignedStart)/(PacketSize))*(PacketSize);
// TODO make sure this product is a real * complex and that the rhs is properly conjugated if needed
@@ -148,7 +142,7 @@ static EIGEN_DONT_INLINE void product_selfadjoint_vector(
register const Scalar* EIGEN_RESTRICT A0 = lhs + j*lhsStride;
Scalar t1 = cjAlpha * rhs[j];
- Scalar t2 = 0;
+ Scalar t2(0);
// TODO make sure this product is a real * complex and that the rhs is properly conjugated if needed
res[j] += cjd.pmul(internal::real(A0[j]), t1);
for (Index i=FirstTriangular ? 0 : j+1; i<(FirstTriangular ? j : size); i++)
@@ -159,6 +153,7 @@ static EIGEN_DONT_INLINE void product_selfadjoint_vector(
res[j] += alpha * t2;
}
}
+};
} // end namespace internal
@@ -193,8 +188,8 @@ struct SelfadjointProductMatrix<Lhs,LhsMode,false,Rhs,0,true>
eigen_assert(dest.rows()==m_lhs.rows() && dest.cols()==m_rhs.cols());
- const ActualLhsType lhs = LhsBlasTraits::extract(m_lhs);
- const ActualRhsType rhs = RhsBlasTraits::extract(m_rhs);
+ typename internal::add_const_on_value_type<ActualLhsType>::type lhs = LhsBlasTraits::extract(m_lhs);
+ typename internal::add_const_on_value_type<ActualRhsType>::type rhs = RhsBlasTraits::extract(m_rhs);
Scalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(m_lhs)
* RhsBlasTraits::extractScalarFactor(m_rhs);
@@ -232,7 +227,7 @@ struct SelfadjointProductMatrix<Lhs,LhsMode,false,Rhs,0,true>
}
- internal::product_selfadjoint_vector<Scalar, Index, (internal::traits<_ActualLhsType>::Flags&RowMajorBit) ? RowMajor : ColMajor, int(LhsUpLo), bool(LhsBlasTraits::NeedToConjugate), bool(RhsBlasTraits::NeedToConjugate)>
+ internal::selfadjoint_matrix_vector_product<Scalar, Index, (internal::traits<_ActualLhsType>::Flags&RowMajorBit) ? RowMajor : ColMajor, int(LhsUpLo), bool(LhsBlasTraits::NeedToConjugate), bool(RhsBlasTraits::NeedToConjugate)>::run
(
lhs.rows(), // size
&lhs.coeffRef(0,0), lhs.outerStride(), // lhs info
@@ -274,5 +269,6 @@ struct SelfadjointProductMatrix<Lhs,0,true,Rhs,RhsMode,false>
}
};
+} // end namespace Eigen
#endif // EIGEN_SELFADJOINT_MATRIX_VECTOR_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector_MKL.h b/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector_MKL.h
new file mode 100644
index 00000000000..f88d483b653
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector_MKL.h
@@ -0,0 +1,114 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Selfadjoint matrix-vector product functionality based on ?SYMV/HEMV.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_SELFADJOINT_MATRIX_VECTOR_MKL_H
+#define EIGEN_SELFADJOINT_MATRIX_VECTOR_MKL_H
+
+namespace Eigen {
+
+namespace internal {
+
+/**********************************************************************
+* This file implements selfadjoint matrix-vector multiplication using BLAS
+**********************************************************************/
+
+// symv/hemv specialization
+
+template<typename Scalar, typename Index, int StorageOrder, int UpLo, bool ConjugateLhs, bool ConjugateRhs>
+struct selfadjoint_matrix_vector_product_symv :
+ selfadjoint_matrix_vector_product<Scalar,Index,StorageOrder,UpLo,ConjugateLhs,ConjugateRhs,BuiltIn> {};
+
+#define EIGEN_MKL_SYMV_SPECIALIZE(Scalar) \
+template<typename Index, int StorageOrder, int UpLo, bool ConjugateLhs, bool ConjugateRhs> \
+struct selfadjoint_matrix_vector_product<Scalar,Index,StorageOrder,UpLo,ConjugateLhs,ConjugateRhs,Specialized> { \
+static EIGEN_DONT_INLINE void run( \
+ Index size, const Scalar* lhs, Index lhsStride, \
+ const Scalar* _rhs, Index rhsIncr, Scalar* res, Scalar alpha) { \
+ enum {\
+ IsColMajor = StorageOrder==ColMajor \
+ }; \
+ if (IsColMajor == ConjugateLhs) {\
+ selfadjoint_matrix_vector_product<Scalar,Index,StorageOrder,UpLo,ConjugateLhs,ConjugateRhs,BuiltIn>::run( \
+ size, lhs, lhsStride, _rhs, rhsIncr, res, alpha); \
+ } else {\
+ selfadjoint_matrix_vector_product_symv<Scalar,Index,StorageOrder,UpLo,ConjugateLhs,ConjugateRhs>::run( \
+ size, lhs, lhsStride, _rhs, rhsIncr, res, alpha); \
+ }\
+ } \
+}; \
+
+EIGEN_MKL_SYMV_SPECIALIZE(double)
+EIGEN_MKL_SYMV_SPECIALIZE(float)
+EIGEN_MKL_SYMV_SPECIALIZE(dcomplex)
+EIGEN_MKL_SYMV_SPECIALIZE(scomplex)
+
+#define EIGEN_MKL_SYMV_SPECIALIZATION(EIGTYPE,MKLTYPE,MKLFUNC) \
+template<typename Index, int StorageOrder, int UpLo, bool ConjugateLhs, bool ConjugateRhs> \
+struct selfadjoint_matrix_vector_product_symv<EIGTYPE,Index,StorageOrder,UpLo,ConjugateLhs,ConjugateRhs> \
+{ \
+typedef Matrix<EIGTYPE,Dynamic,1,ColMajor> SYMVVector;\
+\
+static EIGEN_DONT_INLINE void run( \
+Index size, const EIGTYPE* lhs, Index lhsStride, \
+const EIGTYPE* _rhs, Index rhsIncr, EIGTYPE* res, EIGTYPE alpha) \
+{ \
+ enum {\
+ IsRowMajor = StorageOrder==RowMajor ? 1 : 0, \
+ IsLower = UpLo == Lower ? 1 : 0 \
+ }; \
+ MKL_INT n=size, lda=lhsStride, incx=rhsIncr, incy=1; \
+ MKLTYPE alpha_, beta_; \
+ const EIGTYPE *x_ptr, myone(1); \
+ char uplo=(IsRowMajor) ? (IsLower ? 'U' : 'L') : (IsLower ? 'L' : 'U'); \
+ assign_scalar_eig2mkl(alpha_, alpha); \
+ assign_scalar_eig2mkl(beta_, myone); \
+ SYMVVector x_tmp; \
+ if (ConjugateRhs) { \
+ Map<const SYMVVector, 0, InnerStride<> > map_x(_rhs,size,1,InnerStride<>(incx)); \
+ x_tmp=map_x.conjugate(); \
+ x_ptr=x_tmp.data(); \
+ incx=1; \
+ } else x_ptr=_rhs; \
+ MKLFUNC(&uplo, &n, &alpha_, (const MKLTYPE*)lhs, &lda, (const MKLTYPE*)x_ptr, &incx, &beta_, (MKLTYPE*)res, &incy); \
+}\
+};
+
+EIGEN_MKL_SYMV_SPECIALIZATION(double, double, dsymv)
+EIGEN_MKL_SYMV_SPECIALIZATION(float, float, ssymv)
+EIGEN_MKL_SYMV_SPECIALIZATION(dcomplex, MKL_Complex16, zhemv)
+EIGEN_MKL_SYMV_SPECIALIZATION(scomplex, MKL_Complex8, chemv)
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_SELFADJOINT_MATRIX_VECTOR_MKL_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/SelfadjointProduct.h b/extern/Eigen3/Eigen/src/Core/products/SelfadjointProduct.h
index 3a4523fa4a9..6a55f3d7715 100644
--- a/extern/Eigen3/Eigen/src/Core/products/SelfadjointProduct.h
+++ b/extern/Eigen3/Eigen/src/Core/products/SelfadjointProduct.h
@@ -3,24 +3,9 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SELFADJOINT_PRODUCT_H
#define EIGEN_SELFADJOINT_PRODUCT_H
@@ -31,6 +16,8 @@
* It corresponds to the level 3 SYRK and level 2 SYR Blas routines.
**********************************************************************/
+namespace Eigen {
+
template<typename Scalar, typename Index, int StorageOrder, int UpLo, bool ConjLhs, bool ConjRhs>
struct selfadjoint_rank1_update;
@@ -72,7 +59,7 @@ struct selfadjoint_product_selector<MatrixType,OtherType,UpLo,true>
typedef internal::blas_traits<OtherType> OtherBlasTraits;
typedef typename OtherBlasTraits::DirectLinearAccessType ActualOtherType;
typedef typename internal::remove_all<ActualOtherType>::type _ActualOtherType;
- const ActualOtherType actualOther = OtherBlasTraits::extract(other.derived());
+ typename internal::add_const_on_value_type<ActualOtherType>::type actualOther = OtherBlasTraits::extract(other.derived());
Scalar actualAlpha = alpha * OtherBlasTraits::extractScalarFactor(other.derived());
@@ -105,12 +92,12 @@ struct selfadjoint_product_selector<MatrixType,OtherType,UpLo,false>
typedef internal::blas_traits<OtherType> OtherBlasTraits;
typedef typename OtherBlasTraits::DirectLinearAccessType ActualOtherType;
typedef typename internal::remove_all<ActualOtherType>::type _ActualOtherType;
- const ActualOtherType actualOther = OtherBlasTraits::extract(other.derived());
+ typename internal::add_const_on_value_type<ActualOtherType>::type actualOther = OtherBlasTraits::extract(other.derived());
Scalar actualAlpha = alpha * OtherBlasTraits::extractScalarFactor(other.derived());
enum { IsRowMajor = (internal::traits<MatrixType>::Flags&RowMajorBit) ? 1 : 0 };
-
+
internal::general_matrix_matrix_triangular_product<Index,
Scalar, _ActualOtherType::Flags&RowMajorBit ? RowMajor : ColMajor, OtherBlasTraits::NeedToConjugate && NumTraits<Scalar>::IsComplex,
Scalar, _ActualOtherType::Flags&RowMajorBit ? ColMajor : RowMajor, (!OtherBlasTraits::NeedToConjugate) && NumTraits<Scalar>::IsComplex,
@@ -133,4 +120,6 @@ SelfAdjointView<MatrixType,UpLo>& SelfAdjointView<MatrixType,UpLo>
return *this;
}
+} // end namespace Eigen
+
#endif // EIGEN_SELFADJOINT_PRODUCT_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/SelfadjointRank2Update.h b/extern/Eigen3/Eigen/src/Core/products/SelfadjointRank2Update.h
index 9f8b8438a5d..57a98cc2de9 100644
--- a/extern/Eigen3/Eigen/src/Core/products/SelfadjointRank2Update.h
+++ b/extern/Eigen3/Eigen/src/Core/products/SelfadjointRank2Update.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SELFADJOINTRANK2UPTADE_H
#define EIGEN_SELFADJOINTRANK2UPTADE_H
+namespace Eigen {
+
namespace internal {
/* Optimized selfadjoint matrix += alpha * uv' + conj(alpha)*vu'
@@ -76,12 +63,12 @@ SelfAdjointView<MatrixType,UpLo>& SelfAdjointView<MatrixType,UpLo>
typedef internal::blas_traits<DerivedU> UBlasTraits;
typedef typename UBlasTraits::DirectLinearAccessType ActualUType;
typedef typename internal::remove_all<ActualUType>::type _ActualUType;
- const ActualUType actualU = UBlasTraits::extract(u.derived());
+ typename internal::add_const_on_value_type<ActualUType>::type actualU = UBlasTraits::extract(u.derived());
typedef internal::blas_traits<DerivedV> VBlasTraits;
typedef typename VBlasTraits::DirectLinearAccessType ActualVType;
typedef typename internal::remove_all<ActualVType>::type _ActualVType;
- const ActualVType actualV = VBlasTraits::extract(v.derived());
+ typename internal::add_const_on_value_type<ActualVType>::type actualV = VBlasTraits::extract(v.derived());
// If MatrixType is row major, then we use the routine for lower triangular in the upper triangular case and
// vice versa, and take the complex conjugate of all coefficients and vector entries.
@@ -101,4 +88,6 @@ SelfAdjointView<MatrixType,UpLo>& SelfAdjointView<MatrixType,UpLo>
return *this;
}
+} // end namespace Eigen
+
#endif // EIGEN_SELFADJOINTRANK2UPTADE_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix.h b/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix.h
index 0c48d2efb75..92cba66f615 100644
--- a/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix.h
+++ b/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRIANGULAR_MATRIX_MATRIX_H
#define EIGEN_TRIANGULAR_MATRIX_MATRIX_H
+namespace Eigen {
+
namespace internal {
// template<typename Scalar, int mr, int StorageOrder, bool Conjugate, int Mode>
@@ -58,23 +45,23 @@ template <typename Scalar, typename Index,
int Mode, bool LhsIsTriangular,
int LhsStorageOrder, bool ConjugateLhs,
int RhsStorageOrder, bool ConjugateRhs,
- int ResStorageOrder>
+ int ResStorageOrder, int Version = Specialized>
struct product_triangular_matrix_matrix;
template <typename Scalar, typename Index,
int Mode, bool LhsIsTriangular,
int LhsStorageOrder, bool ConjugateLhs,
- int RhsStorageOrder, bool ConjugateRhs>
+ int RhsStorageOrder, bool ConjugateRhs, int Version>
struct product_triangular_matrix_matrix<Scalar,Index,Mode,LhsIsTriangular,
LhsStorageOrder,ConjugateLhs,
- RhsStorageOrder,ConjugateRhs,RowMajor>
+ RhsStorageOrder,ConjugateRhs,RowMajor,Version>
{
static EIGEN_STRONG_INLINE void run(
Index rows, Index cols, Index depth,
const Scalar* lhs, Index lhsStride,
const Scalar* rhs, Index rhsStride,
Scalar* res, Index resStride,
- Scalar alpha)
+ Scalar alpha, level3_blocking<Scalar,Scalar>& blocking)
{
product_triangular_matrix_matrix<Scalar, Index,
(Mode&(UnitDiag|ZeroDiag)) | ((Mode&Upper) ? Lower : Upper),
@@ -84,22 +71,22 @@ struct product_triangular_matrix_matrix<Scalar,Index,Mode,LhsIsTriangular,
LhsStorageOrder==RowMajor ? ColMajor : RowMajor,
ConjugateLhs,
ColMajor>
- ::run(cols, rows, depth, rhs, rhsStride, lhs, lhsStride, res, resStride, alpha);
+ ::run(cols, rows, depth, rhs, rhsStride, lhs, lhsStride, res, resStride, alpha, blocking);
}
};
// implements col-major += alpha * op(triangular) * op(general)
template <typename Scalar, typename Index, int Mode,
int LhsStorageOrder, bool ConjugateLhs,
- int RhsStorageOrder, bool ConjugateRhs>
+ int RhsStorageOrder, bool ConjugateRhs, int Version>
struct product_triangular_matrix_matrix<Scalar,Index,Mode,true,
LhsStorageOrder,ConjugateLhs,
- RhsStorageOrder,ConjugateRhs,ColMajor>
+ RhsStorageOrder,ConjugateRhs,ColMajor,Version>
{
typedef gebp_traits<Scalar,Scalar> Traits;
enum {
- SmallPanelWidth = EIGEN_PLAIN_ENUM_MAX(Traits::mr,Traits::nr),
+ SmallPanelWidth = 2 * EIGEN_PLAIN_ENUM_MAX(Traits::mr,Traits::nr),
IsLower = (Mode&Lower) == Lower,
SetDiag = (Mode&(ZeroDiag|UnitDiag)) ? 0 : 1
};
@@ -109,7 +96,7 @@ struct product_triangular_matrix_matrix<Scalar,Index,Mode,true,
const Scalar* _lhs, Index lhsStride,
const Scalar* _rhs, Index rhsStride,
Scalar* res, Index resStride,
- Scalar alpha)
+ Scalar alpha, level3_blocking<Scalar,Scalar>& blocking)
{
// strip zeros
Index diagSize = (std::min)(_rows,_depth);
@@ -120,15 +107,16 @@ struct product_triangular_matrix_matrix<Scalar,Index,Mode,true,
const_blas_data_mapper<Scalar, Index, LhsStorageOrder> lhs(_lhs,lhsStride);
const_blas_data_mapper<Scalar, Index, RhsStorageOrder> rhs(_rhs,rhsStride);
- Index kc = depth; // cache block size along the K direction
- Index mc = rows; // cache block size along the M direction
- Index nc = cols; // cache block size along the N direction
- computeProductBlockingSizes<Scalar,Scalar,4>(kc, mc, nc);
+ Index kc = blocking.kc(); // cache block size along the K direction
+ Index mc = (std::min)(rows,blocking.mc()); // cache block size along the M direction
+
+ std::size_t sizeA = kc*mc;
+ std::size_t sizeB = kc*cols;
std::size_t sizeW = kc*Traits::WorkSpaceFactor;
- std::size_t sizeB = sizeW + kc*cols;
- ei_declare_aligned_stack_constructed_variable(Scalar, blockA, kc*mc, 0);
- ei_declare_aligned_stack_constructed_variable(Scalar, allocatedBlockB, sizeB, 0);
- Scalar* blockB = allocatedBlockB + sizeW;
+
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockA, sizeA, blocking.blockA());
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockB, sizeB, blocking.blockB());
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockW, sizeW, blocking.blockW());
Matrix<Scalar,SmallPanelWidth,SmallPanelWidth,LhsStorageOrder> triangularBuffer;
triangularBuffer.setZero();
@@ -186,7 +174,7 @@ struct product_triangular_matrix_matrix<Scalar,Index,Mode,true,
pack_lhs(blockA, triangularBuffer.data(), triangularBuffer.outerStride(), actualPanelWidth, actualPanelWidth);
gebp_kernel(res+startBlock, resStride, blockA, blockB, actualPanelWidth, actualPanelWidth, cols, alpha,
- actualPanelWidth, actual_kc, 0, blockBOffset);
+ actualPanelWidth, actual_kc, 0, blockBOffset, blockW);
// GEBP with remaining micro panel
if (lengthTarget>0)
@@ -196,7 +184,7 @@ struct product_triangular_matrix_matrix<Scalar,Index,Mode,true,
pack_lhs(blockA, &lhs(startTarget,startBlock), lhsStride, actualPanelWidth, lengthTarget);
gebp_kernel(res+startTarget, resStride, blockA, blockB, lengthTarget, actualPanelWidth, cols, alpha,
- actualPanelWidth, actual_kc, 0, blockBOffset);
+ actualPanelWidth, actual_kc, 0, blockBOffset, blockW);
}
}
}
@@ -210,7 +198,7 @@ struct product_triangular_matrix_matrix<Scalar,Index,Mode,true,
gemm_pack_lhs<Scalar, Index, Traits::mr,Traits::LhsProgress, LhsStorageOrder,false>()
(blockA, &lhs(i2, actual_k2), lhsStride, actual_kc, actual_mc);
- gebp_kernel(res+i2, resStride, blockA, blockB, actual_mc, actual_kc, cols, alpha);
+ gebp_kernel(res+i2, resStride, blockA, blockB, actual_mc, actual_kc, cols, alpha, -1, -1, 0, 0, blockW);
}
}
}
@@ -220,10 +208,10 @@ struct product_triangular_matrix_matrix<Scalar,Index,Mode,true,
// implements col-major += alpha * op(general) * op(triangular)
template <typename Scalar, typename Index, int Mode,
int LhsStorageOrder, bool ConjugateLhs,
- int RhsStorageOrder, bool ConjugateRhs>
+ int RhsStorageOrder, bool ConjugateRhs, int Version>
struct product_triangular_matrix_matrix<Scalar,Index,Mode,false,
LhsStorageOrder,ConjugateLhs,
- RhsStorageOrder,ConjugateRhs,ColMajor>
+ RhsStorageOrder,ConjugateRhs,ColMajor,Version>
{
typedef gebp_traits<Scalar,Scalar> Traits;
enum {
@@ -237,7 +225,7 @@ struct product_triangular_matrix_matrix<Scalar,Index,Mode,false,
const Scalar* _lhs, Index lhsStride,
const Scalar* _rhs, Index rhsStride,
Scalar* res, Index resStride,
- Scalar alpha)
+ Scalar alpha, level3_blocking<Scalar,Scalar>& blocking)
{
// strip zeros
Index diagSize = (std::min)(_cols,_depth);
@@ -248,16 +236,16 @@ struct product_triangular_matrix_matrix<Scalar,Index,Mode,false,
const_blas_data_mapper<Scalar, Index, LhsStorageOrder> lhs(_lhs,lhsStride);
const_blas_data_mapper<Scalar, Index, RhsStorageOrder> rhs(_rhs,rhsStride);
- Index kc = depth; // cache block size along the K direction
- Index mc = rows; // cache block size along the M direction
- Index nc = cols; // cache block size along the N direction
- computeProductBlockingSizes<Scalar,Scalar,4>(kc, mc, nc);
+ Index kc = blocking.kc(); // cache block size along the K direction
+ Index mc = (std::min)(rows,blocking.mc()); // cache block size along the M direction
+ std::size_t sizeA = kc*mc;
+ std::size_t sizeB = kc*cols;
std::size_t sizeW = kc*Traits::WorkSpaceFactor;
- std::size_t sizeB = sizeW + kc*cols;
- ei_declare_aligned_stack_constructed_variable(Scalar, blockA, kc*mc, 0);
- ei_declare_aligned_stack_constructed_variable(Scalar, allocatedBlockB, sizeB, 0);
- Scalar* blockB = allocatedBlockB + sizeW;
+
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockA, sizeA, blocking.blockA());
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockB, sizeB, blocking.blockB());
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockW, sizeW, blocking.blockW());
Matrix<Scalar,SmallPanelWidth,SmallPanelWidth,RhsStorageOrder> triangularBuffer;
triangularBuffer.setZero();
@@ -345,13 +333,13 @@ struct product_triangular_matrix_matrix<Scalar,Index,Mode,false,
alpha,
actual_kc, actual_kc, // strides
blockOffset, blockOffset,// offsets
- allocatedBlockB); // workspace
+ blockW); // workspace
}
}
gebp_kernel(res+i2+(IsLower ? 0 : k2)*resStride, resStride,
blockA, geb, actual_mc, actual_kc, rs,
alpha,
- -1, -1, 0, 0, allocatedBlockB);
+ -1, -1, 0, 0, blockW);
}
}
}
@@ -378,26 +366,38 @@ struct TriangularProduct<Mode,LhsIsTriangular,Lhs,false,Rhs,false>
template<typename Dest> void scaleAndAddTo(Dest& dst, Scalar alpha) const
{
- const ActualLhsType lhs = LhsBlasTraits::extract(m_lhs);
- const ActualRhsType rhs = RhsBlasTraits::extract(m_rhs);
+ typename internal::add_const_on_value_type<ActualLhsType>::type lhs = LhsBlasTraits::extract(m_lhs);
+ typename internal::add_const_on_value_type<ActualRhsType>::type rhs = RhsBlasTraits::extract(m_rhs);
Scalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(m_lhs)
* RhsBlasTraits::extractScalarFactor(m_rhs);
+ typedef internal::gemm_blocking_space<(Dest::Flags&RowMajorBit) ? RowMajor : ColMajor,Scalar,Scalar,
+ Lhs::MaxRowsAtCompileTime, Rhs::MaxColsAtCompileTime, Lhs::MaxColsAtCompileTime,4> BlockingType;
+
+ enum { IsLower = (Mode&Lower) == Lower };
+ Index stripedRows = ((!LhsIsTriangular) || (IsLower)) ? lhs.rows() : (std::min)(lhs.rows(),lhs.cols());
+ Index stripedCols = ((LhsIsTriangular) || (!IsLower)) ? rhs.cols() : (std::min)(rhs.cols(),rhs.rows());
+ Index stripedDepth = LhsIsTriangular ? ((!IsLower) ? lhs.cols() : (std::min)(lhs.cols(),lhs.rows()))
+ : ((IsLower) ? rhs.rows() : (std::min)(rhs.rows(),rhs.cols()));
+
+ BlockingType blocking(stripedRows, stripedCols, stripedDepth);
+
internal::product_triangular_matrix_matrix<Scalar, Index,
Mode, LhsIsTriangular,
(internal::traits<_ActualLhsType>::Flags&RowMajorBit) ? RowMajor : ColMajor, LhsBlasTraits::NeedToConjugate,
(internal::traits<_ActualRhsType>::Flags&RowMajorBit) ? RowMajor : ColMajor, RhsBlasTraits::NeedToConjugate,
(internal::traits<Dest >::Flags&RowMajorBit) ? RowMajor : ColMajor>
::run(
- lhs.rows(), rhs.cols(), lhs.cols(),// LhsIsTriangular ? rhs.cols() : lhs.rows(), // sizes
+ stripedRows, stripedCols, stripedDepth, // sizes
&lhs.coeffRef(0,0), lhs.outerStride(), // lhs info
&rhs.coeffRef(0,0), rhs.outerStride(), // rhs info
- &dst.coeffRef(0,0), dst.outerStride(), // result info
- actualAlpha // alpha
+ &dst.coeffRef(0,0), dst.outerStride(), // result info
+ actualAlpha, blocking
);
}
};
+} // end namespace Eigen
#endif // EIGEN_TRIANGULAR_MATRIX_MATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix_MKL.h b/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix_MKL.h
new file mode 100644
index 00000000000..8173da5bb6d
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix_MKL.h
@@ -0,0 +1,309 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Triangular matrix * matrix product functionality based on ?TRMM.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_TRIANGULAR_MATRIX_MATRIX_MKL_H
+#define EIGEN_TRIANGULAR_MATRIX_MATRIX_MKL_H
+
+namespace Eigen {
+
+namespace internal {
+
+
+template <typename Scalar, typename Index,
+ int Mode, bool LhsIsTriangular,
+ int LhsStorageOrder, bool ConjugateLhs,
+ int RhsStorageOrder, bool ConjugateRhs,
+ int ResStorageOrder>
+struct product_triangular_matrix_matrix_trmm :
+ product_triangular_matrix_matrix<Scalar,Index,Mode,
+ LhsIsTriangular,LhsStorageOrder,ConjugateLhs,
+ RhsStorageOrder, ConjugateRhs, ResStorageOrder, BuiltIn> {};
+
+
+// try to go to BLAS specialization
+#define EIGEN_MKL_TRMM_SPECIALIZE(Scalar, LhsIsTriangular) \
+template <typename Index, int Mode, \
+ int LhsStorageOrder, bool ConjugateLhs, \
+ int RhsStorageOrder, bool ConjugateRhs> \
+struct product_triangular_matrix_matrix<Scalar,Index, Mode, LhsIsTriangular, \
+ LhsStorageOrder,ConjugateLhs, RhsStorageOrder,ConjugateRhs,ColMajor,Specialized> { \
+ static inline void run(Index _rows, Index _cols, Index _depth, const Scalar* _lhs, Index lhsStride,\
+ const Scalar* _rhs, Index rhsStride, Scalar* res, Index resStride, Scalar alpha) { \
+ product_triangular_matrix_matrix_trmm<Scalar,Index,Mode, \
+ LhsIsTriangular,LhsStorageOrder,ConjugateLhs, \
+ RhsStorageOrder, ConjugateRhs, ColMajor>::run( \
+ _rows, _cols, _depth, _lhs, lhsStride, _rhs, rhsStride, res, resStride, alpha); \
+ } \
+};
+
+EIGEN_MKL_TRMM_SPECIALIZE(double, true)
+EIGEN_MKL_TRMM_SPECIALIZE(double, false)
+EIGEN_MKL_TRMM_SPECIALIZE(dcomplex, true)
+EIGEN_MKL_TRMM_SPECIALIZE(dcomplex, false)
+EIGEN_MKL_TRMM_SPECIALIZE(float, true)
+EIGEN_MKL_TRMM_SPECIALIZE(float, false)
+EIGEN_MKL_TRMM_SPECIALIZE(scomplex, true)
+EIGEN_MKL_TRMM_SPECIALIZE(scomplex, false)
+
+// implements col-major += alpha * op(triangular) * op(general)
+#define EIGEN_MKL_TRMM_L(EIGTYPE, MKLTYPE, EIGPREFIX, MKLPREFIX) \
+template <typename Index, int Mode, \
+ int LhsStorageOrder, bool ConjugateLhs, \
+ int RhsStorageOrder, bool ConjugateRhs> \
+struct product_triangular_matrix_matrix_trmm<EIGTYPE,Index,Mode,true, \
+ LhsStorageOrder,ConjugateLhs,RhsStorageOrder,ConjugateRhs,ColMajor> \
+{ \
+ enum { \
+ IsLower = (Mode&Lower) == Lower, \
+ SetDiag = (Mode&(ZeroDiag|UnitDiag)) ? 0 : 1, \
+ IsUnitDiag = (Mode&UnitDiag) ? 1 : 0, \
+ IsZeroDiag = (Mode&ZeroDiag) ? 1 : 0, \
+ LowUp = IsLower ? Lower : Upper, \
+ conjA = ((LhsStorageOrder==ColMajor) && ConjugateLhs) ? 1 : 0 \
+ }; \
+\
+ static EIGEN_DONT_INLINE void run( \
+ Index _rows, Index _cols, Index _depth, \
+ const EIGTYPE* _lhs, Index lhsStride, \
+ const EIGTYPE* _rhs, Index rhsStride, \
+ EIGTYPE* res, Index resStride, \
+ EIGTYPE alpha) \
+ { \
+ Index diagSize = (std::min)(_rows,_depth); \
+ Index rows = IsLower ? _rows : diagSize; \
+ Index depth = IsLower ? diagSize : _depth; \
+ Index cols = _cols; \
+\
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic, LhsStorageOrder> MatrixLhs; \
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic, RhsStorageOrder> MatrixRhs; \
+\
+/* Non-square case - doesn't fit to MKL ?TRMM. Fall to default triangular product or call MKL ?GEMM*/ \
+ if (rows != depth) { \
+\
+ int nthr = mkl_domain_get_max_threads(MKL_BLAS); \
+\
+ if (((nthr==1) && (((std::max)(rows,depth)-diagSize)/(double)diagSize < 0.5))) { \
+ /* Most likely no benefit to call TRMM or GEMM from MKL*/ \
+ product_triangular_matrix_matrix<EIGTYPE,Index,Mode,true, \
+ LhsStorageOrder,ConjugateLhs, RhsStorageOrder, ConjugateRhs, ColMajor, BuiltIn>::run( \
+ _rows, _cols, _depth, _lhs, lhsStride, _rhs, rhsStride, res, resStride, alpha); \
+ /*std::cout << "TRMM_L: A is not square! Go to Eigen TRMM implementation!\n";*/ \
+ } else { \
+ /* Make sense to call GEMM */ \
+ Map<const MatrixLhs, 0, OuterStride<> > lhsMap(_lhs,rows,depth,OuterStride<>(lhsStride)); \
+ MatrixLhs aa_tmp=lhsMap.template triangularView<Mode>(); \
+ MKL_INT aStride = aa_tmp.outerStride(); \
+ gemm_blocking_space<ColMajor,EIGTYPE,EIGTYPE,Dynamic,Dynamic,Dynamic> blocking(_rows,_cols,_depth); \
+ general_matrix_matrix_product<Index,EIGTYPE,LhsStorageOrder,ConjugateLhs,EIGTYPE,RhsStorageOrder,ConjugateRhs,ColMajor>::run( \
+ rows, cols, depth, aa_tmp.data(), aStride, _rhs, rhsStride, res, resStride, alpha, blocking, 0); \
+\
+ /*std::cout << "TRMM_L: A is not square! Go to MKL GEMM implementation! " << nthr<<" \n";*/ \
+ } \
+ return; \
+ } \
+ char side = 'L', transa, uplo, diag = 'N'; \
+ EIGTYPE *b; \
+ const EIGTYPE *a; \
+ MKL_INT m, n, lda, ldb; \
+ MKLTYPE alpha_; \
+\
+/* Set alpha_*/ \
+ assign_scalar_eig2mkl<MKLTYPE, EIGTYPE>(alpha_, alpha); \
+\
+/* Set m, n */ \
+ m = (MKL_INT)diagSize; \
+ n = (MKL_INT)cols; \
+\
+/* Set trans */ \
+ transa = (LhsStorageOrder==RowMajor) ? ((ConjugateLhs) ? 'C' : 'T') : 'N'; \
+\
+/* Set b, ldb */ \
+ Map<const MatrixRhs, 0, OuterStride<> > rhs(_rhs,depth,cols,OuterStride<>(rhsStride)); \
+ MatrixX##EIGPREFIX b_tmp; \
+\
+ if (ConjugateRhs) b_tmp = rhs.conjugate(); else b_tmp = rhs; \
+ b = b_tmp.data(); \
+ ldb = b_tmp.outerStride(); \
+\
+/* Set uplo */ \
+ uplo = IsLower ? 'L' : 'U'; \
+ if (LhsStorageOrder==RowMajor) uplo = (uplo == 'L') ? 'U' : 'L'; \
+/* Set a, lda */ \
+ Map<const MatrixLhs, 0, OuterStride<> > lhs(_lhs,rows,depth,OuterStride<>(lhsStride)); \
+ MatrixLhs a_tmp; \
+\
+ if ((conjA!=0) || (SetDiag==0)) { \
+ if (conjA) a_tmp = lhs.conjugate(); else a_tmp = lhs; \
+ if (IsZeroDiag) \
+ a_tmp.diagonal().setZero(); \
+ else if (IsUnitDiag) \
+ a_tmp.diagonal().setOnes();\
+ a = a_tmp.data(); \
+ lda = a_tmp.outerStride(); \
+ } else { \
+ a = _lhs; \
+ lda = lhsStride; \
+ } \
+ /*std::cout << "TRMM_L: A is square! Go to MKL TRMM implementation! \n";*/ \
+/* call ?trmm*/ \
+ MKLPREFIX##trmm(&side, &uplo, &transa, &diag, &m, &n, &alpha_, (const MKLTYPE*)a, &lda, (MKLTYPE*)b, &ldb); \
+\
+/* Add op(a_triangular)*b into res*/ \
+ Map<MatrixX##EIGPREFIX, 0, OuterStride<> > res_tmp(res,rows,cols,OuterStride<>(resStride)); \
+ res_tmp=res_tmp+b_tmp; \
+ } \
+};
+
+EIGEN_MKL_TRMM_L(double, double, d, d)
+EIGEN_MKL_TRMM_L(dcomplex, MKL_Complex16, cd, z)
+EIGEN_MKL_TRMM_L(float, float, f, s)
+EIGEN_MKL_TRMM_L(scomplex, MKL_Complex8, cf, c)
+
+// implements col-major += alpha * op(general) * op(triangular)
+#define EIGEN_MKL_TRMM_R(EIGTYPE, MKLTYPE, EIGPREFIX, MKLPREFIX) \
+template <typename Index, int Mode, \
+ int LhsStorageOrder, bool ConjugateLhs, \
+ int RhsStorageOrder, bool ConjugateRhs> \
+struct product_triangular_matrix_matrix_trmm<EIGTYPE,Index,Mode,false, \
+ LhsStorageOrder,ConjugateLhs,RhsStorageOrder,ConjugateRhs,ColMajor> \
+{ \
+ enum { \
+ IsLower = (Mode&Lower) == Lower, \
+ SetDiag = (Mode&(ZeroDiag|UnitDiag)) ? 0 : 1, \
+ IsUnitDiag = (Mode&UnitDiag) ? 1 : 0, \
+ IsZeroDiag = (Mode&ZeroDiag) ? 1 : 0, \
+ LowUp = IsLower ? Lower : Upper, \
+ conjA = ((RhsStorageOrder==ColMajor) && ConjugateRhs) ? 1 : 0 \
+ }; \
+\
+ static EIGEN_DONT_INLINE void run( \
+ Index _rows, Index _cols, Index _depth, \
+ const EIGTYPE* _lhs, Index lhsStride, \
+ const EIGTYPE* _rhs, Index rhsStride, \
+ EIGTYPE* res, Index resStride, \
+ EIGTYPE alpha) \
+ { \
+ Index diagSize = (std::min)(_cols,_depth); \
+ Index rows = _rows; \
+ Index depth = IsLower ? _depth : diagSize; \
+ Index cols = IsLower ? diagSize : _cols; \
+\
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic, LhsStorageOrder> MatrixLhs; \
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic, RhsStorageOrder> MatrixRhs; \
+\
+/* Non-square case - doesn't fit to MKL ?TRMM. Fall to default triangular product or call MKL ?GEMM*/ \
+ if (cols != depth) { \
+\
+ int nthr = mkl_domain_get_max_threads(MKL_BLAS); \
+\
+ if ((nthr==1) && (((std::max)(cols,depth)-diagSize)/(double)diagSize < 0.5)) { \
+ /* Most likely no benefit to call TRMM or GEMM from MKL*/ \
+ product_triangular_matrix_matrix<EIGTYPE,Index,Mode,false, \
+ LhsStorageOrder,ConjugateLhs, RhsStorageOrder, ConjugateRhs, ColMajor, BuiltIn>::run( \
+ _rows, _cols, _depth, _lhs, lhsStride, _rhs, rhsStride, res, resStride, alpha); \
+ /*std::cout << "TRMM_R: A is not square! Go to Eigen TRMM implementation!\n";*/ \
+ } else { \
+ /* Make sense to call GEMM */ \
+ Map<const MatrixRhs, 0, OuterStride<> > rhsMap(_rhs,depth,cols, OuterStride<>(rhsStride)); \
+ MatrixRhs aa_tmp=rhsMap.template triangularView<Mode>(); \
+ MKL_INT aStride = aa_tmp.outerStride(); \
+ gemm_blocking_space<ColMajor,EIGTYPE,EIGTYPE,Dynamic,Dynamic,Dynamic> blocking(_rows,_cols,_depth); \
+ general_matrix_matrix_product<Index,EIGTYPE,LhsStorageOrder,ConjugateLhs,EIGTYPE,RhsStorageOrder,ConjugateRhs,ColMajor>::run( \
+ rows, cols, depth, _lhs, lhsStride, aa_tmp.data(), aStride, res, resStride, alpha, blocking, 0); \
+\
+ /*std::cout << "TRMM_R: A is not square! Go to MKL GEMM implementation! " << nthr<<" \n";*/ \
+ } \
+ return; \
+ } \
+ char side = 'R', transa, uplo, diag = 'N'; \
+ EIGTYPE *b; \
+ const EIGTYPE *a; \
+ MKL_INT m, n, lda, ldb; \
+ MKLTYPE alpha_; \
+\
+/* Set alpha_*/ \
+ assign_scalar_eig2mkl<MKLTYPE, EIGTYPE>(alpha_, alpha); \
+\
+/* Set m, n */ \
+ m = (MKL_INT)rows; \
+ n = (MKL_INT)diagSize; \
+\
+/* Set trans */ \
+ transa = (RhsStorageOrder==RowMajor) ? ((ConjugateRhs) ? 'C' : 'T') : 'N'; \
+\
+/* Set b, ldb */ \
+ Map<const MatrixLhs, 0, OuterStride<> > lhs(_lhs,rows,depth,OuterStride<>(lhsStride)); \
+ MatrixX##EIGPREFIX b_tmp; \
+\
+ if (ConjugateLhs) b_tmp = lhs.conjugate(); else b_tmp = lhs; \
+ b = b_tmp.data(); \
+ ldb = b_tmp.outerStride(); \
+\
+/* Set uplo */ \
+ uplo = IsLower ? 'L' : 'U'; \
+ if (RhsStorageOrder==RowMajor) uplo = (uplo == 'L') ? 'U' : 'L'; \
+/* Set a, lda */ \
+ Map<const MatrixRhs, 0, OuterStride<> > rhs(_rhs,depth,cols, OuterStride<>(rhsStride)); \
+ MatrixRhs a_tmp; \
+\
+ if ((conjA!=0) || (SetDiag==0)) { \
+ if (conjA) a_tmp = rhs.conjugate(); else a_tmp = rhs; \
+ if (IsZeroDiag) \
+ a_tmp.diagonal().setZero(); \
+ else if (IsUnitDiag) \
+ a_tmp.diagonal().setOnes();\
+ a = a_tmp.data(); \
+ lda = a_tmp.outerStride(); \
+ } else { \
+ a = _rhs; \
+ lda = rhsStride; \
+ } \
+ /*std::cout << "TRMM_R: A is square! Go to MKL TRMM implementation! \n";*/ \
+/* call ?trmm*/ \
+ MKLPREFIX##trmm(&side, &uplo, &transa, &diag, &m, &n, &alpha_, (const MKLTYPE*)a, &lda, (MKLTYPE*)b, &ldb); \
+\
+/* Add op(a_triangular)*b into res*/ \
+ Map<MatrixX##EIGPREFIX, 0, OuterStride<> > res_tmp(res,rows,cols,OuterStride<>(resStride)); \
+ res_tmp=res_tmp+b_tmp; \
+ } \
+};
+
+EIGEN_MKL_TRMM_R(double, double, d, d)
+EIGEN_MKL_TRMM_R(dcomplex, MKL_Complex16, cd, z)
+EIGEN_MKL_TRMM_R(float, float, f, s)
+EIGEN_MKL_TRMM_R(scomplex, MKL_Complex8, cf, c)
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_TRIANGULAR_MATRIX_MATRIX_MKL_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector.h b/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector.h
index 71b4a52ab80..b1c10c201c5 100644
--- a/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector.h
+++ b/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector.h
@@ -3,45 +3,36 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRIANGULARMATRIXVECTOR_H
#define EIGEN_TRIANGULARMATRIXVECTOR_H
+namespace Eigen {
+
namespace internal {
-template<typename Index, int Mode, typename LhsScalar, bool ConjLhs, typename RhsScalar, bool ConjRhs, int StorageOrder>
-struct product_triangular_matrix_vector;
+template<typename Index, int Mode, typename LhsScalar, bool ConjLhs, typename RhsScalar, bool ConjRhs, int StorageOrder, int Version=Specialized>
+struct triangular_matrix_vector_product;
-template<typename Index, int Mode, typename LhsScalar, bool ConjLhs, typename RhsScalar, bool ConjRhs>
-struct product_triangular_matrix_vector<Index,Mode,LhsScalar,ConjLhs,RhsScalar,ConjRhs,ColMajor>
+template<typename Index, int Mode, typename LhsScalar, bool ConjLhs, typename RhsScalar, bool ConjRhs, int Version>
+struct triangular_matrix_vector_product<Index,Mode,LhsScalar,ConjLhs,RhsScalar,ConjRhs,ColMajor,Version>
{
typedef typename scalar_product_traits<LhsScalar, RhsScalar>::ReturnType ResScalar;
enum {
IsLower = ((Mode&Lower)==Lower),
- HasUnitDiag = (Mode & UnitDiag)==UnitDiag
+ HasUnitDiag = (Mode & UnitDiag)==UnitDiag,
+ HasZeroDiag = (Mode & ZeroDiag)==ZeroDiag
};
- static EIGEN_DONT_INLINE void run(Index rows, Index cols, const LhsScalar* _lhs, Index lhsStride,
+ static EIGEN_DONT_INLINE void run(Index _rows, Index _cols, const LhsScalar* _lhs, Index lhsStride,
const RhsScalar* _rhs, Index rhsIncr, ResScalar* _res, Index resIncr, ResScalar alpha)
{
static const Index PanelWidth = EIGEN_TUNE_TRIANGULAR_PANEL_WIDTH;
+ Index size = (std::min)(_rows,_cols);
+ Index rows = IsLower ? _rows : (std::min)(_rows,_cols);
+ Index cols = IsLower ? (std::min)(_rows,_cols) : _cols;
typedef Map<const Matrix<LhsScalar,Dynamic,Dynamic,ColMajor>, 0, OuterStride<> > LhsMap;
const LhsMap lhs(_lhs,rows,cols,OuterStride<>(lhsStride));
@@ -54,45 +45,57 @@ struct product_triangular_matrix_vector<Index,Mode,LhsScalar,ConjLhs,RhsScalar,C
typedef Map<Matrix<ResScalar,Dynamic,1> > ResMap;
ResMap res(_res,rows);
- for (Index pi=0; pi<cols; pi+=PanelWidth)
+ for (Index pi=0; pi<size; pi+=PanelWidth)
{
- Index actualPanelWidth = (std::min)(PanelWidth, cols-pi);
+ Index actualPanelWidth = (std::min)(PanelWidth, size-pi);
for (Index k=0; k<actualPanelWidth; ++k)
{
Index i = pi + k;
- Index s = IsLower ? (HasUnitDiag ? i+1 : i ) : pi;
+ Index s = IsLower ? ((HasUnitDiag||HasZeroDiag) ? i+1 : i ) : pi;
Index r = IsLower ? actualPanelWidth-k : k+1;
- if ((!HasUnitDiag) || (--r)>0)
+ if ((!(HasUnitDiag||HasZeroDiag)) || (--r)>0)
res.segment(s,r) += (alpha * cjRhs.coeff(i)) * cjLhs.col(i).segment(s,r);
if (HasUnitDiag)
res.coeffRef(i) += alpha * cjRhs.coeff(i);
}
- Index r = IsLower ? cols - pi - actualPanelWidth : pi;
+ Index r = IsLower ? rows - pi - actualPanelWidth : pi;
if (r>0)
{
Index s = IsLower ? pi+actualPanelWidth : 0;
- general_matrix_vector_product<Index,LhsScalar,ColMajor,ConjLhs,RhsScalar,ConjRhs>::run(
+ general_matrix_vector_product<Index,LhsScalar,ColMajor,ConjLhs,RhsScalar,ConjRhs,BuiltIn>::run(
r, actualPanelWidth,
&lhs.coeffRef(s,pi), lhsStride,
&rhs.coeffRef(pi), rhsIncr,
&res.coeffRef(s), resIncr, alpha);
}
}
+ if((!IsLower) && cols>size)
+ {
+ general_matrix_vector_product<Index,LhsScalar,ColMajor,ConjLhs,RhsScalar,ConjRhs>::run(
+ rows, cols-size,
+ &lhs.coeffRef(0,size), lhsStride,
+ &rhs.coeffRef(size), rhsIncr,
+ _res, resIncr, alpha);
+ }
}
};
-template<typename Index, int Mode, typename LhsScalar, bool ConjLhs, typename RhsScalar, bool ConjRhs>
-struct product_triangular_matrix_vector<Index,Mode,LhsScalar,ConjLhs,RhsScalar,ConjRhs,RowMajor>
+template<typename Index, int Mode, typename LhsScalar, bool ConjLhs, typename RhsScalar, bool ConjRhs,int Version>
+struct triangular_matrix_vector_product<Index,Mode,LhsScalar,ConjLhs,RhsScalar,ConjRhs,RowMajor,Version>
{
typedef typename scalar_product_traits<LhsScalar, RhsScalar>::ReturnType ResScalar;
enum {
IsLower = ((Mode&Lower)==Lower),
- HasUnitDiag = (Mode & UnitDiag)==UnitDiag
+ HasUnitDiag = (Mode & UnitDiag)==UnitDiag,
+ HasZeroDiag = (Mode & ZeroDiag)==ZeroDiag
};
- static void run(Index rows, Index cols, const LhsScalar* _lhs, Index lhsStride,
+ static void run(Index _rows, Index _cols, const LhsScalar* _lhs, Index lhsStride,
const RhsScalar* _rhs, Index rhsIncr, ResScalar* _res, Index resIncr, ResScalar alpha)
{
static const Index PanelWidth = EIGEN_TUNE_TRIANGULAR_PANEL_WIDTH;
+ Index diagSize = (std::min)(_rows,_cols);
+ Index rows = IsLower ? _rows : diagSize;
+ Index cols = IsLower ? diagSize : _cols;
typedef Map<const Matrix<LhsScalar,Dynamic,Dynamic,RowMajor>, 0, OuterStride<> > LhsMap;
const LhsMap lhs(_lhs,rows,cols,OuterStride<>(lhsStride));
@@ -105,15 +108,15 @@ struct product_triangular_matrix_vector<Index,Mode,LhsScalar,ConjLhs,RhsScalar,C
typedef Map<Matrix<ResScalar,Dynamic,1>, 0, InnerStride<> > ResMap;
ResMap res(_res,rows,InnerStride<>(resIncr));
- for (Index pi=0; pi<cols; pi+=PanelWidth)
+ for (Index pi=0; pi<diagSize; pi+=PanelWidth)
{
- Index actualPanelWidth = (std::min)(PanelWidth, cols-pi);
+ Index actualPanelWidth = (std::min)(PanelWidth, diagSize-pi);
for (Index k=0; k<actualPanelWidth; ++k)
{
Index i = pi + k;
- Index s = IsLower ? pi : (HasUnitDiag ? i+1 : i);
+ Index s = IsLower ? pi : ((HasUnitDiag||HasZeroDiag) ? i+1 : i);
Index r = IsLower ? k+1 : actualPanelWidth-k;
- if ((!HasUnitDiag) || (--r)>0)
+ if ((!(HasUnitDiag||HasZeroDiag)) || (--r)>0)
res.coeffRef(i) += alpha * (cjLhs.row(i).segment(s,r).cwiseProduct(cjRhs.segment(s,r).transpose())).sum();
if (HasUnitDiag)
res.coeffRef(i) += alpha * cjRhs.coeff(i);
@@ -122,13 +125,21 @@ struct product_triangular_matrix_vector<Index,Mode,LhsScalar,ConjLhs,RhsScalar,C
if (r>0)
{
Index s = IsLower ? 0 : pi + actualPanelWidth;
- general_matrix_vector_product<Index,LhsScalar,RowMajor,ConjLhs,RhsScalar,ConjRhs>::run(
+ general_matrix_vector_product<Index,LhsScalar,RowMajor,ConjLhs,RhsScalar,ConjRhs,BuiltIn>::run(
actualPanelWidth, r,
&lhs.coeffRef(pi,s), lhsStride,
&rhs.coeffRef(s), rhsIncr,
&res.coeffRef(pi), resIncr, alpha);
}
}
+ if(IsLower && rows>diagSize)
+ {
+ general_matrix_vector_product<Index,LhsScalar,RowMajor,ConjLhs,RhsScalar,ConjRhs>::run(
+ rows-diagSize, cols,
+ &lhs.coeffRef(diagSize,0), lhsStride,
+ &rhs.coeffRef(0), rhsIncr,
+ &res.coeffRef(diagSize), resIncr, alpha);
+ }
}
};
@@ -180,7 +191,7 @@ struct TriangularProduct<Mode,false,Lhs,true,Rhs,false>
{
eigen_assert(dst.rows()==m_lhs.rows() && dst.cols()==m_rhs.cols());
- typedef TriangularProduct<(Mode & UnitDiag) | ((Mode & Lower) ? Upper : Lower),true,Transpose<const Rhs>,false,Transpose<const Lhs>,true> TriangularProductTranspose;
+ typedef TriangularProduct<(Mode & (UnitDiag|ZeroDiag)) | ((Mode & Lower) ? Upper : Lower),true,Transpose<const Rhs>,false,Transpose<const Lhs>,true> TriangularProductTranspose;
Transpose<Dest> dstT(dst);
internal::trmv_selector<(int(internal::traits<Rhs>::Flags)&RowMajorBit) ? ColMajor : RowMajor>::run(
TriangularProductTranspose(m_rhs.transpose(),m_lhs.transpose()), dstT, alpha);
@@ -208,8 +219,8 @@ template<> struct trmv_selector<ColMajor>
typedef typename ProductType::RhsBlasTraits RhsBlasTraits;
typedef Map<Matrix<ResScalar,Dynamic,1>, Aligned> MappedDest;
- const ActualLhsType actualLhs = LhsBlasTraits::extract(prod.lhs());
- const ActualRhsType actualRhs = RhsBlasTraits::extract(prod.rhs());
+ typename internal::add_const_on_value_type<ActualLhsType>::type actualLhs = LhsBlasTraits::extract(prod.lhs());
+ typename internal::add_const_on_value_type<ActualRhsType>::type actualRhs = RhsBlasTraits::extract(prod.rhs());
ResScalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(prod.lhs())
* RhsBlasTraits::extractScalarFactor(prod.rhs());
@@ -247,7 +258,7 @@ template<> struct trmv_selector<ColMajor>
MappedDest(actualDestPtr, dest.size()) = dest;
}
- internal::product_triangular_matrix_vector
+ internal::triangular_matrix_vector_product
<Index,Mode,
LhsScalar, LhsBlasTraits::NeedToConjugate,
RhsScalar, RhsBlasTraits::NeedToConjugate,
@@ -307,7 +318,7 @@ template<> struct trmv_selector<RowMajor>
Map<typename _ActualRhsType::PlainObject>(actualRhsPtr, actualRhs.size()) = actualRhs;
}
- internal::product_triangular_matrix_vector
+ internal::triangular_matrix_vector_product
<Index,Mode,
LhsScalar, LhsBlasTraits::NeedToConjugate,
RhsScalar, RhsBlasTraits::NeedToConjugate,
@@ -322,4 +333,6 @@ template<> struct trmv_selector<RowMajor>
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_TRIANGULARMATRIXVECTOR_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector_MKL.h b/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector_MKL.h
new file mode 100644
index 00000000000..3589b8c5ef6
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector_MKL.h
@@ -0,0 +1,247 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Triangular matrix-vector product functionality based on ?TRMV.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_TRIANGULAR_MATRIX_VECTOR_MKL_H
+#define EIGEN_TRIANGULAR_MATRIX_VECTOR_MKL_H
+
+namespace Eigen {
+
+namespace internal {
+
+/**********************************************************************
+* This file implements triangular matrix-vector multiplication using BLAS
+**********************************************************************/
+
+// trmv/hemv specialization
+
+template<typename Index, int Mode, typename LhsScalar, bool ConjLhs, typename RhsScalar, bool ConjRhs, int StorageOrder>
+struct triangular_matrix_vector_product_trmv :
+ triangular_matrix_vector_product<Index,Mode,LhsScalar,ConjLhs,RhsScalar,ConjRhs,StorageOrder,BuiltIn> {};
+
+#define EIGEN_MKL_TRMV_SPECIALIZE(Scalar) \
+template<typename Index, int Mode, bool ConjLhs, bool ConjRhs> \
+struct triangular_matrix_vector_product<Index,Mode,Scalar,ConjLhs,Scalar,ConjRhs,ColMajor,Specialized> { \
+ static EIGEN_DONT_INLINE void run(Index _rows, Index _cols, const Scalar* _lhs, Index lhsStride, \
+ const Scalar* _rhs, Index rhsIncr, Scalar* _res, Index resIncr, Scalar alpha) { \
+ triangular_matrix_vector_product_trmv<Index,Mode,Scalar,ConjLhs,Scalar,ConjRhs,ColMajor>::run( \
+ _rows, _cols, _lhs, lhsStride, _rhs, rhsIncr, _res, resIncr, alpha); \
+ } \
+}; \
+template<typename Index, int Mode, bool ConjLhs, bool ConjRhs> \
+struct triangular_matrix_vector_product<Index,Mode,Scalar,ConjLhs,Scalar,ConjRhs,RowMajor,Specialized> { \
+ static EIGEN_DONT_INLINE void run(Index _rows, Index _cols, const Scalar* _lhs, Index lhsStride, \
+ const Scalar* _rhs, Index rhsIncr, Scalar* _res, Index resIncr, Scalar alpha) { \
+ triangular_matrix_vector_product_trmv<Index,Mode,Scalar,ConjLhs,Scalar,ConjRhs,RowMajor>::run( \
+ _rows, _cols, _lhs, lhsStride, _rhs, rhsIncr, _res, resIncr, alpha); \
+ } \
+};
+
+EIGEN_MKL_TRMV_SPECIALIZE(double)
+EIGEN_MKL_TRMV_SPECIALIZE(float)
+EIGEN_MKL_TRMV_SPECIALIZE(dcomplex)
+EIGEN_MKL_TRMV_SPECIALIZE(scomplex)
+
+// implements col-major: res += alpha * op(triangular) * vector
+#define EIGEN_MKL_TRMV_CM(EIGTYPE, MKLTYPE, EIGPREFIX, MKLPREFIX) \
+template<typename Index, int Mode, bool ConjLhs, bool ConjRhs> \
+struct triangular_matrix_vector_product_trmv<Index,Mode,EIGTYPE,ConjLhs,EIGTYPE,ConjRhs,ColMajor> { \
+ enum { \
+ IsLower = (Mode&Lower) == Lower, \
+ SetDiag = (Mode&(ZeroDiag|UnitDiag)) ? 0 : 1, \
+ IsUnitDiag = (Mode&UnitDiag) ? 1 : 0, \
+ IsZeroDiag = (Mode&ZeroDiag) ? 1 : 0, \
+ LowUp = IsLower ? Lower : Upper \
+ }; \
+ static EIGEN_DONT_INLINE void run(Index _rows, Index _cols, const EIGTYPE* _lhs, Index lhsStride, \
+ const EIGTYPE* _rhs, Index rhsIncr, EIGTYPE* _res, Index resIncr, EIGTYPE alpha, level3_blocking<EIGTYPE,EIGTYPE>& blocking) \
+ { \
+ if (ConjLhs || IsZeroDiag) { \
+ triangular_matrix_vector_product<Index,Mode,EIGTYPE,ConjLhs,EIGTYPE,ConjRhs,ColMajor,BuiltIn>::run( \
+ _rows, _cols, _lhs, lhsStride, _rhs, rhsIncr, _res, resIncr, alpha, blocking); \
+ return; \
+ }\
+ Index size = (std::min)(_rows,_cols); \
+ Index rows = IsLower ? _rows : size; \
+ Index cols = IsLower ? size : _cols; \
+\
+ typedef VectorX##EIGPREFIX VectorRhs; \
+ EIGTYPE *x, *y;\
+\
+/* Set x*/ \
+ Map<const VectorRhs, 0, InnerStride<> > rhs(_rhs,cols,InnerStride<>(rhsIncr)); \
+ VectorRhs x_tmp; \
+ if (ConjRhs) x_tmp = rhs.conjugate(); else x_tmp = rhs; \
+ x = x_tmp.data(); \
+\
+/* Square part handling */\
+\
+ char trans, uplo, diag; \
+ MKL_INT m, n, lda, incx, incy; \
+ EIGTYPE const *a; \
+ MKLTYPE alpha_, beta_; \
+ assign_scalar_eig2mkl<MKLTYPE, EIGTYPE>(alpha_, alpha); \
+ assign_scalar_eig2mkl<MKLTYPE, EIGTYPE>(beta_, EIGTYPE(1)); \
+\
+/* Set m, n */ \
+ n = (MKL_INT)size; \
+ lda = lhsStride; \
+ incx = 1; \
+ incy = resIncr; \
+\
+/* Set uplo, trans and diag*/ \
+ trans = 'N'; \
+ uplo = IsLower ? 'L' : 'U'; \
+ diag = IsUnitDiag ? 'U' : 'N'; \
+\
+/* call ?TRMV*/ \
+ MKLPREFIX##trmv(&uplo, &trans, &diag, &n, (const MKLTYPE*)_lhs, &lda, (MKLTYPE*)x, &incx); \
+\
+/* Add op(a_tr)rhs into res*/ \
+ MKLPREFIX##axpy(&n, &alpha_,(const MKLTYPE*)x, &incx, (MKLTYPE*)_res, &incy); \
+/* Non-square case - doesn't fit to MKL ?TRMV. Fall to default triangular product*/ \
+ if (size<(std::max)(rows,cols)) { \
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic> MatrixLhs; \
+ if (ConjRhs) x_tmp = rhs.conjugate(); else x_tmp = rhs; \
+ x = x_tmp.data(); \
+ if (size<rows) { \
+ y = _res + size*resIncr; \
+ a = _lhs + size; \
+ m = rows-size; \
+ n = size; \
+ } \
+ else { \
+ x += size; \
+ y = _res; \
+ a = _lhs + size*lda; \
+ m = size; \
+ n = cols-size; \
+ } \
+ MKLPREFIX##gemv(&trans, &m, &n, &alpha_, (const MKLTYPE*)a, &lda, (const MKLTYPE*)x, &incx, &beta_, (MKLTYPE*)y, &incy); \
+ } \
+ } \
+};
+
+EIGEN_MKL_TRMV_CM(double, double, d, d)
+EIGEN_MKL_TRMV_CM(dcomplex, MKL_Complex16, cd, z)
+EIGEN_MKL_TRMV_CM(float, float, f, s)
+EIGEN_MKL_TRMV_CM(scomplex, MKL_Complex8, cf, c)
+
+// implements row-major: res += alpha * op(triangular) * vector
+#define EIGEN_MKL_TRMV_RM(EIGTYPE, MKLTYPE, EIGPREFIX, MKLPREFIX) \
+template<typename Index, int Mode, bool ConjLhs, bool ConjRhs> \
+struct triangular_matrix_vector_product_trmv<Index,Mode,EIGTYPE,ConjLhs,EIGTYPE,ConjRhs,RowMajor> { \
+ enum { \
+ IsLower = (Mode&Lower) == Lower, \
+ SetDiag = (Mode&(ZeroDiag|UnitDiag)) ? 0 : 1, \
+ IsUnitDiag = (Mode&UnitDiag) ? 1 : 0, \
+ IsZeroDiag = (Mode&ZeroDiag) ? 1 : 0, \
+ LowUp = IsLower ? Lower : Upper \
+ }; \
+ static EIGEN_DONT_INLINE void run(Index _rows, Index _cols, const EIGTYPE* _lhs, Index lhsStride, \
+ const EIGTYPE* _rhs, Index rhsIncr, EIGTYPE* _res, Index resIncr, EIGTYPE alpha, level3_blocking<EIGTYPE,EIGTYPE>& blocking) \
+ { \
+ if (IsZeroDiag) { \
+ triangular_matrix_vector_product<Index,Mode,EIGTYPE,ConjLhs,EIGTYPE,ConjRhs,RowMajor,BuiltIn>::run( \
+ _rows, _cols, _lhs, lhsStride, _rhs, rhsIncr, _res, resIncr, alpha, blocking); \
+ return; \
+ }\
+ Index size = (std::min)(_rows,_cols); \
+ Index rows = IsLower ? _rows : size; \
+ Index cols = IsLower ? size : _cols; \
+\
+ typedef VectorX##EIGPREFIX VectorRhs; \
+ EIGTYPE *x, *y;\
+\
+/* Set x*/ \
+ Map<const VectorRhs, 0, InnerStride<> > rhs(_rhs,cols,InnerStride<>(rhsIncr)); \
+ VectorRhs x_tmp; \
+ if (ConjRhs) x_tmp = rhs.conjugate(); else x_tmp = rhs; \
+ x = x_tmp.data(); \
+\
+/* Square part handling */\
+\
+ char trans, uplo, diag; \
+ MKL_INT m, n, lda, incx, incy; \
+ EIGTYPE const *a; \
+ MKLTYPE alpha_, beta_; \
+ assign_scalar_eig2mkl<MKLTYPE, EIGTYPE>(alpha_, alpha); \
+ assign_scalar_eig2mkl<MKLTYPE, EIGTYPE>(beta_, EIGTYPE(1)); \
+\
+/* Set m, n */ \
+ n = (MKL_INT)size; \
+ lda = lhsStride; \
+ incx = 1; \
+ incy = resIncr; \
+\
+/* Set uplo, trans and diag*/ \
+ trans = ConjLhs ? 'C' : 'T'; \
+ uplo = IsLower ? 'U' : 'L'; \
+ diag = IsUnitDiag ? 'U' : 'N'; \
+\
+/* call ?TRMV*/ \
+ MKLPREFIX##trmv(&uplo, &trans, &diag, &n, (const MKLTYPE*)_lhs, &lda, (MKLTYPE*)x, &incx); \
+\
+/* Add op(a_tr)rhs into res*/ \
+ MKLPREFIX##axpy(&n, &alpha_,(const MKLTYPE*)x, &incx, (MKLTYPE*)_res, &incy); \
+/* Non-square case - doesn't fit to MKL ?TRMV. Fall to default triangular product*/ \
+ if (size<(std::max)(rows,cols)) { \
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic> MatrixLhs; \
+ if (ConjRhs) x_tmp = rhs.conjugate(); else x_tmp = rhs; \
+ x = x_tmp.data(); \
+ if (size<rows) { \
+ y = _res + size*resIncr; \
+ a = _lhs + size*lda; \
+ m = rows-size; \
+ n = size; \
+ } \
+ else { \
+ x += size; \
+ y = _res; \
+ a = _lhs + size; \
+ m = size; \
+ n = cols-size; \
+ } \
+ MKLPREFIX##gemv(&trans, &n, &m, &alpha_, (const MKLTYPE*)a, &lda, (const MKLTYPE*)x, &incx, &beta_, (MKLTYPE*)y, &incy); \
+ } \
+ } \
+};
+
+EIGEN_MKL_TRMV_RM(double, double, d, d)
+EIGEN_MKL_TRMV_RM(dcomplex, MKL_Complex16, cd, z)
+EIGEN_MKL_TRMV_RM(float, float, f, s)
+EIGEN_MKL_TRMV_RM(scomplex, MKL_Complex8, cf, c)
+
+} // end namespase internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_TRIANGULAR_MATRIX_VECTOR_MKL_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/TriangularSolverMatrix.h b/extern/Eigen3/Eigen/src/Core/products/TriangularSolverMatrix.h
index 4dced6b0eb9..a49ea318345 100644
--- a/extern/Eigen3/Eigen/src/Core/products/TriangularSolverMatrix.h
+++ b/extern/Eigen3/Eigen/src/Core/products/TriangularSolverMatrix.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRIANGULAR_SOLVER_MATRIX_H
#define EIGEN_TRIANGULAR_SOLVER_MATRIX_H
+namespace Eigen {
+
namespace internal {
// if the rhs is row major, let's transpose the product
@@ -34,14 +21,15 @@ struct triangular_solve_matrix<Scalar,Index,Side,Mode,Conjugate,TriStorageOrder,
static EIGEN_DONT_INLINE void run(
Index size, Index cols,
const Scalar* tri, Index triStride,
- Scalar* _other, Index otherStride)
+ Scalar* _other, Index otherStride,
+ level3_blocking<Scalar,Scalar>& blocking)
{
triangular_solve_matrix<
Scalar, Index, Side==OnTheLeft?OnTheRight:OnTheLeft,
(Mode&UnitDiag) | ((Mode&Upper) ? Lower : Upper),
NumTraits<Scalar>::IsComplex && Conjugate,
TriStorageOrder==RowMajor ? ColMajor : RowMajor, ColMajor>
- ::run(size, cols, tri, triStride, _other, otherStride);
+ ::run(size, cols, tri, triStride, _other, otherStride, blocking);
}
};
@@ -53,7 +41,8 @@ struct triangular_solve_matrix<Scalar,Index,OnTheLeft,Mode,Conjugate,TriStorageO
static EIGEN_DONT_INLINE void run(
Index size, Index otherSize,
const Scalar* _tri, Index triStride,
- Scalar* _other, Index otherStride)
+ Scalar* _other, Index otherStride,
+ level3_blocking<Scalar,Scalar>& blocking)
{
Index cols = otherSize;
const_blas_data_mapper<Scalar, Index, TriStorageOrder> tri(_tri,triStride);
@@ -65,22 +54,29 @@ struct triangular_solve_matrix<Scalar,Index,OnTheLeft,Mode,Conjugate,TriStorageO
IsLower = (Mode&Lower) == Lower
};
- Index kc = size; // cache block size along the K direction
- Index mc = size; // cache block size along the M direction
- Index nc = cols; // cache block size along the N direction
- computeProductBlockingSizes<Scalar,Scalar,4>(kc, mc, nc);
+ Index kc = blocking.kc(); // cache block size along the K direction
+ Index mc = (std::min)(size,blocking.mc()); // cache block size along the M direction
+ std::size_t sizeA = kc*mc;
+ std::size_t sizeB = kc*cols;
std::size_t sizeW = kc*Traits::WorkSpaceFactor;
- std::size_t sizeB = sizeW + kc*cols;
- ei_declare_aligned_stack_constructed_variable(Scalar, blockA, kc*mc, 0);
- ei_declare_aligned_stack_constructed_variable(Scalar, allocatedBlockB, sizeB, 0);
- Scalar* blockB = allocatedBlockB + sizeW;
+
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockA, sizeA, blocking.blockA());
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockB, sizeB, blocking.blockB());
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockW, sizeW, blocking.blockW());
conj_if<Conjugate> conj;
gebp_kernel<Scalar, Scalar, Index, Traits::mr, Traits::nr, Conjugate, false> gebp_kernel;
gemm_pack_lhs<Scalar, Index, Traits::mr, Traits::LhsProgress, TriStorageOrder> pack_lhs;
gemm_pack_rhs<Scalar, Index, Traits::nr, ColMajor, false, true> pack_rhs;
+ // the goal here is to subdivise the Rhs panels such that we keep some cache
+ // coherence when accessing the rhs elements
+ std::ptrdiff_t l1, l2;
+ manage_caching_sizes(GetAction, &l1, &l2);
+ Index subcols = cols>0 ? l2/(4 * sizeof(Scalar) * otherStride) : 0;
+ subcols = std::max<Index>((subcols/Traits::nr)*Traits::nr, Traits::nr);
+
for(Index k2=IsLower ? 0 : size;
IsLower ? k2<size : k2>0;
IsLower ? k2+=kc : k2-=kc)
@@ -92,16 +88,18 @@ struct triangular_solve_matrix<Scalar,Index,OnTheLeft,Mode,Conjugate,TriStorageO
// A11 (the triangular part) and A21 the remaining rectangular part.
// Then the high level algorithm is:
// - B = R1 => general block copy (done during the next step)
- // - R1 = L1^-1 B => tricky part
+ // - R1 = A11^-1 B => tricky part
// - update B from the new R1 => actually this has to be performed continuously during the above step
- // - R2 = L2 * B => GEPP
+ // - R2 -= A21 * B => GEPP
- // The tricky part: compute R1 = L1^-1 B while updating B from R1
- // The idea is to split L1 into multiple small vertical panels.
- // Each panel can be split into a small triangular part A1 which is processed without optimization,
- // and the remaining small part A2 which is processed using gebp with appropriate block strides
+ // The tricky part: compute R1 = A11^-1 B while updating B from R1
+ // The idea is to split A11 into multiple small vertical panels.
+ // Each panel can be split into a small triangular part T1k which is processed without optimization,
+ // and the remaining small part T2k which is processed using gebp with appropriate block strides
+ for(Index j2=0; j2<cols; j2+=subcols)
{
- // for each small vertical panels of lhs
+ Index actual_cols = (std::min)(cols-j2,subcols);
+ // for each small vertical panels [T1k^T, T2k^T]^T of lhs
for (Index k1=0; k1<actual_kc; k1+=SmallPanelWidth)
{
Index actualPanelWidth = std::min<Index>(actual_kc-k1, SmallPanelWidth);
@@ -114,11 +112,11 @@ struct triangular_solve_matrix<Scalar,Index,OnTheLeft,Mode,Conjugate,TriStorageO
Index rs = actualPanelWidth - k - 1; // remaining size
Scalar a = (Mode & UnitDiag) ? Scalar(1) : Scalar(1)/conj(tri(i,i));
- for (Index j=0; j<cols; ++j)
+ for (Index j=j2; j<j2+actual_cols; ++j)
{
if (TriStorageOrder==RowMajor)
{
- Scalar b = 0;
+ Scalar b(0);
const Scalar* l = &tri(i,s);
Scalar* r = &other(s,j);
for (Index i3=0; i3<k; ++i3)
@@ -143,7 +141,7 @@ struct triangular_solve_matrix<Scalar,Index,OnTheLeft,Mode,Conjugate,TriStorageO
Index blockBOffset = IsLower ? k1 : lengthTarget;
// update the respective rows of B from other
- pack_rhs(blockB, _other+startBlock, otherStride, actualPanelWidth, cols, actual_kc, blockBOffset);
+ pack_rhs(blockB+actual_kc*j2, &other(startBlock,j2), otherStride, actualPanelWidth, actual_cols, actual_kc, blockBOffset);
// GEBP
if (lengthTarget>0)
@@ -152,13 +150,13 @@ struct triangular_solve_matrix<Scalar,Index,OnTheLeft,Mode,Conjugate,TriStorageO
pack_lhs(blockA, &tri(startTarget,startBlock), triStride, actualPanelWidth, lengthTarget);
- gebp_kernel(_other+startTarget, otherStride, blockA, blockB, lengthTarget, actualPanelWidth, cols, Scalar(-1),
- actualPanelWidth, actual_kc, 0, blockBOffset);
+ gebp_kernel(&other(startTarget,j2), otherStride, blockA, blockB+actual_kc*j2, lengthTarget, actualPanelWidth, actual_cols, Scalar(-1),
+ actualPanelWidth, actual_kc, 0, blockBOffset, blockW);
}
}
}
-
- // R2 = A2 * B => GEPP
+
+ // R2 -= A21 * B => GEPP
{
Index start = IsLower ? k2+kc : 0;
Index end = IsLower ? size : k2-kc;
@@ -169,7 +167,7 @@ struct triangular_solve_matrix<Scalar,Index,OnTheLeft,Mode,Conjugate,TriStorageO
{
pack_lhs(blockA, &tri(i2, IsLower ? k2 : k2-kc), triStride, actual_kc, actual_mc);
- gebp_kernel(_other+i2, otherStride, blockA, blockB, actual_mc, actual_kc, cols, Scalar(-1));
+ gebp_kernel(_other+i2, otherStride, blockA, blockB, actual_mc, actual_kc, cols, Scalar(-1), -1, -1, 0, 0, blockW);
}
}
}
@@ -185,7 +183,8 @@ struct triangular_solve_matrix<Scalar,Index,OnTheRight,Mode,Conjugate,TriStorage
static EIGEN_DONT_INLINE void run(
Index size, Index otherSize,
const Scalar* _tri, Index triStride,
- Scalar* _other, Index otherStride)
+ Scalar* _other, Index otherStride,
+ level3_blocking<Scalar,Scalar>& blocking)
{
Index rows = otherSize;
const_blas_data_mapper<Scalar, Index, TriStorageOrder> rhs(_tri,triStride);
@@ -198,19 +197,16 @@ struct triangular_solve_matrix<Scalar,Index,OnTheRight,Mode,Conjugate,TriStorage
IsLower = (Mode&Lower) == Lower
};
-// Index kc = std::min<Index>(Traits::Max_kc/4,size); // cache block size along the K direction
-// Index mc = std::min<Index>(Traits::Max_mc,size); // cache block size along the M direction
- // check that !!!!
- Index kc = size; // cache block size along the K direction
- Index mc = size; // cache block size along the M direction
- Index nc = rows; // cache block size along the N direction
- computeProductBlockingSizes<Scalar,Scalar,4>(kc, mc, nc);
+ Index kc = blocking.kc(); // cache block size along the K direction
+ Index mc = (std::min)(rows,blocking.mc()); // cache block size along the M direction
+ std::size_t sizeA = kc*mc;
+ std::size_t sizeB = kc*size;
std::size_t sizeW = kc*Traits::WorkSpaceFactor;
- std::size_t sizeB = sizeW + kc*size;
- ei_declare_aligned_stack_constructed_variable(Scalar, blockA, kc*mc, 0);
- ei_declare_aligned_stack_constructed_variable(Scalar, allocatedBlockB, sizeB, 0);
- Scalar* blockB = allocatedBlockB + sizeW;
+
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockA, sizeA, blocking.blockA());
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockB, sizeB, blocking.blockB());
+ ei_declare_aligned_stack_constructed_variable(Scalar, blockW, sizeW, blocking.blockW());
conj_if<Conjugate> conj;
gebp_kernel<Scalar,Scalar, Index, Traits::mr, Traits::nr, false, Conjugate> gebp_kernel;
@@ -277,7 +273,7 @@ struct triangular_solve_matrix<Scalar,Index,OnTheRight,Mode,Conjugate,TriStorage
Scalar(-1),
actual_kc, actual_kc, // strides
panelOffset, panelOffset, // offsets
- allocatedBlockB); // workspace
+ blockW); // workspace
}
// unblocked triangular solve
@@ -308,7 +304,7 @@ struct triangular_solve_matrix<Scalar,Index,OnTheRight,Mode,Conjugate,TriStorage
if (rs>0)
gebp_kernel(_other+i2+startPanel*otherStride, otherStride, blockA, geb,
actual_mc, actual_kc, rs, Scalar(-1),
- -1, -1, 0, 0, allocatedBlockB);
+ -1, -1, 0, 0, blockW);
}
}
}
@@ -316,4 +312,6 @@ struct triangular_solve_matrix<Scalar,Index,OnTheRight,Mode,Conjugate,TriStorage
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_TRIANGULAR_SOLVER_MATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/TriangularSolverMatrix_MKL.h b/extern/Eigen3/Eigen/src/Core/products/TriangularSolverMatrix_MKL.h
new file mode 100644
index 00000000000..a4f508b2e83
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/products/TriangularSolverMatrix_MKL.h
@@ -0,0 +1,155 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Triangular matrix * matrix product functionality based on ?TRMM.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_TRIANGULAR_SOLVER_MATRIX_MKL_H
+#define EIGEN_TRIANGULAR_SOLVER_MATRIX_MKL_H
+
+namespace Eigen {
+
+namespace internal {
+
+// implements LeftSide op(triangular)^-1 * general
+#define EIGEN_MKL_TRSM_L(EIGTYPE, MKLTYPE, MKLPREFIX) \
+template <typename Index, int Mode, bool Conjugate, int TriStorageOrder> \
+struct triangular_solve_matrix<EIGTYPE,Index,OnTheLeft,Mode,Conjugate,TriStorageOrder,ColMajor> \
+{ \
+ enum { \
+ IsLower = (Mode&Lower) == Lower, \
+ IsUnitDiag = (Mode&UnitDiag) ? 1 : 0, \
+ IsZeroDiag = (Mode&ZeroDiag) ? 1 : 0, \
+ conjA = ((TriStorageOrder==ColMajor) && Conjugate) ? 1 : 0 \
+ }; \
+ static EIGEN_DONT_INLINE void run( \
+ Index size, Index otherSize, \
+ const EIGTYPE* _tri, Index triStride, \
+ EIGTYPE* _other, Index otherStride, level3_blocking<EIGTYPE,EIGTYPE>& /*blocking*/) \
+ { \
+ MKL_INT m = size, n = otherSize, lda, ldb; \
+ char side = 'L', uplo, diag='N', transa; \
+ /* Set alpha_ */ \
+ MKLTYPE alpha; \
+ EIGTYPE myone(1); \
+ assign_scalar_eig2mkl(alpha, myone); \
+ ldb = otherStride;\
+\
+ const EIGTYPE *a; \
+/* Set trans */ \
+ transa = (TriStorageOrder==RowMajor) ? ((Conjugate) ? 'C' : 'T') : 'N'; \
+/* Set uplo */ \
+ uplo = IsLower ? 'L' : 'U'; \
+ if (TriStorageOrder==RowMajor) uplo = (uplo == 'L') ? 'U' : 'L'; \
+/* Set a, lda */ \
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic, TriStorageOrder> MatrixTri; \
+ Map<const MatrixTri, 0, OuterStride<> > tri(_tri,size,size,OuterStride<>(triStride)); \
+ MatrixTri a_tmp; \
+\
+ if (conjA) { \
+ a_tmp = tri.conjugate(); \
+ a = a_tmp.data(); \
+ lda = a_tmp.outerStride(); \
+ } else { \
+ a = _tri; \
+ lda = triStride; \
+ } \
+ if (IsUnitDiag) diag='U'; \
+/* call ?trsm*/ \
+ MKLPREFIX##trsm(&side, &uplo, &transa, &diag, &m, &n, &alpha, (const MKLTYPE*)a, &lda, (MKLTYPE*)_other, &ldb); \
+ } \
+};
+
+EIGEN_MKL_TRSM_L(double, double, d)
+EIGEN_MKL_TRSM_L(dcomplex, MKL_Complex16, z)
+EIGEN_MKL_TRSM_L(float, float, s)
+EIGEN_MKL_TRSM_L(scomplex, MKL_Complex8, c)
+
+
+// implements RightSide general * op(triangular)^-1
+#define EIGEN_MKL_TRSM_R(EIGTYPE, MKLTYPE, MKLPREFIX) \
+template <typename Index, int Mode, bool Conjugate, int TriStorageOrder> \
+struct triangular_solve_matrix<EIGTYPE,Index,OnTheRight,Mode,Conjugate,TriStorageOrder,ColMajor> \
+{ \
+ enum { \
+ IsLower = (Mode&Lower) == Lower, \
+ IsUnitDiag = (Mode&UnitDiag) ? 1 : 0, \
+ IsZeroDiag = (Mode&ZeroDiag) ? 1 : 0, \
+ conjA = ((TriStorageOrder==ColMajor) && Conjugate) ? 1 : 0 \
+ }; \
+ static EIGEN_DONT_INLINE void run( \
+ Index size, Index otherSize, \
+ const EIGTYPE* _tri, Index triStride, \
+ EIGTYPE* _other, Index otherStride, level3_blocking<EIGTYPE,EIGTYPE>& /*blocking*/) \
+ { \
+ MKL_INT m = otherSize, n = size, lda, ldb; \
+ char side = 'R', uplo, diag='N', transa; \
+ /* Set alpha_ */ \
+ MKLTYPE alpha; \
+ EIGTYPE myone(1); \
+ assign_scalar_eig2mkl(alpha, myone); \
+ ldb = otherStride;\
+\
+ const EIGTYPE *a; \
+/* Set trans */ \
+ transa = (TriStorageOrder==RowMajor) ? ((Conjugate) ? 'C' : 'T') : 'N'; \
+/* Set uplo */ \
+ uplo = IsLower ? 'L' : 'U'; \
+ if (TriStorageOrder==RowMajor) uplo = (uplo == 'L') ? 'U' : 'L'; \
+/* Set a, lda */ \
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic, TriStorageOrder> MatrixTri; \
+ Map<const MatrixTri, 0, OuterStride<> > tri(_tri,size,size,OuterStride<>(triStride)); \
+ MatrixTri a_tmp; \
+\
+ if (conjA) { \
+ a_tmp = tri.conjugate(); \
+ a = a_tmp.data(); \
+ lda = a_tmp.outerStride(); \
+ } else { \
+ a = _tri; \
+ lda = triStride; \
+ } \
+ if (IsUnitDiag) diag='U'; \
+/* call ?trsm*/ \
+ MKLPREFIX##trsm(&side, &uplo, &transa, &diag, &m, &n, &alpha, (const MKLTYPE*)a, &lda, (MKLTYPE*)_other, &ldb); \
+ /*std::cout << "TRMS_L specialization!\n";*/ \
+ } \
+};
+
+EIGEN_MKL_TRSM_R(double, double, d)
+EIGEN_MKL_TRSM_R(dcomplex, MKL_Complex16, z)
+EIGEN_MKL_TRSM_R(float, float, s)
+EIGEN_MKL_TRSM_R(scomplex, MKL_Complex8, c)
+
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_TRIANGULAR_SOLVER_MATRIX_MKL_H
diff --git a/extern/Eigen3/Eigen/src/Core/products/TriangularSolverVector.h b/extern/Eigen3/Eigen/src/Core/products/TriangularSolverVector.h
index 639d4a5b476..ce4d1008801 100644
--- a/extern/Eigen3/Eigen/src/Core/products/TriangularSolverVector.h
+++ b/extern/Eigen3/Eigen/src/Core/products/TriangularSolverVector.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRIANGULAR_SOLVER_VECTOR_H
#define EIGEN_TRIANGULAR_SOLVER_VECTOR_H
+namespace Eigen {
+
namespace internal {
template<typename LhsScalar, typename RhsScalar, typename Index, int Mode, bool Conjugate, int StorageOrder>
@@ -147,4 +134,6 @@ struct triangular_solve_vector<LhsScalar, RhsScalar, Index, OnTheLeft, Mode, Con
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_TRIANGULAR_SOLVER_VECTOR_H
diff --git a/extern/Eigen3/Eigen/src/Core/util/BlasUtil.h b/extern/Eigen3/Eigen/src/Core/util/BlasUtil.h
index f1d93d2f8b9..91496651c82 100644
--- a/extern/Eigen3/Eigen/src/Core/util/BlasUtil.h
+++ b/extern/Eigen3/Eigen/src/Core/util/BlasUtil.h
@@ -3,24 +3,9 @@
//
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BLASUTIL_H
#define EIGEN_BLASUTIL_H
@@ -28,6 +13,8 @@
// This file contains many lightweight helper classes used to
// implement and control fast level 2 and level 3 BLAS-like routines.
+namespace Eigen {
+
namespace internal {
// forward declarations
@@ -47,7 +34,7 @@ template<
int ResStorageOrder>
struct general_matrix_matrix_product;
-template<typename Index, typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs, typename RhsScalar, bool ConjugateRhs>
+template<typename Index, typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs, typename RhsScalar, bool ConjugateRhs, int Version=Specialized>
struct general_matrix_vector_product;
@@ -56,11 +43,15 @@ template<bool Conjugate> struct conj_if;
template<> struct conj_if<true> {
template<typename T>
inline T operator()(const T& x) { return conj(x); }
+ template<typename T>
+ inline T pconj(const T& x) { return internal::pconj(x); }
};
template<> struct conj_if<false> {
template<typename T>
inline const T& operator()(const T& x) { return x; }
+ template<typename T>
+ inline const T& pconj(const T& x) { return x; }
};
template<typename Scalar> struct conj_helper<Scalar,Scalar,false,false>
@@ -118,11 +109,11 @@ template<typename RealScalar,bool Conj> struct conj_helper<RealScalar, std::comp
};
template<typename From,typename To> struct get_factor {
- EIGEN_STRONG_INLINE static To run(const From& x) { return x; }
+ static EIGEN_STRONG_INLINE To run(const From& x) { return x; }
};
template<typename Scalar> struct get_factor<Scalar,typename NumTraits<Scalar>::Real> {
- EIGEN_STRONG_INLINE static typename NumTraits<Scalar>::Real run(const Scalar& x) { return real(x); }
+ static EIGEN_STRONG_INLINE typename NumTraits<Scalar>::Real run(const Scalar& x) { return real(x); }
};
// Lightweight helper class to access matrix coefficients.
@@ -175,7 +166,7 @@ template<typename XprType> struct blas_traits
ExtractType,
typename _ExtractType::PlainObject
>::type DirectLinearAccessType;
- static inline const ExtractType extract(const XprType& x) { return x; }
+ static inline ExtractType extract(const XprType& x) { return x; }
static inline const Scalar extractScalarFactor(const XprType&) { return Scalar(1); }
};
@@ -192,7 +183,7 @@ struct blas_traits<CwiseUnaryOp<scalar_conjugate_op<Scalar>, NestedXpr> >
IsComplex = NumTraits<Scalar>::IsComplex,
NeedToConjugate = Base::NeedToConjugate ? 0 : IsComplex
};
- static inline const ExtractType extract(const XprType& x) { return Base::extract(x.nestedExpression()); }
+ static inline ExtractType extract(const XprType& x) { return Base::extract(x.nestedExpression()); }
static inline Scalar extractScalarFactor(const XprType& x) { return conj(Base::extractScalarFactor(x.nestedExpression())); }
};
@@ -204,7 +195,7 @@ struct blas_traits<CwiseUnaryOp<scalar_multiple_op<Scalar>, NestedXpr> >
typedef blas_traits<NestedXpr> Base;
typedef CwiseUnaryOp<scalar_multiple_op<Scalar>, NestedXpr> XprType;
typedef typename Base::ExtractType ExtractType;
- static inline const ExtractType extract(const XprType& x) { return Base::extract(x.nestedExpression()); }
+ static inline ExtractType extract(const XprType& x) { return Base::extract(x.nestedExpression()); }
static inline Scalar extractScalarFactor(const XprType& x)
{ return x.functor().m_other * Base::extractScalarFactor(x.nestedExpression()); }
};
@@ -217,7 +208,7 @@ struct blas_traits<CwiseUnaryOp<scalar_opposite_op<Scalar>, NestedXpr> >
typedef blas_traits<NestedXpr> Base;
typedef CwiseUnaryOp<scalar_opposite_op<Scalar>, NestedXpr> XprType;
typedef typename Base::ExtractType ExtractType;
- static inline const ExtractType extract(const XprType& x) { return Base::extract(x.nestedExpression()); }
+ static inline ExtractType extract(const XprType& x) { return Base::extract(x.nestedExpression()); }
static inline Scalar extractScalarFactor(const XprType& x)
{ return - Base::extractScalarFactor(x.nestedExpression()); }
};
@@ -239,7 +230,7 @@ struct blas_traits<Transpose<NestedXpr> >
enum {
IsTransposed = Base::IsTransposed ? 0 : 1
};
- static inline const ExtractType extract(const XprType& x) { return Base::extract(x.nestedExpression()); }
+ static inline ExtractType extract(const XprType& x) { return Base::extract(x.nestedExpression()); }
static inline Scalar extractScalarFactor(const XprType& x) { return Base::extractScalarFactor(x.nestedExpression()); }
};
@@ -252,7 +243,7 @@ template<typename T, bool HasUsableDirectAccess=blas_traits<T>::HasUsableDirectA
struct extract_data_selector {
static const typename T::Scalar* run(const T& m)
{
- return const_cast<typename T::Scalar*>(&blas_traits<T>::extract(m).coeffRef(0,0)); // FIXME this should be .data()
+ return blas_traits<T>::extract(m).data();
}
};
@@ -268,4 +259,6 @@ template<typename T> const typename T::Scalar* extract_data(const T& m)
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_BLASUTIL_H
diff --git a/extern/Eigen3/Eigen/src/Core/util/Constants.h b/extern/Eigen3/Eigen/src/Core/util/Constants.h
index c3dd3a09d00..3fd45e84f8e 100644
--- a/extern/Eigen3/Eigen/src/Core/util/Constants.h
+++ b/extern/Eigen3/Eigen/src/Core/util/Constants.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2007-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_CONSTANTS_H
#define EIGEN_CONSTANTS_H
+namespace Eigen {
+
/** This value means that a quantity is not known at compile-time, and that instead the value is
* stored in some runtime variable.
*
@@ -188,7 +175,9 @@ enum {
/** View matrix as an upper triangular matrix with zeros on the diagonal. */
StrictlyUpper=ZeroDiag|Upper,
/** Used in BandMatrix and SelfAdjointView to indicate that the matrix is self-adjoint. */
- SelfAdjoint=0x10
+ SelfAdjoint=0x10,
+ /** Used to support symmetric, non-selfadjoint, complex matrices. */
+ Symmetric=0x20
};
/** \ingroup enums
@@ -200,8 +189,6 @@ enum {
Aligned=1
};
-enum { ConditionalJumpCost = 5 };
-
/** \ingroup enums
* Enum used by DenseBase::corner() in Eigen2 compatibility mode. */
// FIXME after the corner() API change, this was not needed anymore, except by AlignedBox
@@ -223,8 +210,6 @@ enum DirectionType {
BothDirections
};
-enum ProductEvaluationMode { NormalProduct, CacheFriendlyProduct };
-
/** \internal \ingroup enums
* Enum to specify how to traverse the entries of a matrix. */
enum {
@@ -257,6 +242,13 @@ enum {
CompleteUnrolling
};
+/** \internal \ingroup enums
+ * Enum to specify whether to use the default (built-in) implementation or the specialization. */
+enum {
+ Specialized,
+ BuiltIn
+};
+
/** \ingroup enums
* Enum containing possible values for the \p _Options template parameter of
* Matrix, Array and BandMatrix. */
@@ -280,26 +272,21 @@ enum {
OnTheRight = 2
};
-/* the following could as well be written:
- * enum NoChange_t { NoChange };
- * but it feels dangerous to disambiguate overloaded functions on enum/integer types.
- * If on some platform it is really impossible to get rid of "unused variable" warnings, then
- * we can always come back to that solution.
+/* the following used to be written as:
+ *
+ * struct NoChange_t {};
+ * namespace {
+ * EIGEN_UNUSED NoChange_t NoChange;
+ * }
+ *
+ * on the ground that it feels dangerous to disambiguate overloaded functions on enum/integer types.
+ * However, this leads to "variable declared but never referenced" warnings on Intel Composer XE,
+ * and we do not know how to get rid of them (bug 450).
*/
-struct NoChange_t {};
-namespace {
- EIGEN_UNUSED NoChange_t NoChange;
-}
-
-struct Sequential_t {};
-namespace {
- EIGEN_UNUSED Sequential_t Sequential;
-}
-struct Default_t {};
-namespace {
- EIGEN_UNUSED Default_t Default;
-}
+enum NoChange_t { NoChange };
+enum Sequential_t { Sequential };
+enum Default_t { Default };
/** \internal \ingroup enums
* Used in AmbiVector. */
@@ -375,7 +362,7 @@ enum QRPreconditioners {
#error The preprocessor symbol 'Success' is defined, possibly by the X11 header file X.h
#endif
-/** \ingroups enums
+/** \ingroup enums
* Enum for reporting the status of a computation. */
enum ComputationInfo {
/** Computation was successful. */
@@ -383,7 +370,10 @@ enum ComputationInfo {
/** The provided data did not satisfy the prerequisites. */
NumericalIssue = 1,
/** Iterative procedure did not converge. */
- NoConvergence = 2
+ NoConvergence = 2,
+ /** The inputs are invalid, or the algorithm has been improperly called.
+ * When assertions are enabled, such errors trigger an assert. */
+ InvalidInput = 3
};
/** \ingroup enums
@@ -436,4 +426,6 @@ struct MatrixXpr {};
/** The type used to identify an array expression */
struct ArrayXpr {};
+} // end namespace Eigen
+
#endif // EIGEN_CONSTANTS_H
diff --git a/extern/Eigen3/Eigen/src/Core/util/DisableStupidWarnings.h b/extern/Eigen3/Eigen/src/Core/util/DisableStupidWarnings.h
index 00730524b26..6a0bf0629c5 100644
--- a/extern/Eigen3/Eigen/src/Core/util/DisableStupidWarnings.h
+++ b/extern/Eigen3/Eigen/src/Core/util/DisableStupidWarnings.h
@@ -21,15 +21,13 @@
#elif defined __INTEL_COMPILER
// 2196 - routine is both "inline" and "noinline" ("noinline" assumed)
// ICC 12 generates this warning even without any inline keyword, when defining class methods 'inline' i.e. inside of class body
- // 2536 - type qualifiers are meaningless here
- // ICC 12 generates this warning when a function return type is const qualified, even if that type is a template-parameter-dependent
// typedef that may be a reference type.
// 279 - controlling expression is constant
// ICC 12 generates this warning on assert(constant_expression_depending_on_template_params) and frankly this is a legitimate use case.
#ifndef EIGEN_PERMANENTLY_DISABLE_STUPID_WARNINGS
#pragma warning push
#endif
- #pragma warning disable 2196 2536 279
+ #pragma warning disable 2196 279
#elif defined __clang__
// -Wconstant-logical-operand - warning: use of logical && with constant operand; switch to bitwise & or remove constant
// this is really a stupid warning as it warns on compile-time expressions involving enums
diff --git a/extern/Eigen3/Eigen/src/Core/util/ForwardDeclarations.h b/extern/Eigen3/Eigen/src/Core/util/ForwardDeclarations.h
index 7fbccf98c2b..bcdfe3914e3 100644
--- a/extern/Eigen3/Eigen/src/Core/util/ForwardDeclarations.h
+++ b/extern/Eigen3/Eigen/src/Core/util/ForwardDeclarations.h
@@ -4,28 +4,14 @@
// Copyright (C) 2007-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_FORWARDDECLARATIONS_H
#define EIGEN_FORWARDDECLARATIONS_H
+namespace Eigen {
namespace internal {
template<typename T> struct traits;
@@ -133,6 +119,7 @@ template<typename ExpressionType> class WithFormat;
template<typename MatrixType> struct CommaInitializer;
template<typename Derived> class ReturnByValue;
template<typename ExpressionType> class ArrayWrapper;
+template<typename ExpressionType> class MatrixWrapper;
namespace internal {
template<typename DecompositionType, typename Rhs> struct solve_retval_base;
@@ -282,6 +269,8 @@ template<typename MatrixType,int Direction> class Homogeneous;
// MatrixFunctions module
template<typename Derived> struct MatrixExponentialReturnValue;
template<typename Derived> class MatrixFunctionReturnValue;
+template<typename Derived> class MatrixSquareRootReturnValue;
+template<typename Derived> class MatrixLogarithmReturnValue;
namespace internal {
template <typename Scalar>
@@ -304,4 +293,6 @@ template<typename MatrixType, unsigned int Mode> struct eigen2_part_return_type;
}
#endif
+} // end namespace Eigen
+
#endif // EIGEN_FORWARDDECLARATIONS_H
diff --git a/extern/Eigen3/Eigen/src/Core/util/MKL_support.h b/extern/Eigen3/Eigen/src/Core/util/MKL_support.h
new file mode 100644
index 00000000000..1e6e355d626
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/util/MKL_support.h
@@ -0,0 +1,109 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Include file with common MKL declarations
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_MKL_SUPPORT_H
+#define EIGEN_MKL_SUPPORT_H
+
+#ifdef EIGEN_USE_MKL_ALL
+ #ifndef EIGEN_USE_BLAS
+ #define EIGEN_USE_BLAS
+ #endif
+ #ifndef EIGEN_USE_LAPACKE
+ #define EIGEN_USE_LAPACKE
+ #endif
+ #ifndef EIGEN_USE_MKL_VML
+ #define EIGEN_USE_MKL_VML
+ #endif
+#endif
+
+#ifdef EIGEN_USE_LAPACKE_STRICT
+ #define EIGEN_USE_LAPACKE
+#endif
+
+#if defined(EIGEN_USE_BLAS) || defined(EIGEN_USE_LAPACKE) || defined(EIGEN_USE_MKL_VML)
+ #define EIGEN_USE_MKL
+#endif
+
+#if defined EIGEN_USE_MKL
+
+#include <mkl.h>
+#include <mkl_lapacke.h>
+#define EIGEN_MKL_VML_THRESHOLD 128
+
+namespace Eigen {
+
+typedef std::complex<double> dcomplex;
+typedef std::complex<float> scomplex;
+
+namespace internal {
+
+template<typename MKLType, typename EigenType>
+static inline void assign_scalar_eig2mkl(MKLType& mklScalar, const EigenType& eigenScalar) {
+ mklScalar=eigenScalar;
+}
+
+template<typename MKLType, typename EigenType>
+static inline void assign_conj_scalar_eig2mkl(MKLType& mklScalar, const EigenType& eigenScalar) {
+ mklScalar=eigenScalar;
+}
+
+template <>
+inline void assign_scalar_eig2mkl<MKL_Complex16,dcomplex>(MKL_Complex16& mklScalar, const dcomplex& eigenScalar) {
+ mklScalar.real=eigenScalar.real();
+ mklScalar.imag=eigenScalar.imag();
+}
+
+template <>
+inline void assign_scalar_eig2mkl<MKL_Complex8,scomplex>(MKL_Complex8& mklScalar, const scomplex& eigenScalar) {
+ mklScalar.real=eigenScalar.real();
+ mklScalar.imag=eigenScalar.imag();
+}
+
+template <>
+inline void assign_conj_scalar_eig2mkl<MKL_Complex16,dcomplex>(MKL_Complex16& mklScalar, const dcomplex& eigenScalar) {
+ mklScalar.real=eigenScalar.real();
+ mklScalar.imag=-eigenScalar.imag();
+}
+
+template <>
+inline void assign_conj_scalar_eig2mkl<MKL_Complex8,scomplex>(MKL_Complex8& mklScalar, const scomplex& eigenScalar) {
+ mklScalar.real=eigenScalar.real();
+ mklScalar.imag=-eigenScalar.imag();
+}
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif
+
+#endif // EIGEN_MKL_SUPPORT_H
diff --git a/extern/Eigen3/Eigen/src/Core/util/Macros.h b/extern/Eigen3/Eigen/src/Core/util/Macros.h
index b7c2b79af92..d973a68372f 100644
--- a/extern/Eigen3/Eigen/src/Core/util/Macros.h
+++ b/extern/Eigen3/Eigen/src/Core/util/Macros.h
@@ -1,35 +1,19 @@
-
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MACROS_H
#define EIGEN_MACROS_H
#define EIGEN_WORLD_VERSION 3
-#define EIGEN_MAJOR_VERSION 0
-#define EIGEN_MINOR_VERSION 5
+#define EIGEN_MAJOR_VERSION 1
+#define EIGEN_MINOR_VERSION 1
#define EIGEN_VERSION_AT_LEAST(x,y,z) (EIGEN_WORLD_VERSION>x || (EIGEN_WORLD_VERSION>=x && \
(EIGEN_MAJOR_VERSION>y || (EIGEN_MAJOR_VERSION>=y && \
@@ -235,12 +219,16 @@
#define EIGEN_ONLY_USED_FOR_DEBUG(x)
#endif
-#if (defined __GNUC__)
-#define EIGEN_DEPRECATED __attribute__((deprecated))
-#elif (defined _MSC_VER)
-#define EIGEN_DEPRECATED __declspec(deprecated)
+#ifndef EIGEN_NO_DEPRECATED_WARNING
+ #if (defined __GNUC__)
+ #define EIGEN_DEPRECATED __attribute__((deprecated))
+ #elif (defined _MSC_VER)
+ #define EIGEN_DEPRECATED __declspec(deprecated)
+ #else
+ #define EIGEN_DEPRECATED
+ #endif
#else
-#define EIGEN_DEPRECATED
+ #define EIGEN_DEPRECATED
#endif
#if (defined __GNUC__)
@@ -252,7 +240,7 @@
// Suppresses 'unused variable' warnings.
#define EIGEN_UNUSED_VARIABLE(var) (void)var;
-#if (defined __GNUC__)
+#if !defined(EIGEN_ASM_COMMENT) && (defined __GNUC__)
#define EIGEN_ASM_COMMENT(X) asm("#" X)
#else
#define EIGEN_ASM_COMMENT(X)
@@ -265,7 +253,7 @@
* If we made alignment depend on whether or not EIGEN_VECTORIZE is defined, it would be impossible to link
* vectorized and non-vectorized code.
*/
-#if (defined __GNUC__) || (defined __PGI) || (defined __IBMCPP__)
+#if (defined __GNUC__) || (defined __PGI) || (defined __IBMCPP__) || (defined __ARMCC_VERSION)
#define EIGEN_ALIGN_TO_BOUNDARY(n) __attribute__((aligned(n)))
#elif (defined _MSC_VER)
#define EIGEN_ALIGN_TO_BOUNDARY(n) __declspec(align(n))
diff --git a/extern/Eigen3/Eigen/src/Core/util/Memory.h b/extern/Eigen3/Eigen/src/Core/util/Memory.h
index 023716dc9e0..6e06ace44a0 100644
--- a/extern/Eigen3/Eigen/src/Core/util/Memory.h
+++ b/extern/Eigen3/Eigen/src/Core/util/Memory.h
@@ -7,24 +7,9 @@
// Copyright (C) 2010 Hauke Heibel <hauke.heibel@gmail.com>
// Copyright (C) 2010 Thomas Capricelli <orzel@freehackers.org>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
/*****************************************************************************
@@ -80,6 +65,8 @@
#define EIGEN_HAS_MM_MALLOC 0
#endif
+namespace Eigen {
+
namespace internal {
inline void throw_std_bad_alloc()
@@ -457,7 +444,7 @@ template<typename T, bool Align> inline void conditional_aligned_delete_auto(T *
* There is also the variant first_aligned(const MatrixBase&) defined in DenseCoeffsBase.h.
*/
template<typename Scalar, typename Index>
-inline static Index first_aligned(const Scalar* array, Index size)
+static inline Index first_aligned(const Scalar* array, Index size)
{
typedef typename packet_traits<Scalar>::type Packet;
enum { PacketSize = packet_traits<Scalar>::size,
@@ -483,7 +470,26 @@ inline static Index first_aligned(const Scalar* array, Index size)
}
}
-} // end namespace internal
+
+// std::copy is much slower than memcpy, so let's introduce a smart_copy which
+// use memcpy on trivial types, i.e., on types that does not require an initialization ctor.
+template<typename T, bool UseMemcpy> struct smart_copy_helper;
+
+template<typename T> void smart_copy(const T* start, const T* end, T* target)
+{
+ smart_copy_helper<T,!NumTraits<T>::RequireInitialization>::run(start, end, target);
+}
+
+template<typename T> struct smart_copy_helper<T,true> {
+ static inline void run(const T* start, const T* end, T* target)
+ { memcpy(target, start, std::ptrdiff_t(end)-std::ptrdiff_t(start)); }
+};
+
+template<typename T> struct smart_copy_helper<T,false> {
+ static inline void run(const T* start, const T* end, T* target)
+ { std::copy(start, end, target); }
+};
+
/*****************************************************************************
*** Implementation of runtime stack allocation (falling back to malloc) ***
@@ -499,8 +505,6 @@ inline static Index first_aligned(const Scalar* array, Index size)
#endif
#endif
-namespace internal {
-
// This helper class construct the allocated memory, and takes care of destructing and freeing the handled data
// at destruction time. In practice this helper class is mainly useful to avoid memory leak in case of exceptions.
template<typename T> class aligned_stack_memory_handler
@@ -531,14 +535,14 @@ template<typename T> class aligned_stack_memory_handler
bool m_deallocate;
};
-}
+} // end namespace internal
/** \internal
* Declares, allocates and construct an aligned buffer named NAME of SIZE elements of type TYPE on the stack
* if SIZE is smaller than EIGEN_STACK_ALLOCATION_LIMIT, and if stack allocation is supported by the platform
* (currently, this is Linux and Visual Studio only). Otherwise the memory is allocated on the heap.
* The allocated buffer is automatically deleted when exiting the scope of this declaration.
- * If BUFFER is non nul, then the declared variable is simply an alias for BUFFER, and no allocation/deletion occurs.
+ * If BUFFER is non null, then the declared variable is simply an alias for BUFFER, and no allocation/deletion occurs.
* Here is an example:
* \code
* {
@@ -619,7 +623,7 @@ template<typename T> class aligned_stack_memory_handler
#define EIGEN_MAKE_ALIGNED_OPERATOR_NEW EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(true)
#define EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(Scalar,Size) \
- EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(((Size)!=Eigen::Dynamic) && ((sizeof(Scalar)*(Size))%16==0))
+ EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(bool(((Size)!=Eigen::Dynamic) && ((sizeof(Scalar)*(Size))%16==0)))
/****************************************************************************/
@@ -667,24 +671,24 @@ public:
return &value;
}
- aligned_allocator() throw()
+ aligned_allocator()
{
}
- aligned_allocator( const aligned_allocator& ) throw()
+ aligned_allocator( const aligned_allocator& )
{
}
template<class U>
- aligned_allocator( const aligned_allocator<U>& ) throw()
+ aligned_allocator( const aligned_allocator<U>& )
{
}
- ~aligned_allocator() throw()
+ ~aligned_allocator()
{
}
- size_type max_size() const throw()
+ size_type max_size() const
{
return (std::numeric_limits<size_type>::max)();
}
@@ -701,6 +705,15 @@ public:
::new( p ) T( value );
}
+ // Support for c++11
+#if (__cplusplus >= 201103L)
+ template<typename... Args>
+ void construct(pointer p, Args&&... args)
+ {
+ ::new(p) T(std::forward<Args>(args)...);
+ }
+#endif
+
void destroy( pointer p )
{
p->~T();
@@ -720,19 +733,21 @@ public:
//---------- Cache sizes ----------
-#if defined(__GNUC__) && ( defined(__i386__) || defined(__x86_64__) )
-# if defined(__PIC__) && defined(__i386__)
- // Case for x86 with PIC
-# define EIGEN_CPUID(abcd,func,id) \
- __asm__ __volatile__ ("xchgl %%ebx, %%esi;cpuid; xchgl %%ebx,%%esi": "=a" (abcd[0]), "=S" (abcd[1]), "=c" (abcd[2]), "=d" (abcd[3]) : "a" (func), "c" (id));
-# else
- // Case for x86_64 or x86 w/o PIC
-# define EIGEN_CPUID(abcd,func,id) \
- __asm__ __volatile__ ("cpuid": "=a" (abcd[0]), "=b" (abcd[1]), "=c" (abcd[2]), "=d" (abcd[3]) : "a" (func), "c" (id) );
-# endif
-#elif defined(_MSC_VER)
-# if (_MSC_VER > 1500)
-# define EIGEN_CPUID(abcd,func,id) __cpuidex((int*)abcd,func,id)
+#if !defined(EIGEN_NO_CPUID)
+# if defined(__GNUC__) && ( defined(__i386__) || defined(__x86_64__) )
+# if defined(__PIC__) && defined(__i386__)
+ // Case for x86 with PIC
+# define EIGEN_CPUID(abcd,func,id) \
+ __asm__ __volatile__ ("xchgl %%ebx, %%esi;cpuid; xchgl %%ebx,%%esi": "=a" (abcd[0]), "=S" (abcd[1]), "=c" (abcd[2]), "=d" (abcd[3]) : "a" (func), "c" (id));
+# else
+ // Case for x86_64 or x86 w/o PIC
+# define EIGEN_CPUID(abcd,func,id) \
+ __asm__ __volatile__ ("cpuid": "=a" (abcd[0]), "=b" (abcd[1]), "=c" (abcd[2]), "=d" (abcd[3]) : "a" (func), "c" (id) );
+# endif
+# elif defined(_MSC_VER)
+# if (_MSC_VER > 1500)
+# define EIGEN_CPUID(abcd,func,id) __cpuidex((int*)abcd,func,id)
+# endif
# endif
#endif
@@ -742,7 +757,7 @@ namespace internal {
inline bool cpuid_is_vendor(int abcd[4], const char* vendor)
{
- return abcd[1]==((int*)(vendor))[0] && abcd[3]==((int*)(vendor))[1] && abcd[2]==((int*)(vendor))[2];
+ return abcd[1]==(reinterpret_cast<const int*>(vendor))[0] && abcd[3]==(reinterpret_cast<const int*>(vendor))[1] && abcd[2]==(reinterpret_cast<const int*>(vendor))[2];
}
inline void queryCacheSizes_intel_direct(int& l1, int& l2, int& l3)
@@ -932,4 +947,6 @@ inline int queryTopLevelCacheSize()
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_MEMORY_H
diff --git a/extern/Eigen3/Eigen/src/Core/util/Meta.h b/extern/Eigen3/Eigen/src/Core/util/Meta.h
index 4518261efef..a5f31164d15 100644
--- a/extern/Eigen3/Eigen/src/Core/util/Meta.h
+++ b/extern/Eigen3/Eigen/src/Core/util/Meta.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_META_H
#define EIGEN_META_H
+namespace Eigen {
+
namespace internal {
/** \internal
@@ -80,8 +67,6 @@ template<> struct is_arithmetic<signed int> { enum { value = true }; };
template<> struct is_arithmetic<unsigned int> { enum { value = true }; };
template<> struct is_arithmetic<signed long> { enum { value = true }; };
template<> struct is_arithmetic<unsigned long> { enum { value = true }; };
-template<> struct is_arithmetic<signed long long> { enum { value = true }; };
-template<> struct is_arithmetic<unsigned long long> { enum { value = true }; };
template <typename T> struct add_const { typedef const T type; };
template <typename T> struct add_const<T&> { typedef T& type; };
@@ -103,6 +88,21 @@ template<bool Condition, typename T> struct enable_if;
template<typename T> struct enable_if<true,T>
{ typedef T type; };
+
+
+/** \internal
+ * A base class do disable default copy ctor and copy assignement operator.
+ */
+class noncopyable
+{
+ noncopyable(const noncopyable&);
+ const noncopyable& operator=(const noncopyable&);
+protected:
+ noncopyable() {}
+ ~noncopyable() {}
+};
+
+
/** \internal
* Convenient struct to get the result type of a unary or binary functor.
*
@@ -226,4 +226,6 @@ template<typename T, int S> struct is_diagonal<DiagonalMatrix<T,S> >
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_META_H
diff --git a/extern/Eigen3/Eigen/src/Core/util/NonMPL2.h b/extern/Eigen3/Eigen/src/Core/util/NonMPL2.h
new file mode 100644
index 00000000000..1af67cf18c7
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Core/util/NonMPL2.h
@@ -0,0 +1,3 @@
+#ifdef EIGEN_MPL2_ONLY
+#error Including non-MPL2 code in EIGEN_MPL2_ONLY mode
+#endif
diff --git a/extern/Eigen3/Eigen/src/Core/util/StaticAssert.h b/extern/Eigen3/Eigen/src/Core/util/StaticAssert.h
index 99c7c9972f0..b46a75b3783 100644
--- a/extern/Eigen3/Eigen/src/Core/util/StaticAssert.h
+++ b/extern/Eigen3/Eigen/src/Core/util/StaticAssert.h
@@ -4,24 +4,9 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STATIC_ASSERT_H
#define EIGEN_STATIC_ASSERT_H
@@ -48,6 +33,8 @@
#else // not CXX0X
+ namespace Eigen {
+
namespace internal {
template<bool condition>
@@ -70,6 +57,7 @@
YOU_CALLED_A_DYNAMIC_SIZE_METHOD_ON_A_FIXED_SIZE_MATRIX_OR_VECTOR,
UNALIGNED_LOAD_AND_STORE_OPERATIONS_UNIMPLEMENTED_ON_ALTIVEC,
THIS_FUNCTION_IS_NOT_FOR_INTEGER_NUMERIC_TYPES,
+ FLOATING_POINT_ARGUMENT_PASSED__INTEGER_WAS_EXPECTED,
NUMERIC_TYPE_MUST_BE_REAL,
COEFFICIENT_WRITE_ACCESS_TO_SELFADJOINT_NOT_SUPPORTED,
WRITING_TO_TRIANGULAR_PART_WITH_UNIT_DIAGONAL_IS_NOT_SUPPORTED,
@@ -95,12 +83,20 @@
YOU_PERFORMED_AN_INVALID_TRANSFORMATION_CONVERSION,
THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY,
YOU_ARE_TRYING_TO_USE_AN_INDEX_BASED_ACCESSOR_ON_AN_EXPRESSION_THAT_DOES_NOT_SUPPORT_THAT,
- THIS_METHOD_IS_ONLY_FOR_1x1_EXPRESSIONS
+ THIS_METHOD_IS_ONLY_FOR_1x1_EXPRESSIONS,
+ THIS_METHOD_IS_ONLY_FOR_EXPRESSIONS_OF_BOOL,
+ THIS_METHOD_IS_ONLY_FOR_ARRAYS_NOT_MATRICES,
+ YOU_PASSED_A_ROW_VECTOR_BUT_A_COLUMN_VECTOR_WAS_EXPECTED,
+ YOU_PASSED_A_COLUMN_VECTOR_BUT_A_ROW_VECTOR_WAS_EXPECTED,
+ THE_INDEX_TYPE_MUST_BE_A_SIGNED_TYPE,
+ THE_STORAGE_ORDER_OF_BOTH_SIDES_MUST_MATCH
};
};
} // end namespace internal
+ } // end namespace Eigen
+
// Specialized implementation for MSVC to avoid "conditional
// expression is constant" warnings. This implementation doesn't
// appear to work under GCC, hence the multiple implementations.
@@ -195,4 +191,15 @@
EIGEN_STATIC_ASSERT(internal::is_lvalue<Derived>::value, \
THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY)
+#define EIGEN_STATIC_ASSERT_ARRAYXPR(Derived) \
+ EIGEN_STATIC_ASSERT((internal::is_same<typename internal::traits<Derived>::XprKind, ArrayXpr>::value), \
+ THIS_METHOD_IS_ONLY_FOR_ARRAYS_NOT_MATRICES)
+
+#define EIGEN_STATIC_ASSERT_SAME_XPR_KIND(Derived1, Derived2) \
+ EIGEN_STATIC_ASSERT((internal::is_same<typename internal::traits<Derived1>::XprKind, \
+ typename internal::traits<Derived2>::XprKind \
+ >::value), \
+ YOU_CANNOT_MIX_ARRAYS_AND_MATRICES)
+
+
#endif // EIGEN_STATIC_ASSERT_H
diff --git a/extern/Eigen3/Eigen/src/Core/util/XprHelper.h b/extern/Eigen3/Eigen/src/Core/util/XprHelper.h
index c2078f13786..2a65c7cbfa4 100644
--- a/extern/Eigen3/Eigen/src/Core/util/XprHelper.h
+++ b/extern/Eigen3/Eigen/src/Core/util/XprHelper.h
@@ -4,24 +4,9 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_XPRHELPER_H
#define EIGEN_XPRHELPER_H
@@ -37,6 +22,8 @@
#define EIGEN_EMPTY_STRUCT_CTOR(X)
#endif
+namespace Eigen {
+
typedef EIGEN_DEFAULT_DENSE_INDEX_TYPE DenseIndex;
namespace internal {
@@ -260,30 +247,27 @@ template<typename T> struct plain_matrix_type_row_major
// we should be able to get rid of this one too
template<typename T> struct must_nest_by_value { enum { ret = false }; };
-template<class T>
-struct is_reference
-{
- enum { ret = false };
-};
-
-template<class T>
-struct is_reference<T&>
-{
- enum { ret = true };
-};
-
-/**
-* \internal The reference selector for template expressions. The idea is that we don't
-* need to use references for expressions since they are light weight proxy
-* objects which should generate no copying overhead.
-**/
+/** \internal The reference selector for template expressions. The idea is that we don't
+ * need to use references for expressions since they are light weight proxy
+ * objects which should generate no copying overhead. */
template <typename T>
struct ref_selector
{
typedef typename conditional<
bool(traits<T>::Flags & NestByRefBit),
T const&,
- T
+ const T
+ >::type type;
+};
+
+/** \internal Adds the const qualifier on the value-type of T2 if and only if T1 is a const type */
+template<typename T1, typename T2>
+struct transfer_constness
+{
+ typedef typename conditional<
+ bool(internal::is_const<T1>::value),
+ typename internal::add_const_on_value_type<T2>::type,
+ T2
>::type type;
};
@@ -297,6 +281,8 @@ struct ref_selector
* \param T the type of the expression being nested
* \param n the number of coefficient accesses in the nested expression for each coefficient access in the bigger expression.
*
+ * Note that if no evaluation occur, then the constness of T is preserved.
+ *
* Example. Suppose that a, b, and c are of type Matrix3d. The user forms the expression a*(b+c).
* b+c is an expression "sum of matrices", which we will denote by S. In order to determine how to nest it,
* the Product expression uses: nested<S, 3>::ret, which turns out to be Matrix3d because the internal logic of
@@ -456,4 +442,6 @@ struct is_lvalue
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_XPRHELPER_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Block.h b/extern/Eigen3/Eigen/src/Eigen2Support/Block.h
index bc28051e017..604456f40e7 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Block.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Block.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BLOCK2_H
#define EIGEN_BLOCK2_H
+namespace Eigen {
+
/** \returns a dynamic-size expression of a corner of *this.
*
* \param type the type of corner. Can be \a Eigen::TopLeft, \a Eigen::TopRight,
@@ -134,4 +121,6 @@ DenseBase<Derived>::corner(CornerType type) const
}
}
+} // end namespace Eigen
+
#endif // EIGEN_BLOCK2_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Cwise.h b/extern/Eigen3/Eigen/src/Eigen2Support/Cwise.h
index 2dc83b6a7dd..d95009b6e29 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Cwise.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Cwise.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_CWISE_H
#define EIGEN_CWISE_H
+namespace Eigen {
+
/** \internal
* convenient macro to defined the return type of a cwise binary operation */
#define EIGEN_CWISE_BINOP_RETURN_TYPE(OP) \
@@ -200,4 +187,6 @@ inline Cwise<Derived> MatrixBase<Derived>::cwise()
return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_CWISE_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/CwiseOperators.h b/extern/Eigen3/Eigen/src/Eigen2Support/CwiseOperators.h
index 9c28559c329..482f3064856 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/CwiseOperators.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/CwiseOperators.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ARRAY_CWISE_OPERATORS_H
#define EIGEN_ARRAY_CWISE_OPERATORS_H
+namespace Eigen {
+
/***************************************************************************
* The following functions were defined in Core
***************************************************************************/
@@ -306,4 +293,6 @@ inline ExpressionType& Cwise<ExpressionType>::operator-=(const Scalar& scalar)
return m_matrix.const_cast_derived() = *this - scalar;
}
+} // end namespace Eigen
+
#endif // EIGEN_ARRAY_CWISE_OPERATORS_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AlignedBox.h b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AlignedBox.h
index 78df29d408a..5c928e8fc2d 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AlignedBox.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AlignedBox.h
@@ -3,27 +3,14 @@
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// no include guard, we'll include this twice from All.h from Eigen2Support, and it's internal anyway
+namespace Eigen {
+
/** \geometry_module \ingroup Geometry_Module
* \nonstableyet
*
@@ -63,7 +50,7 @@ EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(_Scalar,_AmbientDim==
~AlignedBox() {}
/** \returns the dimension in which the box holds */
- inline int dim() const { return AmbientDimAtCompileTime==Dynamic ? m_min.size()-1 : int(AmbientDimAtCompileTime); }
+ inline int dim() const { return AmbientDimAtCompileTime==Dynamic ? m_min.size()-1 : AmbientDimAtCompileTime; }
/** \returns true if the box is null, i.e, empty. */
inline bool isNull() const { return (m_min.cwise() > m_max).any(); }
@@ -157,14 +144,16 @@ protected:
template<typename Scalar,int AmbiantDim>
inline Scalar AlignedBox<Scalar,AmbiantDim>::squaredExteriorDistance(const VectorType& p) const
{
- Scalar dist2 = 0.;
+ Scalar dist2(0);
Scalar aux;
for (int k=0; k<dim(); ++k)
{
- if ((aux = (p[k]-m_min[k]))<0.)
+ if ((aux = (p[k]-m_min[k]))<Scalar(0))
dist2 += aux*aux;
- else if ( (aux = (m_max[k]-p[k]))<0. )
+ else if ( (aux = (m_max[k]-p[k]))<Scalar(0))
dist2 += aux*aux;
}
return dist2;
}
+
+} // end namespace Eigen
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/All.h b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/All.h
index 9d8244b07a0..e0b00fccccf 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/All.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/All.h
@@ -112,4 +112,4 @@
#undef Hyperplane
#undef ParametrizedLine
-#endif // EIGEN2_GEOMETRY_MODULE_H \ No newline at end of file
+#endif // EIGEN2_GEOMETRY_MODULE_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AngleAxis.h b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AngleAxis.h
index f7b2d51e3e2..20f1fceeb19 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AngleAxis.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AngleAxis.h
@@ -3,27 +3,13 @@
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// no include guard, we'll include this twice from All.h from Eigen2Support, and it's internal anyway
+namespace Eigen {
/** \geometry_module \ingroup Geometry_Module
*
@@ -224,3 +210,5 @@ AngleAxis<Scalar>::toRotationMatrix(void) const
return res;
}
+
+} // end namespace Eigen
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Hyperplane.h b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Hyperplane.h
index 81c4f55b173..19cc1bfd883 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Hyperplane.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Hyperplane.h
@@ -4,27 +4,14 @@
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// no include guard, we'll include this twice from All.h from Eigen2Support, and it's internal anyway
+namespace Eigen {
+
/** \geometry_module \ingroup Geometry_Module
*
* \class Hyperplane
@@ -263,3 +250,5 @@ protected:
Coefficients m_coeffs;
};
+
+} // end namespace Eigen
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/ParametrizedLine.h b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/ParametrizedLine.h
index 411c4b57079..6e4a168a8cd 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/ParametrizedLine.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/ParametrizedLine.h
@@ -4,27 +4,13 @@
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// no include guard, we'll include this twice from All.h from Eigen2Support, and it's internal anyway
+namespace Eigen {
/** \geometry_module \ingroup Geometry_Module
*
@@ -151,3 +137,5 @@ inline _Scalar ParametrizedLine<_Scalar, _AmbientDim>::intersection(const Hyperp
return -(hyperplane.offset()+origin().eigen2_dot(hyperplane.normal()))
/(direction().eigen2_dot(hyperplane.normal()));
}
+
+} // end namespace Eigen
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Quaternion.h b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Quaternion.h
index a75fa42aeac..ec87da054d6 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Quaternion.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Quaternion.h
@@ -3,27 +3,14 @@
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// no include guard, we'll include this twice from All.h from Eigen2Support, and it's internal anyway
+namespace Eigen {
+
template<typename Other,
int OtherRows=Other::RowsAtCompileTime,
int OtherCols=Other::ColsAtCompileTime>
@@ -143,7 +130,7 @@ public:
/** \returns a quaternion representing an identity rotation
* \sa MatrixBase::Identity()
*/
- inline static Quaternion Identity() { return Quaternion(1, 0, 0, 0); }
+ static inline Quaternion Identity() { return Quaternion(1, 0, 0, 0); }
/** \sa Quaternion::Identity(), MatrixBase::setIdentity()
*/
@@ -314,9 +301,9 @@ Quaternion<Scalar>::toRotationMatrix(void) const
// it has to be inlined, and so the return by value is not an issue
Matrix3 res;
- const Scalar tx = 2*this->x();
- const Scalar ty = 2*this->y();
- const Scalar tz = 2*this->z();
+ const Scalar tx = Scalar(2)*this->x();
+ const Scalar ty = Scalar(2)*this->y();
+ const Scalar tz = Scalar(2)*this->z();
const Scalar twx = tx*this->w();
const Scalar twy = ty*this->w();
const Scalar twz = tz*this->w();
@@ -327,15 +314,15 @@ Quaternion<Scalar>::toRotationMatrix(void) const
const Scalar tyz = tz*this->y();
const Scalar tzz = tz*this->z();
- res.coeffRef(0,0) = 1-(tyy+tzz);
+ res.coeffRef(0,0) = Scalar(1)-(tyy+tzz);
res.coeffRef(0,1) = txy-twz;
res.coeffRef(0,2) = txz+twy;
res.coeffRef(1,0) = txy+twz;
- res.coeffRef(1,1) = 1-(txx+tzz);
+ res.coeffRef(1,1) = Scalar(1)-(txx+tzz);
res.coeffRef(1,2) = tyz-twx;
res.coeffRef(2,0) = txz-twy;
res.coeffRef(2,1) = tyz+twx;
- res.coeffRef(2,2) = 1-(txx+tyy);
+ res.coeffRef(2,2) = Scalar(1)-(txx+tyy);
return res;
}
@@ -460,7 +447,7 @@ template<typename Other>
struct ei_quaternion_assign_impl<Other,3,3>
{
typedef typename Other::Scalar Scalar;
- inline static void run(Quaternion<Scalar>& q, const Other& mat)
+ static inline void run(Quaternion<Scalar>& q, const Other& mat)
{
// This algorithm comes from "Quaternion Calculus and Fast Animation",
// Ken Shoemake, 1987 SIGGRAPH course notes
@@ -499,8 +486,10 @@ template<typename Other>
struct ei_quaternion_assign_impl<Other,4,1>
{
typedef typename Other::Scalar Scalar;
- inline static void run(Quaternion<Scalar>& q, const Other& vec)
+ static inline void run(Quaternion<Scalar>& q, const Other& vec)
{
q.coeffs() = vec;
}
};
+
+} // end namespace Eigen
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Rotation2D.h b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Rotation2D.h
index ee7c80e7eaa..3e02b7a4fd1 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Rotation2D.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Rotation2D.h
@@ -3,27 +3,13 @@
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// no include guard, we'll include this twice from All.h from Eigen2Support, and it's internal anyway
+namespace Eigen {
/** \geometry_module \ingroup Geometry_Module
*
@@ -155,3 +141,5 @@ Rotation2D<Scalar>::toRotationMatrix(void) const
Scalar cosA = ei_cos(m_angle);
return (Matrix2() << cosA, -sinA, sinA, cosA).finished();
}
+
+} // end namespace Eigen
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/RotationBase.h b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/RotationBase.h
index 2f494f198bd..78ad73b60ad 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/RotationBase.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/RotationBase.h
@@ -3,27 +3,14 @@
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// no include guard, we'll include this twice from All.h from Eigen2Support, and it's internal anyway
+namespace Eigen {
+
// this file aims to contains the various representations of rotation/orientation
// in 2D and 3D space excepted Matrix and Quaternion.
@@ -113,22 +100,24 @@ Matrix<_Scalar, _Rows, _Cols, _Storage, _MaxRows, _MaxCols>
* \sa class Transform, class Rotation2D, class Quaternion, class AngleAxis
*/
template<typename Scalar, int Dim>
-inline static Matrix<Scalar,2,2> ei_toRotationMatrix(const Scalar& s)
+static inline Matrix<Scalar,2,2> ei_toRotationMatrix(const Scalar& s)
{
EIGEN_STATIC_ASSERT(Dim==2,YOU_MADE_A_PROGRAMMING_MISTAKE)
return Rotation2D<Scalar>(s).toRotationMatrix();
}
template<typename Scalar, int Dim, typename OtherDerived>
-inline static Matrix<Scalar,Dim,Dim> ei_toRotationMatrix(const RotationBase<OtherDerived,Dim>& r)
+static inline Matrix<Scalar,Dim,Dim> ei_toRotationMatrix(const RotationBase<OtherDerived,Dim>& r)
{
return r.toRotationMatrix();
}
template<typename Scalar, int Dim, typename OtherDerived>
-inline static const MatrixBase<OtherDerived>& ei_toRotationMatrix(const MatrixBase<OtherDerived>& mat)
+static inline const MatrixBase<OtherDerived>& ei_toRotationMatrix(const MatrixBase<OtherDerived>& mat)
{
EIGEN_STATIC_ASSERT(OtherDerived::RowsAtCompileTime==Dim && OtherDerived::ColsAtCompileTime==Dim,
YOU_MADE_A_PROGRAMMING_MISTAKE)
return mat;
}
+
+} // end namespace Eigen
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Scaling.h b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Scaling.h
index 108e6d7d58f..a07c1c7c762 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Scaling.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Scaling.h
@@ -3,27 +3,13 @@
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// no include guard, we'll include this twice from All.h from Eigen2Support, and it's internal anyway
+namespace Eigen {
/** \geometry_module \ingroup Geometry_Module
*
@@ -177,3 +163,5 @@ Scaling<Scalar,Dim>::operator* (const TransformType& t) const
res.prescale(m_coeffs);
return res;
}
+
+} // end namespace Eigen
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Transform.h b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Transform.h
index 88956c86c73..dceb8020383 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Transform.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Transform.h
@@ -4,27 +4,13 @@
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// no include guard, we'll include this twice from All.h from Eigen2Support, and it's internal anyway
+namespace Eigen {
// Note that we have to pass Dim and HDim because it is not allowed to use a template
// parameter to define a template specialization. To be more precise, in the following
@@ -796,3 +782,5 @@ struct ei_transform_product_impl<Other,Dim,HDim, Dim,1>
{ return ((tr.linear() * other) + tr.translation())
* (Scalar(1) / ( (tr.matrix().template block<1,Dim>(Dim,0) * other).coeff(0) + tr.matrix().coeff(Dim,Dim))); }
};
+
+} // end namespace Eigen
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Translation.h b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Translation.h
index e651e310212..0fb9a9f9a5a 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Translation.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Translation.h
@@ -3,27 +3,13 @@
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// no include guard, we'll include this twice from All.h from Eigen2Support, and it's internal anyway
+namespace Eigen {
/** \geometry_module \ingroup Geometry_Module
*
@@ -194,3 +180,5 @@ Translation<Scalar,Dim>::operator* (const TransformType& t) const
res.pretranslate(m_coeffs);
return res;
}
+
+} // end namespace Eigen
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/LU.h b/extern/Eigen3/Eigen/src/Eigen2Support/LU.h
index c23c11baa72..49f19ad76e3 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/LU.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/LU.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2011 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN2_LU_H
#define EIGEN2_LU_H
+namespace Eigen {
+
template<typename MatrixType>
class LU : public FullPivLU<MatrixType>
{
@@ -57,7 +44,6 @@ class LU : public FullPivLU<MatrixType>
> ImageResultType;
typedef FullPivLU<MatrixType> Base;
- LU() : Base() {}
template<typename T>
explicit LU(const T& t) : Base(t), m_originalMatrix(t) {}
@@ -129,5 +115,6 @@ MatrixBase<Derived>::eigen2_lu() const
}
#endif
+} // end namespace Eigen
#endif // EIGEN2_LU_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Lazy.h b/extern/Eigen3/Eigen/src/Eigen2Support/Lazy.h
index c4288ede2ef..593fc78e6de 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Lazy.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Lazy.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_LAZY_H
#define EIGEN_LAZY_H
+namespace Eigen {
+
/** \deprecated it is only used by lazy() which is deprecated
*
* \returns an expression of *this with added flags
@@ -79,4 +66,6 @@ Derived& MatrixBase<Derived>::operator-=(const Flagged<ProductBase<ProductDerive
other._expression().derived().subTo(derived()); return derived();
}
+} // end namespace Eigen
+
#endif // EIGEN_LAZY_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/LeastSquares.h b/extern/Eigen3/Eigen/src/Eigen2Support/LeastSquares.h
index 4b62ffa92c7..7aff428dc45 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/LeastSquares.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/LeastSquares.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2006-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN2_LEASTSQUARES_H
#define EIGEN2_LEASTSQUARES_H
+namespace Eigen {
+
/** \ingroup LeastSquares_Module
*
* \leastsquares_module
@@ -178,5 +165,6 @@ void fitHyperplane(int numPoints,
result->offset() = - (result->normal().cwise()* mean).sum();
}
+} // end namespace Eigen
#endif // EIGEN2_LEASTSQUARES_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Macros.h b/extern/Eigen3/Eigen/src/Eigen2Support/Macros.h
index 77e85a41e3d..351c32afb60 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Macros.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Macros.h
@@ -3,24 +3,9 @@
//
// Copyright (C) 2011 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN2_MACROS_H
#define EIGEN2_MACROS_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/MathFunctions.h b/extern/Eigen3/Eigen/src/Eigen2Support/MathFunctions.h
index caa44e63f32..3a8a9ca8146 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/MathFunctions.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/MathFunctions.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN2_MATH_FUNCTIONS_H
#define EIGEN2_MATH_FUNCTIONS_H
+namespace Eigen {
+
template<typename T> inline typename NumTraits<T>::Real ei_real(const T& x) { return internal::real(x); }
template<typename T> inline typename NumTraits<T>::Real ei_imag(const T& x) { return internal::imag(x); }
template<typename T> inline T ei_conj(const T& x) { return internal::conj(x); }
@@ -65,4 +52,6 @@ inline bool ei_isApproxOrLessThan(const Scalar& x, const Scalar& y,
return internal::isApproxOrLessThan(x, y, precision);
}
+} // end namespace Eigen
+
#endif // EIGEN2_MATH_FUNCTIONS_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Memory.h b/extern/Eigen3/Eigen/src/Eigen2Support/Memory.h
index 0283475419e..f86372b6b56 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Memory.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Memory.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2011 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN2_MEMORY_H
#define EIGEN2_MEMORY_H
+namespace Eigen {
+
inline void* ei_aligned_malloc(size_t size) { return internal::aligned_malloc(size); }
inline void ei_aligned_free(void *ptr) { internal::aligned_free(ptr); }
inline void* ei_aligned_realloc(void *ptr, size_t new_size, size_t old_size) { return internal::aligned_realloc(ptr, new_size, old_size); }
@@ -53,6 +40,6 @@ template<typename T> inline void ei_aligned_delete(T *ptr, size_t size)
return internal::aligned_delete(ptr, size);
}
-
+} // end namespace Eigen
#endif // EIGEN2_MACROS_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Meta.h b/extern/Eigen3/Eigen/src/Eigen2Support/Meta.h
index 6e500b79a2e..fa37cfc961e 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Meta.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Meta.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2011 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN2_META_H
#define EIGEN2_META_H
+namespace Eigen {
+
template<typename T>
struct ei_traits : internal::traits<T>
{};
@@ -83,4 +70,6 @@ class ei_meta_sqrt
template<int Y, int InfX, int SupX>
class ei_meta_sqrt<Y, InfX, SupX, true> { public: enum { ret = (SupX*SupX <= Y) ? SupX : InfX }; };
+} // end namespace Eigen
+
#endif // EIGEN2_META_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/Minor.h b/extern/Eigen3/Eigen/src/Eigen2Support/Minor.h
index eda91cc32be..4cded5734fa 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/Minor.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/Minor.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2006-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MINOR_H
#define EIGEN_MINOR_H
+namespace Eigen {
+
/**
* \class Minor
*
@@ -125,4 +112,6 @@ MatrixBase<Derived>::minor(Index row, Index col) const
return Minor<Derived>(derived(), row, col);
}
+} // end namespace Eigen
+
#endif // EIGEN_MINOR_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/QR.h b/extern/Eigen3/Eigen/src/Eigen2Support/QR.h
index 64f5d5ccb30..2042c98510a 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/QR.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/QR.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
// Copyright (C) 2011 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN2_QR_H
#define EIGEN2_QR_H
+namespace Eigen {
+
template<typename MatrixType>
class QR : public HouseholderQR<MatrixType>
{
@@ -75,5 +62,6 @@ MatrixBase<Derived>::qr() const
return QR<PlainObject>(eval());
}
+} // end namespace Eigen
#endif // EIGEN2_QR_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/SVD.h b/extern/Eigen3/Eigen/src/Eigen2Support/SVD.h
index 16b4b488f0c..3d2eeb44586 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/SVD.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/SVD.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN2_SVD_H
#define EIGEN2_SVD_H
+namespace Eigen {
+
/** \ingroup SVD_Module
* \nonstableyet
*
@@ -390,7 +377,7 @@ void SVD<MatrixType>::compute(const MatrixType& matrix)
Scalar ek = e[k]/scale;
Scalar b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/Scalar(2);
Scalar c = (sp*epm1)*(sp*epm1);
- Scalar shift = 0.0;
+ Scalar shift(0);
if ((b != 0.0) || (c != 0.0))
{
shift = ei_sqrt(b*b + c);
@@ -646,4 +633,6 @@ MatrixBase<Derived>::svd() const
return SVD<PlainObject>(derived());
}
+} // end namespace Eigen
+
#endif // EIGEN2_SVD_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/TriangularSolver.h b/extern/Eigen3/Eigen/src/Eigen2Support/TriangularSolver.h
index e94e47a5093..ebbeb3b4958 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/TriangularSolver.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/TriangularSolver.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRIANGULAR_SOLVER2_H
#define EIGEN_TRIANGULAR_SOLVER2_H
+namespace Eigen {
+
const unsigned int UnitDiagBit = UnitDiag;
const unsigned int SelfAdjointBit = SelfAdjoint;
const unsigned int UpperTriangularBit = Upper;
@@ -49,5 +36,7 @@ void Flagged<ExpressionType,Added,Removed>::solveTriangularInPlace(const MatrixB
{
m_matrix.template triangularView<Added>().solveInPlace(other.derived());
}
+
+} // end namespace Eigen
#endif // EIGEN_TRIANGULAR_SOLVER2_H
diff --git a/extern/Eigen3/Eigen/src/Eigen2Support/VectorBlock.h b/extern/Eigen3/Eigen/src/Eigen2Support/VectorBlock.h
index 010031d1971..71a8080a9fc 100644
--- a/extern/Eigen3/Eigen/src/Eigen2Support/VectorBlock.h
+++ b/extern/Eigen3/Eigen/src/Eigen2Support/VectorBlock.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN2_VECTORBLOCK_H
#define EIGEN2_VECTORBLOCK_H
+namespace Eigen {
+
/** \deprecated use DenseMase::head(Index) */
template<typename Derived>
inline VectorBlock<Derived>
@@ -102,4 +89,6 @@ MatrixBase<Derived>::end() const
return VectorBlock<const Derived, Size>(derived(), size() - Size);
}
+} // end namespace Eigen
+
#endif // EIGEN2_VECTORBLOCK_H
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/ComplexEigenSolver.h b/extern/Eigen3/Eigen/src/Eigenvalues/ComplexEigenSolver.h
index 57e00227d72..c4b8a308cee 100644
--- a/extern/Eigen3/Eigen/src/Eigenvalues/ComplexEigenSolver.h
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/ComplexEigenSolver.h
@@ -5,31 +5,17 @@
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COMPLEX_EIGEN_SOLVER_H
#define EIGEN_COMPLEX_EIGEN_SOLVER_H
-#include "./EigenvaluesCommon.h"
#include "./ComplexSchur.h"
+namespace Eigen {
+
/** \eigenvalues_module \ingroup Eigenvalues_Module
*
*
@@ -328,5 +314,6 @@ void ComplexEigenSolver<MatrixType>::sortEigenvalues(bool computeEigenvectors)
}
}
+} // end namespace Eigen
#endif // EIGEN_COMPLEX_EIGEN_SOLVER_H
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur.h b/extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur.h
index ec93af2e58a..16a9a03d219 100644
--- a/extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur.h
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur.h
@@ -5,31 +5,17 @@
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COMPLEX_SCHUR_H
#define EIGEN_COMPLEX_SCHUR_H
-#include "./EigenvaluesCommon.h"
#include "./HessenbergDecomposition.h"
+namespace Eigen {
+
namespace internal {
template<typename MatrixType, bool IsComplex> struct complex_schur_reduce_to_hessenberg;
}
@@ -227,46 +213,6 @@ template<typename _MatrixType> class ComplexSchur
friend struct internal::complex_schur_reduce_to_hessenberg<MatrixType, NumTraits<Scalar>::IsComplex>;
};
-namespace internal {
-
-/** Computes the principal value of the square root of the complex \a z. */
-template<typename RealScalar>
-std::complex<RealScalar> sqrt(const std::complex<RealScalar> &z)
-{
- RealScalar t, tre, tim;
-
- t = abs(z);
-
- if (abs(real(z)) <= abs(imag(z)))
- {
- // No cancellation in these formulas
- tre = sqrt(RealScalar(0.5)*(t + real(z)));
- tim = sqrt(RealScalar(0.5)*(t - real(z)));
- }
- else
- {
- // Stable computation of the above formulas
- if (z.real() > RealScalar(0))
- {
- tre = t + z.real();
- tim = abs(imag(z))*sqrt(RealScalar(0.5)/tre);
- tre = sqrt(RealScalar(0.5)*tre);
- }
- else
- {
- tim = t - z.real();
- tre = abs(imag(z))*sqrt(RealScalar(0.5)/tim);
- tim = sqrt(RealScalar(0.5)*tim);
- }
- }
- if(z.imag() < RealScalar(0))
- tim = -tim;
-
- return (std::complex<RealScalar>(tre,tim));
-}
-} // end namespace internal
-
-
/** If m_matT(i+1,i) is neglegible in floating point arithmetic
* compared to m_matT(i,i) and m_matT(j,j), then set it to zero and
* return true, else return false. */
@@ -302,7 +248,7 @@ typename ComplexSchur<MatrixType>::ComplexScalar ComplexSchur<MatrixType>::compu
ComplexScalar b = t.coeff(0,1) * t.coeff(1,0);
ComplexScalar c = t.coeff(0,0) - t.coeff(1,1);
- ComplexScalar disc = internal::sqrt(c*c + RealScalar(4)*b);
+ ComplexScalar disc = sqrt(c*c + RealScalar(4)*b);
ComplexScalar det = t.coeff(0,0) * t.coeff(1,1) - b;
ComplexScalar trace = t.coeff(0,0) + t.coeff(1,1);
ComplexScalar eival1 = (trace + disc) / RealScalar(2);
@@ -406,7 +352,7 @@ void ComplexSchur<MatrixType>::reduceToTriangularForm(bool computeU)
// if we spent too many iterations on the current element, we give up
iter++;
- if(iter > m_maxIterations) break;
+ if(iter > m_maxIterations * m_matT.cols()) break;
// find il, the top row of the active submatrix
il = iu-1;
@@ -436,7 +382,7 @@ void ComplexSchur<MatrixType>::reduceToTriangularForm(bool computeU)
}
}
- if(iter <= m_maxIterations)
+ if(iter <= m_maxIterations * m_matT.cols())
m_info = Success;
else
m_info = NoConvergence;
@@ -445,4 +391,6 @@ void ComplexSchur<MatrixType>::reduceToTriangularForm(bool computeU)
m_matUisUptodate = computeU;
}
+} // end namespace Eigen
+
#endif // EIGEN_COMPLEX_SCHUR_H
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur_MKL.h b/extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur_MKL.h
new file mode 100644
index 00000000000..aa18e696352
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur_MKL.h
@@ -0,0 +1,94 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Complex Schur needed to complex unsymmetrical eigenvalues/eigenvectors.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_COMPLEX_SCHUR_MKL_H
+#define EIGEN_COMPLEX_SCHUR_MKL_H
+
+#include "Eigen/src/Core/util/MKL_support.h"
+
+namespace Eigen {
+
+/** \internal Specialization for the data types supported by MKL */
+
+#define EIGEN_MKL_SCHUR_COMPLEX(EIGTYPE, MKLTYPE, MKLPREFIX, MKLPREFIX_U, EIGCOLROW, MKLCOLROW) \
+template<> inline\
+ComplexSchur<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW> >& \
+ComplexSchur<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW> >::compute(const Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW>& matrix, bool computeU) \
+{ \
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW> MatrixType; \
+ typedef MatrixType::Scalar Scalar; \
+ typedef MatrixType::RealScalar RealScalar; \
+ typedef std::complex<RealScalar> ComplexScalar; \
+\
+ assert(matrix.cols() == matrix.rows()); \
+\
+ m_matUisUptodate = false; \
+ if(matrix.cols() == 1) \
+ { \
+ m_matT = matrix.cast<ComplexScalar>(); \
+ if(computeU) m_matU = ComplexMatrixType::Identity(1,1); \
+ m_info = Success; \
+ m_isInitialized = true; \
+ m_matUisUptodate = computeU; \
+ return *this; \
+ } \
+ lapack_int n = matrix.cols(), sdim, info; \
+ lapack_int lda = matrix.outerStride(); \
+ lapack_int matrix_order = MKLCOLROW; \
+ char jobvs, sort='N'; \
+ LAPACK_##MKLPREFIX_U##_SELECT1 select = 0; \
+ jobvs = (computeU) ? 'V' : 'N'; \
+ m_matU.resize(n, n); \
+ lapack_int ldvs = m_matU.outerStride(); \
+ m_matT = matrix; \
+ Matrix<EIGTYPE, Dynamic, Dynamic> w; \
+ w.resize(n, 1);\
+ info = LAPACKE_##MKLPREFIX##gees( matrix_order, jobvs, sort, select, n, (MKLTYPE*)m_matT.data(), lda, &sdim, (MKLTYPE*)w.data(), (MKLTYPE*)m_matU.data(), ldvs ); \
+ if(info == 0) \
+ m_info = Success; \
+ else \
+ m_info = NoConvergence; \
+\
+ m_isInitialized = true; \
+ m_matUisUptodate = computeU; \
+ return *this; \
+\
+}
+
+EIGEN_MKL_SCHUR_COMPLEX(dcomplex, MKL_Complex16, z, Z, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_SCHUR_COMPLEX(scomplex, MKL_Complex8, c, C, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_SCHUR_COMPLEX(dcomplex, MKL_Complex16, z, Z, RowMajor, LAPACK_ROW_MAJOR)
+EIGEN_MKL_SCHUR_COMPLEX(scomplex, MKL_Complex8, c, C, RowMajor, LAPACK_ROW_MAJOR)
+
+} // end namespace Eigen
+
+#endif // EIGEN_COMPLEX_SCHUR_MKL_H
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/EigenSolver.h b/extern/Eigen3/Eigen/src/Eigenvalues/EigenSolver.h
index f57353c065f..c16ff2b74e2 100644
--- a/extern/Eigen3/Eigen/src/Eigenvalues/EigenSolver.h
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/EigenSolver.h
@@ -4,31 +4,17 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_EIGENSOLVER_H
#define EIGEN_EIGENSOLVER_H
-#include "./EigenvaluesCommon.h"
#include "./RealSchur.h"
+namespace Eigen {
+
/** \eigenvalues_module \ingroup Eigenvalues_Module
*
*
@@ -432,7 +418,7 @@ void EigenSolver<MatrixType>::doComputeEigenvectors()
const Scalar eps = NumTraits<Scalar>::epsilon();
// inefficient! this is already computed in RealSchur
- Scalar norm = 0.0;
+ Scalar norm(0);
for (Index j = 0; j < size; ++j)
{
norm += m_matT.row(j).segment((std::max)(j-1,Index(0)), size-(std::max)(j-1,Index(0))).cwiseAbs().sum();
@@ -452,7 +438,7 @@ void EigenSolver<MatrixType>::doComputeEigenvectors()
// Scalar vector
if (q == Scalar(0))
{
- Scalar lastr=0, lastw=0;
+ Scalar lastr(0), lastw(0);
Index l = n;
m_matT.coeffRef(n,n) = 1.0;
@@ -498,7 +484,7 @@ void EigenSolver<MatrixType>::doComputeEigenvectors()
}
else if (q < Scalar(0) && n > 0) // Complex vector
{
- Scalar lastra=0, lastsa=0, lastw=0;
+ Scalar lastra(0), lastsa(0), lastw(0);
Index l = n-1;
// Last vector component imaginary so matrix is triangular
@@ -588,4 +574,6 @@ void EigenSolver<MatrixType>::doComputeEigenvectors()
}
}
+} // end namespace Eigen
+
#endif // EIGEN_EIGENSOLVER_H
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/EigenvaluesCommon.h b/extern/Eigen3/Eigen/src/Eigenvalues/EigenvaluesCommon.h
deleted file mode 100644
index 749bea79500..00000000000
--- a/extern/Eigen3/Eigen/src/Eigenvalues/EigenvaluesCommon.h
+++ /dev/null
@@ -1,31 +0,0 @@
-// This file is part of Eigen, a lightweight C++ template library
-// for linear algebra.
-//
-// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
-//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
-
-#ifndef EIGEN_EIGENVALUES_COMMON_H
-#define EIGEN_EIGENVALUES_COMMON_H
-
-
-
-#endif // EIGEN_EIGENVALUES_COMMON_H
-
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h b/extern/Eigen3/Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h
index 980af14ce71..07bf1ea0956 100644
--- a/extern/Eigen3/Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h
@@ -4,31 +4,17 @@
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GENERALIZEDSELFADJOINTEIGENSOLVER_H
#define EIGEN_GENERALIZEDSELFADJOINTEIGENSOLVER_H
-#include "./EigenvaluesCommon.h"
#include "./Tridiagonalization.h"
+namespace Eigen {
+
/** \eigenvalues_module \ingroup Eigenvalues_Module
*
*
@@ -236,4 +222,6 @@ compute(const MatrixType& matA, const MatrixType& matB, int options)
return *this;
}
+} // end namespace Eigen
+
#endif // EIGEN_GENERALIZEDSELFADJOINTEIGENSOLVER_H
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h b/extern/Eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h
index c17f155a59b..b8378b08a09 100644
--- a/extern/Eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_HESSENBERGDECOMPOSITION_H
#define EIGEN_HESSENBERGDECOMPOSITION_H
+namespace Eigen {
+
namespace internal {
template<typename MatrixType> struct HessenbergDecompositionMatrixHReturnType;
@@ -379,6 +366,8 @@ template<typename MatrixType> struct HessenbergDecompositionMatrixHReturnType
const HessenbergDecomposition<MatrixType>& m_hess;
};
-}
+} // end namespace internal
+
+} // end namespace Eigen
#endif // EIGEN_HESSENBERGDECOMPOSITION_H
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h b/extern/Eigen3/Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h
index 5591519fb75..6af481c75f6 100644
--- a/extern/Eigen3/Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MATRIXBASEEIGENVALUES_H
#define EIGEN_MATRIXBASEEIGENVALUES_H
+namespace Eigen {
+
namespace internal {
template<typename Derived, bool IsComplex>
@@ -167,4 +154,6 @@ SelfAdjointView<MatrixType, UpLo>::operatorNorm() const
return eigenvalues().cwiseAbs().maxCoeff();
}
+} // end namespace Eigen
+
#endif
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/RealSchur.h b/extern/Eigen3/Eigen/src/Eigenvalues/RealSchur.h
index cc9af11c117..781692eccd3 100644
--- a/extern/Eigen3/Eigen/src/Eigenvalues/RealSchur.h
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/RealSchur.h
@@ -4,31 +4,17 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_REAL_SCHUR_H
#define EIGEN_REAL_SCHUR_H
-#include "./EigenvaluesCommon.h"
#include "./HessenbergDecomposition.h"
+namespace Eigen {
+
/** \eigenvalues_module \ingroup Eigenvalues_Module
*
*
@@ -235,42 +221,44 @@ RealSchur<MatrixType>& RealSchur<MatrixType>::compute(const MatrixType& matrix,
// Rows iu+1,...,end are already brought in triangular form.
Index iu = m_matT.cols() - 1;
Index iter = 0; // iteration count
- Scalar exshift = 0.0; // sum of exceptional shifts
+ Scalar exshift(0); // sum of exceptional shifts
Scalar norm = computeNormOfT();
- while (iu >= 0)
+ if(norm!=0)
{
- Index il = findSmallSubdiagEntry(iu, norm);
-
- // Check for convergence
- if (il == iu) // One root found
- {
- m_matT.coeffRef(iu,iu) = m_matT.coeff(iu,iu) + exshift;
- if (iu > 0)
- m_matT.coeffRef(iu, iu-1) = Scalar(0);
- iu--;
- iter = 0;
- }
- else if (il == iu-1) // Two roots found
- {
- splitOffTwoRows(iu, computeU, exshift);
- iu -= 2;
- iter = 0;
- }
- else // No convergence yet
+ while (iu >= 0)
{
- // The firstHouseholderVector vector has to be initialized to something to get rid of a silly GCC warning (-O1 -Wall -DNDEBUG )
- Vector3s firstHouseholderVector(0,0,0), shiftInfo;
- computeShift(iu, iter, exshift, shiftInfo);
- iter = iter + 1;
- if (iter > m_maxIterations) break;
- Index im;
- initFrancisQRStep(il, iu, shiftInfo, im, firstHouseholderVector);
- performFrancisQRStep(il, im, iu, computeU, firstHouseholderVector, workspace);
+ Index il = findSmallSubdiagEntry(iu, norm);
+
+ // Check for convergence
+ if (il == iu) // One root found
+ {
+ m_matT.coeffRef(iu,iu) = m_matT.coeff(iu,iu) + exshift;
+ if (iu > 0)
+ m_matT.coeffRef(iu, iu-1) = Scalar(0);
+ iu--;
+ iter = 0;
+ }
+ else if (il == iu-1) // Two roots found
+ {
+ splitOffTwoRows(iu, computeU, exshift);
+ iu -= 2;
+ iter = 0;
+ }
+ else // No convergence yet
+ {
+ // The firstHouseholderVector vector has to be initialized to something to get rid of a silly GCC warning (-O1 -Wall -DNDEBUG )
+ Vector3s firstHouseholderVector(0,0,0), shiftInfo;
+ computeShift(iu, iter, exshift, shiftInfo);
+ iter = iter + 1;
+ if (iter > m_maxIterations * m_matT.cols()) break;
+ Index im;
+ initFrancisQRStep(il, iu, shiftInfo, im, firstHouseholderVector);
+ performFrancisQRStep(il, im, iu, computeU, firstHouseholderVector, workspace);
+ }
}
- }
-
- if(iter <= m_maxIterations)
+ }
+ if(iter <= m_maxIterations * m_matT.cols())
m_info = Success;
else
m_info = NoConvergence;
@@ -288,7 +276,7 @@ inline typename MatrixType::Scalar RealSchur<MatrixType>::computeNormOfT()
// FIXME to be efficient the following would requires a triangular reduxion code
// Scalar norm = m_matT.upper().cwiseAbs().sum()
// + m_matT.bottomLeftCorner(size-1,size-1).diagonal().cwiseAbs().sum();
- Scalar norm = 0.0;
+ Scalar norm(0);
for (Index j = 0; j < size; ++j)
norm += m_matT.row(j).segment((std::max)(j-1,Index(0)), size-(std::max)(j-1,Index(0))).cwiseAbs().sum();
return norm;
@@ -471,4 +459,6 @@ inline void RealSchur<MatrixType>::performFrancisQRStep(Index il, Index im, Inde
}
}
+} // end namespace Eigen
+
#endif // EIGEN_REAL_SCHUR_H
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/RealSchur_MKL.h b/extern/Eigen3/Eigen/src/Eigenvalues/RealSchur_MKL.h
new file mode 100644
index 00000000000..960ec3c764a
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/RealSchur_MKL.h
@@ -0,0 +1,83 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Real Schur needed to real unsymmetrical eigenvalues/eigenvectors.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_REAL_SCHUR_MKL_H
+#define EIGEN_REAL_SCHUR_MKL_H
+
+#include "Eigen/src/Core/util/MKL_support.h"
+
+namespace Eigen {
+
+/** \internal Specialization for the data types supported by MKL */
+
+#define EIGEN_MKL_SCHUR_REAL(EIGTYPE, MKLTYPE, MKLPREFIX, MKLPREFIX_U, EIGCOLROW, MKLCOLROW) \
+template<> inline \
+RealSchur<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW> >& \
+RealSchur<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW> >::compute(const Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW>& matrix, bool computeU) \
+{ \
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW> MatrixType; \
+ typedef MatrixType::Scalar Scalar; \
+ typedef MatrixType::RealScalar RealScalar; \
+\
+ assert(matrix.cols() == matrix.rows()); \
+\
+ lapack_int n = matrix.cols(), sdim, info; \
+ lapack_int lda = matrix.outerStride(); \
+ lapack_int matrix_order = MKLCOLROW; \
+ char jobvs, sort='N'; \
+ LAPACK_##MKLPREFIX_U##_SELECT2 select = 0; \
+ jobvs = (computeU) ? 'V' : 'N'; \
+ m_matU.resize(n, n); \
+ lapack_int ldvs = m_matU.outerStride(); \
+ m_matT = matrix; \
+ Matrix<EIGTYPE, Dynamic, Dynamic> wr, wi; \
+ wr.resize(n, 1); wi.resize(n, 1); \
+ info = LAPACKE_##MKLPREFIX##gees( matrix_order, jobvs, sort, select, n, (MKLTYPE*)m_matT.data(), lda, &sdim, (MKLTYPE*)wr.data(), (MKLTYPE*)wi.data(), (MKLTYPE*)m_matU.data(), ldvs ); \
+ if(info == 0) \
+ m_info = Success; \
+ else \
+ m_info = NoConvergence; \
+\
+ m_isInitialized = true; \
+ m_matUisUptodate = computeU; \
+ return *this; \
+\
+}
+
+EIGEN_MKL_SCHUR_REAL(double, double, d, D, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_SCHUR_REAL(float, float, s, S, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_SCHUR_REAL(double, double, d, D, RowMajor, LAPACK_ROW_MAJOR)
+EIGEN_MKL_SCHUR_REAL(float, float, s, S, RowMajor, LAPACK_ROW_MAJOR)
+
+} // end namespace Eigen
+
+#endif // EIGEN_REAL_SCHUR_MKL_H
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver.h b/extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver.h
index ad107c63282..acc5576feb1 100644
--- a/extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver.h
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver.h
@@ -4,34 +4,24 @@
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SELFADJOINTEIGENSOLVER_H
#define EIGEN_SELFADJOINTEIGENSOLVER_H
-#include "./EigenvaluesCommon.h"
#include "./Tridiagonalization.h"
+namespace Eigen {
+
template<typename _MatrixType>
class GeneralizedSelfAdjointEigenSolver;
+namespace internal {
+template<typename SolverType,int Size,bool IsComplex> struct direct_selfadjoint_eigenvalues;
+}
+
/** \eigenvalues_module \ingroup Eigenvalues_Module
*
*
@@ -86,7 +76,7 @@ template<typename _MatrixType> class SelfAdjointEigenSolver
Options = MatrixType::Options,
MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime
};
-
+
/** \brief Scalar type for matrices of type \p _MatrixType. */
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::Index Index;
@@ -98,6 +88,8 @@ template<typename _MatrixType> class SelfAdjointEigenSolver
* complex.
*/
typedef typename NumTraits<Scalar>::Real RealScalar;
+
+ friend struct internal::direct_selfadjoint_eigenvalues<SelfAdjointEigenSolver,Size,NumTraits<Scalar>::IsComplex>;
/** \brief Type for vector of eigenvalues as returned by eigenvalues().
*
@@ -198,6 +190,22 @@ template<typename _MatrixType> class SelfAdjointEigenSolver
* \sa SelfAdjointEigenSolver(const MatrixType&, int)
*/
SelfAdjointEigenSolver& compute(const MatrixType& matrix, int options = ComputeEigenvectors);
+
+ /** \brief Computes eigendecomposition of given matrix using a direct algorithm
+ *
+ * This is a variant of compute(const MatrixType&, int options) which
+ * directly solves the underlying polynomial equation.
+ *
+ * Currently only 3x3 matrices for which the sizes are known at compile time are supported (e.g., Matrix3d).
+ *
+ * This method is usually significantly faster than the QR algorithm
+ * but it might also be less accurate. It is also worth noting that
+ * for 3x3 matrices it involves trigonometric operations which are
+ * not necessarily available for all scalar types.
+ *
+ * \sa compute(const MatrixType&, int options)
+ */
+ SelfAdjointEigenSolver& computeDirect(const MatrixType& matrix, int options = ComputeEigenvectors);
/** \brief Returns the eigenvectors of given matrix.
*
@@ -401,7 +409,7 @@ SelfAdjointEigenSolver<MatrixType>& SelfAdjointEigenSolver<MatrixType>
// map the matrix coefficients to [-1:1] to avoid over- and underflow.
RealScalar scale = matrix.cwiseAbs().maxCoeff();
- if(scale==Scalar(0)) scale = 1;
+ if(scale==RealScalar(0)) scale = RealScalar(1);
mat = matrix / scale;
m_subdiag.resize(n-1);
internal::tridiagonalization_inplace(mat, diag, m_subdiag, computeEigenvectors);
@@ -466,19 +474,277 @@ SelfAdjointEigenSolver<MatrixType>& SelfAdjointEigenSolver<MatrixType>
return *this;
}
+
+namespace internal {
+
+template<typename SolverType,int Size,bool IsComplex> struct direct_selfadjoint_eigenvalues
+{
+ static inline void run(SolverType& eig, const typename SolverType::MatrixType& A, int options)
+ { eig.compute(A,options); }
+};
+
+template<typename SolverType> struct direct_selfadjoint_eigenvalues<SolverType,3,false>
+{
+ typedef typename SolverType::MatrixType MatrixType;
+ typedef typename SolverType::RealVectorType VectorType;
+ typedef typename SolverType::Scalar Scalar;
+
+ static inline void computeRoots(const MatrixType& m, VectorType& roots)
+ {
+ using std::sqrt;
+ using std::atan2;
+ using std::cos;
+ using std::sin;
+ const Scalar s_inv3 = Scalar(1.0)/Scalar(3.0);
+ const Scalar s_sqrt3 = sqrt(Scalar(3.0));
+
+ // The characteristic equation is x^3 - c2*x^2 + c1*x - c0 = 0. The
+ // eigenvalues are the roots to this equation, all guaranteed to be
+ // real-valued, because the matrix is symmetric.
+ Scalar c0 = m(0,0)*m(1,1)*m(2,2) + Scalar(2)*m(1,0)*m(2,0)*m(2,1) - m(0,0)*m(2,1)*m(2,1) - m(1,1)*m(2,0)*m(2,0) - m(2,2)*m(1,0)*m(1,0);
+ Scalar c1 = m(0,0)*m(1,1) - m(1,0)*m(1,0) + m(0,0)*m(2,2) - m(2,0)*m(2,0) + m(1,1)*m(2,2) - m(2,1)*m(2,1);
+ Scalar c2 = m(0,0) + m(1,1) + m(2,2);
+
+ // Construct the parameters used in classifying the roots of the equation
+ // and in solving the equation for the roots in closed form.
+ Scalar c2_over_3 = c2*s_inv3;
+ Scalar a_over_3 = (c1 - c2*c2_over_3)*s_inv3;
+ if (a_over_3 > Scalar(0))
+ a_over_3 = Scalar(0);
+
+ Scalar half_b = Scalar(0.5)*(c0 + c2_over_3*(Scalar(2)*c2_over_3*c2_over_3 - c1));
+
+ Scalar q = half_b*half_b + a_over_3*a_over_3*a_over_3;
+ if (q > Scalar(0))
+ q = Scalar(0);
+
+ // Compute the eigenvalues by solving for the roots of the polynomial.
+ Scalar rho = sqrt(-a_over_3);
+ Scalar theta = atan2(sqrt(-q),half_b)*s_inv3;
+ Scalar cos_theta = cos(theta);
+ Scalar sin_theta = sin(theta);
+ roots(0) = c2_over_3 + Scalar(2)*rho*cos_theta;
+ roots(1) = c2_over_3 - rho*(cos_theta + s_sqrt3*sin_theta);
+ roots(2) = c2_over_3 - rho*(cos_theta - s_sqrt3*sin_theta);
+
+ // Sort in increasing order.
+ if (roots(0) >= roots(1))
+ std::swap(roots(0),roots(1));
+ if (roots(1) >= roots(2))
+ {
+ std::swap(roots(1),roots(2));
+ if (roots(0) >= roots(1))
+ std::swap(roots(0),roots(1));
+ }
+ }
+
+ static inline void run(SolverType& solver, const MatrixType& mat, int options)
+ {
+ using std::sqrt;
+ eigen_assert(mat.cols() == 3 && mat.cols() == mat.rows());
+ eigen_assert((options&~(EigVecMask|GenEigMask))==0
+ && (options&EigVecMask)!=EigVecMask
+ && "invalid option parameter");
+ bool computeEigenvectors = (options&ComputeEigenvectors)==ComputeEigenvectors;
+
+ MatrixType& eivecs = solver.m_eivec;
+ VectorType& eivals = solver.m_eivalues;
+
+ // map the matrix coefficients to [-1:1] to avoid over- and underflow.
+ Scalar scale = mat.cwiseAbs().maxCoeff();
+ MatrixType scaledMat = mat / scale;
+
+ // compute the eigenvalues
+ computeRoots(scaledMat,eivals);
+
+ // compute the eigen vectors
+ if(computeEigenvectors)
+ {
+ Scalar safeNorm2 = Eigen::NumTraits<Scalar>::epsilon();
+ safeNorm2 *= safeNorm2;
+ if((eivals(2)-eivals(0))<=Eigen::NumTraits<Scalar>::epsilon())
+ {
+ eivecs.setIdentity();
+ }
+ else
+ {
+ scaledMat = scaledMat.template selfadjointView<Lower>();
+ MatrixType tmp;
+ tmp = scaledMat;
+
+ Scalar d0 = eivals(2) - eivals(1);
+ Scalar d1 = eivals(1) - eivals(0);
+ int k = d0 > d1 ? 2 : 0;
+ d0 = d0 > d1 ? d1 : d0;
+
+ tmp.diagonal().array () -= eivals(k);
+ VectorType cross;
+ Scalar n;
+ n = (cross = tmp.row(0).cross(tmp.row(1))).squaredNorm();
+
+ if(n>safeNorm2)
+ eivecs.col(k) = cross / sqrt(n);
+ else
+ {
+ n = (cross = tmp.row(0).cross(tmp.row(2))).squaredNorm();
+
+ if(n>safeNorm2)
+ eivecs.col(k) = cross / sqrt(n);
+ else
+ {
+ n = (cross = tmp.row(1).cross(tmp.row(2))).squaredNorm();
+
+ if(n>safeNorm2)
+ eivecs.col(k) = cross / sqrt(n);
+ else
+ {
+ // the input matrix and/or the eigenvaues probably contains some inf/NaN,
+ // => exit
+ // scale back to the original size.
+ eivals *= scale;
+
+ solver.m_info = NumericalIssue;
+ solver.m_isInitialized = true;
+ solver.m_eigenvectorsOk = computeEigenvectors;
+ return;
+ }
+ }
+ }
+
+ tmp = scaledMat;
+ tmp.diagonal().array() -= eivals(1);
+
+ if(d0<=Eigen::NumTraits<Scalar>::epsilon())
+ eivecs.col(1) = eivecs.col(k).unitOrthogonal();
+ else
+ {
+ n = (cross = eivecs.col(k).cross(tmp.row(0).normalized())).squaredNorm();
+ if(n>safeNorm2)
+ eivecs.col(1) = cross / sqrt(n);
+ else
+ {
+ n = (cross = eivecs.col(k).cross(tmp.row(1))).squaredNorm();
+ if(n>safeNorm2)
+ eivecs.col(1) = cross / sqrt(n);
+ else
+ {
+ n = (cross = eivecs.col(k).cross(tmp.row(2))).squaredNorm();
+ if(n>safeNorm2)
+ eivecs.col(1) = cross / sqrt(n);
+ else
+ {
+ // we should never reach this point,
+ // if so the last two eigenvalues are likely to ve very closed to each other
+ eivecs.col(1) = eivecs.col(k).unitOrthogonal();
+ }
+ }
+ }
+
+ // make sure that eivecs[1] is orthogonal to eivecs[2]
+ Scalar d = eivecs.col(1).dot(eivecs.col(k));
+ eivecs.col(1) = (eivecs.col(1) - d * eivecs.col(k)).normalized();
+ }
+
+ eivecs.col(k==2 ? 0 : 2) = eivecs.col(k).cross(eivecs.col(1)).normalized();
+ }
+ }
+ // Rescale back to the original size.
+ eivals *= scale;
+
+ solver.m_info = Success;
+ solver.m_isInitialized = true;
+ solver.m_eigenvectorsOk = computeEigenvectors;
+ }
+};
+
+// 2x2 direct eigenvalues decomposition, code from Hauke Heibel
+template<typename SolverType> struct direct_selfadjoint_eigenvalues<SolverType,2,false>
+{
+ typedef typename SolverType::MatrixType MatrixType;
+ typedef typename SolverType::RealVectorType VectorType;
+ typedef typename SolverType::Scalar Scalar;
+
+ static inline void computeRoots(const MatrixType& m, VectorType& roots)
+ {
+ using std::sqrt;
+ const Scalar t0 = Scalar(0.5) * sqrt( abs2(m(0,0)-m(1,1)) + Scalar(4)*m(1,0)*m(1,0));
+ const Scalar t1 = Scalar(0.5) * (m(0,0) + m(1,1));
+ roots(0) = t1 - t0;
+ roots(1) = t1 + t0;
+ }
+
+ static inline void run(SolverType& solver, const MatrixType& mat, int options)
+ {
+ eigen_assert(mat.cols() == 2 && mat.cols() == mat.rows());
+ eigen_assert((options&~(EigVecMask|GenEigMask))==0
+ && (options&EigVecMask)!=EigVecMask
+ && "invalid option parameter");
+ bool computeEigenvectors = (options&ComputeEigenvectors)==ComputeEigenvectors;
+
+ MatrixType& eivecs = solver.m_eivec;
+ VectorType& eivals = solver.m_eivalues;
+
+ // map the matrix coefficients to [-1:1] to avoid over- and underflow.
+ Scalar scale = mat.cwiseAbs().maxCoeff();
+ scale = (std::max)(scale,Scalar(1));
+ MatrixType scaledMat = mat / scale;
+
+ // Compute the eigenvalues
+ computeRoots(scaledMat,eivals);
+
+ // compute the eigen vectors
+ if(computeEigenvectors)
+ {
+ scaledMat.diagonal().array () -= eivals(1);
+ Scalar a2 = abs2(scaledMat(0,0));
+ Scalar c2 = abs2(scaledMat(1,1));
+ Scalar b2 = abs2(scaledMat(1,0));
+ if(a2>c2)
+ {
+ eivecs.col(1) << -scaledMat(1,0), scaledMat(0,0);
+ eivecs.col(1) /= sqrt(a2+b2);
+ }
+ else
+ {
+ eivecs.col(1) << -scaledMat(1,1), scaledMat(1,0);
+ eivecs.col(1) /= sqrt(c2+b2);
+ }
+
+ eivecs.col(0) << eivecs.col(1).unitOrthogonal();
+ }
+
+ // Rescale back to the original size.
+ eivals *= scale;
+
+ solver.m_info = Success;
+ solver.m_isInitialized = true;
+ solver.m_eigenvectorsOk = computeEigenvectors;
+ }
+};
+
+}
+
+template<typename MatrixType>
+SelfAdjointEigenSolver<MatrixType>& SelfAdjointEigenSolver<MatrixType>
+::computeDirect(const MatrixType& matrix, int options)
+{
+ internal::direct_selfadjoint_eigenvalues<SelfAdjointEigenSolver,Size,NumTraits<Scalar>::IsComplex>::run(*this,matrix,options);
+ return *this;
+}
+
namespace internal {
template<int StorageOrder,typename RealScalar, typename Scalar, typename Index>
static void tridiagonal_qr_step(RealScalar* diag, RealScalar* subdiag, Index start, Index end, Scalar* matrixQ, Index n)
{
- // NOTE this version avoids over & underflow, however since the matrix is prescaled, overflow cannot occur,
- // and underflows should be meaningless anyway. So I don't any reason to enable this version, but I keep
- // it here for reference:
-// RealScalar td = (diag[end-1] - diag[end])*RealScalar(0.5);
-// RealScalar e = subdiag[end-1];
-// RealScalar mu = diag[end] - (e / (td + (td>0 ? 1 : -1))) * (e / hypot(td,e));
RealScalar td = (diag[end-1] - diag[end])*RealScalar(0.5);
- RealScalar e2 = abs2(subdiag[end-1]);
- RealScalar mu = diag[end] - e2 / (td + (td>0 ? 1 : -1) * sqrt(td*td + e2));
+ RealScalar e = subdiag[end-1];
+ // Note that thanks to scaling, e^2 or td^2 cannot overflow, however they can still
+ // underflow thus leading to inf/NaN values when using the following commented code:
+// RealScalar e2 = abs2(subdiag[end-1]);
+// RealScalar mu = diag[end] - e2 / (td + (td>0 ? 1 : -1) * sqrt(td*td + e2));
+ // This explain the following, somewhat more complicated, version:
+ RealScalar mu = diag[end] - (e / (td + (td>0 ? 1 : -1))) * (e / hypot(td,e));
+
RealScalar x = diag[start] - mu;
RealScalar z = subdiag[start];
for (Index k = start; k < end; ++k)
@@ -515,6 +781,9 @@ static void tridiagonal_qr_step(RealScalar* diag, RealScalar* subdiag, Index sta
}
}
}
+
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_SELFADJOINTEIGENSOLVER_H
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver_MKL.h b/extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver_MKL.h
new file mode 100644
index 00000000000..9380956b5f9
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver_MKL.h
@@ -0,0 +1,92 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Self-adjoint eigenvalues/eigenvectors.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_SAEIGENSOLVER_MKL_H
+#define EIGEN_SAEIGENSOLVER_MKL_H
+
+#include "Eigen/src/Core/util/MKL_support.h"
+
+namespace Eigen {
+
+/** \internal Specialization for the data types supported by MKL */
+
+#define EIGEN_MKL_EIG_SELFADJ(EIGTYPE, MKLTYPE, MKLRTYPE, MKLNAME, EIGCOLROW, MKLCOLROW ) \
+template<> inline\
+SelfAdjointEigenSolver<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW> >& \
+SelfAdjointEigenSolver<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW> >::compute(const Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW>& matrix, int options) \
+{ \
+ eigen_assert(matrix.cols() == matrix.rows()); \
+ eigen_assert((options&~(EigVecMask|GenEigMask))==0 \
+ && (options&EigVecMask)!=EigVecMask \
+ && "invalid option parameter"); \
+ bool computeEigenvectors = (options&ComputeEigenvectors)==ComputeEigenvectors; \
+ lapack_int n = matrix.cols(), lda, matrix_order, info; \
+ m_eivalues.resize(n,1); \
+ m_subdiag.resize(n-1); \
+ m_eivec = matrix; \
+\
+ if(n==1) \
+ { \
+ m_eivalues.coeffRef(0,0) = internal::real(matrix.coeff(0,0)); \
+ if(computeEigenvectors) m_eivec.setOnes(n,n); \
+ m_info = Success; \
+ m_isInitialized = true; \
+ m_eigenvectorsOk = computeEigenvectors; \
+ return *this; \
+ } \
+\
+ lda = matrix.outerStride(); \
+ matrix_order=MKLCOLROW; \
+ char jobz, uplo='L'/*, range='A'*/; \
+ jobz = computeEigenvectors ? 'V' : 'N'; \
+\
+ info = LAPACKE_##MKLNAME( matrix_order, jobz, uplo, n, (MKLTYPE*)m_eivec.data(), lda, (MKLRTYPE*)m_eivalues.data() ); \
+ m_info = (info==0) ? Success : NoConvergence; \
+ m_isInitialized = true; \
+ m_eigenvectorsOk = computeEigenvectors; \
+ return *this; \
+}
+
+
+EIGEN_MKL_EIG_SELFADJ(double, double, double, dsyev, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_EIG_SELFADJ(float, float, float, ssyev, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_EIG_SELFADJ(dcomplex, MKL_Complex16, double, zheev, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_EIG_SELFADJ(scomplex, MKL_Complex8, float, cheev, ColMajor, LAPACK_COL_MAJOR)
+
+EIGEN_MKL_EIG_SELFADJ(double, double, double, dsyev, RowMajor, LAPACK_ROW_MAJOR)
+EIGEN_MKL_EIG_SELFADJ(float, float, float, ssyev, RowMajor, LAPACK_ROW_MAJOR)
+EIGEN_MKL_EIG_SELFADJ(dcomplex, MKL_Complex16, double, zheev, RowMajor, LAPACK_ROW_MAJOR)
+EIGEN_MKL_EIG_SELFADJ(scomplex, MKL_Complex8, float, cheev, RowMajor, LAPACK_ROW_MAJOR)
+
+} // end namespace Eigen
+
+#endif // EIGEN_SAEIGENSOLVER_H
diff --git a/extern/Eigen3/Eigen/src/Eigenvalues/Tridiagonalization.h b/extern/Eigen3/Eigen/src/Eigenvalues/Tridiagonalization.h
index ae4cdce7aeb..c34b7b3b801 100644
--- a/extern/Eigen3/Eigen/src/Eigenvalues/Tridiagonalization.h
+++ b/extern/Eigen3/Eigen/src/Eigenvalues/Tridiagonalization.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRIDIAGONALIZATION_H
#define EIGEN_TRIDIAGONALIZATION_H
+namespace Eigen {
+
namespace internal {
template<typename MatrixType> struct TridiagonalizationMatrixTReturnType;
@@ -97,13 +84,13 @@ template<typename _MatrixType> class Tridiagonalization
typedef internal::TridiagonalizationMatrixTReturnType<MatrixTypeRealView> MatrixTReturnType;
typedef typename internal::conditional<NumTraits<Scalar>::IsComplex,
- const typename Diagonal<const MatrixType>::RealReturnType,
+ typename internal::add_const_on_value_type<typename Diagonal<const MatrixType>::RealReturnType>::type,
const Diagonal<const MatrixType>
>::type DiagonalReturnType;
typedef typename internal::conditional<NumTraits<Scalar>::IsComplex,
- const typename Diagonal<
- Block<const MatrixType,SizeMinusOne,SizeMinusOne> >::RealReturnType,
+ typename internal::add_const_on_value_type<typename Diagonal<
+ Block<const MatrixType,SizeMinusOne,SizeMinusOne> >::RealReturnType>::type,
const Diagonal<
Block<const MatrixType,SizeMinusOne,SizeMinusOne> >
>::type SubDiagonalReturnType;
@@ -560,9 +547,11 @@ template<typename MatrixType> struct TridiagonalizationMatrixTReturnType
Index cols() const { return m_matrix.cols(); }
protected:
- const typename MatrixType::Nested m_matrix;
+ typename MatrixType::Nested m_matrix;
};
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_TRIDIAGONALIZATION_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/AlignedBox.h b/extern/Eigen3/Eigen/src/Geometry/AlignedBox.h
index b51deb3f3c3..5830fcd35fc 100644
--- a/extern/Eigen3/Eigen/src/Geometry/AlignedBox.h
+++ b/extern/Eigen3/Eigen/src/Geometry/AlignedBox.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ALIGNEDBOX_H
#define EIGEN_ALIGNEDBOX_H
+namespace Eigen {
+
/** \geometry_module \ingroup Geometry_Module
*
*
@@ -190,7 +177,7 @@ EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(_Scalar,_AmbientDim)
template<typename Derived>
inline bool contains(const MatrixBase<Derived>& a_p) const
{
- const typename internal::nested<Derived,2>::type p(a_p.derived());
+ typename internal::nested<Derived,2>::type p(a_p.derived());
return (m_min.array()<=p.array()).all() && (p.array()<=m_max.array()).all();
}
@@ -202,7 +189,7 @@ EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(_Scalar,_AmbientDim)
template<typename Derived>
inline AlignedBox& extend(const MatrixBase<Derived>& a_p)
{
- const typename internal::nested<Derived,2>::type p(a_p.derived());
+ typename internal::nested<Derived,2>::type p(a_p.derived());
m_min = m_min.cwiseMin(p);
m_max = m_max.cwiseMax(p);
return *this;
@@ -310,7 +297,7 @@ template<typename Derived>
inline Scalar AlignedBox<Scalar,AmbientDim>::squaredExteriorDistance(const MatrixBase<Derived>& a_p) const
{
const typename internal::nested<Derived,2*AmbientDim>::type p(a_p.derived());
- Scalar dist2 = 0.;
+ Scalar dist2(0);
Scalar aux;
for (Index k=0; k<dim(); ++k)
{
@@ -331,7 +318,7 @@ inline Scalar AlignedBox<Scalar,AmbientDim>::squaredExteriorDistance(const Matri
template<typename Scalar,int AmbientDim>
inline Scalar AlignedBox<Scalar,AmbientDim>::squaredExteriorDistance(const AlignedBox& b) const
{
- Scalar dist2 = 0.;
+ Scalar dist2(0);
Scalar aux;
for (Index k=0; k<dim(); ++k)
{
@@ -349,4 +336,40 @@ inline Scalar AlignedBox<Scalar,AmbientDim>::squaredExteriorDistance(const Align
return dist2;
}
+/** \defgroup alignedboxtypedefs Global aligned box typedefs
+ *
+ * \ingroup Geometry_Module
+ *
+ * Eigen defines several typedef shortcuts for most common aligned box types.
+ *
+ * The general patterns are the following:
+ *
+ * \c AlignedBoxSizeType where \c Size can be \c 1, \c 2,\c 3,\c 4 for fixed size boxes or \c X for dynamic size,
+ * and where \c Type can be \c i for integer, \c f for float, \c d for double.
+ *
+ * For example, \c AlignedBox3d is a fixed-size 3x3 aligned box type of doubles, and \c AlignedBoxXf is a dynamic-size aligned box of floats.
+ *
+ * \sa class AlignedBox
+ */
+
+#define EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, Size, SizeSuffix) \
+/** \ingroup alignedboxtypedefs */ \
+typedef AlignedBox<Type, Size> AlignedBox##SizeSuffix##TypeSuffix;
+
+#define EIGEN_MAKE_TYPEDEFS_ALL_SIZES(Type, TypeSuffix) \
+EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 1, 1) \
+EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 2, 2) \
+EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 3, 3) \
+EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 4, 4) \
+EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, Dynamic, X)
+
+EIGEN_MAKE_TYPEDEFS_ALL_SIZES(int, i)
+EIGEN_MAKE_TYPEDEFS_ALL_SIZES(float, f)
+EIGEN_MAKE_TYPEDEFS_ALL_SIZES(double, d)
+
+#undef EIGEN_MAKE_TYPEDEFS_ALL_SIZES
+#undef EIGEN_MAKE_TYPEDEFS
+
+} // end namespace Eigen
+
#endif // EIGEN_ALIGNEDBOX_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/AngleAxis.h b/extern/Eigen3/Eigen/src/Geometry/AngleAxis.h
index 0ec4624cf98..67197ac78c3 100644
--- a/extern/Eigen3/Eigen/src/Geometry/AngleAxis.h
+++ b/extern/Eigen3/Eigen/src/Geometry/AngleAxis.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ANGLEAXIS_H
#define EIGEN_ANGLEAXIS_H
+namespace Eigen {
+
/** \geometry_module \ingroup Geometry_Module
*
* \class AngleAxis
@@ -144,7 +131,7 @@ public:
m_angle = Scalar(other.angle());
}
- inline static const AngleAxis Identity() { return AngleAxis(0, Vector3::UnitX()); }
+ static inline const AngleAxis Identity() { return AngleAxis(0, Vector3::UnitX()); }
/** \returns \c true if \c *this is approximately equal to \a other, within the precision
* determined by \a prec.
@@ -238,4 +225,6 @@ AngleAxis<Scalar>::toRotationMatrix(void) const
return res;
}
+} // end namespace Eigen
+
#endif // EIGEN_ANGLEAXIS_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/EulerAngles.h b/extern/Eigen3/Eigen/src/Geometry/EulerAngles.h
index d246a6ebf4a..e424d240604 100644
--- a/extern/Eigen3/Eigen/src/Geometry/EulerAngles.h
+++ b/extern/Eigen3/Eigen/src/Geometry/EulerAngles.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_EULERANGLES_H
#define EIGEN_EULERANGLES_H
+namespace Eigen {
+
/** \geometry_module \ingroup Geometry_Module
*
*
@@ -92,5 +79,6 @@ MatrixBase<Derived>::eulerAngles(Index a0, Index a1, Index a2) const
return res;
}
+} // end namespace Eigen
#endif // EIGEN_EULERANGLES_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/Homogeneous.h b/extern/Eigen3/Eigen/src/Geometry/Homogeneous.h
index 2bc4f7e87e3..df03feb55c6 100644
--- a/extern/Eigen3/Eigen/src/Geometry/Homogeneous.h
+++ b/extern/Eigen3/Eigen/src/Geometry/Homogeneous.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_HOMOGENEOUS_H
#define EIGEN_HOMOGENEOUS_H
+namespace Eigen {
+
/** \geometry_module \ingroup Geometry_Module
*
* \class Homogeneous
@@ -121,7 +108,7 @@ template<typename MatrixType,int _Direction> class Homogeneous
}
protected:
- const typename MatrixType::Nested m_matrix;
+ typename MatrixType::Nested m_matrix;
};
/** \geometry_module
@@ -216,8 +203,8 @@ template<typename Scalar, int Dim, int Mode,int Options>
struct take_matrix_for_product<Transform<Scalar, Dim, Mode, Options> >
{
typedef Transform<Scalar, Dim, Mode, Options> TransformType;
- typedef typename TransformType::ConstAffinePart type;
- static const type run (const TransformType& x) { return x.affine(); }
+ typedef typename internal::add_const<typename TransformType::ConstAffinePart>::type type;
+ static type run (const TransformType& x) { return x.affine(); }
};
template<typename Scalar, int Dim, int Options>
@@ -270,8 +257,8 @@ struct homogeneous_left_product_impl<Homogeneous<MatrixType,Vertical>,Lhs>
.template replicate<MatrixType::ColsAtCompileTime>(m_rhs.cols());
}
- const typename LhsMatrixTypeCleaned::Nested m_lhs;
- const typename MatrixType::Nested m_rhs;
+ typename LhsMatrixTypeCleaned::Nested m_lhs;
+ typename MatrixType::Nested m_rhs;
};
template<typename MatrixType,typename Rhs>
@@ -309,10 +296,12 @@ struct homogeneous_right_product_impl<Homogeneous<MatrixType,Horizontal>,Rhs>
.template replicate<MatrixType::RowsAtCompileTime>(m_lhs.rows());
}
- const typename MatrixType::Nested m_lhs;
- const typename Rhs::Nested m_rhs;
+ typename MatrixType::Nested m_lhs;
+ typename Rhs::Nested m_rhs;
};
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_HOMOGENEOUS_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/Hyperplane.h b/extern/Eigen3/Eigen/src/Geometry/Hyperplane.h
index d85d3e553f8..1b7c7c78c80 100644
--- a/extern/Eigen3/Eigen/src/Geometry/Hyperplane.h
+++ b/extern/Eigen3/Eigen/src/Geometry/Hyperplane.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_HYPERPLANE_H
#define EIGEN_HYPERPLANE_H
+namespace Eigen {
+
/** \geometry_module \ingroup Geometry_Module
*
* \class Hyperplane
@@ -277,4 +264,6 @@ protected:
Coefficients m_coeffs;
};
+} // end namespace Eigen
+
#endif // EIGEN_HYPERPLANE_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/OrthoMethods.h b/extern/Eigen3/Eigen/src/Geometry/OrthoMethods.h
index 52b46988196..11ad5829cda 100644
--- a/extern/Eigen3/Eigen/src/Geometry/OrthoMethods.h
+++ b/extern/Eigen3/Eigen/src/Geometry/OrthoMethods.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ORTHOMETHODS_H
#define EIGEN_ORTHOMETHODS_H
+namespace Eigen {
+
/** \geometry_module
*
* \returns the cross product of \c *this and \a other
@@ -43,8 +30,8 @@ MatrixBase<Derived>::cross(const MatrixBase<OtherDerived>& other) const
// Note that there is no need for an expression here since the compiler
// optimize such a small temporary very well (even within a complex expression)
- const typename internal::nested<Derived,2>::type lhs(derived());
- const typename internal::nested<OtherDerived,2>::type rhs(other.derived());
+ typename internal::nested<Derived,2>::type lhs(derived());
+ typename internal::nested<OtherDerived,2>::type rhs(other.derived());
return typename cross_product_return_type<OtherDerived>::type(
internal::conj(lhs.coeff(1) * rhs.coeff(2) - lhs.coeff(2) * rhs.coeff(1)),
internal::conj(lhs.coeff(2) * rhs.coeff(0) - lhs.coeff(0) * rhs.coeff(2)),
@@ -56,9 +43,9 @@ namespace internal {
template< int Arch,typename VectorLhs,typename VectorRhs,
typename Scalar = typename VectorLhs::Scalar,
- bool Vectorizable = (VectorLhs::Flags&VectorRhs::Flags)&PacketAccessBit>
+ bool Vectorizable = bool((VectorLhs::Flags&VectorRhs::Flags)&PacketAccessBit)>
struct cross3_impl {
- inline static typename internal::plain_matrix_type<VectorLhs>::type
+ static inline typename internal::plain_matrix_type<VectorLhs>::type
run(const VectorLhs& lhs, const VectorRhs& rhs)
{
return typename internal::plain_matrix_type<VectorLhs>::type(
@@ -145,7 +132,7 @@ struct unitOrthogonal_selector
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef typename Derived::Index Index;
typedef Matrix<Scalar,2,1> Vector2;
- inline static VectorType run(const Derived& src)
+ static inline VectorType run(const Derived& src)
{
VectorType perp = VectorType::Zero(src.size());
Index maxi = 0;
@@ -167,7 +154,7 @@ struct unitOrthogonal_selector<Derived,3>
typedef typename plain_matrix_type<Derived>::type VectorType;
typedef typename traits<Derived>::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
- inline static VectorType run(const Derived& src)
+ static inline VectorType run(const Derived& src)
{
VectorType perp;
/* Let us compute the crossed product of *this with a vector
@@ -205,7 +192,7 @@ template<typename Derived>
struct unitOrthogonal_selector<Derived,2>
{
typedef typename plain_matrix_type<Derived>::type VectorType;
- inline static VectorType run(const Derived& src)
+ static inline VectorType run(const Derived& src)
{ return VectorType(-conj(src.y()), conj(src.x())).normalized(); }
};
@@ -226,4 +213,6 @@ MatrixBase<Derived>::unitOrthogonal() const
return internal::unitOrthogonal_selector<Derived>::run(derived());
}
+} // end namespace Eigen
+
#endif // EIGEN_ORTHOMETHODS_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/ParametrizedLine.h b/extern/Eigen3/Eigen/src/Geometry/ParametrizedLine.h
index b90f9c088a2..719a904413d 100644
--- a/extern/Eigen3/Eigen/src/Geometry/ParametrizedLine.h
+++ b/extern/Eigen3/Eigen/src/Geometry/ParametrizedLine.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PARAMETRIZEDLINE_H
#define EIGEN_PARAMETRIZEDLINE_H
+namespace Eigen {
+
/** \geometry_module \ingroup Geometry_Module
*
* \class ParametrizedLine
@@ -106,8 +93,16 @@ public:
VectorType projection(const VectorType& p) const
{ return origin() + direction().dot(p-origin()) * direction(); }
+ VectorType pointAt( Scalar t ) const;
+
+ template <int OtherOptions>
+ Scalar intersectionParameter(const Hyperplane<_Scalar, _AmbientDim, OtherOptions>& hyperplane) const;
+
template <int OtherOptions>
Scalar intersection(const Hyperplane<_Scalar, _AmbientDim, OtherOptions>& hyperplane) const;
+
+ template <int OtherOptions>
+ VectorType intersectionPoint(const Hyperplane<_Scalar, _AmbientDim, OtherOptions>& hyperplane) const;
/** \returns \c *this with scalar type casted to \a NewScalarType
*
@@ -155,14 +150,46 @@ inline ParametrizedLine<_Scalar, _AmbientDim,_Options>::ParametrizedLine(const H
origin() = -hyperplane.normal()*hyperplane.offset();
}
-/** \returns the parameter value of the intersection between \c *this and the given hyperplane
+/** \returns the point at \a t along this line
+ */
+template <typename _Scalar, int _AmbientDim, int _Options>
+inline typename ParametrizedLine<_Scalar, _AmbientDim,_Options>::VectorType
+ParametrizedLine<_Scalar, _AmbientDim,_Options>::pointAt( _Scalar t ) const
+{
+ return origin() + (direction()*t);
+}
+
+/** \returns the parameter value of the intersection between \c *this and the given \a hyperplane
*/
template <typename _Scalar, int _AmbientDim, int _Options>
template <int OtherOptions>
-inline _Scalar ParametrizedLine<_Scalar, _AmbientDim,_Options>::intersection(const Hyperplane<_Scalar, _AmbientDim, OtherOptions>& hyperplane) const
+inline _Scalar ParametrizedLine<_Scalar, _AmbientDim,_Options>::intersectionParameter(const Hyperplane<_Scalar, _AmbientDim, OtherOptions>& hyperplane) const
{
return -(hyperplane.offset()+hyperplane.normal().dot(origin()))
/ hyperplane.normal().dot(direction());
}
+
+/** \deprecated use intersectionParameter()
+ * \returns the parameter value of the intersection between \c *this and the given \a hyperplane
+ */
+template <typename _Scalar, int _AmbientDim, int _Options>
+template <int OtherOptions>
+inline _Scalar ParametrizedLine<_Scalar, _AmbientDim,_Options>::intersection(const Hyperplane<_Scalar, _AmbientDim, OtherOptions>& hyperplane) const
+{
+ return intersectionParameter(hyperplane);
+}
+
+/** \returns the point of the intersection between \c *this and the given hyperplane
+ */
+template <typename _Scalar, int _AmbientDim, int _Options>
+template <int OtherOptions>
+inline typename ParametrizedLine<_Scalar, _AmbientDim,_Options>::VectorType
+ParametrizedLine<_Scalar, _AmbientDim,_Options>::intersectionPoint(const Hyperplane<_Scalar, _AmbientDim, OtherOptions>& hyperplane) const
+{
+ return pointAt(intersectionParameter(hyperplane));
+}
+
+} // end namespace Eigen
+
#endif // EIGEN_PARAMETRIZEDLINE_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/Quaternion.h b/extern/Eigen3/Eigen/src/Geometry/Quaternion.h
index 9180db67d84..8792e2da2ae 100644
--- a/extern/Eigen3/Eigen/src/Geometry/Quaternion.h
+++ b/extern/Eigen3/Eigen/src/Geometry/Quaternion.h
@@ -4,27 +4,14 @@
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Mathieu Gautier <mathieu.gautier@cea.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_QUATERNION_H
#define EIGEN_QUATERNION_H
+namespace Eigen {
+
/***************************************************************************
* Definition of QuaternionBase<Derived>
@@ -38,6 +25,12 @@ template<typename Other,
struct quaternionbase_assign_impl;
}
+/** \geometry_module \ingroup Geometry_Module
+ * \class QuaternionBase
+ * \brief Base class for quaternion expressions
+ * \tparam Derived derived type (CRTP)
+ * \sa class Quaternion
+ */
template<class Derived>
class QuaternionBase : public RotationBase<Derived, 3>
{
@@ -109,7 +102,7 @@ public:
/** \returns a quaternion representing an identity rotation
* \sa MatrixBase::Identity()
*/
- inline static Quaternion<Scalar> Identity() { return Quaternion<Scalar>(1, 0, 0, 0); }
+ static inline Quaternion<Scalar> Identity() { return Quaternion<Scalar>(1, 0, 0, 0); }
/** \sa QuaternionBase::Identity(), MatrixBase::setIdentity()
*/
@@ -278,6 +271,9 @@ public:
explicit inline Quaternion(const Quaternion<OtherScalar, OtherOptions>& other)
{ m_coeffs = other.coeffs().template cast<Scalar>(); }
+ template<typename Derived1, typename Derived2>
+ static Quaternion FromTwoVectors(const MatrixBase<Derived1>& a, const MatrixBase<Derived2>& b);
+
inline Coefficients& coeffs() { return m_coeffs;}
inline const Coefficients& coeffs() const { return m_coeffs;}
@@ -287,7 +283,7 @@ protected:
Coefficients m_coeffs;
#ifndef EIGEN_PARSED_BY_DOXYGEN
- EIGEN_STRONG_INLINE static void _check_template_params()
+ static EIGEN_STRONG_INLINE void _check_template_params()
{
EIGEN_STATIC_ASSERT( (_Options & DontAlign) == _Options,
INVALID_MATRIX_TEMPLATE_PARAMETERS)
@@ -434,7 +430,7 @@ typedef Map<Quaternion<double>, Aligned> QuaternionMapAlignedd;
namespace internal {
template<int Arch, class Derived1, class Derived2, typename Scalar, int _Options> struct quat_product
{
- EIGEN_STRONG_INLINE static Quaternion<Scalar> run(const QuaternionBase<Derived1>& a, const QuaternionBase<Derived2>& b){
+ static EIGEN_STRONG_INLINE Quaternion<Scalar> run(const QuaternionBase<Derived1>& a, const QuaternionBase<Derived2>& b){
return Quaternion<Scalar>
(
a.w() * b.w() - a.x() * b.x() - a.y() * b.y() - a.z() * b.z(),
@@ -544,9 +540,9 @@ QuaternionBase<Derived>::toRotationMatrix(void) const
// it has to be inlined, and so the return by value is not an issue
Matrix3 res;
- const Scalar tx = 2*this->x();
- const Scalar ty = 2*this->y();
- const Scalar tz = 2*this->z();
+ const Scalar tx = Scalar(2)*this->x();
+ const Scalar ty = Scalar(2)*this->y();
+ const Scalar tz = Scalar(2)*this->z();
const Scalar twx = tx*this->w();
const Scalar twy = ty*this->w();
const Scalar twz = tz*this->w();
@@ -557,15 +553,15 @@ QuaternionBase<Derived>::toRotationMatrix(void) const
const Scalar tyz = tz*this->y();
const Scalar tzz = tz*this->z();
- res.coeffRef(0,0) = 1-(tyy+tzz);
+ res.coeffRef(0,0) = Scalar(1)-(tyy+tzz);
res.coeffRef(0,1) = txy-twz;
res.coeffRef(0,2) = txz+twy;
res.coeffRef(1,0) = txy+twz;
- res.coeffRef(1,1) = 1-(txx+tzz);
+ res.coeffRef(1,1) = Scalar(1)-(txx+tzz);
res.coeffRef(1,2) = tyz-twx;
res.coeffRef(2,0) = txz-twy;
res.coeffRef(2,1) = tyz+twx;
- res.coeffRef(2,2) = 1-(txx+tyy);
+ res.coeffRef(2,2) = Scalar(1)-(txx+tyy);
return res;
}
@@ -618,6 +614,27 @@ inline Derived& QuaternionBase<Derived>::setFromTwoVectors(const MatrixBase<Deri
return derived();
}
+
+/** Returns a quaternion representing a rotation between
+ * the two arbitrary vectors \a a and \a b. In other words, the built
+ * rotation represent a rotation sending the line of direction \a a
+ * to the line of direction \a b, both lines passing through the origin.
+ *
+ * \returns resulting quaternion
+ *
+ * Note that the two input vectors do \b not have to be normalized, and
+ * do not need to have the same norm.
+ */
+template<typename Scalar, int Options>
+template<typename Derived1, typename Derived2>
+Quaternion<Scalar,Options> Quaternion<Scalar,Options>::FromTwoVectors(const MatrixBase<Derived1>& a, const MatrixBase<Derived2>& b)
+{
+ Quaternion quat;
+ quat.setFromTwoVectors(a, b);
+ return quat;
+}
+
+
/** \returns the multiplicative inverse of \c *this
* Note that in most cases, i.e., if you simply want the opposite rotation,
* and/or the quaternion is normalized, then it is enough to use the conjugate.
@@ -709,7 +726,7 @@ struct quaternionbase_assign_impl<Other,3,3>
{
typedef typename Other::Scalar Scalar;
typedef DenseIndex Index;
- template<class Derived> inline static void run(QuaternionBase<Derived>& q, const Other& mat)
+ template<class Derived> static inline void run(QuaternionBase<Derived>& q, const Other& mat)
{
// This algorithm comes from "Quaternion Calculus and Fast Animation",
// Ken Shoemake, 1987 SIGGRAPH course notes
@@ -748,7 +765,7 @@ template<typename Other>
struct quaternionbase_assign_impl<Other,4,1>
{
typedef typename Other::Scalar Scalar;
- template<class Derived> inline static void run(QuaternionBase<Derived>& q, const Other& vec)
+ template<class Derived> static inline void run(QuaternionBase<Derived>& q, const Other& vec)
{
q.coeffs() = vec;
}
@@ -756,4 +773,6 @@ struct quaternionbase_assign_impl<Other,4,1>
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_QUATERNION_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/Rotation2D.h b/extern/Eigen3/Eigen/src/Geometry/Rotation2D.h
index cf36da1c50c..868e2ef312f 100644
--- a/extern/Eigen3/Eigen/src/Geometry/Rotation2D.h
+++ b/extern/Eigen3/Eigen/src/Geometry/Rotation2D.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ROTATION2D_H
#define EIGEN_ROTATION2D_H
+namespace Eigen {
+
/** \geometry_module \ingroup Geometry_Module
*
* \class Rotation2D
@@ -121,7 +108,7 @@ public:
m_angle = Scalar(other.angle());
}
- inline static Rotation2D Identity() { return Rotation2D(0); }
+ static inline Rotation2D Identity() { return Rotation2D(0); }
/** \returns \c true if \c *this is approximately equal to \a other, within the precision
* determined by \a prec.
@@ -162,4 +149,6 @@ Rotation2D<Scalar>::toRotationMatrix(void) const
return (Matrix2() << cosA, -sinA, sinA, cosA).finished();
}
+} // end namespace Eigen
+
#endif // EIGEN_ROTATION2D_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/RotationBase.h b/extern/Eigen3/Eigen/src/Geometry/RotationBase.h
index 1abf06bb640..b88661de6b1 100644
--- a/extern/Eigen3/Eigen/src/Geometry/RotationBase.h
+++ b/extern/Eigen3/Eigen/src/Geometry/RotationBase.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ROTATIONBASE_H
#define EIGEN_ROTATIONBASE_H
+namespace Eigen {
+
// forward declaration
namespace internal {
template<typename RotationDerived, typename MatrixType, bool IsVector=MatrixType::IsVectorAtCompileTime>
@@ -115,7 +102,7 @@ struct rotation_base_generic_product_selector<RotationDerived,MatrixType,false>
{
enum { Dim = RotationDerived::Dim };
typedef Matrix<typename RotationDerived::Scalar,Dim,Dim> ReturnType;
- inline static ReturnType run(const RotationDerived& r, const MatrixType& m)
+ static inline ReturnType run(const RotationDerived& r, const MatrixType& m)
{ return r.toRotationMatrix() * m; }
};
@@ -123,7 +110,7 @@ template<typename RotationDerived, typename Scalar, int Dim, int MaxDim>
struct rotation_base_generic_product_selector< RotationDerived, DiagonalMatrix<Scalar,Dim,MaxDim>, false >
{
typedef Transform<Scalar,Dim,Affine> ReturnType;
- inline static ReturnType run(const RotationDerived& r, const DiagonalMatrix<Scalar,Dim,MaxDim>& m)
+ static inline ReturnType run(const RotationDerived& r, const DiagonalMatrix<Scalar,Dim,MaxDim>& m)
{
ReturnType res(r);
res.linear() *= m;
@@ -136,7 +123,7 @@ struct rotation_base_generic_product_selector<RotationDerived,OtherVectorType,tr
{
enum { Dim = RotationDerived::Dim };
typedef Matrix<typename RotationDerived::Scalar,Dim,1> ReturnType;
- EIGEN_STRONG_INLINE static ReturnType run(const RotationDerived& r, const OtherVectorType& v)
+ static EIGEN_STRONG_INLINE ReturnType run(const RotationDerived& r, const OtherVectorType& v)
{
return r._transformVector(v);
}
@@ -192,20 +179,20 @@ namespace internal {
* \sa class Transform, class Rotation2D, class Quaternion, class AngleAxis
*/
template<typename Scalar, int Dim>
-inline static Matrix<Scalar,2,2> toRotationMatrix(const Scalar& s)
+static inline Matrix<Scalar,2,2> toRotationMatrix(const Scalar& s)
{
EIGEN_STATIC_ASSERT(Dim==2,YOU_MADE_A_PROGRAMMING_MISTAKE)
return Rotation2D<Scalar>(s).toRotationMatrix();
}
template<typename Scalar, int Dim, typename OtherDerived>
-inline static Matrix<Scalar,Dim,Dim> toRotationMatrix(const RotationBase<OtherDerived,Dim>& r)
+static inline Matrix<Scalar,Dim,Dim> toRotationMatrix(const RotationBase<OtherDerived,Dim>& r)
{
return r.toRotationMatrix();
}
template<typename Scalar, int Dim, typename OtherDerived>
-inline static const MatrixBase<OtherDerived>& toRotationMatrix(const MatrixBase<OtherDerived>& mat)
+static inline const MatrixBase<OtherDerived>& toRotationMatrix(const MatrixBase<OtherDerived>& mat)
{
EIGEN_STATIC_ASSERT(OtherDerived::RowsAtCompileTime==Dim && OtherDerived::ColsAtCompileTime==Dim,
YOU_MADE_A_PROGRAMMING_MISTAKE)
@@ -214,4 +201,6 @@ inline static const MatrixBase<OtherDerived>& toRotationMatrix(const MatrixBase<
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_ROTATIONBASE_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/Scaling.h b/extern/Eigen3/Eigen/src/Geometry/Scaling.h
index c911d13e1d3..8edcac31c74 100644
--- a/extern/Eigen3/Eigen/src/Geometry/Scaling.h
+++ b/extern/Eigen3/Eigen/src/Geometry/Scaling.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SCALING_H
#define EIGEN_SCALING_H
+namespace Eigen {
+
/** \geometry_module \ingroup Geometry_Module
*
* \class Scaling
@@ -73,7 +60,12 @@ public:
/** Concatenates a uniform scaling and an affine transformation */
template<int Dim, int Mode, int Options>
- inline Transform<Scalar,Dim,Mode> operator* (const Transform<Scalar,Dim, Mode, Options>& t) const;
+ inline Transform<Scalar,Dim,(int(Mode)==int(Isometry)?Affine:Mode)> operator* (const Transform<Scalar,Dim, Mode, Options>& t) const
+ {
+ Transform<Scalar,Dim,(int(Mode)==int(Isometry)?Affine:Mode)> res = t;
+ res.prescale(factor());
+ return res;
+}
/** Concatenates a uniform scaling and a linear transformation matrix */
// TODO returns an expression
@@ -169,14 +161,6 @@ UniformScaling<Scalar>::operator* (const Translation<Scalar,Dim>& t) const
return res;
}
-template<typename Scalar>
-template<int Dim,int Mode,int Options>
-inline Transform<Scalar,Dim,Mode>
-UniformScaling<Scalar>::operator* (const Transform<Scalar,Dim, Mode, Options>& t) const
-{
- Transform<Scalar,Dim,Mode> res = t;
- res.prescale(factor());
- return res;
-}
+} // end namespace Eigen
#endif // EIGEN_SCALING_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/Transform.h b/extern/Eigen3/Eigen/src/Geometry/Transform.h
index a694673ebed..4c1ef8eaade 100644
--- a/extern/Eigen3/Eigen/src/Geometry/Transform.h
+++ b/extern/Eigen3/Eigen/src/Geometry/Transform.h
@@ -5,28 +5,15 @@
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2010 Hauke Heibel <hauke.heibel@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRANSFORM_H
#define EIGEN_TRANSFORM_H
+namespace Eigen {
+
namespace internal {
template<typename Transform>
@@ -37,7 +24,7 @@ struct transform_traits
Dim = Transform::Dim,
HDim = Transform::HDim,
Mode = Transform::Mode,
- IsProjective = (Mode==Projective)
+ IsProjective = (int(Mode)==int(Projective))
};
};
@@ -207,9 +194,9 @@ public:
/** type of the matrix used to represent the linear part of the transformation */
typedef Matrix<Scalar,Dim,Dim,Options> LinearMatrixType;
/** type of read/write reference to the linear part of the transformation */
- typedef Block<MatrixType,Dim,Dim> LinearPart;
+ typedef Block<MatrixType,Dim,Dim,int(Mode)==(AffineCompact)> LinearPart;
/** type of read reference to the linear part of the transformation */
- typedef const Block<ConstMatrixType,Dim,Dim> ConstLinearPart;
+ typedef const Block<ConstMatrixType,Dim,Dim,int(Mode)==(AffineCompact)> ConstLinearPart;
/** type of read/write reference to the affine part of the transformation */
typedef typename internal::conditional<int(Mode)==int(AffineCompact),
MatrixType&,
@@ -221,9 +208,9 @@ public:
/** type of a vector */
typedef Matrix<Scalar,Dim,1> VectorType;
/** type of a read/write reference to the translation part of the rotation */
- typedef Block<MatrixType,Dim,1> TranslationPart;
+ typedef Block<MatrixType,Dim,1,int(Mode)==(AffineCompact)> TranslationPart;
/** type of a read reference to the translation part of the rotation */
- typedef const Block<ConstMatrixType,Dim,1> ConstTranslationPart;
+ typedef const Block<ConstMatrixType,Dim,1,int(Mode)==(AffineCompact)> ConstTranslationPart;
/** corresponding translation type */
typedef Translation<Scalar,Dim> TranslationType;
@@ -279,6 +266,9 @@ public:
template<typename OtherDerived>
inline explicit Transform(const EigenBase<OtherDerived>& other)
{
+ EIGEN_STATIC_ASSERT((internal::is_same<Scalar,typename OtherDerived::Scalar>::value),
+ YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY);
+
check_template_params();
internal::transform_construct_from_matrix<OtherDerived,Mode,Options,Dim,HDim>::run(this, other.derived());
}
@@ -287,6 +277,9 @@ public:
template<typename OtherDerived>
inline Transform& operator=(const EigenBase<OtherDerived>& other)
{
+ EIGEN_STATIC_ASSERT((internal::is_same<Scalar,typename OtherDerived::Scalar>::value),
+ YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY);
+
internal::transform_construct_from_matrix<OtherDerived,Mode,Options,Dim,HDim>::run(this, other.derived());
return *this;
}
@@ -376,9 +369,9 @@ public:
inline MatrixType& matrix() { return m_matrix; }
/** \returns a read-only expression of the linear part of the transformation */
- inline ConstLinearPart linear() const { return m_matrix.template block<Dim,Dim>(0,0); }
+ inline ConstLinearPart linear() const { return ConstLinearPart(m_matrix,0,0); }
/** \returns a writable expression of the linear part of the transformation */
- inline LinearPart linear() { return m_matrix.template block<Dim,Dim>(0,0); }
+ inline LinearPart linear() { return LinearPart(m_matrix,0,0); }
/** \returns a read-only expression of the Dim x HDim affine part of the transformation */
inline ConstAffinePart affine() const { return take_affine_part::run(m_matrix); }
@@ -386,9 +379,9 @@ public:
inline AffinePart affine() { return take_affine_part::run(m_matrix); }
/** \returns a read-only expression of the translation vector of the transformation */
- inline ConstTranslationPart translation() const { return m_matrix.template block<Dim,1>(0,Dim); }
+ inline ConstTranslationPart translation() const { return ConstTranslationPart(m_matrix,0,Dim); }
/** \returns a writable expression of the translation vector of the transformation */
- inline TranslationPart translation() { return m_matrix.template block<Dim,1>(0,Dim); }
+ inline TranslationPart translation() { return TranslationPart(m_matrix,0,Dim); }
/** \returns an expression of the product between the transform \c *this and a matrix expression \a other
*
@@ -460,15 +453,40 @@ public:
{
return internal::transform_transform_product_impl<Transform,Transform>::run(*this,other);
}
-
+
+ #ifdef __INTEL_COMPILER
+private:
+ // this intermediate structure permits to workaround a bug in ICC 11:
+ // error: template instantiation resulted in unexpected function type of "Eigen::Transform<double, 3, 32, 0>
+ // (const Eigen::Transform<double, 3, 2, 0> &) const"
+ // (the meaning of a name may have changed since the template declaration -- the type of the template is:
+ // "Eigen::internal::transform_transform_product_impl<Eigen::Transform<double, 3, 32, 0>,
+ // Eigen::Transform<double, 3, Mode, Options>, <expression>>::ResultType (const Eigen::Transform<double, 3, Mode, Options> &) const")
+ //
+ template<int OtherMode,int OtherOptions> struct icc_11_workaround
+ {
+ typedef internal::transform_transform_product_impl<Transform,Transform<Scalar,Dim,OtherMode,OtherOptions> > ProductType;
+ typedef typename ProductType::ResultType ResultType;
+ };
+
+public:
+ /** Concatenates two different transformations */
+ template<int OtherMode,int OtherOptions>
+ inline typename icc_11_workaround<OtherMode,OtherOptions>::ResultType
+ operator * (const Transform<Scalar,Dim,OtherMode,OtherOptions>& other) const
+ {
+ typedef typename icc_11_workaround<OtherMode,OtherOptions>::ProductType ProductType;
+ return ProductType::run(*this,other);
+ }
+ #else
/** Concatenates two different transformations */
template<int OtherMode,int OtherOptions>
- inline const typename internal::transform_transform_product_impl<
- Transform,Transform<Scalar,Dim,OtherMode,OtherOptions> >::ResultType
+ inline typename internal::transform_transform_product_impl<Transform,Transform<Scalar,Dim,OtherMode,OtherOptions> >::ResultType
operator * (const Transform<Scalar,Dim,OtherMode,OtherOptions>& other) const
{
return internal::transform_transform_product_impl<Transform,Transform<Scalar,Dim,OtherMode,OtherOptions> >::run(*this,other);
}
+ #endif
/** \sa MatrixBase::setIdentity() */
void setIdentity() { m_matrix.setIdentity(); }
@@ -512,7 +530,12 @@ public:
inline Transform& operator=(const UniformScaling<Scalar>& t);
inline Transform& operator*=(const UniformScaling<Scalar>& s) { return scale(s.factor()); }
- inline Transform operator*(const UniformScaling<Scalar>& s) const;
+ inline Transform<Scalar,Dim,(int(Mode)==int(Isometry)?Affine:Isometry)> operator*(const UniformScaling<Scalar>& s) const
+ {
+ Transform<Scalar,Dim,(int(Mode)==int(Isometry)?Affine:Isometry),Options> res = *this;
+ res.scale(s.factor());
+ return res;
+ }
inline Transform& operator*=(const DiagonalMatrix<Scalar,Dim>& s) { linear() *= s; return *this; }
@@ -571,7 +594,7 @@ public:
if(int(Mode)!=int(AffineCompact))
{
matrix().template block<1,Dim>(Dim,0).setZero();
- matrix().coeffRef(Dim,Dim) = 1;
+ matrix().coeffRef(Dim,Dim) = Scalar(1);
}
}
@@ -608,7 +631,7 @@ public:
protected:
#ifndef EIGEN_PARSED_BY_DOXYGEN
- EIGEN_STRONG_INLINE static void check_template_params()
+ static EIGEN_STRONG_INLINE void check_template_params()
{
EIGEN_STATIC_ASSERT((Options & (DontAlign|RowMajor)) == Options, INVALID_MATRIX_TEMPLATE_PARAMETERS)
}
@@ -941,14 +964,6 @@ inline Transform<Scalar,Dim,Mode,Options>& Transform<Scalar,Dim,Mode,Options>::o
}
template<typename Scalar, int Dim, int Mode, int Options>
-inline Transform<Scalar,Dim,Mode,Options> Transform<Scalar,Dim,Mode,Options>::operator*(const UniformScaling<Scalar>& s) const
-{
- Transform res = *this;
- res.scale(s.factor());
- return res;
-}
-
-template<typename Scalar, int Dim, int Mode, int Options>
template<typename Derived>
inline Transform<Scalar,Dim,Mode,Options>& Transform<Scalar,Dim,Mode,Options>::operator=(const RotationBase<Derived,Dim>& r)
{
@@ -1219,7 +1234,7 @@ struct transform_right_product_impl< TransformType, MatrixType, 0 >
{
typedef typename MatrixType::PlainObject ResultType;
- EIGEN_STRONG_INLINE static ResultType run(const TransformType& T, const MatrixType& other)
+ static EIGEN_STRONG_INLINE ResultType run(const TransformType& T, const MatrixType& other)
{
return T.matrix() * other;
}
@@ -1237,11 +1252,11 @@ struct transform_right_product_impl< TransformType, MatrixType, 1 >
typedef typename MatrixType::PlainObject ResultType;
- EIGEN_STRONG_INLINE static ResultType run(const TransformType& T, const MatrixType& other)
+ static EIGEN_STRONG_INLINE ResultType run(const TransformType& T, const MatrixType& other)
{
EIGEN_STATIC_ASSERT(OtherRows==HDim, YOU_MIXED_MATRICES_OF_DIFFERENT_SIZES);
- typedef Block<ResultType, Dim, OtherCols> TopLeftLhs;
+ typedef Block<ResultType, Dim, OtherCols, int(MatrixType::RowsAtCompileTime)==Dim> TopLeftLhs;
ResultType res(other.rows(),other.cols());
TopLeftLhs(res, 0, 0, Dim, other.cols()).noalias() = T.affine() * other;
@@ -1263,15 +1278,13 @@ struct transform_right_product_impl< TransformType, MatrixType, 2 >
typedef typename MatrixType::PlainObject ResultType;
- EIGEN_STRONG_INLINE static ResultType run(const TransformType& T, const MatrixType& other)
+ static EIGEN_STRONG_INLINE ResultType run(const TransformType& T, const MatrixType& other)
{
EIGEN_STATIC_ASSERT(OtherRows==Dim, YOU_MIXED_MATRICES_OF_DIFFERENT_SIZES);
- typedef Block<ResultType, Dim, OtherCols> TopLeftLhs;
-
- ResultType res(other.rows(),other.cols());
- TopLeftLhs(res, 0, 0, Dim, other.cols()).noalias() = T.linear() * other;
- TopLeftLhs(res, 0, 0, Dim, other.cols()).colwise() += T.translation();
+ typedef Block<ResultType, Dim, OtherCols, true> TopLeftLhs;
+ ResultType res(Replicate<typename TransformType::ConstTranslationPart, 1, OtherCols>(T.translation(),1,other.cols()));
+ TopLeftLhs(res, 0, 0, Dim, other.cols()).noalias() += T.linear() * other;
return res;
}
@@ -1422,4 +1435,6 @@ struct transform_transform_product_impl<Transform<Scalar,Dim,Projective,LhsOptio
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_TRANSFORM_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/Translation.h b/extern/Eigen3/Eigen/src/Geometry/Translation.h
index d8fe50f987e..7fda179cc35 100644
--- a/extern/Eigen3/Eigen/src/Geometry/Translation.h
+++ b/extern/Eigen3/Eigen/src/Geometry/Translation.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRANSLATION_H
#define EIGEN_TRANSLATION_H
+namespace Eigen {
+
/** \geometry_module \ingroup Geometry_Module
*
* \class Translation
@@ -54,6 +41,8 @@ public:
typedef Matrix<Scalar,Dim,Dim> LinearMatrixType;
/** corresponding affine transformation type */
typedef Transform<Scalar,Dim,Affine> AffineTransformType;
+ /** corresponding isometric transformation type */
+ typedef Transform<Scalar,Dim,Isometry> IsometryTransformType;
protected:
@@ -114,8 +103,8 @@ public:
/** Concatenates a translation and a rotation */
template<typename Derived>
- inline AffineTransformType operator*(const RotationBase<Derived,Dim>& r) const
- { return *this * r.toRotationMatrix(); }
+ inline IsometryTransformType operator*(const RotationBase<Derived,Dim>& r) const
+ { return *this * IsometryTransformType(r); }
/** \returns the concatenation of a linear transformation \a l with the translation \a t */
// its a nightmare to define a templated friend function outside its declaration
@@ -212,4 +201,6 @@ Translation<Scalar,Dim>::operator* (const EigenBase<OtherDerived>& linear) const
return res;
}
+} // end namespace Eigen
+
#endif // EIGEN_TRANSLATION_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/Umeyama.h b/extern/Eigen3/Eigen/src/Geometry/Umeyama.h
index b50f461730e..ac0939cde52 100644
--- a/extern/Eigen3/Eigen/src/Geometry/Umeyama.h
+++ b/extern/Eigen3/Eigen/src/Geometry/Umeyama.h
@@ -3,24 +3,9 @@
//
// Copyright (C) 2009 Hauke Heibel <hauke.heibel@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_UMEYAMA_H
#define EIGEN_UMEYAMA_H
@@ -31,6 +16,8 @@
// * Eigen/SVD
// * Eigen/Array
+namespace Eigen {
+
#ifndef EIGEN_PARSED_BY_DOXYGEN
// These helpers are required since it allows to use mixed types as parameters
@@ -180,4 +167,6 @@ umeyama(const MatrixBase<Derived>& src, const MatrixBase<OtherDerived>& dst, boo
return Rt;
}
+} // end namespace Eigen
+
#endif // EIGEN_UMEYAMA_H
diff --git a/extern/Eigen3/Eigen/src/Geometry/arch/Geometry_SSE.h b/extern/Eigen3/Eigen/src/Geometry/arch/Geometry_SSE.h
index 2af32678d1c..3d8284f2d0c 100644
--- a/extern/Eigen3/Eigen/src/Geometry/arch/Geometry_SSE.h
+++ b/extern/Eigen3/Eigen/src/Geometry/arch/Geometry_SSE.h
@@ -4,34 +4,21 @@
// Copyright (C) 2009 Rohit Garg <rpg.314@gmail.com>
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GEOMETRY_SSE_H
#define EIGEN_GEOMETRY_SSE_H
+namespace Eigen {
+
namespace internal {
template<class Derived, class OtherDerived>
struct quat_product<Architecture::SSE, Derived, OtherDerived, float, Aligned>
{
- inline static Quaternion<float> run(const QuaternionBase<Derived>& _a, const QuaternionBase<OtherDerived>& _b)
+ static inline Quaternion<float> run(const QuaternionBase<Derived>& _a, const QuaternionBase<OtherDerived>& _b)
{
const __m128 mask = _mm_castsi128_ps(_mm_setr_epi32(0,0,0,0x80000000));
Quaternion<float> res;
@@ -53,7 +40,7 @@ struct quat_product<Architecture::SSE, Derived, OtherDerived, float, Aligned>
template<typename VectorLhs,typename VectorRhs>
struct cross3_impl<Architecture::SSE,VectorLhs,VectorRhs,float,true>
{
- inline static typename plain_matrix_type<VectorLhs>::type
+ static inline typename plain_matrix_type<VectorLhs>::type
run(const VectorLhs& lhs, const VectorRhs& rhs)
{
__m128 a = lhs.template packet<VectorLhs::Flags&AlignedBit ? Aligned : Unaligned>(0);
@@ -72,7 +59,7 @@ struct cross3_impl<Architecture::SSE,VectorLhs,VectorRhs,float,true>
template<class Derived, class OtherDerived>
struct quat_product<Architecture::SSE, Derived, OtherDerived, double, Aligned>
{
- inline static Quaternion<double> run(const QuaternionBase<Derived>& _a, const QuaternionBase<OtherDerived>& _b)
+ static inline Quaternion<double> run(const QuaternionBase<Derived>& _a, const QuaternionBase<OtherDerived>& _b)
{
const Packet2d mask = _mm_castsi128_pd(_mm_set_epi32(0x0,0x0,0x80000000,0x0));
@@ -123,4 +110,6 @@ struct quat_product<Architecture::SSE, Derived, OtherDerived, double, Aligned>
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_GEOMETRY_SSE_H
diff --git a/extern/Eigen3/Eigen/src/Householder/BlockHouseholder.h b/extern/Eigen3/Eigen/src/Householder/BlockHouseholder.h
index 23ce1bfbd46..1991c652738 100644
--- a/extern/Eigen3/Eigen/src/Householder/BlockHouseholder.h
+++ b/extern/Eigen3/Eigen/src/Householder/BlockHouseholder.h
@@ -4,30 +4,17 @@
// Copyright (C) 2010 Vincent Lejeune
// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BLOCK_HOUSEHOLDER_H
#define EIGEN_BLOCK_HOUSEHOLDER_H
// This file contains some helper function to deal with block householder reflectors
+namespace Eigen {
+
namespace internal {
/** \internal */
@@ -64,7 +51,7 @@ void apply_block_householder_on_the_left(MatrixType& mat, const VectorsType& vec
Matrix<typename MatrixType::Scalar, TFactorSize, TFactorSize> T(nbVecs,nbVecs);
make_block_householder_triangular_factor(T, vectors, hCoeffs);
- const TriangularView<VectorsType, UnitLower>& V(vectors);
+ const TriangularView<const VectorsType, UnitLower>& V(vectors);
// A -= V T V^* A
Matrix<typename MatrixType::Scalar,VectorsType::ColsAtCompileTime,MatrixType::ColsAtCompileTime,0,
@@ -76,4 +63,6 @@ void apply_block_householder_on_the_left(MatrixType& mat, const VectorsType& vec
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_BLOCK_HOUSEHOLDER_H
diff --git a/extern/Eigen3/Eigen/src/Householder/Householder.h b/extern/Eigen3/Eigen/src/Householder/Householder.h
index 74139c0dcce..3f64b7dde2f 100644
--- a/extern/Eigen3/Eigen/src/Householder/Householder.h
+++ b/extern/Eigen3/Eigen/src/Householder/Householder.h
@@ -4,28 +4,15 @@
// Copyright (C) 2010 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_HOUSEHOLDER_H
#define EIGEN_HOUSEHOLDER_H
+namespace Eigen {
+
namespace internal {
template<int n> struct decrement_size
{
@@ -35,6 +22,22 @@ template<int n> struct decrement_size
};
}
+/** Computes the elementary reflector H such that:
+ * \f$ H *this = [ beta 0 ... 0]^T \f$
+ * where the transformation H is:
+ * \f$ H = I - tau v v^*\f$
+ * and the vector v is:
+ * \f$ v^T = [1 essential^T] \f$
+ *
+ * The essential part of the vector \c v is stored in *this.
+ *
+ * On output:
+ * \param tau the scaling factor of the Householder transformation
+ * \param beta the result of H * \c *this
+ *
+ * \sa MatrixBase::makeHouseholder(), MatrixBase::applyHouseholderOnTheLeft(),
+ * MatrixBase::applyHouseholderOnTheRight()
+ */
template<typename Derived>
void MatrixBase<Derived>::makeHouseholderInPlace(Scalar& tau, RealScalar& beta)
{
@@ -51,7 +54,7 @@ void MatrixBase<Derived>::makeHouseholderInPlace(Scalar& tau, RealScalar& beta)
*
* On output:
* \param essential the essential part of the vector \c v
- * \param tau the scaling factor of the householder transformation
+ * \param tau the scaling factor of the Householder transformation
* \param beta the result of H * \c *this
*
* \sa MatrixBase::makeHouseholderInPlace(), MatrixBase::applyHouseholderOnTheLeft(),
@@ -86,6 +89,21 @@ void MatrixBase<Derived>::makeHouseholder(
}
}
+/** Apply the elementary reflector H given by
+ * \f$ H = I - tau v v^*\f$
+ * with
+ * \f$ v^T = [1 essential^T] \f$
+ * from the left to a vector or matrix.
+ *
+ * On input:
+ * \param essential the essential part of the vector \c v
+ * \param tau the scaling factor of the Householder transformation
+ * \param workspace a pointer to working space with at least
+ * this->cols() * essential.size() entries
+ *
+ * \sa MatrixBase::makeHouseholder(), MatrixBase::makeHouseholderInPlace(),
+ * MatrixBase::applyHouseholderOnTheRight()
+ */
template<typename Derived>
template<typename EssentialPart>
void MatrixBase<Derived>::applyHouseholderOnTheLeft(
@@ -108,6 +126,21 @@ void MatrixBase<Derived>::applyHouseholderOnTheLeft(
}
}
+/** Apply the elementary reflector H given by
+ * \f$ H = I - tau v v^*\f$
+ * with
+ * \f$ v^T = [1 essential^T] \f$
+ * from the right to a vector or matrix.
+ *
+ * On input:
+ * \param essential the essential part of the vector \c v
+ * \param tau the scaling factor of the Householder transformation
+ * \param workspace a pointer to working space with at least
+ * this->cols() * essential.size() entries
+ *
+ * \sa MatrixBase::makeHouseholder(), MatrixBase::makeHouseholderInPlace(),
+ * MatrixBase::applyHouseholderOnTheLeft()
+ */
template<typename Derived>
template<typename EssentialPart>
void MatrixBase<Derived>::applyHouseholderOnTheRight(
@@ -130,4 +163,6 @@ void MatrixBase<Derived>::applyHouseholderOnTheRight(
}
}
+} // end namespace Eigen
+
#endif // EIGEN_HOUSEHOLDER_H
diff --git a/extern/Eigen3/Eigen/src/Householder/HouseholderSequence.h b/extern/Eigen3/Eigen/src/Householder/HouseholderSequence.h
index 717f29c99e9..1e71e16a785 100644
--- a/extern/Eigen3/Eigen/src/Householder/HouseholderSequence.h
+++ b/extern/Eigen3/Eigen/src/Householder/HouseholderSequence.h
@@ -4,28 +4,15 @@
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_HOUSEHOLDER_SEQUENCE_H
#define EIGEN_HOUSEHOLDER_SEQUENCE_H
+namespace Eigen {
+
/** \ingroup Householder_Module
* \householder_module
* \class HouseholderSequence
@@ -237,13 +224,20 @@ template<typename VectorsType, typename CoeffsType, int Side> class HouseholderS
ConjugateReturnType inverse() const { return adjoint(); }
/** \internal */
- template<typename DestType> void evalTo(DestType& dst) const
+ template<typename DestType> inline void evalTo(DestType& dst) const
{
- Index vecs = m_length;
- // FIXME find a way to pass this temporary if the user wants to
Matrix<Scalar, DestType::RowsAtCompileTime, 1,
- AutoAlign|ColMajor, DestType::MaxRowsAtCompileTime, 1> temp(rows());
- if( internal::is_same<typename internal::remove_all<VectorsType>::type,DestType>::value
+ AutoAlign|ColMajor, DestType::MaxRowsAtCompileTime, 1> workspace(rows());
+ evalTo(dst, workspace);
+ }
+
+ /** \internal */
+ template<typename Dest, typename Workspace>
+ void evalTo(Dest& dst, Workspace& workspace) const
+ {
+ workspace.resize(rows());
+ Index vecs = m_length;
+ if( internal::is_same<typename internal::remove_all<VectorsType>::type,Dest>::value
&& internal::extract_data(dst) == internal::extract_data(m_vectors))
{
// in-place
@@ -254,10 +248,10 @@ template<typename VectorsType, typename CoeffsType, int Side> class HouseholderS
Index cornerSize = rows() - k - m_shift;
if(m_trans)
dst.bottomRightCorner(cornerSize, cornerSize)
- .applyHouseholderOnTheRight(essentialVector(k), m_coeffs.coeff(k), &temp.coeffRef(0));
+ .applyHouseholderOnTheRight(essentialVector(k), m_coeffs.coeff(k), workspace.data());
else
dst.bottomRightCorner(cornerSize, cornerSize)
- .applyHouseholderOnTheLeft(essentialVector(k), m_coeffs.coeff(k), &temp.coeffRef(0));
+ .applyHouseholderOnTheLeft(essentialVector(k), m_coeffs.coeff(k), workspace.data());
// clear the off diagonal vector
dst.col(k).tail(rows()-k-1).setZero();
@@ -274,10 +268,10 @@ template<typename VectorsType, typename CoeffsType, int Side> class HouseholderS
Index cornerSize = rows() - k - m_shift;
if(m_trans)
dst.bottomRightCorner(cornerSize, cornerSize)
- .applyHouseholderOnTheRight(essentialVector(k), m_coeffs.coeff(k), &temp.coeffRef(0));
+ .applyHouseholderOnTheRight(essentialVector(k), m_coeffs.coeff(k), &workspace.coeffRef(0));
else
dst.bottomRightCorner(cornerSize, cornerSize)
- .applyHouseholderOnTheLeft(essentialVector(k), m_coeffs.coeff(k), &temp.coeffRef(0));
+ .applyHouseholderOnTheLeft(essentialVector(k), m_coeffs.coeff(k), &workspace.coeffRef(0));
}
}
}
@@ -285,24 +279,40 @@ template<typename VectorsType, typename CoeffsType, int Side> class HouseholderS
/** \internal */
template<typename Dest> inline void applyThisOnTheRight(Dest& dst) const
{
- Matrix<Scalar,1,Dest::RowsAtCompileTime> temp(dst.rows());
+ Matrix<Scalar,1,Dest::RowsAtCompileTime,RowMajor,1,Dest::MaxRowsAtCompileTime> workspace(dst.rows());
+ applyThisOnTheRight(dst, workspace);
+ }
+
+ /** \internal */
+ template<typename Dest, typename Workspace>
+ inline void applyThisOnTheRight(Dest& dst, Workspace& workspace) const
+ {
+ workspace.resize(dst.rows());
for(Index k = 0; k < m_length; ++k)
{
Index actual_k = m_trans ? m_length-k-1 : k;
dst.rightCols(rows()-m_shift-actual_k)
- .applyHouseholderOnTheRight(essentialVector(actual_k), m_coeffs.coeff(actual_k), &temp.coeffRef(0));
+ .applyHouseholderOnTheRight(essentialVector(actual_k), m_coeffs.coeff(actual_k), workspace.data());
}
}
/** \internal */
template<typename Dest> inline void applyThisOnTheLeft(Dest& dst) const
{
- Matrix<Scalar,1,Dest::ColsAtCompileTime> temp(dst.cols());
+ Matrix<Scalar,1,Dest::ColsAtCompileTime,RowMajor,1,Dest::MaxColsAtCompileTime> workspace(dst.cols());
+ applyThisOnTheLeft(dst, workspace);
+ }
+
+ /** \internal */
+ template<typename Dest, typename Workspace>
+ inline void applyThisOnTheLeft(Dest& dst, Workspace& workspace) const
+ {
+ workspace.resize(dst.cols());
for(Index k = 0; k < m_length; ++k)
{
Index actual_k = m_trans ? k : m_length-k-1;
dst.bottomRows(rows()-m_shift-actual_k)
- .applyHouseholderOnTheLeft(essentialVector(actual_k), m_coeffs.coeff(actual_k), &temp.coeffRef(0));
+ .applyHouseholderOnTheLeft(essentialVector(actual_k), m_coeffs.coeff(actual_k), workspace.data());
}
}
@@ -426,4 +436,6 @@ HouseholderSequence<VectorsType,CoeffsType,OnTheRight> rightHouseholderSequence(
return HouseholderSequence<VectorsType,CoeffsType,OnTheRight>(v, h);
}
+} // end namespace Eigen
+
#endif // EIGEN_HOUSEHOLDER_SEQUENCE_H
diff --git a/extern/Eigen3/Eigen/src/IterativeLinearSolvers/BasicPreconditioners.h b/extern/Eigen3/Eigen/src/IterativeLinearSolvers/BasicPreconditioners.h
new file mode 100644
index 00000000000..73ca9bfde6a
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/IterativeLinearSolvers/BasicPreconditioners.h
@@ -0,0 +1,149 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_BASIC_PRECONDITIONERS_H
+#define EIGEN_BASIC_PRECONDITIONERS_H
+
+namespace Eigen {
+
+/** \ingroup IterativeLinearSolvers_Module
+ * \brief A preconditioner based on the digonal entries
+ *
+ * This class allows to approximately solve for A.x = b problems assuming A is a diagonal matrix.
+ * In other words, this preconditioner neglects all off diagonal entries and, in Eigen's language, solves for:
+ * \code
+ * A.diagonal().asDiagonal() . x = b
+ * \endcode
+ *
+ * \tparam _Scalar the type of the scalar.
+ *
+ * This preconditioner is suitable for both selfadjoint and general problems.
+ * The diagonal entries are pre-inverted and stored into a dense vector.
+ *
+ * \note A variant that has yet to be implemented would attempt to preserve the norm of each column.
+ *
+ */
+template <typename _Scalar>
+class DiagonalPreconditioner
+{
+ typedef _Scalar Scalar;
+ typedef Matrix<Scalar,Dynamic,1> Vector;
+ typedef typename Vector::Index Index;
+
+ public:
+ // this typedef is only to export the scalar type and compile-time dimensions to solve_retval
+ typedef Matrix<Scalar,Dynamic,Dynamic> MatrixType;
+
+ DiagonalPreconditioner() : m_isInitialized(false) {}
+
+ template<typename MatType>
+ DiagonalPreconditioner(const MatType& mat) : m_invdiag(mat.cols())
+ {
+ compute(mat);
+ }
+
+ Index rows() const { return m_invdiag.size(); }
+ Index cols() const { return m_invdiag.size(); }
+
+ template<typename MatType>
+ DiagonalPreconditioner& analyzePattern(const MatType& )
+ {
+ return *this;
+ }
+
+ template<typename MatType>
+ DiagonalPreconditioner& factorize(const MatType& mat)
+ {
+ m_invdiag.resize(mat.cols());
+ for(int j=0; j<mat.outerSize(); ++j)
+ {
+ typename MatType::InnerIterator it(mat,j);
+ while(it && it.index()!=j) ++it;
+ if(it && it.index()==j)
+ m_invdiag(j) = Scalar(1)/it.value();
+ else
+ m_invdiag(j) = 0;
+ }
+ m_isInitialized = true;
+ return *this;
+ }
+
+ template<typename MatType>
+ DiagonalPreconditioner& compute(const MatType& mat)
+ {
+ return factorize(mat);
+ }
+
+ template<typename Rhs, typename Dest>
+ void _solve(const Rhs& b, Dest& x) const
+ {
+ x = m_invdiag.array() * b.array() ;
+ }
+
+ template<typename Rhs> inline const internal::solve_retval<DiagonalPreconditioner, Rhs>
+ solve(const MatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "DiagonalPreconditioner is not initialized.");
+ eigen_assert(m_invdiag.size()==b.rows()
+ && "DiagonalPreconditioner::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::solve_retval<DiagonalPreconditioner, Rhs>(*this, b.derived());
+ }
+
+ protected:
+ Vector m_invdiag;
+ bool m_isInitialized;
+};
+
+namespace internal {
+
+template<typename _MatrixType, typename Rhs>
+struct solve_retval<DiagonalPreconditioner<_MatrixType>, Rhs>
+ : solve_retval_base<DiagonalPreconditioner<_MatrixType>, Rhs>
+{
+ typedef DiagonalPreconditioner<_MatrixType> Dec;
+ EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec()._solve(rhs(),dst);
+ }
+};
+
+}
+
+/** \ingroup IterativeLinearSolvers_Module
+ * \brief A naive preconditioner which approximates any matrix as the identity matrix
+ *
+ * \sa class DiagonalPreconditioner
+ */
+class IdentityPreconditioner
+{
+ public:
+
+ IdentityPreconditioner() {}
+
+ template<typename MatrixType>
+ IdentityPreconditioner(const MatrixType& ) {}
+
+ template<typename MatrixType>
+ IdentityPreconditioner& analyzePattern(const MatrixType& ) { return *this; }
+
+ template<typename MatrixType>
+ IdentityPreconditioner& factorize(const MatrixType& ) { return *this; }
+
+ template<typename MatrixType>
+ IdentityPreconditioner& compute(const MatrixType& ) { return *this; }
+
+ template<typename Rhs>
+ inline const Rhs& solve(const Rhs& b) const { return b; }
+};
+
+} // end namespace Eigen
+
+#endif // EIGEN_BASIC_PRECONDITIONERS_H
diff --git a/extern/Eigen3/Eigen/src/IterativeLinearSolvers/BiCGSTAB.h b/extern/Eigen3/Eigen/src/IterativeLinearSolvers/BiCGSTAB.h
new file mode 100644
index 00000000000..126341be8d8
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/IterativeLinearSolvers/BiCGSTAB.h
@@ -0,0 +1,254 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr>
+// Copyright (C) 2012 Désiré Nuentsa-Wakam <desire.nuentsa_wakam@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_BICGSTAB_H
+#define EIGEN_BICGSTAB_H
+
+namespace Eigen {
+
+namespace internal {
+
+/** \internal Low-level bi conjugate gradient stabilized algorithm
+ * \param mat The matrix A
+ * \param rhs The right hand side vector b
+ * \param x On input and initial solution, on output the computed solution.
+ * \param precond A preconditioner being able to efficiently solve for an
+ * approximation of Ax=b (regardless of b)
+ * \param iters On input the max number of iteration, on output the number of performed iterations.
+ * \param tol_error On input the tolerance error, on output an estimation of the relative error.
+ * \return false in the case of numerical issue, for example a break down of BiCGSTAB.
+ */
+template<typename MatrixType, typename Rhs, typename Dest, typename Preconditioner>
+bool bicgstab(const MatrixType& mat, const Rhs& rhs, Dest& x,
+ const Preconditioner& precond, int& iters,
+ typename Dest::RealScalar& tol_error)
+{
+ using std::sqrt;
+ using std::abs;
+ typedef typename Dest::RealScalar RealScalar;
+ typedef typename Dest::Scalar Scalar;
+ typedef Matrix<Scalar,Dynamic,1> VectorType;
+ RealScalar tol = tol_error;
+ int maxIters = iters;
+
+ int n = mat.cols();
+ VectorType r = rhs - mat * x;
+ VectorType r0 = r;
+
+ RealScalar r0_sqnorm = r0.squaredNorm();
+ Scalar rho = 1;
+ Scalar alpha = 1;
+ Scalar w = 1;
+
+ VectorType v = VectorType::Zero(n), p = VectorType::Zero(n);
+ VectorType y(n), z(n);
+ VectorType kt(n), ks(n);
+
+ VectorType s(n), t(n);
+
+ RealScalar tol2 = tol*tol;
+ int i = 0;
+
+ while ( r.squaredNorm()/r0_sqnorm > tol2 && i<maxIters )
+ {
+ Scalar rho_old = rho;
+
+ rho = r0.dot(r);
+ if (rho == Scalar(0)) return false; /* New search directions cannot be found */
+ Scalar beta = (rho/rho_old) * (alpha / w);
+ p = r + beta * (p - w * v);
+
+ y = precond.solve(p);
+
+ v.noalias() = mat * y;
+
+ alpha = rho / r0.dot(v);
+ s = r - alpha * v;
+
+ z = precond.solve(s);
+ t.noalias() = mat * z;
+
+ w = t.dot(s) / t.squaredNorm();
+ x += alpha * y + w * z;
+ r = s - w * t;
+ ++i;
+ }
+ tol_error = sqrt(r.squaredNorm()/r0_sqnorm);
+ iters = i;
+ return true;
+}
+
+}
+
+template< typename _MatrixType,
+ typename _Preconditioner = DiagonalPreconditioner<typename _MatrixType::Scalar> >
+class BiCGSTAB;
+
+namespace internal {
+
+template< typename _MatrixType, typename _Preconditioner>
+struct traits<BiCGSTAB<_MatrixType,_Preconditioner> >
+{
+ typedef _MatrixType MatrixType;
+ typedef _Preconditioner Preconditioner;
+};
+
+}
+
+/** \ingroup IterativeLinearSolvers_Module
+ * \brief A bi conjugate gradient stabilized solver for sparse square problems
+ *
+ * This class allows to solve for A.x = b sparse linear problems using a bi conjugate gradient
+ * stabilized algorithm. The vectors x and b can be either dense or sparse.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, can be a dense or a sparse matrix.
+ * \tparam _Preconditioner the type of the preconditioner. Default is DiagonalPreconditioner
+ *
+ * The maximal number of iterations and tolerance value can be controlled via the setMaxIterations()
+ * and setTolerance() methods. The defaults are the size of the problem for the maximal number of iterations
+ * and NumTraits<Scalar>::epsilon() for the tolerance.
+ *
+ * This class can be used as the direct solver classes. Here is a typical usage example:
+ * \code
+ * int n = 10000;
+ * VectorXd x(n), b(n);
+ * SparseMatrix<double> A(n,n);
+ * // fill A and b
+ * BiCGSTAB<SparseMatrix<double> > solver;
+ * solver(A);
+ * x = solver.solve(b);
+ * std::cout << "#iterations: " << solver.iterations() << std::endl;
+ * std::cout << "estimated error: " << solver.error() << std::endl;
+ * // update b, and solve again
+ * x = solver.solve(b);
+ * \endcode
+ *
+ * By default the iterations start with x=0 as an initial guess of the solution.
+ * One can control the start using the solveWithGuess() method. Here is a step by
+ * step execution example starting with a random guess and printing the evolution
+ * of the estimated error:
+ * * \code
+ * x = VectorXd::Random(n);
+ * solver.setMaxIterations(1);
+ * int i = 0;
+ * do {
+ * x = solver.solveWithGuess(b,x);
+ * std::cout << i << " : " << solver.error() << std::endl;
+ * ++i;
+ * } while (solver.info()!=Success && i<100);
+ * \endcode
+ * Note that such a step by step excution is slightly slower.
+ *
+ * \sa class SimplicialCholesky, DiagonalPreconditioner, IdentityPreconditioner
+ */
+template< typename _MatrixType, typename _Preconditioner>
+class BiCGSTAB : public IterativeSolverBase<BiCGSTAB<_MatrixType,_Preconditioner> >
+{
+ typedef IterativeSolverBase<BiCGSTAB> Base;
+ using Base::mp_matrix;
+ using Base::m_error;
+ using Base::m_iterations;
+ using Base::m_info;
+ using Base::m_isInitialized;
+public:
+ typedef _MatrixType MatrixType;
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::Index Index;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef _Preconditioner Preconditioner;
+
+public:
+
+ /** Default constructor. */
+ BiCGSTAB() : Base() {}
+
+ /** Initialize the solver with matrix \a A for further \c Ax=b solving.
+ *
+ * This constructor is a shortcut for the default constructor followed
+ * by a call to compute().
+ *
+ * \warning this class stores a reference to the matrix A as well as some
+ * precomputed values that depend on it. Therefore, if \a A is changed
+ * this class becomes invalid. Call compute() to update it with the new
+ * matrix A, or modify a copy of A.
+ */
+ BiCGSTAB(const MatrixType& A) : Base(A) {}
+
+ ~BiCGSTAB() {}
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A
+ * \a x0 as an initial solution.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs,typename Guess>
+ inline const internal::solve_retval_with_guess<BiCGSTAB, Rhs, Guess>
+ solveWithGuess(const MatrixBase<Rhs>& b, const Guess& x0) const
+ {
+ eigen_assert(m_isInitialized && "BiCGSTAB is not initialized.");
+ eigen_assert(Base::rows()==b.rows()
+ && "BiCGSTAB::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::solve_retval_with_guess
+ <BiCGSTAB, Rhs, Guess>(*this, b.derived(), x0);
+ }
+
+ /** \internal */
+ template<typename Rhs,typename Dest>
+ void _solveWithGuess(const Rhs& b, Dest& x) const
+ {
+ bool failed = false;
+ for(int j=0; j<b.cols(); ++j)
+ {
+ m_iterations = Base::maxIterations();
+ m_error = Base::m_tolerance;
+
+ typename Dest::ColXpr xj(x,j);
+ if(!internal::bicgstab(*mp_matrix, b.col(j), xj, Base::m_preconditioner, m_iterations, m_error))
+ failed = true;
+ }
+ m_info = failed ? NumericalIssue
+ : m_error <= Base::m_tolerance ? Success
+ : NoConvergence;
+ m_isInitialized = true;
+ }
+
+ /** \internal */
+ template<typename Rhs,typename Dest>
+ void _solve(const Rhs& b, Dest& x) const
+ {
+ x.setZero();
+ _solveWithGuess(b,x);
+ }
+
+protected:
+
+};
+
+
+namespace internal {
+
+ template<typename _MatrixType, typename _Preconditioner, typename Rhs>
+struct solve_retval<BiCGSTAB<_MatrixType, _Preconditioner>, Rhs>
+ : solve_retval_base<BiCGSTAB<_MatrixType, _Preconditioner>, Rhs>
+{
+ typedef BiCGSTAB<_MatrixType, _Preconditioner> Dec;
+ EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec()._solve(rhs(),dst);
+ }
+};
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_BICGSTAB_H
diff --git a/extern/Eigen3/Eigen/src/IterativeLinearSolvers/ConjugateGradient.h b/extern/Eigen3/Eigen/src/IterativeLinearSolvers/ConjugateGradient.h
new file mode 100644
index 00000000000..f64f2534d28
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/IterativeLinearSolvers/ConjugateGradient.h
@@ -0,0 +1,251 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_CONJUGATE_GRADIENT_H
+#define EIGEN_CONJUGATE_GRADIENT_H
+
+namespace Eigen {
+
+namespace internal {
+
+/** \internal Low-level conjugate gradient algorithm
+ * \param mat The matrix A
+ * \param rhs The right hand side vector b
+ * \param x On input and initial solution, on output the computed solution.
+ * \param precond A preconditioner being able to efficiently solve for an
+ * approximation of Ax=b (regardless of b)
+ * \param iters On input the max number of iteration, on output the number of performed iterations.
+ * \param tol_error On input the tolerance error, on output an estimation of the relative error.
+ */
+template<typename MatrixType, typename Rhs, typename Dest, typename Preconditioner>
+EIGEN_DONT_INLINE
+void conjugate_gradient(const MatrixType& mat, const Rhs& rhs, Dest& x,
+ const Preconditioner& precond, int& iters,
+ typename Dest::RealScalar& tol_error)
+{
+ using std::sqrt;
+ using std::abs;
+ typedef typename Dest::RealScalar RealScalar;
+ typedef typename Dest::Scalar Scalar;
+ typedef Matrix<Scalar,Dynamic,1> VectorType;
+
+ RealScalar tol = tol_error;
+ int maxIters = iters;
+
+ int n = mat.cols();
+
+ VectorType residual = rhs - mat * x; //initial residual
+ VectorType p(n);
+
+ p = precond.solve(residual); //initial search direction
+
+ VectorType z(n), tmp(n);
+ RealScalar absNew = internal::real(residual.dot(p)); // the square of the absolute value of r scaled by invM
+ RealScalar rhsNorm2 = rhs.squaredNorm();
+ RealScalar residualNorm2 = 0;
+ RealScalar threshold = tol*tol*rhsNorm2;
+ int i = 0;
+ while(i < maxIters)
+ {
+ tmp.noalias() = mat * p; // the bottleneck of the algorithm
+
+ Scalar alpha = absNew / p.dot(tmp); // the amount we travel on dir
+ x += alpha * p; // update solution
+ residual -= alpha * tmp; // update residue
+
+ residualNorm2 = residual.squaredNorm();
+ if(residualNorm2 < threshold)
+ break;
+
+ z = precond.solve(residual); // approximately solve for "A z = residual"
+
+ RealScalar absOld = absNew;
+ absNew = internal::real(residual.dot(z)); // update the absolute value of r
+ RealScalar beta = absNew / absOld; // calculate the Gram-Schmidt value used to create the new search direction
+ p = z + beta * p; // update search direction
+ i++;
+ }
+ tol_error = sqrt(residualNorm2 / rhsNorm2);
+ iters = i;
+}
+
+}
+
+template< typename _MatrixType, int _UpLo=Lower,
+ typename _Preconditioner = DiagonalPreconditioner<typename _MatrixType::Scalar> >
+class ConjugateGradient;
+
+namespace internal {
+
+template< typename _MatrixType, int _UpLo, typename _Preconditioner>
+struct traits<ConjugateGradient<_MatrixType,_UpLo,_Preconditioner> >
+{
+ typedef _MatrixType MatrixType;
+ typedef _Preconditioner Preconditioner;
+};
+
+}
+
+/** \ingroup IterativeLinearSolvers_Module
+ * \brief A conjugate gradient solver for sparse self-adjoint problems
+ *
+ * This class allows to solve for A.x = b sparse linear problems using a conjugate gradient algorithm.
+ * The sparse matrix A must be selfadjoint. The vectors x and b can be either dense or sparse.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, can be a dense or a sparse matrix.
+ * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower
+ * or Upper. Default is Lower.
+ * \tparam _Preconditioner the type of the preconditioner. Default is DiagonalPreconditioner
+ *
+ * The maximal number of iterations and tolerance value can be controlled via the setMaxIterations()
+ * and setTolerance() methods. The defaults are the size of the problem for the maximal number of iterations
+ * and NumTraits<Scalar>::epsilon() for the tolerance.
+ *
+ * This class can be used as the direct solver classes. Here is a typical usage example:
+ * \code
+ * int n = 10000;
+ * VectorXd x(n), b(n);
+ * SparseMatrix<double> A(n,n);
+ * // fill A and b
+ * ConjugateGradient<SparseMatrix<double> > cg;
+ * cg.compute(A);
+ * x = cg.solve(b);
+ * std::cout << "#iterations: " << cg.iterations() << std::endl;
+ * std::cout << "estimated error: " << cg.error() << std::endl;
+ * // update b, and solve again
+ * x = cg.solve(b);
+ * \endcode
+ *
+ * By default the iterations start with x=0 as an initial guess of the solution.
+ * One can control the start using the solveWithGuess() method. Here is a step by
+ * step execution example starting with a random guess and printing the evolution
+ * of the estimated error:
+ * * \code
+ * x = VectorXd::Random(n);
+ * cg.setMaxIterations(1);
+ * int i = 0;
+ * do {
+ * x = cg.solveWithGuess(b,x);
+ * std::cout << i << " : " << cg.error() << std::endl;
+ * ++i;
+ * } while (cg.info()!=Success && i<100);
+ * \endcode
+ * Note that such a step by step excution is slightly slower.
+ *
+ * \sa class SimplicialCholesky, DiagonalPreconditioner, IdentityPreconditioner
+ */
+template< typename _MatrixType, int _UpLo, typename _Preconditioner>
+class ConjugateGradient : public IterativeSolverBase<ConjugateGradient<_MatrixType,_UpLo,_Preconditioner> >
+{
+ typedef IterativeSolverBase<ConjugateGradient> Base;
+ using Base::mp_matrix;
+ using Base::m_error;
+ using Base::m_iterations;
+ using Base::m_info;
+ using Base::m_isInitialized;
+public:
+ typedef _MatrixType MatrixType;
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::Index Index;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef _Preconditioner Preconditioner;
+
+ enum {
+ UpLo = _UpLo
+ };
+
+public:
+
+ /** Default constructor. */
+ ConjugateGradient() : Base() {}
+
+ /** Initialize the solver with matrix \a A for further \c Ax=b solving.
+ *
+ * This constructor is a shortcut for the default constructor followed
+ * by a call to compute().
+ *
+ * \warning this class stores a reference to the matrix A as well as some
+ * precomputed values that depend on it. Therefore, if \a A is changed
+ * this class becomes invalid. Call compute() to update it with the new
+ * matrix A, or modify a copy of A.
+ */
+ ConjugateGradient(const MatrixType& A) : Base(A) {}
+
+ ~ConjugateGradient() {}
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A
+ * \a x0 as an initial solution.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs,typename Guess>
+ inline const internal::solve_retval_with_guess<ConjugateGradient, Rhs, Guess>
+ solveWithGuess(const MatrixBase<Rhs>& b, const Guess& x0) const
+ {
+ eigen_assert(m_isInitialized && "ConjugateGradient is not initialized.");
+ eigen_assert(Base::rows()==b.rows()
+ && "ConjugateGradient::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::solve_retval_with_guess
+ <ConjugateGradient, Rhs, Guess>(*this, b.derived(), x0);
+ }
+
+ /** \internal */
+ template<typename Rhs,typename Dest>
+ void _solveWithGuess(const Rhs& b, Dest& x) const
+ {
+ m_iterations = Base::maxIterations();
+ m_error = Base::m_tolerance;
+
+ for(int j=0; j<b.cols(); ++j)
+ {
+ m_iterations = Base::maxIterations();
+ m_error = Base::m_tolerance;
+
+ typename Dest::ColXpr xj(x,j);
+ internal::conjugate_gradient(mp_matrix->template selfadjointView<UpLo>(), b.col(j), xj,
+ Base::m_preconditioner, m_iterations, m_error);
+ }
+
+ m_isInitialized = true;
+ m_info = m_error <= Base::m_tolerance ? Success : NoConvergence;
+ }
+
+ /** \internal */
+ template<typename Rhs,typename Dest>
+ void _solve(const Rhs& b, Dest& x) const
+ {
+ x.setOnes();
+ _solveWithGuess(b,x);
+ }
+
+protected:
+
+};
+
+
+namespace internal {
+
+template<typename _MatrixType, int _UpLo, typename _Preconditioner, typename Rhs>
+struct solve_retval<ConjugateGradient<_MatrixType,_UpLo,_Preconditioner>, Rhs>
+ : solve_retval_base<ConjugateGradient<_MatrixType,_UpLo,_Preconditioner>, Rhs>
+{
+ typedef ConjugateGradient<_MatrixType,_UpLo,_Preconditioner> Dec;
+ EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec()._solve(rhs(),dst);
+ }
+};
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_CONJUGATE_GRADIENT_H
diff --git a/extern/Eigen3/Eigen/src/IterativeLinearSolvers/IncompleteLUT.h b/extern/Eigen3/Eigen/src/IterativeLinearSolvers/IncompleteLUT.h
new file mode 100644
index 00000000000..224304f0eb8
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/IterativeLinearSolvers/IncompleteLUT.h
@@ -0,0 +1,466 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2012 Désiré Nuentsa-Wakam <desire.nuentsa_wakam@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_INCOMPLETE_LUT_H
+#define EIGEN_INCOMPLETE_LUT_H
+
+namespace Eigen {
+
+/**
+ * \brief Incomplete LU factorization with dual-threshold strategy
+ * During the numerical factorization, two dropping rules are used :
+ * 1) any element whose magnitude is less than some tolerance is dropped.
+ * This tolerance is obtained by multiplying the input tolerance @p droptol
+ * by the average magnitude of all the original elements in the current row.
+ * 2) After the elimination of the row, only the @p fill largest elements in
+ * the L part and the @p fill largest elements in the U part are kept
+ * (in addition to the diagonal element ). Note that @p fill is computed from
+ * the input parameter @p fillfactor which is used the ratio to control the fill_in
+ * relatively to the initial number of nonzero elements.
+ *
+ * The two extreme cases are when @p droptol=0 (to keep all the @p fill*2 largest elements)
+ * and when @p fill=n/2 with @p droptol being different to zero.
+ *
+ * References : Yousef Saad, ILUT: A dual threshold incomplete LU factorization,
+ * Numerical Linear Algebra with Applications, 1(4), pp 387-402, 1994.
+ *
+ * NOTE : The following implementation is derived from the ILUT implementation
+ * in the SPARSKIT package, Copyright (C) 2005, the Regents of the University of Minnesota
+ * released under the terms of the GNU LGPL:
+ * http://www-users.cs.umn.edu/~saad/software/SPARSKIT/README
+ * However, Yousef Saad gave us permission to relicense his ILUT code to MPL2.
+ * See the Eigen mailing list archive, thread: ILUT, date: July 8, 2012:
+ * http://listengine.tuxfamily.org/lists.tuxfamily.org/eigen/2012/07/msg00064.html
+ * alternatively, on GMANE:
+ * http://comments.gmane.org/gmane.comp.lib.eigen/3302
+ */
+template <typename _Scalar>
+class IncompleteLUT : internal::noncopyable
+{
+ typedef _Scalar Scalar;
+ typedef typename NumTraits<Scalar>::Real RealScalar;
+ typedef Matrix<Scalar,Dynamic,1> Vector;
+ typedef SparseMatrix<Scalar,RowMajor> FactorType;
+ typedef SparseMatrix<Scalar,ColMajor> PermutType;
+ typedef typename FactorType::Index Index;
+
+ public:
+ typedef Matrix<Scalar,Dynamic,Dynamic> MatrixType;
+
+ IncompleteLUT()
+ : m_droptol(NumTraits<Scalar>::dummy_precision()), m_fillfactor(10),
+ m_analysisIsOk(false), m_factorizationIsOk(false), m_isInitialized(false)
+ {}
+
+ template<typename MatrixType>
+ IncompleteLUT(const MatrixType& mat, RealScalar droptol=NumTraits<Scalar>::dummy_precision(), int fillfactor = 10)
+ : m_droptol(droptol),m_fillfactor(fillfactor),
+ m_analysisIsOk(false),m_factorizationIsOk(false),m_isInitialized(false)
+ {
+ eigen_assert(fillfactor != 0);
+ compute(mat);
+ }
+
+ Index rows() const { return m_lu.rows(); }
+
+ Index cols() const { return m_lu.cols(); }
+
+ /** \brief Reports whether previous computation was successful.
+ *
+ * \returns \c Success if computation was succesful,
+ * \c NumericalIssue if the matrix.appears to be negative.
+ */
+ ComputationInfo info() const
+ {
+ eigen_assert(m_isInitialized && "IncompleteLUT is not initialized.");
+ return m_info;
+ }
+
+ template<typename MatrixType>
+ void analyzePattern(const MatrixType& amat);
+
+ template<typename MatrixType>
+ void factorize(const MatrixType& amat);
+
+ /**
+ * Compute an incomplete LU factorization with dual threshold on the matrix mat
+ * No pivoting is done in this version
+ *
+ **/
+ template<typename MatrixType>
+ IncompleteLUT<Scalar>& compute(const MatrixType& amat)
+ {
+ analyzePattern(amat);
+ factorize(amat);
+ eigen_assert(m_factorizationIsOk == true);
+ m_isInitialized = true;
+ return *this;
+ }
+
+ void setDroptol(RealScalar droptol);
+ void setFillfactor(int fillfactor);
+
+ template<typename Rhs, typename Dest>
+ void _solve(const Rhs& b, Dest& x) const
+ {
+ x = m_Pinv * b;
+ x = m_lu.template triangularView<UnitLower>().solve(x);
+ x = m_lu.template triangularView<Upper>().solve(x);
+ x = m_P * x;
+ }
+
+ template<typename Rhs> inline const internal::solve_retval<IncompleteLUT, Rhs>
+ solve(const MatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "IncompleteLUT is not initialized.");
+ eigen_assert(cols()==b.rows()
+ && "IncompleteLUT::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::solve_retval<IncompleteLUT, Rhs>(*this, b.derived());
+ }
+
+protected:
+
+ template <typename VectorV, typename VectorI>
+ int QuickSplit(VectorV &row, VectorI &ind, int ncut);
+
+
+ /** keeps off-diagonal entries; drops diagonal entries */
+ struct keep_diag {
+ inline bool operator() (const Index& row, const Index& col, const Scalar&) const
+ {
+ return row!=col;
+ }
+ };
+
+protected:
+
+ FactorType m_lu;
+ RealScalar m_droptol;
+ int m_fillfactor;
+ bool m_analysisIsOk;
+ bool m_factorizationIsOk;
+ bool m_isInitialized;
+ ComputationInfo m_info;
+ PermutationMatrix<Dynamic,Dynamic,Index> m_P; // Fill-reducing permutation
+ PermutationMatrix<Dynamic,Dynamic,Index> m_Pinv; // Inverse permutation
+};
+
+/**
+ * Set control parameter droptol
+ * \param droptol Drop any element whose magnitude is less than this tolerance
+ **/
+template<typename Scalar>
+void IncompleteLUT<Scalar>::setDroptol(RealScalar droptol)
+{
+ this->m_droptol = droptol;
+}
+
+/**
+ * Set control parameter fillfactor
+ * \param fillfactor This is used to compute the number @p fill_in of largest elements to keep on each row.
+ **/
+template<typename Scalar>
+void IncompleteLUT<Scalar>::setFillfactor(int fillfactor)
+{
+ this->m_fillfactor = fillfactor;
+}
+
+
+/**
+ * Compute a quick-sort split of a vector
+ * On output, the vector row is permuted such that its elements satisfy
+ * abs(row(i)) >= abs(row(ncut)) if i<ncut
+ * abs(row(i)) <= abs(row(ncut)) if i>ncut
+ * \param row The vector of values
+ * \param ind The array of index for the elements in @p row
+ * \param ncut The number of largest elements to keep
+ **/
+template <typename Scalar>
+template <typename VectorV, typename VectorI>
+int IncompleteLUT<Scalar>::QuickSplit(VectorV &row, VectorI &ind, int ncut)
+{
+ using std::swap;
+ int mid;
+ int n = row.size(); /* length of the vector */
+ int first, last ;
+
+ ncut--; /* to fit the zero-based indices */
+ first = 0;
+ last = n-1;
+ if (ncut < first || ncut > last ) return 0;
+
+ do {
+ mid = first;
+ RealScalar abskey = std::abs(row(mid));
+ for (int j = first + 1; j <= last; j++) {
+ if ( std::abs(row(j)) > abskey) {
+ ++mid;
+ swap(row(mid), row(j));
+ swap(ind(mid), ind(j));
+ }
+ }
+ /* Interchange for the pivot element */
+ swap(row(mid), row(first));
+ swap(ind(mid), ind(first));
+
+ if (mid > ncut) last = mid - 1;
+ else if (mid < ncut ) first = mid + 1;
+ } while (mid != ncut );
+
+ return 0; /* mid is equal to ncut */
+}
+
+template <typename Scalar>
+template<typename _MatrixType>
+void IncompleteLUT<Scalar>::analyzePattern(const _MatrixType& amat)
+{
+ // Compute the Fill-reducing permutation
+ SparseMatrix<Scalar,ColMajor, Index> mat1 = amat;
+ SparseMatrix<Scalar,ColMajor, Index> mat2 = amat.transpose();
+ // Symmetrize the pattern
+ // FIXME for a matrix with nearly symmetric pattern, mat2+mat1 is the appropriate choice.
+ // on the other hand for a really non-symmetric pattern, mat2*mat1 should be prefered...
+ SparseMatrix<Scalar,ColMajor, Index> AtA = mat2 + mat1;
+ AtA.prune(keep_diag());
+ internal::minimum_degree_ordering<Scalar, Index>(AtA, m_P); // Then compute the AMD ordering...
+
+ m_Pinv = m_P.inverse(); // ... and the inverse permutation
+
+ m_analysisIsOk = true;
+}
+
+template <typename Scalar>
+template<typename _MatrixType>
+void IncompleteLUT<Scalar>::factorize(const _MatrixType& amat)
+{
+ using std::sqrt;
+ using std::swap;
+ using std::abs;
+
+ eigen_assert((amat.rows() == amat.cols()) && "The factorization should be done on a square matrix");
+ int n = amat.cols(); // Size of the matrix
+ m_lu.resize(n,n);
+ // Declare Working vectors and variables
+ Vector u(n) ; // real values of the row -- maximum size is n --
+ VectorXi ju(n); // column position of the values in u -- maximum size is n
+ VectorXi jr(n); // Indicate the position of the nonzero elements in the vector u -- A zero location is indicated by -1
+
+ // Apply the fill-reducing permutation
+ eigen_assert(m_analysisIsOk && "You must first call analyzePattern()");
+ SparseMatrix<Scalar,RowMajor, Index> mat;
+ mat = amat.twistedBy(m_Pinv);
+
+ // Initialization
+ jr.fill(-1);
+ ju.fill(0);
+ u.fill(0);
+
+ // number of largest elements to keep in each row:
+ int fill_in = static_cast<int> (amat.nonZeros()*m_fillfactor)/n+1;
+ if (fill_in > n) fill_in = n;
+
+ // number of largest nonzero elements to keep in the L and the U part of the current row:
+ int nnzL = fill_in/2;
+ int nnzU = nnzL;
+ m_lu.reserve(n * (nnzL + nnzU + 1));
+
+ // global loop over the rows of the sparse matrix
+ for (int ii = 0; ii < n; ii++)
+ {
+ // 1 - copy the lower and the upper part of the row i of mat in the working vector u
+
+ int sizeu = 1; // number of nonzero elements in the upper part of the current row
+ int sizel = 0; // number of nonzero elements in the lower part of the current row
+ ju(ii) = ii;
+ u(ii) = 0;
+ jr(ii) = ii;
+ RealScalar rownorm = 0;
+
+ typename FactorType::InnerIterator j_it(mat, ii); // Iterate through the current row ii
+ for (; j_it; ++j_it)
+ {
+ int k = j_it.index();
+ if (k < ii)
+ {
+ // copy the lower part
+ ju(sizel) = k;
+ u(sizel) = j_it.value();
+ jr(k) = sizel;
+ ++sizel;
+ }
+ else if (k == ii)
+ {
+ u(ii) = j_it.value();
+ }
+ else
+ {
+ // copy the upper part
+ int jpos = ii + sizeu;
+ ju(jpos) = k;
+ u(jpos) = j_it.value();
+ jr(k) = jpos;
+ ++sizeu;
+ }
+ rownorm += internal::abs2(j_it.value());
+ }
+
+ // 2 - detect possible zero row
+ if(rownorm==0)
+ {
+ m_info = NumericalIssue;
+ return;
+ }
+ // Take the 2-norm of the current row as a relative tolerance
+ rownorm = sqrt(rownorm);
+
+ // 3 - eliminate the previous nonzero rows
+ int jj = 0;
+ int len = 0;
+ while (jj < sizel)
+ {
+ // In order to eliminate in the correct order,
+ // we must select first the smallest column index among ju(jj:sizel)
+ int k;
+ int minrow = ju.segment(jj,sizel-jj).minCoeff(&k); // k is relative to the segment
+ k += jj;
+ if (minrow != ju(jj))
+ {
+ // swap the two locations
+ int j = ju(jj);
+ swap(ju(jj), ju(k));
+ jr(minrow) = jj; jr(j) = k;
+ swap(u(jj), u(k));
+ }
+ // Reset this location
+ jr(minrow) = -1;
+
+ // Start elimination
+ typename FactorType::InnerIterator ki_it(m_lu, minrow);
+ while (ki_it && ki_it.index() < minrow) ++ki_it;
+ eigen_internal_assert(ki_it && ki_it.col()==minrow);
+ Scalar fact = u(jj) / ki_it.value();
+
+ // drop too small elements
+ if(abs(fact) <= m_droptol)
+ {
+ jj++;
+ continue;
+ }
+
+ // linear combination of the current row ii and the row minrow
+ ++ki_it;
+ for (; ki_it; ++ki_it)
+ {
+ Scalar prod = fact * ki_it.value();
+ int j = ki_it.index();
+ int jpos = jr(j);
+ if (jpos == -1) // fill-in element
+ {
+ int newpos;
+ if (j >= ii) // dealing with the upper part
+ {
+ newpos = ii + sizeu;
+ sizeu++;
+ eigen_internal_assert(sizeu<=n);
+ }
+ else // dealing with the lower part
+ {
+ newpos = sizel;
+ sizel++;
+ eigen_internal_assert(sizel<=ii);
+ }
+ ju(newpos) = j;
+ u(newpos) = -prod;
+ jr(j) = newpos;
+ }
+ else
+ u(jpos) -= prod;
+ }
+ // store the pivot element
+ u(len) = fact;
+ ju(len) = minrow;
+ ++len;
+
+ jj++;
+ } // end of the elimination on the row ii
+
+ // reset the upper part of the pointer jr to zero
+ for(int k = 0; k <sizeu; k++) jr(ju(ii+k)) = -1;
+
+ // 4 - partially sort and insert the elements in the m_lu matrix
+
+ // sort the L-part of the row
+ sizel = len;
+ len = (std::min)(sizel, nnzL);
+ typename Vector::SegmentReturnType ul(u.segment(0, sizel));
+ typename VectorXi::SegmentReturnType jul(ju.segment(0, sizel));
+ QuickSplit(ul, jul, len);
+
+ // store the largest m_fill elements of the L part
+ m_lu.startVec(ii);
+ for(int k = 0; k < len; k++)
+ m_lu.insertBackByOuterInnerUnordered(ii,ju(k)) = u(k);
+
+ // store the diagonal element
+ // apply a shifting rule to avoid zero pivots (we are doing an incomplete factorization)
+ if (u(ii) == Scalar(0))
+ u(ii) = sqrt(m_droptol) * rownorm;
+ m_lu.insertBackByOuterInnerUnordered(ii, ii) = u(ii);
+
+ // sort the U-part of the row
+ // apply the dropping rule first
+ len = 0;
+ for(int k = 1; k < sizeu; k++)
+ {
+ if(abs(u(ii+k)) > m_droptol * rownorm )
+ {
+ ++len;
+ u(ii + len) = u(ii + k);
+ ju(ii + len) = ju(ii + k);
+ }
+ }
+ sizeu = len + 1; // +1 to take into account the diagonal element
+ len = (std::min)(sizeu, nnzU);
+ typename Vector::SegmentReturnType uu(u.segment(ii+1, sizeu-1));
+ typename VectorXi::SegmentReturnType juu(ju.segment(ii+1, sizeu-1));
+ QuickSplit(uu, juu, len);
+
+ // store the largest elements of the U part
+ for(int k = ii + 1; k < ii + len; k++)
+ m_lu.insertBackByOuterInnerUnordered(ii,ju(k)) = u(k);
+ }
+
+ m_lu.finalize();
+ m_lu.makeCompressed();
+
+ m_factorizationIsOk = true;
+ m_info = Success;
+}
+
+namespace internal {
+
+template<typename _MatrixType, typename Rhs>
+struct solve_retval<IncompleteLUT<_MatrixType>, Rhs>
+ : solve_retval_base<IncompleteLUT<_MatrixType>, Rhs>
+{
+ typedef IncompleteLUT<_MatrixType> Dec;
+ EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec()._solve(rhs(),dst);
+ }
+};
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_INCOMPLETE_LUT_H
+
diff --git a/extern/Eigen3/Eigen/src/IterativeLinearSolvers/IterativeSolverBase.h b/extern/Eigen3/Eigen/src/IterativeLinearSolvers/IterativeSolverBase.h
new file mode 100644
index 00000000000..11706cebabd
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/IterativeLinearSolvers/IterativeSolverBase.h
@@ -0,0 +1,254 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_ITERATIVE_SOLVER_BASE_H
+#define EIGEN_ITERATIVE_SOLVER_BASE_H
+
+namespace Eigen {
+
+/** \ingroup IterativeLinearSolvers_Module
+ * \brief Base class for linear iterative solvers
+ *
+ * \sa class SimplicialCholesky, DiagonalPreconditioner, IdentityPreconditioner
+ */
+template< typename Derived>
+class IterativeSolverBase : internal::noncopyable
+{
+public:
+ typedef typename internal::traits<Derived>::MatrixType MatrixType;
+ typedef typename internal::traits<Derived>::Preconditioner Preconditioner;
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::Index Index;
+ typedef typename MatrixType::RealScalar RealScalar;
+
+public:
+
+ Derived& derived() { return *static_cast<Derived*>(this); }
+ const Derived& derived() const { return *static_cast<const Derived*>(this); }
+
+ /** Default constructor. */
+ IterativeSolverBase()
+ : mp_matrix(0)
+ {
+ init();
+ }
+
+ /** Initialize the solver with matrix \a A for further \c Ax=b solving.
+ *
+ * This constructor is a shortcut for the default constructor followed
+ * by a call to compute().
+ *
+ * \warning this class stores a reference to the matrix A as well as some
+ * precomputed values that depend on it. Therefore, if \a A is changed
+ * this class becomes invalid. Call compute() to update it with the new
+ * matrix A, or modify a copy of A.
+ */
+ IterativeSolverBase(const MatrixType& A)
+ {
+ init();
+ compute(A);
+ }
+
+ ~IterativeSolverBase() {}
+
+ /** Initializes the iterative solver for the sparcity pattern of the matrix \a A for further solving \c Ax=b problems.
+ *
+ * Currently, this function mostly call analyzePattern on the preconditioner. In the future
+ * we might, for instance, implement column reodering for faster matrix vector products.
+ */
+ Derived& analyzePattern(const MatrixType& A)
+ {
+ m_preconditioner.analyzePattern(A);
+ m_isInitialized = true;
+ m_analysisIsOk = true;
+ m_info = Success;
+ return derived();
+ }
+
+ /** Initializes the iterative solver with the numerical values of the matrix \a A for further solving \c Ax=b problems.
+ *
+ * Currently, this function mostly call factorize on the preconditioner.
+ *
+ * \warning this class stores a reference to the matrix A as well as some
+ * precomputed values that depend on it. Therefore, if \a A is changed
+ * this class becomes invalid. Call compute() to update it with the new
+ * matrix A, or modify a copy of A.
+ */
+ Derived& factorize(const MatrixType& A)
+ {
+ eigen_assert(m_analysisIsOk && "You must first call analyzePattern()");
+ mp_matrix = &A;
+ m_preconditioner.factorize(A);
+ m_factorizationIsOk = true;
+ m_info = Success;
+ return derived();
+ }
+
+ /** Initializes the iterative solver with the matrix \a A for further solving \c Ax=b problems.
+ *
+ * Currently, this function mostly initialized/compute the preconditioner. In the future
+ * we might, for instance, implement column reodering for faster matrix vector products.
+ *
+ * \warning this class stores a reference to the matrix A as well as some
+ * precomputed values that depend on it. Therefore, if \a A is changed
+ * this class becomes invalid. Call compute() to update it with the new
+ * matrix A, or modify a copy of A.
+ */
+ Derived& compute(const MatrixType& A)
+ {
+ mp_matrix = &A;
+ m_preconditioner.compute(A);
+ m_isInitialized = true;
+ m_analysisIsOk = true;
+ m_factorizationIsOk = true;
+ m_info = Success;
+ return derived();
+ }
+
+ /** \internal */
+ Index rows() const { return mp_matrix ? mp_matrix->rows() : 0; }
+ /** \internal */
+ Index cols() const { return mp_matrix ? mp_matrix->cols() : 0; }
+
+ /** \returns the tolerance threshold used by the stopping criteria */
+ RealScalar tolerance() const { return m_tolerance; }
+
+ /** Sets the tolerance threshold used by the stopping criteria */
+ Derived& setTolerance(RealScalar tolerance)
+ {
+ m_tolerance = tolerance;
+ return derived();
+ }
+
+ /** \returns a read-write reference to the preconditioner for custom configuration. */
+ Preconditioner& preconditioner() { return m_preconditioner; }
+
+ /** \returns a read-only reference to the preconditioner. */
+ const Preconditioner& preconditioner() const { return m_preconditioner; }
+
+ /** \returns the max number of iterations */
+ int maxIterations() const
+ {
+ return (mp_matrix && m_maxIterations<0) ? mp_matrix->cols() : m_maxIterations;
+ }
+
+ /** Sets the max number of iterations */
+ Derived& setMaxIterations(int maxIters)
+ {
+ m_maxIterations = maxIters;
+ return derived();
+ }
+
+ /** \returns the number of iterations performed during the last solve */
+ int iterations() const
+ {
+ eigen_assert(m_isInitialized && "ConjugateGradient is not initialized.");
+ return m_iterations;
+ }
+
+ /** \returns the tolerance error reached during the last solve */
+ RealScalar error() const
+ {
+ eigen_assert(m_isInitialized && "ConjugateGradient is not initialized.");
+ return m_error;
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs> inline const internal::solve_retval<Derived, Rhs>
+ solve(const MatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "IterativeSolverBase is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "IterativeSolverBase::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::solve_retval<Derived, Rhs>(derived(), b.derived());
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs>
+ inline const internal::sparse_solve_retval<IterativeSolverBase, Rhs>
+ solve(const SparseMatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "IterativeSolverBase is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "IterativeSolverBase::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::sparse_solve_retval<IterativeSolverBase, Rhs>(*this, b.derived());
+ }
+
+ /** \returns Success if the iterations converged, and NoConvergence otherwise. */
+ ComputationInfo info() const
+ {
+ eigen_assert(m_isInitialized && "IterativeSolverBase is not initialized.");
+ return m_info;
+ }
+
+ /** \internal */
+ template<typename Rhs, typename DestScalar, int DestOptions, typename DestIndex>
+ void _solve_sparse(const Rhs& b, SparseMatrix<DestScalar,DestOptions,DestIndex> &dest) const
+ {
+ eigen_assert(rows()==b.rows());
+
+ int rhsCols = b.cols();
+ int size = b.rows();
+ Eigen::Matrix<DestScalar,Dynamic,1> tb(size);
+ Eigen::Matrix<DestScalar,Dynamic,1> tx(size);
+ for(int k=0; k<rhsCols; ++k)
+ {
+ tb = b.col(k);
+ tx = derived().solve(tb);
+ dest.col(k) = tx.sparseView(0);
+ }
+ }
+
+protected:
+ void init()
+ {
+ m_isInitialized = false;
+ m_analysisIsOk = false;
+ m_factorizationIsOk = false;
+ m_maxIterations = -1;
+ m_tolerance = NumTraits<Scalar>::epsilon();
+ }
+ const MatrixType* mp_matrix;
+ Preconditioner m_preconditioner;
+
+ int m_maxIterations;
+ RealScalar m_tolerance;
+
+ mutable RealScalar m_error;
+ mutable int m_iterations;
+ mutable ComputationInfo m_info;
+ mutable bool m_isInitialized, m_analysisIsOk, m_factorizationIsOk;
+};
+
+namespace internal {
+
+template<typename Derived, typename Rhs>
+struct sparse_solve_retval<IterativeSolverBase<Derived>, Rhs>
+ : sparse_solve_retval_base<IterativeSolverBase<Derived>, Rhs>
+{
+ typedef IterativeSolverBase<Derived> Dec;
+ EIGEN_MAKE_SPARSE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec().derived()._solve_sparse(rhs(),dst);
+ }
+};
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_ITERATIVE_SOLVER_BASE_H
diff --git a/extern/Eigen3/Eigen/src/Jacobi/Jacobi.h b/extern/Eigen3/Eigen/src/Jacobi/Jacobi.h
index 98dea6800bc..a9c17dcdf19 100644
--- a/extern/Eigen3/Eigen/src/Jacobi/Jacobi.h
+++ b/extern/Eigen3/Eigen/src/Jacobi/Jacobi.h
@@ -4,28 +4,15 @@
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_JACOBI_H
#define EIGEN_JACOBI_H
+namespace Eigen {
+
/** \ingroup Jacobi_Module
* \jacobi_module
* \class JacobiRotation
@@ -326,7 +313,7 @@ void /*EIGEN_DONT_INLINE*/ apply_rotation_in_the_plane(VectorX& _x, VectorY& _y,
// both vectors are sequentially stored in memory => vectorization
enum { Peeling = 2 };
- Index alignedStart = first_aligned(y, size);
+ Index alignedStart = internal::first_aligned(y, size);
Index alignedEnd = alignedStart + ((size-alignedStart)/PacketSize)*PacketSize;
const Packet pc = pset1<Packet>(j.c());
@@ -344,7 +331,7 @@ void /*EIGEN_DONT_INLINE*/ apply_rotation_in_the_plane(VectorX& _x, VectorY& _y,
Scalar* EIGEN_RESTRICT px = x + alignedStart;
Scalar* EIGEN_RESTRICT py = y + alignedStart;
- if(first_aligned(x, size)==alignedStart)
+ if(internal::first_aligned(x, size)==alignedStart)
{
for(Index i=alignedStart; i<alignedEnd; i+=PacketSize)
{
@@ -425,6 +412,9 @@ void /*EIGEN_DONT_INLINE*/ apply_rotation_in_the_plane(VectorX& _x, VectorY& _y,
}
}
}
-}
+
+} // end namespace internal
+
+} // end namespace Eigen
#endif // EIGEN_JACOBI_H
diff --git a/extern/Eigen3/Eigen/src/LU/Determinant.h b/extern/Eigen3/Eigen/src/LU/Determinant.h
index b4fe36eb061..d862c5d7784 100644
--- a/extern/Eigen3/Eigen/src/LU/Determinant.h
+++ b/extern/Eigen3/Eigen/src/LU/Determinant.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DETERMINANT_H
#define EIGEN_DETERMINANT_H
+namespace Eigen {
+
namespace internal {
template<typename Derived>
@@ -109,4 +96,6 @@ inline typename internal::traits<Derived>::Scalar MatrixBase<Derived>::determina
return internal::determinant_impl<typename internal::remove_all<Nested>::type>::run(derived());
}
+} // end namespace Eigen
+
#endif // EIGEN_DETERMINANT_H
diff --git a/extern/Eigen3/Eigen/src/LU/FullPivLU.h b/extern/Eigen3/Eigen/src/LU/FullPivLU.h
index 46ae7d651c8..e23f96cdcf1 100644
--- a/extern/Eigen3/Eigen/src/LU/FullPivLU.h
+++ b/extern/Eigen3/Eigen/src/LU/FullPivLU.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2006-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_LU_H
#define EIGEN_LU_H
+namespace Eigen {
+
/** \ingroup LU_Module
*
* \class FullPivLU
@@ -282,6 +269,7 @@ template<typename _MatrixType> class FullPivLU
FullPivLU& setThreshold(Default_t)
{
m_usePrescribedThreshold = false;
+ return *this;
}
/** Returns the threshold that will be used by certain methods such as rank().
@@ -743,4 +731,6 @@ MatrixBase<Derived>::fullPivLu() const
return FullPivLU<PlainObject>(eval());
}
+} // end namespace Eigen
+
#endif // EIGEN_LU_H
diff --git a/extern/Eigen3/Eigen/src/LU/Inverse.h b/extern/Eigen3/Eigen/src/LU/Inverse.h
index 2d3e6d10529..39b8cdbc8dc 100644
--- a/extern/Eigen3/Eigen/src/LU/Inverse.h
+++ b/extern/Eigen3/Eigen/src/LU/Inverse.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_INVERSE_H
#define EIGEN_INVERSE_H
+namespace Eigen {
+
namespace internal {
/**********************************
@@ -286,7 +273,7 @@ struct inverse_impl : public ReturnByValue<inverse_impl<MatrixType> >
typedef typename MatrixType::Index Index;
typedef typename internal::eval<MatrixType>::type MatrixTypeNested;
typedef typename remove_all<MatrixTypeNested>::type MatrixTypeNestedCleaned;
- const MatrixTypeNested m_matrix;
+ MatrixTypeNested m_matrix;
inverse_impl(const MatrixType& matrix)
: m_matrix(matrix)
@@ -404,4 +391,6 @@ inline void MatrixBase<Derived>::computeInverseWithCheck(
computeInverseAndDetWithCheck(inverse,determinant,invertible,absDeterminantThreshold);
}
+} // end namespace Eigen
+
#endif // EIGEN_INVERSE_H
diff --git a/extern/Eigen3/Eigen/src/LU/PartialPivLU.h b/extern/Eigen3/Eigen/src/LU/PartialPivLU.h
index 09394b01f5b..c9ff9dd5a36 100644
--- a/extern/Eigen3/Eigen/src/LU/PartialPivLU.h
+++ b/extern/Eigen3/Eigen/src/LU/PartialPivLU.h
@@ -4,28 +4,15 @@
// Copyright (C) 2006-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PARTIALLU_H
#define EIGEN_PARTIALLU_H
+namespace Eigen {
+
/** \ingroup LU_Module
*
* \class PartialPivLU
@@ -506,4 +493,6 @@ MatrixBase<Derived>::lu() const
}
#endif
+} // end namespace Eigen
+
#endif // EIGEN_PARTIALLU_H
diff --git a/extern/Eigen3/Eigen/src/LU/PartialPivLU_MKL.h b/extern/Eigen3/Eigen/src/LU/PartialPivLU_MKL.h
new file mode 100644
index 00000000000..9035953c82f
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/LU/PartialPivLU_MKL.h
@@ -0,0 +1,85 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * LU decomposition with partial pivoting based on LAPACKE_?getrf function.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_PARTIALLU_LAPACK_H
+#define EIGEN_PARTIALLU_LAPACK_H
+
+#include "Eigen/src/Core/util/MKL_support.h"
+
+namespace Eigen {
+
+namespace internal {
+
+/** \internal Specialization for the data types supported by MKL */
+
+#define EIGEN_MKL_LU_PARTPIV(EIGTYPE, MKLTYPE, MKLPREFIX) \
+template<int StorageOrder> \
+struct partial_lu_impl<EIGTYPE, StorageOrder, lapack_int> \
+{ \
+ /* \internal performs the LU decomposition in-place of the matrix represented */ \
+ static lapack_int blocked_lu(lapack_int rows, lapack_int cols, EIGTYPE* lu_data, lapack_int luStride, lapack_int* row_transpositions, lapack_int& nb_transpositions, lapack_int maxBlockSize=256) \
+ { \
+ EIGEN_UNUSED_VARIABLE(maxBlockSize);\
+ lapack_int matrix_order, first_zero_pivot; \
+ lapack_int m, n, lda, *ipiv, info; \
+ EIGTYPE* a; \
+/* Set up parameters for ?getrf */ \
+ matrix_order = StorageOrder==RowMajor ? LAPACK_ROW_MAJOR : LAPACK_COL_MAJOR; \
+ lda = luStride; \
+ a = lu_data; \
+ ipiv = row_transpositions; \
+ m = rows; \
+ n = cols; \
+ nb_transpositions = 0; \
+\
+ info = LAPACKE_##MKLPREFIX##getrf( matrix_order, m, n, (MKLTYPE*)a, lda, ipiv ); \
+\
+ for(int i=0;i<m;i++) { ipiv[i]--; if (ipiv[i]!=i) nb_transpositions++; } \
+\
+ eigen_assert(info >= 0); \
+/* something should be done with nb_transpositions */ \
+\
+ first_zero_pivot = info; \
+ return first_zero_pivot; \
+ } \
+};
+
+EIGEN_MKL_LU_PARTPIV(double, double, d)
+EIGEN_MKL_LU_PARTPIV(float, float, s)
+EIGEN_MKL_LU_PARTPIV(dcomplex, MKL_Complex16, z)
+EIGEN_MKL_LU_PARTPIV(scomplex, MKL_Complex8, c)
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_PARTIALLU_LAPACK_H
diff --git a/extern/Eigen3/Eigen/src/LU/arch/Inverse_SSE.h b/extern/Eigen3/Eigen/src/LU/arch/Inverse_SSE.h
index 4c6153f0aff..60b7a23763e 100644
--- a/extern/Eigen3/Eigen/src/LU/arch/Inverse_SSE.h
+++ b/extern/Eigen3/Eigen/src/LU/arch/Inverse_SSE.h
@@ -5,24 +5,9 @@
// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// The SSE code for the 4x4 float and double matrix inverse in this file
// comes from the following Intel's library:
@@ -42,6 +27,8 @@
#ifndef EIGEN_INVERSE_SSE_H
#define EIGEN_INVERSE_SSE_H
+namespace Eigen {
+
namespace internal {
template<typename MatrixType, typename ResultType>
@@ -335,6 +322,8 @@ struct compute_inverse_size4<Architecture::SSE, double, MatrixType, ResultType>
}
};
-}
+} // end namespace internal
+
+} // end namespace Eigen
#endif // EIGEN_INVERSE_SSE_H
diff --git a/extern/Eigen3/Eigen/src/OrderingMethods/Amd.h b/extern/Eigen3/Eigen/src/OrderingMethods/Amd.h
new file mode 100644
index 00000000000..ce04852b872
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/OrderingMethods/Amd.h
@@ -0,0 +1,439 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+/*
+
+NOTE: this routine has been adapted from the CSparse library:
+
+Copyright (c) 2006, Timothy A. Davis.
+http://www.cise.ufl.edu/research/sparse/CSparse
+
+CSparse is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+CSparse is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this Module; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+*/
+
+#include "../Core/util/NonMPL2.h"
+
+#ifndef EIGEN_SPARSE_AMD_H
+#define EIGEN_SPARSE_AMD_H
+
+namespace Eigen {
+
+namespace internal {
+
+template<typename T> inline T amd_flip(const T& i) { return -i-2; }
+template<typename T> inline T amd_unflip(const T& i) { return i<0 ? amd_flip(i) : i; }
+template<typename T0, typename T1> inline bool amd_marked(const T0* w, const T1& j) { return w[j]<0; }
+template<typename T0, typename T1> inline void amd_mark(const T0* w, const T1& j) { return w[j] = amd_flip(w[j]); }
+
+/* clear w */
+template<typename Index>
+static int cs_wclear (Index mark, Index lemax, Index *w, Index n)
+{
+ Index k;
+ if(mark < 2 || (mark + lemax < 0))
+ {
+ for(k = 0; k < n; k++)
+ if(w[k] != 0)
+ w[k] = 1;
+ mark = 2;
+ }
+ return (mark); /* at this point, w[0..n-1] < mark holds */
+}
+
+/* depth-first search and postorder of a tree rooted at node j */
+template<typename Index>
+Index cs_tdfs(Index j, Index k, Index *head, const Index *next, Index *post, Index *stack)
+{
+ int i, p, top = 0;
+ if(!head || !next || !post || !stack) return (-1); /* check inputs */
+ stack[0] = j; /* place j on the stack */
+ while (top >= 0) /* while (stack is not empty) */
+ {
+ p = stack[top]; /* p = top of stack */
+ i = head[p]; /* i = youngest child of p */
+ if(i == -1)
+ {
+ top--; /* p has no unordered children left */
+ post[k++] = p; /* node p is the kth postordered node */
+ }
+ else
+ {
+ head[p] = next[i]; /* remove i from children of p */
+ stack[++top] = i; /* start dfs on child node i */
+ }
+ }
+ return k;
+}
+
+
+/** \internal
+ * Approximate minimum degree ordering algorithm.
+ * \returns the permutation P reducing the fill-in of the input matrix \a C
+ * The input matrix \a C must be a selfadjoint compressed column major SparseMatrix object. Both the upper and lower parts have to be stored, but the diagonal entries are optional.
+ * On exit the values of C are destroyed */
+template<typename Scalar, typename Index>
+void minimum_degree_ordering(SparseMatrix<Scalar,ColMajor,Index>& C, PermutationMatrix<Dynamic,Dynamic,Index>& perm)
+{
+ using std::sqrt;
+ typedef SparseMatrix<Scalar,ColMajor,Index> CCS;
+
+ int d, dk, dext, lemax = 0, e, elenk, eln, i, j, k, k1,
+ k2, k3, jlast, ln, dense, nzmax, mindeg = 0, nvi, nvj, nvk, mark, wnvi,
+ ok, nel = 0, p, p1, p2, p3, p4, pj, pk, pk1, pk2, pn, q, t;
+ unsigned int h;
+
+ Index n = C.cols();
+ dense = std::max<Index> (16, Index(10 * sqrt(double(n)))); /* find dense threshold */
+ dense = std::min<Index> (n-2, dense);
+
+ Index cnz = C.nonZeros();
+ perm.resize(n+1);
+ t = cnz + cnz/5 + 2*n; /* add elbow room to C */
+ C.resizeNonZeros(t);
+
+ Index* W = new Index[8*(n+1)]; /* get workspace */
+ Index* len = W;
+ Index* nv = W + (n+1);
+ Index* next = W + 2*(n+1);
+ Index* head = W + 3*(n+1);
+ Index* elen = W + 4*(n+1);
+ Index* degree = W + 5*(n+1);
+ Index* w = W + 6*(n+1);
+ Index* hhead = W + 7*(n+1);
+ Index* last = perm.indices().data(); /* use P as workspace for last */
+
+ /* --- Initialize quotient graph ---------------------------------------- */
+ Index* Cp = C.outerIndexPtr();
+ Index* Ci = C.innerIndexPtr();
+ for(k = 0; k < n; k++)
+ len[k] = Cp[k+1] - Cp[k];
+ len[n] = 0;
+ nzmax = t;
+
+ for(i = 0; i <= n; i++)
+ {
+ head[i] = -1; // degree list i is empty
+ last[i] = -1;
+ next[i] = -1;
+ hhead[i] = -1; // hash list i is empty
+ nv[i] = 1; // node i is just one node
+ w[i] = 1; // node i is alive
+ elen[i] = 0; // Ek of node i is empty
+ degree[i] = len[i]; // degree of node i
+ }
+ mark = internal::cs_wclear<Index>(0, 0, w, n); /* clear w */
+ elen[n] = -2; /* n is a dead element */
+ Cp[n] = -1; /* n is a root of assembly tree */
+ w[n] = 0; /* n is a dead element */
+
+ /* --- Initialize degree lists ------------------------------------------ */
+ for(i = 0; i < n; i++)
+ {
+ d = degree[i];
+ if(d == 0) /* node i is empty */
+ {
+ elen[i] = -2; /* element i is dead */
+ nel++;
+ Cp[i] = -1; /* i is a root of assembly tree */
+ w[i] = 0;
+ }
+ else if(d > dense) /* node i is dense */
+ {
+ nv[i] = 0; /* absorb i into element n */
+ elen[i] = -1; /* node i is dead */
+ nel++;
+ Cp[i] = amd_flip (n);
+ nv[n]++;
+ }
+ else
+ {
+ if(head[d] != -1) last[head[d]] = i;
+ next[i] = head[d]; /* put node i in degree list d */
+ head[d] = i;
+ }
+ }
+
+ while (nel < n) /* while (selecting pivots) do */
+ {
+ /* --- Select node of minimum approximate degree -------------------- */
+ for(k = -1; mindeg < n && (k = head[mindeg]) == -1; mindeg++) {}
+ if(next[k] != -1) last[next[k]] = -1;
+ head[mindeg] = next[k]; /* remove k from degree list */
+ elenk = elen[k]; /* elenk = |Ek| */
+ nvk = nv[k]; /* # of nodes k represents */
+ nel += nvk; /* nv[k] nodes of A eliminated */
+
+ /* --- Garbage collection ------------------------------------------- */
+ if(elenk > 0 && cnz + mindeg >= nzmax)
+ {
+ for(j = 0; j < n; j++)
+ {
+ if((p = Cp[j]) >= 0) /* j is a live node or element */
+ {
+ Cp[j] = Ci[p]; /* save first entry of object */
+ Ci[p] = amd_flip (j); /* first entry is now amd_flip(j) */
+ }
+ }
+ for(q = 0, p = 0; p < cnz; ) /* scan all of memory */
+ {
+ if((j = amd_flip (Ci[p++])) >= 0) /* found object j */
+ {
+ Ci[q] = Cp[j]; /* restore first entry of object */
+ Cp[j] = q++; /* new pointer to object j */
+ for(k3 = 0; k3 < len[j]-1; k3++) Ci[q++] = Ci[p++];
+ }
+ }
+ cnz = q; /* Ci[cnz...nzmax-1] now free */
+ }
+
+ /* --- Construct new element ---------------------------------------- */
+ dk = 0;
+ nv[k] = -nvk; /* flag k as in Lk */
+ p = Cp[k];
+ pk1 = (elenk == 0) ? p : cnz; /* do in place if elen[k] == 0 */
+ pk2 = pk1;
+ for(k1 = 1; k1 <= elenk + 1; k1++)
+ {
+ if(k1 > elenk)
+ {
+ e = k; /* search the nodes in k */
+ pj = p; /* list of nodes starts at Ci[pj]*/
+ ln = len[k] - elenk; /* length of list of nodes in k */
+ }
+ else
+ {
+ e = Ci[p++]; /* search the nodes in e */
+ pj = Cp[e];
+ ln = len[e]; /* length of list of nodes in e */
+ }
+ for(k2 = 1; k2 <= ln; k2++)
+ {
+ i = Ci[pj++];
+ if((nvi = nv[i]) <= 0) continue; /* node i dead, or seen */
+ dk += nvi; /* degree[Lk] += size of node i */
+ nv[i] = -nvi; /* negate nv[i] to denote i in Lk*/
+ Ci[pk2++] = i; /* place i in Lk */
+ if(next[i] != -1) last[next[i]] = last[i];
+ if(last[i] != -1) /* remove i from degree list */
+ {
+ next[last[i]] = next[i];
+ }
+ else
+ {
+ head[degree[i]] = next[i];
+ }
+ }
+ if(e != k)
+ {
+ Cp[e] = amd_flip (k); /* absorb e into k */
+ w[e] = 0; /* e is now a dead element */
+ }
+ }
+ if(elenk != 0) cnz = pk2; /* Ci[cnz...nzmax] is free */
+ degree[k] = dk; /* external degree of k - |Lk\i| */
+ Cp[k] = pk1; /* element k is in Ci[pk1..pk2-1] */
+ len[k] = pk2 - pk1;
+ elen[k] = -2; /* k is now an element */
+
+ /* --- Find set differences ----------------------------------------- */
+ mark = internal::cs_wclear<Index>(mark, lemax, w, n); /* clear w if necessary */
+ for(pk = pk1; pk < pk2; pk++) /* scan 1: find |Le\Lk| */
+ {
+ i = Ci[pk];
+ if((eln = elen[i]) <= 0) continue;/* skip if elen[i] empty */
+ nvi = -nv[i]; /* nv[i] was negated */
+ wnvi = mark - nvi;
+ for(p = Cp[i]; p <= Cp[i] + eln - 1; p++) /* scan Ei */
+ {
+ e = Ci[p];
+ if(w[e] >= mark)
+ {
+ w[e] -= nvi; /* decrement |Le\Lk| */
+ }
+ else if(w[e] != 0) /* ensure e is a live element */
+ {
+ w[e] = degree[e] + wnvi; /* 1st time e seen in scan 1 */
+ }
+ }
+ }
+
+ /* --- Degree update ------------------------------------------------ */
+ for(pk = pk1; pk < pk2; pk++) /* scan2: degree update */
+ {
+ i = Ci[pk]; /* consider node i in Lk */
+ p1 = Cp[i];
+ p2 = p1 + elen[i] - 1;
+ pn = p1;
+ for(h = 0, d = 0, p = p1; p <= p2; p++) /* scan Ei */
+ {
+ e = Ci[p];
+ if(w[e] != 0) /* e is an unabsorbed element */
+ {
+ dext = w[e] - mark; /* dext = |Le\Lk| */
+ if(dext > 0)
+ {
+ d += dext; /* sum up the set differences */
+ Ci[pn++] = e; /* keep e in Ei */
+ h += e; /* compute the hash of node i */
+ }
+ else
+ {
+ Cp[e] = amd_flip (k); /* aggressive absorb. e->k */
+ w[e] = 0; /* e is a dead element */
+ }
+ }
+ }
+ elen[i] = pn - p1 + 1; /* elen[i] = |Ei| */
+ p3 = pn;
+ p4 = p1 + len[i];
+ for(p = p2 + 1; p < p4; p++) /* prune edges in Ai */
+ {
+ j = Ci[p];
+ if((nvj = nv[j]) <= 0) continue; /* node j dead or in Lk */
+ d += nvj; /* degree(i) += |j| */
+ Ci[pn++] = j; /* place j in node list of i */
+ h += j; /* compute hash for node i */
+ }
+ if(d == 0) /* check for mass elimination */
+ {
+ Cp[i] = amd_flip (k); /* absorb i into k */
+ nvi = -nv[i];
+ dk -= nvi; /* |Lk| -= |i| */
+ nvk += nvi; /* |k| += nv[i] */
+ nel += nvi;
+ nv[i] = 0;
+ elen[i] = -1; /* node i is dead */
+ }
+ else
+ {
+ degree[i] = std::min<Index> (degree[i], d); /* update degree(i) */
+ Ci[pn] = Ci[p3]; /* move first node to end */
+ Ci[p3] = Ci[p1]; /* move 1st el. to end of Ei */
+ Ci[p1] = k; /* add k as 1st element in of Ei */
+ len[i] = pn - p1 + 1; /* new len of adj. list of node i */
+ h %= n; /* finalize hash of i */
+ next[i] = hhead[h]; /* place i in hash bucket */
+ hhead[h] = i;
+ last[i] = h; /* save hash of i in last[i] */
+ }
+ } /* scan2 is done */
+ degree[k] = dk; /* finalize |Lk| */
+ lemax = std::max<Index>(lemax, dk);
+ mark = internal::cs_wclear<Index>(mark+lemax, lemax, w, n); /* clear w */
+
+ /* --- Supernode detection ------------------------------------------ */
+ for(pk = pk1; pk < pk2; pk++)
+ {
+ i = Ci[pk];
+ if(nv[i] >= 0) continue; /* skip if i is dead */
+ h = last[i]; /* scan hash bucket of node i */
+ i = hhead[h];
+ hhead[h] = -1; /* hash bucket will be empty */
+ for(; i != -1 && next[i] != -1; i = next[i], mark++)
+ {
+ ln = len[i];
+ eln = elen[i];
+ for(p = Cp[i]+1; p <= Cp[i] + ln-1; p++) w[Ci[p]] = mark;
+ jlast = i;
+ for(j = next[i]; j != -1; ) /* compare i with all j */
+ {
+ ok = (len[j] == ln) && (elen[j] == eln);
+ for(p = Cp[j] + 1; ok && p <= Cp[j] + ln - 1; p++)
+ {
+ if(w[Ci[p]] != mark) ok = 0; /* compare i and j*/
+ }
+ if(ok) /* i and j are identical */
+ {
+ Cp[j] = amd_flip (i); /* absorb j into i */
+ nv[i] += nv[j];
+ nv[j] = 0;
+ elen[j] = -1; /* node j is dead */
+ j = next[j]; /* delete j from hash bucket */
+ next[jlast] = j;
+ }
+ else
+ {
+ jlast = j; /* j and i are different */
+ j = next[j];
+ }
+ }
+ }
+ }
+
+ /* --- Finalize new element------------------------------------------ */
+ for(p = pk1, pk = pk1; pk < pk2; pk++) /* finalize Lk */
+ {
+ i = Ci[pk];
+ if((nvi = -nv[i]) <= 0) continue;/* skip if i is dead */
+ nv[i] = nvi; /* restore nv[i] */
+ d = degree[i] + dk - nvi; /* compute external degree(i) */
+ d = std::min<Index> (d, n - nel - nvi);
+ if(head[d] != -1) last[head[d]] = i;
+ next[i] = head[d]; /* put i back in degree list */
+ last[i] = -1;
+ head[d] = i;
+ mindeg = std::min<Index> (mindeg, d); /* find new minimum degree */
+ degree[i] = d;
+ Ci[p++] = i; /* place i in Lk */
+ }
+ nv[k] = nvk; /* # nodes absorbed into k */
+ if((len[k] = p-pk1) == 0) /* length of adj list of element k*/
+ {
+ Cp[k] = -1; /* k is a root of the tree */
+ w[k] = 0; /* k is now a dead element */
+ }
+ if(elenk != 0) cnz = p; /* free unused space in Lk */
+ }
+
+ /* --- Postordering ----------------------------------------------------- */
+ for(i = 0; i < n; i++) Cp[i] = amd_flip (Cp[i]);/* fix assembly tree */
+ for(j = 0; j <= n; j++) head[j] = -1;
+ for(j = n; j >= 0; j--) /* place unordered nodes in lists */
+ {
+ if(nv[j] > 0) continue; /* skip if j is an element */
+ next[j] = head[Cp[j]]; /* place j in list of its parent */
+ head[Cp[j]] = j;
+ }
+ for(e = n; e >= 0; e--) /* place elements in lists */
+ {
+ if(nv[e] <= 0) continue; /* skip unless e is an element */
+ if(Cp[e] != -1)
+ {
+ next[e] = head[Cp[e]]; /* place e in list of its parent */
+ head[Cp[e]] = e;
+ }
+ }
+ for(k = 0, i = 0; i <= n; i++) /* postorder the assembly tree */
+ {
+ if(Cp[i] == -1) k = internal::cs_tdfs<Index>(i, k, head, next, perm.indices().data(), w);
+ }
+
+ perm.indices().conservativeResize(n);
+
+ delete[] W;
+}
+
+} // namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_SPARSE_AMD_H
diff --git a/extern/Eigen3/Eigen/src/PaStiXSupport/PaStiXSupport.h b/extern/Eigen3/Eigen/src/PaStiXSupport/PaStiXSupport.h
new file mode 100644
index 00000000000..82e137c645a
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/PaStiXSupport/PaStiXSupport.h
@@ -0,0 +1,742 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2012 Désiré Nuentsa-Wakam <desire.nuentsa_wakam@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_PASTIXSUPPORT_H
+#define EIGEN_PASTIXSUPPORT_H
+
+namespace Eigen {
+
+/** \ingroup PaStiXSupport_Module
+ * \brief Interface to the PaStix solver
+ *
+ * This class is used to solve the linear systems A.X = B via the PaStix library.
+ * The matrix can be either real or complex, symmetric or not.
+ *
+ * \sa TutorialSparseDirectSolvers
+ */
+template<typename _MatrixType, bool IsStrSym = false> class PastixLU;
+template<typename _MatrixType, int Options> class PastixLLT;
+template<typename _MatrixType, int Options> class PastixLDLT;
+
+namespace internal
+{
+
+ template<class Pastix> struct pastix_traits;
+
+ template<typename _MatrixType>
+ struct pastix_traits< PastixLU<_MatrixType> >
+ {
+ typedef _MatrixType MatrixType;
+ typedef typename _MatrixType::Scalar Scalar;
+ typedef typename _MatrixType::RealScalar RealScalar;
+ typedef typename _MatrixType::Index Index;
+ };
+
+ template<typename _MatrixType, int Options>
+ struct pastix_traits< PastixLLT<_MatrixType,Options> >
+ {
+ typedef _MatrixType MatrixType;
+ typedef typename _MatrixType::Scalar Scalar;
+ typedef typename _MatrixType::RealScalar RealScalar;
+ typedef typename _MatrixType::Index Index;
+ };
+
+ template<typename _MatrixType, int Options>
+ struct pastix_traits< PastixLDLT<_MatrixType,Options> >
+ {
+ typedef _MatrixType MatrixType;
+ typedef typename _MatrixType::Scalar Scalar;
+ typedef typename _MatrixType::RealScalar RealScalar;
+ typedef typename _MatrixType::Index Index;
+ };
+
+ void eigen_pastix(pastix_data_t **pastix_data, int pastix_comm, int n, int *ptr, int *idx, float *vals, int *perm, int * invp, float *x, int nbrhs, int *iparm, double *dparm)
+ {
+ if (n == 0) { ptr = NULL; idx = NULL; vals = NULL; }
+ if (nbrhs == 0) {x = NULL; nbrhs=1;}
+ s_pastix(pastix_data, pastix_comm, n, ptr, idx, vals, perm, invp, x, nbrhs, iparm, dparm);
+ }
+
+ void eigen_pastix(pastix_data_t **pastix_data, int pastix_comm, int n, int *ptr, int *idx, double *vals, int *perm, int * invp, double *x, int nbrhs, int *iparm, double *dparm)
+ {
+ if (n == 0) { ptr = NULL; idx = NULL; vals = NULL; }
+ if (nbrhs == 0) {x = NULL; nbrhs=1;}
+ d_pastix(pastix_data, pastix_comm, n, ptr, idx, vals, perm, invp, x, nbrhs, iparm, dparm);
+ }
+
+ void eigen_pastix(pastix_data_t **pastix_data, int pastix_comm, int n, int *ptr, int *idx, std::complex<float> *vals, int *perm, int * invp, std::complex<float> *x, int nbrhs, int *iparm, double *dparm)
+ {
+ if (n == 0) { ptr = NULL; idx = NULL; vals = NULL; }
+ if (nbrhs == 0) {x = NULL; nbrhs=1;}
+ c_pastix(pastix_data, pastix_comm, n, ptr, idx, reinterpret_cast<COMPLEX*>(vals), perm, invp, reinterpret_cast<COMPLEX*>(x), nbrhs, iparm, dparm);
+ }
+
+ void eigen_pastix(pastix_data_t **pastix_data, int pastix_comm, int n, int *ptr, int *idx, std::complex<double> *vals, int *perm, int * invp, std::complex<double> *x, int nbrhs, int *iparm, double *dparm)
+ {
+ if (n == 0) { ptr = NULL; idx = NULL; vals = NULL; }
+ if (nbrhs == 0) {x = NULL; nbrhs=1;}
+ z_pastix(pastix_data, pastix_comm, n, ptr, idx, reinterpret_cast<DCOMPLEX*>(vals), perm, invp, reinterpret_cast<DCOMPLEX*>(x), nbrhs, iparm, dparm);
+ }
+
+ // Convert the matrix to Fortran-style Numbering
+ template <typename MatrixType>
+ void c_to_fortran_numbering (MatrixType& mat)
+ {
+ if ( !(mat.outerIndexPtr()[0]) )
+ {
+ int i;
+ for(i = 0; i <= mat.rows(); ++i)
+ ++mat.outerIndexPtr()[i];
+ for(i = 0; i < mat.nonZeros(); ++i)
+ ++mat.innerIndexPtr()[i];
+ }
+ }
+
+ // Convert to C-style Numbering
+ template <typename MatrixType>
+ void fortran_to_c_numbering (MatrixType& mat)
+ {
+ // Check the Numbering
+ if ( mat.outerIndexPtr()[0] == 1 )
+ { // Convert to C-style numbering
+ int i;
+ for(i = 0; i <= mat.rows(); ++i)
+ --mat.outerIndexPtr()[i];
+ for(i = 0; i < mat.nonZeros(); ++i)
+ --mat.innerIndexPtr()[i];
+ }
+ }
+}
+
+// This is the base class to interface with PaStiX functions.
+// Users should not used this class directly.
+template <class Derived>
+class PastixBase : internal::noncopyable
+{
+ public:
+ typedef typename internal::pastix_traits<Derived>::MatrixType _MatrixType;
+ typedef _MatrixType MatrixType;
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef typename MatrixType::Index Index;
+ typedef Matrix<Scalar,Dynamic,1> Vector;
+ typedef SparseMatrix<Scalar, ColMajor> ColSpMatrix;
+
+ public:
+
+ PastixBase() : m_initisOk(false), m_analysisIsOk(false), m_factorizationIsOk(false), m_isInitialized(false), m_pastixdata(0), m_size(0)
+ {
+ init();
+ }
+
+ ~PastixBase()
+ {
+ clean();
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs>
+ inline const internal::solve_retval<PastixBase, Rhs>
+ solve(const MatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "Pastix solver is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "PastixBase::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::solve_retval<PastixBase, Rhs>(*this, b.derived());
+ }
+
+ template<typename Rhs,typename Dest>
+ bool _solve (const MatrixBase<Rhs> &b, MatrixBase<Dest> &x) const;
+
+ /** \internal */
+ template<typename Rhs, typename DestScalar, int DestOptions, typename DestIndex>
+ void _solve_sparse(const Rhs& b, SparseMatrix<DestScalar,DestOptions,DestIndex> &dest) const
+ {
+ eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()");
+ eigen_assert(rows()==b.rows());
+
+ // we process the sparse rhs per block of NbColsAtOnce columns temporarily stored into a dense matrix.
+ static const int NbColsAtOnce = 1;
+ int rhsCols = b.cols();
+ int size = b.rows();
+ Eigen::Matrix<DestScalar,Dynamic,Dynamic> tmp(size,rhsCols);
+ for(int k=0; k<rhsCols; k+=NbColsAtOnce)
+ {
+ int actualCols = std::min<int>(rhsCols-k, NbColsAtOnce);
+ tmp.leftCols(actualCols) = b.middleCols(k,actualCols);
+ tmp.leftCols(actualCols) = derived().solve(tmp.leftCols(actualCols));
+ dest.middleCols(k,actualCols) = tmp.leftCols(actualCols).sparseView();
+ }
+ }
+
+ Derived& derived()
+ {
+ return *static_cast<Derived*>(this);
+ }
+ const Derived& derived() const
+ {
+ return *static_cast<const Derived*>(this);
+ }
+
+ /** Returns a reference to the integer vector IPARM of PaStiX parameters
+ * to modify the default parameters.
+ * The statistics related to the different phases of factorization and solve are saved here as well
+ * \sa analyzePattern() factorize()
+ */
+ Array<Index,IPARM_SIZE,1>& iparm()
+ {
+ return m_iparm;
+ }
+
+ /** Return a reference to a particular index parameter of the IPARM vector
+ * \sa iparm()
+ */
+
+ int& iparm(int idxparam)
+ {
+ return m_iparm(idxparam);
+ }
+
+ /** Returns a reference to the double vector DPARM of PaStiX parameters
+ * The statistics related to the different phases of factorization and solve are saved here as well
+ * \sa analyzePattern() factorize()
+ */
+ Array<RealScalar,IPARM_SIZE,1>& dparm()
+ {
+ return m_dparm;
+ }
+
+
+ /** Return a reference to a particular index parameter of the DPARM vector
+ * \sa dparm()
+ */
+ double& dparm(int idxparam)
+ {
+ return m_dparm(idxparam);
+ }
+
+ inline Index cols() const { return m_size; }
+ inline Index rows() const { return m_size; }
+
+ /** \brief Reports whether previous computation was successful.
+ *
+ * \returns \c Success if computation was succesful,
+ * \c NumericalIssue if the PaStiX reports a problem
+ * \c InvalidInput if the input matrix is invalid
+ *
+ * \sa iparm()
+ */
+ ComputationInfo info() const
+ {
+ eigen_assert(m_isInitialized && "Decomposition is not initialized.");
+ return m_info;
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs>
+ inline const internal::sparse_solve_retval<PastixBase, Rhs>
+ solve(const SparseMatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "Pastix LU, LLT or LDLT is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "PastixBase::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::sparse_solve_retval<PastixBase, Rhs>(*this, b.derived());
+ }
+
+ protected:
+
+ // Initialize the Pastix data structure, check the matrix
+ void init();
+
+ // Compute the ordering and the symbolic factorization
+ void analyzePattern(ColSpMatrix& mat);
+
+ // Compute the numerical factorization
+ void factorize(ColSpMatrix& mat);
+
+ // Free all the data allocated by Pastix
+ void clean()
+ {
+ eigen_assert(m_initisOk && "The Pastix structure should be allocated first");
+ m_iparm(IPARM_START_TASK) = API_TASK_CLEAN;
+ m_iparm(IPARM_END_TASK) = API_TASK_CLEAN;
+ internal::eigen_pastix(&m_pastixdata, MPI_COMM_WORLD, 0, 0, 0, (Scalar*)0,
+ m_perm.data(), m_invp.data(), 0, 0, m_iparm.data(), m_dparm.data());
+ }
+
+ void compute(ColSpMatrix& mat);
+
+ int m_initisOk;
+ int m_analysisIsOk;
+ int m_factorizationIsOk;
+ bool m_isInitialized;
+ mutable ComputationInfo m_info;
+ mutable pastix_data_t *m_pastixdata; // Data structure for pastix
+ mutable int m_comm; // The MPI communicator identifier
+ mutable Matrix<int,IPARM_SIZE,1> m_iparm; // integer vector for the input parameters
+ mutable Matrix<double,DPARM_SIZE,1> m_dparm; // Scalar vector for the input parameters
+ mutable Matrix<Index,Dynamic,1> m_perm; // Permutation vector
+ mutable Matrix<Index,Dynamic,1> m_invp; // Inverse permutation vector
+ mutable int m_size; // Size of the matrix
+};
+
+ /** Initialize the PaStiX data structure.
+ *A first call to this function fills iparm and dparm with the default PaStiX parameters
+ * \sa iparm() dparm()
+ */
+template <class Derived>
+void PastixBase<Derived>::init()
+{
+ m_size = 0;
+ m_iparm.setZero(IPARM_SIZE);
+ m_dparm.setZero(DPARM_SIZE);
+
+ m_iparm(IPARM_MODIFY_PARAMETER) = API_NO;
+ pastix(&m_pastixdata, MPI_COMM_WORLD,
+ 0, 0, 0, 0,
+ 0, 0, 0, 1, m_iparm.data(), m_dparm.data());
+
+ m_iparm[IPARM_MATRIX_VERIFICATION] = API_NO;
+ m_iparm[IPARM_VERBOSE] = 2;
+ m_iparm[IPARM_ORDERING] = API_ORDER_SCOTCH;
+ m_iparm[IPARM_INCOMPLETE] = API_NO;
+ m_iparm[IPARM_OOC_LIMIT] = 2000;
+ m_iparm[IPARM_RHS_MAKING] = API_RHS_B;
+ m_iparm(IPARM_MATRIX_VERIFICATION) = API_NO;
+
+ m_iparm(IPARM_START_TASK) = API_TASK_INIT;
+ m_iparm(IPARM_END_TASK) = API_TASK_INIT;
+ internal::eigen_pastix(&m_pastixdata, MPI_COMM_WORLD, 0, 0, 0, (Scalar*)0,
+ 0, 0, 0, 0, m_iparm.data(), m_dparm.data());
+
+ // Check the returned error
+ if(m_iparm(IPARM_ERROR_NUMBER)) {
+ m_info = InvalidInput;
+ m_initisOk = false;
+ }
+ else {
+ m_info = Success;
+ m_initisOk = true;
+ }
+}
+
+template <class Derived>
+void PastixBase<Derived>::compute(ColSpMatrix& mat)
+{
+ eigen_assert(mat.rows() == mat.cols() && "The input matrix should be squared");
+
+ analyzePattern(mat);
+ factorize(mat);
+
+ m_iparm(IPARM_MATRIX_VERIFICATION) = API_NO;
+ m_isInitialized = m_factorizationIsOk;
+}
+
+
+template <class Derived>
+void PastixBase<Derived>::analyzePattern(ColSpMatrix& mat)
+{
+ eigen_assert(m_initisOk && "The initialization of PaSTiX failed");
+
+ // clean previous calls
+ if(m_size>0)
+ clean();
+
+ m_size = mat.rows();
+ m_perm.resize(m_size);
+ m_invp.resize(m_size);
+
+ m_iparm(IPARM_START_TASK) = API_TASK_ORDERING;
+ m_iparm(IPARM_END_TASK) = API_TASK_ANALYSE;
+ internal::eigen_pastix(&m_pastixdata, MPI_COMM_WORLD, m_size, mat.outerIndexPtr(), mat.innerIndexPtr(),
+ mat.valuePtr(), m_perm.data(), m_invp.data(), 0, 0, m_iparm.data(), m_dparm.data());
+
+ // Check the returned error
+ if(m_iparm(IPARM_ERROR_NUMBER))
+ {
+ m_info = NumericalIssue;
+ m_analysisIsOk = false;
+ }
+ else
+ {
+ m_info = Success;
+ m_analysisIsOk = true;
+ }
+}
+
+template <class Derived>
+void PastixBase<Derived>::factorize(ColSpMatrix& mat)
+{
+// if(&m_cpyMat != &mat) m_cpyMat = mat;
+ eigen_assert(m_analysisIsOk && "The analysis phase should be called before the factorization phase");
+ m_iparm(IPARM_START_TASK) = API_TASK_NUMFACT;
+ m_iparm(IPARM_END_TASK) = API_TASK_NUMFACT;
+ m_size = mat.rows();
+
+ internal::eigen_pastix(&m_pastixdata, MPI_COMM_WORLD, m_size, mat.outerIndexPtr(), mat.innerIndexPtr(),
+ mat.valuePtr(), m_perm.data(), m_invp.data(), 0, 0, m_iparm.data(), m_dparm.data());
+
+ // Check the returned error
+ if(m_iparm(IPARM_ERROR_NUMBER))
+ {
+ m_info = NumericalIssue;
+ m_factorizationIsOk = false;
+ m_isInitialized = false;
+ }
+ else
+ {
+ m_info = Success;
+ m_factorizationIsOk = true;
+ m_isInitialized = true;
+ }
+}
+
+/* Solve the system */
+template<typename Base>
+template<typename Rhs,typename Dest>
+bool PastixBase<Base>::_solve (const MatrixBase<Rhs> &b, MatrixBase<Dest> &x) const
+{
+ eigen_assert(m_isInitialized && "The matrix should be factorized first");
+ EIGEN_STATIC_ASSERT((Dest::Flags&RowMajorBit)==0,
+ THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES);
+ int rhs = 1;
+
+ x = b; /* on return, x is overwritten by the computed solution */
+
+ for (int i = 0; i < b.cols(); i++){
+ m_iparm[IPARM_START_TASK] = API_TASK_SOLVE;
+ m_iparm[IPARM_END_TASK] = API_TASK_REFINE;
+
+ internal::eigen_pastix(&m_pastixdata, MPI_COMM_WORLD, x.rows(), 0, 0, 0,
+ m_perm.data(), m_invp.data(), &x(0, i), rhs, m_iparm.data(), m_dparm.data());
+ }
+
+ // Check the returned error
+ m_info = m_iparm(IPARM_ERROR_NUMBER)==0 ? Success : NumericalIssue;
+
+ return m_iparm(IPARM_ERROR_NUMBER)==0;
+}
+
+/** \ingroup PaStiXSupport_Module
+ * \class PastixLU
+ * \brief Sparse direct LU solver based on PaStiX library
+ *
+ * This class is used to solve the linear systems A.X = B with a supernodal LU
+ * factorization in the PaStiX library. The matrix A should be squared and nonsingular
+ * PaStiX requires that the matrix A has a symmetric structural pattern.
+ * This interface can symmetrize the input matrix otherwise.
+ * The vectors or matrices X and B can be either dense or sparse.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam IsStrSym Indicates if the input matrix has a symmetric pattern, default is false
+ * NOTE : Note that if the analysis and factorization phase are called separately,
+ * the input matrix will be symmetrized at each call, hence it is advised to
+ * symmetrize the matrix in a end-user program and set \p IsStrSym to true
+ *
+ * \sa \ref TutorialSparseDirectSolvers
+ *
+ */
+template<typename _MatrixType, bool IsStrSym>
+class PastixLU : public PastixBase< PastixLU<_MatrixType> >
+{
+ public:
+ typedef _MatrixType MatrixType;
+ typedef PastixBase<PastixLU<MatrixType> > Base;
+ typedef typename Base::ColSpMatrix ColSpMatrix;
+ typedef typename MatrixType::Index Index;
+
+ public:
+ PastixLU() : Base()
+ {
+ init();
+ }
+
+ PastixLU(const MatrixType& matrix):Base()
+ {
+ init();
+ compute(matrix);
+ }
+ /** Compute the LU supernodal factorization of \p matrix.
+ * iparm and dparm can be used to tune the PaStiX parameters.
+ * see the PaStiX user's manual
+ * \sa analyzePattern() factorize()
+ */
+ void compute (const MatrixType& matrix)
+ {
+ m_structureIsUptodate = false;
+ ColSpMatrix temp;
+ grabMatrix(matrix, temp);
+ Base::compute(temp);
+ }
+ /** Compute the LU symbolic factorization of \p matrix using its sparsity pattern.
+ * Several ordering methods can be used at this step. See the PaStiX user's manual.
+ * The result of this operation can be used with successive matrices having the same pattern as \p matrix
+ * \sa factorize()
+ */
+ void analyzePattern(const MatrixType& matrix)
+ {
+ m_structureIsUptodate = false;
+ ColSpMatrix temp;
+ grabMatrix(matrix, temp);
+ Base::analyzePattern(temp);
+ }
+
+ /** Compute the LU supernodal factorization of \p matrix
+ * WARNING The matrix \p matrix should have the same structural pattern
+ * as the same used in the analysis phase.
+ * \sa analyzePattern()
+ */
+ void factorize(const MatrixType& matrix)
+ {
+ ColSpMatrix temp;
+ grabMatrix(matrix, temp);
+ Base::factorize(temp);
+ }
+ protected:
+
+ void init()
+ {
+ m_structureIsUptodate = false;
+ m_iparm(IPARM_SYM) = API_SYM_NO;
+ m_iparm(IPARM_FACTORIZATION) = API_FACT_LU;
+ }
+
+ void grabMatrix(const MatrixType& matrix, ColSpMatrix& out)
+ {
+ if(IsStrSym)
+ out = matrix;
+ else
+ {
+ if(!m_structureIsUptodate)
+ {
+ // update the transposed structure
+ m_transposedStructure = matrix.transpose();
+
+ // Set the elements of the matrix to zero
+ for (Index j=0; j<m_transposedStructure.outerSize(); ++j)
+ for(typename ColSpMatrix::InnerIterator it(m_transposedStructure, j); it; ++it)
+ it.valueRef() = 0.0;
+
+ m_structureIsUptodate = true;
+ }
+
+ out = m_transposedStructure + matrix;
+ }
+ internal::c_to_fortran_numbering(out);
+ }
+
+ using Base::m_iparm;
+ using Base::m_dparm;
+
+ ColSpMatrix m_transposedStructure;
+ bool m_structureIsUptodate;
+};
+
+/** \ingroup PaStiXSupport_Module
+ * \class PastixLLT
+ * \brief A sparse direct supernodal Cholesky (LLT) factorization and solver based on the PaStiX library
+ *
+ * This class is used to solve the linear systems A.X = B via a LL^T supernodal Cholesky factorization
+ * available in the PaStiX library. The matrix A should be symmetric and positive definite
+ * WARNING Selfadjoint complex matrices are not supported in the current version of PaStiX
+ * The vectors or matrices X and B can be either dense or sparse
+ *
+ * \tparam MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam UpLo The part of the matrix to use : Lower or Upper. The default is Lower as required by PaStiX
+ *
+ * \sa \ref TutorialSparseDirectSolvers
+ */
+template<typename _MatrixType, int _UpLo>
+class PastixLLT : public PastixBase< PastixLLT<_MatrixType, _UpLo> >
+{
+ public:
+ typedef _MatrixType MatrixType;
+ typedef PastixBase<PastixLLT<MatrixType, _UpLo> > Base;
+ typedef typename Base::ColSpMatrix ColSpMatrix;
+
+ public:
+ enum { UpLo = _UpLo };
+ PastixLLT() : Base()
+ {
+ init();
+ }
+
+ PastixLLT(const MatrixType& matrix):Base()
+ {
+ init();
+ compute(matrix);
+ }
+
+ /** Compute the L factor of the LL^T supernodal factorization of \p matrix
+ * \sa analyzePattern() factorize()
+ */
+ void compute (const MatrixType& matrix)
+ {
+ ColSpMatrix temp;
+ grabMatrix(matrix, temp);
+ Base::compute(temp);
+ }
+
+ /** Compute the LL^T symbolic factorization of \p matrix using its sparsity pattern
+ * The result of this operation can be used with successive matrices having the same pattern as \p matrix
+ * \sa factorize()
+ */
+ void analyzePattern(const MatrixType& matrix)
+ {
+ ColSpMatrix temp;
+ grabMatrix(matrix, temp);
+ Base::analyzePattern(temp);
+ }
+ /** Compute the LL^T supernodal numerical factorization of \p matrix
+ * \sa analyzePattern()
+ */
+ void factorize(const MatrixType& matrix)
+ {
+ ColSpMatrix temp;
+ grabMatrix(matrix, temp);
+ Base::factorize(temp);
+ }
+ protected:
+ using Base::m_iparm;
+
+ void init()
+ {
+ m_iparm(IPARM_SYM) = API_SYM_YES;
+ m_iparm(IPARM_FACTORIZATION) = API_FACT_LLT;
+ }
+
+ void grabMatrix(const MatrixType& matrix, ColSpMatrix& out)
+ {
+ // Pastix supports only lower, column-major matrices
+ out.template selfadjointView<Lower>() = matrix.template selfadjointView<UpLo>();
+ internal::c_to_fortran_numbering(out);
+ }
+};
+
+/** \ingroup PaStiXSupport_Module
+ * \class PastixLDLT
+ * \brief A sparse direct supernodal Cholesky (LLT) factorization and solver based on the PaStiX library
+ *
+ * This class is used to solve the linear systems A.X = B via a LDL^T supernodal Cholesky factorization
+ * available in the PaStiX library. The matrix A should be symmetric and positive definite
+ * WARNING Selfadjoint complex matrices are not supported in the current version of PaStiX
+ * The vectors or matrices X and B can be either dense or sparse
+ *
+ * \tparam MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam UpLo The part of the matrix to use : Lower or Upper. The default is Lower as required by PaStiX
+ *
+ * \sa \ref TutorialSparseDirectSolvers
+ */
+template<typename _MatrixType, int _UpLo>
+class PastixLDLT : public PastixBase< PastixLDLT<_MatrixType, _UpLo> >
+{
+ public:
+ typedef _MatrixType MatrixType;
+ typedef PastixBase<PastixLDLT<MatrixType, _UpLo> > Base;
+ typedef typename Base::ColSpMatrix ColSpMatrix;
+
+ public:
+ enum { UpLo = _UpLo };
+ PastixLDLT():Base()
+ {
+ init();
+ }
+
+ PastixLDLT(const MatrixType& matrix):Base()
+ {
+ init();
+ compute(matrix);
+ }
+
+ /** Compute the L and D factors of the LDL^T factorization of \p matrix
+ * \sa analyzePattern() factorize()
+ */
+ void compute (const MatrixType& matrix)
+ {
+ ColSpMatrix temp;
+ grabMatrix(matrix, temp);
+ Base::compute(temp);
+ }
+
+ /** Compute the LDL^T symbolic factorization of \p matrix using its sparsity pattern
+ * The result of this operation can be used with successive matrices having the same pattern as \p matrix
+ * \sa factorize()
+ */
+ void analyzePattern(const MatrixType& matrix)
+ {
+ ColSpMatrix temp;
+ grabMatrix(matrix, temp);
+ Base::analyzePattern(temp);
+ }
+ /** Compute the LDL^T supernodal numerical factorization of \p matrix
+ *
+ */
+ void factorize(const MatrixType& matrix)
+ {
+ ColSpMatrix temp;
+ grabMatrix(matrix, temp);
+ Base::factorize(temp);
+ }
+
+ protected:
+ using Base::m_iparm;
+
+ void init()
+ {
+ m_iparm(IPARM_SYM) = API_SYM_YES;
+ m_iparm(IPARM_FACTORIZATION) = API_FACT_LDLT;
+ }
+
+ void grabMatrix(const MatrixType& matrix, ColSpMatrix& out)
+ {
+ // Pastix supports only lower, column-major matrices
+ out.template selfadjointView<Lower>() = matrix.template selfadjointView<UpLo>();
+ internal::c_to_fortran_numbering(out);
+ }
+};
+
+namespace internal {
+
+template<typename _MatrixType, typename Rhs>
+struct solve_retval<PastixBase<_MatrixType>, Rhs>
+ : solve_retval_base<PastixBase<_MatrixType>, Rhs>
+{
+ typedef PastixBase<_MatrixType> Dec;
+ EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec()._solve(rhs(),dst);
+ }
+};
+
+template<typename _MatrixType, typename Rhs>
+struct sparse_solve_retval<PastixBase<_MatrixType>, Rhs>
+ : sparse_solve_retval_base<PastixBase<_MatrixType>, Rhs>
+{
+ typedef PastixBase<_MatrixType> Dec;
+ EIGEN_MAKE_SPARSE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec()._solve_sparse(rhs(),dst);
+ }
+};
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif
diff --git a/extern/Eigen3/Eigen/src/PardisoSupport/PardisoSupport.h b/extern/Eigen3/Eigen/src/PardisoSupport/PardisoSupport.h
new file mode 100644
index 00000000000..e6defc8c39e
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/PardisoSupport/PardisoSupport.h
@@ -0,0 +1,614 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL PARDISO
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_PARDISOSUPPORT_H
+#define EIGEN_PARDISOSUPPORT_H
+
+namespace Eigen {
+
+template<typename _MatrixType> class PardisoLU;
+template<typename _MatrixType, int Options=Upper> class PardisoLLT;
+template<typename _MatrixType, int Options=Upper> class PardisoLDLT;
+
+namespace internal
+{
+ template<typename Index>
+ struct pardiso_run_selector
+ {
+ static Index run( _MKL_DSS_HANDLE_t pt, Index maxfct, Index mnum, Index type, Index phase, Index n, void *a,
+ Index *ia, Index *ja, Index *perm, Index nrhs, Index *iparm, Index msglvl, void *b, void *x)
+ {
+ Index error = 0;
+ ::pardiso(pt, &maxfct, &mnum, &type, &phase, &n, a, ia, ja, perm, &nrhs, iparm, &msglvl, b, x, &error);
+ return error;
+ }
+ };
+ template<>
+ struct pardiso_run_selector<long long int>
+ {
+ typedef long long int Index;
+ static Index run( _MKL_DSS_HANDLE_t pt, Index maxfct, Index mnum, Index type, Index phase, Index n, void *a,
+ Index *ia, Index *ja, Index *perm, Index nrhs, Index *iparm, Index msglvl, void *b, void *x)
+ {
+ Index error = 0;
+ ::pardiso_64(pt, &maxfct, &mnum, &type, &phase, &n, a, ia, ja, perm, &nrhs, iparm, &msglvl, b, x, &error);
+ return error;
+ }
+ };
+
+ template<class Pardiso> struct pardiso_traits;
+
+ template<typename _MatrixType>
+ struct pardiso_traits< PardisoLU<_MatrixType> >
+ {
+ typedef _MatrixType MatrixType;
+ typedef typename _MatrixType::Scalar Scalar;
+ typedef typename _MatrixType::RealScalar RealScalar;
+ typedef typename _MatrixType::Index Index;
+ };
+
+ template<typename _MatrixType, int Options>
+ struct pardiso_traits< PardisoLLT<_MatrixType, Options> >
+ {
+ typedef _MatrixType MatrixType;
+ typedef typename _MatrixType::Scalar Scalar;
+ typedef typename _MatrixType::RealScalar RealScalar;
+ typedef typename _MatrixType::Index Index;
+ };
+
+ template<typename _MatrixType, int Options>
+ struct pardiso_traits< PardisoLDLT<_MatrixType, Options> >
+ {
+ typedef _MatrixType MatrixType;
+ typedef typename _MatrixType::Scalar Scalar;
+ typedef typename _MatrixType::RealScalar RealScalar;
+ typedef typename _MatrixType::Index Index;
+ };
+
+}
+
+template<class Derived>
+class PardisoImpl
+{
+ typedef internal::pardiso_traits<Derived> Traits;
+ public:
+ typedef typename Traits::MatrixType MatrixType;
+ typedef typename Traits::Scalar Scalar;
+ typedef typename Traits::RealScalar RealScalar;
+ typedef typename Traits::Index Index;
+ typedef SparseMatrix<Scalar,RowMajor,Index> SparseMatrixType;
+ typedef Matrix<Scalar,Dynamic,1> VectorType;
+ typedef Matrix<Index, 1, MatrixType::ColsAtCompileTime> IntRowVectorType;
+ typedef Matrix<Index, MatrixType::RowsAtCompileTime, 1> IntColVectorType;
+ enum {
+ ScalarIsComplex = NumTraits<Scalar>::IsComplex
+ };
+
+ PardisoImpl()
+ {
+ eigen_assert((sizeof(Index) >= sizeof(_INTEGER_t) && sizeof(Index) <= 8) && "Non-supported index type");
+ m_iparm.setZero();
+ m_msglvl = 0; // No output
+ m_initialized = false;
+ }
+
+ ~PardisoImpl()
+ {
+ pardisoRelease();
+ }
+
+ inline Index cols() const { return m_size; }
+ inline Index rows() const { return m_size; }
+
+ /** \brief Reports whether previous computation was successful.
+ *
+ * \returns \c Success if computation was succesful,
+ * \c NumericalIssue if the matrix appears to be negative.
+ */
+ ComputationInfo info() const
+ {
+ eigen_assert(m_initialized && "Decomposition is not initialized.");
+ return m_info;
+ }
+
+ /** \warning for advanced usage only.
+ * \returns a reference to the parameter array controlling PARDISO.
+ * See the PARDISO manual to know how to use it. */
+ Array<Index,64,1>& pardisoParameterArray()
+ {
+ return m_iparm;
+ }
+
+ /** Performs a symbolic decomposition on the sparcity of \a matrix.
+ *
+ * This function is particularly useful when solving for several problems having the same structure.
+ *
+ * \sa factorize()
+ */
+ Derived& analyzePattern(const MatrixType& matrix);
+
+ /** Performs a numeric decomposition of \a matrix
+ *
+ * The given matrix must has the same sparcity than the matrix on which the symbolic decomposition has been performed.
+ *
+ * \sa analyzePattern()
+ */
+ Derived& factorize(const MatrixType& matrix);
+
+ Derived& compute(const MatrixType& matrix);
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs>
+ inline const internal::solve_retval<PardisoImpl, Rhs>
+ solve(const MatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_initialized && "Pardiso solver is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "PardisoImpl::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::solve_retval<PardisoImpl, Rhs>(*this, b.derived());
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs>
+ inline const internal::sparse_solve_retval<PardisoImpl, Rhs>
+ solve(const SparseMatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_initialized && "Pardiso solver is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "PardisoImpl::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::sparse_solve_retval<PardisoImpl, Rhs>(*this, b.derived());
+ }
+
+ Derived& derived()
+ {
+ return *static_cast<Derived*>(this);
+ }
+ const Derived& derived() const
+ {
+ return *static_cast<const Derived*>(this);
+ }
+
+ template<typename BDerived, typename XDerived>
+ bool _solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived>& x) const;
+
+ /** \internal */
+ template<typename Rhs, typename DestScalar, int DestOptions, typename DestIndex>
+ void _solve_sparse(const Rhs& b, SparseMatrix<DestScalar,DestOptions,DestIndex> &dest) const
+ {
+ eigen_assert(m_size==b.rows());
+
+ // we process the sparse rhs per block of NbColsAtOnce columns temporarily stored into a dense matrix.
+ static const int NbColsAtOnce = 4;
+ int rhsCols = b.cols();
+ int size = b.rows();
+ // Pardiso cannot solve in-place,
+ // so we need two temporaries
+ Eigen::Matrix<DestScalar,Dynamic,Dynamic,ColMajor> tmp_rhs(size,rhsCols);
+ Eigen::Matrix<DestScalar,Dynamic,Dynamic,ColMajor> tmp_res(size,rhsCols);
+ for(int k=0; k<rhsCols; k+=NbColsAtOnce)
+ {
+ int actualCols = std::min<int>(rhsCols-k, NbColsAtOnce);
+ tmp_rhs.leftCols(actualCols) = b.middleCols(k,actualCols);
+ tmp_res.leftCols(actualCols) = derived().solve(tmp_rhs.leftCols(actualCols));
+ dest.middleCols(k,actualCols) = tmp_res.leftCols(actualCols).sparseView();
+ }
+ }
+
+ protected:
+ void pardisoRelease()
+ {
+ if(m_initialized) // Factorization ran at least once
+ {
+ internal::pardiso_run_selector<Index>::run(m_pt, 1, 1, m_type, -1, m_size, 0, 0, 0, m_perm.data(), 0,
+ m_iparm.data(), m_msglvl, 0, 0);
+ }
+ }
+
+ void pardisoInit(int type)
+ {
+ m_type = type;
+ bool symmetric = abs(m_type) < 10;
+ m_iparm[0] = 1; // No solver default
+ m_iparm[1] = 3; // use Metis for the ordering
+ m_iparm[2] = 1; // Numbers of processors, value of OMP_NUM_THREADS
+ m_iparm[3] = 0; // No iterative-direct algorithm
+ m_iparm[4] = 0; // No user fill-in reducing permutation
+ m_iparm[5] = 0; // Write solution into x
+ m_iparm[6] = 0; // Not in use
+ m_iparm[7] = 2; // Max numbers of iterative refinement steps
+ m_iparm[8] = 0; // Not in use
+ m_iparm[9] = 13; // Perturb the pivot elements with 1E-13
+ m_iparm[10] = symmetric ? 0 : 1; // Use nonsymmetric permutation and scaling MPS
+ m_iparm[11] = 0; // Not in use
+ m_iparm[12] = symmetric ? 0 : 1; // Maximum weighted matching algorithm is switched-off (default for symmetric).
+ // Try m_iparm[12] = 1 in case of inappropriate accuracy
+ m_iparm[13] = 0; // Output: Number of perturbed pivots
+ m_iparm[14] = 0; // Not in use
+ m_iparm[15] = 0; // Not in use
+ m_iparm[16] = 0; // Not in use
+ m_iparm[17] = -1; // Output: Number of nonzeros in the factor LU
+ m_iparm[18] = -1; // Output: Mflops for LU factorization
+ m_iparm[19] = 0; // Output: Numbers of CG Iterations
+
+ m_iparm[20] = 0; // 1x1 pivoting
+ m_iparm[26] = 0; // No matrix checker
+ m_iparm[27] = (sizeof(RealScalar) == 4) ? 1 : 0;
+ m_iparm[34] = 1; // C indexing
+ m_iparm[59] = 1; // Automatic switch between In-Core and Out-of-Core modes
+ }
+
+ protected:
+ // cached data to reduce reallocation, etc.
+
+ void manageErrorCode(Index error)
+ {
+ switch(error)
+ {
+ case 0:
+ m_info = Success;
+ break;
+ case -4:
+ case -7:
+ m_info = NumericalIssue;
+ break;
+ default:
+ m_info = InvalidInput;
+ }
+ }
+
+ mutable SparseMatrixType m_matrix;
+ ComputationInfo m_info;
+ bool m_initialized, m_analysisIsOk, m_factorizationIsOk;
+ Index m_type, m_msglvl;
+ mutable void *m_pt[64];
+ mutable Array<Index,64,1> m_iparm;
+ mutable IntColVectorType m_perm;
+ Index m_size;
+
+ private:
+ PardisoImpl(PardisoImpl &) {}
+};
+
+template<class Derived>
+Derived& PardisoImpl<Derived>::compute(const MatrixType& a)
+{
+ m_size = a.rows();
+ eigen_assert(a.rows() == a.cols());
+
+ pardisoRelease();
+ memset(m_pt, 0, sizeof(m_pt));
+ m_perm.setZero(m_size);
+ derived().getMatrix(a);
+
+ Index error;
+ error = internal::pardiso_run_selector<Index>::run(m_pt, 1, 1, m_type, 12, m_size,
+ m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(),
+ m_perm.data(), 0, m_iparm.data(), m_msglvl, NULL, NULL);
+
+ manageErrorCode(error);
+ m_analysisIsOk = true;
+ m_factorizationIsOk = true;
+ m_initialized = true;
+ return derived();
+}
+
+template<class Derived>
+Derived& PardisoImpl<Derived>::analyzePattern(const MatrixType& a)
+{
+ m_size = a.rows();
+ eigen_assert(m_size == a.cols());
+
+ pardisoRelease();
+ memset(m_pt, 0, sizeof(m_pt));
+ m_perm.setZero(m_size);
+ derived().getMatrix(a);
+
+ Index error;
+ error = internal::pardiso_run_selector<Index>::run(m_pt, 1, 1, m_type, 11, m_size,
+ m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(),
+ m_perm.data(), 0, m_iparm.data(), m_msglvl, NULL, NULL);
+
+ manageErrorCode(error);
+ m_analysisIsOk = true;
+ m_factorizationIsOk = false;
+ m_initialized = true;
+ return derived();
+}
+
+template<class Derived>
+Derived& PardisoImpl<Derived>::factorize(const MatrixType& a)
+{
+ eigen_assert(m_analysisIsOk && "You must first call analyzePattern()");
+ eigen_assert(m_size == a.rows() && m_size == a.cols());
+
+ derived().getMatrix(a);
+
+ Index error;
+ error = internal::pardiso_run_selector<Index>::run(m_pt, 1, 1, m_type, 22, m_size,
+ m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(),
+ m_perm.data(), 0, m_iparm.data(), m_msglvl, NULL, NULL);
+
+ manageErrorCode(error);
+ m_factorizationIsOk = true;
+ return derived();
+}
+
+template<class Base>
+template<typename BDerived,typename XDerived>
+bool PardisoImpl<Base>::_solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived>& x) const
+{
+ if(m_iparm[0] == 0) // Factorization was not computed
+ return false;
+
+ //Index n = m_matrix.rows();
+ Index nrhs = Index(b.cols());
+ eigen_assert(m_size==b.rows());
+ eigen_assert(((MatrixBase<BDerived>::Flags & RowMajorBit) == 0 || nrhs == 1) && "Row-major right hand sides are not supported");
+ eigen_assert(((MatrixBase<XDerived>::Flags & RowMajorBit) == 0 || nrhs == 1) && "Row-major matrices of unknowns are not supported");
+ eigen_assert(((nrhs == 1) || b.outerStride() == b.rows()));
+
+
+// switch (transposed) {
+// case SvNoTrans : m_iparm[11] = 0 ; break;
+// case SvTranspose : m_iparm[11] = 2 ; break;
+// case SvAdjoint : m_iparm[11] = 1 ; break;
+// default:
+// //std::cerr << "Eigen: transposition option \"" << transposed << "\" not supported by the PARDISO backend\n";
+// m_iparm[11] = 0;
+// }
+
+ Scalar* rhs_ptr = const_cast<Scalar*>(b.derived().data());
+ Matrix<Scalar,Dynamic,Dynamic,ColMajor> tmp;
+
+ // Pardiso cannot solve in-place
+ if(rhs_ptr == x.derived().data())
+ {
+ tmp = b;
+ rhs_ptr = tmp.data();
+ }
+
+ Index error;
+ error = internal::pardiso_run_selector<Index>::run(m_pt, 1, 1, m_type, 33, m_size,
+ m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(),
+ m_perm.data(), nrhs, m_iparm.data(), m_msglvl,
+ rhs_ptr, x.derived().data());
+
+ return error==0;
+}
+
+
+/** \ingroup PardisoSupport_Module
+ * \class PardisoLU
+ * \brief A sparse direct LU factorization and solver based on the PARDISO library
+ *
+ * This class allows to solve for A.X = B sparse linear problems via a direct LU factorization
+ * using the Intel MKL PARDISO library. The sparse matrix A must be squared and invertible.
+ * The vectors or matrices X and B can be either dense or sparse.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ *
+ * \sa \ref TutorialSparseDirectSolvers
+ */
+template<typename MatrixType>
+class PardisoLU : public PardisoImpl< PardisoLU<MatrixType> >
+{
+ protected:
+ typedef PardisoImpl< PardisoLU<MatrixType> > Base;
+ typedef typename Base::Scalar Scalar;
+ typedef typename Base::RealScalar RealScalar;
+ using Base::pardisoInit;
+ using Base::m_matrix;
+ friend class PardisoImpl< PardisoLU<MatrixType> >;
+
+ public:
+
+ using Base::compute;
+ using Base::solve;
+
+ PardisoLU()
+ : Base()
+ {
+ pardisoInit(Base::ScalarIsComplex ? 13 : 11);
+ }
+
+ PardisoLU(const MatrixType& matrix)
+ : Base()
+ {
+ pardisoInit(Base::ScalarIsComplex ? 13 : 11);
+ compute(matrix);
+ }
+ protected:
+ void getMatrix(const MatrixType& matrix)
+ {
+ m_matrix = matrix;
+ }
+
+ private:
+ PardisoLU(PardisoLU& ) {}
+};
+
+/** \ingroup PardisoSupport_Module
+ * \class PardisoLLT
+ * \brief A sparse direct Cholesky (LLT) factorization and solver based on the PARDISO library
+ *
+ * This class allows to solve for A.X = B sparse linear problems via a LL^T Cholesky factorization
+ * using the Intel MKL PARDISO library. The sparse matrix A must be selfajoint and positive definite.
+ * The vectors or matrices X and B can be either dense or sparse.
+ *
+ * \tparam MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam UpLo can be any bitwise combination of Upper, Lower. The default is Upper, meaning only the upper triangular part has to be used.
+ * Upper|Lower can be used to tell both triangular parts can be used as input.
+ *
+ * \sa \ref TutorialSparseDirectSolvers
+ */
+template<typename MatrixType, int _UpLo>
+class PardisoLLT : public PardisoImpl< PardisoLLT<MatrixType,_UpLo> >
+{
+ protected:
+ typedef PardisoImpl< PardisoLLT<MatrixType,_UpLo> > Base;
+ typedef typename Base::Scalar Scalar;
+ typedef typename Base::Index Index;
+ typedef typename Base::RealScalar RealScalar;
+ using Base::pardisoInit;
+ using Base::m_matrix;
+ friend class PardisoImpl< PardisoLLT<MatrixType,_UpLo> >;
+
+ public:
+
+ enum { UpLo = _UpLo };
+ using Base::compute;
+ using Base::solve;
+
+ PardisoLLT()
+ : Base()
+ {
+ pardisoInit(Base::ScalarIsComplex ? 4 : 2);
+ }
+
+ PardisoLLT(const MatrixType& matrix)
+ : Base()
+ {
+ pardisoInit(Base::ScalarIsComplex ? 4 : 2);
+ compute(matrix);
+ }
+
+ protected:
+
+ void getMatrix(const MatrixType& matrix)
+ {
+ // PARDISO supports only upper, row-major matrices
+ PermutationMatrix<Dynamic,Dynamic,Index> p_null;
+ m_matrix.resize(matrix.rows(), matrix.cols());
+ m_matrix.template selfadjointView<Upper>() = matrix.template selfadjointView<UpLo>().twistedBy(p_null);
+ }
+
+ private:
+ PardisoLLT(PardisoLLT& ) {}
+};
+
+/** \ingroup PardisoSupport_Module
+ * \class PardisoLDLT
+ * \brief A sparse direct Cholesky (LDLT) factorization and solver based on the PARDISO library
+ *
+ * This class allows to solve for A.X = B sparse linear problems via a LDL^T Cholesky factorization
+ * using the Intel MKL PARDISO library. The sparse matrix A is assumed to be selfajoint and positive definite.
+ * For complex matrices, A can also be symmetric only, see the \a Options template parameter.
+ * The vectors or matrices X and B can be either dense or sparse.
+ *
+ * \tparam MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam Options can be any bitwise combination of Upper, Lower, and Symmetric. The default is Upper, meaning only the upper triangular part has to be used.
+ * Symmetric can be used for symmetric, non-selfadjoint complex matrices, the default being to assume a selfadjoint matrix.
+ * Upper|Lower can be used to tell both triangular parts can be used as input.
+ *
+ * \sa \ref TutorialSparseDirectSolvers
+ */
+template<typename MatrixType, int Options>
+class PardisoLDLT : public PardisoImpl< PardisoLDLT<MatrixType,Options> >
+{
+ protected:
+ typedef PardisoImpl< PardisoLDLT<MatrixType,Options> > Base;
+ typedef typename Base::Scalar Scalar;
+ typedef typename Base::Index Index;
+ typedef typename Base::RealScalar RealScalar;
+ using Base::pardisoInit;
+ using Base::m_matrix;
+ friend class PardisoImpl< PardisoLDLT<MatrixType,Options> >;
+
+ public:
+
+ using Base::compute;
+ using Base::solve;
+ enum { UpLo = Options&(Upper|Lower) };
+
+ PardisoLDLT()
+ : Base()
+ {
+ pardisoInit(Base::ScalarIsComplex ? ( bool(Options&Symmetric) ? 6 : -4 ) : -2);
+ }
+
+ PardisoLDLT(const MatrixType& matrix)
+ : Base()
+ {
+ pardisoInit(Base::ScalarIsComplex ? ( bool(Options&Symmetric) ? 6 : -4 ) : -2);
+ compute(matrix);
+ }
+
+ void getMatrix(const MatrixType& matrix)
+ {
+ // PARDISO supports only upper, row-major matrices
+ PermutationMatrix<Dynamic,Dynamic,Index> p_null;
+ m_matrix.resize(matrix.rows(), matrix.cols());
+ m_matrix.template selfadjointView<Upper>() = matrix.template selfadjointView<UpLo>().twistedBy(p_null);
+ }
+
+ private:
+ PardisoLDLT(PardisoLDLT& ) {}
+};
+
+namespace internal {
+
+template<typename _Derived, typename Rhs>
+struct solve_retval<PardisoImpl<_Derived>, Rhs>
+ : solve_retval_base<PardisoImpl<_Derived>, Rhs>
+{
+ typedef PardisoImpl<_Derived> Dec;
+ EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec()._solve(rhs(),dst);
+ }
+};
+
+template<typename Derived, typename Rhs>
+struct sparse_solve_retval<PardisoImpl<Derived>, Rhs>
+ : sparse_solve_retval_base<PardisoImpl<Derived>, Rhs>
+{
+ typedef PardisoImpl<Derived> Dec;
+ EIGEN_MAKE_SPARSE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec().derived()._solve_sparse(rhs(),dst);
+ }
+};
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_PARDISOSUPPORT_H
diff --git a/extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR.h b/extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR.h
index f04c6038d6a..2daa23cc354 100644
--- a/extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR.h
+++ b/extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR.h
@@ -4,28 +4,15 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COLPIVOTINGHOUSEHOLDERQR_H
#define EIGEN_COLPIVOTINGHOUSEHOLDERQR_H
+namespace Eigen {
+
/** \ingroup QR_Module
*
* \class ColPivHouseholderQR
@@ -528,5 +515,6 @@ MatrixBase<Derived>::colPivHouseholderQr() const
return ColPivHouseholderQR<PlainObject>(eval());
}
+} // end namespace Eigen
#endif // EIGEN_COLPIVOTINGHOUSEHOLDERQR_H
diff --git a/extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR_MKL.h b/extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR_MKL.h
new file mode 100644
index 00000000000..745ecf8be98
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR_MKL.h
@@ -0,0 +1,98 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Householder QR decomposition of a matrix with column pivoting based on
+ * LAPACKE_?geqp3 function.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_COLPIVOTINGHOUSEHOLDERQR_MKL_H
+#define EIGEN_COLPIVOTINGHOUSEHOLDERQR_MKL_H
+
+#include "Eigen/src/Core/util/MKL_support.h"
+
+namespace Eigen {
+
+/** \internal Specialization for the data types supported by MKL */
+
+#define EIGEN_MKL_QR_COLPIV(EIGTYPE, MKLTYPE, MKLPREFIX, EIGCOLROW, MKLCOLROW) \
+template<> inline\
+ColPivHouseholderQR<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW, Dynamic, Dynamic> >& \
+ColPivHouseholderQR<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW, Dynamic, Dynamic> >::compute( \
+ const Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW, Dynamic, Dynamic>& matrix) \
+\
+{ \
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW, Dynamic, Dynamic> MatrixType; \
+ typedef MatrixType::Scalar Scalar; \
+ typedef MatrixType::RealScalar RealScalar; \
+ Index rows = matrix.rows();\
+ Index cols = matrix.cols();\
+ Index size = matrix.diagonalSize();\
+\
+ m_qr = matrix;\
+ m_hCoeffs.resize(size);\
+\
+ m_colsTranspositions.resize(cols);\
+ /*Index number_of_transpositions = 0;*/ \
+\
+ m_nonzero_pivots = 0; \
+ m_maxpivot = RealScalar(0);\
+ m_colsPermutation.resize(cols); \
+ m_colsPermutation.indices().setZero(); \
+\
+ lapack_int lda = m_qr.outerStride(), i; \
+ lapack_int matrix_order = MKLCOLROW; \
+ LAPACKE_##MKLPREFIX##geqp3( matrix_order, rows, cols, (MKLTYPE*)m_qr.data(), lda, (lapack_int*)m_colsPermutation.indices().data(), (MKLTYPE*)m_hCoeffs.data()); \
+ m_isInitialized = true; \
+ m_maxpivot=m_qr.diagonal().cwiseAbs().maxCoeff(); \
+ m_hCoeffs.adjointInPlace(); \
+ RealScalar premultiplied_threshold = internal::abs(m_maxpivot) * threshold(); \
+ lapack_int *perm = m_colsPermutation.indices().data(); \
+ for(i=0;i<size;i++) { \
+ m_nonzero_pivots += (internal::abs(m_qr.coeff(i,i)) > premultiplied_threshold);\
+ } \
+ for(i=0;i<cols;i++) perm[i]--;\
+\
+ /*m_det_pq = (number_of_transpositions%2) ? -1 : 1; // TODO: It's not needed now; fix upon availability in Eigen */ \
+\
+ return *this; \
+}
+
+EIGEN_MKL_QR_COLPIV(double, double, d, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_QR_COLPIV(float, float, s, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_QR_COLPIV(dcomplex, MKL_Complex16, z, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_QR_COLPIV(scomplex, MKL_Complex8, c, ColMajor, LAPACK_COL_MAJOR)
+
+EIGEN_MKL_QR_COLPIV(double, double, d, RowMajor, LAPACK_ROW_MAJOR)
+EIGEN_MKL_QR_COLPIV(float, float, s, RowMajor, LAPACK_ROW_MAJOR)
+EIGEN_MKL_QR_COLPIV(dcomplex, MKL_Complex16, z, RowMajor, LAPACK_ROW_MAJOR)
+EIGEN_MKL_QR_COLPIV(scomplex, MKL_Complex8, c, RowMajor, LAPACK_ROW_MAJOR)
+
+} // end namespace Eigen
+
+#endif // EIGEN_COLPIVOTINGHOUSEHOLDERQR_MKL_H
diff --git a/extern/Eigen3/Eigen/src/QR/FullPivHouseholderQR.h b/extern/Eigen3/Eigen/src/QR/FullPivHouseholderQR.h
index dde3013be9d..37898e77cc2 100644
--- a/extern/Eigen3/Eigen/src/QR/FullPivHouseholderQR.h
+++ b/extern/Eigen3/Eigen/src/QR/FullPivHouseholderQR.h
@@ -4,28 +4,27 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_FULLPIVOTINGHOUSEHOLDERQR_H
#define EIGEN_FULLPIVOTINGHOUSEHOLDERQR_H
+namespace Eigen {
+
+namespace internal {
+
+template<typename MatrixType> struct FullPivHouseholderQRMatrixQReturnType;
+
+template<typename MatrixType>
+struct traits<FullPivHouseholderQRMatrixQReturnType<MatrixType> >
+{
+ typedef typename MatrixType::PlainObject ReturnType;
+};
+
+}
+
/** \ingroup QR_Module
*
* \class FullPivHouseholderQR
@@ -62,7 +61,7 @@ template<typename _MatrixType> class FullPivHouseholderQR
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::RealScalar RealScalar;
typedef typename MatrixType::Index Index;
- typedef Matrix<Scalar, RowsAtCompileTime, RowsAtCompileTime, Options, MaxRowsAtCompileTime, MaxRowsAtCompileTime> MatrixQType;
+ typedef internal::FullPivHouseholderQRMatrixQReturnType<MatrixType> MatrixQReturnType;
typedef typename internal::plain_diag_type<MatrixType>::type HCoeffsType;
typedef Matrix<Index, 1, ColsAtCompileTime, RowMajor, 1, MaxColsAtCompileTime> IntRowVectorType;
typedef PermutationMatrix<ColsAtCompileTime, MaxColsAtCompileTime> PermutationType;
@@ -139,7 +138,9 @@ template<typename _MatrixType> class FullPivHouseholderQR
return internal::solve_retval<FullPivHouseholderQR, Rhs>(*this, b.derived());
}
- MatrixQType matrixQ(void) const;
+ /** \returns Expression object representing the matrix Q
+ */
+ MatrixQReturnType matrixQ(void) const;
/** \returns a reference to the matrix where the Householder QR decomposition is stored
*/
@@ -508,28 +509,73 @@ struct solve_retval<FullPivHouseholderQR<_MatrixType>, Rhs>
}
};
+/** \ingroup QR_Module
+ *
+ * \brief Expression type for return value of FullPivHouseholderQR::matrixQ()
+ *
+ * \tparam MatrixType type of underlying dense matrix
+ */
+template<typename MatrixType> struct FullPivHouseholderQRMatrixQReturnType
+ : public ReturnByValue<FullPivHouseholderQRMatrixQReturnType<MatrixType> >
+{
+public:
+ typedef typename MatrixType::Index Index;
+ typedef typename internal::plain_col_type<MatrixType, Index>::type IntColVectorType;
+ typedef typename internal::plain_diag_type<MatrixType>::type HCoeffsType;
+ typedef Matrix<typename MatrixType::Scalar, 1, MatrixType::RowsAtCompileTime, RowMajor, 1,
+ MatrixType::MaxRowsAtCompileTime> WorkVectorType;
+
+ FullPivHouseholderQRMatrixQReturnType(const MatrixType& qr,
+ const HCoeffsType& hCoeffs,
+ const IntColVectorType& rowsTranspositions)
+ : m_qr(qr),
+ m_hCoeffs(hCoeffs),
+ m_rowsTranspositions(rowsTranspositions)
+ {}
+
+ template <typename ResultType>
+ void evalTo(ResultType& result) const
+ {
+ const Index rows = m_qr.rows();
+ WorkVectorType workspace(rows);
+ evalTo(result, workspace);
+ }
+
+ template <typename ResultType>
+ void evalTo(ResultType& result, WorkVectorType& workspace) const
+ {
+ // compute the product H'_0 H'_1 ... H'_n-1,
+ // where H_k is the k-th Householder transformation I - h_k v_k v_k'
+ // and v_k is the k-th Householder vector [1,m_qr(k+1,k), m_qr(k+2,k), ...]
+ const Index rows = m_qr.rows();
+ const Index cols = m_qr.cols();
+ const Index size = (std::min)(rows, cols);
+ workspace.resize(rows);
+ result.setIdentity(rows, rows);
+ for (Index k = size-1; k >= 0; k--)
+ {
+ result.block(k, k, rows-k, rows-k)
+ .applyHouseholderOnTheLeft(m_qr.col(k).tail(rows-k-1), internal::conj(m_hCoeffs.coeff(k)), &workspace.coeffRef(k));
+ result.row(k).swap(result.row(m_rowsTranspositions.coeff(k)));
+ }
+ }
+
+ Index rows() const { return m_qr.rows(); }
+ Index cols() const { return m_qr.rows(); }
+
+protected:
+ typename MatrixType::Nested m_qr;
+ typename HCoeffsType::Nested m_hCoeffs;
+ typename IntColVectorType::Nested m_rowsTranspositions;
+};
+
} // end namespace internal
-/** \returns the matrix Q */
template<typename MatrixType>
-typename FullPivHouseholderQR<MatrixType>::MatrixQType FullPivHouseholderQR<MatrixType>::matrixQ() const
+inline typename FullPivHouseholderQR<MatrixType>::MatrixQReturnType FullPivHouseholderQR<MatrixType>::matrixQ() const
{
eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
- // compute the product H'_0 H'_1 ... H'_n-1,
- // where H_k is the k-th Householder transformation I - h_k v_k v_k'
- // and v_k is the k-th Householder vector [1,m_qr(k+1,k), m_qr(k+2,k), ...]
- Index rows = m_qr.rows();
- Index cols = m_qr.cols();
- Index size = (std::min)(rows,cols);
- MatrixQType res = MatrixQType::Identity(rows, rows);
- Matrix<Scalar,1,MatrixType::RowsAtCompileTime> temp(rows);
- for (Index k = size-1; k >= 0; k--)
- {
- res.block(k, k, rows-k, rows-k)
- .applyHouseholderOnTheLeft(m_qr.col(k).tail(rows-k-1), internal::conj(m_hCoeffs.coeff(k)), &temp.coeffRef(k));
- res.row(k).swap(res.row(m_rows_transpositions.coeff(k)));
- }
- return res;
+ return MatrixQReturnType(m_qr, m_hCoeffs, m_rows_transpositions);
}
/** \return the full-pivoting Householder QR decomposition of \c *this.
@@ -543,4 +589,6 @@ MatrixBase<Derived>::fullPivHouseholderQr() const
return FullPivHouseholderQR<PlainObject>(eval());
}
+} // end namespace Eigen
+
#endif // EIGEN_FULLPIVOTINGHOUSEHOLDERQR_H
diff --git a/extern/Eigen3/Eigen/src/QR/HouseholderQR.h b/extern/Eigen3/Eigen/src/QR/HouseholderQR.h
index 9ee96de2680..5bcb32c1e18 100644
--- a/extern/Eigen3/Eigen/src/QR/HouseholderQR.h
+++ b/extern/Eigen3/Eigen/src/QR/HouseholderQR.h
@@ -5,28 +5,15 @@
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2010 Vincent Lejeune
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_QR_H
#define EIGEN_QR_H
+namespace Eigen {
+
/** \ingroup QR_Module
*
*
@@ -351,5 +338,6 @@ MatrixBase<Derived>::householderQr() const
return HouseholderQR<PlainObject>(eval());
}
+} // end namespace Eigen
#endif // EIGEN_QR_H
diff --git a/extern/Eigen3/Eigen/src/QR/HouseholderQR_MKL.h b/extern/Eigen3/Eigen/src/QR/HouseholderQR_MKL.h
new file mode 100644
index 00000000000..5313de604d2
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/QR/HouseholderQR_MKL.h
@@ -0,0 +1,69 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Householder QR decomposition of a matrix w/o pivoting based on
+ * LAPACKE_?geqrf function.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_QR_MKL_H
+#define EIGEN_QR_MKL_H
+
+#include "Eigen/src/Core/util/MKL_support.h"
+
+namespace Eigen {
+
+namespace internal {
+
+/** \internal Specialization for the data types supported by MKL */
+
+#define EIGEN_MKL_QR_NOPIV(EIGTYPE, MKLTYPE, MKLPREFIX) \
+template<typename MatrixQR, typename HCoeffs> \
+void householder_qr_inplace_blocked(MatrixQR& mat, HCoeffs& hCoeffs, \
+ typename MatrixQR::Index maxBlockSize=32, \
+ EIGTYPE* tempData = 0) \
+{ \
+ lapack_int m = mat.rows(); \
+ lapack_int n = mat.cols(); \
+ lapack_int lda = mat.outerStride(); \
+ lapack_int matrix_order = (MatrixQR::IsRowMajor) ? LAPACK_ROW_MAJOR : LAPACK_COL_MAJOR; \
+ LAPACKE_##MKLPREFIX##geqrf( matrix_order, m, n, (MKLTYPE*)mat.data(), lda, (MKLTYPE*)hCoeffs.data()); \
+ hCoeffs.adjointInPlace(); \
+\
+}
+
+EIGEN_MKL_QR_NOPIV(double, double, d)
+EIGEN_MKL_QR_NOPIV(float, float, s)
+EIGEN_MKL_QR_NOPIV(dcomplex, MKL_Complex16, z)
+EIGEN_MKL_QR_NOPIV(scomplex, MKL_Complex8, c)
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_QR_MKL_H
diff --git a/extern/Eigen3/Eigen/src/SVD/JacobiSVD.h b/extern/Eigen3/Eigen/src/SVD/JacobiSVD.h
index 3c423095c31..a7dbf073766 100644
--- a/extern/Eigen3/Eigen/src/SVD/JacobiSVD.h
+++ b/extern/Eigen3/Eigen/src/SVD/JacobiSVD.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_JACOBISVD_H
#define EIGEN_JACOBISVD_H
+namespace Eigen {
+
namespace internal {
// forward declaration (needed by ICC)
// the empty body is required by MSVC
@@ -61,9 +48,12 @@ template<typename MatrixType, int QRPreconditioner, int Case,
> struct qr_preconditioner_impl {};
template<typename MatrixType, int QRPreconditioner, int Case>
-struct qr_preconditioner_impl<MatrixType, QRPreconditioner, Case, false>
+class qr_preconditioner_impl<MatrixType, QRPreconditioner, Case, false>
{
- static bool run(JacobiSVD<MatrixType, QRPreconditioner>&, const MatrixType&)
+public:
+ typedef typename MatrixType::Index Index;
+ void allocate(const JacobiSVD<MatrixType, QRPreconditioner>&) {}
+ bool run(JacobiSVD<MatrixType, QRPreconditioner>&, const MatrixType&)
{
return false;
}
@@ -72,134 +62,279 @@ struct qr_preconditioner_impl<MatrixType, QRPreconditioner, Case, false>
/*** preconditioner using FullPivHouseholderQR ***/
template<typename MatrixType>
-struct qr_preconditioner_impl<MatrixType, FullPivHouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols, true>
+class qr_preconditioner_impl<MatrixType, FullPivHouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols, true>
{
- static bool run(JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix)
+public:
+ typedef typename MatrixType::Index Index;
+ typedef typename MatrixType::Scalar Scalar;
+ enum
+ {
+ RowsAtCompileTime = MatrixType::RowsAtCompileTime,
+ MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime
+ };
+ typedef Matrix<Scalar, 1, RowsAtCompileTime, RowMajor, 1, MaxRowsAtCompileTime> WorkspaceType;
+
+ void allocate(const JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner>& svd)
+ {
+ if (svd.rows() != m_qr.rows() || svd.cols() != m_qr.cols())
+ {
+ m_qr = FullPivHouseholderQR<MatrixType>(svd.rows(), svd.cols());
+ }
+ if (svd.m_computeFullU) m_workspace.resize(svd.rows());
+ }
+
+ bool run(JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix)
{
if(matrix.rows() > matrix.cols())
{
- FullPivHouseholderQR<MatrixType> qr(matrix);
- svd.m_workMatrix = qr.matrixQR().block(0,0,matrix.cols(),matrix.cols()).template triangularView<Upper>();
- if(svd.m_computeFullU) svd.m_matrixU = qr.matrixQ();
- if(svd.computeV()) svd.m_matrixV = qr.colsPermutation();
+ m_qr.compute(matrix);
+ svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.cols(),matrix.cols()).template triangularView<Upper>();
+ if(svd.m_computeFullU) m_qr.matrixQ().evalTo(svd.m_matrixU, m_workspace);
+ if(svd.computeV()) svd.m_matrixV = m_qr.colsPermutation();
return true;
}
return false;
}
+private:
+ FullPivHouseholderQR<MatrixType> m_qr;
+ WorkspaceType m_workspace;
};
template<typename MatrixType>
-struct qr_preconditioner_impl<MatrixType, FullPivHouseholderQRPreconditioner, PreconditionIfMoreColsThanRows, true>
+class qr_preconditioner_impl<MatrixType, FullPivHouseholderQRPreconditioner, PreconditionIfMoreColsThanRows, true>
{
- static bool run(JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix)
+public:
+ typedef typename MatrixType::Index Index;
+ typedef typename MatrixType::Scalar Scalar;
+ enum
+ {
+ RowsAtCompileTime = MatrixType::RowsAtCompileTime,
+ ColsAtCompileTime = MatrixType::ColsAtCompileTime,
+ MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
+ MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
+ Options = MatrixType::Options
+ };
+ typedef Matrix<Scalar, ColsAtCompileTime, RowsAtCompileTime, Options, MaxColsAtCompileTime, MaxRowsAtCompileTime>
+ TransposeTypeWithSameStorageOrder;
+
+ void allocate(const JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner>& svd)
+ {
+ if (svd.cols() != m_qr.rows() || svd.rows() != m_qr.cols())
+ {
+ m_qr = FullPivHouseholderQR<TransposeTypeWithSameStorageOrder>(svd.cols(), svd.rows());
+ }
+ m_adjoint.resize(svd.cols(), svd.rows());
+ if (svd.m_computeFullV) m_workspace.resize(svd.cols());
+ }
+
+ bool run(JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix)
{
if(matrix.cols() > matrix.rows())
{
- typedef Matrix<typename MatrixType::Scalar, MatrixType::ColsAtCompileTime, MatrixType::RowsAtCompileTime,
- MatrixType::Options, MatrixType::MaxColsAtCompileTime, MatrixType::MaxRowsAtCompileTime>
- TransposeTypeWithSameStorageOrder;
- FullPivHouseholderQR<TransposeTypeWithSameStorageOrder> qr(matrix.adjoint());
- svd.m_workMatrix = qr.matrixQR().block(0,0,matrix.rows(),matrix.rows()).template triangularView<Upper>().adjoint();
- if(svd.m_computeFullV) svd.m_matrixV = qr.matrixQ();
- if(svd.computeU()) svd.m_matrixU = qr.colsPermutation();
+ m_adjoint = matrix.adjoint();
+ m_qr.compute(m_adjoint);
+ svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.rows(),matrix.rows()).template triangularView<Upper>().adjoint();
+ if(svd.m_computeFullV) m_qr.matrixQ().evalTo(svd.m_matrixV, m_workspace);
+ if(svd.computeU()) svd.m_matrixU = m_qr.colsPermutation();
return true;
}
else return false;
}
+private:
+ FullPivHouseholderQR<TransposeTypeWithSameStorageOrder> m_qr;
+ TransposeTypeWithSameStorageOrder m_adjoint;
+ typename internal::plain_row_type<MatrixType>::type m_workspace;
};
/*** preconditioner using ColPivHouseholderQR ***/
template<typename MatrixType>
-struct qr_preconditioner_impl<MatrixType, ColPivHouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols, true>
+class qr_preconditioner_impl<MatrixType, ColPivHouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols, true>
{
- static bool run(JacobiSVD<MatrixType, ColPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix)
+public:
+ typedef typename MatrixType::Index Index;
+
+ void allocate(const JacobiSVD<MatrixType, ColPivHouseholderQRPreconditioner>& svd)
+ {
+ if (svd.rows() != m_qr.rows() || svd.cols() != m_qr.cols())
+ {
+ m_qr = ColPivHouseholderQR<MatrixType>(svd.rows(), svd.cols());
+ }
+ if (svd.m_computeFullU) m_workspace.resize(svd.rows());
+ else if (svd.m_computeThinU) m_workspace.resize(svd.cols());
+ }
+
+ bool run(JacobiSVD<MatrixType, ColPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix)
{
if(matrix.rows() > matrix.cols())
{
- ColPivHouseholderQR<MatrixType> qr(matrix);
- svd.m_workMatrix = qr.matrixQR().block(0,0,matrix.cols(),matrix.cols()).template triangularView<Upper>();
- if(svd.m_computeFullU) svd.m_matrixU = qr.householderQ();
- else if(svd.m_computeThinU) {
+ m_qr.compute(matrix);
+ svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.cols(),matrix.cols()).template triangularView<Upper>();
+ if(svd.m_computeFullU) m_qr.householderQ().evalTo(svd.m_matrixU, m_workspace);
+ else if(svd.m_computeThinU)
+ {
svd.m_matrixU.setIdentity(matrix.rows(), matrix.cols());
- qr.householderQ().applyThisOnTheLeft(svd.m_matrixU);
+ m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixU, m_workspace);
}
- if(svd.computeV()) svd.m_matrixV = qr.colsPermutation();
+ if(svd.computeV()) svd.m_matrixV = m_qr.colsPermutation();
return true;
}
return false;
}
+
+private:
+ ColPivHouseholderQR<MatrixType> m_qr;
+ typename internal::plain_col_type<MatrixType>::type m_workspace;
};
template<typename MatrixType>
-struct qr_preconditioner_impl<MatrixType, ColPivHouseholderQRPreconditioner, PreconditionIfMoreColsThanRows, true>
+class qr_preconditioner_impl<MatrixType, ColPivHouseholderQRPreconditioner, PreconditionIfMoreColsThanRows, true>
{
- static bool run(JacobiSVD<MatrixType, ColPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix)
+public:
+ typedef typename MatrixType::Index Index;
+ typedef typename MatrixType::Scalar Scalar;
+ enum
+ {
+ RowsAtCompileTime = MatrixType::RowsAtCompileTime,
+ ColsAtCompileTime = MatrixType::ColsAtCompileTime,
+ MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
+ MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
+ Options = MatrixType::Options
+ };
+
+ typedef Matrix<Scalar, ColsAtCompileTime, RowsAtCompileTime, Options, MaxColsAtCompileTime, MaxRowsAtCompileTime>
+ TransposeTypeWithSameStorageOrder;
+
+ void allocate(const JacobiSVD<MatrixType, ColPivHouseholderQRPreconditioner>& svd)
+ {
+ if (svd.cols() != m_qr.rows() || svd.rows() != m_qr.cols())
+ {
+ m_qr = ColPivHouseholderQR<TransposeTypeWithSameStorageOrder>(svd.cols(), svd.rows());
+ }
+ if (svd.m_computeFullV) m_workspace.resize(svd.cols());
+ else if (svd.m_computeThinV) m_workspace.resize(svd.rows());
+ m_adjoint.resize(svd.cols(), svd.rows());
+ }
+
+ bool run(JacobiSVD<MatrixType, ColPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix)
{
if(matrix.cols() > matrix.rows())
{
- typedef Matrix<typename MatrixType::Scalar, MatrixType::ColsAtCompileTime, MatrixType::RowsAtCompileTime,
- MatrixType::Options, MatrixType::MaxColsAtCompileTime, MatrixType::MaxRowsAtCompileTime>
- TransposeTypeWithSameStorageOrder;
- ColPivHouseholderQR<TransposeTypeWithSameStorageOrder> qr(matrix.adjoint());
- svd.m_workMatrix = qr.matrixQR().block(0,0,matrix.rows(),matrix.rows()).template triangularView<Upper>().adjoint();
- if(svd.m_computeFullV) svd.m_matrixV = qr.householderQ();
- else if(svd.m_computeThinV) {
+ m_adjoint = matrix.adjoint();
+ m_qr.compute(m_adjoint);
+
+ svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.rows(),matrix.rows()).template triangularView<Upper>().adjoint();
+ if(svd.m_computeFullV) m_qr.householderQ().evalTo(svd.m_matrixV, m_workspace);
+ else if(svd.m_computeThinV)
+ {
svd.m_matrixV.setIdentity(matrix.cols(), matrix.rows());
- qr.householderQ().applyThisOnTheLeft(svd.m_matrixV);
+ m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixV, m_workspace);
}
- if(svd.computeU()) svd.m_matrixU = qr.colsPermutation();
+ if(svd.computeU()) svd.m_matrixU = m_qr.colsPermutation();
return true;
}
else return false;
}
+
+private:
+ ColPivHouseholderQR<TransposeTypeWithSameStorageOrder> m_qr;
+ TransposeTypeWithSameStorageOrder m_adjoint;
+ typename internal::plain_row_type<MatrixType>::type m_workspace;
};
/*** preconditioner using HouseholderQR ***/
template<typename MatrixType>
-struct qr_preconditioner_impl<MatrixType, HouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols, true>
+class qr_preconditioner_impl<MatrixType, HouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols, true>
{
- static bool run(JacobiSVD<MatrixType, HouseholderQRPreconditioner>& svd, const MatrixType& matrix)
+public:
+ typedef typename MatrixType::Index Index;
+
+ void allocate(const JacobiSVD<MatrixType, HouseholderQRPreconditioner>& svd)
+ {
+ if (svd.rows() != m_qr.rows() || svd.cols() != m_qr.cols())
+ {
+ m_qr = HouseholderQR<MatrixType>(svd.rows(), svd.cols());
+ }
+ if (svd.m_computeFullU) m_workspace.resize(svd.rows());
+ else if (svd.m_computeThinU) m_workspace.resize(svd.cols());
+ }
+
+ bool run(JacobiSVD<MatrixType, HouseholderQRPreconditioner>& svd, const MatrixType& matrix)
{
if(matrix.rows() > matrix.cols())
{
- HouseholderQR<MatrixType> qr(matrix);
- svd.m_workMatrix = qr.matrixQR().block(0,0,matrix.cols(),matrix.cols()).template triangularView<Upper>();
- if(svd.m_computeFullU) svd.m_matrixU = qr.householderQ();
- else if(svd.m_computeThinU) {
+ m_qr.compute(matrix);
+ svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.cols(),matrix.cols()).template triangularView<Upper>();
+ if(svd.m_computeFullU) m_qr.householderQ().evalTo(svd.m_matrixU, m_workspace);
+ else if(svd.m_computeThinU)
+ {
svd.m_matrixU.setIdentity(matrix.rows(), matrix.cols());
- qr.householderQ().applyThisOnTheLeft(svd.m_matrixU);
+ m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixU, m_workspace);
}
if(svd.computeV()) svd.m_matrixV.setIdentity(matrix.cols(), matrix.cols());
return true;
}
return false;
}
+private:
+ HouseholderQR<MatrixType> m_qr;
+ typename internal::plain_col_type<MatrixType>::type m_workspace;
};
template<typename MatrixType>
-struct qr_preconditioner_impl<MatrixType, HouseholderQRPreconditioner, PreconditionIfMoreColsThanRows, true>
+class qr_preconditioner_impl<MatrixType, HouseholderQRPreconditioner, PreconditionIfMoreColsThanRows, true>
{
- static bool run(JacobiSVD<MatrixType, HouseholderQRPreconditioner>& svd, const MatrixType& matrix)
+public:
+ typedef typename MatrixType::Index Index;
+ typedef typename MatrixType::Scalar Scalar;
+ enum
+ {
+ RowsAtCompileTime = MatrixType::RowsAtCompileTime,
+ ColsAtCompileTime = MatrixType::ColsAtCompileTime,
+ MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
+ MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
+ Options = MatrixType::Options
+ };
+
+ typedef Matrix<Scalar, ColsAtCompileTime, RowsAtCompileTime, Options, MaxColsAtCompileTime, MaxRowsAtCompileTime>
+ TransposeTypeWithSameStorageOrder;
+
+ void allocate(const JacobiSVD<MatrixType, HouseholderQRPreconditioner>& svd)
+ {
+ if (svd.cols() != m_qr.rows() || svd.rows() != m_qr.cols())
+ {
+ m_qr = HouseholderQR<TransposeTypeWithSameStorageOrder>(svd.cols(), svd.rows());
+ }
+ if (svd.m_computeFullV) m_workspace.resize(svd.cols());
+ else if (svd.m_computeThinV) m_workspace.resize(svd.rows());
+ m_adjoint.resize(svd.cols(), svd.rows());
+ }
+
+ bool run(JacobiSVD<MatrixType, HouseholderQRPreconditioner>& svd, const MatrixType& matrix)
{
if(matrix.cols() > matrix.rows())
{
- typedef Matrix<typename MatrixType::Scalar, MatrixType::ColsAtCompileTime, MatrixType::RowsAtCompileTime,
- MatrixType::Options, MatrixType::MaxColsAtCompileTime, MatrixType::MaxRowsAtCompileTime>
- TransposeTypeWithSameStorageOrder;
- HouseholderQR<TransposeTypeWithSameStorageOrder> qr(matrix.adjoint());
- svd.m_workMatrix = qr.matrixQR().block(0,0,matrix.rows(),matrix.rows()).template triangularView<Upper>().adjoint();
- if(svd.m_computeFullV) svd.m_matrixV = qr.householderQ();
- else if(svd.m_computeThinV) {
+ m_adjoint = matrix.adjoint();
+ m_qr.compute(m_adjoint);
+
+ svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.rows(),matrix.rows()).template triangularView<Upper>().adjoint();
+ if(svd.m_computeFullV) m_qr.householderQ().evalTo(svd.m_matrixV, m_workspace);
+ else if(svd.m_computeThinV)
+ {
svd.m_matrixV.setIdentity(matrix.cols(), matrix.rows());
- qr.householderQ().applyThisOnTheLeft(svd.m_matrixV);
+ m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixV, m_workspace);
}
if(svd.computeU()) svd.m_matrixU.setIdentity(matrix.rows(), matrix.rows());
return true;
}
else return false;
}
+
+private:
+ HouseholderQR<TransposeTypeWithSameStorageOrder> m_qr;
+ TransposeTypeWithSameStorageOrder m_adjoint;
+ typename internal::plain_row_type<MatrixType>::type m_workspace;
};
/*** 2x2 SVD implementation
@@ -316,7 +451,7 @@ void real_2x2_jacobi_svd(const MatrixType& matrix, Index p, Index q,
* Here's an example demonstrating basic usage:
* \include JacobiSVD_basic.cpp
* Output: \verbinclude JacobiSVD_basic.out
- *
+ *
* This JacobiSVD class is a two-sided Jacobi R-SVD decomposition, ensuring optimal reliability and accuracy. The downside is that it's slower than
* bidiagonalizing SVD algorithms for large square matrices; however its complexity is still \f$ O(n^2p) \f$ where \a n is the smaller dimension and
* \a p is the greater dimension, meaning that it is still of the same order of complexity as the faster bidiagonalizing R-SVD algorithms.
@@ -324,7 +459,7 @@ void real_2x2_jacobi_svd(const MatrixType& matrix, Index p, Index q,
*
* If the input matrix has inf or nan coefficients, the result of the computation is undefined, but the computation is guaranteed to
* terminate in finite (and reasonable) time.
- *
+ *
* The possible values for QRPreconditioner are:
* \li ColPivHouseholderQRPreconditioner is the default. In practice it's very safe. It uses column-pivoting QR.
* \li FullPivHouseholderQRPreconditioner, is the safest and slowest. It uses full-pivoting QR.
@@ -494,7 +629,7 @@ template<typename _MatrixType, int QRPreconditioner> class JacobiSVD
* \param b the right-hand-side of the equation to solve.
*
* \note Solving requires both U and V to be computed. Thin U and V are enough, there is no need for full U or V.
- *
+ *
* \note SVD solving is implicitly least-squares. Thus, this method serves both purposes of exact solving and least-squares solving.
* In other words, the returned solution is guaranteed to minimize the Euclidean norm \f$ \Vert A x - b \Vert \f$.
*/
@@ -535,6 +670,9 @@ template<typename _MatrixType, int QRPreconditioner> class JacobiSVD
friend struct internal::svd_precondition_2x2_block_to_be_real;
template<typename __MatrixType, int _QRPreconditioner, int _Case, bool _DoAnything>
friend struct internal::qr_preconditioner_impl;
+
+ internal::qr_preconditioner_impl<MatrixType, QRPreconditioner, internal::PreconditionIfMoreColsThanRows> m_qr_precond_morecols;
+ internal::qr_preconditioner_impl<MatrixType, QRPreconditioner, internal::PreconditionIfMoreRowsThanCols> m_qr_precond_morerows;
};
template<typename MatrixType, int QRPreconditioner>
@@ -578,6 +716,9 @@ void JacobiSVD<MatrixType, QRPreconditioner>::allocate(Index rows, Index cols, u
: m_computeThinV ? m_diagSize
: 0);
m_workMatrix.resize(m_diagSize, m_diagSize);
+
+ if(m_cols>m_rows) m_qr_precond_morecols.allocate(*this);
+ if(m_rows>m_cols) m_qr_precond_morerows.allocate(*this);
}
template<typename MatrixType, int QRPreconditioner>
@@ -595,8 +736,7 @@ JacobiSVD<MatrixType, QRPreconditioner>::compute(const MatrixType& matrix, unsig
/*** step 1. The R-SVD step: we use a QR decomposition to reduce to the case of a square matrix */
- if(!internal::qr_preconditioner_impl<MatrixType, QRPreconditioner, internal::PreconditionIfMoreColsThanRows>::run(*this, matrix)
- && !internal::qr_preconditioner_impl<MatrixType, QRPreconditioner, internal::PreconditionIfMoreRowsThanCols>::run(*this, matrix))
+ if(!m_qr_precond_morecols.run(*this, matrix) && !m_qr_precond_morerows.run(*this, matrix))
{
m_workMatrix = matrix.block(0,0,m_diagSize,m_diagSize);
if(m_computeFullU) m_matrixU.setIdentity(m_rows,m_rows);
@@ -722,6 +862,6 @@ MatrixBase<Derived>::jacobiSvd(unsigned int computationOptions) const
return JacobiSVD<PlainObject>(*this, computationOptions);
}
-
+} // end namespace Eigen
#endif // EIGEN_JACOBISVD_H
diff --git a/extern/Eigen3/Eigen/src/SVD/JacobiSVD_MKL.h b/extern/Eigen3/Eigen/src/SVD/JacobiSVD_MKL.h
new file mode 100644
index 00000000000..4d479f6b26e
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/SVD/JacobiSVD_MKL.h
@@ -0,0 +1,92 @@
+/*
+ Copyright (c) 2011, Intel Corporation. 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.
+ * Neither the name of Intel Corporation nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ 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.
+
+ ********************************************************************************
+ * Content : Eigen bindings to Intel(R) MKL
+ * Singular Value Decomposition - SVD.
+ ********************************************************************************
+*/
+
+#ifndef EIGEN_JACOBISVD_MKL_H
+#define EIGEN_JACOBISVD_MKL_H
+
+#include "Eigen/src/Core/util/MKL_support.h"
+
+namespace Eigen {
+
+/** \internal Specialization for the data types supported by MKL */
+
+#define EIGEN_MKL_SVD(EIGTYPE, MKLTYPE, MKLRTYPE, MKLPREFIX, EIGCOLROW, MKLCOLROW) \
+template<> inline\
+JacobiSVD<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW, Dynamic, Dynamic>, ColPivHouseholderQRPreconditioner>& \
+JacobiSVD<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW, Dynamic, Dynamic>, ColPivHouseholderQRPreconditioner>::compute(const Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW, Dynamic, Dynamic>& matrix, unsigned int computationOptions) \
+{ \
+ typedef Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW, Dynamic, Dynamic> MatrixType; \
+ typedef MatrixType::Scalar Scalar; \
+ typedef MatrixType::RealScalar RealScalar; \
+ allocate(matrix.rows(), matrix.cols(), computationOptions); \
+\
+ /*const RealScalar precision = RealScalar(2) * NumTraits<Scalar>::epsilon();*/ \
+ m_nonzeroSingularValues = m_diagSize; \
+\
+ lapack_int lda = matrix.outerStride(), ldu, ldvt; \
+ lapack_int matrix_order = MKLCOLROW; \
+ char jobu, jobvt; \
+ MKLTYPE *u, *vt, dummy; \
+ jobu = (m_computeFullU) ? 'A' : (m_computeThinU) ? 'S' : 'N'; \
+ jobvt = (m_computeFullV) ? 'A' : (m_computeThinV) ? 'S' : 'N'; \
+ if (computeU()) { \
+ ldu = m_matrixU.outerStride(); \
+ u = (MKLTYPE*)m_matrixU.data(); \
+ } else { ldu=1; u=&dummy; }\
+ MatrixType localV; \
+ ldvt = (m_computeFullV) ? m_cols : (m_computeThinV) ? m_diagSize : 1; \
+ if (computeV()) { \
+ localV.resize(ldvt, m_cols); \
+ vt = (MKLTYPE*)localV.data(); \
+ } else { ldvt=1; vt=&dummy; }\
+ Matrix<MKLRTYPE, Dynamic, Dynamic> superb; superb.resize(m_diagSize, 1); \
+ MatrixType m_temp; m_temp = matrix; \
+ LAPACKE_##MKLPREFIX##gesvd( matrix_order, jobu, jobvt, m_rows, m_cols, (MKLTYPE*)m_temp.data(), lda, (MKLRTYPE*)m_singularValues.data(), u, ldu, vt, ldvt, superb.data()); \
+ if (computeV()) m_matrixV = localV.adjoint(); \
+ /* for(int i=0;i<m_diagSize;i++) if (m_singularValues.coeffRef(i) < precision) { m_nonzeroSingularValues--; m_singularValues.coeffRef(i)=RealScalar(0);}*/ \
+ m_isInitialized = true; \
+ return *this; \
+}
+
+EIGEN_MKL_SVD(double, double, double, d, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_SVD(float, float, float , s, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_SVD(dcomplex, MKL_Complex16, double, z, ColMajor, LAPACK_COL_MAJOR)
+EIGEN_MKL_SVD(scomplex, MKL_Complex8, float , c, ColMajor, LAPACK_COL_MAJOR)
+
+EIGEN_MKL_SVD(double, double, double, d, RowMajor, LAPACK_ROW_MAJOR)
+EIGEN_MKL_SVD(float, float, float , s, RowMajor, LAPACK_ROW_MAJOR)
+EIGEN_MKL_SVD(dcomplex, MKL_Complex16, double, z, RowMajor, LAPACK_ROW_MAJOR)
+EIGEN_MKL_SVD(scomplex, MKL_Complex8, float , c, RowMajor, LAPACK_ROW_MAJOR)
+
+} // end namespace Eigen
+
+#endif // EIGEN_JACOBISVD_MKL_H
diff --git a/extern/Eigen3/Eigen/src/SVD/UpperBidiagonalization.h b/extern/Eigen3/Eigen/src/SVD/UpperBidiagonalization.h
index 2de197da953..213b3100df5 100644
--- a/extern/Eigen3/Eigen/src/SVD/UpperBidiagonalization.h
+++ b/extern/Eigen3/Eigen/src/SVD/UpperBidiagonalization.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BIDIAGONALIZATION_H
#define EIGEN_BIDIAGONALIZATION_H
+namespace Eigen {
+
namespace internal {
// UpperBidiagonalization will probably be replaced by a Bidiagonalization class, don't want to make it stable API.
// At the same time, it's useful to keep for now as it's about the only thing that is testing the BandMatrix class.
@@ -156,4 +143,6 @@ MatrixBase<Derived>::bidiagonalization() const
} // end namespace internal
+} // end namespace Eigen
+
#endif // EIGEN_BIDIAGONALIZATION_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/DynamicSparseMatrix.h b/extern/Eigen3/Eigen/src/Sparse/DynamicSparseMatrix.h
deleted file mode 100644
index 93e75f4c601..00000000000
--- a/extern/Eigen3/Eigen/src/Sparse/DynamicSparseMatrix.h
+++ /dev/null
@@ -1,346 +0,0 @@
-// This file is part of Eigen, a lightweight C++ template library
-// for linear algebra.
-//
-// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
-//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
-
-#ifndef EIGEN_DYNAMIC_SPARSEMATRIX_H
-#define EIGEN_DYNAMIC_SPARSEMATRIX_H
-
-/** \class DynamicSparseMatrix
- *
- * \brief A sparse matrix class designed for matrix assembly purpose
- *
- * \param _Scalar the scalar type, i.e. the type of the coefficients
- *
- * Unlike SparseMatrix, this class provides a much higher degree of flexibility. In particular, it allows
- * random read/write accesses in log(rho*outer_size) where \c rho is the probability that a coefficient is
- * nonzero and outer_size is the number of columns if the matrix is column-major and the number of rows
- * otherwise.
- *
- * Internally, the data are stored as a std::vector of compressed vector. The performances of random writes might
- * decrease as the number of nonzeros per inner-vector increase. In practice, we observed very good performance
- * till about 100 nonzeros/vector, and the performance remains relatively good till 500 nonzeros/vectors.
- *
- * \see SparseMatrix
- */
-
-namespace internal {
-template<typename _Scalar, int _Options, typename _Index>
-struct traits<DynamicSparseMatrix<_Scalar, _Options, _Index> >
-{
- typedef _Scalar Scalar;
- typedef _Index Index;
- typedef Sparse StorageKind;
- typedef MatrixXpr XprKind;
- enum {
- RowsAtCompileTime = Dynamic,
- ColsAtCompileTime = Dynamic,
- MaxRowsAtCompileTime = Dynamic,
- MaxColsAtCompileTime = Dynamic,
- Flags = _Options | NestByRefBit | LvalueBit,
- CoeffReadCost = NumTraits<Scalar>::ReadCost,
- SupportedAccessPatterns = OuterRandomAccessPattern
- };
-};
-}
-
-template<typename _Scalar, int _Options, typename _Index>
-class DynamicSparseMatrix
- : public SparseMatrixBase<DynamicSparseMatrix<_Scalar, _Options, _Index> >
-{
- public:
- EIGEN_SPARSE_PUBLIC_INTERFACE(DynamicSparseMatrix)
- // FIXME: why are these operator already alvailable ???
- // EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(DynamicSparseMatrix, +=)
- // EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(DynamicSparseMatrix, -=)
- typedef MappedSparseMatrix<Scalar,Flags> Map;
- using Base::IsRowMajor;
- using Base::operator=;
- enum {
- Options = _Options
- };
-
- protected:
-
- typedef DynamicSparseMatrix<Scalar,(Flags&~RowMajorBit)|(IsRowMajor?RowMajorBit:0)> TransposedSparseMatrix;
-
- Index m_innerSize;
- std::vector<CompressedStorage<Scalar,Index> > m_data;
-
- public:
-
- inline Index rows() const { return IsRowMajor ? outerSize() : m_innerSize; }
- inline Index cols() const { return IsRowMajor ? m_innerSize : outerSize(); }
- inline Index innerSize() const { return m_innerSize; }
- inline Index outerSize() const { return static_cast<Index>(m_data.size()); }
- inline Index innerNonZeros(Index j) const { return m_data[j].size(); }
-
- std::vector<CompressedStorage<Scalar,Index> >& _data() { return m_data; }
- const std::vector<CompressedStorage<Scalar,Index> >& _data() const { return m_data; }
-
- /** \returns the coefficient value at given position \a row, \a col
- * This operation involes a log(rho*outer_size) binary search.
- */
- inline Scalar coeff(Index row, Index col) const
- {
- const Index outer = IsRowMajor ? row : col;
- const Index inner = IsRowMajor ? col : row;
- return m_data[outer].at(inner);
- }
-
- /** \returns a reference to the coefficient value at given position \a row, \a col
- * This operation involes a log(rho*outer_size) binary search. If the coefficient does not
- * exist yet, then a sorted insertion into a sequential buffer is performed.
- */
- inline Scalar& coeffRef(Index row, Index col)
- {
- const Index outer = IsRowMajor ? row : col;
- const Index inner = IsRowMajor ? col : row;
- return m_data[outer].atWithInsertion(inner);
- }
-
- class InnerIterator;
-
- void setZero()
- {
- for (Index j=0; j<outerSize(); ++j)
- m_data[j].clear();
- }
-
- /** \returns the number of non zero coefficients */
- Index nonZeros() const
- {
- Index res = 0;
- for (Index j=0; j<outerSize(); ++j)
- res += static_cast<Index>(m_data[j].size());
- return res;
- }
-
-
-
- void reserve(Index reserveSize = 1000)
- {
- if (outerSize()>0)
- {
- Index reserveSizePerVector = (std::max)(reserveSize/outerSize(),Index(4));
- for (Index j=0; j<outerSize(); ++j)
- {
- m_data[j].reserve(reserveSizePerVector);
- }
- }
- }
-
- /** Does nothing: provided for compatibility with SparseMatrix */
- inline void startVec(Index /*outer*/) {}
-
- /** \returns a reference to the non zero coefficient at position \a row, \a col assuming that:
- * - the nonzero does not already exist
- * - the new coefficient is the last one of the given inner vector.
- *
- * \sa insert, insertBackByOuterInner */
- inline Scalar& insertBack(Index row, Index col)
- {
- return insertBackByOuterInner(IsRowMajor?row:col, IsRowMajor?col:row);
- }
-
- /** \sa insertBack */
- inline Scalar& insertBackByOuterInner(Index outer, Index inner)
- {
- eigen_assert(outer<Index(m_data.size()) && inner<m_innerSize && "out of range");
- eigen_assert(((m_data[outer].size()==0) || (m_data[outer].index(m_data[outer].size()-1)<inner))
- && "wrong sorted insertion");
- m_data[outer].append(0, inner);
- return m_data[outer].value(m_data[outer].size()-1);
- }
-
- inline Scalar& insert(Index row, Index col)
- {
- const Index outer = IsRowMajor ? row : col;
- const Index inner = IsRowMajor ? col : row;
-
- Index startId = 0;
- Index id = static_cast<Index>(m_data[outer].size()) - 1;
- m_data[outer].resize(id+2,1);
-
- while ( (id >= startId) && (m_data[outer].index(id) > inner) )
- {
- m_data[outer].index(id+1) = m_data[outer].index(id);
- m_data[outer].value(id+1) = m_data[outer].value(id);
- --id;
- }
- m_data[outer].index(id+1) = inner;
- m_data[outer].value(id+1) = 0;
- return m_data[outer].value(id+1);
- }
-
- /** Does nothing: provided for compatibility with SparseMatrix */
- inline void finalize() {}
-
- /** Suppress all nonzeros which are smaller than \a reference under the tolerence \a epsilon */
- void prune(Scalar reference, RealScalar epsilon = NumTraits<RealScalar>::dummy_precision())
- {
- for (Index j=0; j<outerSize(); ++j)
- m_data[j].prune(reference,epsilon);
- }
-
- /** Resize the matrix without preserving the data (the matrix is set to zero)
- */
- void resize(Index rows, Index cols)
- {
- const Index outerSize = IsRowMajor ? rows : cols;
- m_innerSize = IsRowMajor ? cols : rows;
- setZero();
- if (Index(m_data.size()) != outerSize)
- {
- m_data.resize(outerSize);
- }
- }
-
- void resizeAndKeepData(Index rows, Index cols)
- {
- const Index outerSize = IsRowMajor ? rows : cols;
- const Index innerSize = IsRowMajor ? cols : rows;
- if (m_innerSize>innerSize)
- {
- // remove all coefficients with innerCoord>=innerSize
- // TODO
- //std::cerr << "not implemented yet\n";
- exit(2);
- }
- if (m_data.size() != outerSize)
- {
- m_data.resize(outerSize);
- }
- }
-
- inline DynamicSparseMatrix()
- : m_innerSize(0), m_data(0)
- {
- eigen_assert(innerSize()==0 && outerSize()==0);
- }
-
- inline DynamicSparseMatrix(Index rows, Index cols)
- : m_innerSize(0)
- {
- resize(rows, cols);
- }
-
- template<typename OtherDerived>
- explicit inline DynamicSparseMatrix(const SparseMatrixBase<OtherDerived>& other)
- : m_innerSize(0)
- {
- Base::operator=(other.derived());
- }
-
- inline DynamicSparseMatrix(const DynamicSparseMatrix& other)
- : Base(), m_innerSize(0)
- {
- *this = other.derived();
- }
-
- inline void swap(DynamicSparseMatrix& other)
- {
- //EIGEN_DBG_SPARSE(std::cout << "SparseMatrix:: swap\n");
- std::swap(m_innerSize, other.m_innerSize);
- //std::swap(m_outerSize, other.m_outerSize);
- m_data.swap(other.m_data);
- }
-
- inline DynamicSparseMatrix& operator=(const DynamicSparseMatrix& other)
- {
- if (other.isRValue())
- {
- swap(other.const_cast_derived());
- }
- else
- {
- resize(other.rows(), other.cols());
- m_data = other.m_data;
- }
- return *this;
- }
-
- /** Destructor */
- inline ~DynamicSparseMatrix() {}
-
- public:
-
- /** \deprecated
- * Set the matrix to zero and reserve the memory for \a reserveSize nonzero coefficients. */
- EIGEN_DEPRECATED void startFill(Index reserveSize = 1000)
- {
- setZero();
- reserve(reserveSize);
- }
-
- /** \deprecated use insert()
- * inserts a nonzero coefficient at given coordinates \a row, \a col and returns its reference assuming that:
- * 1 - the coefficient does not exist yet
- * 2 - this the coefficient with greater inner coordinate for the given outer coordinate.
- * In other words, assuming \c *this is column-major, then there must not exists any nonzero coefficient of coordinates
- * \c i \c x \a col such that \c i >= \a row. Otherwise the matrix is invalid.
- *
- * \see fillrand(), coeffRef()
- */
- EIGEN_DEPRECATED Scalar& fill(Index row, Index col)
- {
- const Index outer = IsRowMajor ? row : col;
- const Index inner = IsRowMajor ? col : row;
- return insertBack(outer,inner);
- }
-
- /** \deprecated use insert()
- * Like fill() but with random inner coordinates.
- * Compared to the generic coeffRef(), the unique limitation is that we assume
- * the coefficient does not exist yet.
- */
- EIGEN_DEPRECATED Scalar& fillrand(Index row, Index col)
- {
- return insert(row,col);
- }
-
- /** \deprecated use finalize()
- * Does nothing. Provided for compatibility with SparseMatrix. */
- EIGEN_DEPRECATED void endFill() {}
-
-# ifdef EIGEN_DYNAMICSPARSEMATRIX_PLUGIN
-# include EIGEN_DYNAMICSPARSEMATRIX_PLUGIN
-# endif
-};
-
-template<typename Scalar, int _Options, typename _Index>
-class DynamicSparseMatrix<Scalar,_Options,_Index>::InnerIterator : public SparseVector<Scalar,_Options>::InnerIterator
-{
- typedef typename SparseVector<Scalar,_Options>::InnerIterator Base;
- public:
- InnerIterator(const DynamicSparseMatrix& mat, Index outer)
- : Base(mat.m_data[outer]), m_outer(outer)
- {}
-
- inline Index row() const { return IsRowMajor ? m_outer : Base::index(); }
- inline Index col() const { return IsRowMajor ? Base::index() : m_outer; }
-
- protected:
- const Index m_outer;
-};
-
-#endif // EIGEN_DYNAMIC_SPARSEMATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseCwiseUnaryOp.h b/extern/Eigen3/Eigen/src/Sparse/SparseCwiseUnaryOp.h
deleted file mode 100644
index aa068835fbb..00000000000
--- a/extern/Eigen3/Eigen/src/Sparse/SparseCwiseUnaryOp.h
+++ /dev/null
@@ -1,146 +0,0 @@
-// This file is part of Eigen, a lightweight C++ template library
-// for linear algebra.
-//
-// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
-//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
-
-#ifndef EIGEN_SPARSE_CWISE_UNARY_OP_H
-#define EIGEN_SPARSE_CWISE_UNARY_OP_H
-
-// template<typename UnaryOp, typename MatrixType>
-// struct internal::traits<SparseCwiseUnaryOp<UnaryOp, MatrixType> > : internal::traits<MatrixType>
-// {
-// typedef typename internal::result_of<
-// UnaryOp(typename MatrixType::Scalar)
-// >::type Scalar;
-// typedef typename MatrixType::Nested MatrixTypeNested;
-// typedef typename internal::remove_reference<MatrixTypeNested>::type _MatrixTypeNested;
-// enum {
-// CoeffReadCost = _MatrixTypeNested::CoeffReadCost + internal::functor_traits<UnaryOp>::Cost
-// };
-// };
-
-template<typename UnaryOp, typename MatrixType>
-class CwiseUnaryOpImpl<UnaryOp,MatrixType,Sparse>
- : public SparseMatrixBase<CwiseUnaryOp<UnaryOp, MatrixType> >
-{
- public:
-
- class InnerIterator;
-// typedef typename internal::remove_reference<LhsNested>::type _LhsNested;
-
- typedef CwiseUnaryOp<UnaryOp, MatrixType> Derived;
- EIGEN_SPARSE_PUBLIC_INTERFACE(Derived)
-};
-
-template<typename UnaryOp, typename MatrixType>
-class CwiseUnaryOpImpl<UnaryOp,MatrixType,Sparse>::InnerIterator
-{
- typedef typename CwiseUnaryOpImpl::Scalar Scalar;
- typedef typename internal::traits<Derived>::_XprTypeNested _MatrixTypeNested;
- typedef typename _MatrixTypeNested::InnerIterator MatrixTypeIterator;
- typedef typename MatrixType::Index Index;
- public:
-
- EIGEN_STRONG_INLINE InnerIterator(const CwiseUnaryOpImpl& unaryOp, Index outer)
- : m_iter(unaryOp.derived().nestedExpression(),outer), m_functor(unaryOp.derived().functor())
- {}
-
- EIGEN_STRONG_INLINE InnerIterator& operator++()
- { ++m_iter; return *this; }
-
- EIGEN_STRONG_INLINE Scalar value() const { return m_functor(m_iter.value()); }
-
- EIGEN_STRONG_INLINE Index index() const { return m_iter.index(); }
- EIGEN_STRONG_INLINE Index row() const { return m_iter.row(); }
- EIGEN_STRONG_INLINE Index col() const { return m_iter.col(); }
-
- EIGEN_STRONG_INLINE operator bool() const { return m_iter; }
-
- protected:
- MatrixTypeIterator m_iter;
- const UnaryOp m_functor;
-};
-
-template<typename ViewOp, typename MatrixType>
-class CwiseUnaryViewImpl<ViewOp,MatrixType,Sparse>
- : public SparseMatrixBase<CwiseUnaryView<ViewOp, MatrixType> >
-{
- public:
-
- class InnerIterator;
-// typedef typename internal::remove_reference<LhsNested>::type _LhsNested;
-
- typedef CwiseUnaryView<ViewOp, MatrixType> Derived;
- EIGEN_SPARSE_PUBLIC_INTERFACE(Derived)
-};
-
-template<typename ViewOp, typename MatrixType>
-class CwiseUnaryViewImpl<ViewOp,MatrixType,Sparse>::InnerIterator
-{
- typedef typename CwiseUnaryViewImpl::Scalar Scalar;
- typedef typename internal::traits<Derived>::_MatrixTypeNested _MatrixTypeNested;
- typedef typename _MatrixTypeNested::InnerIterator MatrixTypeIterator;
- typedef typename MatrixType::Index Index;
- public:
-
- EIGEN_STRONG_INLINE InnerIterator(const CwiseUnaryViewImpl& unaryView, Index outer)
- : m_iter(unaryView.derived().nestedExpression(),outer), m_functor(unaryView.derived().functor())
- {}
-
- EIGEN_STRONG_INLINE InnerIterator& operator++()
- { ++m_iter; return *this; }
-
- EIGEN_STRONG_INLINE Scalar value() const { return m_functor(m_iter.value()); }
- EIGEN_STRONG_INLINE Scalar& valueRef() { return m_functor(m_iter.valueRef()); }
-
- EIGEN_STRONG_INLINE Index index() const { return m_iter.index(); }
- EIGEN_STRONG_INLINE Index row() const { return m_iter.row(); }
- EIGEN_STRONG_INLINE Index col() const { return m_iter.col(); }
-
- EIGEN_STRONG_INLINE operator bool() const { return m_iter; }
-
- protected:
- MatrixTypeIterator m_iter;
- const ViewOp m_functor;
-};
-
-template<typename Derived>
-EIGEN_STRONG_INLINE Derived&
-SparseMatrixBase<Derived>::operator*=(const Scalar& other)
-{
- for (Index j=0; j<outerSize(); ++j)
- for (typename Derived::InnerIterator i(derived(),j); i; ++i)
- i.valueRef() *= other;
- return derived();
-}
-
-template<typename Derived>
-EIGEN_STRONG_INLINE Derived&
-SparseMatrixBase<Derived>::operator/=(const Scalar& other)
-{
- for (Index j=0; j<outerSize(); ++j)
- for (typename Derived::InnerIterator i(derived(),j); i; ++i)
- i.valueRef() /= other;
- return derived();
-}
-
-#endif // EIGEN_SPARSE_CWISE_UNARY_OP_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseFuzzy.h b/extern/Eigen3/Eigen/src/Sparse/SparseFuzzy.h
deleted file mode 100644
index f00b3d6469b..00000000000
--- a/extern/Eigen3/Eigen/src/Sparse/SparseFuzzy.h
+++ /dev/null
@@ -1,41 +0,0 @@
-// This file is part of Eigen, a lightweight C++ template library
-// for linear algebra.
-//
-// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
-//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
-
-#ifndef EIGEN_SPARSE_FUZZY_H
-#define EIGEN_SPARSE_FUZZY_H
-
-// template<typename Derived>
-// template<typename OtherDerived>
-// bool SparseMatrixBase<Derived>::isApprox(
-// const OtherDerived& other,
-// typename NumTraits<Scalar>::Real prec
-// ) const
-// {
-// const typename internal::nested<Derived,2>::type nested(derived());
-// const typename internal::nested<OtherDerived,2>::type otherNested(other.derived());
-// return (nested - otherNested).cwise().abs2().sum()
-// <= prec * prec * (std::min)(nested.cwise().abs2().sum(), otherNested.cwise().abs2().sum());
-// }
-
-#endif // EIGEN_SPARSE_FUZZY_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseMatrix.h b/extern/Eigen3/Eigen/src/Sparse/SparseMatrix.h
deleted file mode 100644
index 0e175ec6e71..00000000000
--- a/extern/Eigen3/Eigen/src/Sparse/SparseMatrix.h
+++ /dev/null
@@ -1,651 +0,0 @@
-// This file is part of Eigen, a lightweight C++ template library
-// for linear algebra.
-//
-// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
-//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
-
-#ifndef EIGEN_SPARSEMATRIX_H
-#define EIGEN_SPARSEMATRIX_H
-
-/** \ingroup Sparse_Module
- *
- * \class SparseMatrix
- *
- * \brief The main sparse matrix class
- *
- * This class implements a sparse matrix using the very common compressed row/column storage
- * scheme.
- *
- * \tparam _Scalar the scalar type, i.e. the type of the coefficients
- * \tparam _Options Union of bit flags controlling the storage scheme. Currently the only possibility
- * is RowMajor. The default is 0 which means column-major.
- * \tparam _Index the type of the indices. Default is \c int.
- *
- * See http://www.netlib.org/linalg/html_templates/node91.html for details on the storage scheme.
- *
- * This class can be extended with the help of the plugin mechanism described on the page
- * \ref TopicCustomizingEigen by defining the preprocessor symbol \c EIGEN_SPARSEMATRIX_PLUGIN.
- */
-
-namespace internal {
-template<typename _Scalar, int _Options, typename _Index>
-struct traits<SparseMatrix<_Scalar, _Options, _Index> >
-{
- typedef _Scalar Scalar;
- typedef _Index Index;
- typedef Sparse StorageKind;
- typedef MatrixXpr XprKind;
- enum {
- RowsAtCompileTime = Dynamic,
- ColsAtCompileTime = Dynamic,
- MaxRowsAtCompileTime = Dynamic,
- MaxColsAtCompileTime = Dynamic,
- Flags = _Options | NestByRefBit | LvalueBit,
- CoeffReadCost = NumTraits<Scalar>::ReadCost,
- SupportedAccessPatterns = InnerRandomAccessPattern
- };
-};
-
-} // end namespace internal
-
-template<typename _Scalar, int _Options, typename _Index>
-class SparseMatrix
- : public SparseMatrixBase<SparseMatrix<_Scalar, _Options, _Index> >
-{
- public:
- EIGEN_SPARSE_PUBLIC_INTERFACE(SparseMatrix)
-// using Base::operator=;
- EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(SparseMatrix, +=)
- EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(SparseMatrix, -=)
- // FIXME: why are these operator already alvailable ???
- // EIGEN_SPARSE_INHERIT_SCALAR_ASSIGNMENT_OPERATOR(SparseMatrix, *=)
- // EIGEN_SPARSE_INHERIT_SCALAR_ASSIGNMENT_OPERATOR(SparseMatrix, /=)
-
- typedef MappedSparseMatrix<Scalar,Flags> Map;
- using Base::IsRowMajor;
- typedef CompressedStorage<Scalar,Index> Storage;
- enum {
- Options = _Options
- };
-
- protected:
-
- typedef SparseMatrix<Scalar,(Flags&~RowMajorBit)|(IsRowMajor?RowMajorBit:0)> TransposedSparseMatrix;
-
- Index m_outerSize;
- Index m_innerSize;
- Index* m_outerIndex;
- CompressedStorage<Scalar,Index> m_data;
-
- public:
-
- inline Index rows() const { return IsRowMajor ? m_outerSize : m_innerSize; }
- inline Index cols() const { return IsRowMajor ? m_innerSize : m_outerSize; }
-
- inline Index innerSize() const { return m_innerSize; }
- inline Index outerSize() const { return m_outerSize; }
- inline Index innerNonZeros(Index j) const { return m_outerIndex[j+1]-m_outerIndex[j]; }
-
- inline const Scalar* _valuePtr() const { return &m_data.value(0); }
- inline Scalar* _valuePtr() { return &m_data.value(0); }
-
- inline const Index* _innerIndexPtr() const { return &m_data.index(0); }
- inline Index* _innerIndexPtr() { return &m_data.index(0); }
-
- inline const Index* _outerIndexPtr() const { return m_outerIndex; }
- inline Index* _outerIndexPtr() { return m_outerIndex; }
-
- inline Storage& data() { return m_data; }
- inline const Storage& data() const { return m_data; }
-
- inline Scalar coeff(Index row, Index col) const
- {
- const Index outer = IsRowMajor ? row : col;
- const Index inner = IsRowMajor ? col : row;
- return m_data.atInRange(m_outerIndex[outer], m_outerIndex[outer+1], inner);
- }
-
- inline Scalar& coeffRef(Index row, Index col)
- {
- const Index outer = IsRowMajor ? row : col;
- const Index inner = IsRowMajor ? col : row;
-
- Index start = m_outerIndex[outer];
- Index end = m_outerIndex[outer+1];
- eigen_assert(end>=start && "you probably called coeffRef on a non finalized matrix");
- eigen_assert(end>start && "coeffRef cannot be called on a zero coefficient");
- const Index p = m_data.searchLowerIndex(start,end-1,inner);
- eigen_assert((p<end) && (m_data.index(p)==inner) && "coeffRef cannot be called on a zero coefficient");
- return m_data.value(p);
- }
-
- public:
-
- class InnerIterator;
-
- /** Removes all non zeros */
- inline void setZero()
- {
- m_data.clear();
- memset(m_outerIndex, 0, (m_outerSize+1)*sizeof(Index));
- }
-
- /** \returns the number of non zero coefficients */
- inline Index nonZeros() const { return static_cast<Index>(m_data.size()); }
-
- /** Preallocates \a reserveSize non zeros */
- inline void reserve(Index reserveSize)
- {
- m_data.reserve(reserveSize);
- }
-
- //--- low level purely coherent filling ---
-
- /** \returns a reference to the non zero coefficient at position \a row, \a col assuming that:
- * - the nonzero does not already exist
- * - the new coefficient is the last one according to the storage order
- *
- * Before filling a given inner vector you must call the statVec(Index) function.
- *
- * After an insertion session, you should call the finalize() function.
- *
- * \sa insert, insertBackByOuterInner, startVec */
- inline Scalar& insertBack(Index row, Index col)
- {
- return insertBackByOuterInner(IsRowMajor?row:col, IsRowMajor?col:row);
- }
-
- /** \sa insertBack, startVec */
- inline Scalar& insertBackByOuterInner(Index outer, Index inner)
- {
- eigen_assert(size_t(m_outerIndex[outer+1]) == m_data.size() && "Invalid ordered insertion (invalid outer index)");
- eigen_assert( (m_outerIndex[outer+1]-m_outerIndex[outer]==0 || m_data.index(m_data.size()-1)<inner) && "Invalid ordered insertion (invalid inner index)");
- Index p = m_outerIndex[outer+1];
- ++m_outerIndex[outer+1];
- m_data.append(0, inner);
- return m_data.value(p);
- }
-
- /** \warning use it only if you know what you are doing */
- inline Scalar& insertBackByOuterInnerUnordered(Index outer, Index inner)
- {
- Index p = m_outerIndex[outer+1];
- ++m_outerIndex[outer+1];
- m_data.append(0, inner);
- return m_data.value(p);
- }
-
- /** \sa insertBack, insertBackByOuterInner */
- inline void startVec(Index outer)
- {
- eigen_assert(m_outerIndex[outer]==int(m_data.size()) && "You must call startVec for each inner vector sequentially");
- eigen_assert(m_outerIndex[outer+1]==0 && "You must call startVec for each inner vector sequentially");
- m_outerIndex[outer+1] = m_outerIndex[outer];
- }
-
- //---
-
- /** \returns a reference to a novel non zero coefficient with coordinates \a row x \a col.
- * The non zero coefficient must \b not already exist.
- *
- * \warning This function can be extremely slow if the non zero coefficients
- * are not inserted in a coherent order.
- *
- * After an insertion session, you should call the finalize() function.
- */
- EIGEN_DONT_INLINE Scalar& insert(Index row, Index col)
- {
- const Index outer = IsRowMajor ? row : col;
- const Index inner = IsRowMajor ? col : row;
-
- Index previousOuter = outer;
- if (m_outerIndex[outer+1]==0)
- {
- // we start a new inner vector
- while (previousOuter>=0 && m_outerIndex[previousOuter]==0)
- {
- m_outerIndex[previousOuter] = static_cast<Index>(m_data.size());
- --previousOuter;
- }
- m_outerIndex[outer+1] = m_outerIndex[outer];
- }
-
- // here we have to handle the tricky case where the outerIndex array
- // starts with: [ 0 0 0 0 0 1 ...] and we are inserting in, e.g.,
- // the 2nd inner vector...
- bool isLastVec = (!(previousOuter==-1 && m_data.size()!=0))
- && (size_t(m_outerIndex[outer+1]) == m_data.size());
-
- size_t startId = m_outerIndex[outer];
- // FIXME let's make sure sizeof(long int) == sizeof(size_t)
- size_t p = m_outerIndex[outer+1];
- ++m_outerIndex[outer+1];
-
- float reallocRatio = 1;
- if (m_data.allocatedSize()<=m_data.size())
- {
- // if there is no preallocated memory, let's reserve a minimum of 32 elements
- if (m_data.size()==0)
- {
- m_data.reserve(32);
- }
- else
- {
- // we need to reallocate the data, to reduce multiple reallocations
- // we use a smart resize algorithm based on the current filling ratio
- // in addition, we use float to avoid integers overflows
- float nnzEstimate = float(m_outerIndex[outer])*float(m_outerSize)/float(outer+1);
- reallocRatio = (nnzEstimate-float(m_data.size()))/float(m_data.size());
- // furthermore we bound the realloc ratio to:
- // 1) reduce multiple minor realloc when the matrix is almost filled
- // 2) avoid to allocate too much memory when the matrix is almost empty
- reallocRatio = (std::min)((std::max)(reallocRatio,1.5f),8.f);
- }
- }
- m_data.resize(m_data.size()+1,reallocRatio);
-
- if (!isLastVec)
- {
- if (previousOuter==-1)
- {
- // oops wrong guess.
- // let's correct the outer offsets
- for (Index k=0; k<=(outer+1); ++k)
- m_outerIndex[k] = 0;
- Index k=outer+1;
- while(m_outerIndex[k]==0)
- m_outerIndex[k++] = 1;
- while (k<=m_outerSize && m_outerIndex[k]!=0)
- m_outerIndex[k++]++;
- p = 0;
- --k;
- k = m_outerIndex[k]-1;
- while (k>0)
- {
- m_data.index(k) = m_data.index(k-1);
- m_data.value(k) = m_data.value(k-1);
- k--;
- }
- }
- else
- {
- // we are not inserting into the last inner vec
- // update outer indices:
- Index j = outer+2;
- while (j<=m_outerSize && m_outerIndex[j]!=0)
- m_outerIndex[j++]++;
- --j;
- // shift data of last vecs:
- Index k = m_outerIndex[j]-1;
- while (k>=Index(p))
- {
- m_data.index(k) = m_data.index(k-1);
- m_data.value(k) = m_data.value(k-1);
- k--;
- }
- }
- }
-
- while ( (p > startId) && (m_data.index(p-1) > inner) )
- {
- m_data.index(p) = m_data.index(p-1);
- m_data.value(p) = m_data.value(p-1);
- --p;
- }
-
- m_data.index(p) = inner;
- return (m_data.value(p) = 0);
- }
-
-
-
-
- /** Must be called after inserting a set of non zero entries.
- */
- inline void finalize()
- {
- Index size = static_cast<Index>(m_data.size());
- Index i = m_outerSize;
- // find the last filled column
- while (i>=0 && m_outerIndex[i]==0)
- --i;
- ++i;
- while (i<=m_outerSize)
- {
- m_outerIndex[i] = size;
- ++i;
- }
- }
-
- /** Suppress all nonzeros which are smaller than \a reference under the tolerence \a epsilon */
- void prune(Scalar reference, RealScalar epsilon = NumTraits<RealScalar>::dummy_precision())
- {
- prune(default_prunning_func(reference,epsilon));
- }
-
- /** Suppress all nonzeros which do not satisfy the predicate \a keep.
- * The functor type \a KeepFunc must implement the following function:
- * \code
- * bool operator() (const Index& row, const Index& col, const Scalar& value) const;
- * \endcode
- * \sa prune(Scalar,RealScalar)
- */
- template<typename KeepFunc>
- void prune(const KeepFunc& keep = KeepFunc())
- {
- Index k = 0;
- for(Index j=0; j<m_outerSize; ++j)
- {
- Index previousStart = m_outerIndex[j];
- m_outerIndex[j] = k;
- Index end = m_outerIndex[j+1];
- for(Index i=previousStart; i<end; ++i)
- {
- if(keep(IsRowMajor?j:m_data.index(i), IsRowMajor?m_data.index(i):j, m_data.value(i)))
- {
- m_data.value(k) = m_data.value(i);
- m_data.index(k) = m_data.index(i);
- ++k;
- }
- }
- }
- m_outerIndex[m_outerSize] = k;
- m_data.resize(k,0);
- }
-
- /** Resizes the matrix to a \a rows x \a cols matrix and initializes it to zero
- * \sa resizeNonZeros(Index), reserve(), setZero()
- */
- void resize(Index rows, Index cols)
- {
- const Index outerSize = IsRowMajor ? rows : cols;
- m_innerSize = IsRowMajor ? cols : rows;
- m_data.clear();
- if (m_outerSize != outerSize || m_outerSize==0)
- {
- delete[] m_outerIndex;
- m_outerIndex = new Index [outerSize+1];
- m_outerSize = outerSize;
- }
- memset(m_outerIndex, 0, (m_outerSize+1)*sizeof(Index));
- }
-
- /** Low level API
- * Resize the nonzero vector to \a size */
- void resizeNonZeros(Index size)
- {
- m_data.resize(size);
- }
-
- /** Default constructor yielding an empty \c 0 \c x \c 0 matrix */
- inline SparseMatrix()
- : m_outerSize(-1), m_innerSize(0), m_outerIndex(0)
- {
- resize(0, 0);
- }
-
- /** Constructs a \a rows \c x \a cols empty matrix */
- inline SparseMatrix(Index rows, Index cols)
- : m_outerSize(0), m_innerSize(0), m_outerIndex(0)
- {
- resize(rows, cols);
- }
-
- /** Constructs a sparse matrix from the sparse expression \a other */
- template<typename OtherDerived>
- inline SparseMatrix(const SparseMatrixBase<OtherDerived>& other)
- : m_outerSize(0), m_innerSize(0), m_outerIndex(0)
- {
- *this = other.derived();
- }
-
- /** Copy constructor */
- inline SparseMatrix(const SparseMatrix& other)
- : Base(), m_outerSize(0), m_innerSize(0), m_outerIndex(0)
- {
- *this = other.derived();
- }
-
- /** Swap the content of two sparse matrices of same type (optimization) */
- inline void swap(SparseMatrix& other)
- {
- //EIGEN_DBG_SPARSE(std::cout << "SparseMatrix:: swap\n");
- std::swap(m_outerIndex, other.m_outerIndex);
- std::swap(m_innerSize, other.m_innerSize);
- std::swap(m_outerSize, other.m_outerSize);
- m_data.swap(other.m_data);
- }
-
- inline SparseMatrix& operator=(const SparseMatrix& other)
- {
-// std::cout << "SparseMatrix& operator=(const SparseMatrix& other)\n";
- if (other.isRValue())
- {
- swap(other.const_cast_derived());
- }
- else
- {
- resize(other.rows(), other.cols());
- memcpy(m_outerIndex, other.m_outerIndex, (m_outerSize+1)*sizeof(Index));
- m_data = other.m_data;
- }
- return *this;
- }
-
- #ifndef EIGEN_PARSED_BY_DOXYGEN
- template<typename Lhs, typename Rhs>
- inline SparseMatrix& operator=(const SparseSparseProduct<Lhs,Rhs>& product)
- { return Base::operator=(product); }
-
- template<typename OtherDerived>
- inline SparseMatrix& operator=(const ReturnByValue<OtherDerived>& other)
- { return Base::operator=(other); }
-
- template<typename OtherDerived>
- inline SparseMatrix& operator=(const EigenBase<OtherDerived>& other)
- { return Base::operator=(other); }
- #endif
-
- template<typename OtherDerived>
- EIGEN_DONT_INLINE SparseMatrix& operator=(const SparseMatrixBase<OtherDerived>& other)
- {
- const bool needToTranspose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit);
- if (needToTranspose)
- {
- // two passes algorithm:
- // 1 - compute the number of coeffs per dest inner vector
- // 2 - do the actual copy/eval
- // Since each coeff of the rhs has to be evaluated twice, let's evaluate it if needed
- typedef typename internal::nested<OtherDerived,2>::type OtherCopy;
- typedef typename internal::remove_all<OtherCopy>::type _OtherCopy;
- OtherCopy otherCopy(other.derived());
-
- resize(other.rows(), other.cols());
- Eigen::Map<Matrix<Index, Dynamic, 1> > (m_outerIndex,outerSize()).setZero();
- // pass 1
- // FIXME the above copy could be merged with that pass
- for (Index j=0; j<otherCopy.outerSize(); ++j)
- for (typename _OtherCopy::InnerIterator it(otherCopy, j); it; ++it)
- ++m_outerIndex[it.index()];
-
- // prefix sum
- Index count = 0;
- VectorXi positions(outerSize());
- for (Index j=0; j<outerSize(); ++j)
- {
- Index tmp = m_outerIndex[j];
- m_outerIndex[j] = count;
- positions[j] = count;
- count += tmp;
- }
- m_outerIndex[outerSize()] = count;
- // alloc
- m_data.resize(count);
- // pass 2
- for (Index j=0; j<otherCopy.outerSize(); ++j)
- {
- for (typename _OtherCopy::InnerIterator it(otherCopy, j); it; ++it)
- {
- Index pos = positions[it.index()]++;
- m_data.index(pos) = j;
- m_data.value(pos) = it.value();
- }
- }
- return *this;
- }
- else
- {
- // there is no special optimization
- return SparseMatrixBase<SparseMatrix>::operator=(other.derived());
- }
- }
-
- friend std::ostream & operator << (std::ostream & s, const SparseMatrix& m)
- {
- EIGEN_DBG_SPARSE(
- s << "Nonzero entries:\n";
- for (Index i=0; i<m.nonZeros(); ++i)
- {
- s << "(" << m.m_data.value(i) << "," << m.m_data.index(i) << ") ";
- }
- s << std::endl;
- s << std::endl;
- s << "Column pointers:\n";
- for (Index i=0; i<m.outerSize(); ++i)
- {
- s << m.m_outerIndex[i] << " ";
- }
- s << " $" << std::endl;
- s << std::endl;
- );
- s << static_cast<const SparseMatrixBase<SparseMatrix>&>(m);
- return s;
- }
-
- /** Destructor */
- inline ~SparseMatrix()
- {
- delete[] m_outerIndex;
- }
-
- /** Overloaded for performance */
- Scalar sum() const;
-
- public:
-
- /** \deprecated use setZero() and reserve()
- * Initializes the filling process of \c *this.
- * \param reserveSize approximate number of nonzeros
- * Note that the matrix \c *this is zero-ed.
- */
- EIGEN_DEPRECATED void startFill(Index reserveSize = 1000)
- {
- setZero();
- m_data.reserve(reserveSize);
- }
-
- /** \deprecated use insert()
- * Like fill() but with random inner coordinates.
- */
- EIGEN_DEPRECATED Scalar& fillrand(Index row, Index col)
- {
- return insert(row,col);
- }
-
- /** \deprecated use insert()
- */
- EIGEN_DEPRECATED Scalar& fill(Index row, Index col)
- {
- const Index outer = IsRowMajor ? row : col;
- const Index inner = IsRowMajor ? col : row;
-
- if (m_outerIndex[outer+1]==0)
- {
- // we start a new inner vector
- Index i = outer;
- while (i>=0 && m_outerIndex[i]==0)
- {
- m_outerIndex[i] = m_data.size();
- --i;
- }
- m_outerIndex[outer+1] = m_outerIndex[outer];
- }
- else
- {
- eigen_assert(m_data.index(m_data.size()-1)<inner && "wrong sorted insertion");
- }
-// std::cerr << size_t(m_outerIndex[outer+1]) << " == " << m_data.size() << "\n";
- assert(size_t(m_outerIndex[outer+1]) == m_data.size());
- Index p = m_outerIndex[outer+1];
- ++m_outerIndex[outer+1];
-
- m_data.append(0, inner);
- return m_data.value(p);
- }
-
- /** \deprecated use finalize */
- EIGEN_DEPRECATED void endFill() { finalize(); }
-
-# ifdef EIGEN_SPARSEMATRIX_PLUGIN
-# include EIGEN_SPARSEMATRIX_PLUGIN
-# endif
-
-private:
- struct default_prunning_func {
- default_prunning_func(Scalar ref, RealScalar eps) : reference(ref), epsilon(eps) {}
- inline bool operator() (const Index&, const Index&, const Scalar& value) const
- {
- return !internal::isMuchSmallerThan(value, reference, epsilon);
- }
- Scalar reference;
- RealScalar epsilon;
- };
-};
-
-template<typename Scalar, int _Options, typename _Index>
-class SparseMatrix<Scalar,_Options,_Index>::InnerIterator
-{
- public:
- InnerIterator(const SparseMatrix& mat, Index outer)
- : m_values(mat._valuePtr()), m_indices(mat._innerIndexPtr()), m_outer(outer), m_id(mat.m_outerIndex[outer]), m_end(mat.m_outerIndex[outer+1])
- {}
-
- inline InnerIterator& operator++() { m_id++; return *this; }
-
- inline const Scalar& value() const { return m_values[m_id]; }
- inline Scalar& valueRef() { return const_cast<Scalar&>(m_values[m_id]); }
-
- inline Index index() const { return m_indices[m_id]; }
- inline Index outer() const { return m_outer; }
- inline Index row() const { return IsRowMajor ? m_outer : index(); }
- inline Index col() const { return IsRowMajor ? index() : m_outer; }
-
- inline operator bool() const { return (m_id < m_end); }
-
- protected:
- const Scalar* m_values;
- const Index* m_indices;
- const Index m_outer;
- Index m_id;
- const Index m_end;
-};
-
-#endif // EIGEN_SPARSEMATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseSparseProduct.h b/extern/Eigen3/Eigen/src/Sparse/SparseSparseProduct.h
deleted file mode 100644
index 19abcd1f8e4..00000000000
--- a/extern/Eigen3/Eigen/src/Sparse/SparseSparseProduct.h
+++ /dev/null
@@ -1,401 +0,0 @@
-// This file is part of Eigen, a lightweight C++ template library
-// for linear algebra.
-//
-// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
-//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
-
-#ifndef EIGEN_SPARSESPARSEPRODUCT_H
-#define EIGEN_SPARSESPARSEPRODUCT_H
-
-namespace internal {
-
-template<typename Lhs, typename Rhs, typename ResultType>
-static void sparse_product_impl2(const Lhs& lhs, const Rhs& rhs, ResultType& res)
-{
- typedef typename remove_all<Lhs>::type::Scalar Scalar;
- typedef typename remove_all<Lhs>::type::Index Index;
-
- // make sure to call innerSize/outerSize since we fake the storage order.
- Index rows = lhs.innerSize();
- Index cols = rhs.outerSize();
- eigen_assert(lhs.outerSize() == rhs.innerSize());
-
- std::vector<bool> mask(rows,false);
- Matrix<Scalar,Dynamic,1> values(rows);
- Matrix<Index,Dynamic,1> indices(rows);
-
- // estimate the number of non zero entries
- float ratioLhs = float(lhs.nonZeros())/(float(lhs.rows())*float(lhs.cols()));
- float avgNnzPerRhsColumn = float(rhs.nonZeros())/float(cols);
- float ratioRes = (std::min)(ratioLhs * avgNnzPerRhsColumn, 1.f);
-
-// int t200 = rows/(log2(200)*1.39);
-// int t = (rows*100)/139;
-
- res.resize(rows, cols);
- res.reserve(Index(ratioRes*rows*cols));
- // we compute each column of the result, one after the other
- for (Index j=0; j<cols; ++j)
- {
-
- res.startVec(j);
- Index nnz = 0;
- for (typename Rhs::InnerIterator rhsIt(rhs, j); rhsIt; ++rhsIt)
- {
- Scalar y = rhsIt.value();
- Index k = rhsIt.index();
- for (typename Lhs::InnerIterator lhsIt(lhs, k); lhsIt; ++lhsIt)
- {
- Index i = lhsIt.index();
- Scalar x = lhsIt.value();
- if(!mask[i])
- {
- mask[i] = true;
-// values[i] = x * y;
-// indices[nnz] = i;
- ++nnz;
- }
- else
- values[i] += x * y;
- }
- }
- // FIXME reserve nnz non zeros
- // FIXME implement fast sort algorithms for very small nnz
- // if the result is sparse enough => use a quick sort
- // otherwise => loop through the entire vector
- // In order to avoid to perform an expensive log2 when the
- // result is clearly very sparse we use a linear bound up to 200.
-// if((nnz<200 && nnz<t200) || nnz * log2(nnz) < t)
-// {
-// if(nnz>1) std::sort(indices.data(),indices.data()+nnz);
-// for(int k=0; k<nnz; ++k)
-// {
-// int i = indices[k];
-// res.insertBackNoCheck(j,i) = values[i];
-// mask[i] = false;
-// }
-// }
-// else
-// {
-// // dense path
-// for(int i=0; i<rows; ++i)
-// {
-// if(mask[i])
-// {
-// mask[i] = false;
-// res.insertBackNoCheck(j,i) = values[i];
-// }
-// }
-// }
-
- }
- res.finalize();
-}
-
-// perform a pseudo in-place sparse * sparse product assuming all matrices are col major
-template<typename Lhs, typename Rhs, typename ResultType>
-static void sparse_product_impl(const Lhs& lhs, const Rhs& rhs, ResultType& res)
-{
-// return sparse_product_impl2(lhs,rhs,res);
-
- typedef typename remove_all<Lhs>::type::Scalar Scalar;
- typedef typename remove_all<Lhs>::type::Index Index;
-
- // make sure to call innerSize/outerSize since we fake the storage order.
- Index rows = lhs.innerSize();
- Index cols = rhs.outerSize();
- //int size = lhs.outerSize();
- eigen_assert(lhs.outerSize() == rhs.innerSize());
-
- // allocate a temporary buffer
- AmbiVector<Scalar,Index> tempVector(rows);
-
- // estimate the number of non zero entries
- float ratioLhs = float(lhs.nonZeros())/(float(lhs.rows())*float(lhs.cols()));
- float avgNnzPerRhsColumn = float(rhs.nonZeros())/float(cols);
- float ratioRes = (std::min)(ratioLhs * avgNnzPerRhsColumn, 1.f);
-
- // mimics a resizeByInnerOuter:
- if(ResultType::IsRowMajor)
- res.resize(cols, rows);
- else
- res.resize(rows, cols);
-
- res.reserve(Index(ratioRes*rows*cols));
- for (Index j=0; j<cols; ++j)
- {
- // let's do a more accurate determination of the nnz ratio for the current column j of res
- //float ratioColRes = (std::min)(ratioLhs * rhs.innerNonZeros(j), 1.f);
- // FIXME find a nice way to get the number of nonzeros of a sub matrix (here an inner vector)
- float ratioColRes = ratioRes;
- tempVector.init(ratioColRes);
- tempVector.setZero();
- for (typename Rhs::InnerIterator rhsIt(rhs, j); rhsIt; ++rhsIt)
- {
- // FIXME should be written like this: tmp += rhsIt.value() * lhs.col(rhsIt.index())
- tempVector.restart();
- Scalar x = rhsIt.value();
- for (typename Lhs::InnerIterator lhsIt(lhs, rhsIt.index()); lhsIt; ++lhsIt)
- {
- tempVector.coeffRef(lhsIt.index()) += lhsIt.value() * x;
- }
- }
- res.startVec(j);
- for (typename AmbiVector<Scalar,Index>::Iterator it(tempVector); it; ++it)
- res.insertBackByOuterInner(j,it.index()) = it.value();
- }
- res.finalize();
-}
-
-template<typename Lhs, typename Rhs, typename ResultType,
- int LhsStorageOrder = traits<Lhs>::Flags&RowMajorBit,
- int RhsStorageOrder = traits<Rhs>::Flags&RowMajorBit,
- int ResStorageOrder = traits<ResultType>::Flags&RowMajorBit>
-struct sparse_product_selector;
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector<Lhs,Rhs,ResultType,ColMajor,ColMajor,ColMajor>
-{
- typedef typename traits<typename remove_all<Lhs>::type>::Scalar Scalar;
-
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
-// std::cerr << __LINE__ << "\n";
- typename remove_all<ResultType>::type _res(res.rows(), res.cols());
- sparse_product_impl<Lhs,Rhs,ResultType>(lhs, rhs, _res);
- res.swap(_res);
- }
-};
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector<Lhs,Rhs,ResultType,ColMajor,ColMajor,RowMajor>
-{
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
-// std::cerr << __LINE__ << "\n";
- // we need a col-major matrix to hold the result
- typedef SparseMatrix<typename ResultType::Scalar> SparseTemporaryType;
- SparseTemporaryType _res(res.rows(), res.cols());
- sparse_product_impl<Lhs,Rhs,SparseTemporaryType>(lhs, rhs, _res);
- res = _res;
- }
-};
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector<Lhs,Rhs,ResultType,RowMajor,RowMajor,RowMajor>
-{
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
-// std::cerr << __LINE__ << "\n";
- // let's transpose the product to get a column x column product
- typename remove_all<ResultType>::type _res(res.rows(), res.cols());
- sparse_product_impl<Rhs,Lhs,ResultType>(rhs, lhs, _res);
- res.swap(_res);
- }
-};
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector<Lhs,Rhs,ResultType,RowMajor,RowMajor,ColMajor>
-{
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
-// std::cerr << "here...\n";
- typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
- ColMajorMatrix colLhs(lhs);
- ColMajorMatrix colRhs(rhs);
-// std::cerr << "more...\n";
- sparse_product_impl<ColMajorMatrix,ColMajorMatrix,ResultType>(colLhs, colRhs, res);
-// std::cerr << "OK.\n";
-
- // let's transpose the product to get a column x column product
-
-// typedef SparseMatrix<typename ResultType::Scalar> SparseTemporaryType;
-// SparseTemporaryType _res(res.cols(), res.rows());
-// sparse_product_impl<Rhs,Lhs,SparseTemporaryType>(rhs, lhs, _res);
-// res = _res.transpose();
- }
-};
-
-// NOTE the 2 others cases (col row *) must never occur since they are caught
-// by ProductReturnType which transforms it to (col col *) by evaluating rhs.
-
-} // end namespace internal
-
-// sparse = sparse * sparse
-template<typename Derived>
-template<typename Lhs, typename Rhs>
-inline Derived& SparseMatrixBase<Derived>::operator=(const SparseSparseProduct<Lhs,Rhs>& product)
-{
-// std::cerr << "there..." << typeid(Lhs).name() << " " << typeid(Lhs).name() << " " << (Derived::Flags&&RowMajorBit) << "\n";
- internal::sparse_product_selector<
- typename internal::remove_all<Lhs>::type,
- typename internal::remove_all<Rhs>::type,
- Derived>::run(product.lhs(),product.rhs(),derived());
- return derived();
-}
-
-namespace internal {
-
-template<typename Lhs, typename Rhs, typename ResultType,
- int LhsStorageOrder = traits<Lhs>::Flags&RowMajorBit,
- int RhsStorageOrder = traits<Rhs>::Flags&RowMajorBit,
- int ResStorageOrder = traits<ResultType>::Flags&RowMajorBit>
-struct sparse_product_selector2;
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector2<Lhs,Rhs,ResultType,ColMajor,ColMajor,ColMajor>
-{
- typedef typename traits<typename remove_all<Lhs>::type>::Scalar Scalar;
-
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
- sparse_product_impl2<Lhs,Rhs,ResultType>(lhs, rhs, res);
- }
-};
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector2<Lhs,Rhs,ResultType,RowMajor,ColMajor,ColMajor>
-{
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
- // prevent warnings until the code is fixed
- EIGEN_UNUSED_VARIABLE(lhs);
- EIGEN_UNUSED_VARIABLE(rhs);
- EIGEN_UNUSED_VARIABLE(res);
-
-// typedef SparseMatrix<typename ResultType::Scalar,RowMajor> RowMajorMatrix;
-// RowMajorMatrix rhsRow = rhs;
-// RowMajorMatrix resRow(res.rows(), res.cols());
-// sparse_product_impl2<RowMajorMatrix,Lhs,RowMajorMatrix>(rhsRow, lhs, resRow);
-// res = resRow;
- }
-};
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector2<Lhs,Rhs,ResultType,ColMajor,RowMajor,ColMajor>
-{
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
- typedef SparseMatrix<typename ResultType::Scalar,RowMajor> RowMajorMatrix;
- RowMajorMatrix lhsRow = lhs;
- RowMajorMatrix resRow(res.rows(), res.cols());
- sparse_product_impl2<Rhs,RowMajorMatrix,RowMajorMatrix>(rhs, lhsRow, resRow);
- res = resRow;
- }
-};
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector2<Lhs,Rhs,ResultType,RowMajor,RowMajor,ColMajor>
-{
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
- typedef SparseMatrix<typename ResultType::Scalar,RowMajor> RowMajorMatrix;
- RowMajorMatrix resRow(res.rows(), res.cols());
- sparse_product_impl2<Rhs,Lhs,RowMajorMatrix>(rhs, lhs, resRow);
- res = resRow;
- }
-};
-
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector2<Lhs,Rhs,ResultType,ColMajor,ColMajor,RowMajor>
-{
- typedef typename traits<typename remove_all<Lhs>::type>::Scalar Scalar;
-
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
- typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
- ColMajorMatrix resCol(res.rows(), res.cols());
- sparse_product_impl2<Lhs,Rhs,ColMajorMatrix>(lhs, rhs, resCol);
- res = resCol;
- }
-};
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector2<Lhs,Rhs,ResultType,RowMajor,ColMajor,RowMajor>
-{
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
- typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
- ColMajorMatrix lhsCol = lhs;
- ColMajorMatrix resCol(res.rows(), res.cols());
- sparse_product_impl2<ColMajorMatrix,Rhs,ColMajorMatrix>(lhsCol, rhs, resCol);
- res = resCol;
- }
-};
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector2<Lhs,Rhs,ResultType,ColMajor,RowMajor,RowMajor>
-{
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
- typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
- ColMajorMatrix rhsCol = rhs;
- ColMajorMatrix resCol(res.rows(), res.cols());
- sparse_product_impl2<Lhs,ColMajorMatrix,ColMajorMatrix>(lhs, rhsCol, resCol);
- res = resCol;
- }
-};
-
-template<typename Lhs, typename Rhs, typename ResultType>
-struct sparse_product_selector2<Lhs,Rhs,ResultType,RowMajor,RowMajor,RowMajor>
-{
- static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
- {
- typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
-// ColMajorMatrix lhsTr(lhs);
-// ColMajorMatrix rhsTr(rhs);
-// ColMajorMatrix aux(res.rows(), res.cols());
-// sparse_product_impl2<Rhs,Lhs,ColMajorMatrix>(rhs, lhs, aux);
-// // ColMajorMatrix aux2 = aux.transpose();
-// res = aux;
- typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
- ColMajorMatrix lhsCol(lhs);
- ColMajorMatrix rhsCol(rhs);
- ColMajorMatrix resCol(res.rows(), res.cols());
- sparse_product_impl2<ColMajorMatrix,ColMajorMatrix,ColMajorMatrix>(lhsCol, rhsCol, resCol);
- res = resCol;
- }
-};
-
-} // end namespace internal
-
-template<typename Derived>
-template<typename Lhs, typename Rhs>
-inline void SparseMatrixBase<Derived>::_experimentalNewProduct(const Lhs& lhs, const Rhs& rhs)
-{
- //derived().resize(lhs.rows(), rhs.cols());
- internal::sparse_product_selector2<
- typename internal::remove_all<Lhs>::type,
- typename internal::remove_all<Rhs>::type,
- Derived>::run(lhs,rhs,derived());
-}
-
-// sparse * sparse
-template<typename Derived>
-template<typename OtherDerived>
-inline const typename SparseSparseProductReturnType<Derived,OtherDerived>::Type
-SparseMatrixBase<Derived>::operator*(const SparseMatrixBase<OtherDerived> &other) const
-{
- return typename SparseSparseProductReturnType<Derived,OtherDerived>::Type(derived(), other.derived());
-}
-
-#endif // EIGEN_SPARSESPARSEPRODUCT_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseTriangularView.h b/extern/Eigen3/Eigen/src/Sparse/SparseTriangularView.h
deleted file mode 100644
index 319eaf06638..00000000000
--- a/extern/Eigen3/Eigen/src/Sparse/SparseTriangularView.h
+++ /dev/null
@@ -1,100 +0,0 @@
-// This file is part of Eigen, a lightweight C++ template library
-// for linear algebra.
-//
-// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
-//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
-
-#ifndef EIGEN_SPARSE_TRIANGULARVIEW_H
-#define EIGEN_SPARSE_TRIANGULARVIEW_H
-
-namespace internal {
-
-template<typename MatrixType, int Mode>
-struct traits<SparseTriangularView<MatrixType,Mode> >
-: public traits<MatrixType>
-{};
-
-} // namespace internal
-
-template<typename MatrixType, int Mode> class SparseTriangularView
- : public SparseMatrixBase<SparseTriangularView<MatrixType,Mode> >
-{
- enum { SkipFirst = (Mode==Lower && !(MatrixType::Flags&RowMajorBit))
- || (Mode==Upper && (MatrixType::Flags&RowMajorBit)) };
- public:
-
- EIGEN_SPARSE_PUBLIC_INTERFACE(SparseTriangularView)
-
- class InnerIterator;
-
- inline Index rows() const { return m_matrix.rows(); }
- inline Index cols() const { return m_matrix.cols(); }
-
- typedef typename internal::conditional<internal::must_nest_by_value<MatrixType>::ret,
- MatrixType, const MatrixType&>::type MatrixTypeNested;
-
- inline SparseTriangularView(const MatrixType& matrix) : m_matrix(matrix) {}
-
- /** \internal */
- inline const MatrixType& nestedExpression() const { return m_matrix; }
-
- template<typename OtherDerived>
- typename internal::plain_matrix_type_column_major<OtherDerived>::type
- solve(const MatrixBase<OtherDerived>& other) const;
-
- template<typename OtherDerived> void solveInPlace(MatrixBase<OtherDerived>& other) const;
- template<typename OtherDerived> void solveInPlace(SparseMatrixBase<OtherDerived>& other) const;
-
- protected:
- MatrixTypeNested m_matrix;
-};
-
-template<typename MatrixType, int Mode>
-class SparseTriangularView<MatrixType,Mode>::InnerIterator : public MatrixType::InnerIterator
-{
- typedef typename MatrixType::InnerIterator Base;
- public:
-
- EIGEN_STRONG_INLINE InnerIterator(const SparseTriangularView& view, Index outer)
- : Base(view.nestedExpression(), outer)
- {
- if(SkipFirst)
- while((*this) && this->index()<outer)
- ++(*this);
- }
- inline Index row() const { return Base::row(); }
- inline Index col() const { return Base::col(); }
-
- EIGEN_STRONG_INLINE operator bool() const
- {
- return SkipFirst ? Base::operator bool() : (Base::operator bool() && this->index() <= this->outer());
- }
-};
-
-template<typename Derived>
-template<int Mode>
-inline const SparseTriangularView<Derived, Mode>
-SparseMatrixBase<Derived>::triangularView() const
-{
- return derived();
-}
-
-#endif // EIGEN_SPARSE_TRIANGULARVIEW_H
diff --git a/extern/Eigen3/Eigen/src/SparseCholesky/SimplicialCholesky.h b/extern/Eigen3/Eigen/src/SparseCholesky/SimplicialCholesky.h
new file mode 100644
index 00000000000..9bf38ab2d91
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/SparseCholesky/SimplicialCholesky.h
@@ -0,0 +1,873 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+/*
+
+NOTE: the _symbolic, and _numeric functions has been adapted from
+ the LDL library:
+
+LDL Copyright (c) 2005 by Timothy A. Davis. All Rights Reserved.
+
+LDL License:
+
+ Your use or distribution of LDL or any modified version of
+ LDL implies that you agree to this License.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
+ USA
+
+ Permission is hereby granted to use or copy this program under the
+ terms of the GNU LGPL, provided that the Copyright, this License,
+ and the Availability of the original version is retained on all copies.
+ User documentation of any code that uses this code or any modified
+ version of this code must cite the Copyright, this License, the
+ Availability note, and "Used by permission." Permission to modify
+ the code and to distribute modified code is granted, provided the
+ Copyright, this License, and the Availability note are retained,
+ and a notice that the code was modified is included.
+ */
+
+#include "../Core/util/NonMPL2.h"
+
+#ifndef EIGEN_SIMPLICIAL_CHOLESKY_H
+#define EIGEN_SIMPLICIAL_CHOLESKY_H
+
+namespace Eigen {
+
+enum SimplicialCholeskyMode {
+ SimplicialCholeskyLLT,
+ SimplicialCholeskyLDLT
+};
+
+/** \ingroup SparseCholesky_Module
+ * \brief A direct sparse Cholesky factorizations
+ *
+ * These classes provide LL^T and LDL^T Cholesky factorizations of sparse matrices that are
+ * selfadjoint and positive definite. The factorization allows for solving A.X = B where
+ * X and B can be either dense or sparse.
+ *
+ * In order to reduce the fill-in, a symmetric permutation P is applied prior to the factorization
+ * such that the factorized matrix is P A P^-1.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower
+ * or Upper. Default is Lower.
+ *
+ */
+template<typename Derived>
+class SimplicialCholeskyBase : internal::noncopyable
+{
+ public:
+ typedef typename internal::traits<Derived>::MatrixType MatrixType;
+ enum { UpLo = internal::traits<Derived>::UpLo };
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef typename MatrixType::Index Index;
+ typedef SparseMatrix<Scalar,ColMajor,Index> CholMatrixType;
+ typedef Matrix<Scalar,Dynamic,1> VectorType;
+
+ public:
+
+ /** Default constructor */
+ SimplicialCholeskyBase()
+ : m_info(Success), m_isInitialized(false), m_shiftOffset(0), m_shiftScale(1)
+ {}
+
+ SimplicialCholeskyBase(const MatrixType& matrix)
+ : m_info(Success), m_isInitialized(false), m_shiftOffset(0), m_shiftScale(1)
+ {
+ derived().compute(matrix);
+ }
+
+ ~SimplicialCholeskyBase()
+ {
+ }
+
+ Derived& derived() { return *static_cast<Derived*>(this); }
+ const Derived& derived() const { return *static_cast<const Derived*>(this); }
+
+ inline Index cols() const { return m_matrix.cols(); }
+ inline Index rows() const { return m_matrix.rows(); }
+
+ /** \brief Reports whether previous computation was successful.
+ *
+ * \returns \c Success if computation was succesful,
+ * \c NumericalIssue if the matrix.appears to be negative.
+ */
+ ComputationInfo info() const
+ {
+ eigen_assert(m_isInitialized && "Decomposition is not initialized.");
+ return m_info;
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs>
+ inline const internal::solve_retval<SimplicialCholeskyBase, Rhs>
+ solve(const MatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "Simplicial LLT or LDLT is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "SimplicialCholeskyBase::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::solve_retval<SimplicialCholeskyBase, Rhs>(*this, b.derived());
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs>
+ inline const internal::sparse_solve_retval<SimplicialCholeskyBase, Rhs>
+ solve(const SparseMatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "Simplicial LLT or LDLT is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "SimplicialCholesky::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::sparse_solve_retval<SimplicialCholeskyBase, Rhs>(*this, b.derived());
+ }
+
+ /** \returns the permutation P
+ * \sa permutationPinv() */
+ const PermutationMatrix<Dynamic,Dynamic,Index>& permutationP() const
+ { return m_P; }
+
+ /** \returns the inverse P^-1 of the permutation P
+ * \sa permutationP() */
+ const PermutationMatrix<Dynamic,Dynamic,Index>& permutationPinv() const
+ { return m_Pinv; }
+
+ /** Sets the shift parameters that will be used to adjust the diagonal coefficients during the numerical factorization.
+ *
+ * During the numerical factorization, the diagonal coefficients are transformed by the following linear model:\n
+ * \c d_ii = \a offset + \a scale * \c d_ii
+ *
+ * The default is the identity transformation with \a offset=0, and \a scale=1.
+ *
+ * \returns a reference to \c *this.
+ */
+ Derived& setShift(const RealScalar& offset, const RealScalar& scale = 1)
+ {
+ m_shiftOffset = offset;
+ m_shiftScale = scale;
+ return derived();
+ }
+
+#ifndef EIGEN_PARSED_BY_DOXYGEN
+ /** \internal */
+ template<typename Stream>
+ void dumpMemory(Stream& s)
+ {
+ int total = 0;
+ s << " L: " << ((total+=(m_matrix.cols()+1) * sizeof(int) + m_matrix.nonZeros()*(sizeof(int)+sizeof(Scalar))) >> 20) << "Mb" << "\n";
+ s << " diag: " << ((total+=m_diag.size() * sizeof(Scalar)) >> 20) << "Mb" << "\n";
+ s << " tree: " << ((total+=m_parent.size() * sizeof(int)) >> 20) << "Mb" << "\n";
+ s << " nonzeros: " << ((total+=m_nonZerosPerCol.size() * sizeof(int)) >> 20) << "Mb" << "\n";
+ s << " perm: " << ((total+=m_P.size() * sizeof(int)) >> 20) << "Mb" << "\n";
+ s << " perm^-1: " << ((total+=m_Pinv.size() * sizeof(int)) >> 20) << "Mb" << "\n";
+ s << " TOTAL: " << (total>> 20) << "Mb" << "\n";
+ }
+
+ /** \internal */
+ template<typename Rhs,typename Dest>
+ void _solve(const MatrixBase<Rhs> &b, MatrixBase<Dest> &dest) const
+ {
+ eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()");
+ eigen_assert(m_matrix.rows()==b.rows());
+
+ if(m_info!=Success)
+ return;
+
+ if(m_P.size()>0)
+ dest = m_P * b;
+ else
+ dest = b;
+
+ if(m_matrix.nonZeros()>0) // otherwise L==I
+ derived().matrixL().solveInPlace(dest);
+
+ if(m_diag.size()>0)
+ dest = m_diag.asDiagonal().inverse() * dest;
+
+ if (m_matrix.nonZeros()>0) // otherwise U==I
+ derived().matrixU().solveInPlace(dest);
+
+ if(m_P.size()>0)
+ dest = m_Pinv * dest;
+ }
+
+ /** \internal */
+ template<typename Rhs, typename DestScalar, int DestOptions, typename DestIndex>
+ void _solve_sparse(const Rhs& b, SparseMatrix<DestScalar,DestOptions,DestIndex> &dest) const
+ {
+ eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()");
+ eigen_assert(m_matrix.rows()==b.rows());
+
+ // we process the sparse rhs per block of NbColsAtOnce columns temporarily stored into a dense matrix.
+ static const int NbColsAtOnce = 4;
+ int rhsCols = b.cols();
+ int size = b.rows();
+ Eigen::Matrix<DestScalar,Dynamic,Dynamic> tmp(size,rhsCols);
+ for(int k=0; k<rhsCols; k+=NbColsAtOnce)
+ {
+ int actualCols = std::min<int>(rhsCols-k, NbColsAtOnce);
+ tmp.leftCols(actualCols) = b.middleCols(k,actualCols);
+ tmp.leftCols(actualCols) = derived().solve(tmp.leftCols(actualCols));
+ dest.middleCols(k,actualCols) = tmp.leftCols(actualCols).sparseView();
+ }
+ }
+
+#endif // EIGEN_PARSED_BY_DOXYGEN
+
+ protected:
+
+ /** Computes the sparse Cholesky decomposition of \a matrix */
+ template<bool DoLDLT>
+ void compute(const MatrixType& matrix)
+ {
+ eigen_assert(matrix.rows()==matrix.cols());
+ Index size = matrix.cols();
+ CholMatrixType ap(size,size);
+ ordering(matrix, ap);
+ analyzePattern_preordered(ap, DoLDLT);
+ factorize_preordered<DoLDLT>(ap);
+ }
+
+ template<bool DoLDLT>
+ void factorize(const MatrixType& a)
+ {
+ eigen_assert(a.rows()==a.cols());
+ int size = a.cols();
+ CholMatrixType ap(size,size);
+ ap.template selfadjointView<Upper>() = a.template selfadjointView<UpLo>().twistedBy(m_P);
+ factorize_preordered<DoLDLT>(ap);
+ }
+
+ template<bool DoLDLT>
+ void factorize_preordered(const CholMatrixType& a);
+
+ void analyzePattern(const MatrixType& a, bool doLDLT)
+ {
+ eigen_assert(a.rows()==a.cols());
+ int size = a.cols();
+ CholMatrixType ap(size,size);
+ ordering(a, ap);
+ analyzePattern_preordered(ap,doLDLT);
+ }
+ void analyzePattern_preordered(const CholMatrixType& a, bool doLDLT);
+
+ void ordering(const MatrixType& a, CholMatrixType& ap);
+
+ /** keeps off-diagonal entries; drops diagonal entries */
+ struct keep_diag {
+ inline bool operator() (const Index& row, const Index& col, const Scalar&) const
+ {
+ return row!=col;
+ }
+ };
+
+ mutable ComputationInfo m_info;
+ bool m_isInitialized;
+ bool m_factorizationIsOk;
+ bool m_analysisIsOk;
+
+ CholMatrixType m_matrix;
+ VectorType m_diag; // the diagonal coefficients (LDLT mode)
+ VectorXi m_parent; // elimination tree
+ VectorXi m_nonZerosPerCol;
+ PermutationMatrix<Dynamic,Dynamic,Index> m_P; // the permutation
+ PermutationMatrix<Dynamic,Dynamic,Index> m_Pinv; // the inverse permutation
+
+ RealScalar m_shiftOffset;
+ RealScalar m_shiftScale;
+};
+
+template<typename _MatrixType, int _UpLo = Lower> class SimplicialLLT;
+template<typename _MatrixType, int _UpLo = Lower> class SimplicialLDLT;
+template<typename _MatrixType, int _UpLo = Lower> class SimplicialCholesky;
+
+namespace internal {
+
+template<typename _MatrixType, int _UpLo> struct traits<SimplicialLLT<_MatrixType,_UpLo> >
+{
+ typedef _MatrixType MatrixType;
+ enum { UpLo = _UpLo };
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::Index Index;
+ typedef SparseMatrix<Scalar, ColMajor, Index> CholMatrixType;
+ typedef SparseTriangularView<CholMatrixType, Eigen::Lower> MatrixL;
+ typedef SparseTriangularView<typename CholMatrixType::AdjointReturnType, Eigen::Upper> MatrixU;
+ static inline MatrixL getL(const MatrixType& m) { return m; }
+ static inline MatrixU getU(const MatrixType& m) { return m.adjoint(); }
+};
+
+template<typename _MatrixType,int _UpLo> struct traits<SimplicialLDLT<_MatrixType,_UpLo> >
+{
+ typedef _MatrixType MatrixType;
+ enum { UpLo = _UpLo };
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::Index Index;
+ typedef SparseMatrix<Scalar, ColMajor, Index> CholMatrixType;
+ typedef SparseTriangularView<CholMatrixType, Eigen::UnitLower> MatrixL;
+ typedef SparseTriangularView<typename CholMatrixType::AdjointReturnType, Eigen::UnitUpper> MatrixU;
+ static inline MatrixL getL(const MatrixType& m) { return m; }
+ static inline MatrixU getU(const MatrixType& m) { return m.adjoint(); }
+};
+
+template<typename _MatrixType, int _UpLo> struct traits<SimplicialCholesky<_MatrixType,_UpLo> >
+{
+ typedef _MatrixType MatrixType;
+ enum { UpLo = _UpLo };
+};
+
+}
+
+/** \ingroup SparseCholesky_Module
+ * \class SimplicialLLT
+ * \brief A direct sparse LLT Cholesky factorizations
+ *
+ * This class provides a LL^T Cholesky factorizations of sparse matrices that are
+ * selfadjoint and positive definite. The factorization allows for solving A.X = B where
+ * X and B can be either dense or sparse.
+ *
+ * In order to reduce the fill-in, a symmetric permutation P is applied prior to the factorization
+ * such that the factorized matrix is P A P^-1.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower
+ * or Upper. Default is Lower.
+ *
+ * \sa class SimplicialLDLT
+ */
+template<typename _MatrixType, int _UpLo>
+ class SimplicialLLT : public SimplicialCholeskyBase<SimplicialLLT<_MatrixType,_UpLo> >
+{
+public:
+ typedef _MatrixType MatrixType;
+ enum { UpLo = _UpLo };
+ typedef SimplicialCholeskyBase<SimplicialLLT> Base;
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef typename MatrixType::Index Index;
+ typedef SparseMatrix<Scalar,ColMajor,Index> CholMatrixType;
+ typedef Matrix<Scalar,Dynamic,1> VectorType;
+ typedef internal::traits<SimplicialLLT> Traits;
+ typedef typename Traits::MatrixL MatrixL;
+ typedef typename Traits::MatrixU MatrixU;
+public:
+ /** Default constructor */
+ SimplicialLLT() : Base() {}
+ /** Constructs and performs the LLT factorization of \a matrix */
+ SimplicialLLT(const MatrixType& matrix)
+ : Base(matrix) {}
+
+ /** \returns an expression of the factor L */
+ inline const MatrixL matrixL() const {
+ eigen_assert(Base::m_factorizationIsOk && "Simplicial LLT not factorized");
+ return Traits::getL(Base::m_matrix);
+ }
+
+ /** \returns an expression of the factor U (= L^*) */
+ inline const MatrixU matrixU() const {
+ eigen_assert(Base::m_factorizationIsOk && "Simplicial LLT not factorized");
+ return Traits::getU(Base::m_matrix);
+ }
+
+ /** Computes the sparse Cholesky decomposition of \a matrix */
+ SimplicialLLT& compute(const MatrixType& matrix)
+ {
+ Base::template compute<false>(matrix);
+ return *this;
+ }
+
+ /** Performs a symbolic decomposition on the sparcity of \a matrix.
+ *
+ * This function is particularly useful when solving for several problems having the same structure.
+ *
+ * \sa factorize()
+ */
+ void analyzePattern(const MatrixType& a)
+ {
+ Base::analyzePattern(a, false);
+ }
+
+ /** Performs a numeric decomposition of \a matrix
+ *
+ * The given matrix must has the same sparcity than the matrix on which the symbolic decomposition has been performed.
+ *
+ * \sa analyzePattern()
+ */
+ void factorize(const MatrixType& a)
+ {
+ Base::template factorize<false>(a);
+ }
+
+ /** \returns the determinant of the underlying matrix from the current factorization */
+ Scalar determinant() const
+ {
+ Scalar detL = Base::m_matrix.diagonal().prod();
+ return internal::abs2(detL);
+ }
+};
+
+/** \ingroup SparseCholesky_Module
+ * \class SimplicialLDLT
+ * \brief A direct sparse LDLT Cholesky factorizations without square root.
+ *
+ * This class provides a LDL^T Cholesky factorizations without square root of sparse matrices that are
+ * selfadjoint and positive definite. The factorization allows for solving A.X = B where
+ * X and B can be either dense or sparse.
+ *
+ * In order to reduce the fill-in, a symmetric permutation P is applied prior to the factorization
+ * such that the factorized matrix is P A P^-1.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower
+ * or Upper. Default is Lower.
+ *
+ * \sa class SimplicialLLT
+ */
+template<typename _MatrixType, int _UpLo>
+ class SimplicialLDLT : public SimplicialCholeskyBase<SimplicialLDLT<_MatrixType,_UpLo> >
+{
+public:
+ typedef _MatrixType MatrixType;
+ enum { UpLo = _UpLo };
+ typedef SimplicialCholeskyBase<SimplicialLDLT> Base;
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef typename MatrixType::Index Index;
+ typedef SparseMatrix<Scalar,ColMajor,Index> CholMatrixType;
+ typedef Matrix<Scalar,Dynamic,1> VectorType;
+ typedef internal::traits<SimplicialLDLT> Traits;
+ typedef typename Traits::MatrixL MatrixL;
+ typedef typename Traits::MatrixU MatrixU;
+public:
+ /** Default constructor */
+ SimplicialLDLT() : Base() {}
+
+ /** Constructs and performs the LLT factorization of \a matrix */
+ SimplicialLDLT(const MatrixType& matrix)
+ : Base(matrix) {}
+
+ /** \returns a vector expression of the diagonal D */
+ inline const VectorType vectorD() const {
+ eigen_assert(Base::m_factorizationIsOk && "Simplicial LDLT not factorized");
+ return Base::m_diag;
+ }
+ /** \returns an expression of the factor L */
+ inline const MatrixL matrixL() const {
+ eigen_assert(Base::m_factorizationIsOk && "Simplicial LDLT not factorized");
+ return Traits::getL(Base::m_matrix);
+ }
+
+ /** \returns an expression of the factor U (= L^*) */
+ inline const MatrixU matrixU() const {
+ eigen_assert(Base::m_factorizationIsOk && "Simplicial LDLT not factorized");
+ return Traits::getU(Base::m_matrix);
+ }
+
+ /** Computes the sparse Cholesky decomposition of \a matrix */
+ SimplicialLDLT& compute(const MatrixType& matrix)
+ {
+ Base::template compute<true>(matrix);
+ return *this;
+ }
+
+ /** Performs a symbolic decomposition on the sparcity of \a matrix.
+ *
+ * This function is particularly useful when solving for several problems having the same structure.
+ *
+ * \sa factorize()
+ */
+ void analyzePattern(const MatrixType& a)
+ {
+ Base::analyzePattern(a, true);
+ }
+
+ /** Performs a numeric decomposition of \a matrix
+ *
+ * The given matrix must has the same sparcity than the matrix on which the symbolic decomposition has been performed.
+ *
+ * \sa analyzePattern()
+ */
+ void factorize(const MatrixType& a)
+ {
+ Base::template factorize<true>(a);
+ }
+
+ /** \returns the determinant of the underlying matrix from the current factorization */
+ Scalar determinant() const
+ {
+ return Base::m_diag.prod();
+ }
+};
+
+/** \deprecated use SimplicialLDLT or class SimplicialLLT
+ * \ingroup SparseCholesky_Module
+ * \class SimplicialCholesky
+ *
+ * \sa class SimplicialLDLT, class SimplicialLLT
+ */
+template<typename _MatrixType, int _UpLo>
+ class SimplicialCholesky : public SimplicialCholeskyBase<SimplicialCholesky<_MatrixType,_UpLo> >
+{
+public:
+ typedef _MatrixType MatrixType;
+ enum { UpLo = _UpLo };
+ typedef SimplicialCholeskyBase<SimplicialCholesky> Base;
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef typename MatrixType::Index Index;
+ typedef SparseMatrix<Scalar,ColMajor,Index> CholMatrixType;
+ typedef Matrix<Scalar,Dynamic,1> VectorType;
+ typedef internal::traits<SimplicialCholesky> Traits;
+ typedef internal::traits<SimplicialLDLT<MatrixType,UpLo> > LDLTTraits;
+ typedef internal::traits<SimplicialLLT<MatrixType,UpLo> > LLTTraits;
+ public:
+ SimplicialCholesky() : Base(), m_LDLT(true) {}
+
+ SimplicialCholesky(const MatrixType& matrix)
+ : Base(), m_LDLT(true)
+ {
+ compute(matrix);
+ }
+
+ SimplicialCholesky& setMode(SimplicialCholeskyMode mode)
+ {
+ switch(mode)
+ {
+ case SimplicialCholeskyLLT:
+ m_LDLT = false;
+ break;
+ case SimplicialCholeskyLDLT:
+ m_LDLT = true;
+ break;
+ default:
+ break;
+ }
+
+ return *this;
+ }
+
+ inline const VectorType vectorD() const {
+ eigen_assert(Base::m_factorizationIsOk && "Simplicial Cholesky not factorized");
+ return Base::m_diag;
+ }
+ inline const CholMatrixType rawMatrix() const {
+ eigen_assert(Base::m_factorizationIsOk && "Simplicial Cholesky not factorized");
+ return Base::m_matrix;
+ }
+
+ /** Computes the sparse Cholesky decomposition of \a matrix */
+ SimplicialCholesky& compute(const MatrixType& matrix)
+ {
+ if(m_LDLT)
+ Base::template compute<true>(matrix);
+ else
+ Base::template compute<false>(matrix);
+ return *this;
+ }
+
+ /** Performs a symbolic decomposition on the sparcity of \a matrix.
+ *
+ * This function is particularly useful when solving for several problems having the same structure.
+ *
+ * \sa factorize()
+ */
+ void analyzePattern(const MatrixType& a)
+ {
+ Base::analyzePattern(a, m_LDLT);
+ }
+
+ /** Performs a numeric decomposition of \a matrix
+ *
+ * The given matrix must has the same sparcity than the matrix on which the symbolic decomposition has been performed.
+ *
+ * \sa analyzePattern()
+ */
+ void factorize(const MatrixType& a)
+ {
+ if(m_LDLT)
+ Base::template factorize<true>(a);
+ else
+ Base::template factorize<false>(a);
+ }
+
+ /** \internal */
+ template<typename Rhs,typename Dest>
+ void _solve(const MatrixBase<Rhs> &b, MatrixBase<Dest> &dest) const
+ {
+ eigen_assert(Base::m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()");
+ eigen_assert(Base::m_matrix.rows()==b.rows());
+
+ if(Base::m_info!=Success)
+ return;
+
+ if(Base::m_P.size()>0)
+ dest = Base::m_P * b;
+ else
+ dest = b;
+
+ if(Base::m_matrix.nonZeros()>0) // otherwise L==I
+ {
+ if(m_LDLT)
+ LDLTTraits::getL(Base::m_matrix).solveInPlace(dest);
+ else
+ LLTTraits::getL(Base::m_matrix).solveInPlace(dest);
+ }
+
+ if(Base::m_diag.size()>0)
+ dest = Base::m_diag.asDiagonal().inverse() * dest;
+
+ if (Base::m_matrix.nonZeros()>0) // otherwise I==I
+ {
+ if(m_LDLT)
+ LDLTTraits::getU(Base::m_matrix).solveInPlace(dest);
+ else
+ LLTTraits::getU(Base::m_matrix).solveInPlace(dest);
+ }
+
+ if(Base::m_P.size()>0)
+ dest = Base::m_Pinv * dest;
+ }
+
+ Scalar determinant() const
+ {
+ if(m_LDLT)
+ {
+ return Base::m_diag.prod();
+ }
+ else
+ {
+ Scalar detL = Diagonal<const CholMatrixType>(Base::m_matrix).prod();
+ return internal::abs2(detL);
+ }
+ }
+
+ protected:
+ bool m_LDLT;
+};
+
+template<typename Derived>
+void SimplicialCholeskyBase<Derived>::ordering(const MatrixType& a, CholMatrixType& ap)
+{
+ eigen_assert(a.rows()==a.cols());
+ const Index size = a.rows();
+ // TODO allows to configure the permutation
+ // Note that amd compute the inverse permutation
+ {
+ CholMatrixType C;
+ C = a.template selfadjointView<UpLo>();
+ // remove diagonal entries:
+ // seems not to be needed
+ // C.prune(keep_diag());
+ internal::minimum_degree_ordering(C, m_Pinv);
+ }
+
+ if(m_Pinv.size()>0)
+ m_P = m_Pinv.inverse();
+ else
+ m_P.resize(0);
+
+ ap.resize(size,size);
+ ap.template selfadjointView<Upper>() = a.template selfadjointView<UpLo>().twistedBy(m_P);
+}
+
+template<typename Derived>
+void SimplicialCholeskyBase<Derived>::analyzePattern_preordered(const CholMatrixType& ap, bool doLDLT)
+{
+ const Index size = ap.rows();
+ m_matrix.resize(size, size);
+ m_parent.resize(size);
+ m_nonZerosPerCol.resize(size);
+
+ ei_declare_aligned_stack_constructed_variable(Index, tags, size, 0);
+
+ for(Index k = 0; k < size; ++k)
+ {
+ /* L(k,:) pattern: all nodes reachable in etree from nz in A(0:k-1,k) */
+ m_parent[k] = -1; /* parent of k is not yet known */
+ tags[k] = k; /* mark node k as visited */
+ m_nonZerosPerCol[k] = 0; /* count of nonzeros in column k of L */
+ for(typename CholMatrixType::InnerIterator it(ap,k); it; ++it)
+ {
+ Index i = it.index();
+ if(i < k)
+ {
+ /* follow path from i to root of etree, stop at flagged node */
+ for(; tags[i] != k; i = m_parent[i])
+ {
+ /* find parent of i if not yet determined */
+ if (m_parent[i] == -1)
+ m_parent[i] = k;
+ m_nonZerosPerCol[i]++; /* L (k,i) is nonzero */
+ tags[i] = k; /* mark i as visited */
+ }
+ }
+ }
+ }
+
+ /* construct Lp index array from m_nonZerosPerCol column counts */
+ Index* Lp = m_matrix.outerIndexPtr();
+ Lp[0] = 0;
+ for(Index k = 0; k < size; ++k)
+ Lp[k+1] = Lp[k] + m_nonZerosPerCol[k] + (doLDLT ? 0 : 1);
+
+ m_matrix.resizeNonZeros(Lp[size]);
+
+ m_isInitialized = true;
+ m_info = Success;
+ m_analysisIsOk = true;
+ m_factorizationIsOk = false;
+}
+
+
+template<typename Derived>
+template<bool DoLDLT>
+void SimplicialCholeskyBase<Derived>::factorize_preordered(const CholMatrixType& ap)
+{
+ eigen_assert(m_analysisIsOk && "You must first call analyzePattern()");
+ eigen_assert(ap.rows()==ap.cols());
+ const Index size = ap.rows();
+ eigen_assert(m_parent.size()==size);
+ eigen_assert(m_nonZerosPerCol.size()==size);
+
+ const Index* Lp = m_matrix.outerIndexPtr();
+ Index* Li = m_matrix.innerIndexPtr();
+ Scalar* Lx = m_matrix.valuePtr();
+
+ ei_declare_aligned_stack_constructed_variable(Scalar, y, size, 0);
+ ei_declare_aligned_stack_constructed_variable(Index, pattern, size, 0);
+ ei_declare_aligned_stack_constructed_variable(Index, tags, size, 0);
+
+ bool ok = true;
+ m_diag.resize(DoLDLT ? size : 0);
+
+ for(Index k = 0; k < size; ++k)
+ {
+ // compute nonzero pattern of kth row of L, in topological order
+ y[k] = 0.0; // Y(0:k) is now all zero
+ Index top = size; // stack for pattern is empty
+ tags[k] = k; // mark node k as visited
+ m_nonZerosPerCol[k] = 0; // count of nonzeros in column k of L
+ for(typename MatrixType::InnerIterator it(ap,k); it; ++it)
+ {
+ Index i = it.index();
+ if(i <= k)
+ {
+ y[i] += internal::conj(it.value()); /* scatter A(i,k) into Y (sum duplicates) */
+ Index len;
+ for(len = 0; tags[i] != k; i = m_parent[i])
+ {
+ pattern[len++] = i; /* L(k,i) is nonzero */
+ tags[i] = k; /* mark i as visited */
+ }
+ while(len > 0)
+ pattern[--top] = pattern[--len];
+ }
+ }
+
+ /* compute numerical values kth row of L (a sparse triangular solve) */
+
+ RealScalar d = internal::real(y[k]) * m_shiftScale + m_shiftOffset; // get D(k,k), apply the shift function, and clear Y(k)
+ y[k] = 0.0;
+ for(; top < size; ++top)
+ {
+ Index i = pattern[top]; /* pattern[top:n-1] is pattern of L(:,k) */
+ Scalar yi = y[i]; /* get and clear Y(i) */
+ y[i] = 0.0;
+
+ /* the nonzero entry L(k,i) */
+ Scalar l_ki;
+ if(DoLDLT)
+ l_ki = yi / m_diag[i];
+ else
+ yi = l_ki = yi / Lx[Lp[i]];
+
+ Index p2 = Lp[i] + m_nonZerosPerCol[i];
+ Index p;
+ for(p = Lp[i] + (DoLDLT ? 0 : 1); p < p2; ++p)
+ y[Li[p]] -= internal::conj(Lx[p]) * yi;
+ d -= internal::real(l_ki * internal::conj(yi));
+ Li[p] = k; /* store L(k,i) in column form of L */
+ Lx[p] = l_ki;
+ ++m_nonZerosPerCol[i]; /* increment count of nonzeros in col i */
+ }
+ if(DoLDLT)
+ {
+ m_diag[k] = d;
+ if(d == RealScalar(0))
+ {
+ ok = false; /* failure, D(k,k) is zero */
+ break;
+ }
+ }
+ else
+ {
+ Index p = Lp[k] + m_nonZerosPerCol[k]++;
+ Li[p] = k ; /* store L(k,k) = sqrt (d) in column k */
+ if(d <= RealScalar(0)) {
+ ok = false; /* failure, matrix is not positive definite */
+ break;
+ }
+ Lx[p] = internal::sqrt(d) ;
+ }
+ }
+
+ m_info = ok ? Success : NumericalIssue;
+ m_factorizationIsOk = true;
+}
+
+namespace internal {
+
+template<typename Derived, typename Rhs>
+struct solve_retval<SimplicialCholeskyBase<Derived>, Rhs>
+ : solve_retval_base<SimplicialCholeskyBase<Derived>, Rhs>
+{
+ typedef SimplicialCholeskyBase<Derived> Dec;
+ EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec().derived()._solve(rhs(),dst);
+ }
+};
+
+template<typename Derived, typename Rhs>
+struct sparse_solve_retval<SimplicialCholeskyBase<Derived>, Rhs>
+ : sparse_solve_retval_base<SimplicialCholeskyBase<Derived>, Rhs>
+{
+ typedef SimplicialCholeskyBase<Derived> Dec;
+ EIGEN_MAKE_SPARSE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec().derived()._solve_sparse(rhs(),dst);
+ }
+};
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_SIMPLICIAL_CHOLESKY_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/AmbiVector.h b/extern/Eigen3/Eigen/src/SparseCore/AmbiVector.h
index 2ea8ba3096b..6cfaadbaa9a 100644
--- a/extern/Eigen3/Eigen/src/Sparse/AmbiVector.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/AmbiVector.h
@@ -3,28 +3,17 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_AMBIVECTOR_H
#define EIGEN_AMBIVECTOR_H
+namespace Eigen {
+
+namespace internal {
+
/** \internal
* Hybrid sparse/dense vector class designed for intensive read-write operations.
*
@@ -299,7 +288,7 @@ class AmbiVector<_Scalar,_Index>::Iterator
* In practice, all coefficients having a magnitude smaller than \a epsilon
* are skipped.
*/
- Iterator(const AmbiVector& vec, RealScalar epsilon = RealScalar(0.1)*NumTraits<RealScalar>::dummy_precision())
+ Iterator(const AmbiVector& vec, RealScalar epsilon = 0)
: m_vector(vec)
{
m_epsilon = epsilon;
@@ -315,7 +304,7 @@ class AmbiVector<_Scalar,_Index>::Iterator
{
ListEl* EIGEN_RESTRICT llElements = reinterpret_cast<ListEl*>(m_vector.m_buffer);
m_currentEl = m_vector.m_llStart;
- while (m_currentEl>=0 && internal::abs(llElements[m_currentEl].value)<m_epsilon)
+ while (m_currentEl>=0 && internal::abs(llElements[m_currentEl].value)<=m_epsilon)
m_currentEl = llElements[m_currentEl].next;
if (m_currentEl<0)
{
@@ -375,5 +364,8 @@ class AmbiVector<_Scalar,_Index>::Iterator
bool m_isDense; // mode of the vector
};
+} // end namespace internal
+
+} // end namespace Eigen
#endif // EIGEN_AMBIVECTOR_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/CompressedStorage.h b/extern/Eigen3/Eigen/src/SparseCore/CompressedStorage.h
index b3bde272ec2..85a998aff10 100644
--- a/extern/Eigen3/Eigen/src/Sparse/CompressedStorage.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/CompressedStorage.h
@@ -3,29 +3,19 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COMPRESSED_STORAGE_H
#define EIGEN_COMPRESSED_STORAGE_H
-/** Stores a sparse set of values as a list of values and a list of indices.
+namespace Eigen {
+
+namespace internal {
+
+/** \internal
+ * Stores a sparse set of values as a list of values and a list of indices.
*
*/
template<typename _Scalar,typename _Index>
@@ -218,8 +208,8 @@ class CompressedStorage
Index* newIndices = new Index[size];
size_t copySize = (std::min)(size, m_size);
// copy
- memcpy(newValues, m_values, copySize * sizeof(Scalar));
- memcpy(newIndices, m_indices, copySize * sizeof(Index));
+ internal::smart_copy(m_values, m_values+copySize, newValues);
+ internal::smart_copy(m_indices, m_indices+copySize, newIndices);
// delete old stuff
delete[] m_values;
delete[] m_indices;
@@ -236,4 +226,8 @@ class CompressedStorage
};
+} // end namespace internal
+
+} // end namespace Eigen
+
#endif // EIGEN_COMPRESSED_STORAGE_H
diff --git a/extern/Eigen3/Eigen/src/SparseCore/ConservativeSparseSparseProduct.h b/extern/Eigen3/Eigen/src/SparseCore/ConservativeSparseSparseProduct.h
new file mode 100644
index 00000000000..16b5e1dba6c
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/SparseCore/ConservativeSparseSparseProduct.h
@@ -0,0 +1,245 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_CONSERVATIVESPARSESPARSEPRODUCT_H
+#define EIGEN_CONSERVATIVESPARSESPARSEPRODUCT_H
+
+namespace Eigen {
+
+namespace internal {
+
+template<typename Lhs, typename Rhs, typename ResultType>
+static void conservative_sparse_sparse_product_impl(const Lhs& lhs, const Rhs& rhs, ResultType& res)
+{
+ typedef typename remove_all<Lhs>::type::Scalar Scalar;
+ typedef typename remove_all<Lhs>::type::Index Index;
+
+ // make sure to call innerSize/outerSize since we fake the storage order.
+ Index rows = lhs.innerSize();
+ Index cols = rhs.outerSize();
+ eigen_assert(lhs.outerSize() == rhs.innerSize());
+
+ std::vector<bool> mask(rows,false);
+ Matrix<Scalar,Dynamic,1> values(rows);
+ Matrix<Index,Dynamic,1> indices(rows);
+
+ // estimate the number of non zero entries
+ // given a rhs column containing Y non zeros, we assume that the respective Y columns
+ // of the lhs differs in average of one non zeros, thus the number of non zeros for
+ // the product of a rhs column with the lhs is X+Y where X is the average number of non zero
+ // per column of the lhs.
+ // Therefore, we have nnz(lhs*rhs) = nnz(lhs) + nnz(rhs)
+ Index estimated_nnz_prod = lhs.nonZeros() + rhs.nonZeros();
+
+ res.setZero();
+ res.reserve(Index(estimated_nnz_prod));
+ // we compute each column of the result, one after the other
+ for (Index j=0; j<cols; ++j)
+ {
+
+ res.startVec(j);
+ Index nnz = 0;
+ for (typename Rhs::InnerIterator rhsIt(rhs, j); rhsIt; ++rhsIt)
+ {
+ Scalar y = rhsIt.value();
+ Index k = rhsIt.index();
+ for (typename Lhs::InnerIterator lhsIt(lhs, k); lhsIt; ++lhsIt)
+ {
+ Index i = lhsIt.index();
+ Scalar x = lhsIt.value();
+ if(!mask[i])
+ {
+ mask[i] = true;
+ values[i] = x * y;
+ indices[nnz] = i;
+ ++nnz;
+ }
+ else
+ values[i] += x * y;
+ }
+ }
+
+ // unordered insertion
+ for(int k=0; k<nnz; ++k)
+ {
+ int i = indices[k];
+ res.insertBackByOuterInnerUnordered(j,i) = values[i];
+ mask[i] = false;
+ }
+
+#if 0
+ // alternative ordered insertion code:
+
+ int t200 = rows/(log2(200)*1.39);
+ int t = (rows*100)/139;
+
+ // FIXME reserve nnz non zeros
+ // FIXME implement fast sort algorithms for very small nnz
+ // if the result is sparse enough => use a quick sort
+ // otherwise => loop through the entire vector
+ // In order to avoid to perform an expensive log2 when the
+ // result is clearly very sparse we use a linear bound up to 200.
+ //if((nnz<200 && nnz<t200) || nnz * log2(nnz) < t)
+ //res.startVec(j);
+ if(true)
+ {
+ if(nnz>1) std::sort(indices.data(),indices.data()+nnz);
+ for(int k=0; k<nnz; ++k)
+ {
+ int i = indices[k];
+ res.insertBackByOuterInner(j,i) = values[i];
+ mask[i] = false;
+ }
+ }
+ else
+ {
+ // dense path
+ for(int i=0; i<rows; ++i)
+ {
+ if(mask[i])
+ {
+ mask[i] = false;
+ res.insertBackByOuterInner(j,i) = values[i];
+ }
+ }
+ }
+#endif
+
+ }
+ res.finalize();
+}
+
+
+} // end namespace internal
+
+namespace internal {
+
+template<typename Lhs, typename Rhs, typename ResultType,
+ int LhsStorageOrder = traits<Lhs>::Flags&RowMajorBit,
+ int RhsStorageOrder = traits<Rhs>::Flags&RowMajorBit,
+ int ResStorageOrder = traits<ResultType>::Flags&RowMajorBit>
+struct conservative_sparse_sparse_product_selector;
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct conservative_sparse_sparse_product_selector<Lhs,Rhs,ResultType,ColMajor,ColMajor,ColMajor>
+{
+ typedef typename remove_all<Lhs>::type LhsCleaned;
+ typedef typename LhsCleaned::Scalar Scalar;
+
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
+ {
+ typedef SparseMatrix<typename ResultType::Scalar,RowMajor> RowMajorMatrix;
+ typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
+ ColMajorMatrix resCol(lhs.rows(),rhs.cols());
+ internal::conservative_sparse_sparse_product_impl<Lhs,Rhs,ColMajorMatrix>(lhs, rhs, resCol);
+ // sort the non zeros:
+ RowMajorMatrix resRow(resCol);
+ res = resRow;
+ }
+};
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct conservative_sparse_sparse_product_selector<Lhs,Rhs,ResultType,RowMajor,ColMajor,ColMajor>
+{
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
+ {
+ typedef SparseMatrix<typename ResultType::Scalar,RowMajor> RowMajorMatrix;
+ RowMajorMatrix rhsRow = rhs;
+ RowMajorMatrix resRow(lhs.rows(), rhs.cols());
+ internal::conservative_sparse_sparse_product_impl<RowMajorMatrix,Lhs,RowMajorMatrix>(rhsRow, lhs, resRow);
+ res = resRow;
+ }
+};
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct conservative_sparse_sparse_product_selector<Lhs,Rhs,ResultType,ColMajor,RowMajor,ColMajor>
+{
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
+ {
+ typedef SparseMatrix<typename ResultType::Scalar,RowMajor> RowMajorMatrix;
+ RowMajorMatrix lhsRow = lhs;
+ RowMajorMatrix resRow(lhs.rows(), rhs.cols());
+ internal::conservative_sparse_sparse_product_impl<Rhs,RowMajorMatrix,RowMajorMatrix>(rhs, lhsRow, resRow);
+ res = resRow;
+ }
+};
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct conservative_sparse_sparse_product_selector<Lhs,Rhs,ResultType,RowMajor,RowMajor,ColMajor>
+{
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
+ {
+ typedef SparseMatrix<typename ResultType::Scalar,RowMajor> RowMajorMatrix;
+ RowMajorMatrix resRow(lhs.rows(), rhs.cols());
+ internal::conservative_sparse_sparse_product_impl<Rhs,Lhs,RowMajorMatrix>(rhs, lhs, resRow);
+ res = resRow;
+ }
+};
+
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct conservative_sparse_sparse_product_selector<Lhs,Rhs,ResultType,ColMajor,ColMajor,RowMajor>
+{
+ typedef typename traits<typename remove_all<Lhs>::type>::Scalar Scalar;
+
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
+ {
+ typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
+ ColMajorMatrix resCol(lhs.rows(), rhs.cols());
+ internal::conservative_sparse_sparse_product_impl<Lhs,Rhs,ColMajorMatrix>(lhs, rhs, resCol);
+ res = resCol;
+ }
+};
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct conservative_sparse_sparse_product_selector<Lhs,Rhs,ResultType,RowMajor,ColMajor,RowMajor>
+{
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
+ {
+ typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
+ ColMajorMatrix lhsCol = lhs;
+ ColMajorMatrix resCol(lhs.rows(), rhs.cols());
+ internal::conservative_sparse_sparse_product_impl<ColMajorMatrix,Rhs,ColMajorMatrix>(lhsCol, rhs, resCol);
+ res = resCol;
+ }
+};
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct conservative_sparse_sparse_product_selector<Lhs,Rhs,ResultType,ColMajor,RowMajor,RowMajor>
+{
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
+ {
+ typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
+ ColMajorMatrix rhsCol = rhs;
+ ColMajorMatrix resCol(lhs.rows(), rhs.cols());
+ internal::conservative_sparse_sparse_product_impl<Lhs,ColMajorMatrix,ColMajorMatrix>(lhs, rhsCol, resCol);
+ res = resCol;
+ }
+};
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct conservative_sparse_sparse_product_selector<Lhs,Rhs,ResultType,RowMajor,RowMajor,RowMajor>
+{
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res)
+ {
+ typedef SparseMatrix<typename ResultType::Scalar,RowMajor> RowMajorMatrix;
+ typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
+ RowMajorMatrix resRow(lhs.rows(),rhs.cols());
+ internal::conservative_sparse_sparse_product_impl<Rhs,Lhs,RowMajorMatrix>(rhs, lhs, resRow);
+ // sort the non zeros:
+ ColMajorMatrix resCol(resRow);
+ res = resCol;
+ }
+};
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_CONSERVATIVESPARSESPARSEPRODUCT_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/CoreIterators.h b/extern/Eigen3/Eigen/src/SparseCore/CoreIterators.h
index b4beaeee69e..6da4683d2c2 100644
--- a/extern/Eigen3/Eigen/src/Sparse/CoreIterators.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/CoreIterators.h
@@ -3,32 +3,20 @@
//
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COREITERATORS_H
#define EIGEN_COREITERATORS_H
+namespace Eigen {
+
/* This file contains the respective InnerIterator definition of the expressions defined in Eigen/Core
*/
-/** \class InnerIterator
+/** \ingroup SparseCore_Module
+ * \class InnerIterator
* \brief An InnerIterator allows to loop over the element of a sparse (or dense) matrix or expression
*
* todo
@@ -68,4 +56,6 @@ template<typename Derived> class DenseBase<Derived>::InnerIterator
const Index m_end;
};
+} // end namespace Eigen
+
#endif // EIGEN_COREITERATORS_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/MappedSparseMatrix.h b/extern/Eigen3/Eigen/src/SparseCore/MappedSparseMatrix.h
index 31a431fb224..93cd4832dea 100644
--- a/extern/Eigen3/Eigen/src/Sparse/MappedSparseMatrix.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/MappedSparseMatrix.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MAPPED_SPARSEMATRIX_H
#define EIGEN_MAPPED_SPARSEMATRIX_H
+namespace Eigen {
+
/** \class MappedSparseMatrix
*
* \brief Sparse matrix
@@ -46,9 +33,9 @@ class MappedSparseMatrix
{
public:
EIGEN_SPARSE_PUBLIC_INTERFACE(MappedSparseMatrix)
+ enum { IsRowMajor = Base::IsRowMajor };
protected:
- enum { IsRowMajor = Base::IsRowMajor };
Index m_outerSize;
Index m_innerSize;
@@ -63,18 +50,17 @@ class MappedSparseMatrix
inline Index cols() const { return IsRowMajor ? m_innerSize : m_outerSize; }
inline Index innerSize() const { return m_innerSize; }
inline Index outerSize() const { return m_outerSize; }
- inline Index innerNonZeros(Index j) const { return m_outerIndex[j+1]-m_outerIndex[j]; }
//----------------------------------------
// direct access interface
- inline const Scalar* _valuePtr() const { return m_values; }
- inline Scalar* _valuePtr() { return m_values; }
+ inline const Scalar* valuePtr() const { return m_values; }
+ inline Scalar* valuePtr() { return m_values; }
- inline const Index* _innerIndexPtr() const { return m_innerIndices; }
- inline Index* _innerIndexPtr() { return m_innerIndices; }
+ inline const Index* innerIndexPtr() const { return m_innerIndices; }
+ inline Index* innerIndexPtr() { return m_innerIndices; }
- inline const Index* _outerIndexPtr() const { return m_outerIndex; }
- inline Index* _outerIndexPtr() { return m_outerIndex; }
+ inline const Index* outerIndexPtr() const { return m_outerIndex; }
+ inline Index* outerIndexPtr() { return m_outerIndex; }
//----------------------------------------
inline Scalar coeff(Index row, Index col) const
@@ -112,6 +98,7 @@ class MappedSparseMatrix
}
class InnerIterator;
+ class ReverseInnerIterator;
/** \returns the number of non zero coefficients */
inline Index nonZeros() const { return m_nnz; }
@@ -132,23 +119,17 @@ class MappedSparseMatrix<Scalar,_Flags,_Index>::InnerIterator
InnerIterator(const MappedSparseMatrix& mat, Index outer)
: m_matrix(mat),
m_outer(outer),
- m_id(mat._outerIndexPtr()[outer]),
+ m_id(mat.outerIndexPtr()[outer]),
m_start(m_id),
- m_end(mat._outerIndexPtr()[outer+1])
- {}
-
- template<unsigned int Added, unsigned int Removed>
- InnerIterator(const Flagged<MappedSparseMatrix,Added,Removed>& mat, Index outer)
- : m_matrix(mat._expression()), m_id(m_matrix._outerIndexPtr()[outer]),
- m_start(m_id), m_end(m_matrix._outerIndexPtr()[outer+1])
+ m_end(mat.outerIndexPtr()[outer+1])
{}
inline InnerIterator& operator++() { m_id++; return *this; }
- inline Scalar value() const { return m_matrix._valuePtr()[m_id]; }
- inline Scalar& valueRef() { return const_cast<Scalar&>(m_matrix._valuePtr()[m_id]); }
+ inline Scalar value() const { return m_matrix.valuePtr()[m_id]; }
+ inline Scalar& valueRef() { return const_cast<Scalar&>(m_matrix.valuePtr()[m_id]); }
- inline Index index() const { return m_matrix._innerIndexPtr()[m_id]; }
+ inline Index index() const { return m_matrix.innerIndexPtr()[m_id]; }
inline Index row() const { return IsRowMajor ? m_outer : index(); }
inline Index col() const { return IsRowMajor ? index() : m_outer; }
@@ -162,4 +143,37 @@ class MappedSparseMatrix<Scalar,_Flags,_Index>::InnerIterator
const Index m_end;
};
+template<typename Scalar, int _Flags, typename _Index>
+class MappedSparseMatrix<Scalar,_Flags,_Index>::ReverseInnerIterator
+{
+ public:
+ ReverseInnerIterator(const MappedSparseMatrix& mat, Index outer)
+ : m_matrix(mat),
+ m_outer(outer),
+ m_id(mat.outerIndexPtr()[outer+1]),
+ m_start(mat.outerIndexPtr()[outer]),
+ m_end(m_id)
+ {}
+
+ inline ReverseInnerIterator& operator--() { m_id--; return *this; }
+
+ inline Scalar value() const { return m_matrix.valuePtr()[m_id-1]; }
+ inline Scalar& valueRef() { return const_cast<Scalar&>(m_matrix.valuePtr()[m_id-1]); }
+
+ inline Index index() const { return m_matrix.innerIndexPtr()[m_id-1]; }
+ inline Index row() const { return IsRowMajor ? m_outer : index(); }
+ inline Index col() const { return IsRowMajor ? index() : m_outer; }
+
+ inline operator bool() const { return (m_id <= m_end) && (m_id>m_start); }
+
+ protected:
+ const MappedSparseMatrix& m_matrix;
+ const Index m_outer;
+ Index m_id;
+ const Index m_start;
+ const Index m_end;
+};
+
+} // end namespace Eigen
+
#endif // EIGEN_MAPPED_SPARSEMATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseAssign.h b/extern/Eigen3/Eigen/src/SparseCore/SparseAssign.h
index e69de29bb2d..e69de29bb2d 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseAssign.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseAssign.h
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseBlock.h b/extern/Eigen3/Eigen/src/SparseCore/SparseBlock.h
index 8079c999994..eefd8070251 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseBlock.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseBlock.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSE_BLOCK_H
#define EIGEN_SPARSE_BLOCK_H
+namespace Eigen {
+
namespace internal {
template<typename MatrixType, int Size>
struct traits<SparseInnerVectorSet<MatrixType, Size> >
@@ -65,6 +52,17 @@ class SparseInnerVectorSet : internal::no_assignment_operator,
protected:
Index m_outer;
};
+ class ReverseInnerIterator: public MatrixType::ReverseInnerIterator
+ {
+ public:
+ inline ReverseInnerIterator(const SparseInnerVectorSet& xpr, Index outer)
+ : MatrixType::ReverseInnerIterator(xpr.m_matrix, xpr.m_outerStart + outer), m_outer(outer)
+ {}
+ inline Index row() const { return IsRowMajor ? m_outer : this->index(); }
+ inline Index col() const { return IsRowMajor ? this->index() : m_outer; }
+ protected:
+ Index m_outer;
+ };
inline SparseInnerVectorSet(const MatrixType& matrix, Index outerStart, Index outerSize)
: m_matrix(matrix), m_outerStart(outerStart), m_outerSize(outerSize)
@@ -101,15 +99,16 @@ class SparseInnerVectorSet : internal::no_assignment_operator,
const internal::variable_if_dynamic<Index, Size> m_outerSize;
};
+
/***************************************************************************
-* specialisation for DynamicSparseMatrix
+* specialisation for SparseMatrix
***************************************************************************/
-template<typename _Scalar, int _Options, int Size>
-class SparseInnerVectorSet<DynamicSparseMatrix<_Scalar, _Options>, Size>
- : public SparseMatrixBase<SparseInnerVectorSet<DynamicSparseMatrix<_Scalar, _Options>, Size> >
+template<typename _Scalar, int _Options, typename _Index, int Size>
+class SparseInnerVectorSet<SparseMatrix<_Scalar, _Options, _Index>, Size>
+ : public SparseMatrixBase<SparseInnerVectorSet<SparseMatrix<_Scalar, _Options, _Index>, Size> >
{
- typedef DynamicSparseMatrix<_Scalar, _Options> MatrixType;
+ typedef SparseMatrix<_Scalar, _Options, _Index> MatrixType;
public:
enum { IsRowMajor = internal::traits<SparseInnerVectorSet>::IsRowMajor };
@@ -126,98 +125,11 @@ class SparseInnerVectorSet<DynamicSparseMatrix<_Scalar, _Options>, Size>
protected:
Index m_outer;
};
-
- inline SparseInnerVectorSet(const MatrixType& matrix, Index outerStart, Index outerSize)
- : m_matrix(matrix), m_outerStart(outerStart), m_outerSize(outerSize)
- {
- eigen_assert( (outerStart>=0) && ((outerStart+outerSize)<=matrix.outerSize()) );
- }
-
- inline SparseInnerVectorSet(const MatrixType& matrix, Index outer)
- : m_matrix(matrix), m_outerStart(outer), m_outerSize(Size)
- {
- eigen_assert(Size!=Dynamic);
- eigen_assert( (outer>=0) && (outer<matrix.outerSize()) );
- }
-
- template<typename OtherDerived>
- inline SparseInnerVectorSet& operator=(const SparseMatrixBase<OtherDerived>& other)
- {
- if (IsRowMajor != ((OtherDerived::Flags&RowMajorBit)==RowMajorBit))
- {
- // need to transpose => perform a block evaluation followed by a big swap
- DynamicSparseMatrix<Scalar,IsRowMajor?RowMajorBit:0> aux(other);
- *this = aux.markAsRValue();
- }
- else
- {
- // evaluate/copy vector per vector
- for (Index j=0; j<m_outerSize.value(); ++j)
- {
- SparseVector<Scalar,IsRowMajor ? RowMajorBit : 0> aux(other.innerVector(j));
- m_matrix.const_cast_derived()._data()[m_outerStart+j].swap(aux._data());
- }
- }
- return *this;
- }
-
- inline SparseInnerVectorSet& operator=(const SparseInnerVectorSet& other)
- {
- return operator=<SparseInnerVectorSet>(other);
- }
-
- Index nonZeros() const
- {
- Index count = 0;
- for (Index j=0; j<m_outerSize.value(); ++j)
- count += m_matrix._data()[m_outerStart+j].size();
- return count;
- }
-
- const Scalar& lastCoeff() const
- {
- EIGEN_STATIC_ASSERT_VECTOR_ONLY(SparseInnerVectorSet);
- eigen_assert(m_matrix.data()[m_outerStart].size()>0);
- return m_matrix.data()[m_outerStart].vale(m_matrix.data()[m_outerStart].size()-1);
- }
-
-// template<typename Sparse>
-// inline SparseInnerVectorSet& operator=(const SparseMatrixBase<OtherDerived>& other)
-// {
-// return *this;
-// }
-
- EIGEN_STRONG_INLINE Index rows() const { return IsRowMajor ? m_outerSize.value() : m_matrix.rows(); }
- EIGEN_STRONG_INLINE Index cols() const { return IsRowMajor ? m_matrix.cols() : m_outerSize.value(); }
-
- protected:
-
- const typename MatrixType::Nested m_matrix;
- Index m_outerStart;
- const internal::variable_if_dynamic<Index, Size> m_outerSize;
-
-};
-
-
-/***************************************************************************
-* specialisation for SparseMatrix
-***************************************************************************/
-
-template<typename _Scalar, int _Options, typename _Index, int Size>
-class SparseInnerVectorSet<SparseMatrix<_Scalar, _Options, _Index>, Size>
- : public SparseMatrixBase<SparseInnerVectorSet<SparseMatrix<_Scalar, _Options>, Size> >
-{
- typedef SparseMatrix<_Scalar, _Options> MatrixType;
- public:
-
- enum { IsRowMajor = internal::traits<SparseInnerVectorSet>::IsRowMajor };
-
- EIGEN_SPARSE_PUBLIC_INTERFACE(SparseInnerVectorSet)
- class InnerIterator: public MatrixType::InnerIterator
+ class ReverseInnerIterator: public MatrixType::ReverseInnerIterator
{
public:
- inline InnerIterator(const SparseInnerVectorSet& xpr, Index outer)
- : MatrixType::InnerIterator(xpr.m_matrix, xpr.m_outerStart + outer), m_outer(outer)
+ inline ReverseInnerIterator(const SparseInnerVectorSet& xpr, Index outer)
+ : MatrixType::ReverseInnerIterator(xpr.m_matrix, xpr.m_outerStart + outer), m_outer(outer)
{}
inline Index row() const { return IsRowMajor ? m_outer : this->index(); }
inline Index col() const { return IsRowMajor ? this->index() : m_outer; }
@@ -243,19 +155,19 @@ class SparseInnerVectorSet<SparseMatrix<_Scalar, _Options, _Index>, Size>
{
typedef typename internal::remove_all<typename MatrixType::Nested>::type _NestedMatrixType;
_NestedMatrixType& matrix = const_cast<_NestedMatrixType&>(m_matrix);;
- // This assignement is slow if this vector set not empty
+ // This assignement is slow if this vector set is not empty
// and/or it is not at the end of the nonzeros of the underlying matrix.
// 1 - eval to a temporary to avoid transposition and/or aliasing issues
SparseMatrix<Scalar, IsRowMajor ? RowMajor : ColMajor, Index> tmp(other);
// 2 - let's check whether there is enough allocated memory
- Index nnz = tmp.nonZeros();
- Index nnz_previous = nonZeros();
- Index free_size = matrix.data().allocatedSize() - nnz_previous;
- std::size_t nnz_head = m_outerStart==0 ? 0 : matrix._outerIndexPtr()[m_outerStart];
- std::size_t tail = m_matrix._outerIndexPtr()[m_outerStart+m_outerSize.value()];
- std::size_t nnz_tail = matrix.nonZeros() - tail;
+ Index nnz = tmp.nonZeros();
+ Index nnz_previous = nonZeros();
+ Index free_size = Index(matrix.data().allocatedSize()) + nnz_previous;
+ Index nnz_head = m_outerStart==0 ? 0 : matrix.outerIndexPtr()[m_outerStart];
+ Index tail = m_matrix.outerIndexPtr()[m_outerStart+m_outerSize.value()];
+ Index nnz_tail = matrix.nonZeros() - tail;
if(nnz>free_size)
{
@@ -298,15 +210,15 @@ class SparseInnerVectorSet<SparseMatrix<_Scalar, _Options, _Index>, Size>
// update outer index pointers
Index p = nnz_head;
- for(Index k=1; k<m_outerSize.value(); ++k)
+ for(Index k=0; k<m_outerSize.value(); ++k)
{
- matrix._outerIndexPtr()[m_outerStart+k] = p;
+ matrix.outerIndexPtr()[m_outerStart+k] = p;
p += tmp.innerVector(k).nonZeros();
}
std::ptrdiff_t offset = nnz - nnz_previous;
for(Index k = m_outerStart + m_outerSize.value(); k<=matrix.outerSize(); ++k)
{
- matrix._outerIndexPtr()[k] += offset;
+ matrix.outerIndexPtr()[k] += offset;
}
return *this;
@@ -317,32 +229,40 @@ class SparseInnerVectorSet<SparseMatrix<_Scalar, _Options, _Index>, Size>
return operator=<SparseInnerVectorSet>(other);
}
- inline const Scalar* _valuePtr() const
- { return m_matrix._valuePtr() + m_matrix._outerIndexPtr()[m_outerStart]; }
- inline Scalar* _valuePtr()
- { return m_matrix.const_cast_derived()._valuePtr() + m_matrix._outerIndexPtr()[m_outerStart]; }
+ inline const Scalar* valuePtr() const
+ { return m_matrix.valuePtr() + m_matrix.outerIndexPtr()[m_outerStart]; }
+ inline Scalar* valuePtr()
+ { return m_matrix.const_cast_derived().valuePtr() + m_matrix.outerIndexPtr()[m_outerStart]; }
- inline const Index* _innerIndexPtr() const
- { return m_matrix._innerIndexPtr() + m_matrix._outerIndexPtr()[m_outerStart]; }
- inline Index* _innerIndexPtr()
- { return m_matrix.const_cast_derived()._innerIndexPtr() + m_matrix._outerIndexPtr()[m_outerStart]; }
+ inline const Index* innerIndexPtr() const
+ { return m_matrix.innerIndexPtr() + m_matrix.outerIndexPtr()[m_outerStart]; }
+ inline Index* innerIndexPtr()
+ { return m_matrix.const_cast_derived().innerIndexPtr() + m_matrix.outerIndexPtr()[m_outerStart]; }
- inline const Index* _outerIndexPtr() const
- { return m_matrix._outerIndexPtr() + m_outerStart; }
- inline Index* _outerIndexPtr()
- { return m_matrix.const_cast_derived()._outerIndexPtr() + m_outerStart; }
+ inline const Index* outerIndexPtr() const
+ { return m_matrix.outerIndexPtr() + m_outerStart; }
+ inline Index* outerIndexPtr()
+ { return m_matrix.const_cast_derived().outerIndexPtr() + m_outerStart; }
Index nonZeros() const
{
- return std::size_t(m_matrix._outerIndexPtr()[m_outerStart+m_outerSize.value()])
- - std::size_t(m_matrix._outerIndexPtr()[m_outerStart]);
+ if(m_matrix.isCompressed())
+ return std::size_t(m_matrix.outerIndexPtr()[m_outerStart+m_outerSize.value()])
+ - std::size_t(m_matrix.outerIndexPtr()[m_outerStart]);
+ else if(m_outerSize.value()==0)
+ return 0;
+ else
+ return Map<const Matrix<Index,Size,1> >(m_matrix.innerNonZeroPtr()+m_outerStart, m_outerSize.value()).sum();
}
const Scalar& lastCoeff() const
{
EIGEN_STATIC_ASSERT_VECTOR_ONLY(SparseInnerVectorSet);
eigen_assert(nonZeros()>0);
- return m_matrix._valuePtr()[m_matrix._outerIndexPtr()[m_outerStart+1]-1];
+ if(m_matrix.isCompressed())
+ return m_matrix.valuePtr()[m_matrix.outerIndexPtr()[m_outerStart+1]-1];
+ else
+ return m_matrix.valuePtr()[m_matrix.outerIndexPtr()[m_outerStart]+m_matrix.innerNonZeroPtr()[m_outerStart]-1];
}
// template<typename Sparse>
@@ -356,7 +276,7 @@ class SparseInnerVectorSet<SparseMatrix<_Scalar, _Options, _Index>, Size>
protected:
- const typename MatrixType::Nested m_matrix;
+ typename MatrixType::Nested m_matrix;
Index m_outerStart;
const internal::variable_if_dynamic<Index, Size> m_outerSize;
@@ -412,11 +332,9 @@ template<typename Derived>
const SparseInnerVectorSet<Derived,1> SparseMatrixBase<Derived>::innerVector(Index outer) const
{ return SparseInnerVectorSet<Derived,1>(derived(), outer); }
-//----------
-
/** \returns the i-th row of the matrix \c *this. For row-major matrix only. */
template<typename Derived>
-SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::subrows(Index start, Index size)
+SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::middleRows(Index start, Index size)
{
EIGEN_STATIC_ASSERT(IsRowMajor,THIS_METHOD_IS_ONLY_FOR_ROW_MAJOR_MATRICES);
return innerVectors(start, size);
@@ -425,7 +343,7 @@ SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::subrows(Index s
/** \returns the i-th row of the matrix \c *this. For row-major matrix only.
* (read-only version) */
template<typename Derived>
-const SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::subrows(Index start, Index size) const
+const SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::middleRows(Index start, Index size) const
{
EIGEN_STATIC_ASSERT(IsRowMajor,THIS_METHOD_IS_ONLY_FOR_ROW_MAJOR_MATRICES);
return innerVectors(start, size);
@@ -433,7 +351,7 @@ const SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::subrows(I
/** \returns the i-th column of the matrix \c *this. For column-major matrix only. */
template<typename Derived>
-SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::subcols(Index start, Index size)
+SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::middleCols(Index start, Index size)
{
EIGEN_STATIC_ASSERT(!IsRowMajor,THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES);
return innerVectors(start, size);
@@ -442,12 +360,14 @@ SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::subcols(Index s
/** \returns the i-th column of the matrix \c *this. For column-major matrix only.
* (read-only version) */
template<typename Derived>
-const SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::subcols(Index start, Index size) const
+const SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::middleCols(Index start, Index size) const
{
EIGEN_STATIC_ASSERT(!IsRowMajor,THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES);
return innerVectors(start, size);
}
+
+
/** \returns the \a outer -th column (resp. row) of the matrix \c *this if \c *this
* is col-major (resp. row-major).
*/
@@ -462,4 +382,6 @@ template<typename Derived>
const SparseInnerVectorSet<Derived,Dynamic> SparseMatrixBase<Derived>::innerVectors(Index outerStart, Index outerSize) const
{ return SparseInnerVectorSet<Derived,Dynamic>(derived(), outerStart, outerSize); }
+} // end namespace Eigen
+
#endif // EIGEN_SPARSE_BLOCK_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseCwiseBinaryOp.h b/extern/Eigen3/Eigen/src/SparseCore/SparseCwiseBinaryOp.h
index cde5bbc0300..d5f97f78fc9 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseCwiseBinaryOp.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseCwiseBinaryOp.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSE_CWISE_BINARY_OP_H
#define EIGEN_SPARSE_CWISE_BINARY_OP_H
+namespace Eigen {
+
// Here we have to handle 3 cases:
// 1 - sparse op dense
// 2 - dense op sparse
@@ -63,8 +50,18 @@ class CwiseBinaryOpImpl<BinaryOp, Lhs, Rhs, Sparse>
{
public:
class InnerIterator;
+ class ReverseInnerIterator;
typedef CwiseBinaryOp<BinaryOp, Lhs, Rhs> Derived;
EIGEN_SPARSE_PUBLIC_INTERFACE(Derived)
+ CwiseBinaryOpImpl()
+ {
+ typedef typename internal::traits<Lhs>::StorageKind LhsStorageKind;
+ typedef typename internal::traits<Rhs>::StorageKind RhsStorageKind;
+ EIGEN_STATIC_ASSERT((
+ (!internal::is_same<LhsStorageKind,RhsStorageKind>::value)
+ || ((Lhs::Flags&RowMajorBit) == (Rhs::Flags&RowMajorBit))),
+ THE_STORAGE_ORDER_OF_BOTH_SIDES_MUST_MATCH);
+ }
};
template<typename BinaryOp, typename Lhs, typename Rhs>
@@ -76,7 +73,7 @@ class CwiseBinaryOpImpl<BinaryOp,Lhs,Rhs,Sparse>::InnerIterator
typedef internal::sparse_cwise_binary_op_inner_iterator_selector<
BinaryOp,Lhs,Rhs, InnerIterator> Base;
- EIGEN_STRONG_INLINE InnerIterator(const CwiseBinaryOpImpl& binOp, Index outer)
+ EIGEN_STRONG_INLINE InnerIterator(const CwiseBinaryOpImpl& binOp, typename CwiseBinaryOpImpl::Index outer)
: Base(binOp.derived(),outer)
{}
};
@@ -246,7 +243,7 @@ class sparse_cwise_binary_op_inner_iterator_selector<scalar_product_op<T>, Lhs,
EIGEN_STRONG_INLINE operator bool() const { return m_lhsIter; }
protected:
- const RhsNested m_rhs;
+ RhsNested m_rhs;
LhsIterator m_lhsIter;
const BinaryFunc m_functor;
const Index m_outer;
@@ -298,16 +295,6 @@ class sparse_cwise_binary_op_inner_iterator_selector<scalar_product_op<T>, Lhs,
* Implementation of SparseMatrixBase and SparseCwise functions/operators
***************************************************************************/
-// template<typename Derived>
-// template<typename OtherDerived>
-// EIGEN_STRONG_INLINE const CwiseBinaryOp<internal::scalar_difference_op<typename internal::traits<Derived>::Scalar>,
-// Derived, OtherDerived>
-// SparseMatrixBase<Derived>::operator-(const SparseMatrixBase<OtherDerived> &other) const
-// {
-// return CwiseBinaryOp<internal::scalar_difference_op<Scalar>,
-// Derived, OtherDerived>(derived(), other.derived());
-// }
-
template<typename Derived>
template<typename OtherDerived>
EIGEN_STRONG_INLINE Derived &
@@ -316,14 +303,6 @@ SparseMatrixBase<Derived>::operator-=(const SparseMatrixBase<OtherDerived> &othe
return *this = derived() - other.derived();
}
-// template<typename Derived>
-// template<typename OtherDerived>
-// EIGEN_STRONG_INLINE const CwiseBinaryOp<internal::scalar_sum_op<typename internal::traits<Derived>::Scalar>, Derived, OtherDerived>
-// SparseMatrixBase<Derived>::operator+(const SparseMatrixBase<OtherDerived> &other) const
-// {
-// return CwiseBinaryOp<internal::scalar_sum_op<Scalar>, Derived, OtherDerived>(derived(), other.derived());
-// }
-
template<typename Derived>
template<typename OtherDerived>
EIGEN_STRONG_INLINE Derived &
@@ -332,14 +311,6 @@ SparseMatrixBase<Derived>::operator+=(const SparseMatrixBase<OtherDerived>& othe
return *this = derived() + other.derived();
}
-// template<typename ExpressionType>
-// template<typename OtherDerived>
-// EIGEN_STRONG_INLINE const EIGEN_SPARSE_CWISE_PRODUCT_RETURN_TYPE
-// SparseCwise<ExpressionType>::operator*(const SparseMatrixBase<OtherDerived> &other) const
-// {
-// return EIGEN_SPARSE_CWISE_PRODUCT_RETURN_TYPE(_expression(), other.derived());
-// }
-
template<typename Derived>
template<typename OtherDerived>
EIGEN_STRONG_INLINE const EIGEN_SPARSE_CWISE_PRODUCT_RETURN_TYPE
@@ -348,28 +319,6 @@ SparseMatrixBase<Derived>::cwiseProduct(const MatrixBase<OtherDerived> &other) c
return EIGEN_SPARSE_CWISE_PRODUCT_RETURN_TYPE(derived(), other.derived());
}
-// template<typename ExpressionType>
-// template<typename OtherDerived>
-// EIGEN_STRONG_INLINE const EIGEN_SPARSE_CWISE_BINOP_RETURN_TYPE(internal::scalar_quotient_op)
-// SparseCwise<ExpressionType>::operator/(const SparseMatrixBase<OtherDerived> &other) const
-// {
-// return EIGEN_SPARSE_CWISE_BINOP_RETURN_TYPE(internal::scalar_quotient_op)(_expression(), other.derived());
-// }
-//
-// template<typename ExpressionType>
-// template<typename OtherDerived>
-// EIGEN_STRONG_INLINE const EIGEN_SPARSE_CWISE_BINOP_RETURN_TYPE(internal::scalar_quotient_op)
-// SparseCwise<ExpressionType>::operator/(const MatrixBase<OtherDerived> &other) const
-// {
-// return EIGEN_SPARSE_CWISE_BINOP_RETURN_TYPE(internal::scalar_quotient_op)(_expression(), other.derived());
-// }
-
-// template<typename ExpressionType>
-// template<typename OtherDerived>
-// inline ExpressionType& SparseCwise<ExpressionType>::operator*=(const SparseMatrixBase<OtherDerived> &other)
-// {
-// return m_matrix.const_cast_derived() = _expression() * other.derived();
-// }
-
+} // end namespace Eigen
#endif // EIGEN_SPARSE_CWISE_BINARY_OP_H
diff --git a/extern/Eigen3/Eigen/src/SparseCore/SparseCwiseUnaryOp.h b/extern/Eigen3/Eigen/src/SparseCore/SparseCwiseUnaryOp.h
new file mode 100644
index 00000000000..5a50c780303
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseCwiseUnaryOp.h
@@ -0,0 +1,163 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_SPARSE_CWISE_UNARY_OP_H
+#define EIGEN_SPARSE_CWISE_UNARY_OP_H
+
+namespace Eigen {
+
+template<typename UnaryOp, typename MatrixType>
+class CwiseUnaryOpImpl<UnaryOp,MatrixType,Sparse>
+ : public SparseMatrixBase<CwiseUnaryOp<UnaryOp, MatrixType> >
+{
+ public:
+
+ class InnerIterator;
+ class ReverseInnerIterator;
+
+ typedef CwiseUnaryOp<UnaryOp, MatrixType> Derived;
+ EIGEN_SPARSE_PUBLIC_INTERFACE(Derived)
+
+ protected:
+ typedef typename internal::traits<Derived>::_XprTypeNested _MatrixTypeNested;
+ typedef typename _MatrixTypeNested::InnerIterator MatrixTypeIterator;
+ typedef typename _MatrixTypeNested::ReverseInnerIterator MatrixTypeReverseIterator;
+};
+
+template<typename UnaryOp, typename MatrixType>
+class CwiseUnaryOpImpl<UnaryOp,MatrixType,Sparse>::InnerIterator
+ : public CwiseUnaryOpImpl<UnaryOp,MatrixType,Sparse>::MatrixTypeIterator
+{
+ typedef typename CwiseUnaryOpImpl::Scalar Scalar;
+ typedef typename CwiseUnaryOpImpl<UnaryOp,MatrixType,Sparse>::MatrixTypeIterator Base;
+ public:
+
+ EIGEN_STRONG_INLINE InnerIterator(const CwiseUnaryOpImpl& unaryOp, typename CwiseUnaryOpImpl::Index outer)
+ : Base(unaryOp.derived().nestedExpression(),outer), m_functor(unaryOp.derived().functor())
+ {}
+
+ EIGEN_STRONG_INLINE InnerIterator& operator++()
+ { Base::operator++(); return *this; }
+
+ EIGEN_STRONG_INLINE typename CwiseUnaryOpImpl::Scalar value() const { return m_functor(Base::value()); }
+
+ protected:
+ const UnaryOp m_functor;
+ private:
+ typename CwiseUnaryOpImpl::Scalar& valueRef();
+};
+
+template<typename UnaryOp, typename MatrixType>
+class CwiseUnaryOpImpl<UnaryOp,MatrixType,Sparse>::ReverseInnerIterator
+ : public CwiseUnaryOpImpl<UnaryOp,MatrixType,Sparse>::MatrixTypeReverseIterator
+{
+ typedef typename CwiseUnaryOpImpl::Scalar Scalar;
+ typedef typename CwiseUnaryOpImpl<UnaryOp,MatrixType,Sparse>::MatrixTypeReverseIterator Base;
+ public:
+
+ EIGEN_STRONG_INLINE ReverseInnerIterator(const CwiseUnaryOpImpl& unaryOp, typename CwiseUnaryOpImpl::Index outer)
+ : Base(unaryOp.derived().nestedExpression(),outer), m_functor(unaryOp.derived().functor())
+ {}
+
+ EIGEN_STRONG_INLINE ReverseInnerIterator& operator--()
+ { Base::operator--(); return *this; }
+
+ EIGEN_STRONG_INLINE typename CwiseUnaryOpImpl::Scalar value() const { return m_functor(Base::value()); }
+
+ protected:
+ const UnaryOp m_functor;
+ private:
+ typename CwiseUnaryOpImpl::Scalar& valueRef();
+};
+
+template<typename ViewOp, typename MatrixType>
+class CwiseUnaryViewImpl<ViewOp,MatrixType,Sparse>
+ : public SparseMatrixBase<CwiseUnaryView<ViewOp, MatrixType> >
+{
+ public:
+
+ class InnerIterator;
+ class ReverseInnerIterator;
+
+ typedef CwiseUnaryView<ViewOp, MatrixType> Derived;
+ EIGEN_SPARSE_PUBLIC_INTERFACE(Derived)
+
+ protected:
+ typedef typename internal::traits<Derived>::_MatrixTypeNested _MatrixTypeNested;
+ typedef typename _MatrixTypeNested::InnerIterator MatrixTypeIterator;
+ typedef typename _MatrixTypeNested::ReverseInnerIterator MatrixTypeReverseIterator;
+};
+
+template<typename ViewOp, typename MatrixType>
+class CwiseUnaryViewImpl<ViewOp,MatrixType,Sparse>::InnerIterator
+ : public CwiseUnaryViewImpl<ViewOp,MatrixType,Sparse>::MatrixTypeIterator
+{
+ typedef typename CwiseUnaryViewImpl::Scalar Scalar;
+ typedef typename CwiseUnaryViewImpl<ViewOp,MatrixType,Sparse>::MatrixTypeIterator Base;
+ public:
+
+ EIGEN_STRONG_INLINE InnerIterator(const CwiseUnaryViewImpl& unaryOp, typename CwiseUnaryViewImpl::Index outer)
+ : Base(unaryOp.derived().nestedExpression(),outer), m_functor(unaryOp.derived().functor())
+ {}
+
+ EIGEN_STRONG_INLINE InnerIterator& operator++()
+ { Base::operator++(); return *this; }
+
+ EIGEN_STRONG_INLINE typename CwiseUnaryViewImpl::Scalar value() const { return m_functor(Base::value()); }
+ EIGEN_STRONG_INLINE typename CwiseUnaryViewImpl::Scalar& valueRef() { return m_functor(Base::valueRef()); }
+
+ protected:
+ const ViewOp m_functor;
+};
+
+template<typename ViewOp, typename MatrixType>
+class CwiseUnaryViewImpl<ViewOp,MatrixType,Sparse>::ReverseInnerIterator
+ : public CwiseUnaryViewImpl<ViewOp,MatrixType,Sparse>::MatrixTypeReverseIterator
+{
+ typedef typename CwiseUnaryViewImpl::Scalar Scalar;
+ typedef typename CwiseUnaryViewImpl<ViewOp,MatrixType,Sparse>::MatrixTypeReverseIterator Base;
+ public:
+
+ EIGEN_STRONG_INLINE ReverseInnerIterator(const CwiseUnaryViewImpl& unaryOp, typename CwiseUnaryViewImpl::Index outer)
+ : Base(unaryOp.derived().nestedExpression(),outer), m_functor(unaryOp.derived().functor())
+ {}
+
+ EIGEN_STRONG_INLINE ReverseInnerIterator& operator--()
+ { Base::operator--(); return *this; }
+
+ EIGEN_STRONG_INLINE typename CwiseUnaryViewImpl::Scalar value() const { return m_functor(Base::value()); }
+ EIGEN_STRONG_INLINE typename CwiseUnaryViewImpl::Scalar& valueRef() { return m_functor(Base::valueRef()); }
+
+ protected:
+ const ViewOp m_functor;
+};
+
+template<typename Derived>
+EIGEN_STRONG_INLINE Derived&
+SparseMatrixBase<Derived>::operator*=(const Scalar& other)
+{
+ for (Index j=0; j<outerSize(); ++j)
+ for (typename Derived::InnerIterator i(derived(),j); i; ++i)
+ i.valueRef() *= other;
+ return derived();
+}
+
+template<typename Derived>
+EIGEN_STRONG_INLINE Derived&
+SparseMatrixBase<Derived>::operator/=(const Scalar& other)
+{
+ for (Index j=0; j<outerSize(); ++j)
+ for (typename Derived::InnerIterator i(derived(),j); i; ++i)
+ i.valueRef() /= other;
+ return derived();
+}
+
+} // end namespace Eigen
+
+#endif // EIGEN_SPARSE_CWISE_UNARY_OP_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseDenseProduct.h b/extern/Eigen3/Eigen/src/SparseCore/SparseDenseProduct.h
index 0f77aa5be99..6f32940d6c1 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseDenseProduct.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseDenseProduct.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSEDENSEPRODUCT_H
#define EIGEN_SPARSEDENSEPRODUCT_H
+namespace Eigen {
+
template<typename Lhs, typename Rhs, int InnerSize> struct SparseDenseProductReturnType
{
typedef SparseTimeDenseProduct<Lhs,Rhs> Type;
@@ -149,6 +136,102 @@ struct traits<SparseTimeDenseProduct<Lhs,Rhs> >
typedef Dense StorageKind;
typedef MatrixXpr XprKind;
};
+
+template<typename SparseLhsType, typename DenseRhsType, typename DenseResType,
+ int LhsStorageOrder = ((SparseLhsType::Flags&RowMajorBit)==RowMajorBit) ? RowMajor : ColMajor,
+ bool ColPerCol = ((DenseRhsType::Flags&RowMajorBit)==0) || DenseRhsType::ColsAtCompileTime==1>
+struct sparse_time_dense_product_impl;
+
+template<typename SparseLhsType, typename DenseRhsType, typename DenseResType>
+struct sparse_time_dense_product_impl<SparseLhsType,DenseRhsType,DenseResType, RowMajor, true>
+{
+ typedef typename internal::remove_all<SparseLhsType>::type Lhs;
+ typedef typename internal::remove_all<DenseRhsType>::type Rhs;
+ typedef typename internal::remove_all<DenseResType>::type Res;
+ typedef typename Lhs::Index Index;
+ typedef typename Lhs::InnerIterator LhsInnerIterator;
+ static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, typename Res::Scalar alpha)
+ {
+ for(Index c=0; c<rhs.cols(); ++c)
+ {
+ int n = lhs.outerSize();
+ for(Index j=0; j<n; ++j)
+ {
+ typename Res::Scalar tmp(0);
+ for(LhsInnerIterator it(lhs,j); it ;++it)
+ tmp += it.value() * rhs.coeff(it.index(),c);
+ res.coeffRef(j,c) = alpha * tmp;
+ }
+ }
+ }
+};
+
+template<typename SparseLhsType, typename DenseRhsType, typename DenseResType>
+struct sparse_time_dense_product_impl<SparseLhsType,DenseRhsType,DenseResType, ColMajor, true>
+{
+ typedef typename internal::remove_all<SparseLhsType>::type Lhs;
+ typedef typename internal::remove_all<DenseRhsType>::type Rhs;
+ typedef typename internal::remove_all<DenseResType>::type Res;
+ typedef typename Lhs::InnerIterator LhsInnerIterator;
+ typedef typename Lhs::Index Index;
+ static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, typename Res::Scalar alpha)
+ {
+ for(Index c=0; c<rhs.cols(); ++c)
+ {
+ for(Index j=0; j<lhs.outerSize(); ++j)
+ {
+ typename Res::Scalar rhs_j = alpha * rhs.coeff(j,c);
+ for(LhsInnerIterator it(lhs,j); it ;++it)
+ res.coeffRef(it.index(),c) += it.value() * rhs_j;
+ }
+ }
+ }
+};
+
+template<typename SparseLhsType, typename DenseRhsType, typename DenseResType>
+struct sparse_time_dense_product_impl<SparseLhsType,DenseRhsType,DenseResType, RowMajor, false>
+{
+ typedef typename internal::remove_all<SparseLhsType>::type Lhs;
+ typedef typename internal::remove_all<DenseRhsType>::type Rhs;
+ typedef typename internal::remove_all<DenseResType>::type Res;
+ typedef typename Lhs::InnerIterator LhsInnerIterator;
+ typedef typename Lhs::Index Index;
+ static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, typename Res::Scalar alpha)
+ {
+ for(Index j=0; j<lhs.outerSize(); ++j)
+ {
+ typename Res::RowXpr res_j(res.row(j));
+ for(LhsInnerIterator it(lhs,j); it ;++it)
+ res_j += (alpha*it.value()) * rhs.row(it.index());
+ }
+ }
+};
+
+template<typename SparseLhsType, typename DenseRhsType, typename DenseResType>
+struct sparse_time_dense_product_impl<SparseLhsType,DenseRhsType,DenseResType, ColMajor, false>
+{
+ typedef typename internal::remove_all<SparseLhsType>::type Lhs;
+ typedef typename internal::remove_all<DenseRhsType>::type Rhs;
+ typedef typename internal::remove_all<DenseResType>::type Res;
+ typedef typename Lhs::InnerIterator LhsInnerIterator;
+ typedef typename Lhs::Index Index;
+ static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, typename Res::Scalar alpha)
+ {
+ for(Index j=0; j<lhs.outerSize(); ++j)
+ {
+ typename Rhs::ConstRowXpr rhs_j(rhs.row(j));
+ for(LhsInnerIterator it(lhs,j); it ;++it)
+ res.row(it.index()) += (alpha*it.value()) * rhs_j;
+ }
+ }
+};
+
+template<typename SparseLhsType, typename DenseRhsType, typename DenseResType,typename AlphaType>
+inline void sparse_time_dense_product(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, const AlphaType& alpha)
+{
+ sparse_time_dense_product_impl<SparseLhsType,DenseRhsType,DenseResType>::run(lhs, rhs, res, alpha);
+}
+
} // end namespace internal
template<typename Lhs, typename Rhs>
@@ -163,21 +246,7 @@ class SparseTimeDenseProduct
template<typename Dest> void scaleAndAddTo(Dest& dest, Scalar alpha) const
{
- typedef typename internal::remove_all<Lhs>::type _Lhs;
- typedef typename internal::remove_all<Rhs>::type _Rhs;
- typedef typename _Lhs::InnerIterator LhsInnerIterator;
- enum { LhsIsRowMajor = (_Lhs::Flags&RowMajorBit)==RowMajorBit };
- for(Index j=0; j<m_lhs.outerSize(); ++j)
- {
- typename Rhs::Scalar rhs_j = alpha * m_rhs.coeff(LhsIsRowMajor ? 0 : j,0);
- typename Dest::RowXpr dest_j(dest.row(LhsIsRowMajor ? j : 0));
- for(LhsInnerIterator it(m_lhs,j); it ;++it)
- {
- if(LhsIsRowMajor) dest_j += (alpha*it.value()) * m_rhs.row(it.index());
- else if(Rhs::ColsAtCompileTime==1) dest.coeffRef(it.index()) += it.value() * rhs_j;
- else dest.row(it.index()) += (alpha*it.value()) * m_rhs.row(j);
- }
- }
+ internal::sparse_time_dense_product(m_lhs, m_rhs, dest, alpha);
}
private:
@@ -207,12 +276,10 @@ class DenseTimeSparseProduct
template<typename Dest> void scaleAndAddTo(Dest& dest, Scalar alpha) const
{
- typedef typename internal::remove_all<Rhs>::type _Rhs;
- typedef typename _Rhs::InnerIterator RhsInnerIterator;
- enum { RhsIsRowMajor = (_Rhs::Flags&RowMajorBit)==RowMajorBit };
- for(Index j=0; j<m_rhs.outerSize(); ++j)
- for(RhsInnerIterator i(m_rhs,j); i; ++i)
- dest.col(RhsIsRowMajor ? i.index() : j) += (alpha*i.value()) * m_lhs.col(RhsIsRowMajor ? j : i.index());
+ Transpose<const _LhsNested> lhs_t(m_lhs);
+ Transpose<const _RhsNested> rhs_t(m_rhs);
+ Transpose<Dest> dest_t(dest);
+ internal::sparse_time_dense_product(rhs_t, lhs_t, dest_t, alpha);
}
private:
@@ -228,4 +295,6 @@ SparseMatrixBase<Derived>::operator*(const MatrixBase<OtherDerived> &other) cons
return typename SparseDenseProductReturnType<Derived,OtherDerived>::Type(derived(), other.derived());
}
+} // end namespace Eigen
+
#endif // EIGEN_SPARSEDENSEPRODUCT_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseDiagonalProduct.h b/extern/Eigen3/Eigen/src/SparseCore/SparseDiagonalProduct.h
index fb9a29c051b..095bf6863fc 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseDiagonalProduct.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseDiagonalProduct.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSE_DIAGONAL_PRODUCT_H
#define EIGEN_SPARSE_DIAGONAL_PRODUCT_H
+namespace Eigen {
+
// The product of a diagonal matrix with a sparse matrix can be easily
// implemented using expression template.
// We have two consider very different cases:
@@ -192,4 +179,6 @@ SparseMatrixBase<Derived>::operator*(const DiagonalBase<OtherDerived> &other) co
return SparseDiagonalProduct<Derived,OtherDerived>(this->derived(), other.derived());
}
+} // end namespace Eigen
+
#endif // EIGEN_SPARSE_DIAGONAL_PRODUCT_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseDot.h b/extern/Eigen3/Eigen/src/SparseCore/SparseDot.h
index 1f10f71a402..5c4a593dc01 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseDot.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseDot.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSE_DOT_H
#define EIGEN_SPARSE_DOT_H
+namespace Eigen {
+
template<typename Derived>
template<typename OtherDerived>
typename internal::traits<Derived>::Scalar
@@ -40,7 +27,7 @@ SparseMatrixBase<Derived>::dot(const MatrixBase<OtherDerived>& other) const
eigen_assert(other.size()>0 && "you are using a non initialized vector");
typename Derived::InnerIterator i(derived(),0);
- Scalar res = 0;
+ Scalar res(0);
while (i)
{
res += internal::conj(i.value()) * other.coeff(i.index());
@@ -62,9 +49,17 @@ SparseMatrixBase<Derived>::dot(const SparseMatrixBase<OtherDerived>& other) cons
eigen_assert(size() == other.size());
- typename Derived::InnerIterator i(derived(),0);
- typename OtherDerived::InnerIterator j(other.derived(),0);
- Scalar res = 0;
+ typedef typename Derived::Nested Nested;
+ typedef typename OtherDerived::Nested OtherNested;
+ typedef typename internal::remove_all<Nested>::type NestedCleaned;
+ typedef typename internal::remove_all<OtherNested>::type OtherNestedCleaned;
+
+ const Nested nthis(derived());
+ const OtherNested nother(other.derived());
+
+ typename NestedCleaned::InnerIterator i(nthis,0);
+ typename OtherNestedCleaned::InnerIterator j(nother,0);
+ Scalar res(0);
while (i && j)
{
if (i.index()==j.index())
@@ -94,4 +89,6 @@ SparseMatrixBase<Derived>::norm() const
return internal::sqrt(squaredNorm());
}
+} // end namespace Eigen
+
#endif // EIGEN_SPARSE_DOT_H
diff --git a/extern/Eigen3/Eigen/src/SparseCore/SparseFuzzy.h b/extern/Eigen3/Eigen/src/SparseCore/SparseFuzzy.h
new file mode 100644
index 00000000000..45f36e9eb90
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseFuzzy.h
@@ -0,0 +1,26 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_SPARSE_FUZZY_H
+#define EIGEN_SPARSE_FUZZY_H
+
+// template<typename Derived>
+// template<typename OtherDerived>
+// bool SparseMatrixBase<Derived>::isApprox(
+// const OtherDerived& other,
+// typename NumTraits<Scalar>::Real prec
+// ) const
+// {
+// const typename internal::nested<Derived,2>::type nested(derived());
+// const typename internal::nested<OtherDerived,2>::type otherNested(other.derived());
+// return (nested - otherNested).cwise().abs2().sum()
+// <= prec * prec * (std::min)(nested.cwise().abs2().sum(), otherNested.cwise().abs2().sum());
+// }
+
+#endif // EIGEN_SPARSE_FUZZY_H
diff --git a/extern/Eigen3/Eigen/src/SparseCore/SparseMatrix.h b/extern/Eigen3/Eigen/src/SparseCore/SparseMatrix.h
new file mode 100644
index 00000000000..efb774f031b
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseMatrix.h
@@ -0,0 +1,1116 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_SPARSEMATRIX_H
+#define EIGEN_SPARSEMATRIX_H
+
+namespace Eigen {
+
+/** \ingroup SparseCore_Module
+ *
+ * \class SparseMatrix
+ *
+ * \brief A versatible sparse matrix representation
+ *
+ * This class implements a more versatile variants of the common \em compressed row/column storage format.
+ * Each colmun's (resp. row) non zeros are stored as a pair of value with associated row (resp. colmiun) index.
+ * All the non zeros are stored in a single large buffer. Unlike the \em compressed format, there might be extra
+ * space inbetween the nonzeros of two successive colmuns (resp. rows) such that insertion of new non-zero
+ * can be done with limited memory reallocation and copies.
+ *
+ * A call to the function makeCompressed() turns the matrix into the standard \em compressed format
+ * compatible with many library.
+ *
+ * More details on this storage sceheme are given in the \ref TutorialSparse "manual pages".
+ *
+ * \tparam _Scalar the scalar type, i.e. the type of the coefficients
+ * \tparam _Options Union of bit flags controlling the storage scheme. Currently the only possibility
+ * is RowMajor. The default is 0 which means column-major.
+ * \tparam _Index the type of the indices. It has to be a \b signed type (e.g., short, int, std::ptrdiff_t). Default is \c int.
+ *
+ * This class can be extended with the help of the plugin mechanism described on the page
+ * \ref TopicCustomizingEigen by defining the preprocessor symbol \c EIGEN_SPARSEMATRIX_PLUGIN.
+ */
+
+namespace internal {
+template<typename _Scalar, int _Options, typename _Index>
+struct traits<SparseMatrix<_Scalar, _Options, _Index> >
+{
+ typedef _Scalar Scalar;
+ typedef _Index Index;
+ typedef Sparse StorageKind;
+ typedef MatrixXpr XprKind;
+ enum {
+ RowsAtCompileTime = Dynamic,
+ ColsAtCompileTime = Dynamic,
+ MaxRowsAtCompileTime = Dynamic,
+ MaxColsAtCompileTime = Dynamic,
+ Flags = _Options | NestByRefBit | LvalueBit,
+ CoeffReadCost = NumTraits<Scalar>::ReadCost,
+ SupportedAccessPatterns = InnerRandomAccessPattern
+ };
+};
+
+template<typename _Scalar, int _Options, typename _Index, int DiagIndex>
+struct traits<Diagonal<const SparseMatrix<_Scalar, _Options, _Index>, DiagIndex> >
+{
+ typedef SparseMatrix<_Scalar, _Options, _Index> MatrixType;
+ typedef typename nested<MatrixType>::type MatrixTypeNested;
+ typedef typename remove_reference<MatrixTypeNested>::type _MatrixTypeNested;
+
+ typedef _Scalar Scalar;
+ typedef Dense StorageKind;
+ typedef _Index Index;
+ typedef MatrixXpr XprKind;
+
+ enum {
+ RowsAtCompileTime = Dynamic,
+ ColsAtCompileTime = 1,
+ MaxRowsAtCompileTime = Dynamic,
+ MaxColsAtCompileTime = 1,
+ Flags = 0,
+ CoeffReadCost = _MatrixTypeNested::CoeffReadCost*10
+ };
+};
+
+} // end namespace internal
+
+template<typename _Scalar, int _Options, typename _Index>
+class SparseMatrix
+ : public SparseMatrixBase<SparseMatrix<_Scalar, _Options, _Index> >
+{
+ public:
+ EIGEN_SPARSE_PUBLIC_INTERFACE(SparseMatrix)
+ EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(SparseMatrix, +=)
+ EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(SparseMatrix, -=)
+
+ typedef MappedSparseMatrix<Scalar,Flags> Map;
+ using Base::IsRowMajor;
+ typedef internal::CompressedStorage<Scalar,Index> Storage;
+ enum {
+ Options = _Options
+ };
+
+ protected:
+
+ typedef SparseMatrix<Scalar,(Flags&~RowMajorBit)|(IsRowMajor?RowMajorBit:0)> TransposedSparseMatrix;
+
+ Index m_outerSize;
+ Index m_innerSize;
+ Index* m_outerIndex;
+ Index* m_innerNonZeros; // optional, if null then the data is compressed
+ Storage m_data;
+
+ Eigen::Map<Matrix<Index,Dynamic,1> > innerNonZeros() { return Eigen::Map<Matrix<Index,Dynamic,1> >(m_innerNonZeros, m_innerNonZeros?m_outerSize:0); }
+ const Eigen::Map<const Matrix<Index,Dynamic,1> > innerNonZeros() const { return Eigen::Map<const Matrix<Index,Dynamic,1> >(m_innerNonZeros, m_innerNonZeros?m_outerSize:0); }
+
+ public:
+
+ /** \returns whether \c *this is in compressed form. */
+ inline bool isCompressed() const { return m_innerNonZeros==0; }
+
+ /** \returns the number of rows of the matrix */
+ inline Index rows() const { return IsRowMajor ? m_outerSize : m_innerSize; }
+ /** \returns the number of columns of the matrix */
+ inline Index cols() const { return IsRowMajor ? m_innerSize : m_outerSize; }
+
+ /** \returns the number of rows (resp. columns) of the matrix if the storage order column major (resp. row major) */
+ inline Index innerSize() const { return m_innerSize; }
+ /** \returns the number of columns (resp. rows) of the matrix if the storage order column major (resp. row major) */
+ inline Index outerSize() const { return m_outerSize; }
+
+ /** \returns a const pointer to the array of values.
+ * This function is aimed at interoperability with other libraries.
+ * \sa innerIndexPtr(), outerIndexPtr() */
+ inline const Scalar* valuePtr() const { return &m_data.value(0); }
+ /** \returns a non-const pointer to the array of values.
+ * This function is aimed at interoperability with other libraries.
+ * \sa innerIndexPtr(), outerIndexPtr() */
+ inline Scalar* valuePtr() { return &m_data.value(0); }
+
+ /** \returns a const pointer to the array of inner indices.
+ * This function is aimed at interoperability with other libraries.
+ * \sa valuePtr(), outerIndexPtr() */
+ inline const Index* innerIndexPtr() const { return &m_data.index(0); }
+ /** \returns a non-const pointer to the array of inner indices.
+ * This function is aimed at interoperability with other libraries.
+ * \sa valuePtr(), outerIndexPtr() */
+ inline Index* innerIndexPtr() { return &m_data.index(0); }
+
+ /** \returns a const pointer to the array of the starting positions of the inner vectors.
+ * This function is aimed at interoperability with other libraries.
+ * \sa valuePtr(), innerIndexPtr() */
+ inline const Index* outerIndexPtr() const { return m_outerIndex; }
+ /** \returns a non-const pointer to the array of the starting positions of the inner vectors.
+ * This function is aimed at interoperability with other libraries.
+ * \sa valuePtr(), innerIndexPtr() */
+ inline Index* outerIndexPtr() { return m_outerIndex; }
+
+ /** \returns a const pointer to the array of the number of non zeros of the inner vectors.
+ * This function is aimed at interoperability with other libraries.
+ * \warning it returns the null pointer 0 in compressed mode */
+ inline const Index* innerNonZeroPtr() const { return m_innerNonZeros; }
+ /** \returns a non-const pointer to the array of the number of non zeros of the inner vectors.
+ * This function is aimed at interoperability with other libraries.
+ * \warning it returns the null pointer 0 in compressed mode */
+ inline Index* innerNonZeroPtr() { return m_innerNonZeros; }
+
+ /** \internal */
+ inline Storage& data() { return m_data; }
+ /** \internal */
+ inline const Storage& data() const { return m_data; }
+
+ /** \returns the value of the matrix at position \a i, \a j
+ * This function returns Scalar(0) if the element is an explicit \em zero */
+ inline Scalar coeff(Index row, Index col) const
+ {
+ const Index outer = IsRowMajor ? row : col;
+ const Index inner = IsRowMajor ? col : row;
+ Index end = m_innerNonZeros ? m_outerIndex[outer] + m_innerNonZeros[outer] : m_outerIndex[outer+1];
+ return m_data.atInRange(m_outerIndex[outer], end, inner);
+ }
+
+ /** \returns a non-const reference to the value of the matrix at position \a i, \a j
+ *
+ * If the element does not exist then it is inserted via the insert(Index,Index) function
+ * which itself turns the matrix into a non compressed form if that was not the case.
+ *
+ * This is a O(log(nnz_j)) operation (binary search) plus the cost of insert(Index,Index)
+ * function if the element does not already exist.
+ */
+ inline Scalar& coeffRef(Index row, Index col)
+ {
+ const Index outer = IsRowMajor ? row : col;
+ const Index inner = IsRowMajor ? col : row;
+
+ Index start = m_outerIndex[outer];
+ Index end = m_innerNonZeros ? m_outerIndex[outer] + m_innerNonZeros[outer] : m_outerIndex[outer+1];
+ eigen_assert(end>=start && "you probably called coeffRef on a non finalized matrix");
+ if(end<=start)
+ return insert(row,col);
+ const Index p = m_data.searchLowerIndex(start,end-1,inner);
+ if((p<end) && (m_data.index(p)==inner))
+ return m_data.value(p);
+ else
+ return insert(row,col);
+ }
+
+ /** \returns a reference to a novel non zero coefficient with coordinates \a row x \a col.
+ * The non zero coefficient must \b not already exist.
+ *
+ * If the matrix \c *this is in compressed mode, then \c *this is turned into uncompressed
+ * mode while reserving room for 2 non zeros per inner vector. It is strongly recommended to first
+ * call reserve(const SizesType &) to reserve a more appropriate number of elements per
+ * inner vector that better match your scenario.
+ *
+ * This function performs a sorted insertion in O(1) if the elements of each inner vector are
+ * inserted in increasing inner index order, and in O(nnz_j) for a random insertion.
+ *
+ */
+ EIGEN_DONT_INLINE Scalar& insert(Index row, Index col)
+ {
+ if(isCompressed())
+ {
+ reserve(VectorXi::Constant(outerSize(), 2));
+ }
+ return insertUncompressed(row,col);
+ }
+
+ public:
+
+ class InnerIterator;
+ class ReverseInnerIterator;
+
+ /** Removes all non zeros but keep allocated memory */
+ inline void setZero()
+ {
+ m_data.clear();
+ memset(m_outerIndex, 0, (m_outerSize+1)*sizeof(Index));
+ if(m_innerNonZeros)
+ memset(m_innerNonZeros, 0, (m_outerSize)*sizeof(Index));
+ }
+
+ /** \returns the number of non zero coefficients */
+ inline Index nonZeros() const
+ {
+ if(m_innerNonZeros)
+ return innerNonZeros().sum();
+ return static_cast<Index>(m_data.size());
+ }
+
+ /** Preallocates \a reserveSize non zeros.
+ *
+ * Precondition: the matrix must be in compressed mode. */
+ inline void reserve(Index reserveSize)
+ {
+ eigen_assert(isCompressed() && "This function does not make sense in non compressed mode.");
+ m_data.reserve(reserveSize);
+ }
+
+ #ifdef EIGEN_PARSED_BY_DOXYGEN
+ /** Preallocates \a reserveSize[\c j] non zeros for each column (resp. row) \c j.
+ *
+ * This function turns the matrix in non-compressed mode */
+ template<class SizesType>
+ inline void reserve(const SizesType& reserveSizes);
+ #else
+ template<class SizesType>
+ inline void reserve(const SizesType& reserveSizes, const typename SizesType::value_type& enableif = typename SizesType::value_type())
+ {
+ EIGEN_UNUSED_VARIABLE(enableif);
+ reserveInnerVectors(reserveSizes);
+ }
+ template<class SizesType>
+ inline void reserve(const SizesType& reserveSizes, const typename SizesType::Scalar& enableif =
+ #if (!defined(_MSC_VER)) || (_MSC_VER>=1500) // MSVC 2005 fails to compile with this typename
+ typename
+ #endif
+ SizesType::Scalar())
+ {
+ EIGEN_UNUSED_VARIABLE(enableif);
+ reserveInnerVectors(reserveSizes);
+ }
+ #endif // EIGEN_PARSED_BY_DOXYGEN
+ protected:
+ template<class SizesType>
+ inline void reserveInnerVectors(const SizesType& reserveSizes)
+ {
+
+ if(isCompressed())
+ {
+ std::size_t totalReserveSize = 0;
+ // turn the matrix into non-compressed mode
+ m_innerNonZeros = new Index[m_outerSize];
+
+ // temporarily use m_innerSizes to hold the new starting points.
+ Index* newOuterIndex = m_innerNonZeros;
+
+ Index count = 0;
+ for(Index j=0; j<m_outerSize; ++j)
+ {
+ newOuterIndex[j] = count;
+ count += reserveSizes[j] + (m_outerIndex[j+1]-m_outerIndex[j]);
+ totalReserveSize += reserveSizes[j];
+ }
+ m_data.reserve(totalReserveSize);
+ std::ptrdiff_t previousOuterIndex = m_outerIndex[m_outerSize];
+ for(std::ptrdiff_t j=m_outerSize-1; j>=0; --j)
+ {
+ ptrdiff_t innerNNZ = previousOuterIndex - m_outerIndex[j];
+ for(std::ptrdiff_t i=innerNNZ-1; i>=0; --i)
+ {
+ m_data.index(newOuterIndex[j]+i) = m_data.index(m_outerIndex[j]+i);
+ m_data.value(newOuterIndex[j]+i) = m_data.value(m_outerIndex[j]+i);
+ }
+ previousOuterIndex = m_outerIndex[j];
+ m_outerIndex[j] = newOuterIndex[j];
+ m_innerNonZeros[j] = innerNNZ;
+ }
+ m_outerIndex[m_outerSize] = m_outerIndex[m_outerSize-1] + m_innerNonZeros[m_outerSize-1] + reserveSizes[m_outerSize-1];
+
+ m_data.resize(m_outerIndex[m_outerSize]);
+ }
+ else
+ {
+ Index* newOuterIndex = new Index[m_outerSize+1];
+ Index count = 0;
+ for(Index j=0; j<m_outerSize; ++j)
+ {
+ newOuterIndex[j] = count;
+ Index alreadyReserved = (m_outerIndex[j+1]-m_outerIndex[j]) - m_innerNonZeros[j];
+ Index toReserve = std::max<std::ptrdiff_t>(reserveSizes[j], alreadyReserved);
+ count += toReserve + m_innerNonZeros[j];
+ }
+ newOuterIndex[m_outerSize] = count;
+
+ m_data.resize(count);
+ for(ptrdiff_t j=m_outerSize-1; j>=0; --j)
+ {
+ std::ptrdiff_t offset = newOuterIndex[j] - m_outerIndex[j];
+ if(offset>0)
+ {
+ std::ptrdiff_t innerNNZ = m_innerNonZeros[j];
+ for(std::ptrdiff_t i=innerNNZ-1; i>=0; --i)
+ {
+ m_data.index(newOuterIndex[j]+i) = m_data.index(m_outerIndex[j]+i);
+ m_data.value(newOuterIndex[j]+i) = m_data.value(m_outerIndex[j]+i);
+ }
+ }
+ }
+
+ std::swap(m_outerIndex, newOuterIndex);
+ delete[] newOuterIndex;
+ }
+
+ }
+ public:
+
+ //--- low level purely coherent filling ---
+
+ /** \internal
+ * \returns a reference to the non zero coefficient at position \a row, \a col assuming that:
+ * - the nonzero does not already exist
+ * - the new coefficient is the last one according to the storage order
+ *
+ * Before filling a given inner vector you must call the statVec(Index) function.
+ *
+ * After an insertion session, you should call the finalize() function.
+ *
+ * \sa insert, insertBackByOuterInner, startVec */
+ inline Scalar& insertBack(Index row, Index col)
+ {
+ return insertBackByOuterInner(IsRowMajor?row:col, IsRowMajor?col:row);
+ }
+
+ /** \internal
+ * \sa insertBack, startVec */
+ inline Scalar& insertBackByOuterInner(Index outer, Index inner)
+ {
+ eigen_assert(size_t(m_outerIndex[outer+1]) == m_data.size() && "Invalid ordered insertion (invalid outer index)");
+ eigen_assert( (m_outerIndex[outer+1]-m_outerIndex[outer]==0 || m_data.index(m_data.size()-1)<inner) && "Invalid ordered insertion (invalid inner index)");
+ Index p = m_outerIndex[outer+1];
+ ++m_outerIndex[outer+1];
+ m_data.append(0, inner);
+ return m_data.value(p);
+ }
+
+ /** \internal
+ * \warning use it only if you know what you are doing */
+ inline Scalar& insertBackByOuterInnerUnordered(Index outer, Index inner)
+ {
+ Index p = m_outerIndex[outer+1];
+ ++m_outerIndex[outer+1];
+ m_data.append(0, inner);
+ return m_data.value(p);
+ }
+
+ /** \internal
+ * \sa insertBack, insertBackByOuterInner */
+ inline void startVec(Index outer)
+ {
+ eigen_assert(m_outerIndex[outer]==int(m_data.size()) && "You must call startVec for each inner vector sequentially");
+ eigen_assert(m_outerIndex[outer+1]==0 && "You must call startVec for each inner vector sequentially");
+ m_outerIndex[outer+1] = m_outerIndex[outer];
+ }
+
+ /** \internal
+ * Must be called after inserting a set of non zero entries using the low level compressed API.
+ */
+ inline void finalize()
+ {
+ if(isCompressed())
+ {
+ Index size = static_cast<Index>(m_data.size());
+ Index i = m_outerSize;
+ // find the last filled column
+ while (i>=0 && m_outerIndex[i]==0)
+ --i;
+ ++i;
+ while (i<=m_outerSize)
+ {
+ m_outerIndex[i] = size;
+ ++i;
+ }
+ }
+ }
+
+ //---
+
+ template<typename InputIterators>
+ void setFromTriplets(const InputIterators& begin, const InputIterators& end);
+
+ void sumupDuplicates();
+
+ //---
+
+ /** \internal
+ * same as insert(Index,Index) except that the indices are given relative to the storage order */
+ EIGEN_DONT_INLINE Scalar& insertByOuterInner(Index j, Index i)
+ {
+ return insert(IsRowMajor ? j : i, IsRowMajor ? i : j);
+ }
+
+ /** Turns the matrix into the \em compressed format.
+ */
+ void makeCompressed()
+ {
+ if(isCompressed())
+ return;
+
+ Index oldStart = m_outerIndex[1];
+ m_outerIndex[1] = m_innerNonZeros[0];
+ for(Index j=1; j<m_outerSize; ++j)
+ {
+ Index nextOldStart = m_outerIndex[j+1];
+ std::ptrdiff_t offset = oldStart - m_outerIndex[j];
+ if(offset>0)
+ {
+ for(Index k=0; k<m_innerNonZeros[j]; ++k)
+ {
+ m_data.index(m_outerIndex[j]+k) = m_data.index(oldStart+k);
+ m_data.value(m_outerIndex[j]+k) = m_data.value(oldStart+k);
+ }
+ }
+ m_outerIndex[j+1] = m_outerIndex[j] + m_innerNonZeros[j];
+ oldStart = nextOldStart;
+ }
+ delete[] m_innerNonZeros;
+ m_innerNonZeros = 0;
+ m_data.resize(m_outerIndex[m_outerSize]);
+ m_data.squeeze();
+ }
+
+ /** Suppresses all nonzeros which are \b much \b smaller \b than \a reference under the tolerence \a epsilon */
+ void prune(Scalar reference, RealScalar epsilon = NumTraits<RealScalar>::dummy_precision())
+ {
+ prune(default_prunning_func(reference,epsilon));
+ }
+
+ /** Turns the matrix into compressed format, and suppresses all nonzeros which do not satisfy the predicate \a keep.
+ * The functor type \a KeepFunc must implement the following function:
+ * \code
+ * bool operator() (const Index& row, const Index& col, const Scalar& value) const;
+ * \endcode
+ * \sa prune(Scalar,RealScalar)
+ */
+ template<typename KeepFunc>
+ void prune(const KeepFunc& keep = KeepFunc())
+ {
+ // TODO optimize the uncompressed mode to avoid moving and allocating the data twice
+ // TODO also implement a unit test
+ makeCompressed();
+
+ Index k = 0;
+ for(Index j=0; j<m_outerSize; ++j)
+ {
+ Index previousStart = m_outerIndex[j];
+ m_outerIndex[j] = k;
+ Index end = m_outerIndex[j+1];
+ for(Index i=previousStart; i<end; ++i)
+ {
+ if(keep(IsRowMajor?j:m_data.index(i), IsRowMajor?m_data.index(i):j, m_data.value(i)))
+ {
+ m_data.value(k) = m_data.value(i);
+ m_data.index(k) = m_data.index(i);
+ ++k;
+ }
+ }
+ }
+ m_outerIndex[m_outerSize] = k;
+ m_data.resize(k,0);
+ }
+
+ /** Resizes the matrix to a \a rows x \a cols matrix and initializes it to zero.
+ * \sa resizeNonZeros(Index), reserve(), setZero()
+ */
+ void resize(Index rows, Index cols)
+ {
+ const Index outerSize = IsRowMajor ? rows : cols;
+ m_innerSize = IsRowMajor ? cols : rows;
+ m_data.clear();
+ if (m_outerSize != outerSize || m_outerSize==0)
+ {
+ delete[] m_outerIndex;
+ m_outerIndex = new Index [outerSize+1];
+ m_outerSize = outerSize;
+ }
+ if(m_innerNonZeros)
+ {
+ delete[] m_innerNonZeros;
+ m_innerNonZeros = 0;
+ }
+ memset(m_outerIndex, 0, (m_outerSize+1)*sizeof(Index));
+ }
+
+ /** \internal
+ * Resize the nonzero vector to \a size */
+ void resizeNonZeros(Index size)
+ {
+ // TODO remove this function
+ m_data.resize(size);
+ }
+
+ /** \returns a const expression of the diagonal coefficients */
+ const Diagonal<const SparseMatrix> diagonal() const { return *this; }
+
+ /** Default constructor yielding an empty \c 0 \c x \c 0 matrix */
+ inline SparseMatrix()
+ : m_outerSize(-1), m_innerSize(0), m_outerIndex(0), m_innerNonZeros(0)
+ {
+ check_template_parameters();
+ resize(0, 0);
+ }
+
+ /** Constructs a \a rows \c x \a cols empty matrix */
+ inline SparseMatrix(Index rows, Index cols)
+ : m_outerSize(0), m_innerSize(0), m_outerIndex(0), m_innerNonZeros(0)
+ {
+ check_template_parameters();
+ resize(rows, cols);
+ }
+
+ /** Constructs a sparse matrix from the sparse expression \a other */
+ template<typename OtherDerived>
+ inline SparseMatrix(const SparseMatrixBase<OtherDerived>& other)
+ : m_outerSize(0), m_innerSize(0), m_outerIndex(0), m_innerNonZeros(0)
+ {
+ check_template_parameters();
+ *this = other.derived();
+ }
+
+ /** Copy constructor (it performs a deep copy) */
+ inline SparseMatrix(const SparseMatrix& other)
+ : Base(), m_outerSize(0), m_innerSize(0), m_outerIndex(0), m_innerNonZeros(0)
+ {
+ check_template_parameters();
+ *this = other.derived();
+ }
+
+ /** Swaps the content of two sparse matrices of the same type.
+ * This is a fast operation that simply swaps the underlying pointers and parameters. */
+ inline void swap(SparseMatrix& other)
+ {
+ //EIGEN_DBG_SPARSE(std::cout << "SparseMatrix:: swap\n");
+ std::swap(m_outerIndex, other.m_outerIndex);
+ std::swap(m_innerSize, other.m_innerSize);
+ std::swap(m_outerSize, other.m_outerSize);
+ std::swap(m_innerNonZeros, other.m_innerNonZeros);
+ m_data.swap(other.m_data);
+ }
+
+ inline SparseMatrix& operator=(const SparseMatrix& other)
+ {
+ if (other.isRValue())
+ {
+ swap(other.const_cast_derived());
+ }
+ else
+ {
+ initAssignment(other);
+ if(other.isCompressed())
+ {
+ memcpy(m_outerIndex, other.m_outerIndex, (m_outerSize+1)*sizeof(Index));
+ m_data = other.m_data;
+ }
+ else
+ {
+ Base::operator=(other);
+ }
+ }
+ return *this;
+ }
+
+ #ifndef EIGEN_PARSED_BY_DOXYGEN
+ template<typename Lhs, typename Rhs>
+ inline SparseMatrix& operator=(const SparseSparseProduct<Lhs,Rhs>& product)
+ { return Base::operator=(product); }
+
+ template<typename OtherDerived>
+ inline SparseMatrix& operator=(const ReturnByValue<OtherDerived>& other)
+ { return Base::operator=(other.derived()); }
+
+ template<typename OtherDerived>
+ inline SparseMatrix& operator=(const EigenBase<OtherDerived>& other)
+ { return Base::operator=(other.derived()); }
+ #endif
+
+ template<typename OtherDerived>
+ EIGEN_DONT_INLINE SparseMatrix& operator=(const SparseMatrixBase<OtherDerived>& other)
+ {
+ initAssignment(other.derived());
+ const bool needToTranspose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit);
+ if (needToTranspose)
+ {
+ // two passes algorithm:
+ // 1 - compute the number of coeffs per dest inner vector
+ // 2 - do the actual copy/eval
+ // Since each coeff of the rhs has to be evaluated twice, let's evaluate it if needed
+ typedef typename internal::nested<OtherDerived,2>::type OtherCopy;
+ typedef typename internal::remove_all<OtherCopy>::type _OtherCopy;
+ OtherCopy otherCopy(other.derived());
+
+ Eigen::Map<Matrix<Index, Dynamic, 1> > (m_outerIndex,outerSize()).setZero();
+ // pass 1
+ // FIXME the above copy could be merged with that pass
+ for (Index j=0; j<otherCopy.outerSize(); ++j)
+ for (typename _OtherCopy::InnerIterator it(otherCopy, j); it; ++it)
+ ++m_outerIndex[it.index()];
+
+ // prefix sum
+ Index count = 0;
+ VectorXi positions(outerSize());
+ for (Index j=0; j<outerSize(); ++j)
+ {
+ Index tmp = m_outerIndex[j];
+ m_outerIndex[j] = count;
+ positions[j] = count;
+ count += tmp;
+ }
+ m_outerIndex[outerSize()] = count;
+ // alloc
+ m_data.resize(count);
+ // pass 2
+ for (Index j=0; j<otherCopy.outerSize(); ++j)
+ {
+ for (typename _OtherCopy::InnerIterator it(otherCopy, j); it; ++it)
+ {
+ Index pos = positions[it.index()]++;
+ m_data.index(pos) = j;
+ m_data.value(pos) = it.value();
+ }
+ }
+ return *this;
+ }
+ else
+ {
+ // there is no special optimization
+ return Base::operator=(other.derived());
+ }
+ }
+
+ friend std::ostream & operator << (std::ostream & s, const SparseMatrix& m)
+ {
+ EIGEN_DBG_SPARSE(
+ s << "Nonzero entries:\n";
+ if(m.isCompressed())
+ for (Index i=0; i<m.nonZeros(); ++i)
+ s << "(" << m.m_data.value(i) << "," << m.m_data.index(i) << ") ";
+ else
+ for (Index i=0; i<m.outerSize(); ++i)
+ {
+ int p = m.m_outerIndex[i];
+ int pe = m.m_outerIndex[i]+m.m_innerNonZeros[i];
+ Index k=p;
+ for (; k<pe; ++k)
+ s << "(" << m.m_data.value(k) << "," << m.m_data.index(k) << ") ";
+ for (; k<m.m_outerIndex[i+1]; ++k)
+ s << "(_,_) ";
+ }
+ s << std::endl;
+ s << std::endl;
+ s << "Outer pointers:\n";
+ for (Index i=0; i<m.outerSize(); ++i)
+ s << m.m_outerIndex[i] << " ";
+ s << " $" << std::endl;
+ if(!m.isCompressed())
+ {
+ s << "Inner non zeros:\n";
+ for (Index i=0; i<m.outerSize(); ++i)
+ s << m.m_innerNonZeros[i] << " ";
+ s << " $" << std::endl;
+ }
+ s << std::endl;
+ );
+ s << static_cast<const SparseMatrixBase<SparseMatrix>&>(m);
+ return s;
+ }
+
+ /** Destructor */
+ inline ~SparseMatrix()
+ {
+ delete[] m_outerIndex;
+ delete[] m_innerNonZeros;
+ }
+
+#ifndef EIGEN_PARSED_BY_DOXYGEN
+ /** Overloaded for performance */
+ Scalar sum() const;
+#endif
+
+# ifdef EIGEN_SPARSEMATRIX_PLUGIN
+# include EIGEN_SPARSEMATRIX_PLUGIN
+# endif
+
+protected:
+
+ template<typename Other>
+ void initAssignment(const Other& other)
+ {
+ resize(other.rows(), other.cols());
+ if(m_innerNonZeros)
+ {
+ delete[] m_innerNonZeros;
+ m_innerNonZeros = 0;
+ }
+ }
+
+ /** \internal
+ * \sa insert(Index,Index) */
+ EIGEN_DONT_INLINE Scalar& insertCompressed(Index row, Index col)
+ {
+ eigen_assert(isCompressed());
+
+ const Index outer = IsRowMajor ? row : col;
+ const Index inner = IsRowMajor ? col : row;
+
+ Index previousOuter = outer;
+ if (m_outerIndex[outer+1]==0)
+ {
+ // we start a new inner vector
+ while (previousOuter>=0 && m_outerIndex[previousOuter]==0)
+ {
+ m_outerIndex[previousOuter] = static_cast<Index>(m_data.size());
+ --previousOuter;
+ }
+ m_outerIndex[outer+1] = m_outerIndex[outer];
+ }
+
+ // here we have to handle the tricky case where the outerIndex array
+ // starts with: [ 0 0 0 0 0 1 ...] and we are inserted in, e.g.,
+ // the 2nd inner vector...
+ bool isLastVec = (!(previousOuter==-1 && m_data.size()!=0))
+ && (size_t(m_outerIndex[outer+1]) == m_data.size());
+
+ size_t startId = m_outerIndex[outer];
+ // FIXME let's make sure sizeof(long int) == sizeof(size_t)
+ size_t p = m_outerIndex[outer+1];
+ ++m_outerIndex[outer+1];
+
+ float reallocRatio = 1;
+ if (m_data.allocatedSize()<=m_data.size())
+ {
+ // if there is no preallocated memory, let's reserve a minimum of 32 elements
+ if (m_data.size()==0)
+ {
+ m_data.reserve(32);
+ }
+ else
+ {
+ // we need to reallocate the data, to reduce multiple reallocations
+ // we use a smart resize algorithm based on the current filling ratio
+ // in addition, we use float to avoid integers overflows
+ float nnzEstimate = float(m_outerIndex[outer])*float(m_outerSize)/float(outer+1);
+ reallocRatio = (nnzEstimate-float(m_data.size()))/float(m_data.size());
+ // furthermore we bound the realloc ratio to:
+ // 1) reduce multiple minor realloc when the matrix is almost filled
+ // 2) avoid to allocate too much memory when the matrix is almost empty
+ reallocRatio = (std::min)((std::max)(reallocRatio,1.5f),8.f);
+ }
+ }
+ m_data.resize(m_data.size()+1,reallocRatio);
+
+ if (!isLastVec)
+ {
+ if (previousOuter==-1)
+ {
+ // oops wrong guess.
+ // let's correct the outer offsets
+ for (Index k=0; k<=(outer+1); ++k)
+ m_outerIndex[k] = 0;
+ Index k=outer+1;
+ while(m_outerIndex[k]==0)
+ m_outerIndex[k++] = 1;
+ while (k<=m_outerSize && m_outerIndex[k]!=0)
+ m_outerIndex[k++]++;
+ p = 0;
+ --k;
+ k = m_outerIndex[k]-1;
+ while (k>0)
+ {
+ m_data.index(k) = m_data.index(k-1);
+ m_data.value(k) = m_data.value(k-1);
+ k--;
+ }
+ }
+ else
+ {
+ // we are not inserting into the last inner vec
+ // update outer indices:
+ Index j = outer+2;
+ while (j<=m_outerSize && m_outerIndex[j]!=0)
+ m_outerIndex[j++]++;
+ --j;
+ // shift data of last vecs:
+ Index k = m_outerIndex[j]-1;
+ while (k>=Index(p))
+ {
+ m_data.index(k) = m_data.index(k-1);
+ m_data.value(k) = m_data.value(k-1);
+ k--;
+ }
+ }
+ }
+
+ while ( (p > startId) && (m_data.index(p-1) > inner) )
+ {
+ m_data.index(p) = m_data.index(p-1);
+ m_data.value(p) = m_data.value(p-1);
+ --p;
+ }
+
+ m_data.index(p) = inner;
+ return (m_data.value(p) = 0);
+ }
+
+ /** \internal
+ * A vector object that is equal to 0 everywhere but v at the position i */
+ class SingletonVector
+ {
+ Index m_index;
+ Index m_value;
+ public:
+ typedef Index value_type;
+ SingletonVector(Index i, Index v)
+ : m_index(i), m_value(v)
+ {}
+
+ Index operator[](Index i) const { return i==m_index ? m_value : 0; }
+ };
+
+ /** \internal
+ * \sa insert(Index,Index) */
+ EIGEN_DONT_INLINE Scalar& insertUncompressed(Index row, Index col)
+ {
+ eigen_assert(!isCompressed());
+
+ const Index outer = IsRowMajor ? row : col;
+ const Index inner = IsRowMajor ? col : row;
+
+ std::ptrdiff_t room = m_outerIndex[outer+1] - m_outerIndex[outer];
+ std::ptrdiff_t innerNNZ = m_innerNonZeros[outer];
+ if(innerNNZ>=room)
+ {
+ // this inner vector is full, we need to reallocate the whole buffer :(
+ reserve(SingletonVector(outer,std::max<std::ptrdiff_t>(2,innerNNZ)));
+ }
+
+ Index startId = m_outerIndex[outer];
+ Index p = startId + m_innerNonZeros[outer];
+ while ( (p > startId) && (m_data.index(p-1) > inner) )
+ {
+ m_data.index(p) = m_data.index(p-1);
+ m_data.value(p) = m_data.value(p-1);
+ --p;
+ }
+
+ m_innerNonZeros[outer]++;
+
+ m_data.index(p) = inner;
+ return (m_data.value(p) = 0);
+ }
+
+public:
+ /** \internal
+ * \sa insert(Index,Index) */
+ inline Scalar& insertBackUncompressed(Index row, Index col)
+ {
+ const Index outer = IsRowMajor ? row : col;
+ const Index inner = IsRowMajor ? col : row;
+
+ eigen_assert(!isCompressed());
+ eigen_assert(m_innerNonZeros[outer]<=(m_outerIndex[outer+1] - m_outerIndex[outer]));
+
+ Index p = m_outerIndex[outer] + m_innerNonZeros[outer];
+ m_innerNonZeros[outer]++;
+ m_data.index(p) = inner;
+ return (m_data.value(p) = 0);
+ }
+
+private:
+ static void check_template_parameters()
+ {
+ EIGEN_STATIC_ASSERT(NumTraits<Index>::IsSigned,THE_INDEX_TYPE_MUST_BE_A_SIGNED_TYPE);
+ }
+
+ struct default_prunning_func {
+ default_prunning_func(Scalar ref, RealScalar eps) : reference(ref), epsilon(eps) {}
+ inline bool operator() (const Index&, const Index&, const Scalar& value) const
+ {
+ return !internal::isMuchSmallerThan(value, reference, epsilon);
+ }
+ Scalar reference;
+ RealScalar epsilon;
+ };
+};
+
+template<typename Scalar, int _Options, typename _Index>
+class SparseMatrix<Scalar,_Options,_Index>::InnerIterator
+{
+ public:
+ InnerIterator(const SparseMatrix& mat, Index outer)
+ : m_values(mat.valuePtr()), m_indices(mat.innerIndexPtr()), m_outer(outer), m_id(mat.m_outerIndex[outer])
+ {
+ if(mat.isCompressed())
+ m_end = mat.m_outerIndex[outer+1];
+ else
+ m_end = m_id + mat.m_innerNonZeros[outer];
+ }
+
+ inline InnerIterator& operator++() { m_id++; return *this; }
+
+ inline const Scalar& value() const { return m_values[m_id]; }
+ inline Scalar& valueRef() { return const_cast<Scalar&>(m_values[m_id]); }
+
+ inline Index index() const { return m_indices[m_id]; }
+ inline Index outer() const { return m_outer; }
+ inline Index row() const { return IsRowMajor ? m_outer : index(); }
+ inline Index col() const { return IsRowMajor ? index() : m_outer; }
+
+ inline operator bool() const { return (m_id < m_end); }
+
+ protected:
+ const Scalar* m_values;
+ const Index* m_indices;
+ const Index m_outer;
+ Index m_id;
+ Index m_end;
+};
+
+template<typename Scalar, int _Options, typename _Index>
+class SparseMatrix<Scalar,_Options,_Index>::ReverseInnerIterator
+{
+ public:
+ ReverseInnerIterator(const SparseMatrix& mat, Index outer)
+ : m_values(mat.valuePtr()), m_indices(mat.innerIndexPtr()), m_outer(outer), m_start(mat.m_outerIndex[outer])
+ {
+ if(mat.isCompressed())
+ m_id = mat.m_outerIndex[outer+1];
+ else
+ m_id = m_start + mat.m_innerNonZeros[outer];
+ }
+
+ inline ReverseInnerIterator& operator--() { --m_id; return *this; }
+
+ inline const Scalar& value() const { return m_values[m_id-1]; }
+ inline Scalar& valueRef() { return const_cast<Scalar&>(m_values[m_id-1]); }
+
+ inline Index index() const { return m_indices[m_id-1]; }
+ inline Index outer() const { return m_outer; }
+ inline Index row() const { return IsRowMajor ? m_outer : index(); }
+ inline Index col() const { return IsRowMajor ? index() : m_outer; }
+
+ inline operator bool() const { return (m_id > m_start); }
+
+ protected:
+ const Scalar* m_values;
+ const Index* m_indices;
+ const Index m_outer;
+ Index m_id;
+ const Index m_start;
+};
+
+namespace internal {
+
+template<typename InputIterator, typename SparseMatrixType>
+void set_from_triplets(const InputIterator& begin, const InputIterator& end, SparseMatrixType& mat, int Options = 0)
+{
+ EIGEN_UNUSED_VARIABLE(Options);
+ enum { IsRowMajor = SparseMatrixType::IsRowMajor };
+ typedef typename SparseMatrixType::Scalar Scalar;
+ typedef typename SparseMatrixType::Index Index;
+ SparseMatrix<Scalar,IsRowMajor?ColMajor:RowMajor> trMat(mat.rows(),mat.cols());
+
+ // pass 1: count the nnz per inner-vector
+ VectorXi wi(trMat.outerSize());
+ wi.setZero();
+ for(InputIterator it(begin); it!=end; ++it)
+ wi(IsRowMajor ? it->col() : it->row())++;
+
+ // pass 2: insert all the elements into trMat
+ trMat.reserve(wi);
+ for(InputIterator it(begin); it!=end; ++it)
+ trMat.insertBackUncompressed(it->row(),it->col()) = it->value();
+
+ // pass 3:
+ trMat.sumupDuplicates();
+
+ // pass 4: transposed copy -> implicit sorting
+ mat = trMat;
+}
+
+}
+
+
+/** Fill the matrix \c *this with the list of \em triplets defined by the iterator range \a begin - \b.
+ *
+ * A \em triplet is a tuple (i,j,value) defining a non-zero element.
+ * The input list of triplets does not have to be sorted, and can contains duplicated elements.
+ * In any case, the result is a \b sorted and \b compressed sparse matrix where the duplicates have been summed up.
+ * This is a \em O(n) operation, with \em n the number of triplet elements.
+ * The initial contents of \c *this is destroyed.
+ * The matrix \c *this must be properly resized beforehand using the SparseMatrix(Index,Index) constructor,
+ * or the resize(Index,Index) method. The sizes are not extracted from the triplet list.
+ *
+ * The \a InputIterators value_type must provide the following interface:
+ * \code
+ * Scalar value() const; // the value
+ * Scalar row() const; // the row index i
+ * Scalar col() const; // the column index j
+ * \endcode
+ * See for instance the Eigen::Triplet template class.
+ *
+ * Here is a typical usage example:
+ * \code
+ typedef Triplet<double> T;
+ std::vector<T> tripletList;
+ triplets.reserve(estimation_of_entries);
+ for(...)
+ {
+ // ...
+ tripletList.push_back(T(i,j,v_ij));
+ }
+ SparseMatrixType m(rows,cols);
+ m.setFromTriplets(tripletList.begin(), tripletList.end());
+ // m is ready to go!
+ * \endcode
+ *
+ * \warning The list of triplets is read multiple times (at least twice). Therefore, it is not recommended to define
+ * an abstract iterator over a complex data-structure that would be expensive to evaluate. The triplets should rather
+ * be explicitely stored into a std::vector for instance.
+ */
+template<typename Scalar, int _Options, typename _Index>
+template<typename InputIterators>
+void SparseMatrix<Scalar,_Options,_Index>::setFromTriplets(const InputIterators& begin, const InputIterators& end)
+{
+ internal::set_from_triplets(begin, end, *this);
+}
+
+/** \internal */
+template<typename Scalar, int _Options, typename _Index>
+void SparseMatrix<Scalar,_Options,_Index>::sumupDuplicates()
+{
+ eigen_assert(!isCompressed());
+ // TODO, in practice we should be able to use m_innerNonZeros for that task
+ VectorXi wi(innerSize());
+ wi.fill(-1);
+ Index count = 0;
+ // for each inner-vector, wi[inner_index] will hold the position of first element into the index/value buffers
+ for(int j=0; j<outerSize(); ++j)
+ {
+ Index start = count;
+ Index oldEnd = m_outerIndex[j]+m_innerNonZeros[j];
+ for(Index k=m_outerIndex[j]; k<oldEnd; ++k)
+ {
+ Index i = m_data.index(k);
+ if(wi(i)>=start)
+ {
+ // we already meet this entry => accumulate it
+ m_data.value(wi(i)) += m_data.value(k);
+ }
+ else
+ {
+ m_data.value(count) = m_data.value(k);
+ m_data.index(count) = m_data.index(k);
+ wi(i) = count;
+ ++count;
+ }
+ }
+ m_outerIndex[j] = start;
+ }
+ m_outerIndex[m_outerSize] = count;
+
+ // turn the matrix into compressed form
+ delete[] m_innerNonZeros;
+ m_innerNonZeros = 0;
+ m_data.resize(m_outerIndex[m_outerSize]);
+}
+
+} // end namespace Eigen
+
+#endif // EIGEN_SPARSEMATRIX_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseMatrixBase.h b/extern/Eigen3/Eigen/src/SparseCore/SparseMatrixBase.h
index c01981bc935..9a1258097fe 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseMatrixBase.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseMatrixBase.h
@@ -1,31 +1,18 @@
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
-// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
+// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSEMATRIXBASE_H
#define EIGEN_SPARSEMATRIXBASE_H
-/** \ingroup Sparse_Module
+namespace Eigen {
+
+/** \ingroup SparseCore_Module
*
* \class SparseMatrixBase
*
@@ -44,6 +31,9 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
typedef typename internal::packet_traits<Scalar>::type PacketScalar;
typedef typename internal::traits<Derived>::StorageKind StorageKind;
typedef typename internal::traits<Derived>::Index Index;
+ typedef typename internal::add_const_on_value_type_if_arithmetic<
+ typename internal::packet_traits<Scalar>::type
+ >::type PacketReturnType;
typedef SparseMatrixBase StorageBaseType;
typedef EigenBase<Derived> Base;
@@ -54,8 +44,6 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
other.derived().evalTo(derived());
return derived();
}
-
-// using Base::operator=;
enum {
@@ -107,15 +95,6 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
#endif
};
- /* \internal the return type of MatrixBase::conjugate() */
-// typedef typename internal::conditional<NumTraits<Scalar>::IsComplex,
-// const SparseCwiseUnaryOp<internal::scalar_conjugate_op<Scalar>, Derived>,
-// const Derived&
-// >::type ConjugateReturnType;
- /* \internal the return type of MatrixBase::real() */
-// typedef SparseCwiseUnaryOp<internal::scalar_real_op<Scalar>, Derived> RealReturnType;
- /* \internal the return type of MatrixBase::imag() */
-// typedef SparseCwiseUnaryOp<internal::scalar_imag_op<Scalar>, Derived> ImagReturnType;
/** \internal the return type of MatrixBase::adjoint() */
typedef typename internal::conditional<NumTraits<Scalar>::IsComplex,
CwiseUnaryOp<internal::scalar_conjugate_op<Scalar>, Eigen::Transpose<const Derived> >,
@@ -125,16 +104,6 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
typedef SparseMatrix<Scalar, Flags&RowMajorBit ? RowMajor : ColMajor> PlainObject;
-#define EIGEN_CURRENT_STORAGE_BASE_CLASS Eigen::SparseMatrixBase
-# include "../plugins/CommonCwiseUnaryOps.h"
-# include "../plugins/CommonCwiseBinaryOps.h"
-# include "../plugins/MatrixCwiseUnaryOps.h"
-# include "../plugins/MatrixCwiseBinaryOps.h"
-# ifdef EIGEN_SPARSEMATRIXBASE_PLUGIN
-# include EIGEN_SPARSEMATRIXBASE_PLUGIN
-# endif
-# undef EIGEN_CURRENT_STORAGE_BASE_CLASS
-#undef EIGEN_CURRENT_STORAGE_BASE_CLASS
#ifndef EIGEN_PARSED_BY_DOXYGEN
/** This is the "real scalar" type; if the \a Scalar type is already real numbers
@@ -162,12 +131,24 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
{ return *static_cast<Derived*>(const_cast<SparseMatrixBase*>(this)); }
#endif // not EIGEN_PARSED_BY_DOXYGEN
- /** \returns the number of rows. \sa cols(), RowsAtCompileTime */
+#define EIGEN_CURRENT_STORAGE_BASE_CLASS Eigen::SparseMatrixBase
+# include "../plugins/CommonCwiseUnaryOps.h"
+# include "../plugins/CommonCwiseBinaryOps.h"
+# include "../plugins/MatrixCwiseUnaryOps.h"
+# include "../plugins/MatrixCwiseBinaryOps.h"
+# ifdef EIGEN_SPARSEMATRIXBASE_PLUGIN
+# include EIGEN_SPARSEMATRIXBASE_PLUGIN
+# endif
+# undef EIGEN_CURRENT_STORAGE_BASE_CLASS
+#undef EIGEN_CURRENT_STORAGE_BASE_CLASS
+
+
+ /** \returns the number of rows. \sa cols() */
inline Index rows() const { return derived().rows(); }
- /** \returns the number of columns. \sa rows(), ColsAtCompileTime*/
+ /** \returns the number of columns. \sa rows() */
inline Index cols() const { return derived().cols(); }
/** \returns the number of coefficients, which is \a rows()*cols().
- * \sa rows(), cols(), SizeAtCompileTime. */
+ * \sa rows(), cols(). */
inline Index size() const { return rows() * cols(); }
/** \returns the number of nonzero coefficients which is in practice the number
* of stored coefficients. */
@@ -188,29 +169,64 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
Derived& markAsRValue() { m_isRValue = true; return derived(); }
SparseMatrixBase() : m_isRValue(false) { /* TODO check flags */ }
+
+ template<typename OtherDerived>
+ Derived& operator=(const ReturnByValue<OtherDerived>& other)
+ {
+ other.evalTo(derived());
+ return derived();
+ }
+
+
+ template<typename OtherDerived>
+ inline Derived& operator=(const SparseMatrixBase<OtherDerived>& other)
+ {
+ return assign(other.derived());
+ }
+
inline Derived& operator=(const Derived& other)
{
-// std::cout << "Derived& operator=(const Derived& other)\n";
// if (other.isRValue())
// derived().swap(other.const_cast_derived());
// else
- this->operator=<Derived>(other);
- return derived();
+ return assign(other.derived());
}
-
+
+ protected:
+
template<typename OtherDerived>
- Derived& operator=(const ReturnByValue<OtherDerived>& other)
+ inline Derived& assign(const OtherDerived& other)
{
- other.evalTo(derived());
+ const bool transpose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit);
+ const Index outerSize = (int(OtherDerived::Flags) & RowMajorBit) ? other.rows() : other.cols();
+ if ((!transpose) && other.isRValue())
+ {
+ // eval without temporary
+ derived().resize(other.rows(), other.cols());
+ derived().setZero();
+ derived().reserve((std::max)(this->rows(),this->cols())*2);
+ for (Index j=0; j<outerSize; ++j)
+ {
+ derived().startVec(j);
+ for (typename OtherDerived::InnerIterator it(other, j); it; ++it)
+ {
+ Scalar v = it.value();
+ derived().insertBackByOuterInner(j,it.index()) = v;
+ }
+ }
+ derived().finalize();
+ }
+ else
+ {
+ assignGeneric(other);
+ }
return derived();
}
-
template<typename OtherDerived>
inline void assignGeneric(const OtherDerived& other)
{
-// std::cout << "Derived& operator=(const MatrixBase<OtherDerived>& other)\n";
//const bool transpose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit);
eigen_assert(( ((internal::traits<Derived>::SupportedAccessPatterns&OuterRandomAccessPattern)==OuterRandomAccessPattern) ||
(!((Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit)))) &&
@@ -230,8 +246,7 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
for (typename OtherDerived::InnerIterator it(other.derived(), j); it; ++it)
{
Scalar v = it.value();
- if (v!=Scalar(0))
- temp.insertBackByOuterInner(Flip?it.index():j,Flip?j:it.index()) = v;
+ temp.insertBackByOuterInner(Flip?it.index():j,Flip?j:it.index()) = v;
}
}
temp.finalize();
@@ -239,54 +254,23 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
derived() = temp.markAsRValue();
}
-
- template<typename OtherDerived>
- inline Derived& operator=(const SparseMatrixBase<OtherDerived>& other)
- {
-// std::cout << typeid(OtherDerived).name() << "\n";
-// std::cout << Flags << " " << OtherDerived::Flags << "\n";
- const bool transpose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit);
-// std::cout << "eval transpose = " << transpose << "\n";
- const Index outerSize = (int(OtherDerived::Flags) & RowMajorBit) ? other.rows() : other.cols();
- if ((!transpose) && other.isRValue())
- {
- // eval without temporary
- derived().resize(other.rows(), other.cols());
- derived().setZero();
- derived().reserve((std::max)(this->rows(),this->cols())*2);
- for (Index j=0; j<outerSize; ++j)
- {
- derived().startVec(j);
- for (typename OtherDerived::InnerIterator it(other.derived(), j); it; ++it)
- {
- Scalar v = it.value();
- if (v!=Scalar(0))
- derived().insertBackByOuterInner(j,it.index()) = v;
- }
- }
- derived().finalize();
- }
- else
- {
- assignGeneric(other.derived());
- }
- return derived();
- }
+ public:
template<typename Lhs, typename Rhs>
inline Derived& operator=(const SparseSparseProduct<Lhs,Rhs>& product);
- template<typename Lhs, typename Rhs>
- inline void _experimentalNewProduct(const Lhs& lhs, const Rhs& rhs);
-
friend std::ostream & operator << (std::ostream & s, const SparseMatrixBase& m)
{
+ typedef typename Derived::Nested Nested;
+ typedef typename internal::remove_all<Nested>::type NestedCleaned;
+
if (Flags&RowMajorBit)
{
- for (Index row=0; row<m.outerSize(); ++row)
+ const Nested nm(m.derived());
+ for (Index row=0; row<nm.outerSize(); ++row)
{
Index col = 0;
- for (typename Derived::InnerIterator it(m.derived(), row); it; ++it)
+ for (typename NestedCleaned::InnerIterator it(nm.derived(), row); it; ++it)
{
for ( ; col<it.index(); ++col)
s << "0 ";
@@ -300,9 +284,10 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
}
else
{
+ const Nested nm(m.derived());
if (m.cols() == 1) {
Index row = 0;
- for (typename Derived::InnerIterator it(m.derived(), 0); it; ++it)
+ for (typename NestedCleaned::InnerIterator it(nm.derived(), 0); it; ++it)
{
for ( ; row<it.index(); ++row)
s << "0" << std::endl;
@@ -314,31 +299,18 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
}
else
{
- SparseMatrix<Scalar, RowMajorBit> trans = m.derived();
- s << trans;
+ SparseMatrix<Scalar, RowMajorBit> trans = m;
+ s << static_cast<const SparseMatrixBase<SparseMatrix<Scalar, RowMajorBit> >&>(trans);
}
}
return s;
}
-// const SparseCwiseUnaryOp<internal::scalar_opposite_op<typename internal::traits<Derived>::Scalar>,Derived> operator-() const;
-
-// template<typename OtherDerived>
-// const CwiseBinaryOp<internal::scalar_sum_op<typename internal::traits<Derived>::Scalar>, Derived, OtherDerived>
-// operator+(const SparseMatrixBase<OtherDerived> &other) const;
-
-// template<typename OtherDerived>
-// const CwiseBinaryOp<internal::scalar_difference_op<typename internal::traits<Derived>::Scalar>, Derived, OtherDerived>
-// operator-(const SparseMatrixBase<OtherDerived> &other) const;
-
template<typename OtherDerived>
Derived& operator+=(const SparseMatrixBase<OtherDerived>& other);
template<typename OtherDerived>
Derived& operator-=(const SparseMatrixBase<OtherDerived>& other);
-// template<typename Lhs,typename Rhs>
-// Derived& operator+=(const Flagged<Product<Lhs,Rhs,CacheFriendlyProduct>, 0, EvalBeforeNestingBit | EvalBeforeAssigningBit>& other);
-
Derived& operator*=(const Scalar& other);
Derived& operator/=(const Scalar& other);
@@ -358,16 +330,6 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
EIGEN_STRONG_INLINE const EIGEN_SPARSE_CWISE_PRODUCT_RETURN_TYPE
cwiseProduct(const MatrixBase<OtherDerived> &other) const;
-// const SparseCwiseUnaryOp<internal::scalar_multiple_op<typename internal::traits<Derived>::Scalar>, Derived>
-// operator*(const Scalar& scalar) const;
-// const SparseCwiseUnaryOp<internal::scalar_quotient1_op<typename internal::traits<Derived>::Scalar>, Derived>
-// operator/(const Scalar& scalar) const;
-
-// inline friend const SparseCwiseUnaryOp<internal::scalar_multiple_op<typename internal::traits<Derived>::Scalar>, Derived>
-// operator*(const Scalar& scalar, const SparseMatrixBase& matrix)
-// { return matrix*scalar; }
-
-
// sparse * sparse
template<typename OtherDerived>
const typename SparseSparseProductReturnType<Derived,OtherDerived>::Type
@@ -394,6 +356,12 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
template<typename OtherDerived>
const typename SparseDenseProductReturnType<Derived,OtherDerived>::Type
operator*(const MatrixBase<OtherDerived> &other) const;
+
+ /** \returns an expression of P H P^-1 where H is the matrix represented by \c *this */
+ SparseSymmetricPermutationProduct<Derived,Upper|Lower> twistedBy(const PermutationMatrix<Dynamic,Dynamic,Index>& perm) const
+ {
+ return SparseSymmetricPermutationProduct<Derived,Upper|Lower>(derived(), perm);
+ }
template<typename OtherDerived>
Derived& operator*=(const SparseMatrixBase<OtherDerived>& other);
@@ -407,8 +375,6 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
// deprecated
template<typename OtherDerived>
void solveTriangularInPlace(MatrixBase<OtherDerived>& other) const;
-// template<typename OtherDerived>
-// void solveTriangularInPlace(SparseMatrixBase<OtherDerived>& other) const;
#endif // EIGEN2_SUPPORT
template<int Mode>
@@ -421,12 +387,9 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
template<typename OtherDerived> Scalar dot(const SparseMatrixBase<OtherDerived>& other) const;
RealScalar squaredNorm() const;
RealScalar norm() const;
-// const PlainObject normalized() const;
-// void normalize();
Transpose<Derived> transpose() { return derived(); }
const Transpose<const Derived> transpose() const { return derived(); }
- // void transposeInPlace();
const AdjointReturnType adjoint() const { return transpose(); }
// sub-vector
@@ -442,77 +405,14 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
const SparseInnerVectorSet<Derived,Dynamic> subrows(Index start, Index size) const;
SparseInnerVectorSet<Derived,Dynamic> subcols(Index start, Index size);
const SparseInnerVectorSet<Derived,Dynamic> subcols(Index start, Index size) const;
+
+ SparseInnerVectorSet<Derived,Dynamic> middleRows(Index start, Index size);
+ const SparseInnerVectorSet<Derived,Dynamic> middleRows(Index start, Index size) const;
+ SparseInnerVectorSet<Derived,Dynamic> middleCols(Index start, Index size);
+ const SparseInnerVectorSet<Derived,Dynamic> middleCols(Index start, Index size) const;
SparseInnerVectorSet<Derived,Dynamic> innerVectors(Index outerStart, Index outerSize);
const SparseInnerVectorSet<Derived,Dynamic> innerVectors(Index outerStart, Index outerSize) const;
-// typename BlockReturnType<Derived>::Type block(int startRow, int startCol, int blockRows, int blockCols);
-// const typename BlockReturnType<Derived>::Type
-// block(int startRow, int startCol, int blockRows, int blockCols) const;
-//
-// typename BlockReturnType<Derived>::SubVectorType segment(int start, int size);
-// const typename BlockReturnType<Derived>::SubVectorType segment(int start, int size) const;
-//
-// typename BlockReturnType<Derived,Dynamic>::SubVectorType start(int size);
-// const typename BlockReturnType<Derived,Dynamic>::SubVectorType start(int size) const;
-//
-// typename BlockReturnType<Derived,Dynamic>::SubVectorType end(int size);
-// const typename BlockReturnType<Derived,Dynamic>::SubVectorType end(int size) const;
-//
-// template<int BlockRows, int BlockCols>
-// typename BlockReturnType<Derived, BlockRows, BlockCols>::Type block(int startRow, int startCol);
-// template<int BlockRows, int BlockCols>
-// const typename BlockReturnType<Derived, BlockRows, BlockCols>::Type block(int startRow, int startCol) const;
-
-// template<int Size> typename BlockReturnType<Derived,Size>::SubVectorType start(void);
-// template<int Size> const typename BlockReturnType<Derived,Size>::SubVectorType start() const;
-
-// template<int Size> typename BlockReturnType<Derived,Size>::SubVectorType end();
-// template<int Size> const typename BlockReturnType<Derived,Size>::SubVectorType end() const;
-
-// template<int Size> typename BlockReturnType<Derived,Size>::SubVectorType segment(int start);
-// template<int Size> const typename BlockReturnType<Derived,Size>::SubVectorType segment(int start) const;
-
-// Diagonal<Derived> diagonal();
-// const Diagonal<Derived> diagonal() const;
-
-// template<unsigned int Mode> Part<Derived, Mode> part();
-// template<unsigned int Mode> const Part<Derived, Mode> part() const;
-
-
-// static const ConstantReturnType Constant(int rows, int cols, const Scalar& value);
-// static const ConstantReturnType Constant(int size, const Scalar& value);
-// static const ConstantReturnType Constant(const Scalar& value);
-
-// template<typename CustomNullaryOp>
-// static const CwiseNullaryOp<CustomNullaryOp, Derived> NullaryExpr(int rows, int cols, const CustomNullaryOp& func);
-// template<typename CustomNullaryOp>
-// static const CwiseNullaryOp<CustomNullaryOp, Derived> NullaryExpr(int size, const CustomNullaryOp& func);
-// template<typename CustomNullaryOp>
-// static const CwiseNullaryOp<CustomNullaryOp, Derived> NullaryExpr(const CustomNullaryOp& func);
-
-// static const ConstantReturnType Zero(int rows, int cols);
-// static const ConstantReturnType Zero(int size);
-// static const ConstantReturnType Zero();
-// static const ConstantReturnType Ones(int rows, int cols);
-// static const ConstantReturnType Ones(int size);
-// static const ConstantReturnType Ones();
-// static const IdentityReturnType Identity();
-// static const IdentityReturnType Identity(int rows, int cols);
-// static const BasisReturnType Unit(int size, int i);
-// static const BasisReturnType Unit(int i);
-// static const BasisReturnType UnitX();
-// static const BasisReturnType UnitY();
-// static const BasisReturnType UnitZ();
-// static const BasisReturnType UnitW();
-
-// const DiagonalMatrix<Derived> asDiagonal() const;
-
-// Derived& setConstant(const Scalar& value);
-// Derived& setZero();
-// Derived& setOnes();
-// Derived& setRandom();
-// Derived& setIdentity();
-
/** \internal use operator= */
template<typename DenseDerived>
void evalTo(MatrixBase<DenseDerived>& dst) const
@@ -537,37 +437,6 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
bool isApprox(const MatrixBase<OtherDerived>& other,
RealScalar prec = NumTraits<Scalar>::dummy_precision()) const
{ return toDense().isApprox(other,prec); }
-// bool isMuchSmallerThan(const RealScalar& other,
-// RealScalar prec = NumTraits<Scalar>::dummy_precision()) const;
-// template<typename OtherDerived>
-// bool isMuchSmallerThan(const MatrixBase<OtherDerived>& other,
-// RealScalar prec = NumTraits<Scalar>::dummy_precision()) const;
-
-// bool isApproxToConstant(const Scalar& value, RealScalar prec = NumTraits<Scalar>::dummy_precision()) const;
-// bool isZero(RealScalar prec = NumTraits<Scalar>::dummy_precision()) const;
-// bool isOnes(RealScalar prec = NumTraits<Scalar>::dummy_precision()) const;
-// bool isIdentity(RealScalar prec = NumTraits<Scalar>::dummy_precision()) const;
-// bool isDiagonal(RealScalar prec = NumTraits<Scalar>::dummy_precision()) const;
-
-// bool isUpper(RealScalar prec = NumTraits<Scalar>::dummy_precision()) const;
-// bool isLower(RealScalar prec = NumTraits<Scalar>::dummy_precision()) const;
-
-// template<typename OtherDerived>
-// bool isOrthogonal(const MatrixBase<OtherDerived>& other,
-// RealScalar prec = NumTraits<Scalar>::dummy_precision()) const;
-// bool isUnitary(RealScalar prec = NumTraits<Scalar>::dummy_precision()) const;
-
-// template<typename OtherDerived>
-// inline bool operator==(const MatrixBase<OtherDerived>& other) const
-// { return (cwise() == other).all(); }
-
-// template<typename OtherDerived>
-// inline bool operator!=(const MatrixBase<OtherDerived>& other) const
-// { return (cwise() != other).any(); }
-
-
-// template<typename NewType>
-// const SparseCwiseUnaryOp<internal::scalar_cast_op<typename internal::traits<Derived>::Scalar, NewType>, Derived> cast() const;
/** \returns the matrix or vector obtained by evaluating this expression.
*
@@ -577,130 +446,13 @@ template<typename Derived> class SparseMatrixBase : public EigenBase<Derived>
inline const typename internal::eval<Derived>::type eval() const
{ return typename internal::eval<Derived>::type(derived()); }
-// template<typename OtherDerived>
-// void swap(MatrixBase<OtherDerived> const & other);
-
-// template<unsigned int Added>
-// const SparseFlagged<Derived, Added, 0> marked() const;
-// const Flagged<Derived, 0, EvalBeforeNestingBit | EvalBeforeAssigningBit> lazy() const;
-
- /** \returns number of elements to skip to pass from one row (resp. column) to another
- * for a row-major (resp. column-major) matrix.
- * Combined with coeffRef() and the \ref flags flags, it allows a direct access to the data
- * of the underlying matrix.
- */
-// inline int stride(void) const { return derived().stride(); }
-
-// FIXME
-// ConjugateReturnType conjugate() const;
-// const RealReturnType real() const;
-// const ImagReturnType imag() const;
-
-// template<typename CustomUnaryOp>
-// const SparseCwiseUnaryOp<CustomUnaryOp, Derived> unaryExpr(const CustomUnaryOp& func = CustomUnaryOp()) const;
-
-// template<typename CustomBinaryOp, typename OtherDerived>
-// const CwiseBinaryOp<CustomBinaryOp, Derived, OtherDerived>
-// binaryExpr(const MatrixBase<OtherDerived> &other, const CustomBinaryOp& func = CustomBinaryOp()) const;
-
-
Scalar sum() const;
-// Scalar trace() const;
-
-// typename internal::traits<Derived>::Scalar minCoeff() const;
-// typename internal::traits<Derived>::Scalar maxCoeff() const;
-
-// typename internal::traits<Derived>::Scalar minCoeff(int* row, int* col = 0) const;
-// typename internal::traits<Derived>::Scalar maxCoeff(int* row, int* col = 0) const;
-
-// template<typename BinaryOp>
-// typename internal::result_of<BinaryOp(typename internal::traits<Derived>::Scalar)>::type
-// redux(const BinaryOp& func) const;
-
-// template<typename Visitor>
-// void visit(Visitor& func) const;
-
-
-// const SparseCwise<Derived> cwise() const;
-// SparseCwise<Derived> cwise();
-
-// inline const WithFormat<Derived> format(const IOFormat& fmt) const;
-
-/////////// Array module ///////////
- /*
- bool all(void) const;
- bool any(void) const;
-
- const VectorwiseOp<Derived,Horizontal> rowwise() const;
- const VectorwiseOp<Derived,Vertical> colwise() const;
-
- static const CwiseNullaryOp<internal::scalar_random_op<Scalar>,Derived> Random(int rows, int cols);
- static const CwiseNullaryOp<internal::scalar_random_op<Scalar>,Derived> Random(int size);
- static const CwiseNullaryOp<internal::scalar_random_op<Scalar>,Derived> Random();
-
- template<typename ThenDerived,typename ElseDerived>
- const Select<Derived,ThenDerived,ElseDerived>
- select(const MatrixBase<ThenDerived>& thenMatrix,
- const MatrixBase<ElseDerived>& elseMatrix) const;
-
- template<typename ThenDerived>
- inline const Select<Derived,ThenDerived, typename ThenDerived::ConstantReturnType>
- select(const MatrixBase<ThenDerived>& thenMatrix, typename ThenDerived::Scalar elseScalar) const;
-
- template<typename ElseDerived>
- inline const Select<Derived, typename ElseDerived::ConstantReturnType, ElseDerived >
- select(typename ElseDerived::Scalar thenScalar, const MatrixBase<ElseDerived>& elseMatrix) const;
-
- template<int p> RealScalar lpNorm() const;
- */
-
-
-// template<typename OtherDerived>
-// Scalar dot(const MatrixBase<OtherDerived>& other) const
-// {
-// EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived)
-// EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
-// EIGEN_STATIC_ASSERT((internal::is_same<Scalar, typename OtherDerived::Scalar>::value),
-// YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)
-//
-// eigen_assert(derived().size() == other.size());
-// // short version, but the assembly looks more complicated because
-// // of the CwiseBinaryOp iterator complexity
-// // return res = (derived().cwise() * other.derived().conjugate()).sum();
-//
-// // optimized, generic version
-// typename Derived::InnerIterator i(derived(),0);
-// typename OtherDerived::InnerIterator j(other.derived(),0);
-// Scalar res = 0;
-// while (i && j)
-// {
-// if (i.index()==j.index())
-// {
-// // std::cerr << i.value() << " * " << j.value() << "\n";
-// res += i.value() * internal::conj(j.value());
-// ++i; ++j;
-// }
-// else if (i.index()<j.index())
-// ++i;
-// else
-// ++j;
-// }
-// return res;
-// }
-//
-// Scalar sum() const
-// {
-// Scalar res = 0;
-// for (typename Derived::InnerIterator iter(*this,0); iter; ++iter)
-// {
-// res += iter.value();
-// }
-// return res;
-// }
protected:
bool m_isRValue;
};
+} // end namespace Eigen
+
#endif // EIGEN_SPARSEMATRIXBASE_H
diff --git a/extern/Eigen3/Eigen/src/SparseCore/SparsePermutation.h b/extern/Eigen3/Eigen/src/SparseCore/SparsePermutation.h
new file mode 100644
index 00000000000..b897b7595b5
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparsePermutation.h
@@ -0,0 +1,148 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2012 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_SPARSE_PERMUTATION_H
+#define EIGEN_SPARSE_PERMUTATION_H
+
+// This file implements sparse * permutation products
+
+namespace Eigen {
+
+namespace internal {
+
+template<typename PermutationType, typename MatrixType, int Side, bool Transposed>
+struct traits<permut_sparsematrix_product_retval<PermutationType, MatrixType, Side, Transposed> >
+{
+ typedef typename remove_all<typename MatrixType::Nested>::type MatrixTypeNestedCleaned;
+ typedef typename MatrixTypeNestedCleaned::Scalar Scalar;
+ typedef typename MatrixTypeNestedCleaned::Index Index;
+ enum {
+ SrcStorageOrder = MatrixTypeNestedCleaned::Flags&RowMajorBit ? RowMajor : ColMajor,
+ MoveOuter = SrcStorageOrder==RowMajor ? Side==OnTheLeft : Side==OnTheRight
+ };
+
+ typedef typename internal::conditional<MoveOuter,
+ SparseMatrix<Scalar,SrcStorageOrder,Index>,
+ SparseMatrix<Scalar,int(SrcStorageOrder)==RowMajor?ColMajor:RowMajor,Index> >::type ReturnType;
+};
+
+template<typename PermutationType, typename MatrixType, int Side, bool Transposed>
+struct permut_sparsematrix_product_retval
+ : public ReturnByValue<permut_sparsematrix_product_retval<PermutationType, MatrixType, Side, Transposed> >
+{
+ typedef typename remove_all<typename MatrixType::Nested>::type MatrixTypeNestedCleaned;
+ typedef typename MatrixTypeNestedCleaned::Scalar Scalar;
+ typedef typename MatrixTypeNestedCleaned::Index Index;
+
+ enum {
+ SrcStorageOrder = MatrixTypeNestedCleaned::Flags&RowMajorBit ? RowMajor : ColMajor,
+ MoveOuter = SrcStorageOrder==RowMajor ? Side==OnTheLeft : Side==OnTheRight
+ };
+
+ permut_sparsematrix_product_retval(const PermutationType& perm, const MatrixType& matrix)
+ : m_permutation(perm), m_matrix(matrix)
+ {}
+
+ inline int rows() const { return m_matrix.rows(); }
+ inline int cols() const { return m_matrix.cols(); }
+
+ template<typename Dest> inline void evalTo(Dest& dst) const
+ {
+ if(MoveOuter)
+ {
+ SparseMatrix<Scalar,SrcStorageOrder,Index> tmp(m_matrix.rows(), m_matrix.cols());
+ VectorXi sizes(m_matrix.outerSize());
+ for(Index j=0; j<m_matrix.outerSize(); ++j)
+ {
+ Index jp = m_permutation.indices().coeff(j);
+ sizes[((Side==OnTheLeft) ^ Transposed) ? jp : j] = m_matrix.innerVector(((Side==OnTheRight) ^ Transposed) ? jp : j).size();
+ }
+ tmp.reserve(sizes);
+ for(Index j=0; j<m_matrix.outerSize(); ++j)
+ {
+ Index jp = m_permutation.indices().coeff(j);
+ Index jsrc = ((Side==OnTheRight) ^ Transposed) ? jp : j;
+ Index jdst = ((Side==OnTheLeft) ^ Transposed) ? jp : j;
+ for(typename MatrixTypeNestedCleaned::InnerIterator it(m_matrix,jsrc); it; ++it)
+ tmp.insertByOuterInner(jdst,it.index()) = it.value();
+ }
+ dst = tmp;
+ }
+ else
+ {
+ SparseMatrix<Scalar,int(SrcStorageOrder)==RowMajor?ColMajor:RowMajor,Index> tmp(m_matrix.rows(), m_matrix.cols());
+ VectorXi sizes(tmp.outerSize());
+ sizes.setZero();
+ PermutationMatrix<Dynamic,Dynamic,Index> perm;
+ if((Side==OnTheLeft) ^ Transposed)
+ perm = m_permutation;
+ else
+ perm = m_permutation.transpose();
+
+ for(Index j=0; j<m_matrix.outerSize(); ++j)
+ for(typename MatrixTypeNestedCleaned::InnerIterator it(m_matrix,j); it; ++it)
+ sizes[perm.indices().coeff(it.index())]++;
+ tmp.reserve(sizes);
+ for(Index j=0; j<m_matrix.outerSize(); ++j)
+ for(typename MatrixTypeNestedCleaned::InnerIterator it(m_matrix,j); it; ++it)
+ tmp.insertByOuterInner(perm.indices().coeff(it.index()),j) = it.value();
+ dst = tmp;
+ }
+ }
+
+ protected:
+ const PermutationType& m_permutation;
+ typename MatrixType::Nested m_matrix;
+};
+
+}
+
+
+
+/** \returns the matrix with the permutation applied to the columns
+ */
+template<typename SparseDerived, typename PermDerived>
+inline const internal::permut_sparsematrix_product_retval<PermutationBase<PermDerived>, SparseDerived, OnTheRight, false>
+operator*(const SparseMatrixBase<SparseDerived>& matrix, const PermutationBase<PermDerived>& perm)
+{
+ return internal::permut_sparsematrix_product_retval<PermutationBase<PermDerived>, SparseDerived, OnTheRight, false>(perm, matrix.derived());
+}
+
+/** \returns the matrix with the permutation applied to the rows
+ */
+template<typename SparseDerived, typename PermDerived>
+inline const internal::permut_sparsematrix_product_retval<PermutationBase<PermDerived>, SparseDerived, OnTheLeft, false>
+operator*( const PermutationBase<PermDerived>& perm, const SparseMatrixBase<SparseDerived>& matrix)
+{
+ return internal::permut_sparsematrix_product_retval<PermutationBase<PermDerived>, SparseDerived, OnTheLeft, false>(perm, matrix.derived());
+}
+
+
+
+/** \returns the matrix with the inverse permutation applied to the columns.
+ */
+template<typename SparseDerived, typename PermDerived>
+inline const internal::permut_sparsematrix_product_retval<PermutationBase<PermDerived>, SparseDerived, OnTheRight, true>
+operator*(const SparseMatrixBase<SparseDerived>& matrix, const Transpose<PermutationBase<PermDerived> >& tperm)
+{
+ return internal::permut_sparsematrix_product_retval<PermutationBase<PermDerived>, SparseDerived, OnTheRight, true>(tperm.nestedPermutation(), matrix.derived());
+}
+
+/** \returns the matrix with the inverse permutation applied to the rows.
+ */
+template<typename SparseDerived, typename PermDerived>
+inline const internal::permut_sparsematrix_product_retval<PermutationBase<PermDerived>, SparseDerived, OnTheLeft, true>
+operator*(const Transpose<PermutationBase<PermDerived> >& tperm, const SparseMatrixBase<SparseDerived>& matrix)
+{
+ return internal::permut_sparsematrix_product_retval<PermutationBase<PermDerived>, SparseDerived, OnTheLeft, true>(tperm.nestedPermutation(), matrix.derived());
+}
+
+} // end namespace Eigen
+
+#endif // EIGEN_SPARSE_SELFADJOINTVIEW_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseProduct.h b/extern/Eigen3/Eigen/src/SparseCore/SparseProduct.h
index 1c1f54706ac..6a555b83434 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseProduct.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseProduct.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSEPRODUCT_H
#define EIGEN_SPARSEPRODUCT_H
+namespace Eigen {
+
template<typename Lhs, typename Rhs>
struct SparseSparseProductReturnType
{
@@ -38,11 +25,11 @@ struct SparseSparseProductReturnType
typedef typename internal::conditional<TransposeLhs,
SparseMatrix<Scalar,0>,
- const typename internal::nested<Lhs,Rhs::RowsAtCompileTime>::type>::type LhsNested;
+ typename internal::nested<Lhs,Rhs::RowsAtCompileTime>::type>::type LhsNested;
typedef typename internal::conditional<TransposeRhs,
SparseMatrix<Scalar,0>,
- const typename internal::nested<Rhs,Lhs::RowsAtCompileTime>::type>::type RhsNested;
+ typename internal::nested<Rhs,Lhs::RowsAtCompileTime>::type>::type RhsNested;
typedef SparseSparseProduct<LhsNested, RhsNested> Type;
};
@@ -106,9 +93,42 @@ class SparseSparseProduct : internal::no_assignment_operator,
template<typename Lhs, typename Rhs>
EIGEN_STRONG_INLINE SparseSparseProduct(const Lhs& lhs, const Rhs& rhs)
- : m_lhs(lhs), m_rhs(rhs)
+ : m_lhs(lhs), m_rhs(rhs), m_tolerance(0), m_conservative(true)
+ {
+ init();
+ }
+
+ template<typename Lhs, typename Rhs>
+ EIGEN_STRONG_INLINE SparseSparseProduct(const Lhs& lhs, const Rhs& rhs, RealScalar tolerance)
+ : m_lhs(lhs), m_rhs(rhs), m_tolerance(tolerance), m_conservative(false)
+ {
+ init();
+ }
+
+ SparseSparseProduct pruned(Scalar reference = 0, RealScalar epsilon = NumTraits<RealScalar>::dummy_precision()) const
+ {
+ return SparseSparseProduct(m_lhs,m_rhs,internal::abs(reference)*epsilon);
+ }
+
+ template<typename Dest>
+ void evalTo(Dest& result) const
+ {
+ if(m_conservative)
+ internal::conservative_sparse_sparse_product_selector<_LhsNested, _RhsNested, Dest>::run(lhs(),rhs(),result);
+ else
+ internal::sparse_sparse_product_with_pruning_selector<_LhsNested, _RhsNested, Dest>::run(lhs(),rhs(),result,m_tolerance);
+ }
+
+ EIGEN_STRONG_INLINE Index rows() const { return m_lhs.rows(); }
+ EIGEN_STRONG_INLINE Index cols() const { return m_rhs.cols(); }
+
+ EIGEN_STRONG_INLINE const _LhsNested& lhs() const { return m_lhs; }
+ EIGEN_STRONG_INLINE const _RhsNested& rhs() const { return m_rhs; }
+
+ protected:
+ void init()
{
- eigen_assert(lhs.cols() == rhs.rows());
+ eigen_assert(m_lhs.cols() == m_rhs.rows());
enum {
ProductIsValid = _LhsNested::ColsAtCompileTime==Dynamic
@@ -127,15 +147,40 @@ class SparseSparseProduct : internal::no_assignment_operator,
EIGEN_STATIC_ASSERT(ProductIsValid || SameSizes, INVALID_MATRIX_PRODUCT)
}
- EIGEN_STRONG_INLINE Index rows() const { return m_lhs.rows(); }
- EIGEN_STRONG_INLINE Index cols() const { return m_rhs.cols(); }
-
- EIGEN_STRONG_INLINE const _LhsNested& lhs() const { return m_lhs; }
- EIGEN_STRONG_INLINE const _RhsNested& rhs() const { return m_rhs; }
-
- protected:
LhsNested m_lhs;
RhsNested m_rhs;
+ RealScalar m_tolerance;
+ bool m_conservative;
};
+// sparse = sparse * sparse
+template<typename Derived>
+template<typename Lhs, typename Rhs>
+inline Derived& SparseMatrixBase<Derived>::operator=(const SparseSparseProduct<Lhs,Rhs>& product)
+{
+ product.evalTo(derived());
+ return derived();
+}
+
+/** \returns an expression of the product of two sparse matrices.
+ * By default a conservative product preserving the symbolic non zeros is performed.
+ * The automatic pruning of the small values can be achieved by calling the pruned() function
+ * in which case a totally different product algorithm is employed:
+ * \code
+ * C = (A*B).pruned(); // supress numerical zeros (exact)
+ * C = (A*B).pruned(ref);
+ * C = (A*B).pruned(ref,epsilon);
+ * \endcode
+ * where \c ref is a meaningful non zero reference value.
+ * */
+template<typename Derived>
+template<typename OtherDerived>
+inline const typename SparseSparseProductReturnType<Derived,OtherDerived>::Type
+SparseMatrixBase<Derived>::operator*(const SparseMatrixBase<OtherDerived> &other) const
+{
+ return typename SparseSparseProductReturnType<Derived,OtherDerived>::Type(derived(), other.derived());
+}
+
+} // end namespace Eigen
+
#endif // EIGEN_SPARSEPRODUCT_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseRedux.h b/extern/Eigen3/Eigen/src/SparseCore/SparseRedux.h
index afc49de7aad..f3da93a71d4 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseRedux.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseRedux.h
@@ -3,34 +3,21 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSEREDUX_H
#define EIGEN_SPARSEREDUX_H
+namespace Eigen {
+
template<typename Derived>
typename internal::traits<Derived>::Scalar
SparseMatrixBase<Derived>::sum() const
{
eigen_assert(rows()>0 && cols()>0 && "you are using a non initialized matrix");
- Scalar res = 0;
+ Scalar res(0);
for (Index j=0; j<outerSize(); ++j)
for (typename Derived::InnerIterator iter(derived(),j); iter; ++iter)
res += iter.value();
@@ -53,4 +40,6 @@ SparseVector<_Scalar,_Options,_Index>::sum() const
return Matrix<Scalar,1,Dynamic>::Map(&m_data.value(0), m_data.size()).sum();
}
+} // end namespace Eigen
+
#endif // EIGEN_SPARSEREDUX_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseSelfAdjointView.h b/extern/Eigen3/Eigen/src/SparseCore/SparseSelfAdjointView.h
index d82044c789c..86ec0a6c5e2 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseSelfAdjointView.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseSelfAdjointView.h
@@ -3,30 +3,17 @@
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSE_SELFADJOINTVIEW_H
#define EIGEN_SPARSE_SELFADJOINTVIEW_H
-/** \class SparseSelfAdjointView
- *
+namespace Eigen {
+
+/** \ingroup SparseCore_Module
+ * \class SparseSelfAdjointView
*
* \brief Pseudo expression to manipulate a triangular sparse matrix as a selfadjoint matrix.
*
@@ -45,9 +32,6 @@ class SparseSelfAdjointTimeDenseProduct;
template<typename Lhs, typename Rhs, int UpLo>
class DenseTimeSparseSelfAdjointProduct;
-template<typename MatrixType,int UpLo>
-class SparseSymmetricPermutationProduct;
-
namespace internal {
template<typename MatrixType, unsigned int UpLo>
@@ -106,9 +90,6 @@ template<typename MatrixType, unsigned int UpLo> class SparseSelfAdjointView
*
* \returns a reference to \c *this
*
- * Note that it is faster to set alpha=0 than initializing the matrix to zero
- * and then keep the default value alpha=1.
- *
* To perform \f$ this = this + \alpha ( u^* u ) \f$ you can simply
* call this function with u.adjoint().
*/
@@ -116,21 +97,21 @@ template<typename MatrixType, unsigned int UpLo> class SparseSelfAdjointView
SparseSelfAdjointView& rankUpdate(const SparseMatrixBase<DerivedU>& u, Scalar alpha = Scalar(1));
/** \internal triggered by sparse_matrix = SparseSelfadjointView; */
- template<typename DestScalar> void evalTo(SparseMatrix<DestScalar>& _dest) const
+ template<typename DestScalar,int StorageOrder> void evalTo(SparseMatrix<DestScalar,StorageOrder,Index>& _dest) const
{
internal::permute_symm_to_fullsymm<UpLo>(m_matrix, _dest);
}
- template<typename DestScalar> void evalTo(DynamicSparseMatrix<DestScalar>& _dest) const
+ template<typename DestScalar> void evalTo(DynamicSparseMatrix<DestScalar,ColMajor,Index>& _dest) const
{
// TODO directly evaluate into _dest;
- SparseMatrix<DestScalar> tmp(_dest.rows(),_dest.cols());
+ SparseMatrix<DestScalar,ColMajor,Index> tmp(_dest.rows(),_dest.cols());
internal::permute_symm_to_fullsymm<UpLo>(m_matrix, tmp);
_dest = tmp;
}
- /** \returns an expression of P^-1 H P */
- SparseSymmetricPermutationProduct<_MatrixTypeNested,UpLo> twistedBy(const PermutationMatrix<Dynamic>& perm) const
+ /** \returns an expression of P H P^-1 */
+ SparseSymmetricPermutationProduct<_MatrixTypeNested,UpLo> twistedBy(const PermutationMatrix<Dynamic,Dynamic,Index>& perm) const
{
return SparseSymmetricPermutationProduct<_MatrixTypeNested,UpLo>(m_matrix, perm);
}
@@ -141,6 +122,20 @@ template<typename MatrixType, unsigned int UpLo> class SparseSelfAdjointView
permutedMatrix.evalTo(*this);
return *this;
}
+
+
+ SparseSelfAdjointView& operator=(const SparseSelfAdjointView& src)
+ {
+ PermutationMatrix<Dynamic> pnull;
+ return *this = src.twistedBy(pnull);
+ }
+
+ template<typename SrcMatrixType,unsigned int SrcUpLo>
+ SparseSelfAdjointView& operator=(const SparseSelfAdjointView<SrcMatrixType,SrcUpLo>& src)
+ {
+ PermutationMatrix<Dynamic> pnull;
+ return *this = src.twistedBy(pnull);
+ }
// const SparseLLT<PlainObject, UpLo> llt() const;
@@ -148,7 +143,7 @@ template<typename MatrixType, unsigned int UpLo> class SparseSelfAdjointView
protected:
- const typename MatrixType::Nested m_matrix;
+ typename MatrixType::Nested m_matrix;
mutable VectorI m_countPerRow;
mutable VectorI m_countPerCol;
};
@@ -230,12 +225,15 @@ class SparseSelfAdjointTimeDenseProduct
for (Index j=0; j<m_lhs.outerSize(); ++j)
{
LhsInnerIterator i(m_lhs,j);
- if (ProcessSecondHalf && i && (i.index()==j))
+ if (ProcessSecondHalf)
{
- dest.row(j) += i.value() * m_rhs.row(j);
- ++i;
+ while (i && i.index()<j) ++i;
+ if(i && i.index()==j)
+ {
+ dest.row(j) += i.value() * m_rhs.row(j);
+ ++i;
+ }
}
- Block<Dest,1,Dest::ColsAtCompileTime> dest_j(dest.row(LhsIsRowMajor ? j : 0));
for(; (ProcessFirstHalf ? i && i.index() < j : i) ; ++i)
{
Index a = LhsIsRowMajor ? j : i.index();
@@ -300,7 +298,7 @@ void permute_symm_to_fullsymm(const MatrixType& mat, SparseMatrix<typename Matri
enum {
StorageOrderMatch = int(Dest::IsRowMajor) == int(MatrixType::IsRowMajor)
};
- eigen_assert(perm==0);
+
Index size = mat.rows();
VectorI count;
count.resize(size);
@@ -312,10 +310,14 @@ void permute_symm_to_fullsymm(const MatrixType& mat, SparseMatrix<typename Matri
for(typename MatrixType::InnerIterator it(mat,j); it; ++it)
{
Index i = it.index();
+ Index r = it.row();
+ Index c = it.col();
Index ip = perm ? perm[i] : i;
- if(i==j)
+ if(UpLo==(Upper|Lower))
+ count[StorageOrderMatch ? jp : ip]++;
+ else if(r==c)
count[ip]++;
- else if((UpLo==Lower && i>j) || (UpLo==Upper && i<j))
+ else if(( UpLo==Lower && r>c) || ( UpLo==Upper && r<c))
{
count[ip]++;
count[jp]++;
@@ -325,49 +327,65 @@ void permute_symm_to_fullsymm(const MatrixType& mat, SparseMatrix<typename Matri
Index nnz = count.sum();
// reserve space
- dest.reserve(nnz);
- dest._outerIndexPtr()[0] = 0;
+ dest.resizeNonZeros(nnz);
+ dest.outerIndexPtr()[0] = 0;
for(Index j=0; j<size; ++j)
- dest._outerIndexPtr()[j+1] = dest._outerIndexPtr()[j] + count[j];
+ dest.outerIndexPtr()[j+1] = dest.outerIndexPtr()[j] + count[j];
for(Index j=0; j<size; ++j)
- count[j] = dest._outerIndexPtr()[j];
+ count[j] = dest.outerIndexPtr()[j];
// copy data
for(Index j = 0; j<size; ++j)
{
- Index jp = perm ? perm[j] : j;
for(typename MatrixType::InnerIterator it(mat,j); it; ++it)
{
Index i = it.index();
+ Index r = it.row();
+ Index c = it.col();
+
+ Index jp = perm ? perm[j] : j;
Index ip = perm ? perm[i] : i;
- if(i==j)
+
+ if(UpLo==(Upper|Lower))
+ {
+ Index k = count[StorageOrderMatch ? jp : ip]++;
+ dest.innerIndexPtr()[k] = StorageOrderMatch ? ip : jp;
+ dest.valuePtr()[k] = it.value();
+ }
+ else if(r==c)
{
- int k = count[ip]++;
- dest._innerIndexPtr()[k] = ip;
- dest._valuePtr()[k] = it.value();
+ Index k = count[ip]++;
+ dest.innerIndexPtr()[k] = ip;
+ dest.valuePtr()[k] = it.value();
}
- else if((UpLo==Lower && i>j) || (UpLo==Upper && i<j))
+ else if(( (UpLo&Lower)==Lower && r>c) || ( (UpLo&Upper)==Upper && r<c))
{
- int k = count[jp]++;
- dest._innerIndexPtr()[k] = ip;
- dest._valuePtr()[k] = it.value();
+ if(!StorageOrderMatch)
+ std::swap(ip,jp);
+ Index k = count[jp]++;
+ dest.innerIndexPtr()[k] = ip;
+ dest.valuePtr()[k] = it.value();
k = count[ip]++;
- dest._innerIndexPtr()[k] = jp;
- dest._valuePtr()[k] = internal::conj(it.value());
+ dest.innerIndexPtr()[k] = jp;
+ dest.valuePtr()[k] = internal::conj(it.value());
}
}
}
}
-template<int SrcUpLo,int DstUpLo,typename MatrixType,int DestOrder>
-void permute_symm_to_symm(const MatrixType& mat, SparseMatrix<typename MatrixType::Scalar,DestOrder,typename MatrixType::Index>& _dest, const typename MatrixType::Index* perm)
+template<int _SrcUpLo,int _DstUpLo,typename MatrixType,int DstOrder>
+void permute_symm_to_symm(const MatrixType& mat, SparseMatrix<typename MatrixType::Scalar,DstOrder,typename MatrixType::Index>& _dest, const typename MatrixType::Index* perm)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
- typedef SparseMatrix<Scalar,DestOrder,Index> Dest;
- Dest& dest(_dest.derived());
+ SparseMatrix<Scalar,DstOrder,Index>& dest(_dest.derived());
typedef Matrix<Index,Dynamic,1> VectorI;
- //internal::conj_if<SrcUpLo!=DstUpLo> cj;
+ enum {
+ SrcOrder = MatrixType::IsRowMajor ? RowMajor : ColMajor,
+ StorageOrderMatch = int(SrcOrder) == int(DstOrder),
+ DstUpLo = DstOrder==RowMajor ? (_DstUpLo==Upper ? Lower : Upper) : _DstUpLo,
+ SrcUpLo = SrcOrder==RowMajor ? (_SrcUpLo==Upper ? Lower : Upper) : _SrcUpLo
+ };
Index size = mat.rows();
VectorI count(size);
@@ -379,37 +397,40 @@ void permute_symm_to_symm(const MatrixType& mat, SparseMatrix<typename MatrixTyp
for(typename MatrixType::InnerIterator it(mat,j); it; ++it)
{
Index i = it.index();
- if((SrcUpLo==Lower && i<j) || (SrcUpLo==Upper && i>j))
+ if((int(SrcUpLo)==int(Lower) && i<j) || (int(SrcUpLo)==int(Upper) && i>j))
continue;
Index ip = perm ? perm[i] : i;
- count[DstUpLo==Lower ? (std::min)(ip,jp) : (std::max)(ip,jp)]++;
+ count[int(DstUpLo)==int(Lower) ? (std::min)(ip,jp) : (std::max)(ip,jp)]++;
}
}
- dest._outerIndexPtr()[0] = 0;
+ dest.outerIndexPtr()[0] = 0;
for(Index j=0; j<size; ++j)
- dest._outerIndexPtr()[j+1] = dest._outerIndexPtr()[j] + count[j];
- dest.resizeNonZeros(dest._outerIndexPtr()[size]);
+ dest.outerIndexPtr()[j+1] = dest.outerIndexPtr()[j] + count[j];
+ dest.resizeNonZeros(dest.outerIndexPtr()[size]);
for(Index j=0; j<size; ++j)
- count[j] = dest._outerIndexPtr()[j];
+ count[j] = dest.outerIndexPtr()[j];
for(Index j = 0; j<size; ++j)
{
- Index jp = perm ? perm[j] : j;
+
for(typename MatrixType::InnerIterator it(mat,j); it; ++it)
{
Index i = it.index();
- if((SrcUpLo==Lower && i<j) || (SrcUpLo==Upper && i>j))
+ if((int(SrcUpLo)==int(Lower) && i<j) || (int(SrcUpLo)==int(Upper) && i>j))
continue;
+ Index jp = perm ? perm[j] : j;
Index ip = perm? perm[i] : i;
- Index k = count[DstUpLo==Lower ? (std::min)(ip,jp) : (std::max)(ip,jp)]++;
- dest._innerIndexPtr()[k] = DstUpLo==Lower ? (std::max)(ip,jp) : (std::min)(ip,jp);
- if((DstUpLo==Lower && ip<jp) || (DstUpLo==Upper && ip>jp))
- dest._valuePtr()[k] = conj(it.value());
+ Index k = count[int(DstUpLo)==int(Lower) ? (std::min)(ip,jp) : (std::max)(ip,jp)]++;
+ dest.innerIndexPtr()[k] = int(DstUpLo)==int(Lower) ? (std::max)(ip,jp) : (std::min)(ip,jp);
+
+ if(!StorageOrderMatch) std::swap(ip,jp);
+ if( ((int(DstUpLo)==int(Lower) && ip<jp) || (int(DstUpLo)==int(Upper) && ip>jp)))
+ dest.valuePtr()[k] = conj(it.value());
else
- dest._valuePtr()[k] = it.value();
+ dest.valuePtr()[k] = it.value();
}
}
}
@@ -420,10 +441,12 @@ template<typename MatrixType,int UpLo>
class SparseSymmetricPermutationProduct
: public EigenBase<SparseSymmetricPermutationProduct<MatrixType,UpLo> >
{
- typedef PermutationMatrix<Dynamic> Perm;
public:
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::Index Index;
+ protected:
+ typedef PermutationMatrix<Dynamic,Dynamic,Index> Perm;
+ public:
typedef Matrix<Index,Dynamic,1> VectorI;
typedef typename MatrixType::Nested MatrixTypeNested;
typedef typename internal::remove_all<MatrixTypeNested>::type _MatrixTypeNested;
@@ -435,7 +458,8 @@ class SparseSymmetricPermutationProduct
inline Index rows() const { return m_matrix.rows(); }
inline Index cols() const { return m_matrix.cols(); }
- template<typename DestScalar> void evalTo(SparseMatrix<DestScalar>& _dest) const
+ template<typename DestScalar, int Options, typename DstIndex>
+ void evalTo(SparseMatrix<DestScalar,Options,DstIndex>& _dest) const
{
internal::permute_symm_to_fullsymm<UpLo>(m_matrix,_dest,m_perm.indices().data());
}
@@ -446,9 +470,11 @@ class SparseSymmetricPermutationProduct
}
protected:
- const MatrixTypeNested m_matrix;
+ MatrixTypeNested m_matrix;
const Perm& m_perm;
};
+} // end namespace Eigen
+
#endif // EIGEN_SPARSE_SELFADJOINTVIEW_H
diff --git a/extern/Eigen3/Eigen/src/SparseCore/SparseSparseProductWithPruning.h b/extern/Eigen3/Eigen/src/SparseCore/SparseSparseProductWithPruning.h
new file mode 100644
index 00000000000..2438ac573d0
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseSparseProductWithPruning.h
@@ -0,0 +1,149 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_SPARSESPARSEPRODUCTWITHPRUNING_H
+#define EIGEN_SPARSESPARSEPRODUCTWITHPRUNING_H
+
+namespace Eigen {
+
+namespace internal {
+
+
+// perform a pseudo in-place sparse * sparse product assuming all matrices are col major
+template<typename Lhs, typename Rhs, typename ResultType>
+static void sparse_sparse_product_with_pruning_impl(const Lhs& lhs, const Rhs& rhs, ResultType& res, typename ResultType::RealScalar tolerance)
+{
+ // return sparse_sparse_product_with_pruning_impl2(lhs,rhs,res);
+
+ typedef typename remove_all<Lhs>::type::Scalar Scalar;
+ typedef typename remove_all<Lhs>::type::Index Index;
+
+ // make sure to call innerSize/outerSize since we fake the storage order.
+ Index rows = lhs.innerSize();
+ Index cols = rhs.outerSize();
+ //int size = lhs.outerSize();
+ eigen_assert(lhs.outerSize() == rhs.innerSize());
+
+ // allocate a temporary buffer
+ AmbiVector<Scalar,Index> tempVector(rows);
+
+ // estimate the number of non zero entries
+ // given a rhs column containing Y non zeros, we assume that the respective Y columns
+ // of the lhs differs in average of one non zeros, thus the number of non zeros for
+ // the product of a rhs column with the lhs is X+Y where X is the average number of non zero
+ // per column of the lhs.
+ // Therefore, we have nnz(lhs*rhs) = nnz(lhs) + nnz(rhs)
+ Index estimated_nnz_prod = lhs.nonZeros() + rhs.nonZeros();
+
+ // mimics a resizeByInnerOuter:
+ if(ResultType::IsRowMajor)
+ res.resize(cols, rows);
+ else
+ res.resize(rows, cols);
+
+ res.reserve(estimated_nnz_prod);
+ double ratioColRes = double(estimated_nnz_prod)/double(lhs.rows()*rhs.cols());
+ for (Index j=0; j<cols; ++j)
+ {
+ // FIXME:
+ //double ratioColRes = (double(rhs.innerVector(j).nonZeros()) + double(lhs.nonZeros())/double(lhs.cols()))/double(lhs.rows());
+ // let's do a more accurate determination of the nnz ratio for the current column j of res
+ tempVector.init(ratioColRes);
+ tempVector.setZero();
+ for (typename Rhs::InnerIterator rhsIt(rhs, j); rhsIt; ++rhsIt)
+ {
+ // FIXME should be written like this: tmp += rhsIt.value() * lhs.col(rhsIt.index())
+ tempVector.restart();
+ Scalar x = rhsIt.value();
+ for (typename Lhs::InnerIterator lhsIt(lhs, rhsIt.index()); lhsIt; ++lhsIt)
+ {
+ tempVector.coeffRef(lhsIt.index()) += lhsIt.value() * x;
+ }
+ }
+ res.startVec(j);
+ for (typename AmbiVector<Scalar,Index>::Iterator it(tempVector,tolerance); it; ++it)
+ res.insertBackByOuterInner(j,it.index()) = it.value();
+ }
+ res.finalize();
+}
+
+template<typename Lhs, typename Rhs, typename ResultType,
+ int LhsStorageOrder = traits<Lhs>::Flags&RowMajorBit,
+ int RhsStorageOrder = traits<Rhs>::Flags&RowMajorBit,
+ int ResStorageOrder = traits<ResultType>::Flags&RowMajorBit>
+struct sparse_sparse_product_with_pruning_selector;
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,ColMajor,ColMajor,ColMajor>
+{
+ typedef typename traits<typename remove_all<Lhs>::type>::Scalar Scalar;
+ typedef typename ResultType::RealScalar RealScalar;
+
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, RealScalar tolerance)
+ {
+ typename remove_all<ResultType>::type _res(res.rows(), res.cols());
+ internal::sparse_sparse_product_with_pruning_impl<Lhs,Rhs,ResultType>(lhs, rhs, _res, tolerance);
+ res.swap(_res);
+ }
+};
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,ColMajor,ColMajor,RowMajor>
+{
+ typedef typename ResultType::RealScalar RealScalar;
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, RealScalar tolerance)
+ {
+ // we need a col-major matrix to hold the result
+ typedef SparseMatrix<typename ResultType::Scalar> SparseTemporaryType;
+ SparseTemporaryType _res(res.rows(), res.cols());
+ internal::sparse_sparse_product_with_pruning_impl<Lhs,Rhs,SparseTemporaryType>(lhs, rhs, _res, tolerance);
+ res = _res;
+ }
+};
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,RowMajor,RowMajor,RowMajor>
+{
+ typedef typename ResultType::RealScalar RealScalar;
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, RealScalar tolerance)
+ {
+ // let's transpose the product to get a column x column product
+ typename remove_all<ResultType>::type _res(res.rows(), res.cols());
+ internal::sparse_sparse_product_with_pruning_impl<Rhs,Lhs,ResultType>(rhs, lhs, _res, tolerance);
+ res.swap(_res);
+ }
+};
+
+template<typename Lhs, typename Rhs, typename ResultType>
+struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,RowMajor,RowMajor,ColMajor>
+{
+ typedef typename ResultType::RealScalar RealScalar;
+ static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, RealScalar tolerance)
+ {
+ typedef SparseMatrix<typename ResultType::Scalar,ColMajor> ColMajorMatrix;
+ ColMajorMatrix colLhs(lhs);
+ ColMajorMatrix colRhs(rhs);
+ internal::sparse_sparse_product_with_pruning_impl<ColMajorMatrix,ColMajorMatrix,ResultType>(colLhs, colRhs, res, tolerance);
+
+ // let's transpose the product to get a column x column product
+// typedef SparseMatrix<typename ResultType::Scalar> SparseTemporaryType;
+// SparseTemporaryType _res(res.cols(), res.rows());
+// sparse_sparse_product_with_pruning_impl<Rhs,Lhs,SparseTemporaryType>(rhs, lhs, _res);
+// res = _res.transpose();
+ }
+};
+
+// NOTE the 2 others cases (col row *) must never occur since they are caught
+// by ProductReturnType which transforms it to (col col *) by evaluating rhs.
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_SPARSESPARSEPRODUCTWITHPRUNING_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseTranspose.h b/extern/Eigen3/Eigen/src/SparseCore/SparseTranspose.h
index 2aea2fa32c7..273f9de688f 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseTranspose.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseTranspose.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSETRANSPOSE_H
#define EIGEN_SPARSETRANSPOSE_H
+namespace Eigen {
+
template<typename MatrixType> class TransposeImpl<MatrixType,Sparse>
: public SparseMatrixBase<Transpose<MatrixType> >
{
@@ -39,17 +26,21 @@ template<typename MatrixType> class TransposeImpl<MatrixType,Sparse>
inline Index nonZeros() const { return derived().nestedExpression().nonZeros(); }
};
+// NOTE: VC10 trigger an ICE if don't put typename TransposeImpl<MatrixType,Sparse>:: in front of Index,
+// a typedef typename TransposeImpl<MatrixType,Sparse>::Index Index;
+// does not fix the issue.
+// An alternative is to define the nested class in the parent class itself.
template<typename MatrixType> class TransposeImpl<MatrixType,Sparse>::InnerIterator
: public _MatrixTypeNested::InnerIterator
{
typedef typename _MatrixTypeNested::InnerIterator Base;
public:
- EIGEN_STRONG_INLINE InnerIterator(const TransposeImpl& trans, Index outer)
+ EIGEN_STRONG_INLINE InnerIterator(const TransposeImpl& trans, typename TransposeImpl<MatrixType,Sparse>::Index outer)
: Base(trans.derived().nestedExpression(), outer)
{}
- inline Index row() const { return Base::col(); }
- inline Index col() const { return Base::row(); }
+ inline typename TransposeImpl<MatrixType,Sparse>::Index row() const { return Base::col(); }
+ inline typename TransposeImpl<MatrixType,Sparse>::Index col() const { return Base::row(); }
};
template<typename MatrixType> class TransposeImpl<MatrixType,Sparse>::ReverseInnerIterator
@@ -58,11 +49,13 @@ template<typename MatrixType> class TransposeImpl<MatrixType,Sparse>::ReverseInn
typedef typename _MatrixTypeNested::ReverseInnerIterator Base;
public:
- EIGEN_STRONG_INLINE ReverseInnerIterator(const TransposeImpl& xpr, Index outer)
+ EIGEN_STRONG_INLINE ReverseInnerIterator(const TransposeImpl& xpr, typename TransposeImpl<MatrixType,Sparse>::Index outer)
: Base(xpr.derived().nestedExpression(), outer)
{}
- inline Index row() const { return Base::col(); }
- inline Index col() const { return Base::row(); }
+ inline typename TransposeImpl<MatrixType,Sparse>::Index row() const { return Base::col(); }
+ inline typename TransposeImpl<MatrixType,Sparse>::Index col() const { return Base::row(); }
};
+} // end namespace Eigen
+
#endif // EIGEN_SPARSETRANSPOSE_H
diff --git a/extern/Eigen3/Eigen/src/SparseCore/SparseTriangularView.h b/extern/Eigen3/Eigen/src/SparseCore/SparseTriangularView.h
new file mode 100644
index 00000000000..477e4bd94b0
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseTriangularView.h
@@ -0,0 +1,164 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_SPARSE_TRIANGULARVIEW_H
+#define EIGEN_SPARSE_TRIANGULARVIEW_H
+
+namespace Eigen {
+
+namespace internal {
+
+template<typename MatrixType, int Mode>
+struct traits<SparseTriangularView<MatrixType,Mode> >
+: public traits<MatrixType>
+{};
+
+} // namespace internal
+
+template<typename MatrixType, int Mode> class SparseTriangularView
+ : public SparseMatrixBase<SparseTriangularView<MatrixType,Mode> >
+{
+ enum { SkipFirst = ((Mode&Lower) && !(MatrixType::Flags&RowMajorBit))
+ || ((Mode&Upper) && (MatrixType::Flags&RowMajorBit)),
+ SkipLast = !SkipFirst,
+ HasUnitDiag = (Mode&UnitDiag) ? 1 : 0
+ };
+
+ public:
+
+ EIGEN_SPARSE_PUBLIC_INTERFACE(SparseTriangularView)
+
+ class InnerIterator;
+ class ReverseInnerIterator;
+
+ inline Index rows() const { return m_matrix.rows(); }
+ inline Index cols() const { return m_matrix.cols(); }
+
+ typedef typename MatrixType::Nested MatrixTypeNested;
+ typedef typename internal::remove_reference<MatrixTypeNested>::type MatrixTypeNestedNonRef;
+ typedef typename internal::remove_all<MatrixTypeNested>::type MatrixTypeNestedCleaned;
+
+ inline SparseTriangularView(const MatrixType& matrix) : m_matrix(matrix) {}
+
+ /** \internal */
+ inline const MatrixTypeNestedCleaned& nestedExpression() const { return m_matrix; }
+
+ template<typename OtherDerived>
+ typename internal::plain_matrix_type_column_major<OtherDerived>::type
+ solve(const MatrixBase<OtherDerived>& other) const;
+
+ template<typename OtherDerived> void solveInPlace(MatrixBase<OtherDerived>& other) const;
+ template<typename OtherDerived> void solveInPlace(SparseMatrixBase<OtherDerived>& other) const;
+
+ protected:
+ MatrixTypeNested m_matrix;
+};
+
+template<typename MatrixType, int Mode>
+class SparseTriangularView<MatrixType,Mode>::InnerIterator : public MatrixTypeNestedCleaned::InnerIterator
+{
+ typedef typename MatrixTypeNestedCleaned::InnerIterator Base;
+ public:
+
+ EIGEN_STRONG_INLINE InnerIterator(const SparseTriangularView& view, Index outer)
+ : Base(view.nestedExpression(), outer), m_returnOne(false)
+ {
+ if(SkipFirst)
+ {
+ while((*this) && (HasUnitDiag ? this->index()<=outer : this->index()<outer))
+ Base::operator++();
+ if(HasUnitDiag)
+ m_returnOne = true;
+ }
+ else if(HasUnitDiag && ((!Base::operator bool()) || Base::index()>=Base::outer()))
+ {
+ if((!SkipFirst) && Base::operator bool())
+ Base::operator++();
+ m_returnOne = true;
+ }
+ }
+
+ EIGEN_STRONG_INLINE InnerIterator& operator++()
+ {
+ if(HasUnitDiag && m_returnOne)
+ m_returnOne = false;
+ else
+ {
+ Base::operator++();
+ if(HasUnitDiag && (!SkipFirst) && ((!Base::operator bool()) || Base::index()>=Base::outer()))
+ {
+ if((!SkipFirst) && Base::operator bool())
+ Base::operator++();
+ m_returnOne = true;
+ }
+ }
+ return *this;
+ }
+
+ inline Index row() const { return Base::row(); }
+ inline Index col() const { return Base::col(); }
+ inline Index index() const
+ {
+ if(HasUnitDiag && m_returnOne) return Base::outer();
+ else return Base::index();
+ }
+ inline Scalar value() const
+ {
+ if(HasUnitDiag && m_returnOne) return Scalar(1);
+ else return Base::value();
+ }
+
+ EIGEN_STRONG_INLINE operator bool() const
+ {
+ if(HasUnitDiag && m_returnOne)
+ return true;
+ return (SkipFirst ? Base::operator bool() : (Base::operator bool() && this->index() <= this->outer()));
+ }
+ protected:
+ bool m_returnOne;
+};
+
+template<typename MatrixType, int Mode>
+class SparseTriangularView<MatrixType,Mode>::ReverseInnerIterator : public MatrixTypeNestedCleaned::ReverseInnerIterator
+{
+ typedef typename MatrixTypeNestedCleaned::ReverseInnerIterator Base;
+ public:
+
+ EIGEN_STRONG_INLINE ReverseInnerIterator(const SparseTriangularView& view, Index outer)
+ : Base(view.nestedExpression(), outer)
+ {
+ eigen_assert((!HasUnitDiag) && "ReverseInnerIterator does not support yet triangular views with a unit diagonal");
+ if(SkipLast)
+ while((*this) && this->index()>outer)
+ --(*this);
+ }
+
+ EIGEN_STRONG_INLINE InnerIterator& operator--()
+ { Base::operator--(); return *this; }
+
+ inline Index row() const { return Base::row(); }
+ inline Index col() const { return Base::col(); }
+
+ EIGEN_STRONG_INLINE operator bool() const
+ {
+ return SkipLast ? Base::operator bool() : (Base::operator bool() && this->index() >= this->outer());
+ }
+};
+
+template<typename Derived>
+template<int Mode>
+inline const SparseTriangularView<Derived, Mode>
+SparseMatrixBase<Derived>::triangularView() const
+{
+ return derived();
+}
+
+} // end namespace Eigen
+
+#endif // EIGEN_SPARSE_TRIANGULARVIEW_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseUtil.h b/extern/Eigen3/Eigen/src/SparseCore/SparseUtil.h
index db9ae98e7a0..6062a086ff7 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseUtil.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseUtil.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSEUTIL_H
#define EIGEN_SPARSEUTIL_H
+namespace Eigen {
+
#ifdef NDEBUG
#define EIGEN_DBG_SPARSE(X)
#else
@@ -58,22 +45,22 @@ EIGEN_SPARSE_INHERIT_SCALAR_ASSIGNMENT_OPERATOR(Derived, /=)
#define _EIGEN_SPARSE_PUBLIC_INTERFACE(Derived, BaseClass) \
typedef BaseClass Base; \
- typedef typename Eigen::internal::traits<Derived>::Scalar Scalar; \
+ typedef typename Eigen::internal::traits<Derived >::Scalar Scalar; \
typedef typename Eigen::NumTraits<Scalar>::Real RealScalar; \
- typedef typename Eigen::internal::nested<Derived>::type Nested; \
- typedef typename Eigen::internal::traits<Derived>::StorageKind StorageKind; \
- typedef typename Eigen::internal::traits<Derived>::Index Index; \
- enum { RowsAtCompileTime = Eigen::internal::traits<Derived>::RowsAtCompileTime, \
- ColsAtCompileTime = Eigen::internal::traits<Derived>::ColsAtCompileTime, \
- Flags = Eigen::internal::traits<Derived>::Flags, \
- CoeffReadCost = Eigen::internal::traits<Derived>::CoeffReadCost, \
+ typedef typename Eigen::internal::nested<Derived >::type Nested; \
+ typedef typename Eigen::internal::traits<Derived >::StorageKind StorageKind; \
+ typedef typename Eigen::internal::traits<Derived >::Index Index; \
+ enum { RowsAtCompileTime = Eigen::internal::traits<Derived >::RowsAtCompileTime, \
+ ColsAtCompileTime = Eigen::internal::traits<Derived >::ColsAtCompileTime, \
+ Flags = Eigen::internal::traits<Derived >::Flags, \
+ CoeffReadCost = Eigen::internal::traits<Derived >::CoeffReadCost, \
SizeAtCompileTime = Base::SizeAtCompileTime, \
IsVectorAtCompileTime = Base::IsVectorAtCompileTime }; \
using Base::derived; \
using Base::const_cast_derived;
#define EIGEN_SPARSE_PUBLIC_INTERFACE(Derived) \
- _EIGEN_SPARSE_PUBLIC_INTERFACE(Derived, Eigen::SparseMatrixBase<Derived>)
+ _EIGEN_SPARSE_PUBLIC_INTERFACE(Derived, Eigen::SparseMatrixBase<Derived >)
const int CoherentAccessPattern = 0x1;
const int InnerRandomAccessPattern = 0x2 | CoherentAccessPattern;
@@ -100,20 +87,43 @@ template<typename Lhs, typename Rhs, bool Transpose> class SparseDenseOuterProdu
template<typename Lhs, typename Rhs> struct SparseSparseProductReturnType;
template<typename Lhs, typename Rhs, int InnerSize = internal::traits<Lhs>::ColsAtCompileTime> struct DenseSparseProductReturnType;
template<typename Lhs, typename Rhs, int InnerSize = internal::traits<Lhs>::ColsAtCompileTime> struct SparseDenseProductReturnType;
+template<typename MatrixType,int UpLo> class SparseSymmetricPermutationProduct;
namespace internal {
+template<typename T,int Rows,int Cols> struct sparse_eval;
+
template<typename T> struct eval<T,Sparse>
-{
+ : public sparse_eval<T, traits<T>::RowsAtCompileTime,traits<T>::ColsAtCompileTime>
+{};
+
+template<typename T,int Cols> struct sparse_eval<T,1,Cols> {
typedef typename traits<T>::Scalar _Scalar;
- enum {
- _Flags = traits<T>::Flags
- };
+ enum { _Flags = traits<T>::Flags| RowMajorBit };
+ public:
+ typedef SparseVector<_Scalar, _Flags> type;
+};
+template<typename T,int Rows> struct sparse_eval<T,Rows,1> {
+ typedef typename traits<T>::Scalar _Scalar;
+ enum { _Flags = traits<T>::Flags & (~RowMajorBit) };
+ public:
+ typedef SparseVector<_Scalar, _Flags> type;
+};
+
+template<typename T,int Rows,int Cols> struct sparse_eval {
+ typedef typename traits<T>::Scalar _Scalar;
+ enum { _Flags = traits<T>::Flags };
public:
typedef SparseMatrix<_Scalar, _Flags> type;
};
+template<typename T> struct sparse_eval<T,1,1> {
+ typedef typename traits<T>::Scalar _Scalar;
+ public:
+ typedef Matrix<_Scalar, 1, 1> type;
+};
+
template<typename T> struct plain_matrix_type<T,Sparse>
{
typedef typename traits<T>::Scalar _Scalar;
@@ -127,4 +137,37 @@ template<typename T> struct plain_matrix_type<T,Sparse>
} // end namespace internal
+/** \ingroup SparseCore_Module
+ *
+ * \class Triplet
+ *
+ * \brief A small structure to hold a non zero as a triplet (i,j,value).
+ *
+ * \sa SparseMatrix::setFromTriplets()
+ */
+template<typename Scalar, typename Index=unsigned int>
+class Triplet
+{
+public:
+ Triplet() : m_row(0), m_col(0), m_value(0) {}
+
+ Triplet(const Index& i, const Index& j, const Scalar& v = Scalar(0))
+ : m_row(i), m_col(j), m_value(v)
+ {}
+
+ /** \returns the row index of the element */
+ const Index& row() const { return m_row; }
+
+ /** \returns the column index of the element */
+ const Index& col() const { return m_col; }
+
+ /** \returns the value of the element */
+ const Scalar& value() const { return m_value; }
+protected:
+ Index m_row, m_col;
+ Scalar m_value;
+};
+
+} // end namespace Eigen
+
#endif // EIGEN_SPARSEUTIL_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseVector.h b/extern/Eigen3/Eigen/src/SparseCore/SparseVector.h
index ce4bb51a27e..c952f654038 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseVector.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseVector.h
@@ -3,29 +3,17 @@
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSEVECTOR_H
#define EIGEN_SPARSEVECTOR_H
-/** \class SparseVector
+namespace Eigen {
+
+/** \ingroup SparseCore_Module
+ * \class SparseVector
*
* \brief a sparse vector class
*
@@ -46,13 +34,13 @@ struct traits<SparseVector<_Scalar, _Options, _Index> >
typedef Sparse StorageKind;
typedef MatrixXpr XprKind;
enum {
- IsColVector = _Options & RowMajorBit ? 0 : 1,
+ IsColVector = (_Options & RowMajorBit) ? 0 : 1,
RowsAtCompileTime = IsColVector ? Dynamic : 1,
ColsAtCompileTime = IsColVector ? 1 : Dynamic,
MaxRowsAtCompileTime = RowsAtCompileTime,
MaxColsAtCompileTime = ColsAtCompileTime,
- Flags = _Options | NestByRefBit | LvalueBit,
+ Flags = _Options | NestByRefBit | LvalueBit | (IsColVector ? 0 : RowMajorBit),
CoeffReadCost = NumTraits<Scalar>::ReadCost,
SupportedAccessPatterns = InnerRandomAccessPattern
};
@@ -67,7 +55,6 @@ class SparseVector
EIGEN_SPARSE_PUBLIC_INTERFACE(SparseVector)
EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(SparseVector, +=)
EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(SparseVector, -=)
-// EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(SparseVector, =)
protected:
public:
@@ -79,11 +66,11 @@ class SparseVector
Options = _Options
};
- CompressedStorage<Scalar,Index> m_data;
+ internal::CompressedStorage<Scalar,Index> m_data;
Index m_size;
- CompressedStorage<Scalar,Index>& _data() { return m_data; }
- CompressedStorage<Scalar,Index>& _data() const { return m_data; }
+ internal::CompressedStorage<Scalar,Index>& _data() { return m_data; }
+ internal::CompressedStorage<Scalar,Index>& _data() const { return m_data; }
public:
@@ -91,13 +78,12 @@ class SparseVector
EIGEN_STRONG_INLINE Index cols() const { return IsColVector ? 1 : m_size; }
EIGEN_STRONG_INLINE Index innerSize() const { return m_size; }
EIGEN_STRONG_INLINE Index outerSize() const { return 1; }
- EIGEN_STRONG_INLINE Index innerNonZeros(Index j) const { eigen_assert(j==0); return m_size; }
- EIGEN_STRONG_INLINE const Scalar* _valuePtr() const { return &m_data.value(0); }
- EIGEN_STRONG_INLINE Scalar* _valuePtr() { return &m_data.value(0); }
+ EIGEN_STRONG_INLINE const Scalar* valuePtr() const { return &m_data.value(0); }
+ EIGEN_STRONG_INLINE Scalar* valuePtr() { return &m_data.value(0); }
- EIGEN_STRONG_INLINE const Index* _innerIndexPtr() const { return &m_data.index(0); }
- EIGEN_STRONG_INLINE Index* _innerIndexPtr() { return &m_data.index(0); }
+ EIGEN_STRONG_INLINE const Index* innerIndexPtr() const { return &m_data.index(0); }
+ EIGEN_STRONG_INLINE Index* innerIndexPtr() { return &m_data.index(0); }
inline Scalar coeff(Index row, Index col) const
{
@@ -126,6 +112,7 @@ class SparseVector
public:
class InnerIterator;
+ class ReverseInnerIterator;
inline void setZero() { m_data.clear(); }
@@ -134,11 +121,13 @@ class SparseVector
inline void startVec(Index outer)
{
+ EIGEN_UNUSED_VARIABLE(outer);
eigen_assert(outer==0);
}
inline Scalar& insertBackByOuterInner(Index outer, Index inner)
{
+ EIGEN_UNUSED_VARIABLE(outer);
eigen_assert(outer==0);
return insertBack(inner);
}
@@ -158,7 +147,7 @@ class SparseVector
Scalar& insert(Index i)
{
Index startId = 0;
- Index p = m_data.size() - 1;
+ Index p = Index(m_data.size()) - 1;
// TODO smart realloc
m_data.resize(p+2,1);
@@ -206,13 +195,6 @@ class SparseVector
inline SparseVector(Index rows, Index cols) : m_size(0) { resize(rows,cols); }
template<typename OtherDerived>
- inline SparseVector(const MatrixBase<OtherDerived>& other)
- : m_size(0)
- {
- *this = other.derived();
- }
-
- template<typename OtherDerived>
inline SparseVector(const SparseMatrixBase<OtherDerived>& other)
: m_size(0)
{
@@ -249,9 +231,9 @@ class SparseVector
inline SparseVector& operator=(const SparseMatrixBase<OtherDerived>& other)
{
if (int(RowsAtCompileTime)!=int(OtherDerived::RowsAtCompileTime))
- return Base::operator=(other.transpose());
+ return assign(other.transpose());
else
- return Base::operator=(other);
+ return assign(other);
}
#ifndef EIGEN_PARSED_BY_DOXYGEN
@@ -262,56 +244,6 @@ class SparseVector
}
#endif
-// const bool needToTranspose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit);
-// if (needToTranspose)
-// {
-// // two passes algorithm:
-// // 1 - compute the number of coeffs per dest inner vector
-// // 2 - do the actual copy/eval
-// // Since each coeff of the rhs has to be evaluated twice, let's evauluate it if needed
-// typedef typename internal::nested<OtherDerived,2>::type OtherCopy;
-// OtherCopy otherCopy(other.derived());
-// typedef typename internal::remove_all<OtherCopy>::type _OtherCopy;
-//
-// resize(other.rows(), other.cols());
-// Eigen::Map<VectorXi>(m_outerIndex,outerSize()).setZero();
-// // pass 1
-// // FIXME the above copy could be merged with that pass
-// for (int j=0; j<otherCopy.outerSize(); ++j)
-// for (typename _OtherCopy::InnerIterator it(otherCopy, j); it; ++it)
-// ++m_outerIndex[it.index()];
-//
-// // prefix sum
-// int count = 0;
-// VectorXi positions(outerSize());
-// for (int j=0; j<outerSize(); ++j)
-// {
-// int tmp = m_outerIndex[j];
-// m_outerIndex[j] = count;
-// positions[j] = count;
-// count += tmp;
-// }
-// m_outerIndex[outerSize()] = count;
-// // alloc
-// m_data.resize(count);
-// // pass 2
-// for (int j=0; j<otherCopy.outerSize(); ++j)
-// for (typename _OtherCopy::InnerIterator it(otherCopy, j); it; ++it)
-// {
-// int pos = positions[it.index()]++;
-// m_data.index(pos) = j;
-// m_data.value(pos) = it.value();
-// }
-//
-// return *this;
-// }
-// else
-// {
-// // there is no special optimization
-// return SparseMatrixBase<SparseMatrix>::operator=(other.derived());
-// }
-// }
-
friend std::ostream & operator << (std::ostream & s, const SparseVector& m)
{
for (Index i=0; i<m.nonZeros(); ++i)
@@ -320,28 +252,6 @@ class SparseVector
return s;
}
- // this specialized version does not seems to be faster
-// Scalar dot(const SparseVector& other) const
-// {
-// int i=0, j=0;
-// Scalar res = 0;
-// asm("#begindot");
-// while (i<nonZeros() && j<other.nonZeros())
-// {
-// if (m_data.index(i)==other.m_data.index(j))
-// {
-// res += m_data.value(i) * internal::conj(other.m_data.value(j));
-// ++i; ++j;
-// }
-// else if (m_data.index(i)<other.m_data.index(j))
-// ++i;
-// else
-// ++j;
-// }
-// asm("#enddot");
-// return res;
-// }
-
/** Destructor */
inline ~SparseVector() {}
@@ -390,6 +300,33 @@ class SparseVector
# ifdef EIGEN_SPARSEVECTOR_PLUGIN
# include EIGEN_SPARSEVECTOR_PLUGIN
# endif
+
+protected:
+ template<typename OtherDerived>
+ EIGEN_DONT_INLINE SparseVector& assign(const SparseMatrixBase<OtherDerived>& _other)
+ {
+ const OtherDerived& other(_other.derived());
+ const bool needToTranspose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit);
+ if(needToTranspose)
+ {
+ Index size = other.size();
+ Index nnz = other.nonZeros();
+ resize(size);
+ reserve(nnz);
+ for(Index i=0; i<size; ++i)
+ {
+ typename OtherDerived::InnerIterator it(other, i);
+ if(it)
+ insert(i) = it.value();
+ }
+ return *this;
+ }
+ else
+ {
+ // there is no special optimization
+ return Base::operator=(other);
+ }
+ }
};
template<typename Scalar, int _Options, typename _Index>
@@ -399,18 +336,14 @@ class SparseVector<Scalar,_Options,_Index>::InnerIterator
InnerIterator(const SparseVector& vec, Index outer=0)
: m_data(vec.m_data), m_id(0), m_end(static_cast<Index>(m_data.size()))
{
+ EIGEN_UNUSED_VARIABLE(outer);
eigen_assert(outer==0);
}
- InnerIterator(const CompressedStorage<Scalar,Index>& data)
+ InnerIterator(const internal::CompressedStorage<Scalar,Index>& data)
: m_data(data), m_id(0), m_end(static_cast<Index>(m_data.size()))
{}
- template<unsigned int Added, unsigned int Removed>
- InnerIterator(const Flagged<SparseVector,Added,Removed>& vec, Index )
- : m_data(vec._expression().m_data), m_id(0), m_end(m_data.size())
- {}
-
inline InnerIterator& operator++() { m_id++; return *this; }
inline Scalar value() const { return m_data.value(m_id); }
@@ -423,9 +356,43 @@ class SparseVector<Scalar,_Options,_Index>::InnerIterator
inline operator bool() const { return (m_id < m_end); }
protected:
- const CompressedStorage<Scalar,Index>& m_data;
+ const internal::CompressedStorage<Scalar,Index>& m_data;
Index m_id;
const Index m_end;
};
+template<typename Scalar, int _Options, typename _Index>
+class SparseVector<Scalar,_Options,_Index>::ReverseInnerIterator
+{
+ public:
+ ReverseInnerIterator(const SparseVector& vec, Index outer=0)
+ : m_data(vec.m_data), m_id(static_cast<Index>(m_data.size())), m_start(0)
+ {
+ EIGEN_UNUSED_VARIABLE(outer);
+ eigen_assert(outer==0);
+ }
+
+ ReverseInnerIterator(const internal::CompressedStorage<Scalar,Index>& data)
+ : m_data(data), m_id(static_cast<Index>(m_data.size())), m_start(0)
+ {}
+
+ inline ReverseInnerIterator& operator--() { m_id--; return *this; }
+
+ inline Scalar value() const { return m_data.value(m_id-1); }
+ inline Scalar& valueRef() { return const_cast<Scalar&>(m_data.value(m_id-1)); }
+
+ inline Index index() const { return m_data.index(m_id-1); }
+ inline Index row() const { return IsColVector ? index() : 0; }
+ inline Index col() const { return IsColVector ? 0 : index(); }
+
+ inline operator bool() const { return (m_id > m_start); }
+
+ protected:
+ const internal::CompressedStorage<Scalar,Index>& m_data;
+ Index m_id;
+ const Index m_start;
+};
+
+} // end namespace Eigen
+
#endif // EIGEN_SPARSEVECTOR_H
diff --git a/extern/Eigen3/Eigen/src/Sparse/SparseView.h b/extern/Eigen3/Eigen/src/SparseCore/SparseView.h
index 24306561098..8b0b9ea0304 100644
--- a/extern/Eigen3/Eigen/src/Sparse/SparseView.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/SparseView.h
@@ -1,31 +1,18 @@
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
-// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
+// Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010 Daniel Lowengrub <lowdanie@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSEVIEW_H
#define EIGEN_SPARSEVIEW_H
+namespace Eigen {
+
namespace internal {
template<typename MatrixType>
@@ -61,7 +48,7 @@ public:
inline Index outerSize() const { return m_matrix.outerSize(); }
protected:
- const MatrixTypeNested m_matrix;
+ MatrixTypeNested m_matrix;
Scalar m_reference;
typename NumTraits<Scalar>::Real m_epsilon;
};
@@ -92,10 +79,10 @@ protected:
private:
void incrementToNonZero()
{
- while(internal::isMuchSmallerThan(value(), m_view.m_reference, m_view.m_epsilon) && (bool(*this)))
- {
- IterBase::operator++();
- }
+ while((bool(*this)) && internal::isMuchSmallerThan(value(), m_view.m_reference, m_view.m_epsilon))
+ {
+ IterBase::operator++();
+ }
}
};
@@ -106,4 +93,6 @@ const SparseView<Derived> MatrixBase<Derived>::sparseView(const Scalar& m_refere
return SparseView<Derived>(derived(), m_reference, m_epsilon);
}
+} // end namespace Eigen
+
#endif
diff --git a/extern/Eigen3/Eigen/src/Sparse/TriangularSolver.h b/extern/Eigen3/Eigen/src/SparseCore/TriangularSolver.h
index 62bb8bb44c9..cb8ad82b4f6 100644
--- a/extern/Eigen3/Eigen/src/Sparse/TriangularSolver.h
+++ b/extern/Eigen3/Eigen/src/SparseCore/TriangularSolver.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSETRIANGULARSOLVER_H
#define EIGEN_SPARSETRIANGULARSOLVER_H
+namespace Eigen {
+
namespace internal {
template<typename Lhs, typename Rhs, int Mode,
@@ -48,7 +35,7 @@ struct sparse_solve_triangular_selector<Lhs,Rhs,Mode,Lower,RowMajor>
for(int i=0; i<lhs.rows(); ++i)
{
Scalar tmp = other.coeff(i,col);
- Scalar lastVal = 0;
+ Scalar lastVal(0);
int lastIndex = 0;
for(typename Lhs::InnerIterator it(lhs, i); it; ++it)
{
@@ -82,8 +69,17 @@ struct sparse_solve_triangular_selector<Lhs,Rhs,Mode,Upper,RowMajor>
for(int i=lhs.rows()-1 ; i>=0 ; --i)
{
Scalar tmp = other.coeff(i,col);
+ Scalar l_ii = 0;
typename Lhs::InnerIterator it(lhs, i);
- if (it && it.index() == i)
+ while(it && it.index()<i)
+ ++it;
+ if(!(Mode & UnitDiag))
+ {
+ eigen_assert(it && it.index()==i);
+ l_ii = it.value();
+ ++it;
+ }
+ else if (it && it.index() == i)
++it;
for(; it; ++it)
{
@@ -93,11 +89,7 @@ struct sparse_solve_triangular_selector<Lhs,Rhs,Mode,Upper,RowMajor>
if (Mode & UnitDiag)
other.coeffRef(i,col) = tmp;
else
- {
- typename Lhs::InnerIterator it(lhs, i);
- eigen_assert(it && it.index() == i);
- other.coeffRef(i,col) = tmp/it.value();
- }
+ other.coeffRef(i,col) = tmp/l_ii;
}
}
}
@@ -118,9 +110,11 @@ struct sparse_solve_triangular_selector<Lhs,Rhs,Mode,Lower,ColMajor>
if (tmp!=Scalar(0)) // optimization when other is actually sparse
{
typename Lhs::InnerIterator it(lhs, i);
+ while(it && it.index()<i)
+ ++it;
if(!(Mode & UnitDiag))
{
- eigen_assert(it.index()==i);
+ eigen_assert(it && it.index()==i);
tmp /= it.value();
}
if (it && it.index()==i)
@@ -149,9 +143,12 @@ struct sparse_solve_triangular_selector<Lhs,Rhs,Mode,Upper,ColMajor>
{
if(!(Mode & UnitDiag))
{
- // FIXME lhs.coeff(i,i) might not be always efficient while it must simply be the
- // last element of the column !
- other.coeffRef(i,col) /= lhs.innerVector(i).lastCoeff();
+ // TODO replace this by a binary search. make sure the binary search is safe for partially sorted elements
+ typename Lhs::ReverseInnerIterator it(lhs, i);
+ while(it && it.index()!=i)
+ --it;
+ eigen_assert(it && it.index()==i);
+ other.coeffRef(i,col) /= it.value();
}
typename Lhs::InnerIterator it(lhs, i);
for(; it && it.index()<i; ++it)
@@ -168,10 +165,8 @@ template<typename ExpressionType,int Mode>
template<typename OtherDerived>
void SparseTriangularView<ExpressionType,Mode>::solveInPlace(MatrixBase<OtherDerived>& other) const
{
- eigen_assert(m_matrix.cols() == m_matrix.rows());
- eigen_assert(m_matrix.cols() == other.rows());
- eigen_assert(!(Mode & ZeroDiag));
- eigen_assert((Mode & (Upper|Lower)) != 0);
+ eigen_assert(m_matrix.cols() == m_matrix.rows() && m_matrix.cols() == other.rows());
+ eigen_assert((!(Mode & ZeroDiag)) && bool(Mode & (Upper|Lower)));
enum { copy = internal::traits<OtherDerived>::Flags & RowMajorBit };
@@ -295,10 +290,8 @@ template<typename ExpressionType,int Mode>
template<typename OtherDerived>
void SparseTriangularView<ExpressionType,Mode>::solveInPlace(SparseMatrixBase<OtherDerived>& other) const
{
- eigen_assert(m_matrix.cols() == m_matrix.rows());
- eigen_assert(m_matrix.cols() == other.rows());
- eigen_assert(!(Mode & ZeroDiag));
- eigen_assert((Mode & (Upper|Lower)) != 0);
+ eigen_assert(m_matrix.cols() == m_matrix.rows() && m_matrix.cols() == other.rows());
+ eigen_assert( (!(Mode & ZeroDiag)) && bool(Mode & (Upper|Lower)));
// enum { copy = internal::traits<OtherDerived>::Flags & RowMajorBit };
@@ -336,4 +329,6 @@ SparseMatrixBase<Derived>::solveTriangular(const MatrixBase<OtherDerived>& other
}
#endif // EIGEN2_SUPPORT
+} // end namespace Eigen
+
#endif // EIGEN_SPARSETRIANGULARSOLVER_H
diff --git a/extern/Eigen3/Eigen/src/StlSupport/StdDeque.h b/extern/Eigen3/Eigen/src/StlSupport/StdDeque.h
index 6f12c106dbc..4ee8e5c10a5 100644
--- a/extern/Eigen3/Eigen/src/StlSupport/StdDeque.h
+++ b/extern/Eigen3/Eigen/src/StlSupport/StdDeque.h
@@ -4,24 +4,9 @@
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Hauke Heibel <hauke.heibel@googlemail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STDDEQUE_H
#define EIGEN_STDDEQUE_H
diff --git a/extern/Eigen3/Eigen/src/StlSupport/StdList.h b/extern/Eigen3/Eigen/src/StlSupport/StdList.h
index d329a0b2dc5..627381ecec0 100644
--- a/extern/Eigen3/Eigen/src/StlSupport/StdList.h
+++ b/extern/Eigen3/Eigen/src/StlSupport/StdList.h
@@ -3,24 +3,9 @@
//
// Copyright (C) 2009 Hauke Heibel <hauke.heibel@googlemail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STDLIST_H
#define EIGEN_STDLIST_H
diff --git a/extern/Eigen3/Eigen/src/StlSupport/StdVector.h b/extern/Eigen3/Eigen/src/StlSupport/StdVector.h
index 27d6ab539f9..40a9abefa82 100644
--- a/extern/Eigen3/Eigen/src/StlSupport/StdVector.h
+++ b/extern/Eigen3/Eigen/src/StlSupport/StdVector.h
@@ -4,24 +4,9 @@
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Hauke Heibel <hauke.heibel@googlemail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STDVECTOR_H
#define EIGEN_STDVECTOR_H
diff --git a/extern/Eigen3/Eigen/src/StlSupport/details.h b/extern/Eigen3/Eigen/src/StlSupport/details.h
index 397c8ef8581..d8debc7c4f8 100644
--- a/extern/Eigen3/Eigen/src/StlSupport/details.h
+++ b/extern/Eigen3/Eigen/src/StlSupport/details.h
@@ -4,24 +4,9 @@
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Hauke Heibel <hauke.heibel@googlemail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STL_DETAILS_H
#define EIGEN_STL_DETAILS_H
diff --git a/extern/Eigen3/Eigen/src/SuperLUSupport/SuperLUSupport.h b/extern/Eigen3/Eigen/src/SuperLUSupport/SuperLUSupport.h
new file mode 100644
index 00000000000..11fb014dd93
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/SuperLUSupport/SuperLUSupport.h
@@ -0,0 +1,1025 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_SUPERLUSUPPORT_H
+#define EIGEN_SUPERLUSUPPORT_H
+
+namespace Eigen {
+
+#define DECL_GSSVX(PREFIX,FLOATTYPE,KEYTYPE) \
+ extern "C" { \
+ typedef struct { FLOATTYPE for_lu; FLOATTYPE total_needed; int expansions; } PREFIX##mem_usage_t; \
+ extern void PREFIX##gssvx(superlu_options_t *, SuperMatrix *, int *, int *, int *, \
+ char *, FLOATTYPE *, FLOATTYPE *, SuperMatrix *, SuperMatrix *, \
+ void *, int, SuperMatrix *, SuperMatrix *, \
+ FLOATTYPE *, FLOATTYPE *, FLOATTYPE *, FLOATTYPE *, \
+ PREFIX##mem_usage_t *, SuperLUStat_t *, int *); \
+ } \
+ inline float SuperLU_gssvx(superlu_options_t *options, SuperMatrix *A, \
+ int *perm_c, int *perm_r, int *etree, char *equed, \
+ FLOATTYPE *R, FLOATTYPE *C, SuperMatrix *L, \
+ SuperMatrix *U, void *work, int lwork, \
+ SuperMatrix *B, SuperMatrix *X, \
+ FLOATTYPE *recip_pivot_growth, \
+ FLOATTYPE *rcond, FLOATTYPE *ferr, FLOATTYPE *berr, \
+ SuperLUStat_t *stats, int *info, KEYTYPE) { \
+ PREFIX##mem_usage_t mem_usage; \
+ PREFIX##gssvx(options, A, perm_c, perm_r, etree, equed, R, C, L, \
+ U, work, lwork, B, X, recip_pivot_growth, rcond, \
+ ferr, berr, &mem_usage, stats, info); \
+ return mem_usage.for_lu; /* bytes used by the factor storage */ \
+ }
+
+DECL_GSSVX(s,float,float)
+DECL_GSSVX(c,float,std::complex<float>)
+DECL_GSSVX(d,double,double)
+DECL_GSSVX(z,double,std::complex<double>)
+
+#ifdef MILU_ALPHA
+#define EIGEN_SUPERLU_HAS_ILU
+#endif
+
+#ifdef EIGEN_SUPERLU_HAS_ILU
+
+// similarly for the incomplete factorization using gsisx
+#define DECL_GSISX(PREFIX,FLOATTYPE,KEYTYPE) \
+ extern "C" { \
+ extern void PREFIX##gsisx(superlu_options_t *, SuperMatrix *, int *, int *, int *, \
+ char *, FLOATTYPE *, FLOATTYPE *, SuperMatrix *, SuperMatrix *, \
+ void *, int, SuperMatrix *, SuperMatrix *, FLOATTYPE *, FLOATTYPE *, \
+ PREFIX##mem_usage_t *, SuperLUStat_t *, int *); \
+ } \
+ inline float SuperLU_gsisx(superlu_options_t *options, SuperMatrix *A, \
+ int *perm_c, int *perm_r, int *etree, char *equed, \
+ FLOATTYPE *R, FLOATTYPE *C, SuperMatrix *L, \
+ SuperMatrix *U, void *work, int lwork, \
+ SuperMatrix *B, SuperMatrix *X, \
+ FLOATTYPE *recip_pivot_growth, \
+ FLOATTYPE *rcond, \
+ SuperLUStat_t *stats, int *info, KEYTYPE) { \
+ PREFIX##mem_usage_t mem_usage; \
+ PREFIX##gsisx(options, A, perm_c, perm_r, etree, equed, R, C, L, \
+ U, work, lwork, B, X, recip_pivot_growth, rcond, \
+ &mem_usage, stats, info); \
+ return mem_usage.for_lu; /* bytes used by the factor storage */ \
+ }
+
+DECL_GSISX(s,float,float)
+DECL_GSISX(c,float,std::complex<float>)
+DECL_GSISX(d,double,double)
+DECL_GSISX(z,double,std::complex<double>)
+
+#endif
+
+template<typename MatrixType>
+struct SluMatrixMapHelper;
+
+/** \internal
+ *
+ * A wrapper class for SuperLU matrices. It supports only compressed sparse matrices
+ * and dense matrices. Supernodal and other fancy format are not supported by this wrapper.
+ *
+ * This wrapper class mainly aims to avoids the need of dynamic allocation of the storage structure.
+ */
+struct SluMatrix : SuperMatrix
+{
+ SluMatrix()
+ {
+ Store = &storage;
+ }
+
+ SluMatrix(const SluMatrix& other)
+ : SuperMatrix(other)
+ {
+ Store = &storage;
+ storage = other.storage;
+ }
+
+ SluMatrix& operator=(const SluMatrix& other)
+ {
+ SuperMatrix::operator=(static_cast<const SuperMatrix&>(other));
+ Store = &storage;
+ storage = other.storage;
+ return *this;
+ }
+
+ struct
+ {
+ union {int nnz;int lda;};
+ void *values;
+ int *innerInd;
+ int *outerInd;
+ } storage;
+
+ void setStorageType(Stype_t t)
+ {
+ Stype = t;
+ if (t==SLU_NC || t==SLU_NR || t==SLU_DN)
+ Store = &storage;
+ else
+ {
+ eigen_assert(false && "storage type not supported");
+ Store = 0;
+ }
+ }
+
+ template<typename Scalar>
+ void setScalarType()
+ {
+ if (internal::is_same<Scalar,float>::value)
+ Dtype = SLU_S;
+ else if (internal::is_same<Scalar,double>::value)
+ Dtype = SLU_D;
+ else if (internal::is_same<Scalar,std::complex<float> >::value)
+ Dtype = SLU_C;
+ else if (internal::is_same<Scalar,std::complex<double> >::value)
+ Dtype = SLU_Z;
+ else
+ {
+ eigen_assert(false && "Scalar type not supported by SuperLU");
+ }
+ }
+
+ template<typename MatrixType>
+ static SluMatrix Map(MatrixBase<MatrixType>& _mat)
+ {
+ MatrixType& mat(_mat.derived());
+ eigen_assert( ((MatrixType::Flags&RowMajorBit)!=RowMajorBit) && "row-major dense matrices are not supported by SuperLU");
+ SluMatrix res;
+ res.setStorageType(SLU_DN);
+ res.setScalarType<typename MatrixType::Scalar>();
+ res.Mtype = SLU_GE;
+
+ res.nrow = mat.rows();
+ res.ncol = mat.cols();
+
+ res.storage.lda = MatrixType::IsVectorAtCompileTime ? mat.size() : mat.outerStride();
+ res.storage.values = mat.data();
+ return res;
+ }
+
+ template<typename MatrixType>
+ static SluMatrix Map(SparseMatrixBase<MatrixType>& mat)
+ {
+ SluMatrix res;
+ if ((MatrixType::Flags&RowMajorBit)==RowMajorBit)
+ {
+ res.setStorageType(SLU_NR);
+ res.nrow = mat.cols();
+ res.ncol = mat.rows();
+ }
+ else
+ {
+ res.setStorageType(SLU_NC);
+ res.nrow = mat.rows();
+ res.ncol = mat.cols();
+ }
+
+ res.Mtype = SLU_GE;
+
+ res.storage.nnz = mat.nonZeros();
+ res.storage.values = mat.derived().valuePtr();
+ res.storage.innerInd = mat.derived().innerIndexPtr();
+ res.storage.outerInd = mat.derived().outerIndexPtr();
+
+ res.setScalarType<typename MatrixType::Scalar>();
+
+ // FIXME the following is not very accurate
+ if (MatrixType::Flags & Upper)
+ res.Mtype = SLU_TRU;
+ if (MatrixType::Flags & Lower)
+ res.Mtype = SLU_TRL;
+
+ eigen_assert(((MatrixType::Flags & SelfAdjoint)==0) && "SelfAdjoint matrix shape not supported by SuperLU");
+
+ return res;
+ }
+};
+
+template<typename Scalar, int Rows, int Cols, int Options, int MRows, int MCols>
+struct SluMatrixMapHelper<Matrix<Scalar,Rows,Cols,Options,MRows,MCols> >
+{
+ typedef Matrix<Scalar,Rows,Cols,Options,MRows,MCols> MatrixType;
+ static void run(MatrixType& mat, SluMatrix& res)
+ {
+ eigen_assert( ((Options&RowMajor)!=RowMajor) && "row-major dense matrices is not supported by SuperLU");
+ res.setStorageType(SLU_DN);
+ res.setScalarType<Scalar>();
+ res.Mtype = SLU_GE;
+
+ res.nrow = mat.rows();
+ res.ncol = mat.cols();
+
+ res.storage.lda = mat.outerStride();
+ res.storage.values = mat.data();
+ }
+};
+
+template<typename Derived>
+struct SluMatrixMapHelper<SparseMatrixBase<Derived> >
+{
+ typedef Derived MatrixType;
+ static void run(MatrixType& mat, SluMatrix& res)
+ {
+ if ((MatrixType::Flags&RowMajorBit)==RowMajorBit)
+ {
+ res.setStorageType(SLU_NR);
+ res.nrow = mat.cols();
+ res.ncol = mat.rows();
+ }
+ else
+ {
+ res.setStorageType(SLU_NC);
+ res.nrow = mat.rows();
+ res.ncol = mat.cols();
+ }
+
+ res.Mtype = SLU_GE;
+
+ res.storage.nnz = mat.nonZeros();
+ res.storage.values = mat.valuePtr();
+ res.storage.innerInd = mat.innerIndexPtr();
+ res.storage.outerInd = mat.outerIndexPtr();
+
+ res.setScalarType<typename MatrixType::Scalar>();
+
+ // FIXME the following is not very accurate
+ if (MatrixType::Flags & Upper)
+ res.Mtype = SLU_TRU;
+ if (MatrixType::Flags & Lower)
+ res.Mtype = SLU_TRL;
+
+ eigen_assert(((MatrixType::Flags & SelfAdjoint)==0) && "SelfAdjoint matrix shape not supported by SuperLU");
+ }
+};
+
+namespace internal {
+
+template<typename MatrixType>
+SluMatrix asSluMatrix(MatrixType& mat)
+{
+ return SluMatrix::Map(mat);
+}
+
+/** View a Super LU matrix as an Eigen expression */
+template<typename Scalar, int Flags, typename Index>
+MappedSparseMatrix<Scalar,Flags,Index> map_superlu(SluMatrix& sluMat)
+{
+ eigen_assert((Flags&RowMajor)==RowMajor && sluMat.Stype == SLU_NR
+ || (Flags&ColMajor)==ColMajor && sluMat.Stype == SLU_NC);
+
+ Index outerSize = (Flags&RowMajor)==RowMajor ? sluMat.ncol : sluMat.nrow;
+
+ return MappedSparseMatrix<Scalar,Flags,Index>(
+ sluMat.nrow, sluMat.ncol, sluMat.storage.outerInd[outerSize],
+ sluMat.storage.outerInd, sluMat.storage.innerInd, reinterpret_cast<Scalar*>(sluMat.storage.values) );
+}
+
+} // end namespace internal
+
+/** \ingroup SuperLUSupport_Module
+ * \class SuperLUBase
+ * \brief The base class for the direct and incomplete LU factorization of SuperLU
+ */
+template<typename _MatrixType, typename Derived>
+class SuperLUBase : internal::noncopyable
+{
+ public:
+ typedef _MatrixType MatrixType;
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef typename MatrixType::Index Index;
+ typedef Matrix<Scalar,Dynamic,1> Vector;
+ typedef Matrix<int, 1, MatrixType::ColsAtCompileTime> IntRowVectorType;
+ typedef Matrix<int, MatrixType::RowsAtCompileTime, 1> IntColVectorType;
+ typedef SparseMatrix<Scalar> LUMatrixType;
+
+ public:
+
+ SuperLUBase() {}
+
+ ~SuperLUBase()
+ {
+ clearFactors();
+ }
+
+ Derived& derived() { return *static_cast<Derived*>(this); }
+ const Derived& derived() const { return *static_cast<const Derived*>(this); }
+
+ inline Index rows() const { return m_matrix.rows(); }
+ inline Index cols() const { return m_matrix.cols(); }
+
+ /** \returns a reference to the Super LU option object to configure the Super LU algorithms. */
+ inline superlu_options_t& options() { return m_sluOptions; }
+
+ /** \brief Reports whether previous computation was successful.
+ *
+ * \returns \c Success if computation was succesful,
+ * \c NumericalIssue if the matrix.appears to be negative.
+ */
+ ComputationInfo info() const
+ {
+ eigen_assert(m_isInitialized && "Decomposition is not initialized.");
+ return m_info;
+ }
+
+ /** Computes the sparse Cholesky decomposition of \a matrix */
+ void compute(const MatrixType& matrix)
+ {
+ derived().analyzePattern(matrix);
+ derived().factorize(matrix);
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs>
+ inline const internal::solve_retval<SuperLUBase, Rhs> solve(const MatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "SuperLU is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "SuperLU::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::solve_retval<SuperLUBase, Rhs>(*this, b.derived());
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+// template<typename Rhs>
+// inline const internal::sparse_solve_retval<SuperLU, Rhs> solve(const SparseMatrixBase<Rhs>& b) const
+// {
+// eigen_assert(m_isInitialized && "SuperLU is not initialized.");
+// eigen_assert(rows()==b.rows()
+// && "SuperLU::solve(): invalid number of rows of the right hand side matrix b");
+// return internal::sparse_solve_retval<SuperLU, Rhs>(*this, b.derived());
+// }
+
+ /** Performs a symbolic decomposition on the sparcity of \a matrix.
+ *
+ * This function is particularly useful when solving for several problems having the same structure.
+ *
+ * \sa factorize()
+ */
+ void analyzePattern(const MatrixType& /*matrix*/)
+ {
+ m_isInitialized = true;
+ m_info = Success;
+ m_analysisIsOk = true;
+ m_factorizationIsOk = false;
+ }
+
+ template<typename Stream>
+ void dumpMemory(Stream& s)
+ {}
+
+ protected:
+
+ void initFactorization(const MatrixType& a)
+ {
+ set_default_options(&this->m_sluOptions);
+
+ const int size = a.rows();
+ m_matrix = a;
+
+ m_sluA = internal::asSluMatrix(m_matrix);
+ clearFactors();
+
+ m_p.resize(size);
+ m_q.resize(size);
+ m_sluRscale.resize(size);
+ m_sluCscale.resize(size);
+ m_sluEtree.resize(size);
+
+ // set empty B and X
+ m_sluB.setStorageType(SLU_DN);
+ m_sluB.setScalarType<Scalar>();
+ m_sluB.Mtype = SLU_GE;
+ m_sluB.storage.values = 0;
+ m_sluB.nrow = 0;
+ m_sluB.ncol = 0;
+ m_sluB.storage.lda = size;
+ m_sluX = m_sluB;
+
+ m_extractedDataAreDirty = true;
+ }
+
+ void init()
+ {
+ m_info = InvalidInput;
+ m_isInitialized = false;
+ m_sluL.Store = 0;
+ m_sluU.Store = 0;
+ }
+
+ void extractData() const;
+
+ void clearFactors()
+ {
+ if(m_sluL.Store)
+ Destroy_SuperNode_Matrix(&m_sluL);
+ if(m_sluU.Store)
+ Destroy_CompCol_Matrix(&m_sluU);
+
+ m_sluL.Store = 0;
+ m_sluU.Store = 0;
+
+ memset(&m_sluL,0,sizeof m_sluL);
+ memset(&m_sluU,0,sizeof m_sluU);
+ }
+
+ // cached data to reduce reallocation, etc.
+ mutable LUMatrixType m_l;
+ mutable LUMatrixType m_u;
+ mutable IntColVectorType m_p;
+ mutable IntRowVectorType m_q;
+
+ mutable LUMatrixType m_matrix; // copy of the factorized matrix
+ mutable SluMatrix m_sluA;
+ mutable SuperMatrix m_sluL, m_sluU;
+ mutable SluMatrix m_sluB, m_sluX;
+ mutable SuperLUStat_t m_sluStat;
+ mutable superlu_options_t m_sluOptions;
+ mutable std::vector<int> m_sluEtree;
+ mutable Matrix<RealScalar,Dynamic,1> m_sluRscale, m_sluCscale;
+ mutable Matrix<RealScalar,Dynamic,1> m_sluFerr, m_sluBerr;
+ mutable char m_sluEqued;
+
+ mutable ComputationInfo m_info;
+ bool m_isInitialized;
+ int m_factorizationIsOk;
+ int m_analysisIsOk;
+ mutable bool m_extractedDataAreDirty;
+
+ private:
+ SuperLUBase(SuperLUBase& ) { }
+};
+
+
+/** \ingroup SuperLUSupport_Module
+ * \class SuperLU
+ * \brief A sparse direct LU factorization and solver based on the SuperLU library
+ *
+ * This class allows to solve for A.X = B sparse linear problems via a direct LU factorization
+ * using the SuperLU library. The sparse matrix A must be squared and invertible. The vectors or matrices
+ * X and B can be either dense or sparse.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ *
+ * \sa \ref TutorialSparseDirectSolvers
+ */
+template<typename _MatrixType>
+class SuperLU : public SuperLUBase<_MatrixType,SuperLU<_MatrixType> >
+{
+ public:
+ typedef SuperLUBase<_MatrixType,SuperLU> Base;
+ typedef _MatrixType MatrixType;
+ typedef typename Base::Scalar Scalar;
+ typedef typename Base::RealScalar RealScalar;
+ typedef typename Base::Index Index;
+ typedef typename Base::IntRowVectorType IntRowVectorType;
+ typedef typename Base::IntColVectorType IntColVectorType;
+ typedef typename Base::LUMatrixType LUMatrixType;
+ typedef TriangularView<LUMatrixType, Lower|UnitDiag> LMatrixType;
+ typedef TriangularView<LUMatrixType, Upper> UMatrixType;
+
+ public:
+
+ SuperLU() : Base() { init(); }
+
+ SuperLU(const MatrixType& matrix) : Base()
+ {
+ Base::init();
+ compute(matrix);
+ }
+
+ ~SuperLU()
+ {
+ }
+
+ /** Performs a symbolic decomposition on the sparcity of \a matrix.
+ *
+ * This function is particularly useful when solving for several problems having the same structure.
+ *
+ * \sa factorize()
+ */
+ void analyzePattern(const MatrixType& matrix)
+ {
+ m_info = InvalidInput;
+ m_isInitialized = false;
+ Base::analyzePattern(matrix);
+ }
+
+ /** Performs a numeric decomposition of \a matrix
+ *
+ * The given matrix must has the same sparcity than the matrix on which the symbolic decomposition has been performed.
+ *
+ * \sa analyzePattern()
+ */
+ void factorize(const MatrixType& matrix);
+
+ #ifndef EIGEN_PARSED_BY_DOXYGEN
+ /** \internal */
+ template<typename Rhs,typename Dest>
+ void _solve(const MatrixBase<Rhs> &b, MatrixBase<Dest> &dest) const;
+ #endif // EIGEN_PARSED_BY_DOXYGEN
+
+ inline const LMatrixType& matrixL() const
+ {
+ if (m_extractedDataAreDirty) this->extractData();
+ return m_l;
+ }
+
+ inline const UMatrixType& matrixU() const
+ {
+ if (m_extractedDataAreDirty) this->extractData();
+ return m_u;
+ }
+
+ inline const IntColVectorType& permutationP() const
+ {
+ if (m_extractedDataAreDirty) this->extractData();
+ return m_p;
+ }
+
+ inline const IntRowVectorType& permutationQ() const
+ {
+ if (m_extractedDataAreDirty) this->extractData();
+ return m_q;
+ }
+
+ Scalar determinant() const;
+
+ protected:
+
+ using Base::m_matrix;
+ using Base::m_sluOptions;
+ using Base::m_sluA;
+ using Base::m_sluB;
+ using Base::m_sluX;
+ using Base::m_p;
+ using Base::m_q;
+ using Base::m_sluEtree;
+ using Base::m_sluEqued;
+ using Base::m_sluRscale;
+ using Base::m_sluCscale;
+ using Base::m_sluL;
+ using Base::m_sluU;
+ using Base::m_sluStat;
+ using Base::m_sluFerr;
+ using Base::m_sluBerr;
+ using Base::m_l;
+ using Base::m_u;
+
+ using Base::m_analysisIsOk;
+ using Base::m_factorizationIsOk;
+ using Base::m_extractedDataAreDirty;
+ using Base::m_isInitialized;
+ using Base::m_info;
+
+ void init()
+ {
+ Base::init();
+
+ set_default_options(&this->m_sluOptions);
+ m_sluOptions.PrintStat = NO;
+ m_sluOptions.ConditionNumber = NO;
+ m_sluOptions.Trans = NOTRANS;
+ m_sluOptions.ColPerm = COLAMD;
+ }
+
+
+ private:
+ SuperLU(SuperLU& ) { }
+};
+
+template<typename MatrixType>
+void SuperLU<MatrixType>::factorize(const MatrixType& a)
+{
+ eigen_assert(m_analysisIsOk && "You must first call analyzePattern()");
+ if(!m_analysisIsOk)
+ {
+ m_info = InvalidInput;
+ return;
+ }
+
+ this->initFactorization(a);
+
+ int info = 0;
+ RealScalar recip_pivot_growth, rcond;
+ RealScalar ferr, berr;
+
+ StatInit(&m_sluStat);
+ SuperLU_gssvx(&m_sluOptions, &m_sluA, m_q.data(), m_p.data(), &m_sluEtree[0],
+ &m_sluEqued, &m_sluRscale[0], &m_sluCscale[0],
+ &m_sluL, &m_sluU,
+ NULL, 0,
+ &m_sluB, &m_sluX,
+ &recip_pivot_growth, &rcond,
+ &ferr, &berr,
+ &m_sluStat, &info, Scalar());
+ StatFree(&m_sluStat);
+
+ m_extractedDataAreDirty = true;
+
+ // FIXME how to better check for errors ???
+ m_info = info == 0 ? Success : NumericalIssue;
+ m_factorizationIsOk = true;
+}
+
+template<typename MatrixType>
+template<typename Rhs,typename Dest>
+void SuperLU<MatrixType>::_solve(const MatrixBase<Rhs> &b, MatrixBase<Dest>& x) const
+{
+ eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or analyzePattern()/factorize()");
+
+ const int size = m_matrix.rows();
+ const int rhsCols = b.cols();
+ eigen_assert(size==b.rows());
+
+ m_sluOptions.Trans = NOTRANS;
+ m_sluOptions.Fact = FACTORED;
+ m_sluOptions.IterRefine = NOREFINE;
+
+
+ m_sluFerr.resize(rhsCols);
+ m_sluBerr.resize(rhsCols);
+ m_sluB = SluMatrix::Map(b.const_cast_derived());
+ m_sluX = SluMatrix::Map(x.derived());
+
+ typename Rhs::PlainObject b_cpy;
+ if(m_sluEqued!='N')
+ {
+ b_cpy = b;
+ m_sluB = SluMatrix::Map(b_cpy.const_cast_derived());
+ }
+
+ StatInit(&m_sluStat);
+ int info = 0;
+ RealScalar recip_pivot_growth, rcond;
+ SuperLU_gssvx(&m_sluOptions, &m_sluA,
+ m_q.data(), m_p.data(),
+ &m_sluEtree[0], &m_sluEqued,
+ &m_sluRscale[0], &m_sluCscale[0],
+ &m_sluL, &m_sluU,
+ NULL, 0,
+ &m_sluB, &m_sluX,
+ &recip_pivot_growth, &rcond,
+ &m_sluFerr[0], &m_sluBerr[0],
+ &m_sluStat, &info, Scalar());
+ StatFree(&m_sluStat);
+ m_info = info==0 ? Success : NumericalIssue;
+}
+
+// the code of this extractData() function has been adapted from the SuperLU's Matlab support code,
+//
+// Copyright (c) 1994 by Xerox Corporation. All rights reserved.
+//
+// THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
+// EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
+//
+template<typename MatrixType, typename Derived>
+void SuperLUBase<MatrixType,Derived>::extractData() const
+{
+ eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for extracting factors, you must first call either compute() or analyzePattern()/factorize()");
+ if (m_extractedDataAreDirty)
+ {
+ int upper;
+ int fsupc, istart, nsupr;
+ int lastl = 0, lastu = 0;
+ SCformat *Lstore = static_cast<SCformat*>(m_sluL.Store);
+ NCformat *Ustore = static_cast<NCformat*>(m_sluU.Store);
+ Scalar *SNptr;
+
+ const int size = m_matrix.rows();
+ m_l.resize(size,size);
+ m_l.resizeNonZeros(Lstore->nnz);
+ m_u.resize(size,size);
+ m_u.resizeNonZeros(Ustore->nnz);
+
+ int* Lcol = m_l.outerIndexPtr();
+ int* Lrow = m_l.innerIndexPtr();
+ Scalar* Lval = m_l.valuePtr();
+
+ int* Ucol = m_u.outerIndexPtr();
+ int* Urow = m_u.innerIndexPtr();
+ Scalar* Uval = m_u.valuePtr();
+
+ Ucol[0] = 0;
+ Ucol[0] = 0;
+
+ /* for each supernode */
+ for (int k = 0; k <= Lstore->nsuper; ++k)
+ {
+ fsupc = L_FST_SUPC(k);
+ istart = L_SUB_START(fsupc);
+ nsupr = L_SUB_START(fsupc+1) - istart;
+ upper = 1;
+
+ /* for each column in the supernode */
+ for (int j = fsupc; j < L_FST_SUPC(k+1); ++j)
+ {
+ SNptr = &((Scalar*)Lstore->nzval)[L_NZ_START(j)];
+
+ /* Extract U */
+ for (int i = U_NZ_START(j); i < U_NZ_START(j+1); ++i)
+ {
+ Uval[lastu] = ((Scalar*)Ustore->nzval)[i];
+ /* Matlab doesn't like explicit zero. */
+ if (Uval[lastu] != 0.0)
+ Urow[lastu++] = U_SUB(i);
+ }
+ for (int i = 0; i < upper; ++i)
+ {
+ /* upper triangle in the supernode */
+ Uval[lastu] = SNptr[i];
+ /* Matlab doesn't like explicit zero. */
+ if (Uval[lastu] != 0.0)
+ Urow[lastu++] = L_SUB(istart+i);
+ }
+ Ucol[j+1] = lastu;
+
+ /* Extract L */
+ Lval[lastl] = 1.0; /* unit diagonal */
+ Lrow[lastl++] = L_SUB(istart + upper - 1);
+ for (int i = upper; i < nsupr; ++i)
+ {
+ Lval[lastl] = SNptr[i];
+ /* Matlab doesn't like explicit zero. */
+ if (Lval[lastl] != 0.0)
+ Lrow[lastl++] = L_SUB(istart+i);
+ }
+ Lcol[j+1] = lastl;
+
+ ++upper;
+ } /* for j ... */
+
+ } /* for k ... */
+
+ // squeeze the matrices :
+ m_l.resizeNonZeros(lastl);
+ m_u.resizeNonZeros(lastu);
+
+ m_extractedDataAreDirty = false;
+ }
+}
+
+template<typename MatrixType>
+typename SuperLU<MatrixType>::Scalar SuperLU<MatrixType>::determinant() const
+{
+ eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for computing the determinant, you must first call either compute() or analyzePattern()/factorize()");
+
+ if (m_extractedDataAreDirty)
+ this->extractData();
+
+ Scalar det = Scalar(1);
+ for (int j=0; j<m_u.cols(); ++j)
+ {
+ if (m_u.outerIndexPtr()[j+1]-m_u.outerIndexPtr()[j] > 0)
+ {
+ int lastId = m_u.outerIndexPtr()[j+1]-1;
+ eigen_assert(m_u.innerIndexPtr()[lastId]<=j);
+ if (m_u.innerIndexPtr()[lastId]==j)
+ det *= m_u.valuePtr()[lastId];
+ }
+ }
+ if(m_sluEqued!='N')
+ return det/m_sluRscale.prod()/m_sluCscale.prod();
+ else
+ return det;
+}
+
+#ifdef EIGEN_PARSED_BY_DOXYGEN
+#define EIGEN_SUPERLU_HAS_ILU
+#endif
+
+#ifdef EIGEN_SUPERLU_HAS_ILU
+
+/** \ingroup SuperLUSupport_Module
+ * \class SuperILU
+ * \brief A sparse direct \b incomplete LU factorization and solver based on the SuperLU library
+ *
+ * This class allows to solve for an approximate solution of A.X = B sparse linear problems via an incomplete LU factorization
+ * using the SuperLU library. This class is aimed to be used as a preconditioner of the iterative linear solvers.
+ *
+ * \warning This class requires SuperLU 4 or later.
+ *
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ *
+ * \sa \ref TutorialSparseDirectSolvers, class ConjugateGradient, class BiCGSTAB
+ */
+
+template<typename _MatrixType>
+class SuperILU : public SuperLUBase<_MatrixType,SuperILU<_MatrixType> >
+{
+ public:
+ typedef SuperLUBase<_MatrixType,SuperILU> Base;
+ typedef _MatrixType MatrixType;
+ typedef typename Base::Scalar Scalar;
+ typedef typename Base::RealScalar RealScalar;
+ typedef typename Base::Index Index;
+
+ public:
+
+ SuperILU() : Base() { init(); }
+
+ SuperILU(const MatrixType& matrix) : Base()
+ {
+ init();
+ compute(matrix);
+ }
+
+ ~SuperILU()
+ {
+ }
+
+ /** Performs a symbolic decomposition on the sparcity of \a matrix.
+ *
+ * This function is particularly useful when solving for several problems having the same structure.
+ *
+ * \sa factorize()
+ */
+ void analyzePattern(const MatrixType& matrix)
+ {
+ Base::analyzePattern(matrix);
+ }
+
+ /** Performs a numeric decomposition of \a matrix
+ *
+ * The given matrix must has the same sparcity than the matrix on which the symbolic decomposition has been performed.
+ *
+ * \sa analyzePattern()
+ */
+ void factorize(const MatrixType& matrix);
+
+ #ifndef EIGEN_PARSED_BY_DOXYGEN
+ /** \internal */
+ template<typename Rhs,typename Dest>
+ void _solve(const MatrixBase<Rhs> &b, MatrixBase<Dest> &dest) const;
+ #endif // EIGEN_PARSED_BY_DOXYGEN
+
+ protected:
+
+ using Base::m_matrix;
+ using Base::m_sluOptions;
+ using Base::m_sluA;
+ using Base::m_sluB;
+ using Base::m_sluX;
+ using Base::m_p;
+ using Base::m_q;
+ using Base::m_sluEtree;
+ using Base::m_sluEqued;
+ using Base::m_sluRscale;
+ using Base::m_sluCscale;
+ using Base::m_sluL;
+ using Base::m_sluU;
+ using Base::m_sluStat;
+ using Base::m_sluFerr;
+ using Base::m_sluBerr;
+ using Base::m_l;
+ using Base::m_u;
+
+ using Base::m_analysisIsOk;
+ using Base::m_factorizationIsOk;
+ using Base::m_extractedDataAreDirty;
+ using Base::m_isInitialized;
+ using Base::m_info;
+
+ void init()
+ {
+ Base::init();
+
+ ilu_set_default_options(&m_sluOptions);
+ m_sluOptions.PrintStat = NO;
+ m_sluOptions.ConditionNumber = NO;
+ m_sluOptions.Trans = NOTRANS;
+ m_sluOptions.ColPerm = MMD_AT_PLUS_A;
+
+ // no attempt to preserve column sum
+ m_sluOptions.ILU_MILU = SILU;
+ // only basic ILU(k) support -- no direct control over memory consumption
+ // better to use ILU_DropRule = DROP_BASIC | DROP_AREA
+ // and set ILU_FillFactor to max memory growth
+ m_sluOptions.ILU_DropRule = DROP_BASIC;
+ m_sluOptions.ILU_DropTol = NumTraits<Scalar>::dummy_precision()*10;
+ }
+
+ private:
+ SuperILU(SuperILU& ) { }
+};
+
+template<typename MatrixType>
+void SuperILU<MatrixType>::factorize(const MatrixType& a)
+{
+ eigen_assert(m_analysisIsOk && "You must first call analyzePattern()");
+ if(!m_analysisIsOk)
+ {
+ m_info = InvalidInput;
+ return;
+ }
+
+ this->initFactorization(a);
+
+ int info = 0;
+ RealScalar recip_pivot_growth, rcond;
+
+ StatInit(&m_sluStat);
+ SuperLU_gsisx(&m_sluOptions, &m_sluA, m_q.data(), m_p.data(), &m_sluEtree[0],
+ &m_sluEqued, &m_sluRscale[0], &m_sluCscale[0],
+ &m_sluL, &m_sluU,
+ NULL, 0,
+ &m_sluB, &m_sluX,
+ &recip_pivot_growth, &rcond,
+ &m_sluStat, &info, Scalar());
+ StatFree(&m_sluStat);
+
+ // FIXME how to better check for errors ???
+ m_info = info == 0 ? Success : NumericalIssue;
+ m_factorizationIsOk = true;
+}
+
+template<typename MatrixType>
+template<typename Rhs,typename Dest>
+void SuperILU<MatrixType>::_solve(const MatrixBase<Rhs> &b, MatrixBase<Dest>& x) const
+{
+ eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or analyzePattern()/factorize()");
+
+ const int size = m_matrix.rows();
+ const int rhsCols = b.cols();
+ eigen_assert(size==b.rows());
+
+ m_sluOptions.Trans = NOTRANS;
+ m_sluOptions.Fact = FACTORED;
+ m_sluOptions.IterRefine = NOREFINE;
+
+ m_sluFerr.resize(rhsCols);
+ m_sluBerr.resize(rhsCols);
+ m_sluB = SluMatrix::Map(b.const_cast_derived());
+ m_sluX = SluMatrix::Map(x.derived());
+
+ typename Rhs::PlainObject b_cpy;
+ if(m_sluEqued!='N')
+ {
+ b_cpy = b;
+ m_sluB = SluMatrix::Map(b_cpy.const_cast_derived());
+ }
+
+ int info = 0;
+ RealScalar recip_pivot_growth, rcond;
+
+ StatInit(&m_sluStat);
+ SuperLU_gsisx(&m_sluOptions, &m_sluA,
+ m_q.data(), m_p.data(),
+ &m_sluEtree[0], &m_sluEqued,
+ &m_sluRscale[0], &m_sluCscale[0],
+ &m_sluL, &m_sluU,
+ NULL, 0,
+ &m_sluB, &m_sluX,
+ &recip_pivot_growth, &rcond,
+ &m_sluStat, &info, Scalar());
+ StatFree(&m_sluStat);
+
+ m_info = info==0 ? Success : NumericalIssue;
+}
+#endif
+
+namespace internal {
+
+template<typename _MatrixType, typename Derived, typename Rhs>
+struct solve_retval<SuperLUBase<_MatrixType,Derived>, Rhs>
+ : solve_retval_base<SuperLUBase<_MatrixType,Derived>, Rhs>
+{
+ typedef SuperLUBase<_MatrixType,Derived> Dec;
+ EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec().derived()._solve(rhs(),dst);
+ }
+};
+
+template<typename _MatrixType, typename Derived, typename Rhs>
+struct sparse_solve_retval<SuperLUBase<_MatrixType,Derived>, Rhs>
+ : sparse_solve_retval_base<SuperLUBase<_MatrixType,Derived>, Rhs>
+{
+ typedef SuperLUBase<_MatrixType,Derived> Dec;
+ EIGEN_MAKE_SPARSE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec().derived()._solve(rhs(),dst);
+ }
+};
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_SUPERLUSUPPORT_H
diff --git a/extern/Eigen3/Eigen/src/UmfPackSupport/UmfPackSupport.h b/extern/Eigen3/Eigen/src/UmfPackSupport/UmfPackSupport.h
new file mode 100644
index 00000000000..f01720362de
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/UmfPackSupport/UmfPackSupport.h
@@ -0,0 +1,431 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_UMFPACKSUPPORT_H
+#define EIGEN_UMFPACKSUPPORT_H
+
+namespace Eigen {
+
+/* TODO extract L, extract U, compute det, etc... */
+
+// generic double/complex<double> wrapper functions:
+
+inline void umfpack_free_numeric(void **Numeric, double)
+{ umfpack_di_free_numeric(Numeric); *Numeric = 0; }
+
+inline void umfpack_free_numeric(void **Numeric, std::complex<double>)
+{ umfpack_zi_free_numeric(Numeric); *Numeric = 0; }
+
+inline void umfpack_free_symbolic(void **Symbolic, double)
+{ umfpack_di_free_symbolic(Symbolic); *Symbolic = 0; }
+
+inline void umfpack_free_symbolic(void **Symbolic, std::complex<double>)
+{ umfpack_zi_free_symbolic(Symbolic); *Symbolic = 0; }
+
+inline int umfpack_symbolic(int n_row,int n_col,
+ const int Ap[], const int Ai[], const double Ax[], void **Symbolic,
+ const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO])
+{
+ return umfpack_di_symbolic(n_row,n_col,Ap,Ai,Ax,Symbolic,Control,Info);
+}
+
+inline int umfpack_symbolic(int n_row,int n_col,
+ const int Ap[], const int Ai[], const std::complex<double> Ax[], void **Symbolic,
+ const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO])
+{
+ return umfpack_zi_symbolic(n_row,n_col,Ap,Ai,&internal::real_ref(Ax[0]),0,Symbolic,Control,Info);
+}
+
+inline int umfpack_numeric( const int Ap[], const int Ai[], const double Ax[],
+ void *Symbolic, void **Numeric,
+ const double Control[UMFPACK_CONTROL],double Info [UMFPACK_INFO])
+{
+ return umfpack_di_numeric(Ap,Ai,Ax,Symbolic,Numeric,Control,Info);
+}
+
+inline int umfpack_numeric( const int Ap[], const int Ai[], const std::complex<double> Ax[],
+ void *Symbolic, void **Numeric,
+ const double Control[UMFPACK_CONTROL],double Info [UMFPACK_INFO])
+{
+ return umfpack_zi_numeric(Ap,Ai,&internal::real_ref(Ax[0]),0,Symbolic,Numeric,Control,Info);
+}
+
+inline int umfpack_solve( int sys, const int Ap[], const int Ai[], const double Ax[],
+ double X[], const double B[], void *Numeric,
+ const double Control[UMFPACK_CONTROL], double Info[UMFPACK_INFO])
+{
+ return umfpack_di_solve(sys,Ap,Ai,Ax,X,B,Numeric,Control,Info);
+}
+
+inline int umfpack_solve( int sys, const int Ap[], const int Ai[], const std::complex<double> Ax[],
+ std::complex<double> X[], const std::complex<double> B[], void *Numeric,
+ const double Control[UMFPACK_CONTROL], double Info[UMFPACK_INFO])
+{
+ return umfpack_zi_solve(sys,Ap,Ai,&internal::real_ref(Ax[0]),0,&internal::real_ref(X[0]),0,&internal::real_ref(B[0]),0,Numeric,Control,Info);
+}
+
+inline int umfpack_get_lunz(int *lnz, int *unz, int *n_row, int *n_col, int *nz_udiag, void *Numeric, double)
+{
+ return umfpack_di_get_lunz(lnz,unz,n_row,n_col,nz_udiag,Numeric);
+}
+
+inline int umfpack_get_lunz(int *lnz, int *unz, int *n_row, int *n_col, int *nz_udiag, void *Numeric, std::complex<double>)
+{
+ return umfpack_zi_get_lunz(lnz,unz,n_row,n_col,nz_udiag,Numeric);
+}
+
+inline int umfpack_get_numeric(int Lp[], int Lj[], double Lx[], int Up[], int Ui[], double Ux[],
+ int P[], int Q[], double Dx[], int *do_recip, double Rs[], void *Numeric)
+{
+ return umfpack_di_get_numeric(Lp,Lj,Lx,Up,Ui,Ux,P,Q,Dx,do_recip,Rs,Numeric);
+}
+
+inline int umfpack_get_numeric(int Lp[], int Lj[], std::complex<double> Lx[], int Up[], int Ui[], std::complex<double> Ux[],
+ int P[], int Q[], std::complex<double> Dx[], int *do_recip, double Rs[], void *Numeric)
+{
+ double& lx0_real = internal::real_ref(Lx[0]);
+ double& ux0_real = internal::real_ref(Ux[0]);
+ double& dx0_real = internal::real_ref(Dx[0]);
+ return umfpack_zi_get_numeric(Lp,Lj,Lx?&lx0_real:0,0,Up,Ui,Ux?&ux0_real:0,0,P,Q,
+ Dx?&dx0_real:0,0,do_recip,Rs,Numeric);
+}
+
+inline int umfpack_get_determinant(double *Mx, double *Ex, void *NumericHandle, double User_Info [UMFPACK_INFO])
+{
+ return umfpack_di_get_determinant(Mx,Ex,NumericHandle,User_Info);
+}
+
+inline int umfpack_get_determinant(std::complex<double> *Mx, double *Ex, void *NumericHandle, double User_Info [UMFPACK_INFO])
+{
+ double& mx_real = internal::real_ref(*Mx);
+ return umfpack_zi_get_determinant(&mx_real,0,Ex,NumericHandle,User_Info);
+}
+
+/** \ingroup UmfPackSupport_Module
+ * \brief A sparse LU factorization and solver based on UmfPack
+ *
+ * This class allows to solve for A.X = B sparse linear problems via a LU factorization
+ * using the UmfPack library. The sparse matrix A must be squared and full rank.
+ * The vectors or matrices X and B can be either dense or sparse.
+ *
+ * \WARNING The input matrix A should be in a \b compressed and \b column-major form.
+ * Otherwise an expensive copy will be made. You can call the inexpensive makeCompressed() to get a compressed matrix.
+ * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<>
+ *
+ * \sa \ref TutorialSparseDirectSolvers
+ */
+template<typename _MatrixType>
+class UmfPackLU : internal::noncopyable
+{
+ public:
+ typedef _MatrixType MatrixType;
+ typedef typename MatrixType::Scalar Scalar;
+ typedef typename MatrixType::RealScalar RealScalar;
+ typedef typename MatrixType::Index Index;
+ typedef Matrix<Scalar,Dynamic,1> Vector;
+ typedef Matrix<int, 1, MatrixType::ColsAtCompileTime> IntRowVectorType;
+ typedef Matrix<int, MatrixType::RowsAtCompileTime, 1> IntColVectorType;
+ typedef SparseMatrix<Scalar> LUMatrixType;
+ typedef SparseMatrix<Scalar,ColMajor,int> UmfpackMatrixType;
+
+ public:
+
+ UmfPackLU() { init(); }
+
+ UmfPackLU(const MatrixType& matrix)
+ {
+ init();
+ compute(matrix);
+ }
+
+ ~UmfPackLU()
+ {
+ if(m_symbolic) umfpack_free_symbolic(&m_symbolic,Scalar());
+ if(m_numeric) umfpack_free_numeric(&m_numeric,Scalar());
+ }
+
+ inline Index rows() const { return m_copyMatrix.rows(); }
+ inline Index cols() const { return m_copyMatrix.cols(); }
+
+ /** \brief Reports whether previous computation was successful.
+ *
+ * \returns \c Success if computation was succesful,
+ * \c NumericalIssue if the matrix.appears to be negative.
+ */
+ ComputationInfo info() const
+ {
+ eigen_assert(m_isInitialized && "Decomposition is not initialized.");
+ return m_info;
+ }
+
+ inline const LUMatrixType& matrixL() const
+ {
+ if (m_extractedDataAreDirty) extractData();
+ return m_l;
+ }
+
+ inline const LUMatrixType& matrixU() const
+ {
+ if (m_extractedDataAreDirty) extractData();
+ return m_u;
+ }
+
+ inline const IntColVectorType& permutationP() const
+ {
+ if (m_extractedDataAreDirty) extractData();
+ return m_p;
+ }
+
+ inline const IntRowVectorType& permutationQ() const
+ {
+ if (m_extractedDataAreDirty) extractData();
+ return m_q;
+ }
+
+ /** Computes the sparse Cholesky decomposition of \a matrix
+ * Note that the matrix should be column-major, and in compressed format for best performance.
+ * \sa SparseMatrix::makeCompressed().
+ */
+ void compute(const MatrixType& matrix)
+ {
+ analyzePattern(matrix);
+ factorize(matrix);
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+ template<typename Rhs>
+ inline const internal::solve_retval<UmfPackLU, Rhs> solve(const MatrixBase<Rhs>& b) const
+ {
+ eigen_assert(m_isInitialized && "UmfPackLU is not initialized.");
+ eigen_assert(rows()==b.rows()
+ && "UmfPackLU::solve(): invalid number of rows of the right hand side matrix b");
+ return internal::solve_retval<UmfPackLU, Rhs>(*this, b.derived());
+ }
+
+ /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A.
+ *
+ * \sa compute()
+ */
+// template<typename Rhs>
+// inline const internal::sparse_solve_retval<UmfPAckLU, Rhs> solve(const SparseMatrixBase<Rhs>& b) const
+// {
+// eigen_assert(m_isInitialized && "UmfPAckLU is not initialized.");
+// eigen_assert(rows()==b.rows()
+// && "UmfPAckLU::solve(): invalid number of rows of the right hand side matrix b");
+// return internal::sparse_solve_retval<UmfPAckLU, Rhs>(*this, b.derived());
+// }
+
+ /** Performs a symbolic decomposition on the sparcity of \a matrix.
+ *
+ * This function is particularly useful when solving for several problems having the same structure.
+ *
+ * \sa factorize(), compute()
+ */
+ void analyzePattern(const MatrixType& matrix)
+ {
+ if(m_symbolic)
+ umfpack_free_symbolic(&m_symbolic,Scalar());
+ if(m_numeric)
+ umfpack_free_numeric(&m_numeric,Scalar());
+
+ grapInput(matrix);
+
+ int errorCode = 0;
+ errorCode = umfpack_symbolic(matrix.rows(), matrix.cols(), m_outerIndexPtr, m_innerIndexPtr, m_valuePtr,
+ &m_symbolic, 0, 0);
+
+ m_isInitialized = true;
+ m_info = errorCode ? InvalidInput : Success;
+ m_analysisIsOk = true;
+ m_factorizationIsOk = false;
+ }
+
+ /** Performs a numeric decomposition of \a matrix
+ *
+ * The given matrix must has the same sparcity than the matrix on which the pattern anylysis has been performed.
+ *
+ * \sa analyzePattern(), compute()
+ */
+ void factorize(const MatrixType& matrix)
+ {
+ eigen_assert(m_analysisIsOk && "UmfPackLU: you must first call analyzePattern()");
+ if(m_numeric)
+ umfpack_free_numeric(&m_numeric,Scalar());
+
+ grapInput(matrix);
+
+ int errorCode;
+ errorCode = umfpack_numeric(m_outerIndexPtr, m_innerIndexPtr, m_valuePtr,
+ m_symbolic, &m_numeric, 0, 0);
+
+ m_info = errorCode ? NumericalIssue : Success;
+ m_factorizationIsOk = true;
+ }
+
+ #ifndef EIGEN_PARSED_BY_DOXYGEN
+ /** \internal */
+ template<typename BDerived,typename XDerived>
+ bool _solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived> &x) const;
+ #endif
+
+ Scalar determinant() const;
+
+ void extractData() const;
+
+ protected:
+
+
+ void init()
+ {
+ m_info = InvalidInput;
+ m_isInitialized = false;
+ m_numeric = 0;
+ m_symbolic = 0;
+ m_outerIndexPtr = 0;
+ m_innerIndexPtr = 0;
+ m_valuePtr = 0;
+ }
+
+ void grapInput(const MatrixType& mat)
+ {
+ m_copyMatrix.resize(mat.rows(), mat.cols());
+ if( ((MatrixType::Flags&RowMajorBit)==RowMajorBit) || sizeof(typename MatrixType::Index)!=sizeof(int) || !mat.isCompressed() )
+ {
+ // non supported input -> copy
+ m_copyMatrix = mat;
+ m_outerIndexPtr = m_copyMatrix.outerIndexPtr();
+ m_innerIndexPtr = m_copyMatrix.innerIndexPtr();
+ m_valuePtr = m_copyMatrix.valuePtr();
+ }
+ else
+ {
+ m_outerIndexPtr = mat.outerIndexPtr();
+ m_innerIndexPtr = mat.innerIndexPtr();
+ m_valuePtr = mat.valuePtr();
+ }
+ }
+
+ // cached data to reduce reallocation, etc.
+ mutable LUMatrixType m_l;
+ mutable LUMatrixType m_u;
+ mutable IntColVectorType m_p;
+ mutable IntRowVectorType m_q;
+
+ UmfpackMatrixType m_copyMatrix;
+ const Scalar* m_valuePtr;
+ const int* m_outerIndexPtr;
+ const int* m_innerIndexPtr;
+ void* m_numeric;
+ void* m_symbolic;
+
+ mutable ComputationInfo m_info;
+ bool m_isInitialized;
+ int m_factorizationIsOk;
+ int m_analysisIsOk;
+ mutable bool m_extractedDataAreDirty;
+
+ private:
+ UmfPackLU(UmfPackLU& ) { }
+};
+
+
+template<typename MatrixType>
+void UmfPackLU<MatrixType>::extractData() const
+{
+ if (m_extractedDataAreDirty)
+ {
+ // get size of the data
+ int lnz, unz, rows, cols, nz_udiag;
+ umfpack_get_lunz(&lnz, &unz, &rows, &cols, &nz_udiag, m_numeric, Scalar());
+
+ // allocate data
+ m_l.resize(rows,(std::min)(rows,cols));
+ m_l.resizeNonZeros(lnz);
+
+ m_u.resize((std::min)(rows,cols),cols);
+ m_u.resizeNonZeros(unz);
+
+ m_p.resize(rows);
+ m_q.resize(cols);
+
+ // extract
+ umfpack_get_numeric(m_l.outerIndexPtr(), m_l.innerIndexPtr(), m_l.valuePtr(),
+ m_u.outerIndexPtr(), m_u.innerIndexPtr(), m_u.valuePtr(),
+ m_p.data(), m_q.data(), 0, 0, 0, m_numeric);
+
+ m_extractedDataAreDirty = false;
+ }
+}
+
+template<typename MatrixType>
+typename UmfPackLU<MatrixType>::Scalar UmfPackLU<MatrixType>::determinant() const
+{
+ Scalar det;
+ umfpack_get_determinant(&det, 0, m_numeric, 0);
+ return det;
+}
+
+template<typename MatrixType>
+template<typename BDerived,typename XDerived>
+bool UmfPackLU<MatrixType>::_solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived> &x) const
+{
+ const int rhsCols = b.cols();
+ eigen_assert((BDerived::Flags&RowMajorBit)==0 && "UmfPackLU backend does not support non col-major rhs yet");
+ eigen_assert((XDerived::Flags&RowMajorBit)==0 && "UmfPackLU backend does not support non col-major result yet");
+
+ int errorCode;
+ for (int j=0; j<rhsCols; ++j)
+ {
+ errorCode = umfpack_solve(UMFPACK_A,
+ m_outerIndexPtr, m_innerIndexPtr, m_valuePtr,
+ &x.col(j).coeffRef(0), &b.const_cast_derived().col(j).coeffRef(0), m_numeric, 0, 0);
+ if (errorCode!=0)
+ return false;
+ }
+
+ return true;
+}
+
+
+namespace internal {
+
+template<typename _MatrixType, typename Rhs>
+struct solve_retval<UmfPackLU<_MatrixType>, Rhs>
+ : solve_retval_base<UmfPackLU<_MatrixType>, Rhs>
+{
+ typedef UmfPackLU<_MatrixType> Dec;
+ EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec()._solve(rhs(),dst);
+ }
+};
+
+template<typename _MatrixType, typename Rhs>
+struct sparse_solve_retval<UmfPackLU<_MatrixType>, Rhs>
+ : sparse_solve_retval_base<UmfPackLU<_MatrixType>, Rhs>
+{
+ typedef UmfPackLU<_MatrixType> Dec;
+ EIGEN_MAKE_SPARSE_SOLVE_HELPERS(Dec,Rhs)
+
+ template<typename Dest> void evalTo(Dest& dst) const
+ {
+ dec()._solve(rhs(),dst);
+ }
+};
+
+} // end namespace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_UMFPACKSUPPORT_H
diff --git a/extern/Eigen3/Eigen/src/misc/Image.h b/extern/Eigen3/Eigen/src/misc/Image.h
index 19b3e08cbfd..75c5f433a8a 100644
--- a/extern/Eigen3/Eigen/src/misc/Image.h
+++ b/extern/Eigen3/Eigen/src/misc/Image.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MISC_IMAGE_H
#define EIGEN_MISC_IMAGE_H
+namespace Eigen {
+
namespace internal {
/** \class image_retval_base
@@ -92,4 +79,6 @@ template<typename _DecompositionType> struct image_retval_base
image_retval(const DecompositionType& dec, const MatrixType& originalMatrix) \
: Base(dec, originalMatrix) {}
+} // end namespace Eigen
+
#endif // EIGEN_MISC_IMAGE_H
diff --git a/extern/Eigen3/Eigen/src/misc/Kernel.h b/extern/Eigen3/Eigen/src/misc/Kernel.h
index 0115970e8eb..b9e1518fd49 100644
--- a/extern/Eigen3/Eigen/src/misc/Kernel.h
+++ b/extern/Eigen3/Eigen/src/misc/Kernel.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MISC_KERNEL_H
#define EIGEN_MISC_KERNEL_H
+namespace Eigen {
+
namespace internal {
/** \class kernel_retval_base
@@ -89,4 +76,6 @@ template<typename _DecompositionType> struct kernel_retval_base
using Base::cols; \
kernel_retval(const DecompositionType& dec) : Base(dec) {}
+} // end namespace Eigen
+
#endif // EIGEN_MISC_KERNEL_H
diff --git a/extern/Eigen3/Eigen/src/misc/Solve.h b/extern/Eigen3/Eigen/src/misc/Solve.h
index b7cbcadb392..7f70d60afbd 100644
--- a/extern/Eigen3/Eigen/src/misc/Solve.h
+++ b/extern/Eigen3/Eigen/src/misc/Solve.h
@@ -3,28 +3,15 @@
//
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MISC_SOLVE_H
#define EIGEN_MISC_SOLVE_H
+namespace Eigen {
+
namespace internal {
/** \class solve_retval_base
@@ -66,7 +53,7 @@ template<typename _DecompositionType, typename Rhs> struct solve_retval_base
protected:
const DecompositionType& m_dec;
- const typename Rhs::Nested m_rhs;
+ typename Rhs::Nested m_rhs;
};
} // end namespace internal
@@ -84,4 +71,6 @@ template<typename _DecompositionType, typename Rhs> struct solve_retval_base
solve_retval(const DecompositionType& dec, const Rhs& rhs) \
: Base(dec, rhs) {}
+} // end namespace Eigen
+
#endif // EIGEN_MISC_SOLVE_H
diff --git a/extern/Eigen3/Eigen/src/misc/SparseSolve.h b/extern/Eigen3/Eigen/src/misc/SparseSolve.h
new file mode 100644
index 00000000000..272c4a479d7
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/misc/SparseSolve.h
@@ -0,0 +1,111 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef EIGEN_SPARSE_SOLVE_H
+#define EIGEN_SPARSE_SOLVE_H
+
+namespace Eigen {
+
+namespace internal {
+
+template<typename _DecompositionType, typename Rhs> struct sparse_solve_retval_base;
+template<typename _DecompositionType, typename Rhs> struct sparse_solve_retval;
+
+template<typename DecompositionType, typename Rhs>
+struct traits<sparse_solve_retval_base<DecompositionType, Rhs> >
+{
+ typedef typename DecompositionType::MatrixType MatrixType;
+ typedef SparseMatrix<typename Rhs::Scalar, Rhs::Options, typename Rhs::Index> ReturnType;
+};
+
+template<typename _DecompositionType, typename Rhs> struct sparse_solve_retval_base
+ : public ReturnByValue<sparse_solve_retval_base<_DecompositionType, Rhs> >
+{
+ typedef typename remove_all<typename Rhs::Nested>::type RhsNestedCleaned;
+ typedef _DecompositionType DecompositionType;
+ typedef ReturnByValue<sparse_solve_retval_base> Base;
+ typedef typename Base::Index Index;
+
+ sparse_solve_retval_base(const DecompositionType& dec, const Rhs& rhs)
+ : m_dec(dec), m_rhs(rhs)
+ {}
+
+ inline Index rows() const { return m_dec.cols(); }
+ inline Index cols() const { return m_rhs.cols(); }
+ inline const DecompositionType& dec() const { return m_dec; }
+ inline const RhsNestedCleaned& rhs() const { return m_rhs; }
+
+ template<typename Dest> inline void evalTo(Dest& dst) const
+ {
+ static_cast<const sparse_solve_retval<DecompositionType,Rhs>*>(this)->evalTo(dst);
+ }
+
+ protected:
+ const DecompositionType& m_dec;
+ typename Rhs::Nested m_rhs;
+};
+
+#define EIGEN_MAKE_SPARSE_SOLVE_HELPERS(DecompositionType,Rhs) \
+ typedef typename DecompositionType::MatrixType MatrixType; \
+ typedef typename MatrixType::Scalar Scalar; \
+ typedef typename MatrixType::RealScalar RealScalar; \
+ typedef typename MatrixType::Index Index; \
+ typedef Eigen::internal::sparse_solve_retval_base<DecompositionType,Rhs> Base; \
+ using Base::dec; \
+ using Base::rhs; \
+ using Base::rows; \
+ using Base::cols; \
+ sparse_solve_retval(const DecompositionType& dec, const Rhs& rhs) \
+ : Base(dec, rhs) {}
+
+
+
+template<typename DecompositionType, typename Rhs, typename Guess> struct solve_retval_with_guess;
+
+template<typename DecompositionType, typename Rhs, typename Guess>
+struct traits<solve_retval_with_guess<DecompositionType, Rhs, Guess> >
+{
+ typedef typename DecompositionType::MatrixType MatrixType;
+ typedef Matrix<typename Rhs::Scalar,
+ MatrixType::ColsAtCompileTime,
+ Rhs::ColsAtCompileTime,
+ Rhs::PlainObject::Options,
+ MatrixType::MaxColsAtCompileTime,
+ Rhs::MaxColsAtCompileTime> ReturnType;
+};
+
+template<typename DecompositionType, typename Rhs, typename Guess> struct solve_retval_with_guess
+ : public ReturnByValue<solve_retval_with_guess<DecompositionType, Rhs, Guess> >
+{
+ typedef typename DecompositionType::Index Index;
+
+ solve_retval_with_guess(const DecompositionType& dec, const Rhs& rhs, const Guess& guess)
+ : m_dec(dec), m_rhs(rhs), m_guess(guess)
+ {}
+
+ inline Index rows() const { return m_dec.cols(); }
+ inline Index cols() const { return m_rhs.cols(); }
+
+ template<typename Dest> inline void evalTo(Dest& dst) const
+ {
+ dst = m_guess;
+ m_dec._solveWithGuess(m_rhs,dst);
+ }
+
+ protected:
+ const DecompositionType& m_dec;
+ const typename Rhs::Nested m_rhs;
+ const typename Guess::Nested m_guess;
+};
+
+} // namepsace internal
+
+} // end namespace Eigen
+
+#endif // EIGEN_SPARSE_SOLVE_H
diff --git a/extern/Eigen3/Eigen/src/misc/blas.h b/extern/Eigen3/Eigen/src/misc/blas.h
new file mode 100644
index 00000000000..6fce99ed5c4
--- /dev/null
+++ b/extern/Eigen3/Eigen/src/misc/blas.h
@@ -0,0 +1,658 @@
+#ifndef BLAS_H
+#define BLAS_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#define BLASFUNC(FUNC) FUNC##_
+
+#ifdef __WIN64__
+typedef long long BLASLONG;
+typedef unsigned long long BLASULONG;
+#else
+typedef long BLASLONG;
+typedef unsigned long BLASULONG;
+#endif
+
+int BLASFUNC(xerbla)(const char *, int *info, int);
+
+float BLASFUNC(sdot) (int *, float *, int *, float *, int *);
+float BLASFUNC(sdsdot)(int *, float *, float *, int *, float *, int *);
+
+double BLASFUNC(dsdot) (int *, float *, int *, float *, int *);
+double BLASFUNC(ddot) (int *, double *, int *, double *, int *);
+double BLASFUNC(qdot) (int *, double *, int *, double *, int *);
+
+int BLASFUNC(cdotuw) (int *, float *, int *, float *, int *, float*);
+int BLASFUNC(cdotcw) (int *, float *, int *, float *, int *, float*);
+int BLASFUNC(zdotuw) (int *, double *, int *, double *, int *, double*);
+int BLASFUNC(zdotcw) (int *, double *, int *, double *, int *, double*);
+
+int BLASFUNC(saxpy) (int *, float *, float *, int *, float *, int *);
+int BLASFUNC(daxpy) (int *, double *, double *, int *, double *, int *);
+int BLASFUNC(qaxpy) (int *, double *, double *, int *, double *, int *);
+int BLASFUNC(caxpy) (int *, float *, float *, int *, float *, int *);
+int BLASFUNC(zaxpy) (int *, double *, double *, int *, double *, int *);
+int BLASFUNC(xaxpy) (int *, double *, double *, int *, double *, int *);
+int BLASFUNC(caxpyc)(int *, float *, float *, int *, float *, int *);
+int BLASFUNC(zaxpyc)(int *, double *, double *, int *, double *, int *);
+int BLASFUNC(xaxpyc)(int *, double *, double *, int *, double *, int *);
+
+int BLASFUNC(scopy) (int *, float *, int *, float *, int *);
+int BLASFUNC(dcopy) (int *, double *, int *, double *, int *);
+int BLASFUNC(qcopy) (int *, double *, int *, double *, int *);
+int BLASFUNC(ccopy) (int *, float *, int *, float *, int *);
+int BLASFUNC(zcopy) (int *, double *, int *, double *, int *);
+int BLASFUNC(xcopy) (int *, double *, int *, double *, int *);
+
+int BLASFUNC(sswap) (int *, float *, int *, float *, int *);
+int BLASFUNC(dswap) (int *, double *, int *, double *, int *);
+int BLASFUNC(qswap) (int *, double *, int *, double *, int *);
+int BLASFUNC(cswap) (int *, float *, int *, float *, int *);
+int BLASFUNC(zswap) (int *, double *, int *, double *, int *);
+int BLASFUNC(xswap) (int *, double *, int *, double *, int *);
+
+float BLASFUNC(sasum) (int *, float *, int *);
+float BLASFUNC(scasum)(int *, float *, int *);
+double BLASFUNC(dasum) (int *, double *, int *);
+double BLASFUNC(qasum) (int *, double *, int *);
+double BLASFUNC(dzasum)(int *, double *, int *);
+double BLASFUNC(qxasum)(int *, double *, int *);
+
+int BLASFUNC(isamax)(int *, float *, int *);
+int BLASFUNC(idamax)(int *, double *, int *);
+int BLASFUNC(iqamax)(int *, double *, int *);
+int BLASFUNC(icamax)(int *, float *, int *);
+int BLASFUNC(izamax)(int *, double *, int *);
+int BLASFUNC(ixamax)(int *, double *, int *);
+
+int BLASFUNC(ismax) (int *, float *, int *);
+int BLASFUNC(idmax) (int *, double *, int *);
+int BLASFUNC(iqmax) (int *, double *, int *);
+int BLASFUNC(icmax) (int *, float *, int *);
+int BLASFUNC(izmax) (int *, double *, int *);
+int BLASFUNC(ixmax) (int *, double *, int *);
+
+int BLASFUNC(isamin)(int *, float *, int *);
+int BLASFUNC(idamin)(int *, double *, int *);
+int BLASFUNC(iqamin)(int *, double *, int *);
+int BLASFUNC(icamin)(int *, float *, int *);
+int BLASFUNC(izamin)(int *, double *, int *);
+int BLASFUNC(ixamin)(int *, double *, int *);
+
+int BLASFUNC(ismin)(int *, float *, int *);
+int BLASFUNC(idmin)(int *, double *, int *);
+int BLASFUNC(iqmin)(int *, double *, int *);
+int BLASFUNC(icmin)(int *, float *, int *);
+int BLASFUNC(izmin)(int *, double *, int *);
+int BLASFUNC(ixmin)(int *, double *, int *);
+
+float BLASFUNC(samax) (int *, float *, int *);
+double BLASFUNC(damax) (int *, double *, int *);
+double BLASFUNC(qamax) (int *, double *, int *);
+float BLASFUNC(scamax)(int *, float *, int *);
+double BLASFUNC(dzamax)(int *, double *, int *);
+double BLASFUNC(qxamax)(int *, double *, int *);
+
+float BLASFUNC(samin) (int *, float *, int *);
+double BLASFUNC(damin) (int *, double *, int *);
+double BLASFUNC(qamin) (int *, double *, int *);
+float BLASFUNC(scamin)(int *, float *, int *);
+double BLASFUNC(dzamin)(int *, double *, int *);
+double BLASFUNC(qxamin)(int *, double *, int *);
+
+float BLASFUNC(smax) (int *, float *, int *);
+double BLASFUNC(dmax) (int *, double *, int *);
+double BLASFUNC(qmax) (int *, double *, int *);
+float BLASFUNC(scmax) (int *, float *, int *);
+double BLASFUNC(dzmax) (int *, double *, int *);
+double BLASFUNC(qxmax) (int *, double *, int *);
+
+float BLASFUNC(smin) (int *, float *, int *);
+double BLASFUNC(dmin) (int *, double *, int *);
+double BLASFUNC(qmin) (int *, double *, int *);
+float BLASFUNC(scmin) (int *, float *, int *);
+double BLASFUNC(dzmin) (int *, double *, int *);
+double BLASFUNC(qxmin) (int *, double *, int *);
+
+int BLASFUNC(sscal) (int *, float *, float *, int *);
+int BLASFUNC(dscal) (int *, double *, double *, int *);
+int BLASFUNC(qscal) (int *, double *, double *, int *);
+int BLASFUNC(cscal) (int *, float *, float *, int *);
+int BLASFUNC(zscal) (int *, double *, double *, int *);
+int BLASFUNC(xscal) (int *, double *, double *, int *);
+int BLASFUNC(csscal)(int *, float *, float *, int *);
+int BLASFUNC(zdscal)(int *, double *, double *, int *);
+int BLASFUNC(xqscal)(int *, double *, double *, int *);
+
+float BLASFUNC(snrm2) (int *, float *, int *);
+float BLASFUNC(scnrm2)(int *, float *, int *);
+
+double BLASFUNC(dnrm2) (int *, double *, int *);
+double BLASFUNC(qnrm2) (int *, double *, int *);
+double BLASFUNC(dznrm2)(int *, double *, int *);
+double BLASFUNC(qxnrm2)(int *, double *, int *);
+
+int BLASFUNC(srot) (int *, float *, int *, float *, int *, float *, float *);
+int BLASFUNC(drot) (int *, double *, int *, double *, int *, double *, double *);
+int BLASFUNC(qrot) (int *, double *, int *, double *, int *, double *, double *);
+int BLASFUNC(csrot) (int *, float *, int *, float *, int *, float *, float *);
+int BLASFUNC(zdrot) (int *, double *, int *, double *, int *, double *, double *);
+int BLASFUNC(xqrot) (int *, double *, int *, double *, int *, double *, double *);
+
+int BLASFUNC(srotg) (float *, float *, float *, float *);
+int BLASFUNC(drotg) (double *, double *, double *, double *);
+int BLASFUNC(qrotg) (double *, double *, double *, double *);
+int BLASFUNC(crotg) (float *, float *, float *, float *);
+int BLASFUNC(zrotg) (double *, double *, double *, double *);
+int BLASFUNC(xrotg) (double *, double *, double *, double *);
+
+int BLASFUNC(srotmg)(float *, float *, float *, float *, float *);
+int BLASFUNC(drotmg)(double *, double *, double *, double *, double *);
+
+int BLASFUNC(srotm) (int *, float *, int *, float *, int *, float *);
+int BLASFUNC(drotm) (int *, double *, int *, double *, int *, double *);
+int BLASFUNC(qrotm) (int *, double *, int *, double *, int *, double *);
+
+/* Level 2 routines */
+
+int BLASFUNC(sger)(int *, int *, float *, float *, int *,
+ float *, int *, float *, int *);
+int BLASFUNC(dger)(int *, int *, double *, double *, int *,
+ double *, int *, double *, int *);
+int BLASFUNC(qger)(int *, int *, double *, double *, int *,
+ double *, int *, double *, int *);
+int BLASFUNC(cgeru)(int *, int *, float *, float *, int *,
+ float *, int *, float *, int *);
+int BLASFUNC(cgerc)(int *, int *, float *, float *, int *,
+ float *, int *, float *, int *);
+int BLASFUNC(zgeru)(int *, int *, double *, double *, int *,
+ double *, int *, double *, int *);
+int BLASFUNC(zgerc)(int *, int *, double *, double *, int *,
+ double *, int *, double *, int *);
+int BLASFUNC(xgeru)(int *, int *, double *, double *, int *,
+ double *, int *, double *, int *);
+int BLASFUNC(xgerc)(int *, int *, double *, double *, int *,
+ double *, int *, double *, int *);
+
+int BLASFUNC(sgemv)(char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(dgemv)(char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(qgemv)(char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(cgemv)(char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zgemv)(char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xgemv)(char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+
+int BLASFUNC(strsv) (char *, char *, char *, int *, float *, int *,
+ float *, int *);
+int BLASFUNC(dtrsv) (char *, char *, char *, int *, double *, int *,
+ double *, int *);
+int BLASFUNC(qtrsv) (char *, char *, char *, int *, double *, int *,
+ double *, int *);
+int BLASFUNC(ctrsv) (char *, char *, char *, int *, float *, int *,
+ float *, int *);
+int BLASFUNC(ztrsv) (char *, char *, char *, int *, double *, int *,
+ double *, int *);
+int BLASFUNC(xtrsv) (char *, char *, char *, int *, double *, int *,
+ double *, int *);
+
+int BLASFUNC(stpsv) (char *, char *, char *, int *, float *, float *, int *);
+int BLASFUNC(dtpsv) (char *, char *, char *, int *, double *, double *, int *);
+int BLASFUNC(qtpsv) (char *, char *, char *, int *, double *, double *, int *);
+int BLASFUNC(ctpsv) (char *, char *, char *, int *, float *, float *, int *);
+int BLASFUNC(ztpsv) (char *, char *, char *, int *, double *, double *, int *);
+int BLASFUNC(xtpsv) (char *, char *, char *, int *, double *, double *, int *);
+
+int BLASFUNC(strmv) (char *, char *, char *, int *, float *, int *,
+ float *, int *);
+int BLASFUNC(dtrmv) (char *, char *, char *, int *, double *, int *,
+ double *, int *);
+int BLASFUNC(qtrmv) (char *, char *, char *, int *, double *, int *,
+ double *, int *);
+int BLASFUNC(ctrmv) (char *, char *, char *, int *, float *, int *,
+ float *, int *);
+int BLASFUNC(ztrmv) (char *, char *, char *, int *, double *, int *,
+ double *, int *);
+int BLASFUNC(xtrmv) (char *, char *, char *, int *, double *, int *,
+ double *, int *);
+
+int BLASFUNC(stpmv) (char *, char *, char *, int *, float *, float *, int *);
+int BLASFUNC(dtpmv) (char *, char *, char *, int *, double *, double *, int *);
+int BLASFUNC(qtpmv) (char *, char *, char *, int *, double *, double *, int *);
+int BLASFUNC(ctpmv) (char *, char *, char *, int *, float *, float *, int *);
+int BLASFUNC(ztpmv) (char *, char *, char *, int *, double *, double *, int *);
+int BLASFUNC(xtpmv) (char *, char *, char *, int *, double *, double *, int *);
+
+int BLASFUNC(stbmv) (char *, char *, char *, int *, int *, float *, int *, float *, int *);
+int BLASFUNC(dtbmv) (char *, char *, char *, int *, int *, double *, int *, double *, int *);
+int BLASFUNC(qtbmv) (char *, char *, char *, int *, int *, double *, int *, double *, int *);
+int BLASFUNC(ctbmv) (char *, char *, char *, int *, int *, float *, int *, float *, int *);
+int BLASFUNC(ztbmv) (char *, char *, char *, int *, int *, double *, int *, double *, int *);
+int BLASFUNC(xtbmv) (char *, char *, char *, int *, int *, double *, int *, double *, int *);
+
+int BLASFUNC(stbsv) (char *, char *, char *, int *, int *, float *, int *, float *, int *);
+int BLASFUNC(dtbsv) (char *, char *, char *, int *, int *, double *, int *, double *, int *);
+int BLASFUNC(qtbsv) (char *, char *, char *, int *, int *, double *, int *, double *, int *);
+int BLASFUNC(ctbsv) (char *, char *, char *, int *, int *, float *, int *, float *, int *);
+int BLASFUNC(ztbsv) (char *, char *, char *, int *, int *, double *, int *, double *, int *);
+int BLASFUNC(xtbsv) (char *, char *, char *, int *, int *, double *, int *, double *, int *);
+
+int BLASFUNC(ssymv) (char *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(dsymv) (char *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(qsymv) (char *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(csymv) (char *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zsymv) (char *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xsymv) (char *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+
+int BLASFUNC(sspmv) (char *, int *, float *, float *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(dspmv) (char *, int *, double *, double *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(qspmv) (char *, int *, double *, double *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(cspmv) (char *, int *, float *, float *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zspmv) (char *, int *, double *, double *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xspmv) (char *, int *, double *, double *,
+ double *, int *, double *, double *, int *);
+
+int BLASFUNC(ssyr) (char *, int *, float *, float *, int *,
+ float *, int *);
+int BLASFUNC(dsyr) (char *, int *, double *, double *, int *,
+ double *, int *);
+int BLASFUNC(qsyr) (char *, int *, double *, double *, int *,
+ double *, int *);
+int BLASFUNC(csyr) (char *, int *, float *, float *, int *,
+ float *, int *);
+int BLASFUNC(zsyr) (char *, int *, double *, double *, int *,
+ double *, int *);
+int BLASFUNC(xsyr) (char *, int *, double *, double *, int *,
+ double *, int *);
+
+int BLASFUNC(ssyr2) (char *, int *, float *,
+ float *, int *, float *, int *, float *, int *);
+int BLASFUNC(dsyr2) (char *, int *, double *,
+ double *, int *, double *, int *, double *, int *);
+int BLASFUNC(qsyr2) (char *, int *, double *,
+ double *, int *, double *, int *, double *, int *);
+int BLASFUNC(csyr2) (char *, int *, float *,
+ float *, int *, float *, int *, float *, int *);
+int BLASFUNC(zsyr2) (char *, int *, double *,
+ double *, int *, double *, int *, double *, int *);
+int BLASFUNC(xsyr2) (char *, int *, double *,
+ double *, int *, double *, int *, double *, int *);
+
+int BLASFUNC(sspr) (char *, int *, float *, float *, int *,
+ float *);
+int BLASFUNC(dspr) (char *, int *, double *, double *, int *,
+ double *);
+int BLASFUNC(qspr) (char *, int *, double *, double *, int *,
+ double *);
+int BLASFUNC(cspr) (char *, int *, float *, float *, int *,
+ float *);
+int BLASFUNC(zspr) (char *, int *, double *, double *, int *,
+ double *);
+int BLASFUNC(xspr) (char *, int *, double *, double *, int *,
+ double *);
+
+int BLASFUNC(sspr2) (char *, int *, float *,
+ float *, int *, float *, int *, float *);
+int BLASFUNC(dspr2) (char *, int *, double *,
+ double *, int *, double *, int *, double *);
+int BLASFUNC(qspr2) (char *, int *, double *,
+ double *, int *, double *, int *, double *);
+int BLASFUNC(cspr2) (char *, int *, float *,
+ float *, int *, float *, int *, float *);
+int BLASFUNC(zspr2) (char *, int *, double *,
+ double *, int *, double *, int *, double *);
+int BLASFUNC(xspr2) (char *, int *, double *,
+ double *, int *, double *, int *, double *);
+
+int BLASFUNC(cher) (char *, int *, float *, float *, int *,
+ float *, int *);
+int BLASFUNC(zher) (char *, int *, double *, double *, int *,
+ double *, int *);
+int BLASFUNC(xher) (char *, int *, double *, double *, int *,
+ double *, int *);
+
+int BLASFUNC(chpr) (char *, int *, float *, float *, int *, float *);
+int BLASFUNC(zhpr) (char *, int *, double *, double *, int *, double *);
+int BLASFUNC(xhpr) (char *, int *, double *, double *, int *, double *);
+
+int BLASFUNC(cher2) (char *, int *, float *,
+ float *, int *, float *, int *, float *, int *);
+int BLASFUNC(zher2) (char *, int *, double *,
+ double *, int *, double *, int *, double *, int *);
+int BLASFUNC(xher2) (char *, int *, double *,
+ double *, int *, double *, int *, double *, int *);
+
+int BLASFUNC(chpr2) (char *, int *, float *,
+ float *, int *, float *, int *, float *);
+int BLASFUNC(zhpr2) (char *, int *, double *,
+ double *, int *, double *, int *, double *);
+int BLASFUNC(xhpr2) (char *, int *, double *,
+ double *, int *, double *, int *, double *);
+
+int BLASFUNC(chemv) (char *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zhemv) (char *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xhemv) (char *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+
+int BLASFUNC(chpmv) (char *, int *, float *, float *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zhpmv) (char *, int *, double *, double *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xhpmv) (char *, int *, double *, double *,
+ double *, int *, double *, double *, int *);
+
+int BLASFUNC(snorm)(char *, int *, int *, float *, int *);
+int BLASFUNC(dnorm)(char *, int *, int *, double *, int *);
+int BLASFUNC(cnorm)(char *, int *, int *, float *, int *);
+int BLASFUNC(znorm)(char *, int *, int *, double *, int *);
+
+int BLASFUNC(sgbmv)(char *, int *, int *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(dgbmv)(char *, int *, int *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(qgbmv)(char *, int *, int *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(cgbmv)(char *, int *, int *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zgbmv)(char *, int *, int *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xgbmv)(char *, int *, int *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+
+int BLASFUNC(ssbmv)(char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(dsbmv)(char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(qsbmv)(char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(csbmv)(char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zsbmv)(char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xsbmv)(char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+
+int BLASFUNC(chbmv)(char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zhbmv)(char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xhbmv)(char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+
+/* Level 3 routines */
+
+int BLASFUNC(sgemm)(char *, char *, int *, int *, int *, float *,
+ float *, int *, float *, int *, float *, float *, int *);
+int BLASFUNC(dgemm)(char *, char *, int *, int *, int *, double *,
+ double *, int *, double *, int *, double *, double *, int *);
+int BLASFUNC(qgemm)(char *, char *, int *, int *, int *, double *,
+ double *, int *, double *, int *, double *, double *, int *);
+int BLASFUNC(cgemm)(char *, char *, int *, int *, int *, float *,
+ float *, int *, float *, int *, float *, float *, int *);
+int BLASFUNC(zgemm)(char *, char *, int *, int *, int *, double *,
+ double *, int *, double *, int *, double *, double *, int *);
+int BLASFUNC(xgemm)(char *, char *, int *, int *, int *, double *,
+ double *, int *, double *, int *, double *, double *, int *);
+
+int BLASFUNC(cgemm3m)(char *, char *, int *, int *, int *, float *,
+ float *, int *, float *, int *, float *, float *, int *);
+int BLASFUNC(zgemm3m)(char *, char *, int *, int *, int *, double *,
+ double *, int *, double *, int *, double *, double *, int *);
+int BLASFUNC(xgemm3m)(char *, char *, int *, int *, int *, double *,
+ double *, int *, double *, int *, double *, double *, int *);
+
+int BLASFUNC(sge2mm)(char *, char *, char *, int *, int *,
+ float *, float *, int *, float *, int *,
+ float *, float *, int *);
+int BLASFUNC(dge2mm)(char *, char *, char *, int *, int *,
+ double *, double *, int *, double *, int *,
+ double *, double *, int *);
+int BLASFUNC(cge2mm)(char *, char *, char *, int *, int *,
+ float *, float *, int *, float *, int *,
+ float *, float *, int *);
+int BLASFUNC(zge2mm)(char *, char *, char *, int *, int *,
+ double *, double *, int *, double *, int *,
+ double *, double *, int *);
+
+int BLASFUNC(strsm)(char *, char *, char *, char *, int *, int *,
+ float *, float *, int *, float *, int *);
+int BLASFUNC(dtrsm)(char *, char *, char *, char *, int *, int *,
+ double *, double *, int *, double *, int *);
+int BLASFUNC(qtrsm)(char *, char *, char *, char *, int *, int *,
+ double *, double *, int *, double *, int *);
+int BLASFUNC(ctrsm)(char *, char *, char *, char *, int *, int *,
+ float *, float *, int *, float *, int *);
+int BLASFUNC(ztrsm)(char *, char *, char *, char *, int *, int *,
+ double *, double *, int *, double *, int *);
+int BLASFUNC(xtrsm)(char *, char *, char *, char *, int *, int *,
+ double *, double *, int *, double *, int *);
+
+int BLASFUNC(strmm)(char *, char *, char *, char *, int *, int *,
+ float *, float *, int *, float *, int *);
+int BLASFUNC(dtrmm)(char *, char *, char *, char *, int *, int *,
+ double *, double *, int *, double *, int *);
+int BLASFUNC(qtrmm)(char *, char *, char *, char *, int *, int *,
+ double *, double *, int *, double *, int *);
+int BLASFUNC(ctrmm)(char *, char *, char *, char *, int *, int *,
+ float *, float *, int *, float *, int *);
+int BLASFUNC(ztrmm)(char *, char *, char *, char *, int *, int *,
+ double *, double *, int *, double *, int *);
+int BLASFUNC(xtrmm)(char *, char *, char *, char *, int *, int *,
+ double *, double *, int *, double *, int *);
+
+int BLASFUNC(ssymm)(char *, char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(dsymm)(char *, char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(qsymm)(char *, char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(csymm)(char *, char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zsymm)(char *, char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xsymm)(char *, char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+
+int BLASFUNC(csymm3m)(char *, char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zsymm3m)(char *, char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xsymm3m)(char *, char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+
+int BLASFUNC(ssyrk)(char *, char *, int *, int *, float *, float *, int *,
+ float *, float *, int *);
+int BLASFUNC(dsyrk)(char *, char *, int *, int *, double *, double *, int *,
+ double *, double *, int *);
+int BLASFUNC(qsyrk)(char *, char *, int *, int *, double *, double *, int *,
+ double *, double *, int *);
+int BLASFUNC(csyrk)(char *, char *, int *, int *, float *, float *, int *,
+ float *, float *, int *);
+int BLASFUNC(zsyrk)(char *, char *, int *, int *, double *, double *, int *,
+ double *, double *, int *);
+int BLASFUNC(xsyrk)(char *, char *, int *, int *, double *, double *, int *,
+ double *, double *, int *);
+
+int BLASFUNC(ssyr2k)(char *, char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(dsyr2k)(char *, char *, int *, int *, double *, double *, int *,
+ double*, int *, double *, double *, int *);
+int BLASFUNC(qsyr2k)(char *, char *, int *, int *, double *, double *, int *,
+ double*, int *, double *, double *, int *);
+int BLASFUNC(csyr2k)(char *, char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zsyr2k)(char *, char *, int *, int *, double *, double *, int *,
+ double*, int *, double *, double *, int *);
+int BLASFUNC(xsyr2k)(char *, char *, int *, int *, double *, double *, int *,
+ double*, int *, double *, double *, int *);
+
+int BLASFUNC(chemm)(char *, char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zhemm)(char *, char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xhemm)(char *, char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+
+int BLASFUNC(chemm3m)(char *, char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zhemm3m)(char *, char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+int BLASFUNC(xhemm3m)(char *, char *, int *, int *, double *, double *, int *,
+ double *, int *, double *, double *, int *);
+
+int BLASFUNC(cherk)(char *, char *, int *, int *, float *, float *, int *,
+ float *, float *, int *);
+int BLASFUNC(zherk)(char *, char *, int *, int *, double *, double *, int *,
+ double *, double *, int *);
+int BLASFUNC(xherk)(char *, char *, int *, int *, double *, double *, int *,
+ double *, double *, int *);
+
+int BLASFUNC(cher2k)(char *, char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zher2k)(char *, char *, int *, int *, double *, double *, int *,
+ double*, int *, double *, double *, int *);
+int BLASFUNC(xher2k)(char *, char *, int *, int *, double *, double *, int *,
+ double*, int *, double *, double *, int *);
+int BLASFUNC(cher2m)(char *, char *, char *, int *, int *, float *, float *, int *,
+ float *, int *, float *, float *, int *);
+int BLASFUNC(zher2m)(char *, char *, char *, int *, int *, double *, double *, int *,
+ double*, int *, double *, double *, int *);
+int BLASFUNC(xher2m)(char *, char *, char *, int *, int *, double *, double *, int *,
+ double*, int *, double *, double *, int *);
+
+int BLASFUNC(sgemt)(char *, int *, int *, float *, float *, int *,
+ float *, int *);
+int BLASFUNC(dgemt)(char *, int *, int *, double *, double *, int *,
+ double *, int *);
+int BLASFUNC(cgemt)(char *, int *, int *, float *, float *, int *,
+ float *, int *);
+int BLASFUNC(zgemt)(char *, int *, int *, double *, double *, int *,
+ double *, int *);
+
+int BLASFUNC(sgema)(char *, char *, int *, int *, float *,
+ float *, int *, float *, float *, int *, float *, int *);
+int BLASFUNC(dgema)(char *, char *, int *, int *, double *,
+ double *, int *, double*, double *, int *, double*, int *);
+int BLASFUNC(cgema)(char *, char *, int *, int *, float *,
+ float *, int *, float *, float *, int *, float *, int *);
+int BLASFUNC(zgema)(char *, char *, int *, int *, double *,
+ double *, int *, double*, double *, int *, double*, int *);
+
+int BLASFUNC(sgems)(char *, char *, int *, int *, float *,
+ float *, int *, float *, float *, int *, float *, int *);
+int BLASFUNC(dgems)(char *, char *, int *, int *, double *,
+ double *, int *, double*, double *, int *, double*, int *);
+int BLASFUNC(cgems)(char *, char *, int *, int *, float *,
+ float *, int *, float *, float *, int *, float *, int *);
+int BLASFUNC(zgems)(char *, char *, int *, int *, double *,
+ double *, int *, double*, double *, int *, double*, int *);
+
+int BLASFUNC(sgetf2)(int *, int *, float *, int *, int *, int *);
+int BLASFUNC(dgetf2)(int *, int *, double *, int *, int *, int *);
+int BLASFUNC(qgetf2)(int *, int *, double *, int *, int *, int *);
+int BLASFUNC(cgetf2)(int *, int *, float *, int *, int *, int *);
+int BLASFUNC(zgetf2)(int *, int *, double *, int *, int *, int *);
+int BLASFUNC(xgetf2)(int *, int *, double *, int *, int *, int *);
+
+int BLASFUNC(sgetrf)(int *, int *, float *, int *, int *, int *);
+int BLASFUNC(dgetrf)(int *, int *, double *, int *, int *, int *);
+int BLASFUNC(qgetrf)(int *, int *, double *, int *, int *, int *);
+int BLASFUNC(cgetrf)(int *, int *, float *, int *, int *, int *);
+int BLASFUNC(zgetrf)(int *, int *, double *, int *, int *, int *);
+int BLASFUNC(xgetrf)(int *, int *, double *, int *, int *, int *);
+
+int BLASFUNC(slaswp)(int *, float *, int *, int *, int *, int *, int *);
+int BLASFUNC(dlaswp)(int *, double *, int *, int *, int *, int *, int *);
+int BLASFUNC(qlaswp)(int *, double *, int *, int *, int *, int *, int *);
+int BLASFUNC(claswp)(int *, float *, int *, int *, int *, int *, int *);
+int BLASFUNC(zlaswp)(int *, double *, int *, int *, int *, int *, int *);
+int BLASFUNC(xlaswp)(int *, double *, int *, int *, int *, int *, int *);
+
+int BLASFUNC(sgetrs)(char *, int *, int *, float *, int *, int *, float *, int *, int *);
+int BLASFUNC(dgetrs)(char *, int *, int *, double *, int *, int *, double *, int *, int *);
+int BLASFUNC(qgetrs)(char *, int *, int *, double *, int *, int *, double *, int *, int *);
+int BLASFUNC(cgetrs)(char *, int *, int *, float *, int *, int *, float *, int *, int *);
+int BLASFUNC(zgetrs)(char *, int *, int *, double *, int *, int *, double *, int *, int *);
+int BLASFUNC(xgetrs)(char *, int *, int *, double *, int *, int *, double *, int *, int *);
+
+int BLASFUNC(sgesv)(int *, int *, float *, int *, int *, float *, int *, int *);
+int BLASFUNC(dgesv)(int *, int *, double *, int *, int *, double*, int *, int *);
+int BLASFUNC(qgesv)(int *, int *, double *, int *, int *, double*, int *, int *);
+int BLASFUNC(cgesv)(int *, int *, float *, int *, int *, float *, int *, int *);
+int BLASFUNC(zgesv)(int *, int *, double *, int *, int *, double*, int *, int *);
+int BLASFUNC(xgesv)(int *, int *, double *, int *, int *, double*, int *, int *);
+
+int BLASFUNC(spotf2)(char *, int *, float *, int *, int *);
+int BLASFUNC(dpotf2)(char *, int *, double *, int *, int *);
+int BLASFUNC(qpotf2)(char *, int *, double *, int *, int *);
+int BLASFUNC(cpotf2)(char *, int *, float *, int *, int *);
+int BLASFUNC(zpotf2)(char *, int *, double *, int *, int *);
+int BLASFUNC(xpotf2)(char *, int *, double *, int *, int *);
+
+int BLASFUNC(spotrf)(char *, int *, float *, int *, int *);
+int BLASFUNC(dpotrf)(char *, int *, double *, int *, int *);
+int BLASFUNC(qpotrf)(char *, int *, double *, int *, int *);
+int BLASFUNC(cpotrf)(char *, int *, float *, int *, int *);
+int BLASFUNC(zpotrf)(char *, int *, double *, int *, int *);
+int BLASFUNC(xpotrf)(char *, int *, double *, int *, int *);
+
+int BLASFUNC(slauu2)(char *, int *, float *, int *, int *);
+int BLASFUNC(dlauu2)(char *, int *, double *, int *, int *);
+int BLASFUNC(qlauu2)(char *, int *, double *, int *, int *);
+int BLASFUNC(clauu2)(char *, int *, float *, int *, int *);
+int BLASFUNC(zlauu2)(char *, int *, double *, int *, int *);
+int BLASFUNC(xlauu2)(char *, int *, double *, int *, int *);
+
+int BLASFUNC(slauum)(char *, int *, float *, int *, int *);
+int BLASFUNC(dlauum)(char *, int *, double *, int *, int *);
+int BLASFUNC(qlauum)(char *, int *, double *, int *, int *);
+int BLASFUNC(clauum)(char *, int *, float *, int *, int *);
+int BLASFUNC(zlauum)(char *, int *, double *, int *, int *);
+int BLASFUNC(xlauum)(char *, int *, double *, int *, int *);
+
+int BLASFUNC(strti2)(char *, char *, int *, float *, int *, int *);
+int BLASFUNC(dtrti2)(char *, char *, int *, double *, int *, int *);
+int BLASFUNC(qtrti2)(char *, char *, int *, double *, int *, int *);
+int BLASFUNC(ctrti2)(char *, char *, int *, float *, int *, int *);
+int BLASFUNC(ztrti2)(char *, char *, int *, double *, int *, int *);
+int BLASFUNC(xtrti2)(char *, char *, int *, double *, int *, int *);
+
+int BLASFUNC(strtri)(char *, char *, int *, float *, int *, int *);
+int BLASFUNC(dtrtri)(char *, char *, int *, double *, int *, int *);
+int BLASFUNC(qtrtri)(char *, char *, int *, double *, int *, int *);
+int BLASFUNC(ctrtri)(char *, char *, int *, float *, int *, int *);
+int BLASFUNC(ztrtri)(char *, char *, int *, double *, int *, int *);
+int BLASFUNC(xtrtri)(char *, char *, int *, double *, int *, int *);
+
+int BLASFUNC(spotri)(char *, int *, float *, int *, int *);
+int BLASFUNC(dpotri)(char *, int *, double *, int *, int *);
+int BLASFUNC(qpotri)(char *, int *, double *, int *, int *);
+int BLASFUNC(cpotri)(char *, int *, float *, int *, int *);
+int BLASFUNC(zpotri)(char *, int *, double *, int *, int *);
+int BLASFUNC(xpotri)(char *, int *, double *, int *, int *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/extern/Eigen3/Eigen/src/plugins/ArrayCwiseBinaryOps.h b/extern/Eigen3/Eigen/src/plugins/ArrayCwiseBinaryOps.h
index 7d509e78f3a..5b979ebf89d 100644
--- a/extern/Eigen3/Eigen/src/plugins/ArrayCwiseBinaryOps.h
+++ b/extern/Eigen3/Eigen/src/plugins/ArrayCwiseBinaryOps.h
@@ -29,6 +29,16 @@ operator/(const EIGEN_CURRENT_STORAGE_BASE_CLASS<OtherDerived> &other) const
*/
EIGEN_MAKE_CWISE_BINARY_OP(min,internal::scalar_min_op)
+/** \returns an expression of the coefficient-wise min of \c *this and scalar \a other
+ *
+ * \sa max()
+ */
+EIGEN_STRONG_INLINE const CwiseBinaryOp<internal::scalar_min_op<Scalar>, const Derived, const ConstantReturnType>
+(min)(const Scalar &other) const
+{
+ return (min)(Derived::PlainObject::Constant(rows(), cols(), other));
+}
+
/** \returns an expression of the coefficient-wise max of \c *this and \a other
*
* Example: \include Cwise_max.cpp
@@ -38,6 +48,16 @@ EIGEN_MAKE_CWISE_BINARY_OP(min,internal::scalar_min_op)
*/
EIGEN_MAKE_CWISE_BINARY_OP(max,internal::scalar_max_op)
+/** \returns an expression of the coefficient-wise max of \c *this and scalar \a other
+ *
+ * \sa min()
+ */
+EIGEN_STRONG_INLINE const CwiseBinaryOp<internal::scalar_max_op<Scalar>, const Derived, const ConstantReturnType>
+(max)(const Scalar &other) const
+{
+ return (max)(Derived::PlainObject::Constant(rows(), cols(), other));
+}
+
/** \returns an expression of the coefficient-wise \< operator of *this and \a other
*
* Example: \include Cwise_less.cpp
@@ -141,3 +161,39 @@ operator-(const Scalar& scalar,const EIGEN_CURRENT_STORAGE_BASE_CLASS<Derived>&
{
return (-other) + scalar;
}
+
+/** \returns an expression of the coefficient-wise && operator of *this and \a other
+ *
+ * \warning this operator is for expression of bool only.
+ *
+ * Example: \include Cwise_boolean_and.cpp
+ * Output: \verbinclude Cwise_boolean_and.out
+ *
+ * \sa operator||(), select()
+ */
+template<typename OtherDerived>
+inline const CwiseBinaryOp<internal::scalar_boolean_and_op, const Derived, const OtherDerived>
+operator&&(const EIGEN_CURRENT_STORAGE_BASE_CLASS<OtherDerived> &other) const
+{
+ EIGEN_STATIC_ASSERT((internal::is_same<bool,Scalar>::value && internal::is_same<bool,typename OtherDerived::Scalar>::value),
+ THIS_METHOD_IS_ONLY_FOR_EXPRESSIONS_OF_BOOL);
+ return CwiseBinaryOp<internal::scalar_boolean_and_op, const Derived, const OtherDerived>(derived(),other.derived());
+}
+
+/** \returns an expression of the coefficient-wise || operator of *this and \a other
+ *
+ * \warning this operator is for expression of bool only.
+ *
+ * Example: \include Cwise_boolean_or.cpp
+ * Output: \verbinclude Cwise_boolean_or.out
+ *
+ * \sa operator&&(), select()
+ */
+template<typename OtherDerived>
+inline const CwiseBinaryOp<internal::scalar_boolean_or_op, const Derived, const OtherDerived>
+operator||(const EIGEN_CURRENT_STORAGE_BASE_CLASS<OtherDerived> &other) const
+{
+ EIGEN_STATIC_ASSERT((internal::is_same<bool,Scalar>::value && internal::is_same<bool,typename OtherDerived::Scalar>::value),
+ THIS_METHOD_IS_ONLY_FOR_EXPRESSIONS_OF_BOOL);
+ return CwiseBinaryOp<internal::scalar_boolean_or_op, const Derived, const OtherDerived>(derived(),other.derived());
+}
diff --git a/extern/Eigen3/Eigen/src/plugins/BlockMethods.h b/extern/Eigen3/Eigen/src/plugins/BlockMethods.h
index 4eba933388a..ef224001a54 100644
--- a/extern/Eigen3/Eigen/src/plugins/BlockMethods.h
+++ b/extern/Eigen3/Eigen/src/plugins/BlockMethods.h
@@ -4,24 +4,9 @@
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BLOCKMETHODS_H
#define EIGEN_BLOCKMETHODS_H
diff --git a/extern/Eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h b/extern/Eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h
index 8f7765e72bd..688d2244088 100644
--- a/extern/Eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h
+++ b/extern/Eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h
@@ -4,24 +4,9 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// This file is a base class plugin containing common coefficient wise functions.
diff --git a/extern/Eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h b/extern/Eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h
index 941d5153c59..08e931aaddd 100644
--- a/extern/Eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h
+++ b/extern/Eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h
@@ -4,24 +4,9 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// This file is a base class plugin containing common coefficient wise functions.
diff --git a/extern/Eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h b/extern/Eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h
index 35183f91f80..3a737df7b86 100644
--- a/extern/Eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h
+++ b/extern/Eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h
@@ -4,24 +4,9 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// This file is a base class plugin containing matrix specifics coefficient wise functions.
@@ -91,6 +76,16 @@ cwiseMin(const EIGEN_CURRENT_STORAGE_BASE_CLASS<OtherDerived> &other) const
return CwiseBinaryOp<internal::scalar_min_op<Scalar>, const Derived, const OtherDerived>(derived(), other.derived());
}
+/** \returns an expression of the coefficient-wise min of *this and scalar \a other
+ *
+ * \sa class CwiseBinaryOp, min()
+ */
+EIGEN_STRONG_INLINE const CwiseBinaryOp<internal::scalar_min_op<Scalar>, const Derived, const ConstantReturnType>
+cwiseMin(const Scalar &other) const
+{
+ return cwiseMin(Derived::PlainObject::Constant(rows(), cols(), other));
+}
+
/** \returns an expression of the coefficient-wise max of *this and \a other
*
* Example: \include MatrixBase_cwiseMax.cpp
@@ -105,6 +100,17 @@ cwiseMax(const EIGEN_CURRENT_STORAGE_BASE_CLASS<OtherDerived> &other) const
return CwiseBinaryOp<internal::scalar_max_op<Scalar>, const Derived, const OtherDerived>(derived(), other.derived());
}
+/** \returns an expression of the coefficient-wise max of *this and scalar \a other
+ *
+ * \sa class CwiseBinaryOp, min()
+ */
+EIGEN_STRONG_INLINE const CwiseBinaryOp<internal::scalar_max_op<Scalar>, const Derived, const ConstantReturnType>
+cwiseMax(const Scalar &other) const
+{
+ return cwiseMax(Derived::PlainObject::Constant(rows(), cols(), other));
+}
+
+
/** \returns an expression of the coefficient-wise quotient of *this and \a other
*
* Example: \include MatrixBase_cwiseQuotient.cpp
diff --git a/extern/Eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h b/extern/Eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h
index a3d9a0e1465..0cf0640bae6 100644
--- a/extern/Eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h
+++ b/extern/Eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h
@@ -4,24 +4,9 @@
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
-// Eigen is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 3 of the License, or (at your option) any later version.
-//
-// Alternatively, you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation; either version 2 of
-// the License, or (at your option) any later version.
-//
-// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License and a copy of the GNU General Public License along with
-// Eigen. If not, see <http://www.gnu.org/licenses/>.
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// This file is a base class plugin containing matrix specifics coefficient wise functions.
diff --git a/extern/bullet2/patches/convex_hull.patch b/extern/bullet2/patches/convex_hull.patch
new file mode 100644
index 00000000000..1b2978221fb
--- /dev/null
+++ b/extern/bullet2/patches/convex_hull.patch
@@ -0,0 +1,127 @@
+Index: extern/bullet2/src/Bullet-C-Api.h
+===================================================================
+--- extern/bullet2/src/Bullet-C-Api.h (revision 51556)
++++ extern/bullet2/src/Bullet-C-Api.h (working copy)
+@@ -167,6 +167,16 @@ extern "C" {
+ // needed for source/blender/blenkernel/intern/collision.c
+ double plNearestPoints(float p1[3], float p2[3], float p3[3], float q1[3], float q2[3], float q3[3], float *pa, float *pb, float normal[3]);
+
++
++ /* Convex Hull */
++ PL_DECLARE_HANDLE(plConvexHull);
++ plConvexHull plConvexHullCompute(float (*coords)[3], int count);
++ int plConvexHullNumVertices(plConvexHull hull);
++ int plConvexHullNumFaces(plConvexHull hull);
++ void plConvexHullGetVertex(plConvexHull hull, int n, float coords[3], int *original_index);
++ int plConvexHullGetFaceSize(plConvexHull hull, int n);
++ void plConvexHullGetFaceVertices(plConvexHull hull, int n, int *vertices);
++
+ #ifdef __cplusplus
+ }
+ #endif
+Index: extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp
+===================================================================
+--- extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp (revision 51556)
++++ extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp (working copy)
+@@ -23,7 +23,7 @@ subject to the following restrictions:
+ #include "Bullet-C-Api.h"
+ #include "btBulletDynamicsCommon.h"
+ #include "LinearMath/btAlignedAllocator.h"
+-
++#include "LinearMath/btConvexHullComputer.h"
+
+
+ #include "LinearMath/btVector3.h"
+@@ -403,3 +403,60 @@ double plNearestPoints(float p1[3], float p2[3], float p3[3], float q1[3], float
+ return -1.0f;
+ }
+
++// Convex hull
++plConvexHull plConvexHullCompute(float (*coords)[3], int count)
++{
++ btConvexHullComputer *computer = new btConvexHullComputer;
++ computer->compute(reinterpret_cast< float* >(coords),
++ sizeof(*coords), count, 0, 0);
++ return reinterpret_cast<plConvexHull>(computer);
++}
++
++int plConvexHullNumVertices(plConvexHull hull)
++{
++ btConvexHullComputer *computer(reinterpret_cast< btConvexHullComputer* >(hull));
++ return computer->vertices.size();
++}
++
++int plConvexHullNumFaces(plConvexHull hull)
++{
++ btConvexHullComputer *computer(reinterpret_cast< btConvexHullComputer* >(hull));
++ return computer->faces.size();
++}
++
++void plConvexHullGetVertex(plConvexHull hull, int n, float coords[3],
++ int *original_index)
++{
++ btConvexHullComputer *computer(reinterpret_cast< btConvexHullComputer* >(hull));
++ const btVector3 &v(computer->vertices[n]);
++ coords[0] = v[0];
++ coords[1] = v[1];
++ coords[2] = v[2];
++ (*original_index) = computer->original_vertex_index[n];
++}
++
++int plConvexHullGetFaceSize(plConvexHull hull, int n)
++{
++ btConvexHullComputer *computer(reinterpret_cast< btConvexHullComputer* >(hull));
++ const btConvexHullComputer::Edge *e_orig, *e;
++ int count;
++
++ for (e_orig = &computer->edges[computer->faces[n]], e = e_orig, count = 0;
++ count == 0 || e != e_orig;
++ e = e->getNextEdgeOfFace(), count++);
++ return count;
++}
++
++void plConvexHullGetFaceVertices(plConvexHull hull, int n, int *vertices)
++{
++ btConvexHullComputer *computer(reinterpret_cast< btConvexHullComputer* >(hull));
++ const btConvexHullComputer::Edge *e_orig, *e;
++ int count;
++
++ for (e_orig = &computer->edges[computer->faces[n]], e = e_orig, count = 0;
++ count == 0 || e != e_orig;
++ e = e->getNextEdgeOfFace(), count++)
++ {
++ vertices[count] = e->getTargetVertex();
++ }
++}
+Index: extern/bullet2/src/LinearMath/btConvexHullComputer.cpp
+===================================================================
+--- extern/bullet2/src/LinearMath/btConvexHullComputer.cpp (revision 51556)
++++ extern/bullet2/src/LinearMath/btConvexHullComputer.cpp (working copy)
+@@ -2661,6 +2661,7 @@ btScalar btConvexHullComputer::compute(const void* coords, bool doubleCoords, in
+ }
+
+ vertices.resize(0);
++ original_vertex_index.resize(0);
+ edges.resize(0);
+ faces.resize(0);
+
+@@ -2671,6 +2672,7 @@ btScalar btConvexHullComputer::compute(const void* coords, bool doubleCoords, in
+ {
+ btConvexHullInternal::Vertex* v = oldVertices[copied];
+ vertices.push_back(hull.getCoordinates(v));
++ original_vertex_index.push_back(v->point.index);
+ btConvexHullInternal::Edge* firstEdge = v->edges;
+ if (firstEdge)
+ {
+Index: extern/bullet2/src/LinearMath/btConvexHullComputer.h
+===================================================================
+--- extern/bullet2/src/LinearMath/btConvexHullComputer.h (revision 51556)
++++ extern/bullet2/src/LinearMath/btConvexHullComputer.h (working copy)
+@@ -67,6 +67,7 @@ class btConvexHullComputer
+
+ // Vertices of the output hull
+ btAlignedObjectArray<btVector3> vertices;
++ btAlignedObjectArray<int> original_vertex_index;
+
+ // Edges of the output hull
+ btAlignedObjectArray<Edge> edges;
diff --git a/extern/bullet2/readme.txt b/extern/bullet2/readme.txt
index 343cb104c4d..7f5a7f1e163 100644
--- a/extern/bullet2/readme.txt
+++ b/extern/bullet2/readme.txt
@@ -14,6 +14,8 @@ Apply patches/make_id.patch to prevent duplicated define of MAKE_ID macro in ble
side and bullet side.
Sergey
-Apply patches/ghost_character.path to prevent characters from colliding with ghost objects.
+Apply patches/ghost_character.patch to prevent characters from colliding with ghost objects.
Mitchell
+Apply patches/convex_hull.patch to add access to the convex hull
+operation, used in the BMesh convex hull operator.
diff --git a/extern/bullet2/src/Bullet-C-Api.h b/extern/bullet2/src/Bullet-C-Api.h
index f27a17d51f7..2eabf3840e1 100644
--- a/extern/bullet2/src/Bullet-C-Api.h
+++ b/extern/bullet2/src/Bullet-C-Api.h
@@ -167,6 +167,16 @@ extern "C" {
// needed for source/blender/blenkernel/intern/collision.c
double plNearestPoints(float p1[3], float p2[3], float p3[3], float q1[3], float q2[3], float q3[3], float *pa, float *pb, float normal[3]);
+
+ /* Convex Hull */
+ PL_DECLARE_HANDLE(plConvexHull);
+ plConvexHull plConvexHullCompute(float (*coords)[3], int count);
+ int plConvexHullNumVertices(plConvexHull hull);
+ int plConvexHullNumFaces(plConvexHull hull);
+ void plConvexHullGetVertex(plConvexHull hull, int n, float coords[3], int *original_index);
+ int plConvexHullGetFaceSize(plConvexHull hull, int n);
+ void plConvexHullGetFaceVertices(plConvexHull hull, int n, int *vertices);
+
#ifdef __cplusplus
}
#endif
diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp b/extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp
index bd8e2748383..cf735569a9d 100644
--- a/extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp
+++ b/extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp
@@ -23,7 +23,7 @@ subject to the following restrictions:
#include "Bullet-C-Api.h"
#include "btBulletDynamicsCommon.h"
#include "LinearMath/btAlignedAllocator.h"
-
+#include "LinearMath/btConvexHullComputer.h"
#include "LinearMath/btVector3.h"
@@ -403,3 +403,60 @@ double plNearestPoints(float p1[3], float p2[3], float p3[3], float q1[3], float
return -1.0f;
}
+// Convex hull
+plConvexHull plConvexHullCompute(float (*coords)[3], int count)
+{
+ btConvexHullComputer *computer = new btConvexHullComputer;
+ computer->compute(reinterpret_cast< float* >(coords),
+ sizeof(*coords), count, 0, 0);
+ return reinterpret_cast<plConvexHull>(computer);
+}
+
+int plConvexHullNumVertices(plConvexHull hull)
+{
+ btConvexHullComputer *computer(reinterpret_cast< btConvexHullComputer* >(hull));
+ return computer->vertices.size();
+}
+
+int plConvexHullNumFaces(plConvexHull hull)
+{
+ btConvexHullComputer *computer(reinterpret_cast< btConvexHullComputer* >(hull));
+ return computer->faces.size();
+}
+
+void plConvexHullGetVertex(plConvexHull hull, int n, float coords[3],
+ int *original_index)
+{
+ btConvexHullComputer *computer(reinterpret_cast< btConvexHullComputer* >(hull));
+ const btVector3 &v(computer->vertices[n]);
+ coords[0] = v[0];
+ coords[1] = v[1];
+ coords[2] = v[2];
+ (*original_index) = computer->original_vertex_index[n];
+}
+
+int plConvexHullGetFaceSize(plConvexHull hull, int n)
+{
+ btConvexHullComputer *computer(reinterpret_cast< btConvexHullComputer* >(hull));
+ const btConvexHullComputer::Edge *e_orig, *e;
+ int count;
+
+ for (e_orig = &computer->edges[computer->faces[n]], e = e_orig, count = 0;
+ count == 0 || e != e_orig;
+ e = e->getNextEdgeOfFace(), count++);
+ return count;
+}
+
+void plConvexHullGetFaceVertices(plConvexHull hull, int n, int *vertices)
+{
+ btConvexHullComputer *computer(reinterpret_cast< btConvexHullComputer* >(hull));
+ const btConvexHullComputer::Edge *e_orig, *e;
+ int count;
+
+ for (e_orig = &computer->edges[computer->faces[n]], e = e_orig, count = 0;
+ count == 0 || e != e_orig;
+ e = e->getNextEdgeOfFace(), count++)
+ {
+ vertices[count] = e->getTargetVertex();
+ }
+}
diff --git a/extern/bullet2/src/LinearMath/btConvexHullComputer.cpp b/extern/bullet2/src/LinearMath/btConvexHullComputer.cpp
index c03c901c051..4fd81dac107 100644
--- a/extern/bullet2/src/LinearMath/btConvexHullComputer.cpp
+++ b/extern/bullet2/src/LinearMath/btConvexHullComputer.cpp
@@ -2661,6 +2661,7 @@ btScalar btConvexHullComputer::compute(const void* coords, bool doubleCoords, in
}
vertices.resize(0);
+ original_vertex_index.resize(0);
edges.resize(0);
faces.resize(0);
@@ -2671,6 +2672,7 @@ btScalar btConvexHullComputer::compute(const void* coords, bool doubleCoords, in
{
btConvexHullInternal::Vertex* v = oldVertices[copied];
vertices.push_back(hull.getCoordinates(v));
+ original_vertex_index.push_back(v->point.index);
btConvexHullInternal::Edge* firstEdge = v->edges;
if (firstEdge)
{
diff --git a/extern/bullet2/src/LinearMath/btConvexHullComputer.h b/extern/bullet2/src/LinearMath/btConvexHullComputer.h
index 7240ac4fb52..6871ce80e00 100644
--- a/extern/bullet2/src/LinearMath/btConvexHullComputer.h
+++ b/extern/bullet2/src/LinearMath/btConvexHullComputer.h
@@ -67,6 +67,7 @@ class btConvexHullComputer
// Vertices of the output hull
btAlignedObjectArray<btVector3> vertices;
+ btAlignedObjectArray<int> original_vertex_index;
// Edges of the output hull
btAlignedObjectArray<Edge> edges;
diff --git a/extern/carve/CMakeLists.txt b/extern/carve/CMakeLists.txt
index 3916047ff32..5e917ac1e44 100644
--- a/extern/carve/CMakeLists.txt
+++ b/extern/carve/CMakeLists.txt
@@ -158,7 +158,7 @@ if(WITH_BOOST)
-DCARVE_SYSTEM_BOOST
)
- list(APPEND INC
+ list(APPEND INC_SYS
${BOOST_INCLUDE_DIR}
)
endif()
diff --git a/extern/libmv/CMakeLists.txt b/extern/libmv/CMakeLists.txt
index 60cd84d89d4..38be34add75 100644
--- a/extern/libmv/CMakeLists.txt
+++ b/extern/libmv/CMakeLists.txt
@@ -28,31 +28,18 @@
set(INC
.
- ../Eigen3
- third_party/ssba
- third_party/ldl/Include
../colamd/Include
third_party/ceres/include
)
set(INC_SYS
+ ../Eigen3
+ third_party/ssba
+ third_party/ldl/Include
${PNG_INCLUDE_DIR}
${ZLIB_INCLUDE_DIRS}
)
-
-# XXX - FIXME
-# this is a momentary hack to find unwind.h in 10.6.sdk
-if(APPLE)
- if(${CMAKE_OSX_DEPLOYMENT_TARGET} STREQUAL "10.6")
- list(APPEND INC_SYS
- ${CMAKE_OSX_SYSROOT}/Developer/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin10/4.2.1/include
- )
- endif()
-endif()
-# XXX - END
-
-
set(SRC
libmv-capi.cpp
libmv/image/array_nd.cc
diff --git a/extern/libmv/bundle.sh b/extern/libmv/bundle.sh
index 3f877508c46..1e386ec8096 100755
--- a/extern/libmv/bundle.sh
+++ b/extern/libmv/bundle.sh
@@ -124,14 +124,14 @@ cat > CMakeLists.txt << EOF
set(INC
.
- ../Eigen3
- third_party/ssba
- third_party/ldl/Include
../colamd/Include
third_party/ceres/include
)
set(INC_SYS
+ ../Eigen3
+ third_party/ssba
+ third_party/ldl/Include
\${PNG_INCLUDE_DIR}
\${ZLIB_INCLUDE_DIRS}
)
diff --git a/extern/libmv/libmv-capi.cpp b/extern/libmv/libmv-capi.cpp
index 3d3b7398c9b..a15927f881d 100644
--- a/extern/libmv/libmv-capi.cpp
+++ b/extern/libmv/libmv-capi.cpp
@@ -523,7 +523,7 @@ int libmv_refineParametersAreValid(int parameters) {
LIBMV_REFINE_RADIAL_DISTORTION_K1));
}
-void libmv_solveRefineIntrinsics(libmv::Tracks *tracks, libmv::CameraIntrinsics *intrinsics,
+static void libmv_solveRefineIntrinsics(libmv::Tracks *tracks, libmv::CameraIntrinsics *intrinsics,
libmv::EuclideanReconstruction *reconstruction, int refine_intrinsics,
reconstruct_progress_update_cb progress_update_callback, void *callback_customdata)
{
@@ -550,7 +550,8 @@ void libmv_solveRefineIntrinsics(libmv::Tracks *tracks, libmv::CameraIntrinsics
}
libmv_Reconstruction *libmv_solveReconstruction(libmv_Tracks *tracks, int keyframe1, int keyframe2,
- int refine_intrinsics, double focal_length, double principal_x, double principal_y, double k1, double k2, double k3,
+ int refine_intrinsics, double focal_length, double principal_x, double principal_y,
+ double k1, double k2, double k3, struct libmv_reconstructionOptions *options,
reconstruct_progress_update_cb progress_update_callback, void *callback_customdata)
{
/* Invert the camera intrinsics. */
@@ -558,6 +559,7 @@ libmv_Reconstruction *libmv_solveReconstruction(libmv_Tracks *tracks, int keyfra
libmv_Reconstruction *libmv_reconstruction = new libmv_Reconstruction();
libmv::EuclideanReconstruction *reconstruction = &libmv_reconstruction->reconstruction;
libmv::CameraIntrinsics *intrinsics = &libmv_reconstruction->intrinsics;
+ libmv::ReconstructionOptions reconstruction_options;
ReconstructUpdateCallback update_callback =
ReconstructUpdateCallback(progress_update_callback, callback_customdata);
@@ -566,6 +568,9 @@ libmv_Reconstruction *libmv_solveReconstruction(libmv_Tracks *tracks, int keyfra
intrinsics->SetPrincipalPoint(principal_x, principal_y);
intrinsics->SetRadialDistortion(k1, k2, k3);
+ reconstruction_options.success_threshold = options->success_threshold;
+ reconstruction_options.use_fallback_reconstruction = options->use_fallback_reconstruction;
+
for (int i = 0; i < markers.size(); ++i) {
intrinsics->InvertIntrinsics(markers[i].x,
markers[i].y,
@@ -584,7 +589,8 @@ libmv_Reconstruction *libmv_solveReconstruction(libmv_Tracks *tracks, int keyfra
libmv::EuclideanReconstructTwoFrames(keyframe_markers, reconstruction);
libmv::EuclideanBundle(normalized_tracks, reconstruction);
- libmv::EuclideanCompleteReconstruction(normalized_tracks, reconstruction, &update_callback);
+ libmv::EuclideanCompleteReconstruction(reconstruction_options, normalized_tracks,
+ reconstruction, &update_callback);
if (refine_intrinsics) {
libmv_solveRefineIntrinsics((libmv::Tracks *)tracks, intrinsics, reconstruction,
@@ -1027,7 +1033,7 @@ void libmv_InvertIntrinsics(double focal_length, double principal_x, double prin
/* ************ point clouds ************ */
-void libmvTransformToMat4(libmv::Mat3 &R, libmv::Vec3 &S, libmv::Vec3 &t, double M[4][4])
+static void libmvTransformToMat4(libmv::Mat3 &R, libmv::Vec3 &S, libmv::Vec3 &t, double M[4][4])
{
for (int j = 0; j < 3; ++j)
for (int k = 0; k < 3; ++k)
diff --git a/extern/libmv/libmv-capi.h b/extern/libmv/libmv-capi.h
index fc3b6f94f62..e5885e7addf 100644
--- a/extern/libmv/libmv-capi.h
+++ b/extern/libmv/libmv-capi.h
@@ -91,13 +91,20 @@ void libmv_tracksDestroy(struct libmv_Tracks *libmv_tracks);
#define LIBMV_REFINE_RADIAL_DISTORTION_K1 (1<<2)
#define LIBMV_REFINE_RADIAL_DISTORTION_K2 (1<<4)
+/* TODO: make keyframes/distortion model a part of options? */
+struct libmv_reconstructionOptions {
+ double success_threshold;
+ int use_fallback_reconstruction;
+};
+
typedef void (*reconstruct_progress_update_cb) (void *customdata, double progress, const char *message);
int libmv_refineParametersAreValid(int parameters);
struct libmv_Reconstruction *libmv_solveReconstruction(struct libmv_Tracks *tracks, int keyframe1, int keyframe2,
int refine_intrinsics, double focal_length, double principal_x, double principal_y, double k1, double k2, double k3,
- reconstruct_progress_update_cb progress_update_callback, void *callback_customdata);
+ struct libmv_reconstructionOptions *options, reconstruct_progress_update_cb progress_update_callback,
+ void *callback_customdata);
struct libmv_Reconstruction *libmv_solveModal(struct libmv_Tracks *tracks, double focal_length,
double principal_x, double principal_y, double k1, double k2, double k3,
reconstruct_progress_update_cb progress_update_callback, void *callback_customdata);
@@ -147,14 +154,14 @@ void libmv_CameraIntrinsicsDistortFloat(struct libmv_CameraIntrinsics *libmvIntr
/* dsitortion */
void libmv_undistortByte(double focal_length, double principal_x, double principal_y, double k1, double k2, double k3,
- unsigned char *src, unsigned char *dst, int width, int height, int channels);
+ unsigned char *src, unsigned char *dst, int width, int height, float overscan, int channels);
void libmv_undistortFloat(double focal_length, double principal_x, double principal_y, double k1, double k2, double k3,
- float *src, float *dst, int width, int height, int channels);
+ float *src, float *dst, int width, int height, float overscan, int channels);
void libmv_distortByte(double focal_length, double principal_x, double principal_y, double k1, double k2, double k3,
- unsigned char *src, unsigned char *dst, int width, int height, int channels);
+ unsigned char *src, unsigned char *dst, int width, int height, float overscan, int channels);
void libmv_distortFloat(double focal_length, double principal_x, double principal_y, double k1, double k2, double k3,
- float *src, float *dst, int width, int height, int channels);
+ float *src, float *dst, int width, int height, float overscan, int channels);
/* utils */
void libmv_applyCameraIntrinsics(double focal_length, double principal_x, double principal_y, double k1, double k2, double k3,
diff --git a/extern/libmv/libmv/multiview/euclidean_resection.cc b/extern/libmv/libmv/multiview/euclidean_resection.cc
index 92862515d7e..2605bf04622 100644
--- a/extern/libmv/libmv/multiview/euclidean_resection.cc
+++ b/extern/libmv/libmv/multiview/euclidean_resection.cc
@@ -37,13 +37,14 @@ typedef unsigned int uint;
bool EuclideanResection(const Mat2X &x_camera,
const Mat3X &X_world,
Mat3 *R, Vec3 *t,
- ResectionMethod method) {
+ ResectionMethod method,
+ double success_threshold) {
switch (method) {
case RESECTION_ANSAR_DANIILIDIS:
EuclideanResectionAnsarDaniilidis(x_camera, X_world, R, t);
break;
case RESECTION_EPNP:
- return EuclideanResectionEPnP(x_camera, X_world, R, t);
+ return EuclideanResectionEPnP(x_camera, X_world, R, t, success_threshold);
break;
default:
LOG(FATAL) << "Unknown resection method.";
@@ -351,9 +352,9 @@ void EuclideanResectionAnsarDaniilidis(const Mat2X &x_camera,
}
// Selects 4 virtual control points using mean and PCA.
-void SelectControlPoints(const Mat3X &X_world,
- Mat *X_centered,
- Mat34 *X_control_points) {
+static void SelectControlPoints(const Mat3X &X_world,
+ Mat *X_centered,
+ Mat34 *X_control_points) {
size_t num_points = X_world.cols();
// The first virtual control point, C0, is the centroid.
@@ -377,9 +378,9 @@ void SelectControlPoints(const Mat3X &X_world,
}
// Computes the barycentric coordinates for all real points
-void ComputeBarycentricCoordinates(const Mat3X &X_world_centered,
- const Mat34 &X_control_points,
- Mat4X *alphas) {
+static void ComputeBarycentricCoordinates(const Mat3X &X_world_centered,
+ const Mat34 &X_control_points,
+ Mat4X *alphas) {
size_t num_points = X_world_centered.cols();
Mat3 C2 ;
for (size_t c = 1; c < 4; c++) {
@@ -398,7 +399,7 @@ void ComputeBarycentricCoordinates(const Mat3X &X_world_centered,
}
// Estimates the coordinates of all real points in the camera coordinate frame
-void ComputePointsCoordinatesInCameraFrame(
+static void ComputePointsCoordinatesInCameraFrame(
const Mat4X &alphas,
const Vec4 &betas,
const Eigen::Matrix<double, 12, 12> &U,
@@ -435,8 +436,9 @@ void ComputePointsCoordinatesInCameraFrame(
}
bool EuclideanResectionEPnP(const Mat2X &x_camera,
- const Mat3X &X_world,
- Mat3 *R, Vec3 *t) {
+ const Mat3X &X_world,
+ Mat3 *R, Vec3 *t,
+ double success_threshold) {
CHECK(x_camera.cols() == X_world.cols());
CHECK(x_camera.cols() > 3);
size_t num_points = X_world.cols();
@@ -535,7 +537,21 @@ bool EuclideanResectionEPnP(const Mat2X &x_camera,
vector<Vec3> ts(3);
Vec rmse(3);
- // TODO(julien): Document where the "1e-3" magical constant comes from below.
+ // At one point this threshold was 1e-3, and caused no end of problems in
+ // Blender by causing frames to not resect when they would have worked fine.
+ // When the resect failed, the projective followup is run leading to worse
+ // results, and often the dreaded "flipping" where objects get flipped
+ // between frames. Instead, disable the check for now, always succeeding. The
+ // ultimate check is always reprojection error anyway.
+ //
+ // TODO(keir): Decide if setting this to infinity, effectively disabling the
+ // check, is the right approach. So far this seems the case.
+ //
+ // TODO(sergey): Made it an option for now, in some cases it makes sense to
+ // still fallback to reprojection solution (see bug [#32765] from Blender bug tracker)
+
+ // double kSuccessThreshold = std::numeric_limits<double>::max();
+ double kSuccessThreshold = success_threshold;
// Find the first possible solution for R, t corresponding to:
// Betas = [b00 b01 b11 b02 b12 b22 b03 b13 b23 b33]
@@ -548,7 +564,7 @@ bool EuclideanResectionEPnP(const Mat2X &x_camera,
Eigen::JacobiSVD<Mat> svd_of_l4(l_6x4,
Eigen::ComputeFullU | Eigen::ComputeFullV);
Vec4 b4 = svd_of_l4.solve(rho);
- if ((l_6x4 * b4).isApprox(rho, 1e-3)) {
+ if ((l_6x4 * b4).isApprox(rho, kSuccessThreshold)) {
if (b4(0) < 0) {
b4 = -b4;
}
@@ -574,7 +590,7 @@ bool EuclideanResectionEPnP(const Mat2X &x_camera,
Vec3 b3 = svdOfL3.solve(rho);
VLOG(2) << " rho = " << rho;
VLOG(2) << " l_6x3 * b3 = " << l_6x3 * b3;
- if ((l_6x3 * b3).isApprox(rho, 1e-3)) {
+ if ((l_6x3 * b3).isApprox(rho, kSuccessThreshold)) {
if (b3(0) < 0) {
betas(0) = std::sqrt(-b3(0));
betas(1) = (b3(2) < 0) ? std::sqrt(-b3(2)) : 0;
@@ -605,7 +621,7 @@ bool EuclideanResectionEPnP(const Mat2X &x_camera,
Eigen::JacobiSVD<Mat> svdOfL5(l_6x5,
Eigen::ComputeFullU | Eigen::ComputeFullV);
Vec5 b5 = svdOfL5.solve(rho);
- if ((l_6x5 * b5).isApprox(rho, 1e-3)) {
+ if ((l_6x5 * b5).isApprox(rho, kSuccessThreshold)) {
if (b5(0) < 0) {
betas(0) = std::sqrt(-b5(0));
if (b5(2) < 0) {
diff --git a/extern/libmv/libmv/multiview/euclidean_resection.h b/extern/libmv/libmv/multiview/euclidean_resection.h
index 08fa3d90bd3..b0428ec61fd 100644
--- a/extern/libmv/libmv/multiview/euclidean_resection.h
+++ b/extern/libmv/libmv/multiview/euclidean_resection.h
@@ -29,6 +29,9 @@ namespace euclidean_resection {
enum ResectionMethod {
RESECTION_ANSAR_DANIILIDIS,
+
+ // The "EPnP" algorithm by Lepetit et al.
+ // http://cvlab.epfl.ch/~lepetit/papers/lepetit_ijcv08.pdf
RESECTION_EPNP,
};
@@ -42,11 +45,14 @@ enum ResectionMethod {
* \param R Solution for the camera rotation matrix
* \param t Solution for the camera translation vector
* \param method The resection method to use.
+ * \param success_threshold Threshold of an error which is still considered a success
+ * (currently used by EPnP algorithm only)
*/
bool EuclideanResection(const Mat2X &x_camera,
const Mat3X &X_world,
Mat3 *R, Vec3 *t,
- ResectionMethod method = RESECTION_EPNP);
+ ResectionMethod method = RESECTION_EPNP,
+ double success_threshold = 1e-3);
/**
* Computes the extrinsic parameters, R and t for a calibrated camera
@@ -107,6 +113,7 @@ void EuclideanResectionAnsarDaniilidis(const Mat2X &x_camera,
* \param X_world 3D points in the world coordinate system
* \param R Solution for the camera rotation matrix
* \param t Solution for the camera translation vector
+ * \param success_threshold Threshold of an error which is still considered a success
*
* This is the algorithm described in:
* "{EP$n$P: An Accurate $O(n)$ Solution to the P$n$P Problem", by V. Lepetit
@@ -115,7 +122,8 @@ void EuclideanResectionAnsarDaniilidis(const Mat2X &x_camera,
*/
bool EuclideanResectionEPnP(const Mat2X &x_camera,
const Mat3X &X_world,
- Mat3 *R, Vec3 *t);
+ Mat3 *R, Vec3 *t,
+ double success_threshold = 1e-3);
} // namespace euclidean_resection
} // namespace libmv
diff --git a/extern/libmv/libmv/multiview/fundamental.cc b/extern/libmv/libmv/multiview/fundamental.cc
index 7a6b4a08439..80f155e804d 100644
--- a/extern/libmv/libmv/multiview/fundamental.cc
+++ b/extern/libmv/libmv/multiview/fundamental.cc
@@ -28,7 +28,7 @@
namespace libmv {
-void EliminateRow(const Mat34 &P, int row, Mat *X) {
+static void EliminateRow(const Mat34 &P, int row, Mat *X) {
X->resize(2, 4);
int first_row = (row + 1) % 3;
@@ -69,7 +69,7 @@ void FundamentalFromProjections(const Mat34 &P1, const Mat34 &P2, Mat3 *F) {
// HZ 11.1 pag.279 (x1 = x, x2 = x')
// http://www.cs.unc.edu/~marc/tutorial/node54.html
-double EightPointSolver(const Mat &x1, const Mat &x2, Mat3 *F) {
+static double EightPointSolver(const Mat &x1, const Mat &x2, Mat3 *F) {
DCHECK_EQ(x1.rows(), 2);
DCHECK_GE(x1.cols(), 8);
DCHECK_EQ(x1.rows(), x2.rows());
diff --git a/extern/libmv/libmv/multiview/homography.cc b/extern/libmv/libmv/multiview/homography.cc
index 366392f3923..b5c483998d8 100644
--- a/extern/libmv/libmv/multiview/homography.cc
+++ b/extern/libmv/libmv/multiview/homography.cc
@@ -40,7 +40,7 @@ namespace libmv {
* (a-x1*g)*y1 + (b-x1*h)*y2 + c-x1 = |0|
* (-x2*a+x1*d)*y1 + (-x2*b+x1*e)*y2 + -x2*c+x1*f |0|
*/
-bool Homography2DFromCorrespondencesLinearEuc(
+static bool Homography2DFromCorrespondencesLinearEuc(
const Mat &x1,
const Mat &x2,
Mat3 *H,
diff --git a/extern/libmv/libmv/numeric/levenberg_marquardt.h b/extern/libmv/libmv/numeric/levenberg_marquardt.h
index 4473b72f156..a7877e0270b 100644
--- a/extern/libmv/libmv/numeric/levenberg_marquardt.h
+++ b/extern/libmv/libmv/numeric/levenberg_marquardt.h
@@ -124,11 +124,11 @@ class LevenbergMarquardt {
Parameters dx, x_new;
int i;
for (i = 0; results.status == RUNNING && i < params.max_iterations; ++i) {
- VLOG(1) << "iteration: " << i;
- VLOG(1) << "||f(x)||: " << f_(x).norm();
- VLOG(1) << "max(g): " << g.array().abs().maxCoeff();
- VLOG(1) << "u: " << u;
- VLOG(1) << "v: " << v;
+ VLOG(3) << "iteration: " << i;
+ VLOG(3) << "||f(x)||: " << f_(x).norm();
+ VLOG(3) << "max(g): " << g.array().abs().maxCoeff();
+ VLOG(3) << "u: " << u;
+ VLOG(3) << "v: " << v;
AMatrixType A_augmented = A + u*AMatrixType::Identity(J.cols(), J.cols());
Solver solver(A_augmented);
diff --git a/extern/libmv/libmv/simple_pipeline/detect.cc b/extern/libmv/libmv/simple_pipeline/detect.cc
index 8a093dadeca..9e3edf32d71 100644
--- a/extern/libmv/libmv/simple_pipeline/detect.cc
+++ b/extern/libmv/libmv/simple_pipeline/detect.cc
@@ -35,7 +35,7 @@ namespace libmv {
typedef unsigned int uint;
-int featurecmp(const void *a_v, const void *b_v)
+static int featurecmp(const void *a_v, const void *b_v)
{
Feature *a = (Feature*)a_v;
Feature *b = (Feature*)b_v;
diff --git a/extern/libmv/libmv/simple_pipeline/initialize_reconstruction.cc b/extern/libmv/libmv/simple_pipeline/initialize_reconstruction.cc
index 77fe2a530c4..9c06d1ef4e6 100644
--- a/extern/libmv/libmv/simple_pipeline/initialize_reconstruction.cc
+++ b/extern/libmv/libmv/simple_pipeline/initialize_reconstruction.cc
@@ -24,6 +24,7 @@
#include "libmv/multiview/projection.h"
#include "libmv/numeric/levenberg_marquardt.h"
#include "libmv/numeric/numeric.h"
+#include "libmv/simple_pipeline/initialize_reconstruction.h"
#include "libmv/simple_pipeline/reconstruction.h"
#include "libmv/simple_pipeline/tracks.h"
diff --git a/extern/libmv/libmv/simple_pipeline/intersect.cc b/extern/libmv/libmv/simple_pipeline/intersect.cc
index b1518e04651..0c2f744dc1c 100644
--- a/extern/libmv/libmv/simple_pipeline/intersect.cc
+++ b/extern/libmv/libmv/simple_pipeline/intersect.cc
@@ -26,6 +26,7 @@
#include "libmv/multiview/projection.h"
#include "libmv/numeric/numeric.h"
#include "libmv/numeric/levenberg_marquardt.h"
+#include "libmv/simple_pipeline/intersect.h"
#include "libmv/simple_pipeline/reconstruction.h"
#include "libmv/simple_pipeline/tracks.h"
diff --git a/extern/libmv/libmv/simple_pipeline/pipeline.cc b/extern/libmv/libmv/simple_pipeline/pipeline.cc
index 2459d059114..efceda5c455 100644
--- a/extern/libmv/libmv/simple_pipeline/pipeline.cc
+++ b/extern/libmv/libmv/simple_pipeline/pipeline.cc
@@ -50,9 +50,10 @@ struct EuclideanPipelineRoutines {
EuclideanBundle(tracks, reconstruction);
}
- static bool Resect(const vector<Marker> &markers,
+ static bool Resect(const ReconstructionOptions &options,
+ const vector<Marker> &markers,
EuclideanReconstruction *reconstruction, bool final_pass) {
- return EuclideanResect(markers, reconstruction, final_pass);
+ return EuclideanResect(options, markers, reconstruction, final_pass);
}
static bool Intersect(const vector<Marker> &markers,
@@ -88,7 +89,8 @@ struct ProjectivePipelineRoutines {
ProjectiveBundle(tracks, reconstruction);
}
- static bool Resect(const vector<Marker> &markers,
+ static bool Resect(const ReconstructionOptions &options,
+ const vector<Marker> &markers,
ProjectiveReconstruction *reconstruction, bool final_pass) {
return ProjectiveResect(markers, reconstruction);
}
@@ -136,6 +138,7 @@ static void CompleteReconstructionLogProress(ProgressUpdateCallback *update_call
template<typename PipelineRoutines>
void InternalCompleteReconstruction(
+ const ReconstructionOptions &options,
const Tracks &tracks,
typename PipelineRoutines::Reconstruction *reconstruction,
ProgressUpdateCallback *update_callback = NULL) {
@@ -204,7 +207,7 @@ void InternalCompleteReconstruction(
if (reconstructed_markers.size() >= 5) {
CompleteReconstructionLogProress(update_callback,
(double)tot_resects/(max_image));
- if (PipelineRoutines::Resect(reconstructed_markers, reconstruction, false)) {
+ if (PipelineRoutines::Resect(options, reconstructed_markers, reconstruction, false)) {
num_resects++;
tot_resects++;
LG << "Ran Resect() for image " << image;
@@ -240,11 +243,11 @@ void InternalCompleteReconstruction(
if (reconstructed_markers.size() >= 5) {
CompleteReconstructionLogProress(update_callback,
(double)tot_resects/(max_image));
- if (PipelineRoutines::Resect(reconstructed_markers, reconstruction, true)) {
+ if (PipelineRoutines::Resect(options, reconstructed_markers, reconstruction, true)) {
num_resects++;
- LG << "Ran Resect() for image " << image;
+ LG << "Ran final Resect() for image " << image;
} else {
- LG << "Failed Resect() for image " << image;
+ LG << "Failed final Resect() for image " << image;
}
}
}
@@ -325,17 +328,21 @@ double ProjectiveReprojectionError(
intrinsics);
}
-void EuclideanCompleteReconstruction(const Tracks &tracks,
+void EuclideanCompleteReconstruction(const ReconstructionOptions &options,
+ const Tracks &tracks,
EuclideanReconstruction *reconstruction,
ProgressUpdateCallback *update_callback) {
- InternalCompleteReconstruction<EuclideanPipelineRoutines>(tracks,
+ InternalCompleteReconstruction<EuclideanPipelineRoutines>(options,
+ tracks,
reconstruction,
update_callback);
}
-void ProjectiveCompleteReconstruction(const Tracks &tracks,
+void ProjectiveCompleteReconstruction(const ReconstructionOptions &options,
+ const Tracks &tracks,
ProjectiveReconstruction *reconstruction) {
- InternalCompleteReconstruction<ProjectivePipelineRoutines>(tracks,
+ InternalCompleteReconstruction<ProjectivePipelineRoutines>(options,
+ tracks,
reconstruction);
}
diff --git a/extern/libmv/libmv/simple_pipeline/pipeline.h b/extern/libmv/libmv/simple_pipeline/pipeline.h
index e940b57bc0d..11c11297d78 100644
--- a/extern/libmv/libmv/simple_pipeline/pipeline.h
+++ b/extern/libmv/libmv/simple_pipeline/pipeline.h
@@ -39,6 +39,9 @@ namespace libmv {
repeated until all points and cameras are estimated. Periodically, bundle
adjustment is run to ensure a quality reconstruction.
+ \a options are used to define some specific befaviours based on settings
+ see documentation for ReconstructionOptions
+
\a tracks should contain markers used in the reconstruction.
\a reconstruction should contain at least some 3D points or some estimated
cameras. The minimum number of cameras is two (with no 3D points) and the
@@ -46,7 +49,8 @@ namespace libmv {
\sa EuclideanResect, EuclideanIntersect, EuclideanBundle
*/
-void EuclideanCompleteReconstruction(const Tracks &tracks,
+void EuclideanCompleteReconstruction(const ReconstructionOptions &options,
+ const Tracks &tracks,
EuclideanReconstruction *reconstruction,
ProgressUpdateCallback *update_callback = NULL);
@@ -63,6 +67,9 @@ void EuclideanCompleteReconstruction(const Tracks &tracks,
repeated until all points and cameras are estimated. Periodically, bundle
adjustment is run to ensure a quality reconstruction.
+ \a options are used to define some specific befaviours based on settings
+ see documentation for ReconstructionOptions
+
\a tracks should contain markers used in the reconstruction.
\a reconstruction should contain at least some 3D points or some estimated
cameras. The minimum number of cameras is two (with no 3D points) and the
@@ -70,7 +77,8 @@ void EuclideanCompleteReconstruction(const Tracks &tracks,
\sa ProjectiveResect, ProjectiveIntersect, ProjectiveBundle
*/
-void ProjectiveCompleteReconstruction(const Tracks &tracks,
+void ProjectiveCompleteReconstruction(const ReconstructionOptions &options,
+ const Tracks &tracks,
ProjectiveReconstruction *reconstruction);
diff --git a/extern/libmv/libmv/simple_pipeline/reconstruction.h b/extern/libmv/libmv/simple_pipeline/reconstruction.h
index 947a0636476..71789e3a245 100644
--- a/extern/libmv/libmv/simple_pipeline/reconstruction.h
+++ b/extern/libmv/libmv/simple_pipeline/reconstruction.h
@@ -26,6 +26,17 @@
namespace libmv {
+struct ReconstructionOptions {
+ // threshold value of reconstruction error which is still considered successful
+ // if reconstruction error bigger than this value, fallback reconstruction
+ // algorithm would be used (if enabled)
+ double success_threshold;
+
+ // use fallback reconstruction algorithm in cases main reconstruction algorithm
+ // failed to reconstruct
+ bool use_fallback_reconstruction;
+};
+
/*!
A EuclideanCamera is the location and rotation of the camera viewing \a image.
diff --git a/extern/libmv/libmv/simple_pipeline/resect.cc b/extern/libmv/libmv/simple_pipeline/resect.cc
index b30d959b512..4c9ca6d8677 100644
--- a/extern/libmv/libmv/simple_pipeline/resect.cc
+++ b/extern/libmv/libmv/simple_pipeline/resect.cc
@@ -27,6 +27,7 @@
#include "libmv/multiview/projection.h"
#include "libmv/numeric/numeric.h"
#include "libmv/numeric/levenberg_marquardt.h"
+#include "libmv/simple_pipeline/resect.h"
#include "libmv/simple_pipeline/reconstruction.h"
#include "libmv/simple_pipeline/tracks.h"
@@ -89,7 +90,8 @@ struct EuclideanResectCostFunction {
} // namespace
-bool EuclideanResect(const vector<Marker> &markers,
+bool EuclideanResect(const ReconstructionOptions &options,
+ const vector<Marker> &markers,
EuclideanReconstruction *reconstruction, bool final_pass) {
if (markers.size() < 5) {
return false;
@@ -103,10 +105,25 @@ bool EuclideanResect(const vector<Marker> &markers,
Mat3 R;
Vec3 t;
- if (0 || !euclidean_resection::EuclideanResection(points_2d, points_3d, &R, &t)) {
+
+ double success_threshold = std::numeric_limits<double>::max();
+
+ if(options.use_fallback_reconstruction)
+ success_threshold = options.success_threshold;
+
+ if (0 || !euclidean_resection::EuclideanResection(points_2d, points_3d, &R, &t,
+ euclidean_resection::RESECTION_EPNP,
+ success_threshold))
+ {
// printf("Resection for image %d failed\n", markers[0].image);
LG << "Resection for image " << markers[0].image << " failed;"
<< " trying fallback projective resection.";
+
+ if (!options.use_fallback_reconstruction) {
+ LG << "No fallback; failing resection for " << markers[0].image;
+ return false;
+ }
+
if (!final_pass) return false;
// Euclidean resection failed. Fall back to projective resection, which is
// less reliable but better conditioned when there are many points.
diff --git a/extern/libmv/libmv/simple_pipeline/resect.h b/extern/libmv/libmv/simple_pipeline/resect.h
index f8b5b9f68ee..1691e7ee245 100644
--- a/extern/libmv/libmv/simple_pipeline/resect.h
+++ b/extern/libmv/libmv/simple_pipeline/resect.h
@@ -35,6 +35,9 @@ namespace libmv {
reconstruction object, and solves for the pose and orientation of the
camera for that frame.
+ \a options are used to define some specific befaviours based on settings
+ see documentation for ReconstructionOptions
+
\a markers should contain \l Marker markers \endlink belonging to tracks
visible in the one frame to be resectioned. Each of the tracks associated
with the markers must have a corresponding reconstructed 3D position in the
@@ -51,7 +54,8 @@ namespace libmv {
\sa EuclideanIntersect, EuclideanReconstructTwoFrames
*/
-bool EuclideanResect(const vector<Marker> &markers,
+bool EuclideanResect(const ReconstructionOptions &options,
+ const vector<Marker> &markers,
EuclideanReconstruction *reconstruction, bool final_pass);
/*!
diff --git a/extern/libmv/libmv/tracking/track_region.cc b/extern/libmv/libmv/tracking/track_region.cc
index f52919b2a61..472d58a1547 100644
--- a/extern/libmv/libmv/tracking/track_region.cc
+++ b/extern/libmv/libmv/tracking/track_region.cc
@@ -18,7 +18,7 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
-// Author: mierle@google.com (Keir Mierle)
+// Author: mierle@gmail.com (Keir Mierle)
//
// TODO(keir): While this tracking code works rather well, it has some
// outragous inefficiencies. There is probably a 5-10x speedup to be had if a
@@ -41,6 +41,85 @@
#include "libmv/multiview/homography.h"
#include "libmv/numeric/numeric.h"
+// Expand the Jet functionality of Ceres to allow mixed numeric/autodiff.
+//
+// TODO(keir): Push this (or something similar) into upstream Ceres.
+namespace ceres {
+
+// A jet traits class to make it easier to work with mixed auto / numeric diff.
+template<typename T>
+struct JetOps {
+ static bool IsScalar() {
+ return true;
+ }
+ static T GetScalar(const T& t) {
+ return t;
+ }
+ static void SetScalar(const T& scalar, T* t) {
+ *t = scalar;
+ }
+ static void ScaleDerivative(double scale_by, T *value) {
+ // For double, there is no derivative to scale.
+ }
+};
+
+template<typename T, int N>
+struct JetOps<Jet<T, N> > {
+ static bool IsScalar() {
+ return false;
+ }
+ static T GetScalar(const Jet<T, N>& t) {
+ return t.a;
+ }
+ static void SetScalar(const T& scalar, Jet<T, N>* t) {
+ t->a = scalar;
+ }
+ static void ScaleDerivative(double scale_by, Jet<T, N> *value) {
+ value->v *= scale_by;
+ }
+};
+
+template<typename FunctionType, int kNumArgs, typename ArgumentType>
+struct Chain {
+ static ArgumentType Rule(const FunctionType &f,
+ const FunctionType dfdx[kNumArgs],
+ const ArgumentType x[kNumArgs]) {
+ // In the default case of scalars, there's nothing to do since there are no
+ // derivatives to propagate.
+ return f;
+ }
+};
+
+// XXX Add documentation here!
+template<typename FunctionType, int kNumArgs, typename T, int N>
+struct Chain<FunctionType, kNumArgs, Jet<T, N> > {
+ static Jet<T, N> Rule(const FunctionType &f,
+ const FunctionType dfdx[kNumArgs],
+ const Jet<T, N> x[kNumArgs]) {
+ // x is itself a function of another variable ("z"); what this function
+ // needs to return is "f", but with the derivative with respect to z
+ // attached to the jet. So combine the derivative part of x's jets to form
+ // a Jacobian matrix between x and z (i.e. dx/dz).
+ Eigen::Matrix<T, kNumArgs, N> dxdz;
+ for (int i = 0; i < kNumArgs; ++i) {
+ dxdz.row(i) = x[i].v.transpose();
+ }
+
+ // Map the input gradient dfdx into an Eigen row vector.
+ Eigen::Map<const Eigen::Matrix<FunctionType, 1, kNumArgs> >
+ vector_dfdx(dfdx, 1, kNumArgs);
+
+ // Now apply the chain rule to obtain df/dz. Combine the derivative with
+ // the scalar part to obtain f with full derivative information.
+ Jet<T, N> jet_f;
+ jet_f.a = f;
+ jet_f.v = vector_dfdx.template cast<T>() * dxdz; // Also known as dfdz.
+ return jet_f;
+ }
+};
+
+} // namespace ceres
+
namespace libmv {
using ceres::Jet;
@@ -57,6 +136,7 @@ TrackRegionOptions::TrackRegionOptions()
sigma(0.9),
num_extra_points(0),
regularization_coefficient(0.0),
+ minimum_corner_shift_tolerance_pixels(0.005),
image1_mask(NULL) {
}
@@ -108,45 +188,93 @@ static T SampleWithDerivative(const FloatImage &image_and_gradient,
}
template<typename Warp>
-class BoundaryCheckingCallback : public ceres::IterationCallback {
+class TerminationCheckingCallback : public ceres::IterationCallback {
public:
- BoundaryCheckingCallback(const FloatImage& image2,
- const Warp &warp,
- const double *x1, const double *y1)
- : image2_(image2), warp_(warp), x1_(x1), y1_(y1) {}
+ TerminationCheckingCallback(const TrackRegionOptions &options,
+ const FloatImage& image2,
+ const Warp &warp,
+ const double *x1, const double *y1)
+ : options_(options), image2_(image2), warp_(warp), x1_(x1), y1_(y1),
+ have_last_successful_step_(false) {}
virtual ceres::CallbackReturnType operator()(
const ceres::IterationSummary& summary) {
+ // If the step wasn't successful, there's nothing to do.
+ if (!summary.step_is_successful) {
+ return ceres::SOLVER_CONTINUE;
+ }
// Warp the original 4 points with the current warp into image2.
double x2[4];
double y2[4];
for (int i = 0; i < 4; ++i) {
warp_.Forward(warp_.parameters, x1_[i], y1_[i], x2 + i, y2 + i);
}
- // Enusre they are all in bounds.
+ // Ensure the corners are all in bounds.
if (!AllInBounds(image2_, x2, y2)) {
+ LG << "Successful step fell outside of the pattern bounds; aborting.";
return ceres::SOLVER_ABORT;
}
+
+ // Ensure the minimizer is making large enough shifts to bother continuing.
+ // Ideally, this check would happen on the parameters themselves which
+ // Ceres supports directly; however, the mapping from parameter change
+ // magnitude to corner movement in pixels is not a simple norm. Hence, the
+ // need for a stateful callback which tracks the last successful set of
+ // parameters (and the position of the projected patch corners).
+ if (have_last_successful_step_) {
+ // Compute the maximum shift of any corner in pixels since the last
+ // successful iteration.
+ double max_change_pixels = 0;
+ for (int i = 0; i < 4; ++i) {
+ double dx = x2[i] - x2_last_successful_[i];
+ double dy = y2[i] - y2_last_successful_[i];
+ double change_pixels = dx*dx + dy*dy;
+ if (change_pixels > max_change_pixels) {
+ max_change_pixels = change_pixels;
+ }
+ }
+ max_change_pixels = sqrt(max_change_pixels);
+ LG << "Max patch corner shift is " << max_change_pixels;
+
+ // Bail if the shift is too small.
+ if (max_change_pixels < options_.minimum_corner_shift_tolerance_pixels) {
+ LG << "Max patch corner shift is " << max_change_pixels
+ << " from the last iteration; returning success.";
+ return ceres::SOLVER_TERMINATE_SUCCESSFULLY;
+ }
+ }
+
+ // Save the projected corners for checking on the next successful iteration.
+ for (int i = 0; i < 4; ++i) {
+ x2_last_successful_[i] = x2[i];
+ y2_last_successful_[i] = y2[i];
+ }
+ have_last_successful_step_ = true;
return ceres::SOLVER_CONTINUE;
}
private:
+ const TrackRegionOptions &options_;
const FloatImage &image2_;
const Warp &warp_;
const double *x1_;
const double *y1_;
+
+ bool have_last_successful_step_;
+ double x2_last_successful_[4];
+ double y2_last_successful_[4];
};
template<typename Warp>
class PixelDifferenceCostFunctor {
public:
PixelDifferenceCostFunctor(const TrackRegionOptions &options,
- const FloatImage &image_and_gradient1,
- const FloatImage &image_and_gradient2,
- const Mat3 &canonical_to_image1,
- int num_samples_x,
- int num_samples_y,
- const Warp &warp)
+ const FloatImage &image_and_gradient1,
+ const FloatImage &image_and_gradient2,
+ const Mat3 &canonical_to_image1,
+ int num_samples_x,
+ int num_samples_y,
+ const Warp &warp)
: options_(options),
image_and_gradient1_(image_and_gradient1),
image_and_gradient2_(image_and_gradient2),
@@ -1044,6 +1172,9 @@ void CreateBrutePattern(const double *x1, const double *y1,
// correlation. Instead, this is a dumb implementation. Surprisingly, it is
// fast enough in practice.
//
+// Returns true if any alignment was found, and false if the projected pattern
+// is zero sized.
+//
// TODO(keir): The normalization is less effective for the brute force search
// than it is with the Ceres solver. It's unclear if this is a bug or due to
// the original frame being too different from the reprojected reference in the
@@ -1054,7 +1185,7 @@ void CreateBrutePattern(const double *x1, const double *y1,
// totally different warping interface, since access to more than a the source
// and current destination frame is necessary.
template<typename Warp>
-void BruteTranslationOnlyInitialize(const FloatImage &image1,
+bool BruteTranslationOnlyInitialize(const FloatImage &image1,
const FloatImage *image1_mask,
const FloatImage &image2,
const int num_extra_points,
@@ -1100,6 +1231,7 @@ void BruteTranslationOnlyInitialize(const FloatImage &image1,
int best_c = -1;
int w = pattern.cols();
int h = pattern.rows();
+
for (int r = 0; r < (image2.Height() - h); ++r) {
for (int c = 0; c < (image2.Width() - w); ++c) {
// Compute the weighted sum of absolute differences, Eigen style. Note
@@ -1124,8 +1256,12 @@ void BruteTranslationOnlyInitialize(const FloatImage &image1,
}
}
}
- CHECK_NE(best_r, -1);
- CHECK_NE(best_c, -1);
+
+ // This mean the effective pattern area is zero. This check could go earlier,
+ // but this is less code.
+ if (best_r == -1 || best_c == -1) {
+ return false;
+ }
LG << "Brute force translation found a shift. "
<< "best_c: " << best_c << ", best_r: " << best_r << ", "
@@ -1140,6 +1276,7 @@ void BruteTranslationOnlyInitialize(const FloatImage &image1,
x2[i] += best_c - origin_x;
y2[i] += best_r - origin_y;
}
+ return true;
}
} // namespace
@@ -1191,12 +1328,19 @@ void TemplatedTrackRegion(const FloatImage &image1,
if (SearchAreaTooBigForDescent(image2, x2, y2) &&
options.use_brute_initialization) {
LG << "Running brute initialization...";
- BruteTranslationOnlyInitialize<Warp>(image_and_gradient1,
- options.image1_mask,
- image2,
- options.num_extra_points,
- options.use_normalized_intensities,
- x1, y1, x2, y2);
+ bool found_any_alignment = BruteTranslationOnlyInitialize<Warp>(
+ image_and_gradient1,
+ options.image1_mask,
+ image2,
+ options.num_extra_points,
+ options.use_normalized_intensities,
+ x1, y1, x2, y2);
+ if (!found_any_alignment) {
+ LG << "Brute failed to find an alignment; pattern too small. "
+ << "Failing entire track operation.";
+ result->termination = TrackRegionResult::INSUFFICIENT_PATTERN_AREA;
+ return;
+ }
for (int i = 0; i < 4; ++i) {
LG << "P" << i << ": (" << x1[i] << ", " << y1[i] << "); brute ("
<< x2[i] << ", " << y2[i] << "); (dx, dy): (" << (x2[i] - x1[i])
@@ -1260,14 +1404,15 @@ void TemplatedTrackRegion(const FloatImage &image1,
// Configure the solve.
ceres::Solver::Options solver_options;
- solver_options.linear_solver_type = ceres::DENSE_QR;
+ solver_options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;
solver_options.max_num_iterations = options.max_iterations;
solver_options.update_state_every_iteration = true;
solver_options.parameter_tolerance = 1e-16;
solver_options.function_tolerance = 1e-16;
- // Prevent the corners from going outside the destination image.
- BoundaryCheckingCallback<Warp> callback(image2, warp, x1, y1);
+ // Prevent the corners from going outside the destination image and
+ // terminate if the optimizer is making tiny moves (converged).
+ TerminationCheckingCallback<Warp> callback(options, image2, warp, x1, y1);
solver_options.callbacks.push_back(&callback);
// Run the solve.
@@ -1290,11 +1435,21 @@ void TemplatedTrackRegion(const FloatImage &image1,
// TODO(keir): Update the result statistics.
// TODO(keir): Add a normalize-cross-correlation variant.
- CHECK_NE(summary.termination_type, ceres::USER_ABORT) << "Libmv bug.";
if (summary.termination_type == ceres::USER_ABORT) {
result->termination = TrackRegionResult::FELL_OUT_OF_BOUNDS;
return;
}
+
+ // This happens when the minimum corner shift tolerance is reached. Due to
+ // how the tolerance is computed this can't be done by Ceres. So return the
+ // same termination enum as Ceres, even though this is slightly different
+ // than Ceres's parameter tolerance, which operates on the raw parameter
+ // values rather than the pixel shifts of the patch corners.
+ if (summary.termination_type == ceres::USER_SUCCESS) {
+ result->termination = TrackRegionResult::PARAMETER_TOLERANCE;
+ return;
+ }
+
#define HANDLE_TERMINATION(termination_enum) \
if (summary.termination_type == ceres::termination_enum) { \
result->termination = TrackRegionResult::termination_enum; \
@@ -1377,11 +1532,11 @@ bool SamplePlanarPatch(const FloatImage &image,
image_position(0),
&(*patch)(r, c, 0));
if (mask) {
- float maskValue = SampleLinear(*mask, image_position(1),
- image_position(0), 0);
+ float mask_value = SampleLinear(*mask, image_position(1),
+ image_position(0), 0);
for (int d = 0; d < image.Depth(); d++)
- (*patch)(r, c, d) *= maskValue;
+ (*patch)(r, c, d) *= mask_value;
}
}
}
diff --git a/extern/libmv/libmv/tracking/track_region.h b/extern/libmv/libmv/tracking/track_region.h
index 22ecfc54a15..cd7ee0aa2ba 100644
--- a/extern/libmv/libmv/tracking/track_region.h
+++ b/extern/libmv/libmv/tracking/track_region.h
@@ -90,6 +90,11 @@ struct TrackRegionOptions {
// If zero, no regularization is used.
double regularization_coefficient;
+ // If the maximum shift of any patch corner between successful iterations of
+ // the solver is less than this amount, then the tracking is declared
+ // successful. The solver termination becomes PARAMETER_TOLERANCE.
+ double minimum_corner_shift_tolerance_pixels;
+
// If non-null, this is used as the pattern mask. It should match the size of
// image1, even though only values inside the image1 quad are examined. The
// values must be in the range 0.0 to 0.1.
@@ -111,6 +116,7 @@ struct TrackRegionResult {
DESTINATION_OUT_OF_BOUNDS,
FELL_OUT_OF_BOUNDS,
INSUFFICIENT_CORRELATION,
+ INSUFFICIENT_PATTERN_AREA,
CONFIGURATION_ERROR,
};
Termination termination;
diff --git a/extern/libmv/third_party/ceres/CMakeLists.txt b/extern/libmv/third_party/ceres/CMakeLists.txt
index e6a9e430c47..e2f06d74646 100644
--- a/extern/libmv/third_party/ceres/CMakeLists.txt
+++ b/extern/libmv/third_party/ceres/CMakeLists.txt
@@ -28,16 +28,17 @@
set(INC
.
- ../../../Eigen3
include
internal
../gflags
)
set(INC_SYS
+ ../../../Eigen3
)
set(SRC
+ internal/ceres/array_utils.cc
internal/ceres/block_evaluate_preparer.cc
internal/ceres/block_jacobian_writer.cc
internal/ceres/block_jacobi_preconditioner.cc
@@ -53,16 +54,19 @@ set(SRC
internal/ceres/conditioned_cost_function.cc
internal/ceres/conjugate_gradients_solver.cc
internal/ceres/corrector.cc
+ internal/ceres/cxsparse.cc
+ internal/ceres/dense_normal_cholesky_solver.cc
internal/ceres/dense_qr_solver.cc
internal/ceres/dense_sparse_matrix.cc
internal/ceres/detect_structure.cc
+ internal/ceres/dogleg_strategy.cc
internal/ceres/evaluator.cc
internal/ceres/file.cc
internal/ceres/generated/schur_eliminator_d_d_d.cc
internal/ceres/gradient_checking_cost_function.cc
internal/ceres/implicit_schur_complement.cc
internal/ceres/iterative_schur_complement_solver.cc
- internal/ceres/levenberg_marquardt.cc
+ internal/ceres/levenberg_marquardt_strategy.cc
internal/ceres/linear_least_squares_problems.cc
internal/ceres/linear_operator.cc
internal/ceres/linear_solver.cc
@@ -70,6 +74,7 @@ set(SRC
internal/ceres/loss_function.cc
internal/ceres/normal_prior.cc
internal/ceres/partitioned_matrix_view.cc
+ internal/ceres/polynomial_solver.cc
internal/ceres/problem.cc
internal/ceres/problem_impl.cc
internal/ceres/program.cc
@@ -88,6 +93,8 @@ set(SRC
internal/ceres/stringprintf.cc
internal/ceres/suitesparse.cc
internal/ceres/triplet_sparse_matrix.cc
+ internal/ceres/trust_region_minimizer.cc
+ internal/ceres/trust_region_strategy.cc
internal/ceres/types.cc
internal/ceres/visibility_based_preconditioner.cc
internal/ceres/visibility.cc
@@ -96,6 +103,8 @@ set(SRC
include/ceres/ceres.h
include/ceres/conditioned_cost_function.h
include/ceres/cost_function.h
+ include/ceres/crs_matrix.h
+ include/ceres/fpclassify.h
include/ceres/internal/autodiff.h
include/ceres/internal/eigen.h
include/ceres/internal/fixed_array.h
@@ -114,6 +123,7 @@ set(SRC
include/ceres/sized_cost_function.h
include/ceres/solver.h
include/ceres/types.h
+ internal/ceres/array_utils.h
internal/ceres/block_evaluate_preparer.h
internal/ceres/block_jacobian_writer.h
internal/ceres/block_jacobi_preconditioner.h
@@ -131,10 +141,13 @@ set(SRC
internal/ceres/compressed_row_sparse_matrix.h
internal/ceres/conjugate_gradients_solver.h
internal/ceres/corrector.h
+ internal/ceres/cxsparse.h
internal/ceres/dense_jacobian_writer.h
+ internal/ceres/dense_normal_cholesky_solver.h
internal/ceres/dense_qr_solver.h
internal/ceres/dense_sparse_matrix.h
internal/ceres/detect_structure.h
+ internal/ceres/dogleg_strategy.h
internal/ceres/evaluator.h
internal/ceres/file.h
internal/ceres/gradient_checking_cost_function.h
@@ -143,7 +156,7 @@ set(SRC
internal/ceres/implicit_schur_complement.h
internal/ceres/integral_types.h
internal/ceres/iterative_schur_complement_solver.h
- internal/ceres/levenberg_marquardt.h
+ internal/ceres/levenberg_marquardt_strategy.h
internal/ceres/linear_least_squares_problems.h
internal/ceres/linear_operator.h
internal/ceres/linear_solver.h
@@ -153,6 +166,7 @@ set(SRC
internal/ceres/mutex.h
internal/ceres/parameter_block.h
internal/ceres/partitioned_matrix_view.h
+ internal/ceres/polynomial_solver.h
internal/ceres/problem_impl.h
internal/ceres/program_evaluator.h
internal/ceres/program.h
@@ -168,10 +182,13 @@ set(SRC
internal/ceres/solver_impl.h
internal/ceres/sparse_matrix.h
internal/ceres/sparse_normal_cholesky_solver.h
+ internal/ceres/split.h
internal/ceres/stl_util.h
internal/ceres/stringprintf.h
internal/ceres/suitesparse.h
internal/ceres/triplet_sparse_matrix.h
+ internal/ceres/trust_region_minimizer.h
+ internal/ceres/trust_region_strategy.h
internal/ceres/visibility_based_preconditioner.h
internal/ceres/visibility.h
)
@@ -203,7 +220,7 @@ if(WIN32)
if(NOT MINGW)
list(APPEND INC
- third_party/msinttypes
+ ../msinttypes
)
endif()
else()
@@ -214,11 +231,30 @@ endif()
add_definitions(
-DCERES_HAVE_PTHREAD
- -D"CERES_HASH_NAMESPACE_START=namespace std { namespace tr1 {"
- -D"CERES_HASH_NAMESPACE_END=}}"
-DCERES_NO_SUITESPARSE
- -DCERES_DONT_HAVE_PROTOCOL_BUFFERS
+ -DCERES_NO_CXSPARSE
+ -DCERES_NO_PROTOCOL_BUFFERS
-DCERES_RESTRICT_SCHUR_SPECIALIZATION
)
+if(MSVC10)
+ add_definitions(
+ -D"CERES_HASH_NAMESPACE_START=namespace std {"
+ -D"CERES_HASH_NAMESPACE_END=}"
+ )
+else()
+ add_definitions(
+ -D"CERES_HASH_NAMESPACE_START=namespace std { namespace tr1 {"
+ -D"CERES_HASH_NAMESPACE_END=}}"
+ )
+endif()
+
+if(APPLE)
+ if(CMAKE_OSX_DEPLOYMENT_TARGET STREQUAL "10.5")
+ add_definitions(
+ -DCERES_NO_TR1
+ )
+ endif()
+endif()
+
blender_add_lib(extern_ceres "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/extern/libmv/third_party/ceres/ChangeLog b/extern/libmv/third_party/ceres/ChangeLog
index 6e919658f13..8b84328cf98 100644
--- a/extern/libmv/third_party/ceres/ChangeLog
+++ b/extern/libmv/third_party/ceres/ChangeLog
@@ -1,324 +1,524 @@
-commit ca72152362ae1f4b9928c012e74b4d49d094a4ca
-Merge: d297f8d 0a04199
-Author: Keir Mierle <mierle@gmail.com>
-Date: Wed May 9 13:10:59 2012 -0700
+commit 552f9f85bba89f00ca307bc18fbda1dff23bd0e4
+Author: Sameer Agarwal <sameeragarwal@google.com>
+Date: Fri Aug 31 07:27:22 2012 -0700
- Merge branch 'master' into windows
+ Various minor bug fixes to the solver logic.
+
+ 1. CostFunction returning false is handled better.
+ If only the cost is being evaluated, it is possible to
+ use the false value as an infinite value signal/outside
+ a region of validity. This allows a weak form of constraint
+ handling. Useful for example in handling infinities.
+
+ 2. Changed the way how the slop around zero when model_cost
+ is larger than the current cost. Relative instead of absolute
+ tolerances are used. The same logic is propagated how the
+ corresponding clamping of the model_cost is done.
+
+ 3. Fixed a minor indexing bug in nist.cc.
+
+ 4. Some minor logging fixes to nist.cc to make it more
+ compatible with the rest of ceres.
+
+ Together these changes, take the successful solve count from
+ 41/54 to 46/54 and eliminate all NUMERICAL_FAILURE problems.
+
+ Change-Id: If94170ea4731af5b243805c0200963dd31aa94a7
-commit 0a04199ef279cc9ea97f665fed8e7fae717813c3
-Merge: fdeb577 f2571f1
-Author: Keir Mierle <mierle@gmail.com>
-Date: Wed May 9 12:54:56 2012 -0700
+commit 0b776b5cc9634d3b88d623905b96006f7647ce3e
+Author: Sameer Agarwal <sameeragarwal@google.com>
+Date: Thu Aug 30 15:26:17 2012 -0700
- Merge branch 'master' of https://code.google.com/p/ceres-solver
+ Update docs.
+
+ Change-Id: I69d50bcd37aed3bea2190ca614f023e83172901b
-commit fdeb5772cc5eeebca4d776d220d80cc91b6d0f74
-Author: Keir Mierle <mierle@gmail.com>
-Date: Wed May 9 07:38:07 2012 -0700
+commit 2d7176ad7c8fb7238ca8abd6de73415d95877494
+Author: Petter Strandmark <petter.strandmark@gmail.com>
+Date: Thu Aug 30 19:51:24 2012 -0700
- Support varying numbers of residuals in autodiff.
+ max_consecutive_nonmonotonic_steps should be int
- This commit modifies the only function in autodiff that takes a
- templated number of outputs (i.e. residuals) and makes that
- template parameter a normal parameter. With that change, it
- is a trivial matter to support a dynamic number of residuals.
+ Found via Visual Studio warning.
- The API for dynamic residuals is to pass a fake number of
- residuals as the second template argument to
- AutoDiffCostFunction, and to pass the real number of
- parameters as a second constructor argument.
+ Change-Id: Id2cd7de562dfc8cd35df5d5f5220dd2d7350eb2c
-commit da3e0563cc12e08e7b3e0fbf11d9cc8cfe9658aa
+commit 1a89bcc94e88933f89b20427a45bc40cdd23c056
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Wed May 9 11:57:47 2012 -0700
+Date: Thu Aug 30 15:26:17 2012 -0700
- Typo corrections in the documentation from Bing
+ Better reporting on the NIST problems.
+
+ Change-Id: I7cf774ec3242c0612dbe52fc233c3fc6cff3f031
-commit aa9526d8e8fb34c23d63e3af5bf9239b0c4ea603
+commit ea11704857a1e4a735e096896e4d775d83981499
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Tue May 8 21:22:09 2012 -0700
+Date: Wed Aug 29 18:18:48 2012 -0700
- Share search paths across various library searches.
- Fix typos in glog search.
- Split the error messages for include and lib.
- Enable building of tests by default.
- Made building on homebrew installations a bit better.
- Remove temporary variables for glog and gflags.
+ Basic harness for testing NIST problems.
+
+ Change-Id: I5baaa24dbf0506ceedf4a9be4ed17c84974d71a1
-commit f2571f186850ed3dd316236ac4be488979df7d30
+commit 98bf14d2b95386c2c4a6c29154637943dae4c36c
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Wed May 9 11:57:47 2012 -0700
+Date: Thu Aug 30 10:26:44 2012 -0700
- Typo corrections in the documentation from Bing
+ Miscellaneous fixes.
+
+ Change-Id: I521e11f2d20bf24960bbc6b5dab4ec8bb1503d23
-commit 8f7f11ff7d07737435428a2620c52419cf99f98e
-Merge: e6c17c4 eaccbb3
-Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Wed May 9 11:34:15 2012 -0700
+commit 1e3cbd9a4442cdd8fda43a7fb452f19dac8c74af
+Author: Petter Strandmark <strandmark@google.com>
+Date: Wed Aug 29 09:39:56 2012 -0700
- Merge branch 'master' of https://code.google.com/p/ceres-solver
+ Caching the symbolic Cholesky factorization when using CXSparse
+
+ Average factorization times for bundle adjustment test problem:
+ SuiteSparse: 0.2794 s.
+ CXSparse: 0.4039 s.
+ CXSparse cached: 0.2399 s.
+
+ CXSparse will still be slower, though, because it has to compute
+ the transpose and J^T * J.
+
+ Change-Id: If9cdaa3dd520bee84b56e5fd4953b56a93db6bde
-commit e6c17c4c9d9307218f6f739cea39bc2d87733d4d
+commit 8b64140878ccd1e183d3715c38942a81fdecefde
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Tue May 8 21:22:09 2012 -0700
+Date: Wed Aug 29 05:41:22 2012 -0700
- Share search paths across various library searches.
- Fix typos in glog search.
- Split the error messages for include and lib.
- Enable building of tests by default.
- Made building on homebrew installations a bit better.
- Remove temporary variables for glog and gflags.
+ Documentation update
+
+ Change-Id: I271a0422e7f6f42bcfd1dc6b5dc10c7a18f6a179
-commit eaccbb345614c0d24c5e21fa931f470cfda874df
-Author: Keir Mierle <mierle@gmail.com>
-Date: Wed May 9 05:31:29 2012 -0700
+commit a5353acd85a9fd19370b3d74035d87b0f0bac230
+Author: Petter Strandmark <petter.strandmark@gmail.com>
+Date: Tue Aug 28 18:16:41 2012 -0700
- Remove unused template parameter from VariadicEvaluate.
+ Adding gflags include to test_util.cc
+
+ test_util seems to need gflags.
+
+ Change-Id: I0c4757960f8ac69ad599c138aea58e3c88a4ea28
-commit 82f4b88c34b0b2cf85064e5fc20e374e978b2e3b
-Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Sun May 6 21:05:28 2012 -0700
+commit 87ca1b2ba28ec512752bbcf5fc994ce1434eb765
+Author: Petter Strandmark <petter.strandmark@gmail.com>
+Date: Tue Aug 28 18:05:20 2012 -0700
- Extend support writing linear least squares problems to disk.
+ Changing random.h to use cstdlib for Windows compability.
- 1. Make the mechanism for writing problems to disk, generic and
- controllable using an enum DumpType visible in the API.
+ As discussed with Sameer today.
- 2. Instead of single file containing protocol buffers, now matrices can
- be written in a matlab/octave friendly format. This is now the default.
+ Change-Id: If3d0284830c6591c71cc77b8400cafb45c0da61f
+
+commit aeb00a07323808a0a1816e733ad18a87d5109ea3
+Author: Petter Strandmark <strandmark@google.com>
+Date: Mon Aug 27 22:22:57 2012 -0700
+
+ Removing gomp for Visual Studio
- 3. The support for writing problems to disk is moved into
- linear_least_squares_problem.cc/h
+ Linking currently fails in Visual Studio due to a missing library
+ "gomp.lib". This is not needed in Visual Studio. OpenMP works
+ without it.
+
+ Change-Id: I39e204a8dd4f1b7425df7d4b222d86a8bb961432
+
+commit 6f362464ba99b800494d2f15c27768a342ddaa68
+Author: Markus Moll <markus.moll@esat.kuleuven.be>
+Date: Tue Aug 28 01:03:38 2012 +0200
+
+ Add some tests for DoglegStrategy.
- 4. SparseMatrix now has a ToTextFile virtual method which is
- implemented by each of its subclasses to write a (i,j,s) triplets.
+ Not necessarily a complete set.
- 5. Minor changes to simple_bundle_adjuster to enable logging at startup.
+ Change-Id: I14eb3a38c6fe976c8212f3934655411b6d1e0aa4
-commit d297f8d3d3f5025c24752f0f4c1ec2469a769f99
-Merge: 7e74d81 f8bd7fa
-Author: Keir Mierle <mierle@gmail.com>
-Date: Tue May 8 05:39:56 2012 -0700
+commit 122cf836a6dc9726489ce2fbecc6143bddc1caaf
+Author: Sameer Agarwal <sameeragarwal@google.com>
+Date: Fri Aug 24 16:28:27 2012 -0700
- Merge branch 'master' into windows
+ Documentation update.
+
+ Change-Id: I0a3c5ae4bc981a8f5bdd5a8905f923dc5f09a024
-commit f8bd7fa9aa9dbf64b6165606630287cf8cf21194
+commit 69081719f73da8de2935774a42d237837a91952a
Author: Keir Mierle <mierle@gmail.com>
-Date: Tue May 8 05:39:32 2012 -0700
+Date: Mon Aug 27 13:28:56 2012 -0700
- Small tweaks to the block jacobi preconditioner.
+ Remove unnecessary overload for hash<>
+
+ The overload for pointers in hash tables was applied in normal
+ usage of schur_ordering.cc. However, the tests did not include the
+ overload since they only included collections_port.h. As a result,
+ the routines in schur_ordering.cc were using a different hash
+ function than that inside the tests.
+
+ The fix is to remove the specialization. If this breaks one of the
+ compiler configurations, we will find a workaround at that time.
+
+ Change-Id: Idbf60415d5e2aec0c865b514ad0c577d21b91405
-commit 7e74d81ad57a159f14110eb5348b3bc7990b8bd4
-Merge: ecd7c8d e2a6cdc
-Author: Keir Mierle <mierle@gmail.com>
-Date: Mon May 7 07:02:49 2012 -0700
+commit 1762420b6ed76b1c4d30b913b2cac1927b666534
+Author: Sameer Agarwal <sameeragarwal@google.com>
+Date: Wed Aug 22 10:01:31 2012 -0700
- Merge branch 'master' into windows
+ Update changelog.
+
+ Change-Id: Idf5af69d5a9dbe35f58e30a8afcbfcd29bb7ebfe
-commit e2a6cdc0816af9d0c77933f5017f137da3d52a35
+commit 976ab7aca908309b8282cb40bc080ca859136854
Author: Keir Mierle <mierle@gmail.com>
-Date: Mon May 7 06:39:56 2012 -0700
+Date: Thu Aug 23 18:21:36 2012 -0700
- Address some of the comments on CGNR patch
+ Remove Google-era vestigial unit test.
- - Rename BlockDiagonalPreconditioner to BlockJacobiPreconditioner
- - Include the diagonal in the block jacobi preconditioner.
- - Better flag help for eta.
- - Enable test for CGNR
- - Rename CONJUGATE_GRADIENTS to CGNR.
- - etc.
+ Change-Id: Ia7a295a5c759a17c1675a3055d287d3e40e9e0fe
-commit 1b95dc580aa5d89be021c0915e26df83f18013bb
-Merge: 211812a 7646039
+commit 6ad6257de0e2152ac5e77dc003758de45187d6ea
Author: Keir Mierle <mierle@gmail.com>
-Date: Mon May 7 04:34:10 2012 -0700
+Date: Wed Aug 22 11:10:31 2012 -0700
- Merge branch 'master' of https://code.google.com/p/ceres-solver
+ Add a workaround for an Android NDK compiler bug.
+
+ On certain NDK build configurations, one of the innermost
+ parts of the Schur eliminator would get compiled
+ incorrectly. The compiler changed a -= to a +=.
+
+ The normal Ceres unit tests caught the problem; however,
+ since it is not possible to build the tests with the NDK
+ (only with the standalone toolchain) this was difficult to
+ track down. Finding the issue involved pasting the schur
+ eliminator unit test inside of solver_impl.cc and other such
+ hacks.
+
+ Change-Id: Ie91bb545d74fe39f0c8cbd1a6eb69ee4d8b25fb2
-commit 211812a57360d2011cbcfd115cd55e0eb73600db
-Author: Keir Mierle <mierle@gmail.com>
-Date: Mon May 7 04:33:50 2012 -0700
+commit aecb2dc92b4aa7f3bf77a1ac918e62953602392b
+Author: Sameer Agarwal <sameeragarwal@google.com>
+Date: Wed Aug 22 10:08:17 2012 -0700
- Better error handling in bundle_adjuster.cc
+ Fix relative path bug in bibtex call.
+
+ Change-Id: I0d31786564320a6831259bcdf4c75a6b665c43ad
-commit 7646039ad9672b267495f5b31925473ad3022ac8
+commit 1e2892009e591804df6286caebd5c960e7e3b099
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Sun May 6 22:02:19 2012 -0700
+Date: Tue Aug 21 18:00:54 2012 -0700
- Kashif's corrections to the docs
+ Update Summary::FullReport to report dogleg type.
+
+ Change-Id: I0b4be8d7486c1c4b36b299693b3fe8b0d3426537
-commit 0d2d34148d10c5c7e924b3ca82ad2b237573ef64
+commit 295ade1122a86b83e1ea605d5ca394f315874717
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Sun May 6 21:16:03 2012 -0700
+Date: Wed Aug 22 06:51:22 2012 -0700
- glog minimum version requirements
+ Fix Eigen3 Row/Column Major storage issue.
- Building Ceres requires version 0.3.1 or better of glog.
- Fedora 16 ships with a busted version 0.3.
+ Eigen3 does not allow column vectors to be stored in row-major
+ format. NumericDiffCostFunction by default stores its Jacobian
+ matrices in row-major format. This works fine if the residual
+ contains more than one variable. But if the residual block
+ depends on one variable and has more than one residuals, the
+ resulting Jacobian matrix is a column matrix in row-major format
+ resulting in a compile time error.
- issue 15 contains the gory details.
+ The fix is to check the template parameters and switch to column-major
+ storage as needed.
- Added a note to the build documentation to this effect.
+ Thanks to Lena Gieseke for reporting this.
+
+ Change-Id: Icc51c5b38e1f3609e0e1ecb3c4e4a02aecd72c3b
-commit 39efc5ec4b64b8f5a2c5a3dbacdbc45421221547
-Author: Keir Mierle <mierle@gmail.com>
-Date: Sun May 6 16:09:52 2012 -0700
+commit 9ad27e8e9fb1bbd2054e2f6ae37623e01428f1c0
+Author: Arnaud Gelas <arnaudgelas@gmail.com>
+Date: Tue Aug 21 09:56:30 2012 +0200
- Fix tests broken by the CGNR change.
+ Add one uninstall target to remove all installed files
+
+ Change-Id: Ifcf89a6c27b25f28403d95a50e29c093a525298f
-commit 3faa08b7f7c4ac73661c6a15a6824c12080dfcb1
-Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Sun May 6 16:08:22 2012 -0700
+commit 0c3a748ee49e04fe334f8f5a433649d18003d550
+Author: Markus Moll <markus.moll@esat.kuleuven.be>
+Date: Tue Aug 21 14:44:59 2012 +0200
- Formatting fixed based on Keir's comments and extended the tests
+ Allow equal lower and upper bound for diagonal scaling.
+
+ This way, setting the lower and upper bound both to 1.0, one can disable
+ the automatic trust region scaling.
+
+ Change-Id: Ifa317a6911b813a89c1cf7fdfde25af603705319
-commit 4f21c68409bc478c431a9b6aedf9e5cfdf11d2f3
-Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Sun May 6 15:33:47 2012 -0700
+commit 3d644b76adefac6475b91dc53c3ae5e01c4f4d66
+Author: Arnaud Gelas <arnaudgelas@gmail.com>
+Date: Thu Aug 16 17:33:21 2012 +0200
- Fix the struct weak ordering used by independent set ordering, tests for it
+ Install headers, libraries and pdf
+
+ Headers are installed in ${CMAKE_INSTALL_PREFIX}/include/ceres
+ Libraries are installed in ${CMAKE_INSTALL_PREFIX}/lib
+ pdf is installed in ${CMAKE_INSTALL_PREFIX}/share/ceres/docs
+
+ Change-Id: Ic175f2c2f5fa86820a1e8c64c2ed171f4a302a68
-commit 887b156b917ccd4c172484452b059d33ea45f4f0
-Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Sun May 6 15:14:47 2012 -0700
+commit d2fb5adea4d8c2aeb43c4289c6976798a54d3cf1
+Author: Arnaud Gelas <arnaudgelas@gmail.com>
+Date: Fri Aug 17 10:11:02 2012 +0200
- fix he degree ordering routine
+ Configure gerrit hook at CMake time
+
+ If the source directory is a clone, at CMake time the commit-msg hook gets
+ downloaded and installed in the right location.
+
+ Change-Id: I5fee17d050ca22d8b92a49fdcc2a1cd6659f209b
-commit ecd7c8df2af19404dc394b36bbe96e9db3bce840
-Author: Keir Mierle <mierle@gmail.com>
-Date: Sun May 6 00:09:41 2012 -0700
+commit 73166098fc4b1072adc30321c666188a3909c43c
+Author: Arnaud Gelas <arnaudgelas@gmail.com>
+Date: Mon Aug 20 15:40:41 2012 +0200
- First step towards windows compatibilty
+ Add one CMake option to build the examples.
+
+ Currently the examples are always built. For external projects, it is useful
+ not to compile the examples.
- This adds some small changes to Ceres to make it mostly
- compile on Windows. There are still issues with the
- hash map use in schur_ordering.cc but I will fix those
- shortly.
+ Change-Id: I41d3bde19c7e742818e60f78222d39c43992ca8b
-commit f7898fba1b92f0e996571b5bfa22a37f5e3644de
+commit 86d4f1ba41ef14eb1b6b61a7936af83387b35eb2
Author: Keir Mierle <mierle@gmail.com>
-Date: Sat May 5 20:55:08 2012 -0700
+Date: Mon Aug 20 11:52:04 2012 -0700
- Add a general sparse iterative solver: CGNR
+ Add missing return statement.
- This adds a new LinearOperator which implements symmetric
- products of a matrix, and a new CGNR solver to leverage
- CG to directly solve the normal equations. This also
- includes a block diagonal preconditioner. In experiments
- on problem-16, the non-preconditioned version is about
- 1/5 the speed of SPARSE_SCHUR, and the preconditioned
- version using block cholesky is about 20% slower than
- SPARSE_SCHUR.
+ Change-Id: I5eaf718318e27040e3c97e32ee46cf0a11176a37
-commit 0a359d6198d257776a8831c3eb98f64ee91cf836
+commit 51eb229da34187a4e8ce73ed9cc0e731998bb2be
Author: Keir Mierle <mierle@gmail.com>
-Date: Sat May 5 20:33:46 2012 -0700
+Date: Mon Aug 20 11:46:12 2012 -0700
- Comment formatting.
+ Add Program::ToString() to aid debugging.
+
+ Change-Id: I0ab37ed2fe0947ca87a152919d4e7dc9b56dedc6
-commit db4ec9312bb2f1ca7b2337812f6bad6cdd75b227
+commit bcc7100635e2047dc2b77df19a4ded8a6ab4d4b9
Author: Keir Mierle <mierle@gmail.com>
-Date: Sat May 5 20:33:16 2012 -0700
+Date: Mon Aug 20 11:45:04 2012 -0700
- Comment formatting
+ Ignore minted.sty.
+
+ Change-Id: I2467a6f801812b9007b51bf14b00757f026e4322
-commit f10163aaf3e57f52551bcd60bbdae873890a49dd
+commit 9705a736dd3d6fbead0d8a6ff77102c69bbcdc08
Author: Keir Mierle <mierle@gmail.com>
-Date: Fri May 4 21:33:53 2012 -0700
+Date: Mon Aug 20 11:24:05 2012 -0700
- Warn about disabled schur specializations.
+ Add ParameterBlock::ToString() to aid debugging.
- This commit brought to you from 30,000ft.
+ Change-Id: Id3f5cb27b855c536dd65a986f345bd8eb2799dfa
-commit ad7b2b4aaf3ccc51f2b854febd53a9df54686cfe
-Author: Keir Mierle <mierle@gmail.com>
-Date: Fri May 4 20:15:28 2012 -0700
+commit 0c714a70e6123ceb68e5cfcd3cfbee0d09deb1db
+Author: Sameer Agarwal <sameeragarwal@google.com>
+Date: Mon Aug 20 11:18:16 2012 -0700
+
+ Fix blanks before private in loss_function.h
+
+ Change-Id: I068bed6431bc7c9b7958af391655df61499000b2
+
+commit 51cf7cbe3bac45c6807c2703a2fc3175d76a1b47
+Author: Markus Moll <markus.moll@esat.kuleuven.be>
+Date: Mon Aug 20 20:10:20 2012 +0200
+
+ Add the two-dimensional subspace search to DoglegStrategy
+
+ Change-Id: I5163744c100cdf07dd93343d0734ffe0e80364f3
- Add vim swapfiles to .gitignore
+commit ad1f7b772e559a911ac3a3b078b0aee1836fe785
+Author: Sameer Agarwal <sameeragarwal@google.com>
+Date: Mon Aug 20 11:10:34 2012 -0700
+
+ Add ArcTanLoss, TolerantLoss and ComposedLossFunction.
+
+ Based on work by James Roseborough.
+
+ Change-Id: Idc4e0b099028f67702bfc7fe3e43dbd96b6f9256
-commit 6447219826bf6e47b0c99d9ff0eaf5e2ba573d79
+commit 05292bf8fc5208b86b4a13544615b584f6efa936
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Thu May 3 21:53:07 2012 -0700
+Date: Mon Aug 20 07:40:45 2012 -0700
+
+ Add a TrustRegionStrategy::Summary object.
+
+ Change-Id: I7caee35a3408ee4a0ec16ba407410d822929340d
- 1. Changes the tutorial to refer to BriefReport.
- 2. Some of the enums have commas at the end.
- 3. Fix a bug in the default value of circle_fit.cc in the examples.
+commit b12b906c4d21c3949f0dce62c4c0d083c8edecf1
+Author: Arnaud Gelas <arnaudgelas@gmail.com>
+Date: Wed Aug 15 16:27:38 2012 +0200
-commit 30c5f93c7f88dec49f76168663372772e06f17f5
+ Add one option to generate the PDF from CMake at build time
+
+ Make sure pygmentize is installed
+
+ Change-Id: I068ba45c33a8e96acc906a464b12d10d58b3e231
+
+commit b9f15a59361c609ffc4a328aea9be3d265b5da81
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Thu May 3 10:44:43 2012 -0700
+Date: Sat Aug 18 13:06:19 2012 -0700
+
+ Add a dense Cholesky factorization based linear solver.
+
+ For problems with a small number of variables, but a large
+ number of residuals, it is sometimes beneficial to use the
+ Cholesky factorization on the normal equations, instead of
+ the dense QR factorization of the Jacobian, even though it
+ is numerically the better thing to do.
+
+ Change-Id: I3506b006195754018deec964e6e190b7e8c9ac8f
- Rework the glog and gtest path checking to be consistent with the rest of the file and disable the dashboard support enabled by the earlier ctesting related patch.
+commit b3fa009435acf476cd373052e62988f6437970b1
+Author: Arnaud Gelas <arnaudgelas@gmail.com>
+Date: Fri Aug 17 10:31:41 2012 +0200
-commit f10b033eb4aca77919987bc551d16d8a88b10110
-Merge: cc38774 e0a52a9
+ Set CMAKE_*_OUTPUT_DIRECTORY
+
+ Gather
+ * all executables in ${CMAKE_BINARY_DIR}/bin
+ * all libraries (static and dynamic) in ${CMAKE_BINARY_DIR}/lib
+
+ Change-Id: Ibc2fa1adfb6f0aea65d66d570259b79546bf3b07
+
+commit 1b8a4d5d11671ed83cf6077e363dd95333f08ef8
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Thu May 3 08:45:20 2012 -0700
+Date: Fri Aug 17 16:49:11 2012 -0700
+
+ Fix a minor bug in detect_structure logging.
+
+ Change-Id: I117f7745e4c67595b3ff9244cde82b5b5b34ee4b
- Merge branch 'ctest'
+commit 31c1e784ab2cb9294c6e05414cf06aae2b3766de
+Author: Keir Mierle <mierle@gmail.com>
+Date: Fri Aug 17 16:16:32 2012 -0700
+
+ Minor cleanups.
+
+ Change-Id: Ida4866997deeaa1bc2cebd6b69313a05ac82e457
-commit e0a52a993394e73bc7f7db8d520728926feab83e
+commit e83f7879a8b21c6976e116958caf35bcdcf41cb0
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Thu May 3 08:43:34 2012 -0700
+Date: Fri Aug 17 15:34:42 2012 -0700
- Arnaus Gelas' patch to add better path searching for gflags and glog
+ Fix SuiteSparse3 UFConfig.h detection really.
+
+ Change-Id: Id187102e755b7d778dff4363f22f9a4697ed12dd
-commit a9b8e815e1c026599734510399b10f4cf014c9cd
+commit 96f25dc57658d296ee6b6633818b4f1e51d7d587
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Thu May 3 08:41:52 2012 -0700
+Date: Fri Aug 17 15:34:42 2012 -0700
+
+ Fix SuiteSparse3 UFConfig.h detection.
+
+ Change-Id: Ia59aefdb0ad7f713f76ed79692f2db4fa2821e5b
+
+commit c497bd6cd9aa944f518aa491d3bc645851ff9594
+Author: Markus Moll <markus.moll@esat.kuleuven.be>
+Date: Fri Aug 17 14:40:13 2012 +0200
- Arnaus Gelas' patch to add .gitignore
+ Add UFconfig and/or SuiteSparse_config test to CMakeLists.txt
+
+ SuiteSparse 4 requires linking to libsuitesparseconfig.a.
+ Both SuiteSparse 3 and SuiteSparse 4 require an additional header
+ (either UFconfig.h or SuiteSparse_config.h) that is not found if it is
+ in a separate path. Therefore, add explicit checks.
+
+ Change-Id: I699902b5db4f1b7f17134b5a54f9aa681445e294
-commit a0cefc3347c32b2065053bbaff4f34d11529d931
+commit 383c04f4236d92801c7c674892814362dedf7ad6
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Thu May 3 08:38:33 2012 -0700
+Date: Fri Aug 17 10:14:04 2012 -0700
- Arnaus Gelas' patch to move to Ctest
+ Fix QuaternionToAngleAxis to ensure rotations are between -pi and pi.
+
+ Thanks to Guoxuan Zhang for reporting this.
+
+ Change-Id: I2831ca3a04d5dc6467849c290461adbe23faaea3
-commit cc38774d74e287704915282425fbd16818a72ec3
-Author: Keir Mierle <mierle@gmail.com>
-Date: Thu May 3 01:27:50 2012 -0700
+commit dd2b17d7dd9750801ba4720bdece2062e59b7ae3
+Author: Sameer Agarwal <sameeragarwal@google.com>
+Date: Thu Aug 16 19:34:57 2012 -0700
- Clarify ProgramEvaluator comments.
+ CERES_DONT_HAVE_PROTOCOL_BUFFERS -> CERES_NO_PROTOCOL_BUFFERS.
+
+ Change-Id: I6c9f50e4c006faf4e75a8f417455db18357f3187
-commit 017c9530df557863f78212fb5ccd02814baa9fa8
+commit 8b4cb7aa2c74a0da62c638b2023566aa242af995
Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Wed May 2 08:21:59 2012 -0700
+Date: Thu Aug 16 19:26:55 2012 -0700
- Mac OS X build instructions are much simpler, as homebrew takes care of gflags when glog is brought in. Also CMAKE does not need any flags to do the default thing
+ Fix sparse linear algebra library logging in Summary::FullReport.
+
+ Change-Id: Id2c902dc86c00954fde7749c7b4a67dd94215a31
-commit 92d5ab5f8ae6fe355c30b606a5f230415ee0494b
-Author: Keir Mierle <mierle@gmail.com>
-Date: Tue May 1 18:33:08 2012 -0700
+commit 47d26bcd3b38b5ff53b34768c33b499d47b26bd0
+Author: Markus Moll <markus.moll@esat.kuleuven.be>
+Date: Thu Aug 16 00:23:38 2012 +0200
- Link BLAS explicitly on non-Mac platforms
+ Do not implicitly negate the step in the TrustRegionMinimizer.
- Fixes issue #3.
+ In the TrustRegionMinimizer, the step is currently implicitly negated.
+ This is done so that the linearized residual is |r - J*step|^2, which
+ corresponds to J*step = r, so neither J nor r have to be modified.
+ However, it leads to the rather unintuitive situation that the strategy
+ returns a step in positive gradient direction, which you would expect to
+ increase the function value. One way is to rename the "step" parameter in
+ the strategy to "negative_step" and document it.
+ This patch instead moves the negation inside the strategy, just around
+ the linear solver call, so that it is done in a local context and easier
+ to document.
+
+ Change-Id: Idb258149a01f61c64e22128ea221c5a30cd89c89
-commit df3e54eb4a6b001b7f0560a2da73a5bd7f18615e
-Author: Keir Mierle <mierle@gmail.com>
-Date: Tue May 1 18:22:51 2012 -0700
+commit 51da590c8457e6664f76fe9813425a0c71351497
+Author: Markus Moll <markus.moll@esat.kuleuven.be>
+Date: Fri Aug 17 12:56:09 2012 +0200
+
+ Remove tmp file
+
+ Change-Id: I07496fafae7b0c5c12cc26ae336e0db3b5592735
+
+commit 7006a1f2b1701b8d89b8d1525fc0101943802221
+Author: Sameer Agarwal <sameeragarwal@google.com>
+Date: Thu Aug 16 18:04:22 2012 -0700
- Fix link order of CHOLMOD
+ Correct example code in Powell's function example.
+
+ Thanks to Petter Strandmark for pointing this out.
- This was working by accident due to dynamic linking. Fixes issue #2.
+ Change-Id: I967632235dccdb481396e94904bb911c9a1efe1e
-commit f477a3835329e2b48eb20c34c631a480b0f0d5bf
+commit 57a44b27bc6fc95b4e70fdc25c25c9925a2072a0
Author: Keir Mierle <mierle@gmail.com>
-Date: Tue May 1 18:10:48 2012 -0700
+Date: Thu Aug 16 17:04:50 2012 -0700
- Fix Eigen search paths
+ Remove unnecessary flags in NDK build.
- Fixes issue #1 on http://code.google.com/p/ceres-solver.
+ Change-Id: Ib5b4d0b7f2d898671252734978c789b8171d96a8
-commit 17fbc8ebb894c1d22bb3b0b02ea1394b580120f8
-Author: Sameer Agarwal <sameeragarwal@google.com>
-Date: Tue May 1 00:21:19 2012 -0700
+commit f21bee247251a8b2e836c215a84c4668c31d75cd
+Author: Keir Mierle <mierle@gmail.com>
+Date: Thu Aug 16 16:27:10 2012 -0700
- Minor changes to the documentation. Formatting, and typos.
+ Fix for fpclassify.h NDK porting work.
+
+ Change-Id: I69df1b4caf2941ed96a53e35e43ec54073f84f59
-commit 8ebb0730388045570f22b89fe8672c860cd2ad1b
+commit 8ceb02cb75b66602de44a35e413225386cb21c27
Author: Keir Mierle <mierle@gmail.com>
-Date: Mon Apr 30 23:09:08 2012 -0700
+Date: Thu Aug 16 14:23:47 2012 -0700
- Initial commit of Ceres Solver.
+ Add Android NDK build files.
+
+ This adds a Android.mk build that builds a Ceres static library
+ suitable for embetting in larger Android applications. This is
+ useful when needing to build Ceres without GPL'd components, since
+ the standalone toolchain (needed for the CMake Android build) does
+ not work with STLPort.
+
+ Change-Id: I8d857237f6f82658741017d161b2e31d9a20e5a7
diff --git a/extern/libmv/third_party/ceres/SConscript b/extern/libmv/third_party/ceres/SConscript
index c629fa00176..6d0d2cd5c40 100644
--- a/extern/libmv/third_party/ceres/SConscript
+++ b/extern/libmv/third_party/ceres/SConscript
@@ -20,9 +20,13 @@ defs.append('CERES_HAVE_PTHREAD')
defs.append('CERES_HASH_NAMESPACE_START=namespace std { namespace tr1 {')
defs.append('CERES_HASH_NAMESPACE_END=}}')
defs.append('CERES_NO_SUITESPARSE')
-defs.append('CERES_DONT_HAVE_PROTOCOL_BUFFERS')
+defs.append('CERES_NO_CXSPARSE')
+defs.append('CERES_NO_PROTOCOL_BUFFERS')
defs.append('CERES_RESTRICT_SCHUR_SPECIALIZATION')
+if 'Mac OS X 10.5' in env['MACOSX_SDK_CHECK']:
+ defs.append('CERES_NO_TR1')
+
incs = '. ../../ ../../../Eigen3 ./include ./internal ../gflags'
# work around broken hashtable in 10.5 SDK
diff --git a/extern/libmv/third_party/ceres/bundle.sh b/extern/libmv/third_party/ceres/bundle.sh
index 99aaadd8d87..ccf6d0aca16 100755
--- a/extern/libmv/third_party/ceres/bundle.sh
+++ b/extern/libmv/third_party/ceres/bundle.sh
@@ -1,6 +1,5 @@
#!/bin/sh
-if false; then
if [ "x$1" = "x--i-really-know-what-im-doing" ] ; then
echo Proceeding as requested by command line ...
else
@@ -8,16 +7,22 @@ else
exit 1
fi
-repo="https://code.google.com/p/ceres-solver/"
-branch="windows"
+repo="https://ceres-solver.googlesource.com/ceres-solver"
+branch="master"
+tag="1.3.0"
tmp=`mktemp -d`
+checkout="$tmp/ceres"
-GIT="git --git-dir $tmp/ceres/.git --work-tree $tmp/ceres"
+GIT="git --git-dir $tmp/ceres/.git --work-tree $checkout"
-git clone $repo $tmp/ceres
+git clone $repo $checkout
if [ $branch != "master" ]; then
$GIT checkout -t remotes/origin/$branch
+else
+ if [ "x$tag" != "x" ]; then
+ $GIT checkout $tag
+ fi
fi
$GIT log -n 50 > ChangeLog
@@ -37,8 +42,6 @@ done
rm -rf $tmp
-fi
-
sources=`find ./include ./internal -type f -iname '*.cc' -or -iname '*.cpp' -or -iname '*.c' | sed -r 's/^\.\//\t/' | grep -v -E 'schur_eliminator_[0-9]_[0-9]_[0-9d].cc' | sort -d`
generated_sources=`find ./include ./internal -type f -iname '*.cc' -or -iname '*.cpp' -or -iname '*.c' | sed -r 's/^\.\//#\t\t/' | grep -E 'schur_eliminator_[0-9]_[0-9]_[0-9d].cc' | sort -d`
headers=`find ./include ./internal -type f -iname '*.h' | sed -r 's/^\.\//\t/' | sort -d`
@@ -114,13 +117,13 @@ cat > CMakeLists.txt << EOF
set(INC
.
- ../../../Eigen3
include
internal
../gflags
)
set(INC_SYS
+ ../../../Eigen3
)
set(SRC
@@ -142,7 +145,7 @@ if(WIN32)
if(NOT MINGW)
list(APPEND INC
- third_party/msinttypes
+ ../msinttypes
)
endif()
else()
@@ -153,13 +156,32 @@ endif()
add_definitions(
-DCERES_HAVE_PTHREAD
- -D"CERES_HASH_NAMESPACE_START=namespace std { namespace tr1 {"
- -D"CERES_HASH_NAMESPACE_END=}}"
-DCERES_NO_SUITESPARSE
- -DCERES_DONT_HAVE_PROTOCOL_BUFFERS
+ -DCERES_NO_CXSPARSE
+ -DCERES_NO_PROTOCOL_BUFFERS
-DCERES_RESTRICT_SCHUR_SPECIALIZATION
)
+if(MSVC10)
+ add_definitions(
+ -D"CERES_HASH_NAMESPACE_START=namespace std {"
+ -D"CERES_HASH_NAMESPACE_END=}"
+ )
+else()
+ add_definitions(
+ -D"CERES_HASH_NAMESPACE_START=namespace std { namespace tr1 {"
+ -D"CERES_HASH_NAMESPACE_END=}}"
+ )
+endif()
+
+if(APPLE)
+ if(CMAKE_OSX_DEPLOYMENT_TARGET STREQUAL "10.5")
+ add_definitions(
+ -DCERES_NO_TR1
+ )
+ endif()
+endif()
+
blender_add_lib(extern_ceres "\${SRC}" "\${INC}" "\${INC_SYS}")
EOF
@@ -186,11 +208,20 @@ defs.append('CERES_HAVE_PTHREAD')
defs.append('CERES_HASH_NAMESPACE_START=namespace std { namespace tr1 {')
defs.append('CERES_HASH_NAMESPACE_END=}}')
defs.append('CERES_NO_SUITESPARSE')
-defs.append('CERES_DONT_HAVE_PROTOCOL_BUFFERS')
+defs.append('CERES_NO_CXSPARSE')
+defs.append('CERES_NO_PROTOCOL_BUFFERS')
defs.append('CERES_RESTRICT_SCHUR_SPECIALIZATION')
+if 'Mac OS X 10.5' in env['MACOSX_SDK_CHECK']:
+ defs.append('CERES_NO_TR1')
+
incs = '. ../../ ../../../Eigen3 ./include ./internal ../gflags'
+# work around broken hashtable in 10.5 SDK
+if env['OURPLATFORM'] == 'darwin' and env['WITH_BF_BOOST']:
+ incs += ' ' + env['BF_BOOST_INC']
+ defs.append('CERES_HASH_BOOST')
+
if env['OURPLATFORM'] in ('win32-vc', 'win32-mingw', 'linuxcross', 'win64-vc', 'win64-mingw'):
if env['OURPLATFORM'] in ('win32-vc', 'win64-vc'):
incs += ' ../msinttypes'
diff --git a/extern/libmv/third_party/ceres/files.txt b/extern/libmv/third_party/ceres/files.txt
index e9d7f585260..55083572977 100644
--- a/extern/libmv/third_party/ceres/files.txt
+++ b/extern/libmv/third_party/ceres/files.txt
@@ -2,6 +2,8 @@ include/ceres/autodiff_cost_function.h
include/ceres/ceres.h
include/ceres/conditioned_cost_function.h
include/ceres/cost_function.h
+include/ceres/crs_matrix.h
+include/ceres/fpclassify.h
include/ceres/internal/autodiff.h
include/ceres/internal/eigen.h
include/ceres/internal/fixed_array.h
@@ -20,6 +22,8 @@ include/ceres/rotation.h
include/ceres/sized_cost_function.h
include/ceres/solver.h
include/ceres/types.h
+internal/ceres/array_utils.cc
+internal/ceres/array_utils.h
internal/ceres/block_evaluate_preparer.cc
internal/ceres/block_evaluate_preparer.h
internal/ceres/block_jacobian_writer.cc
@@ -52,13 +56,19 @@ internal/ceres/conjugate_gradients_solver.cc
internal/ceres/conjugate_gradients_solver.h
internal/ceres/corrector.cc
internal/ceres/corrector.h
+internal/ceres/cxsparse.cc
+internal/ceres/cxsparse.h
internal/ceres/dense_jacobian_writer.h
+internal/ceres/dense_normal_cholesky_solver.cc
+internal/ceres/dense_normal_cholesky_solver.h
internal/ceres/dense_qr_solver.cc
internal/ceres/dense_qr_solver.h
internal/ceres/dense_sparse_matrix.cc
internal/ceres/dense_sparse_matrix.h
internal/ceres/detect_structure.cc
internal/ceres/detect_structure.h
+internal/ceres/dogleg_strategy.cc
+internal/ceres/dogleg_strategy.h
internal/ceres/evaluator.cc
internal/ceres/evaluator.h
internal/ceres/file.cc
@@ -79,6 +89,7 @@ internal/ceres/generated/schur_eliminator_4_4_3.cc
internal/ceres/generated/schur_eliminator_4_4_4.cc
internal/ceres/generated/schur_eliminator_4_4_d.cc
internal/ceres/generated/schur_eliminator_d_d_d.cc
+internal/ceres/generate_eliminator_specialization.py
internal/ceres/gradient_checking_cost_function.cc
internal/ceres/gradient_checking_cost_function.h
internal/ceres/graph_algorithms.h
@@ -88,8 +99,8 @@ internal/ceres/implicit_schur_complement.h
internal/ceres/integral_types.h
internal/ceres/iterative_schur_complement_solver.cc
internal/ceres/iterative_schur_complement_solver.h
-internal/ceres/levenberg_marquardt.cc
-internal/ceres/levenberg_marquardt.h
+internal/ceres/levenberg_marquardt_strategy.cc
+internal/ceres/levenberg_marquardt_strategy.h
internal/ceres/linear_least_squares_problems.cc
internal/ceres/linear_least_squares_problems.h
internal/ceres/linear_operator.cc
@@ -106,6 +117,8 @@ internal/ceres/normal_prior.cc
internal/ceres/parameter_block.h
internal/ceres/partitioned_matrix_view.cc
internal/ceres/partitioned_matrix_view.h
+internal/ceres/polynomial_solver.cc
+internal/ceres/polynomial_solver.h
internal/ceres/problem.cc
internal/ceres/problem_impl.cc
internal/ceres/problem_impl.h
@@ -136,6 +149,7 @@ internal/ceres/sparse_matrix.h
internal/ceres/sparse_normal_cholesky_solver.cc
internal/ceres/sparse_normal_cholesky_solver.h
internal/ceres/split.cc
+internal/ceres/split.h
internal/ceres/stl_util.h
internal/ceres/stringprintf.cc
internal/ceres/stringprintf.h
@@ -143,6 +157,10 @@ internal/ceres/suitesparse.cc
internal/ceres/suitesparse.h
internal/ceres/triplet_sparse_matrix.cc
internal/ceres/triplet_sparse_matrix.h
+internal/ceres/trust_region_minimizer.cc
+internal/ceres/trust_region_minimizer.h
+internal/ceres/trust_region_strategy.cc
+internal/ceres/trust_region_strategy.h
internal/ceres/types.cc
internal/ceres/visibility_based_preconditioner.cc
internal/ceres/visibility_based_preconditioner.h
diff --git a/extern/libmv/third_party/ceres/include/ceres/autodiff_cost_function.h b/extern/libmv/third_party/ceres/include/ceres/autodiff_cost_function.h
index e86d6993864..da9ee2c7993 100644
--- a/extern/libmv/third_party/ceres/include/ceres/autodiff_cost_function.h
+++ b/extern/libmv/third_party/ceres/include/ceres/autodiff_cost_function.h
@@ -163,7 +163,7 @@ class AutoDiffCostFunction :
explicit AutoDiffCostFunction(CostFunctor* functor)
: functor_(functor) {
CHECK_NE(M, DYNAMIC) << "Can't run the fixed-size constructor if the "
- << "number of residuals is set to ceres::DYNAMIC.";
+ << "number of residuals is set to ceres::DYNAMIC.";
}
// Takes ownership of functor. Ignores the template-provided number of
@@ -174,7 +174,7 @@ class AutoDiffCostFunction :
AutoDiffCostFunction(CostFunctor* functor, int num_residuals)
: functor_(functor) {
CHECK_EQ(M, DYNAMIC) << "Can't run the dynamic-size constructor if the "
- << "number of residuals is not ceres::DYNAMIC.";
+ << "number of residuals is not ceres::DYNAMIC.";
SizedCostFunction<M, N0, N1, N2, N3, N4, N5>::set_num_residuals(num_residuals);
}
diff --git a/extern/libmv/third_party/ceres/include/ceres/cost_function.h b/extern/libmv/third_party/ceres/include/ceres/cost_function.h
index 84403d90636..9b010f78f9d 100644
--- a/extern/libmv/third_party/ceres/include/ceres/cost_function.h
+++ b/extern/libmv/third_party/ceres/include/ceres/cost_function.h
@@ -119,7 +119,7 @@ class CostFunction {
// number of outputs (residuals).
vector<int16> parameter_block_sizes_;
int num_residuals_;
- DISALLOW_COPY_AND_ASSIGN(CostFunction);
+ CERES_DISALLOW_COPY_AND_ASSIGN(CostFunction);
};
} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/include/ceres/crs_matrix.h b/extern/libmv/third_party/ceres/include/ceres/crs_matrix.h
new file mode 100644
index 00000000000..c9fe8f78b7c
--- /dev/null
+++ b/extern/libmv/third_party/ceres/include/ceres/crs_matrix.h
@@ -0,0 +1,65 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+
+#ifndef CERES_PUBLIC_CRS_MATRIX_H_
+#define CERES_PUBLIC_CRS_MATRIX_H_
+
+#include <vector>
+#include "ceres/internal/port.h"
+
+namespace ceres {
+
+// A compressed row sparse matrix used primarily for communicating the
+// Jacobian matrix to the user.
+struct CRSMatrix {
+ CRSMatrix() : num_rows(0), num_cols(0) {}
+
+ int num_rows;
+ int num_cols;
+
+ // A compressed row matrix stores its contents in three arrays.
+ // The non-zero pattern of the i^th row is given by
+ //
+ // rows[cols[i] ... cols[i + 1]]
+ //
+ // and the corresponding values by
+ //
+ // values[cols[i] ... cols[i + 1]]
+ //
+ // Thus, cols is a vector of size num_cols + 1, and rows and values
+ // have as many entries as number of non-zeros in the matrix.
+ vector<int> cols;
+ vector<int> rows;
+ vector<double> values;
+};
+
+} // namespace ceres
+
+#endif // CERES_PUBLIC_CRS_MATRIX_H_
diff --git a/extern/libmv/third_party/ceres/include/ceres/fpclassify.h b/extern/libmv/third_party/ceres/include/ceres/fpclassify.h
new file mode 100644
index 00000000000..5a9ea1599d2
--- /dev/null
+++ b/extern/libmv/third_party/ceres/include/ceres/fpclassify.h
@@ -0,0 +1,88 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: keir@google.com (Keir Mierle)
+//
+// Portable floating point classification. The names are picked such that they
+// do not collide with macros. For example, "isnan" in C99 is a macro and hence
+// does not respect namespaces.
+//
+// TODO(keir): Finish porting!
+
+#ifndef CERES_PUBLIC_FPCLASSIFY_H_
+#define CERES_PUBLIC_FPCLASSIFY_H_
+
+#if defined(_MSC_VER)
+#include <float.h>
+#endif
+
+namespace ceres {
+
+#if defined(_MSC_VER)
+inline bool IsFinite (double x) { return _finite(x); }
+inline bool IsInfinite(double x) { return !_finite(x) && !_isnan(x); }
+inline bool IsNaN (double x) { return _isnan(x); }
+inline bool IsNormal (double x) {
+ int classification = _fpclass(x);
+ return classification == _FPCLASS_NN ||
+ classification == _FPCLASS_PN;
+}
+#elif defined(ANDROID)
+
+// On Android when using the GNU STL, the C++ fpclassify functions are not
+// available. Strictly speaking, the std functions are are not standard until
+// C++11. Instead use the C99 macros on Android.
+inline bool IsNaN (double x) { return isnan(x); }
+inline bool IsNormal (double x) { return isnormal(x); }
+
+// On Android NDK r6, when using STLPort, the isinf and isfinite functions are
+// not available, so reimplement them.
+# if defined(_STLPORT_VERSION)
+inline bool IsInfinite(double x) {
+ return x == std::numeric_limits<double>::infinity() ||
+ x == -std::numeric_limits<double>::infinity();
+}
+inline bool IsFinite(double x) {
+ return !isnan(x) && !IsInfinite(x);
+}
+# else
+inline bool IsFinite (double x) { return isfinite(x); }
+inline bool IsInfinite(double x) { return isinf(x); }
+# endif // defined(_STLPORT_VERSION)
+#else
+// These definitions are for the normal Unix suspects.
+// TODO(keir): Test the "else" with more platforms.
+inline bool IsFinite (double x) { return std::isfinite(x); }
+inline bool IsInfinite(double x) { return std::isinf(x); }
+inline bool IsNaN (double x) { return std::isnan(x); }
+inline bool IsNormal (double x) { return std::isnormal(x); }
+#endif
+
+} // namespace ceres
+
+#endif // CERES_PUBLIC_FPCLASSIFY_H_
diff --git a/extern/libmv/third_party/ceres/include/ceres/internal/fixed_array.h b/extern/libmv/third_party/ceres/include/ceres/internal/fixed_array.h
index 84617c4fa06..ce777d22dc7 100644
--- a/extern/libmv/third_party/ceres/include/ceres/internal/fixed_array.h
+++ b/extern/libmv/third_party/ceres/include/ceres/internal/fixed_array.h
@@ -34,6 +34,8 @@
#include <cstddef>
#include <glog/logging.h>
+#include "Eigen/Core"
+#include "ceres/internal/macros.h"
#include "ceres/internal/manual_constructor.h"
namespace ceres {
@@ -136,7 +138,6 @@ class FixedArray {
// and T must be the same, otherwise callers' assumptions about use
// of this code will be broken.
struct InnerContainer {
- EIGEN_MAKE_ALIGNED_OPERATOR_NEW
T element;
};
diff --git a/extern/libmv/third_party/ceres/include/ceres/internal/macros.h b/extern/libmv/third_party/ceres/include/ceres/internal/macros.h
index 0cfd773bcca..83ec31193e7 100644
--- a/extern/libmv/third_party/ceres/include/ceres/internal/macros.h
+++ b/extern/libmv/third_party/ceres/include/ceres/internal/macros.h
@@ -43,11 +43,13 @@
//
// For disallowing only assign or copy, write the code directly, but declare
// the intend in a comment, for example:
-// void operator=(const TypeName&); // DISALLOW_ASSIGN
-// Note, that most uses of DISALLOW_ASSIGN and DISALLOW_COPY are broken
-// semantically, one should either use disallow both or neither. Try to
-// avoid these in new code.
-#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
+//
+// void operator=(const TypeName&); // _DISALLOW_ASSIGN
+
+// Note, that most uses of CERES_DISALLOW_ASSIGN and CERES_DISALLOW_COPY
+// are broken semantically, one should either use disallow both or
+// neither. Try to avoid these in new code.
+#define CERES_DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
@@ -57,9 +59,9 @@
// This should be used in the private: declarations for a class
// that wants to prevent anyone from instantiating it. This is
// especially useful for classes containing only static methods.
-#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
+#define CERES_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
TypeName(); \
- DISALLOW_COPY_AND_ASSIGN(TypeName)
+ CERES_DISALLOW_COPY_AND_ASSIGN(TypeName)
// The arraysize(arr) macro returns the # of elements in an array arr.
// The expression is a compile-time constant, and therefore can be
@@ -151,4 +153,19 @@ char (&ArraySizeHelper(const T (&array)[N]))[N];
#define MUST_USE_RESULT
#endif
+// Platform independent macros to get aligned memory allocations.
+// For example
+//
+// MyFoo my_foo CERES_ALIGN_ATTRIBUTE(16);
+//
+// Gives us an instance of MyFoo which is aligned at a 16 byte
+// boundary.
+#if defined(_MSC_VER)
+#define CERES_ALIGN_ATTRIBUTE(n) __declspec(align(n))
+#define CERES_ALIGN_OF(T) __alignof(T)
+#elif defined(__GNUC__)
+#define CERES_ALIGN_ATTRIBUTE(n) __attribute__((aligned(n)))
+#define CERES_ALIGN_OF(T) __alignof(T)
+#endif
+
#endif // CERES_PUBLIC_INTERNAL_MACROS_H_
diff --git a/extern/libmv/third_party/ceres/include/ceres/internal/manual_constructor.h b/extern/libmv/third_party/ceres/include/ceres/internal/manual_constructor.h
index a1d1f444e36..174d35ee2bd 100644
--- a/extern/libmv/third_party/ceres/include/ceres/internal/manual_constructor.h
+++ b/extern/libmv/third_party/ceres/include/ceres/internal/manual_constructor.h
@@ -45,60 +45,49 @@
namespace ceres {
namespace internal {
-// ------- Define ALIGNED_CHAR_ARRAY --------------------------------
+// ------- Define CERES_ALIGNED_CHAR_ARRAY --------------------------------
-#ifndef ALIGNED_CHAR_ARRAY
+#ifndef CERES_ALIGNED_CHAR_ARRAY
// Because MSVC and older GCCs require that the argument to their alignment
// construct to be a literal constant integer, we use a template instantiated
// at all the possible powers of two.
template<int alignment, int size> struct AlignType { };
template<int size> struct AlignType<0, size> { typedef char result[size]; };
-#if defined(_MSC_VER)
-#define BASE_PORT_H_ALIGN_ATTRIBUTE(X) __declspec(align(X))
-#define BASE_PORT_H_ALIGN_OF(T) __alignof(T)
-#elif defined(__GNUC__)
-#define BASE_PORT_H_ALIGN_ATTRIBUTE(X) __attribute__((aligned(X)))
-#define BASE_PORT_H_ALIGN_OF(T) __alignof__(T)
-#endif
-#if defined(BASE_PORT_H_ALIGN_ATTRIBUTE)
+#if !defined(CERES_ALIGN_ATTRIBUTE)
+#define CERES_ALIGNED_CHAR_ARRAY you_must_define_CERES_ALIGNED_CHAR_ARRAY_for_your_compiler
+#else // !defined(CERES_ALIGN_ATTRIBUTE)
-#define BASE_PORT_H_ALIGNTYPE_TEMPLATE(X) \
+#define CERES_ALIGN_TYPE_TEMPLATE(X) \
template<int size> struct AlignType<X, size> { \
- typedef BASE_PORT_H_ALIGN_ATTRIBUTE(X) char result[size]; \
- }
-
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(1);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(2);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(4);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(8);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(16);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(32);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(64);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(128);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(256);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(512);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(1024);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(2048);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(4096);
-BASE_PORT_H_ALIGNTYPE_TEMPLATE(8192);
+ typedef CERES_ALIGN_ATTRIBUTE(X) char result[size]; \
+ }
+
+CERES_ALIGN_TYPE_TEMPLATE(1);
+CERES_ALIGN_TYPE_TEMPLATE(2);
+CERES_ALIGN_TYPE_TEMPLATE(4);
+CERES_ALIGN_TYPE_TEMPLATE(8);
+CERES_ALIGN_TYPE_TEMPLATE(16);
+CERES_ALIGN_TYPE_TEMPLATE(32);
+CERES_ALIGN_TYPE_TEMPLATE(64);
+CERES_ALIGN_TYPE_TEMPLATE(128);
+CERES_ALIGN_TYPE_TEMPLATE(256);
+CERES_ALIGN_TYPE_TEMPLATE(512);
+CERES_ALIGN_TYPE_TEMPLATE(1024);
+CERES_ALIGN_TYPE_TEMPLATE(2048);
+CERES_ALIGN_TYPE_TEMPLATE(4096);
+CERES_ALIGN_TYPE_TEMPLATE(8192);
// Any larger and MSVC++ will complain.
-#define ALIGNED_CHAR_ARRAY(T, Size) \
- typename AlignType<BASE_PORT_H_ALIGN_OF(T), sizeof(T) * Size>::result
+#undef CERES_ALIGN_TYPE_TEMPLATE
-#undef BASE_PORT_H_ALIGNTYPE_TEMPLATE
-#undef BASE_PORT_H_ALIGN_ATTRIBUTE
+#define CERES_ALIGNED_CHAR_ARRAY(T, Size) \
+ typename AlignType<CERES_ALIGN_OF(T), sizeof(T) * Size>::result
-#else // defined(BASE_PORT_H_ALIGN_ATTRIBUTE)
-#define ALIGNED_CHAR_ARRAY you_must_define_ALIGNED_CHAR_ARRAY_for_your_compiler
-#endif // defined(BASE_PORT_H_ALIGN_ATTRIBUTE)
+#endif // !defined(CERES_ALIGN_ATTRIBUTE)
-#undef BASE_PORT_H_ALIGNTYPE_TEMPLATE
-#undef BASE_PORT_H_ALIGN_ATTRIBUTE
-
-#endif // ALIGNED_CHAR_ARRAY
+#endif // CERES_ALIGNED_CHAR_ARRAY
template <typename Type>
class ManualConstructor {
@@ -203,10 +192,10 @@ class ManualConstructor {
}
private:
- ALIGNED_CHAR_ARRAY(Type, 1) space_;
+ CERES_ALIGNED_CHAR_ARRAY(Type, 1) space_;
};
-#undef ALIGNED_CHAR_ARRAY
+#undef CERES_ALIGNED_CHAR_ARRAY
} // namespace internal
} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/include/ceres/internal/port.h b/extern/libmv/third_party/ceres/include/ceres/internal/port.h
index 9a3e5cced58..a9fe247cef5 100644
--- a/extern/libmv/third_party/ceres/include/ceres/internal/port.h
+++ b/extern/libmv/third_party/ceres/include/ceres/internal/port.h
@@ -31,6 +31,8 @@
#ifndef CERES_PUBLIC_INTERNAL_PORT_H_
#define CERES_PUBLIC_INTERNAL_PORT_H_
+#include <string>
+
namespace ceres {
// It is unfortunate that this import of the entire standard namespace is
@@ -39,6 +41,10 @@ namespace ceres {
// things outside of the Ceres optimization package.
using namespace std;
+// This is necessary to properly handle the case that there is a different
+// "string" implementation in the global namespace.
+using std::string;
+
} // namespace ceres
#endif // CERES_PUBLIC_INTERNAL_PORT_H_
diff --git a/extern/libmv/third_party/ceres/include/ceres/iteration_callback.h b/extern/libmv/third_party/ceres/include/ceres/iteration_callback.h
index 88da992d0c5..29157d380f2 100644
--- a/extern/libmv/third_party/ceres/include/ceres/iteration_callback.h
+++ b/extern/libmv/third_party/ceres/include/ceres/iteration_callback.h
@@ -28,8 +28,9 @@
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
//
-// When an iteration callback is specified, Ceres calls the callback after each
-// optimizer step and pass it an IterationSummary object, defined below.
+// When an iteration callback is specified, Ceres calls the callback
+// after each minimizer step (if the minimizer has not converged) and
+// passes it an IterationSummary object, defined below.
#ifndef CERES_PUBLIC_ITERATION_CALLBACK_H_
#define CERES_PUBLIC_ITERATION_CALLBACK_H_
@@ -44,7 +45,15 @@ struct IterationSummary {
// Current iteration number.
int32 iteration;
+ // Step was numerically valid, i.e., all values are finite and the
+ // step reduces the value of the linearized model.
+ //
+ // Note: step_is_valid is false when iteration = 0.
+ bool step_is_valid;
+
// Whether or not the algorithm made progress in this iteration.
+ //
+ // Note: step_is_successful is false when iteration = 0.
bool step_is_successful;
// Value of the objective function.
@@ -66,9 +75,10 @@ struct IterationSummary {
// cost and the change in the cost of the linearized approximation.
double relative_decrease;
- // Value of the regularization parameter for Levenberg-Marquardt
- // algorithm at the end of the current iteration.
- double mu;
+ // Size of the trust region at the end of the current iteration. For
+ // the Levenberg-Marquardt algorithm, the regularization parameter
+ // mu = 1.0 / trust_region_radius.
+ double trust_region_radius;
// For the inexact step Levenberg-Marquardt algorithm, this is the
// relative accuracy with which the Newton(LM) step is solved. This
@@ -81,13 +91,15 @@ struct IterationSummary {
// Newton step.
int linear_solver_iterations;
- // TODO(sameeragarwal): Change to use a higher precision timer using
- // clock_gettime.
- // Time (in seconds) spent inside the linear least squares solver.
- int iteration_time_sec;
+ // Time (in seconds) spent inside the minimizer loop in the current
+ // iteration.
+ double iteration_time_in_seconds;
+
+ // Time (in seconds) spent inside the trust region step solver.
+ double step_solver_time_in_seconds;
- // Time (in seconds) spent inside the linear least squares solver.
- int linear_solver_time_sec;
+ // Time (in seconds) since the user called Solve().
+ double cumulative_time_in_seconds;
};
// Interface for specifying callbacks that are executed at the end of
@@ -133,7 +145,7 @@ struct IterationSummary {
// summary.gradient_max_norm,
// summary.step_norm,
// summary.relative_decrease,
-// summary.mu,
+// summary.trust_region_radius,
// summary.eta,
// summary.linear_solver_iterations);
// if (log_to_stdout_) {
diff --git a/extern/libmv/third_party/ceres/include/ceres/jet.h b/extern/libmv/third_party/ceres/include/ceres/jet.h
index a37870210f1..96e2256fd02 100644
--- a/extern/libmv/third_party/ceres/include/ceres/jet.h
+++ b/extern/libmv/third_party/ceres/include/ceres/jet.h
@@ -162,16 +162,7 @@
#include <string>
#include "Eigen/Core"
-
-// Visual Studio 2012 or older version
-#if defined(_MSC_VER) && _MSC_VER <= 1700
-namespace std {
-inline bool isfinite(double x) { return _finite(x); }
-inline bool isinf (double x) { return !_finite(x) && !_isnan(x); }
-inline bool isnan (double x) { return _isnan(x); }
-inline bool isnormal(double x) { return _finite(x) && x != 0.0; }
-} // namespace std
-#endif
+#include "ceres/fpclassify.h"
namespace ceres {
@@ -184,7 +175,9 @@ struct Jet {
// (where T is a Jet<T, N>). This usually only happens in opt mode. Note that
// the C++ standard mandates that e.g. default constructed doubles are
// initialized to 0.0; see sections 8.5 of the C++03 standard.
- Jet() : a() {}
+ Jet() : a() {
+ v.setZero();
+ }
// Constructor from scalar: a + 0.
explicit Jet(const T& value) {
@@ -199,18 +192,6 @@ struct Jet {
v[k] = T(1.0);
}
- /*
-
- // Construct from an array where the first element is the scalar.
- // This is templated to support converting from other data types.
- template<typename D>
- Jet(const D* scalar_and_derivatives) {
- a = T(scalar_and_derivatives[0]);
- v = Eigen::Map<const Eigen::Matrix<D, N, 1> >(
- scalar_and_derivatives + 1, N).cast<T>();
- }
- */
-
// Compound operators
Jet<T, N>& operator+=(const Jet<T, N> &y) {
*this = *this + y;
@@ -232,8 +213,25 @@ struct Jet {
return *this;
}
- T a; // The scalar part.
- Eigen::Matrix<T, N, 1> v; // The infinitesimal part.
+ // The scalar part.
+ T a;
+
+ // The infinitesimal part.
+ //
+ // Note the Eigen::DontAlign bit is needed here because this object
+ // gets allocated on the stack and as part of other arrays and
+ // structs. Forcing the right alignment there is the source of much
+ // pain and suffering. Even if that works, passing Jets around to
+ // functions by value has problems because the C++ ABI does not
+ // guarantee alignment for function arguments.
+ //
+ // Setting the DontAlign bit prevents Eigen from using SSE for the
+ // various operations on Jets. This is a small performance penalty
+ // since the AutoDiff code will still expose much of the code as
+ // statically sized loops to the compiler. But given the subtle
+ // issues that arise due to alignment, especially when dealing with
+ // multiple platforms, it seems to be a trade off worth making.
+ Eigen::Matrix<T, N, 1, Eigen::DontAlign> v;
};
// Unary +
@@ -411,10 +409,6 @@ inline double cos (double x) { return std::cos(x); }
inline double acos (double x) { return std::acos(x); }
inline double sin (double x) { return std::sin(x); }
inline double asin (double x) { return std::asin(x); }
-inline bool isfinite(double x) { return std::isfinite(x); }
-inline bool isinf (double x) { return std::isinf(x); }
-inline bool isnan (double x) { return std::isnan(x); }
-inline bool isnormal(double x) { return std::isnormal(x); }
inline double pow (double x, double y) { return std::pow(x, y); }
inline double atan2(double y, double x) { return std::atan2(y, x); }
@@ -492,22 +486,23 @@ Jet<T, N> asin(const Jet<T, N>& f) {
}
// Jet Classification. It is not clear what the appropriate semantics are for
-// these classifications. This picks that isfinite and isnormal are "all"
-// operations, i.e. all elements of the jet must be finite for the jet itself to
-// be finite (or normal). For isnan and isinf, the answer is less clear. This
-// takes a "any" approach for isnan and isinf such that if any part of a jet is
-// nan or inf, then the entire jet is nan or inf. This leads to strange
-// situations like a jet can be both isinf and isnan, but in practice the "any"
-// semantics are the most useful for e.g. checking that derivatives are sane.
+// these classifications. This picks that IsFinite and isnormal are "all"
+// operations, i.e. all elements of the jet must be finite for the jet itself
+// to be finite (or normal). For IsNaN and IsInfinite, the answer is less
+// clear. This takes a "any" approach for IsNaN and IsInfinite such that if any
+// part of a jet is nan or inf, then the entire jet is nan or inf. This leads
+// to strange situations like a jet can be both IsInfinite and IsNaN, but in
+// practice the "any" semantics are the most useful for e.g. checking that
+// derivatives are sane.
// The jet is finite if all parts of the jet are finite.
template <typename T, int N> inline
-bool isfinite(const Jet<T, N>& f) {
- if (!isfinite(f.a)) {
+bool IsFinite(const Jet<T, N>& f) {
+ if (!IsFinite(f.a)) {
return false;
}
for (int i = 0; i < N; ++i) {
- if (!isfinite(f.v[i])) {
+ if (!IsFinite(f.v[i])) {
return false;
}
}
@@ -516,12 +511,12 @@ bool isfinite(const Jet<T, N>& f) {
// The jet is infinite if any part of the jet is infinite.
template <typename T, int N> inline
-bool isinf(const Jet<T, N>& f) {
- if (isinf(f.a)) {
+bool IsInfinite(const Jet<T, N>& f) {
+ if (IsInfinite(f.a)) {
return true;
}
for (int i = 0; i < N; i++) {
- if (isinf(f.v[i])) {
+ if (IsInfinite(f.v[i])) {
return true;
}
}
@@ -530,12 +525,12 @@ bool isinf(const Jet<T, N>& f) {
// The jet is NaN if any part of the jet is NaN.
template <typename T, int N> inline
-bool isnan(const Jet<T, N>& f) {
- if (isnan(f.a)) {
+bool IsNaN(const Jet<T, N>& f) {
+ if (IsNaN(f.a)) {
return true;
}
for (int i = 0; i < N; ++i) {
- if (isnan(f.v[i])) {
+ if (IsNaN(f.v[i])) {
return true;
}
}
@@ -544,12 +539,12 @@ bool isnan(const Jet<T, N>& f) {
// The jet is normal if all parts of the jet are normal.
template <typename T, int N> inline
-bool isnormal(const Jet<T, N>& f) {
- if (!isnormal(f.a)) {
+bool IsNormal(const Jet<T, N>& f) {
+ if (!IsNormal(f.a)) {
return false;
}
for (int i = 0; i < N; ++i) {
- if (!isnormal(f.v[i])) {
+ if (!IsNormal(f.v[i])) {
return false;
}
}
@@ -650,78 +645,6 @@ inline std::ostream &operator<<(std::ostream &s, const Jet<T, N>& z) {
return s << "[" << z.a << " ; " << z.v.transpose() << "]";
}
-// A jet traits class to make it easier to work with mixed auto / numeric diff.
-template<typename T>
-struct JetOps {
- static bool IsScalar() {
- return true;
- }
- static T GetScalar(const T& t) {
- return t;
- }
- static void SetScalar(const T& scalar, T* t) {
- *t = scalar;
- }
- static void ScaleDerivative(double scale_by, T *value) {
- // For double, there is no derivative to scale.
- }
-};
-
-template<typename T, int N>
-struct JetOps<Jet<T, N> > {
- static bool IsScalar() {
- return false;
- }
- static T GetScalar(const Jet<T, N>& t) {
- return t.a;
- }
- static void SetScalar(const T& scalar, Jet<T, N>* t) {
- t->a = scalar;
- }
- static void ScaleDerivative(double scale_by, Jet<T, N> *value) {
- value->v *= scale_by;
- }
-};
-
-template<typename FunctionType, int kNumArgs, typename ArgumentType>
-struct Chain {
- static ArgumentType Rule(const FunctionType &f,
- const FunctionType dfdx[kNumArgs],
- const ArgumentType x[kNumArgs]) {
- // In the default case of scalars, there's nothing to do since there are no
- // derivatives to propagate.
- return f;
- }
-};
-
-// XXX Add documentation here!
-template<typename FunctionType, int kNumArgs, typename T, int N>
-struct Chain<FunctionType, kNumArgs, Jet<T, N> > {
- static Jet<T, N> Rule(const FunctionType &f,
- const FunctionType dfdx[kNumArgs],
- const Jet<T, N> x[kNumArgs]) {
- // x is itself a function of another variable ("z"); what this function
- // needs to return is "f", but with the derivative with respect to z
- // attached to the jet. So combine the derivative part of x's jets to form
- // a Jacobian matrix between x and z (i.e. dx/dz).
- Eigen::Matrix<T, kNumArgs, N> dxdz;
- for (int i = 0; i < kNumArgs; ++i) {
- dxdz.row(i) = x[i].v.transpose();
- }
-
- // Map the input gradient dfdx into an Eigen row vector.
- Eigen::Map<const Eigen::Matrix<FunctionType, 1, kNumArgs> >
- vector_dfdx(dfdx, 1, kNumArgs);
-
- // Now apply the chain rule to obtain df/dz. Combine the derivative with
- // the scalar part to obtain f with full derivative information.
- Jet<T, N> jet_f;
- jet_f.a = f;
- jet_f.v = vector_dfdx.template cast<T>() * dxdz; // Also known as dfdz.
- return jet_f;
- }
-};
-
} // namespace ceres
namespace Eigen {
diff --git a/extern/libmv/third_party/ceres/include/ceres/loss_function.h b/extern/libmv/third_party/ceres/include/ceres/loss_function.h
index 81add02cdee..0c0ceaaecd0 100644
--- a/extern/libmv/third_party/ceres/include/ceres/loss_function.h
+++ b/extern/libmv/third_party/ceres/include/ceres/loss_function.h
@@ -175,6 +175,7 @@ class HuberLoss : public LossFunction {
public:
explicit HuberLoss(double a) : a_(a), b_(a * a) { }
virtual void Evaluate(double, double*) const;
+
private:
const double a_;
// b = a^2.
@@ -190,6 +191,7 @@ class SoftLOneLoss : public LossFunction {
public:
explicit SoftLOneLoss(double a) : b_(a * a), c_(1 / b_) { }
virtual void Evaluate(double, double*) const;
+
private:
// b = a^2.
const double b_;
@@ -206,6 +208,7 @@ class CauchyLoss : public LossFunction {
public:
explicit CauchyLoss(double a) : b_(a * a), c_(1 / b_) { }
virtual void Evaluate(double, double*) const;
+
private:
// b = a^2.
const double b_;
@@ -213,6 +216,78 @@ class CauchyLoss : public LossFunction {
const double c_;
};
+// Loss that is capped beyond a certain level using the arc-tangent function.
+// The scaling parameter 'a' determines the level where falloff occurs.
+// For costs much smaller than 'a', the loss function is linear and behaves like
+// TrivialLoss, and for values much larger than 'a' the value asymptotically
+// approaches the constant value of a * PI / 2.
+//
+// rho(s) = a atan(s / a).
+//
+// At s = 0: rho = [0, 1, 0].
+class ArctanLoss : public LossFunction {
+ public:
+ explicit ArctanLoss(double a) : a_(a), b_(1 / (a * a)) { }
+ virtual void Evaluate(double, double*) const;
+
+ private:
+ const double a_;
+ // b = 1 / a^2.
+ const double b_;
+};
+
+// Loss function that maps to approximately zero cost in a range around the
+// origin, and reverts to linear in error (quadratic in cost) beyond this range.
+// The tolerance parameter 'a' sets the nominal point at which the
+// transition occurs, and the transition size parameter 'b' sets the nominal
+// distance over which most of the transition occurs. Both a and b must be
+// greater than zero, and typically b will be set to a fraction of a.
+// The slope rho'[s] varies smoothly from about 0 at s <= a - b to
+// about 1 at s >= a + b.
+//
+// The term is computed as:
+//
+// rho(s) = b log(1 + exp((s - a) / b)) - c0.
+//
+// where c0 is chosen so that rho(0) == 0
+//
+// c0 = b log(1 + exp(-a / b)
+//
+// This has the following useful properties:
+//
+// rho(s) == 0 for s = 0
+// rho'(s) ~= 0 for s << a - b
+// rho'(s) ~= 1 for s >> a + b
+// rho''(s) > 0 for all s
+//
+// In addition, all derivatives are continuous, and the curvature is
+// concentrated in the range a - b to a + b.
+//
+// At s = 0: rho = [0, ~0, ~0].
+class TolerantLoss : public LossFunction {
+ public:
+ explicit TolerantLoss(double a, double b);
+ virtual void Evaluate(double, double*) const;
+
+ private:
+ const double a_, b_, c_;
+};
+
+// Composition of two loss functions. The error is the result of first
+// evaluating g followed by f to yield the composition f(g(s)).
+// The loss functions must not be NULL.
+class ComposedLoss : public LossFunction {
+ public:
+ explicit ComposedLoss(const LossFunction* f, Ownership ownership_f,
+ const LossFunction* g, Ownership ownership_g);
+ virtual ~ComposedLoss();
+ virtual void Evaluate(double, double*) const;
+
+ private:
+ internal::scoped_ptr<const LossFunction> f_, g_;
+ const Ownership ownership_f_, ownership_g_;
+};
+
// The discussion above has to do with length scaling: it affects the space
// in which s is measured. Sometimes you want to simply scale the output
// value of the robustifier. For example, you might want to weight
@@ -249,7 +324,7 @@ class ScaledLoss : public LossFunction {
internal::scoped_ptr<const LossFunction> rho_;
const double a_;
const Ownership ownership_;
- DISALLOW_COPY_AND_ASSIGN(ScaledLoss);
+ CERES_DISALLOW_COPY_AND_ASSIGN(ScaledLoss);
};
// Sometimes after the optimization problem has been constructed, we
@@ -314,7 +389,7 @@ class LossFunctionWrapper : public LossFunction {
private:
internal::scoped_ptr<const LossFunction> rho_;
Ownership ownership_;
- DISALLOW_COPY_AND_ASSIGN(LossFunctionWrapper);
+ CERES_DISALLOW_COPY_AND_ASSIGN(LossFunctionWrapper);
};
} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/include/ceres/numeric_diff_cost_function.h b/extern/libmv/third_party/ceres/include/ceres/numeric_diff_cost_function.h
index bbaefca5b6c..8544e44d0bc 100644
--- a/extern/libmv/third_party/ceres/include/ceres/numeric_diff_cost_function.h
+++ b/extern/libmv/third_party/ceres/include/ceres/numeric_diff_cost_function.h
@@ -93,11 +93,13 @@ struct Differencer {
using Eigen::Map;
using Eigen::Matrix;
using Eigen::RowMajor;
+ using Eigen::ColMajor;
typedef Matrix<double, num_residuals, 1> ResidualVector;
typedef Matrix<double, parameter_block_size, 1> ParameterVector;
- typedef Matrix<double, num_residuals, parameter_block_size, RowMajor>
- JacobianMatrix;
+ typedef Matrix<double, num_residuals, parameter_block_size,
+ (parameter_block_size == 1 &&
+ num_residuals > 1) ? ColMajor : RowMajor> JacobianMatrix;
Map<JacobianMatrix> parameter_jacobian(jacobians[parameter_block],
num_residuals,
diff --git a/extern/libmv/third_party/ceres/include/ceres/problem.h b/extern/libmv/third_party/ceres/include/ceres/problem.h
index 0ca61006bdb..2b08c6723e8 100644
--- a/extern/libmv/third_party/ceres/include/ceres/problem.h
+++ b/extern/libmv/third_party/ceres/include/ceres/problem.h
@@ -50,13 +50,13 @@ namespace ceres {
class CostFunction;
class LossFunction;
class LocalParameterization;
+class Solver;
namespace internal {
class Preprocessor;
class ProblemImpl;
class ParameterBlock;
class ResidualBlock;
-class SolverImpl;
} // namespace internal
// A ResidualBlockId is a handle clients can use to delete residual
@@ -255,9 +255,9 @@ class Problem {
int NumResiduals() const;
private:
- friend class internal::SolverImpl;
+ friend class Solver;
internal::scoped_ptr<internal::ProblemImpl> problem_impl_;
- DISALLOW_COPY_AND_ASSIGN(Problem);
+ CERES_DISALLOW_COPY_AND_ASSIGN(Problem);
};
} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/include/ceres/rotation.h b/extern/libmv/third_party/ceres/include/ceres/rotation.h
index e4227e78b9a..0d8a390d5d1 100644
--- a/extern/libmv/third_party/ceres/include/ceres/rotation.h
+++ b/extern/libmv/third_party/ceres/include/ceres/rotation.h
@@ -47,6 +47,7 @@
#include <algorithm>
#include <cmath>
+#include "glog/logging.h"
namespace ceres {
@@ -145,18 +146,11 @@ void AngleAxisRotatePoint(const T angle_axis[3], const T pt[3], T result[3]);
// --- IMPLEMENTATION
-// Duplicate rather than decorate every use of cmath with _USE_MATH_CONSTANTS.
-// Necessitated by Windows.
-#ifndef M_PI
-#define M_PI 3.14159265358979323846
-#define CERES_NEED_M_PI_UNDEF
-#endif
-
template<typename T>
inline void AngleAxisToQuaternion(const T* angle_axis, T* quaternion) {
- const T &a0 = angle_axis[0];
- const T &a1 = angle_axis[1];
- const T &a2 = angle_axis[2];
+ const T& a0 = angle_axis[0];
+ const T& a1 = angle_axis[1];
+ const T& a2 = angle_axis[2];
const T theta_squared = a0 * a0 + a1 * a1 + a2 * a2;
// For points not at the origin, the full conversion is numerically stable.
@@ -183,16 +177,35 @@ inline void AngleAxisToQuaternion(const T* angle_axis, T* quaternion) {
template<typename T>
inline void QuaternionToAngleAxis(const T* quaternion, T* angle_axis) {
- const T &q1 = quaternion[1];
- const T &q2 = quaternion[2];
- const T &q3 = quaternion[3];
- const T sin_squared = q1 * q1 + q2 * q2 + q3 * q3;
+ const T& q1 = quaternion[1];
+ const T& q2 = quaternion[2];
+ const T& q3 = quaternion[3];
+ const T sin_squared_theta = q1 * q1 + q2 * q2 + q3 * q3;
// For quaternions representing non-zero rotation, the conversion
// is numerically stable.
- if (sin_squared > T(0.0)) {
- const T sin_theta = sqrt(sin_squared);
- const T k = T(2.0) * atan2(sin_theta, quaternion[0]) / sin_theta;
+ if (sin_squared_theta > T(0.0)) {
+ const T sin_theta = sqrt(sin_squared_theta);
+ const T& cos_theta = quaternion[0];
+
+ // If cos_theta is negative, theta is greater than pi/2, which
+ // means that angle for the angle_axis vector which is 2 * theta
+ // would be greater than pi.
+ //
+ // While this will result in the correct rotation, it does not
+ // result in a normalized angle-axis vector.
+ //
+ // In that case we observe that 2 * theta ~ 2 * theta - 2 * pi,
+ // which is equivalent saying
+ //
+ // theta - pi = atan(sin(theta - pi), cos(theta - pi))
+ // = atan(-sin(theta), -cos(theta))
+ //
+ const T two_theta =
+ T(2.0) * ((cos_theta < 0.0)
+ ? atan2(-sin_theta, -cos_theta)
+ : atan2(sin_theta, cos_theta));
+ const T k = two_theta / sin_theta;
angle_axis[0] = q1 * k;
angle_axis[1] = q2 * k;
angle_axis[2] = q3 * k;
@@ -259,7 +272,7 @@ inline void RotationMatrixToAngleAxis(const T * R, T * angle_axis) {
// Case 2: theta ~ 0, means sin(theta) ~ theta to a good
// approximation.
- if (costheta > 0) {
+ if (costheta > 0.0) {
const T kHalf = T(0.5);
for (int i = 0; i < 3; ++i) {
angle_axis[i] *= kHalf;
@@ -284,8 +297,8 @@ inline void RotationMatrixToAngleAxis(const T * R, T * angle_axis) {
// angle_axis[i] should be positive, otherwise negative.
for (int i = 0; i < 3; ++i) {
angle_axis[i] = theta * sqrt((R[i*4] - costheta) * inv_one_minus_costheta);
- if (((sintheta < 0) && (angle_axis[i] > 0)) ||
- ((sintheta > 0) && (angle_axis[i] < 0))) {
+ if (((sintheta < 0.0) && (angle_axis[i] > 0.0)) ||
+ ((sintheta > 0.0) && (angle_axis[i] < 0.0))) {
angle_axis[i] = -angle_axis[i];
}
}
@@ -334,7 +347,8 @@ template <typename T>
inline void EulerAnglesToRotationMatrix(const T* euler,
const int row_stride,
T* R) {
- const T degrees_to_radians(M_PI / 180.0);
+ const double kPi = 3.14159265358979323846;
+ const T degrees_to_radians(kPi / 180.0);
const T pitch(euler[0] * degrees_to_radians);
const T roll(euler[1] * degrees_to_radians);
@@ -517,10 +531,4 @@ void AngleAxisRotatePoint(const T angle_axis[3], const T pt[3], T result[3]) {
} // namespace ceres
-// Clean define pollution.
-#ifdef CERES_NEED_M_PI_UNDEF
-#undef CERES_NEED_M_PI_UNDEF
-#undef M_PI
-#endif
-
#endif // CERES_PUBLIC_ROTATION_H_
diff --git a/extern/libmv/third_party/ceres/include/ceres/solver.h b/extern/libmv/third_party/ceres/include/ceres/solver.h
index bd669272023..31d5e8d7987 100644
--- a/extern/libmv/third_party/ceres/include/ceres/solver.h
+++ b/extern/libmv/third_party/ceres/include/ceres/solver.h
@@ -34,10 +34,10 @@
#include <cmath>
#include <string>
#include <vector>
-
-#include "ceres/iteration_callback.h"
+#include "ceres/crs_matrix.h"
#include "ceres/internal/macros.h"
#include "ceres/internal/port.h"
+#include "ceres/iteration_callback.h"
#include "ceres/types.h"
namespace ceres {
@@ -57,24 +57,47 @@ class Solver {
struct Options {
// Default constructor that sets up a generic sparse problem.
Options() {
- minimizer_type = LEVENBERG_MARQUARDT;
+ trust_region_strategy_type = LEVENBERG_MARQUARDT;
+ dogleg_type = TRADITIONAL_DOGLEG;
+ use_nonmonotonic_steps = false;
+ max_consecutive_nonmonotonic_steps = 5;
max_num_iterations = 50;
- max_solver_time_sec = 1.0e9;
+ max_solver_time_in_seconds = 1e9;
num_threads = 1;
- tau = 1e-4;
+ initial_trust_region_radius = 1e4;
+ max_trust_region_radius = 1e16;
+ min_trust_region_radius = 1e-32;
min_relative_decrease = 1e-3;
+ lm_min_diagonal = 1e-6;
+ lm_max_diagonal = 1e32;
+ max_num_consecutive_invalid_steps = 5;
function_tolerance = 1e-6;
gradient_tolerance = 1e-10;
parameter_tolerance = 1e-8;
-#ifndef CERES_NO_SUITESPARSE
- linear_solver_type = SPARSE_NORMAL_CHOLESKY;
-#else
+
+#if defined(CERES_NO_SUITESPARSE) && defined(CERES_NO_CXSPARSE)
linear_solver_type = DENSE_QR;
-#endif // CERES_NO_SUITESPARSE
+#else
+ linear_solver_type = SPARSE_NORMAL_CHOLESKY;
+#endif
+
preconditioner_type = JACOBI;
+
+ sparse_linear_algebra_library = SUITE_SPARSE;
+#if defined(CERES_NO_SUITESPARSE) && !defined(CERES_NO_CXSPARSE)
+ sparse_linear_algebra_library = CX_SPARSE;
+#endif
+
num_linear_solver_threads = 1;
num_eliminate_blocks = 0;
ordering_type = NATURAL;
+
+#if defined(CERES_NO_SUITESPARSE)
+ use_block_amd = false;
+#else
+ use_block_amd = true;
+#endif
+
linear_solver_min_num_iterations = 1;
linear_solver_max_num_iterations = 500;
eta = 1e-1;
@@ -82,10 +105,13 @@ class Solver {
logging_type = PER_MINIMIZER_ITERATION;
minimizer_progress_to_stdout = false;
return_initial_residuals = false;
+ return_initial_gradient = false;
+ return_initial_jacobian = false;
return_final_residuals = false;
+ return_final_gradient = false;
+ return_final_jacobian = false;
lsqp_dump_directory = "/tmp";
lsqp_dump_format_type = TEXTFILE;
- crash_and_dump_lsqp_on_failure = false;
check_gradients = false;
gradient_check_relative_precision = 1e-8;
numeric_derivative_relative_step_size = 1e-6;
@@ -94,27 +120,78 @@ class Solver {
// Minimizer options ----------------------------------------
- MinimizerType minimizer_type;
+ TrustRegionStrategyType trust_region_strategy_type;
+
+ // Type of dogleg strategy to use.
+ DoglegType dogleg_type;
+
+ // The classical trust region methods are descent methods, in that
+ // they only accept a point if it strictly reduces the value of
+ // the objective function.
+ //
+ // Relaxing this requirement allows the algorithm to be more
+ // efficient in the long term at the cost of some local increase
+ // in the value of the objective function.
+ //
+ // This is because allowing for non-decreasing objective function
+ // values in a princpled manner allows the algorithm to "jump over
+ // boulders" as the method is not restricted to move into narrow
+ // valleys while preserving its convergence properties.
+ //
+ // Setting use_nonmonotonic_steps to true enables the
+ // non-monotonic trust region algorithm as described by Conn,
+ // Gould & Toint in "Trust Region Methods", Section 10.1.
+ //
+ // The parameter max_consecutive_nonmonotonic_steps controls the
+ // window size used by the step selection algorithm to accept
+ // non-monotonic steps.
+ //
+ // Even though the value of the objective function may be larger
+ // than the minimum value encountered over the course of the
+ // optimization, the final parameters returned to the user are the
+ // ones corresponding to the minimum cost over all iterations.
+ bool use_nonmonotonic_steps;
+ int max_consecutive_nonmonotonic_steps;
// Maximum number of iterations for the minimizer to run for.
int max_num_iterations;
// Maximum time for which the minimizer should run for.
- double max_solver_time_sec;
+ double max_solver_time_in_seconds;
// Number of threads used by Ceres for evaluating the cost and
// jacobians.
int num_threads;
- // For Levenberg-Marquardt, the initial value for the
- // regularizer. This is the inversely related to the size of the
- // initial trust region.
- double tau;
+ // Trust region minimizer settings.
+ double initial_trust_region_radius;
+ double max_trust_region_radius;
+
+ // Minimizer terminates when the trust region radius becomes
+ // smaller than this value.
+ double min_trust_region_radius;
- // For trust region methods, this is lower threshold for the
- // relative decrease before a step is accepted.
+ // Lower bound for the relative decrease before a step is
+ // accepted.
double min_relative_decrease;
+ // For the Levenberg-Marquadt algorithm, the scaled diagonal of
+ // the normal equations J'J is used to control the size of the
+ // trust region. Extremely small and large values along the
+ // diagonal can make this regularization scheme
+ // fail. lm_max_diagonal and lm_min_diagonal, clamp the values of
+ // diag(J'J) from above and below. In the normal course of
+ // operation, the user should not have to modify these parameters.
+ double lm_min_diagonal;
+ double lm_max_diagonal;
+
+ // Sometimes due to numerical conditioning problems or linear
+ // solver flakiness, the trust region strategy may return a
+ // numerically invalid step that can be fixed by reducing the
+ // trust region size. So the TrustRegionMinimizer allows for a few
+ // successive invalid steps before it declares NUMERICAL_FAILURE.
+ int max_num_consecutive_invalid_steps;
+
// Minimizer terminates when
//
// (new_cost - old_cost) < function_tolerance * old_cost;
@@ -141,6 +218,12 @@ class Solver {
// Type of preconditioner to use with the iterative linear solvers.
PreconditionerType preconditioner_type;
+ // Ceres supports using multiple sparse linear algebra libraries
+ // for sparse matrix ordering and factorizations. Currently,
+ // SUITE_SPARSE and CX_SPARSE are the valid choices, depending on
+ // whether they are linked into Ceres at build time.
+ SparseLinearAlgebraLibraryType sparse_linear_algebra_library;
+
// Number of threads used by Ceres to solve the Newton
// step. Currently only the SPARSE_SCHUR solver is capable of
// using this setting.
@@ -170,6 +253,19 @@ class Solver {
// non-empty.
vector<double*> ordering;
+ // By virtue of the modeling layer in Ceres being block oriented,
+ // all the matrices used by Ceres are also block oriented. When
+ // doing sparse direct factorization of these matrices (for
+ // SPARSE_NORMAL_CHOLESKY, SPARSE_SCHUR and ITERATIVE in
+ // conjunction with CLUSTER_TRIDIAGONAL AND CLUSTER_JACOBI
+ // preconditioners), the fill-reducing ordering algorithms can
+ // either be run on the block or the scalar form of these matrices.
+ // Running it on the block form exposes more of the super-nodal
+ // structure of the matrix to the factorization routines. Setting
+ // this parameter to true runs the ordering algorithms in block
+ // form. Currently this option only makes sense with
+ // sparse_linear_algebra_library = SUITE_SPARSE.
+ bool use_block_amd;
// Minimum number of iterations for which the linear solver should
// run, even if the convergence criterion is satisfied.
@@ -206,7 +302,12 @@ class Solver {
bool minimizer_progress_to_stdout;
bool return_initial_residuals;
+ bool return_initial_gradient;
+ bool return_initial_jacobian;
+
bool return_final_residuals;
+ bool return_final_gradient;
+ bool return_final_jacobian;
// List of iterations at which the optimizer should dump the
// linear least squares problem to disk. Useful for testing and
@@ -217,15 +318,6 @@ class Solver {
string lsqp_dump_directory;
DumpFormatType lsqp_dump_format_type;
- // Dump the linear least squares problem to disk if the minimizer
- // fails due to NUMERICAL_FAILURE and crash the process. This flag
- // is useful for generating debugging information. The problem is
- // dumped in a file whose name is determined by
- // Solver::Options::lsqp_dump_format.
- //
- // Note: This requires a version of Ceres built with protocol buffers.
- bool crash_and_dump_lsqp_on_failure;
-
// Finite differences options ----------------------------------------------
// Check all jacobians computed by each residual block with finite
@@ -273,16 +365,25 @@ class Solver {
bool update_state_every_iteration;
// Callbacks that are executed at the end of each iteration of the
- // Minimizer. They are executed in the order that they are
- // specified in this vector. By default, parameter blocks are
- // updated only at the end of the optimization, i.e when the
- // Minimizer terminates. This behaviour is controlled by
+ // Minimizer. An iteration may terminate midway, either due to
+ // numerical failures or because one of the convergence tests has
+ // been satisfied. In this case none of the callbacks are
+ // executed.
+
+ // Callbacks are executed in the order that they are specified in
+ // this vector. By default, parameter blocks are updated only at
+ // the end of the optimization, i.e when the Minimizer
+ // terminates. This behaviour is controlled by
// update_state_every_variable. If the user wishes to have access
// to the update parameter blocks when his/her callbacks are
// executed, then set update_state_every_iteration to true.
//
// The solver does NOT take ownership of these pointers.
vector<IterationCallback*> callbacks;
+
+ // If non-empty, a summary of the execution of the solver is
+ // recorded to this file.
+ string solver_log;
};
struct Summary {
@@ -313,20 +414,74 @@ class Solver {
// blocks that they depend on were fixed.
double fixed_cost;
- // Residuals before and after the optimization. Each vector
- // contains problem.NumResiduals() elements. Residuals are in the
- // same order in which they were added to the problem object when
- // constructing this problem.
+ // Vectors of residuals before and after the optimization. The
+ // entries of these vectors are in the order in which
+ // ResidualBlocks were added to the Problem object.
+ //
+ // Whether the residual vectors are populated with values is
+ // controlled by Solver::Options::return_initial_residuals and
+ // Solver::Options::return_final_residuals respectively.
vector<double> initial_residuals;
vector<double> final_residuals;
+ // Gradient vectors, before and after the optimization. The rows
+ // are in the same order in which the ParameterBlocks were added
+ // to the Problem object.
+ //
+ // NOTE: Since AddResidualBlock adds ParameterBlocks to the
+ // Problem automatically if they do not already exist, if you wish
+ // to have explicit control over the ordering of the vectors, then
+ // use Problem::AddParameterBlock to explicitly add the
+ // ParameterBlocks in the order desired.
+ //
+ // Whether the vectors are populated with values is controlled by
+ // Solver::Options::return_initial_gradient and
+ // Solver::Options::return_final_gradient respectively.
+ vector<double> initial_gradient;
+ vector<double> final_gradient;
+
+ // Jacobian matrices before and after the optimization. The rows
+ // of these matrices are in the same order in which the
+ // ResidualBlocks were added to the Problem object. The columns
+ // are in the same order in which the ParameterBlocks were added
+ // to the Problem object.
+ //
+ // NOTE: Since AddResidualBlock adds ParameterBlocks to the
+ // Problem automatically if they do not already exist, if you wish
+ // to have explicit control over the column ordering of the
+ // matrix, then use Problem::AddParameterBlock to explicitly add
+ // the ParameterBlocks in the order desired.
+ //
+ // The Jacobian matrices are stored as compressed row sparse
+ // matrices. Please see ceres/crs_matrix.h for more details of the
+ // format.
+ //
+ // Whether the Jacboan matrices are populated with values is
+ // controlled by Solver::Options::return_initial_jacobian and
+ // Solver::Options::return_final_jacobian respectively.
+ CRSMatrix initial_jacobian;
+ CRSMatrix final_jacobian;
+
vector<IterationSummary> iterations;
int num_successful_steps;
int num_unsuccessful_steps;
+ // When the user calls Solve, before the actual optimization
+ // occurs, Ceres performs a number of preprocessing steps. These
+ // include error checks, memory allocations, and reorderings. This
+ // time is accounted for as preprocessing time.
double preprocessor_time_in_seconds;
+
+ // Time spent in the TrustRegionMinimizer.
double minimizer_time_in_seconds;
+
+ // After the Minimizer is finished, some time is spent in
+ // re-evaluating residuals etc. This time is accounted for in the
+ // postprocessor time.
+ double postprocessor_time_in_seconds;
+
+ // Some total of all time spent inside Ceres when Solve is called.
double total_time_in_seconds;
// Preprocessor summary.
@@ -354,6 +509,10 @@ class Solver {
PreconditionerType preconditioner_type;
OrderingType ordering_type;
+
+ TrustRegionStrategyType trust_region_strategy_type;
+ DoglegType dogleg_type;
+ SparseLinearAlgebraLibraryType sparse_linear_algebra_library;
};
// Once a least squares problem has been built, this function takes
diff --git a/extern/libmv/third_party/ceres/include/ceres/types.h b/extern/libmv/third_party/ceres/include/ceres/types.h
index a30c79029ac..3980885b53c 100644
--- a/extern/libmv/third_party/ceres/include/ceres/types.h
+++ b/extern/libmv/third_party/ceres/include/ceres/types.h
@@ -59,14 +59,18 @@ enum LinearSolverType {
// normal equations A'A x = A'b. They are direct solvers and do not
// assume any special problem structure.
- // Solve the normal equations using a sparse cholesky solver; based
- // on CHOLMOD.
- SPARSE_NORMAL_CHOLESKY,
+ // Solve the normal equations using a dense Cholesky solver; based
+ // on Eigen.
+ DENSE_NORMAL_CHOLESKY,
// Solve the normal equations using a dense QR solver; based on
// Eigen.
DENSE_QR,
+ // Solve the normal equations using a sparse cholesky solver; requires
+ // SuiteSparse or CXSparse.
+ SPARSE_NORMAL_CHOLESKY,
+
// Specialized solvers, specific to problems with a generalized
// bi-partitite structure.
@@ -110,6 +114,15 @@ enum PreconditionerType {
CLUSTER_TRIDIAGONAL
};
+enum SparseLinearAlgebraLibraryType {
+ // High performance sparse Cholesky factorization and approximate
+ // minimum degree ordering.
+ SUITE_SPARSE,
+
+ // A lightweight replacment for SuiteSparse.
+ CX_SPARSE
+};
+
enum LinearSolverTerminationType {
// Termination criterion was met. For factorization based solvers
// the tolerance is assumed to be zero. Any user provided values are
@@ -149,8 +162,47 @@ enum LoggingType {
PER_MINIMIZER_ITERATION
};
-enum MinimizerType {
- LEVENBERG_MARQUARDT
+// Ceres supports different strategies for computing the trust region
+// step.
+enum TrustRegionStrategyType {
+ // The default trust region strategy is to use the step computation
+ // used in the Levenberg-Marquardt algorithm. For more details see
+ // levenberg_marquardt_strategy.h
+ LEVENBERG_MARQUARDT,
+
+ // Powell's dogleg algorithm interpolates between the Cauchy point
+ // and the Gauss-Newton step. It is particularly useful if the
+ // LEVENBERG_MARQUARDT algorithm is making a large number of
+ // unsuccessful steps. For more details see dogleg_strategy.h.
+ //
+ // NOTES:
+ //
+ // 1. This strategy has not been experimented with or tested as
+ // extensively as LEVENBERG_MARQUARDT, and therefore it should be
+ // considered EXPERIMENTAL for now.
+ //
+ // 2. For now this strategy should only be used with exact
+ // factorization based linear solvers, i.e., SPARSE_SCHUR,
+ // DENSE_SCHUR, DENSE_QR and SPARSE_NORMAL_CHOLESKY.
+ DOGLEG
+};
+
+// Ceres supports two different dogleg strategies.
+// The "traditional" dogleg method by Powell and the
+// "subspace" method described in
+// R. H. Byrd, R. B. Schnabel, and G. A. Shultz,
+// "Approximate solution of the trust region problem by minimization
+// over two-dimensional subspaces", Mathematical Programming,
+// 40 (1988), pp. 247--263
+enum DoglegType {
+ // The traditional approach constructs a dogleg path
+ // consisting of two line segments and finds the furthest
+ // point on that path that is still inside the trust region.
+ TRADITIONAL_DOGLEG,
+
+ // The subspace approach finds the exact minimum of the model
+ // constrained to the subspace spanned by the dogleg path.
+ SUBSPACE_DOGLEG
};
enum SolverTerminationType {
@@ -246,11 +298,15 @@ enum DimensionType {
const char* LinearSolverTypeToString(LinearSolverType type);
const char* PreconditionerTypeToString(PreconditionerType type);
+const char* SparseLinearAlgebraLibraryTypeToString(
+ SparseLinearAlgebraLibraryType type);
const char* LinearSolverTerminationTypeToString(
LinearSolverTerminationType type);
const char* OrderingTypeToString(OrderingType type);
const char* SolverTerminationTypeToString(SolverTerminationType type);
-
+const char* SparseLinearAlgebraLibraryTypeToString(
+ SparseLinearAlgebraLibraryType type);
+const char* TrustRegionStrategyTypeToString( TrustRegionStrategyType type);
bool IsSchurType(LinearSolverType type);
} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt.h b/extern/libmv/third_party/ceres/internal/ceres/array_utils.cc
index d00bb9095be..673baa4f70f 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/array_utils.cc
@@ -1,5 +1,5 @@
// Ceres Solver - A fast non-linear least squares minimizer
-// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
+// Copyright 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// Redistribution and use in source and binary forms, with or without
@@ -27,39 +27,41 @@
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
-//
-// Implmentation of Levenberg Marquardt algorithm based on "Methods for
-// Nonlinear Least Squares" by K. Madsen, H.B. Nielsen and
-// O. Tingleff. Available to download from
-//
-// http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3215/pdf/imm3215.pdf
-//
-#ifndef CERES_INTERNAL_LEVENBERG_MARQUARDT_H_
-#define CERES_INTERNAL_LEVENBERG_MARQUARDT_H_
+#include "ceres/array_utils.h"
-#include "ceres/minimizer.h"
-#include "ceres/solver.h"
+#include <cmath>
+#include <cstddef>
+#include "ceres/fpclassify.h"
namespace ceres {
namespace internal {
-class Evaluator;
-class LinearSolver;
+// It is a near impossibility that user code generates this exact
+// value in normal operation, thus we will use it to fill arrays
+// before passing them to user code. If on return an element of the
+// array still contains this value, we will assume that the user code
+// did not write to that memory location.
+const double kImpossibleValue = 1e302;
-class LevenbergMarquardt : public Minimizer {
- public:
- virtual ~LevenbergMarquardt();
+bool IsArrayValid(const int size, const double* x) {
+ if (x != NULL) {
+ for (int i = 0; i < size; ++i) {
+ if (!IsFinite(x[i]) || (x[i] == kImpossibleValue)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
- virtual void Minimize(const Minimizer::Options& options,
- Evaluator* evaluator,
- LinearSolver* linear_solver,
- const double* initial_parameters,
- double* final_parameters,
- Solver::Summary* summary);
-};
+void InvalidateArray(const int size, double* x) {
+ if (x != NULL) {
+ for (int i = 0; i < size; ++i) {
+ x[i] = kImpossibleValue;
+ }
+ }
+}
} // namespace internal
} // namespace ceres
-
-#endif // CERES_INTERNAL_LEVENBERG_MARQUARDT_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/array_utils.h b/extern/libmv/third_party/ceres/internal/ceres/array_utils.h
new file mode 100644
index 00000000000..99cc8d8ebbf
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/array_utils.h
@@ -0,0 +1,65 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+//
+// Utility routines for validating arrays.
+//
+// These are useful for detecting two common class of errors.
+//
+// 1. Uninitialized memory - where the user for some reason did not
+// compute part of an array, but the code expects it.
+//
+// 2. Numerical failure while computing the cost/residual/jacobian,
+// e.g. NaN, infinities etc. This is particularly useful since the
+// automatic differentiation code does computations that are not
+// evident to the user and can silently generate hard to debug errors.
+
+#ifndef CERES_INTERNAL_ARRAY_UTILS_H_
+#define CERES_INTERNAL_ARRAY_UTILS_H_
+
+#include "ceres/internal/port.h"
+
+namespace ceres {
+namespace internal {
+
+// Fill the array x with an impossible value that the user code is
+// never expected to compute.
+void InvalidateArray(int size, double* x);
+
+// Check if all the entries of the array x are valid, i.e. all the
+// values in the array should be finite and none of them should be
+// equal to the "impossible" value used by InvalidateArray.
+bool IsArrayValid(int size, const double* x);
+
+extern const double kImpossibleValue;
+
+} // namespace internal
+} // namespace ceres
+
+#endif // CERES_INTERNAL_ARRAY_UTILS_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_evaluate_preparer.cc b/extern/libmv/third_party/ceres/internal/ceres/block_evaluate_preparer.cc
index 05e63eb560b..9edc4fa23bd 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_evaluate_preparer.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_evaluate_preparer.cc
@@ -40,16 +40,26 @@
namespace ceres {
namespace internal {
-void BlockEvaluatePreparer::Init(int** jacobian_layout) {
+void BlockEvaluatePreparer::Init(int const* const* jacobian_layout,
+ int max_derivatives_per_residual_block) {
jacobian_layout_ = jacobian_layout;
+ scratch_evaluate_preparer_.Init(max_derivatives_per_residual_block);
}
// Point the jacobian blocks directly into the block sparse matrix.
void BlockEvaluatePreparer::Prepare(const ResidualBlock* residual_block,
int residual_block_index,
SparseMatrix* jacobian,
- double** jacobians) const {
- CHECK(jacobian != NULL);
+ double** jacobians) {
+ // If the overall jacobian is not available, use the scratch space.
+ if (jacobian == NULL) {
+ scratch_evaluate_preparer_.Prepare(residual_block,
+ residual_block_index,
+ jacobian,
+ jacobians);
+ return;
+ }
+
double* jacobian_values =
down_cast<BlockSparseMatrix*>(jacobian)->mutable_values();
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_evaluate_preparer.h b/extern/libmv/third_party/ceres/internal/ceres/block_evaluate_preparer.h
index a7869311e6e..354acc031f4 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_evaluate_preparer.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_evaluate_preparer.h
@@ -36,6 +36,8 @@
#ifndef CERES_INTERNAL_BLOCK_EVALUATE_PREPARER_H_
#define CERES_INTERNAL_BLOCK_EVALUATE_PREPARER_H_
+#include "ceres/scratch_evaluate_preparer.h"
+
namespace ceres {
namespace internal {
@@ -47,18 +49,26 @@ class BlockEvaluatePreparer {
// Using Init() instead of a constructor allows for allocating this structure
// with new[]. This is because C++ doesn't allow passing arguments to objects
// constructed with new[] (as opposed to plain 'new').
- void Init(int** jacobian_layout);
+ void Init(int const* const* jacobian_layout,
+ int max_derivatives_per_residual_block);
// EvaluatePreparer interface
- // Point the jacobian blocks directly into the block sparse matrix.
+ // Point the jacobian blocks directly into the block sparse matrix, if
+ // jacobian is non-null. Otherwise, uses an internal per-thread buffer to
+ // store the jacobians temporarily.
void Prepare(const ResidualBlock* residual_block,
int residual_block_index,
SparseMatrix* jacobian,
- double** jacobians) const;
+ double** jacobians);
private:
int const* const* jacobian_layout_;
+
+ // For the case that the overall jacobian is not available, but the
+ // individual jacobians are requested, use a pass-through scratch evaluate
+ // preparer.
+ ScratchEvaluatePreparer scratch_evaluate_preparer_;
};
} // namespace internal
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_jacobi_preconditioner.cc b/extern/libmv/third_party/ceres/internal/ceres/block_jacobi_preconditioner.cc
index 1a5001f9c71..474c37f7ca4 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_jacobi_preconditioner.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_jacobi_preconditioner.cc
@@ -40,11 +40,10 @@
namespace ceres {
namespace internal {
-BlockJacobiPreconditioner::BlockJacobiPreconditioner(
- const LinearOperator& A)
- : block_structure_(
- *(down_cast<const BlockSparseMatrix*>(&A)->block_structure())),
- num_rows_(A.num_rows()) {
+BlockJacobiPreconditioner::BlockJacobiPreconditioner(const LinearOperator& A)
+ : num_rows_(A.num_rows()),
+ block_structure_(
+ *(down_cast<const BlockSparseMatrix*>(&A)->block_structure())) {
// Calculate the amount of storage needed.
int storage_needed = 0;
for (int c = 0; c < block_structure_.cols.size(); ++c) {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_jacobian_writer.cc b/extern/libmv/third_party/ceres/internal/ceres/block_jacobian_writer.cc
index 52a58bb43a6..f90c350cc80 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_jacobian_writer.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_jacobian_writer.cc
@@ -136,9 +136,12 @@ BlockJacobianWriter::BlockJacobianWriter(const Evaluator::Options& options,
// makes the final Write() a nop.
BlockEvaluatePreparer* BlockJacobianWriter::CreateEvaluatePreparers(
int num_threads) {
+ int max_derivatives_per_residual_block =
+ program_->MaxDerivativesPerResidualBlock();
+
BlockEvaluatePreparer* preparers = new BlockEvaluatePreparer[num_threads];
for (int i = 0; i < num_threads; i++) {
- preparers[i].Init(&jacobian_layout_[0]);
+ preparers[i].Init(&jacobian_layout_[0], max_derivatives_per_residual_block);
}
return preparers;
}
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_random_access_dense_matrix.cc b/extern/libmv/third_party/ceres/internal/ceres/block_random_access_dense_matrix.cc
index 2afaf5e2ea2..0f95e8932b8 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_random_access_dense_matrix.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_random_access_dense_matrix.cc
@@ -28,10 +28,10 @@
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
+#include "glog/logging.h"
#include "ceres/block_random_access_dense_matrix.h"
#include <vector>
-#include <glog/logging.h>
#include "ceres/internal/eigen.h"
#include "ceres/internal/scoped_ptr.h"
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_random_access_dense_matrix.h b/extern/libmv/third_party/ceres/internal/ceres/block_random_access_dense_matrix.h
index 3a0096209f7..9f27a4c30f3 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_random_access_dense_matrix.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_random_access_dense_matrix.h
@@ -89,7 +89,7 @@ class BlockRandomAccessDenseMatrix : public BlockRandomAccessMatrix {
vector<int> block_layout_;
scoped_array<double> values_;
- DISALLOW_COPY_AND_ASSIGN(BlockRandomAccessDenseMatrix);
+ CERES_DISALLOW_COPY_AND_ASSIGN(BlockRandomAccessDenseMatrix);
};
} // namespace internal
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_random_access_matrix.h b/extern/libmv/third_party/ceres/internal/ceres/block_random_access_matrix.h
index f398af3be87..b76cb78b160 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_random_access_matrix.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_random_access_matrix.h
@@ -77,7 +77,7 @@ namespace internal {
//
// if (cell != NULL) {
// MatrixRef m(cell->values, row_stride, col_stride);
-// MutexLock l(&cell->m);
+// CeresMutexLock l(&cell->m);
// m.block(row, col, row_block_size, col_block_size) = ...
// }
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_random_access_sparse_matrix.cc b/extern/libmv/third_party/ceres/internal/ceres/block_random_access_sparse_matrix.cc
index c496fcd13de..9ed62ce948b 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_random_access_sparse_matrix.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_random_access_sparse_matrix.cc
@@ -28,17 +28,17 @@
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
+#include "glog/logging.h"
#include "ceres/block_random_access_sparse_matrix.h"
#include <algorithm>
#include <set>
#include <utility>
#include <vector>
-#include <glog/logging.h>
-#include "ceres/mutex.h"
-#include "ceres/triplet_sparse_matrix.h"
#include "ceres/internal/port.h"
#include "ceres/internal/scoped_ptr.h"
+#include "ceres/mutex.h"
+#include "ceres/triplet_sparse_matrix.h"
#include "ceres/types.h"
namespace ceres {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_random_access_sparse_matrix.h b/extern/libmv/third_party/ceres/internal/ceres/block_random_access_sparse_matrix.h
index 12613c3daa0..48a00437cf6 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_random_access_sparse_matrix.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_random_access_sparse_matrix.h
@@ -38,6 +38,7 @@
#include "ceres/block_random_access_matrix.h"
#include "ceres/collections_port.h"
#include "ceres/triplet_sparse_matrix.h"
+#include "ceres/integral_types.h"
#include "ceres/internal/macros.h"
#include "ceres/internal/port.h"
#include "ceres/internal/scoped_ptr.h"
@@ -84,11 +85,11 @@ class BlockRandomAccessSparseMatrix : public BlockRandomAccessMatrix {
TripletSparseMatrix* mutable_matrix() { return tsm_.get(); }
private:
- long int IntPairToLong(int a, int b) {
+ int64 IntPairToLong(int a, int b) {
return a * kMaxRowBlocks + b;
}
- const int kMaxRowBlocks;
+ const int64 kMaxRowBlocks;
// row/column block sizes.
const vector<int> blocks_;
@@ -100,7 +101,8 @@ class BlockRandomAccessSparseMatrix : public BlockRandomAccessMatrix {
// The underlying matrix object which actually stores the cells.
scoped_ptr<TripletSparseMatrix> tsm_;
- DISALLOW_COPY_AND_ASSIGN(BlockRandomAccessSparseMatrix);
+ friend class BlockRandomAccessSparseMatrixTest;
+ CERES_DISALLOW_COPY_AND_ASSIGN(BlockRandomAccessSparseMatrix);
};
} // namespace internal
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_sparse_matrix.cc b/extern/libmv/third_party/ceres/internal/ceres/block_sparse_matrix.cc
index 7dd395e2975..dbe5ec93ef0 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_sparse_matrix.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_sparse_matrix.cc
@@ -33,11 +33,11 @@
#include <cstddef>
#include <algorithm>
#include <vector>
-#include <glog/logging.h>
#include "ceres/block_structure.h"
+#include "ceres/internal/eigen.h"
#include "ceres/matrix_proto.h"
#include "ceres/triplet_sparse_matrix.h"
-#include "ceres/internal/eigen.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -81,7 +81,7 @@ BlockSparseMatrix::BlockSparseMatrix(
CHECK_NOTNULL(values_.get());
}
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
BlockSparseMatrix::BlockSparseMatrix(const SparseMatrixProto& outer_proto) {
CHECK(outer_proto.has_block_matrix());
@@ -244,7 +244,7 @@ const CompressedRowBlockStructure* BlockSparseMatrix::block_structure()
return block_structure_.get();
}
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
void BlockSparseMatrix::ToProto(SparseMatrixProto* outer_proto) const {
outer_proto->Clear();
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_sparse_matrix.h b/extern/libmv/third_party/ceres/internal/ceres/block_sparse_matrix.h
index f71446e8f58..513d398c54d 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_sparse_matrix.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_sparse_matrix.h
@@ -74,7 +74,7 @@ class BlockSparseMatrixBase : public SparseMatrix {
virtual const double* RowBlockValues(int row_block_index) const = 0;
private:
- DISALLOW_COPY_AND_ASSIGN(BlockSparseMatrixBase);
+ CERES_DISALLOW_COPY_AND_ASSIGN(BlockSparseMatrixBase);
};
// This class implements the SparseMatrix interface for storing and
@@ -96,7 +96,7 @@ class BlockSparseMatrix : public BlockSparseMatrixBase {
explicit BlockSparseMatrix(CompressedRowBlockStructure* block_structure);
// Construct a block sparse matrix from a protocol buffer.
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
explicit BlockSparseMatrix(const SparseMatrixProto& proto);
#endif
@@ -110,7 +110,7 @@ class BlockSparseMatrix : public BlockSparseMatrixBase {
virtual void SquaredColumnNorm(double* x) const;
virtual void ScaleColumns(const double* scale);
virtual void ToDenseMatrix(Matrix* dense_matrix) const;
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
virtual void ToProto(SparseMatrixProto* proto) const;
#endif
virtual void ToTextFile(FILE* file) const;
@@ -135,7 +135,7 @@ class BlockSparseMatrix : public BlockSparseMatrixBase {
int num_nonzeros_;
scoped_array<double> values_;
scoped_ptr<CompressedRowBlockStructure> block_structure_;
- DISALLOW_COPY_AND_ASSIGN(BlockSparseMatrix);
+ CERES_DISALLOW_COPY_AND_ASSIGN(BlockSparseMatrix);
};
} // namespace internal
diff --git a/extern/libmv/third_party/ceres/internal/ceres/block_structure.cc b/extern/libmv/third_party/ceres/internal/ceres/block_structure.cc
index 5add4f3b94d..e61131192af 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/block_structure.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/block_structure.cc
@@ -38,7 +38,7 @@ bool CellLessThan(const Cell& lhs, const Cell& rhs) {
return (lhs.block_id < rhs.block_id);
}
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
void ProtoToBlockStructure(const BlockStructureProto &proto,
CompressedRowBlockStructure *block_structure) {
// Decode the column blocks.
diff --git a/extern/libmv/third_party/ceres/internal/ceres/canonical_views_clustering.cc b/extern/libmv/third_party/ceres/internal/ceres/canonical_views_clustering.cc
index 53190ada6fc..d0dc1e670c2 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/canonical_views_clustering.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/canonical_views_clustering.cc
@@ -31,11 +31,11 @@
#include "ceres/canonical_views_clustering.h"
-#include <glog/logging.h>
-#include "ceres/graph.h"
#include "ceres/collections_port.h"
-#include "ceres/map_util.h"
+#include "ceres/graph.h"
#include "ceres/internal/macros.h"
+#include "ceres/map_util.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -75,7 +75,7 @@ class CanonicalViewsClustering {
IntMap view_to_canonical_view_;
// Maps a view to its similarity to its current cluster center.
HashMap<int, double> view_to_canonical_view_similarity_;
- DISALLOW_COPY_AND_ASSIGN(CanonicalViewsClustering);
+ CERES_DISALLOW_COPY_AND_ASSIGN(CanonicalViewsClustering);
};
void ComputeCanonicalViewsClustering(
diff --git a/extern/libmv/third_party/ceres/internal/ceres/cgnr_solver.h b/extern/libmv/third_party/ceres/internal/ceres/cgnr_solver.h
index dd36f99006b..877b4c4ceea 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/cgnr_solver.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/cgnr_solver.h
@@ -57,7 +57,7 @@ class CgnrSolver : public LinearSolver {
private:
const LinearSolver::Options options_;
scoped_ptr<BlockJacobiPreconditioner> jacobi_preconditioner_;
- DISALLOW_COPY_AND_ASSIGN(CgnrSolver);
+ CERES_DISALLOW_COPY_AND_ASSIGN(CgnrSolver);
};
} // namespace internal
diff --git a/extern/libmv/third_party/ceres/internal/ceres/collections_port.h b/extern/libmv/third_party/ceres/internal/ceres/collections_port.h
index 9dff0efe245..c2fce9033cd 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/collections_port.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/collections_port.h
@@ -33,31 +33,49 @@
#ifndef CERES_INTERNAL_COLLECTIONS_PORT_H_
#define CERES_INTERNAL_COLLECTIONS_PORT_H_
-#ifdef CERES_HASH_BOOST
-#include <boost/tr1/unordered_map.hpp>
-#include <boost/tr1/unordered_set.hpp>
+#if defined(CERES_NO_TR1)
+# include <map>
+# include <set>
#else
-#if defined(_MSC_VER) && _MSC_VER <= 1700
-#include <unordered_map>
-#include <unordered_set>
-#else
-#include <tr1/unordered_map>
-#include <tr1/unordered_set>
-#endif
+# if defined(_MSC_VER) && _MSC_VER <= 1600
+# include <unordered_map>
+# include <unordered_set>
+# else
+# include <tr1/unordered_map>
+# include <tr1/unordered_set>
+# endif
#endif
-
#include <utility>
#include "ceres/integral_types.h"
#include "ceres/internal/port.h"
+// Some systems don't have access to TR1. In that case, substitute the hash
+// map/set with normal map/set. The price to pay is slightly slower speed for
+// some operations.
+#if defined(CERES_NO_TR1)
+
namespace ceres {
namespace internal {
template<typename K, typename V>
-struct HashMap : tr1::unordered_map<K, V> {};
+struct HashMap : map<K, V> {};
template<typename K>
-struct HashSet : tr1::unordered_set<K> {};
+struct HashSet : set<K> {};
+
+} // namespace internal
+} // namespace ceres
+
+#else
+
+namespace ceres {
+namespace internal {
+
+template<typename K, typename V>
+struct HashMap : std::tr1::unordered_map<K, V> {};
+
+template<typename K>
+struct HashSet : std::tr1::unordered_set<K> {};
#if defined(_WIN32) && !defined(__MINGW64__) && !defined(__MINGW32__)
#define GG_LONGLONG(x) x##I64
@@ -124,11 +142,7 @@ CERES_HASH_NAMESPACE_START
// Hasher for STL pairs. Requires hashers for both members to be defined.
template<typename T>
-#ifdef CERES_HASH_BOOST
-struct hash {
-#else
struct hash<pair<T, T> > {
-#endif
size_t operator()(const pair<T, T>& p) const {
size_t h1 = hash<T>()(p.first);
size_t h2 = hash<T>()(p.second);
@@ -148,4 +162,6 @@ struct hash<pair<T, T> > {
CERES_HASH_NAMESPACE_END
+#endif // CERES_NO_TR1
+
#endif // CERES_INTERNAL_COLLECTIONS_PORT_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/compressed_row_jacobian_writer.cc b/extern/libmv/third_party/ceres/internal/ceres/compressed_row_jacobian_writer.cc
index aa883b7d353..912c4845441 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/compressed_row_jacobian_writer.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/compressed_row_jacobian_writer.cc
@@ -130,8 +130,24 @@ SparseMatrix* CompressedRowJacobianWriter::CreateJacobian() const {
}
row_pos += num_residuals;
}
-
CHECK_EQ(num_jacobian_nonzeros, rows[total_num_residuals]);
+
+ // Populate the row and column block vectors for use by block
+ // oriented ordering algorithms. This is useful when
+ // Solver::Options::use_block_amd = true.
+ const vector<ParameterBlock*>& parameter_blocks = program_->parameter_blocks();
+ vector<int>& col_blocks = *(jacobian->mutable_col_blocks());
+ col_blocks.resize(parameter_blocks.size());
+ for (int i = 0; i < parameter_blocks.size(); ++i) {
+ col_blocks[i] = parameter_blocks[i]->LocalSize();
+ }
+
+ vector<int>& row_blocks = *(jacobian->mutable_row_blocks());
+ row_blocks.resize(residual_blocks.size());
+ for (int i = 0; i < residual_blocks.size(); ++i) {
+ row_blocks[i] = residual_blocks[i]->NumResiduals();
+ }
+
return jacobian;
}
diff --git a/extern/libmv/third_party/ceres/internal/ceres/compressed_row_sparse_matrix.cc b/extern/libmv/third_party/ceres/internal/ceres/compressed_row_sparse_matrix.cc
index 95edf5396af..1b61468aaae 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/compressed_row_sparse_matrix.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/compressed_row_sparse_matrix.cc
@@ -32,15 +32,22 @@
#include <algorithm>
#include <vector>
-#include "ceres/matrix_proto.h"
+#include "ceres/crs_matrix.h"
#include "ceres/internal/port.h"
+#include "ceres/matrix_proto.h"
namespace ceres {
namespace internal {
namespace {
// Helper functor used by the constructor for reordering the contents
-// of a TripletSparseMatrix.
+// of a TripletSparseMatrix. This comparator assumes thay there are no
+// duplicates in the pair of arrays rows and cols, i.e., there is no
+// indices i and j (not equal to each other) s.t.
+//
+// rows[i] == rows[j] && cols[i] == cols[j]
+//
+// If this is the case, this functor will not be a StrictWeakOrdering.
struct RowColLessThan {
RowColLessThan(const int* rows, const int* cols)
: rows(rows), cols(cols) {
@@ -128,7 +135,7 @@ CompressedRowSparseMatrix::CompressedRowSparseMatrix(
CHECK_EQ(num_nonzeros(), m.num_nonzeros());
}
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
CompressedRowSparseMatrix::CompressedRowSparseMatrix(
const SparseMatrixProto& outer_proto) {
CHECK(outer_proto.has_compressed_row_matrix());
@@ -241,7 +248,7 @@ void CompressedRowSparseMatrix::ToDenseMatrix(Matrix* dense_matrix) const {
}
}
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
void CompressedRowSparseMatrix::ToProto(SparseMatrixProto* outer_proto) const {
CHECK_NOTNULL(outer_proto);
@@ -330,5 +337,18 @@ void CompressedRowSparseMatrix::ToTextFile(FILE* file) const {
}
}
+void CompressedRowSparseMatrix::ToCRSMatrix(CRSMatrix* matrix) const {
+ matrix->num_rows = num_rows();
+ matrix->num_cols = num_cols();
+
+ matrix->rows.resize(matrix->num_rows + 1);
+ matrix->cols.resize(num_nonzeros());
+ matrix->values.resize(num_nonzeros());
+
+ copy(rows_.get(), rows_.get() + matrix->num_rows + 1, matrix->rows.begin());
+ copy(cols_.get(), cols_.get() + num_nonzeros(), matrix->cols.begin());
+ copy(values_.get(), values_.get() + num_nonzeros(), matrix->values.begin());
+}
+
} // namespace internal
} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/compressed_row_sparse_matrix.h b/extern/libmv/third_party/ceres/internal/ceres/compressed_row_sparse_matrix.h
index 9a39d28e111..6a9d82842e5 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/compressed_row_sparse_matrix.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/compressed_row_sparse_matrix.h
@@ -31,14 +31,19 @@
#ifndef CERES_INTERNAL_COMPRESSED_ROW_SPARSE_MATRIX_H_
#define CERES_INTERNAL_COMPRESSED_ROW_SPARSE_MATRIX_H_
+#include <vector>
#include <glog/logging.h>
#include "ceres/sparse_matrix.h"
#include "ceres/triplet_sparse_matrix.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/macros.h"
+#include "ceres/internal/port.h"
#include "ceres/types.h"
namespace ceres {
+
+class CRSMatrix;
+
namespace internal {
class SparseMatrixProto;
@@ -52,7 +57,7 @@ class CompressedRowSparseMatrix : public SparseMatrix {
//
// We assume that m does not have any repeated entries.
explicit CompressedRowSparseMatrix(const TripletSparseMatrix& m);
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
explicit CompressedRowSparseMatrix(const SparseMatrixProto& proto);
#endif
@@ -85,7 +90,7 @@ class CompressedRowSparseMatrix : public SparseMatrix {
virtual void ScaleColumns(const double* scale);
virtual void ToDenseMatrix(Matrix* dense_matrix) const;
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
virtual void ToProto(SparseMatrixProto* proto) const;
#endif
virtual void ToTextFile(FILE* file) const;
@@ -103,6 +108,8 @@ class CompressedRowSparseMatrix : public SparseMatrix {
// have the same number of columns as this matrix.
void AppendRows(const CompressedRowSparseMatrix& m);
+ void ToCRSMatrix(CRSMatrix* matrix) const;
+
// Low level access methods that expose the structure of the matrix.
const int* cols() const { return cols_.get(); }
int* mutable_cols() { return cols_.get(); }
@@ -110,6 +117,12 @@ class CompressedRowSparseMatrix : public SparseMatrix {
const int* rows() const { return rows_.get(); }
int* mutable_rows() { return rows_.get(); }
+ const vector<int>& row_blocks() const { return row_blocks_; }
+ vector<int>* mutable_row_blocks() { return &row_blocks_; }
+
+ const vector<int>& col_blocks() const { return col_blocks_; }
+ vector<int>* mutable_col_blocks() { return &col_blocks_; }
+
private:
scoped_array<int> cols_;
scoped_array<int> rows_;
@@ -117,10 +130,17 @@ class CompressedRowSparseMatrix : public SparseMatrix {
int num_rows_;
int num_cols_;
-
int max_num_nonzeros_;
- DISALLOW_COPY_AND_ASSIGN(CompressedRowSparseMatrix);
+ // If the matrix has an underlying block structure, then it can also
+ // carry with it row and column block sizes. This is auxilliary and
+ // optional information for use by algorithms operating on the
+ // matrix. The class itself does not make use of this information in
+ // any way.
+ vector<int> row_blocks_;
+ vector<int> col_blocks_;
+
+ CERES_DISALLOW_COPY_AND_ASSIGN(CompressedRowSparseMatrix);
};
} // namespace internal
diff --git a/extern/libmv/third_party/ceres/internal/ceres/conditioned_cost_function.cc b/extern/libmv/third_party/ceres/internal/ceres/conditioned_cost_function.cc
index ca80bfb9c9d..7322790f717 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/conditioned_cost_function.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/conditioned_cost_function.cc
@@ -34,10 +34,10 @@
#include <cstddef>
-#include <glog/logging.h>
-#include "ceres/stl_util.h"
#include "ceres/internal/eigen.h"
+#include "ceres/stl_util.h"
#include "ceres/types.h"
+#include "glog/logging.h"
namespace ceres {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/conjugate_gradients_solver.cc b/extern/libmv/third_party/ceres/internal/ceres/conjugate_gradients_solver.cc
index 75f9e043fa5..ae8e8774709 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/conjugate_gradients_solver.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/conjugate_gradients_solver.cc
@@ -41,18 +41,18 @@
#include <cmath>
#include <cstddef>
-#include <glog/logging.h>
-#include "ceres/linear_operator.h"
+#include "ceres/fpclassify.h"
#include "ceres/internal/eigen.h"
+#include "ceres/linear_operator.h"
#include "ceres/types.h"
-#include "ceres/jet.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
namespace {
bool IsZeroOrInfinity(double x) {
- return ((x == 0.0) || (isinf(x)));
+ return ((x == 0.0) || (IsInfinite(x)));
}
// Constant used in the MATLAB implementation ~ 2 * eps.
@@ -115,7 +115,7 @@ LinearSolver::Summary ConjugateGradientsSolver::Solve(
for (summary.num_iterations = 1;
summary.num_iterations < options_.max_num_iterations;
++summary.num_iterations) {
- VLOG(2) << "cg iteration " << summary.num_iterations;
+ VLOG(3) << "cg iteration " << summary.num_iterations;
// Apply preconditioner
if (per_solve_options.preconditioner != NULL) {
@@ -151,14 +151,14 @@ LinearSolver::Summary ConjugateGradientsSolver::Solve(
A->RightMultiply(p.data(), q.data());
double pq = p.dot(q);
- if ((pq <= 0) || isinf(pq)) {
+ if ((pq <= 0) || IsInfinite(pq)) {
LOG(ERROR) << "Numerical failure. pq = " << pq;
summary.termination_type = FAILURE;
break;
}
double alpha = rho / pq;
- if (isinf(alpha)) {
+ if (IsInfinite(alpha)) {
LOG(ERROR) << "Numerical failure. alpha " << alpha;
summary.termination_type = FAILURE;
break;
@@ -202,13 +202,13 @@ LinearSolver::Summary ConjugateGradientsSolver::Solve(
// 1. Stephen G. Nash & Ariela Sofer, Assessing A Search
// Direction Within A Truncated Newton Method, Operation
// Research Letters 9(1990) 219-221.
- //
+ //
// 2. Stephen G. Nash, A Survey of Truncated Newton Methods,
// Journal of Computational and Applied Mathematics,
// 124(1-2), 45-59, 2000.
//
double zeta = summary.num_iterations * (Q1 - Q0) / Q1;
- VLOG(2) << "Q termination: zeta " << zeta
+ VLOG(3) << "Q termination: zeta " << zeta
<< " " << per_solve_options.q_tolerance;
if (zeta < per_solve_options.q_tolerance) {
summary.termination_type = TOLERANCE;
@@ -218,7 +218,7 @@ LinearSolver::Summary ConjugateGradientsSolver::Solve(
// Residual based termination.
norm_r = r. norm();
- VLOG(2) << "R termination: norm_r " << norm_r
+ VLOG(3) << "R termination: norm_r " << norm_r
<< " " << tol_r;
if (norm_r <= tol_r) {
summary.termination_type = TOLERANCE;
diff --git a/extern/libmv/third_party/ceres/internal/ceres/conjugate_gradients_solver.h b/extern/libmv/third_party/ceres/internal/ceres/conjugate_gradients_solver.h
index 57f99e31db7..b8dfa56b526 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/conjugate_gradients_solver.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/conjugate_gradients_solver.h
@@ -65,7 +65,7 @@ class ConjugateGradientsSolver : public LinearSolver {
private:
const LinearSolver::Options options_;
- DISALLOW_COPY_AND_ASSIGN(ConjugateGradientsSolver);
+ CERES_DISALLOW_COPY_AND_ASSIGN(ConjugateGradientsSolver);
};
} // namespace internal
diff --git a/extern/libmv/third_party/ceres/internal/ceres/corrector.cc b/extern/libmv/third_party/ceres/internal/ceres/corrector.cc
index 4ca2c6f6c86..eff4dff8566 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/corrector.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/corrector.cc
@@ -32,8 +32,8 @@
#include <cstddef>
#include <cmath>
-#include <glog/logging.h>
#include "ceres/internal/eigen.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/cxsparse.cc b/extern/libmv/third_party/ceres/internal/ceres/cxsparse.cc
new file mode 100644
index 00000000000..ca36ce07614
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/cxsparse.cc
@@ -0,0 +1,130 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: strandmark@google.com (Petter Strandmark)
+
+#ifndef CERES_NO_CXSPARSE
+
+#include "ceres/cxsparse.h"
+
+#include "ceres/compressed_row_sparse_matrix.h"
+#include "ceres/triplet_sparse_matrix.h"
+#include "glog/logging.h"
+
+namespace ceres {
+namespace internal {
+
+CXSparse::CXSparse() : scratch_size_(0), scratch_(NULL) {
+}
+
+CXSparse::~CXSparse() {
+ if (scratch_size_ > 0) {
+ cs_free(scratch_);
+ }
+}
+
+bool CXSparse::SolveCholesky(cs_di* A,
+ cs_dis* symbolic_factorization,
+ double* b) {
+ // Make sure we have enough scratch space available.
+ if (scratch_size_ < A->n) {
+ if (scratch_size_ > 0) {
+ cs_free(scratch_);
+ }
+ scratch_ = reinterpret_cast<CS_ENTRY*>(cs_malloc(A->n, sizeof(CS_ENTRY)));
+ }
+
+ // Solve using Cholesky factorization
+ csn* numeric_factorization = cs_chol(A, symbolic_factorization);
+ if (numeric_factorization == NULL) {
+ LOG(WARNING) << "Cholesky factorization failed.";
+ return false;
+ }
+
+ // When the Cholesky factorization succeeded, these methods are guaranteed to
+ // succeeded as well. In the comments below, "x" refers to the scratch space.
+ //
+ // Set x = P * b.
+ cs_ipvec(symbolic_factorization->pinv, b, scratch_, A->n);
+
+ // Set x = L \ x.
+ cs_lsolve(numeric_factorization->L, scratch_);
+
+ // Set x = L' \ x.
+ cs_ltsolve(numeric_factorization->L, scratch_);
+
+ // Set b = P' * x.
+ cs_pvec(symbolic_factorization->pinv, scratch_, b, A->n);
+
+ // Free Cholesky factorization.
+ cs_nfree(numeric_factorization);
+ return true;
+}
+
+cs_dis* CXSparse::AnalyzeCholesky(cs_di* A) {
+ // order = 1 for Cholesky factorization.
+ return cs_schol(1, A);
+}
+
+cs_di CXSparse::CreateSparseMatrixTransposeView(CompressedRowSparseMatrix* A) {
+ cs_di At;
+ At.m = A->num_cols();
+ At.n = A->num_rows();
+ At.nz = -1;
+ At.nzmax = A->num_nonzeros();
+ At.p = A->mutable_rows();
+ At.i = A->mutable_cols();
+ At.x = A->mutable_values();
+ return At;
+}
+
+cs_di* CXSparse::CreateSparseMatrix(TripletSparseMatrix* tsm) {
+ cs_di_sparse tsm_wrapper;
+ tsm_wrapper.nzmax = tsm->num_nonzeros();;
+ tsm_wrapper.nz = tsm->num_nonzeros();;
+ tsm_wrapper.m = tsm->num_rows();
+ tsm_wrapper.n = tsm->num_cols();
+ tsm_wrapper.p = tsm->mutable_cols();
+ tsm_wrapper.i = tsm->mutable_rows();
+ tsm_wrapper.x = tsm->mutable_values();
+
+ return cs_compress(&tsm_wrapper);
+}
+
+void CXSparse::Free(cs_di* factor) {
+ cs_free(factor);
+}
+
+void CXSparse::Free(cs_dis* factor) {
+ cs_sfree(factor);
+}
+
+} // namespace internal
+} // namespace ceres
+
+#endif // CERES_NO_CXSPARSE
diff --git a/extern/libmv/third_party/ceres/internal/ceres/cxsparse.h b/extern/libmv/third_party/ceres/internal/ceres/cxsparse.h
new file mode 100644
index 00000000000..d3b64fcd1a5
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/cxsparse.h
@@ -0,0 +1,90 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: strandmark@google.com (Petter Strandmark)
+
+#ifndef CERES_INTERNAL_CXSPARSE_H_
+#define CERES_INTERNAL_CXSPARSE_H_
+
+#ifndef CERES_NO_CXSPARSE
+
+#include "cs.h"
+
+namespace ceres {
+namespace internal {
+
+class CompressedRowSparseMatrix;
+class TripletSparseMatrix;
+
+// This object provides access to solving linear systems using Cholesky
+// factorization with a known symbolic factorization. This features does not
+// explicity exist in CXSparse. The methods in the class are nonstatic because
+// the class manages internal scratch space.
+class CXSparse {
+ public:
+ CXSparse();
+ ~CXSparse();
+
+ // Solves a symmetric linear system A * x = b using Cholesky factorization.
+ // A - The system matrix.
+ // symbolic_factorization - The symbolic factorization of A. This is obtained
+ // from AnalyzeCholesky.
+ // b - The right hand size of the linear equation. This
+ // array will also recieve the solution.
+ // Returns false if Cholesky factorization of A fails.
+ bool SolveCholesky(cs_di* A, cs_dis* symbolic_factorization, double* b);
+
+ // Creates a sparse matrix from a compressed-column form. No memory is
+ // allocated or copied; the structure A is filled out with info from the
+ // argument.
+ cs_di CreateSparseMatrixTransposeView(CompressedRowSparseMatrix* A);
+
+ // Creates a new matrix from a triplet form. Deallocate the returned matrix
+ // with Free. May return NULL if the compression or allocation fails.
+ cs_di* CreateSparseMatrix(TripletSparseMatrix* A);
+
+ // Computes a symbolic factorization of A that can be used in SolveCholesky.
+ // The returned matrix should be deallocated with Free when not used anymore.
+ cs_dis* AnalyzeCholesky(cs_di* A);
+
+ // Deallocates the memory of a matrix obtained from AnalyzeCholesky.
+ void Free(cs_di* factor);
+ void Free(cs_dis* factor);
+
+ private:
+ // Cached scratch space
+ CS_ENTRY* scratch_;
+ int scratch_size_;
+};
+
+} // namespace internal
+} // namespace ceres
+
+#endif // CERES_NO_CXSPARSE
+
+#endif // CERES_INTERNAL_CXSPARSE_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/dense_normal_cholesky_solver.cc b/extern/libmv/third_party/ceres/internal/ceres/dense_normal_cholesky_solver.cc
new file mode 100644
index 00000000000..f6bb99abf63
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/dense_normal_cholesky_solver.cc
@@ -0,0 +1,86 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+
+#include "ceres/dense_normal_cholesky_solver.h"
+
+#include <cstddef>
+
+#include "Eigen/Dense"
+#include "ceres/dense_sparse_matrix.h"
+#include "ceres/linear_solver.h"
+#include "ceres/internal/eigen.h"
+#include "ceres/internal/scoped_ptr.h"
+#include "ceres/types.h"
+
+namespace ceres {
+namespace internal {
+
+DenseNormalCholeskySolver::DenseNormalCholeskySolver(
+ const LinearSolver::Options& options)
+ : options_(options) {}
+
+LinearSolver::Summary DenseNormalCholeskySolver::SolveImpl(
+ DenseSparseMatrix* A,
+ const double* b,
+ const LinearSolver::PerSolveOptions& per_solve_options,
+ double* x) {
+ const int num_rows = A->num_rows();
+ const int num_cols = A->num_cols();
+
+ ConstAlignedMatrixRef Aref = A->matrix();
+ Matrix lhs(num_cols, num_cols);
+ lhs.setZero();
+
+ // lhs += A'A
+ //
+ // Using rankUpdate instead of GEMM, exposes the fact that its the
+ // same matrix being multiplied with itself and that the product is
+ // symmetric.
+ lhs.selfadjointView<Eigen::Upper>().rankUpdate(Aref.transpose());
+
+ // rhs = A'b
+ Vector rhs = Aref.transpose() * ConstVectorRef(b, num_rows);
+
+ if (per_solve_options.D != NULL) {
+ ConstVectorRef D(per_solve_options.D, num_cols);
+ lhs += D.array().square().matrix().asDiagonal();
+ }
+
+ VectorRef(x, num_cols) =
+ lhs.selfadjointView<Eigen::Upper>().ldlt().solve(rhs);
+
+ LinearSolver::Summary summary;
+ summary.num_iterations = 1;
+ summary.termination_type = TOLERANCE;
+ return summary;
+}
+
+} // namespace internal
+} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/dense_normal_cholesky_solver.h b/extern/libmv/third_party/ceres/internal/ceres/dense_normal_cholesky_solver.h
new file mode 100644
index 00000000000..de47740583d
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/dense_normal_cholesky_solver.h
@@ -0,0 +1,95 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+//
+// Solve dense rectangular systems Ax = b by forming the normal
+// equations and solving them using the Cholesky factorization.
+
+#ifndef CERES_INTERNAL_DENSE_NORMAL_CHOLESKY_SOLVER_H_
+#define CERES_INTERNAL_DENSE_NORMAL_CHOLESKY_SOLVER_H_
+
+#include "ceres/linear_solver.h"
+#include "ceres/internal/macros.h"
+
+namespace ceres {
+namespace internal {
+
+class DenseSparseMatrix;
+
+// This class implements the LinearSolver interface for solving
+// rectangular/unsymmetric (well constrained) linear systems of the
+// form
+//
+// Ax = b
+//
+// Since there does not usually exist a solution that satisfies these
+// equations, the solver instead solves the linear least squares
+// problem
+//
+// min_x |Ax - b|^2
+//
+// Setting the gradient of the above optimization problem to zero
+// gives us the normal equations
+//
+// A'Ax = A'b
+//
+// A'A is a positive definite matrix (hopefully), and the resulting
+// linear system can be solved using Cholesky factorization.
+//
+// If the PerSolveOptions struct has a non-null array D, then the
+// augmented/regularized linear system
+//
+// [ A ]x = [b]
+// [ diag(D) ] [0]
+//
+// is solved.
+//
+// This class uses the LDLT factorization routines from the Eigen
+// library. This solver always returns a solution, it is the user's
+// responsibility to judge if the solution is good enough for their
+// purposes.
+class DenseNormalCholeskySolver: public DenseSparseMatrixSolver {
+ public:
+ explicit DenseNormalCholeskySolver(const LinearSolver::Options& options);
+
+ private:
+ virtual LinearSolver::Summary SolveImpl(
+ DenseSparseMatrix* A,
+ const double* b,
+ const LinearSolver::PerSolveOptions& per_solve_options,
+ double* x);
+
+ const LinearSolver::Options options_;
+ CERES_DISALLOW_COPY_AND_ASSIGN(DenseNormalCholeskySolver);
+};
+
+} // namespace internal
+} // namespace ceres
+
+#endif // CERES_INTERNAL_DENSE_NORMAL_CHOLESKY_SOLVER_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/dense_qr_solver.cc b/extern/libmv/third_party/ceres/internal/ceres/dense_qr_solver.cc
index 328505404d7..2b329ee0e9c 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/dense_qr_solver.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/dense_qr_solver.cc
@@ -33,8 +33,8 @@
#include <cstddef>
#include "Eigen/Dense"
+#include "ceres/dense_sparse_matrix.h"
#include "ceres/linear_solver.h"
-#include "ceres/triplet_sparse_matrix.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/scoped_ptr.h"
#include "ceres/types.h"
@@ -62,7 +62,7 @@ LinearSolver::Summary DenseQRSolver::SolveImpl(
}
// rhs = [b;0] to account for the additional rows in the lhs.
- Vector rhs(num_rows + ((per_solve_options.D !=NULL) ? num_cols : 0));
+ Vector rhs(num_rows + ((per_solve_options.D != NULL) ? num_cols : 0));
rhs.setZero();
rhs.head(num_rows) = ConstVectorRef(b, num_rows);
diff --git a/extern/libmv/third_party/ceres/internal/ceres/dense_qr_solver.h b/extern/libmv/third_party/ceres/internal/ceres/dense_qr_solver.h
index 990c8d445eb..dd683a8c4ea 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/dense_qr_solver.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/dense_qr_solver.h
@@ -28,7 +28,7 @@
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
//
-// Solve dense rectangular systems Ax = b using the QR factoriztion.
+// Solve dense rectangular systems Ax = b using the QR factorization.
#ifndef CERES_INTERNAL_DENSE_QR_SOLVER_H_
#define CERES_INTERNAL_DENSE_QR_SOLVER_H_
@@ -90,7 +90,7 @@ class DenseQRSolver: public DenseSparseMatrixSolver {
double* x);
const LinearSolver::Options options_;
- DISALLOW_COPY_AND_ASSIGN(DenseQRSolver);
+ CERES_DISALLOW_COPY_AND_ASSIGN(DenseQRSolver);
};
} // namespace internal
diff --git a/extern/libmv/third_party/ceres/internal/ceres/dense_sparse_matrix.cc b/extern/libmv/third_party/ceres/internal/ceres/dense_sparse_matrix.cc
index 5d392ba6c3b..86730cc101b 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/dense_sparse_matrix.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/dense_sparse_matrix.cc
@@ -67,7 +67,7 @@ DenseSparseMatrix::DenseSparseMatrix(const Matrix& m)
has_diagonal_reserved_(false) {
}
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
DenseSparseMatrix::DenseSparseMatrix(const SparseMatrixProto& outer_proto)
: m_(Eigen::MatrixXd::Zero(
outer_proto.dense_matrix().num_rows(),
@@ -108,7 +108,7 @@ void DenseSparseMatrix::ToDenseMatrix(Matrix* dense_matrix) const {
*dense_matrix = m_;
}
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
void DenseSparseMatrix::ToProto(SparseMatrixProto* outer_proto) const {
CHECK(!has_diagonal_appended_) << "Not supported.";
outer_proto->Clear();
@@ -183,7 +183,7 @@ void DenseSparseMatrix::ToTextFile(FILE* file) const {
CHECK_NOTNULL(file);
const int active_rows =
(has_diagonal_reserved_ && !has_diagonal_appended_)
- ? (m_.rows() - m_.cols())
+ ? (m_.rows() - m_.cols())
: m_.rows();
for (int r = 0; r < active_rows; ++r) {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/dense_sparse_matrix.h b/extern/libmv/third_party/ceres/internal/ceres/dense_sparse_matrix.h
index 416c2143c2c..e7ad14d0ee6 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/dense_sparse_matrix.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/dense_sparse_matrix.h
@@ -52,7 +52,7 @@ class DenseSparseMatrix : public SparseMatrix {
// m. This assumes that m does not have any repeated entries.
explicit DenseSparseMatrix(const TripletSparseMatrix& m);
explicit DenseSparseMatrix(const Matrix& m);
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
explicit DenseSparseMatrix(const SparseMatrixProto& proto);
#endif
@@ -67,7 +67,7 @@ class DenseSparseMatrix : public SparseMatrix {
virtual void SquaredColumnNorm(double* x) const;
virtual void ScaleColumns(const double* scale);
virtual void ToDenseMatrix(Matrix* dense_matrix) const;
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
virtual void ToProto(SparseMatrixProto* proto) const;
#endif
virtual void ToTextFile(FILE* file) const;
diff --git a/extern/libmv/third_party/ceres/internal/ceres/detect_structure.cc b/extern/libmv/third_party/ceres/internal/ceres/detect_structure.cc
index e9755043bab..ea5bf2e9690 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/detect_structure.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/detect_structure.cc
@@ -28,9 +28,9 @@
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
-#include <glog/logging.h>
#include "ceres/detect_structure.h"
#include "ceres/internal/eigen.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -60,10 +60,10 @@ void DetectStructure(const CompressedRowBlockStructure& bs,
*row_block_size = row.block.size;
} else if (*row_block_size != Eigen::Dynamic &&
*row_block_size != row.block.size) {
- *row_block_size = Eigen::Dynamic;
VLOG(2) << "Dynamic row block size because the block size changed from "
<< *row_block_size << " to "
<< row.block.size;
+ *row_block_size = Eigen::Dynamic;
}
@@ -71,10 +71,10 @@ void DetectStructure(const CompressedRowBlockStructure& bs,
*e_block_size = bs.cols[e_block_id].size;
} else if (*e_block_size != Eigen::Dynamic &&
*e_block_size != bs.cols[e_block_id].size) {
- *e_block_size = Eigen::Dynamic;
VLOG(2) << "Dynamic e block size because the block size changed from "
<< *e_block_size << " to "
<< bs.cols[e_block_id].size;
+ *e_block_size = Eigen::Dynamic;
}
if (*f_block_size == 0) {
@@ -85,11 +85,11 @@ void DetectStructure(const CompressedRowBlockStructure& bs,
} else if (*f_block_size != Eigen::Dynamic) {
for (int c = 1; c < row.cells.size(); ++c) {
if (*f_block_size != bs.cols[row.cells[c].block_id].size) {
- *f_block_size = Eigen::Dynamic;
VLOG(2) << "Dynamic f block size because the block size "
- << "changed from " << *f_block_size << " to "
- << bs.cols[row.cells[c].block_id].size;
- break;
+ << "changed from " << *f_block_size << " to "
+ << bs.cols[row.cells[c].block_id].size;
+ *f_block_size = Eigen::Dynamic;
+ break;
}
}
}
diff --git a/extern/libmv/third_party/ceres/internal/ceres/detect_structure.h b/extern/libmv/third_party/ceres/internal/ceres/detect_structure.h
index 8af4f236690..5f8e1b4ff46 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/detect_structure.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/detect_structure.h
@@ -49,7 +49,7 @@ namespace internal {
// is known as compile time.
//
// For more details about e_blocks and f_blocks, see
-// schur_complement.h. This information is used to initialized an
+// schur_eliminator.h. This information is used to initialized an
// appropriate template specialization of SchurEliminator.
void DetectStructure(const CompressedRowBlockStructure& bs,
const int num_eliminate_blocks,
diff --git a/extern/libmv/third_party/ceres/internal/ceres/dogleg_strategy.cc b/extern/libmv/third_party/ceres/internal/ceres/dogleg_strategy.cc
new file mode 100644
index 00000000000..668fa54b8b8
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/dogleg_strategy.cc
@@ -0,0 +1,691 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+
+#include "ceres/dogleg_strategy.h"
+
+#include <cmath>
+#include "Eigen/Dense"
+#include "ceres/array_utils.h"
+#include "ceres/internal/eigen.h"
+#include "ceres/linear_solver.h"
+#include "ceres/polynomial_solver.h"
+#include "ceres/sparse_matrix.h"
+#include "ceres/trust_region_strategy.h"
+#include "ceres/types.h"
+#include "glog/logging.h"
+
+namespace ceres {
+namespace internal {
+namespace {
+const double kMaxMu = 1.0;
+const double kMinMu = 1e-8;
+}
+
+DoglegStrategy::DoglegStrategy(const TrustRegionStrategy::Options& options)
+ : linear_solver_(options.linear_solver),
+ radius_(options.initial_radius),
+ max_radius_(options.max_radius),
+ min_diagonal_(options.lm_min_diagonal),
+ max_diagonal_(options.lm_max_diagonal),
+ mu_(kMinMu),
+ min_mu_(kMinMu),
+ max_mu_(kMaxMu),
+ mu_increase_factor_(10.0),
+ increase_threshold_(0.75),
+ decrease_threshold_(0.25),
+ dogleg_step_norm_(0.0),
+ reuse_(false),
+ dogleg_type_(options.dogleg_type) {
+ CHECK_NOTNULL(linear_solver_);
+ CHECK_GT(min_diagonal_, 0.0);
+ CHECK_LE(min_diagonal_, max_diagonal_);
+ CHECK_GT(max_radius_, 0.0);
+}
+
+// If the reuse_ flag is not set, then the Cauchy point (scaled
+// gradient) and the new Gauss-Newton step are computed from
+// scratch. The Dogleg step is then computed as interpolation of these
+// two vectors.
+TrustRegionStrategy::Summary DoglegStrategy::ComputeStep(
+ const TrustRegionStrategy::PerSolveOptions& per_solve_options,
+ SparseMatrix* jacobian,
+ const double* residuals,
+ double* step) {
+ CHECK_NOTNULL(jacobian);
+ CHECK_NOTNULL(residuals);
+ CHECK_NOTNULL(step);
+
+ const int n = jacobian->num_cols();
+ if (reuse_) {
+ // Gauss-Newton and gradient vectors are always available, only a
+ // new interpolant need to be computed. For the subspace case,
+ // the subspace and the two-dimensional model are also still valid.
+ switch(dogleg_type_) {
+ case TRADITIONAL_DOGLEG:
+ ComputeTraditionalDoglegStep(step);
+ break;
+
+ case SUBSPACE_DOGLEG:
+ ComputeSubspaceDoglegStep(step);
+ break;
+ }
+ TrustRegionStrategy::Summary summary;
+ summary.num_iterations = 0;
+ summary.termination_type = TOLERANCE;
+ return summary;
+ }
+
+ reuse_ = true;
+ // Check that we have the storage needed to hold the various
+ // temporary vectors.
+ if (diagonal_.rows() != n) {
+ diagonal_.resize(n, 1);
+ gradient_.resize(n, 1);
+ gauss_newton_step_.resize(n, 1);
+ }
+
+ // Vector used to form the diagonal matrix that is used to
+ // regularize the Gauss-Newton solve and that defines the
+ // elliptical trust region
+ //
+ // || D * step || <= radius_ .
+ //
+ jacobian->SquaredColumnNorm(diagonal_.data());
+ for (int i = 0; i < n; ++i) {
+ diagonal_[i] = min(max(diagonal_[i], min_diagonal_), max_diagonal_);
+ }
+ diagonal_ = diagonal_.array().sqrt();
+
+ ComputeGradient(jacobian, residuals);
+ ComputeCauchyPoint(jacobian);
+
+ LinearSolver::Summary linear_solver_summary =
+ ComputeGaussNewtonStep(jacobian, residuals);
+
+ TrustRegionStrategy::Summary summary;
+ summary.residual_norm = linear_solver_summary.residual_norm;
+ summary.num_iterations = linear_solver_summary.num_iterations;
+ summary.termination_type = linear_solver_summary.termination_type;
+
+ if (linear_solver_summary.termination_type != FAILURE) {
+ switch(dogleg_type_) {
+ // Interpolate the Cauchy point and the Gauss-Newton step.
+ case TRADITIONAL_DOGLEG:
+ ComputeTraditionalDoglegStep(step);
+ break;
+
+ // Find the minimum in the subspace defined by the
+ // Cauchy point and the (Gauss-)Newton step.
+ case SUBSPACE_DOGLEG:
+ if (!ComputeSubspaceModel(jacobian)) {
+ summary.termination_type = FAILURE;
+ break;
+ }
+ ComputeSubspaceDoglegStep(step);
+ break;
+ }
+ }
+
+ return summary;
+}
+
+// The trust region is assumed to be elliptical with the
+// diagonal scaling matrix D defined by sqrt(diagonal_).
+// It is implemented by substituting step' = D * step.
+// The trust region for step' is spherical.
+// The gradient, the Gauss-Newton step, the Cauchy point,
+// and all calculations involving the Jacobian have to
+// be adjusted accordingly.
+void DoglegStrategy::ComputeGradient(
+ SparseMatrix* jacobian,
+ const double* residuals) {
+ gradient_.setZero();
+ jacobian->LeftMultiply(residuals, gradient_.data());
+ gradient_.array() /= diagonal_.array();
+}
+
+// The Cauchy point is the global minimizer of the quadratic model
+// along the one-dimensional subspace spanned by the gradient.
+void DoglegStrategy::ComputeCauchyPoint(SparseMatrix* jacobian) {
+ // alpha * -gradient is the Cauchy point.
+ Vector Jg(jacobian->num_rows());
+ Jg.setZero();
+ // The Jacobian is scaled implicitly by computing J * (D^-1 * (D^-1 * g))
+ // instead of (J * D^-1) * (D^-1 * g).
+ Vector scaled_gradient =
+ (gradient_.array() / diagonal_.array()).matrix();
+ jacobian->RightMultiply(scaled_gradient.data(), Jg.data());
+ alpha_ = gradient_.squaredNorm() / Jg.squaredNorm();
+}
+
+// The dogleg step is defined as the intersection of the trust region
+// boundary with the piecewise linear path from the origin to the Cauchy
+// point and then from there to the Gauss-Newton point (global minimizer
+// of the model function). The Gauss-Newton point is taken if it lies
+// within the trust region.
+void DoglegStrategy::ComputeTraditionalDoglegStep(double* dogleg) {
+ VectorRef dogleg_step(dogleg, gradient_.rows());
+
+ // Case 1. The Gauss-Newton step lies inside the trust region, and
+ // is therefore the optimal solution to the trust-region problem.
+ const double gradient_norm = gradient_.norm();
+ const double gauss_newton_norm = gauss_newton_step_.norm();
+ if (gauss_newton_norm <= radius_) {
+ dogleg_step = gauss_newton_step_;
+ dogleg_step_norm_ = gauss_newton_norm;
+ dogleg_step.array() /= diagonal_.array();
+ VLOG(3) << "GaussNewton step size: " << dogleg_step_norm_
+ << " radius: " << radius_;
+ return;
+ }
+
+ // Case 2. The Cauchy point and the Gauss-Newton steps lie outside
+ // the trust region. Rescale the Cauchy point to the trust region
+ // and return.
+ if (gradient_norm * alpha_ >= radius_) {
+ dogleg_step = -(radius_ / gradient_norm) * gradient_;
+ dogleg_step_norm_ = radius_;
+ dogleg_step.array() /= diagonal_.array();
+ VLOG(3) << "Cauchy step size: " << dogleg_step_norm_
+ << " radius: " << radius_;
+ return;
+ }
+
+ // Case 3. The Cauchy point is inside the trust region and the
+ // Gauss-Newton step is outside. Compute the line joining the two
+ // points and the point on it which intersects the trust region
+ // boundary.
+
+ // a = alpha * -gradient
+ // b = gauss_newton_step
+ const double b_dot_a = -alpha_ * gradient_.dot(gauss_newton_step_);
+ const double a_squared_norm = pow(alpha_ * gradient_norm, 2.0);
+ const double b_minus_a_squared_norm =
+ a_squared_norm - 2 * b_dot_a + pow(gauss_newton_norm, 2);
+
+ // c = a' (b - a)
+ // = alpha * -gradient' gauss_newton_step - alpha^2 |gradient|^2
+ const double c = b_dot_a - a_squared_norm;
+ const double d = sqrt(c * c + b_minus_a_squared_norm *
+ (pow(radius_, 2.0) - a_squared_norm));
+
+ double beta =
+ (c <= 0)
+ ? (d - c) / b_minus_a_squared_norm
+ : (radius_ * radius_ - a_squared_norm) / (d + c);
+ dogleg_step = (-alpha_ * (1.0 - beta)) * gradient_
+ + beta * gauss_newton_step_;
+ dogleg_step_norm_ = dogleg_step.norm();
+ dogleg_step.array() /= diagonal_.array();
+ VLOG(3) << "Dogleg step size: " << dogleg_step_norm_
+ << " radius: " << radius_;
+}
+
+// The subspace method finds the minimum of the two-dimensional problem
+//
+// min. 1/2 x' B' H B x + g' B x
+// s.t. || B x ||^2 <= r^2
+//
+// where r is the trust region radius and B is the matrix with unit columns
+// spanning the subspace defined by the steepest descent and Newton direction.
+// This subspace by definition includes the Gauss-Newton point, which is
+// therefore taken if it lies within the trust region.
+void DoglegStrategy::ComputeSubspaceDoglegStep(double* dogleg) {
+ VectorRef dogleg_step(dogleg, gradient_.rows());
+
+ // The Gauss-Newton point is inside the trust region if |GN| <= radius_.
+ // This test is valid even though radius_ is a length in the two-dimensional
+ // subspace while gauss_newton_step_ is expressed in the (scaled)
+ // higher dimensional original space. This is because
+ //
+ // 1. gauss_newton_step_ by definition lies in the subspace, and
+ // 2. the subspace basis is orthonormal.
+ //
+ // As a consequence, the norm of the gauss_newton_step_ in the subspace is
+ // the same as its norm in the original space.
+ const double gauss_newton_norm = gauss_newton_step_.norm();
+ if (gauss_newton_norm <= radius_) {
+ dogleg_step = gauss_newton_step_;
+ dogleg_step_norm_ = gauss_newton_norm;
+ dogleg_step.array() /= diagonal_.array();
+ VLOG(3) << "GaussNewton step size: " << dogleg_step_norm_
+ << " radius: " << radius_;
+ return;
+ }
+
+ // The optimum lies on the boundary of the trust region. The above problem
+ // therefore becomes
+ //
+ // min. 1/2 x^T B^T H B x + g^T B x
+ // s.t. || B x ||^2 = r^2
+ //
+ // Notice the equality in the constraint.
+ //
+ // This can be solved by forming the Lagrangian, solving for x(y), where
+ // y is the Lagrange multiplier, using the gradient of the objective, and
+ // putting x(y) back into the constraint. This results in a fourth order
+ // polynomial in y, which can be solved using e.g. the companion matrix.
+ // See the description of MakePolynomialForBoundaryConstrainedProblem for
+ // details. The result is up to four real roots y*, not all of which
+ // correspond to feasible points. The feasible points x(y*) have to be
+ // tested for optimality.
+
+ if (subspace_is_one_dimensional_) {
+ // The subspace is one-dimensional, so both the gradient and
+ // the Gauss-Newton step point towards the same direction.
+ // In this case, we move along the gradient until we reach the trust
+ // region boundary.
+ dogleg_step = -(radius_ / gradient_.norm()) * gradient_;
+ dogleg_step_norm_ = radius_;
+ dogleg_step.array() /= diagonal_.array();
+ VLOG(3) << "Dogleg subspace step size (1D): " << dogleg_step_norm_
+ << " radius: " << radius_;
+ return;
+ }
+
+ Vector2d minimum(0.0, 0.0);
+ if (!FindMinimumOnTrustRegionBoundary(&minimum)) {
+ // For the positive semi-definite case, a traditional dogleg step
+ // is taken in this case.
+ LOG(WARNING) << "Failed to compute polynomial roots. "
+ << "Taking traditional dogleg step instead.";
+ ComputeTraditionalDoglegStep(dogleg);
+ return;
+ }
+
+ // Test first order optimality at the minimum.
+ // The first order KKT conditions state that the minimum x*
+ // has to satisfy either || x* ||^2 < r^2 (i.e. has to lie within
+ // the trust region), or
+ //
+ // (B x* + g) + y x* = 0
+ //
+ // for some positive scalar y.
+ // Here, as it is already known that the minimum lies on the boundary, the
+ // latter condition is tested. To allow for small imprecisions, we test if
+ // the angle between (B x* + g) and -x* is smaller than acos(0.99).
+ // The exact value of the cosine is arbitrary but should be close to 1.
+ //
+ // This condition should not be violated. If it is, the minimum was not
+ // correctly determined.
+ const double kCosineThreshold = 0.99;
+ const Vector2d grad_minimum = subspace_B_ * minimum + subspace_g_;
+ const double cosine_angle = -minimum.dot(grad_minimum) /
+ (minimum.norm() * grad_minimum.norm());
+ if (cosine_angle < kCosineThreshold) {
+ LOG(WARNING) << "First order optimality seems to be violated "
+ << "in the subspace method!\n"
+ << "Cosine of angle between x and B x + g is "
+ << cosine_angle << ".\n"
+ << "Taking a regular dogleg step instead.\n"
+ << "Please consider filing a bug report if this "
+ << "happens frequently or consistently.\n";
+ ComputeTraditionalDoglegStep(dogleg);
+ return;
+ }
+
+ // Create the full step from the optimal 2d solution.
+ dogleg_step = subspace_basis_ * minimum;
+ dogleg_step_norm_ = radius_;
+ dogleg_step.array() /= diagonal_.array();
+ VLOG(3) << "Dogleg subspace step size: " << dogleg_step_norm_
+ << " radius: " << radius_;
+}
+
+// Build the polynomial that defines the optimal Lagrange multipliers.
+// Let the Lagrangian be
+//
+// L(x, y) = 0.5 x^T B x + x^T g + y (0.5 x^T x - 0.5 r^2). (1)
+//
+// Stationary points of the Lagrangian are given by
+//
+// 0 = d L(x, y) / dx = Bx + g + y x (2)
+// 0 = d L(x, y) / dy = 0.5 x^T x - 0.5 r^2 (3)
+//
+// For any given y, we can solve (2) for x as
+//
+// x(y) = -(B + y I)^-1 g . (4)
+//
+// As B + y I is 2x2, we form the inverse explicitly:
+//
+// (B + y I)^-1 = (1 / det(B + y I)) adj(B + y I) (5)
+//
+// where adj() denotes adjugation. This should be safe, as B is positive
+// semi-definite and y is necessarily positive, so (B + y I) is indeed
+// invertible.
+// Plugging (5) into (4) and the result into (3), then dividing by 0.5 we
+// obtain
+//
+// 0 = (1 / det(B + y I))^2 g^T adj(B + y I)^T adj(B + y I) g - r^2
+// (6)
+//
+// or
+//
+// det(B + y I)^2 r^2 = g^T adj(B + y I)^T adj(B + y I) g (7a)
+// = g^T adj(B)^T adj(B) g
+// + 2 y g^T adj(B)^T g + y^2 g^T g (7b)
+//
+// as
+//
+// adj(B + y I) = adj(B) + y I = adj(B)^T + y I . (8)
+//
+// The left hand side can be expressed explicitly using
+//
+// det(B + y I) = det(B) + y tr(B) + y^2 . (9)
+//
+// So (7) is a polynomial in y of degree four.
+// Bringing everything back to the left hand side, the coefficients can
+// be read off as
+//
+// y^4 r^2
+// + y^3 2 r^2 tr(B)
+// + y^2 (r^2 tr(B)^2 + 2 r^2 det(B) - g^T g)
+// + y^1 (2 r^2 det(B) tr(B) - 2 g^T adj(B)^T g)
+// + y^0 (r^2 det(B)^2 - g^T adj(B)^T adj(B) g)
+//
+Vector DoglegStrategy::MakePolynomialForBoundaryConstrainedProblem() const {
+ const double detB = subspace_B_.determinant();
+ const double trB = subspace_B_.trace();
+ const double r2 = radius_ * radius_;
+ Matrix2d B_adj;
+ B_adj << subspace_B_(1,1) , -subspace_B_(0,1),
+ -subspace_B_(1,0) , subspace_B_(0,0);
+
+ Vector polynomial(5);
+ polynomial(0) = r2;
+ polynomial(1) = 2.0 * r2 * trB;
+ polynomial(2) = r2 * ( trB * trB + 2.0 * detB ) - subspace_g_.squaredNorm();
+ polynomial(3) = -2.0 * ( subspace_g_.transpose() * B_adj * subspace_g_
+ - r2 * detB * trB );
+ polynomial(4) = r2 * detB * detB - (B_adj * subspace_g_).squaredNorm();
+
+ return polynomial;
+}
+
+// Given a Lagrange multiplier y that corresponds to a stationary point
+// of the Lagrangian L(x, y), compute the corresponding x from the
+// equation
+//
+// 0 = d L(x, y) / dx
+// = B * x + g + y * x
+// = (B + y * I) * x + g
+//
+DoglegStrategy::Vector2d DoglegStrategy::ComputeSubspaceStepFromRoot(
+ double y) const {
+ const Matrix2d B_i = subspace_B_ + y * Matrix2d::Identity();
+ return -B_i.partialPivLu().solve(subspace_g_);
+}
+
+// This function evaluates the quadratic model at a point x in the
+// subspace spanned by subspace_basis_.
+double DoglegStrategy::EvaluateSubspaceModel(const Vector2d& x) const {
+ return 0.5 * x.dot(subspace_B_ * x) + subspace_g_.dot(x);
+}
+
+// This function attempts to solve the boundary-constrained subspace problem
+//
+// min. 1/2 x^T B^T H B x + g^T B x
+// s.t. || B x ||^2 = r^2
+//
+// where B is an orthonormal subspace basis and r is the trust-region radius.
+//
+// This is done by finding the roots of a fourth degree polynomial. If the
+// root finding fails, the function returns false and minimum will be set
+// to (0, 0). If it succeeds, true is returned.
+//
+// In the failure case, another step should be taken, such as the traditional
+// dogleg step.
+bool DoglegStrategy::FindMinimumOnTrustRegionBoundary(Vector2d* minimum) const {
+ CHECK_NOTNULL(minimum);
+
+ // Return (0, 0) in all error cases.
+ minimum->setZero();
+
+ // Create the fourth-degree polynomial that is a necessary condition for
+ // optimality.
+ const Vector polynomial = MakePolynomialForBoundaryConstrainedProblem();
+
+ // Find the real parts y_i of its roots (not only the real roots).
+ Vector roots_real;
+ if (!FindPolynomialRoots(polynomial, &roots_real, NULL)) {
+ // Failed to find the roots of the polynomial, i.e. the candidate
+ // solutions of the constrained problem. Report this back to the caller.
+ return false;
+ }
+
+ // For each root y, compute B x(y) and check for feasibility.
+ // Notice that there should always be four roots, as the leading term of
+ // the polynomial is r^2 and therefore non-zero. However, as some roots
+ // may be complex, the real parts are not necessarily unique.
+ double minimum_value = std::numeric_limits<double>::max();
+ bool valid_root_found = false;
+ for (int i = 0; i < roots_real.size(); ++i) {
+ const Vector2d x_i = ComputeSubspaceStepFromRoot(roots_real(i));
+
+ // Not all roots correspond to points on the trust region boundary.
+ // There are at most four candidate solutions. As we are interested
+ // in the minimum, it is safe to consider all of them after projecting
+ // them onto the trust region boundary.
+ if (x_i.norm() > 0) {
+ const double f_i = EvaluateSubspaceModel((radius_ / x_i.norm()) * x_i);
+ valid_root_found = true;
+ if (f_i < minimum_value) {
+ minimum_value = f_i;
+ *minimum = x_i;
+ }
+ }
+ }
+
+ return valid_root_found;
+}
+
+LinearSolver::Summary DoglegStrategy::ComputeGaussNewtonStep(
+ SparseMatrix* jacobian,
+ const double* residuals) {
+ const int n = jacobian->num_cols();
+ LinearSolver::Summary linear_solver_summary;
+ linear_solver_summary.termination_type = FAILURE;
+
+ // The Jacobian matrix is often quite poorly conditioned. Thus it is
+ // necessary to add a diagonal matrix at the bottom to prevent the
+ // linear solver from failing.
+ //
+ // We do this by computing the same diagonal matrix as the one used
+ // by Levenberg-Marquardt (other choices are possible), and scaling
+ // it by a small constant (independent of the trust region radius).
+ //
+ // If the solve fails, the multiplier to the diagonal is increased
+ // up to max_mu_ by a factor of mu_increase_factor_ every time. If
+ // the linear solver is still not successful, the strategy returns
+ // with FAILURE.
+ //
+ // Next time when a new Gauss-Newton step is requested, the
+ // multiplier starts out from the last successful solve.
+ //
+ // When a step is declared successful, the multiplier is decreased
+ // by half of mu_increase_factor_.
+
+ while (mu_ < max_mu_) {
+ // Dogleg, as far as I (sameeragarwal) understand it, requires a
+ // reasonably good estimate of the Gauss-Newton step. This means
+ // that we need to solve the normal equations more or less
+ // exactly. This is reflected in the values of the tolerances set
+ // below.
+ //
+ // For now, this strategy should only be used with exact
+ // factorization based solvers, for which these tolerances are
+ // automatically satisfied.
+ //
+ // The right way to combine inexact solves with trust region
+ // methods is to use Stiehaug's method.
+ LinearSolver::PerSolveOptions solve_options;
+ solve_options.q_tolerance = 0.0;
+ solve_options.r_tolerance = 0.0;
+
+ lm_diagonal_ = diagonal_ * std::sqrt(mu_);
+ solve_options.D = lm_diagonal_.data();
+
+ // As in the LevenbergMarquardtStrategy, solve Jy = r instead
+ // of Jx = -r and later set x = -y to avoid having to modify
+ // either jacobian or residuals.
+ InvalidateArray(n, gauss_newton_step_.data());
+ linear_solver_summary = linear_solver_->Solve(jacobian,
+ residuals,
+ solve_options,
+ gauss_newton_step_.data());
+
+ if (linear_solver_summary.termination_type == FAILURE ||
+ !IsArrayValid(n, gauss_newton_step_.data())) {
+ mu_ *= mu_increase_factor_;
+ VLOG(2) << "Increasing mu " << mu_;
+ linear_solver_summary.termination_type = FAILURE;
+ continue;
+ }
+ break;
+ }
+
+ if (linear_solver_summary.termination_type != FAILURE) {
+ // The scaled Gauss-Newton step is D * GN:
+ //
+ // - (D^-1 J^T J D^-1)^-1 (D^-1 g)
+ // = - D (J^T J)^-1 D D^-1 g
+ // = D -(J^T J)^-1 g
+ //
+ gauss_newton_step_.array() *= -diagonal_.array();
+ }
+
+ return linear_solver_summary;
+}
+
+void DoglegStrategy::StepAccepted(double step_quality) {
+ CHECK_GT(step_quality, 0.0);
+
+ if (step_quality < decrease_threshold_) {
+ radius_ *= 0.5;
+ }
+
+ if (step_quality > increase_threshold_) {
+ radius_ = max(radius_, 3.0 * dogleg_step_norm_);
+ }
+
+ // Reduce the regularization multiplier, in the hope that whatever
+ // was causing the rank deficiency has gone away and we can return
+ // to doing a pure Gauss-Newton solve.
+ mu_ = max(min_mu_, 2.0 * mu_ / mu_increase_factor_ );
+ reuse_ = false;
+}
+
+void DoglegStrategy::StepRejected(double step_quality) {
+ radius_ *= 0.5;
+ reuse_ = true;
+}
+
+void DoglegStrategy::StepIsInvalid() {
+ mu_ *= mu_increase_factor_;
+ reuse_ = false;
+}
+
+double DoglegStrategy::Radius() const {
+ return radius_;
+}
+
+bool DoglegStrategy::ComputeSubspaceModel(SparseMatrix* jacobian) {
+ // Compute an orthogonal basis for the subspace using QR decomposition.
+ Matrix basis_vectors(jacobian->num_cols(), 2);
+ basis_vectors.col(0) = gradient_;
+ basis_vectors.col(1) = gauss_newton_step_;
+ Eigen::ColPivHouseholderQR<Matrix> basis_qr(basis_vectors);
+
+ switch (basis_qr.rank()) {
+ case 0:
+ // This should never happen, as it implies that both the gradient
+ // and the Gauss-Newton step are zero. In this case, the minimizer should
+ // have stopped due to the gradient being too small.
+ LOG(ERROR) << "Rank of subspace basis is 0. "
+ << "This means that the gradient at the current iterate is "
+ << "zero but the optimization has not been terminated. "
+ << "You may have found a bug in Ceres.";
+ return false;
+
+ case 1:
+ // Gradient and Gauss-Newton step coincide, so we lie on one of the
+ // major axes of the quadratic problem. In this case, we simply move
+ // along the gradient until we reach the trust region boundary.
+ subspace_is_one_dimensional_ = true;
+ return true;
+
+ case 2:
+ subspace_is_one_dimensional_ = false;
+ break;
+
+ default:
+ LOG(ERROR) << "Rank of the subspace basis matrix is reported to be "
+ << "greater than 2. As the matrix contains only two "
+ << "columns this cannot be true and is indicative of "
+ << "a bug.";
+ return false;
+ }
+
+ // The subspace is two-dimensional, so compute the subspace model.
+ // Given the basis U, this is
+ //
+ // subspace_g_ = g_scaled^T U
+ //
+ // and
+ //
+ // subspace_B_ = U^T (J_scaled^T J_scaled) U
+ //
+ // As J_scaled = J * D^-1, the latter becomes
+ //
+ // subspace_B_ = ((U^T D^-1) J^T) (J (D^-1 U))
+ // = (J (D^-1 U))^T (J (D^-1 U))
+
+ subspace_basis_ =
+ basis_qr.householderQ() * Matrix::Identity(jacobian->num_cols(), 2);
+
+ subspace_g_ = subspace_basis_.transpose() * gradient_;
+
+ Eigen::Matrix<double, 2, Eigen::Dynamic, Eigen::RowMajor>
+ Jb(2, jacobian->num_rows());
+ Jb.setZero();
+
+ Vector tmp;
+ tmp = (subspace_basis_.col(0).array() / diagonal_.array()).matrix();
+ jacobian->RightMultiply(tmp.data(), Jb.row(0).data());
+ tmp = (subspace_basis_.col(1).array() / diagonal_.array()).matrix();
+ jacobian->RightMultiply(tmp.data(), Jb.row(1).data());
+
+ subspace_B_ = Jb * Jb.transpose();
+
+ return true;
+}
+
+} // namespace internal
+} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/dogleg_strategy.h b/extern/libmv/third_party/ceres/internal/ceres/dogleg_strategy.h
new file mode 100644
index 00000000000..bff1689aa4a
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/dogleg_strategy.h
@@ -0,0 +1,163 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+
+#ifndef CERES_INTERNAL_DOGLEG_STRATEGY_H_
+#define CERES_INTERNAL_DOGLEG_STRATEGY_H_
+
+#include "ceres/linear_solver.h"
+#include "ceres/trust_region_strategy.h"
+
+namespace ceres {
+namespace internal {
+
+// Dogleg step computation and trust region sizing strategy based on
+// on "Methods for Nonlinear Least Squares" by K. Madsen, H.B. Nielsen
+// and O. Tingleff. Available to download from
+//
+// http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3215/pdf/imm3215.pdf
+//
+// One minor modification is that instead of computing the pure
+// Gauss-Newton step, we compute a regularized version of it. This is
+// because the Jacobian is often rank-deficient and in such cases
+// using a direct solver leads to numerical failure.
+//
+// If SUBSPACE is passed as the type argument to the constructor, the
+// DoglegStrategy follows the approach by Shultz, Schnabel, Byrd.
+// This finds the exact optimum over the two-dimensional subspace
+// spanned by the two Dogleg vectors.
+class DoglegStrategy : public TrustRegionStrategy {
+public:
+ DoglegStrategy(const TrustRegionStrategy::Options& options);
+ virtual ~DoglegStrategy() {}
+
+ // TrustRegionStrategy interface
+ virtual Summary ComputeStep(const PerSolveOptions& per_solve_options,
+ SparseMatrix* jacobian,
+ const double* residuals,
+ double* step);
+ virtual void StepAccepted(double step_quality);
+ virtual void StepRejected(double step_quality);
+ virtual void StepIsInvalid();
+
+ virtual double Radius() const;
+
+ // These functions are predominantly for testing.
+ Vector gradient() const { return gradient_; }
+ Vector gauss_newton_step() const { return gauss_newton_step_; }
+ Matrix subspace_basis() const { return subspace_basis_; }
+ Vector subspace_g() const { return subspace_g_; }
+ Matrix subspace_B() const { return subspace_B_; }
+
+ private:
+ typedef Eigen::Matrix<double, 2, 1, Eigen::DontAlign> Vector2d;
+ typedef Eigen::Matrix<double, 2, 2, Eigen::DontAlign> Matrix2d;
+
+ LinearSolver::Summary ComputeGaussNewtonStep(SparseMatrix* jacobian,
+ const double* residuals);
+ void ComputeCauchyPoint(SparseMatrix* jacobian);
+ void ComputeGradient(SparseMatrix* jacobian, const double* residuals);
+ void ComputeTraditionalDoglegStep(double* step);
+ bool ComputeSubspaceModel(SparseMatrix* jacobian);
+ void ComputeSubspaceDoglegStep(double* step);
+
+ bool FindMinimumOnTrustRegionBoundary(Vector2d* minimum) const;
+ Vector MakePolynomialForBoundaryConstrainedProblem() const;
+ Vector2d ComputeSubspaceStepFromRoot(double lambda) const;
+ double EvaluateSubspaceModel(const Vector2d& x) const;
+
+ LinearSolver* linear_solver_;
+ double radius_;
+ const double max_radius_;
+
+ const double min_diagonal_;
+ const double max_diagonal_;
+
+ // mu is used to scale the diagonal matrix used to make the
+ // Gauss-Newton solve full rank. In each solve, the strategy starts
+ // out with mu = min_mu, and tries values upto max_mu. If the user
+ // reports an invalid step, the value of mu_ is increased so that
+ // the next solve starts with a stronger regularization.
+ //
+ // If a successful step is reported, then the value of mu_ is
+ // decreased with a lower bound of min_mu_.
+ double mu_;
+ const double min_mu_;
+ const double max_mu_;
+ const double mu_increase_factor_;
+ const double increase_threshold_;
+ const double decrease_threshold_;
+
+ Vector diagonal_; // sqrt(diag(J^T J))
+ Vector lm_diagonal_;
+
+ Vector gradient_;
+ Vector gauss_newton_step_;
+
+ // cauchy_step = alpha * gradient
+ double alpha_;
+ double dogleg_step_norm_;
+
+ // When, ComputeStep is called, reuse_ indicates whether the
+ // Gauss-Newton and Cauchy steps from the last call to ComputeStep
+ // can be reused or not.
+ //
+ // If the user called StepAccepted, then it is expected that the
+ // user has recomputed the Jacobian matrix and new Gauss-Newton
+ // solve is needed and reuse is set to false.
+ //
+ // If the user called StepRejected, then it is expected that the
+ // user wants to solve the trust region problem with the same matrix
+ // but a different trust region radius and the Gauss-Newton and
+ // Cauchy steps can be reused to compute the Dogleg, thus reuse is
+ // set to true.
+ //
+ // If the user called StepIsInvalid, then there was a numerical
+ // problem with the step computed in the last call to ComputeStep,
+ // and the regularization used to do the Gauss-Newton solve is
+ // increased and a new solve should be done when ComputeStep is
+ // called again, thus reuse is set to false.
+ bool reuse_;
+
+ // The dogleg type determines how the minimum of the local
+ // quadratic model is found.
+ DoglegType dogleg_type_;
+
+ // If the type is SUBSPACE_DOGLEG, the two-dimensional
+ // model 1/2 x^T B x + g^T x has to be computed and stored.
+ bool subspace_is_one_dimensional_;
+ Matrix subspace_basis_;
+ Vector2d subspace_g_;
+ Matrix2d subspace_B_;
+};
+
+} // namespace internal
+} // namespace ceres
+
+#endif // CERES_INTERNAL_DOGLEG_STRATEGY_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/evaluator.cc b/extern/libmv/third_party/ceres/internal/ceres/evaluator.cc
index ea05aefec8c..a3ce6f04bd4 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/evaluator.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/evaluator.cc
@@ -28,14 +28,18 @@
//
// Author: keir@google.com (Keir Mierle)
-#include <glog/logging.h>
-#include "ceres/evaluator.h"
+#include <vector>
#include "ceres/block_evaluate_preparer.h"
#include "ceres/block_jacobian_writer.h"
#include "ceres/compressed_row_jacobian_writer.h"
-#include "ceres/scratch_evaluate_preparer.h"
+#include "ceres/compressed_row_sparse_matrix.h"
+#include "ceres/crs_matrix.h"
#include "ceres/dense_jacobian_writer.h"
+#include "ceres/evaluator.h"
+#include "ceres/internal/port.h"
#include "ceres/program_evaluator.h"
+#include "ceres/scratch_evaluate_preparer.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -47,6 +51,7 @@ Evaluator* Evaluator::Create(const Evaluator::Options& options,
string* error) {
switch (options.linear_solver_type) {
case DENSE_QR:
+ case DENSE_NORMAL_CHOLESKY:
return new ProgramEvaluator<ScratchEvaluatePreparer,
DenseJacobianWriter>(options,
program);
@@ -67,5 +72,76 @@ Evaluator* Evaluator::Create(const Evaluator::Options& options,
}
}
+bool Evaluator::Evaluate(Program* program,
+ int num_threads,
+ double* cost,
+ vector<double>* residuals,
+ vector<double>* gradient,
+ CRSMatrix* output_jacobian) {
+ CHECK_GE(num_threads, 1)
+ << "This is a Ceres bug; please contact the developers!";
+ CHECK_NOTNULL(cost);
+
+ // Setup the Parameter indices and offsets before an evaluator can
+ // be constructed and used.
+ program->SetParameterOffsetsAndIndex();
+
+ Evaluator::Options evaluator_options;
+ evaluator_options.linear_solver_type = SPARSE_NORMAL_CHOLESKY;
+ evaluator_options.num_threads = num_threads;
+
+ string error;
+ scoped_ptr<Evaluator> evaluator(
+ Evaluator::Create(evaluator_options, program, &error));
+ if (evaluator.get() == NULL) {
+ LOG(ERROR) << "Unable to create an Evaluator object. "
+ << "Error: " << error
+ << "This is a Ceres bug; please contact the developers!";
+ return false;
+ }
+
+ if (residuals !=NULL) {
+ residuals->resize(evaluator->NumResiduals());
+ }
+
+ if (gradient != NULL) {
+ gradient->resize(evaluator->NumEffectiveParameters());
+ }
+
+ scoped_ptr<CompressedRowSparseMatrix> jacobian;
+ if (output_jacobian != NULL) {
+ jacobian.reset(
+ down_cast<CompressedRowSparseMatrix*>(evaluator->CreateJacobian()));
+ }
+
+ // Point the state pointers to the user state pointers. This is
+ // needed so that we can extract a parameter vector which is then
+ // passed to Evaluator::Evaluate.
+ program->SetParameterBlockStatePtrsToUserStatePtrs();
+
+ // Copy the value of the parameter blocks into a vector, since the
+ // Evaluate::Evaluate method needs its input as such. The previous
+ // call to SetParameterBlockStatePtrsToUserStatePtrs ensures that
+ // these values are the ones corresponding to the actual state of
+ // the parameter blocks, rather than the temporary state pointer
+ // used for evaluation.
+ Vector parameters(program->NumParameters());
+ program->ParameterBlocksToStateVector(parameters.data());
+
+ if (!evaluator->Evaluate(parameters.data(),
+ cost,
+ residuals != NULL ? &(*residuals)[0] : NULL,
+ gradient != NULL ? &(*gradient)[0] : NULL,
+ jacobian.get())) {
+ return false;
+ }
+
+ if (output_jacobian != NULL) {
+ jacobian->ToCRSMatrix(output_jacobian);
+ }
+
+ return true;
+}
+
} // namespace internal
} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/evaluator.h b/extern/libmv/third_party/ceres/internal/ceres/evaluator.h
index adefdd26660..6aa30d7b739 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/evaluator.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/evaluator.h
@@ -33,10 +33,14 @@
#define CERES_INTERNAL_EVALUATOR_H_
#include <string>
+#include <vector>
#include "ceres/internal/port.h"
#include "ceres/types.h"
namespace ceres {
+
+class CRSMatrix;
+
namespace internal {
class Program;
@@ -65,6 +69,32 @@ class Evaluator {
Program* program,
string* error);
+
+ // This is used for computing the cost, residual and Jacobian for
+ // returning to the user. For actually solving the optimization
+ // problem, the optimization algorithm uses the ProgramEvaluator
+ // objects directly.
+ //
+ // The residual, gradients and jacobian pointers can be NULL, in
+ // which case they will not be evaluated. cost cannot be NULL.
+ //
+ // The parallelism of the evaluator is controlled by num_threads; it
+ // should be at least 1.
+ //
+ // Note: That this function does not take a parameter vector as
+ // input. The parameter blocks are evaluated on the values contained
+ // in the arrays pointed to by their user_state pointers.
+ //
+ // Also worth noting is that this function mutates program by
+ // calling Program::SetParameterOffsetsAndIndex() on it so that an
+ // evaluator object can be constructed.
+ static bool Evaluate(Program* program,
+ int num_threads,
+ double* cost,
+ vector<double>* residuals,
+ vector<double>* gradient,
+ CRSMatrix* jacobian);
+
// Build and return a sparse matrix for storing and working with the Jacobian
// of the objective function. The jacobian has dimensions
// NumEffectiveParameters() by NumParameters(), and is typically extremely
@@ -95,6 +125,7 @@ class Evaluator {
virtual bool Evaluate(const double* state,
double* cost,
double* residuals,
+ double* gradient,
SparseMatrix* jacobian) = 0;
// Make a change delta (of size NumEffectiveParameters()) to state (of size
diff --git a/extern/libmv/third_party/ceres/internal/ceres/file.cc b/extern/libmv/third_party/ceres/internal/ceres/file.cc
index 5fc9d220861..6fe7557246d 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/file.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/file.cc
@@ -31,7 +31,8 @@
// Really simple file IO.
#include <cstdio>
-#include <glog/logging.h>
+#include "file.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -48,7 +49,7 @@ void WriteStringToFileOrDie(const string &data, const string &filename) {
}
void ReadFileToStringOrDie(const string &filename, string *data) {
- FILE* file_descriptor = file_descriptor = fopen(filename.c_str(), "r");
+ FILE* file_descriptor = fopen(filename.c_str(), "r");
if (!file_descriptor) {
LOG(FATAL) << "Couldn't read file: " << filename;
diff --git a/extern/libmv/third_party/ceres/internal/ceres/generate_eliminator_specialization.py b/extern/libmv/third_party/ceres/internal/ceres/generate_eliminator_specialization.py
new file mode 100644
index 00000000000..af9873f94c0
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/generate_eliminator_specialization.py
@@ -0,0 +1,186 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+#
+# Copyright 2011 Google Inc. All Rights Reserved.
+# Author: sameeragarwal@google.com (Sameer Agarwal)
+#
+# Script for explicitly generating template specialization of the
+# SchurEliminator class. It is a rather large class
+# and the number of explicit instantiations is also large. Explicitly
+# generating these instantiations in separate .cc files breaks the
+# compilation into separate compilation unit rather than one large cc
+# file which takes 2+GB of RAM to compile.
+#
+# This script creates two sets of files.
+#
+# 1. schur_eliminator_x_x_x.cc
+# where, the x indicates the template parameters and
+#
+# 2. schur_eliminator.cc
+#
+# that contains a factory function for instantiating these classes
+# based on runtime parameters.
+#
+# The list of tuples, specializations indicates the set of
+# specializations that is generated.
+
+# Set of template specializations to generate
+SPECIALIZATIONS = [(2, 2, 2),
+ (2, 2, 3),
+ (2, 2, 4),
+ (2, 2, "Dynamic"),
+ (2, 3, 3),
+ (2, 3, 4),
+ (2, 3, 9),
+ (2, 3, "Dynamic"),
+ (2, 4, 3),
+ (2, 4, 4),
+ (2, 4, "Dynamic"),
+ (4, 4, 2),
+ (4, 4, 3),
+ (4, 4, 4),
+ (4, 4, "Dynamic"),
+ ("Dynamic", "Dynamic", "Dynamic")]
+
+SPECIALIZATION_FILE = """// Copyright 2011 Google Inc. All Rights Reserved.
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+//
+// Template specialization of SchurEliminator.
+//
+// ========================================
+// THIS FILE IS AUTOGENERATED. DO NOT EDIT.
+// THIS FILE IS AUTOGENERATED. DO NOT EDIT.
+// THIS FILE IS AUTOGENERATED. DO NOT EDIT.
+// THIS FILE IS AUTOGENERATED. DO NOT EDIT.
+//=========================================
+//
+// This file is generated using generate_eliminator_specializations.py.
+// Editing it manually is not recommended.
+
+#include "ceres/schur_eliminator_impl.h"
+#include "ceres/internal/eigen.h"
+
+namespace ceres {
+namespace internal {
+
+template class SchurEliminator<%s, %s, %s>;
+
+} // namespace internal
+} // namespace ceres
+
+"""
+
+FACTORY_FILE_HEADER = """// Copyright 2011 Google Inc. All Rights Reserved.
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+//
+// ========================================
+// THIS FILE IS AUTOGENERATED. DO NOT EDIT.
+// THIS FILE IS AUTOGENERATED. DO NOT EDIT.
+// THIS FILE IS AUTOGENERATED. DO NOT EDIT.
+// THIS FILE IS AUTOGENERATED. DO NOT EDIT.
+//=========================================
+//
+// This file is generated using generate_template_specializations.py.
+// Editing it manually is not recommended.
+
+#include "ceres/linear_solver.h"
+#include "ceres/schur_eliminator.h"
+#include "ceres/internal/eigen.h"
+
+namespace ceres {
+namespace internal {
+
+SchurEliminatorBase*
+SchurEliminatorBase::Create(const LinearSolver::Options& options) {
+#ifndef CERES_RESTRICT_SCHUR_SPECIALIZATION
+"""
+
+FACTORY_CONDITIONAL = """ if ((options.row_block_size == %s) &&
+ (options.e_block_size == %s) &&
+ (options.f_block_size == %s)) {
+ return new SchurEliminator<%s, %s, %s>(options);
+ }
+"""
+
+FACTORY_FOOTER = """
+#endif
+ VLOG(1) << "Template specializations not found for <"
+ << options.row_block_size << ","
+ << options.e_block_size << ","
+ << options.f_block_size << ">";
+ return new SchurEliminator<Dynamic, Dynamic, Dynamic>(options);
+}
+
+} // namespace internal
+} // namespace ceres
+"""
+
+
+def SuffixForSize(size):
+ if size == "Dynamic":
+ return "d"
+ return str(size)
+
+
+def SpecializationFilename(prefix, row_block_size, e_block_size, f_block_size):
+ return "_".join([prefix] + map(SuffixForSize, (row_block_size,
+ e_block_size,
+ f_block_size)))
+
+
+def Specialize():
+ """
+ Generate specialization code and the conditionals to instantiate it.
+ """
+ f = open("schur_eliminator.cc", "w")
+ f.write(FACTORY_FILE_HEADER)
+
+ for row_block_size, e_block_size, f_block_size in SPECIALIZATIONS:
+ output = SpecializationFilename("generated/schur_eliminator",
+ row_block_size,
+ e_block_size,
+ f_block_size) + ".cc"
+ fptr = open(output, "w")
+ fptr.write(SPECIALIZATION_FILE % (row_block_size,
+ e_block_size,
+ f_block_size))
+ fptr.close()
+
+ f.write(FACTORY_CONDITIONAL % (row_block_size,
+ e_block_size,
+ f_block_size,
+ row_block_size,
+ e_block_size,
+ f_block_size))
+ f.write(FACTORY_FOOTER)
+ f.close()
+
+
+if __name__ == "__main__":
+ Specialize()
diff --git a/extern/libmv/third_party/ceres/internal/ceres/gradient_checking_cost_function.cc b/extern/libmv/third_party/ceres/internal/ceres/gradient_checking_cost_function.cc
index abba40824ef..7fb3ed7b3a8 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/gradient_checking_cost_function.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/gradient_checking_cost_function.cc
@@ -36,18 +36,18 @@
#include <string>
#include <vector>
-#include <glog/logging.h>
+#include "ceres/cost_function.h"
+#include "ceres/internal/eigen.h"
+#include "ceres/internal/scoped_ptr.h"
#include "ceres/parameter_block.h"
+#include "ceres/problem.h"
#include "ceres/problem_impl.h"
#include "ceres/program.h"
#include "ceres/residual_block.h"
#include "ceres/runtime_numeric_diff_cost_function.h"
#include "ceres/stringprintf.h"
-#include "ceres/cost_function.h"
-#include "ceres/internal/eigen.h"
-#include "ceres/internal/scoped_ptr.h"
-#include "ceres/problem.h"
#include "ceres/types.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/graph.h b/extern/libmv/third_party/ceres/internal/ceres/graph.h
index fd7a224f0aa..2c0f6d28e54 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/graph.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/graph.h
@@ -129,7 +129,7 @@ class Graph {
HashMap<Vertex, HashSet<Vertex> > edges_;
HashMap<pair<Vertex, Vertex>, double> edge_weights_;
- DISALLOW_COPY_AND_ASSIGN(Graph);
+ CERES_DISALLOW_COPY_AND_ASSIGN(Graph);
};
} // namespace internal
diff --git a/extern/libmv/third_party/ceres/internal/ceres/implicit_schur_complement.cc b/extern/libmv/third_party/ceres/internal/ceres/implicit_schur_complement.cc
index bd908846362..4af030a8535 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/implicit_schur_complement.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/implicit_schur_complement.cc
@@ -30,22 +30,20 @@
#include "ceres/implicit_schur_complement.h"
-#include <glog/logging.h>
#include "Eigen/Dense"
#include "ceres/block_sparse_matrix.h"
#include "ceres/block_structure.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/scoped_ptr.h"
#include "ceres/types.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
ImplicitSchurComplement::ImplicitSchurComplement(int num_eliminate_blocks,
- bool constant_sparsity,
bool preconditioner)
: num_eliminate_blocks_(num_eliminate_blocks),
- constant_sparsity_(constant_sparsity),
preconditioner_(preconditioner),
A_(NULL),
D_(NULL),
@@ -62,7 +60,7 @@ void ImplicitSchurComplement::Init(const BlockSparseMatrixBase& A,
const double* b) {
// Since initialization is reasonably heavy, perhaps we can save on
// constructing a new object everytime.
- if ((A_ == NULL) || !constant_sparsity_) {
+ if (A_ == NULL) {
A_.reset(new PartitionedMatrixView(A, num_eliminate_blocks_));
}
@@ -71,7 +69,7 @@ void ImplicitSchurComplement::Init(const BlockSparseMatrixBase& A,
// Initialize temporary storage and compute the block diagonals of
// E'E and F'E.
- if ((!constant_sparsity_) || (block_diagonal_EtE_inverse_ == NULL)) {
+ if (block_diagonal_EtE_inverse_ == NULL) {
block_diagonal_EtE_inverse_.reset(A_->CreateBlockDiagonalEtE());
if (preconditioner_) {
block_diagonal_FtF_inverse_.reset(A_->CreateBlockDiagonalFtF());
@@ -92,17 +90,10 @@ void ImplicitSchurComplement::Init(const BlockSparseMatrixBase& A,
// The block diagonals of the augmented linear system contain
// contributions from the diagonal D if it is non-null. Add that to
// the block diagonals and invert them.
- if (D_ != NULL) {
- AddDiagonalAndInvert(D_, block_diagonal_EtE_inverse_.get());
- if (preconditioner_) {
- AddDiagonalAndInvert(D_ + A_->num_cols_e(),
- block_diagonal_FtF_inverse_.get());
- }
- } else {
- AddDiagonalAndInvert(NULL, block_diagonal_EtE_inverse_.get());
- if (preconditioner_) {
- AddDiagonalAndInvert(NULL, block_diagonal_FtF_inverse_.get());
- }
+ AddDiagonalAndInvert(D_, block_diagonal_EtE_inverse_.get());
+ if (preconditioner_) {
+ AddDiagonalAndInvert((D_ == NULL) ? NULL : D_ + A_->num_cols_e(),
+ block_diagonal_FtF_inverse_.get());
}
// Compute the RHS of the Schur complement system.
diff --git a/extern/libmv/third_party/ceres/internal/ceres/implicit_schur_complement.h b/extern/libmv/third_party/ceres/internal/ceres/implicit_schur_complement.h
index 37a319f9c57..b9ebaa4628e 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/implicit_schur_complement.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/implicit_schur_complement.h
@@ -91,20 +91,13 @@ class ImplicitSchurComplement : public LinearOperator {
// num_eliminate_blocks is the number of E blocks in the matrix
// A.
//
- // constant_sparsity indicates if across calls to Init, the sparsity
- // structure of the matrix A remains constant or not. This makes for
- // significant savings across multiple matrices A, e.g. when used in
- // conjunction with an optimization algorithm.
- //
// preconditioner indicates whether the inverse of the matrix F'F
// should be computed or not as a preconditioner for the Schur
// Complement.
//
// TODO(sameeragarwal): Get rid of the two bools below and replace
// them with enums.
- ImplicitSchurComplement(int num_eliminate_blocks,
- bool constant_sparsity,
- bool preconditioner);
+ ImplicitSchurComplement(int num_eliminate_blocks, bool preconditioner);
virtual ~ImplicitSchurComplement();
// Initialize the Schur complement for a linear least squares
@@ -151,7 +144,6 @@ class ImplicitSchurComplement : public LinearOperator {
void UpdateRhs();
int num_eliminate_blocks_;
- bool constant_sparsity_;
bool preconditioner_;
scoped_ptr<PartitionedMatrixView> A_;
diff --git a/extern/libmv/third_party/ceres/internal/ceres/iterative_schur_complement_solver.cc b/extern/libmv/third_party/ceres/internal/ceres/iterative_schur_complement_solver.cc
index 51303195317..679c41f2431 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/iterative_schur_complement_solver.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/iterative_schur_complement_solver.cc
@@ -33,22 +33,18 @@
#include <algorithm>
#include <cstring>
#include <vector>
-
-#include <glog/logging.h>
#include "Eigen/Dense"
#include "ceres/block_sparse_matrix.h"
#include "ceres/block_structure.h"
#include "ceres/conjugate_gradients_solver.h"
#include "ceres/implicit_schur_complement.h"
-#include "ceres/linear_solver.h"
-#include "ceres/triplet_sparse_matrix.h"
-#include "ceres/visibility_based_preconditioner.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/scoped_ptr.h"
#include "ceres/linear_solver.h"
#include "ceres/triplet_sparse_matrix.h"
#include "ceres/types.h"
#include "ceres/visibility_based_preconditioner.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -69,10 +65,9 @@ LinearSolver::Summary IterativeSchurComplementSolver::SolveImpl(
CHECK_NOTNULL(A->block_structure());
// Initialize a ImplicitSchurComplement object.
- if ((schur_complement_ == NULL) || (!options_.constant_sparsity)) {
+ if (schur_complement_ == NULL) {
schur_complement_.reset(
new ImplicitSchurComplement(options_.num_eliminate_blocks,
- options_.constant_sparsity,
options_.preconditioner_type == JACOBI));
}
schur_complement_->Init(*A, per_solve_options.D, b);
@@ -119,7 +114,7 @@ LinearSolver::Summary IterativeSchurComplementSolver::SolveImpl(
new VisibilityBasedPreconditioner(*A->block_structure(), options_));
}
is_preconditioner_good =
- visibility_based_preconditioner_->Compute(*A, per_solve_options.D);
+ visibility_based_preconditioner_->Update(*A, per_solve_options.D);
cg_per_solve_options.preconditioner =
visibility_based_preconditioner_.get();
break;
diff --git a/extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt.cc b/extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt.cc
deleted file mode 100644
index b40a5162adc..00000000000
--- a/extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt.cc
+++ /dev/null
@@ -1,574 +0,0 @@
-// Ceres Solver - A fast non-linear least squares minimizer
-// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
-// http://code.google.com/p/ceres-solver/
-//
-// 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.
-// * Neither the name of Google Inc. nor the names of its contributors may be
-// used to endorse or promote products derived from this software without
-// specific prior written permission.
-//
-// 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.
-//
-// Author: sameeragarwal@google.com (Sameer Agarwal)
-//
-// Implementation of a simple LM algorithm which uses the step sizing
-// rule of "Methods for Nonlinear Least Squares" by K. Madsen,
-// H.B. Nielsen and O. Tingleff. Available to download from
-//
-// http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3215/pdf/imm3215.pdf
-//
-// The basic algorithm described in this note is an exact step
-// algorithm that depends on the Newton(LM) step being solved exactly
-// in each iteration. When a suitable iterative solver is available to
-// solve the Newton(LM) step, the algorithm will automatically switch
-// to an inexact step solution method. This trades some slowdown in
-// convergence for significant savings in solve time and memory
-// usage. Our implementation of the Truncated Newton algorithm follows
-// the discussion and recommendataions in "Stephen G. Nash, A Survey
-// of Truncated Newton Methods, Journal of Computational and Applied
-// Mathematics, 124(1-2), 45-59, 2000.
-
-#include "ceres/levenberg_marquardt.h"
-
-#include <algorithm>
-#include <cstdlib>
-#include <cmath>
-#include <cstring>
-#include <string>
-#include <vector>
-
-#include <glog/logging.h>
-#include "Eigen/Core"
-#include "ceres/evaluator.h"
-#include "ceres/file.h"
-#include "ceres/linear_least_squares_problems.h"
-#include "ceres/linear_solver.h"
-#include "ceres/matrix_proto.h"
-#include "ceres/sparse_matrix.h"
-#include "ceres/stringprintf.h"
-#include "ceres/internal/eigen.h"
-#include "ceres/internal/scoped_ptr.h"
-#include "ceres/types.h"
-
-namespace ceres {
-namespace internal {
-namespace {
-
-// Numbers for clamping the size of the LM diagonal. The size of these
-// numbers is heuristic. We will probably be adjusting them in the
-// future based on more numerical experience. With jacobi scaling
-// enabled, these numbers should be all but redundant.
-const double kMinLevenbergMarquardtDiagonal = 1e-6;
-const double kMaxLevenbergMarquardtDiagonal = 1e32;
-
-// Small constant for various floating point issues.
-const double kEpsilon = 1e-12;
-
-// Number of times the linear solver should be retried in case of
-// numerical failure. The retries are done by exponentially scaling up
-// mu at each retry. This leads to stronger and stronger
-// regularization making the linear least squares problem better
-// conditioned at each retry.
-const int kMaxLinearSolverRetries = 5;
-
-// D = 1/sqrt(diag(J^T * J))
-void EstimateScale(const SparseMatrix& jacobian, double* D) {
- CHECK_NOTNULL(D);
- jacobian.SquaredColumnNorm(D);
- for (int i = 0; i < jacobian.num_cols(); ++i) {
- D[i] = 1.0 / (kEpsilon + sqrt(D[i]));
- }
-}
-
-// D = diag(J^T * J)
-void LevenbergMarquardtDiagonal(const SparseMatrix& jacobian,
- double* D) {
- CHECK_NOTNULL(D);
- jacobian.SquaredColumnNorm(D);
- for (int i = 0; i < jacobian.num_cols(); ++i) {
- D[i] = min(max(D[i], kMinLevenbergMarquardtDiagonal),
- kMaxLevenbergMarquardtDiagonal);
- }
-}
-
-bool RunCallback(IterationCallback* callback,
- const IterationSummary& iteration_summary,
- Solver::Summary* summary) {
- const CallbackReturnType status = (*callback)(iteration_summary);
- switch (status) {
- case SOLVER_TERMINATE_SUCCESSFULLY:
- summary->termination_type = USER_SUCCESS;
- VLOG(1) << "Terminating on USER_SUCCESS.";
- return false;
- case SOLVER_ABORT:
- summary->termination_type = USER_ABORT;
- VLOG(1) << "Terminating on USER_ABORT.";
- return false;
- case SOLVER_CONTINUE:
- return true;
- default:
- LOG(FATAL) << "Unknown status returned by callback: "
- << status;
- return NULL;
- }
-}
-
-} // namespace
-
-LevenbergMarquardt::~LevenbergMarquardt() {}
-
-void LevenbergMarquardt::Minimize(const Minimizer::Options& options,
- Evaluator* evaluator,
- LinearSolver* linear_solver,
- const double* initial_parameters,
- double* final_parameters,
- Solver::Summary* summary) {
- time_t start_time = time(NULL);
- const int num_parameters = evaluator->NumParameters();
- const int num_effective_parameters = evaluator->NumEffectiveParameters();
- const int num_residuals = evaluator->NumResiduals();
-
- summary->termination_type = NO_CONVERGENCE;
- summary->num_successful_steps = 0;
- summary->num_unsuccessful_steps = 0;
-
- // Allocate the various vectors needed by the algorithm.
- memcpy(final_parameters, initial_parameters,
- num_parameters * sizeof(*initial_parameters));
-
- VectorRef x(final_parameters, num_parameters);
- Vector x_new(num_parameters);
-
- Vector lm_step(num_effective_parameters);
- Vector gradient(num_effective_parameters);
- Vector scaled_gradient(num_effective_parameters);
- // Jacobi scaling vector
- Vector scale(num_effective_parameters);
-
- Vector f_model(num_residuals);
- Vector f(num_residuals);
- Vector f_new(num_residuals);
- Vector D(num_parameters);
- Vector muD(num_parameters);
-
- // Ask the Evaluator to create the jacobian matrix. The sparsity
- // pattern of this matrix is going to remain constant, so we only do
- // this once and then re-use this matrix for all subsequent Jacobian
- // computations.
- scoped_ptr<SparseMatrix> jacobian(evaluator->CreateJacobian());
-
- double x_norm = x.norm();
-
- double cost = 0.0;
- D.setOnes();
- f.setZero();
-
- // Do initial cost and Jacobian evaluation.
- if (!evaluator->Evaluate(x.data(), &cost, f.data(), jacobian.get())) {
- LOG(WARNING) << "Failed to compute residuals and Jacobian. "
- << "Terminating.";
- summary->termination_type = NUMERICAL_FAILURE;
- return;
- }
-
- if (options.jacobi_scaling) {
- EstimateScale(*jacobian, scale.data());
- jacobian->ScaleColumns(scale.data());
- } else {
- scale.setOnes();
- }
-
- // This is a poor way to do this computation. Even if fixed_cost is
- // zero, because we are subtracting two possibly large numbers, we
- // are depending on exact cancellation to give us a zero here. But
- // initial_cost and cost have been computed by two different
- // evaluators. One which runs on the whole problem (in
- // solver_impl.cc) in single threaded mode and another which runs
- // here on the reduced problem, so fixed_cost can (and does) contain
- // some numerical garbage with a relative magnitude of 1e-14.
- //
- // The right way to do this, would be to compute the fixed cost on
- // just the set of residual blocks which are held constant and were
- // removed from the original problem when the reduced problem was
- // constructed.
- summary->fixed_cost = summary->initial_cost - cost;
-
- double model_cost = f.squaredNorm() / 2.0;
- double total_cost = summary->fixed_cost + cost;
-
- scaled_gradient.setZero();
- jacobian->LeftMultiply(f.data(), scaled_gradient.data());
- gradient = scaled_gradient.array() / scale.array();
-
- double gradient_max_norm = gradient.lpNorm<Eigen::Infinity>();
- // We need the max here to guard againt the gradient being zero.
- const double gradient_max_norm_0 = max(gradient_max_norm, kEpsilon);
- double gradient_tolerance = options.gradient_tolerance * gradient_max_norm_0;
-
- double mu = options.tau;
- double nu = 2.0;
- int iteration = 0;
- double actual_cost_change = 0.0;
- double step_norm = 0.0;
- double relative_decrease = 0.0;
-
- // Insane steps are steps which are not sane, i.e. there is some
- // numerical kookiness going on with them. There are various reasons
- // for this kookiness, some easier to diagnose then others. From the
- // point of view of the non-linear solver, they are steps which
- // cannot be used. We return with NUMERICAL_FAILURE after
- // kMaxLinearSolverRetries consecutive insane steps.
- bool step_is_sane = false;
- int num_consecutive_insane_steps = 0;
-
- // Whether the step resulted in a sufficient decrease in the
- // objective function when compared to the decrease in the value of
- // the lineariztion.
- bool step_is_successful = false;
-
- // Parse the iterations for which to dump the linear problem.
- vector<int> iterations_to_dump = options.lsqp_iterations_to_dump;
- sort(iterations_to_dump.begin(), iterations_to_dump.end());
-
- IterationSummary iteration_summary;
- iteration_summary.iteration = iteration;
- iteration_summary.step_is_successful = false;
- iteration_summary.cost = total_cost;
- iteration_summary.cost_change = actual_cost_change;
- iteration_summary.gradient_max_norm = gradient_max_norm;
- iteration_summary.step_norm = step_norm;
- iteration_summary.relative_decrease = relative_decrease;
- iteration_summary.mu = mu;
- iteration_summary.eta = options.eta;
- iteration_summary.linear_solver_iterations = 0;
- iteration_summary.linear_solver_time_sec = 0.0;
- iteration_summary.iteration_time_sec = (time(NULL) - start_time);
- if (options.logging_type >= PER_MINIMIZER_ITERATION) {
- summary->iterations.push_back(iteration_summary);
- }
-
- // Check if the starting point is an optimum.
- VLOG(2) << "Gradient max norm: " << gradient_max_norm
- << " tolerance: " << gradient_tolerance
- << " ratio: " << gradient_max_norm / gradient_max_norm_0
- << " tolerance: " << options.gradient_tolerance;
- if (gradient_max_norm <= gradient_tolerance) {
- summary->termination_type = GRADIENT_TOLERANCE;
- VLOG(1) << "Terminating on GRADIENT_TOLERANCE. "
- << "Relative gradient max norm: "
- << gradient_max_norm / gradient_max_norm_0
- << " <= " << options.gradient_tolerance;
- return;
- }
-
- // Call the various callbacks.
- for (int i = 0; i < options.callbacks.size(); ++i) {
- if (!RunCallback(options.callbacks[i], iteration_summary, summary)) {
- return;
- }
- }
-
- // We only need the LM diagonal if we are actually going to do at
- // least one iteration of the optimization. So we wait to do it
- // until now.
- LevenbergMarquardtDiagonal(*jacobian, D.data());
-
- while ((iteration < options.max_num_iterations) &&
- (time(NULL) - start_time) <= options.max_solver_time_sec) {
- time_t iteration_start_time = time(NULL);
- step_is_sane = false;
- step_is_successful = false;
-
- IterationSummary iteration_summary;
- // The while loop here is just to provide an easily breakable
- // control structure. We are guaranteed to always exit this loop
- // at the end of one iteration or before.
- while (1) {
- muD = (mu * D).array().sqrt();
- LinearSolver::PerSolveOptions solve_options;
- solve_options.D = muD.data();
- solve_options.q_tolerance = options.eta;
- // Disable r_tolerance checking. Since we only care about
- // termination via the q_tolerance. As Nash and Sofer show,
- // r_tolerance based termination is essentially useless in
- // Truncated Newton methods.
- solve_options.r_tolerance = -1.0;
-
- const time_t linear_solver_start_time = time(NULL);
- LinearSolver::Summary linear_solver_summary =
- linear_solver->Solve(jacobian.get(),
- f.data(),
- solve_options,
- lm_step.data());
- iteration_summary.linear_solver_time_sec =
- (time(NULL) - linear_solver_start_time);
- iteration_summary.linear_solver_iterations =
- linear_solver_summary.num_iterations;
-
- if (binary_search(iterations_to_dump.begin(),
- iterations_to_dump.end(),
- iteration)) {
- CHECK(DumpLinearLeastSquaresProblem(options.lsqp_dump_directory,
- iteration,
- options.lsqp_dump_format_type,
- jacobian.get(),
- muD.data(),
- f.data(),
- lm_step.data(),
- options.num_eliminate_blocks))
- << "Tried writing linear least squares problem: "
- << options.lsqp_dump_directory
- << " but failed.";
- }
-
- // We ignore the case where the linear solver did not converge,
- // since the partial solution computed by it still maybe of use,
- // and there is no reason to ignore it, especially since we
- // spent so much time computing it.
- if ((linear_solver_summary.termination_type != TOLERANCE) &&
- (linear_solver_summary.termination_type != MAX_ITERATIONS)) {
- VLOG(1) << "Linear solver failure: retrying with a higher mu";
- break;
- }
-
- step_norm = (lm_step.array() * scale.array()).matrix().norm();
-
- // Check step length based convergence. If the step length is
- // too small, then we are done.
- const double step_size_tolerance = options.parameter_tolerance *
- (x_norm + options.parameter_tolerance);
-
- VLOG(2) << "Step size: " << step_norm
- << " tolerance: " << step_size_tolerance
- << " ratio: " << step_norm / step_size_tolerance
- << " tolerance: " << options.parameter_tolerance;
- if (step_norm <= options.parameter_tolerance *
- (x_norm + options.parameter_tolerance)) {
- summary->termination_type = PARAMETER_TOLERANCE;
- VLOG(1) << "Terminating on PARAMETER_TOLERANCE."
- << "Relative step size: " << step_norm / step_size_tolerance
- << " <= " << options.parameter_tolerance;
- return;
- }
-
- Vector delta = -(lm_step.array() * scale.array()).matrix();
- if (!evaluator->Plus(x.data(), delta.data(), x_new.data())) {
- LOG(WARNING) << "Failed to compute Plus(x, delta, x_plus_delta). "
- << "Terminating.";
- summary->termination_type = NUMERICAL_FAILURE;
- return;
- }
-
- double cost_new = 0.0;
- if (!evaluator->Evaluate(x_new.data(), &cost_new, NULL, NULL)) {
- LOG(WARNING) << "Failed to compute the value of the objective "
- << "function. Terminating.";
- summary->termination_type = NUMERICAL_FAILURE;
- return;
- }
-
- f_model.setZero();
- jacobian->RightMultiply(lm_step.data(), f_model.data());
- const double model_cost_new =
- (f.segment(0, num_residuals) - f_model).squaredNorm() / 2;
-
- actual_cost_change = cost - cost_new;
- double model_cost_change = model_cost - model_cost_new;
-
- VLOG(2) << "[Model cost] current: " << model_cost
- << " new : " << model_cost_new
- << " change: " << model_cost_change;
-
- VLOG(2) << "[Nonlinear cost] current: " << cost
- << " new : " << cost_new
- << " change: " << actual_cost_change
- << " relative change: " << fabs(actual_cost_change) / cost
- << " tolerance: " << options.function_tolerance;
-
- // In exact arithmetic model_cost_change should never be
- // negative. But due to numerical precision issues, we may end up
- // with a small negative number. model_cost_change which are
- // negative and large in absolute value are indicative of a
- // numerical failure in the solver.
- if (model_cost_change < -kEpsilon) {
- VLOG(1) << "Model cost change is negative.\n"
- << "Current : " << model_cost
- << " new : " << model_cost_new
- << " change: " << model_cost_change << "\n";
- break;
- }
-
- // If we have reached this far, then we are willing to trust the
- // numerical quality of the step.
- step_is_sane = true;
- num_consecutive_insane_steps = 0;
-
- // Check function value based convergence.
- if (fabs(actual_cost_change) < options.function_tolerance * cost) {
- VLOG(1) << "Termination on FUNCTION_TOLERANCE."
- << " Relative cost change: " << fabs(actual_cost_change) / cost
- << " tolerance: " << options.function_tolerance;
- summary->termination_type = FUNCTION_TOLERANCE;
- return;
- }
-
- // Clamp model_cost_change at kEpsilon from below.
- if (model_cost_change < kEpsilon) {
- VLOG(1) << "Clamping model cost change " << model_cost_change
- << " to " << kEpsilon;
- model_cost_change = kEpsilon;
- }
-
- relative_decrease = actual_cost_change / model_cost_change;
- VLOG(2) << "actual_cost_change / model_cost_change = "
- << relative_decrease;
-
- if (relative_decrease < options.min_relative_decrease) {
- VLOG(2) << "Unsuccessful step.";
- break;
- }
-
- VLOG(2) << "Successful step.";
-
- ++summary->num_successful_steps;
- x = x_new;
- x_norm = x.norm();
-
- if (!evaluator->Evaluate(x.data(), &cost, f.data(), jacobian.get())) {
- LOG(WARNING) << "Failed to compute residuals and jacobian. "
- << "Terminating.";
- summary->termination_type = NUMERICAL_FAILURE;
- return;
- }
-
- if (options.jacobi_scaling) {
- jacobian->ScaleColumns(scale.data());
- }
-
- model_cost = f.squaredNorm() / 2.0;
- LevenbergMarquardtDiagonal(*jacobian, D.data());
- scaled_gradient.setZero();
- jacobian->LeftMultiply(f.data(), scaled_gradient.data());
- gradient = scaled_gradient.array() / scale.array();
- gradient_max_norm = gradient.lpNorm<Eigen::Infinity>();
-
- // Check gradient based convergence.
- VLOG(2) << "Gradient max norm: " << gradient_max_norm
- << " tolerance: " << gradient_tolerance
- << " ratio: " << gradient_max_norm / gradient_max_norm_0
- << " tolerance: " << options.gradient_tolerance;
- if (gradient_max_norm <= gradient_tolerance) {
- summary->termination_type = GRADIENT_TOLERANCE;
- VLOG(1) << "Terminating on GRADIENT_TOLERANCE. "
- << "Relative gradient max norm: "
- << gradient_max_norm / gradient_max_norm_0
- << " <= " << options.gradient_tolerance
- << " (tolerance).";
- return;
- }
-
- mu = mu * max(1.0 / 3.0, 1 - pow(2 * relative_decrease - 1, 3));
- nu = 2.0;
- step_is_successful = true;
- break;
- }
-
- if (!step_is_sane) {
- ++num_consecutive_insane_steps;
- }
-
- if (num_consecutive_insane_steps == kMaxLinearSolverRetries) {
- summary->termination_type = NUMERICAL_FAILURE;
- VLOG(1) << "Too many consecutive retries; ending with numerical fail.";
-
- if (!options.crash_and_dump_lsqp_on_failure) {
- return;
- }
-
- // Dump debugging information to disk.
- CHECK(options.lsqp_dump_format_type == TEXTFILE ||
- options.lsqp_dump_format_type == PROTOBUF)
- << "Dumping the linear least squares problem on crash "
- << "requires Solver::Options::lsqp_dump_format_type to be "
- << "PROTOBUF or TEXTFILE.";
-
- if (DumpLinearLeastSquaresProblem(options.lsqp_dump_directory,
- iteration,
- options.lsqp_dump_format_type,
- jacobian.get(),
- muD.data(),
- f.data(),
- lm_step.data(),
- options.num_eliminate_blocks)) {
- LOG(FATAL) << "Linear least squares problem saved to: "
- << options.lsqp_dump_directory
- << ". Please provide this to the Ceres developers for "
- << " debugging along with the v=2 log.";
- } else {
- LOG(FATAL) << "Tried writing linear least squares problem: "
- << options.lsqp_dump_directory
- << " but failed.";
- }
- }
-
- if (!step_is_successful) {
- // Either the step did not lead to a decrease in cost or there
- // was numerical failure. In either case we will scale mu up and
- // retry. If it was a numerical failure, we hope that the
- // stronger regularization will make the linear system better
- // conditioned. If it was numerically sane, but there was no
- // decrease in cost, then increasing mu reduces the size of the
- // trust region and we look for a decrease closer to the
- // linearization point.
- ++summary->num_unsuccessful_steps;
- mu = mu * nu;
- nu = 2 * nu;
- }
-
- ++iteration;
-
- total_cost = summary->fixed_cost + cost;
-
- iteration_summary.iteration = iteration;
- iteration_summary.step_is_successful = step_is_successful;
- iteration_summary.cost = total_cost;
- iteration_summary.cost_change = actual_cost_change;
- iteration_summary.gradient_max_norm = gradient_max_norm;
- iteration_summary.step_norm = step_norm;
- iteration_summary.relative_decrease = relative_decrease;
- iteration_summary.mu = mu;
- iteration_summary.eta = options.eta;
- iteration_summary.iteration_time_sec = (time(NULL) - iteration_start_time);
-
- if (options.logging_type >= PER_MINIMIZER_ITERATION) {
- summary->iterations.push_back(iteration_summary);
- }
-
- // Call the various callbacks.
- for (int i = 0; i < options.callbacks.size(); ++i) {
- if (!RunCallback(options.callbacks[i], iteration_summary, summary)) {
- return;
- }
- }
- }
-}
-
-} // namespace internal
-} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt_strategy.cc b/extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt_strategy.cc
new file mode 100644
index 00000000000..9e6a59e3813
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt_strategy.cc
@@ -0,0 +1,144 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+
+#include "ceres/levenberg_marquardt_strategy.h"
+
+#include <cmath>
+#include "Eigen/Core"
+#include "ceres/array_utils.h"
+#include "ceres/internal/eigen.h"
+#include "ceres/linear_solver.h"
+#include "ceres/sparse_matrix.h"
+#include "ceres/trust_region_strategy.h"
+#include "ceres/types.h"
+#include "glog/logging.h"
+
+namespace ceres {
+namespace internal {
+
+LevenbergMarquardtStrategy::LevenbergMarquardtStrategy(
+ const TrustRegionStrategy::Options& options)
+ : linear_solver_(options.linear_solver),
+ radius_(options.initial_radius),
+ max_radius_(options.max_radius),
+ min_diagonal_(options.lm_min_diagonal),
+ max_diagonal_(options.lm_max_diagonal),
+ decrease_factor_(2.0),
+ reuse_diagonal_(false) {
+ CHECK_NOTNULL(linear_solver_);
+ CHECK_GT(min_diagonal_, 0.0);
+ CHECK_LE(min_diagonal_, max_diagonal_);
+ CHECK_GT(max_radius_, 0.0);
+}
+
+LevenbergMarquardtStrategy::~LevenbergMarquardtStrategy() {
+}
+
+TrustRegionStrategy::Summary LevenbergMarquardtStrategy::ComputeStep(
+ const TrustRegionStrategy::PerSolveOptions& per_solve_options,
+ SparseMatrix* jacobian,
+ const double* residuals,
+ double* step) {
+ CHECK_NOTNULL(jacobian);
+ CHECK_NOTNULL(residuals);
+ CHECK_NOTNULL(step);
+
+ const int num_parameters = jacobian->num_cols();
+ if (!reuse_diagonal_) {
+ if (diagonal_.rows() != num_parameters) {
+ diagonal_.resize(num_parameters, 1);
+ }
+
+ jacobian->SquaredColumnNorm(diagonal_.data());
+ for (int i = 0; i < num_parameters; ++i) {
+ diagonal_[i] = min(max(diagonal_[i], min_diagonal_), max_diagonal_);
+ }
+ }
+
+ lm_diagonal_ = (diagonal_ / radius_).array().sqrt();
+
+ LinearSolver::PerSolveOptions solve_options;
+ solve_options.D = lm_diagonal_.data();
+ solve_options.q_tolerance = per_solve_options.eta;
+ // Disable r_tolerance checking. Since we only care about
+ // termination via the q_tolerance. As Nash and Sofer show,
+ // r_tolerance based termination is essentially useless in
+ // Truncated Newton methods.
+ solve_options.r_tolerance = -1.0;
+
+ // Invalidate the output array lm_step, so that we can detect if
+ // the linear solver generated numerical garbage. This is known
+ // to happen for the DENSE_QR and then DENSE_SCHUR solver when
+ // the Jacobin is severly rank deficient and mu is too small.
+ InvalidateArray(num_parameters, step);
+
+ // Instead of solving Jx = -r, solve Jy = r.
+ // Then x can be found as x = -y, but the inputs jacobian and residuals
+ // do not need to be modified.
+ LinearSolver::Summary linear_solver_summary =
+ linear_solver_->Solve(jacobian, residuals, solve_options, step);
+ if (linear_solver_summary.termination_type == FAILURE ||
+ !IsArrayValid(num_parameters, step)) {
+ LOG(WARNING) << "Linear solver failure. Failed to compute a finite step.";
+ linear_solver_summary.termination_type = FAILURE;
+ } else {
+ VectorRef(step, num_parameters) *= -1.0;
+ }
+
+ reuse_diagonal_ = true;
+
+ TrustRegionStrategy::Summary summary;
+ summary.residual_norm = linear_solver_summary.residual_norm;
+ summary.num_iterations = linear_solver_summary.num_iterations;
+ summary.termination_type = linear_solver_summary.termination_type;
+ return summary;
+}
+
+void LevenbergMarquardtStrategy::StepAccepted(double step_quality) {
+ CHECK_GT(step_quality, 0.0);
+ radius_ = radius_ / std::max(1.0 / 3.0,
+ 1.0 - pow(2.0 * step_quality - 1.0, 3));
+ radius_ = std::min(max_radius_, radius_);
+ decrease_factor_ = 2.0;
+ reuse_diagonal_ = false;
+}
+
+void LevenbergMarquardtStrategy::StepRejected(double step_quality) {
+ radius_ = radius_ / decrease_factor_;
+ decrease_factor_ *= 2.0;
+ reuse_diagonal_ = true;
+}
+
+double LevenbergMarquardtStrategy::Radius() const {
+ return radius_;
+}
+
+} // namespace internal
+} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt_strategy.h b/extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt_strategy.h
new file mode 100644
index 00000000000..90c21789797
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/levenberg_marquardt_strategy.h
@@ -0,0 +1,86 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+
+#ifndef CERES_INTERNAL_LEVENBERG_MARQUARDT_STRATEGY_H_
+#define CERES_INTERNAL_LEVENBERG_MARQUARDT_STRATEGY_H_
+
+#include "ceres/internal/eigen.h"
+#include "ceres/trust_region_strategy.h"
+
+namespace ceres {
+namespace internal {
+
+// Levenberg-Marquardt step computation and trust region sizing
+// strategy based on on "Methods for Nonlinear Least Squares" by
+// K. Madsen, H.B. Nielsen and O. Tingleff. Available to download from
+//
+// http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3215/pdf/imm3215.pdf
+class LevenbergMarquardtStrategy : public TrustRegionStrategy {
+public:
+ LevenbergMarquardtStrategy(const TrustRegionStrategy::Options& options);
+ virtual ~LevenbergMarquardtStrategy();
+
+ // TrustRegionStrategy interface
+ virtual TrustRegionStrategy::Summary ComputeStep(
+ const TrustRegionStrategy::PerSolveOptions& per_solve_options,
+ SparseMatrix* jacobian,
+ const double* residuals,
+ double* step);
+ virtual void StepAccepted(double step_quality);
+ virtual void StepRejected(double step_quality);
+ virtual void StepIsInvalid() {
+ // Treat the current step as a rejected step with no increase in
+ // solution quality. Since rejected steps lead to decrease in the
+ // size of the trust region, the next time ComputeStep is called,
+ // this will lead to a better conditioned system.
+ StepRejected(0.0);
+ }
+
+ virtual double Radius() const;
+
+ private:
+ LinearSolver* linear_solver_;
+ double radius_;
+ double max_radius_;
+ const double min_diagonal_;
+ const double max_diagonal_;
+ double decrease_factor_;
+ bool reuse_diagonal_;
+ Vector diagonal_; // diagonal_ = diag(J'J)
+ // Scaled copy of diagonal_. Stored here as optimization to prevent
+ // allocations in every iteration and reuse when a step fails and
+ // ComputeStep is called again.
+ Vector lm_diagonal_; // lm_diagonal_ = diagonal_ / radius_;
+};
+
+} // namespace internal
+} // namespace ceres
+
+#endif // CERES_INTERNAL_LEVENBERG_MARQUARDT_STRATEGY_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/linear_least_squares_problems.cc b/extern/libmv/third_party/ceres/internal/ceres/linear_least_squares_problems.cc
index cca9f442fe7..a91e254a663 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/linear_least_squares_problems.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/linear_least_squares_problems.cc
@@ -33,17 +33,17 @@
#include <cstdio>
#include <string>
#include <vector>
-#include <glog/logging.h>
#include "ceres/block_sparse_matrix.h"
#include "ceres/block_structure.h"
#include "ceres/casts.h"
#include "ceres/compressed_row_sparse_matrix.h"
#include "ceres/file.h"
+#include "ceres/internal/scoped_ptr.h"
#include "ceres/matrix_proto.h"
-#include "ceres/triplet_sparse_matrix.h"
#include "ceres/stringprintf.h"
-#include "ceres/internal/scoped_ptr.h"
+#include "ceres/triplet_sparse_matrix.h"
#include "ceres/types.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -64,7 +64,7 @@ LinearLeastSquaresProblem* CreateLinearLeastSquaresProblemFromId(int id) {
return NULL;
}
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
LinearLeastSquaresProblem* CreateLinearLeastSquaresProblemFromFile(
const string& filename) {
LinearLeastSquaresProblemProto problem_proto;
@@ -130,7 +130,7 @@ LinearLeastSquaresProblem* CreateLinearLeastSquaresProblemFromFile(
<< "Ceres to be built with Protocol Buffers support.";
return NULL;
}
-#endif // CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#endif // CERES_NO_PROTOCOL_BUFFERS
/*
A = [1 2]
@@ -573,13 +573,13 @@ LinearLeastSquaresProblem* LinearLeastSquaresProblem3() {
return problem;
}
-bool DumpLinearLeastSquaresProblemToConsole(const string& directory,
- int iteration,
- const SparseMatrix* A,
- const double* D,
- const double* b,
- const double* x,
- int num_eliminate_blocks) {
+static bool DumpLinearLeastSquaresProblemToConsole(const string& directory,
+ int iteration,
+ const SparseMatrix* A,
+ const double* D,
+ const double* b,
+ const double* x,
+ int num_eliminate_blocks) {
CHECK_NOTNULL(A);
Matrix AA;
A->ToDenseMatrix(&AA);
@@ -600,14 +600,14 @@ bool DumpLinearLeastSquaresProblemToConsole(const string& directory,
return true;
};
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
-bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
- int iteration,
- const SparseMatrix* A,
- const double* D,
- const double* b,
- const double* x,
- int num_eliminate_blocks) {
+#ifndef CERES_NO_PROTOCOL_BUFFERS
+static bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
+ int iteration,
+ const SparseMatrix* A,
+ const double* D,
+ const double* b,
+ const double* x,
+ int num_eliminate_blocks) {
CHECK_NOTNULL(A);
LinearLeastSquaresProblemProto lsqp;
A->ToProto(lsqp.mutable_a());
@@ -641,13 +641,13 @@ bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
return true;
}
#else
-bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
- int iteration,
- const SparseMatrix* A,
- const double* D,
- const double* b,
- const double* x,
- int num_eliminate_blocks) {
+static bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
+ int iteration,
+ const SparseMatrix* A,
+ const double* D,
+ const double* b,
+ const double* x,
+ int num_eliminate_blocks) {
LOG(ERROR) << "Dumping least squares problems is only "
<< "supported when Ceres is compiled with "
<< "protocol buffer support.";
@@ -655,9 +655,9 @@ bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
}
#endif
-void WriteArrayToFileOrDie(const string& filename,
- const double* x,
- const int size) {
+static void WriteArrayToFileOrDie(const string& filename,
+ const double* x,
+ const int size) {
CHECK_NOTNULL(x);
VLOG(2) << "Writing array to: " << filename;
FILE* fptr = fopen(filename.c_str(), "w");
@@ -668,43 +668,68 @@ void WriteArrayToFileOrDie(const string& filename,
fclose(fptr);
}
-bool DumpLinearLeastSquaresProblemToTextFile(const string& directory,
- int iteration,
- const SparseMatrix* A,
- const double* D,
- const double* b,
- const double* x,
- int num_eliminate_blocks) {
+static bool DumpLinearLeastSquaresProblemToTextFile(const string& directory,
+ int iteration,
+ const SparseMatrix* A,
+ const double* D,
+ const double* b,
+ const double* x,
+ int num_eliminate_blocks) {
CHECK_NOTNULL(A);
string format_string = JoinPath(directory,
"lm_iteration_%03d");
string filename_prefix =
StringPrintf(format_string.c_str(), iteration);
+ LOG(INFO) << "writing to: " << filename_prefix << "*";
+
+ string matlab_script;
+ StringAppendF(&matlab_script,
+ "function lsqp = lm_iteration_%03d()\n", iteration);
+ StringAppendF(&matlab_script,
+ "lsqp.num_rows = %d;\n", A->num_rows());
+ StringAppendF(&matlab_script,
+ "lsqp.num_cols = %d;\n", A->num_cols());
+
{
string filename = filename_prefix + "_A.txt";
- LOG(INFO) << "writing to: " << filename;
FILE* fptr = fopen(filename.c_str(), "w");
CHECK_NOTNULL(fptr);
A->ToTextFile(fptr);
fclose(fptr);
+ StringAppendF(&matlab_script,
+ "tmp = load('%s', '-ascii');\n", filename.c_str());
+ StringAppendF(
+ &matlab_script,
+ "lsqp.A = sparse(tmp(:, 1) + 1, tmp(:, 2) + 1, tmp(:, 3), %d, %d);\n",
+ A->num_rows(),
+ A->num_cols());
}
+
if (D != NULL) {
string filename = filename_prefix + "_D.txt";
WriteArrayToFileOrDie(filename, D, A->num_cols());
+ StringAppendF(&matlab_script,
+ "lsqp.D = load('%s', '-ascii');\n", filename.c_str());
}
if (b != NULL) {
string filename = filename_prefix + "_b.txt";
WriteArrayToFileOrDie(filename, b, A->num_rows());
+ StringAppendF(&matlab_script,
+ "lsqp.b = load('%s', '-ascii');\n", filename.c_str());
}
if (x != NULL) {
string filename = filename_prefix + "_x.txt";
WriteArrayToFileOrDie(filename, x, A->num_cols());
+ StringAppendF(&matlab_script,
+ "lsqp.x = load('%s', '-ascii');\n", filename.c_str());
}
+ string matlab_filename = filename_prefix + ".m";
+ WriteStringToFileOrDie(matlab_script, matlab_filename);
return true;
}
diff --git a/extern/libmv/third_party/ceres/internal/ceres/linear_solver.cc b/extern/libmv/third_party/ceres/internal/ceres/linear_solver.cc
index b2e3941eea1..08c3ba110d0 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/linear_solver.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/linear_solver.cc
@@ -30,13 +30,14 @@
#include "ceres/linear_solver.h"
-#include <glog/logging.h>
#include "ceres/cgnr_solver.h"
+#include "ceres/dense_normal_cholesky_solver.h"
#include "ceres/dense_qr_solver.h"
#include "ceres/iterative_schur_complement_solver.h"
#include "ceres/schur_complement_solver.h"
#include "ceres/sparse_normal_cholesky_solver.h"
#include "ceres/types.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -50,22 +51,24 @@ LinearSolver* LinearSolver::Create(const LinearSolver::Options& options) {
return new CgnrSolver(options);
case SPARSE_NORMAL_CHOLESKY:
-#ifndef CERES_NO_SUITESPARSE
- return new SparseNormalCholeskySolver(options);
-#else
+#if defined(CERES_NO_SUITESPARSE) && defined(CERES_NO_CXSPARSE)
LOG(WARNING) << "SPARSE_NORMAL_CHOLESKY is not available. Please "
- << "build Ceres with SuiteSparse. Returning NULL.";
+ << "build Ceres with SuiteSparse or CXSparse. "
+ << "Returning NULL.";
return NULL;
-#endif // CERES_NO_SUITESPARSE
+#else
+ return new SparseNormalCholeskySolver(options);
+#endif
case SPARSE_SCHUR:
-#ifndef CERES_NO_SUITESPARSE
- return new SparseSchurComplementSolver(options);
-#else
+#if defined(CERES_NO_SUITESPARSE) && defined(CERES_NO_CXSPARSE)
LOG(WARNING) << "SPARSE_SCHUR is not available. Please "
- << "build Ceres with SuiteSparse. Returning NULL.";
+ << "build Ceres with SuiteSparse or CXSparse. "
+ << "Returning NULL.";
return NULL;
-#endif // CERES_NO_SUITESPARSE
+#else
+ return new SparseSchurComplementSolver(options);
+#endif
case DENSE_SCHUR:
return new DenseSchurComplementSolver(options);
@@ -76,10 +79,13 @@ LinearSolver* LinearSolver::Create(const LinearSolver::Options& options) {
case DENSE_QR:
return new DenseQRSolver(options);
+ case DENSE_NORMAL_CHOLESKY:
+ return new DenseNormalCholeskySolver(options);
+
default:
LOG(FATAL) << "Unknown linear solver type :"
<< options.type;
- return NULL; // MSVC doesn't understand that LOG(FATAL) never returns.
+ return NULL; // MSVC doesn't understand that LOG(FATAL) never returns.
}
}
diff --git a/extern/libmv/third_party/ceres/internal/ceres/linear_solver.h b/extern/libmv/third_party/ceres/internal/ceres/linear_solver.h
index 5860ecc8a77..31f88740b9f 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/linear_solver.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/linear_solver.h
@@ -55,10 +55,11 @@ class LinearOperator;
// Ax = b
//
// It is expected that a single instance of a LinearSolver object
-// maybe used multiple times for solving different linear
-// systems. This allows them to cache and reuse information across
-// solves if for example the sparsity of the linear system remains
-// constant.
+// maybe used multiple times for solving multiple linear systems with
+// the same sparsity structure. This allows them to cache and reuse
+// information across solves. This means that calling Solve on the
+// same LinearSolver instance with two different linear systems will
+// result in undefined behaviour.
//
// Subclasses of LinearSolver use two structs to configure themselves.
// The Options struct configures the LinearSolver object for its
@@ -70,10 +71,11 @@ class LinearSolver {
Options()
: type(SPARSE_NORMAL_CHOLESKY),
preconditioner_type(JACOBI),
+ sparse_linear_algebra_library(SUITE_SPARSE),
+ use_block_amd(true),
min_num_iterations(1),
max_num_iterations(1),
num_threads(1),
- constant_sparsity(false),
num_eliminate_blocks(0),
residual_reset_period(10),
row_block_size(Dynamic),
@@ -85,6 +87,11 @@ class LinearSolver {
PreconditionerType preconditioner_type;
+ SparseLinearAlgebraLibraryType sparse_linear_algebra_library;
+
+ // See solver.h for explanation of this option.
+ bool use_block_amd;
+
// Number of internal iterations that the solver uses. This
// parameter only makes sense for iterative solvers like CG.
int min_num_iterations;
@@ -93,10 +100,6 @@ class LinearSolver {
// If possible, how many threads can the solver use.
int num_threads;
- // If possible cache and reuse the symbolic factorization across
- // multiple calls.
- bool constant_sparsity;
-
// Eliminate 0 to num_eliminate_blocks - 1 from the Normal
// equations to form a schur complement. Only used by the Schur
// complement based solver. The most common use for this parameter
@@ -121,8 +124,8 @@ class LinearSolver {
// It is expected that these parameters are set programmatically
// rather than manually.
//
- // Please see explicit_schur_complement_solver_impl.h for more
- // details.
+ // Please see schur_complement_solver.h and schur_eliminator.h for
+ // more details.
int row_block_size;
int e_block_size;
int f_block_size;
@@ -244,6 +247,7 @@ class LinearSolver {
const PerSolveOptions& per_solve_options,
double* x) = 0;
+ // Factory
static LinearSolver* Create(const Options& options);
};
diff --git a/extern/libmv/third_party/ceres/internal/ceres/local_parameterization.cc b/extern/libmv/third_party/ceres/internal/ceres/local_parameterization.cc
index eeae74e3f95..26e7f4908a4 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/local_parameterization.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/local_parameterization.cc
@@ -28,10 +28,11 @@
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
-#include <glog/logging.h>
-#include "ceres/internal/eigen.h"
#include "ceres/local_parameterization.h"
+
+#include "ceres/internal/eigen.h"
#include "ceres/rotation.h"
+#include "glog/logging.h"
namespace ceres {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/loss_function.cc b/extern/libmv/third_party/ceres/internal/ceres/loss_function.cc
index 00b2b184729..b948f289f21 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/loss_function.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/loss_function.cc
@@ -77,6 +77,70 @@ void CauchyLoss::Evaluate(double s, double rho[3]) const {
rho[2] = - c_ * (inv * inv);
}
+void ArctanLoss::Evaluate(double s, double rho[3]) const {
+ const double sum = 1 + s * s * b_;
+ const double inv = 1 / sum;
+ // 'sum' and 'inv' are always positive.
+ rho[0] = a_ * atan2(s, a_);
+ rho[1] = inv;
+ rho[2] = -2 * s * b_ * (inv * inv);
+}
+
+TolerantLoss::TolerantLoss(double a, double b)
+ : a_(a),
+ b_(b),
+ c_(b * log(1.0 + exp(-a / b))) {
+ CHECK_GE(a, 0.0);
+ CHECK_GT(b, 0.0);
+}
+
+void TolerantLoss::Evaluate(double s, double rho[3]) const {
+ const double x = (s - a_) / b_;
+ // The basic equation is rho[0] = b ln(1 + e^x). However, if e^x is too
+ // large, it will overflow. Since numerically 1 + e^x == e^x when the
+ // x is greater than about ln(2^53) for doubles, beyond this threshold
+ // we substitute x for ln(1 + e^x) as a numerically equivalent approximation.
+ static const double kLog2Pow53 = 36.7; // ln(MathLimits<double>::kEpsilon).
+ if (x > kLog2Pow53) {
+ rho[0] = s - a_ - c_;
+ rho[1] = 1.0;
+ rho[2] = 0.0;
+ } else {
+ const double e_x = exp(x);
+ rho[0] = b_ * log(1.0 + e_x) - c_;
+ rho[1] = e_x / (1.0 + e_x);
+ rho[2] = 0.5 / (b_ * (1.0 + cosh(x)));
+ }
+}
+
+ComposedLoss::ComposedLoss(const LossFunction* f, Ownership ownership_f,
+ const LossFunction* g, Ownership ownership_g)
+ : f_(CHECK_NOTNULL(f)),
+ g_(CHECK_NOTNULL(g)),
+ ownership_f_(ownership_f),
+ ownership_g_(ownership_g) {
+}
+
+ComposedLoss::~ComposedLoss() {
+ if (ownership_f_ == DO_NOT_TAKE_OWNERSHIP) {
+ f_.release();
+ }
+ if (ownership_g_ == DO_NOT_TAKE_OWNERSHIP) {
+ g_.release();
+ }
+}
+
+void ComposedLoss::Evaluate(double s, double rho[3]) const {
+ double rho_f[3], rho_g[3];
+ g_->Evaluate(s, rho_g);
+ f_->Evaluate(rho_g[0], rho_f);
+ rho[0] = rho_f[0];
+ // f'(g(s)) * g'(s).
+ rho[1] = rho_f[1] * rho_g[1];
+ // f''(g(s)) * g'(s) * g'(s) + f'(g(s)) * g''(s).
+ rho[2] = rho_f[2] * rho_g[1] * rho_g[1] + rho_f[1] * rho_g[2];
+}
+
void ScaledLoss::Evaluate(double s, double rho[3]) const {
if (rho_.get() == NULL) {
rho[0] = a_ * s;
diff --git a/extern/libmv/third_party/ceres/internal/ceres/matrix_proto.h b/extern/libmv/third_party/ceres/internal/ceres/matrix_proto.h
index b8a3a1a6de6..94b3076e3d7 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/matrix_proto.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/matrix_proto.h
@@ -33,7 +33,7 @@
#ifndef CERES_INTERNAL_MATRIX_PROTO_H_
#define CERES_INTERNAL_MATRIX_PROTO_H_
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
#include "ceres/matrix.pb.h"
#endif
diff --git a/extern/libmv/third_party/ceres/internal/ceres/minimizer.h b/extern/libmv/third_party/ceres/internal/ceres/minimizer.h
index 77cb00cb6b4..cfc98a3ebd0 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/minimizer.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/minimizer.h
@@ -40,6 +40,8 @@ namespace internal {
class Evaluator;
class LinearSolver;
+class SparseMatrix;
+class TrustRegionStrategy;
// Interface for non-linear least squares solvers.
class Minimizer {
@@ -48,53 +50,93 @@ class Minimizer {
// see solver.h for detailed information about the meaning and
// default values of each of these parameters.
struct Options {
+ Options() {
+ Init(Solver::Options());
+ }
+
explicit Options(const Solver::Options& options) {
+ Init(options);
+ }
+
+ void Init(const Solver::Options& options) {
max_num_iterations = options.max_num_iterations;
- max_solver_time_sec = options.max_solver_time_sec;
+ max_solver_time_in_seconds = options.max_solver_time_in_seconds;
+ max_step_solver_retries = 5;
gradient_tolerance = options.gradient_tolerance;
parameter_tolerance = options.parameter_tolerance;
function_tolerance = options.function_tolerance;
min_relative_decrease = options.min_relative_decrease;
eta = options.eta;
- tau = options.tau;
jacobi_scaling = options.jacobi_scaling;
- crash_and_dump_lsqp_on_failure = options.crash_and_dump_lsqp_on_failure;
+ use_nonmonotonic_steps = options.use_nonmonotonic_steps;
+ max_consecutive_nonmonotonic_steps =
+ options.max_consecutive_nonmonotonic_steps;
lsqp_dump_directory = options.lsqp_dump_directory;
lsqp_iterations_to_dump = options.lsqp_iterations_to_dump;
lsqp_dump_format_type = options.lsqp_dump_format_type;
num_eliminate_blocks = options.num_eliminate_blocks;
- logging_type = options.logging_type;
+ max_num_consecutive_invalid_steps =
+ options.max_num_consecutive_invalid_steps;
+ min_trust_region_radius = options.min_trust_region_radius;
+ evaluator = NULL;
+ trust_region_strategy = NULL;
+ jacobian = NULL;
+ callbacks = options.callbacks;
}
int max_num_iterations;
- int max_solver_time_sec;
+ double max_solver_time_in_seconds;
+
+ // Number of times the linear solver should be retried in case of
+ // numerical failure. The retries are done by exponentially scaling up
+ // mu at each retry. This leads to stronger and stronger
+ // regularization making the linear least squares problem better
+ // conditioned at each retry.
+ int max_step_solver_retries;
double gradient_tolerance;
double parameter_tolerance;
double function_tolerance;
double min_relative_decrease;
double eta;
- double tau;
bool jacobi_scaling;
- bool crash_and_dump_lsqp_on_failure;
+ bool use_nonmonotonic_steps;
+ int max_consecutive_nonmonotonic_steps;
vector<int> lsqp_iterations_to_dump;
DumpFormatType lsqp_dump_format_type;
string lsqp_dump_directory;
int num_eliminate_blocks;
- LoggingType logging_type;
+ int max_num_consecutive_invalid_steps;
+ int min_trust_region_radius;
// List of callbacks that are executed by the Minimizer at the end
// of each iteration.
//
- // Client owns these pointers.
+ // The Options struct does not own these pointers.
vector<IterationCallback*> callbacks;
+
+ // Object responsible for evaluating the cost, residuals and
+ // Jacobian matrix. The Options struct does not own this pointer.
+ Evaluator* evaluator;
+
+ // Object responsible for actually computing the trust region
+ // step, and sizing the trust region radius. The Options struct
+ // does not own this pointer.
+ TrustRegionStrategy* trust_region_strategy;
+
+ // Object holding the Jacobian matrix. It is assumed that the
+ // sparsity structure of the matrix has already been initialized
+ // and will remain constant for the life time of the
+ // optimization. The Options struct does not own this pointer.
+ SparseMatrix* jacobian;
};
virtual ~Minimizer() {}
+
+ // Note: The minimizer is expected to update the state of the
+ // parameters array every iteration. This is required for the
+ // StateUpdatingCallback to work.
virtual void Minimize(const Options& options,
- Evaluator* evaluator,
- LinearSolver* linear_solver,
- const double* initial_parameters,
- double* final_parameters,
+ double* parameters,
Solver::Summary* summary) = 0;
};
diff --git a/extern/libmv/third_party/ceres/internal/ceres/mutex.h b/extern/libmv/third_party/ceres/internal/ceres/mutex.h
index 6514b107041..5090a71b78d 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/mutex.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/mutex.h
@@ -95,11 +95,11 @@
#ifndef CERES_INTERNAL_MUTEX_H_
#define CERES_INTERNAL_MUTEX_H_
-#if defined(NO_THREADS)
+#if defined(CERES_NO_THREADS)
typedef int MutexType; // to keep a lock-count
#elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
-# define WIN32_LEAN_AND_MEAN // We only need minimal includes
-# ifdef GMUTEX_TRYLOCK
+# define CERES_WIN32_LEAN_AND_MEAN // We only need minimal includes
+# ifdef CERES_GMUTEX_TRYLOCK
// We need Windows NT or later for TryEnterCriticalSection(). If you
// don't need that functionality, you can remove these _WIN32_WINNT
// lines, and change TryLock() to assert(0) or something.
@@ -108,9 +108,9 @@
# endif
# endif
// To avoid macro definition of ERROR.
-# define NOGDI
+# define CERES_NOGDI
// To avoid macro definition of min/max.
-# define NOMINMAX
+# define CERES_NOMINMAX
# include <windows.h>
typedef CRITICAL_SECTION MutexType;
#elif defined(CERES_HAVE_PTHREAD) && defined(CERES_HAVE_RWLOCK)
@@ -151,7 +151,7 @@ class Mutex {
inline void Lock(); // Block if needed until free then acquire exclusively
inline void Unlock(); // Release a lock acquired via Lock()
-#ifdef GMUTEX_TRYLOCK
+#ifdef CERES_GMUTEX_TRYLOCK
inline bool TryLock(); // If free, Lock() and return true, else return false
#endif
// Note that on systems that don't support read-write locks, these may
@@ -183,7 +183,7 @@ class Mutex {
};
// Now the implementation of Mutex for various systems
-#if defined(NO_THREADS)
+#if defined(CERES_NO_THREADS)
// When we don't have threads, we can be either reading or writing,
// but not both. We can have lots of readers at once (in no-threads
@@ -199,7 +199,7 @@ Mutex::Mutex() : mutex_(0) { }
Mutex::~Mutex() { assert(mutex_ == 0); }
void Mutex::Lock() { assert(--mutex_ == -1); }
void Mutex::Unlock() { assert(mutex_++ == -1); }
-#ifdef GMUTEX_TRYLOCK
+#ifdef CERES_GMUTEX_TRYLOCK
bool Mutex::TryLock() { if (mutex_) return false; Lock(); return true; }
#endif
void Mutex::ReaderLock() { assert(++mutex_ > 0); }
@@ -220,91 +220,101 @@ void Mutex::ReaderUnlock() { Unlock(); }
#elif defined(CERES_HAVE_PTHREAD) && defined(CERES_HAVE_RWLOCK)
-#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
- if (is_safe_ && fncall(&mutex_) != 0) abort(); \
+#define CERES_SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
+ if (is_safe_ && fncall(&mutex_) != 0) abort(); \
} while (0)
Mutex::Mutex() {
SetIsSafe();
if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
}
-Mutex::~Mutex() { SAFE_PTHREAD(pthread_rwlock_destroy); }
-void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); }
-void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); }
-#ifdef GMUTEX_TRYLOCK
+Mutex::~Mutex() { CERES_SAFE_PTHREAD(pthread_rwlock_destroy); }
+void Mutex::Lock() { CERES_SAFE_PTHREAD(pthread_rwlock_wrlock); }
+void Mutex::Unlock() { CERES_SAFE_PTHREAD(pthread_rwlock_unlock); }
+#ifdef CERES_GMUTEX_TRYLOCK
bool Mutex::TryLock() { return is_safe_ ?
pthread_rwlock_trywrlock(&mutex_) == 0 :
true; }
#endif
-void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); }
-void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); }
-#undef SAFE_PTHREAD
+void Mutex::ReaderLock() { CERES_SAFE_PTHREAD(pthread_rwlock_rdlock); }
+void Mutex::ReaderUnlock() { CERES_SAFE_PTHREAD(pthread_rwlock_unlock); }
+#undef CERES_SAFE_PTHREAD
#elif defined(CERES_HAVE_PTHREAD)
-#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
- if (is_safe_ && fncall(&mutex_) != 0) abort(); \
+#define CERES_SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
+ if (is_safe_ && fncall(&mutex_) != 0) abort(); \
} while (0)
Mutex::Mutex() {
SetIsSafe();
if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
}
-Mutex::~Mutex() { SAFE_PTHREAD(pthread_mutex_destroy); }
-void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock); }
-void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock); }
-#ifdef GMUTEX_TRYLOCK
+Mutex::~Mutex() { CERES_SAFE_PTHREAD(pthread_mutex_destroy); }
+void Mutex::Lock() { CERES_SAFE_PTHREAD(pthread_mutex_lock); }
+void Mutex::Unlock() { CERES_SAFE_PTHREAD(pthread_mutex_unlock); }
+#ifdef CERES_GMUTEX_TRYLOCK
bool Mutex::TryLock() { return is_safe_ ?
pthread_mutex_trylock(&mutex_) == 0 : true; }
#endif
void Mutex::ReaderLock() { Lock(); }
void Mutex::ReaderUnlock() { Unlock(); }
-#undef SAFE_PTHREAD
+#undef CERES_SAFE_PTHREAD
#endif
// --------------------------------------------------------------------------
// Some helper classes
-// MutexLock(mu) acquires mu when constructed and releases it when destroyed.
-class MutexLock {
+// Note: The weird "Ceres" prefix for the class is a workaround for having two
+// similar mutex.h files included in the same translation unit. This is a
+// problem because macros do not respect C++ namespaces, and as a result, this
+// does not work well (e.g. inside Chrome). The offending macros are
+// "MutexLock(x) COMPILE_ASSERT(false)". To work around this, "Ceres" is
+// prefixed to the class names; this permits defining the classes.
+
+// CeresMutexLock(mu) acquires mu when constructed and releases it when destroyed.
+class CeresMutexLock {
public:
- explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); }
- ~MutexLock() { mu_->Unlock(); }
+ explicit CeresMutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); }
+ ~CeresMutexLock() { mu_->Unlock(); }
private:
Mutex * const mu_;
// Disallow "evil" constructors
- MutexLock(const MutexLock&);
- void operator=(const MutexLock&);
+ CeresMutexLock(const CeresMutexLock&);
+ void operator=(const CeresMutexLock&);
};
-// ReaderMutexLock and WriterMutexLock do the same, for rwlocks
-class ReaderMutexLock {
+// CeresReaderMutexLock and CeresWriterMutexLock do the same, for rwlocks
+class CeresReaderMutexLock {
public:
- explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); }
- ~ReaderMutexLock() { mu_->ReaderUnlock(); }
+ explicit CeresReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); }
+ ~CeresReaderMutexLock() { mu_->ReaderUnlock(); }
private:
Mutex * const mu_;
// Disallow "evil" constructors
- ReaderMutexLock(const ReaderMutexLock&);
- void operator=(const ReaderMutexLock&);
+ CeresReaderMutexLock(const CeresReaderMutexLock&);
+ void operator=(const CeresReaderMutexLock&);
};
-class WriterMutexLock {
+class CeresWriterMutexLock {
public:
- explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); }
- ~WriterMutexLock() { mu_->WriterUnlock(); }
+ explicit CeresWriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); }
+ ~CeresWriterMutexLock() { mu_->WriterUnlock(); }
private:
Mutex * const mu_;
// Disallow "evil" constructors
- WriterMutexLock(const WriterMutexLock&);
- void operator=(const WriterMutexLock&);
+ CeresWriterMutexLock(const CeresWriterMutexLock&);
+ void operator=(const CeresWriterMutexLock&);
};
// Catch bug where variable name is omitted, e.g. MutexLock (&mu);
-#define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name)
-#define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name)
-#define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name)
+#define CeresMutexLock(x) \
+ COMPILE_ASSERT(0, ceres_mutex_lock_decl_missing_var_name)
+#define CeresReaderMutexLock(x) \
+ COMPILE_ASSERT(0, ceres_rmutex_lock_decl_missing_var_name)
+#define CeresWriterMutexLock(x) \
+ COMPILE_ASSERT(0, ceres_wmutex_lock_decl_missing_var_name)
} // namespace internal
} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/normal_prior.cc b/extern/libmv/third_party/ceres/internal/ceres/normal_prior.cc
index f30bbc8b46b..392d728fb32 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/normal_prior.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/normal_prior.cc
@@ -32,11 +32,10 @@
#include <cstddef>
#include <vector>
-
-#include <glog/logging.h>
#include "ceres/internal/eigen.h"
#include "ceres/internal/scoped_ptr.h"
#include "ceres/types.h"
+#include "glog/logging.h"
namespace ceres {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/parameter_block.h b/extern/libmv/third_party/ceres/internal/ceres/parameter_block.h
index 4bac1a85828..f20805ca873 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/parameter_block.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/parameter_block.h
@@ -32,13 +32,15 @@
#define CERES_INTERNAL_PARAMETER_BLOCK_H_
#include <cstdlib>
+#include <string>
+#include "ceres/array_utils.h"
#include "ceres/integral_types.h"
-#include <glog/logging.h>
#include "ceres/internal/eigen.h"
#include "ceres/internal/port.h"
#include "ceres/internal/scoped_ptr.h"
#include "ceres/local_parameterization.h"
-#include "ceres/residual_block_utils.h"
+#include "ceres/stringprintf.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -172,6 +174,19 @@ class ParameterBlock {
return local_parameterization_->Plus(x, delta, x_plus_delta);
}
+ string ToString() const {
+ return StringPrintf("{ user_state=%p, state=%p, size=%d, "
+ "constant=%d, index=%d, state_offset=%d, "
+ "delta_offset=%d }",
+ user_state_,
+ state_,
+ size_,
+ is_constant_,
+ index_,
+ state_offset_,
+ delta_offset_);
+ }
+
private:
void Init(double* user_state,
int size,
diff --git a/extern/libmv/third_party/ceres/internal/ceres/partitioned_matrix_view.cc b/extern/libmv/third_party/ceres/internal/ceres/partitioned_matrix_view.cc
index fcf8fd53aed..0722fc82c02 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/partitioned_matrix_view.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/partitioned_matrix_view.cc
@@ -35,10 +35,10 @@
#include <algorithm>
#include <cstring>
#include <vector>
-#include <glog/logging.h>
#include "ceres/block_sparse_matrix.h"
#include "ceres/block_structure.h"
#include "ceres/internal/eigen.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/polynomial_solver.cc b/extern/libmv/third_party/ceres/internal/ceres/polynomial_solver.cc
new file mode 100644
index 00000000000..20c01566a89
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/polynomial_solver.cc
@@ -0,0 +1,184 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: moll.markus@arcor.de (Markus Moll)
+
+#include "ceres/polynomial_solver.h"
+
+#include <cmath>
+#include <cstddef>
+#include "Eigen/Dense"
+#include "ceres/internal/port.h"
+#include "glog/logging.h"
+
+namespace ceres {
+namespace internal {
+namespace {
+
+// Balancing function as described by B. N. Parlett and C. Reinsch,
+// "Balancing a Matrix for Calculation of Eigenvalues and Eigenvectors".
+// In: Numerische Mathematik, Volume 13, Number 4 (1969), 293-304,
+// Springer Berlin / Heidelberg. DOI: 10.1007/BF02165404
+void BalanceCompanionMatrix(Matrix* companion_matrix_ptr) {
+ CHECK_NOTNULL(companion_matrix_ptr);
+ Matrix& companion_matrix = *companion_matrix_ptr;
+ Matrix companion_matrix_offdiagonal = companion_matrix;
+ companion_matrix_offdiagonal.diagonal().setZero();
+
+ const int degree = companion_matrix.rows();
+
+ // gamma <= 1 controls how much a change in the scaling has to
+ // lower the 1-norm of the companion matrix to be accepted.
+ //
+ // gamma = 1 seems to lead to cycles (numerical issues?), so
+ // we set it slightly lower.
+ const double gamma = 0.9;
+
+ // Greedily scale row/column pairs until there is no change.
+ bool scaling_has_changed;
+ do {
+ scaling_has_changed = false;
+
+ for (int i = 0; i < degree; ++i) {
+ const double row_norm = companion_matrix_offdiagonal.row(i).lpNorm<1>();
+ const double col_norm = companion_matrix_offdiagonal.col(i).lpNorm<1>();
+
+ // Decompose row_norm/col_norm into mantissa * 2^exponent,
+ // where 0.5 <= mantissa < 1. Discard mantissa (return value
+ // of frexp), as only the exponent is needed.
+ int exponent = 0;
+ std::frexp(row_norm / col_norm, &exponent);
+ exponent /= 2;
+
+ if (exponent != 0) {
+ const double scaled_col_norm = std::ldexp(col_norm, exponent);
+ const double scaled_row_norm = std::ldexp(row_norm, -exponent);
+ if (scaled_col_norm + scaled_row_norm < gamma * (col_norm + row_norm)) {
+ // Accept the new scaling. (Multiplication by powers of 2 should not
+ // introduce rounding errors (ignoring non-normalized numbers and
+ // over- or underflow))
+ scaling_has_changed = true;
+ companion_matrix_offdiagonal.row(i) *= std::ldexp(1.0, -exponent);
+ companion_matrix_offdiagonal.col(i) *= std::ldexp(1.0, exponent);
+ }
+ }
+ }
+ } while (scaling_has_changed);
+
+ companion_matrix_offdiagonal.diagonal() = companion_matrix.diagonal();
+ companion_matrix = companion_matrix_offdiagonal;
+ VLOG(3) << "Balanced companion matrix is\n" << companion_matrix;
+}
+
+void BuildCompanionMatrix(const Vector& polynomial,
+ Matrix* companion_matrix_ptr) {
+ CHECK_NOTNULL(companion_matrix_ptr);
+ Matrix& companion_matrix = *companion_matrix_ptr;
+
+ const int degree = polynomial.size() - 1;
+
+ companion_matrix.resize(degree, degree);
+ companion_matrix.setZero();
+ companion_matrix.diagonal(-1).setOnes();
+ companion_matrix.col(degree - 1) = -polynomial.reverse().head(degree);
+}
+
+// Remove leading terms with zero coefficients.
+Vector RemoveLeadingZeros(const Vector& polynomial_in) {
+ int i = 0;
+ while (i < (polynomial_in.size() - 1) && polynomial_in(i) == 0.0) {
+ ++i;
+ }
+ return polynomial_in.tail(polynomial_in.size() - i);
+}
+} // namespace
+
+bool FindPolynomialRoots(const Vector& polynomial_in,
+ Vector* real,
+ Vector* imaginary) {
+ if (polynomial_in.size() == 0) {
+ LOG(ERROR) << "Invalid polynomial of size 0 passed to FindPolynomialRoots";
+ return false;
+ }
+
+ Vector polynomial = RemoveLeadingZeros(polynomial_in);
+ const int degree = polynomial.size() - 1;
+
+ // Is the polynomial constant?
+ if (degree == 0) {
+ LOG(WARNING) << "Trying to extract roots from a constant "
+ << "polynomial in FindPolynomialRoots";
+ return true;
+ }
+
+ // Divide by leading term
+ const double leading_term = polynomial(0);
+ polynomial /= leading_term;
+
+ // Separately handle linear polynomials.
+ if (degree == 1) {
+ if (real != NULL) {
+ real->resize(1);
+ (*real)(0) = -polynomial(1);
+ }
+ if (imaginary != NULL) {
+ imaginary->resize(1);
+ imaginary->setZero();
+ }
+ }
+
+ // The degree is now known to be at least 2.
+ // Build and balance the companion matrix to the polynomial.
+ Matrix companion_matrix(degree, degree);
+ BuildCompanionMatrix(polynomial, &companion_matrix);
+ BalanceCompanionMatrix(&companion_matrix);
+
+ // Find its (complex) eigenvalues.
+ Eigen::EigenSolver<Matrix> solver(companion_matrix,
+ Eigen::EigenvaluesOnly);
+ if (solver.info() != Eigen::Success) {
+ LOG(ERROR) << "Failed to extract eigenvalues from companion matrix.";
+ return false;
+ }
+
+ // Output roots
+ if (real != NULL) {
+ *real = solver.eigenvalues().real();
+ } else {
+ LOG(WARNING) << "NULL pointer passed as real argument to "
+ << "FindPolynomialRoots. Real parts of the roots will not "
+ << "be returned.";
+ }
+ if (imaginary != NULL) {
+ *imaginary = solver.eigenvalues().imag();
+ }
+ return true;
+}
+
+} // namespace internal
+} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/polynomial_solver.h b/extern/libmv/third_party/ceres/internal/ceres/polynomial_solver.h
new file mode 100644
index 00000000000..1cf07ddb549
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/polynomial_solver.h
@@ -0,0 +1,65 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: moll.markus@arcor.de (Markus Moll)
+
+#ifndef CERES_INTERNAL_POLYNOMIAL_SOLVER_H_
+#define CERES_INTERNAL_POLYNOMIAL_SOLVER_H_
+
+#include "ceres/internal/eigen.h"
+
+namespace ceres {
+namespace internal {
+
+// Use the companion matrix eigenvalues to determine the roots of the polynomial
+//
+// sum_{i=0}^N polynomial(i) x^{N-i}.
+//
+// This function returns true on success, false otherwise.
+// Failure indicates that the polynomial is invalid (of size 0) or
+// that the eigenvalues of the companion matrix could not be computed.
+// On failure, a more detailed message will be written to LOG(ERROR).
+// If real is not NULL, the real parts of the roots will be returned in it.
+// Likewise, if imaginary is not NULL, imaginary parts will be returned in it.
+bool FindPolynomialRoots(const Vector& polynomial,
+ Vector* real,
+ Vector* imaginary);
+
+// Evaluate the polynomial at x using the Horner scheme.
+inline double EvaluatePolynomial(const Vector& polynomial, double x) {
+ double v = 0.0;
+ for (int i = 0; i < polynomial.size(); ++i) {
+ v = v * x + polynomial(i);
+ }
+ return v;
+}
+
+} // namespace internal
+} // namespace ceres
+
+#endif // CERES_INTERNAL_POLYNOMIAL_SOLVER_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/problem_impl.cc b/extern/libmv/third_party/ceres/internal/ceres/problem_impl.cc
index 68242477d6f..c186f527be8 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/problem_impl.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/problem_impl.cc
@@ -37,16 +37,15 @@
#include <string>
#include <utility>
#include <vector>
-
-#include <glog/logging.h>
+#include "ceres/cost_function.h"
+#include "ceres/loss_function.h"
+#include "ceres/map_util.h"
#include "ceres/parameter_block.h"
#include "ceres/program.h"
#include "ceres/residual_block.h"
#include "ceres/stl_util.h"
-#include "ceres/map_util.h"
#include "ceres/stringprintf.h"
-#include "ceres/cost_function.h"
-#include "ceres/loss_function.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/problem_impl.h b/extern/libmv/third_party/ceres/internal/ceres/problem_impl.h
index 523860e652a..2ca055448c3 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/problem_impl.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/problem_impl.h
@@ -118,7 +118,7 @@ class ProblemImpl {
map<double*, ParameterBlock*> parameter_block_map_;
internal::scoped_ptr<internal::Program> program_;
- DISALLOW_COPY_AND_ASSIGN(ProblemImpl);
+ CERES_DISALLOW_COPY_AND_ASSIGN(ProblemImpl);
};
} // namespace internal
diff --git a/extern/libmv/third_party/ceres/internal/ceres/program.cc b/extern/libmv/third_party/ceres/internal/ceres/program.cc
index 444b1020253..82d76d39233 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/program.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/program.cc
@@ -32,14 +32,18 @@
#include <map>
#include <vector>
+#include "ceres/casts.h"
+#include "ceres/compressed_row_sparse_matrix.h"
+#include "ceres/cost_function.h"
+#include "ceres/evaluator.h"
+#include "ceres/internal/port.h"
+#include "ceres/local_parameterization.h"
+#include "ceres/loss_function.h"
+#include "ceres/map_util.h"
#include "ceres/parameter_block.h"
+#include "ceres/problem.h"
#include "ceres/residual_block.h"
#include "ceres/stl_util.h"
-#include "ceres/map_util.h"
-#include "ceres/problem.h"
-#include "ceres/cost_function.h"
-#include "ceres/loss_function.h"
-#include "ceres/local_parameterization.h"
namespace ceres {
namespace internal {
@@ -69,7 +73,8 @@ vector<ResidualBlock*>* Program::mutable_residual_blocks() {
bool Program::StateVectorToParameterBlocks(const double *state) {
for (int i = 0; i < parameter_blocks_.size(); ++i) {
- if (!parameter_blocks_[i]->SetState(state)) {
+ if (!parameter_blocks_[i]->IsConstant() &&
+ !parameter_blocks_[i]->SetState(state)) {
return false;
}
state += parameter_blocks_[i]->Size();
@@ -86,9 +91,18 @@ void Program::ParameterBlocksToStateVector(double *state) const {
void Program::CopyParameterBlockStateToUserState() {
for (int i = 0; i < parameter_blocks_.size(); ++i) {
- parameter_blocks_[i]->GetState(
- parameter_blocks_[i]->mutable_user_state());
+ parameter_blocks_[i]->GetState(parameter_blocks_[i]->mutable_user_state());
+ }
+}
+
+bool Program::SetParameterBlockStatePtrsToUserStatePtrs() {
+ for (int i = 0; i < parameter_blocks_.size(); ++i) {
+ if (!parameter_blocks_[i]->IsConstant() &&
+ !parameter_blocks_[i]->SetState(parameter_blocks_[i]->user_state())) {
+ return false;
+ }
}
+ return true;
}
bool Program::Plus(const double* state,
@@ -193,40 +207,25 @@ int Program::MaxParametersPerResidualBlock() const {
return max_parameters;
}
-bool Program::Evaluate(double* cost, double* residuals) {
- *cost = 0.0;
-
- // Scratch space is only needed if residuals is NULL.
- scoped_array<double> scratch;
- if (residuals == NULL) {
- scratch.reset(new double[MaxScratchDoublesNeededForEvaluate()]);
- } else {
- // TODO(keir): Is this needed? Check by removing the equivalent statement in
- // dense_evaluator.cc and running the tests.
- VectorRef(residuals, NumResiduals()).setZero();
- }
-
+int Program::MaxResidualsPerResidualBlock() const {
+ int max_residuals = 0;
for (int i = 0; i < residual_blocks_.size(); ++i) {
- ResidualBlock* residual_block = residual_blocks_[i];
-
- // Evaluate the cost function for this residual.
- double residual_cost;
- if (!residual_block->Evaluate(&residual_cost,
- residuals,
- NULL, // No jacobian.
- scratch.get())) {
- return false;
- }
-
- // Accumulate residual cost into the total cost.
- *cost += residual_cost;
+ max_residuals = max(max_residuals,
+ residual_blocks_[i]->NumResiduals());
+ }
+ return max_residuals;
+}
- // Update the residuals cursor.
- if (residuals != NULL) {
- residuals += residual_block->NumResiduals();
- }
+string Program::ToString() const {
+ string ret = "Program dump\n";
+ ret += StringPrintf("Number of parameter blocks: %d\n", NumParameterBlocks());
+ ret += StringPrintf("Number of parameters: %d\n", NumParameters());
+ ret += "Parameters:\n";
+ for (int i = 0; i < parameter_blocks_.size(); ++i) {
+ ret += StringPrintf("%d: %s\n",
+ i, parameter_blocks_[i]->ToString().c_str());
}
- return true;
+ return ret;
}
} // namespace internal
diff --git a/extern/libmv/third_party/ceres/internal/ceres/program.h b/extern/libmv/third_party/ceres/internal/ceres/program.h
index 113d352d562..5002b7e752e 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/program.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/program.h
@@ -31,6 +31,7 @@
#ifndef CERES_INTERNAL_PROGRAM_H_
#define CERES_INTERNAL_PROGRAM_H_
+#include <string>
#include <vector>
#include "ceres/internal/port.h"
@@ -71,9 +72,14 @@ class Program {
bool StateVectorToParameterBlocks(const double *state);
void ParameterBlocksToStateVector(double *state) const;
- // Copy internal state out to the user's parameters.
+ // Copy internal state to the user's parameters.
void CopyParameterBlockStateToUserState();
+ // Set the parameter block pointers to the user pointers. Since this
+ // runs parameter block set state internally, which may call local
+ // parameterizations, this can fail. False is returned on failure.
+ bool SetParameterBlockStatePtrsToUserStatePtrs();
+
// Update a state vector for the program given a delta.
bool Plus(const double* state,
const double* delta,
@@ -103,16 +109,11 @@ class Program {
int MaxScratchDoublesNeededForEvaluate() const;
int MaxDerivativesPerResidualBlock() const;
int MaxParametersPerResidualBlock() const;
+ int MaxResidualsPerResidualBlock() const;
- // Evaluate the cost and maybe the residuals for the program. If residuals is
- // NULL, then residuals are not calculated. If the jacobian is needed, instead
- // use the various evaluators (e.g. dense_evaluator.h).
- //
- // This is a trivial implementation of evaluate not intended for use in the
- // core solving loop. The other evaluators, which support constructing the
- // jacobian in addition to the cost and residuals, are considerably
- // complicated by the need to construct the jacobian.
- bool Evaluate(double* cost, double* residuals);
+ // A human-readable dump of the parameter blocks for debugging.
+ // TODO(keir): If necessary, also dump the residual blocks.
+ string ToString() const;
private:
// The Program does not own the ParameterBlock or ResidualBlock objects.
diff --git a/extern/libmv/third_party/ceres/internal/ceres/program_evaluator.h b/extern/libmv/third_party/ceres/internal/ceres/program_evaluator.h
index 7ec74b1b269..6c48e7d7643 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/program_evaluator.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/program_evaluator.h
@@ -120,13 +120,18 @@ class ProgramEvaluator : public Evaluator {
bool Evaluate(const double* state,
double* cost,
double* residuals,
+ double* gradient,
SparseMatrix* jacobian) {
// The parameters are stateful, so set the state before evaluating.
if (!program_->StateVectorToParameterBlocks(state)) {
return false;
}
- if (jacobian) {
+ if (residuals != NULL) {
+ VectorRef(residuals, program_->NumResiduals()).setZero();
+ }
+
+ if (jacobian != NULL) {
jacobian->SetZero();
}
@@ -158,13 +163,16 @@ class ProgramEvaluator : public Evaluator {
// Prepare block residuals if requested.
const ResidualBlock* residual_block = program_->residual_blocks()[i];
- double* block_residuals = (residuals != NULL)
- ? (residuals + residual_layout_[i])
- : NULL;
+ double* block_residuals = NULL;
+ if (residuals != NULL) {
+ block_residuals = residuals + residual_layout_[i];
+ } else if (gradient != NULL) {
+ block_residuals = scratch->residual_block_residuals.get();
+ }
// Prepare block jacobians if requested.
double** block_jacobians = NULL;
- if (jacobian != NULL) {
+ if (jacobian != NULL || gradient != NULL) {
preparer->Prepare(residual_block,
i,
jacobian,
@@ -174,10 +182,11 @@ class ProgramEvaluator : public Evaluator {
// Evaluate the cost, residuals, and jacobians.
double block_cost;
- if (!residual_block->Evaluate(&block_cost,
- block_residuals,
- block_jacobians,
- scratch->scratch.get())) {
+ if (!residual_block->Evaluate(
+ &block_cost,
+ block_residuals,
+ block_jacobians,
+ scratch->residual_block_evaluate_scratch.get())) {
abort = true;
// This ensures that the OpenMP threads have a consistent view of 'abort'. Do
// the flush inside the failure case so that there is usually only one
@@ -188,19 +197,49 @@ class ProgramEvaluator : public Evaluator {
scratch->cost += block_cost;
+ // Store the jacobians, if they were requested.
if (jacobian != NULL) {
jacobian_writer_.Write(i,
residual_layout_[i],
block_jacobians,
jacobian);
}
+
+ // Compute and store the gradient, if it was requested.
+ if (gradient != NULL) {
+ int num_residuals = residual_block->NumResiduals();
+ int num_parameter_blocks = residual_block->NumParameterBlocks();
+ for (int j = 0; j < num_parameter_blocks; ++j) {
+ const ParameterBlock* parameter_block =
+ residual_block->parameter_blocks()[j];
+ if (parameter_block->IsConstant()) {
+ continue;
+ }
+ MatrixRef block_jacobian(block_jacobians[j],
+ num_residuals,
+ parameter_block->LocalSize());
+ VectorRef block_gradient(scratch->gradient.get() +
+ parameter_block->delta_offset(),
+ parameter_block->LocalSize());
+ VectorRef block_residual(block_residuals, num_residuals);
+ block_gradient += block_residual.transpose() * block_jacobian;
+ }
+ }
}
if (!abort) {
- // Sum the cost from each thread.
+ // Sum the cost and gradient (if requested) from each thread.
(*cost) = 0.0;
+ int num_parameters = program_->NumEffectiveParameters();
+ if (gradient != NULL) {
+ VectorRef(gradient, num_parameters).setZero();
+ }
for (int i = 0; i < options_.num_threads; ++i) {
(*cost) += evaluate_scratch_[i].cost;
+ if (gradient != NULL) {
+ VectorRef(gradient, num_parameters) +=
+ VectorRef(evaluate_scratch_[i].gradient.get(), num_parameters);
+ }
}
}
return !abort;
@@ -224,16 +263,28 @@ class ProgramEvaluator : public Evaluator {
}
private:
+ // Per-thread scratch space needed to evaluate and store each residual block.
struct EvaluateScratch {
void Init(int max_parameters_per_residual_block,
- int max_scratch_doubles_needed_for_evaluate) {
+ int max_scratch_doubles_needed_for_evaluate,
+ int max_residuals_per_residual_block,
+ int num_parameters) {
+ residual_block_evaluate_scratch.reset(
+ new double[max_scratch_doubles_needed_for_evaluate]);
+ gradient.reset(new double[num_parameters]);
+ VectorRef(gradient.get(), num_parameters).setZero();
+ residual_block_residuals.reset(
+ new double[max_residuals_per_residual_block]);
jacobian_block_ptrs.reset(
new double*[max_parameters_per_residual_block]);
- scratch.reset(new double[max_scratch_doubles_needed_for_evaluate]);
}
double cost;
- scoped_array<double> scratch;
+ scoped_array<double> residual_block_evaluate_scratch;
+ // The gradient in the local parameterization.
+ scoped_array<double> gradient;
+ // Enough space to store the residual for the largest residual block.
+ scoped_array<double> residual_block_residuals;
scoped_array<double*> jacobian_block_ptrs;
};
@@ -256,11 +307,16 @@ class ProgramEvaluator : public Evaluator {
program.MaxParametersPerResidualBlock();
int max_scratch_doubles_needed_for_evaluate =
program.MaxScratchDoublesNeededForEvaluate();
+ int max_residuals_per_residual_block =
+ program.MaxResidualsPerResidualBlock();
+ int num_parameters = program.NumEffectiveParameters();
EvaluateScratch* evaluate_scratch = new EvaluateScratch[num_threads];
for (int i = 0; i < num_threads; i++) {
evaluate_scratch[i].Init(max_parameters_per_residual_block,
- max_scratch_doubles_needed_for_evaluate);
+ max_scratch_doubles_needed_for_evaluate,
+ max_residuals_per_residual_block,
+ num_parameters);
}
return evaluate_scratch;
}
diff --git a/extern/libmv/third_party/ceres/internal/ceres/random.h b/extern/libmv/third_party/ceres/internal/ceres/random.h
index 769e0b4dd27..352c0032b5a 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/random.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/random.h
@@ -27,21 +27,44 @@
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: keir@google.com (Keir Mierle)
+// sameeragarwal@google.com (Sameer Agarwal)
#ifndef CERES_INTERNAL_RANDOM_H_
#define CERES_INTERNAL_RANDOM_H_
+#include <cmath>
+#include <cstdlib>
+#include "ceres/internal/port.h"
+
namespace ceres {
-inline double RandDouble() {
- double r = rand();
- return r / RAND_MAX;
+inline void SetRandomState(int state) {
+ srand(state);
}
inline int Uniform(int n) {
return rand() % n;
}
+inline double RandDouble() {
+ double r = static_cast<double>(rand());
+ return r / RAND_MAX;
+}
+
+// Box-Muller algorithm for normal random number generation.
+// http://en.wikipedia.org/wiki/Box-Muller_transform
+inline double RandNormal() {
+ double x1, x2, w;
+ do {
+ x1 = 2.0 * RandDouble() - 1.0;
+ x2 = 2.0 * RandDouble() - 1.0;
+ w = x1 * x1 + x2 * x2;
+ } while ( w >= 1.0 || w == 0.0 );
+
+ w = sqrt((-2.0 * log(w)) / w);
+ return x1 * w;
+}
+
} // namespace ceres
#endif // CERES_INTERNAL_RANDOM_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/residual_block.cc b/extern/libmv/third_party/ceres/internal/ceres/residual_block.cc
index 03867891dba..bdb88b1dd97 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/residual_block.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/residual_block.cc
@@ -102,8 +102,11 @@ bool ResidualBlock::Evaluate(double* cost,
InvalidateEvaluation(*this, cost, residuals, eval_jacobians);
- if (!cost_function_->Evaluate(parameters.get(), residuals, eval_jacobians) ||
- !IsEvaluationValid(*this,
+ if (!cost_function_->Evaluate(parameters.get(), residuals, eval_jacobians)) {
+ return false;
+ }
+
+ if (!IsEvaluationValid(*this,
parameters.get(),
cost,
residuals,
diff --git a/extern/libmv/third_party/ceres/internal/ceres/residual_block_utils.cc b/extern/libmv/third_party/ceres/internal/ceres/residual_block_utils.cc
index 28e03130844..9442bb2a1c1 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/residual_block_utils.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/residual_block_utils.cc
@@ -33,46 +33,17 @@
#include <cmath>
#include <cstddef>
#include <limits>
-#include <glog/logging.h>
-#include "ceres/residual_block.h"
-#include "ceres/parameter_block.h"
-#include "ceres/stringprintf.h"
+#include "ceres/array_utils.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/port.h"
-
-#ifdef _MSC_VER
-# define isfinite _finite
-#endif
+#include "ceres/parameter_block.h"
+#include "ceres/residual_block.h"
+#include "ceres/stringprintf.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
-// It is a near impossibility that user code generates this exact
-// value in normal operation, thus we will use it to fill arrays
-// before passing them to user code. If on return an element of the
-// array still contains this value, we will assume that the user code
-// did not write to that memory location.
-static const double kImpossibleValue = 1e302;
-
-bool IsArrayValid(const int size, const double* x) {
- if (x != NULL) {
- for (int i = 0; i < size; ++i) {
- if (!isfinite(x[i]) || (x[i] == kImpossibleValue)) {
- return false;
- }
- }
- }
- return true;
-}
-
-void InvalidateArray(const int size, double* x) {
- if (x != NULL) {
- for (int i = 0; i < size; ++i) {
- x[i] = kImpossibleValue;
- }
- }
-}
-
void InvalidateEvaluation(const ResidualBlock& block,
double* cost,
double* residuals,
@@ -92,7 +63,7 @@ void InvalidateEvaluation(const ResidualBlock& block,
// Utility routine to print an array of doubles to a string. If the
// array pointer is NULL, it is treated as an array of zeros.
-void AppendArrayToString(const int size, const double* x, string* result) {
+static void AppendArrayToString(const int size, const double* x, string* result) {
for (int i = 0; i < size; ++i) {
if (x == NULL) {
StringAppendF(result, "Not Computed ");
diff --git a/extern/libmv/third_party/ceres/internal/ceres/residual_block_utils.h b/extern/libmv/third_party/ceres/internal/ceres/residual_block_utils.h
index 228867cc60c..7051c2112fd 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/residual_block_utils.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/residual_block_utils.h
@@ -51,15 +51,6 @@ namespace internal {
class ResidualBlock;
-// Fill the array x with an impossible value that the user code is
-// never expected to compute.
-void InvalidateArray(int size, double* x);
-
-// Check if all the entries of the array x are valid, i.e. all the
-// values in the array should be finite and none of them should be
-// equal to the "impossible" value used by InvalidateArray.
-bool IsArrayValid(int size, const double* x);
-
// Invalidate cost, resdual and jacobian arrays (if not NULL).
void InvalidateEvaluation(const ResidualBlock& block,
double* cost,
diff --git a/extern/libmv/third_party/ceres/internal/ceres/runtime_numeric_diff_cost_function.cc b/extern/libmv/third_party/ceres/internal/ceres/runtime_numeric_diff_cost_function.cc
index ac6d8aa279a..7af275c1dd8 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/runtime_numeric_diff_cost_function.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/runtime_numeric_diff_cost_function.cc
@@ -35,11 +35,10 @@
#include <algorithm>
#include <numeric>
#include <vector>
-
-#include <glog/logging.h>
#include "Eigen/Dense"
#include "ceres/cost_function.h"
#include "ceres/internal/scoped_ptr.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/schur_complement_solver.cc b/extern/libmv/third_party/ceres/internal/ceres/schur_complement_solver.cc
index 2bc8cdd6bec..2cbe78d133a 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/schur_complement_solver.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/schur_complement_solver.cc
@@ -32,7 +32,13 @@
#include <ctime>
#include <set>
#include <vector>
+
+#ifndef CERES_NO_CXSPARSE
+#include "cs.h"
+#endif // CERES_NO_CXSPARSE
+
#include "Eigen/Dense"
+#include "glog/logging.h"
#include "ceres/block_random_access_dense_matrix.h"
#include "ceres/block_random_access_matrix.h"
#include "ceres/block_random_access_sparse_matrix.h"
@@ -48,6 +54,7 @@
#include "ceres/internal/scoped_ptr.h"
#include "ceres/types.h"
+
namespace ceres {
namespace internal {
@@ -57,7 +64,7 @@ LinearSolver::Summary SchurComplementSolver::SolveImpl(
const LinearSolver::PerSolveOptions& per_solve_options,
double* x) {
const time_t start_time = time(NULL);
- if (!options_.constant_sparsity || (eliminator_.get() == NULL)) {
+ if (eliminator_.get() == NULL) {
InitStorage(A->block_structure());
DetectStructure(*A->block_structure(),
options_.num_eliminate_blocks,
@@ -88,11 +95,11 @@ LinearSolver::Summary SchurComplementSolver::SolveImpl(
const time_t backsubstitute_time = time(NULL);
summary.termination_type = TOLERANCE;
- VLOG(2) << "time (sec) total: " << backsubstitute_time - start_time
- << " init: " << init_time - start_time
- << " eliminate: " << eliminate_time - init_time
- << " solve: " << solve_time - eliminate_time
- << " backsubstitute: " << backsubstitute_time - solve_time;
+ VLOG(2) << "time (sec) total: " << (backsubstitute_time - start_time)
+ << " init: " << (init_time - start_time)
+ << " eliminate: " << (eliminate_time - init_time)
+ << " solve: " << (solve_time - eliminate_time)
+ << " backsubstitute: " << (backsubstitute_time - solve_time);
return summary;
}
@@ -139,18 +146,33 @@ bool DenseSchurComplementSolver::SolveReducedLinearSystem(double* solution) {
return true;
}
-#ifndef CERES_NO_SUITESPARSE
+
SparseSchurComplementSolver::SparseSchurComplementSolver(
const LinearSolver::Options& options)
- : SchurComplementSolver(options),
- symbolic_factor_(NULL) {
+ : SchurComplementSolver(options) {
+#ifndef CERES_NO_SUITESPARSE
+ factor_ = NULL;
+#endif // CERES_NO_SUITESPARSE
+
+#ifndef CERES_NO_CXSPARSE
+ cxsparse_factor_ = NULL;
+#endif // CERES_NO_CXSPARSE
}
SparseSchurComplementSolver::~SparseSchurComplementSolver() {
- if (symbolic_factor_ != NULL) {
- ss_.Free(symbolic_factor_);
- symbolic_factor_ = NULL;
+#ifndef CERES_NO_SUITESPARSE
+ if (factor_ != NULL) {
+ ss_.Free(factor_);
+ factor_ = NULL;
}
+#endif // CERES_NO_SUITESPARSE
+
+#ifndef CERES_NO_CXSPARSE
+ if (cxsparse_factor_ != NULL) {
+ cxsparse_.Free(cxsparse_factor_);
+ cxsparse_factor_ = NULL;
+ }
+#endif // CERES_NO_CXSPARSE
}
// Determine the non-zero blocks in the Schur Complement matrix, and
@@ -161,13 +183,13 @@ void SparseSchurComplementSolver::InitStorage(
const int num_col_blocks = bs->cols.size();
const int num_row_blocks = bs->rows.size();
- vector<int> blocks(num_col_blocks - num_eliminate_blocks, 0);
+ blocks_.resize(num_col_blocks - num_eliminate_blocks, 0);
for (int i = num_eliminate_blocks; i < num_col_blocks; ++i) {
- blocks[i - num_eliminate_blocks] = bs->cols[i].size;
+ blocks_[i - num_eliminate_blocks] = bs->cols[i].size;
}
set<pair<int, int> > block_pairs;
- for (int i = 0; i < blocks.size(); ++i) {
+ for (int i = 0; i < blocks_.size(); ++i) {
block_pairs.insert(make_pair(i, i));
}
@@ -220,15 +242,34 @@ void SparseSchurComplementSolver::InitStorage(
}
}
- set_lhs(new BlockRandomAccessSparseMatrix(blocks, block_pairs));
+ set_lhs(new BlockRandomAccessSparseMatrix(blocks_, block_pairs));
set_rhs(new double[lhs()->num_rows()]);
}
+bool SparseSchurComplementSolver::SolveReducedLinearSystem(double* solution) {
+ switch (options().sparse_linear_algebra_library) {
+ case SUITE_SPARSE:
+ return SolveReducedLinearSystemUsingSuiteSparse(solution);
+ case CX_SPARSE:
+ return SolveReducedLinearSystemUsingCXSparse(solution);
+ default:
+ LOG(FATAL) << "Unknown sparse linear algebra library : "
+ << options().sparse_linear_algebra_library;
+ }
+
+ LOG(FATAL) << "Unknown sparse linear algebra library : "
+ << options().sparse_linear_algebra_library;
+ return false;
+}
+
+#ifndef CERES_NO_SUITESPARSE
// Solve the system Sx = r, assuming that the matrix S is stored in a
// BlockRandomAccessSparseMatrix. The linear system is solved using
// CHOLMOD's sparse cholesky factorization routines.
-bool SparseSchurComplementSolver::SolveReducedLinearSystem(double* solution) {
- // Extract the TripletSparseMatrix that is used for actually storing S.
+bool SparseSchurComplementSolver::SolveReducedLinearSystemUsingSuiteSparse(
+ double* solution) {
+ const time_t start_time = time(NULL);
+
TripletSparseMatrix* tsm =
const_cast<TripletSparseMatrix*>(
down_cast<const BlockRandomAccessSparseMatrix*>(lhs())->matrix());
@@ -245,30 +286,38 @@ bool SparseSchurComplementSolver::SolveReducedLinearSystem(double* solution) {
// The matrix is symmetric, and the upper triangular part of the
// matrix contains the values.
cholmod_lhs->stype = 1;
+ const time_t lhs_time = time(NULL);
cholmod_dense* cholmod_rhs =
ss_.CreateDenseVector(const_cast<double*>(rhs()), num_rows, num_rows);
+ const time_t rhs_time = time(NULL);
// Symbolic factorization is computed if we don't already have one handy.
- if (symbolic_factor_ == NULL) {
- symbolic_factor_ = ss_.AnalyzeCholesky(cholmod_lhs);
+ if (factor_ == NULL) {
+ if (options().use_block_amd) {
+ factor_ = ss_.BlockAnalyzeCholesky(cholmod_lhs, blocks_, blocks_);
+ } else {
+ factor_ = ss_.AnalyzeCholesky(cholmod_lhs);
+ }
+
+ if (VLOG_IS_ON(2)) {
+ cholmod_print_common("Symbolic Analysis", ss_.mutable_cc());
+ }
}
+ CHECK_NOTNULL(factor_);
+
+ const time_t symbolic_time = time(NULL);
cholmod_dense* cholmod_solution =
- ss_.SolveCholesky(cholmod_lhs, symbolic_factor_, cholmod_rhs);
+ ss_.SolveCholesky(cholmod_lhs, factor_, cholmod_rhs);
+
+ const time_t solve_time = time(NULL);
ss_.Free(cholmod_lhs);
cholmod_lhs = NULL;
ss_.Free(cholmod_rhs);
cholmod_rhs = NULL;
- // If sparsity is not constant across calls, then reset the symbolic
- // factorization.
- if (!options().constant_sparsity) {
- ss_.Free(symbolic_factor_);
- symbolic_factor_ = NULL;
- }
-
if (cholmod_solution == NULL) {
LOG(ERROR) << "CHOLMOD solve failed.";
return false;
@@ -277,9 +326,63 @@ bool SparseSchurComplementSolver::SolveReducedLinearSystem(double* solution) {
VectorRef(solution, num_rows)
= VectorRef(static_cast<double*>(cholmod_solution->x), num_rows);
ss_.Free(cholmod_solution);
+ const time_t final_time = time(NULL);
+ VLOG(2) << "time: " << (final_time - start_time)
+ << " lhs : " << (lhs_time - start_time)
+ << " rhs: " << (rhs_time - lhs_time)
+ << " analyze: " << (symbolic_time - rhs_time)
+ << " factor_and_solve: " << (solve_time - symbolic_time)
+ << " cleanup: " << (final_time - solve_time);
return true;
}
+#else
+bool SparseSchurComplementSolver::SolveReducedLinearSystemUsingSuiteSparse(
+ double* solution) {
+ LOG(FATAL) << "No SuiteSparse support in Ceres.";
+ return false;
+}
#endif // CERES_NO_SUITESPARSE
+#ifndef CERES_NO_CXSPARSE
+// Solve the system Sx = r, assuming that the matrix S is stored in a
+// BlockRandomAccessSparseMatrix. The linear system is solved using
+// CXSparse's sparse cholesky factorization routines.
+bool SparseSchurComplementSolver::SolveReducedLinearSystemUsingCXSparse(
+ double* solution) {
+ // Extract the TripletSparseMatrix that is used for actually storing S.
+ TripletSparseMatrix* tsm =
+ const_cast<TripletSparseMatrix*>(
+ down_cast<const BlockRandomAccessSparseMatrix*>(lhs())->matrix());
+
+ const int num_rows = tsm->num_rows();
+
+ // The case where there are no f blocks, and the system is block
+ // diagonal.
+ if (num_rows == 0) {
+ return true;
+ }
+
+ cs_di* lhs = CHECK_NOTNULL(cxsparse_.CreateSparseMatrix(tsm));
+ VectorRef(solution, num_rows) = ConstVectorRef(rhs(), num_rows);
+
+ // Compute symbolic factorization if not available.
+ if (cxsparse_factor_ == NULL) {
+ cxsparse_factor_ = CHECK_NOTNULL(cxsparse_.AnalyzeCholesky(lhs));
+ }
+
+ // Solve the linear system.
+ bool ok = cxsparse_.SolveCholesky(lhs, cxsparse_factor_, solution);
+
+ cxsparse_.Free(lhs);
+ return ok;
+}
+#else
+bool SparseSchurComplementSolver::SolveReducedLinearSystemUsingCXSparse(
+ double* solution) {
+ LOG(FATAL) << "No CXSparse support in Ceres.";
+ return false;
+}
+#endif // CERES_NO_CXPARSE
+
} // namespace internal
} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/schur_complement_solver.h b/extern/libmv/third_party/ceres/internal/ceres/schur_complement_solver.h
index 039bc09e3ce..ea1b3184c33 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/schur_complement_solver.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/schur_complement_solver.h
@@ -31,9 +31,13 @@
#ifndef CERES_INTERNAL_SCHUR_COMPLEMENT_SOLVER_H_
#define CERES_INTERNAL_SCHUR_COMPLEMENT_SOLVER_H_
+#include <set>
+#include <utility>
+
#include "ceres/block_random_access_matrix.h"
#include "ceres/block_sparse_matrix.h"
#include "ceres/block_structure.h"
+#include "ceres/cxsparse.h"
#include "ceres/linear_solver.h"
#include "ceres/schur_eliminator.h"
#include "ceres/suitesparse.h"
@@ -128,7 +132,7 @@ class SchurComplementSolver : public BlockSparseMatrixBaseSolver {
scoped_ptr<BlockRandomAccessMatrix> lhs_;
scoped_array<double> rhs_;
- DISALLOW_COPY_AND_ASSIGN(SchurComplementSolver);
+ CERES_DISALLOW_COPY_AND_ASSIGN(SchurComplementSolver);
};
// Dense Cholesky factorization based solver.
@@ -142,10 +146,10 @@ class DenseSchurComplementSolver : public SchurComplementSolver {
virtual void InitStorage(const CompressedRowBlockStructure* bs);
virtual bool SolveReducedLinearSystem(double* solution);
- DISALLOW_COPY_AND_ASSIGN(DenseSchurComplementSolver);
+ CERES_DISALLOW_COPY_AND_ASSIGN(DenseSchurComplementSolver);
};
-#ifndef CERES_NO_SUITESPARSE
+
// Sparse Cholesky factorization based solver.
class SparseSchurComplementSolver : public SchurComplementSolver {
public:
@@ -155,26 +159,26 @@ class SparseSchurComplementSolver : public SchurComplementSolver {
private:
virtual void InitStorage(const CompressedRowBlockStructure* bs);
virtual bool SolveReducedLinearSystem(double* solution);
+ bool SolveReducedLinearSystemUsingSuiteSparse(double* solution);
+ bool SolveReducedLinearSystemUsingCXSparse(double* solution);
+ // Size of the blocks in the Schur complement.
+ vector<int> blocks_;
+#ifndef CERES_NO_SUITESPARSE
SuiteSparse ss_;
// Symbolic factorization of the reduced linear system. Precomputed
- // once and reused if constant_sparsity_ is true.
- cholmod_factor* symbolic_factor_;
- DISALLOW_COPY_AND_ASSIGN(SparseSchurComplementSolver);
-};
-#else // CERES_NO_SUITESPARSE
-class SparseSchurComplementSolver : public SchurComplementSolver {
- public:
- explicit SparseSchurComplementSolver(const LinearSolver::Options& options)
- : SchurComplementSolver(options) {
- LOG(FATAL) << "SPARSE_SCHUR is not available. Please "
- "build Ceres with SuiteSparse.";
- }
+ // once and reused in subsequent calls.
+ cholmod_factor* factor_;
+#endif // CERES_NO_SUITESPARSE
- virtual ~SparseSchurComplementSolver() {}
+#ifndef CERES_NO_CXSPARSE
+ CXSparse cxsparse_;
+ // Cached factorization
+ cs_dis* cxsparse_factor_;
+#endif // CERES_NO_CXSPARSE
+ CERES_DISALLOW_COPY_AND_ASSIGN(SparseSchurComplementSolver);
};
-#endif // CERES_NO_SUITESPARSE
} // namespace internal
} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/schur_eliminator_impl.h b/extern/libmv/third_party/ceres/internal/ceres/schur_eliminator_impl.h
index a388d005424..6120db9b009 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/schur_eliminator_impl.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/schur_eliminator_impl.h
@@ -188,7 +188,7 @@ Eliminate(const BlockSparseMatrixBase* A,
typename EigenTypes<kFBlockSize>::ConstVectorRef
diag(D + bs->cols[i].position, block_size);
- MutexLock l(&cell_info->m);
+ CeresMutexLock l(&cell_info->m);
MatrixRef m(cell_info->values, row_stride, col_stride);
m.block(r, c, block_size, block_size).diagonal()
+= diag.array().square().matrix();
@@ -387,7 +387,7 @@ UpdateRhs(const Chunk& chunk,
row.block.size, block_size);
const int block = block_id - num_eliminate_blocks_;
- MutexLock l(rhs_locks_[block]);
+ CeresMutexLock l(rhs_locks_[block]);
typename EigenTypes<kFBlockSize>::VectorRef
(rhs + lhs_row_layout_[block], block_size).noalias()
+= b.transpose() * sj;
@@ -523,7 +523,7 @@ ChunkOuterProduct(const CompressedRowBlockStructure* bs,
const typename EigenTypes<kEBlockSize, kFBlockSize>::ConstMatrixRef
b2(buffer + it2->second, e_block_size, block2_size);
- MutexLock l(&cell_info->m);
+ CeresMutexLock l(&cell_info->m);
MatrixRef m(cell_info->values, row_stride, col_stride);
// We explicitly construct a block object here instead of using
@@ -532,7 +532,29 @@ ChunkOuterProduct(const CompressedRowBlockStructure* bs,
// like the Matrix class does.
Eigen::Block<MatrixRef, kFBlockSize, kFBlockSize>
block(m, r, c, block1_size, block2_size);
- block.noalias() -= b1_transpose_inverse_ete * b2;
+#ifdef CERES_WORK_AROUND_ANDROID_NDK_COMPILER_BUG
+ // Removing the ".noalias()" annotation on the following statement is
+ // necessary to produce a correct build with the Android NDK, including
+ // versions 6, 7, 8, and 8b, when built with STLPort and the
+ // non-standalone toolchain (i.e. ndk-build). This appears to be a
+ // compiler bug; if the workaround is not in place, the line
+ //
+ // block.noalias() -= b1_transpose_inverse_ete * b2;
+ //
+ // gets compiled to
+ //
+ // block.noalias() += b1_transpose_inverse_ete * b2;
+ //
+ // which breaks schur elimination. Introducing a temporary by removing the
+ // .noalias() annotation causes the issue to disappear. Tracking this
+ // issue down was tricky, since the test suite doesn't run when built with
+ // the non-standalone toolchain.
+ //
+ // TODO(keir): Make a reproduction case for this and send it upstream.
+ block -= b1_transpose_inverse_ete * b2;
+#else
+ block.noalias() -= b1_transpose_inverse_ete * b2;
+#endif // CERES_WORK_AROUND_ANDROID_NDK_COMPILER_BUG
}
}
}
@@ -601,7 +623,7 @@ NoEBlockRowOuterProduct(const BlockSparseMatrixBase* A,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
- MutexLock l(&cell_info->m);
+ CeresMutexLock l(&cell_info->m);
MatrixRef m(cell_info->values, row_stride, col_stride);
m.block(r, c, block1_size, block1_size)
.selfadjointView<Eigen::Upper>()
@@ -621,7 +643,7 @@ NoEBlockRowOuterProduct(const BlockSparseMatrixBase* A,
}
const int block2_size = bs->cols[row.cells[j].block_id].size;
- MutexLock l(&cell_info->m);
+ CeresMutexLock l(&cell_info->m);
MatrixRef m(cell_info->values, row_stride, col_stride);
m.block(r, c, block1_size, block2_size).noalias() +=
b1.transpose() * ConstMatrixRef(row_values + row.cells[j].position,
@@ -660,7 +682,7 @@ EBlockRowOuterProduct(const BlockSparseMatrixBase* A,
continue;
}
- MutexLock l(&cell_info->m);
+ CeresMutexLock l(&cell_info->m);
MatrixRef m(cell_info->values, row_stride, col_stride);
Eigen::Block<MatrixRef, kFBlockSize, kFBlockSize>
@@ -687,7 +709,7 @@ EBlockRowOuterProduct(const BlockSparseMatrixBase* A,
row.block.size,
block2_size);
- MutexLock l(&cell_info->m);
+ CeresMutexLock l(&cell_info->m);
MatrixRef m(cell_info->values, row_stride, col_stride);
Eigen::Block<MatrixRef, kFBlockSize, kFBlockSize>
block(m, r, c, block1_size, block2_size);
diff --git a/extern/libmv/third_party/ceres/internal/ceres/schur_ordering.cc b/extern/libmv/third_party/ceres/internal/ceres/schur_ordering.cc
index c4fc1da3c2f..1cdff4e6dec 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/schur_ordering.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/schur_ordering.cc
@@ -30,25 +30,14 @@
#include "ceres/schur_ordering.h"
-#include <glog/logging.h>
#include "ceres/graph.h"
#include "ceres/graph_algorithms.h"
+#include "ceres/internal/scoped_ptr.h"
#include "ceres/map_util.h"
#include "ceres/parameter_block.h"
#include "ceres/program.h"
#include "ceres/residual_block.h"
-#include "ceres/internal/scoped_ptr.h"
-
-CERES_HASH_NAMESPACE_START
-
-// Allow us to hash pointers as if they were int's
-template<> struct hash< ::ceres::internal::ParameterBlock*> {
- size_t operator()(::ceres::internal::ParameterBlock* x) const {
- return reinterpret_cast<size_t>(x);
- }
-};
-
-CERES_HASH_NAMESPACE_END
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -59,8 +48,7 @@ int ComputeSchurOrdering(const Program& program,
scoped_ptr<Graph< ParameterBlock*> > graph(
CHECK_NOTNULL(CreateHessianGraph(program)));
- int independent_set_size =
- IndependentSetOrdering<ParameterBlock*>(*graph, ordering);
+ int independent_set_size = IndependentSetOrdering(*graph, ordering);
const vector<ParameterBlock*>& parameter_blocks = program.parameter_blocks();
// Add the excluded blocks to back of the ordering vector.
diff --git a/extern/libmv/third_party/ceres/internal/ceres/solver.cc b/extern/libmv/third_party/ceres/internal/ceres/solver.cc
index 77f04d1d918..66ca93283a1 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/solver.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/solver.cc
@@ -32,36 +32,32 @@
#include "ceres/solver.h"
#include <vector>
-#include "ceres/levenberg_marquardt.h"
+#include "ceres/problem.h"
+#include "ceres/problem_impl.h"
#include "ceres/program.h"
#include "ceres/solver_impl.h"
#include "ceres/stringprintf.h"
-#include "ceres/problem.h"
namespace ceres {
Solver::~Solver() {}
-// TODO(sameeragarwal): The timing code here should use a sub-second
-// timer.
+// TODO(sameeragarwal): Use subsecond timers.
void Solver::Solve(const Solver::Options& options,
Problem* problem,
Solver::Summary* summary) {
time_t start_time_seconds = time(NULL);
- internal::SolverImpl::Solve(options, problem, summary);
+ internal::ProblemImpl* problem_impl =
+ CHECK_NOTNULL(problem)->problem_impl_.get();
+ internal::SolverImpl::Solve(options, problem_impl, summary);
summary->total_time_in_seconds = time(NULL) - start_time_seconds;
- summary->preprocessor_time_in_seconds =
- summary->total_time_in_seconds - summary->minimizer_time_in_seconds;
}
void Solve(const Solver::Options& options,
Problem* problem,
Solver::Summary* summary) {
- time_t start_time_seconds = time(NULL);
- internal::SolverImpl::Solve(options, problem, summary);
- summary->total_time_in_seconds = time(NULL) - start_time_seconds;
- summary->preprocessor_time_in_seconds =
- summary->total_time_in_seconds - summary->minimizer_time_in_seconds;
+ Solver solver;
+ solver.Solve(options, problem, summary);
}
Solver::Summary::Summary()
@@ -75,6 +71,7 @@ Solver::Summary::Summary()
num_unsuccessful_steps(-1),
preprocessor_time_in_seconds(-1.0),
minimizer_time_in_seconds(-1.0),
+ postprocessor_time_in_seconds(-1.0),
total_time_in_seconds(-1.0),
num_parameter_blocks(-1),
num_parameters(-1),
@@ -93,7 +90,9 @@ Solver::Summary::Summary()
linear_solver_type_given(SPARSE_NORMAL_CHOLESKY),
linear_solver_type_used(SPARSE_NORMAL_CHOLESKY),
preconditioner_type(IDENTITY),
- ordering_type(NATURAL) {
+ ordering_type(NATURAL),
+ trust_region_strategy_type(LEVENBERG_MARQUARDT),
+ sparse_linear_algebra_library(SUITE_SPARSE) {
}
string Solver::Summary::BriefReport() const {
@@ -136,7 +135,7 @@ string Solver::Summary::FullReport() const {
num_parameters);
internal::StringAppendF(&report, "Residual blocks % 10d\n",
num_residual_blocks);
- internal::StringAppendF(&report, "Residual % 10d\n\n",
+ internal::StringAppendF(&report, "Residuals % 10d\n\n",
num_residuals);
} else {
internal::StringAppendF(&report, "%45s %21s\n", "Original", "Reduced");
@@ -183,10 +182,33 @@ string Solver::Summary::FullReport() const {
internal::StringAppendF(&report, "Threads: % 25d% 25d\n",
num_threads_given, num_threads_used);
- internal::StringAppendF(&report, "Linear Solver Threads:% 23d% 25d\n",
+ internal::StringAppendF(&report, "Linear solver threads % 23d% 25d\n",
num_linear_solver_threads_given,
num_linear_solver_threads_used);
+ if (linear_solver_type_used == SPARSE_NORMAL_CHOLESKY ||
+ linear_solver_type_used == SPARSE_SCHUR ||
+ (linear_solver_type_used == ITERATIVE_SCHUR &&
+ (preconditioner_type == SCHUR_JACOBI ||
+ preconditioner_type == CLUSTER_JACOBI ||
+ preconditioner_type == CLUSTER_TRIDIAGONAL))) {
+ internal::StringAppendF(&report, "\nSparse Linear Algebra Library %15s\n",
+ SparseLinearAlgebraLibraryTypeToString(
+ sparse_linear_algebra_library));
+ }
+
+ internal::StringAppendF(&report, "Trust Region Strategy %19s",
+ TrustRegionStrategyTypeToString(
+ trust_region_strategy_type));
+ if (trust_region_strategy_type == DOGLEG) {
+ if (dogleg_type == TRADITIONAL_DOGLEG) {
+ internal::StringAppendF(&report, " (TRADITIONAL)");
+ } else {
+ internal::StringAppendF(&report, " (SUBSPACE)");
+ }
+ }
+ internal::StringAppendF(&report, "\n");
+
if (termination_type == DID_NOT_RUN) {
CHECK(!error.empty())
diff --git a/extern/libmv/third_party/ceres/internal/ceres/solver_impl.cc b/extern/libmv/third_party/ceres/internal/ceres/solver_impl.cc
index ed07d9dc6d7..8ef5b98e35f 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/solver_impl.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/solver_impl.cc
@@ -30,40 +30,29 @@
#include "ceres/solver_impl.h"
+#include <cstdio>
#include <iostream> // NOLINT
#include <numeric>
#include "ceres/evaluator.h"
#include "ceres/gradient_checking_cost_function.h"
-#include "ceres/levenberg_marquardt.h"
+#include "ceres/iteration_callback.h"
+#include "ceres/levenberg_marquardt_strategy.h"
#include "ceres/linear_solver.h"
#include "ceres/map_util.h"
#include "ceres/minimizer.h"
#include "ceres/parameter_block.h"
+#include "ceres/problem.h"
#include "ceres/problem_impl.h"
#include "ceres/program.h"
#include "ceres/residual_block.h"
#include "ceres/schur_ordering.h"
#include "ceres/stringprintf.h"
-#include "ceres/iteration_callback.h"
-#include "ceres/problem.h"
+#include "ceres/trust_region_minimizer.h"
namespace ceres {
namespace internal {
namespace {
-void EvaluateCostAndResiduals(ProblemImpl* problem_impl,
- double* cost,
- vector<double>* residuals) {
- CHECK_NOTNULL(cost);
- Program* program = CHECK_NOTNULL(problem_impl)->mutable_program();
- if (residuals != NULL) {
- residuals->resize(program->NumResiduals());
- program->Evaluate(cost, &(*residuals)[0]);
- } else {
- program->Evaluate(cost, NULL);
- }
-}
-
// Callback for updating the user's parameter blocks. Updates are only
// done if the step is successful.
class StateUpdatingCallback : public IterationCallback {
@@ -96,7 +85,7 @@ class LoggingCallback : public IterationCallback {
CallbackReturnType operator()(const IterationSummary& summary) {
const char* kReportRowFormat =
"% 4d: f:% 8e d:% 3.2e g:% 3.2e h:% 3.2e "
- "rho:% 3.2e mu:% 3.2e li:% 3d";
+ "rho:% 3.2e mu:% 3.2e li:% 3d it:% 3.2e tt:% 3.2e";
string output = StringPrintf(kReportRowFormat,
summary.iteration,
summary.cost,
@@ -104,8 +93,10 @@ class LoggingCallback : public IterationCallback {
summary.gradient_max_norm,
summary.step_norm,
summary.relative_decrease,
- summary.mu,
- summary.linear_solver_iterations);
+ summary.trust_region_radius,
+ summary.linear_solver_iterations,
+ summary.iteration_time_in_seconds,
+ summary.cumulative_time_in_seconds);
if (log_to_stdout_) {
cout << output << endl;
} else {
@@ -118,44 +109,101 @@ class LoggingCallback : public IterationCallback {
const bool log_to_stdout_;
};
+// Basic callback to record the execution of the solver to a file for
+// offline analysis.
+class FileLoggingCallback : public IterationCallback {
+ public:
+ explicit FileLoggingCallback(const string& filename)
+ : fptr_(NULL) {
+ fptr_ = fopen(filename.c_str(), "w");
+ CHECK_NOTNULL(fptr_);
+ }
+
+ virtual ~FileLoggingCallback() {
+ if (fptr_ != NULL) {
+ fclose(fptr_);
+ }
+ }
+
+ virtual CallbackReturnType operator()(const IterationSummary& summary) {
+ fprintf(fptr_,
+ "%4d %e %e\n",
+ summary.iteration,
+ summary.cost,
+ summary.cumulative_time_in_seconds);
+ return SOLVER_CONTINUE;
+ }
+ private:
+ FILE* fptr_;
+};
+
} // namespace
void SolverImpl::Minimize(const Solver::Options& options,
Program* program,
Evaluator* evaluator,
LinearSolver* linear_solver,
- double* initial_parameters,
- double* final_parameters,
+ double* parameters,
Solver::Summary* summary) {
Minimizer::Options minimizer_options(options);
+ // TODO(sameeragarwal): Add support for logging the configuration
+ // and more detailed stats.
+ scoped_ptr<IterationCallback> file_logging_callback;
+ if (!options.solver_log.empty()) {
+ file_logging_callback.reset(new FileLoggingCallback(options.solver_log));
+ minimizer_options.callbacks.insert(minimizer_options.callbacks.begin(),
+ file_logging_callback.get());
+ }
+
LoggingCallback logging_callback(options.minimizer_progress_to_stdout);
if (options.logging_type != SILENT) {
- minimizer_options.callbacks.push_back(&logging_callback);
+ minimizer_options.callbacks.insert(minimizer_options.callbacks.begin(),
+ &logging_callback);
}
- StateUpdatingCallback updating_callback(program, initial_parameters);
+ StateUpdatingCallback updating_callback(program, parameters);
if (options.update_state_every_iteration) {
- minimizer_options.callbacks.push_back(&updating_callback);
- }
-
- LevenbergMarquardt levenberg_marquardt;
-
- time_t start_minimizer_time_seconds = time(NULL);
- levenberg_marquardt.Minimize(minimizer_options,
- evaluator,
- linear_solver,
- initial_parameters,
- final_parameters,
- summary);
- summary->minimizer_time_in_seconds =
- time(NULL) - start_minimizer_time_seconds;
+ // This must get pushed to the front of the callbacks so that it is run
+ // before any of the user callbacks.
+ minimizer_options.callbacks.insert(minimizer_options.callbacks.begin(),
+ &updating_callback);
+ }
+
+ minimizer_options.evaluator = evaluator;
+ scoped_ptr<SparseMatrix> jacobian(evaluator->CreateJacobian());
+ minimizer_options.jacobian = jacobian.get();
+
+ TrustRegionStrategy::Options trust_region_strategy_options;
+ trust_region_strategy_options.linear_solver = linear_solver;
+ trust_region_strategy_options.initial_radius =
+ options.initial_trust_region_radius;
+ trust_region_strategy_options.max_radius = options.max_trust_region_radius;
+ trust_region_strategy_options.lm_min_diagonal = options.lm_min_diagonal;
+ trust_region_strategy_options.lm_max_diagonal = options.lm_max_diagonal;
+ trust_region_strategy_options.trust_region_strategy_type =
+ options.trust_region_strategy_type;
+ trust_region_strategy_options.dogleg_type = options.dogleg_type;
+ scoped_ptr<TrustRegionStrategy> strategy(
+ TrustRegionStrategy::Create(trust_region_strategy_options));
+ minimizer_options.trust_region_strategy = strategy.get();
+
+ TrustRegionMinimizer minimizer;
+ time_t minimizer_start_time = time(NULL);
+ minimizer.Minimize(minimizer_options, parameters, summary);
+ summary->minimizer_time_in_seconds = time(NULL) - minimizer_start_time;
}
void SolverImpl::Solve(const Solver::Options& original_options,
- Problem* problem,
+ ProblemImpl* original_problem_impl,
Solver::Summary* summary) {
+ time_t solver_start_time = time(NULL);
Solver::Options options(original_options);
+ Program* original_program = original_problem_impl->mutable_program();
+ ProblemImpl* problem_impl = original_problem_impl;
+ // Reset the summary object to its default values.
+ *CHECK_NOTNULL(summary) = Solver::Summary();
+
#ifndef CERES_USE_OPENMP
if (options.num_threads > 1) {
@@ -174,8 +222,6 @@ void SolverImpl::Solve(const Solver::Options& original_options,
}
#endif
- // Reset the summary object to its default values;
- *CHECK_NOTNULL(summary) = Solver::Summary();
summary->linear_solver_type_given = options.linear_solver_type;
summary->num_eliminate_blocks_given = original_options.num_eliminate_blocks;
summary->num_threads_given = original_options.num_threads;
@@ -183,32 +229,38 @@ void SolverImpl::Solve(const Solver::Options& original_options,
original_options.num_linear_solver_threads;
summary->ordering_type = original_options.ordering_type;
- ProblemImpl* problem_impl = CHECK_NOTNULL(problem)->problem_impl_.get();
-
summary->num_parameter_blocks = problem_impl->NumParameterBlocks();
summary->num_parameters = problem_impl->NumParameters();
summary->num_residual_blocks = problem_impl->NumResidualBlocks();
summary->num_residuals = problem_impl->NumResiduals();
summary->num_threads_used = options.num_threads;
-
- // Evaluate the initial cost and residual vector (if needed). The
- // initial cost needs to be computed on the original unpreprocessed
- // problem, as it is used to determine the value of the "fixed" part
- // of the objective function after the problem has undergone
- // reduction. Also the initial residuals are in the order in which
- // the user added the ResidualBlocks to the optimization problem.
- EvaluateCostAndResiduals(problem_impl,
- &summary->initial_cost,
- options.return_initial_residuals
- ? &summary->initial_residuals
- : NULL);
+ summary->sparse_linear_algebra_library =
+ options.sparse_linear_algebra_library;
+ summary->trust_region_strategy_type = options.trust_region_strategy_type;
+ summary->dogleg_type = options.dogleg_type;
+
+ // Evaluate the initial cost, residual vector and the jacobian
+ // matrix if requested by the user. The initial cost needs to be
+ // computed on the original unpreprocessed problem, as it is used to
+ // determine the value of the "fixed" part of the objective function
+ // after the problem has undergone reduction.
+ Evaluator::Evaluate(
+ original_program,
+ options.num_threads,
+ &(summary->initial_cost),
+ options.return_initial_residuals ? &summary->initial_residuals : NULL,
+ options.return_initial_gradient ? &summary->initial_gradient : NULL,
+ options.return_initial_jacobian ? &summary->initial_jacobian : NULL);
+ original_program->SetParameterBlockStatePtrsToUserStatePtrs();
// If the user requests gradient checking, construct a new
// ProblemImpl by wrapping the CostFunctions of problem_impl inside
// GradientCheckingCostFunction and replacing problem_impl with
// gradient_checking_problem_impl.
scoped_ptr<ProblemImpl> gradient_checking_problem_impl;
+ // Save the original problem impl so we don't use the gradient
+ // checking one when computing the residuals.
if (options.check_gradients) {
VLOG(1) << "Checking Gradients";
gradient_checking_problem_impl.reset(
@@ -224,8 +276,10 @@ void SolverImpl::Solve(const Solver::Options& original_options,
// Create the three objects needed to minimize: the transformed program, the
// evaluator, and the linear solver.
- scoped_ptr<Program> reduced_program(
- CreateReducedProgram(&options, problem_impl, &summary->error));
+ scoped_ptr<Program> reduced_program(CreateReducedProgram(&options,
+ problem_impl,
+ &summary->fixed_cost,
+ &summary->error));
if (reduced_program == NULL) {
return;
}
@@ -259,19 +313,21 @@ void SolverImpl::Solve(const Solver::Options& original_options,
}
// The optimizer works on contiguous parameter vectors; allocate some.
- Vector initial_parameters(reduced_program->NumParameters());
- Vector optimized_parameters(reduced_program->NumParameters());
+ Vector parameters(reduced_program->NumParameters());
// Collect the discontiguous parameters into a contiguous state vector.
- reduced_program->ParameterBlocksToStateVector(&initial_parameters[0]);
+ reduced_program->ParameterBlocksToStateVector(parameters.data());
+
+ time_t minimizer_start_time = time(NULL);
+ summary->preprocessor_time_in_seconds =
+ minimizer_start_time - solver_start_time;
// Run the optimization.
Minimize(options,
reduced_program.get(),
evaluator.get(),
linear_solver.get(),
- initial_parameters.data(),
- optimized_parameters.data(),
+ parameters.data(),
summary);
// If the user aborted mid-optimization or the optimization
@@ -282,30 +338,45 @@ void SolverImpl::Solve(const Solver::Options& original_options,
return;
}
+ time_t post_process_start_time = time(NULL);
+
// Push the contiguous optimized parameters back to the user's parameters.
- reduced_program->StateVectorToParameterBlocks(&optimized_parameters[0]);
+ reduced_program->StateVectorToParameterBlocks(parameters.data());
reduced_program->CopyParameterBlockStateToUserState();
- // Return the final cost and residuals for the original problem.
- EvaluateCostAndResiduals(problem->problem_impl_.get(),
- &summary->final_cost,
- options.return_final_residuals
- ? &summary->final_residuals
- : NULL);
-
+ // Evaluate the final cost, residual vector and the jacobian
+ // matrix if requested by the user.
+ Evaluator::Evaluate(
+ original_program,
+ options.num_threads,
+ &summary->final_cost,
+ options.return_final_residuals ? &summary->final_residuals : NULL,
+ options.return_final_gradient ? &summary->final_gradient : NULL,
+ options.return_final_jacobian ? &summary->final_jacobian : NULL);
+
+ // Ensure the program state is set to the user parameters on the way out.
+ original_program->SetParameterBlockStatePtrsToUserStatePtrs();
// Stick a fork in it, we're done.
- return;
+ summary->postprocessor_time_in_seconds = time(NULL) - post_process_start_time;
}
// Strips varying parameters and residuals, maintaining order, and updating
// num_eliminate_blocks.
bool SolverImpl::RemoveFixedBlocksFromProgram(Program* program,
int* num_eliminate_blocks,
+ double* fixed_cost,
string* error) {
int original_num_eliminate_blocks = *num_eliminate_blocks;
vector<ParameterBlock*>* parameter_blocks =
program->mutable_parameter_blocks();
+ scoped_array<double> residual_block_evaluate_scratch;
+ if (fixed_cost != NULL) {
+ residual_block_evaluate_scratch.reset(
+ new double[program->MaxScratchDoublesNeededForEvaluate()]);
+ *fixed_cost = 0.0;
+ }
+
// Mark all the parameters as unused. Abuse the index member of the parameter
// blocks for the marking.
for (int i = 0; i < parameter_blocks->size(); ++i) {
@@ -335,6 +406,17 @@ bool SolverImpl::RemoveFixedBlocksFromProgram(Program* program,
if (!all_constant) {
(*residual_blocks)[j++] = (*residual_blocks)[i];
+ } else if (fixed_cost != NULL) {
+ // The residual is constant and will be removed, so its cost is
+ // added to the variable fixed_cost.
+ double cost = 0.0;
+ if (!residual_block->Evaluate(
+ &cost, NULL, NULL, residual_block_evaluate_scratch.get())) {
+ *error = StringPrintf("Evaluation of the residual %d failed during "
+ "removal of fixed residual blocks.", i);
+ return false;
+ }
+ *fixed_cost += cost;
}
}
residual_blocks->resize(j);
@@ -367,6 +449,7 @@ bool SolverImpl::RemoveFixedBlocksFromProgram(Program* program,
Program* SolverImpl::CreateReducedProgram(Solver::Options* options,
ProblemImpl* problem_impl,
+ double* fixed_cost,
string* error) {
Program* original_program = problem_impl->mutable_program();
scoped_ptr<Program> transformed_program(new Program(*original_program));
@@ -397,6 +480,7 @@ Program* SolverImpl::CreateReducedProgram(Solver::Options* options,
if (!RemoveFixedBlocksFromProgram(transformed_program.get(),
&num_eliminate_blocks,
+ fixed_cost,
error)) {
return NULL;
}
@@ -431,13 +515,34 @@ Program* SolverImpl::CreateReducedProgram(Solver::Options* options,
LinearSolver* SolverImpl::CreateLinearSolver(Solver::Options* options,
string* error) {
+ if (options->trust_region_strategy_type == DOGLEG) {
+ if (options->linear_solver_type == ITERATIVE_SCHUR ||
+ options->linear_solver_type == CGNR) {
+ *error = "DOGLEG only supports exact factorization based linear "
+ "solvers. If you want to use an iterative solver please "
+ "use LEVENBERG_MARQUARDT as the trust_region_strategy_type";
+ return NULL;
+ }
+ }
+
#ifdef CERES_NO_SUITESPARSE
- if (options->linear_solver_type == SPARSE_NORMAL_CHOLESKY) {
- *error = "Can't use SPARSE_NORMAL_CHOLESKY because SuiteSparse was not "
- "enabled when Ceres was built.";
+ if (options->linear_solver_type == SPARSE_NORMAL_CHOLESKY &&
+ options->sparse_linear_algebra_library == SUITE_SPARSE) {
+ *error = "Can't use SPARSE_NORMAL_CHOLESKY with SUITESPARSE because "
+ "SuiteSparse was not enabled when Ceres was built.";
+ return NULL;
+ }
+#endif
+
+#ifdef CERES_NO_CXSPARSE
+ if (options->linear_solver_type == SPARSE_NORMAL_CHOLESKY &&
+ options->sparse_linear_algebra_library == CX_SPARSE) {
+ *error = "Can't use SPARSE_NORMAL_CHOLESKY with CXSPARSE because "
+ "CXSparse was not enabled when Ceres was built.";
return NULL;
}
-#endif // CERES_NO_SUITESPARSE
+#endif
+
if (options->linear_solver_max_num_iterations <= 0) {
*error = "Solver::Options::linear_solver_max_num_iterations is 0.";
@@ -455,30 +560,32 @@ LinearSolver* SolverImpl::CreateLinearSolver(Solver::Options* options,
}
LinearSolver::Options linear_solver_options;
- linear_solver_options.constant_sparsity = true;
linear_solver_options.min_num_iterations =
options->linear_solver_min_num_iterations;
linear_solver_options.max_num_iterations =
options->linear_solver_max_num_iterations;
linear_solver_options.type = options->linear_solver_type;
linear_solver_options.preconditioner_type = options->preconditioner_type;
+ linear_solver_options.sparse_linear_algebra_library =
+ options->sparse_linear_algebra_library;
+ linear_solver_options.use_block_amd = options->use_block_amd;
#ifdef CERES_NO_SUITESPARSE
if (linear_solver_options.preconditioner_type == SCHUR_JACOBI) {
*error = "SCHUR_JACOBI preconditioner not suppored. Please build Ceres "
- "with SuiteSparse support";
+ "with SuiteSparse support.";
return NULL;
}
if (linear_solver_options.preconditioner_type == CLUSTER_JACOBI) {
*error = "CLUSTER_JACOBI preconditioner not suppored. Please build Ceres "
- "with SuiteSparse support";
+ "with SuiteSparse support.";
return NULL;
}
if (linear_solver_options.preconditioner_type == CLUSTER_TRIDIAGONAL) {
*error = "CLUSTER_TRIDIAGONAL preconditioner not suppored. Please build "
- "Ceres with SuiteSparse support";
+ "Ceres with SuiteSparse support.";
return NULL;
}
#endif
@@ -489,23 +596,23 @@ LinearSolver* SolverImpl::CreateLinearSolver(Solver::Options* options,
if ((linear_solver_options.num_eliminate_blocks == 0) &&
IsSchurType(linear_solver_options.type)) {
-#ifndef CERES_NO_SUITESPARSE
+#if defined(CERES_NO_SUITESPARSE) && defined(CERES_NO_CXSPARSE)
+ LOG(INFO) << "No elimination block remaining switching to DENSE_QR.";
+ linear_solver_options.type = DENSE_QR;
+#else
LOG(INFO) << "No elimination block remaining "
<< "switching to SPARSE_NORMAL_CHOLESKY.";
linear_solver_options.type = SPARSE_NORMAL_CHOLESKY;
-#else
- LOG(INFO) << "No elimination block remaining switching to DENSE_QR.";
- linear_solver_options.type = DENSE_QR;
-#endif // CERES_NO_SUITESPARSE
+#endif
}
-#ifdef CERES_NO_SUITESPARSE
+#if defined(CERES_NO_SUITESPARSE) && defined(CERES_NO_CXSPARSE)
if (linear_solver_options.type == SPARSE_SCHUR) {
- *error = "Can't use SPARSE_SCHUR because SuiteSparse was not "
- "enabled when Ceres was built.";
+ *error = "Can't use SPARSE_SCHUR because neither SuiteSparse nor"
+ "CXSparse was enabled when Ceres was compiled.";
return NULL;
}
-#endif // CERES_NO_SUITESPARSE
+#endif
// The matrix used for storing the dense Schur complement has a
// single lock guarding the whole matrix. Running the
@@ -578,15 +685,18 @@ bool SolverImpl::ApplyUserOrdering(const ProblemImpl& problem_impl,
// Find the minimum index of any parameter block to the given residual.
// Parameter blocks that have indices greater than num_eliminate_blocks are
// considered to have an index equal to num_eliminate_blocks.
-int MinParameterBlock(const ResidualBlock* residual_block,
- int num_eliminate_blocks) {
+static int MinParameterBlock(const ResidualBlock* residual_block,
+ int num_eliminate_blocks) {
int min_parameter_block_position = num_eliminate_blocks;
for (int i = 0; i < residual_block->NumParameterBlocks(); ++i) {
ParameterBlock* parameter_block = residual_block->parameter_blocks()[i];
- DCHECK_NE(parameter_block->index(), -1)
- << "Did you forget to call Program::SetParameterOffsetsAndIndex()?";
- min_parameter_block_position = std::min(parameter_block->index(),
- min_parameter_block_position);
+ if (!parameter_block->IsConstant()) {
+ CHECK_NE(parameter_block->index(), -1)
+ << "Did you forget to call Program::SetParameterOffsetsAndIndex()? "
+ << "This is a Ceres bug; please contact the developers!";
+ min_parameter_block_position = std::min(parameter_block->index(),
+ min_parameter_block_position);
+ }
}
return min_parameter_block_position;
}
diff --git a/extern/libmv/third_party/ceres/internal/ceres/solver_impl.h b/extern/libmv/third_party/ceres/internal/ceres/solver_impl.h
index 957ebcc65df..11b44de6f42 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/solver_impl.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/solver_impl.h
@@ -31,6 +31,9 @@
#ifndef CERES_INTERNAL_SOLVER_IMPL_H_
#define CERES_INTERNAL_SOLVER_IMPL_H_
+#include <string>
+#include <vector>
+#include "ceres/internal/port.h"
#include "ceres/solver.h"
namespace ceres {
@@ -46,15 +49,18 @@ class SolverImpl {
// Mirrors the interface in solver.h, but exposes implementation
// details for testing internally.
static void Solve(const Solver::Options& options,
- Problem* problem,
+ ProblemImpl* problem_impl,
Solver::Summary* summary);
// Create the transformed Program, which has all the fixed blocks
// and residuals eliminated, and in the case of automatic schur
// ordering, has the E blocks first in the resulting program, with
// options.num_eliminate_blocks set appropriately.
+ // If fixed_cost is not NULL, the residual blocks that are removed
+ // are evaluated and the sum of their cost is returned in fixed_cost.
static Program* CreateReducedProgram(Solver::Options* options,
ProblemImpl* problem_impl,
+ double* fixed_cost,
string* error);
// Create the appropriate linear solver, taking into account any
@@ -92,16 +98,18 @@ class SolverImpl {
Program* program,
Evaluator* evaluator,
LinearSolver* linear_solver,
- double* initial_parameters,
- double* final_parameters,
+ double* parameters,
Solver::Summary* summary);
// Remove the fixed or unused parameter blocks and residuals
// depending only on fixed parameters from the problem. Also updates
// num_eliminate_blocks, since removed parameters changes the point
// at which the eliminated blocks is valid.
+ // If fixed_cost is not NULL, the residual blocks that are removed
+ // are evaluated and the sum of their cost is returned in fixed_cost.
static bool RemoveFixedBlocksFromProgram(Program* program,
int* num_eliminate_blocks,
+ double* fixed_cost,
string* error);
};
diff --git a/extern/libmv/third_party/ceres/internal/ceres/sparse_matrix.h b/extern/libmv/third_party/ceres/internal/ceres/sparse_matrix.h
index 562210dfec8..1b19f887946 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/sparse_matrix.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/sparse_matrix.h
@@ -86,7 +86,7 @@ class SparseMatrix : public LinearOperator {
// sparse matrix.
virtual void ToDenseMatrix(Matrix* dense_matrix) const = 0;
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
// Dump the sparse matrix to a proto. Destroys the contents of proto.
virtual void ToProto(SparseMatrixProto* proto) const = 0;
#endif
diff --git a/extern/libmv/third_party/ceres/internal/ceres/sparse_normal_cholesky_solver.cc b/extern/libmv/third_party/ceres/internal/ceres/sparse_normal_cholesky_solver.cc
index 59222dc374d..9e00b4402dc 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/sparse_normal_cholesky_solver.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/sparse_normal_cholesky_solver.cc
@@ -28,13 +28,16 @@
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
-#ifndef CERES_NO_SUITESPARSE
-
#include "ceres/sparse_normal_cholesky_solver.h"
#include <algorithm>
#include <cstring>
#include <ctime>
+
+#ifndef CERES_NO_CXSPARSE
+#include "cs.h"
+#endif
+
#include "ceres/compressed_row_sparse_matrix.h"
#include "ceres/linear_solver.h"
#include "ceres/suitesparse.h"
@@ -48,13 +51,30 @@ namespace internal {
SparseNormalCholeskySolver::SparseNormalCholeskySolver(
const LinearSolver::Options& options)
- : options_(options), symbolic_factor_(NULL) {}
+ : options_(options) {
+#ifndef CERES_NO_SUITESPARSE
+ factor_ = NULL;
+#endif
+
+#ifndef CERES_NO_CXSPARSE
+ cxsparse_factor_ = NULL;
+#endif // CERES_NO_CXSPARSE
+}
SparseNormalCholeskySolver::~SparseNormalCholeskySolver() {
- if (symbolic_factor_ != NULL) {
- ss_.Free(symbolic_factor_);
- symbolic_factor_ = NULL;
+#ifndef CERES_NO_SUITESPARSE
+ if (factor_ != NULL) {
+ ss_.Free(factor_);
+ factor_ = NULL;
}
+#endif
+
+#ifndef CERES_NO_CXSPARSE
+ if (cxsparse_factor_ != NULL) {
+ cxsparse_.Free(cxsparse_factor_);
+ cxsparse_factor_ = NULL;
+ }
+#endif // CERES_NO_CXSPARSE
}
LinearSolver::Summary SparseNormalCholeskySolver::SolveImpl(
@@ -62,6 +82,93 @@ LinearSolver::Summary SparseNormalCholeskySolver::SolveImpl(
const double* b,
const LinearSolver::PerSolveOptions& per_solve_options,
double * x) {
+ switch (options_.sparse_linear_algebra_library) {
+ case SUITE_SPARSE:
+ return SolveImplUsingSuiteSparse(A, b, per_solve_options, x);
+ case CX_SPARSE:
+ return SolveImplUsingCXSparse(A, b, per_solve_options, x);
+ default:
+ LOG(FATAL) << "Unknown sparse linear algebra library : "
+ << options_.sparse_linear_algebra_library;
+ }
+
+ LOG(FATAL) << "Unknown sparse linear algebra library : "
+ << options_.sparse_linear_algebra_library;
+ return LinearSolver::Summary();
+}
+
+#ifndef CERES_NO_CXSPARSE
+LinearSolver::Summary SparseNormalCholeskySolver::SolveImplUsingCXSparse(
+ CompressedRowSparseMatrix* A,
+ const double* b,
+ const LinearSolver::PerSolveOptions& per_solve_options,
+ double * x) {
+ LinearSolver::Summary summary;
+ summary.num_iterations = 1;
+ const int num_cols = A->num_cols();
+ Vector Atb = Vector::Zero(num_cols);
+ A->LeftMultiply(b, Atb.data());
+
+ if (per_solve_options.D != NULL) {
+ // Temporarily append a diagonal block to the A matrix, but undo
+ // it before returning the matrix to the user.
+ CompressedRowSparseMatrix D(per_solve_options.D, num_cols);
+ A->AppendRows(D);
+ }
+
+ VectorRef(x, num_cols).setZero();
+
+ // Wrap the augmented Jacobian in a compressed sparse column matrix.
+ cs_di At = cxsparse_.CreateSparseMatrixTransposeView(A);
+
+ // Compute the normal equations. J'J delta = J'f and solve them
+ // using a sparse Cholesky factorization. Notice that when compared
+ // to SuiteSparse we have to explicitly compute the transpose of Jt,
+ // and then the normal equations before they can be
+ // factorized. CHOLMOD/SuiteSparse on the other hand can just work
+ // off of Jt to compute the Cholesky factorization of the normal
+ // equations.
+ cs_di* A2 = cs_transpose(&At, 1);
+ cs_di* AtA = cs_multiply(&At,A2);
+
+ cxsparse_.Free(A2);
+ if (per_solve_options.D != NULL) {
+ A->DeleteRows(num_cols);
+ }
+
+ // Compute symbolic factorization if not available.
+ if (cxsparse_factor_ == NULL) {
+ cxsparse_factor_ = CHECK_NOTNULL(cxsparse_.AnalyzeCholesky(AtA));
+ }
+
+ // Solve the linear system.
+ if (cxsparse_.SolveCholesky(AtA, cxsparse_factor_, Atb.data())) {
+ VectorRef(x, Atb.rows()) = Atb;
+ summary.termination_type = TOLERANCE;
+ }
+
+ cxsparse_.Free(AtA);
+ return summary;
+}
+#else
+LinearSolver::Summary SparseNormalCholeskySolver::SolveImplUsingCXSparse(
+ CompressedRowSparseMatrix* A,
+ const double* b,
+ const LinearSolver::PerSolveOptions& per_solve_options,
+ double * x) {
+ LOG(FATAL) << "No CXSparse support in Ceres.";
+
+ // Unreachable but MSVC does not know this.
+ return LinearSolver::Summary();
+}
+#endif
+
+#ifndef CERES_NO_SUITESPARSE
+LinearSolver::Summary SparseNormalCholeskySolver::SolveImplUsingSuiteSparse(
+ CompressedRowSparseMatrix* A,
+ const double* b,
+ const LinearSolver::PerSolveOptions& per_solve_options,
+ double * x) {
const time_t start_time = time(NULL);
const int num_cols = A->num_cols();
@@ -84,13 +191,25 @@ LinearSolver::Summary SparseNormalCholeskySolver::SolveImpl(
cholmod_dense* rhs = ss_.CreateDenseVector(Atb.data(), num_cols, num_cols);
const time_t init_time = time(NULL);
- if (symbolic_factor_ == NULL) {
- symbolic_factor_ = CHECK_NOTNULL(ss_.AnalyzeCholesky(lhs.get()));
+ if (factor_ == NULL) {
+ if (options_.use_block_amd) {
+ factor_ = ss_.BlockAnalyzeCholesky(lhs.get(),
+ A->col_blocks(),
+ A->row_blocks());
+ } else {
+ factor_ = ss_.AnalyzeCholesky(lhs.get());
+ }
+
+ if (VLOG_IS_ON(2)) {
+ cholmod_print_common("Symbolic Analysis", ss_.mutable_cc());
+ }
}
+ CHECK_NOTNULL(factor_);
+
const time_t symbolic_time = time(NULL);
- cholmod_dense* sol = ss_.SolveCholesky(lhs.get(), symbolic_factor_, rhs);
+ cholmod_dense* sol = ss_.SolveCholesky(lhs.get(), factor_, rhs);
const time_t solve_time = time(NULL);
ss_.Free(rhs);
@@ -100,11 +219,6 @@ LinearSolver::Summary SparseNormalCholeskySolver::SolveImpl(
A->DeleteRows(num_cols);
}
- if (!options_.constant_sparsity) {
- ss_.Free(symbolic_factor_);
- symbolic_factor_ = NULL;
- }
-
summary.num_iterations = 1;
if (sol != NULL) {
memcpy(x, sol->x, num_cols * sizeof(*x));
@@ -115,15 +229,25 @@ LinearSolver::Summary SparseNormalCholeskySolver::SolveImpl(
}
const time_t cleanup_time = time(NULL);
- VLOG(2) << "time (sec) total: " << cleanup_time - start_time
- << " init: " << init_time - start_time
- << " symbolic: " << symbolic_time - init_time
- << " solve: " << solve_time - symbolic_time
- << " cleanup: " << cleanup_time - solve_time;
+ VLOG(2) << "time (sec) total: " << (cleanup_time - start_time)
+ << " init: " << (init_time - start_time)
+ << " symbolic: " << (symbolic_time - init_time)
+ << " solve: " << (solve_time - symbolic_time)
+ << " cleanup: " << (cleanup_time - solve_time);
return summary;
}
+#else
+LinearSolver::Summary SparseNormalCholeskySolver::SolveImplUsingSuiteSparse(
+ CompressedRowSparseMatrix* A,
+ const double* b,
+ const LinearSolver::PerSolveOptions& per_solve_options,
+ double * x) {
+ LOG(FATAL) << "No SuiteSparse support in Ceres.";
+
+ // Unreachable but MSVC does not know this.
+ return LinearSolver::Summary();
+}
+#endif
} // namespace internal
} // namespace ceres
-
-#endif // CERES_NO_SUITESPARSE
diff --git a/extern/libmv/third_party/ceres/internal/ceres/sparse_normal_cholesky_solver.h b/extern/libmv/third_party/ceres/internal/ceres/sparse_normal_cholesky_solver.h
index ce1d6d285be..40d9e0a0327 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/sparse_normal_cholesky_solver.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/sparse_normal_cholesky_solver.h
@@ -34,13 +34,10 @@
#ifndef CERES_INTERNAL_SPARSE_NORMAL_CHOLESKY_SOLVER_H_
#define CERES_INTERNAL_SPARSE_NORMAL_CHOLESKY_SOLVER_H_
-#ifndef CERES_NO_SUITESPARSE
-
-#include "cholmod.h"
-#include "cholmod_core.h"
+#include "ceres/cxsparse.h"
#include "ceres/linear_solver.h"
-#include "ceres/suitesparse.h"
#include "ceres/internal/macros.h"
+#include "ceres/suitesparse.h"
namespace ceres {
namespace internal {
@@ -61,17 +58,36 @@ class SparseNormalCholeskySolver : public CompressedRowSparseMatrixSolver {
const LinearSolver::PerSolveOptions& options,
double* x);
- const LinearSolver::Options options_;
+ LinearSolver::Summary SolveImplUsingSuiteSparse(
+ CompressedRowSparseMatrix* A,
+ const double* b,
+ const LinearSolver::PerSolveOptions& options,
+ double* x);
+
+ // Crashes if CSparse is not installed.
+ LinearSolver::Summary SolveImplUsingCXSparse(
+ CompressedRowSparseMatrix* A,
+ const double* b,
+ const LinearSolver::PerSolveOptions& options,
+ double* x);
+
+#ifndef CERES_NO_SUITESPARSE
SuiteSparse ss_;
+ // Cached factorization
+ cholmod_factor* factor_;
+#endif // CERES_NO_SUITESPARSE
+#ifndef CERES_NO_CXSPARSE
+ CXSparse cxsparse_;
// Cached factorization
- cholmod_factor* symbolic_factor_;
- DISALLOW_COPY_AND_ASSIGN(SparseNormalCholeskySolver);
+ cs_dis* cxsparse_factor_;
+#endif // CERES_NO_CXSPARSE
+
+ const LinearSolver::Options options_;
+ CERES_DISALLOW_COPY_AND_ASSIGN(SparseNormalCholeskySolver);
};
} // namespace internal
} // namespace ceres
-#endif // CERES_NO_SUITESPARSE
-
#endif // CERES_INTERNAL_SPARSE_NORMAL_CHOLESKY_SOLVER_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/split.cc b/extern/libmv/third_party/ceres/internal/ceres/split.cc
index 4fa1bd468b9..c65c8a5bb5d 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/split.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/split.cc
@@ -31,6 +31,7 @@
#include <string>
#include <vector>
#include <iterator>
+#include "ceres/split.h"
#include "ceres/internal/port.h"
namespace ceres {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/split.h b/extern/libmv/third_party/ceres/internal/ceres/split.h
new file mode 100644
index 00000000000..ec579e974da
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/split.h
@@ -0,0 +1,21 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+// Author: keir@google.com (Keir Mierle)
+
+#ifndef CERES_INTERNAL_SPLIT_H_
+#define VISION_OPTIMIZATION_LEAST_SQUARES_INTERNAL_SPLIT_H_
+
+#include <string>
+#include <vector>
+#include "ceres/internal/port.h"
+
+namespace ceres {
+
+// Split a string using one or more character delimiters, presented as a
+// nul-terminated c string. Append the components to 'result'. If there are
+// consecutive delimiters, this function skips over all of them.
+void SplitStringUsing(const string& full, const char* delim,
+ vector<string>* res);
+
+} // namespace ceres
+
+#endif // CERES_INTERNAL_SPLIT_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/stringprintf.cc b/extern/libmv/third_party/ceres/internal/ceres/stringprintf.cc
index c0f35225bc3..396a48b7d97 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/stringprintf.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/stringprintf.cc
@@ -34,6 +34,7 @@
#include <string>
#include <vector>
+#include "ceres/stringprintf.h"
#include "ceres/internal/port.h"
namespace ceres {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/stringprintf.h b/extern/libmv/third_party/ceres/internal/ceres/stringprintf.h
index 30b974e7ae5..f2f907ab32d 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/stringprintf.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/stringprintf.h
@@ -54,34 +54,34 @@ namespace internal {
// N.B.: As the GCC manual states, "[s]ince non-static C++ methods
// have an implicit 'this' argument, the arguments of such methods
// should be counted from two, not one."
-#define PRINTF_ATTRIBUTE(string_index, first_to_check) \
+#define CERES_PRINTF_ATTRIBUTE(string_index, first_to_check) \
__attribute__((__format__ (__printf__, string_index, first_to_check)))
-#define SCANF_ATTRIBUTE(string_index, first_to_check) \
+#define CERES_SCANF_ATTRIBUTE(string_index, first_to_check) \
__attribute__((__format__ (__scanf__, string_index, first_to_check)))
#else
-#define PRINTF_ATTRIBUTE(string_index, first_to_check)
+#define CERES_PRINTF_ATTRIBUTE(string_index, first_to_check)
#endif
// Return a C++ string.
extern string StringPrintf(const char* format, ...)
// Tell the compiler to do printf format string checking.
- PRINTF_ATTRIBUTE(1,2);
+ CERES_PRINTF_ATTRIBUTE(1,2);
// Store result into a supplied string and return it.
extern const string& SStringPrintf(string* dst, const char* format, ...)
// Tell the compiler to do printf format string checking.
- PRINTF_ATTRIBUTE(2,3);
+ CERES_PRINTF_ATTRIBUTE(2,3);
// Append result to a supplied string.
extern void StringAppendF(string* dst, const char* format, ...)
// Tell the compiler to do printf format string checking.
- PRINTF_ATTRIBUTE(2,3);
+ CERES_PRINTF_ATTRIBUTE(2,3);
// Lower-level routine that takes a va_list and appends to a specified string.
// All other routines are just convenience wrappers around it.
extern void StringAppendV(string* dst, const char* format, va_list ap);
-#undef PRINTF_ATTRIBUTE
+#undef CERES_PRINTF_ATTRIBUTE
} // namespace internal
} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/suitesparse.cc b/extern/libmv/third_party/ceres/internal/ceres/suitesparse.cc
index 1cf6a7496a7..cf3c48f84e6 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/suitesparse.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/suitesparse.cc
@@ -29,15 +29,14 @@
// Author: sameeragarwal@google.com (Sameer Agarwal)
#ifndef CERES_NO_SUITESPARSE
-
#include "ceres/suitesparse.h"
+#include <vector>
#include "cholmod.h"
#include "ceres/compressed_row_sparse_matrix.h"
#include "ceres/triplet_sparse_matrix.h"
namespace ceres {
namespace internal {
-
cholmod_sparse* SuiteSparse::CreateSparseMatrix(TripletSparseMatrix* A) {
cholmod_triplet triplet;
@@ -111,6 +110,13 @@ cholmod_dense* SuiteSparse::CreateDenseVector(const double* x,
}
cholmod_factor* SuiteSparse::AnalyzeCholesky(cholmod_sparse* A) {
+ // Cholmod can try multiple re-ordering strategies to find a fill
+ // reducing ordering. Here we just tell it use AMD with automatic
+ // matrix dependence choice of supernodal versus simplicial
+ // factorization.
+ cc_.nmethods = 1;
+ cc_.method[0].ordering = CHOLMOD_AMD;
+ cc_.supernodal = CHOLMOD_AUTO;
cholmod_factor* factor = cholmod_analyze(A, &cc_);
CHECK_EQ(cc_.status, CHOLMOD_OK)
<< "Cholmod symbolic analysis failed " << cc_.status;
@@ -118,6 +124,153 @@ cholmod_factor* SuiteSparse::AnalyzeCholesky(cholmod_sparse* A) {
return factor;
}
+cholmod_factor* SuiteSparse::BlockAnalyzeCholesky(
+ cholmod_sparse* A,
+ const vector<int>& row_blocks,
+ const vector<int>& col_blocks) {
+ vector<int> ordering;
+ if (!BlockAMDOrdering(A, row_blocks, col_blocks, &ordering)) {
+ return NULL;
+ }
+ return AnalyzeCholeskyWithUserOrdering(A, ordering);
+}
+
+cholmod_factor* SuiteSparse::AnalyzeCholeskyWithUserOrdering(cholmod_sparse* A,
+ const vector<int>& ordering) {
+ CHECK_EQ(ordering.size(), A->nrow);
+ cc_.nmethods = 1 ;
+ cc_.method[0].ordering = CHOLMOD_GIVEN;
+ cholmod_factor* factor =
+ cholmod_analyze_p(A, const_cast<int*>(&ordering[0]), NULL, 0, &cc_);
+ CHECK_EQ(cc_.status, CHOLMOD_OK)
+ << "Cholmod symbolic analysis failed " << cc_.status;
+ CHECK_NOTNULL(factor);
+ return factor;
+}
+
+bool SuiteSparse::BlockAMDOrdering(const cholmod_sparse* A,
+ const vector<int>& row_blocks,
+ const vector<int>& col_blocks,
+ vector<int>* ordering) {
+ const int num_row_blocks = row_blocks.size();
+ const int num_col_blocks = col_blocks.size();
+
+ // Arrays storing the compressed column structure of the matrix
+ // incoding the block sparsity of A.
+ vector<int> block_cols;
+ vector<int> block_rows;
+
+ ScalarMatrixToBlockMatrix(A,
+ row_blocks,
+ col_blocks,
+ &block_rows,
+ &block_cols);
+
+ cholmod_sparse_struct block_matrix;
+ block_matrix.nrow = num_row_blocks;
+ block_matrix.ncol = num_col_blocks;
+ block_matrix.nzmax = block_rows.size();
+ block_matrix.p = reinterpret_cast<void*>(&block_cols[0]);
+ block_matrix.i = reinterpret_cast<void*>(&block_rows[0]);
+ block_matrix.x = NULL;
+ block_matrix.stype = A->stype;
+ block_matrix.itype = CHOLMOD_INT;
+ block_matrix.xtype = CHOLMOD_PATTERN;
+ block_matrix.dtype = CHOLMOD_DOUBLE;
+ block_matrix.sorted = 1;
+ block_matrix.packed = 1;
+
+ vector<int> block_ordering(num_row_blocks);
+ if (!cholmod_amd(&block_matrix, NULL, 0, &block_ordering[0], &cc_)) {
+ return false;
+ }
+
+ BlockOrderingToScalarOrdering(row_blocks, block_ordering, ordering);
+ return true;
+}
+
+void SuiteSparse::ScalarMatrixToBlockMatrix(const cholmod_sparse* A,
+ const vector<int>& row_blocks,
+ const vector<int>& col_blocks,
+ vector<int>* block_rows,
+ vector<int>* block_cols) {
+ CHECK_NOTNULL(block_rows)->clear();
+ CHECK_NOTNULL(block_cols)->clear();
+ const int num_row_blocks = row_blocks.size();
+ const int num_col_blocks = col_blocks.size();
+
+ vector<int> row_block_starts(num_row_blocks);
+ for (int i = 0, cursor = 0; i < num_row_blocks; ++i) {
+ row_block_starts[i] = cursor;
+ cursor += row_blocks[i];
+ }
+
+ // The reinterpret_cast is needed here because CHOLMOD stores arrays
+ // as void*.
+ const int* scalar_cols = reinterpret_cast<const int*>(A->p);
+ const int* scalar_rows = reinterpret_cast<const int*>(A->i);
+
+ // This loop extracts the block sparsity of the scalar sparse matrix
+ // A. It does so by iterating over the columns, but only considering
+ // the columns corresponding to the first element of each column
+ // block. Within each column, the inner loop iterates over the rows,
+ // and detects the presence of a row block by checking for the
+ // presence of a non-zero entry corresponding to its first element.
+ block_cols->push_back(0);
+ int c = 0;
+ for (int col_block = 0; col_block < num_col_blocks; ++col_block) {
+ int column_size = 0;
+ for (int idx = scalar_cols[c]; idx < scalar_cols[c + 1]; ++idx) {
+ vector<int>::const_iterator it = lower_bound(row_block_starts.begin(),
+ row_block_starts.end(),
+ scalar_rows[idx]);
+ // Since we are using lower_bound, it will return the row id
+ // where the row block starts. For everything but the first row
+ // of the block, where these values will be the same, we can
+ // skip, as we only need the first row to detect the presence of
+ // the block.
+ //
+ // For rows all but the first row in the last row block,
+ // lower_bound will return row_block_starts.end(), but those can
+ // be skipped like the rows in other row blocks too.
+ if (it == row_block_starts.end() || *it != scalar_rows[idx]) {
+ continue;
+ }
+
+ block_rows->push_back(it - row_block_starts.begin());
+ ++column_size;
+ }
+ block_cols->push_back(block_cols->back() + column_size);
+ c += col_blocks[col_block];
+ }
+}
+
+void SuiteSparse::BlockOrderingToScalarOrdering(
+ const vector<int>& blocks,
+ const vector<int>& block_ordering,
+ vector<int>* scalar_ordering) {
+ CHECK_EQ(blocks.size(), block_ordering.size());
+ const int num_blocks = blocks.size();
+
+ // block_starts = [0, block1, block1 + block2 ..]
+ vector<int> block_starts(num_blocks);
+ for (int i = 0, cursor = 0; i < num_blocks ; ++i) {
+ block_starts[i] = cursor;
+ cursor += blocks[i];
+ }
+
+ scalar_ordering->resize(block_starts.back() + blocks.back());
+ int cursor = 0;
+ for (int i = 0; i < num_blocks; ++i) {
+ const int block_id = block_ordering[i];
+ const int block_size = blocks[block_id];
+ int block_position = block_starts[block_id];
+ for (int j = 0; j < block_size; ++j) {
+ (*scalar_ordering)[cursor++] = block_position++;
+ }
+ }
+}
+
bool SuiteSparse::Cholesky(cholmod_sparse* A, cholmod_factor* L) {
CHECK_NOTNULL(A);
CHECK_NOTNULL(L);
diff --git a/extern/libmv/third_party/ceres/internal/ceres/suitesparse.h b/extern/libmv/third_party/ceres/internal/ceres/suitesparse.h
index 091e67a69a9..eb691c0c0ed 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/suitesparse.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/suitesparse.h
@@ -37,6 +37,7 @@
#include <cstring>
#include <string>
+#include <vector>
#include <glog/logging.h>
#include "cholmod.h"
@@ -105,12 +106,35 @@ class SuiteSparse {
cholmod_sdmult(A, 0, alpha_, beta_, x, y, &cc_);
}
- // Analyze the sparsity structure of the matrix A compute the
- // symbolic factorization of A. A is not modified, only the pattern
- // of non-zeros of A is used, the actual numerical values in A are
- // of no consequence. Caller owns the result.
+ // Find an ordering of A or AA' (if A is unsymmetric) that minimizes
+ // the fill-in in the Cholesky factorization of the corresponding
+ // matrix. This is done by using the AMD algorithm.
+ //
+ // Using this ordering, the symbolic Cholesky factorization of A (or
+ // AA') is computed and returned.
+ //
+ // A is not modified, only the pattern of non-zeros of A is used,
+ // the actual numerical values in A are of no consequence.
+ //
+ // Caller owns the result.
cholmod_factor* AnalyzeCholesky(cholmod_sparse* A);
+ cholmod_factor* BlockAnalyzeCholesky(cholmod_sparse* A,
+ const vector<int>& row_blocks,
+ const vector<int>& col_blocks);
+
+ // If A is symmetric, then compute the symbolic Cholesky
+ // factorization of A(ordering, ordering). If A is unsymmetric, then
+ // compute the symbolic factorization of
+ // A(ordering,:) A(ordering,:)'.
+ //
+ // A is not modified, only the pattern of non-zeros of A is used,
+ // the actual numerical values in A are of no consequence.
+ //
+ // Caller owns the result.
+ cholmod_factor* AnalyzeCholeskyWithUserOrdering(cholmod_sparse* A,
+ const vector<int>& ordering);
+
// Use the symbolic factorization in L, to find the numerical
// factorization for the matrix A or AA^T. Return true if
// successful, false otherwise. L contains the numeric factorization
@@ -129,6 +153,56 @@ class SuiteSparse {
cholmod_factor* L,
cholmod_dense* b);
+ // By virtue of the modeling layer in Ceres being block oriented,
+ // all the matrices used by Ceres are also block oriented. When
+ // doing sparse direct factorization of these matrices the
+ // fill-reducing ordering algorithms (in particular AMD) can either
+ // be run on the block or the scalar form of these matrices. The two
+ // SuiteSparse::AnalyzeCholesky methods allows the the client to
+ // compute the symbolic factorization of a matrix by either using
+ // AMD on the matrix or a user provided ordering of the rows.
+ //
+ // But since the underlying matrices are block oriented, it is worth
+ // running AMD on just the block structre of these matrices and then
+ // lifting these block orderings to a full scalar ordering. This
+ // preserves the block structure of the permuted matrix, and exposes
+ // more of the super-nodal structure of the matrix to the numerical
+ // factorization routines.
+ //
+ // Find the block oriented AMD ordering of a matrix A, whose row and
+ // column blocks are given by row_blocks, and col_blocks
+ // respectively. The matrix may or may not be symmetric. The entries
+ // of col_blocks do not need to sum to the number of columns in
+ // A. If this is the case, only the first sum(col_blocks) are used
+ // to compute the ordering.
+ bool BlockAMDOrdering(const cholmod_sparse* A,
+ const vector<int>& row_blocks,
+ const vector<int>& col_blocks,
+ vector<int>* ordering);
+
+ // Given a set of blocks and a permutation of these blocks, compute
+ // the corresponding "scalar" ordering, where the scalar ordering of
+ // size sum(blocks).
+ static void BlockOrderingToScalarOrdering(const vector<int>& blocks,
+ const vector<int>& block_ordering,
+ vector<int>* scalar_ordering);
+
+ // Extract the block sparsity pattern of the scalar sparse matrix
+ // A and return it in compressed column form. The compressed column
+ // form is stored in two vectors block_rows, and block_cols, which
+ // correspond to the row and column arrays in a compressed column sparse
+ // matrix.
+ //
+ // If c_ij is the block in the matrix A corresponding to row block i
+ // and column block j, then it is expected that A contains at least
+ // one non-zero entry corresponding to the top left entry of c_ij,
+ // as that entry is used to detect the presence of a non-zero c_ij.
+ static void ScalarMatrixToBlockMatrix(const cholmod_sparse* A,
+ const vector<int>& row_blocks,
+ const vector<int>& col_blocks,
+ vector<int>* block_rows,
+ vector<int>* block_cols);
+
void Free(cholmod_sparse* m) { cholmod_free_sparse(&m, &cc_); }
void Free(cholmod_dense* m) { cholmod_free_dense(&m, &cc_); }
void Free(cholmod_factor* m) { cholmod_free_factor(&m, &cc_); }
diff --git a/extern/libmv/third_party/ceres/internal/ceres/triplet_sparse_matrix.cc b/extern/libmv/third_party/ceres/internal/ceres/triplet_sparse_matrix.cc
index 247ab2e697b..ed8677ea18a 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/triplet_sparse_matrix.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/triplet_sparse_matrix.cc
@@ -32,12 +32,12 @@
#include <algorithm>
#include <cstddef>
-#include <glog/logging.h>
-#include "ceres/matrix_proto.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/port.h"
#include "ceres/internal/scoped_ptr.h"
+#include "ceres/matrix_proto.h"
#include "ceres/types.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -82,7 +82,7 @@ TripletSparseMatrix::TripletSparseMatrix(const TripletSparseMatrix& orig)
CopyData(orig);
}
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
TripletSparseMatrix::TripletSparseMatrix(const SparseMatrixProto& outer_proto) {
CHECK(outer_proto.has_triplet_matrix());
@@ -130,7 +130,7 @@ bool TripletSparseMatrix::AllTripletsWithinBounds() const {
void TripletSparseMatrix::Reserve(int new_max_num_nonzeros) {
CHECK_LE(num_nonzeros_, new_max_num_nonzeros)
- << "Reallocation will cause data loss";
+ << "Reallocation will cause data loss";
// Nothing to do if we have enough space already.
if (new_max_num_nonzeros <= max_num_nonzeros_)
@@ -214,7 +214,7 @@ void TripletSparseMatrix::ToDenseMatrix(Matrix* dense_matrix) const {
}
}
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
void TripletSparseMatrix::ToProto(SparseMatrixProto *proto) const {
proto->Clear();
diff --git a/extern/libmv/third_party/ceres/internal/ceres/triplet_sparse_matrix.h b/extern/libmv/third_party/ceres/internal/ceres/triplet_sparse_matrix.h
index 300e74d0bbc..89a645bd879 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/triplet_sparse_matrix.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/triplet_sparse_matrix.h
@@ -50,7 +50,7 @@ class TripletSparseMatrix : public SparseMatrix {
TripletSparseMatrix();
TripletSparseMatrix(int num_rows, int num_cols, int max_num_nonzeros);
explicit TripletSparseMatrix(const TripletSparseMatrix& orig);
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
explicit TripletSparseMatrix(const SparseMatrixProto& proto);
#endif
@@ -65,7 +65,7 @@ class TripletSparseMatrix : public SparseMatrix {
virtual void SquaredColumnNorm(double* x) const;
virtual void ScaleColumns(const double* scale);
virtual void ToDenseMatrix(Matrix* dense_matrix) const;
-#ifndef CERES_DONT_HAVE_PROTOCOL_BUFFERS
+#ifndef CERES_NO_PROTOCOL_BUFFERS
virtual void ToProto(SparseMatrixProto *proto) const;
#endif
virtual void ToTextFile(FILE* file) const;
diff --git a/extern/libmv/third_party/ceres/internal/ceres/trust_region_minimizer.cc b/extern/libmv/third_party/ceres/internal/ceres/trust_region_minimizer.cc
new file mode 100644
index 00000000000..76c4f8a7580
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/trust_region_minimizer.cc
@@ -0,0 +1,550 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+
+#include "ceres/trust_region_minimizer.h"
+
+#include <algorithm>
+#include <cstdlib>
+#include <cmath>
+#include <cstring>
+#include <limits>
+#include <string>
+#include <vector>
+
+#include "Eigen/Core"
+#include "ceres/array_utils.h"
+#include "ceres/evaluator.h"
+#include "ceres/internal/eigen.h"
+#include "ceres/internal/scoped_ptr.h"
+#include "ceres/linear_least_squares_problems.h"
+#include "ceres/sparse_matrix.h"
+#include "ceres/trust_region_strategy.h"
+#include "ceres/types.h"
+#include "glog/logging.h"
+
+namespace ceres {
+namespace internal {
+namespace {
+// Small constant for various floating point issues.
+const double kEpsilon = 1e-12;
+} // namespace
+
+// Execute the list of IterationCallbacks sequentially. If any one of
+// the callbacks does not return SOLVER_CONTINUE, then stop and return
+// its status.
+CallbackReturnType TrustRegionMinimizer::RunCallbacks(
+ const IterationSummary& iteration_summary) {
+ for (int i = 0; i < options_.callbacks.size(); ++i) {
+ const CallbackReturnType status =
+ (*options_.callbacks[i])(iteration_summary);
+ if (status != SOLVER_CONTINUE) {
+ return status;
+ }
+ }
+ return SOLVER_CONTINUE;
+}
+
+// Compute a scaling vector that is used to improve the conditioning
+// of the Jacobian.
+void TrustRegionMinimizer::EstimateScale(const SparseMatrix& jacobian,
+ double* scale) const {
+ jacobian.SquaredColumnNorm(scale);
+ for (int i = 0; i < jacobian.num_cols(); ++i) {
+ scale[i] = 1.0 / (kEpsilon + sqrt(scale[i]));
+ }
+}
+
+void TrustRegionMinimizer::Init(const Minimizer::Options& options) {
+ options_ = options;
+ sort(options_.lsqp_iterations_to_dump.begin(),
+ options_.lsqp_iterations_to_dump.end());
+}
+
+bool TrustRegionMinimizer::MaybeDumpLinearLeastSquaresProblem(
+ const int iteration,
+ const SparseMatrix* jacobian,
+ const double* residuals,
+ const double* step) const {
+ // TODO(sameeragarwal): Since the use of trust_region_radius has
+ // moved inside TrustRegionStrategy, its not clear how we dump the
+ // regularization vector/matrix anymore.
+ //
+ // Doing this right requires either an API change to the
+ // TrustRegionStrategy and/or how LinearLeastSquares problems are
+ // stored on disk.
+ //
+ // For now, we will just not dump the regularizer.
+ return (!binary_search(options_.lsqp_iterations_to_dump.begin(),
+ options_.lsqp_iterations_to_dump.end(),
+ iteration) ||
+ DumpLinearLeastSquaresProblem(options_.lsqp_dump_directory,
+ iteration,
+ options_.lsqp_dump_format_type,
+ jacobian,
+ NULL,
+ residuals,
+ step,
+ options_.num_eliminate_blocks));
+}
+
+void TrustRegionMinimizer::Minimize(const Minimizer::Options& options,
+ double* parameters,
+ Solver::Summary* summary) {
+ time_t start_time = time(NULL);
+ time_t iteration_start_time = start_time;
+ Init(options);
+
+ summary->termination_type = NO_CONVERGENCE;
+ summary->num_successful_steps = 0;
+ summary->num_unsuccessful_steps = 0;
+
+ Evaluator* evaluator = CHECK_NOTNULL(options_.evaluator);
+ SparseMatrix* jacobian = CHECK_NOTNULL(options_.jacobian);
+ TrustRegionStrategy* strategy = CHECK_NOTNULL(options_.trust_region_strategy);
+
+ const int num_parameters = evaluator->NumParameters();
+ const int num_effective_parameters = evaluator->NumEffectiveParameters();
+ const int num_residuals = evaluator->NumResiduals();
+
+ VectorRef x_min(parameters, num_parameters);
+ Vector x = x_min;
+ double x_norm = x.norm();
+
+ Vector residuals(num_residuals);
+ Vector trust_region_step(num_effective_parameters);
+ Vector delta(num_effective_parameters);
+ Vector x_plus_delta(num_parameters);
+ Vector gradient(num_effective_parameters);
+ Vector model_residuals(num_residuals);
+ Vector scale(num_effective_parameters);
+
+ IterationSummary iteration_summary;
+ iteration_summary.iteration = 0;
+ iteration_summary.step_is_valid = false;
+ iteration_summary.step_is_successful = false;
+ iteration_summary.cost = summary->initial_cost;
+ iteration_summary.cost_change = 0.0;
+ iteration_summary.gradient_max_norm = 0.0;
+ iteration_summary.step_norm = 0.0;
+ iteration_summary.relative_decrease = 0.0;
+ iteration_summary.trust_region_radius = strategy->Radius();
+ // TODO(sameeragarwal): Rename eta to linear_solver_accuracy or
+ // something similar across the board.
+ iteration_summary.eta = options_.eta;
+ iteration_summary.linear_solver_iterations = 0;
+ iteration_summary.step_solver_time_in_seconds = 0;
+
+ // Do initial cost and Jacobian evaluation.
+ double cost = 0.0;
+ if (!evaluator->Evaluate(x.data(), &cost, residuals.data(), NULL, jacobian)) {
+ LOG(WARNING) << "Terminating: Residual and Jacobian evaluation failed.";
+ summary->termination_type = NUMERICAL_FAILURE;
+ return;
+ }
+
+ int num_consecutive_nonmonotonic_steps = 0;
+ double minimum_cost = cost;
+ double reference_cost = cost;
+ double accumulated_reference_model_cost_change = 0.0;
+ double candidate_cost = cost;
+ double accumulated_candidate_model_cost_change = 0.0;
+
+ gradient.setZero();
+ jacobian->LeftMultiply(residuals.data(), gradient.data());
+ iteration_summary.gradient_max_norm = gradient.lpNorm<Eigen::Infinity>();
+
+ if (options_.jacobi_scaling) {
+ EstimateScale(*jacobian, scale.data());
+ jacobian->ScaleColumns(scale.data());
+ } else {
+ scale.setOnes();
+ }
+
+ // The initial gradient max_norm is bounded from below so that we do
+ // not divide by zero.
+ const double gradient_max_norm_0 =
+ max(iteration_summary.gradient_max_norm, kEpsilon);
+ const double absolute_gradient_tolerance =
+ options_.gradient_tolerance * gradient_max_norm_0;
+
+ if (iteration_summary.gradient_max_norm <= absolute_gradient_tolerance) {
+ summary->termination_type = GRADIENT_TOLERANCE;
+ VLOG(1) << "Terminating: Gradient tolerance reached."
+ << "Relative gradient max norm: "
+ << iteration_summary.gradient_max_norm / gradient_max_norm_0
+ << " <= " << options_.gradient_tolerance;
+ return;
+ }
+
+ iteration_summary.iteration_time_in_seconds =
+ time(NULL) - iteration_start_time;
+ iteration_summary.cumulative_time_in_seconds = time(NULL) - start_time +
+ summary->preprocessor_time_in_seconds;
+ summary->iterations.push_back(iteration_summary);
+
+ // Call the various callbacks.
+ switch (RunCallbacks(iteration_summary)) {
+ case SOLVER_TERMINATE_SUCCESSFULLY:
+ summary->termination_type = USER_SUCCESS;
+ VLOG(1) << "Terminating: User callback returned USER_SUCCESS.";
+ return;
+ case SOLVER_ABORT:
+ summary->termination_type = USER_ABORT;
+ VLOG(1) << "Terminating: User callback returned USER_ABORT.";
+ return;
+ case SOLVER_CONTINUE:
+ break;
+ default:
+ LOG(FATAL) << "Unknown type of user callback status";
+ }
+
+ int num_consecutive_invalid_steps = 0;
+ while (true) {
+ iteration_start_time = time(NULL);
+ if (iteration_summary.iteration >= options_.max_num_iterations) {
+ summary->termination_type = NO_CONVERGENCE;
+ VLOG(1) << "Terminating: Maximum number of iterations reached.";
+ break;
+ }
+
+ const double total_solver_time = iteration_start_time - start_time +
+ summary->preprocessor_time_in_seconds;
+ if (total_solver_time >= options_.max_solver_time_in_seconds) {
+ summary->termination_type = NO_CONVERGENCE;
+ VLOG(1) << "Terminating: Maximum solver time reached.";
+ break;
+ }
+
+ iteration_summary = IterationSummary();
+ iteration_summary = summary->iterations.back();
+ iteration_summary.iteration = summary->iterations.back().iteration + 1;
+ iteration_summary.step_is_valid = false;
+ iteration_summary.step_is_successful = false;
+
+ const time_t strategy_start_time = time(NULL);
+ TrustRegionStrategy::PerSolveOptions per_solve_options;
+ per_solve_options.eta = options_.eta;
+ TrustRegionStrategy::Summary strategy_summary =
+ strategy->ComputeStep(per_solve_options,
+ jacobian,
+ residuals.data(),
+ trust_region_step.data());
+
+ iteration_summary.step_solver_time_in_seconds =
+ time(NULL) - strategy_start_time;
+ iteration_summary.linear_solver_iterations =
+ strategy_summary.num_iterations;
+
+ if (!MaybeDumpLinearLeastSquaresProblem(iteration_summary.iteration,
+ jacobian,
+ residuals.data(),
+ trust_region_step.data())) {
+ LOG(FATAL) << "Tried writing linear least squares problem: "
+ << options.lsqp_dump_directory << "but failed.";
+ }
+
+ double new_model_cost = 0.0;
+ if (strategy_summary.termination_type != FAILURE) {
+ // new_model_cost = 1/2 |f + J * step|^2
+ model_residuals = residuals;
+ jacobian->RightMultiply(trust_region_step.data(), model_residuals.data());
+ new_model_cost = model_residuals.squaredNorm() / 2.0;
+
+ // In exact arithmetic, this would never be the case. But poorly
+ // conditioned matrices can give rise to situations where the
+ // new_model_cost can actually be larger than half the squared
+ // norm of the residual vector. We allow for small tolerance
+ // around cost and beyond that declare the step to be invalid.
+ if ((1.0 - new_model_cost / cost) < -kEpsilon) {
+ VLOG(1) << "Invalid step: current_cost: " << cost
+ << " new_model_cost " << new_model_cost
+ << " absolute difference " << (cost - new_model_cost)
+ << " relative difference " << (1.0 - new_model_cost/cost);
+ } else {
+ iteration_summary.step_is_valid = true;
+ }
+ }
+
+ if (!iteration_summary.step_is_valid) {
+ // Invalid steps can happen due to a number of reasons, and we
+ // allow a limited number of successive failures, and return with
+ // NUMERICAL_FAILURE if this limit is exceeded.
+ if (++num_consecutive_invalid_steps >=
+ options_.max_num_consecutive_invalid_steps) {
+ summary->termination_type = NUMERICAL_FAILURE;
+ LOG(WARNING) << "Terminating. Number of successive invalid steps more "
+ << "than "
+ << "Solver::Options::max_num_consecutive_invalid_steps: "
+ << options_.max_num_consecutive_invalid_steps;
+ return;
+ }
+
+ // We are going to try and reduce the trust region radius and
+ // solve again. To do this, we are going to treat this iteration
+ // as an unsuccessful iteration. Since the various callbacks are
+ // still executed, we are going to fill the iteration summary
+ // with data that assumes a step of length zero and no progress.
+ iteration_summary.cost = cost;
+ iteration_summary.cost_change = 0.0;
+ iteration_summary.gradient_max_norm =
+ summary->iterations.back().gradient_max_norm;
+ iteration_summary.step_norm = 0.0;
+ iteration_summary.relative_decrease = 0.0;
+ iteration_summary.eta = options_.eta;
+ } else {
+ // The step is numerically valid, so now we can judge its quality.
+ num_consecutive_invalid_steps = 0;
+
+ // We allow some slop around 0, and clamp the model_cost_change
+ // at kEpsilon * min(1.0, cost) from below.
+ //
+ // In exact arithmetic this should never be needed, as we are
+ // guaranteed to new_model_cost <= cost. However, due to various
+ // numerical issues, it is possible that new_model_cost is
+ // nearly equal to cost, and the difference is a small negative
+ // number. To make sure that the relative_decrease computation
+ // remains sane, as clamp the difference (cost - new_model_cost)
+ // from below at a small positive number.
+ //
+ // This number is the minimum of kEpsilon * (cost, 1.0), which
+ // ensures that it will never get too large in absolute value,
+ // while scaling down proportionally with the magnitude of the
+ // cost. This is important for problems where the minimum of the
+ // objective function is near zero.
+ const double model_cost_change =
+ max(kEpsilon * min(1.0, cost), cost - new_model_cost);
+
+ // Undo the Jacobian column scaling.
+ delta = (trust_region_step.array() * scale.array()).matrix();
+ iteration_summary.step_norm = delta.norm();
+
+ // Convergence based on parameter_tolerance.
+ const double step_size_tolerance = options_.parameter_tolerance *
+ (x_norm + options_.parameter_tolerance);
+ if (iteration_summary.step_norm <= step_size_tolerance) {
+ VLOG(1) << "Terminating. Parameter tolerance reached. "
+ << "relative step_norm: "
+ << iteration_summary.step_norm /
+ (x_norm + options_.parameter_tolerance)
+ << " <= " << options_.parameter_tolerance;
+ summary->termination_type = PARAMETER_TOLERANCE;
+ return;
+ }
+
+ if (!evaluator->Plus(x.data(), delta.data(), x_plus_delta.data())) {
+ summary->termination_type = NUMERICAL_FAILURE;
+ LOG(WARNING) << "Terminating. Failed to compute "
+ << "Plus(x, delta, x_plus_delta).";
+ return;
+ }
+
+ // Try this step.
+ double new_cost;
+ if (!evaluator->Evaluate(x_plus_delta.data(),
+ &new_cost,
+ NULL, NULL, NULL)) {
+ // If the evaluation of the new cost fails, treat it as a step
+ // with high cost.
+ LOG(WARNING) << "Step failed to evaluate. "
+ << "Treating it as step with infinite cost";
+ new_cost = numeric_limits<double>::max();
+ }
+
+ VLOG(2) << "old cost: " << cost << " new cost: " << new_cost;
+ iteration_summary.cost_change = cost - new_cost;
+ const double absolute_function_tolerance =
+ options_.function_tolerance * cost;
+ if (fabs(iteration_summary.cost_change) < absolute_function_tolerance) {
+ VLOG(1) << "Terminating. Function tolerance reached. "
+ << "|cost_change|/cost: "
+ << fabs(iteration_summary.cost_change) / cost
+ << " <= " << options_.function_tolerance;
+ summary->termination_type = FUNCTION_TOLERANCE;
+ return;
+ }
+
+ const double relative_decrease =
+ iteration_summary.cost_change / model_cost_change;
+
+ const double historical_relative_decrease =
+ (reference_cost - new_cost) /
+ (accumulated_reference_model_cost_change + model_cost_change);
+
+ // If monotonic steps are being used, then the relative_decrease
+ // is the usual ratio of the change in objective function value
+ // divided by the change in model cost.
+ //
+ // If non-monotonic steps are allowed, then we take the maximum
+ // of the relative_decrease and the
+ // historical_relative_decrease, which measures the increase
+ // from a reference iteration. The model cost change is
+ // estimated by accumulating the model cost changes since the
+ // reference iteration. The historical relative_decrease offers
+ // a boost to a step which is not too bad compared to the
+ // reference iteration, allowing for non-monotonic steps.
+ iteration_summary.relative_decrease =
+ options.use_nonmonotonic_steps
+ ? max(relative_decrease, historical_relative_decrease)
+ : relative_decrease;
+
+ iteration_summary.step_is_successful =
+ iteration_summary.relative_decrease > options_.min_relative_decrease;
+
+ if (iteration_summary.step_is_successful) {
+ accumulated_candidate_model_cost_change += model_cost_change;
+ accumulated_reference_model_cost_change += model_cost_change;
+ if (relative_decrease <= options_.min_relative_decrease) {
+ VLOG(2) << "Non-monotonic step! "
+ << " relative_decrease: " << relative_decrease
+ << " historical_relative_decrease: "
+ << historical_relative_decrease;
+ }
+ }
+ }
+
+ if (iteration_summary.step_is_successful) {
+ ++summary->num_successful_steps;
+ strategy->StepAccepted(iteration_summary.relative_decrease);
+ x = x_plus_delta;
+ x_norm = x.norm();
+
+ // Step looks good, evaluate the residuals and Jacobian at this
+ // point.
+ if (!evaluator->Evaluate(x.data(),
+ &cost,
+ residuals.data(),
+ NULL,
+ jacobian)) {
+ summary->termination_type = NUMERICAL_FAILURE;
+ LOG(WARNING) << "Terminating: Residual and Jacobian evaluation failed.";
+ return;
+ }
+
+ gradient.setZero();
+ jacobian->LeftMultiply(residuals.data(), gradient.data());
+ iteration_summary.gradient_max_norm = gradient.lpNorm<Eigen::Infinity>();
+
+ if (iteration_summary.gradient_max_norm <= absolute_gradient_tolerance) {
+ summary->termination_type = GRADIENT_TOLERANCE;
+ VLOG(1) << "Terminating: Gradient tolerance reached."
+ << "Relative gradient max norm: "
+ << iteration_summary.gradient_max_norm / gradient_max_norm_0
+ << " <= " << options_.gradient_tolerance;
+ return;
+ }
+
+ if (options_.jacobi_scaling) {
+ jacobian->ScaleColumns(scale.data());
+ }
+
+ // Update the best, reference and candidate iterates.
+ //
+ // Based on algorithm 10.1.2 (page 357) of "Trust Region
+ // Methods" by Conn Gould & Toint, or equations 33-40 of
+ // "Non-monotone trust-region algorithms for nonlinear
+ // optimization subject to convex constraints" by Phil Toint,
+ // Mathematical Programming, 77, 1997.
+ if (cost < minimum_cost) {
+ // A step that improves solution quality was found.
+ x_min = x;
+ minimum_cost = cost;
+ // Set the candidate iterate to the current point.
+ candidate_cost = cost;
+ num_consecutive_nonmonotonic_steps = 0;
+ accumulated_candidate_model_cost_change = 0.0;
+ } else {
+ ++num_consecutive_nonmonotonic_steps;
+ if (cost > candidate_cost) {
+ // The current iterate is has a higher cost than the
+ // candidate iterate. Set the candidate to this point.
+ VLOG(2) << "Updating the candidate iterate to the current point.";
+ candidate_cost = cost;
+ accumulated_candidate_model_cost_change = 0.0;
+ }
+
+ // At this point we have made too many non-monotonic steps and
+ // we are going to reset the value of the reference iterate so
+ // as to force the algorithm to descend.
+ //
+ // This is the case because the candidate iterate has a value
+ // greater than minimum_cost but smaller than the reference
+ // iterate.
+ if (num_consecutive_nonmonotonic_steps ==
+ options.max_consecutive_nonmonotonic_steps) {
+ VLOG(2) << "Resetting the reference point to the candidate point";
+ reference_cost = candidate_cost;
+ accumulated_reference_model_cost_change =
+ accumulated_candidate_model_cost_change;
+ }
+ }
+ } else {
+ ++summary->num_unsuccessful_steps;
+ if (iteration_summary.step_is_valid) {
+ strategy->StepRejected(iteration_summary.relative_decrease);
+ } else {
+ strategy->StepIsInvalid();
+ }
+ }
+
+ iteration_summary.cost = cost + summary->fixed_cost;
+ iteration_summary.trust_region_radius = strategy->Radius();
+ if (iteration_summary.trust_region_radius <
+ options_.min_trust_region_radius) {
+ summary->termination_type = PARAMETER_TOLERANCE;
+ VLOG(1) << "Termination. Minimum trust region radius reached.";
+ return;
+ }
+
+ iteration_summary.iteration_time_in_seconds =
+ time(NULL) - iteration_start_time;
+ iteration_summary.cumulative_time_in_seconds = time(NULL) - start_time +
+ summary->preprocessor_time_in_seconds;
+ summary->iterations.push_back(iteration_summary);
+
+ switch (RunCallbacks(iteration_summary)) {
+ case SOLVER_TERMINATE_SUCCESSFULLY:
+ summary->termination_type = USER_SUCCESS;
+ VLOG(1) << "Terminating: User callback returned USER_SUCCESS.";
+ return;
+ case SOLVER_ABORT:
+ summary->termination_type = USER_ABORT;
+ VLOG(1) << "Terminating: User callback returned USER_ABORT.";
+ return;
+ case SOLVER_CONTINUE:
+ break;
+ default:
+ LOG(FATAL) << "Unknown type of user callback status";
+ }
+ }
+}
+
+
+} // namespace internal
+} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/trust_region_minimizer.h b/extern/libmv/third_party/ceres/internal/ceres/trust_region_minimizer.h
new file mode 100644
index 00000000000..a4f5ba3674d
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/trust_region_minimizer.h
@@ -0,0 +1,67 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+
+#ifndef CERES_INTERNAL_TRUST_REGION_MINIMIZER_H_
+#define CERES_INTERNAL_TRUST_REGION_MINIMIZER_H_
+
+#include "ceres/minimizer.h"
+#include "ceres/solver.h"
+#include "ceres/types.h"
+
+namespace ceres {
+namespace internal {
+
+// Generic trust region minimization algorithm. The heavy lifting is
+// done by a TrustRegionStrategy object passed in as one of the
+// arguments to the Minimize method.
+//
+// For example usage, see SolverImpl::Minimize.
+class TrustRegionMinimizer : public Minimizer {
+ public:
+ ~TrustRegionMinimizer() {}
+ virtual void Minimize(const Minimizer::Options& options,
+ double* parameters,
+ Solver::Summary* summary);
+
+ private:
+ void Init(const Minimizer::Options& options);
+ void EstimateScale(const SparseMatrix& jacobian, double* scale) const;
+ CallbackReturnType RunCallbacks(const IterationSummary& iteration_summary);
+ bool MaybeDumpLinearLeastSquaresProblem( const int iteration,
+ const SparseMatrix* jacobian,
+ const double* residuals,
+ const double* step) const;
+
+ Minimizer::Options options_;
+};
+
+} // namespace internal
+} // namespace ceres
+#endif // CERES_INTERNAL_TRUST_REGION_MINIMIZER_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/trust_region_strategy.cc b/extern/libmv/third_party/ceres/internal/ceres/trust_region_strategy.cc
new file mode 100644
index 00000000000..89bc19d084b
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/trust_region_strategy.cc
@@ -0,0 +1,27 @@
+#include "ceres/trust_region_strategy.h"
+#include "ceres/dogleg_strategy.h"
+#include "ceres/levenberg_marquardt_strategy.h"
+
+namespace ceres {
+namespace internal {
+
+TrustRegionStrategy::~TrustRegionStrategy() {}
+
+TrustRegionStrategy* TrustRegionStrategy::Create(const Options& options) {
+ switch (options.trust_region_strategy_type) {
+ case LEVENBERG_MARQUARDT:
+ return new LevenbergMarquardtStrategy(options);
+ case DOGLEG:
+ return new DoglegStrategy(options);
+ default:
+ LOG(FATAL) << "Unknown trust region strategy: "
+ << options.trust_region_strategy_type;
+ }
+
+ LOG(FATAL) << "Unknown trust region strategy: "
+ << options.trust_region_strategy_type;
+ return NULL;
+}
+
+} // namespace internal
+} // namespace ceres
diff --git a/extern/libmv/third_party/ceres/internal/ceres/trust_region_strategy.h b/extern/libmv/third_party/ceres/internal/ceres/trust_region_strategy.h
new file mode 100644
index 00000000000..391da97d5eb
--- /dev/null
+++ b/extern/libmv/third_party/ceres/internal/ceres/trust_region_strategy.h
@@ -0,0 +1,148 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2012 Google Inc. All rights reserved.
+// http://code.google.com/p/ceres-solver/
+//
+// 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.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// 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.
+//
+// Author: sameeragarwal@google.com (Sameer Agarwal)
+
+#ifndef CERES_INTERNAL_TRUST_REGION_STRATEGY_H_
+#define CERES_INTERNAL_TRUST_REGION_STRATEGY_H_
+
+#include "ceres/types.h"
+
+namespace ceres {
+namespace internal {
+
+class LinearSolver;
+class SparseMatrix;
+
+// Interface for classes implementing various trust region strategies
+// for nonlinear least squares problems.
+//
+// The object is expected to maintain and update a trust region
+// radius, which it then uses to solve for the trust region step using
+// the jacobian matrix and residual vector.
+//
+// Here the term trust region radius is used loosely, as the strategy
+// is free to treat it as guidance and violate it as need be. e.g.,
+// the LevenbergMarquardtStrategy uses the inverse of the trust region
+// radius to scale the damping term, which controls the step size, but
+// does not set a hard limit on its size.
+class TrustRegionStrategy {
+public:
+ struct Options {
+ Options()
+ : trust_region_strategy_type(LEVENBERG_MARQUARDT),
+ initial_radius(1e4),
+ max_radius(1e32),
+ lm_min_diagonal(1e-6),
+ lm_max_diagonal(1e32),
+ dogleg_type(TRADITIONAL_DOGLEG) {
+ }
+
+ TrustRegionStrategyType trust_region_strategy_type;
+ // Linear solver used for actually solving the trust region step.
+ LinearSolver* linear_solver;
+ double initial_radius;
+ double max_radius;
+
+ // Minimum and maximum values of the diagonal damping matrix used
+ // by LevenbergMarquardtStrategy. The DoglegStrategy also uses
+ // these bounds to construct a regularizing diagonal to ensure
+ // that the Gauss-Newton step computation is of full rank.
+ double lm_min_diagonal;
+ double lm_max_diagonal;
+
+ // Further specify which dogleg method to use
+ DoglegType dogleg_type;
+ };
+
+ // Per solve options.
+ struct PerSolveOptions {
+ // Forcing sequence for inexact solves.
+ double eta;
+ };
+
+ struct Summary {
+ Summary()
+ : residual_norm(0.0),
+ num_iterations(-1),
+ termination_type(FAILURE) {
+ }
+
+ // If the trust region problem is,
+ //
+ // 1/2 x'Ax + b'x + c,
+ //
+ // then
+ //
+ // residual_norm = |Ax -b|
+ double residual_norm;
+
+ // Number of iterations used by the linear solver. If a linear
+ // solver was not called (e.g., DogLegStrategy after an
+ // unsuccessful step), then this would be zero.
+ int num_iterations;
+
+ // Status of the linear solver used to solve the Newton system.
+ LinearSolverTerminationType termination_type;
+ };
+
+ virtual ~TrustRegionStrategy();
+
+ // Use the current radius to solve for the trust region step.
+ virtual Summary ComputeStep(const PerSolveOptions& per_solve_options,
+ SparseMatrix* jacobian,
+ const double* residuals,
+ double* step) = 0;
+
+ // Inform the strategy that the current step has been accepted, and
+ // that the ratio of the decrease in the non-linear objective to the
+ // decrease in the trust region model is step_quality.
+ virtual void StepAccepted(double step_quality) = 0;
+
+ // Inform the strategy that the current step has been rejected, and
+ // that the ratio of the decrease in the non-linear objective to the
+ // decrease in the trust region model is step_quality.
+ virtual void StepRejected(double step_quality) = 0;
+
+ // Inform the strategy that the current step has been rejected
+ // because it was found to be numerically invalid.
+ // StepRejected/StepAccepted will not be called for this step, and
+ // the strategy is free to do what it wants with this information.
+ virtual void StepIsInvalid() = 0;
+
+ // Current trust region radius.
+ virtual double Radius() const = 0;
+
+ // Factory.
+ static TrustRegionStrategy* Create(const Options& options);
+};
+
+} // namespace internal
+} // namespace ceres
+
+#endif // CERES_INTERNAL_TRUST_REGION_STRATEGY_H_
diff --git a/extern/libmv/third_party/ceres/internal/ceres/types.cc b/extern/libmv/third_party/ceres/internal/ceres/types.cc
index 860f8a43f37..05e573ff6d5 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/types.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/types.cc
@@ -37,8 +37,9 @@ namespace ceres {
const char* LinearSolverTypeToString(LinearSolverType solver_type) {
switch (solver_type) {
- CASESTR(SPARSE_NORMAL_CHOLESKY);
+ CASESTR(DENSE_NORMAL_CHOLESKY);
CASESTR(DENSE_QR);
+ CASESTR(SPARSE_NORMAL_CHOLESKY);
CASESTR(DENSE_SCHUR);
CASESTR(SPARSE_SCHUR);
CASESTR(ITERATIVE_SCHUR);
@@ -61,6 +62,16 @@ const char* PreconditionerTypeToString(
}
}
+const char* SparseLinearAlgebraLibraryTypeToString(
+ SparseLinearAlgebraLibraryType sparse_linear_algebra_library_type) {
+ switch (sparse_linear_algebra_library_type) {
+ CASESTR(SUITE_SPARSE);
+ CASESTR(CX_SPARSE);
+ default:
+ return "UNKNOWN";
+ }
+}
+
const char* OrderingTypeToString(OrderingType ordering_type) {
switch (ordering_type) {
CASESTR(NATURAL);
@@ -87,6 +98,28 @@ const char* SolverTerminationTypeToString(
}
}
+#if 0 /* UNUSED */
+static const char* SparseLinearAlgebraTypeToString(
+ SparseLinearAlgebraLibraryType sparse_linear_algebra_library_type) {
+ switch (sparse_linear_algebra_library_type) {
+ CASESTR(CX_SPARSE);
+ CASESTR(SUITE_SPARSE);
+ default:
+ return "UNKNOWN";
+ }
+}
+#endif
+
+const char* TrustRegionStrategyTypeToString(
+ TrustRegionStrategyType trust_region_strategy_type) {
+ switch (trust_region_strategy_type) {
+ CASESTR(LEVENBERG_MARQUARDT);
+ CASESTR(DOGLEG);
+ default:
+ return "UNKNOWN";
+ }
+}
+
#undef CASESTR
bool IsSchurType(LinearSolverType type) {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/visibility.cc b/extern/libmv/third_party/ceres/internal/ceres/visibility.cc
index fd41648a7af..564cc54493e 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/visibility.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/visibility.cc
@@ -34,11 +34,11 @@
#include <set>
#include <vector>
#include <utility>
-
-#include <glog/logging.h>
#include "ceres/block_structure.h"
#include "ceres/collections_port.h"
+#include "ceres/visibility.h"
#include "ceres/graph.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
diff --git a/extern/libmv/third_party/ceres/internal/ceres/visibility_based_preconditioner.cc b/extern/libmv/third_party/ceres/internal/ceres/visibility_based_preconditioner.cc
index aca77528215..4caad03d7a1 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/visibility_based_preconditioner.cc
+++ b/extern/libmv/third_party/ceres/internal/ceres/visibility_based_preconditioner.cc
@@ -33,11 +33,9 @@
#include <algorithm>
#include <functional>
#include <iterator>
-#include <numeric>
#include <set>
#include <utility>
#include <vector>
-#include <glog/logging.h>
#include "Eigen/Dense"
#include "ceres/block_random_access_sparse_matrix.h"
#include "ceres/block_sparse_matrix.h"
@@ -46,10 +44,11 @@
#include "ceres/detect_structure.h"
#include "ceres/graph.h"
#include "ceres/graph_algorithms.h"
+#include "ceres/internal/scoped_ptr.h"
#include "ceres/linear_solver.h"
#include "ceres/schur_eliminator.h"
#include "ceres/visibility.h"
-#include "ceres/internal/scoped_ptr.h"
+#include "glog/logging.h"
namespace ceres {
namespace internal {
@@ -253,7 +252,6 @@ void VisibilityBasedPreconditioner::ComputeBlockPairsInPreconditioner(
}
int r = 0;
- set<pair<int, int> > skipped_pairs;
const int num_row_blocks = bs.rows.size();
const int num_eliminate_blocks = options_.num_eliminate_blocks;
@@ -304,8 +302,6 @@ void VisibilityBasedPreconditioner::ComputeBlockPairsInPreconditioner(
for (; block2 != f_blocks.end(); ++block2) {
if (IsBlockPairInPreconditioner(*block1, *block2)) {
block_pairs_.insert(make_pair(*block1, *block2));
- } else {
- skipped_pairs.insert(make_pair(*block1, *block2));
}
}
}
@@ -322,17 +318,13 @@ void VisibilityBasedPreconditioner::ComputeBlockPairsInPreconditioner(
if (block1 <= block2) {
if (IsBlockPairInPreconditioner(block1, block2)) {
block_pairs_.insert(make_pair(block1, block2));
- } else {
- skipped_pairs.insert(make_pair(block1, block2));
}
}
}
}
}
- VLOG(1) << "Block pair stats: "
- << block_pairs_.size() << " included "
- << skipped_pairs.size() << " excluded";
+ VLOG(1) << "Block pair stats: " << block_pairs_.size();
}
// Initialize the SchurEliminator.
@@ -341,7 +333,6 @@ void VisibilityBasedPreconditioner::InitEliminator(
LinearSolver::Options eliminator_options;
eliminator_options.num_eliminate_blocks = options_.num_eliminate_blocks;
eliminator_options.num_threads = options_.num_threads;
- eliminator_options.constant_sparsity = true;
DetectStructure(bs, options_.num_eliminate_blocks,
&eliminator_options.row_block_size,
@@ -352,9 +343,9 @@ void VisibilityBasedPreconditioner::InitEliminator(
eliminator_->Init(options_.num_eliminate_blocks, &bs);
}
-// Compute the values of the preconditioner matrix and factorize it.
-bool VisibilityBasedPreconditioner::Compute(const BlockSparseMatrixBase& A,
- const double* D) {
+// Update the values of the preconditioner matrix and factorize it.
+bool VisibilityBasedPreconditioner::Update(const BlockSparseMatrixBase& A,
+ const double* D) {
const time_t start_time = time(NULL);
const int num_rows = m_->num_rows();
CHECK_GT(num_rows, 0);
@@ -448,12 +439,21 @@ bool VisibilityBasedPreconditioner::Factorize() {
// matrix contains the values.
lhs->stype = 1;
- // Symbolic factorization is computed if we don't already have one
- // handy.
+ // Symbolic factorization is computed if we don't already have one handy.
if (factor_ == NULL) {
- factor_ = ss_.AnalyzeCholesky(lhs);
+ if (options_.use_block_amd) {
+ factor_ = ss_.BlockAnalyzeCholesky(lhs, block_size_, block_size_);
+ } else {
+ factor_ = ss_.AnalyzeCholesky(lhs);
+ }
+
+ if (VLOG_IS_ON(2)) {
+ cholmod_print_common("Symbolic Analysis", ss_.mutable_cc());
+ }
}
+ CHECK_NOTNULL(factor_);
+
bool status = ss_.Cholesky(lhs, factor_);
ss_.Free(lhs);
return status;
diff --git a/extern/libmv/third_party/ceres/internal/ceres/visibility_based_preconditioner.h b/extern/libmv/third_party/ceres/internal/ceres/visibility_based_preconditioner.h
index fa095ca1dd8..888c65eba3a 100644
--- a/extern/libmv/third_party/ceres/internal/ceres/visibility_based_preconditioner.h
+++ b/extern/libmv/third_party/ceres/internal/ceres/visibility_based_preconditioner.h
@@ -133,7 +133,7 @@ class SchurEliminatorBase;
// options.num_eliminate_blocks = num_points;
// VisibilityBasedPreconditioner preconditioner(
// *A.block_structure(), options);
-// preconditioner.Compute(A, NULL);
+// preconditioner.Update(A, NULL);
// preconditioner.RightMultiply(x, y);
//
@@ -160,7 +160,7 @@ class VisibilityBasedPreconditioner : public LinearOperator {
const LinearSolver::Options& options);
virtual ~VisibilityBasedPreconditioner();
- // Compute the numerical value of the preconditioner for the linear
+ // Update the numerical value of the preconditioner for the linear
// system:
//
// | A | x = |b|
@@ -171,12 +171,12 @@ class VisibilityBasedPreconditioner : public LinearOperator {
//
// D can be NULL, in which case its interpreted as a diagonal matrix
// of size zero.
- bool Compute(const BlockSparseMatrixBase& A,
- const double* D);
+ bool Update(const BlockSparseMatrixBase& A, const double* D);
+
// LinearOperator interface. Since the operator is symmetric,
// LeftMultiply and num_cols are just calls to RightMultiply and
- // num_rows respectively. Compute() must be called before
+ // num_rows respectively. Update() must be called before
// RightMultiply can be called.
virtual void RightMultiply(const double* x, double* y) const;
virtual void LeftMultiply(const double* x, double* y) const {
@@ -244,7 +244,7 @@ class VisibilityBasedPreconditioner : public LinearOperator {
// Temporary vector used by RightMultiply.
cholmod_dense* tmp_rhs_;
- DISALLOW_COPY_AND_ASSIGN(VisibilityBasedPreconditioner);
+ CERES_DISALLOW_COPY_AND_ASSIGN(VisibilityBasedPreconditioner);
};
#else // SuiteSparse
// If SuiteSparse is not compiled in, the preconditioner is not
@@ -261,7 +261,7 @@ class VisibilityBasedPreconditioner : public LinearOperator {
virtual void LeftMultiply(const double* x, double* y) const {}
virtual int num_rows() const { return -1; }
virtual int num_cols() const { return -1; }
- bool Compute(const BlockSparseMatrixBase& A, const double* D) {
+ bool Update(const BlockSparseMatrixBase& A, const double* D) {
return false;
}
};
diff --git a/extern/libmv/third_party/ceres/patches/collections_port.h.mingw.patch b/extern/libmv/third_party/ceres/patches/collections_port.h.mingw.patch
index bbb366e22bc..c01a17c7992 100644
--- a/extern/libmv/third_party/ceres/patches/collections_port.h.mingw.patch
+++ b/extern/libmv/third_party/ceres/patches/collections_port.h.mingw.patch
@@ -1,10 +1,10 @@
-Index: internal/ceres/collections_port.h
-===================================================================
---- internal/ceres/collections_port.h (revision 47730)
-+++ internal/ceres/collections_port.h (working copy)
-@@ -53,7 +53,7 @@
+diff --git a/internal/ceres/collections_port.h b/internal/ceres/collections_port.h
+index a356cc0..c2fce90 100644
+--- a/internal/ceres/collections_port.h
++++ b/internal/ceres/collections_port.h
+@@ -77,7 +77,7 @@ struct HashMap : std::tr1::unordered_map<K, V> {};
template<typename K>
- struct HashSet : tr1::unordered_set<K> {};
+ struct HashSet : std::tr1::unordered_set<K> {};
-#ifdef _WIN32
+#if defined(_WIN32) && !defined(__MINGW64__) && !defined(__MINGW32__)
diff --git a/extern/libmv/third_party/ceres/patches/msvc_glog_fix.patch b/extern/libmv/third_party/ceres/patches/msvc_glog_fix.patch
new file mode 100644
index 00000000000..f3200fb8e0a
--- /dev/null
+++ b/extern/libmv/third_party/ceres/patches/msvc_glog_fix.patch
@@ -0,0 +1,50 @@
+diff --git a/internal/ceres/block_random_access_dense_matrix.cc b/internal/ceres/block_random_access_dense_matrix.cc
+index aedfc74..0f95e89 100644
+--- a/internal/ceres/block_random_access_dense_matrix.cc
++++ b/internal/ceres/block_random_access_dense_matrix.cc
+@@ -28,12 +28,12 @@
+ //
+ // Author: sameeragarwal@google.com (Sameer Agarwal)
+
++#include "glog/logging.h"
+ #include "ceres/block_random_access_dense_matrix.h"
+
+ #include <vector>
+ #include "ceres/internal/eigen.h"
+ #include "ceres/internal/scoped_ptr.h"
+-#include "glog/logging.h"
+
+ namespace ceres {
+ namespace internal {
+diff --git a/internal/ceres/block_random_access_sparse_matrix.cc b/internal/ceres/block_random_access_sparse_matrix.cc
+index f789436..9ed62ce 100644
+--- a/internal/ceres/block_random_access_sparse_matrix.cc
++++ b/internal/ceres/block_random_access_sparse_matrix.cc
+@@ -28,6 +28,7 @@
+ //
+ // Author: sameeragarwal@google.com (Sameer Agarwal)
+
++#include "glog/logging.h"
+ #include "ceres/block_random_access_sparse_matrix.h"
+
+ #include <algorithm>
+@@ -39,7 +40,6 @@
+ #include "ceres/mutex.h"
+ #include "ceres/triplet_sparse_matrix.h"
+ #include "ceres/types.h"
+-#include "glog/logging.h"
+
+ namespace ceres {
+ namespace internal {
+diff --git a/internal/ceres/schur_complement_solver.cc b/internal/ceres/schur_complement_solver.cc
+index b9224d8..2cbe78d 100644
+--- a/internal/ceres/schur_complement_solver.cc
++++ b/internal/ceres/schur_complement_solver.cc
+@@ -38,6 +38,7 @@
+ #endif // CERES_NO_CXSPARSE
+
+ #include "Eigen/Dense"
++#include "glog/logging.h"
+ #include "ceres/block_random_access_dense_matrix.h"
+ #include "ceres/block_random_access_matrix.h"
+ #include "ceres/block_random_access_sparse_matrix.h"
diff --git a/extern/libmv/third_party/ceres/patches/msvc_isfinite.patch b/extern/libmv/third_party/ceres/patches/msvc_isfinite.patch
deleted file mode 100644
index c3129d8e02b..00000000000
--- a/extern/libmv/third_party/ceres/patches/msvc_isfinite.patch
+++ /dev/null
@@ -1,15 +0,0 @@
-diff --git a/internal/ceres/residual_block_utils.cc b/internal/ceres/residual_block_utils.cc
-index ed3499b..28e0313 100644
---- a/internal/ceres/residual_block_utils.cc
-+++ b/internal/ceres/residual_block_utils.cc
-@@ -40,6 +40,10 @@
- #include "ceres/internal/eigen.h"
- #include "ceres/internal/port.h"
-
-+#ifdef _MSC_VER
-+# define isfinite _finite
-+#endif
-+
- namespace ceres {
- namespace internal {
-
diff --git a/extern/libmv/third_party/ceres/patches/no_previous_declaration_fix.patch b/extern/libmv/third_party/ceres/patches/no_previous_declaration_fix.patch
new file mode 100644
index 00000000000..03f1c500d9a
--- /dev/null
+++ b/extern/libmv/third_party/ceres/patches/no_previous_declaration_fix.patch
@@ -0,0 +1,199 @@
+diff --git a/internal/ceres/file.cc b/internal/ceres/file.cc
+index 387f359..6fe7557 100644
+--- a/internal/ceres/file.cc
++++ b/internal/ceres/file.cc
+@@ -31,6 +31,7 @@
+ // Really simple file IO.
+
+ #include <cstdio>
++#include "file.h"
+ #include "glog/logging.h"
+
+ namespace ceres {
+diff --git a/internal/ceres/linear_least_squares_problems.cc b/internal/ceres/linear_least_squares_problems.cc
+index 3e3bcd0..a91e254 100644
+--- a/internal/ceres/linear_least_squares_problems.cc
++++ b/internal/ceres/linear_least_squares_problems.cc
+@@ -573,13 +573,13 @@ LinearLeastSquaresProblem* LinearLeastSquaresProblem3() {
+ return problem;
+ }
+
+-bool DumpLinearLeastSquaresProblemToConsole(const string& directory,
+- int iteration,
+- const SparseMatrix* A,
+- const double* D,
+- const double* b,
+- const double* x,
+- int num_eliminate_blocks) {
++static bool DumpLinearLeastSquaresProblemToConsole(const string& directory,
++ int iteration,
++ const SparseMatrix* A,
++ const double* D,
++ const double* b,
++ const double* x,
++ int num_eliminate_blocks) {
+ CHECK_NOTNULL(A);
+ Matrix AA;
+ A->ToDenseMatrix(&AA);
+@@ -601,13 +601,13 @@ bool DumpLinearLeastSquaresProblemToConsole(const string& directory,
+ };
+
+ #ifndef CERES_NO_PROTOCOL_BUFFERS
+-bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
+- int iteration,
+- const SparseMatrix* A,
+- const double* D,
+- const double* b,
+- const double* x,
+- int num_eliminate_blocks) {
++static bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
++ int iteration,
++ const SparseMatrix* A,
++ const double* D,
++ const double* b,
++ const double* x,
++ int num_eliminate_blocks) {
+ CHECK_NOTNULL(A);
+ LinearLeastSquaresProblemProto lsqp;
+ A->ToProto(lsqp.mutable_a());
+@@ -641,13 +641,13 @@ bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
+ return true;
+ }
+ #else
+-bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
+- int iteration,
+- const SparseMatrix* A,
+- const double* D,
+- const double* b,
+- const double* x,
+- int num_eliminate_blocks) {
++static bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
++ int iteration,
++ const SparseMatrix* A,
++ const double* D,
++ const double* b,
++ const double* x,
++ int num_eliminate_blocks) {
+ LOG(ERROR) << "Dumping least squares problems is only "
+ << "supported when Ceres is compiled with "
+ << "protocol buffer support.";
+@@ -655,9 +655,9 @@ bool DumpLinearLeastSquaresProblemToProtocolBuffer(const string& directory,
+ }
+ #endif
+
+-void WriteArrayToFileOrDie(const string& filename,
+- const double* x,
+- const int size) {
++static void WriteArrayToFileOrDie(const string& filename,
++ const double* x,
++ const int size) {
+ CHECK_NOTNULL(x);
+ VLOG(2) << "Writing array to: " << filename;
+ FILE* fptr = fopen(filename.c_str(), "w");
+@@ -668,13 +668,13 @@ void WriteArrayToFileOrDie(const string& filename,
+ fclose(fptr);
+ }
+
+-bool DumpLinearLeastSquaresProblemToTextFile(const string& directory,
+- int iteration,
+- const SparseMatrix* A,
+- const double* D,
+- const double* b,
+- const double* x,
+- int num_eliminate_blocks) {
++static bool DumpLinearLeastSquaresProblemToTextFile(const string& directory,
++ int iteration,
++ const SparseMatrix* A,
++ const double* D,
++ const double* b,
++ const double* x,
++ int num_eliminate_blocks) {
+ CHECK_NOTNULL(A);
+ string format_string = JoinPath(directory,
+ "lm_iteration_%03d");
+diff --git a/internal/ceres/residual_block_utils.cc b/internal/ceres/residual_block_utils.cc
+index ff18e21..9442bb2 100644
+--- a/internal/ceres/residual_block_utils.cc
++++ b/internal/ceres/residual_block_utils.cc
+@@ -63,7 +63,7 @@ void InvalidateEvaluation(const ResidualBlock& block,
+
+ // Utility routine to print an array of doubles to a string. If the
+ // array pointer is NULL, it is treated as an array of zeros.
+-void AppendArrayToString(const int size, const double* x, string* result) {
++static void AppendArrayToString(const int size, const double* x, string* result) {
+ for (int i = 0; i < size; ++i) {
+ if (x == NULL) {
+ StringAppendF(result, "Not Computed ");
+diff --git a/internal/ceres/solver_impl.cc b/internal/ceres/solver_impl.cc
+index 2802a75..8ef5b98 100644
+--- a/internal/ceres/solver_impl.cc
++++ b/internal/ceres/solver_impl.cc
+@@ -685,8 +685,8 @@ bool SolverImpl::ApplyUserOrdering(const ProblemImpl& problem_impl,
+ // Find the minimum index of any parameter block to the given residual.
+ // Parameter blocks that have indices greater than num_eliminate_blocks are
+ // considered to have an index equal to num_eliminate_blocks.
+-int MinParameterBlock(const ResidualBlock* residual_block,
+- int num_eliminate_blocks) {
++static int MinParameterBlock(const ResidualBlock* residual_block,
++ int num_eliminate_blocks) {
+ int min_parameter_block_position = num_eliminate_blocks;
+ for (int i = 0; i < residual_block->NumParameterBlocks(); ++i) {
+ ParameterBlock* parameter_block = residual_block->parameter_blocks()[i];
+diff --git a/internal/ceres/split.cc b/internal/ceres/split.cc
+index 4fa1bd4..c65c8a5 100644
+--- a/internal/ceres/split.cc
++++ b/internal/ceres/split.cc
+@@ -31,6 +31,7 @@
+ #include <string>
+ #include <vector>
+ #include <iterator>
++#include "ceres/split.h"
+ #include "ceres/internal/port.h"
+
+ namespace ceres {
+diff --git a/internal/ceres/stringprintf.cc b/internal/ceres/stringprintf.cc
+index c0f3522..396a48b 100644
+--- a/internal/ceres/stringprintf.cc
++++ b/internal/ceres/stringprintf.cc
+@@ -34,6 +34,7 @@
+ #include <string>
+ #include <vector>
+
++#include "ceres/stringprintf.h"
+ #include "ceres/internal/port.h"
+
+ namespace ceres {
+diff --git a/internal/ceres/types.cc b/internal/ceres/types.cc
+index 2e950c5..05e573f 100644
+--- a/internal/ceres/types.cc
++++ b/internal/ceres/types.cc
+@@ -98,7 +98,8 @@ const char* SolverTerminationTypeToString(
+ }
+ }
+
+-const char* SparseLinearAlgebraTypeToString(
++#if 0 /* UNUSED */
++static const char* SparseLinearAlgebraTypeToString(
+ SparseLinearAlgebraLibraryType sparse_linear_algebra_library_type) {
+ switch (sparse_linear_algebra_library_type) {
+ CASESTR(CX_SPARSE);
+@@ -107,6 +108,7 @@ const char* SparseLinearAlgebraTypeToString(
+ return "UNKNOWN";
+ }
+ }
++#endif
+
+ const char* TrustRegionStrategyTypeToString(
+ TrustRegionStrategyType trust_region_strategy_type) {
+diff --git a/internal/ceres/visibility.cc b/internal/ceres/visibility.cc
+index 9d80654..564cc54 100644
+--- a/internal/ceres/visibility.cc
++++ b/internal/ceres/visibility.cc
+@@ -36,6 +36,7 @@
+ #include <utility>
+ #include "ceres/block_structure.h"
+ #include "ceres/collections_port.h"
++#include "ceres/visibility.h"
+ #include "ceres/graph.h"
+ #include "glog/logging.h"
+
diff --git a/extern/libmv/third_party/ceres/patches/series b/extern/libmv/third_party/ceres/patches/series
index dbe955ae61e..a6874318923 100644
--- a/extern/libmv/third_party/ceres/patches/series
+++ b/extern/libmv/third_party/ceres/patches/series
@@ -1 +1,3 @@
-msvc_isfinite.patch
+collections_port.h.mingw.patch
+msvc_glog_fix.patch
+no_previous_declaration_fix.patch \ No newline at end of file
diff --git a/extern/recastnavigation/Recast/Source/RecastMeshDetail.cpp b/extern/recastnavigation/Recast/Source/RecastMeshDetail.cpp
index 130c08ec369..b52da597675 100644
--- a/extern/recastnavigation/Recast/Source/RecastMeshDetail.cpp
+++ b/extern/recastnavigation/Recast/Source/RecastMeshDetail.cpp
@@ -1015,7 +1015,7 @@ bool rcBuildPolyMeshDetail(rcContext* ctx, const rcPolyMesh& mesh, const rcCompa
maxhh = rcMax(maxhh, ymax-ymin);
}
- hp.data = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxhw*maxhh, RC_ALLOC_TEMP);
+ hp.data = (unsigned short *)rcAlloc(sizeof(unsigned short)*maxhw*maxhh, RC_ALLOC_TEMP);
if (!hp.data)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'hp.data' (%d).", maxhw*maxhh);
diff --git a/intern/CMakeLists.txt b/intern/CMakeLists.txt
index 2551df6ba76..cb2fc239859 100644
--- a/intern/CMakeLists.txt
+++ b/intern/CMakeLists.txt
@@ -49,11 +49,6 @@ if(WITH_MOD_SMOKE)
add_subdirectory(smoke)
endif()
-if(WITH_MOD_DECIMATE)
- add_subdirectory(container)
- add_subdirectory(decimation)
-endif()
-
if(WITH_MOD_BOOLEAN)
add_subdirectory(bsp)
endif()
diff --git a/intern/SConscript b/intern/SConscript
index 3e40ef38705..59e412333b0 100644
--- a/intern/SConscript
+++ b/intern/SConscript
@@ -6,9 +6,7 @@ SConscript(['audaspace/SConscript',
'ghost/SConscript',
'guardedalloc/SConscript',
'moto/SConscript',
- 'container/SConscript',
'memutil/SConscript/',
- 'decimation/SConscript',
'iksolver/SConscript',
'itasc/SConscript',
'opencolorio/SConscript',
@@ -17,6 +15,9 @@ SConscript(['audaspace/SConscript',
'smoke/SConscript',
'raskter/SConscript'])
+# currently only contains headers
+# SConscript('container/SConscript')
+
if env ['WITH_BF_REMESH']:
SConscript(['dualcon/SConscript'])
diff --git a/intern/audaspace/CMakeLists.txt b/intern/audaspace/CMakeLists.txt
index dc4ca7903cd..1671194653a 100644
--- a/intern/audaspace/CMakeLists.txt
+++ b/intern/audaspace/CMakeLists.txt
@@ -94,6 +94,7 @@ set(SRC
intern/AUD_IDevice.h
intern/AUD_IFactory.h
intern/AUD_IHandle.h
+ intern/AUD_ILockable.h
intern/AUD_IReader.h
intern/AUD_IWriter.h
intern/AUD_JOSResampleFactory.cpp
@@ -108,6 +109,7 @@ set(SRC
intern/AUD_Mixer.h
intern/AUD_MixerFactory.cpp
intern/AUD_MixerFactory.h
+ intern/AUD_MutexLock.h
intern/AUD_NULLDevice.cpp
intern/AUD_NULLDevice.h
intern/AUD_PyInit.h
diff --git a/intern/audaspace/FX/AUD_ButterworthFactory.cpp b/intern/audaspace/FX/AUD_ButterworthFactory.cpp
index 5edca302ece..af1a5af97df 100644
--- a/intern/audaspace/FX/AUD_ButterworthFactory.cpp
+++ b/intern/audaspace/FX/AUD_ButterworthFactory.cpp
@@ -53,11 +53,11 @@ void AUD_ButterworthFactory::recalculateCoefficients(AUD_SampleRate rate,
float omega = 2 * tan(m_frequency * M_PI / rate);
float o2 = omega * omega;
float o4 = o2 * o2;
- float x1 = o2 + 2 * BWPB41 * omega + 4;
- float x2 = o2 + 2 * BWPB42 * omega + 4;
- float y1 = o2 - 2 * BWPB41 * omega + 4;
- float y2 = o2 - 2 * BWPB42 * omega + 4;
- float o228 = 2 * o2 - 8;
+ float x1 = o2 + 2.0f * (float)BWPB41 * omega + 4.0f;
+ float x2 = o2 + 2.0f * (float)BWPB42 * omega + 4.0f;
+ float y1 = o2 - 2.0f * (float)BWPB41 * omega + 4.0f;
+ float y2 = o2 - 2.0f * (float)BWPB42 * omega + 4.0f;
+ float o228 = 2.0f * o2 - 8.0f;
float norm = x1 * x2;
a.push_back(1);
a.push_back((x1 + x2) * o228 / norm);
diff --git a/intern/audaspace/FX/AUD_DelayReader.cpp b/intern/audaspace/FX/AUD_DelayReader.cpp
index 903e043af01..0e9833cd07f 100644
--- a/intern/audaspace/FX/AUD_DelayReader.cpp
+++ b/intern/audaspace/FX/AUD_DelayReader.cpp
@@ -33,8 +33,8 @@
AUD_DelayReader::AUD_DelayReader(AUD_Reference<AUD_IReader> reader, float delay) :
AUD_EffectReader(reader),
- m_delay(int(delay * reader->getSpecs().rate)),
- m_remdelay(int(delay * reader->getSpecs().rate))
+ m_delay(int((AUD_SampleRate)delay * reader->getSpecs().rate)),
+ m_remdelay(int((AUD_SampleRate)delay * reader->getSpecs().rate))
{
}
diff --git a/intern/audaspace/FX/AUD_HighpassFactory.cpp b/intern/audaspace/FX/AUD_HighpassFactory.cpp
index 41070842596..b56be8942ff 100644
--- a/intern/audaspace/FX/AUD_HighpassFactory.cpp
+++ b/intern/audaspace/FX/AUD_HighpassFactory.cpp
@@ -48,8 +48,8 @@ void AUD_HighpassFactory::recalculateCoefficients(AUD_SampleRate rate,
std::vector<float> &b,
std::vector<float> &a)
{
- float w0 = 2 * M_PI * m_frequency / rate;
- float alpha = sin(w0) / (2 * m_Q);
+ float w0 = 2.0 * M_PI * (AUD_SampleRate)m_frequency / rate;
+ float alpha = (float)(sin(w0) / (2.0 * (double)m_Q));
float norm = 1 + alpha;
float c = cos(w0);
a.push_back(1);
diff --git a/intern/audaspace/FX/AUD_IIRFilterReader.cpp b/intern/audaspace/FX/AUD_IIRFilterReader.cpp
index 06880818692..8f78c110d1f 100644
--- a/intern/audaspace/FX/AUD_IIRFilterReader.cpp
+++ b/intern/audaspace/FX/AUD_IIRFilterReader.cpp
@@ -34,7 +34,7 @@ AUD_IIRFilterReader::AUD_IIRFilterReader(AUD_Reference<AUD_IReader> reader,
const std::vector<float>& a) :
AUD_BaseIIRFilterReader(reader, b.size(), a.size()), m_a(a), m_b(b)
{
- if(m_a.size())
+ if(m_a.empty() == false)
{
for(int i = 1; i < m_a.size(); i++)
m_a[i] /= m_a[0];
diff --git a/intern/audaspace/OpenAL/AUD_OpenALDevice.cpp b/intern/audaspace/OpenAL/AUD_OpenALDevice.cpp
index c3f3f46d188..a114d8b8a87 100644
--- a/intern/audaspace/OpenAL/AUD_OpenALDevice.cpp
+++ b/intern/audaspace/OpenAL/AUD_OpenALDevice.cpp
@@ -31,6 +31,7 @@
#include "AUD_IFactory.h"
#include "AUD_IReader.h"
#include "AUD_ConverterReader.h"
+#include "AUD_MutexLock.h"
#include <cstring>
#include <limits>
@@ -125,7 +126,7 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::pause()
{
if(m_status)
{
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
if(m_status == AUD_STATUS_PLAYING)
{
@@ -135,12 +136,9 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::pause()
alSourcePause(m_source);
m_status = AUD_STATUS_PAUSED;
- m_device->unlock();
return true;
}
-
- m_device->unlock();
}
return false;
@@ -150,7 +148,7 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::resume()
{
if(m_status)
{
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
if(m_status == AUD_STATUS_PAUSED)
{
@@ -159,11 +157,8 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::resume()
m_device->start();
m_status = AUD_STATUS_PLAYING;
- m_device->unlock();
return true;
}
-
- m_device->unlock();
}
return false;
@@ -174,25 +169,39 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::stop()
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- // AUD_XXX Create a reference of our own object so that it doesn't get
- // deleted before the end of this function
- AUD_Reference<AUD_OpenALHandle> This = this;
-
- if(m_status == AUD_STATUS_PLAYING)
- m_device->m_playingSounds.remove(This);
- else
- m_device->m_pausedSounds.remove(This);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ m_status = AUD_STATUS_INVALID;
alDeleteSources(1, &m_source);
if(!m_isBuffered)
alDeleteBuffers(CYCLE_BUFFERS, m_buffers);
- m_status = AUD_STATUS_INVALID;
- return true;
+ for(AUD_HandleIterator it = m_device->m_playingSounds.begin(); it != m_device->m_playingSounds.end(); it++)
+ {
+ if(it->get() == this)
+ {
+ AUD_Reference<AUD_OpenALHandle> This = *it;
+
+ m_device->m_playingSounds.erase(it);
+
+ return true;
+ }
+ }
+
+ for(AUD_HandleIterator it = m_device->m_pausedSounds.begin(); it != m_device->m_pausedSounds.end(); it++)
+ {
+ if(it->get() == this)
+ {
+ m_device->m_pausedSounds.erase(it);
+ return true;
+ }
+ }
+
+ return false;
}
bool AUD_OpenALDevice::AUD_OpenALHandle::getKeep()
@@ -208,11 +217,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setKeep(bool keep)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- m_keep = keep;
+ if(!m_status)
+ return false;
- m_device->unlock();
+ m_keep = keep;
return true;
}
@@ -222,7 +232,10 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::seek(float position)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
+
+ if(!m_status)
+ return false;
if(m_isBuffered)
alSourcef(m_source, AL_SEC_OFFSET, position);
@@ -272,17 +285,18 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::seek(float position)
}
}
- m_device->unlock();
-
return true;
}
float AUD_OpenALDevice::AUD_OpenALHandle::getPosition()
{
if(!m_status)
- return 0.0f;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
+
+ if(!m_status)
+ return 0.0f;
float position = 0.0f;
@@ -295,8 +309,6 @@ float AUD_OpenALDevice::AUD_OpenALHandle::getPosition()
CYCLE_BUFFERS) / (float)specs.rate;
}
- m_device->unlock();
-
return position;
}
@@ -310,13 +322,14 @@ float AUD_OpenALDevice::AUD_OpenALHandle::getVolume()
float result = std::numeric_limits<float>::quiet_NaN();
if(!m_status)
- return result;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alGetSourcef(m_source, AL_GAIN, &result);
+ if(!m_status)
+ return result;
- m_device->unlock();
+ alGetSourcef(m_source, AL_GAIN, &result);
return result;
}
@@ -326,11 +339,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setVolume(float volume)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcef(m_source, AL_GAIN, volume);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcef(m_source, AL_GAIN, volume);
return true;
}
@@ -340,13 +354,14 @@ float AUD_OpenALDevice::AUD_OpenALHandle::getPitch()
float result = std::numeric_limits<float>::quiet_NaN();
if(!m_status)
- return result;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alGetSourcef(m_source, AL_PITCH, &result);
+ if(!m_status)
+ return result;
- m_device->unlock();
+ alGetSourcef(m_source, AL_PITCH, &result);
return result;
}
@@ -356,11 +371,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setPitch(float pitch)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcef(m_source, AL_PITCH, pitch);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcef(m_source, AL_PITCH, pitch);
return true;
}
@@ -385,13 +401,14 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setStopCallback(stopCallback callback,
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
+
+ if(!m_status)
+ return false;
m_stop = callback;
m_stop_data = data;
- m_device->unlock();
-
return true;
}
@@ -404,15 +421,16 @@ AUD_Vector3 AUD_OpenALDevice::AUD_OpenALHandle::getSourceLocation()
AUD_Vector3 result = AUD_Vector3(0, 0, 0);
if(!m_status)
- return result;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
+
+ if(!m_status)
+ return result;
ALfloat p[3];
alGetSourcefv(m_source, AL_POSITION, p);
- m_device->unlock();
-
result = AUD_Vector3(p[0], p[1], p[2]);
return result;
@@ -423,11 +441,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setSourceLocation(const AUD_Vector3& lo
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcefv(m_source, AL_POSITION, (ALfloat*)location.get());
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcefv(m_source, AL_POSITION, (ALfloat*)location.get());
return true;
}
@@ -437,15 +456,16 @@ AUD_Vector3 AUD_OpenALDevice::AUD_OpenALHandle::getSourceVelocity()
AUD_Vector3 result = AUD_Vector3(0, 0, 0);
if(!m_status)
- return result;
+ return false;
+
+ AUD_MutexLock lock(*m_device);
- m_device->lock();
+ if(!m_status)
+ return result;
ALfloat v[3];
alGetSourcefv(m_source, AL_VELOCITY, v);
- m_device->unlock();
-
result = AUD_Vector3(v[0], v[1], v[2]);
return result;
@@ -456,11 +476,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setSourceVelocity(const AUD_Vector3& ve
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcefv(m_source, AL_VELOCITY, (ALfloat*)velocity.get());
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcefv(m_source, AL_VELOCITY, (ALfloat*)velocity.get());
return true;
}
@@ -472,9 +493,6 @@ AUD_Quaternion AUD_OpenALDevice::AUD_OpenALHandle::getSourceOrientation()
bool AUD_OpenALDevice::AUD_OpenALHandle::setSourceOrientation(const AUD_Quaternion& orientation)
{
- if(!m_status)
- return false;
-
ALfloat direction[3];
direction[0] = -2 * (orientation.w() * orientation.y() +
orientation.x() * orientation.z());
@@ -482,11 +500,16 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setSourceOrientation(const AUD_Quaterni
orientation.z() * orientation.y());
direction[2] = 2 * (orientation.x() * orientation.x() +
orientation.y() * orientation.y()) - 1;
- m_device->lock();
- alSourcefv(m_source, AL_DIRECTION, direction);
+ if(!m_status)
+ return false;
+
+ AUD_MutexLock lock(*m_device);
+
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcefv(m_source, AL_DIRECTION, direction);
m_orientation = orientation;
@@ -500,11 +523,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::isRelative()
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alGetSourcei(m_source, AL_SOURCE_RELATIVE, &result);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alGetSourcei(m_source, AL_SOURCE_RELATIVE, &result);
return result;
}
@@ -514,11 +538,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setRelative(bool relative)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcei(m_source, AL_SOURCE_RELATIVE, relative);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcei(m_source, AL_SOURCE_RELATIVE, relative);
return true;
}
@@ -528,13 +553,14 @@ float AUD_OpenALDevice::AUD_OpenALHandle::getVolumeMaximum()
float result = std::numeric_limits<float>::quiet_NaN();
if(!m_status)
- return result;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alGetSourcef(m_source, AL_MAX_GAIN, &result);
+ if(!m_status)
+ return result;
- m_device->unlock();
+ alGetSourcef(m_source, AL_MAX_GAIN, &result);
return result;
}
@@ -544,11 +570,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setVolumeMaximum(float volume)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcef(m_source, AL_MAX_GAIN, volume);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcef(m_source, AL_MAX_GAIN, volume);
return true;
}
@@ -558,13 +585,14 @@ float AUD_OpenALDevice::AUD_OpenALHandle::getVolumeMinimum()
float result = std::numeric_limits<float>::quiet_NaN();
if(!m_status)
- return result;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alGetSourcef(m_source, AL_MIN_GAIN, &result);
+ if(!m_status)
+ return result;
- m_device->unlock();
+ alGetSourcef(m_source, AL_MIN_GAIN, &result);
return result;
}
@@ -574,11 +602,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setVolumeMinimum(float volume)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcef(m_source, AL_MIN_GAIN, volume);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcef(m_source, AL_MIN_GAIN, volume);
return true;
}
@@ -588,13 +617,14 @@ float AUD_OpenALDevice::AUD_OpenALHandle::getDistanceMaximum()
float result = std::numeric_limits<float>::quiet_NaN();
if(!m_status)
- return result;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alGetSourcef(m_source, AL_MAX_DISTANCE, &result);
+ if(!m_status)
+ return result;
- m_device->unlock();
+ alGetSourcef(m_source, AL_MAX_DISTANCE, &result);
return result;
}
@@ -604,11 +634,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setDistanceMaximum(float distance)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcef(m_source, AL_MAX_DISTANCE, distance);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcef(m_source, AL_MAX_DISTANCE, distance);
return true;
}
@@ -618,13 +649,14 @@ float AUD_OpenALDevice::AUD_OpenALHandle::getDistanceReference()
float result = std::numeric_limits<float>::quiet_NaN();
if(!m_status)
- return result;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alGetSourcef(m_source, AL_REFERENCE_DISTANCE, &result);
+ if(!m_status)
+ return result;
- m_device->unlock();
+ alGetSourcef(m_source, AL_REFERENCE_DISTANCE, &result);
return result;
}
@@ -634,11 +666,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setDistanceReference(float distance)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcef(m_source, AL_REFERENCE_DISTANCE, distance);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcef(m_source, AL_REFERENCE_DISTANCE, distance);
return true;
}
@@ -648,13 +681,14 @@ float AUD_OpenALDevice::AUD_OpenALHandle::getAttenuation()
float result = std::numeric_limits<float>::quiet_NaN();
if(!m_status)
- return result;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alGetSourcef(m_source, AL_ROLLOFF_FACTOR, &result);
+ if(!m_status)
+ return result;
- m_device->unlock();
+ alGetSourcef(m_source, AL_ROLLOFF_FACTOR, &result);
return result;
}
@@ -664,11 +698,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setAttenuation(float factor)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcef(m_source, AL_ROLLOFF_FACTOR, factor);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcef(m_source, AL_ROLLOFF_FACTOR, factor);
return true;
}
@@ -678,13 +713,14 @@ float AUD_OpenALDevice::AUD_OpenALHandle::getConeAngleOuter()
float result = std::numeric_limits<float>::quiet_NaN();
if(!m_status)
- return result;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alGetSourcef(m_source, AL_CONE_OUTER_ANGLE, &result);
+ if(!m_status)
+ return result;
- m_device->unlock();
+ alGetSourcef(m_source, AL_CONE_OUTER_ANGLE, &result);
return result;
}
@@ -694,11 +730,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setConeAngleOuter(float angle)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcef(m_source, AL_CONE_OUTER_ANGLE, angle);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcef(m_source, AL_CONE_OUTER_ANGLE, angle);
return true;
}
@@ -708,13 +745,14 @@ float AUD_OpenALDevice::AUD_OpenALHandle::getConeAngleInner()
float result = std::numeric_limits<float>::quiet_NaN();
if(!m_status)
- return result;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alGetSourcef(m_source, AL_CONE_INNER_ANGLE, &result);
+ if(!m_status)
+ return result;
- m_device->unlock();
+ alGetSourcef(m_source, AL_CONE_INNER_ANGLE, &result);
return result;
}
@@ -724,11 +762,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setConeAngleInner(float angle)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcef(m_source, AL_CONE_INNER_ANGLE, angle);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcef(m_source, AL_CONE_INNER_ANGLE, angle);
return true;
}
@@ -738,13 +777,14 @@ float AUD_OpenALDevice::AUD_OpenALHandle::getConeVolumeOuter()
float result = std::numeric_limits<float>::quiet_NaN();
if(!m_status)
- return result;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alGetSourcef(m_source, AL_CONE_OUTER_GAIN, &result);
+ if(!m_status)
+ return result;
- m_device->unlock();
+ alGetSourcef(m_source, AL_CONE_OUTER_GAIN, &result);
return result;
}
@@ -754,11 +794,12 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setConeVolumeOuter(float volume)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- alSourcef(m_source, AL_CONE_OUTER_GAIN, volume);
+ if(!m_status)
+ return false;
- m_device->unlock();
+ alSourcef(m_source, AL_CONE_OUTER_GAIN, volume);
return true;
}
@@ -767,7 +808,7 @@ bool AUD_OpenALDevice::AUD_OpenALHandle::setConeVolumeOuter(float volume)
/**************************** Threading Code **********************************/
/******************************************************************************/
-void* AUD_openalRunThread(void* device)
+static void *AUD_openalRunThread(void *device)
{
AUD_OpenALDevice* dev = (AUD_OpenALDevice*)device;
dev->updateStreams();
@@ -776,7 +817,7 @@ void* AUD_openalRunThread(void* device)
void AUD_OpenALDevice::start(bool join)
{
- lock();
+ AUD_MutexLock lock(*this);
if(!m_playing)
{
@@ -793,8 +834,6 @@ void AUD_OpenALDevice::start(bool join)
m_playing = true;
}
-
- unlock();
}
void AUD_OpenALDevice::updateStreams()
@@ -970,7 +1009,6 @@ AUD_OpenALDevice::AUD_OpenALDevice(AUD_DeviceSpecs specs, int buffersize)
{
// cannot determine how many channels or which format OpenAL uses, but
// it at least is able to play 16 bit stereo audio
- specs.channels = AUD_CHANNELS_STEREO;
specs.format = AUD_FORMAT_S16;
#if 0
@@ -993,7 +1031,7 @@ AUD_OpenALDevice::AUD_OpenALDevice(AUD_DeviceSpecs specs, int buffersize)
AUD_THROW(AUD_ERROR_OPENAL, open_error);
// at least try to set the frequency
- ALCint attribs[] = { ALC_FREQUENCY, specs.rate, 0 };
+ ALCint attribs[] = { ALC_FREQUENCY, (ALCint)specs.rate, 0 };
ALCint* attributes = attribs;
if(specs.rate == AUD_RATE_INVALID)
attributes = NULL;
@@ -1009,6 +1047,11 @@ AUD_OpenALDevice::AUD_OpenALDevice(AUD_DeviceSpecs specs, int buffersize)
m_useMC = alIsExtensionPresent("AL_EXT_MCFORMATS") == AL_TRUE;
+ if((!m_useMC && specs.channels > AUD_CHANNELS_STEREO) ||
+ specs.channels == AUD_CHANNELS_STEREO_LFE ||
+ specs.channels == AUD_CHANNELS_SURROUND5)
+ specs.channels = AUD_CHANNELS_STEREO;
+
alGetError();
alcGetError(m_device);
@@ -1177,7 +1220,8 @@ AUD_Reference<AUD_IHandle> AUD_OpenALDevice::play(AUD_Reference<AUD_IReader> rea
if(!getFormat(format, specs))
return AUD_Reference<AUD_IHandle>();
- lock();
+ AUD_MutexLock lock(*this);
+
alcSuspendContext(m_context);
AUD_Reference<AUD_OpenALDevice::AUD_OpenALHandle> sound;
@@ -1190,7 +1234,6 @@ AUD_Reference<AUD_IHandle> AUD_OpenALDevice::play(AUD_Reference<AUD_IReader> rea
catch(AUD_Exception&)
{
alcProcessContext(m_context);
- unlock();
throw;
}
@@ -1201,8 +1244,6 @@ AUD_Reference<AUD_IHandle> AUD_OpenALDevice::play(AUD_Reference<AUD_IReader> rea
start();
- unlock();
-
return AUD_Reference<AUD_IHandle>(sound);
}
@@ -1285,7 +1326,8 @@ AUD_Reference<AUD_IHandle> AUD_OpenALDevice::play(AUD_Reference<AUD_IFactory> fa
void AUD_OpenALDevice::stopAll()
{
- lock();
+ AUD_MutexLock lock(*this);
+
alcSuspendContext(m_context);
while(!m_playingSounds.empty())
@@ -1295,7 +1337,6 @@ void AUD_OpenALDevice::stopAll()
m_pausedSounds.front()->stop();
alcProcessContext(m_context);
- unlock();
}
void AUD_OpenALDevice::lock()
diff --git a/intern/audaspace/Python/AUD_PyAPI.cpp b/intern/audaspace/Python/AUD_PyAPI.cpp
index 238249bc7c8..dd58e5a7398 100644
--- a/intern/audaspace/Python/AUD_PyAPI.cpp
+++ b/intern/audaspace/Python/AUD_PyAPI.cpp
@@ -80,7 +80,7 @@ typedef enum
// ====================================================================
-static PyObject* AUDError;
+static PyObject *AUDError;
static const char* device_not_3d_error = "Device is not a 3D device!";
@@ -92,7 +92,7 @@ Factory_dealloc(Factory* self)
if(self->factory)
delete reinterpret_cast<AUD_Reference<AUD_IFactory>*>(self->factory);
Py_XDECREF(self->child_list);
- Py_TYPE(self)->tp_free((PyObject*)self);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
@@ -139,7 +139,7 @@ PyDoc_STRVAR(M_aud_Factory_sine_doc,
":rtype: :class:`Factory`");
static PyObject *
-Factory_sine(PyTypeObject* type, PyObject* args)
+Factory_sine(PyTypeObject* type, PyObject *args)
{
float frequency;
double rate = 44100;
@@ -179,7 +179,7 @@ PyDoc_STRVAR(M_aud_Factory_file_doc,
"playback of that factory.");
static PyObject *
-Factory_file(PyTypeObject* type, PyObject* args)
+Factory_file(PyTypeObject* type, PyObject *args)
{
const char* filename = NULL;
@@ -218,7 +218,7 @@ PyDoc_STRVAR(M_aud_Factory_lowpass_doc,
":rtype: :class:`Factory`");
static PyObject *
-Factory_lowpass(Factory* self, PyObject* args)
+Factory_lowpass(Factory* self, PyObject *args)
{
float frequency;
float Q = 0.5;
@@ -232,7 +232,7 @@ Factory_lowpass(Factory* self, PyObject* args)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -260,7 +260,7 @@ PyDoc_STRVAR(M_aud_Factory_delay_doc,
":rtype: :class:`Factory`");
static PyObject *
-Factory_delay(Factory* self, PyObject* args)
+Factory_delay(Factory* self, PyObject *args)
{
float delay;
@@ -273,7 +273,7 @@ Factory_delay(Factory* self, PyObject* args)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -301,7 +301,7 @@ PyDoc_STRVAR(M_aud_Factory_join_doc,
"(channels and samplerate).");
static PyObject *
-Factory_join(Factory* self, PyObject* object)
+Factory_join(Factory* self, PyObject *object)
{
PyTypeObject* type = Py_TYPE(self);
@@ -346,7 +346,7 @@ PyDoc_STRVAR(M_aud_Factory_highpass_doc,
":rtype: :class:`Factory`");
static PyObject *
-Factory_highpass(Factory* self, PyObject* args)
+Factory_highpass(Factory* self, PyObject *args)
{
float frequency;
float Q = 0.5;
@@ -360,7 +360,7 @@ Factory_highpass(Factory* self, PyObject* args)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -388,7 +388,7 @@ PyDoc_STRVAR(M_aud_Factory_limit_doc,
":rtype: :class:`Factory`");
static PyObject *
-Factory_limit(Factory* self, PyObject* args)
+Factory_limit(Factory* self, PyObject *args)
{
float start, end;
@@ -401,7 +401,7 @@ Factory_limit(Factory* self, PyObject* args)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -432,7 +432,7 @@ PyDoc_STRVAR(M_aud_Factory_pitch_doc,
":attr:`Handle.pitch` instead.");
static PyObject *
-Factory_pitch(Factory* self, PyObject* args)
+Factory_pitch(Factory* self, PyObject *args)
{
float factor;
@@ -445,7 +445,7 @@ Factory_pitch(Factory* self, PyObject* args)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -474,7 +474,7 @@ PyDoc_STRVAR(M_aud_Factory_volume_doc,
":attr:`Handle.volume` instead.");
static PyObject *
-Factory_volume(Factory* self, PyObject* args)
+Factory_volume(Factory* self, PyObject *args)
{
float volume;
@@ -487,7 +487,7 @@ Factory_volume(Factory* self, PyObject* args)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -517,7 +517,7 @@ PyDoc_STRVAR(M_aud_Factory_fadein_doc,
".. note:: Before the fade starts it plays silence.");
static PyObject *
-Factory_fadein(Factory* self, PyObject* args)
+Factory_fadein(Factory* self, PyObject *args)
{
float start, length;
@@ -530,7 +530,7 @@ Factory_fadein(Factory* self, PyObject* args)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -561,7 +561,7 @@ PyDoc_STRVAR(M_aud_Factory_fadeout_doc,
"the length of the factory is not altered.");
static PyObject *
-Factory_fadeout(Factory* self, PyObject* args)
+Factory_fadeout(Factory* self, PyObject *args)
{
float start, length;
@@ -574,7 +574,7 @@ Factory_fadeout(Factory* self, PyObject* args)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -603,7 +603,7 @@ PyDoc_STRVAR(M_aud_Factory_loop_doc,
":attr:`Handle.loop_count` instead.");
static PyObject *
-Factory_loop(Factory* self, PyObject* args)
+Factory_loop(Factory* self, PyObject *args)
{
int loop;
@@ -616,7 +616,7 @@ Factory_loop(Factory* self, PyObject* args)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -644,7 +644,7 @@ PyDoc_STRVAR(M_aud_Factory_mix_doc,
"(channels and samplerate).");
static PyObject *
-Factory_mix(Factory* self, PyObject* object)
+Factory_mix(Factory* self, PyObject *object)
{
PyTypeObject* type = Py_TYPE(self);
@@ -692,7 +692,7 @@ Factory_pingpong(Factory* self)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -731,7 +731,7 @@ Factory_reverse(Factory* self)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -795,7 +795,7 @@ PyDoc_STRVAR(M_aud_Factory_square_doc,
":rtype: :class:`Factory`");
static PyObject *
-Factory_square(Factory* self, PyObject* args)
+Factory_square(Factory* self, PyObject *args)
{
float threshold = 0;
@@ -808,7 +808,7 @@ Factory_square(Factory* self, PyObject* args)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -842,10 +842,10 @@ PyDoc_STRVAR(M_aud_Factory_filter_doc,
":rtype: :class:`Factory`");
static PyObject *
-Factory_filter(Factory* self, PyObject* args)
+Factory_filter(Factory* self, PyObject *args)
{
- PyObject* py_b;
- PyObject* py_a = NULL;
+ PyObject *py_b;
+ PyObject *py_a = NULL;
Py_ssize_t py_a_len;
Py_ssize_t py_b_len;
@@ -868,7 +868,7 @@ Factory_filter(Factory* self, PyObject* args)
}
std::vector<float> a, b;
- PyObject* py_value;
+ PyObject *py_value;
float value;
for(Py_ssize_t i = 0; i < py_b_len; i++)
@@ -911,7 +911,7 @@ Factory_filter(Factory* self, PyObject* args)
if(parent != NULL)
{
Py_INCREF(self);
- parent->child_list = (PyObject*)self;
+ parent->child_list = (PyObject *)self;
try
{
@@ -1040,7 +1040,7 @@ Handle_dealloc(Handle* self)
{
if(self->handle)
delete reinterpret_cast<AUD_Reference<AUD_IHandle>*>(self->handle);
- Py_TYPE(self)->tp_free((PyObject*)self);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
PyDoc_STRVAR(M_aud_Handle_pause_doc,
@@ -1135,7 +1135,7 @@ Handle_get_position(Handle *self, void* nothing)
}
static int
-Handle_set_position(Handle *self, PyObject* args, void* nothing)
+Handle_set_position(Handle *self, PyObject *args, void* nothing)
{
float position;
@@ -1180,7 +1180,7 @@ Handle_get_keep(Handle *self, void* nothing)
}
static int
-Handle_set_keep(Handle *self, PyObject* args, void* nothing)
+Handle_set_keep(Handle *self, PyObject *args, void* nothing)
{
if(!PyBool_Check(args))
{
@@ -1239,7 +1239,7 @@ Handle_get_volume(Handle *self, void* nothing)
}
static int
-Handle_set_volume(Handle *self, PyObject* args, void* nothing)
+Handle_set_volume(Handle *self, PyObject *args, void* nothing)
{
float volume;
@@ -1278,7 +1278,7 @@ Handle_get_pitch(Handle *self, void* nothing)
}
static int
-Handle_set_pitch(Handle *self, PyObject* args, void* nothing)
+Handle_set_pitch(Handle *self, PyObject *args, void* nothing)
{
float pitch;
@@ -1317,7 +1317,7 @@ Handle_get_loop_count(Handle *self, void* nothing)
}
static int
-Handle_set_loop_count(Handle *self, PyObject* args, void* nothing)
+Handle_set_loop_count(Handle *self, PyObject *args, void* nothing)
{
int loops;
@@ -1366,7 +1366,7 @@ Handle_get_location(Handle *self, void* nothing)
}
static int
-Handle_set_location(Handle *self, PyObject* args, void* nothing)
+Handle_set_location(Handle *self, PyObject *args, void* nothing)
{
float x, y, z;
@@ -1422,7 +1422,7 @@ Handle_get_velocity(Handle *self, void* nothing)
}
static int
-Handle_set_velocity(Handle *self, PyObject* args, void* nothing)
+Handle_set_velocity(Handle *self, PyObject *args, void* nothing)
{
float x, y, z;
@@ -1478,7 +1478,7 @@ Handle_get_orientation(Handle *self, void* nothing)
}
static int
-Handle_set_orientation(Handle *self, PyObject* args, void* nothing)
+Handle_set_orientation(Handle *self, PyObject *args, void* nothing)
{
float w, x, y, z;
@@ -1533,7 +1533,7 @@ Handle_get_relative(Handle *self, void* nothing)
}
static int
-Handle_set_relative(Handle *self, PyObject* args, void* nothing)
+Handle_set_relative(Handle *self, PyObject *args, void* nothing)
{
if(!PyBool_Check(args))
{
@@ -1591,7 +1591,7 @@ Handle_get_volume_minimum(Handle *self, void* nothing)
}
static int
-Handle_set_volume_minimum(Handle *self, PyObject* args, void* nothing)
+Handle_set_volume_minimum(Handle *self, PyObject *args, void* nothing)
{
float volume;
@@ -1646,7 +1646,7 @@ Handle_get_volume_maximum(Handle *self, void* nothing)
}
static int
-Handle_set_volume_maximum(Handle *self, PyObject* args, void* nothing)
+Handle_set_volume_maximum(Handle *self, PyObject *args, void* nothing)
{
float volume;
@@ -1702,7 +1702,7 @@ Handle_get_distance_reference(Handle *self, void* nothing)
}
static int
-Handle_set_distance_reference(Handle *self, PyObject* args, void* nothing)
+Handle_set_distance_reference(Handle *self, PyObject *args, void* nothing)
{
float distance;
@@ -1758,7 +1758,7 @@ Handle_get_distance_maximum(Handle *self, void* nothing)
}
static int
-Handle_set_distance_maximum(Handle *self, PyObject* args, void* nothing)
+Handle_set_distance_maximum(Handle *self, PyObject *args, void* nothing)
{
float distance;
@@ -1814,7 +1814,7 @@ Handle_get_attenuation(Handle *self, void* nothing)
}
static int
-Handle_set_attenuation(Handle *self, PyObject* args, void* nothing)
+Handle_set_attenuation(Handle *self, PyObject *args, void* nothing)
{
float factor;
@@ -1875,7 +1875,7 @@ Handle_get_cone_angle_inner(Handle *self, void* nothing)
}
static int
-Handle_set_cone_angle_inner(Handle *self, PyObject* args, void* nothing)
+Handle_set_cone_angle_inner(Handle *self, PyObject *args, void* nothing)
{
float angle;
@@ -1930,7 +1930,7 @@ Handle_get_cone_angle_outer(Handle *self, void* nothing)
}
static int
-Handle_set_cone_angle_outer(Handle *self, PyObject* args, void* nothing)
+Handle_set_cone_angle_outer(Handle *self, PyObject *args, void* nothing)
{
float angle;
@@ -1985,7 +1985,7 @@ Handle_get_cone_volume_outer(Handle *self, void* nothing)
}
static int
-Handle_set_cone_volume_outer(Handle *self, PyObject* args, void* nothing)
+Handle_set_cone_volume_outer(Handle *self, PyObject *args, void* nothing)
{
float volume;
@@ -2105,7 +2105,7 @@ Device_dealloc(Device* self)
{
if(self->device)
delete reinterpret_cast<AUD_Reference<AUD_IDevice>*>(self->device);
- Py_TYPE(self)->tp_free((PyObject*)self);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
@@ -2201,8 +2201,8 @@ PyDoc_STRVAR(M_aud_Device_play_doc,
static PyObject *
Device_play(Device *self, PyObject *args, PyObject *kwds)
{
- PyObject* object;
- PyObject* keepo = NULL;
+ PyObject *object;
+ PyObject *keepo = NULL;
bool keep = false;
@@ -2402,7 +2402,7 @@ Device_get_volume(Device *self, void* nothing)
}
static int
-Device_set_volume(Device *self, PyObject* args, void* nothing)
+Device_set_volume(Device *self, PyObject *args, void* nothing)
{
float volume;
@@ -2449,7 +2449,7 @@ Device_get_listener_location(Device *self, void* nothing)
}
static int
-Device_set_listener_location(Device *self, PyObject* args, void* nothing)
+Device_set_listener_location(Device *self, PyObject *args, void* nothing)
{
float x, y, z;
@@ -2504,7 +2504,7 @@ Device_get_listener_velocity(Device *self, void* nothing)
}
static int
-Device_set_listener_velocity(Device *self, PyObject* args, void* nothing)
+Device_set_listener_velocity(Device *self, PyObject *args, void* nothing)
{
float x, y, z;
@@ -2559,7 +2559,7 @@ Device_get_listener_orientation(Device *self, void* nothing)
}
static int
-Device_set_listener_orientation(Device *self, PyObject* args, void* nothing)
+Device_set_listener_orientation(Device *self, PyObject *args, void* nothing)
{
float w, x, y, z;
@@ -2614,7 +2614,7 @@ Device_get_speed_of_sound(Device *self, void* nothing)
}
static int
-Device_set_speed_of_sound(Device *self, PyObject* args, void* nothing)
+Device_set_speed_of_sound(Device *self, PyObject *args, void* nothing)
{
float speed;
@@ -2670,7 +2670,7 @@ Device_get_doppler_factor(Device *self, void* nothing)
}
static int
-Device_set_doppler_factor(Device *self, PyObject* args, void* nothing)
+Device_set_doppler_factor(Device *self, PyObject *args, void* nothing)
{
float factor;
@@ -2724,7 +2724,7 @@ Device_get_distance_model(Device *self, void* nothing)
}
static int
-Device_set_distance_model(Device *self, PyObject* args, void* nothing)
+Device_set_distance_model(Device *self, PyObject *args, void* nothing)
{
int model;
@@ -2833,7 +2833,7 @@ Factory_empty()
}
Factory*
-checkFactory(PyObject* factory)
+checkFactory(PyObject *factory)
{
if(!PyObject_TypeCheck(factory, &FactoryType))
{
@@ -2862,7 +2862,7 @@ static struct PyModuleDef audmodule = {
PyMODINIT_FUNC
PyInit_aud(void)
{
- PyObject* m;
+ PyObject *m;
if(PyType_Ready(&FactoryType) < 0)
return NULL;
@@ -2878,13 +2878,13 @@ PyInit_aud(void)
return NULL;
Py_INCREF(&FactoryType);
- PyModule_AddObject(m, "Factory", (PyObject*)&FactoryType);
+ PyModule_AddObject(m, "Factory", (PyObject *)&FactoryType);
Py_INCREF(&DeviceType);
- PyModule_AddObject(m, "Device", (PyObject*)&DeviceType);
+ PyModule_AddObject(m, "Device", (PyObject *)&DeviceType);
Py_INCREF(&HandleType);
- PyModule_AddObject(m, "Handle", (PyObject*)&HandleType);
+ PyModule_AddObject(m, "Handle", (PyObject *)&HandleType);
AUDError = PyErr_NewException("aud.error", NULL, NULL);
Py_INCREF(AUDError);
diff --git a/intern/audaspace/Python/AUD_PyAPI.h b/intern/audaspace/Python/AUD_PyAPI.h
index 7a7e87ec67d..0183a2df6b2 100644
--- a/intern/audaspace/Python/AUD_PyAPI.h
+++ b/intern/audaspace/Python/AUD_PyAPI.h
@@ -46,7 +46,7 @@ typedef void AUD_Reference_AUD_IHandle;
typedef struct {
PyObject_HEAD
- PyObject* child_list;
+ PyObject *child_list;
AUD_Reference_AUD_IFactory* factory;
} Factory;
@@ -63,9 +63,9 @@ typedef struct {
PyMODINIT_FUNC
PyInit_aud(void);
-extern PyObject* Device_empty();
-extern PyObject* Factory_empty();
-extern Factory* checkFactory(PyObject* factory);
+extern PyObject *Device_empty();
+extern PyObject *Factory_empty();
+extern Factory *checkFactory(PyObject *factory);
#ifdef __cplusplus
}
diff --git a/intern/audaspace/fftw/AUD_BandPassFactory.h b/intern/audaspace/fftw/AUD_BandPassFactory.h
index 75de071403f..90b090dce16 100644
--- a/intern/audaspace/fftw/AUD_BandPassFactory.h
+++ b/intern/audaspace/fftw/AUD_BandPassFactory.h
@@ -84,7 +84,7 @@ public:
* Sets the highest passed frequency.
* \param high The highest passed frequency.
*/
- void setHigh(float hight);
+ void setHigh(float high);
virtual AUD_IReader* createReader();
};
diff --git a/intern/audaspace/intern/AUD_AnimateableProperty.cpp b/intern/audaspace/intern/AUD_AnimateableProperty.cpp
index 8a5c538c094..0b333e687ff 100644
--- a/intern/audaspace/intern/AUD_AnimateableProperty.cpp
+++ b/intern/audaspace/intern/AUD_AnimateableProperty.cpp
@@ -28,6 +28,7 @@
#include "AUD_AnimateableProperty.h"
+#include "AUD_MutexLock.h"
#include <cstring>
#include <cmath>
@@ -63,17 +64,15 @@ void AUD_AnimateableProperty::unlock()
void AUD_AnimateableProperty::write(const float* data)
{
- lock();
+ AUD_MutexLock lock(*this);
m_isAnimated = false;
memcpy(getBuffer(), data, m_count * sizeof(float));
-
- unlock();
}
void AUD_AnimateableProperty::write(const float* data, int position, int count)
{
- lock();
+ AUD_MutexLock lock(*this);
m_isAnimated = true;
@@ -87,18 +86,15 @@ void AUD_AnimateableProperty::write(const float* data, int position, int count)
for(int i = pos; i < position; i++)
memcpy(buf + i * m_count, buf + (pos - 1) * m_count, m_count * sizeof(float));
-
- unlock();
}
void AUD_AnimateableProperty::read(float position, float* out)
{
- lock();
+ AUD_MutexLock lock(*this);
if(!m_isAnimated)
{
memcpy(out, getBuffer(), m_count * sizeof(float));
- unlock();
return;
}
@@ -147,8 +143,6 @@ void AUD_AnimateableProperty::read(float position, float* out)
(t3 - 2 * t2 + t) * m0 + (t3 - t2) * m1;
}
}
-
- unlock();
}
bool AUD_AnimateableProperty::isAnimated() const
diff --git a/intern/audaspace/intern/AUD_AnimateableProperty.h b/intern/audaspace/intern/AUD_AnimateableProperty.h
index 2f25e330ebd..322748ad571 100644
--- a/intern/audaspace/intern/AUD_AnimateableProperty.h
+++ b/intern/audaspace/intern/AUD_AnimateableProperty.h
@@ -31,13 +31,14 @@
#define __AUD_ANIMATEABLEPROPERTY_H__
#include "AUD_Buffer.h"
+#include "AUD_ILockable.h"
#include <pthread.h>
/**
* This class saves animation data for float properties.
*/
-class AUD_AnimateableProperty : private AUD_Buffer
+class AUD_AnimateableProperty : private AUD_Buffer, public AUD_ILockable
{
private:
/// The count of floats for a single property.
@@ -68,12 +69,12 @@ public:
/**
* Locks the property.
*/
- void lock();
+ virtual void lock();
/**
* Unlocks the previously locked property.
*/
- void unlock();
+ virtual void unlock();
/**
* Writes the properties value and marks it non-animated.
diff --git a/intern/audaspace/intern/AUD_C-API.cpp b/intern/audaspace/intern/AUD_C-API.cpp
index 46bba237cff..a1da90b073e 100644
--- a/intern/audaspace/intern/AUD_C-API.cpp
+++ b/intern/audaspace/intern/AUD_C-API.cpp
@@ -68,6 +68,7 @@
#include "AUD_SequencerFactory.h"
#include "AUD_SequencerEntry.h"
#include "AUD_SilenceFactory.h"
+#include "AUD_MutexLock.h"
#ifdef WITH_SDL
#include "AUD_SDLDevice.h"
@@ -858,13 +859,12 @@ AUD_Handle *AUD_pauseAfter(AUD_Handle *handle, float seconds)
AUD_Reference<AUD_IFactory> silence = new AUD_SilenceFactory;
AUD_Reference<AUD_IFactory> limiter = new AUD_LimiterFactory(silence, 0, seconds);
- AUD_device->lock();
+ AUD_MutexLock lock(*AUD_device);
try {
AUD_Handle handle2 = AUD_device->play(limiter);
if (!handle2.isNull()) {
handle2->setStopCallback((stopCallback)pauseSound, handle);
- AUD_device->unlock();
return new AUD_Handle(handle2);
}
}
@@ -872,8 +872,6 @@ AUD_Handle *AUD_pauseAfter(AUD_Handle *handle, float seconds)
{
}
- AUD_device->unlock();
-
return NULL;
}
diff --git a/intern/audaspace/intern/AUD_ChannelMapperReader.cpp b/intern/audaspace/intern/AUD_ChannelMapperReader.cpp
index 61796098bf7..7a179c6f94a 100644
--- a/intern/audaspace/intern/AUD_ChannelMapperReader.cpp
+++ b/intern/audaspace/intern/AUD_ChannelMapperReader.cpp
@@ -67,10 +67,12 @@ void AUD_ChannelMapperReader::setMonoAngle(float angle)
float AUD_ChannelMapperReader::angleDistance(float alpha, float beta)
{
- alpha = fabs(alpha - beta);
+ alpha = beta - alpha;
if(alpha > M_PI)
- alpha = fabs(alpha - 2 * M_PI);
+ alpha -= 2 * M_PI;
+ if(alpha < -M_PI)
+ alpha += 2 * M_PI;
return alpha;
}
@@ -107,8 +109,8 @@ void AUD_ChannelMapperReader::calculateMapping()
if(m_source_channels == AUD_CHANNELS_MONO)
source_angles = &m_mono_angle;
- int channel_min1, channel_min2;
- float angle_min1, angle_min2, angle;
+ int channel_left, channel_right;
+ float angle_left, angle_right, angle;
for(int i = 0; i < m_source_channels; i++)
{
@@ -120,38 +122,46 @@ void AUD_ChannelMapperReader::calculateMapping()
continue;
}
- channel_min1 = channel_min2 = -1;
- angle_min1 = angle_min2 = 2 * M_PI;
+ channel_left = channel_right = -1;
+ angle_left = -2 * M_PI;
+ angle_right = 2 * M_PI;
for(int j = 0; j < m_target_channels; j++)
{
if(j == lfe)
continue;
angle = angleDistance(source_angles[i], target_angles[j]);
- if(angle < angle_min1)
+ if(angle < 0)
{
- channel_min2 = channel_min1;
- angle_min2 = angle_min1;
-
- channel_min1 = j;
- angle_min1 = angle;
+ if(angle > angle_left)
+ {
+ angle_left = angle;
+ channel_left = j;
+ }
}
- else if(angle < angle_min2)
+ else
{
- channel_min2 = j;
- angle_min2 = angle;
+ if(angle < angle_right)
+ {
+ angle_right = angle;
+ channel_right = j;
+ }
}
}
- angle = angle_min1 + angle_min2;
- if(channel_min2 == -1 || angle == 0)
+ angle = angle_right - angle_left;
+ if(channel_right == -1 || angle == 0)
+ {
+ m_mapping[channel_left * m_source_channels + i] = 1;
+ }
+ else if(channel_left == -1)
{
- m_mapping[channel_min1 * m_source_channels + i] = 1;
+ m_mapping[channel_right * m_source_channels + i] = 1;
}
else
{
- m_mapping[channel_min1 * m_source_channels + i] = cos(M_PI_2 * angle_min1 / angle);
- m_mapping[channel_min2 * m_source_channels + i] = cos(M_PI_2 * angle_min2 / angle);
+ m_mapping[channel_left * m_source_channels + i] = cos(M_PI_2 * angle_left / angle);
+ m_mapping[channel_right * m_source_channels + i] = cos(M_PI_2 * angle_right / angle);
}
}
diff --git a/intern/audaspace/intern/AUD_IDevice.h b/intern/audaspace/intern/AUD_IDevice.h
index 1d6f8ca6efb..f4d6635e79a 100644
--- a/intern/audaspace/intern/AUD_IDevice.h
+++ b/intern/audaspace/intern/AUD_IDevice.h
@@ -35,6 +35,7 @@
#include "AUD_IFactory.h"
#include "AUD_IReader.h"
#include "AUD_IHandle.h"
+#include "AUD_ILockable.h"
/**
* This class represents an output device for sound sources.
@@ -44,7 +45,7 @@
* \warning Thread safety must be insured so that no reader is beeing called
* twice at the same time.
*/
-class AUD_IDevice
+class AUD_IDevice : public AUD_ILockable
{
public:
/**
diff --git a/intern/audaspace/intern/AUD_IFactory.h b/intern/audaspace/intern/AUD_IFactory.h
index a7c214bb5a1..95b4643072e 100644
--- a/intern/audaspace/intern/AUD_IFactory.h
+++ b/intern/audaspace/intern/AUD_IFactory.h
@@ -45,7 +45,7 @@ public:
/**
* Destroys the factory.
*/
- virtual ~AUD_IFactory(){}
+ virtual ~AUD_IFactory() {}
/**
* Creates a reader for playback of the sound source.
diff --git a/intern/audaspace/intern/AUD_ILockable.h b/intern/audaspace/intern/AUD_ILockable.h
new file mode 100644
index 00000000000..9bc417504fe
--- /dev/null
+++ b/intern/audaspace/intern/AUD_ILockable.h
@@ -0,0 +1,21 @@
+#ifndef AUD_ILOCKABLE_H
+#define AUD_ILOCKABLE_H
+
+/**
+ * This class provides an interface for lockable objects.
+ * The main reason for this interface is to be used with AUD_MutexLock.
+ */
+class AUD_ILockable
+{
+public:
+ /**
+ * Locks the object.
+ */
+ virtual void lock()=0;
+ /**
+ * Unlocks the previously locked object.
+ */
+ virtual void unlock()=0;
+};
+
+#endif // AUD_ILOCKABLE_H
diff --git a/intern/audaspace/intern/AUD_IReader.h b/intern/audaspace/intern/AUD_IReader.h
index 8e0e03dd95d..c2c9e607b55 100644
--- a/intern/audaspace/intern/AUD_IReader.h
+++ b/intern/audaspace/intern/AUD_IReader.h
@@ -42,7 +42,7 @@ public:
/**
* Destroys the reader.
*/
- virtual ~AUD_IReader(){}
+ virtual ~AUD_IReader() {}
/**
* Tells whether the source provides seeking functionality or not.
diff --git a/intern/audaspace/intern/AUD_IWriter.h b/intern/audaspace/intern/AUD_IWriter.h
index 3c92661c75d..5406577dd50 100644
--- a/intern/audaspace/intern/AUD_IWriter.h
+++ b/intern/audaspace/intern/AUD_IWriter.h
@@ -41,7 +41,7 @@ public:
/**
* Destroys the writer.
*/
- virtual ~AUD_IWriter(){}
+ virtual ~AUD_IWriter() {}
/**
* Returns how many samples have been written so far.
diff --git a/intern/audaspace/intern/AUD_MutexLock.h b/intern/audaspace/intern/AUD_MutexLock.h
new file mode 100644
index 00000000000..b6f6d2b4334
--- /dev/null
+++ b/intern/audaspace/intern/AUD_MutexLock.h
@@ -0,0 +1,24 @@
+#ifndef AUD_MUTEXLOCK_H
+#define AUD_MUTEXLOCK_H
+
+#include "AUD_ILockable.h"
+
+class AUD_MutexLock
+{
+public:
+ inline AUD_MutexLock(AUD_ILockable& lockable) :
+ lockable(lockable)
+ {
+ lockable.lock();
+ }
+
+ inline ~AUD_MutexLock()
+ {
+ lockable.unlock();
+ }
+
+private:
+ AUD_ILockable& lockable;
+};
+
+#endif // AUD_MUTEXLOCK_H
diff --git a/intern/audaspace/intern/AUD_PyInit.h b/intern/audaspace/intern/AUD_PyInit.h
index 8c045e60f37..d8b6e2f3519 100644
--- a/intern/audaspace/intern/AUD_PyInit.h
+++ b/intern/audaspace/intern/AUD_PyInit.h
@@ -38,9 +38,9 @@ extern "C" {
#endif
/**
- * Initalizes the Python module.
+ * Initializes the Python module.
*/
-extern PyObject* AUD_initPython(void);
+extern PyObject *AUD_initPython(void);
#ifdef __cplusplus
}
diff --git a/intern/audaspace/intern/AUD_SequencerEntry.cpp b/intern/audaspace/intern/AUD_SequencerEntry.cpp
index 6e6e2397626..96fd15a0bf8 100644
--- a/intern/audaspace/intern/AUD_SequencerEntry.cpp
+++ b/intern/audaspace/intern/AUD_SequencerEntry.cpp
@@ -29,6 +29,7 @@
#include "AUD_SequencerEntry.h"
#include "AUD_SequencerReader.h"
+#include "AUD_MutexLock.h"
#include <cmath>
#include <limits>
@@ -87,20 +88,18 @@ void AUD_SequencerEntry::unlock()
void AUD_SequencerEntry::setSound(AUD_Reference<AUD_IFactory> sound)
{
- lock();
+ AUD_MutexLock lock(*this);
if(m_sound.get() != sound.get())
{
m_sound = sound;
m_sound_status++;
}
-
- unlock();
}
void AUD_SequencerEntry::move(float begin, float end, float skip)
{
- lock();
+ AUD_MutexLock lock(*this);
if(m_begin != begin || m_skip != skip || m_end != end)
{
@@ -109,17 +108,13 @@ void AUD_SequencerEntry::move(float begin, float end, float skip)
m_end = end;
m_pos_status++;
}
-
- unlock();
}
void AUD_SequencerEntry::mute(bool mute)
{
- lock();
+ AUD_MutexLock lock(*this);
m_muted = mute;
-
- unlock();
}
int AUD_SequencerEntry::getID() const
@@ -150,7 +145,7 @@ void AUD_SequencerEntry::updateAll(float volume_max, float volume_min, float dis
float distance_reference, float attenuation, float cone_angle_outer,
float cone_angle_inner, float cone_volume_outer)
{
- lock();
+ AUD_MutexLock lock(*this);
if(volume_max != m_volume_max)
{
@@ -199,8 +194,6 @@ void AUD_SequencerEntry::updateAll(float volume_max, float volume_min, float dis
m_cone_volume_outer = cone_volume_outer;
m_status++;
}
-
- unlock();
}
bool AUD_SequencerEntry::isRelative()
@@ -210,15 +203,13 @@ bool AUD_SequencerEntry::isRelative()
void AUD_SequencerEntry::setRelative(bool relative)
{
- lock();
+ AUD_MutexLock lock(*this);
if(m_relative != relative)
{
m_relative = relative;
m_status++;
}
-
- unlock();
}
float AUD_SequencerEntry::getVolumeMaximum()
@@ -228,12 +219,10 @@ float AUD_SequencerEntry::getVolumeMaximum()
void AUD_SequencerEntry::setVolumeMaximum(float volume)
{
- lock();
+ AUD_MutexLock lock(*this);
m_volume_max = volume;
m_status++;
-
- unlock();
}
float AUD_SequencerEntry::getVolumeMinimum()
@@ -243,12 +232,10 @@ float AUD_SequencerEntry::getVolumeMinimum()
void AUD_SequencerEntry::setVolumeMinimum(float volume)
{
- lock();
+ AUD_MutexLock lock(*this);
m_volume_min = volume;
m_status++;
-
- unlock();
}
float AUD_SequencerEntry::getDistanceMaximum()
@@ -258,12 +245,10 @@ float AUD_SequencerEntry::getDistanceMaximum()
void AUD_SequencerEntry::setDistanceMaximum(float distance)
{
- lock();
+ AUD_MutexLock lock(*this);
m_distance_max = distance;
m_status++;
-
- unlock();
}
float AUD_SequencerEntry::getDistanceReference()
@@ -273,12 +258,10 @@ float AUD_SequencerEntry::getDistanceReference()
void AUD_SequencerEntry::setDistanceReference(float distance)
{
- lock();
+ AUD_MutexLock lock(*this);
m_distance_reference = distance;
m_status++;
-
- unlock();
}
float AUD_SequencerEntry::getAttenuation()
@@ -288,12 +271,10 @@ float AUD_SequencerEntry::getAttenuation()
void AUD_SequencerEntry::setAttenuation(float factor)
{
- lock();
+ AUD_MutexLock lock(*this);
m_attenuation = factor;
m_status++;
-
- unlock();
}
float AUD_SequencerEntry::getConeAngleOuter()
@@ -303,12 +284,10 @@ float AUD_SequencerEntry::getConeAngleOuter()
void AUD_SequencerEntry::setConeAngleOuter(float angle)
{
- lock();
+ AUD_MutexLock lock(*this);
m_cone_angle_outer = angle;
m_status++;
-
- unlock();
}
float AUD_SequencerEntry::getConeAngleInner()
@@ -318,12 +297,10 @@ float AUD_SequencerEntry::getConeAngleInner()
void AUD_SequencerEntry::setConeAngleInner(float angle)
{
- lock();
+ AUD_MutexLock lock(*this);
m_cone_angle_inner = angle;
m_status++;
-
- unlock();
}
float AUD_SequencerEntry::getConeVolumeOuter()
@@ -333,10 +310,8 @@ float AUD_SequencerEntry::getConeVolumeOuter()
void AUD_SequencerEntry::setConeVolumeOuter(float volume)
{
- lock();
+ AUD_MutexLock lock(*this);
m_cone_volume_outer = volume;
m_status++;
-
- unlock();
}
diff --git a/intern/audaspace/intern/AUD_SequencerEntry.h b/intern/audaspace/intern/AUD_SequencerEntry.h
index 7ff6fffea11..46efc52d66b 100644
--- a/intern/audaspace/intern/AUD_SequencerEntry.h
+++ b/intern/audaspace/intern/AUD_SequencerEntry.h
@@ -33,13 +33,14 @@
#include "AUD_Reference.h"
#include "AUD_AnimateableProperty.h"
#include "AUD_IFactory.h"
+#include "AUD_ILockable.h"
#include <pthread.h>
/**
* This class represents a sequenced entry in a sequencer factory.
*/
-class AUD_SequencerEntry
+class AUD_SequencerEntry : public AUD_ILockable
{
friend class AUD_SequencerHandle;
private:
@@ -130,12 +131,12 @@ public:
/**
* Locks the entry.
*/
- void lock();
+ virtual void lock();
/**
* Unlocks the previously locked entry.
*/
- void unlock();
+ virtual void unlock();
/**
* Sets the sound of the entry.
diff --git a/intern/audaspace/intern/AUD_SequencerFactory.cpp b/intern/audaspace/intern/AUD_SequencerFactory.cpp
index fd495f467cf..2cc0a656cf1 100644
--- a/intern/audaspace/intern/AUD_SequencerFactory.cpp
+++ b/intern/audaspace/intern/AUD_SequencerFactory.cpp
@@ -30,6 +30,7 @@
#include "AUD_SequencerFactory.h"
#include "AUD_SequencerReader.h"
#include "AUD_3DMath.h"
+#include "AUD_MutexLock.h"
AUD_SequencerFactory::AUD_SequencerFactory(AUD_Specs specs, float fps, bool muted) :
m_specs(specs),
@@ -75,30 +76,24 @@ void AUD_SequencerFactory::unlock()
void AUD_SequencerFactory::setSpecs(AUD_Specs specs)
{
- lock();
+ AUD_MutexLock lock(*this);
m_specs = specs;
m_status++;
-
- unlock();
}
void AUD_SequencerFactory::setFPS(float fps)
{
- lock();
+ AUD_MutexLock lock(*this);
m_fps = fps;
-
- unlock();
}
void AUD_SequencerFactory::mute(bool muted)
{
- lock();
+ AUD_MutexLock lock(*this);
m_muted = muted;
-
- unlock();
}
bool AUD_SequencerFactory::getMute() const
@@ -113,12 +108,10 @@ float AUD_SequencerFactory::getSpeedOfSound() const
void AUD_SequencerFactory::setSpeedOfSound(float speed)
{
- lock();
+ AUD_MutexLock lock(*this);
m_speed_of_sound = speed;
m_status++;
-
- unlock();
}
float AUD_SequencerFactory::getDopplerFactor() const
@@ -128,12 +121,10 @@ float AUD_SequencerFactory::getDopplerFactor() const
void AUD_SequencerFactory::setDopplerFactor(float factor)
{
- lock();
+ AUD_MutexLock lock(*this);
m_doppler_factor = factor;
m_status++;
-
- unlock();
}
AUD_DistanceModel AUD_SequencerFactory::getDistanceModel() const
@@ -143,12 +134,10 @@ AUD_DistanceModel AUD_SequencerFactory::getDistanceModel() const
void AUD_SequencerFactory::setDistanceModel(AUD_DistanceModel model)
{
- lock();
+ AUD_MutexLock lock(*this);
m_distance_model = model;
m_status++;
-
- unlock();
}
AUD_AnimateableProperty* AUD_SequencerFactory::getAnimProperty(AUD_AnimateablePropertyType type)
@@ -168,26 +157,22 @@ AUD_AnimateableProperty* AUD_SequencerFactory::getAnimProperty(AUD_AnimateablePr
AUD_Reference<AUD_SequencerEntry> AUD_SequencerFactory::add(AUD_Reference<AUD_IFactory> sound, float begin, float end, float skip)
{
- lock();
+ AUD_MutexLock lock(*this);
AUD_Reference<AUD_SequencerEntry> entry = new AUD_SequencerEntry(sound, begin, end, skip, m_id++);
m_entries.push_front(entry);
m_entry_status++;
- unlock();
-
return entry;
}
void AUD_SequencerFactory::remove(AUD_Reference<AUD_SequencerEntry> entry)
{
- lock();
+ AUD_MutexLock lock(*this);
m_entries.remove(entry);
m_entry_status++;
-
- unlock();
}
AUD_Reference<AUD_IReader> AUD_SequencerFactory::createQualityReader()
diff --git a/intern/audaspace/intern/AUD_SequencerFactory.h b/intern/audaspace/intern/AUD_SequencerFactory.h
index 38241112020..38cbc2d1867 100644
--- a/intern/audaspace/intern/AUD_SequencerFactory.h
+++ b/intern/audaspace/intern/AUD_SequencerFactory.h
@@ -32,6 +32,7 @@
#include "AUD_IFactory.h"
#include "AUD_AnimateableProperty.h"
+#include "AUD_ILockable.h"
#include <list>
#include <pthread.h>
@@ -41,7 +42,7 @@ class AUD_SequencerEntry;
/**
* This factory represents sequenced entries to play a sound scene.
*/
-class AUD_SequencerFactory : public AUD_IFactory
+class AUD_SequencerFactory : public AUD_IFactory, public AUD_ILockable
{
friend class AUD_SequencerReader;
private:
@@ -104,12 +105,12 @@ public:
/**
* Locks the factory.
*/
- void lock();
+ virtual void lock();
/**
* Unlocks the previously locked factory.
*/
- void unlock();
+ virtual void unlock();
/**
* Sets the audio output specification.
diff --git a/intern/audaspace/intern/AUD_SequencerHandle.cpp b/intern/audaspace/intern/AUD_SequencerHandle.cpp
index f4bfae6cee7..38d2ed38a7e 100644
--- a/intern/audaspace/intern/AUD_SequencerHandle.cpp
+++ b/intern/audaspace/intern/AUD_SequencerHandle.cpp
@@ -29,6 +29,7 @@
#include "AUD_SequencerHandle.h"
#include "AUD_ReadDevice.h"
+#include "AUD_MutexLock.h"
AUD_SequencerHandle::AUD_SequencerHandle(AUD_Reference<AUD_SequencerEntry> entry, AUD_ReadDevice& device) :
m_entry(entry),
@@ -68,7 +69,7 @@ void AUD_SequencerHandle::update(float position, float frame, float fps)
{
if(!m_handle.isNull())
{
- m_entry->lock();
+ AUD_MutexLock lock(*m_entry);
if(position >= m_entry->m_end && m_entry->m_end >= 0)
m_handle->pause();
else if(position >= m_entry->m_begin)
@@ -134,7 +135,6 @@ void AUD_SequencerHandle::update(float position, float frame, float fps)
if(m_entry->m_muted)
m_handle->setVolume(0);
- m_entry->unlock();
}
}
@@ -142,11 +142,10 @@ void AUD_SequencerHandle::seek(float position)
{
if(!m_handle.isNull())
{
- m_entry->lock();
+ AUD_MutexLock lock(*m_entry);
if(position >= m_entry->m_end && m_entry->m_end >= 0)
{
m_handle->pause();
- m_entry->unlock();
return;
}
@@ -160,6 +159,5 @@ void AUD_SequencerHandle::seek(float position)
m_handle->pause();
else
m_handle->resume();
- m_entry->unlock();
}
}
diff --git a/intern/audaspace/intern/AUD_SequencerReader.cpp b/intern/audaspace/intern/AUD_SequencerReader.cpp
index 2e41a99d3db..39a4d29e6e4 100644
--- a/intern/audaspace/intern/AUD_SequencerReader.cpp
+++ b/intern/audaspace/intern/AUD_SequencerReader.cpp
@@ -28,6 +28,7 @@
#include "AUD_SequencerReader.h"
+#include "AUD_MutexLock.h"
typedef std::list<AUD_Reference<AUD_SequencerHandle> >::iterator AUD_HandleIterator;
typedef std::list<AUD_Reference<AUD_SequencerEntry> >::iterator AUD_EntryIterator;
@@ -77,7 +78,7 @@ AUD_Specs AUD_SequencerReader::getSpecs() const
void AUD_SequencerReader::read(int& length, bool& eos, sample_t* buffer)
{
- m_factory->lock();
+ AUD_MutexLock lock(*m_factory);
if(m_factory->m_status != m_status)
{
@@ -197,8 +198,6 @@ void AUD_SequencerReader::read(int& length, bool& eos, sample_t* buffer)
time += float(len) / float(specs.rate);
}
- m_factory->unlock();
-
m_position += length;
eos = false;
diff --git a/intern/audaspace/intern/AUD_SoftwareDevice.cpp b/intern/audaspace/intern/AUD_SoftwareDevice.cpp
index 1d993abab73..1fbd0ad82d2 100644
--- a/intern/audaspace/intern/AUD_SoftwareDevice.cpp
+++ b/intern/audaspace/intern/AUD_SoftwareDevice.cpp
@@ -33,6 +33,7 @@
#include "AUD_IFactory.h"
#include "AUD_JOSResampleReader.h"
#include "AUD_LinearResampleReader.h"
+#include "AUD_MutexLock.h"
#include <cstring>
#include <cmath>
@@ -226,7 +227,7 @@ bool AUD_SoftwareDevice::AUD_SoftwareHandle::pause()
{
if(m_status)
{
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
if(m_status == AUD_STATUS_PLAYING)
{
@@ -236,12 +237,9 @@ bool AUD_SoftwareDevice::AUD_SoftwareHandle::pause()
if(m_device->m_playingSounds.empty())
m_device->playing(m_device->m_playback = false);
m_status = AUD_STATUS_PAUSED;
- m_device->unlock();
return true;
}
-
- m_device->unlock();
}
return false;
@@ -251,7 +249,7 @@ bool AUD_SoftwareDevice::AUD_SoftwareHandle::resume()
{
if(m_status)
{
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
if(m_status == AUD_STATUS_PAUSED)
{
@@ -261,11 +259,9 @@ bool AUD_SoftwareDevice::AUD_SoftwareHandle::resume()
if(!m_device->m_playback)
m_device->playing(m_device->m_playback = true);
m_status = AUD_STATUS_PLAYING;
- m_device->unlock();
return true;
}
- m_device->unlock();
}
return false;
@@ -276,25 +272,38 @@ bool AUD_SoftwareDevice::AUD_SoftwareHandle::stop()
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
+
+ if(!m_status)
+ return false;
- // AUD_XXX Create a reference of our own object so that it doesn't get
- // deleted before the end of this function
- AUD_Reference<AUD_SoftwareHandle> This = this;
+ m_status = AUD_STATUS_INVALID;
- if(m_status == AUD_STATUS_PLAYING)
+ for(AUD_HandleIterator it = m_device->m_playingSounds.begin(); it != m_device->m_playingSounds.end(); it++)
{
- m_device->m_playingSounds.remove(This);
+ if(it->get() == this)
+ {
+ AUD_Reference<AUD_SoftwareHandle> This = *it;
+
+ m_device->m_playingSounds.erase(it);
+
+ if(m_device->m_playingSounds.empty())
+ m_device->playing(m_device->m_playback = false);
+
+ return true;
+ }
+ }
- if(m_device->m_playingSounds.empty())
- m_device->playing(m_device->m_playback = false);
+ for(AUD_HandleIterator it = m_device->m_pausedSounds.begin(); it != m_device->m_pausedSounds.end(); it++)
+ {
+ if(it->get() == this)
+ {
+ m_device->m_pausedSounds.erase(it);
+ return true;
+ }
}
- else
- m_device->m_pausedSounds.remove(This);
- m_device->unlock();
- m_status = AUD_STATUS_INVALID;
- return true;
+ return false;
}
bool AUD_SoftwareDevice::AUD_SoftwareHandle::getKeep()
@@ -310,11 +319,12 @@ bool AUD_SoftwareDevice::AUD_SoftwareHandle::setKeep(bool keep)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- m_keep = keep;
+ if(!m_status)
+ return false;
- m_device->unlock();
+ m_keep = keep;
return true;
}
@@ -324,11 +334,12 @@ bool AUD_SoftwareDevice::AUD_SoftwareHandle::seek(float position)
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- m_reader->seek((int)(position * m_reader->getSpecs().rate));
+ if(!m_status)
+ return false;
- m_device->unlock();
+ m_reader->seek((int)(position * m_reader->getSpecs().rate));
return true;
}
@@ -336,13 +347,14 @@ bool AUD_SoftwareDevice::AUD_SoftwareHandle::seek(float position)
float AUD_SoftwareDevice::AUD_SoftwareHandle::getPosition()
{
if(!m_status)
- return 0.0f;
+ return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
- float position = m_reader->getPosition() / (float)m_device->m_specs.rate;
+ if(!m_status)
+ return 0.0f;
- m_device->unlock();
+ float position = m_reader->getPosition() / (float)m_device->m_specs.rate;
return position;
}
@@ -407,13 +419,14 @@ bool AUD_SoftwareDevice::AUD_SoftwareHandle::setStopCallback(stopCallback callba
if(!m_status)
return false;
- m_device->lock();
+ AUD_MutexLock lock(*m_device);
+
+ if(!m_status)
+ return false;
m_stop = callback;
m_stop_data = data;
- m_device->unlock();
-
return true;
}
@@ -691,7 +704,7 @@ void AUD_SoftwareDevice::mix(data_t* buffer, int length)
{
m_buffer.assureSize(length * AUD_SAMPLE_SIZE(m_specs));
- lock();
+ AUD_MutexLock lock(*this);
{
AUD_Reference<AUD_SoftwareDevice::AUD_SoftwareHandle> sound;
@@ -775,8 +788,6 @@ void AUD_SoftwareDevice::mix(data_t* buffer, int length)
sound->pause();
}
}
-
- unlock();
}
void AUD_SoftwareDevice::setPanning(AUD_IHandle* handle, float pan)
@@ -833,12 +844,12 @@ AUD_Reference<AUD_IHandle> AUD_SoftwareDevice::play(AUD_Reference<AUD_IReader> r
// play sound
AUD_Reference<AUD_SoftwareDevice::AUD_SoftwareHandle> sound = new AUD_SoftwareDevice::AUD_SoftwareHandle(this, reader, pitch, resampler, mapper, keep);
- lock();
+ AUD_MutexLock lock(*this);
+
m_playingSounds.push_back(sound);
if(!m_playback)
playing(m_playback = true);
- unlock();
return AUD_Reference<AUD_IHandle>(sound);
}
@@ -850,15 +861,13 @@ AUD_Reference<AUD_IHandle> AUD_SoftwareDevice::play(AUD_Reference<AUD_IFactory>
void AUD_SoftwareDevice::stopAll()
{
- lock();
+ AUD_MutexLock lock(*this);
while(!m_playingSounds.empty())
m_playingSounds.front()->stop();
while(!m_pausedSounds.empty())
m_pausedSounds.front()->stop();
-
- unlock();
}
void AUD_SoftwareDevice::lock()
diff --git a/intern/bsp/CMakeLists.txt b/intern/bsp/CMakeLists.txt
index e492c04423e..e3907c5273d 100644
--- a/intern/bsp/CMakeLists.txt
+++ b/intern/bsp/CMakeLists.txt
@@ -29,11 +29,10 @@ set(INC
../guardedalloc
../memutil
../moto/include
- ../../extern/carve/include
)
set(INC_SYS
-
+ ../../extern/carve/include
)
set(SRC
@@ -62,7 +61,7 @@ if(WITH_BOOST)
-DCARVE_SYSTEM_BOOST
)
- list(APPEND INC
+ list(APPEND INC_SYS
${BOOST_INCLUDE_DIR}
)
endif()
diff --git a/intern/bsp/extern/CSG_BooleanOps.h b/intern/bsp/extern/CSG_BooleanOps.h
index 94a74c30536..5ba6e0d76a1 100644
--- a/intern/bsp/extern/CSG_BooleanOps.h
+++ b/intern/bsp/extern/CSG_BooleanOps.h
@@ -61,9 +61,9 @@ extern "C" {
#endif
typedef struct {
- int vertex_index[4];
- int vertex_number;
- int orig_face;
+ int vertex_index[4];
+ int vertex_number;
+ int orig_face;
} CSG_IFace;
/**
@@ -72,7 +72,7 @@ typedef struct {
*/
typedef struct {
- float position[3];
+ float position[3];
} CSG_IVertex;
/**
diff --git a/intern/bsp/intern/BOP_CarveInterface.cpp b/intern/bsp/intern/BOP_CarveInterface.cpp
index 255d885007c..49c999a1dd4 100644
--- a/intern/bsp/intern/BOP_CarveInterface.cpp
+++ b/intern/bsp/intern/BOP_CarveInterface.cpp
@@ -58,9 +58,9 @@ static bool isQuadPlanar(carve::geom3d::Vector &v1, carve::geom3d::Vector &v2,
cross = carve::geom::cross(vec1, vec2);
float production = carve::geom::dot(cross, vec3);
- float magnitude = 1e-6 * cross.length();
+ float magnitude = 1e-5 * cross.length();
- return fabs(production) < magnitude;
+ return fabsf(production) < magnitude;
}
static bool isFacePlanar(CSG_IFace &face, std::vector<carve::geom3d::Vector> &vertices)
@@ -135,10 +135,10 @@ static bool Carve_checkEdgeFaceIntersections(carve::csg::Intersections &intersec
static inline bool Carve_facesAreCoplanar(const MeshSet<3>::face_t *a, const MeshSet<3>::face_t *b)
{
- carve::geom3d::Ray temp;
- // XXX: Find a better definition. This may be a source of problems
- // if floating point inaccuracies cause an incorrect answer.
- return !carve::geom3d::planeIntersection(a->plane, b->plane, temp);
+ carve::geom3d::Ray temp;
+ // XXX: Find a better definition. This may be a source of problems
+ // if floating point inaccuracies cause an incorrect answer.
+ return !carve::geom3d::planeIntersection(a->plane, b->plane, temp);
}
static bool Carve_checkMeshSetInterseciton_do(carve::csg::Intersections &intersections,
diff --git a/intern/container/CMakeLists.txt b/intern/container/CMakeLists.txt
index b29eea37bc7..8adc46a59de 100644
--- a/intern/container/CMakeLists.txt
+++ b/intern/container/CMakeLists.txt
@@ -33,14 +33,11 @@ set(INC_SYS
)
set(SRC
- intern/CTR_List.cpp
-
CTR_HashedPtr.h
- CTR_List.h
CTR_Map.h
CTR_TaggedIndex.h
CTR_TaggedSetOps.h
- CTR_UHeap.h
)
+# infact nothing to compile!
blender_add_lib(bf_intern_ctr "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/intern/container/CTR_HashedPtr.h b/intern/container/CTR_HashedPtr.h
index 11dc37b3625..b7ac460f270 100644
--- a/intern/container/CTR_HashedPtr.h
+++ b/intern/container/CTR_HashedPtr.h
@@ -30,8 +30,8 @@
* \ingroup ctr
*/
-#ifndef CTR_HASHEDPTR_H
-#define CTR_HASHEDPTR_H
+#ifndef __CTR_HASHEDPTR_H__
+#define __CTR_HASHEDPTR_H__
#include <stdlib.h>
@@ -43,13 +43,20 @@ inline unsigned int CTR_Hash(void *inDWord)
class CTR_HashedPtr
{
- void* m_valptr;
+ void *m_valptr;
public:
- CTR_HashedPtr(void* val) : m_valptr(val) {};
- unsigned int hash() const { return CTR_Hash(m_valptr);};
- inline friend bool operator ==(const CTR_HashedPtr & rhs, const CTR_HashedPtr & lhs) { return rhs.m_valptr == lhs.m_valptr;};
- void *getValue() const { return m_valptr; }
+ CTR_HashedPtr(void *val) : m_valptr(val) {
+ };
+ unsigned int hash() const {
+ return CTR_Hash(m_valptr);
+ };
+ inline friend bool operator ==(const CTR_HashedPtr & rhs, const CTR_HashedPtr & lhs) {
+ return rhs.m_valptr == lhs.m_valptr;
+ };
+ void *getValue() const {
+ return m_valptr;
+ }
};
-#endif //CTR_HASHEDPTR_H
+#endif /* __CTR_HASHEDPTR_H__ */
diff --git a/intern/container/CTR_List.h b/intern/container/CTR_List.h
deleted file mode 100644
index 404a08fddf2..00000000000
--- a/intern/container/CTR_List.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file container/CTR_List.h
- * \ingroup ctr
- */
-
-
-
-#ifndef CTR_LIST_H
-#define CTR_LIST_H
-
-class CTR_Link {
-public:
- CTR_Link(
- );
-
- CTR_Link(
- CTR_Link *next,
- CTR_Link *prev
- );
-
- CTR_Link *
- getNext(
- ) const;
-
- CTR_Link *
- getPrev(
- ) const;
-
- bool
- isHead(
- ) const;
-
- bool
- isTail(
- ) const;
-
- void
- insertBefore(
- CTR_Link *link
- );
-
- void
- insertAfter(
- CTR_Link *link
- );
-
- void
- remove(
- );
-
-private:
- CTR_Link *m_next;
- CTR_Link *m_prev;
-};
-
-class CTR_List {
-public:
-
- CTR_List(
- );
-
- CTR_Link *
- getHead(
- ) const;
-
- CTR_Link *
- getTail(
- ) const;
-
- void
- addHead(
- CTR_Link *link
- );
-
- void
- addTail(
- CTR_Link *link
- );
-
-private:
- CTR_Link m_head;
- CTR_Link m_tail;
-};
-
-#endif
-
diff --git a/intern/container/CTR_Map.h b/intern/container/CTR_Map.h
index 9557821d642..c278fe5330c 100644
--- a/intern/container/CTR_Map.h
+++ b/intern/container/CTR_Map.h
@@ -29,22 +29,22 @@
* \ingroup ctr
*/
-
-#ifndef CTR_MAP_H
-#define CTR_MAP_H
+#ifndef __CTR_MAP_H__
+#define __CTR_MAP_H__
template <class Key, class Value>
class CTR_Map {
private:
struct Entry {
Entry (Entry *next, Key key, Value value) :
- m_next(next),
- m_key(key),
- m_value(value) {}
+ m_next(next),
+ m_key(key),
+ m_value(value) {
+ }
Entry *m_next;
- Key m_key;
- Value m_value;
+ Key m_key;
+ Value m_value;
};
public:
@@ -63,18 +63,18 @@ public:
for (int i = 0; i < m_num_buckets; ++i) {
m_buckets[i] = 0;
- for (Entry *entry = map.m_buckets[i]; entry; entry=entry->m_next)
+ for (Entry *entry = map.m_buckets[i]; entry; entry = entry->m_next) {
insert(entry->m_key, entry->m_value);
+ }
}
}
- int size() {
- int count=0;
- for (int i=0;i<m_num_buckets;i++)
- {
- Entry* bucket = m_buckets[i];
- while(bucket)
- {
+ int size()
+ {
+ int count = 0;
+ for (int i = 0; i < m_num_buckets; i++) {
+ Entry *bucket = m_buckets[i];
+ while (bucket) {
bucket = bucket->m_next;
count++;
}
@@ -82,15 +82,13 @@ public:
return count;
}
- Value* at(int index) {
- int count=0;
- for (int i=0;i<m_num_buckets;i++)
- {
- Entry* bucket = m_buckets[i];
- while(bucket)
- {
- if (count==index)
- {
+ Value *at(int index)
+ {
+ int count = 0;
+ for (int i = 0; i < m_num_buckets; i++) {
+ Entry *bucket = m_buckets[i];
+ while (bucket) {
+ if (count == index) {
return &bucket->m_value;
}
bucket = bucket->m_next;
@@ -100,15 +98,13 @@ public:
return 0;
}
- Key* getKey(int index) {
- int count=0;
- for (int i=0;i<m_num_buckets;i++)
- {
- Entry* bucket = m_buckets[i];
- while(bucket)
- {
- if (count==index)
- {
+ Key *getKey(int index)
+ {
+ int count = 0;
+ for (int i = 0; i < m_num_buckets; i++) {
+ Entry *bucket = m_buckets[i];
+ while (bucket) {
+ if (count == index) {
return &bucket->m_key;
}
bucket = bucket->m_next;
@@ -118,7 +114,8 @@ public:
return 0;
}
- void clear() {
+ void clear()
+ {
for (int i = 0; i < m_num_buckets; ++i) {
Entry *entry_ptr = m_buckets[i];
@@ -131,12 +128,14 @@ public:
}
}
- ~CTR_Map() {
+ ~CTR_Map()
+ {
clear();
- delete [] m_buckets;
+ delete[] m_buckets;
}
- void insert(const Key& key, const Value& value) {
+ void insert(const Key& key, const Value& value)
+ {
Entry *entry_ptr = m_buckets[key.hash() % m_num_buckets];
while ((entry_ptr != 0) && !(key == entry_ptr->m_key)) {
entry_ptr = entry_ptr->m_next;
@@ -151,7 +150,8 @@ public:
}
}
- void remove(const Key& key) {
+ void remove(const Key& key)
+ {
Entry **entry_ptr = &m_buckets[key.hash() % m_num_buckets];
while ((*entry_ptr != 0) && !(key == (*entry_ptr)->m_key)) {
entry_ptr = &(*entry_ptr)->m_next;
@@ -164,7 +164,8 @@ public:
}
}
- Value *operator[](Key key) {
+ Value *operator[](Key key)
+ {
Entry *bucket = m_buckets[key.hash() % m_num_buckets];
while ((bucket != 0) && !(key == bucket->m_key)) {
bucket = bucket->m_next;
@@ -177,5 +178,4 @@ private:
Entry **m_buckets;
};
-#endif
-
+#endif /* __CTR_MAP_H__ */
diff --git a/intern/container/CTR_TaggedIndex.h b/intern/container/CTR_TaggedIndex.h
index 8420414d6c7..0eb4e02e84f 100644
--- a/intern/container/CTR_TaggedIndex.h
+++ b/intern/container/CTR_TaggedIndex.h
@@ -29,13 +29,6 @@
* \ingroup ctr
*/
-
-/**
-
- * Copyright (C) 2001 NaN Technologies B.V.
- * Simple tagged index class.
- */
-
#ifndef __CTR_TAGGEDINDEX_H__
#define __CTR_TAGGEDINDEX_H__
@@ -53,7 +46,6 @@
#include "MEM_sys_types.h"
enum {
-
empty_tag = 0x0,
empty_index = 0xffffffff
};
@@ -191,7 +183,7 @@ public:
return (Tag() == Empty().Tag());
}
- // functionals
+ /* functionals */
struct greater : std::binary_function<CTR_TaggedIndex, CTR_TaggedIndex, bool>
{
@@ -213,7 +205,6 @@ private :
unsigned int m_val;
-};
-
-#endif
+};
+#endif /* __CTR_TAGGEDINDEX_H__ */
diff --git a/intern/container/CTR_TaggedSetOps.h b/intern/container/CTR_TaggedSetOps.h
index d30081d2d60..6ebf20b77bf 100644
--- a/intern/container/CTR_TaggedSetOps.h
+++ b/intern/container/CTR_TaggedSetOps.h
@@ -50,16 +50,16 @@
* type ObjectType must have the following public methods to be used by
* this template class:
*
- * int
+ * int
* OpenTag(void) --- return a persistent tag value for the primitive
*
- * void
+ * void
* SetOpenTag(int bla) --- set the persistent tag value for this primitive to bla.
*
- * bool
+ * bool
* SelectTag() --- return a persistent boolean tag for this primitive
*
- * void
+ * void
* SetSelectTag(bool bla) --- set the persistent boolean tag for this primitive to bla.
*
* Here persistent means that the tag should be associated with the object for the
@@ -86,16 +86,16 @@ public :
unsigned int shift
) {
- // iterate through vectors in index_list
- // iterate through individual members of each vector
- // mark each obejct that the index points to
+ /* iterate through vectors in index_list
+ * iterate through individual members of each vector
+ * mark each obejct that the index points to */
typename std::vector< std::vector<IndexType> >::const_iterator
last_vector = index_list.end();
typename std::vector< std::vector<IndexType> >::const_iterator
start_vector = index_list.begin();
- // FIXME some temporary space
+ /* FIXME some temporary space */
std::vector<IndexType> temp_union;
temp_union.reserve(64);
@@ -114,7 +114,7 @@ public :
ObjectType & prim = primitives[*start_index];
if (!prim.OpenTag()) {
- // compute the union
+ /* compute the union */
temp_union.push_back(*start_index);
}
int tag = prim.OpenTag();
@@ -126,7 +126,7 @@ public :
++tag_num;
}
- // now iterate through the union and pull out all those with the right tag
+ /* now iterate through the union and pull out all those with the right tag */
typename std::vector<IndexType>::const_iterator last_index =
temp_union.end();
@@ -138,20 +138,20 @@ public :
ObjectType & prim = primitives[*start_index];
if (prim.OpenTag() == tag_num) {
- //it's part of the intersection!
+ /* it's part of the intersection! */
output.push_back(*start_index);
- // because we're iterating through the union
- // it's safe to remove the tag at this point
+ /* because we're iterating through the union
+ * it's safe to remove the tag at this point */
prim.SetOpenTag(prim.OpenTag() & ~mask);
}
}
};
- // note not a strict set intersection!
- // if x appears twice in b and is part of the intersection
- // it will appear twice in the intersection
+ /* note not a strict set intersection!
+ * if x appears twice in b and is part of the intersection
+ * it will appear twice in the intersection */
static
void
@@ -180,7 +180,7 @@ public :
output.push_back(*start_index);
}
}
- // deselect
+ /* deselect */
last_index = a.end();
start_index = a.begin();
@@ -199,9 +199,9 @@ public :
std::vector<IndexType> &output
) {
- // iterate through vectors in index_list
- // iterate through individual members of each vector
- // mark each obejct that the index points to
+ /* iterate through vectors in index_list
+ * iterate through individual members of each vector
+ * mark each obejct that the index points to */
typename std::vector< std::vector<IndexType> >::const_iterator
last_vector = index_list.end();
@@ -220,15 +220,15 @@ public :
ObjectType & prim = primitives[*start_index];
if (!prim.SelectTag()) {
- // compute the union
+ /* compute the union */
output.push_back(*start_index);
prim.SetSelectTag(true);
}
}
}
- // now iterate through the union and reset the tags
-
+ /* now iterate through the union and reset the tags */
+
typename std::vector<IndexType>::const_iterator last_index =
output.end();
typename std::vector<IndexType>::iterator start_index =
@@ -238,7 +238,7 @@ public :
ObjectType & prim = primitives[*start_index];
prim.SetSelectTag(false);
- }
+ }
}
@@ -251,8 +251,8 @@ public :
std::vector< IndexType> &output
) {
- // iterate through b mark all
- // iterate through a and add to output all unmarked
+ /* iterate through b mark all
+ * iterate through a and add to output all unmarked */
typename std::vector<IndexType>::const_iterator last_index =
b.end();
@@ -276,7 +276,7 @@ public :
}
}
- // clean up the tags
+ /* clean up the tags */
last_index = b.end();
start_index = b.begin();
@@ -290,12 +290,11 @@ public :
private :
- // private constructor - this class is not meant for
- // instantiation
+ /* private constructor - this class is not meant for
+ * instantiation */
CTR_TaggedSetOps();
};
-#endif
-
+#endif /* __CTR_TAGGEDSETOPS_H__ */
diff --git a/intern/container/CTR_UHeap.h b/intern/container/CTR_UHeap.h
deleted file mode 100644
index 8330faa2f54..00000000000
--- a/intern/container/CTR_UHeap.h
+++ /dev/null
@@ -1,307 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file container/CTR_UHeap.h
- * \ingroup ctr
- */
-
-
-/**
-
- * Copyright (C) 2001 NaN Technologies B.V.
- *
- * @author Laurence
- * @mainpage CTR_UHeap an updatable heap template class (also
- * known as an updatable priority queue)
- *
- * Todo: Make CTR_UHeapable a template class with m_key the
- * template parameter, so that arbitrary value types with
- * operators (=,>) defined can be used.
- *
- */
-
-#ifndef __CTR_UHEAP_H__
-#define __CTR_UHEAP_H__
-
-#include <vector>
-
-#include "MEM_NonCopyable.h"
-
-class CTR_UHeapable {
-
-public:
- int &
- HeapPos(
- ) {
- return m_ind;
- };
- float &
- HeapKey(
- ) {
- return m_key;
- };
-
- const
- float &
- HeapKey(
- ) const {
- return m_key;
- };
-
- const
- int &
- HeapPos(
- ) const {
- return m_ind;
- };
-
-private:
-
- float m_key;
- int m_ind;
-
-protected:
-
- CTR_UHeapable(
- ) : m_key(0),
- m_ind(0)
- {
- };
-
- ~CTR_UHeapable(
- ) {
- };
-};
-
-template <class HeapType>
-class CTR_UHeap : public MEM_NonCopyable
-{
-
-public:
-
- static
- CTR_UHeap *
- New(
- ) {
- return new CTR_UHeap();
- }
-
- void
- MakeHeap(
- HeapType *base
- ) {
- int i;
- int start = Parent(m_vector.size() - 1);
- for (i = start; i >= 0; --i) {
- DownHeap(base, i);
- }
- };
-
- void
- Insert(
- HeapType *base,
- int elem
- ) {
- // add element to vector
- m_vector.push_back(elem);
- base[elem].HeapPos() = m_vector.size() - 1;
-
- // push the element up the heap
- UpHeap(base, m_vector.size() - 1);
- }
-
- // access to the vector for initial loading of elements
-
- std::vector<int> &
- HeapVector(
- ) {
- return m_vector;
- };
-
-
- void
- Remove(
- HeapType *base,
- int i
- ) {
-
- // exchange with last element - pop last
- // element and move up or down the heap as appropriate
- if (m_vector.empty()) {
- assert(false);
- }
-
- if (i != int(m_vector.size()) - 1) {
-
- Swap(base, i, m_vector.size() - 1);
- m_vector.pop_back();
-
- if (!m_vector.empty()) {
- UpHeap(base, i);
- DownHeap(base, i);
- }
- }
- else {
- m_vector.pop_back();
- }
- }
-
- int
- Top(
- ) const {
- if (m_vector.empty()) return -1;
- return m_vector[0];
- }
-
-
- void
- SC_Heap(
- HeapType *base
- ) {
- int i;
- for (i = 1; i < int(m_vector.size()); i++) {
-
- CTR_UHeapable *elem = base + m_vector[i];
- CTR_UHeapable *p_elem = base + m_vector[Parent(i)];
-
- assert(p_elem->HeapKey() >= elem->HeapKey());
- assert(elem->HeapPos() == i);
- }
-
- };
-
-
- ~CTR_UHeap(
- ) {
- };
-
-
-private:
-
- CTR_UHeap(
- ) {
- };
-
-
- std::vector<int> m_vector;
-
-private:
- void
- Swap(
- HeapType *base,
- int i,
- int j
- ) {
- std::swap(m_vector[i], m_vector[j]);
-
- CTR_UHeapable *heap_i = base + m_vector[i];
- CTR_UHeapable *heap_j = base + m_vector[j];
-
- // Exchange heap positions
- heap_i->HeapPos() = i;
- heap_j->HeapPos() = j;
- }
-
- int
- Parent(
- unsigned int i
- ) {
- return (i - 1) >> 1;
- }
- int
- Left(
- int i
- ) {
- return (i << 1) + 1;
- }
-
- int
- Right(
- int i
- ) {
- return (i << 1) + 2;
- }
-
- float
- HeapVal(
- HeapType *base,
- int i
- ) {
- return base[m_vector[i]].HeapKey();
- }
-
- void
- DownHeap(
- HeapType *base,
- int i
- ) {
- int heap_size = m_vector.size();
-
- int l = Left(i);
- int r = Right(i);
-
- int largest;
- if (l < heap_size && HeapVal(base, l) > HeapVal(base, i)) {
- largest = l;
- }
- else {
- largest = i;
- }
-
- if (r < heap_size && HeapVal(base, r) > HeapVal(base, largest)) {
- largest = r;
- }
-
- if (largest != i) {
- // exchange i and largest
- Swap(base, i, largest);
- DownHeap(base, largest);
- }
- }
-
- void
- UpHeap(
- HeapType *base,
- int i
- ) {
-
- // swap parents untill it's found a place in the heap < it's parent or
- // top of heap
-
- while (i > 0) {
- int p = Parent(i);
- if (HeapVal(base, i) < HeapVal(base, p)) {
- break;
- }
- Swap(base, p, i);
- i = p;
- }
- }
-};
-
-#endif
-
diff --git a/intern/container/intern/CTR_List.cpp b/intern/container/intern/CTR_List.cpp
deleted file mode 100644
index c72d3ccf0d8..00000000000
--- a/intern/container/intern/CTR_List.cpp
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file container/intern/CTR_List.cpp
- * \ingroup ctr
- */
-
-
-#include "CTR_List.h"
-
-
-CTR_Link::CTR_Link() :
- m_next(0),
- m_prev(0)
-{
-}
-
-CTR_Link::CTR_Link(CTR_Link *next, CTR_Link *prev) :
- m_next(next),
- m_prev(prev)
-{
-}
-
-CTR_Link *
-CTR_Link::getNext() const
-{
- return m_next;
-}
-
-CTR_Link *
-CTR_Link::getPrev() const
-{
- return m_prev;
-}
-
-bool
-CTR_Link::isHead() const
-{
- return m_prev == 0;
-}
-
-bool
-CTR_Link::isTail() const
-{
- return m_next == 0;
-}
-
-void
-CTR_Link::insertBefore(CTR_Link *link)
-{
- m_next = link;
- m_prev = link->m_prev;
- m_next->m_prev = this;
- m_prev->m_next = this;
-}
-
-void
-CTR_Link::insertAfter(CTR_Link *link)
-{
- m_next = link->m_next;
- m_prev = link;
- m_next->m_prev = this;
- m_prev->m_next = this;
-}
-
-void
-CTR_Link::remove()
-{
- m_next->m_prev = m_prev;
- m_prev->m_next = m_next;
-}
-
-
-CTR_List::CTR_List() :
- m_head(&m_tail, 0),
- m_tail(0, &m_head)
-{
-}
-
-CTR_Link *
-CTR_List:: getHead() const
-{
- return m_head.getNext();
-}
-
-CTR_Link *
-CTR_List::getTail() const
-{
- return m_tail.getPrev();
-}
-
-void
-CTR_List::addHead(CTR_Link *link)
-{
- link->insertAfter(&m_head);
-}
-
-void
-CTR_List::addTail(CTR_Link *link)
-{
- link->insertBefore(&m_tail);
-}
-
diff --git a/intern/cycles/CMakeLists.txt b/intern/cycles/CMakeLists.txt
index 337eebe4be0..7562ee0a0a5 100644
--- a/intern/cycles/CMakeLists.txt
+++ b/intern/cycles/CMakeLists.txt
@@ -41,6 +41,7 @@ endif()
if(WITH_CYCLES_OSL)
add_definitions(-DWITH_OSL)
+ include_directories(${OSL_INCLUDES})
endif()
if(WITH_CYCLES_PARTIO)
@@ -56,9 +57,11 @@ add_definitions(-DWITH_CUDA)
add_definitions(-DWITH_MULTI)
include_directories(
+ SYSTEM
${BOOST_INCLUDE_DIR}
${OPENIMAGEIO_INCLUDE_DIRS}
- ${OPENIMAGEIO_INCLUDE_DIRS}/OpenImageIO)
+ ${OPENIMAGEIO_INCLUDE_DIRS}/OpenImageIO
+ ${OPENEXR_INCLUDE_DIR})
# Subdirectories
diff --git a/intern/cycles/SConscript b/intern/cycles/SConscript
index a7b8637e3ad..c0e0353d37d 100644
--- a/intern/cycles/SConscript
+++ b/intern/cycles/SConscript
@@ -29,7 +29,7 @@ if env['WITH_BF_CYCLES_CUDA_BINARIES']:
incs.extend('. bvh render device kernel kernel/osl kernel/svm util subd'.split())
incs.extend('#intern/guardedalloc #source/blender/makesrna #source/blender/makesdna'.split())
incs.extend('#source/blender/blenloader ../../source/blender/makesrna/intern'.split())
-incs.extend('#extern/glew/include'.split())
+incs.extend('#extern/glew/include #intern/mikktspace'.split())
incs.append(cycles['BF_OIIO_INC'])
incs.append(cycles['BF_BOOST_INC'])
incs.append(cycles['BF_PYTHON_INC'])
diff --git a/intern/cycles/app/CMakeLists.txt b/intern/cycles/app/CMakeLists.txt
index 2e2897d0443..83b3f731ffe 100644
--- a/intern/cycles/app/CMakeLists.txt
+++ b/intern/cycles/app/CMakeLists.txt
@@ -9,6 +9,8 @@ set(INC
../render
../subd
)
+set(INC_SYS
+)
set(LIBRARIES
cycles_device
@@ -38,6 +40,7 @@ if(WITH_CYCLES_PARTIO)
endif()
include_directories(${INC})
+include_directories(SYSTEM ${INC_SYS})
if(WITH_CYCLES_TEST)
set(SRC
diff --git a/intern/cycles/app/cycles_xml.cpp b/intern/cycles/app/cycles_xml.cpp
index 87a238e508c..5de9d71b8cc 100644
--- a/intern/cycles/app/cycles_xml.cpp
+++ b/intern/cycles/app/cycles_xml.cpp
@@ -591,6 +591,7 @@ static void xml_read_shader_graph(const XMLReadState& state, Shader *shader, pug
if(string_iequals(in->name, attr.name())) {
switch(in->type) {
case SHADER_SOCKET_FLOAT:
+ case SHADER_SOCKET_INT:
xml_read_float(&in->value.x, node, attr.name());
break;
case SHADER_SOCKET_COLOR:
diff --git a/intern/cycles/blender/CMakeLists.txt b/intern/cycles/blender/CMakeLists.txt
index a8c7eef89fa..292c37d6b61 100644
--- a/intern/cycles/blender/CMakeLists.txt
+++ b/intern/cycles/blender/CMakeLists.txt
@@ -7,6 +7,7 @@ set(INC
../util
../subd
../../guardedalloc
+ ../../mikktspace
../../../source/blender/makesdna
../../../source/blender/makesrna
../../../source/blender/blenloader
@@ -38,6 +39,7 @@ set(ADDON_FILES
addon/__init__.py
addon/engine.py
addon/enums.py
+ addon/osl.py
addon/presets.py
addon/properties.py
addon/ui.py
diff --git a/intern/cycles/blender/addon/__init__.py b/intern/cycles/blender/addon/__init__.py
index 4a60a329e2b..16697c08b2b 100644
--- a/intern/cycles/blender/addon/__init__.py
+++ b/intern/cycles/blender/addon/__init__.py
@@ -25,7 +25,7 @@ bl_info = {
"location": "Info header, render engine menu",
"description": "Cycles Render Engine integration",
"warning": "",
- "wiki_url": "http://wiki.blender.org/index.php/Dev:2.6/Source/Render/Cycles",
+ "wiki_url": "http://wiki.blender.org/index.php/Doc:2.6/Manual/Render/Cycles",
"tracker_url": "",
"support": 'OFFICIAL',
"category": "Render"}
@@ -71,6 +71,13 @@ class CyclesRender(bpy.types.RenderEngine):
def view_draw(self, context):
engine.draw(self, context.region, context.space_data, context.region_data)
+ def update_script_node(self, node):
+ if engine.with_osl():
+ from . import osl
+ osl.update_script_node(node, self.report)
+ else:
+ self.report({'ERROR'}, "OSL support disabled in this build.")
+
def register():
properties.register()
@@ -84,3 +91,4 @@ def unregister():
properties.unregister()
presets.unregister()
bpy.utils.unregister_module(__name__)
+
diff --git a/intern/cycles/blender/addon/engine.py b/intern/cycles/blender/addon/engine.py
index 05b1f883594..e4f80cb4d5d 100644
--- a/intern/cycles/blender/addon/engine.py
+++ b/intern/cycles/blender/addon/engine.py
@@ -83,3 +83,4 @@ def available_devices():
def with_osl():
import _cycles
return _cycles.with_osl
+
diff --git a/intern/cycles/blender/addon/enums.py b/intern/cycles/blender/addon/enums.py
index 6cc3010eb0e..e63e1e84245 100644
--- a/intern/cycles/blender/addon/enums.py
+++ b/intern/cycles/blender/addon/enums.py
@@ -60,3 +60,4 @@ panorama_types = (
('FISHEYE_EQUIDISTANT', "Fisheye Equidistant", "Ideal for fulldomes, ignore the sensor dimensions"),
('FISHEYE_EQUISOLID', "Fisheye Equisolid", "Similar to most fisheye modern lens, take sensor dimensions into consideration"),
)
+
diff --git a/intern/cycles/blender/addon/osl.py b/intern/cycles/blender/addon/osl.py
new file mode 100644
index 00000000000..aac1e2422b9
--- /dev/null
+++ b/intern/cycles/blender/addon/osl.py
@@ -0,0 +1,127 @@
+#
+# Copyright 2011, Blender Foundation.
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+
+# <pep8 compliant>
+
+import bpy, _cycles, os, tempfile
+
+# compile .osl file with given filepath to temporary .oso file
+def osl_compile(input_path, report):
+ output_file = tempfile.NamedTemporaryFile(mode='w', suffix=".oso", delete=False)
+ output_path = output_file.name
+ output_file.close()
+
+ ok = _cycles.osl_compile(input_path, output_path)
+
+ if ok:
+ report({'INFO'}, "OSL shader compilation succeeded")
+
+ return ok, output_path
+
+# compile and update shader script node
+def update_script_node(node, report):
+ import os, shutil
+
+ if node.mode == 'EXTERNAL':
+ # compile external script file
+ script_path = bpy.path.abspath(node.filepath, library=node.id_data.library)
+ script_path_noext, script_ext = os.path.splitext(script_path)
+
+ if script_ext == ".oso":
+ # it's a .oso file, no need to compile
+ ok, oso_path = True, script_path
+ oso_file_remove = False
+ elif script_ext == ".osl":
+ # compile .osl file
+ ok, oso_path = osl_compile(script_path, report)
+ oso_file_remove = True
+
+ if ok:
+ # copy .oso from temporary path to .osl directory
+ dst_path = script_path_noext + ".oso"
+ try:
+ shutil.copy2(oso_path, dst_path)
+ except:
+ report({'ERROR'}, "Failed to write .oso file next to external .osl file at " + dst_path)
+ elif os.path.dirname(node.filepath) == "":
+ # module in search path
+ oso_path = node.filepath
+ oso_file_remove = False
+ ok = True
+ else:
+ # unknown
+ report({'ERROR'}, "External shader script must have .osl or .oso extension, or be a module name")
+ ok = False
+
+ if ok:
+ node.bytecode = ""
+ node.bytecode_hash = ""
+
+ elif node.mode == 'INTERNAL' and node.script:
+ # internal script, we will store bytecode in the node
+ script = node.script
+ osl_path = bpy.path.abspath(script.filepath, library=script.library)
+
+ if script.is_in_memory or script.is_dirty or script.is_modified or not os.path.exists(osl_path):
+ # write text datablock contents to temporary file
+ osl_file = tempfile.NamedTemporaryFile(mode='w', suffix=".osl", delete=True)
+ osl_file.write(script.as_string())
+ osl_file.flush()
+ ok, oso_path = osl_compile(osl_file.name, report)
+ oso_file_remove = False
+ osl_file.close()
+ else:
+ # compile text datablock from disk directly
+ ok, oso_path = osl_compile(osl_path, report)
+ oso_file_remove = False
+
+ if ok:
+ # read bytecode
+ try:
+ oso = open(oso_path, 'r')
+ node.bytecode = oso.read()
+ oso.close()
+ except:
+ import traceback
+ traceback.print_exc()
+
+ report({'ERROR'}, "Can't read OSO bytecode to store in node at %r" % oso_path)
+ ok = False
+
+ else:
+ report({'WARNING'}, "No text or file specified in node, nothing to compile")
+ return
+
+ if ok:
+ # now update node with new sockets
+ ok = _cycles.osl_update_node(node.id_data.as_pointer(), node.as_pointer(), oso_path)
+
+ if not ok:
+ report({'ERROR'}, "OSL query failed to open " + oso_path)
+ else:
+ report({'ERROR'}, "OSL script compilation failed, see console for errors")
+
+ # remove temporary oso file
+ if oso_file_remove:
+ try:
+ os.remove(oso_path)
+ except:
+ pass
+
+ return ok
+
diff --git a/intern/cycles/blender/addon/properties.py b/intern/cycles/blender/addon/properties.py
index 7f3eca471e6..0b8ca6e0fbe 100644
--- a/intern/cycles/blender/addon/properties.py
+++ b/intern/cycles/blender/addon/properties.py
@@ -136,7 +136,8 @@ class CyclesRenderSettings(bpy.types.PropertyGroup):
)
cls.blur_glossy = FloatProperty(
name="Filter Glossy",
- description="Adaptively blur glossy shaders after blurry bounces, to reduce noise at the cost of accuracy",
+ description="Adaptively blur glossy shaders after blurry bounces, "
+ "to reduce noise at the cost of accuracy",
min=0.0, max=10.0,
default=0.0,
)
@@ -230,7 +231,9 @@ class CyclesRenderSettings(bpy.types.PropertyGroup):
cls.sample_clamp = FloatProperty(
name="Clamp",
- description="If non-zero, the maximum value for a sample, higher values will be scaled down to avoid too much noise and slow convergence at the cost of accuracy",
+ description="If non-zero, the maximum value for a sample, "
+ "higher values will be scaled down to avoid too "
+ "much noise and slow convergence at the cost of accuracy",
min=0.0, max=1e8,
default=0.0,
)
@@ -242,11 +245,12 @@ class CyclesRenderSettings(bpy.types.PropertyGroup):
default=1024,
)
- cls.resolution_divider = IntProperty(
- name="Resolution Divider",
- description="For viewport render, the number of lower resolutions to render before the full resolution",
- min=1, max=512,
- default=4,
+ cls.preview_start_resolution = IntProperty(
+ name="Start Resolution",
+ description="Resolution to start rendering preview at, "
+ "progressively increasing it to the full viewport size",
+ min=8, max=16384,
+ default=64,
)
cls.debug_reset_timeout = FloatProperty(
@@ -284,6 +288,14 @@ class CyclesRenderSettings(bpy.types.PropertyGroup):
description="Cache last built BVH to disk for faster re-render if no geometry changed",
default=False,
)
+ cls.use_progressive_refine = BoolProperty(
+ name="Progressive Refine",
+ description="Instead of rendering each tile until it is finished, "
+ "refine the whole image progressively "
+ "(this renders somewhat slower, "
+ "but time can be saved by manually stopping the render when the noise is low enough)",
+ default=False,
+ )
@classmethod
def unregister(cls):
@@ -369,12 +381,15 @@ class CyclesMaterialSettings(bpy.types.PropertyGroup):
)
cls.sample_as_light = BoolProperty(
name="Sample as Lamp",
- description="Use direct light sampling for this material, disabling may reduce overall noise for large objects that emit little light compared to other light sources",
+ description="Use direct light sampling for this material, "
+ "disabling may reduce overall noise for large "
+ "objects that emit little light compared to other light sources",
default=True,
)
cls.homogeneous_volume = BoolProperty(
name="Homogeneous Volume",
- description="When using volume rendering, assume volume has the same density everywhere, for faster rendering",
+ description="When using volume rendering, assume volume has the same density everywhere, "
+ "for faster rendering",
default=False,
)
@@ -418,12 +433,14 @@ class CyclesWorldSettings(bpy.types.PropertyGroup):
)
cls.sample_as_light = BoolProperty(
name="Sample as Lamp",
- description="Use direct light sampling for the environment, enabling for non-solid colors is recommended",
+ description="Use direct light sampling for the environment, "
+ "enabling for non-solid colors is recommended",
default=False,
)
cls.sample_map_resolution = IntProperty(
name="Map Resolution",
- description="Importance map size is resolution x resolution; higher values potentially produce less noise, at the cost of memory and speed",
+ description="Importance map size is resolution x resolution; "
+ "higher values potentially produce less noise, at the cost of memory and speed",
min=4, max=8096,
default=256,
)
diff --git a/intern/cycles/blender/addon/ui.py b/intern/cycles/blender/addon/ui.py
index 7486edf2319..9cc58e65bef 100644
--- a/intern/cycles/blender/addon/ui.py
+++ b/intern/cycles/blender/addon/ui.py
@@ -59,7 +59,7 @@ class CyclesRender_PT_sampling(CyclesButtonsPanel, Panel):
col = split.column()
sub = col.column()
- sub.enabled = (device_type == 'NONE' or cscene.device == 'CPU')
+ sub.active = (device_type == 'NONE' or cscene.device == 'CPU')
sub.prop(cscene, "progressive")
sub = col.column(align=True)
@@ -134,10 +134,6 @@ class CyclesRender_PT_motion_blur(CyclesButtonsPanel, Panel):
bl_label = "Motion Blur"
bl_options = {'DEFAULT_CLOSED'}
- @classmethod
- def poll(cls, context):
- return False
-
def draw_header(self, context):
rd = context.scene.render
@@ -197,10 +193,12 @@ class CyclesRender_PT_performance(CyclesButtonsPanel, Panel):
sub.prop(rd, "threads")
sub = col.column(align=True)
- sub.label(text="Tiles:")
+ sub.label(text="Tile Size:")
- sub.prop(rd, "parts_x", text="X")
- sub.prop(rd, "parts_y", text="Y")
+ sub.prop(rd, "tile_x", text="X")
+ sub.prop(rd, "tile_y", text="Y")
+
+ sub.prop(cscene, "use_progressive_refine")
subsub = sub.column()
subsub.enabled = not rd.use_border
@@ -216,7 +214,7 @@ class CyclesRender_PT_performance(CyclesButtonsPanel, Panel):
sub = col.column(align=True)
sub.label(text="Viewport:")
- sub.prop(cscene, "resolution_divider")
+ sub.prop(cscene, "preview_start_resolution")
class CyclesRender_PT_layers(CyclesButtonsPanel, Panel):
@@ -438,6 +436,28 @@ class Cycles_PT_mesh_displacement(CyclesButtonsPanel, Panel):
layout.prop(cdata, "dicing_rate")
+class Cycles_PT_mesh_normals(CyclesButtonsPanel, Panel):
+ bl_label = "Normals"
+ bl_context = "data"
+
+ @classmethod
+ def poll(cls, context):
+ return CyclesButtonsPanel.poll(context) and context.mesh
+
+ def draw(self, context):
+ layout = self.layout
+
+ mesh = context.mesh
+
+ split = layout.split()
+
+ col = split.column()
+ col.prop(mesh, "show_double_sided")
+
+ col = split.column()
+ col.label()
+
+
class CyclesObject_PT_ray_visibility(CyclesButtonsPanel, Panel):
bl_label = "Ray Visibility"
bl_context = "object"
@@ -513,6 +533,7 @@ class CyclesLamp_PT_lamp(CyclesButtonsPanel, Panel):
lamp = context.lamp
clamp = lamp.cycles
cscene = context.scene.cycles
+ device_type = context.user_preferences.system.compute_device_type
layout.prop(lamp, "type", expand=True)
@@ -531,7 +552,7 @@ class CyclesLamp_PT_lamp(CyclesButtonsPanel, Panel):
sub.prop(lamp, "size", text="Size X")
sub.prop(lamp, "size_y", text="Size Y")
- if not cscene.progressive and cscene.device == 'CPU':
+ if not cscene.progressive and (device_type == 'NONE' or cscene.device == 'CPU'):
col.prop(clamp, "samples")
col = split.column()
@@ -656,6 +677,7 @@ class CyclesWorld_PT_settings(CyclesButtonsPanel, Panel):
world = context.world
cworld = world.cycles
cscene = context.scene.cycles
+ device_type = context.user_preferences.system.compute_device_type
col = layout.column()
@@ -663,7 +685,7 @@ class CyclesWorld_PT_settings(CyclesButtonsPanel, Panel):
sub = col.row(align=True)
sub.active = cworld.sample_as_light
sub.prop(cworld, "sample_map_resolution")
- if not cscene.progressive and cscene.device == 'CPU':
+ if not cscene.progressive and (device_type == 'NONE' or cscene.device == 'CPU'):
sub.prop(cworld, "samples")
@@ -930,8 +952,8 @@ def draw_device(self, context):
layout.prop(cscene, "device")
elif device_type == 'OPENCL' and cscene.feature_set == 'EXPERIMENTAL':
layout.prop(cscene, "device")
-
- if cscene.feature_set == 'EXPERIMENTAL' and cscene.device == 'CPU' and engine.with_osl():
+
+ if engine.with_osl() and (cscene.device == 'CPU' or device_type == 'None'):
layout.prop(cscene, "shading_system")
@@ -966,6 +988,7 @@ def get_panels():
bpy.types.DATA_PT_context_mesh,
bpy.types.DATA_PT_context_camera,
bpy.types.DATA_PT_context_lamp,
+ bpy.types.DATA_PT_context_speaker,
bpy.types.DATA_PT_texture_space,
bpy.types.DATA_PT_curve_texture_space,
bpy.types.DATA_PT_mball_texture_space,
@@ -976,9 +999,14 @@ def get_panels():
bpy.types.DATA_PT_camera,
bpy.types.DATA_PT_camera_display,
bpy.types.DATA_PT_lens,
+ bpy.types.DATA_PT_speaker,
+ bpy.types.DATA_PT_distance,
+ bpy.types.DATA_PT_cone,
+ bpy.types.DATA_PT_customdata,
bpy.types.DATA_PT_custom_props_mesh,
bpy.types.DATA_PT_custom_props_camera,
bpy.types.DATA_PT_custom_props_lamp,
+ bpy.types.DATA_PT_custom_props_speaker,
bpy.types.TEXTURE_PT_clouds,
bpy.types.TEXTURE_PT_wood,
bpy.types.TEXTURE_PT_marble,
diff --git a/intern/cycles/blender/blender_camera.cpp b/intern/cycles/blender/blender_camera.cpp
index 46d5fefd4dc..af16e210301 100644
--- a/intern/cycles/blender/blender_camera.cpp
+++ b/intern/cycles/blender/blender_camera.cpp
@@ -94,7 +94,7 @@ static float blender_camera_focal_distance(BL::Object b_ob, BL::Camera b_camera)
return fabsf(transform_get_column(&mat, 3).z);
}
-static void blender_camera_from_object(BlenderCamera *bcam, BL::Object b_ob)
+static void blender_camera_from_object(BlenderCamera *bcam, BL::Object b_ob, bool skip_panorama = false)
{
BL::ID b_ob_data = b_ob.data();
@@ -111,7 +111,10 @@ static void blender_camera_from_object(BlenderCamera *bcam, BL::Object b_ob)
bcam->type = CAMERA_ORTHOGRAPHIC;
break;
case BL::Camera::type_PANO:
- bcam->type = CAMERA_PANORAMA;
+ if(!skip_panorama)
+ bcam->type = CAMERA_PANORAMA;
+ else
+ bcam->type = CAMERA_PERSPECTIVE;
break;
case BL::Camera::type_PERSP:
default:
@@ -378,7 +381,7 @@ void BlenderSync::sync_camera_motion(BL::Object b_ob, int motion)
/* Sync 3D View Camera */
-static void blender_camera_from_view(BlenderCamera *bcam, BL::Scene b_scene, BL::SpaceView3D b_v3d, BL::RegionView3D b_rv3d, int width, int height)
+static void blender_camera_from_view(BlenderCamera *bcam, BL::Scene b_scene, BL::SpaceView3D b_v3d, BL::RegionView3D b_rv3d, int width, int height, bool skip_panorama = false)
{
/* 3d view parameters */
bcam->nearclip = b_v3d.clip_start();
@@ -391,7 +394,7 @@ static void blender_camera_from_view(BlenderCamera *bcam, BL::Scene b_scene, BL:
BL::Object b_ob = (b_v3d.lock_camera_and_layers())? b_scene.camera(): b_v3d.camera();
if(b_ob) {
- blender_camera_from_object(bcam, b_ob);
+ blender_camera_from_object(bcam, b_ob, skip_panorama);
/* magic zoom formula */
bcam->zoom = (float)b_rv3d.view_camera_zoom();
@@ -408,8 +411,14 @@ static void blender_camera_from_view(BlenderCamera *bcam, BL::Scene b_scene, BL:
bcam->farclip *= 0.5f;
bcam->nearclip = -bcam->farclip;
+ float sensor_size;
+ if(bcam->sensor_fit == BlenderCamera::VERTICAL)
+ sensor_size = bcam->sensor_height;
+ else
+ sensor_size = bcam->sensor_width;
+
bcam->type = CAMERA_ORTHOGRAPHIC;
- bcam->ortho_scale = b_rv3d.view_distance();
+ bcam->ortho_scale = b_rv3d.view_distance() * sensor_size / b_v3d.lens();
}
bcam->zoom *= 2.0f;
@@ -422,12 +431,26 @@ static void blender_camera_border(BlenderCamera *bcam, BL::Scene b_scene, BL::Sp
BL::RegionView3D b_rv3d, int width, int height)
{
BL::RenderSettings r = b_scene.render();
-
- if(!r.use_border())
- return;
+ bool is_camera_view;
/* camera view? */
- if(!(b_rv3d && b_rv3d.view_perspective() == BL::RegionView3D::view_perspective_CAMERA))
+ is_camera_view = b_rv3d.view_perspective() == BL::RegionView3D::view_perspective_CAMERA;
+
+ if(!is_camera_view) {
+ /* for non-camera view check whether render border is enabled for viewport
+ * and if so use border from 3d viewport
+ * assume viewport has got correctly clamped border already
+ */
+ if(b_v3d.use_render_border()) {
+ bcam->border_left = b_v3d.render_border_min_x();
+ bcam->border_right = b_v3d.render_border_max_x();
+ bcam->border_bottom = b_v3d.render_border_min_y();
+ bcam->border_top = b_v3d.render_border_max_y();
+
+ return;
+ }
+ }
+ else if(!r.use_border())
return;
BL::Object b_ob = (b_v3d.lock_camera_and_layers())? b_scene.camera(): b_v3d.camera();
@@ -447,7 +470,7 @@ static void blender_camera_border(BlenderCamera *bcam, BL::Scene b_scene, BL::Sp
/* get viewport viewplane */
BlenderCamera view_bcam;
blender_camera_init(&view_bcam);
- blender_camera_from_view(&view_bcam, b_scene, b_v3d, b_rv3d, width, height);
+ blender_camera_from_view(&view_bcam, b_scene, b_v3d, b_rv3d, width, height, true);
blender_camera_viewplane(&view_bcam, width, height,
&view_left, &view_right, &view_bottom, &view_top, &view_aspect, &sensor_size);
@@ -460,7 +483,7 @@ static void blender_camera_border(BlenderCamera *bcam, BL::Scene b_scene, BL::Sp
/* get camera viewplane */
BlenderCamera cam_bcam;
blender_camera_init(&cam_bcam);
- blender_camera_from_object(&cam_bcam, b_ob);
+ blender_camera_from_object(&cam_bcam, b_ob, true);
width = (int)(r.resolution_x()*r.resolution_percentage()/100);
height = (int)(r.resolution_y()*r.resolution_percentage()/100);
@@ -501,14 +524,20 @@ void BlenderSync::sync_view(BL::SpaceView3D b_v3d, BL::RegionView3D b_rv3d, int
blender_camera_sync(scene->camera, &bcam, width, height);
}
-BufferParams BlenderSync::get_buffer_params(BL::Scene b_scene, Camera *cam, int width, int height)
+BufferParams BlenderSync::get_buffer_params(BL::Scene b_scene, BL::SpaceView3D b_v3d, BL::RegionView3D b_rv3d, Camera *cam, int width, int height)
{
BufferParams params;
+ bool use_border = false;
params.full_width = width;
params.full_height = height;
- if(b_scene.render().use_border()) {
+ if(b_v3d && b_rv3d && b_rv3d.view_perspective() != BL::RegionView3D::view_perspective_CAMERA)
+ use_border = b_v3d.use_render_border();
+ else
+ use_border = b_scene.render().use_border();
+
+ if(use_border) {
/* border render */
params.full_x = cam->border_left*width;
params.full_y = cam->border_bottom*height;
diff --git a/intern/cycles/blender/blender_mesh.cpp b/intern/cycles/blender/blender_mesh.cpp
index 9764f24a893..0e13479a761 100644
--- a/intern/cycles/blender/blender_mesh.cpp
+++ b/intern/cycles/blender/blender_mesh.cpp
@@ -16,6 +16,7 @@
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
+
#include "mesh.h"
#include "object.h"
#include "scene.h"
@@ -29,9 +30,137 @@
#include "util_foreach.h"
+#include "mikktspace.h"
+
CCL_NAMESPACE_BEGIN
-/* Find/Add */
+/* Tangent Space */
+
+struct MikkUserData {
+ MikkUserData(const BL::Mesh mesh_, const BL::MeshTextureFaceLayer layer_, int num_faces_)
+ : mesh(mesh_), layer(layer_), num_faces(num_faces_)
+ {
+ tangent.resize(num_faces*4);
+ }
+
+ BL::Mesh mesh;
+ BL::MeshTextureFaceLayer layer;
+ int num_faces;
+ vector<float4> tangent;
+};
+
+static int mikk_get_num_faces(const SMikkTSpaceContext *context)
+{
+ MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
+ return userdata->num_faces;
+}
+
+static int mikk_get_num_verts_of_face(const SMikkTSpaceContext *context, const int face_num)
+{
+ MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
+ BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
+ int4 vi = get_int4(f.vertices_raw());
+
+ return (vi[3] == 0)? 3: 4;
+}
+
+static void mikk_get_position(const SMikkTSpaceContext *context, float P[3], const int face_num, const int vert_num)
+{
+ MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
+ BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
+ int4 vi = get_int4(f.vertices_raw());
+ BL::MeshVertex v = userdata->mesh.vertices[vi[vert_num]];
+ float3 vP = get_float3(v.co());
+
+ P[0] = vP.x;
+ P[1] = vP.y;
+ P[2] = vP.z;
+}
+
+static void mikk_get_texture_coordinate(const SMikkTSpaceContext *context, float uv[2], const int face_num, const int vert_num)
+{
+ MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
+ BL::MeshTextureFace tf = userdata->layer.data[face_num];
+ float3 tfuv;
+
+ if(vert_num == 0)
+ tfuv = get_float3(tf.uv1());
+ else if(vert_num == 1)
+ tfuv = get_float3(tf.uv2());
+ else if(vert_num == 2)
+ tfuv = get_float3(tf.uv3());
+ else
+ tfuv = get_float3(tf.uv4());
+
+ uv[0] = tfuv.x;
+ uv[1] = tfuv.y;
+}
+
+static void mikk_get_normal(const SMikkTSpaceContext *context, float N[3], const int face_num, const int vert_num)
+{
+ MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
+ BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
+ int4 vi = get_int4(f.vertices_raw());
+ BL::MeshVertex v = userdata->mesh.vertices[vi[vert_num]];
+ float3 vN = get_float3(v.normal());
+
+ N[0] = vN.x;
+ N[1] = vN.y;
+ N[2] = vN.z;
+}
+
+static void mikk_set_tangent_space(const SMikkTSpaceContext *context, const float T[], const float sign, const int face, const int vert)
+{
+ MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
+
+ userdata->tangent[face*4 + vert] = make_float4(T[0], T[1], T[2], sign);
+}
+
+static void mikk_compute_tangents(BL::Mesh b_mesh, BL::MeshTextureFaceLayer b_layer, Mesh *mesh, vector<int>& nverts)
+{
+ /* setup userdata */
+ MikkUserData userdata(b_mesh, b_layer, nverts.size());
+
+ /* setup interface */
+ SMikkTSpaceInterface sm_interface;
+ memset(&sm_interface, 0, sizeof(sm_interface));
+ sm_interface.m_getNumFaces = mikk_get_num_faces;
+ sm_interface.m_getNumVerticesOfFace = mikk_get_num_verts_of_face;
+ sm_interface.m_getPosition = mikk_get_position;
+ sm_interface.m_getTexCoord = mikk_get_texture_coordinate;
+ sm_interface.m_getNormal = mikk_get_normal;
+ sm_interface.m_setTSpaceBasic = mikk_set_tangent_space;
+
+ /* setup context */
+ SMikkTSpaceContext context;
+ memset(&context, 0, sizeof(context));
+ context.m_pUserData = &userdata;
+ context.m_pInterface = &sm_interface;
+
+ /* compute tangents */
+ genTangSpaceDefault(&context);
+
+ /* create attribute */
+ /* todo: create float4 attribute for sign */
+ Attribute *attr = mesh->attributes.add(ATTR_STD_TANGENT, ustring("tangent"));
+ float3 *tangent = attr->data_float3();
+
+ for (int i = 0; i < nverts.size(); i++) {
+ tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
+ tangent[1] = float4_to_float3(userdata.tangent[i*4 + 1]);
+ tangent[2] = float4_to_float3(userdata.tangent[i*4 + 2]);
+ tangent += 3;
+
+ if(nverts[i] == 4) {
+ tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
+ tangent[1] = float4_to_float3(userdata.tangent[i*4 + 2]);
+ tangent[2] = float4_to_float3(userdata.tangent[i*4 + 3]);
+ tangent += 3;
+ }
+ }
+}
+
+/* Create Mesh */
static void create_mesh(Scene *scene, Mesh *mesh, BL::Mesh b_mesh, const vector<uint>& used_shaders)
{
@@ -67,27 +196,6 @@ static void create_mesh(Scene *scene, Mesh *mesh, BL::Mesh b_mesh, const vector<
nverts.push_back(n);
}
- /* create generated coordinates. todo: we should actually get the orco
- * coordinates from modifiers, for now we use texspace loc/size which
- * is available in the api. */
- if(mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
- Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED);
- float3 loc = get_float3(b_mesh.texspace_location());
- float3 size = get_float3(b_mesh.texspace_size());
-
- if(size.x != 0.0f) size.x = 0.5f/size.x;
- if(size.y != 0.0f) size.y = 0.5f/size.y;
- if(size.z != 0.0f) size.z = 0.5f/size.z;
-
- loc = loc*size - make_float3(0.5f, 0.5f, 0.5f);
-
- float3 *fdata = attr->data_float3();
- size_t i = 0;
-
- for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
- fdata[i++] = get_float3(v->co())*size - loc;
- }
-
/* create vertex color attributes */
{
BL::Mesh::tessface_vertex_colors_iterator l;
@@ -157,6 +265,39 @@ static void create_mesh(Scene *scene, Mesh *mesh, BL::Mesh b_mesh, const vector<
}
}
}
+
+ /* create texcoord-based tangent attributes */
+ if(mesh->need_attribute(scene, ATTR_STD_TANGENT)) {
+ BL::Mesh::tessface_uv_textures_iterator l;
+
+ for(b_mesh.tessface_uv_textures.begin(l); l != b_mesh.tessface_uv_textures.end(); ++l) {
+ if(!l->active_render())
+ continue;
+
+ mikk_compute_tangents(b_mesh, *l, mesh, nverts);
+ }
+ }
+
+ /* create generated coordinates. todo: we should actually get the orco
+ * coordinates from modifiers, for now we use texspace loc/size which
+ * is available in the api. */
+ if(mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
+ Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED);
+ float3 loc = get_float3(b_mesh.texspace_location());
+ float3 size = get_float3(b_mesh.texspace_size());
+
+ if(size.x != 0.0f) size.x = 0.5f/size.x;
+ if(size.y != 0.0f) size.y = 0.5f/size.y;
+ if(size.z != 0.0f) size.z = 0.5f/size.z;
+
+ loc = loc*size - make_float3(0.5f, 0.5f, 0.5f);
+
+ float3 *generated = attr->data_float3();
+ size_t i = 0;
+
+ for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
+ generated[i++] = get_float3(v->co())*size - loc;
+ }
}
static void create_subd_mesh(Mesh *mesh, BL::Mesh b_mesh, PointerRNA *cmesh, const vector<uint>& used_shaders)
@@ -270,7 +411,7 @@ Mesh *BlenderSync::sync_mesh(BL::Object b_ob, bool object_updated)
create_mesh(scene, mesh, b_mesh, used_shaders);
/* free derived mesh */
- object_remove_mesh(b_data, b_mesh);
+ b_data.meshes.remove(b_mesh);
}
/* displacement method */
@@ -328,7 +469,7 @@ void BlenderSync::sync_mesh_motion(BL::Object b_ob, Mesh *mesh, int motion)
mesh->attributes.remove(std);
/* free derived mesh */
- object_remove_mesh(b_data, b_mesh);
+ b_data.meshes.remove(b_mesh);
}
}
diff --git a/intern/cycles/blender/blender_object.cpp b/intern/cycles/blender/blender_object.cpp
index eb9deb0de2d..1b920249733 100644
--- a/intern/cycles/blender/blender_object.cpp
+++ b/intern/cycles/blender/blender_object.cpp
@@ -17,12 +17,14 @@
*/
#include "camera.h"
+#include "integrator.h"
#include "graph.h"
#include "light.h"
#include "mesh.h"
#include "object.h"
#include "scene.h"
#include "nodes.h"
+#include "particles.h"
#include "shader.h"
#include "blender_sync.h"
@@ -194,8 +196,10 @@ void BlenderSync::sync_background_light()
/* Object */
-void BlenderSync::sync_object(BL::Object b_parent, int b_index, BL::Object b_ob, Transform& tfm, uint layer_flag, int motion, int particle_id)
+void BlenderSync::sync_object(BL::Object b_parent, int b_index, BL::DupliObject b_dupli_ob, Transform& tfm, uint layer_flag, int motion, int particle_id)
{
+ BL::Object b_ob = (b_dupli_ob ? b_dupli_ob.object() : b_parent);
+
/* light is handled separately */
if(object_is_light(b_ob)) {
if(!motion)
@@ -225,7 +229,9 @@ void BlenderSync::sync_object(BL::Object b_parent, int b_index, BL::Object b_ob,
object->use_motion = true;
}
- sync_mesh_motion(b_ob, object->mesh, motion);
+ /* mesh deformation blur not supported yet */
+ if(!scene->integrator->motion_blur)
+ sync_mesh_motion(b_ob, object->mesh, motion);
}
return;
@@ -274,6 +280,15 @@ void BlenderSync::sync_object(BL::Object b_parent, int b_index, BL::Object b_ob,
object->visibility &= ~PATH_RAY_CAMERA;
}
+ if (b_dupli_ob) {
+ object->dupli_generated = get_float3(b_dupli_ob.orco());
+ object->dupli_uv = get_float2(b_dupli_ob.uv());
+ }
+ else {
+ object->dupli_generated = make_float3(0.0f, 0.0f, 0.0f);
+ object->dupli_uv = make_float2(0.0f, 0.0f);
+ }
+
object->particle_id = particle_id;
object->tag_update(scene);
@@ -293,6 +308,7 @@ void BlenderSync::sync_objects(BL::SpaceView3D b_v3d, int motion)
mesh_map.pre_sync();
object_map.pre_sync();
mesh_synced.clear();
+ particle_system_map.pre_sync();
}
/* object loop */
@@ -309,15 +325,15 @@ void BlenderSync::sync_objects(BL::SpaceView3D b_v3d, int motion)
hide = hide || !(ob_layer & scene_layer);
if(!hide) {
- progress.set_status("Synchronizing object", (*b_ob).name());
+ progress.set_sync_status("Synchronizing object", (*b_ob).name());
int num_particles = object_count_particles(*b_ob);
if(b_ob->is_duplicator()) {
- hide = true; /* duplicators hidden by default */
+ hide = true; /* duplicators hidden by default */
/* dupli objects */
- object_create_duplilist(*b_ob, b_scene);
+ b_ob->dupli_list_create(b_scene, 2);
BL::Object::dupli_list_iterator b_dup;
int b_index = 0;
@@ -326,27 +342,42 @@ void BlenderSync::sync_objects(BL::SpaceView3D b_v3d, int motion)
Transform tfm = get_transform(b_dup->matrix());
BL::Object b_dup_ob = b_dup->object();
bool dup_hide = (b_v3d)? b_dup_ob.hide(): b_dup_ob.hide_render();
+ bool emitter_hide = false;
+
+ if(b_dup_ob.is_duplicator()) {
+ emitter_hide = true; /* duplicators hidden by default */
+
+ /* check if we should render or hide particle emitter */
+ BL::Object::particle_systems_iterator b_psys;
+ for(b_dup_ob.particle_systems.begin(b_psys); b_psys != b_dup_ob.particle_systems.end(); ++b_psys)
+ if(b_psys->settings().use_render_emitter())
+ emitter_hide = false;
+ }
- if(!(b_dup->hide() || dup_hide)) {
- sync_object(*b_ob, b_index, b_dup_ob, tfm, ob_layer, motion, b_dup->particle_index() + particle_offset);
+ if(!(b_dup->hide() || dup_hide || emitter_hide)) {
+ sync_object(*b_ob, b_index, *b_dup, tfm, ob_layer, motion, b_dup->particle_index() + particle_offset);
}
++b_index;
}
- object_free_duplilist(*b_ob);
+ b_ob->dupli_list_clear();
}
- /* check if we should render or hide particle emitter */
+ /* sync particles and check if we should render or hide particle emitter */
BL::Object::particle_systems_iterator b_psys;
- for(b_ob->particle_systems.begin(b_psys); b_psys != b_ob->particle_systems.end(); ++b_psys)
+ for(b_ob->particle_systems.begin(b_psys); b_psys != b_ob->particle_systems.end(); ++b_psys) {
+ if(!motion)
+ sync_particles(*b_ob, *b_psys);
+
if(b_psys->settings().use_render_emitter())
hide = false;
+ }
if(!hide) {
/* object itself */
Transform tfm = get_transform(b_ob->matrix_world());
- sync_object(*b_ob, 0, *b_ob, tfm, ob_layer, motion, 0);
+ sync_object(*b_ob, 0, PointerRNA_NULL, tfm, ob_layer, motion, 0);
}
particle_offset += num_particles;
@@ -356,6 +387,8 @@ void BlenderSync::sync_objects(BL::SpaceView3D b_v3d, int motion)
}
}
+ progress.set_sync_status("");
+
if(!cancel && !motion) {
sync_background_light();
@@ -366,6 +399,8 @@ void BlenderSync::sync_objects(BL::SpaceView3D b_v3d, int motion)
scene->mesh_manager->tag_update(scene);
if(object_map.post_sync())
scene->object_manager->tag_update(scene);
+ if(particle_system_map.post_sync())
+ scene->particle_system_manager->tag_update(scene);
mesh_synced.clear();
}
}
@@ -380,11 +415,13 @@ void BlenderSync::sync_motion(BL::SpaceView3D b_v3d, BL::Object b_override)
if(b_override)
b_cam = b_override;
+ Camera prevcam = *(scene->camera);
+
/* go back and forth one frame */
int frame = b_scene.frame_current();
for(int motion = -1; motion <= 1; motion += 2) {
- scene_frame_set(b_scene, frame + motion);
+ b_scene.frame_set(frame + motion, 0.0f);
/* camera object */
if(b_cam)
@@ -394,7 +431,11 @@ void BlenderSync::sync_motion(BL::SpaceView3D b_v3d, BL::Object b_override)
sync_objects(b_v3d, motion);
}
- scene_frame_set(b_scene, frame);
+ b_scene.frame_set(frame, 0.0f);
+
+ /* tag camera for motion update */
+ if(scene->camera->motion_modified(prevcam))
+ scene->camera->tag_update();
}
CCL_NAMESPACE_END
diff --git a/intern/cycles/blender/blender_particles.cpp b/intern/cycles/blender/blender_particles.cpp
index f309960fc55..c4c6d2f79a3 100644
--- a/intern/cycles/blender/blender_particles.cpp
+++ b/intern/cycles/blender/blender_particles.cpp
@@ -51,7 +51,7 @@ bool BlenderSync::psys_need_update(BL::ParticleSystem b_psys)
case BL::ParticleSettings::render_type_PATH: { /* for strand rendering */
BL::ID key = (BKE_object_is_modified(b_ob))? b_ob: b_ob.data();
Mesh *mesh = mesh_map.find(key);
- if (mesh) {
+ if(mesh) {
need_update |= mesh->need_attribute(scene, ATTR_STD_PARTICLE) && mesh->need_update;
}
break;
@@ -60,10 +60,10 @@ bool BlenderSync::psys_need_update(BL::ParticleSystem b_psys)
case BL::ParticleSettings::render_type_OBJECT: {
BL::Object b_dupli_ob = b_psys.settings().dupli_object();
- if (b_dupli_ob) {
+ if(b_dupli_ob) {
BL::ID key = (BKE_object_is_modified(b_dupli_ob))? b_dupli_ob: b_dupli_ob.data();
Mesh *mesh = mesh_map.find(key);
- if (mesh) {
+ if(mesh) {
need_update |= mesh->need_attribute(scene, ATTR_STD_PARTICLE) && mesh->need_update;
}
}
@@ -72,12 +72,12 @@ bool BlenderSync::psys_need_update(BL::ParticleSystem b_psys)
case BL::ParticleSettings::render_type_GROUP: {
BL::Group b_dupli_group = b_psys.settings().dupli_group();
- if (b_dupli_group) {
+ if(b_dupli_group) {
BL::Group::objects_iterator b_gob;
for (b_dupli_group.objects.begin(b_gob); b_gob != b_dupli_group.objects.end(); ++b_gob) {
BL::ID key = (BKE_object_is_modified(*b_gob))? *b_gob: b_gob->data();
Mesh *mesh = mesh_map.find(key);
- if (mesh) {
+ if(mesh) {
need_update |= mesh->need_attribute(scene, ATTR_STD_PARTICLE) && mesh->need_update;
}
}
@@ -109,38 +109,43 @@ static bool use_particle_system(BL::ParticleSystem b_psys)
return true;
}
-static bool use_particle(BL::Particle b_pa)
+static bool use_particle(BL::Particle b_pa, bool preview, bool show_unborn, bool use_dead)
{
- return b_pa.is_exist() && b_pa.is_visible() &&
- (b_pa.alive_state()==BL::Particle::alive_state_ALIVE || b_pa.alive_state()==BL::Particle::alive_state_DYING);
+ return b_pa.is_exist() && (!preview || b_pa.is_visible()) &&
+ (b_pa.alive_state() != BL::Particle::alive_state_UNBORN || show_unborn) &&
+ (b_pa.alive_state() != BL::Particle::alive_state_DEAD || use_dead);
}
-static int psys_count_particles(BL::ParticleSystem b_psys)
+static int psys_count_particles(BL::ParticleSystem b_psys, bool preview)
{
- int tot = 0;
BL::ParticleSystem::particles_iterator b_pa;
- for(b_psys.particles.begin(b_pa); b_pa != b_psys.particles.end(); ++b_pa) {
- if(use_particle(*b_pa))
- ++tot;
- }
- return tot;
+ bool show_unborn = b_psys.settings().show_unborn();
+ bool use_dead = b_psys.settings().use_dead();
+ int num = 0;
+
+ for(b_psys.particles.begin(b_pa); b_pa != b_psys.particles.end(); ++b_pa)
+ if(use_particle(*b_pa, preview, show_unborn, use_dead))
+ ++num;
+
+ return num;
}
int BlenderSync::object_count_particles(BL::Object b_ob)
{
- int tot = 0;
BL::Object::particle_systems_iterator b_psys;
- for(b_ob.particle_systems.begin(b_psys); b_psys != b_ob.particle_systems.end(); ++b_psys) {
- if (use_particle_system(*b_psys))
- tot += psys_count_particles(*b_psys);
- }
- return tot;
+ int num = 0;
+
+ for(b_ob.particle_systems.begin(b_psys); b_psys != b_ob.particle_systems.end(); ++b_psys)
+ if(use_particle_system(*b_psys))
+ num += psys_count_particles(*b_psys, preview);
+
+ return num;
}
void BlenderSync::sync_particles(BL::Object b_ob, BL::ParticleSystem b_psys)
{
/* depending on settings the psys may not even be rendered */
- if (!use_particle_system(b_psys))
+ if(!use_particle_system(b_psys))
return;
/* key to lookup particle system */
@@ -155,15 +160,19 @@ void BlenderSync::sync_particles(BL::Object b_ob, BL::ParticleSystem b_psys)
bool need_update = psys_need_update(b_psys);
- if (object_updated || need_update) {
- int tot = psys_count_particles(b_psys);
+ if(object_updated || need_update) {
+ bool show_unborn = b_psys.settings().show_unborn();
+ bool use_dead = b_psys.settings().use_dead();
+
+ int num = psys_count_particles(b_psys, preview);
psys->particles.clear();
- psys->particles.reserve(tot);
+ psys->particles.reserve(num);
- int index = 0;
BL::ParticleSystem::particles_iterator b_pa;
+ int index = 0;
+
for(b_psys.particles.begin(b_pa); b_pa != b_psys.particles.end(); ++b_pa) {
- if(use_particle(*b_pa)) {
+ if(use_particle(*b_pa, preview, show_unborn, use_dead)) {
Particle pa;
pa.index = index;
@@ -185,34 +194,4 @@ void BlenderSync::sync_particles(BL::Object b_ob, BL::ParticleSystem b_psys)
}
}
-void BlenderSync::sync_particle_systems()
-{
- /* layer data */
- uint scene_layer = render_layer.scene_layer;
-
- particle_system_map.pre_sync();
-
- /* object loop */
- BL::Scene::objects_iterator b_ob;
- BL::Scene b_sce = b_scene;
-
- for(; b_sce; b_sce = b_sce.background_set()) {
- for(b_sce.objects.begin(b_ob); b_ob != b_sce.objects.end(); ++b_ob) {
- bool hide = (render_layer.use_viewport_visibility)? b_ob->hide(): b_ob->hide_render();
- uint ob_layer = get_layer(b_ob->layers(), b_ob->layers_local_view(), render_layer.use_localview, object_is_light(*b_ob));
- hide = hide || !(ob_layer & scene_layer);
-
- if(!hide) {
- BL::Object::particle_systems_iterator b_psys;
- for(b_ob->particle_systems.begin(b_psys); b_psys != b_ob->particle_systems.end(); ++b_psys)
- sync_particles(*b_ob, *b_psys);
- }
- }
- }
-
- /* handle removed data and modified pointers */
- if(particle_system_map.post_sync())
- scene->particle_system_manager->tag_update(scene);
-}
-
CCL_NAMESPACE_END
diff --git a/intern/cycles/blender/blender_python.cpp b/intern/cycles/blender/blender_python.cpp
index 96d5bb61ff8..c047805c6ae 100644
--- a/intern/cycles/blender/blender_python.cpp
+++ b/intern/cycles/blender/blender_python.cpp
@@ -24,9 +24,17 @@
#include "blender_session.h"
#include "util_foreach.h"
+#include "util_md5.h"
#include "util_opengl.h"
#include "util_path.h"
+#ifdef WITH_OSL
+#include "osl.h"
+
+#include <OSL/oslquery.h>
+#include <OSL/oslconfig.h>
+#endif
+
CCL_NAMESPACE_BEGIN
static PyObject *init_func(PyObject *self, PyObject *args)
@@ -163,6 +171,170 @@ static PyObject *available_devices_func(PyObject *self, PyObject *args)
return ret;
}
+#ifdef WITH_OSL
+static PyObject *osl_update_node_func(PyObject *self, PyObject *args)
+{
+ PyObject *pynodegroup, *pynode;
+ const char *filepath = NULL;
+
+ if(!PyArg_ParseTuple(args, "OOs", &pynodegroup, &pynode, &filepath))
+ return NULL;
+
+ /* RNA */
+ PointerRNA nodeptr;
+ RNA_pointer_create((ID*)PyLong_AsVoidPtr(pynodegroup), &RNA_ShaderNodeScript, (void*)PyLong_AsVoidPtr(pynode), &nodeptr);
+ BL::ShaderNodeScript b_node(nodeptr);
+
+ /* update bytecode hash */
+ string bytecode = b_node.bytecode();
+
+ if(!bytecode.empty()) {
+ MD5Hash md5;
+ md5.append((const uint8_t*)bytecode.c_str(), bytecode.size());
+ b_node.bytecode_hash(md5.get_hex().c_str());
+ }
+ else
+ b_node.bytecode_hash("");
+
+ /* query from file path */
+ OSL::OSLQuery query;
+
+ if(!OSLShaderManager::osl_query(query, filepath))
+ Py_RETURN_FALSE;
+
+ /* add new sockets from parameters */
+ set<void*> used_sockets;
+
+ for(int i = 0; i < query.nparams(); i++) {
+ const OSL::OSLQuery::Parameter *param = query.getparam(i);
+
+ /* skip unsupported types */
+ if(param->varlenarray || param->isstruct || param->type.arraylen > 1)
+ continue;
+
+ /* determine socket type */
+ BL::NodeSocket::type_enum socket_type;
+ float default_float4[4] = {0.0f, 0.0f, 0.0f, 1.0f};
+ float default_float = 0.0f;
+ int default_int = 0;
+
+ if(param->isclosure) {
+ socket_type = BL::NodeSocket::type_SHADER;
+ }
+ else if(param->type.vecsemantics == TypeDesc::COLOR) {
+ socket_type = BL::NodeSocket::type_RGBA;
+
+ if(param->validdefault) {
+ default_float4[0] = param->fdefault[0];
+ default_float4[1] = param->fdefault[1];
+ default_float4[2] = param->fdefault[2];
+ }
+ }
+ else if(param->type.vecsemantics == TypeDesc::POINT ||
+ param->type.vecsemantics == TypeDesc::VECTOR ||
+ param->type.vecsemantics == TypeDesc::NORMAL) {
+ socket_type = BL::NodeSocket::type_VECTOR;
+
+ if(param->validdefault) {
+ default_float4[0] = param->fdefault[0];
+ default_float4[1] = param->fdefault[1];
+ default_float4[2] = param->fdefault[2];
+ }
+ }
+ else if(param->type.aggregate == TypeDesc::SCALAR) {
+ if(param->type.basetype == TypeDesc::INT) {
+ socket_type = BL::NodeSocket::type_INT;
+ if(param->validdefault)
+ default_int = param->idefault[0];
+ }
+ else if(param->type.basetype == TypeDesc::FLOAT) {
+ socket_type = BL::NodeSocket::type_VALUE;
+ if(param->validdefault)
+ default_float = param->fdefault[0];
+ }
+ }
+ else
+ continue;
+
+ /* find socket socket */
+ BL::NodeSocket b_sock = b_node.find_socket(param->name.c_str(), param->isoutput);
+
+ /* remove if type no longer matches */
+ if(b_sock && b_sock.type() != socket_type) {
+ b_node.remove_socket(b_sock);
+ b_sock = BL::NodeSocket(PointerRNA_NULL);
+ }
+
+ /* create new socket */
+ if(!b_sock) {
+ b_sock = b_node.add_socket(param->name.c_str(), socket_type, param->isoutput);
+
+ /* set default value */
+ if(socket_type == BL::NodeSocket::type_VALUE) {
+ BL::NodeSocketFloatNone b_float_sock(b_sock.ptr);
+ b_float_sock.default_value(default_float);
+ }
+ else if(socket_type == BL::NodeSocket::type_INT) {
+ BL::NodeSocketIntNone b_int_sock(b_sock.ptr);
+ b_int_sock.default_value(default_int);
+ }
+ else if(socket_type == BL::NodeSocket::type_RGBA) {
+ BL::NodeSocketRGBA b_rgba_sock(b_sock.ptr);
+ b_rgba_sock.default_value(default_float4);
+ }
+ else if(socket_type == BL::NodeSocket::type_VECTOR) {
+ BL::NodeSocketVectorNone b_vector_sock(b_sock.ptr);
+ b_vector_sock.default_value(default_float4);
+ }
+ }
+
+ used_sockets.insert(b_sock.ptr.data);
+ }
+
+ /* remove unused parameters */
+ bool removed;
+
+ do {
+ BL::Node::inputs_iterator b_input;
+ BL::Node::outputs_iterator b_output;
+
+ removed = false;
+
+ for (b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
+ if(used_sockets.find(b_input->ptr.data) == used_sockets.end()) {
+ b_node.remove_socket(*b_input);
+ removed = true;
+ break;
+ }
+ }
+
+ for (b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
+ if(used_sockets.find(b_output->ptr.data) == used_sockets.end()) {
+ b_node.remove_socket(*b_output);
+ removed = true;
+ break;
+ }
+ }
+ } while(removed);
+
+ Py_RETURN_TRUE;
+}
+
+static PyObject *osl_compile_func(PyObject *self, PyObject *args)
+{
+ const char *inputfile = NULL, *outputfile = NULL;
+
+ if(!PyArg_ParseTuple(args, "ss", &inputfile, &outputfile))
+ return NULL;
+
+ /* return */
+ if(!OSLShaderManager::osl_compile(inputfile, outputfile))
+ Py_RETURN_FALSE;
+
+ Py_RETURN_TRUE;
+}
+#endif
+
static PyMethodDef methods[] = {
{"init", init_func, METH_VARARGS, ""},
{"create", create_func, METH_VARARGS, ""},
@@ -170,6 +342,10 @@ static PyMethodDef methods[] = {
{"render", render_func, METH_O, ""},
{"draw", draw_func, METH_VARARGS, ""},
{"sync", sync_func, METH_O, ""},
+#ifdef WITH_OSL
+ {"osl_update_node", osl_update_node_func, METH_VARARGS, ""},
+ {"osl_compile", osl_compile_func, METH_VARARGS, ""},
+#endif
{"available_devices", available_devices_func, METH_NOARGS, ""},
{NULL, NULL, 0, NULL},
};
@@ -183,7 +359,7 @@ static struct PyModuleDef module = {
NULL, NULL, NULL, NULL
};
-CCLDeviceInfo *compute_device_list(DeviceType type)
+static CCLDeviceInfo *compute_device_list(DeviceType type)
{
/* device list stored static */
static ccl::vector<CCLDeviceInfo> device_list;
diff --git a/intern/cycles/blender/blender_session.cpp b/intern/cycles/blender/blender_session.cpp
index 5930a2800bf..01bd5f013e3 100644
--- a/intern/cycles/blender/blender_session.cpp
+++ b/intern/cycles/blender/blender_session.cpp
@@ -105,7 +105,7 @@ void BlenderSession::create_session()
sync->sync_camera(b_engine.camera_override(), width, height);
/* set buffer parameters */
- BufferParams buffer_params = BlenderSync::get_buffer_params(b_scene, scene->camera, width, height);
+ BufferParams buffer_params = BlenderSync::get_buffer_params(b_scene, b_v3d, b_rv3d, scene->camera, width, height);
session->reset(buffer_params, session_params.samples);
}
@@ -178,15 +178,12 @@ static PassType get_pass_type(BL::RenderPass b_pass)
static BL::RenderResult begin_render_result(BL::RenderEngine b_engine, int x, int y, int w, int h, const char *layername)
{
- RenderResult *rrp = RE_engine_begin_result((RenderEngine*)b_engine.ptr.data, x, y, w, h, layername);
- PointerRNA rrptr;
- RNA_pointer_create(NULL, &RNA_RenderResult, rrp, &rrptr);
- return BL::RenderResult(rrptr);
+ return b_engine.begin_result(x, y, w, h, layername);
}
static void end_render_result(BL::RenderEngine b_engine, BL::RenderResult b_rr, bool cancel = false)
{
- RE_engine_end_result((RenderEngine*)b_engine.ptr.data, (RenderResult*)b_rr.ptr.data, (int)cancel);
+ b_engine.end_result(b_rr, (int)cancel);
}
void BlenderSession::do_write_update_render_tile(RenderTile& rtile, bool do_update_only)
@@ -239,7 +236,7 @@ void BlenderSession::render()
/* get buffer parameters */
SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
- BufferParams buffer_params = BlenderSync::get_buffer_params(b_scene, scene->camera, width, height);
+ BufferParams buffer_params = BlenderSync::get_buffer_params(b_scene, b_v3d, b_rv3d, scene->camera, width, height);
/* render each layer */
BL::RenderSettings r = b_scene.render();
@@ -335,16 +332,16 @@ void BlenderSession::do_write_update_render_result(BL::RenderResult b_rr, BL::Re
/* copy pixels */
if(buffers->get_pass_rect(pass_type, exposure, rtile.sample, components, &pixels[0]))
- rna_RenderPass_rect_set(&b_pass.ptr, &pixels[0]);
+ b_pass.rect(&pixels[0]);
}
}
/* copy combined pass */
if(buffers->get_pass_rect(PASS_COMBINED, exposure, rtile.sample, 4, &pixels[0]))
- rna_RenderLayer_rect_set(&b_rlay.ptr, &pixels[0]);
+ b_rlay.rect(&pixels[0]);
/* tag result as updated */
- RE_engine_update_result((RenderEngine*)b_engine.ptr.data, (RenderResult*)b_rr.ptr.data);
+ b_engine.update_result(b_rr);
}
void BlenderSession::write_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile)
@@ -372,12 +369,6 @@ void BlenderSession::synchronize()
return;
}
- /* if the session is still resetting the device come back later */
- if(session->resetting()) {
- tag_update();
- return;
- }
-
/* increase samples, but never decrease */
session->set_samples(session_params.samples);
session->set_pause(BlenderSync::get_session_pause(b_scene, background));
@@ -405,7 +396,7 @@ void BlenderSession::synchronize()
/* reset if needed */
if(scene->need_reset()) {
- BufferParams buffer_params = BlenderSync::get_buffer_params(b_scene, scene->camera, width, height);
+ BufferParams buffer_params = BlenderSync::get_buffer_params(b_scene, b_v3d, b_rv3d, scene->camera, width, height);
session->reset(buffer_params, session_params.samples);
}
}
@@ -443,7 +434,7 @@ bool BlenderSession::draw(int w, int h)
/* reset if requested */
if(reset) {
SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
- BufferParams buffer_params = BlenderSync::get_buffer_params(b_scene, scene->camera, w, h);
+ BufferParams buffer_params = BlenderSync::get_buffer_params(b_scene, b_v3d, b_rv3d, scene->camera, w, h);
session->reset(buffer_params, session_params.samples);
}
@@ -453,7 +444,7 @@ bool BlenderSession::draw(int w, int h)
update_status_progress();
/* draw */
- BufferParams buffer_params = BlenderSync::get_buffer_params(b_scene, scene->camera, width, height);
+ BufferParams buffer_params = BlenderSync::get_buffer_params(b_scene, b_v3d, b_rv3d, scene->camera, width, height);
return !session->draw(buffer_params);
}
@@ -472,9 +463,12 @@ void BlenderSession::get_progress(float& progress, double& total_time)
session->progress.get_tile(tile, total_time, tile_time);
sample = session->progress.get_sample();
- samples_per_tile = session->tile_manager.state.num_samples;
+ samples_per_tile = session->params.samples;
- progress = ((float)sample/(float)(tile_total * samples_per_tile));
+ if(samples_per_tile)
+ progress = ((float)sample/(float)(tile_total * samples_per_tile));
+ else
+ progress = 0.0;
}
void BlenderSession::update_status_progress()
@@ -483,11 +477,15 @@ void BlenderSession::update_status_progress()
float progress;
double total_time;
char time_str[128];
+ float mem_used = (float)session->stats.mem_used / 1024.0f / 1024.0f;
+ float mem_peak = (float)session->stats.mem_peak / 1024.0f / 1024.0f;
get_status(status, substatus);
get_progress(progress, total_time);
- timestatus = b_scene.name();
+ timestatus = string_printf("Mem: %.2fM, Peak: %.2fM | ", mem_used, mem_peak);
+
+ timestatus += b_scene.name();
if(b_rlay_name != "")
timestatus += ", " + b_rlay_name;
timestatus += " | ";
@@ -499,11 +497,12 @@ void BlenderSession::update_status_progress()
status += " | " + substatus;
if(status != last_status) {
- RE_engine_update_stats((RenderEngine*)b_engine.ptr.data, "", (timestatus + status).c_str());
+ b_engine.update_stats("", (timestatus + status).c_str());
+ b_engine.update_memory_stats(mem_used, mem_peak);
last_status = status;
}
if(progress != last_progress) {
- RE_engine_update_progress((RenderEngine*)b_engine.ptr.data, progress);
+ b_engine.update_progress(progress);
last_progress = progress;
}
}
@@ -511,7 +510,7 @@ void BlenderSession::update_status_progress()
void BlenderSession::tag_update()
{
/* tell blender that we want to get another update callback */
- engine_tag_update((RenderEngine*)b_engine.ptr.data);
+ b_engine.tag_update();
}
void BlenderSession::tag_redraw()
@@ -523,13 +522,13 @@ void BlenderSession::tag_redraw()
/* offline render, redraw if timeout passed */
if(time_dt() - last_redraw_time > 1.0) {
- engine_tag_redraw((RenderEngine*)b_engine.ptr.data);
+ b_engine.tag_redraw();
last_redraw_time = time_dt();
}
}
else {
/* tell blender that we want to redraw */
- engine_tag_redraw((RenderEngine*)b_engine.ptr.data);
+ b_engine.tag_redraw();
}
}
@@ -537,7 +536,7 @@ void BlenderSession::test_cancel()
{
/* test if we need to cancel rendering */
if(background)
- if(RE_engine_test_break((RenderEngine*)b_engine.ptr.data))
+ if(b_engine.test_break())
session->progress.set_cancel("Cancelled");
}
diff --git a/intern/cycles/blender/blender_shader.cpp b/intern/cycles/blender/blender_shader.cpp
index 9758d9bf92a..9e3380c6f8e 100644
--- a/intern/cycles/blender/blender_shader.cpp
+++ b/intern/cycles/blender/blender_shader.cpp
@@ -20,6 +20,7 @@
#include "graph.h"
#include "light.h"
#include "nodes.h"
+#include "osl.h"
#include "scene.h"
#include "shader.h"
@@ -43,6 +44,7 @@ void BlenderSync::find_shader(BL::ID id, vector<uint>& used_shaders, int default
for(size_t i = 0; i < scene->shaders.size(); i++) {
if(scene->shaders[i] == shader) {
used_shaders.push_back(i);
+ scene->shaders[i]->tag_used(scene);
break;
}
}
@@ -80,6 +82,8 @@ static ShaderSocketType convert_socket_type(BL::NodeSocket::type_enum b_type)
switch (b_type) {
case BL::NodeSocket::type_VALUE:
return SHADER_SOCKET_FLOAT;
+ case BL::NodeSocket::type_INT:
+ return SHADER_SOCKET_INT;
case BL::NodeSocket::type_VECTOR:
return SHADER_SOCKET_VECTOR;
case BL::NodeSocket::type_RGBA:
@@ -89,7 +93,6 @@ static ShaderSocketType convert_socket_type(BL::NodeSocket::type_enum b_type)
case BL::NodeSocket::type_BOOLEAN:
case BL::NodeSocket::type_MESH:
- case BL::NodeSocket::type_INT:
default:
return SHADER_SOCKET_FLOAT;
}
@@ -104,6 +107,11 @@ static void set_default_value(ShaderInput *input, BL::NodeSocket sock)
input->set(value_sock.default_value());
break;
}
+ case SHADER_SOCKET_INT: {
+ BL::NodeSocketIntNone value_sock(sock);
+ input->set((float)value_sock.default_value());
+ break;
+ }
case SHADER_SOCKET_COLOR: {
BL::NodeSocketRGBA rgba_sock(sock);
input->set(get_float3(rgba_sock.default_value()));
@@ -152,7 +160,7 @@ static void get_tex_mapping(TextureMapping *mapping, BL::ShaderNodeMapping b_map
mapping->max = get_float3(b_mapping.max());
}
-static ShaderNode *add_node(BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNode b_node)
+static ShaderNode *add_node(Scene *scene, BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNodeTree b_ntree, BL::ShaderNode b_node)
{
ShaderNode *node = NULL;
@@ -315,6 +323,10 @@ static ShaderNode *add_node(BL::BlendData b_data, BL::Scene b_scene, ShaderGraph
node = new HoldoutNode();
break;
}
+ case BL::ShaderNode::type_BSDF_ANISOTROPIC: {
+ node = new WardBsdfNode();
+ break;
+ }
case BL::ShaderNode::type_BSDF_DIFFUSE: {
node = new DiffuseBsdfNode();
break;
@@ -398,12 +410,68 @@ static ShaderNode *add_node(BL::BlendData b_data, BL::Scene b_scene, ShaderGraph
node = new ParticleInfoNode();
break;
}
+ case BL::ShaderNode::type_BUMP: {
+ node = new BumpNode();
+ break;
+ }
+ case BL::ShaderNode::type_SCRIPT: {
+#ifdef WITH_OSL
+ if(scene->params.shadingsystem != SceneParams::OSL)
+ break;
+
+ /* create script node */
+ BL::ShaderNodeScript b_script_node(b_node);
+ OSLScriptNode *script_node = new OSLScriptNode();
+
+ /* Generate inputs/outputs from node sockets
+ *
+ * Note: the node sockets are generated from OSL parameters,
+ * so the names match those of the corresponding parameters exactly.
+ *
+ * Note 2: ShaderInput/ShaderOutput store shallow string copies only!
+ * Socket names must be stored in the extra lists instead. */
+ BL::Node::inputs_iterator b_input;
+
+ for (b_script_node.inputs.begin(b_input); b_input != b_script_node.inputs.end(); ++b_input) {
+ script_node->input_names.push_back(ustring(b_input->name()));
+ ShaderInput *input = script_node->add_input(script_node->input_names.back().c_str(), convert_socket_type(b_input->type()));
+ set_default_value(input, *b_input);
+ }
+
+ BL::Node::outputs_iterator b_output;
+
+ for (b_script_node.outputs.begin(b_output); b_output != b_script_node.outputs.end(); ++b_output) {
+ script_node->output_names.push_back(ustring(b_output->name()));
+ script_node->add_output(script_node->output_names.back().c_str(), convert_socket_type(b_output->type()));
+ }
+
+ /* load bytecode or filepath */
+ OSLShaderManager *manager = (OSLShaderManager*)scene->shader_manager;
+ string bytecode_hash = b_script_node.bytecode_hash();
+
+ if(!bytecode_hash.empty()) {
+ /* loaded bytecode if not already done */
+ if(!manager->shader_test_loaded(bytecode_hash))
+ manager->shader_load_bytecode(bytecode_hash, b_script_node.bytecode());
+
+ script_node->bytecode_hash = bytecode_hash;
+ }
+ else {
+ /* set filepath */
+ script_node->filepath = blender_absolute_path(b_data, b_ntree, b_script_node.filepath());
+ }
+
+ node = script_node;
+#endif
+
+ break;
+ }
case BL::ShaderNode::type_TEX_IMAGE: {
BL::ShaderNodeTexImage b_image_node(b_node);
BL::Image b_image(b_image_node.image());
ImageTextureNode *image = new ImageTextureNode();
/* todo: handle generated/builtin images */
- if(b_image)
+ if(b_image && b_image.source() != BL::Image::source_MOVIE)
image->filename = image_user_file_path(b_image_node.image_user(), b_image, b_scene.frame_current());
image->color_space = ImageTextureNode::color_space_enum[(int)b_image_node.color_space()];
image->projection = ImageTextureNode::projection_enum[(int)b_image_node.projection()];
@@ -416,7 +484,7 @@ static ShaderNode *add_node(BL::BlendData b_data, BL::Scene b_scene, ShaderGraph
BL::ShaderNodeTexEnvironment b_env_node(b_node);
BL::Image b_image(b_env_node.image());
EnvironmentTextureNode *env = new EnvironmentTextureNode();
- if(b_image)
+ if(b_image && b_image.source() != BL::Image::source_MOVIE)
env->filename = image_user_file_path(b_env_node.image_user(), b_image, b_scene.frame_current());
env->color_space = EnvironmentTextureNode::color_space_enum[(int)b_env_node.color_space()];
env->projection = EnvironmentTextureNode::projection_enum[(int)b_env_node.projection()];
@@ -490,7 +558,10 @@ static ShaderNode *add_node(BL::BlendData b_data, BL::Scene b_scene, ShaderGraph
break;
}
case BL::ShaderNode::type_TEX_COORD: {
- node = new TextureCoordinateNode();
+ BL::ShaderNodeTexCoord b_tex_coord_node(b_node);
+ TextureCoordinateNode *tex_coord = new TextureCoordinateNode();
+ tex_coord->from_dupli = b_tex_coord_node.from_dupli();
+ node = tex_coord;
break;
}
case BL::ShaderNode::type_TEX_SKY: {
@@ -558,7 +629,7 @@ static SocketPair node_socket_map_pair(PtrNodeMap& node_map, BL::Node b_node, BL
return SocketPair(node_map[b_node.ptr.data], name);
}
-static void add_nodes(BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNodeTree b_ntree, PtrSockMap& sockets_map)
+static void add_nodes(Scene *scene, BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNodeTree b_ntree, PtrSockMap& sockets_map)
{
/* add nodes */
BL::ShaderNodeTree::nodes_iterator b_node;
@@ -566,7 +637,34 @@ static void add_nodes(BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *grap
PtrSockMap proxy_map;
for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
- if(b_node->is_a(&RNA_NodeGroup)) {
+ if(b_node->mute()) {
+ BL::Node::inputs_iterator b_input;
+ BL::Node::outputs_iterator b_output;
+ bool found_match = false;
+
+ /* this is slightly different than blender logic, we just connect a
+ * single pair for of input/output, but works ok for the node we have */
+ for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
+ if(b_input->is_linked()) {
+ for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
+ if(b_output->is_linked() && b_input->type() == b_output->type()) {
+ ProxyNode *proxy = new ProxyNode(convert_socket_type(b_input->type()), convert_socket_type(b_output->type()));
+ graph->add(proxy);
+
+ proxy_map[b_input->ptr.data] = SocketPair(proxy, proxy->inputs[0]->name);
+ proxy_map[b_output->ptr.data] = SocketPair(proxy, proxy->outputs[0]->name);
+ found_match = true;
+
+ break;
+ }
+ }
+ }
+
+ if(found_match)
+ break;
+ }
+ }
+ else if(b_node->is_a(&RNA_NodeGroup)) {
/* add proxy converter nodes for inputs and outputs */
BL::NodeGroup b_gnode(*b_node);
BL::ShaderNodeTree b_group_ntree(b_gnode.node_tree());
@@ -606,10 +704,10 @@ static void add_nodes(BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *grap
set_default_value(proxy->inputs[0], b_output->group_socket());
}
- add_nodes(b_data, b_scene, graph, b_group_ntree, group_sockmap);
+ add_nodes(scene, b_data, b_scene, graph, b_group_ntree, group_sockmap);
}
else {
- ShaderNode *node = add_node(b_data, b_scene, graph, BL::ShaderNode(*b_node));
+ ShaderNode *node = add_node(scene, b_data, b_scene, graph, b_ntree, BL::ShaderNode(*b_node));
if(node) {
BL::Node::inputs_iterator b_input;
@@ -646,7 +744,7 @@ static void add_nodes(BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *grap
/* from sock */
if(b_from_node) {
- if (b_from_node.is_a(&RNA_NodeGroup))
+ if (b_from_node.mute() || b_from_node.is_a(&RNA_NodeGroup))
from_pair = proxy_map[b_from_sock.ptr.data];
else
from_pair = node_socket_map_pair(node_map, b_from_node, b_from_sock);
@@ -656,7 +754,7 @@ static void add_nodes(BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *grap
/* to sock */
if(b_to_node) {
- if (b_to_node.is_a(&RNA_NodeGroup))
+ if (b_to_node.mute() || b_to_node.is_a(&RNA_NodeGroup))
to_pair = proxy_map[b_to_sock.ptr.data];
else
to_pair = node_socket_map_pair(node_map, b_to_node, b_to_sock);
@@ -699,7 +797,7 @@ void BlenderSync::sync_materials()
PtrSockMap sock_to_node;
BL::ShaderNodeTree b_ntree(b_mat->node_tree());
- add_nodes(b_data, b_scene, graph, b_ntree, sock_to_node);
+ add_nodes(scene, b_data, b_scene, graph, b_ntree, sock_to_node);
}
else {
ShaderNode *closure, *out;
@@ -740,7 +838,7 @@ void BlenderSync::sync_world()
PtrSockMap sock_to_node;
BL::ShaderNodeTree b_ntree(b_world.node_tree());
- add_nodes(b_data, b_scene, graph, b_ntree, sock_to_node);
+ add_nodes(scene, b_data, b_scene, graph, b_ntree, sock_to_node);
}
else if(b_world) {
ShaderNode *closure, *out;
@@ -799,7 +897,7 @@ void BlenderSync::sync_lamps()
PtrSockMap sock_to_node;
BL::ShaderNodeTree b_ntree(b_lamp->node_tree());
- add_nodes(b_data, b_scene, graph, b_ntree, sock_to_node);
+ add_nodes(scene, b_data, b_scene, graph, b_ntree, sock_to_node);
}
else {
ShaderNode *closure, *out;
diff --git a/intern/cycles/blender/blender_sync.cpp b/intern/cycles/blender/blender_sync.cpp
index 907573cf072..c63f72c68c6 100644
--- a/intern/cycles/blender/blender_sync.cpp
+++ b/intern/cycles/blender/blender_sync.cpp
@@ -17,6 +17,7 @@
*/
#include "background.h"
+#include "camera.h"
#include "film.h"
#include "../render/filter.h"
#include "graph.h"
@@ -141,7 +142,6 @@ void BlenderSync::sync_data(BL::SpaceView3D b_v3d, BL::Object b_override, const
sync_film();
sync_shaders();
sync_objects(b_v3d);
- sync_particle_systems();
sync_motion(b_v3d, b_override);
}
@@ -149,6 +149,9 @@ void BlenderSync::sync_data(BL::SpaceView3D b_v3d, BL::Object b_override, const
void BlenderSync::sync_integrator()
{
+#ifdef __CAMERA_MOTION__
+ BL::RenderSettings r = b_scene.render();
+#endif
PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
experimental = (RNA_enum_get(&cscene, "feature_set") != 0);
@@ -175,7 +178,12 @@ void BlenderSync::sync_integrator()
integrator->layer_flag = render_layer.layer;
integrator->sample_clamp = get_float(cscene, "sample_clamp");
-#ifdef __MOTION__
+#ifdef __CAMERA_MOTION__
+ if(integrator->motion_blur != r.use_motion_blur()) {
+ scene->object_manager->tag_update(scene);
+ scene->camera->tag_update();
+ }
+
integrator->motion_blur = (!preview && r.use_motion_blur());
#endif
@@ -368,7 +376,7 @@ SessionParams BlenderSync::get_session_params(BL::RenderEngine b_engine, BL::Use
params.tile_size = make_int2(tile_x, tile_y);
}
- params.resolution = 1 << get_int(cscene, "resolution_divider");
+ params.start_resolution = get_int(cscene, "preview_start_resolution");
/* other parameters */
params.threads = b_scene.render().threads();
@@ -377,13 +385,27 @@ SessionParams BlenderSync::get_session_params(BL::RenderEngine b_engine, BL::Use
params.reset_timeout = get_float(cscene, "debug_reset_timeout");
params.text_timeout = get_float(cscene, "debug_text_timeout");
+ params.progressive_refine = get_boolean(cscene, "use_progressive_refine");
+
if(background) {
- params.progressive = false;
- params.resolution = 1;
+ if(params.progressive_refine)
+ params.progressive = true;
+ else
+ params.progressive = false;
+
+ params.start_resolution = INT_MAX;
}
else
params.progressive = true;
-
+
+ /* shading system - scene level needs full refresh */
+ int shadingsystem = RNA_enum_get(&cscene, "shading_system");
+
+ if(shadingsystem == 0)
+ params.shadingsystem = SessionParams::SVM;
+ else if(shadingsystem == 1)
+ params.shadingsystem = SessionParams::OSL;
+
return params;
}
diff --git a/intern/cycles/blender/blender_sync.h b/intern/cycles/blender/blender_sync.h
index 27f6b6ee4ee..36cd5e684a7 100644
--- a/intern/cycles/blender/blender_sync.h
+++ b/intern/cycles/blender/blender_sync.h
@@ -63,7 +63,7 @@ public:
static SceneParams get_scene_params(BL::Scene b_scene, bool background);
static SessionParams get_session_params(BL::RenderEngine b_engine, BL::UserPreferences b_userpref, BL::Scene b_scene, bool background);
static bool get_session_pause(BL::Scene b_scene, bool background);
- static BufferParams get_buffer_params(BL::Scene b_scene, Camera *cam, int width, int height);
+ static BufferParams get_buffer_params(BL::Scene b_scene, BL::SpaceView3D b_v3d, BL::RegionView3D b_rv3d, Camera *cam, int width, int height);
private:
/* sync */
@@ -77,11 +77,10 @@ private:
void sync_world();
void sync_render_layers(BL::SpaceView3D b_v3d, const char *layer);
void sync_shaders();
- void sync_particle_systems();
void sync_nodes(Shader *shader, BL::ShaderNodeTree b_ntree);
Mesh *sync_mesh(BL::Object b_ob, bool object_updated);
- void sync_object(BL::Object b_parent, int b_index, BL::Object b_object, Transform& tfm, uint layer_flag, int motion, int particle_id);
+ void sync_object(BL::Object b_parent, int b_index, BL::DupliObject b_dupli_object, Transform& tfm, uint layer_flag, int motion, int particle_id);
void sync_light(BL::Object b_parent, int b_index, BL::Object b_ob, Transform& tfm);
void sync_background_light();
void sync_mesh_motion(BL::Object b_ob, Mesh *mesh, int motion);
diff --git a/intern/cycles/blender/blender_util.h b/intern/cycles/blender/blender_util.h
index d0fca9a9fb9..df1e99882b8 100644
--- a/intern/cycles/blender/blender_util.h
+++ b/intern/cycles/blender/blender_util.h
@@ -30,29 +30,7 @@
* todo: clean this up ... */
extern "C" {
-
-struct RenderEngine;
-struct RenderResult;
-
-ID *rna_Object_to_mesh(void *_self, void *reports, void *scene, int apply_modifiers, int settings);
-void rna_Main_meshes_remove(void *bmain, void *reports, void *mesh);
-void rna_Object_create_duplilist(void *ob, void *reports, void *sce);
-void rna_Object_free_duplilist(void *ob, void *reports);
-void rna_RenderLayer_rect_set(PointerRNA *ptr, const float *values);
-void rna_RenderPass_rect_set(PointerRNA *ptr, const float *values);
-struct RenderResult *RE_engine_begin_result(struct RenderEngine *engine, int x, int y, int w, int h, const char *layername);
-void RE_engine_update_result(struct RenderEngine *engine, struct RenderResult *result);
-void RE_engine_end_result(struct RenderEngine *engine, struct RenderResult *result, int cancel);
-int RE_engine_test_break(struct RenderEngine *engine);
-void RE_engine_update_stats(struct RenderEngine *engine, const char *stats, const char *info);
-void RE_engine_update_progress(struct RenderEngine *engine, float progress);
-void engine_tag_redraw(void *engine);
-void engine_tag_update(void *engine);
-int rna_Object_is_modified(void *ob, void *scene, int settings);
-int rna_Object_is_deform_modified(void *ob, void *scene, int settings);
void BLI_timestr(double _time, char *str);
-void rna_ColorRamp_eval(void *coba, float position, float color[4]);
-void rna_Scene_frame_set(void *scene, int frame, float subframe);
void BKE_image_user_frame_calc(void *iuser, int cfra, int fieldnr);
void BKE_image_user_file_path(void *iuser, void *ima, char *path);
}
@@ -61,10 +39,7 @@ CCL_NAMESPACE_BEGIN
static inline BL::Mesh object_to_mesh(BL::Object self, BL::Scene scene, bool apply_modifiers, bool render)
{
- ID *data = rna_Object_to_mesh(self.ptr.data, NULL, scene.ptr.data, apply_modifiers, (render)? 2: 1);
- PointerRNA ptr;
- RNA_id_pointer_create(data, &ptr);
- return BL::Mesh(ptr);
+ return self.to_mesh(scene, apply_modifiers, (render)? 2: 1);
}
static inline void colorramp_to_array(BL::ColorRamp ramp, float4 *data, int size)
@@ -72,34 +47,19 @@ static inline void colorramp_to_array(BL::ColorRamp ramp, float4 *data, int size
for(int i = 0; i < size; i++) {
float color[4];
- rna_ColorRamp_eval(ramp.ptr.data, i/(float)(size-1), color);
+ ramp.evaluate(i/(float)(size-1), color);
data[i] = make_float4(color[0], color[1], color[2], color[3]);
}
}
-static inline void object_remove_mesh(BL::BlendData data, BL::Mesh mesh)
-{
- rna_Main_meshes_remove(data.ptr.data, NULL, mesh.ptr.data);
-}
-
-static inline void object_create_duplilist(BL::Object self, BL::Scene scene)
-{
- rna_Object_create_duplilist(self.ptr.data, NULL, scene.ptr.data);
-}
-
-static inline void object_free_duplilist(BL::Object self)
-{
- rna_Object_free_duplilist(self.ptr.data, NULL);
-}
-
static inline bool BKE_object_is_modified(BL::Object self, BL::Scene scene, bool preview)
{
- return rna_Object_is_modified(self.ptr.data, scene.ptr.data, (preview)? (1<<0): (1<<1))? true: false;
+ return self.is_modified(scene, (preview)? (1<<0): (1<<1))? true: false;
}
static inline bool BKE_object_is_deform_modified(BL::Object self, BL::Scene scene, bool preview)
{
- return rna_Object_is_deform_modified(self.ptr.data, scene.ptr.data, (preview)? (1<<0): (1<<1))? true: false;
+ return self.is_deform_modified(scene, (preview)? (1<<0): (1<<1))? true: false;
}
static inline string image_user_file_path(BL::ImageUser iuser, BL::Image ima, int cfra)
@@ -110,11 +70,6 @@ static inline string image_user_file_path(BL::ImageUser iuser, BL::Image ima, in
return string(filepath);
}
-static inline void scene_frame_set(BL::Scene scene, int frame)
-{
- rna_Scene_frame_set(scene.ptr.data, frame, 0.0f);
-}
-
/* Utilities */
static inline Transform get_transform(BL::Array<float, 16> array)
diff --git a/intern/cycles/bvh/CMakeLists.txt b/intern/cycles/bvh/CMakeLists.txt
index 131a7a1f750..cbbd23fcff8 100644
--- a/intern/cycles/bvh/CMakeLists.txt
+++ b/intern/cycles/bvh/CMakeLists.txt
@@ -8,6 +8,9 @@ set(INC
../device
)
+set(INC_SYS
+)
+
set(SRC
bvh.cpp
bvh_binning.cpp
@@ -28,5 +31,6 @@ set(SRC_HEADERS
)
include_directories(${INC})
+include_directories(SYSTEM ${INC_SYS})
add_library(cycles_bvh ${SRC} ${SRC_HEADERS})
diff --git a/intern/cycles/bvh/bvh_node.h b/intern/cycles/bvh/bvh_node.h
index 5c00f7b7a38..a0d10a46bfc 100644
--- a/intern/cycles/bvh/bvh_node.h
+++ b/intern/cycles/bvh/bvh_node.h
@@ -54,7 +54,7 @@ public:
// Subtree functions
int getSubtreeSize(BVH_STAT stat=BVH_STAT_NODE_COUNT) const;
- float computeSubtreeSAHCost(const BVHParams& p, float probability = 1.0f) const;
+ float computeSubtreeSAHCost(const BVHParams& p, float probability = 1.0f) const;
void deleteSubtree();
uint update_visibility();
diff --git a/intern/cycles/device/CMakeLists.txt b/intern/cycles/device/CMakeLists.txt
index 6038abd815e..0071bbe5cdc 100644
--- a/intern/cycles/device/CMakeLists.txt
+++ b/intern/cycles/device/CMakeLists.txt
@@ -6,6 +6,9 @@ set(INC
../kernel/osl
../util
../render
+)
+
+set(INC_SYS
${OPENGL_INCLUDE_DIR}
${GLEW_INCLUDE_PATH}
)
@@ -31,5 +34,6 @@ set(SRC_HEADERS
add_definitions(-DGLEW_STATIC)
include_directories(${INC})
+include_directories(SYSTEM ${INC_SYS})
add_library(cycles_device ${SRC} ${SRC_HEADERS})
diff --git a/intern/cycles/device/device.cpp b/intern/cycles/device/device.cpp
index 9a4d364a9b8..550da2982a3 100644
--- a/intern/cycles/device/device.cpp
+++ b/intern/cycles/device/device.cpp
@@ -28,6 +28,7 @@
#include "util_math.h"
#include "util_opencl.h"
#include "util_opengl.h"
+#include "util_time.h"
#include "util_types.h"
#include "util_vector.h"
@@ -77,36 +78,36 @@ void Device::draw_pixels(device_memory& rgba, int y, int w, int h, int dy, int w
glDisable(GL_BLEND);
}
-Device *Device::create(DeviceInfo& info, bool background, int threads)
+Device *Device::create(DeviceInfo& info, Stats &stats, bool background, int threads)
{
Device *device;
switch(info.type) {
case DEVICE_CPU:
- device = device_cpu_create(info, threads);
+ device = device_cpu_create(info, stats, threads);
break;
#ifdef WITH_CUDA
case DEVICE_CUDA:
if(cuLibraryInit())
- device = device_cuda_create(info, background);
+ device = device_cuda_create(info, stats, background);
else
device = NULL;
break;
#endif
#ifdef WITH_MULTI
case DEVICE_MULTI:
- device = device_multi_create(info, background);
+ device = device_multi_create(info, stats, background);
break;
#endif
#ifdef WITH_NETWORK
case DEVICE_NETWORK:
- device = device_network_create(info, "127.0.0.1");
+ device = device_network_create(info, stats, "127.0.0.1");
break;
#endif
#ifdef WITH_OPENCL
case DEVICE_OPENCL:
if(clLibraryInit())
- device = device_opencl_create(info, background);
+ device = device_opencl_create(info, stats, background);
else
device = NULL;
break;
@@ -188,6 +189,18 @@ vector<DeviceInfo>& Device::available_devices()
{
static vector<DeviceInfo> devices;
static bool devices_init = false;
+ static double device_update_time = 0.0;
+
+ /* only update device list if we're not actively rendering already, things
+ * could go very wrong if a device suddenly becomes (un)available. also do
+ * it only every 5 seconds. it not super cpu intensive but don't want to do
+ * it on every redraw. */
+ if(devices_init) {
+ if(!TaskScheduler::active() && (time_dt() > device_update_time + 5.0)) {
+ devices.clear();
+ devices_init = false;
+ }
+ }
if(!devices_init) {
#ifdef WITH_CUDA
@@ -211,6 +224,7 @@ vector<DeviceInfo>& Device::available_devices()
#endif
devices_init = true;
+ device_update_time = time_dt();
}
return devices;
diff --git a/intern/cycles/device/device.h b/intern/cycles/device/device.h
index 8e3bc408399..95da0a89833 100644
--- a/intern/cycles/device/device.h
+++ b/intern/cycles/device/device.h
@@ -25,6 +25,7 @@
#include "device_task.h"
#include "util_list.h"
+#include "util_stats.h"
#include "util_string.h"
#include "util_thread.h"
#include "util_types.h"
@@ -72,7 +73,7 @@ public:
class Device {
protected:
- Device() {}
+ Device(Stats &stats_) : stats(stats_) {}
bool background;
string error_msg;
@@ -84,6 +85,9 @@ public:
DeviceInfo info;
virtual const string& error_message() { return error_msg; }
+ /* statistics */
+ Stats &stats;
+
/* regular memory */
virtual void mem_alloc(device_memory& mem, MemoryType type) = 0;
virtual void mem_copy_to(device_memory& mem) = 0;
@@ -115,7 +119,6 @@ public:
virtual void task_add(DeviceTask& task) = 0;
virtual void task_wait() = 0;
virtual void task_cancel() = 0;
- virtual bool task_cancelled() = 0;
/* opengl drawing */
virtual void draw_pixels(device_memory& mem, int y, int w, int h,
@@ -131,7 +134,7 @@ public:
virtual int device_number(Device *sub_device) { return 0; }
/* static */
- static Device *create(DeviceInfo& info, bool background = true, int threads = 0);
+ static Device *create(DeviceInfo& info, Stats &stats, bool background = true, int threads = 0);
static DeviceType type_from_string(const char *name);
static string string_from_type(DeviceType type);
diff --git a/intern/cycles/device/device_cpu.cpp b/intern/cycles/device/device_cpu.cpp
index e2f612ee233..519c458ffdf 100644
--- a/intern/cycles/device/device_cpu.cpp
+++ b/intern/cycles/device/device_cpu.cpp
@@ -45,7 +45,7 @@ public:
TaskPool task_pool;
KernelGlobals *kg;
- CPUDevice(int threads_num)
+ CPUDevice(Stats &stats, int threads_num) : Device(stats)
{
kg = kernel_globals_create();
@@ -67,6 +67,8 @@ public:
void mem_alloc(device_memory& mem, MemoryType type)
{
mem.device_pointer = mem.data_pointer;
+
+ stats.mem_alloc(mem.memory_size());
}
void mem_copy_to(device_memory& mem)
@@ -87,6 +89,8 @@ public:
void mem_free(device_memory& mem)
{
mem.device_pointer = 0;
+
+ stats.mem_free(mem.memory_size());
}
void const_copy_to(const char *name, void *host, size_t size)
@@ -98,11 +102,15 @@ public:
{
kernel_tex_copy(kg, name, mem.data_pointer, mem.data_width, mem.data_height);
mem.device_pointer = mem.data_pointer;
+
+ stats.mem_alloc(mem.memory_size());
}
void tex_free(device_memory& mem)
{
mem.device_pointer = 0;
+
+ stats.mem_free(mem.memory_size());
}
void *osl_memory()
@@ -135,8 +143,10 @@ public:
void thread_path_trace(DeviceTask& task)
{
- if(task_pool.cancelled())
- return;
+ if(task_pool.cancelled()) {
+ if(task.need_finish_queue == false)
+ return;
+ }
#ifdef WITH_OSL
if(kernel_osl_use(kg))
@@ -154,8 +164,10 @@ public:
#ifdef WITH_OPTIMIZED_KERNEL
if(system_cpu_support_optimized()) {
for(int sample = start_sample; sample < end_sample; sample++) {
- if (task.get_cancel() || task_pool.cancelled())
- break;
+ if (task.get_cancel() || task_pool.cancelled()) {
+ if(task.need_finish_queue == false)
+ break;
+ }
for(int y = tile.y; y < tile.y + tile.h; y++) {
for(int x = tile.x; x < tile.x + tile.w; x++) {
@@ -173,8 +185,10 @@ public:
#endif
{
for(int sample = start_sample; sample < end_sample; sample++) {
- if (task.get_cancel() || task_pool.cancelled())
- break;
+ if (task.get_cancel() || task_pool.cancelled()) {
+ if(task.need_finish_queue == false)
+ break;
+ }
for(int y = tile.y; y < tile.y + tile.h; y++) {
for(int x = tile.x; x < tile.x + tile.w; x++) {
@@ -191,8 +205,10 @@ public:
task.release_tile(tile);
- if(task_pool.cancelled())
- break;
+ if(task_pool.cancelled()) {
+ if(task.need_finish_queue == false)
+ break;
+ }
}
#ifdef WITH_OSL
@@ -273,16 +289,11 @@ public:
{
task_pool.cancel();
}
-
- bool task_cancelled()
- {
- return task_pool.cancelled();
- }
};
-Device *device_cpu_create(DeviceInfo& info, int threads)
+Device *device_cpu_create(DeviceInfo& info, Stats &stats, int threads)
{
- return new CPUDevice(threads);
+ return new CPUDevice(stats, threads);
}
void device_cpu_info(vector<DeviceInfo>& devices)
diff --git a/intern/cycles/device/device_cuda.cpp b/intern/cycles/device/device_cuda.cpp
index acc1086cc35..d797c0f09ca 100644
--- a/intern/cycles/device/device_cuda.cpp
+++ b/intern/cycles/device/device_cuda.cpp
@@ -157,7 +157,7 @@ public:
cuda_assert(cuCtxSetCurrent(NULL));
}
- CUDADevice(DeviceInfo& info, bool background_)
+ CUDADevice(DeviceInfo& info, Stats &stats, bool background_) : Device(stats)
{
background = background_;
@@ -316,8 +316,10 @@ public:
{
cuda_push_context();
CUdeviceptr device_pointer;
- cuda_assert(cuMemAlloc(&device_pointer, mem.memory_size()))
+ size_t size = mem.memory_size();
+ cuda_assert(cuMemAlloc(&device_pointer, size))
mem.device_pointer = (device_ptr)device_pointer;
+ stats.mem_alloc(size);
cuda_pop_context();
}
@@ -356,6 +358,8 @@ public:
cuda_pop_context();
mem.device_pointer = 0;
+
+ stats.mem_free(mem.memory_size());
}
}
@@ -424,6 +428,8 @@ public:
cuda_assert(cuTexRefSetFlags(texref, CU_TRSF_NORMALIZED_COORDINATES))
mem.device_pointer = (device_ptr)handle;
+
+ stats.mem_alloc(size);
}
else {
cuda_pop_context();
@@ -463,6 +469,8 @@ public:
tex_interp_map.erase(tex_interp_map.find(mem.device_pointer));
mem.device_pointer = 0;
+
+ stats.mem_free(mem.memory_size());
}
else {
tex_interp_map.erase(tex_interp_map.find(mem.device_pointer));
@@ -707,6 +715,8 @@ public:
mem.device_pointer = pmem.cuTexId;
pixel_mem_map[mem.device_pointer] = pmem;
+ stats.mem_alloc(mem.memory_size());
+
return;
}
else {
@@ -762,6 +772,8 @@ public:
pixel_mem_map.erase(pixel_mem_map.find(mem.device_pointer));
mem.device_pointer = 0;
+ stats.mem_free(mem.memory_size());
+
return;
}
@@ -837,8 +849,10 @@ public:
int end_sample = tile.start_sample + tile.num_samples;
for(int sample = start_sample; sample < end_sample; sample++) {
- if (task->get_cancel())
- break;
+ if (task->get_cancel()) {
+ if(task->need_finish_queue == false)
+ break;
+ }
path_trace(tile, sample);
@@ -892,16 +906,11 @@ public:
{
task_pool.cancel();
}
-
- bool task_cancelled()
- {
- return task_pool.cancelled();
- }
};
-Device *device_cuda_create(DeviceInfo& info, bool background)
+Device *device_cuda_create(DeviceInfo& info, Stats &stats, bool background)
{
- return new CUDADevice(info, background);
+ return new CUDADevice(info, stats, background);
}
void device_cuda_info(vector<DeviceInfo>& devices)
diff --git a/intern/cycles/device/device_intern.h b/intern/cycles/device/device_intern.h
index e3601aa8ad4..02fbac6860e 100644
--- a/intern/cycles/device/device_intern.h
+++ b/intern/cycles/device/device_intern.h
@@ -23,11 +23,11 @@ CCL_NAMESPACE_BEGIN
class Device;
-Device *device_cpu_create(DeviceInfo& info, int threads);
-Device *device_opencl_create(DeviceInfo& info, bool background);
-Device *device_cuda_create(DeviceInfo& info, bool background);
-Device *device_network_create(DeviceInfo& info, const char *address);
-Device *device_multi_create(DeviceInfo& info, bool background);
+Device *device_cpu_create(DeviceInfo& info, Stats &stats, int threads);
+Device *device_opencl_create(DeviceInfo& info, Stats &stats, bool background);
+Device *device_cuda_create(DeviceInfo& info, Stats &stats, bool background);
+Device *device_network_create(DeviceInfo& info, Stats &stats, const char *address);
+Device *device_multi_create(DeviceInfo& info, Stats &stats, bool background);
void device_cpu_info(vector<DeviceInfo>& devices);
void device_opencl_info(vector<DeviceInfo>& devices);
diff --git a/intern/cycles/device/device_multi.cpp b/intern/cycles/device/device_multi.cpp
index 4923e5c9e66..807bfe578f3 100644
--- a/intern/cycles/device/device_multi.cpp
+++ b/intern/cycles/device/device_multi.cpp
@@ -46,14 +46,14 @@ public:
list<SubDevice> devices;
device_ptr unique_ptr;
- MultiDevice(DeviceInfo& info, bool background_)
- : unique_ptr(1)
+ MultiDevice(DeviceInfo& info, Stats &stats, bool background_)
+ : Device(stats), unique_ptr(1)
{
Device *device;
background = background_;
foreach(DeviceInfo& subinfo, info.multi_devices) {
- device = Device::create(subinfo, background);
+ device = Device::create(subinfo, stats, background);
devices.push_back(SubDevice(device));
}
@@ -312,19 +312,11 @@ public:
foreach(SubDevice& sub, devices)
sub.device->task_cancel();
}
-
- bool task_cancelled()
- {
- foreach(SubDevice& sub, devices)
- if (sub.device->task_cancelled())
- return true;
- return false;
- }
};
-Device *device_multi_create(DeviceInfo& info, bool background)
+Device *device_multi_create(DeviceInfo& info, Stats &stats, bool background)
{
- return new MultiDevice(info, background);
+ return new MultiDevice(info, stats, background);
}
static bool device_multi_add(vector<DeviceInfo>& devices, DeviceType type, bool with_display, bool with_advanced_shading, const char *id_fmt, int num)
diff --git a/intern/cycles/device/device_network.cpp b/intern/cycles/device/device_network.cpp
index 931890b5859..a5e0d39df73 100644
--- a/intern/cycles/device/device_network.cpp
+++ b/intern/cycles/device/device_network.cpp
@@ -32,8 +32,8 @@ public:
boost::asio::io_service io_service;
tcp::socket socket;
- NetworkDevice(const char *address)
- : socket(io_service)
+ NetworkDevice(Stats &stats, const char *address)
+ : Device(stats), socket(io_service)
{
stringstream portstr;
portstr << SERVER_PORT;
@@ -202,9 +202,9 @@ public:
}
};
-Device *device_network_create(DeviceInfo& info, const char *address)
+Device *device_network_create(DeviceInfo& info, Stats &stats, const char *address)
{
- return new NetworkDevice(address);
+ return new NetworkDevice(stats, address);
}
void device_network_info(vector<DeviceInfo>& devices)
diff --git a/intern/cycles/device/device_opencl.cpp b/intern/cycles/device/device_opencl.cpp
index ed7229d49da..69287f1a8bd 100644
--- a/intern/cycles/device/device_opencl.cpp
+++ b/intern/cycles/device/device_opencl.cpp
@@ -144,7 +144,8 @@ public:
}
}
- OpenCLDevice(DeviceInfo& info, bool background_)
+ OpenCLDevice(DeviceInfo& info, Stats &stats, bool background_)
+ : Device(stats)
{
background = background_;
cpPlatform = NULL;
@@ -473,6 +474,8 @@ public:
mem.device_pointer = (device_ptr)clCreateBuffer(cxContext, CL_MEM_READ_WRITE, size, NULL, &ciErr);
opencl_assert(ciErr);
+
+ stats.mem_alloc(size);
}
void mem_copy_to(device_memory& mem)
@@ -506,6 +509,8 @@ public:
ciErr = clReleaseMemObject(CL_MEM_PTR(mem.device_pointer));
mem.device_pointer = 0;
opencl_assert(ciErr);
+
+ stats.mem_free(mem.memory_size());
}
}
@@ -686,8 +691,10 @@ public:
int end_sample = tile.start_sample + tile.num_samples;
for(int sample = start_sample; sample < end_sample; sample++) {
- if (task->get_cancel())
- break;
+ if (task->get_cancel()) {
+ if(task->need_finish_queue == false)
+ break;
+ }
path_trace(tile, sample);
@@ -724,16 +731,11 @@ public:
{
task_pool.cancel();
}
-
- bool task_cancelled()
- {
- return task_pool.cancelled();
- }
};
-Device *device_opencl_create(DeviceInfo& info, bool background)
+Device *device_opencl_create(DeviceInfo& info, Stats &stats, bool background)
{
- return new OpenCLDevice(info, background);
+ return new OpenCLDevice(info, stats, background);
}
void device_opencl_info(vector<DeviceInfo>& devices)
diff --git a/intern/cycles/device/device_task.h b/intern/cycles/device/device_task.h
index cfb3d8d988e..8ca8b88ea49 100644
--- a/intern/cycles/device/device_task.h
+++ b/intern/cycles/device/device_task.h
@@ -65,6 +65,7 @@ public:
boost::function<void(RenderTile&)> release_tile;
boost::function<bool(void)> get_cancel;
+ bool need_finish_queue;
protected:
double last_update_time;
};
diff --git a/intern/cycles/kernel/CMakeLists.txt b/intern/cycles/kernel/CMakeLists.txt
index b43aca24496..82b0605ab6b 100644
--- a/intern/cycles/kernel/CMakeLists.txt
+++ b/intern/cycles/kernel/CMakeLists.txt
@@ -6,6 +6,10 @@ set(INC
svm
)
+set(INC_SYS
+
+)
+
set(SRC
kernel.cpp
kernel_optimized.cpp
@@ -29,13 +33,11 @@ set(SRC_HEADERS
kernel_globals.h
kernel_light.h
kernel_math.h
- kernel_mbvh.h
kernel_montecarlo.h
kernel_object.h
kernel_passes.h
kernel_path.h
kernel_projection.h
- kernel_qbvh.h
kernel_random.h
kernel_shader.h
kernel_textures.h
@@ -43,18 +45,21 @@ set(SRC_HEADERS
kernel_types.h
)
+set(SRC_CLOSURE_HEADERS
+ closure/bsdf.h
+ closure/bsdf_ashikhmin_velvet.h
+ closure/bsdf_diffuse.h
+ closure/bsdf_microfacet.h
+ closure/bsdf_oren_nayar.h
+ closure/bsdf_reflection.h
+ closure/bsdf_refraction.h
+ closure/bsdf_transparent.h
+ closure/bsdf_ward.h
+ closure/bsdf_westin.h
+ closure/emissive.h
+ closure/volume.h
+)
set(SRC_SVM_HEADERS
- svm/bsdf.h
- svm/bsdf_ashikhmin_velvet.h
- svm/bsdf_diffuse.h
- svm/bsdf_oren_nayar.h
- svm/bsdf_microfacet.h
- svm/bsdf_reflection.h
- svm/bsdf_refraction.h
- svm/bsdf_transparent.h
- svm/bsdf_ward.h
- svm/bsdf_westin.h
- svm/emissive.h
svm/svm.h
svm/svm_attribute.h
svm/svm_bsdf.h
@@ -90,7 +95,6 @@ set(SRC_SVM_HEADERS
svm/svm_value.h
svm/svm_voronoi.h
svm/svm_wave.h
- svm/volume.h
)
set(SRC_UTIL_HEADERS
@@ -108,7 +112,7 @@ if(WITH_CYCLES_CUDA_BINARIES)
set(CUDA_BITS 32)
endif()
- set(cuda_sources kernel.cu ${SRC_HEADERS} ${SRC_SVM_HEADERS} ${SRC_UTIL_HEADERS})
+ set(cuda_sources kernel.cu ${SRC_HEADERS} ${SRC_SVM_HEADERS} ${SRC_CLOSURE_HEADERS} ${SRC_UTIL_HEADERS})
set(cuda_cubins)
foreach(arch ${CYCLES_CUDA_BINARIES_ARCH})
@@ -130,13 +134,15 @@ endif()
if(WITH_CYCLES_OSL)
add_subdirectory(osl)
+ add_subdirectory(shaders)
endif()
# CPU module
include_directories(${INC})
+include_directories(SYSTEM ${INC_SYS})
-add_library(cycles_kernel ${SRC} ${SRC_HEADERS} ${SRC_SVM_HEADERS})
+add_library(cycles_kernel ${SRC} ${SRC_HEADERS} ${SRC_CLOSURE_HEADERS} ${SRC_SVM_HEADERS})
if(WITH_CYCLES_OPTIMIZED_KERNEL)
set_source_files_properties(kernel_optimized.cpp PROPERTIES COMPILE_FLAGS "${CYCLES_OPTIMIZED_KERNEL_FLAGS}")
@@ -159,6 +165,7 @@ endif()
delayed_install(${CMAKE_CURRENT_SOURCE_DIR} "kernel.cl" ${CYCLES_INSTALL_PATH}/kernel)
delayed_install(${CMAKE_CURRENT_SOURCE_DIR} "kernel.cu" ${CYCLES_INSTALL_PATH}/kernel)
delayed_install(${CMAKE_CURRENT_SOURCE_DIR} "${SRC_HEADERS}" ${CYCLES_INSTALL_PATH}/kernel)
+delayed_install(${CMAKE_CURRENT_SOURCE_DIR} "${SRC_CLOSURE_HEADERS}" ${CYCLES_INSTALL_PATH}/kernel/closure)
delayed_install(${CMAKE_CURRENT_SOURCE_DIR} "${SRC_SVM_HEADERS}" ${CYCLES_INSTALL_PATH}/kernel/svm)
delayed_install(${CMAKE_CURRENT_SOURCE_DIR} "${SRC_UTIL_HEADERS}" ${CYCLES_INSTALL_PATH}/kernel)
diff --git a/intern/cycles/kernel/svm/bsdf.h b/intern/cycles/kernel/closure/bsdf.h
index 1a90eab0cd1..cfb6321a918 100644
--- a/intern/cycles/kernel/svm/bsdf.h
+++ b/intern/cycles/kernel/closure/bsdf.h
@@ -58,7 +58,8 @@ __device float fresnel_dielectric(float eta, const float3 N,
neta = 1 / eta;
Nn = N;
*is_inside = false;
- } else {
+ }
+ else {
// we are inside the surface,
cos = -cos;
neta = eta;
@@ -74,7 +75,8 @@ __device float fresnel_dielectric(float eta, const float3 N,
*dTdy = make_float3(0.0f, 0.0f, 0.0f);
#endif
return 1; // total internal reflection
- } else {
+ }
+ else {
float dnp = sqrtf(arg);
float nK = (neta * cos)- dnp;
*T = -(neta * I)+(nK * Nn);
diff --git a/intern/cycles/kernel/svm/bsdf_ashikhmin_velvet.h b/intern/cycles/kernel/closure/bsdf_ashikhmin_velvet.h
index 40249dbe9c6..016fd73204e 100644
--- a/intern/cycles/kernel/svm/bsdf_ashikhmin_velvet.h
+++ b/intern/cycles/kernel/closure/bsdf_ashikhmin_velvet.h
@@ -35,37 +35,34 @@
CCL_NAMESPACE_BEGIN
-typedef struct BsdfAshikhminVelvetClosure {
- //float3 m_N;
- float m_invsigma2;
-} BsdfAshikhminVelvetClosure;
-
-__device void bsdf_ashikhmin_velvet_setup(ShaderData *sd, ShaderClosure *sc, float sigma)
+__device int bsdf_ashikhmin_velvet_setup(ShaderClosure *sc)
{
+ float sigma = sc->data0;
sigma = fmaxf(sigma, 0.01f);
float m_invsigma2 = 1.0f/(sigma * sigma);
sc->type = CLOSURE_BSDF_ASHIKHMIN_VELVET_ID;
- sd->flag |= SD_BSDF|SD_BSDF_HAS_EVAL;
sc->data0 = m_invsigma2;
+
+ return SD_BSDF|SD_BSDF_HAS_EVAL;
}
__device void bsdf_ashikhmin_velvet_blur(ShaderClosure *sc, float roughness)
{
}
-__device float3 bsdf_ashikhmin_velvet_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_ashikhmin_velvet_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
float m_invsigma2 = sc->data0;
- float3 m_N = sd->N;
+ float3 N = sc->N;
- float cosNO = dot(m_N, I);
- float cosNI = dot(m_N, omega_in);
+ float cosNO = dot(N, I);
+ float cosNI = dot(N, omega_in);
if(cosNO > 0 && cosNI > 0) {
float3 H = normalize(omega_in + I);
- float cosNH = dot(m_N, H);
+ float cosNH = dot(N, H);
float cosHO = fabsf(dot(I, H));
if(!(fabsf(cosNH) < 1.0f-1e-5f && cosHO > 1e-5f))
@@ -93,32 +90,27 @@ __device float3 bsdf_ashikhmin_velvet_eval_reflect(const ShaderData *sd, const S
return make_float3(0, 0, 0);
}
-__device float3 bsdf_ashikhmin_velvet_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_ashikhmin_velvet_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float bsdf_ashikhmin_velvet_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
-{
- return 1.0f;
-}
-
-__device int bsdf_ashikhmin_velvet_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_ashikhmin_velvet_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
float m_invsigma2 = sc->data0;
- float3 m_N = sd->N;
+ float3 N = sc->N;
// we are viewing the surface from above - send a ray out with uniform
// distribution over the hemisphere
- sample_uniform_hemisphere(m_N, randu, randv, omega_in, pdf);
+ sample_uniform_hemisphere(N, randu, randv, omega_in, pdf);
- if(dot(sd->Ng, *omega_in) > 0) {
- float3 H = normalize(*omega_in + sd->I);
+ if(dot(Ng, *omega_in) > 0) {
+ float3 H = normalize(*omega_in + I);
- float cosNI = dot(m_N, *omega_in);
- float cosNO = dot(m_N, sd->I);
- float cosNH = dot(m_N, H);
- float cosHO = fabsf(dot(sd->I, H));
+ float cosNI = dot(N, *omega_in);
+ float cosNO = dot(N, I);
+ float cosNH = dot(N, H);
+ float cosHO = fabsf(dot(I, H));
if(fabsf(cosNO) > 1e-5f && fabsf(cosNH) < 1.0f-1e-5f && cosHO > 1e-5f) {
float cosNHdivHO = cosNH / cosHO;
@@ -140,8 +132,8 @@ __device int bsdf_ashikhmin_velvet_sample(const ShaderData *sd, const ShaderClos
#ifdef __RAY_DIFFERENTIALS__
// TODO: find a better approximation for the retroreflective bounce
- *domega_in_dx = (2 * dot(m_N, sd->dI.dx)) * m_N - sd->dI.dx;
- *domega_in_dy = (2 * dot(m_N, sd->dI.dy)) * m_N - sd->dI.dy;
+ *domega_in_dx = (2 * dot(N, dIdx)) * N - dIdx;
+ *domega_in_dy = (2 * dot(N, dIdy)) * N - dIdy;
*domega_in_dx *= 125.0f;
*domega_in_dy *= 125.0f;
#endif
diff --git a/intern/cycles/kernel/svm/bsdf_diffuse.h b/intern/cycles/kernel/closure/bsdf_diffuse.h
index 45e82a566c0..88b40e3d479 100644
--- a/intern/cycles/kernel/svm/bsdf_diffuse.h
+++ b/intern/cycles/kernel/closure/bsdf_diffuse.h
@@ -37,52 +37,43 @@ CCL_NAMESPACE_BEGIN
/* DIFFUSE */
-typedef struct BsdfDiffuseClosure {
- //float3 m_N;
-} BsdfDiffuseClosure;
-
-__device void bsdf_diffuse_setup(ShaderData *sd, ShaderClosure *sc)
+__device int bsdf_diffuse_setup(ShaderClosure *sc)
{
sc->type = CLOSURE_BSDF_DIFFUSE_ID;
- sd->flag |= SD_BSDF|SD_BSDF_HAS_EVAL;
+ return SD_BSDF|SD_BSDF_HAS_EVAL;
}
__device void bsdf_diffuse_blur(ShaderClosure *sc, float roughness)
{
}
-__device float3 bsdf_diffuse_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_diffuse_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
- float3 m_N = sd->N;
+ float3 N = sc->N;
- float cos_pi = fmaxf(dot(m_N, omega_in), 0.0f) * M_1_PI_F;
+ float cos_pi = fmaxf(dot(N, omega_in), 0.0f) * M_1_PI_F;
*pdf = cos_pi;
return make_float3(cos_pi, cos_pi, cos_pi);
}
-__device float3 bsdf_diffuse_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_diffuse_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float bsdf_diffuse_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
-{
- return 1.0f;
-}
-
-__device int bsdf_diffuse_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_diffuse_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
- float3 m_N = sd->N;
+ float3 N = sc->N;
// distribution over the hemisphere
- sample_cos_hemisphere(m_N, randu, randv, omega_in, pdf);
+ sample_cos_hemisphere(N, randu, randv, omega_in, pdf);
- if(dot(sd->Ng, *omega_in) > 0.0f) {
+ if(dot(Ng, *omega_in) > 0.0f) {
*eval = make_float3(*pdf, *pdf, *pdf);
#ifdef __RAY_DIFFERENTIALS__
// TODO: find a better approximation for the diffuse bounce
- *domega_in_dx = (2 * dot(m_N, sd->dI.dx)) * m_N - sd->dI.dx;
- *domega_in_dy = (2 * dot(m_N, sd->dI.dy)) * m_N - sd->dI.dy;
+ *domega_in_dx = (2 * dot(N, dIdx)) * N - dIdx;
+ *domega_in_dy = (2 * dot(N, dIdy)) * N - dIdy;
*domega_in_dx *= 125.0f;
*domega_in_dy *= 125.0f;
#endif
@@ -95,58 +86,55 @@ __device int bsdf_diffuse_sample(const ShaderData *sd, const ShaderClosure *sc,
/* TRANSLUCENT */
-typedef struct BsdfTranslucentClosure {
- //float3 m_N;
-} BsdfTranslucentClosure;
-
-__device void bsdf_translucent_setup(ShaderData *sd, ShaderClosure *sc)
+__device int bsdf_translucent_setup(ShaderClosure *sc)
{
sc->type = CLOSURE_BSDF_TRANSLUCENT_ID;
- sd->flag |= SD_BSDF|SD_BSDF_HAS_EVAL;
+ return SD_BSDF|SD_BSDF_HAS_EVAL;
}
__device void bsdf_translucent_blur(ShaderClosure *sc, float roughness)
{
}
-__device float3 bsdf_translucent_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_translucent_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float3 bsdf_translucent_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_translucent_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
- float3 m_N = sd->N;
+ float3 N = sc->N;
- float cos_pi = fmaxf(-dot(m_N, omega_in), 0.0f) * M_1_PI_F;
+ float cos_pi = fmaxf(-dot(N, omega_in), 0.0f) * M_1_PI_F;
*pdf = cos_pi;
return make_float3 (cos_pi, cos_pi, cos_pi);
}
-__device float bsdf_translucent_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
+__device float bsdf_translucent_albedo(const ShaderClosure *sc, const float3 I)
{
return 1.0f;
}
-__device int bsdf_translucent_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_translucent_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
- float3 m_N = sd->N;
+ float3 N = sc->N;
// we are viewing the surface from the right side - send a ray out with cosine
// distribution over the hemisphere
- sample_cos_hemisphere (-m_N, randu, randv, omega_in, pdf);
- if(dot(sd->Ng, *omega_in) < 0) {
+ sample_cos_hemisphere (-N, randu, randv, omega_in, pdf);
+ if(dot(Ng, *omega_in) < 0) {
*eval = make_float3(*pdf, *pdf, *pdf);
#ifdef __RAY_DIFFERENTIALS__
// TODO: find a better approximation for the diffuse bounce
- *domega_in_dx = (2 * dot(m_N, sd->dI.dx)) * m_N - sd->dI.dx;
- *domega_in_dy = (2 * dot(m_N, sd->dI.dy)) * m_N - sd->dI.dy;
+ *domega_in_dx = (2 * dot(N, dIdx)) * N - dIdx;
+ *domega_in_dy = (2 * dot(N, dIdy)) * N - dIdy;
*domega_in_dx *= -125.0f;
*domega_in_dy *= -125.0f;
#endif
- } else
+ }
+ else {
*pdf = 0;
-
+ }
return LABEL_TRANSMIT|LABEL_DIFFUSE;
}
diff --git a/intern/cycles/kernel/svm/bsdf_microfacet.h b/intern/cycles/kernel/closure/bsdf_microfacet.h
index 01e3acb76e8..a564b99e759 100644
--- a/intern/cycles/kernel/svm/bsdf_microfacet.h
+++ b/intern/cycles/kernel/closure/bsdf_microfacet.h
@@ -37,31 +37,36 @@ CCL_NAMESPACE_BEGIN
/* GGX */
-typedef struct BsdfMicrofacetGGXClosure {
- //float3 m_N;
- float m_ag;
- float m_eta;
-} BsdfMicrofacetGGXClosure;
-
__device_inline float safe_sqrtf(float f)
{
return sqrtf(max(f, 0.0f));
}
-__device void bsdf_microfacet_ggx_setup(ShaderData *sd, ShaderClosure *sc, float ag, float eta, bool refractive)
+__device int bsdf_microfacet_ggx_setup(ShaderClosure *sc)
+{
+ float ag = sc->data0;
+
+ float m_ag = clamp(ag, 1e-4f, 1.0f);
+
+ sc->data0 = m_ag;
+ sc->type = CLOSURE_BSDF_MICROFACET_GGX_ID;
+
+ return SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
+}
+
+__device int bsdf_microfacet_ggx_refraction_setup(ShaderClosure *sc)
{
+ float ag = sc->data0;
+ float eta = sc->data1;
+
float m_ag = clamp(ag, 1e-4f, 1.0f);
float m_eta = eta;
sc->data0 = m_ag;
sc->data1 = m_eta;
+ sc->type = CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID;
- if(refractive)
- sc->type = CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID;
- else
- sc->type = CLOSURE_BSDF_MICROFACET_GGX_ID;
-
- sd->flag |= SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
+ return SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
}
__device void bsdf_microfacet_ggx_blur(ShaderClosure *sc, float roughness)
@@ -71,23 +76,22 @@ __device void bsdf_microfacet_ggx_blur(ShaderClosure *sc, float roughness)
sc->data0 = m_ag;
}
-__device float3 bsdf_microfacet_ggx_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_microfacet_ggx_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
float m_ag = sc->data0;
- //float m_eta = sc->data1;
int m_refractive = sc->type == CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID;
- float3 m_N = sd->N;
+ float3 N = sc->N;
if(m_refractive) return make_float3 (0, 0, 0);
- float cosNO = dot(m_N, I);
- float cosNI = dot(m_N, omega_in);
+ float cosNO = dot(N, I);
+ float cosNI = dot(N, omega_in);
if(cosNI > 0 && cosNO > 0) {
// get half vector
float3 Hr = normalize(omega_in + I);
// eq. 20: (F*G*D)/(4*in*on)
// eq. 33: first we calculate D(m) with m=Hr:
float alpha2 = m_ag * m_ag;
- float cosThetaM = dot(m_N, Hr);
+ float cosThetaM = dot(N, Hr);
float cosThetaM2 = cosThetaM * cosThetaM;
float tanThetaM2 = (1 - cosThetaM2) / cosThetaM2;
float cosThetaM4 = cosThetaM2 * cosThetaM2;
@@ -108,16 +112,16 @@ __device float3 bsdf_microfacet_ggx_eval_reflect(const ShaderData *sd, const Sha
return make_float3 (0, 0, 0);
}
-__device float3 bsdf_microfacet_ggx_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_microfacet_ggx_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
float m_ag = sc->data0;
float m_eta = sc->data1;
int m_refractive = sc->type == CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID;
- float3 m_N = sd->N;
+ float3 N = sc->N;
if(!m_refractive) return make_float3 (0, 0, 0);
- float cosNO = dot(m_N, I);
- float cosNI = dot(m_N, omega_in);
+ float cosNO = dot(N, I);
+ float cosNI = dot(N, omega_in);
if(cosNO <= 0 || cosNI >= 0)
return make_float3 (0, 0, 0); // vectors on same side -- not possible
// compute half-vector of the refraction (eq. 16)
@@ -128,7 +132,7 @@ __device float3 bsdf_microfacet_ggx_eval_transmit(const ShaderData *sd, const Sh
float cosHI = dot(Ht, omega_in);
// eq. 33: first we calculate D(m) with m=Ht:
float alpha2 = m_ag * m_ag;
- float cosThetaM = dot(m_N, Ht);
+ float cosThetaM = dot(N, Ht);
float cosThetaM2 = cosThetaM * cosThetaM;
float tanThetaM2 = (1 - cosThetaM2) / cosThetaM2;
float cosThetaM4 = cosThetaM2 * cosThetaM2;
@@ -144,21 +148,15 @@ __device float3 bsdf_microfacet_ggx_eval_transmit(const ShaderData *sd, const Sh
return make_float3 (out, out, out);
}
-__device float bsdf_microfacet_ggx_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
-{
- return 1.0f;
-}
-
-__device int bsdf_microfacet_ggx_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_microfacet_ggx_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
float m_ag = sc->data0;
- float m_eta = sc->data1;
int m_refractive = sc->type == CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID;
- float3 m_N = sd->N;
+ float3 N = sc->N;
- float cosNO = dot(m_N, sd->I);
+ float cosNO = dot(N, I);
if(cosNO > 0) {
- float3 X, Y, Z = m_N;
+ float3 X, Y, Z = N;
make_orthonormals(Z, &X, &Y);
// generate a random microfacet normal m
// eq. 35,36:
@@ -173,11 +171,11 @@ __device int bsdf_microfacet_ggx_sample(const ShaderData *sd, const ShaderClosur
(sinf(phiM) * sinThetaM) * Y +
cosThetaM * Z;
if(!m_refractive) {
- float cosMO = dot(m, sd->I);
+ float cosMO = dot(m, I);
if(cosMO > 0) {
// eq. 39 - compute actual reflected direction
- *omega_in = 2 * cosMO * m - sd->I;
- if(dot(sd->Ng, *omega_in) > 0) {
+ *omega_in = 2 * cosMO * m - I;
+ if(dot(Ng, *omega_in) > 0) {
// microfacet normal is visible to this ray
// eq. 33
float cosThetaM2 = cosThetaM * cosThetaM;
@@ -190,7 +188,7 @@ __device int bsdf_microfacet_ggx_sample(const ShaderData *sd, const ShaderClosur
// eq. 17 in http://www.graphics.cornell.edu/~bjw/wardnotes.pdf
*pdf = pm * 0.25f / cosMO;
// eval BRDF*cosNI
- float cosNI = dot(m_N, *omega_in);
+ float cosNI = dot(N, *omega_in);
// eq. 34: now calculate G1(i,m) and G1(o,m)
float G1o = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNO * cosNO) / (cosNO * cosNO)));
float G1i = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI)));
@@ -199,8 +197,8 @@ __device int bsdf_microfacet_ggx_sample(const ShaderData *sd, const ShaderClosur
float out = (G * D) * 0.25f / cosNO;
*eval = make_float3(out, out, out);
#ifdef __RAY_DIFFERENTIALS__
- *domega_in_dx = (2 * dot(m, sd->dI.dx)) * m - sd->dI.dx;
- *domega_in_dy = (2 * dot(m, sd->dI.dy)) * m - sd->dI.dy;
+ *domega_in_dx = (2 * dot(m, dIdx)) * m - dIdx;
+ *domega_in_dy = (2 * dot(m, dIdy)) * m - dIdy;
// Since there is some blur to this reflection, make the
// derivatives a bit bigger. In theory this varies with the
// roughness but the exact relationship is complex and
@@ -210,17 +208,19 @@ __device int bsdf_microfacet_ggx_sample(const ShaderData *sd, const ShaderClosur
#endif
}
}
- } else {
+ }
+ else {
// CAUTION: the i and o variables are inverted relative to the paper
// eq. 39 - compute actual refractive direction
float3 R, T;
#ifdef __RAY_DIFFERENTIALS__
float3 dRdx, dRdy, dTdx, dTdy;
#endif
+ float m_eta = sc->data1;
bool inside;
- fresnel_dielectric(m_eta, m, sd->I, &R, &T,
+ fresnel_dielectric(m_eta, m, I, &R, &T,
#ifdef __RAY_DIFFERENTIALS__
- sd->dI.dx, sd->dI.dy, &dRdx, &dRdy, &dTdx, &dTdy,
+ dIdx, dIdy, &dRdx, &dRdy, &dTdx, &dTdy,
#endif
&inside);
@@ -237,14 +237,14 @@ __device int bsdf_microfacet_ggx_sample(const ShaderData *sd, const ShaderClosur
// eq. 24
float pm = D * cosThetaM;
// eval BRDF*cosNI
- float cosNI = dot(m_N, *omega_in);
+ float cosNI = dot(N, *omega_in);
// eq. 34: now calculate G1(i,m) and G1(o,m)
float G1o = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNO * cosNO) / (cosNO * cosNO)));
float G1i = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI)));
float G = G1o * G1i;
// eq. 21
float cosHI = dot(m, *omega_in);
- float cosHO = dot(m, sd->I);
+ float cosHO = dot(m, I);
float Ht2 = m_eta * cosHI + cosHO;
Ht2 *= Ht2;
float out = (fabsf(cosHI * cosHO) * (m_eta * m_eta) * (G * D)) / (cosNO * Ht2);
@@ -267,26 +267,29 @@ __device int bsdf_microfacet_ggx_sample(const ShaderData *sd, const ShaderClosur
/* BECKMANN */
-typedef struct BsdfMicrofacetBeckmannClosure {
- //float3 m_N;
- float m_ab;
- float m_eta;
-} BsdfMicrofacetBeckmannClosure;
+__device int bsdf_microfacet_beckmann_setup(ShaderClosure *sc)
+{
+ float ab = sc->data0;
+ float m_ab = clamp(ab, 1e-4f, 1.0f);
+
+ sc->data0 = m_ab;
+
+ sc->type = CLOSURE_BSDF_MICROFACET_BECKMANN_ID;
+ return SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
+}
-__device void bsdf_microfacet_beckmann_setup(ShaderData *sd, ShaderClosure *sc, float ab, float eta, bool refractive)
+__device int bsdf_microfacet_beckmann_refraction_setup(ShaderClosure *sc)
{
+ float ab = sc->data0;
+ float eta = sc->data1;
float m_ab = clamp(ab, 1e-4f, 1.0f);
float m_eta = eta;
sc->data0 = m_ab;
sc->data1 = m_eta;
- if(refractive)
- sc->type = CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID;
- else
- sc->type = CLOSURE_BSDF_MICROFACET_BECKMANN_ID;
-
- sd->flag |= SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
+ sc->type = CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID;
+ return SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
}
__device void bsdf_microfacet_beckmann_blur(ShaderClosure *sc, float roughness)
@@ -296,23 +299,22 @@ __device void bsdf_microfacet_beckmann_blur(ShaderClosure *sc, float roughness)
sc->data0 = m_ab;
}
-__device float3 bsdf_microfacet_beckmann_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_microfacet_beckmann_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
float m_ab = sc->data0;
- //float m_eta = sc->data1;
int m_refractive = sc->type == CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID;
- float3 m_N = sd->N;
+ float3 N = sc->N;
if(m_refractive) return make_float3 (0, 0, 0);
- float cosNO = dot(m_N, I);
- float cosNI = dot(m_N, omega_in);
+ float cosNO = dot(N, I);
+ float cosNI = dot(N, omega_in);
if(cosNO > 0 && cosNI > 0) {
// get half vector
float3 Hr = normalize(omega_in + I);
// eq. 20: (F*G*D)/(4*in*on)
// eq. 25: first we calculate D(m) with m=Hr:
float alpha2 = m_ab * m_ab;
- float cosThetaM = dot(m_N, Hr);
+ float cosThetaM = dot(N, Hr);
float cosThetaM2 = cosThetaM * cosThetaM;
float tanThetaM2 = (1 - cosThetaM2) / cosThetaM2;
float cosThetaM4 = cosThetaM2 * cosThetaM2;
@@ -335,16 +337,16 @@ __device float3 bsdf_microfacet_beckmann_eval_reflect(const ShaderData *sd, cons
return make_float3 (0, 0, 0);
}
-__device float3 bsdf_microfacet_beckmann_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_microfacet_beckmann_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
float m_ab = sc->data0;
float m_eta = sc->data1;
int m_refractive = sc->type == CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID;
- float3 m_N = sd->N;
+ float3 N = sc->N;
if(!m_refractive) return make_float3 (0, 0, 0);
- float cosNO = dot(m_N, I);
- float cosNI = dot(m_N, omega_in);
+ float cosNO = dot(N, I);
+ float cosNI = dot(N, omega_in);
if(cosNO <= 0 || cosNI >= 0)
return make_float3 (0, 0, 0);
// compute half-vector of the refraction (eq. 16)
@@ -355,7 +357,7 @@ __device float3 bsdf_microfacet_beckmann_eval_transmit(const ShaderData *sd, con
float cosHI = dot(Ht, omega_in);
// eq. 33: first we calculate D(m) with m=Ht:
float alpha2 = m_ab * m_ab;
- float cosThetaM = dot(m_N, Ht);
+ float cosThetaM = dot(N, Ht);
float cosThetaM2 = cosThetaM * cosThetaM;
float tanThetaM2 = (1 - cosThetaM2) / cosThetaM2;
float cosThetaM4 = cosThetaM2 * cosThetaM2;
@@ -373,21 +375,15 @@ __device float3 bsdf_microfacet_beckmann_eval_transmit(const ShaderData *sd, con
return make_float3 (out, out, out);
}
-__device float bsdf_microfacet_beckmann_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
-{
- return 1.0f;
-}
-
-__device int bsdf_microfacet_beckmann_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_microfacet_beckmann_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
float m_ab = sc->data0;
- float m_eta = sc->data1;
int m_refractive = sc->type == CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID;
- float3 m_N = sd->N;
+ float3 N = sc->N;
- float cosNO = dot(m_N, sd->I);
+ float cosNO = dot(N, I);
if(cosNO > 0) {
- float3 X, Y, Z = m_N;
+ float3 X, Y, Z = N;
make_orthonormals(Z, &X, &Y);
// generate a random microfacet normal m
// eq. 35,36:
@@ -403,11 +399,11 @@ __device int bsdf_microfacet_beckmann_sample(const ShaderData *sd, const ShaderC
cosThetaM * Z;
if(!m_refractive) {
- float cosMO = dot(m, sd->I);
+ float cosMO = dot(m, I);
if(cosMO > 0) {
// eq. 39 - compute actual reflected direction
- *omega_in = 2 * cosMO * m - sd->I;
- if(dot(sd->Ng, *omega_in) > 0) {
+ *omega_in = 2 * cosMO * m - I;
+ if(dot(Ng, *omega_in) > 0) {
// microfacet normal is visible to this ray
// eq. 25
float cosThetaM2 = cosThetaM * cosThetaM;
@@ -421,7 +417,7 @@ __device int bsdf_microfacet_beckmann_sample(const ShaderData *sd, const ShaderC
// eq. 17 in http://www.graphics.cornell.edu/~bjw/wardnotes.pdf
*pdf = pm * 0.25f / cosMO;
// Eval BRDF*cosNI
- float cosNI = dot(m_N, *omega_in);
+ float cosNI = dot(N, *omega_in);
// eq. 26, 27: now calculate G1(i,m) and G1(o,m)
float ao = 1 / (m_ab * safe_sqrtf((1 - cosNO * cosNO) / (cosNO * cosNO)));
float ai = 1 / (m_ab * safe_sqrtf((1 - cosNI * cosNI) / (cosNI * cosNI)));
@@ -432,8 +428,8 @@ __device int bsdf_microfacet_beckmann_sample(const ShaderData *sd, const ShaderC
float out = (G * D) * 0.25f / cosNO;
*eval = make_float3(out, out, out);
#ifdef __RAY_DIFFERENTIALS__
- *domega_in_dx = (2 * dot(m, sd->dI.dx)) * m - sd->dI.dx;
- *domega_in_dy = (2 * dot(m, sd->dI.dy)) * m - sd->dI.dy;
+ *domega_in_dx = (2 * dot(m, dIdx)) * m - dIdx;
+ *domega_in_dy = (2 * dot(m, dIdy)) * m - dIdy;
// Since there is some blur to this reflection, make the
// derivatives a bit bigger. In theory this varies with the
// roughness but the exact relationship is complex and
@@ -443,17 +439,19 @@ __device int bsdf_microfacet_beckmann_sample(const ShaderData *sd, const ShaderC
#endif
}
}
- } else {
+ }
+ else {
// CAUTION: the i and o variables are inverted relative to the paper
// eq. 39 - compute actual refractive direction
float3 R, T;
#ifdef __RAY_DIFFERENTIALS__
float3 dRdx, dRdy, dTdx, dTdy;
#endif
+ float m_eta = sc->data1;
bool inside;
- fresnel_dielectric(m_eta, m, sd->I, &R, &T,
+ fresnel_dielectric(m_eta, m, I, &R, &T,
#ifdef __RAY_DIFFERENTIALS__
- sd->dI.dx, sd->dI.dy, &dRdx, &dRdy, &dTdx, &dTdy,
+ dIdx, dIdy, &dRdx, &dRdy, &dTdx, &dTdy,
#endif
&inside);
@@ -472,7 +470,7 @@ __device int bsdf_microfacet_beckmann_sample(const ShaderData *sd, const ShaderC
// eq. 24
float pm = D * cosThetaM;
// eval BRDF*cosNI
- float cosNI = dot(m_N, *omega_in);
+ float cosNI = dot(N, *omega_in);
// eq. 26, 27: now calculate G1(i,m) and G1(o,m)
float ao = 1 / (m_ab * safe_sqrtf((1 - cosNO * cosNO) / (cosNO * cosNO)));
float ai = 1 / (m_ab * safe_sqrtf((1 - cosNI * cosNI) / (cosNI * cosNI)));
@@ -481,7 +479,7 @@ __device int bsdf_microfacet_beckmann_sample(const ShaderData *sd, const ShaderC
float G = G1o * G1i;
// eq. 21
float cosHI = dot(m, *omega_in);
- float cosHO = dot(m, sd->I);
+ float cosHO = dot(m, I);
float Ht2 = m_eta * cosHI + cosHO;
Ht2 *= Ht2;
float out = (fabsf(cosHI * cosHO) * (m_eta * m_eta) * (G * D)) / (cosNO * Ht2);
diff --git a/intern/cycles/kernel/svm/bsdf_oren_nayar.h b/intern/cycles/kernel/closure/bsdf_oren_nayar.h
index a7edccdc423..066937da6eb 100644
--- a/intern/cycles/kernel/svm/bsdf_oren_nayar.h
+++ b/intern/cycles/kernel/closure/bsdf_oren_nayar.h
@@ -21,11 +21,6 @@
CCL_NAMESPACE_BEGIN
-typedef struct BsdfOrenNayarClosure {
- float m_a;
- float m_b;
-} BsdfOrenNayarClosure;
-
__device float3 bsdf_oren_nayar_get_intensity(const ShaderClosure *sc, float3 n, float3 v, float3 l)
{
float nl = max(dot(n, l), 0.0f);
@@ -38,10 +33,11 @@ __device float3 bsdf_oren_nayar_get_intensity(const ShaderClosure *sc, float3 n,
return make_float3(is, is, is);
}
-__device void bsdf_oren_nayar_setup(ShaderData *sd, ShaderClosure *sc, float sigma)
+__device int bsdf_oren_nayar_setup(ShaderClosure *sc)
{
+ float sigma = sc->data0;
+
sc->type = CLOSURE_BSDF_OREN_NAYAR_ID;
- sd->flag |= SD_BSDF | SD_BSDF_HAS_EVAL;
sigma = clamp(sigma, 0.0f, 1.0f);
@@ -49,17 +45,19 @@ __device void bsdf_oren_nayar_setup(ShaderData *sd, ShaderClosure *sc, float sig
sc->data0 = 1.0f * div;
sc->data1 = sigma * div;
+
+ return SD_BSDF | SD_BSDF_HAS_EVAL;
}
__device void bsdf_oren_nayar_blur(ShaderClosure *sc, float roughness)
{
}
-__device float3 bsdf_oren_nayar_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_oren_nayar_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
- if (dot(sd->N, omega_in) > 0.0f) {
+ if (dot(sc->N, omega_in) > 0.0f) {
*pdf = 0.5f * M_1_PI_F;
- return bsdf_oren_nayar_get_intensity(sc, sd->N, I, omega_in);
+ return bsdf_oren_nayar_get_intensity(sc, sc->N, I, omega_in);
}
else {
*pdf = 0.0f;
@@ -67,27 +65,22 @@ __device float3 bsdf_oren_nayar_eval_reflect(const ShaderData *sd, const ShaderC
}
}
-__device float3 bsdf_oren_nayar_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_oren_nayar_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float bsdf_oren_nayar_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
-{
- return 1.0f;
-}
-
-__device int bsdf_oren_nayar_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_oren_nayar_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
- sample_uniform_hemisphere(sd->N, randu, randv, omega_in, pdf);
+ sample_uniform_hemisphere(sc->N, randu, randv, omega_in, pdf);
- if (dot(sd->Ng, *omega_in) > 0.0f) {
- *eval = bsdf_oren_nayar_get_intensity(sc, sd->N, sd->I, *omega_in);
+ if (dot(Ng, *omega_in) > 0.0f) {
+ *eval = bsdf_oren_nayar_get_intensity(sc, sc->N, I, *omega_in);
#ifdef __RAY_DIFFERENTIALS__
// TODO: find a better approximation for the bounce
- *domega_in_dx = (2.0f * dot(sd->N, sd->dI.dx)) * sd->N - sd->dI.dx;
- *domega_in_dy = (2.0f * dot(sd->N, sd->dI.dy)) * sd->N - sd->dI.dy;
+ *domega_in_dx = (2.0f * dot(sc->N, dIdx)) * sc->N - dIdx;
+ *domega_in_dy = (2.0f * dot(sc->N, dIdy)) * sc->N - dIdy;
*domega_in_dx *= 125.0f;
*domega_in_dy *= 125.0f;
#endif
diff --git a/intern/cycles/kernel/svm/bsdf_reflection.h b/intern/cycles/kernel/closure/bsdf_reflection.h
index 09b4e0e48f0..9356f950d98 100644
--- a/intern/cycles/kernel/svm/bsdf_reflection.h
+++ b/intern/cycles/kernel/closure/bsdf_reflection.h
@@ -37,48 +37,39 @@ CCL_NAMESPACE_BEGIN
/* REFLECTION */
-typedef struct BsdfReflectionClosure {
- //float3 m_N;
-} BsdfReflectionClosure;
-
-__device void bsdf_reflection_setup(ShaderData *sd, ShaderClosure *sc)
+__device int bsdf_reflection_setup(ShaderClosure *sc)
{
sc->type = CLOSURE_BSDF_REFLECTION_ID;
- sd->flag |= SD_BSDF;
+ return SD_BSDF;
}
__device void bsdf_reflection_blur(ShaderClosure *sc, float roughness)
{
}
-__device float3 bsdf_reflection_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_reflection_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float3 bsdf_reflection_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_reflection_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float bsdf_reflection_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
-{
- return 1.0f;
-}
-
-__device int bsdf_reflection_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_reflection_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
//const BsdfReflectionClosure *self = (const BsdfReflectionClosure*)sc->data;
- float3 m_N = sd->N;
+ float3 N = sc->N;
// only one direction is possible
- float cosNO = dot(m_N, sd->I);
+ float cosNO = dot(N, I);
if(cosNO > 0) {
- *omega_in = (2 * cosNO) * m_N - sd->I;
- if(dot(sd->Ng, *omega_in) > 0) {
+ *omega_in = (2 * cosNO) * N - I;
+ if(dot(Ng, *omega_in) > 0) {
#ifdef __RAY_DIFFERENTIALS__
- *domega_in_dx = 2 * dot(m_N, sd->dI.dx) * m_N - sd->dI.dx;
- *domega_in_dy = 2 * dot(m_N, sd->dI.dy) * m_N - sd->dI.dy;
+ *domega_in_dx = 2 * dot(N, dIdx) * N - dIdx;
+ *domega_in_dy = 2 * dot(N, dIdy) * N - dIdy;
#endif
*pdf = 1;
*eval = make_float3(1, 1, 1);
diff --git a/intern/cycles/kernel/svm/bsdf_refraction.h b/intern/cycles/kernel/closure/bsdf_refraction.h
index c9c268999c0..ef79d6cc259 100644
--- a/intern/cycles/kernel/svm/bsdf_refraction.h
+++ b/intern/cycles/kernel/closure/bsdf_refraction.h
@@ -37,50 +37,39 @@ CCL_NAMESPACE_BEGIN
/* REFRACTION */
-typedef struct BsdfRefractionClosure {
- float m_eta;
-} BsdfRefractionClosure;
-
-__device void bsdf_refraction_setup(ShaderData *sd, ShaderClosure *sc, float eta)
+__device int bsdf_refraction_setup(ShaderClosure *sc)
{
- sc->data0 = eta;
-
sc->type = CLOSURE_BSDF_REFRACTION_ID;
- sd->flag |= SD_BSDF;
+ return SD_BSDF;
}
__device void bsdf_refraction_blur(ShaderClosure *sc, float roughness)
{
}
-__device float3 bsdf_refraction_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_refraction_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float3 bsdf_refraction_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_refraction_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float bsdf_refraction_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
-{
- return 1.0f;
-}
-
-__device int bsdf_refraction_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_refraction_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
float m_eta = sc->data0;
- float3 m_N = sd->N;
+ float3 N = sc->N;
float3 R, T;
#ifdef __RAY_DIFFERENTIALS__
float3 dRdx, dRdy, dTdx, dTdy;
#endif
bool inside;
- fresnel_dielectric(m_eta, m_N, sd->I, &R, &T,
+ fresnel_dielectric(m_eta, N, I, &R, &T,
#ifdef __RAY_DIFFERENTIALS__
- sd->dI.dx, sd->dI.dy, &dRdx, &dRdy, &dTdx, &dTdy,
+ dIdx, dIdy, &dRdx, &dRdy, &dTdx, &dTdy,
#endif
&inside);
diff --git a/intern/cycles/kernel/svm/bsdf_transparent.h b/intern/cycles/kernel/closure/bsdf_transparent.h
index 511836cdfa2..81bc7690b50 100644
--- a/intern/cycles/kernel/svm/bsdf_transparent.h
+++ b/intern/cycles/kernel/closure/bsdf_transparent.h
@@ -35,38 +35,33 @@
CCL_NAMESPACE_BEGIN
-__device void bsdf_transparent_setup(ShaderData *sd, ShaderClosure *sc)
+__device int bsdf_transparent_setup(ShaderClosure *sc)
{
sc->type = CLOSURE_BSDF_TRANSPARENT_ID;
- sd->flag |= SD_BSDF;
+ return SD_BSDF;
}
__device void bsdf_transparent_blur(ShaderClosure *sc, float roughness)
{
}
-__device float3 bsdf_transparent_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_transparent_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float3 bsdf_transparent_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_transparent_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float bsdf_transparent_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
-{
- return 1.0f;
-}
-
-__device int bsdf_transparent_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_transparent_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
// only one direction is possible
- *omega_in = -sd->I;
+ *omega_in = -I;
#ifdef __RAY_DIFFERENTIALS__
- *domega_in_dx = -sd->dI.dx;
- *domega_in_dy = -sd->dI.dy;
+ *domega_in_dx = -dIdx;
+ *domega_in_dy = -dIdy;
#endif
*pdf = 1;
*eval = make_float3(1, 1, 1);
diff --git a/intern/cycles/kernel/svm/bsdf_ward.h b/intern/cycles/kernel/closure/bsdf_ward.h
index 86bca69425d..9c81548a2c3 100644
--- a/intern/cycles/kernel/svm/bsdf_ward.h
+++ b/intern/cycles/kernel/closure/bsdf_ward.h
@@ -37,23 +37,19 @@ CCL_NAMESPACE_BEGIN
/* WARD */
-typedef struct BsdfWardClosure {
- //float3 m_N;
- //float3 m_T;
- float m_ax;
- float m_ay;
-} BsdfWardClosure;
-
-__device void bsdf_ward_setup(ShaderData *sd, ShaderClosure *sc, float3 T, float ax, float ay)
+__device int bsdf_ward_setup(ShaderClosure *sc)
{
- float m_ax = clamp(ax, 1e-5f, 1.0f);
- float m_ay = clamp(ay, 1e-5f, 1.0f);
+ float ax = sc->data0;
+ float ay = sc->data1;
+
+ float m_ax = clamp(ax, 1e-4f, 1.0f);
+ float m_ay = clamp(ay, 1e-4f, 1.0f);
sc->data0 = m_ax;
sc->data1 = m_ay;
sc->type = CLOSURE_BSDF_WARD_ID;
- sd->flag |= SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
+ return SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
}
__device void bsdf_ward_blur(ShaderClosure *sc, float roughness)
@@ -62,25 +58,25 @@ __device void bsdf_ward_blur(ShaderClosure *sc, float roughness)
sc->data1 = fmaxf(roughness, sc->data1);
}
-__device float3 bsdf_ward_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_ward_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
float m_ax = sc->data0;
float m_ay = sc->data1;
- float3 m_N = sd->N;
- float3 m_T = normalize(sd->dPdu);
+ float3 N = sc->N;
+ float3 T = sc->T;
- float cosNO = dot(m_N, I);
- float cosNI = dot(m_N, omega_in);
+ float cosNO = dot(N, I);
+ float cosNI = dot(N, omega_in);
if(cosNI > 0 && cosNO > 0) {
// get half vector and get x,y basis on the surface for anisotropy
float3 H = normalize(omega_in + I); // normalize needed for pdf
float3 X, Y;
- make_orthonormals_tangent(m_N, m_T, &X, &Y);
+ make_orthonormals_tangent(N, T, &X, &Y);
// eq. 4
float dotx = dot(H, X) / m_ax;
float doty = dot(H, Y) / m_ay;
- float dotn = dot(H, m_N);
+ float dotn = dot(H, N);
float exp_arg = (dotx * dotx + doty * doty) / (dotn * dotn);
float denom = (4 * M_PI_F * m_ax * m_ay * sqrtf(cosNO * cosNI));
float exp_val = expf(-exp_arg);
@@ -90,31 +86,27 @@ __device float3 bsdf_ward_eval_reflect(const ShaderData *sd, const ShaderClosure
*pdf = exp_val / denom;
return make_float3 (out, out, out);
}
+
return make_float3 (0, 0, 0);
}
-__device float3 bsdf_ward_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_ward_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float bsdf_ward_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
-{
- return 1.0f;
-}
-
-__device int bsdf_ward_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_ward_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
float m_ax = sc->data0;
float m_ay = sc->data1;
- float3 m_N = sd->N;
- float3 m_T = normalize(sd->dPdu);
+ float3 N = sc->N;
+ float3 T = sc->T;
- float cosNO = dot(m_N, sd->I);
+ float cosNO = dot(N, I);
if(cosNO > 0) {
// get x,y basis on the surface for anisotropy
float3 X, Y;
- make_orthonormals_tangent(m_N, m_T, &X, &Y);
+ make_orthonormals_tangent(N, T, &X, &Y);
// generate random angles for the half vector
// eq. 7 (taking care around discontinuities to keep
//ttoutput angle in the right quadrant)
@@ -127,19 +119,22 @@ __device int bsdf_ward_sample(const ShaderData *sd, const ShaderClosure *sc, flo
float tanPhi = alphaRatio * tanf(M_PI_2_F * val);
cosPhi = 1 / sqrtf(1 + tanPhi * tanPhi);
sinPhi = tanPhi * cosPhi;
- } else if(randu < 0.5f) {
+ }
+ else if(randu < 0.5f) {
float val = 1 - 4 * (0.5f - randu);
float tanPhi = alphaRatio * tanf(M_PI_2_F * val);
// phi = M_PI_F - phi;
cosPhi = -1 / sqrtf(1 + tanPhi * tanPhi);
sinPhi = -tanPhi * cosPhi;
- } else if(randu < 0.75f) {
+ }
+ else if(randu < 0.75f) {
float val = 4 * (randu - 0.5f);
float tanPhi = alphaRatio * tanf(M_PI_2_F * val);
//phi = M_PI_F + phi;
cosPhi = -1 / sqrtf(1 + tanPhi * tanPhi);
sinPhi = tanPhi * cosPhi;
- } else {
+ }
+ else {
float val = 1 - 4 * (1 - randu);
float tanPhi = alphaRatio * tanf(M_PI_2_F * val);
// phi = 2 * M_PI_F - phi;
@@ -163,12 +158,12 @@ __device int bsdf_ward_sample(const ShaderData *sd, const ShaderClosure *sc, flo
float doty = h.y / m_ay;
float dotn = h.z;
// transform to world space
- h = h.x * X + h.y * Y + h.z * m_N;
+ h = h.x * X + h.y * Y + h.z * N;
// generate the final sample
- float oh = dot(h, sd->I);
- *omega_in = 2.0f * oh * h - sd->I;
- if(dot(sd->Ng, *omega_in) > 0) {
- float cosNI = dot(m_N, *omega_in);
+ float oh = dot(h, I);
+ *omega_in = 2.0f * oh * h - I;
+ if(dot(Ng, *omega_in) > 0) {
+ float cosNI = dot(N, *omega_in);
if(cosNI > 0) {
// eq. 9
float exp_arg = (dotx * dotx + doty * doty) / (dotn * dotn);
@@ -179,8 +174,8 @@ __device int bsdf_ward_sample(const ShaderData *sd, const ShaderClosure *sc, flo
float power = cosNI * expf(-exp_arg) / denom;
*eval = make_float3(power, power, power);
#ifdef __RAY_DIFFERENTIALS__
- *domega_in_dx = (2 * dot(m_N, sd->dI.dx)) * m_N - sd->dI.dx;
- *domega_in_dy = (2 * dot(m_N, sd->dI.dy)) * m_N - sd->dI.dy;
+ *domega_in_dx = (2 * dot(N, dIdx)) * N - dIdx;
+ *domega_in_dy = (2 * dot(N, dIdy)) * N - dIdy;
// Since there is some blur to this reflection, make the
// derivatives a bit bigger. In theory this varies with the
// roughness but the exact relationship is complex and
diff --git a/intern/cycles/kernel/svm/bsdf_westin.h b/intern/cycles/kernel/closure/bsdf_westin.h
index 6193d81c244..968173208b4 100644
--- a/intern/cycles/kernel/svm/bsdf_westin.h
+++ b/intern/cycles/kernel/closure/bsdf_westin.h
@@ -37,19 +37,16 @@ CCL_NAMESPACE_BEGIN
/* WESTIN BACKSCATTER */
-typedef struct BsdfWestinBackscatterClosure {
- //float3 m_N;
- float m_invroughness;
-} BsdfWestinBackscatterClosure;
-
-__device void bsdf_westin_backscatter_setup(ShaderData *sd, ShaderClosure *sc, float roughness)
+__device int bsdf_westin_backscatter_setup(ShaderClosure *sc)
{
+ float roughness = sc->data0;
roughness = clamp(roughness, 1e-5f, 1.0f);
float m_invroughness = 1.0f/roughness;
sc->type = CLOSURE_BSDF_WESTIN_BACKSCATTER_ID;
- sd->flag |= SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
sc->data0 = m_invroughness;
+
+ return SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
}
__device void bsdf_westin_backscatter_blur(ShaderClosure *sc, float roughness)
@@ -59,14 +56,14 @@ __device void bsdf_westin_backscatter_blur(ShaderClosure *sc, float roughness)
sc->data0 = m_invroughness;
}
-__device float3 bsdf_westin_backscatter_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_westin_backscatter_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
float m_invroughness = sc->data0;
- float3 m_N = sd->N;
+ float3 N = sc->N;
// pdf is implicitly 0 (no indirect sampling)
- float cosNO = dot(m_N, I);
- float cosNI = dot(m_N, omega_in);
+ float cosNO = dot(N, I);
+ float cosNI = dot(N, omega_in);
if(cosNO > 0 && cosNI > 0) {
float cosine = dot(I, omega_in);
*pdf = cosine > 0 ? (m_invroughness + 1) * powf(cosine, m_invroughness) : 0;
@@ -76,40 +73,35 @@ __device float3 bsdf_westin_backscatter_eval_reflect(const ShaderData *sd, const
return make_float3 (0, 0, 0);
}
-__device float3 bsdf_westin_backscatter_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_westin_backscatter_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float bsdf_westin_backscatter_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
-{
- return 1.0f;
-}
-
-__device int bsdf_westin_backscatter_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_westin_backscatter_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
float m_invroughness = sc->data0;
- float3 m_N = sd->N;
+ float3 N = sc->N;
- float cosNO = dot(m_N, sd->I);
+ float cosNO = dot(N, I);
if(cosNO > 0) {
#ifdef __RAY_DIFFERENTIALS__
- *domega_in_dx = sd->dI.dx;
- *domega_in_dy = sd->dI.dy;
+ *domega_in_dx = dIdx;
+ *domega_in_dy = dIdy;
#endif
float3 T, B;
- make_orthonormals (sd->I, &T, &B);
+ make_orthonormals (I, &T, &B);
float phi = 2 * M_PI_F * randu;
float cosTheta = powf(randv, 1 / (m_invroughness + 1));
float sinTheta2 = 1 - cosTheta * cosTheta;
float sinTheta = sinTheta2 > 0 ? sqrtf(sinTheta2) : 0;
*omega_in = (cosf(phi) * sinTheta) * T +
(sinf(phi) * sinTheta) * B +
- (cosTheta) * sd->I;
- if(dot(sd->Ng, *omega_in) > 0)
+ (cosTheta) * I;
+ if(dot(Ng, *omega_in) > 0)
{
// common terms for pdf and eval
- float cosNI = dot(m_N, *omega_in);
+ float cosNI = dot(N, *omega_in);
// make sure the direction we chose is still in the right hemisphere
if(cosNI > 0)
{
@@ -132,30 +124,26 @@ __device int bsdf_westin_backscatter_sample(const ShaderData *sd, const ShaderCl
/* WESTIN SHEEN */
-typedef struct BsdfWestinSheenClosure {
- //float3 m_N;
- float m_edginess;
-} BsdfWestinSheenClosure;
-
-__device void bsdf_westin_sheen_setup(ShaderData *sd, ShaderClosure *sc, float edginess)
+__device int bsdf_westin_sheen_setup(ShaderClosure *sc)
{
+ float edginess = sc->data0;
sc->type = CLOSURE_BSDF_WESTIN_SHEEN_ID;
- sd->flag |= SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
sc->data0 = edginess;
+ return SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_GLOSSY;
}
__device void bsdf_westin_sheen_blur(ShaderClosure *sc, float roughness)
{
}
-__device float3 bsdf_westin_sheen_eval_reflect(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_westin_sheen_eval_reflect(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
float m_edginess = sc->data0;
- float3 m_N = sd->N;
+ float3 N = sc->N;
// pdf is implicitly 0 (no indirect sampling)
- float cosNO = dot(m_N, I);
- float cosNI = dot(m_N, omega_in);
+ float cosNO = dot(N, I);
+ float cosNI = dot(N, omega_in);
if(cosNO > 0 && cosNI > 0) {
float sinNO2 = 1 - cosNO * cosNO;
*pdf = cosNI * M_1_PI_F;
@@ -165,39 +153,36 @@ __device float3 bsdf_westin_sheen_eval_reflect(const ShaderData *sd, const Shade
return make_float3 (0, 0, 0);
}
-__device float3 bsdf_westin_sheen_eval_transmit(const ShaderData *sd, const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
+__device float3 bsdf_westin_sheen_eval_transmit(const ShaderClosure *sc, const float3 I, const float3 omega_in, float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
-__device float bsdf_westin_sheen_albedo(const ShaderData *sd, const ShaderClosure *sc, const float3 I)
-{
- return 1.0f;
-}
-
-__device int bsdf_westin_sheen_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
+__device int bsdf_westin_sheen_sample(const ShaderClosure *sc, float3 Ng, float3 I, float3 dIdx, float3 dIdy, float randu, float randv, float3 *eval, float3 *omega_in, float3 *domega_in_dx, float3 *domega_in_dy, float *pdf)
{
float m_edginess = sc->data0;
- float3 m_N = sd->N;
+ float3 N = sc->N;
// we are viewing the surface from the right side - send a ray out with cosine
// distribution over the hemisphere
- sample_cos_hemisphere(m_N, randu, randv, omega_in, pdf);
- if(dot(sd->Ng, *omega_in) > 0) {
+ sample_cos_hemisphere(N, randu, randv, omega_in, pdf);
+ if(dot(Ng, *omega_in) > 0) {
// TODO: account for sheen when sampling
- float cosNO = dot(m_N, sd->I);
+ float cosNO = dot(N, I);
float sinNO2 = 1 - cosNO * cosNO;
float westin = sinNO2 > 0 ? powf(sinNO2, 0.5f * m_edginess) * (*pdf) : 0;
*eval = make_float3(westin, westin, westin);
#ifdef __RAY_DIFFERENTIALS__
// TODO: find a better approximation for the diffuse bounce
- *domega_in_dx = (2 * dot(m_N, sd->dI.dx)) * m_N - sd->dI.dx;
- *domega_in_dy = (2 * dot(m_N, sd->dI.dy)) * m_N - sd->dI.dy;
+ *domega_in_dx = (2 * dot(N, dIdx)) * N - dIdx;
+ *domega_in_dy = (2 * dot(N, dIdy)) * N - dIdy;
*domega_in_dx *= 125.0f;
*domega_in_dy *= 125.0f;
#endif
- } else
+ }
+ else {
pdf = 0;
+ }
return LABEL_REFLECT|LABEL_DIFFUSE;
}
diff --git a/intern/cycles/kernel/svm/emissive.h b/intern/cycles/kernel/closure/emissive.h
index 9a906f82963..cbf9d9a4efb 100644
--- a/intern/cycles/kernel/svm/emissive.h
+++ b/intern/cycles/kernel/closure/emissive.h
@@ -34,15 +34,21 @@ CCL_NAMESPACE_BEGIN
/* EMISSION CLOSURE */
-/// Return the probability distribution function in the direction I,
-/// given the parameters and the light's surface normal. This MUST match
-/// the PDF computed by sample().
+/* return the probability distribution function in the direction I,
+ * given the parameters and the light's surface normal. This MUST match
+ * the PDF computed by sample(). */
__device float emissive_pdf(const float3 Ng, const float3 I)
{
float cosNO = fabsf(dot(Ng, I));
return (cosNO > 0.0f)? 1.0f: 0.0f;
}
+__device void emissive_sample(const float3 Ng, float randu, float randv,
+ float3 *omega_out, float *pdf)
+{
+ /* todo: not implemented and used yet */
+}
+
__device float3 emissive_eval(const float3 Ng, const float3 I)
{
float res = emissive_pdf(Ng, I);
diff --git a/intern/cycles/kernel/svm/volume.h b/intern/cycles/kernel/closure/volume.h
index 10e9c5de352..734f9111ab6 100644
--- a/intern/cycles/kernel/svm/volume.h
+++ b/intern/cycles/kernel/closure/volume.h
@@ -23,44 +23,46 @@ CCL_NAMESPACE_BEGIN
/* ISOTROPIC VOLUME CLOSURE */
-__device void volume_isotropic_setup(ShaderData *sd, ShaderClosure *sc, float density)
+__device int volume_isotropic_setup(ShaderClosure *sc, float density)
{
sc->type = CLOSURE_VOLUME_ISOTROPIC_ID;
- sd->flag |= SD_VOLUME;
sc->data0 = density;
+
+ return SD_VOLUME;
}
-__device float3 volume_isotropic_eval_phase(const ShaderData *sd, const ShaderClosure *sc, const float3 omega_in, const float3 omega_out)
+__device float3 volume_isotropic_eval_phase(const ShaderClosure *sc, const float3 omega_in, const float3 omega_out)
{
return make_float3(1.0f, 1.0f, 1.0f);
}
/* TRANSPARENT VOLUME CLOSURE */
-__device void volume_transparent_setup(ShaderData *sd, ShaderClosure *sc, float density)
+__device int volume_transparent_setup(ShaderClosure *sc, float density)
{
sc->type = CLOSURE_VOLUME_TRANSPARENT_ID;
- sd->flag |= SD_VOLUME;
sc->data0 = density;
+
+ return SD_VOLUME;
}
-__device float3 volume_transparent_eval_phase(const ShaderData *sd, const ShaderClosure *sc, const float3 omega_in, const float3 omega_out)
+__device float3 volume_transparent_eval_phase(const ShaderClosure *sc, const float3 omega_in, const float3 omega_out)
{
return make_float3(1.0f, 1.0f, 1.0f);
}
/* VOLUME CLOSURE */
-__device float3 volume_eval_phase(const ShaderData *sd, const ShaderClosure *sc, const float3 omega_in, const float3 omega_out)
+__device float3 volume_eval_phase(const ShaderClosure *sc, const float3 omega_in, const float3 omega_out)
{
float3 eval;
switch(sc->type) {
case CLOSURE_VOLUME_ISOTROPIC_ID:
- eval = volume_isotropic_eval_phase(sd, sc, omega_in, omega_out);
+ eval = volume_isotropic_eval_phase(sc, omega_in, omega_out);
break;
case CLOSURE_VOLUME_TRANSPARENT_ID:
- eval = volume_transparent_eval_phase(sd, sc, omega_in, omega_out);
+ eval = volume_transparent_eval_phase(sc, omega_in, omega_out);
break;
default:
eval = make_float3(0.0f, 0.0f, 0.0f);
diff --git a/intern/cycles/kernel/kernel_attribute.h b/intern/cycles/kernel/kernel_attribute.h
index 115de2fdbdb..2774f5e924b 100644
--- a/intern/cycles/kernel/kernel_attribute.h
+++ b/intern/cycles/kernel/kernel_attribute.h
@@ -59,7 +59,7 @@ __device_inline int find_attribute(KernelGlobals *kg, ShaderData *sd, uint id)
attr_map = kernel_tex_fetch(__attributes_map, ++attr_offset);
/* return result */
- return (attr_map.y == ATTR_ELEMENT_NONE) ? (int)ATTR_STD_NOT_FOUND : attr_map.z;
+ return (attr_map.y == ATTR_ELEMENT_NONE) ? (int)ATTR_STD_NOT_FOUND : (int)attr_map.z;
}
}
diff --git a/intern/cycles/kernel/kernel_bvh.h b/intern/cycles/kernel/kernel_bvh.h
index 34a44af8b8d..d70485fd6cf 100644
--- a/intern/cycles/kernel/kernel_bvh.h
+++ b/intern/cycles/kernel/kernel_bvh.h
@@ -57,7 +57,7 @@ __device_inline float3 bvh_inverse_direction(float3 dir)
__device_inline void bvh_instance_push(KernelGlobals *kg, int object, const Ray *ray, float3 *P, float3 *idir, float *t, const float tmax)
{
- Transform tfm = object_fetch_transform(kg, object, ray->time, OBJECT_INVERSE_TRANSFORM);
+ Transform tfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM);
*P = transform_point(&tfm, ray->P);
@@ -75,7 +75,7 @@ __device_inline void bvh_instance_push(KernelGlobals *kg, int object, const Ray
__device_inline void bvh_instance_pop(KernelGlobals *kg, int object, const Ray *ray, float3 *P, float3 *idir, float *t, const float tmax)
{
if(*t != FLT_MAX) {
- Transform tfm = object_fetch_transform(kg, object, ray->time, OBJECT_TRANSFORM);
+ Transform tfm = object_fetch_transform(kg, object, OBJECT_TRANSFORM);
*t *= len(transform_direction(&tfm, 1.0f/(*idir)));
}
@@ -83,6 +83,35 @@ __device_inline void bvh_instance_pop(KernelGlobals *kg, int object, const Ray *
*idir = bvh_inverse_direction(ray->D);
}
+#ifdef __OBJECT_MOTION__
+__device_inline void bvh_instance_motion_push(KernelGlobals *kg, int object, const Ray *ray, float3 *P, float3 *idir, float *t, Transform *tfm, const float tmax)
+{
+ Transform itfm;
+ *tfm = object_fetch_transform_motion_test(kg, object, ray->time, &itfm);
+
+ *P = transform_point(&itfm, ray->P);
+
+ float3 dir = transform_direction(&itfm, ray->D);
+
+ float len;
+ dir = normalize_len(dir, &len);
+
+ *idir = bvh_inverse_direction(dir);
+
+ if(*t != FLT_MAX)
+ *t *= len;
+}
+
+__device_inline void bvh_instance_motion_pop(KernelGlobals *kg, int object, const Ray *ray, float3 *P, float3 *idir, float *t, Transform *tfm, const float tmax)
+{
+ if(*t != FLT_MAX)
+ *t *= len(transform_direction(tfm, 1.0f/(*idir)));
+
+ *P = ray->P;
+ *idir = bvh_inverse_direction(ray->D);
+}
+#endif
+
/* intersect two bounding boxes */
__device_inline void bvh_node_intersect(KernelGlobals *kg,
bool *traverseChild0, bool *traverseChild1,
@@ -176,7 +205,7 @@ __device_inline void bvh_triangle_intersect(KernelGlobals *kg, Intersection *ise
}
}
-__device_inline bool scene_intersect(KernelGlobals *kg, const Ray *ray, const uint visibility, Intersection *isect)
+__device_inline bool bvh_intersect(KernelGlobals *kg, const Ray *ray, const uint visibility, Intersection *isect)
{
/* traversal stack in CUDA thread-local memory */
int traversalStack[BVH_STACK_SIZE];
@@ -268,7 +297,6 @@ __device_inline bool scene_intersect(KernelGlobals *kg, const Ray *ray, const ui
else {
/* instance push */
object = kernel_tex_fetch(__prim_object, -primAddr-1);
-
bvh_instance_push(kg, object, ray, &P, &idir, &isect->t, tmax);
++stackPtr;
@@ -296,6 +324,135 @@ __device_inline bool scene_intersect(KernelGlobals *kg, const Ray *ray, const ui
return (isect->prim != ~0);
}
+#ifdef __OBJECT_MOTION__
+__device_inline bool bvh_intersect_motion(KernelGlobals *kg, const Ray *ray, const uint visibility, Intersection *isect)
+{
+ /* traversal stack in CUDA thread-local memory */
+ int traversalStack[BVH_STACK_SIZE];
+ traversalStack[0] = ENTRYPOINT_SENTINEL;
+
+ /* traversal variables in registers */
+ int stackPtr = 0;
+ int nodeAddr = kernel_data.bvh.root;
+
+ /* ray parameters in registers */
+ const float tmax = ray->t;
+ float3 P = ray->P;
+ float3 idir = bvh_inverse_direction(ray->D);
+ int object = ~0;
+
+ Transform ob_tfm;
+
+ isect->t = tmax;
+ isect->object = ~0;
+ isect->prim = ~0;
+ isect->u = 0.0f;
+ isect->v = 0.0f;
+
+ /* traversal loop */
+ do {
+ do
+ {
+ /* traverse internal nodes */
+ while(nodeAddr >= 0 && nodeAddr != ENTRYPOINT_SENTINEL)
+ {
+ bool traverseChild0, traverseChild1, closestChild1;
+ int nodeAddrChild1;
+
+ bvh_node_intersect(kg, &traverseChild0, &traverseChild1,
+ &closestChild1, &nodeAddr, &nodeAddrChild1,
+ P, idir, isect->t, visibility, nodeAddr);
+
+ if(traverseChild0 != traverseChild1) {
+ /* one child was intersected */
+ if(traverseChild1) {
+ nodeAddr = nodeAddrChild1;
+ }
+ }
+ else {
+ if(!traverseChild0) {
+ /* neither child was intersected */
+ nodeAddr = traversalStack[stackPtr];
+ --stackPtr;
+ }
+ else {
+ /* both children were intersected, push the farther one */
+ if(closestChild1) {
+ int tmp = nodeAddr;
+ nodeAddr = nodeAddrChild1;
+ nodeAddrChild1 = tmp;
+ }
+
+ ++stackPtr;
+ traversalStack[stackPtr] = nodeAddrChild1;
+ }
+ }
+ }
+
+ /* if node is leaf, fetch triangle list */
+ if(nodeAddr < 0) {
+ float4 leaf = kernel_tex_fetch(__bvh_nodes, (-nodeAddr-1)*BVH_NODE_SIZE+(BVH_NODE_SIZE-1));
+ int primAddr = __float_as_int(leaf.x);
+
+ if(primAddr >= 0) {
+ int primAddr2 = __float_as_int(leaf.y);
+
+ /* pop */
+ nodeAddr = traversalStack[stackPtr];
+ --stackPtr;
+
+ /* triangle intersection */
+ while(primAddr < primAddr2) {
+ /* intersect ray against triangle */
+ bvh_triangle_intersect(kg, isect, P, idir, visibility, object, primAddr);
+
+ /* shadow ray early termination */
+ if(visibility == PATH_RAY_SHADOW_OPAQUE && isect->prim != ~0)
+ return true;
+
+ primAddr++;
+ }
+ }
+ else {
+ /* instance push */
+ object = kernel_tex_fetch(__prim_object, -primAddr-1);
+ bvh_instance_motion_push(kg, object, ray, &P, &idir, &isect->t, &ob_tfm, tmax);
+
+ ++stackPtr;
+ traversalStack[stackPtr] = ENTRYPOINT_SENTINEL;
+
+ nodeAddr = kernel_tex_fetch(__object_node, object);
+ }
+ }
+ } while(nodeAddr != ENTRYPOINT_SENTINEL);
+
+ if(stackPtr >= 0) {
+ kernel_assert(object != ~0);
+
+ /* instance pop */
+ bvh_instance_motion_pop(kg, object, ray, &P, &idir, &isect->t, &ob_tfm, tmax);
+ object = ~0;
+ nodeAddr = traversalStack[stackPtr];
+ --stackPtr;
+ }
+ } while(nodeAddr != ENTRYPOINT_SENTINEL);
+
+ return (isect->prim != ~0);
+}
+#endif
+
+__device_inline bool scene_intersect(KernelGlobals *kg, const Ray *ray, const uint visibility, Intersection *isect)
+{
+#ifdef __OBJECT_MOTION__
+ if(kernel_data.bvh.have_motion)
+ return bvh_intersect_motion(kg, ray, visibility, isect);
+ else
+ return bvh_intersect(kg, ray, visibility, isect);
+#else
+ return bvh_intersect(kg, ray, visibility, isect);
+#endif
+}
+
__device_inline float3 ray_offset(float3 P, float3 Ng)
{
#ifdef __INTERSECTION_REFINE__
@@ -349,10 +506,10 @@ __device_inline float3 bvh_triangle_refine(KernelGlobals *kg, ShaderData *sd, co
#ifdef __INTERSECTION_REFINE__
if(isect->object != ~0) {
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
Transform tfm = sd->ob_itfm;
#else
- Transform tfm = object_fetch_transform(kg, isect->object, ray->time, OBJECT_INVERSE_TRANSFORM);
+ Transform tfm = object_fetch_transform(kg, isect->object, OBJECT_INVERSE_TRANSFORM);
#endif
P = transform_point(&tfm, P);
@@ -370,10 +527,10 @@ __device_inline float3 bvh_triangle_refine(KernelGlobals *kg, ShaderData *sd, co
P = P + D*rt;
if(isect->object != ~0) {
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
Transform tfm = sd->ob_tfm;
#else
- Transform tfm = object_fetch_transform(kg, isect->object, ray->time, OBJECT_TRANSFORM);
+ Transform tfm = object_fetch_transform(kg, isect->object, OBJECT_TRANSFORM);
#endif
P = transform_point(&tfm, P);
diff --git a/intern/cycles/kernel/kernel_camera.h b/intern/cycles/kernel/kernel_camera.h
index e1b474d8537..1b2fe8c56ee 100644
--- a/intern/cycles/kernel/kernel_camera.h
+++ b/intern/cycles/kernel/kernel_camera.h
@@ -63,7 +63,7 @@ __device void camera_sample_perspective(KernelGlobals *kg, float raster_x, float
/* transform ray from camera to world */
Transform cameratoworld = kernel_data.cam.cameratoworld;
-#ifdef __MOTION__
+#ifdef __CAMERA_MOTION__
if(kernel_data.cam.have_motion)
transform_motion_interpolate(&cameratoworld, &kernel_data.cam.motion, ray->time);
#endif
@@ -106,7 +106,7 @@ __device void camera_sample_orthographic(KernelGlobals *kg, float raster_x, floa
/* transform ray from camera to world */
Transform cameratoworld = kernel_data.cam.cameratoworld;
-#ifdef __MOTION__
+#ifdef __CAMERA_MOTION__
if(kernel_data.cam.have_motion)
transform_motion_interpolate(&cameratoworld, &kernel_data.cam.motion, ray->time);
#endif
@@ -134,7 +134,7 @@ __device void camera_sample_orthographic(KernelGlobals *kg, float raster_x, floa
/* Panorama Camera */
-__device void camera_sample_panorama(KernelGlobals *kg, float raster_x, float raster_y, Ray *ray)
+__device void camera_sample_panorama(KernelGlobals *kg, float raster_x, float raster_y, float lens_u, float lens_v, Ray *ray)
{
Transform rastertocamera = kernel_data.cam.rastertocamera;
float3 Pcamera = transform_perspective(&rastertocamera, make_float3(raster_x, raster_y, 0.0f));
@@ -151,6 +151,26 @@ __device void camera_sample_panorama(KernelGlobals *kg, float raster_x, float ra
ray->D = panorama_to_direction(kg, Pcamera.x, Pcamera.y);
+ /* modify ray for depth of field */
+ float aperturesize = kernel_data.cam.aperturesize;
+
+ if(aperturesize > 0.0f) {
+ /* sample point on aperture */
+ float2 lensuv = camera_sample_aperture(kg, lens_u, lens_v)*aperturesize;
+
+ /* compute point on plane of focus */
+ float3 D = normalize(ray->D);
+ float3 Pfocus = D * kernel_data.cam.focaldistance;
+
+ /* calculate orthonormal coordinates perpendicular to D */
+ float3 U, V;
+ make_orthonormals(D, &U, &V);
+
+ /* update ray for effect of lens */
+ ray->P = U * lensuv.x + V * lensuv.y;
+ ray->D = normalize(Pfocus - ray->P);
+ }
+
/* indicates ray should not receive any light, outside of the lens */
if(len_squared(ray->D) == 0.0f) {
ray->t = 0.0f;
@@ -160,7 +180,7 @@ __device void camera_sample_panorama(KernelGlobals *kg, float raster_x, float ra
/* transform ray from camera to world */
Transform cameratoworld = kernel_data.cam.cameratoworld;
-#ifdef __MOTION__
+#ifdef __CAMERA_MOTION__
if(kernel_data.cam.have_motion)
transform_motion_interpolate(&cameratoworld, &kernel_data.cam.motion, ray->time);
#endif
@@ -192,12 +212,12 @@ __device void camera_sample(KernelGlobals *kg, int x, int y, float filter_u, flo
float raster_x = x + kernel_tex_interp(__filter_table, filter_u, FILTER_TABLE_SIZE);
float raster_y = y + kernel_tex_interp(__filter_table, filter_v, FILTER_TABLE_SIZE);
-#ifdef __MOTION__
+#ifdef __CAMERA_MOTION__
/* motion blur */
if(kernel_data.cam.shuttertime == 0.0f)
ray->time = TIME_INVALID;
else
- ray->time = 0.5f + (time - 0.5f)*kernel_data.cam.shuttertime;
+ ray->time = 0.5f + 0.5f*(time - 0.5f)*kernel_data.cam.shuttertime;
#endif
/* sample */
@@ -206,7 +226,7 @@ __device void camera_sample(KernelGlobals *kg, int x, int y, float filter_u, flo
else if(kernel_data.cam.type == CAMERA_ORTHOGRAPHIC)
camera_sample_orthographic(kg, raster_x, raster_y, ray);
else
- camera_sample_panorama(kg, raster_x, raster_y, ray);
+ camera_sample_panorama(kg, raster_x, raster_y, lens_u, lens_v, ray);
}
CCL_NAMESPACE_END
diff --git a/intern/cycles/kernel/kernel_displace.h b/intern/cycles/kernel/kernel_displace.h
index 6461a1eea38..a55f7a7fd75 100644
--- a/intern/cycles/kernel/kernel_displace.h
+++ b/intern/cycles/kernel/kernel_displace.h
@@ -47,6 +47,9 @@ __device void kernel_shader_evaluate(KernelGlobals *kg, uint4 *input, float4 *ou
ray.P = make_float3(0.0f, 0.0f, 0.0f);
ray.D = equirectangular_to_direction(u, v);
ray.t = 0.0f;
+#ifdef __CAMERA_MOTION__
+ ray.time = 0.5f;
+#endif
#ifdef __RAY_DIFFERENTIALS__
ray.dD.dx = make_float3(0.0f, 0.0f, 0.0f);
diff --git a/intern/cycles/kernel/kernel_emission.h b/intern/cycles/kernel/kernel_emission.h
index 53d53b4bedd..6d650a0158d 100644
--- a/intern/cycles/kernel/kernel_emission.h
+++ b/intern/cycles/kernel/kernel_emission.h
@@ -32,8 +32,15 @@ __device float3 direct_emissive_eval(KernelGlobals *kg, float rando,
Ray ray;
ray.D = ls->D;
ray.P = ls->P;
+ ray.t = 1.0f;
+#ifdef __OBJECT_MOTION__
+ ray.time = time;
+#endif
ray.dP.dx = make_float3(0.0f, 0.0f, 0.0f);
ray.dP.dy = make_float3(0.0f, 0.0f, 0.0f);
+#ifdef __CAMERA_MOTION__
+ ray.time = time;
+#endif
shader_setup_from_background(kg, &sd, &ray);
eval = shader_eval_background(kg, &sd, 0);
}
diff --git a/intern/cycles/kernel/kernel_light.h b/intern/cycles/kernel/kernel_light.h
index 1084415d0cf..2791b3abbb6 100644
--- a/intern/cycles/kernel/kernel_light.h
+++ b/intern/cycles/kernel/kernel_light.h
@@ -301,8 +301,13 @@ __device void triangle_light_sample(KernelGlobals *kg, int prim, int object,
#ifdef __INSTANCING__
/* instance transform */
if(ls->object >= 0) {
- Transform tfm = object_fetch_transform(kg, ls->object, time, OBJECT_TRANSFORM);
- Transform itfm = object_fetch_transform(kg, ls->object, time, OBJECT_INVERSE_TRANSFORM);
+#ifdef __OBJECT_MOTION__
+ Transform itfm;
+ Transform tfm = object_fetch_transform_motion_test(kg, object, time, &itfm);
+#else
+ Transform tfm = object_fetch_transform(kg, ls->object, OBJECT_TRANSFORM);
+ Transform itfm = object_fetch_transform(kg, ls->object, OBJECT_INVERSE_TRANSFORM);
+#endif
ls->P = transform_point(&tfm, ls->P);
ls->Ng = normalize(transform_direction_transposed(&itfm, ls->Ng));
diff --git a/intern/cycles/kernel/kernel_mbvh.h b/intern/cycles/kernel/kernel_mbvh.h
deleted file mode 100644
index ccbd3d069b4..00000000000
--- a/intern/cycles/kernel/kernel_mbvh.h
+++ /dev/null
@@ -1,394 +0,0 @@
-/*
- * Copyright 2011, Blender Foundation.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-CCL_NAMESPACE_BEGIN
-
-#define MBVH_OBJECT_SENTINEL 0x76543210
-#define MBVH_NODE_SIZE 8
-#define MBVH_STACK_SIZE 1024
-#define MBVH_RAY_STACK_SIZE 10000
-
-typedef struct MBVHTask {
- int node;
- int index;
- int num;
- int object;
-} MBVHTask;
-
-typedef struct MVBHRay {
- float3 P;
- float u;
- float3 idir;
- float v;
- float t;
- int index;
- int object;
-
- float3 origP;
- float3 origD;
- float tmax;
-} MBVHRay;
-
-__device float3 mbvh_inverse_direction(float3 dir)
-{
- // Avoid divide by zero (ooeps = exp2f(-80.0f))
- float ooeps = 0.00000000000000000000000082718061255302767487140869206996285356581211090087890625f;
- float3 idir;
-
- idir.x = 1.0f / (fabsf(dir.x) > ooeps ? dir.x : copysignf(ooeps, dir.x));
- idir.y = 1.0f / (fabsf(dir.y) > ooeps ? dir.y : copysignf(ooeps, dir.y));
- idir.z = 1.0f / (fabsf(dir.z) > ooeps ? dir.z : copysignf(ooeps, dir.z));
-
- return idir;
-}
-
-__device void mbvh_instance_push(KernelGlobals *kg, int object, MBVHRay *ray)
-{
- Transform tfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM);
-
- ray->P = transform_point(&tfm, ray->origP);
-
- float3 dir = ray->origD;
-
- if(ray->t != ray->tmax) dir *= ray->t;
-
- dir = transform_direction(&tfm, dir);
- ray->idir = mbvh_inverse_direction(normalize(dir));
-
- if(ray->t != ray->tmax) ray->t = len(dir);
-}
-
-__device void mbvh_instance_pop(KernelGlobals *kg, int object, MBVHRay *ray)
-{
- Transform tfm = object_fetch_transform(kg, object, OBJECT_TRANSFORM);
-
- if(ray->t != ray->tmax)
- ray->t = len(transform_direction(&tfm, (1.0f/(ray->idir)) * (ray->t)));
-
- ray->P = ray->origP;
- ray->idir = mbvh_inverse_direction(ray->origD);
-}
-
-/* Sven Woop's algorithm */
-__device void mbvh_triangle_intersect(KernelGlobals *kg, MBVHRay *ray, int object, int triAddr)
-{
- float3 P = ray->P;
- float3 idir = ray->idir;
-
- /* compute and check intersection t-value */
- float4 v00 = kernel_tex_fetch(__tri_woop, triAddr*MBVH_NODE_SIZE+0);
- float4 v11 = kernel_tex_fetch(__tri_woop, triAddr*MBVH_NODE_SIZE+1);
- float3 dir = 1.0f/idir;
-
- float Oz = v00.w - P.x*v00.x - P.y*v00.y - P.z*v00.z;
- float invDz = 1.0f/(dir.x*v00.x + dir.y*v00.y + dir.z*v00.z);
- float t = Oz * invDz;
-
- if(t > 0.0f && t < ray->t) {
- /* compute and check barycentric u */
- float Ox = v11.w + P.x*v11.x + P.y*v11.y + P.z*v11.z;
- float Dx = dir.x*v11.x + dir.y*v11.y + dir.z*v11.z;
- float u = Ox + t*Dx;
-
- if(u >= 0.0f) {
- /* compute and check barycentric v */
- float4 v22 = kernel_tex_fetch(__tri_woop, triAddr*MBVH_NODE_SIZE+2);
- float Oy = v22.w + P.x*v22.x + P.y*v22.y + P.z*v22.z;
- float Dy = dir.x*v22.x + dir.y*v22.y + dir.z*v22.z;
- float v = Oy + t*Dy;
-
- if(v >= 0.0f && u + v <= 1.0f) {
- /* record intersection */
- ray->index = triAddr;
- ray->object = object;
- ray->u = u;
- ray->v = v;
- ray->t = t;
- }
- }
- }
-}
-
-__device void mbvh_node_intersect(KernelGlobals *kg, __m128 *traverseChild,
- __m128 *tHit, float3 P, float3 idir, float t, int nodeAddr)
-{
- /* X axis */
- const __m128 bminx = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*MBVH_NODE_SIZE+0);
- const __m128 t0x = _mm_mul_ps(_mm_sub_ps(bminx, _mm_set_ps1(P.x)), _mm_set_ps1(idir.x));
- const __m128 bmaxx = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*MBVH_NODE_SIZE+1);
- const __m128 t1x = _mm_mul_ps(_mm_sub_ps(bmaxx, _mm_set_ps1(P.x)), _mm_set_ps1(idir.x));
-
- __m128 tmin = _mm_max_ps(_mm_min_ps(t0x, t1x), _mm_setzero_ps());
- __m128 tmax = _mm_min_ps(_mm_max_ps(t0x, t1x), _mm_set_ps1(t));
-
- /* Y axis */
- const __m128 bminy = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*MBVH_NODE_SIZE+2);
- const __m128 t0y = _mm_mul_ps(_mm_sub_ps(bminy, _mm_set_ps1(P.y)), _mm_set_ps1(idir.y));
- const __m128 bmaxy = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*MBVH_NODE_SIZE+3);
- const __m128 t1y = _mm_mul_ps(_mm_sub_ps(bmaxy, _mm_set_ps1(P.y)), _mm_set_ps1(idir.y));
-
- tmin = _mm_max_ps(_mm_min_ps(t0y, t1y), tmin);
- tmax = _mm_min_ps(_mm_max_ps(t0y, t1y), tmax);
-
- /* Z axis */
- const __m128 bminz = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*MBVH_NODE_SIZE+4);
- const __m128 t0z = _mm_mul_ps(_mm_sub_ps(bminz, _mm_set_ps1(P.z)), _mm_set_ps1(idir.z));
- const __m128 bmaxz = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*MBVH_NODE_SIZE+5);
- const __m128 t1z = _mm_mul_ps(_mm_sub_ps(bmaxz, _mm_set_ps1(P.z)), _mm_set_ps1(idir.z));
-
- tmin = _mm_max_ps(_mm_min_ps(t0z, t1z), tmin);
- tmax = _mm_min_ps(_mm_max_ps(t0z, t1z), tmax);
-
- /* compare and get mask */
- *traverseChild = _mm_cmple_ps(tmin, tmax);
-
- /* get distance XXX probably wrong */
- *tHit = tmin;
-}
-
-static void mbvh_sort_by_length(int id[4], float len[4])
-{
- for(int i = 1; i < 4; i++) {
- int j = i - 1;
-
- while(j >= 0 && len[j] > len[j+1]) {
- swap(len[j], len[j+1]);
- swap(id[j], id[j+1]);
- j--;
- }
- }
-}
-
-__device void scene_intersect(KernelGlobals *kg, MBVHRay *rays, int numrays)
-{
- /* traversal stacks */
- MBVHTask task_stack[MBVH_STACK_SIZE];
- int active_ray_stacks[4][MBVH_RAY_STACK_SIZE];
- int num_task, num_active[4] = {0, 0, 0, 0};
- __m128i one_mm = _mm_set1_epi32(1);
-
- /* push root node task on stack */
- task_stack[0].node = kernel_data.bvh.root;
- task_stack[0].index = 0;
- task_stack[0].num = numrays;
- task_stack[0].object = ~0;
- num_task = 1;
-
- /* push all rays in first SIMD lane */
- for(int i = 0; i < numrays; i++)
- active_ray_stacks[0][i] = i;
- num_active[0] = numrays;
-
- while(num_task >= 1) {
- /* pop task */
- MBVHTask task = task_stack[--num_task];
-
- if(task.node == MBVH_OBJECT_SENTINEL) {
- /* instance pop */
-
- /* pop rays from stack */
- num_active[task.index] -= task.num;
- int ray_offset = num_active[task.index];
-
- /* transform rays */
- for(int i = 0; i < task.num; i++) {
- MBVHRay *ray = &rays[active_ray_stacks[task.index][ray_offset + i]];
- mbvh_instance_pop(kg, task.object, ray);
- }
- }
- else if(task.node >= 0) {
- /* inner node? */
-
- /* pop rays from stack*/
- num_active[task.index] -= task.num;
- int ray_offset = num_active[task.index];
-
- /* initialze simd values */
- __m128i num_active_mm = _mm_load_si128((__m128i*)num_active);
- __m128 len_mm = _mm_set_ps1(0.0f);
-
- for(int i = 0; i < task.num; i++) {
- int rayid = active_ray_stacks[task.index][ray_offset + i];
- MVBHRay *ray = rays + rayid;
-
- /* intersect 4 QBVH node children */
- __m128 result;
- __m128 thit;
-
- mbvh_node_intersect(kg, &result, &thit, ray->P, ray->idir, ray->t, task.node);
-
- /* update length for sorting */
- len_mm = _mm_add_ps(len_mm, _mm_and_ps(thit, result));
-
- /* push rays on stack */
- for(int j = 0; j < 4; j++)
- active_ray_stacks[j][num_active[j]] = rayid;
-
- /* update num active */
- __m128i resulti = _mm_and_si128(*((__m128i*)&result), one_mm);
- num_active_mm = _mm_add_epi32(resulti, num_active_mm);
- _mm_store_si128((__m128i*)num_active, num_active_mm);
- }
-
- if(num_active[0] || num_active[1] || num_active[2] || num_active[3]) {
- /* load child node addresses */
- float4 cnodes = kernel_tex_fetch(__bvh_nodes, task.node);
- int child[4] = {
- __float_as_int(cnodes.x),
- __float_as_int(cnodes.y),
- __float_as_int(cnodes.z),
- __float_as_int(cnodes.w)};
-
- /* sort nodes by average intersection distance */
- int ids[4] = {0, 1, 2, 3};
- float len[4];
-
- _mm_store_ps(len, len_mm);
- mbvh_sort_by_length(ids, len);
-
- /* push new tasks on stack */
- for(int j = 0; j < 4; j++) {
- if(num_active[j]) {
- int id = ids[j];
-
- task_stack[num_task].node = child[id];
- task_stack[num_task].index = id;
- task_stack[num_task].num = num_active[id];
- task_stack[num_task].object = task.object;
- num_task++;
- }
- }
- }
- }
- else {
- /* fetch leaf node data */
- float4 leaf = kernel_tex_fetch(__bvh_nodes, (-task.node-1)*MBVH_NODE_SIZE+(MBVH_NODE_SIZE-2));
- int triAddr = __float_as_int(leaf.x);
- int triAddr2 = __float_as_int(leaf.y);
-
- /* pop rays from stack*/
- num_active[task.index] -= task.num;
- int ray_offset = num_active[task.index];
-
- /* triangles */
- if(triAddr >= 0) {
- int i, numq = (task.num >> 2) << 2;
-
- /* SIMD ray leaf intersection */
- for(i = 0; i < numq; i += 4) {
- MBVHRay *ray4[4] = {
- &rays[active_ray_stacks[task.index][ray_offset + i + 0]],
- &rays[active_ray_stacks[task.index][ray_offset + i + 1]],
- &rays[active_ray_stacks[task.index][ray_offset + i + 2]],
- &rays[active_ray_stacks[task.index][ray_offset + i + 3]]};
-
- /* load SoA */
-
- while(triAddr < triAddr2) {
- mbvh_triangle_intersect(ray4[0], task.object, task.node);
- mbvh_triangle_intersect(ray4[1], task.object, task.node);
- mbvh_triangle_intersect(ray4[2], task.object, task.node);
- mbvh_triangle_intersect(ray4[3], task.object, task.node);
- triAddr++;
-
- /* some shadow ray optim could be done by setting t=0 */
- }
-
- /* store AoS */
- }
-
- /* mono ray leaf intersection */
- for(; i < task.num; i++) {
- MBVHRay *ray = &rays[active_ray_stacks[task.index][ray_offset + i]];
-
- while(triAddr < triAddr2) {
- mbvh_triangle_intersect(kg, ray, task.object, task.node);
- triAddr++;
- }
- }
- }
- else {
- /* instance push */
- int object = -triAddr-1;
- int node = triAddr;
-
- /* push instance pop task */
- task_stack[num_task].node = MBVH_OBJECT_SENTINEL;
- task_stack[num_task].index = task.index;
- task_stack[num_task].num = task.num;
- task_stack[num_task].object = object;
- num_task++;
-
- num_active[task.index] += task.num;
-
- /* push node task */
- task_stack[num_task].node = node;
- task_stack[num_task].index = task.index;
- task_stack[num_task].num = task.num;
- task_stack[num_task].object = object;
- num_task++;
-
- for(int i = 0; i < task.num; i++) {
- int rayid = active_ray_stacks[task.index][ray_offset + i];
-
- /* push on stack for last task */
- active_ray_stacks[task.index][num_active[task.index]] = rayid;
- num_active[task.index]++;
-
- /* transform ray */
- MBVHRay *ray = &rays[rayid];
- mbvh_instance_push(kg, object, ray);
- }
- }
- }
- }
-}
-
-__device void mbvh_set_ray(MBVHRay *rays, int i, Ray *ray, float tmax)
-{
- MBVHRay *mray = &rays[i];
-
- /* ray parameters in registers */
- mray->P = ray->P;
- mray->idir = mbvh_inverse_direction(ray->D);
- mray->t = tmax;
-}
-
-__device bool mbvh_get_intersection(MVBHRay *rays, int i, Intersection *isect, float tmax)
-{
- MBVHRay *mray = &rays[i];
-
- if(mray->t == tmax)
- return false;
-
- isect->t = mray->t;
- isect->u = mray->u;
- isect->v = mray->v;
- isect->index = mray->index;
- isect->object = mray->object;
-
- return true;
-}
-
-__device bool mbvh_get_shadow(MBVHRay *rays, int i, float tmax)
-{
- return (rays[i].t == tmax);
-}
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/kernel_montecarlo.h b/intern/cycles/kernel/kernel_montecarlo.h
index afc53b1117a..48d1aa64c9f 100644
--- a/intern/cycles/kernel/kernel_montecarlo.h
+++ b/intern/cycles/kernel/kernel_montecarlo.h
@@ -46,16 +46,19 @@ __device void to_unit_disk(float *x, float *y)
if(a > -b) {
if(a > b) {
r = a;
- phi = M_PI_4_F *(b/a);
- } else {
- r = b;
- phi = M_PI_4_F *(2.0f - a/b);
- }
- } else {
+ phi = M_PI_4_F *(b/a);
+ }
+ else {
+ r = b;
+ phi = M_PI_4_F *(2.0f - a/b);
+ }
+ }
+ else {
if(a < b) {
r = -a;
phi = M_PI_4_F *(4.0f + b/a);
- } else {
+ }
+ else {
r = -b;
if(b != 0.0f)
phi = M_PI_4_F *(6.0f - a/b);
@@ -69,7 +72,7 @@ __device void to_unit_disk(float *x, float *y)
__device void make_orthonormals_tangent(const float3 N, const float3 T, float3 *a, float3 *b)
{
- *b = cross(N, T);
+ *b = normalize(cross(N, T));
*a = cross(*b, N);
}
diff --git a/intern/cycles/kernel/kernel_object.h b/intern/cycles/kernel/kernel_object.h
index 222ade504cc..112bfbb86b5 100644
--- a/intern/cycles/kernel/kernel_object.h
+++ b/intern/cycles/kernel/kernel_object.h
@@ -23,106 +23,134 @@ enum ObjectTransform {
OBJECT_INVERSE_TRANSFORM = 3,
OBJECT_PROPERTIES = 6,
OBJECT_TRANSFORM_MOTION_PRE = 8,
- OBJECT_TRANSFORM_MOTION_POST = 12
+ OBJECT_TRANSFORM_MOTION_MID = 12,
+ OBJECT_TRANSFORM_MOTION_POST = 16,
+ OBJECT_DUPLI = 20
};
-__device_inline Transform object_fetch_transform(KernelGlobals *kg, int object, float time, enum ObjectTransform type)
+__device_inline Transform object_fetch_transform(KernelGlobals *kg, int object, enum ObjectTransform type)
{
+ int offset = object*OBJECT_SIZE + (int)type;
+
Transform tfm;
+ tfm.x = kernel_tex_fetch(__objects, offset + 0);
+ tfm.y = kernel_tex_fetch(__objects, offset + 1);
+ tfm.z = kernel_tex_fetch(__objects, offset + 2);
+ tfm.w = make_float4(0.0f, 0.0f, 0.0f, 1.0f);
-#ifdef __MOTION__
- /* if we do motion blur */
- if(sd->flag & SD_OBJECT_MOTION) {
- /* fetch motion transforms */
- MotionTransform motion;
+ return tfm;
+}
- motion.pre.x = have_motion;
- motion.pre.y = kernel_tex_fetch(__objects, offset + 1);
- motion.pre.z = kernel_tex_fetch(__objects, offset + 2);
- motion.pre.w = kernel_tex_fetch(__objects, offset + 3);
+#ifdef __OBJECT_MOTION__
+__device_inline Transform object_fetch_transform_motion(KernelGlobals *kg, int object, float time)
+{
+ MotionTransform motion;
- motion.post.x = kernel_tex_fetch(__objects, offset + 4);
- motion.post.y = kernel_tex_fetch(__objects, offset + 5);
- motion.post.z = kernel_tex_fetch(__objects, offset + 6);
- motion.post.w = kernel_tex_fetch(__objects, offset + 7);
+ int offset = object*OBJECT_SIZE + (int)OBJECT_TRANSFORM_MOTION_PRE;
- /* interpolate (todo: do only once per object) */
- transform_motion_interpolate(&tfm, &motion, time);
+ motion.pre.x = kernel_tex_fetch(__objects, offset + 0);
+ motion.pre.y = kernel_tex_fetch(__objects, offset + 1);
+ motion.pre.z = kernel_tex_fetch(__objects, offset + 2);
+ motion.pre.w = kernel_tex_fetch(__objects, offset + 3);
- /* invert */
- if(type == OBJECT_INVERSE_TRANSFORM)
- tfm = transform_quick_inverse(tfm);
+ motion.mid.x = kernel_tex_fetch(__objects, offset + 4);
+ motion.mid.y = kernel_tex_fetch(__objects, offset + 5);
+ motion.mid.z = kernel_tex_fetch(__objects, offset + 6);
+ motion.mid.w = kernel_tex_fetch(__objects, offset + 7);
- return tfm;
- }
-#endif
+ motion.post.x = kernel_tex_fetch(__objects, offset + 8);
+ motion.post.y = kernel_tex_fetch(__objects, offset + 9);
+ motion.post.z = kernel_tex_fetch(__objects, offset + 10);
+ motion.post.w = kernel_tex_fetch(__objects, offset + 11);
- int offset = object*OBJECT_SIZE + (int)type;
-
- tfm.x = kernel_tex_fetch(__objects, offset + 0);
- tfm.y = kernel_tex_fetch(__objects, offset + 1);
- tfm.z = kernel_tex_fetch(__objects, offset + 2);
- tfm.w = make_float4(0.0f, 0.0f, 0.0f, 1.0f);
+ Transform tfm;
+ transform_motion_interpolate(&tfm, &motion, time);
return tfm;
}
+__device_inline Transform object_fetch_transform_motion_test(KernelGlobals *kg, int object, float time, Transform *itfm)
+{
+ int object_flag = kernel_tex_fetch(__object_flag, object);
+
+ if(object_flag & SD_OBJECT_MOTION) {
+ /* if we do motion blur */
+ Transform tfm = object_fetch_transform_motion(kg, object, time);
+
+ if(itfm)
+ *itfm = transform_quick_inverse(tfm);
+
+ return tfm;
+ }
+ else {
+ Transform tfm = object_fetch_transform(kg, object, OBJECT_TRANSFORM);
+ if(itfm)
+ *itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM);
+
+ return tfm;
+ }
+}
+#endif
+
__device_inline void object_position_transform(KernelGlobals *kg, ShaderData *sd, float3 *P)
{
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
*P = transform_point(&sd->ob_tfm, *P);
#else
- Transform tfm = object_fetch_transform(kg, sd->object, TIME_INVALID, OBJECT_TRANSFORM);
+ Transform tfm = object_fetch_transform(kg, sd->object, OBJECT_TRANSFORM);
*P = transform_point(&tfm, *P);
#endif
}
__device_inline void object_inverse_position_transform(KernelGlobals *kg, ShaderData *sd, float3 *P)
{
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
*P = transform_point(&sd->ob_itfm, *P);
#else
- Transform tfm = object_fetch_transform(kg, sd->object, TIME_INVALID, OBJECT_INVERSE_TRANSFORM);
+ Transform tfm = object_fetch_transform(kg, sd->object, OBJECT_INVERSE_TRANSFORM);
*P = transform_point(&tfm, *P);
#endif
}
__device_inline void object_inverse_normal_transform(KernelGlobals *kg, ShaderData *sd, float3 *N)
{
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
*N = normalize(transform_direction_transposed(&sd->ob_tfm, *N));
#else
- Transform tfm = object_fetch_transform(kg, sd->object, TIME_INVALID, OBJECT_TRANSFORM);
+ Transform tfm = object_fetch_transform(kg, sd->object, OBJECT_TRANSFORM);
*N = normalize(transform_direction_transposed(&tfm, *N));
#endif
}
__device_inline void object_normal_transform(KernelGlobals *kg, ShaderData *sd, float3 *N)
{
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
*N = normalize(transform_direction_transposed(&sd->ob_itfm, *N));
#else
- Transform tfm = object_fetch_transform(kg, sd->object, TIME_INVALID, OBJECT_INVERSE_TRANSFORM);
+ Transform tfm = object_fetch_transform(kg, sd->object, OBJECT_INVERSE_TRANSFORM);
*N = normalize(transform_direction_transposed(&tfm, *N));
#endif
}
__device_inline void object_dir_transform(KernelGlobals *kg, ShaderData *sd, float3 *D)
{
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
*D = transform_direction(&sd->ob_tfm, *D);
#else
- Transform tfm = object_fetch_transform(kg, sd->object, 0.0f, OBJECT_TRANSFORM);
+ Transform tfm = object_fetch_transform(kg, sd->object, OBJECT_TRANSFORM);
*D = transform_direction(&tfm, *D);
#endif
}
__device_inline float3 object_location(KernelGlobals *kg, ShaderData *sd)
{
-#ifdef __MOTION__
+ if(sd->object == ~0)
+ return make_float3(0.0f, 0.0f, 0.0f);
+
+#ifdef __OBJECT_MOTION__
return make_float3(sd->ob_tfm.x.w, sd->ob_tfm.y.w, sd->ob_tfm.z.w);
#else
- Transform tfm = object_fetch_transform(kg, sd->object, 0.0f, OBJECT_TRANSFORM);
+ Transform tfm = object_fetch_transform(kg, sd->object, OBJECT_TRANSFORM);
return make_float3(tfm.x.w, tfm.y.w, tfm.z.w);
#endif
}
@@ -164,6 +192,27 @@ __device_inline uint object_particle_id(KernelGlobals *kg, int object)
return __float_as_int(f.w);
}
+__device_inline float3 object_dupli_generated(KernelGlobals *kg, int object)
+{
+ if(object == ~0)
+ return make_float3(0.0f, 0.0f, 0.0f);
+
+ int offset = object*OBJECT_SIZE + OBJECT_DUPLI;
+ float4 f = kernel_tex_fetch(__objects, offset);
+ return make_float3(f.x, f.y, f.z);
+}
+
+__device_inline float3 object_dupli_uv(KernelGlobals *kg, int object)
+{
+ if(object == ~0)
+ return make_float3(0.0f, 0.0f, 0.0f);
+
+ int offset = object*OBJECT_SIZE + OBJECT_DUPLI;
+ float4 f = kernel_tex_fetch(__objects, offset + 1);
+ return make_float3(f.x, f.y, 0.0f);
+}
+
+
__device int shader_pass_id(KernelGlobals *kg, ShaderData *sd)
{
return kernel_tex_fetch(__shader_flag, (sd->shader & SHADER_MASK)*2 + 1);
@@ -227,6 +276,5 @@ __device float3 particle_angular_velocity(KernelGlobals *kg, int particle)
return make_float3(f3.z, f3.w, f4.x);
}
-
CCL_NAMESPACE_END
diff --git a/intern/cycles/kernel/kernel_passes.h b/intern/cycles/kernel/kernel_passes.h
index f3ddda4a392..42733d691e0 100644
--- a/intern/cycles/kernel/kernel_passes.h
+++ b/intern/cycles/kernel/kernel_passes.h
@@ -125,8 +125,18 @@ __device_inline void kernel_write_light_passes(KernelGlobals *kg, __global float
kernel_write_pass_float3(buffer + kernel_data.film.pass_glossy_color, sample, L->color_glossy);
if(flag & PASS_TRANSMISSION_COLOR)
kernel_write_pass_float3(buffer + kernel_data.film.pass_transmission_color, sample, L->color_transmission);
- if(flag & PASS_SHADOW)
- kernel_write_pass_float4(buffer + kernel_data.film.pass_shadow, sample, L->shadow);
+ if(flag & PASS_SHADOW) {
+ float4 shadow = L->shadow;
+
+ /* bit of an ugly hack to compensate for emitting triangles influencing
+ * amount of samples we get for this pass */
+ if(kernel_data.integrator.progressive && kernel_data.integrator.pdf_triangles != 0.0f)
+ shadow.w = 0.5f;
+ else
+ shadow.w = 1.0f;
+
+ kernel_write_pass_float4(buffer + kernel_data.film.pass_shadow, sample, shadow);
+ }
#endif
}
diff --git a/intern/cycles/kernel/kernel_path.h b/intern/cycles/kernel/kernel_path.h
index d606c3d634a..817f254a5e5 100644
--- a/intern/cycles/kernel/kernel_path.h
+++ b/intern/cycles/kernel/kernel_path.h
@@ -343,7 +343,7 @@ __device float4 kernel_path_progressive(KernelGlobals *kg, RNG *rng, int sample,
light_ray.P = ray_offset(sd.P, sd.Ng);
light_ray.D = ao_D;
light_ray.t = kernel_data.background.ao_distance;
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
light_ray.time = sd.time;
#endif
@@ -368,7 +368,7 @@ __device float4 kernel_path_progressive(KernelGlobals *kg, RNG *rng, int sample,
BsdfEval L_light;
bool is_lamp;
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
light_ray.time = sd.time;
#endif
@@ -520,7 +520,7 @@ __device void kernel_path_indirect(KernelGlobals *kg, RNG *rng, int sample, Ray
light_ray.P = ray_offset(sd.P, sd.Ng);
light_ray.D = ao_D;
light_ray.t = kernel_data.background.ao_distance;
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
light_ray.time = sd.time;
#endif
@@ -545,7 +545,7 @@ __device void kernel_path_indirect(KernelGlobals *kg, RNG *rng, int sample, Ray
BsdfEval L_light;
bool is_lamp;
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
light_ray.time = sd.time;
#endif
@@ -728,7 +728,7 @@ __device float4 kernel_path_non_progressive(KernelGlobals *kg, RNG *rng, int sam
light_ray.P = ray_offset(sd.P, sd.Ng);
light_ray.D = ao_D;
light_ray.t = kernel_data.background.ao_distance;
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
light_ray.time = sd.time;
#endif
@@ -748,7 +748,7 @@ __device float4 kernel_path_non_progressive(KernelGlobals *kg, RNG *rng, int sam
BsdfEval L_light;
bool is_lamp;
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
light_ray.time = sd.time;
#endif
@@ -867,7 +867,7 @@ __device float4 kernel_path_non_progressive(KernelGlobals *kg, RNG *rng, int sam
bsdf_ray.dP = sd.dP;
bsdf_ray.dD = bsdf_domega_in;
#endif
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
bsdf_ray.time = sd.time;
#endif
@@ -925,7 +925,7 @@ __device void kernel_path_trace(KernelGlobals *kg,
float lens_u = path_rng(kg, &rng, sample, PRNG_LENS_U);
float lens_v = path_rng(kg, &rng, sample, PRNG_LENS_V);
-#ifdef __MOTION__
+#ifdef __CAMERA_MOTION__
float time = path_rng(kg, &rng, sample, PRNG_TIME);
#else
float time = 0.0f;
diff --git a/intern/cycles/kernel/kernel_qbvh.h b/intern/cycles/kernel/kernel_qbvh.h
deleted file mode 100644
index 525b616921d..00000000000
--- a/intern/cycles/kernel/kernel_qbvh.h
+++ /dev/null
@@ -1,413 +0,0 @@
-/*
- * Adapted from code Copyright 2009-2010 NVIDIA Corporation
- * Modifications Copyright 2011, Blender Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-CCL_NAMESPACE_BEGIN
-
-/*
- * "Persistent while-while kernel" used in:
- *
- * "Understanding the Efficiency of Ray Traversal on GPUs",
- * Timo Aila and Samuli Laine,
- * Proc. High-Performance Graphics 2009
- */
-
-/* bottom-most stack entry, indicating the end of traversal */
-
-#define ENTRYPOINT_SENTINEL 0x76543210
-/* 64 object BVH + 64 mesh BVH + 64 object node splitting */
-#define QBVH_STACK_SIZE 192
-#define QBVH_NODE_SIZE 8
-#define TRI_NODE_SIZE 3
-
-__device_inline float3 qbvh_inverse_direction(float3 dir)
-{
- // Avoid divide by zero (ooeps = exp2f(-80.0f))
- float ooeps = 0.00000000000000000000000082718061255302767487140869206996285356581211090087890625f;
- float3 idir;
-
- idir.x = 1.0f/((fabsf(dir.x) > ooeps)? dir.x: copysignf(ooeps, dir.x));
- idir.y = 1.0f/((fabsf(dir.y) > ooeps)? dir.y: copysignf(ooeps, dir.y));
- idir.z = 1.0f/((fabsf(dir.z) > ooeps)? dir.z: copysignf(ooeps, dir.z));
-
- return idir;
-}
-
-__device_inline void qbvh_instance_push(KernelGlobals *kg, int object, const Ray *ray, float3 *P, float3 *idir, float *t, const float tmax)
-{
- Transform tfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM);
-
- *P = transform_point(&tfm, ray->P);
-
- float3 dir = transform_direction(&tfm, ray->D);
-
- float len;
- dir = normalize_len(dir, &len);
-
- *idir = qbvh_inverse_direction(dir);
-
- if(*t != FLT_MAX)
- *t *= len;
-}
-
-__device_inline void qbvh_instance_pop(KernelGlobals *kg, int object, const Ray *ray, float3 *P, float3 *idir, float *t, const float tmax)
-{
- Transform tfm = object_fetch_transform(kg, object, OBJECT_TRANSFORM);
-
- if(*t != FLT_MAX)
- *t *= len(transform_direction(&tfm, 1.0f/(*idir)));
-
- *P = ray->P;
- *idir = qbvh_inverse_direction(ray->D);
-}
-
-#ifdef __KERNEL_CPU__
-
-__device_inline void qbvh_node_intersect(KernelGlobals *kg, int *traverseChild,
- int nodeAddrChild[4], float3 P, float3 idir, float t, int nodeAddr)
-{
- /* X axis */
- const __m128 bminx = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+0);
- const __m128 t0x = _mm_mul_ps(_mm_sub_ps(bminx, _mm_set_ps1(P.x)), _mm_set_ps1(idir.x));
- const __m128 bmaxx = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+1);
- const __m128 t1x = _mm_mul_ps(_mm_sub_ps(bmaxx, _mm_set_ps1(P.x)), _mm_set_ps1(idir.x));
-
- __m128 tmin = _mm_max_ps(_mm_min_ps(t0x, t1x), _mm_setzero_ps());
- __m128 tmax = _mm_min_ps(_mm_max_ps(t0x, t1x), _mm_set_ps1(t));
-
- /* Y axis */
- const __m128 bminy = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+2);
- const __m128 t0y = _mm_mul_ps(_mm_sub_ps(bminy, _mm_set_ps1(P.y)), _mm_set_ps1(idir.y));
- const __m128 bmaxy = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+3);
- const __m128 t1y = _mm_mul_ps(_mm_sub_ps(bmaxy, _mm_set_ps1(P.y)), _mm_set_ps1(idir.y));
-
- tmin = _mm_max_ps(_mm_min_ps(t0y, t1y), tmin);
- tmax = _mm_min_ps(_mm_max_ps(t0y, t1y), tmax);
-
- /* Z axis */
- const __m128 bminz = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+4);
- const __m128 t0z = _mm_mul_ps(_mm_sub_ps(bminz, _mm_set_ps1(P.z)), _mm_set_ps1(idir.z));
- const __m128 bmaxz = kernel_tex_fetch_m128(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+5);
- const __m128 t1z = _mm_mul_ps(_mm_sub_ps(bmaxz, _mm_set_ps1(P.z)), _mm_set_ps1(idir.z));
-
- tmin = _mm_max_ps(_mm_min_ps(t0z, t1z), tmin);
- tmax = _mm_min_ps(_mm_max_ps(t0z, t1z), tmax);
-
- /* compare and get mask */
- *traverseChild = _mm_movemask_ps(_mm_cmple_ps(tmin, tmax));
-
- /* get node addresses */
- float4 cnodes = kernel_tex_fetch(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+6);
-
- nodeAddrChild[0] = __float_as_int(cnodes.x);
- nodeAddrChild[1] = __float_as_int(cnodes.y);
- nodeAddrChild[2] = __float_as_int(cnodes.z);
- nodeAddrChild[3] = __float_as_int(cnodes.w);
-}
-
-#else
-
-__device_inline bool qbvh_bb_intersect(float3 bmin, float3 bmax, float3 P, float3 idir, float t)
-{
- float t0x = (bmin.x - P.x)*idir.x;
- float t1x = (bmax.x - P.x)*idir.x;
- float t0y = (bmin.y - P.y)*idir.y;
- float t1y = (bmax.y - P.y)*idir.y;
- float t0z = (bmin.z - P.z)*idir.z;
- float t1z = (bmax.z - P.z)*idir.z;
-
- float minx = min(t0x, t1x);
- float maxx = max(t0x, t1x);
- float miny = min(t0y, t1y);
- float maxy = max(t0y, t1y);
- float minz = min(t0z, t1z);
- float maxz = max(t0z, t1z);
-
- float tmin = max4(0.0f, minx, miny, minz);
- float tmax = min4(t, maxx, maxy, maxz);
-
- return (tmin <= tmax);
-}
-
-/* intersect four bounding boxes */
-__device_inline void qbvh_node_intersect(KernelGlobals *kg, int *traverseChild,
- int nodeAddrChild[4], float3 P, float3 idir, float t, int nodeAddr)
-{
- /* fetch node data */
- float4 minx = kernel_tex_fetch(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+0);
- float4 miny = kernel_tex_fetch(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+2);
- float4 minz = kernel_tex_fetch(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+4);
- float4 maxx = kernel_tex_fetch(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+1);
- float4 maxy = kernel_tex_fetch(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+3);
- float4 maxz = kernel_tex_fetch(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+5);
-
- /* intersect bounding boxes */
- bool traverseChild0 = qbvh_bb_intersect(make_float3(minx.x, miny.x, minz.x), make_float3(maxx.x, maxy.x, maxz.x), P, idir, t);
- bool traverseChild1 = qbvh_bb_intersect(make_float3(minx.y, miny.y, minz.y), make_float3(maxx.y, maxy.y, maxz.y), P, idir, t);
- bool traverseChild2 = qbvh_bb_intersect(make_float3(minx.z, miny.z, minz.z), make_float3(maxx.z, maxy.z, maxz.z), P, idir, t);
- bool traverseChild3 = qbvh_bb_intersect(make_float3(minx.w, miny.w, minz.w), make_float3(maxx.w, maxy.w, maxz.w), P, idir, t);
-
- *traverseChild = 0;
- if(traverseChild0) *traverseChild |= 1;
- if(traverseChild1) *traverseChild |= 2;
- if(traverseChild2) *traverseChild |= 4;
- if(traverseChild3) *traverseChild |= 8;
-
- /* get node addresses */
- float4 cnodes = kernel_tex_fetch(__bvh_nodes, nodeAddr*QBVH_NODE_SIZE+6);
-
- nodeAddrChild[0] = __float_as_int(cnodes.x);
- nodeAddrChild[1] = __float_as_int(cnodes.y);
- nodeAddrChild[2] = __float_as_int(cnodes.z);
- nodeAddrChild[3] = __float_as_int(cnodes.w);
-}
-
-#endif
-
-/* Sven Woop's algorithm */
-__device_inline void qbvh_triangle_intersect(KernelGlobals *kg, Intersection *isect, float3 P, float3 idir, int object, int triAddr)
-{
- /* compute and check intersection t-value */
- float4 v00 = kernel_tex_fetch(__tri_woop, triAddr*TRI_NODE_SIZE+0);
- float4 v11 = kernel_tex_fetch(__tri_woop, triAddr*TRI_NODE_SIZE+1);
- float3 dir = 1.0f/idir;
-
- float Oz = v00.w - P.x*v00.x - P.y*v00.y - P.z*v00.z;
- float invDz = 1.0f/(dir.x*v00.x + dir.y*v00.y + dir.z*v00.z);
- float t = Oz * invDz;
-
- if(t > 0.0f && t < isect->t) {
- /* compute and check barycentric u */
- float Ox = v11.w + P.x*v11.x + P.y*v11.y + P.z*v11.z;
- float Dx = dir.x*v11.x + dir.y*v11.y + dir.z*v11.z;
- float u = Ox + t*Dx;
-
- if(u >= 0.0f) {
- /* compute and check barycentric v */
- float4 v22 = kernel_tex_fetch(__tri_woop, triAddr*TRI_NODE_SIZE+2);
- float Oy = v22.w + P.x*v22.x + P.y*v22.y + P.z*v22.z;
- float Dy = dir.x*v22.x + dir.y*v22.y + dir.z*v22.z;
- float v = Oy + t*Dy;
-
- if(v >= 0.0f && u + v <= 1.0f) {
- /* record intersection */
- isect->prim = triAddr;
- isect->object = object;
- isect->u = u;
- isect->v = v;
- isect->t = t;
- }
- }
- }
-}
-
-__device_inline bool scene_intersect(KernelGlobals *kg, const Ray *ray, const bool isshadowray, Intersection *isect)
-{
- /* traversal stack in CUDA thread-local memory */
- int traversalStack[QBVH_STACK_SIZE];
- traversalStack[0] = ENTRYPOINT_SENTINEL;
-
- /* traversal variables in registers */
- int stackPtr = 0;
- int nodeAddr = kernel_data.bvh.root;
-
- /* ray parameters in registers */
- const float tmax = ray->t;
- float3 P = ray->P;
- float3 idir = qbvh_inverse_direction(ray->D);
- int object = ~0;
-
- isect->t = tmax;
- isect->object = ~0;
- isect->prim = ~0;
- isect->u = 0.0f;
- isect->v = 0.0f;
-
- /* traversal loop */
- do {
- do
- {
- /* traverse internal nodes */
- while(nodeAddr >= 0 && nodeAddr != ENTRYPOINT_SENTINEL)
- {
- int traverseChild, nodeAddrChild[4];
-
- qbvh_node_intersect(kg, &traverseChild, nodeAddrChild,
- P, idir, isect->t, nodeAddr);
-
- if(traverseChild & 1) {
- ++stackPtr;
- traversalStack[stackPtr] = nodeAddrChild[0];
- }
-
- if(traverseChild & 2) {
- ++stackPtr;
- traversalStack[stackPtr] = nodeAddrChild[1];
- }
- if(traverseChild & 4) {
- ++stackPtr;
- traversalStack[stackPtr] = nodeAddrChild[2];
- }
-
- if(traverseChild & 8) {
- ++stackPtr;
- traversalStack[stackPtr] = nodeAddrChild[3];
- }
-
- nodeAddr = traversalStack[stackPtr];
- --stackPtr;
- }
-
- /* if node is leaf, fetch triangle list */
- if(nodeAddr < 0) {
- float4 leaf = kernel_tex_fetch(__bvh_nodes, (-nodeAddr-1)*QBVH_NODE_SIZE+(QBVH_NODE_SIZE-2));
- int primAddr = __float_as_int(leaf.x);
-
-#ifdef __INSTANCING__
- if(primAddr >= 0) {
-#endif
- int primAddr2 = __float_as_int(leaf.y);
-
- /* pop */
- nodeAddr = traversalStack[stackPtr];
- --stackPtr;
-
- /* triangle intersection */
- while(primAddr < primAddr2) {
- /* intersect ray against triangle */
- qbvh_triangle_intersect(kg, isect, P, idir, object, primAddr);
-
- /* shadow ray early termination */
- if(isshadowray && isect->prim != ~0)
- return true;
-
- primAddr++;
- }
-#ifdef __INSTANCING__
- }
- else {
- /* instance push */
- object = kernel_tex_fetch(__prim_object, -primAddr-1);
-
- qbvh_instance_push(kg, object, ray, &P, &idir, &isect->t, tmax);
-
- ++stackPtr;
- traversalStack[stackPtr] = ENTRYPOINT_SENTINEL;
-
- nodeAddr = kernel_tex_fetch(__object_node, object);
- }
-#endif
- }
- } while(nodeAddr != ENTRYPOINT_SENTINEL);
-
-#ifdef __INSTANCING__
- if(stackPtr >= 0) {
- kernel_assert(object != ~0);
-
- /* instance pop */
- qbvh_instance_pop(kg, object, ray, &P, &idir, &isect->t, tmax);
- object = ~0;
- nodeAddr = traversalStack[stackPtr];
- --stackPtr;
- }
-#endif
- } while(nodeAddr != ENTRYPOINT_SENTINEL);
-
- return (isect->prim != ~0);
-}
-
-__device_inline float3 ray_offset(float3 P, float3 Ng)
-{
-#ifdef __INTERSECTION_REFINE__
- const float epsilon_f = 1e-5f;
- const int epsilon_i = 32;
-
- float3 res;
-
- /* x component */
- if(fabsf(P.x) < epsilon_f) {
- res.x = P.x + Ng.x*epsilon_f;
- }
- else {
- uint ix = __float_as_uint(P.x);
- ix += ((ix ^ __float_as_uint(Ng.x)) >> 31)? -epsilon_i: epsilon_i;
- res.x = __uint_as_float(ix);
- }
-
- /* y component */
- if(fabsf(P.y) < epsilon_f) {
- res.y = P.y + Ng.y*epsilon_f;
- }
- else {
- uint iy = __float_as_uint(P.y);
- iy += ((iy ^ __float_as_uint(Ng.y)) >> 31)? -epsilon_i: epsilon_i;
- res.y = __uint_as_float(iy);
- }
-
- /* z component */
- if(fabsf(P.z) < epsilon_f) {
- res.z = P.z + Ng.z*epsilon_f;
- }
- else {
- uint iz = __float_as_uint(P.z);
- iz += ((iz ^ __float_as_uint(Ng.z)) >> 31)? -epsilon_i: epsilon_i;
- res.z = __uint_as_float(iz);
- }
-
- return res;
-#else
- const float epsilon_f = 1e-4f;
- return P + epsilon_f*Ng;
-#endif
-}
-
-__device_inline float3 bvh_triangle_refine(KernelGlobals *kg, const Intersection *isect, const Ray *ray)
-{
- float3 P = ray->P;
- float3 D = ray->D;
- float t = isect->t;
-
-#ifdef __INTERSECTION_REFINE__
- if(isect->object != ~0) {
- Transform tfm = object_fetch_transform(kg, isect->object, OBJECT_INVERSE_TRANSFORM);
-
- P = transform_point(&tfm, P);
- D = transform_direction(&tfm, D*t);
- D = normalize_len(D, &t);
- }
-
- P = P + D*t;
-
- float4 v00 = kernel_tex_fetch(__tri_woop, isect->prim*TRI_NODE_SIZE+0);
- float Oz = v00.w - P.x*v00.x - P.y*v00.y - P.z*v00.z;
- float invDz = 1.0f/(D.x*v00.x + D.y*v00.y + D.z*v00.z);
- float rt = Oz * invDz;
-
- P = P + D*rt;
-
- if(isect->object != ~0) {
- Transform tfm = object_fetch_transform(kg, isect->object, OBJECT_TRANSFORM);
- P = transform_point(&tfm, P);
- }
-
- return P;
-#else
- return P + D*t;
-#endif
-}
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/kernel_shader.h b/intern/cycles/kernel/kernel_shader.h
index b57e27bc8ed..86886a6a231 100644
--- a/intern/cycles/kernel/kernel_shader.h
+++ b/intern/cycles/kernel/kernel_shader.h
@@ -27,22 +27,36 @@
*/
#ifdef __OSL__
-
#include "osl_shader.h"
-
#endif
-#include "svm/bsdf.h"
-#include "svm/emissive.h"
-#include "svm/volume.h"
+#include "closure/bsdf.h"
+#include "closure/emissive.h"
+#include "closure/volume.h"
+
#include "svm/svm_bsdf.h"
#include "svm/svm.h"
-
CCL_NAMESPACE_BEGIN
/* ShaderData setup from incoming ray */
+#ifdef __OBJECT_MOTION__
+__device_noinline void shader_setup_object_transforms(KernelGlobals *kg, ShaderData *sd, float time)
+{
+ /* note that this is a separate non-inlined function to work around crash
+ * on CUDA sm 2.0, otherwise kernel execution crashes (compiler bug?) */
+ if(sd->flag & SD_OBJECT_MOTION) {
+ sd->ob_tfm = object_fetch_transform_motion(kg, sd->object, time);
+ sd->ob_itfm= transform_quick_inverse(sd->ob_tfm);
+ }
+ else {
+ sd->ob_tfm = object_fetch_transform(kg, sd->object, OBJECT_TRANSFORM);
+ sd->ob_itfm = object_fetch_transform(kg, sd->object, OBJECT_INVERSE_TRANSFORM);
+ }
+}
+#endif
+
__device_inline void shader_setup_from_ray(KernelGlobals *kg, ShaderData *sd,
const Intersection *isect, const Ray *ray)
{
@@ -67,11 +81,12 @@ __device_inline void shader_setup_from_ray(KernelGlobals *kg, ShaderData *sd,
sd->v = isect->v;
#endif
- /* matrices and time */
-#ifdef __MOTION__
- sd->ob_tfm = object_fetch_transform(kg, sd->object, ray->time, OBJECT_TRANSFORM);
- sd->ob_itfm = object_fetch_transform(kg, sd->object, ray->time, OBJECT_INVERSE_TRANSFORM);
+ sd->flag = kernel_tex_fetch(__shader_flag, (shader & SHADER_MASK)*2);
+ sd->flag |= kernel_tex_fetch(__object_flag, sd->object);
+ /* matrices and time */
+#ifdef __OBJECT_MOTION__
+ shader_setup_object_transforms(kg, sd, ray->time);
sd->time = ray->time;
#endif
@@ -87,9 +102,6 @@ __device_inline void shader_setup_from_ray(KernelGlobals *kg, ShaderData *sd,
if(sd->shader & SHADER_SMOOTH_NORMAL)
sd->N = triangle_smooth_normal(kg, sd->prim, sd->u, sd->v);
- sd->flag = kernel_tex_fetch(__shader_flag, (sd->shader & SHADER_MASK)*2);
- sd->flag |= kernel_tex_fetch(__object_flag, sd->object);
-
#ifdef __DPDU__
/* dPdu/dPdv */
triangle_dPdudv(kg, &sd->dPdu, &sd->dPdv, sd->prim);
@@ -171,11 +183,17 @@ __device void shader_setup_from_sample(KernelGlobals *kg, ShaderData *sd,
}
#endif
-#ifdef __MOTION__
- sd->time = time;
+ sd->flag = kernel_tex_fetch(__shader_flag, (sd->shader & SHADER_MASK)*2);
+ if(sd->object != -1) {
+ sd->flag |= kernel_tex_fetch(__object_flag, sd->object);
- sd->ob_tfm = object_fetch_transform(kg, sd->object, time, OBJECT_TRANSFORM);
- sd->ob_itfm = object_fetch_transform(kg, sd->object, time, OBJECT_INVERSE_TRANSFORM);
+#ifdef __OBJECT_MOTION__
+ shader_setup_object_transforms(kg, sd, time);
+ }
+
+ sd->time = time;
+#else
+ }
#endif
/* smooth normal */
@@ -188,10 +206,6 @@ __device void shader_setup_from_sample(KernelGlobals *kg, ShaderData *sd,
#endif
}
- sd->flag = kernel_tex_fetch(__shader_flag, (sd->shader & SHADER_MASK)*2);
- if(sd->object != -1)
- sd->flag |= kernel_tex_fetch(__object_flag, sd->object);
-
#ifdef __DPDU__
/* dPdu/dPdv */
if(sd->prim == ~0) {
@@ -275,7 +289,7 @@ __device_inline void shader_setup_from_background(KernelGlobals *kg, ShaderData
sd->I = -sd->P;
sd->shader = kernel_data.background.shader;
sd->flag = kernel_tex_fetch(__shader_flag, (sd->shader & SHADER_MASK)*2);
-#ifdef __MOTION__
+#ifdef __OBJECT_MOTION__
sd->time = ray->time;
#endif
sd->ray_length = 0.0f;
@@ -483,18 +497,22 @@ __device int shader_bsdf_sample_closure(KernelGlobals *kg, const ShaderData *sd,
__device void shader_bsdf_blur(KernelGlobals *kg, ShaderData *sd, float roughness)
{
-#ifndef __OSL__
#ifdef __MULTI_CLOSURE__
for(int i = 0; i< sd->num_closure; i++) {
ShaderClosure *sc = &sd->closure[i];
- if(CLOSURE_IS_BSDF(sc->type))
- svm_bsdf_blur(sc, roughness);
+ if(CLOSURE_IS_BSDF(sc->type)) {
+#ifdef __OSL__
+ if (kernel_osl_use(kg))
+ OSLShader::bsdf_blur(sc, roughness);
+ else
+#endif
+ svm_bsdf_blur(sc, roughness);
+ }
}
#else
svm_bsdf_blur(&sd->closure, roughness);
#endif
-#endif
}
__device float3 shader_bsdf_transparency(KernelGlobals *kg, ShaderData *sd)
@@ -704,16 +722,16 @@ __device float3 shader_volume_eval_phase(KernelGlobals *kg, ShaderData *sd,
if(CLOSURE_IS_VOLUME(sc->type)) {
#ifdef __OSL__
if (kernel_osl_use(kg))
- eval += OSLShader::volume_eval_phase(sd, sc, omega_in, omega_out);
+ eval += OSLShader::volume_eval_phase(sc, omega_in, omega_out);
else
#endif
- eval += volume_eval_phase(sd, sc, omega_in, omega_out);
+ eval += volume_eval_phase(sc, omega_in, omega_out);
}
}
return eval;
#else
- return volume_eval_phase(sd, &sd->closure, omega_in, omega_out);
+ return volume_eval_phase(&sd->closure, omega_in, omega_out);
#endif
}
diff --git a/intern/cycles/kernel/kernel_triangle.h b/intern/cycles/kernel/kernel_triangle.h
index f57c59a45eb..e39ae1d4fbc 100644
--- a/intern/cycles/kernel/kernel_triangle.h
+++ b/intern/cycles/kernel/kernel_triangle.h
@@ -68,6 +68,17 @@ __device_inline float3 triangle_normal_MT(KernelGlobals *kg, int tri_index, int
#endif
}
+/* Return 3 triangle vertex locations */
+__device_inline void triangle_vertices(KernelGlobals *kg, int tri_index, float3 P[3])
+{
+ /* load triangle vertices */
+ float3 tri_vindex = float4_to_float3(kernel_tex_fetch(__tri_vindex, tri_index));
+
+ P[0] = float4_to_float3(kernel_tex_fetch(__tri_verts, __float_as_int(tri_vindex.x)));
+ P[1] = float4_to_float3(kernel_tex_fetch(__tri_verts, __float_as_int(tri_vindex.y)));
+ P[2] = float4_to_float3(kernel_tex_fetch(__tri_verts, __float_as_int(tri_vindex.z)));
+}
+
__device_inline float3 triangle_smooth_normal(KernelGlobals *kg, int tri_index, float u, float v)
{
/* load triangle vertices */
@@ -201,10 +212,10 @@ __device float4 triangle_motion_vector(KernelGlobals *kg, ShaderData *sd)
* transformation was set match the world/object space of motion_pre/post */
Transform tfm;
- tfm = object_fetch_transform(kg, sd->object, TIME_INVALID, OBJECT_TRANSFORM_MOTION_PRE);
+ tfm = object_fetch_transform(kg, sd->object, OBJECT_TRANSFORM_MOTION_PRE);
motion_pre = transform_point(&tfm, motion_pre);
- tfm = object_fetch_transform(kg, sd->object, TIME_INVALID, OBJECT_TRANSFORM_MOTION_POST);
+ tfm = object_fetch_transform(kg, sd->object, OBJECT_TRANSFORM_MOTION_POST);
motion_post = transform_point(&tfm, motion_post);
float3 P;
diff --git a/intern/cycles/kernel/kernel_types.h b/intern/cycles/kernel/kernel_types.h
index ce21ab994f0..98d998351a7 100644
--- a/intern/cycles/kernel/kernel_types.h
+++ b/intern/cycles/kernel/kernel_types.h
@@ -29,13 +29,15 @@
CCL_NAMESPACE_BEGIN
/* constants */
-#define OBJECT_SIZE 16
+#define OBJECT_SIZE 22
#define LIGHT_SIZE 4
#define FILTER_TABLE_SIZE 256
#define RAMP_TABLE_SIZE 256
#define PARTICLE_SIZE 5
#define TIME_INVALID FLT_MAX
+#define TEX_NUM_FLOAT_IMAGES 5
+
/* device capabilities */
#ifdef __KERNEL_CPU__
#define __KERNEL_SHADING__
@@ -108,11 +110,15 @@ CCL_NAMESPACE_BEGIN
#define __PASSES__
#define __BACKGROUND_MIS__
#define __AO__
-//#define __MOTION__
+#define __CAMERA_MOTION__
+
+#ifndef __KERNEL_CUDA__
+#define __OBJECT_MOTION__
+#endif
+
#endif
//#define __SOBOL_FULL_SCREEN__
-//#define __QBVH__
/* Shader Evaluation */
@@ -129,7 +135,7 @@ enum PathTraceDimension {
PRNG_FILTER_V = 1,
PRNG_LENS_U = 2,
PRNG_LENS_V = 3,
-#ifdef __MOTION__
+#ifdef __CAMERA_MOTION__
PRNG_TIME = 4,
PRNG_UNUSED = 5,
PRNG_BASE_NUM = 6,
@@ -148,9 +154,7 @@ enum PathTraceDimension {
PRNG_BOUNCE_NUM = 8
};
-/* these flag values correspond exactly to OSL defaults, so be careful not to
- * change this, or if you do, set the "raytypes" shading system attribute with
- * your own new ray types and bitflag values.
+/* these flags values correspond to raytypes in osl.cpp, so keep them in sync!
*
* for ray visibility tests in BVH traversal, the upper 20 bits are used for
* layer visibility tests. */
@@ -370,6 +374,9 @@ typedef struct ShaderClosure {
float data0;
float data1;
+ float3 N;
+ float3 T;
+
} ShaderClosure;
/* Shader Data
@@ -408,7 +415,7 @@ typedef struct ShaderData {
/* view/incoming direction */
float3 I;
/* shader id */
- int shader;
+ int shader;
/* booleans describing shader, see ShaderDataFlag */
int flag;
@@ -426,13 +433,6 @@ typedef struct ShaderData {
/* length of the ray being shaded */
float ray_length;
-#ifdef __MOTION__
- /* object <-> world space transformations, cached to avoid
- * re-interpolating them constantly for shading */
- Transform ob_tfm;
- Transform ob_itfm;
-#endif
-
#ifdef __RAY_DIFFERENTIALS__
/* differential of P. these are orthogonal to Ng, not N */
differential3 dP;
@@ -448,6 +448,13 @@ typedef struct ShaderData {
float3 dPdu, dPdv;
#endif
+#ifdef __OBJECT_MOTION__
+ /* object <-> world space transformations, cached to avoid
+ * re-interpolating them constantly for shading */
+ Transform ob_tfm;
+ Transform ob_itfm;
+#endif
+
#ifdef __MULTI_CLOSURE__
/* Closure data, we store a fixed array of closures */
ShaderClosure closure[MAX_CLOSURE];
@@ -511,7 +518,9 @@ typedef struct KernelCamera {
/* more matrices */
Transform screentoworld;
Transform rastertoworld;
- Transform ndctoworld;
+ /* work around cuda sm 2.0 crash, this seems to
+ * cross some limit in combination with motion
+ * Transform ndctoworld; */
Transform worldtoscreen;
Transform worldtoraster;
Transform worldtondc;
@@ -627,7 +636,8 @@ typedef struct KernelBVH {
/* root node */
int root;
int attributes_map_stride;
- int pad1, pad2;
+ int have_motion;
+ int pad2;
} KernelBVH;
typedef struct KernelData {
diff --git a/intern/cycles/kernel/osl/CMakeLists.txt b/intern/cycles/kernel/osl/CMakeLists.txt
index d4ea8b12f5a..8938b16a48f 100644
--- a/intern/cycles/kernel/osl/CMakeLists.txt
+++ b/intern/cycles/kernel/osl/CMakeLists.txt
@@ -8,25 +8,16 @@ set(INC
../../device
)
+set(INC_SYS
+
+)
+
set(SRC
background.cpp
- bsdf_ashikhmin_velvet.cpp
- bsdf_diffuse.cpp
- bsdf_oren_nayar.cpp
- bsdf_phong.cpp
- bsdf_microfacet.cpp
- bsdf_reflection.cpp
- bsdf_refraction.cpp
- bsdf_transparent.cpp
- bsdf_ward.cpp
- bsdf_westin.cpp
- bssrdf.cpp
- debug.cpp
emissive.cpp
osl_closures.cpp
osl_services.cpp
osl_shader.cpp
- vol_subsurface.cpp
)
set(HEADER_SRC
@@ -39,7 +30,7 @@ set(HEADER_SRC
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${RTTI_DISABLE_FLAGS}")
include_directories(${INC})
+include_directories(SYSTEM ${INC_SYS})
add_library(cycles_kernel_osl ${SRC} ${HEADER_SRC})
-add_subdirectory(nodes)
diff --git a/intern/cycles/kernel/osl/background.cpp b/intern/cycles/kernel/osl/background.cpp
index 81812a46b6c..b6e9473b7bf 100644
--- a/intern/cycles/kernel/osl/background.cpp
+++ b/intern/cycles/kernel/osl/background.cpp
@@ -46,23 +46,16 @@ using namespace OSL;
/// to return a color in background shaders. No methods,
/// only the weight is taking into account
///
-class GenericBackgroundClosure : public BackgroundClosure {
+class GenericBackgroundClosure : public OSL::BackgroundClosure {
public:
GenericBackgroundClosure() {}
void setup() {};
-
size_t memsize() const { return sizeof(*this); }
-
const char *name() const { return "background"; }
-
- void print_on(std::ostream &out) const {
- out << name() << " ()";
- }
-
+ void print_on(std::ostream &out) const { out << name() << " ()"; }
};
-
/// Holdout closure
///
/// This will be used by the shader to mark the
@@ -75,26 +68,29 @@ public:
HoldoutClosure () : ClosurePrimitive(Holdout) {}
void setup() {};
-
size_t memsize() const { return sizeof(*this); }
-
const char *name() const { return "holdout"; }
-
- void print_on(std::ostream &out) const {
- out << name() << " ()";
- }
+ void print_on(std::ostream &out) const { out << name() << " ()"; }
};
-ClosureParam closure_background_params[] = {
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(GenericBackgroundClosure)
-};
+ClosureParam *closure_background_params()
+{
+ static ClosureParam params[] = {
+ CLOSURE_STRING_KEYPARAM("label"),
+ CLOSURE_FINISH_PARAM(GenericBackgroundClosure)
+ };
+ return params;
+}
CLOSURE_PREPARE(closure_background_prepare, GenericBackgroundClosure)
-ClosureParam closure_holdout_params[] = {
- CLOSURE_FINISH_PARAM(HoldoutClosure)
-};
+ClosureParam *closure_holdout_params()
+{
+ static ClosureParam params[] = {
+ CLOSURE_FINISH_PARAM(HoldoutClosure)
+ };
+ return params;
+}
CLOSURE_PREPARE(closure_holdout_prepare, HoldoutClosure)
diff --git a/intern/cycles/kernel/osl/bsdf_ashikhmin_velvet.cpp b/intern/cycles/kernel/osl/bsdf_ashikhmin_velvet.cpp
deleted file mode 100644
index cb6be6959f5..00000000000
--- a/intern/cycles/kernel/osl/bsdf_ashikhmin_velvet.cpp
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2011, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-
-#include "osl_closures.h"
-
-#include "util_math.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-class AshikhminVelvetClosure : public BSDFClosure {
-public:
- Vec3 m_N;
- float m_sigma;
- float m_invsigma2;
-
- AshikhminVelvetClosure() : BSDFClosure(Labels::DIFFUSE) {}
-
- void setup()
- {
- m_sigma = max(m_sigma, 0.01f);
- m_invsigma2 = 1.0f / (m_sigma * m_sigma);
- }
-
- bool mergeable(const ClosurePrimitive *other) const {
- const AshikhminVelvetClosure *comp = (const AshikhminVelvetClosure *)other;
- return m_N == comp->m_N && m_sigma == comp->m_sigma &&
- BSDFClosure::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "ashikhmin_velvet"; }
-
- void print_on(std::ostream &out) const
- {
- out << name() << " (";
- out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), ";
- out << m_sigma;
- out << ")";
- }
-
- float albedo(const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_reflect(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- float cosNO = m_N.dot(omega_out);
- float cosNI = m_N.dot(omega_in);
- if (cosNO > 0 && cosNI > 0) {
- Vec3 H = omega_in + omega_out;
- H.normalize();
-
- float cosNH = m_N.dot(H);
- float cosHO = fabsf(omega_out.dot(H));
-
- float cosNHdivHO = cosNH / cosHO;
- cosNHdivHO = max(cosNHdivHO, 0.00001f);
-
- float fac1 = 2 * fabsf(cosNHdivHO * cosNO);
- float fac2 = 2 * fabsf(cosNHdivHO * cosNI);
-
- float sinNH2 = 1 - cosNH * cosNH;
- float sinNH4 = sinNH2 * sinNH2;
- float cotangent2 = (cosNH * cosNH) / sinNH2;
-
- float D = expf(-cotangent2 * m_invsigma2) * m_invsigma2 * float(M_1_PI) / sinNH4;
- float G = min(1.0f, min(fac1, fac2)); // TODO: derive G from D analytically
-
- float out = 0.25f * (D * G) / cosNO;
-
- pdf = 0.5f * (float) M_1_PI;
- return Color3(out, out, out);
- }
- return Color3(0, 0, 0);
- }
-
- Color3 eval_transmit(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- ustring sample(const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- // we are viewing the surface from above - send a ray out with uniform
- // distribution over the hemisphere
- sample_uniform_hemisphere(m_N, omega_out, randu, randv, omega_in, pdf);
- if (Ng.dot(omega_in) > 0) {
- Vec3 H = omega_in + omega_out;
- H.normalize();
-
- float cosNI = m_N.dot(omega_in);
- float cosNO = m_N.dot(omega_out);
- float cosNH = m_N.dot(H);
- float cosHO = fabsf(omega_out.dot(H));
-
- float cosNHdivHO = cosNH / cosHO;
- cosNHdivHO = max(cosNHdivHO, 0.00001f);
-
- float fac1 = 2 * fabsf(cosNHdivHO * cosNO);
- float fac2 = 2 * fabsf(cosNHdivHO * cosNI);
-
- float sinNH2 = 1 - cosNH * cosNH;
- float sinNH4 = sinNH2 * sinNH2;
- float cotangent2 = (cosNH * cosNH) / sinNH2;
-
- float D = expf(-cotangent2 * m_invsigma2) * m_invsigma2 * float(M_1_PI) / sinNH4;
- float G = min(1.0f, min(fac1, fac2)); // TODO: derive G from D analytically
-
- float power = 0.25f * (D * G) / cosNO;
-
- eval.setValue(power, power, power);
-
- // TODO: find a better approximation for the retroreflective bounce
- domega_in_dx = (2 * m_N.dot(domega_out_dx)) * m_N - domega_out_dx;
- domega_in_dy = (2 * m_N.dot(domega_out_dy)) * m_N - domega_out_dy;
- domega_in_dx *= 125;
- domega_in_dy *= 125;
- }
- else
- pdf = 0;
- return Labels::REFLECT;
- }
-
-};
-
-
-
-ClosureParam bsdf_ashikhmin_velvet_params[] = {
- CLOSURE_VECTOR_PARAM(AshikhminVelvetClosure, m_N),
- CLOSURE_FLOAT_PARAM(AshikhminVelvetClosure, m_sigma),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(AshikhminVelvetClosure)
-};
-
-CLOSURE_PREPARE(bsdf_ashikhmin_velvet_prepare, AshikhminVelvetClosure)
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/osl/bsdf_diffuse.cpp b/intern/cycles/kernel/osl/bsdf_diffuse.cpp
deleted file mode 100644
index 582ac01d959..00000000000
--- a/intern/cycles/kernel/osl/bsdf_diffuse.cpp
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2011, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-
-#include "osl_closures.h"
-
-#include "util_math.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-class DiffuseClosure : public BSDFClosure {
-public:
- Vec3 m_N;
-
- DiffuseClosure() : BSDFClosure(Labels::DIFFUSE) {}
-
- void setup() {};
-
- bool mergeable(const ClosurePrimitive *other) const {
- const DiffuseClosure *comp = (const DiffuseClosure *)other;
- return m_N == comp->m_N && BSDFClosure::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "diffuse"; }
-
- void print_on(std::ostream &out) const
- {
- out << name() << " ((" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "))";
- }
-
- float albedo(const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_reflect(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- float cos_pi = max(m_N.dot(omega_in), 0.0f) * (float) M_1_PI;
- pdf = cos_pi;
- return Color3(cos_pi, cos_pi, cos_pi);
- }
-
- Color3 eval_transmit(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- ustring sample(const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- // we are viewing the surface from the right side - send a ray out with cosine
- // distribution over the hemisphere
- sample_cos_hemisphere(m_N, omega_out, randu, randv, omega_in, pdf);
- if (Ng.dot(omega_in) > 0) {
- eval.setValue(pdf, pdf, pdf);
- // TODO: find a better approximation for the diffuse bounce
- domega_in_dx = (2 * m_N.dot(domega_out_dx)) * m_N - domega_out_dx;
- domega_in_dy = (2 * m_N.dot(domega_out_dy)) * m_N - domega_out_dy;
- domega_in_dx *= 125;
- domega_in_dy *= 125;
- }
- else
- pdf = 0;
- return Labels::REFLECT;
- }
-};
-
-
-
-class TranslucentClosure : public BSDFClosure {
-public:
- Vec3 m_N;
-
- TranslucentClosure() : BSDFClosure(Labels::DIFFUSE, Back) {}
-
- void setup() {};
-
- bool mergeable(const ClosurePrimitive *other) const {
- const TranslucentClosure *comp = (const TranslucentClosure *)other;
- return m_N == comp->m_N && BSDFClosure::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "translucent"; }
-
- void print_on(std::ostream &out) const
- {
- out << name() << " ((" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "))";
- }
-
- Color3 eval_reflect(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- float albedo(const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_transmit(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- float cos_pi = max(-m_N.dot(omega_in), 0.0f) * (float) M_1_PI;
- pdf = cos_pi;
- return Color3(cos_pi, cos_pi, cos_pi);
- }
-
- ustring sample(const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- // we are viewing the surface from the right side - send a ray out with cosine
- // distribution over the hemisphere
- sample_cos_hemisphere(-m_N, omega_out, randu, randv, omega_in, pdf);
- if (Ng.dot(omega_in) < 0) {
- eval.setValue(pdf, pdf, pdf);
- // TODO: find a better approximation for the diffuse bounce
- domega_in_dx = (2 * m_N.dot(domega_out_dx)) * m_N - domega_out_dx;
- domega_in_dy = (2 * m_N.dot(domega_out_dy)) * m_N - domega_out_dy;
- domega_in_dx *= -125;
- domega_in_dy *= -125;
- }
- else
- pdf = 0;
- return Labels::TRANSMIT;
- }
-};
-
-ClosureParam bsdf_diffuse_params[] = {
- CLOSURE_VECTOR_PARAM(DiffuseClosure, m_N),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(DiffuseClosure)
-};
-
-ClosureParam bsdf_translucent_params[] = {
- CLOSURE_VECTOR_PARAM(TranslucentClosure, m_N),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(TranslucentClosure)
-};
-
-CLOSURE_PREPARE(bsdf_diffuse_prepare, DiffuseClosure)
-CLOSURE_PREPARE(bsdf_translucent_prepare, TranslucentClosure)
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/osl/bsdf_microfacet.cpp b/intern/cycles/kernel/osl/bsdf_microfacet.cpp
deleted file mode 100644
index 09730d8c3e1..00000000000
--- a/intern/cycles/kernel/osl/bsdf_microfacet.cpp
+++ /dev/null
@@ -1,542 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2011, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-
-#include "osl_closures.h"
-
-#include "util_math.h"
-
-using namespace OSL;
-
-CCL_NAMESPACE_BEGIN
-
-// TODO: fresnel_dielectric is only used for derivatives, could be optimized
-
-// TODO: refactor these two classes so they share everything by the microfacet
-// distribution terms
-
-// microfacet model with GGX facet distribution
-// see http://www.graphics.cornell.edu/~bjw/microfacetbsdf.pdf
-template <int Refractive = 0>
-class MicrofacetGGXClosure : public BSDFClosure {
-public:
- Vec3 m_N;
- float m_ag; // width parameter (roughness)
- float m_eta; // index of refraction (for fresnel term)
- MicrofacetGGXClosure() : BSDFClosure(Labels::GLOSSY, Refractive ? Back : Front) { m_eta = 1.0f; }
-
- void setup()
- {
- m_ag = clamp(m_ag, 1e-5f, 1.0f);
- }
-
- bool mergeable(const ClosurePrimitive *other) const {
- const MicrofacetGGXClosure *comp = (const MicrofacetGGXClosure *)other;
- return m_N == comp->m_N && m_ag == comp->m_ag &&
- m_eta == comp->m_eta && BSDFClosure::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const {
- return Refractive ? "microfacet_ggx_refraction" : "microfacet_ggx";
- }
-
- void print_on(std::ostream &out) const {
- out << name() << " (";
- out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), ";
- out << m_ag << ", ";
- out << m_eta;
- out << ")";
- }
-
- float albedo(const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_reflect(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- if (Refractive == 1) return Color3(0, 0, 0);
- float cosNO = m_N.dot(omega_out);
- float cosNI = m_N.dot(omega_in);
- if (cosNI > 0 && cosNO > 0) {
- // get half vector
- Vec3 Hr = omega_in + omega_out;
- Hr.normalize();
- // eq. 20: (F*G*D)/(4*in*on)
- // eq. 33: first we calculate D(m) with m=Hr:
- float alpha2 = m_ag * m_ag;
- float cosThetaM = m_N.dot(Hr);
- float cosThetaM2 = cosThetaM * cosThetaM;
- float tanThetaM2 = (1 - cosThetaM2) / cosThetaM2;
- float cosThetaM4 = cosThetaM2 * cosThetaM2;
- float D = alpha2 / ((float) M_PI * cosThetaM4 * (alpha2 + tanThetaM2) * (alpha2 + tanThetaM2));
- // eq. 34: now calculate G1(i,m) and G1(o,m)
- float G1o = 2 / (1 + sqrtf(1 + alpha2 * (1 - cosNO * cosNO) / (cosNO * cosNO)));
- float G1i = 2 / (1 + sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI)));
- float G = G1o * G1i;
- float out = (G * D) * 0.25f / cosNO;
- // eq. 24
- float pm = D * cosThetaM;
- // convert into pdf of the sampled direction
- // eq. 38 - but see also:
- // eq. 17 in http://www.graphics.cornell.edu/~bjw/wardnotes.pdf
- pdf = pm * 0.25f / Hr.dot(omega_out);
- return Color3(out, out, out);
- }
- return Color3(0, 0, 0);
- }
-
- Color3 eval_transmit(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- if (Refractive == 0) return Color3(0, 0, 0);
- float cosNO = m_N.dot(omega_out);
- float cosNI = m_N.dot(omega_in);
- if (cosNO <= 0 || cosNI >= 0)
- return Color3(0, 0, 0); // vectors on same side -- not possible
- // compute half-vector of the refraction (eq. 16)
- Vec3 ht = -(m_eta * omega_in + omega_out);
- Vec3 Ht = ht; Ht.normalize();
- float cosHO = Ht.dot(omega_out);
-
- float cosHI = Ht.dot(omega_in);
- // eq. 33: first we calculate D(m) with m=Ht:
- float alpha2 = m_ag * m_ag;
- float cosThetaM = m_N.dot(Ht);
- float cosThetaM2 = cosThetaM * cosThetaM;
- float tanThetaM2 = (1 - cosThetaM2) / cosThetaM2;
- float cosThetaM4 = cosThetaM2 * cosThetaM2;
- float D = alpha2 / ((float) M_PI * cosThetaM4 * (alpha2 + tanThetaM2) * (alpha2 + tanThetaM2));
- // eq. 34: now calculate G1(i,m) and G1(o,m)
- float G1o = 2 / (1 + sqrtf(1 + alpha2 * (1 - cosNO * cosNO) / (cosNO * cosNO)));
- float G1i = 2 / (1 + sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI)));
- float G = G1o * G1i;
- // probability
- float invHt2 = 1 / ht.dot(ht);
- pdf = D * fabsf(cosThetaM) * (fabsf(cosHI) * (m_eta * m_eta)) * invHt2;
- float out = (fabsf(cosHI * cosHO) * (m_eta * m_eta) * (G * D) * invHt2) / cosNO;
- return Color3(out, out, out);
- }
-
- ustring sample(const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- float cosNO = m_N.dot(omega_out);
- if (cosNO > 0) {
- Vec3 X, Y, Z = m_N;
- make_orthonormals(Z, X, Y);
- // generate a random microfacet normal m
- // eq. 35,36:
- // we take advantage of cos(atan(x)) == 1/sqrt(1+x^2)
- // and sin(atan(x)) == x/sqrt(1+x^2)
- float alpha2 = m_ag * m_ag;
- float tanThetaM2 = alpha2 * randu / (1 - randu);
- float cosThetaM = 1 / sqrtf(1 + tanThetaM2);
- float sinThetaM = cosThetaM * sqrtf(tanThetaM2);
- float phiM = 2 * float(M_PI) * randv;
- Vec3 m = (cosf(phiM) * sinThetaM) * X +
- (sinf(phiM) * sinThetaM) * Y +
- cosThetaM * Z;
- if (Refractive == 0) {
- float cosMO = m.dot(omega_out);
- if (cosMO > 0) {
- // eq. 39 - compute actual reflected direction
- omega_in = 2 * cosMO * m - omega_out;
- if (Ng.dot(omega_in) > 0) {
- // microfacet normal is visible to this ray
- // eq. 33
- float cosThetaM2 = cosThetaM * cosThetaM;
- float cosThetaM4 = cosThetaM2 * cosThetaM2;
- float D = alpha2 / (float(M_PI) * cosThetaM4 * (alpha2 + tanThetaM2) * (alpha2 + tanThetaM2));
- // eq. 24
- float pm = D * cosThetaM;
- // convert into pdf of the sampled direction
- // eq. 38 - but see also:
- // eq. 17 in http://www.graphics.cornell.edu/~bjw/wardnotes.pdf
- pdf = pm * 0.25f / cosMO;
- // eval BRDF*cosNI
- float cosNI = m_N.dot(omega_in);
- // eq. 34: now calculate G1(i,m) and G1(o,m)
- float G1o = 2 / (1 + sqrtf(1 + alpha2 * (1 - cosNO * cosNO) / (cosNO * cosNO)));
- float G1i = 2 / (1 + sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI)));
- float G = G1o * G1i;
- // eq. 20: (F*G*D)/(4*in*on)
- float out = (G * D) * 0.25f / cosNO;
- eval.setValue(out, out, out);
- domega_in_dx = (2 * m.dot(domega_out_dx)) * m - domega_out_dx;
- domega_in_dy = (2 * m.dot(domega_out_dy)) * m - domega_out_dy;
-
- /* disabled for now - gives texture filtering problems */
-#if 0
- // Since there is some blur to this reflection, make the
- // derivatives a bit bigger. In theory this varies with the
- // roughness but the exact relationship is complex and
- // requires more ops than are practical.
- domega_in_dx *= 10;
- domega_in_dy *= 10;
-#endif
- }
- }
- }
- else {
- // CAUTION: the i and o variables are inverted relative to the paper
- // eq. 39 - compute actual refractive direction
- Vec3 R, dRdx, dRdy;
- Vec3 T, dTdx, dTdy;
- bool inside;
- fresnel_dielectric(m_eta, m, omega_out, domega_out_dx, domega_out_dy,
- R, dRdx, dRdy,
- T, dTdx, dTdy,
- inside);
-
- if (!inside) {
- omega_in = T;
- domega_in_dx = dTdx;
- domega_in_dy = dTdy;
- // eq. 33
- float cosThetaM2 = cosThetaM * cosThetaM;
- float cosThetaM4 = cosThetaM2 * cosThetaM2;
- float D = alpha2 / (float(M_PI) * cosThetaM4 * (alpha2 + tanThetaM2) * (alpha2 + tanThetaM2));
- // eq. 24
- float pm = D * cosThetaM;
- // eval BRDF*cosNI
- float cosNI = m_N.dot(omega_in);
- // eq. 34: now calculate G1(i,m) and G1(o,m)
- float G1o = 2 / (1 + sqrtf(1 + alpha2 * (1 - cosNO * cosNO) / (cosNO * cosNO)));
- float G1i = 2 / (1 + sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI)));
- float G = G1o * G1i;
- // eq. 21
- float cosHI = m.dot(omega_in);
- float cosHO = m.dot(omega_out);
- float Ht2 = m_eta * cosHI + cosHO;
- Ht2 *= Ht2;
- float out = (fabsf(cosHI * cosHO) * (m_eta * m_eta) * (G * D)) / (cosNO * Ht2);
- // eq. 38 and eq. 17
- pdf = pm * (m_eta * m_eta) * fabsf(cosHI) / Ht2;
- eval.setValue(out, out, out);
-
- /* disabled for now - gives texture filtering problems */
-#if 0
- // Since there is some blur to this refraction, make the
- // derivatives a bit bigger. In theory this varies with the
- // roughness but the exact relationship is complex and
- // requires more ops than are practical.
- domega_in_dx *= 10;
- domega_in_dy *= 10;
-#endif
- }
- }
- }
- return Refractive ? Labels::TRANSMIT : Labels::REFLECT;
- }
-};
-
-// microfacet model with Beckmann facet distribution
-// see http://www.graphics.cornell.edu/~bjw/microfacetbsdf.pdf
-template <int Refractive = 0>
-class MicrofacetBeckmannClosure : public BSDFClosure {
-public:
- Vec3 m_N;
- float m_ab; // width parameter (roughness)
- float m_eta; // index of refraction (for fresnel term)
- MicrofacetBeckmannClosure() : BSDFClosure(Labels::GLOSSY, Refractive ? Back : Front) {
- }
-
- void setup()
- {
- m_ab = clamp(m_ab, 1e-5f, 1.0f);
- }
-
- bool mergeable(const ClosurePrimitive *other) const {
- const MicrofacetBeckmannClosure *comp = (const MicrofacetBeckmannClosure *)other;
- return m_N == comp->m_N && m_ab == comp->m_ab &&
- m_eta == comp->m_eta && BSDFClosure::mergeable(other);
- }
-
- size_t memsize() const {
- return sizeof(*this);
- }
-
- const char *name() const {
- return Refractive ? "microfacet_beckmann_refraction"
- : "microfacet_beckmann";
- }
-
- void print_on(std::ostream &out) const
- {
- out << name() << " (";
- out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), ";
- out << m_ab << ", ";
- out << m_eta;
- out << ")";
- }
-
- float albedo(const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_reflect(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- if (Refractive == 1) return Color3(0, 0, 0);
- float cosNO = m_N.dot(omega_out);
- float cosNI = m_N.dot(omega_in);
- if (cosNO > 0 && cosNI > 0) {
- // get half vector
- Vec3 Hr = omega_in + omega_out;
- Hr.normalize();
- // eq. 20: (F*G*D)/(4*in*on)
- // eq. 25: first we calculate D(m) with m=Hr:
- float alpha2 = m_ab * m_ab;
- float cosThetaM = m_N.dot(Hr);
- float cosThetaM2 = cosThetaM * cosThetaM;
- float tanThetaM2 = (1 - cosThetaM2) / cosThetaM2;
- float cosThetaM4 = cosThetaM2 * cosThetaM2;
- float D = expf(-tanThetaM2 / alpha2) / (float(M_PI) * alpha2 * cosThetaM4);
- // eq. 26, 27: now calculate G1(i,m) and G1(o,m)
- float ao = 1 / (m_ab * sqrtf((1 - cosNO * cosNO) / (cosNO * cosNO)));
- float ai = 1 / (m_ab * sqrtf((1 - cosNI * cosNI) / (cosNI * cosNI)));
- float G1o = ao < 1.6f ? (3.535f * ao + 2.181f * ao * ao) / (1 + 2.276f * ao + 2.577f * ao * ao) : 1.0f;
- float G1i = ai < 1.6f ? (3.535f * ai + 2.181f * ai * ai) / (1 + 2.276f * ai + 2.577f * ai * ai) : 1.0f;
- float G = G1o * G1i;
- float out = (G * D) * 0.25f / cosNO;
- // eq. 24
- float pm = D * cosThetaM;
- // convert into pdf of the sampled direction
- // eq. 38 - but see also:
- // eq. 17 in http://www.graphics.cornell.edu/~bjw/wardnotes.pdf
- pdf = pm * 0.25f / Hr.dot(omega_out);
- return Color3(out, out, out);
- }
- return Color3(0, 0, 0);
- }
-
- Color3 eval_transmit(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- if (Refractive == 0) return Color3(0, 0, 0);
- float cosNO = m_N.dot(omega_out);
- float cosNI = m_N.dot(omega_in);
- if (cosNO <= 0 || cosNI >= 0)
- return Color3(0, 0, 0);
- // compute half-vector of the refraction (eq. 16)
- Vec3 ht = -(m_eta * omega_in + omega_out);
- Vec3 Ht = ht; Ht.normalize();
- float cosHO = Ht.dot(omega_out);
-
- float cosHI = Ht.dot(omega_in);
- // eq. 33: first we calculate D(m) with m=Ht:
- float alpha2 = m_ab * m_ab;
- float cosThetaM = m_N.dot(Ht);
- float cosThetaM2 = cosThetaM * cosThetaM;
- float tanThetaM2 = (1 - cosThetaM2) / cosThetaM2;
- float cosThetaM4 = cosThetaM2 * cosThetaM2;
- float D = expf(-tanThetaM2 / alpha2) / (float(M_PI) * alpha2 * cosThetaM4);
- // eq. 26, 27: now calculate G1(i,m) and G1(o,m)
- float ao = 1 / (m_ab * sqrtf((1 - cosNO * cosNO) / (cosNO * cosNO)));
- float ai = 1 / (m_ab * sqrtf((1 - cosNI * cosNI) / (cosNI * cosNI)));
- float G1o = ao < 1.6f ? (3.535f * ao + 2.181f * ao * ao) / (1 + 2.276f * ao + 2.577f * ao * ao) : 1.0f;
- float G1i = ai < 1.6f ? (3.535f * ai + 2.181f * ai * ai) / (1 + 2.276f * ai + 2.577f * ai * ai) : 1.0f;
- float G = G1o * G1i;
- // probability
- float invHt2 = 1 / ht.dot(ht);
- pdf = D * fabsf(cosThetaM) * (fabsf(cosHI) * (m_eta * m_eta)) * invHt2;
- float out = (fabsf(cosHI * cosHO) * (m_eta * m_eta) * (G * D) * invHt2) / cosNO;
- return Color3(out, out, out);
- }
-
- ustring sample(const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- float cosNO = m_N.dot(omega_out);
- if (cosNO > 0) {
- Vec3 X, Y, Z = m_N;
- make_orthonormals(Z, X, Y);
- // generate a random microfacet normal m
- // eq. 35,36:
- // we take advantage of cos(atan(x)) == 1/sqrt(1+x^2)
- // and sin(atan(x)) == x/sqrt(1+x^2)
- float alpha2 = m_ab * m_ab;
- float tanThetaM = sqrtf(-alpha2 * logf(1 - randu));
- float cosThetaM = 1 / sqrtf(1 + tanThetaM * tanThetaM);
- float sinThetaM = cosThetaM * tanThetaM;
- float phiM = 2 * float(M_PI) * randv;
- Vec3 m = (cosf(phiM) * sinThetaM) * X +
- (sinf(phiM) * sinThetaM) * Y +
- cosThetaM * Z;
- if (Refractive == 0) {
- float cosMO = m.dot(omega_out);
- if (cosMO > 0) {
- // eq. 39 - compute actual reflected direction
- omega_in = 2 * cosMO * m - omega_out;
- if (Ng.dot(omega_in) > 0) {
- // microfacet normal is visible to this ray
- // eq. 25
- float cosThetaM2 = cosThetaM * cosThetaM;
- float tanThetaM2 = tanThetaM * tanThetaM;
- float cosThetaM4 = cosThetaM2 * cosThetaM2;
- float D = expf(-tanThetaM2 / alpha2) / (float(M_PI) * alpha2 * cosThetaM4);
- // eq. 24
- float pm = D * cosThetaM;
- // convert into pdf of the sampled direction
- // eq. 38 - but see also:
- // eq. 17 in http://www.graphics.cornell.edu/~bjw/wardnotes.pdf
- pdf = pm * 0.25f / cosMO;
- // Eval BRDF*cosNI
- float cosNI = m_N.dot(omega_in);
- // eq. 26, 27: now calculate G1(i,m) and G1(o,m)
- float ao = 1 / (m_ab * sqrtf((1 - cosNO * cosNO) / (cosNO * cosNO)));
- float ai = 1 / (m_ab * sqrtf((1 - cosNI * cosNI) / (cosNI * cosNI)));
- float G1o = ao < 1.6f ? (3.535f * ao + 2.181f * ao * ao) / (1 + 2.276f * ao + 2.577f * ao * ao) : 1.0f;
- float G1i = ai < 1.6f ? (3.535f * ai + 2.181f * ai * ai) / (1 + 2.276f * ai + 2.577f * ai * ai) : 1.0f;
- float G = G1o * G1i;
- // eq. 20: (F*G*D)/(4*in*on)
- float out = (G * D) * 0.25f / cosNO;
- eval.setValue(out, out, out);
- domega_in_dx = (2 * m.dot(domega_out_dx)) * m - domega_out_dx;
- domega_in_dy = (2 * m.dot(domega_out_dy)) * m - domega_out_dy;
-
- /* disabled for now - gives texture filtering problems */
-#if 0
- // Since there is some blur to this reflection, make the
- // derivatives a bit bigger. In theory this varies with the
- // roughness but the exact relationship is complex and
- // requires more ops than are practical.
- domega_in_dx *= 10;
- domega_in_dy *= 10;
-#endif
- }
- }
- }
- else {
- // CAUTION: the i and o variables are inverted relative to the paper
- // eq. 39 - compute actual refractive direction
- Vec3 R, dRdx, dRdy;
- Vec3 T, dTdx, dTdy;
- bool inside;
- fresnel_dielectric(m_eta, m, omega_out, domega_out_dx, domega_out_dy,
- R, dRdx, dRdy,
- T, dTdx, dTdy,
- inside);
- if (!inside) {
- omega_in = T;
- domega_in_dx = dTdx;
- domega_in_dy = dTdy;
- // eq. 33
- float cosThetaM2 = cosThetaM * cosThetaM;
- float tanThetaM2 = tanThetaM * tanThetaM;
- float cosThetaM4 = cosThetaM2 * cosThetaM2;
- float D = expf(-tanThetaM2 / alpha2) / (float(M_PI) * alpha2 * cosThetaM4);
- // eq. 24
- float pm = D * cosThetaM;
- // eval BRDF*cosNI
- float cosNI = m_N.dot(omega_in);
- // eq. 26, 27: now calculate G1(i,m) and G1(o,m)
- float ao = 1 / (m_ab * sqrtf((1 - cosNO * cosNO) / (cosNO * cosNO)));
- float ai = 1 / (m_ab * sqrtf((1 - cosNI * cosNI) / (cosNI * cosNI)));
- float G1o = ao < 1.6f ? (3.535f * ao + 2.181f * ao * ao) / (1 + 2.276f * ao + 2.577f * ao * ao) : 1.0f;
- float G1i = ai < 1.6f ? (3.535f * ai + 2.181f * ai * ai) / (1 + 2.276f * ai + 2.577f * ai * ai) : 1.0f;
- float G = G1o * G1i;
- // eq. 21
- float cosHI = m.dot(omega_in);
- float cosHO = m.dot(omega_out);
- float Ht2 = m_eta * cosHI + cosHO;
- Ht2 *= Ht2;
- float out = (fabsf(cosHI * cosHO) * (m_eta * m_eta) * (G * D)) / (cosNO * Ht2);
- // eq. 38 and eq. 17
- pdf = pm * (m_eta * m_eta) * fabsf(cosHI) / Ht2;
- eval.setValue(out, out, out);
-
- /* disabled for now - gives texture filtering problems */
-#if 0
- // Since there is some blur to this refraction, make the
- // derivatives a bit bigger. In theory this varies with the
- // roughness but the exact relationship is complex and
- // requires more ops than are practical.
- domega_in_dx *= 10;
- domega_in_dy *= 10;
-#endif
- }
- }
- }
- return Refractive ? Labels::TRANSMIT : Labels::REFLECT;
- }
-};
-
-
-
-ClosureParam bsdf_microfacet_ggx_params[] = {
- CLOSURE_VECTOR_PARAM(MicrofacetGGXClosure<0>, m_N),
- CLOSURE_FLOAT_PARAM(MicrofacetGGXClosure<0>, m_ag),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(MicrofacetGGXClosure<0>)
-};
-
-ClosureParam bsdf_microfacet_ggx_refraction_params[] = {
- CLOSURE_VECTOR_PARAM(MicrofacetGGXClosure<1>, m_N),
- CLOSURE_FLOAT_PARAM(MicrofacetGGXClosure<1>, m_ag),
- CLOSURE_FLOAT_PARAM(MicrofacetGGXClosure<1>, m_eta),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(MicrofacetGGXClosure<1>)
-};
-
-ClosureParam bsdf_microfacet_beckmann_params[] = {
- CLOSURE_VECTOR_PARAM(MicrofacetBeckmannClosure<0>, m_N),
- CLOSURE_FLOAT_PARAM(MicrofacetBeckmannClosure<0>, m_ab),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(MicrofacetBeckmannClosure<0>)
-};
-
-ClosureParam bsdf_microfacet_beckmann_refraction_params[] = {
- CLOSURE_VECTOR_PARAM(MicrofacetBeckmannClosure<1>, m_N),
- CLOSURE_FLOAT_PARAM(MicrofacetBeckmannClosure<1>, m_ab),
- CLOSURE_FLOAT_PARAM(MicrofacetBeckmannClosure<1>, m_eta),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(MicrofacetBeckmannClosure<1>)
-};
-
-CLOSURE_PREPARE(bsdf_microfacet_ggx_prepare, MicrofacetGGXClosure<0>)
-CLOSURE_PREPARE(bsdf_microfacet_ggx_refraction_prepare, MicrofacetGGXClosure<1>)
-CLOSURE_PREPARE(bsdf_microfacet_beckmann_prepare, MicrofacetBeckmannClosure<0>)
-CLOSURE_PREPARE(bsdf_microfacet_beckmann_refraction_prepare, MicrofacetBeckmannClosure<1>)
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/osl/bsdf_oren_nayar.cpp b/intern/cycles/kernel/osl/bsdf_oren_nayar.cpp
deleted file mode 100644
index 83d0e583695..00000000000
--- a/intern/cycles/kernel/osl/bsdf_oren_nayar.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright 2011, Blender Foundation.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <OpenImageIO/fmath.h>
-#include <OSL/genclosure.h>
-#include "osl_closures.h"
-#include "util_math.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-
-class OrenNayarClosure : public BSDFClosure {
-public:
- Vec3 m_N;
- float m_sigma;
- float m_a, m_b;
-
- OrenNayarClosure() : BSDFClosure(Labels::DIFFUSE) {}
-
- void setup() {
- m_sigma = clamp(m_sigma, 0.0f, 1.0f);
-
- float div = 1.0f / (M_PI + ((3.0f * M_PI - 4.0f) / 6.0f) * m_sigma);
-
- m_a = 1.0f * div;
- m_b = m_sigma * div;
- }
-
- bool mergeable(const ClosurePrimitive *other) const {
- const OrenNayarClosure *comp = static_cast<const OrenNayarClosure *>(other);
- return
- m_N == comp->m_N &&
- m_sigma == comp->m_sigma &&
- BSDFClosure::mergeable(other);
- }
-
- size_t memsize() const {
- return sizeof(*this);
- }
-
- const char *name() const {
- return "oren_nayar";
- }
-
- void print_on(std::ostream& out) const {
- out << name() << " (";
- out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), ";
- out << m_sigma;
- out << ")";
- }
-
- float albedo(const Vec3& omega_out) const {
- return 1.0f;
- }
-
- Color3 eval_reflect(const Vec3& omega_out, const Vec3& omega_in, float& pdf) const {
- if (m_N.dot(omega_in) > 0.0f) {
- pdf = float(0.5 * M_1_PI);
- float is = get_intensity(m_N, omega_out, omega_in);
- return Color3(is, is, is);
- }
- else {
- pdf = 0.0f;
- return Color3(0.0f, 0.0f, 0.0f);
- }
- }
-
- Color3 eval_transmit(const Vec3& omega_out, const Vec3& omega_in, float& pdf) const {
- return Color3(0.0f, 0.0f, 0.0f);
- }
-
- ustring sample(
- const Vec3& Ng,
- const Vec3& omega_out, const Vec3& domega_out_dx, const Vec3& domega_out_dy,
- float randu, float randv,
- Vec3& omega_in, Vec3& domega_in_dx, Vec3& domega_in_dy,
- float& pdf, Color3& eval
- ) const {
- sample_uniform_hemisphere(m_N, omega_out, randu, randv, omega_in, pdf);
-
- if (Ng.dot(omega_in) > 0.0f) {
- float is = get_intensity(m_N, omega_out, omega_in);
- eval.setValue(is, is, is);
-
- // TODO: find a better approximation for the bounce
- domega_in_dx = (2.0f * m_N.dot(domega_out_dx)) * m_N - domega_out_dx;
- domega_in_dy = (2.0f * m_N.dot(domega_out_dy)) * m_N - domega_out_dy;
- domega_in_dx *= 125.0f;
- domega_in_dy *= 125.0f;
- }
- else {
- pdf = 0.0f;
- }
-
- return Labels::REFLECT;
- }
-
-private:
- float get_intensity(Vec3 const& n, Vec3 const& v, Vec3 const& l) const {
- float nl = max(n.dot(l), 0.0f);
- float nv = max(n.dot(v), 0.0f);
- float t = l.dot(v) - nl * nv;
-
- if (t > 0.0f) {
- t /= max(nl, nv) + 1e-8f;
- }
- return nl * (m_a + m_b * t);
- }
-};
-
-ClosureParam bsdf_oren_nayar_params[] = {
- CLOSURE_VECTOR_PARAM(OrenNayarClosure, m_N),
- CLOSURE_FLOAT_PARAM(OrenNayarClosure, m_sigma),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(OrenNayarClosure)
-};
-
-CLOSURE_PREPARE(bsdf_oren_nayar_prepare, OrenNayarClosure)
-
-
-CCL_NAMESPACE_END
diff --git a/intern/cycles/kernel/osl/bsdf_phong.cpp b/intern/cycles/kernel/osl/bsdf_phong.cpp
deleted file mode 100644
index 57745079d33..00000000000
--- a/intern/cycles/kernel/osl/bsdf_phong.cpp
+++ /dev/null
@@ -1,277 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2012, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-#include "osl_closures.h"
-#include "util_math.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-// vanilla phong - leaks energy at grazing angles
-// see Global Illumination Compendium entry (66)
-class PhongClosure : public BSDFClosure {
-public:
- Vec3 m_N;
- float m_exponent;
- PhongClosure() : BSDFClosure(Labels::GLOSSY) { }
-
- void setup() {};
-
- bool mergeable (const ClosurePrimitive *other) const {
- const PhongClosure *comp = (const PhongClosure *)other;
- return m_N == comp->m_N && m_exponent == comp->m_exponent &&
- BSDFClosure::mergeable(other);
- }
-
- size_t memsize () const { return sizeof(*this); }
-
- const char *name () const { return "phong"; }
-
- void print_on (std::ostream &out) const {
- out << name() << " ((";
- out << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), ";
- out << m_exponent << ")";
- }
-
- float albedo (const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_reflect (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- float cosNI = m_N.dot(omega_in);
- float cosNO = m_N.dot(omega_out);
- if (cosNI > 0 && cosNO > 0) {
- // reflect the view vector
- Vec3 R = (2 * cosNO) * m_N - omega_out;
- float cosRI = R.dot(omega_in);
- if (cosRI > 0) {
- float common = 0.5f * (float) M_1_PI * powf(cosRI, m_exponent);
- float out = cosNI * (m_exponent + 2) * common;
- pdf = (m_exponent + 1) * common;
- return Color3 (out, out, out);
- }
- }
- return Color3 (0, 0, 0);
- }
-
- Color3 eval_transmit (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3 (0, 0, 0);
- }
-
- ustring sample (const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- float cosNO = m_N.dot(omega_out);
- if (cosNO > 0) {
- // reflect the view vector
- Vec3 R = (2 * cosNO) * m_N - omega_out;
- domega_in_dx = (2 * m_N.dot(domega_out_dx)) * m_N - domega_out_dx;
- domega_in_dy = (2 * m_N.dot(domega_out_dy)) * m_N - domega_out_dy;
- Vec3 T, B;
- make_orthonormals (R, T, B);
- float phi = 2 * (float) M_PI * randu;
- float cosTheta = powf(randv, 1 / (m_exponent + 1));
- float sinTheta2 = 1 - cosTheta * cosTheta;
- float sinTheta = sinTheta2 > 0 ? sqrtf(sinTheta2) : 0;
- omega_in = (cosf(phi) * sinTheta) * T +
- (sinf(phi) * sinTheta) * B +
- ( cosTheta) * R;
- if (Ng.dot(omega_in) > 0)
- {
- // common terms for pdf and eval
- float cosNI = m_N.dot(omega_in);
- // make sure the direction we chose is still in the right hemisphere
- if (cosNI > 0)
- {
- float common = 0.5f * (float) M_1_PI * powf(cosTheta, m_exponent);
- pdf = (m_exponent + 1) * common;
- float out = cosNI * (m_exponent + 2) * common;
- eval.setValue(out, out, out);
- // Since there is some blur to this reflection, make the
- // derivatives a bit bigger. In theory this varies with the
- // exponent but the exact relationship is complex and
- // requires more ops than are practical.
- domega_in_dx *= 10;
- domega_in_dy *= 10;
- }
- }
- }
- return Labels::REFLECT;
- }
-};
-
-
-class PhongRampClosure : public BSDFClosure {
-public:
- static const int MAXCOLORS = 8;
- Vec3 m_N;
- float m_exponent;
- Color3 m_colors[MAXCOLORS];
- PhongRampClosure() : BSDFClosure(Labels::GLOSSY) { }
-
- void setup() {};
-
- bool mergeable (const ClosurePrimitive *other) const {
- const PhongRampClosure *comp = (const PhongRampClosure *)other;
- if (! (m_N == comp->m_N && m_exponent == comp->m_exponent &&
- BSDFClosure::mergeable(other)))
- return false;
- for (int i = 0; i < MAXCOLORS; ++i)
- if (m_colors[i] != comp->m_colors[i])
- return false;
- return true;
- }
-
- size_t memsize () const { return sizeof(*this); }
-
- const char *name () const { return "phong_ramp"; }
-
- void print_on (std::ostream &out) const {
- out << name() << " ((";
- out << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), ";
- out << m_exponent << ")";
- }
-
- Color3 get_color (float pos) const
- {
- float npos = pos * (float)(MAXCOLORS - 1);
- int ipos = (int)npos;
- if (ipos >= (MAXCOLORS - 1))
- return m_colors[MAXCOLORS - 1];
- float offset = npos - (float)ipos;
- return m_colors[ipos] * (1.0f - offset) + m_colors[ipos+1] * offset;
- }
-
- float albedo (const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_reflect (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- float cosNI = m_N.dot(omega_in);
- float cosNO = m_N.dot(omega_out);
- if (cosNI > 0 && cosNO > 0) {
- // reflect the view vector
- Vec3 R = (2 * cosNO) * m_N - omega_out;
- float cosRI = R.dot(omega_in);
- if (cosRI > 0) {
- float cosp = powf(cosRI, m_exponent);
- float common = 0.5f * (float) M_1_PI * cosp;
- float out = cosNI * (m_exponent + 2) * common;
- pdf = (m_exponent + 1) * common;
- return get_color(cosp) * out;
- }
- }
- return Color3 (0, 0, 0);
- }
-
- Color3 eval_transmit (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3 (0, 0, 0);
- }
-
- ustring sample (const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- float cosNO = m_N.dot(omega_out);
- if (cosNO > 0) {
- // reflect the view vector
- Vec3 R = (2 * cosNO) * m_N - omega_out;
- domega_in_dx = (2 * m_N.dot(domega_out_dx)) * m_N - domega_out_dx;
- domega_in_dy = (2 * m_N.dot(domega_out_dy)) * m_N - domega_out_dy;
- Vec3 T, B;
- make_orthonormals (R, T, B);
- float phi = 2 * (float) M_PI * randu;
- float cosTheta = powf(randv, 1 / (m_exponent + 1));
- float sinTheta2 = 1 - cosTheta * cosTheta;
- float sinTheta = sinTheta2 > 0 ? sqrtf(sinTheta2) : 0;
- omega_in = (cosf(phi) * sinTheta) * T +
- (sinf(phi) * sinTheta) * B +
- ( cosTheta) * R;
- if (Ng.dot(omega_in) > 0)
- {
- // common terms for pdf and eval
- float cosNI = m_N.dot(omega_in);
- // make sure the direction we chose is still in the right hemisphere
- if (cosNI > 0)
- {
- float cosp = powf(cosTheta, m_exponent);
- float common = 0.5f * (float) M_1_PI * cosp;
- pdf = (m_exponent + 1) * common;
- float out = cosNI * (m_exponent + 2) * common;
- eval = get_color(cosp) * out;
- // Since there is some blur to this reflection, make the
- // derivatives a bit bigger. In theory this varies with the
- // exponent but the exact relationship is complex and
- // requires more ops than are practical.
- domega_in_dx *= 10;
- domega_in_dy *= 10;
- }
- }
- }
- return Labels::REFLECT;
- }
-};
-
-
-
-ClosureParam bsdf_phong_params[] = {
- CLOSURE_VECTOR_PARAM(PhongClosure, m_N),
- CLOSURE_FLOAT_PARAM (PhongClosure, m_exponent),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(PhongClosure) };
-
-ClosureParam bsdf_phong_ramp_params[] = {
- CLOSURE_VECTOR_PARAM (PhongRampClosure, m_N),
- CLOSURE_FLOAT_PARAM (PhongRampClosure, m_exponent),
- CLOSURE_COLOR_ARRAY_PARAM(PhongRampClosure, m_colors, PhongRampClosure::MAXCOLORS),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM (PhongRampClosure) };
-
-CLOSURE_PREPARE(bsdf_phong_prepare, PhongClosure)
-CLOSURE_PREPARE(bsdf_phong_ramp_prepare, PhongRampClosure)
-
-CCL_NAMESPACE_END
diff --git a/intern/cycles/kernel/osl/bsdf_reflection.cpp b/intern/cycles/kernel/osl/bsdf_reflection.cpp
deleted file mode 100644
index 7041b4ced6f..00000000000
--- a/intern/cycles/kernel/osl/bsdf_reflection.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2011, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-
-#include "osl_closures.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-class ReflectionClosure : public BSDFClosure {
-public:
- Vec3 m_N; // shading normal
- ReflectionClosure() : BSDFClosure(Labels::SINGULAR) {}
-
- void setup() {};
-
- bool mergeable(const ClosurePrimitive *other) const {
- const ReflectionClosure *comp = (const ReflectionClosure *)other;
- return m_N == comp->m_N && BSDFClosure::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "reflection"; }
-
- void print_on(std::ostream &out) const {
- out << name() << " (";
- out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "))";
- }
-
- float albedo(const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_reflect(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- Color3 eval_transmit(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- ustring sample(const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- // only one direction is possible
- float cosNO = m_N.dot(omega_out);
- if (cosNO > 0) {
- omega_in = (2 * cosNO) * m_N - omega_out;
- if (Ng.dot(omega_in) > 0) {
- domega_in_dx = 2 * m_N.dot(domega_out_dx) * m_N - domega_out_dx;
- domega_in_dy = 2 * m_N.dot(domega_out_dy) * m_N - domega_out_dy;
- pdf = 1;
- eval.setValue(1, 1, 1);
- }
- }
- return Labels::REFLECT;
- }
-};
-
-ClosureParam bsdf_reflection_params[] = {
- CLOSURE_VECTOR_PARAM(ReflectionClosure, m_N),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(ReflectionClosure)
-};
-
-CLOSURE_PREPARE(bsdf_reflection_prepare, ReflectionClosure)
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/osl/bsdf_refraction.cpp b/intern/cycles/kernel/osl/bsdf_refraction.cpp
deleted file mode 100644
index f56ad7b127c..00000000000
--- a/intern/cycles/kernel/osl/bsdf_refraction.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2011, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-
-#include "osl_closures.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-class RefractionClosure : public BSDFClosure {
-public:
- Vec3 m_N; // shading normal
- float m_eta; // ratio of indices of refraction (inside / outside)
- RefractionClosure() : BSDFClosure(Labels::SINGULAR, Back) {}
-
- void setup() {}
-
- bool mergeable(const ClosurePrimitive *other) const {
- const RefractionClosure *comp = (const RefractionClosure *)other;
- return m_N == comp->m_N && m_eta == comp->m_eta &&
- BSDFClosure::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "refraction"; }
-
- void print_on(std::ostream &out) const {
- out << name() << " (";
- out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), ";
- out << m_eta;
- out << ")";
- }
-
- Color3 eval_reflect(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- Color3 eval_transmit(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- float albedo(const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- ustring sample(const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- Vec3 R, dRdx, dRdy;
- Vec3 T, dTdx, dTdy;
- bool inside;
-
- fresnel_dielectric(m_eta, m_N,
- omega_out, domega_out_dx, domega_out_dy,
- R, dRdx, dRdy,
- T, dTdx, dTdy,
- inside);
-
- if (!inside) {
- pdf = 1;
- eval.setValue(1.0f, 1.0f, 1.0f);
- omega_in = T;
- domega_in_dx = dTdx;
- domega_in_dy = dTdy;
- }
-
- return Labels::TRANSMIT;
- }
-};
-
-ClosureParam bsdf_refraction_params[] = {
- CLOSURE_VECTOR_PARAM(RefractionClosure, m_N),
- CLOSURE_FLOAT_PARAM(RefractionClosure, m_eta),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(RefractionClosure)
-};
-
-CLOSURE_PREPARE(bsdf_refraction_prepare, RefractionClosure)
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/osl/bsdf_transparent.cpp b/intern/cycles/kernel/osl/bsdf_transparent.cpp
deleted file mode 100644
index acde92530a2..00000000000
--- a/intern/cycles/kernel/osl/bsdf_transparent.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2011, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-
-#include "osl_closures.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-class TransparentClosure : public BSDFClosure {
-public:
- TransparentClosure() : BSDFClosure(Labels::STRAIGHT, Back) {}
-
- void setup() {}
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "transparent"; }
-
- void print_on(std::ostream &out) const {
- out << name() << " ()";
- }
-
- float albedo(const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_reflect(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- Color3 eval_transmit(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- ustring sample(const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- // only one direction is possible
- omega_in = -omega_out;
- domega_in_dx = -domega_out_dx;
- domega_in_dy = -domega_out_dy;
- pdf = 1;
- eval.setValue(1, 1, 1);
- return Labels::TRANSMIT;
- }
-};
-
-
-
-ClosureParam bsdf_transparent_params[] = {
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(TransparentClosure)
-};
-
-CLOSURE_PREPARE(bsdf_transparent_prepare, TransparentClosure)
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/osl/bsdf_ward.cpp b/intern/cycles/kernel/osl/bsdf_ward.cpp
deleted file mode 100644
index 4aacbc4ffc3..00000000000
--- a/intern/cycles/kernel/osl/bsdf_ward.cpp
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2011, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-
-#include "osl_closures.h"
-
-#include "util_math.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-// anisotropic ward - leaks energy at grazing angles
-// see http://www.graphics.cornell.edu/~bjw/wardnotes.pdf
-class WardClosure : public BSDFClosure {
-public:
- Vec3 m_N;
- Vec3 m_T;
- float m_ax, m_ay;
- WardClosure() : BSDFClosure(Labels::GLOSSY) {}
-
- void setup()
- {
- m_ax = clamp(m_ax, 1e-5f, 1.0f);
- m_ay = clamp(m_ay, 1e-5f, 1.0f);
- }
-
- bool mergeable(const ClosurePrimitive *other) const {
- const WardClosure *comp = (const WardClosure *)other;
- return m_N == comp->m_N && m_T == comp->m_T &&
- m_ax == comp->m_ax && m_ay == comp->m_ay &&
- BSDFClosure::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "ward"; }
-
- void print_on(std::ostream &out) const {
- out << name() << " ((";
- out << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), (";
- out << m_T[0] << ", " << m_T[1] << ", " << m_T[2] << "), ";
- out << m_ax << ", " << m_ay << ")";
- }
-
- float albedo(const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_reflect(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- float cosNO = m_N.dot(omega_out);
- float cosNI = m_N.dot(omega_in);
- if (cosNI > 0 && cosNO > 0) {
- // get half vector and get x,y basis on the surface for anisotropy
- Vec3 H = omega_in + omega_out;
- H.normalize(); // normalize needed for pdf
- Vec3 X, Y;
- make_orthonormals(m_N, m_T, X, Y);
- // eq. 4
- float dotx = H.dot(X) / m_ax;
- float doty = H.dot(Y) / m_ay;
- float dotn = H.dot(m_N);
- float exp_arg = (dotx * dotx + doty * doty) / (dotn * dotn);
- float denom = (4 * (float) M_PI * m_ax * m_ay * sqrtf(cosNO * cosNI));
- float exp_val = expf(-exp_arg);
- float out = cosNI * exp_val / denom;
- float oh = H.dot(omega_out);
- denom = 4 * (float) M_PI * m_ax * m_ay * oh * dotn * dotn * dotn;
- pdf = exp_val / denom;
- return Color3(out, out, out);
- }
- return Color3(0, 0, 0);
- }
-
- Color3 eval_transmit(const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- ustring sample(const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- float cosNO = m_N.dot(omega_out);
- if (cosNO > 0) {
- // get x,y basis on the surface for anisotropy
- Vec3 X, Y;
- make_orthonormals(m_N, m_T, X, Y);
- // generate random angles for the half vector
- // eq. 7 (taking care around discontinuities to keep
- // output angle in the right quadrant)
- // we take advantage of cos(atan(x)) == 1/sqrt(1+x^2)
- // and sin(atan(x)) == x/sqrt(1+x^2)
- float alphaRatio = m_ay / m_ax;
- float cosPhi, sinPhi;
- if (randu < 0.25f) {
- float val = 4 * randu;
- float tanPhi = alphaRatio * tanf((float) M_PI_2 * val);
- cosPhi = 1 / sqrtf(1 + tanPhi * tanPhi);
- sinPhi = tanPhi * cosPhi;
- }
- else if (randu < 0.5) {
- float val = 1 - 4 * (0.5f - randu);
- float tanPhi = alphaRatio * tanf((float) M_PI_2 * val);
- // phi = (float) M_PI - phi;
- cosPhi = -1 / sqrtf(1 + tanPhi * tanPhi);
- sinPhi = -tanPhi * cosPhi;
- }
- else if (randu < 0.75f) {
- float val = 4 * (randu - 0.5f);
- float tanPhi = alphaRatio * tanf((float) M_PI_2 * val);
- //phi = (float) M_PI + phi;
- cosPhi = -1 / sqrtf(1 + tanPhi * tanPhi);
- sinPhi = tanPhi * cosPhi;
- }
- else {
- float val = 1 - 4 * (1 - randu);
- float tanPhi = alphaRatio * tanf((float) M_PI_2 * val);
- // phi = 2 * (float) M_PI - phi;
- cosPhi = 1 / sqrtf(1 + tanPhi * tanPhi);
- sinPhi = -tanPhi * cosPhi;
- }
- // eq. 6
- // we take advantage of cos(atan(x)) == 1/sqrt(1+x^2)
- // and sin(atan(x)) == x/sqrt(1+x^2)
- float thetaDenom = (cosPhi * cosPhi) / (m_ax * m_ax) + (sinPhi * sinPhi) / (m_ay * m_ay);
- float tanTheta2 = -logf(1 - randv) / thetaDenom;
- float cosTheta = 1 / sqrtf(1 + tanTheta2);
- float sinTheta = cosTheta * sqrtf(tanTheta2);
-
- Vec3 h; // already normalized becaused expressed from spherical coordinates
- h.x = sinTheta * cosPhi;
- h.y = sinTheta * sinPhi;
- h.z = cosTheta;
- // compute terms that are easier in local space
- float dotx = h.x / m_ax;
- float doty = h.y / m_ay;
- float dotn = h.z;
- // transform to world space
- h = h.x * X + h.y * Y + h.z * m_N;
- // generate the final sample
- float oh = h.dot(omega_out);
- omega_in.x = 2 * oh * h.x - omega_out.x;
- omega_in.y = 2 * oh * h.y - omega_out.y;
- omega_in.z = 2 * oh * h.z - omega_out.z;
- if (Ng.dot(omega_in) > 0) {
- float cosNI = m_N.dot(omega_in);
- if (cosNI > 0) {
- // eq. 9
- float exp_arg = (dotx * dotx + doty * doty) / (dotn * dotn);
- float denom = 4 * (float) M_PI * m_ax * m_ay * oh * dotn * dotn * dotn;
- pdf = expf(-exp_arg) / denom;
- // compiler will reuse expressions already computed
- denom = (4 * (float) M_PI * m_ax * m_ay * sqrtf(cosNO * cosNI));
- float power = cosNI * expf(-exp_arg) / denom;
- eval.setValue(power, power, power);
- domega_in_dx = (2 * m_N.dot(domega_out_dx)) * m_N - domega_out_dx;
- domega_in_dy = (2 * m_N.dot(domega_out_dy)) * m_N - domega_out_dy;
-
- /* disabled for now - gives texture filtering problems */
-#if 0
- // Since there is some blur to this reflection, make the
- // derivatives a bit bigger. In theory this varies with the
- // roughness but the exact relationship is complex and
- // requires more ops than are practical.
- domega_in_dx *= 10;
- domega_in_dy *= 10;
-#endif
- }
- }
- }
- return Labels::REFLECT;
- }
-};
-
-
-
-ClosureParam bsdf_ward_params[] = {
- CLOSURE_VECTOR_PARAM(WardClosure, m_N),
- CLOSURE_VECTOR_PARAM(WardClosure, m_T),
- CLOSURE_FLOAT_PARAM(WardClosure, m_ax),
- CLOSURE_FLOAT_PARAM(WardClosure, m_ay),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(WardClosure)
-};
-
-CLOSURE_PREPARE(bsdf_ward_prepare, WardClosure)
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/osl/bsdf_westin.cpp b/intern/cycles/kernel/osl/bsdf_westin.cpp
deleted file mode 100644
index a476e8045f7..00000000000
--- a/intern/cycles/kernel/osl/bsdf_westin.cpp
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2011, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-
-#include "osl_closures.h"
-
-#include "util_math.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-class WestinBackscatterClosure : public BSDFClosure {
-public:
- Vec3 m_N;
- float m_roughness;
- float m_invroughness;
- WestinBackscatterClosure() : BSDFClosure(Labels::GLOSSY) {}
-
- void setup()
- {
- m_roughness = clamp(m_roughness, 1e-5f, 1.0f);
- m_invroughness = m_roughness > 0 ? 1 / m_roughness : 0;
- }
-
- bool mergeable(const ClosurePrimitive *other) const {
- const WestinBackscatterClosure *comp = (const WestinBackscatterClosure *)other;
- return m_N == comp->m_N && m_roughness == comp->m_roughness &&
- BSDFClosure::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "westin_backscatter"; }
-
- void print_on(std::ostream &out) const
- {
- out << name() << " (";
- out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), ";
- out << m_roughness;
- out << ")";
- }
-
- float albedo(const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_reflect(const Vec3 &omega_out, const Vec3 &omega_in, float &pdf) const
- {
- // pdf is implicitly 0 (no indirect sampling)
- float cosNO = m_N.dot(omega_out);
- float cosNI = m_N.dot(omega_in);
- if (cosNO > 0 && cosNI > 0) {
- float cosine = omega_out.dot(omega_in);
- pdf = cosine > 0 ? (m_invroughness + 1) * powf(cosine, m_invroughness) : 0;
- pdf *= 0.5f * float(M_1_PI);
- return Color3(pdf, pdf, pdf);
- }
- return Color3(0, 0, 0);
- }
-
- Color3 eval_transmit(const Vec3 &omega_out, const Vec3 &omega_in, float &pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- ustring sample(const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- float cosNO = m_N.dot(omega_out);
- if (cosNO > 0) {
- domega_in_dx = domega_out_dx;
- domega_in_dy = domega_out_dy;
- Vec3 T, B;
- make_orthonormals(omega_out, T, B);
- float phi = 2 * (float) M_PI * randu;
- float cosTheta = powf(randv, 1 / (m_invroughness + 1));
- float sinTheta2 = 1 - cosTheta * cosTheta;
- float sinTheta = sinTheta2 > 0 ? sqrtf(sinTheta2) : 0;
- omega_in = (cosf(phi) * sinTheta) * T +
- (sinf(phi) * sinTheta) * B +
- (cosTheta) * omega_out;
- if (Ng.dot(omega_in) > 0)
- {
- // common terms for pdf and eval
- float cosNI = m_N.dot(omega_in);
- // make sure the direction we chose is still in the right hemisphere
- if (cosNI > 0)
- {
- pdf = 0.5f * (float) M_1_PI * powf(cosTheta, m_invroughness);
- pdf = (m_invroughness + 1) * pdf;
- eval.setValue(pdf, pdf, pdf);
- // Since there is some blur to this reflection, make the
- // derivatives a bit bigger. In theory this varies with the
- // exponent but the exact relationship is complex and
- // requires more ops than are practical.
- domega_in_dx *= 10;
- domega_in_dy *= 10;
- }
- }
- }
- return Labels::REFLECT;
- }
-
-};
-
-
-class WestinSheenClosure : public BSDFClosure {
-public:
- Vec3 m_N;
- float m_edginess;
-// float m_normalization;
- WestinSheenClosure() : BSDFClosure(Labels::DIFFUSE) {}
-
- void setup() {};
-
- bool mergeable(const ClosurePrimitive *other) const {
- const WestinSheenClosure *comp = (const WestinSheenClosure *)other;
- return m_N == comp->m_N && m_edginess == comp->m_edginess &&
- BSDFClosure::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "westin_sheen"; }
-
- void print_on(std::ostream &out) const
- {
- out << name() << " (";
- out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), ";
- out << m_edginess;
- out << ")";
- }
-
- float albedo(const Vec3 &omega_out) const
- {
- return 1.0f;
- }
-
- Color3 eval_reflect(const Vec3 &omega_out, const Vec3 &omega_in, float &pdf) const
- {
- // pdf is implicitly 0 (no indirect sampling)
- float cosNO = m_N.dot(omega_out);
- float cosNI = m_N.dot(omega_in);
- if (cosNO > 0 && cosNI > 0) {
- float sinNO2 = 1 - cosNO * cosNO;
- pdf = cosNI * float(M_1_PI);
- float westin = sinNO2 > 0 ? powf(sinNO2, 0.5f * m_edginess) * pdf : 0;
- return Color3(westin, westin, westin);
- }
- return Color3(0, 0, 0);
- }
-
- Color3 eval_transmit(const Vec3 &omega_out, const Vec3 &omega_in, float &pdf) const
- {
- return Color3(0, 0, 0);
- }
-
- ustring sample(const Vec3 &Ng,
- const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
- float randu, float randv,
- Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
- float &pdf, Color3 &eval) const
- {
- // we are viewing the surface from the right side - send a ray out with cosine
- // distribution over the hemisphere
- sample_cos_hemisphere(m_N, omega_out, randu, randv, omega_in, pdf);
- if (Ng.dot(omega_in) > 0) {
- // TODO: account for sheen when sampling
- float cosNO = m_N.dot(omega_out);
- float sinNO2 = 1 - cosNO * cosNO;
- float westin = sinNO2 > 0 ? powf(sinNO2, 0.5f * m_edginess) * pdf : 0;
- eval.setValue(westin, westin, westin);
- // TODO: find a better approximation for the diffuse bounce
- domega_in_dx = (2 * m_N.dot(domega_out_dx)) * m_N - domega_out_dx;
- domega_in_dy = (2 * m_N.dot(domega_out_dy)) * m_N - domega_out_dy;
- domega_in_dx *= 125;
- domega_in_dy *= 125;
- }
- else {
- pdf = 0;
- }
- return Labels::REFLECT;
- }
-};
-
-
-
-ClosureParam bsdf_westin_backscatter_params[] = {
- CLOSURE_VECTOR_PARAM(WestinBackscatterClosure, m_N),
- CLOSURE_FLOAT_PARAM(WestinBackscatterClosure, m_roughness),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(WestinBackscatterClosure)
-};
-
-ClosureParam bsdf_westin_sheen_params[] = {
- CLOSURE_VECTOR_PARAM(WestinSheenClosure, m_N),
- CLOSURE_FLOAT_PARAM(WestinSheenClosure, m_edginess),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(WestinSheenClosure)
-};
-
-CLOSURE_PREPARE(bsdf_westin_backscatter_prepare, WestinBackscatterClosure)
-CLOSURE_PREPARE(bsdf_westin_sheen_prepare, WestinSheenClosure)
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/osl/bssrdf.cpp b/intern/cycles/kernel/osl/bssrdf.cpp
deleted file mode 100644
index b195cf513cd..00000000000
--- a/intern/cycles/kernel/osl/bssrdf.cpp
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2011, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-
-#include "osl_closures.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-class BSSRDFCubicClosure : public BSSRDFClosure {
-public:
- Color3 m_radius;
- Color3 m_scale;
- float m_max_radius;
-
- template <typename T>
- static inline T pow3(const T &x) { return x * x * x; }
-
- template <typename T>
- static inline T pow5(const T &x) { T x2 = x * x; return x2 * x2 * x; }
-
- BSSRDFCubicClosure() {}
-
- void setup()
- {
- // pre-compute some terms
- m_max_radius = 0;
- for (int i = 0; i < 3; i++) {
- m_scale[i] = m_radius[i] > 0 ? 4 / pow5(m_radius[i]) : 0;
- m_max_radius = std::max(m_max_radius, m_radius[i]);
- }
- }
-
- bool mergeable(const ClosurePrimitive *other) const {
- const BSSRDFCubicClosure *comp = (const BSSRDFCubicClosure *)other;
- return m_radius == comp->m_radius && BSSRDFClosure::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "bssrdf_cubic"; }
-
- void print_on(std::ostream &out) const
- {
- out << name() << " ((" << m_radius[0] << ", " << m_radius[1] << ", " << m_radius[2] << "), ("
- << m_scale[0] << ", " << m_scale[1] << ", " << m_scale[2] << "))";
- }
-
- Color3 eval(float r) const
- {
- return Color3((r < m_radius.x) ? pow3(m_radius.x - r) * m_scale.x : 0,
- (r < m_radius.y) ? pow3(m_radius.y - r) * m_scale.y : 0,
- (r < m_radius.z) ? pow3(m_radius.z - r) * m_scale.z : 0);
- }
-
- float max_radius() const
- {
- return m_max_radius;
- }
-};
-
-
-
-ClosureParam closure_bssrdf_cubic_params[] = {
- CLOSURE_COLOR_PARAM(BSSRDFCubicClosure, m_radius),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(BSSRDFCubicClosure)
-};
-
-CLOSURE_PREPARE(closure_bssrdf_cubic_prepare, BSSRDFCubicClosure)
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/osl/debug.cpp b/intern/cycles/kernel/osl/debug.cpp
deleted file mode 100644
index 768a9100e8a..00000000000
--- a/intern/cycles/kernel/osl/debug.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2011, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-
-#include "osl_closures.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-/// Debug closure
-///
-/// This is going to be used for mask AOV's and similar
-/// purposes. A tag (string) is always associated with
-/// this closure, that "selects: the channel where the
-/// weight should be sent.
-
-class DebugClosure : public ClosurePrimitive {
-public:
- ustring m_tag;
-
- DebugClosure () : ClosurePrimitive(Debug) {}
-
- bool mergeable(const ClosurePrimitive *other) const {
- const DebugClosure *comp = (const DebugClosure *)other;
- return m_tag == comp->m_tag &&
- ClosurePrimitive::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "debug"; }
-
- void print_on(std::ostream &out) const {
- out << name() << " (\"" << m_tag.c_str() << "\")";
- }
-
-};
-
-ClosureParam closure_debug_params[] = {
- CLOSURE_STRING_PARAM(DebugClosure, m_tag),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(DebugClosure)
-};
-
-CLOSURE_PREPARE(closure_debug_prepare, DebugClosure)
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/osl/emissive.cpp b/intern/cycles/kernel/osl/emissive.cpp
index 0a582c3f558..37e3e37c00a 100644
--- a/intern/cycles/kernel/osl/emissive.cpp
+++ b/intern/cycles/kernel/osl/emissive.cpp
@@ -36,6 +36,9 @@
#include "osl_closures.h"
+#include "kernel_types.h"
+#include "closure/emissive.h"
+
CCL_NAMESPACE_BEGIN
using namespace OSL;
@@ -52,55 +55,42 @@ public:
GenericEmissiveClosure() { }
void setup() {}
-
size_t memsize() const { return sizeof(*this); }
-
const char *name() const { return "emission"; }
- void print_on(std::ostream &out) const {
+ void print_on(std::ostream &out) const
+ {
out << name() << "()";
}
Color3 eval(const Vec3 &Ng, const Vec3 &omega_out) const
{
- float cosNO = fabsf(Ng.dot(omega_out));
- float res = cosNO > 0 ? 1.0f : 0.0f;
- return Color3(res, res, res);
+ float3 result = emissive_eval(TO_FLOAT3(Ng), TO_FLOAT3(omega_out));
+ return TO_COLOR3(result);
}
void sample(const Vec3 &Ng, float randu, float randv,
Vec3 &omega_out, float &pdf) const
{
- // We don't do anything sophisticated here for the step
- // We just sample the whole cone uniformly to the cosine
- Vec3 T, B;
- make_orthonormals(Ng, T, B);
- float phi = 2 * (float) M_PI * randu;
- float cosTheta = sqrtf(1.0f - 1.0f * randv);
- float sinTheta = sqrtf(1.0f - cosTheta * cosTheta);
- omega_out = (cosf(phi) * sinTheta) * T +
- (sinf(phi) * sinTheta) * B +
- cosTheta * Ng;
- pdf = 1.0f / float(M_PI);
+ float3 omega_out_;
+ emissive_sample(TO_FLOAT3(Ng), randu, randv, &omega_out_, &pdf);
+ omega_out = TO_VEC3(omega_out_);
}
- /// Return the probability distribution function in the direction omega_out,
- /// given the parameters and the light's surface normal. This MUST match
- /// the PDF computed by sample().
- float pdf(const Vec3 &Ng,
- const Vec3 &omega_out) const
+ float pdf(const Vec3 &Ng, const Vec3 &omega_out) const
{
- float cosNO = Ng.dot(omega_out);
- return cosNO > 0 ? 1.0f : 0.0f;
+ return emissive_pdf(TO_FLOAT3(Ng), TO_FLOAT3(omega_out));
}
};
-
-
-ClosureParam closure_emission_params[] = {
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(GenericEmissiveClosure)
-};
+ClosureParam *closure_emission_params()
+{
+ static ClosureParam params[] = {
+ CLOSURE_STRING_KEYPARAM("label"),
+ CLOSURE_FINISH_PARAM(GenericEmissiveClosure)
+ };
+ return params;
+}
CLOSURE_PREPARE(closure_emission_prepare, GenericEmissiveClosure)
diff --git a/intern/cycles/kernel/osl/nodes/node_object_info.osl b/intern/cycles/kernel/osl/nodes/node_object_info.osl
deleted file mode 100644
index 21e50d8a43e..00000000000
--- a/intern/cycles/kernel/osl/nodes/node_object_info.osl
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2011, Blender Foundation.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "stdosl.h"
-
-shader node_object_info(
- output point Location = point(0.0, 0.0, 0.0),
- output float ObjectIndex = 0.0,
- output float MaterialIndex = 0.0,
- output float Random = 0.0
- )
-{
- getattribute("std::object_location", Location);
- getattribute("std::object_index", ObjectIndex);
- getattribute("std::material_index", MaterialIndex);
- getattribute("std::object_random", Random);
-}
-
diff --git a/intern/cycles/kernel/osl/nodes/node_voronoi_texture.osl b/intern/cycles/kernel/osl/nodes/node_voronoi_texture.osl
deleted file mode 100644
index f24f154be84..00000000000
--- a/intern/cycles/kernel/osl/nodes/node_voronoi_texture.osl
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright 2011, Blender Foundation.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "stdosl.h"
-#include "node_texture.h"
-
-/* Voronoi */
-
-shader node_voronoi_texture(
- string DistanceMetric = "Actual Distance",
- string Coloring = "Intensity",
- float Weight1 = 1.0,
- float Weight2 = 0.0,
- float Weight3 = 0.0,
- float Weight4 = 0.0,
- float Exponent = 2.5,
- float Intensity = 1.0,
- float Scale = 5.0,
- point Vector = P,
- output float Fac = 0.0,
- output color Color = color(0.0, 0.0, 0.0))
-{
- float exponent = max(Exponent, 1e-5);
-
- float aw1 = fabs(Weight1);
- float aw2 = fabs(Weight2);
- float aw3 = fabs(Weight3);
- float aw4 = fabs(Weight4);
- float sc = (aw1 + aw2 + aw3 + aw4);
-
- if(sc != 0.0)
- sc = Intensity/sc;
-
- /* compute distance and point coordinate of 4 nearest neighbours */
- float da[4];
- point pa[4];
-
- voronoi(Vector*Scale, DistanceMetric, exponent, da, pa);
-
- /* Scalar output */
- Fac = sc * fabs(Weight1*da[0] + Weight2*da[1] + Weight3*da[2] + Weight4*da[3]);
-
- /* Colored output */
- if(Coloring == "Intensity") {
- Color = color(Fac, Fac, Fac);
- }
- else {
- Color = aw1*cellnoise_color(pa[0]);
- Color += aw2*cellnoise_color(pa[1]);
- Color += aw3*cellnoise_color(pa[2]);
- Color += aw4*cellnoise_color(pa[3]);
-
- if(Coloring != "Position") {
- float t1 = min((da[1] - da[0])*10.0, 1.0);
-
- if(Coloring == "Position, Outline, and Intensity")
- Color *= t1*Fac;
- else if(Coloring == "Position and Outline")
- Color *= t1*sc;
- }
- else {
- Color *= sc;
- }
- }
-}
-
diff --git a/intern/cycles/kernel/osl/osl_closures.cpp b/intern/cycles/kernel/osl/osl_closures.cpp
index a1a108a1b1d..73e96643df7 100644
--- a/intern/cycles/kernel/osl/osl_closures.cpp
+++ b/intern/cycles/kernel/osl/osl_closures.cpp
@@ -37,10 +37,100 @@
#include "osl_shader.h"
#include "util_debug.h"
+#include "util_math.h"
#include "util_param.h"
+#include "kernel_types.h"
+#include "kernel_montecarlo.h"
+
+#include "closure/bsdf.h"
+#include "closure/bsdf_ashikhmin_velvet.h"
+#include "closure/bsdf_diffuse.h"
+#include "closure/bsdf_microfacet.h"
+#include "closure/bsdf_oren_nayar.h"
+#include "closure/bsdf_reflection.h"
+#include "closure/bsdf_refraction.h"
+#include "closure/bsdf_transparent.h"
+#include "closure/bsdf_ward.h"
+#include "closure/bsdf_westin.h"
+
CCL_NAMESPACE_BEGIN
+using namespace OSL;
+
+/* BSDF class definitions */
+
+BSDF_CLOSURE_CLASS_BEGIN(Diffuse, diffuse, diffuse, LABEL_DIFFUSE)
+ CLOSURE_VECTOR_PARAM(DiffuseClosure, N),
+BSDF_CLOSURE_CLASS_END(Diffuse, diffuse)
+
+BSDF_CLOSURE_CLASS_BEGIN(Translucent, translucent, translucent, LABEL_DIFFUSE)
+ CLOSURE_VECTOR_PARAM(TranslucentClosure, N),
+BSDF_CLOSURE_CLASS_END(Translucent, translucent)
+
+BSDF_CLOSURE_CLASS_BEGIN(OrenNayar, oren_nayar, oren_nayar, LABEL_DIFFUSE)
+ CLOSURE_VECTOR_PARAM(OrenNayarClosure, N),
+ CLOSURE_FLOAT_PARAM(OrenNayarClosure, sc.data0),
+BSDF_CLOSURE_CLASS_END(OrenNayar, oren_nayar)
+
+BSDF_CLOSURE_CLASS_BEGIN(Reflection, reflection, reflection, LABEL_SINGULAR)
+ CLOSURE_VECTOR_PARAM(ReflectionClosure, N),
+BSDF_CLOSURE_CLASS_END(Reflection, reflection)
+
+BSDF_CLOSURE_CLASS_BEGIN(Refraction, refraction, refraction, LABEL_SINGULAR)
+ CLOSURE_VECTOR_PARAM(RefractionClosure, N),
+ CLOSURE_FLOAT_PARAM(RefractionClosure, sc.data0),
+BSDF_CLOSURE_CLASS_END(Refraction, refraction)
+
+BSDF_CLOSURE_CLASS_BEGIN(WestinBackscatter, westin_backscatter, westin_backscatter, LABEL_GLOSSY)
+ CLOSURE_VECTOR_PARAM(WestinBackscatterClosure, N),
+ CLOSURE_FLOAT_PARAM(WestinBackscatterClosure, sc.data0),
+BSDF_CLOSURE_CLASS_END(WestinBackscatter, westin_backscatter)
+
+BSDF_CLOSURE_CLASS_BEGIN(WestinSheen, westin_sheen, westin_sheen, LABEL_DIFFUSE)
+ CLOSURE_VECTOR_PARAM(WestinSheenClosure, N),
+ CLOSURE_FLOAT_PARAM(WestinSheenClosure, sc.data0),
+BSDF_CLOSURE_CLASS_END(WestinSheen, westin_sheen)
+
+BSDF_CLOSURE_CLASS_BEGIN(Transparent, transparent, transparent, LABEL_SINGULAR)
+BSDF_CLOSURE_CLASS_END(Transparent, transparent)
+
+BSDF_CLOSURE_CLASS_BEGIN(AshikhminVelvet, ashikhmin_velvet, ashikhmin_velvet, LABEL_DIFFUSE)
+ CLOSURE_VECTOR_PARAM(AshikhminVelvetClosure, N),
+ CLOSURE_FLOAT_PARAM(AshikhminVelvetClosure, sc.data0),
+BSDF_CLOSURE_CLASS_END(AshikhminVelvet, ashikhmin_velvet)
+
+BSDF_CLOSURE_CLASS_BEGIN(Ward, ward, ward, LABEL_GLOSSY)
+ CLOSURE_VECTOR_PARAM(WardClosure, N),
+ CLOSURE_VECTOR_PARAM(WardClosure, T),
+ CLOSURE_FLOAT_PARAM(WardClosure, sc.data0),
+ CLOSURE_FLOAT_PARAM(WardClosure, sc.data1),
+BSDF_CLOSURE_CLASS_END(Ward, ward)
+
+BSDF_CLOSURE_CLASS_BEGIN(MicrofacetGGX, microfacet_ggx, microfacet_ggx, LABEL_GLOSSY)
+ CLOSURE_VECTOR_PARAM(MicrofacetGGXClosure, N),
+ CLOSURE_FLOAT_PARAM(MicrofacetGGXClosure, sc.data0),
+BSDF_CLOSURE_CLASS_END(MicrofacetGGX, microfacet_ggx)
+
+BSDF_CLOSURE_CLASS_BEGIN(MicrofacetBeckmann, microfacet_beckmann, microfacet_beckmann, LABEL_GLOSSY)
+ CLOSURE_VECTOR_PARAM(MicrofacetBeckmannClosure, N),
+ CLOSURE_FLOAT_PARAM(MicrofacetBeckmannClosure, sc.data0),
+BSDF_CLOSURE_CLASS_END(MicrofacetBeckmann, microfacet_beckmann)
+
+BSDF_CLOSURE_CLASS_BEGIN(MicrofacetGGXRefraction, microfacet_ggx_refraction, microfacet_ggx, LABEL_GLOSSY)
+ CLOSURE_VECTOR_PARAM(MicrofacetGGXRefractionClosure, N),
+ CLOSURE_FLOAT_PARAM(MicrofacetGGXRefractionClosure, sc.data0),
+ CLOSURE_FLOAT_PARAM(MicrofacetGGXRefractionClosure, sc.data1),
+BSDF_CLOSURE_CLASS_END(MicrofacetGGXRefraction, microfacet_ggx_refraction)
+
+BSDF_CLOSURE_CLASS_BEGIN(MicrofacetBeckmannRefraction, microfacet_beckmann_refraction, microfacet_beckmann, LABEL_GLOSSY)
+ CLOSURE_VECTOR_PARAM(MicrofacetBeckmannRefractionClosure, N),
+ CLOSURE_FLOAT_PARAM(MicrofacetBeckmannRefractionClosure, sc.data0),
+ CLOSURE_FLOAT_PARAM(MicrofacetBeckmannRefractionClosure, sc.data1),
+BSDF_CLOSURE_CLASS_END(MicrofacetBeckmannRefraction, microfacet_beckmann_refraction)
+
+/* Registration */
+
static void generic_closure_setup(OSL::RendererServices *, int id, void *data)
{
assert(data);
@@ -64,28 +154,42 @@ static void register_closure(OSL::ShadingSystem *ss, const char *name, int id, O
void OSLShader::register_closures(OSL::ShadingSystem *ss)
{
- register_closure(ss, "diffuse", OSL_CLOSURE_BSDF_DIFFUSE_ID, bsdf_diffuse_params, bsdf_diffuse_prepare);
- register_closure(ss, "oren_nayar", OSL_CLOSURE_BSDF_OREN_NAYAR_ID, bsdf_oren_nayar_params, bsdf_oren_nayar_prepare);
- register_closure(ss, "translucent", OSL_CLOSURE_BSDF_TRANSLUCENT_ID, bsdf_translucent_params, bsdf_translucent_prepare);
- register_closure(ss, "reflection", OSL_CLOSURE_BSDF_REFLECTION_ID, bsdf_reflection_params, bsdf_reflection_prepare);
- register_closure(ss, "refraction", OSL_CLOSURE_BSDF_REFRACTION_ID, bsdf_refraction_params, bsdf_refraction_prepare);
- register_closure(ss, "transparent", OSL_CLOSURE_BSDF_TRANSPARENT_ID, bsdf_transparent_params, bsdf_transparent_prepare);
- register_closure(ss, "microfacet_ggx", OSL_CLOSURE_BSDF_MICROFACET_GGX_ID, bsdf_microfacet_ggx_params, bsdf_microfacet_ggx_prepare);
- register_closure(ss, "microfacet_ggx_refraction", OSL_CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID, bsdf_microfacet_ggx_refraction_params, bsdf_microfacet_ggx_refraction_prepare);
- register_closure(ss, "microfacet_beckmann", OSL_CLOSURE_BSDF_MICROFACET_BECKMANN_ID, bsdf_microfacet_beckmann_params, bsdf_microfacet_beckmann_prepare);
- register_closure(ss, "microfacet_beckmann_refraction", OSL_CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID, bsdf_microfacet_beckmann_refraction_params, bsdf_microfacet_beckmann_refraction_prepare);
- register_closure(ss, "ward", OSL_CLOSURE_BSDF_WARD_ID, bsdf_ward_params, bsdf_ward_prepare);
- register_closure(ss, "phong", OSL_CLOSURE_BSDF_PHONG_ID, bsdf_phong_params, bsdf_phong_prepare);
- register_closure(ss, "phong_ramp", OSL_CLOSURE_BSDF_PHONG_RAMP_ID, bsdf_phong_ramp_params, bsdf_phong_ramp_prepare);
- register_closure(ss, "ashikhmin_velvet", OSL_CLOSURE_BSDF_ASHIKHMIN_VELVET_ID, bsdf_ashikhmin_velvet_params, bsdf_ashikhmin_velvet_prepare);
- register_closure(ss, "westin_backscatter", OSL_CLOSURE_BSDF_WESTIN_BACKSCATTER_ID, bsdf_westin_backscatter_params, bsdf_westin_backscatter_prepare);
- register_closure(ss, "westin_sheen", OSL_CLOSURE_BSDF_WESTIN_SHEEN_ID, bsdf_westin_sheen_params, bsdf_westin_sheen_prepare);
- register_closure(ss, "bssrdf_cubic", OSL_CLOSURE_BSSRDF_CUBIC_ID, closure_bssrdf_cubic_params, closure_bssrdf_cubic_prepare);
- register_closure(ss, "emission", OSL_CLOSURE_EMISSION_ID, closure_emission_params, closure_emission_prepare);
- register_closure(ss, "debug", OSL_CLOSURE_DEBUG_ID, closure_debug_params, closure_debug_prepare);
- register_closure(ss, "background", OSL_CLOSURE_BACKGROUND_ID, closure_background_params, closure_background_prepare);
- register_closure(ss, "holdout", OSL_CLOSURE_HOLDOUT_ID, closure_holdout_params, closure_holdout_prepare);
- register_closure(ss, "subsurface", OSL_CLOSURE_SUBSURFACE_ID, closure_subsurface_params, closure_subsurface_prepare);
+ int id = 0;
+
+ register_closure(ss, "diffuse", id++,
+ bsdf_diffuse_params(), bsdf_diffuse_prepare);
+ register_closure(ss, "oren_nayar", id++,
+ bsdf_oren_nayar_params(), bsdf_oren_nayar_prepare);
+ register_closure(ss, "translucent", id++,
+ bsdf_translucent_params(), bsdf_translucent_prepare);
+ register_closure(ss, "reflection", id++,
+ bsdf_reflection_params(), bsdf_reflection_prepare);
+ register_closure(ss, "refraction", id++,
+ bsdf_refraction_params(), bsdf_refraction_prepare);
+ register_closure(ss, "transparent", id++,
+ bsdf_transparent_params(), bsdf_transparent_prepare);
+ register_closure(ss, "microfacet_ggx", id++,
+ bsdf_microfacet_ggx_params(), bsdf_microfacet_ggx_prepare);
+ register_closure(ss, "microfacet_ggx_refraction", id++,
+ bsdf_microfacet_ggx_refraction_params(), bsdf_microfacet_ggx_refraction_prepare);
+ register_closure(ss, "microfacet_beckmann", id++,
+ bsdf_microfacet_beckmann_params(), bsdf_microfacet_beckmann_prepare);
+ register_closure(ss, "microfacet_beckmann_refraction", id++,
+ bsdf_microfacet_beckmann_refraction_params(), bsdf_microfacet_beckmann_refraction_prepare);
+ register_closure(ss, "ward", id++,
+ bsdf_ward_params(), bsdf_ward_prepare);
+ register_closure(ss, "ashikhmin_velvet", id++,
+ bsdf_ashikhmin_velvet_params(), bsdf_ashikhmin_velvet_prepare);
+ register_closure(ss, "westin_backscatter", id++,
+ bsdf_westin_backscatter_params(), bsdf_westin_backscatter_prepare);
+ register_closure(ss, "westin_sheen", id++,
+ bsdf_westin_sheen_params(), bsdf_westin_sheen_prepare);
+ register_closure(ss, "emission", id++,
+ closure_emission_params(), closure_emission_prepare);
+ register_closure(ss, "background", id++,
+ closure_background_params(), closure_background_prepare);
+ register_closure(ss, "holdout", id++,
+ closure_holdout_params(), closure_holdout_prepare);
}
CCL_NAMESPACE_END
diff --git a/intern/cycles/kernel/osl/osl_closures.h b/intern/cycles/kernel/osl/osl_closures.h
index 00794183ca5..574cb685db5 100644
--- a/intern/cycles/kernel/osl/osl_closures.h
+++ b/intern/cycles/kernel/osl/osl_closures.h
@@ -37,78 +37,19 @@
#include <OSL/oslexec.h>
#include <OSL/genclosure.h>
+#include "kernel_types.h"
+
+#include "util_types.h"
+
CCL_NAMESPACE_BEGIN
-enum {
- OSL_CLOSURE_BSDF_DIFFUSE_ID,
- OSL_CLOSURE_BSDF_OREN_NAYAR_ID,
- OSL_CLOSURE_BSDF_TRANSLUCENT_ID,
- OSL_CLOSURE_BSDF_REFLECTION_ID,
- OSL_CLOSURE_BSDF_REFRACTION_ID,
- OSL_CLOSURE_BSDF_TRANSPARENT_ID,
- OSL_CLOSURE_BSDF_MICROFACET_GGX_ID,
- OSL_CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID,
- OSL_CLOSURE_BSDF_MICROFACET_BECKMANN_ID,
- OSL_CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID,
- OSL_CLOSURE_BSDF_WARD_ID,
- OSL_CLOSURE_BSDF_PHONG_ID,
- OSL_CLOSURE_BSDF_PHONG_RAMP_ID,
- OSL_CLOSURE_BSDF_ASHIKHMIN_VELVET_ID,
- OSL_CLOSURE_BSDF_WESTIN_BACKSCATTER_ID,
- OSL_CLOSURE_BSDF_WESTIN_SHEEN_ID,
- OSL_CLOSURE_BSSRDF_CUBIC_ID,
- OSL_CLOSURE_EMISSION_ID,
- OSL_CLOSURE_DEBUG_ID,
- OSL_CLOSURE_BACKGROUND_ID,
- OSL_CLOSURE_HOLDOUT_ID,
- OSL_CLOSURE_SUBSURFACE_ID
-};
+OSL::ClosureParam *closure_emission_params();
+OSL::ClosureParam *closure_background_params();
+OSL::ClosureParam *closure_holdout_params();
-extern OSL::ClosureParam bsdf_diffuse_params[];
-extern OSL::ClosureParam bsdf_oren_nayar_params[];
-extern OSL::ClosureParam bsdf_translucent_params[];
-extern OSL::ClosureParam bsdf_reflection_params[];
-extern OSL::ClosureParam bsdf_refraction_params[];
-extern OSL::ClosureParam bsdf_transparent_params[];
-extern OSL::ClosureParam bsdf_microfacet_ggx_params[];
-extern OSL::ClosureParam bsdf_microfacet_ggx_refraction_params[];
-extern OSL::ClosureParam bsdf_microfacet_beckmann_params[];
-extern OSL::ClosureParam bsdf_microfacet_beckmann_refraction_params[];
-extern OSL::ClosureParam bsdf_ward_params[];
-extern OSL::ClosureParam bsdf_phong_params[];
-extern OSL::ClosureParam bsdf_phong_ramp_params[];
-extern OSL::ClosureParam bsdf_ashikhmin_velvet_params[];
-extern OSL::ClosureParam bsdf_westin_backscatter_params[];
-extern OSL::ClosureParam bsdf_westin_sheen_params[];
-extern OSL::ClosureParam closure_bssrdf_cubic_params[];
-extern OSL::ClosureParam closure_emission_params[];
-extern OSL::ClosureParam closure_debug_params[];
-extern OSL::ClosureParam closure_background_params[];
-extern OSL::ClosureParam closure_holdout_params[];
-extern OSL::ClosureParam closure_subsurface_params[];
-
-void bsdf_diffuse_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_oren_nayar_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_translucent_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_reflection_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_refraction_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_transparent_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_microfacet_ggx_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_microfacet_ggx_refraction_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_microfacet_beckmann_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_microfacet_beckmann_refraction_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_ward_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_phong_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_phong_ramp_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_ashikhmin_velvet_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_westin_backscatter_prepare(OSL::RendererServices *, int id, void *data);
-void bsdf_westin_sheen_prepare(OSL::RendererServices *, int id, void *data);
-void closure_bssrdf_cubic_prepare(OSL::RendererServices *, int id, void *data);
void closure_emission_prepare(OSL::RendererServices *, int id, void *data);
-void closure_debug_prepare(OSL::RendererServices *, int id, void *data);
void closure_background_prepare(OSL::RendererServices *, int id, void *data);
void closure_holdout_prepare(OSL::RendererServices *, int id, void *data);
-void closure_subsurface_prepare(OSL::RendererServices *, int id, void *data);
#define CLOSURE_PREPARE(name, classname) \
void name(RendererServices *, int id, void *data) \
@@ -117,6 +58,106 @@ void name(RendererServices *, int id, void *data) \
new (data) classname(); \
}
+#define TO_VEC3(v) (*(OSL::Vec3 *)&(v))
+#define TO_COLOR3(v) (*(OSL::Color3 *)&(v))
+#define TO_FLOAT3(v) make_float3(v[0], v[1], v[2])
+
+/* BSDF */
+
+class CBSDFClosure : public OSL::ClosurePrimitive {
+public:
+ ShaderClosure sc;
+ OSL::Vec3 N, T;
+
+ CBSDFClosure(int scattering) : OSL::ClosurePrimitive(BSDF),
+ m_scattering_label(scattering), m_shaderdata_flag(0) { }
+ ~CBSDFClosure() { }
+
+ int scattering() const { return m_scattering_label; }
+ int shaderdata_flag() const { return m_shaderdata_flag; }
+ ClosureType shaderclosure_type() const { return sc.type; }
+
+ virtual void blur(float roughness) = 0;
+ virtual float3 eval_reflect(const float3 &omega_out, const float3 &omega_in, float &pdf) const = 0;
+ virtual float3 eval_transmit(const float3 &omega_out, const float3 &omega_in, float &pdf) const = 0;
+
+ virtual int sample(const float3 &Ng,
+ const float3 &omega_out, const float3 &domega_out_dx, const float3 &domega_out_dy,
+ float randu, float randv,
+ float3 &omega_in, float3 &domega_in_dx, float3 &domega_in_dy,
+ float &pdf, float3 &eval) const = 0;
+
+protected:
+ int m_scattering_label;
+ int m_shaderdata_flag;
+};
+
+#define BSDF_CLOSURE_CLASS_BEGIN(Upper, lower, svmlower, TYPE) \
+\
+class Upper##Closure : public CBSDFClosure { \
+public: \
+ Upper##Closure() : CBSDFClosure(TYPE) {} \
+ size_t memsize() const { return sizeof(*this); } \
+ const char *name() const { return #lower; } \
+\
+ void setup() \
+ { \
+ sc.N = TO_FLOAT3(N); \
+ sc.T = TO_FLOAT3(T); \
+ m_shaderdata_flag = bsdf_##lower##_setup(&sc); \
+ } \
+\
+ bool mergeable(const ClosurePrimitive *other) const \
+ { \
+ return false; \
+ } \
+ \
+ void blur(float roughness) \
+ { \
+ bsdf_##svmlower##_blur(&sc, roughness); \
+ } \
+\
+ void print_on(std::ostream &out) const \
+ { \
+ out << name() << " ((" << sc.N[0] << ", " << sc.N[1] << ", " << sc.N[2] << "))"; \
+ } \
+\
+ float3 eval_reflect(const float3 &omega_out, const float3 &omega_in, float& pdf) const \
+ { \
+ return bsdf_##svmlower##_eval_reflect(&sc, omega_out, omega_in, &pdf); \
+ } \
+\
+ float3 eval_transmit(const float3 &omega_out, const float3 &omega_in, float& pdf) const \
+ { \
+ return bsdf_##svmlower##_eval_transmit(&sc, omega_out, omega_in, &pdf); \
+ } \
+\
+ int sample(const float3 &Ng, \
+ const float3 &omega_out, const float3 &domega_out_dx, const float3 &domega_out_dy, \
+ float randu, float randv, \
+ float3 &omega_in, float3 &domega_in_dx, float3 &domega_in_dy, \
+ float &pdf, float3 &eval) const \
+ { \
+ return bsdf_##svmlower##_sample(&sc, Ng, omega_out, domega_out_dx, domega_out_dy, \
+ randu, randv, &eval, &omega_in, &domega_in_dx, &domega_in_dy, &pdf); \
+ } \
+}; \
+\
+ClosureParam *bsdf_##lower##_params() \
+{ \
+ static ClosureParam params[] = {
+
+/* parameters */
+
+#define BSDF_CLOSURE_CLASS_END(Upper, lower) \
+ CLOSURE_STRING_KEYPARAM("label"), \
+ CLOSURE_FINISH_PARAM(Upper##Closure) \
+ }; \
+ return params; \
+} \
+\
+CLOSURE_PREPARE(bsdf_##lower##_prepare, Upper##Closure)
+
CCL_NAMESPACE_END
#endif /* __OSL_CLOSURES_H__ */
diff --git a/intern/cycles/kernel/osl/osl_services.cpp b/intern/cycles/kernel/osl/osl_services.cpp
index f1deaa9db9d..ac26fc1c18d 100644
--- a/intern/cycles/kernel/osl/osl_services.cpp
+++ b/intern/cycles/kernel/osl/osl_services.cpp
@@ -72,7 +72,11 @@ bool OSLRenderServices::get_matrix(OSL::Matrix44 &result, OSL::TransformationPtr
int object = sd->object;
if (object != ~0) {
- Transform tfm = object_fetch_transform(kg, object, time, OBJECT_TRANSFORM);
+#ifdef __OBJECT_MOTION__
+ Transform tfm = object_fetch_transform_motion_test(kg, object, time, NULL);
+#else
+ Transform tfm = object_fetch_transform(kg, object, OBJECT_TRANSFORM);
+#endif
tfm = transform_transpose(tfm);
result = TO_MATRIX44(tfm);
@@ -93,9 +97,14 @@ bool OSLRenderServices::get_inverse_matrix(OSL::Matrix44 &result, OSL::Transform
int object = sd->object;
if (object != ~0) {
- Transform tfm = object_fetch_transform(kg, object, time, OBJECT_INVERSE_TRANSFORM);
- tfm = transform_transpose(tfm);
- result = TO_MATRIX44(tfm);
+#ifdef __OBJECT_MOTION__
+ Transform itfm;
+ object_fetch_transform_motion_test(kg, object, time, &itfm);
+#else
+ Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM);
+#endif
+ itfm = transform_transpose(itfm);
+ result = TO_MATRIX44(itfm);
return true;
}
@@ -109,7 +118,7 @@ bool OSLRenderServices::get_matrix(OSL::Matrix44 &result, ustring from, float ti
KernelGlobals *kg = kernel_globals;
if (from == u_ndc) {
- Transform tfm = transform_transpose(kernel_data.cam.ndctoworld);
+ Transform tfm = transform_transpose(transform_quick_inverse(kernel_data.cam.worldtondc));
result = TO_MATRIX44(tfm);
return true;
}
@@ -162,14 +171,108 @@ bool OSLRenderServices::get_inverse_matrix(OSL::Matrix44 &result, ustring to, fl
bool OSLRenderServices::get_matrix(OSL::Matrix44 &result, OSL::TransformationPtr xform)
{
- // XXX implementation
- return true;
+ /* this is only used for shader and object space, we don't really have
+ * a concept of shader space, so we just use object space for both. */
+ if (xform) {
+ const ShaderData *sd = (const ShaderData *)xform;
+ int object = sd->object;
+
+ if (object != ~0) {
+#ifdef __OBJECT_MOTION__
+ Transform tfm = sd->ob_tfm;
+#else
+ KernelGlobals *kg = kernel_globals;
+ Transform tfm = object_fetch_transform(kg, object, OBJECT_TRANSFORM);
+#endif
+ tfm = transform_transpose(tfm);
+ result = TO_MATRIX44(tfm);
+
+ return true;
+ }
+ }
+
+ return false;
+}
+
+bool OSLRenderServices::get_inverse_matrix(OSL::Matrix44 &result, OSL::TransformationPtr xform)
+{
+ /* this is only used for shader and object space, we don't really have
+ * a concept of shader space, so we just use object space for both. */
+ if (xform) {
+ const ShaderData *sd = (const ShaderData *)xform;
+ int object = sd->object;
+
+ if (object != ~0) {
+#ifdef __OBJECT_MOTION__
+ Transform tfm = sd->ob_itfm;
+#else
+ KernelGlobals *kg = kernel_globals;
+ Transform tfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM);
+#endif
+ tfm = transform_transpose(tfm);
+ result = TO_MATRIX44(tfm);
+
+ return true;
+ }
+ }
+
+ return false;
}
bool OSLRenderServices::get_matrix(OSL::Matrix44 &result, ustring from)
{
- // XXX implementation
- return true;
+ KernelGlobals *kg = kernel_globals;
+
+ if (from == u_ndc) {
+ Transform tfm = transform_transpose(transform_quick_inverse(kernel_data.cam.worldtondc));
+ result = TO_MATRIX44(tfm);
+ return true;
+ }
+ else if (from == u_raster) {
+ Transform tfm = transform_transpose(kernel_data.cam.rastertoworld);
+ result = TO_MATRIX44(tfm);
+ return true;
+ }
+ else if (from == u_screen) {
+ Transform tfm = transform_transpose(kernel_data.cam.screentoworld);
+ result = TO_MATRIX44(tfm);
+ return true;
+ }
+ else if (from == u_camera) {
+ Transform tfm = transform_transpose(kernel_data.cam.cameratoworld);
+ result = TO_MATRIX44(tfm);
+ return true;
+ }
+
+ return false;
+}
+
+bool OSLRenderServices::get_inverse_matrix(OSL::Matrix44 &result, ustring to)
+{
+ KernelGlobals *kg = kernel_globals;
+
+ if (to == u_ndc) {
+ Transform tfm = transform_transpose(kernel_data.cam.worldtondc);
+ result = TO_MATRIX44(tfm);
+ return true;
+ }
+ else if (to == u_raster) {
+ Transform tfm = transform_transpose(kernel_data.cam.worldtoraster);
+ result = TO_MATRIX44(tfm);
+ return true;
+ }
+ else if (to == u_screen) {
+ Transform tfm = transform_transpose(kernel_data.cam.worldtoscreen);
+ result = TO_MATRIX44(tfm);
+ return true;
+ }
+ else if (to == u_camera) {
+ Transform tfm = transform_transpose(kernel_data.cam.worldtocamera);
+ result = TO_MATRIX44(tfm);
+ return true;
+ }
+
+ return false;
}
bool OSLRenderServices::get_array_attribute(void *renderstate, bool derivatives,
@@ -184,16 +287,26 @@ static void set_attribute_float3(float3 f[3], TypeDesc type, bool derivatives, v
if (type == TypeDesc::TypePoint || type == TypeDesc::TypeVector ||
type == TypeDesc::TypeNormal || type == TypeDesc::TypeColor)
{
- float3 *fval = (float3 *)val;
- fval[0] = f[0];
+ float *fval = (float *)val;
+
+ fval[0] = f[0].x;
+ fval[1] = f[0].y;
+ fval[2] = f[0].z;
+
if (derivatives) {
- fval[1] = f[1];
- fval[2] = f[2];
+ fval[3] = f[1].x;
+ fval[4] = f[1].y;
+ fval[5] = f[1].z;
+
+ fval[6] = f[2].x;
+ fval[7] = f[2].y;
+ fval[8] = f[2].z;
}
}
else {
float *fval = (float *)val;
fval[0] = average(f[0]);
+
if (derivatives) {
fval[1] = average(f[1]);
fval[2] = average(f[2]);
@@ -206,16 +319,25 @@ static void set_attribute_float(float f[3], TypeDesc type, bool derivatives, voi
if (type == TypeDesc::TypePoint || type == TypeDesc::TypeVector ||
type == TypeDesc::TypeNormal || type == TypeDesc::TypeColor)
{
- float3 *fval = (float3 *)val;
- fval[0] = make_float3(f[0], f[0], f[0]);
+ float *fval = (float *)val;
+ fval[0] = f[0];
+ fval[1] = f[1];
+ fval[2] = f[2];
+
if (derivatives) {
- fval[1] = make_float3(f[1], f[2], f[1]);
- fval[2] = make_float3(f[2], f[2], f[2]);
+ fval[3] = f[1];
+ fval[4] = f[1];
+ fval[5] = f[1];
+
+ fval[6] = f[2];
+ fval[7] = f[2];
+ fval[8] = f[2];
}
}
else {
float *fval = (float *)val;
fval[0] = f[0];
+
if (derivatives) {
fval[1] = f[1];
fval[2] = f[2];
@@ -223,28 +345,73 @@ static void set_attribute_float(float f[3], TypeDesc type, bool derivatives, voi
}
}
-static bool get_mesh_attribute(KernelGlobals *kg, const ShaderData *sd, const OSLGlobals::Attribute& attr,
- const TypeDesc& type, bool derivatives, void *val)
+static bool set_attribute_int(int i, TypeDesc type, bool derivatives, void *val)
{
- if (attr.type == TypeDesc::TypeFloat) {
- float fval[3];
- fval[0] = triangle_attribute_float(kg, sd, attr.elem, attr.offset,
- (derivatives) ? &fval[1] : NULL, (derivatives) ? &fval[2] : NULL);
- set_attribute_float(fval, type, derivatives, val);
+ if(type.basetype == TypeDesc::INT && type.aggregate == TypeDesc::SCALAR && type.arraylen == 0) {
+ int *ival = (int *)val;
+ ival[0] = i;
+
+ if (derivatives) {
+ ival[1] = 0;
+ ival[2] = 0;
+ }
+
return true;
}
- else if (attr.type == TypeDesc::TypePoint || attr.type == TypeDesc::TypeVector ||
+
+ return false;
+}
+
+static bool set_attribute_float3_3(float3 P[3], TypeDesc type, bool derivatives, void *val)
+{
+ if(type.vecsemantics == TypeDesc::POINT && type.arraylen >= 3) {
+ float *fval = (float *)val;
+
+ fval[0] = P[0].x;
+ fval[1] = P[0].y;
+ fval[2] = P[0].z;
+
+ fval[3] = P[1].x;
+ fval[4] = P[1].y;
+ fval[5] = P[1].z;
+
+ fval[6] = P[2].x;
+ fval[7] = P[2].y;
+ fval[8] = P[2].z;
+
+ if(type.arraylen > 3)
+ memset(fval + 3*3, 0, sizeof(float)*3*(type.arraylen - 3));
+ if (derivatives)
+ memset(fval + type.arraylen*3, 0, sizeof(float)*2*3*type.arraylen);
+
+ return true;
+ }
+
+ return false;
+}
+
+static bool get_mesh_attribute(KernelGlobals *kg, const ShaderData *sd, const OSLGlobals::Attribute& attr,
+ const TypeDesc& type, bool derivatives, void *val)
+{
+ if (attr.type == TypeDesc::TypePoint || attr.type == TypeDesc::TypeVector ||
attr.type == TypeDesc::TypeNormal || attr.type == TypeDesc::TypeColor)
{
- /* todo: this won't work when float3 has w component */
float3 fval[3];
fval[0] = triangle_attribute_float3(kg, sd, attr.elem, attr.offset,
(derivatives) ? &fval[1] : NULL, (derivatives) ? &fval[2] : NULL);
set_attribute_float3(fval, type, derivatives, val);
return true;
}
- else
+ else if (attr.type == TypeDesc::TypeFloat) {
+ float fval[3];
+ fval[0] = triangle_attribute_float(kg, sd, attr.elem, attr.offset,
+ (derivatives) ? &fval[1] : NULL, (derivatives) ? &fval[2] : NULL);
+ set_attribute_float(fval, type, derivatives, val);
+ return true;
+ }
+ else {
return false;
+ }
}
static void get_object_attribute(const OSLGlobals::Attribute& attr, bool derivatives, void *val)
@@ -259,29 +426,45 @@ static void get_object_attribute(const OSLGlobals::Attribute& attr, bool derivat
static bool get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ustring name,
TypeDesc type, bool derivatives, void *val)
{
+ /* todo: turn this into hash table + callback once */
+
/* Object Attributes */
- if (name == "std::object_location") {
+ if (name == "object:location") {
float3 fval[3];
fval[0] = object_location(kg, sd);
fval[1] = fval[2] = make_float3(0.0, 0.0, 0.0); /* derivates set to 0 */
set_attribute_float3(fval, type, derivatives, val);
return true;
}
- else if (name == "std::object_index") {
+ else if (name == "object:index") {
float fval[3];
fval[0] = object_pass_id(kg, sd->object);
fval[1] = fval[2] = 0.0; /* derivates set to 0 */
set_attribute_float(fval, type, derivatives, val);
return true;
}
- else if (name == "std::material_index") {
+ else if (name == "geom:dupli_generated") {
+ float3 fval[3];
+ fval[0] = object_dupli_generated(kg, sd->object);
+ fval[1] = fval[2] = make_float3(0.0, 0.0, 0.0); /* derivates set to 0 */
+ set_attribute_float3(fval, type, derivatives, val);
+ return true;
+ }
+ else if (name == "geom:dupli_uv") {
+ float3 fval[3];
+ fval[0] = object_dupli_uv(kg, sd->object);
+ fval[1] = fval[2] = make_float3(0.0, 0.0, 0.0); /* derivates set to 0 */
+ set_attribute_float3(fval, type, derivatives, val);
+ return true;
+ }
+ else if (name == "material:index") {
float fval[3];
fval[0] = shader_pass_id(kg, sd);
fval[1] = fval[2] = 0.0; /* derivates set to 0 */
set_attribute_float(fval, type, derivatives, val);
return true;
}
- else if (name == "std::object_random") {
+ else if (name == "object:random") {
float fval[3];
fval[0] = object_random_number(kg, sd->object);
fval[1] = fval[2] = 0.0; /* derivates set to 0 */
@@ -290,7 +473,7 @@ static bool get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ust
}
/* Particle Attributes */
- else if (name == "std::particle_index") {
+ else if (name == "particle:index") {
float fval[3];
uint particle_id = object_particle_id(kg, sd->object);
fval[0] = particle_index(kg, particle_id);
@@ -298,7 +481,7 @@ static bool get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ust
set_attribute_float(fval, type, derivatives, val);
return true;
}
- else if (name == "std::particle_age") {
+ else if (name == "particle:age") {
float fval[3];
uint particle_id = object_particle_id(kg, sd->object);
fval[0] = particle_age(kg, particle_id);
@@ -306,7 +489,7 @@ static bool get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ust
set_attribute_float(fval, type, derivatives, val);
return true;
}
- else if (name == "std::particle_lifetime") {
+ else if (name == "particle:lifetime") {
float fval[3];
uint particle_id = object_particle_id(kg, sd->object);
fval[0] = particle_lifetime(kg, particle_id);
@@ -314,7 +497,7 @@ static bool get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ust
set_attribute_float(fval, type, derivatives, val);
return true;
}
- else if (name == "std::particle_location") {
+ else if (name == "particle:location") {
float3 fval[3];
uint particle_id = object_particle_id(kg, sd->object);
fval[0] = particle_location(kg, particle_id);
@@ -323,7 +506,7 @@ static bool get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ust
return true;
}
#if 0 /* unsupported */
- else if (name == "std::particle_rotation") {
+ else if (name == "particle:rotation") {
float4 fval[3];
uint particle_id = object_particle_id(kg, sd->object);
fval[0] = particle_rotation(kg, particle_id);
@@ -332,7 +515,7 @@ static bool get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ust
return true;
}
#endif
- else if (name == "std::particle_size") {
+ else if (name == "particle:size") {
float fval[3];
uint particle_id = object_particle_id(kg, sd->object);
fval[0] = particle_size(kg, particle_id);
@@ -340,7 +523,7 @@ static bool get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ust
set_attribute_float(fval, type, derivatives, val);
return true;
}
- else if (name == "std::particle_velocity") {
+ else if (name == "particle:velocity") {
float3 fval[3];
uint particle_id = object_particle_id(kg, sd->object);
fval[0] = particle_velocity(kg, particle_id);
@@ -348,7 +531,7 @@ static bool get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ust
set_attribute_float3(fval, type, derivatives, val);
return true;
}
- else if (name == "std::particle_angular_velocity") {
+ else if (name == "particle:angular_velocity") {
float3 fval[3];
uint particle_id = object_particle_id(kg, sd->object);
fval[0] = particle_angular_velocity(kg, particle_id);
@@ -356,6 +539,32 @@ static bool get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ust
set_attribute_float3(fval, type, derivatives, val);
return true;
}
+ else if (name == "geom:numpolyvertices") {
+ return set_attribute_int(3, type, derivatives, val);
+ }
+ else if (name == "geom:trianglevertices" || name == "geom:polyvertices") {
+ float3 P[3];
+ triangle_vertices(kg, sd->prim, P);
+ object_position_transform(kg, sd, &P[0]);
+ object_position_transform(kg, sd, &P[1]);
+ object_position_transform(kg, sd, &P[2]);
+ return set_attribute_float3_3(P, type, derivatives, val);
+ }
+ else
+ return false;
+}
+
+static bool get_background_attribute(KernelGlobals *kg, ShaderData *sd, ustring name,
+ TypeDesc type, bool derivatives, void *val)
+{
+ /* Ray Length */
+ if (name == "path:ray_length") {
+ float fval[3];
+ fval[0] = sd->ray_length;
+ fval[1] = fval[2] = 0.0; /* derivates set to 0 */
+ set_attribute_float(fval, type, derivatives, val);
+ return true;
+ }
else
return false;
@@ -380,8 +589,7 @@ bool OSLRenderServices::get_attribute(void *renderstate, bool derivatives, ustri
tri = ~0;
}
else if (object == ~0) {
- /* no background attributes supported */
- return false;
+ return get_background_attribute(kg, sd, name, type, derivatives, val);
}
/* find attribute on object */
@@ -390,7 +598,7 @@ bool OSLRenderServices::get_attribute(void *renderstate, bool derivatives, ustri
if (it != attribute_map.end()) {
const OSLGlobals::Attribute& attr = it->second;
-
+
if (attr.elem != ATTR_ELEMENT_VALUE) {
/* triangle and vertex attributes */
if (tri != ~0)
@@ -404,7 +612,12 @@ bool OSLRenderServices::get_attribute(void *renderstate, bool derivatives, ustri
}
else {
/* not found in attribute, check standard object info */
- return get_object_standard_attribute(kg, sd, name, type, derivatives, val);
+ bool is_std_object_attribute = get_object_standard_attribute(kg, sd, name, type, derivatives, val);
+
+ if (is_std_object_attribute)
+ return true;
+
+ return get_background_attribute(kg, sd, name, type, derivatives, val);
}
return false;
diff --git a/intern/cycles/kernel/osl/osl_services.h b/intern/cycles/kernel/osl/osl_services.h
index 790b02a8abc..fa32d47a89f 100644
--- a/intern/cycles/kernel/osl/osl_services.h
+++ b/intern/cycles/kernel/osl/osl_services.h
@@ -54,7 +54,10 @@ public:
bool get_inverse_matrix(OSL::Matrix44 &result, ustring to, float time);
bool get_matrix(OSL::Matrix44 &result, OSL::TransformationPtr xform);
+ bool get_inverse_matrix(OSL::Matrix44 &result, OSL::TransformationPtr xform);
+
bool get_matrix(OSL::Matrix44 &result, ustring from);
+ bool get_inverse_matrix(OSL::Matrix44 &result, ustring from);
bool get_array_attribute(void *renderstate, bool derivatives,
ustring object, TypeDesc type, ustring name,
diff --git a/intern/cycles/kernel/osl/osl_shader.cpp b/intern/cycles/kernel/osl/osl_shader.cpp
index 98ede0e4f60..8b71ac30ab6 100644
--- a/intern/cycles/kernel/osl/osl_shader.cpp
+++ b/intern/cycles/kernel/osl/osl_shader.cpp
@@ -21,6 +21,7 @@
#include "kernel_globals.h"
#include "kernel_object.h"
+#include "osl_closures.h"
#include "osl_services.h"
#include "osl_shader.h"
@@ -61,10 +62,6 @@ void OSLShader::thread_free(KernelGlobals *kg)
/* Globals */
-#define TO_VEC3(v) (*(OSL::Vec3 *)&(v))
-#define TO_COLOR3(v) (*(OSL::Color3 *)&(v))
-#define TO_FLOAT3(v) make_float3(v[0], v[1], v[2])
-
static void shaderdata_to_shaderglobals(KernelGlobals *kg, ShaderData *sd,
int path_flag, OSL::ShaderGlobals *globals)
{
@@ -127,27 +124,20 @@ static void flatten_surface_closure_tree(ShaderData *sd, bool no_glossy,
if (sd->num_closure == MAX_CLOSURE)
return;
- OSL::BSDFClosure *bsdf = (OSL::BSDFClosure *)prim;
- ustring scattering = bsdf->scattering();
+ CBSDFClosure *bsdf = (CBSDFClosure *)prim;
+ int scattering = bsdf->scattering();
/* no caustics option */
- if (no_glossy && scattering == OSL::Labels::GLOSSY)
+ if (no_glossy && scattering == LABEL_GLOSSY)
return;
/* sample weight */
- float albedo = bsdf->albedo(TO_VEC3(sd->I));
- float sample_weight = fabsf(average(weight)) * albedo;
+ float sample_weight = fabsf(average(weight));
- sc.sample_weight = sample_weight;
- sc.type = CLOSURE_BSDF_ID;
+ sd->flag |= bsdf->shaderdata_flag();
- /* scattering flags */
- if (scattering == OSL::Labels::DIFFUSE)
- sd->flag |= SD_BSDF | SD_BSDF_HAS_EVAL;
- else if (scattering == OSL::Labels::GLOSSY)
- sd->flag |= SD_BSDF | SD_BSDF_HAS_EVAL | SD_BSDF_GLOSSY;
- else
- sd->flag |= SD_BSDF;
+ sc.sample_weight = sample_weight;
+ sc.type = bsdf->shaderclosure_type();
/* add */
sd->closure[sd->num_closure++] = sc;
@@ -394,54 +384,34 @@ void OSLShader::release(KernelGlobals *kg, ShaderData *sd)
int OSLShader::bsdf_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3& eval, float3& omega_in, differential3& domega_in, float& pdf)
{
- OSL::BSDFClosure *sample_bsdf = (OSL::BSDFClosure *)sc->prim;
- int label = LABEL_NONE;
+ CBSDFClosure *sample_bsdf = (CBSDFClosure *)sc->prim;
pdf = 0.0f;
- /* sample BSDF closure */
- ustring ulabel;
-
- ulabel = sample_bsdf->sample(TO_VEC3(sd->Ng),
- TO_VEC3(sd->I), TO_VEC3(sd->dI.dx), TO_VEC3(sd->dI.dy),
- randu, randv,
- TO_VEC3(omega_in), TO_VEC3(domega_in.dx), TO_VEC3(domega_in.dy),
- pdf, TO_COLOR3(eval));
-
- /* convert OSL label */
- if (ulabel == OSL::Labels::REFLECT)
- label = LABEL_REFLECT;
- else if (ulabel == OSL::Labels::TRANSMIT)
- label = LABEL_TRANSMIT;
- else
- return LABEL_NONE; /* sampling failed */
-
- /* convert scattering to our bitflag label */
- ustring uscattering = sample_bsdf->scattering();
-
- if (uscattering == OSL::Labels::DIFFUSE)
- label |= LABEL_DIFFUSE;
- else if (uscattering == OSL::Labels::GLOSSY)
- label |= LABEL_GLOSSY;
- else if (uscattering == OSL::Labels::SINGULAR)
- label |= LABEL_SINGULAR;
- else
- label |= LABEL_TRANSPARENT;
-
- return label;
+ return sample_bsdf->sample(sd->Ng,
+ sd->I, sd->dI.dx, sd->dI.dy,
+ randu, randv,
+ omega_in, domega_in.dx, domega_in.dy,
+ pdf, eval);
}
float3 OSLShader::bsdf_eval(const ShaderData *sd, const ShaderClosure *sc, const float3& omega_in, float& pdf)
{
- OSL::BSDFClosure *bsdf = (OSL::BSDFClosure *)sc->prim;
- OSL::Color3 bsdf_eval;
+ CBSDFClosure *bsdf = (CBSDFClosure *)sc->prim;
+ float3 bsdf_eval;
if (dot(sd->Ng, omega_in) >= 0.0f)
- bsdf_eval = bsdf->eval_reflect(TO_VEC3(sd->I), TO_VEC3(omega_in), pdf);
+ bsdf_eval = bsdf->eval_reflect(sd->I, omega_in, pdf);
else
- bsdf_eval = bsdf->eval_transmit(TO_VEC3(sd->I), TO_VEC3(omega_in), pdf);
+ bsdf_eval = bsdf->eval_transmit(sd->I, omega_in, pdf);
- return TO_FLOAT3(bsdf_eval);
+ return bsdf_eval;
+}
+
+void OSLShader::bsdf_blur(ShaderClosure *sc, float roughness)
+{
+ CBSDFClosure *bsdf = (CBSDFClosure *)sc->prim;
+ bsdf->blur(roughness);
}
/* Emissive Closure */
@@ -456,7 +426,7 @@ float3 OSLShader::emissive_eval(const ShaderData *sd, const ShaderClosure *sc)
/* Volume Closure */
-float3 OSLShader::volume_eval_phase(const ShaderData *sd, const ShaderClosure *sc, const float3 omega_in, const float3 omega_out)
+float3 OSLShader::volume_eval_phase(const ShaderClosure *sc, const float3 omega_in, const float3 omega_out)
{
OSL::VolumeClosure *volume = (OSL::VolumeClosure *)sc->prim;
OSL::Color3 volume_eval = volume->eval_phase(TO_VEC3(omega_in), TO_VEC3(omega_out));
diff --git a/intern/cycles/kernel/osl/osl_shader.h b/intern/cycles/kernel/osl/osl_shader.h
index e2f4d1e94b8..9ff31e9160b 100644
--- a/intern/cycles/kernel/osl/osl_shader.h
+++ b/intern/cycles/kernel/osl/osl_shader.h
@@ -72,10 +72,11 @@ public:
float3& eval, float3& omega_in, differential3& domega_in, float& pdf);
static float3 bsdf_eval(const ShaderData *sd, const ShaderClosure *sc,
const float3& omega_in, float& pdf);
+ static void bsdf_blur(ShaderClosure *sc, float roughness);
static float3 emissive_eval(const ShaderData *sd, const ShaderClosure *sc);
- static float3 volume_eval_phase(const ShaderData *sd, const ShaderClosure *sc,
+ static float3 volume_eval_phase(const ShaderClosure *sc,
const float3 omega_in, const float3 omega_out);
/* release */
diff --git a/intern/cycles/kernel/osl/vol_subsurface.cpp b/intern/cycles/kernel/osl/vol_subsurface.cpp
deleted file mode 100644
index 818a057b6cc..00000000000
--- a/intern/cycles/kernel/osl/vol_subsurface.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Adapted from Open Shading Language with this license:
- *
- * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
- * All Rights Reserved.
- *
- * Modifications Copyright 2011, Blender Foundation.
- *
- * 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.
- * * Neither the name of Sony Pictures Imageworks nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 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 <OpenImageIO/fmath.h>
-
-#include <OSL/genclosure.h>
-
-#include "osl_closures.h"
-
-CCL_NAMESPACE_BEGIN
-
-using namespace OSL;
-
-// Computes scattering properties based on Jensen's reparameterization
-// described in:
-// http://graphics.ucsd.edu/~henrik/papers/fast_bssrdf/
-
-class SubsurfaceClosure : public VolumeClosure {
-public:
- float m_g;
- float m_eta;
- Color3 m_mfp, m_albedo;
- static float root_find_Rd(const float Rd0, const float A) {
- // quick exit for trivial cases
- if (Rd0 <= 0) return 0;
- const float A43 = A * 4.0f / 3.0f;
- // Find alpha such that f(alpha) = Rd (see eq.15). A simple bisection
- // method can be used because this function is monotonicaly increasing.
- float lo = 0, hi = 1;
- for (int i = 0; i < 20; i++) { // 2^20 divisions should be sufficient
- // eval function at midpoint
- float alpha = 0.5f * (lo + hi);
- float a1 = sqrtf(3 * (1 - alpha));
- float e1 = expf(-a1);
- float e2 = expf(-A43 * a1);
- float Rd = 0.5f * alpha * (1 + e2) * e1 - Rd0;
- if (fabsf(Rd) < 1e-6f)
- return alpha; // close enough
- else if (Rd > 0)
- hi = alpha; // root is on left side
- else
- lo = alpha; // root is on right side
- }
- // didn't quite converge, pick result in the middle of remaining interval
- return 0.5f * (lo + hi);
- }
- SubsurfaceClosure() {
- }
-
- void setup()
- {
- ior(m_eta);
-
- if (m_g >= 0.99f) m_g = 0.99f;
- if (m_g <= -0.99f) m_g = -0.99f;
-
- // eq.10
- float inv_eta = 1 / m_eta;
- float Fdr = -1.440f * inv_eta * inv_eta + 0.710 * inv_eta + 0.668f + 0.0636 * m_eta;
- float A = (1 + Fdr) / (1 - Fdr);
- // compute sigma_s, sigma_a (eq.16)
- Color3 alpha_prime = Color3(root_find_Rd(m_albedo[0], A),
- root_find_Rd(m_albedo[1], A),
- root_find_Rd(m_albedo[2], A));
- Color3 sigma_t_prime = Color3(m_mfp.x > 0 ? 1.0f / (m_mfp[0] * sqrtf(3 * (1 - alpha_prime[0]))) : 0.0f,
- m_mfp.y > 0 ? 1.0f / (m_mfp[1] * sqrtf(3 * (1 - alpha_prime[1]))) : 0.0f,
- m_mfp.z > 0 ? 1.0f / (m_mfp[2] * sqrtf(3 * (1 - alpha_prime[2]))) : 0.0f);
- Color3 sigma_s_prime = alpha_prime * sigma_t_prime;
-
- sigma_s((1.0f / (1 - m_g)) * sigma_s_prime);
- sigma_a(sigma_t_prime - sigma_s_prime);
- }
-
- bool mergeable(const ClosurePrimitive *other) const {
- const SubsurfaceClosure *comp = (const SubsurfaceClosure *)other;
- return m_g == comp->m_g && VolumeClosure::mergeable(other);
- }
-
- size_t memsize() const { return sizeof(*this); }
-
- const char *name() const { return "subsurface"; }
-
- void print_on(std::ostream &out) const {
- out << name() << " ()";
- }
-
- virtual Color3 eval_phase(const Vec3 &omega_in, const Vec3 &omega_out) const {
- float costheta = omega_in.dot(omega_out);
- float ph = 0.25f * float(M_1_PI) * ((1 - m_g * m_g) / powf(1 + m_g * m_g - 2.0f * m_g * costheta, 1.5f));
- return Color3(ph, ph, ph);
- }
-};
-
-
-
-ClosureParam closure_subsurface_params[] = {
- CLOSURE_FLOAT_PARAM(SubsurfaceClosure, m_eta),
- CLOSURE_FLOAT_PARAM(SubsurfaceClosure, m_g),
- CLOSURE_COLOR_PARAM(SubsurfaceClosure, m_mfp),
- CLOSURE_COLOR_PARAM(SubsurfaceClosure, m_albedo),
- CLOSURE_STRING_KEYPARAM("label"),
- CLOSURE_FINISH_PARAM(SubsurfaceClosure)
-};
-
-CLOSURE_PREPARE(closure_subsurface_prepare, SubsurfaceClosure)
-
-CCL_NAMESPACE_END
-
diff --git a/intern/cycles/kernel/osl/nodes/CMakeLists.txt b/intern/cycles/kernel/shaders/CMakeLists.txt
index 729d4dae1c9..00ab52a1d13 100644
--- a/intern/cycles/kernel/osl/nodes/CMakeLists.txt
+++ b/intern/cycles/kernel/shaders/CMakeLists.txt
@@ -12,6 +12,7 @@ set(SRC_OSL
node_combine_rgb.osl
node_convert_from_color.osl
node_convert_from_float.osl
+ node_convert_from_int.osl
node_convert_from_normal.osl
node_convert_from_point.osl
node_convert_from_vector.osl
@@ -29,7 +30,9 @@ set(SRC_OSL
node_hsv.osl
node_image_texture.osl
node_invert.osl
+ node_layer_weight.osl
node_light_path.osl
+ node_light_falloff.osl
node_magic_texture.osl
node_mapping.osl
node_math.osl
@@ -43,7 +46,9 @@ set(SRC_OSL
node_output_surface.osl
node_output_volume.osl
node_particle_info.osl
+ node_rgb_ramp.osl
node_separate_rgb.osl
+ node_set_normal.osl
node_sky_texture.osl
node_texture_coordinate.osl
node_translucent_bsdf.osl
@@ -71,11 +76,11 @@ set(SRC_OSO
# TODO, add a module to compile OSL
foreach(_file ${SRC_OSL})
set(_OSL_FILE ${CMAKE_CURRENT_SOURCE_DIR}/${_file})
- string(REPLACE ".osl" ".oso" _OSO_FILE ${_OSL_FILE}) # TODO, replace extension only
+ string(REPLACE ".osl" ".oso" _OSO_FILE ${_OSL_FILE})
string(REPLACE ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} _OSO_FILE ${_OSO_FILE})
add_custom_command(
OUTPUT ${_OSO_FILE}
- COMMAND ${OSL_COMPILER} -O2 ${_OSL_FILE}
+ COMMAND ${OSL_COMPILER} -O2 -I"${CMAKE_CURRENT_SOURCE_DIR}" ${_OSL_FILE}
DEPENDS ${_OSL_FILE} ${SRC_OSL_HEADERS})
list(APPEND SRC_OSO
${_OSO_FILE}
@@ -85,7 +90,9 @@ foreach(_file ${SRC_OSL})
unset(_OSO_FILE)
endforeach()
-add_custom_target(shader ALL DEPENDS ${SRC_OSO} ${SRC_OSL_HEADERS})
+add_custom_target(cycles_osl_shaders ALL DEPENDS ${SRC_OSO} ${SRC_OSL_HEADERS})
# CMAKE_CURRENT_SOURCE_DIR is already included in OSO paths
delayed_install("" "${SRC_OSO}" ${CYCLES_INSTALL_PATH}/shader)
+delayed_install("${CMAKE_CURRENT_SOURCE_DIR}" "${SRC_OSL_HEADERS}" ${CYCLES_INSTALL_PATH}/shader)
+
diff --git a/intern/cycles/kernel/osl/nodes/node_add_closure.osl b/intern/cycles/kernel/shaders/node_add_closure.osl
index ecf6bf5912e..ecf6bf5912e 100644
--- a/intern/cycles/kernel/osl/nodes/node_add_closure.osl
+++ b/intern/cycles/kernel/shaders/node_add_closure.osl
diff --git a/intern/cycles/kernel/osl/nodes/node_attribute.osl b/intern/cycles/kernel/shaders/node_attribute.osl
index d273d0c68d7..8e7c846d1a3 100644
--- a/intern/cycles/kernel/osl/nodes/node_attribute.osl
+++ b/intern/cycles/kernel/shaders/node_attribute.osl
@@ -29,12 +29,12 @@ shader node_attribute(
Vector = point(Color);
getattribute(name, Fac);
- if(bump_offset == "dx") {
+ if (bump_offset == "dx") {
Color += Dx(Color);
Vector += Dx(Vector);
Fac += Dx(Fac);
}
- else if(bump_offset == "dy") {
+ else if (bump_offset == "dy") {
Color += Dy(Color);
Vector += Dy(Vector);
Fac += Dy(Fac);
diff --git a/intern/cycles/kernel/osl/nodes/node_background.osl b/intern/cycles/kernel/shaders/node_background.osl
index 69f8d85a82e..b51a1685294 100644
--- a/intern/cycles/kernel/osl/nodes/node_background.osl
+++ b/intern/cycles/kernel/shaders/node_background.osl
@@ -23,6 +23,6 @@ shader node_background(
float Strength = 1.0,
output closure color Background = background())
{
- Background = Color*Strength*background();
+ Background = Color * Strength * background();
}
diff --git a/intern/cycles/kernel/osl/nodes/node_brick_texture.osl b/intern/cycles/kernel/shaders/node_brick_texture.osl
index 4daceb4018e..478d9457001 100644
--- a/intern/cycles/kernel/osl/nodes/node_brick_texture.osl
+++ b/intern/cycles/kernel/shaders/node_brick_texture.osl
@@ -40,21 +40,21 @@ float brick(point p, float mortar_size, float bias,
rownum = (int)floor(p[1] / row_height);
- if(offset_frequency && squash_frequency) {
- brick_width *= ((int)(rownum) % squash_frequency ) ? 1.0 : squash_amount; /* squash */
- offset = ((int)(rownum) % offset_frequency ) ? 0 : (brick_width*offset_amount); /* offset */
+ if (offset_frequency && squash_frequency) {
+ brick_width *= ((int)(rownum) % squash_frequency) ? 1.0 : squash_amount; /* squash */
+ offset = ((int)(rownum) % offset_frequency) ? 0 : (brick_width * offset_amount); /* offset */
}
- bricknum = (int)floor((p[0]+offset) / brick_width);
+ bricknum = (int)floor((p[0] + offset) / brick_width);
- x = (p[0]+offset) - brick_width*bricknum;
- y = p[1] - row_height*rownum;
+ x = (p[0] + offset) - brick_width * bricknum;
+ y = p[1] - row_height * rownum;
tint = clamp((brick_noise((rownum << 16) + (bricknum & 65535)) + bias), 0.0, 1.0);
return (x < mortar_size || y < mortar_size ||
- x > (brick_width - mortar_size) ||
- y > (row_height - mortar_size)) ? 1.0 : 0.0;
+ x > (brick_width - mortar_size) ||
+ y > (row_height - mortar_size)) ? 1.0 : 0.0;
}
shader node_brick_texture(
@@ -77,10 +77,10 @@ shader node_brick_texture(
float tint = 0.0;
color Col = Color1;
- Fac = brick(Vector*Scale, MortarSize, Bias, BrickWidth, RowHeight,
+ Fac = brick(Vector * Scale, MortarSize, Bias, BrickWidth, RowHeight,
Offset, OffsetFrequency, Squash, SquashFrequency, tint);
- if(Fac != 1.0) {
+ if (Fac != 1.0) {
float facm = 1.0 - tint;
Col[0] = facm * (Color1[0]) + tint * Color2[0];
@@ -89,6 +89,5 @@ shader node_brick_texture(
}
Color = (Fac == 1.0) ? Mortar: Col;
-
}
diff --git a/intern/cycles/kernel/osl/nodes/node_brightness.osl b/intern/cycles/kernel/shaders/node_brightness.osl
index 4f19a20f736..8e9f5c9c796 100644
--- a/intern/cycles/kernel/osl/nodes/node_brightness.osl
+++ b/intern/cycles/kernel/shaders/node_brightness.osl
@@ -24,7 +24,7 @@ shader node_brightness(
float Contrast = 0.0,
output color ColorOut = color(0.8, 0.8, 0.8))
{
- float delta = Contrast * (1.0/200.0);
+ float delta = Contrast * (1.0 / 200.0);
float a = 1.0 - delta * 2.0;
float b;
@@ -32,13 +32,13 @@ shader node_brightness(
float bright_factor = Brightness / 100.0;
/*
- * The algorithm is by Werner D. Streidt
- * (http://visca.com/ffactory/archives/5-99/msg00021.html)
- * Extracted of OpenCV demhist.c
- */
+ * The algorithm is by Werner D. Streidt
+ * (http://visca.com/ffactory/archives/5-99/msg00021.html)
+ * Extracted of OpenCV demhist.c
+ */
if (Contrast > 0.0) {
- a = (a < 0.0 ? 1.0/a : 0.0);
+ a = (a < 0.0 ? 1.0 / a : 0.0);
b = a * (bright_factor - delta);
}
else {
diff --git a/intern/cycles/kernel/osl/nodes/node_bump.osl b/intern/cycles/kernel/shaders/node_bump.osl
index a3849e70f98..24db1b24458 100644
--- a/intern/cycles/kernel/osl/nodes/node_bump.osl
+++ b/intern/cycles/kernel/shaders/node_bump.osl
@@ -18,29 +18,32 @@
#include "stdosl.h"
-/* "Bump Mapping Unparametrized Surfaces on the GPU"
+/* "Bump Mapping Unparameterized Surfaces on the GPU"
* Morten S. Mikkelsen, 2010 */
surface node_bump(
+ normal NormalIn = N,
+ float Strength = 0.0,
float SampleCenter = 0.0,
float SampleX = 0.0,
float SampleY = 0.0,
output normal Normal = N)
{
- float dx = SampleX - SampleCenter;
- float dy = SampleY - SampleCenter;
-
+ /* get surface tangents from normal */
vector dPdx = Dx(P);
vector dPdy = Dy(P);
- vector Rx = cross(dPdy, N);
- vector Ry = cross(N, dPdx);
+ vector Rx = cross(dPdy, NormalIn);
+ vector Ry = cross(NormalIn, dPdx);
+ /* compute surface gradient and determinant */
float det = dot(dPdx, Rx);
- vector surfgrad = dx*Rx + dy*Ry;
+ vector surfgrad = (SampleX - SampleCenter) * Rx + (SampleY - SampleCenter) * Ry;
- surfgrad *= 0.1; /* todo: remove this factor */
+ surfgrad *= Strength;
+ float absdet = fabs(det);
- Normal = normalize(abs(det)*N - sign(det)*surfgrad);
+ /* compute and output perturbed normal */
+ Normal = normalize(absdet * NormalIn - sign(det) * surfgrad);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_camera.osl b/intern/cycles/kernel/shaders/node_camera.osl
index 898ebd2bbb2..898ebd2bbb2 100644
--- a/intern/cycles/kernel/osl/nodes/node_camera.osl
+++ b/intern/cycles/kernel/shaders/node_camera.osl
diff --git a/intern/cycles/kernel/osl/nodes/node_checker_texture.osl b/intern/cycles/kernel/shaders/node_checker_texture.osl
index e92d7be34fc..577caf308ff 100644
--- a/intern/cycles/kernel/osl/nodes/node_checker_texture.osl
+++ b/intern/cycles/kernel/shaders/node_checker_texture.osl
@@ -23,15 +23,15 @@
float checker(point p)
{
- p[0] = (p[0] + 0.00001)*0.9999;
- p[1] = (p[1] + 0.00001)*0.9999;
- p[2] = (p[2] + 0.00001)*0.9999;
+ p[0] = (p[0] + 0.00001) * 0.9999;
+ p[1] = (p[1] + 0.00001) * 0.9999;
+ p[2] = (p[2] + 0.00001) * 0.9999;
int xi = (int)fabs(floor(p[0]));
int yi = (int)fabs(floor(p[1]));
int zi = (int)fabs(floor(p[2]));
- if((xi % 2 == yi % 2) == (zi % 2)) {
+ if ((xi % 2 == yi % 2) == (zi % 2)) {
return 1.0;
}
else {
@@ -47,8 +47,8 @@ shader node_checker_texture(
output float Fac = 0.0,
output color Color = color(0.0, 0.0, 0.0))
{
- Fac = checker(Vector*Scale);
- if(Fac == 1.0) {
+ Fac = checker(Vector * Scale);
+ if (Fac == 1.0) {
Color = Color1;
}
else {
diff --git a/intern/cycles/kernel/osl/nodes/node_color.h b/intern/cycles/kernel/shaders/node_color.h
index 80786e4e369..80786e4e369 100644
--- a/intern/cycles/kernel/osl/nodes/node_color.h
+++ b/intern/cycles/kernel/shaders/node_color.h
diff --git a/intern/cycles/kernel/osl/nodes/node_combine_rgb.osl b/intern/cycles/kernel/shaders/node_combine_rgb.osl
index 546369f660e..546369f660e 100644
--- a/intern/cycles/kernel/osl/nodes/node_combine_rgb.osl
+++ b/intern/cycles/kernel/shaders/node_combine_rgb.osl
diff --git a/intern/cycles/kernel/osl/nodes/node_convert_from_color.osl b/intern/cycles/kernel/shaders/node_convert_from_color.osl
index 97356139c48..2884c772414 100644
--- a/intern/cycles/kernel/osl/nodes/node_convert_from_color.osl
+++ b/intern/cycles/kernel/shaders/node_convert_from_color.osl
@@ -21,11 +21,13 @@
shader node_convert_from_color(
color Color = color(0.0, 0.0, 0.0),
output float Val = 0.0,
+ output int ValInt = 0,
output vector Vector = vector(0.0, 0.0, 0.0),
output point Point = point(0.0, 0.0, 0.0),
output normal Normal = normal(0.0, 0.0, 0.0))
{
- Val = Color[0]*0.2126 + Color[1]*0.7152 + Color[2]*0.0722;
+ Val = Color[0] * 0.2126 + Color[1] * 0.7152 + Color[2] * 0.0722;
+ ValInt = (int)(Color[0]*0.2126 + Color[1]*0.7152 + Color[2]*0.0722);
Vector = vector(Color[0], Color[1], Color[2]);
Point = point(Color[0], Color[1], Color[2]);
Normal = normal(Color[0], Color[1], Color[2]);
diff --git a/intern/cycles/kernel/osl/nodes/node_convert_from_float.osl b/intern/cycles/kernel/shaders/node_convert_from_float.osl
index 00e78f3bab4..4466fbae3a6 100644
--- a/intern/cycles/kernel/osl/nodes/node_convert_from_float.osl
+++ b/intern/cycles/kernel/shaders/node_convert_from_float.osl
@@ -20,11 +20,13 @@
shader node_convert_from_float(
float Val = 0.0,
+ output int ValInt = 0,
output color Color = color(0.0, 0.0, 0.0),
output vector Vector = vector(0.0, 0.0, 0.0),
output point Point = point(0.0, 0.0, 0.0),
output normal Normal = normal(0.0, 0.0, 0.0))
{
+ ValInt = (int)Val;
Color = color(Val, Val, Val);
Vector = vector(Val, Val, Val);
Point = point(Val, Val, Val);
diff --git a/intern/cycles/kernel/shaders/node_convert_from_int.osl b/intern/cycles/kernel/shaders/node_convert_from_int.osl
new file mode 100644
index 00000000000..060d4184fa6
--- /dev/null
+++ b/intern/cycles/kernel/shaders/node_convert_from_int.osl
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2011, Blender Foundation.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "stdosl.h"
+
+shader node_convert_from_int(
+ int ValInt = 0,
+ output float Val = 0.0,
+ output color Color = color(0.0, 0.0, 0.0),
+ output vector Vector = vector(0.0, 0.0, 0.0),
+ output point Point = point(0.0, 0.0, 0.0),
+ output normal Normal = normal(0.0, 0.0, 0.0))
+{
+ float f = (float)ValInt;
+ Val = f;
+ Color = color(f, f, f);
+ Vector = vector(f, f, f);
+ Point = point(f, f, f);
+ Normal = normal(f, f, f);
+}
+
diff --git a/intern/cycles/kernel/osl/nodes/node_convert_from_normal.osl b/intern/cycles/kernel/shaders/node_convert_from_normal.osl
index 0bb9092591d..32ef430d93b 100644
--- a/intern/cycles/kernel/osl/nodes/node_convert_from_normal.osl
+++ b/intern/cycles/kernel/shaders/node_convert_from_normal.osl
@@ -21,11 +21,13 @@
shader node_convert_from_normal(
normal Normal = normal(0.0, 0.0, 0.0),
output float Val = 0.0,
+ output int ValInt = 0,
output vector Vector = vector(0.0, 0.0, 0.0),
output color Color = color(0.0, 0.0, 0.0),
output point Point = point(0.0, 0.0, 0.0))
{
- Val = (Normal[0] + Normal[1] + Normal[2])*(1.0/3.0);
+ Val = (Normal[0] + Normal[1] + Normal[2]) * (1.0 / 3.0);
+ ValInt = (int)((Normal[0] + Normal[1] + Normal[2]) * (1.0 / 3.0));
Vector = vector(Normal[0], Normal[1], Normal[2]);
Color = color(Normal[0], Normal[1], Normal[2]);
Point = point(Normal[0], Normal[1], Normal[2]);
diff --git a/intern/cycles/kernel/osl/nodes/node_convert_from_point.osl b/intern/cycles/kernel/shaders/node_convert_from_point.osl
index e66d6a864d6..a9435c8abf4 100644
--- a/intern/cycles/kernel/osl/nodes/node_convert_from_point.osl
+++ b/intern/cycles/kernel/shaders/node_convert_from_point.osl
@@ -21,11 +21,13 @@
shader node_convert_from_point(
point Point = point(0.0, 0.0, 0.0),
output float Val = 0.0,
+ output int ValInt = 0,
output vector Vector = vector(0.0, 0.0, 0.0),
output color Color = color(0.0, 0.0, 0.0),
output normal Normal = normal(0.0, 0.0, 0.0))
{
- Val = (Point[0] + Point[1] + Point[2])*(1.0/3.0);
+ Val = (Point[0] + Point[1] + Point[2]) * (1.0 / 3.0);
+ ValInt = (int)((Normal[0] + Normal[1] + Normal[2]) * (1.0 / 3.0));
Vector = vector(Point[0], Point[1], Point[2]);
Color = color(Point[0], Point[1], Point[2]);
Normal = normal(Point[0], Point[1], Point[2]);
diff --git a/intern/cycles/kernel/osl/nodes/node_convert_from_vector.osl b/intern/cycles/kernel/shaders/node_convert_from_vector.osl
index 37ba9582cad..4516f92c753 100644
--- a/intern/cycles/kernel/osl/nodes/node_convert_from_vector.osl
+++ b/intern/cycles/kernel/shaders/node_convert_from_vector.osl
@@ -21,11 +21,13 @@
shader node_convert_from_vector(
vector Vector = vector(0.0, 0.0, 0.0),
output float Val = 0.0,
+ output int ValInt = 0,
output color Color = color(0.0, 0.0, 0.0),
output point Point = point(0.0, 0.0, 0.0),
output normal Normal = normal(0.0, 0.0, 0.0))
{
- Val = (Vector[0] + Vector[1] + Vector[2])*(1.0/3.0);
+ Val = (Vector[0] + Vector[1] + Vector[2]) * (1.0 / 3.0);
+ ValInt = (int)((Normal[0] + Normal[1] + Normal[2]) * (1.0 / 3.0));
Color = color(Vector[0], Vector[1], Vector[2]);
Point = point(Vector[0], Vector[1], Vector[2]);
Normal = normal(Vector[0], Vector[1], Vector[2]);
diff --git a/intern/cycles/kernel/osl/nodes/node_diffuse_bsdf.osl b/intern/cycles/kernel/shaders/node_diffuse_bsdf.osl
index 6075b7c93f3..d6dc17316e8 100644
--- a/intern/cycles/kernel/osl/nodes/node_diffuse_bsdf.osl
+++ b/intern/cycles/kernel/shaders/node_diffuse_bsdf.osl
@@ -24,7 +24,7 @@ shader node_diffuse_bsdf(
normal Normal = N,
output closure color BSDF = diffuse(Normal))
{
- if(Roughness == 0.0)
+ if (Roughness == 0.0)
BSDF = Color * diffuse(Normal);
else
BSDF = Color * oren_nayar(Normal, Roughness);
diff --git a/intern/cycles/kernel/osl/nodes/node_emission.osl b/intern/cycles/kernel/shaders/node_emission.osl
index 8bfd1af173a..7ad0f9f7760 100644
--- a/intern/cycles/kernel/osl/nodes/node_emission.osl
+++ b/intern/cycles/kernel/shaders/node_emission.osl
@@ -24,9 +24,9 @@ shader node_emission(
float Strength = 1.0,
output closure color Emission = emission())
{
- if(TotalPower)
- Emission = ((Strength/surfacearea())*Color)*emission();
+ if (TotalPower)
+ Emission = ((Strength / surfacearea()) * Color) * emission();
else
- Emission = (Strength*Color)*emission();
+ Emission = (Strength * Color) * emission();
}
diff --git a/intern/cycles/kernel/osl/nodes/node_environment_texture.osl b/intern/cycles/kernel/shaders/node_environment_texture.osl
index 3ad806781eb..bad62e56ab4 100644
--- a/intern/cycles/kernel/osl/nodes/node_environment_texture.osl
+++ b/intern/cycles/kernel/shaders/node_environment_texture.osl
@@ -28,7 +28,7 @@ shader node_environment_texture(
{
Color = (color)environment(filename, Vector, "alpha", Alpha);
- if(color_space == "sRGB")
+ if (color_space == "sRGB")
Color = color_srgb_to_scene_linear(Color);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_fresnel.h b/intern/cycles/kernel/shaders/node_fresnel.h
index dfd0a23fe1e..dfd0a23fe1e 100644
--- a/intern/cycles/kernel/osl/nodes/node_fresnel.h
+++ b/intern/cycles/kernel/shaders/node_fresnel.h
diff --git a/intern/cycles/kernel/osl/nodes/node_fresnel.osl b/intern/cycles/kernel/shaders/node_fresnel.osl
index 3af4448b43f..e8d8e945f98 100644
--- a/intern/cycles/kernel/osl/nodes/node_fresnel.osl
+++ b/intern/cycles/kernel/shaders/node_fresnel.osl
@@ -25,7 +25,7 @@ shader node_fresnel(
output float Fac = 0.0)
{
float f = max(IOR, 1.0 + 1e-5);
- float eta = backfacing()? 1.0/f: f;
+ float eta = backfacing() ? 1.0 / f: f;
Fac = fresnel_dielectric(I, Normal, eta);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_gamma.osl b/intern/cycles/kernel/shaders/node_gamma.osl
index d55e908b0b7..d55e908b0b7 100644
--- a/intern/cycles/kernel/osl/nodes/node_gamma.osl
+++ b/intern/cycles/kernel/shaders/node_gamma.osl
diff --git a/intern/cycles/kernel/osl/nodes/node_geometry.osl b/intern/cycles/kernel/shaders/node_geometry.osl
index 9efc2a75c64..953c5d1fa2b 100644
--- a/intern/cycles/kernel/osl/nodes/node_geometry.osl
+++ b/intern/cycles/kernel/shaders/node_geometry.osl
@@ -32,19 +32,41 @@ shader node_geometry(
{
Position = P;
Normal = NormalIn;
- Tangent = normalize(dPdu);
TrueNormal = Ng;
Incoming = I;
Parametric = point(u, v, 0.0);
Backfacing = backfacing();
- if(bump_offset == "dx") {
+ if (bump_offset == "dx") {
Position += Dx(Position);
Parametric += Dx(Parametric);
}
- else if(bump_offset == "dy") {
+ else if (bump_offset == "dy") {
Position += Dy(Position);
Parametric += Dy(Parametric);
}
+
+ /* first try to get tangent attribute */
+ vector T;
+
+ if (getattribute("geom:tangent", T)) {
+ /* ensure orthogonal and normalized (interpolation breaks it) */
+ T = transform("object", "world", T);
+ Tangent = cross(Normal, normalize(cross(T, Normal)));
+ }
+ else {
+ point generated;
+
+ /* try to create spherical tangent from generated coordinates */
+ if (getattribute("geom:generated", generated)) {
+ T = vector(-(generated[1] - 0.5), (generated[0] - 0.5), 0.0);
+ T = transform("object", "world", T);
+ Tangent = cross(Normal, normalize(cross(T, Normal)));
+ }
+ else {
+ /* otherwise use surface derivatives */
+ Tangent = normalize(dPdu);
+ }
+ }
}
diff --git a/intern/cycles/kernel/osl/nodes/node_glass_bsdf.osl b/intern/cycles/kernel/shaders/node_glass_bsdf.osl
index 52743669c99..30b9d301f32 100644
--- a/intern/cycles/kernel/osl/nodes/node_glass_bsdf.osl
+++ b/intern/cycles/kernel/shaders/node_glass_bsdf.osl
@@ -28,14 +28,16 @@ shader node_glass_bsdf(
output closure color BSDF = diffuse(Normal))
{
float f = max(IOR, 1.0 + 1e-5);
- float eta = backfacing()? 1.0/f: f;
+ float eta = backfacing() ? 1.0 / f: f;
float Fr = fresnel_dielectric(I, Normal, eta);
- if(distribution == "Sharp")
- BSDF = Color*(Fr*reflection(Normal) + (1.0-Fr)*refraction(Normal, eta));
- else if(distribution == "Beckmann")
- BSDF = Color*(Fr*microfacet_beckmann(Normal, Roughness, eta) + (1.0-Fr)*microfacet_beckmann_refraction(Normal, Roughness, eta));
- else if(distribution == "GGX")
- BSDF = Color*(Fr*microfacet_ggx(Normal, Roughness, eta) + (1.0-Fr)*microfacet_ggx_refraction(Normal, Roughness, eta));
+ if (distribution == "Sharp")
+ BSDF = Color * (Fr * reflection(Normal) + (1.0 - Fr) * refraction(Normal, eta));
+ else if (distribution == "Beckmann")
+ BSDF = Color * (Fr * microfacet_beckmann(Normal, Roughness) +
+ (1.0 - Fr) * microfacet_beckmann_refraction(Normal, Roughness, eta));
+ else if (distribution == "GGX")
+ BSDF = Color * (Fr * microfacet_ggx(Normal, Roughness) +
+ (1.0 - Fr) * microfacet_ggx_refraction(Normal, Roughness, eta));
}
diff --git a/intern/cycles/kernel/osl/nodes/node_glossy_bsdf.osl b/intern/cycles/kernel/shaders/node_glossy_bsdf.osl
index 3890630e8a2..03340c74af5 100644
--- a/intern/cycles/kernel/osl/nodes/node_glossy_bsdf.osl
+++ b/intern/cycles/kernel/shaders/node_glossy_bsdf.osl
@@ -26,12 +26,12 @@ shader node_glossy_bsdf(
normal Normal = N,
output closure color BSDF = diffuse(Normal))
{
- if(distribution == "Sharp")
- BSDF = Color*reflection(Normal);
- else if(distribution == "Beckmann")
- BSDF = Color*microfacet_beckmann(Normal, Roughness, 1.0);
- else if(distribution == "GGX")
- BSDF = Color*microfacet_ggx(Normal, Roughness, 1.0);
+ if (distribution == "Sharp")
+ BSDF = Color * reflection(Normal);
+ else if (distribution == "Beckmann")
+ BSDF = Color * microfacet_beckmann(Normal, Roughness);
+ else if (distribution == "GGX")
+ BSDF = Color * microfacet_ggx(Normal, Roughness);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_gradient_texture.osl b/intern/cycles/kernel/shaders/node_gradient_texture.osl
index a8dd65ae23b..ae7cfa51f59 100644
--- a/intern/cycles/kernel/osl/nodes/node_gradient_texture.osl
+++ b/intern/cycles/kernel/shaders/node_gradient_texture.osl
@@ -23,38 +23,39 @@
float gradient(point p, string type)
{
- float x, y;
+ float x, y, z;
x = p[0];
y = p[1];
+ z = p[2];
float result = 0.0;
- if(type == "Linear") {
- result = (1.0 + x)/2.0;
+ if (type == "Linear") {
+ result = x;
}
- else if(type == "Quadratic") {
- float r = max((1.0 + x)/2.0, 0.0);
- result = r*r;
+ else if (type == "Quadratic") {
+ float r = max(x, 0.0);
+ result = r * r;
}
- else if(type == "Easing") {
- float r = min(max((1.0 + x)/2.0, 0.0), 1.0);
- float t = r*r;
+ else if (type == "Easing") {
+ float r = min(max(x, 0.0), 1.0);
+ float t = r * r;
- result = (3.0*t - 2.0*t*r);
+ result = (3.0 * t - 2.0 * t * r);
}
- else if(type == "Diagonal") {
- result = (2.0 + x + y)/4.0;
+ else if (type == "Diagonal") {
+ result = (x + y) / 2.0;
}
- else if(type == "Radial") {
- result = atan2(y, x)/(2*M_PI) + 0.5;
+ else if (type == "Radial") {
+ result = atan2(y, x) / (2.0 * M_PI) + 0.5;
}
else {
- float r = max(1.0 - sqrt(x*x + y*y + p[2]*p[2]), 0.0);
+ float r = max(1.0 - sqrt(x * x + y * y + z * z), 0.0);
- if(type == "Quadratic Sphere")
- result = r*r;
- else if(type == "Spherical")
+ if (type == "Quadratic Sphere")
+ result = r * r;
+ else if (type == "Spherical")
result = r;
}
diff --git a/intern/cycles/kernel/osl/nodes/node_holdout.osl b/intern/cycles/kernel/shaders/node_holdout.osl
index aede50c7ca0..aede50c7ca0 100644
--- a/intern/cycles/kernel/osl/nodes/node_holdout.osl
+++ b/intern/cycles/kernel/shaders/node_holdout.osl
diff --git a/intern/cycles/kernel/osl/nodes/node_hsv.osl b/intern/cycles/kernel/shaders/node_hsv.osl
index 8fd7a1612e8..8fd7a1612e8 100644
--- a/intern/cycles/kernel/osl/nodes/node_hsv.osl
+++ b/intern/cycles/kernel/shaders/node_hsv.osl
diff --git a/intern/cycles/kernel/shaders/node_image_texture.osl b/intern/cycles/kernel/shaders/node_image_texture.osl
new file mode 100644
index 00000000000..6393605e6b5
--- /dev/null
+++ b/intern/cycles/kernel/shaders/node_image_texture.osl
@@ -0,0 +1,120 @@
+/*
+ * Copyright 2011, Blender Foundation.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "stdosl.h"
+#include "node_color.h"
+
+color image_texture_lookup(string filename, string color_space, float u, float v, output float Alpha)
+{
+ color rgb = (color)texture(filename, u, 1.0 - v, "wrap", "periodic", "alpha", Alpha);
+
+ if (color_space == "sRGB")
+ rgb = color_srgb_to_scene_linear(rgb);
+
+ return rgb;
+}
+
+shader node_image_texture(
+ point Vector = P,
+ string filename = "",
+ string color_space = "sRGB",
+ string projection = "Flat",
+ float projection_blend = 0.0,
+ output color Color = color(0.0, 0.0, 0.0),
+ output float Alpha = 1.0)
+{
+ if (projection == "Flat") {
+ Color = image_texture_lookup(filename, color_space, Vector[0], Vector[1], Alpha);
+ }
+ else if (projection == "Box") {
+ /* object space normal */
+ vector Nob = transform("world", "object", N);
+
+ /* project from direction vector to barycentric coordinates in triangles */
+ Nob = vector(fabs(Nob[0]), fabs(Nob[1]), fabs(Nob[2]));
+ Nob /= (Nob[0] + Nob[1] + Nob[2]);
+
+ /* basic idea is to think of this as a triangle, each corner representing
+ * one of the 3 faces of the cube. in the corners we have single textures,
+ * in between we blend between two textures, and in the middle we a blend
+ * between three textures.
+ *
+ * the Nxyz values are the barycentric coordinates in an equilateral
+ * triangle, which in case of blending, in the middle has a smaller
+ * equilateral triangle where 3 textures blend. this divides things into
+ * 7 zones, with an if () test for each zone */
+
+ vector weight = vector(0.0, 0.0, 0.0);
+ float blend = projection_blend;
+ float limit = 0.5*(1.0 + blend);
+
+ /* first test for corners with single texture */
+ if (Nob[0] > limit*(Nob[0] + Nob[1]) && Nob[0] > limit*(Nob[0] + Nob[2])) {
+ weight[0] = 1.0;
+ }
+ else if (Nob[1] > limit*(Nob[0] + Nob[1]) && Nob[1] > limit*(Nob[1] + Nob[2])) {
+ weight[1] = 1.0;
+ }
+ else if (Nob[2] > limit*(Nob[0] + Nob[2]) && Nob[2] > limit*(Nob[1] + Nob[2])) {
+ weight[2] = 1.0;
+ }
+ else if (blend > 0.0) {
+ /* in case of blending, test for mixes between two textures */
+ if (Nob[2] < (1.0 - limit)*(Nob[1] + Nob[0])) {
+ weight[0] = Nob[0] / (Nob[0] + Nob[1]);
+ weight[0] = clamp((weight[0] - 0.5 * (1.0 - blend)) / blend, 0.0, 1.0);
+ weight[1] = 1.0 - weight[0];
+ }
+ else if (Nob[0] < (1.0 - limit)*(Nob[1] + Nob[2])) {
+ weight[1] = Nob[1] / (Nob[1] + Nob[2]);
+ weight[1] = clamp((weight[1] - 0.5 * (1.0 - blend)) / blend, 0.0, 1.0);
+ weight[2] = 1.0 - weight[1];
+ }
+ else if (Nob[1] < (1.0 - limit) * (Nob[0] + Nob[2])) {
+ weight[0] = Nob[0] / (Nob[0] + Nob[2]);
+ weight[0] = clamp((weight[0] - 0.5 * (1.0 - blend)) / blend, 0.0, 1.0);
+ weight[2] = 1.0 - weight[0];
+ }
+ else {
+ /* last case, we have a mix between three */
+ weight[0] = ((2.0 - limit) * Nob[0] + (limit - 1.0)) / (2.0 * limit - 1.0);
+ weight[1] = ((2.0 - limit) * Nob[1] + (limit - 1.0)) / (2.0 * limit - 1.0);
+ weight[2] = ((2.0 - limit) * Nob[2] + (limit - 1.0)) / (2.0 * limit - 1.0);
+ }
+ }
+
+ Color = color(0.0, 0.0, 0.0);
+ Alpha = 0.0;
+
+ float tmp_alpha;
+
+ if (weight[0] > 0.0) {
+ Color += weight[0]*image_texture_lookup(filename, color_space, Vector[1], Vector[2], tmp_alpha);
+ Alpha += weight[0]*tmp_alpha;
+ }
+ if (weight[1] > 0.0) {
+ Color += weight[1]*image_texture_lookup(filename, color_space, Vector[0], Vector[2], tmp_alpha);
+ Alpha += weight[1]*tmp_alpha;
+ }
+ if (weight[2] > 0.0) {
+ Color += weight[2]*image_texture_lookup(filename, color_space, Vector[1], Vector[0], tmp_alpha);
+ Alpha += weight[2]*tmp_alpha;
+ }
+ }
+}
+
diff --git a/intern/cycles/kernel/osl/nodes/node_invert.osl b/intern/cycles/kernel/shaders/node_invert.osl
index 27021942558..27021942558 100644
--- a/intern/cycles/kernel/osl/nodes/node_invert.osl
+++ b/intern/cycles/kernel/shaders/node_invert.osl
diff --git a/intern/cycles/kernel/osl/nodes/node_blend_weight.osl b/intern/cycles/kernel/shaders/node_layer_weight.osl
index d834819ef3a..3ea57f71786 100644
--- a/intern/cycles/kernel/osl/nodes/node_blend_weight.osl
+++ b/intern/cycles/kernel/shaders/node_layer_weight.osl
@@ -19,24 +19,28 @@
#include "stdosl.h"
#include "node_fresnel.h"
-shader node_blend_weight(
- float Blend = 0.3,
+shader node_layer_weight(
+ float Blend = 0.5,
normal Normal = N,
output float Fresnel = 0.0,
output float Facing = 0.0)
{
- float f = max(1.0 - Blend, 1e-5);
- Fresnel = fresnel_dielectric(I, Normal, backfacing()? f: 1.0/f);
+ float blend = Blend;
+ /* Fresnel */
+ float eta = max(1.0 - Blend, 1e-5);
+ eta = backfacing() ? eta : 1.0 / eta;
+ Fresnel = fresnel_dielectric(I, Normal, eta);
+
+ /* Facing */
Facing = abs(dot(I, Normal));
- if(Blend != 0.5) {
- Blend = clamp(Blend, 0.0, 1.0);
- Blend = (Blend < 0.5)? 2.0*Blend: 0.5/(1.0 - Blend);
+ if (blend != 0.5) {
+ blend = clamp(blend, 0.0, 1.0 - 1e-5);
+ blend = (blend < 0.5) ? 2.0 * blend : 0.5 / (1.0 - blend);
- Facing = powf(Facing, Blend);
+ Facing = pow(Facing, blend);
}
Facing = 1.0 - Facing;
}
-
diff --git a/intern/cycles/kernel/shaders/node_light_falloff.osl b/intern/cycles/kernel/shaders/node_light_falloff.osl
new file mode 100644
index 00000000000..7ffa6fe0ffb
--- /dev/null
+++ b/intern/cycles/kernel/shaders/node_light_falloff.osl
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2012, Blender Foundation.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "stdosl.h"
+
+shader node_light_falloff(
+ float Strength = 0.0,
+ float Smooth = 0.0,
+ output float Quadratic = 0.0,
+ output float Linear = 0.0,
+ output float Constant = 0.0)
+{
+ float ray_length = 0.0;
+ float strength = Strength;
+ getattribute("path:ray_length", ray_length);
+
+ if (Smooth > 0.0) {
+ float squared = ray_length*ray_length;
+ strength *= squared / (Smooth + squared);
+ }
+
+ /* Quadratic */
+ Quadratic = strength;
+
+ /* Linear */
+ Linear = (strength*ray_length);
+
+ /* Constant */
+ Constant = (strength*ray_length*ray_length);
+}
+
diff --git a/intern/cycles/kernel/osl/nodes/node_light_path.osl b/intern/cycles/kernel/shaders/node_light_path.osl
index 0ead20bf2bb..9e3f6c7b4a9 100644
--- a/intern/cycles/kernel/osl/nodes/node_light_path.osl
+++ b/intern/cycles/kernel/shaders/node_light_path.osl
@@ -25,7 +25,8 @@ shader node_light_path(
output float IsGlossyRay = 0.0,
output float IsSingularRay = 0.0,
output float IsReflectionRay = 0.0,
- output float IsTransmissionRay = 0.0)
+ output float IsTransmissionRay = 0.0,
+ output float RayLength = 0.0)
{
IsCameraRay = raytype("camera");
IsShadowRay = raytype("shadow");
@@ -34,5 +35,7 @@ shader node_light_path(
IsSingularRay = raytype("singular");
IsReflectionRay = raytype("reflection");
IsTransmissionRay = raytype("refraction");
+
+ getattribute("path:ray_length", RayLength);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_magic_texture.osl b/intern/cycles/kernel/shaders/node_magic_texture.osl
index 0b6e980debc..e464b83bc9e 100644
--- a/intern/cycles/kernel/osl/nodes/node_magic_texture.osl
+++ b/intern/cycles/kernel/shaders/node_magic_texture.osl
@@ -21,56 +21,56 @@
/* Magic */
-color magic(point p, int n, float turbulence)
+color magic(point p, int n, float distortion)
{
- float turb = turbulence/5.0;
-
- float x = sin((p[0] + p[1] + p[2])*5.0);
- float y = cos((-p[0] + p[1] - p[2])*5.0);
- float z = -cos((-p[0] - p[1] + p[2])*5.0);
-
- if(n > 0) {
- x *= turb;
- y *= turb;
- z *= turb;
- y = -cos(x-y+z);
- y *= turb;
-
- if(n > 1) {
- x= cos(x-y-z);
- x *= turb;
-
- if(n > 2) {
- z= sin(-x-y-z);
- z *= turb;
-
- if(n > 3) {
- x= -cos(-x+y-z);
- x *= turb;
-
- if(n > 4) {
- y= -sin(-x+y+z);
- y *= turb;
-
- if(n > 5) {
- y= -cos(-x+y+z);
- y *= turb;
-
- if(n > 6) {
- x= cos(x+y+z);
- x *= turb;
-
- if(n > 7) {
- z= sin(x+y-z);
- z *= turb;
-
- if(n > 8) {
- x= -cos(-x-y+z);
- x *= turb;
-
- if(n > 9) {
- y= -sin(x-y+z);
- y *= turb;
+ float dist = distortion;
+
+ float x = sin(( p[0] + p[1] + p[2]) * 5.0);
+ float y = cos((-p[0] + p[1] - p[2]) * 5.0);
+ float z = -cos((-p[0] - p[1] + p[2]) * 5.0);
+
+ if (n > 0) {
+ x *= dist;
+ y *= dist;
+ z *= dist;
+ y = -cos(x - y + z);
+ y *= dist;
+
+ if (n > 1) {
+ x = cos(x - y - z);
+ x *= dist;
+
+ if (n > 2) {
+ z = sin(-x - y - z);
+ z *= dist;
+
+ if (n > 3) {
+ x = -cos(-x + y - z);
+ x *= dist;
+
+ if (n > 4) {
+ y = -sin(-x + y + z);
+ y *= dist;
+
+ if (n > 5) {
+ y = -cos(-x + y + z);
+ y *= dist;
+
+ if (n > 6) {
+ x = cos(x + y + z);
+ x *= dist;
+
+ if (n > 7) {
+ z = sin(x + y - z);
+ z *= dist;
+
+ if (n > 8) {
+ x = -cos(-x - y + z);
+ x *= dist;
+
+ if (n > 9) {
+ y = -sin(x - y + z);
+ y *= dist;
}
}
}
@@ -82,11 +82,11 @@ color magic(point p, int n, float turbulence)
}
}
- if(turb != 0.0) {
- turb *= 2.0;
- x /= turb;
- y /= turb;
- z /= turb;
+ if (dist != 0.0) {
+ dist *= 2.0;
+ x /= dist;
+ y /= dist;
+ z /= dist;
}
return color(0.5 - x, 0.5 - y, 0.5 - z);
@@ -94,10 +94,11 @@ color magic(point p, int n, float turbulence)
shader node_magic_texture(
int Depth = 2,
- float Turbulence = 5.0,
+ float Distortion = 5.0,
+ float Scale = 5.0,
point Vector = P,
output color Color = color(0.0, 0.0, 0.0))
{
- Color = magic(Vector, Depth, Turbulence);
+ Color = magic(Vector * Scale, Depth, Distortion);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_mapping.osl b/intern/cycles/kernel/shaders/node_mapping.osl
index f342837d3c9..2e720edfc7e 100644
--- a/intern/cycles/kernel/osl/nodes/node_mapping.osl
+++ b/intern/cycles/kernel/shaders/node_mapping.osl
@@ -20,9 +20,9 @@
shader node_mapping(
matrix Matrix = matrix(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
- point Vector = point(0.0, 0.0, 0.0),
- output point Vector_ = point(0.0, 0.0, 0.0))
+ point VectorIn = point(0.0, 0.0, 0.0),
+ output point VectorOut = point(0.0, 0.0, 0.0))
{
- Vector_ = transform(Matrix, Vector);
+ VectorOut = transform(Matrix, VectorIn);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_math.osl b/intern/cycles/kernel/shaders/node_math.osl
index 3327795286a..24dce898fd2 100644
--- a/intern/cycles/kernel/osl/nodes/node_math.osl
+++ b/intern/cycles/kernel/shaders/node_math.osl
@@ -22,20 +22,20 @@ float safe_divide(float a, float b)
{
float result;
- if(b == 0.0)
+ if (b == 0.0)
result = 0.0;
else
- result = a/b;
+ result = a / b;
return result;
}
float safe_log(float a, float b)
{
- if(a < 0.0 || b < 0.0)
+ if (a < 0.0 || b < 0.0)
return 0.0;
- return log(a)/log(b);
+ return log(a) / log(b);
}
shader node_math(
@@ -47,42 +47,42 @@ shader node_math(
{
/* OSL asin, acos, pow check for values that could give rise to nan */
- if(type == "Add")
+ if (type == "Add")
Value = Value1 + Value2;
- if(type == "Subtract")
+ if (type == "Subtract")
Value = Value1 - Value2;
- if(type == "Multiply")
- Value = Value1*Value2;
- if(type == "Divide")
+ if (type == "Multiply")
+ Value = Value1 * Value2;
+ if (type == "Divide")
Value = safe_divide(Value1, Value2);
- if(type == "Sine")
+ if (type == "Sine")
Value = sin(Value1);
- if(type == "Cosine")
+ if (type == "Cosine")
Value = cos(Value1);
- if(type == "Tangent")
+ if (type == "Tangent")
Value = tan(Value1);
- if(type == "Arcsine")
+ if (type == "Arcsine")
Value = asin(Value1);
- if(type == "Arccosine")
+ if (type == "Arccosine")
Value = acos(Value1);
- if(type == "Arctangent")
+ if (type == "Arctangent")
Value = atan(Value1);
- if(type == "Power")
+ if (type == "Power")
Value = pow(Value1, Value2);
- if(type == "Logarithm")
+ if (type == "Logarithm")
Value = safe_log(Value1, Value2);
- if(type == "Minimum")
+ if (type == "Minimum")
Value = min(Value1, Value2);
- if(type == "Maximum")
+ if (type == "Maximum")
Value = max(Value1, Value2);
- if(type == "Round")
+ if (type == "Round")
Value = floor(Value1 + 0.5);
- if(type == "Less Than")
+ if (type == "Less Than")
Value = Value1 < Value2;
- if(type == "Greater Than")
+ if (type == "Greater Than")
Value = Value1 > Value2;
- if(Clamp)
+ if (Clamp)
Value = clamp(Value1, 0.0, 1.0);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_mix.osl b/intern/cycles/kernel/shaders/node_mix.osl
index 661e543fdd8..69e68e5ed15 100644
--- a/intern/cycles/kernel/osl/nodes/node_mix.osl
+++ b/intern/cycles/kernel/shaders/node_mix.osl
@@ -38,7 +38,7 @@ color node_mix_screen(float t, color col1, color col2)
{
float tm = 1.0 - t;
- return color(1.0) - (color(tm) + t*(color(1.0) - col2))*(color(1.0) - col1);
+ return color(1.0) - (color(tm) + t * (color(1.0) - col2)) * (color(1.0) - col1);
}
color node_mix_overlay(float t, color col1, color col2)
@@ -47,20 +47,20 @@ color node_mix_overlay(float t, color col1, color col2)
color outcol = col1;
- if(outcol[0] < 0.5)
- outcol[0] *= tm + 2.0*t*col2[0];
+ if (outcol[0] < 0.5)
+ outcol[0] *= tm + 2.0 * t * col2[0];
else
- outcol[0] = 1.0 - (tm + 2.0*t*(1.0 - col2[0]))*(1.0 - outcol[0]);
+ outcol[0] = 1.0 - (tm + 2.0 * t * (1.0 - col2[0])) * (1.0 - outcol[0]);
- if(outcol[1] < 0.5)
- outcol[1] *= tm + 2.0*t*col2[1];
+ if (outcol[1] < 0.5)
+ outcol[1] *= tm + 2.0 * t * col2[1];
else
- outcol[1] = 1.0 - (tm + 2.0*t*(1.0 - col2[1]))*(1.0 - outcol[1]);
+ outcol[1] = 1.0 - (tm + 2.0 * t * (1.0 - col2[1])) * (1.0 - outcol[1]);
- if(outcol[2] < 0.5)
- outcol[2] *= tm + 2.0*t*col2[2];
+ if (outcol[2] < 0.5)
+ outcol[2] *= tm + 2.0 * t * col2[2];
else
- outcol[2] = 1.0 - (tm + 2.0*t*(1.0 - col2[2]))*(1.0 - outcol[2]);
+ outcol[2] = 1.0 - (tm + 2.0 * t * (1.0 - col2[2])) * (1.0 - outcol[2]);
return outcol;
}
@@ -76,9 +76,9 @@ color node_mix_div(float t, color col1, color col2)
color outcol = col1;
- if(col2[0] != 0.0) outcol[0] = tm*outcol[0] + t*outcol[0]/col2[0];
- if(col2[1] != 0.0) outcol[1] = tm*outcol[1] + t*outcol[1]/col2[1];
- if(col2[2] != 0.0) outcol[2] = tm*outcol[2] + t*outcol[2]/col2[2];
+ if (col2[0] != 0.0) outcol[0] = tm * outcol[0] + t * outcol[0] / col2[0];
+ if (col2[1] != 0.0) outcol[1] = tm * outcol[1] + t * outcol[1] / col2[1];
+ if (col2[2] != 0.0) outcol[2] = tm * outcol[2] + t * outcol[2] / col2[2];
return outcol;
}
@@ -90,41 +90,41 @@ color node_mix_diff(float t, color col1, color col2)
color node_mix_dark(float t, color col1, color col2)
{
- return min(col1, col2*t);
+ return min(col1, col2 * t);
}
color node_mix_light(float t, color col1, color col2)
{
- return max(col1, col2*t);
+ return max(col1, col2 * t);
}
color node_mix_dodge(float t, color col1, color col2)
{
color outcol = col1;
- if(outcol[0] != 0.0) {
- float tmp = 1.0 - t*col2[0];
- if(tmp <= 0.0)
+ if (outcol[0] != 0.0) {
+ float tmp = 1.0 - t * col2[0];
+ if (tmp <= 0.0)
outcol[0] = 1.0;
- else if((tmp = outcol[0]/tmp) > 1.0)
+ else if ((tmp = outcol[0] / tmp) > 1.0)
outcol[0] = 1.0;
else
outcol[0] = tmp;
}
- if(outcol[1] != 0.0) {
- float tmp = 1.0 - t*col2[1];
- if(tmp <= 0.0)
+ if (outcol[1] != 0.0) {
+ float tmp = 1.0 - t * col2[1];
+ if (tmp <= 0.0)
outcol[1] = 1.0;
- else if((tmp = outcol[1]/tmp) > 1.0)
+ else if ((tmp = outcol[1] / tmp) > 1.0)
outcol[1] = 1.0;
else
outcol[1] = tmp;
}
- if(outcol[2] != 0.0) {
- float tmp = 1.0 - t*col2[2];
- if(tmp <= 0.0)
+ if (outcol[2] != 0.0) {
+ float tmp = 1.0 - t * col2[2];
+ if (tmp <= 0.0)
outcol[2] = 1.0;
- else if((tmp = outcol[2]/tmp) > 1.0)
+ else if ((tmp = outcol[2] / tmp) > 1.0)
outcol[2] = 1.0;
else
outcol[2] = tmp;
@@ -139,32 +139,32 @@ color node_mix_burn(float t, color col1, color col2)
color outcol = col1;
- tmp = tm + t*col2[0];
- if(tmp <= 0.0)
+ tmp = tm + t * col2[0];
+ if (tmp <= 0.0)
outcol[0] = 0.0;
- else if((tmp = (1.0 - (1.0 - outcol[0])/tmp)) < 0.0)
+ else if ((tmp = (1.0 - (1.0 - outcol[0]) / tmp)) < 0.0)
outcol[0] = 0.0;
- else if(tmp > 1.0)
+ else if (tmp > 1.0)
outcol[0] = 1.0;
else
outcol[0] = tmp;
- tmp = tm + t*col2[1];
- if(tmp <= 0.0)
+ tmp = tm + t * col2[1];
+ if (tmp <= 0.0)
outcol[1] = 0.0;
- else if((tmp = (1.0 - (1.0 - outcol[1])/tmp)) < 0.0)
+ else if ((tmp = (1.0 - (1.0 - outcol[1]) / tmp)) < 0.0)
outcol[1] = 0.0;
- else if(tmp > 1.0)
+ else if (tmp > 1.0)
outcol[1] = 1.0;
else
outcol[1] = tmp;
- tmp = tm + t*col2[2];
- if(tmp <= 0.0)
+ tmp = tm + t * col2[2];
+ if (tmp <= 0.0)
outcol[2] = 0.0;
- else if((tmp = (1.0 - (1.0 - outcol[2])/tmp)) < 0.0)
+ else if ((tmp = (1.0 - (1.0 - outcol[2]) / tmp)) < 0.0)
outcol[2] = 0.0;
- else if(tmp > 1.0)
+ else if (tmp > 1.0)
outcol[2] = 1.0;
else
outcol[2] = tmp;
@@ -177,7 +177,7 @@ color node_mix_hue(float t, color col1, color col2)
color outcol = col1;
color hsv2 = rgb_to_hsv(col2);
- if(hsv2[1] != 0.0) {
+ if (hsv2[1] != 0.0) {
color hsv = rgb_to_hsv(outcol);
hsv[0] = hsv2[0];
color tmp = hsv_to_rgb(hsv);
@@ -196,10 +196,10 @@ color node_mix_sat(float t, color col1, color col2)
color hsv = rgb_to_hsv(outcol);
- if(hsv[1] != 0.0) {
+ if (hsv[1] != 0.0) {
color hsv2 = rgb_to_hsv(col2);
- hsv[1] = tm*hsv[1] + t*hsv2[1];
+ hsv[1] = tm * hsv[1] + t * hsv2[1];
outcol = hsv_to_rgb(hsv);
}
@@ -213,7 +213,7 @@ color node_mix_val(float t, color col1, color col2)
color hsv = rgb_to_hsv(col1);
color hsv2 = rgb_to_hsv(col2);
- hsv[2] = tm*hsv[2] + t*hsv2[2];
+ hsv[2] = tm * hsv[2] + t * hsv2[2];
return hsv_to_rgb(hsv);
}
@@ -223,7 +223,7 @@ color node_mix_color(float t, color col1, color col2)
color outcol = col1;
color hsv2 = rgb_to_hsv(col2);
- if(hsv2[1] != 0.0) {
+ if (hsv2[1] != 0.0) {
color hsv = rgb_to_hsv(outcol);
hsv[0] = hsv2[0];
hsv[1] = hsv2[1];
@@ -239,30 +239,30 @@ color node_mix_soft(float t, color col1, color col2)
{
float tm = 1.0 - t;
- color one= color(1.0);
- color scr= one - (one - col2)*(one - col1);
+ color one = color(1.0);
+ color scr = one - (one - col2) * (one - col1);
- return tm*col1 + t*((one - col1)*col2*col1 + col1*scr);
+ return tm * col1 + t * ((one - col1) * col2 * col1 + col1 * scr);
}
color node_mix_linear(float t, color col1, color col2)
{
color outcol = col1;
- if(col2[0] > 0.5)
- outcol[0]= col1[0] + t*(2.0*(col2[0] - 0.5));
+ if (col2[0] > 0.5)
+ outcol[0] = col1[0] + t * (2.0 * (col2[0] - 0.5));
else
- outcol[0]= col1[0] + t*(2.0*(col2[0]) - 1.0);
+ outcol[0] = col1[0] + t * (2.0 * (col2[0]) - 1.0);
- if(col2[1] > 0.5)
- outcol[1]= col1[1] + t*(2.0*(col2[1] - 0.5));
+ if (col2[1] > 0.5)
+ outcol[1] = col1[1] + t * (2.0 * (col2[1] - 0.5));
else
- outcol[1]= col1[1] + t*(2.0*(col2[1]) - 1.0);
+ outcol[1] = col1[1] + t * (2.0 * (col2[1]) - 1.0);
- if(col2[2] > 0.5)
- outcol[2]= col1[2] + t*(2.0*(col2[2] - 0.5));
+ if (col2[2] > 0.5)
+ outcol[2] = col1[2] + t * (2.0 * (col2[2] - 0.5));
else
- outcol[2]= col1[2] + t*(2.0*(col2[2]) - 1.0);
+ outcol[2] = col1[2] + t * (2.0 * (col2[2]) - 1.0);
return outcol;
}
@@ -288,44 +288,44 @@ shader node_mix(
{
float t = clamp(Fac, 0.0, 1.0);
- if(type == "Mix")
+ if (type == "Mix")
Color = node_mix_blend(t, Color1, Color2);
- if(type == "Add")
+ if (type == "Add")
Color = node_mix_add(t, Color1, Color2);
- if(type == "Multiply")
+ if (type == "Multiply")
Color = node_mix_mul(t, Color1, Color2);
- if(type == "Screen")
+ if (type == "Screen")
Color = node_mix_screen(t, Color1, Color2);
- if(type == "Overlay")
+ if (type == "Overlay")
Color = node_mix_overlay(t, Color1, Color2);
- if(type == "Subtract")
+ if (type == "Subtract")
Color = node_mix_sub(t, Color1, Color2);
- if(type == "Divide")
+ if (type == "Divide")
Color = node_mix_div(t, Color1, Color2);
- if(type == "Difference")
+ if (type == "Difference")
Color = node_mix_diff(t, Color1, Color2);
- if(type == "Darken")
+ if (type == "Darken")
Color = node_mix_dark(t, Color1, Color2);
- if(type == "Lighten")
+ if (type == "Lighten")
Color = node_mix_light(t, Color1, Color2);
- if(type == "Dodge")
+ if (type == "Dodge")
Color = node_mix_dodge(t, Color1, Color2);
- if(type == "Burn")
+ if (type == "Burn")
Color = node_mix_burn(t, Color1, Color2);
- if(type == "Hue")
+ if (type == "Hue")
Color = node_mix_hue(t, Color1, Color2);
- if(type == "Saturation")
+ if (type == "Saturation")
Color = node_mix_sat(t, Color1, Color2);
- if(type == "Value")
+ if (type == "Value")
Color = node_mix_val (t, Color1, Color2);
- if(type == "Color")
+ if (type == "Color")
Color = node_mix_color(t, Color1, Color2);
- if(type == "Soft Light")
+ if (type == "Soft Light")
Color = node_mix_soft(t, Color1, Color2);
- if(type == "Linear Light")
+ if (type == "Linear Light")
Color = node_mix_linear(t, Color1, Color2);
- if(Clamp)
+ if (Clamp)
Color = node_mix_clamp(Color);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_mix_closure.osl b/intern/cycles/kernel/shaders/node_mix_closure.osl
index 1a377abd381..e28dd1fc436 100644
--- a/intern/cycles/kernel/osl/nodes/node_mix_closure.osl
+++ b/intern/cycles/kernel/shaders/node_mix_closure.osl
@@ -25,6 +25,6 @@ shader node_mix_closure(
output closure color Closure = background())
{
float t = clamp(Fac, 0.0, 1.0);
- Closure = (1.0 - t)*Closure1 + t*Closure2;
+ Closure = (1.0 - t) * Closure1 + t * Closure2;
}
diff --git a/intern/cycles/kernel/osl/nodes/node_musgrave_texture.osl b/intern/cycles/kernel/shaders/node_musgrave_texture.osl
index 3e1a6862660..71461b8fd79 100644
--- a/intern/cycles/kernel/osl/nodes/node_musgrave_texture.osl
+++ b/intern/cycles/kernel/shaders/node_musgrave_texture.osl
@@ -36,15 +36,15 @@ float noise_musgrave_fBm(point p, string basis, float H, float lacunarity, float
float pwHL = pow(lacunarity, -H);
int i;
- for(i = 0; i < (int)octaves; i++) {
- value += noise_basis(p, basis) * pwr;
+ for (i = 0; i < (int)octaves; i++) {
+ value += noise("perlin", p) * pwr;
pwr *= pwHL;
p *= lacunarity;
}
rmd = octaves - floor(octaves);
- if(rmd != 0.0)
- value += rmd * noise_basis(p, basis) * pwr;
+ if (rmd != 0.0)
+ value += rmd * noise("perlin", p) * pwr;
return value;
}
@@ -64,15 +64,15 @@ float noise_musgrave_multi_fractal(point p, string basis, float H, float lacunar
float pwHL = pow(lacunarity, -H);
int i;
- for(i = 0; i < (int)octaves; i++) {
- value *= (pwr * noise_basis(p, basis) + 1.0);
+ for (i = 0; i < (int)octaves; i++) {
+ value *= (pwr * noise("perlin", p) + 1.0);
pwr *= pwHL;
p *= lacunarity;
}
rmd = octaves - floor(octaves);
- if(rmd != 0.0)
- value *= (rmd * pwr * noise_basis(p, basis) + 1.0); /* correct? */
+ if (rmd != 0.0)
+ value *= (rmd * pwr * noise("perlin", p) + 1.0); /* correct? */
return value;
}
@@ -93,19 +93,19 @@ float noise_musgrave_hetero_terrain(point p, string basis, float H, float lacuna
int i;
/* first unscaled octave of function; later octaves are scaled */
- value = offset + noise_basis(p, basis);
+ value = offset + noise("perlin", p);
p *= lacunarity;
- for(i = 1; i < (int)octaves; i++) {
- increment = (noise_basis(p, basis) + offset) * pwr * value;
+ for (i = 1; i < (int)octaves; i++) {
+ increment = (noise("perlin", p) + offset) * pwr * value;
value += increment;
pwr *= pwHL;
p *= lacunarity;
}
rmd = octaves - floor(octaves);
- if(rmd != 0.0) {
- increment = (noise_basis(p, basis) + offset) * pwr * value;
+ if (rmd != 0.0) {
+ increment = (noise("perlin", p) + offset) * pwr * value;
value += rmd * increment;
}
@@ -120,22 +120,23 @@ float noise_musgrave_hetero_terrain(point p, string basis, float H, float lacuna
* offset: raises the terrain from `sea level'
*/
-float noise_musgrave_hybrid_multi_fractal(point p, string basis, float H, float lacunarity, float octaves, float offset, float gain)
+float noise_musgrave_hybrid_multi_fractal(point p, string basis, float H,
+ float lacunarity, float octaves, float offset, float gain)
{
float result, signal, weight, rmd;
float pwHL = pow(lacunarity, -H);
float pwr = pwHL;
int i;
- result = noise_basis(p, basis) + offset;
+ result = noise("perlin", p) + offset;
weight = gain * result;
p *= lacunarity;
- for(i = 1; (weight > 0.001) && (i < (int)octaves); i++) {
- if(weight > 1.0)
+ for (i = 1; (weight > 0.001) && (i < (int)octaves); i++) {
+ if (weight > 1.0)
weight = 1.0;
- signal = (noise_basis(p, basis) + offset) * pwr;
+ signal = (noise("perlin", p) + offset) * pwr;
pwr *= pwHL;
result += weight * signal;
weight *= gain * signal;
@@ -143,8 +144,8 @@ float noise_musgrave_hybrid_multi_fractal(point p, string basis, float H, float
}
rmd = octaves - floor(octaves);
- if(rmd != 0.0)
- result += rmd * ((noise_basis(p, basis) + offset) * pwr);
+ if (rmd != 0.0)
+ result += rmd * ((noise("perlin", p) + offset) * pwr);
return result;
}
@@ -157,22 +158,23 @@ float noise_musgrave_hybrid_multi_fractal(point p, string basis, float H, float
* offset: raises the terrain from `sea level'
*/
-float noise_musgrave_ridged_multi_fractal(point p, string basis, float H, float lacunarity, float octaves, float offset, float gain)
+float noise_musgrave_ridged_multi_fractal(point p, string basis, float H,
+ float lacunarity, float octaves, float offset, float gain)
{
float result, signal, weight;
float pwHL = pow(lacunarity, -H);
float pwr = pwHL;
int i;
- signal = offset - fabs(noise_basis(p, basis));
+ signal = offset - fabs(noise("perlin", p));
signal *= signal;
result = signal;
weight = 1.0;
- for(i = 1; i < (int)octaves; i++) {
+ for (i = 1; i < (int)octaves; i++) {
p *= lacunarity;
weight = clamp(signal * gain, 0.0, 1.0);
- signal = offset - fabs(noise_basis(p, basis));
+ signal = offset - fabs(noise("perlin", p));
signal *= signal;
signal *= weight;
result += signal * pwr;
@@ -202,18 +204,18 @@ shader node_musgrave_texture(
string Basis = "Perlin";
float intensity = 1.0;
- point p = Vector*Scale;
-
- if(Type == "Multifractal")
- Fac = intensity*noise_musgrave_multi_fractal(p, Basis, dimension, lacunarity, octaves);
- else if(Type == "fBM")
- Fac = intensity*noise_musgrave_fBm(p, Basis, dimension, lacunarity, octaves);
- else if(Type == "Hybrid Multifractal")
- Fac = intensity*noise_musgrave_hybrid_multi_fractal(p, Basis, dimension, lacunarity, octaves, Offset, Gain);
- else if(Type == "Ridged Multifractal")
- Fac = intensity*noise_musgrave_ridged_multi_fractal(p, Basis, dimension, lacunarity, octaves, Offset, Gain);
- else if(Type == "Hetero Terrain")
- Fac = intensity*noise_musgrave_hetero_terrain(p, Basis, dimension, lacunarity, octaves, Offset);
+ point p = Vector * Scale;
+
+ if (Type == "Multifractal")
+ Fac = intensity * noise_musgrave_multi_fractal(p, Basis, dimension, lacunarity, octaves);
+ else if (Type == "fBM")
+ Fac = intensity * noise_musgrave_fBm(p, Basis, dimension, lacunarity, octaves);
+ else if (Type == "Hybrid Multifractal")
+ Fac = intensity * noise_musgrave_hybrid_multi_fractal(p, Basis, dimension, lacunarity, octaves, Offset, Gain);
+ else if (Type == "Ridged Multifractal")
+ Fac = intensity * noise_musgrave_ridged_multi_fractal(p, Basis, dimension, lacunarity, octaves, Offset, Gain);
+ else if (Type == "Hetero Terrain")
+ Fac = intensity * noise_musgrave_hetero_terrain(p, Basis, dimension, lacunarity, octaves, Offset);
Color = color(Fac, Fac, Fac);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_noise_texture.osl b/intern/cycles/kernel/shaders/node_noise_texture.osl
index 1ddb4d8a08b..227b2bf8cea 100644
--- a/intern/cycles/kernel/osl/nodes/node_noise_texture.osl
+++ b/intern/cycles/kernel/shaders/node_noise_texture.osl
@@ -25,8 +25,8 @@ float noise(point p, string basis, float distortion, float detail, float fac, co
{
point r;
int hard = 0;
-
- if(distortion != 0.0) {
+
+ if (distortion != 0.0) {
r[0] = noise_basis(p + point(13.5), basis) * distortion;
r[1] = noise_basis(p, basis) * distortion;
r[2] = noise_basis(p - point(13.5), basis) * distortion;
@@ -51,6 +51,6 @@ shader node_noise_texture(
output color Color = color(0.2, 0.2, 0.2))
{
string Basis = "Perlin";
- Fac = noise(Vector*Scale, Basis, Distortion, Detail, Fac, Color);
+ Fac = noise(Vector * Scale, Basis, Distortion, Detail, Fac, Color);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_normal.osl b/intern/cycles/kernel/shaders/node_normal.osl
index d5f16acb88c..d5f16acb88c 100644
--- a/intern/cycles/kernel/osl/nodes/node_normal.osl
+++ b/intern/cycles/kernel/shaders/node_normal.osl
diff --git a/intern/cycles/kernel/shaders/node_object_info.osl b/intern/cycles/kernel/shaders/node_object_info.osl
new file mode 100644
index 00000000000..c3b1ff29f09
--- /dev/null
+++ b/intern/cycles/kernel/shaders/node_object_info.osl
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2011, Blender Foundation.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "stdosl.h"
+
+shader node_object_info(
+ output point Location = point(0.0, 0.0, 0.0),
+ output float ObjectIndex = 0.0,
+ output float MaterialIndex = 0.0,
+ output float Random = 0.0)
+{
+ getattribute("object:location", Location);
+ getattribute("object:index", ObjectIndex);
+ getattribute("material:index", MaterialIndex);
+ getattribute("object:random", Random);
+}
+
diff --git a/intern/cycles/kernel/osl/nodes/node_output_displacement.osl b/intern/cycles/kernel/shaders/node_output_displacement.osl
index a6b452c532a..5649b879c5b 100644
--- a/intern/cycles/kernel/osl/nodes/node_output_displacement.osl
+++ b/intern/cycles/kernel/shaders/node_output_displacement.osl
@@ -20,6 +20,6 @@
displacement node_output_displacement(float Displacement = 0.0)
{
- P += N*Displacement*0.1; /* todo: get rid of this factor */
+ P += N * Displacement * 0.1; /* todo: get rid of this factor */
}
diff --git a/intern/cycles/kernel/osl/nodes/node_output_surface.osl b/intern/cycles/kernel/shaders/node_output_surface.osl
index 6efaf91121b..6efaf91121b 100644
--- a/intern/cycles/kernel/osl/nodes/node_output_surface.osl
+++ b/intern/cycles/kernel/shaders/node_output_surface.osl
diff --git a/intern/cycles/kernel/osl/nodes/node_output_volume.osl b/intern/cycles/kernel/shaders/node_output_volume.osl
index 18094242dc7..18094242dc7 100644
--- a/intern/cycles/kernel/osl/nodes/node_output_volume.osl
+++ b/intern/cycles/kernel/shaders/node_output_volume.osl
diff --git a/intern/cycles/kernel/osl/nodes/node_particle_info.osl b/intern/cycles/kernel/shaders/node_particle_info.osl
index aadc2812865..5e59ad1a990 100644
--- a/intern/cycles/kernel/osl/nodes/node_particle_info.osl
+++ b/intern/cycles/kernel/shaders/node_particle_info.osl
@@ -25,15 +25,14 @@ shader node_particle_info(
output point Location = point(0.0, 0.0, 0.0),
output float Size = 0.0,
output vector Velocity = point(0.0, 0.0, 0.0),
- output vector AngularVelocity = point(0.0, 0.0, 0.0)
- )
+ output vector AngularVelocity = point(0.0, 0.0, 0.0))
{
- getattribute("std::particle_index", Index);
- getattribute("std::particle_age", Age);
- getattribute("std::particle_lifetime", Lifetime);
- getattribute("std::particle_location", Location);
- getattribute("std::particle_size", Size);
- getattribute("std::particle_velocity", Velocity);
- getattribute("std::particle_angular_velocity", AngularVelocity);
+ getattribute("particle:index", Index);
+ getattribute("particle:age", Age);
+ getattribute("particle:lifetime", Lifetime);
+ getattribute("particle:location", Location);
+ getattribute("particle:size", Size);
+ getattribute("particle:velocity", Velocity);
+ getattribute("particle:angular_velocity", AngularVelocity);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_image_texture.osl b/intern/cycles/kernel/shaders/node_rgb_ramp.osl
index 38126401d76..a128ebbd1cf 100644
--- a/intern/cycles/kernel/osl/nodes/node_image_texture.osl
+++ b/intern/cycles/kernel/shaders/node_rgb_ramp.osl
@@ -17,18 +17,27 @@
*/
#include "stdosl.h"
-#include "node_color.h"
+#include "oslutil.h"
-shader node_image_texture(
- point Vector = P,
- string filename = "",
- string color_space = "sRGB",
+shader node_rgb_ramp(
+ color ramp_color[RAMP_TABLE_SIZE] = {0.0},
+ float ramp_alpha[RAMP_TABLE_SIZE] = {0.0},
+
+ float Fac = 0.0,
output color Color = color(0.0, 0.0, 0.0),
output float Alpha = 1.0)
{
- Color = (color)texture(filename, Vector[0], 1.0-Vector[1], "wrap", "periodic", "alpha", Alpha);
+ float f = clamp(Fac, 0.0, 1.0) * (RAMP_TABLE_SIZE - 1);
+
+ int i = (int)f;
+ float t = f - (float)i;
+
+ Color = ramp_color[i];
+ Alpha = ramp_alpha[i];
- if(color_space == "sRGB")
- Color = color_srgb_to_scene_linear(Color);
+ if (t > 0.0) {
+ Color = (1.0 - t) * Color + t * ramp_color[i + 1];
+ Alpha = (1.0 - t) * Alpha + t * ramp_alpha[i + 1];
+ }
}
diff --git a/intern/cycles/kernel/osl/nodes/node_separate_rgb.osl b/intern/cycles/kernel/shaders/node_separate_rgb.osl
index b48bd7e59d6..b48bd7e59d6 100644
--- a/intern/cycles/kernel/osl/nodes/node_separate_rgb.osl
+++ b/intern/cycles/kernel/shaders/node_separate_rgb.osl
diff --git a/intern/cycles/kernel/shaders/node_set_normal.osl b/intern/cycles/kernel/shaders/node_set_normal.osl
new file mode 100644
index 00000000000..27a4b2f5b8b
--- /dev/null
+++ b/intern/cycles/kernel/shaders/node_set_normal.osl
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2012, Blender Foundation.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "stdosl.h"
+
+surface node_set_normal(
+ normal Direction = N,
+ output normal Normal = N)
+{
+ N = Direction;
+ Normal = Direction;
+}
+
diff --git a/intern/cycles/kernel/osl/nodes/node_sky_texture.osl b/intern/cycles/kernel/shaders/node_sky_texture.osl
index fdb9b1d9708..932fb1e2f17 100644
--- a/intern/cycles/kernel/osl/nodes/node_sky_texture.osl
+++ b/intern/cycles/kernel/shaders/node_sky_texture.osl
@@ -32,10 +32,10 @@ color xyY_to_xyz(float x, float y, float Y)
{
float X, Z;
- if(y != 0.0) X = (x / y) * Y;
+ if (y != 0.0) X = (x / y) * Y;
else X = 0.0;
- if(y != 0.0 && Y != 0.0) Z = ((1.0 - x - y) / y) * Y;
+ if (y != 0.0 && Y != 0.0) Z = ((1.0 - x - y) / y) * Y;
else Z = 0.0;
return color(X, Y, Z);
@@ -50,11 +50,11 @@ color xyz_to_rgb(float x, float y, float z)
float sky_angle_between(float thetav, float phiv, float theta, float phi)
{
- float cospsi = sin(thetav)*sin(theta)*cos(phi - phiv) + cos(thetav)*cos(theta);
+ float cospsi = sin(thetav) * sin(theta) * cos(phi - phiv) + cos(thetav) * cos(theta);
- if(cospsi > 1.0)
+ if (cospsi > 1.0)
return 0.0;
- if(cospsi < -1.0)
+ if (cospsi < -1.0)
return M_PI;
return acos(cospsi);
@@ -70,7 +70,7 @@ float sky_perez_function(float lam[5], float theta, float gamma)
float ctheta = cos(theta);
float cgamma = cos(gamma);
- return (1.0 + lam[0]*exp(lam[1] / ctheta)) * (1.0 + lam[2]*exp(lam[3]*gamma) + lam[4]*cgamma*cgamma);
+ return (1.0 + lam[0] * exp(lam[1] / ctheta)) * (1.0 + lam[2] * exp(lam[3] * gamma) + lam[4] * cgamma * cgamma);
}
color sky_xyz_radiance(KernelSunSky sunsky, vector dir)
@@ -106,42 +106,42 @@ void precompute_sunsky(vector dir, float turbidity, output KernelSunSky sunsky)
sunsky.phi = phi;
sunsky.dir = dir;
- float theta2 = theta*theta;
- float theta3 = theta*theta*theta;
+ float theta2 = theta * theta;
+ float theta3 = theta * theta * theta;
float T = turbidity;
- float T2 = T*T;
+ float T2 = T * T;
- float chi = (4.0/ 9.0- T / 120.0) * (M_PI - 2.0* theta);
- sunsky.zenith_Y = (4.0453*T - 4.9710) * tan(chi) - 0.2155*T + 2.4192;
+ float chi = (4.0 / 9.0 - T / 120.0) * (M_PI - 2.0 * theta);
+ sunsky.zenith_Y = (4.0453 * T - 4.9710) * tan(chi) - 0.2155 * T + 2.4192;
sunsky.zenith_Y *= 0.06;
sunsky.zenith_x =
- (0.00166* theta3 - 0.00375* theta2 + 0.00209* theta)*T2 +
- (-0.02903* theta3 + 0.06377* theta2 - 0.03202* theta + 0.00394)*T +
- (0.11693* theta3 - 0.21196* theta2 + 0.06052* theta + 0.25886);
+ ( 0.00166 * theta3 - 0.00375 * theta2 + 0.00209 * theta) * T2 +
+ (-0.02903 * theta3 + 0.06377 * theta2 - 0.03202 * theta + 0.00394) * T +
+ ( 0.11693 * theta3 - 0.21196 * theta2 + 0.06052 * theta + 0.25886);
sunsky.zenith_y =
- (0.00275* theta3 - 0.00610* theta2 + 0.00317* theta)*T2 +
- (-0.04214* theta3 + 0.08970* theta2 - 0.04153* theta + 0.00516)*T +
- (0.15346* theta3 - 0.26756* theta2 + 0.06670* theta + 0.26688);
-
- sunsky.perez_Y[0] = (0.1787*T - 1.4630);
- sunsky.perez_Y[1] = (-0.3554*T + 0.4275);
- sunsky.perez_Y[2] = (-0.0227*T + 5.3251);
- sunsky.perez_Y[3] = (0.1206*T - 2.5771);
- sunsky.perez_Y[4] = (-0.0670*T + 0.3703);
-
- sunsky.perez_x[0] = (-0.0193*T - 0.2592);
- sunsky.perez_x[1] = (-0.0665*T + 0.0008);
- sunsky.perez_x[2] = (-0.0004*T + 0.2125);
- sunsky.perez_x[3] = (-0.0641*T - 0.8989);
- sunsky.perez_x[4] = (-0.0033*T + 0.0452);
-
- sunsky.perez_y[0] = (-0.0167*T - 0.2608);
- sunsky.perez_y[1] = (-0.0950*T + 0.0092);
- sunsky.perez_y[2] = (-0.0079*T + 0.2102);
- sunsky.perez_y[3] = (-0.0441*T - 1.6537);
- sunsky.perez_y[4] = (-0.0109*T + 0.0529);
+ ( 0.00275 * theta3 - 0.00610 * theta2 + 0.00317 * theta) * T2 +
+ (-0.04214 * theta3 + 0.08970 * theta2 - 0.04153 * theta + 0.00516) * T +
+ ( 0.15346 * theta3 - 0.26756 * theta2 + 0.06670 * theta + 0.26688);
+
+ sunsky.perez_Y[0] = ( 0.1787 * T - 1.4630);
+ sunsky.perez_Y[1] = (-0.3554 * T + 0.4275);
+ sunsky.perez_Y[2] = (-0.0227 * T + 5.3251);
+ sunsky.perez_Y[3] = ( 0.1206 * T - 2.5771);
+ sunsky.perez_Y[4] = (-0.0670 * T + 0.3703);
+
+ sunsky.perez_x[0] = (-0.0193 * T - 0.2592);
+ sunsky.perez_x[1] = (-0.0665 * T + 0.0008);
+ sunsky.perez_x[2] = (-0.0004 * T + 0.2125);
+ sunsky.perez_x[3] = (-0.0641 * T - 0.8989);
+ sunsky.perez_x[4] = (-0.0033 * T + 0.0452);
+
+ sunsky.perez_y[0] = (-0.0167 * T - 0.2608);
+ sunsky.perez_y[1] = (-0.0950 * T + 0.0092);
+ sunsky.perez_y[2] = (-0.0079 * T + 0.2102);
+ sunsky.perez_y[3] = (-0.0441 * T - 1.6537);
+ sunsky.perez_y[4] = (-0.0109 * T + 0.0529);
sunsky.zenith_Y /= sky_perez_function(sunsky.perez_Y, 0, theta);
sunsky.zenith_x /= sky_perez_function(sunsky.perez_x, 0, theta);
diff --git a/intern/cycles/kernel/osl/nodes/node_texture.h b/intern/cycles/kernel/shaders/node_texture.h
index b00bf6ab31f..1b3ba8207ab 100644
--- a/intern/cycles/kernel/osl/nodes/node_texture.h
+++ b/intern/cycles/kernel/shaders/node_texture.h
@@ -156,7 +156,7 @@ float noise_basis(point p, string basis)
float result = 0.0;
if (basis == "Perlin")
- result = noise(p);
+ result = noise(p); /* returns perlin noise in range 0..1 */
if (basis == "Voronoi F1")
result = voronoi_F1S(p);
if (basis == "Voronoi F2")
@@ -235,21 +235,21 @@ float noise_turbulence(point p, string basis, float details, int hard)
float rmd = octaves - floor(octaves);
- if(rmd != 0.0) {
- float t = noise_basis(fscale*p, basis);
+ if (rmd != 0.0) {
+ float t = noise_basis(fscale * p, basis);
- if(hard)
- t = fabs(2.0*t - 1.0);
+ if (hard)
+ t = fabs(2.0 * t - 1.0);
float sum2 = sum + t*amp;
- sum *= ((float)(1 << n)/(float)((1 << (n+1)) - 1));
- sum2 *= ((float)(1 << (n+1))/(float)((1 << (n+2)) - 1));
+ sum *= ((float)(1 << n) / (float)((1 << (n + 1)) - 1));
+ sum2 *= ((float)(1 << (n + 1)) / (float)((1 << (n + 2)) - 1));
return (1.0 - rmd)*sum + rmd*sum2;
}
else {
- sum *= ((float)(1 << n)/(float)((1 << (n+1)) - 1));
+ sum *= ((float)(1 << n) / (float)((1 << (n + 1)) - 1));
return sum;
}
}
diff --git a/intern/cycles/kernel/osl/nodes/node_texture_coordinate.osl b/intern/cycles/kernel/shaders/node_texture_coordinate.osl
index 2acf72aef54..791838dfffe 100644
--- a/intern/cycles/kernel/osl/nodes/node_texture_coordinate.osl
+++ b/intern/cycles/kernel/shaders/node_texture_coordinate.osl
@@ -19,8 +19,9 @@
#include "stdosl.h"
shader node_texture_coordinate(
- normal Normal = N,
+ normal NormalIn = N,
int is_background = 0,
+ int from_dupli = 0,
string bump_offset = "center",
output point Generated = point(0.0, 0.0, 0.0),
@@ -28,36 +29,50 @@ shader node_texture_coordinate(
output point Object = point(0.0, 0.0, 0.0),
output point Camera = point(0.0, 0.0, 0.0),
output point Window = point(0.0, 0.0, 0.0),
+ output normal Normal = normal(0.0, 0.0, 0.0),
output point Reflection = point(0.0, 0.0, 0.0))
{
- if(is_background) {
+ if (is_background) {
Generated = P;
UV = point(0.0, 0.0, 0.0);
Object = P;
point Pcam = transform("camera", "world", point(0, 0, 0));
Camera = transform("camera", P + Pcam);
Window = transform("NDC", P + Pcam);
+ Normal = NormalIn;
Reflection = I;
}
else {
- getattribute("std::generated", Generated);
- getattribute("std::uv", UV);
+ if (from_dupli) {
+ getattribute("geom:dupli_generated", Generated);
+ getattribute("geom:dupli_uv", UV);
+ }
+ else {
+ getattribute("geom:generated", Generated);
+ getattribute("geom:uv", UV);
+ }
+
Object = transform("object", P);
Camera = transform("camera", P);
Window = transform("NDC", P);
- Reflection = reflect(I, Normal);
+ Normal = transform("world", "object", NormalIn);
+ Reflection = reflect(I, NormalIn);
}
- if(bump_offset == "dx") {
- Generated += Dx(Generated);
- UV += Dx(UV);
+ if (bump_offset == "dx") {
+ if (!from_dupli) {
+ Generated += Dx(Generated);
+ UV += Dx(UV);
+ }
Object += Dx(Object);
Camera += Dx(Camera);
Window += Dx(Window);
}
- else if(bump_offset == "dy") {
- Generated += Dy(Generated);
- UV += Dy(UV);
+ else if (bump_offset == "dy") {
+ if (!from_dupli) {
+ Generated += Dy(Generated);
+ UV += Dy(UV);
+ }
Object += Dy(Object);
Camera += Dy(Camera);
Window += Dy(Window);
diff --git a/intern/cycles/kernel/osl/nodes/node_translucent_bsdf.osl b/intern/cycles/kernel/shaders/node_translucent_bsdf.osl
index 9acd46756d2..e7efe73700c 100644
--- a/intern/cycles/kernel/osl/nodes/node_translucent_bsdf.osl
+++ b/intern/cycles/kernel/shaders/node_translucent_bsdf.osl
@@ -23,6 +23,6 @@ shader node_translucent_bsdf(
normal Normal = N,
output closure color BSDF = diffuse(Normal))
{
- BSDF = Color*translucent(Normal);
+ BSDF = Color * translucent(Normal);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_transparent_bsdf.osl b/intern/cycles/kernel/shaders/node_transparent_bsdf.osl
index b347bfb116b..875bce3f16c 100644
--- a/intern/cycles/kernel/osl/nodes/node_transparent_bsdf.osl
+++ b/intern/cycles/kernel/shaders/node_transparent_bsdf.osl
@@ -23,6 +23,6 @@ shader node_transparent_bsdf(
normal Normal = N,
output closure color BSDF = diffuse(Normal))
{
- BSDF = Color*transparent();
+ BSDF = Color * transparent();
}
diff --git a/intern/cycles/kernel/osl/nodes/node_value.osl b/intern/cycles/kernel/shaders/node_value.osl
index bee6f39f2bc..bee6f39f2bc 100644
--- a/intern/cycles/kernel/osl/nodes/node_value.osl
+++ b/intern/cycles/kernel/shaders/node_value.osl
diff --git a/intern/cycles/kernel/osl/nodes/node_vector_math.osl b/intern/cycles/kernel/shaders/node_vector_math.osl
index 9e0f0b60522..f22a6e8441a 100644
--- a/intern/cycles/kernel/osl/nodes/node_vector_math.osl
+++ b/intern/cycles/kernel/shaders/node_vector_math.osl
@@ -25,27 +25,27 @@ shader node_vector_math(
output float Value = 0.0,
output vector Vector = vector(0.0, 0.0, 0.0))
{
- if(type == "Add") {
+ if (type == "Add") {
Vector = Vector1 + Vector2;
- Value = (abs(Vector[0]) + abs(Vector[1]) + abs(Vector[2]))/3.0;
+ Value = (abs(Vector[0]) + abs(Vector[1]) + abs(Vector[2])) / 3.0;
}
- if(type == "Subtract") {
+ if (type == "Subtract") {
Vector = Vector1 - Vector2;
- Value = (abs(Vector[0]) + abs(Vector[1]) + abs(Vector[2]))/3.0;
+ Value = (abs(Vector[0]) + abs(Vector[1]) + abs(Vector[2])) / 3.0;
}
- if(type == "Average") {
+ if (type == "Average") {
Value = length(Vector1 + Vector2);
Vector = normalize(Vector1 + Vector2);
}
- if(type == "Dot Product") {
+ if (type == "Dot Product") {
Value = dot(Vector1, Vector2);
}
- if(type == "Cross Product") {
+ if (type == "Cross Product") {
vector c = cross(Vector1, Vector2);
Value = length(c);
Vector = normalize(c);
}
- if(type == "Normalize") {
+ if (type == "Normalize") {
Value = length(Vector1);
Vector = normalize(Vector1);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_velvet_bsdf.osl b/intern/cycles/kernel/shaders/node_velvet_bsdf.osl
index 5e0cae8cbd1..3aa662bdd08 100644
--- a/intern/cycles/kernel/osl/nodes/node_velvet_bsdf.osl
+++ b/intern/cycles/kernel/shaders/node_velvet_bsdf.osl
@@ -27,6 +27,6 @@ shader node_velvet_bsdf(
{
float sigma = clamp(Sigma, 0.0, 1.0);
- BSDF = Color*ashikhmin_velvet(Normal, sigma, 1.0);
+ BSDF = Color * ashikhmin_velvet(Normal, sigma);
}
diff --git a/intern/cycles/kernel/shaders/node_voronoi_texture.osl b/intern/cycles/kernel/shaders/node_voronoi_texture.osl
new file mode 100644
index 00000000000..a44df00a267
--- /dev/null
+++ b/intern/cycles/kernel/shaders/node_voronoi_texture.osl
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2011, Blender Foundation.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "stdosl.h"
+#include "node_texture.h"
+
+/* Voronoi */
+
+shader node_voronoi_texture(
+ string Coloring = "Intensity",
+ float Scale = 5.0,
+ point Vector = P,
+ output float Fac = 0.0,
+ output color Color = color(0.0, 0.0, 0.0))
+{
+ /* compute distance and point coordinate of 4 nearest neighbours */
+ float da[4];
+ point pa[4];
+
+ voronoi(Vector * Scale, "Distance Squared", 1.0, da, pa);
+
+ /* Colored output */
+ if (Coloring == "Intensity") {
+ Fac = fabs(da[0]);
+ Color = color(Fac);
+ }
+ else {
+ Color = cellnoise_color(pa[0]);
+ Fac = (Color[0] + Color[1] + Color[2]) * (1.0 / 3.0);
+
+ }
+}
+
diff --git a/intern/cycles/kernel/osl/nodes/node_ward_bsdf.osl b/intern/cycles/kernel/shaders/node_ward_bsdf.osl
index 68db07109ed..03a0477038e 100644
--- a/intern/cycles/kernel/osl/nodes/node_ward_bsdf.osl
+++ b/intern/cycles/kernel/shaders/node_ward_bsdf.osl
@@ -20,11 +20,32 @@
shader node_ward_bsdf(
color Color = color(0.8, 0.8, 0.8),
- float RoughnessU = 0.0,
- float RoughnessV = 0.0,
+ float Roughness = 0.0,
+ float Anisotropy = 0.0,
+ float Rotation = 0.0,
normal Normal = N,
+ normal Tangent = normalize(dPdu),
output closure color BSDF = diffuse(Normal))
{
- BSDF = Color*ward(Normal, normalize(dPdu), RoughnessU, RoughnessV);
+ /* rotate tangent around normal */
+ vector T = Tangent;
+
+ if(Rotation != 0.0)
+ T = rotate(T, Rotation*2.0*M_PI, point(0.0, 0.0, 0.0), Normal);
+
+ /* compute roughness */
+ float RoughnessU, RoughnessV;
+ float aniso = clamp(Anisotropy, -0.99, 0.99);
+
+ if(aniso < 0.0) {
+ RoughnessU = Roughness*(1.0 + aniso);
+ RoughnessV = Roughness/(1.0 + aniso);
+ }
+ else {
+ RoughnessU = Roughness/(1.0 - aniso);
+ RoughnessV = Roughness*(1.0 - aniso);
+ }
+
+ BSDF = Color * ward(Normal, T, RoughnessU, RoughnessV);
}
diff --git a/intern/cycles/kernel/osl/nodes/node_wave_texture.osl b/intern/cycles/kernel/shaders/node_wave_texture.osl
index db53faaf94b..79b8a8885d1 100644
--- a/intern/cycles/kernel/osl/nodes/node_wave_texture.osl
+++ b/intern/cycles/kernel/shaders/node_wave_texture.osl
@@ -30,15 +30,15 @@ float wave(point p, float scale, string type, float detail, float distortion, fl
float result = 0.0;
float n = 0.0;
- if(type == "Bands") {
- n = (x + y + z)*10.0;
+ if (type == "Bands") {
+ n = (x + y + z) * 10.0;
}
- else if(type == "Rings") {
- n = (sqrt(x*x + y*y + z*z)*20.0);
+ else if (type == "Rings") {
+ n = (sqrt(x * x + y * y + z * z) * 20.0);
}
-
- if(distortion != 0.0) {
- n = n +(distortion * noise_turbulence(p*dscale, "Perlin", detail, 0));
+
+ if (distortion != 0.0) {
+ n = n + (distortion * noise_turbulence(p * dscale, "Perlin", detail, 0));
}
result = noise_wave("Sine", n);
diff --git a/intern/cycles/kernel/osl/nodes/oslutil.h b/intern/cycles/kernel/shaders/oslutil.h
index 08611187a3c..6c91684d9a6 100644
--- a/intern/cycles/kernel/osl/nodes/oslutil.h
+++ b/intern/cycles/kernel/shaders/oslutil.h
@@ -29,6 +29,9 @@
#ifndef CCL_OSLUTIL_H
#define CCL_OSLUTIL_H
+/* NB: must match the value in kernel_types.h */
+#define RAMP_TABLE_SIZE 256
+
// Return wireframe opacity factor [0, 1] given a geometry type in
// ("triangles", "polygons" or "patches"), and a line_width in raster
// or world space depending on the last (raster) boolean argument.
diff --git a/intern/cycles/kernel/osl/nodes/stdosl.h b/intern/cycles/kernel/shaders/stdosl.h
index e5accf4eb54..4237291c7a4 100644
--- a/intern/cycles/kernel/osl/nodes/stdosl.h
+++ b/intern/cycles/kernel/shaders/stdosl.h
@@ -434,81 +434,18 @@ string concat (string a, string b, string c, string d, string e, string f) {
closure color diffuse(normal N) BUILTIN;
closure color oren_nayar(normal N, float sigma) BUILTIN;
closure color translucent(normal N) BUILTIN;
-closure color reflection(normal N, float eta) BUILTIN;
-closure color reflection(normal N) { return reflection (N, 0.0); }
+closure color reflection(normal N) BUILTIN;
closure color refraction(normal N, float eta) BUILTIN;
-closure color dielectric(normal N, float eta) BUILTIN;
closure color transparent() BUILTIN;
-closure color microfacet_ggx(normal N, float ag, float eta) BUILTIN;
+closure color microfacet_ggx(normal N, float ag) BUILTIN;
closure color microfacet_ggx_refraction(normal N, float ag, float eta) BUILTIN;
-closure color microfacet_beckmann(normal N, float ab, float eta) BUILTIN;
+closure color microfacet_beckmann(normal N, float ab) BUILTIN;
closure color microfacet_beckmann_refraction(normal N, float ab, float eta) BUILTIN;
closure color ward(normal N, vector T,float ax, float ay) BUILTIN;
-closure color phong(normal N, float exponent) BUILTIN;
-closure color phong_ramp(normal N, float exponent, color colors[8]) BUILTIN;
-closure color hair_diffuse(vector T) BUILTIN;
-closure color hair_specular(vector T, float offset, float exponent) BUILTIN;
-closure color ashikhmin_velvet(normal N, float sigma, float eta) BUILTIN;
-closure color westin_backscatter(normal N, float roughness) BUILTIN;
-closure color westin_sheen(normal N, float edginess) BUILTIN;
-closure color bssrdf_cubic(color radius) BUILTIN;
-closure color emission(float inner_angle, float outer_angle) BUILTIN;
-closure color emission(float outer_angle) BUILTIN;
+closure color ashikhmin_velvet(normal N, float sigma) BUILTIN;
closure color emission() BUILTIN;
-closure color debug(string tag) BUILTIN;
closure color background() BUILTIN;
closure color holdout() BUILTIN;
-closure color subsurface(float eta, float g, color mfp, color albedo) BUILTIN;
-
-closure color cloth(normal N, float s, float t, float dsdx, float dtdx, float dsdy, float dtdy,
- float area_scaled, vector dPdu, color diff_warp_col, color diff_weft_col,
- color spec_warp_col, color spec_weft_col, float fresnel_warp, float fresnel_weft,
- float spread_x_mult, float spread_y_mult, int pattern, float pattern_angle,
- float warp_width_scale, float weft_width_scale, float thread_count_mult_u,
- float thread_count_mult_v) BUILTIN;
-closure color cloth_specular(normal N, color spec_col[4], float eta[4], int thread_pattern[4],
- float pattern_weight[4], int current_thread, float brdf_interp,
- float btf_interp, float uux, float vvx, float area_scaled, vector dPdu,
- float eccentricity[4], float angle[4], float Kx[4], float Ky[4],
- float Sx[4], float Sy[4]) BUILTIN;
-closure color fakefur_diffuse(normal N, vector T, float fur_reflectivity, float fur_transmission,
- float shadow_start, float shadow_end, float fur_attenuation, float fur_density,
- float fur_avg_radius, float fur_length, float fur_shadow_fraction) BUILTIN;
-closure color fakefur_specular(normal N, vector T, float offset, float exp, float fur_reflectivity,
- float fur_transmission, float shadow_start, float shadow_end,
- float fur_attenuation, float fur_density, float fur_avg_radius,
- float fur_length, float fur_shadow_fraction) BUILTIN;
-
-closure color fakefur_skin(vector N, vector T, float fur_reflectivity, float fur_transmission,
- float shadow_start, float shadow_end, float fur_attenuation, float fur_density,
- float fur_avg_radius, float fur_length) BUILTIN;
-
-
-closure color cloth(normal N, float s, float t, color diff_warp, color diff_weft,
- color spec_warp, color spec_weft, float fresnel_warp, float fresnel_weft,
- float spread_x_mult, float spread_y_mult, int pattern, float pattern_angle,
- float warp_width_scale, float weft_width_scale, float thread_count_mult_u,
- float thread_count_mult_v)
-{
-
- return cloth(N, s, t, Dx(s), Dx(t), Dy(s), Dy(t), area(P), dPdu, diff_warp, diff_weft, spec_warp, spec_weft,
- fresnel_warp, fresnel_weft, spread_x_mult, spread_y_mult, pattern, pattern_angle,
- warp_width_scale, weft_width_scale, thread_count_mult_u, thread_count_mult_v);
-}
-
-closure color cloth(normal N, float s, float t, color diff_warp, color diff_weft,
- color spec_warp, color spec_weft, float fresnel_warp, float fresnel_weft,
- float spread_x_mult, float spread_y_mult, int pattern, float pattern_angle,
- float warp_width_scale, float weft_width_scale, float thread_count_mult_u,
- float thread_count_mult_v, string tok, string val)
-{
-
- return cloth(N, s, t, Dx(s), Dx(t), Dy(s), Dy(t), area(P), dPdu, diff_warp, diff_weft, spec_warp, spec_weft,
- fresnel_warp, fresnel_weft, spread_x_mult, spread_y_mult, pattern, pattern_angle,
- warp_width_scale, weft_width_scale, thread_count_mult_u, thread_count_mult_v, tok, val);
-}
-
-
// Renderer state
int raytype (string typename) BUILTIN;
diff --git a/intern/cycles/kernel/svm/svm.h b/intern/cycles/kernel/svm/svm.h
index 5b0f192ea47..698ef5016f0 100644
--- a/intern/cycles/kernel/svm/svm.h
+++ b/intern/cycles/kernel/svm/svm.h
@@ -82,6 +82,25 @@ __device_inline void stack_store_float(float *stack, uint a, float f)
stack[a] = f;
}
+__device_inline int stack_load_int(float *stack, uint a)
+{
+ kernel_assert(a < SVM_STACK_SIZE);
+
+ return __float_as_int(stack[a]);
+}
+
+__device_inline float stack_load_int_default(float *stack, uint a, uint value)
+{
+ return (a == (uint)SVM_STACK_INVALID)? (int)value: stack_load_int(stack, a);
+}
+
+__device_inline void stack_store_int(float *stack, uint a, int i)
+{
+ kernel_assert(a < SVM_STACK_SIZE);
+
+ stack[a] = __int_as_float(i);
+}
+
__device_inline bool stack_valid(uint a)
{
return a != (uint)SVM_STACK_INVALID;
@@ -185,7 +204,7 @@ __device_noinline void svm_eval_nodes(KernelGlobals *kg, ShaderData *sd, ShaderT
break;
}
case NODE_CLOSURE_BSDF:
- svm_node_closure_bsdf(kg, sd, stack, node, randb, path_flag);
+ svm_node_closure_bsdf(kg, sd, stack, node, randb, path_flag, &offset);
break;
case NODE_CLOSURE_EMISSION:
svm_node_closure_emission(sd, stack, node);
@@ -261,14 +280,14 @@ __device_noinline void svm_eval_nodes(KernelGlobals *kg, ShaderData *sd, ShaderT
svm_node_camera(kg, sd, stack, node.y, node.z, node.w);
break;
case NODE_GEOMETRY:
- svm_node_geometry(sd, stack, node.y, node.z);
+ svm_node_geometry(kg, sd, stack, node.y, node.z);
break;
#ifdef __EXTRA_NODES__
case NODE_GEOMETRY_BUMP_DX:
- svm_node_geometry_bump_dx(sd, stack, node.y, node.z);
+ svm_node_geometry_bump_dx(kg, sd, stack, node.y, node.z);
break;
case NODE_GEOMETRY_BUMP_DY:
- svm_node_geometry_bump_dy(sd, stack, node.y, node.z);
+ svm_node_geometry_bump_dy(kg, sd, stack, node.y, node.z);
break;
case NODE_LIGHT_PATH:
svm_node_light_path(sd, stack, node.y, node.z, path_flag);
@@ -334,7 +353,7 @@ __device_noinline void svm_eval_nodes(KernelGlobals *kg, ShaderData *sd, ShaderT
svm_node_set_displacement(sd, stack, node.y);
break;
case NODE_SET_BUMP:
- svm_node_set_bump(sd, stack, node.y, node.z, node.w);
+ svm_node_set_bump(kg, sd, stack, node);
break;
case NODE_MATH:
svm_node_math(kg, sd, stack, node.y, node.z, node.w, &offset);
@@ -362,6 +381,9 @@ __device_noinline void svm_eval_nodes(KernelGlobals *kg, ShaderData *sd, ShaderT
case NODE_TEX_COORD_BUMP_DY:
svm_node_tex_coord_bump_dy(kg, sd, stack, node.y, node.z);
break;
+ case NODE_CLOSURE_SET_NORMAL:
+ svm_node_set_normal(kg, sd, stack, node.y, node.z );
+ break;
#endif
case NODE_EMISSION_SET_WEIGHT_TOTAL:
svm_node_emission_set_weight_total(kg, sd, node.y, node.z, node.w);
@@ -376,7 +398,7 @@ __device_noinline void svm_eval_nodes(KernelGlobals *kg, ShaderData *sd, ShaderT
case NODE_LIGHT_FALLOFF:
svm_node_light_falloff(sd, stack, node);
break;
-#endif
+#endif
case NODE_END:
default:
#ifndef __MULTI_CLOSURE__
diff --git a/intern/cycles/kernel/svm/svm_bsdf.h b/intern/cycles/kernel/svm/svm_bsdf.h
index 411916f8aa0..07c20231d54 100644
--- a/intern/cycles/kernel/svm/svm_bsdf.h
+++ b/intern/cycles/kernel/svm/svm_bsdf.h
@@ -16,17 +16,17 @@
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
-#include "bsdf_ashikhmin_velvet.h"
-#include "bsdf_diffuse.h"
-#include "bsdf_oren_nayar.h"
-#include "bsdf_microfacet.h"
-#include "bsdf_reflection.h"
-#include "bsdf_refraction.h"
-#include "bsdf_transparent.h"
+#include "../closure/bsdf_ashikhmin_velvet.h"
+#include "../closure/bsdf_diffuse.h"
+#include "../closure/bsdf_oren_nayar.h"
+#include "../closure/bsdf_microfacet.h"
+#include "../closure/bsdf_reflection.h"
+#include "../closure/bsdf_refraction.h"
+#include "../closure/bsdf_transparent.h"
#ifdef __DPDU__
-#include "bsdf_ward.h"
+#include "../closure/bsdf_ward.h"
#endif
-#include "bsdf_westin.h"
+#include "../closure/bsdf_westin.h"
CCL_NAMESPACE_BEGIN
@@ -36,45 +36,57 @@ __device int svm_bsdf_sample(const ShaderData *sd, const ShaderClosure *sc, floa
switch(sc->type) {
case CLOSURE_BSDF_DIFFUSE_ID:
- label = bsdf_diffuse_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_diffuse_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
#ifdef __SVM__
case CLOSURE_BSDF_OREN_NAYAR_ID:
- label = bsdf_oren_nayar_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_oren_nayar_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
case CLOSURE_BSDF_TRANSLUCENT_ID:
- label = bsdf_translucent_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_translucent_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
case CLOSURE_BSDF_REFLECTION_ID:
- label = bsdf_reflection_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_reflection_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
case CLOSURE_BSDF_REFRACTION_ID:
- label = bsdf_refraction_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_refraction_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
case CLOSURE_BSDF_TRANSPARENT_ID:
- label = bsdf_transparent_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_transparent_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
case CLOSURE_BSDF_MICROFACET_GGX_ID:
case CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID:
- label = bsdf_microfacet_ggx_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_microfacet_ggx_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
case CLOSURE_BSDF_MICROFACET_BECKMANN_ID:
case CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID:
- label = bsdf_microfacet_beckmann_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_microfacet_beckmann_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
#ifdef __DPDU__
case CLOSURE_BSDF_WARD_ID:
- label = bsdf_ward_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_ward_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
#endif
case CLOSURE_BSDF_ASHIKHMIN_VELVET_ID:
- label = bsdf_ashikhmin_velvet_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_ashikhmin_velvet_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
case CLOSURE_BSDF_WESTIN_BACKSCATTER_ID:
- label = bsdf_westin_backscatter_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_westin_backscatter_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
case CLOSURE_BSDF_WESTIN_SHEEN_ID:
- label = bsdf_westin_sheen_sample(sd, sc, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
+ label = bsdf_westin_sheen_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv,
+ eval, omega_in, &domega_in->dx, &domega_in->dy, pdf);
break;
#endif
default:
@@ -92,45 +104,45 @@ __device float3 svm_bsdf_eval(const ShaderData *sd, const ShaderClosure *sc, con
if(dot(sd->Ng, omega_in) >= 0.0f) {
switch(sc->type) {
case CLOSURE_BSDF_DIFFUSE_ID:
- eval = bsdf_diffuse_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_diffuse_eval_reflect(sc, sd->I, omega_in, pdf);
break;
#ifdef __SVM__
case CLOSURE_BSDF_OREN_NAYAR_ID:
- eval = bsdf_oren_nayar_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_oren_nayar_eval_reflect(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_TRANSLUCENT_ID:
- eval = bsdf_translucent_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_translucent_eval_reflect(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_REFLECTION_ID:
- eval = bsdf_reflection_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_reflection_eval_reflect(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_REFRACTION_ID:
- eval = bsdf_refraction_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_refraction_eval_reflect(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_TRANSPARENT_ID:
- eval = bsdf_transparent_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_transparent_eval_reflect(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_MICROFACET_GGX_ID:
case CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID:
- eval = bsdf_microfacet_ggx_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_microfacet_ggx_eval_reflect(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_MICROFACET_BECKMANN_ID:
case CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID:
- eval = bsdf_microfacet_beckmann_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_microfacet_beckmann_eval_reflect(sc, sd->I, omega_in, pdf);
break;
#ifdef __DPDU__
case CLOSURE_BSDF_WARD_ID:
- eval = bsdf_ward_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_ward_eval_reflect(sc, sd->I, omega_in, pdf);
break;
#endif
case CLOSURE_BSDF_ASHIKHMIN_VELVET_ID:
- eval = bsdf_ashikhmin_velvet_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_ashikhmin_velvet_eval_reflect(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_WESTIN_BACKSCATTER_ID:
- eval = bsdf_westin_backscatter_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_westin_backscatter_eval_reflect(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_WESTIN_SHEEN_ID:
- eval = bsdf_westin_sheen_eval_reflect(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_westin_sheen_eval_reflect(sc, sd->I, omega_in, pdf);
break;
#endif
default:
@@ -141,45 +153,45 @@ __device float3 svm_bsdf_eval(const ShaderData *sd, const ShaderClosure *sc, con
else {
switch(sc->type) {
case CLOSURE_BSDF_DIFFUSE_ID:
- eval = bsdf_diffuse_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_diffuse_eval_transmit(sc, sd->I, omega_in, pdf);
break;
#ifdef __SVM__
case CLOSURE_BSDF_OREN_NAYAR_ID:
- eval = bsdf_oren_nayar_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_oren_nayar_eval_transmit(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_TRANSLUCENT_ID:
- eval = bsdf_translucent_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_translucent_eval_transmit(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_REFLECTION_ID:
- eval = bsdf_reflection_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_reflection_eval_transmit(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_REFRACTION_ID:
- eval = bsdf_refraction_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_refraction_eval_transmit(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_TRANSPARENT_ID:
- eval = bsdf_transparent_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_transparent_eval_transmit(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_MICROFACET_GGX_ID:
case CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID:
- eval = bsdf_microfacet_ggx_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_microfacet_ggx_eval_transmit(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_MICROFACET_BECKMANN_ID:
case CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID:
- eval = bsdf_microfacet_beckmann_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_microfacet_beckmann_eval_transmit(sc, sd->I, omega_in, pdf);
break;
#ifdef __DPDU__
case CLOSURE_BSDF_WARD_ID:
- eval = bsdf_ward_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_ward_eval_transmit(sc, sd->I, omega_in, pdf);
break;
#endif
case CLOSURE_BSDF_ASHIKHMIN_VELVET_ID:
- eval = bsdf_ashikhmin_velvet_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_ashikhmin_velvet_eval_transmit(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_WESTIN_BACKSCATTER_ID:
- eval = bsdf_westin_backscatter_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_westin_backscatter_eval_transmit(sc, sd->I, omega_in, pdf);
break;
case CLOSURE_BSDF_WESTIN_SHEEN_ID:
- eval = bsdf_westin_sheen_eval_transmit(sd, sc, sd->I, omega_in, pdf);
+ eval = bsdf_westin_sheen_eval_transmit(sc, sd->I, omega_in, pdf);
break;
#endif
default:
diff --git a/intern/cycles/kernel/svm/svm_closure.h b/intern/cycles/kernel/svm/svm_closure.h
index 935504026ef..11ce3b7c5d1 100644
--- a/intern/cycles/kernel/svm/svm_closure.h
+++ b/intern/cycles/kernel/svm/svm_closure.h
@@ -23,16 +23,31 @@ CCL_NAMESPACE_BEGIN
__device void svm_node_glossy_setup(ShaderData *sd, ShaderClosure *sc, int type, float eta, float roughness, bool refract)
{
if(type == CLOSURE_BSDF_REFRACTION_ID) {
- if(refract)
- bsdf_refraction_setup(sd, sc, eta);
+ if(refract) {
+ sc->data0 = eta;
+ sd->flag |= bsdf_refraction_setup(sc);
+ }
else
- bsdf_reflection_setup(sd, sc);
+ sd->flag |= bsdf_reflection_setup(sc);
}
else if(type == CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID) {
- bsdf_microfacet_beckmann_setup(sd, sc, roughness, eta, refract);
+ sc->data0 = roughness;
+ sc->data1 = eta;
+
+ if(refract)
+ sd->flag |= bsdf_microfacet_beckmann_refraction_setup(sc);
+ else
+ sd->flag |= bsdf_microfacet_beckmann_setup(sc);
+ }
+ else {
+ sc->data0 = roughness;
+ sc->data1 = eta;
+
+ if(refract)
+ sd->flag |= bsdf_microfacet_ggx_refraction_setup(sc);
+ else
+ sd->flag |= bsdf_microfacet_ggx_setup(sc);
}
- else
- bsdf_microfacet_ggx_setup(sd, sc, roughness, eta, refract);
}
__device_inline ShaderClosure *svm_node_closure_get(ShaderData *sd)
@@ -57,7 +72,7 @@ __device_inline void svm_node_closure_set_mix_weight(ShaderClosure *sc, float mi
#endif
}
-__device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float *stack, uint4 node, float randb, int path_flag)
+__device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float *stack, uint4 node, float randb, int path_flag, int *offset)
{
uint type, param1_offset, param2_offset;
@@ -66,11 +81,19 @@ __device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float *st
decode_node_uchar4(node.y, &type, &param1_offset, &param2_offset, &mix_weight_offset);
float mix_weight = (stack_valid(mix_weight_offset)? stack_load_float(stack, mix_weight_offset): 1.0f);
+ /* note we read this extra node before weight check, so offset is added */
+ uint4 data_node = read_node(kg, offset);
+
if(mix_weight == 0.0f)
return;
+
+ float3 N = stack_valid(data_node.y)? stack_load_float3(stack, data_node.y): sd->N;
#else
decode_node_uchar4(node.y, &type, &param1_offset, &param2_offset, NULL);
float mix_weight = 1.0f;
+
+ uint4 data_node = read_node(kg, offset);
+ float3 N = stack_valid(data_node.y)? stack_load_float3(stack, data_node.y): sd->N;
#endif
float param1 = (stack_valid(param1_offset))? stack_load_float(stack, param1_offset): __int_as_float(node.z);
@@ -79,25 +102,32 @@ __device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float *st
switch(type) {
case CLOSURE_BSDF_DIFFUSE_ID: {
ShaderClosure *sc = svm_node_closure_get(sd);
+ sc->N = N;
svm_node_closure_set_mix_weight(sc, mix_weight);
float roughness = param1;
- if(roughness == 0.0f)
- bsdf_diffuse_setup(sd, sc);
- else
- bsdf_oren_nayar_setup(sd, sc, roughness);
+
+ if(roughness == 0.0f) {
+ sd->flag |= bsdf_diffuse_setup(sc);
+ }
+ else {
+ sc->data0 = roughness;
+ sd->flag |= bsdf_oren_nayar_setup(sc);
+ }
break;
}
case CLOSURE_BSDF_TRANSLUCENT_ID: {
ShaderClosure *sc = svm_node_closure_get(sd);
+ sc->N = N;
svm_node_closure_set_mix_weight(sc, mix_weight);
- bsdf_translucent_setup(sd, sc);
+ sd->flag |= bsdf_translucent_setup(sc);
break;
}
case CLOSURE_BSDF_TRANSPARENT_ID: {
ShaderClosure *sc = svm_node_closure_get(sd);
+ sc->N = N;
svm_node_closure_set_mix_weight(sc, mix_weight);
- bsdf_transparent_setup(sd, sc);
+ sd->flag |= bsdf_transparent_setup(sc);
break;
}
case CLOSURE_BSDF_REFLECTION_ID:
@@ -108,17 +138,17 @@ __device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float *st
break;
#endif
ShaderClosure *sc = svm_node_closure_get(sd);
+ sc->N = N;
+ sc->data0 = param1;
svm_node_closure_set_mix_weight(sc, mix_weight);
- float roughness = param1;
-
/* setup bsdf */
if(type == CLOSURE_BSDF_REFLECTION_ID)
- bsdf_reflection_setup(sd, sc);
+ sd->flag |= bsdf_reflection_setup(sc);
else if(type == CLOSURE_BSDF_MICROFACET_BECKMANN_ID)
- bsdf_microfacet_beckmann_setup(sd, sc, roughness, 1.0f, false);
+ sd->flag |= bsdf_microfacet_beckmann_setup(sc);
else
- bsdf_microfacet_ggx_setup(sd, sc, roughness, 1.0f, false);
+ sd->flag |= bsdf_microfacet_ggx_setup(sc);
break;
}
@@ -134,13 +164,14 @@ __device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float *st
eta = (sd->flag & SD_BACKFACING)? 1.0f/eta: eta;
/* fresnel */
- float cosNO = dot(sd->N, sd->I);
+ float cosNO = dot(N, sd->I);
float fresnel = fresnel_dielectric_cos(cosNO, eta);
float roughness = param1;
#ifdef __MULTI_CLOSURE__
/* reflection */
ShaderClosure *sc = svm_node_closure_get(sd);
+ sc->N = N;
float3 weight = sc->weight;
float sample_weight = sc->sample_weight;
@@ -150,6 +181,7 @@ __device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float *st
/* refraction */
sc = svm_node_closure_get(sd);
+ sc->N = N;
sc->weight = weight;
sc->sample_weight = sample_weight;
@@ -158,6 +190,7 @@ __device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float *st
svm_node_glossy_setup(sd, sc, type, eta, roughness, true);
#else
ShaderClosure *sc = svm_node_closure_get(sd);
+ sc->N = N;
bool refract = (randb > fresnel);
@@ -174,22 +207,41 @@ __device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float *st
break;
#endif
ShaderClosure *sc = svm_node_closure_get(sd);
+ sc->N = N;
+ sc->T = stack_load_float3(stack, data_node.z);
svm_node_closure_set_mix_weight(sc, mix_weight);
- float roughness_u = param1;
- float roughness_v = param2;
+ /* rotate tangent */
+ float rotation = stack_load_float(stack, data_node.w);
- bsdf_ward_setup(sd, sc, normalize(sd->dPdu), roughness_u, roughness_v);
+ if(rotation != 0.0f)
+ sc->T = rotate_around_axis(sc->T, sc->N, rotation * 2.0f * M_PI_F);
+
+ /* compute roughness */
+ float roughness = param1;
+ float anisotropy = clamp(param2, -0.99f, 0.99f);
+
+ if(anisotropy < 0.0f) {
+ sc->data0 = roughness*(1.0f + anisotropy);
+ sc->data1 = roughness/(1.0f + anisotropy);
+ }
+ else {
+ sc->data0 = roughness/(1.0f - anisotropy);
+ sc->data1 = roughness*(1.0f - anisotropy);
+ }
+
+ sd->flag |= bsdf_ward_setup(sc);
break;
}
#endif
case CLOSURE_BSDF_ASHIKHMIN_VELVET_ID: {
ShaderClosure *sc = svm_node_closure_get(sd);
+ sc->N = N;
svm_node_closure_set_mix_weight(sc, mix_weight);
/* sigma */
- float sigma = clamp(param1, 0.0f, 1.0f);
- bsdf_ashikhmin_velvet_setup(sd, sc, sigma);
+ sc->data0 = clamp(param1, 0.0f, 1.0f);
+ sd->flag |= bsdf_ashikhmin_velvet_setup(sc);
break;
}
default:
@@ -222,7 +274,7 @@ __device void svm_node_closure_volume(KernelGlobals *kg, ShaderData *sd, float *
svm_node_closure_set_mix_weight(sc, mix_weight);
float density = param1;
- volume_transparent_setup(sd, sc, density);
+ sd->flag |= volume_transparent_setup(sc, density);
break;
}
case CLOSURE_VOLUME_ISOTROPIC_ID: {
@@ -230,7 +282,7 @@ __device void svm_node_closure_volume(KernelGlobals *kg, ShaderData *sd, float *
svm_node_closure_set_mix_weight(sc, mix_weight);
float density = param1;
- volume_isotropic_setup(sd, sc, density);
+ sd->flag |= volume_isotropic_setup(sc, density);
break;
}
default:
@@ -425,5 +477,14 @@ __device void svm_node_add_closure(ShaderData *sd, float *stack, uint unused,
#endif
}
+/* (Bump) normal */
+
+__device void svm_node_set_normal(KernelGlobals *kg, ShaderData *sd, float *stack, uint in_direction, uint out_normal)
+{
+ float3 normal = stack_load_float3(stack, in_direction);
+ sd->N = normal;
+ stack_store_float3(stack, out_normal, normal);
+}
+
CCL_NAMESPACE_END
diff --git a/intern/cycles/kernel/svm/svm_convert.h b/intern/cycles/kernel/svm/svm_convert.h
index 188b0489d9e..f74915a4bc9 100644
--- a/intern/cycles/kernel/svm/svm_convert.h
+++ b/intern/cycles/kernel/svm/svm_convert.h
@@ -23,6 +23,11 @@ CCL_NAMESPACE_BEGIN
__device void svm_node_convert(ShaderData *sd, float *stack, uint type, uint from, uint to)
{
switch(type) {
+ case NODE_CONVERT_FI: {
+ float f = stack_load_float(stack, from);
+ stack_store_int(stack, to, (int)f);
+ break;
+ }
case NODE_CONVERT_FV: {
float f = stack_load_float(stack, from);
stack_store_float3(stack, to, make_float3(f, f, f));
@@ -34,13 +39,34 @@ __device void svm_node_convert(ShaderData *sd, float *stack, uint type, uint fro
stack_store_float(stack, to, g);
break;
}
+ case NODE_CONVERT_CI: {
+ float3 f = stack_load_float3(stack, from);
+ int i = (int)linear_rgb_to_gray(f);
+ stack_store_int(stack, to, i);
+ break;
+ }
case NODE_CONVERT_VF: {
float3 f = stack_load_float3(stack, from);
float g = (f.x + f.y + f.z)*(1.0f/3.0f);
stack_store_float(stack, to, g);
break;
}
-
+ case NODE_CONVERT_VI: {
+ float3 f = stack_load_float3(stack, from);
+ int i = (f.x + f.y + f.z)*(1.0f/3.0f);
+ stack_store_int(stack, to, i);
+ break;
+ }
+ case NODE_CONVERT_IF: {
+ float f = (float)stack_load_int(stack, from);
+ stack_store_float(stack, to, f);
+ break;
+ }
+ case NODE_CONVERT_IV: {
+ float f = (float)stack_load_int(stack, from);
+ stack_store_float3(stack, to, make_float3(f, f, f));
+ break;
+ }
}
}
diff --git a/intern/cycles/kernel/svm/svm_displace.h b/intern/cycles/kernel/svm/svm_displace.h
index b1677f67eca..92f23990ad1 100644
--- a/intern/cycles/kernel/svm/svm_displace.h
+++ b/intern/cycles/kernel/svm/svm_displace.h
@@ -20,23 +20,35 @@ CCL_NAMESPACE_BEGIN
/* Bump Node */
-__device void svm_node_set_bump(ShaderData *sd, float *stack, uint c_offset, uint x_offset, uint y_offset)
+__device void svm_node_set_bump(KernelGlobals *kg, ShaderData *sd, float *stack, uint4 node)
{
#ifdef __RAY_DIFFERENTIALS__
+ /* get normal input */
+ float3 normal_in = stack_valid(node.y)? stack_load_float3(stack, node.y): sd->N;
+
+ /* get surface tangents from normal */
+ float3 Rx = cross(sd->dP.dy, normal_in);
+ float3 Ry = cross(normal_in, sd->dP.dx);
+
+ /* get bump values */
+ uint c_offset, x_offset, y_offset, intensity_offset;
+ decode_node_uchar4(node.z, &c_offset, &x_offset, &y_offset, &intensity_offset);
+
float h_c = stack_load_float(stack, c_offset);
float h_x = stack_load_float(stack, x_offset);
float h_y = stack_load_float(stack, y_offset);
- float3 Rx = cross(sd->dP.dy, sd->N);
- float3 Ry = cross(sd->N, sd->dP.dx);
-
+ /* compute surface gradient and determinant */
float det = dot(sd->dP.dx, Rx);
float3 surfgrad = (h_x - h_c)*Rx + (h_y - h_c)*Ry;
+ float intensity = stack_load_float(stack, intensity_offset);
- surfgrad *= 0.1f; /* todo: remove this factor */
-
+ surfgrad *= intensity;
float absdet = fabsf(det);
- sd->N = normalize(absdet*sd->N - signf(det)*surfgrad);
+
+ /* compute and output perturbed normal */
+ float3 outN = normalize(absdet*normal_in - signf(det)*surfgrad);
+ stack_store_float3(stack, node.w, outN);
#endif
}
diff --git a/intern/cycles/kernel/svm/svm_fresnel.h b/intern/cycles/kernel/svm/svm_fresnel.h
index 7684eabeecb..d5b415a87ce 100644
--- a/intern/cycles/kernel/svm/svm_fresnel.h
+++ b/intern/cycles/kernel/svm/svm_fresnel.h
@@ -54,7 +54,7 @@ __device void svm_node_layer_weight(ShaderData *sd, float *stack, uint4 node)
f = fabsf(dot(sd->I, sd->N));
if(blend != 0.5f) {
- blend = clamp(blend, 0.0f, 1.0f);
+ blend = clamp(blend, 0.0f, 1.0f-1e-5f);
blend = (blend < 0.5f)? 2.0f*blend: 0.5f/(1.0f - blend);
f = powf(f, blend);
diff --git a/intern/cycles/kernel/svm/svm_geometry.h b/intern/cycles/kernel/svm/svm_geometry.h
index 22741bdb067..8e772f849c7 100644
--- a/intern/cycles/kernel/svm/svm_geometry.h
+++ b/intern/cycles/kernel/svm/svm_geometry.h
@@ -20,7 +20,7 @@ CCL_NAMESPACE_BEGIN
/* Geometry Node */
-__device void svm_node_geometry(ShaderData *sd, float *stack, uint type, uint out_offset)
+__device void svm_node_geometry(KernelGlobals *kg, ShaderData *sd, float *stack, uint type, uint out_offset)
{
float3 data;
@@ -28,7 +28,34 @@ __device void svm_node_geometry(ShaderData *sd, float *stack, uint type, uint ou
case NODE_GEOM_P: data = sd->P; break;
case NODE_GEOM_N: data = sd->N; break;
#ifdef __DPDU__
- case NODE_GEOM_T: data = normalize(sd->dPdu); break;
+ case NODE_GEOM_T: {
+ /* first try to get tangent attribute */
+ int attr_offset = (sd->object != ~0)? find_attribute(kg, sd, ATTR_STD_TANGENT): ATTR_STD_NOT_FOUND;
+
+ if(attr_offset != ATTR_STD_NOT_FOUND) {
+ /* ensure orthogonal and normalized (interpolation breaks it) */
+ data = triangle_attribute_float3(kg, sd, ATTR_ELEMENT_CORNER, attr_offset, NULL, NULL);
+ object_normal_transform(kg, sd, &data);
+ data = cross(sd->N, normalize(cross(data, sd->N)));;
+ }
+ else {
+ /* try to create spherical tangent from generated coordinates */
+ int attr_offset = (sd->object != ~0)? find_attribute(kg, sd, ATTR_STD_GENERATED): ATTR_STD_NOT_FOUND;
+
+ if(attr_offset != ATTR_STD_NOT_FOUND) {
+ data = triangle_attribute_float3(kg, sd, ATTR_ELEMENT_VERTEX, attr_offset, NULL, NULL);
+ data = make_float3(-(data.y - 0.5), (data.x - 0.5), 0.0f);
+ object_normal_transform(kg, sd, &data);
+ data = cross(sd->N, normalize(cross(data, sd->N)));;
+ }
+ else {
+ /* otherwise use surface derivatives */
+ data = normalize(sd->dPdu);
+ }
+ }
+
+ break;
+ }
#endif
case NODE_GEOM_I: data = sd->I; break;
case NODE_GEOM_Ng: data = sd->Ng; break;
@@ -40,7 +67,7 @@ __device void svm_node_geometry(ShaderData *sd, float *stack, uint type, uint ou
stack_store_float3(stack, out_offset, data);
}
-__device void svm_node_geometry_bump_dx(ShaderData *sd, float *stack, uint type, uint out_offset)
+__device void svm_node_geometry_bump_dx(KernelGlobals *kg, ShaderData *sd, float *stack, uint type, uint out_offset)
{
#ifdef __RAY_DIFFERENTIALS__
float3 data;
@@ -48,16 +75,16 @@ __device void svm_node_geometry_bump_dx(ShaderData *sd, float *stack, uint type,
switch(type) {
case NODE_GEOM_P: data = sd->P + sd->dP.dx; break;
case NODE_GEOM_uv: data = make_float3(sd->u + sd->du.dx, sd->v + sd->dv.dx, 0.0f); break;
- default: svm_node_geometry(sd, stack, type, out_offset); return;
+ default: svm_node_geometry(kg, sd, stack, type, out_offset); return;
}
stack_store_float3(stack, out_offset, data);
#else
- svm_node_geometry(sd, stack, type, out_offset);
+ svm_node_geometry(kg, sd, stack, type, out_offset);
#endif
}
-__device void svm_node_geometry_bump_dy(ShaderData *sd, float *stack, uint type, uint out_offset)
+__device void svm_node_geometry_bump_dy(KernelGlobals *kg, ShaderData *sd, float *stack, uint type, uint out_offset)
{
#ifdef __RAY_DIFFERENTIALS__
float3 data;
@@ -65,12 +92,12 @@ __device void svm_node_geometry_bump_dy(ShaderData *sd, float *stack, uint type,
switch(type) {
case NODE_GEOM_P: data = sd->P + sd->dP.dy; break;
case NODE_GEOM_uv: data = make_float3(sd->u + sd->du.dy, sd->v + sd->dv.dy, 0.0f); break;
- default: svm_node_geometry(sd, stack, type, out_offset); return;
+ default: svm_node_geometry(kg, sd, stack, type, out_offset); return;
}
stack_store_float3(stack, out_offset, data);
#else
- svm_node_geometry(sd, stack, type, out_offset);
+ svm_node_geometry(kg, sd, stack, type, out_offset);
#endif
}
diff --git a/intern/cycles/kernel/svm/svm_hsv.h b/intern/cycles/kernel/svm/svm_hsv.h
index ed17d3fc985..bce11d62923 100644
--- a/intern/cycles/kernel/svm/svm_hsv.h
+++ b/intern/cycles/kernel/svm/svm_hsv.h
@@ -69,11 +69,11 @@ __device float3 hsv_to_rgb(float3 hsv)
s = hsv.y;
v = hsv.z;
- if(s==0.0f) {
+ if(s == 0.0f) {
rgb = make_float3(v, v, v);
}
else {
- if(h==1.0f)
+ if(h == 1.0f)
h = 0.0f;
h *= 6.0f;
diff --git a/intern/cycles/kernel/svm/svm_image.h b/intern/cycles/kernel/svm/svm_image.h
index 662419418e3..0894c9c8290 100644
--- a/intern/cycles/kernel/svm/svm_image.h
+++ b/intern/cycles/kernel/svm/svm_image.h
@@ -52,6 +52,12 @@ __device_inline float svm_image_texture_frac(float x, int *ix)
__device float4 svm_image_texture(KernelGlobals *kg, int id, float x, float y, uint srgb)
{
+ /* first slots are used by float textures, which are not supported here */
+ if(id < TEX_NUM_FLOAT_IMAGES)
+ return make_float4(1.0f, 0.0f, 1.0f, 1.0f);
+
+ id -= TEX_NUM_FLOAT_IMAGES;
+
uint4 info = kernel_tex_fetch(__tex_image_packed_info, id);
uint width = info.x;
uint height = info.y;
@@ -265,7 +271,7 @@ __device void svm_node_tex_image_box(KernelGlobals *kg, ShaderData *sd, float *s
* between three textures.
*
* the Nxyz values are the barycentric coordinates in an equilateral
- * triangle, which in case of blending in the middle has a smaller
+ * triangle, which in case of blending, in the middle has a smaller
* equilateral triangle where 3 textures blend. this divides things into
* 7 zones, with an if() test for each zone */
diff --git a/intern/cycles/kernel/svm/svm_noise.h b/intern/cycles/kernel/svm/svm_noise.h
index dfaf43acbd4..224a1d96543 100644
--- a/intern/cycles/kernel/svm/svm_noise.h
+++ b/intern/cycles/kernel/svm/svm_noise.h
@@ -104,7 +104,7 @@ __device float grad(int hash, float x, float y, float z)
// use vectors pointing to the edges of the cube
int h = hash & 15;
float u = h<8 ? x : y;
- float v = h<4 ? y : h==12||h==14 ? x : z;
+ float v = h<4 ? y : h == 12 || h == 14 ? x : z;
return ((h&1) ? -u : u) + ((h&2) ? -v : v);
}
diff --git a/intern/cycles/kernel/svm/svm_tex_coord.h b/intern/cycles/kernel/svm/svm_tex_coord.h
index fbaf253177d..6bd8f2ac69c 100644
--- a/intern/cycles/kernel/svm/svm_tex_coord.h
+++ b/intern/cycles/kernel/svm/svm_tex_coord.h
@@ -92,6 +92,14 @@ __device void svm_node_tex_coord(KernelGlobals *kg, ShaderData *sd, float *stack
data = sd->I;
break;
}
+ case NODE_TEXCO_DUPLI_GENERATED: {
+ data = object_dupli_generated(kg, sd->object);
+ break;
+ }
+ case NODE_TEXCO_DUPLI_UV: {
+ data = object_dupli_uv(kg, sd->object);
+ break;
+ }
}
stack_store_float3(stack, out_offset, data);
@@ -141,6 +149,14 @@ __device void svm_node_tex_coord_bump_dx(KernelGlobals *kg, ShaderData *sd, floa
data = sd->I;
break;
}
+ case NODE_TEXCO_DUPLI_GENERATED: {
+ data = object_dupli_generated(kg, sd->object);
+ break;
+ }
+ case NODE_TEXCO_DUPLI_UV: {
+ data = object_dupli_uv(kg, sd->object);
+ break;
+ }
}
stack_store_float3(stack, out_offset, data);
@@ -193,6 +209,14 @@ __device void svm_node_tex_coord_bump_dy(KernelGlobals *kg, ShaderData *sd, floa
data = sd->I;
break;
}
+ case NODE_TEXCO_DUPLI_GENERATED: {
+ data = object_dupli_generated(kg, sd->object);
+ break;
+ }
+ case NODE_TEXCO_DUPLI_UV: {
+ data = object_dupli_uv(kg, sd->object);
+ break;
+ }
}
stack_store_float3(stack, out_offset, data);
diff --git a/intern/cycles/kernel/svm/svm_types.h b/intern/cycles/kernel/svm/svm_types.h
index c82eafc790a..77df373a159 100644
--- a/intern/cycles/kernel/svm/svm_types.h
+++ b/intern/cycles/kernel/svm/svm_types.h
@@ -43,6 +43,7 @@ typedef enum NodeType {
NODE_TEX_IMAGE_BOX,
NODE_TEX_SKY,
NODE_GEOMETRY,
+ NODE_GEOMETRY_DUPLI,
NODE_LIGHT_PATH,
NODE_VALUE_F,
NODE_VALUE_V,
@@ -91,7 +92,8 @@ typedef enum NodeType {
NODE_LIGHT_FALLOFF,
NODE_OBJECT_INFO,
NODE_PARTICLE_INFO,
- NODE_TEX_BRICK
+ NODE_TEX_BRICK,
+ NODE_CLOSURE_SET_NORMAL,
} NodeType;
typedef enum NodeAttributeType {
@@ -149,7 +151,9 @@ typedef enum NodeTexCoord {
NODE_TEXCO_OBJECT,
NODE_TEXCO_CAMERA,
NODE_TEXCO_WINDOW,
- NODE_TEXCO_REFLECTION
+ NODE_TEXCO_REFLECTION,
+ NODE_TEXCO_DUPLI_GENERATED,
+ NODE_TEXCO_DUPLI_UV
} NodeTexCoord;
typedef enum NodeMix {
@@ -206,8 +210,13 @@ typedef enum NodeVectorMath {
typedef enum NodeConvert {
NODE_CONVERT_FV,
+ NODE_CONVERT_FI,
NODE_CONVERT_CF,
- NODE_CONVERT_VF
+ NODE_CONVERT_CI,
+ NODE_CONVERT_VF,
+ NODE_CONVERT_VI,
+ NODE_CONVERT_IF,
+ NODE_CONVERT_IV
} NodeConvert;
typedef enum NodeDistanceMetric {
@@ -284,16 +293,18 @@ typedef enum ClosureType {
CLOSURE_BSDF_DIFFUSE_ID,
CLOSURE_BSDF_OREN_NAYAR_ID,
+ CLOSURE_BSDF_GLOSSY_ID,
CLOSURE_BSDF_REFLECTION_ID,
CLOSURE_BSDF_MICROFACET_GGX_ID,
CLOSURE_BSDF_MICROFACET_BECKMANN_ID,
CLOSURE_BSDF_WARD_ID,
+ CLOSURE_BSDF_ASHIKHMIN_VELVET_ID,
CLOSURE_BSDF_WESTIN_SHEEN_ID,
+ CLOSURE_BSDF_TRANSMISSION_ID,
CLOSURE_BSDF_TRANSLUCENT_ID,
CLOSURE_BSDF_REFRACTION_ID,
CLOSURE_BSDF_WESTIN_BACKSCATTER_ID,
- CLOSURE_BSDF_ASHIKHMIN_VELVET_ID,
CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID,
CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID,
CLOSURE_BSDF_GLASS_ID,
@@ -317,8 +328,8 @@ typedef enum ClosureType {
/* watch this, being lazy with memory usage */
#define CLOSURE_IS_BSDF(type) (type <= CLOSURE_BSDF_TRANSPARENT_ID)
#define CLOSURE_IS_BSDF_DIFFUSE(type) (type >= CLOSURE_BSDF_DIFFUSE_ID && type <= CLOSURE_BSDF_OREN_NAYAR_ID)
-#define CLOSURE_IS_BSDF_GLOSSY(type) (type >= CLOSURE_BSDF_REFLECTION_ID && type <= CLOSURE_BSDF_WESTIN_SHEEN_ID)
-#define CLOSURE_IS_BSDF_TRANSMISSION(type) (type >= CLOSURE_BSDF_TRANSLUCENT_ID && type <= CLOSURE_BSDF_GLASS_ID)
+#define CLOSURE_IS_BSDF_GLOSSY(type) (type >= CLOSURE_BSDF_GLOSSY_ID && type <= CLOSURE_BSDF_WESTIN_SHEEN_ID)
+#define CLOSURE_IS_BSDF_TRANSMISSION(type) (type >= CLOSURE_BSDF_TRANSMISSION_ID && type <= CLOSURE_BSDF_GLASS_ID)
#define CLOSURE_IS_VOLUME(type) (type >= CLOSURE_VOLUME_ID && type <= CLOSURE_VOLUME_ISOTROPIC_ID)
#define CLOSURE_IS_EMISSION(type) (type == CLOSURE_EMISSION_ID)
#define CLOSURE_IS_HOLDOUT(type) (type == CLOSURE_HOLDOUT_ID)
diff --git a/intern/cycles/render/CMakeLists.txt b/intern/cycles/render/CMakeLists.txt
index 85b476e60d9..7907061c19c 100644
--- a/intern/cycles/render/CMakeLists.txt
+++ b/intern/cycles/render/CMakeLists.txt
@@ -7,6 +7,9 @@ set(INC
../kernel/osl
../bvh
../util
+)
+
+set(INC_SYS
${GLEW_INCLUDE_PATH}
)
@@ -64,6 +67,7 @@ set(SRC_HEADERS
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${RTTI_DISABLE_FLAGS}")
include_directories(${INC})
+include_directories(SYSTEM ${INC_SYS})
add_library(cycles_render ${SRC} ${SRC_HEADERS})
diff --git a/intern/cycles/render/attribute.cpp b/intern/cycles/render/attribute.cpp
index 5122c1af410..c7a9ab3e51a 100644
--- a/intern/cycles/render/attribute.cpp
+++ b/intern/cycles/render/attribute.cpp
@@ -162,6 +162,8 @@ Attribute *AttributeSet::add(AttributeStandard std, ustring name)
attr = add(name, TypeDesc::TypeNormal, Attribute::FACE);
else if(std == ATTR_STD_UV)
attr = add(name, TypeDesc::TypePoint, Attribute::CORNER);
+ else if(std == ATTR_STD_TANGENT)
+ attr = add(name, TypeDesc::TypeVector, Attribute::CORNER);
else if(std == ATTR_STD_GENERATED)
attr = add(name, TypeDesc::TypePoint, Attribute::VERTEX);
else if(std == ATTR_STD_POSITION_UNDEFORMED)
diff --git a/intern/cycles/render/buffers.cpp b/intern/cycles/render/buffers.cpp
index 51568f65323..3b61ccd176d 100644
--- a/intern/cycles/render/buffers.cpp
+++ b/intern/cycles/render/buffers.cpp
@@ -101,7 +101,7 @@ RenderTile::RenderTile()
RenderBuffers::RenderBuffers(Device *device_)
{
- device = device_;
+ device = device_;
}
RenderBuffers::~RenderBuffers()
@@ -196,7 +196,18 @@ bool RenderBuffers::get_pass_rect(PassType type, float exposure, int sample, int
else if(components == 3) {
assert(pass.components == 4);
- if(pass.divide_type != PASS_NONE) {
+ /* RGBA */
+ if(type == PASS_SHADOW) {
+ for(int i = 0; i < size; i++, in += pass_stride, pixels += 3) {
+ float4 f = make_float4(in[0], in[1], in[2], in[3]);
+ float invw = (f.w > 0.0f)? 1.0f/f.w: 1.0f;
+
+ pixels[0] = f.x*invw;
+ pixels[1] = f.y*invw;
+ pixels[2] = f.z*invw;
+ }
+ }
+ else if(pass.divide_type != PASS_NONE) {
/* RGB lighting passes that need to divide out color */
pass_offset = 0;
foreach(Pass& color_pass, params.passes) {
diff --git a/intern/cycles/render/camera.cpp b/intern/cycles/render/camera.cpp
index e44caa90f12..649936bec04 100644
--- a/intern/cycles/render/camera.cpp
+++ b/intern/cycles/render/camera.cpp
@@ -19,6 +19,8 @@
#include "camera.h"
#include "scene.h"
+#include "device.h"
+
#include "util_vector.h"
CCL_NAMESPACE_BEGIN
@@ -141,7 +143,7 @@ void Camera::update()
void Camera::device_update(Device *device, DeviceScene *dscene, Scene *scene)
{
- Scene::MotionType need_motion = scene->need_motion();
+ Scene::MotionType need_motion = scene->need_motion(device->info.advanced_shading);
update();
@@ -160,7 +162,6 @@ void Camera::device_update(Device *device, DeviceScene *dscene, Scene *scene)
/* store matrices */
kcam->screentoworld = screentoworld;
kcam->rastertoworld = rastertoworld;
- kcam->ndctoworld = ndctoworld;
kcam->rastertocamera = rastertocamera;
kcam->cameratoworld = cameratoworld;
kcam->worldtoscreen = transform_inverse(screentoworld);
@@ -193,13 +194,14 @@ void Camera::device_update(Device *device, DeviceScene *dscene, Scene *scene)
}
}
}
+#ifdef __CAMERA_MOTION__
else if(need_motion == Scene::MOTION_BLUR) {
- /* todo: exact camera position will not be hit this way */
if(use_motion) {
- transform_motion_decompose(&kcam->motion, &motion);
+ transform_motion_decompose(&kcam->motion, &motion, &matrix);
kcam->have_motion = 1;
}
}
+#endif
/* depth of field */
kcam->aperturesize = aperturesize;
@@ -208,7 +210,11 @@ void Camera::device_update(Device *device, DeviceScene *dscene, Scene *scene)
kcam->bladesrotation = bladesrotation;
/* motion blur */
+#ifdef __CAMERA_MOTION__
kcam->shuttertime = (need_motion == Scene::MOTION_BLUR) ? shuttertime: 0.0f;
+#else
+ kcam->shuttertime = 0.0f;
+#endif
/* type */
kcam->type = type;
@@ -245,7 +251,7 @@ void Camera::device_free(Device *device, DeviceScene *dscene)
bool Camera::modified(const Camera& cam)
{
- return !((shuttertime== cam.shuttertime) &&
+ return !((shuttertime == cam.shuttertime) &&
(aperturesize == cam.aperturesize) &&
(blades == cam.blades) &&
(bladesrotation == cam.bladesrotation) &&
@@ -268,13 +274,17 @@ bool Camera::modified(const Camera& cam)
(border_bottom == cam.border_bottom) &&
(border_top == cam.border_top) &&
(matrix == cam.matrix) &&
- (motion == cam.motion) &&
- (use_motion == cam.use_motion) &&
(panorama_type == cam.panorama_type) &&
(fisheye_fov == cam.fisheye_fov) &&
(fisheye_lens == cam.fisheye_lens));
}
+bool Camera::motion_modified(const Camera& cam)
+{
+ return !((motion == cam.motion) &&
+ (use_motion == cam.use_motion));
+}
+
void Camera::tag_update()
{
need_update = true;
diff --git a/intern/cycles/render/camera.h b/intern/cycles/render/camera.h
index 82852bde5e0..1407c86e7c2 100644
--- a/intern/cycles/render/camera.h
+++ b/intern/cycles/render/camera.h
@@ -103,6 +103,7 @@ public:
void device_free(Device *device, DeviceScene *dscene);
bool modified(const Camera& cam);
+ bool motion_modified(const Camera& cam);
void tag_update();
};
diff --git a/intern/cycles/render/graph.cpp b/intern/cycles/render/graph.cpp
index 20fbfa0cf27..c1c976dc193 100644
--- a/intern/cycles/render/graph.cpp
+++ b/intern/cycles/render/graph.cpp
@@ -181,14 +181,14 @@ void ShaderGraph::connect(ShaderOutput *from, ShaderInput *to)
assert(from && to);
if(to->link) {
- fprintf(stderr, "ShaderGraph connect: input already connected.\n");
+ fprintf(stderr, "Cycles shader graph connect: input already connected.\n");
return;
}
if(from->type != to->type) {
/* for closures we can't do automatic conversion */
if(from->type == SHADER_SOCKET_CLOSURE || to->type == SHADER_SOCKET_CLOSURE) {
- fprintf(stderr, "ShaderGraph connect: can only connect closure to closure "
+ fprintf(stderr, "Cycles shader graph connect: can only connect closure to closure "
"(ShaderNode:%s, ShaderOutput:%s , type:%d -> to ShaderNode:%s, ShaderInput:%s, type:%d).\n",
from->parent->name.c_str(), from->name, (int)from->type,
to->parent->name.c_str(), to->name, (int)to->type);
@@ -229,6 +229,8 @@ void ShaderGraph::finalize(bool do_bump, bool do_osl)
if(!finalized) {
clean();
default_inputs(do_osl);
+ refine_bump_nodes();
+
if(do_bump)
bump_from_displacement();
@@ -363,7 +365,7 @@ void ShaderGraph::break_cycles(ShaderNode *node, vector<bool>& visited, vector<b
if(on_stack[depnode->id]) {
/* break cycle */
disconnect(input);
- fprintf(stderr, "ShaderGraph: detected cycle in graph, connection removed.\n");
+ fprintf(stderr, "Cycles shader graph: detected cycle in graph, connection removed.\n");
}
else if(!visited[depnode->id]) {
/* visit dependencies */
@@ -468,6 +470,12 @@ void ShaderGraph::default_inputs(bool do_osl)
connect(geom->output("Position"), input);
}
+ else if(input->default_value == ShaderInput::TANGENT) {
+ if(!geom)
+ geom = new GeometryNode();
+
+ connect(geom->output("Tangent"), input);
+ }
}
}
}
@@ -478,6 +486,61 @@ void ShaderGraph::default_inputs(bool do_osl)
add(texco);
}
+void ShaderGraph::refine_bump_nodes()
+{
+ /* we transverse the node graph looking for bump nodes, when we find them,
+ * like in bump_from_displacement(), we copy the sub-graph defined from "bump"
+ * input to the inputs "center","dx" and "dy" What is in "bump" input is moved
+ * to "center" input. */
+
+ foreach(ShaderNode *node, nodes) {
+ if(node->name == ustring("bump") && node->input("Height")->link) {
+ ShaderInput *bump_input = node->input("Height");
+ set<ShaderNode*> nodes_bump;
+
+ /* make 2 extra copies of the subgraph defined in Bump input */
+ map<ShaderNode*, ShaderNode*> nodes_dx;
+ map<ShaderNode*, ShaderNode*> nodes_dy;
+
+ /* find dependencies for the given input */
+ find_dependencies(nodes_bump, bump_input );
+
+ copy_nodes(nodes_bump, nodes_dx);
+ copy_nodes(nodes_bump, nodes_dy);
+
+ /* mark nodes to indicate they are use for bump computation, so
+ that any texture coordinates are shifted by dx/dy when sampling */
+ foreach(ShaderNode *node, nodes_bump)
+ node->bump = SHADER_BUMP_CENTER;
+ foreach(NodePair& pair, nodes_dx)
+ pair.second->bump = SHADER_BUMP_DX;
+ foreach(NodePair& pair, nodes_dy)
+ pair.second->bump = SHADER_BUMP_DY;
+
+ ShaderOutput *out = bump_input->link;
+ ShaderOutput *out_dx = nodes_dx[out->parent]->output(out->name);
+ ShaderOutput *out_dy = nodes_dy[out->parent]->output(out->name);
+
+ connect(out_dx, node->input("SampleX"));
+ connect(out_dy, node->input("SampleY"));
+
+ /* add generated nodes */
+ foreach(NodePair& pair, nodes_dx)
+ add(pair.second);
+ foreach(NodePair& pair, nodes_dy)
+ add(pair.second);
+
+ /* connect what is conected is bump to samplecenter input*/
+ connect(out , node->input("SampleCenter"));
+
+ /* bump input is just for connectivity purpose for the graph input,
+ * we reconected this input to samplecenter, so lets disconnect it
+ * from bump input */
+ disconnect(bump_input);
+ }
+ }
+}
+
void ShaderGraph::bump_from_displacement()
{
/* generate bump mapping automatically from displacement. bump mapping is
@@ -491,7 +554,7 @@ void ShaderGraph::bump_from_displacement()
* different shifted coordinates.
*
* these 3 displacement values are then fed into the bump node, which will
- * modify the normal. */
+ * output the the perturbed normal. */
ShaderInput *displacement_in = output()->input("Displacement");
@@ -520,6 +583,12 @@ void ShaderGraph::bump_from_displacement()
foreach(NodePair& pair, nodes_dy)
pair.second->bump = SHADER_BUMP_DY;
+ /* add set normal node and connect the bump normal ouput to the set normal
+ * output, so it can finally set the shader normal, note we are only doing
+ * this for bump from displacement, this will be the only bump allowed to
+ * overwrite the shader normal */
+ ShaderNode *set_normal = add(new SetNormalNode());
+
/* add bump node and connect copied graphs to it */
ShaderNode *bump = add(new BumpNode());
@@ -531,6 +600,9 @@ void ShaderGraph::bump_from_displacement()
connect(out_center, bump->input("SampleCenter"));
connect(out_dx, bump->input("SampleX"));
connect(out_dy, bump->input("SampleY"));
+
+ /* connect the bump out to the set normal in: */
+ connect(bump->output("Normal"), set_normal->input("Direction"));
/* connect bump output to normal input nodes that aren't set yet. actually
* this will only set the normal input to the geometry node that we created
@@ -538,8 +610,14 @@ void ShaderGraph::bump_from_displacement()
foreach(ShaderNode *node, nodes)
foreach(ShaderInput *input, node->inputs)
if(!input->link && input->default_value == ShaderInput::NORMAL)
- connect(bump->output("Normal"), input);
-
+ connect(set_normal->output("Normal"), input);
+
+ /* for displacement bump, clear the normal input in case the above loop
+ * connected the setnormal out to the bump normalin */
+ ShaderInput *bump_normal_in = bump->input("NormalIn");
+ if(bump_normal_in)
+ bump_normal_in->link = NULL;
+
/* finally, add the copied nodes to the graph. we can't do this earlier
* because we would create dependency cycles in the above loop */
foreach(NodePair& pair, nodes_center)
diff --git a/intern/cycles/render/graph.h b/intern/cycles/render/graph.h
index c3b674d0f23..b339c3c3847 100644
--- a/intern/cycles/render/graph.h
+++ b/intern/cycles/render/graph.h
@@ -44,6 +44,7 @@ class OSLCompiler;
enum ShaderSocketType {
SHADER_SOCKET_FLOAT,
+ SHADER_SOCKET_INT,
SHADER_SOCKET_COLOR,
SHADER_SOCKET_VECTOR,
SHADER_SOCKET_POINT,
@@ -112,6 +113,7 @@ public:
INCOMING,
NORMAL,
POSITION,
+ TANGENT,
NONE
};
@@ -234,6 +236,7 @@ protected:
void break_cycles(ShaderNode *node, vector<bool>& visited, vector<bool>& on_stack);
void clean();
void bump_from_displacement();
+ void refine_bump_nodes();
void default_inputs(bool do_osl);
};
diff --git a/intern/cycles/render/image.cpp b/intern/cycles/render/image.cpp
index 4ee024dd52a..f136f08dc2c 100644
--- a/intern/cycles/render/image.cpp
+++ b/intern/cycles/render/image.cpp
@@ -366,8 +366,10 @@ void ImageManager::device_load_image(Device *device, DeviceScene *dscene, int sl
device_vector<float4>& tex_img = dscene->tex_float_image[slot];
- if(tex_img.device_pointer)
+ if(tex_img.device_pointer) {
+ thread_scoped_lock device_lock(device_mutex);
device->tex_free(tex_img);
+ }
if(!file_load_float_image(img, tex_img)) {
/* on failure to load, we set a 1x1 pixels pink image */
@@ -384,8 +386,10 @@ void ImageManager::device_load_image(Device *device, DeviceScene *dscene, int sl
if(slot >= 10) name = string_printf("__tex_image_float_0%d", slot);
else name = string_printf("__tex_image_float_00%d", slot);
- if(!pack_images)
+ if(!pack_images) {
+ thread_scoped_lock device_lock(device_mutex);
device->tex_alloc(name.c_str(), tex_img, true, true);
+ }
}
else {
string filename = path_filename(images[slot - tex_image_byte_start]->filename);
@@ -393,8 +397,10 @@ void ImageManager::device_load_image(Device *device, DeviceScene *dscene, int sl
device_vector<uchar4>& tex_img = dscene->tex_image[slot - tex_image_byte_start];
- if(tex_img.device_pointer)
+ if(tex_img.device_pointer) {
+ thread_scoped_lock device_lock(device_mutex);
device->tex_free(tex_img);
+ }
if(!file_load_image(img, tex_img)) {
/* on failure to load, we set a 1x1 pixels pink image */
@@ -411,8 +417,10 @@ void ImageManager::device_load_image(Device *device, DeviceScene *dscene, int sl
if(slot >= 10) name = string_printf("__tex_image_0%d", slot);
else name = string_printf("__tex_image_00%d", slot);
- if(!pack_images)
+ if(!pack_images) {
+ thread_scoped_lock device_lock(device_mutex);
device->tex_alloc(name.c_str(), tex_img, true, true);
+ }
}
img->need_load = false;
@@ -440,15 +448,27 @@ void ImageManager::device_free_image(Device *device, DeviceScene *dscene, int sl
#endif
}
else if(is_float) {
- device->tex_free(dscene->tex_float_image[slot]);
- dscene->tex_float_image[slot].clear();
+ device_vector<float4>& tex_img = dscene->tex_float_image[slot];
+
+ if(tex_img.device_pointer) {
+ thread_scoped_lock device_lock(device_mutex);
+ device->tex_free(tex_img);
+ }
+
+ tex_img.clear();
delete float_images[slot];
float_images[slot] = NULL;
}
else {
- device->tex_free(dscene->tex_image[slot - tex_image_byte_start]);
- dscene->tex_image[slot - tex_image_byte_start].clear();
+ device_vector<uchar4>& tex_img = dscene->tex_image[slot - tex_image_byte_start];
+
+ if(tex_img.device_pointer) {
+ thread_scoped_lock device_lock(device_mutex);
+ device->tex_free(tex_img);
+ }
+
+ tex_img.clear();
delete images[slot - tex_image_byte_start];
images[slot - tex_image_byte_start] = NULL;
@@ -460,7 +480,7 @@ void ImageManager::device_update(Device *device, DeviceScene *dscene, Progress&
{
if(!need_update)
return;
-
+
TaskPool pool;
for(size_t slot = 0; slot < images.size(); slot++) {
@@ -542,9 +562,9 @@ void ImageManager::device_free(Device *device, DeviceScene *dscene)
device_free_image(device, dscene, slot);
device->tex_free(dscene->tex_image_packed);
- dscene->tex_image_packed.clear();
-
device->tex_free(dscene->tex_image_packed_info);
+
+ dscene->tex_image_packed.clear();
dscene->tex_image_packed_info.clear();
images.clear();
diff --git a/intern/cycles/render/image.h b/intern/cycles/render/image.h
index 04a705c27bf..485bfc5cbf5 100644
--- a/intern/cycles/render/image.h
+++ b/intern/cycles/render/image.h
@@ -22,11 +22,13 @@
#include "device_memory.h"
#include "util_string.h"
+#include "util_thread.h"
#include "util_vector.h"
+#include "kernel_types.h" /* for TEX_NUM_FLOAT_IMAGES */
+
CCL_NAMESPACE_BEGIN
-#define TEX_NUM_FLOAT_IMAGES 5
#define TEX_NUM_IMAGES 95
#define TEX_IMAGE_BYTE_START TEX_NUM_FLOAT_IMAGES
@@ -66,6 +68,7 @@ private:
int tex_num_images;
int tex_num_float_images;
int tex_image_byte_start;
+ thread_mutex device_mutex;
struct Image {
string filename;
diff --git a/intern/cycles/render/integrator.cpp b/intern/cycles/render/integrator.cpp
index da563c9c4ec..699e6979990 100644
--- a/intern/cycles/render/integrator.cpp
+++ b/intern/cycles/render/integrator.cpp
@@ -123,6 +123,8 @@ void Integrator::device_update(Device *device, DeviceScene *dscene, Scene *scene
max_samples *= (max_bounce + transparent_max_bounce + 2);
int dimensions = PRNG_BASE_NUM + max_samples*PRNG_BOUNCE_NUM;
+ dimensions = min(dimensions, SOBOL_MAX_DIMENSIONS);
+
uint *directions = dscene->sobol_directions.resize(SOBOL_BITS*dimensions);
sobol_generate_direction_vectors((uint(*)[SOBOL_BITS])directions, dimensions);
diff --git a/intern/cycles/render/light.cpp b/intern/cycles/render/light.cpp
index 6445c04257f..d77516a1b18 100644
--- a/intern/cycles/render/light.cpp
+++ b/intern/cycles/render/light.cpp
@@ -67,15 +67,16 @@ static void dump_background_pixels(Device *device, DeviceScene *dscene, int res,
main_task.shader_x = 0;
main_task.shader_w = width*height;
+ /* disabled splitting for now, there's an issue with multi-GPU mem_copy_from */
list<DeviceTask> split_tasks;
- main_task.split_max_size(split_tasks, 128*128);
+ main_task.split_max_size(split_tasks, 128*128);
foreach(DeviceTask& task, split_tasks) {
device->task_add(task);
device->task_wait();
+ device->mem_copy_from(d_output, task.shader_x, 1, task.shader_w, sizeof(float4));
}
- device->mem_copy_from(d_output, 0, 1, d_output.size(), sizeof(float4));
device->mem_free(d_input);
device->mem_free(d_output);
diff --git a/intern/cycles/render/mesh.cpp b/intern/cycles/render/mesh.cpp
index 7037e36f313..14f23992664 100644
--- a/intern/cycles/render/mesh.cpp
+++ b/intern/cycles/render/mesh.cpp
@@ -19,6 +19,7 @@
#include "bvh.h"
#include "bvh_build.h"
+#include "camera.h"
#include "device.h"
#include "shader.h"
#include "light.h"
@@ -354,6 +355,9 @@ void MeshManager::update_osl_attributes(Device *device, Scene *scene, vector<Att
/* set object attributes */
foreach(AttributeRequest& req, attributes.requests) {
+ if(req.element == ATTR_ELEMENT_NONE)
+ continue;
+
OSLGlobals::Attribute osl_attr;
osl_attr.elem = req.element;
@@ -365,8 +369,8 @@ void MeshManager::update_osl_attributes(Device *device, Scene *scene, vector<Att
osl_attr.type = TypeDesc::TypeColor;
if(req.std != ATTR_STD_NONE) {
- /* if standard attribute, add lookup by std:: name convention */
- ustring stdname(std::string("std::") + std::string(attribute_standard_name(req.std)));
+ /* if standard attribute, add lookup by geom: name convention */
+ ustring stdname(string("geom:") + string(attribute_standard_name(req.std)));
og->attribute_map[i][stdname] = osl_attr;
}
else if(req.name != ustring()) {
@@ -722,10 +726,16 @@ void MeshManager::device_update(Device *device, DeviceScene *dscene, Scene *scen
foreach(Shader *shader, scene->shaders)
shader->need_update_attributes = false;
- bool motion_blur = scene->need_motion() == Scene::MOTION_BLUR;
+ float shuttertime = scene->camera->shuttertime;
+#ifdef __OBJECT_MOTION__
+ Scene::MotionType need_motion = scene->need_motion(device->info.advanced_shading);
+ bool motion_blur = need_motion == Scene::MOTION_BLUR;
+#else
+ bool motion_blur = false;
+#endif
foreach(Object *object, scene->objects)
- object->compute_bounds(motion_blur);
+ object->compute_bounds(motion_blur, shuttertime);
if(progress.get_cancel()) return;
diff --git a/intern/cycles/render/nodes.cpp b/intern/cycles/render/nodes.cpp
index 1f03ab4e347..d7bf71337f6 100644
--- a/intern/cycles/render/nodes.cpp
+++ b/intern/cycles/render/nodes.cpp
@@ -225,6 +225,8 @@ void ImageTextureNode::compile(OSLCompiler& compiler)
compiler.parameter("color_space", "Linear");
else
compiler.parameter("color_space", "sRGB");
+ compiler.parameter("projection", projection);
+ compiler.parameter("projection_blend", projection_blend);
compiler.add(this, "node_image_texture");
}
@@ -1021,7 +1023,7 @@ void NormalNode::compile(SVMCompiler& compiler)
void NormalNode::compile(OSLCompiler& compiler)
{
- compiler.parameter_vector("Direction", direction);
+ compiler.parameter_normal("Direction", direction);
compiler.add(this, "node_normal");
}
@@ -1065,6 +1067,8 @@ ConvertNode::ConvertNode(ShaderSocketType from_, ShaderSocketType to_)
if(from == SHADER_SOCKET_FLOAT)
add_input("Val", SHADER_SOCKET_FLOAT);
+ else if(from == SHADER_SOCKET_INT)
+ add_input("ValInt", SHADER_SOCKET_INT);
else if(from == SHADER_SOCKET_COLOR)
add_input("Color", SHADER_SOCKET_COLOR);
else if(from == SHADER_SOCKET_VECTOR)
@@ -1078,6 +1082,8 @@ ConvertNode::ConvertNode(ShaderSocketType from_, ShaderSocketType to_)
if(to == SHADER_SOCKET_FLOAT)
add_output("Val", SHADER_SOCKET_FLOAT);
+ else if(to == SHADER_SOCKET_INT)
+ add_output("ValInt", SHADER_SOCKET_INT);
else if(to == SHADER_SOCKET_COLOR)
add_output("Color", SHADER_SOCKET_COLOR);
else if(to == SHADER_SOCKET_VECTOR)
@@ -1095,7 +1101,29 @@ void ConvertNode::compile(SVMCompiler& compiler)
ShaderInput *in = inputs[0];
ShaderOutput *out = outputs[0];
- if(to == SHADER_SOCKET_FLOAT) {
+ if(from == SHADER_SOCKET_FLOAT) {
+ compiler.stack_assign(in);
+ compiler.stack_assign(out);
+
+ if(to == SHADER_SOCKET_INT)
+ /* float to int */
+ compiler.add_node(NODE_CONVERT, NODE_CONVERT_FI, in->stack_offset, out->stack_offset);
+ else
+ /* float to float3 */
+ compiler.add_node(NODE_CONVERT, NODE_CONVERT_FV, in->stack_offset, out->stack_offset);
+ }
+ else if(from == SHADER_SOCKET_INT) {
+ compiler.stack_assign(in);
+ compiler.stack_assign(out);
+
+ if(to == SHADER_SOCKET_FLOAT)
+ /* int to float */
+ compiler.add_node(NODE_CONVERT, NODE_CONVERT_IF, in->stack_offset, out->stack_offset);
+ else
+ /* int to vector/point/normal */
+ compiler.add_node(NODE_CONVERT, NODE_CONVERT_IV, in->stack_offset, out->stack_offset);
+ }
+ else if(to == SHADER_SOCKET_FLOAT) {
compiler.stack_assign(in);
compiler.stack_assign(out);
@@ -1106,12 +1134,16 @@ void ConvertNode::compile(SVMCompiler& compiler)
/* vector/point/normal to float */
compiler.add_node(NODE_CONVERT, NODE_CONVERT_VF, in->stack_offset, out->stack_offset);
}
- else if(from == SHADER_SOCKET_FLOAT) {
+ else if(to == SHADER_SOCKET_INT) {
compiler.stack_assign(in);
compiler.stack_assign(out);
- /* float to float3 */
- compiler.add_node(NODE_CONVERT, NODE_CONVERT_FV, in->stack_offset, out->stack_offset);
+ if(from == SHADER_SOCKET_COLOR)
+ /* color to int */
+ compiler.add_node(NODE_CONVERT, NODE_CONVERT_CI, in->stack_offset, out->stack_offset);
+ else
+ /* vector/point/normal to int */
+ compiler.add_node(NODE_CONVERT, NODE_CONVERT_VI, in->stack_offset, out->stack_offset);
}
else {
/* float3 to float3 */
@@ -1134,6 +1166,8 @@ void ConvertNode::compile(OSLCompiler& compiler)
{
if(from == SHADER_SOCKET_FLOAT)
compiler.add(this, "node_convert_from_float");
+ else if(from == SHADER_SOCKET_INT)
+ compiler.add(this, "node_convert_from_int");
else if(from == SHADER_SOCKET_COLOR)
compiler.add(this, "node_convert_from_color");
else if(from == SHADER_SOCKET_VECTOR)
@@ -1175,14 +1209,16 @@ BsdfNode::BsdfNode()
closure = ccl::CLOSURE_BSDF_DIFFUSE_ID;
add_input("Color", SHADER_SOCKET_COLOR, make_float3(0.8f, 0.8f, 0.8f));
- add_input("Normal", SHADER_SOCKET_NORMAL, ShaderInput::NORMAL, true);
+ add_input("Normal", SHADER_SOCKET_NORMAL, ShaderInput::NORMAL);
add_output("BSDF", SHADER_SOCKET_CLOSURE);
}
-void BsdfNode::compile(SVMCompiler& compiler, ShaderInput *param1, ShaderInput *param2)
+void BsdfNode::compile(SVMCompiler& compiler, ShaderInput *param1, ShaderInput *param2, ShaderInput *param3)
{
ShaderInput *color_in = input("Color");
+ ShaderInput *normal_in = input("Normal");
+ ShaderInput *tangent_in = input("Tangent");
if(color_in->link) {
compiler.stack_assign(color_in);
@@ -1195,6 +1231,14 @@ void BsdfNode::compile(SVMCompiler& compiler, ShaderInput *param1, ShaderInput *
compiler.stack_assign(param1);
if(param2)
compiler.stack_assign(param2);
+ if(param3)
+ compiler.stack_assign(param3);
+
+ if(normal_in->link)
+ compiler.stack_assign(normal_in);
+
+ if(tangent_in && tangent_in->link)
+ compiler.stack_assign(tangent_in);
compiler.add_node(NODE_CLOSURE_BSDF,
compiler.encode_uchar4(closure,
@@ -1203,6 +1247,14 @@ void BsdfNode::compile(SVMCompiler& compiler, ShaderInput *param1, ShaderInput *
compiler.closure_mix_weight_offset()),
__float_as_int((param1)? param1->value.x: 0.0f),
__float_as_int((param2)? param2->value.x: 0.0f));
+
+ if(tangent_in) {
+ compiler.add_node(NODE_CLOSURE_BSDF, normal_in->stack_offset, tangent_in->stack_offset,
+ (param3)? param3->stack_offset: SVM_STACK_INVALID);
+ }
+ else {
+ compiler.add_node(NODE_CLOSURE_BSDF, normal_in->stack_offset);
+ }
}
void BsdfNode::compile(SVMCompiler& compiler)
@@ -1221,13 +1273,28 @@ WardBsdfNode::WardBsdfNode()
{
closure = CLOSURE_BSDF_WARD_ID;
- add_input("Roughness U", SHADER_SOCKET_FLOAT, 0.2f);
- add_input("Roughness V", SHADER_SOCKET_FLOAT, 0.2f);
+ add_input("Tangent", SHADER_SOCKET_VECTOR, ShaderInput::TANGENT);
+
+ add_input("Roughness", SHADER_SOCKET_FLOAT, 0.2f);
+ add_input("Anisotropy", SHADER_SOCKET_FLOAT, 0.5f);
+ add_input("Rotation", SHADER_SOCKET_FLOAT, 0.0f);
+}
+
+void WardBsdfNode::attributes(AttributeRequestSet *attributes)
+{
+ ShaderInput *tangent_in = input("Tangent");
+
+ if(!tangent_in->link) {
+ attributes->add(ATTR_STD_TANGENT);
+ attributes->add(ATTR_STD_GENERATED);
+ }
+
+ ShaderNode::attributes(attributes);
}
void WardBsdfNode::compile(SVMCompiler& compiler)
{
- BsdfNode::compile(compiler, input("Roughness U"), input("Roughness V"));
+ BsdfNode::compile(compiler, input("Roughness"), input("Anisotropy"), input("Rotation"));
}
void WardBsdfNode::compile(OSLCompiler& compiler)
@@ -1566,6 +1633,16 @@ GeometryNode::GeometryNode()
add_output("Backfacing", SHADER_SOCKET_FLOAT);
}
+void GeometryNode::attributes(AttributeRequestSet *attributes)
+{
+ if(!output("Tangent")->links.empty()) {
+ attributes->add(ATTR_STD_TANGENT);
+ attributes->add(ATTR_STD_GENERATED);
+ }
+
+ ShaderNode::attributes(attributes);
+}
+
void GeometryNode::compile(SVMCompiler& compiler)
{
ShaderOutput *out;
@@ -1636,7 +1713,7 @@ void GeometryNode::compile(OSLCompiler& compiler)
TextureCoordinateNode::TextureCoordinateNode()
: ShaderNode("texture_coordinate")
{
- add_input("Normal", SHADER_SOCKET_NORMAL, ShaderInput::NORMAL, true);
+ add_input("NormalIn", SHADER_SOCKET_NORMAL, ShaderInput::NORMAL, true);
add_output("Generated", SHADER_SOCKET_POINT);
add_output("Normal", SHADER_SOCKET_NORMAL);
add_output("UV", SHADER_SOCKET_POINT);
@@ -1644,14 +1721,18 @@ TextureCoordinateNode::TextureCoordinateNode()
add_output("Camera", SHADER_SOCKET_POINT);
add_output("Window", SHADER_SOCKET_POINT);
add_output("Reflection", SHADER_SOCKET_NORMAL);
+
+ from_dupli = false;
}
void TextureCoordinateNode::attributes(AttributeRequestSet *attributes)
{
- if(!output("Generated")->links.empty())
- attributes->add(ATTR_STD_GENERATED);
- if(!output("UV")->links.empty())
- attributes->add(ATTR_STD_UV);
+ if(!from_dupli) {
+ if(!output("Generated")->links.empty())
+ attributes->add(ATTR_STD_GENERATED);
+ if(!output("UV")->links.empty())
+ attributes->add(ATTR_STD_UV);
+ }
ShaderNode::attributes(attributes);
}
@@ -1681,9 +1762,15 @@ void TextureCoordinateNode::compile(SVMCompiler& compiler)
compiler.add_node(geom_node, NODE_GEOM_P, out->stack_offset);
}
else {
- int attr = compiler.attribute(ATTR_STD_GENERATED);
- compiler.stack_assign(out);
- compiler.add_node(attr_node, attr, out->stack_offset, NODE_ATTR_FLOAT3);
+ if(from_dupli) {
+ compiler.stack_assign(out);
+ compiler.add_node(texco_node, NODE_TEXCO_DUPLI_GENERATED, out->stack_offset);
+ }
+ else {
+ int attr = compiler.attribute(ATTR_STD_GENERATED);
+ compiler.stack_assign(out);
+ compiler.add_node(attr_node, attr, out->stack_offset, NODE_ATTR_FLOAT3);
+ }
}
}
@@ -1695,9 +1782,15 @@ void TextureCoordinateNode::compile(SVMCompiler& compiler)
out = output("UV");
if(!out->links.empty()) {
- int attr = compiler.attribute(ATTR_STD_UV);
- compiler.stack_assign(out);
- compiler.add_node(attr_node, attr, out->stack_offset, NODE_ATTR_FLOAT3);
+ if(from_dupli) {
+ compiler.stack_assign(out);
+ compiler.add_node(texco_node, NODE_TEXCO_DUPLI_UV, out->stack_offset);
+ }
+ else {
+ int attr = compiler.attribute(ATTR_STD_UV);
+ compiler.stack_assign(out);
+ compiler.add_node(attr_node, attr, out->stack_offset, NODE_ATTR_FLOAT3);
+ }
}
out = output("Object");
@@ -1742,6 +1835,8 @@ void TextureCoordinateNode::compile(OSLCompiler& compiler)
if(compiler.background)
compiler.parameter("is_background", true);
+
+ compiler.parameter("from_dupli", from_dupli);
compiler.add(this, "node_texture_coordinate");
}
@@ -2168,7 +2263,7 @@ static ShaderEnum mix_type_init()
enm.insert("Burn", NODE_MIX_BURN);
enm.insert("Hue", NODE_MIX_HUE);
enm.insert("Saturation", NODE_MIX_SAT);
- enm.insert("Value", NODE_MIX_VAL );
+ enm.insert("Value", NODE_MIX_VAL);
enm.insert("Color", NODE_MIX_COLOR);
enm.insert("Soft Light", NODE_MIX_SOFT);
enm.insert("Linear Light", NODE_MIX_LINEAR);
@@ -2528,7 +2623,7 @@ void LayerWeightNode::compile(SVMCompiler& compiler)
void LayerWeightNode::compile(OSLCompiler& compiler)
{
- compiler.add(this, "node_blend_weight");
+ compiler.add(this, "node_layer_weight");
}
/* Output */
@@ -2539,6 +2634,7 @@ OutputNode::OutputNode()
add_input("Surface", SHADER_SOCKET_CLOSURE);
add_input("Volume", SHADER_SOCKET_CLOSURE);
add_input("Displacement", SHADER_SOCKET_FLOAT);
+ add_input("Normal", SHADER_SOCKET_NORMAL);
}
void OutputNode::compile(SVMCompiler& compiler)
@@ -2686,9 +2782,15 @@ void VectorMathNode::compile(OSLCompiler& compiler)
BumpNode::BumpNode()
: ShaderNode("bump")
{
+ /* this input is used by the user, but after graph transform it is no longer
+ * used and moved to sampler center/x/y instead */
+ add_input("Height", SHADER_SOCKET_FLOAT);
+
add_input("SampleCenter", SHADER_SOCKET_FLOAT);
add_input("SampleX", SHADER_SOCKET_FLOAT);
add_input("SampleY", SHADER_SOCKET_FLOAT);
+ add_input("NormalIn", SHADER_SOCKET_NORMAL, ShaderInput::NORMAL);
+ add_input("Strength", SHADER_SOCKET_FLOAT, 0.1f);
add_output("Normal", SHADER_SOCKET_NORMAL);
}
@@ -2698,12 +2800,25 @@ void BumpNode::compile(SVMCompiler& compiler)
ShaderInput *center_in = input("SampleCenter");
ShaderInput *dx_in = input("SampleX");
ShaderInput *dy_in = input("SampleY");
+ ShaderInput *normal_in = input("NormalIn");
+ ShaderInput *intensity_in = input("Strength");
+ ShaderOutput *normal_out = output("Normal");
compiler.stack_assign(center_in);
compiler.stack_assign(dx_in);
compiler.stack_assign(dy_in);
+ compiler.stack_assign(intensity_in);
+ compiler.stack_assign(normal_out);
- compiler.add_node(NODE_SET_BUMP, center_in->stack_offset, dx_in->stack_offset, dy_in->stack_offset);
+ if(normal_in->link)
+ compiler.stack_assign(normal_in);
+
+ /* pack all parameters in the node */
+ compiler.add_node(NODE_SET_BUMP,
+ normal_in->stack_offset,
+ compiler.encode_uchar4(center_in->stack_offset, dx_in->stack_offset,
+ dy_in->stack_offset, intensity_in->stack_offset),
+ normal_out->stack_offset);
}
void BumpNode::compile(OSLCompiler& compiler)
@@ -2768,8 +2883,68 @@ void RGBRampNode::compile(SVMCompiler& compiler)
void RGBRampNode::compile(OSLCompiler& compiler)
{
+ /* OSL shader only takes separate RGB and A array, split the RGBA base array */
+ /* NB: cycles float3 type is actually 4 floats! need to use an explicit array */
+ float ramp_color[RAMP_TABLE_SIZE][3];
+ float ramp_alpha[RAMP_TABLE_SIZE];
+
+ for (int i = 0; i < RAMP_TABLE_SIZE; ++i) {
+ ramp_color[i][0] = ramp[i].x;
+ ramp_color[i][1] = ramp[i].y;
+ ramp_color[i][2] = ramp[i].z;
+ ramp_alpha[i] = ramp[i].w;
+ }
+
+ compiler.parameter_color_array("ramp_color", ramp_color, RAMP_TABLE_SIZE);
+ compiler.parameter_array("ramp_alpha", ramp_alpha, RAMP_TABLE_SIZE);
+
compiler.add(this, "node_rgb_ramp");
}
+/* Set Normal Node */
+
+SetNormalNode::SetNormalNode()
+: ShaderNode("set_normal")
+{
+ add_input("Direction", SHADER_SOCKET_VECTOR);
+ add_output("Normal", SHADER_SOCKET_NORMAL);
+}
+
+void SetNormalNode::compile(SVMCompiler& compiler)
+{
+ ShaderInput *direction_in = input("Direction");
+ ShaderOutput *normal_out = output("Normal");
+
+ compiler.stack_assign(direction_in);
+ compiler.stack_assign(normal_out);
+
+ compiler.add_node(NODE_CLOSURE_SET_NORMAL, direction_in->stack_offset, normal_out->stack_offset);
+}
+
+void SetNormalNode::compile(OSLCompiler& compiler)
+{
+ compiler.add(this, "node_set_normal");
+}
+
+/* OSLScriptNode */
+
+OSLScriptNode::OSLScriptNode()
+: ShaderNode("osl_script")
+{
+}
+
+void OSLScriptNode::compile(SVMCompiler& compiler)
+{
+ /* doesn't work for SVM, obviously ... */
+}
+
+void OSLScriptNode::compile(OSLCompiler& compiler)
+{
+ if(!filepath.empty())
+ compiler.add(this, filepath.c_str(), true);
+ else
+ compiler.add(this, bytecode_hash.c_str(), false);
+}
+
CCL_NAMESPACE_END
diff --git a/intern/cycles/render/nodes.h b/intern/cycles/render/nodes.h
index 82bead7e41a..d90cae5f668 100644
--- a/intern/cycles/render/nodes.h
+++ b/intern/cycles/render/nodes.h
@@ -193,7 +193,7 @@ class BsdfNode : public ShaderNode {
public:
SHADER_NODE_CLASS(BsdfNode)
- void compile(SVMCompiler& compiler, ShaderInput *param1, ShaderInput *param2);
+ void compile(SVMCompiler& compiler, ShaderInput *param1, ShaderInput *param2, ShaderInput *param3 = NULL);
ClosureType closure;
};
@@ -201,6 +201,7 @@ public:
class WardBsdfNode : public BsdfNode {
public:
SHADER_NODE_CLASS(WardBsdfNode)
+ void attributes(AttributeRequestSet *attributes);
};
class DiffuseBsdfNode : public BsdfNode {
@@ -278,12 +279,15 @@ public:
class GeometryNode : public ShaderNode {
public:
SHADER_NODE_CLASS(GeometryNode)
+ void attributes(AttributeRequestSet *attributes);
};
class TextureCoordinateNode : public ShaderNode {
public:
SHADER_NODE_CLASS(TextureCoordinateNode)
void attributes(AttributeRequestSet *attributes);
+
+ bool from_dupli;
};
class LightPathNode : public ShaderNode {
@@ -436,6 +440,23 @@ public:
float4 ramp[RAMP_TABLE_SIZE];
};
+class SetNormalNode : public ShaderNode {
+public:
+ SHADER_NODE_CLASS(SetNormalNode)
+};
+
+class OSLScriptNode : public ShaderNode {
+public:
+ SHADER_NODE_CLASS(OSLScriptNode)
+ string filepath;
+ string bytecode_hash;
+
+ /* ShaderInput/ShaderOutput only stores a shallow string copy (const char *)!
+ * The actual socket names have to be stored externally to avoid memory errors. */
+ vector<ustring> input_names;
+ vector<ustring> output_names;
+};
+
CCL_NAMESPACE_END
#endif /* __NODES_H__ */
diff --git a/intern/cycles/render/object.cpp b/intern/cycles/render/object.cpp
index 7389b239627..25b4d1f08cc 100644
--- a/intern/cycles/render/object.cpp
+++ b/intern/cycles/render/object.cpp
@@ -51,20 +51,23 @@ Object::~Object()
{
}
-void Object::compute_bounds(bool motion_blur)
+void Object::compute_bounds(bool motion_blur, float shuttertime)
{
BoundBox mbounds = mesh->bounds;
if(motion_blur && use_motion) {
MotionTransform decomp;
- transform_motion_decompose(&decomp, &motion);
+ transform_motion_decompose(&decomp, &motion, &tfm);
bounds = BoundBox::empty;
/* todo: this is really terrible. according to pbrt there is a better
* way to find this iteratively, but did not find implementation yet
* or try to implement myself */
- for(float t = 0.0f; t < 1.0f; t += 1.0f/128.0f) {
+ float start_t = 0.5f - shuttertime*0.25f;
+ float end_t = 0.5f + shuttertime*0.25f;
+
+ for(float t = start_t; t < end_t; t += (1.0f/128.0f)*shuttertime) {
Transform ttfm;
transform_motion_interpolate(&ttfm, &decomp, t);
@@ -109,7 +112,7 @@ void Object::apply_transform()
if(bounds.valid()) {
mesh->compute_bounds();
- compute_bounds(false);
+ compute_bounds(false, 0.0f);
}
/* tfm is not reset to identity, all code that uses it needs to check the
@@ -151,7 +154,8 @@ void ObjectManager::device_update_transforms(Device *device, DeviceScene *dscene
uint *object_flag = dscene->object_flag.resize(scene->objects.size());
int i = 0;
map<Mesh*, float> surface_area_map;
- Scene::MotionType need_motion = scene->need_motion();
+ Scene::MotionType need_motion = scene->need_motion(device->info.advanced_shading);
+ bool have_motion = false;
foreach(Object *ob, scene->objects) {
Mesh *mesh = ob->mesh;
@@ -218,22 +222,29 @@ void ObjectManager::device_update_transforms(Device *device, DeviceScene *dscene
mtfm_post = mtfm_post * itfm;
memcpy(&objects[offset+8], &mtfm_pre, sizeof(float4)*4);
- memcpy(&objects[offset+12], &mtfm_post, sizeof(float4)*4);
+ memcpy(&objects[offset+16], &mtfm_post, sizeof(float4)*4);
}
+#ifdef __OBJECT_MOTION__
else if(need_motion == Scene::MOTION_BLUR) {
if(ob->use_motion) {
/* decompose transformations for interpolation */
MotionTransform decomp;
- transform_motion_decompose(&decomp, &ob->motion);
- memcpy(&objects[offset+8], &decomp, sizeof(float4)*8);
+ transform_motion_decompose(&decomp, &ob->motion, &ob->tfm);
+ memcpy(&objects[offset+8], &decomp, sizeof(float4)*12);
flag |= SD_OBJECT_MOTION;
+ have_motion = true;
}
else {
float4 no_motion = make_float4(FLT_MAX);
- memcpy(&objects[offset+8], &no_motion, sizeof(float4));
+ memcpy(&objects[offset+8], &no_motion, sizeof(float4)*12);
}
}
+#endif
+
+ /* dupli object coords */
+ objects[offset+20] = make_float4(ob->dupli_generated[0], ob->dupli_generated[1], ob->dupli_generated[2], 0.0f);
+ objects[offset+21] = make_float4(ob->dupli_uv[0], ob->dupli_uv[1], 0.0f, 0.0f);
/* object flag */
if(ob->use_holdout)
@@ -247,6 +258,8 @@ void ObjectManager::device_update_transforms(Device *device, DeviceScene *dscene
device->tex_alloc("__objects", dscene->objects);
device->tex_alloc("__object_flag", dscene->object_flag);
+
+ dscene->data.bvh.have_motion = have_motion;
}
void ObjectManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
@@ -293,7 +306,12 @@ void ObjectManager::apply_static_transforms(Scene *scene, Progress& progress)
/* counter mesh users */
map<Mesh*, int> mesh_users;
- bool motion_blur = scene->need_motion() == Scene::MOTION_BLUR;
+#ifdef __OBJECT_MOTION__
+ Scene::MotionType need_motion = scene->need_motion();
+ bool motion_blur = need_motion == Scene::MOTION_BLUR;
+#else
+ bool motion_blur = false;
+#endif
foreach(Object *object, scene->objects) {
map<Mesh*, int>::iterator it = mesh_users.find(object->mesh);
diff --git a/intern/cycles/render/object.h b/intern/cycles/render/object.h
index 88677d79dff..922c886d961 100644
--- a/intern/cycles/render/object.h
+++ b/intern/cycles/render/object.h
@@ -49,6 +49,9 @@ public:
bool use_motion;
bool use_holdout;
+ float3 dupli_generated;
+ float2 dupli_uv;
+
int particle_id;
Object();
@@ -56,7 +59,7 @@ public:
void tag_update(Scene *scene);
- void compute_bounds(bool motion_blur);
+ void compute_bounds(bool motion_blur, float shuttertime);
void apply_transform();
};
diff --git a/intern/cycles/render/osl.cpp b/intern/cycles/render/osl.cpp
index dbd6b0ac9d9..a8a40a4e596 100644
--- a/intern/cycles/render/osl.cpp
+++ b/intern/cycles/render/osl.cpp
@@ -31,6 +31,7 @@
#include "osl_shader.h"
#include "util_foreach.h"
+#include "util_md5.h"
#include "util_path.h"
#include "util_progress.h"
@@ -46,20 +47,8 @@ OSLShaderManager::OSLShaderManager()
{
services = new OSLRenderServices();
- /* if we let OSL create it, it leaks */
- ts = TextureSystem::create(true);
- ts->attribute("automip", 1);
- ts->attribute("autotile", 64);
-
- ss = OSL::ShadingSystem::create(services, ts, &errhandler);
- ss->attribute("lockgeom", 1);
- ss->attribute("commonspace", "world");
- ss->attribute("optimize", 2);
- //ss->attribute("debug", 1);
- //ss->attribute("statistics:level", 1);
- ss->attribute("searchpath:shader", path_get("shader").c_str());
-
- OSLShader::register_closures(ss);
+ shading_system_init();
+ texture_system_init();
}
OSLShaderManager::~OSLShaderManager()
@@ -71,18 +60,14 @@ OSLShaderManager::~OSLShaderManager()
void OSLShaderManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
{
- /* test if we need to update */
- bool need_update = false;
-
- foreach(Shader *shader, scene->shaders)
- if(shader->need_update)
- need_update = true;
-
if(!need_update)
return;
device_free(device, dscene);
+ /* determine which shaders are in use */
+ device_update_shaders_used(scene);
+
/* create shaders */
OSLGlobals *og = (OSLGlobals*)device->osl_memory();
@@ -94,7 +79,7 @@ void OSLShaderManager::device_update(Device *device, DeviceScene *dscene, Scene
if(shader->sample_as_light && shader->has_surface_emission)
scene->light_manager->need_update = true;
- OSLCompiler compiler((void*)ss);
+ OSLCompiler compiler((void*)this, (void*)ss);
compiler.background = (shader == scene->shaders[scene->default_background]);
compiler.compile(og, shader);
}
@@ -110,6 +95,8 @@ void OSLShaderManager::device_update(Device *device, DeviceScene *dscene, Scene
foreach(Shader *shader, scene->shaders)
shader->need_update = false;
+
+ need_update = false;
/* set texture system */
scene->image_manager->set_osl_texture_system((void*)ts);
@@ -135,10 +122,165 @@ void OSLShaderManager::device_free(Device *device, DeviceScene *dscene)
og->background_state.reset();
}
+void OSLShaderManager::texture_system_init()
+{
+ /* if we let OSL create it, it leaks */
+ ts = TextureSystem::create(true);
+ ts->attribute("automip", 1);
+ ts->attribute("autotile", 64);
+
+ /* effectively unlimited for now, until we support proper mipmap lookups */
+ ts->attribute("max_memory_MB", 16384);
+}
+
+void OSLShaderManager::shading_system_init()
+{
+ ss = OSL::ShadingSystem::create(services, ts, &errhandler);
+ ss->attribute("lockgeom", 1);
+ ss->attribute("commonspace", "world");
+ ss->attribute("optimize", 2);
+ //ss->attribute("debug", 1);
+ //ss->attribute("statistics:level", 1);
+ ss->attribute("searchpath:shader", path_get("shader"));
+
+ /* our own ray types */
+ static const char *raytypes[] = {
+ "camera", /* PATH_RAY_CAMERA */
+ "reflection", /* PATH_RAY_REFLECT */
+ "refraction", /* PATH_RAY_TRANSMIT */
+ "diffuse", /* PATH_RAY_DIFFUSE */
+ "glossy", /* PATH_RAY_GLOSSY */
+ "singular", /* PATH_RAY_SINGULAR */
+ "transparent", /* PATH_RAY_TRANSPARENT */
+ "shadow", /* PATH_RAY_SHADOW_OPAQUE */
+ "shadow", /* PATH_RAY_SHADOW_TRANSPARENT */
+ };
+
+ const int nraytypes = sizeof(raytypes)/sizeof(raytypes[0]);
+ ss->attribute("raytypes", TypeDesc(TypeDesc::STRING, nraytypes), raytypes);
+
+ OSLShader::register_closures(ss);
+
+ loaded_shaders.clear();
+}
+
+bool OSLShaderManager::osl_compile(const string& inputfile, const string& outputfile)
+{
+ vector<string> options;
+ string stdosl_path;
+
+ /* specify output file name */
+ options.push_back("-o");
+ options.push_back(outputfile);
+
+ /* specify standard include path */
+ options.push_back("-I" + path_get("shader"));
+ stdosl_path = path_get("shader/stdosl.h");
+
+ /* compile */
+ OSL::OSLCompiler *compiler = OSL::OSLCompiler::create();
+ bool ok = compiler->compile(inputfile, options, stdosl_path);
+ delete compiler;
+
+ return ok;
+}
+
+bool OSLShaderManager::osl_query(OSL::OSLQuery& query, const string& filepath)
+{
+ string searchpath = path_user_get("shaders");
+ return query.open(filepath, searchpath);
+}
+
+static string shader_filepath_hash(const string& filepath, uint64_t modified_time)
+{
+ /* compute a hash from filepath and modified time to detect changes */
+ MD5Hash md5;
+ md5.append((const uint8_t*)filepath.c_str(), filepath.size());
+ md5.append((const uint8_t*)&modified_time, sizeof(modified_time));
+
+ return md5.get_hex();
+}
+
+const char *OSLShaderManager::shader_test_loaded(const string& hash)
+{
+ set<string>::iterator it = loaded_shaders.find(hash);
+ return (it == loaded_shaders.end())? NULL: it->c_str();
+}
+
+const char *OSLShaderManager::shader_load_filepath(string filepath)
+{
+ size_t len = filepath.size();
+ string extension = filepath.substr(len - 4);
+ uint64_t modified_time = path_modified_time(filepath);
+
+ if(extension == ".osl") {
+ /* .OSL File */
+ string osopath = filepath.substr(0, len - 4) + ".oso";
+ uint64_t oso_modified_time = path_modified_time(osopath);
+
+ /* test if we have loaded the corresponding .OSO already */
+ if(oso_modified_time != 0) {
+ const char *hash = shader_test_loaded(shader_filepath_hash(osopath, oso_modified_time));
+
+ if(hash)
+ return hash;
+ }
+
+ /* autocompile .OSL to .OSO if needed */
+ if(oso_modified_time == 0 || (oso_modified_time < modified_time)) {
+ OSLShaderManager::osl_compile(filepath, osopath);
+ modified_time = path_modified_time(osopath);
+ }
+ else
+ modified_time = oso_modified_time;
+
+ filepath = osopath;
+ }
+ else {
+ if(extension == ".oso") {
+ /* .OSO File, nothing to do */
+ }
+ else if(path_dirname(filepath) == "") {
+ /* .OSO File in search path */
+ filepath = path_join(path_user_get("shaders"), filepath + ".oso");
+ }
+ else {
+ /* unknown file */
+ return NULL;
+ }
+
+ /* test if we have loaded this .OSO already */
+ const char *hash = shader_test_loaded(shader_filepath_hash(filepath, modified_time));
+
+ if(hash)
+ return hash;
+ }
+
+ /* read oso bytecode from file */
+ string bytecode_hash = shader_filepath_hash(filepath, modified_time);
+ string bytecode;
+
+ if(!path_read_text(filepath, bytecode)) {
+ fprintf(stderr, "Cycles shader graph: failed to read file %s\n", filepath.c_str());
+ loaded_shaders.insert(bytecode_hash); /* to avoid repeat tries */
+ return NULL;
+ }
+
+ return shader_load_bytecode(bytecode_hash, bytecode);
+}
+
+const char *OSLShaderManager::shader_load_bytecode(const string& hash, const string& bytecode)
+{
+ ss->LoadMemoryShader(hash.c_str(), bytecode.c_str());
+
+ return loaded_shaders.insert(hash).first->c_str();
+}
+
/* Graph Compiler */
-OSLCompiler::OSLCompiler(void *shadingsys_)
+OSLCompiler::OSLCompiler(void *manager_, void *shadingsys_)
{
+ manager = manager_;
shadingsys = shadingsys_;
current_type = SHADER_TYPE_SURFACE;
current_shader = NULL;
@@ -154,14 +296,43 @@ string OSLCompiler::id(ShaderNode *node)
return stream.str();
}
-string OSLCompiler::compatible_name(const char *name)
+string OSLCompiler::compatible_name(ShaderNode *node, ShaderInput *input)
+{
+ string sname(input->name);
+ size_t i;
+
+ /* strip whitespace */
+ while((i = sname.find(" ")) != string::npos)
+ sname.replace(i, 1, "");
+
+ /* if output exists with the same name, add "In" suffix */
+ foreach(ShaderOutput *output, node->outputs) {
+ if (strcmp(input->name, output->name)==0) {
+ sname += "In";
+ break;
+ }
+ }
+
+ return sname;
+}
+
+string OSLCompiler::compatible_name(ShaderNode *node, ShaderOutput *output)
{
- string sname = name;
+ string sname(output->name);
size_t i;
+ /* strip whitespace */
while((i = sname.find(" ")) != string::npos)
sname.replace(i, 1, "");
+ /* if output exists with the same name, add "In" suffix */
+ foreach(ShaderInput *input, node->inputs) {
+ if (strcmp(input->name, output->name)==0) {
+ sname += "Out";
+ break;
+ }
+ }
+
return sname;
}
@@ -177,6 +348,12 @@ bool OSLCompiler::node_skip_input(ShaderNode *node, ShaderInput *input)
return true;
if(strcmp(input->name, "Displacement") == 0 && current_type != SHADER_TYPE_DISPLACEMENT)
return true;
+ if(strcmp(input->name, "Normal") == 0)
+ return true;
+ }
+ else if(node->name == ustring("bump")) {
+ if(strcmp(input->name, "Height") == 0)
+ return true;
}
else if(current_type == SHADER_TYPE_DISPLACEMENT && input->link && input->link->parent->name == ustring("bump"))
return true;
@@ -184,10 +361,18 @@ bool OSLCompiler::node_skip_input(ShaderNode *node, ShaderInput *input)
return false;
}
-void OSLCompiler::add(ShaderNode *node, const char *name)
+void OSLCompiler::add(ShaderNode *node, const char *name, bool isfilepath)
{
OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
+ /* load filepath */
+ if(isfilepath) {
+ name = ((OSLShaderManager*)manager)->shader_load_filepath(name);
+
+ if(name == NULL)
+ return;
+ }
+
/* pass in fixed parameter values */
foreach(ShaderInput *input, node->inputs) {
if(!input->link) {
@@ -198,21 +383,25 @@ void OSLCompiler::add(ShaderNode *node, const char *name)
else if(input->default_value != ShaderInput::NONE)
continue;
+ string param_name = compatible_name(node, input);
switch(input->type) {
case SHADER_SOCKET_COLOR:
- parameter_color(compatible_name(input->name).c_str(), input->value);
+ parameter_color(param_name.c_str(), input->value);
break;
case SHADER_SOCKET_POINT:
- parameter_point(compatible_name(input->name).c_str(), input->value);
+ parameter_point(param_name.c_str(), input->value);
break;
case SHADER_SOCKET_VECTOR:
- parameter_vector(compatible_name(input->name).c_str(), input->value);
+ parameter_vector(param_name.c_str(), input->value);
break;
case SHADER_SOCKET_NORMAL:
- parameter_normal(compatible_name(input->name).c_str(), input->value);
+ parameter_normal(param_name.c_str(), input->value);
break;
case SHADER_SOCKET_FLOAT:
- parameter(compatible_name(input->name).c_str(), input->value.x);
+ parameter(param_name.c_str(), input->value.x);
+ break;
+ case SHADER_SOCKET_INT:
+ parameter(param_name.c_str(), (int)input->value.x);
break;
case SHADER_SOCKET_CLOSURE:
break;
@@ -242,12 +431,8 @@ void OSLCompiler::add(ShaderNode *node, const char *name)
/* connect shaders */
string id_from = id(input->link->parent);
string id_to = id(node);
- string param_from = compatible_name(input->link->name);
- string param_to = compatible_name(input->name);
-
- /* avoid name conflict with same input/output socket name */
- if(input->link->parent->input(input->link->name))
- param_from += "_";
+ string param_from = compatible_name(input->link->parent, input->link);
+ string param_to = compatible_name(node, input);
ss->ConnectShaders(id_from.c_str(), param_from.c_str(), id_to.c_str(), param_to.c_str());
}
@@ -309,6 +494,70 @@ void OSLCompiler::parameter(const char *name, const Transform& tfm)
ss->Parameter(name, TypeDesc::TypeMatrix, (float*)&tfm);
}
+void OSLCompiler::parameter_array(const char *name, const float f[], int arraylen)
+{
+ OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
+ TypeDesc type = TypeDesc::TypeFloat;
+ type.arraylen = arraylen;
+ ss->Parameter(name, type, f);
+}
+
+void OSLCompiler::parameter_color_array(const char *name, const float f[][3], int arraylen)
+{
+ OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
+ TypeDesc type = TypeDesc::TypeColor;
+ type.arraylen = arraylen;
+ ss->Parameter(name, type, f);
+}
+
+void OSLCompiler::parameter_vector_array(const char *name, const float f[][3], int arraylen)
+{
+ OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
+ TypeDesc type = TypeDesc::TypeVector;
+ type.arraylen = arraylen;
+ ss->Parameter(name, type, f);
+}
+
+void OSLCompiler::parameter_normal_array(const char *name, const float f[][3], int arraylen)
+{
+ OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
+ TypeDesc type = TypeDesc::TypeNormal;
+ type.arraylen = arraylen;
+ ss->Parameter(name, type, f);
+}
+
+void OSLCompiler::parameter_point_array(const char *name, const float f[][3], int arraylen)
+{
+ OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
+ TypeDesc type = TypeDesc::TypePoint;
+ type.arraylen = arraylen;
+ ss->Parameter(name, type, f);
+}
+
+void OSLCompiler::parameter_array(const char *name, const int f[], int arraylen)
+{
+ OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
+ TypeDesc type = TypeDesc::TypeInt;
+ type.arraylen = arraylen;
+ ss->Parameter(name, type, f);
+}
+
+void OSLCompiler::parameter_array(const char *name, const char * const s[], int arraylen)
+{
+ OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
+ TypeDesc type = TypeDesc::TypeString;
+ type.arraylen = arraylen;
+ ss->Parameter(name, type, s);
+}
+
+void OSLCompiler::parameter_array(const char *name, const Transform tfm[], int arraylen)
+{
+ OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
+ TypeDesc type = TypeDesc::TypeMatrix;
+ type.arraylen = arraylen;
+ ss->Parameter(name, type, (const float *)tfm);
+}
+
void OSLCompiler::find_dependencies(set<ShaderNode*>& dependencies, ShaderInput *input)
{
ShaderNode *node = (input->link)? input->link->parent: NULL;
@@ -392,82 +641,85 @@ void OSLCompiler::compile_type(Shader *shader, ShaderGraph *graph, ShaderType ty
void OSLCompiler::compile(OSLGlobals *og, Shader *shader)
{
- OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
- ShaderGraph *graph = shader->graph;
- ShaderNode *output = (graph)? graph->output(): NULL;
+ if(shader->need_update) {
+ OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
+ ShaderGraph *graph = shader->graph;
+ ShaderNode *output = (graph)? graph->output(): NULL;
+
+ /* copy graph for shader with bump mapping */
+ if(output->input("Surface")->link && output->input("Displacement")->link)
+ if(!shader->graph_bump)
+ shader->graph_bump = shader->graph->copy();
- /* copy graph for shader with bump mapping */
- if(output->input("Surface")->link && output->input("Displacement")->link)
- if(!shader->graph_bump)
- shader->graph_bump = shader->graph->copy();
+ /* finalize */
+ shader->graph->finalize(false, true);
+ if(shader->graph_bump)
+ shader->graph_bump->finalize(true, true);
- /* finalize */
- shader->graph->finalize(false, true);
- if(shader->graph_bump)
- shader->graph_bump->finalize(true, true);
+ current_shader = shader;
- current_shader = shader;
+ shader->has_surface = false;
+ shader->has_surface_emission = false;
+ shader->has_surface_transparent = false;
+ shader->has_volume = false;
+ shader->has_displacement = false;
- shader->has_surface = false;
- shader->has_surface_emission = false;
- shader->has_surface_transparent = false;
- shader->has_volume = false;
- shader->has_displacement = false;
+ /* generate surface shader */
+ if(shader->used && graph && output->input("Surface")->link) {
+ compile_type(shader, shader->graph, SHADER_TYPE_SURFACE);
+ shader->osl_surface_ref = ss->state();
- /* generate surface shader */
- if(graph && output->input("Surface")->link) {
- compile_type(shader, shader->graph, SHADER_TYPE_SURFACE);
- og->surface_state.push_back(ss->state());
+ if(shader->graph_bump) {
+ ss->clear_state();
+ compile_type(shader, shader->graph_bump, SHADER_TYPE_SURFACE);
+ }
- if(shader->graph_bump) {
+ shader->osl_surface_bump_ref = ss->state();
ss->clear_state();
- compile_type(shader, shader->graph_bump, SHADER_TYPE_SURFACE);
- og->surface_state.push_back(ss->state());
- }
- else
- og->surface_state.push_back(ss->state());
- ss->clear_state();
+ shader->has_surface = true;
+ }
+ else {
+ shader->osl_surface_ref = OSL::ShadingAttribStateRef();
+ shader->osl_surface_bump_ref = OSL::ShadingAttribStateRef();
+ }
- shader->has_surface = true;
- }
- else {
- og->surface_state.push_back(OSL::ShadingAttribStateRef());
- og->surface_state.push_back(OSL::ShadingAttribStateRef());
- }
+ /* generate volume shader */
+ if(shader->used && graph && output->input("Volume")->link) {
+ compile_type(shader, shader->graph, SHADER_TYPE_VOLUME);
+ shader->has_volume = true;
- /* generate volume shader */
- if(graph && output->input("Volume")->link) {
- compile_type(shader, shader->graph, SHADER_TYPE_VOLUME);
- shader->has_volume = true;
+ shader->osl_volume_ref = ss->state();
+ ss->clear_state();
+ }
+ else
+ shader->osl_volume_ref = OSL::ShadingAttribStateRef();
- og->volume_state.push_back(ss->state());
- og->volume_state.push_back(ss->state());
- ss->clear_state();
- }
- else {
- og->volume_state.push_back(OSL::ShadingAttribStateRef());
- og->volume_state.push_back(OSL::ShadingAttribStateRef());
+ /* generate displacement shader */
+ if(shader->used && graph && output->input("Displacement")->link) {
+ compile_type(shader, shader->graph, SHADER_TYPE_DISPLACEMENT);
+ shader->has_displacement = true;
+ shader->osl_displacement_ref = ss->state();
+ ss->clear_state();
+ }
+ else
+ shader->osl_displacement_ref = OSL::ShadingAttribStateRef();
}
- /* generate displacement shader */
- if(graph && output->input("Displacement")->link) {
- compile_type(shader, shader->graph, SHADER_TYPE_DISPLACEMENT);
- shader->has_displacement = true;
+ /* push state to array for lookup */
+ og->surface_state.push_back(shader->osl_surface_ref);
+ og->surface_state.push_back(shader->osl_surface_bump_ref);
- og->displacement_state.push_back(ss->state());
- og->displacement_state.push_back(ss->state());
- ss->clear_state();
- }
- else {
- og->displacement_state.push_back(OSL::ShadingAttribStateRef());
- og->displacement_state.push_back(OSL::ShadingAttribStateRef());
- }
+ og->volume_state.push_back(shader->osl_volume_ref);
+ og->volume_state.push_back(shader->osl_volume_ref);
+
+ og->displacement_state.push_back(shader->osl_displacement_ref);
+ og->displacement_state.push_back(shader->osl_displacement_ref);
}
#else
-void OSLCompiler::add(ShaderNode *node, const char *name)
+void OSLCompiler::add(ShaderNode *node, const char *name, bool isfilepath)
{
}
@@ -483,6 +735,14 @@ void OSLCompiler::parameter_vector(const char *name, float3 f)
{
}
+void OSLCompiler::parameter_point(const char *name, float3 f)
+{
+}
+
+void OSLCompiler::parameter_normal(const char *name, float3 f)
+{
+}
+
void OSLCompiler::parameter(const char *name, int f)
{
}
@@ -499,6 +759,38 @@ void OSLCompiler::parameter(const char *name, const Transform& tfm)
{
}
+void OSLCompiler::parameter_array(const char *name, const float f[], int arraylen)
+{
+}
+
+void OSLCompiler::parameter_color_array(const char *name, const float f[][3], int arraylen)
+{
+}
+
+void OSLCompiler::parameter_vector_array(const char *name, const float f[][3], int arraylen)
+{
+}
+
+void OSLCompiler::parameter_normal_array(const char *name, const float f[][3], int arraylen)
+{
+}
+
+void OSLCompiler::parameter_point_array(const char *name, const float f[][3], int arraylen)
+{
+}
+
+void OSLCompiler::parameter_array(const char *name, const int f[], int arraylen)
+{
+}
+
+void OSLCompiler::parameter_array(const char *name, const char * const s[], int arraylen)
+{
+}
+
+void OSLCompiler::parameter_array(const char *name, const Transform tfm[], int arraylen)
+{
+}
+
#endif /* WITH_OSL */
CCL_NAMESPACE_END
diff --git a/intern/cycles/render/osl.h b/intern/cycles/render/osl.h
index 329cf9a4828..cee37c58d74 100644
--- a/intern/cycles/render/osl.h
+++ b/intern/cycles/render/osl.h
@@ -20,11 +20,14 @@
#define __OSL_H__
#include "util_set.h"
+#include "util_string.h"
#include "shader.h"
#ifdef WITH_OSL
+#include <OSL/oslcomp.h>
#include <OSL/oslexec.h>
+#include <OSL/oslquery.h>
#endif
CCL_NAMESPACE_BEGIN
@@ -37,6 +40,7 @@ class OSLGlobals;
class Scene;
class ShaderGraph;
class ShaderNode;
+class ShaderInput;
class ShaderOutput;
#ifdef WITH_OSL
@@ -51,11 +55,24 @@ public:
void device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress);
void device_free(Device *device, DeviceScene *dscene);
-private:
+ /* osl compile and query */
+ static bool osl_compile(const string& inputfile, const string& outputfile);
+ static bool osl_query(OSL::OSLQuery& query, const string& filepath);
+
+ /* shader file loading, all functions return pointer to hash string if found */
+ const char *shader_test_loaded(const string& hash);
+ const char *shader_load_bytecode(const string& hash, const string& bytecode);
+ const char *shader_load_filepath(string filepath);
+
+protected:
+ void texture_system_init();
+ void shading_system_init();
+
OSL::ShadingSystem *ss;
OSL::TextureSystem *ts;
OSLRenderServices *services;
OSL::ErrorHandler errhandler;
+ set<string> loaded_shaders;
};
#endif
@@ -64,10 +81,10 @@ private:
class OSLCompiler {
public:
- OSLCompiler(void *shadingsys);
+ OSLCompiler(void *manager, void *shadingsys);
void compile(OSLGlobals *og, Shader *shader);
- void add(ShaderNode *node, const char *name);
+ void add(ShaderNode *node, const char *name, bool isfilepath = false);
void parameter(const char *name, float f);
void parameter_color(const char *name, float3 f);
@@ -79,6 +96,15 @@ public:
void parameter(const char *name, ustring str);
void parameter(const char *name, const Transform& tfm);
+ void parameter_array(const char *name, const float f[], int arraylen);
+ void parameter_color_array(const char *name, const float f[][3], int arraylen);
+ void parameter_vector_array(const char *name, const float f[][3], int arraylen);
+ void parameter_normal_array(const char *name, const float f[][3], int arraylen);
+ void parameter_point_array(const char *name, const float f[][3], int arraylen);
+ void parameter_array(const char *name, const int f[], int arraylen);
+ void parameter_array(const char *name, const char * const s[], int arraylen);
+ void parameter_array(const char *name, const Transform tfm[], int arraylen);
+
ShaderType output_type() { return current_type; }
bool background;
@@ -87,12 +113,14 @@ private:
string id(ShaderNode *node);
void compile_type(Shader *shader, ShaderGraph *graph, ShaderType type);
bool node_skip_input(ShaderNode *node, ShaderInput *input);
- string compatible_name(const char *name);
+ string compatible_name(ShaderNode *node, ShaderInput *input);
+ string compatible_name(ShaderNode *node, ShaderOutput *output);
void find_dependencies(set<ShaderNode*>& dependencies, ShaderInput *input);
void generate_nodes(const set<ShaderNode*>& nodes);
void *shadingsys;
+ void *manager;
ShaderType current_type;
Shader *current_shader;
};
diff --git a/intern/cycles/render/scene.cpp b/intern/cycles/render/scene.cpp
index 071338d49c2..15031b9500c 100644
--- a/intern/cycles/render/scene.cpp
+++ b/intern/cycles/render/scene.cpp
@@ -183,10 +183,10 @@ void Scene::device_update(Device *device_, Progress& progress)
device->const_copy_to("__data", &dscene.data, sizeof(dscene.data));
}
-Scene::MotionType Scene::need_motion()
+Scene::MotionType Scene::need_motion(bool advanced_shading)
{
if(integrator->motion_blur)
- return MOTION_BLUR;
+ return (advanced_shading)? MOTION_BLUR: MOTION_NONE;
else if(Pass::contains(film->passes, PASS_MOTION))
return MOTION_PASS;
else
diff --git a/intern/cycles/render/scene.h b/intern/cycles/render/scene.h
index 09087fb2970..bd45c1c04e6 100644
--- a/intern/cycles/render/scene.h
+++ b/intern/cycles/render/scene.h
@@ -194,7 +194,7 @@ public:
void need_global_attributes(AttributeRequestSet& attributes);
enum MotionType { MOTION_NONE = 0, MOTION_PASS, MOTION_BLUR };
- MotionType need_motion();
+ MotionType need_motion(bool advanced_shading = true);
bool need_update();
bool need_reset();
diff --git a/intern/cycles/render/session.cpp b/intern/cycles/render/session.cpp
index 05c57ba48ec..7303cb52ad8 100644
--- a/intern/cycles/render/session.cpp
+++ b/intern/cycles/render/session.cpp
@@ -34,16 +34,22 @@
CCL_NAMESPACE_BEGIN
+/* Note about preserve_tile_device option for tile manager:
+ * progressive refine and viewport rendering does requires tiles to
+ * always be allocated for the same device
+ */
Session::Session(const SessionParams& params_)
: params(params_),
- tile_manager(params.progressive, params.samples, params.tile_size, params.resolution,
- (params.background)? 1: max(params.device.multi_devices.size(), 1))
+ tile_manager(params.progressive, params.samples, params.tile_size, params.start_resolution,
+ params.background == false || params.progressive_refine, params.background,
+ max(params.device.multi_devices.size(), 1)),
+ stats()
{
device_use_gl = ((params.device.type != DEVICE_CPU) && !params.background);
TaskScheduler::init(params.threads);
- device = Device::create(params.device, params.background, params.threads);
+ device = Device::create(params.device, stats, params.background, params.threads);
if(params.background) {
buffers = NULL;
@@ -96,6 +102,9 @@ Session::~Session()
display->write(device, params.output_path);
}
+ foreach(RenderBuffers *buffers, tile_buffers)
+ delete buffers;
+
delete buffers;
delete display;
delete scene;
@@ -140,12 +149,6 @@ void Session::reset_gpu(BufferParams& buffer_params, int samples)
pause_cond.notify_all();
}
-bool Session::resetting_gpu() const
-{
- /* no need to wait for gpu device */
- return false;
-}
-
bool Session::draw_gpu(BufferParams& buffer_params)
{
/* block for buffer access */
@@ -179,9 +182,12 @@ bool Session::draw_gpu(BufferParams& buffer_params)
void Session::run_gpu()
{
+ bool tiles_written = false;
+
start_time = time_dt();
reset_time = time_dt();
paused_time = 0.0;
+ last_update_time = time_dt();
if(!params.background)
progress.set_start_time(start_time + paused_time);
@@ -273,10 +279,15 @@ void Session::run_gpu()
if(device->error_message() != "")
progress.set_cancel(device->error_message());
+ tiles_written = update_progressive_refine(progress.get_cancel());
+
if(progress.get_cancel())
break;
}
}
+
+ if(!tiles_written)
+ update_progressive_refine(true);
}
/* CPU Session */
@@ -296,11 +307,6 @@ void Session::reset_cpu(BufferParams& buffer_params, int samples)
pause_cond.notify_all();
}
-bool Session::resetting_cpu() const
-{
- return device->task_cancelled();
-}
-
bool Session::draw_cpu(BufferParams& buffer_params)
{
thread_scoped_lock display_lock(display_mutex);
@@ -324,14 +330,18 @@ bool Session::draw_cpu(BufferParams& buffer_params)
bool Session::acquire_tile(Device *tile_device, RenderTile& rtile)
{
- if(progress.get_cancel())
- return false;
+ if(progress.get_cancel()) {
+ if(params.progressive_refine == false) {
+ /* for progressive refine current sample should be finished for all tiles */
+ return false;
+ }
+ }
thread_scoped_lock tile_lock(tile_mutex);
/* get next tile from manager */
Tile tile;
- int device_num = (params.background)? 0: device->device_number(tile_device);
+ int device_num = device->device_number(tile_device);
if(!tile_manager.next_tile(tile, device_num))
return false;
@@ -343,13 +353,13 @@ bool Session::acquire_tile(Device *tile_device, RenderTile& rtile)
rtile.h = tile.h;
rtile.start_sample = tile_manager.state.sample;
rtile.num_samples = tile_manager.state.num_samples;
- rtile.resolution = tile_manager.state.resolution;
+ rtile.resolution = tile_manager.state.resolution_divider;
tile_lock.unlock();
/* in case of a permant buffer, return it, otherwise we will allocate
* a new temporary buffer */
- if(!write_render_tile_cb) {
+ if(!params.background) {
tile_manager.state.buffer.get_offset_stride(rtile.offset, rtile.stride);
rtile.buffer = buffers->buffer.device_pointer;
@@ -371,9 +381,30 @@ bool Session::acquire_tile(Device *tile_device, RenderTile& rtile)
buffer_params.get_offset_stride(rtile.offset, rtile.stride);
- /* allocate buffers */
RenderBuffers *tilebuffers = new RenderBuffers(tile_device);
- tilebuffers->reset(tile_device, buffer_params);
+
+ /* allocate buffers */
+ if(params.progressive_refine) {
+ tile_lock.lock();
+
+ if(tile_buffers.size() == 0)
+ tile_buffers.resize(tile_manager.state.num_tiles, NULL);
+
+ tilebuffers = tile_buffers[tile.index];
+ if(tilebuffers == NULL) {
+ tilebuffers = new RenderBuffers(tile_device);
+ tile_buffers[tile.index] = tilebuffers;
+
+ tilebuffers->reset(tile_device, buffer_params);
+ }
+
+ tile_lock.unlock();
+ }
+ else {
+ tilebuffers = new RenderBuffers(tile_device);
+
+ tilebuffers->reset(tile_device, buffer_params);
+ }
rtile.buffer = tilebuffers->buffer.device_pointer;
rtile.rng_state = tilebuffers->rng_state.device_pointer;
@@ -388,9 +419,11 @@ void Session::update_tile_sample(RenderTile& rtile)
thread_scoped_lock tile_lock(tile_mutex);
if(update_render_tile_cb) {
- /* todo: optimize this by making it thread safe and removing lock */
+ if(params.progressive_refine == false) {
+ /* todo: optimize this by making it thread safe and removing lock */
- update_render_tile_cb(rtile);
+ update_render_tile_cb(rtile);
+ }
}
update_status_time();
@@ -401,10 +434,12 @@ void Session::release_tile(RenderTile& rtile)
thread_scoped_lock tile_lock(tile_mutex);
if(write_render_tile_cb) {
- /* todo: optimize this by making it thread safe and removing lock */
- write_render_tile_cb(rtile);
+ if(params.progressive_refine == false) {
+ /* todo: optimize this by making it thread safe and removing lock */
+ write_render_tile_cb(rtile);
- delete rtile.buffers;
+ delete rtile.buffers;
+ }
}
update_status_time();
@@ -412,6 +447,10 @@ void Session::release_tile(RenderTile& rtile)
void Session::run_cpu()
{
+ bool tiles_written = false;
+
+ last_update_time = time_dt();
+
{
/* reset once to start */
thread_scoped_lock reset_lock(delayed_reset.mutex);
@@ -513,10 +552,15 @@ void Session::run_cpu()
if(device->error_message() != "")
progress.set_cancel(device->error_message());
+
+ tiles_written = update_progressive_refine(progress.get_cancel());
}
progress.set_update();
}
+
+ if(!tiles_written)
+ update_progressive_refine(true);
}
void Session::run()
@@ -595,14 +639,6 @@ void Session::reset(BufferParams& buffer_params, int samples)
reset_cpu(buffer_params, samples);
}
-bool Session::resetting() const
-{
- if(device_use_gl)
- return resetting_gpu();
- else
- return resetting_cpu();
-}
-
void Session::set_samples(int samples)
{
if(samples != params.samples) {
@@ -668,7 +704,7 @@ void Session::update_scene()
void Session::update_status_time(bool show_pause, bool show_done)
{
int sample = tile_manager.state.sample;
- int resolution = tile_manager.state.resolution;
+ int resolution = tile_manager.state.resolution_divider;
int num_tiles = tile_manager.state.num_tiles;
int tile = tile_manager.state.num_rendered_tiles;
@@ -676,10 +712,13 @@ void Session::update_status_time(bool show_pause, bool show_done)
string status, substatus;
if(!params.progressive) {
+ bool is_gpu = params.device.type == DEVICE_CUDA || params.device.type == DEVICE_OPENCL;
+ bool is_multidevice = params.device.multi_devices.size() > 1;
+ bool is_cpu = params.device.type == DEVICE_CPU;
+
substatus = string_printf("Path Tracing Tile %d/%d", tile, num_tiles);
- if(params.device.type == DEVICE_CUDA || params.device.type == DEVICE_OPENCL ||
- (params.device.type == DEVICE_CPU && num_tiles == 1)) {
+ if((is_gpu && !is_multidevice) || (is_cpu && num_tiles == 1)) {
/* when rendering on GPU multithreading happens within single tile, as in
* tiles are handling sequentially and in this case we could display
* currently rendering sample number
@@ -741,6 +780,7 @@ void Session::path_trace()
task.get_cancel = function_bind(&Progress::get_cancel, &this->progress);
task.update_tile_sample = function_bind(&Session::update_tile_sample, this, _1);
task.update_progress_sample = function_bind(&Session::update_progress_sample, this);
+ task.need_finish_queue = params.progressive_refine;
device->task_add(task);
}
@@ -757,7 +797,7 @@ void Session::tonemap()
task.rgba = display->rgba.device_pointer;
task.buffer = buffers->buffer.device_pointer;
task.sample = tile_manager.state.sample;
- task.resolution = tile_manager.state.resolution;
+ task.resolution = tile_manager.state.resolution_divider;
tile_manager.state.buffer.get_offset_stride(task.offset, task.stride);
if(task.w > 0 && task.h > 0) {
@@ -771,5 +811,35 @@ void Session::tonemap()
display_outdated = false;
}
-CCL_NAMESPACE_END
+bool Session::update_progressive_refine(bool cancel)
+{
+ int sample = tile_manager.state.sample + 1;
+ bool write = sample == params.samples || cancel;
+ double current_time = time_dt();
+
+ if (current_time - last_update_time < 1.0f) {
+ /* if last sample was processed, we need to write buffers anyway */
+ if (!write)
+ return false;
+ }
+
+ if(params.progressive_refine) {
+ foreach(RenderBuffers *buffers, tile_buffers) {
+ RenderTile rtile;
+ rtile.buffers = buffers;
+ rtile.sample = sample;
+
+ if(write)
+ write_render_tile_cb(rtile);
+ else
+ update_render_tile_cb(rtile);
+ }
+ }
+
+ last_update_time = current_time;
+
+ return write;
+}
+
+CCL_NAMESPACE_END
diff --git a/intern/cycles/render/session.h b/intern/cycles/render/session.h
index e45753d22a0..7bb0cd1ae01 100644
--- a/intern/cycles/render/session.h
+++ b/intern/cycles/render/session.h
@@ -24,7 +24,9 @@
#include "tile.h"
#include "util_progress.h"
+#include "util_stats.h"
#include "util_thread.h"
+#include "util_vector.h"
CCL_NAMESPACE_BEGIN
@@ -42,50 +44,58 @@ class SessionParams {
public:
DeviceInfo device;
bool background;
+ bool progressive_refine;
string output_path;
bool progressive;
bool experimental;
int samples;
int2 tile_size;
- int resolution;
+ int start_resolution;
int threads;
double cancel_timeout;
double reset_timeout;
double text_timeout;
+ enum { OSL, SVM } shadingsystem;
+
SessionParams()
{
background = false;
+ progressive_refine = false;
output_path = "";
progressive = false;
experimental = false;
samples = INT_MAX;
tile_size = make_int2(64, 64);
- resolution = 4;
+ start_resolution = INT_MAX;
threads = 0;
cancel_timeout = 0.1;
reset_timeout = 0.1;
text_timeout = 1.0;
+
+ shadingsystem = SVM;
}
bool modified(const SessionParams& params)
{ return !(device.type == params.device.type
&& device.id == params.device.id
&& background == params.background
+ && progressive_refine == params.progressive_refine
&& output_path == params.output_path
/* && samples == params.samples */
&& progressive == params.progressive
&& experimental == params.experimental
&& tile_size == params.tile_size
- && resolution == params.resolution
+ && start_resolution == params.start_resolution
&& threads == params.threads
&& cancel_timeout == params.cancel_timeout
&& reset_timeout == params.reset_timeout
- && text_timeout == params.text_timeout); }
+ && text_timeout == params.text_timeout
+ && shadingsystem == params.shadingsystem); }
};
@@ -103,6 +113,7 @@ public:
Progress progress;
SessionParams params;
TileManager tile_manager;
+ Stats stats;
boost::function<void(RenderTile&)> write_render_tile_cb;
boost::function<void(RenderTile&)> update_render_tile_cb;
@@ -116,7 +127,6 @@ public:
bool ready_to_reset();
void reset(BufferParams& params, int samples);
- bool resetting() const;
void set_samples(int samples);
void set_pause(bool pause);
@@ -140,12 +150,10 @@ protected:
void run_cpu();
bool draw_cpu(BufferParams& params);
void reset_cpu(BufferParams& params, int samples);
- bool resetting_cpu() const;
void run_gpu();
bool draw_gpu(BufferParams& params);
void reset_gpu(BufferParams& params, int samples);
- bool resetting_gpu() const;
bool acquire_tile(Device *tile_device, RenderTile& tile);
void update_tile_sample(RenderTile& tile);
@@ -176,6 +184,12 @@ protected:
double reset_time;
double preview_time;
double paused_time;
+
+ /* progressive refine */
+ double last_update_time;
+ bool update_progressive_refine(bool cancel);
+
+ vector<RenderBuffers *> tile_buffers;
};
CCL_NAMESPACE_END
diff --git a/intern/cycles/render/shader.cpp b/intern/cycles/render/shader.cpp
index fae1d6bd81c..17f7fbd43d6 100644
--- a/intern/cycles/render/shader.cpp
+++ b/intern/cycles/render/shader.cpp
@@ -49,6 +49,8 @@ Shader::Shader()
has_volume = false;
has_displacement = false;
+ used = false;
+
need_update = true;
need_update_attributes = true;
}
@@ -98,6 +100,16 @@ void Shader::tag_update(Scene *scene)
}
}
+void Shader::tag_used(Scene *scene)
+{
+ /* if an unused shader suddenly gets used somewhere, it needs to be
+ * recompiled because it was skipped for compilation before */
+ if(!used) {
+ need_update = true;
+ scene->shader_manager->need_update = true;
+ }
+}
+
/* Shader Manager */
ShaderManager::ShaderManager()
@@ -161,6 +173,27 @@ int ShaderManager::get_shader_id(uint shader, Mesh *mesh, bool smooth)
return id;
}
+void ShaderManager::device_update_shaders_used(Scene *scene)
+{
+ /* figure out which shaders are in use, so SVM/OSL can skip compiling them
+ * for speed and avoid loading image textures into memory */
+ foreach(Shader *shader, scene->shaders)
+ shader->used = false;
+
+ scene->shaders[scene->default_surface]->used = true;
+ scene->shaders[scene->default_light]->used = true;
+ scene->shaders[scene->default_background]->used = true;
+ scene->shaders[scene->default_holdout]->used = true;
+ scene->shaders[scene->default_empty]->used = true;
+
+ foreach(Mesh *mesh, scene->meshes)
+ foreach(uint shader, mesh->used_shaders)
+ scene->shaders[shader]->used = true;
+
+ foreach(Light *light, scene->lights)
+ scene->shaders[light->shader]->used = true;
+}
+
void ShaderManager::device_update_common(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
{
device_free_common(device, dscene);
diff --git a/intern/cycles/render/shader.h b/intern/cycles/render/shader.h
index 02788008060..373b3356f51 100644
--- a/intern/cycles/render/shader.h
+++ b/intern/cycles/render/shader.h
@@ -27,6 +27,10 @@
#include "util_string.h"
#include "util_types.h"
+#ifdef WITH_OSL
+#include <OSL/oslexec.h>
+#endif
+
CCL_NAMESPACE_BEGIN
class Device;
@@ -75,11 +79,23 @@ public:
/* requested mesh attributes */
AttributeRequestSet attributes;
+ /* determined before compiling */
+ bool used;
+
+#ifdef WITH_OSL
+ /* osl shading state references */
+ OSL::ShadingAttribStateRef osl_surface_ref;
+ OSL::ShadingAttribStateRef osl_surface_bump_ref;
+ OSL::ShadingAttribStateRef osl_volume_ref;
+ OSL::ShadingAttribStateRef osl_displacement_ref;
+#endif
+
Shader();
~Shader();
void set_graph(ShaderGraph *graph);
void tag_update(Scene *scene);
+ void tag_used(Scene *scene);
};
/* Shader Manager virtual base class
@@ -98,6 +114,7 @@ public:
virtual void device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress) = 0;
virtual void device_free(Device *device, DeviceScene *dscene) = 0;
+ void device_update_shaders_used(Scene *scene);
void device_update_common(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress);
void device_free_common(Device *device, DeviceScene *dscene);
diff --git a/intern/cycles/render/svm.cpp b/intern/cycles/render/svm.cpp
index 844ce01569f..dc249984499 100644
--- a/intern/cycles/render/svm.cpp
+++ b/intern/cycles/render/svm.cpp
@@ -48,6 +48,9 @@ void SVMShaderManager::device_update(Device *device, DeviceScene *dscene, Scene
/* test if we need to update */
device_free(device, dscene);
+ /* determine which shaders are in use */
+ device_update_shaders_used(scene);
+
/* svm_nodes */
vector<int4> svm_nodes;
size_t i;
@@ -119,6 +122,8 @@ int SVMCompiler::stack_size(ShaderSocketType type)
{
if(type == SHADER_SOCKET_FLOAT)
return 1;
+ else if(type == SHADER_SOCKET_INT)
+ return 1;
else if(type == SHADER_SOCKET_COLOR)
return 3;
else if(type == SHADER_SOCKET_VECTOR)
@@ -212,10 +217,13 @@ void SVMCompiler::stack_assign(ShaderInput *input)
if(input->type == SHADER_SOCKET_FLOAT) {
add_node(NODE_VALUE_F, __float_as_int(input->value.x), input->stack_offset);
}
+ else if(input->type == SHADER_SOCKET_INT) {
+ add_node(NODE_VALUE_F, (int)input->value.x, input->stack_offset);
+ }
else if(input->type == SHADER_SOCKET_VECTOR ||
- input->type == SHADER_SOCKET_NORMAL ||
- input->type == SHADER_SOCKET_POINT ||
- input->type == SHADER_SOCKET_COLOR) {
+ input->type == SHADER_SOCKET_NORMAL ||
+ input->type == SHADER_SOCKET_POINT ||
+ input->type == SHADER_SOCKET_COLOR) {
add_node(NODE_VALUE_V, input->stack_offset);
add_node(NODE_VALUE_V, input->value);
@@ -604,36 +612,38 @@ void SVMCompiler::compile_type(Shader *shader, ShaderGraph *graph, ShaderType ty
output->stack_offset = SVM_STACK_INVALID;
}
- if(clin->link) {
- bool generate = false;
- if(type == SHADER_TYPE_SURFACE) {
- /* generate surface shader */
- generate = true;
- shader->has_surface = true;
- }
- else if(type == SHADER_TYPE_VOLUME) {
- /* generate volume shader */
- generate = true;
- shader->has_volume = true;
- }
- else if(type == SHADER_TYPE_DISPLACEMENT) {
- /* generate displacement shader */
- generate = true;
- shader->has_displacement = true;
- }
+ if(shader->used) {
+ if(clin->link) {
+ bool generate = false;
+ if(type == SHADER_TYPE_SURFACE) {
+ /* generate surface shader */
+ generate = true;
+ shader->has_surface = true;
+ }
+ else if(type == SHADER_TYPE_VOLUME) {
+ /* generate volume shader */
+ generate = true;
+ shader->has_volume = true;
+ }
+ else if(type == SHADER_TYPE_DISPLACEMENT) {
+ /* generate displacement shader */
+ generate = true;
+ shader->has_displacement = true;
+ }
- if(generate) {
- set<ShaderNode*> done;
+ if(generate) {
+ set<ShaderNode*> done;
- if(use_multi_closure)
- generate_multi_closure(clin->link->parent, done, SVM_STACK_INVALID);
- else
- generate_closure(clin->link->parent, done);
+ if(use_multi_closure)
+ generate_multi_closure(clin->link->parent, done, SVM_STACK_INVALID);
+ else
+ generate_closure(clin->link->parent, done);
+ }
}
- }
- /* compile output node */
- node->compile(*this);
+ /* compile output node */
+ node->compile(*this);
+ }
add_node(NODE_END, 0, 0, 0);
}
diff --git a/intern/cycles/render/tile.cpp b/intern/cycles/render/tile.cpp
index b4156fd9471..74585dd5058 100644
--- a/intern/cycles/render/tile.cpp
+++ b/intern/cycles/render/tile.cpp
@@ -23,12 +23,15 @@
CCL_NAMESPACE_BEGIN
-TileManager::TileManager(bool progressive_, int num_samples_, int2 tile_size_, int resolution_, int num_devices_)
+TileManager::TileManager(bool progressive_, int num_samples_, int2 tile_size_, int start_resolution_,
+ bool preserve_tile_device_, bool background_, int num_devices_)
{
progressive = progressive_;
tile_size = tile_size_;
- resolution = resolution_;
+ start_resolution = start_resolution_;
num_devices = num_devices_;
+ preserve_tile_device = preserve_tile_device_;
+ background = background_;
BufferParams buffer_params;
reset(buffer_params, 0);
@@ -42,6 +45,18 @@ void TileManager::reset(BufferParams& params_, int num_samples_)
{
params = params_;
+ int divider = 1;
+ int w = params.width, h = params.height;
+
+ if(start_resolution != INT_MAX) {
+ while(w*h > start_resolution*start_resolution) {
+ w = max(1, w/2);
+ h = max(1, h/2);
+
+ divider *= 2;
+ }
+ }
+
num_samples = num_samples_;
state.buffer = BufferParams();
@@ -49,7 +64,7 @@ void TileManager::reset(BufferParams& params_, int num_samples_)
state.num_tiles = 0;
state.num_rendered_tiles = 0;
state.num_samples = 0;
- state.resolution = resolution;
+ state.resolution_divider = divider;
state.tiles.clear();
}
@@ -58,15 +73,55 @@ void TileManager::set_samples(int num_samples_)
num_samples = num_samples_;
}
-void TileManager::set_tiles()
+/* splits image into tiles and assigns equal amount of tiles to every render device */
+void TileManager::gen_tiles_global()
+{
+ int resolution = state.resolution_divider;
+ int image_w = max(1, params.width/resolution);
+ int image_h = max(1, params.height/resolution);
+
+ state.tiles.clear();
+
+ int tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)/tile_size.x;
+ int tile_h = (tile_size.y >= image_h)? 1: (image_h + tile_size.y - 1)/tile_size.y;
+
+ int num_logical_devices = preserve_tile_device? num_devices: 1;
+ int num = min(image_h, num_logical_devices);
+ int tile_index = 0;
+
+ int tiles_per_device = (tile_w * tile_h + num - 1) / num;
+ int cur_device = 0, cur_tiles = 0;
+
+ for(int tile_y = 0; tile_y < tile_h; tile_y++) {
+ for(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) {
+ int x = tile_x * tile_size.x;
+ int y = tile_y * tile_size.y;
+ int w = (tile_x == tile_w-1)? image_w - x: tile_size.x;
+ int h = (tile_y == tile_h-1)? image_h - y: tile_size.y;
+
+ state.tiles.push_back(Tile(tile_index, x, y, w, h, cur_device));
+ cur_tiles++;
+
+ if(cur_tiles == tiles_per_device) {
+ cur_tiles = 0;
+ cur_device++;
+ }
+ }
+ }
+}
+
+/* slices image into as much pieces as how many devices are rendering this image */
+void TileManager::gen_tiles_sliced()
{
- int resolution = state.resolution;
+ int resolution = state.resolution_divider;
int image_w = max(1, params.width/resolution);
int image_h = max(1, params.height/resolution);
state.tiles.clear();
- int num = min(image_h, num_devices);
+ int num_logical_devices = preserve_tile_device? num_devices: 1;
+ int num = min(image_h, num_logical_devices);
+ int tile_index = 0;
for(int device = 0; device < num; device++) {
int device_y = (image_h/num)*device;
@@ -74,20 +129,30 @@ void TileManager::set_tiles()
int tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)/tile_size.x;
int tile_h = (tile_size.y >= device_h)? 1: (device_h + tile_size.y - 1)/tile_size.y;
- int sub_w = (image_w + tile_w - 1)/tile_w;
- int sub_h = (device_h + tile_h - 1)/tile_h;
for(int tile_y = 0; tile_y < tile_h; tile_y++) {
- for(int tile_x = 0; tile_x < tile_w; tile_x++) {
- int x = tile_x * sub_w;
- int y = tile_y * sub_h;
- int w = (tile_x == tile_w-1)? image_w - x: sub_w;
- int h = (tile_y == tile_h-1)? device_h - y: sub_h;
+ for(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) {
+ int x = tile_x * tile_size.x;
+ int y = tile_y * tile_size.y;
+ int w = (tile_x == tile_w-1)? image_w - x: tile_size.x;
+ int h = (tile_y == tile_h-1)? device_h - y: tile_size.x;
- state.tiles.push_back(Tile(x, y + device_y, w, h, device));
+ state.tiles.push_back(Tile(tile_index, x, y + device_y, w, h, device));
}
}
}
+}
+
+void TileManager::set_tiles()
+{
+ int resolution = state.resolution_divider;
+ int image_w = max(1, params.width/resolution);
+ int image_h = max(1, params.height/resolution);
+
+ if(background)
+ gen_tiles_global();
+ else
+ gen_tiles_sliced();
state.num_tiles = state.tiles.size();
@@ -104,17 +169,14 @@ list<Tile>::iterator TileManager::next_center_tile(int device)
{
list<Tile>::iterator iter, best = state.tiles.end();
- int resolution = state.resolution;
+ int resolution = state.resolution_divider;
int image_w = max(1, params.width/resolution);
int image_h = max(1, params.height/resolution);
- int num = min(image_h, num_devices);
+ int logical_device = preserve_tile_device? device: 0;
- int device_y = (image_h / num) * device;
- int device_h = (device == num - 1) ? image_h - device * (image_h / num) : image_h / num;
-
- int64_t centx = image_w / 2, centy = device_y + device_h / 2, tot = 1;
- int64_t mindist = (int64_t) image_w * (int64_t) device_h;
+ int64_t centx = image_w / 2, centy = image_h / 2, tot = 1;
+ int64_t mindist = (int64_t) image_w * (int64_t) image_h;
/* find center of rendering tiles, image center counts for 1 too */
for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) {
@@ -131,7 +193,7 @@ list<Tile>::iterator TileManager::next_center_tile(int device)
/* closest of the non-rendering tiles */
for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) {
- if(iter->device == device && iter->rendering == false) {
+ if(iter->device == logical_device && iter->rendering == false) {
Tile &cur_tile = *iter;
int64_t distx = centx - (cur_tile.x + cur_tile.w / 2);
@@ -148,11 +210,28 @@ list<Tile>::iterator TileManager::next_center_tile(int device)
return best;
}
+list<Tile>::iterator TileManager::next_simple_tile(int device)
+{
+ list<Tile>::iterator iter;
+
+ int logical_device = preserve_tile_device? device: 0;
+
+ for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) {
+ if(iter->device == logical_device && iter->rendering == false)
+ return iter;
+ }
+
+ return state.tiles.end();
+}
+
bool TileManager::next_tile(Tile& tile, int device)
{
list<Tile>::iterator tile_it;
- tile_it = next_center_tile(device);
+ if(background)
+ tile_it = next_center_tile(device);
+ else
+ tile_it = next_simple_tile(device);
if(tile_it != state.tiles.end()) {
tile_it->rendering = true;
@@ -167,7 +246,7 @@ bool TileManager::next_tile(Tile& tile, int device)
bool TileManager::done()
{
- return (state.sample+state.num_samples >= num_samples && state.resolution == 1);
+ return (state.sample+state.num_samples >= num_samples && state.resolution_divider == 1);
}
bool TileManager::next()
@@ -175,9 +254,9 @@ bool TileManager::next()
if(done())
return false;
- if(progressive && state.resolution > 1) {
+ if(progressive && state.resolution_divider > 1) {
state.sample = 0;
- state.resolution /= 2;
+ state.resolution_divider /= 2;
state.num_samples = 1;
set_tiles();
}
@@ -189,7 +268,7 @@ bool TileManager::next()
else
state.num_samples = num_samples;
- state.resolution = 1;
+ state.resolution_divider = 1;
set_tiles();
}
diff --git a/intern/cycles/render/tile.h b/intern/cycles/render/tile.h
index 29f2b1ef9f9..6f7a8f20734 100644
--- a/intern/cycles/render/tile.h
+++ b/intern/cycles/render/tile.h
@@ -30,6 +30,7 @@ CCL_NAMESPACE_BEGIN
class Tile {
public:
+ int index;
int x, y, w, h;
int device;
bool rendering;
@@ -37,8 +38,8 @@ public:
Tile()
{}
- Tile(int x_, int y_, int w_, int h_, int device_)
- : x(x_), y(y_), w(w_), h(h_), device(device_), rendering(false) {}
+ Tile(int index_, int x_, int y_, int w_, int h_, int device_)
+ : index(index_), x(x_), y(y_), w(w_), h(h_), device(device_), rendering(false) {}
};
/* Tile Manager */
@@ -51,13 +52,14 @@ public:
BufferParams buffer;
int sample;
int num_samples;
- int resolution;
+ int resolution_divider;
int num_tiles;
int num_rendered_tiles;
list<Tile> tiles;
} state;
- TileManager(bool progressive, int num_samples, int2 tile_size, int resolution, int num_devices = 1);
+ TileManager(bool progressive, int num_samples, int2 tile_size, int start_resolution,
+ bool preserve_tile_device, bool background, int num_devices = 1);
~TileManager();
void reset(BufferParams& params, int num_samples);
@@ -72,12 +74,41 @@ protected:
bool progressive;
int num_samples;
int2 tile_size;
- int resolution;
- int num_devices;
-
int start_resolution;
+ int num_devices;
- list<Tile>::iterator next_center_tile(int device = 0);
+ /* in some cases it is important that the same tile will be returned for the same
+ * device it was originally generated for (i.e. viewport rendering when buffer is
+ * allocating once for tile and then always used by it)
+ *
+ * in other cases any tile could be handled by any device (i.e. final rendering
+ * without progressive refine)
+ */
+ bool preserve_tile_device;
+
+ /* for background render tiles should exactly match render parts generated from
+ * blender side, which means image first gets split into tiles and then tiles are
+ * assigning to render devices
+ *
+ * however viewport rendering expects tiles to be allocated in a special way,
+ * meaning image is being sliced horizontally first and every device handles
+ * it's own slice
+ */
+ bool background;
+
+ /* splits image into tiles and assigns equal amount of tiles to every render device */
+ void gen_tiles_global();
+
+ /* slices image into as much pieces as how many devices are rendering this image */
+ void gen_tiles_sliced();
+
+ /* returns closest tile to center of rendered tiles
+ * mimics behavior of blender internal's tile order
+ */
+ list<Tile>::iterator next_center_tile(int device);
+
+ /* returns first unhandled tile starting from left bottom corner of the image */
+ list<Tile>::iterator next_simple_tile(int device);
};
CCL_NAMESPACE_END
diff --git a/intern/cycles/subd/CMakeLists.txt b/intern/cycles/subd/CMakeLists.txt
index 75f70753ddf..838776d60bf 100644
--- a/intern/cycles/subd/CMakeLists.txt
+++ b/intern/cycles/subd/CMakeLists.txt
@@ -7,6 +7,10 @@ set(INC
../render
)
+set(INC_SYS
+
+)
+
set(SRC
subd_build.cpp
subd_dice.cpp
@@ -31,5 +35,6 @@ set(SRC_HEADERS
)
include_directories(${INC})
+include_directories(SYSTEM ${INC_SYS})
add_library(cycles_subd ${SRC} ${SRC_HEADERS})
diff --git a/intern/cycles/subd/subd_build.cpp b/intern/cycles/subd/subd_build.cpp
index 312980f1fa2..8e84da7f019 100644
--- a/intern/cycles/subd/subd_build.cpp
+++ b/intern/cycles/subd/subd_build.cpp
@@ -333,7 +333,7 @@ void SubdAccBuilder::computeEdgeStencil(SubdFaceRing *ring, GregoryAccStencil *s
/* @@ this probably does not provide watertight results!! (1/3 + 1/3 + 1/3 != 1) */
/* distribute weight to all verts */
- stencil->get(eid1, vert) += beta * costerm1_b / 3.0f;
+ stencil->get(eid1, vert) += beta * costerm1_b / 3.0f;
stencil->get(eid1, edge->to()) += beta * costerm1_b / 3.0f;
stencil->get(eid1, edge->next->to()) += beta * costerm1_b / 3.0f;
diff --git a/intern/cycles/util/CMakeLists.txt b/intern/cycles/util/CMakeLists.txt
index ae8403a14a8..bf5f791a245 100644
--- a/intern/cycles/util/CMakeLists.txt
+++ b/intern/cycles/util/CMakeLists.txt
@@ -1,6 +1,9 @@
set(INC
.
+)
+
+set(INC_SYS
${GLEW_INCLUDE_PATH}
${OPENGL_INCLUDE_DIR}
)
@@ -64,5 +67,6 @@ set(SRC_HEADERS
)
include_directories(${INC})
+include_directories(SYSTEM ${INC_SYS})
add_library(cycles_util ${SRC} ${SRC_HEADERS})
diff --git a/intern/cycles/util/util_attribute.cpp b/intern/cycles/util/util_attribute.cpp
index 3a1c2b6f332..163a92902f3 100644
--- a/intern/cycles/util/util_attribute.cpp
+++ b/intern/cycles/util/util_attribute.cpp
@@ -30,6 +30,8 @@ const char *attribute_standard_name(AttributeStandard std)
return "uv";
else if(std == ATTR_STD_GENERATED)
return "generated";
+ else if(std == ATTR_STD_TANGENT)
+ return "tangent";
else if(std == ATTR_STD_POSITION_UNDEFORMED)
return "undeformed";
else if(std == ATTR_STD_POSITION_UNDISPLACED)
diff --git a/intern/cycles/util/util_cuda.cpp b/intern/cycles/util/util_cuda.cpp
index 2960022fd8d..2716f00e173 100644
--- a/intern/cycles/util/util_cuda.cpp
+++ b/intern/cycles/util/util_cuda.cpp
@@ -17,6 +17,7 @@
*/
#include <stdlib.h>
+#include <stdio.h>
#include "util_cuda.h"
#include "util_debug.h"
@@ -413,8 +414,18 @@ string cuCompilerPath()
return nvcc;
#ifndef _WIN32
- if(system("which nvcc") == 0)
- return "nvcc";
+ {
+ FILE *handle = popen("which nvcc", "r");
+ if(handle) {
+ char buffer[4096] = {0};
+ int len = fread(buffer, 1, sizeof(buffer) - 1, handle);
+ buffer[len] = '\0';
+ pclose(handle);
+
+ if(buffer[0])
+ return "nvcc";
+ }
+ }
#endif
return "";
diff --git a/intern/cycles/util/util_math.h b/intern/cycles/util/util_math.h
index 71a5dedeaa4..70adee4385b 100644
--- a/intern/cycles/util/util_math.h
+++ b/intern/cycles/util/util_math.h
@@ -26,7 +26,9 @@
#ifndef __KERNEL_OPENCL__
-#define _USE_MATH_DEFINES
+#ifdef _MSC_VER
+# define _USE_MATH_DEFINES
+#endif
#include <float.h>
#include <math.h>
@@ -1067,6 +1069,29 @@ __device_inline float3 safe_divide_color(float3 a, float3 b)
return make_float3(x, y, z);
}
+/* Rotation of point around axis and angle */
+
+__device_inline float3 rotate_around_axis(float3 p, float3 axis, float angle)
+{
+ float costheta = cosf(angle);
+ float sintheta = sinf(angle);
+ float3 r;
+
+ r.x = ((costheta + (1 - costheta) * axis.x * axis.x) * p.x) +
+ (((1 - costheta) * axis.x * axis.y - axis.z * sintheta) * p.y) +
+ (((1 - costheta) * axis.x * axis.z + axis.y * sintheta) * p.z);
+
+ r.y = (((1 - costheta) * axis.x * axis.y + axis.z * sintheta) * p.x) +
+ ((costheta + (1 - costheta) * axis.y * axis.y) * p.y) +
+ (((1 - costheta) * axis.y * axis.z - axis.x * sintheta) * p.z);
+
+ r.z = (((1 - costheta) * axis.x * axis.z - axis.y * sintheta) * p.x) +
+ (((1 - costheta) * axis.y * axis.z + axis.x * sintheta) * p.y) +
+ ((costheta + (1 - costheta) * axis.z * axis.z) * p.z);
+
+ return r;
+}
+
CCL_NAMESPACE_END
#endif /* __UTIL_MATH_H__ */
diff --git a/intern/cycles/util/util_md5.h b/intern/cycles/util/util_md5.h
index 43e08e64f39..aab177d9fe6 100644
--- a/intern/cycles/util/util_md5.h
+++ b/intern/cycles/util/util_md5.h
@@ -44,7 +44,7 @@ public:
bool append_file(const string& filepath);
string get_hex();
- protected:
+protected:
void process(const uint8_t *data);
void finish(uint8_t digest[16]);
diff --git a/intern/cycles/util/util_path.cpp b/intern/cycles/util/util_path.cpp
index a571fe81118..8cf23bc6a76 100644
--- a/intern/cycles/util/util_path.cpp
+++ b/intern/cycles/util/util_path.cpp
@@ -170,7 +170,7 @@ bool path_read_binary(const string& path, vector<uint8_t>& binary)
return true;
}
-static bool path_read_text(const string& path, string& text)
+bool path_read_text(const string& path, string& text)
{
vector<uint8_t> binary;
@@ -184,6 +184,14 @@ static bool path_read_text(const string& path, string& text)
return true;
}
+uint64_t path_modified_time(const string& path)
+{
+ if(boost::filesystem::exists(path))
+ return (uint64_t)boost::filesystem::last_write_time(path);
+
+ return 0;
+}
+
string path_source_replace_includes(const string& source_, const string& path)
{
/* our own little c preprocessor that replaces #includes with the file
diff --git a/intern/cycles/util/util_path.h b/intern/cycles/util/util_path.h
index 6cba6a3158f..89e4452ecd9 100644
--- a/intern/cycles/util/util_path.h
+++ b/intern/cycles/util/util_path.h
@@ -45,6 +45,9 @@ string path_files_md5_hash(const string& dir);
void path_create_directories(const string& path);
bool path_write_binary(const string& path, const vector<uint8_t>& binary);
bool path_read_binary(const string& path, vector<uint8_t>& binary);
+bool path_read_text(const string& path, string& text);
+
+uint64_t path_modified_time(const string& path);
string path_source_replace_includes(const string& source, const string& path);
diff --git a/intern/cycles/util/util_progress.h b/intern/cycles/util/util_progress.h
index ab9ab7243e9..c97379d8776 100644
--- a/intern/cycles/util/util_progress.h
+++ b/intern/cycles/util/util_progress.h
@@ -43,6 +43,8 @@ public:
tile_time = 0.0f;
status = "Initializing";
substatus = "";
+ sync_status = "";
+ sync_substatus = "";
update_cb = NULL;
cancel = false;
cancel_message = "";
@@ -164,11 +166,42 @@ public:
set_update();
}
+ void set_sync_status(const string& status_, const string& substatus_ = "")
+ {
+ {
+ thread_scoped_lock lock(progress_mutex);
+ sync_status = status_;
+ sync_substatus = substatus_;
+ total_time = time_dt() - start_time;
+ }
+
+ set_update();
+
+ }
+
+ void set_sync_substatus(const string& substatus_)
+ {
+ {
+ thread_scoped_lock lock(progress_mutex);
+ sync_substatus = substatus_;
+ total_time = time_dt() - start_time;
+ }
+
+ set_update();
+ }
+
void get_status(string& status_, string& substatus_)
{
thread_scoped_lock lock(progress_mutex);
- status_ = status;
- substatus_ = substatus;
+
+ if(sync_status != "") {
+ status_ = sync_status;
+ substatus_ = sync_substatus;
+ }
+ else {
+ status_ = status;
+ substatus_ = substatus;
+ }
}
/* callback */
@@ -202,6 +235,9 @@ protected:
string status;
string substatus;
+ string sync_status;
+ string sync_substatus;
+
volatile bool cancel;
string cancel_message;
};
diff --git a/intern/cycles/util/util_stats.h b/intern/cycles/util/util_stats.h
new file mode 100644
index 00000000000..405c81a1e1f
--- /dev/null
+++ b/intern/cycles/util/util_stats.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2012, Blender Foundation.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef __UTIL_STATS_H__
+#define __UTIL_STATS_H__
+
+#include "util_thread.h"
+
+CCL_NAMESPACE_BEGIN
+
+class Stats {
+public:
+ Stats() : lock(), mem_used(0), mem_peak(0) {}
+
+ void mem_alloc(size_t size) {
+ lock.lock();
+
+ mem_used += size;
+ if(mem_used > mem_peak)
+ mem_peak = mem_used;
+
+ lock.unlock();
+ }
+
+ void mem_free(size_t size) {
+ lock.lock();
+ mem_used -= size;
+ lock.unlock();
+ }
+
+ spin_lock lock;
+ size_t mem_used;
+ size_t mem_peak;
+};
+
+CCL_NAMESPACE_END
+
+#endif /* __UTIL_STATS_H__ */
diff --git a/intern/cycles/util/util_task.cpp b/intern/cycles/util/util_task.cpp
index 2b209c135f4..ea0abd6f54f 100644
--- a/intern/cycles/util/util_task.cpp
+++ b/intern/cycles/util/util_task.cpp
@@ -38,8 +38,6 @@ TaskPool::~TaskPool()
void TaskPool::push(Task *task, bool front)
{
- thread_scoped_lock num_lock(num_mutex);
-
TaskScheduler::Entry entry;
entry.task = task;
@@ -104,17 +102,22 @@ void TaskPool::wait_work()
void TaskPool::cancel()
{
- thread_scoped_lock num_lock(num_mutex);
-
do_cancel = true;
TaskScheduler::clear(this);
+
+ {
+ thread_scoped_lock num_lock(num_mutex);
+
+ while(num)
+ num_cond.wait(num_lock);
+ }
+
+ do_cancel = false;
}
void TaskPool::stop()
{
- thread_scoped_lock num_lock(num_mutex);
-
TaskScheduler::clear(this);
assert(num == 0);
@@ -127,20 +130,20 @@ bool TaskPool::cancelled()
void TaskPool::num_decrease(int done)
{
+ num_mutex.lock();
num -= done;
+
assert(num >= 0);
-
- if(num == 0) {
- do_cancel = false;
-
+ if(num == 0)
num_cond.notify_all();
- }
+
+ num_mutex.unlock();
}
void TaskPool::num_increase()
{
+ thread_scoped_lock num_lock(num_mutex);
num++;
-
num_cond.notify_all();
}
@@ -236,11 +239,7 @@ void TaskScheduler::thread_run(int thread_id)
delete entry.task;
/* notify pool task was done */
- {
- /* not called from TaskPool, have to explicitly lock the mutex here */
- thread_scoped_lock num_lock(entry.pool->num_mutex);
- entry.pool->num_decrease(1);
- }
+ entry.pool->num_decrease(1);
}
}
diff --git a/intern/cycles/util/util_task.h b/intern/cycles/util/util_task.h
index 401a503f540..a2f284479c7 100644
--- a/intern/cycles/util/util_task.h
+++ b/intern/cycles/util/util_task.h
@@ -95,6 +95,7 @@ public:
static void exit();
static int num_threads() { return threads.size(); }
+ static bool active() { return users != 0; }
protected:
friend class TaskPool;
diff --git a/intern/cycles/util/util_thread.h b/intern/cycles/util/util_thread.h
index 9bea4e7808a..6d1bd0023a7 100644
--- a/intern/cycles/util/util_thread.h
+++ b/intern/cycles/util/util_thread.h
@@ -33,6 +33,9 @@ typedef boost::mutex thread_mutex;
typedef boost::mutex::scoped_lock thread_scoped_lock;
typedef boost::condition_variable thread_condition_variable;
+/* use boost for spinlocks as well */
+typedef boost::detail::spinlock spin_lock;
+
/* own pthread based implementation, to avoid boost version conflicts with
* dynamically loaded blender plugins */
@@ -60,6 +63,7 @@ public:
bool join()
{
+ joined = true;
return pthread_join(pthread_id, NULL) == 0;
}
diff --git a/intern/cycles/util/util_transform.cpp b/intern/cycles/util/util_transform.cpp
index b3c6506dfa0..70ee13d96d7 100644
--- a/intern/cycles/util/util_transform.cpp
+++ b/intern/cycles/util/util_transform.cpp
@@ -246,9 +246,10 @@ static void transform_decompose(Transform *decomp, const Transform *tfm)
decomp->w = make_float4(scale.y.z, scale.z.x, scale.z.y, scale.z.z);
}
-void transform_motion_decompose(MotionTransform *decomp, const MotionTransform *motion)
+void transform_motion_decompose(MotionTransform *decomp, const MotionTransform *motion, const Transform *mid)
{
transform_decompose(&decomp->pre, &motion->pre);
+ transform_decompose(&decomp->mid, mid);
transform_decompose(&decomp->post, &motion->post);
}
diff --git a/intern/cycles/util/util_transform.h b/intern/cycles/util/util_transform.h
index d93bbff5415..df525542207 100644
--- a/intern/cycles/util/util_transform.h
+++ b/intern/cycles/util/util_transform.h
@@ -41,6 +41,7 @@ typedef struct Transform {
typedef struct MotionTransform {
Transform pre;
+ Transform mid;
Transform post;
} MotionTransform;
@@ -304,10 +305,18 @@ __device_inline float4 quat_interpolate(float4 q1, float4 q2, float t)
{
float costheta = dot(q1, q2);
+ /* rotate around shortest angle */
+ if(costheta < 0.0f) {
+ costheta = -costheta;
+ q1 = -q1;
+ }
+
if(costheta > 0.9995f) {
+ /* linear interpolation in degenerate case */
return normalize((1.0f - t)*q1 + t*q2);
}
else {
+ /* slerp */
float theta = acosf(clamp(costheta, -1.0f, 1.0f));
float thetap = theta * t;
float4 qperp = normalize(q2 - q1 * costheta);
@@ -375,11 +384,37 @@ __device void transform_motion_interpolate(Transform *tfm, const MotionTransform
{
Transform decomp;
- decomp.x = quat_interpolate(motion->pre.x, motion->post.x, t);
- decomp.y = (1.0f - t)*motion->pre.y + t*motion->post.y;
- decomp.z = (1.0f - t)*motion->pre.z + t*motion->post.z;
- decomp.w = (1.0f - t)*motion->pre.w + t*motion->post.w;
+ /* 3 point bezier curve interpolation for position */
+ float3 Ppre = float4_to_float3(motion->pre.y);
+ float3 Pmid = float4_to_float3(motion->mid.y);
+ float3 Ppost = float4_to_float3(motion->post.y);
+
+ float3 Pcontrol = 2.0f*Pmid - 0.5f*(Ppre + Ppost);
+ float3 P = Ppre*t*t + Pcontrol*2.0f*t*(1.0f - t) + Ppost*(1.0f - t)*(1.0f - t);
+
+ decomp.y.x = P.x;
+ decomp.y.y = P.y;
+ decomp.y.z = P.z;
+
+ /* linear interpolation for rotation and scale */
+ if(t < 0.5f) {
+ t *= 2.0f;
+
+ decomp.x = quat_interpolate(motion->pre.x, motion->mid.x, t);
+ decomp.y.w = (1.0f - t)*motion->pre.y.w + t*motion->mid.y.w;
+ decomp.z = (1.0f - t)*motion->pre.z + t*motion->mid.z;
+ decomp.w = (1.0f - t)*motion->pre.w + t*motion->mid.w;
+ }
+ else {
+ t = (t - 0.5f)*2.0f;
+
+ decomp.x = quat_interpolate(motion->mid.x, motion->post.x, t);
+ decomp.y.w = (1.0f - t)*motion->mid.y.w + t*motion->post.y.w;
+ decomp.z = (1.0f - t)*motion->mid.z + t*motion->post.z;
+ decomp.w = (1.0f - t)*motion->mid.w + t*motion->post.w;
+ }
+ /* compose rotation, translation, scale into matrix */
transform_compose(tfm, &decomp);
}
@@ -390,7 +425,7 @@ __device_inline bool operator==(const MotionTransform& A, const MotionTransform&
return (A.pre == B.pre && A.post == B.post);
}
-void transform_motion_decompose(MotionTransform *decomp, const MotionTransform *motion);
+void transform_motion_decompose(MotionTransform *decomp, const MotionTransform *motion, const Transform *mid);
#endif
diff --git a/intern/cycles/util/util_types.h b/intern/cycles/util/util_types.h
index 5c6b9d5bb78..f2c02cadcbf 100644
--- a/intern/cycles/util/util_types.h
+++ b/intern/cycles/util/util_types.h
@@ -449,6 +449,7 @@ typedef enum AttributeStandard {
ATTR_STD_VERTEX_NORMAL,
ATTR_STD_FACE_NORMAL,
ATTR_STD_UV,
+ ATTR_STD_TANGENT,
ATTR_STD_GENERATED,
ATTR_STD_POSITION_UNDEFORMED,
ATTR_STD_POSITION_UNDISPLACED,
diff --git a/intern/decimation/CMakeLists.txt b/intern/decimation/CMakeLists.txt
deleted file mode 100644
index 73b67d7f3b1..00000000000
--- a/intern/decimation/CMakeLists.txt
+++ /dev/null
@@ -1,63 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ../container
- ../guardedalloc
- ../memutil
- ../moto/include
-)
-
-set(INC_SYS
-
-)
-
-set(SRC
- intern/LOD_EdgeCollapser.cpp
- intern/LOD_ExternNormalEditor.cpp
- intern/LOD_FaceNormalEditor.cpp
- intern/LOD_ManMesh2.cpp
- intern/LOD_MeshPrimitives.cpp
- intern/LOD_QSDecimator.cpp
- intern/LOD_QuadricEditor.cpp
- intern/LOD_decimation.cpp
-
- extern/LOD_decimation.h
- intern/LOD_DecimationClass.h
- intern/LOD_EdgeCollapser.h
- intern/LOD_ExternBufferEditor.h
- intern/LOD_ExternNormalEditor.h
- intern/LOD_FaceNormalEditor.h
- intern/LOD_ManMesh2.h
- intern/LOD_MeshBounds.h
- intern/LOD_MeshException.h
- intern/LOD_MeshPrimitives.h
- intern/LOD_QSDecimator.h
- intern/LOD_Quadric.h
- intern/LOD_QuadricEditor.h
-)
-
-blender_add_lib(bf_intern_decimate "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/intern/decimation/SConscript b/intern/decimation/SConscript
deleted file mode 100644
index 6f4befb3ffa..00000000000
--- a/intern/decimation/SConscript
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/usr/bin/python
-Import ('env')
-
-sources = env.Glob('intern/*.cpp')
-
-incs = '. ../moto/include ../container ../memutil ../guardedalloc'
-
-env.BlenderLib ('bf_intern_decimate', sources, Split(incs) , [], libtype=['core', 'player'], priority = [200, 100] )
diff --git a/intern/decimation/extern/LOD_decimation.h b/intern/decimation/extern/LOD_decimation.h
deleted file mode 100644
index 4c52cb18577..00000000000
--- a/intern/decimation/extern/LOD_decimation.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/extern/LOD_decimation.h
- * \ingroup decimation
- */
-
-
-/**
-
- * @author Laurence Bourn
- * @date 6/7/2001
- *
- * This is the external interface for the decimation module.
- */
-
-#ifndef __LOD_DECIMATION_H__
-#define __LOD_DECIMATION_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * External decimation structure
- */
-
-typedef struct LOD_Decimation_Info {
- float * vertex_buffer;
- float * vertex_normal_buffer;
- int * triangle_index_buffer;
- int vertex_num;
- int face_num;
- void * intern;
-} LOD_Decimation_Info;
-
-typedef LOD_Decimation_Info* LOD_Decimation_InfoPtr;
-
-/**
- * Create internal mesh representation from
- * LOD_Decimation_Info structure.
- * @return 1 on successful loading
- * @return 0 on failure
- * @warning This should be changed to return an enumeration
- * detailing the error encountered
- */
-
-extern int LOD_LoadMesh(LOD_Decimation_InfoPtr info);
-
-/**
- * Allocate and Compute internal data strucures required for
- * decimation.
- * @return 1 on successful computation of data
- * @return 0 on failure
- * @warning This should be changed to return an enumeration
- * detailing the error encountered
- */
-
-extern int LOD_PreprocessMesh(LOD_Decimation_InfoPtr info);
-
-/**
- * Once both the stages above have been completed
- * this function collapses a single edge in the mesh.
- * The LOD_Decimation_Info structure is updated
- * to represent the new mesh.
- * @return 1 if an edge was collapsed.
- * @return 0 if no suitable edge was found to be collapsable
- * You should stop calling this method in this case
- * @warning Do not expect that the order of polygons, vertices or
- * vertex normals will be preserved by this operation. This function
- * returns a packed array of polygons and vertices and so necessarily
- * the order will be different. This means you should not expect to
- * find the same polygon in the same place in the polygon array after
- * this function has been called.
- */
-
-extern int LOD_CollapseEdge(LOD_Decimation_InfoPtr info);
-
-/**
- * Free any memory the decimation process used
- * during the decimation process
- * @return 1 if internal data successfully freed
- * @return 0 if no data was freed
- */
-
-extern int LOD_FreeDecimationData(LOD_Decimation_InfoPtr);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // __LOD_DECIMATION_H__
-
diff --git a/intern/decimation/intern/LOD_DecimationClass.h b/intern/decimation/intern/LOD_DecimationClass.h
deleted file mode 100644
index ecf2e4e6790..00000000000
--- a/intern/decimation/intern/LOD_DecimationClass.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_DecimationClass.h
- * \ingroup decimation
- */
-
-
-#ifndef __LOD_DECIMATIONCLASS_H__
-#define __LOD_DECIMATIONCLASS_H__
-
-#include "MEM_SmartPtr.h"
-#include "MEM_NonCopyable.h"
-
-#include "LOD_ManMesh2.h"
-#include "LOD_QSDecimator.h"
-#include "LOD_ExternNormalEditor.h"
-#include "../extern/LOD_decimation.h"
-#include "LOD_ExternBufferEditor.h"
-
-
-class LOD_DecimationClass : public MEM_NonCopyable
-{
-public :
-
- enum {
- e_not_loaded,
- e_loaded,
- e_preprocessed
- } m_e_decimation_state;
-
-
- static
- LOD_DecimationClass *
- New(
- LOD_Decimation_InfoPtr extern_info
- ) {
- // create everything
-
- MEM_SmartPtr<LOD_DecimationClass> output(new LOD_DecimationClass());
- MEM_SmartPtr<LOD_ManMesh2> mesh(LOD_ManMesh2::New());
- MEM_SmartPtr<LOD_ExternBufferEditor> extern_editor(LOD_ExternBufferEditor::New(extern_info));
-
- if (mesh == NULL || extern_editor == NULL) return NULL;
- MEM_SmartPtr<LOD_ExternNormalEditor> normals(LOD_ExternNormalEditor::New(extern_info,mesh.Ref()));
-
- if (normals == NULL) return NULL;
- MEM_SmartPtr<LOD_QSDecimator> decimator(LOD_QSDecimator::New(
- mesh.Ref(),
- normals.Ref(),
- extern_editor.Ref()
- ));
- if (decimator == NULL || output == NULL) return NULL;
-
- output->m_mesh = mesh.Release();
- output->m_decimator = decimator.Release();
- output->m_normals = normals.Release();
- output->m_extern_editor = extern_editor.Release();
-
- return output.Release();
- }
-
- LOD_ManMesh2 &
- Mesh(
- ){
- return m_mesh.Ref();
- }
-
- LOD_QSDecimator &
- Decimator(
- ) {
- return m_decimator.Ref();
- }
-
- LOD_ExternNormalEditor &
- FaceEditor(
- ){
- return m_normals.Ref();
- }
-
-private :
-
- LOD_DecimationClass(
- ) : m_e_decimation_state(e_not_loaded) {
- };
-
- MEM_SmartPtr<LOD_ManMesh2> m_mesh;
- MEM_SmartPtr<LOD_QSDecimator> m_decimator;
- MEM_SmartPtr<LOD_ExternNormalEditor> m_normals;
- MEM_SmartPtr<LOD_ExternBufferEditor> m_extern_editor;
-};
-
-#endif
-
diff --git a/intern/decimation/intern/LOD_EdgeCollapser.cpp b/intern/decimation/intern/LOD_EdgeCollapser.cpp
deleted file mode 100644
index 1405d6f53fa..00000000000
--- a/intern/decimation/intern/LOD_EdgeCollapser.cpp
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_EdgeCollapser.cpp
- * \ingroup decimation
- */
-
-
-#include "LOD_EdgeCollapser.h"
-
-#include "LOD_ManMesh2.h"
-#include "CTR_TaggedSetOps.h"
-#include <algorithm>
-#include <functional>
-
-
-using namespace std;
-
-
- LOD_EdgeCollapser *
-LOD_EdgeCollapser::
-New(
-){
- return new LOD_EdgeCollapser();
-}
-
-
- bool
-LOD_EdgeCollapser::
-TJunctionTest(
- LOD_ManMesh2 &mesh,
- vector<LOD_EdgeInd> &e_v0v1,
- LOD_EdgeInd collapse_edge
-){
-
- // we need to copy the edges in e_v0v1 from the mesh
- // into a new buffer -> we are going to modify them
-
- int original_size = e_v0v1.size();
- if (original_size == 0) return true;
-
- vector<LOD_Edge> &edge_set = mesh.EdgeSet();
-
- LOD_VertexInd c_v0 = edge_set[collapse_edge].m_verts[0];
- LOD_VertexInd c_v1 = edge_set[collapse_edge].m_verts[1];
-
- vector<LOD_Edge> temp_edges;
- temp_edges.reserve(e_v0v1.size());
-
- vector<LOD_EdgeInd>::iterator edge_it = e_v0v1.begin();
- vector<LOD_EdgeInd>::const_iterator edge_end = e_v0v1.end();
-
- for (;edge_it != edge_end; ++edge_it) {
- temp_edges.push_back(edge_set[*edge_it]);
- }
-
- // in the copied edges replace all instances of c_v0 with c_v1
-
- vector<LOD_Edge>::iterator e_it = temp_edges.begin();
- vector<LOD_Edge>::const_iterator e_it_end = temp_edges.end();
-
- for (; e_it != e_it_end; ++e_it) {
-
- if (e_it->m_verts[0] == c_v0) {
- e_it->m_verts[0] = c_v1;
- }
- if (e_it->m_verts[1] == c_v0) {
- e_it->m_verts[1] = c_v1;
- }
-
- // normalize the edge
- if (int(e_it->m_verts[0]) > int(e_it->m_verts[1])) {
- LOD_EdgeInd temp = e_it->m_verts[0];
- e_it->m_verts[0] = e_it->m_verts[1];
- e_it->m_verts[1] = temp;
- }
- }
-
- // sort the edges using the edge less functional
-
- sort(temp_edges.begin(),temp_edges.end(),LOD_EdgeCollapser::less());
- // count the unique edges.
-
- e_it = temp_edges.begin();
- e_it_end = temp_edges.end();
-
- int coincedent_edges = 0;
-
- vector<LOD_Edge>::const_iterator last_edge = e_it;
- ++e_it;
-
- for (; e_it != e_it_end; ++e_it) {
-
- if ((e_it->m_verts[0] == last_edge->m_verts[0]) &&
- (e_it->m_verts[1] == last_edge->m_verts[1])
- ) {
- ++coincedent_edges;
- }
- last_edge = e_it;
- }
-
- // now if the collapse edge is a boundary edges
- // then we are alloved at most one coincedent edge
-
- // otherwise at most 2 coincedent edges
-
- if (edge_set[collapse_edge].BoundaryEdge()) {
- return (coincedent_edges > 1);
- } else {
- return (coincedent_edges > 2);
- }
-
-
-}
-
-
-
- bool
-LOD_EdgeCollapser::
-CollapseEdge(
- LOD_EdgeInd ei,
- LOD_ManMesh2 &mesh,
- vector<LOD_EdgeInd> & degenerate_edges,
- vector<LOD_FaceInd> & degenerate_faces,
- vector<LOD_VertexInd> & degenerate_vertices,
- vector<LOD_EdgeInd> & new_edges,
- vector<LOD_FaceInd> & update_faces,
- vector<LOD_VertexInd> & update_vertices
-){
-
- vector<LOD_Vertex> &verts = mesh.VertexSet();
- vector<LOD_Edge> &edges = mesh.EdgeSet();
- vector<LOD_TriFace> &faces = mesh.FaceSet();
-
- // shouldn't do this (use mesh interface instead!)
- LOD_VertexInd v0_ind = edges[ei].m_verts[0];
- LOD_VertexInd v1_ind = edges[ei].m_verts[1];
-#if 0
- LOD_Vertex &v0 = verts[v0_ind];
- LOD_Vertex &v1 = verts[v1_ind];
-#endif
- vector<vector<LOD_EdgeInd> > e_v01(2);
- e_v01[0].reserve(32);
- e_v01[1].reserve(32);
-
- mesh.VertexEdges(v0_ind,e_v01[0]);
- mesh.VertexEdges(v1_ind,e_v01[1]);
-
-
- // compute the union of e_v0 and e_v1 -> this is the degenerate edges of the collapse
- // we remove old edges and replace edges inside the collapse zone with new ones
-
- CTR_TaggedSetOps<LOD_EdgeInd,LOD_Edge>::Union(e_v01,edges,degenerate_edges);
-
- vector< vector<LOD_FaceInd> > p_v01(2);
- p_v01[0].reserve(32);
- p_v01[1].reserve(32);
-
- mesh.VertexFaces(v0_ind,p_v01[0]);
- mesh.VertexFaces(v1_ind,p_v01[1]);
-
- // compute the union of p_v0 anf p_v1
- vector<LOD_FaceInd> p_v0v1;
- p_v0v1.reserve(32);
-
- CTR_TaggedSetOps<LOD_FaceInd,LOD_TriFace>::Union(p_v01,faces,p_v0v1);
-
- // compute the union of all the edges in p_v0v1 this is the collapse zone
-
- vector<vector<LOD_EdgeInd> > e_input_vectors(p_v0v1.size());
-
- vector<LOD_FaceInd>::iterator p_v0v1_end = p_v0v1.end();
- vector<LOD_FaceInd>::iterator p_v0v1_start = p_v0v1.begin();
-
- vector<vector<LOD_FaceInd> >::iterator vector_insert_it = e_input_vectors.begin();
-
- for (;p_v0v1_start != p_v0v1_end; ++p_v0v1_start , ++vector_insert_it) {
- mesh.FaceEdges(*p_v0v1_start,*vector_insert_it);
- }
-
- vector<LOD_EdgeInd> collapse_zone;
- collapse_zone.reserve(32);
-
- CTR_TaggedSetOps<LOD_EdgeInd,LOD_Edge>::Union(e_input_vectors,edges,collapse_zone);
-
- // compute the ring edges = collpase_zone - e_v0v1
-
- vector<LOD_EdgeInd> edge_ring;
- edge_ring.reserve(32);
-
- CTR_TaggedSetOps<LOD_EdgeInd,LOD_Edge>::Difference(collapse_zone,degenerate_edges,edges,edge_ring);
-
- // T Junction test
- //////////////////
- // At this point we check to see if any of the polygons
- // in p_v0v1 are coninceddent - this leads
- // to errors later on if we try and insert a polygon
- // into the mesh to an edge which already has 2 polygons.
-
- // not that t junctions occur naturally from edge collapses
- // and are not just the result of coincedent polygons
- // for example consider collapsing an edge that forms part
- // of a triangular bottle neck.
-
- // Really we need to make sure that we don't create t-junctions.
-
- // I think that a sufficient test is to check the number of
- // coincedent edge pairs after a collapse. If it is more than 2
- // then collapsing the edge may result in an undeleted edge
- // sharing more than 2 polygons. This test probably is too
- // restictive though.
-
- // To perform this test we need to make a copy of the edges
- // in e_v0v1. We then apply the contraction to these edge
- // copies. Sort them using a function that places coincedent
- // edges next to each other. And then count the number
- // of coincedent pairs.
-
- // Of course we have to do this test before we change any of the
- // mesh -> so we can back out safely.
-
- if (TJunctionTest(mesh,degenerate_edges,ei)) return false;
-
- // Compute the set of possibly degenerate vertices
- // this is the union of all the vertices of polygons
- // of v0 and v1
-
- vector<LOD_FaceInd>::iterator face_it = p_v0v1.begin();
- vector<LOD_FaceInd>::const_iterator face_end = p_v0v1.end();
-
-
- vector<vector<LOD_VertexInd> > p_v0v1_vertices(p_v0v1.size());
-
- for (int i = 0; face_it != face_end; ++face_it, ++i) {
- mesh.FaceVertices(*face_it,p_v0v1_vertices[i]);
- }
-
- vector<LOD_VertexInd> vertex_ring;
- vertex_ring.reserve(32);
-
- CTR_TaggedSetOps<LOD_VertexInd,LOD_Vertex>::Union(p_v0v1_vertices,verts,vertex_ring);
-
- // remove all the internal edges e_v0v1 from the mesh.
- // for each edge remove the egde from it's vertices edge lists.
-
- vector<LOD_EdgeInd>::iterator edge_it = degenerate_edges.begin();
- vector<LOD_EdgeInd>::const_iterator edge_end = degenerate_edges.end();
-
- for (; !(edge_it == edge_end); ++edge_it) {
-
- LOD_EdgeInd ed = (*edge_it);
- LOD_Edge & edge = edges[ed];//*edge_it];
-
- verts[edge.m_verts[0]].RemoveEdge(ed);
- verts[edge.m_verts[1]].RemoveEdge(ed);
- }
-
- // we postpone deletion of the internal edges untill the end
- // this is because deleting edges invalidates all of the
- // EdgeInd vectors above.
-
-
- // now untie all the polygons in p_v0v1 from the edge ring
-
- // select all polygons in p_v0v1
-
- face_it = p_v0v1.begin();
- face_end = p_v0v1.end();
-
- for (;face_it != face_end; ++face_it) {
- faces[*face_it].SetSelectTag(true);
- }
-
- edge_it = edge_ring.begin();
- edge_end = edge_ring.end();
-
- for (;edge_it != edge_end; ++edge_it) {
- LOD_Edge & edge = edges[*edge_it];
-
- // presumably all edges in edge_ring point to at least
- // one polygon from p_v0v1
-
- if (!edge.m_faces[0].IsEmpty() && faces[edge.m_faces[0]].SelectTag()) {
- edge.m_faces[0].Invalidate();
- }
-
- if (!edge.m_faces[1].IsEmpty() && faces[edge.m_faces[1]].SelectTag()) {
- edge.m_faces[1].Invalidate();
- }
- }
-
- // deselect the faces
-
- face_it = p_v0v1.begin();
- face_end = p_v0v1.end();
-
- for (;face_it != face_end; ++face_it) {
- faces[*face_it].SetSelectTag(false);
- }
-
- // perform the edge collapse
- ////////////////////////////
-
- // iterate through the polygons of p_v0 and replace the vertex
- // index v0 with v1
-
- face_it = p_v01[0].begin();
- face_end = p_v01[0].end();
-
- for (;face_it != face_end; ++face_it) {
- faces[*face_it].SwapVertex(v0_ind,v1_ind);
- }
-
- face_it = p_v0v1.begin();
- face_end = p_v0v1.end();
-
- for (;face_it != face_end; ++face_it) {
- if (faces[*face_it].Degenerate()) {
- degenerate_faces.push_back(*face_it);
- } else {
- update_faces.push_back(*face_it);
- }
- }
-
- // Add all the non-degenerate faces back into the
- // mesh. Get a record of the new edges created in
- // this process.
-
- face_it = update_faces.begin();
- face_end = update_faces.end();
-
- for (;face_it != face_end; ++face_it) {
- mesh.ConnectTriangle(*face_it,new_edges);
- }
-
- // degenerate ring primitives
- /////////////////////////////
-
- // we now need to examine each of the edges on the ring
- // and work out if they are degenerate - if so we attempt
- // to delete them -> add them to the other edges to delete
- // in e_v0v1
-
- edge_it = edge_ring.begin();
- edge_end = edge_ring.end();
-
- for (;edge_it != edge_end; ++edge_it) {
- if (edges[*edge_it].Degenerate()) {
- degenerate_edges.push_back(*edge_it);
- }
- }
-
- // do the same for the ring vertices.
-
- vector<LOD_VertexInd>::iterator vertex_it = vertex_ring.begin();
- vector<LOD_VertexInd>::const_iterator vertex_end = vertex_ring.end();
-
- for (;vertex_it != vertex_end; ++vertex_it) {
- if (verts[*vertex_it].Degenerate()) {
- degenerate_vertices.push_back(*vertex_it);
- } else {
- update_vertices.push_back(*vertex_it);
- }
- }
-
- // we now know all the degenerate primitives
- // and the new primitives we have inserted into the mesh
-
- // We now delete the mesh primitives, mesh.DeleteXXXXXX() methods
- // assume that the index vectors are sorted into descending order.
- // we do that now.
-
- sort(degenerate_edges.begin(),degenerate_edges.end(),LOD_EdgeInd::greater());
- sort(degenerate_faces.begin(),degenerate_faces.end(),LOD_FaceInd::greater());
- sort(degenerate_vertices.begin(),degenerate_vertices.end(),LOD_VertexInd::greater());
-
-
- return true;
-
-}
-
-LOD_EdgeCollapser::
-LOD_EdgeCollapser(
-){
- // nothing to do
-}
diff --git a/intern/decimation/intern/LOD_EdgeCollapser.h b/intern/decimation/intern/LOD_EdgeCollapser.h
deleted file mode 100644
index 75a8b70f672..00000000000
--- a/intern/decimation/intern/LOD_EdgeCollapser.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_EdgeCollapser.h
- * \ingroup decimation
- */
-
-
-#ifndef __LOD_EDGECOLLAPSER_H__
-#define __LOD_EDGECOLLAPSER_H__
-
-// This is a helper class that collapses edges of a 2 - manifold mesh.
-
-#include "LOD_MeshPrimitives.h"
-#include "MEM_NonCopyable.h"
-#include <vector>
-#include <functional>
-
-class LOD_ManMesh2;
-
-class LOD_EdgeCollapser
-: public MEM_NonCopyable
-{
-
-public :
-
- static
- LOD_EdgeCollapser *
- New(
- );
-
- // returns via arguments the set of modified
- // verts,edges and faces.
-
- bool
- CollapseEdge(
- LOD_EdgeInd ei,
- LOD_ManMesh2 &mesh,
- std::vector<LOD_EdgeInd> & degenerate_edges,
- std::vector<LOD_FaceInd> & degenerate_faces,
- std::vector<LOD_VertexInd> & degenerate_vertices,
- std::vector<LOD_EdgeInd> & new_edges,
- std::vector<LOD_FaceInd> & update_faces,
- std::vector<LOD_VertexInd> & update_vertices
- );
-
-private :
-
- LOD_EdgeCollapser(
- );
-
- // Test to see if the result of collapsing the
- // edge produces 2 junctions in the mesh i.e. where
- // an edge is shared by more than 2 polygons
-
- // We count the number of coincedent edge pairs that
- // result from the collapse of collapse_edge.
-
- // If collapse edge is a boundary edge then the number of
- // coincedent pairs should be 1
- // else it should be 2.
-
- bool
- TJunctionTest(
- LOD_ManMesh2 &mesh,
- std::vector<LOD_EdgeInd> &e_v0v1,
- LOD_EdgeInd collapse_edge
- );
-
- // here's the definition of the sort function
- // we use to determine coincedent edges
-
- // assumes the edges are normalized i.e. m_verts[0] <= m_verts[1]
-
- struct less : std::binary_function<LOD_Edge, LOD_Edge, bool> {
- bool
- operator()(
- const LOD_Edge& a,
- const LOD_Edge& b
- ) const {
-
- if (int(a.m_verts[0]) == int(b.m_verts[0])) {
- return (int(a.m_verts[1]) < int(b.m_verts[1]));
- } else {
- return (int(a.m_verts[0]) < int(b.m_verts[0]));
- }
- }
- };
-
-};
-
-#endif
-
diff --git a/intern/decimation/intern/LOD_ExternBufferEditor.h b/intern/decimation/intern/LOD_ExternBufferEditor.h
deleted file mode 100644
index c903b255812..00000000000
--- a/intern/decimation/intern/LOD_ExternBufferEditor.h
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_ExternBufferEditor.h
- * \ingroup decimation
- */
-
-
-/**
-
- * Copyright (C) 2001 NaN Technologies B.V.
- */
-
-#ifndef __LOD_EXTERNBUFFEREDITOR_H__
-#define __LOD_EXTERNBUFFEREDITOR_H__
-
-#include "LOD_MeshPrimitives.h"
-#include <vector>
-#include "LOD_ManMesh2.h"
-#include "../extern/LOD_decimation.h"
-
-
-// This class syncs external vertex/face buffers
-// with the internal mesh representation during
-// decimation.
-
-class LOD_ExternBufferEditor
-{
-
-public :
-
- static
- LOD_ExternBufferEditor *
- New(
- LOD_Decimation_InfoPtr extern_info
- ){
- if (extern_info == NULL) return NULL;
- return new LOD_ExternBufferEditor(extern_info);
- }
-
- // update the external vertex buffer with vertices
- // from the mesh
-
- void
- CopyModifiedVerts(
- LOD_ManMesh2 & mesh,
- const std::vector<LOD_VertexInd> & mod_vertices
- ){
-
- std::vector<LOD_VertexInd>::const_iterator v_start = mod_vertices.begin();
- std::vector<LOD_VertexInd>::const_iterator v_end = mod_vertices.end();
-
- std::vector<LOD_Vertex> & mesh_verts = mesh.VertexSet();
-
- float * const extern_vertex_ptr = m_extern_info->vertex_buffer;
-
- for (; v_start != v_end; ++v_start) {
- float * mod_vert = extern_vertex_ptr + int(*v_start)*3;
- mesh_verts[*v_start].CopyPosition(mod_vert);
- }
- }
-
- // update the external face buffer with faces from the mesh
-
- void
- CopyModifiedFaces(
- LOD_ManMesh2 & mesh,
- const std::vector<LOD_FaceInd> & mod_faces
- ){
-
- std::vector<LOD_FaceInd>::const_iterator f_start = mod_faces.begin();
- std::vector<LOD_FaceInd>::const_iterator f_end = mod_faces.end();
-
- std::vector<LOD_TriFace> &mesh_faces = mesh.FaceSet();
-
- int * const extern_face_ptr = m_extern_info->triangle_index_buffer;
-
- for (; f_start != f_end; ++f_start) {
- int *mod_face = extern_face_ptr + 3*int(*f_start);
- mesh_faces[*f_start].CopyVerts(mod_face);
- }
- }
-
-
- // Copy the last vertex over the vertex specified by
- // vi. Decrement the size of the vertex array
-
- void
- CopyBackVertex(
- LOD_VertexInd vi
- ){
-
- float * const extern_vertex_ptr = m_extern_info->vertex_buffer;
- int * extern_vertex_num = &(m_extern_info->vertex_num);
-
- float * last_external_vert = extern_vertex_ptr + 3*((*extern_vertex_num) - 1);
- float * external_vert = extern_vertex_ptr + 3*int(vi);
-
- external_vert[0] = last_external_vert[0];
- external_vert[1] = last_external_vert[1];
- external_vert[2] = last_external_vert[2];
-
- *extern_vertex_num -=1;
- }
-
- // Copy the last face over the face specified by fi
- // Decrement the size of the face array
-
- void
- CopyBackFace(
- LOD_FaceInd fi
- ) {
- int * const extern_face_ptr = m_extern_info->triangle_index_buffer;
- int * extern_face_num = &(m_extern_info->face_num);
-
- int * last_external_face = extern_face_ptr + 3*((*extern_face_num) -1);
- int * external_face = extern_face_ptr + 3*int(fi);
- external_face[0] = last_external_face[0];
- external_face[1] = last_external_face[1];
- external_face[2] = last_external_face[2];
-
- *extern_face_num -=1;
- }
-
-
-private :
-
- LOD_ExternBufferEditor(
- LOD_Decimation_InfoPtr extern_info
- ) :
- m_extern_info (extern_info)
- {
- }
-
- LOD_Decimation_InfoPtr const m_extern_info;
-
-};
-
-#endif
-
diff --git a/intern/decimation/intern/LOD_ExternNormalEditor.cpp b/intern/decimation/intern/LOD_ExternNormalEditor.cpp
deleted file mode 100644
index 90033fe672b..00000000000
--- a/intern/decimation/intern/LOD_ExternNormalEditor.cpp
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_ExternNormalEditor.cpp
- * \ingroup decimation
- */
-
-
-#include "LOD_ExternNormalEditor.h"
-#include <vector>
-
-using namespace std;
-
-
-LOD_ExternNormalEditor::
-LOD_ExternNormalEditor(
- LOD_Decimation_InfoPtr extern_info,
- LOD_ManMesh2 &mesh
-) :
- m_mesh(mesh),
- m_extern_info (extern_info)
-{
-}
-
- LOD_ExternNormalEditor *
-LOD_ExternNormalEditor::
-New(
- LOD_Decimation_InfoPtr extern_info,
- LOD_ManMesh2 &mesh
-){
- if (extern_info == NULL) return NULL;
-
- MEM_SmartPtr<LOD_ExternNormalEditor> output(new LOD_ExternNormalEditor(extern_info,mesh));
-
- int face_num = mesh.FaceSet().size();
-
- MEM_SmartPtr<vector<MT_Vector3> > normals(new vector<MT_Vector3>);
-
- if (output == NULL ||
- normals == NULL
- ) {
- return NULL;
- }
-
- normals->reserve(face_num);
- output->m_normals = normals.Release();
-
- return output.Release();
-};
-
-
- void
-LOD_ExternNormalEditor::
-Remove(
- std::vector<LOD_FaceInd> &sorted_faces
-){
- // assumes a collection of faces sorted in descending order .
-
- vector<MT_Vector3> & normals = m_normals.Ref();
-
- vector<LOD_FaceInd>::const_iterator it_start = sorted_faces.begin();
- vector<LOD_FaceInd>::const_iterator it_end = sorted_faces.end();
-
- for (; it_start != it_end; ++it_start) {
-
- if (normals.size() > 0) {
- MT_Vector3 temp = normals[*it_start];
-
- normals[*it_start] = normals.back();
- normals.back() = temp;
-
- normals.pop_back();
- }
-
- // FIXME - throw exception
- }
-}
-
-
- void
-LOD_ExternNormalEditor::
-Add(
-){
- MT_Vector3 zero(0.0f,0.0f,0.0f);
- m_normals->push_back(zero);
-};
-
- void
-LOD_ExternNormalEditor::
-Update(
- std::vector<LOD_FaceInd> &sorted_faces
-){
- vector<MT_Vector3> & normals = m_normals.Ref();
-
- vector<LOD_FaceInd>::const_iterator it_start = sorted_faces.begin();
- vector<LOD_FaceInd>::const_iterator it_end = sorted_faces.end();
-
- const vector<LOD_TriFace> &faces = m_mesh.FaceSet();
-
- for (; it_start != it_end; ++it_start) {
- normals[*it_start] = ComputeNormal(faces[*it_start]);
- }
-};
-
-
-
-
-// vertex normals
-/////////////////
-
- void
-LOD_ExternNormalEditor::
-RemoveVertexNormals(
- std::vector<LOD_VertexInd> &sorted_verts
-){
-
- float * vertex_normals = m_extern_info->vertex_normal_buffer;
-
- // assumption here that the vertexs normal number corresponds with
- // the number of vertices !
-
- int vertex_normal_num = m_extern_info->vertex_num;
-
- vector<LOD_VertexInd>::const_iterator it_start = sorted_verts.begin();
- vector<LOD_VertexInd>::const_iterator it_end = sorted_verts.end();
-
- for (; it_start != it_end; ++it_start) {
-
- if (vertex_normal_num > 0) {
- float * vertex_normal = vertex_normals + int(*it_start)*3;
- float * last_vertex = vertex_normals + ((vertex_normal_num-1)*3);
-
- MT_Vector3 last_v(last_vertex);
- last_v.getValue(vertex_normal);
- vertex_normal_num--;
- }
-
- // FIXME - through exception
- }
-};
-
-
-
- void
-LOD_ExternNormalEditor::
-UpdateVertexNormals(
- std::vector<LOD_VertexInd> &sorted_verts
-){
- float * vertex_normals = m_extern_info->vertex_normal_buffer;
-
- vector<LOD_VertexInd>::const_iterator it_start = sorted_verts.begin();
- vector<LOD_VertexInd>::const_iterator it_end = sorted_verts.end();
-
- for (; it_start != it_end; ++it_start) {
- MT_Vector3 temp = ComputeVertexNormal(*it_start);
- float * vertex_normal = vertex_normals + int(*it_start)*3;
- temp.getValue(vertex_normal);
- }
-}
-
-// Editor specific methods
-//////////////////////////
-
- void
-LOD_ExternNormalEditor::
-BuildNormals(
-) {
- const vector<LOD_TriFace> &faces = m_mesh.FaceSet();
- vector<MT_Vector3> & normals = m_normals.Ref();
-
- int face_num = faces.size();
- int cur_face = 0;
-
- for (; cur_face < face_num; ++cur_face) {
-
- MT_Vector3 new_normal = ComputeNormal(faces[cur_face]);
- normals.push_back(new_normal);
- }
-}
-
-const
- MT_Vector3
-LOD_ExternNormalEditor::
-ComputeNormal(
- const LOD_TriFace &face
-) const {
-
- const vector<LOD_Vertex> &verts = m_mesh.VertexSet();
-
- MT_Vector3 vec1 =
- verts[face.m_verts[1]].pos -
- verts[face.m_verts[0]].pos;
-
- MT_Vector3 vec2 =
- verts[face.m_verts[2]].pos -
- verts[face.m_verts[1]].pos;
-
- vec1 = vec1.cross(vec2);
-
- if (!vec1.fuzzyZero()) {
- vec1.normalize();
- return (vec1);
- } else {
- return (MT_Vector3(1.0,0,0));
- }
-}
-
-const
- MT_Vector3
-LOD_ExternNormalEditor::
-ComputeVertexNormal(
- const LOD_VertexInd v
-) const {
-
- // average the face normals surrounding this
- // vertex and normalize
- // vector<LOD_Vertex> &verts = m_mesh.VertexSet(); /*unused*/
- const vector<MT_Vector3> & face_normals = m_normals.Ref();
-
- vector<LOD_FaceInd> vertex_faces;
- vertex_faces.reserve(32);
-
- m_mesh.VertexFaces(v,vertex_faces);
-
- MT_Vector3 normal(0,0,0);
-
- vector<LOD_FaceInd>::const_iterator face_it = vertex_faces.begin();
- vector<LOD_FaceInd>::const_iterator face_end = vertex_faces.end();
-
- for (; face_it != face_end; ++face_it) {
- normal += face_normals[*face_it];
- }
-
- if (!normal.fuzzyZero()) {
- normal.normalize();
- return (normal);
- } else {
- return (MT_Vector3(1.0,0,0));
- }
-}
diff --git a/intern/decimation/intern/LOD_ExternNormalEditor.h b/intern/decimation/intern/LOD_ExternNormalEditor.h
deleted file mode 100644
index 52135196dc5..00000000000
--- a/intern/decimation/intern/LOD_ExternNormalEditor.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_ExternNormalEditor.h
- * \ingroup decimation
- */
-
-
-#ifndef __LOD_EXTERNNORMALEDITOR_H__
-#define __LOD_EXTERNNORMALEDITOR_H__
-
-#include "MEM_NonCopyable.h"
-#include "LOD_ManMesh2.h"
-#include "MT_Vector3.h"
-#include "../extern/LOD_decimation.h"
-
-class LOD_ExternNormalEditor : public MEM_NonCopyable
-{
-
-public :
-
- // Creation
- ///////////
-
- static
- LOD_ExternNormalEditor *
- New(
- LOD_Decimation_InfoPtr,
- LOD_ManMesh2 &mesh
- );
-
- // Property editor interface
- ////////////////////////////
-
-
- // Faces
- ////////
- void
- Remove(
- std::vector<LOD_FaceInd> &sorted_faces
- );
-
- void
- Add(
- );
-
- void
- Update(
- std::vector<LOD_FaceInd> &sorted_faces
- );
-
- const
- std::vector<MT_Vector3> &
- Normals(
- ) const {
- return m_normals.Ref();
- };
-
-
- // vertex normals
- /////////////////
-
- void
- RemoveVertexNormals(
- std::vector<LOD_VertexInd> &sorted_verts
- );
-
-
- void
- UpdateVertexNormals(
- std::vector<LOD_VertexInd> &sorted_verts
- );
-
- // Editor specific methods
- //////////////////////////
-
- void
- BuildNormals(
- );
-
-
-private :
-
- MEM_SmartPtr<std::vector<MT_Vector3> > m_normals;
-
- LOD_ManMesh2 &m_mesh;
- LOD_Decimation_InfoPtr m_extern_info;
-
-private :
-
-
- LOD_ExternNormalEditor(
- LOD_Decimation_InfoPtr extern_info,
- LOD_ManMesh2 &mesh
- );
-
- const
- MT_Vector3
- ComputeNormal(
- const LOD_TriFace &face
- ) const;
-
- const
- MT_Vector3
- ComputeVertexNormal (
- const LOD_VertexInd vi
- ) const;
-};
-
-#endif
-
diff --git a/intern/decimation/intern/LOD_FaceNormalEditor.cpp b/intern/decimation/intern/LOD_FaceNormalEditor.cpp
deleted file mode 100644
index 430406a6d63..00000000000
--- a/intern/decimation/intern/LOD_FaceNormalEditor.cpp
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_FaceNormalEditor.cpp
- * \ingroup decimation
- */
-
-
-// implementation of LOD_FaceNormalEditor.h
-
-///////////////////////////////////////
-#include "LOD_FaceNormalEditor.h"
-
-using namespace std;
-
-LOD_FaceNormalEditor::
-LOD_FaceNormalEditor(
- LOD_ManMesh2 & mesh
-) : m_mesh(mesh) {
-};
-
- LOD_FaceNormalEditor *
-LOD_FaceNormalEditor::
-New(
- LOD_ManMesh2 &mesh
-){
- // build a set of normals of the same size
- // as the number of polys in the mesh
-
- MEM_SmartPtr<LOD_FaceNormalEditor> output(new LOD_FaceNormalEditor(mesh));
-
- int face_num = mesh.FaceSet().size();
-
- MEM_SmartPtr<vector<MT_Vector3> > normals(new vector<MT_Vector3>);
- MEM_SmartPtr<vector<MT_Vector3> > vertex_normals(new vector<MT_Vector3>);
-
- if (output == NULL ||
- normals == NULL
- ) {
- return NULL;
- }
-
- normals->reserve(face_num);
- vertex_normals->reserve(mesh.VertexSet().size());
- output->m_normals = normals.Release();
- output->m_vertex_normals = vertex_normals.Release();
-
- return output.Release();
-};
-
-
-// Property editor interface
-////////////////////////////
-
- void
-LOD_FaceNormalEditor::
-Remove(
- std::vector<LOD_FaceInd> &sorted_faces
-){
-
- // assumes a collection of faces sorted in descending order .
-
- vector<MT_Vector3> & normals = m_normals.Ref();
-
- vector<LOD_FaceInd>::const_iterator it_start = sorted_faces.begin();
- vector<LOD_FaceInd>::const_iterator it_end = sorted_faces.end();
-
- for (; it_start != it_end; ++it_start) {
-
- if (normals.size() > 0) {
- MT_Vector3 temp = normals[*it_start];
-
- normals[*it_start] = normals.back();
- normals.back() = temp;
-
- normals.pop_back();
- }
-
- // FIXME - through exception
- }
-}
-
-
- void
-LOD_FaceNormalEditor::
-Add(
-){
- MT_Vector3 zero(0.0f,0.0f,0.0f);
- m_normals->push_back(zero);
-}
-
- void
-LOD_FaceNormalEditor::
-Update(
- std::vector<LOD_FaceInd> &sorted_faces
-){
-
- vector<MT_Vector3> & normals = m_normals.Ref();
-
- vector<LOD_FaceInd>::const_iterator it_start = sorted_faces.begin();
- vector<LOD_FaceInd>::const_iterator it_end = sorted_faces.end();
-
- const vector<LOD_TriFace> &faces = m_mesh.FaceSet();
-
- for (; it_start != it_end; ++it_start) {
- normals[*it_start] = ComputeNormal(faces[*it_start]);
- }
-};
-
-// vertex normals
-/////////////////
-
-
- void
-LOD_FaceNormalEditor::
-RemoveVertexNormals(
- vector<LOD_VertexInd> &sorted_verts
-){
- vector<MT_Vector3> & vertex_normals = m_vertex_normals.Ref();
-
- vector<LOD_VertexInd>::const_iterator it_start = sorted_verts.begin();
- vector<LOD_VertexInd>::const_iterator it_end = sorted_verts.end();
-
- for (; it_start != it_end; ++it_start) {
-
- if (vertex_normals.size() > 0) {
- MT_Vector3 temp = vertex_normals[*it_start];
-
- vertex_normals[*it_start] = vertex_normals.back();
- vertex_normals.back() = temp;
-
- vertex_normals.pop_back();
- }
-
- // FIXME - through exception
- }
-};
-
- void
-LOD_FaceNormalEditor::
-UpdateVertexNormals(
- vector<LOD_VertexInd> &sorted_verts
-){
- vector<MT_Vector3> & vertex_normals = m_vertex_normals.Ref();
-
- vector<LOD_VertexInd>::const_iterator it_start = sorted_verts.begin();
- vector<LOD_VertexInd>::const_iterator it_end = sorted_verts.end();
-
- for (; it_start != it_end; ++it_start) {
- vertex_normals[*it_start] = ComputeVertexNormal(*it_start);
- }
-}
-
-
-
-// Editor specific methods
-//////////////////////////
-
- void
-LOD_FaceNormalEditor::
-BuildNormals(
-){
-
- const vector<LOD_TriFace> &faces = m_mesh.FaceSet();
- vector<MT_Vector3> & normals = m_normals.Ref();
-
- int face_num = faces.size();
- int cur_face = 0;
-
- for (; cur_face < face_num; ++cur_face) {
-
- MT_Vector3 new_normal = ComputeNormal(faces[cur_face]);
- normals.push_back(new_normal);
- }
- // now build the vertex normals
-
- vector<MT_Vector3> & vertex_normals = m_vertex_normals.Ref();
- const vector<LOD_Vertex> &verts = m_mesh.VertexSet();
-
- int vertex_num = verts.size();
- int cur_vertex = 0;
-
- for (; cur_vertex < vertex_num; ++cur_vertex) {
- MT_Vector3 new_normal = ComputeVertexNormal(cur_vertex);
- vertex_normals.push_back(new_normal);
- }
-}
-
-const
- MT_Vector3
-LOD_FaceNormalEditor::
-ComputeNormal(
- const LOD_TriFace &face
-) const {
-
- const vector<LOD_Vertex> &verts = m_mesh.VertexSet();
-
- MT_Vector3 vec1 =
- verts[face.m_verts[1]].pos -
- verts[face.m_verts[0]].pos;
-
- MT_Vector3 vec2 =
- verts[face.m_verts[2]].pos -
- verts[face.m_verts[1]].pos;
-
- vec1 = vec1.cross(vec2);
-
- if (!vec1.fuzzyZero()) {
- vec1.normalize();
- return (vec1);
- } else {
- return (MT_Vector3(1.0,0,0));
- }
-}
-
-const
- MT_Vector3
-LOD_FaceNormalEditor::
-ComputeVertexNormal(
- const LOD_VertexInd v
-) const {
-
- // average the face normals surrounding this
- // vertex and normalize
- const vector<MT_Vector3> & face_normals = m_normals.Ref();
-
- vector<LOD_FaceInd> vertex_faces;
- vertex_faces.reserve(32);
-
- m_mesh.VertexFaces(v,vertex_faces);
-
- MT_Vector3 normal(0,0,0);
-
- vector<LOD_FaceInd>::const_iterator face_it = vertex_faces.begin();
- vector<LOD_FaceInd>::const_iterator face_end = vertex_faces.end();
-
- for (; face_it != face_end; ++face_it) {
- normal += face_normals[*face_it];
- }
-
- if (!normal.fuzzyZero()) {
- normal.normalize();
- return (normal);
- } else {
- return (MT_Vector3(1.0,0,0));
- }
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/intern/decimation/intern/LOD_FaceNormalEditor.h b/intern/decimation/intern/LOD_FaceNormalEditor.h
deleted file mode 100644
index a221ab0bd7a..00000000000
--- a/intern/decimation/intern/LOD_FaceNormalEditor.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_FaceNormalEditor.h
- * \ingroup decimation
- */
-
-
-#ifndef __LOD_FACENORMALEDITOR_H__
-#define __LOD_FACENORMALEDITOR_H__
-
-#include "MEM_NonCopyable.h"
-#include "LOD_ManMesh2.h"
-#include "MT_Vector3.h"
-
-
-class LOD_FaceNormalEditor : public MEM_NonCopyable
-{
-
-public :
-
- // Creation
- ///////////
-
- static
- LOD_FaceNormalEditor *
- New(
- LOD_ManMesh2 &mesh
- );
-
- // Property editor interface
- ////////////////////////////
-
-
- // Faces
- ////////
- void
- Remove(
- std::vector<LOD_FaceInd> &sorted_faces
- );
-
- void
- Add(
- );
-
- void
- Update(
- std::vector<LOD_FaceInd> &sorted_faces
- );
-
-
- // vertex normals
- /////////////////
-
- void
- RemoveVertexNormals(
- std::vector<LOD_VertexInd> &sorted_verts
- );
-
-
- void
- UpdateVertexNormals(
- std::vector<LOD_VertexInd> &sorted_verts
- );
-
-
-
- const
- std::vector<MT_Vector3> &
- Normals(
- ) const {
- return m_normals.Ref();
- };
-
-
- const
- std::vector<MT_Vector3> &
- VertexNormals(
- ) const {
- return m_vertex_normals.Ref();
- };
-
- // Editor specific methods
- //////////////////////////
-
- void
- BuildNormals(
- );
-
-
-private :
-
- MEM_SmartPtr<std::vector<MT_Vector3> > m_normals;
- MEM_SmartPtr<std::vector<MT_Vector3> > m_vertex_normals;
-
- LOD_ManMesh2 &m_mesh;
-
-private :
-
-
- LOD_FaceNormalEditor(LOD_ManMesh2 &mesh);
-
- const
- MT_Vector3
- ComputeNormal(
- const LOD_TriFace &face
- ) const;
-
- const
- MT_Vector3
- ComputeVertexNormal (
- const LOD_VertexInd vi
- ) const;
-
-
-
-};
-
-#endif
-
diff --git a/intern/decimation/intern/LOD_ManMesh2.cpp b/intern/decimation/intern/LOD_ManMesh2.cpp
deleted file mode 100644
index c618944162f..00000000000
--- a/intern/decimation/intern/LOD_ManMesh2.cpp
+++ /dev/null
@@ -1,618 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_ManMesh2.cpp
- * \ingroup decimation
- */
-
-
-#include "LOD_ManMesh2.h"
-
-#include "MT_assert.h"
-#include <algorithm>
-#include "LOD_MeshException.h"
-#include "CTR_TaggedSetOps.h"
-#include "CTR_UHeap.h"
-#include "LOD_ExternBufferEditor.h"
-
-
-using namespace std;
-
-LOD_ManMesh2::
-LOD_ManMesh2(
-) :
- m_bbox_min(0,0,0),
- m_bbox_max(0,0,0)
-{
-}
-
-
- LOD_ManMesh2 *
-LOD_ManMesh2::
-New(
-){
- MEM_SmartPtr<LOD_ManMesh2> output(new LOD_ManMesh2());
- if (output == NULL) return NULL;
-
- // build the vertex, edge and face sets.
-
- MEM_SmartPtr<vector<LOD_Vertex> > verts(new vector<LOD_Vertex>);
- MEM_SmartPtr<vector<LOD_TriFace> > faces(new vector<LOD_TriFace>);
- MEM_SmartPtr<vector<LOD_Edge> > edges(new vector<LOD_Edge>);
-
- if ((faces == NULL) || (edges == NULL) || (verts == NULL)) {
- return NULL;
- }
-
- output->m_verts = verts.Release();
- output->m_faces = faces.Release();
- output->m_edges = edges.Release();
-
- return output.Release();
-}
-
-// take ownership of the vertices.
-
- bool
-LOD_ManMesh2::
-SetVertices(
- MEM_SmartPtr<vector<LOD_Vertex> > verts
-){
-
-
- // take ownership of vertices
- m_verts = verts;
-
- // create a polygon and edge buffer of half the size
- // and just use the automatic resizing feature of vector<>
- // to worry about the dynamic array resizing
-
- m_faces->clear();
- m_edges->clear();
-
- m_faces->reserve(m_verts->size()/2);
- m_edges->reserve(m_verts->size()/2);
-
- return true;
-
-}
-
-
-// add a triangle to the mesh
-
- void
-LOD_ManMesh2::
-AddTriangle(
- int verts[3]
-) {
-
- MT_assert(verts[0] < int(m_verts->size()));
- MT_assert(verts[1] < int(m_verts->size()));
- MT_assert(verts[2] < int(m_verts->size()));
-
- LOD_TriFace face;
- face.m_verts[0] = verts[0];
- face.m_verts[1] = verts[1];
- face.m_verts[2] = verts[2];
-
- LOD_FaceInd face_index = m_faces->size();
-
- m_faces->push_back(face);
-
- // now work out if any of the directed edges or their
- // companion edges exist already.
- // We go through the edges associated with each of the given vertices
-
- // the safest thing to do is iterate through each of the edge sets
- // check against each of the 2 other triangle edges to see if they are there
-
- vector<LOD_EdgeInd> new_edges;
- new_edges.reserve(3);
-
- InsertEdge(verts[0],verts[1],face_index,new_edges);
- InsertEdge(verts[1],verts[2],face_index,new_edges);
- InsertEdge(verts[2],verts[0],face_index,new_edges);
-
-}
-
-// Adds the index of any created edges to new_edges
-
- bool
-LOD_ManMesh2::
-InsertEdge(
- const LOD_VertexInd v1,
- const LOD_VertexInd v2,
- const LOD_FaceInd f,
- vector<LOD_EdgeInd> &new_edges
-){
-
- MT_assert(!v1.IsEmpty());
- MT_assert(!v2.IsEmpty());
- MT_assert(!f.IsEmpty());
-
- vector<LOD_Vertex> &verts = VertexSet();
- vector<LOD_Edge> &edges = EdgeSet();
-
- LOD_EdgeInd e;
-
- e = FindEdge(v1,v2);
-
- if (e.IsEmpty()) {
- // This edge does not exist -- make a new one
-
- LOD_Edge temp_e;
- temp_e.m_verts[0] = v1;
- temp_e.m_verts[1] = v2;
-
- e = m_edges->size();
-
- // set the face ptr for this half-edge
- temp_e.m_faces[0] = f;
-
- m_edges->push_back(temp_e);
-
- // add the edge index to it's vertices
-
- verts[v1].AddEdge(e);
- verts[v2].AddEdge(e);
-
- new_edges.push_back(e);
-
- } else {
-
- // edge already exists
- // insure that there is no polygon already
- // attached to the other side of this edge
-
- // swap the empty face pointer in edge with f
-
- LOD_Edge &edge = edges[e];
-
- edge.SwapFace(LOD_FaceInd::Empty(),f);
- }
-
-
- return true;
-
-}
-
- void
-LOD_ManMesh2::
-ConnectTriangle(
- LOD_FaceInd fi,
- std::vector<LOD_EdgeInd> & new_edges
-){
-
- vector<LOD_TriFace> &faces = FaceSet();
-
- MT_assert(!faces[fi].Degenerate());
-
- LOD_TriFace & face = faces[fi];
-
- InsertEdge(face.m_verts[0],face.m_verts[1],fi,new_edges);
- InsertEdge(face.m_verts[1],face.m_verts[2],fi,new_edges);
- InsertEdge(face.m_verts[2],face.m_verts[0],fi,new_edges);
-};
-
-
-
-
-// geometry access
-//////////////////
-
- vector<LOD_Vertex> &
-LOD_ManMesh2::
-VertexSet(
-) const {
- return m_verts.Ref();
-}
-
- vector<LOD_TriFace> &
-LOD_ManMesh2::
-FaceSet(
-) const {
- return m_faces.Ref();
-}
-
- vector<LOD_Edge> &
-LOD_ManMesh2::
-EdgeSet(
-) const {
- return m_edges.Ref();
-};
-
-LOD_ManMesh2::
-~LOD_ManMesh2(
-){
- //auto ptr takes care of vertex arrays etc.
-}
-
- LOD_EdgeInd
-LOD_ManMesh2::
-FindEdge(
- const LOD_VertexInd v1,
- const LOD_VertexInd v2
-) {
-
- vector<LOD_Vertex> &verts = VertexSet();
- vector<LOD_Edge> &edges = EdgeSet();
-
- LOD_Edge e;
- e.m_verts[0] = v1;
- e.m_verts[1] = v2;
-
- vector<LOD_EdgeInd> &v1_edges = verts[v1].m_edges;
- vector<LOD_EdgeInd>::const_iterator v1_end = v1_edges.end();
- vector<LOD_EdgeInd>::iterator v1_begin = v1_edges.begin();
-
- for (; v1_begin != v1_end; ++v1_begin) {
- if (edges[*v1_begin] == e) return *v1_begin;
- }
-
- return LOD_EdgeInd::Empty();
-}
-
-// face queries
-///////////////
-
- void
-LOD_ManMesh2::
-FaceVertices(
- LOD_FaceInd fi,
- vector<LOD_VertexInd> &output
-){
- const vector<LOD_TriFace> &faces = FaceSet();
- const LOD_TriFace & f = faces[fi];
-
- output.push_back(f.m_verts[0]);
- output.push_back(f.m_verts[1]);
- output.push_back(f.m_verts[2]);
-}
-
- void
-LOD_ManMesh2::
-FaceEdges(
- LOD_FaceInd fi,
- vector<LOD_EdgeInd> &output
-){
- const vector<LOD_TriFace> &faces = FaceSet();
- vector<LOD_Edge> &edges = EdgeSet();
- vector<LOD_Vertex> &verts = VertexSet();
-
- const LOD_TriFace & f = faces[fi];
- // intersect vertex edges
-
- vector<LOD_EdgeInd> & v0_edges = verts[f.m_verts[0]].m_edges;
- vector<LOD_EdgeInd> & v1_edges = verts[f.m_verts[1]].m_edges;
- vector<LOD_EdgeInd> & v2_edges = verts[f.m_verts[2]].m_edges;
-
- CTR_TaggedSetOps<LOD_EdgeInd,LOD_Edge>::IntersectPair(v0_edges,v1_edges,edges,output);
- CTR_TaggedSetOps<LOD_EdgeInd,LOD_Edge>::IntersectPair(v1_edges,v2_edges,edges,output);
- CTR_TaggedSetOps<LOD_EdgeInd,LOD_Edge>::IntersectPair(v2_edges,v0_edges,edges,output);
-
- MT_assert(output.size() == 3);
- if (output.size() != 3) {
- LOD_MeshException e(LOD_MeshException::e_non_manifold);
- throw(e);
- }
-}
-
-
-// edge queries
-///////////////
-
- void
-LOD_ManMesh2::
-EdgeVertices(
- LOD_EdgeInd ei,
- vector<LOD_VertexInd> &output
-){
- const vector<LOD_Edge> &edges = EdgeSet();
- const LOD_Edge & e = edges[ei];
-
- output.push_back(e.m_verts[0]);
- output.push_back(e.m_verts[1]);
-}
-
- void
-LOD_ManMesh2::
-EdgeFaces(
- LOD_EdgeInd ei,
- vector<LOD_FaceInd> &output
-){
- const vector<LOD_Edge> &edges = EdgeSet();
- const LOD_Edge & e = edges[ei];
-
- if (!e.m_faces[0].IsEmpty()) {
- output.push_back(e.m_faces[0]);
- }
- if (!e.m_faces[1].IsEmpty()) {
- output.push_back(e.m_faces[1]);
- }
-}
-
-// vertex queries
-/////////////////
-
- void
-LOD_ManMesh2::
-VertexEdges(
- LOD_VertexInd vi,
- vector<LOD_EdgeInd> &output
-){
- // iterate through the edges of v and push them onto the
- // output
-
- vector<LOD_Vertex> &verts = VertexSet();
-
- vector<LOD_EdgeInd> & v_edges = verts[vi].m_edges;
- vector<LOD_EdgeInd>::iterator v_it = v_edges.begin();
-
- for (; v_it != v_edges.end(); ++v_it) {
- output.push_back(*v_it);
- }
-}
-
- void
-LOD_ManMesh2::
-VertexFaces(
- LOD_VertexInd vi,
- vector<LOD_FaceInd> &output
-){
- const vector<LOD_Vertex> &verts = VertexSet();
- vector<LOD_Edge> &edges = EdgeSet();
- vector<LOD_TriFace> &faces = FaceSet();
-
- const vector<LOD_EdgeInd> &v_edges = verts[vi].m_edges;
- vector<LOD_EdgeInd>::const_iterator e_it = v_edges.begin();
-
- for (; e_it != v_edges.end(); ++e_it) {
-
- LOD_Edge &e = edges[*e_it];
-
- if ((!e.m_faces[0].IsEmpty()) && (!faces[e.m_faces[0]].SelectTag())) {
- output.push_back(e.m_faces[0]);
- faces[e.m_faces[0]].SetSelectTag(true);
- }
-
- if ((!e.m_faces[1].IsEmpty()) && (!faces[e.m_faces[1]].SelectTag())) {
- output.push_back(e.m_faces[1]);
- faces[e.m_faces[1]].SetSelectTag(true);
- }
- }
-
- vector<LOD_FaceInd>::iterator f_it = output.begin();
-
- for (; f_it != output.end(); ++f_it) {
- faces[*f_it].SetSelectTag(false);
- }
-};
-
- void
-LOD_ManMesh2::
-SetBBox(
- MT_Vector3 bbox_min,
- MT_Vector3 bbox_max
-){
- m_bbox_min = bbox_min;
- m_bbox_max = bbox_max;
-};
-
- void
-LOD_ManMesh2::
-SC_TriFace(
- LOD_FaceInd f
-){
- LOD_TriFace face = (*m_faces)[f];
-
- // check for unique vertices
-
- if (
- (face.m_verts[0] == face.m_verts[1]) ||
- (face.m_verts[1] == face.m_verts[2]) ||
- (face.m_verts[2] == face.m_verts[0])
- ) {
- MT_assert(false);
- }
-
-}
-
-
- void
-LOD_ManMesh2::
-SC_EdgeList(
- LOD_VertexInd v
-){
- vector<LOD_Edge> &edges = EdgeSet();
- vector<LOD_Vertex> &verts = VertexSet();
-
- vector<LOD_EdgeInd>::iterator e_it = verts[v].m_edges.begin();
-
- for (;e_it != verts[v].m_edges.end(); ++e_it) {
- MT_assert( (edges[*e_it].m_verts[0] == v) || (edges[*e_it].m_verts[1] == v));
- }
-
-};
-
- void
-LOD_ManMesh2::
-DeleteVertex(
- LOD_ExternBufferEditor & extern_editor,
- LOD_VertexInd v
-){
-
- vector<LOD_Edge> &edges = EdgeSet();
- vector<LOD_Vertex> &verts = VertexSet();
- vector<LOD_TriFace> &faces = FaceSet();
-
- // need to update all the edge and polygons pointing to
- // the last vertex in m_verts
-
- if (verts.size() == 1) {
- verts.clear();
- return;
- }
-
- LOD_VertexInd last = LOD_VertexInd(size_t(verts.end() - verts.begin() - 1));
-
- if (!(last == v)) {
-
- // we asume that v is already disconnected
-
- vector<LOD_FaceInd> v_faces;
- vector<LOD_EdgeInd> v_edges;
-
- v_faces.reserve(64);
- v_edges.reserve(64);
-
- VertexFaces(last,v_faces);
- VertexEdges(last,v_edges);
-
- // map the faces and edges to look at v
-
- vector<LOD_FaceInd>::iterator face_it = v_faces.begin();
-
- for(; face_it != v_faces.end(); ++face_it) {
- faces[*face_it].SwapVertex(last,v);
- }
- vector<LOD_EdgeInd>::iterator edge_it = v_edges.begin();
-
- for (; edge_it != v_edges.end(); ++edge_it) {
- edges[*edge_it].SwapVertex(last,v);
- }
-
- // copy the last vertex onto v and pop off the back.
-
- verts[v] = verts[last];
-
- // tidy external buffer
- extern_editor.CopyModifiedFaces(*this,v_faces);
- }
-
- verts.pop_back();
- extern_editor.CopyBackVertex(v);
-
-
-};
-
- void
-LOD_ManMesh2::
-DeleteEdge(
- LOD_EdgeInd e,
- CTR_UHeap<LOD_Edge> * heap
-){
- vector<LOD_Edge> &edges = EdgeSet();
- vector<LOD_Vertex> &verts = VertexSet();
-
- if (edges.size() == 1) {
- edges.clear();
- return;
- }
-
- LOD_EdgeInd last = LOD_EdgeInd(size_t(edges.end() - edges.begin() - 1));
-
- if (!(last == e)) {
- vector<LOD_EdgeInd> e_verts;
- e_verts.reserve(2);
- EdgeVertices(last,e_verts);
- // something is wrong if there arent two!
-
- verts[e_verts[0]].SwapEdge(last,e);
- verts[e_verts[1]].SwapEdge(last,e);
-
- // edges[e] should already have been removed from the heap
-
- MT_assert(edges[e].HeapPos() == -1);
-
- edges[e] = edges[last];
- // also have to swap there heap positions.!!!!!
-
- heap->HeapVector()[edges[e].HeapPos()] = e;
-
-
- }
- edges.pop_back();
-};
-
- void
-LOD_ManMesh2::
-DeleteFace(
- LOD_ExternBufferEditor & extern_editor,
- LOD_FaceInd f
-){
-
- vector<LOD_Edge> &edges = EdgeSet();
- vector<LOD_TriFace> &faces = FaceSet();
-
- if (faces.size() == 1) {
- faces.clear();
- return;
- }
-
- LOD_FaceInd last = LOD_FaceInd(size_t (faces.end() - faces.begin() - 1));
-
- if (!(last == f)) {
-
- // we have to update the edges which point to the last
- // face
-
- vector<LOD_EdgeInd> f_edges;
- f_edges.reserve(3);
-
- FaceEdges(last,f_edges);
-
- vector<LOD_EdgeInd>::iterator edge_it = f_edges.begin();
- vector<LOD_EdgeInd>::const_iterator edge_end = f_edges.end();
-
- for (; edge_it != edge_end; ++edge_it) {
- edges[*edge_it].SwapFace(last,f);
- }
-
- faces[f] = faces[last];
-
- }
- faces.pop_back();
-
- // tidy external buffers
- extern_editor.CopyBackFace(f);
-};
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/intern/decimation/intern/LOD_ManMesh2.h b/intern/decimation/intern/LOD_ManMesh2.h
deleted file mode 100644
index 5d4e1aff4e6..00000000000
--- a/intern/decimation/intern/LOD_ManMesh2.h
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_ManMesh2.h
- * \ingroup decimation
- */
-
-
-#ifndef __LOD_MANMESH2_H__
-#define __LOD_MANMESH2_H__
-
-#include "LOD_MeshPrimitives.h"
-#include "MEM_SmartPtr.h"
-#include <vector>
-
-template <class HeapType> class CTR_UHeap;
-
-class LOD_ExternBufferEditor;
-
-class LOD_ManMesh2 // Manifold 2 dimensional mesh
-{
-
-public:
-
- static
- LOD_ManMesh2 *
- New(
- );
-
- // take ownership of the vertices.
-
- bool
- SetVertices(
- MEM_SmartPtr<std::vector<LOD_Vertex> > verts
- );
-
- // Add a triangle to the mesh
-
- void
- AddTriangle(
- int verts[3]
- );
-
- void
- ConnectTriangle(
- LOD_FaceInd fi,
- std::vector<LOD_EdgeInd> & new_edges
- );
-
- // geometry access
- //////////////////
-
- std::vector<LOD_Vertex> &
- VertexSet(
- ) const;
-
- std::vector<LOD_TriFace> &
- FaceSet(
- ) const;
-
- std::vector<LOD_Edge> &
- EdgeSet(
- ) const;
-
- ~LOD_ManMesh2(
- );
-
- // local geometry queries
- /////////////////////////
-
- // face queries
- ///////////////
-
- void
- FaceVertices(
- LOD_FaceInd f,
- std::vector<LOD_VertexInd> &output
- );
-
- void
- FaceEdges(
- LOD_FaceInd f,
- std::vector<LOD_EdgeInd> &output
- );
-
- // edge queries
- ///////////////
-
- void
- EdgeVertices(
- LOD_EdgeInd e,
- std::vector<LOD_VertexInd> &output
- );
-
- void
- EdgeFaces(
- LOD_EdgeInd e,
- std::vector<LOD_FaceInd> &output
- );
-
- // vertex queries
- /////////////////
-
- void
- VertexEdges(
- LOD_VertexInd v,
- std::vector<LOD_EdgeInd> &output
- );
-
- void
- VertexFaces(
- LOD_VertexInd v,
- std::vector<LOD_FaceInd> &output
- );
-
- void
- SetBBox(
- MT_Vector3 bbox_min,
- MT_Vector3 bbox_max
- );
-
- MT_Vector3
- BBoxMin(
- ) const {
- return m_bbox_min;
- };
-
- MT_Vector3
- BBoxMax(
- ) const {
- return m_bbox_max;
- };
-
- // Remove a primitive from the mesh
- ///////////////////////////////////
-
- // These methods assume you have correctly
- // tidied up the index pointers in other primitives,
- // so that nothing refers to this object any more
-
- // These methods exchange the primitive with the
- // last primitive in the vector. It modifies everything
- // pointing to the last primitive correctly.
-
- // FIXME refactor extern editor out of primitive deletion
- // insead return a vector of primitives that need to be
- // modified and do this externally
-
- void
- DeleteVertex(
- LOD_ExternBufferEditor & extern_editor,
- LOD_VertexInd v
- );
-
- void
- DeleteEdge(
- LOD_EdgeInd e,
- CTR_UHeap<LOD_Edge> *heap
- );
-
- void
- DeleteFace(
- LOD_ExternBufferEditor & extern_editor,
- LOD_FaceInd f
- );
-
- // Sanity Check routines
- ////////////////////////
-
- // Make sure the edge sets and the vertex sets are
- // consistent
-
- void
- SC_TriFace(
- LOD_FaceInd f
- );
-
- // basic sanity checking of an edge list bails out if there are more than 1024
- // edges
-
- void
- SC_EdgeList(
- LOD_EdgeInd e
- );
-
-
- // Check to see that the edges of v1 and v2 are unique.
-
- bool
- SC_UniqueEdge(
- LOD_EdgeInd e
- );
-
-
-private :
-
-
- // Returns the edge index of the edge from v1 to v2.
- // Does this by searching the edge sets of v1 - but not v2.
- // If you are paranoid you should check both and make sure the
- // indices are the same. If the edge doe not exist edgeInd is empty.
-
- LOD_EdgeInd
- FindEdge(
- const LOD_VertexInd v1,
- const LOD_VertexInd v2
- );
-
- // Insert an edge into the mesh
- // Tie up the ptrs and create space for the edge
- // returns manifold errors - need to sort out memory edges
-
- bool
- InsertEdge(
- const LOD_VertexInd v1,
- const LOD_VertexInd v2,
- const LOD_FaceInd f,
- std::vector<LOD_EdgeInd> &new_edges
- );
-
-
-private :
-
- LOD_ManMesh2(
- );
-
- MEM_SmartPtr< std::vector<LOD_Vertex> > m_verts;
- MEM_SmartPtr< std::vector<LOD_TriFace> > m_faces;
- MEM_SmartPtr< std::vector<LOD_Edge> > m_edges;
-
- // not sure of these descrtiptions of the mesh should
- // reside in this class coz may lead to very bloated interface.
-
- MT_Vector3 m_bbox_min;
- MT_Vector3 m_bbox_max;
-
-
-};
-
-#endif
-
diff --git a/intern/decimation/intern/LOD_MeshBounds.h b/intern/decimation/intern/LOD_MeshBounds.h
deleted file mode 100644
index c95e6c7b61f..00000000000
--- a/intern/decimation/intern/LOD_MeshBounds.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_MeshBounds.h
- * \ingroup decimation
- */
-
-
-#ifndef __LOD_MESHBOUNDS_H__
-#define __LOD_MESHBOUNDS_H__
-
-#include "MEM_SmartPtr.h"
-#include "LOD_MeshPrimitives.h"
-#include "LOD_ManMesh2.h"
-#include "MT_assert.h"
-
-// simple class to compute the mesh bounds of a manifold mesh,
-
-class LOD_MeshBounds {
-
-public :
- static
- LOD_MeshBounds *
- New(
- ){
-
- MEM_SmartPtr<LOD_MeshBounds> output(new LOD_MeshBounds());
- return output.Release();
- }
-
- void
- ComputeBounds(
- const LOD_ManMesh2 * mesh
- ){
- MT_assert(mesh!=NULL);
- MT_assert(mesh->VertexSet().size() > 0);
-
- const std::vector<LOD_Vertex> &verts = mesh->VertexSet();
-
- m_min = verts[0].pos;
- m_max = verts[0].pos;
-
- // iterate through the verts
-
- int t;
- const int size = verts.size();
-
- for (t=1; t< size ; ++t) {
-
- UpdateBounds(verts[t].pos,m_min,m_max);
- }
- }
-
- MT_Vector3
- Min(
- ) const {
- return m_min;
- }
-
- MT_Vector3
- Max(
- ) const {
- return m_max;
- }
-
-private :
-
- void
- UpdateBounds(
- MT_Vector3 vertex,
- MT_Vector3& min,
- MT_Vector3& max
- ) {
- if (vertex.x() < min.x()) {
- min.x() = vertex.x();
- } else
- if (vertex.x() > max.x()) {
- max.x()= vertex.x();
- }
-
- if (vertex.y() < min.y()) {
- min.y() = vertex.y();
- } else
- if (vertex.y() > max.y()) {
- max.y()= vertex.y();
- }
-
- if (vertex.z() < min.z()) {
- min.z() = vertex.z();
- } else
- if (vertex.z() > max.z()) {
- max.z()= vertex.z();
- }
- }
-
- LOD_MeshBounds(
- ) :
- m_min(0,0,0),
- m_max(0,0,0)
- {
- };
-
- MT_Vector3 m_min;
- MT_Vector3 m_max;
-
-};
-
-#endif
-
diff --git a/intern/decimation/intern/LOD_MeshPrimitives.cpp b/intern/decimation/intern/LOD_MeshPrimitives.cpp
deleted file mode 100644
index ee4e4c120fc..00000000000
--- a/intern/decimation/intern/LOD_MeshPrimitives.cpp
+++ /dev/null
@@ -1,404 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_MeshPrimitives.cpp
- * \ingroup decimation
- */
-
-
-#include "LOD_MeshPrimitives.h"
-
-#include "MT_assert.h"
-#include "LOD_MeshException.h"
-#include <algorithm>
-
-using namespace std;
-
-// Vertex Methods
-/////////////////
-
-LOD_Vertex::
-LOD_Vertex(
-) :
- pos (MT_Vector3()),
- m_select_tag(false)
-{
-};
-
- bool
-LOD_Vertex::
-RemoveEdge(
- LOD_EdgeInd e
-){
-
- vector<LOD_EdgeInd>::iterator result = find(m_edges.begin(),m_edges.end(),e);
- if (result == m_edges.end()) {
- return false;
- }
-
- std::swap(*result, m_edges.back());
- m_edges.pop_back();
- return true;
-};
-
- void
-LOD_Vertex::
-AddEdge(
- LOD_EdgeInd e
-){
- m_edges.push_back(e);
-};
-
- void
-LOD_Vertex::
-SwapEdge(
- LOD_EdgeInd e_old,
- LOD_EdgeInd e_new
-){
-
- vector<LOD_EdgeInd>::iterator result =
- find(m_edges.begin(),m_edges.end(),e_old);
- if (result == m_edges.end()) {
- MT_assert(false);
- LOD_MeshException e(LOD_MeshException::e_search_error);
- throw(e);
- }
-
- *result = e_new;
-};
-
- bool
-LOD_Vertex::
-SelectTag(
-) const {
- return m_select_tag;
-};
-
- void
-LOD_Vertex::
-SetSelectTag(
- bool tag
-){
- m_select_tag = tag;
-};
-
- bool
-LOD_Vertex::
-Degenerate(
-){
- return m_edges.empty();
-}
-
- void
-LOD_Vertex::
-CopyPosition(
- float *float_ptr
-){
- pos.getValue(float_ptr);
-}
-
-
-
-// Edge Methods
-///////////////
-
-LOD_Edge::
-LOD_Edge (
-) {
- m_verts[0] = m_verts[1] = LOD_VertexInd::Empty();
- m_faces[0] = m_faces[1] = LOD_FaceInd::Empty();
-}
-
- bool
-LOD_Edge::
-operator == (
- LOD_Edge & rhs
-) {
- // edges are the same if their vertex indices are the
- // same!!! Other properties are not checked
-
- int matches = 0;
-
- if (this->m_verts[0] == rhs.m_verts[0]) {
- ++matches;
- }
- if (this->m_verts[1] == rhs.m_verts[0]) {
- ++matches;
- }
- if (this->m_verts[0] == rhs.m_verts[1]) {
- ++matches;
- }
- if (this->m_verts[1] == rhs.m_verts[1]) {
- ++matches;
- }
-
- if (matches >= 2) {
- return true;
- }
- return false;
-}
-
-// Elementary helper methods
-////////////////////////////
-
- LOD_FaceInd
-LOD_Edge::
-OpFace(
- LOD_FaceInd f
-) const {
- if (f == m_faces[0]) {
- return m_faces[1];
- } else
- if (f == m_faces[1]) {
- return m_faces[0];
- } else {
- MT_assert(false);
- LOD_MeshException e(LOD_MeshException::e_search_error);
- throw(e);
-
- return LOD_FaceInd::Empty();
- }
-}
-
- void
-LOD_Edge::
-SwapFace(
- LOD_FaceInd old_f,
- LOD_FaceInd new_f
-) {
- if (old_f == m_faces[0]) {
- m_faces[0] = new_f;
- } else
- if (old_f == m_faces[1]) {
- m_faces[1] = new_f;
- } else {
- LOD_MeshException e(LOD_MeshException::e_search_error);
- throw(e);
- }
-}
-
-
-// return the half edge face - the half edge is defined
-// by the {vertex,edge} tuple.
-
- LOD_FaceInd
-LOD_Edge::
-HalfEdgeFace(
- LOD_VertexInd vi
-){
- if (vi == m_verts[0]) return m_faces[0];
- if (vi == m_verts[1]) return m_faces[1];
- MT_assert(false);
-
- LOD_MeshException e(LOD_MeshException::e_search_error);
- throw(e);
-
- return LOD_FaceInd::Empty();
-}
-
-
- LOD_VertexInd
-LOD_Edge::
-OpVertex(
- LOD_VertexInd vi
-) {
- if (vi == m_verts[0]) return m_verts[1];
- if (vi == m_verts[1]) return m_verts[0];
- MT_assert(false);
-
- LOD_MeshException e(LOD_MeshException::e_search_error);
- throw(e);
-
- return LOD_VertexInd::Empty();
-}
-
-// replace the vertex v_old with vertex v_new
-// error if v_old is not one of the original vertices
-
- void
-LOD_Edge::
-SwapVertex(
- LOD_VertexInd v_old,
- LOD_VertexInd v_new
-) {
- if (v_old == m_verts[0]) {
- m_verts[0] = v_new;
- } else
- if (v_old == m_verts[1]) {
- m_verts[1] = v_new;
- } else {
-
- MT_assert(false);
-
- LOD_MeshException e(LOD_MeshException::e_search_error);
- throw(e);
- }
- if(m_verts[0] == m_verts[1]) {
- MT_assert(false);
-
- LOD_MeshException e(LOD_MeshException::e_non_manifold);
- throw(e);
- }
-
-}
-
- bool
-LOD_Edge::
-SelectTag(
-) const {
- return bool(m_verts[1].Tag() & 0x1);
-};
-
- void
-LOD_Edge::
-SetSelectTag(
- bool tag
-) {
- m_verts[1].SetTag(int(tag));
-};
-
- int
-LOD_Edge::
-OpenTag(
-) const {
- return m_faces[0].Tag();
-}
-
- void
-LOD_Edge::
-SetOpenTag(
- int tag
-) {
- m_faces[0].SetTag(tag);
-}
-
- bool
-LOD_Edge::
-Degenerate(
-) const {
- return (
- (m_faces[0].IsEmpty() && m_faces[1].IsEmpty()) ||
- (m_verts[0] == m_verts[1])
- );
-};
-
-// TriFace Methods
-//////////////////
-
-LOD_TriFace::
-LOD_TriFace(
-) {
- m_verts[0] = m_verts[1] = m_verts[2] = LOD_VertexInd::Empty();
-}
-
-// Elementary helper methods
-////////////////////////////
-
- void
-LOD_TriFace::
-SwapVertex(
- LOD_VertexInd old_v,
- LOD_VertexInd new_v
-) {
- // could save branching here...
-
- if (m_verts[0] == old_v) {
- m_verts[0] = new_v;
- } else
- if (m_verts[1] == old_v) {
- m_verts[1] = new_v;
- } else
- if (m_verts[2] == old_v) {
- m_verts[2] = new_v;
- } else {
- MT_assert(false);
-
- LOD_MeshException excep(LOD_MeshException::e_search_error);
- throw(excep);
- }
-}
-
- bool
-LOD_TriFace::
-SelectTag(
-) const {
- return bool(m_verts[1].Tag() & 0x1);
-};
-
- void
-LOD_TriFace::
-SetSelectTag(
- bool tag
-) {
- m_verts[1].SetTag(int(tag));
-};
-
- int
-LOD_TriFace::
-OpenTag(
-) {
- return m_verts[2].Tag();
-}
-
- void
-LOD_TriFace::
-SetOpenTag(
- int tag
-) {
- m_verts[2].SetTag(tag);
-}
-
- bool
-LOD_TriFace::
-Degenerate(
-) {
-
- return (
- (m_verts[0] == m_verts[1]) ||
- (m_verts[1] == m_verts[2]) ||
- (m_verts[2] == m_verts[0])
- );
-}
-
- void
-LOD_TriFace::
-CopyVerts(
- int * index_ptr
-){
- index_ptr[0] = m_verts[0];
- index_ptr[1] = m_verts[1];
- index_ptr[2] = m_verts[2];
-};
-
-
-
-
-
-
-
-
-
diff --git a/intern/decimation/intern/LOD_MeshPrimitives.h b/intern/decimation/intern/LOD_MeshPrimitives.h
deleted file mode 100644
index ea2d157308b..00000000000
--- a/intern/decimation/intern/LOD_MeshPrimitives.h
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_MeshPrimitives.h
- * \ingroup decimation
- */
-
-
-#ifndef __LOD_MESHPRIMITIVES_H__
-#define __LOD_MESHPRIMITIVES_H__
-
-#include "MT_Vector3.h"
-#include "CTR_TaggedIndex.h"
-#include "CTR_UHeap.h"
-#include <vector>
-
-typedef CTR_TaggedIndex<24,0x00ffffff> LOD_VertexInd;
-typedef CTR_TaggedIndex<24,0x00ffffff> LOD_EdgeInd;
-typedef CTR_TaggedIndex<24,0x00ffffff> LOD_FaceInd;
-typedef CTR_TaggedIndex<24,0x00ffffff> LOD_HeapInd;
-
-class LOD_Vertex {
-public :
- MT_Vector3 pos;
- std::vector<LOD_EdgeInd> m_edges;
- bool m_select_tag;
-
- LOD_Vertex(
- );
-
- bool
- RemoveEdge(
- LOD_EdgeInd e
- );
-
- void
- AddEdge(
- LOD_EdgeInd e
- );
-
- void
- SwapEdge(
- LOD_EdgeInd e_old,
- LOD_EdgeInd e_new
- );
-
- bool
- SelectTag(
- ) const;
-
- void
- SetSelectTag(
- bool tag
- );
-
- bool
- Degenerate(
- );
-
- void
- CopyPosition(
- float *float_ptr
- );
-
-private :
-
-
-};
-
-class LOD_Edge : public CTR_UHeapable {
-public :
- LOD_VertexInd m_verts[2];
- LOD_FaceInd m_faces[2];
-
- LOD_Edge (
- );
-
- bool operator == (
- LOD_Edge & rhs
- );
-
- // Elementary helper methods
- ////////////////////////////
-
- LOD_FaceInd
- OpFace(
- LOD_FaceInd f
- ) const;
-
- void
- SwapFace(
- LOD_FaceInd old_f,
- LOD_FaceInd new_f
- );
-
-
- // return the half edge face - the half edge is defined
- // by the {vertex,edge} tuple.
-
- LOD_FaceInd
- HalfEdgeFace(
- LOD_VertexInd vi
- );
-
-
- LOD_VertexInd
- OpVertex(
- LOD_VertexInd vi
- );
-
- // replace the vertex v_old with vertex v_new
- // error if v_old is not one of the original vertices
-
- void
- SwapVertex(
- LOD_VertexInd v_old,
- LOD_VertexInd v_new
- );
-
- bool
- SelectTag(
- ) const;
-
- void
- SetSelectTag(
- bool tag
- );
-
- int
- OpenTag(
- ) const;
-
- void
- SetOpenTag(
- int tag
- );
-
- bool
- Degenerate(
- ) const;
-
- bool
- BoundaryEdge(
- ) const {
- return (m_faces[0].IsEmpty() || m_faces[1].IsEmpty());
- };
-
-
-};
-
-class LOD_TriFace {
-public:
-
- LOD_VertexInd m_verts[3];
-
- LOD_TriFace(
- );
-
- // Elementary helper methods
- ////////////////////////////
-
- void
- SwapVertex(
- LOD_VertexInd old_v,
- LOD_VertexInd new_v
- );
-
- bool
- SelectTag(
- ) const;
-
- void
- SetSelectTag(
- bool tag
- );
-
- int
- OpenTag(
- );
- void
- SetOpenTag(
- int tag
- );
-
- bool
- Degenerate(
- );
-
- void
- CopyVerts(
- int * index_ptr
- );
-
-};
-
-#endif
-
diff --git a/intern/decimation/intern/LOD_QSDecimator.cpp b/intern/decimation/intern/LOD_QSDecimator.cpp
deleted file mode 100644
index bdcf7950447..00000000000
--- a/intern/decimation/intern/LOD_QSDecimator.cpp
+++ /dev/null
@@ -1,327 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_QSDecimator.cpp
- * \ingroup decimation
- */
-
-
-#include "LOD_QSDecimator.h"
-
-#include "LOD_ExternBufferEditor.h"
-
-using namespace std;
-
- LOD_QSDecimator *
-LOD_QSDecimator::
-New(
- LOD_ManMesh2 &mesh,
- LOD_ExternNormalEditor &face_editor,
- LOD_ExternBufferEditor &extern_editor
-){
-
- MEM_SmartPtr<LOD_QSDecimator> output
- = new LOD_QSDecimator(mesh,face_editor,extern_editor);
-
- MEM_SmartPtr<LOD_EdgeCollapser > collapser(LOD_EdgeCollapser::New());
- MEM_SmartPtr<LOD_QuadricEditor> q_editor(LOD_QuadricEditor::New(mesh));
-
- if (
- output == NULL ||
- collapser == NULL ||
- q_editor == NULL
- ) {
- return NULL;
- }
- output->m_collapser = collapser.Release();
- output->m_quadric_editor = q_editor.Release();
- return output.Release();
-}
-
-
-
- bool
-LOD_QSDecimator::
-Arm(
-){
- MT_assert(!m_is_armed);
- bool heap_result = BuildHeap();
- if (!heap_result) {
- return false;
- }
- m_is_armed = true;
- return true;
-}
-
- bool
-LOD_QSDecimator::
-Step(
-){
- return CollapseEdge();
-}
-
-
-LOD_QSDecimator::
-LOD_QSDecimator(
- LOD_ManMesh2 &mesh,
- LOD_ExternNormalEditor &face_editor,
- LOD_ExternBufferEditor &extern_editor
-) :
- m_is_armed (false),
- m_mesh(mesh),
- m_face_editor(face_editor),
- m_extern_editor(extern_editor)
-{
- m_deg_edges.reserve(32);
- m_deg_faces.reserve(32);
- m_deg_vertices.reserve(32);
- m_update_faces.reserve(32);
- m_new_edges.reserve(32);
- m_update_vertices.reserve(32);
-};
-
- bool
-LOD_QSDecimator::
-CollapseEdge(
-){
-
- // find an edge to collapse
-
- // FIXME force an edge collapse
- // or return false
-
- std::vector<LOD_Edge> & edges = m_mesh.EdgeSet();
- std::vector<LOD_Vertex> & verts = m_mesh.VertexSet();
- std::vector<LOD_Quadric> & quadrics = m_quadric_editor->Quadrics();
- int size = edges.size();
-
- if (size == 0) return false;
-
- const int heap_top = m_heap->Top();
-
- if (heap_top == -1 || edges[heap_top].HeapKey() <= -MT_INFINITY) {
- return false;
- }
-
- // compute the target position
- MT_Vector3 new_vertex = m_quadric_editor->TargetVertex(edges[heap_top]);
- LOD_Quadric & q0 = quadrics[edges[heap_top].m_verts[0]];
- LOD_Quadric & q1 = quadrics[edges[heap_top].m_verts[1]];
-
- LOD_Vertex &v0 = verts[edges[heap_top].m_verts[0]];
- LOD_Vertex &v1 = verts[edges[heap_top].m_verts[1]];
-
- LOD_Quadric sum = q0;
- sum += q1;
-
-
- if (m_collapser->CollapseEdge(
- heap_top,
- m_mesh,
- m_deg_edges,
- m_deg_faces,
- m_deg_vertices,
- m_new_edges,
- m_update_faces,
- m_update_vertices
- )) {
-
- // assign new vertex position
-
- v0.pos = new_vertex;
- v1.pos = new_vertex;
-
- // sum the quadrics of v0 and v1
- q0 = sum;
- q1 = sum;
-
- // ok update the primitive properties
-
- m_face_editor.Update(m_update_faces);
- m_face_editor.UpdateVertexNormals(m_update_vertices);
-
- // update the external vertex buffer
- m_extern_editor.CopyModifiedVerts(m_mesh,m_update_vertices);
-
- // update the external face buffer
- m_extern_editor.CopyModifiedFaces(m_mesh,m_update_faces);
-
- // update the edge heap
- UpdateHeap(m_deg_edges,m_new_edges);
-
- m_quadric_editor->Remove(m_deg_vertices);
- m_face_editor.Remove(m_deg_faces);
- m_face_editor.RemoveVertexNormals(m_deg_vertices);
-
- // delete the primitives
-
- DeletePrimitives(m_deg_edges,m_deg_faces,m_deg_vertices);
-
- } else {
- // the edge could not be collapsed at the moment - so
- // we adjust it's priority and add it back to the heap.
- m_heap->Remove(&edges[0],0);
- edges[heap_top].HeapKey() = - MT_INFINITY;
- m_heap->Insert(&edges[0],heap_top);
- }
-
- //clear all the temporary buffers
-
- m_deg_faces.clear();
- m_deg_edges.clear();
- m_deg_vertices.clear();
-
- m_update_faces.clear();
- m_update_vertices.clear();
- m_new_edges.clear();
-
- return true;
-
-}
-
- void
-LOD_QSDecimator::
-DeletePrimitives(
- const vector<LOD_EdgeInd> & degenerate_edges,
- const vector<LOD_FaceInd> & degenerate_faces,
- const vector<LOD_VertexInd> & degenerate_vertices
-) {
-
- // assumes that the 3 vectors are sorted in descending order.
-
- // Delete Degnerate primitives
- //////////////////////////////
-
-
- // delete the old edges - we have to be very careful here
- // mesh.delete() swaps edges to be deleted with the last edge in
- // the edge buffer. However the next edge to be deleted may have
- // been the last edge in the buffer!
-
- // One way to solve this is to sort degenerate_edges in descending order.
- // And then delete them in that order.
-
- // it is also vital that degenerate_edges contains no duplicates
-
- vector<LOD_EdgeInd>::const_iterator edge_it = degenerate_edges.begin();
- vector<LOD_EdgeInd>::const_iterator edge_end = degenerate_edges.end();
-
- for (; edge_it != edge_end; ++edge_it) {
- m_mesh.DeleteEdge(*edge_it,m_heap);
- }
-
-
-
- vector<LOD_FaceInd>::const_iterator face_it = degenerate_faces.begin();
- vector<LOD_FaceInd>::const_iterator face_end = degenerate_faces.end();
-
- for (;face_it != face_end; ++face_it) {
- m_mesh.DeleteFace(m_extern_editor,*face_it);
- }
-
- vector<LOD_VertexInd>::const_iterator vertex_it = degenerate_vertices.begin();
- vector<LOD_VertexInd>::const_iterator vertex_end = degenerate_vertices.end();
-
- for (;vertex_it != vertex_end; ++vertex_it) {
- m_mesh.DeleteVertex(m_extern_editor,*vertex_it);
- }
-}
-
-
- bool
-LOD_QSDecimator::
-BuildHeap(
-){
- // build the quadrics
-
- if (m_quadric_editor->BuildQuadrics(m_face_editor,true) == false) return false;
-
-
- m_heap = CTR_UHeap<LOD_Edge>::New();
- // load in edge pointers to the heap
-
- std::vector<LOD_Edge> & edge_set= m_mesh.EdgeSet();
-
- // UNUSED
- // std::vector<LOD_Edge>::const_iterator edge_end = edge_set.end();
- // std::vector<LOD_Edge>::iterator edge_start = edge_set.begin();
-
- std::vector<int> & heap_vector = m_heap->HeapVector();
-
- for (unsigned int i = 0; i < edge_set.size(); ++i) {
- edge_set[i].HeapPos() = i;
- heap_vector.push_back(i);
- }
-
- m_heap->MakeHeap(&edge_set[0]);
-
- return true;
-}
-
- void
-LOD_QSDecimator::
-UpdateHeap(
- std::vector<LOD_EdgeInd> &deg_edges,
- std::vector<LOD_EdgeInd> &new_edges
-){
- // first of all compute values for the new edges
- // and bung them on the heap.
-
- std::vector<LOD_Edge> & edge_set= m_mesh.EdgeSet();
-
- std::vector<LOD_EdgeInd>::const_iterator edge_it = new_edges.begin();
- std::vector<LOD_EdgeInd>::const_iterator end_it = new_edges.end();
-
-
- // insert all the new edges
- ///////////////////////////
-
- // compute edge costs ffor the new edges
-
- m_quadric_editor->ComputeEdgeCosts(new_edges);
-
- // inser the new elements into the heap
-
- for (; edge_it != end_it; ++edge_it) {
- m_heap->Insert(&edge_set[0],*edge_it);
- }
-
-
- // remove all the old values from the heap
-
- edge_it = deg_edges.begin();
- end_it = deg_edges.end();
-
- for (; edge_it != end_it; ++edge_it) {
- LOD_Edge &e = edge_set[*edge_it];
- m_heap->Remove(&edge_set[0],e.HeapPos());
-
- e.HeapPos() = -1;
-
- }
-}
-
diff --git a/intern/decimation/intern/LOD_QSDecimator.h b/intern/decimation/intern/LOD_QSDecimator.h
deleted file mode 100644
index 2ac223996f2..00000000000
--- a/intern/decimation/intern/LOD_QSDecimator.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_QSDecimator.h
- * \ingroup decimation
- */
-
-
-#ifndef __LOD_QSDECIMATOR_H__
-#define __LOD_QSDECIMATOR_H__
-
-#include "MEM_NonCopyable.h"
-#include "LOD_ManMesh2.h"
-#include "LOD_ExternNormalEditor.h"
-#include "LOD_EdgeCollapser.h"
-#include "LOD_QuadricEditor.h"
-
-class LOD_ExternBufferEditor;
-
-class LOD_QSDecimator : public MEM_NonCopyable {
-
-public :
-
- static
- LOD_QSDecimator *
- New(
- LOD_ManMesh2 &mesh,
- LOD_ExternNormalEditor &face_editor,
- LOD_ExternBufferEditor &extern_editor
- );
-
-
- bool
- Arm(
- );
-
-
- bool
- Step(
- );
-
-private :
-
- LOD_QSDecimator(
- LOD_ManMesh2 &mesh,
- LOD_ExternNormalEditor &face_editor,
- LOD_ExternBufferEditor &extern_editor
- );
-
- bool
- CollapseEdge(
- );
-
- bool
- BuildHeap(
- );
-
- void
- UpdateHeap(
- std::vector<LOD_EdgeInd> &deg_edges,
- std::vector<LOD_EdgeInd> &new_edges
- );
-
- void
- DeletePrimitives(
- const std::vector<LOD_EdgeInd> & degenerate_edges,
- const std::vector<LOD_FaceInd> & degenerate_faces,
- const std::vector<LOD_VertexInd> & degenerate_vertices
- );
-
-
-private :
-
- // owned by this class
- //////////////////////
-
- MEM_SmartPtr<LOD_EdgeCollapser> m_collapser;
- MEM_SmartPtr<CTR_UHeap<LOD_Edge> > m_heap;
- MEM_SmartPtr<LOD_QuadricEditor> m_quadric_editor;
-
- bool m_is_armed;
-
- // arguments to New(...)
- ////////////////////////
-
- LOD_ManMesh2 & m_mesh;
- LOD_ExternNormalEditor &m_face_editor;
- LOD_ExternBufferEditor & m_extern_editor;
-
- // temporary buffers
- ////////////////////
-
- std::vector<LOD_FaceInd> m_deg_faces;
- std::vector<LOD_EdgeInd> m_deg_edges;
- std::vector<LOD_VertexInd> m_deg_vertices;
-
- std::vector<LOD_FaceInd> m_update_faces;
- std::vector<LOD_EdgeInd> m_new_edges;
- std::vector<LOD_VertexInd> m_update_vertices;
-
-
-};
-
-#endif
-
diff --git a/intern/decimation/intern/LOD_Quadric.h b/intern/decimation/intern/LOD_Quadric.h
deleted file mode 100644
index 9dde0502aa3..00000000000
--- a/intern/decimation/intern/LOD_Quadric.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_Quadric.h
- * \ingroup decimation
- */
-
-
-#ifndef __LOD_QUADRIC_H__
-#define __LOD_QUADRIC_H__
-
-#include "MT_Vector3.h"
-#include "MT_Matrix3x3.h"
-
-
-class LOD_Quadric {
-
-private:
- MT_Scalar a2, ab, ac, ad;
- MT_Scalar b2, bc, bd;
- MT_Scalar c2, cd;
- MT_Scalar d2;
-
- void init(MT_Scalar a, MT_Scalar b, MT_Scalar c, MT_Scalar d);
-
-public:
-
- LOD_Quadric(
- ) {
- Clear();
- };
-
- LOD_Quadric(
- const MT_Vector3 & vec,
- const MT_Scalar & offset
- ) {
- a2 = vec[0] *vec[0];
- b2 = vec[1] *vec[1];
- c2 = vec[2] *vec[2];
-
- ab = vec[0]*vec[1];
- ac = vec[0]*vec[2];
- bc = vec[1]*vec[2];
-
- MT_Vector3 temp = vec*offset;
- ad = temp[0];
- bd = temp[1];
- cd = temp[2];
-
- d2 = offset*offset;
- };
-
- MT_Matrix3x3
- Tensor(
- ) const {
- // return a symmetric matrix
-
- return MT_Matrix3x3(
- a2,ab,ac,
- ab,b2,bc,
- ac,bc,c2
- );
- };
-
-
- MT_Vector3
- Vector(
- ) const {
- return MT_Vector3(ad, bd, cd);
- };
-
- void
- Clear(
- MT_Scalar val=0.0
- ) {
- a2=ab=ac=ad=b2=bc=bd=c2=cd=d2=val;
- };
-
- LOD_Quadric &
- operator=(
- const LOD_Quadric& Q
- ) {
-
- a2 = Q.a2; ab = Q.ab; ac = Q.ac; ad = Q.ad;
- b2 = Q.b2; bc = Q.bc; bd = Q.bd;
- c2 = Q.c2; cd = Q.cd;
- d2 = Q.d2;
- return *this;
- };
-
- LOD_Quadric&
- operator+=(
- const LOD_Quadric& Q
- ) {
- a2 += Q.a2; ab += Q.ab; ac += Q.ac; ad += Q.ad;
- b2 += Q.b2; bc += Q.bc; bd += Q.bd;
- c2 += Q.c2; cd += Q.cd;
- d2 += Q.d2;
- return *this;
- };
-
- LOD_Quadric&
- operator*=(
- const MT_Scalar & s
- ) {
- a2 *= s; ab *= s; ac *= s; ad *= s;
- b2 *= s; bc *= s; bd *= s;
- c2 *= s; cd *= s;
- d2 *= s;
- return *this;
- };
-
-
- MT_Scalar
- Evaluate(
- const MT_Vector3 &v
- ) const {
- // compute the LOD_Quadric error
-
- return v[0]*v[0]*a2 + 2*v[0]*v[1]*ab + 2*v[0]*v[2]*ac + 2*v[0]*ad
- +v[1]*v[1]*b2 + 2*v[1]*v[2]*bc + 2*v[1]*bd
- +v[2]*v[2]*c2 + 2*v[2]*cd
- + d2;
- };
-
- bool
- Optimize(
- MT_Vector3& v
- ) const {
-
- MT_Scalar det = Tensor().determinant();
- if (MT_fuzzyZero(det)) {
- return false;
- }
-
- v = -((Tensor().inverse()) * Vector());
- return true;
- };
-
-};
-
-#endif
-
diff --git a/intern/decimation/intern/LOD_QuadricEditor.cpp b/intern/decimation/intern/LOD_QuadricEditor.cpp
deleted file mode 100644
index fbaf0c1180f..00000000000
--- a/intern/decimation/intern/LOD_QuadricEditor.cpp
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_QuadricEditor.cpp
- * \ingroup decimation
- */
-
-
-#include "LOD_QuadricEditor.h"
-#include "LOD_ExternNormalEditor.h"
-
-// Creation
-///////////
-
-using namespace std;
-
-
-LOD_QuadricEditor::
-LOD_QuadricEditor(
- LOD_ManMesh2 &mesh
-) :
- m_quadrics(NULL),
- m_mesh(mesh)
-{
-};
-
- LOD_QuadricEditor *
-LOD_QuadricEditor::
-New(
- LOD_ManMesh2 &mesh
-){
- //same number of quadrics as vertices in the mesh
-
- MEM_SmartPtr<LOD_QuadricEditor> output(new LOD_QuadricEditor(mesh));
-
- if (output == NULL) {
- return NULL;
- }
- return output.Release();
-}
-
-
-// Property editor interface
-////////////////////////////
-
- void
-LOD_QuadricEditor::
-Remove(
- std::vector<LOD_VertexInd> &sorted_vertices
-){
- vector<LOD_Quadric> & quadrics = *m_quadrics;
-
- vector<LOD_VertexInd>::const_iterator it_start = sorted_vertices.begin();
- vector<LOD_VertexInd>::const_iterator it_end = sorted_vertices.end();
-
- for (; it_start != it_end; ++it_start) {
-
- if (quadrics.size() > 0) {
- LOD_Quadric temp = quadrics[*it_start];
-
- quadrics[*it_start] = quadrics.back();
- quadrics.back() = temp;
-
- quadrics.pop_back();
- }
- }
-};
-
-
-// Editor specific methods
-//////////////////////////
-
- bool
-LOD_QuadricEditor::
-BuildQuadrics(
- LOD_ExternNormalEditor& normal_editor,
- bool preserve_boundaries
-){
- if (m_quadrics != NULL) delete(m_quadrics);
-
- m_quadrics =new vector<LOD_Quadric> (m_mesh.VertexSet().size());
- if (m_quadrics == NULL) return false;
-
- // iterate through the face set of the mesh
- // compute a quadric based upon that face and
- // add it to each of it's vertices quadrics.
-
- const vector<LOD_TriFace> &faces = m_mesh.FaceSet();
- const vector<LOD_Vertex> &verts = m_mesh.VertexSet();
- vector<LOD_Edge> &edges = m_mesh.EdgeSet();
-
- const vector<MT_Vector3> &normals = normal_editor.Normals();
- vector<MT_Vector3>::const_iterator normal_it = normals.begin();
-
- vector<LOD_TriFace>::const_iterator face_it = faces.begin();
- vector<LOD_TriFace>::const_iterator face_end = faces.end();
-
- vector<LOD_Quadric> & quadrics = *m_quadrics;
-
-
- for (; face_it != face_end; ++face_it, ++normal_it) {
-
- MT_Vector3 normal = *normal_it;
- MT_Scalar offset = -normal.dot(verts[face_it->m_verts[0]].pos);
-
- LOD_Quadric q(normal,offset);
-
- quadrics[face_it->m_verts[0]] += q;
- quadrics[face_it->m_verts[1]] += q;
- quadrics[face_it->m_verts[2]] += q;
- }
-
- if (preserve_boundaries) {
-
- // iterate through the edge set and add a boundary quadric to
- // each of the boundary edges vertices.
-
- vector<LOD_Edge>::const_iterator edge_it = edges.begin();
- vector<LOD_Edge>::const_iterator edge_end = edges.end();
-
- for (; edge_it != edge_end; ++edge_it) {
- if (edge_it->BoundaryEdge()) {
-
- // compute a plane perpendicular to the edge and the normal
- // of the edges single polygon.
- const MT_Vector3 & v0 = verts[edge_it->m_verts[0]].pos;
- const MT_Vector3 & v1 = verts[edge_it->m_verts[1]].pos;
-
- MT_Vector3 edge_vector = v1 - v0;
-
- LOD_FaceInd edge_face = edge_it->OpFace(LOD_EdgeInd::Empty());
- edge_vector = edge_vector.cross(normals[edge_face]);
-
- if (!edge_vector.fuzzyZero()) {
- edge_vector.normalize();
-
- LOD_Quadric boundary_q(edge_vector, - edge_vector.dot(v0));
- boundary_q *= 100;
-
- quadrics[edge_it->m_verts[0]] += boundary_q;
- quadrics[edge_it->m_verts[1]] += boundary_q;
- }
- }
- }
- }
-
-
- // initiate the heap keys of the edges by computing the edge costs.
-
- vector<LOD_Edge>::iterator edge_it = edges.begin();
- vector<LOD_Edge>::const_iterator edge_end = edges.end();
-
- for (; edge_it != edge_end; ++edge_it) {
-
- MT_Vector3 target = TargetVertex(*edge_it);
-
- LOD_Edge &e = *edge_it;
- LOD_Quadric q0 = quadrics[e.m_verts[0]];
- const LOD_Quadric &q1 = quadrics[e.m_verts[1]];
-
- e.HeapKey() = -float(q0.Evaluate(target) + q1.Evaluate(target));
- }
-
- return true;
-
-};
-
- MT_Vector3
-LOD_QuadricEditor::
-TargetVertex(
- LOD_Edge & e
-){
-
- // compute an edge contration target for edge ei
- // this is computed by summing it's vertices quadrics and
- // optimizing the result.
- vector<LOD_Vertex> &verts = m_mesh.VertexSet();
-
- vector<LOD_Quadric> &quadrics = *m_quadrics;
-
- LOD_VertexInd v0 = e.m_verts[0];
- LOD_VertexInd v1 = e.m_verts[1];
-
- LOD_Quadric q0 = quadrics[v0];
- q0 += quadrics[v1];
-
- MT_Vector3 result;
-
- if (q0.Optimize(result)) {
- return result;
- } else {
- // the quadric was degenerate -> just take the average of
- // v0 and v1
-
- return ((verts[v0].pos + verts[v1].pos) * 0.5);
- }
-};
-
- void
-LOD_QuadricEditor::
-ComputeEdgeCosts(
- vector<LOD_EdgeInd> &edges
-){
-
- // for each we compute the target vertex and then compute
- // the quadric error e = Q1(v') + Q2(v')
- vector<LOD_Edge> &edge_set = m_mesh.EdgeSet();
-
- vector<LOD_Quadric> &quadrics = *m_quadrics;
-
- vector<LOD_EdgeInd>::const_iterator edge_it = edges.begin();
- vector<LOD_EdgeInd>::const_iterator edge_end = edges.end();
-
- for (; edge_it != edge_end; ++edge_it) {
-
- MT_Vector3 target = TargetVertex(edge_set[*edge_it]);
-
- LOD_Edge &e = edge_set[*edge_it];
- LOD_Quadric q0 = quadrics[e.m_verts[0]];
- const LOD_Quadric &q1 = quadrics[e.m_verts[1]];
-
- e.HeapKey() = -float(q0.Evaluate(target) + q1.Evaluate(target));
- }
-};
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/intern/decimation/intern/LOD_QuadricEditor.h b/intern/decimation/intern/LOD_QuadricEditor.h
deleted file mode 100644
index 0a66d299e15..00000000000
--- a/intern/decimation/intern/LOD_QuadricEditor.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_QuadricEditor.h
- * \ingroup decimation
- */
-
-
-#ifndef __LOD_QUADRICEDITOR_H__
-#define __LOD_QUADRICEDITOR_H__
-
-#include "MEM_NonCopyable.h"
-#include "LOD_ManMesh2.h"
-#include "MT_Vector3.h"
-#include "LOD_Quadric.h"
-
-class LOD_ExternNormalEditor;
-
-
-class LOD_QuadricEditor : public MEM_NonCopyable
-{
-
-public :
-
- // Creation
- ///////////
-
- static
- LOD_QuadricEditor *
- New(
- LOD_ManMesh2 &mesh
- );
-
- // Property editor interface
- ////////////////////////////
-
- void
- Remove(
- std::vector<LOD_VertexInd> &sorted_vertices
- );
-
- void
- Update(
- std::vector<LOD_FaceInd> &sorted_vertices
- );
-
-
- std::vector<LOD_Quadric> &
- Quadrics(
- ) const {
- return *m_quadrics;
- };
-
-
- // Editor specific methods
- //////////////////////////
-
- bool
- BuildQuadrics(
- LOD_ExternNormalEditor& normal_editor,
- bool preserve_boundaries
- );
-
-
- void
- ComputeEdgeCosts(
- std::vector<LOD_EdgeInd> &edges
- );
-
- MT_Vector3
- TargetVertex(
- LOD_Edge &e
- );
-
- ~LOD_QuadricEditor(
- ){
- delete(m_quadrics);
- };
-
-
-private :
-
- std::vector<LOD_Quadric> * m_quadrics;
-
- LOD_ManMesh2 &m_mesh;
-
-private :
-
- LOD_QuadricEditor(LOD_ManMesh2 &mesh);
-
-
-
-};
-
-#endif
-
diff --git a/intern/decimation/intern/LOD_decimation.cpp b/intern/decimation/intern/LOD_decimation.cpp
deleted file mode 100644
index 49033933cd6..00000000000
--- a/intern/decimation/intern/LOD_decimation.cpp
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file decimation/intern/LOD_decimation.cpp
- * \ingroup decimation
- */
-
-
-// implementation of external c api
-#include "../extern/LOD_decimation.h"
-#include "LOD_DecimationClass.h"
-
-using namespace std;
-
- int
-LOD_LoadMesh(
- LOD_Decimation_InfoPtr info
-) {
- if (info == NULL) return 0;
- if (
- info->vertex_buffer == NULL ||
- info->vertex_normal_buffer == NULL ||
- info->triangle_index_buffer == NULL
- ) {
- return 0;
- }
-
-
- // create the intern object to hold all
- // the decimation classes
-
- MEM_SmartPtr<LOD_DecimationClass> intern(LOD_DecimationClass::New(info));
-
- if (intern == NULL) return 0;
-
- MEM_SmartPtr<vector<LOD_Vertex> > intern_vertex_buffer(new vector<LOD_Vertex>(info->vertex_num));
- if (intern_vertex_buffer == NULL) return 0;
-
- vector<LOD_Vertex>::iterator intern_vertex_it(intern_vertex_buffer->begin());
-
- // now load in the vertices to the mesh
-
- const int vertex_stride = 3;
-
- float * vertex_ptr = info->vertex_buffer;
- const float * vertex_end = vertex_ptr + info->vertex_num*vertex_stride;
-
- LOD_ManMesh2 &mesh = intern->Mesh();
-
- for (;vertex_ptr < vertex_end; vertex_ptr += vertex_stride,++intern_vertex_it) {
- intern_vertex_it->pos = MT_Vector3(vertex_ptr);
- }
-
- mesh.SetVertices(intern_vertex_buffer);
-
- // load in the triangles
-
- const int triangle_stride = 3;
-
- int * triangle_ptr = info->triangle_index_buffer;
- const int * triangle_end = triangle_ptr + info->face_num*triangle_stride;
-
- try {
-
- for (;triangle_ptr < triangle_end; triangle_ptr += triangle_stride) {
- mesh.AddTriangle(triangle_ptr);
- }
- }
-
- catch (...) {
- return 0;
- }
-
- // ok we have built the mesh
-
- intern->m_e_decimation_state = LOD_DecimationClass::e_loaded;
-
- info->intern = (void *) (intern.Release());
-
- return 1;
-}
-
- int
-LOD_PreprocessMesh(
- LOD_Decimation_InfoPtr info
-) {
- if (info == NULL) return 0;
- if (info->intern == NULL) return 0;
-
- LOD_DecimationClass *intern = (LOD_DecimationClass *) info->intern;
- if (intern->m_e_decimation_state != LOD_DecimationClass::e_loaded) return 0;
-
- // arm the various internal classes so that we are ready to step
- // through decimation
-
- intern->FaceEditor().BuildNormals();
- if (intern->Decimator().Arm() == false) return 0;
-
- // ok preprocessing done
- intern->m_e_decimation_state = LOD_DecimationClass::e_preprocessed;
-
- return 1;
-}
-
- int
-LOD_CollapseEdge(
- LOD_Decimation_InfoPtr info
-){
- if (info == NULL) return 0;
- if (info->intern == NULL) return 0;
- LOD_DecimationClass *intern = (LOD_DecimationClass *) info->intern;
- if (intern->m_e_decimation_state != LOD_DecimationClass::e_preprocessed) return 0;
-
- bool step_result = intern->Decimator().Step();
-
- return step_result == true ? 1 : 0;
-}
-
-
- int
-LOD_FreeDecimationData(
- LOD_Decimation_InfoPtr info
-){
- if (info == NULL) return 0;
- if (info->intern == NULL) return 0;
- LOD_DecimationClass *intern = (LOD_DecimationClass *) info->intern;
- delete(intern);
- info->intern = NULL;
- return 1;
-}
-
diff --git a/intern/dualcon/CMakeLists.txt b/intern/dualcon/CMakeLists.txt
index caa1ea09b04..da5e10fe6a7 100644
--- a/intern/dualcon/CMakeLists.txt
+++ b/intern/dualcon/CMakeLists.txt
@@ -19,6 +19,9 @@
set(INC
.
intern
+)
+
+set(INC_SYS
../../extern/Eigen3
)
@@ -42,5 +45,5 @@ set(SRC
dualcon.h
)
-blender_add_lib(bf_intern_dualcon "${SRC}" "${INC}" "")
+blender_add_lib(bf_intern_dualcon "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/intern/dualcon/intern/Projections.cpp b/intern/dualcon/intern/Projections.cpp
index 2a52cc9972a..f00d998591f 100644
--- a/intern/dualcon/intern/Projections.cpp
+++ b/intern/dualcon/intern/Projections.cpp
@@ -92,12 +92,12 @@ static void crossProduct(double res[3], const double a[3], const double b[3])
/**
* Method to perform dot product
*/
-int64_t dotProduct(const int64_t a[3], const int64_t b[3])
+static int64_t dotProduct(const int64_t a[3], const int64_t b[3])
{
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
-void normalize(double a[3])
+static void normalize(double a[3])
{
double mag = a[0] * a[0] + a[1] * a[1] + a[2] * a[2];
if (mag > 0) {
diff --git a/intern/dualcon/intern/dualcon_c_api.cpp b/intern/dualcon/intern/dualcon_c_api.cpp
index 894ab6b0873..c96415bfb54 100644
--- a/intern/dualcon/intern/dualcon_c_api.cpp
+++ b/intern/dualcon/intern/dualcon_c_api.cpp
@@ -32,7 +32,7 @@
#define isnan(n) _isnan(n)
#endif
-void veccopy(float dst[3], const float src[3])
+static void veccopy(float dst[3], const float src[3])
{
dst[0] = src[0];
dst[1] = src[1];
diff --git a/intern/dualcon/intern/octree.cpp b/intern/dualcon/intern/octree.cpp
index 9f44e7bbfdf..49c50c8240d 100644
--- a/intern/dualcon/intern/octree.cpp
+++ b/intern/dualcon/intern/octree.cpp
@@ -345,11 +345,13 @@ void Octree::addTriangle(Triangle *trian, int triind)
delete proj;
}
-void print_depth(int height, int maxDepth)
+#if 0
+static void print_depth(int height, int maxDepth)
{
for (int i = 0; i < maxDepth - height; i++)
printf(" ");
}
+#endif
InternalNode *Octree::addTriangle(InternalNode *node, CubeTriangleIsect *p, int height)
{
@@ -382,22 +384,22 @@ InternalNode *Octree::addTriangle(InternalNode *node, CubeTriangleIsect *p, int
/* Pruning using intersection test */
if (subp->isIntersecting()) {
- if (!hasChild(node, i)) {
+ if (!node->has_child(i)) {
if (height == 1)
node = addLeafChild(node, i, count, createLeaf(0));
else
node = addInternalChild(node, i, count, createInternal(0));
}
- Node *chd = getChild(node, count);
+ Node *chd = node->get_child(count);
if (node->is_child_leaf(i))
- setChild(node, count, (Node *)updateCell(&chd->leaf, subp));
+ node->set_child(count, (Node *)updateCell(&chd->leaf, subp));
else
- setChild(node, count, (Node *)addTriangle(&chd->internal, subp, height - 1));
+ node->set_child(count, (Node *)addTriangle(&chd->internal, subp, height - 1));
}
}
- if (hasChild(node, i))
+ if (node->has_child(i))
count++;
}
@@ -448,11 +450,11 @@ void Octree::preparePrimalEdgesMask(InternalNode *node)
{
int count = 0;
for (int i = 0; i < 8; i++) {
- if (hasChild(node, i)) {
+ if (node->has_child(i)) {
if (node->is_child_leaf(i))
- createPrimalEdgesMask(&getChild(node, count)->leaf);
+ createPrimalEdgesMask(&node->get_child(count)->leaf);
else
- preparePrimalEdgesMask(&getChild(node, count)->internal);
+ preparePrimalEdgesMask(&node->get_child(count)->internal);
count++;
}
@@ -485,7 +487,7 @@ Node *Octree::trace(Node *newnode, int *st, int len, int depth, PathList *& path
// Get children paths
int chdleaf[8];
- fillChildren(&newnode->internal, chd, chdleaf);
+ newnode->internal.fill_children(chd, chdleaf);
// int count = 0;
for (i = 0; i < 8; i++) {
@@ -508,7 +510,7 @@ Node *Octree::trace(Node *newnode, int *st, int len, int depth, PathList *& path
int df[2] = {depth - 1, depth - 1};
int *nstf[2];
- fillChildren(&newnode->internal, chd, chdleaf);
+ newnode->internal.fill_children(chd, chdleaf);
for (i = 0; i < 12; i++) {
int c[2] = {cellProcFaceMask[i][0], cellProcFaceMask[i][1]};
@@ -588,7 +590,7 @@ void Octree::findPaths(Node *node[2], int leaf[2], int depth[2], int *st[2], int
for (j = 0; j < 2; j++) {
if (!leaf[j]) {
- fillChildren(&node[j]->internal, chd[j], chdleaf[j]);
+ node[j]->internal.fill_children(chd[j], chdleaf[j]);
int len = (dimen >> (maxDepth - depth[j] + 1));
for (i = 0; i < 8; i++) {
@@ -964,10 +966,10 @@ Node *Octree::patch(Node *newnode, int st[3], int len, PathList *rings)
st[1] + len * vertmap[i][1],
st[2] + len * vertmap[i][2]
};
- patch(getChild(&newnode->internal, count), nori, len, zlists[i]);
+ patch(newnode->internal.get_child(count), nori, len, zlists[i]);
}
- if (hasChild(&newnode->internal, i)) {
+ if (newnode->internal.has_child(i)) {
count++;
}
}
@@ -1406,16 +1408,16 @@ Node *Octree::locateCell(InternalNode *node, int st[3], int len, int ori[3], int
rst[1] = st[1] + vertmap[ind][1] * len;
rst[2] = st[2] + vertmap[ind][2] * len;
- if (hasChild(node, ind)) {
- int count = getChildCount(node, ind);
- Node *chd = getChild(node, count);
+ if (node->has_child(ind)) {
+ int count = node->get_child_count(ind);
+ Node *chd = node->get_child(count);
if (node->is_child_leaf(ind)) {
rleaf = chd;
rlen = len;
}
else {
// Recur
- setChild(node, count, locateCell(&chd->internal, rst, len, ori, dir, side, rleaf, rst, rlen));
+ node->set_child(count, locateCell(&chd->internal, rst, len, ori, dir, side, rleaf, rst, rlen));
}
}
else {
@@ -1722,7 +1724,7 @@ void Octree::buildSigns(unsigned char table[], Node *node, int isLeaf, int sg, i
// Internal node
Node *chd[8];
int leaf[8];
- fillChildren(&node->internal, chd, leaf);
+ node->internal.fill_children(chd, leaf);
// Get the signs at the corners of the first cube
rvalue[0] = sg;
@@ -1782,8 +1784,8 @@ void Octree::clearProcessBits(Node *node, int height)
// Internal cell, recur
int count = 0;
for (i = 0; i < 8; i++) {
- if (hasChild(&node->internal, i)) {
- clearProcessBits(getChild(&node->internal, count), height - 1);
+ if (node->internal.has_child(i)) {
+ clearProcessBits(node->internal.get_child(count), height - 1);
count++;
}
}
@@ -2014,13 +2016,13 @@ int Octree::floodFill(Node *node, int st[3], int len, int height, int threshold)
int count = 0;
len >>= 1;
for (i = 0; i < 8; i++) {
- if (hasChild((InternalNode *)node, i)) {
+ if (node->internal.has_child(i)) {
int nst[3];
nst[0] = st[0] + vertmap[i][0] * len;
nst[1] = st[1] + vertmap[i][1] * len;
nst[2] = st[2] + vertmap[i][2] * len;
- int d = floodFill(getChild((InternalNode *)node, count), nst, len, height - 1, threshold);
+ int d = floodFill(node->internal.get_child(count), nst, len, height - 1, threshold);
if (d > maxtotal) {
maxtotal = d;
}
@@ -2060,9 +2062,9 @@ void Octree::writeOut()
void Octree::countIntersection(Node *node, int height, int& nedge, int& ncell, int& nface)
{
if (height > 0) {
- int total = getNumChildren(&node->internal);
+ int total = node->internal.get_num_children();
for (int i = 0; i < total; i++) {
- countIntersection(getChild(&node->internal, i), height - 1, nedge, ncell, nface);
+ countIntersection(node->internal.get_child(i), height - 1, nedge, ncell, nface);
}
}
else {
@@ -2108,8 +2110,8 @@ void pseudoInverse(const _Matrix_Type_ &a,
svd.matrixU().adjoint();
}
-void solve_least_squares(const float halfA[], const float b[],
- const float midpoint[], float rvalue[])
+static void solve_least_squares(const float halfA[], const float b[],
+ const float midpoint[], float rvalue[])
{
/* calculate pseudo-inverse */
Eigen::MatrixXf A(3, 3), pinv(3, 3);
@@ -2126,8 +2128,32 @@ void solve_least_squares(const float halfA[], const float b[],
rvalue[i] = result(i);
}
-void minimize(float rvalue[3], float mp[3], const float pts[12][3],
- const float norms[12][3], const int parity[12])
+static void mass_point(float mp[3], const float pts[12][3], const int parity[12])
+{
+ int ec = 0;
+
+ for (int i = 0; i < 12; i++) {
+ if (parity[i]) {
+ const float *p = pts[i];
+
+ mp[0] += p[0];
+ mp[1] += p[1];
+ mp[2] += p[2];
+
+ ec++;
+ }
+ }
+
+ if (ec == 0) {
+ return;
+ }
+ mp[0] /= ec;
+ mp[1] /= ec;
+ mp[2] /= ec;
+}
+
+static void minimize(float rvalue[3], float mp[3], const float pts[12][3],
+ const float norms[12][3], const int parity[12])
{
float ata[6] = {0, 0, 0, 0, 0, 0};
float atb[3] = {0, 0, 0};
@@ -2173,34 +2199,51 @@ void minimize(float rvalue[3], float mp[3], const float pts[12][3],
solve_least_squares(ata, atb, mp, rvalue);
}
-void Octree::computeMinimizer(LeafNode *leaf, int st[3], int len, float rvalue[3])
+void Octree::computeMinimizer(const LeafNode *leaf, int st[3], int len,
+ float rvalue[3]) const
{
// First, gather all edge intersections
float pts[12][3], norms[12][3];
int parity[12];
fillEdgeIntersections(leaf, st, len, pts, norms, parity);
- // Next, construct QEF and minimizer
- float mp[3] = {0, 0, 0};
- minimize(rvalue, mp, pts, norms, parity);
-
- /* Restraining the location of the minimizer */
- float nh1 = hermite_num * len;
- float nh2 = (1 + hermite_num) * len;
- if ((mode == DUALCON_MASS_POINT || mode == DUALCON_CENTROID) ||
- (rvalue[0] < st[0] - nh1 || rvalue[1] < st[1] - nh1 || rvalue[2] < st[2] - nh1 ||
- rvalue[0] > st[0] + nh2 || rvalue[1] > st[1] + nh2 || rvalue[2] > st[2] + nh2)) {
- if (mode == DUALCON_CENTROID) {
- // Use centroids
+ switch (mode) {
+ case DUALCON_CENTROID:
rvalue[0] = (float) st[0] + len / 2;
rvalue[1] = (float) st[1] + len / 2;
rvalue[2] = (float) st[2] + len / 2;
- }
- else {
- // Use mass point instead
- rvalue[0] = mp[0];
- rvalue[1] = mp[1];
- rvalue[2] = mp[2];
+ break;
+
+ case DUALCON_MASS_POINT:
+ rvalue[0] = rvalue[1] = rvalue[2] = 0;
+ mass_point(rvalue, pts, parity);
+ break;
+
+ default: {
+ // Sharp features */
+
+ // construct QEF and minimizer
+ float mp[3] = {0, 0, 0};
+ minimize(rvalue, mp, pts, norms, parity);
+
+ /* Restraining the location of the minimizer */
+ float nh1 = hermite_num * len;
+ float nh2 = (1 + hermite_num) * len;
+
+ if (rvalue[0] < st[0] - nh1 ||
+ rvalue[1] < st[1] - nh1 ||
+ rvalue[2] < st[2] - nh1 ||
+
+ rvalue[0] > st[0] + nh2 ||
+ rvalue[1] > st[1] + nh2 ||
+ rvalue[2] > st[2] + nh2)
+ {
+ // Use mass point instead
+ rvalue[0] = mp[0];
+ rvalue[1] = mp[1];
+ rvalue[2] = mp[2];
+ }
+ break;
}
}
}
@@ -2251,13 +2294,13 @@ void Octree::generateMinimizer(Node *node, int st[3], int len, int height, int&
int count = 0;
len >>= 1;
for (i = 0; i < 8; i++) {
- if (hasChild(&node->internal, i)) {
+ if (node->internal.has_child(i)) {
int nst[3];
nst[0] = st[0] + vertmap[i][0] * len;
nst[1] = st[1] + vertmap[i][1] * len;
nst[2] = st[2] + vertmap[i][2] * len;
- generateMinimizer(getChild(&node->internal, count),
+ generateMinimizer(node->internal.get_child(count),
nst, len, height - 1, offset);
count++;
}
@@ -2342,9 +2385,9 @@ void Octree::edgeProcContour(Node *node[4], int leaf[4], int depth[4], int maxde
Node *chd[4][8];
for (j = 0; j < 4; j++) {
for (i = 0; i < 8; i++) {
- chd[j][i] = ((!leaf[j]) && hasChild(&node[j]->internal, i)) ?
- getChild(&node[j]->internal,
- getChildCount(&node[j]->internal, i)) : NULL;
+ chd[j][i] = ((!leaf[j]) && node[j]->internal.has_child(i)) ?
+ node[j]->internal.get_child(
+ node[j]->internal.get_child_count(i)) : NULL;
}
}
@@ -2389,9 +2432,9 @@ void Octree::faceProcContour(Node *node[2], int leaf[2], int depth[2], int maxde
Node *chd[2][8];
for (j = 0; j < 2; j++) {
for (i = 0; i < 8; i++) {
- chd[j][i] = ((!leaf[j]) && hasChild(&node[j]->internal, i)) ?
- getChild(&node[j]->internal,
- getChildCount(&node[j]->internal, i)) : NULL;
+ chd[j][i] = ((!leaf[j]) && node[j]->internal.has_child(i)) ?
+ node[j]->internal.get_child(
+ node[j]->internal.get_child_count(i)) : NULL;
}
}
@@ -2458,9 +2501,8 @@ void Octree::cellProcContour(Node *node, int leaf, int depth)
// Fill children nodes
Node *chd[8];
for (i = 0; i < 8; i++) {
- chd[i] = ((!leaf) && hasChild(&node->internal, i)) ?
- getChild(&node->internal,
- getChildCount(&node->internal, i)) : NULL;
+ chd[i] = ((!leaf) && node->internal.has_child(i)) ?
+ node->internal.get_child(node->internal.get_child_count(i)) : NULL;
}
// 8 Cell calls
@@ -2537,8 +2579,8 @@ void Octree::edgeProcParity(Node *node[4], int leaf[4], int depth[4], int maxdep
Node *chd[4][8];
for (j = 0; j < 4; j++) {
for (i = 0; i < 8; i++) {
- chd[j][i] = ((!leaf[j]) && hasChild(&node[j]->internal, i)) ?
- getChild(&node[j]->internal, getChildCount(&node[j]->internal, i)) : NULL;
+ chd[j][i] = ((!leaf[j]) && node[j]->internal.has_child(i)) ?
+ node[j]->internal.get_child( node[j]->internal.get_child_count(i)) : NULL;
}
}
@@ -2587,9 +2629,9 @@ void Octree::faceProcParity(Node *node[2], int leaf[2], int depth[2], int maxdep
Node *chd[2][8];
for (j = 0; j < 2; j++) {
for (i = 0; i < 8; i++) {
- chd[j][i] = ((!leaf[j]) && hasChild(&node[j]->internal, i)) ?
- getChild(&node[j]->internal,
- getChildCount(&node[j]->internal, i)) : NULL;
+ chd[j][i] = ((!leaf[j]) && node[j]->internal.has_child(i)) ?
+ node[j]->internal.get_child(
+ node[j]->internal.get_child_count(i)) : NULL;
}
}
@@ -2656,9 +2698,8 @@ void Octree::cellProcParity(Node *node, int leaf, int depth)
// Fill children nodes
Node *chd[8];
for (i = 0; i < 8; i++) {
- chd[i] = ((!leaf) && hasChild((InternalNode *)node, i)) ?
- getChild((InternalNode *)node,
- getChildCount((InternalNode *)node, i)) : NULL;
+ chd[i] = ((!leaf) && node->internal.has_child(i)) ?
+ node->internal.get_child(node->internal.get_child_count(i)) : NULL;
}
// 8 Cell calls
@@ -2801,3 +2842,7 @@ const int dirEdge[3][4] = {
{7, 6, 5, 4},
{11, 10, 9, 8}
};
+
+int InternalNode::numChildrenTable[256];
+int InternalNode::childrenCountTable[256][8];
+int InternalNode::childrenIndexTable[256][8];
diff --git a/intern/dualcon/intern/octree.h b/intern/dualcon/intern/octree.h
index 550d584baa7..6cbdc9fb3d8 100644
--- a/intern/dualcon/intern/octree.h
+++ b/intern/dualcon/intern/octree.h
@@ -56,12 +56,18 @@
#define EDGE_FLOATS 4
union Node;
+struct LeafNode;
struct InternalNode {
- /* Treat as bitfield, bit N indicates whether child N exists or not */
- unsigned char has_child;
- /* Treat as bitfield, bit N indicates whether child N is a leaf or not */
- unsigned char child_is_leaf;
+ /* Initialized in Octree::BuildTable */
+ static int numChildrenTable[256];
+ static int childrenCountTable[256][8];
+ static int childrenIndexTable[256][8];
+
+ /* Bit N indicates whether child N exists or not */
+ unsigned char has_child_bitfield;
+ /* Bit N indicates whether child N is a leaf or not */
+ unsigned char child_is_leaf_bitfield;
/* Can have up to eight children */
Node *children[0];
@@ -69,7 +75,78 @@ struct InternalNode {
/// Test if child is leaf
int is_child_leaf(int index) const
{
- return (child_is_leaf >> index) & 1;
+ return (child_is_leaf_bitfield >> index) & 1;
+ }
+
+ /// If child index exists
+ int has_child(int index) const
+ {
+ return (has_child_bitfield >> index) & 1;
+ }
+
+ /// Get the pointer to child index
+ Node *get_child(int count)
+ {
+ return children[count];
+ }
+
+ const Node *get_child(int count) const
+ {
+ return children[count];
+ }
+
+ /// Get total number of children
+ int get_num_children() const
+ {
+ return numChildrenTable[has_child_bitfield];
+ }
+
+ /// Get the count of children
+ int get_child_count(int index) const
+ {
+ return childrenCountTable[has_child_bitfield][index];
+ }
+ int get_child_index(int count)
+ {
+ return childrenIndexTable[has_child_bitfield][count];
+ }
+ const int *get_child_counts() const
+ {
+ return childrenCountTable[has_child_bitfield];
+ }
+
+ /// Get all children
+ void fill_children(Node *children[8], int leaf[8])
+ {
+ int count = 0;
+ for (int i = 0; i < 8; i++) {
+ leaf[i] = is_child_leaf(i);
+ if (has_child(i)) {
+ children[i] = get_child(count);
+ count++;
+ }
+ else {
+ children[i] = NULL;
+ leaf[i] = 0;
+ }
+ }
+ }
+
+ /// Sets the child pointer
+ void set_child(int count, Node *chd)
+ {
+ children[count] = chd;
+ }
+ void set_internal_child(int index, int count, InternalNode *chd)
+ {
+ set_child(count, (Node *)chd);
+ has_child_bitfield |= (1 << index);
+ }
+ void set_leaf_child(int index, int count, LeafNode *chd)
+ {
+ set_child(count, (Node *)chd);
+ has_child_bitfield |= (1 << index);
+ child_is_leaf_bitfield |= (1 << index);
}
};
@@ -345,7 +422,8 @@ class Octree
void countIntersection(Node *node, int height, int& nedge, int& ncell, int& nface);
void generateMinimizer(Node * node, int st[3], int len, int height, int& offset);
- void computeMinimizer(LeafNode * leaf, int st[3], int len, float rvalue[3]);
+ void computeMinimizer(const LeafNode * leaf, int st[3], int len,
+ float rvalue[3]) const;
/**
* Traversal functions to generate polygon model
* op: 0 for counting, 1 for writing OBJ, 2 for writing OFF, 3 for writing PLY
@@ -365,9 +443,6 @@ class Octree
/************ Operators for all nodes ************/
/// Lookup table
- int numChildrenTable[256];
- int childrenCountTable[256][8];
- int childrenIndexTable[256][8];
int numEdgeTable[8];
int edgeCountTable[8][3];
@@ -375,12 +450,12 @@ class Octree
void buildTable()
{
for (int i = 0; i < 256; i++) {
- numChildrenTable[i] = 0;
+ InternalNode::numChildrenTable[i] = 0;
int count = 0;
for (int j = 0; j < 8; j++) {
- numChildrenTable[i] += ((i >> j) & 1);
- childrenCountTable[i][j] = count;
- childrenIndexTable[i][count] = j;
+ InternalNode::numChildrenTable[i] += ((i >> j) & 1);
+ InternalNode::childrenCountTable[i][j] = count;
+ InternalNode::childrenIndexTable[i][count] = j;
count += ((i >> j) & 1);
}
}
@@ -402,15 +477,15 @@ class Octree
return getSign(&node->leaf, index);
}
else {
- if (hasChild(&node->internal, index)) {
- return getSign(getChild(&node->internal, getChildCount(&node->internal, index)),
+ if (node->internal.has_child(index)) {
+ return getSign(node->internal.get_child(node->internal.get_child_count(index)),
height - 1,
index);
}
else {
- return getSign(getChild(&node->internal, 0),
+ return getSign(node->internal.get_child(0),
height - 1,
- 7 - getChildIndex(&node->internal, 0));
+ 7 - node->internal.get_child_index(0));
}
}
}
@@ -469,7 +544,7 @@ class Octree
leaf->signs |= ((sign & 1) << index);
}
- int getSignMask(const LeafNode *leaf)
+ int getSignMask(const LeafNode *leaf) const
{
return leaf->signs;
}
@@ -536,7 +611,7 @@ class Octree
}
/// Get edge parity
- int getEdgeParity(LeafNode *leaf, int index)
+ int getEdgeParity(const LeafNode *leaf, int index) const
{
assert(index >= 0 && index <= 11);
@@ -597,7 +672,8 @@ class Octree
leaf->primary_edge_intersections |= (1 << pindex);
}
- int getStoredEdgesParity(LeafNode *leaf, int pindex)
+
+ int getStoredEdgesParity(const LeafNode *leaf, int pindex) const
{
assert(pindex <= 2 && pindex >= 0);
@@ -652,7 +728,7 @@ class Octree
InternalNode *parent = locateParent(node, len, st, count);
// Update
- setChild(parent, count, (Node *)leaf);
+ parent->set_child(count, (Node *)leaf);
}
void updateParent(InternalNode *node, int len, int st[3])
@@ -667,14 +743,14 @@ class Octree
InternalNode *parent = locateParent(len, st, count);
// UPdate
- setChild(parent, count, (Node *)node);
+ parent->set_child(count, (Node *)node);
}
/// Find edge intersection on a given edge
- int getEdgeIntersectionByIndex(int st[3], int index, float pt[3], int check)
+ int getEdgeIntersectionByIndex(int st[3], int index, float pt[3], int check) const
{
// First, locat the leaf
- LeafNode *leaf;
+ const LeafNode *leaf;
if (check) {
leaf = locateLeafCheck(st);
}
@@ -697,7 +773,7 @@ class Octree
}
/// Retrieve number of edges intersected
- int getPrimalEdgesMask(LeafNode *leaf)
+ int getPrimalEdgesMask(const LeafNode *leaf) const
{
return leaf->primary_edge_intersections;
}
@@ -710,7 +786,7 @@ class Octree
}
/// Get the count for a primary edge
- int getEdgeCount(LeafNode *leaf, int index)
+ int getEdgeCount(const LeafNode *leaf, int index) const
{
return edgeCountTable[getPrimalEdgesMask(leaf)][index];
}
@@ -744,7 +820,7 @@ class Octree
}
/// Retrieve edge intersection
- float getEdgeOffset(LeafNode *leaf, int count)
+ float getEdgeOffset(const LeafNode *leaf, int count) const
{
return leaf->edge_intersections[4 * count];
}
@@ -834,10 +910,11 @@ class Octree
}
/// Retrieve complete edge intersection
- void getEdgeIntersectionByIndex(LeafNode *leaf, int index, int st[3], int len, float pt[3], float nm[3])
+ void getEdgeIntersectionByIndex(const LeafNode *leaf, int index, int st[3],
+ int len, float pt[3], float nm[3]) const
{
int count = getEdgeCount(leaf, index);
- float *pts = leaf->edge_intersections;
+ const float *pts = leaf->edge_intersections;
float off = pts[4 * count];
@@ -865,7 +942,8 @@ class Octree
return off;
}
- void fillEdgeIntersections(LeafNode *leaf, int st[3], int len, float pts[12][3], float norms[12][3])
+ void fillEdgeIntersections(const LeafNode *leaf, int st[3], int len,
+ float pts[12][3], float norms[12][3]) const
{
int i;
// int stt[3] = {0, 0, 0};
@@ -890,7 +968,7 @@ class Octree
nst[i] += len;
// int nstt[3] = {0, 0, 0};
// nstt[i] += 1;
- LeafNode *node = locateLeaf(nst);
+ const LeafNode *node = locateLeaf(nst);
if (e1) {
// getEdgeIntersectionByIndex(node, femask[i][0], nstt, 1, pts[fmask[i][0]], norms[fmask[i][0]]);
@@ -912,7 +990,7 @@ class Octree
nst[i] -= len;
// int nstt[3] = {1, 1, 1};
// nstt[i] -= 1;
- LeafNode *node = locateLeaf(nst);
+ const LeafNode *node = locateLeaf(nst);
// getEdgeIntersectionByIndex(node, eemask[i], nstt, 1, pts[emask[i]], norms[emask[i]]);
getEdgeIntersectionByIndex(node, eemask[i], nst, len, pts[emask[i]], norms[emask[i]]);
@@ -921,7 +999,9 @@ class Octree
}
- void fillEdgeIntersections(LeafNode *leaf, int st[3], int len, float pts[12][3], float norms[12][3], int parity[12])
+ void fillEdgeIntersections(const LeafNode *leaf, int st[3], int len,
+ float pts[12][3], float norms[12][3],
+ int parity[12]) const
{
int i;
for (i = 0; i < 12; i++) {
@@ -948,7 +1028,7 @@ class Octree
nst[i] += len;
// int nstt[3] = {0, 0, 0};
// nstt[i] += 1;
- LeafNode *node = locateLeafCheck(nst);
+ const LeafNode *node = locateLeafCheck(nst);
if (node == NULL) {
continue;
}
@@ -979,7 +1059,7 @@ class Octree
nst[i] -= len;
// int nstt[3] = {1, 1, 1};
// nstt[i] -= 1;
- LeafNode *node = locateLeafCheck(nst);
+ const LeafNode *node = locateLeafCheck(nst);
if (node == NULL) {
continue;
}
@@ -1088,7 +1168,20 @@ class Octree
int index = (((st[0] >> i) & 1) << 2) |
(((st[1] >> i) & 1) << 1) |
(((st[2] >> i) & 1));
- node = getChild(&node->internal, getChildCount(&node->internal, index));
+ node = node->internal.get_child(node->internal.get_child_count(index));
+ }
+
+ return &node->leaf;
+ }
+
+ const LeafNode *locateLeaf(int st[3]) const
+ {
+ const Node *node = root;
+ for (int i = GRID_DIMENSION - 1; i > GRID_DIMENSION - maxDepth - 1; i--) {
+ int index = (((st[0] >> i) & 1) << 2) |
+ (((st[1] >> i) & 1) << 1) |
+ (((st[2] >> i) & 1));
+ node = node->internal.get_child(node->internal.get_child_count(index));
}
return &node->leaf;
@@ -1102,8 +1195,7 @@ class Octree
index = (((st[0] & i) ? 4 : 0) |
((st[1] & i) ? 2 : 0) |
((st[2] & i) ? 1 : 0));
- node = getChild(&node->internal,
- getChildCount(&node->internal, index));
+ node = node->internal.get_child(node->internal.get_child_count(index));
}
return &node->leaf;
@@ -1116,10 +1208,26 @@ class Octree
int index = (((st[0] >> i) & 1) << 2) |
(((st[1] >> i) & 1) << 1) |
(((st[2] >> i) & 1));
- if (!hasChild(&node->internal, index)) {
+ if (!node->internal.has_child(index)) {
+ return NULL;
+ }
+ node = node->internal.get_child(node->internal.get_child_count(index));
+ }
+
+ return &node->leaf;
+ }
+
+ const LeafNode *locateLeafCheck(int st[3]) const
+ {
+ const Node *node = root;
+ for (int i = GRID_DIMENSION - 1; i > GRID_DIMENSION - maxDepth - 1; i--) {
+ int index = (((st[0] >> i) & 1) << 2) |
+ (((st[1] >> i) & 1) << 1) |
+ (((st[2] >> i) & 1));
+ if (!node->internal.has_child(index)) {
return NULL;
}
- node = getChild(&node->internal, getChildCount(&node->internal, index));
+ node = node->internal.get_child(node->internal.get_child_count(index));
}
return &node->leaf;
@@ -1135,10 +1243,10 @@ class Octree
((st[1] & i) ? 2 : 0) |
((st[2] & i) ? 1 : 0));
pre = node;
- node = &getChild(node, getChildCount(node, index))->internal;
+ node = &node->get_child(node->get_child_count(index))->internal;
}
- count = getChildCount(pre, index);
+ count = pre->get_child_count(index);
return pre;
}
@@ -1152,88 +1260,21 @@ class Octree
((st[1] & i) ? 2 : 0) |
((st[2] & i) ? 1 : 0));
pre = node;
- node = (InternalNode *)getChild(node, getChildCount(node, index));
+ node = &node->get_child(node->get_child_count(index))->internal;
}
- count = getChildCount(pre, index);
+ count = pre->get_child_count(index);
return pre;
}
/************ Operators for internal nodes ************/
- /// If child index exists
- int hasChild(InternalNode *node, int index)
- {
- return (node->has_child >> index) & 1;
- }
-
- /// Get the pointer to child index
- Node *getChild(InternalNode *node, int count)
- {
- return node->children[count];
- };
-
- /// Get total number of children
- int getNumChildren(InternalNode *node)
- {
- return numChildrenTable[node->has_child];
- }
-
- /// Get the count of children
- int getChildCount(InternalNode *node, int index)
- {
- return childrenCountTable[node->has_child][index];
- }
- int getChildIndex(InternalNode *node, int count)
- {
- return childrenIndexTable[node->has_child][count];
- }
- int *getChildCounts(InternalNode *node)
- {
- return childrenCountTable[node->has_child];
- }
-
- /// Get all children
- void fillChildren(InternalNode *node, Node *children[8], int leaf[8])
- {
- int count = 0;
- for (int i = 0; i < 8; i++) {
- leaf[i] = node->is_child_leaf(i);
- if (hasChild(node, i)) {
- children[i] = getChild(node, count);
- count++;
- }
- else {
- children[i] = NULL;
- leaf[i] = 0;
- }
- }
- }
-
- /// Sets the child pointer
- void setChild(InternalNode *node, int count, Node *chd)
- {
- node->children[count] = chd;
- }
- void setInternalChild(InternalNode *node, int index, int count, InternalNode *chd)
- {
- setChild(node, count, (Node *)chd);
- node->has_child |= (1 << index);
- }
- void setLeafChild(InternalNode *node, int index, int count, LeafNode *chd)
- {
- setChild(node, count, (Node *)chd);
- node->has_child |= (1 << index);
- node->child_is_leaf |= (1 << index);
- }
/// Add a kid to an existing internal node
- /// Fix me: can we do this without wasting memory ?
- /// Fixed: using variable memory
InternalNode *addChild(InternalNode *node, int index, Node *child, int aLeaf)
{
// Create new internal node
- int num = getNumChildren(node);
+ int num = node->get_num_children();
InternalNode *rnode = createInternal(num + 1);
// Establish children
@@ -1242,19 +1283,19 @@ class Octree
for (i = 0; i < 8; i++) {
if (i == index) {
if (aLeaf) {
- setLeafChild(rnode, i, count2, &child->leaf);
+ rnode->set_leaf_child(i, count2, &child->leaf);
}
else {
- setInternalChild(rnode, i, count2, &child->internal);
+ rnode->set_internal_child(i, count2, &child->internal);
}
count2++;
}
- else if (hasChild(node, i)) {
+ else if (node->has_child(i)) {
if (node->is_child_leaf(i)) {
- setLeafChild(rnode, i, count2, &getChild(node, count1)->leaf);
+ rnode->set_leaf_child(i, count2, &node->get_child(count1)->leaf);
}
else {
- setInternalChild(rnode, i, count2, &getChild(node, count1)->internal);
+ rnode->set_internal_child(i, count2, &node->get_child(count1)->internal);
}
count1++;
count2++;
@@ -1269,8 +1310,8 @@ class Octree
InternalNode *createInternal(int length)
{
InternalNode *inode = (InternalNode *)alloc[length]->allocate();
- inode->has_child = 0;
- inode->child_is_leaf = 0;
+ inode->has_child_bitfield = 0;
+ inode->child_is_leaf_bitfield = 0;
return inode;
}
@@ -1301,21 +1342,21 @@ class Octree
InternalNode *addLeafChild(InternalNode *par, int index, int count,
LeafNode *leaf)
{
- int num = getNumChildren(par) + 1;
+ int num = par->get_num_children() + 1;
InternalNode *npar = createInternal(num);
*npar = *par;
if (num == 1) {
- setLeafChild(npar, index, 0, leaf);
+ npar->set_leaf_child(index, 0, leaf);
}
else {
int i;
for (i = 0; i < count; i++) {
- setChild(npar, i, getChild(par, i));
+ npar->set_child(i, par->get_child(i));
}
- setLeafChild(npar, index, count, leaf);
+ npar->set_leaf_child(index, count, leaf);
for (i = count + 1; i < num; i++) {
- setChild(npar, i, getChild(par, i - 1));
+ npar->set_child(i, par->get_child(i - 1));
}
}
@@ -1326,21 +1367,21 @@ class Octree
InternalNode *addInternalChild(InternalNode *par, int index, int count,
InternalNode *node)
{
- int num = getNumChildren(par) + 1;
+ int num = par->get_num_children() + 1;
InternalNode *npar = createInternal(num);
*npar = *par;
if (num == 1) {
- setInternalChild(npar, index, 0, node);
+ npar->set_internal_child(index, 0, node);
}
else {
int i;
for (i = 0; i < count; i++) {
- setChild(npar, i, getChild(par, i));
+ npar->set_child(i, par->get_child(i));
}
- setInternalChild(npar, index, count, node);
+ npar->set_internal_child(index, count, node);
for (i = count + 1; i < num; i++) {
- setChild(npar, i, getChild(par, i - 1));
+ npar->set_child(i, par->get_child(i - 1));
}
}
diff --git a/intern/elbeem/intern/ntl_geometryshader.h b/intern/elbeem/intern/ntl_geometryshader.h
index 61598556b7e..f43df6539e6 100644
--- a/intern/elbeem/intern/ntl_geometryshader.h
+++ b/intern/elbeem/intern/ntl_geometryshader.h
@@ -46,7 +46,7 @@ class ntlGeometryShader :
/*! notify object that dump is in progress (e.g. for field dump) */
virtual void notifyShaderOfDump(int dumptype, int frameNr,char *frameNrStr,string outfilename) = 0;
- /*! get ouput filename, returns global render outfile if empty */
+ /*! get output filename, returns global render outfile if empty */
string getOutFilename( void ) { return mOutFilename; }
protected:
diff --git a/intern/elbeem/intern/utilities.cpp b/intern/elbeem/intern/utilities.cpp
index c912e70b281..2b9b8d5b8a5 100644
--- a/intern/elbeem/intern/utilities.cpp
+++ b/intern/elbeem/intern/utilities.cpp
@@ -51,7 +51,7 @@ int getElbeemState(void) {
return gElbeemState;
}
int isSimworldOk(void) {
- return (getElbeemState>=0);
+ return (getElbeemState() >=0);
}
// last error as string, acces with get/setElbeemErrorString
diff --git a/intern/ffmpeg/ffmpeg_compat.h b/intern/ffmpeg/ffmpeg_compat.h
index 2fd61570011..37cde2c2837 100644
--- a/intern/ffmpeg/ffmpeg_compat.h
+++ b/intern/ffmpeg/ffmpeg_compat.h
@@ -110,7 +110,7 @@ void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
#endif
/* there are some version inbetween, which have avio_... functions but no
- AVIO_FLAG_... */
+ * AVIO_FLAG_... */
#ifndef AVIO_FLAG_WRITE
#define AVIO_FLAG_WRITE URL_WRONLY
#endif
diff --git a/intern/ghost/GHOST_C-api.h b/intern/ghost/GHOST_C-api.h
index ae30458a5e5..87ab3c013c6 100644
--- a/intern/ghost/GHOST_C-api.h
+++ b/intern/ghost/GHOST_C-api.h
@@ -387,11 +387,12 @@ extern GHOST_TSuccess GHOST_SetCursorPosition(GHOST_SystemHandle systemhandle,
* \param windowhandle The handle to the window
* \param mode The new grab state of the cursor.
* \param bounds The grab ragion (optional) - left,top,right,bottom
+ * \param mouse_ungrab_xy XY for new mouse location (optional) - x,y
* \return Indication of success.
*/
extern GHOST_TSuccess GHOST_SetCursorGrab(GHOST_WindowHandle windowhandle,
GHOST_TGrabCursorMode mode,
- int *bounds);
+ int bounds[4], int mouse_ungrab_xy[2]);
/***************************************************************************************
* Access to mouse button and keyboard states.
diff --git a/intern/ghost/GHOST_IEventConsumer.h b/intern/ghost/GHOST_IEventConsumer.h
index 5682d04d434..5b6fa7ba046 100644
--- a/intern/ghost/GHOST_IEventConsumer.h
+++ b/intern/ghost/GHOST_IEventConsumer.h
@@ -42,8 +42,8 @@
* they want to receive events. The system will call the processEvent() method
* for every installed event consumer to pass events.
* \see GHOST_ISystem#addEventConsumer
- * \author Maarten Gribnau
- * \date May 14, 2001
+ * \author Maarten Gribnau
+ * \date May 14, 2001
*/
class GHOST_IEventConsumer
{
@@ -58,15 +58,14 @@ public:
/**
* This method is called by the system when it has events to dispatch.
* \see GHOST_ISystem#dispatchEvents
- * \param event The event that can be handled or ignored.
- * \return Indication as to whether the event was handled.
+ * \param event The event that can be handled or ignored.
+ * \return Indication as to whether the event was handled.
*/
virtual bool processEvent(GHOST_IEvent *event) = 0;
-
+
#ifdef WITH_CXX_GUARDEDALLOC
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_IEventConsumer")
#endif
};
-#endif // _GHOST_EVENT_CONSUMER_H_
-
+#endif /* __GHOST_IEVENTCONSUMER_H__ */
diff --git a/intern/ghost/GHOST_ISystem.h b/intern/ghost/GHOST_ISystem.h
index 8aef81bb762..ad5d2379787 100644
--- a/intern/ghost/GHOST_ISystem.h
+++ b/intern/ghost/GHOST_ISystem.h
@@ -47,14 +47,14 @@ class GHOST_IEventConsumer;
* \section intro Introduction
*
* GHOST is yet another acronym. It stands for "Generic Handy Operating System
- * Toolkit". It has been created to replace the OpenGL utility tool kit
+ * Toolkit". It has been created to replace the OpenGL utility tool kit
* <a href="http://www.opengl.org/developers/documentation/glut.html">GLUT</a>.
* GLUT was used in <a href="http://www.blender3d.com">Blender</a> until the
* point that Blender needed to be ported to Apple's Mac OSX. Blender needed a
* number of modifications in GLUT to work but the GLUT sources for OSX were
* unavailable at the time. The decision was made to build our own replacement
- * for GLUT. In those days, NaN Technologies BV was the company that developed
- * Blender.
+ * for GLUT. In those days, NaN Technologies BV was the company that developed
+ * Blender.
* <br><br>
* Enough history. What does GHOST have to offer?<br>
* In short: everything that Blender needed from GLUT to run on all it's supported
@@ -96,7 +96,7 @@ class GHOST_IEventConsumer;
* <li>The C-API. For programs written in C.</li>
* <li>The C++-API. For programs written in C++.</li>
* </ul>
- * GHOST itself is writtem in C++ and the C-API is a wrapper around the C++
+ * GHOST itself is writtem in C++ and the C-API is a wrapper around the C++
* API.
*
* \subsection cplusplus_api The C++ API consists of the following files:
@@ -113,7 +113,7 @@ class GHOST_IEventConsumer;
* program in the ?/ghost/test/gears/ directory.
*
* \subsection c_api The C-API
- * To use GHOST in programs written in C, include the file GHOST_C-API.h in
+ * To use GHOST in programs written in C, include the file GHOST_C-API.h in
* your program. This file includes the GHOST_Types.h file for all GHOST types
* and defines functions that give you access to the same functionality present
* in the C++ API.<br>
@@ -123,7 +123,7 @@ class GHOST_IEventConsumer;
* \section work Work in progress
* \todo write WIP section
*/
-
+
/** \interface GHOST_ISystem
* Interface for classes that provide access to the operating system.
* There should be only one system class in an application.
@@ -136,8 +136,8 @@ class GHOST_IEventConsumer;
* -# Access to the state of the mouse buttons and the keyboard.
* -# Menus for windows with events generated when they are accessed (this is
* work in progress).
- * \author Maarten Gribnau
- * \date May 30, 2001
+ * \author Maarten Gribnau
+ * \date May 30, 2001
*/
class GHOST_ISystem
{
@@ -190,12 +190,12 @@ public:
/**
* Installs a timer.
- * Note that, on most operating systems, messages need to be processed in order
+ * Note that, on most operating systems, messages need to be processed in order
* for the timer callbacks to be invoked.
- * \param delay The time to wait for the first call to the timerProc (in milliseconds)
- * \param interval The interval between calls to the timerProc (in milliseconds)
- * \param timerProc The callback invoked when the interval expires,
- * \param userData Placeholder for user data.
+ * \param delay The time to wait for the first call to the timerProc (in milliseconds)
+ * \param interval The interval between calls to the timerProc (in milliseconds)
+ * \param timerProc The callback invoked when the interval expires,
+ * \param userData Placeholder for user data.
* \return A timer task (0 if timer task installation failed).
*/
virtual GHOST_ITimerTask *installTimer(GHOST_TUns64 delay,
@@ -225,22 +225,22 @@ public:
* \return The dimension of the main display.
*/
virtual void getMainDisplayDimensions(GHOST_TUns32& width, GHOST_TUns32& height) const = 0;
-
+
/**
* Create a new window.
- * The new window is added to the list of windows managed.
+ * The new window is added to the list of windows managed.
* Never explicitly delete the window, use disposeWindow() instead.
- * \param title The name of the window (displayed in the title bar of the window if the OS supports it).
- * \param left The coordinate of the left edge of the window.
- * \param top The coordinate of the top edge of the window.
- * \param width The width the window.
- * \param height The height the window.
- * \param state The state of the window when opened.
- * \param type The type of drawing context installed in this window.
- * \param stereoVisual Create a stereo visual for quad buffered stereo.
- * \param numOfAASamples Number of samples used for AA (zero if no AA)
- * \param parentWindow Parent (embedder) window
- * \return The new window (or 0 if creation failed).
+ * \param title The name of the window (displayed in the title bar of the window if the OS supports it).
+ * \param left The coordinate of the left edge of the window.
+ * \param top The coordinate of the top edge of the window.
+ * \param width The width the window.
+ * \param height The height the window.
+ * \param state The state of the window when opened.
+ * \param type The type of drawing context installed in this window.
+ * \param stereoVisual Create a stereo visual for quad buffered stereo.
+ * \param numOfAASamples Number of samples used for AA (zero if no AA)
+ * \param parentWindow Parent (embedder) window
+ * \return The new window (or 0 if creation failed).
*/
virtual GHOST_IWindow *createWindow(
const STR_String& title,
@@ -252,40 +252,40 @@ public:
/**
* Dispose a window.
- * \param window Pointer to the window to be disposed.
- * \return Indication of success.
+ * \param window Pointer to the window to be disposed.
+ * \return Indication of success.
*/
virtual GHOST_TSuccess disposeWindow(GHOST_IWindow *window) = 0;
/**
* Returns whether a window is valid.
- * \param window Pointer to the window to be checked.
- * \return Indication of validity.
+ * \param window Pointer to the window to be checked.
+ * \return Indication of validity.
*/
virtual bool validWindow(GHOST_IWindow *window) = 0;
/**
* Begins full screen mode.
- * \param setting The new setting of the display.
- * \param window Window displayed in full screen.
- * This window is invalid after full screen has been ended.
- * \return Indication of success.
+ * \param setting The new setting of the display.
+ * \param window Window displayed in full screen.
+ * This window is invalid after full screen has been ended.
+ * \return Indication of success.
*/
virtual GHOST_TSuccess beginFullScreen(const GHOST_DisplaySetting& setting, GHOST_IWindow **window,
const bool stereoVisual, const GHOST_TUns16 numOfAASamples = 0) = 0;
-
+
/**
* Updates the resolution while in fullscreen mode.
- * \param setting The new setting of the display.
- * \param window Window displayed in full screen.
+ * \param setting The new setting of the display.
+ * \param window Window displayed in full screen.
*
- * \return Indication of success.
+ * \return Indication of success.
*/
virtual GHOST_TSuccess updateFullScreen(const GHOST_DisplaySetting& setting, GHOST_IWindow **window) = 0;
/**
* Ends full screen mode.
- * \return Indication of success.
+ * \return Indication of success.
*/
virtual GHOST_TSuccess endFullScreen(void) = 0;
@@ -305,7 +305,7 @@ public:
* \return Indication of the presence of events.
*/
virtual bool processEvents(bool waitForEvent) = 0;
-
+
/**
* Retrieves events from the queue and send them to the event consumers.
* \return Indication of the presence of events.
@@ -332,18 +332,18 @@ public:
/**
* Returns the current location of the cursor (location in screen coordinates)
- * \param x The x-coordinate of the cursor.
- * \param y The y-coordinate of the cursor.
- * \return Indication of success.
+ * \param x The x-coordinate of the cursor.
+ * \param y The y-coordinate of the cursor.
+ * \return Indication of success.
*/
virtual GHOST_TSuccess getCursorPosition(GHOST_TInt32& x, GHOST_TInt32& y) const = 0;
/**
* Updates the location of the cursor (location in screen coordinates).
* Not all operating systems allow the cursor to be moved (without the input device being moved).
- * \param x The x-coordinate of the cursor.
- * \param y The y-coordinate of the cursor.
- * \return Indication of success.
+ * \param x The x-coordinate of the cursor.
+ * \param y The y-coordinate of the cursor.
+ * \return Indication of success.
*/
virtual GHOST_TSuccess setCursorPosition(GHOST_TInt32 x, GHOST_TInt32 y) = 0;
@@ -353,17 +353,17 @@ public:
/**
* Returns the state of a modifier key (ouside the message queue).
- * \param mask The modifier key state to retrieve.
- * \param isDown The state of a modifier key (true == pressed).
- * \return Indication of success.
+ * \param mask The modifier key state to retrieve.
+ * \param isDown The state of a modifier key (true == pressed).
+ * \return Indication of success.
*/
virtual GHOST_TSuccess getModifierKeyState(GHOST_TModifierKeyMask mask, bool& isDown) const = 0;
/**
* Returns the state of a mouse button (ouside the message queue).
- * \param mask The button state to retrieve.
- * \param isDown Button state.
- * \return Indication of success.
+ * \param mask The button state to retrieve.
+ * \param isDown Button state.
+ * \return Indication of success.
*/
virtual GHOST_TSuccess getButtonState(GHOST_TButtonMask mask, bool& isDown) const = 0;
@@ -378,11 +378,11 @@ public:
* \return current status (1 -visible, 0 - hidden)
*/
virtual int toggleConsole(int action) = 0;
-
+
/***************************************************************************************
* Access to clipboard.
***************************************************************************************/
-
+
/**
* Returns the selection buffer
* \return Returns "unsinged char" from X11 XA_CUT_BUFFER0 buffer
diff --git a/intern/ghost/GHOST_IWindow.h b/intern/ghost/GHOST_IWindow.h
index a1a1acfca75..88f130aabe8 100644
--- a/intern/ghost/GHOST_IWindow.h
+++ b/intern/ghost/GHOST_IWindow.h
@@ -41,20 +41,20 @@
/**
* Interface for GHOST windows.
*
- * You can create a window with the system's GHOST_ISystem::createWindow
+ * You can create a window with the system's GHOST_ISystem::createWindow
* method.
* \see GHOST_ISystem#createWindow
*
* There are two coordinate systems:
* <ul>
* <li>The screen coordinate system. The origin of the screen is located in the
- * upper left corner of the screen.</li>
+ * upper left corner of the screen.</li>
* <li>The client rectangle coordinate system. The client rectangle of a window
* is the area that is drawable by the application (excluding title bars etc.).
- * </li>
+ * </li>
* </ul>
- * \author Maarten Gribnau
- * \date May 31, 2001
+ * \author Maarten Gribnau
+ * \date May 31, 2001
*/
class GHOST_IWindow
{
@@ -86,20 +86,20 @@ public:
/**
* Tries to install a rendering context in this window.
- * \param type The type of rendering context installed.
+ * \param type The type of rendering context installed.
* \return Indication as to whether installation has succeeded.
*/
virtual GHOST_TSuccess setDrawingContextType(GHOST_TDrawingContextType type) = 0;
/**
* Sets the title displayed in the title bar.
- * \param title The title to display in the title bar.
+ * \param title The title to display in the title bar.
*/
virtual void setTitle(const STR_String& title) = 0;
/**
* Returns the title displayed in the title bar.
- * \param title The title displayed in the title bar.
+ * \param title The title displayed in the title bar.
*/
virtual void getTitle(STR_String& title) const = 0;
@@ -109,7 +109,7 @@ public:
* \param bounds The bounding rectangle of the window.
*/
virtual void getWindowBounds(GHOST_Rect& bounds) const = 0;
-
+
/**
* Returns the client rectangle dimensions.
* The left and top members of the rectangle are always zero.
@@ -131,26 +131,26 @@ public:
/**
* Resizes client rectangle.
- * \param width The new width of the client area of the window.
- * \param height The new height of the client area of the window.
+ * \param width The new width of the client area of the window.
+ * \param height The new height of the client area of the window.
*/
virtual GHOST_TSuccess setClientSize(GHOST_TUns32 width, GHOST_TUns32 height) = 0;
/**
* Converts a point in screen coordinates to client rectangle coordinates
- * \param inX The x-coordinate on the screen.
- * \param inY The y-coordinate on the screen.
- * \param outX The x-coordinate in the client rectangle.
- * \param outY The y-coordinate in the client rectangle.
+ * \param inX The x-coordinate on the screen.
+ * \param inY The y-coordinate on the screen.
+ * \param outX The x-coordinate in the client rectangle.
+ * \param outY The y-coordinate in the client rectangle.
*/
virtual void screenToClient(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const = 0;
/**
* Converts a point in screen coordinates to client rectangle coordinates
- * \param inX The x-coordinate in the client rectangle.
- * \param inY The y-coordinate in the client rectangle.
- * \param outX The x-coordinate on the screen.
- * \param outY The y-coordinate on the screen.
+ * \param inX The x-coordinate in the client rectangle.
+ * \param inY The y-coordinate in the client rectangle.
+ * \param outX The x-coordinate on the screen.
+ * \param outY The y-coordinate on the screen.
*/
virtual void clientToScreen(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const = 0;
@@ -158,13 +158,13 @@ public:
* Tells if the ongoing drag'n'drop object can be accepted upon mouse drop
*/
virtual void setAcceptDragOperation(bool canAccept) = 0;
-
+
/**
* Returns acceptance of the dropped object
* Usually called by the "object dropped" event handling function
*/
virtual bool canAcceptDragOperation() const = 0;
-
+
/**
* Returns the state of the window (normal, minimized, maximized).
* \return The state of the window.
@@ -184,13 +184,13 @@ public:
* \return Indication of success.
*/
virtual GHOST_TSuccess setModifiedState(bool isUnsavedChanges) = 0;
-
+
/**
* Gets the window "modified" status, indicating unsaved changes
* \return True if there are unsaved changes
*/
virtual bool getModifiedState() = 0;
-
+
/**
* Sets the order of the window (bottom, top).
* \param order The order of the window.
@@ -200,13 +200,13 @@ public:
/**
* Swaps front and back buffers of a window.
- * \return A boolean success indicator.
+ * \return A boolean success indicator.
*/
virtual GHOST_TSuccess swapBuffers() = 0;
/**
* Activates the drawing context of this window.
- * \return A boolean success indicator.
+ * \return A boolean success indicator.
*/
virtual GHOST_TSuccess activateDrawingContext() = 0;
@@ -215,71 +215,71 @@ public:
* \return Indication of success.
*/
virtual GHOST_TSuccess invalidate() = 0;
-
+
/**
* Returns the window user data.
* \return The window user data.
*/
virtual GHOST_TUserDataPtr getUserData() const = 0;
-
+
/**
* Changes the window user data.
* \param data The window user data.
*/
virtual void setUserData(const GHOST_TUserDataPtr userData) = 0;
-
+
/**
* Returns the tablet data (pressure etc).
* \return The tablet data (pressure etc).
*/
virtual const GHOST_TabletData *GetTabletData() = 0;
-
+
/***************************************************************************************
* Progress bar functionality
***************************************************************************************/
-
+
/**
* Sets the progress bar value displayed in the window/application icon
* \param progress The progress %
*/
virtual GHOST_TSuccess setProgressBar(float progress) = 0;
-
+
/**
* Hides the progress bar in the icon
*/
virtual GHOST_TSuccess endProgressBar() = 0;
-
+
/***************************************************************************************
* Cursor management functionality
***************************************************************************************/
/**
* Returns the current cursor shape.
- * \return The current cursor shape.
+ * \return The current cursor shape.
*/
virtual GHOST_TStandardCursor getCursorShape() const = 0;
/**
* Set the shape of the cursor.
- * \param cursor The new cursor shape type id.
- * \return Indication of success.
+ * \param cursor The new cursor shape type id.
+ * \return Indication of success.
*/
virtual GHOST_TSuccess setCursorShape(GHOST_TStandardCursor cursorShape) = 0;
/**
* Set the shape of the cursor to a custom cursor.
- * \param bitmap The bitmap data for the cursor.
- * \param mask The mask data for the cursor.
- * \param hotX The X coordinate of the cursor hotspot.
- * \param hotY The Y coordinate of the cursor hotspot.
- * \return Indication of success.
+ * \param bitmap The bitmap data for the cursor.
+ * \param mask The mask data for the cursor.
+ * \param hotX The X coordinate of the cursor hotspot.
+ * \param hotY The Y coordinate of the cursor hotspot.
+ * \return Indication of success.
*/
- virtual GHOST_TSuccess setCustomCursorShape(GHOST_TUns8 bitmap[16][2],
+ virtual GHOST_TSuccess setCustomCursorShape(GHOST_TUns8 bitmap[16][2],
GHOST_TUns8 mask[16][2],
int hotX,
int hotY) = 0;
- virtual GHOST_TSuccess setCustomCursorShape(GHOST_TUns8 *bitmap,
+ virtual GHOST_TSuccess setCustomCursorShape(GHOST_TUns8 *bitmap,
GHOST_TUns8 *mask,
int sizex, int sizey,
int hotX, int hotY,
@@ -287,23 +287,23 @@ public:
/**
* Returns the visibility state of the cursor.
- * \return The visibility state of the cursor.
+ * \return The visibility state of the cursor.
*/
virtual bool getCursorVisibility() const = 0;
/**
* Shows or hides the cursor.
- * \param visible The new visibility state of the cursor.
- * \return Indication of success.
+ * \param visible The new visibility state of the cursor.
+ * \return Indication of success.
*/
virtual GHOST_TSuccess setCursorVisibility(bool visible) = 0;
/**
* Grabs the cursor for a modal operation.
- * \param grab The new grab state of the cursor.
- * \return Indication of success.
+ * \param grab The new grab state of the cursor.
+ * \return Indication of success.
*/
- virtual GHOST_TSuccess setCursorGrab(GHOST_TGrabCursorMode mode, GHOST_Rect *bounds) { return GHOST_kSuccess; }
+ virtual GHOST_TSuccess setCursorGrab(GHOST_TGrabCursorMode mode, GHOST_Rect *bounds, GHOST_TInt32 mouse_ungrab_xy[2]) { return GHOST_kSuccess; }
#ifdef WITH_CXX_GUARDEDALLOC
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_IWindow")
diff --git a/intern/ghost/GHOST_Rect.h b/intern/ghost/GHOST_Rect.h
index e52d6a7e6a0..a055b6f7f0d 100644
--- a/intern/ghost/GHOST_Rect.h
+++ b/intern/ghost/GHOST_Rect.h
@@ -41,8 +41,8 @@
* The four extreme coordinates are stored as left, top, right and bottom.
* To be valid, a rectangle should have a left coordinate smaller than or equal to right.
* To be valid, a rectangle should have a top coordinate smaller than or equal to bottom.
- * \author Maarten Gribnau
- * \date May 10, 2001
+ * \author Maarten Gribnau
+ * \date May 10, 2001
*/
class GHOST_Rect {
@@ -50,10 +50,10 @@ public:
/**
* Constructs a rectangle with the given values.
- * \param l requested left coordinate of the rectangle
- * \param t requested top coordinate of the rectangle
- * \param r requested right coordinate of the rectangle
- * \param b requested bottom coordinate of the rectangle
+ * \param l requested left coordinate of the rectangle
+ * \param t requested top coordinate of the rectangle
+ * \param r requested right coordinate of the rectangle
+ * \param b requested bottom coordinate of the rectangle
*/
GHOST_Rect(GHOST_TInt32 l = 0, GHOST_TInt32 t = 0, GHOST_TInt32 r = 0, GHOST_TInt32 b = 0)
: m_l(l), m_t(t), m_r(r), m_b(b)
@@ -61,85 +61,84 @@ public:
/**
* Copy constructor.
- * \param r rectangle to copy
+ * \param r rectangle to copy
*/
GHOST_Rect(const GHOST_Rect& r)
: m_l(r.m_l), m_t(r.m_t), m_r(r.m_r), m_b(r.m_b)
{}
-
+
/**
* Destructor.
*/
- virtual ~GHOST_Rect()
- {};
+ virtual ~GHOST_Rect() {}
/**
* Access to rectangle width.
- * \return width of the rectangle
+ * \return width of the rectangle
*/
virtual inline GHOST_TInt32 getWidth() const;
/**
* Access to rectangle height.
- * \return height of the rectangle
+ * \return height of the rectangle
*/
virtual inline GHOST_TInt32 getHeight() const;
/**
* Sets all members of the rectangle.
- * \param l requested left coordinate of the rectangle
- * \param t requested top coordinate of the rectangle
- * \param r requested right coordinate of the rectangle
- * \param b requested bottom coordinate of the rectangle
+ * \param l requested left coordinate of the rectangle
+ * \param t requested top coordinate of the rectangle
+ * \param r requested right coordinate of the rectangle
+ * \param b requested bottom coordinate of the rectangle
*/
virtual inline void set(GHOST_TInt32 l, GHOST_TInt32 t, GHOST_TInt32 r, GHOST_TInt32 b);
/**
* Returns whether this rectangle is empty.
* Empty rectangles are rectangles that have width==0 and/or height==0.
- * \return boolean value (true==empty rectangle)
+ * \return boolean value (true==empty rectangle)
*/
virtual inline bool isEmpty() const;
/**
* Returns whether this rectangle is valid.
* Valid rectangles are rectangles that have m_l <= m_r and m_t <= m_b. Thus, emapty rectangles are valid.
- * \return boolean value (true==valid rectangle)
+ * \return boolean value (true==valid rectangle)
*/
virtual inline bool isValid() const;
/**
* Grows (or shrinks the rectangle).
* The method avoids negative insets making the rectangle invalid
- * \param i The amount of offset given to each extreme (negative values shrink the rectangle).
+ * \param i The amount of offset given to each extreme (negative values shrink the rectangle).
*/
virtual void inset(GHOST_TInt32 i);
/**
* Does a union of the rectangle given and this rectangle.
* The result is stored in this rectangle.
- * \param r The rectangle that is input for the union operation.
+ * \param r The rectangle that is input for the union operation.
*/
virtual inline void unionRect(const GHOST_Rect& r);
/**
* Grows the rectangle to included a point.
- * \param x The x-coordinate of the point.
- * \param y The y-coordinate of the point.
+ * \param x The x-coordinate of the point.
+ * \param y The y-coordinate of the point.
*/
virtual inline void unionPoint(GHOST_TInt32 x, GHOST_TInt32 y);
/**
* Grows the rectangle to included a point.
- * \param x The x-coordinate of the point.
- * \param y The y-coordinate of the point.
+ * \param x The x-coordinate of the point.
+ * \param y The y-coordinate of the point.
*/
virtual inline void wrapPoint(GHOST_TInt32 &x, GHOST_TInt32 &y, GHOST_TInt32 ofs);
/**
* Returns whether the point is inside this rectangle.
* Point on the boundary is considered inside.
- * \param x x-coordinate of point to test.
+ * \param x x-coordinate of point to test.
* \param y y-coordinate of point to test.
* \return boolean value (true if point is inside).
*/
@@ -147,16 +146,16 @@ public:
/**
* Returns whether the rectangle is inside this rectangle.
- * \param r rectangle to test.
- * \return visibility (not, partially or fully visible).
+ * \param r rectangle to test.
+ * \return visibility (not, partially or fully visible).
*/
virtual GHOST_TVisibility getVisibility(GHOST_Rect& r) const;
/**
* Sets rectangle members.
* Sets rectangle members such that it is centered at the given location.
- * \param cx requested center x-coordinate of the rectangle
- * \param cy requested center y-coordinate of the rectangle
+ * \param cx requested center x-coordinate of the rectangle
+ * \param cy requested center y-coordinate of the rectangle
*/
virtual void setCenter(GHOST_TInt32 cx, GHOST_TInt32 cy);
@@ -164,10 +163,10 @@ public:
* Sets rectangle members.
* Sets rectangle members such that it is centered at the given location,
* with the width requested.
- * \param cx requested center x-coordinate of the rectangle
- * \param cy requested center y-coordinate of the rectangle
- * \param w requested width of the rectangle
- * \param h requested height of the rectangle
+ * \param cx requested center x-coordinate of the rectangle
+ * \param cy requested center y-coordinate of the rectangle
+ * \param w requested width of the rectangle
+ * \param h requested height of the rectangle
*/
virtual void setCenter(GHOST_TInt32 cx, GHOST_TInt32 cy, GHOST_TInt32 w, GHOST_TInt32 h);
@@ -175,8 +174,8 @@ public:
* Clips a rectangle.
* Updates the rectangle given such that it will fit within this one.
* This can result in an empty rectangle.
- * \param r the rectangle to clip
- * \return whether clipping has occurred
+ * \param r the rectangle to clip
+ * \return whether clipping has occurred
*/
virtual bool clip(GHOST_Rect& r) const;
diff --git a/intern/ghost/GHOST_Types.h b/intern/ghost/GHOST_Types.h
index c6d364c361c..868d787b5f9 100644
--- a/intern/ghost/GHOST_Types.h
+++ b/intern/ghost/GHOST_Types.h
@@ -50,7 +50,7 @@ typedef unsigned short GHOST_TUns16;
typedef int GHOST_TInt32;
typedef unsigned int GHOST_TUns32;
-#if defined(WIN32) && !defined(FREE_WINDOWS)
+#ifdef _MSC_VER
typedef __int64 GHOST_TInt64;
typedef unsigned __int64 GHOST_TUns64;
#else
@@ -388,7 +388,7 @@ typedef struct {
typedef struct {
/** Displacement of a mouse wheel. */
- GHOST_TInt32 z;
+ GHOST_TInt32 z;
} GHOST_TEventWheelData;
typedef enum {
diff --git a/intern/ghost/intern/GHOST_C-api.cpp b/intern/ghost/intern/GHOST_C-api.cpp
index 0a4325930d5..88d02c46f61 100644
--- a/intern/ghost/intern/GHOST_C-api.cpp
+++ b/intern/ghost/intern/GHOST_C-api.cpp
@@ -355,10 +355,11 @@ GHOST_TSuccess GHOST_SetCursorPosition(GHOST_SystemHandle systemhandle,
GHOST_TSuccess GHOST_SetCursorGrab(GHOST_WindowHandle windowhandle,
GHOST_TGrabCursorMode mode,
- int *bounds)
+ int bounds[4], int mouse_ungrab_xy[2])
{
GHOST_IWindow *window = (GHOST_IWindow *) windowhandle;
GHOST_Rect bounds_rect, bounds_win;
+ GHOST_TInt32 mouse_ungrab_xy_global[2];
if (bounds) {
/* if this is X11 specific we need a function that converts */
@@ -368,7 +369,16 @@ GHOST_TSuccess GHOST_SetCursorGrab(GHOST_WindowHandle windowhandle,
}
- return window->setCursorGrab(mode, bounds ? &bounds_rect : NULL);
+ if (mouse_ungrab_xy) {
+ if (bounds == NULL)
+ window->getClientBounds(bounds_win);
+ window->clientToScreen(mouse_ungrab_xy[0], bounds_win.getHeight() - mouse_ungrab_xy[1],
+ mouse_ungrab_xy_global[0], mouse_ungrab_xy_global[1]);
+ }
+
+ return window->setCursorGrab(mode,
+ bounds ? &bounds_rect : NULL,
+ mouse_ungrab_xy ? mouse_ungrab_xy_global : NULL);
}
diff --git a/intern/ghost/intern/GHOST_Debug.h b/intern/ghost/intern/GHOST_Debug.h
index c364f1d26a4..f0db1b3de8d 100644
--- a/intern/ghost/intern/GHOST_Debug.h
+++ b/intern/ghost/intern/GHOST_Debug.h
@@ -33,12 +33,12 @@
#ifndef __GHOST_DEBUG_H__
#define __GHOST_DEBUG_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
+#ifdef _MSC_VER
# ifdef DEBUG
# pragma warning (disable:4786) // suppress stl-MSVC debug info warning
// #define GHOST_DEBUG
# endif // DEBUG
-#endif // WIN32
+#endif // _MSC_VER
#ifdef WITH_GHOST_DEBUG
# define GHOST_DEBUG // spit ghost events to stdout
diff --git a/intern/ghost/intern/GHOST_DisplayManagerCocoa.mm b/intern/ghost/intern/GHOST_DisplayManagerCocoa.mm
index c5a2fecd3b8..555f883cbf2 100644
--- a/intern/ghost/intern/GHOST_DisplayManagerCocoa.mm
+++ b/intern/ghost/intern/GHOST_DisplayManagerCocoa.mm
@@ -102,7 +102,7 @@ GHOST_TSuccess GHOST_DisplayManagerCocoa::getCurrentDisplaySetting(GHOST_TUns8 d
GHOST_ASSERT((display==kMainDisplay), "GHOST_DisplayManagerCocoa::getCurrentDisplaySetting(): only main display is supported");
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (display == kMainDisplay) //Screen #0 may not be the main one
askedDisplay = [NSScreen mainScreen];
diff --git a/intern/ghost/intern/GHOST_DisplayManagerX11.cpp b/intern/ghost/intern/GHOST_DisplayManagerX11.cpp
index 0bd90854a31..754218191a5 100644
--- a/intern/ghost/intern/GHOST_DisplayManagerX11.cpp
+++ b/intern/ghost/intern/GHOST_DisplayManagerX11.cpp
@@ -88,8 +88,8 @@ getNumDisplaySettings(
#else
/* We only have one X11 setting at the moment. */
- GHOST_ASSERT(display < 1, "Only single display systems are currently supported.\n");
- numSettings = GHOST_TInt32(1);
+ GHOST_ASSERT(display < 1, "Only single display systems are currently supported.\n");
+ numSettings = 1;
#endif
return GHOST_kSuccess;
@@ -130,8 +130,8 @@ getDisplaySetting(
setting.bpp = DefaultDepth(dpy, DefaultScreen(dpy));
#else
- GHOST_ASSERT(display < 1, "Only single display systems are currently supported.\n");
- GHOST_ASSERT(index < 1, "Requested setting outside of valid range.\n");
+ GHOST_ASSERT(display < 1, "Only single display systems are currently supported.\n");
+ GHOST_ASSERT(index < 1, "Requested setting outside of valid range.\n");
Display *x_display = m_system->getXDisplay();
@@ -160,7 +160,7 @@ getCurrentDisplaySetting(
/* According to the xf86vidmodegetallmodelines man page,
* "The first element of the array corresponds to the current video mode."
*/
- return getDisplaySetting(display, GHOST_TInt32(0), setting);
+ return getDisplaySetting(display, 0, setting);
}
diff --git a/intern/ghost/intern/GHOST_EventDragnDrop.h b/intern/ghost/intern/GHOST_EventDragnDrop.h
index cef9bb0a34a..c51f9568087 100644
--- a/intern/ghost/intern/GHOST_EventDragnDrop.h
+++ b/intern/ghost/intern/GHOST_EventDragnDrop.h
@@ -72,13 +72,13 @@ class GHOST_EventDragnDrop : public GHOST_Event
public:
/**
* Constructor.
- * \param time The time this event was generated.
- * \param type The type of this event.
- * \param dataType The type of the drop candidate object
- * \param window The window where the event occurred
- * \param x The x-coordinate of the location the cursor was at at the time of the event.
- * \param y The y-coordinate of the location the cursor was at at the time of the event.
- * \param data The "content" dropped in the window
+ * \param time The time this event was generated.
+ * \param type The type of this event.
+ * \param dataType The type of the drop candidate object
+ * \param window The window where the event occurred
+ * \param x The x-coordinate of the location the cursor was at at the time of the event.
+ * \param y The y-coordinate of the location the cursor was at at the time of the event.
+ * \param data The "content" dropped in the window
*/
GHOST_EventDragnDrop(GHOST_TUns64 time,
GHOST_TEventType type,
diff --git a/intern/ghost/intern/GHOST_EventManager.cpp b/intern/ghost/intern/GHOST_EventManager.cpp
index b8660b3038e..014eef85aa8 100644
--- a/intern/ghost/intern/GHOST_EventManager.cpp
+++ b/intern/ghost/intern/GHOST_EventManager.cpp
@@ -70,7 +70,7 @@ GHOST_TUns32 GHOST_EventManager::getNumEvents(GHOST_TEventType type)
{
GHOST_TUns32 numEvents = 0;
TEventStack::iterator p;
- for (p = m_events.begin(); p != m_events.end(); p++) {
+ for (p = m_events.begin(); p != m_events.end(); ++p) {
if ((*p)->getType() == type) {
numEvents++;
}
@@ -82,7 +82,7 @@ GHOST_TUns32 GHOST_EventManager::getNumEvents(GHOST_TEventType type)
GHOST_IEvent *GHOST_EventManager::peekEvent()
{
GHOST_IEvent *event = 0;
- if (m_events.size() > 0) {
+ if (m_events.empty() == false) {
event = m_events.back();
}
return event;
@@ -110,7 +110,7 @@ bool GHOST_EventManager::dispatchEvent(GHOST_IEvent *event)
if (event) {
handled = true;
TConsumerVector::iterator iter;
- for (iter = m_consumers.begin(); iter != m_consumers.end(); iter++) {
+ for (iter = m_consumers.begin(); iter != m_consumers.end(); ++iter) {
if ((*iter)->processEvent(event)) {
handled = false;
}
@@ -212,7 +212,7 @@ void GHOST_EventManager::removeWindowEvents(GHOST_IWindow *window)
iter = m_events.begin();
}
else {
- iter++;
+ ++iter;
}
}
}
@@ -236,7 +236,7 @@ void GHOST_EventManager::removeTypeEvents(GHOST_TEventType type, GHOST_IWindow *
iter = m_events.begin();
}
else {
- iter++;
+ ++iter;
}
}
}
@@ -254,7 +254,7 @@ GHOST_IEvent *GHOST_EventManager::popEvent()
void GHOST_EventManager::disposeEvents()
{
- while (m_events.size() > 0) {
+ while (m_events.empty() == false) {
GHOST_ASSERT(m_events[0], "invalid event");
delete m_events[0];
m_events.pop_front();
diff --git a/intern/ghost/intern/GHOST_NDOFManager.h b/intern/ghost/intern/GHOST_NDOFManager.h
index 2baf0f6fa42..2c213752f94 100644
--- a/intern/ghost/intern/GHOST_NDOFManager.h
+++ b/intern/ghost/intern/GHOST_NDOFManager.h
@@ -107,7 +107,7 @@ class GHOST_NDOFManager
public:
GHOST_NDOFManager(GHOST_System&);
- virtual ~GHOST_NDOFManager() {};
+ virtual ~GHOST_NDOFManager() {}
// whether multi-axis functionality is available (via the OS or driver)
// does not imply that a device is plugged in or being used
diff --git a/intern/ghost/intern/GHOST_Rect.cpp b/intern/ghost/intern/GHOST_Rect.cpp
index dc30b3eb220..9af4f30ebc1 100644
--- a/intern/ghost/intern/GHOST_Rect.cpp
+++ b/intern/ghost/intern/GHOST_Rect.cpp
@@ -75,7 +75,7 @@ GHOST_TVisibility GHOST_Rect::getVisibility(GHOST_Rect& r) const
GHOST_TVisibility v;
if (lt && rt && lb && rb) {
// All points inside, rectangle is inside this
- v = GHOST_kFullyVisible;
+ v = GHOST_kFullyVisible;
}
else if (!(lt || rt || lb || rb)) {
// None of the points inside
diff --git a/intern/ghost/intern/GHOST_System.h b/intern/ghost/intern/GHOST_System.h
index 070bf914dda..d2e3377f6ce 100644
--- a/intern/ghost/intern/GHOST_System.h
+++ b/intern/ghost/intern/GHOST_System.h
@@ -206,7 +206,7 @@ public:
***************************************************************************************/
/** Inherited from GHOST_ISystem but left pure virtual
- * GHOST_TSuccess getCursorPosition(GHOST_TInt32& x, GHOST_TInt32& y) const = 0;
+ * GHOST_TSuccess getCursorPosition(GHOST_TInt32& x, GHOST_TInt32& y) const = 0;
* GHOST_TSuccess setCursorPosition(GHOST_TInt32 x, GHOST_TInt32 y)
*/
diff --git a/intern/ghost/intern/GHOST_SystemCarbon.cpp b/intern/ghost/intern/GHOST_SystemCarbon.cpp
index bb68ce8889c..f5784c7d451 100644
--- a/intern/ghost/intern/GHOST_SystemCarbon.cpp
+++ b/intern/ghost/intern/GHOST_SystemCarbon.cpp
@@ -126,7 +126,7 @@ static GHOST_TKey convertKey(int rawCode)
*/
static UInt32 dummy = 0;
Handle transData = (Handle) GetScriptManagerVariable(smKCHRCache);
- unsigned char vk = KeyTranslate(transData, rawCode, &dummy);
+ unsigned char vk = KeyTranslate(transData, rawCode, &dummy);
/* Map numpad based on rawcodes first, otherwise they
* look like non-numpad events.
* Added too: mapping the number keys, for french keyboards etc (ton)
diff --git a/intern/ghost/intern/GHOST_SystemCocoa.mm b/intern/ghost/intern/GHOST_SystemCocoa.mm
index 7bc40287dc3..27720a01a3f 100644
--- a/intern/ghost/intern/GHOST_SystemCocoa.mm
+++ b/intern/ghost/intern/GHOST_SystemCocoa.mm
@@ -355,16 +355,18 @@ static GHOST_TKey convertKey(int rawCode, unichar recvChar, UInt16 keyAction)
/* alphanumerical or punctuation key that is remappable in int'l keyboards */
if ((recvChar >= 'A') && (recvChar <= 'Z')) {
return (GHOST_TKey) (recvChar - 'A' + GHOST_kKeyA);
- } else if ((recvChar >= 'a') && (recvChar <= 'z')) {
+ }
+ else if ((recvChar >= 'a') && (recvChar <= 'z')) {
return (GHOST_TKey) (recvChar - 'a' + GHOST_kKeyA);
- } else {
+ }
+ else {
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
KeyboardLayoutRef keyLayout;
UCKeyboardLayout *uchrData;
KLGetCurrentKeyboardLayout(&keyLayout);
KLGetKeyboardLayoutProperty(keyLayout, kKLuchrData, (const void **)
- &uchrData);
+ &uchrData);
/*get actual character value of the "remappable" keys in int'l keyboards,
if keyboard layout is not correctly reported (e.g. some non Apple keyboards in Tiger),
then fallback on using the received charactersIgnoringModifiers */
@@ -457,7 +459,8 @@ extern "C" int GHOST_HACK_getFirstFile(char buf[FIRSTFILEBUFLG])
strncpy(buf, g_firstFileBuf, FIRSTFILEBUFLG - 1);
buf[FIRSTFILEBUFLG - 1] = '\0';
return 1;
- } else {
+ }
+ else {
return 0;
}
}
@@ -870,29 +873,30 @@ bool GHOST_SystemCocoa::processEvents(bool waitForEvent)
// SetMouseCoalescingEnabled(false, NULL);
//TODO : implement timer ??
-
- /*do {
+#if 0
+ do {
GHOST_TimerManager* timerMgr = getTimerManager();
if (waitForEvent) {
- GHOST_TUns64 next = timerMgr->nextFireTime();
- double timeOut;
-
- if (next == GHOST_kFireTimeNever) {
- timeOut = kEventDurationForever;
- } else {
- timeOut = (double)(next - getMilliSeconds())/1000.0;
- if (timeOut < 0.0)
- timeOut = 0.0;
- }
+ GHOST_TUns64 next = timerMgr->nextFireTime();
+ double timeOut;
+
+ if (next == GHOST_kFireTimeNever) {
+ timeOut = kEventDurationForever;
+ }
+ else {
+ timeOut = (double)(next - getMilliSeconds())/1000.0;
+ if (timeOut < 0.0)
+ timeOut = 0.0;
+ }
- ::ReceiveNextEvent(0, NULL, timeOut, false, &event);
+ ::ReceiveNextEvent(0, NULL, timeOut, false, &event);
}
if (timerMgr->fireTimers(getMilliSeconds())) {
- anyProcessed = true;
+ anyProcessed = true;
}
- */
+#endif
do {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
@@ -962,8 +966,10 @@ bool GHOST_SystemCocoa::processEvents(bool waitForEvent)
//Resend event to NSApp to ensure Mac wide events are handled
[NSApp sendEvent:event];
[pool drain];
- } while (event!= nil);
- //} while (waitForEvent && !anyProcessed); Needed only for timer implementation
+ } while (event != nil);
+#if 0
+ } while (waitForEvent && !anyProcessed); // Needed only for timer implementation
+#endif
if (m_needDelayedApplicationBecomeActiveEventProcessing) handleApplicationBecomeActiveEvent();
@@ -994,16 +1000,16 @@ GHOST_TSuccess GHOST_SystemCocoa::handleApplicationBecomeActiveEvent()
modifiers = [[[NSApplication sharedApplication] currentEvent] modifierFlags];
if ((modifiers & NSShiftKeyMask) != (m_modifierMask & NSShiftKeyMask)) {
- pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSShiftKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftShift) );
+ pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSShiftKeyMask) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp, window, GHOST_kKeyLeftShift));
}
if ((modifiers & NSControlKeyMask) != (m_modifierMask & NSControlKeyMask)) {
- pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSControlKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftControl) );
+ pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSControlKeyMask) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp, window, GHOST_kKeyLeftControl));
}
if ((modifiers & NSAlternateKeyMask) != (m_modifierMask & NSAlternateKeyMask)) {
- pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSAlternateKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftAlt) );
+ pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSAlternateKeyMask) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp, window, GHOST_kKeyLeftAlt));
}
if ((modifiers & NSCommandKeyMask) != (m_modifierMask & NSCommandKeyMask)) {
- pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSCommandKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyOS) );
+ pushEvent( new GHOST_EventKey(getMilliSeconds(), (modifiers & NSCommandKeyMask) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp, window, GHOST_kKeyOS));
}
m_modifierMask = modifiers;
@@ -1046,7 +1052,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleWindowEvent(GHOST_TEventType eventType,
case GHOST_kEventWindowSize:
if (!m_ignoreWindowSizedMessages)
{
- //Enforce only one resize message per event loop (coalescing all the live resize messages)
+ //Enforce only one resize message per event loop (coalescing all the live resize messages)
window->updateDrawingContext();
pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window) );
//Mouse up event is trapped by the resizing event loop, so send it anyway to the window manager
@@ -1083,7 +1089,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleDraggingEvent(GHOST_TEventType eventType
GHOST_TUns8 * temp_buff;
GHOST_TStringArray *strArray;
NSArray *droppedArray;
- size_t pastedTextSize;
+ size_t pastedTextSize;
NSString *droppedStr;
GHOST_TEventDataPtr eventData;
int i;
@@ -1120,7 +1126,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleDraggingEvent(GHOST_TEventType eventType
strArray->strings[i] = temp_buff;
}
- eventData = (GHOST_TEventDataPtr) strArray;
+ eventData = (GHOST_TEventDataPtr) strArray;
break;
case GHOST_kDragnDropTypeString:
@@ -1153,7 +1159,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleDraggingEvent(GHOST_TEventType eventType
NSEnumerator *enumerator;
NSImageRep *representation;
- ibuf = IMB_allocImBuf (imgSize.width , imgSize.height, 32, IB_rect);
+ ibuf = IMB_allocImBuf (imgSize.width, imgSize.height, 32, IB_rect);
if (!ibuf) {
[droppedImg release];
return GHOST_kFailure;
@@ -1285,12 +1291,13 @@ GHOST_TUns8 GHOST_SystemCocoa::handleQuitRequest()
if (m_windowManager->getAnyModifiedState())
{
int shouldQuit = NSRunAlertPanel(@"Exit Blender", @"Some changes have not been saved.\nDo you really want to quit ?",
- @"Cancel", @"Quit Anyway", nil);
+ @"Cancel", @"Quit Anyway", nil);
if (shouldQuit == NSAlertAlternateReturn)
{
pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventQuit, NULL) );
return GHOST_kExitNow;
- } else {
+ }
+ else {
//Give back focus to the blender window if user selected cancel quit
NSArray *windowsList = [NSApp orderedWindows];
if ([windowsList count]) {
@@ -1319,7 +1326,7 @@ bool GHOST_SystemCocoa::handleOpenDocumentRequest(void *filepathStr)
int confirmOpen = NSAlertAlternateReturn;
NSArray *windowsList;
char * temp_buff;
- size_t filenameTextSize;
+ size_t filenameTextSize;
GHOST_Window* window= (GHOST_Window*)m_windowManager->getActiveWindow();
if (!window) {
@@ -1405,7 +1412,8 @@ GHOST_TSuccess GHOST_SystemCocoa::handleTabletEvent(void *eventPtr, short eventT
ct.Active = GHOST_kTabletModeNone;
break;
}
- } else {
+ }
+ else {
// pointer is leaving - return to mouse
ct.Active = GHOST_kTabletModeNone;
}
@@ -1452,7 +1460,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
case NSLeftMouseDown:
case NSRightMouseDown:
case NSOtherMouseDown:
- pushEvent(new GHOST_EventButton([event timestamp]*1000, GHOST_kEventButtonDown, window, convertButton([event buttonNumber])));
+ pushEvent(new GHOST_EventButton([event timestamp] * 1000, GHOST_kEventButtonDown, window, convertButton([event buttonNumber])));
//Handle tablet events combined with mouse events
handleTabletEvent(event);
break;
@@ -1460,14 +1468,14 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
case NSLeftMouseUp:
case NSRightMouseUp:
case NSOtherMouseUp:
- pushEvent(new GHOST_EventButton([event timestamp]*1000, GHOST_kEventButtonUp, window, convertButton([event buttonNumber])));
+ pushEvent(new GHOST_EventButton([event timestamp] * 1000, GHOST_kEventButtonUp, window, convertButton([event buttonNumber])));
//Handle tablet events combined with mouse events
handleTabletEvent(event);
break;
case NSLeftMouseDragged:
case NSRightMouseDragged:
- case NSOtherMouseDragged:
+ case NSOtherMouseDragged:
//Handle tablet events combined with mouse events
handleTabletEvent(event);
@@ -1495,7 +1503,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
window->setCursorGrabAccum(x_accum, y_accum);
window->clientToScreenIntern(x_warp+x_accum, y_warp+y_accum, x, y);
- pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x, y));
+ pushEvent(new GHOST_EventCursor([event timestamp] * 1000, GHOST_kEventCursorMove, window, x, y));
}
break;
case GHOST_kGrabWrap: //Wrap cursor at area/window boundaries
@@ -1540,7 +1548,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
//Post event
window->getCursorGrabInitPos(x_cur, y_cur);
window->clientToScreenIntern(x_cur + x_accum, y_cur + y_accum, x, y);
- pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x, y));
+ pushEvent(new GHOST_EventCursor([event timestamp] * 1000, GHOST_kEventCursorMove, window, x, y));
}
break;
default:
@@ -1550,7 +1558,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
GHOST_TInt32 x, y;
window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
- pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x, y));
+ pushEvent(new GHOST_EventCursor([event timestamp] * 1000, GHOST_kEventCursorMove, window, x, y));
m_cursorDelta_x=0;
m_cursorDelta_y=0; //Mouse motion occurred between two cursor warps, so we can reset the delta counter
@@ -1572,7 +1580,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
if (deltaF == 0.0) break; //discard trackpad delta=0 events
delta = deltaF > 0.0 ? 1 : -1;
- pushEvent(new GHOST_EventWheel([event timestamp]*1000, window, delta));
+ pushEvent(new GHOST_EventWheel([event timestamp] * 1000, window, delta));
}
else {
NSPoint mousePos = [event locationInWindow];
@@ -1596,7 +1604,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
dy = -dy;
- pushEvent(new GHOST_EventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventScroll, x, y, dx, dy));
+ pushEvent(new GHOST_EventTrackpad([event timestamp] * 1000, window, GHOST_kTrackpadEventScroll, x, y, dx, dy));
}
}
break;
@@ -1606,8 +1614,8 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
NSPoint mousePos = [event locationInWindow];
GHOST_TInt32 x, y;
window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
- pushEvent(new GHOST_EventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventMagnify, x, y,
- [event magnification]*125.0 + 0.1, 0));
+ pushEvent(new GHOST_EventTrackpad([event timestamp] * 1000, window, GHOST_kTrackpadEventMagnify, x, y,
+ [event magnification] * 125.0 + 0.1, 0));
}
break;
@@ -1616,8 +1624,8 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
NSPoint mousePos = [event locationInWindow];
GHOST_TInt32 x, y;
window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
- pushEvent(new GHOST_EventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventRotate, x, y,
- -[event rotation] * 5.0, 0));
+ pushEvent(new GHOST_EventTrackpad([event timestamp] * 1000, window, GHOST_kTrackpadEventRotate, x, y,
+ -[event rotation] * 5.0, 0));
}
case NSEventTypeBeginGesture:
m_isGestureInProgress = true;
@@ -1692,10 +1700,11 @@ GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
break; //Cmd-Q is directly handled by Cocoa
if ([event type] == NSKeyDown) {
- pushEvent( new GHOST_EventKey([event timestamp]*1000, GHOST_kEventKeyDown, window, keyCode, ascii, utf8_buf) );
+ pushEvent( new GHOST_EventKey([event timestamp] * 1000, GHOST_kEventKeyDown, window, keyCode, ascii, utf8_buf) );
//printf("Key down rawCode=0x%x charsIgnoringModifiers=%c keyCode=%u ascii=%i %c utf8=%s\n",[event keyCode],[charsIgnoringModifiers length]>0?[charsIgnoringModifiers characterAtIndex:0]:' ',keyCode,ascii,ascii, utf8_buf);
- } else {
- pushEvent( new GHOST_EventKey([event timestamp]*1000, GHOST_kEventKeyUp, window, keyCode, 0, '\0') );
+ }
+ else {
+ pushEvent( new GHOST_EventKey([event timestamp] * 1000, GHOST_kEventKeyUp, window, keyCode, 0, '\0') );
//printf("Key up rawCode=0x%x charsIgnoringModifiers=%c keyCode=%u ascii=%i %c utf8=%s\n",[event keyCode],[charsIgnoringModifiers length]>0?[charsIgnoringModifiers characterAtIndex:0]:' ',keyCode,ascii,ascii, utf8_buf);
}
break;
@@ -1704,16 +1713,16 @@ GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
modifiers = [event modifierFlags];
if ((modifiers & NSShiftKeyMask) != (m_modifierMask & NSShiftKeyMask)) {
- pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSShiftKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftShift) );
+ pushEvent(new GHOST_EventKey([event timestamp] * 1000, (modifiers & NSShiftKeyMask) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp, window, GHOST_kKeyLeftShift));
}
if ((modifiers & NSControlKeyMask) != (m_modifierMask & NSControlKeyMask)) {
- pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSControlKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftControl) );
+ pushEvent(new GHOST_EventKey([event timestamp] * 1000, (modifiers & NSControlKeyMask) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp, window, GHOST_kKeyLeftControl));
}
if ((modifiers & NSAlternateKeyMask) != (m_modifierMask & NSAlternateKeyMask)) {
- pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSAlternateKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyLeftAlt) );
+ pushEvent(new GHOST_EventKey([event timestamp] * 1000, (modifiers & NSAlternateKeyMask) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp, window, GHOST_kKeyLeftAlt));
}
if ((modifiers & NSCommandKeyMask) != (m_modifierMask & NSCommandKeyMask)) {
- pushEvent( new GHOST_EventKey([event timestamp]*1000, (modifiers & NSCommandKeyMask)?GHOST_kEventKeyDown:GHOST_kEventKeyUp, window, GHOST_kKeyOS) );
+ pushEvent(new GHOST_EventKey([event timestamp] * 1000, (modifiers & NSCommandKeyMask) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp, window, GHOST_kKeyOS));
}
m_modifierMask = modifiers;
@@ -1734,7 +1743,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
GHOST_TUns8* GHOST_SystemCocoa::getClipboard(bool selection) const
{
GHOST_TUns8 * temp_buff;
- size_t pastedTextSize;
+ size_t pastedTextSize;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@@ -1780,7 +1789,8 @@ GHOST_TUns8* GHOST_SystemCocoa::getClipboard(bool selection) const
if(temp_buff) {
return temp_buff;
- } else {
+ }
+ else {
return NULL;
}
}
diff --git a/intern/ghost/intern/GHOST_SystemPaths.h b/intern/ghost/intern/GHOST_SystemPaths.h
index 53cad347293..22879c71e1e 100644
--- a/intern/ghost/intern/GHOST_SystemPaths.h
+++ b/intern/ghost/intern/GHOST_SystemPaths.h
@@ -40,13 +40,13 @@ protected:
* Constructor.
* Protected default constructor to force use of static createSystem member.
*/
- GHOST_SystemPaths() {};
+ GHOST_SystemPaths() {}
/**
* Destructor.
* Protected default constructor to force use of static dispose member.
*/
- virtual ~GHOST_SystemPaths() {};
+ virtual ~GHOST_SystemPaths() {}
public:
diff --git a/intern/ghost/intern/GHOST_SystemWin32.cpp b/intern/ghost/intern/GHOST_SystemWin32.cpp
index 52ebaf02404..46c71f57c6f 100644
--- a/intern/ghost/intern/GHOST_SystemWin32.cpp
+++ b/intern/ghost/intern/GHOST_SystemWin32.cpp
@@ -742,8 +742,6 @@ GHOST_EventKey *GHOST_SystemWin32::processKeyEvent(GHOST_IWindow *window, RAWINP
ascii = utf8_char[0] & 0x80 ? '?' : utf8_char[0];
}
- if (0x80 & state[VK_MENU]) utf8_char[0] = '\0';
-
event = new GHOST_EventKey(system->getMilliSeconds(), keyDown ? GHOST_kEventKeyDown : GHOST_kEventKeyUp, window, key, ascii, utf8_char);
#ifdef GHOST_DEBUG
diff --git a/intern/ghost/intern/GHOST_SystemX11.cpp b/intern/ghost/intern/GHOST_SystemX11.cpp
index e75ecfb641e..c9953c80a52 100644
--- a/intern/ghost/intern/GHOST_SystemX11.cpp
+++ b/intern/ghost/intern/GHOST_SystemX11.cpp
@@ -858,7 +858,7 @@ GHOST_SystemX11::processEvent(XEvent *xe)
}
case DestroyNotify:
- ::exit(-1);
+ ::exit(-1);
/* We're not interested in the following things.(yet...) */
case NoExpose:
case GraphicsExpose:
@@ -983,8 +983,7 @@ GHOST_SystemX11::processEvent(XEvent *xe)
default: {
#ifdef WITH_X11_XINPUT
- if (xe->type == window->GetXTablet().MotionEvent)
- {
+ if (xe->type == window->GetXTablet().MotionEvent) {
XDeviceMotionEvent *data = (XDeviceMotionEvent *)xe;
/* stroke might begin without leading ProxyIn event,
@@ -993,23 +992,23 @@ GHOST_SystemX11::processEvent(XEvent *xe)
setTabletMode(window, data->deviceid);
window->GetXTablet().CommonData.Pressure =
- data->axis_data[2] / ((float)window->GetXTablet().PressureLevels);
-
+ data->axis_data[2] / ((float)window->GetXTablet().PressureLevels);
+
/* the (short) cast and the &0xffff is bizarre and unexplained anywhere,
* but I got garbage data without it. Found it in the xidump.c source --matt */
window->GetXTablet().CommonData.Xtilt =
- (short)(data->axis_data[3] & 0xffff) / ((float)window->GetXTablet().XtiltLevels);
+ (short)(data->axis_data[3] & 0xffff) / ((float)window->GetXTablet().XtiltLevels);
window->GetXTablet().CommonData.Ytilt =
- (short)(data->axis_data[4] & 0xffff) / ((float)window->GetXTablet().YtiltLevels);
+ (short)(data->axis_data[4] & 0xffff) / ((float)window->GetXTablet().YtiltLevels);
}
- else if (xe->type == window->GetXTablet().ProxInEvent)
- {
+ else if (xe->type == window->GetXTablet().ProxInEvent) {
XProximityNotifyEvent *data = (XProximityNotifyEvent *)xe;
setTabletMode(window, data->deviceid);
}
- else if (xe->type == window->GetXTablet().ProxOutEvent)
+ else if (xe->type == window->GetXTablet().ProxOutEvent) {
window->GetXTablet().CommonData.Active = GHOST_kTabletModeNone;
+ }
#endif // WITH_X11_XINPUT
break;
}
@@ -1172,7 +1171,7 @@ generateWindowExposeEvents()
*w_start
);
- (*w_start)->validate();
+ (*w_start)->validate();
if (g_event) {
pushEvent(g_event);
@@ -1457,7 +1456,7 @@ void GHOST_SystemX11::getClipboard_xcout(XEvent evt,
/* check size and format of the property */
XGetWindowProperty(m_display, win, m_xclip_out, 0, 0, False,
AnyPropertyType, &pty_type, &pty_format,
- &pty_items, &pty_size, (unsigned char **) &buffer);
+ &pty_items, &pty_size, &buffer);
if (pty_format != 8) {
/* property does not contain text, delete it
@@ -1485,7 +1484,7 @@ void GHOST_SystemX11::getClipboard_xcout(XEvent evt,
* text, we know the size. */
XGetWindowProperty(m_display, win, m_xclip_out, 0, (long) pty_size,
False, AnyPropertyType, &pty_type, &pty_format,
- &pty_items, &pty_size, (unsigned char **) &buffer);
+ &pty_items, &pty_size, &buffer);
/* allocate memory to accommodate data in *txt */
if (*len == 0) {
@@ -1539,12 +1538,12 @@ GHOST_TUns8 *GHOST_SystemX11::getClipboard(bool selection) const
if (sseln == m_clipboard) {
sel_buf = (unsigned char *)malloc(strlen(txt_cut_buffer) + 1);
strcpy((char *)sel_buf, txt_cut_buffer);
- return((GHOST_TUns8 *)sel_buf);
+ return sel_buf;
}
else {
sel_buf = (unsigned char *)malloc(strlen(txt_select_buffer) + 1);
strcpy((char *)sel_buf, txt_select_buffer);
- return((GHOST_TUns8 *)sel_buf);
+ return sel_buf;
}
}
else if (owner == None)
@@ -1595,7 +1594,7 @@ GHOST_TUns8 *GHOST_SystemX11::getClipboard(bool selection) const
else
free(sel_buf);
- return (GHOST_TUns8 *)tmp_data;
+ return tmp_data;
}
return(NULL);
}
@@ -1604,7 +1603,7 @@ void GHOST_SystemX11::putClipboard(GHOST_TInt8 *buffer, bool selection) const
{
Window m_window, owner;
- vector<GHOST_IWindow *> & win_vec = m_windowManager->getWindows();
+ vector<GHOST_IWindow *> & win_vec = m_windowManager->getWindows();
vector<GHOST_IWindow *>::iterator win_it = win_vec.begin();
GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
m_window = window->getXWindow();
diff --git a/intern/ghost/intern/GHOST_SystemX11.h b/intern/ghost/intern/GHOST_SystemX11.h
index 92bffe46357..02c0109085a 100644
--- a/intern/ghost/intern/GHOST_SystemX11.h
+++ b/intern/ghost/intern/GHOST_SystemX11.h
@@ -210,8 +210,8 @@ public:
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
XIM
- getX11_XIM(
- ) {
+ getX11_XIM()
+ {
return m_xim;
}
#endif
@@ -230,12 +230,12 @@ public:
/**
* Puts buffer to system clipboard
- * \param buffer The buffer to copy to the clipboard
+ * \param buffer The buffer to copy to the clipboard
* \param selection Set the selection into the clipboard, X11 only feature
*/
void putClipboard(GHOST_TInt8 *buffer, bool selection) const;
-#if WITH_XDND
+#ifdef WITH_XDND
/**
* Creates a drag'n'drop event and pushes it immediately onto the event queue.
* Called by GHOST_DropTargetX11 class.
diff --git a/intern/ghost/intern/GHOST_TimerManager.cpp b/intern/ghost/intern/GHOST_TimerManager.cpp
index b1186507028..601359984de 100644
--- a/intern/ghost/intern/GHOST_TimerManager.cpp
+++ b/intern/ghost/intern/GHOST_TimerManager.cpp
@@ -104,7 +104,7 @@ GHOST_TUns64 GHOST_TimerManager::nextFireTime()
GHOST_TUns64 smallest = GHOST_kFireTimeNever;
TTimerVector::iterator iter;
- for (iter = m_timers.begin(); iter != m_timers.end(); iter++) {
+ for (iter = m_timers.begin(); iter != m_timers.end(); ++iter) {
GHOST_TUns64 next = (*iter)->getNext();
if (next < smallest)
@@ -119,7 +119,7 @@ bool GHOST_TimerManager::fireTimers(GHOST_TUns64 time)
TTimerVector::iterator iter;
bool anyProcessed = false;
- for (iter = m_timers.begin(); iter != m_timers.end(); iter++) {
+ for (iter = m_timers.begin(); iter != m_timers.end(); ++iter) {
if (fireTimer(time, *iter))
anyProcessed = true;
}
@@ -156,7 +156,7 @@ bool GHOST_TimerManager::fireTimer(GHOST_TUns64 time, GHOST_TimerTask *task)
void GHOST_TimerManager::disposeTimers()
{
- while (m_timers.size() > 0) {
+ while (m_timers.empty() == false) {
delete m_timers[0];
m_timers.erase(m_timers.begin());
}
diff --git a/intern/ghost/intern/GHOST_Window.cpp b/intern/ghost/intern/GHOST_Window.cpp
index eb80a073b44..fd3ff4f85f0 100644
--- a/intern/ghost/intern/GHOST_Window.cpp
+++ b/intern/ghost/intern/GHOST_Window.cpp
@@ -38,6 +38,7 @@
#include "GHOST_Window.h"
+#include <assert.h>
GHOST_Window::GHOST_Window(
GHOST_TUns32 width, GHOST_TUns32 height,
@@ -105,11 +106,18 @@ GHOST_TSuccess GHOST_Window::setCursorVisibility(bool visible)
}
}
-GHOST_TSuccess GHOST_Window::setCursorGrab(GHOST_TGrabCursorMode mode, GHOST_Rect *bounds)
+GHOST_TSuccess GHOST_Window::setCursorGrab(GHOST_TGrabCursorMode mode, GHOST_Rect *bounds, GHOST_TInt32 mouse_ungrab_xy[2])
{
if (m_cursorGrab == mode)
return GHOST_kSuccess;
+ /* override with new location */
+ if (mouse_ungrab_xy) {
+ assert(mode == GHOST_kGrabDisable);
+ m_cursorGrabInitPos[0] = mouse_ungrab_xy[0];
+ m_cursorGrabInitPos[1] = mouse_ungrab_xy[1];
+ }
+
if (setWindowCursorGrab(mode)) {
if (mode == GHOST_kGrabDisable)
diff --git a/intern/ghost/intern/GHOST_Window.h b/intern/ghost/intern/GHOST_Window.h
index 3043b107aa1..fd870327fd4 100644
--- a/intern/ghost/intern/GHOST_Window.h
+++ b/intern/ghost/intern/GHOST_Window.h
@@ -178,7 +178,7 @@ public:
* \param mode The new grab state of the cursor.
* \return Indication of success.
*/
- virtual GHOST_TSuccess setCursorGrab(GHOST_TGrabCursorMode mode, GHOST_Rect *bounds);
+ virtual GHOST_TSuccess setCursorGrab(GHOST_TGrabCursorMode mode, GHOST_Rect *bounds, GHOST_TInt32 mouse_ungrab_xy[2]);
/**
* Gets the cursor grab region, if unset the window is used.
@@ -192,14 +192,14 @@ public:
*/
virtual GHOST_TSuccess setProgressBar(float progress) {
return GHOST_kFailure;
- };
+ }
/**
* Hides the progress bar in the icon
*/
virtual GHOST_TSuccess endProgressBar() {
return GHOST_kFailure;
- };
+ }
/**
* Tells if the ongoing drag'n'drop object can be accepted upon mouse drop
@@ -284,7 +284,7 @@ protected:
*/
virtual GHOST_TSuccess setWindowCursorGrab(GHOST_TGrabCursorMode mode) {
return GHOST_kSuccess;
- };
+ }
/**
* Sets the cursor shape on the window using
diff --git a/intern/ghost/intern/GHOST_WindowCocoa.mm b/intern/ghost/intern/GHOST_WindowCocoa.mm
index 31589003131..23eefe17959 100644
--- a/intern/ghost/intern/GHOST_WindowCocoa.mm
+++ b/intern/ghost/intern/GHOST_WindowCocoa.mm
@@ -187,7 +187,7 @@ extern "C" {
NSPoint mouseLocation = [sender draggingLocation];
systemCocoa->handleDraggingEvent(GHOST_kEventDraggingUpdated, m_draggedObjectType, associatedWindow, mouseLocation.x, mouseLocation.y, nil);
- return associatedWindow->canAcceptDragOperation()?NSDragOperationCopy:NSDragOperationNone;
+ return associatedWindow->canAcceptDragOperation() ? NSDragOperationCopy : NSDragOperationNone;
}
- (void)draggingExited:(id < NSDraggingInfo >)sender
@@ -368,7 +368,7 @@ extern "C" {
- (BOOL)hasMarkedText
{
- return (composing)? YES: NO;
+ return (composing) ? YES : NO;
}
- (void)doCommandBySelector:(SEL)selector
@@ -392,7 +392,7 @@ extern "C" {
- (NSRange)markedRange
{
- unsigned int length = (composing_text)? [composing_text length]: 0;
+ unsigned int length = (composing_text) ? [composing_text length] : 0;
if (composing)
return NSMakeRange(0, length);
@@ -402,7 +402,7 @@ extern "C" {
- (NSRange)selectedRange
{
- unsigned int length = (composing_text)? [composing_text length]: 0;
+ unsigned int length = (composing_text) ? [composing_text length] : 0;
return NSMakeRange(0, length);
}
@@ -637,7 +637,7 @@ void* GHOST_WindowCocoa::getOSWindow() const
void GHOST_WindowCocoa::setTitle(const STR_String& title)
{
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setTitle(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setTitle(): window invalid");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *windowTitle = [[NSString alloc] initWithCString:title encoding:NSUTF8StringEncoding];
@@ -670,7 +670,8 @@ void GHOST_WindowCocoa::setTitle(const STR_String& title)
[m_window setRepresentedFilename:@""];
}
- } else {
+ }
+ else {
[m_window setTitle:windowTitle];
[m_window setRepresentedFilename:@""];
}
@@ -683,7 +684,7 @@ void GHOST_WindowCocoa::setTitle(const STR_String& title)
void GHOST_WindowCocoa::getTitle(STR_String& title) const
{
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getTitle(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getTitle(): window invalid");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@@ -700,7 +701,7 @@ void GHOST_WindowCocoa::getTitle(STR_String& title) const
void GHOST_WindowCocoa::getWindowBounds(GHOST_Rect& bounds) const
{
NSRect rect;
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getWindowBounds(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getWindowBounds(): window invalid");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@@ -720,7 +721,7 @@ void GHOST_WindowCocoa::getWindowBounds(GHOST_Rect& bounds) const
void GHOST_WindowCocoa::getClientBounds(GHOST_Rect& bounds) const
{
NSRect rect;
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getClientBounds(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getClientBounds(): window invalid");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@@ -752,7 +753,7 @@ void GHOST_WindowCocoa::getClientBounds(GHOST_Rect& bounds) const
GHOST_TSuccess GHOST_WindowCocoa::setClientWidth(GHOST_TUns32 width)
{
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientWidth(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientWidth(): window invalid");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
GHOST_Rect cBnds, wBnds;
getClientBounds(cBnds);
@@ -769,7 +770,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setClientWidth(GHOST_TUns32 width)
GHOST_TSuccess GHOST_WindowCocoa::setClientHeight(GHOST_TUns32 height)
{
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientHeight(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientHeight(): window invalid");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
GHOST_Rect cBnds, wBnds;
getClientBounds(cBnds);
@@ -786,7 +787,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setClientHeight(GHOST_TUns32 height)
GHOST_TSuccess GHOST_WindowCocoa::setClientSize(GHOST_TUns32 width, GHOST_TUns32 height)
{
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientSize(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientSize(): window invalid");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
GHOST_Rect cBnds, wBnds;
getClientBounds(cBnds);
@@ -805,7 +806,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setClientSize(GHOST_TUns32 width, GHOST_TUns32
GHOST_TWindowState GHOST_WindowCocoa::getState() const
{
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getState(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getState(): window invalid");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
GHOST_TWindowState state;
if (m_fullScreen) {
@@ -827,7 +828,7 @@ GHOST_TWindowState GHOST_WindowCocoa::getState() const
void GHOST_WindowCocoa::screenToClient(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
{
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::screenToClient(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::screenToClient(): window invalid");
screenToClientIntern(inX, inY, outX, outY);
@@ -840,7 +841,7 @@ void GHOST_WindowCocoa::screenToClient(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST
void GHOST_WindowCocoa::clientToScreen(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
{
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::clientToScreen(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::clientToScreen(): window invalid");
/* switch y to match ghost convention */
GHOST_Rect cBnds;
@@ -894,7 +895,7 @@ NSScreen* GHOST_WindowCocoa::getScreen()
*/
GHOST_TSuccess GHOST_WindowCocoa::setState(GHOST_TWindowState state)
{
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setState(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setState(): window invalid");
switch (state) {
case GHOST_kWindowStateMinimized:
[m_window miniaturize:nil];
@@ -1048,7 +1049,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setOrder(GHOST_TWindowOrder order)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setOrder(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setOrder(): window invalid");
if (order == GHOST_kWindowOrderTop) {
[m_window makeKeyAndOrderFront:nil];
}
@@ -1198,7 +1199,7 @@ GHOST_TSuccess GHOST_WindowCocoa::removeDrawingContext()
GHOST_TSuccess GHOST_WindowCocoa::invalidate()
{
- GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::invalidate(): window invalid")
+ GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::invalidate(): window invalid");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[m_openGLView setNeedsDisplay:YES];
[pool drain];
@@ -1288,7 +1289,8 @@ void GHOST_WindowCocoa::loadCursor(bool visible, GHOST_TStandardCursor cursor) c
if (cursor == GHOST_kStandardCursorCustom && m_customCursor) {
tmpCursor = m_customCursor;
- } else {
+ }
+ else {
switch (cursor) {
case GHOST_kStandardCursorDestroy:
tmpCursor = [NSCursor disappearingItemCursor];
diff --git a/intern/ghost/intern/GHOST_WindowManager.cpp b/intern/ghost/intern/GHOST_WindowManager.cpp
index 1816c57a150..daf1c2f2d22 100644
--- a/intern/ghost/intern/GHOST_WindowManager.cpp
+++ b/intern/ghost/intern/GHOST_WindowManager.cpp
@@ -195,7 +195,7 @@ GHOST_IWindow *GHOST_WindowManager::getWindowAssociatedWithOSWindow(void *osWind
{
std::vector<GHOST_IWindow *>::iterator iter;
- for (iter = m_windows.begin(); iter != m_windows.end(); iter++) {
+ for (iter = m_windows.begin(); iter != m_windows.end(); ++iter) {
if ((*iter)->getOSWindow() == osWindow)
return *iter;
}
@@ -208,7 +208,7 @@ bool GHOST_WindowManager::getAnyModifiedState()
bool isAnyModified = false;
std::vector<GHOST_IWindow *>::iterator iter;
- for (iter = m_windows.begin(); iter != m_windows.end(); iter++) {
+ for (iter = m_windows.begin(); iter != m_windows.end(); ++iter) {
if ((*iter)->getModifiedState())
isAnyModified = true;
}
diff --git a/intern/ghost/intern/GHOST_WindowWin32.cpp b/intern/ghost/intern/GHOST_WindowWin32.cpp
index c9c902fca8b..dded7dc256d 100644
--- a/intern/ghost/intern/GHOST_WindowWin32.cpp
+++ b/intern/ghost/intern/GHOST_WindowWin32.cpp
@@ -720,7 +720,7 @@ GHOST_TSuccess GHOST_WindowWin32::initMultisample(PIXELFORMATDESCRIPTOR pfd)
};
// Get the function
- PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
+ PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
if (!wglChoosePixelFormatARB)
{
diff --git a/intern/ghost/intern/GHOST_WindowX11.cpp b/intern/ghost/intern/GHOST_WindowX11.cpp
index 4ad95fcab53..dd1930a241b 100644
--- a/intern/ghost/intern/GHOST_WindowX11.cpp
+++ b/intern/ghost/intern/GHOST_WindowX11.cpp
@@ -76,7 +76,7 @@ typedef struct {
*/
#define _NET_WM_STATE_REMOVE 0
#define _NET_WM_STATE_ADD 1
-#define _NET_WM_STATE_TOGGLE 2
+// #define _NET_WM_STATE_TOGGLE 2 // UNUSED
/*
import bpy
@@ -1326,7 +1326,7 @@ GHOST_WindowX11::
c_owner = XGetSelectionOwner(m_display, Clipboard_atom);
std::map<unsigned int, Cursor>::iterator it = m_standard_cursors.begin();
- for (; it != m_standard_cursors.end(); it++) {
+ for (; it != m_standard_cursors.end(); ++it) {
XFreeCursor(m_display, it->second);
}
diff --git a/intern/ghost/test/multitest/EventToBuf.c b/intern/ghost/test/multitest/EventToBuf.c
index 0eb37a58be2..49255de5e64 100644
--- a/intern/ghost/test/multitest/EventToBuf.c
+++ b/intern/ghost/test/multitest/EventToBuf.c
@@ -197,31 +197,32 @@ static char *keytype_to_string(GHOST_TKey key)
void event_to_buf(GHOST_EventHandle evt, char buf[128])
{
- GHOST_TEventType type= GHOST_GetEventType(evt);
- double time= (double) ((GHOST_TInt64) GHOST_GetEventTime(evt))/1000;
- GHOST_WindowHandle win= GHOST_GetEventWindow(evt);
- void *data= GHOST_GetEventData(evt);
- char *pos= buf;
+ GHOST_TEventType type = GHOST_GetEventType(evt);
+ double time = (double) ((GHOST_TInt64) GHOST_GetEventTime(evt))/1000;
+ GHOST_WindowHandle win = GHOST_GetEventWindow(evt);
+ void *data = GHOST_GetEventData(evt);
+ char *pos = buf;
pos += sprintf(pos, "event: %6.2f, %16s", time, eventtype_to_string(type));
if (win) {
- char *s= GHOST_GetTitle(win);
+ char *s = GHOST_GetTitle(win);
pos += sprintf(pos, " - win: %s", s);
free(s);
- } else {
+ }
+ else {
pos+= sprintf(pos, " - sys evt");
}
switch (type) {
case GHOST_kEventCursorMove:
{
- GHOST_TEventCursorData *cd= data;
+ GHOST_TEventCursorData *cd = data;
pos += sprintf(pos, " - pos: (%d, %d)", cd->x, cd->y);
break;
}
case GHOST_kEventButtonDown:
case GHOST_kEventButtonUp:
{
- GHOST_TEventButtonData *bd= data;
+ GHOST_TEventButtonData *bd = data;
pos += sprintf(pos, " - but: %d", bd->button);
break;
}
@@ -229,7 +230,7 @@ void event_to_buf(GHOST_EventHandle evt, char buf[128])
case GHOST_kEventKeyDown:
case GHOST_kEventKeyUp:
{
- GHOST_TEventKeyData *kd= data;
+ GHOST_TEventKeyData *kd = data;
pos += sprintf(pos, " - key: %s (%d)", keytype_to_string(kd->key), kd->key);
if (kd->ascii) pos+= sprintf(pos, " ascii: '%c' (%d)", kd->ascii, kd->ascii);
break;
diff --git a/intern/ghost/test/multitest/MultiTest.c b/intern/ghost/test/multitest/MultiTest.c
index 5d207dafaaf..2d0afcf671c 100644
--- a/intern/ghost/test/multitest/MultiTest.c
+++ b/intern/ghost/test/multitest/MultiTest.c
@@ -26,9 +26,8 @@
*/
#define FALSE 0
-#ifdef WIN32
-
-#pragma warning(disable: 4244 4305)
+#ifdef _MSC_VER
+# pragma warning(disable: 4244 4305)
#endif
#include <stdlib.h>
diff --git a/intern/guardedalloc/test/simpletest/memtest.c b/intern/guardedalloc/test/simpletest/memtest.c
index 7c6a0a2d546..749e2500dd1 100644
--- a/intern/guardedalloc/test/simpletest/memtest.c
+++ b/intern/guardedalloc/test/simpletest/memtest.c
@@ -94,7 +94,8 @@ int main (int argc, char *argv[])
if (verbose) {
if (error_status) {
fprintf(stderr, "|--* Memory test FAILED\n|\n");
- } else {
+ }
+ else {
fprintf(stderr, "|--* Memory tested as good (as it should be)\n|\n");
}
}
@@ -130,7 +131,8 @@ int main (int argc, char *argv[])
if (verbose) {
if (retval) {
fprintf(stderr, "|--* Memory test failed (as it should be)\n");
- } else {
+ }
+ else {
fprintf(stderr, "|--* Memory test FAILED to find corrupted blocks \n");
}
}
@@ -147,7 +149,8 @@ int main (int argc, char *argv[])
if (verbose) {
if (error_status) {
fprintf(stderr,"|\n|--* Errors were detected\n");
- } else {
+ }
+ else {
fprintf(stderr,"|\n|--* Test exited succesfully\n");
}
diff --git a/intern/iksolver/intern/IK_QJacobianSolver.h b/intern/iksolver/intern/IK_QJacobianSolver.h
index ead2b150b40..646f952b9ff 100644
--- a/intern/iksolver/intern/IK_QJacobianSolver.h
+++ b/intern/iksolver/intern/IK_QJacobianSolver.h
@@ -53,12 +53,12 @@ class IK_QJacobianSolver
{
public:
IK_QJacobianSolver();
- ~IK_QJacobianSolver() {};
+ ~IK_QJacobianSolver() {}
// setup pole vector constraint
void SetPoleVectorConstraint(IK_QSegment *tip, MT_Vector3& goal,
MT_Vector3& polegoal, float poleangle, bool getangle);
- float GetPoleAngle() { return m_poleangle; };
+ float GetPoleAngle() { return m_poleangle; }
// call setup once before solving, if it fails don't solve
bool Setup(IK_QSegment *root, std::list<IK_QTask*>& tasks);
diff --git a/intern/iksolver/intern/IK_QSegment.h b/intern/iksolver/intern/IK_QSegment.h
index 25a8fbc0804..b40bf3739ff 100644
--- a/intern/iksolver/intern/IK_QSegment.h
+++ b/intern/iksolver/intern/IK_QSegment.h
@@ -158,10 +158,10 @@ public:
virtual void UpdateAngleApply()=0;
// set joint limits
- virtual void SetLimit(int, MT_Scalar, MT_Scalar) {};
+ virtual void SetLimit(int, MT_Scalar, MT_Scalar) {}
// set joint weights (per axis)
- virtual void SetWeight(int, MT_Scalar) {};
+ virtual void SetWeight(int, MT_Scalar) {}
virtual void SetBasis(const MT_Matrix3x3& basis) { m_basis = basis; }
diff --git a/intern/iksolver/intern/IK_QTask.h b/intern/iksolver/intern/IK_QTask.h
index 45b1e59e606..baf1c346d62 100644
--- a/intern/iksolver/intern/IK_QTask.h
+++ b/intern/iksolver/intern/IK_QTask.h
@@ -49,7 +49,7 @@ public:
bool active,
const IK_QSegment *segment
);
- virtual ~IK_QTask() {};
+ virtual ~IK_QTask() {}
int Id() const
{ return m_size; }
@@ -119,7 +119,7 @@ public:
const MT_Matrix3x3& goal
);
- MT_Scalar Distance() const { return m_distance; };
+ MT_Scalar Distance() const { return m_distance; }
void ComputeJacobian(IK_QJacobian& jacobian);
private:
diff --git a/intern/iksolver/intern/IK_Solver.cpp b/intern/iksolver/intern/IK_Solver.cpp
index 6c2e30932bb..c1a4ffcb1e8 100644
--- a/intern/iksolver/intern/IK_Solver.cpp
+++ b/intern/iksolver/intern/IK_Solver.cpp
@@ -43,7 +43,7 @@ using namespace std;
class IK_QSolver {
public:
IK_QSolver() : root(NULL) {
- };
+ }
IK_QJacobianSolver solver;
IK_QSegment *root;
@@ -51,7 +51,7 @@ public:
};
// FIXME: locks still result in small "residual" changes to the locked axes...
-IK_QSegment *CreateSegment(int flag, bool translate)
+static IK_QSegment *CreateSegment(int flag, bool translate)
{
int ndof = 0;
ndof += (flag & IK_XDOF) ? 1 : 0;
@@ -348,7 +348,7 @@ float IK_SolverGetPoleAngle(IK_Solver *solver)
return qsolver->solver.GetPoleAngle();
}
-void IK_SolverAddCenterOfMass(IK_Solver *solver, IK_Segment *root, float goal[3], float weight)
+static void IK_SolverAddCenterOfMass(IK_Solver *solver, IK_Segment *root, float goal[3], float weight)
{
if (solver == NULL || root == NULL)
return;
diff --git a/intern/iksolver/intern/MT_ExpMap.h b/intern/iksolver/intern/MT_ExpMap.h
index 9485428dc9f..65bbe4d4ad5 100644
--- a/intern/iksolver/intern/MT_ExpMap.h
+++ b/intern/iksolver/intern/MT_ExpMap.h
@@ -103,7 +103,7 @@ public:
const MT_Quaternion &q
) {
setRotation(q);
- };
+ }
/**
* Accessors
@@ -118,7 +118,7 @@ public:
vector(
) const {
return m_v;
- };
+ }
/**
* Set the exponential map from a quaternion
diff --git a/intern/iksolver/intern/TNT/cmat.h b/intern/iksolver/intern/TNT/cmat.h
index 146afdc79d7..fd3a1851262 100644
--- a/intern/iksolver/intern/TNT/cmat.h
+++ b/intern/iksolver/intern/TNT/cmat.h
@@ -182,7 +182,7 @@ class Matrix
// constructors
- Matrix() : m_(0), n_(0), mn_(0), v_(0), row_(0), vm1_(0), rowm1_(0) {};
+ Matrix() : m_(0), n_(0), mn_(0), v_(0), row_(0), vm1_(0), rowm1_(0) {}
Matrix(const Matrix<T> &A)
{
diff --git a/intern/iksolver/intern/TNT/vec.h b/intern/iksolver/intern/TNT/vec.h
index ff1b5c0ea0e..5d4ef14bf73 100644
--- a/intern/iksolver/intern/TNT/vec.h
+++ b/intern/iksolver/intern/TNT/vec.h
@@ -164,7 +164,7 @@ class Vector
// constructors
- Vector() : v_(0), vm1_(0), n_(0) {};
+ Vector() : v_(0), vm1_(0), n_(0) {}
Vector(const Vector<T> &A) : v_(0), vm1_(0), n_(0)
{
diff --git a/intern/itasc/CMakeLists.txt b/intern/itasc/CMakeLists.txt
index f4bc0326ea1..99c64d956cb 100644
--- a/intern/itasc/CMakeLists.txt
+++ b/intern/itasc/CMakeLists.txt
@@ -24,11 +24,11 @@
# ***** END GPL LICENSE BLOCK *****
set(INC
- ../../extern/Eigen3
+
)
set(INC_SYS
-
+ ../../extern/Eigen3
)
set(SRC
@@ -121,201 +121,235 @@ set(SRC
kdl/framevel.inl
# until we have another user...
- ../../extern/Eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h
- ../../extern/Eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h
- ../../extern/Eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h
- ../../extern/Eigen3/Eigen/src/plugins/BlockMethods.h
- ../../extern/Eigen3/Eigen/src/plugins/ArrayCwiseUnaryOps.h
- ../../extern/Eigen3/Eigen/src/plugins/ArrayCwiseBinaryOps.h
- ../../extern/Eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h
- ../../extern/Eigen3/Eigen/src/misc/Kernel.h
- ../../extern/Eigen3/Eigen/src/misc/Image.h
- ../../extern/Eigen3/Eigen/src/misc/Solve.h
- ../../extern/Eigen3/Eigen/src/QR/HouseholderQR.h
- ../../extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR.h
- ../../extern/Eigen3/Eigen/src/QR/FullPivHouseholderQR.h
- ../../extern/Eigen3/Eigen/src/StlSupport/details.h
- ../../extern/Eigen3/Eigen/src/StlSupport/StdList.h
- ../../extern/Eigen3/Eigen/src/StlSupport/StdDeque.h
- ../../extern/Eigen3/Eigen/src/StlSupport/StdVector.h
- ../../extern/Eigen3/Eigen/src/SVD/UpperBidiagonalization.h
- ../../extern/Eigen3/Eigen/src/SVD/JacobiSVD.h
- ../../extern/Eigen3/Eigen/src/Eigenvalues/ComplexEigenSolver.h
- ../../extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur.h
- ../../extern/Eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h
- ../../extern/Eigen3/Eigen/src/Eigenvalues/Tridiagonalization.h
- ../../extern/Eigen3/Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h
- ../../extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver.h
- ../../extern/Eigen3/Eigen/src/Eigenvalues/RealSchur.h
- ../../extern/Eigen3/Eigen/src/Eigenvalues/EigenvaluesCommon.h
- ../../extern/Eigen3/Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h
- ../../extern/Eigen3/Eigen/src/Eigenvalues/EigenSolver.h
- ../../extern/Eigen3/Eigen/src/Jacobi/Jacobi.h
- ../../extern/Eigen3/Eigen/src/Householder/Householder.h
- ../../extern/Eigen3/Eigen/src/Householder/BlockHouseholder.h
- ../../extern/Eigen3/Eigen/src/Householder/HouseholderSequence.h
- ../../extern/Eigen3/Eigen/src/Geometry/RotationBase.h
- ../../extern/Eigen3/Eigen/src/Geometry/Rotation2D.h
- ../../extern/Eigen3/Eigen/src/Geometry/Homogeneous.h
- ../../extern/Eigen3/Eigen/src/Geometry/Hyperplane.h
- ../../extern/Eigen3/Eigen/src/Geometry/EulerAngles.h
- ../../extern/Eigen3/Eigen/src/Geometry/arch/Geometry_SSE.h
- ../../extern/Eigen3/Eigen/src/Geometry/ParametrizedLine.h
- ../../extern/Eigen3/Eigen/src/Geometry/OrthoMethods.h
- ../../extern/Eigen3/Eigen/src/Geometry/AngleAxis.h
- ../../extern/Eigen3/Eigen/src/Geometry/Umeyama.h
- ../../extern/Eigen3/Eigen/src/Geometry/Scaling.h
- ../../extern/Eigen3/Eigen/src/Geometry/Translation.h
- ../../extern/Eigen3/Eigen/src/Geometry/AlignedBox.h
- ../../extern/Eigen3/Eigen/src/Geometry/Transform.h
- ../../extern/Eigen3/Eigen/src/Geometry/Quaternion.h
- ../../extern/Eigen3/Eigen/src/LU/PartialPivLU.h
- ../../extern/Eigen3/Eigen/src/LU/Determinant.h
- ../../extern/Eigen3/Eigen/src/LU/arch/Inverse_SSE.h
- ../../extern/Eigen3/Eigen/src/LU/FullPivLU.h
- ../../extern/Eigen3/Eigen/src/LU/Inverse.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseMatrixBase.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseSelfAdjointView.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseVector.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseDiagonalProduct.h
- ../../extern/Eigen3/Eigen/src/Sparse/TriangularSolver.h
- ../../extern/Eigen3/Eigen/src/Sparse/AmbiVector.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseDenseProduct.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseBlock.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseTriangularView.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseCwiseBinaryOp.h
- ../../extern/Eigen3/Eigen/src/Sparse/CoreIterators.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseMatrix.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseAssign.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseSparseProduct.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseDot.h
- ../../extern/Eigen3/Eigen/src/Sparse/DynamicSparseMatrix.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseRedux.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseFuzzy.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseCwiseUnaryOp.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseView.h
- ../../extern/Eigen3/Eigen/src/Sparse/MappedSparseMatrix.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseUtil.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseTranspose.h
- ../../extern/Eigen3/Eigen/src/Sparse/SparseProduct.h
- ../../extern/Eigen3/Eigen/src/Sparse/CompressedStorage.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Cwise.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/TriangularSolver.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/QR.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Lazy.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Memory.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/SVD.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/CwiseOperators.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/VectorBlock.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Meta.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Macros.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/LeastSquares.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/LU.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Block.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/RotationBase.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Rotation2D.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Hyperplane.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/ParametrizedLine.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AngleAxis.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Scaling.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/All.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Translation.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AlignedBox.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Transform.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Quaternion.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/Minor.h
- ../../extern/Eigen3/Eigen/src/Eigen2Support/MathFunctions.h
- ../../extern/Eigen3/Eigen/src/Core/SelfAdjointView.h
- ../../extern/Eigen3/Eigen/src/Core/MatrixBase.h
- ../../extern/Eigen3/Eigen/src/Core/Swap.h
- ../../extern/Eigen3/Eigen/src/Core/DenseCoeffsBase.h
- ../../extern/Eigen3/Eigen/src/Core/DenseBase.h
- ../../extern/Eigen3/Eigen/src/Core/GlobalFunctions.h
- ../../extern/Eigen3/Eigen/src/Core/ProductBase.h
- ../../extern/Eigen3/Eigen/src/Core/CwiseBinaryOp.h
- ../../extern/Eigen3/Eigen/src/Core/Stride.h
- ../../extern/Eigen3/Eigen/src/Core/Matrix.h
- ../../extern/Eigen3/Eigen/src/Core/Visitor.h
+ ../../extern/Eigen3/Eigen/src/Cholesky/LDLT.h
+ ../../extern/Eigen3/Eigen/src/Cholesky/LLT.h
+ ../../extern/Eigen3/Eigen/src/Cholesky/LLT_MKL.h
+ ../../extern/Eigen3/Eigen/src/CholmodSupport/CholmodSupport.h
../../extern/Eigen3/Eigen/src/Core/Array.h
- ../../extern/Eigen3/Eigen/src/Core/ReturnByValue.h
- ../../extern/Eigen3/Eigen/src/Core/SelfCwiseBinaryOp.h
- ../../extern/Eigen3/Eigen/src/Core/EigenBase.h
- ../../extern/Eigen3/Eigen/src/Core/Random.h
- ../../extern/Eigen3/Eigen/src/Core/Redux.h
- ../../extern/Eigen3/Eigen/src/Core/arch/Default/Settings.h
- ../../extern/Eigen3/Eigen/src/Core/arch/AltiVec/PacketMath.h
- ../../extern/Eigen3/Eigen/src/Core/arch/AltiVec/Complex.h
- ../../extern/Eigen3/Eigen/src/Core/arch/NEON/PacketMath.h
- ../../extern/Eigen3/Eigen/src/Core/arch/NEON/Complex.h
- ../../extern/Eigen3/Eigen/src/Core/arch/SSE/PacketMath.h
- ../../extern/Eigen3/Eigen/src/Core/arch/SSE/Complex.h
- ../../extern/Eigen3/Eigen/src/Core/arch/SSE/MathFunctions.h
- ../../extern/Eigen3/Eigen/src/Core/BooleanRedux.h
- ../../extern/Eigen3/Eigen/src/Core/util/ReenableStupidWarnings.h
- ../../extern/Eigen3/Eigen/src/Core/util/BlasUtil.h
- ../../extern/Eigen3/Eigen/src/Core/util/Memory.h
- ../../extern/Eigen3/Eigen/src/Core/util/Meta.h
- ../../extern/Eigen3/Eigen/src/Core/util/Constants.h
- ../../extern/Eigen3/Eigen/src/Core/util/Macros.h
- ../../extern/Eigen3/Eigen/src/Core/util/ForwardDeclarations.h
- ../../extern/Eigen3/Eigen/src/Core/util/StaticAssert.h
- ../../extern/Eigen3/Eigen/src/Core/util/DisableStupidWarnings.h
- ../../extern/Eigen3/Eigen/src/Core/util/XprHelper.h
- ../../extern/Eigen3/Eigen/src/Core/VectorBlock.h
- ../../extern/Eigen3/Eigen/src/Core/Transpositions.h
- ../../extern/Eigen3/Eigen/src/Core/Select.h
+ ../../extern/Eigen3/Eigen/src/Core/ArrayBase.h
+ ../../extern/Eigen3/Eigen/src/Core/ArrayWrapper.h
+ ../../extern/Eigen3/Eigen/src/Core/Assign.h
+ ../../extern/Eigen3/Eigen/src/Core/Assign_MKL.h
../../extern/Eigen3/Eigen/src/Core/BandMatrix.h
+ ../../extern/Eigen3/Eigen/src/Core/Block.h
+ ../../extern/Eigen3/Eigen/src/Core/BooleanRedux.h
+ ../../extern/Eigen3/Eigen/src/Core/CommaInitializer.h
+ ../../extern/Eigen3/Eigen/src/Core/CwiseBinaryOp.h
+ ../../extern/Eigen3/Eigen/src/Core/CwiseNullaryOp.h
+ ../../extern/Eigen3/Eigen/src/Core/CwiseUnaryOp.h
../../extern/Eigen3/Eigen/src/Core/CwiseUnaryView.h
+ ../../extern/Eigen3/Eigen/src/Core/DenseBase.h
+ ../../extern/Eigen3/Eigen/src/Core/DenseCoeffsBase.h
+ ../../extern/Eigen3/Eigen/src/Core/DenseStorage.h
+ ../../extern/Eigen3/Eigen/src/Core/Diagonal.h
+ ../../extern/Eigen3/Eigen/src/Core/DiagonalMatrix.h
+ ../../extern/Eigen3/Eigen/src/Core/DiagonalProduct.h
../../extern/Eigen3/Eigen/src/Core/Dot.h
+ ../../extern/Eigen3/Eigen/src/Core/EigenBase.h
+ ../../extern/Eigen3/Eigen/src/Core/Flagged.h
+ ../../extern/Eigen3/Eigen/src/Core/ForceAlignedAccess.h
+ ../../extern/Eigen3/Eigen/src/Core/Functors.h
+ ../../extern/Eigen3/Eigen/src/Core/Fuzzy.h
+ ../../extern/Eigen3/Eigen/src/Core/GeneralProduct.h
../../extern/Eigen3/Eigen/src/Core/GenericPacketMath.h
- ../../extern/Eigen3/Eigen/src/Core/Product.h
- ../../extern/Eigen3/Eigen/src/Core/Transpose.h
- ../../extern/Eigen3/Eigen/src/Core/Block.h
- ../../extern/Eigen3/Eigen/src/Core/ArrayWrapper.h
+ ../../extern/Eigen3/Eigen/src/Core/GlobalFunctions.h
+ ../../extern/Eigen3/Eigen/src/Core/IO.h
+ ../../extern/Eigen3/Eigen/src/Core/Map.h
../../extern/Eigen3/Eigen/src/Core/MapBase.h
+ ../../extern/Eigen3/Eigen/src/Core/MathFunctions.h
+ ../../extern/Eigen3/Eigen/src/Core/Matrix.h
+ ../../extern/Eigen3/Eigen/src/Core/MatrixBase.h
+ ../../extern/Eigen3/Eigen/src/Core/NestByValue.h
../../extern/Eigen3/Eigen/src/Core/NoAlias.h
- ../../extern/Eigen3/Eigen/src/Core/ForceAlignedAccess.h
- ../../extern/Eigen3/Eigen/src/Core/PlainObjectBase.h
- ../../extern/Eigen3/Eigen/src/Core/IO.h
- ../../extern/Eigen3/Eigen/src/Core/DiagonalMatrix.h
- ../../extern/Eigen3/Eigen/src/Core/CwiseUnaryOp.h
- ../../extern/Eigen3/Eigen/src/Core/Reverse.h
- ../../extern/Eigen3/Eigen/src/Core/Fuzzy.h
- ../../extern/Eigen3/Eigen/src/Core/DenseStorage.h
- ../../extern/Eigen3/Eigen/src/Core/StableNorm.h
../../extern/Eigen3/Eigen/src/Core/NumTraits.h
- ../../extern/Eigen3/Eigen/src/Core/Map.h
- ../../extern/Eigen3/Eigen/src/Core/Functors.h
../../extern/Eigen3/Eigen/src/Core/PermutationMatrix.h
- ../../extern/Eigen3/Eigen/src/Core/ArrayBase.h
- ../../extern/Eigen3/Eigen/src/Core/CwiseNullaryOp.h
- ../../extern/Eigen3/Eigen/src/Core/SolveTriangular.h
- ../../extern/Eigen3/Eigen/src/Core/NestByValue.h
- ../../extern/Eigen3/Eigen/src/Core/DiagonalProduct.h
- ../../extern/Eigen3/Eigen/src/Core/CommaInitializer.h
- ../../extern/Eigen3/Eigen/src/Core/MathFunctions.h
- ../../extern/Eigen3/Eigen/src/Core/Diagonal.h
+ ../../extern/Eigen3/Eigen/src/Core/PlainObjectBase.h
+ ../../extern/Eigen3/Eigen/src/Core/Product.h
+ ../../extern/Eigen3/Eigen/src/Core/ProductBase.h
+ ../../extern/Eigen3/Eigen/src/Core/Random.h
+ ../../extern/Eigen3/Eigen/src/Core/Redux.h
../../extern/Eigen3/Eigen/src/Core/Replicate.h
- ../../extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix.h
- ../../extern/Eigen3/Eigen/src/Core/products/SelfadjointProduct.h
- ../../extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector.h
+ ../../extern/Eigen3/Eigen/src/Core/ReturnByValue.h
+ ../../extern/Eigen3/Eigen/src/Core/Reverse.h
+ ../../extern/Eigen3/Eigen/src/Core/Select.h
+ ../../extern/Eigen3/Eigen/src/Core/SelfAdjointView.h
+ ../../extern/Eigen3/Eigen/src/Core/SelfCwiseBinaryOp.h
+ ../../extern/Eigen3/Eigen/src/Core/SolveTriangular.h
+ ../../extern/Eigen3/Eigen/src/Core/StableNorm.h
+ ../../extern/Eigen3/Eigen/src/Core/Stride.h
+ ../../extern/Eigen3/Eigen/src/Core/Swap.h
+ ../../extern/Eigen3/Eigen/src/Core/Transpose.h
+ ../../extern/Eigen3/Eigen/src/Core/Transpositions.h
+ ../../extern/Eigen3/Eigen/src/Core/TriangularMatrix.h
+ ../../extern/Eigen3/Eigen/src/Core/VectorBlock.h
+ ../../extern/Eigen3/Eigen/src/Core/VectorwiseOp.h
+ ../../extern/Eigen3/Eigen/src/Core/Visitor.h
+ ../../extern/Eigen3/Eigen/src/Core/arch/AltiVec/Complex.h
+ ../../extern/Eigen3/Eigen/src/Core/arch/AltiVec/PacketMath.h
+ ../../extern/Eigen3/Eigen/src/Core/arch/Default/Settings.h
+ ../../extern/Eigen3/Eigen/src/Core/arch/NEON/Complex.h
+ ../../extern/Eigen3/Eigen/src/Core/arch/NEON/PacketMath.h
+ ../../extern/Eigen3/Eigen/src/Core/arch/SSE/Complex.h
+ ../../extern/Eigen3/Eigen/src/Core/arch/SSE/MathFunctions.h
+ ../../extern/Eigen3/Eigen/src/Core/arch/SSE/PacketMath.h
../../extern/Eigen3/Eigen/src/Core/products/CoeffBasedProduct.h
- ../../extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector.h
- ../../extern/Eigen3/Eigen/src/Core/products/SelfadjointRank2Update.h
- ../../extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular.h
+ ../../extern/Eigen3/Eigen/src/Core/products/GeneralBlockPanelKernel.h
../../extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrix.h
- ../../extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix.h
+ ../../extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular.h
+ ../../extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular_MKL.h
+ ../../extern/Eigen3/Eigen/src/Core/products/GeneralMatrixMatrix_MKL.h
+ ../../extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector.h
+ ../../extern/Eigen3/Eigen/src/Core/products/GeneralMatrixVector_MKL.h
../../extern/Eigen3/Eigen/src/Core/products/Parallelizer.h
+ ../../extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix.h
+ ../../extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix_MKL.h
+ ../../extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector.h
+ ../../extern/Eigen3/Eigen/src/Core/products/SelfadjointMatrixVector_MKL.h
+ ../../extern/Eigen3/Eigen/src/Core/products/SelfadjointProduct.h
+ ../../extern/Eigen3/Eigen/src/Core/products/SelfadjointRank2Update.h
+ ../../extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix.h
+ ../../extern/Eigen3/Eigen/src/Core/products/TriangularMatrixMatrix_MKL.h
+ ../../extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector.h
+ ../../extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector_MKL.h
../../extern/Eigen3/Eigen/src/Core/products/TriangularSolverMatrix.h
+ ../../extern/Eigen3/Eigen/src/Core/products/TriangularSolverMatrix_MKL.h
../../extern/Eigen3/Eigen/src/Core/products/TriangularSolverVector.h
- ../../extern/Eigen3/Eigen/src/Core/products/TriangularMatrixVector.h
- ../../extern/Eigen3/Eigen/src/Core/products/GeneralBlockPanelKernel.h
- ../../extern/Eigen3/Eigen/src/Core/TriangularMatrix.h
- ../../extern/Eigen3/Eigen/src/Core/VectorwiseOp.h
- ../../extern/Eigen3/Eigen/src/Core/Assign.h
- ../../extern/Eigen3/Eigen/src/Core/Flagged.h
- ../../extern/Eigen3/Eigen/src/Cholesky/LDLT.h
- ../../extern/Eigen3/Eigen/src/Cholesky/LLT.h
+ ../../extern/Eigen3/Eigen/src/Core/util/BlasUtil.h
+ ../../extern/Eigen3/Eigen/src/Core/util/Constants.h
+ ../../extern/Eigen3/Eigen/src/Core/util/DisableStupidWarnings.h
+ ../../extern/Eigen3/Eigen/src/Core/util/ForwardDeclarations.h
+ ../../extern/Eigen3/Eigen/src/Core/util/Macros.h
+ ../../extern/Eigen3/Eigen/src/Core/util/Memory.h
+ ../../extern/Eigen3/Eigen/src/Core/util/Meta.h
+ ../../extern/Eigen3/Eigen/src/Core/util/MKL_support.h
+ ../../extern/Eigen3/Eigen/src/Core/util/NonMPL2.h
+ ../../extern/Eigen3/Eigen/src/Core/util/ReenableStupidWarnings.h
+ ../../extern/Eigen3/Eigen/src/Core/util/StaticAssert.h
+ ../../extern/Eigen3/Eigen/src/Core/util/XprHelper.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Block.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Cwise.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/CwiseOperators.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Lazy.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/LeastSquares.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/LU.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Macros.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/MathFunctions.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Memory.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Meta.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Minor.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/QR.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/SVD.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/TriangularSolver.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/VectorBlock.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AlignedBox.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/All.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/AngleAxis.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Hyperplane.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/ParametrizedLine.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Quaternion.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Rotation2D.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/RotationBase.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Scaling.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Transform.h
+ ../../extern/Eigen3/Eigen/src/Eigen2Support/Geometry/Translation.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/ComplexEigenSolver.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/ComplexSchur_MKL.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/EigenSolver.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/RealSchur.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/RealSchur_MKL.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver_MKL.h
+ ../../extern/Eigen3/Eigen/src/Eigenvalues/Tridiagonalization.h
+ ../../extern/Eigen3/Eigen/src/Geometry/AlignedBox.h
+ ../../extern/Eigen3/Eigen/src/Geometry/AngleAxis.h
+ ../../extern/Eigen3/Eigen/src/Geometry/EulerAngles.h
+ ../../extern/Eigen3/Eigen/src/Geometry/Homogeneous.h
+ ../../extern/Eigen3/Eigen/src/Geometry/Hyperplane.h
+ ../../extern/Eigen3/Eigen/src/Geometry/OrthoMethods.h
+ ../../extern/Eigen3/Eigen/src/Geometry/ParametrizedLine.h
+ ../../extern/Eigen3/Eigen/src/Geometry/Quaternion.h
+ ../../extern/Eigen3/Eigen/src/Geometry/Rotation2D.h
+ ../../extern/Eigen3/Eigen/src/Geometry/RotationBase.h
+ ../../extern/Eigen3/Eigen/src/Geometry/Scaling.h
+ ../../extern/Eigen3/Eigen/src/Geometry/Transform.h
+ ../../extern/Eigen3/Eigen/src/Geometry/Translation.h
+ ../../extern/Eigen3/Eigen/src/Geometry/Umeyama.h
+ ../../extern/Eigen3/Eigen/src/Geometry/arch/Geometry_SSE.h
+ ../../extern/Eigen3/Eigen/src/Householder/BlockHouseholder.h
+ ../../extern/Eigen3/Eigen/src/Householder/Householder.h
+ ../../extern/Eigen3/Eigen/src/Householder/HouseholderSequence.h
+ ../../extern/Eigen3/Eigen/src/IterativeLinearSolvers/BasicPreconditioners.h
+ ../../extern/Eigen3/Eigen/src/IterativeLinearSolvers/BiCGSTAB.h
+ ../../extern/Eigen3/Eigen/src/IterativeLinearSolvers/ConjugateGradient.h
+ ../../extern/Eigen3/Eigen/src/IterativeLinearSolvers/IncompleteLUT.h
+ ../../extern/Eigen3/Eigen/src/IterativeLinearSolvers/IterativeSolverBase.h
+ ../../extern/Eigen3/Eigen/src/Jacobi/Jacobi.h
+ ../../extern/Eigen3/Eigen/src/LU/Determinant.h
+ ../../extern/Eigen3/Eigen/src/LU/FullPivLU.h
+ ../../extern/Eigen3/Eigen/src/LU/Inverse.h
+ ../../extern/Eigen3/Eigen/src/LU/PartialPivLU.h
+ ../../extern/Eigen3/Eigen/src/LU/PartialPivLU_MKL.h
+ ../../extern/Eigen3/Eigen/src/LU/arch/Inverse_SSE.h
+ ../../extern/Eigen3/Eigen/src/misc/blas.h
+ ../../extern/Eigen3/Eigen/src/misc/Image.h
+ ../../extern/Eigen3/Eigen/src/misc/Kernel.h
+ ../../extern/Eigen3/Eigen/src/misc/Solve.h
+ ../../extern/Eigen3/Eigen/src/misc/SparseSolve.h
+ ../../extern/Eigen3/Eigen/src/OrderingMethods/Amd.h
+ ../../extern/Eigen3/Eigen/src/PardisoSupport/PardisoSupport.h
+ ../../extern/Eigen3/Eigen/src/PaStiXSupport/PaStiXSupport.h
+ ../../extern/Eigen3/Eigen/src/plugins/ArrayCwiseBinaryOps.h
+ ../../extern/Eigen3/Eigen/src/plugins/ArrayCwiseUnaryOps.h
+ ../../extern/Eigen3/Eigen/src/plugins/BlockMethods.h
+ ../../extern/Eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h
+ ../../extern/Eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h
+ ../../extern/Eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h
+ ../../extern/Eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h
+ ../../extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR.h
+ ../../extern/Eigen3/Eigen/src/QR/ColPivHouseholderQR_MKL.h
+ ../../extern/Eigen3/Eigen/src/QR/FullPivHouseholderQR.h
+ ../../extern/Eigen3/Eigen/src/QR/HouseholderQR.h
+ ../../extern/Eigen3/Eigen/src/QR/HouseholderQR_MKL.h
+ ../../extern/Eigen3/Eigen/src/SparseCholesky/SimplicialCholesky.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/AmbiVector.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/CompressedStorage.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/ConservativeSparseSparseProduct.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/CoreIterators.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/MappedSparseMatrix.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseAssign.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseBlock.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseCwiseBinaryOp.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseCwiseUnaryOp.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseDenseProduct.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseDiagonalProduct.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseDot.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseFuzzy.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseMatrix.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseMatrixBase.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparsePermutation.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseProduct.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseRedux.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseSelfAdjointView.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseSparseProductWithPruning.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseTranspose.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseTriangularView.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseUtil.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseVector.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/SparseView.h
+ ../../extern/Eigen3/Eigen/src/SparseCore/TriangularSolver.h
+ ../../extern/Eigen3/Eigen/src/StlSupport/details.h
+ ../../extern/Eigen3/Eigen/src/StlSupport/StdDeque.h
+ ../../extern/Eigen3/Eigen/src/StlSupport/StdList.h
+ ../../extern/Eigen3/Eigen/src/StlSupport/StdVector.h
+ ../../extern/Eigen3/Eigen/src/SuperLUSupport/SuperLUSupport.h
+ ../../extern/Eigen3/Eigen/src/SVD/JacobiSVD.h
+ ../../extern/Eigen3/Eigen/src/SVD/JacobiSVD_MKL.h
+ ../../extern/Eigen3/Eigen/src/SVD/UpperBidiagonalization.h
+ ../../extern/Eigen3/Eigen/src/UmfPackSupport/UmfPackSupport.h
)
diff --git a/intern/itasc/Scene.cpp b/intern/itasc/Scene.cpp
index 7a83f821bf0..7ed8fc4e63c 100644
--- a/intern/itasc/Scene.cpp
+++ b/intern/itasc/Scene.cpp
@@ -40,7 +40,7 @@ public:
{
q_nr += m_qrange.start;
project(m_scene->m_Wq, Range(q_nr, ndof), m_qrange).setZero();
- // update the ouput vector so that the movement of this joint will be
+ // update the output vector so that the movement of this joint will be
// taken into account and we can put the joint back in its initial position
// which means that the jacobian doesn't need to be changed
for (unsigned int i=0 ;i<ndof ; ++i, ++q_nr) {
diff --git a/intern/itasc/kdl/utilities/utility_io.cpp b/intern/itasc/kdl/utilities/utility_io.cpp
index e16a85167bc..8656b05545c 100644
--- a/intern/itasc/kdl/utilities/utility_io.cpp
+++ b/intern/itasc/kdl/utilities/utility_io.cpp
@@ -39,7 +39,7 @@ namespace KDL {
}
}
// Eats until the end of the line
- int _EatUntilEndOfLine( std::istream& is, int* countp=NULL) {
+static int _EatUntilEndOfLine( std::istream& is, int* countp=NULL) {
int ch;
int count;
count = 0;
@@ -53,7 +53,7 @@ namespace KDL {
}
// Eats until the end of the comment
- int _EatUntilEndOfComment( std::istream& is, int* countp=NULL) {
+static int _EatUntilEndOfComment( std::istream& is, int* countp=NULL) {
int ch;
int count;
count = 0;
@@ -75,7 +75,7 @@ namespace KDL {
// Eats space-like characters and comments
// possibly returns the number of space-like characters eaten.
-int _EatSpace( std::istream& is,int* countp=NULL) {
+static int _EatSpace( std::istream& is,int* countp=NULL) {
int ch;
int count;
count=-1;
diff --git a/intern/memutil/MEM_CacheLimiter.h b/intern/memutil/MEM_CacheLimiter.h
index 801ee154d40..cfff5d10e4f 100644
--- a/intern/memutil/MEM_CacheLimiter.h
+++ b/intern/memutil/MEM_CacheLimiter.h
@@ -123,20 +123,11 @@ public:
parent->touch(this);
}
- void set_priority(int priority) {
- this->priority = priority;
- }
-
- int get_priority(void) {
- return this->priority;
- }
-
private:
friend class MEM_CacheLimiter<T>;
T * data;
int refcount;
- int priority;
typename std::list<MEM_CacheLimiterHandle<T> *, MEM_Allocator<MEM_CacheLimiterHandle<T> *> >::iterator me;
MEM_CacheLimiter<T> * parent;
};
@@ -171,7 +162,6 @@ public:
}
void enforce_limits() {
- MEM_CachePriorityQueue priority_queue;
size_t max = MEM_CacheLimiter_get_maximum();
size_t mem_in_use, cur_size;
@@ -179,9 +169,10 @@ public:
return;
}
- if(getDataSize) {
+ if (getDataSize) {
mem_in_use = total_size();
- } else {
+ }
+ else {
mem_in_use = MEM_get_memory_in_use();
}
@@ -189,23 +180,24 @@ public:
return;
}
- priority_queue = get_priority_queue();
-
- while (!priority_queue.empty() && mem_in_use > max) {
- MEM_CacheElementPtr elem = priority_queue.top();
+ while (!queue.empty() && mem_in_use > max) {
+ MEM_CacheElementPtr elem = get_least_priority_destroyable_element();
- priority_queue.pop();
+ if (!elem)
+ break;
- if(getDataSize) {
+ if (getDataSize) {
cur_size = getDataSize(elem->get()->get_data());
- } else {
+ }
+ else {
cur_size = mem_in_use;
}
if (elem->destroy_if_possible()) {
if (getDataSize) {
mem_in_use -= cur_size;
- } else {
+ }
+ else {
mem_in_use -= cur_size - MEM_get_memory_in_use();
}
}
@@ -229,14 +221,6 @@ private:
typedef std::list<MEM_CacheElementPtr, MEM_Allocator<MEM_CacheElementPtr> > MEM_CacheQueue;
typedef typename MEM_CacheQueue::iterator iterator;
- struct compare_element_priority : public std::binary_function<MEM_CacheElementPtr, MEM_CacheElementPtr, bool> {
- bool operator()(const MEM_CacheElementPtr left_elem, const MEM_CacheElementPtr right_elem) const {
- return left_elem->get_priority() > right_elem->get_priority();
- }
- };
-
- typedef std::priority_queue<MEM_CacheElementPtr, std::vector<MEM_CacheElementPtr>, compare_element_priority > MEM_CachePriorityQueue;
-
size_t total_size() {
size_t size = 0;
for (iterator it = queue.begin(); it != queue.end(); it++) {
@@ -245,28 +229,35 @@ private:
return size;
}
- MEM_CachePriorityQueue get_priority_queue(void) {
- MEM_CachePriorityQueue priority_queue;
+ MEM_CacheElementPtr get_least_priority_destroyable_element(void) {
+ if (queue.empty())
+ return NULL;
+
+ if (!getItemPriority)
+ return *queue.begin();
+
+ MEM_CacheElementPtr best_match_elem = NULL;
+ int best_match_priority = 0;
iterator it;
int i;
for (it = queue.begin(), i = 0; it != queue.end(); it++, i++) {
MEM_CacheElementPtr elem = *it;
- int priority;
+
+ if (!elem->can_destroy())
+ continue;
/* by default 0 means higherst priority element */
- priority = -(queue.size() - i - 1);
+ int priority = -(queue.size() - i - 1);
+ priority = getItemPriority(elem->get()->get_data(), priority);
- if (getItemPriority) {
- priority = getItemPriority(elem->get()->get_data(), priority);
+ if (priority < best_match_priority || best_match_elem == NULL) {
+ best_match_priority = priority;
+ best_match_elem = elem;
}
-
- elem->set_priority(priority);
-
- priority_queue.push(elem);
}
- return priority_queue;
+ return best_match_elem;
}
MEM_CacheQueue queue;
diff --git a/intern/memutil/MEM_CacheLimiterC-Api.h b/intern/memutil/MEM_CacheLimiterC-Api.h
index 1ae5e9df1c6..c05c9d61ea2 100644
--- a/intern/memutil/MEM_CacheLimiterC-Api.h
+++ b/intern/memutil/MEM_CacheLimiterC-Api.h
@@ -80,7 +80,7 @@ void delete_MEM_CacheLimiter(MEM_CacheLimiterC *This);
* @return CacheLimiterHandle to ref, unref, touch the managed object
*/
-MEM_CacheLimiterHandleC *MEM_CacheLimiter_insert(MEM_CacheLimiterC * This, void * data);
+MEM_CacheLimiterHandleC *MEM_CacheLimiter_insert(MEM_CacheLimiterC *This, void *data);
/**
* Free objects until memory constraints are satisfied
@@ -140,7 +140,7 @@ int MEM_CacheLimiter_get_refcount(MEM_CacheLimiterHandleC *handle);
* @param handle of object
*/
-void * MEM_CacheLimiter_get(MEM_CacheLimiterHandleC *handle);
+void *MEM_CacheLimiter_get(MEM_CacheLimiterHandleC *handle);
void MEM_CacheLimiter_ItemPriority_Func_set(MEM_CacheLimiterC *This,
MEM_CacheLimiter_ItemPriority_Func item_priority_func);
diff --git a/intern/memutil/MEM_SmartPtr.h b/intern/memutil/MEM_SmartPtr.h
index 722a0a8fd3b..09cf5c95854 100644
--- a/intern/memutil/MEM_SmartPtr.h
+++ b/intern/memutil/MEM_SmartPtr.h
@@ -86,7 +86,7 @@
* private :
* MEM_SmartPtr<foo> m_foo;
* }
- *
+ *
* You may also safely construct vectors of MEM_SmartPtrs and
* have the vector own stuff you put into it.
*
@@ -167,7 +167,7 @@ public :
Ref(
) const {
return *m_val;
- }
+ }
/**
* Assignment operator - ownership is transfered from rhs to lhs.
@@ -207,7 +207,7 @@ public :
Release(
) const {
T* temp = m_val;
- (const_cast<MEM_SmartPtr *>(this))->m_val = NULL;
+ (const_cast<MEM_SmartPtr *>(this))->m_val = NULL;
return temp;
}
diff --git a/intern/memutil/intern/MEM_CacheLimiterC-Api.cpp b/intern/memutil/intern/MEM_CacheLimiterC-Api.cpp
index 81a1ce670ae..7a19543b2db 100644
--- a/intern/memutil/intern/MEM_CacheLimiterC-Api.cpp
+++ b/intern/memutil/intern/MEM_CacheLimiterC-Api.cpp
@@ -59,9 +59,9 @@ public:
}
~MEM_CacheLimiterCClass();
- handle_t * insert(void * data);
+ handle_t * insert(void *data);
- void destruct(void * data, list_t::iterator it);
+ void destruct(void *data, list_t::iterator it);
cache_t * get_cache() {
return &cache;
@@ -76,7 +76,7 @@ private:
class MEM_CacheLimiterHandleCClass {
public:
- MEM_CacheLimiterHandleCClass(void * data_, MEM_CacheLimiterCClass * parent_) :
+ MEM_CacheLimiterHandleCClass(void *data_, MEM_CacheLimiterCClass *parent_) :
data(data_),
parent(parent_)
{ }
@@ -87,7 +87,7 @@ public:
it = it_;
}
- void set_data(void * data_) {
+ void set_data(void *data_) {
data = data_;
}
@@ -101,7 +101,7 @@ private:
list_t::iterator it;
};
-handle_t *MEM_CacheLimiterCClass::insert(void * data)
+handle_t *MEM_CacheLimiterCClass::insert(void *data)
{
cclass_list.push_back(new MEM_CacheLimiterHandleCClass(data, this));
list_t::iterator it = cclass_list.end();
@@ -111,7 +111,7 @@ handle_t *MEM_CacheLimiterCClass::insert(void * data)
return cache.insert(cclass_list.back());
}
-void MEM_CacheLimiterCClass::destruct(void * data, list_t::iterator it)
+void MEM_CacheLimiterCClass::destruct(void *data, list_t::iterator it)
{
data_destructor(data);
cclass_list.erase(it);
diff --git a/intern/mikktspace/mikktspace.c b/intern/mikktspace/mikktspace.c
index a1ae6bd81c0..a6597986c0a 100644
--- a/intern/mikktspace/mikktspace.c
+++ b/intern/mikktspace/mikktspace.c
@@ -1063,6 +1063,7 @@ static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupT
const int iNrMaxGroups = iNrTrianglesIn*3;
int iNrActiveGroups = 0;
int iOffset = 0, f=0, i=0;
+ (void)iNrMaxGroups; /* quiet warnings in non debug mode */
for (f=0; f<iNrTrianglesIn; f++)
{
for (i=0; i<3; i++)
@@ -1094,6 +1095,7 @@ static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupT
const tbool bOrPre2 = (pTriInfos[neigh_indexL].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE;
assert(bAnswer || bDiff);
+ (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */
}
if (neigh_indexR>=0) // neighbor
{
@@ -1104,6 +1106,7 @@ static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupT
const tbool bOrPre2 = (pTriInfos[neigh_indexR].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE;
assert(bAnswer || bDiff);
+ (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */
}
// update offset
diff --git a/intern/opencolorio/CMakeLists.txt b/intern/opencolorio/CMakeLists.txt
index 479bbd3ab0a..aeb10669d57 100644
--- a/intern/opencolorio/CMakeLists.txt
+++ b/intern/opencolorio/CMakeLists.txt
@@ -23,40 +23,43 @@
#
# ***** END GPL LICENSE BLOCK *****
-if(WITH_OPENCOLORIO)
set(INC
.
- ${OPENCOLORIO_INCLUDE_DIRS}
+ ../guardedalloc
+ ../../source/blender/blenlib
+)
+
+set(INC_SYS
+
)
set(SRC
- ocio_capi.cpp
+ ocio_capi.cc
+ fallback_impl.cc
+
ocio_capi.h
+ ocio_impl.h
)
- if(WIN32 AND NOT MINGW)
- list(APPEND INC
- ${BOOST_INCLUDE_DIR}
- )
- endif()
-else()
- set(INC
- .
- ../../source/blender/blenlib
+if(WITH_OPENCOLORIO)
+ add_definitions(
+ -DWITH_OCIO
)
- set(SRC
- ocio_capi_stub.cpp
- ocio_capi.h
+ list(APPEND INC_SYS
+ ${OPENCOLORIO_INCLUDE_DIRS}
)
-endif()
-set(INC_SYS
- ../guardedalloc
+ list(APPEND SRC
+ ocio_impl.cc
)
-add_definitions(
+ if(WIN32 AND NOT MINGW)
+ list(APPEND INC_SYS
+ ${BOOST_INCLUDE_DIR}
)
+ endif()
+endif()
-blender_add_lib(bf_intern_opencolorio "${SRC}" "${INC}" "${INC_SYS}")
+blender_add_lib(bf_intern_opencolorio "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/intern/opencolorio/SConscript b/intern/opencolorio/SConscript
index fec07662735..a4d21f3e440 100644
--- a/intern/opencolorio/SConscript
+++ b/intern/opencolorio/SConscript
@@ -2,18 +2,18 @@
Import('env')
-sources = env.Glob('*.cpp')
+sources = env.Glob('*.cc')
incs = '. ../guardedalloc ../../source/blender/blenlib'
+defs = []
if env['WITH_BF_OCIO']:
- sources.remove('ocio_capi_stub.cpp')
-
+ defs.append('WITH_OCIO')
incs += ' ' + env['BF_OCIO_INC']
if env['OURPLATFORM'] in ('win32-vc', 'win64-vc'):
incs += ' ' + env['BF_BOOST_INC']
else:
- sources.remove('ocio_capi.cpp')
+ sources.remove('ocio_impl.cc')
-env.BlenderLib( 'bf_intern_opencolorio', sources, Split(incs), [], libtype=['extern','player'], priority=[10, 185])
+env.BlenderLib( 'bf_intern_opencolorio', sources, Split(incs), defs, libtype=['extern','player'], priority=[10, 185])
diff --git a/intern/opencolorio/ocio_capi.h b/intern/opencolorio/ocio_capi.h
index f0edd25ac14..0ce5f8a1456 100644
--- a/intern/opencolorio/ocio_capi.h
+++ b/intern/opencolorio/ocio_capi.h
@@ -28,96 +28,94 @@
#ifndef __OCIO_CAPI_H__
#define __OCIO_CAPI_H__
-
-
#ifdef __cplusplus
-using namespace OCIO_NAMESPACE;
extern "C" {
#endif
#define OCIO_DECLARE_HANDLE(name) typedef struct name##__ { int unused; } *name
-
-#ifndef OCIO_CAPI_IMPLEMENTATION
- #define OCIO_ROLE_SCENE_LINEAR "scene_linear"
- #define OCIO_ROLE_COLOR_PICKING "color_picking"
- #define OCIO_ROLE_TEXTURE_PAINT "texture_paint"
- #define OCIO_ROLE_DEFAULT_BYTE "default_byte"
- #define OCIO_ROLE_DEFAULT_FLOAT "default_float"
- #define OCIO_ROLE_DEFAULT_SEQUENCER "default_sequencer"
-
- OCIO_DECLARE_HANDLE(ConstConfigRcPtr);
- OCIO_DECLARE_HANDLE(ConstColorSpaceRcPtr);
- OCIO_DECLARE_HANDLE(ConstProcessorRcPtr);
- OCIO_DECLARE_HANDLE(ConstContextRcPtr);
- OCIO_DECLARE_HANDLE(PackedImageDesc);
- OCIO_DECLARE_HANDLE(DisplayTransformRcPtr);
- OCIO_DECLARE_HANDLE(ConstTransformRcPtr);
- OCIO_DECLARE_HANDLE(ExponentTransformRcPtr);
- OCIO_DECLARE_HANDLE(MatrixTransformRcPtr);
-#endif
-
-
-ConstConfigRcPtr *OCIO_getCurrentConfig(void);
-void OCIO_setCurrentConfig(const ConstConfigRcPtr *config);
-
-ConstConfigRcPtr *OCIO_configCreateFromEnv(void);
-ConstConfigRcPtr *OCIO_configCreateFromFile(const char* filename);
-
-void OCIO_configRelease(ConstConfigRcPtr *config);
-
-int OCIO_configGetNumColorSpaces(ConstConfigRcPtr *config);
-const char *OCIO_configGetColorSpaceNameByIndex(ConstConfigRcPtr *config, int index);
-ConstColorSpaceRcPtr *OCIO_configGetColorSpace(ConstConfigRcPtr *config, const char *name);
-int OCIO_configGetIndexForColorSpace(ConstConfigRcPtr *config, const char *name);
-
-int OCIO_colorSpaceIsInvertible(ConstColorSpaceRcPtr *cs);
-
-void OCIO_colorSpaceRelease(ConstColorSpaceRcPtr *cs);
-
-const char *OCIO_configGetDefaultDisplay(ConstConfigRcPtr *config);
-int OCIO_configGetNumDisplays(ConstConfigRcPtr *config);
-const char *OCIO_configGetDisplay(ConstConfigRcPtr *config, int index);
-const char *OCIO_configGetDefaultView(ConstConfigRcPtr *config, const char *display);
-int OCIO_configGetNumViews(ConstConfigRcPtr *config, const char *display);
-const char *OCIO_configGetView(ConstConfigRcPtr *config, const char *display, int index);
-const char *OCIO_configGetDisplayColorSpaceName(ConstConfigRcPtr *config, const char *display, const char *view);
-
-ConstProcessorRcPtr *OCIO_configGetProcessorWithNames(ConstConfigRcPtr *config, const char *srcName, const char *dstName);
-ConstProcessorRcPtr *OCIO_configGetProcessor(ConstConfigRcPtr *config, ConstTransformRcPtr *transform);
-
-void OCIO_processorApply(ConstProcessorRcPtr *processor, PackedImageDesc *img);
-void OCIO_processorApply_predivide(ConstProcessorRcPtr *processor, PackedImageDesc *img);
-void OCIO_processorApplyRGB(ConstProcessorRcPtr *processor, float *pixel);
-void OCIO_processorApplyRGBA(ConstProcessorRcPtr *processor, float *pixel);
-void OCIO_processorApplyRGBA_predivide(ConstProcessorRcPtr *processor, float *pixel);
-
-void OCIO_processorRelease(ConstProcessorRcPtr *p);
-
-const char *OCIO_colorSpaceGetName(ConstColorSpaceRcPtr *cs);
-const char *OCIO_colorSpaceGetDescription(ConstColorSpaceRcPtr *cs);
-const char *OCIO_colorSpaceGetFamily(ConstColorSpaceRcPtr *cs);
-
-DisplayTransformRcPtr *OCIO_createDisplayTransform(void);
-void OCIO_displayTransformSetInputColorSpaceName(DisplayTransformRcPtr *dt, const char *name);
-void OCIO_displayTransformSetDisplay(DisplayTransformRcPtr *dt, const char *name);
-void OCIO_displayTransformSetView(DisplayTransformRcPtr *dt, const char *name);
-void OCIO_displayTransformSetDisplayCC(DisplayTransformRcPtr *dt, ConstTransformRcPtr *et);
-void OCIO_displayTransformSetLinearCC(DisplayTransformRcPtr *dt, ConstTransformRcPtr *et);
-void OCIO_displayTransformRelease(DisplayTransformRcPtr *dt);
-
-PackedImageDesc *OCIO_createPackedImageDesc(float *data, long width, long height, long numChannels,
+#define OCIO_ROLE_SCENE_LINEAR "scene_linear"
+#define OCIO_ROLE_COLOR_PICKING "color_picking"
+#define OCIO_ROLE_TEXTURE_PAINT "texture_paint"
+#define OCIO_ROLE_DEFAULT_BYTE "default_byte"
+#define OCIO_ROLE_DEFAULT_FLOAT "default_float"
+#define OCIO_ROLE_DEFAULT_SEQUENCER "default_sequencer"
+
+OCIO_DECLARE_HANDLE(OCIO_ConstConfigRcPtr);
+OCIO_DECLARE_HANDLE(OCIO_ConstColorSpaceRcPtr);
+OCIO_DECLARE_HANDLE(OCIO_ConstProcessorRcPtr);
+OCIO_DECLARE_HANDLE(OCIO_ConstContextRcPtr);
+OCIO_DECLARE_HANDLE(OCIO_PackedImageDesc);
+OCIO_DECLARE_HANDLE(OCIO_DisplayTransformRcPtr);
+OCIO_DECLARE_HANDLE(OCIO_ConstTransformRcPtr);
+OCIO_DECLARE_HANDLE(OCIO_ExponentTransformRcPtr);
+OCIO_DECLARE_HANDLE(OCIO_MatrixTransformRcPtr);
+
+void OCIO_init(void);
+void OCIO_exit(void);
+
+OCIO_ConstConfigRcPtr *OCIO_getCurrentConfig(void);
+void OCIO_setCurrentConfig(const OCIO_ConstConfigRcPtr *config);
+
+OCIO_ConstConfigRcPtr *OCIO_configCreateFromEnv(void);
+OCIO_ConstConfigRcPtr *OCIO_configCreateFromFile(const char* filename);
+OCIO_ConstConfigRcPtr *OCIO_configCreateFallback(void);
+
+void OCIO_configRelease(OCIO_ConstConfigRcPtr *config);
+
+int OCIO_configGetNumColorSpaces(OCIO_ConstConfigRcPtr *config);
+const char *OCIO_configGetColorSpaceNameByIndex(OCIO_ConstConfigRcPtr *config, int index);
+OCIO_ConstColorSpaceRcPtr *OCIO_configGetColorSpace(OCIO_ConstConfigRcPtr *config, const char *name);
+int OCIO_configGetIndexForColorSpace(OCIO_ConstConfigRcPtr *config, const char *name);
+
+int OCIO_colorSpaceIsInvertible(OCIO_ConstColorSpaceRcPtr *cs);
+int OCIO_colorSpaceIsData(OCIO_ConstColorSpaceRcPtr *cs);
+
+void OCIO_colorSpaceRelease(OCIO_ConstColorSpaceRcPtr *cs);
+
+const char *OCIO_configGetDefaultDisplay(OCIO_ConstConfigRcPtr *config);
+int OCIO_configGetNumDisplays(OCIO_ConstConfigRcPtr *config);
+const char *OCIO_configGetDisplay(OCIO_ConstConfigRcPtr *config, int index);
+const char *OCIO_configGetDefaultView(OCIO_ConstConfigRcPtr *config, const char *display);
+int OCIO_configGetNumViews(OCIO_ConstConfigRcPtr *config, const char *display);
+const char *OCIO_configGetView(OCIO_ConstConfigRcPtr *config, const char *display, int index);
+const char *OCIO_configGetDisplayColorSpaceName(OCIO_ConstConfigRcPtr *config, const char *display, const char *view);
+
+OCIO_ConstProcessorRcPtr *OCIO_configGetProcessorWithNames(OCIO_ConstConfigRcPtr *config, const char *srcName, const char *dstName);
+OCIO_ConstProcessorRcPtr *OCIO_configGetProcessor(OCIO_ConstConfigRcPtr *config, OCIO_ConstTransformRcPtr *transform);
+
+void OCIO_processorApply(OCIO_ConstProcessorRcPtr *processor, OCIO_PackedImageDesc *img);
+void OCIO_processorApply_predivide(OCIO_ConstProcessorRcPtr *processor, OCIO_PackedImageDesc *img);
+void OCIO_processorApplyRGB(OCIO_ConstProcessorRcPtr *processor, float *pixel);
+void OCIO_processorApplyRGBA(OCIO_ConstProcessorRcPtr *processor, float *pixel);
+void OCIO_processorApplyRGBA_predivide(OCIO_ConstProcessorRcPtr *processor, float *pixel);
+
+void OCIO_processorRelease(OCIO_ConstProcessorRcPtr *p);
+
+const char *OCIO_colorSpaceGetName(OCIO_ConstColorSpaceRcPtr *cs);
+const char *OCIO_colorSpaceGetDescription(OCIO_ConstColorSpaceRcPtr *cs);
+const char *OCIO_colorSpaceGetFamily(OCIO_ConstColorSpaceRcPtr *cs);
+
+OCIO_DisplayTransformRcPtr *OCIO_createDisplayTransform(void);
+void OCIO_displayTransformSetInputColorSpaceName(OCIO_DisplayTransformRcPtr *dt, const char *name);
+void OCIO_displayTransformSetDisplay(OCIO_DisplayTransformRcPtr *dt, const char *name);
+void OCIO_displayTransformSetView(OCIO_DisplayTransformRcPtr *dt, const char *name);
+void OCIO_displayTransformSetDisplayCC(OCIO_DisplayTransformRcPtr *dt, OCIO_ConstTransformRcPtr *et);
+void OCIO_displayTransformSetLinearCC(OCIO_DisplayTransformRcPtr *dt, OCIO_ConstTransformRcPtr *et);
+void OCIO_displayTransformRelease(OCIO_DisplayTransformRcPtr *dt);
+
+OCIO_PackedImageDesc *OCIO_createOCIO_PackedImageDesc(float *data, long width, long height, long numChannels,
long chanStrideBytes, long xStrideBytes, long yStrideBytes);
-void OCIO_packedImageDescRelease(PackedImageDesc *p);
+void OCIO_OCIO_PackedImageDescRelease(OCIO_PackedImageDesc *p);
-ExponentTransformRcPtr *OCIO_createExponentTransform(void);
-void OCIO_exponentTransformSetValue(ExponentTransformRcPtr *et, const float *exponent);
-void OCIO_exponentTransformRelease(ExponentTransformRcPtr *et);
+OCIO_ExponentTransformRcPtr *OCIO_createExponentTransform(void);
+void OCIO_exponentTransformSetValue(OCIO_ExponentTransformRcPtr *et, const float *exponent);
+void OCIO_exponentTransformRelease(OCIO_ExponentTransformRcPtr *et);
-MatrixTransformRcPtr *OCIO_createMatrixTransform(void);
-void OCIO_matrixTransformSetValue(MatrixTransformRcPtr *et, const float *m44, const float *offset4);
-void OCIO_matrixTransformRelease(MatrixTransformRcPtr *mt);
+OCIO_MatrixTransformRcPtr *OCIO_createMatrixTransform(void);
+void OCIO_matrixTransformSetValue(OCIO_MatrixTransformRcPtr *et, const float *m44, const float *offset4);
+void OCIO_matrixTransformRelease(OCIO_MatrixTransformRcPtr *mt);
void OCIO_matrixTransformScale(float * m44, float * offset4, const float * scale4);
@@ -125,4 +123,4 @@ void OCIO_matrixTransformScale(float * m44, float * offset4, const float * scale
}
#endif
-#endif //OCIO_CAPI_H
+#endif /* OCIO_CAPI_H */
diff --git a/intern/opennl/CMakeLists.txt b/intern/opennl/CMakeLists.txt
index 322428386b1..b7a24839e38 100644
--- a/intern/opennl/CMakeLists.txt
+++ b/intern/opennl/CMakeLists.txt
@@ -40,11 +40,10 @@ add_definitions(
set(INC
extern
superlu
- ../../extern/colamd/Include
)
set(INC_SYS
-
+ ../../extern/colamd/Include
)
set(SRC
diff --git a/intern/opennl/SConscript b/intern/opennl/SConscript
index 711955cbfeb..a0f02735748 100644
--- a/intern/opennl/SConscript
+++ b/intern/opennl/SConscript
@@ -5,8 +5,5 @@ sources = env.Glob('intern/*.c') + env.Glob('superlu/*.c')
incs = 'extern superlu ../../extern/colamd/Include'
-if (env['OURPLATFORM'] in ('win32-mingw', 'win64-mingw')):
- env.BlenderLib ('bf_intern_opennl', sources, Split(incs), [], libtype=['core','intern'], priority=[1,80] )
-else:
- env.BlenderLib ('bf_intern_opennl', sources, Split(incs), [], libtype=['core'], priority=[55] )
+env.BlenderLib ('bf_intern_opennl', sources, Split(incs), [], libtype=['intern','player'], priority=[100,90] )
diff --git a/intern/opennl/intern/opennl.c b/intern/opennl/intern/opennl.c
index 71809cc7480..f9c63e9ecf6 100644
--- a/intern/opennl/intern/opennl.c
+++ b/intern/opennl/intern/opennl.c
@@ -137,14 +137,14 @@ static void __nl_should_not_have_reached(char* file, int line) {
/************************************************************************************/
/* memory management */
-#define __NL_NEW(T) (T*)(calloc(1, sizeof(T)))
-#define __NL_NEW_ARRAY(T,NB) (T*)(calloc((NB),sizeof(T)))
+#define __NL_NEW(T) (T*)(calloc(1, sizeof(T)))
+#define __NL_NEW_ARRAY(T,NB) (T*)(calloc(MAX(NB, 1),sizeof(T)))
#define __NL_RENEW_ARRAY(T,x,NB) (T*)(realloc(x,(NB)*sizeof(T)))
-#define __NL_DELETE(x) free(x); x = NULL
-#define __NL_DELETE_ARRAY(x) free(x); x = NULL
+#define __NL_DELETE(x) if(x) free(x); x = NULL
+#define __NL_DELETE_ARRAY(x) if(x) free(x); x = NULL
-#define __NL_CLEAR(T, x) memset(x, 0, sizeof(T))
-#define __NL_CLEAR_ARRAY(T,x,NB) memset(x, 0, (NB)*sizeof(T))
+#define __NL_CLEAR(T, x) memset(x, 0, sizeof(T))
+#define __NL_CLEAR_ARRAY(T,x,NB) if(NB) memset(x, 0, (NB)*sizeof(T))
/************************************************************************************/
/* Dynamic arrays for sparse row/columns */
@@ -1042,6 +1042,9 @@ static NLboolean __nlFactorize_SUPERLU(__NLContext *context, NLint *permutation)
NLuint n = context->n;
NLuint nnz = __nlSparseMatrixNNZ(M); /* number of non-zero coeffs */
+ /*if(n > 10)
+ n = 10;*/
+
/* Compressed Row Storage matrix representation */
NLint *xa = __NL_NEW_ARRAY(NLint, n+1);
NLfloat *rhs = __NL_NEW_ARRAY(NLfloat, n);
diff --git a/intern/opennl/superlu/get_perm_c.c b/intern/opennl/superlu/get_perm_c.c
index 320fe3471f4..59889645988 100644
--- a/intern/opennl/superlu/get_perm_c.c
+++ b/intern/opennl/superlu/get_perm_c.c
@@ -173,17 +173,19 @@ getata(
/* Flag the diagonal so it's not included in the B matrix */
marker[j] = j;
- for (i = colptr[j]; i < colptr[j+1]; ++i) {
- /* A_kj is nonzero, add pattern of column T_*k to B_*j */
- k = rowind[i];
- for (ti = t_colptr[k]; ti < t_colptr[k+1]; ++ti) {
- trow = t_rowind[ti];
- if ( marker[trow] != j ) {
- marker[trow] = j;
- b_rowind[num_nz++] = trow;
+ if ( *atanz ) {
+ for (i = colptr[j]; i < colptr[j+1]; ++i) {
+ /* A_kj is nonzero, add pattern of column T_*k to B_*j */
+ k = rowind[i];
+ for (ti = t_colptr[k]; ti < t_colptr[k+1]; ++ti) {
+ trow = t_rowind[ti];
+ if ( marker[trow] != j ) {
+ marker[trow] = j;
+ b_rowind[num_nz++] = trow;
+ }
+ }
+ }
}
- }
- }
}
b_colptr[n] = num_nz;
@@ -305,21 +307,23 @@ at_plus_a(
marker[j] = j;
/* Add pattern of column A_*k to B_*j */
- for (i = colptr[j]; i < colptr[j+1]; ++i) {
- k = rowind[i];
- if ( marker[k] != j ) {
- marker[k] = j;
- (*b_rowind)[num_nz++] = k;
- }
- }
+ if (*bnz) {
+ for (i = colptr[j]; i < colptr[j+1]; ++i) {
+ k = rowind[i];
+ if ( marker[k] != j ) {
+ marker[k] = j;
+ (*b_rowind)[num_nz++] = k;
+ }
+ }
- /* Add pattern of column T_*k to B_*j */
- for (i = t_colptr[j]; i < t_colptr[j+1]; ++i) {
- k = t_rowind[i];
- if ( marker[k] != j ) {
- marker[k] = j;
- (*b_rowind)[num_nz++] = k;
- }
+ /* Add pattern of column T_*k to B_*j */
+ for (i = t_colptr[j]; i < t_colptr[j+1]; ++i) {
+ k = t_rowind[i];
+ if ( marker[k] != j ) {
+ marker[k] = j;
+ (*b_rowind)[num_nz++] = k;
+ }
+ }
}
}
(*b_colptr)[n] = num_nz;
diff --git a/intern/raskter/CMakeLists.txt b/intern/raskter/CMakeLists.txt
index de6d2c33b7f..3e1368d8eb0 100644
--- a/intern/raskter/CMakeLists.txt
+++ b/intern/raskter/CMakeLists.txt
@@ -33,11 +33,8 @@ set(INC_SYS
set(SRC
raskter.c
- raskter_mt.c
- raskter_kdtree.c
raskter.h
- raskter_kdtree.h
)
blender_add_lib(bf_intern_raskter "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/intern/raskter/raskter.c b/intern/raskter/raskter.c
index 875dfc8a63b..21153082324 100644
--- a/intern/raskter/raskter.c
+++ b/intern/raskter/raskter.c
@@ -24,28 +24,49 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
+
/** \file raskter.c
* \ingroup RASKTER
*/
#include <stdlib.h>
#include "raskter.h"
-//#define __PLX__FAKE_AA__
-//#define __PLX_KD_TREE__
-#ifdef __PLX_KD_TREE__
-#include "kdtree.h"
-#endif
-
-
-// this is needed for inlining behavior
-#if defined _MSC_VER
-# define DO_INLINE __inline
-#elif defined (__sun) || defined (__sun__)
-# define DO_INLINE
-#else
-# define DO_INLINE static inline
-#endif
+/* from BLI_utildefines.h */
+#define MIN2(x, y) ( (x) < (y) ? (x) : (y) )
+#define MAX2(x, y) ( (x) > (y) ? (x) : (y) )
+
+struct PolyVert {
+ int x;
+ int y;
+};
+
+struct e_Status {
+ int x;
+ int ybeg;
+ int xshift;
+ int xdir;
+ int drift;
+ int drift_inc;
+ int drift_dec;
+ int num;
+ struct e_Status *e_next;
+};
+
+struct r_BufferStats {
+ float *buf;
+ int sizex;
+ int sizey;
+ int ymin;
+ int ymax;
+ int xmin;
+ int xmax;
+};
+
+struct r_FillContext {
+ struct e_Status *all_edges, *possible_edges;
+ struct r_BufferStats rb;
+};
/*
* Sort all the edges of the input polygon by Y, then by X, of the "first" vertex encountered.
@@ -55,113 +76,121 @@
* just the poly. Since the DEM code could end up being coupled with this, we'll keep it separate
* for now.
*/
-void preprocess_all_edges(struct r_fill_context *ctx, struct poly_vert *verts, int num_verts, struct e_status *open_edge) {
- int i;
- int xbeg;
- int ybeg;
- int xend;
- int yend;
- int dx;
- int dy;
- int temp_pos;
- int xdist;
- struct e_status *e_new;
- struct e_status *next_edge;
- struct e_status **next_edge_ref;
- struct poly_vert *v;
- /* set up pointers */
- v = verts;
- ctx->all_edges = NULL;
- /* initialize some boundaries */
- ctx->rb.xmax = v[0].x;
- ctx->rb.xmin = v[0].x;
- ctx->rb.ymax = v[0].y;
- ctx->rb.ymin = v[0].y;
- /* loop all verts */
- for(i = 0; i < num_verts; i++) {
- /* determine beginnings and endings of edges, linking last vertex to first vertex */
- xbeg = v[i].x;
- ybeg = v[i].y;
- /* keep track of our x and y bounds */
- if(xbeg >= ctx->rb.xmax) {
- ctx->rb.xmax = xbeg;
- } else if(xbeg <= ctx->rb.xmin) {
- ctx->rb.xmin = xbeg;
- }
- if(ybeg >= ctx->rb.ymax) {
- ctx->rb.ymax= ybeg;
- } else if(ybeg <= ctx->rb.ymin) {
- ctx->rb.ymin=ybeg;
- }
- if(i) {
- /* we're not at the last vert, so end of the edge is the previous vertex */
- xend = v[i - 1].x;
- yend = v[i - 1].y;
- } else {
- /* we're at the first vertex, so the "end" of this edge is the last vertex */
- xend = v[num_verts - 1].x;
- yend = v[num_verts - 1].y;
- }
- /* make sure our edges are facing the correct direction */
- if(ybeg > yend) {
- /* flip the Xs */
- temp_pos = xbeg;
- xbeg = xend;
- xend = temp_pos;
- /* flip the Ys */
- temp_pos = ybeg;
- ybeg = yend;
- yend = temp_pos;
- }
-
- /* calculate y delta */
- dy = yend - ybeg;
- /* dont draw horizontal lines directly, they are scanned as part of the edges they connect, so skip em. :) */
- if(dy) {
- /* create the edge and determine it's slope (for incremental line drawing) */
- e_new = open_edge++;
-
- /* calculate x delta */
- dx = xend - xbeg;
- if(dx > 0) {
- e_new->xdir = 1;
- xdist = dx;
- } else {
- e_new->xdir = -1;
- xdist = -dx;
- }
-
- e_new->x = xbeg;
- e_new->ybeg = ybeg;
- e_new->num = dy;
- e_new->drift_dec = dy;
-
- /* calculate deltas for incremental drawing */
- if(dx >= 0) {
- e_new->drift = 0;
- } else {
- e_new->drift = -dy + 1;
- }
- if(dy >= xdist) {
- e_new->drift_inc = xdist;
- e_new->xshift = 0;
- } else {
- e_new->drift_inc = xdist % dy;
- e_new->xshift = (xdist / dy) * e_new->xdir;
- }
- next_edge_ref = &ctx->all_edges;
- /* link in all the edges, in sorted order */
- for(;;) {
- next_edge = *next_edge_ref;
- if(!next_edge || (next_edge->ybeg > ybeg) || ((next_edge->ybeg == ybeg) && (next_edge->x >= xbeg))) {
- e_new->e_next = next_edge;
- *next_edge_ref = e_new;
- break;
- }
- next_edge_ref = &next_edge->e_next;
- }
- }
- }
+static void preprocess_all_edges(struct r_FillContext *ctx,
+ struct PolyVert *verts, int num_verts, struct e_Status *open_edge)
+{
+ int i;
+ int xbeg;
+ int ybeg;
+ int xend;
+ int yend;
+ int dx;
+ int dy;
+ int temp_pos;
+ int xdist;
+ struct e_Status *e_new;
+ struct e_Status *next_edge;
+ struct e_Status **next_edge_ref;
+ struct PolyVert *v;
+ /* set up pointers */
+ v = verts;
+ ctx->all_edges = NULL;
+ /* initialize some boundaries */
+ ctx->rb.xmax = v[0].x;
+ ctx->rb.xmin = v[0].x;
+ ctx->rb.ymax = v[0].y;
+ ctx->rb.ymin = v[0].y;
+ /* loop all verts */
+ for (i = 0; i < num_verts; i++) {
+ /* determine beginnings and endings of edges, linking last vertex to first vertex */
+ xbeg = v[i].x;
+ ybeg = v[i].y;
+ /* keep track of our x and y bounds */
+ if (xbeg >= ctx->rb.xmax) {
+ ctx->rb.xmax = xbeg;
+ }
+ else if (xbeg <= ctx->rb.xmin) {
+ ctx->rb.xmin = xbeg;
+ }
+ if (ybeg >= ctx->rb.ymax) {
+ ctx->rb.ymax = ybeg;
+ }
+ else if (ybeg <= ctx->rb.ymin) {
+ ctx->rb.ymin=ybeg;
+ }
+ if (i) {
+ /* we're not at the last vert, so end of the edge is the previous vertex */
+ xend = v[i - 1].x;
+ yend = v[i - 1].y;
+ }
+ else {
+ /* we're at the first vertex, so the "end" of this edge is the last vertex */
+ xend = v[num_verts - 1].x;
+ yend = v[num_verts - 1].y;
+ }
+ /* make sure our edges are facing the correct direction */
+ if (ybeg > yend) {
+ /* flip the Xs */
+ temp_pos = xbeg;
+ xbeg = xend;
+ xend = temp_pos;
+ /* flip the Ys */
+ temp_pos = ybeg;
+ ybeg = yend;
+ yend = temp_pos;
+ }
+
+ /* calculate y delta */
+ dy = yend - ybeg;
+ /* dont draw horizontal lines directly, they are scanned as part of the edges they connect, so skip em. :) */
+ if (dy) {
+ /* create the edge and determine it's slope (for incremental line drawing) */
+ e_new = open_edge++;
+
+ /* calculate x delta */
+ dx = xend - xbeg;
+ if (dx > 0) {
+ e_new->xdir = 1;
+ xdist = dx;
+ }
+ else {
+ e_new->xdir = -1;
+ xdist = -dx;
+ }
+
+ e_new->x = xbeg;
+ e_new->ybeg = ybeg;
+ e_new->num = dy;
+ e_new->drift_dec = dy;
+
+ /* calculate deltas for incremental drawing */
+ if (dx >= 0) {
+ e_new->drift = 0;
+ }
+ else {
+ e_new->drift = -dy + 1;
+ }
+ if (dy >= xdist) {
+ e_new->drift_inc = xdist;
+ e_new->xshift = 0;
+ }
+ else {
+ e_new->drift_inc = xdist % dy;
+ e_new->xshift = (xdist / dy) * e_new->xdir;
+ }
+ next_edge_ref = &ctx->all_edges;
+ /* link in all the edges, in sorted order */
+ for (;;) {
+ next_edge = *next_edge_ref;
+ if (!next_edge || (next_edge->ybeg > ybeg) || ((next_edge->ybeg == ybeg) && (next_edge->x >= xbeg))) {
+ e_new->e_next = next_edge;
+ *next_edge_ref = e_new;
+ break;
+ }
+ next_edge_ref = &next_edge->e_next;
+ }
+ }
+ }
}
/*
@@ -169,1364 +198,261 @@ void preprocess_all_edges(struct r_fill_context *ctx, struct poly_vert *verts, i
* for speed, but waiting on final design choices for curve-data before eliminating data the DEM code will need
* if it ends up being coupled with this function.
*/
-static int rast_scan_fill(struct r_fill_context *ctx, struct poly_vert *verts, int num_verts, float intensity) {
- int x_curr; /* current pixel position in X */
- int y_curr; /* current scan line being drawn */
- int yp; /* y-pixel's position in frame buffer */
- int swixd = 0; /* whether or not edges switched position in X */
- float *cpxl; /* pixel pointers... */
- float *mpxl;
- float *spxl;
- struct e_status *e_curr; /* edge pointers... */
- struct e_status *e_temp;
- struct e_status *edgbuf;
- struct e_status **edgec;
-
-
- /*
- * If the number of verts specified to render as a polygon is less than 3,
- * return immediately. Obviously we cant render a poly with sides < 3. The
- * return for this we set to 1, simply so it can be distinguished from the
- * next place we could return, /home/guest/blender-svn/soc-2011-tomato/intern/raskter/raskter.
- * which is a failure to allocate memory.
- */
- if(num_verts < 3) {
- return(1);
- }
-
- /*
- * Try to allocate an edge buffer in memory. needs to be the size of the edge tracking data
- * multiplied by the number of edges, which is always equal to the number of verts in
- * a 2D polygon. Here we return 0 to indicate a memory allocation failure, as opposed to a 1 for
- * the preceeding error, which was a rasterization request on a 2D poly with less than
- * 3 sides.
- */
- if((edgbuf = (struct e_status *)(malloc(sizeof(struct e_status) * num_verts))) == NULL) {
- return(0);
- }
-
- /*
- * Do some preprocessing on all edges. This constructs a table structure in memory of all
- * the edge properties and can "flip" some edges so sorting works correctly.
- */
- preprocess_all_edges(ctx, verts, num_verts, edgbuf);
-
- /* can happen with a zero area mask */
- if (ctx->all_edges == NULL) {
- free(edgbuf);
- return(1);
- }
- /*
- * Set the pointer for tracking the edges currently in processing to NULL to make sure
- * we don't get some crazy value after initialization.
- */
- ctx->possible_edges = NULL;
-
- /*
- * Loop through all scan lines to be drawn. Since we sorted by Y values during
- * preprocess_all_edges(), we can already exact values for the lowest and
- * highest Y values we could possibly need by induction. The preprocessing sorted
- * out edges by Y position, we can cycle the current edge being processed once
- * it runs out of Y pixels. When we have no more edges, meaning the current edge
- * is NULL after setting the "current" edge to be the previous current edge's
- * "next" edge in the Y sorted edge connection chain, we can stop looping Y values,
- * since we can't possibly have more scan lines if we ran out of edges. :)
- *
- * TODO: This clips Y to the frame buffer, which should be done in the preprocessor, but for now is done here.
- * Will get changed once DEM code gets in.
- */
- for(y_curr = ctx->all_edges->ybeg; (ctx->all_edges || ctx->possible_edges); y_curr++) {
-
- /*
- * Link any edges that start on the current scan line into the list of
- * edges currently needed to draw at least this, if not several, scan lines.
- */
-
- /*
- * Set the current edge to the beginning of the list of edges to be rasterized
- * into this scan line.
- *
- * We could have lots of edge here, so iterate over all the edges needed. The
- * preprocess_all_edges() function sorted edges by X within each chunk of Y sorting
- * so we safely cycle edges to thier own "next" edges in order.
- *
- * At each iteration, make sure we still have a non-NULL edge.
- */
- for(edgec = &ctx->possible_edges; ctx->all_edges && (ctx->all_edges->ybeg == y_curr);) {
- x_curr = ctx->all_edges->x; /* Set current X position. */
- for(;;) { /* Start looping edges. Will break when edges run out. */
- e_curr = *edgec; /* Set up a current edge pointer. */
- if(!e_curr || (e_curr->x >= x_curr)) { /* If we have an no edge, or we need to skip some X-span, */
- e_temp = ctx->all_edges->e_next; /* set a temp "next" edge to test. */
- *edgec = ctx->all_edges; /* Add this edge to the list to be scanned. */
- ctx->all_edges->e_next = e_curr; /* Set up the next edge. */
- edgec = &ctx->all_edges->e_next; /* Set our list to the next edge's location in memory. */
- ctx->all_edges = e_temp; /* Skip the NULL or bad X edge, set pointer to next edge. */
- break; /* Stop looping edges (since we ran out or hit empty X span. */
- } else {
- edgec = &e_curr->e_next; /* Set the pointer to the edge list the "next" edge. */
- }
- }
- }
-
- /*
- * Determine the current scan line's offset in the pixel buffer based on its Y position.
- * Basically we just multiply the current scan line's Y value by the number of pixels in each line.
- */
- yp = y_curr * ctx->rb.sizex;
- /*
- * Set a "scan line pointer" in memory. The location of the buffer plus the row offset.
- */
- spxl = ctx->rb.buf + (yp);
- /*
- * Set up the current edge to the first (in X) edge. The edges which could possibly be in this
- * list were determined in the preceeding edge loop above. They were already sorted in X by the
- * initial processing function.
- *
- * At each iteration, test for a NULL edge. Since we'll keep cycling edge's to their own "next" edge
- * we will eventually hit a NULL when the list runs out.
- */
- for(e_curr = ctx->possible_edges; e_curr; e_curr = e_curr->e_next) {
- /*
- * Calculate a span of pixels to fill on the current scan line.
- *
- * Set the current pixel pointer by adding the X offset to the scan line's start offset.
- * Cycle the current edge the next edge.
- * Set the max X value to draw to be one less than the next edge's first pixel. This way we are
- * sure not to ever get into a situation where we have overdraw. (drawing the same pixel more than
- * one time because it's on a vertex connecting two edges)
- *
- * Then blast through all the pixels in the span, advancing the pointer and setting the color to white.
- *
- * TODO: Here we clip to the scan line, this is not efficient, and should be done in the preprocessor,
- * but for now it is done here until the DEM code comes in.
- */
-
- /* set up xmin and xmax bounds on this scan line */
- cpxl = spxl + MAX2(e_curr->x, 0);
- e_curr = e_curr->e_next;
- mpxl = spxl + MIN2(e_curr->x, ctx->rb.sizex) - 1;
-
- if((y_curr >= 0) && (y_curr < ctx->rb.sizey)) {
- /* draw the pixels. */
- for(; cpxl <= mpxl; *cpxl++ += intensity);
- }
- }
-
- /*
- * Loop through all edges of polygon that could be hit by this scan line,
- * and figure out their x-intersections with the next scan line.
- *
- * Either A.) we wont have any more edges to test, or B.) we just add on the
- * slope delta computed in preprocessing step. Since this draws non-antialiased
- * polygons, we dont have fractional positions, so we only move in x-direction
- * when needed to get all the way to the next pixel over...
- */
- for(edgec = &ctx->possible_edges; (e_curr = *edgec);) {
- if(!(--(e_curr->num))) {
- *edgec = e_curr->e_next;
- } else {
- e_curr->x += e_curr->xshift;
- if((e_curr->drift += e_curr->drift_inc) > 0) {
- e_curr->x += e_curr->xdir;
- e_curr->drift -= e_curr->drift_dec;
- }
- edgec = &e_curr->e_next;
- }
- }
- /*
- * It's possible that some edges may have crossed during the last step, so we'll be sure
- * that we ALWAYS intersect scan lines in order by shuffling if needed to make all edges
- * sorted by x-intersection coordinate. We'll always scan through at least once to see if
- * edges crossed, and if so, we set the 'swixd' flag. If 'swixd' gets set on the initial
- * pass, then we know we need to sort by x, so then cycle through edges again and perform
- * the sort.-
- */
- if(ctx->possible_edges) {
- for(edgec = &ctx->possible_edges; (e_curr = *edgec)->e_next; edgec = &(*edgec)->e_next) {
- /* if the current edge hits scan line at greater X than the next edge, we need to exchange the edges */
- if(e_curr->x > e_curr->e_next->x) {
- *edgec = e_curr->e_next;
- /* exchange the pointers */
- e_temp = e_curr->e_next->e_next;
- e_curr->e_next->e_next = e_curr;
- e_curr->e_next = e_temp;
- /* set flag that we had at least one switch */
- swixd = 1;
- }
- }
- /* if we did have a switch, look for more (there will more if there was one) */
- for(;;) {
- /* reset exchange flag so it's only set if we encounter another one */
- swixd = 0;
- for(edgec = &ctx->possible_edges; (e_curr = *edgec)->e_next; edgec = &(*edgec)->e_next) {
- /* again, if current edge hits scan line at higher X than next edge, exchange the edges and set flag */
- if(e_curr->x > e_curr->e_next->x) {
- *edgec = e_curr->e_next;
- /* exchange the pointers */
- e_temp = e_curr->e_next->e_next;
- e_curr->e_next->e_next = e_curr;
- e_curr->e_next = e_temp;
- /* flip the exchanged flag */
- swixd = 1;
- }
- }
- /* if we had no exchanges, we're done reshuffling the pointers */
- if(!swixd) {
- break;
- }
- }
- }
- }
-
- free(edgbuf);
- return 1;
+static int rast_scan_fill(struct r_FillContext *ctx, struct PolyVert *verts, int num_verts, float intensity)
+{
+ int x_curr; /* current pixel position in X */
+ int y_curr; /* current scan line being drawn */
+ int yp; /* y-pixel's position in frame buffer */
+ int swixd = 0; /* whether or not edges switched position in X */
+ float *cpxl; /* pixel pointers... */
+ float *mpxl;
+ float *spxl;
+ struct e_Status *e_curr; /* edge pointers... */
+ struct e_Status *e_temp;
+ struct e_Status *edgbuf;
+ struct e_Status **edgec;
+
+
+ /*
+ * If the number of verts specified to render as a polygon is less than 3,
+ * return immediately. Obviously we cant render a poly with sides < 3. The
+ * return for this we set to 1, simply so it can be distinguished from the
+ * next place we could return, /home/guest/blender-svn/soc-2011-tomato/intern/raskter/raskter.
+ * which is a failure to allocate memory.
+ */
+ if (num_verts < 3) {
+ return(1);
+ }
+
+ /*
+ * Try to allocate an edge buffer in memory. needs to be the size of the edge tracking data
+ * multiplied by the number of edges, which is always equal to the number of verts in
+ * a 2D polygon. Here we return 0 to indicate a memory allocation failure, as opposed to a 1 for
+ * the preceeding error, which was a rasterization request on a 2D poly with less than
+ * 3 sides.
+ */
+ if ((edgbuf = (struct e_Status *)(malloc(sizeof(struct e_Status) * num_verts))) == NULL) {
+ return(0);
+ }
+
+ /*
+ * Do some preprocessing on all edges. This constructs a table structure in memory of all
+ * the edge properties and can "flip" some edges so sorting works correctly.
+ */
+ preprocess_all_edges(ctx, verts, num_verts, edgbuf);
+
+ /* can happen with a zero area mask */
+ if (ctx->all_edges == NULL) {
+ free(edgbuf);
+ return(1);
+ }
+ /*
+ * Set the pointer for tracking the edges currently in processing to NULL to make sure
+ * we don't get some crazy value after initialization.
+ */
+ ctx->possible_edges = NULL;
+
+ /*
+ * Loop through all scan lines to be drawn. Since we sorted by Y values during
+ * preprocess_all_edges(), we can already exact values for the lowest and
+ * highest Y values we could possibly need by induction. The preprocessing sorted
+ * out edges by Y position, we can cycle the current edge being processed once
+ * it runs out of Y pixels. When we have no more edges, meaning the current edge
+ * is NULL after setting the "current" edge to be the previous current edge's
+ * "next" edge in the Y sorted edge connection chain, we can stop looping Y values,
+ * since we can't possibly have more scan lines if we ran out of edges. :)
+ *
+ * TODO: This clips Y to the frame buffer, which should be done in the preprocessor, but for now is done here.
+ * Will get changed once DEM code gets in.
+ */
+ for (y_curr = ctx->all_edges->ybeg; (ctx->all_edges || ctx->possible_edges); y_curr++) {
+
+ /*
+ * Link any edges that start on the current scan line into the list of
+ * edges currently needed to draw at least this, if not several, scan lines.
+ */
+
+ /*
+ * Set the current edge to the beginning of the list of edges to be rasterized
+ * into this scan line.
+ *
+ * We could have lots of edge here, so iterate over all the edges needed. The
+ * preprocess_all_edges() function sorted edges by X within each chunk of Y sorting
+ * so we safely cycle edges to thier own "next" edges in order.
+ *
+ * At each iteration, make sure we still have a non-NULL edge.
+ */
+ for (edgec = &ctx->possible_edges; ctx->all_edges && (ctx->all_edges->ybeg == y_curr);) {
+ x_curr = ctx->all_edges->x; /* Set current X position. */
+ for (;;) { /* Start looping edges. Will break when edges run out. */
+ e_curr = *edgec; /* Set up a current edge pointer. */
+ if (!e_curr || (e_curr->x >= x_curr)) { /* If we have an no edge, or we need to skip some X-span, */
+ e_temp = ctx->all_edges->e_next; /* set a temp "next" edge to test. */
+ *edgec = ctx->all_edges; /* Add this edge to the list to be scanned. */
+ ctx->all_edges->e_next = e_curr; /* Set up the next edge. */
+ edgec = &ctx->all_edges->e_next; /* Set our list to the next edge's location in memory. */
+ ctx->all_edges = e_temp; /* Skip the NULL or bad X edge, set pointer to next edge. */
+ break; /* Stop looping edges (since we ran out or hit empty X span. */
+ }
+ else {
+ edgec = &e_curr->e_next; /* Set the pointer to the edge list the "next" edge. */
+ }
+ }
+ }
+
+ /*
+ * Determine the current scan line's offset in the pixel buffer based on its Y position.
+ * Basically we just multiply the current scan line's Y value by the number of pixels in each line.
+ */
+ yp = y_curr * ctx->rb.sizex;
+ /*
+ * Set a "scan line pointer" in memory. The location of the buffer plus the row offset.
+ */
+ spxl = ctx->rb.buf + (yp);
+ /*
+ * Set up the current edge to the first (in X) edge. The edges which could possibly be in this
+ * list were determined in the preceeding edge loop above. They were already sorted in X by the
+ * initial processing function.
+ *
+ * At each iteration, test for a NULL edge. Since we'll keep cycling edge's to their own "next" edge
+ * we will eventually hit a NULL when the list runs out.
+ */
+ for (e_curr = ctx->possible_edges; e_curr; e_curr = e_curr->e_next) {
+ /*
+ * Calculate a span of pixels to fill on the current scan line.
+ *
+ * Set the current pixel pointer by adding the X offset to the scan line's start offset.
+ * Cycle the current edge the next edge.
+ * Set the max X value to draw to be one less than the next edge's first pixel. This way we are
+ * sure not to ever get into a situation where we have overdraw. (drawing the same pixel more than
+ * one time because it's on a vertex connecting two edges)
+ *
+ * Then blast through all the pixels in the span, advancing the pointer and setting the color to white.
+ *
+ * TODO: Here we clip to the scan line, this is not efficient, and should be done in the preprocessor,
+ * but for now it is done here until the DEM code comes in.
+ */
+
+ /* set up xmin and xmax bounds on this scan line */
+ cpxl = spxl + MAX2(e_curr->x, 0);
+ e_curr = e_curr->e_next;
+ mpxl = spxl + MIN2(e_curr->x, ctx->rb.sizex) - 1;
+
+ if ((y_curr >= 0) && (y_curr < ctx->rb.sizey)) {
+ /* draw the pixels. */
+ for (; cpxl <= mpxl; *cpxl++ += intensity) {}
+ }
+ }
+
+ /*
+ * Loop through all edges of polygon that could be hit by this scan line,
+ * and figure out their x-intersections with the next scan line.
+ *
+ * Either A.) we wont have any more edges to test, or B.) we just add on the
+ * slope delta computed in preprocessing step. Since this draws non-antialiased
+ * polygons, we dont have fractional positions, so we only move in x-direction
+ * when needed to get all the way to the next pixel over...
+ */
+ for (edgec = &ctx->possible_edges; (e_curr = *edgec);) {
+ if (!(--(e_curr->num))) {
+ *edgec = e_curr->e_next;
+ }
+ else {
+ e_curr->x += e_curr->xshift;
+ if ((e_curr->drift += e_curr->drift_inc) > 0) {
+ e_curr->x += e_curr->xdir;
+ e_curr->drift -= e_curr->drift_dec;
+ }
+ edgec = &e_curr->e_next;
+ }
+ }
+ /*
+ * It's possible that some edges may have crossed during the last step, so we'll be sure
+ * that we ALWAYS intersect scan lines in order by shuffling if needed to make all edges
+ * sorted by x-intersection coordinate. We'll always scan through at least once to see if
+ * edges crossed, and if so, we set the 'swixd' flag. If 'swixd' gets set on the initial
+ * pass, then we know we need to sort by x, so then cycle through edges again and perform
+ * the sort.-
+ */
+ if (ctx->possible_edges) {
+ for (edgec = &ctx->possible_edges; (e_curr = *edgec)->e_next; edgec = &(*edgec)->e_next) {
+ /* if the current edge hits scan line at greater X than the next edge, we need to exchange the edges */
+ if (e_curr->x > e_curr->e_next->x) {
+ *edgec = e_curr->e_next;
+ /* exchange the pointers */
+ e_temp = e_curr->e_next->e_next;
+ e_curr->e_next->e_next = e_curr;
+ e_curr->e_next = e_temp;
+ /* set flag that we had at least one switch */
+ swixd = 1;
+ }
+ }
+ /* if we did have a switch, look for more (there will more if there was one) */
+ for (;;) {
+ /* reset exchange flag so it's only set if we encounter another one */
+ swixd = 0;
+ for (edgec = &ctx->possible_edges; (e_curr = *edgec)->e_next; edgec = &(*edgec)->e_next) {
+ /* again, if current edge hits scan line at higher X than next edge, exchange the edges and set flag */
+ if (e_curr->x > e_curr->e_next->x) {
+ *edgec = e_curr->e_next;
+ /* exchange the pointers */
+ e_temp = e_curr->e_next->e_next;
+ e_curr->e_next->e_next = e_curr;
+ e_curr->e_next = e_temp;
+ /* flip the exchanged flag */
+ swixd = 1;
+ }
+ }
+ /* if we had no exchanges, we're done reshuffling the pointers */
+ if (!swixd) {
+ break;
+ }
+ }
+ }
+ }
+
+ free(edgbuf);
+ return 1;
}
int PLX_raskterize(float(*base_verts)[2], int num_base_verts,
- float *buf, int buf_x, int buf_y, int do_mask_AA) {
- int subdiv_AA = (do_mask_AA != 0)? 0:0;
- int i; /* i: Loop counter. */
- int sAx;
- int sAy;
- struct poly_vert *ply; /* ply: Pointer to a list of integer buffer-space vertex coordinates. */
- struct r_fill_context ctx = {0};
- const float buf_x_f = (float)(buf_x);
- const float buf_y_f = (float)(buf_y);
- float div_offset=(1.0f / (float)(subdiv_AA));
- float div_offset_static = 0.5f * (float)(subdiv_AA) * div_offset;
- /*
- * Allocate enough memory for our poly_vert list. It'll be the size of the poly_vert
- * data structure multiplied by the number of base_verts.
- *
- * In the event of a failure to allocate the memory, return 0, so this error can
- * be distinguished as a memory allocation error.
- */
- if((ply = (struct poly_vert *)(malloc(sizeof(struct poly_vert) * num_base_verts))) == NULL) {
- return(0);
- }
-
- ctx.rb.buf = buf; /* Set the output buffer pointer. */
- ctx.rb.sizex = buf_x; /* Set the output buffer size in X. (width) */
- ctx.rb.sizey = buf_y; /* Set the output buffer size in Y. (height) */
- /*
- * Loop over all verts passed in to be rasterized. Each vertex's X and Y coordinates are
- * then converted from normalized screen space (0.0 <= POS <= 1.0) to integer coordinates
- * in the buffer-space coordinates passed in inside buf_x and buf_y.
- *
- * It's worth noting that this function ONLY outputs fully white pixels in a mask. Every pixel
- * drawn will be 1.0f in value, there is no anti-aliasing.
- */
-
- if(!subdiv_AA) {
- for(i = 0; i < num_base_verts; i++) { /* Loop over all base_verts. */
- ply[i].x = (int)((base_verts[i][0] * buf_x_f) + 0.5f); /* Range expand normalized X to integer buffer-space X. */
- ply[i].y = (int)((base_verts[i][1] * buf_y_f) + 0.5f); /* Range expand normalized Y to integer buffer-space Y. */
- }
-
- i = rast_scan_fill(&ctx, ply, num_base_verts,1.0f); /* Call our rasterizer, passing in the integer coords for each vert. */
- } else {
- for(sAx=0; sAx < subdiv_AA; sAx++) {
- for(sAy=0; sAy < subdiv_AA; sAy++) {
- for(i=0; i < num_base_verts; i++) {
- ply[i].x = (int)((base_verts[i][0]*buf_x_f)+0.5f - div_offset_static + (div_offset*(float)(sAx)));
- ply[i].y = (int)((base_verts[i][1]*buf_y_f)+0.5f - div_offset_static + (div_offset*(float)(sAy)));
- }
- i = rast_scan_fill(&ctx, ply, num_base_verts,(1.0f / (float)(subdiv_AA*subdiv_AA)));
- }
- }
- }
- free(ply); /* Free the memory allocated for the integer coordinate table. */
- return(i); /* Return the value returned by the rasterizer. */
-}
-
-/*
- * This function clips drawing to the frame buffer. That clipping will likely be moved into the preprocessor
- * for speed, but waiting on final design choices for curve-data before eliminating data the DEM code will need
- * if it ends up being coupled with this function.
- */
-static int rast_scan_feather(struct r_fill_context *ctx,
- float(*base_verts_f)[2], int num_base_verts,
- struct poly_vert *feather_verts, float(*feather_verts_f)[2], int num_feather_verts) {
- int x_curr; /* current pixel position in X */
- int y_curr; /* current scan line being drawn */
- int yp; /* y-pixel's position in frame buffer */
- int swixd = 0; /* whether or not edges switched position in X */
- float *cpxl; /* pixel pointers... */
- float *mpxl;
- float *spxl;
- struct e_status *e_curr; /* edge pointers... */
- struct e_status *e_temp;
- struct e_status *edgbuf;
- struct e_status **edgec;
-
- /* from dem */
- int a; // a = temporary pixel index buffer loop counter
- float fsz; // size of the frame
- unsigned int rsl; // long used for finding fast 1.0/sqrt
- float rsf; // float used for finding fast 1.0/sqrt
- const float rsopf = 1.5f; // constant float used for finding fast 1.0/sqrt
-
- //unsigned int gradientFillOffset;
- float t;
- float ud; // ud = unscaled edge distance
- float dmin; // dmin = minimum edge distance
- float odist; // odist = current outer edge distance
- float idist; // idist = current inner edge distance
- float dx; // dx = X-delta (used for distance proportion calculation)
- float dy; // dy = Y-delta (used for distance proportion calculation)
- float xpxw = (1.0f / (float)(ctx->rb.sizex)); // xpxw = normalized pixel width
- float ypxh = (1.0f / (float)(ctx->rb.sizey)); // ypxh = normalized pixel height
-#ifdef __PLX_KD_TREE__
- void *res_kdi;
- void *res_kdo;
- float clup[2];
-#endif
-
- /*
- * If the number of verts specified to render as a polygon is less than 3,
- * return immediately. Obviously we cant render a poly with sides < 3. The
- * return for this we set to 1, simply so it can be distinguished from the
- * next place we could return,
- * which is a failure to allocate memory.
- */
- if(num_feather_verts < 3) {
- return(1);
- }
-
- /*
- * Try to allocate an edge buffer in memory. needs to be the size of the edge tracking data
- * multiplied by the number of edges, which is always equal to the number of verts in
- * a 2D polygon. Here we return 0 to indicate a memory allocation failure, as opposed to a 1 for
- * the preceeding error, which was a rasterization request on a 2D poly with less than
- * 3 sides.
- */
- if((edgbuf = (struct e_status *)(malloc(sizeof(struct e_status) * num_feather_verts))) == NULL) {
- return(0);
- }
-
- /*
- * Do some preprocessing on all edges. This constructs a table structure in memory of all
- * the edge properties and can "flip" some edges so sorting works correctly.
- */
- preprocess_all_edges(ctx, feather_verts, num_feather_verts, edgbuf);
-
- /* can happen with a zero area mask */
- if (ctx->all_edges == NULL) {
- free(edgbuf);
- return(1);
- }
-
- /*
- * Set the pointer for tracking the edges currently in processing to NULL to make sure
- * we don't get some crazy value after initialization.
- */
- ctx->possible_edges = NULL;
-
- /*
- * Loop through all scan lines to be drawn. Since we sorted by Y values during
- * preprocess_all_edges(), we can already exact values for the lowest and
- * highest Y values we could possibly need by induction. The preprocessing sorted
- * out edges by Y position, we can cycle the current edge being processed once
- * it runs out of Y pixels. When we have no more edges, meaning the current edge
- * is NULL after setting the "current" edge to be the previous current edge's
- * "next" edge in the Y sorted edge connection chain, we can stop looping Y values,
- * since we can't possibly have more scan lines if we ran out of edges. :)
- *
- * TODO: This clips Y to the frame buffer, which should be done in the preprocessor, but for now is done here.
- * Will get changed once DEM code gets in.
- */
- for(y_curr = ctx->all_edges->ybeg; (ctx->all_edges || ctx->possible_edges); y_curr++) {
-
- /*
- * Link any edges that start on the current scan line into the list of
- * edges currently needed to draw at least this, if not several, scan lines.
- */
-
- /*
- * Set the current edge to the beginning of the list of edges to be rasterized
- * into this scan line.
- *
- * We could have lots of edge here, so iterate over all the edges needed. The
- * preprocess_all_edges() function sorted edges by X within each chunk of Y sorting
- * so we safely cycle edges to thier own "next" edges in order.
- *
- * At each iteration, make sure we still have a non-NULL edge.
- */
- for(edgec = &ctx->possible_edges; ctx->all_edges && (ctx->all_edges->ybeg == y_curr);) {
- x_curr = ctx->all_edges->x; /* Set current X position. */
- for(;;) { /* Start looping edges. Will break when edges run out. */
- e_curr = *edgec; /* Set up a current edge pointer. */
- if(!e_curr || (e_curr->x >= x_curr)) { /* If we have an no edge, or we need to skip some X-span, */
- e_temp = ctx->all_edges->e_next; /* set a temp "next" edge to test. */
- *edgec = ctx->all_edges; /* Add this edge to the list to be scanned. */
- ctx->all_edges->e_next = e_curr; /* Set up the next edge. */
- edgec = &ctx->all_edges->e_next; /* Set our list to the next edge's location in memory. */
- ctx->all_edges = e_temp; /* Skip the NULL or bad X edge, set pointer to next edge. */
- break; /* Stop looping edges (since we ran out or hit empty X span. */
- } else {
- edgec = &e_curr->e_next; /* Set the pointer to the edge list the "next" edge. */
- }
- }
- }
-
- /*
- * Determine the current scan line's offset in the pixel buffer based on its Y position.
- * Basically we just multiply the current scan line's Y value by the number of pixels in each line.
- */
- yp = y_curr * ctx->rb.sizex;
- /*
- * Set a "scan line pointer" in memory. The location of the buffer plus the row offset.
- */
- spxl = ctx->rb.buf + (yp);
- /*
- * Set up the current edge to the first (in X) edge. The edges which could possibly be in this
- * list were determined in the preceeding edge loop above. They were already sorted in X by the
- * initial processing function.
- *
- * At each iteration, test for a NULL edge. Since we'll keep cycling edge's to their own "next" edge
- * we will eventually hit a NULL when the list runs out.
- */
- for(e_curr = ctx->possible_edges; e_curr; e_curr = e_curr->e_next) {
- /*
- * Calculate a span of pixels to fill on the current scan line.
- *
- * Set the current pixel pointer by adding the X offset to the scan line's start offset.
- * Cycle the current edge the next edge.
- * Set the max X value to draw to be one less than the next edge's first pixel. This way we are
- * sure not to ever get into a situation where we have overdraw. (drawing the same pixel more than
- * one time because it's on a vertex connecting two edges)
- *
- * Then blast through all the pixels in the span, advancing the pointer and setting the color to white.
- *
- * TODO: Here we clip to the scan line, this is not efficient, and should be done in the preprocessor,
- * but for now it is done here until the DEM code comes in.
- */
-
- /* set up xmin and xmax bounds on this scan line */
- cpxl = spxl + MAX2(e_curr->x, 0);
- e_curr = e_curr->e_next;
- mpxl = spxl + MIN2(e_curr->x, ctx->rb.sizex) - 1;
-
- if((y_curr >= 0) && (y_curr < ctx->rb.sizey)) {
- t = ((float)((cpxl - spxl) % ctx->rb.sizex) + 0.5f) * xpxw;
- fsz = ((float)(y_curr) + 0.5f) * ypxh;
- /* draw the pixels. */
- for(; cpxl <= mpxl; cpxl++, t += xpxw) {
- //do feather check
- // first check that pixel isn't already full, and only operate if it is not
- if(*cpxl < 0.9999f) {
-#ifndef __PLX_KD_TREE__
- dmin = 2.0f; // reset min distance to edge pixel
- for(a = 0; a < num_feather_verts; a++) { // loop through all outer edge buffer pixels
- dx = t - feather_verts_f[a][0]; // set dx to gradient pixel column - outer edge pixel row
- dy = fsz - feather_verts_f[a][1]; // set dy to gradient pixel row - outer edge pixel column
- ud = dx * dx + dy * dy; // compute sum of squares
- if(ud < dmin) { // if our new sum of squares is less than the current minimum
- dmin = ud; // set a new minimum equal to the new lower value
- }
- }
- odist = dmin; // cast outer min to a float
- rsf = odist * 0.5f; //
- rsl = *(unsigned int *)&odist; // use some peculiar properties of the way bits are stored
- rsl = 0x5f3759df - (rsl >> 1); // in floats vs. unsigned ints to compute an approximate
- odist = *(float *)&rsl; // reciprocal square root
- odist = odist * (rsopf - (rsf * odist * odist)); // -- ** this line can be iterated for more accuracy ** --
- odist = odist * (rsopf - (rsf * odist * odist));
- dmin = 2.0f; // reset min distance to edge pixel
- for(a = 0; a < num_base_verts; a++) { // loop through all inside edge pixels
- dx = t - base_verts_f[a][0]; // compute delta in Y from gradient pixel to inside edge pixel
- dy = fsz - base_verts_f[a][1]; // compute delta in X from gradient pixel to inside edge pixel
- ud = dx * dx + dy * dy; // compute sum of squares
- if(ud < dmin) { // if our new sum of squares is less than the current minimum we've found
- dmin = ud; // set a new minimum equal to the new lower value
- }
- }
- idist = dmin; // cast inner min to a float
- rsf = idist * 0.5f; //
- rsl = *(unsigned int *)&idist; //
- rsl = 0x5f3759df - (rsl >> 1); // see notes above
- idist = *(float *)&rsl; //
- idist = idist * (rsopf - (rsf * idist * idist)); //
- idist = idist * (rsopf - (rsf * idist * idist));
- /*
- * Note once again that since we are using reciprocals of distance values our
- * proportion is already the correct intensity, and does not need to be
- * subtracted from 1.0 like it would have if we used real distances.
- */
-#else
- clup[0]=t;
- clup[1]=fsz;
- res_kdi=kd_nearestf(ctx->kdi,clup);
- res_kdo=kd_nearestf(ctx->kdo,clup);
- kd_res_itemf(res_kdi,clup);
- dx=t-clup[0];
- dy=fsz-clup[1];
- idist=dx*dx+dy*dy;
- rsf = idist * 0.5f; //
- rsl = *(unsigned int *)&idist; //
- rsl = 0x5f3759df - (rsl >> 1); // see notes above
- idist = *(float *)&rsl; //
- idist = idist * (rsopf - (rsf * idist * idist)); //
- idist = idist * (rsopf - (rsf * idist * idist));
- kd_res_itemf(res_kdo,clup);
- dx=t-clup[0];
- dy=fsz-clup[1];
- odist=dx*dx+dy*dy;
- rsf = odist * 0.5f; //
- rsl = *(unsigned int *)&odist; // use some peculiar properties of the way bits are stored
- rsl = 0x5f3759df - (rsl >> 1); // in floats vs. unsigned ints to compute an approximate
- odist = *(float *)&rsl; // reciprocal square root
- odist = odist * (rsopf - (rsf * odist * odist)); // -- ** this line can be iterated for more accuracy ** --
- odist = odist * (rsopf - (rsf * odist * odist));
-
-#endif
- /* set intensity, do the += so overlapping gradients are additive */
- *cpxl = (idist / (idist+odist));
- }
- }
- }
- }
-
- /*
- * Loop through all edges of polygon that could be hit by this scan line,
- * and figure out their x-intersections with the next scan line.
- *
- * Either A.) we wont have any more edges to test, or B.) we just add on the
- * slope delta computed in preprocessing step. Since this draws non-antialiased
- * polygons, we dont have fractional positions, so we only move in x-direction
- * when needed to get all the way to the next pixel over...
- */
- for(edgec = &ctx->possible_edges; (e_curr = *edgec);) {
- if(!(--(e_curr->num))) {
- *edgec = e_curr->e_next;
- } else {
- e_curr->x += e_curr->xshift;
- if((e_curr->drift += e_curr->drift_inc) > 0) {
- e_curr->x += e_curr->xdir;
- e_curr->drift -= e_curr->drift_dec;
- }
- edgec = &e_curr->e_next;
- }
- }
- /*
- * It's possible that some edges may have crossed during the last step, so we'll be sure
- * that we ALWAYS intersect scan lines in order by shuffling if needed to make all edges
- * sorted by x-intersection coordinate. We'll always scan through at least once to see if
- * edges crossed, and if so, we set the 'swixd' flag. If 'swixd' gets set on the initial
- * pass, then we know we need to sort by x, so then cycle through edges again and perform
- * the sort.-
- */
- if(ctx->possible_edges) {
- for(edgec = &ctx->possible_edges; (e_curr = *edgec)->e_next; edgec = &(*edgec)->e_next) {
- /* if the current edge hits scan line at greater X than the next edge, we need to exchange the edges */
- if(e_curr->x > e_curr->e_next->x) {
- *edgec = e_curr->e_next;
- /* exchange the pointers */
- e_temp = e_curr->e_next->e_next;
- e_curr->e_next->e_next = e_curr;
- e_curr->e_next = e_temp;
- /* set flag that we had at least one switch */
- swixd = 1;
- }
- }
- /* if we did have a switch, look for more (there will more if there was one) */
- for(;;) {
- /* reset exchange flag so it's only set if we encounter another one */
- swixd = 0;
- for(edgec = &ctx->possible_edges; (e_curr = *edgec)->e_next; edgec = &(*edgec)->e_next) {
- /* again, if current edge hits scan line at higher X than next edge,
- * exchange the edges and set flag */
- if(e_curr->x > e_curr->e_next->x) {
- *edgec = e_curr->e_next;
- /* exchange the pointers */
- e_temp = e_curr->e_next->e_next;
- e_curr->e_next->e_next = e_curr;
- e_curr->e_next = e_temp;
- /* flip the exchanged flag */
- swixd = 1;
- }
- }
- /* if we had no exchanges, we're done reshuffling the pointers */
- if(!swixd) {
- break;
- }
- }
- }
- }
-
- free(edgbuf);
- return 1;
+ float *buf, int buf_x, int buf_y)
+{
+ int i; /* i: Loop counter. */
+ struct PolyVert *ply; /* ply: Pointer to a list of integer buffer-space vertex coordinates. */
+ struct r_FillContext ctx = {0};
+ const float buf_x_f = (float)(buf_x);
+ const float buf_y_f = (float)(buf_y);
+ /*
+ * Allocate enough memory for our PolyVert list. It'll be the size of the PolyVert
+ * data structure multiplied by the number of base_verts.
+ *
+ * In the event of a failure to allocate the memory, return 0, so this error can
+ * be distinguished as a memory allocation error.
+ */
+ if ((ply = (struct PolyVert *)(malloc(sizeof(struct PolyVert) * num_base_verts))) == NULL) {
+ return(0);
+ }
+
+ ctx.rb.buf = buf; /* Set the output buffer pointer. */
+ ctx.rb.sizex = buf_x; /* Set the output buffer size in X. (width) */
+ ctx.rb.sizey = buf_y; /* Set the output buffer size in Y. (height) */
+ /*
+ * Loop over all verts passed in to be rasterized. Each vertex's X and Y coordinates are
+ * then converted from normalized screen space (0.0 <= POS <= 1.0) to integer coordinates
+ * in the buffer-space coordinates passed in inside buf_x and buf_y.
+ *
+ * It's worth noting that this function ONLY outputs fully white pixels in a mask. Every pixel
+ * drawn will be 1.0f in value, there is no anti-aliasing.
+ */
+
+ for (i = 0; i < num_base_verts; i++) { /* Loop over all base_verts. */
+ ply[i].x = (int)((base_verts[i][0] * buf_x_f) + 0.5f); /* Range expand normalized X to integer buffer-space X. */
+ ply[i].y = (int)((base_verts[i][1] * buf_y_f) + 0.5f); /* Range expand normalized Y to integer buffer-space Y. */
+ }
+
+ i = rast_scan_fill(&ctx, ply, num_base_verts,1.0f); /* Call our rasterizer, passing in the integer coords for each vert. */
+
+ free(ply); /* Free the memory allocated for the integer coordinate table. */
+ return(i); /* Return the value returned by the rasterizer. */
}
-
-int PLX_raskterize_feather(float(*base_verts)[2], int num_base_verts, float(*feather_verts)[2], int num_feather_verts,
- float *buf, int buf_x, int buf_y) {
- //void plx_floatsort(float(*f)[2], unsigned int n, int sortby);
- int i; /* i: Loop counter. */
- struct poly_vert *fe; /* fe: Pointer to a list of integer buffer-space feather vertex coords. */
- struct r_fill_context ctx = {0};
-
- /* for faster multiply */
- const float buf_x_f = (float)buf_x;
- const float buf_y_f = (float)buf_y;
-#ifdef __PLX_KD_TREE__
- ctx.kdi = kd_create(2);
- ctx.kdo = kd_create(2);
-#endif
- /*
- * Allocate enough memory for our poly_vert list. It'll be the size of the poly_vert
- * data structure multiplied by the number of verts.
- *
- * In the event of a failure to allocate the memory, return 0, so this error can
- * be distinguished as a memory allocation error.
- */
- if((fe = (struct poly_vert *)(malloc(sizeof(struct poly_vert) * num_feather_verts))) == NULL) {
- return(0);
- }
-
- /*
- * Loop over all verts passed in to be rasterized. Each vertex's X and Y coordinates are
- * then converted from normalized screen space (0.0 <= POS <= 1.0) to integer coordinates
- * in the buffer-space coordinates passed in inside buf_x and buf_y.
- *
- * It's worth noting that this function ONLY outputs fully white pixels in a mask. Every pixel
- * drawn will be 1.0f in value, there is no anti-aliasing.
- */
- for(i = 0; i < num_feather_verts; i++) { /* Loop over all verts. */
- fe[i].x = (int)((feather_verts[i][0] * buf_x_f) + 0.5f); /* Range expand normalized X to integer buffer-space X. */
- fe[i].y = (int)((feather_verts[i][1] * buf_y_f) + 0.5f); /* Range expand normalized Y to integer buffer-space Y. */
-#ifdef __PLX_KD_TREE__
- kd_insertf(ctx.kdo,feather_verts[i],NULL);
- }
- for(i=0;i<num_base_verts;i++){
- kd_insertf(ctx.kdi,base_verts[i],NULL);
-#endif
- }
-
- ctx.rb.buf = buf; /* Set the output buffer pointer. */
- ctx.rb.sizex = buf_x; /* Set the output buffer size in X. (width) */
- ctx.rb.sizey = buf_y; /* Set the output buffer size in Y. (height) */
- /* pre-sort the sets of edge verts on y */
- //plx_floatsort(base_verts,num_base_verts,0);
- //plx_floatsort(base_verts,num_base_verts,1);
- //plx_floatsort(feather_verts,num_feather_verts,0);
- //plx_floatsort(feather_verts,num_feather_verts,1);
- /* Call our rasterizer, passing in the integer coords for each vert. */
- i = rast_scan_feather(&ctx, base_verts, num_base_verts, fe, feather_verts, num_feather_verts);
- free(fe);
- return i; /* Return the value returned by the rasterizer. */
-}
-
-#ifndef __PLX__FAKE_AA__
-
-static int get_range_expanded_pixel_coord(float normalized_value, int max_value) {
- return (int)((normalized_value * (float)(max_value)) + 0.5f);
-}
-
-DO_INLINE float get_pixel_intensity(float *buf, int buf_x, int buf_y, int pos_x, int pos_y) {
- if(pos_x < 0 || pos_x >= buf_x || pos_y < 0 || pos_y >= buf_y) {
- return 0.0f;
- }
- return buf[(pos_y * buf_x) + pos_x];
-}
-
-DO_INLINE float get_pixel_intensity_bilinear(float *buf, int buf_x, int buf_y, float u, float v) {
- int a;
- int b;
- int a_plus_1;
- int b_plus_1;
- float prop_u;
- float prop_v;
- float inv_prop_u;
- float inv_prop_v;
- if(u<0.0f || u>1.0f || v<0.0f || v>1.0f) {
- return 0.0f;
- }
- u = u * (float)(buf_x) - 0.5f;
- v = v * (float)(buf_y) - 0.5f;
- a = (int)(u);
- b = (int)(v);
- prop_u = u - (float)(a);
- prop_v = v - (float)(b);
- inv_prop_u = 1.0f - prop_u;
- inv_prop_v = 1.0f - prop_v;
- a_plus_1 = MIN2((buf_x-1),a+1);
- b_plus_1 = MIN2((buf_y-1),b+1);
- return (buf[(b * buf_x) + a] * inv_prop_u + buf[(b*buf_x)+(a_plus_1)] * prop_u)*inv_prop_v+(buf[((b_plus_1) * buf_x)+a] * inv_prop_u + buf[((b_plus_1)*buf_x)+(a_plus_1)] * prop_u) * prop_v;
-
-}
-
-DO_INLINE void set_pixel_intensity(float *buf, int buf_x, int buf_y, int pos_x, int pos_y, float intensity) {
- if(pos_x < 0 || pos_x >= buf_x || pos_y < 0 || pos_y >= buf_y) {
- return;
- }
- buf[(pos_y * buf_x) + pos_x] = intensity;
-}
-#endif
-
-int PLX_antialias_buffer(float *buf, int buf_x, int buf_y) {
-#ifdef __PLX__FAKE_AA__
-#ifdef __PLX_GREY_AA__
- int i=0;
- int sz = buf_x * buf_y;
- for(i=0; i<sz; i++) {
- buf[i] *= 0.5f;
- }
-#endif
- (void)buf_x;
- (void)buf_y;
- (void)buf;
- return 1;
-#else
- const float jump01 = 1.0f;
- const float jump02 = 1.0f;
- const float jump03 = 1.0f;
- const float jump04 = 1.0f;
- const float jump05 = 1.0f;
- const float jump06 = 1.5f;
- const float jump07 = 2.0f;
- const float jump08 = 2.0f;
- const float jump09 = 2.0f;
- const float jump10 = 2.0f;
- const float jump11 = 4.0f;
- const float jump12 = 8.0f;
-
- const float edge_threshold = 0.063f;
- const float edge_threshold_min = 0.0312f;
- const float quality_subpix = 1.0f;
-
- float fpcx,fpcy;
- float fpsqx,fpsqy;
- float fprevx,fprevy;
- float fpfowx,fpfowy;
- float offset_dgx,offset_dgy;
- float pci;
- float pdi;
- float pri;
- float pui;
- float pli;
- float uli;
- float dri;
- float uri;
- float dli;
- float udi;
- float lri;
- float fsi;
- float ti;
- float cdi;
- float bi;
- float uui;
- float ddi;
- float eri;
- float efi;
- float cci;
- float ltz;
- float spX;
- float inv_r;
- float spP;
- float gdc;
- float sdc;
- float gedc;
- float sedc;
- float glu;
- float slu;
- float gr;
- float sr;
- float grexp;
- float r;
- float grc;
- float lre;
- float ude;
- float lre0;
- float ude0;
- float lre1;
- float ude1;
- float lre2;
- float ude2;
- float lre3;
- float ude3;
- float sdst;
- float tg0;
- float tg1;
- float tg2;
- float tg3;
- float tg4;
- float tg5;
- float tg6;
- float tg7;
- float ugrad;
- float dgrad;
- float grad;
- float gradexp;
- float revdst;
- float fowdst;
- float dst;
- float dsts;
- float inv_dsts;
- float pxOff;
- float gpxOff;
- float tgpxOff;
- float opx;
- float opy;
- int uls;
- int sph;
- int revsph;
- int fowsph;
- int lrsp;
- int done;
- int revpp;
- int revdone;
- int fowdone;
- int tug_of_war;
- int curr_x=0;
- int curr_y=0;
- opx = (1.0f / (float)(buf_x));
- opy = (1.0f / (float)(buf_y));
- for(curr_y=0; curr_y < buf_y; curr_y++) {
- for(curr_x=0; curr_x < buf_x; curr_x++) {
- fpcx = ((float)(curr_x) + 0.5f) * opx;
- fpcy = ((float)(curr_y) + 0.5f) * opy;
-//#define __PLX_BILINEAR_INITIAL_SAMPLES__ 1
-#ifdef __PLX_BILINEAR_INITIAL_SAMPLES__
- lumaM = get_pixel_intensity_bilinear(buf, buf_x, buf_y, posM_x, posM_y);
- lumaS = get_pixel_intensity_bilinear(buf, buf_x, buf_y, posM_x, posM_y + opy);
- lumaE = get_pixel_intensity_bilinear(buf, buf_x, buf_y, posM_x + opx, posM_y);
- lumaN = get_pixel_intensity_bilinear(buf, buf_x, buf_y, posM_x, posM_y - opy);
- lumaW = get_pixel_intensity_bilinear(buf, buf_x, buf_y, posM_x - opx, posM_y);
-#else
- pci = get_pixel_intensity(buf, buf_x, buf_y, curr_x, curr_y);
- pdi = get_pixel_intensity(buf, buf_x, buf_y, curr_x, curr_y + 1);
- pri = get_pixel_intensity(buf, buf_x, buf_y, curr_x + 1, curr_y);
- pui = get_pixel_intensity(buf, buf_x, buf_y, curr_x, curr_y - 1);
- pli = get_pixel_intensity(buf, buf_x, buf_y, curr_x - 1, curr_y);
-#endif
- gdc = MAX2(pdi, pci);
- sdc = MIN2(pdi, pci);
- gedc = MAX2(pri, gdc);
- sedc = MIN2(pri, sdc);
- glu = MAX2(pui, pli);
- slu = MIN2(pui, pli);
- gr = MAX2(glu, gedc);
- sr = MIN2(slu, sedc);
- grexp = gr * edge_threshold;
- r = gr - sr;
- grc = MAX2(edge_threshold_min, grexp);
-
- done = r < grc ? 1:0;
- if(done) {
- set_pixel_intensity(buf, buf_x, buf_y, curr_x, curr_y, pci);
- } else {
-
- uli = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpcx - opx, fpcy - opy);
- dri = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpcx + opx, fpcy + opy);
- uri = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpcx + opx, fpcy - opy);
- dli = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpcx - opx, fpcy + opy);
-
- udi = pui + pdi;
- lri = pli + pri;
- inv_r = 1.0f/r;
- spP = udi + lri;
- lre0 = (-2.0f * pci) + udi;
- ude0 = (-2.0f * pci) + lri;
-
- fsi = uri + dri;
- ti = uli + uri;
- lre1 = (-2.0f * pri) + fsi;
- ude1 = (-2.0f * pui) + ti;
-
- cdi = uli + dli;
- bi = dli + dri;
- lre3 = (ABS(lre0) * 2.0f) + ABS(lre1);
- ude3 = (ABS(ude0) * 2.0f) + ABS(ude1);
- lre2 = (-2.0f * pli) + cdi;
- ude2 = (-2.0f * pdi) + bi;
- lre = ABS(lre2) + lre3;
- ude = ABS(ude2) + ude3;
-
- spX = cdi + fsi;
- sdst = 1.0f / (float)(buf_x);
- lrsp = lre >= ude ? 1:0;
- tg0 = spP * 2.0f + spX;
-
- if(!lrsp) {
- pui = pli;
- pdi = pri;
- } else {
- sdst = 1.0f / (float)(buf_y);
- }
- tg1 = (tg0 * (1.0f/12.0f)) - pci;
-
- ugrad = pui - pci;
- dgrad = pdi - pci;
- uui = pui + pci;
- ddi = pdi + pci;
- revpp = (ABS(ugrad)) >= (ABS(dgrad)) ? 1:0;
- grad = MAX2(ABS(ugrad), ABS(dgrad));
- if(revpp) {
- sdst = -sdst;
- }
- tg2 = MAX2(MIN2(ABS(tg1) * inv_r,1.0f),0.0f);
-
- fpsqx = fpcx;
- fpsqy = fpcy;
- offset_dgx = (!lrsp) ? 0.0f:(1.0f / (float)(buf_x));
- offset_dgy = (lrsp) ? 0.0f:(1.0f / (float)(buf_y));
- if(!lrsp) {
- fpsqx += sdst * 0.5f;
- } else {
- fpsqy += sdst * 0.5f;
- }
-
- fprevx = fpsqx - offset_dgx * jump01;
- fprevy = fpsqy - offset_dgy * jump01;
- fpfowx = fpsqx + offset_dgx * jump01;
- fpfowy = fpsqy + offset_dgy * jump01;
- tg3 = ((-2.0f)*tg2) + 3.0f;
- eri = get_pixel_intensity_bilinear(buf, buf_x, buf_y,fprevx,fprevy);
- tg4 = tg2 * tg2;
- efi = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpfowx,fpfowy);
-
- if(!revpp) {
- uui = ddi;
- }
- gradexp = grad * 1.0f/4.0f;
- cci =pci - uui * 0.5f;
- tg5 = tg3 * tg4;
- ltz = cci < 0.0f ? 1:0;
-
- eri -= uui * 0.5f;
- efi -= uui * 0.5f;
- revdone = (ABS(eri)) >= gradexp ? 1:0;
- fowdone = (ABS(efi)) >= gradexp ? 1:0;
- if(!revdone) {
- fprevx -= offset_dgx * jump02;
- fprevy -= offset_dgy * jump02;
- }
- tug_of_war = (!revdone) || (!fowdone) ? 1:0;
- if(!fowdone) {
- fpfowx += offset_dgx * jump02;
- fpfowy += offset_dgy * jump02;
- }
-
- if(tug_of_war) {
- if(!revdone) {
- eri = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fprevx,fprevy);
- }
- if(!fowdone) {
- efi = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpfowx, fpfowy);
- }
- if(!revdone) {
- eri = eri - uui * 0.5;
- }
- if(!fowdone) {
- efi = efi - uui * 0.5;
- }
- revdone = (ABS(eri)) >= gradexp ? 1:0;
- fowdone = (ABS(efi)) >= gradexp ? 1:0;
- if(!revdone) {
- fprevx -= offset_dgx * jump03;
- fprevy -= offset_dgy * jump03;
- }
- tug_of_war = (!revdone) || (!fowdone) ? 1:0;
- if(!fowdone) {
- fpfowx += offset_dgx * jump03;
- fpfowy += offset_dgy * jump03;
- }
- if(tug_of_war) {
- if(!revdone) {
- eri = get_pixel_intensity_bilinear(buf, buf_x, buf_y,fprevx,fprevy);
- }
- if(!fowdone) {
- efi = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpfowx,fpfowy);
- }
- if(!revdone) {
- eri = eri - uui * 0.5;
- }
- if(!fowdone) {
- efi = efi - uui * 0.5;
- }
- revdone = (ABS(eri)) >= gradexp ? 1:0;
- fowdone = (ABS(efi)) >= gradexp ? 1:0;
- if(!revdone) {
- fprevx -= offset_dgx * jump04;
- fprevy -= offset_dgy * jump04;
- }
- tug_of_war = (!revdone) || (!fowdone) ? 1:0;
- if(!fowdone) {
- fpfowx += offset_dgx * jump04;
- fpfowy += offset_dgy * jump04;
- }
- if(tug_of_war) {
- if(!revdone) {
- eri = get_pixel_intensity_bilinear(buf, buf_x, buf_y,fprevx,fprevy);
- }
- if(!fowdone) {
- efi = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpfowx,fpfowy);
- }
- if(!revdone) {
- eri = eri - uui * 0.5;
- }
- if(!fowdone) {
- efi = efi - uui * 0.5;
- }
- revdone = (ABS(eri)) >= gradexp ? 1:0;
- fowdone = (ABS(efi)) >= gradexp ? 1:0;
- if(!revdone) {
- fprevx -= offset_dgx * jump05;
- fprevy -= offset_dgy * jump05;
- }
- tug_of_war = (!revdone) || (!fowdone) ? 1:0;
- if(!fowdone) {
- fpfowx += offset_dgx * jump05;
- fpfowy += offset_dgy * jump05;
- }
- if(tug_of_war) {
- if(!revdone) {
- eri = get_pixel_intensity_bilinear(buf, buf_x, buf_y,fprevx,fprevy);
- }
- if(!fowdone) {
- efi = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpfowx,fpfowy);
- }
- if(!revdone) {
- eri = eri - uui * 0.5;
- }
- if(!fowdone) {
- efi = efi - uui * 0.5;
- }
- revdone = (ABS(eri)) >= gradexp ? 1:0;
- fowdone = (ABS(efi)) >= gradexp ? 1:0;
- if(!revdone) {
- fprevx -= offset_dgx * jump06;
- fprevy -= offset_dgy * jump06;
- }
- tug_of_war = (!revdone) || (!fowdone) ? 1:0;
- if(!fowdone) {
- fpfowx += offset_dgx * jump06;
- fpfowy += offset_dgy * jump06;
- }
- if(tug_of_war) {
- if(!revdone) {
- eri = get_pixel_intensity_bilinear(buf, buf_x, buf_y,fprevx,fprevy);
- }
- if(!fowdone) {
- efi = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpfowx,fpfowy);
- }
- if(!revdone) {
- eri = eri - uui * 0.5;
- }
- if(!fowdone) {
- efi = efi - uui * 0.5;
- }
- revdone = (ABS(eri)) >= gradexp ? 1:0;
- fowdone = (ABS(efi)) >= gradexp ? 1:0;
- if(!revdone) {
- fprevx -= offset_dgx * jump07;
- fprevy -= offset_dgy * jump07;
- }
- tug_of_war = (!revdone) || (!fowdone) ? 1:0;
- if(!fowdone) {
- fpfowx += offset_dgx * jump07;
- fpfowy += offset_dgy * jump07;
- }
- if(tug_of_war) {
- if(!revdone) {
- eri = get_pixel_intensity_bilinear(buf, buf_x, buf_y,fprevx,fprevy);
- }
- if(!fowdone) {
- efi = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpfowx,fpfowy);
- }
- if(!revdone) {
- eri = eri - uui * 0.5;
- }
- if(!fowdone) {
- efi = efi - uui * 0.5;
- }
- revdone = (ABS(eri)) >= gradexp ? 1:0;
- fowdone = (ABS(efi)) >= gradexp ? 1:0;
- if(!revdone) {
- fprevx -= offset_dgx * jump08;
- fprevy -= offset_dgy * jump08;
- }
- tug_of_war = (!revdone) || (!fowdone) ? 1:0;
- if(!fowdone) {
- fpfowx += offset_dgx * jump08;
- fpfowy += offset_dgy * jump08;
- }
- if(tug_of_war) {
- if(!revdone) {
- eri = get_pixel_intensity_bilinear(buf, buf_x, buf_y,fprevx,fprevy);
- }
- if(!fowdone) {
- efi = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpfowx,fpfowy);
- }
- if(!revdone) {
- eri = eri - uui * 0.5;
- }
- if(!fowdone) {
- efi = efi - uui * 0.5;
- }
- revdone = (ABS(eri)) >= gradexp ? 1:0;
- fowdone = (ABS(efi)) >= gradexp ? 1:0;
- if(!revdone) {
- fprevx -= offset_dgx * jump09;
- fprevy -= offset_dgy * jump09;
- }
- tug_of_war = (!revdone) || (!fowdone) ? 1:0;
- if(!fowdone) {
- fpfowx += offset_dgx * jump09;
- fpfowy += offset_dgy * jump09;
- }
- if(tug_of_war) {
- if(!revdone) {
- eri = get_pixel_intensity_bilinear(buf, buf_x, buf_y,fprevx,fprevy);
- }
- if(!fowdone) {
- efi = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpfowx,fpfowy);
- }
- if(!revdone) {
- eri = eri - uui * 0.5;
- }
- if(!fowdone) {
- efi = efi - uui * 0.5;
- }
- revdone = (ABS(eri)) >= gradexp ? 1:0;
- fowdone = (ABS(efi)) >= gradexp ? 1:0;
- if(!revdone) {
- fprevx -= offset_dgx * jump10;
- fprevy -= offset_dgy * jump10;
- }
- tug_of_war = (!revdone) || (!fowdone) ? 1:0;
- if(!fowdone) {
- fpfowx += offset_dgx * jump10;
- fpfowy += offset_dgy * jump10;
- }
- if(tug_of_war) {
- if(!revdone) {
- eri = get_pixel_intensity_bilinear(buf, buf_x, buf_y,fprevx,fprevy);
- }
- if(!fowdone) {
- efi = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpfowx,fpfowy);
- }
- if(!revdone) {
- eri = eri - uui * 0.5;
- }
- if(!fowdone) {
- efi = efi - uui * 0.5;
- }
- revdone = (ABS(eri)) >= gradexp ? 1:0;
- fowdone = (ABS(efi)) >= gradexp ? 1:0;
- if(!revdone) {
- fprevx -= offset_dgx * jump11;
- fprevy -= offset_dgy * jump11;
- }
- tug_of_war = (!revdone) || (!fowdone) ? 1:0;
- if(!fowdone) {
- fpfowx += offset_dgx * jump11;
- fpfowy += offset_dgy * jump11;
- }
- if(tug_of_war) {
- if(!revdone) {
- eri = get_pixel_intensity_bilinear(buf, buf_x, buf_y,fprevx,fprevy);
- }
- if(!fowdone) {
- efi = get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpfowx,fpfowy);
- }
- if(!revdone) {
- eri = eri - uui * 0.5;
- }
- if(!fowdone) {
- efi = efi - uui * 0.5;
- }
- revdone = (ABS(eri)) >= gradexp ? 1:0;
- fowdone = (ABS(efi)) >= gradexp ? 1:0;
- if(!revdone) {
- fprevx -= offset_dgx * jump12;
- fprevy -= offset_dgy * jump12;
- }
- tug_of_war = (!revdone) || (!fowdone) ? 1:0;
- if(!fowdone) {
- fpfowx += offset_dgx * jump12;
- fpfowy += offset_dgy * jump12;
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- revdst = fpcx - fprevx;
- fowdst = fpfowx - fpcx;
- if(!lrsp) {
- revdst = fpcy - fprevy;
- fowdst = fpfowy - fpcy;
- }
-
- revsph = ((eri < 0.0f) ? 1:0) != ltz ? 1:0;
- dsts = (fowdst + revdst);
- fowsph = ((efi < 0.0f) ? 1:0) != ltz ? 1:0;
- inv_dsts = 1.0f/dsts;
-
- uls = revdst < fowdst ? 1:0;
- dst = MIN2(revdst, fowdst);
- sph = (uls==1) ? revsph:fowsph;
- tg6 = tg5 * tg5;
- pxOff = (dst * (-inv_dsts)) + 0.5f;
- tg7 = tg6 * quality_subpix;
-
- gpxOff = (sph==1) ? pxOff : 0.0f;
- tgpxOff = MAX2(gpxOff, tg7);
- if(!lrsp) {
- fpcx += tgpxOff * sdst;
- } else {
- fpcy += tgpxOff * sdst;
- }
- set_pixel_intensity(buf,buf_x,buf_y,curr_x,curr_y,get_pixel_intensity_bilinear(buf, buf_x, buf_y, fpcx,fpcy));
- }
- }
- }
- return 1;
-
-#endif
-}
-
-#define SWAP_POLYVERT(a,b) point_temp[0]=(a)[0]; point_temp[1]=(a)[1]; (a)[0]=(b)[0]; (a)[1]=(b)[1]; (b)[0]=point_temp[0]; (b)[1]=point_temp[1];
-#define __PLX_SMALL_COUNT__ 13
-static void plx_floatsort(float(*f)[2], unsigned int n, int sortby) {
- unsigned int a;
- unsigned int b;
- unsigned int c;
- unsigned int d=1;
- unsigned int hold;
- unsigned int index_list[50];
- int index_offset=0;
- float t[2];
- float point_temp[2];
-
- hold=n;
- for(;;) {
- if(hold-d < __PLX_SMALL_COUNT__) {
- for(b=d+1; b<=hold; b++) {
- t[1]=f[b][1];
- t[0]=f[b][0];
- for(a=b-1; a>=d; a--) {
- if(f[a][sortby] <= t[sortby]) {
- break;
- }
- f[a+1][1]=f[a][1];
- f[a+1][0]=f[a][0];
- }
- f[a+1][1]=t[1];
- f[a+1][0]=t[0];
- }
- if(index_offset < 0) {
- break;
- }
- hold=index_list[index_offset--];
- d=index_list[index_offset--];
- } else {
- c=(d+hold) >> 1;
- SWAP_POLYVERT(f[c],f[d+1])
- if(f[d][sortby] > f[hold][sortby]) {
- SWAP_POLYVERT(f[d],f[hold])
- }
- if(f[d+1][sortby] > f[hold][sortby]) {
- SWAP_POLYVERT(f[d+1],f[hold])
- }
- if(f[d][sortby] > f[d+1][sortby]) {
- SWAP_POLYVERT(f[d],f[d+1])
- }
- a=d+1;
- b=hold;
- t[0]=f[d+1][0];
- t[1]=f[d+1][1];
- for(;;) {
- do a++;
- while(f[a][sortby] < t[sortby]);
- do b--;
- while(f[b][sortby] > t[sortby]);
- if(b < a) {
- break;
- }
- SWAP_POLYVERT(f[a],f[b])
- }
- f[d+1][0]=f[b][0];
- f[d+1][1]=f[b][1];
- f[b][0]=t[0];
- f[b][1]=t[1];
- index_offset+=2;
- if(index_offset > __PLX_SMALL_COUNT__) {
- return;
- }
- if(hold-a+1 >= b-d) {
- index_list[index_offset]=hold;
- index_list[index_offset-1]=a;
- hold=b-1;
- } else {
- index_list[index_offset]=b-1;
- index_list[index_offset-1]=d;
- d=a;
- }
- }
- }
-}
-
-static int plx_find_lower_bound(float v, float(*a)[2], int num_feather_verts) {
- int x;
- int l;
- int r;
- l=1;
- r=num_feather_verts;
- for(;;) {
- // interpolation style search
- //x=l+(v-a[l][1])*(r-l) / (a[r][1]-a[l][1]);
-
- // binary search
- x=(l+r) / 2;
- if(v<a[x][1]) {
- r=x-1;
- } else {
- l=x+1;
- }
- if((v>a[x-1][1] && v <= a[x][1]) || l>r) {
- break;
- }
- }
- if(v>a[x-1][1] && v <= a[x][1]) {
- return x;
- } else {
- return num_feather_verts;
- }
-}
-
-static int plx_find_upper_bound(float v, float(*a)[2], int num_feather_verts) {
- int x;
- int l;
- int r;
- l=1;
- r=num_feather_verts;
- for(;;) {
- // interpolation style search
- //x=l+(v-a[l][1])*(r-l) / (a[r][1]-a[l][1]);
-
- // binary search
- x=(l+r) / 2;
- if(v<a[x][1]) {
- r=x-1;
- } else {
- l=x+1;
- }
- if((v>=a[x-1][1] && v < a[x][1]) || l>r) {
- break;
- }
- }
- if(v>=a[x-1][1] && v < a[x][1]) {
- return x-1;
- } else {
- return num_feather_verts;
- }
-}
-
diff --git a/intern/raskter/raskter.h b/intern/raskter/raskter.h
index cf679dd37c0..cf691a9784b 100644
--- a/intern/raskter/raskter.h
+++ b/intern/raskter/raskter.h
@@ -27,80 +27,14 @@
/** \file raskter.h
* \ingroup RASKTER
*/
-/* from BLI_utildefines.h */
-#define MIN2(x, y) ( (x) < (y) ? (x) : (y) )
-#define MAX2(x, y) ( (x) > (y) ? (x) : (y) )
-#define ABS(a) ( (a) < 0 ? (-(a)) : (a) )
-
-struct poly_vert {
- int x;
- int y;
-};
-
-struct scan_line {
- int xstart;
- int xend;
-};
-
-struct scan_line_batch {
- int num;
- int ystart;
- struct scan_line *slines;
-};
-
-struct e_status {
- int x;
- int ybeg;
- int xshift;
- int xdir;
- int drift;
- int drift_inc;
- int drift_dec;
- int num;
- struct e_status *e_next;
-};
-
-struct r_buffer_stats {
- float *buf;
- int sizex;
- int sizey;
- int ymin;
- int ymax;
- int xmin;
- int xmax;
-};
-
-struct r_fill_context {
- struct e_status *all_edges, *possible_edges;
- struct r_buffer_stats rb;
- struct scan_line *bounds;
- void *kdo; //only used with kd tree
- void *kdi; //only used with kd tree
- int *bound_indexes;
- int bounds_length;
-};
-
-struct layer_init_data {
- struct poly_vert *imask;
- struct poly_vert *omask;
- struct scan_line *bounds;
- int *bound_indexes;
- int bounds_length;
-};
#ifdef __cplusplus
extern "C" {
#endif
-void preprocess_all_edges(struct r_fill_context *ctx, struct poly_vert *verts, int num_verts, struct e_status *open_edge);
-int PLX_init_base_data(struct layer_init_data *mlayer_data, float(*base_verts)[2], int num_base_verts,
- float *buf, int buf_x, int buf_y);
int PLX_raskterize(float (*base_verts)[2], int num_base_verts,
- float *buf, int buf_x, int buf_y, int do_mask_AA);
-int PLX_raskterize_feather(float (*base_verts)[2], int num_base_verts,
- float (*feather_verts)[2], int num_feather_verts,
- float *buf, int buf_x, int buf_y);
-int PLX_antialias_buffer(float *buf, int buf_x, int buf_y);
+ float *buf, int buf_x, int buf_y);
+
#ifdef __cplusplus
}
#endif
diff --git a/intern/raskter/raskter_kdtree.c b/intern/raskter/raskter_kdtree.c
deleted file mode 100644
index 06fbc5dccd0..00000000000
--- a/intern/raskter/raskter_kdtree.c
+++ /dev/null
@@ -1,836 +0,0 @@
-/*
-This file is part of ``kdtree'', a library for working with kd-trees.
-Copyright (C) 2007-2011 John Tsiombikas <nuclear@member.fsf.org>
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-1. Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-2. 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.
-3. The name of the author may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
-*/
-/* single nearest neighbor search written by Tamas Nepusz <tamas@cs.rhul.ac.uk> */
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <math.h>
-#include "raskter_kdtree.h"
-
-#if defined(WIN32) || defined(__WIN32__)
-#include <malloc.h>
-#endif
-
-#ifdef USE_LIST_NODE_ALLOCATOR
-
-#ifndef NO_PTHREADS
-#include <pthread.h>
-#else
-
-#ifndef I_WANT_THREAD_BUGS
-#error "You are compiling with the fast list node allocator, with pthreads disabled! This WILL break if used from multiple threads."
-#endif /* I want thread bugs */
-
-#endif /* pthread support */
-#endif /* use list node allocator */
-
-struct kdhyperrect {
- int dim;
- double *min, *max; /* minimum/maximum coords */
-};
-
-struct kdnode {
- double *pos;
- int dir;
- void *data;
-
- struct kdnode *left, *right; /* negative/positive side */
-};
-
-struct res_node {
- struct kdnode *item;
- double dist_sq;
- struct res_node *next;
-};
-
-struct kdtree {
- int dim;
- struct kdnode *root;
- struct kdhyperrect *rect;
- void (*destr)(void*);
-};
-
-struct kdres {
- struct kdtree *tree;
- struct res_node *rlist, *riter;
- int size;
-};
-
-#define SQ(x) ((x) * (x))
-
-
-static void clear_rec(struct kdnode *node, void (*destr)(void*));
-static int insert_rec(struct kdnode **node, const double *pos, void *data, int dir, int dim);
-static int rlist_insert(struct res_node *list, struct kdnode *item, double dist_sq);
-static void clear_results(struct kdres *set);
-
-static struct kdhyperrect* hyperrect_create(int dim, const double *min, const double *max);
-static void hyperrect_free(struct kdhyperrect *rect);
-static struct kdhyperrect* hyperrect_duplicate(const struct kdhyperrect *rect);
-static void hyperrect_extend(struct kdhyperrect *rect, const double *pos);
-static double hyperrect_dist_sq(struct kdhyperrect *rect, const double *pos);
-
-#ifdef USE_LIST_NODE_ALLOCATOR
-static struct res_node *alloc_resnode(void);
-static void free_resnode(struct res_node*);
-#else
-#define alloc_resnode() malloc(sizeof(struct res_node))
-#define free_resnode(n) free(n)
-#endif
-
-
-
-struct kdtree *kd_create(int k)
-{
- struct kdtree *tree;
-
- if(!(tree = malloc(sizeof *tree))) {
- return 0;
- }
-
- tree->dim = k;
- tree->root = 0;
- tree->destr = 0;
- tree->rect = 0;
-
- return tree;
-}
-
-void kd_free(struct kdtree *tree)
-{
- if(tree) {
- kd_clear(tree);
- free(tree);
- }
-}
-
-static void clear_rec(struct kdnode *node, void (*destr)(void*))
-{
- if(!node) return;
-
- clear_rec(node->left, destr);
- clear_rec(node->right, destr);
-
- if(destr) {
- destr(node->data);
- }
- free(node->pos);
- free(node);
-}
-
-void kd_clear(struct kdtree *tree)
-{
- clear_rec(tree->root, tree->destr);
- tree->root = 0;
-
- if (tree->rect) {
- hyperrect_free(tree->rect);
- tree->rect = 0;
- }
-}
-
-void kd_data_destructor(struct kdtree *tree, void (*destr)(void*))
-{
- tree->destr = destr;
-}
-
-
-static int insert_rec(struct kdnode **nptr, const double *pos, void *data, int dir, int dim)
-{
- int new_dir;
- struct kdnode *node;
-
- if(!*nptr) {
- if(!(node = malloc(sizeof *node))) {
- return -1;
- }
- if(!(node->pos = malloc(dim * sizeof *node->pos))) {
- free(node);
- return -1;
- }
- memcpy(node->pos, pos, dim * sizeof *node->pos);
- node->data = data;
- node->dir = dir;
- node->left = node->right = 0;
- *nptr = node;
- return 0;
- }
-
- node = *nptr;
- new_dir = (node->dir + 1) % dim;
- if(pos[node->dir] < node->pos[node->dir]) {
- return insert_rec(&(*nptr)->left, pos, data, new_dir, dim);
- }
- return insert_rec(&(*nptr)->right, pos, data, new_dir, dim);
-}
-
-int kd_insert(struct kdtree *tree, const double *pos, void *data)
-{
- if (insert_rec(&tree->root, pos, data, 0, tree->dim)) {
- return -1;
- }
-
- if (tree->rect == 0) {
- tree->rect = hyperrect_create(tree->dim, pos, pos);
- } else {
- hyperrect_extend(tree->rect, pos);
- }
-
- return 0;
-}
-
-int kd_insertf(struct kdtree *tree, const float *pos, void *data)
-{
- static double sbuf[16];
- double *bptr, *buf = 0;
- int res, dim = tree->dim;
-
- if(dim > 16) {
-#ifndef NO_ALLOCA
- if(dim <= 256)
- bptr = buf = alloca(dim * sizeof *bptr);
- else
-#endif
- if(!(bptr = buf = malloc(dim * sizeof *bptr))) {
- return -1;
- }
- } else {
- bptr = buf = sbuf;
- }
-
- while(dim-- > 0) {
- *bptr++ = *pos++;
- }
-
- res = kd_insert(tree, buf, data);
-#ifndef NO_ALLOCA
- if(tree->dim > 256)
-#else
- if(tree->dim > 16)
-#endif
- free(buf);
- return res;
-}
-
-int kd_insert3(struct kdtree *tree, double x, double y, double z, void *data)
-{
- double buf[3];
- buf[0] = x;
- buf[1] = y;
- buf[2] = z;
- return kd_insert(tree, buf, data);
-}
-
-int kd_insert3f(struct kdtree *tree, float x, float y, float z, void *data)
-{
- double buf[3];
- buf[0] = x;
- buf[1] = y;
- buf[2] = z;
- return kd_insert(tree, buf, data);
-}
-
-static int find_nearest(struct kdnode *node, const double *pos, double range, struct res_node *list, int ordered, int dim)
-{
- double dist_sq, dx;
- int i, ret, added_res = 0;
-
- if(!node) return 0;
-
- dist_sq = 0;
- for(i=0; i<dim; i++) {
- dist_sq += SQ(node->pos[i] - pos[i]);
- }
- if(dist_sq <= SQ(range)) {
- if(rlist_insert(list, node, ordered ? dist_sq : -1.0) == -1) {
- return -1;
- }
- added_res = 1;
- }
-
- dx = pos[node->dir] - node->pos[node->dir];
-
- ret = find_nearest(dx <= 0.0 ? node->left : node->right, pos, range, list, ordered, dim);
- if(ret >= 0 && fabs(dx) < range) {
- added_res += ret;
- ret = find_nearest(dx <= 0.0 ? node->right : node->left, pos, range, list, ordered, dim);
- }
- if(ret == -1) {
- return -1;
- }
- added_res += ret;
-
- return added_res;
-}
-
-#if 0
-static int find_nearest_n(struct kdnode *node, const double *pos, double range, int num, struct rheap *heap, int dim)
-{
- double dist_sq, dx;
- int i, ret, added_res = 0;
-
- if(!node) return 0;
-
- /* if the photon is close enough, add it to the result heap */
- dist_sq = 0;
- for(i=0; i<dim; i++) {
- dist_sq += SQ(node->pos[i] - pos[i]);
- }
- if(dist_sq <= range_sq) {
- if(heap->size >= num) {
- /* get furthest element */
- struct res_node *maxelem = rheap_get_max(heap);
-
- /* and check if the new one is closer than that */
- if(maxelem->dist_sq > dist_sq) {
- rheap_remove_max(heap);
-
- if(rheap_insert(heap, node, dist_sq) == -1) {
- return -1;
- }
- added_res = 1;
-
- range_sq = dist_sq;
- }
- } else {
- if(rheap_insert(heap, node, dist_sq) == -1) {
- return =1;
- }
- added_res = 1;
- }
- }
-
-
- /* find signed distance from the splitting plane */
- dx = pos[node->dir] - node->pos[node->dir];
-
- ret = find_nearest_n(dx <= 0.0 ? node->left : node->right, pos, range, num, heap, dim);
- if(ret >= 0 && fabs(dx) < range) {
- added_res += ret;
- ret = find_nearest_n(dx <= 0.0 ? node->right : node->left, pos, range, num, heap, dim);
- }
-
-}
-#endif
-
-static void kd_nearest_i(struct kdnode *node, const double *pos, struct kdnode **result, double *result_dist_sq, struct kdhyperrect* rect)
-{
- int dir = node->dir;
- int i;
- double dummy, dist_sq;
- struct kdnode *nearer_subtree, *farther_subtree;
- double *nearer_hyperrect_coord, *farther_hyperrect_coord;
-
- /* Decide whether to go left or right in the tree */
- dummy = pos[dir] - node->pos[dir];
- if (dummy <= 0) {
- nearer_subtree = node->left;
- farther_subtree = node->right;
- nearer_hyperrect_coord = rect->max + dir;
- farther_hyperrect_coord = rect->min + dir;
- } else {
- nearer_subtree = node->right;
- farther_subtree = node->left;
- nearer_hyperrect_coord = rect->min + dir;
- farther_hyperrect_coord = rect->max + dir;
- }
-
- if (nearer_subtree) {
- /* Slice the hyperrect to get the hyperrect of the nearer subtree */
- dummy = *nearer_hyperrect_coord;
- *nearer_hyperrect_coord = node->pos[dir];
- /* Recurse down into nearer subtree */
- kd_nearest_i(nearer_subtree, pos, result, result_dist_sq, rect);
- /* Undo the slice */
- *nearer_hyperrect_coord = dummy;
- }
-
- /* Check the distance of the point at the current node, compare it
- * with our best so far */
- dist_sq = 0;
- for(i=0; i < rect->dim; i++) {
- dist_sq += SQ(node->pos[i] - pos[i]);
- }
- if (dist_sq < *result_dist_sq) {
- *result = node;
- *result_dist_sq = dist_sq;
- }
-
- if (farther_subtree) {
- /* Get the hyperrect of the farther subtree */
- dummy = *farther_hyperrect_coord;
- *farther_hyperrect_coord = node->pos[dir];
- /* Check if we have to recurse down by calculating the closest
- * point of the hyperrect and see if it's closer than our
- * minimum distance in result_dist_sq. */
- if (hyperrect_dist_sq(rect, pos) < *result_dist_sq) {
- /* Recurse down into farther subtree */
- kd_nearest_i(farther_subtree, pos, result, result_dist_sq, rect);
- }
- /* Undo the slice on the hyperrect */
- *farther_hyperrect_coord = dummy;
- }
-}
-
-struct kdres *kd_nearest(struct kdtree *kd, const double *pos)
-{
- struct kdhyperrect *rect;
- struct kdnode *result;
- struct kdres *rset;
- double dist_sq;
- int i;
-
- if (!kd) return 0;
- if (!kd->rect) return 0;
-
- /* Allocate result set */
- if(!(rset = malloc(sizeof *rset))) {
- return 0;
- }
- if(!(rset->rlist = alloc_resnode())) {
- free(rset);
- return 0;
- }
- rset->rlist->next = 0;
- rset->tree = kd;
-
- /* Duplicate the bounding hyperrectangle, we will work on the copy */
- if (!(rect = hyperrect_duplicate(kd->rect))) {
- kd_res_free(rset);
- return 0;
- }
-
- /* Our first guesstimate is the root node */
- result = kd->root;
- dist_sq = 0;
- for (i = 0; i < kd->dim; i++)
- dist_sq += SQ(result->pos[i] - pos[i]);
-
- /* Search for the nearest neighbour recursively */
- kd_nearest_i(kd->root, pos, &result, &dist_sq, rect);
-
- /* Free the copy of the hyperrect */
- hyperrect_free(rect);
-
- /* Store the result */
- if (result) {
- if (rlist_insert(rset->rlist, result, -1.0) == -1) {
- kd_res_free(rset);
- return 0;
- }
- rset->size = 1;
- kd_res_rewind(rset);
- return rset;
- } else {
- kd_res_free(rset);
- return 0;
- }
-}
-
-struct kdres *kd_nearestf(struct kdtree *tree, const float *pos)
-{
- static double sbuf[16];
- double *bptr, *buf = 0;
- int dim = tree->dim;
- struct kdres *res;
-
- if(dim > 16) {
-#ifndef NO_ALLOCA
- if(dim <= 256)
- bptr = buf = alloca(dim * sizeof *bptr);
- else
-#endif
- if(!(bptr = buf = malloc(dim * sizeof *bptr))) {
- return 0;
- }
- } else {
- bptr = buf = sbuf;
- }
-
- while(dim-- > 0) {
- *bptr++ = *pos++;
- }
-
- res = kd_nearest(tree, buf);
-#ifndef NO_ALLOCA
- if(tree->dim > 256)
-#else
- if(tree->dim > 16)
-#endif
- free(buf);
- return res;
-}
-
-struct kdres *kd_nearest3(struct kdtree *tree, double x, double y, double z)
-{
- double pos[3];
- pos[0] = x;
- pos[1] = y;
- pos[2] = z;
- return kd_nearest(tree, pos);
-}
-
-struct kdres *kd_nearest3f(struct kdtree *tree, float x, float y, float z)
-{
- double pos[3];
- pos[0] = x;
- pos[1] = y;
- pos[2] = z;
- return kd_nearest(tree, pos);
-}
-
-/* ---- nearest N search ---- */
-/*
-static kdres *kd_nearest_n(struct kdtree *kd, const double *pos, int num)
-{
- int ret;
- struct kdres *rset;
-
- if(!(rset = malloc(sizeof *rset))) {
- return 0;
- }
- if(!(rset->rlist = alloc_resnode())) {
- free(rset);
- return 0;
- }
- rset->rlist->next = 0;
- rset->tree = kd;
-
- if((ret = find_nearest_n(kd->root, pos, range, num, rset->rlist, kd->dim)) == -1) {
- kd_res_free(rset);
- return 0;
- }
- rset->size = ret;
- kd_res_rewind(rset);
- return rset;
-}*/
-
-struct kdres *kd_nearest_range(struct kdtree *kd, const double *pos, double range)
-{
- int ret;
- struct kdres *rset;
-
- if(!(rset = malloc(sizeof *rset))) {
- return 0;
- }
- if(!(rset->rlist = alloc_resnode())) {
- free(rset);
- return 0;
- }
- rset->rlist->next = 0;
- rset->tree = kd;
-
- if((ret = find_nearest(kd->root, pos, range, rset->rlist, 0, kd->dim)) == -1) {
- kd_res_free(rset);
- return 0;
- }
- rset->size = ret;
- kd_res_rewind(rset);
- return rset;
-}
-
-struct kdres *kd_nearest_rangef(struct kdtree *kd, const float *pos, float range)
-{
- static double sbuf[16];
- double *bptr, *buf = 0;
- int dim = kd->dim;
- struct kdres *res;
-
- if(dim > 16) {
-#ifndef NO_ALLOCA
- if(dim <= 256)
- bptr = buf = alloca(dim * sizeof *bptr);
- else
-#endif
- if(!(bptr = buf = malloc(dim * sizeof *bptr))) {
- return 0;
- }
- } else {
- bptr = buf = sbuf;
- }
-
- while(dim-- > 0) {
- *bptr++ = *pos++;
- }
-
- res = kd_nearest_range(kd, buf, range);
-#ifndef NO_ALLOCA
- if(kd->dim > 256)
-#else
- if(kd->dim > 16)
-#endif
- free(buf);
- return res;
-}
-
-struct kdres *kd_nearest_range3(struct kdtree *tree, double x, double y, double z, double range)
-{
- double buf[3];
- buf[0] = x;
- buf[1] = y;
- buf[2] = z;
- return kd_nearest_range(tree, buf, range);
-}
-
-struct kdres *kd_nearest_range3f(struct kdtree *tree, float x, float y, float z, float range)
-{
- double buf[3];
- buf[0] = x;
- buf[1] = y;
- buf[2] = z;
- return kd_nearest_range(tree, buf, range);
-}
-
-void kd_res_free(struct kdres *rset)
-{
- clear_results(rset);
- free_resnode(rset->rlist);
- free(rset);
-}
-
-int kd_res_size(struct kdres *set)
-{
- return (set->size);
-}
-
-void kd_res_rewind(struct kdres *rset)
-{
- rset->riter = rset->rlist->next;
-}
-
-int kd_res_end(struct kdres *rset)
-{
- return rset->riter == 0;
-}
-
-int kd_res_next(struct kdres *rset)
-{
- rset->riter = rset->riter->next;
- return rset->riter != 0;
-}
-
-void *kd_res_item(struct kdres *rset, double *pos)
-{
- if(rset->riter) {
- if(pos) {
- memcpy(pos, rset->riter->item->pos, rset->tree->dim * sizeof *pos);
- }
- return rset->riter->item->data;
- }
- return 0;
-}
-
-void *kd_res_itemf(struct kdres *rset, float *pos)
-{
- if(rset->riter) {
- if(pos) {
- int i;
- for(i=0; i<rset->tree->dim; i++) {
- pos[i] = rset->riter->item->pos[i];
- }
- }
- return rset->riter->item->data;
- }
- return 0;
-}
-
-void *kd_res_item3(struct kdres *rset, double *x, double *y, double *z)
-{
- if(rset->riter) {
- if(*x) *x = rset->riter->item->pos[0];
- if(*y) *y = rset->riter->item->pos[1];
- if(*z) *z = rset->riter->item->pos[2];
- }
- return 0;
-}
-
-void *kd_res_item3f(struct kdres *rset, float *x, float *y, float *z)
-{
- if(rset->riter) {
- if(*x) *x = rset->riter->item->pos[0];
- if(*y) *y = rset->riter->item->pos[1];
- if(*z) *z = rset->riter->item->pos[2];
- }
- return 0;
-}
-
-void *kd_res_item_data(struct kdres *set)
-{
- return kd_res_item(set, 0);
-}
-
-/* ---- hyperrectangle helpers ---- */
-static struct kdhyperrect* hyperrect_create(int dim, const double *min, const double *max)
-{
- size_t size = dim * sizeof(double);
- struct kdhyperrect* rect = 0;
-
- if (!(rect = malloc(sizeof(struct kdhyperrect)))) {
- return 0;
- }
-
- rect->dim = dim;
- if (!(rect->min = malloc(size))) {
- free(rect);
- return 0;
- }
- if (!(rect->max = malloc(size))) {
- free(rect->min);
- free(rect);
- return 0;
- }
- memcpy(rect->min, min, size);
- memcpy(rect->max, max, size);
-
- return rect;
-}
-
-static void hyperrect_free(struct kdhyperrect *rect)
-{
- free(rect->min);
- free(rect->max);
- free(rect);
-}
-
-static struct kdhyperrect* hyperrect_duplicate(const struct kdhyperrect *rect)
-{
- return hyperrect_create(rect->dim, rect->min, rect->max);
-}
-
-static void hyperrect_extend(struct kdhyperrect *rect, const double *pos)
-{
- int i;
-
- for (i=0; i < rect->dim; i++) {
- if (pos[i] < rect->min[i]) {
- rect->min[i] = pos[i];
- }
- if (pos[i] > rect->max[i]) {
- rect->max[i] = pos[i];
- }
- }
-}
-
-static double hyperrect_dist_sq(struct kdhyperrect *rect, const double *pos)
-{
- int i;
- double result = 0;
-
- for (i=0; i < rect->dim; i++) {
- if (pos[i] < rect->min[i]) {
- result += SQ(rect->min[i] - pos[i]);
- } else if (pos[i] > rect->max[i]) {
- result += SQ(rect->max[i] - pos[i]);
- }
- }
-
- return result;
-}
-
-/* ---- static helpers ---- */
-
-#ifdef USE_LIST_NODE_ALLOCATOR
-/* special list node allocators. */
-static struct res_node *free_nodes;
-
-#ifndef NO_PTHREADS
-static pthread_mutex_t alloc_mutex = PTHREAD_MUTEX_INITIALIZER;
-#endif
-
-static struct res_node *alloc_resnode(void)
-{
- struct res_node *node;
-
-#ifndef NO_PTHREADS
- pthread_mutex_lock(&alloc_mutex);
-#endif
-
- if(!free_nodes) {
- node = malloc(sizeof *node);
- } else {
- node = free_nodes;
- free_nodes = free_nodes->next;
- node->next = 0;
- }
-
-#ifndef NO_PTHREADS
- pthread_mutex_unlock(&alloc_mutex);
-#endif
-
- return node;
-}
-
-static void free_resnode(struct res_node *node)
-{
-#ifndef NO_PTHREADS
- pthread_mutex_lock(&alloc_mutex);
-#endif
-
- node->next = free_nodes;
- free_nodes = node;
-
-#ifndef NO_PTHREADS
- pthread_mutex_unlock(&alloc_mutex);
-#endif
-}
-#endif /* list node allocator or not */
-
-
-/* inserts the item. if dist_sq is >= 0, then do an ordered insert */
-/* TODO make the ordering code use heapsort */
-static int rlist_insert(struct res_node *list, struct kdnode *item, double dist_sq)
-{
- struct res_node *rnode;
-
- if(!(rnode = alloc_resnode())) {
- return -1;
- }
- rnode->item = item;
- rnode->dist_sq = dist_sq;
-
- if(dist_sq >= 0.0) {
- while(list->next && list->next->dist_sq < dist_sq) {
- list = list->next;
- }
- }
- rnode->next = list->next;
- list->next = rnode;
- return 0;
-}
-
-static void clear_results(struct kdres *rset)
-{
- struct res_node *tmp, *node = rset->rlist->next;
-
- while(node) {
- tmp = node;
- node = node->next;
- free_resnode(tmp);
- }
-
- rset->rlist->next = 0;
-}
diff --git a/intern/raskter/raskter_kdtree.h b/intern/raskter/raskter_kdtree.h
deleted file mode 100644
index da80e422a80..00000000000
--- a/intern/raskter/raskter_kdtree.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
-This file is part of ``kdtree'', a library for working with kd-trees.
-Copyright (C) 2007-2011 John Tsiombikas <nuclear@member.fsf.org>
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-1. Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-2. 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.
-3. The name of the author may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 _KDTREE_H_
-#define _KDTREE_H_
-#define USE_LIST_NODE_ALLOCATOR
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct kdtree;
-struct kdres;
-
-
-/* create a kd-tree for "k"-dimensional data */
-struct kdtree *kd_create(int k);
-
-/* free the struct kdtree */
-void kd_free(struct kdtree *tree);
-
-/* remove all the elements from the tree */
-void kd_clear(struct kdtree *tree);
-
-/* if called with non-null 2nd argument, the function provided
- * will be called on data pointers (see kd_insert) when nodes
- * are to be removed from the tree.
- */
-void kd_data_destructor(struct kdtree *tree, void (*destr)(void*));
-
-/* insert a node, specifying its position, and optional data */
-int kd_insert(struct kdtree *tree, const double *pos, void *data);
-int kd_insertf(struct kdtree *tree, const float *pos, void *data);
-int kd_insert3(struct kdtree *tree, double x, double y, double z, void *data);
-int kd_insert3f(struct kdtree *tree, float x, float y, float z, void *data);
-
-/* Find the nearest node from a given point.
- *
- * This function returns a pointer to a result set with at most one element.
- */
-struct kdres *kd_nearest(struct kdtree *tree, const double *pos);
-struct kdres *kd_nearestf(struct kdtree *tree, const float *pos);
-struct kdres *kd_nearest3(struct kdtree *tree, double x, double y, double z);
-struct kdres *kd_nearest3f(struct kdtree *tree, float x, float y, float z);
-
-/* Find the N nearest nodes from a given point.
- *
- * This function returns a pointer to a result set, with at most N elements,
- * which can be manipulated with the kd_res_* functions.
- * The returned pointer can be null as an indication of an error. Otherwise
- * a valid result set is always returned which may contain 0 or more elements.
- * The result set must be deallocated with kd_res_free after use.
- */
-/*
-struct kdres *kd_nearest_n(struct kdtree *tree, const double *pos, int num);
-struct kdres *kd_nearest_nf(struct kdtree *tree, const float *pos, int num);
-struct kdres *kd_nearest_n3(struct kdtree *tree, double x, double y, double z);
-struct kdres *kd_nearest_n3f(struct kdtree *tree, float x, float y, float z);
-*/
-
-/* Find any nearest nodes from a given point within a range.
- *
- * This function returns a pointer to a result set, which can be manipulated
- * by the kd_res_* functions.
- * The returned pointer can be null as an indication of an error. Otherwise
- * a valid result set is always returned which may contain 0 or more elements.
- * The result set must be deallocated with kd_res_free after use.
- */
-struct kdres *kd_nearest_range(struct kdtree *tree, const double *pos, double range);
-struct kdres *kd_nearest_rangef(struct kdtree *tree, const float *pos, float range);
-struct kdres *kd_nearest_range3(struct kdtree *tree, double x, double y, double z, double range);
-struct kdres *kd_nearest_range3f(struct kdtree *tree, float x, float y, float z, float range);
-
-/* frees a result set returned by kd_nearest_range() */
-void kd_res_free(struct kdres *set);
-
-/* returns the size of the result set (in elements) */
-int kd_res_size(struct kdres *set);
-
-/* rewinds the result set iterator */
-void kd_res_rewind(struct kdres *set);
-
-/* returns non-zero if the set iterator reached the end after the last element */
-int kd_res_end(struct kdres *set);
-
-/* advances the result set iterator, returns non-zero on success, zero if
- * there are no more elements in the result set.
- */
-int kd_res_next(struct kdres *set);
-
-/* returns the data pointer (can be null) of the current result set item
- * and optionally sets its position to the pointers(s) if not null.
- */
-void *kd_res_item(struct kdres *set, double *pos);
-void *kd_res_itemf(struct kdres *set, float *pos);
-void *kd_res_item3(struct kdres *set, double *x, double *y, double *z);
-void *kd_res_item3f(struct kdres *set, float *x, float *y, float *z);
-
-/* equivalent to kd_res_item(set, 0) */
-void *kd_res_item_data(struct kdres *set);
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _KDTREE_H_ */
diff --git a/intern/raskter/raskter_mt.c b/intern/raskter/raskter_mt.c
deleted file mode 100644
index feda624d668..00000000000
--- a/intern/raskter/raskter_mt.c
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2012 Blender Foundation.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Peter Larabell.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-/** \file raskter_mt.c
- * \ingroup RASKTER
- */
-#include <stdlib.h>
-
-#include "raskter.h"
-static int rast_scan_init(struct layer_init_data *mlayer_data, struct r_fill_context *ctx, struct poly_vert *verts, int num_verts) {
- int x_curr; /* current pixel position in X */
- int y_curr; /* current scan line being drawn */
- int yp; /* y-pixel's position in frame buffer */
- int swixd = 0; /* whether or not edges switched position in X */
- int i=0; /* counter */
- float *cpxl; /* pixel pointers... */
- float *mpxl;
- float *spxl;
- struct e_status *e_curr; /* edge pointers... */
- struct e_status *e_temp;
- struct e_status *edgbuf;
- struct e_status **edgec;
-
-
- if(num_verts < 3) {
- return(1);
- }
-
- if((edgbuf = (struct e_status *)(malloc(sizeof(struct e_status) * num_verts))) == NULL) {
- return(0);
- }
-
- /* set initial bounds length to 0 */
- mlayer_data->bounds_length=0;
-
- /* round 1, count up all the possible spans in the base buffer */
- preprocess_all_edges(ctx, verts, num_verts, edgbuf);
-
- /* can happen with a zero area mask */
- if (ctx->all_edges == NULL) {
- free(edgbuf);
- return(1);
- }
- ctx->possible_edges = NULL;
-
- for(y_curr = ctx->all_edges->ybeg; (ctx->all_edges || ctx->possible_edges); y_curr++) {
-
- for(edgec = &ctx->possible_edges; ctx->all_edges && (ctx->all_edges->ybeg == y_curr);) {
- x_curr = ctx->all_edges->x; /* Set current X position. */
- for(;;) { /* Start looping edges. Will break when edges run out. */
- e_curr = *edgec; /* Set up a current edge pointer. */
- if(!e_curr || (e_curr->x >= x_curr)) { /* If we have an no edge, or we need to skip some X-span, */
- e_temp = ctx->all_edges->e_next; /* set a temp "next" edge to test. */
- *edgec = ctx->all_edges; /* Add this edge to the list to be scanned. */
- ctx->all_edges->e_next = e_curr; /* Set up the next edge. */
- edgec = &ctx->all_edges->e_next; /* Set our list to the next edge's location in memory. */
- ctx->all_edges = e_temp; /* Skip the NULL or bad X edge, set pointer to next edge. */
- break; /* Stop looping edges (since we ran out or hit empty X span. */
- } else {
- edgec = &e_curr->e_next; /* Set the pointer to the edge list the "next" edge. */
- }
- }
- }
-
- yp = y_curr * ctx->rb.sizex;
- spxl = ctx->rb.buf + (yp);
-
- for(e_curr = ctx->possible_edges; e_curr; e_curr = e_curr->e_next) {
-
- /* set up xmin and xmax bounds on this scan line */
- cpxl = spxl + MAX2(e_curr->x, 0);
- e_curr = e_curr->e_next;
- mpxl = spxl + MIN2(e_curr->x, ctx->rb.sizex) - 1;
-
- if((y_curr >= 0) && (y_curr < ctx->rb.sizey)) {
- mlayer_data->bounds_length++;
- }
- }
-
- for(edgec = &ctx->possible_edges; (e_curr = *edgec);) {
- if(!(--(e_curr->num))) {
- *edgec = e_curr->e_next;
- } else {
- e_curr->x += e_curr->xshift;
- if((e_curr->drift += e_curr->drift_inc) > 0) {
- e_curr->x += e_curr->xdir;
- e_curr->drift -= e_curr->drift_dec;
- }
- edgec = &e_curr->e_next;
- }
- }
- if(ctx->possible_edges) {
- for(edgec = &ctx->possible_edges; (e_curr = *edgec)->e_next; edgec = &(*edgec)->e_next) {
- /* if the current edge hits scan line at greater X than the next edge, we need to exchange the edges */
- if(e_curr->x > e_curr->e_next->x) {
- *edgec = e_curr->e_next;
- /* exchange the pointers */
- e_temp = e_curr->e_next->e_next;
- e_curr->e_next->e_next = e_curr;
- e_curr->e_next = e_temp;
- /* set flag that we had at least one switch */
- swixd = 1;
- }
- }
- /* if we did have a switch, look for more (there will more if there was one) */
- for(;;) {
- /* reset exchange flag so it's only set if we encounter another one */
- swixd = 0;
- for(edgec = &ctx->possible_edges; (e_curr = *edgec)->e_next; edgec = &(*edgec)->e_next) {
- /* again, if current edge hits scan line at higher X than next edge, exchange the edges and set flag */
- if(e_curr->x > e_curr->e_next->x) {
- *edgec = e_curr->e_next;
- /* exchange the pointers */
- e_temp = e_curr->e_next->e_next;
- e_curr->e_next->e_next = e_curr;
- e_curr->e_next = e_temp;
- /* flip the exchanged flag */
- swixd = 1;
- }
- }
- /* if we had no exchanges, we're done reshuffling the pointers */
- if(!swixd) {
- break;
- }
- }
- }
- }
-
-
-/*initialize index buffer and bounds buffers*/
- //gets the +1 for dummy at the end
- if((mlayer_data->bound_indexes = (int *)(malloc(sizeof(int) * ctx->rb.sizey+1)))==NULL) {
- return(0);
- }
- //gets the +1 for dummy at the start
- if((mlayer_data->bounds = (struct scan_line *)(malloc(sizeof(struct scan_line) * mlayer_data->bounds_length+1)))==NULL){
- return(0);
- }
- //init all the indexes to zero (are they already zeroed from malloc???)
- for(i=0;i<ctx->rb.sizey+1;i++){
- mlayer_data->bound_indexes[i]=0;
- }
- /* round 2, fill in the full list of bounds, and create indexes to the list... */
- preprocess_all_edges(ctx, verts, num_verts, edgbuf);
-
- /* can happen with a zero area mask */
- if (ctx->all_edges == NULL) {
- free(edgbuf);
- return(1);
- }
- ctx->possible_edges = NULL;
-
- /* restart i as a counter for total span placement in buffer */
- i=1;
- for(y_curr = ctx->all_edges->ybeg; (ctx->all_edges || ctx->possible_edges); y_curr++) {
-
- for(edgec = &ctx->possible_edges; ctx->all_edges && (ctx->all_edges->ybeg == y_curr);) {
- x_curr = ctx->all_edges->x; /* Set current X position. */
- for(;;) { /* Start looping edges. Will break when edges run out. */
- e_curr = *edgec; /* Set up a current edge pointer. */
- if(!e_curr || (e_curr->x >= x_curr)) { /* If we have an no edge, or we need to skip some X-span, */
- e_temp = ctx->all_edges->e_next; /* set a temp "next" edge to test. */
- *edgec = ctx->all_edges; /* Add this edge to the list to be scanned. */
- ctx->all_edges->e_next = e_curr; /* Set up the next edge. */
- edgec = &ctx->all_edges->e_next; /* Set our list to the next edge's location in memory. */
- ctx->all_edges = e_temp; /* Skip the NULL or bad X edge, set pointer to next edge. */
- break; /* Stop looping edges (since we ran out or hit empty X span. */
- } else {
- edgec = &e_curr->e_next; /* Set the pointer to the edge list the "next" edge. */
- }
- }
- }
-
- yp = y_curr * ctx->rb.sizex;
- spxl = ctx->rb.buf + (yp);
- if((y_curr >=0) && (y_curr < ctx->rb.sizey)){
- ctx->bound_indexes[y_curr]=i;
- }
- for(e_curr = ctx->possible_edges; e_curr; e_curr = e_curr->e_next) {
-
- /* set up xmin and xmax bounds on this scan line */
- cpxl = spxl + MAX2(e_curr->x, 0);
- e_curr = e_curr->e_next;
- mpxl = spxl + MIN2(e_curr->x, ctx->rb.sizex) - 1;
-
- if((y_curr >= 0) && (y_curr < ctx->rb.sizey)) {
- mlayer_data->bounds[i].xstart=cpxl-spxl;
- mlayer_data->bounds[i].xend=mpxl-spxl;
- i++;
- }
- }
-
- for(edgec = &ctx->possible_edges; (e_curr = *edgec);) {
- if(!(--(e_curr->num))) {
- *edgec = e_curr->e_next;
- } else {
- e_curr->x += e_curr->xshift;
- if((e_curr->drift += e_curr->drift_inc) > 0) {
- e_curr->x += e_curr->xdir;
- e_curr->drift -= e_curr->drift_dec;
- }
- edgec = &e_curr->e_next;
- }
- }
- if(ctx->possible_edges) {
- for(edgec = &ctx->possible_edges; (e_curr = *edgec)->e_next; edgec = &(*edgec)->e_next) {
- /* if the current edge hits scan line at greater X than the next edge, we need to exchange the edges */
- if(e_curr->x > e_curr->e_next->x) {
- *edgec = e_curr->e_next;
- /* exchange the pointers */
- e_temp = e_curr->e_next->e_next;
- e_curr->e_next->e_next = e_curr;
- e_curr->e_next = e_temp;
- /* set flag that we had at least one switch */
- swixd = 1;
- }
- }
- /* if we did have a switch, look for more (there will more if there was one) */
- for(;;) {
- /* reset exchange flag so it's only set if we encounter another one */
- swixd = 0;
- for(edgec = &ctx->possible_edges; (e_curr = *edgec)->e_next; edgec = &(*edgec)->e_next) {
- /* again, if current edge hits scan line at higher X than next edge, exchange the edges and set flag */
- if(e_curr->x > e_curr->e_next->x) {
- *edgec = e_curr->e_next;
- /* exchange the pointers */
- e_temp = e_curr->e_next->e_next;
- e_curr->e_next->e_next = e_curr;
- e_curr->e_next = e_temp;
- /* flip the exchanged flag */
- swixd = 1;
- }
- }
- /* if we had no exchanges, we're done reshuffling the pointers */
- if(!swixd) {
- break;
- }
- }
- }
- }
-
- free(edgbuf);
- return 1;
-}
-
-/* static */ int PLX_init_base_data(struct layer_init_data *mlayer_data, float(*base_verts)[2], int num_base_verts,
- float *buf, int buf_x, int buf_y) {
- int i; /* i: Loop counter. */
- struct poly_vert *ply; /* ply: Pointer to a list of integer buffer-space vertex coordinates. */
- struct r_fill_context ctx = {0};
- const float buf_x_f = (float)(buf_x);
- const float buf_y_f = (float)(buf_y);
- if((ply = (struct poly_vert *)(malloc(sizeof(struct poly_vert) * num_base_verts))) == NULL) {
- return(0);
- }
- ctx.rb.buf = buf; /* Set the output buffer pointer. */
- ctx.rb.sizex = buf_x; /* Set the output buffer size in X. (width) */
- ctx.rb.sizey = buf_y; /* Set the output buffer size in Y. (height) */
- for(i = 0; i < num_base_verts; i++) { /* Loop over all base_verts. */
- ply[i].x = (int)((base_verts[i][0] * buf_x_f) + 0.5f); /* Range expand normalized X to integer buffer-space X. */
- ply[i].y = (int)((base_verts[i][1] * buf_y_f) + 0.5f); /* Range expand normalized Y to integer buffer-space Y. */
- }
- i = rast_scan_init(mlayer_data, &ctx, ply, num_base_verts); /* Call our rasterizer, passing in the integer coords for each vert. */
- free(ply); /* Free the memory allocated for the integer coordinate table. */
- return(i); /* Return the value returned by the rasterizer. */
-}
-
diff --git a/intern/smoke/CMakeLists.txt b/intern/smoke/CMakeLists.txt
index 9524f7b2935..3b8a4c06e69 100644
--- a/intern/smoke/CMakeLists.txt
+++ b/intern/smoke/CMakeLists.txt
@@ -26,10 +26,10 @@
set(INC
intern
../memutil
- ../../extern/bullet2/src
)
set(INC_SYS
+ ../../extern/bullet2/src
${PNG_INCLUDE_DIR}
${ZLIB_INCLUDE_DIRS}
)
@@ -40,6 +40,7 @@ set(SRC
intern/FLUID_3D_SOLVERS.cpp
intern/FLUID_3D_STATIC.cpp
intern/LU_HELPER.cpp
+ intern/spectrum.cpp
intern/SPHERE.cpp
intern/WTURBULENCE.cpp
intern/smoke_API.cpp
@@ -53,6 +54,7 @@ set(SRC
intern/LU_HELPER.h
intern/MERSENNETWISTER.h
intern/OBSTACLE.h
+ intern/spectrum.h
intern/SPHERE.h
intern/VEC3.h
intern/WAVELET_NOISE.h
diff --git a/intern/smoke/extern/smoke_API.h b/intern/smoke/extern/smoke_API.h
index a0eb1bf38e0..98c63f08fbd 100644
--- a/intern/smoke/extern/smoke_API.h
+++ b/intern/smoke/extern/smoke_API.h
@@ -37,17 +37,23 @@ extern "C" {
struct FLUID_3D;
-// export
-void smoke_export(struct FLUID_3D *fluid, float *dt, float *dx, float **dens, float **densold, float **heat, float **heatold, float **vx, float **vy, float **vz, float **vxold, float **vyold, float **vzold, unsigned char **obstacles);
-
// low res
-struct FLUID_3D *smoke_init(int *res, float *p0, float dtdef);
+struct FLUID_3D *smoke_init(int *res, float dx, float dtdef, int use_heat, int use_fire, int use_colors);
void smoke_free(struct FLUID_3D *fluid);
-void smoke_initBlenderRNA(struct FLUID_3D *fluid, float *alpha, float *beta, float *dt_factor, float *vorticity, int *border_colli);
-void smoke_step(struct FLUID_3D *fluid, float dtSubdiv);
+void smoke_initBlenderRNA(struct FLUID_3D *fluid, float *alpha, float *beta, float *dt_factor, float *vorticity, int *border_colli, float *burning_rate,
+ float *flame_smoke, float *flame_smoke_color, float *flame_vorticity, float *flame_ignition_temp, float *flame_max_temp);
+void smoke_step(struct FLUID_3D *fluid, float gravity[3], float dtSubdiv);
float *smoke_get_density(struct FLUID_3D *fluid);
+float *smoke_get_flame(struct FLUID_3D *fluid);
+float *smoke_get_fuel(struct FLUID_3D *fluid);
+float *smoke_get_react(struct FLUID_3D *fluid);
+float *smoke_get_color_r(struct FLUID_3D *fluid);
+float *smoke_get_color_g(struct FLUID_3D *fluid);
+float *smoke_get_color_b(struct FLUID_3D *fluid);
+void smoke_get_rgba(struct FLUID_3D *fluid, float *data, int sequential);
+void smoke_get_rgba_from_density(struct FLUID_3D *fluid, float color[3], float *data, int sequential);
float *smoke_get_heat(struct FLUID_3D *fluid);
float *smoke_get_velocity_x(struct FLUID_3D *fluid);
float *smoke_get_velocity_y(struct FLUID_3D *fluid);
@@ -68,19 +74,44 @@ size_t smoke_get_index2d(int x, int max_x, int y);
void smoke_dissolve(struct FLUID_3D *fluid, int speed, int log);
// wavelet turbulence functions
-struct WTURBULENCE *smoke_turbulence_init(int *res, int amplify, int noisetype);
+struct WTURBULENCE *smoke_turbulence_init(int *res, int amplify, int noisetype, int use_fire, int use_colors);
void smoke_turbulence_free(struct WTURBULENCE *wt);
void smoke_turbulence_step(struct WTURBULENCE *wt, struct FLUID_3D *fluid);
float *smoke_turbulence_get_density(struct WTURBULENCE *wt);
+float *smoke_turbulence_get_color_r(struct WTURBULENCE *wt);
+float *smoke_turbulence_get_color_g(struct WTURBULENCE *wt);
+float *smoke_turbulence_get_color_b(struct WTURBULENCE *wt);
+void smoke_turbulence_get_rgba(struct WTURBULENCE *wt, float *data, int sequential);
+void smoke_turbulence_get_rgba_from_density(struct WTURBULENCE *wt, float color[3], float *data, int sequential);
+float *smoke_turbulence_get_flame(struct WTURBULENCE *wt);
+float *smoke_turbulence_get_fuel(struct WTURBULENCE *wt);
+float *smoke_turbulence_get_react(struct WTURBULENCE *wt);
void smoke_turbulence_get_res(struct WTURBULENCE *wt, int *res);
+int smoke_turbulence_get_cells(struct WTURBULENCE *wt);
void smoke_turbulence_set_noise(struct WTURBULENCE *wt, int type);
void smoke_initWaveletBlenderRNA(struct WTURBULENCE *wt, float *strength);
-
void smoke_dissolve_wavelet(struct WTURBULENCE *wt, int speed, int log);
-// export
-void smoke_turbulence_export(struct WTURBULENCE *wt, float **dens, float **densold, float **tcu, float **tcv, float **tcw);
+/* export */
+void smoke_export(struct FLUID_3D *fluid, float *dt, float *dx, float **dens, float **react, float **flame, float **fuel, float **heat, float **heatold,
+ float **vx, float **vy, float **vz, float **r, float **g, float **b, unsigned char **obstacles);
+void smoke_turbulence_export(struct WTURBULENCE *wt, float **dens, float **react, float **flame, float **fuel,
+ float **r, float **g, float **b, float **tcu, float **tcv, float **tcw);
+
+/* flame spectrum */
+void flame_get_spectrum(unsigned char *spec, int width, float t1, float t2);
+
+/* data fields */
+int smoke_has_heat(struct FLUID_3D *fluid);
+int smoke_has_fuel(struct FLUID_3D *fluid);
+int smoke_has_colors(struct FLUID_3D *fluid);
+int smoke_turbulence_has_fuel(struct WTURBULENCE *wt);
+int smoke_turbulence_has_colors(struct WTURBULENCE *wt);
+
+void smoke_ensure_heat(struct FLUID_3D *fluid);
+void smoke_ensure_fire(struct FLUID_3D *fluid, struct WTURBULENCE *wt);
+void smoke_ensure_colors(struct FLUID_3D *fluid, struct WTURBULENCE *wt, float init_r, float init_g, float init_b);
#ifdef __cplusplus
}
diff --git a/intern/smoke/intern/FLUID_3D.cpp b/intern/smoke/intern/FLUID_3D.cpp
index e006132ea8f..4eb11a46f5b 100644
--- a/intern/smoke/intern/FLUID_3D.cpp
+++ b/intern/smoke/intern/FLUID_3D.cpp
@@ -44,16 +44,11 @@
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
-FLUID_3D::FLUID_3D(int *res, float *p0, float dtdef) :
+FLUID_3D::FLUID_3D(int *res, float dx, float dtdef, int init_heat, int init_fire, int init_colors) :
_xRes(res[0]), _yRes(res[1]), _zRes(res[2]), _res(0.0f)
{
// set simulation consts
_dt = dtdef; // just in case. set in step from a RNA factor
-
- // start point of array
- _p0[0] = p0[0];
- _p0[1] = p0[1];
- _p0[2] = p0[2];
_iterations = 100;
_tempAmb = 0;
@@ -72,7 +67,10 @@ FLUID_3D::FLUID_3D(int *res, float *p0, float dtdef) :
*/
// scale the constants according to the refinement of the grid
- _dx = 1.0f / (float)_maxRes;
+ if (!dx)
+ _dx = 1.0f / (float)_maxRes;
+ else
+ _dx = dx;
_constantScaling = 64.0f / _maxRes;
_constantScaling = (_constantScaling < 1.0f) ? 1.0f : _constantScaling;
_vorticityEps = 2.0f / _constantScaling; // Just in case set a default value
@@ -94,8 +92,6 @@ FLUID_3D::FLUID_3D(int *res, float *p0, float dtdef) :
_zForce = new float[_totalCells];
_density = new float[_totalCells];
_densityOld = new float[_totalCells];
- _heat = new float[_totalCells];
- _heatOld = new float[_totalCells];
_obstacles = new unsigned char[_totalCells]; // set 0 at end of step
// For threaded version:
@@ -103,7 +99,6 @@ FLUID_3D::FLUID_3D(int *res, float *p0, float dtdef) :
_yVelocityTemp = new float[_totalCells];
_zVelocityTemp = new float[_totalCells];
_densityTemp = new float[_totalCells];
- _heatTemp = new float[_totalCells];
// DG TODO: check if alloc went fine
@@ -111,8 +106,6 @@ FLUID_3D::FLUID_3D(int *res, float *p0, float dtdef) :
{
_density[x] = 0.0f;
_densityOld[x] = 0.0f;
- _heat[x] = 0.0f;
- _heatOld[x] = 0.0f;
_xVelocity[x] = 0.0f;
_yVelocity[x] = 0.0f;
_zVelocity[x] = 0.0f;
@@ -128,6 +121,25 @@ FLUID_3D::FLUID_3D(int *res, float *p0, float dtdef) :
_obstacles[x] = false;
}
+ /* heat */
+ _heat = _heatOld = _heatTemp = NULL;
+ if (init_heat) {
+ initHeat();
+ }
+ // Fire simulation
+ _flame = _fuel = _fuelTemp = _fuelOld = NULL;
+ _react = _reactTemp = _reactOld = NULL;
+ if (init_fire) {
+ initFire();
+ }
+ // Smoke color
+ _color_r = _color_rOld = _color_rTemp = NULL;
+ _color_g = _color_gOld = _color_gTemp = NULL;
+ _color_b = _color_bOld = _color_bTemp = NULL;
+ if (init_colors) {
+ initColors(0.0f, 0.0f, 0.0f);
+ }
+
// boundary conditions of the fluid domain
// set default values -> vertically non-colliding
_domainBcFront = true;
@@ -138,9 +150,70 @@ FLUID_3D::FLUID_3D(int *res, float *p0, float dtdef) :
_domainBcRight = _domainBcLeft;
_colloPrev = 1; // default value
+}
- setBorderObstacles(); // walls
+void FLUID_3D::initHeat()
+{
+ if (!_heat) {
+ _heat = new float[_totalCells];
+ _heatOld = new float[_totalCells];
+ _heatTemp = new float[_totalCells];
+ for (int x = 0; x < _totalCells; x++)
+ {
+ _heat[x] = 0.0f;
+ _heatOld[x] = 0.0f;
+ }
+ }
+}
+
+void FLUID_3D::initFire()
+{
+ if (!_flame) {
+ _flame = new float[_totalCells];
+ _fuel = new float[_totalCells];
+ _fuelTemp = new float[_totalCells];
+ _fuelOld = new float[_totalCells];
+ _react = new float[_totalCells];
+ _reactTemp = new float[_totalCells];
+ _reactOld = new float[_totalCells];
+
+ for (int x = 0; x < _totalCells; x++)
+ {
+ _flame[x] = 0.0f;
+ _fuel[x] = 0.0f;
+ _fuelTemp[x] = 0.0f;
+ _fuelOld[x] = 0.0f;
+ _react[x] = 0.0f;
+ _reactTemp[x] = 0.0f;
+ _reactOld[x] = 0.0f;
+ }
+ }
+}
+
+void FLUID_3D::initColors(float init_r, float init_g, float init_b)
+{
+ if (!_color_r) {
+ _color_r = new float[_totalCells];
+ _color_rOld = new float[_totalCells];
+ _color_rTemp = new float[_totalCells];
+ _color_g = new float[_totalCells];
+ _color_gOld = new float[_totalCells];
+ _color_gTemp = new float[_totalCells];
+ _color_b = new float[_totalCells];
+ _color_bOld = new float[_totalCells];
+ _color_bTemp = new float[_totalCells];
+
+ for (int x = 0; x < _totalCells; x++)
+ {
+ _color_r[x] = _density[x] * init_r;
+ _color_rOld[x] = 0.0f;
+ _color_g[x] = _density[x] * init_g;
+ _color_gOld[x] = 0.0f;
+ _color_b[x] = _density[x] * init_b;
+ _color_bOld[x] = 0.0f;
+ }
+ }
}
void FLUID_3D::setBorderObstacles()
@@ -204,7 +277,6 @@ FLUID_3D::~FLUID_3D()
if (_heat) delete[] _heat;
if (_heatOld) delete[] _heatOld;
if (_obstacles) delete[] _obstacles;
- // if (_wTurbulence) delete _wTurbulence;
if (_xVelocityTemp) delete[] _xVelocityTemp;
if (_yVelocityTemp) delete[] _yVelocityTemp;
@@ -212,23 +284,48 @@ FLUID_3D::~FLUID_3D()
if (_densityTemp) delete[] _densityTemp;
if (_heatTemp) delete[] _heatTemp;
+ if (_flame) delete[] _flame;
+ if (_fuel) delete[] _fuel;
+ if (_fuelTemp) delete[] _fuelTemp;
+ if (_fuelOld) delete[] _fuelOld;
+ if (_react) delete[] _react;
+ if (_reactTemp) delete[] _reactTemp;
+ if (_reactOld) delete[] _reactOld;
+
+ if (_color_r) delete[] _color_r;
+ if (_color_rOld) delete[] _color_rOld;
+ if (_color_rTemp) delete[] _color_rTemp;
+ if (_color_g) delete[] _color_g;
+ if (_color_gOld) delete[] _color_gOld;
+ if (_color_gTemp) delete[] _color_gTemp;
+ if (_color_b) delete[] _color_b;
+ if (_color_bOld) delete[] _color_bOld;
+ if (_color_bTemp) delete[] _color_bTemp;
+
// printf("deleted fluid\n");
}
// init direct access functions from blender
-void FLUID_3D::initBlenderRNA(float *alpha, float *beta, float *dt_factor, float *vorticity, int *borderCollision)
+void FLUID_3D::initBlenderRNA(float *alpha, float *beta, float *dt_factor, float *vorticity, int *borderCollision, float *burning_rate,
+ float *flame_smoke, float *flame_smoke_color, float *flame_vorticity, float *flame_ignition_temp, float *flame_max_temp)
{
_alpha = alpha;
_beta = beta;
_dtFactor = dt_factor;
_vorticityRNA = vorticity;
_borderColli = borderCollision;
+ _burning_rate = burning_rate;
+ _flame_smoke = flame_smoke;
+ _flame_smoke_color = flame_smoke_color;
+ _flame_vorticity = flame_vorticity;
+ _ignition_temp = flame_ignition_temp;
+ _max_temp = flame_max_temp;
}
//////////////////////////////////////////////////////////////////////
// step simulation once
//////////////////////////////////////////////////////////////////////
-void FLUID_3D::step(float dt)
+void FLUID_3D::step(float dt, float gravity[3])
{
#if 0
// If border rules have been changed
@@ -281,7 +378,7 @@ void FLUID_3D::step(float dt)
wipeBoundariesSL(zBegin, zEnd);
addVorticity(zBegin, zEnd);
- addBuoyancy(_heat, _density, zBegin, zEnd);
+ addBuoyancy(_heat, _density, gravity, zBegin, zEnd);
addForce(zBegin, zEnd);
#if PARALLEL==1
@@ -312,13 +409,15 @@ void FLUID_3D::step(float dt)
if (i==0)
{
#endif
- project();
+ project();
#if PARALLEL==1
}
- else
+ else if (i==1)
{
#endif
- diffuseHeat();
+ if (_heat) {
+ diffuseHeat();
+ }
#if PARALLEL==1
}
}
@@ -338,6 +437,13 @@ void FLUID_3D::step(float dt)
SWAP_POINTERS(_density, _densityOld);
SWAP_POINTERS(_heat, _heatOld);
+ SWAP_POINTERS(_fuel, _fuelOld);
+ SWAP_POINTERS(_react, _reactOld);
+
+ SWAP_POINTERS(_color_r, _color_rOld);
+ SWAP_POINTERS(_color_g, _color_gOld);
+ SWAP_POINTERS(_color_b, _color_bOld);
+
advectMacCormackBegin(0, _zRes);
#if PARALLEL==1
@@ -398,11 +504,8 @@ void FLUID_3D::step(float dt)
SWAP_POINTERS(_yVelocity, _yForce);
SWAP_POINTERS(_zVelocity, _zForce);
-
-
-
_totalTime += _dt;
- _totalSteps++;
+ _totalSteps++;
for (int i = 0; i < _totalCells; i++)
{
@@ -643,6 +746,15 @@ void FLUID_3D::wipeBoundaries(int zBegin, int zEnd)
setZeroBorder(_yVelocity, _res, zBegin, zEnd);
setZeroBorder(_zVelocity, _res, zBegin, zEnd);
setZeroBorder(_density, _res, zBegin, zEnd);
+ if (_fuel) {
+ setZeroBorder(_fuel, _res, zBegin, zEnd);
+ setZeroBorder(_react, _res, zBegin, zEnd);
+ }
+ if (_color_r) {
+ setZeroBorder(_color_r, _res, zBegin, zEnd);
+ setZeroBorder(_color_g, _res, zBegin, zEnd);
+ setZeroBorder(_color_b, _res, zBegin, zEnd);
+ }
}
void FLUID_3D::wipeBoundariesSL(int zBegin, int zEnd)
@@ -668,6 +780,15 @@ void FLUID_3D::wipeBoundariesSL(int zBegin, int zEnd)
_yVelocity[index] = 0.0f;
_zVelocity[index] = 0.0f;
_density[index] = 0.0f;
+ if (_fuel) {
+ _fuel[index] = 0.0f;
+ _react[index] = 0.0f;
+ }
+ if (_color_r) {
+ _color_r[index] = 0.0f;
+ _color_g[index] = 0.0f;
+ _color_b[index] = 0.0f;
+ }
// right slab
index += _xRes - 1;
@@ -675,6 +796,15 @@ void FLUID_3D::wipeBoundariesSL(int zBegin, int zEnd)
_yVelocity[index] = 0.0f;
_zVelocity[index] = 0.0f;
_density[index] = 0.0f;
+ if (_fuel) {
+ _fuel[index] = 0.0f;
+ _react[index] = 0.0f;
+ }
+ if (_color_r) {
+ _color_r[index] = 0.0f;
+ _color_g[index] = 0.0f;
+ _color_b[index] = 0.0f;
+ }
}
/////////////////////////////////////
@@ -690,6 +820,15 @@ void FLUID_3D::wipeBoundariesSL(int zBegin, int zEnd)
_yVelocity[index] = 0.0f;
_zVelocity[index] = 0.0f;
_density[index] = 0.0f;
+ if (_fuel) {
+ _fuel[index] = 0.0f;
+ _react[index] = 0.0f;
+ }
+ if (_color_r) {
+ _color_r[index] = 0.0f;
+ _color_g[index] = 0.0f;
+ _color_b[index] = 0.0f;
+ }
// top slab
index += slabSize - _xRes;
@@ -697,6 +836,15 @@ void FLUID_3D::wipeBoundariesSL(int zBegin, int zEnd)
_yVelocity[index] = 0.0f;
_zVelocity[index] = 0.0f;
_density[index] = 0.0f;
+ if (_fuel) {
+ _fuel[index] = 0.0f;
+ _react[index] = 0.0f;
+ }
+ if (_color_r) {
+ _color_r[index] = 0.0f;
+ _color_g[index] = 0.0f;
+ _color_b[index] = 0.0f;
+ }
}
@@ -717,6 +865,15 @@ void FLUID_3D::wipeBoundariesSL(int zBegin, int zEnd)
_yVelocity[index] = 0.0f;
_zVelocity[index] = 0.0f;
_density[index] = 0.0f;
+ if (_fuel) {
+ _fuel[index] = 0.0f;
+ _react[index] = 0.0f;
+ }
+ if (_color_r) {
+ _color_r[index] = 0.0f;
+ _color_g[index] = 0.0f;
+ _color_b[index] = 0.0f;
+ }
}
if (zEnd == _zRes)
@@ -735,6 +892,15 @@ void FLUID_3D::wipeBoundariesSL(int zBegin, int zEnd)
_yVelocity[indexx] = 0.0f;
_zVelocity[indexx] = 0.0f;
_density[indexx] = 0.0f;
+ if (_fuel) {
+ _fuel[index] = 0.0f;
+ _react[index] = 0.0f;
+ }
+ if (_color_r) {
+ _color_r[index] = 0.0f;
+ _color_g[index] = 0.0f;
+ _color_b[index] = 0.0f;
+ }
}
}
@@ -781,35 +947,6 @@ void FLUID_3D::project()
if(!_domainBcTop) setNeumannZ(_zVelocity, _res, 0, _zRes);
else setZeroZ(_zVelocity, _res, 0, _zRes);
- /*
- {
- float maxx = 0, maxy = 0, maxz = 0;
- for(unsigned int i = 0; i < _xRes * _yRes * _zRes; i++)
- {
- if(_xVelocity[i] > maxx)
- maxx = _xVelocity[i];
- if(_yVelocity[i] > maxy)
- maxy = _yVelocity[i];
- if(_zVelocity[i] > maxz)
- maxz = _zVelocity[i];
- }
- printf("Max velx: %f, vely: %f, velz: %f\n", maxx, maxy, maxz);
- }
- */
-
- /*
- {
- float maxvalue = 0;
- for(unsigned int i = 0; i < _xRes * _yRes * _zRes; i++)
- {
- if(_heat[i] > maxvalue)
- maxvalue = _heat[i];
-
- }
- printf("Max heat: %f\n", maxvalue);
- }
- */
-
// calculate divergence
index = _slabSize + _xRes + 1;
for (z = 1; z < _zRes - 1; z++, index += 2 * _xRes)
@@ -910,21 +1047,52 @@ void FLUID_3D::project()
setObstaclePressure(_pressure, 0, _zRes);
// project out solution
+ // New idea for code from NVIDIA graphic gems 3 - DG
float invDx = 1.0f / _dx;
index = _slabSize + _xRes + 1;
for (z = 1; z < _zRes - 1; z++, index += 2 * _xRes)
for (y = 1; y < _yRes - 1; y++, index += 2)
for (x = 1; x < _xRes - 1; x++, index++)
{
+ float vMask[3] = {1.0f, 1.0f, 1.0f}, vObst[3] = {0, 0, 0};
+ float vR = 0.0f, vL = 0.0f, vT = 0.0f, vB = 0.0f, vD = 0.0f, vU = 0.0f;
+
+ float pC = _pressure[index]; // center
+ float pR = _pressure[index + 1]; // right
+ float pL = _pressure[index - 1]; // left
+ float pU = _pressure[index + _xRes]; // Up
+ float pD = _pressure[index - _xRes]; // Down
+ float pT = _pressure[index + _slabSize]; // top
+ float pB = _pressure[index - _slabSize]; // bottom
+
if(!_obstacles[index])
{
- _xVelocity[index] -= 0.5f * (_pressure[index + 1] - _pressure[index - 1]) * invDx;
- _yVelocity[index] -= 0.5f * (_pressure[index + _xRes] - _pressure[index - _xRes]) * invDx;
- _zVelocity[index] -= 0.5f * (_pressure[index + _slabSize] - _pressure[index - _slabSize]) * invDx;
+ // DG TODO: What if obstacle is left + right and one of them is moving?
+ if(_obstacles[index+1]) { pR = pC; vObst[0] = _xVelocityOb[index + 1]; vMask[0] = 0; }
+ if(_obstacles[index-1]) { pL = pC; vObst[0] = _xVelocityOb[index - 1]; vMask[0] = 0; }
+ if(_obstacles[index+_xRes]) { pU = pC; vObst[1] = _yVelocityOb[index + _xRes]; vMask[1] = 0; }
+ if(_obstacles[index-_xRes]) { pD = pC; vObst[1] = _yVelocityOb[index - _xRes]; vMask[1] = 0; }
+ if(_obstacles[index+_slabSize]) { pT = pC; vObst[2] = _zVelocityOb[index + _slabSize]; vMask[2] = 0; }
+ if(_obstacles[index-_slabSize]) { pB = pC; vObst[2] = _zVelocityOb[index - _slabSize]; vMask[2] = 0; }
+
+ _xVelocity[index] -= 0.5f * (pR - pL) * invDx;
+ _yVelocity[index] -= 0.5f * (pU - pD) * invDx;
+ _zVelocity[index] -= 0.5f * (pT - pB) * invDx;
+
+ _xVelocity[index] = (vMask[0] * _xVelocity[index]) + vObst[0];
+ _yVelocity[index] = (vMask[1] * _yVelocity[index]) + vObst[1];
+ _zVelocity[index] = (vMask[2] * _zVelocity[index]) + vObst[2];
+ }
+ else
+ {
+ _xVelocity[index] = _xVelocityOb[index];
+ _yVelocity[index] = _yVelocityOb[index];
+ _zVelocity[index] = _zVelocityOb[index];
}
}
- setObstacleVelocity(0, _zRes);
+ // DG: was enabled in original code but now we do this later
+ // setObstacleVelocity(0, _zRes);
if (_pressure) delete[] _pressure;
if (_divergence) delete[] _divergence;
@@ -1007,7 +1175,6 @@ void FLUID_3D::diffuseHeat()
for (int x = 0; x < _totalCells; x++)
if (_obstacles[x])
_heat[x] = 0.0f;
-
}
//////////////////////////////////////////////////////////////////////
@@ -1175,7 +1342,7 @@ void FLUID_3D::setObstacleBoundaries(float *_pressure, int zBegin, int zEnd)
//////////////////////////////////////////////////////////////////////
// add buoyancy forces
//////////////////////////////////////////////////////////////////////
-void FLUID_3D::addBuoyancy(float *heat, float *density, int zBegin, int zEnd)
+void FLUID_3D::addBuoyancy(float *heat, float *density, float gravity[3], int zBegin, int zEnd)
{
int index = zBegin*_slabSize;
@@ -1183,17 +1350,26 @@ void FLUID_3D::addBuoyancy(float *heat, float *density, int zBegin, int zEnd)
for (int y = 0; y < _yRes; y++)
for (int x = 0; x < _xRes; x++, index++)
{
- _zForce[index] += *_alpha * density[index] + (*_beta * (heat[index] - _tempAmb)); // DG: was _yForce, changed for Blender
+ float buoyancy = *_alpha * density[index] + (*_beta * (((heat) ? heat[index] : 0.0f) - _tempAmb));
+ _xForce[index] -= gravity[0] * buoyancy;
+ _yForce[index] -= gravity[1] * buoyancy;
+ _zForce[index] -= gravity[2] * buoyancy;
}
}
+
//////////////////////////////////////////////////////////////////////
// add vorticity to the force field
//////////////////////////////////////////////////////////////////////
+#define VORT_VEL(i, j) \
+ ((_obstacles[obpos[(i)]] & 8) ? ((abs(objvelocity[(j)][obpos[(i)]]) > FLT_EPSILON) ? objvelocity[(j)][obpos[(i)]] : velocity[(j)][index]) : velocity[(j)][obpos[(i)]])
+
void FLUID_3D::addVorticity(int zBegin, int zEnd)
{
+ // set flame vorticity from RNA value
+ float flame_vorticity = (*_flame_vorticity)/_constantScaling;
//int x,y,z,index;
- if(_vorticityEps<=0.) return;
+ if(_vorticityEps+flame_vorticity<=0.) return;
int _blockSize=zEnd-zBegin;
int _blockTotalCells = _slabSize * (_blockSize+2);
@@ -1225,9 +1401,18 @@ void FLUID_3D::addVorticity(int zBegin, int zEnd)
float gridSize = 0.5f / _dx;
//index = _slabSize + _xRes + 1;
+ float *velocity[3];
+ float *objvelocity[3];
- size_t vIndex=_xRes + 1;
+ velocity[0] = _xVelocity;
+ velocity[1] = _yVelocity;
+ velocity[2] = _zVelocity;
+
+ objvelocity[0] = _xVelocityOb;
+ objvelocity[1] = _yVelocityOb;
+ objvelocity[2] = _zVelocityOb;
+ size_t vIndex=_xRes + 1;
for (int z = zBegin + bb1; z < (zEnd - bt1); z++)
{
size_t index = index_ +(z-1)*_slabSize;
@@ -1237,25 +1422,47 @@ void FLUID_3D::addVorticity(int zBegin, int zEnd)
{
for (int x = 1; x < _xRes - 1; x++, index++)
{
+ if (!_obstacles[index])
+ {
+ int obpos[6];
+
+ obpos[0] = (_obstacles[index + _xRes] == 1) ? index : index + _xRes; // up
+ obpos[1] = (_obstacles[index - _xRes] == 1) ? index : index - _xRes; // down
+ float dy = (obpos[0] == index || obpos[1] == index) ? 1.0f / _dx : gridSize;
+
+ obpos[2] = (_obstacles[index + _slabSize] == 1) ? index : index + _slabSize; // out
+ obpos[3] = (_obstacles[index - _slabSize] == 1) ? index : index - _slabSize; // in
+ float dz = (obpos[2] == index || obpos[3] == index) ? 1.0f / _dx : gridSize;
+
+ obpos[4] = (_obstacles[index + 1] == 1) ? index : index + 1; // right
+ obpos[5] = (_obstacles[index - 1] == 1) ? index : index - 1; // left
+ float dx = (obpos[4] == index || obpos[5] == index) ? 1.0f / _dx : gridSize;
+
+ float xV[2], yV[2], zV[2];
+
+ zV[1] = VORT_VEL(0, 2);
+ zV[0] = VORT_VEL(1, 2);
+ yV[1] = VORT_VEL(2, 1);
+ yV[0] = VORT_VEL(3, 1);
+ _xVorticity[vIndex] = (zV[1] - zV[0]) * dy + (-yV[1] + yV[0]) * dz;
+
+ xV[1] = VORT_VEL(2, 0);
+ xV[0] = VORT_VEL(3, 0);
+ zV[1] = VORT_VEL(4, 2);
+ zV[0] = VORT_VEL(5, 2);
+ _yVorticity[vIndex] = (xV[1] - xV[0]) * dz + (-zV[1] + zV[0]) * dx;
+
+ yV[1] = VORT_VEL(4, 1);
+ yV[0] = VORT_VEL(5, 1);
+ xV[1] = VORT_VEL(0, 0);
+ xV[0] = VORT_VEL(1, 0);
+ _zVorticity[vIndex] = (yV[1] - yV[0]) * dx + (-xV[1] + xV[0])* dy;
- int up = _obstacles[index + _xRes] ? index : index + _xRes;
- int down = _obstacles[index - _xRes] ? index : index - _xRes;
- float dy = (up == index || down == index) ? 1.0f / _dx : gridSize;
- int out = _obstacles[index + _slabSize] ? index : index + _slabSize;
- int in = _obstacles[index - _slabSize] ? index : index - _slabSize;
- float dz = (out == index || in == index) ? 1.0f / _dx : gridSize;
- int right = _obstacles[index + 1] ? index : index + 1;
- int left = _obstacles[index - 1] ? index : index - 1;
- float dx = (right == index || left == index) ? 1.0f / _dx : gridSize;
-
- _xVorticity[vIndex] = (_zVelocity[up] - _zVelocity[down]) * dy + (-_yVelocity[out] + _yVelocity[in]) * dz;
- _yVorticity[vIndex] = (_xVelocity[out] - _xVelocity[in]) * dz + (-_zVelocity[right] + _zVelocity[left]) * dx;
- _zVorticity[vIndex] = (_yVelocity[right] - _yVelocity[left]) * dx + (-_xVelocity[up] + _xVelocity[down])* dy;
-
- _vorticity[vIndex] = sqrtf(_xVorticity[vIndex] * _xVorticity[vIndex] +
+ _vorticity[vIndex] = sqrtf(_xVorticity[vIndex] * _xVorticity[vIndex] +
_yVorticity[vIndex] * _yVorticity[vIndex] +
_zVorticity[vIndex] * _zVorticity[vIndex]);
+ }
vIndex++;
}
vIndex+=2;
@@ -1284,15 +1491,18 @@ void FLUID_3D::addVorticity(int zBegin, int zEnd)
{
float N[3];
- int up = _obstacles[index + _xRes] ? vIndex : vIndex + _xRes;
- int down = _obstacles[index - _xRes] ? vIndex : vIndex - _xRes;
+ int up = (_obstacles[index + _xRes] == 1) ? vIndex : vIndex + _xRes;
+ int down = (_obstacles[index - _xRes] == 1) ? vIndex : vIndex - _xRes;
float dy = (up == vIndex || down == vIndex) ? 1.0f / _dx : gridSize;
- int out = _obstacles[index + _slabSize] ? vIndex : vIndex + _slabSize;
- int in = _obstacles[index - _slabSize] ? vIndex : vIndex - _slabSize;
+
+ int out = (_obstacles[index + _slabSize] == 1) ? vIndex : vIndex + _slabSize;
+ int in = (_obstacles[index - _slabSize] == 1) ? vIndex : vIndex - _slabSize;
float dz = (out == vIndex || in == vIndex) ? 1.0f / _dx : gridSize;
- int right = _obstacles[index + 1] ? vIndex : vIndex + 1;
- int left = _obstacles[index - 1] ? vIndex : vIndex - 1;
+
+ int right = (_obstacles[index + 1] == 1) ? vIndex : vIndex + 1;
+ int left = (_obstacles[index - 1] == 1) ? vIndex : vIndex - 1;
float dx = (right == vIndex || left == vIndex) ? 1.0f / _dx : gridSize;
+
N[0] = (_vorticity[right] - _vorticity[left]) * dx;
N[1] = (_vorticity[up] - _vorticity[down]) * dy;
N[2] = (_vorticity[out] - _vorticity[in]) * dz;
@@ -1300,14 +1510,15 @@ void FLUID_3D::addVorticity(int zBegin, int zEnd)
float magnitude = sqrtf(N[0] * N[0] + N[1] * N[1] + N[2] * N[2]);
if (magnitude > FLT_EPSILON)
{
+ float flame_vort = (_fuel) ? _fuel[index]*flame_vorticity : 0.0f;
magnitude = 1.0f / magnitude;
N[0] *= magnitude;
N[1] *= magnitude;
N[2] *= magnitude;
- _xForce[index] += (N[1] * _zVorticity[vIndex] - N[2] * _yVorticity[vIndex]) * _dx * eps;
- _yForce[index] += (N[2] * _xVorticity[vIndex] - N[0] * _zVorticity[vIndex]) * _dx * eps;
- _zForce[index] += (N[0] * _yVorticity[vIndex] - N[1] * _xVorticity[vIndex]) * _dx * eps;
+ _xForce[index] += (N[1] * _zVorticity[vIndex] - N[2] * _yVorticity[vIndex]) * _dx * (eps + flame_vort);
+ _yForce[index] += (N[2] * _xVorticity[vIndex] - N[0] * _zVorticity[vIndex]) * _dx * (eps + flame_vort);
+ _zForce[index] += (N[0] * _yVorticity[vIndex] - N[1] * _xVorticity[vIndex]) * _dx * (eps + flame_vort);
}
} // if
vIndex++;
@@ -1328,14 +1539,9 @@ void FLUID_3D::advectMacCormackBegin(int zBegin, int zEnd)
{
Vec3Int res = Vec3Int(_xRes,_yRes,_zRes);
- if(!_domainBcLeft) copyBorderX(_xVelocityOld, res, zBegin, zEnd);
- else setZeroX(_xVelocityOld, res, zBegin, zEnd);
-
- if(!_domainBcFront) copyBorderY(_yVelocityOld, res, zBegin, zEnd);
- else setZeroY(_yVelocityOld, res, zBegin, zEnd);
-
- if(!_domainBcTop) copyBorderZ(_zVelocityOld, res, zBegin, zEnd);
- else setZeroZ(_zVelocityOld, res, zBegin, zEnd);
+ setZeroX(_xVelocityOld, res, zBegin, zEnd);
+ setZeroY(_yVelocityOld, res, zBegin, zEnd);
+ setZeroZ(_zVelocityOld, res, zBegin, zEnd);
}
//////////////////////////////////////////////////////////////////////
@@ -1355,7 +1561,18 @@ void FLUID_3D::advectMacCormackEnd1(int zBegin, int zEnd)
// advectFieldMacCormack1(dt, xVelocity, yVelocity, zVelocity, oldField, newField, res)
advectFieldMacCormack1(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _densityOld, _densityTemp, res, zBegin, zEnd);
- advectFieldMacCormack1(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _heatOld, _heatTemp, res, zBegin, zEnd);
+ if (_heat) {
+ advectFieldMacCormack1(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _heatOld, _heatTemp, res, zBegin, zEnd);
+ }
+ if (_fuel) {
+ advectFieldMacCormack1(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _fuelOld, _fuelTemp, res, zBegin, zEnd);
+ advectFieldMacCormack1(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _reactOld, _reactTemp, res, zBegin, zEnd);
+ }
+ if (_color_r) {
+ advectFieldMacCormack1(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _color_rOld, _color_rTemp, res, zBegin, zEnd);
+ advectFieldMacCormack1(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _color_gOld, _color_gTemp, res, zBegin, zEnd);
+ advectFieldMacCormack1(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _color_bOld, _color_bTemp, res, zBegin, zEnd);
+ }
advectFieldMacCormack1(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _xVelocityOld, _xVelocity, res, zBegin, zEnd);
advectFieldMacCormack1(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _yVelocityOld, _yVelocity, res, zBegin, zEnd);
advectFieldMacCormack1(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _zVelocityOld, _zVelocity, res, zBegin, zEnd);
@@ -1371,17 +1588,30 @@ void FLUID_3D::advectMacCormackEnd2(int zBegin, int zEnd)
const float dt0 = _dt / _dx;
Vec3Int res = Vec3Int(_xRes,_yRes,_zRes);
- // use force array as temp arrays
+ // use force array as temp array
float* t1 = _xForce;
// advectFieldMacCormack2(dt, xVelocity, yVelocity, zVelocity, oldField, newField, tempfield, temp, res, obstacles)
+ /* finish advection */
advectFieldMacCormack2(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _densityOld, _density, _densityTemp, t1, res, _obstacles, zBegin, zEnd);
- advectFieldMacCormack2(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _heatOld, _heat, _heatTemp, t1, res, _obstacles, zBegin, zEnd);
+ if (_heat) {
+ advectFieldMacCormack2(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _heatOld, _heat, _heatTemp, t1, res, _obstacles, zBegin, zEnd);
+ }
+ if (_fuel) {
+ advectFieldMacCormack2(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _fuelOld, _fuel, _fuelTemp, t1, res, _obstacles, zBegin, zEnd);
+ advectFieldMacCormack2(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _reactOld, _react, _reactTemp, t1, res, _obstacles, zBegin, zEnd);
+ }
+ if (_color_r) {
+ advectFieldMacCormack2(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _color_rOld, _color_r, _color_rTemp, t1, res, _obstacles, zBegin, zEnd);
+ advectFieldMacCormack2(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _color_gOld, _color_g, _color_gTemp, t1, res, _obstacles, zBegin, zEnd);
+ advectFieldMacCormack2(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _color_bOld, _color_b, _color_bTemp, t1, res, _obstacles, zBegin, zEnd);
+ }
advectFieldMacCormack2(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _xVelocityOld, _xVelocityTemp, _xVelocity, t1, res, _obstacles, zBegin, zEnd);
advectFieldMacCormack2(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _yVelocityOld, _yVelocityTemp, _yVelocity, t1, res, _obstacles, zBegin, zEnd);
advectFieldMacCormack2(dt0, _xVelocityOld, _yVelocityOld, _zVelocityOld, _zVelocityOld, _zVelocityTemp, _zVelocity, t1, res, _obstacles, zBegin, zEnd);
+ /* set boundary conditions for velocity */
if(!_domainBcLeft) copyBorderX(_xVelocityTemp, res, zBegin, zEnd);
else setZeroX(_xVelocityTemp, res, zBegin, zEnd);
@@ -1391,40 +1621,71 @@ void FLUID_3D::advectMacCormackEnd2(int zBegin, int zEnd)
if(!_domainBcTop) copyBorderZ(_zVelocityTemp, res, zBegin, zEnd);
else setZeroZ(_zVelocityTemp, res, zBegin, zEnd);
+ /* clear data boundaries */
setZeroBorder(_density, res, zBegin, zEnd);
- setZeroBorder(_heat, res, zBegin, zEnd);
-#if 0
- {
- const size_t index_ = _slabSize + _xRes + 1;
- int bb=0;
- int bt=0;
+ if (_fuel) {
+ setZeroBorder(_fuel, res, zBegin, zEnd);
+ setZeroBorder(_react, res, zBegin, zEnd);
+ }
+ if (_color_r) {
+ setZeroBorder(_color_r, res, zBegin, zEnd);
+ setZeroBorder(_color_g, res, zBegin, zEnd);
+ setZeroBorder(_color_b, res, zBegin, zEnd);
+ }
+}
- if (zBegin == 0) {bb = 1;}
- if (zEnd == _zRes) {bt = 1;}
-
- for (int z = zBegin + bb; z < zEnd - bt; z++)
+
+void FLUID_3D::processBurn(float *fuel, float *smoke, float *react, float *flame, float *heat,
+ float *r, float *g, float *b, int total_cells, float dt)
+{
+ float burning_rate = *_burning_rate;
+ float flame_smoke = *_flame_smoke;
+ float ignition_point = *_ignition_temp;
+ float temp_max = *_max_temp;
+
+ for (int index = 0; index < total_cells; index++)
{
- size_t index = index_ +(z-1)*_slabSize;
+ float orig_fuel = fuel[index];
+ float orig_smoke = smoke[index];
+ float smoke_emit = 0.0f;
+ float react_coord = 0.0f;
+
+ /* process fuel */
+ fuel[index] -= burning_rate * dt;
+ if (fuel[index] < 0.0f) fuel[index] = 0.0f;
+ /* process reaction coordinate */
+ if (orig_fuel) {
+ react[index] *= fuel[index]/orig_fuel;
+ react_coord = react[index];
+ }
+ else {
+ react[index] = 0.0f;
+ }
- for (int y = 1; y < _yRes - 1; y++, index += 2)
- {
- for (int x = 1; x < _xRes - 1; x++, index++)
- {
- // clean custom velocities from moving obstacles again
- if (_obstacles[index])
- {
- _xVelocity[index] =
- _yVelocity[index] =
- _zVelocity[index] = 0.0f;
- }
- }
+ /* emit smoke based on fuel burn rate and "flame_smoke" factor */
+ smoke_emit = (orig_fuel < 1.0f) ? (1.0f - orig_fuel)*0.5f : 0.0f;
+ smoke_emit = (smoke_emit + 0.5f) * (orig_fuel-fuel[index]) * 0.1f * flame_smoke;
+ smoke[index] += smoke_emit;
+ CLAMP(smoke[index], 0.0f, 1.0f);
+
+ /* model flame temperature curve from the reaction coordinate (fuel) */
+ if (react_coord>0.0f) {
+ /* do a smooth falloff for rest of the values */
+ flame[index] = pow(react_coord, 0.5f);
+ }
+ else
+ flame[index] = 0.0f;
+
+ /* set fluid temperature from the flame temperature profile */
+ if (heat && flame[index])
+ heat[index] = (1.0f-flame[index])*ignition_point + flame[index]*temp_max;
+
+ /* mix new color */
+ if (r && smoke_emit) {
+ float smoke_factor = smoke[index]/(orig_smoke+smoke_emit);
+ r[index] = (r[index] + _flame_smoke_color[0] * smoke_emit) * smoke_factor;
+ g[index] = (g[index] + _flame_smoke_color[1] * smoke_emit) * smoke_factor;
+ b[index] = (b[index] + _flame_smoke_color[2] * smoke_emit) * smoke_factor;
}
}
- }
-#endif
-
- /*int begin=zBegin * _slabSize;
- int end=begin + (zEnd - zBegin) * _slabSize;
- for (int x = begin; x < end; x++)
- _xForce[x] = _yForce[x] = 0.0f;*/
}
diff --git a/intern/smoke/intern/FLUID_3D.h b/intern/smoke/intern/FLUID_3D.h
index ac77148ce84..8cadf3bc989 100644
--- a/intern/smoke/intern/FLUID_3D.h
+++ b/intern/smoke/intern/FLUID_3D.h
@@ -46,11 +46,16 @@ class WTURBULENCE;
class FLUID_3D
{
public:
- FLUID_3D(int *res, /* int amplify, */ float *p0, float dtdef);
+ FLUID_3D(int *res, float dx, float dtdef, int init_heat, int init_fire, int init_colors);
FLUID_3D() {};
virtual ~FLUID_3D();
- void initBlenderRNA(float *alpha, float *beta, float *dt_factor, float *vorticity, int *border_colli);
+ void initHeat();
+ void initFire();
+ void initColors(float init_r, float init_g, float init_b);
+
+ void initBlenderRNA(float *alpha, float *beta, float *dt_factor, float *vorticity, int *border_colli, float *burning_rate,
+ float *flame_smoke, float *flame_smoke_color, float *flame_vorticity, float *ignition_temp, float *max_temp);
// create & allocate vector noise advection
void initVectorNoise(int amplify);
@@ -58,7 +63,7 @@ class FLUID_3D
void addSmokeColumn();
static void addSmokeTestCase(float* field, Vec3Int res);
- void step(float dt);
+ void step(float dt, float gravity[3]);
void addObstacle(OBSTACLE* obstacle);
const float* xVelocity() { return _xVelocity; };
@@ -115,6 +120,27 @@ class FLUID_3D
float* _heatTemp;
float* _densityTemp;
+ // fire simulation
+ float *_flame;
+ float *_fuel;
+ float *_fuelTemp;
+ float *_fuelOld;
+ float *_react;
+ float *_reactTemp;
+ float *_reactOld;
+
+ // smoke color
+ float *_color_r;
+ float *_color_rOld;
+ float *_color_rTemp;
+ float *_color_g;
+ float *_color_gOld;
+ float *_color_gTemp;
+ float *_color_b;
+ float *_color_bOld;
+ float *_color_bTemp;
+
+
// CG fields
int _iterations;
@@ -153,14 +179,16 @@ class FLUID_3D
void wipeBoundariesSL(int zBegin, int zEnd);
void addForce(int zBegin, int zEnd);
void addVorticity(int zBegin, int zEnd);
- void addBuoyancy(float *heat, float *density, int zBegin, int zEnd);
+ void addBuoyancy(float *heat, float *density, float gravity[3], int zBegin, int zEnd);
// solver stuff
void project();
void diffuseHeat();
+ void diffuseColor();
void solvePressure(float* field, float* b, unsigned char* skip);
void solvePressurePre(float* field, float* b, unsigned char* skip);
void solveHeat(float* field, float* b, unsigned char* skip);
+ void solveDiffusion(float* field, float* b, float* factor);
// handle obstacle boundaries
@@ -174,6 +202,16 @@ class FLUID_3D
void advectMacCormackEnd1(int zBegin, int zEnd);
void advectMacCormackEnd2(int zBegin, int zEnd);
+ /* burning */
+ float *_burning_rate; // RNA pointer
+ float *_flame_smoke; // RNA pointer
+ float *_flame_smoke_color; // RNA pointer
+ float *_flame_vorticity; // RNA pointer
+ float *_ignition_temp; // RNA pointer
+ float *_max_temp; // RNA pointer
+ void processBurn(float *fuel, float *smoke, float *react, float *flame, float *heat,
+ float *r, float *g, float *b, int total_cells, float dt);
+
// boundary setting functions
static void copyBorderX(float* field, Vec3Int res, int zBegin, int zEnd);
static void copyBorderY(float* field, Vec3Int res, int zBegin, int zEnd);
diff --git a/intern/smoke/intern/FLUID_3D_SOLVERS.cpp b/intern/smoke/intern/FLUID_3D_SOLVERS.cpp
index 3cf94eb00a9..42a8b2d6923 100644
--- a/intern/smoke/intern/FLUID_3D_SOLVERS.cpp
+++ b/intern/smoke/intern/FLUID_3D_SOLVERS.cpp
@@ -165,7 +165,6 @@ void FLUID_3D::solveHeat(float* field, float* b, unsigned char* skip)
if (_Acenter) delete[] _Acenter;
}
-
void FLUID_3D::solvePressurePre(float* field, float* b, unsigned char* skip)
{
int x, y, z;
diff --git a/intern/smoke/intern/FLUID_3D_STATIC.cpp b/intern/smoke/intern/FLUID_3D_STATIC.cpp
index c7a0ddcd04c..ac485ad983a 100644
--- a/intern/smoke/intern/FLUID_3D_STATIC.cpp
+++ b/intern/smoke/intern/FLUID_3D_STATIC.cpp
@@ -92,18 +92,10 @@ void FLUID_3D::setNeumannX(float* field, Vec3Int res, int zBegin, int zEnd)
// left slab
index = y * res[0] + z * slabSize;
field[index] = field[index + 2];
- /* only allow outwards flux */
- if(field[index]>0.) field[index] = 0.;
- index += 1;
- if(field[index]>0.) field[index] = 0.;
// right slab
index = y * res[0] + z * slabSize + res[0] - 1;
field[index] = field[index - 2];
- /* only allow outwards flux */
- if(field[index]<0.) field[index] = 0.;
- index -= 1;
- if(field[index]<0.) field[index] = 0.;
}
}
@@ -120,18 +112,10 @@ void FLUID_3D::setNeumannY(float* field, Vec3Int res, int zBegin, int zEnd)
// front slab
index = x + z * slabSize;
field[index] = field[index + 2 * res[0]];
- /* only allow outwards flux */
- if(field[index]>0.) field[index] = 0.;
- index += res[0];
- if(field[index]>0.) field[index] = 0.;
// back slab
index = x + z * slabSize + slabSize - res[0];
field[index] = field[index - 2 * res[0]];
- /* only allow outwards flux */
- if(field[index]<0.) field[index] = 0.;
- index -= res[0];
- if(field[index]<0.) field[index] = 0.;
}
}
@@ -152,14 +136,6 @@ void FLUID_3D::setNeumannZ(float* field, Vec3Int res, int zBegin, int zEnd)
// front slab
index = x + y * res[0];
field[index] = field[index + 2 * slabSize];
- /* only allow outwards flux */
-
- // DG: Disable this for z-axis.
- // The problem is that smoke somehow gets sucked in again
- // from the TOP slab when this is enabled
- // if(field[index]>0.) field[index] = 0.;
- // index += slabSize;
- // if(field[index]>0.) field[index] = 0.;
}
}
@@ -170,10 +146,6 @@ void FLUID_3D::setNeumannZ(float* field, Vec3Int res, int zBegin, int zEnd)
// back slab
index = x + y * res[0] + cellsslab;
field[index] = field[index - 2 * slabSize];
- /* only allow outwards flux */
- if(field[index]<0.) field[index] = 0.;
- index -= slabSize;
- if(field[index]<0.) field[index] = 0.;
}
}
diff --git a/intern/smoke/intern/WTURBULENCE.cpp b/intern/smoke/intern/WTURBULENCE.cpp
index 671198065e8..1c89f5d681b 100644
--- a/intern/smoke/intern/WTURBULENCE.cpp
+++ b/intern/smoke/intern/WTURBULENCE.cpp
@@ -51,7 +51,7 @@ static const float persistence = 0.56123f;
//////////////////////////////////////////////////////////////////////
// constructor
//////////////////////////////////////////////////////////////////////
-WTURBULENCE::WTURBULENCE(int xResSm, int yResSm, int zResSm, int amplify, int noisetype)
+WTURBULENCE::WTURBULENCE(int xResSm, int yResSm, int zResSm, int amplify, int noisetype, int init_fire, int init_colors)
{
// if noise magnitude is below this threshold, its contribution
// is negilgible, so stop evaluating new octaves
@@ -87,12 +87,26 @@ WTURBULENCE::WTURBULENCE(int xResSm, int yResSm, int zResSm, int amplify, int no
// allocate high resolution density field
_totalStepsBig = 0;
_densityBig = new float[_totalCellsBig];
- _densityBigOld = new float[_totalCellsBig];
+ _densityBigOld = new float[_totalCellsBig];
for(int i = 0; i < _totalCellsBig; i++) {
_densityBig[i] =
_densityBigOld[i] = 0.;
}
+
+ /* fire */
+ _flameBig = _fuelBig = _fuelBigOld = NULL;
+ _reactBig = _reactBigOld = NULL;
+ if (init_fire) {
+ initFire();
+ }
+ /* colors */
+ _color_rBig = _color_rBigOld = NULL;
+ _color_gBig = _color_gBigOld = NULL;
+ _color_bBig = _color_bBigOld = NULL;
+ if (init_colors) {
+ initColors(0.0f, 0.0f, 0.0f);
+ }
// allocate & init texture coordinates
_tcU = new float[_totalCellsSm];
@@ -128,12 +142,64 @@ WTURBULENCE::WTURBULENCE(int xResSm, int yResSm, int zResSm, int amplify, int no
*/
}
+void WTURBULENCE::initFire()
+{
+ if (!_fuelBig) {
+ _flameBig = new float[_totalCellsBig];
+ _fuelBig = new float[_totalCellsBig];
+ _fuelBigOld = new float[_totalCellsBig];
+ _reactBig = new float[_totalCellsBig];
+ _reactBigOld = new float[_totalCellsBig];
+
+ for(int i = 0; i < _totalCellsBig; i++) {
+ _flameBig[i] =
+ _fuelBig[i] =
+ _fuelBigOld[i] = 0.;
+ _reactBig[i] =
+ _reactBigOld[i] = 0.;
+ }
+ }
+}
+
+void WTURBULENCE::initColors(float init_r, float init_g, float init_b)
+{
+ if (!_color_rBig) {
+ _color_rBig = new float[_totalCellsBig];
+ _color_rBigOld = new float[_totalCellsBig];
+ _color_gBig = new float[_totalCellsBig];
+ _color_gBigOld = new float[_totalCellsBig];
+ _color_bBig = new float[_totalCellsBig];
+ _color_bBigOld = new float[_totalCellsBig];
+
+ for(int i = 0; i < _totalCellsBig; i++) {
+ _color_rBig[i] = _densityBig[i] * init_r;
+ _color_rBigOld[i] = 0.0f;
+ _color_gBig[i] = _densityBig[i] * init_g;
+ _color_gBigOld[i] = 0.0f;
+ _color_bBig[i] = _densityBig[i] * init_b;
+ _color_bBigOld[i] = 0.0f;
+ }
+ }
+}
+
//////////////////////////////////////////////////////////////////////
// destructor
//////////////////////////////////////////////////////////////////////
WTURBULENCE::~WTURBULENCE() {
delete[] _densityBig;
delete[] _densityBigOld;
+ if (_flameBig) delete[] _flameBig;
+ if (_fuelBig) delete[] _fuelBig;
+ if (_fuelBigOld) delete[] _fuelBigOld;
+ if (_reactBig) delete[] _reactBig;
+ if (_reactBigOld) delete[] _reactBigOld;
+
+ if (_color_rBig) delete[] _color_rBig;
+ if (_color_rBigOld) delete[] _color_rBigOld;
+ if (_color_gBig) delete[] _color_gBig;
+ if (_color_gBigOld) delete[] _color_gBigOld;
+ if (_color_bBig) delete[] _color_bBig;
+ if (_color_bBigOld) delete[] _color_bBigOld;
delete[] _tcU;
delete[] _tcV;
@@ -757,8 +823,10 @@ void WTURBULENCE::stepTurbulenceFull(float dtOrg, float* xvel, float* yvel, floa
// enlarge timestep to match grid
const float dt = dtOrg * _amplify;
const float invAmp = 1.0f / _amplify;
- float *tempBig1 = (float *)calloc(_totalCellsBig, sizeof(float));
- float *tempBig2 = (float *)calloc(_totalCellsBig, sizeof(float));
+ float *tempFuelBig = NULL, *tempReactBig = NULL;
+ float *tempColor_rBig = NULL, *tempColor_gBig = NULL, *tempColor_bBig = NULL;
+ float *tempDensityBig = (float *)calloc(_totalCellsBig, sizeof(float));
+ float *tempBig = (float *)calloc(_totalCellsBig, sizeof(float));
float *bigUx = (float *)calloc(_totalCellsBig, sizeof(float));
float *bigUy = (float *)calloc(_totalCellsBig, sizeof(float));
float *bigUz = (float *)calloc(_totalCellsBig, sizeof(float));
@@ -767,11 +835,21 @@ void WTURBULENCE::stepTurbulenceFull(float dtOrg, float* xvel, float* yvel, floa
float *eigMin = (float *)calloc(_totalCellsSm, sizeof(float));
float *eigMax = (float *)calloc(_totalCellsSm, sizeof(float));
+ if (_fuelBig) {
+ tempFuelBig = (float *)calloc(_totalCellsBig, sizeof(float));
+ tempReactBig = (float *)calloc(_totalCellsBig, sizeof(float));
+ }
+ if (_color_rBig) {
+ tempColor_rBig = (float *)calloc(_totalCellsBig, sizeof(float));
+ tempColor_gBig = (float *)calloc(_totalCellsBig, sizeof(float));
+ tempColor_bBig = (float *)calloc(_totalCellsBig, sizeof(float));
+ }
+
memset(_tcTemp, 0, sizeof(float)*_totalCellsSm);
// prepare textures
- advectTextureCoordinates(dtOrg, xvel,yvel,zvel, tempBig1, tempBig2);
+ advectTextureCoordinates(dtOrg, xvel,yvel,zvel, tempDensityBig, tempBig);
// do wavelet decomposition of energy
computeEnergy(_energy, xvel, yvel, zvel, obstacles);
@@ -972,6 +1050,11 @@ void WTURBULENCE::stepTurbulenceFull(float dtOrg, float* xvel, float* yvel, floa
// prepare density for an advection
SWAP_POINTERS(_densityBig, _densityBigOld);
+ SWAP_POINTERS(_fuelBig, _fuelBigOld);
+ SWAP_POINTERS(_reactBig, _reactBigOld);
+ SWAP_POINTERS(_color_rBig, _color_rBigOld);
+ SWAP_POINTERS(_color_gBig, _color_gBigOld);
+ SWAP_POINTERS(_color_bBig, _color_bBigOld);
// based on the maximum velocity present, see if we need to substep,
// but cap the maximum number of substeps to 5
@@ -1017,7 +1100,21 @@ void WTURBULENCE::stepTurbulenceFull(float dtOrg, float* xvel, float* yvel, floa
int zEnd = (int)((float)(i+1)*partSize + 0.5f);
#endif
FLUID_3D::advectFieldMacCormack1(dtSubdiv, bigUx, bigUy, bigUz,
- _densityBigOld, tempBig1, _resBig, zBegin, zEnd);
+ _densityBigOld, tempDensityBig, _resBig, zBegin, zEnd);
+ if (_fuelBig) {
+ FLUID_3D::advectFieldMacCormack1(dtSubdiv, bigUx, bigUy, bigUz,
+ _fuelBigOld, tempFuelBig, _resBig, zBegin, zEnd);
+ FLUID_3D::advectFieldMacCormack1(dtSubdiv, bigUx, bigUy, bigUz,
+ _reactBigOld, tempReactBig, _resBig, zBegin, zEnd);
+ }
+ if (_color_rBig) {
+ FLUID_3D::advectFieldMacCormack1(dtSubdiv, bigUx, bigUy, bigUz,
+ _color_rBigOld, tempColor_rBig, _resBig, zBegin, zEnd);
+ FLUID_3D::advectFieldMacCormack1(dtSubdiv, bigUx, bigUy, bigUz,
+ _color_gBigOld, tempColor_gBig, _resBig, zBegin, zEnd);
+ FLUID_3D::advectFieldMacCormack1(dtSubdiv, bigUx, bigUy, bigUz,
+ _color_bBigOld, tempColor_bBig, _resBig, zBegin, zEnd);
+ }
#if PARALLEL==1
}
@@ -1030,18 +1127,43 @@ void WTURBULENCE::stepTurbulenceFull(float dtOrg, float* xvel, float* yvel, floa
int zEnd = (int)((float)(i+1)*partSize + 0.5f);
#endif
FLUID_3D::advectFieldMacCormack2(dtSubdiv, bigUx, bigUy, bigUz,
- _densityBigOld, _densityBig, tempBig1, tempBig2, _resBig, NULL, zBegin, zEnd);
+ _densityBigOld, _densityBig, tempDensityBig, tempBig, _resBig, NULL, zBegin, zEnd);
+ if (_fuelBig) {
+ FLUID_3D::advectFieldMacCormack2(dtSubdiv, bigUx, bigUy, bigUz,
+ _fuelBigOld, _fuelBig, tempFuelBig, tempBig, _resBig, NULL, zBegin, zEnd);
+ FLUID_3D::advectFieldMacCormack2(dtSubdiv, bigUx, bigUy, bigUz,
+ _reactBigOld, _reactBig, tempReactBig, tempBig, _resBig, NULL, zBegin, zEnd);
+ }
+ if (_color_rBig) {
+ FLUID_3D::advectFieldMacCormack2(dtSubdiv, bigUx, bigUy, bigUz,
+ _color_rBigOld, _color_rBig, tempColor_rBig, tempBig, _resBig, NULL, zBegin, zEnd);
+ FLUID_3D::advectFieldMacCormack2(dtSubdiv, bigUx, bigUy, bigUz,
+ _color_gBigOld, _color_gBig, tempColor_gBig, tempBig, _resBig, NULL, zBegin, zEnd);
+ FLUID_3D::advectFieldMacCormack2(dtSubdiv, bigUx, bigUy, bigUz,
+ _color_bBigOld, _color_bBig, tempColor_bBig, tempBig, _resBig, NULL, zBegin, zEnd);
+ }
#if PARALLEL==1
}
}
#endif
- if (substep < totalSubsteps - 1)
+ if (substep < totalSubsteps - 1) {
SWAP_POINTERS(_densityBig, _densityBigOld);
+ SWAP_POINTERS(_fuelBig, _fuelBigOld);
+ SWAP_POINTERS(_reactBig, _reactBigOld);
+ SWAP_POINTERS(_color_rBig, _color_rBigOld);
+ SWAP_POINTERS(_color_gBig, _color_gBigOld);
+ SWAP_POINTERS(_color_bBig, _color_bBigOld);
+ }
} // substep
- free(tempBig1);
- free(tempBig2);
+ free(tempDensityBig);
+ if (tempFuelBig) free(tempFuelBig);
+ if (tempReactBig) free(tempReactBig);
+ if (tempColor_rBig) free(tempColor_rBig);
+ if (tempColor_gBig) free(tempColor_gBig);
+ if (tempColor_bBig) free(tempColor_bBig);
+ free(tempBig);
free(bigUx);
free(bigUy);
free(bigUz);
@@ -1050,6 +1172,15 @@ void WTURBULENCE::stepTurbulenceFull(float dtOrg, float* xvel, float* yvel, floa
// wipe the density borders
FLUID_3D::setZeroBorder(_densityBig, _resBig, 0 , _resBig[2]);
+ if (_fuelBig) {
+ FLUID_3D::setZeroBorder(_fuelBig, _resBig, 0 , _resBig[2]);
+ FLUID_3D::setZeroBorder(_reactBig, _resBig, 0 , _resBig[2]);
+ }
+ if (_color_rBig) {
+ FLUID_3D::setZeroBorder(_color_rBig, _resBig, 0 , _resBig[2]);
+ FLUID_3D::setZeroBorder(_color_gBig, _resBig, 0 , _resBig[2]);
+ FLUID_3D::setZeroBorder(_color_bBig, _resBig, 0 , _resBig[2]);
+ }
// reset texture coordinates now in preparation for next timestep
// Shouldn't do this before generating the noise because then the
diff --git a/intern/smoke/intern/WTURBULENCE.h b/intern/smoke/intern/WTURBULENCE.h
index f31ca100fdf..1655bd95d32 100644
--- a/intern/smoke/intern/WTURBULENCE.h
+++ b/intern/smoke/intern/WTURBULENCE.h
@@ -36,10 +36,13 @@ class WTURBULENCE
{
public:
// both config files can be NULL, altCfg might override values from noiseCfg
- WTURBULENCE(int xResSm, int yResSm, int zResSm, int amplify, int noisetype);
+ WTURBULENCE(int xResSm, int yResSm, int zResSm, int amplify, int noisetype, int init_fire, int init_colors);
/// destructor
virtual ~WTURBULENCE();
+
+ void initFire();
+ void initColors(float init_r, float init_g, float init_b);
void setNoise(int type);
void initBlenderRNA(float *strength);
@@ -63,6 +66,8 @@ class WTURBULENCE
// access functions
inline float* getDensityBig() { return _densityBig; }
+ inline float* getFlameBig() { return _flameBig; }
+ inline float* getFuelBig() { return _fuelBig; }
inline float* getArrayTcU() { return _tcU; }
inline float* getArrayTcV() { return _tcV; }
inline float* getArrayTcW() { return _tcW; }
@@ -111,6 +116,18 @@ class WTURBULENCE
float* _densityBig;
float* _densityBigOld;
+ float* _flameBig;
+ float* _fuelBig;
+ float* _fuelBigOld;
+ float* _reactBig;
+ float* _reactBigOld;
+
+ float* _color_rBig;
+ float* _color_rBigOld;
+ float* _color_gBig;
+ float* _color_gBigOld;
+ float* _color_bBig;
+ float* _color_bBigOld;
// texture coordinates for noise
float* _tcU;
diff --git a/intern/smoke/intern/smoke_API.cpp b/intern/smoke/intern/smoke_API.cpp
index b45fef26504..6011de0bddb 100644
--- a/intern/smoke/intern/smoke_API.cpp
+++ b/intern/smoke/intern/smoke_API.cpp
@@ -28,30 +28,26 @@
* \ingroup smoke
*/
-
#include "FLUID_3D.h"
#include "WTURBULENCE.h"
+#include "spectrum.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
-// y in smoke is z in blender
-extern "C" FLUID_3D *smoke_init(int *res, float *p0, float dtdef)
-{
- // smoke lib uses y as top-bottom/vertical axis where blender uses z
- FLUID_3D *fluid = new FLUID_3D(res, p0, dtdef);
-
- // printf("xres: %d, yres: %d, zres: %d\n", res[0], res[1], res[2]);
+#include "../extern/smoke_API.h" /* to ensure valid prototypes */
+extern "C" FLUID_3D *smoke_init(int *res, float dx, float dtdef, int use_heat, int use_fire, int use_colors)
+{
+ FLUID_3D *fluid = new FLUID_3D(res, dx, dtdef, use_heat, use_fire, use_colors);
return fluid;
}
-extern "C" WTURBULENCE *smoke_turbulence_init(int *res, int amplify, int noisetype)
+extern "C" WTURBULENCE *smoke_turbulence_init(int *res, int amplify, int noisetype, int use_fire, int use_colors)
{
- // initialize wavelet turbulence
- if(amplify)
- return new WTURBULENCE(res[0],res[1],res[2], amplify, noisetype);
+ if (amplify)
+ return new WTURBULENCE(res[0],res[1],res[2], amplify, noisetype, use_fire, use_colors);
else
return NULL;
}
@@ -70,7 +66,6 @@ extern "C" void smoke_turbulence_free(WTURBULENCE *wt)
extern "C" size_t smoke_get_index(int x, int max_x, int y, int max_y, int z /*, int max_z */)
{
- // // const int index = x + y * smd->res[0] + z * smd->res[0]*smd->res[1];
return x + y * max_x + z * max_x*max_y;
}
@@ -79,137 +74,133 @@ extern "C" size_t smoke_get_index2d(int x, int max_x, int y /*, int max_y, int z
return x + y * max_x;
}
-extern "C" void smoke_step(FLUID_3D *fluid, float dtSubdiv)
+extern "C" void smoke_step(FLUID_3D *fluid, float gravity[3], float dtSubdiv)
{
- fluid->step(dtSubdiv);
+ if (fluid->_fuel) {
+ fluid->processBurn(fluid->_fuel, fluid->_density, fluid->_react, fluid->_flame, fluid->_heat,
+ fluid->_color_r, fluid->_color_g, fluid->_color_b, fluid->_totalCells, (*fluid->_dtFactor)*dtSubdiv);
+ }
+ fluid->step(dtSubdiv, gravity);
}
extern "C" void smoke_turbulence_step(WTURBULENCE *wt, FLUID_3D *fluid)
{
+ if (wt->_fuelBig) {
+ fluid->processBurn(wt->_fuelBig, wt->_densityBig, wt->_reactBig, wt->_flameBig, 0,
+ wt->_color_rBig, wt->_color_gBig, wt->_color_bBig, wt->_totalCellsBig, fluid->_dt);
+ }
wt->stepTurbulenceFull(fluid->_dt/fluid->_dx, fluid->_xVelocity, fluid->_yVelocity, fluid->_zVelocity, fluid->_obstacles);
}
-extern "C" void smoke_initBlenderRNA(FLUID_3D *fluid, float *alpha, float *beta, float *dt_factor, float *vorticity, int *border_colli)
+extern "C" void smoke_initBlenderRNA(FLUID_3D *fluid, float *alpha, float *beta, float *dt_factor, float *vorticity, int *border_colli, float *burning_rate,
+ float *flame_smoke, float *flame_smoke_color, float *flame_vorticity, float *flame_ignition_temp, float *flame_max_temp)
{
- fluid->initBlenderRNA(alpha, beta, dt_factor, vorticity, border_colli);
+ fluid->initBlenderRNA(alpha, beta, dt_factor, vorticity, border_colli, burning_rate, flame_smoke, flame_smoke_color, flame_vorticity, flame_ignition_temp, flame_max_temp);
}
-extern "C" void smoke_dissolve(FLUID_3D *fluid, int speed, int log)
+extern "C" void smoke_initWaveletBlenderRNA(WTURBULENCE *wt, float *strength)
{
- float *density = fluid->_density;
- //float *densityOld = fluid->_densityOld;
- float *heat = fluid->_heat;
-
- if(log)
- {
- /* max density/speed = dydx */
- float dydx = 1.0 / (float)speed;
- size_t size= fluid->_xRes * fluid->_yRes * fluid->_zRes;
-
- for(size_t i = 0; i < size; i++)
- {
- density[i] *= (1.0 - dydx);
-
- if(density[i] < 0.0f)
- density[i] = 0.0f;
-
- heat[i] *= (1.0 - dydx);
-
- /*if(heat[i] < 0.0f)
- heat[i] = 0.0f;*/
- }
- }
- else // linear falloff
- {
- /* max density/speed = dydx */
- float dydx = 1.0 / (float)speed;
- size_t size= fluid->_xRes * fluid->_yRes * fluid->_zRes;
-
- for(size_t i = 0; i < size; i++)
- {
- density[i] -= dydx;
-
- if(density[i] < 0.0f)
- density[i] = 0.0f;
-
- if(abs(heat[i]) < dydx) heat[i] = 0.0f;
- else if (heat[i]>0.0f) heat[i] -= dydx;
- else if (heat[i]<0.0f) heat[i] += dydx;
-
- }
- }
+ wt->initBlenderRNA(strength);
}
-extern "C" void smoke_dissolve_wavelet(WTURBULENCE *wt, int speed, int log)
+static void data_dissolve(float *density, float *heat, float *r, float *g, float *b, int total_cells, int speed, int log)
{
- float *density = wt->getDensityBig();
- Vec3Int r = wt->getResBig();
-
- if(log)
- {
+ if (log) {
/* max density/speed = dydx */
- float dydx = 1.0 / (float)speed;
- size_t size= r[0] * r[1] * r[2];
+ float fac = 1.0f - (1.0f / (float)speed);
- for(size_t i = 0; i < size; i++)
+ for(size_t i = 0; i < total_cells; i++)
{
- density[i] *= (1.0 - dydx);
-
- if(density[i] < 0.0f)
- density[i] = 0.0f;
+ /* density */
+ density[i] *= fac;
+
+ /* heat */
+ if (heat) {
+ heat[i] *= fac;
+ }
+
+ /* color */
+ if (r) {
+ r[i] *= fac;
+ g[i] *= fac;
+ b[i] *= fac;
+ }
}
}
else // linear falloff
{
/* max density/speed = dydx */
- float dydx = 1.0 / (float)speed;
- size_t size= r[0] * r[1] * r[2];
+ float dydx = 1.0f / (float)speed;
- for(size_t i = 0; i < size; i++)
+ for(size_t i = 0; i < total_cells; i++)
{
+ float d = density[i];
+ /* density */
density[i] -= dydx;
+ if (density[i] < 0.0f)
+ density[i] = 0.0f;
- if(density[i] < 0.0f)
- density[i] = 0.0f;
+ /* heat */
+ if (heat) {
+ if (abs(heat[i]) < dydx) heat[i] = 0.0f;
+ else if (heat[i] > 0.0f) heat[i] -= dydx;
+ else if (heat[i] < 0.0f) heat[i] += dydx;
+ }
+
+ /* color */
+ if (r && d) {
+ r[i] *= (density[i]/d);
+ g[i] *= (density[i]/d);
+ b[i] *= (density[i]/d);
+ }
+
}
}
}
-extern "C" void smoke_initWaveletBlenderRNA(WTURBULENCE *wt, float *strength)
+extern "C" void smoke_dissolve(FLUID_3D *fluid, int speed, int log)
{
- wt->initBlenderRNA(strength);
+ data_dissolve(fluid->_density, fluid->_heat, fluid->_color_r, fluid->_color_g, fluid->_color_b, fluid->_totalCells, speed, log);
}
-template < class T > inline T ABS( T a )
+extern "C" void smoke_dissolve_wavelet(WTURBULENCE *wt, int speed, int log)
{
- return (0 < a) ? a : -a ;
+ data_dissolve(wt->_densityBig, 0, wt->_color_rBig, wt->_color_gBig, wt->_color_bBig, wt->_totalCellsBig, speed, log);
}
-extern "C" void smoke_export(FLUID_3D *fluid, float *dt, float *dx, float **dens, float **densold, float **heat, float **heatold, float **vx, float **vy, float **vz, float **vxold, float **vyold, float **vzold, unsigned char **obstacles)
+extern "C" void smoke_export(FLUID_3D *fluid, float *dt, float *dx, float **dens, float **react, float **flame, float **fuel, float **heat,
+ float **heatold, float **vx, float **vy, float **vz, float **r, float **g, float **b, unsigned char **obstacles)
{
*dens = fluid->_density;
- *densold = fluid->_densityOld;
+ *fuel = fluid->_fuel;
+ *react = fluid->_react;
+ *flame = fluid->_flame;
*heat = fluid->_heat;
*heatold = fluid->_heatOld;
*vx = fluid->_xVelocity;
*vy = fluid->_yVelocity;
*vz = fluid->_zVelocity;
- *vxold = fluid->_xVelocityOld;
- *vyold = fluid->_yVelocityOld;
- *vzold = fluid->_zVelocityOld;
+ *r = fluid->_color_r;
+ *g = fluid->_color_g;
+ *b = fluid->_color_b;
*obstacles = fluid->_obstacles;
*dt = fluid->_dt;
*dx = fluid->_dx;
-
}
-extern "C" void smoke_turbulence_export(WTURBULENCE *wt, float **dens, float **densold, float **tcu, float **tcv, float **tcw)
+extern "C" void smoke_turbulence_export(WTURBULENCE *wt, float **dens, float **react, float **flame, float **fuel,
+ float **r, float **g, float **b , float **tcu, float **tcv, float **tcw)
{
- if(!wt)
+ if (!wt)
return;
*dens = wt->_densityBig;
- *densold = wt->_densityBigOld;
+ *fuel = wt->_fuelBig;
+ *react = wt->_reactBig;
+ *flame = wt->_flameBig;
+ *r = wt->_color_rBig;
+ *g = wt->_color_gBig;
+ *b = wt->_color_bBig;
*tcu = wt->_tcU;
*tcv = wt->_tcV;
*tcw = wt->_tcW;
@@ -220,6 +211,16 @@ extern "C" float *smoke_get_density(FLUID_3D *fluid)
return fluid->_density;
}
+extern "C" float *smoke_get_fuel(FLUID_3D *fluid)
+{
+ return fluid->_fuel;
+}
+
+extern "C" float *smoke_get_react(FLUID_3D *fluid)
+{
+ return fluid->_react;
+}
+
extern "C" float *smoke_get_heat(FLUID_3D *fluid)
{
return fluid->_heat;
@@ -255,15 +256,137 @@ extern "C" float *smoke_get_force_z(FLUID_3D *fluid)
return fluid->_zForce;
}
+extern "C" float *smoke_get_flame(FLUID_3D *fluid)
+{
+ return fluid->_flame;
+}
+
+extern "C" float *smoke_get_color_r(FLUID_3D *fluid)
+{
+ return fluid->_color_r;
+}
+
+extern "C" float *smoke_get_color_g(FLUID_3D *fluid)
+{
+ return fluid->_color_g;
+}
+
+extern "C" float *smoke_get_color_b(FLUID_3D *fluid)
+{
+ return fluid->_color_b;
+}
+
+static void get_rgba(float *r, float *g, float *b, float *a, int total_cells, float *data, int sequential)
+{
+ int i;
+ int m = 4, i_g = 1, i_b = 2, i_a = 3;
+ /* sequential data */
+ if (sequential) {
+ m = 1;
+ i_g *= total_cells;
+ i_b *= total_cells;
+ i_a *= total_cells;
+ }
+
+ for (i=0; i<total_cells; i++) {
+ float alpha = a[i];
+ if (alpha) {
+ data[i*m ] = r[i];
+ data[i*m+i_g] = g[i];
+ data[i*m+i_b] = b[i];
+ }
+ else {
+ data[i*m ] = data[i*m+i_g] = data[i*m+i_b] = 0.0f;
+ }
+ data[i*m+i_a] = alpha;
+ }
+}
+
+extern "C" void smoke_get_rgba(FLUID_3D *fluid, float *data, int sequential)
+{
+ get_rgba(fluid->_color_r, fluid->_color_g, fluid->_color_b, fluid->_density, fluid->_totalCells, data, sequential);
+}
+
+extern "C" void smoke_turbulence_get_rgba(WTURBULENCE *wt, float *data, int sequential)
+{
+ get_rgba(wt->_color_rBig, wt->_color_gBig, wt->_color_bBig, wt->_densityBig, wt->_totalCellsBig, data, sequential);
+}
+
+/* get a single color premultiplied voxel grid */
+static void get_rgba_from_density(float color[3], float *a, int total_cells, float *data, int sequential)
+{
+ int i;
+ int m = 4, i_g = 1, i_b = 2, i_a = 3;
+ /* sequential data */
+ if (sequential) {
+ m = 1;
+ i_g *= total_cells;
+ i_b *= total_cells;
+ i_a *= total_cells;
+ }
+
+ for (i=0; i<total_cells; i++) {
+ float alpha = a[i];
+ if (alpha) {
+ data[i*m ] = color[0] * alpha;
+ data[i*m+i_g] = color[1] * alpha;
+ data[i*m+i_b] = color[2] * alpha;
+ }
+ else {
+ data[i*m ] = data[i*m+i_g] = data[i*m+i_b] = 0.0f;
+ }
+ data[i*m+i_a] = alpha;
+ }
+}
+
+extern "C" void smoke_get_rgba_from_density(FLUID_3D *fluid, float color[3], float *data, int sequential)
+{
+ get_rgba_from_density(color, fluid->_density, fluid->_totalCells, data, sequential);
+}
+
+extern "C" void smoke_turbulence_get_rgba_from_density(WTURBULENCE *wt, float color[3], float *data, int sequential)
+{
+ get_rgba_from_density(color, wt->_densityBig, wt->_totalCellsBig, data, sequential);
+}
+
extern "C" float *smoke_turbulence_get_density(WTURBULENCE *wt)
{
return wt ? wt->getDensityBig() : NULL;
}
+extern "C" float *smoke_turbulence_get_fuel(WTURBULENCE *wt)
+{
+ return wt ? wt->getFuelBig() : NULL;
+}
+
+extern "C" float *smoke_turbulence_get_react(WTURBULENCE *wt)
+{
+ return wt ? wt->_reactBig : NULL;
+}
+
+extern "C" float *smoke_turbulence_get_color_r(WTURBULENCE *wt)
+{
+ return wt ? wt->_color_rBig : NULL;
+}
+
+extern "C" float *smoke_turbulence_get_color_g(WTURBULENCE *wt)
+{
+ return wt ? wt->_color_gBig : NULL;
+}
+
+extern "C" float *smoke_turbulence_get_color_b(WTURBULENCE *wt)
+{
+ return wt ? wt->_color_bBig : NULL;
+}
+
+extern "C" float *smoke_turbulence_get_flame(WTURBULENCE *wt)
+{
+ return wt ? wt->getFlameBig() : NULL;
+}
+
extern "C" void smoke_turbulence_get_res(WTURBULENCE *wt, int *res)
{
- if(wt)
- {
+ if (wt) {
Vec3Int r = wt->getResBig();
res[0] = r[0];
res[1] = r[1];
@@ -271,6 +394,15 @@ extern "C" void smoke_turbulence_get_res(WTURBULENCE *wt, int *res)
}
}
+extern "C" int smoke_turbulence_get_cells(WTURBULENCE *wt)
+{
+ if (wt) {
+ Vec3Int r = wt->getResBig();
+ return r[0] * r[1] * r[2];
+ }
+ return 0;
+}
+
extern "C" unsigned char *smoke_get_obstacle(FLUID_3D *fluid)
{
return fluid->_obstacles;
@@ -283,12 +415,72 @@ extern "C" void smoke_get_ob_velocity(FLUID_3D *fluid, float **x, float **y, flo
*z = fluid->_zVelocityOb;
}
+#if 0
extern "C" unsigned char *smoke_get_obstacle_anim(FLUID_3D *fluid)
{
return fluid->_obstaclesAnim;
}
+#endif
extern "C" void smoke_turbulence_set_noise(WTURBULENCE *wt, int type)
{
wt->setNoise(type);
}
+
+extern "C" void flame_get_spectrum(unsigned char *spec, int width, float t1, float t2)
+{
+ spectrum(t1, t2, width, spec);
+}
+
+extern "C" int smoke_has_heat(FLUID_3D *fluid)
+{
+ return (fluid->_heat) ? 1 : 0;
+}
+
+extern "C" int smoke_has_fuel(FLUID_3D *fluid)
+{
+ return (fluid->_fuel) ? 1 : 0;
+}
+
+extern "C" int smoke_has_colors(FLUID_3D *fluid)
+{
+ return (fluid->_color_r && fluid->_color_g && fluid->_color_b) ? 1 : 0;
+}
+
+extern "C" int smoke_turbulence_has_fuel(WTURBULENCE *wt)
+{
+ return (wt->_fuelBig) ? 1 : 0;
+}
+
+extern "C" int smoke_turbulence_has_colors(WTURBULENCE *wt)
+{
+ return (wt->_color_rBig && wt->_color_gBig && wt->_color_bBig) ? 1 : 0;
+}
+
+/* additional field initialization */
+extern "C" void smoke_ensure_heat(FLUID_3D *fluid)
+{
+ if (fluid) {
+ fluid->initHeat();
+ }
+}
+
+extern "C" void smoke_ensure_fire(FLUID_3D *fluid, WTURBULENCE *wt)
+{
+ if (fluid) {
+ fluid->initFire();
+ }
+ if (wt) {
+ wt->initFire();
+ }
+}
+
+extern "C" void smoke_ensure_colors(FLUID_3D *fluid, WTURBULENCE *wt, float init_r, float init_g, float init_b)
+{
+ if (fluid) {
+ fluid->initColors(init_r, init_g, init_b);
+ }
+ if (wt) {
+ wt->initColors(init_r, init_g, init_b);
+ }
+}
diff --git a/intern/smoke/intern/spectrum.cpp b/intern/smoke/intern/spectrum.cpp
new file mode 100644
index 00000000000..30433451ac2
--- /dev/null
+++ b/intern/smoke/intern/spectrum.cpp
@@ -0,0 +1,426 @@
+/*
+ Colour Rendering of Spectra
+
+ by John Walker
+ http://www.fourmilab.ch/
+
+ Last updated: March 9, 2003
+
+ This program is in the public domain.
+
+ For complete information about the techniques employed in
+ this program, see the World-Wide Web document:
+
+ http://www.fourmilab.ch/documents/specrend/
+
+ The xyz_to_rgb() function, which was wrong in the original
+ version of this program, was corrected by:
+
+ Andrew J. S. Hamilton 21 May 1999
+ Andrew.Hamilton@Colorado.EDU
+ http://casa.colorado.edu/~ajsh/
+
+ who also added the gamma correction facilities and
+ modified constrain_rgb() to work by desaturating the
+ colour by adding white.
+
+ A program which uses these functions to plot CIE
+ "tongue" diagrams called "ppmcie" is included in
+ the Netpbm graphics toolkit:
+ http://netpbm.sourceforge.net/
+ (The program was called cietoppm in earlier
+ versions of Netpbm.)
+
+*/
+
+#include <stdio.h>
+#include <math.h>
+#include "spectrum.h"
+
+/* A colour system is defined by the CIE x and y coordinates of
+ its three primary illuminants and the x and y coordinates of
+ the white point. */
+
+struct colourSystem {
+ const char *name; /* Colour system name */
+ double xRed, yRed, /* Red x, y */
+ xGreen, yGreen, /* Green x, y */
+ xBlue, yBlue, /* Blue x, y */
+ xWhite, yWhite, /* White point x, y */
+ gamma; /* Gamma correction for system */
+};
+
+/* White point chromaticities. */
+
+#define IlluminantC 0.3101, 0.3162 /* For NTSC television */
+#define IlluminantD65 0.3127, 0.3291 /* For EBU and SMPTE */
+#define IlluminantE 0.33333333, 0.33333333 /* CIE equal-energy illuminant */
+
+/* Gamma of nonlinear correction.
+
+ See Charles Poynton's ColorFAQ Item 45 and GammaFAQ Item 6 at:
+
+ http://www.poynton.com/ColorFAQ.html
+ http://www.poynton.com/GammaFAQ.html
+
+*/
+
+#define GAMMA_REC709 0 /* Rec. 709 */
+
+static struct colourSystem
+ /* Name xRed yRed xGreen yGreen xBlue yBlue White point Gamma */
+#if 0 /* UNUSED */
+ NTSCsystem = { "NTSC", 0.67, 0.33, 0.21, 0.71, 0.14, 0.08, IlluminantC, GAMMA_REC709 },
+ EBUsystem = { "EBU (PAL/SECAM)", 0.64, 0.33, 0.29, 0.60, 0.15, 0.06, IlluminantD65, GAMMA_REC709 },
+ SMPTEsystem = { "SMPTE", 0.630, 0.340, 0.310, 0.595, 0.155, 0.070, IlluminantD65, GAMMA_REC709 },
+ HDTVsystem = { "HDTV", 0.670, 0.330, 0.210, 0.710, 0.150, 0.060, IlluminantD65, GAMMA_REC709 },
+#endif
+
+ CIEsystem = { "CIE", 0.7355, 0.2645, 0.2658, 0.7243, 0.1669, 0.0085, IlluminantE, GAMMA_REC709 };
+
+#if 0 /* UNUSED */
+ Rec709system = { "CIE REC 709", 0.64, 0.33, 0.30, 0.60, 0.15, 0.06, IlluminantD65, GAMMA_REC709 };
+#endif
+
+/* UPVP_TO_XY
+
+ Given 1976 coordinates u', v', determine 1931 chromaticities x, y
+
+*/
+
+#if 0 /* UNUSED */
+static void upvp_to_xy(double up, double vp, double *xc, double *yc)
+{
+ *xc = (9 * up) / ((6 * up) - (16 * vp) + 12);
+ *yc = (4 * vp) / ((6 * up) - (16 * vp) + 12);
+}
+#endif
+
+/* XY_TO_UPVP
+
+ Given 1931 chromaticities x, y, determine 1976 coordinates u', v'
+
+*/
+
+#if 0 /* UNUSED */
+static void xy_to_upvp(double xc, double yc, double *up, double *vp)
+{
+ *up = (4 * xc) / ((-2 * xc) + (12 * yc) + 3);
+ *vp = (9 * yc) / ((-2 * xc) + (12 * yc) + 3);
+}
+#endif
+
+/* XYZ_TO_RGB
+
+ Given an additive tricolour system CS, defined by the CIE x
+ and y chromaticities of its three primaries (z is derived
+ trivially as 1-(x+y)), and a desired chromaticity (XC, YC,
+ ZC) in CIE space, determine the contribution of each
+ primary in a linear combination which sums to the desired
+ chromaticity. If the requested chromaticity falls outside
+ the Maxwell triangle (colour gamut) formed by the three
+ primaries, one of the r, g, or b weights will be negative.
+
+ Caller can use constrain_rgb() to desaturate an
+ outside-gamut colour to the closest representation within
+ the available gamut and/or norm_rgb to normalise the RGB
+ components so the largest nonzero component has value 1.
+
+*/
+
+static void xyz_to_rgb(struct colourSystem *cs,
+ double xc, double yc, double zc,
+ double *r, double *g, double *b)
+{
+ double xr, yr, zr, xg, yg, zg, xb, yb, zb;
+ double xw, yw, zw;
+ double rx, ry, rz, gx, gy, gz, bx, by, bz;
+ double rw, gw, bw;
+
+ xr = cs->xRed; yr = cs->yRed; zr = 1 - (xr + yr);
+ xg = cs->xGreen; yg = cs->yGreen; zg = 1 - (xg + yg);
+ xb = cs->xBlue; yb = cs->yBlue; zb = 1 - (xb + yb);
+
+ xw = cs->xWhite; yw = cs->yWhite; zw = 1 - (xw + yw);
+
+ /* xyz -> rgb matrix, before scaling to white. */
+
+ rx = (yg * zb) - (yb * zg); ry = (xb * zg) - (xg * zb); rz = (xg * yb) - (xb * yg);
+ gx = (yb * zr) - (yr * zb); gy = (xr * zb) - (xb * zr); gz = (xb * yr) - (xr * yb);
+ bx = (yr * zg) - (yg * zr); by = (xg * zr) - (xr * zg); bz = (xr * yg) - (xg * yr);
+
+ /* White scaling factors.
+ Dividing by yw scales the white luminance to unity, as conventional. */
+
+ rw = ((rx * xw) + (ry * yw) + (rz * zw)) / yw;
+ gw = ((gx * xw) + (gy * yw) + (gz * zw)) / yw;
+ bw = ((bx * xw) + (by * yw) + (bz * zw)) / yw;
+
+ /* xyz -> rgb matrix, correctly scaled to white. */
+
+ rx = rx / rw; ry = ry / rw; rz = rz / rw;
+ gx = gx / gw; gy = gy / gw; gz = gz / gw;
+ bx = bx / bw; by = by / bw; bz = bz / bw;
+
+ /* rgb of the desired point */
+
+ *r = (rx * xc) + (ry * yc) + (rz * zc);
+ *g = (gx * xc) + (gy * yc) + (gz * zc);
+ *b = (bx * xc) + (by * yc) + (bz * zc);
+}
+
+/* INSIDE_GAMUT
+
+ Test whether a requested colour is within the gamut
+ achievable with the primaries of the current colour
+ system. This amounts simply to testing whether all the
+ primary weights are non-negative. */
+
+#if 0 /* UNUSED */
+static int inside_gamut(double r, double g, double b)
+{
+ return (r >= 0) && (g >= 0) && (b >= 0);
+}
+#endif
+
+/* CONSTRAIN_RGB
+
+ If the requested RGB shade contains a negative weight for
+ one of the primaries, it lies outside the colour gamut
+ accessible from the given triple of primaries. Desaturate
+ it by adding white, equal quantities of R, G, and B, enough
+ to make RGB all positive. The function returns 1 if the
+ components were modified, zero otherwise.
+
+*/
+
+static int constrain_rgb(double *r, double *g, double *b)
+{
+ double w;
+
+ /* Amount of white needed is w = - min(0, *r, *g, *b) */
+
+ w = (0 < *r) ? 0 : *r;
+ w = (w < *g) ? w : *g;
+ w = (w < *b) ? w : *b;
+ w = -w;
+
+ /* Add just enough white to make r, g, b all positive. */
+
+ if (w > 0) {
+ *r += w; *g += w; *b += w;
+ return 1; /* Colour modified to fit RGB gamut */
+ }
+
+ return 0; /* Colour within RGB gamut */
+}
+
+/* GAMMA_CORRECT_RGB
+
+ Transform linear RGB values to nonlinear RGB values. Rec.
+ 709 is ITU-R Recommendation BT. 709 (1990) ``Basic
+ Parameter Values for the HDTV Standard for the Studio and
+ for International Programme Exchange'', formerly CCIR Rec.
+ 709. For details see
+
+ http://www.poynton.com/ColorFAQ.html
+ http://www.poynton.com/GammaFAQ.html
+*/
+
+#if 0 /* UNUSED */
+static void gamma_correct(const struct colourSystem *cs, double *c)
+{
+ double gamma;
+
+ gamma = cs->gamma;
+
+ if (gamma == GAMMA_REC709) {
+ /* Rec. 709 gamma correction. */
+ double cc = 0.018;
+
+ if (*c < cc) {
+ *c *= ((1.099 * pow(cc, 0.45)) - 0.099) / cc;
+ } else {
+ *c = (1.099 * pow(*c, 0.45)) - 0.099;
+ }
+ } else {
+ /* Nonlinear colour = (Linear colour)^(1/gamma) */
+ *c = pow(*c, 1.0 / gamma);
+ }
+}
+
+static void gamma_correct_rgb(const struct colourSystem *cs, double *r, double *g, double *b)
+{
+ gamma_correct(cs, r);
+ gamma_correct(cs, g);
+ gamma_correct(cs, b);
+}
+#endif
+
+/* NORM_RGB
+
+ Normalise RGB components so the most intense (unless all
+ are zero) has a value of 1.
+
+*/
+
+static void norm_rgb(double *r, double *g, double *b)
+{
+#define Max(a, b) (((a) > (b)) ? (a) : (b))
+ double greatest = Max(*r, Max(*g, *b));
+
+ if (greatest > 0) {
+ *r /= greatest;
+ *g /= greatest;
+ *b /= greatest;
+ }
+#undef Max
+}
+
+/* SPECTRUM_TO_XYZ
+
+ Calculate the CIE X, Y, and Z coordinates corresponding to
+ a light source with spectral distribution given by the
+ function SPEC_INTENS, which is called with a series of
+ wavelengths between 380 and 780 nm (the argument is
+ expressed in meters), which returns emittance at that
+ wavelength in arbitrary units. The chromaticity
+ coordinates of the spectrum are returned in the x, y, and z
+ arguments which respect the identity:
+
+ x + y + z = 1.
+*/
+
+static void spectrum_to_xyz(double (*spec_intens)(double wavelength),
+ double *x, double *y, double *z)
+{
+ int i;
+ double lambda, X = 0, Y = 0, Z = 0, XYZ;
+
+ /* CIE colour matching functions xBar, yBar, and zBar for
+ wavelengths from 380 through 780 nanometers, every 5
+ nanometers. For a wavelength lambda in this range:
+
+ cie_colour_match[(lambda - 380) / 5][0] = xBar
+ cie_colour_match[(lambda - 380) / 5][1] = yBar
+ cie_colour_match[(lambda - 380) / 5][2] = zBar
+
+ To save memory, this table can be declared as floats
+ rather than doubles; (IEEE) float has enough
+ significant bits to represent the values. It's declared
+ as a double here to avoid warnings about "conversion
+ between floating-point types" from certain persnickety
+ compilers. */
+
+ static double cie_colour_match[81][3] = {
+ {0.0014,0.0000,0.0065}, {0.0022,0.0001,0.0105}, {0.0042,0.0001,0.0201},
+ {0.0076,0.0002,0.0362}, {0.0143,0.0004,0.0679}, {0.0232,0.0006,0.1102},
+ {0.0435,0.0012,0.2074}, {0.0776,0.0022,0.3713}, {0.1344,0.0040,0.6456},
+ {0.2148,0.0073,1.0391}, {0.2839,0.0116,1.3856}, {0.3285,0.0168,1.6230},
+ {0.3483,0.0230,1.7471}, {0.3481,0.0298,1.7826}, {0.3362,0.0380,1.7721},
+ {0.3187,0.0480,1.7441}, {0.2908,0.0600,1.6692}, {0.2511,0.0739,1.5281},
+ {0.1954,0.0910,1.2876}, {0.1421,0.1126,1.0419}, {0.0956,0.1390,0.8130},
+ {0.0580,0.1693,0.6162}, {0.0320,0.2080,0.4652}, {0.0147,0.2586,0.3533},
+ {0.0049,0.3230,0.2720}, {0.0024,0.4073,0.2123}, {0.0093,0.5030,0.1582},
+ {0.0291,0.6082,0.1117}, {0.0633,0.7100,0.0782}, {0.1096,0.7932,0.0573},
+ {0.1655,0.8620,0.0422}, {0.2257,0.9149,0.0298}, {0.2904,0.9540,0.0203},
+ {0.3597,0.9803,0.0134}, {0.4334,0.9950,0.0087}, {0.5121,1.0000,0.0057},
+ {0.5945,0.9950,0.0039}, {0.6784,0.9786,0.0027}, {0.7621,0.9520,0.0021},
+ {0.8425,0.9154,0.0018}, {0.9163,0.8700,0.0017}, {0.9786,0.8163,0.0014},
+ {1.0263,0.7570,0.0011}, {1.0567,0.6949,0.0010}, {1.0622,0.6310,0.0008},
+ {1.0456,0.5668,0.0006}, {1.0026,0.5030,0.0003}, {0.9384,0.4412,0.0002},
+ {0.8544,0.3810,0.0002}, {0.7514,0.3210,0.0001}, {0.6424,0.2650,0.0000},
+ {0.5419,0.2170,0.0000}, {0.4479,0.1750,0.0000}, {0.3608,0.1382,0.0000},
+ {0.2835,0.1070,0.0000}, {0.2187,0.0816,0.0000}, {0.1649,0.0610,0.0000},
+ {0.1212,0.0446,0.0000}, {0.0874,0.0320,0.0000}, {0.0636,0.0232,0.0000},
+ {0.0468,0.0170,0.0000}, {0.0329,0.0119,0.0000}, {0.0227,0.0082,0.0000},
+ {0.0158,0.0057,0.0000}, {0.0114,0.0041,0.0000}, {0.0081,0.0029,0.0000},
+ {0.0058,0.0021,0.0000}, {0.0041,0.0015,0.0000}, {0.0029,0.0010,0.0000},
+ {0.0020,0.0007,0.0000}, {0.0014,0.0005,0.0000}, {0.0010,0.0004,0.0000},
+ {0.0007,0.0002,0.0000}, {0.0005,0.0002,0.0000}, {0.0003,0.0001,0.0000},
+ {0.0002,0.0001,0.0000}, {0.0002,0.0001,0.0000}, {0.0001,0.0000,0.0000},
+ {0.0001,0.0000,0.0000}, {0.0001,0.0000,0.0000}, {0.0000,0.0000,0.0000}
+ };
+
+ for (i = 0, lambda = 380; lambda < 780.1; i++, lambda += 5) {
+ double Me;
+
+ Me = (*spec_intens)(lambda);
+ X += Me * cie_colour_match[i][0];
+ Y += Me * cie_colour_match[i][1];
+ Z += Me * cie_colour_match[i][2];
+ }
+ XYZ = (X + Y + Z);
+ *x = X / XYZ;
+ *y = Y / XYZ;
+ *z = Z / XYZ;
+}
+
+/* BB_SPECTRUM
+
+ Calculate, by Planck's radiation law, the emittance of a black body
+ of temperature bbTemp at the given wavelength (in metres). */
+
+double bbTemp = 5000; /* Hidden temperature argument
+ to BB_SPECTRUM. */
+static double bb_spectrum(double wavelength)
+{
+ double wlm = wavelength * 1e-9; /* Wavelength in meters */
+
+ return (3.74183e-16 * pow(wlm, -5.0)) /
+ (exp(1.4388e-2 / (wlm * bbTemp)) - 1.0);
+}
+
+static void xyz_to_lms(double x, double y, double z, double* l, double* m, double* s)
+{
+ *l = 0.3897*x + 0.6890*y - 0.0787*z;
+ *m = -0.2298*x + 1.1834*y + 0.0464*z;
+ *s = z;
+}
+
+static void lms_to_xyz(double l, double m, double s, double* x, double *y, double* z)
+{
+ *x = 1.9102*l - 1.1121*m + 0.2019*s;
+ *y = 0.3709*l + 0.6290*m + 0.0000*s;
+ *z = s;
+}
+
+void spectrum(double t1, double t2, int N, unsigned char *d)
+{
+ int i,j,dj;
+ double X,Y,Z,R,G,B,L,M,S, Lw, Mw, Sw;
+ struct colourSystem *cs = &CIEsystem;
+
+ j = 0; dj = 1;
+ if (t1<t2) {
+ double t = t1;
+ t1 = t2;
+ t2 = t;
+ j = N-1; dj=-1;
+ }
+
+ for (i=0; i<N; i++) {
+ bbTemp = t1 + (t2-t1)/N*i;
+
+ // integrate blackbody radiation spectrum to XYZ
+ spectrum_to_xyz(bb_spectrum, &X, &Y, &Z);
+
+ // normalize highest temperature to white (in LMS system)
+ xyz_to_lms(X,Y,Z,&L,&M,&S);
+ if (i==0) {
+ Lw=1/L; Mw=1/M; Sw=1/S;
+ }
+ L *= Lw; M *= Mw; S *= Sw;
+ lms_to_xyz(L,M,S,&X,&Y,&Z);
+
+ // convert to RGB
+ xyz_to_rgb(cs, X, Y, Z, &R, &G, &B);
+ constrain_rgb(&R, &G, &B);
+ norm_rgb(&R, &G, &B);
+ d[(j<<2)] = (unsigned char) ((double)R*255);
+ d[(j<<2)+1] = (unsigned char) ((double)G*255);
+ d[(j<<2)+2] = (unsigned char) ((double)B*255);
+ d[(j<<2)+3] = (B>0.1)? B*255 : 0;
+ j += dj;
+ }
+}
diff --git a/intern/smoke/intern/spectrum.h b/intern/smoke/intern/spectrum.h
new file mode 100644
index 00000000000..3ffd41f9517
--- /dev/null
+++ b/intern/smoke/intern/spectrum.h
@@ -0,0 +1,6 @@
+#ifndef __SPECTRUM_H
+#define __SPECTRUM_H
+
+void spectrum(double t1, double t2, int n, unsigned char *d);
+
+#endif
diff --git a/intern/string/STR_String.h b/intern/string/STR_String.h
index 6e9f6007e0b..a3d367a6fef 100644
--- a/intern/string/STR_String.h
+++ b/intern/string/STR_String.h
@@ -88,8 +88,16 @@ public:
inline ~STR_String() { delete[] this->m_data; }
// Operations
- STR_String& Format(const char *fmt, ...); // Set formatted text to string
- STR_String& FormatAdd(const char *fmt, ...); // Add formatted text to string
+ STR_String& Format(const char *fmt, ...) // Set formatted text to string
+#ifdef __GNUC__
+ __attribute__ ((format(printf, 2, 3)))
+#endif
+ ;
+ STR_String& FormatAdd(const char *fmt, ...) // Add formatted text to string
+#ifdef __GNUC__
+ __attribute__ ((format(printf, 2, 3)))
+#endif
+ ;
inline void Clear() { this->m_len = this->m_data[0] = 0; }
inline const STR_String & Reverse()
{
@@ -208,12 +216,10 @@ protected:
#endif
};
-inline STR_String operator+(rcSTR_String lhs, rcSTR_String rhs) { return STR_String(lhs.ReadPtr(), lhs.Length(), rhs.ReadPtr(), rhs.Length()); }
-inline STR_String operator+(rcSTR_String lhs, char rhs) { return STR_String(lhs.ReadPtr(), lhs.Length(), &rhs, 1); }
-inline STR_String operator+(char lhs, rcSTR_String rhs) { return STR_String(&lhs, 1, rhs.ReadPtr(), rhs.Length()); }
-inline STR_String operator+(rcSTR_String lhs, const char *rhs) { return STR_String(lhs.ReadPtr(), lhs.Length(), rhs, strlen(rhs)); }
-inline STR_String operator+(const char *lhs, rcSTR_String rhs) { return STR_String(lhs, strlen(lhs), rhs.ReadPtr(), rhs.Length()); }
-
+inline STR_String operator+(rcSTR_String lhs, rcSTR_String rhs) { return STR_String(lhs.ReadPtr(), lhs.Length(), rhs.ReadPtr(), rhs.Length()); }
+inline STR_String operator+(rcSTR_String lhs, char rhs) { return STR_String(lhs.ReadPtr(), lhs.Length(), &rhs, 1); }
+inline STR_String operator+(char lhs, rcSTR_String rhs) { return STR_String(&lhs, 1, rhs.ReadPtr(), rhs.Length()); }
+inline STR_String operator+(rcSTR_String lhs, const char *rhs) { return STR_String(lhs.ReadPtr(), lhs.Length(), rhs, strlen(rhs)); }
+inline STR_String operator+(const char *lhs, rcSTR_String rhs) { return STR_String(lhs, strlen(lhs), rhs.ReadPtr(), rhs.Length()); }
#endif //__STR_STRING_H__
-
diff --git a/intern/string/intern/STR_String.cpp b/intern/string/intern/STR_String.cpp
index 4b2261e89f9..283b44380ee 100644
--- a/intern/string/intern/STR_String.cpp
+++ b/intern/string/intern/STR_String.cpp
@@ -738,4 +738,3 @@ int STR_String::Serialize(pCStream stream)
return this->m_len + sizeof(this->m_len);
}
#endif
-
diff --git a/intern/utfconv/utfconv.h b/intern/utfconv/utfconv.h
index 3bfd2772991..cf0e69170a2 100644
--- a/intern/utfconv/utfconv.h
+++ b/intern/utfconv/utfconv.h
@@ -95,7 +95,7 @@ wchar_t *alloc_utf16_from_8(const char *in8, size_t add);
wchar_t *in8str ## _16 = alloc_utf16_from_8((char *)in8str, 0)
#define UTF16_UN_ENCODE(in8str) \
- free(in8str ## _16); } (void)0
+ free(in8str ## _16); } (void)0
#ifdef __cplusplus
}
diff --git a/release/datafiles/blender_icons.png b/release/datafiles/blender_icons.png
index a0d460b0153..55a83964a8b 100644
--- a/release/datafiles/blender_icons.png
+++ b/release/datafiles/blender_icons.png
Binary files differ
diff --git a/release/datafiles/colormanagement/config.ocio b/release/datafiles/colormanagement/config.ocio
index 121c5b2055c..d73561338ba 100644
--- a/release/datafiles/colormanagement/config.ocio
+++ b/release/datafiles/colormanagement/config.ocio
@@ -11,7 +11,7 @@ luma: [0.2126, 0.7152, 0.0722]
description: RRT version ut33
roles:
- reference: Linear ACES
+ reference: Linear
# Internal scene linear space
scene_linear: Linear
@@ -51,17 +51,19 @@ displays:
- !<View> {name: Raw, colorspace: Raw}
- !<View> {name: Log, colorspace: adx10}
None:
- - !<View> {name: Default, colorspace: raw}
+ - !<View> {name: Default, colorspace: Raw}
active_displays: [sRGB, DCIP3, Rec709, XYZ, None]
active_views: [Default, RRT, Raw, Log]
colorspaces:
- !<ColorSpace>
- name: Linear ACES
+ name: Linear
family: aces
equalitygroup:
bitdepth: 32f
+ description: |
+ Rec. 709 (Full Range), Blender native linear space
isdata: false
allocation: lg2
allocationvars: [-8.5, 5]
@@ -93,18 +95,19 @@ colorspaces:
- !<FileTransform> {src: adx_cid_to_rle.spi1d, interpolation: linear}
- !<LogTransform> {base: 10, direction: inverse}
- !<FileTransform> {src: adx_exp_to_aces.spimtx}
+ - !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: linear, direction: inverse}
- !<ColorSpace>
- name: Linear
+ name: Linear ACES
family:
equalitygroup:
bitdepth: 32f
description: |
- Rec. 709 (Full Range), Blender native linear space
+ ACES linear space
isdata: false
allocation: uniform
- allocationvars: [-0.125, 1.125]
- to_reference: !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: nearest}
+ allocationvars: [-8.5, 5]
+ to_reference: !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: linear, direction: inverse}
- !<ColorSpace>
name: rrt_srgb
@@ -116,6 +119,7 @@ colorspaces:
allocationvars: [0, 1]
from_reference: !<GroupTransform>
children:
+ - !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: nearest}
- !<AllocationTransform> {allocation: lg2, vars: [-8.5, 5]}
- !<FileTransform> {src: rrt_ut33_sRGB.spi3d, interpolation: tetrahedral}
@@ -132,7 +136,6 @@ colorspaces:
to_reference: !<GroupTransform>
children:
- !<FileTransform> {src: rec709.spi1d, interpolation: linear}
- - !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: nearest}
- !<ColorSpace>
name: rrt_rec709
@@ -144,6 +147,7 @@ colorspaces:
allocationvars: [0, 1]
from_reference: !<GroupTransform>
children:
+ - !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: nearest}
- !<AllocationTransform> {allocation: lg2, vars: [-8.5, 5]}
- !<FileTransform> {src: rrt_ut33_rec709.spi3d, interpolation: tetrahedral}
@@ -157,6 +161,7 @@ colorspaces:
allocationvars: [0, 1]
from_reference: !<GroupTransform>
children:
+ - !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: nearest}
- !<AllocationTransform> {allocation: lg2, vars: [-8.5, 5]}
- !<FileTransform> {src: rrt_ut33_p3dci.spi3d, interpolation: tetrahedral}
@@ -170,6 +175,7 @@ colorspaces:
allocationvars: [0, 1]
from_reference: !<GroupTransform>
children:
+ - !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: nearest}
- !<FileTransform> {src: aces_to_xyz.spimtx, interpolation: linear}
- !<ColorSpace>
@@ -182,6 +188,7 @@ colorspaces:
allocationvars: [0, 1]
from_reference: !<GroupTransform>
children:
+ - !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: nearest}
- !<AllocationTransform> {allocation: lg2, vars: [-8.5, 5]}
- !<FileTransform> {src: rrt_ut33_dcdm.spi3d, interpolation: tetrahedral}
@@ -197,7 +204,6 @@ colorspaces:
allocationvars: [0, 1]
from_reference: !<GroupTransform>
children:
- - !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: linear, direction: inverse}
- !<FileTransform> {src: srgb_to_xyz.spimtx, interpolation: linear}
- !<FileTransform> {src: dci_xyz.spi1d, interpolation: linear}
@@ -213,7 +219,6 @@ colorspaces:
to_reference: !<GroupTransform>
children:
- !<FileTransform> {src: lg10.spi1d, interpolation: nearest}
- - !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: nearest}
- !<ColorSpace>
name: srgb8
@@ -226,7 +231,7 @@ colorspaces:
allocation: uniform
from_reference: !<GroupTransform>
children:
- - !<ColorSpaceTransform> {src: Linear ACES, dst: lg10}
+ - !<ColorSpaceTransform> {src: Linear, dst: lg10}
- !<FileTransform> {src: spi_ocio_srgb_test.spi3d, interpolation: linear}
- !<ColorSpace>
@@ -242,7 +247,6 @@ colorspaces:
to_reference: !<GroupTransform>
children:
- !<FileTransform> {src: srgb.spi1d, interpolation: linear}
- - !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: nearest}
- !<ColorSpace>
name: VD16
@@ -256,7 +260,6 @@ colorspaces:
to_reference: !<GroupTransform>
children:
- !<FileTransform> {src: vd16.spi1d, interpolation: nearest}
- - !<FileTransform> {src: rec709_to_aces.spimtx, interpolation: linear}
- !<ColorSpace>
name: Non-Color
@@ -280,5 +283,5 @@ colorspaces:
allocation: uniform
from_reference: !<GroupTransform>
children:
- - !<ColorSpaceTransform> {src: Linear ACES, dst: lg10}
+ - !<ColorSpaceTransform> {src: Linear, dst: lg10}
- !<FileTransform> {src: colorworks_filmlg_to_p3.3dl, interpolation: linear}
diff --git a/release/datafiles/prvicons.png b/release/datafiles/prvicons.png
index 364d9678f0b..dc31964b33f 100644
--- a/release/datafiles/prvicons.png
+++ b/release/datafiles/prvicons.png
Binary files differ
diff --git a/release/datafiles/splash.png b/release/datafiles/splash.png
index ca209835c89..7f40ead3911 100644
--- a/release/datafiles/splash.png
+++ b/release/datafiles/splash.png
Binary files differ
diff --git a/release/datafiles/startup.blend b/release/datafiles/startup.blend
index 6f6c6646e31..5056246e743 100644
--- a/release/datafiles/startup.blend
+++ b/release/datafiles/startup.blend
Binary files differ
diff --git a/release/scripts/modules/addon_utils.py b/release/scripts/modules/addon_utils.py
index 485b4829b71..7e604c5de4c 100644
--- a/release/scripts/modules/addon_utils.py
+++ b/release/scripts/modules/addon_utils.py
@@ -275,7 +275,8 @@ def enable(module_name, default_set=True, persistent=False):
try:
mod.register()
except:
- print("Exception in module register(): %r" % getattr(mod, "__file__", module_name))
+ print("Exception in module register(): %r" %
+ getattr(mod, "__file__", module_name))
handle_error()
del sys.modules[module_name]
return None
@@ -310,18 +311,20 @@ def disable(module_name, default_set=True):
# possible this addon is from a previous session and didn't load a
# module this time. So even if the module is not found, still disable
# the addon in the user prefs.
- if mod:
+ if mod and getattr(mod, "__addon_enabled__", False) is not False:
mod.__addon_enabled__ = False
mod.__addon_persistent = False
try:
mod.unregister()
except:
- print("Exception in module unregister(): %r" % getattr(mod, "__file__", module_name))
+ print("Exception in module unregister(): %r" %
+ getattr(mod, "__file__", module_name))
import traceback
traceback.print_exc()
else:
- print("addon_utils.disable", module_name, "not loaded")
+ print("addon_utils.disable: %s not %s." %
+ (module_name, "disabled" if mod is None else "loaded"))
# could be in more then once, unlikely but better do this just in case.
addons = _bpy.context.user_preferences.addons
diff --git a/release/scripts/modules/bl_i18n_utils/bl_process_msg.py b/release/scripts/modules/bl_i18n_utils/bl_process_msg.py
index b884423606d..7e9266d0530 100644
--- a/release/scripts/modules/bl_i18n_utils/bl_process_msg.py
+++ b/release/scripts/modules/bl_i18n_utils/bl_process_msg.py
@@ -16,7 +16,7 @@
#
# ***** END GPL LICENSE BLOCK *****
-# <pep8-80 compliant>
+# <pep8 compliant>
# Write out messages.txt from Blender.
# XXX: This script is meant to be used from inside Blender!
@@ -33,8 +33,7 @@ from bl_i18n_utils import settings
SOURCE_DIR = settings.SOURCE_DIR
-CUSTOM_PY_UI_FILES = [os.path.abspath(os.path.join(SOURCE_DIR, p))
- for p in settings.CUSTOM_PY_UI_FILES]
+CUSTOM_PY_UI_FILES = [os.path.abspath(os.path.join(SOURCE_DIR, p)) for p in settings.CUSTOM_PY_UI_FILES]
FILE_NAME_MESSAGES = settings.FILE_NAME_MESSAGES
COMMENT_PREFIX = settings.COMMENT_PREFIX
CONTEXT_PREFIX = settings.CONTEXT_PREFIX
@@ -43,6 +42,7 @@ UNDOC_OPS_STR = settings.UNDOC_OPS_STR
NC_ALLOWED = settings.WARN_MSGID_NOT_CAPITALIZED_ALLOWED
+
def check(check_ctxt, messages, key, msgsrc):
if check_ctxt is None:
return
@@ -63,8 +63,7 @@ def check(check_ctxt, messages, key, msgsrc):
if key in py_in_rna[1]:
py_in_rna[0].add(key)
if not_capitalized is not None:
- if(key[1] not in NC_ALLOWED and key[1][0].isalpha() and
- not key[1][0].isupper()):
+ if(key[1] not in NC_ALLOWED and key[1][0].isalpha() and not key[1][0].isupper()):
not_capitalized.add(key)
if end_point is not None:
if key[1].strip().endswith('.'):
@@ -78,12 +77,11 @@ def dump_messages_rna(messages, check_ctxt):
import bpy
def classBlackList():
- blacklist_rna_class = [# core classes
- "Context", "Event", "Function", "UILayout",
- "BlendData",
+ blacklist_rna_class = [
+ # core classes
+ "Context", "Event", "Function", "UILayout", "BlendData",
# registerable classes
- "Panel", "Menu", "Header", "RenderEngine",
- "Operator", "OperatorMacro", "Macro",
+ "Panel", "Menu", "Header", "RenderEngine", "Operator", "OperatorMacro", "Macro",
"KeyingSetInfo", "UnknownType",
# window classes
"Window",
@@ -95,28 +93,22 @@ def dump_messages_rna(messages, check_ctxt):
# extend with all internal operators
# note that this uses internal api introspection functions
# all possible operator names
- op_ids = set(cls.bl_rna.identifier for cls in
- bpy.types.OperatorProperties.__subclasses__()) | \
- set(cls.bl_rna.identifier for cls in
- bpy.types.Operator.__subclasses__()) | \
- set(cls.bl_rna.identifier for cls in
- bpy.types.OperatorMacro.__subclasses__())
+ op_ids = set(cls.bl_rna.identifier for cls in bpy.types.OperatorProperties.__subclasses__()) | \
+ set(cls.bl_rna.identifier for cls in bpy.types.Operator.__subclasses__()) | \
+ set(cls.bl_rna.identifier for cls in bpy.types.OperatorMacro.__subclasses__())
get_instance = __import__("_bpy").ops.get_instance
path_resolve = type(bpy.context).__base__.path_resolve
for idname in op_ids:
op = get_instance(idname)
- # XXX Do not skip INTERNAL's anymore, some of those ops
- # show up in UI now!
+ # XXX Do not skip INTERNAL's anymore, some of those ops show up in UI now!
# if 'INTERNAL' in path_resolve(op, "bl_options"):
# blacklist_rna_class.append(idname)
# ---------------------------------------------------------------------
# Collect builtin classes we don't need to doc
blacklist_rna_class.append("Property")
- blacklist_rna_class.extend(
- [cls.__name__ for cls in
- bpy.types.Property.__subclasses__()])
+ blacklist_rna_class.extend([cls.__name__ for cls in bpy.types.Property.__subclasses__()])
# ---------------------------------------------------------------------
# Collect classes which are attached to collections, these are api
@@ -250,6 +242,12 @@ def dump_messages_rna(messages, check_ctxt):
cls_list.sort(key=full_class_id)
processed = 0
for cls in cls_list:
+ # XXX translation_context of Operator sub-classes are not "good"!
+ # So ignore those Operator sub-classes (anyway, will get the same from OperatorProperties
+ # sub-classes!)...
+ if issubclass(cls, bpy.types.Operator):
+ continue
+
walkClass(cls)
# classes.add(cls)
# Recursively process subclasses.
@@ -296,7 +294,7 @@ def dump_messages_pytext(messages, check_ctxt):
# check it has a 'text' argument
for (arg_pos, (arg_kw, arg)) in enumerate(func.parameters.items()):
if ((arg_kw in translate_kw) and
- (arg.is_output == False) and
+ (arg.is_output is False) and
(arg.type == 'STRING')):
func_translate_args.setdefault(func_id, []).append((arg_kw,
@@ -387,6 +385,7 @@ def dump_messages_pytext(messages, check_ctxt):
def dump_messages(do_messages, do_checks):
import collections
+ import re
def enable_addons():
"""For now, enable all official addons, before extracting msgids."""
@@ -417,21 +416,8 @@ def dump_messages(do_messages, do_checks):
getattr(cat, op).get_rna()
# check for strings like ": %d"
- ignore = ("%d", "%f", "%s", "%r", # string formatting
- "*", ".", "(", ")", "-", "/", "\\", "+", ":", "#", "%"
- "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
- "x", # used on its own eg: 100x200
- "X", "Y", "Z", "W", # used alone. no need to include
- )
-
- def filter_message(msg):
- msg_tmp = msg
- for ign in ignore:
- msg_tmp = msg_tmp.replace(ign, "")
- if not msg_tmp.strip():
- return True
- # we could filter out different strings here
- return False
+ ignore_reg = re.compile(r"^(?:[-*.()/\\+:%xWXYZ0-9]|%d|%f|%s|%r|\s)*$")
+ filter_message = ignore_reg.match
messages = getattr(collections, 'OrderedDict', dict)()
@@ -501,7 +487,7 @@ def dump_messages(do_messages, do_checks):
message_file.write(key.replace("\n", "") + "\n")
num_written += 1
- print("Written {} messages to: {} ({} were filtered out)." \
+ print("Written {} messages to: {} ({} were filtered out)."
"".format(num_written, FILE_NAME_MESSAGES, num_filtered))
@@ -514,17 +500,13 @@ def main():
import sys
back_argv = sys.argv
+ # Get rid of Blender args!
sys.argv = sys.argv[sys.argv.index("--") + 1:]
import argparse
- parser = argparse.ArgumentParser(description="Process UI messages " \
- "from inside Blender.")
- parser.add_argument('-c', '--no_checks', default=True,
- action="store_false",
- help="No checks over UI messages.")
- parser.add_argument('-m', '--no_messages', default=True,
- action="store_false",
- help="No export of UI messages.")
+ parser = argparse.ArgumentParser(description="Process UI messages from inside Blender.")
+ parser.add_argument('-c', '--no_checks', default=True, action="store_false", help="No checks over UI messages.")
+ parser.add_argument('-m', '--no_messages', default=True, action="store_false", help="No export of UI messages.")
parser.add_argument('-o', '--output', help="Output messages file path.")
args = parser.parse_args()
diff --git a/release/scripts/modules/bl_i18n_utils/check_po.py b/release/scripts/modules/bl_i18n_utils/check_po.py
index 03a933887c6..2e82047bb95 100755
--- a/release/scripts/modules/bl_i18n_utils/check_po.py
+++ b/release/scripts/modules/bl_i18n_utils/check_po.py
@@ -162,9 +162,9 @@ def main():
" {} specific context{} present:\n {}\n"
"".format(glob_stats["nbr"], glob_stats["lvl"] / glob_stats["nbr"],
glob_stats["lvl_ttips"] / glob_stats["nbr"],
- glob_stats["lvl_trans_ttips"]/glob_stats["nbr"],
- glob_stats["lvl_ttips_in_trans"]/glob_stats["nbr"],
- glob_stats["lvl_comm"]/glob_stats["nbr"], glob_stats["nbr_signs"],
+ glob_stats["lvl_trans_ttips"] / glob_stats["nbr"],
+ glob_stats["lvl_ttips_in_trans"] / glob_stats["nbr"],
+ glob_stats["lvl_comm"] / glob_stats["nbr"], glob_stats["nbr_signs"],
glob_stats["nbr_trans_signs"], nbr_contexts, _ctx_txt,
"\n ".join(glob_stats["contexts"]-{""})))
diff --git a/release/scripts/modules/bl_i18n_utils/import_po_from_branches.py b/release/scripts/modules/bl_i18n_utils/import_po_from_branches.py
index a15bea9ef0d..533dded3c57 100755
--- a/release/scripts/modules/bl_i18n_utils/import_po_from_branches.py
+++ b/release/scripts/modules/bl_i18n_utils/import_po_from_branches.py
@@ -39,6 +39,8 @@ except:
TRUNK_PO_DIR = settings.TRUNK_PO_DIR
BRANCHES_DIR = settings.BRANCHES_DIR
+IMPORT_LANGUAGES_SKIP = settings.IMPORT_LANGUAGES_SKIP
+
RTL_PREPROCESS_FILE = settings.RTL_PREPROCESS_FILE
PY3 = settings.PYTHON3_EXEC
@@ -63,7 +65,7 @@ def main():
threshold = float(args.threshold) / 100.0
for lang in os.listdir(BRANCHES_DIR):
- if args.langs and lang not in args.langs:
+ if (args.langs and lang not in args.langs) or lang in IMPORT_LANGUAGES_SKIP:
continue
po = os.path.join(BRANCHES_DIR, lang, ".".join((lang, "po")))
if os.path.exists(po):
diff --git a/release/scripts/modules/bl_i18n_utils/rtl_preprocess.py b/release/scripts/modules/bl_i18n_utils/rtl_preprocess.py
index 5ee5c71be8b..d28f87cf042 100755
--- a/release/scripts/modules/bl_i18n_utils/rtl_preprocess.py
+++ b/release/scripts/modules/bl_i18n_utils/rtl_preprocess.py
@@ -34,6 +34,7 @@
import sys
import ctypes
+import re
try:
import settings
@@ -87,44 +88,64 @@ FRIBIDI_FLAGS_ARABIC = FRIBIDI_FLAG_SHAPE_ARAB_PRES | \
FRIBIDI_FLAG_SHAPE_ARAB_LIGA
+MENU_DETECT_REGEX = re.compile("%x\\d+\\|")
+
+
##### Kernel processing funcs. #####
def protect_format_seq(msg):
"""
Find some specific escaping/formating sequences (like \", %s, etc.,
and protect them from any modification!
"""
+# LRM = "\u200E"
+# RLM = "\u200F"
LRE = "\u202A"
+ RLE = "\u202B"
PDF = "\u202C"
+ LRO = "\u202D"
+ RLO = "\u202E"
+ uctrl = {LRE, RLE, PDF, LRO, RLO}
# Most likely incomplete, but seems to cover current needs.
format_codes = set("tslfd")
digits = set(".0123456789")
+ if not msg:
+ return msg
+ elif MENU_DETECT_REGEX.search(msg):
+ # An ugly "menu" message, just force it whole LRE if not yet done.
+ if msg[0] not in {LRE, LRO}:
+ msg = LRE + msg
+
idx = 0
ret = []
ln = len(msg)
while idx < ln:
dlt = 1
+# # If we find a control char, skip any additional protection!
+# if msg[idx] in uctrl:
+# ret.append(msg[idx:])
+# break
# \" or \'
if idx < (ln - 1) and msg[idx] == '\\' and msg[idx + 1] in "\"\'":
dlt = 2
- # %x12
- elif idx < (ln - 2) and msg[idx] == '%' and msg[idx + 1] in "x" and \
- msg[idx + 2] in digits:
+ # %x12|
+ elif idx < (ln - 2) and msg[idx] == '%' and msg[idx + 1] in "x" and msg[idx + 2] in digits:
dlt = 2
- while (idx + dlt + 1) < ln and msg[idx + dlt + 1] in digits:
+ while (idx + dlt) < ln and msg[idx + dlt] in digits:
+ dlt += 1
+ if (idx + dlt) < ln and msg[idx + dlt] is '|':
dlt += 1
# %.4f
elif idx < (ln - 3) and msg[idx] == '%' and msg[idx + 1] in digits:
dlt = 2
- while (idx + dlt + 1) < ln and msg[idx + dlt + 1] in digits:
+ while (idx + dlt) < ln and msg[idx + dlt] in digits:
dlt += 1
- if (idx + dlt + 1) < ln and msg[idx + dlt + 1] in format_codes:
+ if (idx + dlt) < ln and msg[idx + dlt] in format_codes:
dlt += 1
else:
dlt = 1
# %s
- elif idx < (ln - 1) and msg[idx] == '%' and \
- msg[idx + 1] in format_codes:
+ elif idx < (ln - 1) and msg[idx] == '%' and msg[idx + 1] in format_codes:
dlt = 2
if dlt > 1:
diff --git a/release/scripts/modules/bl_i18n_utils/settings.py b/release/scripts/modules/bl_i18n_utils/settings.py
index d323dd37979..0db3f85f1ff 100644
--- a/release/scripts/modules/bl_i18n_utils/settings.py
+++ b/release/scripts/modules/bl_i18n_utils/settings.py
@@ -31,10 +31,67 @@ import os.path
# MISC
###############################################################################
+# The languages defined in Blender.
+LANGUAGES_CATEGORIES = (
+ # Min completeness level, UI english label.
+ ( 0.95, "Complete"),
+ ( 0.33, "In Progress"),
+ ( -1.0, "Starting"),
+)
+LANGUAGES = (
+ # ID, UI english label, ISO code.
+ ( 0, "Default (Default)", "DEFAULT", ""),
+ ( 1, "English (English)", "en_US", "english"),
+ ( 2, "Japanese (日本語)", "ja_JP", "japanese"),
+ ( 3, "Dutch (Nederlandse taal)", "nl_NL", "dutch"),
+ ( 4, "Italian (Italiano)", "it_IT", "italian"),
+ ( 5, "German (Deutsch)", "de_DE", "german"),
+ ( 6, "Finnish (Suomi)", "fi_FI", "finnish"),
+ ( 7, "Swedish (Svenska)", "sv_SE", "swedish"),
+ ( 8, "French (Français)", "fr_FR", "french"),
+ ( 9, "Spanish (Español)", "es", "spanish"),
+ (10, "Catalan (Català)", "ca_AD", "catalan"),
+ (11, "Czech (Český)", "cs_CZ", "czech"),
+ (12, "Portuguese (Português)", "pt_PT", "portuguese_portugal"),
+ (13, "Simplified Chinese (简体中文)", "zh_CN", "Chinese (Simplified)_China.1252"),
+ (14, "Traditional Chinese (繁體中文)", "zh_TW", "Chinese (Traditional)_China.1252"),
+ (15, "Russian (Русский)", "ru_RU", "russian"),
+ (16, "Croatian (Hrvatski)", "hr_HR", "croatian"),
+ (17, "Serbian (Српски)", "sr_RS", "serbian"),
+ (18, "Ukrainian (Український)", "uk_UA", "ukrainian"),
+ (19, "Polish (Polski)", "pl_PL", "polish"),
+ (20, "Romanian (Român)", "ro_RO", "romanian"),
+ # Using the utf8 flipped form of Arabic (العربية).
+ (21, "Arabic (ﺔﻴﺑﺮﻌﻟﺍ)", "ar_EG", "arabic"),
+ (22, "Bulgarian (Български)", "bg_BG", "bulgarian"),
+ (23, "Greek (Ελληνικά)", "el_GR", "greek"),
+ (24, "Korean (한국 언어)", "ko_KR", "korean"),
+ (25, "Nepali (नेपाली)", "ne_NP", "nepali"),
+ # Using the utf8 flipped form of Persian (فارسی).
+ (26, "Persian (ﯽﺳﺭﺎﻓ)", "fa_IR", "farsi"),
+ (27, "Indonesian (Bahasa indonesia)", "id_ID", "indonesian"),
+ (28, "Serbian Latin (Srpski latinica)", "sr_RS@latin", "serbian (latin)"),
+ (29, "Kyrgyz (Кыргыз тили)", "ky_KG", "kyrgyz"),
+ (30, "Turkish (Türkçe)", "tr_TR", "turkish"),
+ (31, "Hungarian (Magyar)", "hu_HU", "hungarian"),
+ (32, "Brazilian Portuguese (Português do Brasil)", "pt_BR", "protuguese_brazil"),
+ # Using the utf8 flipped form of Hebrew (עִבְרִית)).
+ (33, "Hebrew (תירִבְעִ)", "he_IL", "hebrew"),
+ (34, "Estonian (Eestlane)", "et_EE", "estonian"),
+ (35, "Esperanto (Esperanto)", "eo", "esperanto"),
+ (36, "Spanish from Spain (Español de España)", "es_ES", "spanish_spain"),
+)
+
+# Name of language file used by Blender to generate translations' menu.
+LANGUAGES_FILE = "languages"
+
# The min level of completeness for a po file to be imported from /branches
# into /trunk, as a percentage. -1 means "import everything".
IMPORT_MIN_LEVEL = -1
+# Languages in /branches we do not want to import in /trunk currently...
+IMPORT_LANGUAGES_SKIP = {'bg', 'ca', 'fi', 'el', 'ko', 'ne', 'pl', 'ro'}
+
# The comment prefix used in generated messages.txt file.
COMMENT_PREFIX = "#~ "
@@ -97,12 +154,22 @@ _msg_re = r"(?P<msg_raw>" + _str_whole_re.format(_="_msg") + r")"
PYGETTEXT_KEYWORDS = (() +
tuple((r"{}\(\s*" + _msg_re + r"\s*\)").format(it)
for it in ("IFACE_", "TIP_", "N_")) +
+
tuple((r"{}\(\s*" + _ctxt_re + r"\s*,\s*" + _msg_re + r"\s*\)").format(it)
- for it in ("CTX_IFACE_", "CTX_TIP_", "CTX_N_"))
+ for it in ("CTX_IFACE_", "CTX_TIP_", "CTX_N_")) +
+
+ tuple(("{}\\((?:[^\"',]+,){{1,2}}\\s*" + _msg_re + r"\s*(?:\)|,)").format(it)
+ for it in ("BKE_report", "BKE_reportf", "BKE_reports_prepend", "BKE_reports_prependf")) +
+
+ tuple(("{}\\((?:[^\"',]+,){{3}}\\s*" + _msg_re + r"\s*,").format(it)
+ for it in ("BMO_error_raise",)) +
+
+ tuple(("{}\\((?:[^\"',]+,)\\s*" + _msg_re + r"\s*(?:\)|,)").format(it)
+ for it in ("modifier_setError",))
)
ESCAPE_RE = (
- ('((?<!\\\\)"|(?<!\\\\)\\\\(?!\\\\|"))', r"\\\1"),
+ (r'((?<!\\)"|(?<!\\)\\(?!\\|"))', r"\\\1"),
('\t', r"\\t"),
)
@@ -136,37 +203,8 @@ WARN_MSGID_NOT_CAPITALIZED_ALLOWED = {
"iTaSC parameters",
"vBVH",
"rv",
- "en_US",
- "fr_FR",
- "it_IT",
- "ru_RU",
- "zh_CN",
- "es",
- "zh_TW",
- "ar_EG",
- "pt",
- "bg_BG",
- "ca_AD",
- "hr_HR",
- "cs_CZ",
- "nl_NL",
- "fi_FI",
- "de_DE",
- "el_GR",
- "id_ID",
- "ja_JP",
- "ky_KG",
- "ko_KR",
- "ne_NP",
- "fa_IR",
- "pl_PL",
- "ro_RO",
- "sr_RS",
- "sr_RS@latin",
- "sv_SE",
- "uk_UA",
- "tr_TR",
- "hu_HU",
+ "et_EE",
+ "eo",
"available with", # Is part of multi-line msg.
"virtual parents", # Is part of multi-line msg.
"description", # Addons' field. :/
@@ -178,6 +216,7 @@ WARN_MSGID_NOT_CAPITALIZED_ALLOWED = {
"p0",
"res",
}
+WARN_MSGID_NOT_CAPITALIZED_ALLOWED |= set(lng[2] for lng in LANGUAGES)
###############################################################################
@@ -192,47 +231,35 @@ TOOLS_DIR = os.path.join(os.path.dirname(__file__))
PYTHON3_EXEC = "python3"
# The Blender executable!
-# This is just an example, you’ll most likely have to edit it in your
-# user_settings.py!
-BLENDER_EXEC = os.path.abspath(os.path.join(TOOLS_DIR, "..", "..", "..", "..",
- "blender"))
+# This is just an example, you’ll most likely have to edit it in your user_settings.py!
+BLENDER_EXEC = os.path.abspath(os.path.join(TOOLS_DIR, "..", "..", "..", "..", "blender"))
-# The xgettext tool. You’ll likely have to edit it in your user_settings.py
-# if you’re under Windows.
+# The xgettext tool. You’ll likely have to edit it in your user_settings.py if you’re under Windows.
GETTEXT_XGETTEXT_EXECUTABLE = "xgettext"
-# The gettext msgmerge tool. You’ll likely have to edit it in your
-# user_settings.py if you’re under Windows.
+# The gettext msgmerge tool. You’ll likely have to edit it in your user_settings.py if you’re under Windows.
GETTEXT_MSGMERGE_EXECUTABLE = "msgmerge"
-# The gettext msgfmt "compiler". You’ll likely have to edit it in your
-# user_settings.py if you’re under Windows.
+# The gettext msgfmt "compiler". You’ll likely have to edit it in your user_settings.py if you’re under Windows.
GETTEXT_MSGFMT_EXECUTABLE = "msgfmt"
-# The svn binary... You’ll likely have to edit it in your
-# user_settings.py if you’re under Windows.
+# The svn binary... You’ll likely have to edit it in your user_settings.py if you’re under Windows.
SVN_EXECUTABLE = "svn"
# The FriBidi C compiled library (.so under Linux, .dll under windows...).
-# You’ll likely have to edit it in your user_settings.py if you’re under
-# Windows., e.g. using the included one:
+# You’ll likely have to edit it in your user_settings.py if you’re under Windows., e.g. using the included one:
# FRIBIDI_LIB = os.path.join(TOOLS_DIR, "libfribidi.dll")
FRIBIDI_LIB = "libfribidi.so.0"
-# The name of the (currently empty) file that must be present in a po's
-# directory to enable rtl-preprocess.
+# The name of the (currently empty) file that must be present in a po's directory to enable rtl-preprocess.
RTL_PREPROCESS_FILE = "is_rtl"
# The Blender source root path.
-# This is just an example, you’ll most likely have to override it in your
-# user_settings.py!
-SOURCE_DIR = os.path.abspath(os.path.join(TOOLS_DIR, "..", "..", "..", "..",
- "..", "..", "blender_msgs"))
+# This is just an example, you’ll most likely have to override it in your user_settings.py!
+SOURCE_DIR = os.path.abspath(os.path.join(TOOLS_DIR, "..", "..", "..", "..", "..", "..", "blender_msgs"))
-# The bf-translation repository (you'll likely have to override this in your
-# user_settings.py).
-I18N_DIR = os.path.abspath(os.path.join(TOOLS_DIR, "..", "..", "..", "..",
- "..", "..", "i18n"))
+# The bf-translation repository (you'll likely have to override this in your user_settings.py).
+I18N_DIR = os.path.abspath(os.path.join(TOOLS_DIR, "..", "..", "..", "..", "..", "..", "i18n"))
# The /branches path (overriden in bf-translation's i18n_override_settings.py).
BRANCHES_DIR = os.path.join(I18N_DIR, "branches")
@@ -252,12 +279,10 @@ FILE_NAME_MESSAGES = os.path.join(TRUNK_PO_DIR, "messages.txt")
# The Blender source path to check for i18n macros.
POTFILES_SOURCE_DIR = os.path.join(SOURCE_DIR, "source")
-# The "source" file storing which files should be processed by xgettext,
-# used to create FILE_NAME_POTFILES
+# The "source" file storing which files should be processed by xgettext, used to create FILE_NAME_POTFILES
FILE_NAME_SRC_POTFILES = os.path.join(TRUNK_PO_DIR, "_POTFILES.in")
-# The final (generated) file storing which files
-# should be processed by xgettext.
+# The final (generated) file storing which files should be processed by xgettext.
FILE_NAME_POTFILES = os.path.join(TRUNK_PO_DIR, "POTFILES.in")
# The template messages file.
@@ -265,9 +290,7 @@ FILE_NAME_POT = os.path.join(TRUNK_PO_DIR, ".".join((DOMAIN, "pot")))
# Other py files that should be searched for ui strings, relative to SOURCE_DIR.
# Needed for Cycles, currently...
-CUSTOM_PY_UI_FILES = [os.path.join("intern", "cycles", "blender",
- "addon", "ui.py"),
- ]
+CUSTOM_PY_UI_FILES = [os.path.join("intern", "cycles", "blender", "addon", "ui.py"),]
# A cache storing validated msgids, to avoid re-spellchecking them.
diff --git a/release/scripts/modules/bl_i18n_utils/spell_check_utils.py b/release/scripts/modules/bl_i18n_utils/spell_check_utils.py
index 46b369146b7..60a943d2bd4 100644
--- a/release/scripts/modules/bl_i18n_utils/spell_check_utils.py
+++ b/release/scripts/modules/bl_i18n_utils/spell_check_utils.py
@@ -37,10 +37,12 @@ dict_uimsgs = {
"aren", # aren't
"betweens", # yuck! in-betweens!
"boolean", "booleans",
+ "couldn", #couldn't
"decrement",
"derivate",
"doesn", # doesn't
"fader",
+ "hasn", # hasn't
"hoc", # ad-hoc
"indices",
"iridas",
@@ -89,7 +91,9 @@ dict_uimsgs = {
"fullscreen",
"gridline",
"hemi",
+ "inbetween",
"inscatter", "inscattering",
+ "libdata",
"lightless",
"lookup", "lookups",
"mathutils",
@@ -101,6 +105,7 @@ dict_uimsgs = {
"multires", "multiresolution",
"multisampling",
"multitexture",
+ "multiuser",
"namespace",
"keyconfig",
"playhead",
@@ -143,6 +148,7 @@ dict_uimsgs = {
"tilemode",
"timestamp", "timestamps",
"timestep", "timesteps",
+ "todo",
"un",
"unbake",
"uncomment",
@@ -157,7 +163,7 @@ dict_uimsgs = {
"unreacted",
"unregister",
"unselected",
- "unsubdivided",
+ "unsubdivided", "unsubdivide",
"unshadowed",
"unspill",
"unstitchable",
@@ -185,6 +191,7 @@ dict_uimsgs = {
"selectability",
"slurph",
"stitchable",
+ "symmetrize",
"trackability",
"transmissivity",
"rasterized", "rasterization",
@@ -230,6 +237,7 @@ dict_uimsgs = {
"quat", "quats",
"recalc", "recalcs",
"refl",
+ "sel",
"spec",
"struct", "structs",
"tex",
@@ -290,6 +298,7 @@ dict_uimsgs = {
"crossfade",
"deinterlace",
"dropoff",
+ "dv",
"eigenvectors",
"equirectangular",
"fisheye",
@@ -303,6 +312,7 @@ dict_uimsgs = {
"midtones",
"mipmap", "mipmaps", "mip",
"ngon", "ngons",
+ "ntsc",
"nurb", "nurbs",
"perlin",
"phong",
@@ -323,6 +333,7 @@ dict_uimsgs = {
"ztransp",
# Blender terms
+ "audaspace",
"bbone",
"breakdowner",
"bspline",
@@ -347,6 +358,8 @@ dict_uimsgs = {
"metaelement", "metaelements",
"metastrip", "metastrips",
"movieclip",
+ "mpoly",
+ "mtex",
"nabla",
"navmesh",
"outliner",
@@ -362,6 +375,7 @@ dict_uimsgs = {
"stucci",
"sunsky",
"subsurf",
+ "tessface", "tessfaces",
"texface",
"timeline", "timelines",
"tosphere",
@@ -376,6 +390,7 @@ dict_uimsgs = {
"catmull",
"catrom",
"chebychev",
+ "courant",
"kutta",
"lennard",
"minkowski",
@@ -406,6 +421,7 @@ dict_uimsgs = {
"dpi",
"dvar",
"dx",
+ "eo",
"fh",
"fov",
"fft",
@@ -448,6 +464,7 @@ dict_uimsgs = {
"dop", # BLI K-Dop BVH
"ik",
"nla",
+ "py",
"qbvh",
"rna",
"rvo",
diff --git a/release/scripts/modules/bl_i18n_utils/update_branches.py b/release/scripts/modules/bl_i18n_utils/update_branches.py
index 199b09aa13a..4c38a2f71fb 100755
--- a/release/scripts/modules/bl_i18n_utils/update_branches.py
+++ b/release/scripts/modules/bl_i18n_utils/update_branches.py
@@ -38,6 +38,8 @@ except:
PY3 = settings.PYTHON3_EXEC
+FILE_NAME_POT = settings.FILE_NAME_POT
+
def main():
import argparse
@@ -71,16 +73,13 @@ def main():
if t:
ret = t
- # Regenerate POTFILES.in.
-# cmd = (PY3, "./update_potinput.py")
-# t = subprocess.call(cmd)
-# if t:
-# ret = t
-
# Generate a temp pot file.
- dummy, potfile = tempfile.mkstemp(suffix=".pot",
- prefix="blender_pot_")
- os.close(dummy)
+ # Back to having a pot file in trunk/po. It's quite useful for translators that want to start
+ # a new translation and not not want to bother generating their own po from scratch!
+# dummy, potfile = tempfile.mkstemp(suffix=".pot",
+# prefix="blender_pot_")
+# os.close(dummy)
+ potfile = FILE_NAME_POT
cmd = [PY3, "./update_pot.py", "-i", msgfile, "-o", potfile]
if not args.no_checks:
cmd.append("-c")
diff --git a/release/scripts/modules/bl_i18n_utils/update_languages_menu.py b/release/scripts/modules/bl_i18n_utils/update_languages_menu.py
new file mode 100755
index 00000000000..d45a5543220
--- /dev/null
+++ b/release/scripts/modules/bl_i18n_utils/update_languages_menu.py
@@ -0,0 +1,148 @@
+#!/usr/bin/python3
+
+# ***** BEGIN GPL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# ***** END GPL LICENSE BLOCK *****
+
+# <pep8 compliant>
+
+# Update "languages" text file used by Blender at runtime to build translations menu.
+
+import os
+import sys
+import shutil
+
+try:
+ import settings
+ import utils
+except:
+ from . import (settings, utils)
+
+TRUNK_PO_DIR = settings.TRUNK_PO_DIR
+TRUNK_MO_DIR = settings.TRUNK_MO_DIR
+
+LANGUAGES_CATEGORIES = settings.LANGUAGES_CATEGORIES
+LANGUAGES = settings.LANGUAGES
+LANGUAGES_FILE = settings.LANGUAGES_FILE
+
+OK = 0
+MISSING = 1
+TOOLOW = 2
+FORBIDDEN = 3
+FLAG_MESSAGES = {
+ OK: "",
+ MISSING: "No translation yet!",
+ TOOLOW: "Not enough advanced to be included...",
+ FORBIDDEN: "Explicitly forbidden!",
+}
+
+def find_matching_po(languages, stats, forbidden):
+ """Match languages defined in LANGUAGES setting to relevant po, if possible!"""
+ ret = []
+ for uid, label, org_key, long_loc in languages:
+ key = org_key
+ if key not in stats:
+ # Try to simplify the key (eg from es_ES to es).
+ if '_' in org_key:
+ key = org_key[0:org_key.index('_')]
+ # For stuff like sr_SR@latin -> sr@latin...
+ if '@' in org_key:
+ key = key + org_key[org_key.index('@'):]
+ if key in stats:
+ if key in forbidden:
+ ret.append((stats[key], uid, label, org_key, long_loc, FORBIDDEN))
+ else:
+ ret.append((stats[key], uid, label, org_key, long_loc, OK))
+ else:
+ ret.append((0.0, uid, label, org_key, long_loc, MISSING))
+ return ret
+
+def main():
+ import argparse
+ parser = argparse.ArgumentParser(description=""
+ "Update 'languages' text file used by Blender at runtime to build translations menu.")
+ parser.add_argument('-m', '--min_translation', type=int, default=-100,
+ help="Minimum level of translation, as a percentage "
+ "(translations below this are commented out in menu).")
+ parser.add_argument('langs', metavar='ISO_code', nargs='*',
+ help="Unconditionally exclude those languages from the menu.")
+ args = parser.parse_args()
+
+ ret = 0
+ min_trans = args.min_translation / 100.0
+ forbidden = set(args.langs)
+ # 'DEFAULT' and en_US are always valid, fully-translated "languages"!
+ stats = {"DEFAULT": 1.0, "en_US": 1.0}
+
+ # Get the "done level" of each po in trunk...
+ for po in os.listdir(TRUNK_PO_DIR):
+ if po.endswith(".po") and not po.endswith("_raw.po"):
+ lang = os.path.basename(po)[:-3]
+ u1, u2, _stats = utils.parse_messages(os.path.join(TRUNK_PO_DIR, po))
+ stats[lang] = _stats["trans_msg"] / _stats["tot_msg"]
+
+ # Generate languages file used by Blender's i18n system.
+ # First, match all entries in LANGUAGES to a lang in stats, if possible!
+ stats = find_matching_po(LANGUAGES, stats, forbidden)
+ limits = sorted(LANGUAGES_CATEGORIES, key=lambda it: it[0], reverse=True)
+ idx = 0
+ stats = sorted(stats, key=lambda it: it[0], reverse=True)
+ langs_cats = [[] for i in range(len(limits))]
+ highest_uid = 0
+ for prop, uid, label, key, long_loc, flag in stats:
+ if prop < limits[idx][0]:
+ # Sub-sort languages by iso-codes.
+ langs_cats[idx].sort(key=lambda it: it[2])
+ idx += 1
+ if prop < min_trans and flag == OK:
+ flag = TOOLOW
+ langs_cats[idx].append((uid, label, key, long_loc, flag))
+ if abs(uid) > highest_uid:
+ highest_uid = abs(uid)
+ # Sub-sort last group of languages by iso-codes!
+ langs_cats[idx].sort(key=lambda it: it[2])
+ with open(os.path.join(TRUNK_MO_DIR, LANGUAGES_FILE), 'w', encoding="utf-8") as f:
+ f.write("# File used by Blender to know which languages (translations) are available, \n")
+ f.write("# and to generate translation menu.\n")
+ f.write("#\n")
+ f.write("# File format:\n")
+ f.write("# ID:MENULABEL:ISOCODE:WINCODE\n")
+ f.write("# ID must be unique, except for 0 value (marks categories for menu).\n")
+ f.write("# Line starting with a # are comments!\n")
+ f.write("#\n")
+ f.write("# Automatically generated by bl_i18n_utils/update_languages_menu.py script.\n")
+ f.write("# Highest ID currently in use: {}\n".format(highest_uid))
+ for cat, langs_cat in zip(limits, langs_cats):
+ f.write("#\n")
+ # Write "category menu label"...
+ if langs_cat:
+ f.write("0:{}::\n".format(cat[1]))
+ else:
+ # Do not write the category if it has no language!
+ f.write("# Void category! #0:{}:\n".format(cat[1]))
+ # ...and all matching language entries!
+ for uid, label, key, long_loc, flag in langs_cat:
+ if flag == OK:
+ f.write("{}:{}:{}:{}\n".format(uid, label, key, long_loc))
+ else:
+ # Non-existing, commented entry!
+ f.write("# {} #{}:{}:{}:{}\n".format(FLAG_MESSAGES[flag], uid, label, key, long_loc))
+
+
+if __name__ == "__main__":
+ print("\n\n *** Running {} *** \n".format(__file__))
+ sys.exit(main())
diff --git a/release/scripts/modules/bl_i18n_utils/update_mo.py b/release/scripts/modules/bl_i18n_utils/update_mo.py
index 4a68f19fab0..7f68736593c 100755
--- a/release/scripts/modules/bl_i18n_utils/update_mo.py
+++ b/release/scripts/modules/bl_i18n_utils/update_mo.py
@@ -69,9 +69,9 @@ def main():
"under {}.".format(TRUNK_MO_DIR))
parser.add_argument('langs', metavar='ISO_code', nargs='*',
help="Restrict processed languages to those.")
- parser.add_argument('po', help="Only process that po file (implies --mo).",
+ parser.add_argument('--po', help="Only process that po file (implies --mo).",
nargs='?')
- parser.add_argument('mo', help="Mo file to generate (implies --po).",
+ parser.add_argument('--mo', help="Mo file to generate (implies --po).",
nargs='?')
args = parser.parse_args()
@@ -97,6 +97,7 @@ def main():
t = process_po(po, lang)
if t:
ret = t
+
return ret
diff --git a/release/scripts/modules/bl_i18n_utils/update_pot.py b/release/scripts/modules/bl_i18n_utils/update_pot.py
index f98fc5d7705..51197b86678 100755
--- a/release/scripts/modules/bl_i18n_utils/update_pot.py
+++ b/release/scripts/modules/bl_i18n_utils/update_pot.py
@@ -38,6 +38,9 @@ except:
from . import (settings, utils)
+LANGUAGES_CATEGORIES = settings.LANGUAGES_CATEGORIES
+LANGUAGES = settings.LANGUAGES
+
COMMENT_PREFIX = settings.COMMENT_PREFIX
COMMENT_PREFIX_SOURCE = settings.COMMENT_PREFIX_SOURCE
CONTEXT_PREFIX = settings.CONTEXT_PREFIX
@@ -117,28 +120,30 @@ def check_file(path, rel_path, messages):
def py_xgettext(messages):
+ forbidden = set()
+ forced = set()
with open(SRC_POTFILES) as src:
- forbidden = set()
- forced = set()
for l in src:
if l[0] == '-':
forbidden.add(l[1:].rstrip('\n'))
elif l[0] != '#':
forced.add(l.rstrip('\n'))
- for root, dirs, files in os.walk(POTFILES_DIR):
- if "/.svn" in root:
+ for root, dirs, files in os.walk(POTFILES_DIR):
+ if "/.svn" in root:
+ continue
+ for fname in files:
+ if os.path.splitext(fname)[1] not in PYGETTEXT_ALLOWED_EXTS:
continue
- for fname in files:
- if os.path.splitext(fname)[1] not in PYGETTEXT_ALLOWED_EXTS:
- continue
- path = os.path.join(root, fname)
- rel_path = os.path.relpath(path, SOURCE_DIR)
- if rel_path in forbidden | forced:
- continue
- check_file(path, rel_path, messages)
- for path in forced:
- if os.path.exists(path):
- check_file(os.path.join(SOURCE_DIR, path), path, messages)
+ path = os.path.join(root, fname)
+ rel_path = os.path.relpath(path, SOURCE_DIR)
+ if rel_path in forbidden:
+ continue
+ elif rel_path in forced:
+ forced.remove(rel_path)
+ check_file(path, rel_path, messages)
+ for path in forced:
+ if os.path.exists(path):
+ check_file(os.path.join(SOURCE_DIR, path), path, messages)
# Spell checking!
@@ -187,7 +192,7 @@ def get_svnrev():
def gen_empty_pot():
- blender_rev = get_svnrev()
+ blender_rev = get_svnrev().decode()
utctime = time.gmtime()
time_str = time.strftime("%Y-%m-%d %H:%M+0000", utctime)
year_str = time.strftime("%Y", utctime)
@@ -231,8 +236,8 @@ def merge_messages(msgs, states, messages, do_checks, spell_cache):
def main():
- parser = argparse.ArgumentParser(description="Update blender.pot file " \
- "from messages.txt")
+ parser = argparse.ArgumentParser(description="Update blender.pot file from messages.txt and source code parsing, "
+ "and performs some checks over msgids.")
parser.add_argument('-w', '--warning', action="store_true",
help="Show warnings.")
parser.add_argument('-i', '--input', metavar="File",
@@ -250,7 +255,7 @@ def main():
print("Running fake py gettext…")
# Not using any more xgettext, simpler to do it ourself!
- messages = {}
+ messages = utils.new_messages()
py_xgettext(messages)
print("Finished, found {} messages.".format(len(messages)))
@@ -259,7 +264,6 @@ def main():
spell_cache = pickle.load(f)
else:
spell_cache = set()
- print(len(spell_cache))
print("Generating POT file {}…".format(FILE_NAME_POT))
msgs, states = gen_empty_pot()
@@ -268,7 +272,7 @@ def main():
# add messages collected automatically from RNA
print("\tMerging RNA messages from {}…".format(FILE_NAME_MESSAGES))
- messages = {}
+ messages = utils.new_messages()
with open(FILE_NAME_MESSAGES, encoding="utf-8") as f:
srcs = []
context = ""
@@ -290,11 +294,22 @@ def main():
print("\tMerged {} messages ({} were already present)."
"".format(num_added, num_present))
+ print("\tAdding languages labels...")
+ messages = {(CONTEXT_DEFAULT, lng[1]):
+ ("Languages’ labels from bl_i18n_utils/settings.py",)
+ for lng in LANGUAGES}
+ messages.update({(CONTEXT_DEFAULT, cat[1]):
+ ("Language categories’ labels from bl_i18n_utils/settings.py",)
+ for cat in LANGUAGES_CATEGORIES})
+ num_added, num_present = merge_messages(msgs, states, messages,
+ True, spell_cache)
+ tot_messages += num_added
+ print("\tAdded {} language messages.".format(num_added))
+
# Write back all messages into blender.pot.
utils.write_messages(FILE_NAME_POT, msgs, states["comm_msg"],
states["fuzzy_msg"])
- print(len(spell_cache))
if SPELL_CACHE and spell_cache:
with open(SPELL_CACHE, 'wb') as f:
pickle.dump(spell_cache, f)
diff --git a/release/scripts/modules/bl_i18n_utils/update_trunk.py b/release/scripts/modules/bl_i18n_utils/update_trunk.py
index b7f8f375744..9b904ec861a 100755
--- a/release/scripts/modules/bl_i18n_utils/update_trunk.py
+++ b/release/scripts/modules/bl_i18n_utils/update_trunk.py
@@ -35,34 +35,55 @@ import shutil
try:
import settings
+ import utils
except:
- from . import settings
+ from . import (settings, utils)
+BRANCHES_DIR = settings.BRANCHES_DIR
TRUNK_PO_DIR = settings.TRUNK_PO_DIR
TRUNK_MO_DIR = settings.TRUNK_MO_DIR
+LANGUAGES_CATEGORIES = settings.LANGUAGES_CATEGORIES
+LANGUAGES = settings.LANGUAGES
+LANGUAGES_FILE = settings.LANGUAGES_FILE
+
PY3 = settings.PYTHON3_EXEC
+def find_matching_po(languages, stats):
+ """Match languages defined in LANGUAGES setting to relevant po, if possible!"""
+ ret = []
+ for uid, label, org_key in languages:
+ key = org_key
+ if key not in stats:
+ # Try to simplify the key (eg from es_ES to es).
+ if '_' in org_key:
+ key = org_key[0:org_key.index('_')]
+ if '@' in org_key:
+ key = key + org_key[org_key.index('@'):]
+ if key in stats:
+ ret.append((stats[key], uid, label, org_key))
+ else:
+ # Mark invalid entries, so that we can put them in the languages file,
+ # but commented!
+ ret.append((0.0, -uid, label, org_key))
+ return ret
+
def main():
import argparse
- parser = argparse.ArgumentParser(description="" \
- "Update trunk from branches:\n" \
- "* Remove po’s in trunk.\n" \
- "* Copy po’s from branches advanced enough.\n" \
- "* Clean po’s in trunk.\n" \
- "* Compile po’s in trunk in mo’s, keeping " \
- "track of those failing.\n" \
- "* Remove po’s and mo’s (and their dir’s) that " \
- "failed to compile or are no more present in trunk.")
- parser.add_argument('-t', '--threshold', type=int,
- help="Import threshold, as a percentage.")
- parser.add_argument('-p', '--po', action="store_false",
- help="Do not remove failing po’s.")
- parser.add_argument('-m', '--mo', action="store_false",
- help="Do not remove failing mo’s.")
- parser.add_argument('langs', metavar='ISO_code', nargs='*',
- help="Restrict processed languages to those.")
+ parser = argparse.ArgumentParser(description=""
+ "Update trunk from branches:\n"
+ "* Remove po’s in trunk.\n"
+ "* Copy po’s from branches advanced enough.\n"
+ "* Clean po’s in trunk.\n"
+ "* Compile po’s in trunk in mo’s, keeping track of those failing.\n"
+ "* Remove po’s and mo’s (and their dir’s) that "
+ "failed to compile or are no more present in trunk."
+ "* Generate languages file used by Blender's i18n.")
+ parser.add_argument('-t', '--threshold', type=int, help="Import threshold, as a percentage.")
+ parser.add_argument('-p', '--po', action="store_true", help="Remove failing po’s.")
+ parser.add_argument('-m', '--mo', action="store_true", help="Remove failing mo’s.")
+ parser.add_argument('langs', metavar='ISO_code', nargs='*', help="Restrict processed languages to those.")
args = parser.parse_args()
ret = 0
@@ -89,7 +110,7 @@ def main():
# Add in failed all mo’s no more having relevant po’s in trunk.
for lang in os.listdir(TRUNK_MO_DIR):
- if lang == ".svn":
+ if lang in {".svn", LANGUAGES_FILE}:
continue # !!!
if not os.path.exists(os.path.join(TRUNK_PO_DIR, ".".join((lang, "po")))):
failed.add(lang)
@@ -115,6 +136,13 @@ def main():
if t:
ret = t
failed.add(lang)
+ continue
+
+ # Generate languages file used by Blender's i18n system.
+ cmd = [PY3, "./update_languages_menu.py"]
+ t = subprocess.call(cmd)
+ if t:
+ ret = t
# Remove failing po’s, mo’s and related dir’s.
for lang in failed:
diff --git a/release/scripts/modules/bl_i18n_utils/utils.py b/release/scripts/modules/bl_i18n_utils/utils.py
index 3e5394d85a4..9481f750092 100644
--- a/release/scripts/modules/bl_i18n_utils/utils.py
+++ b/release/scripts/modules/bl_i18n_utils/utils.py
@@ -41,6 +41,10 @@ def is_tooltip(msgid):
return len(msgid) > 30
+def new_messages():
+ return getattr(collections, 'OrderedDict', dict)()
+
+
def parse_messages(fname):
"""
Returns a tupple (messages, states, stats).
@@ -78,7 +82,7 @@ def parse_messages(fname):
msgctxt_lines = []
comment_lines = []
- messages = getattr(collections, 'OrderedDict', dict)()
+ messages = new_messages()
translated_messages = set()
fuzzy_messages = set()
commented_messages = set()
@@ -95,7 +99,6 @@ def parse_messages(fname):
msgctxt_lines = []
comment_lines = []
-
def finalize_message():
nonlocal reading_msgid, reading_msgstr, reading_msgctxt, \
reading_comment, is_fuzzy, is_translated, is_commented, \
@@ -225,7 +228,6 @@ def parse_messages(fname):
if reading_msgstr:
finalize_message()
-
return (messages,
{"trans_msg": translated_messages,
"fuzzy_msg": fuzzy_messages,
@@ -284,7 +286,7 @@ def gen_empty_messages(blender_rev, time_str, year_str):
"""Generate an empty messages & state data (only header if present!)."""
header_key = ("", "")
- messages = getattr(collections, 'OrderedDict', dict)()
+ messages = new_messages()
messages[header_key] = {
"msgid_lines": [""],
"msgctxt_lines": [],
diff --git a/release/scripts/modules/bpy/path.py b/release/scripts/modules/bpy/path.py
index 41fe052c434..d32b69b501c 100644
--- a/release/scripts/modules/bpy/path.py
+++ b/release/scripts/modules/bpy/path.py
@@ -264,8 +264,8 @@ def module_names(path, recursive=False):
if recursive:
for mod_name, mod_path in module_names(directory, True):
modules.append(("%s.%s" % (filename, mod_name),
- mod_path,
- ))
+ mod_path,
+ ))
return modules
diff --git a/release/scripts/modules/bpy/utils.py b/release/scripts/modules/bpy/utils.py
index e24b61a757d..573694ff08e 100644
--- a/release/scripts/modules/bpy/utils.py
+++ b/release/scripts/modules/bpy/utils.py
@@ -59,6 +59,7 @@ import addon_utils as _addon_utils
_script_module_dirs = "startup", "modules"
+
def _test_import(module_name, loaded_modules):
use_time = _bpy.app.debug_python
@@ -615,12 +616,15 @@ def _blender_default_map():
# hooks for doc lookups
_manual_map = [_blender_default_map]
+
def register_manual_map(manual_hook):
_manual_map.append(manual_hook)
+
def unregister_manual_map(manual_hook):
_manual_map.remove(manual_hook)
+
def manual_map():
# reverse so default is called last
for cb in reversed(_manual_map):
@@ -633,4 +637,3 @@ def manual_map():
continue
yield prefix, url_manual_mapping
-
diff --git a/release/scripts/modules/bpy_extras/mesh_utils.py b/release/scripts/modules/bpy_extras/mesh_utils.py
index ad0fe06b68b..ad3cf8c08ec 100644
--- a/release/scripts/modules/bpy_extras/mesh_utils.py
+++ b/release/scripts/modules/bpy_extras/mesh_utils.py
@@ -232,7 +232,7 @@ def edge_loops_from_tessfaces(mesh, tessfaces=None, seams=()):
ed_adj = edges[context_loop[-1]]
if len(ed_adj) != 2:
# the original edge had 2 other edges
- if other_dir and flipped == False:
+ if other_dir and flipped is False:
flipped = True # only flip the list once
context_loop.reverse()
ed_adj[:] = []
diff --git a/release/scripts/modules/bpy_extras/object_utils.py b/release/scripts/modules/bpy_extras/object_utils.py
index b1de1fd47a4..46731b807f7 100644
--- a/release/scripts/modules/bpy_extras/object_utils.py
+++ b/release/scripts/modules/bpy_extras/object_utils.py
@@ -187,3 +187,16 @@ class AddObjectHelper:
name="Rotation",
subtype='EULER',
)
+
+
+def object_add_grid_scale(context):
+ """
+ Return scale which should be applied on object data to align it to grid scale
+ """
+
+ space_data = context.space_data
+
+ if space_data and space_data.type == 'VIEW_3D':
+ return space_data.grid_scale_unit
+
+ return 1.0
diff --git a/release/scripts/modules/bpy_types.py b/release/scripts/modules/bpy_types.py
index 9ad9a7affc3..4cd823d9184 100644
--- a/release/scripts/modules/bpy_types.py
+++ b/release/scripts/modules/bpy_types.py
@@ -689,10 +689,10 @@ class Menu(StructRNA, _GenericUI, metaclass=RNAMeta):
files = []
for directory in searchpaths:
files.extend([(f, os.path.join(directory, f))
- for f in os.listdir(directory)
- if (not f.startswith("."))
- if ((filter_ext is None) or
- (filter_ext(os.path.splitext(f)[1])))
+ for f in os.listdir(directory)
+ if (not f.startswith("."))
+ if ((filter_ext is None) or
+ (filter_ext(os.path.splitext(f)[1])))
])
files.sort()
diff --git a/release/scripts/modules/bpyml.py b/release/scripts/modules/bpyml.py
index 42d2bf94fba..e942006010b 100644
--- a/release/scripts/modules/bpyml.py
+++ b/release/scripts/modules/bpyml.py
@@ -160,7 +160,7 @@ if __name__ == "__main__":
from bpyml_test import *
draw = [
- ui()[
+ ui()[
split()[
column()[
prop(data='context.scene.render', property='use_stamp_time', text='Time'),
diff --git a/release/scripts/modules/console_python.py b/release/scripts/modules/console_python.py
index 6e8fee07c0f..60dfa2b6344 100644
--- a/release/scripts/modules/console_python.py
+++ b/release/scripts/modules/console_python.py
@@ -30,7 +30,7 @@ _BPY_MAIN_OWN = True
def add_scrollback(text, text_type):
for l in text.split("\n"):
bpy.ops.console.scrollback_append(text=l.replace("\t", " "),
- type=text_type)
+ type=text_type)
def replace_help(namespace):
@@ -195,7 +195,7 @@ def execute(context):
# insert a new blank line
bpy.ops.console.history_append(text="", current_character=0,
- remove_duplicates=True)
+ remove_duplicates=True)
# Insert the output into the editor
# not quite correct because the order might have changed,
@@ -294,8 +294,8 @@ def copy_as_script(context):
sc = context.space_data
lines = [
"import bpy",
- "import bpy.context as C",
- "import bpy.data as D",
+ "from bpy import data as D",
+ "from bpy import context as C",
"from mathutils import *",
"from math import *",
"",
@@ -304,7 +304,7 @@ def copy_as_script(context):
for line in sc.scrollback:
text = line.body
type = line.type
-
+
if type == 'INFO': # ignore autocomp.
continue
if type == 'INPUT':
diff --git a/release/scripts/modules/console_shell.py b/release/scripts/modules/console_shell.py
index 8beff24eedb..42348f453cd 100644
--- a/release/scripts/modules/console_shell.py
+++ b/release/scripts/modules/console_shell.py
@@ -26,7 +26,7 @@ language_id = "shell"
def add_scrollback(text, text_type):
for l in text.split("\n"):
bpy.ops.console.scrollback_append(text=l.replace("\t", " "),
- type=text_type)
+ type=text_type)
def shell_run(text):
@@ -57,7 +57,7 @@ def execute(context):
# insert a new blank line
bpy.ops.console.history_append(text="", current_character=0,
- remove_duplicates=True)
+ remove_duplicates=True)
sc.prompt = os.getcwd() + PROMPT
return {'FINISHED'}
diff --git a/release/scripts/modules/rna_info.py b/release/scripts/modules/rna_info.py
index 0ef2ac5164d..6f4b63fc99a 100644
--- a/release/scripts/modules/rna_info.py
+++ b/release/scripts/modules/rna_info.py
@@ -249,7 +249,7 @@ class InfoPropertyRNA:
def get_arg_default(self, force=True):
default = self.default_str
- if default and (force or self.is_required == False):
+ if default and (force or self.is_required is False):
return "%s=%s" % (self.identifier, default)
return self.identifier
@@ -493,7 +493,7 @@ def BuildRNAInfo():
# Arrange so classes are always defined in the correct order
deps_ok = False
- while deps_ok == False:
+ while deps_ok is False:
deps_ok = True
rna_done = set()
diff --git a/release/scripts/modules/rna_xml.py b/release/scripts/modules/rna_xml.py
index a259a4ec396..fc8e3125228 100644
--- a/release/scripts/modules/rna_xml.py
+++ b/release/scripts/modules/rna_xml.py
@@ -250,14 +250,17 @@ def xml2rna(root_xml,
if value_xml.startswith("#"):
# read hexidecimal value as float array
value_xml_split = value_xml[1:]
- value_xml_coerce = [int(value_xml_split[i:i + 2], 16) / 255 for i in range(0, len(value_xml_split), 2)]
+ value_xml_coerce = [int(value_xml_split[i:i + 2], 16) / 255 for i in range(0, len(value_xml_split), 2)]
del value_xml_split
else:
value_xml_split = value_xml.split()
try:
value_xml_coerce = [int(v) for v in value_xml_split]
except ValueError:
- value_xml_coerce = [float(v) for v in value_xml_split]
+ try:
+ value_xml_coerce = [float(v) for v in value_xml_split]
+ except ValueError: # bool vector property
+ value_xml_coerce = [{'TRUE': True, 'FALSE': False}[v] for v in value_xml_split]
del value_xml_split
tp_name = 'ARRAY'
diff --git a/release/scripts/presets/interface_theme/back_to_black.xml b/release/scripts/presets/interface_theme/back_to_black.xml
index 24f135e8548..805aa9bd184 100644
--- a/release/scripts/presets/interface_theme/back_to_black.xml
+++ b/release/scripts/presets/interface_theme/back_to_black.xml
@@ -9,6 +9,7 @@
handle_auto="#909000"
handle_sel_auto="#f0ff40"
bone_pose="#50c8ff"
+ bone_pose_active="#8cffff"
bone_solid="#c8c8c8"
bundle_solid="#c8c8c8"
camera="#000000"
diff --git a/release/scripts/presets/interface_theme/blender_24x.xml b/release/scripts/presets/interface_theme/blender_24x.xml
index 79d1ed4ecf4..232276e300e 100644
--- a/release/scripts/presets/interface_theme/blender_24x.xml
+++ b/release/scripts/presets/interface_theme/blender_24x.xml
@@ -9,6 +9,7 @@
handle_auto="#909000"
handle_sel_auto="#f0ff40"
bone_pose="#50c8ff"
+ bone_pose_active="#8cffff"
bone_solid="#c8c8c8"
bundle_solid="#c8c8c8"
camera="#000000"
diff --git a/release/scripts/presets/interface_theme/elsyiun.xml b/release/scripts/presets/interface_theme/elsyiun.xml
index bfeb3a0175e..581f5ce82d6 100644
--- a/release/scripts/presets/interface_theme/elsyiun.xml
+++ b/release/scripts/presets/interface_theme/elsyiun.xml
@@ -9,6 +9,7 @@
handle_auto="#909000"
handle_sel_auto="#f0ff40"
bone_pose="#50c8ff"
+ bone_pose_active="#8cffff"
bone_solid="#c8c8c8"
bundle_solid="#c8c8c8"
camera="#000000"
@@ -282,7 +283,7 @@
<ThemeInfo>
<space>
<ThemeSpaceGeneric header="#3b3b3b"
- header_text="#8b8b8b"
+ header_text="#000000"
header_text_hi="#000000"
button="#3b3b3b"
button_text="#000000"
diff --git a/release/scripts/presets/interface_theme/hexagon.xml b/release/scripts/presets/interface_theme/hexagon.xml
index 7727d860a90..61730583396 100644
--- a/release/scripts/presets/interface_theme/hexagon.xml
+++ b/release/scripts/presets/interface_theme/hexagon.xml
@@ -9,6 +9,7 @@
handle_auto="#909000"
handle_sel_auto="#f0ff40"
bone_pose="#50c8ff"
+ bone_pose_active="#8cffff"
bone_solid="#c8c8c8"
bundle_solid="#c8c8c8"
camera="#000000"
diff --git a/release/scripts/presets/interface_theme/ubuntu_ambiance.xml b/release/scripts/presets/interface_theme/ubuntu_ambiance.xml
index 72852e27604..05075f06239 100644
--- a/release/scripts/presets/interface_theme/ubuntu_ambiance.xml
+++ b/release/scripts/presets/interface_theme/ubuntu_ambiance.xml
@@ -1,68 +1,69 @@
<bpy>
<Theme>
<view_3d>
- <ThemeView3D object_active="#f58032"
+ <ThemeView3D object_active="#f47421"
editmesh_active="#ffffff80"
act_spline="#ee4000"
- handle_align="#862074"
- handle_sel_align="#f090a0"
- handle_auto="#909000"
- handle_sel_auto="#f0ff40"
+ handle_align="#93237f"
+ handle_sel_align="#f47421"
+ handle_auto="#00c59a"
+ handle_sel_auto="#f47421"
bone_pose="#50c8ff"
+ bone_pose_active="#8cffff"
bone_solid="#c8c8c8"
bundle_solid="#c8c8c8"
- camera="#000000"
- camera_path="#000000"
+ camera="#159dce"
+ camera_path="#7dbd00"
frame_current="#60c040"
edge_crease="#ce33b8"
extra_edge_len="#200000"
edge_seam="#db4100"
- edge_select="#f68d46"
+ edge_select="#f47421"
edge_sharp="#ff4c00"
edge_facesel="#4b4b4b"
- empty="#000000"
+ empty="#93237f"
face="#75757512"
extra_face_angle="#002000"
extra_face_area="#0059ee"
- face_dot="#ff8500"
+ face_dot="#f47421"
facedot_size="3"
normal="#19b6ee"
- face_select="#ff85003c"
- handle_free="#000000"
- handle_sel_free="#000000"
+ face_select="#f474213c"
+ handle_free="#a5ca00"
+ handle_sel_free="#f47421"
grid="#3c3b37"
- lamp="#00000028"
+ lamp="#ffffff34"
lastsel_point="#ffffff"
nurb_uline="#909000"
nurb_vline="#862074"
nurb_sel_uline="#f0ff40"
nurb_sel_vline="#d15d85"
- object_grouped="#083008"
- object_grouped_active="#55bb55"
+ object_grouped="#117211"
+ object_grouped_active="#65d665"
object_selected="#f15800"
- outline_width="1"
+ outline_width="2"
panel="#a5a5a57f"
skin_root="#000000"
- speaker="#000000"
+ speaker="#93237f"
transform="#ffffff"
handle_vect="#409030"
handle_sel_vect="#82c036"
vertex="#c96cb8"
vertex_normal="#19b6ee"
- vertex_select="#f15800"
+ vertex_select="#f47421"
vertex_size="2"
- wire="#862074">
+ wire="#93237f">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#3c3b37"
button_text="#9c9c9c"
button_text_hi="#ffffff"
button_title="#9c9c9c"
- text="#000000"
+ text="#9c9c9c"
text_hi="#ffffff"
- title="#000000"
+ title="#9c9c9c"
back="#131311">
</ThemeSpaceGeneric>
</space>
@@ -70,7 +71,7 @@
</view_3d>
<clip_editor>
<ThemeClipEditor active_marker="#ffffff"
- frame_current="#c07100"
+ frame_current="#f47421"
disabled_marker="#7f0000"
grid="#302e2c"
handle_vertex="#000000"
@@ -85,16 +86,16 @@
strips="#0c0a0a"
strips_selected="#ff8c00">
<space>
- <ThemeSpaceGeneric header="#3c3b37"
- header_text="#000000"
+ <ThemeSpaceGeneric header="#464541"
+ header_text="#9c9c9c"
header_text_hi="#ffffff"
button="#3c3b37"
- button_text="#000000"
+ button_text="#ffffff"
button_text_hi="#ffffff"
- button_title="#000000"
- text="#000000"
+ button_title="#9c9c9c"
+ text="#9c9c9c"
text_hi="#ffffff"
- title="#000000"
+ title="#9c9c9c"
back="#131311">
</ThemeSpaceGeneric>
</space>
@@ -108,14 +109,14 @@
</ThemeClipEditor>
</clip_editor>
<console>
- <ThemeConsole cursor="#dc5a00"
- line_error="#dc0000"
- line_info="#85aa00"
- line_input="#828282"
- line_output="#f58032">
+ <ThemeConsole cursor="#f47421"
+ line_error="#ff0000"
+ line_info="#f47421"
+ line_input="#19b6ee"
+ line_output="#97f500">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#3c3b37"
button_text="#000000"
@@ -132,7 +133,7 @@
<dopesheet_editor>
<ThemeDopeSheet active_channels_group="#a2b15c"
channel_group="#4f6549"
- channels="#74736e"
+ channels="#9c9c9c"
channels_selected="#6592f5"
frame_current="#f58032"
dopesheet_channel="#64486e"
@@ -142,26 +143,26 @@
long_key_selected="#f47421"
summary="#00000000"
value_sliders="#000000"
- view_sliders="#969696">
+ view_sliders="#9c9c9c">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#cacaca"
header_text_hi="#ffffff"
button="#3c3b37"
- button_text="#000000"
+ button_text="#9c9c9c"
button_text_hi="#ffffff"
- button_title="#000000"
- text="#000000"
+ button_title="#9c9c9c"
+ text="#e7e7e7"
text_hi="#ffffff"
- title="#000000"
+ title="#9c9c9c"
back="#131311">
</ThemeSpaceGeneric>
</space>
<space_list>
<ThemeSpaceListGeneric list="#3c3b37"
- list_text="#000000"
- list_text_hi="#ffffff"
- list_title="#dddddd">
+ list_text="#e2e2e2"
+ list_text_hi="#f47421"
+ list_title="#ffffff">
</ThemeSpaceListGeneric>
</space_list>
</ThemeDopeSheet>
@@ -174,8 +175,8 @@
selected_file="#6b395a"
tiles="#3c3b37">
<space>
- <ThemeSpaceGeneric header="#3c3b37"
- header_text="#000000"
+ <ThemeSpaceGeneric header="#464541"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#727272"
button_text="#000000"
@@ -198,50 +199,50 @@
</file_browser>
<graph_editor>
<ThemeGraphEditor active_channels_group="#87b17d"
- handle_align="#803060"
- handle_sel_align="#f090a0"
- handle_auto="#909000"
- handle_sel_auto="#f0ff40"
- handle_auto_clamped="#994030"
- handle_sel_auto_clamped="#f0af90"
+ handle_align="#93237f"
+ handle_sel_align="#f49600"
+ handle_auto="#00c59a"
+ handle_sel_auto="#f49600"
+ handle_auto_clamped="#03aa60"
+ handle_sel_auto_clamped="#f49600"
channel_group="#4f6549"
channels_region="#707070"
frame_current="#f58032"
dopesheet_channel="#695c6e"
dopesheet_subchannel="#7c8996"
- handle_free="#000000"
- handle_sel_free="#000000"
+ handle_free="#a5ca00"
+ handle_sel_free="#f49600"
grid="#3c3b37"
- handle_vertex="#000000"
- handle_vertex_select="#f47421"
- handle_vertex_size="3"
- lastsel_point="#000000"
+ handle_vertex="#bbbbbb"
+ handle_vertex_select="#f49600"
+ handle_vertex_size="4"
+ lastsel_point="#fafafa"
panel="#ffffff"
handle_vect="#409030"
handle_sel_vect="#40c030"
- vertex="#000000"
- vertex_select="#ff8500"
- vertex_size="3"
+ vertex="#ffffff"
+ vertex_select="#f49600"
+ vertex_size="4"
window_sliders="#95948f">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#3c3b37"
- button_text="#c3c2bc"
+ button_text="#9c9c9c"
button_text_hi="#ffffff"
- button_title="#9e9d98"
- text="#000000"
+ button_title="#9c9c9c"
+ text="#e9e9e9"
text_hi="#ffffff"
- title="#000000"
+ title="#9c9c9c"
back="#131311">
</ThemeSpaceGeneric>
</space>
<space_list>
<ThemeSpaceListGeneric list="#3c3b37"
- list_text="#000000"
- list_text_hi="#ffffff"
- list_title="#000000">
+ list_text="#e2e2e2"
+ list_text_hi="#f47421"
+ list_title="#ffffff">
</ThemeSpaceListGeneric>
</space_list>
</ThemeGraphEditor>
@@ -264,7 +265,7 @@
vertex_size="3">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#3c3b37"
button_text="#b9b9b9"
@@ -300,16 +301,16 @@
<ThemeLogicEditor panel="#acacac">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
- button="#131311"
+ button="#353430"
button_text="#acacac"
button_text_hi="#ffffff"
button_title="#7d7d7d"
text="#acacac"
text_hi="#ffffff"
title="#000000"
- back="#131311">
+ back="#29001b">
</ThemeSpaceGeneric>
</space>
</ThemeLogicEditor>
@@ -332,7 +333,7 @@
view_sliders="#969696">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#3c3b37"
button_text="#000000"
@@ -368,7 +369,7 @@
wire="#f45b00">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#353430"
button_text="#acacac"
@@ -394,7 +395,7 @@
selected_highlight="#6a3859">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#3c3b37"
button_text="#000000"
@@ -412,7 +413,7 @@
<ThemeProperties panel="#3c3b37">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#3c3b37"
button_text="#000000"
@@ -443,32 +444,32 @@
window_sliders="#a0a0a0">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#3c3b37"
- button_text="#000000"
+ button_text="#acacac"
button_text_hi="#ffffff"
- button_title="#000000"
- text="#000000"
+ button_title="#acacac"
+ text="#acacac"
text_hi="#ffffff"
- title="#000000"
+ title="#acacac"
back="#191919">
</ThemeSpaceGeneric>
</space>
</ThemeSequenceEditor>
</sequence_editor>
<text_editor>
- <ThemeTextEditor cursor="#df5106"
- syntax_special="#8c8c28"
+ <ThemeTextEditor cursor="#f47421"
+ syntax_special="#33a500"
line_numbers_background="#3c3b37"
- selected_text="#ffffff"
- syntax_builtin="#df3ac2"
+ selected_text="#641f44"
+ syntax_builtin="#d6ff01"
syntax_comment="#249d60"
- syntax_numbers="#3c68ff"
- syntax_string="#aa2694">
+ syntax_numbers="#972144"
+ syntax_string="#6e00ff">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#191919"
button_text="#95948f"
@@ -487,13 +488,13 @@
grid="#272727">
<space>
<ThemeSpaceGeneric header="#464541"
- header_text="#000000"
+ header_text="#acacac"
header_text_hi="#ffffff"
button="#3c3b37"
- button_text="#000000"
+ button_text="#9c9c9c"
button_text_hi="#ffffff"
- button_title="#000000"
- text="#949494"
+ button_title="#9c9c9c"
+ text="#9c9c9c"
text_hi="#ffffff"
title="#000000"
back="#131311">
@@ -531,13 +532,13 @@
<wcol_menu_back>
<ThemeWidgetColors inner="#131312db"
inner_sel="#2d2d2de6"
- item="#cbc3bbff"
+ item="#6a3859ff"
outline="#0d0d0d"
shadedown="-20"
shadetop="25"
show_shaded="FALSE"
- text="#7a7a7a"
- text_sel="#ffffff">
+ text="#dddddd"
+ text_sel="#dddddd">
</ThemeWidgetColors>
</wcol_menu_back>
<wcol_menu_item>
@@ -573,7 +574,7 @@
shadetop="20"
show_shaded="TRUE"
text="#dfdbcf"
- text_sel="#fffbed">
+ text_sel="#f47421">
</ThemeWidgetColors>
</wcol_num>
<wcol_option>
@@ -614,7 +615,7 @@
shadetop="25"
show_shaded="FALSE"
text="#dddddd"
- text_sel="#fff7fb">
+ text_sel="#ffffff">
</ThemeWidgetColors>
</wcol_pulldown>
<wcol_radio>
@@ -626,7 +627,7 @@
shadetop="5"
show_shaded="TRUE"
text="#dfdbcf"
- text_sel="#ffffff">
+ text_sel="#dfdbcf">
</ThemeWidgetColors>
</wcol_radio>
<wcol_regular>
@@ -638,16 +639,16 @@
shadetop="21"
show_shaded="TRUE"
text="#dfdfdf"
- text_sel="#ffffff">
+ text_sel="#dfdfdf">
</ThemeWidgetColors>
</wcol_regular>
<wcol_scroll>
- <ThemeWidgetColors inner="#020202b4"
+ <ThemeWidgetColors inner="#000000b4"
inner_sel="#646464c6"
- item="#2c2b28ff"
- outline="#0d0d0d"
- shadedown="-5"
- shadetop="5"
+ item="#2e2d2aff"
+ outline="#000000"
+ shadedown="-10"
+ shadetop="10"
show_shaded="TRUE"
text="#cbc3bb"
text_sel="#ffffff">
@@ -684,7 +685,7 @@
shadetop="-10"
show_shaded="TRUE"
text="#dfdbcf"
- text_sel="#fffaec">
+ text_sel="#ffffff">
</ThemeWidgetColors>
</wcol_text>
<wcol_toggle>
@@ -720,7 +721,7 @@
shadetop="25"
show_shaded="FALSE"
text="#ffffff"
- text_sel="#ffffff">
+ text_sel="#ff5d0d">
</ThemeWidgetColors>
</wcol_tooltip>
</ThemeUserInterface>
diff --git a/release/scripts/presets/keyconfig/maya.py b/release/scripts/presets/keyconfig/maya.py
index fe011a51e22..b5df519cf59 100644
--- a/release/scripts/presets/keyconfig/maya.py
+++ b/release/scripts/presets/keyconfig/maya.py
@@ -133,42 +133,42 @@ kmi = km.keymap_items.new('wm.context_toggle_enum', 'Z', 'PRESS', alt=True)
kmi.properties.data_path = 'space_data.viewport_shade'
kmi.properties.value_1 = 'TEXTURED'
kmi.properties.value_2 = 'SOLID'
-kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'PRESS')
+kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'RELEASE')
kmi.properties.extend = False
kmi.properties.center = False
kmi.properties.object = False
kmi.properties.enumerate = False
-kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'PRESS', shift=True)
+kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'RELEASE', shift=True)
kmi.properties.extend = True
kmi.properties.center = False
kmi.properties.object = False
kmi.properties.enumerate = False
-kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'PRESS', ctrl=True)
+kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'RELEASE', ctrl=True)
kmi.properties.extend = False
kmi.properties.center = True
kmi.properties.object = False
kmi.properties.enumerate = False
-kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'PRESS', alt=True)
+kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'RELEASE', alt=True)
kmi.properties.extend = False
kmi.properties.center = False
kmi.properties.object = False
kmi.properties.enumerate = True
-kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'PRESS', shift=True, ctrl=True)
+kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'RELEASE', shift=True, ctrl=True)
kmi.properties.extend = True
kmi.properties.center = True
kmi.properties.object = False
kmi.properties.enumerate = False
-kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'PRESS', ctrl=True, alt=True)
+kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'RELEASE', ctrl=True, alt=True)
kmi.properties.extend = False
kmi.properties.center = True
kmi.properties.object = False
kmi.properties.enumerate = True
-kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'PRESS', shift=True, alt=True)
+kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'RELEASE', shift=True, alt=True)
kmi.properties.extend = True
kmi.properties.center = False
kmi.properties.object = False
kmi.properties.enumerate = True
-kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'PRESS', shift=True, ctrl=True, alt=True)
+kmi = km.keymap_items.new('view3d.select', 'SELECTMOUSE', 'RELEASE', shift=True, ctrl=True, alt=True)
kmi.properties.extend = True
kmi.properties.center = True
kmi.properties.object = False
diff --git a/release/scripts/presets/tracking_settings/blurry_footage.py b/release/scripts/presets/tracking_settings/blurry_footage.py
index 0423f7662a2..de6f085f53d 100644
--- a/release/scripts/presets/tracking_settings/blurry_footage.py
+++ b/release/scripts/presets/tracking_settings/blurry_footage.py
@@ -14,4 +14,4 @@ settings.default_margin = 0
settings.use_default_red_channel = True
settings.use_default_green_channel = True
settings.use_default_blue_channel = True
-settings.default_correlation_min = 0.6 \ No newline at end of file
+settings.default_correlation_min = 0.6
diff --git a/release/scripts/presets/tracking_settings/default.py b/release/scripts/presets/tracking_settings/default.py
index 0aef22195e7..3c61ea7cd7f 100644
--- a/release/scripts/presets/tracking_settings/default.py
+++ b/release/scripts/presets/tracking_settings/default.py
@@ -14,4 +14,4 @@ settings.default_margin = 0
settings.use_default_red_channel = True
settings.use_default_green_channel = True
settings.use_default_blue_channel = True
-settings.default_correlation_min = 0.75 \ No newline at end of file
+settings.default_correlation_min = 0.75
diff --git a/release/scripts/presets/tracking_settings/fast_motion.py b/release/scripts/presets/tracking_settings/fast_motion.py
index f7f6b37db74..6051f235b0c 100644
--- a/release/scripts/presets/tracking_settings/fast_motion.py
+++ b/release/scripts/presets/tracking_settings/fast_motion.py
@@ -14,4 +14,4 @@ settings.default_margin = 0
settings.use_default_red_channel = True
settings.use_default_green_channel = True
settings.use_default_blue_channel = True
-settings.default_correlation_min = 0.6 \ No newline at end of file
+settings.default_correlation_min = 0.6
diff --git a/release/scripts/presets/tracking_settings/planar.py b/release/scripts/presets/tracking_settings/planar.py
index b25df1fc466..49a64046002 100644
--- a/release/scripts/presets/tracking_settings/planar.py
+++ b/release/scripts/presets/tracking_settings/planar.py
@@ -14,4 +14,4 @@ settings.default_margin = 0
settings.use_default_red_channel = True
settings.use_default_green_channel = True
settings.use_default_blue_channel = True
-settings.default_correlation_min = 0.75 \ No newline at end of file
+settings.default_correlation_min = 0.75
diff --git a/release/scripts/startup/bl_operators/add_mesh_torus.py b/release/scripts/startup/bl_operators/add_mesh_torus.py
index 6c48ae72e4b..552247f0940 100644
--- a/release/scripts/startup/bl_operators/add_mesh_torus.py
+++ b/release/scripts/startup/bl_operators/add_mesh_torus.py
@@ -49,9 +49,9 @@ def add_torus(major_rad, minor_rad, major_seg, minor_seg):
angle = 2 * pi * minor_index / minor_seg
vec = quat * Vector((major_rad + (cos(angle) * minor_rad),
- 0.0,
- (sin(angle) * minor_rad),
- ))
+ 0.0,
+ (sin(angle) * minor_rad),
+ ))
verts.extend(vec[:])
@@ -133,13 +133,15 @@ class AddTorus(Operator, object_utils.AddObjectHelper):
)
def execute(self, context):
- if self.use_abso == True:
+ grid_scale = object_utils.object_add_grid_scale(context)
+
+ if self.use_abso is True:
extra_helper = (self.abso_major_rad - self.abso_minor_rad) * 0.5
self.major_radius = self.abso_minor_rad + extra_helper
self.minor_radius = extra_helper
- verts_loc, faces = add_torus(self.major_radius,
- self.minor_radius,
+ verts_loc, faces = add_torus(self.major_radius * grid_scale,
+ self.minor_radius * grid_scale,
self.major_segments,
self.minor_segments)
diff --git a/release/scripts/startup/bl_operators/anim.py b/release/scripts/startup/bl_operators/anim.py
index 98bad276109..902c7007fb9 100644
--- a/release/scripts/startup/bl_operators/anim.py
+++ b/release/scripts/startup/bl_operators/anim.py
@@ -189,7 +189,7 @@ class BakeAction(Operator):
name="Only Selected",
default=True,
)
- clear_consraints = BoolProperty(
+ clear_constraints = BoolProperty(
name="Clear Constraints",
default=False,
)
@@ -212,9 +212,9 @@ class BakeAction(Operator):
self.only_selected,
'POSE' in self.bake_types,
'OBJECT' in self.bake_types,
- self.clear_consraints,
+ self.clear_constraints,
True,
- )
+ )
if action is None:
self.report({'INFO'}, "Nothing to bake")
@@ -252,8 +252,8 @@ class ClearUselessActions(Operator):
for action in bpy.data.actions:
# if only user is "fake" user...
- if ((self.only_unused is False) or
- (action.use_fake_user and action.users == 1)):
+ if ((self.only_unused is False) or
+ (action.use_fake_user and action.users == 1)):
# if it has F-Curves, then it's a "action library"
# (i.e. walk, wave, jump, etc.)
diff --git a/release/scripts/startup/bl_operators/clip.py b/release/scripts/startup/bl_operators/clip.py
index c45d2f2e702..70967a01d1c 100644
--- a/release/scripts/startup/bl_operators/clip.py
+++ b/release/scripts/startup/bl_operators/clip.py
@@ -57,7 +57,7 @@ def CLIP_set_viewport_background(context, all_screens, clip, clip_user):
space_v3d.show_background_images = True
CLIP_spaces_walk(context, all_screens, 'VIEW_3D', 'VIEW_3D',
- set_background, clip, clip_user)
+ set_background, clip, clip_user)
def CLIP_camera_for_clip(context, clip):
@@ -329,7 +329,7 @@ object's movement caused by this constraint"""
if not con:
self.report({'ERROR'},
- "Motion Tracking constraint to be converted not found")
+ "Motion Tracking constraint to be converted not found")
return {'CANCELLED'}
@@ -341,7 +341,7 @@ object's movement caused by this constraint"""
if not clip:
self.report({'ERROR'},
- "Movie clip to use tracking data from isn't set")
+ "Movie clip to use tracking data from isn't set")
return {'CANCELLED'}
@@ -461,9 +461,9 @@ class CLIP_OT_setup_tracking_scene(Operator):
scene.camera = camob
camob.matrix_local = (Matrix.Translation((7.481, -6.508, 5.344)) *
- Matrix.Rotation(0.815, 4, 'Z') *
- Matrix.Rotation(0.011, 4, 'Y') *
- Matrix.Rotation(1.109, 4, 'X'))
+ Matrix.Rotation(0.815, 4, 'Z') *
+ Matrix.Rotation(0.011, 4, 'Y') *
+ Matrix.Rotation(1.109, 4, 'X'))
return camob
@@ -629,7 +629,7 @@ class CLIP_OT_setup_tracking_scene(Operator):
if need_stabilization:
tree.links.new(distortion.outputs["Image"],
- stabilize.inputs["Image"])
+ stabilize.inputs["Image"])
tree.links.new(stabilize.outputs["Image"], scale.inputs["Image"])
else:
tree.links.new(distortion.outputs["Image"], scale.inputs["Image"])
diff --git a/release/scripts/startup/bl_operators/console.py b/release/scripts/startup/bl_operators/console.py
index fd95da02b28..307165a4d18 100644
--- a/release/scripts/startup/bl_operators/console.py
+++ b/release/scripts/startup/bl_operators/console.py
@@ -129,6 +129,6 @@ class ConsoleLanguage(Operator):
# insert a new blank line
bpy.ops.console.history_append(text="", current_character=0,
- remove_duplicates=True)
+ remove_duplicates=True)
return {'FINISHED'}
diff --git a/release/scripts/startup/bl_operators/mesh.py b/release/scripts/startup/bl_operators/mesh.py
index 3dc25d84aca..df21349da47 100644
--- a/release/scripts/startup/bl_operators/mesh.py
+++ b/release/scripts/startup/bl_operators/mesh.py
@@ -92,7 +92,7 @@ class MeshMirrorUV(Operator):
puvs[i] = tuple(uv.uv for uv in uv_loops[lstart:lend])
puvs_cpy[i] = tuple(uv.copy() for uv in puvs[i])
puvsel[i] = (False not in
- (uv.select for uv in uv_loops[lstart:lend]))
+ (uv.select for uv in uv_loops[lstart:lend]))
# Vert idx of the poly.
vidxs[i] = tuple(l.vertex_index for l in loops[lstart:lend])
# As we have no poly.center yet...
diff --git a/release/scripts/startup/bl_operators/node.py b/release/scripts/startup/bl_operators/node.py
index ee005fcb8bb..fb264cb3429 100644
--- a/release/scripts/startup/bl_operators/node.py
+++ b/release/scripts/startup/bl_operators/node.py
@@ -22,12 +22,16 @@ import bpy
from bpy.types import Operator
from bpy.props import EnumProperty
-# XXX These node item lists should actually be generated by a callback at operator execution time (see node_type_items below),
-# using the active node tree from the context. Due to a difficult bug in bpy this is not possible (item list memory gets freed too early),
+# XXX These node item lists should actually be generated by a callback at
+# operator execution time (see node_type_items below),
+# using the active node tree from the context.
+# Due to a difficult bug in bpy this is not possible
+# (item list memory gets freed too early),
# so for now just copy the static item lists to these global variables.
#
-# In the custom_nodes branch, the static per-tree-type node items are replaced by a single independent type list anyway (with a poll function
-# to limit node types to the respective trees). So this workaround is only temporary.
+# In the custom_nodes branch, the static per-tree-type node items are replaced
+# by a single independent type list anyway (with a poll function to limit node
+# types to the respective trees). So this workaround is only temporary.
# lazy init
node_type_items_dict = {}
@@ -39,18 +43,21 @@ node_group_prefix = 'GROUP_'
# Generate a list of enum items for a given node class
# Copy existing type enum, adding a prefix to distinguish from node groups
-# Skip the base node group type, node groups will be added below for all existing group trees
+# Skip the base node group type,
+# node groups will be added below for all existing group trees
def node_type_items(node_class):
return [(node_type_prefix + item.identifier, item.name, item.description)
- for item in node_class.bl_rna.properties['type'].enum_items if item.identifier != 'GROUP']
+ for item in node_class.bl_rna.properties['type'].enum_items
+ if item.identifier != 'GROUP']
# Generate items for node group types
# Filter by the given tree_type
-# Node group trees don't have a description property yet (could add this as a custom property though)
+# Node group trees don't have a description property yet
+# (could add this as a custom property though)
def node_group_items(tree_type):
return [(node_group_prefix + group.name, group.name, '')
- for group in bpy.data.node_groups if group.type == tree_type]
+ for group in bpy.data.node_groups if group.type == tree_type]
# Returns the enum item list for the edited tree in the context
@@ -71,7 +78,11 @@ def node_type_items_cb(self, context):
})
# XXX Does not work correctly, see comment above
- #return [(item.identifier, item.name, item.description, item.value) for item in tree.nodes.bl_rna.functions['new'].parameters['type'].enum_items]
+ '''
+ return [(item.identifier, item.name, item.description, item.value)
+ for item in
+ tree.nodes.bl_rna.functions['new'].parameters['type'].enum_items]
+ '''
if tree.type in node_type_items_dict:
return node_type_items_dict[tree.type] + node_group_items(tree.type)
@@ -85,7 +96,8 @@ class NODE_OT_add_search(Operator):
bl_label = "Search and Add Node"
bl_options = {'REGISTER', 'UNDO'}
- # XXX this should be called 'node_type' but the operator search property is hardcoded to 'type' by a hack in bpy_operator_wrap.c ...
+ # XXX this should be called 'node_type' but the operator search
+ # property is hardcoded to 'type' by a hack in bpy_operator_wrap.c ...
type = EnumProperty(
name="Node Type",
description="Node type",
@@ -98,14 +110,17 @@ class NODE_OT_add_search(Operator):
space = context.space_data
tree = space.edit_tree
- # Enum item identifier has an additional prefix to distinguish base node types from node groups
+ # Enum item identifier has an additional prefix to
+ # distinguish base node types from node groups
item = self.type
if item.startswith(node_type_prefix):
# item means base node type
node = tree.nodes.new(type=item[len(node_type_prefix):])
elif item.startswith(node_group_prefix):
# item means node group type
- node = tree.nodes.new(type='GROUP', group=bpy.data.node_groups[item[len(node_group_prefix):]])
+ node = tree.nodes.new(
+ type='GROUP',
+ group=bpy.data.node_groups[item[len(node_group_prefix):]])
else:
return None
@@ -133,7 +148,8 @@ class NODE_OT_add_search(Operator):
v2d = context.region.view2d
# convert mouse position to the View2D for later node placement
- space.cursor_location = v2d.region_to_view(event.mouse_region_x, event.mouse_region_y)
+ space.cursor_location = v2d.region_to_view(event.mouse_region_x,
+ event.mouse_region_y)
context.window_manager.invoke_search_popup(self)
return {'CANCELLED'}
diff --git a/release/scripts/startup/bl_operators/object.py b/release/scripts/startup/bl_operators/object.py
index 5000d718182..4e90f2e8585 100644
--- a/release/scripts/startup/bl_operators/object.py
+++ b/release/scripts/startup/bl_operators/object.py
@@ -408,13 +408,13 @@ class ShapeTransfer(Operator):
n2loc_to = v2_to + target_normals[i2] * edlen_to
pt = barycentric_transform(orig_shape_coords[i1],
- v2, v1, n1loc,
- v2_to, v1_to, n1loc_to)
+ v2, v1, n1loc,
+ v2_to, v1_to, n1loc_to)
median_coords[i1].append(pt)
pt = barycentric_transform(orig_shape_coords[i2],
- v1, v2, n2loc,
- v1_to, v2_to, n2loc_to)
+ v1, v2, n2loc,
+ v1_to, v2_to, n2loc_to)
median_coords[i2].append(pt)
# apply the offsets to the new shape
@@ -507,7 +507,7 @@ class JoinUVs(Operator):
if obj_other != obj and obj_other.type == 'MESH':
mesh_other = obj_other.data
if mesh_other != mesh:
- if mesh_other.tag == False:
+ if mesh_other.tag is False:
mesh_other.tag = True
if len(mesh_other.loops) != nbr_loops:
@@ -520,7 +520,7 @@ class JoinUVs(Operator):
len(mesh_other.polygons),
nbr_loops,
),
- )
+ )
else:
uv_other = mesh_other.uv_layers.active
if not uv_other:
diff --git a/release/scripts/startup/bl_operators/object_quick_effects.py b/release/scripts/startup/bl_operators/object_quick_effects.py
index 35b496b6dd0..cd0b63a6b78 100644
--- a/release/scripts/startup/bl_operators/object_quick_effects.py
+++ b/release/scripts/startup/bl_operators/object_quick_effects.py
@@ -299,7 +299,6 @@ class QuickSmoke(Operator):
style = EnumProperty(
name="Smoke Style",
items=(('STREAM', "Stream", ""),
- ('PUFF', "Puff", ""),
('FIRE', "Fire", ""),
),
default='STREAM',
@@ -328,20 +327,9 @@ class QuickSmoke(Operator):
bpy.ops.object.modifier_add(fake_context, type='SMOKE')
obj.modifiers[-1].smoke_type = 'FLOW'
- psys = obj.particle_systems[-1]
- if self.style == 'PUFF':
- psys.settings.frame_end = psys.settings.frame_start
- psys.settings.emit_from = 'VOLUME'
- psys.settings.distribution = 'RAND'
- elif self.style == 'FIRE':
- psys.settings.effector_weights.gravity = -1
- psys.settings.lifetime = 5
- psys.settings.count = 100000
-
- obj.modifiers[-2].flow_settings.initial_velocity = True
- obj.modifiers[-2].flow_settings.temperature = 2
-
- psys.settings.use_render_emitter = self.show_flows
+ if self.style == 'FIRE':
+ obj.modifiers[-1].flow_settings.smoke_flow_type = 'FIRE'
+
if not self.show_flows:
obj.draw_type = 'WIRE'
@@ -361,8 +349,6 @@ class QuickSmoke(Operator):
bpy.ops.object.modifier_add(type='SMOKE')
obj.modifiers[-1].smoke_type = 'DOMAIN'
if self.style == 'FIRE':
- obj.modifiers[-1].domain_settings.use_dissolve_smoke = True
- obj.modifiers[-1].domain_settings.dissolve_speed = 20
obj.modifiers[-1].domain_settings.use_high_resolution = True
# create a volume material with a voxel data texture for the domain
@@ -373,6 +359,7 @@ class QuickSmoke(Operator):
mat.type = 'VOLUME'
mat.volume.density = 0
mat.volume.density_scale = 5
+ mat.volume.step_size = 0.1
tex = bpy.data.textures.new("Smoke Density", 'VOXEL_DATA')
tex.voxel_data.domain_object = obj
@@ -381,29 +368,35 @@ class QuickSmoke(Operator):
tex_slot.texture = tex
tex_slot.use_map_color_emission = False
tex_slot.use_map_density = True
+ tex_slot.use_map_color_reflection = True
- # for fire add a second texture for emission and emission color
- if self.style == 'FIRE':
- mat.volume.emission = 5
- tex = bpy.data.textures.new("Smoke Heat", 'VOXEL_DATA')
- tex.voxel_data.domain_object = obj
- tex.use_color_ramp = True
-
- tex_slot = mat.texture_slots.add()
- tex_slot.texture = tex
-
- ramp = tex.color_ramp
-
- elem = ramp.elements.new(0.333)
- elem.color[0] = elem.color[3] = 1
- elem.color[1] = elem.color[2] = 0
+ # for fire add a second texture for flame emission
+ mat.volume.emission_color = Vector((0.0, 0.0, 0.0))
+ tex = bpy.data.textures.new("Flame", 'VOXEL_DATA')
+ tex.voxel_data.domain_object = obj
+ tex.voxel_data.smoke_data_type = 'SMOKEFLAME'
+ tex.use_color_ramp = True
- elem = ramp.elements.new(0.666)
- elem.color[0] = elem.color[1] = elem.color[3] = 1
- elem.color[2] = 0
+ tex_slot = mat.texture_slots.add()
+ tex_slot.texture = tex
- mat.texture_slots[1].use_map_emission = True
- mat.texture_slots[1].blend_type = 'MULTIPLY'
+ # add color ramp for flame color
+ ramp = tex.color_ramp
+ # dark orange
+ elem = ramp.elements.new(0.333)
+ elem.color[0] = 0.2
+ elem.color[1] = 0.03
+ elem.color[2] = 0
+ elem.color[3] = 1
+ # yellow glow
+ elem = ramp.elements.new(0.666)
+ elem.color[0] = elem.color[3] = 1
+ elem.color[1] = 0.65
+ elem.color[2] = 0.25
+
+ mat.texture_slots[1].use_map_density = True
+ mat.texture_slots[1].use_map_emission = True
+ mat.texture_slots[1].emission_factor = 5
return {'FINISHED'}
diff --git a/release/scripts/startup/bl_operators/presets.py b/release/scripts/startup/bl_operators/presets.py
index db492450e28..b7adf53dbf1 100644
--- a/release/scripts/startup/bl_operators/presets.py
+++ b/release/scripts/startup/bl_operators/presets.py
@@ -185,10 +185,12 @@ class ExecutePreset(Operator):
filepath = StringProperty(
subtype='FILE_PATH',
+ options={'SKIP_SAVE'},
)
menu_idname = StringProperty(
name="Menu ID Name",
description="ID name of the menu this was called from",
+ options={'SKIP_SAVE'},
)
def execute(self, context):
@@ -436,19 +438,19 @@ class AddPresetTrackingSettings(AddPresetBase, Operator):
]
preset_values = [
- "default_correlation_min",
- "default_pattern_size",
- "default_search_size",
- "default_frames_limit",
- "default_pattern_match",
- "default_margin",
- "default_motion_model",
- "use_default_brute",
- "use_default_normalization",
- "use_default_mask",
- "use_default_red_channel",
- "use_default_green_channel",
- "use_default_blue_channel"
+ "settings.default_correlation_min",
+ "settings.default_pattern_size",
+ "settings.default_search_size",
+ "settings.default_frames_limit",
+ "settings.default_pattern_match",
+ "settings.default_margin",
+ "settings.default_motion_model",
+ "settings.use_default_brute",
+ "settings.use_default_normalization",
+ "settings.use_default_mask",
+ "settings.use_default_red_channel",
+ "settings.use_default_green_channel",
+ "settings.use_default_blue_channel"
]
preset_subdir = "tracking_settings"
@@ -504,7 +506,7 @@ class AddPresetKeyconfig(AddPresetBase, Operator):
class AddPresetOperator(AddPresetBase, Operator):
- """Add an Application Interaction Preset"""
+ """Add an Operator Preset"""
bl_idname = "wm.operator_preset_add"
bl_label = "Operator Preset"
preset_menu = "WM_MT_operator_presets"
@@ -512,7 +514,7 @@ class AddPresetOperator(AddPresetBase, Operator):
operator = StringProperty(
name="Operator",
maxlen=64,
- options={'HIDDEN'},
+ options={'HIDDEN', 'SKIP_SAVE'},
)
preset_defines = [
diff --git a/release/scripts/startup/bl_operators/screen_play_rendered_anim.py b/release/scripts/startup/bl_operators/screen_play_rendered_anim.py
index 32658d353d9..694412e51d7 100644
--- a/release/scripts/startup/bl_operators/screen_play_rendered_anim.py
+++ b/release/scripts/startup/bl_operators/screen_play_rendered_anim.py
@@ -89,7 +89,7 @@ class PlayRenderedAnim(Operator):
if player_path == "":
player_path = guess_player_path(preset)
- if is_movie == False and preset in {'FRAMECYCLER', 'RV', 'MPLAYER'}:
+ if is_movie is False and preset in {'FRAMECYCLER', 'RV', 'MPLAYER'}:
# replace the number with '#'
file_a = rd.frame_path(frame=0)
diff --git a/release/scripts/startup/bl_operators/wm.py b/release/scripts/startup/bl_operators/wm.py
index 07d4096632f..2bff11a686d 100644
--- a/release/scripts/startup/bl_operators/wm.py
+++ b/release/scripts/startup/bl_operators/wm.py
@@ -608,9 +608,9 @@ class WM_OT_context_collection_boolean_set(Operator):
except:
continue
- if value_orig == True:
+ if value_orig is True:
is_set = True
- elif value_orig == False:
+ elif value_orig is False:
pass
else:
self.report({'WARNING'}, "Non boolean value found: %s[ ].%s" %
@@ -1028,7 +1028,7 @@ class WM_OT_properties_edit(Operator):
min = rna_min
max = rna_max
description = StringProperty(
- name="Tip",
+ name="Tooltip",
)
def execute(self, context):
@@ -1124,9 +1124,15 @@ class WM_OT_properties_add(Operator):
return prop_new
- property = unique_name(item.keys())
+ prop = unique_name(item.keys())
+
+ item[prop] = 1.0
+
+ # not essential, but without this we get [#31661]
+ prop_ui = rna_idprop_ui_prop_get(item, prop)
+ prop_ui["soft_min"] = prop_ui["min"] = 0.0
+ prop_ui["soft_max"] = prop_ui["max"] = 1.0
- item[property] = 1.0
return {'FINISHED'}
@@ -1284,7 +1290,7 @@ class WM_OT_blenderplayer_start(Operator):
return {'CANCELLED'}
filepath = os.path.join(bpy.app.tempdir, "game.blend")
- bpy.ops.wm.save_as_mainfile(filepath=filepath, check_existing=False, copy=True)
+ bpy.ops.wm.save_as_mainfile('EXEC_DEFAULT', filepath=filepath, copy=True)
subprocess.call([player_path, filepath])
return {'FINISHED'}
@@ -1583,7 +1589,7 @@ class WM_OT_addon_enable(Operator):
"version %d.%d.%d and might not "
"function (correctly), "
"though it is enabled") %
- info_ver)
+ info_ver)
return {'FINISHED'}
else:
return {'CANCELLED'}
@@ -1668,7 +1674,7 @@ class WM_OT_theme_install(Operator):
class WM_OT_addon_install(Operator):
"Install an addon"
bl_idname = "wm.addon_install"
- bl_label = "Install Addon..."
+ bl_label = "Install from File..."
overwrite = BoolProperty(
name="Overwrite",
@@ -1773,12 +1779,6 @@ class WM_OT_addon_install(Operator):
try: # extract the file to "addons"
file_to_extract.extractall(path_addons)
-
- # zip files can create this dir with metadata, don't need it
- macosx_dir = os.path.join(path_addons, '__MACOSX')
- if os.path.isdir(macosx_dir):
- shutil.rmtree(macosx_dir)
-
except:
traceback.print_exc()
return {'CANCELLED'}
@@ -1822,8 +1822,11 @@ class WM_OT_addon_install(Operator):
# in case a new module path was created to install this addon.
bpy.utils.refresh_script_paths()
- # TODO, should not be a warning.
- #~ self.report({'WARNING'}, "File installed to '%s'\n" % path_dest)
+ # print message
+ msg = "Modules Installed from %r into %r (%s)" % (pyfile, path_addons, ", ".join(sorted(addons_new)))
+ print(msg)
+ self.report({'INFO'}, msg)
+
return {'FINISHED'}
def invoke(self, context, event):
diff --git a/release/scripts/startup/bl_ui/__init__.py b/release/scripts/startup/bl_ui/__init__.py
index 847807029fa..e4be84d5396 100644
--- a/release/scripts/startup/bl_ui/__init__.py
+++ b/release/scripts/startup/bl_ui/__init__.py
@@ -92,10 +92,11 @@ def register():
def addon_filter_items(self, context):
import addon_utils
- items = [('All', "All", ""),
- ('Enabled', "Enabled", ""),
- ('Disabled', "Disabled", ""),
- ]
+ items = [('All', "All", "All Addons"),
+ ('User', "User", "All Addons Installed by User"),
+ ('Enabled', "Enabled", "All Enabled Addons"),
+ ('Disabled', "Disabled", "All Disabled Addons"),
+ ]
items_unique = set()
@@ -119,8 +120,8 @@ def register():
WindowManager.addon_support = EnumProperty(
items=[('OFFICIAL', "Official", "Officially supported"),
('COMMUNITY', "Community", "Maintained by community developers"),
- ('TESTING', "Testing", "Newly contributed scripts (excluded from release builds)"),
- ],
+ ('TESTING', "Testing", "Newly contributed scripts (excluded from release builds)")
+ ],
name="Support",
description="Display support level",
default={'OFFICIAL', 'COMMUNITY'},
diff --git a/release/scripts/startup/bl_ui/properties_animviz.py b/release/scripts/startup/bl_ui/properties_animviz.py
index 2d15c534e9f..8308c7fc425 100644
--- a/release/scripts/startup/bl_ui/properties_animviz.py
+++ b/release/scripts/startup/bl_ui/properties_animviz.py
@@ -65,10 +65,13 @@ class MotionPathButtonsPanel():
sub.prop(mpath, "frame_start", text="From")
sub.prop(mpath, "frame_end", text="To")
+ sub = col.row(align=True)
if bones:
- col.operator("pose.paths_update", text="Update Paths", icon='BONE_DATA')
+ sub.operator("pose.paths_update", text="Update Paths", icon='BONE_DATA')
+ sub.operator("pose.paths_clear", text="", icon='X')
else:
- col.operator("object.paths_update", text="Update Paths", icon='OBJECT_DATA')
+ sub.operator("object.paths_update", text="Update Paths", icon='OBJECT_DATA')
+ sub.operator("object.paths_clear", text="", icon='X')
else:
sub = col.column(align=True)
sub.label(text="Nothing to show yet...", icon='ERROR')
diff --git a/release/scripts/startup/bl_ui/properties_data_armature.py b/release/scripts/startup/bl_ui/properties_data_armature.py
index e194d7a1370..50c34be1414 100644
--- a/release/scripts/startup/bl_ui/properties_data_armature.py
+++ b/release/scripts/startup/bl_ui/properties_data_armature.py
@@ -285,10 +285,9 @@ class DATA_PT_iksolver_itasc(ArmatureButtonsPanel, Panel):
row.prop(itasc, "damping_max", text="Damp", slider=True)
row.prop(itasc, "damping_epsilon", text="Eps", slider=True)
-from bl_ui.properties_animviz import (
- MotionPathButtonsPanel,
- OnionSkinButtonsPanel,
- )
+from bl_ui.properties_animviz import (MotionPathButtonsPanel,
+ OnionSkinButtonsPanel,
+ )
class DATA_PT_motion_paths(MotionPathButtonsPanel, Panel):
diff --git a/release/scripts/startup/bl_ui/properties_data_bone.py b/release/scripts/startup/bl_ui/properties_data_bone.py
index e6d9affee93..1441c642d51 100644
--- a/release/scripts/startup/bl_ui/properties_data_bone.py
+++ b/release/scripts/startup/bl_ui/properties_data_bone.py
@@ -246,72 +246,74 @@ class BONE_PT_inverse_kinematics(BoneButtonsPanel, Panel):
row = layout.row()
row.prop(ob.pose, "ik_solver")
+ active = pchan.is_in_ik_chain
+
split = layout.split(percentage=0.25)
split.prop(pchan, "lock_ik_x", icon='LOCKED' if pchan.lock_ik_x else 'UNLOCKED', text="X")
- split.active = pchan.is_in_ik_chain
+ split.active = active
row = split.row()
row.prop(pchan, "ik_stiffness_x", text="Stiffness", slider=True)
- row.active = pchan.lock_ik_x == False and pchan.is_in_ik_chain
+ row.active = pchan.lock_ik_x is False and active
split = layout.split(percentage=0.25)
sub = split.row()
sub.prop(pchan, "use_ik_limit_x", text="Limit")
- sub.active = pchan.lock_ik_x == False and pchan.is_in_ik_chain
+ sub.active = pchan.lock_ik_x is False and active
sub = split.row(align=True)
sub.prop(pchan, "ik_min_x", text="")
sub.prop(pchan, "ik_max_x", text="")
- sub.active = pchan.lock_ik_x == False and pchan.use_ik_limit_x and pchan.is_in_ik_chain
+ sub.active = pchan.lock_ik_x is False and pchan.use_ik_limit_x and active
split = layout.split(percentage=0.25)
split.prop(pchan, "lock_ik_y", icon='LOCKED' if pchan.lock_ik_y else 'UNLOCKED', text="Y")
- split.active = pchan.is_in_ik_chain
+ split.active = active
row = split.row()
row.prop(pchan, "ik_stiffness_y", text="Stiffness", slider=True)
- row.active = pchan.lock_ik_y == False and pchan.is_in_ik_chain
+ row.active = pchan.lock_ik_y is False and active
split = layout.split(percentage=0.25)
sub = split.row()
sub.prop(pchan, "use_ik_limit_y", text="Limit")
- sub.active = pchan.lock_ik_y == False and pchan.is_in_ik_chain
+ sub.active = pchan.lock_ik_y is False and active
sub = split.row(align=True)
sub.prop(pchan, "ik_min_y", text="")
sub.prop(pchan, "ik_max_y", text="")
- sub.active = pchan.lock_ik_y == False and pchan.use_ik_limit_y and pchan.is_in_ik_chain
+ sub.active = pchan.lock_ik_y is False and pchan.use_ik_limit_y and active
split = layout.split(percentage=0.25)
split.prop(pchan, "lock_ik_z", icon='LOCKED' if pchan.lock_ik_z else 'UNLOCKED', text="Z")
- split.active = pchan.is_in_ik_chain
+ split.active = active
sub = split.row()
sub.prop(pchan, "ik_stiffness_z", text="Stiffness", slider=True)
- sub.active = pchan.lock_ik_z == False and pchan.is_in_ik_chain
+ sub.active = pchan.lock_ik_z is False and active
split = layout.split(percentage=0.25)
sub = split.row()
sub.prop(pchan, "use_ik_limit_z", text="Limit")
- sub.active = pchan.lock_ik_z == False and pchan.is_in_ik_chain
+ sub.active = pchan.lock_ik_z is False and active
sub = split.row(align=True)
sub.prop(pchan, "ik_min_z", text="")
sub.prop(pchan, "ik_max_z", text="")
- sub.active = pchan.lock_ik_z == False and pchan.use_ik_limit_z and pchan.is_in_ik_chain
+ sub.active = pchan.lock_ik_z is False and pchan.use_ik_limit_z and active
split = layout.split(percentage=0.25)
split.label(text="Stretch:")
sub = split.row()
sub.prop(pchan, "ik_stretch", text="", slider=True)
- sub.active = pchan.is_in_ik_chain
+ sub.active = active
if ob.pose.ik_solver == 'ITASC':
split = layout.split()
col = split.column()
col.prop(pchan, "use_ik_rotation_control", text="Control Rotation")
- col.active = pchan.is_in_ik_chain
+ col.active = active
col = split.column()
col.prop(pchan, "ik_rotation_weight", text="Weight", slider=True)
- col.active = pchan.is_in_ik_chain
+ col.active = active
# not supported yet
#row = layout.row()
#row.prop(pchan, "use_ik_linear_control", text="Joint Size")
diff --git a/release/scripts/startup/bl_ui/properties_data_camera.py b/release/scripts/startup/bl_ui/properties_data_camera.py
index 49457b8e569..5f6036c8945 100644
--- a/release/scripts/startup/bl_ui/properties_data_camera.py
+++ b/release/scripts/startup/bl_ui/properties_data_camera.py
@@ -88,7 +88,8 @@ class DATA_PT_lens(CameraButtonsPanel, Panel):
col.prop(cam, "ortho_scale")
elif cam.type == 'PANO':
- if context.scene.render.engine == 'CYCLES':
+ engine = context.scene.render.engine
+ if engine == 'CYCLES':
ccam = cam.cycles
col.prop(ccam, "panorama_type", text="Type")
if ccam.panorama_type == 'FISHEYE_EQUIDISTANT':
@@ -97,6 +98,13 @@ class DATA_PT_lens(CameraButtonsPanel, Panel):
row = layout.row()
row.prop(ccam, "fisheye_lens", text="Lens")
row.prop(ccam, "fisheye_fov")
+ elif engine == 'BLENDER_RENDER':
+ row = col.row()
+ if cam.lens_unit == 'MILLIMETERS':
+ row.prop(cam, "lens")
+ elif cam.lens_unit == 'DEGREES':
+ row.prop(cam, "angle")
+ row.prop(cam, "lens_unit", text="")
split = layout.split()
@@ -175,7 +183,7 @@ class DATA_PT_camera_display(CameraButtonsPanel, Panel):
col = split.column()
col.prop(cam, "show_limits", text="Limits")
col.prop(cam, "show_mist", text="Mist")
- col.prop(cam, "show_title_safe", text="Title Safe")
+ col.prop(cam, "show_title_safe", text="Safe Areas")
col.prop(cam, "show_sensor", text="Sensor")
col.prop(cam, "show_name", text="Name")
diff --git a/release/scripts/startup/bl_ui/properties_data_lamp.py b/release/scripts/startup/bl_ui/properties_data_lamp.py
index 769715ef1b9..71fdc1d7b67 100644
--- a/release/scripts/startup/bl_ui/properties_data_lamp.py
+++ b/release/scripts/startup/bl_ui/properties_data_lamp.py
@@ -118,7 +118,7 @@ class DATA_PT_lamp(DataButtonsPanel, Panel):
class DATA_PT_sunsky(DataButtonsPanel, Panel):
bl_label = "Sky & Atmosphere"
- COMPAT_ENGINES = {'BLENDER_RENDER', 'BLENDER_GAME'}
+ COMPAT_ENGINES = {'BLENDER_RENDER'}
@classmethod
def poll(cls, context):
diff --git a/release/scripts/startup/bl_ui/properties_data_mesh.py b/release/scripts/startup/bl_ui/properties_data_mesh.py
index 5f21f78a375..6125540d491 100644
--- a/release/scripts/startup/bl_ui/properties_data_mesh.py
+++ b/release/scripts/startup/bl_ui/properties_data_mesh.py
@@ -316,10 +316,31 @@ class DATA_PT_vertex_colors(MeshButtonsPanel, Panel):
layout.prop(lay, "name")
+class DATA_PT_customdata(MeshButtonsPanel, Panel):
+ bl_label = "Geometry Data"
+ bl_options = {'DEFAULT_CLOSED'}
+ COMPAT_ENGINES = {'BLENDER_RENDER', 'BLENDER_GAME'}
+
+ def draw(self, context):
+ layout = self.layout
+
+ # me = context.mesh
+ col = layout.column()
+ # sticky has no UI access since 2.49 - we may remove
+ '''
+ row = col.row(align=True)
+ row.operator("mesh.customdata_create_sticky")
+ row.operator("mesh.customdata_clear_sticky", icon='X')
+ '''
+ col.operator("mesh.customdata_clear_mask", icon='X')
+ col.operator("mesh.customdata_clear_skin", icon='X')
+
+
class DATA_PT_custom_props_mesh(MeshButtonsPanel, PropertyPanel, Panel):
COMPAT_ENGINES = {'BLENDER_RENDER', 'BLENDER_GAME'}
_context_path = "object.data"
_property_type = bpy.types.Mesh
+
if __name__ == "__main__": # only for live edit.
bpy.utils.register_module(__name__)
diff --git a/release/scripts/startup/bl_ui/properties_data_modifier.py b/release/scripts/startup/bl_ui/properties_data_modifier.py
index ae0c4d4161c..902358813df 100644
--- a/release/scripts/startup/bl_ui/properties_data_modifier.py
+++ b/release/scripts/startup/bl_ui/properties_data_modifier.py
@@ -211,12 +211,27 @@ class DATA_PT_modifiers(ModifierButtonsPanel, Panel):
layout.row().prop(md, "deform_axis", expand=True)
def DECIMATE(self, layout, ob, md):
- layout.prop(md, "ratio")
+ row = layout.row()
+ row.prop(md, "decimate_type", expand=True)
+ decimate_type = md.decimate_type
+
+ if decimate_type == 'COLLAPSE':
+ layout.prop(md, "ratio")
+ row = layout.row()
+ row.prop_search(md, "vertex_group", ob, "vertex_groups", text="")
+ row.prop(md, "invert_vertex_group")
+ layout.prop(md, "use_collapse_triangulate")
+ elif decimate_type == 'UNSUBDIV':
+ layout.prop(md, "iterations")
+ else: # decimate_type == 'DISSOLVE':
+ layout.prop(md, "angle_limit")
+ layout.prop(md, "use_dissolve_boundaries")
+
layout.label(text="Face Count" + ": %d" % md.face_count)
def DISPLACE(self, layout, ob, md):
has_texture = (md.texture is not None)
-
+
split = layout.split()
col = split.column()
@@ -316,6 +331,28 @@ class DATA_PT_modifiers(ModifierButtonsPanel, Panel):
row.operator("object.hook_select", text="Select")
row.operator("object.hook_assign", text="Assign")
+ def LAPLACIANSMOOTH(self, layout, ob, md):
+ layout.prop(md, "iterations")
+
+ split = layout.split(percentage=0.25)
+
+ col = split.column()
+ col.label(text="Axis:")
+ col.prop(md, "use_x")
+ col.prop(md, "use_y")
+ col.prop(md, "use_z")
+
+ col = split.column()
+ col.label(text="Lambda:")
+ col.prop(md, "lambda_factor", text="Factor")
+ col.prop(md, "lambda_border", text="Border")
+
+ col.separator()
+ col.prop(md, "use_volume_preserve")
+
+ layout.label(text="Vertex Group:")
+ layout.prop_search(md, "vertex_group", ob, "vertex_groups", text="")
+
def LATTICE(self, layout, ob, md):
split = layout.split()
@@ -397,7 +434,7 @@ class DATA_PT_modifiers(ModifierButtonsPanel, Panel):
col = layout.column()
- if md.use_mirror_merge == True:
+ if md.use_mirror_merge is True:
col.prop(md, "merge_threshold")
col.label(text="Mirror Object:")
col.prop(md, "mirror_object", text="")
@@ -559,7 +596,7 @@ class DATA_PT_modifiers(ModifierButtonsPanel, Panel):
col = split.column()
row = col.row()
- row.active = (md.object is None or md.use_object_screw_offset == False)
+ row.active = (md.object is None or md.use_object_screw_offset is False)
row.prop(md, "screw_offset")
row = col.row()
row.active = (md.object is not None)
diff --git a/release/scripts/startup/bl_ui/properties_game.py b/release/scripts/startup/bl_ui/properties_game.py
index 5ff49a7d369..bf0c9eb762a 100644
--- a/release/scripts/startup/bl_ui/properties_game.py
+++ b/release/scripts/startup/bl_ui/properties_game.py
@@ -190,6 +190,14 @@ class PHYSICS_PT_game_physics(PhysicsButtonsPanel, Panel):
layout.operator("mesh.navmesh_reset")
layout.operator("mesh.navmesh_clear")
+ if physics_type not in {'NO_COLLISION', 'OCCLUDE'}:
+ layout.separator()
+ split = layout.split()
+
+ col = split.column()
+ col.prop(game, "collision_group")
+ col = split.column()
+ col.prop(game, "collision_mask")
class PHYSICS_PT_game_collision_bounds(PhysicsButtonsPanel, Panel):
bl_label = "Collision Bounds"
diff --git a/release/scripts/startup/bl_ui/properties_material.py b/release/scripts/startup/bl_ui/properties_material.py
index dfc75168d2b..951644db752 100644
--- a/release/scripts/startup/bl_ui/properties_material.py
+++ b/release/scripts/startup/bl_ui/properties_material.py
@@ -753,6 +753,7 @@ class MATERIAL_PT_options(MaterialButtonsPanel, Panel):
row = sub.row()
row.active = bool(mat.light_group)
row.prop(mat, "use_light_group_exclusive", text="Exclusive")
+ row.prop(mat, "use_light_group_local", text="Local")
col = split.column()
col.prop(mat, "use_face_texture")
@@ -763,6 +764,7 @@ class MATERIAL_PT_options(MaterialButtonsPanel, Panel):
col.prop(mat, "use_vertex_color_paint")
col.prop(mat, "use_vertex_color_light")
col.prop(mat, "use_object_color")
+ col.prop(mat, "use_uv_project")
if simple_material(base_mat):
col.prop(mat, "pass_index")
diff --git a/release/scripts/startup/bl_ui/properties_object.py b/release/scripts/startup/bl_ui/properties_object.py
index 275cb8fab65..8a668b5d95b 100644
--- a/release/scripts/startup/bl_ui/properties_object.py
+++ b/release/scripts/startup/bl_ui/properties_object.py
@@ -185,7 +185,7 @@ class OBJECT_PT_groups(ObjectButtonsPanel, Panel):
split = col.box().split()
col = split.column()
- col.prop(group, "layers", text="Dupli")
+ col.prop(group, "layers", text="Dupli Visibility")
col = split.column()
col.prop(group, "dupli_offset", text="")
@@ -290,10 +290,8 @@ class OBJECT_PT_relations_extras(ObjectButtonsPanel, Panel):
row.prop(ob, "slow_parent_offset", text="Offset")
-from bl_ui.properties_animviz import (
- MotionPathButtonsPanel,
- OnionSkinButtonsPanel,
- )
+from bl_ui.properties_animviz import (MotionPathButtonsPanel,
+ OnionSkinButtonsPanel)
class OBJECT_PT_motion_paths(MotionPathButtonsPanel, Panel):
diff --git a/release/scripts/startup/bl_ui/properties_object_constraint.py b/release/scripts/startup/bl_ui/properties_object_constraint.py
index 3d671a0d1b7..3fa63bac13c 100644
--- a/release/scripts/startup/bl_ui/properties_object_constraint.py
+++ b/release/scripts/startup/bl_ui/properties_object_constraint.py
@@ -88,7 +88,6 @@ class ConstraintButtonsPanel():
col = split.column()
col.prop(con, "chain_count")
- col.prop(con, "use_target")
def CHILD_OF(self, context, layout, con):
self.target_template(layout, con)
@@ -162,7 +161,6 @@ class ConstraintButtonsPanel():
col.prop(con, "use_tail")
col.prop(con, "use_stretch")
col.separator()
- col.prop(con, "use_target")
col.prop(con, "use_rotation")
def IK_COPY_POSE(self, context, layout, con):
@@ -212,6 +210,7 @@ class ConstraintButtonsPanel():
def FOLLOW_PATH(self, context, layout, con):
self.target_template(layout, con)
+ layout.operator("constraint.followpath_path_animate", text="Animate Path", icon='ANIM_DATA')
split = layout.split()
@@ -484,6 +483,8 @@ class ConstraintButtonsPanel():
row.prop(con, "use_transform_limit")
row.label()
+ self.space_template(layout, con)
+
def STRETCH_TO(self, context, layout, con):
self.target_template(layout, con)
diff --git a/release/scripts/startup/bl_ui/properties_particle.py b/release/scripts/startup/bl_ui/properties_particle.py
index aa0ea1d2d9e..6fcd56fb99e 100644
--- a/release/scripts/startup/bl_ui/properties_particle.py
+++ b/release/scripts/startup/bl_ui/properties_particle.py
@@ -21,12 +21,11 @@ import bpy
from bpy.types import Panel
from rna_prop_ui import PropertyPanel
-from bl_ui.properties_physics_common import (
- point_cache_ui,
- effector_weights_ui,
- basic_force_field_settings_ui,
- basic_force_field_falloff_ui,
- )
+from bl_ui.properties_physics_common import (point_cache_ui,
+ effector_weights_ui,
+ basic_force_field_settings_ui,
+ basic_force_field_falloff_ui,
+ )
def particle_panel_enabled(context, psys):
@@ -52,7 +51,7 @@ def particle_panel_poll(cls, context):
if not settings:
return False
- return settings.is_fluid == False and (engine in cls.COMPAT_ENGINES)
+ return settings.is_fluid is False and (engine in cls.COMPAT_ENGINES)
def particle_get_settings(context):
@@ -133,13 +132,13 @@ class PARTICLE_PT_context_particles(ParticleButtonsPanel, Panel):
split = layout.split(percentage=0.32)
col = split.column()
col.label(text="Name:")
- if part.is_fluid == False:
+ if part.is_fluid is False:
col.label(text="Settings:")
col.label(text="Type:")
col = split.column()
col.prop(psys, "name", text="")
- if part.is_fluid == False:
+ if part.is_fluid is False:
row = col.row()
row.enabled = particle_panel_enabled(context, psys)
row.template_ID(psys, "settings", new="particle.new")
@@ -279,7 +278,7 @@ class PARTICLE_PT_hair_dynamics(ParticleButtonsPanel, Panel):
cloth = psys.cloth.settings
- layout.enabled = psys.use_hair_dynamics and psys.point_cache.is_baked == False
+ layout.enabled = psys.use_hair_dynamics and psys.point_cache.is_baked is False
split = layout.split()
@@ -813,7 +812,7 @@ class PARTICLE_PT_render(ParticleButtonsPanel, Panel):
sub.active = (part.use_strand_primitive is False)
sub.prop(part, "use_render_adaptive")
sub = col.column()
- sub.active = part.use_render_adaptive or part.use_strand_primitive == True
+ sub.active = part.use_render_adaptive or part.use_strand_primitive is True
sub.prop(part, "adaptive_angle")
sub = col.column()
sub.active = (part.use_render_adaptive is True and part.use_strand_primitive is False)
@@ -831,9 +830,9 @@ class PARTICLE_PT_render(ParticleButtonsPanel, Panel):
row = layout.row()
col = row.column()
- if part.type == 'HAIR' and part.use_strand_primitive == True and part.child_type == 'INTERPOLATED':
+ if part.type == 'HAIR' and part.use_strand_primitive is True and part.child_type == 'INTERPOLATED':
layout.prop(part, "use_simplify")
- if part.use_simplify == True:
+ if part.use_simplify is True:
row = layout.row()
row.prop(part, "simplify_refsize")
row.prop(part, "simplify_rate")
@@ -841,7 +840,7 @@ class PARTICLE_PT_render(ParticleButtonsPanel, Panel):
row = layout.row()
row.prop(part, "use_simplify_viewport")
sub = row.row()
- sub.active = part.use_simplify_viewport == True
+ sub.active = part.use_simplify_viewport is True
sub.prop(part, "simplify_viewport")
elif part.render_type == 'OBJECT':
@@ -988,11 +987,11 @@ class PARTICLE_PT_draw(ParticleButtonsPanel, Panel):
if part.draw_percentage != 100 and psys is not None:
if part.type == 'HAIR':
- if psys.use_hair_dynamics and psys.point_cache.is_baked == False:
+ if psys.use_hair_dynamics and psys.point_cache.is_baked is False:
layout.row().label(text="Display percentage makes dynamics inaccurate without baking!")
else:
phystype = part.physics_type
- if phystype != 'NO' and phystype != 'KEYED' and psys.point_cache.is_baked == False:
+ if phystype != 'NO' and phystype != 'KEYED' and psys.point_cache.is_baked is False:
layout.row().label(text="Display percentage makes dynamics inaccurate without baking!")
row = layout.row()
@@ -1125,7 +1124,7 @@ class PARTICLE_PT_field_weights(ParticleButtonsPanel, Panel):
def draw(self, context):
part = particle_get_settings(context)
- effector_weights_ui(self, context, part.effector_weights)
+ effector_weights_ui(self, context, part.effector_weights, 'PSYS')
if part.type == 'HAIR':
row = self.layout.row()
diff --git a/release/scripts/startup/bl_ui/properties_physics_cloth.py b/release/scripts/startup/bl_ui/properties_physics_cloth.py
index 33b977b5f04..5a44294f0e0 100644
--- a/release/scripts/startup/bl_ui/properties_physics_cloth.py
+++ b/release/scripts/startup/bl_ui/properties_physics_cloth.py
@@ -20,10 +20,8 @@
import bpy
from bpy.types import Menu, Panel
-from bl_ui.properties_physics_common import (
- point_cache_ui,
- effector_weights_ui,
- )
+from bl_ui.properties_physics_common import (point_cache_ui,
+ effector_weights_ui)
def cloth_panel_enabled(md):
@@ -178,7 +176,7 @@ class PHYSICS_PT_cloth_stiffness(PhysicButtonsPanel, Panel):
ob = context.object
cloth = context.cloth.settings
- layout.active = cloth.use_stiffness_scale and cloth_panel_enabled(md)
+ layout.active = (cloth.use_stiffness_scale and cloth_panel_enabled(md))
split = layout.split()
@@ -199,7 +197,7 @@ class PHYSICS_PT_cloth_field_weights(PhysicButtonsPanel, Panel):
def draw(self, context):
cloth = context.cloth.settings
- effector_weights_ui(self, context, cloth.effector_weights)
+ effector_weights_ui(self, context, cloth.effector_weights, 'CLOTH')
if __name__ == "__main__": # only for live edit.
bpy.utils.register_module(__name__)
diff --git a/release/scripts/startup/bl_ui/properties_physics_common.py b/release/scripts/startup/bl_ui/properties_physics_common.py
index 7f824d94431..405e877d1e2 100644
--- a/release/scripts/startup/bl_ui/properties_physics_common.py
+++ b/release/scripts/startup/bl_ui/properties_physics_common.py
@@ -133,7 +133,7 @@ def point_cache_ui(self, context, cache, enabled, cachetype):
row.prop(cache, "frame_end")
if cachetype not in {'SMOKE', 'CLOTH', 'DYNAMIC_PAINT'}:
row.prop(cache, "frame_step")
- row.prop(cache, "use_quick_cache")
+
if cachetype != 'SMOKE':
layout.label(text=cache.info)
@@ -160,7 +160,7 @@ def point_cache_ui(self, context, cache, enabled, cachetype):
col = split.column()
- if cache.is_baked == True:
+ if cache.is_baked is True:
col.operator("ptcache.free_bake", text="Free Bake")
else:
col.operator("ptcache.bake", text="Bake").bake = True
@@ -179,7 +179,7 @@ def point_cache_ui(self, context, cache, enabled, cachetype):
col.operator("ptcache.bake_all", text="Update All To Frame").bake = False
-def effector_weights_ui(self, context, weights):
+def effector_weights_ui(self, context, weights, weight_type):
layout = self.layout
layout.prop(weights, "group")
@@ -200,6 +200,8 @@ def effector_weights_ui(self, context, weights):
col.prop(weights, "wind", slider=True)
col.prop(weights, "curve_guide", slider=True)
col.prop(weights, "texture", slider=True)
+ if weight_type != 'SMOKE':
+ col.prop(weights, "smokeflow", slider=True)
col = split.column()
col.prop(weights, "harmonic", slider=True)
diff --git a/release/scripts/startup/bl_ui/properties_physics_dynamicpaint.py b/release/scripts/startup/bl_ui/properties_physics_dynamicpaint.py
index db0794d8a8a..1df2936b2d4 100644
--- a/release/scripts/startup/bl_ui/properties_physics_dynamicpaint.py
+++ b/release/scripts/startup/bl_ui/properties_physics_dynamicpaint.py
@@ -20,10 +20,9 @@
import bpy
from bpy.types import Panel
-from bl_ui.properties_physics_common import (
- point_cache_ui,
- effector_weights_ui,
- )
+from bl_ui.properties_physics_common import (point_cache_ui,
+ effector_weights_ui,
+ )
class PhysicButtonsPanel():
@@ -350,7 +349,7 @@ class PHYSICS_PT_dp_effects(PhysicButtonsPanel, Panel):
col = layout.column()
col.active = surface.use_drip
- effector_weights_ui(self, context, surface.effector_weights)
+ effector_weights_ui(self, context, surface.effector_weights, 'DYNAMIC_PAINT')
layout.label(text="Surface Movement:")
row = layout.row()
diff --git a/release/scripts/startup/bl_ui/properties_physics_field.py b/release/scripts/startup/bl_ui/properties_physics_field.py
index 569037cb0da..933a9aa12a3 100644
--- a/release/scripts/startup/bl_ui/properties_physics_field.py
+++ b/release/scripts/startup/bl_ui/properties_physics_field.py
@@ -20,10 +20,9 @@
import bpy
from bpy.types import Panel
-from bl_ui.properties_physics_common import (
- basic_force_field_settings_ui,
- basic_force_field_falloff_ui,
- )
+from bl_ui.properties_physics_common import (basic_force_field_settings_ui,
+ basic_force_field_falloff_ui,
+ )
class PhysicButtonsPanel():
@@ -113,6 +112,14 @@ class PHYSICS_PT_field(PhysicButtonsPanel, Panel):
col = split.column()
col.prop(field, "use_object_coords")
col.prop(field, "use_2d_force")
+ elif field.type == 'SMOKE_FLOW':
+ col = split.column()
+ col.prop(field, "strength")
+ col.prop(field, "flow")
+ col = split.column()
+ col.label(text="Domain Object:")
+ col.prop(field, "source_object", "")
+ col.prop(field, "use_smoke_density")
else:
basic_force_field_settings_ui(self, context, field)
diff --git a/release/scripts/startup/bl_ui/properties_physics_smoke.py b/release/scripts/startup/bl_ui/properties_physics_smoke.py
index 1b333f1e505..ce5053f0ecf 100644
--- a/release/scripts/startup/bl_ui/properties_physics_smoke.py
+++ b/release/scripts/startup/bl_ui/properties_physics_smoke.py
@@ -20,10 +20,8 @@
import bpy
from bpy.types import Panel
-from bl_ui.properties_physics_common import (
- point_cache_ui,
- effector_weights_ui,
- )
+from bl_ui.properties_physics_common import (point_cache_ui,
+ effector_weights_ui)
class PhysicButtonsPanel():
@@ -78,28 +76,40 @@ class PHYSICS_PT_smoke(PhysicButtonsPanel, Panel):
elif md.smoke_type == 'FLOW':
flow = md.flow_settings
-
- split = layout.split()
-
- col = split.column()
- col.prop(flow, "use_outflow")
- col.label(text="Particle System:")
- col.prop_search(flow, "particle_system", ob, "particle_systems", text="")
-
- sub = col.column()
- sub.active = not md.flow_settings.use_outflow
-
- sub.prop(flow, "initial_velocity", text="Initial Velocity")
- sub = sub.column()
- sub.active = flow.initial_velocity
- sub.prop(flow, "velocity_factor", text="Multiplier")
-
- sub = split.column()
- sub.active = not md.flow_settings.use_outflow
- sub.label(text="Initial Values:")
- sub.prop(flow, "use_absolute")
- sub.prop(flow, "density")
- sub.prop(flow, "temperature")
+
+ layout.prop(flow, "smoke_flow_type", expand=False)
+
+ if flow.smoke_flow_type != "OUTFLOW":
+ split = layout.split()
+ col = split.column()
+ col.label(text="Flow Source:")
+ col.prop(flow, "smoke_flow_source", expand=False, text="")
+ if flow.smoke_flow_source == "PARTICLES":
+ col.label(text="Particle System:")
+ col.prop_search(flow, "particle_system", ob, "particle_systems", text="")
+ else:
+ col.prop(flow, "surface_distance")
+ col.prop(flow, "volume_density")
+
+ sub = col.column(align=True)
+
+ sub.prop(flow, "initial_velocity")
+ sub = sub.column()
+ sub.active = flow.initial_velocity
+ sub.prop(flow, "velocity_factor")
+ if flow.smoke_flow_source == "MESH":
+ sub.prop(flow, "velocity_normal")
+ #sub.prop(flow, "velocity_random")
+
+ sub = split.column()
+ sub.label(text="Initial Values:")
+ sub.prop(flow, "use_absolute")
+ if flow.smoke_flow_type in {'SMOKE', 'BOTH'}:
+ sub.prop(flow, "density")
+ sub.prop(flow, "temperature")
+ sub.prop(flow, "smoke_color")
+ if flow.smoke_flow_type in {'FIRE', 'BOTH'}:
+ sub.prop(flow, "fuel_amount")
elif md.smoke_type == 'COLLISION':
coll = md.coll_settings
@@ -108,36 +118,99 @@ class PHYSICS_PT_smoke(PhysicButtonsPanel, Panel):
col = split.column()
col.prop(coll, "collision_type")
+
+class PHYSICS_PT_smoke_flow_advanced(PhysicButtonsPanel, Panel):
+ bl_label = "Smoke Flow Advanced"
+ bl_options = {'DEFAULT_CLOSED'}
+ @classmethod
+ def poll(cls, context):
+ md = context.smoke
+ return md and (md.smoke_type == 'FLOW') and (md.flow_settings.smoke_flow_source == "MESH")
-class PHYSICS_PT_smoke_groups(PhysicButtonsPanel, Panel):
- bl_label = "Smoke Groups"
+ def draw(self, context):
+ layout = self.layout
+ ob = context.object
+ flow = context.smoke.flow_settings
+
+ split = layout.split()
+ col = split.column()
+
+ col.prop(flow, "use_texture")
+ sub = col.column()
+ sub.active = flow.use_texture
+ sub.prop(flow, "noise_texture", text="")
+ sub.label(text="Mapping:")
+ sub.prop(flow, "texture_map_type", expand=False, text="")
+ if flow.texture_map_type == "UV":
+ sub.prop_search(flow, "uv_layer", ob.data, "uv_textures", text="")
+ if flow.texture_map_type == "AUTO":
+ sub.prop(flow, "texture_size")
+ sub.prop(flow, "texture_offset")
+
+ col = split.column()
+ col.label(text="Vertex Group:")
+ col.prop_search(flow, "density_vertex_group", ob, "vertex_groups", text="")
+
+class PHYSICS_PT_smoke_fire(PhysicButtonsPanel, Panel):
+ bl_label = "Smoke Flames"
bl_options = {'DEFAULT_CLOSED'}
@classmethod
def poll(cls, context):
md = context.smoke
- rd = context.scene.render
- return md and (md.smoke_type == 'DOMAIN') and (not rd.use_game_engine)
+ return md and (md.smoke_type == 'DOMAIN')
def draw(self, context):
layout = self.layout
-
- group = context.smoke.domain_settings
+ domain = context.smoke.domain_settings
split = layout.split()
+ split.enabled = not domain.point_cache.is_baked
+
+ col = split.column(align=True)
+ col.label(text="Reaction:")
+ col.prop(domain, "burning_rate")
+ col.prop(domain, "flame_smoke")
+ col.prop(domain, "flame_vorticity")
+
+ col = split.column(align=True)
+ col.label(text="Temperatures:")
+ col.prop(domain, "flame_ignition")
+ col.prop(domain, "flame_max_temp")
+ col.prop(domain, "flame_smoke_color")
+
+class PHYSICS_PT_smoke_adaptive_domain(PhysicButtonsPanel, Panel):
+ bl_label = "Smoke Adaptive Domain"
+ bl_options = {'DEFAULT_CLOSED'}
- col = split.column()
- col.label(text="Flow Group:")
- col.prop(group, "fluid_group", text="")
+ @classmethod
+ def poll(cls, context):
+ md = context.smoke
+ return md and (md.smoke_type == 'DOMAIN')
- #col.label(text="Effector Group:")
- #col.prop(group, "effector_group", text="")
+ def draw_header(self, context):
+ md = context.smoke.domain_settings
- col = split.column()
- col.label(text="Collision Group:")
- col.prop(group, "collision_group", text="")
+ self.layout.prop(md, "use_adaptive_domain", text="")
+ def draw(self, context):
+ layout = self.layout
+
+ domain = context.smoke.domain_settings
+ layout.active = domain.use_adaptive_domain
+
+ split = layout.split()
+ split.enabled = not domain.point_cache.is_baked
+
+ col = split.column(align=True)
+ col.label(text="Resolution:")
+ col.prop(domain, "additional_res")
+ col.prop(domain, "adapt_margin")
+
+ col = split.column(align=True)
+ col.label(text="Advanced:")
+ col.prop(domain, "adapt_threshold")
class PHYSICS_PT_smoke_highres(PhysicButtonsPanel, Panel):
bl_label = "Smoke High Resolution"
@@ -176,6 +249,32 @@ class PHYSICS_PT_smoke_highres(PhysicButtonsPanel, Panel):
layout.prop(md, "show_high_resolution")
+class PHYSICS_PT_smoke_groups(PhysicButtonsPanel, Panel):
+ bl_label = "Smoke Groups"
+ bl_options = {'DEFAULT_CLOSED'}
+
+ @classmethod
+ def poll(cls, context):
+ md = context.smoke
+ rd = context.scene.render
+ return md and (md.smoke_type == 'DOMAIN') and (not rd.use_game_engine)
+
+ def draw(self, context):
+ layout = self.layout
+ domain = context.smoke.domain_settings
+
+ split = layout.split()
+
+ col = split.column()
+ col.label(text="Flow Group:")
+ col.prop(domain, "fluid_group", text="")
+
+ #col.label(text="Effector Group:")
+ #col.prop(domain, "effector_group", text="")
+
+ col = split.column()
+ col.label(text="Collision Group:")
+ col.prop(domain, "collision_group", text="")
class PHYSICS_PT_smoke_cache(PhysicButtonsPanel, Panel):
bl_label = "Smoke Cache"
@@ -211,7 +310,7 @@ class PHYSICS_PT_smoke_field_weights(PhysicButtonsPanel, Panel):
def draw(self, context):
domain = context.smoke.domain_settings
- effector_weights_ui(self, context, domain.effector_weights)
+ effector_weights_ui(self, context, domain.effector_weights, 'SMOKE')
if __name__ == "__main__": # only for live edit.
bpy.utils.register_module(__name__)
diff --git a/release/scripts/startup/bl_ui/properties_physics_softbody.py b/release/scripts/startup/bl_ui/properties_physics_softbody.py
index b043c1f9b68..79d676533a5 100644
--- a/release/scripts/startup/bl_ui/properties_physics_softbody.py
+++ b/release/scripts/startup/bl_ui/properties_physics_softbody.py
@@ -20,10 +20,8 @@
import bpy
from bpy.types import Panel
-from bl_ui.properties_physics_common import (
- point_cache_ui,
- effector_weights_ui,
- )
+from bl_ui.properties_physics_common import (point_cache_ui,
+ effector_weights_ui)
def softbody_panel_enabled(md):
@@ -233,7 +231,7 @@ class PHYSICS_PT_softbody_field_weights(PhysicButtonsPanel, Panel):
md = context.soft_body
softbody = md.settings
- effector_weights_ui(self, context, softbody.effector_weights)
+ effector_weights_ui(self, context, softbody.effector_weights, 'SOFTBODY')
if __name__ == "__main__": # only for live edit.
bpy.utils.register_module(__name__)
diff --git a/release/scripts/startup/bl_ui/properties_render.py b/release/scripts/startup/bl_ui/properties_render.py
index b777fcddcf2..9814dd7e902 100644
--- a/release/scripts/startup/bl_ui/properties_render.py
+++ b/release/scripts/startup/bl_ui/properties_render.py
@@ -63,10 +63,10 @@ class RENDER_PT_render(RenderButtonsPanel, Panel):
rd = context.scene.render
- row = layout.row()
- row.operator("render.render", text="Image", icon='RENDER_STILL')
+ row = layout.row(align=True)
+ row.operator("render.render", text="Render", icon='RENDER_STILL')
row.operator("render.render", text="Animation", icon='RENDER_ANIMATION').animation = True
- row.operator("render.play_rendered_anim", text="Play", icon='RENDER_ANIMATION')
+ row.operator("render.play_rendered_anim", text="Play", icon='PLAY')
layout.prop(rd, "display_mode", text="Display")
@@ -225,7 +225,7 @@ class RENDER_PT_dimensions(RenderButtonsPanel, Panel):
# TODO: Change the following to iterate over existing presets
custom_framerate = (fps_rate not in {23.98, 24, 25, 29.97, 30, 50, 59.94, 60})
- if custom_framerate == True:
+ if custom_framerate is True:
fps_label_text = "Custom (" + str(fps_rate) + " fps)"
else:
fps_label_text = str(fps_rate) + " fps"
@@ -316,7 +316,6 @@ class RENDER_PT_shading(RenderButtonsPanel, Panel):
col = split.column()
col.prop(rd, "use_raytrace", text="Ray Tracing")
- col.prop(rd, "use_color_unpremultiply")
col.prop(rd, "alpha_mode", text="Alpha")
@@ -333,15 +332,17 @@ class RENDER_PT_performance(RenderButtonsPanel, Panel):
split = layout.split()
col = split.column()
- col.label(text="Threads:")
- col.row().prop(rd, "threads_mode", expand=True)
- sub = col.column()
- sub.enabled = rd.threads_mode == 'FIXED'
- sub.prop(rd, "threads")
sub = col.column(align=True)
- sub.label(text="Tiles:")
- sub.prop(rd, "parts_x", text="X")
- sub.prop(rd, "parts_y", text="Y")
+ sub.label(text="Threads:")
+ sub.row().prop(rd, "threads_mode", expand=True)
+ subsub = sub.column()
+ subsub.enabled = rd.threads_mode == 'FIXED'
+ subsub.prop(rd, "threads")
+
+ sub = col.column(align=True)
+ sub.label(text="Tile Size:")
+ sub.prop(rd, "tile_x", text="X")
+ sub.prop(rd, "tile_y", text="Y")
col = split.column()
col.label(text="Memory:")
diff --git a/release/scripts/startup/bl_ui/properties_scene.py b/release/scripts/startup/bl_ui/properties_scene.py
index 2ccdb9cee26..518b253d0b0 100644
--- a/release/scripts/startup/bl_ui/properties_scene.py
+++ b/release/scripts/startup/bl_ui/properties_scene.py
@@ -241,6 +241,7 @@ class SCENE_PT_color_management(Panel):
layout = self.layout
scene = context.scene
+ rd = scene.render
col = layout.column()
col.label(text="Display:")
@@ -250,6 +251,7 @@ class SCENE_PT_color_management(Panel):
col.separator()
col.label(text="Render:")
col.template_colormanaged_view_settings(scene, "view_settings")
+ col.prop(rd, "use_color_unpremultiply")
col = layout.column()
col.separator()
diff --git a/release/scripts/startup/bl_ui/properties_texture.py b/release/scripts/startup/bl_ui/properties_texture.py
index 46a17675c91..e623d034b48 100644
--- a/release/scripts/startup/bl_ui/properties_texture.py
+++ b/release/scripts/startup/bl_ui/properties_texture.py
@@ -111,8 +111,14 @@ class TEXTURE_PT_context_texture(TextureButtonsPanel, Panel):
engine = context.scene.render.engine
if not (hasattr(context, "texture_slot") or hasattr(context, "texture_node")):
return False
- return ((context.material or context.world or context.lamp or context.brush or context.texture or context.particle_system or isinstance(context.space_data.pin_id, ParticleSettings))
- and (engine in cls.COMPAT_ENGINES))
+ return ((context.material or
+ context.world or
+ context.lamp or
+ context.brush or
+ context.texture or
+ context.particle_system or
+ isinstance(context.space_data.pin_id, ParticleSettings)) and
+ (engine in cls.COMPAT_ENGINES))
def draw(self, context):
layout = self.layout
@@ -143,20 +149,15 @@ class TEXTURE_PT_context_texture(TextureButtonsPanel, Panel):
col.operator("texture.slot_move", text="", icon='TRIA_DOWN').type = 'DOWN'
col.menu("TEXTURE_MT_specials", icon='DOWNARROW_HLT', text="")
- split = layout.split(percentage=0.65)
- col = split.column()
-
if tex_collection:
- col.template_ID(idblock, "active_texture", new="texture.new")
+ layout.template_ID(idblock, "active_texture", new="texture.new")
elif node:
- col.template_ID(node, "texture", new="texture.new")
+ layout.template_ID(node, "texture", new="texture.new")
elif idblock:
- col.template_ID(idblock, "texture", new="texture.new")
+ layout.template_ID(idblock, "texture", new="texture.new")
if pin_id:
- col.template_ID(space, "pin_id")
-
- col = split.column()
+ layout.template_ID(space, "pin_id")
if tex:
split = layout.split(percentage=0.2)
@@ -881,8 +882,12 @@ class TEXTURE_PT_mapping(TextureSlotPanel, Panel):
col = split.column()
if tex.texture_coords in {'ORCO', 'UV'}:
col.prop(tex, "use_from_dupli")
+ if (idblock.type == 'VOLUME' and tex.texture_coords == 'ORCO'):
+ col.prop(tex, "use_map_to_bounds")
elif tex.texture_coords == 'OBJECT':
col.prop(tex, "use_from_original")
+ if (idblock.type == 'VOLUME'):
+ col.prop(tex, "use_map_to_bounds")
else:
col.label()
diff --git a/release/scripts/startup/bl_ui/space_clip.py b/release/scripts/startup/bl_ui/space_clip.py
index efac7a66086..cb88226b55a 100644
--- a/release/scripts/startup/bl_ui/space_clip.py
+++ b/release/scripts/startup/bl_ui/space_clip.py
@@ -311,8 +311,8 @@ class CLIP_PT_tools_solve(CLIP_PT_tracking_panel, Panel):
col = layout.column(align=True)
col.active = not settings.use_tripod_solver
- col.prop(settings, "keyframe_a")
- col.prop(settings, "keyframe_b")
+ col.prop(tracking_object, "keyframe_a")
+ col.prop(tracking_object, "keyframe_b")
col = layout.column(align=True)
col.active = (tracking_object.is_camera and
@@ -320,6 +320,13 @@ class CLIP_PT_tools_solve(CLIP_PT_tracking_panel, Panel):
col.label(text="Refine:")
col.prop(settings, "refine_intrinsics", text="")
+ col = layout.column(align=True)
+ col.active = not settings.use_tripod_solver
+ col.prop(settings, "use_fallback_reconstruction", text="Allow Fallback")
+ sub = col.column()
+ sub.active = settings.use_fallback_reconstruction
+ sub.prop(settings, "reconstruction_success_threshold")
+
class CLIP_PT_tools_cleanup(CLIP_PT_tracking_panel, Panel):
bl_space_type = 'CLIP_EDITOR'
@@ -790,42 +797,45 @@ class CLIP_PT_proxy(CLIP_PT_clip_view_panel, Panel):
sc = context.space_data
clip = sc.clip
- layout.active = clip.use_proxy
+ col = layout.column()
+ col.active = clip.use_proxy
- layout.label(text="Build Original:")
+ col.label(text="Build Original:")
- row = layout.row(align=True)
+ row = col.row(align=True)
row.prop(clip.proxy, "build_25", toggle=True)
row.prop(clip.proxy, "build_50", toggle=True)
row.prop(clip.proxy, "build_75", toggle=True)
row.prop(clip.proxy, "build_100", toggle=True)
- layout.label(text="Build Undistorted:")
+ col.label(text="Build Undistorted:")
- row = layout.row(align=True)
+ row = col.row(align=True)
row.prop(clip.proxy, "build_undistorted_25", toggle=True)
row.prop(clip.proxy, "build_undistorted_50", toggle=True)
row.prop(clip.proxy, "build_undistorted_75", toggle=True)
row.prop(clip.proxy, "build_undistorted_100", toggle=True)
- layout.prop(clip.proxy, "quality")
+ col.prop(clip.proxy, "quality")
- layout.prop(clip, "use_proxy_custom_directory")
+ col.prop(clip, "use_proxy_custom_directory")
if clip.use_proxy_custom_directory:
- layout.prop(clip.proxy, "directory")
+ col.prop(clip.proxy, "directory")
- layout.operator("clip.rebuild_proxy", text="Build Proxy")
+ col.operator("clip.rebuild_proxy", text="Build Proxy")
if clip.source == 'MOVIE':
- col = layout.column()
+ col2 = col.column()
- col.label(text="Use timecode index:")
- col.prop(clip.proxy, "timecode", text="")
+ col2.label(text="Use timecode index:")
+ col2.prop(clip.proxy, "timecode", text="")
- col = layout.column()
- col.label(text="Proxy render size:")
+ col2 = col.column()
+ col2.label(text="Proxy render size:")
col.prop(sc.clip_user, "proxy_render_size", text="")
+
+ col = layout.column()
col.prop(sc.clip_user, "use_render_undistorted")
@@ -888,6 +898,12 @@ class CLIP_MT_view(Menu):
layout.operator("clip.view_zoom_ratio",
text=text).ratio = a / b
else:
+ if sc.view == 'GRAPH':
+ layout.operator_context = 'INVOKE_REGION_PREVIEW'
+ layout.operator("clip.graph_center_current_frame")
+ layout.operator("clip.graph_view_all")
+ layout.operator_context = 'INVOKE_DEFAULT'
+
layout.prop(sc, "show_seconds")
layout.separator()
@@ -939,7 +955,7 @@ class CLIP_MT_track(Menu):
props.action = 'UPTO'
props = layout.operator("clip.clear_track_path",
- text="Clear Track Path")
+ text="Clear Track Path")
props.action = 'ALL'
layout.separator()
@@ -954,7 +970,7 @@ class CLIP_MT_track(Menu):
layout.separator()
props = layout.operator("clip.track_markers",
- text="Track Frame Backwards")
+ text="Track Frame Backwards")
props.backwards = True
props = layout.operator("clip.track_markers", text="Track Backwards")
diff --git a/release/scripts/startup/bl_ui/space_console.py b/release/scripts/startup/bl_ui/space_console.py
index 7ded4954f80..5ff179902a3 100644
--- a/release/scripts/startup/bl_ui/space_console.py
+++ b/release/scripts/startup/bl_ui/space_console.py
@@ -86,7 +86,7 @@ class CONSOLE_MT_language(Menu):
def add_scrollback(text, text_type):
for l in text.split("\n"):
bpy.ops.console.scrollback_append(text=l.replace('\t', ' '),
- type=text_type)
+ type=text_type)
if __name__ == "__main__": # only for live edit.
bpy.utils.register_module(__name__)
diff --git a/release/scripts/startup/bl_ui/space_dopesheet.py b/release/scripts/startup/bl_ui/space_dopesheet.py
index 8e955338480..a81553a8257 100644
--- a/release/scripts/startup/bl_ui/space_dopesheet.py
+++ b/release/scripts/startup/bl_ui/space_dopesheet.py
@@ -29,6 +29,7 @@ from bpy.types import Header, Menu
def dopesheet_filter(layout, context, genericFiltersOnly=False):
dopesheet = context.space_data.dopesheet
is_nla = context.area.type == 'NLA_EDITOR'
+ is_drivers = (context.area.type == 'GRAPH_EDITOR' and context.space_data.mode == 'DRIVERS')
row = layout.row(align=True)
row.prop(dopesheet, "show_only_selected", text="")
@@ -37,6 +38,9 @@ def dopesheet_filter(layout, context, genericFiltersOnly=False):
if is_nla:
row.prop(dopesheet, "show_missing_nla", text="")
+ if is_drivers:
+ row.prop(dopesheet, "show_only_errors", text="")
+
if not genericFiltersOnly:
if bpy.data.groups:
row = layout.row(align=True)
@@ -161,7 +165,6 @@ class DOPESHEET_MT_view(Menu):
layout.operator("action.previewrange_set")
layout.separator()
- layout.operator("action.frame_jump")
layout.operator("action.view_all")
layout.operator("action.view_selected")
@@ -272,6 +275,9 @@ class DOPESHEET_MT_key(Menu):
layout.operator("action.keyframe_insert")
layout.separator()
+ layout.operator("action.frame_jump")
+
+ layout.separator()
layout.operator("action.duplicate_move")
layout.operator("action.delete")
diff --git a/release/scripts/startup/bl_ui/space_filebrowser.py b/release/scripts/startup/bl_ui/space_filebrowser.py
index 435b968f243..256545bab70 100644
--- a/release/scripts/startup/bl_ui/space_filebrowser.py
+++ b/release/scripts/startup/bl_ui/space_filebrowser.py
@@ -67,6 +67,7 @@ class FILEBROWSER_HT_header(Header):
row.label(params.filter_glob)
else:
row.prop(params, "use_filter_blender", text="")
+ row.prop(params, "use_filter_backup", text="")
row.prop(params, "use_filter_image", text="")
row.prop(params, "use_filter_movie", text="")
row.prop(params, "use_filter_script", text="")
diff --git a/release/scripts/startup/bl_ui/space_graph.py b/release/scripts/startup/bl_ui/space_graph.py
index 972b4ebe721..e89bd78a84f 100644
--- a/release/scripts/startup/bl_ui/space_graph.py
+++ b/release/scripts/startup/bl_ui/space_graph.py
@@ -96,7 +96,6 @@ class GRAPH_MT_view(Menu):
layout.operator("graph.previewrange_set")
layout.separator()
- layout.operator("graph.frame_jump")
layout.operator("graph.view_all")
layout.operator("graph.view_selected")
@@ -199,6 +198,9 @@ class GRAPH_MT_key(Menu):
layout.operator("graph.sound_bake")
layout.separator()
+ layout.operator("graph.frame_jump")
+
+ layout.separator()
layout.operator("graph.duplicate_move")
layout.operator("graph.delete")
diff --git a/release/scripts/startup/bl_ui/space_info.py b/release/scripts/startup/bl_ui/space_info.py
index 04ea6b818ac..c0f2d3c361b 100644
--- a/release/scripts/startup/bl_ui/space_info.py
+++ b/release/scripts/startup/bl_ui/space_info.py
@@ -112,8 +112,9 @@ class INFO_MT_file(Menu):
layout.separator()
- layout.operator_context = 'INVOKE_AREA'
- layout.operator("wm.save_mainfile", text="Save", icon='FILE_TICK').check_existing = False
+ layout.operator_context = 'EXEC_AREA' if context.blend_data.is_saved else 'INVOKE_AREA'
+ layout.operator("wm.save_mainfile", text="Save", icon='FILE_TICK')
+
layout.operator_context = 'INVOKE_AREA'
layout.operator("wm.save_as_mainfile", text="Save As...", icon='SAVE_AS')
layout.operator_context = 'INVOKE_AREA'
@@ -192,7 +193,7 @@ class INFO_MT_mesh_add(Menu):
def draw(self, context):
layout = self.layout
- layout.operator_context = 'INVOKE_REGION_WIN'
+ layout.operator_context = 'EXEC_REGION_WIN'
layout.operator("mesh.primitive_plane_add", icon='MESH_PLANE', text="Plane")
layout.operator("mesh.primitive_cube_add", icon='MESH_CUBE', text="Cube")
layout.operator("mesh.primitive_circle_add", icon='MESH_CIRCLE', text="Circle")
@@ -203,7 +204,7 @@ class INFO_MT_mesh_add(Menu):
layout.separator()
layout.operator("mesh.primitive_grid_add", icon='MESH_GRID', text="Grid")
layout.operator("mesh.primitive_monkey_add", icon='MESH_MONKEY', text="Monkey")
- layout.operator("mesh.primitive_torus_add", text="Torus", icon='MESH_TORUS')
+ layout.operator("mesh.primitive_torus_add", icon='MESH_TORUS', text="Torus")
class INFO_MT_curve_add(Menu):
@@ -213,7 +214,7 @@ class INFO_MT_curve_add(Menu):
def draw(self, context):
layout = self.layout
- layout.operator_context = 'INVOKE_REGION_WIN'
+ layout.operator_context = 'EXEC_REGION_WIN'
layout.operator("curve.primitive_bezier_curve_add", icon='CURVE_BEZCURVE', text="Bezier")
layout.operator("curve.primitive_bezier_circle_add", icon='CURVE_BEZCIRCLE', text="Circle")
layout.operator("curve.primitive_nurbs_curve_add", icon='CURVE_NCURVE', text="Nurbs Curve")
@@ -221,22 +222,6 @@ class INFO_MT_curve_add(Menu):
layout.operator("curve.primitive_nurbs_path_add", icon='CURVE_PATH', text="Path")
-class INFO_MT_edit_curve_add(Menu):
- bl_idname = "INFO_MT_edit_curve_add"
- bl_label = "Add"
-
- def draw(self, context):
- is_surf = context.active_object.type == 'SURFACE'
-
- layout = self.layout
- layout.operator_context = 'INVOKE_REGION_WIN'
-
- if is_surf:
- INFO_MT_surface_add.draw(self, context)
- else:
- INFO_MT_curve_add.draw(self, context)
-
-
class INFO_MT_surface_add(Menu):
bl_idname = "INFO_MT_surface_add"
bl_label = "Surface"
@@ -244,7 +229,7 @@ class INFO_MT_surface_add(Menu):
def draw(self, context):
layout = self.layout
- layout.operator_context = 'INVOKE_REGION_WIN'
+ layout.operator_context = 'EXEC_REGION_WIN'
layout.operator("surface.primitive_nurbs_surface_curve_add", icon='SURFACE_NCURVE', text="NURBS Curve")
layout.operator("surface.primitive_nurbs_surface_circle_add", icon='SURFACE_NCIRCLE', text="NURBS Circle")
layout.operator("surface.primitive_nurbs_surface_surface_add", icon='SURFACE_NSURFACE', text="NURBS Surface")
@@ -253,6 +238,22 @@ class INFO_MT_surface_add(Menu):
layout.operator("surface.primitive_nurbs_surface_torus_add", icon='SURFACE_NTORUS', text="NURBS Torus")
+class INFO_MT_edit_curve_add(Menu):
+ bl_idname = "INFO_MT_edit_curve_add"
+ bl_label = "Add"
+
+ def draw(self, context):
+ is_surf = context.active_object.type == 'SURFACE'
+
+ layout = self.layout
+ layout.operator_context = 'EXEC_REGION_WIN'
+
+ if is_surf:
+ INFO_MT_surface_add.draw(self, context)
+ else:
+ INFO_MT_curve_add.draw(self, context)
+
+
class INFO_MT_armature_add(Menu):
bl_idname = "INFO_MT_armature_add"
bl_label = "Armature"
@@ -260,7 +261,7 @@ class INFO_MT_armature_add(Menu):
def draw(self, context):
layout = self.layout
- layout.operator_context = 'INVOKE_REGION_WIN'
+ layout.operator_context = 'EXEC_REGION_WIN'
layout.operator("object.armature_add", text="Single Bone", icon='BONE_DATA')
@@ -272,7 +273,9 @@ class INFO_MT_add(Menu):
# note, don't use 'EXEC_SCREEN' or operators wont get the 'v3d' context.
- layout.operator_context = 'EXEC_AREA'
+ # Note: was EXEC_AREA, but this context does not have the 'rv3d', which prevents
+ # "align_view" to work on first call (see [#32719]).
+ layout.operator_context = 'EXEC_REGION_WIN'
#layout.operator_menu_enum("object.mesh_add", "type", text="Mesh", icon='OUTLINER_OB_MESH')
layout.menu("INFO_MT_mesh_add", icon='OUTLINER_OB_MESH')
@@ -282,20 +285,18 @@ class INFO_MT_add(Menu):
#layout.operator_menu_enum("object.surface_add", "type", text="Surface", icon='OUTLINER_OB_SURFACE')
layout.menu("INFO_MT_surface_add", icon='OUTLINER_OB_SURFACE')
layout.operator_menu_enum("object.metaball_add", "type", text="Metaball", icon='OUTLINER_OB_META')
- layout.operator_context = 'INVOKE_REGION_WIN'
layout.operator("object.text_add", text="Text", icon='OUTLINER_OB_FONT')
layout.separator()
layout.menu("INFO_MT_armature_add", icon='OUTLINER_OB_ARMATURE')
layout.operator("object.add", text="Lattice", icon='OUTLINER_OB_LATTICE').type = 'LATTICE'
- layout.operator("object.add", text="Empty", icon='OUTLINER_OB_EMPTY').type = 'EMPTY'
+ layout.operator_menu_enum("object.empty_add", "type", text="Empty", icon='OUTLINER_OB_EMPTY')
layout.separator()
layout.operator("object.speaker_add", text="Speaker", icon='OUTLINER_OB_SPEAKER')
layout.separator()
layout.operator("object.camera_add", text="Camera", icon='OUTLINER_OB_CAMERA')
- layout.operator_context = 'EXEC_AREA'
layout.operator_menu_enum("object.lamp_add", "type", text="Lamp", icon='OUTLINER_OB_LAMP')
layout.separator()
@@ -303,7 +304,7 @@ class INFO_MT_add(Menu):
layout.separator()
if(len(bpy.data.groups) > 10):
- layout.operator_context = 'INVOKE_DEFAULT'
+ layout.operator_context = 'INVOKE_REGION_WIN'
layout.operator("object.group_instance_add", text="Group Instance...", icon='OUTLINER_OB_EMPTY')
else:
layout.operator_menu_enum("object.group_instance_add", "group", text="Group Instance", icon='OUTLINER_OB_EMPTY')
diff --git a/release/scripts/startup/bl_ui/space_logic.py b/release/scripts/startup/bl_ui/space_logic.py
index 846169b3339..730398171d6 100644
--- a/release/scripts/startup/bl_ui/space_logic.py
+++ b/release/scripts/startup/bl_ui/space_logic.py
@@ -107,5 +107,10 @@ class LOGIC_MT_view(Menu):
layout.operator("logic.properties", icon='MENU_PANEL')
+ layout.separator()
+
+ layout.operator("screen.area_dupli")
+ layout.operator("screen.screen_full_area")
+
if __name__ == "__main__": # only for live edit.
bpy.utils.register_module(__name__)
diff --git a/release/scripts/startup/bl_ui/space_node.py b/release/scripts/startup/bl_ui/space_node.py
index 5b7ecbfb618..c46b1c20738 100644
--- a/release/scripts/startup/bl_ui/space_node.py
+++ b/release/scripts/startup/bl_ui/space_node.py
@@ -166,11 +166,19 @@ class NODE_MT_node(Menu):
layout.operator("node.delete_reconnect")
layout.separator()
+
+ layout.operator("node.join", text="Join in new Frame")
+ layout.operator("node.detach", text="Remove from Frame")
+
+ layout.separator()
+
layout.operator("node.link_make")
layout.operator("node.link_make", text="Make and Replace Links").replace = True
layout.operator("node.links_cut")
+ layout.operator("node.links_detach")
layout.separator()
+
layout.operator("node.group_edit")
layout.operator("node.group_ungroup")
layout.operator("node.group_make")
diff --git a/release/scripts/startup/bl_ui/space_sequencer.py b/release/scripts/startup/bl_ui/space_sequencer.py
index 39c892930f4..14fbc7c34be 100644
--- a/release/scripts/startup/bl_ui/space_sequencer.py
+++ b/release/scripts/startup/bl_ui/space_sequencer.py
@@ -83,11 +83,11 @@ class SEQUENCER_HT_header(Header):
layout.separator()
layout.operator("sequencer.refresh_all")
- elif st.view_type == 'SEQUENCER_PREVIEW':
- layout.separator()
- layout.operator("sequencer.refresh_all")
- layout.prop(st, "display_channel", text="Channel")
else:
+ if st.view_type == 'SEQUENCER_PREVIEW':
+ layout.separator()
+ layout.operator("sequencer.refresh_all")
+
layout.prop(st, "display_channel", text="Channel")
ed = context.scene.sequence_editor
@@ -101,12 +101,12 @@ class SEQUENCER_HT_header(Header):
row = layout.row()
row.prop(st, "overlay_type", text="")
- row = layout.row(align=True)
- props = row.operator("render.opengl", text="", icon='RENDER_STILL')
- props.sequencer = True
- props = row.operator("render.opengl", text="", icon='RENDER_ANIMATION')
- props.animation = True
- props.sequencer = True
+ row = layout.row(align=True)
+ props = row.operator("render.opengl", text="", icon='RENDER_STILL')
+ props.sequencer = True
+ props = row.operator("render.opengl", text="", icon='RENDER_ANIMATION')
+ props.animation = True
+ props.sequencer = True
layout.template_running_jobs()
@@ -130,12 +130,19 @@ class SEQUENCER_MT_view(Menu):
st = context.space_data
+ if st.view_type in {'PREVIEW'}:
+ # Specifying the REGION_PREVIEW context is needed in preview-only
+ # mode, else the lookup for the shortcut will fail in
+ # wm_keymap_item_find_props() (see #32595).
+ layout.operator_context = 'INVOKE_REGION_PREVIEW'
layout.operator("sequencer.properties", icon='MENU_PANEL')
+ layout.operator_context = 'INVOKE_DEFAULT'
layout.separator()
if st.view_type in {'SEQUENCER', 'SEQUENCER_PREVIEW'}:
layout.operator("sequencer.view_all", text="View all Sequences")
+ layout.operator("sequencer.view_selected")
if st.view_type in {'PREVIEW', 'SEQUENCER_PREVIEW'}:
layout.operator_context = 'INVOKE_REGION_PREVIEW'
layout.operator("sequencer.view_all_preview", text="Fit preview in window")
@@ -145,19 +152,21 @@ class SEQUENCER_MT_view(Menu):
# # XXX, invokes in the header view
# layout.operator("sequencer.view_ghost_border", text="Overlay Border")
- layout.operator("sequencer.view_selected")
-
- layout.prop(st, "show_seconds")
+ if st.view_type in {'SEQUENCER', 'SEQUENCER_PREVIEW'}:
+ layout.prop(st, "show_seconds")
+ layout.prop(st, "show_frame_indicator")
- layout.prop(st, "show_frame_indicator")
- if st.display_mode == 'IMAGE':
- layout.prop(st, "show_safe_margin")
- if st.display_mode == 'WAVEFORM':
- layout.prop(st, "show_separate_color")
+ if st.view_type in {'PREVIEW', 'SEQUENCER_PREVIEW'}:
+ if st.display_mode == 'IMAGE':
+ layout.prop(st, "show_safe_margin")
+ elif st.display_mode == 'WAVEFORM':
+ layout.prop(st, "show_separate_color")
layout.separator()
- layout.prop(st, "use_marker_sync")
- layout.separator()
+
+ if st.view_type in {'SEQUENCER', 'SEQUENCER_PREVIEW'}:
+ layout.prop(st, "use_marker_sync")
+ layout.separator()
layout.operator("screen.area_dupli")
layout.operator("screen.screen_full_area")
@@ -851,7 +860,6 @@ class SEQUENCER_PT_preview(SequencerButtonsPanel_Output, Panel):
render = context.scene.render
col = layout.column()
- col.active = False # Currently only opengl preview works!
col.prop(render, "use_sequencer_gl_preview", text="Open GL Preview")
col = layout.column()
#col.active = render.use_sequencer_gl_preview
diff --git a/release/scripts/startup/bl_ui/space_text.py b/release/scripts/startup/bl_ui/space_text.py
index eca9bc22db9..a64f8aa4aed 100644
--- a/release/scripts/startup/bl_ui/space_text.py
+++ b/release/scripts/startup/bl_ui/space_text.py
@@ -56,12 +56,17 @@ class TEXT_HT_header(Header):
row.prop(st, "show_syntax_highlight", text="")
if text:
- row = layout.row()
- row.operator("text.run_script")
+ osl = text.name.endswith(".osl") or text.name.endswith(".oso")
- row = layout.row()
- row.active = text.name.endswith(".py")
- row.prop(text, "use_module")
+ if osl:
+ row = layout.row()
+ row.operator("node.shader_script_update")
+ else:
+ row = layout.row()
+ row.operator("text.run_script")
+
+ row = layout.row()
+ row.prop(text, "use_module")
row = layout.row()
if text.filepath:
@@ -149,12 +154,7 @@ class TEXT_MT_view(Menu):
layout = self.layout
layout.operator("text.properties", icon='MENU_PANEL')
-
- layout.separator()
-
- layout.operator("screen.area_dupli")
- layout.operator("screen.screen_full_area")
-
+
layout.separator()
layout.operator("text.move",
@@ -164,6 +164,11 @@ class TEXT_MT_view(Menu):
text="Bottom of File",
).type = 'FILE_BOTTOM'
+ layout.separator()
+
+ layout.operator("screen.area_dupli")
+ layout.operator("screen.screen_full_area")
+
class TEXT_MT_text(Menu):
bl_label = "Text"
diff --git a/release/scripts/startup/bl_ui/space_time.py b/release/scripts/startup/bl_ui/space_time.py
index ed1d2a0ae24..cb9e2444793 100644
--- a/release/scripts/startup/bl_ui/space_time.py
+++ b/release/scripts/startup/bl_ui/space_time.py
@@ -127,6 +127,11 @@ class TIME_MT_view(Menu):
layout.operator("marker.camera_bind")
+ layout.separator()
+
+ layout.operator("screen.area_dupli")
+ layout.operator("screen.screen_full_area")
+
class TIME_MT_cache(Menu):
bl_label = "Cache"
diff --git a/release/scripts/startup/bl_ui/space_userpref.py b/release/scripts/startup/bl_ui/space_userpref.py
index b0b587056b1..455bf210ac2 100644
--- a/release/scripts/startup/bl_ui/space_userpref.py
+++ b/release/scripts/startup/bl_ui/space_userpref.py
@@ -20,7 +20,6 @@
import bpy
from bpy.types import Header, Menu, Panel
import os
-import addon_utils
def ui_items_general(col, context):
@@ -93,7 +92,7 @@ class USERPREF_HT_header(Header):
layout.operator("wm.keyconfig_import")
layout.operator("wm.keyconfig_export")
elif userpref.active_section == 'ADDONS':
- layout.operator("wm.addon_install")
+ layout.operator("wm.addon_install", icon="FILESEL")
layout.menu("USERPREF_MT_addons_dev_guides")
elif userpref.active_section == 'THEMES':
layout.operator("ui.reset_default_theme")
@@ -249,7 +248,7 @@ class USERPREF_PT_interface(Panel):
col.prop(view, "show_splash")
if os.name == "nt":
- col.prop(view, "quit_dialog")
+ col.prop(view, "use_quit_dialog")
class USERPREF_PT_edit(Panel):
@@ -300,9 +299,9 @@ class USERPREF_PT_edit(Panel):
col.label(text="Grease Pencil:")
col.prop(edit, "grease_pencil_manhattan_distance", text="Manhattan Distance")
col.prop(edit, "grease_pencil_euclidean_distance", text="Euclidean Distance")
- #~ col.prop(edit, "use_grease_pencil_simplify_stroke", text="Simplify Stroke")
col.prop(edit, "grease_pencil_eraser_radius", text="Eraser Radius")
col.prop(edit, "use_grease_pencil_smooth_stroke", text="Smooth Stroke")
+ col.prop(edit, "use_grease_pencil_simplify_stroke", text="Simplify Stroke")
col.separator()
col.separator()
col.separator()
@@ -325,6 +324,7 @@ class USERPREF_PT_edit(Panel):
col.separator()
col.prop(edit, "use_auto_keying", text="Auto Keyframing:")
+ col.prop(edit, "use_auto_keying_warning")
sub = col.column()
@@ -823,6 +823,7 @@ class USERPREF_PT_file(Panel):
col.prop(paths, "use_filter_files")
col.prop(paths, "show_hidden_files_datablocks")
col.prop(paths, "hide_recent_locations")
+ col.prop(paths, "hide_system_bookmarks")
col.prop(paths, "show_thumbnails")
col.separator()
@@ -866,7 +867,7 @@ class USERPREF_MT_ndof_settings(Menu):
layout.separator()
layout.label(text="Orbit options")
- layout.prop(input_prefs, "ndof_turntable")
+ layout.row().prop(input_prefs, "ndof_view_rotate_method", text="")
layout.prop(input_prefs, "ndof_roll_invert_axis")
layout.prop(input_prefs, "ndof_tilt_invert_axis")
layout.prop(input_prefs, "ndof_rotate_invert_axis")
@@ -953,6 +954,8 @@ class USERPREF_PT_input(Panel, InputKeyMapPanel):
sub = col.column()
sub.label(text="NDOF Device:")
sub.prop(inputs, "ndof_sensitivity", text="NDOF Sensitivity")
+ sub.prop(inputs, "ndof_orbit_sensitivity", text="NDOF Orbit Sensitivity")
+ sub.row().prop(inputs, "ndof_view_rotate_method", expand=True)
row.separator()
@@ -1031,11 +1034,16 @@ class USERPREF_PT_addons(Panel):
box.label(l)
def draw(self, context):
+ import addon_utils
+
layout = self.layout
userpref = context.user_preferences
used_ext = {ext.module for ext in userpref.addons}
+ userpref_addons_folder = os.path.join(userpref.filepaths.script_directory, "addons")
+ scripts_addons_folder = bpy.utils.user_resource('SCRIPTS', "addons")
+
# collect the categories that can be filtered on
addons = [(mod, addon_utils.module_bl_info(mod)) for mod in addon_utils.modules(addon_utils.addons_fake_modules)]
@@ -1081,10 +1089,12 @@ class USERPREF_PT_addons(Panel):
continue
# check if addon should be visible with current filters
- if ((filter == "All") or
- (filter == info["category"]) or
- (filter == "Enabled" and is_enabled) or
- (filter == "Disabled" and not is_enabled)):
+ if ((filter == "All") or
+ (filter == info["category"]) or
+ (filter == "Enabled" and is_enabled) or
+ (filter == "Disabled" and not is_enabled) or
+ (filter == "User" and (mod.__file__.startswith((scripts_addons_folder, userpref_addons_folder))))
+ ):
if search and search not in info["name"].lower():
if info["author"]:
diff --git a/release/scripts/startup/bl_ui/space_userpref_keymap.py b/release/scripts/startup/bl_ui/space_userpref_keymap.py
index 6646da4a91a..81d67aa662c 100644
--- a/release/scripts/startup/bl_ui/space_userpref_keymap.py
+++ b/release/scripts/startup/bl_ui/space_userpref_keymap.py
@@ -186,10 +186,10 @@ class InputKeyMapPanel:
sub = split.column()
subrow = sub.row(align=True)
- if map_type in {'KEYBOARD', 'NDOF'}:
+ if map_type == 'KEYBOARD':
subrow.prop(kmi, "type", text="", event=True)
subrow.prop(kmi, "value", text="")
- elif map_type == 'MOUSE':
+ elif map_type in {'MOUSE', 'NDOF'}:
subrow.prop(kmi, "type", text="")
subrow.prop(kmi, "value", text="")
@@ -218,8 +218,8 @@ class InputKeyMapPanel:
layout.context_pointer_set("keymap", km)
filtered_items = [kmi for kmi in km.keymap_items
- if filter_text in kmi.idname.lower() or
- filter_text in kmi.name.lower()]
+ if (filter_text in kmi.idname.lower() or
+ filter_text in kmi.name.lower())]
if filtered_items:
col = layout.column()
diff --git a/release/scripts/startup/bl_ui/space_view3d.py b/release/scripts/startup/bl_ui/space_view3d.py
index 5db103466a9..6361a0dfc27 100644
--- a/release/scripts/startup/bl_ui/space_view3d.py
+++ b/release/scripts/startup/bl_ui/space_view3d.py
@@ -223,8 +223,8 @@ class VIEW3D_MT_transform_armature(VIEW3D_MT_transform_base):
layout.separator()
obj = context.object
- if (obj.type == 'ARMATURE' and obj.mode in {'EDIT', 'POSE'} and
- obj.data.draw_type in {'BBONE', 'ENVELOPE'}):
+ if (obj.type == 'ARMATURE' and obj.mode in {'EDIT', 'POSE'} and
+ obj.data.draw_type in {'BBONE', 'ENVELOPE'}):
layout.operator("transform.transform", text="Scale Envelope/BBone").mode = 'BONE_SIZE'
if context.edit_object and context.edit_object.type == 'ARMATURE':
@@ -571,7 +571,7 @@ class VIEW3D_MT_select_edit_mesh(Menu):
layout.separator()
layout.operator("mesh.select_random", text="Random")
- layout.operator("mesh.select_nth", text="Every N Number of Verts")
+ layout.operator("mesh.select_nth")
layout.operator("mesh.edges_select_sharp", text="Sharp Edges")
layout.operator("mesh.faces_select_linked_flat", text="Linked Flat Faces")
layout.operator("mesh.select_interior_faces", text="Interior Faces")
@@ -579,11 +579,11 @@ class VIEW3D_MT_select_edit_mesh(Menu):
layout.separator()
- layout.operator("mesh.select_by_number_vertices", text="By Number of Verts")
- if context.scene.tool_settings.mesh_select_mode[2] == False:
+ layout.operator("mesh.select_face_by_sides")
+ if context.scene.tool_settings.mesh_select_mode[2] is False:
layout.operator("mesh.select_non_manifold", text="Non Manifold")
layout.operator("mesh.select_loose_verts", text="Loose Verts/Edges")
- layout.operator("mesh.select_similar", text="Similar")
+ layout.operator_menu_enum("mesh.select_similar", "type", text="Similar")
layout.separator()
@@ -722,6 +722,7 @@ class VIEW3D_MT_select_edit_armature(Menu):
props.extend = True
props.direction = 'CHILD'
+ layout.operator_menu_enum("armature.select_similar", "type", text="Similar")
layout.operator("object.select_pattern", text="Select Pattern...")
@@ -806,7 +807,8 @@ class VIEW3D_MT_object_animation(Menu):
layout = self.layout
layout.operator("anim.keyframe_insert_menu", text="Insert Keyframe...")
- layout.operator("anim.keyframe_delete_v3d", text="Delete Keyframe...")
+ layout.operator("anim.keyframe_delete_v3d", text="Delete Keyframes...")
+ layout.operator("anim.keyframe_clear_v3d", text="Clear Keyframes...")
layout.operator("anim.keying_set_active_set", text="Change Keying Set...")
layout.separator()
@@ -966,8 +968,9 @@ class VIEW3D_MT_object_parent(Menu):
def draw(self, context):
layout = self.layout
- layout.operator_menu_enum("object.parent_set", "type", text="Set")
- layout.operator_menu_enum("object.parent_clear", "type", text="Clear")
+ layout.operator_enum("object.parent_set", "type")
+ layout.separator()
+ layout.operator_enum("object.parent_clear", "type")
class VIEW3D_MT_object_track(Menu):
@@ -976,8 +979,9 @@ class VIEW3D_MT_object_track(Menu):
def draw(self, context):
layout = self.layout
- layout.operator_menu_enum("object.track_set", "type", text="Set")
- layout.operator_menu_enum("object.track_clear", "type", text="Clear")
+ layout.operator_enum("object.track_set", "type")
+ layout.separator()
+ layout.operator_enum("object.track_clear", "type")
class VIEW3D_MT_object_group(Menu):
@@ -1245,6 +1249,8 @@ class VIEW3D_MT_paint_weight(Menu):
layout.operator("object.vertex_group_clean", text="Clean")
layout.operator("object.vertex_group_levels", text="Levels")
layout.operator("object.vertex_group_blend", text="Blend")
+ layout.operator("object.vertex_group_transfer_weight", text="Transfer Weights")
+ layout.operator("object.vertex_group_limit_total", text="Limit Total")
layout.operator("object.vertex_group_fix", text="Fix Deforms")
layout.separator()
@@ -1281,6 +1287,7 @@ class VIEW3D_MT_sculpt(Menu):
layout.prop(sculpt, "show_low_resolution")
layout.prop(sculpt, "show_brush")
layout.prop(sculpt, "use_deform_only")
+ layout.prop(sculpt, "show_diffuse_color")
class VIEW3D_MT_hide_mask(Menu):
@@ -1526,13 +1533,20 @@ class VIEW3D_MT_pose_group(Menu):
def draw(self, context):
layout = self.layout
- layout.operator("pose.group_add")
- layout.operator("pose.group_remove")
+
+ pose = context.active_object.pose
- layout.separator()
+ layout.operator_context = 'EXEC_AREA'
+ layout.operator("pose.group_assign", text="Assign to New Group").type = 0
+ if pose.bone_groups:
+ active_group = pose.bone_groups.active_index + 1
+ layout.operator("pose.group_assign", text="Assign to Group").type = active_group
+
+ layout.separator()
- layout.operator("pose.group_assign")
- layout.operator("pose.group_unassign")
+ #layout.operator_context = 'INVOKE_AREA'
+ layout.operator("pose.group_unassign")
+ layout.operator("pose.group_remove")
class VIEW3D_MT_pose_ik(Menu):
@@ -1657,7 +1671,7 @@ class VIEW3D_MT_edit_mesh(Menu):
layout.menu("VIEW3D_MT_uv_map", text="UV Unwrap...")
layout.separator()
-
+ layout.operator("mesh.symmetrize")
layout.operator("view3d.edit_mesh_extrude_move_normal", text="Extrude Region")
layout.operator("view3d.edit_mesh_extrude_individual_move", text="Extrude Individual")
layout.operator("mesh.duplicate_move")
@@ -1699,6 +1713,7 @@ class VIEW3D_MT_edit_mesh_specials(Menu):
layout.operator("mesh.select_all", text="Select Inverse").action = 'INVERT'
layout.operator("mesh.flip_normals")
layout.operator("mesh.vertices_smooth", text="Smooth")
+ layout.operator("mesh.vertices_smooth_laplacian", text="Laplacian Smooth")
layout.operator("mesh.inset")
layout.operator("mesh.bevel", text="Bevel")
layout.operator("mesh.bridge_edge_loops")
@@ -1708,6 +1723,7 @@ class VIEW3D_MT_edit_mesh_specials(Menu):
layout.operator("mesh.shape_propagate_to_all")
layout.operator("mesh.select_vertex_path")
layout.operator("mesh.sort_elements")
+ layout.operator("mesh.symmetrize")
class VIEW3D_MT_edit_mesh_select_mode(Menu):
@@ -1774,6 +1790,7 @@ class VIEW3D_MT_edit_mesh_vertices(Menu):
layout.operator("mesh.merge")
layout.operator("mesh.rip_move")
+ layout.operator("mesh.rip_move_fill")
layout.operator("mesh.split")
layout.operator_menu_enum("mesh.separate", "type")
layout.operator("mesh.vert_connect")
@@ -1808,6 +1825,7 @@ class VIEW3D_MT_edit_mesh_edges(Menu):
layout.operator("mesh.edge_face_add")
layout.operator("mesh.subdivide")
+ layout.operator("mesh.unsubdivide")
layout.separator()
@@ -1925,10 +1943,6 @@ class VIEW3D_MT_edit_mesh_dissolve(Menu):
layout.separator()
- layout.operator_enum("mesh.dissolve", "type")
-
- layout.separator()
-
layout.operator("mesh.dissolve_limited")
@@ -2143,6 +2157,7 @@ class VIEW3D_MT_edit_lattice(Menu):
layout.menu("VIEW3D_MT_transform")
layout.menu("VIEW3D_MT_mirror")
layout.menu("VIEW3D_MT_snap")
+ layout.operator_menu_enum("lattice.flip", "axis")
layout.separator()
@@ -2280,7 +2295,7 @@ class VIEW3D_PT_view3d_properties(Panel):
if lock_object.type == 'ARMATURE':
col.prop_search(view, "lock_bone", lock_object.data,
"edit_bones" if lock_object.mode == 'EDIT'
- else "bones",
+ else "bones",
text="")
else:
col.prop(view, "lock_cursor", text="Lock to Cursor")
@@ -2298,6 +2313,9 @@ class VIEW3D_PT_view3d_properties(Panel):
subcol.label(text="Local Camera:")
subcol.prop(view, "camera", text="")
+ col = layout.column(align=True)
+ col.prop(view, "use_render_border")
+
class VIEW3D_PT_view3d_cursor(Panel):
bl_space_type = 'VIEW_3D'
diff --git a/release/scripts/startup/bl_ui/space_view3d_toolbar.py b/release/scripts/startup/bl_ui/space_view3d_toolbar.py
index 1b67b30d17a..49355de4006 100644
--- a/release/scripts/startup/bl_ui/space_view3d_toolbar.py
+++ b/release/scripts/startup/bl_ui/space_view3d_toolbar.py
@@ -520,8 +520,8 @@ class VIEW3D_PT_tools_brush(Panel, View3DPaintPanel):
row = col.row(align=True)
ups = toolsettings.unified_paint_settings
- if ((ups.use_unified_size and ups.use_locked_size) or
- ((not ups.use_unified_size) and brush.use_locked_size)):
+ if ((ups.use_unified_size and ups.use_locked_size) or
+ ((not ups.use_unified_size) and brush.use_locked_size)):
self.prop_unified_size(row, context, brush, "use_locked_size", icon='LOCKED')
self.prop_unified_size(row, context, brush, "unprojected_radius", slider=True, text="Radius")
else:
@@ -707,8 +707,8 @@ class VIEW3D_PT_tools_brush_texture(Panel, View3DPaintPanel):
@classmethod
def poll(cls, context):
settings = cls.paint_settings(context)
- return (settings and settings.brush and (context.sculpt_object or
- context.image_paint_object))
+ return (settings and settings.brush and
+ (context.sculpt_object or context.image_paint_object))
def draw(self, context):
layout = self.layout
@@ -747,10 +747,12 @@ class VIEW3D_PT_tools_brush_stroke(Panel, View3DPaintPanel):
@classmethod
def poll(cls, context):
settings = cls.paint_settings(context)
- return (settings and settings.brush and (context.sculpt_object or
- context.vertex_paint_object or
- context.weight_paint_object or
- context.image_paint_object))
+ return (settings and
+ settings.brush and
+ (context.sculpt_object or
+ context.vertex_paint_object or
+ context.weight_paint_object or
+ context.image_paint_object))
def draw(self, context):
layout = self.layout
@@ -876,6 +878,7 @@ class VIEW3D_PT_sculpt_options(Panel, View3DPaintPanel):
layout.prop(sculpt, "show_low_resolution")
layout.prop(sculpt, "show_brush")
layout.prop(sculpt, "use_deform_only")
+ layout.prop(sculpt, "show_diffuse_color")
layout.prop(sculpt, "input_samples")
@@ -965,6 +968,8 @@ class VIEW3D_PT_tools_weightpaint(View3DPanel, Panel):
col.operator("object.vertex_group_clean", text="Clean")
col.operator("object.vertex_group_levels", text="Levels")
col.operator("object.vertex_group_blend", text="Blend")
+ col.operator("object.vertex_group_transfer_weight", text="Transfer Weights")
+ col.operator("object.vertex_group_limit_total", text="Limit Total")
col.operator("object.vertex_group_fix", text="Fix Deforms")
diff --git a/release/scripts/startup/keyingsets_builtins.py b/release/scripts/startup/keyingsets_builtins.py
index b7693880f9c..6ad87375738 100644
--- a/release/scripts/startup/keyingsets_builtins.py
+++ b/release/scripts/startup/keyingsets_builtins.py
@@ -360,10 +360,10 @@ class BUILTIN_KSI_WholeCharacter(KeyingSetInfo):
# add rotation properties if they will
if bone.lock_rotations_4d:
# can check individually
- if (bone.lock_rotation == (False, False, False)) and (bone.lock_rotation_w == False):
+ if (bone.lock_rotation == (False, False, False)) and (bone.lock_rotation_w is False):
ksi.addProp(ks, bone, prop)
else:
- if bone.lock_rotation_w == False:
+ if bone.lock_rotation_w is False:
ksi.addProp(ks, bone, prop, 0) # w = 0
for i in range(3):
diff --git a/release/scripts/templates/addon_add_object.py b/release/scripts/templates/addon_add_object.py
index d7fc23f9242..a4df5fb7436 100644
--- a/release/scripts/templates/addon_add_object.py
+++ b/release/scripts/templates/addon_add_object.py
@@ -39,10 +39,9 @@ def add_object(self, context):
class OBJECT_OT_add_object(Operator, AddObjectHelper):
- """Add a Mesh Object"""
+ """Create a new Mesh Object"""
bl_idname = "mesh.add_object"
bl_label = "Add Mesh Object"
- bl_description = "Create a new Mesh Object"
bl_options = {'REGISTER', 'UNDO'}
scale = FloatVectorProperty(
@@ -82,6 +81,7 @@ def register():
bpy.utils.register_manual_map(add_object_manual_map)
bpy.types.INFO_MT_mesh_add.append(add_object_button)
+
def unregister():
bpy.utils.unregister_class(OBJECT_OT_add_object)
bpy.utils.unregister_manual_map(add_object_manual_map)
diff --git a/release/scripts/templates/script_stub.py b/release/scripts/templates/script_stub.py
new file mode 100644
index 00000000000..3b3212892d5
--- /dev/null
+++ b/release/scripts/templates/script_stub.py
@@ -0,0 +1,11 @@
+# This stub runs a python script relative to the currently open
+# blend file, useful when editing scripts externally.
+
+import bpy
+import os
+
+# Use your own script name here:
+filename = "my_script.py"
+
+filepath = os.path.join(os.path.dirname(bpy.data.filepath), filename)
+exec(compile(open(filepath).read(), filepath, 'exec'))
diff --git a/release/scripts/templates/ui_panel.py b/release/scripts/templates/ui_panel.py
index 095fa105efa..cacdb83e815 100644
--- a/release/scripts/templates/ui_panel.py
+++ b/release/scripts/templates/ui_panel.py
@@ -12,36 +12,53 @@ class LayoutDemoPanel(bpy.types.Panel):
def draw(self, context):
layout = self.layout
- sc = context.scene
-
- #Create a simple row.
+ scene = context.scene
+
+ # Create a simple row.
layout.label(text=" Simple Row:")
-
+
row = layout.row()
- row.prop(sc, "frame_start")
- row.prop(sc, "frame_end")
-
- #Create an row where the buttons are aligned to each other.
- layout.label(text=" Aligned Row")
-
+ row.prop(scene, "frame_start")
+ row.prop(scene, "frame_end")
+
+ # Create an row where the buttons are aligned to each other.
+ layout.label(text=" Aligned Row:")
+
row = layout.row(align=True)
- row.prop(sc, "frame_start")
- row.prop(sc, "frame_end")
-
- #Create two columns, by using a split layout.
+ row.prop(scene, "frame_start")
+ row.prop(scene, "frame_end")
+
+ # Create two columns, by using a split layout.
split = layout.split()
-
+
# First column
col = split.column()
col.label(text="Column One:")
- col.prop(sc, "frame_end")
- col.prop(sc, "frame_start")
-
+ col.prop(scene, "frame_end")
+ col.prop(scene, "frame_start")
+
# Second column, aligned
col = split.column(align=True)
- col.label(text="Column Two")
- col.prop(sc, "frame_start")
- col.prop(sc, "frame_end")
+ col.label(text="Column Two:")
+ col.prop(scene, "frame_start")
+ col.prop(scene, "frame_end")
+
+ # Big render button
+ layout.label(text="Big Button:")
+ row = layout.row()
+ row.scale_y = 3.0
+ row.operator("render.render")
+
+ # Different sizes in a row
+ layout.label(text="Different button sizes:")
+ row = layout.row(align=True)
+ row.operator("render.render")
+
+ sub = row.row()
+ sub.scale_x = 2.0
+ sub.operator("render.render")
+
+ row.operator("render.render")
def register():
diff --git a/release/scripts/templates/ui_panel_simple.py b/release/scripts/templates/ui_panel_simple.py
index 3fab7d92675..9bcc750560f 100644
--- a/release/scripts/templates/ui_panel_simple.py
+++ b/release/scripts/templates/ui_panel_simple.py
@@ -22,6 +22,9 @@ class HelloWorldPanel(bpy.types.Panel):
row = layout.row()
row.prop(obj, "name")
+ row = layout.row()
+ row.operator("mesh.primitive_cube_add")
+
def register():
bpy.utils.register_class(HelloWorldPanel)
diff --git a/release/text/readme.html b/release/text/readme.html
index 512ba32bac0..40ea9035835 100644
--- a/release/text/readme.html
+++ b/release/text/readme.html
@@ -20,7 +20,7 @@
<p class="body">For more information, visit <a href="http://www.blender.org">blender.org</a>.</p>
<p><br></p>
<p class="header"><b>2.64</b></p>
-<p class="body">The Blender Foundation and online developer community is proud to present Blender 2.64. This release is the fifth official stable release of the Blender 2.6 series, in which we will refine the 2.5 series and add exciting new features. <a href="http://www.blender.org/development/release-logs/blender-263/">More information about this release</a>.</p>
+<p class="body">The Blender Foundation and online developer community is proud to present Blender 2.64. This release is the fifth official stable release of the Blender 2.6 series, in which we will refine the 2.5 series and add exciting new features. <a href="http://www.blender.org/development/release-logs/blender-264/">More information about this release</a>.</p>
<p><br></p>
<p class="header"><b>Bugs</b></p>
<p class="body">Although Blender 2.64 is considered a stable release, you may encounter a bug. If you do, please help us by posting it in the bug tracker or using Help → Report a Bug from inside Blender. If it wasn’t reported yet, please log in (or register) and fill in detailed information about the error. Please post detailed instructions on how to reproduce it or post a .blend file showcasing the bug.</p>
diff --git a/release/windows/contrib/vfapi/vfapi-plugin.c b/release/windows/contrib/vfapi/vfapi-plugin.c
index 81547b8bb1a..99ca6c64e80 100644
--- a/release/windows/contrib/vfapi/vfapi-plugin.c
+++ b/release/windows/contrib/vfapi/vfapi-plugin.c
@@ -15,7 +15,6 @@
*
*/
-
#include <windows.h>
#include <winbase.h>
#include <stdio.h>
@@ -83,16 +82,16 @@ typedef struct {
} VF_ReadData_Audio,*LPVF_ReadData_Audio;
typedef struct {
- DWORD dwSize;
- HRESULT (__stdcall *OpenFile)(
- char *lpFileName, LPVF_FileHandle lpFileHandle );
+ DWORD dwSize;
+ HRESULT (__stdcall *OpenFile)(
+ char *lpFileName, LPVF_FileHandle lpFileHandle );
HRESULT (__stdcall *CloseFile)( VF_FileHandle hFileHandle );
HRESULT (__stdcall *GetFileInfo)( VF_FileHandle hFileHandle,
- LPVF_FileInfo lpFileInfo );
+ LPVF_FileInfo lpFileInfo );
HRESULT (__stdcall *GetStreamInfo)( VF_FileHandle hFileHandle,
- DWORD dwStream,void *lpStreamInfo );
+ DWORD dwStream,void *lpStreamInfo );
HRESULT (__stdcall *ReadData)( VF_FileHandle hFileHandle,
- DWORD dwStream,void *lpData );
+ DWORD dwStream,void *lpData );
} VF_PluginFunc,*LPVF_PluginFunc;
__declspec(dllexport) HRESULT vfGetPluginInfo(
@@ -117,8 +116,9 @@ static unsigned long getipaddress(const char * ipaddr)
struct hostent *host;
unsigned long ip;
- if (((ip = inet_addr(ipaddr)) == INADDR_NONE)
- && strcmp(ipaddr, "255.255.255.255") != 0) {
+ if (((ip = inet_addr(ipaddr)) == INADDR_NONE) &&
+ strcmp(ipaddr, "255.255.255.255") != 0)
+ {
if ((host = gethostbyname(ipaddr)) != NULL) {
memcpy(&ip, host->h_addr, sizeof(ip));
}
@@ -157,7 +157,8 @@ static int my_gets(SOCKET sock, char * line, int maxlen)
line++;
*line = 0;
break;
- } else {
+ }
+ else {
line++;
maxlen--;
}
@@ -187,7 +188,7 @@ HRESULT __stdcall VF_OpenFileFunc_Blen(
SOCKET s_in;
char buf[256];
struct sockaddr_in addr;
- FILE* fp;
+ FILE *fp;
p = lpFileName;
while (*p && *p != '.') p++;
@@ -228,7 +229,7 @@ HRESULT __stdcall VF_OpenFileFunc_Blen(
return VF_ERROR;
}
- rval = (conndesc*) malloc(sizeof(conndesc));
+ rval = (conndesc *) malloc(sizeof(conndesc));
rval->addr = addr;
@@ -251,15 +252,20 @@ HRESULT __stdcall VF_OpenFileFunc_Blen(
if (strcmp(key, "width") == 0) {
rval->width = atoi(val);
- } else if (strcmp(key, "height") == 0) {
+ }
+ else if (strcmp(key, "height") == 0) {
rval->height = atoi(val);
- } else if (strcmp(key, "start") == 0) {
+ }
+ else if (strcmp(key, "start") == 0) {
rval->start = atoi(val);
- } else if (strcmp(key, "end") == 0) {
+ }
+ else if (strcmp(key, "end") == 0) {
rval->end = atoi(val);
- } else if (strcmp(key, "rate") == 0) {
+ }
+ else if (strcmp(key, "rate") == 0) {
rval->rate = atoi(val);
- } else if (strcmp(key, "ratescale") == 0) {
+ }
+ else if (strcmp(key, "ratescale") == 0) {
rval->ratescale = atoi(val);
}
}
@@ -275,7 +281,7 @@ HRESULT __stdcall VF_OpenFileFunc_Blen(
HRESULT __stdcall VF_CloseFileFunc_Blen(
VF_FileHandle hFileHandle )
{
- free((conndesc*) hFileHandle);
+ free((conndesc *) hFileHandle);
return VF_OK;
}
@@ -284,7 +290,7 @@ HRESULT __stdcall VF_GetFileInfoFunc_Blen(
VF_FileHandle hFileHandle,
LPVF_FileInfo lpFileInfo )
{
- conndesc * c = (conndesc*) hFileHandle;
+ conndesc *c = (conndesc *) hFileHandle;
if (c == 0) {
return VF_ERROR;
}
@@ -376,13 +382,13 @@ HRESULT __stdcall VF_ReadDataFunc_Blen(
my_gets(s_in, buf, 256); /* 255 */
- framebuf = (unsigned char*) v->lpData;
+ framebuf = (unsigned char *) v->lpData;
for (y = 0; y < height; y++) {
- unsigned char * p = framebuf + v->lPitch * y;
- unsigned char * e = p + width * 3;
+ unsigned char *p = framebuf + v->lPitch * y;
+ unsigned char *e = p + width * 3;
- my_recv(s_in, (char*) p, width * 3);
+ my_recv(s_in, (char *)p, width * 3);
while (p != e) {
unsigned char tmp = p[2];
p[2] = p[0];
@@ -413,6 +419,3 @@ __declspec(dllexport) HRESULT vfGetPluginFunc(
return VF_OK;
}
-
-
-
diff --git a/source/blender/CMakeLists.txt b/source/blender/CMakeLists.txt
index 92785804b01..ae3f3dce396 100644
--- a/source/blender/CMakeLists.txt
+++ b/source/blender/CMakeLists.txt
@@ -101,7 +101,6 @@ add_subdirectory(blenloader)
add_subdirectory(ikplugin)
add_subdirectory(gpu)
add_subdirectory(imbuf)
-add_subdirectory(avi)
add_subdirectory(nodes)
add_subdirectory(modifiers)
add_subdirectory(makesdna)
@@ -124,6 +123,10 @@ if(WITH_IMAGE_CINEON)
add_subdirectory(imbuf/intern/cineon)
endif()
+if(WITH_CODEC_AVI)
+ add_subdirectory(avi)
+endif()
+
if(WITH_CODEC_QUICKTIME)
add_subdirectory(quicktime)
endif()
diff --git a/source/blender/avi/AVI_avi.h b/source/blender/avi/AVI_avi.h
index bdfdbc117ed..4dc52970119 100644
--- a/source/blender/avi/AVI_avi.h
+++ b/source/blender/avi/AVI_avi.h
@@ -178,7 +178,7 @@ typedef struct _AviStreamRec {
} AviStreamRec;
typedef struct _AviMovie {
- FILE *fp;
+ FILE *fp;
int type;
#define AVI_MOVIE_READ 0
diff --git a/source/blender/avi/CMakeLists.txt b/source/blender/avi/CMakeLists.txt
index 79422dff917..292206d8cb9 100644
--- a/source/blender/avi/CMakeLists.txt
+++ b/source/blender/avi/CMakeLists.txt
@@ -35,19 +35,19 @@ set(INC_SYS
set(SRC
intern/avi.c
- intern/avirgb.c
- intern/codecs.c
- intern/endian.c
- intern/mjpeg.c
- intern/options.c
- intern/rgb32.c
+ intern/avi_rgb.c
+ intern/avi_codecs.c
+ intern/avi_endian.c
+ intern/avi_mjpeg.c
+ intern/avi_options.c
+ intern/avi_rgb32.c
AVI_avi.h
intern/avi_intern.h
- intern/avirgb.h
- intern/endian.h
- intern/mjpeg.h
- intern/rgb32.h
+ intern/avi_rgb.h
+ intern/avi_endian.h
+ intern/avi_mjpeg.h
+ intern/avi_rgb32.h
)
blender_add_lib(bf_avi "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/avi/intern/avi.c b/source/blender/avi/intern/avi.c
index 2845b2f95c9..e1732b0caae 100644
--- a/source/blender/avi/intern/avi.c
+++ b/source/blender/avi/intern/avi.c
@@ -32,7 +32,6 @@
* This is external code.
*/
-
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
@@ -49,7 +48,7 @@
#include "AVI_avi.h"
#include "avi_intern.h"
-#include "endian.h"
+#include "avi_endian.h"
static int AVI_DEBUG = 0;
static char DEBUG_FCC[4];
@@ -95,7 +94,7 @@ char *fcc_to_char(unsigned int fcc)
DEBUG_FCC[2] = (fcc >> 16) & 127;
DEBUG_FCC[3] = (fcc >> 24) & 127;
- return DEBUG_FCC;
+ return DEBUG_FCC;
}
char *tcc_to_char(unsigned int tcc)
@@ -105,7 +104,7 @@ char *tcc_to_char(unsigned int tcc)
DEBUG_FCC[2] = 0;
DEBUG_FCC[3] = 0;
- return DEBUG_FCC;
+ return DEBUG_FCC;
}
int AVI_get_stream(AviMovie *movie, int avist_type, int stream_num)
@@ -303,7 +302,7 @@ int AVI_is_avi(const char *name)
MEM_freeN(movie.streams);
fclose(movie.fp);
- return 0;
+ return 0;
}
movie.streams[temp].sh.Type = GET_FCC(movie.fp);
@@ -402,12 +401,12 @@ int AVI_is_avi(const char *name)
}
}
- }
+ }
if (j > 0) fseek(movie.fp, j, SEEK_CUR);
}
else fseek(movie.fp, movie.streams[temp].sf_size, SEEK_CUR);
- /* Walk to the next LIST */
+ /* Walk to the next LIST */
while (GET_FCC(movie.fp) != FCC("LIST")) {
temp = GET_FCC(movie.fp);
if (temp < 0 || ftell(movie.fp) > movie.size) {
@@ -415,9 +414,9 @@ int AVI_is_avi(const char *name)
MEM_freeN(movie.streams);
fclose(movie.fp);
- return 0;
+ return 0;
}
- fseek(movie.fp, temp, SEEK_CUR);
+ fseek(movie.fp, temp, SEEK_CUR);
}
fseek(movie.fp, -4L, SEEK_CUR);
@@ -593,12 +592,12 @@ AviError AVI_open_movie(const char *name, AviMovie *movie)
}
}
- }
+ }
if (j > 0) fseek(movie->fp, j, SEEK_CUR);
}
else fseek(movie->fp, movie->streams[temp].sf_size, SEEK_CUR);
- /* Walk to the next LIST */
+ /* Walk to the next LIST */
while (GET_FCC(movie->fp) != FCC("LIST")) {
temp = GET_FCC(movie->fp);
if (temp < 0 || ftell(movie->fp) > movie->size) {
@@ -828,7 +827,7 @@ AviError AVI_open_compress(char *name, AviMovie *movie, int streams, ...)
movie->streams[i].sh.right = 0;
movie->streams[i].sh.bottom = 0;
- if (movie->streams[i].sh.Type == FCC("vids")) {
+ if (movie->streams[i].sh.Type == FCC("vids")) {
#if 0
if (movie->streams[i].format == AVI_FORMAT_MJPEG) {
movie->streams[i].sf = MEM_mallocN(sizeof(AviBitmapInfoHeader) +
diff --git a/source/blender/avi/intern/codecs.c b/source/blender/avi/intern/avi_codecs.c
index 01e228d570e..e43826064a6 100644
--- a/source/blender/avi/intern/codecs.c
+++ b/source/blender/avi/intern/avi_codecs.c
@@ -25,7 +25,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/avi/intern/codecs.c
+/** \file blender/avi/intern/avi_codecs.c
* \ingroup avi
*
* This is external code. Identify and convert different avi-files.
@@ -35,9 +35,9 @@
#include "AVI_avi.h"
#include "avi_intern.h"
-#include "avirgb.h"
-#include "mjpeg.h"
-#include "rgb32.h"
+#include "avi_rgb.h"
+#include "avi_mjpeg.h"
+#include "avi_rgb32.h"
void *avi_format_convert(AviMovie *movie, int stream, void *buffer, AviFormat from, AviFormat to, int *size)
{
diff --git a/source/blender/avi/intern/endian.c b/source/blender/avi/intern/avi_endian.c
index c9b95d25810..70add8bd90f 100644
--- a/source/blender/avi/intern/endian.c
+++ b/source/blender/avi/intern/avi_endian.c
@@ -26,7 +26,7 @@
*
*/
-/** \file blender/avi/intern/endian.c
+/** \file blender/avi/intern/avi_endian.c
* \ingroup avi
*
* This is external code. Streams bytes to output depending on the
@@ -36,9 +36,10 @@
#include <stdlib.h>
#include <string.h>
-#include <stdio.h>
+#include <stdio.h>
+
#include "AVI_avi.h"
-#include "endian.h"
+#include "avi_endian.h"
#include "avi_intern.h"
#ifdef __BIG_ENDIAN__
@@ -46,31 +47,22 @@
#endif
#ifdef __BIG_ENDIAN__
+
+/* copied from BLI_endian_switch_inline.h */
static void invert(int *num)
{
- int new = 0, i, j;
-
- for (j = 0; j < 4; j++) {
- for (i = 0; i < 8; i++) {
- new |= ((*num >> (j * 8 + i)) & 1) << ((3 - j) * 8 + i);
- }
- }
-
- *num = new;
+ int tval = *val;
+ *val = ((tval >> 24)) |
+ ((tval << 8) & 0x00ff0000) |
+ ((tval >> 8) & 0x0000ff00) |
+ ((tval << 24));
}
-static void sinvert(short int *num)
+static void sinvert(short int *val)
{
- short int new = 0;
- int i, j;
-
- for (j = 0; j < 2; j++) {
- for (i = 0; i < 8; i++) {
- new |= ((*num >> (j * 8 + i)) & 1) << ((1 - j) * 8 + i);
- }
- }
-
- *num = new;
+ short tval = *val;
+ *val = (tval >> 8) |
+ (tval << 8);
}
static void Ichunk(AviChunk *chunk)
diff --git a/source/blender/avi/intern/endian.h b/source/blender/avi/intern/avi_endian.h
index 7ef49cb1699..8cea283a553 100644
--- a/source/blender/avi/intern/endian.h
+++ b/source/blender/avi/intern/avi_endian.h
@@ -25,17 +25,14 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/avi/intern/endian.h
+/** \file blender/avi/intern/avi_endian.h
* \ingroup avi
*
* This is external code.
*/
-#ifndef __ENDIAN_H__
-#define __ENDIAN_H__
-
-#include <stdio.h>
-#include "AVI_avi.h"
+#ifndef __AVI_ENDIAN_H__
+#define __AVI_ENDIAN_H__
#define AVI_RAW 0
#define AVI_CHUNK 1
@@ -48,5 +45,4 @@
void awrite(AviMovie *movie, void *datain, int block, int size, FILE *fp, int type);
-#endif
-
+#endif /* __AVI_ENDIAN_H__ */
diff --git a/source/blender/avi/intern/mjpeg.c b/source/blender/avi/intern/avi_mjpeg.c
index a700284bf68..396f1199cd9 100644
--- a/source/blender/avi/intern/mjpeg.c
+++ b/source/blender/avi/intern/avi_mjpeg.c
@@ -26,21 +26,23 @@
*
*/
-/** \file blender/avi/intern/mjpeg.c
+/** \file blender/avi/intern/avi_mjpeg.c
* \ingroup avi
*
* This is external code. Converts between avi and mpeg/jpeg.
*/
-
-#include "AVI_avi.h"
#include <stdlib.h>
#include <string.h>
+
+#include "AVI_avi.h"
+
+#include "MEM_guardedalloc.h"
+
#include "jpeglib.h"
#include "jerror.h"
-#include "MEM_guardedalloc.h"
-#include "mjpeg.h"
+#include "avi_mjpeg.h"
#define PADUP(num, amt) ((num + (amt - 1)) & ~(amt - 1))
@@ -71,7 +73,7 @@ static void std_huff_tables(j_decompress_ptr dinfo)
0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0
};
static const UINT8 val_dc_luminance[] =
- {
+ {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};
@@ -80,7 +82,7 @@ static void std_huff_tables(j_decompress_ptr dinfo)
0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
};
static const UINT8 val_dc_chrominance[] =
- {
+ {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};
@@ -89,7 +91,7 @@ static void std_huff_tables(j_decompress_ptr dinfo)
0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d
};
static const UINT8 val_ac_luminance[] =
- {
+ {
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
@@ -117,7 +119,7 @@ static void std_huff_tables(j_decompress_ptr dinfo)
0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77
};
static const UINT8 val_ac_chrominance[] =
- {
+ {
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
@@ -391,7 +393,7 @@ void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer,
numbytes = 0;
check_and_compress_jpeg(movie->streams[stream].sh.Quality / 100, buf + *size, buffer + (movie->header->Height / 2) * movie->header->Width * 3, movie->header->Width, movie->header->Height / 2, bufsize / 2);
}
- *size += numbytes;
+ *size += numbytes;
MEM_freeN(buffer);
return buf;
diff --git a/source/blender/avi/intern/mjpeg.h b/source/blender/avi/intern/avi_mjpeg.h
index 75649891f2b..6ae0e56ffa4 100644
--- a/source/blender/avi/intern/mjpeg.h
+++ b/source/blender/avi/intern/avi_mjpeg.h
@@ -25,11 +25,14 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/avi/intern/mjpeg.h
+/** \file blender/avi/intern/avi_mjpeg.h
* \ingroup avi
*/
+#ifndef __AVI_MJPEG_H__
+#define __AVI_MJPEG_H__
void *avi_converter_from_mjpeg (AviMovie *movie, int stream, unsigned char *buffer, int *size);
void *avi_converter_to_mjpeg (AviMovie *movie, int stream, unsigned char *buffer, int *size);
+#endif /* __AVI_MJPEG_H__ */
diff --git a/source/blender/avi/intern/options.c b/source/blender/avi/intern/avi_options.c
index 7de91318ecf..f7759a1099f 100644
--- a/source/blender/avi/intern/options.c
+++ b/source/blender/avi/intern/avi_options.c
@@ -26,7 +26,7 @@
*
*/
-/** \file blender/avi/intern/options.c
+/** \file blender/avi/intern/avi_options.c
* \ingroup avi
*
* This is external code. Sets some compression related options
@@ -35,7 +35,7 @@
#include "AVI_avi.h"
#include "avi_intern.h"
-#include "endian.h"
+#include "avi_endian.h"
#ifdef WIN32
# include "BLI_winstuff.h"
diff --git a/source/blender/avi/intern/avirgb.c b/source/blender/avi/intern/avi_rgb.c
index 7a95972845a..11d9bdf8612 100644
--- a/source/blender/avi/intern/avirgb.c
+++ b/source/blender/avi/intern/avi_rgb.c
@@ -26,19 +26,19 @@
*
*/
-/** \file blender/avi/intern/avirgb.c
+/** \file blender/avi/intern/avi_rgb.c
* \ingroup avi
*
* This is external code. Converts rgb-type avi-s.
*/
-
-#include "AVI_avi.h"
#include <stdlib.h>
#include <string.h>
#include "MEM_guardedalloc.h"
-#include "avirgb.h"
+
+#include "AVI_avi.h"
+#include "avi_rgb.h"
/* implementation */
@@ -86,7 +86,7 @@ void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buf
*(to++) = ((*pxl >> 10) & 0x1f) * 8;
*(to++) = ((*pxl >> 5) & 0x1f) * 8;
*(to++) = (*pxl & 0x1f) * 8;
- pxl++;
+ pxl++;
}
}
diff --git a/source/blender/avi/intern/avirgb.h b/source/blender/avi/intern/avi_rgb.h
index 20211d6ab2d..773166e9fab 100644
--- a/source/blender/avi/intern/avirgb.h
+++ b/source/blender/avi/intern/avi_rgb.h
@@ -25,11 +25,14 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/avi/intern/avirgb.h
+/** \file blender/avi/intern/avi_rgb.h
* \ingroup avi
*/
+#ifndef __AVI_RGB_H__
+#define __AVI_RGB_H__
-void *avi_converter_from_avi_rgb (AviMovie *movie, int stream, unsigned char *buffer, int *size);
-void *avi_converter_to_avi_rgb (AviMovie *movie, int stream, unsigned char *buffer, int *size);
+void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, int *size);
+void *avi_converter_to_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, int *size);
+#endif /* __AVI_RGB_H__ */
diff --git a/source/blender/avi/intern/rgb32.c b/source/blender/avi/intern/avi_rgb32.c
index 84630f09fe5..5c7a4889d97 100644
--- a/source/blender/avi/intern/rgb32.c
+++ b/source/blender/avi/intern/avi_rgb32.c
@@ -26,18 +26,19 @@
*
*/
-/** \file blender/avi/intern/rgb32.c
+/** \file blender/avi/intern/avi_rgb32.c
* \ingroup avi
*
* This is external code. Converts between rgb32 and avi.
*/
-
-#include "AVI_avi.h"
#include <stdlib.h>
#include <string.h>
+
#include "MEM_guardedalloc.h"
-#include "rgb32.h"
+
+#include "AVI_avi.h"
+#include "avi_rgb32.h"
void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffer, int *size)
{
diff --git a/source/blender/avi/intern/rgb32.h b/source/blender/avi/intern/avi_rgb32.h
index 55f9771a4df..523f9e795fd 100644
--- a/source/blender/avi/intern/rgb32.h
+++ b/source/blender/avi/intern/avi_rgb32.h
@@ -25,11 +25,14 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/avi/intern/rgb32.h
+/** \file blender/avi/intern/avi_rgb32.h
* \ingroup avi
*/
+#ifndef __AVI_RGB32_H__
+#define __AVI_RGB32_H__
-void *avi_converter_from_rgb32 (AviMovie *movie, int stream, unsigned char *buffer, int *size);
-void *avi_converter_to_rgb32 (AviMovie *movie, int stream, unsigned char *buffer, int *size);
+void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffer, int *size);
+void *avi_converter_to_rgb32(AviMovie *movie, int stream, unsigned char *buffer, int *size);
+#endif /* __AVI_RGB32_H__ */
diff --git a/source/blender/blenfont/BLF_api.h b/source/blender/blenfont/BLF_api.h
index ce10951d6ff..6f348ccc267 100644
--- a/source/blender/blenfont/BLF_api.h
+++ b/source/blender/blenfont/BLF_api.h
@@ -109,6 +109,7 @@ float BLF_fixed_width(int fontid);
* of the string, using the default font and both value
* are multiplied by the aspect of the font.
*/
+void BLF_width_and_height_default(const char *str, float *width, float *height);
float BLF_width_default(const char *str);
float BLF_height_default(const char *str);
diff --git a/source/blender/blenfont/BLF_translation.h b/source/blender/blenfont/BLF_translation.h
index 56eabf4bb43..b01ce93cb65 100644
--- a/source/blender/blenfont/BLF_translation.h
+++ b/source/blender/blenfont/BLF_translation.h
@@ -49,9 +49,13 @@ const char *BLF_pgettext(const char *context, const char *message);
/* Search the path directory to the locale files, this try all
* the case for Linux, Win and Mac.
+ * Also dynamically builds locales and locales' menu from "languages" text file.
*/
void BLF_lang_init(void);
+/* Free languages and locales_menu arrays created by BLF_lang_init. */
+void BLF_lang_free(void);
+
/* Set the current locale. */
void BLF_lang_set(const char *);
/* Get the current locale (short code, e.g. es_ES). */
@@ -60,6 +64,9 @@ const char *BLF_lang_get(void);
/* Set the current encoding name. */
void BLF_lang_encoding(const char *str);
+/* Get EnumPropertyItem's for translations menu. */
+struct EnumPropertyItem *BLF_RNA_lang_enum_properties(void);
+
/* translation */
int BLF_translate_iface(void);
int BLF_translate_tooltips(void);
@@ -97,6 +104,8 @@ const char *BLF_translate_do_tooltip(const char *contex, const char *msgid);
/* Default context for operator names/labels. */
#define BLF_I18NCONTEXT_OPERATOR_DEFAULT "Operator"
+/* Audio disambiguation context. */
+#define BLF_I18NCONTEXT_AUDIO "Audio"
#endif /* __BLF_TRANSLATION_H__ */
diff --git a/source/blender/blenfont/CMakeLists.txt b/source/blender/blenfont/CMakeLists.txt
index da60710a137..022dfd282b0 100644
--- a/source/blender/blenfont/CMakeLists.txt
+++ b/source/blender/blenfont/CMakeLists.txt
@@ -25,8 +25,10 @@ set(INC
.
../blenkernel
../blenlib
+ ../blenloader
../editors/include
../makesdna
+ ../makesrna
../imbuf
../../../intern/guardedalloc
)
diff --git a/source/blender/blenfont/SConscript b/source/blender/blenfont/SConscript
index d3c7b1c2fcc..075da58b116 100644
--- a/source/blender/blenfont/SConscript
+++ b/source/blender/blenfont/SConscript
@@ -4,7 +4,8 @@ Import ('env')
sources = env.Glob('intern/*.c')
-incs = '. intern #/intern/guardedalloc ../blenkernel ../blenlib ../makesdna ../imbuf ../editors/include'
+incs = '. intern #/intern/guardedalloc ../blenkernel ../blenlib ../blenloader'
+incs += ' ../makesdna ../makesrna ../imbuf ../editors/include'
incs += ' #/extern/glew/include'
incs += ' ' + env['BF_FREETYPE_INC']
incs += ' ' + env['BF_GETTEXT_INC']
diff --git a/source/blender/blenfont/intern/blf.c b/source/blender/blenfont/intern/blf.c
index 92fcb576e7d..f3cc92e7a27 100644
--- a/source/blender/blenfont/intern/blf.c
+++ b/source/blender/blenfont/intern/blf.c
@@ -69,7 +69,7 @@ static int global_font_dpi = 72;
int blf_mono_font = -1;
int blf_mono_font_render = -1;
-static FontBLF *BLF_get(int fontid)
+static FontBLF *blf_get(int fontid)
{
if (fontid >= 0 && fontid < BLF_MAX_FONT)
return global_font[fontid];
@@ -141,6 +141,21 @@ static int blf_search_available(void)
return -1;
}
+static int blf_global_font_init(void)
+{
+ if (global_font_default == -1) {
+ global_font_default = blf_search("default");
+ }
+
+ if (global_font_default == -1) {
+ printf("Warning: Can't find default font!\n");
+ return 0;
+ }
+ else {
+ return 1;
+ }
+}
+
int BLF_load(const char *name)
{
FontBLF *font;
@@ -219,7 +234,7 @@ int BLF_load_unique(const char *name)
void BLF_metrics_attach(int fontid, unsigned char *mem, int mem_size)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
blf_font_attach_from_mem(font, mem, mem_size);
@@ -311,7 +326,7 @@ void BLF_unload(const char *name)
void BLF_enable(int fontid, int option)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
font->flags |= option;
@@ -320,7 +335,7 @@ void BLF_enable(int fontid, int option)
void BLF_disable(int fontid, int option)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
font->flags &= ~option;
@@ -329,7 +344,7 @@ void BLF_disable(int fontid, int option)
void BLF_enable_default(int option)
{
- FontBLF *font = BLF_get(global_font_default);
+ FontBLF *font = blf_get(global_font_default);
if (font) {
font->flags |= option;
@@ -338,7 +353,7 @@ void BLF_enable_default(int option)
void BLF_disable_default(int option)
{
- FontBLF *font = BLF_get(global_font_default);
+ FontBLF *font = blf_get(global_font_default);
if (font) {
font->flags &= ~option;
@@ -347,7 +362,7 @@ void BLF_disable_default(int option)
void BLF_aspect(int fontid, float x, float y, float z)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
font->aspect[0] = x;
@@ -358,7 +373,7 @@ void BLF_aspect(int fontid, float x, float y, float z)
void BLF_matrix(int fontid, const double m[16])
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
memcpy(font->m, m, sizeof(font->m));
@@ -367,7 +382,7 @@ void BLF_matrix(int fontid, const double m[16])
void BLF_position(int fontid, float x, float y, float z)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
float xa, ya, za;
@@ -416,7 +431,7 @@ void BLF_position(int fontid, float x, float y, float z)
void BLF_size(int fontid, int size, int dpi)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
blf_font_size(font, size, dpi);
@@ -425,7 +440,7 @@ void BLF_size(int fontid, int size, int dpi)
void BLF_blur(int fontid, int size)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
font->blur = size;
@@ -437,13 +452,8 @@ void BLF_draw_default(float x, float y, float z, const char *str, size_t len)
if (!str)
return;
- if (global_font_default == -1)
- global_font_default = blf_search("default");
-
- if (global_font_default == -1) {
- printf("Warning: Can't found default font!!\n");
+ if (!blf_global_font_init())
return;
- }
BLF_size(global_font_default, global_font_points, global_font_dpi);
BLF_position(global_font_default, x, y, z);
@@ -456,13 +466,8 @@ void BLF_draw_default_ascii(float x, float y, float z, const char *str, size_t l
if (!str)
return;
- if (global_font_default == -1)
- global_font_default = blf_search("default");
-
- if (global_font_default == -1) {
- printf("Warning: Can't found default font!!\n");
+ if (!blf_global_font_init())
return;
- }
BLF_size(global_font_default, global_font_points, global_font_dpi);
BLF_position(global_font_default, x, y, z);
@@ -471,7 +476,7 @@ void BLF_draw_default_ascii(float x, float y, float z, const char *str, size_t l
void BLF_rotation_default(float angle)
{
- FontBLF *font = BLF_get(global_font_default);
+ FontBLF *font = blf_get(global_font_default);
if (font) {
font->angle = angle;
@@ -543,7 +548,7 @@ static void blf_draw__end(GLint mode, GLint param)
void BLF_draw(int fontid, const char *str, size_t len)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
GLint mode, param;
if (font && font->glyph_cache) {
@@ -555,7 +560,7 @@ void BLF_draw(int fontid, const char *str, size_t len)
void BLF_draw_ascii(int fontid, const char *str, size_t len)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
GLint mode, param;
if (font && font->glyph_cache) {
@@ -567,7 +572,7 @@ void BLF_draw_ascii(int fontid, const char *str, size_t len)
void BLF_boundbox(int fontid, const char *str, rctf *box)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
blf_font_boundbox(font, str, box);
@@ -576,16 +581,29 @@ void BLF_boundbox(int fontid, const char *str, rctf *box)
void BLF_width_and_height(int fontid, const char *str, float *width, float *height)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font && font->glyph_cache) {
blf_font_width_and_height(font, str, width, height);
}
+ else {
+ *width = *height = 0.0f;
+ }
+}
+
+void BLF_width_and_height_default(const char *str, float *width, float *height)
+{
+ if (!blf_global_font_init()) {
+ *width = *height = 0.0f;
+ return;
+ }
+
+ BLF_width_and_height(global_font_default, str, width, height);
}
float BLF_width(int fontid, const char *str)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font && font->glyph_cache) {
return blf_font_width(font, str);
@@ -596,7 +614,7 @@ float BLF_width(int fontid, const char *str)
float BLF_fixed_width(int fontid)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font && font->glyph_cache) {
return blf_font_fixed_width(font);
@@ -607,13 +625,8 @@ float BLF_fixed_width(int fontid)
float BLF_width_default(const char *str)
{
- if (global_font_default == -1)
- global_font_default = blf_search("default");
-
- if (global_font_default == -1) {
- printf("Error: Can't found default font!!\n");
+ if (!blf_global_font_init())
return 0.0f;
- }
BLF_size(global_font_default, global_font_points, global_font_dpi);
return BLF_width(global_font_default, str);
@@ -621,7 +634,7 @@ float BLF_width_default(const char *str)
float BLF_height(int fontid, const char *str)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font && font->glyph_cache) {
return blf_font_height(font, str);
@@ -632,7 +645,7 @@ float BLF_height(int fontid, const char *str)
float BLF_height_max(int fontid)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font && font->glyph_cache) {
return font->glyph_cache->max_glyph_height;
@@ -643,7 +656,7 @@ float BLF_height_max(int fontid)
float BLF_width_max(int fontid)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font && font->glyph_cache) {
return font->glyph_cache->max_glyph_width;
@@ -654,7 +667,7 @@ float BLF_width_max(int fontid)
float BLF_descender(int fontid)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font && font->glyph_cache) {
return font->glyph_cache->descender;
@@ -665,7 +678,7 @@ float BLF_descender(int fontid)
float BLF_ascender(int fontid)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font && font->glyph_cache) {
return font->glyph_cache->ascender;
@@ -676,13 +689,8 @@ float BLF_ascender(int fontid)
float BLF_height_default(const char *str)
{
- if (global_font_default == -1)
- global_font_default = blf_search("default");
-
- if (global_font_default == -1) {
- printf("Error: Can't found default font!!\n");
+ if (!blf_global_font_init())
return 0.0f;
- }
BLF_size(global_font_default, global_font_points, global_font_dpi);
@@ -691,7 +699,7 @@ float BLF_height_default(const char *str)
void BLF_rotation(int fontid, float angle)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
font->angle = angle;
@@ -700,7 +708,7 @@ void BLF_rotation(int fontid, float angle)
void BLF_clipping(int fontid, float xmin, float ymin, float xmax, float ymax)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
font->clip_rec.xmin = xmin;
@@ -712,7 +720,7 @@ void BLF_clipping(int fontid, float xmin, float ymin, float xmax, float ymax)
void BLF_clipping_default(float xmin, float ymin, float xmax, float ymax)
{
- FontBLF *font = BLF_get(global_font_default);
+ FontBLF *font = blf_get(global_font_default);
if (font) {
font->clip_rec.xmin = xmin;
@@ -724,7 +732,7 @@ void BLF_clipping_default(float xmin, float ymin, float xmax, float ymax)
void BLF_shadow(int fontid, int level, float r, float g, float b, float a)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
font->shadow = level;
@@ -737,7 +745,7 @@ void BLF_shadow(int fontid, int level, float r, float g, float b, float a)
void BLF_shadow_offset(int fontid, int x, int y)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
font->shadow_x = x;
@@ -747,7 +755,7 @@ void BLF_shadow_offset(int fontid, int x, int y)
void BLF_buffer(int fontid, float *fbuf, unsigned char *cbuf, int w, int h, int nch, struct ColorManagedDisplay *display)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
font->buf_info.fbuf = fbuf;
@@ -761,7 +769,7 @@ void BLF_buffer(int fontid, float *fbuf, unsigned char *cbuf, int w, int h, int
void BLF_buffer_col(int fontid, float r, float g, float b, float a)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font) {
font->buf_info.col[0] = r;
@@ -773,7 +781,7 @@ void BLF_buffer_col(int fontid, float r, float g, float b, float a)
void BLF_draw_buffer(int fontid, const char *str)
{
- FontBLF *font = BLF_get(fontid);
+ FontBLF *font = blf_get(fontid);
if (font && font->glyph_cache && (font->buf_info.fbuf || font->buf_info.cbuf)) {
blf_font_buffer(font, str);
diff --git a/source/blender/blenfont/intern/blf_font.c b/source/blender/blenfont/intern/blf_font.c
index 02b66993c0a..1900efa2dbc 100644
--- a/source/blender/blenfont/intern/blf_font.c
+++ b/source/blender/blenfont/intern/blf_font.c
@@ -174,7 +174,7 @@ void blf_font_draw(FontBLF *font, const char *str, size_t len)
blf_font_ensure_ascii_table(font);
- while (str[i] && i < len) {
+ while ((i < len) && str[i]) {
BLF_UTF8_NEXT_FAST(font, g, str, i, c, glyph_ascii_table);
if (c == BLI_UTF8_ERR)
@@ -430,8 +430,8 @@ void blf_font_width_and_height(FontBLF *font, const char *str, float *width, flo
}
blf_font_boundbox(font, str, &box);
- *width = (BLI_RCT_SIZE_X(&box) * xa);
- *height = (BLI_RCT_SIZE_Y(&box) * ya);
+ *width = (BLI_rctf_size_x(&box) * xa);
+ *height = (BLI_rctf_size_y(&box) * ya);
}
float blf_font_width(FontBLF *font, const char *str)
@@ -445,7 +445,7 @@ float blf_font_width(FontBLF *font, const char *str)
xa = 1.0f;
blf_font_boundbox(font, str, &box);
- return BLI_RCT_SIZE_X(&box) * xa;
+ return BLI_rctf_size_x(&box) * xa;
}
float blf_font_height(FontBLF *font, const char *str)
@@ -459,7 +459,7 @@ float blf_font_height(FontBLF *font, const char *str)
ya = 1.0f;
blf_font_boundbox(font, str, &box);
- return BLI_RCT_SIZE_Y(&box) * ya;
+ return BLI_rctf_size_y(&box) * ya;
}
float blf_font_fixed_width(FontBLF *font)
diff --git a/source/blender/blenfont/intern/blf_glyph.c b/source/blender/blenfont/intern/blf_glyph.c
index 63225651e5b..91ecded88be 100644
--- a/source/blender/blenfont/intern/blf_glyph.c
+++ b/source/blender/blenfont/intern/blf_glyph.c
@@ -415,7 +415,7 @@ int blf_glyph_render(FontBLF *font, GlyphBLF *g, float x, float y)
g->uv[1][1] = ((float)(g->yoff + g->height)) / ((float)gc->p2_height);
/* update the x offset for the next glyph. */
- gc->x_offs += (int)(BLI_RCT_SIZE_X(&g->box) + gc->pad);
+ gc->x_offs += (int)(BLI_rctf_size_x(&g->box) + gc->pad);
gc->rem_glyphs--;
g->build_tex = 1;
diff --git a/source/blender/blenfont/intern/blf_lang.c b/source/blender/blenfont/intern/blf_lang.c
index d0b77222114..501f8cd2958 100644
--- a/source/blender/blenfont/intern/blf_lang.c
+++ b/source/blender/blenfont/intern/blf_lang.c
@@ -35,100 +35,196 @@
#include "BKE_global.h"
#include "BLF_api.h"
-
#include "BLF_translation.h" /* own include */
#ifdef WITH_INTERNATIONAL
#include <locale.h>
-#if defined(_WIN32)
-#include <windows.h>
-#endif
-
#include "libintl.h"
#include "DNA_userdef_types.h"
-#include "DNA_listBase.h"
-#include "DNA_vec_types.h"
+#include "RNA_types.h"
#include "MEM_guardedalloc.h"
-#include "BLI_linklist.h" /* linknode */
#include "BLI_string.h"
#include "BLI_utildefines.h"
#include "BLI_path_util.h"
+#include "BLI_fileops.h"
+#include "BLI_linklist.h"
+#include "BLI_string.h"
#define SYSTEM_ENCODING_DEFAULT "UTF-8"
#define FONT_SIZE_DEFAULT 12
-/* locale options. */
+/* Locale options. */
static char global_messagepath[1024];
static char global_language[32];
static char global_encoding_name[32];
-/* map from the rna_userdef.c:rna_def_userdef_system(BlenderRNA *brna):language_items */
-static const char *locales[] = {
- "", "",
- "english", "en_US",
- "japanese", "ja_JP",
- "dutch", "nl_NL",
- "italian", "it_IT",
- "german", "de_DE",
- "finnish", "fi_FI",
- "swedish", "sv_SE",
- "french", "fr_FR",
- "spanish", "es",
- "catalan", "ca_AD",
- "czech", "cs_CZ",
- "portuguese", "pt_PT",
-#if defined(_WIN32) && !defined(FREE_WINDOWS)
- "Chinese (Simplified)_China.1252", "zh_CN",
- "Chinese (Traditional)_China.1252", "zh_TW",
-#else
- "chs", "zh_CN",
- "cht", "zh_TW",
-#endif
- "russian", "ru_RU",
- "croatian", "hr_HR",
- "serbian", "sr_RS",
- "ukrainian", "uk_UA",
- "polish", "pl_PL",
- "romanian", "ro_RO",
- "arabic", "ar_EG",
- "bulgarian", "bg_BG",
- "greek", "el_GR",
- "korean", "ko_KR",
- "nepali", "ne_NP",
- "persian", "fa_IR",
- "indonesian", "id_ID",
- "serbian (latin)", "sr_RS@latin",
- "kyrgyz", "ky_KG",
- "turkish", "tr_TR",
- "hungarian", "hu_HU",
- "brazilian portuguese", "pt_BR",
- "hebrew", "he_IL",
-};
+static const char **locales = NULL;
+static char **long_locales = NULL; /* XXX Temp fix until we get a final solution with modern intl lib under windows! */
+static int num_locales = 0;
+static EnumPropertyItem *locales_menu = NULL;
+static int num_locales_menu = 0;
+
+#define ULANGUAGE ((U.language >= 0 && U.language < num_locales) ? U.language : 0)
+#define LOCALE(_id) (locales ? locales[_id] : "")
+#define LONG_LOCALE(_id) (long_locales ? long_locales[_id] : "")
+
+static void free_locales(void)
+{
+ if (locales) {
+ int idx = num_locales_menu - 1; /* Last item does not need to be freed! */
+ while (idx--) {
+ MEM_freeN((void*)locales_menu[idx].identifier);
+ MEM_freeN((void*)locales_menu[idx].name);
+ MEM_freeN((void*)locales_menu[idx].description); /* Also frees locales's relevant value! */
+ }
+
+ idx = num_locales;
+ while (idx--) {
+ if (long_locales[idx]) {
+ MEM_freeN(long_locales[idx]);
+ }
+ }
+
+ MEM_freeN(locales);
+ locales = NULL;
+ MEM_freeN(long_locales);
+ long_locales = NULL;
+ }
+ if (locales_menu) {
+ MEM_freeN(locales_menu);
+ locales_menu = NULL;
+ }
+ num_locales = num_locales_menu = 0;
+}
+
+static void fill_locales(void)
+{
+ char *languages_path = BLI_get_folder(BLENDER_DATAFILES, "locale");
+ LinkNode *lines = NULL, *line;
+ char *str;
+ int idx = 0;
+
+ free_locales();
+
+ BLI_join_dirfile(languages_path, FILE_MAX, languages_path, "languages");
+ line = lines = BLI_file_read_as_lines(languages_path);
+
+ /* This whole "parsing" code is a bit weak, in that it expects strictly formated input file...
+ * Should not be a problem, though, as this file is script-generated! */
+
+ /* First loop to find highest locale ID */
+ while (line) {
+ int t;
+ str = (char*) line->link;
+ if (str[0] == '#' || str[0] == '\0') {
+ line = line->next;
+ continue; /* Comment or void... */
+ }
+ t = atoi(str);
+ if (t >= num_locales)
+ num_locales = t + 1;
+ num_locales_menu++;
+ line = line->next;
+ }
+ num_locales_menu++; /* The "closing" void item... */
+
+ /* And now, buil locales and locale_menu! */
+ locales_menu = MEM_callocN(num_locales_menu * sizeof(EnumPropertyItem), __func__);
+ line = lines;
+ /* Do not allocate locales with zero-sized mem, as LOCALE macro uses NULL locales as invalid marker! */
+ if (num_locales > 0) {
+ locales = MEM_callocN(num_locales * sizeof(char*), __func__);
+ long_locales = MEM_callocN(num_locales * sizeof(char*), __func__);
+ while (line) {
+ int id;
+ char *loc, *sep1, *sep2, *sep3;
+
+ str = (char*) line->link;
+ if (str[0] == '#' || str[0] == '\0') {
+ line = line->next;
+ continue;
+ }
+
+ id = atoi(str);
+ sep1 = strchr(str, ':');
+ if (sep1) {
+ sep1++;
+ sep2 = strchr(sep1, ':');
+ if (sep2) {
+ locales_menu[idx].value = id;
+ locales_menu[idx].icon = 0;
+ locales_menu[idx].name = BLI_strdupn(sep1, sep2 - sep1);
+
+ sep2++;
+ sep3 = strchr(sep2, ':');
+ if (sep3) {
+ locales_menu[idx].identifier = loc = BLI_strdupn(sep2, sep3 - sep2);
+
+ if (id == 0) {
+ /* The DEFAULT item... */
+ if (BLI_strnlen(loc, 2)) {
+ locales[id] = locales_menu[idx].description = BLI_strdup("");
+ long_locales[id] = BLI_strdup("");
+ }
+ /* Menu "label", not to be stored in locales! */
+ else {
+ locales_menu[idx].description = BLI_strdup("");
+ }
+ }
+ else {
+ locales[id] = locales_menu[idx].description = BLI_strdup(loc);
+ long_locales[id] = BLI_strdup(sep3 + 1);
+ }
+ idx++;
+ }
+ }
+ }
+
+ line = line->next;
+ }
+ }
+
+ /* Add closing item to menu! */
+ locales_menu[idx].identifier = NULL;
+ locales_menu[idx].value = locales_menu[idx].icon = 0;
+ locales_menu[idx].name = locales_menu[idx].description = "";
+
+ BLI_file_free_lines(lines);
+}
+
+EnumPropertyItem *BLF_RNA_lang_enum_properties(void)
+{
+ return locales_menu;
+}
void BLF_lang_init(void)
{
char *messagepath = BLI_get_folder(BLENDER_DATAFILES, "locale");
-/* printf("%s\n", messagepath);*/
BLI_strncpy(global_encoding_name, SYSTEM_ENCODING_DEFAULT, sizeof(global_encoding_name));
-
+
if (messagepath) {
BLI_strncpy(global_messagepath, messagepath, sizeof(global_messagepath));
+ fill_locales();
}
else {
printf("%s: 'locale' data path for translations not found, continuing\n", __func__);
global_messagepath[0] = '\0';
}
-
}
-/* get LANG/LANGUAGE environment variable */
+void BLF_lang_free(void)
+{
+ free_locales();
+}
+
+/* Get LANG/LANGUAGE environment variable. */
static void get_language_variable(const char *varname, char *var, const size_t maxlen)
{
char *env = getenv(varname);
@@ -136,18 +232,18 @@ static void get_language_variable(const char *varname, char *var, const size_t m
if (env) {
char *s;
- /* store defaul locale */
+ /* Store defaul locale. */
BLI_strncpy(var, env, maxlen);
- /* use first language as default */
+ /* Use first language as default. */
s = strchr(var, ':');
if (s)
s[0] = 0;
}
}
-/* get language to be used based on locale(which might be empty when using default language) and
- * LANG environment variable
+/* Get language to be used based on locale (which might be empty when using default language) and
+ * LANG environment variable.
*/
static void get_language(const char *locale, const char *lang, char *language, const size_t maxlen)
{
@@ -165,45 +261,43 @@ static void get_language(const char *locale, const char *lang, char *language, c
}
}
-/* XXX WARNING!!! IN osx somehow the previous function call jumps in this one??? (ton, ppc) */
+/* XXX WARNING!!! In osx somehow the previous function call jumps in this one??? (ton, ppc) */
void BLF_lang_set(const char *str)
{
char *locreturn;
- const char *short_locale;
- int ok = 1;
- const char *long_locale = locales[2 * U.language];
+ int ok = TRUE;
+ int ulang = ULANGUAGE;
if ((U.transopts & USER_DOTRANSLATE) == 0)
return;
- if (str)
- short_locale = str;
- else
- short_locale = locales[2 * U.language + 1];
-
#if defined(_WIN32) && !defined(FREE_WINDOWS)
- if (short_locale) {
- char *envStr;
+ {
+ const char *long_locale = str ? str : LONG_LOCALE(ulang);
+ if (long_locale) {
+ char *envStr;
- if (U.language == 0) /* use system setting */
- envStr = BLI_sprintfN("LANG=%s", getenv("LANG"));
- else
- envStr = BLI_sprintfN("LANG=%s", short_locale);
+ if (ulang)
+ envStr = BLI_sprintfN("LANG=%s", long_locale);
+ else /* Use system setting. */
+ envStr = BLI_sprintfN("LANG=%s", getenv("LANG"));
- gettext_putenv(envStr);
- MEM_freeN(envStr);
- }
+ gettext_putenv(envStr);
+ MEM_freeN(envStr);
+ }
- locreturn = setlocale(LC_ALL, long_locale);
+ locreturn = setlocale(LC_ALL, long_locale);
- if (locreturn == NULL) {
- if (G.debug & G_DEBUG)
- printf("Could not change locale to %s\n", long_locale);
+ if (locreturn == NULL) {
+ if (G.debug & G_DEBUG)
+ printf("Could not change locale to %s\n", long_locale);
- ok = 0;
+ ok = FALSE;
+ }
}
#else
{
+ const char *short_locale = str ? str : LOCALE(ulang);
static char default_lang[64] = "\0";
static char default_language[64] = "\0";
@@ -214,11 +308,33 @@ void BLF_lang_set(const char *str)
get_language_variable("LANGUAGE", default_language, sizeof(default_language));
if (short_locale[0]) {
+ char *short_locale_utf8 = BLI_sprintfN("%s.UTF-8", short_locale);
+
if (G.debug & G_DEBUG)
- printf("Setting LANG= and LANGUAGE to %s\n", short_locale);
+ printf("Setting LANG and LANGUAGE to %s\n", short_locale_utf8);
+
+ locreturn = setlocale(LC_ALL, short_locale_utf8);
+
+ if (locreturn != NULL) {
+ BLI_setenv("LANG", short_locale_utf8);
+ BLI_setenv("LANGUAGE", short_locale_utf8);
+ }
+ else {
+ if (G.debug & G_DEBUG)
+ printf("Setting LANG and LANGUAGE to %s\n", short_locale);
+
+ locreturn = setlocale(LC_ALL, short_locale);
+
+ if (locreturn != NULL) {
+ BLI_setenv("LANG", short_locale);
+ BLI_setenv("LANGUAGE", short_locale);
+ }
+ }
- BLI_setenv("LANG", short_locale);
- BLI_setenv("LANGUAGE", short_locale);
+ if (G.debug & G_DEBUG && locreturn == NULL)
+ printf("Could not change locale to %s nor %s\n", short_locale, short_locale_utf8);
+
+ MEM_freeN(short_locale_utf8);
}
else {
if (G.debug & G_DEBUG)
@@ -226,43 +342,27 @@ void BLF_lang_set(const char *str)
BLI_setenv("LANG", default_lang);
BLI_setenv("LANGUAGE", default_language);
- }
+ locreturn = setlocale(LC_ALL, "");
- locreturn = setlocale(LC_ALL, short_locale);
+ if (G.debug & G_DEBUG && locreturn == NULL)
+ printf("Could not reset locale\n");
+ }
if (locreturn == NULL) {
- char *short_locale_utf8 = NULL;
-
- if (short_locale[0]) {
- short_locale_utf8 = BLI_sprintfN("%s.UTF-8", short_locale);
- locreturn = setlocale(LC_ALL, short_locale_utf8);
- }
+ char language[65];
- if (locreturn == NULL) {
- char language[65];
-
- get_language(long_locale, default_lang, language, sizeof(language));
-
- if (G.debug & G_DEBUG) {
- if (short_locale[0])
- printf("Could not change locale to %s nor %s\n", short_locale, short_locale_utf8);
- else
- printf("Could not reset locale\n");
-
- printf("Fallback to LANG=%s and LANGUAGE=%s\n", default_lang, language);
- }
+ get_language(short_locale, default_lang, language, sizeof(language));
- /* fallback to default settings */
- BLI_setenv("LANG", default_lang);
- BLI_setenv("LANGUAGE", language);
+ if (G.debug & G_DEBUG)
+ printf("Fallback to LANG=%s and LANGUAGE=%s\n", default_lang, language);
- locreturn = setlocale(LC_ALL, "");
+ /* Fallback to default settings. */
+ BLI_setenv("LANG", default_lang);
+ BLI_setenv("LANGUAGE", language);
- ok = 0;
- }
+ locreturn = setlocale(LC_ALL, "");
- if (short_locale_utf8)
- MEM_freeN(short_locale_utf8);
+ ok = FALSE;
}
}
#endif
@@ -281,7 +381,8 @@ void BLF_lang_set(const char *str)
const char *BLF_lang_get(void)
{
- return locales[2 * U.language + 1];
+ int uilang = ULANGUAGE;
+ return LOCALE(uilang);
}
void BLF_lang_encoding(const char *str)
@@ -290,6 +391,9 @@ void BLF_lang_encoding(const char *str)
/* bind_textdomain_codeset(TEXT_DOMAIN_NAME, encoding_name); */
}
+#undef LOCALE
+#undef ULANGUAGE
+
#else /* ! WITH_INTERNATIONAL */
void BLF_lang_init(void)
@@ -297,6 +401,11 @@ void BLF_lang_init(void)
return;
}
+void BLF_lang_free(void)
+{
+ return;
+}
+
void BLF_lang_encoding(const char *str)
{
(void)str;
diff --git a/source/blender/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h
index fa9223ba6e2..c6c54cc6e8a 100644
--- a/source/blender/blenkernel/BKE_DerivedMesh.h
+++ b/source/blender/blenkernel/BKE_DerivedMesh.h
@@ -148,6 +148,11 @@ typedef enum DMDrawFlag {
typedef enum DMDirtyFlag {
/* dm has valid tessellated faces, but tessellated CDDATA need to be updated. */
DM_DIRTY_TESS_CDLAYERS = 1 << 0,
+ /* One of the MCOL layers have been updated, force updating of GPUDrawObject's colors buffer.
+ * This is necessary with modern, VBO draw code, as e.g. in vpaint mode me->mcol may be updated
+ * without actually rebuilding dm (hence by defautl keeping same GPUDrawObject, and same colors
+ * buffer, which prevents update during a stroke!). */
+ DM_DIRTY_MCOL_UPDATE_DRAW = 1 << 1,
} DMDirtyFlag;
typedef struct DerivedMesh DerivedMesh;
@@ -223,6 +228,7 @@ struct DerivedMesh {
void *(*getVertData)(DerivedMesh * dm, int index, int type);
void *(*getEdgeData)(DerivedMesh * dm, int index, int type);
void *(*getTessFaceData)(DerivedMesh * dm, int index, int type);
+ void *(*getPolyData)(DerivedMesh * dm, int index, int type);
/** Return a pointer to the entire array of vert/edge/face custom data
* from the derived mesh (this gives a pointer to the actual data, not
@@ -231,7 +237,8 @@ struct DerivedMesh {
void *(*getVertDataArray)(DerivedMesh * dm, int type);
void *(*getEdgeDataArray)(DerivedMesh * dm, int type);
void *(*getTessFaceDataArray)(DerivedMesh * dm, int type);
-
+ void *(*getPolyDataArray)(DerivedMesh * dm, int type);
+
/** Retrieves the base CustomData structures for
* verts/edges/tessfaces/loops/facdes*/
CustomData *(*getVertDataLayout)(DerivedMesh * dm);
@@ -493,6 +500,7 @@ void DM_add_poly_layer(struct DerivedMesh *dm, int type, int alloctype,
void *DM_get_vert_data(struct DerivedMesh *dm, int index, int type);
void *DM_get_edge_data(struct DerivedMesh *dm, int index, int type);
void *DM_get_tessface_data(struct DerivedMesh *dm, int index, int type);
+void *DM_get_poly_data(struct DerivedMesh *dm, int index, int type);
/* custom data layer access functions
* return pointer to first data layer which matches type (a flat array)
@@ -701,4 +709,10 @@ void DM_debug_print(DerivedMesh *dm);
void DM_debug_print_cdlayers(CustomData *cdata);
#endif
+BLI_INLINE int DM_origindex_mface_mpoly(const int *index_mf_to_mpoly, const int *index_mp_to_orig, const int i)
+{
+ const int j = index_mf_to_mpoly[i];
+ return (j != ORIGINDEX_NONE) ? index_mp_to_orig[j] : ORIGINDEX_NONE;
+}
+
#endif
diff --git a/source/blender/blenkernel/BKE_action.h b/source/blender/blenkernel/BKE_action.h
index 7df491c0fef..2d7030b2d42 100644
--- a/source/blender/blenkernel/BKE_action.h
+++ b/source/blender/blenkernel/BKE_action.h
@@ -203,7 +203,7 @@ void BKE_pose_ikparam_init(struct bPose *pose);
void BKE_pose_itasc_init(struct bItasc *itasc);
/* clears BONE_UNKEYED flags for frame changing */
-// XXX to be depreceated for a more general solution in animsys...
+// XXX to be deprecated for a more general solution in animsys...
void framechange_poses_clear_unkeyed(void);
/* Bone Groups API --------------------- */
diff --git a/source/blender/blenkernel/BKE_anim.h b/source/blender/blenkernel/BKE_anim.h
index f506c67a36c..11537964e32 100644
--- a/source/blender/blenkernel/BKE_anim.h
+++ b/source/blender/blenkernel/BKE_anim.h
@@ -65,8 +65,8 @@ int where_on_path(struct Object *ob, float ctime, float vec[4], float dir[3], fl
/* ---------------------------------------------------- */
/* Dupli-Geometry */
-struct ListBase *object_duplilist_ex(struct Scene *sce, struct Object *ob, int update);
-struct ListBase *object_duplilist(struct Scene *sce, struct Object *ob);
+struct ListBase *object_duplilist_ex(struct Scene *sce, struct Object *ob, int update, int for_render);
+struct ListBase *object_duplilist(struct Scene *sce, struct Object *ob, int for_render);
void free_object_duplilist(struct ListBase *lb);
int count_duplilist(struct Object *ob);
diff --git a/source/blender/blenkernel/BKE_armature.h b/source/blender/blenkernel/BKE_armature.h
index d750e88ac04..b0f372e0bac 100644
--- a/source/blender/blenkernel/BKE_armature.h
+++ b/source/blender/blenkernel/BKE_armature.h
@@ -99,7 +99,7 @@ void BKE_pose_where_is_bone_tail(struct bPoseChannel *pchan);
/* get_objectspace_bone_matrix has to be removed still */
void get_objectspace_bone_matrix(struct Bone *bone, float M_accumulatedMatrix[][4], int root, int posed);
void vec_roll_to_mat3(const float vec[3], const float roll, float mat[][3]);
-void mat3_to_vec_roll(float mat[][3], float *vec, float *roll);
+void mat3_to_vec_roll(float mat[][3], float r_vec[3], float *r_roll);
/* Common Conversions Between Co-ordinate Spaces */
void BKE_armature_mat_world_to_pose(struct Object *ob, float inmat[][4], float outmat[][4]);
@@ -131,7 +131,14 @@ typedef struct Mat4 {
Mat4 *b_bone_spline_setup(struct bPoseChannel *pchan, int rest);
/* like EBONE_VISIBLE */
-#define PBONE_VISIBLE(arm, bone) (((bone)->layer & (arm)->layer) && !((bone)->flag & BONE_HIDDEN_P))
+#define PBONE_VISIBLE(arm, bone) ( \
+ CHECK_TYPE_INLINE(arm, bArmature), \
+ CHECK_TYPE_INLINE(bone, Bone), \
+ (((bone)->layer & (arm)->layer) && !((bone)->flag & BONE_HIDDEN_P)) \
+ )
+
+#define PBONE_SELECTABLE(arm, bone) \
+ (PBONE_VISIBLE(arm, bone) && !((bone)->flag & BONE_UNSELECTABLE))
#ifdef __cplusplus
}
diff --git a/source/blender/blenkernel/BKE_blender.h b/source/blender/blenkernel/BKE_blender.h
index 1e67027ae8c..87e87904fe7 100644
--- a/source/blender/blenkernel/BKE_blender.h
+++ b/source/blender/blenkernel/BKE_blender.h
@@ -41,19 +41,18 @@ extern "C" {
/* these lines are grep'd, watch out for our not-so-awesome regex
* and keep comment above the defines.
* Use STRINGIFY() rather than defining with quotes */
-#define BLENDER_VERSION 263
-#define BLENDER_SUBVERSION 18
+#define BLENDER_VERSION 264
+#define BLENDER_SUBVERSION 7
-/* 262 was the last editmesh release but its has compatibility code for bmesh data,
- * so set the minversion to 2.61 */
-#define BLENDER_MINVERSION 261
+/* 262 was the last editmesh release but it has compatibility code for bmesh data */
+#define BLENDER_MINVERSION 262
#define BLENDER_MINSUBVERSION 0
/* used by packaging tools */
/* can be left blank, otherwise a,b,c... etc with no quotes */
#define BLENDER_VERSION_CHAR a
/* alpha/beta/rc/release, docs use this */
-#define BLENDER_VERSION_CYCLE beta
+#define BLENDER_VERSION_CYCLE alpha
extern char versionstr[]; /* from blender.c */
diff --git a/source/blender/blenkernel/BKE_bmesh.h b/source/blender/blenkernel/BKE_bmesh.h
index 67b21eb764c..8bfee836c0d 100644
--- a/source/blender/blenkernel/BKE_bmesh.h
+++ b/source/blender/blenkernel/BKE_bmesh.h
@@ -99,7 +99,7 @@ typedef struct BME_Glob { /* stored in Global G for Transform() purposes */
struct BME_TransData *BME_get_transdata(struct BME_TransData_Head *td, struct BMVert *v);
void BME_free_transdata(struct BME_TransData_Head *td);
-struct BMesh *BME_bevel(struct BMEditMesh *em, float value, int res, int options, int defgrp_index, float angle,
- BME_TransData_Head **rtd, int do_tessface);
+struct BMesh *BME_bevel(struct BMesh *bm, float value, int res, int options, int defgrp_index, float angle,
+ BME_TransData_Head **rtd);
#endif
diff --git a/source/blender/blenkernel/BKE_cdderivedmesh.h b/source/blender/blenkernel/BKE_cdderivedmesh.h
index d7882d8e7ec..2b2497f3f50 100644
--- a/source/blender/blenkernel/BKE_cdderivedmesh.h
+++ b/source/blender/blenkernel/BKE_cdderivedmesh.h
@@ -55,8 +55,10 @@ int CDDM_Check(struct DerivedMesh *dm);
* data to not overwrite the original */
struct DerivedMesh *CDDM_from_mesh(struct Mesh *mesh, struct Object *ob);
+struct DerivedMesh *CDDM_from_bmesh(struct BMesh *bm, int use_mdisps);
+
/* creates a CDDerivedMesh from the given BMEditMesh */
-DerivedMesh *CDDM_from_BMEditMesh(struct BMEditMesh *em, struct Mesh *me, int use_mdisps, int use_tessface);
+DerivedMesh *CDDM_from_editbmesh(struct BMEditMesh *em, int use_mdisps, int use_tessface);
/* merge verts */
DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap);
diff --git a/source/blender/blenkernel/BKE_colortools.h b/source/blender/blenkernel/BKE_colortools.h
index cd67059ea8c..96e05aa87b9 100644
--- a/source/blender/blenkernel/BKE_colortools.h
+++ b/source/blender/blenkernel/BKE_colortools.h
@@ -61,10 +61,10 @@ void curvemapping_set_black_white(struct CurveMapping *cumap, con
#define CURVEMAP_SLOPE_NEGATIVE 0
#define CURVEMAP_SLOPE_POSITIVE 1
-void curvemap_reset(struct CurveMap *cuma, struct rctf *clipr, int preset, int slope);
+void curvemap_reset(struct CurveMap *cuma, const struct rctf *clipr, int preset, int slope);
void curvemap_remove(struct CurveMap *cuma, const short flag);
-void curvemap_remove_point(struct CurveMap *cuma, struct CurveMapPoint *cmp);
-struct CurveMapPoint *curvemap_insert(struct CurveMap *cuma, float x, float y);
+int curvemap_remove_point(struct CurveMap *cuma, struct CurveMapPoint *cmp);
+struct CurveMapPoint *curvemap_insert(struct CurveMap *cuma, float x, float y);
void curvemap_sethandle(struct CurveMap *cuma, int type);
void curvemapping_changed(struct CurveMapping *cumap, int rem_doubles);
@@ -88,7 +88,6 @@ int curvemapping_RGBA_does_something(const struct CurveMapping *
void curvemapping_table_RGBA(const struct CurveMapping *cumap, float **array, int *size);
/* non-const, these modify the curve */
-void curvemapping_do_ibuf(struct CurveMapping *cumap, struct ImBuf *ibuf);
void curvemapping_premultiply(struct CurveMapping *cumap, int restore);
diff --git a/source/blender/blenkernel/BKE_curve.h b/source/blender/blenkernel/BKE_curve.h
index a845ac10c9d..536bbecb79b 100644
--- a/source/blender/blenkernel/BKE_curve.h
+++ b/source/blender/blenkernel/BKE_curve.h
@@ -93,6 +93,8 @@ void BKE_curve_forward_diff_bezier(float q0, float q1, float q2, float q3, float
/* ** Nurbs ** */
+int BKE_nurbList_index_get_co(struct ListBase *editnurb, const int index, float r_co[3]);
+
int BKE_nurbList_verts_count(struct ListBase *nurb);
int BKE_nurbList_verts_count_without_handles(struct ListBase *nurb);
@@ -106,7 +108,7 @@ void BKE_nurb_free(struct Nurb *nu);
struct Nurb *BKE_nurb_duplicate(struct Nurb *nu);
void BKE_nurb_test2D(struct Nurb *nu);
-void BKE_nurb_minmax(struct Nurb *nu, float *min, float *max);
+void BKE_nurb_minmax(struct Nurb *nu, float min[3], float max[3]);
void BKE_nurb_makeFaces(struct Nurb *nu, float *coord_array, int rowstride, int resolu, int resolv);
void BKE_nurb_makeCurve(struct Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, float *weight_array, int resolu, int stride);
diff --git a/source/blender/blenkernel/BKE_customdata.h b/source/blender/blenkernel/BKE_customdata.h
index 33361b9921c..4736e7b7312 100644
--- a/source/blender/blenkernel/BKE_customdata.h
+++ b/source/blender/blenkernel/BKE_customdata.h
@@ -80,6 +80,13 @@ void customData_mask_layers__print(CustomDataMask mask);
* the below operations.
*/
int CustomData_layer_has_math(struct CustomData *data, int layer_n);
+int CustomData_layer_has_interp(struct CustomData *data, int layer_n);
+
+/**
+ * Checks if any of the customdata layers has math.
+ */
+int CustomData_has_math(struct CustomData *data);
+int CustomData_has_interp(struct CustomData *data);
/* copies the "value" (e.g. mloopuv uv or mloopcol colors) from one block to
* another, while not overwriting anything else (e.g. flags). probably only
@@ -115,7 +122,10 @@ void CustomData_merge(const struct CustomData *source, struct CustomData *dest,
void CustomData_bmesh_merge(struct CustomData *source, struct CustomData *dest,
CustomDataMask mask, int alloctype, struct BMesh *bm, const char htype);
-/* frees data associated with a CustomData object (doesn't free the object
+/** NULL's all members and resets the typemap. */
+void CustomData_reset(struct CustomData *data);
+
+/** frees data associated with a CustomData object (doesn't free the object
* itself, though)
*/
void CustomData_free(struct CustomData *data, int totelem);
@@ -205,8 +215,8 @@ void CustomData_free_elem(struct CustomData *data, int index, int count);
void CustomData_interp(const struct CustomData *source, struct CustomData *dest,
int *src_indices, float *weights, float *sub_weights,
int count, int dest_index);
-void CustomData_bmesh_interp(struct CustomData *data, void **src_blocks,
- float *weights, float *sub_weights, int count,
+void CustomData_bmesh_interp(struct CustomData *data, void **src_blocks,
+ const float *weights, const float *sub_weights, int count,
void *dest_block);
diff --git a/source/blender/blenkernel/BKE_deform.h b/source/blender/blenkernel/BKE_deform.h
index 52a143ddf55..8306da71432 100644
--- a/source/blender/blenkernel/BKE_deform.h
+++ b/source/blender/blenkernel/BKE_deform.h
@@ -54,6 +54,7 @@ struct MDeformWeight *defvert_verify_index(struct MDeformVert *dv, const int
void defvert_add_index_notest(struct MDeformVert *dv, int defgroup, const float weight);
void defvert_remove_group(struct MDeformVert *dvert, struct MDeformWeight *dw);
void defvert_clear(struct MDeformVert *dvert);
+int defvert_find_shared(const struct MDeformVert *dvert_a, const struct MDeformVert *dvert_b);
float defvert_find_weight(const struct MDeformVert *dvert, const int defgroup);
float defvert_array_find_weight_safe(const struct MDeformVert *dvert, const int index, const int defgroup);
diff --git a/source/blender/blenkernel/BKE_global.h b/source/blender/blenkernel/BKE_global.h
index 2656495a918..f7af534c2c2 100644
--- a/source/blender/blenkernel/BKE_global.h
+++ b/source/blender/blenkernel/BKE_global.h
@@ -130,8 +130,9 @@ enum {
G_DEBUG_FFMPEG = (1 << 1),
G_DEBUG_PYTHON = (1 << 2), /* extra python info */
G_DEBUG_EVENTS = (1 << 3), /* input/window/screen events */
- G_DEBUG_WM = (1 << 4), /* operator, undo */
- G_DEBUG_JOBS = (1 << 5) /* jobs time profiling */
+ G_DEBUG_HANDLERS = (1 << 4), /* events handling */
+ G_DEBUG_WM = (1 << 5), /* operator, undo */
+ G_DEBUG_JOBS = (1 << 6) /* jobs time profiling */
};
#define G_DEBUG_ALL (G_DEBUG | G_DEBUG_FFMPEG | G_DEBUG_PYTHON | G_DEBUG_EVENTS | G_DEBUG_WM | G_DEBUG_JOBS)
@@ -145,17 +146,17 @@ enum {
#define G_FILE_ENABLE_ALL_FRAMES (1 << 3) /* deprecated */
#define G_FILE_SHOW_DEBUG_PROPS (1 << 4) /* deprecated */
#define G_FILE_SHOW_FRAMERATE (1 << 5) /* deprecated */
-/* #define G_FILE_SHOW_PROFILE (1 << 6) */ /* deprecated */
+/* #define G_FILE_SHOW_PROFILE (1 << 6) */ /* deprecated */
#define G_FILE_LOCK (1 << 7)
#define G_FILE_SIGN (1 << 8)
-/* #define G_FILE_PUBLISH (1 << 9) */ /* deprecated */
+/* #define G_FILE_PUBLISH (1 << 9) */ /* deprecated */
#define G_FILE_NO_UI (1 << 10)
-/* #define G_FILE_GAME_TO_IPO (1 << 11) */ /* deprecated */
+/* #define G_FILE_GAME_TO_IPO (1 << 11) */ /* deprecated */
#define G_FILE_GAME_MAT (1 << 12) /* deprecated */
-/* #define G_FILE_DISPLAY_LISTS (1 << 13) */ /* deprecated */
+/* #define G_FILE_DISPLAY_LISTS (1 << 13) */ /* deprecated */
#define G_FILE_SHOW_PHYSICS (1 << 14) /* deprecated */
#define G_FILE_GAME_MAT_GLSL (1 << 15) /* deprecated */
-/* #define G_FILE_GLSL_NO_LIGHTS (1 << 16) */ /* deprecated */
+/* #define G_FILE_GLSL_NO_LIGHTS (1 << 16) */ /* deprecated */
#define G_FILE_GLSL_NO_SHADERS (1 << 17) /* deprecated */
#define G_FILE_GLSL_NO_SHADOWS (1 << 18) /* deprecated */
#define G_FILE_GLSL_NO_RAMPS (1 << 19) /* deprecated */
diff --git a/source/blender/blenkernel/BKE_gpencil.h b/source/blender/blenkernel/BKE_gpencil.h
index f3223fb4af1..3cb20ead39e 100644
--- a/source/blender/blenkernel/BKE_gpencil.h
+++ b/source/blender/blenkernel/BKE_gpencil.h
@@ -44,7 +44,7 @@ void free_gpencil_layers(struct ListBase *list);
void BKE_gpencil_free(struct bGPdata *gpd);
struct bGPDframe *gpencil_frame_addnew(struct bGPDlayer *gpl, int cframe);
-struct bGPDlayer *gpencil_layer_addnew(struct bGPdata *gpd);
+struct bGPDlayer *gpencil_layer_addnew(struct bGPdata *gpd, const char *name, int setactive);
struct bGPdata *gpencil_data_addnew(const char name[]);
struct bGPDframe *gpencil_frame_duplicate(struct bGPDframe *src);
@@ -62,6 +62,6 @@ struct bGPDframe *gpencil_layer_getframe(struct bGPDlayer *gpl, int cframe, shor
void gpencil_layer_delframe(struct bGPDlayer *gpl, struct bGPDframe *gpf);
struct bGPDlayer *gpencil_layer_getactive(struct bGPdata *gpd);
void gpencil_layer_setactive(struct bGPdata *gpd, struct bGPDlayer *active);
-void gpencil_layer_delactive(struct bGPdata *gpd);
+void gpencil_layer_delete(struct bGPdata *gpd, struct bGPDlayer *gpl);
#endif /* __BKE_GPENCIL_H__ */
diff --git a/source/blender/blenkernel/BKE_group.h b/source/blender/blenkernel/BKE_group.h
index 67cdee9fa07..3e9803a908b 100644
--- a/source/blender/blenkernel/BKE_group.h
+++ b/source/blender/blenkernel/BKE_group.h
@@ -52,10 +52,6 @@ int group_is_animated(struct Object *parent, struct Group *group);
void group_tag_recalc(struct Group *group);
void group_handle_recalc_and_update(struct Scene *scene, struct Object *parent, struct Group *group);
-#if 0 /* UNUSED */
-struct Object *group_get_member_with_action(struct Group *group, struct bAction *act);
-void group_relink_nla_objects(struct Object *ob);
-#endif
#endif
diff --git a/source/blender/blenkernel/BKE_idprop.h b/source/blender/blenkernel/BKE_idprop.h
index 3cf4a2c5cdc..a9f6a61a655 100644
--- a/source/blender/blenkernel/BKE_idprop.h
+++ b/source/blender/blenkernel/BKE_idprop.h
@@ -154,6 +154,12 @@ __attribute__((nonnull))
#endif
;
+void IDP_MergeGroup(IDProperty *dest, IDProperty *src, const int do_overwrite)
+#ifdef __GNUC__
+__attribute__((nonnull))
+#endif
+;
+
/**
* This function has a sanity check to make sure ID properties with the same name don't
* get added to the group.
@@ -260,6 +266,12 @@ __attribute__((nonnull))
#endif
;
+int IDP_EqualsProperties_ex(IDProperty *prop1, IDProperty *prop2, const int is_strict)
+#ifdef __GNUC__
+__attribute__((warn_unused_result))
+#endif
+;
+
int IDP_EqualsProperties(struct IDProperty *prop1, struct IDProperty *prop2)
#ifdef __GNUC__
__attribute__((warn_unused_result))
@@ -306,11 +318,16 @@ void IDP_FreeProperty(struct IDProperty *prop);
/** Unlinks any struct IDProperty<->ID linkage that might be going on.*/
void IDP_UnlinkProperty(struct IDProperty *prop);
-#define IDP_Int(prop) ((prop)->data.val)
-#define IDP_Float(prop) (*(float *)&(prop)->data.val)
-#define IDP_String(prop) ((char *)(prop)->data.pointer)
-#define IDP_Array(prop) ((prop)->data.pointer)
-#define IDP_IDPArray(prop) ((IDProperty *)(prop)->data.pointer)
-#define IDP_Double(prop) (*(double *)&(prop)->data.val)
+#define IDP_Int(prop) ((prop)->data.val)
+#define IDP_Float(prop) (*(float *)&(prop)->data.val)
+#define IDP_Double(prop) (*(double *)&(prop)->data.val)
+#define IDP_String(prop) ((char *) (prop)->data.pointer)
+#define IDP_Array(prop) ((prop)->data.pointer)
+#define IDP_IDPArray(prop) ((IDProperty *) (prop)->data.pointer)
+
+#ifdef DEBUG
+/* for printout only */
+void IDP_spit(IDProperty *prop);
+#endif
#endif /* __BKE_IDPROP_H__ */
diff --git a/source/blender/blenkernel/BKE_image.h b/source/blender/blenkernel/BKE_image.h
index ac324b2af00..1875fd66628 100644
--- a/source/blender/blenkernel/BKE_image.h
+++ b/source/blender/blenkernel/BKE_image.h
@@ -66,7 +66,7 @@ int BKE_imtype_is_movie(const char imtype);
int BKE_imtype_supports_zbuf(const char imtype);
int BKE_imtype_supports_compress(const char imtype);
int BKE_imtype_supports_quality(const char imtype);
-int BKE_imtype_supports_float(const char imtype);
+int BKE_imtype_requires_linear_float(const char imtype);
char BKE_imtype_valid_channels(const char imtype);
char BKE_imtype_valid_depths(const char imtype);
@@ -127,6 +127,7 @@ enum {
#define IMA_SIGNAL_SRC_CHANGE 5
/* image-user gets a new image, check settings */
#define IMA_SIGNAL_USER_NEW_IMAGE 6
+#define IMA_SIGNAL_COLORMANAGE 7
#define IMA_CHAN_FLAG_BW 1
#define IMA_CHAN_FLAG_RGB 2
diff --git a/source/blender/blenkernel/BKE_key.h b/source/blender/blenkernel/BKE_key.h
index 1ad451b0937..d7d75b4c4c9 100644
--- a/source/blender/blenkernel/BKE_key.h
+++ b/source/blender/blenkernel/BKE_key.h
@@ -47,13 +47,13 @@ struct Mesh;
extern "C" {
#endif
-void BKE_key_free(struct Key *sc);
-void free_key_nolib(struct Key *key);
-struct Key *add_key(struct ID *id);
+void BKE_key_free(struct Key *sc);
+void BKE_key_free_nolib(struct Key *key);
+struct Key *BKE_key_add(struct ID *id);
struct Key *BKE_key_copy(struct Key *key);
-struct Key *copy_key_nolib(struct Key *key);
-void BKE_key_make_local(struct Key *key);
-void sort_keys(struct Key *key);
+struct Key *BKE_key_copy_nolib(struct Key *key);
+void BKE_key_make_local(struct Key *key);
+void BKE_key_sort(struct Key *key);
void key_curve_position_weights(float t, float data[4], int type);
void key_curve_tangent_weights(float t, float data[4], int type);
@@ -61,27 +61,29 @@ void key_curve_normal_weights(float t, float data[4], int type);
float *do_ob_key(struct Scene *scene, struct Object *ob);
-struct Key *ob_get_key(struct Object *ob);
-struct KeyBlock *add_keyblock(struct Key *key, const char *name);
-struct KeyBlock *add_keyblock_ctime(struct Key *key, const char *name, const short do_force);
-struct KeyBlock *ob_get_keyblock(struct Object *ob);
-struct KeyBlock *ob_get_reference_keyblock(struct Object *ob);
-struct KeyBlock *key_get_keyblock(struct Key *key, int index);
-struct KeyBlock *key_get_named_keyblock(struct Key *key, const char name[]);
-char *key_get_curValue_rnaPath(struct Key *key, struct KeyBlock *kb);
+struct Key *BKE_key_from_object(struct Object *ob);
+struct KeyBlock *BKE_keyblock_from_object(struct Object *ob);
+struct KeyBlock *BKE_keyblock_from_object_reference(struct Object *ob);
+
+struct KeyBlock *BKE_keyblock_add(struct Key *key, const char *name);
+struct KeyBlock *BKE_keyblock_add_ctime(struct Key *key, const char *name, const short do_force);
+struct KeyBlock *BKE_keyblock_from_key(struct Key *key, int index);
+struct KeyBlock *BKE_keyblock_find_name(struct Key *key, const char name[]);
+void BKE_keyblock_copy_settings(struct KeyBlock *kb_dst, const struct KeyBlock *kb_src);
+char *BKE_keyblock_curval_rnapath_get(struct Key *key, struct KeyBlock *kb);
// needed for the GE
-void do_rel_key(const int start, int end, const int tot, char *basispoin, struct Key *key, struct KeyBlock *actkb, const int mode);
+void BKE_key_evaluate_relative(const int start, int end, const int tot, char *basispoin, struct Key *key, struct KeyBlock *actkb, const int mode);
/* conversion functions */
-void key_to_mesh(struct KeyBlock *kb, struct Mesh *me);
-void mesh_to_key(struct Mesh *me, struct KeyBlock *kb);
-void key_to_latt(struct KeyBlock *kb, struct Lattice *lt);
-void latt_to_key(struct Lattice *lt, struct KeyBlock *kb);
-void key_to_curve(struct KeyBlock *kb, struct Curve *cu, struct ListBase *nurb);
-void curve_to_key(struct Curve *cu, struct KeyBlock *kb, struct ListBase *nurb);
-float (*key_to_vertcos(struct Object *ob, struct KeyBlock *kb))[3];
-void vertcos_to_key(struct Object *ob, struct KeyBlock *kb, float (*vertCos)[3]);
-void offset_to_key(struct Object *ob, struct KeyBlock *kb, float (*ofs)[3]);
+void BKE_key_convert_to_mesh(struct KeyBlock *kb, struct Mesh *me);
+void BKE_key_convert_from_mesh(struct Mesh *me, struct KeyBlock *kb);
+void BKE_key_convert_to_lattice(struct KeyBlock *kb, struct Lattice *lt);
+void BKE_key_convert_from_lattice(struct Lattice *lt, struct KeyBlock *kb);
+void BKE_key_convert_to_curve(struct KeyBlock *kb, struct Curve *cu, struct ListBase *nurb);
+void BKE_key_convert_from_curve(struct Curve *cu, struct KeyBlock *kb, struct ListBase *nurb);
+float (*BKE_key_convert_to_vertcos(struct Object *ob, struct KeyBlock *kb))[3];
+void BKE_key_convert_from_vertcos(struct Object *ob, struct KeyBlock *kb, float (*vertCos)[3]);
+void BKE_key_convert_from_offset(struct Object *ob, struct KeyBlock *kb, float (*ofs)[3]);
/* key.c */
extern int slurph_opt;
@@ -90,4 +92,4 @@ extern int slurph_opt;
};
#endif
-#endif // __BKE_KEY_H__
+#endif /* __BKE_KEY_H__ */
diff --git a/source/blender/blenkernel/BKE_lattice.h b/source/blender/blenkernel/BKE_lattice.h
index 31626ef4a58..34baa48dbe2 100644
--- a/source/blender/blenkernel/BKE_lattice.h
+++ b/source/blender/blenkernel/BKE_lattice.h
@@ -46,7 +46,7 @@ struct Lattice *BKE_lattice_add(const char *name);
struct Lattice *BKE_lattice_copy(struct Lattice *lt);
void BKE_lattice_free(struct Lattice *lt);
void BKE_lattice_make_local(struct Lattice *lt);
-void calc_lat_fudu(int flag, int res, float *fu, float *du);
+void calc_lat_fudu(int flag, int res, float *r_fu, float *r_du);
void init_latt_deform(struct Object *oblatt, struct Object *ob);
void calc_latt_deform(struct Object *, float co[3], float weight);
diff --git a/source/blender/blenkernel/BKE_library.h b/source/blender/blenkernel/BKE_library.h
index 91756448297..bc081b7f308 100644
--- a/source/blender/blenkernel/BKE_library.h
+++ b/source/blender/blenkernel/BKE_library.h
@@ -81,6 +81,7 @@ int set_listbasepointers(struct Main *main, struct ListBase **lb);
void BKE_libblock_free(struct ListBase *lb, void *idv);
void BKE_libblock_free_us(struct ListBase *lb, void *idv);
+void BKE_libblock_free_data(struct ID *id);
void free_main(struct Main *mainvar);
void tag_main_idcode(struct Main *mainvar, const short type, const short tag);
diff --git a/source/blender/blenkernel/BKE_main.h b/source/blender/blenkernel/BKE_main.h
index 3074e1c0e63..cfdcf1436bf 100644
--- a/source/blender/blenkernel/BKE_main.h
+++ b/source/blender/blenkernel/BKE_main.h
@@ -68,7 +68,7 @@ typedef struct Main {
ListBase latt;
ListBase lamp;
ListBase camera;
- ListBase ipo; // XXX depreceated
+ ListBase ipo; // XXX deprecated
ListBase key;
ListBase world;
ListBase screen;
diff --git a/source/blender/blenkernel/BKE_mball.h b/source/blender/blenkernel/BKE_mball.h
index 913e8653b9b..7a0eea1b009 100644
--- a/source/blender/blenkernel/BKE_mball.h
+++ b/source/blender/blenkernel/BKE_mball.h
@@ -59,8 +59,12 @@ void BKE_mball_properties_copy(struct Scene *scene, struct Object *active_object
int BKE_mball_minmax(struct MetaBall *mb, float min[3], float max[3]);
int BKE_mball_center_median(struct MetaBall *mb, float r_cent[3]);
int BKE_mball_center_bounds(struct MetaBall *mb, float r_cent[3]);
-void BKE_mball_translate(struct MetaBall *mb, float offset[3]);
+void BKE_mball_translate(struct MetaBall *mb, const float offset[3]);
struct MetaElem *BKE_mball_element_add(struct MetaBall *mb, const int type);
+void BKE_mball_select_all(struct MetaBall *mb);
+void BKE_mball_deselect_all(struct MetaBall *mb);
+void BKE_mball_select_swap(struct MetaBall *mb);
+
#endif
diff --git a/source/blender/blenkernel/BKE_mesh.h b/source/blender/blenkernel/BKE_mesh.h
index 954fb47806b..2f889084d0e 100644
--- a/source/blender/blenkernel/BKE_mesh.h
+++ b/source/blender/blenkernel/BKE_mesh.h
@@ -88,8 +88,8 @@ int BKE_mesh_mpoly_to_mface(struct CustomData *fdata, struct CustomData *ldata,
struct CustomData *pdata, int totface, int totloop, int totpoly);
/*calculates a face normal.*/
-void mesh_calc_poly_normal(struct MPoly *mpoly, struct MLoop *loopstart,
- struct MVert *mvarray, float no[3]);
+void BKE_mesh_calc_poly_normal(struct MPoly *mpoly, struct MLoop *loopstart,
+ struct MVert *mvarray, float no[3]);
void BKE_mesh_calc_poly_normal_coords(struct MPoly *mpoly, struct MLoop *loopstart,
const float (*vertex_coords)[3], float no[3]);
@@ -98,7 +98,7 @@ void BKE_mesh_calc_poly_center(struct MPoly *mpoly, struct MLoop *loopstart,
struct MVert *mvarray, float cent[3]);
float BKE_mesh_calc_poly_area(struct MPoly *mpoly, struct MLoop *loopstart,
- struct MVert *mvarray, float polynormal[3]);
+ struct MVert *mvarray, const float polynormal[3]);
/* Find the index of the loop in 'poly' which references vertex,
* returns -1 if not found */
@@ -130,7 +130,7 @@ struct Mesh *BKE_mesh_copy(struct Mesh *me);
void mesh_update_customdata_pointers(struct Mesh *me, const short do_ensure_tess_cd);
void BKE_mesh_make_local(struct Mesh *me);
-void BKE_mesh_boundbox_calc(struct Mesh *me, float *loc, float *size);
+void BKE_mesh_boundbox_calc(struct Mesh *me, float r_loc[3], float r_size[3]);
void BKE_mesh_texspace_calc(struct Mesh *me);
float *BKE_mesh_orco_verts_get(struct Object *ob);
void BKE_mesh_orco_verts_transform(struct Mesh *me, float (*orco)[3], int totvert, int invert);
@@ -292,6 +292,7 @@ void create_vert_edge_map(MeshElemMap **map, int **mem,
int BKE_mesh_minmax(struct Mesh *me, float r_min[3], float r_max[3]);
int BKE_mesh_center_median(struct Mesh *me, float cent[3]);
int BKE_mesh_center_bounds(struct Mesh *me, float cent[3]);
+int BKE_mesh_center_centroid(struct Mesh *me, float cent[3]);
void BKE_mesh_translate(struct Mesh *me, float offset[3], int do_keys);
/* mesh_validate.c */
diff --git a/source/blender/blenkernel/BKE_modifier.h b/source/blender/blenkernel/BKE_modifier.h
index 3b675f3b620..7ee1c85d0de 100644
--- a/source/blender/blenkernel/BKE_modifier.h
+++ b/source/blender/blenkernel/BKE_modifier.h
@@ -352,6 +352,7 @@ int modifiers_isParticleEnabled(struct Object *ob);
struct Object *modifiers_isDeformedByArmature(struct Object *ob);
struct Object *modifiers_isDeformedByLattice(struct Object *ob);
+struct Object *modifiers_isDeformedByCurve(struct Object *ob);
int modifiers_usesArmature(struct Object *ob, struct bArmature *arm);
int modifiers_isCorrectableDeformed(struct Object *ob);
void modifier_freeTemporaryData(struct ModifierData *md);
diff --git a/source/blender/blenkernel/BKE_multires.h b/source/blender/blenkernel/BKE_multires.h
index 82a791348dd..8fa20eb2cc2 100644
--- a/source/blender/blenkernel/BKE_multires.h
+++ b/source/blender/blenkernel/BKE_multires.h
@@ -116,5 +116,4 @@ void multires_topology_changed(struct Mesh *me);
void old_mdisps_bilinear(float out[3], float (*disps)[3], const int st, float u, float v);
int mdisp_rot_face_to_crn(const int corners, const int face_side, const float u, const float v, float *x, float *y);
-#endif // __BKE_MULTIRES_H__
-
+#endif /* __BKE_MULTIRES_H__ */
diff --git a/source/blender/blenkernel/BKE_navmesh_conversion.h b/source/blender/blenkernel/BKE_navmesh_conversion.h
index aab359b307a..cc9c18c764d 100644
--- a/source/blender/blenkernel/BKE_navmesh_conversion.h
+++ b/source/blender/blenkernel/BKE_navmesh_conversion.h
@@ -60,4 +60,4 @@ int polyFindVertex(const unsigned short *p, const int vertsPerPoly, unsigned sho
float distPointToSegmentSq(const float *point, const float *a, const float *b);
-#endif //NAVMESH_CONVERSION_H
+#endif /* NAVMESH_CONVERSION_H */
diff --git a/source/blender/blenkernel/BKE_node.h b/source/blender/blenkernel/BKE_node.h
index 6ad2ad924e2..29e03f66bcc 100644
--- a/source/blender/blenkernel/BKE_node.h
+++ b/source/blender/blenkernel/BKE_node.h
@@ -193,10 +193,8 @@ typedef struct bNodeType {
struct bNodeTree *(*group_edit_set)(struct bNode *node, int edit);
void (*group_edit_clear)(struct bNode *node);
- /* Generate a temporary list of internal links (bNodeLink), for muting and disconnect operators.
- * Result must be freed by caller!
- */
- ListBase (*internal_connect)(struct bNodeTree *, struct bNode *node);
+ /* Update the internal links list, for muting and disconnect operators. */
+ void (*update_internal_links)(struct bNodeTree *, struct bNode *node);
/* **** execution callbacks **** */
void *(*initexecfunc)(struct bNode *node);
@@ -247,6 +245,7 @@ typedef struct bNodeType {
#define NODE_CLASS_PARTICLES 25
#define NODE_CLASS_TRANSFORM 30
#define NODE_CLASS_COMBINE 31
+#define NODE_CLASS_SCRIPT 32
#define NODE_CLASS_SHADER 40
#define NODE_CLASS_LAYOUT 100
@@ -293,7 +292,7 @@ typedef struct bNodeTreeType {
int (*validate_link)(struct bNodeTree *ntree, struct bNodeLink *link);
/* Default internal linking. */
- ListBase (*internal_connect)(struct bNodeTree *, struct bNode *node);
+ void (*update_internal_links)(struct bNodeTree *, struct bNode *node);
} bNodeTreeType;
/* ************** GENERIC API, TREES *************** */
@@ -349,7 +348,7 @@ struct bNodeSocket *nodeInsertSocket(struct bNodeTree *ntree, struct bNode *node
void nodeRemoveSocket(struct bNodeTree *ntree, struct bNode *node, struct bNodeSocket *sock);
void nodeRemoveAllSockets(struct bNodeTree *ntree, struct bNode *node);
-void nodeAddToPreview(struct bNode *node, float col[4], int x, int y, int do_manage);
+void nodeAddToPreview(struct bNode *node, const float col[4], int x, int y, int do_manage);
struct bNode *nodeAddNode(struct bNodeTree *ntree, struct bNodeTemplate *ntemp);
void nodeUnlinkNode(struct bNodeTree *ntree, struct bNode *node);
@@ -389,6 +388,7 @@ struct bNode *nodeGetActiveTexture(struct bNodeTree *ntree);
void nodeUpdate(struct bNodeTree *ntree, struct bNode *node);
int nodeUpdateID(struct bNodeTree *ntree, struct ID *id);
+void nodeUpdateInternalLinks(struct bNodeTree *ntree, struct bNode *node);
void nodeFreePreview(struct bNode *node);
@@ -445,7 +445,7 @@ void node_type_exec_new(struct bNodeType *ntype,
void (*freeexecfunc)(struct bNode *node, void *nodedata),
void (*newexecfunc)(void *data, int thread, struct bNode *, void *nodedata,
struct bNodeStack **, struct bNodeStack **));
-void node_type_internal_connect(struct bNodeType *ntype, ListBase (*internal_connect)(struct bNodeTree *, struct bNode *));
+void node_type_internal_links(struct bNodeType *ntype, void (*update_internal_links)(struct bNodeTree *, struct bNode *));
void node_type_gpu(struct bNodeType *ntype, int (*gpufunc)(struct GPUMaterial *mat, struct bNode *node,
struct GPUNodeStack *in, struct GPUNodeStack *out));
void node_type_gpu_ext(struct bNodeType *ntype, int (*gpuextfunc)(struct GPUMaterial *mat, struct bNode *node,
@@ -456,8 +456,8 @@ void node_type_compatibility(struct bNodeType *ntype, short compatibi
/* ************** COMMON NODES *************** */
#define NODE_GROUP 2
-#define NODE_FORLOOP 3
-#define NODE_WHILELOOP 4
+#define __NODE_FORLOOP 3 /* deprecated */
+#define __NODE_WHILELOOP 4 /* deprecated */
#define NODE_FRAME 5
#define NODE_REROUTE 6
@@ -475,6 +475,8 @@ struct bNodeSocket *node_group_add_extern_socket(struct bNodeTree *ntree, ListBa
void register_node_type_frame(struct bNodeTreeType *ttype);
void register_node_type_reroute(struct bNodeTreeType *ttype);
+void BKE_node_tree_unlink_id_cb(void *calldata, struct ID *owner_id, struct bNodeTree *ntree);
+
/* ************** SHADER NODES *************** */
struct ShadeInput;
@@ -549,6 +551,8 @@ struct ShadeResult;
#define SH_NODE_OBJECT_INFO 167
#define SH_NODE_PARTICLE_INFO 168
#define SH_NODE_TEX_BRICK 169
+#define SH_NODE_BUMP 170
+#define SH_NODE_SCRIPT 171
/* custom defines options for Material node */
#define SH_NODE_MAT_DIFF 1
@@ -696,6 +700,7 @@ void ntreeGPUMaterialNodes(struct bNodeTree *ntree, struct GPUMateria
#define CMP_NODE_BOKEHIMAGE 315
#define CMP_NODE_BOKEHBLUR 316
#define CMP_NODE_SWITCH 317
+#define CMP_NODE_PIXELATE 318
/* channel toggles */
#define CMP_CHAN_RGB 1
@@ -782,7 +787,9 @@ void ntreeTexCheckCyclics(struct bNodeTree *ntree);
struct bNodeTreeExec *ntreeTexBeginExecTree(struct bNodeTree *ntree, int use_tree_data);
void ntreeTexEndExecTree(struct bNodeTreeExec *exec, int use_tree_data);
-int ntreeTexExecTree(struct bNodeTree *ntree, struct TexResult *target, float *coord, float *dxt, float *dyt, int osatex, short thread, struct Tex *tex, short which_output, int cfra, int preview, struct ShadeInput *shi, struct MTex *mtex);
+int ntreeTexExecTree(struct bNodeTree *ntree, struct TexResult *target,
+ float coord[3], float dxt[3], float dyt[3], int osatex, const short thread,
+ struct Tex *tex, short which_output, int cfra, int preview, struct ShadeInput *shi, struct MTex *mtex);
/*************************************************/
diff --git a/source/blender/blenkernel/BKE_object.h b/source/blender/blenkernel/BKE_object.h
index 31642dad60d..ec0703248fd 100644
--- a/source/blender/blenkernel/BKE_object.h
+++ b/source/blender/blenkernel/BKE_object.h
@@ -54,7 +54,7 @@ void BKE_object_workob_clear(struct Object *workob);
void BKE_object_workob_calc_parent(struct Scene *scene, struct Object *ob, struct Object *workob);
void BKE_object_transform_copy(struct Object *ob_tar, const struct Object *ob_src);
-struct SoftBody *copy_softbody(struct SoftBody *sb);
+struct SoftBody *copy_softbody(struct SoftBody *sb, int copy_caches);
struct BulletSoftBody *copy_bulletsoftbody(struct BulletSoftBody *sb);
void BKE_object_copy_particlesystems(struct Object *obn, struct Object *ob);
void BKE_object_copy_softbody(struct Object *obn, struct Object *ob);
@@ -82,6 +82,7 @@ struct Object *BKE_object_add(struct Scene *scene, int type);
void *BKE_object_obdata_add_from_type(int type);
struct Object *BKE_object_copy(struct Object *ob);
+struct Object *BKE_object_copy_with_caches(struct Object *ob);
void BKE_object_make_local(struct Object *ob);
int BKE_object_is_libdata(struct Object *ob);
int BKE_object_obdata_is_libdata(struct Object *ob);
@@ -93,6 +94,7 @@ void BKE_object_to_mat3(struct Object *ob, float mat[][3]);
void BKE_object_to_mat4(struct Object *ob, float mat[][4]);
void BKE_object_apply_mat4(struct Object *ob, float mat[][4], const short use_compat, const short use_parent);
+int BKE_object_pose_context_check(struct Object *ob);
struct Object *BKE_object_pose_armature_get(struct Object *ob);
void BKE_object_where_is_calc(struct Scene *scene, struct Object *ob);
diff --git a/source/blender/blenkernel/BKE_paint.h b/source/blender/blenkernel/BKE_paint.h
index a93e542fe15..c452c177143 100644
--- a/source/blender/blenkernel/BKE_paint.h
+++ b/source/blender/blenkernel/BKE_paint.h
@@ -94,6 +94,7 @@ typedef struct SculptSession {
/* PBVH acceleration structure */
struct PBVH *pbvh;
+ int show_diffuse_color;
/* Paiting on deformed mesh */
int modifiers_active; /* object is deformed with some modifiers */
diff --git a/source/blender/blenkernel/BKE_particle.h b/source/blender/blenkernel/BKE_particle.h
index b3e650b2aa5..ec03f53dbdb 100644
--- a/source/blender/blenkernel/BKE_particle.h
+++ b/source/blender/blenkernel/BKE_particle.h
@@ -257,7 +257,9 @@ void psys_interpolate_mcol(const struct MCol *mcol, int quad, const float w[4],
void copy_particle_key(struct ParticleKey *to, struct ParticleKey *from, int time);
-void psys_particle_on_emitter(struct ParticleSystemModifierData *psmd, int distr, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
+void psys_particle_on_emitter(struct ParticleSystemModifierData *psmd, int distr, int index, int index_dmcache,
+ float fuv[4], float foffset, float vec[3], float nor[3],
+ float utan[3], float vtan[3], float orco[3], float ornor[3]);
struct ParticleSystemModifierData *psys_get_modifier(struct Object *ob, struct ParticleSystem *psys);
struct ModifierData *object_add_particle_system(struct Scene *scene, struct Object *ob, const char *name);
@@ -282,8 +284,11 @@ void psys_get_particle_on_path(struct ParticleSimulationData *sim, int pa_num, s
int psys_get_particle_state(struct ParticleSimulationData *sim, int p, struct ParticleKey *state, int always);
/* for anim.c */
-void psys_get_dupli_texture(struct ParticleSystem *psys, struct ParticleSettings *part, struct ParticleSystemModifierData *psmd, struct ParticleData *pa, struct ChildParticle *cpa, float *uv, float *orco);
-void psys_get_dupli_path_transform(struct ParticleSimulationData *sim, struct ParticleData *pa, struct ChildParticle *cpa, struct ParticleCacheKey *cache, float mat[][4], float *scale);
+void psys_get_dupli_texture(struct ParticleSystem *psys, struct ParticleSettings *part,
+ struct ParticleSystemModifierData *psmd, struct ParticleData *pa, struct ChildParticle *cpa,
+ float uv[2], float orco[3]);
+void psys_get_dupli_path_transform(struct ParticleSimulationData *sim, struct ParticleData *pa, struct ChildParticle *cpa,
+ struct ParticleCacheKey *cache, float mat[][4], float *scale);
ParticleThread *psys_threads_create(struct ParticleSimulationData *sim);
void psys_threads_free(ParticleThread *threads);
@@ -327,13 +332,17 @@ void psys_free_pdd(struct ParticleSystem *psys);
float *psys_cache_vgroup(struct DerivedMesh *dm, struct ParticleSystem *psys, int vgroup);
void psys_get_texture(struct ParticleSimulationData *sim, struct ParticleData *pa, struct ParticleTexture *ptex, int event, float cfra);
-void psys_interpolate_face(struct MVert *mvert, struct MFace *mface, struct MTFace *tface, float (*orcodata)[3], float *uv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
+void psys_interpolate_face(struct MVert *mvert, struct MFace *mface, struct MTFace *tface,
+ float (*orcodata)[3], float w[4], float vec[3], float nor[3], float utan[3], float vtan[3],
+ float orco[3], float ornor[3]);
float psys_particle_value_from_verts(struct DerivedMesh *dm, short from, struct ParticleData *pa, float *values);
-void psys_get_from_key(struct ParticleKey *key, float *loc, float *vel, float *rot, float *time);
+void psys_get_from_key(struct ParticleKey *key, float loc[3], float vel[3], float rot[4], float *time);
/* BLI_bvhtree_ray_cast callback */
void BKE_psys_collision_neartest_cb(void *userdata, int index, const struct BVHTreeRay *ray, struct BVHTreeRayHit *hit);
-void psys_particle_on_dm(struct DerivedMesh *dm, int from, int index, int index_dmcache, const float fw[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3], float orco[3], float ornor[3]);
+void psys_particle_on_dm(struct DerivedMesh *dm, int from, int index, int index_dmcache,
+ const float fw[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3],
+ float orco[3], float ornor[3]);
/* particle_system.c */
void initialize_particle(struct ParticleSimulationData *sim, struct ParticleData *pa, int p);
diff --git a/source/blender/blenkernel/BKE_pointcache.h b/source/blender/blenkernel/BKE_pointcache.h
index d6ab9a35697..77b35e1a25c 100644
--- a/source/blender/blenkernel/BKE_pointcache.h
+++ b/source/blender/blenkernel/BKE_pointcache.h
@@ -303,7 +303,7 @@ struct PointCache *BKE_ptcache_add(struct ListBase *ptcaches);
void BKE_ptcache_free_mem(struct ListBase *mem_cache);
void BKE_ptcache_free(struct PointCache *cache);
void BKE_ptcache_free_list(struct ListBase *ptcaches);
-struct PointCache *BKE_ptcache_copy_list(struct ListBase *ptcaches_new, struct ListBase *ptcaches_old);
+struct PointCache *BKE_ptcache_copy_list(struct ListBase *ptcaches_new, struct ListBase *ptcaches_old, int copy_data);
/********************** Baking *********************/
diff --git a/source/blender/blenkernel/BKE_property.h b/source/blender/blenkernel/BKE_property.h
index a29dc0e7be4..e0eb8c04b60 100644
--- a/source/blender/blenkernel/BKE_property.h
+++ b/source/blender/blenkernel/BKE_property.h
@@ -35,19 +35,18 @@ struct bProperty;
struct ListBase;
struct Object;
-void free_property(struct bProperty *prop);
-void free_properties(struct ListBase *lb);
-struct bProperty *copy_property(struct bProperty *prop);
-void copy_properties(struct ListBase *lbn, struct ListBase *lbo);
-void init_property(struct bProperty *prop);
-struct bProperty *new_property(int type);
-void unique_property(struct bProperty *first, struct bProperty *prop, int force);
-struct bProperty *get_ob_property(struct Object *ob, const char *name);
-void set_ob_property(struct Object *ob, struct bProperty *propc);
-int compare_property(struct bProperty *prop, const char *str);
-void set_property(struct bProperty *prop, const char *str);
-void add_property(struct bProperty *prop, const char *str);
-void set_property_valstr(struct bProperty *prop, char *str);
-void cp_property(struct bProperty *prop1, struct bProperty *prop2);
+void BKE_bproperty_free(struct bProperty *prop);
+void BKE_bproperty_free_list(struct ListBase *lb);
+struct bProperty *BKE_bproperty_copy(struct bProperty *prop);
+void BKE_bproperty_copy_list(struct ListBase *lbn, struct ListBase *lbo);
+void BKE_bproperty_init(struct bProperty *prop);
+struct bProperty *BKE_bproperty_new(int type);
+void BKE_bproperty_unique(struct bProperty *first, struct bProperty *prop, int force);
+struct bProperty *BKE_bproperty_object_get(struct Object *ob, const char *name);
+void BKE_bproperty_object_set(struct Object *ob, struct bProperty *propc);
+// int BKE_bproperty_cmp(struct bProperty *prop, const char *str);
+void BKE_bproperty_set(struct bProperty *prop, const char *str);
+void BKE_bproperty_add(struct bProperty *prop, const char *str);
+void BKE_bproperty_set_valstr(struct bProperty *prop, char *str);
#endif
diff --git a/source/blender/blenkernel/BKE_sca.h b/source/blender/blenkernel/BKE_sca.h
index 22b44511195..d598a26fdf9 100644
--- a/source/blender/blenkernel/BKE_sca.h
+++ b/source/blender/blenkernel/BKE_sca.h
@@ -74,5 +74,7 @@ void sca_move_sensor(struct bSensor *sens_to_move, struct Object *ob, int move_u
void sca_move_controller(struct bController *cont_to_move, struct Object *ob, int move_up);
void sca_move_actuator(struct bActuator *act_to_move, struct Object *ob, int move_up);
+const char *sca_state_name_get(Object *ob, short bit);
+
#endif
diff --git a/source/blender/blenkernel/BKE_scene.h b/source/blender/blenkernel/BKE_scene.h
index 023b7e85c40..9927c7a42ed 100644
--- a/source/blender/blenkernel/BKE_scene.h
+++ b/source/blender/blenkernel/BKE_scene.h
@@ -55,7 +55,12 @@ struct Text;
#define SCE_COPY_LINK_DATA 3
#define SCE_COPY_FULL 4
-#define SETLOOPER(_sce_basis, _sce_iter, _base) _sce_iter = _sce_basis, _base = _setlooper_base_step(&_sce_iter, NULL); _base; _base = _setlooper_base_step(&_sce_iter, _base)
+/* Use as the contents of a 'for' loop: for (SETLOOPER(...)) { ... */
+#define SETLOOPER(_sce_basis, _sce_iter, _base) \
+ _sce_iter = _sce_basis, _base = _setlooper_base_step(&_sce_iter, NULL); \
+ _base; \
+ _base = _setlooper_base_step(&_sce_iter, _base)
+
struct Base *_setlooper_base_step(struct Scene **sce_iter, struct Base *base);
void free_avicodecdata(struct AviCodecData *acd);
@@ -109,6 +114,7 @@ float get_render_aosss_error(struct RenderData *r, float error);
int BKE_scene_use_new_shading_nodes(struct Scene *scene);
void BKE_scene_disable_color_management(struct Scene *scene);
+int BKE_scene_check_color_management_enabled(const struct Scene *scene);
#ifdef __cplusplus
}
diff --git a/source/blender/blenkernel/BKE_sequencer.h b/source/blender/blenkernel/BKE_sequencer.h
index 0c571f62f0e..1667c119790 100644
--- a/source/blender/blenkernel/BKE_sequencer.h
+++ b/source/blender/blenkernel/BKE_sequencer.h
@@ -64,29 +64,31 @@ typedef struct SeqIterator {
int valid;
} SeqIterator;
-void BKE_seqence_iterator_begin(struct Editing *ed, SeqIterator *iter, int use_pointer);
-void BKE_seqence_iterator_next(SeqIterator *iter);
-void BKE_seqence_iterator_end(SeqIterator *iter);
+void BKE_sequence_iterator_begin(struct Editing *ed, SeqIterator *iter, int use_pointer);
+void BKE_sequence_iterator_next(SeqIterator *iter);
+void BKE_sequence_iterator_end(SeqIterator *iter);
-#define SEQP_BEGIN(ed, _seq) \
+#define SEQP_BEGIN(_ed, _seq) \
{ \
- SeqIterator iter; \
- for (BKE_seqence_iterator_begin(ed, &iter, 1); \
- iter.valid; \
- BKE_seqence_iterator_next(&iter)) { \
- _seq = iter.seq;
-
+ SeqIterator iter_macro; \
+ for (BKE_sequence_iterator_begin(_ed, &iter_macro, 1); \
+ iter_macro.valid; \
+ BKE_sequence_iterator_next(&iter_macro)) \
+ { \
+ _seq = iter_macro.seq;
+
#define SEQ_BEGIN(ed, _seq) \
{ \
- SeqIterator iter; \
- for (BKE_seqence_iterator_begin(ed, &iter, 0); \
- iter.valid; \
- BKE_seqence_iterator_next(&iter)) { \
- _seq = iter.seq;
+ SeqIterator iter_macro; \
+ for (BKE_sequence_iterator_begin(ed, &iter_macro, 0); \
+ iter_macro.valid; \
+ BKE_sequence_iterator_next(&iter_macro)) \
+ { \
+ _seq = iter_macro.seq;
#define SEQ_END \
} \
- BKE_seqence_iterator_end(&iter); \
+ BKE_sequence_iterator_end(&iter_macro); \
}
typedef struct SeqRenderData {
@@ -307,7 +309,7 @@ int BKE_sequence_swap(struct Sequence *seq_a, struct Sequence *seq_b, const char
int BKE_sequence_check_depend(struct Sequence *seq, struct Sequence *cur);
void BKE_sequence_invalidate_cache(struct Scene *scene, struct Sequence *seq);
-void BKE_sequence_invalidate_deendent(struct Scene *scene, struct Sequence *seq);
+void BKE_sequence_invalidate_dependent(struct Scene *scene, struct Sequence *seq);
void BKE_sequence_invalidate_cache_for_modifier(struct Scene *scene, struct Sequence *seq);
void BKE_sequencer_update_sound_bounds_all(struct Scene *scene);
@@ -315,9 +317,9 @@ void BKE_sequencer_update_sound_bounds(struct Scene *scene, struct Sequence *seq
void BKE_sequencer_update_muting(struct Editing *ed);
void BKE_sequencer_update_sound(struct Scene *scene, struct bSound *sound);
-void BKE_seqence_base_unique_name_recursive(ListBase *seqbasep, struct Sequence *seq);
+void BKE_sequence_base_unique_name_recursive(ListBase *seqbasep, struct Sequence *seq);
void BKE_sequence_base_dupli_recursive(struct Scene *scene, struct Scene *scene_to, ListBase *nseqbase, ListBase *seqbase, int dupe_flag);
-int BKE_seqence_is_valid_check(struct Sequence *seq);
+int BKE_sequence_is_valid_check(struct Sequence *seq);
void BKE_sequencer_clear_scene_in_allseqs(struct Main *bmain, struct Scene *sce);
diff --git a/source/blender/blenkernel/BKE_smoke.h b/source/blender/blenkernel/BKE_smoke.h
index 1f824ccbafc..3a9d2b86b41 100644
--- a/source/blender/blenkernel/BKE_smoke.h
+++ b/source/blender/blenkernel/BKE_smoke.h
@@ -35,8 +35,10 @@
typedef float (*bresenham_callback)(float *result, float *input, int res[3], int *pixel, float *tRay, float correct);
-void smokeModifier_do(struct SmokeModifierData *smd, struct Scene *scene, struct Object *ob, struct DerivedMesh *dm);
+struct DerivedMesh *smokeModifier_do(struct SmokeModifierData *smd, struct Scene *scene, struct Object *ob, struct DerivedMesh *dm);
+void smoke_reallocate_fluid(struct SmokeDomainSettings *sds, float dx, int res[3], int free_old);
+void smoke_reallocate_highres_fluid(struct SmokeDomainSettings *sds, float dx, int res[3], int free_old);
void smokeModifier_free(struct SmokeModifierData *smd);
void smokeModifier_reset(struct SmokeModifierData *smd);
void smokeModifier_reset_turbulence(struct SmokeModifierData *smd);
@@ -44,5 +46,7 @@ void smokeModifier_createType(struct SmokeModifierData *smd);
void smokeModifier_copy(struct SmokeModifierData *smd, struct SmokeModifierData *tsmd);
long long smoke_get_mem_req(int xres, int yres, int zres, int amplify);
+float smoke_get_velocity_at(struct Object *ob, float position[3], float velocity[3]);
+int smoke_get_data_flags(struct SmokeDomainSettings *sds);
#endif /* __BKE_SMOKE_H__ */
diff --git a/source/blender/blenkernel/BKE_subsurf.h b/source/blender/blenkernel/BKE_subsurf.h
index 3b8d0eafd4d..653f2a42675 100644
--- a/source/blender/blenkernel/BKE_subsurf.h
+++ b/source/blender/blenkernel/BKE_subsurf.h
@@ -64,10 +64,10 @@ typedef enum {
} SubsurfFlags;
struct DerivedMesh *subsurf_make_derived_from_derived(
- struct DerivedMesh *dm,
- struct SubsurfModifierData *smd,
- float (*vertCos)[3],
- SubsurfFlags flags);
+ struct DerivedMesh *dm,
+ struct SubsurfModifierData *smd,
+ float (*vertCos)[3],
+ SubsurfFlags flags);
void subsurf_calculate_limit_positions(struct Mesh *me, float (*positions_r)[3]);
diff --git a/source/blender/blenkernel/BKE_tracking.h b/source/blender/blenkernel/BKE_tracking.h
index c14476a3b59..eb7004b1ced 100644
--- a/source/blender/blenkernel/BKE_tracking.h
+++ b/source/blender/blenkernel/BKE_tracking.h
@@ -80,7 +80,7 @@ int BKE_tracking_track_has_marker_at_frame(struct MovieTrackingTrack *track, int
int BKE_tracking_track_has_enabled_marker_at_frame(struct MovieTrackingTrack *track, int framenr);
void BKE_tracking_track_path_clear(struct MovieTrackingTrack *track, int ref_frame, int action);
-void BKE_tracking_tracks_join(struct MovieTrackingTrack *dst_track, struct MovieTrackingTrack *src_track);
+void BKE_tracking_tracks_join(struct MovieTracking *tracking, struct MovieTrackingTrack *dst_track, struct MovieTrackingTrack *src_track);
struct MovieTrackingTrack *BKE_tracking_track_get_named(struct MovieTracking *tracking,
struct MovieTrackingObject *object,
@@ -114,7 +114,7 @@ void BKE_tracking_marker_get_subframe_position(struct MovieTrackingTrack *track,
/* **** Object **** */
struct MovieTrackingObject *BKE_tracking_object_add(struct MovieTracking *tracking, const char *name);
-void BKE_tracking_object_delete(struct MovieTracking *tracking, struct MovieTrackingObject *object);
+int BKE_tracking_object_delete(struct MovieTracking *tracking, struct MovieTrackingObject *object);
void BKE_tracking_object_unique_name(struct MovieTracking *tracking, struct MovieTrackingObject *object);
diff --git a/source/blender/blenkernel/BKE_utildefines.h b/source/blender/blenkernel/BKE_utildefines.h
index 63f5ec59a0b..06f8b89ec05 100644
--- a/source/blender/blenkernel/BKE_utildefines.h
+++ b/source/blender/blenkernel/BKE_utildefines.h
@@ -38,4 +38,4 @@ extern "C" {
}
#endif
-#endif // __BKE_UTILDEFINES_H__
+#endif /* __BKE_UTILDEFINES_H__ */
diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt
index efdb80433c6..c5dc7da8edf 100644
--- a/source/blender/blenkernel/CMakeLists.txt
+++ b/source/blender/blenkernel/CMakeLists.txt
@@ -25,7 +25,6 @@
set(INC
.
- ../avi
../blenfont
../blenlib
../blenloader
@@ -194,8 +193,8 @@ set(SRC
BKE_lamp.h
BKE_lattice.h
BKE_library.h
- BKE_mask.h
BKE_main.h
+ BKE_mask.h
BKE_material.h
BKE_mball.h
BKE_mesh.h
@@ -250,7 +249,7 @@ if(WITH_AUDASPACE)
endif()
if(WITH_BULLET)
- list(APPEND INC
+ list(APPEND INC_SYS
../../../extern/bullet2/src
)
add_definitions(-DUSE_BULLET)
@@ -292,6 +291,13 @@ if(WITH_IMAGE_HDR)
add_definitions(-DWITH_HDR)
endif()
+if(WITH_CODEC_AVI)
+ list(APPEND INC
+ ../avi
+ )
+ add_definitions(-DWITH_AVI)
+endif()
+
if(WITH_CODEC_QUICKTIME)
list(APPEND INC
../quicktime
@@ -350,12 +356,6 @@ if(WITH_MOD_OCEANSIM)
add_definitions(-DWITH_OCEANSIM)
endif()
-if(WITH_MOD_DECIMATE)
- list(APPEND INC
- ../../../intern/decimation/extern
- )
-endif()
-
if(WITH_MOD_BOOLEAN)
list(APPEND INC
../../../intern/bsp/extern
diff --git a/source/blender/blenkernel/SConscript b/source/blender/blenkernel/SConscript
index d1a35b122e8..f7b8f59fa57 100644
--- a/source/blender/blenkernel/SConscript
+++ b/source/blender/blenkernel/SConscript
@@ -10,7 +10,7 @@ sources_mask = env.Glob('intern/mask*.c')
incs = '. #/intern/guardedalloc #/intern/memutil'
incs += ' ../blenlib ../blenfont ../makesdna ../windowmanager'
-incs += ' ../render/extern/include #/intern/decimation/extern ../makesrna'
+incs += ' ../render/extern/include ../makesrna'
incs += ' ../imbuf ../ikplugin ../avi #/intern/elbeem/extern ../nodes ../modifiers'
incs += ' #/intern/iksolver/extern ../blenloader'
incs += ' #/extern/bullet2/src'
diff --git a/source/blender/blenkernel/depsgraph_private.h b/source/blender/blenkernel/depsgraph_private.h
index 512b799aeed..12c111f5f16 100644
--- a/source/blender/blenkernel/depsgraph_private.h
+++ b/source/blender/blenkernel/depsgraph_private.h
@@ -61,7 +61,7 @@ typedef struct DagAdjList {
typedef struct DagNode {
int color;
short type;
- float x, y, k;
+ float x, y, k;
void *ob;
void *first_ancestor;
int ancestor_count;
diff --git a/source/blender/blenkernel/intern/CCGSubSurf.c b/source/blender/blenkernel/intern/CCGSubSurf.c
index 387d4775ad4..cc20470b4d5 100644
--- a/source/blender/blenkernel/intern/CCGSubSurf.c
+++ b/source/blender/blenkernel/intern/CCGSubSurf.c
@@ -868,7 +868,7 @@ CCGSubSurf *ccgSubSurf_new(CCGMeshIFC *ifc, int subdivLevels, CCGAllocatorIFC *a
ss->oldVMap = ss->oldEMap = ss->oldFMap = NULL;
ss->lenTempArrays = 0;
ss->tempVerts = NULL;
- ss->tempEdges = NULL;
+ ss->tempEdges = NULL;
return ss;
}
@@ -1397,7 +1397,7 @@ CCGError ccgSubSurf_processSync(CCGSubSurf *ss)
return eCCGError_None;
}
-#define VERT_getNo(e, lvl) _vert_getNo(e, lvl, vertDataSize, normalDataOffset)
+#define VERT_getNo(e, lvl) _vert_getNo(v, lvl, vertDataSize, normalDataOffset)
#define EDGE_getNo(e, lvl, x) _edge_getNo(e, lvl, x, vertDataSize, normalDataOffset)
#define FACE_getIFNo(f, lvl, S, x, y) _face_getIFNo(f, lvl, S, x, y, subdivLevels, vertDataSize, normalDataOffset)
#define FACE_calcIFNo(f, lvl, S, x, y, no) _face_calcIFNo(f, lvl, S, x, y, no, subdivLevels, vertDataSize)
@@ -1491,7 +1491,7 @@ static void ccgSubSurf__calcVertNormals(CCGSubSurf *ss,
/* XXX can I reduce the number of normalisations here? */
for (ptrIdx = 0; ptrIdx < numEffectedV; ptrIdx++) {
CCGVert *v = (CCGVert *) effectedV[ptrIdx];
- float length, *no = _vert_getNo(v, lvl, vertDataSize, normalDataOffset);
+ float length, *no = VERT_getNo(v, lvl);
NormZero(no);
diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c
index 07d14513bd0..fd92b7b5d69 100644
--- a/source/blender/blenkernel/intern/DerivedMesh.c
+++ b/source/blender/blenkernel/intern/DerivedMesh.c
@@ -51,8 +51,6 @@
#include "BLI_utildefines.h"
#include "BLI_linklist.h"
-#include "BLF_translation.h"
-
#include "BKE_cdderivedmesh.h"
#include "BKE_displist.h"
#include "BKE_key.h"
@@ -267,9 +265,11 @@ void DM_init_funcs(DerivedMesh *dm)
dm->getVertData = DM_get_vert_data;
dm->getEdgeData = DM_get_edge_data;
dm->getTessFaceData = DM_get_tessface_data;
+ dm->getPolyData = DM_get_poly_data;
dm->getVertDataArray = DM_get_vert_data_layer;
dm->getEdgeDataArray = DM_get_edge_data_layer;
dm->getTessFaceDataArray = DM_get_tessface_data_layer;
+ dm->getPolyDataArray = DM_get_poly_data_layer;
bvhcache_init(&dm->bvhCache);
}
@@ -289,6 +289,13 @@ void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
dm->needsFree = 1;
dm->auto_bump_scale = -1.0f;
dm->dirty = 0;
+
+ /* don't use CustomData_reset(...); because we dont want to touch customdata */
+ fill_vn_i(dm->vertData.typemap, CD_NUMTYPES, -1);
+ fill_vn_i(dm->edgeData.typemap, CD_NUMTYPES, -1);
+ fill_vn_i(dm->faceData.typemap, CD_NUMTYPES, -1);
+ fill_vn_i(dm->loopData.typemap, CD_NUMTYPES, -1);
+ fill_vn_i(dm->polyData.typemap, CD_NUMTYPES, -1);
}
void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
@@ -385,7 +392,7 @@ void DM_ensure_tessface(DerivedMesh *dm)
}
else if (dm->dirty & DM_DIRTY_TESS_CDLAYERS) {
- BLI_assert(CustomData_has_layer(&dm->faceData, CD_POLYINDEX));
+ BLI_assert(CustomData_has_layer(&dm->faceData, CD_ORIGINDEX));
DM_update_tessface_data(dm);
}
@@ -409,7 +416,7 @@ void DM_update_tessface_data(DerivedMesh *dm)
const int hasPCol = CustomData_has_layer(ldata, CD_PREVIEW_MLOOPCOL);
const int hasOrigSpace = CustomData_has_layer(ldata, CD_ORIGSPACE_MLOOP);
- int *polyindex = CustomData_get_layer(fdata, CD_POLYINDEX);
+ int *polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX);
int mf_idx,
totface = dm->getNumTessFaces(dm),
@@ -466,11 +473,11 @@ void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob)
int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
int did_shapekeys = 0;
- memset(&tmp.vdata, 0, sizeof(tmp.vdata));
- memset(&tmp.edata, 0, sizeof(tmp.edata));
- memset(&tmp.fdata, 0, sizeof(tmp.fdata));
- memset(&tmp.ldata, 0, sizeof(tmp.ldata));
- memset(&tmp.pdata, 0, sizeof(tmp.pdata));
+ CustomData_reset(&tmp.vdata);
+ CustomData_reset(&tmp.edata);
+ CustomData_reset(&tmp.fdata);
+ CustomData_reset(&tmp.ldata);
+ CustomData_reset(&tmp.pdata);
totvert = tmp.totvert = dm->getNumVerts(dm);
totedge = tmp.totedge = dm->getNumEdges(dm);
@@ -578,6 +585,13 @@ void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
CustomData_set_only_copy(&dm->vertData, mask);
CustomData_set_only_copy(&dm->edgeData, mask);
CustomData_set_only_copy(&dm->faceData, mask);
+ /* this wasn't in 2.63 and is disabled for 2.64 because it gives problems with
+ * weight paint mode when there are modifiers applied, needs further investigation,
+ * see replies to r50969, Campbell */
+#if 0
+ CustomData_set_only_copy(&dm->loopData, mask);
+ CustomData_set_only_copy(&dm->polyData, mask);
+#endif
}
void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
@@ -620,6 +634,12 @@ void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
return CustomData_get(&dm->faceData, index, type);
}
+void *DM_get_poly_data(DerivedMesh *dm, int index, int type)
+{
+ return CustomData_get(&dm->polyData, index, type);
+}
+
+
void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
{
if (type == CD_MVERT)
@@ -808,7 +828,7 @@ DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob,
if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr - 1))) {
- key_to_mesh(kb, me);
+ BKE_key_convert_to_mesh(kb, me);
}
if (mti->type == eModifierTypeType_OnlyDeform) {
@@ -878,7 +898,7 @@ static void *get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free
* by a more flexible customdata system, but not simple */
if (!em) {
ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
- KeyBlock *kb = key_get_keyblock(ob_get_key(ob), clmd->sim_parms->shapekey_rest);
+ KeyBlock *kb = BKE_keyblock_from_key(BKE_key_from_object(ob), clmd->sim_parms->shapekey_rest);
if (kb->data)
return kb->data;
@@ -896,7 +916,7 @@ static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int lay
float (*orco)[3];
int free;
- if (em) dm = CDDM_from_BMEditMesh(em, me, FALSE, FALSE);
+ if (em) dm = CDDM_from_editbmesh(em, FALSE, FALSE);
else dm = CDDM_from_mesh(me, ob);
orco = get_orco_coords_dm(ob, em, layer, &free);
@@ -1263,7 +1283,7 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape
int i, j, tot;
if (!me->key)
- return;
+ return;
tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
for (i = 0; i < tot; i++) {
@@ -1276,7 +1296,7 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape
}
if (!kb) {
- kb = add_keyblock(me->key, layer->name);
+ kb = BKE_keyblock_add(me->key, layer->name);
kb->uid = layer->uid;
}
@@ -1368,7 +1388,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
ModifierData *firstmd, *md, *previewmd = NULL;
CDMaskLink *datamasks, *curr;
/* XXX Always copying POLYINDEX, else tessellated data are no more valid! */
- CustomDataMask mask, nextmask, append_mask = CD_MASK_POLYINDEX;
+ CustomDataMask mask, nextmask, append_mask = CD_MASK_ORIGINDEX;
float (*deformedVerts)[3] = NULL;
DerivedMesh *dm = NULL, *orcodm, *clothorcodm, *finaldm;
int numVerts = me->totvert;
@@ -1500,7 +1520,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
if (!modifier_isEnabled(scene, md, required_mode)) continue;
if (mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
- modifier_setError(md, "%s", TIP_("Modifier requires original data, bad stack position."));
+ modifier_setError(md, "Modifier requires original data, bad stack position");
continue;
}
if (sculpt_mode && (!has_multires || multires_applied)) {
@@ -1513,7 +1533,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
unsupported |= multires_applied;
if (unsupported) {
- modifier_setError(md, "%s", TIP_("Not supported in sculpt mode."));
+ modifier_setError(md, "Not supported in sculpt mode");
continue;
}
}
@@ -1796,7 +1816,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
#if 0
if (num_tessface == 0 && finaldm->getNumTessFaces(finaldm) == 0)
#else
- if (finaldm->getNumTessFaces(finaldm) == 0) /* || !CustomData_has_layer(&finaldm->faceData, CD_POLYINDEX)) */
+ if (finaldm->getNumTessFaces(finaldm) == 0) /* || !CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX)) */
#endif
{
finaldm->recalcTessellation(finaldm);
@@ -1804,8 +1824,8 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
/* Even if tessellation is not needed, some modifiers might have modified CD layers
* (like mloopcol or mloopuv), hence we have to update those. */
else if (finaldm->dirty & DM_DIRTY_TESS_CDLAYERS) {
- /* A tessellation already exists, it should always have a CD_POLYINDEX. */
- BLI_assert(CustomData_has_layer(&finaldm->faceData, CD_POLYINDEX));
+ /* A tessellation already exists, it should always have a CD_ORIGINDEX. */
+ BLI_assert(CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX));
DM_update_tessface_data(finaldm);
}
/* Need to watch this, it can cause issues, see bug [#29338] */
@@ -1874,7 +1894,7 @@ int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *d
if (!modifier_isEnabled(scene, md, required_mode)) return 0;
if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
- modifier_setError(md, "%s", TIP_("Modifier requires original data, bad stack position."));
+ modifier_setError(md, "Modifier requires original data, bad stack position");
return 0;
}
@@ -1969,7 +1989,7 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
}
else {
- dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE);
+ dm = CDDM_from_editbmesh(em, FALSE, FALSE);
if (deformedVerts) {
CDDM_apply_vert_coords(dm, deformedVerts);
@@ -2060,12 +2080,18 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
}
else if (dm) {
*final_r = dm;
- (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
+
+ /* once we support skipping normal calculation with modifiers we may want to add this back */
+#if 0 // was added for bmesh but is not needed
+ (*final_r)->calcNormals(*final_r);
+#endif
}
else if (!deformedVerts && cage_r && *cage_r) {
/* cage should already have up to date normals */
*final_r = *cage_r;
- (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
+#if 0 // was added for bmesh but is not needed
+ (*final_r)->calcNormals(*final_r);
+#endif
}
else {
/* this is just a copy of the editmesh, no need to calc normals */
@@ -2242,8 +2268,16 @@ DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask d
{
DerivedMesh *final;
+ /* XXX hack
+ * psys modifier updates particle state when called during dupli-list generation,
+ * which can lead to wrong transforms. This disables particle system modifier execution.
+ */
+ ob->transflag |= OB_NO_PSYS_UPDATE;
+
mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
+ ob->transflag &= ~OB_NO_PSYS_UPDATE;
+
return final;
}
@@ -2413,7 +2447,7 @@ static int GetNumVertsOfFace(const SMikkTSpaceContext *pContext, const int face_
static void GetPosition(const SMikkTSpaceContext *pContext, float fPos[], const int face_num, const int vert_index)
{
- //assert(vert_index>=0 && vert_index<4);
+ //assert(vert_index >= 0 && vert_index < 4);
SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
const float *co = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
copy_v3_v3(fPos, co);
@@ -2421,7 +2455,7 @@ static void GetPosition(const SMikkTSpaceContext *pContext, float fPos[], const
static void GetTextureCoordinate(const SMikkTSpaceContext *pContext, float fUV[], const int face_num, const int vert_index)
{
- //assert(vert_index>=0 && vert_index<4);
+ //assert(vert_index >= 0 && vert_index < 4);
SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
if (pMesh->mtface != NULL) {
@@ -2436,7 +2470,7 @@ static void GetTextureCoordinate(const SMikkTSpaceContext *pContext, float fUV[]
static void GetNormal(const SMikkTSpaceContext *pContext, float fNorm[], const int face_num, const int vert_index)
{
- //assert(vert_index>=0 && vert_index<4);
+ //assert(vert_index >= 0 && vert_index < 4);
SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
@@ -2466,7 +2500,7 @@ static void GetNormal(const SMikkTSpaceContext *pContext, float fNorm[], const i
}
static void SetTSpace(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
{
- //assert(vert_index>=0 && vert_index<4);
+ //assert(vert_index >= 0 && vert_index < 4);
SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
float *pRes = pMesh->tangent[4 * face_num + iVert];
copy_v3_v3(pRes, fvTangent);
@@ -2477,15 +2511,11 @@ static void SetTSpace(const SMikkTSpaceContext *pContext, const float fvTangent[
void DM_add_tangent_layer(DerivedMesh *dm)
{
/* mesh vars */
- MTFace *mtface, *tf;
- MFace *mface, *mf;
- MVert *mvert, *v1, *v2, *v3, *v4;
- MemArena *arena = NULL;
- VertexTangent **vtangents = NULL;
+ MVert *mvert;
+ MTFace *mtface;
+ MFace *mface;
float (*orco)[3] = NULL, (*tangent)[4];
- float *uv1, *uv2, *uv3, *uv4, *vtang;
- float fno[3], tang[3], uv[4][2];
- int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
+ int /* totvert, */ totface;
float *nors;
if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
@@ -2494,7 +2524,7 @@ void DM_add_tangent_layer(DerivedMesh *dm)
nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
/* check we have all the needed layers */
- totvert = dm->getNumVerts(dm);
+ /* totvert = dm->getNumVerts(dm); */ /* UNUSED */
totface = dm->getNumTessFaces(dm);
mvert = dm->getVertArray(dm);
@@ -2511,14 +2541,8 @@ void DM_add_tangent_layer(DerivedMesh *dm)
DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
tangent = DM_get_tessface_data_layer(dm, CD_TANGENT);
- /* allocate some space */
- arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
- BLI_memarena_use_calloc(arena);
- vtangents = MEM_callocN(sizeof(VertexTangent *) * totvert, "VertexTangent");
-
/* new computation method */
- iCalcNewMethod = 1;
- if (iCalcNewMethod != 0) {
+ {
SGLSLMeshToTangent mesh2tangent = {0};
SMikkTSpaceContext sContext = {0};
SMikkTSpaceInterface sInterface = {0};
@@ -2541,87 +2565,13 @@ void DM_add_tangent_layer(DerivedMesh *dm)
sInterface.m_setTSpaceBasic = SetTSpace;
/* 0 if failed */
- iCalcNewMethod = genTangSpaceDefault(&sContext);
+ genTangSpaceDefault(&sContext);
}
-
- if (!iCalcNewMethod) {
- /* sum tangents at connected vertices */
- for (i = 0, tf = mtface, mf = mface; i < totface; mf++, tf++, i++) {
- v1 = &mvert[mf->v1];
- v2 = &mvert[mf->v2];
- v3 = &mvert[mf->v3];
-
- if (mf->v4) {
- v4 = &mvert[mf->v4];
- normal_quad_v3(fno, v4->co, v3->co, v2->co, v1->co);
- }
- else {
- v4 = NULL;
- normal_tri_v3(fno, v3->co, v2->co, v1->co);
- }
-
- if (mtface) {
- uv1 = tf->uv[0];
- uv2 = tf->uv[1];
- uv3 = tf->uv[2];
- uv4 = tf->uv[3];
- }
- else {
- uv1 = uv[0]; uv2 = uv[1]; uv3 = uv[2]; uv4 = uv[3];
- map_to_sphere(&uv[0][0], &uv[0][1], orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
- map_to_sphere(&uv[1][0], &uv[1][1], orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
- map_to_sphere(&uv[2][0], &uv[2][1], orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
- if (v4)
- map_to_sphere(&uv[3][0], &uv[3][1], orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
- }
-
- tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
- sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
- sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
- sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
-
- if (mf->v4) {
- v4 = &mvert[mf->v4];
-
- tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
- sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
- sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
- sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
- }
- }
-
- /* write tangent to layer */
- for (i = 0, tf = mtface, mf = mface; i < totface; mf++, tf++, i++, tangent += 4) {
- len = (mf->v4) ? 4 : 3;
-
- if (mtface == NULL) {
- map_to_sphere(&uv[0][0], &uv[0][1], orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
- map_to_sphere(&uv[1][0], &uv[1][1], orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
- map_to_sphere(&uv[2][0], &uv[2][1], orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
- if (len == 4)
- map_to_sphere(&uv[3][0], &uv[3][1], orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
- }
-
- mf_vi[0] = mf->v1;
- mf_vi[1] = mf->v2;
- mf_vi[2] = mf->v3;
- mf_vi[3] = mf->v4;
-
- for (j = 0; j < len; j++) {
- vtang = find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
- normalize_v3_v3(tangent[j], vtang);
- ((float *) tangent[j])[3] = 1.0f;
- }
- }
- }
-
- BLI_memarena_free(arena);
- MEM_freeN(vtangents);
}
void DM_calc_auto_bump_scale(DerivedMesh *dm)
{
- /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
+ /* int totvert = dm->getNumVerts(dm); */ /* UNUSED */
int totface = dm->getNumTessFaces(dm);
MVert *mvert = dm->getVertArray(dm);
diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c
index 06bf5211abb..e95451252d0 100644
--- a/source/blender/blenkernel/intern/action.c
+++ b/source/blender/blenkernel/intern/action.c
@@ -224,7 +224,7 @@ bActionGroup *get_active_actiongroup(bAction *act)
{
bActionGroup *agrp = NULL;
- if (act && act->groups.first) {
+ if (act && act->groups.first) {
for (agrp = act->groups.first; agrp; agrp = agrp->next) {
if (agrp->flag & AGRP_ACTIVE)
break;
@@ -301,7 +301,7 @@ bActionGroup *action_groups_add_new(bAction *act, const char name[])
/* add to action, and validate */
BLI_addtail(&act->groups, agrp);
- BLI_uniquename(&act->groups, agrp, "Group", '.', offsetof(bActionGroup, name), sizeof(agrp->name));
+ BLI_uniquename(&act->groups, agrp, "Group", '.', offsetof(bActionGroup, name), sizeof(agrp->name));
/* return the new group */
return agrp;
@@ -380,7 +380,7 @@ void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve)
void action_groups_remove_channel(bAction *act, FCurve *fcu)
{
/* sanity checks */
- if (ELEM(NULL, act, fcu))
+ if (ELEM(NULL, act, fcu))
return;
/* check if any group used this directly */
@@ -539,6 +539,7 @@ void BKE_pose_copy_data(bPose **dst, bPose *src, int copycon)
outPose->iksolver = src->iksolver;
outPose->ikdata = NULL;
outPose->ikparam = MEM_dupallocN(src->ikparam);
+ outPose->avs = src->avs;
for (pchan = outPose->chanbase.first; pchan; pchan = pchan->next) {
/* TODO: rename this argument... */
@@ -905,8 +906,8 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_
calc_fcurve_range(fcu, &nmin, &nmax, FALSE, TRUE);
/* compare to the running tally */
- min = MIN2(min, nmin);
- max = MAX2(max, nmax);
+ min = min_ff(min, nmin);
+ max = max_ff(max, nmax);
foundvert = 1;
}
@@ -924,10 +925,10 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_
FMod_Limits *fmd = (FMod_Limits *)fcm->data;
if (fmd->flag & FCM_LIMIT_XMIN) {
- min = MIN2(min, fmd->rect.xmin);
+ min = min_ff(min, fmd->rect.xmin);
}
if (fmd->flag & FCM_LIMIT_XMAX) {
- max = MAX2(max, fmd->rect.xmax);
+ max = max_ff(max, fmd->rect.xmax);
}
}
break;
@@ -954,7 +955,7 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_
foundmod = 1;
}
}
- }
+ }
if (foundvert || foundmod) {
if (min == max) max += 1.0f;
@@ -1214,475 +1215,3 @@ void what_does_obaction(Object *ob, Object *workob, bPose *pose, bAction *act, c
}
}
-/* ********** NLA with non-poses works with ipo channels ********** */
-
-#if 0 // XXX OLD ANIMATION SYSTEM (TO BE REMOVED)
-
-/* ************************ Blending with NLA *************** */
-
-static void blend_pose_strides(bPose *dst, bPose *src, float srcweight, short mode)
-{
- float dstweight;
-
- switch (mode) {
- case ACTSTRIPMODE_BLEND:
- dstweight = 1.0F - srcweight;
- break;
- case ACTSTRIPMODE_ADD:
- dstweight = 1.0F;
- break;
- default:
- dstweight = 1.0F;
- }
-
- interp_v3_v3v3(dst->stride_offset, dst->stride_offset, src->stride_offset, srcweight);
-}
-
-
-/*
- * bone matching diagram, strips A and B
- *
- * .------------------------.
- * | A |
- * '------------------------'
- * . . b2
- * . .-------------v----------.
- * . | B . |
- * . '------------------------'
- * . . .
- * . . .
- * offset: . 0 . A-B . A-b2+B
- * . . .
- *
- * */
-
-
-static void blend_pose_offset_bone(bActionStrip *strip, bPose *dst, bPose *src, float srcweight, short mode)
-{
- /* matching offset bones */
- /* take dst offset, and put src on on that location */
-
- if (strip->offs_bone[0] == 0)
- return;
-
- /* are we also blending with matching bones? */
- if (strip->prev && strip->start >= strip->prev->start) {
- bPoseChannel *dpchan = BKE_pose_channel_find_name(dst, strip->offs_bone);
- if (dpchan) {
- bPoseChannel *spchan = BKE_pose_channel_find_name(src, strip->offs_bone);
- if (spchan) {
- float vec[3];
-
- /* dst->ctime has the internal strip->prev action time */
- /* map this time to nla time */
-
- float ctime = get_actionstrip_frame(strip, src->ctime, 1);
-
- if (ctime > strip->prev->end) {
- bActionChannel *achan;
-
- /* add src to dest, minus the position of src on strip->prev->end */
-
- ctime = get_actionstrip_frame(strip, strip->prev->end, 0);
-
- achan = get_action_channel(strip->act, strip->offs_bone);
- if (achan && achan->ipo) {
- bPoseChannel pchan;
- /* Evaluates and sets the internal ipo value */
- calc_ipo(achan->ipo, ctime);
- /* This call also sets the pchan flags */
- execute_action_ipo(achan, &pchan);
-
- /* store offset that moves src to location of pchan */
- sub_v3_v3v3(vec, dpchan->loc, pchan.loc);
-
- mul_mat3_m4_v3(dpchan->bone->arm_mat, vec);
- }
- }
- else {
- /* store offset that moves src to location of dst */
-
- sub_v3_v3v3(vec, dpchan->loc, spchan->loc);
- mul_mat3_m4_v3(dpchan->bone->arm_mat, vec);
- }
-
- /* if blending, we only add with factor scrweight */
- mul_v3_fl(vec, srcweight);
-
- add_v3_v3(dst->cyclic_offset, vec);
- }
- }
- }
-
- add_v3_v3(dst->cyclic_offset, src->cyclic_offset);
-}
-
-/* added "sizecorr" here, to allow armatures to be scaled and still have striding.
- * Only works for uniform scaling. In general I'd advise against scaling armatures ever though! (ton)
- */
-static float stridechannel_frame(Object *ob, float sizecorr, bActionStrip *strip, Path *path, float pathdist, float *stride_offset)
-{
- bAction *act = strip->act;
- const char *name = strip->stridechannel;
- bActionChannel *achan = get_action_channel(act, name);
- int stride_axis = strip->stride_axis;
-
- if (achan && achan->ipo) {
- IpoCurve *icu = NULL;
- float minx = 0.0f, maxx = 0.0f, miny = 0.0f, maxy = 0.0f;
- int foundvert = 0;
-
- if (stride_axis == 0) stride_axis = AC_LOC_X;
- else if (stride_axis == 1) stride_axis = AC_LOC_Y;
- else stride_axis = AC_LOC_Z;
-
- /* calculate the min/max */
- for (icu = achan->ipo->curve.first; icu; icu = icu->next) {
- if (icu->adrcode == stride_axis) {
- if (icu->totvert > 1) {
- foundvert = 1;
- minx = icu->bezt[0].vec[1][0];
- maxx = icu->bezt[icu->totvert - 1].vec[1][0];
-
- miny = icu->bezt[0].vec[1][1];
- maxy = icu->bezt[icu->totvert - 1].vec[1][1];
- }
- break;
- }
- }
-
- if (foundvert && miny != maxy) {
- float stridelen = sizecorr * fabs(maxy - miny), striptime;
- float actiondist, pdist, pdistNewNormalized, offs;
- float vec1[4], vec2[4], dir[3];
-
- /* internal cycling, actoffs is in frames */
- offs = stridelen * strip->actoffs / (maxx - minx);
-
- /* amount path moves object */
- pdist = (float)fmod(pathdist + offs, stridelen);
- striptime = pdist / stridelen;
-
- /* amount stride bone moves */
- actiondist = sizecorr * eval_icu(icu, minx + striptime * (maxx - minx)) - miny;
-
- pdist = fabs(actiondist) - pdist;
- pdistNewNormalized = (pathdist + pdist) / path->totdist;
-
- /* now we need to go pdist further (or less) on cu path */
- where_on_path(ob, (pathdist) / path->totdist, vec1, dir); /* vec needs size 4 */
- if (pdistNewNormalized <= 1) {
- /* search for correction in positive path-direction */
- where_on_path(ob, pdistNewNormalized, vec2, dir); /* vec needs size 4 */
- sub_v3_v3v3(stride_offset, vec2, vec1);
- }
- else {
- /* we reached the end of the path, search backwards instead */
- where_on_path(ob, (pathdist - pdist) / path->totdist, vec2, dir); /* vec needs size 4 */
- sub_v3_v3v3(stride_offset, vec1, vec2);
- }
- mul_mat3_m4_v3(ob->obmat, stride_offset);
- return striptime;
- }
- }
- return 0.0f;
-}
-
-static void cyclic_offs_bone(Object *ob, bPose *pose, bActionStrip *strip, float time)
-{
- /* only called when strip has cyclic, so >= 1.0f works... */
- if (time >= 1.0f) {
- bActionChannel *achan = get_action_channel(strip->act, strip->offs_bone);
-
- if (achan && achan->ipo) {
- IpoCurve *icu = NULL;
- Bone *bone;
- float min[3] = {0.0f, 0.0f, 0.0f}, max[3] = {0.0f, 0.0f, 0.0f};
- int index = 0, foundvert = 0;
-
- /* calculate the min/max */
- for (icu = achan->ipo->curve.first; icu; icu = icu->next) {
- if (icu->totvert > 1) {
-
- if (icu->adrcode == AC_LOC_X)
- index = 0;
- else if (icu->adrcode == AC_LOC_Y)
- index = 1;
- else if (icu->adrcode == AC_LOC_Z)
- index = 2;
- else
- continue;
-
- foundvert = 1;
- min[index] = icu->bezt[0].vec[1][1];
- max[index] = icu->bezt[icu->totvert - 1].vec[1][1];
- }
- }
- if (foundvert) {
- /* bring it into armature space */
- sub_v3_v3v3(min, max, min);
- bone = BKE_armature_find_bone_name(ob->data, strip->offs_bone); /* weak */
- if (bone) {
- mul_mat3_m4_v3(bone->arm_mat, min);
-
- /* dominant motion, cyclic_offset was cleared in BKE_pose_rest */
- if (strip->flag & (ACTSTRIP_CYCLIC_USEX | ACTSTRIP_CYCLIC_USEY | ACTSTRIP_CYCLIC_USEZ)) {
- if (strip->flag & ACTSTRIP_CYCLIC_USEX) pose->cyclic_offset[0] = time * min[0];
- if (strip->flag & ACTSTRIP_CYCLIC_USEY) pose->cyclic_offset[1] = time * min[1];
- if (strip->flag & ACTSTRIP_CYCLIC_USEZ) pose->cyclic_offset[2] = time * min[2];
- }
- else {
- if (fabsf(min[0]) >= fabsf(min[1]) && fabsf(min[0]) >= fabsf(min[2]))
- pose->cyclic_offset[0] = time * min[0];
- else if (fabsf(min[1]) >= fabsf(min[0]) && fabsf(min[1]) >= fabsf(min[2]))
- pose->cyclic_offset[1] = time * min[1];
- else
- pose->cyclic_offset[2] = time * min[2];
- }
- }
- }
- }
- }
-}
-
-/* simple case for now; only the curve path with constraint value > 0.5 */
-/* blending we might do later... */
-static Object *get_parent_path(Object *ob)
-{
- bConstraint *con;
-
- if (ob->parent && ob->parent->type == OB_CURVE)
- return ob->parent;
-
- for (con = ob->constraints.first; con; con = con->next) {
- if (con->type == CONSTRAINT_TYPE_FOLLOWPATH) {
- if (con->enforce > 0.5f) {
- bFollowPathConstraint *data = con->data;
- return data->tar;
- }
- }
- }
- return NULL;
-}
-
-/* ************** do the action ************ */
-
-/* ----- nla, etc. --------- */
-
-static void do_nla(Scene *scene, Object *ob, int blocktype)
-{
- bPose *tpose = NULL;
- Key *key = NULL;
- ListBase tchanbase = {NULL, NULL}, chanbase = {NULL, NULL};
- bActionStrip *strip, *striplast = NULL, *stripfirst = NULL;
- float striptime, frametime, length, actlength;
- float blendfac, stripframe;
- float scene_cfra = BKE_scene_frame_get(scene);
- int doit, dostride;
-
- if (blocktype == ID_AR) {
- BKE_pose_copy_data(&tpose, ob->pose, 1);
- BKE_pose_rest(ob->pose); // potentially destroying current not-keyed pose
- }
- else {
- key = ob_get_key(ob);
- }
-
- /* check on extend to left or right, when no strip is hit by 'cfra' */
- for (strip = ob->nlastrips.first; strip; strip = strip->next) {
- /* escape loop on a hit */
- if (scene_cfra >= strip->start && scene_cfra <= strip->end + 0.1f) /* note 0.1 comes back below */
- break;
- if (scene_cfra < strip->start) {
- if (stripfirst == NULL)
- stripfirst = strip;
- else if (stripfirst->start > strip->start)
- stripfirst = strip;
- }
- else if (scene_cfra > strip->end) {
- if (striplast == NULL)
- striplast = strip;
- else if (striplast->end < strip->end)
- striplast = strip;
- }
- }
- if (strip == NULL) { /* extend */
- if (striplast)
- scene_cfra = striplast->end;
- else if (stripfirst)
- scene_cfra = stripfirst->start;
- }
-
- /* and now go over all strips */
- for (strip = ob->nlastrips.first; strip; strip = strip->next) {
- doit = dostride = 0;
-
- if (strip->act && !(strip->flag & ACTSTRIP_MUTE)) { /* so theres an action */
-
- /* Determine if the current frame is within the strip's range */
- length = strip->end - strip->start;
- actlength = strip->actend - strip->actstart;
- striptime = (scene_cfra - strip->start) / length;
- stripframe = (scene_cfra - strip->start);
-
- if (striptime >= 0.0) {
-
- if (blocktype == ID_AR)
- BKE_pose_rest(tpose);
-
- /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
- if (striptime < 1.0f + 0.1f / length) {
-
- /* Handle path */
- if ((strip->flag & ACTSTRIP_USESTRIDE) && (blocktype == ID_AR) && (ob->ipoflag & OB_DISABLE_PATH) == 0) {
- Object *parent = get_parent_path(ob);
-
- if (parent) {
- Curve *cu = parent->data;
- float ctime, pdist;
-
- if (cu->flag & CU_PATH) {
- /* Ensure we have a valid path */
- if (cu->path == NULL || cu->path->data == NULL) makeDispListCurveTypes(scene, parent, 0);
- if (cu->path) {
-
- /* Find the position on the path */
- ctime = bsystem_time(scene, ob, scene_cfra, 0.0);
-
- if (calc_ipo_spec(cu->ipo, CU_SPEED, &ctime) == 0) {
- /* correct for actions not starting on zero */
- ctime = (ctime - strip->actstart) / cu->pathlen;
- CLAMP(ctime, 0.0, 1.0);
- }
- pdist = ctime * cu->path->totdist;
-
- if (tpose && strip->stridechannel[0]) {
- striptime = stridechannel_frame(parent, ob->size[0], strip, cu->path, pdist, tpose->stride_offset);
- }
- else {
- if (strip->stridelen) {
- striptime = pdist / strip->stridelen;
- striptime = (float)fmod(striptime + strip->actoffs, 1.0);
- }
- else
- striptime = 0;
- }
-
- frametime = (striptime * actlength) + strip->actstart;
- frametime = bsystem_time(scene, ob, frametime, 0.0);
-
- if (blocktype == ID_AR) {
- extract_pose_from_action(tpose, strip->act, frametime);
- }
- else if (blocktype == ID_OB) {
- extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
- if (key)
- extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
- }
- doit = dostride = 1;
- }
- }
- }
- }
- /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
- else {
-
- /* Mod to repeat */
- if (strip->repeat != 1.0f) {
- float cycle = striptime * strip->repeat;
-
- striptime = (float)fmod(cycle, 1.0f + 0.1f / length);
- cycle -= striptime;
-
- if (blocktype == ID_AR)
- cyclic_offs_bone(ob, tpose, strip, cycle);
- }
-
- frametime = (striptime * actlength) + strip->actstart;
- frametime = nla_time(scene, frametime, (float)strip->repeat);
-
- if (blocktype == ID_AR) {
- extract_pose_from_action(tpose, strip->act, frametime);
- }
- else if (blocktype == ID_OB) {
- extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
- if (key)
- extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
- }
-
- doit = 1;
- }
- }
- /* Handle extend */
- else {
- if (strip->flag & ACTSTRIP_HOLDLASTFRAME) {
- /* we want the strip to hold on the exact fraction of the repeat value */
-
- frametime = actlength * (strip->repeat - (int)strip->repeat);
- if (frametime <= 0.000001f) frametime = actlength; /* rounding errors... */
- frametime = bsystem_time(scene, ob, frametime + strip->actstart, 0.0);
-
- if (blocktype == ID_AR)
- extract_pose_from_action(tpose, strip->act, frametime);
- else if (blocktype == ID_OB) {
- extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
- if (key)
- extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
- }
-
- /* handle cycle hold */
- if (strip->repeat != 1.0f) {
- if (blocktype == ID_AR)
- cyclic_offs_bone(ob, tpose, strip, strip->repeat - 1.0f);
- }
-
- doit = 1;
- }
- }
-
- /* Handle blendin & blendout */
- if (doit) {
- /* Handle blendin */
-
- if (strip->blendin > 0.0 && stripframe <= strip->blendin && scene_cfra >= strip->start) {
- blendfac = stripframe / strip->blendin;
- }
- else if (strip->blendout > 0.0 && stripframe >= (length - strip->blendout) && scene_cfra <= strip->end) {
- blendfac = (length - stripframe) / (strip->blendout);
- }
- else
- blendfac = 1;
-
- if (blocktype == ID_AR) { /* Blend this pose with the accumulated pose */
- /* offset bone, for matching cycles */
- blend_pose_offset_bone(strip, ob->pose, tpose, blendfac, strip->mode);
-
- blend_poses(ob->pose, tpose, blendfac, strip->mode);
- if (dostride)
- blend_pose_strides(ob->pose, tpose, blendfac, strip->mode);
- }
- else {
- blend_ipochannels(&chanbase, &tchanbase, blendfac, strip->mode);
- BLI_freelistN(&tchanbase);
- }
- }
- }
- }
- }
-
- if (blocktype == ID_OB) {
- execute_ipochannels(&chanbase);
- }
- else if (blocktype == ID_AR) {
- /* apply stride offset to object */
- add_v3_v3(ob->obmat[3], ob->pose->stride_offset);
- }
-
- /* free */
- if (tpose)
- BKE_pose_free(tpose);
- if (chanbase.first)
- BLI_freelistN(&chanbase);
-}
-
-#endif // XXX OLD ANIMATION SYSTEM (TO BE REMOVED)
diff --git a/source/blender/blenkernel/intern/anim.c b/source/blender/blenkernel/intern/anim.c
index 1b301ba43b3..dffe26bd782 100644
--- a/source/blender/blenkernel/intern/anim.c
+++ b/source/blender/blenkernel/intern/anim.c
@@ -40,6 +40,8 @@
#include "BLI_rand.h"
#include "BLI_utildefines.h"
+#include "BLF_translation.h"
+
#include "DNA_anim_types.h"
#include "DNA_armature_types.h"
#include "DNA_group_types.h"
@@ -75,7 +77,7 @@
/* forward declarations */
static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int par_index,
- int level, short animated, short update);
+ int level, short flag);
/* ******************************************************************** */
/* Animation Visualization */
@@ -174,10 +176,10 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec
/* avoid 0 size allocs */
if (avs->path_sf >= avs->path_ef) {
BKE_reportf(reports, RPT_ERROR,
- "Motion Path frame extents invalid for %s (%d to %d).%s\n",
+ "Motion path frame extents invalid for %s (%d to %d)%s",
(pchan) ? pchan->name : ob->id.name,
avs->path_sf, avs->path_ef,
- (avs->path_sf == avs->path_ef) ? " Cannot have single-frame paths." : "");
+ (avs->path_sf == avs->path_ef) ? TIP_(", cannot have single-frame paths") : "");
return NULL;
}
@@ -700,7 +702,11 @@ int where_on_path(Object *ob, float ctime, float vec[4], float dir[3], float qua
/* ******************************************************************** */
/* Dupli-Geometry */
-static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, int index, int par_index, int type, short animated)
+#define DUPLILIST_DO_UPDATE 1
+#define DUPLILIST_FOR_RENDER 2
+#define DUPLILIST_ANIMATED 4
+
+static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, int index, int par_index, int type, short flag)
{
DupliObject *dob = MEM_callocN(sizeof(DupliObject), "dupliobject");
@@ -712,14 +718,14 @@ static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], i
dob->index = index;
dob->particle_index = par_index;
dob->type = type;
- dob->animated = (type == OB_DUPLIGROUP) && animated;
+ dob->animated = (type == OB_DUPLIGROUP) && (flag & DUPLILIST_ANIMATED);
ob->lay = lay;
return dob;
}
static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_index,
- int level, short animated, short update)
+ int level, short flag)
{
DupliObject *dob;
Group *group;
@@ -735,13 +741,14 @@ static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_inde
/* handles animated groups, and */
/* we need to check update for objects that are not in scene... */
- if (update) {
+ if (flag & DUPLILIST_DO_UPDATE) {
/* note: update is optional because we don't always need object
* transformations to be correct. Also fixes bug [#29616]. */
group_handle_recalc_and_update(scene, ob, group);
}
- animated = animated || group_is_animated(ob, group);
+ if (group_is_animated(ob, group))
+ flag |= DUPLILIST_ANIMATED;
for (go = group->gobject.first; go; go = go->next) {
/* note, if you check on layer here, render goes wrong... it still deforms verts and uses parent imat */
@@ -757,7 +764,7 @@ static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_inde
mult_m4_m4m4(mat, ob->obmat, go->ob->obmat);
}
- dob = new_dupli_object(lb, go->ob, mat, ob->lay, 0, par_index, OB_DUPLIGROUP, animated);
+ dob = new_dupli_object(lb, go->ob, mat, ob->lay, 0, par_index, OB_DUPLIGROUP, flag);
/* check the group instance and object layers match, also that the object visible flags are ok. */
if ((dob->origlay & group->layer) == 0 ||
@@ -772,14 +779,14 @@ static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_inde
if (go->ob->transflag & OB_DUPLI) {
copy_m4_m4(dob->ob->obmat, dob->mat);
- object_duplilist_recursive(&group->id, scene, go->ob, lb, ob->obmat, par_index, level + 1, animated, update);
+ object_duplilist_recursive(&group->id, scene, go->ob, lb, ob->obmat, par_index, level + 1, flag);
copy_m4_m4(dob->ob->obmat, dob->omat);
}
}
}
}
-static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_index, int level, short animated)
+static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_index, int level, short flag)
{
extern int enable_cu_speed; /* object.c */
Object copyob;
@@ -817,7 +824,7 @@ static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_ind
ok = (ok < ob->dupon);
}
- if (ok) {
+ if (ok) {
DupliObject *dob;
/* WARNING: doing animation updates in this way is not terribly accurate, as the dependencies
@@ -827,7 +834,7 @@ static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_ind
BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, (float)scene->r.cfra, ADT_RECALC_ANIM); /* ob-eval will do drivers, so we don't need to do them */
BKE_object_where_is_calc_time(scene, ob, (float)scene->r.cfra);
- dob = new_dupli_object(lb, ob, ob->obmat, ob->lay, scene->r.cfra, par_index, OB_DUPLIFRAMES, animated);
+ dob = new_dupli_object(lb, ob, ob->obmat, ob->lay, scene->r.cfra, par_index, OB_DUPLIFRAMES, flag);
copy_m4_m4(dob->omat, copyob.obmat);
}
}
@@ -851,8 +858,7 @@ static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_ind
typedef struct VertexDupliData {
ID *id; /* scene or group, for recursive loops */
int level;
- short animated;
- short update;
+ short flag;
ListBase *lb;
float pmat[4][4];
float obmat[4][4]; /* Only used for dupliverts inside dupligroups, where the ob->obmat is modified */
@@ -896,7 +902,7 @@ static void vertex_dupli__mapFunc(void *userData, int index, const float co[3],
origlay = vdd->ob->lay;
- dob = new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index, vdd->par_index, OB_DUPLIVERTS, vdd->animated);
+ dob = new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index, vdd->par_index, OB_DUPLIVERTS, vdd->flag);
/* restore the original layer so that each dupli will have proper dob->origlay */
vdd->ob->lay = origlay;
@@ -908,13 +914,13 @@ static void vertex_dupli__mapFunc(void *userData, int index, const float co[3],
float tmpmat[4][4];
copy_m4_m4(tmpmat, vdd->ob->obmat);
copy_m4_m4(vdd->ob->obmat, obmat); /* pretend we are really this mat */
- object_duplilist_recursive((ID *)vdd->id, vdd->scene, vdd->ob, vdd->lb, obmat, vdd->par_index, vdd->level + 1, vdd->animated, vdd->update);
+ object_duplilist_recursive((ID *)vdd->id, vdd->scene, vdd->ob, vdd->lb, obmat, vdd->par_index, vdd->level + 1, vdd->flag);
copy_m4_m4(vdd->ob->obmat, tmpmat);
}
}
static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int par_index,
- int level, short animated, short update)
+ int level, short flag)
{
Object *ob, *ob_iter;
Mesh *me = par->data;
@@ -942,7 +948,7 @@ static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, fl
else
dm = mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
- if (G.is_rendering) {
+ if (flag & DUPLILIST_FOR_RENDER) {
vdd.orco = (float(*)[3])BKE_mesh_orco_verts_get(par);
BKE_mesh_orco_verts_transform(me, vdd.orco, me->totvert, 0);
}
@@ -964,7 +970,7 @@ static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, fl
}
/* Start looping on Scene OR Group objects */
- while (base || go) {
+ while (base || go) {
if (sce) {
ob_iter = base->object;
oblay = base->lay;
@@ -992,8 +998,7 @@ static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, fl
vdd.id = id;
vdd.level = level;
- vdd.animated = animated;
- vdd.update = update;
+ vdd.flag = flag;
vdd.lb = lb;
vdd.ob = ob;
vdd.scene = scene;
@@ -1039,7 +1044,7 @@ static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, fl
}
static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int par_index,
- int level, short animated, short update)
+ int level, short flag)
{
Object *ob, *ob_iter;
Base *base = NULL;
@@ -1076,8 +1081,7 @@ static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, floa
mloop = dm->getLoopArray(dm);
mvert = dm->getVertArray(dm);
- if (G.is_rendering) {
-
+ if (flag & DUPLILIST_FOR_RENDER) {
orco = (float(*)[3])BKE_mesh_orco_verts_get(par);
BKE_mesh_orco_verts_transform(me, orco, me->totvert, 0);
mloopuv = me->mloopuv;
@@ -1100,7 +1104,7 @@ static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, floa
}
/* Start looping on Scene OR Group objects */
- while (base || go) {
+ while (base || go) {
if (sce) {
ob_iter = base->object;
oblay = base->lay;
@@ -1140,21 +1144,17 @@ static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, floa
float *v3;
/* float *v4; */ /* UNUSED */
float cent[3], quat[4], mat[3][3], mat3[3][3], tmat[4][4], obmat[4][4];
+ float f_no[3];
MLoop *loopstart = mloop + mp->loopstart;
- if (mp->totloop < 3) {
- /* highly unlikely but to be safe */
+ if (UNLIKELY(mp->totloop < 3)) {
continue;
}
else {
+ BKE_mesh_calc_poly_normal(mp, mloop + mp->loopstart, mvert, f_no);
v1 = mvert[(mv1 = loopstart[0].v)].co;
v2 = mvert[(mv2 = loopstart[1].v)].co;
v3 = mvert[(mv3 = loopstart[2].v)].co;
-#if 0
- if (mp->totloop > 3) {
- v4 = mvert[(mv4 = loopstart[3].v)].co;
- }
-#endif
}
/* translation */
@@ -1170,12 +1170,12 @@ static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, floa
copy_v3_v3(obmat[3], cent);
/* rotation */
- tri_to_quat(quat, v1, v2, v3);
+ tri_to_quat_ex(quat, v1, v2, v3, f_no);
quat_to_mat3(mat, quat);
/* scale */
if (par->transflag & OB_DUPLIFACES_SCALE) {
- float size = BKE_mesh_calc_poly_area(mp, loopstart, mvert, NULL);
+ float size = BKE_mesh_calc_poly_area(mp, loopstart, mvert, f_no);
size = sqrtf(size) * par->dupfacesca;
mul_m3_fl(mat, size);
}
@@ -1186,8 +1186,8 @@ static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, floa
copy_m4_m4(tmat, obmat);
mul_m4_m4m3(obmat, tmat, mat);
- dob = new_dupli_object(lb, ob, obmat, par->lay, a, par_index, OB_DUPLIFACES, animated);
- if (G.is_rendering) {
+ dob = new_dupli_object(lb, ob, obmat, par->lay, a, par_index, OB_DUPLIFACES, (flag & DUPLILIST_ANIMATED));
+ if (flag & DUPLILIST_FOR_RENDER) {
w = 1.0f / (float)mp->totloop;
if (orco) {
@@ -1209,7 +1209,7 @@ static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, floa
float tmpmat[4][4];
copy_m4_m4(tmpmat, ob->obmat);
copy_m4_m4(ob->obmat, obmat); /* pretend we are really this mat */
- object_duplilist_recursive((ID *)id, scene, ob, lb, ob->obmat, par_index, level + 1, animated, update);
+ object_duplilist_recursive((ID *)id, scene, ob, lb, ob->obmat, par_index, level + 1, flag);
copy_m4_m4(ob->obmat, tmpmat);
}
}
@@ -1230,7 +1230,7 @@ static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, floa
}
static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int UNUSED(par_index), ParticleSystem *psys,
- int level, short animated, short update)
+ int level, short flag)
{
GroupObject *go;
Object *ob = NULL, **oblist = NULL, obcopy, *obcopylist = NULL;
@@ -1313,7 +1313,7 @@ static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *p
/* gather list of objects or single object */
if (part->ren_as == PART_DRAW_GR) {
- if (update) {
+ if (flag & DUPLILIST_DO_UPDATE) {
group_handle_recalc_and_update(scene, par, part->dup_group);
}
@@ -1456,9 +1456,9 @@ static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *p
else
copy_m4_m4(mat, tmat);
- dob = new_dupli_object(lb, go->ob, mat, par->lay, counter, index, OB_DUPLIPARTS, animated);
+ dob = new_dupli_object(lb, go->ob, mat, par->lay, counter, index, OB_DUPLIPARTS, (flag & DUPLILIST_ANIMATED));
copy_m4_m4(dob->omat, obcopylist[b].obmat);
- if (G.is_rendering)
+ if (flag & DUPLILIST_FOR_RENDER)
psys_get_dupli_texture(psys, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
}
}
@@ -1516,9 +1516,9 @@ static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *p
if (part->draw & PART_DRAW_GLOBAL_OB)
add_v3_v3v3(mat[3], mat[3], vec);
- dob = new_dupli_object(lb, ob, mat, ob->lay, counter, index, GS(id->name) == ID_GR ? OB_DUPLIGROUP : OB_DUPLIPARTS, animated);
+ dob = new_dupli_object(lb, ob, mat, ob->lay, counter, index, GS(id->name) == ID_GR ? OB_DUPLIGROUP : OB_DUPLIPARTS, (flag & DUPLILIST_ANIMATED));
copy_m4_m4(dob->omat, oldobmat);
- if (G.is_rendering)
+ if (flag & DUPLILIST_FOR_RENDER)
psys_get_dupli_texture(psys, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
}
@@ -1570,7 +1570,7 @@ static Object *find_family_object(Object **obar, char *family, char ch)
}
-static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int par_index, int level, short animated)
+static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int par_index, int level, short flag)
{
Object *ob, *obar[256] = {NULL};
Curve *cu;
@@ -1609,7 +1609,7 @@ static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int par_inde
copy_m4_m4(obmat, par->obmat);
copy_v3_v3(obmat[3], vec);
- new_dupli_object(lb, ob, obmat, par->lay, a, par_index, OB_DUPLIVERTS, animated);
+ new_dupli_object(lb, ob, obmat, par->lay, a, par_index, OB_DUPLIVERTS, flag);
}
}
@@ -1619,7 +1619,7 @@ static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int par_inde
/* ------------- */
static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int par_index,
- int level, short animated, short update)
+ int level, short flag)
{
if ((ob->transflag & OB_DUPLI) == 0)
return;
@@ -1639,31 +1639,31 @@ static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBas
if (ob->transflag & OB_DUPLIPARTS) {
ParticleSystem *psys = ob->particlesystem.first;
for (; psys; psys = psys->next)
- new_particle_duplilist(duplilist, id, scene, ob, par_space_mat, par_index, psys, level + 1, animated, update);
+ new_particle_duplilist(duplilist, id, scene, ob, par_space_mat, par_index, psys, level + 1, flag);
}
else if (ob->transflag & OB_DUPLIVERTS) {
if (ob->type == OB_MESH) {
- vertex_duplilist(duplilist, id, scene, ob, par_space_mat, par_index, level + 1, animated, update);
+ vertex_duplilist(duplilist, id, scene, ob, par_space_mat, par_index, level + 1, flag);
}
else if (ob->type == OB_FONT) {
if (GS(id->name) == ID_SCE) { /* TODO - support dupligroups */
- font_duplilist(duplilist, scene, ob, par_index, level + 1, animated);
+ font_duplilist(duplilist, scene, ob, par_index, level + 1, flag);
}
}
}
else if (ob->transflag & OB_DUPLIFACES) {
if (ob->type == OB_MESH)
- face_duplilist(duplilist, id, scene, ob, par_space_mat, par_index, level + 1, animated, update);
+ face_duplilist(duplilist, id, scene, ob, par_space_mat, par_index, level + 1, flag);
}
else if (ob->transflag & OB_DUPLIFRAMES) {
if (GS(id->name) == ID_SCE) { /* TODO - support dupligroups */
- frames_duplilist(duplilist, scene, ob, par_index, level + 1, animated);
+ frames_duplilist(duplilist, scene, ob, par_index, level + 1, flag);
}
}
else if (ob->transflag & OB_DUPLIGROUP) {
DupliObject *dob;
- group_duplilist(duplilist, scene, ob, par_index, level + 1, animated, update); /* now recursive */
+ group_duplilist(duplilist, scene, ob, par_index, level + 1, flag); /* now recursive */
if (level == 0) {
for (dob = duplilist->first; dob; dob = dob->next)
@@ -1675,19 +1675,24 @@ static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBas
/* Returns a list of DupliObject
* note; group dupli's already set transform matrix. see note in group_duplilist() */
-ListBase *object_duplilist_ex(Scene *sce, Object *ob, int update)
+ListBase *object_duplilist_ex(Scene *sce, Object *ob, int update, int for_render)
{
ListBase *duplilist = MEM_mallocN(sizeof(ListBase), "duplilist");
+ int flag = 0;
+
+ if (update) flag |= DUPLILIST_DO_UPDATE;
+ if (for_render) flag |= DUPLILIST_FOR_RENDER;
+
duplilist->first = duplilist->last = NULL;
- object_duplilist_recursive((ID *)sce, sce, ob, duplilist, NULL, 0, 0, 0, update);
+ object_duplilist_recursive((ID *)sce, sce, ob, duplilist, NULL, 0, 0, flag);
return duplilist;
}
/* note: previously updating was always done, this is why it defaults to be on
* but there are likely places it can be called without updating */
-ListBase *object_duplilist(Scene *sce, Object *ob)
+ListBase *object_duplilist(Scene *sce, Object *ob, int for_render)
{
- return object_duplilist_ex(sce, ob, TRUE);
+ return object_duplilist_ex(sce, ob, TRUE, for_render);
}
diff --git a/source/blender/blenkernel/intern/anim_sys.c b/source/blender/blenkernel/intern/anim_sys.c
index 6a3dae93639..66ed31c5b72 100644
--- a/source/blender/blenkernel/intern/anim_sys.c
+++ b/source/blender/blenkernel/intern/anim_sys.c
@@ -188,9 +188,9 @@ short BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act)
else {
/* cannot set */
BKE_reportf(reports, RPT_ERROR,
- "Couldn't set Action '%s' onto ID '%s', as it doesn't have suitably rooted paths for this purpose",
- act->id.name + 2, id->name);
- //ok = 0;
+ "Could not set action '%s' onto ID '%s', as it does not have suitably rooted paths "
+ "for this purpose", act->id.name + 2, id->name);
+ /* ok = 0; */
}
}
else {
@@ -419,7 +419,7 @@ void action_move_fcurves_by_basepath(bAction *srcAct, bAction *dstAct, const cha
/* should F-Curve be moved over?
* - we only need the start of the path to match basepath
*/
- if (animpath_matches_basepath(fcu->rna_path, basepath)) {
+ if (animpath_matches_basepath(fcu->rna_path, basepath)) {
bActionGroup *agrp = NULL;
/* if grouped... */
@@ -574,7 +574,7 @@ static char *rna_path_rename_fix(ID *owner_id, const char *prefix, const char *o
*/
if ( (prefixPtr && oldNamePtr) && (prefixPtr + prefixLen == oldNamePtr) ) {
/* if we haven't aren't able to resolve the path now, try again after fixing it */
- if (!verify_paths || check_rna_path_is_valid(owner_id, oldpath) == 0) {
+ if (!verify_paths || check_rna_path_is_valid(owner_id, oldpath) == 0) {
DynStr *ds = BLI_dynstr_new();
char *postfixPtr = oldNamePtr + oldNameLen;
char *newPath = NULL;
@@ -639,7 +639,7 @@ static void fcurves_path_rename_fix(ID *owner_id, const char *prefix, const char
if (fcu->rna_path != old_path) {
bActionGroup *agrp = fcu->grp;
- if ((agrp) && strcmp(oldName, agrp->name)==0) {
+ if ((agrp) && strcmp(oldName, agrp->name) == 0) {
BLI_strncpy(agrp->name, newName, sizeof(agrp->name));
}
}
@@ -724,7 +724,7 @@ void BKE_animdata_fix_paths_rename(ID *owner_id, AnimData *adt, ID *ref_id, cons
/* pad the names with [" "] so that only exact matches are made */
oldN = BLI_sprintfN("[\"%s\"]", oldName);
newN = BLI_sprintfN("[\"%s\"]", newName);
- }
+ }
else {
oldN = BLI_sprintfN("[%d]", oldSubscript);
newN = BLI_sprintfN("[%d]", newSubscript);
@@ -1239,7 +1239,7 @@ static short animsys_write_rna_setting(PointerRNA *ptr, char *path, int array_in
if (new_ptr.type == &RNA_PoseBone) {
/* bone transforms - update pose (i.e. tag depsgraph) */
skip_updates_hack = 1;
- }
+ }
if (skip_updates_hack == 0)
RNA_property_update_cache_add(&new_ptr, prop);
diff --git a/source/blender/blenkernel/intern/armature.c b/source/blender/blenkernel/intern/armature.c
index b87342f85fa..b3cbc1f2b16 100644
--- a/source/blender/blenkernel/intern/armature.c
+++ b/source/blender/blenkernel/intern/armature.c
@@ -534,10 +534,12 @@ Mat4 *b_bone_spline_setup(bPoseChannel *pchan, int rest)
mul_m4_v3(imat, h2);
/* if next bone is B-bone too, use average handle direction */
- if (next->bone->segments > 1)
- ;
- else
+ if (next->bone->segments > 1) {
+ /* pass */
+ }
+ else {
h2[1] -= length;
+ }
normalize_v3(h2);
/* find the next roll to interpolate as well */
@@ -945,7 +947,7 @@ void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float
}
}
- if (use_dverts || armature_def_nr >= 0) {
+ if (use_dverts || armature_def_nr != -1) {
if (dm)
dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
else if (dverts && i < target_totvert)
@@ -956,7 +958,7 @@ void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float
else
dvert = NULL;
- if (armature_def_nr >= 0 && dvert) {
+ if (armature_def_nr != -1 && dvert) {
armature_weight = defvert_find_weight(dvert, armature_def_nr);
if (invert_vgroup)
@@ -1423,19 +1425,20 @@ void BKE_rotMode_change_values(float quat[4], float eul[3], float axis[3], float
* *************************************************************************** */
/* Computes vector and roll based on a rotation.
* "mat" must contain only a rotation, and no scaling. */
-void mat3_to_vec_roll(float mat[][3], float vec[3], float *roll)
+void mat3_to_vec_roll(float mat[][3], float r_vec[3], float *r_roll)
{
- if (vec)
- copy_v3_v3(vec, mat[1]);
+ if (r_vec) {
+ copy_v3_v3(r_vec, mat[1]);
+ }
- if (roll) {
+ if (r_roll) {
float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
vec_roll_to_mat3(mat[1], 0.0f, vecmat);
invert_m3_m3(vecmatinv, vecmat);
mul_m3_m3m3(rollmat, vecmatinv, mat);
- *roll = (float)atan2(rollmat[2][0], rollmat[2][2]);
+ *r_roll = atan2f(rollmat[2][0], rollmat[2][2]);
}
}
@@ -1459,7 +1462,7 @@ void vec_roll_to_mat3(const float vec[3], const float roll, float mat[][3])
* so a value inbetween these is needed.
*
* was 0.000001, causes bug [#30438] (which is same as [#27675, imho).
- * Reseting it to org value seems to cause no more [#23954]...
+ * Resetting it to org value seems to cause no more [#23954]...
*
* was 0.0000000000001, caused bug [#31333], smaller values give unstable
* roll when toggling editmode again...
@@ -1590,7 +1593,7 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected
if (UNLIKELY(pchanp == NULL)) {
/* happens for proxies that become invalid because of a missing link
- * for regulat cases it shouldn't happen at all */
+ * for regular cases it shouldn't happen at all */
}
else if (pchan->bone->layer & layer_protected) {
ListBase proxylocal_constraints = {NULL, NULL};
diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c
index 99b788e80ce..e1e868b234e 100644
--- a/source/blender/blenkernel/intern/blender.c
+++ b/source/blender/blenkernel/intern/blender.c
@@ -119,7 +119,7 @@ void free_blender(void)
BKE_sequencer_cache_destruct();
IMB_moviecache_destruct();
- free_nodesystem();
+ free_nodesystem();
}
void initglobals(void)
@@ -237,7 +237,7 @@ static void setup_app_data(bContext *C, BlendFileData *bfd, const char *filepath
/* free G.main Main database */
// CTX_wm_manager_set(C, NULL);
- clear_global();
+ clear_global();
/* clear old property update cache, in case some old references are left dangling */
RNA_property_update_cache_free();
@@ -338,7 +338,7 @@ static int handle_subversion_warning(Main *main, ReportList *reports)
(main->minversionfile == BLENDER_VERSION &&
main->minsubversionfile > BLENDER_SUBVERSION))
{
- BKE_reportf(reports, RPT_ERROR, "File written by newer Blender binary: %d.%d, expect loss of data!",
+ BKE_reportf(reports, RPT_ERROR, "File written by newer Blender binary (%d.%d), expect loss of data!",
main->minversionfile, main->minsubversionfile);
}
@@ -407,9 +407,9 @@ int BKE_read_file(bContext *C, const char *filepath, ReportList *reports)
}
else
setup_app_data(C, bfd, filepath); // frees BFD
- }
+ }
else
- BKE_reports_prependf(reports, "Loading %s failed: ", filepath);
+ BKE_reports_prependf(reports, "Loading '%s' failed: ", filepath);
return (bfd ? retval : BKE_READ_FILE_FAIL);
}
@@ -485,7 +485,7 @@ static int read_undosave(bContext *C, UndoElem *uel)
int success = 0, fileflags;
/* This is needed so undoing/redoing doesn't crash with threaded previews going */
- WM_jobs_stop_all(CTX_wm_manager(C));
+ WM_jobs_kill_all_except(CTX_wm_manager(C), CTX_wm_screen(C));
BLI_strncpy(mainstr, G.main->name, sizeof(mainstr)); /* temporal store */
@@ -612,7 +612,7 @@ void BKE_write_undo(bContext *C, const char *name)
}
}
-/* 1= an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation */
+/* 1 = an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation */
void BKE_undo_step(bContext *C, int step)
{
@@ -621,7 +621,9 @@ void BKE_undo_step(bContext *C, int step)
}
else if (step == 1) {
/* curundo should never be NULL, after restart or load file it should call undo_save */
- if (curundo == NULL || curundo->prev == NULL) ; // XXX error("No undo available");
+ if (curundo == NULL || curundo->prev == NULL) {
+ // XXX error("No undo available");
+ }
else {
if (G.debug & G_DEBUG) printf("undo %s\n", curundo->name);
curundo = curundo->prev;
@@ -631,7 +633,9 @@ void BKE_undo_step(bContext *C, int step)
else {
/* curundo has to remain current situation! */
- if (curundo == NULL || curundo->next == NULL) ; // XXX error("No redo available");
+ if (curundo == NULL || curundo->next == NULL) {
+ // XXX error("No redo available");
+ }
else {
read_undosave(C, curundo->next);
curundo = curundo->next;
diff --git a/source/blender/blenkernel/intern/bmfont.c b/source/blender/blenkernel/intern/bmfont.c
index 18161bc6fcb..df7fb2c1807 100644
--- a/source/blender/blenkernel/intern/bmfont.c
+++ b/source/blender/blenkernel/intern/bmfont.c
@@ -96,13 +96,13 @@ void readBitmapFontVersion0(ImBuf * ibuf, unsigned char * rect, int step)
ysize = (bytes + (ibuf->x - 1)) / ibuf->x;
if (ysize < ibuf->y) {
- /* we're first going to copy all data into a liniar buffer.
+ /* we're first going to copy all data into a linear buffer.
* step can be 4 or 1 bytes, and the data is not sequential because
* the bitmap was flipped vertically. */
buffer = MEM_mallocN(bytes, "readBitmapFontVersion0:buffer");
- index = 0;
+ index = 0;
for (i = 0; i < bytes; i++) {
buffer[i] = rect[index];
index += step;
diff --git a/source/blender/blenkernel/intern/boids.c b/source/blender/blenkernel/intern/boids.c
index 79d5e092a10..b6f1b88c912 100644
--- a/source/blender/blenkernel/intern/boids.c
+++ b/source/blender/blenkernel/intern/boids.c
@@ -101,13 +101,15 @@ static int rule_goal_avoid(BoidRule *rule, BoidBrainData *bbd, BoidValues *val,
break;
}
}
- else if (rule->type == eBoidRuleType_Goal && eob == bpa->ground)
- ; /* skip current object */
+ else if (rule->type == eBoidRuleType_Goal && eob == bpa->ground) {
+ /* skip current object */
+ }
else if (pd->forcefield == PFIELD_BOID && mul * pd->f_strength > 0.0f && get_effector_data(cur, &cur_efd, &epoint, 0)) {
float temp = mul * pd->f_strength * effector_falloff(cur, &cur_efd, &epoint, bbd->part->effector_weights);
- if (temp == 0.0f)
- ; /* do nothing */
+ if (temp == 0.0f) {
+ /* do nothing */
+ }
else if (temp > priority) {
priority = temp;
eff = cur;
@@ -954,7 +956,8 @@ void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa)
// }
//}
- bbd->wanted_co[0]=bbd->wanted_co[1]=bbd->wanted_co[2]=bbd->wanted_speed=0.0f;
+ zero_v3(bbd->wanted_co);
+ bbd->wanted_speed = 0.0f;
/* create random seed for every particle & frame */
rand = (int)(PSYS_FRAND(psys->seed + p) * 1000);
@@ -988,7 +991,8 @@ void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa)
add_v3_v3(wanted_co, bbd->wanted_co);
wanted_speed += bbd->wanted_speed;
n++;
- bbd->wanted_co[0]=bbd->wanted_co[1]=bbd->wanted_co[2]=bbd->wanted_speed=0.0f;
+ zero_v3(bbd->wanted_co);
+ bbd->wanted_speed = 0.0f;
}
}
@@ -1168,7 +1172,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa)
/* constrain direction with maximum angular velocity */
angle = saacos(dot_v3v3(old_dir, wanted_dir));
- angle = minf(angle, val.max_ave);
+ angle = min_ff(angle, val.max_ave);
cross_v3_v3v3(nor, old_dir, wanted_dir);
axis_angle_to_quat(q, nor, angle);
@@ -1264,9 +1268,9 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa)
{
float grav[3];
- grav[0]= 0.0f;
- grav[1]= 0.0f;
- grav[2]= bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f;
+ grav[0] = 0.0f;
+ grav[1] = 0.0f;
+ grav[2] = bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f;
/* don't take forward acceleration into account (better banking) */
if (dot_v3v3(bpa->data.acc, pa->state.vel) > 0.0f) {
@@ -1307,9 +1311,9 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa)
{
float grav[3];
- grav[0]= 0.0f;
- grav[1]= 0.0f;
- grav[2]= bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f;
+ grav[0] = 0.0f;
+ grav[1] = 0.0f;
+ grav[2] = bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f;
/* gather apparent gravity */
diff --git a/source/blender/blenkernel/intern/booleanops_mesh.c b/source/blender/blenkernel/intern/booleanops_mesh.c
index be79077bb58..461b945282f 100644
--- a/source/blender/blenkernel/intern/booleanops_mesh.c
+++ b/source/blender/blenkernel/intern/booleanops_mesh.c
@@ -142,7 +142,7 @@ CSG_AddMeshToBlender(
/* Create a new blender mesh object - using 'base' as
* a template for the new object. */
- ob_new= AddNewBlenderMesh(mesh->base);
+ ob_new = AddNewBlenderMesh(mesh->base);
me_new = ob_new->data;
@@ -180,7 +180,7 @@ CSG_PerformOp(
if ((mesh1 == NULL) || (mesh2 == NULL) || (output == NULL)) {
return 0;
- }
+ }
if ((int_op_type < 1) || (int_op_type > 3)) return 0;
switch (int_op_type) {
@@ -203,8 +203,8 @@ CSG_PerformOp(
mesh1->m_face_iterator,
mesh1->m_vertex_iterator,
mesh2->m_face_iterator,
- mesh2->m_vertex_iterator,
- InterpFaceVertexData
+ mesh2->m_vertex_iterator,
+ InterpFaceVertexData
);
}
else {
@@ -215,8 +215,8 @@ CSG_PerformOp(
mesh1->m_face_iterator,
mesh1->m_vertex_iterator,
mesh2->m_face_iterator,
- mesh2->m_vertex_iterator,
- InterpNoUserData
+ mesh2->m_vertex_iterator,
+ InterpNoUserData
);
}
diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c
index fde95e0767e..98b206712d6 100644
--- a/source/blender/blenkernel/intern/brush.c
+++ b/source/blender/blenkernel/intern/brush.c
@@ -529,7 +529,7 @@ void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texf
unsigned char *dst, crgb[3];
const float alpha = BKE_brush_alpha_get(scene, brush);
float brush_rgb[3];
-
+
imbflag = (flt) ? IB_rectfloat : IB_rect;
xoff = -bufsize / 2.0f + 0.5f;
yoff = -bufsize / 2.0f + 0.5f;
@@ -563,7 +563,7 @@ void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texf
else {
BKE_brush_sample_tex(scene, brush, xy, rgba, 0);
mul_v3_v3v3(dstf, rgba, brush_rgb);
- dstf[3] = rgba[3] *alpha *BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
+ dstf[3] = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
}
}
}
@@ -594,7 +594,7 @@ void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texf
else if (texfall == 2) {
BKE_brush_sample_tex(scene, brush, xy, rgba, 0);
mul_v3_v3(rgba, brush->rgb);
- alpha_f = rgba[3] *alpha *BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
+ alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
rgb_float_to_uchar(dst, rgba);
@@ -602,7 +602,7 @@ void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texf
}
else {
BKE_brush_sample_tex(scene, brush, xy, rgba, 0);
- alpha_f = rgba[3] *alpha *BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
+ alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
dst[0] = crgb[0];
dst[1] = crgb[1];
@@ -618,18 +618,18 @@ void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texf
/* Unified Size and Strength */
-// XXX: be careful about setting size and unprojected radius
-// because they depend on one another
-// these functions do not set the other corresponding value
-// this can lead to odd behavior if size and unprojected
-// radius become inconsistent.
-// the biggest problem is that it isn't possible to change
-// unprojected radius because a view context is not
-// available. my ussual solution to this is to use the
-// ratio of change of the size to change the unprojected
-// radius. Not completely convinced that is correct.
-// In anycase, a better solution is needed to prevent
-// inconsistency.
+/* XXX: be careful about setting size and unprojected radius
+ * because they depend on one another
+ * these functions do not set the other corresponding value
+ * this can lead to odd behavior if size and unprojected
+ * radius become inconsistent.
+ * the biggest problem is that it isn't possible to change
+ * unprojected radius because a view context is not
+ * available. my ussual solution to this is to use the
+ * ratio of change of the size to change the unprojected
+ * radius. Not completely convinced that is correct.
+ * In anycase, a better solution is needed to prevent
+ * inconsistency. */
void BKE_brush_size_set(Scene *scene, Brush *brush, int size)
{
@@ -741,7 +741,7 @@ void BKE_brush_scale_unprojected_radius(float *unprojected_radius,
}
/* scale brush size to reflect a change in the brush's unprojected radius */
-void BKE_brush_scale_size(int *BKE_brush_size_get,
+void BKE_brush_scale_size(int *r_brush_size,
float new_unprojected_radius,
float old_unprojected_radius)
{
@@ -749,7 +749,7 @@ void BKE_brush_scale_size(int *BKE_brush_size_get,
/* avoid division by zero */
if (old_unprojected_radius != 0)
scale /= new_unprojected_radius;
- (*BKE_brush_size_get) = (int)((float)(*BKE_brush_size_get) * scale);
+ (*r_brush_size) = (int)((float)(*r_brush_size) * scale);
}
/* Brush Painting */
@@ -876,8 +876,8 @@ static void brush_painter_do_partial(BrushPainter *painter, ImBuf *oldtexibuf,
/* not sure if it's actually needed or it's a mistake in coords/sizes
* calculation in brush_painter_fixed_tex_partial_update(), but without this
* limitation memory gets corrupted at fast strokes with quite big spacing (sergey) */
- w = MIN2(w, ibuf->x);
- h = MIN2(h, ibuf->y);
+ w = min_ii(w, ibuf->x);
+ h = min_ii(h, ibuf->y);
if (painter->cache.flt) {
for (; y < h; y++) {
@@ -1052,13 +1052,13 @@ void BKE_brush_painter_break_stroke(BrushPainter *painter)
static void brush_pressure_apply(BrushPainter *painter, Brush *brush, float pressure)
{
if (BKE_brush_use_alpha_pressure(painter->scene, brush))
- brush_alpha_set(painter->scene, brush, maxf(0.0f, painter->startalpha * pressure));
+ brush_alpha_set(painter->scene, brush, max_ff(0.0f, painter->startalpha * pressure));
if (BKE_brush_use_size_pressure(painter->scene, brush))
- BKE_brush_size_set(painter->scene, brush, maxf(1.0f, painter->startsize * pressure));
+ BKE_brush_size_set(painter->scene, brush, max_ff(1.0f, painter->startsize * pressure));
if (brush->flag & BRUSH_JITTER_PRESSURE)
- brush->jitter = maxf(0.0f, painter->startjitter * pressure);
+ brush->jitter = max_ff(0.0f, painter->startjitter * pressure);
if (brush->flag & BRUSH_SPACING_PRESSURE)
- brush->spacing = maxf(1.0f, painter->startspacing * (1.5f - pressure));
+ brush->spacing = max_ff(1.0f, painter->startspacing * (1.5f - pressure));
}
void BKE_brush_jitter_pos(const Scene *scene, Brush *brush, const float pos[2], float jitterpos[2])
@@ -1158,7 +1158,7 @@ int BKE_brush_painter_paint(BrushPainter *painter, BrushFunc func, const float p
/* compute brush spacing adapted to brush radius, spacing may depend
* on pressure, so update it */
brush_pressure_apply(painter, brush, painter->lastpressure);
- spacing = maxf(1.0f, radius) * brush->spacing * 0.01f;
+ spacing = max_ff(1.0f, radius) * brush->spacing * 0.01f;
/* setup starting distance, direction vector and accumulated distance */
startdistance = painter->accumdistance;
@@ -1176,7 +1176,7 @@ int BKE_brush_painter_paint(BrushPainter *painter, BrushFunc func, const float p
t = step / len;
press = (1.0f - t) * painter->lastpressure + t * pressure;
brush_pressure_apply(painter, brush, press);
- spacing = maxf(1.0f, radius) * brush->spacing * 0.01f;
+ spacing = max_ff(1.0f, radius) * brush->spacing * 0.01f;
BKE_brush_jitter_pos(scene, brush, paintpos, finalpos);
diff --git a/source/blender/blenkernel/intern/bullet.c b/source/blender/blenkernel/intern/bullet.c
index 7defa7e1be3..088031e16a7 100644
--- a/source/blender/blenkernel/intern/bullet.c
+++ b/source/blender/blenkernel/intern/bullet.c
@@ -54,7 +54,7 @@ BulletSoftBody *bsbNew(void)
bsb->viterations = 0;
- bsb->piterations = 2;
+ bsb->piterations = 2;
bsb->diterations = 0;
bsb->citerations = 4;
diff --git a/source/blender/blenkernel/intern/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.c
index 32ae6d04934..ad828a70dd8 100644
--- a/source/blender/blenkernel/intern/bvhutils.c
+++ b/source/blender/blenkernel/intern/bvhutils.c
@@ -358,8 +358,8 @@ float nearest_point_in_tri_surface(const float v0[3], const float v1[3], const f
* BVH from meshs callbacks
*/
-// Callback to bvh tree nearest point. The tree must bust have been built using bvhtree_from_mesh_faces.
-// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree.
+/* Callback to bvh tree nearest point. The tree must bust have been built using bvhtree_from_mesh_faces.
+ * userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. */
static void mesh_faces_nearest_point(void *userdata, int index, const float co[3], BVHTreeNearest *nearest)
{
const BVHTreeFromMesh *data = (BVHTreeFromMesh *) userdata;
@@ -395,8 +395,8 @@ static void mesh_faces_nearest_point(void *userdata, int index, const float co[3
} while (t2);
}
-// Callback to bvh tree raycast. The tree must bust have been built using bvhtree_from_mesh_faces.
-// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree.
+/* Callback to bvh tree raycast. The tree must bust have been built using bvhtree_from_mesh_faces.
+ * userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. */
static void mesh_faces_spherecast(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
{
const BVHTreeFromMesh *data = (BVHTreeFromMesh *) userdata;
@@ -435,8 +435,8 @@ static void mesh_faces_spherecast(void *userdata, int index, const BVHTreeRay *r
} while (t2);
}
-// Callback to bvh tree nearest point. The tree must bust have been built using bvhtree_from_mesh_edges.
-// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree.
+/* Callback to bvh tree nearest point. The tree must bust have been built using bvhtree_from_mesh_edges.
+ * userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. */
static void mesh_edges_nearest_point(void *userdata, int index, const float co[3], BVHTreeNearest *nearest)
{
const BVHTreeFromMesh *data = (BVHTreeFromMesh *) userdata;
@@ -463,12 +463,12 @@ static void mesh_edges_nearest_point(void *userdata, int index, const float co[3
/*
* BVH builders
*/
-// Builds a bvh tree.. where nodes are the vertexs of the given mesh
+/* Builds a bvh tree.. where nodes are the vertexs of the given mesh */
BVHTree *bvhtree_from_mesh_verts(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis)
{
BVHTree *tree = bvhcache_find(&mesh->bvhCache, BVHTREE_FROM_VERTICES);
- //Not in cache
+ /* Not in cache */
if (tree == NULL) {
int i;
int numVerts = mesh->getNumVerts(mesh);
@@ -484,7 +484,7 @@ BVHTree *bvhtree_from_mesh_verts(BVHTreeFromMesh *data, DerivedMesh *mesh, float
BLI_bvhtree_balance(tree);
- //Save on cache for later use
+ /* Save on cache for later use */
// printf("BVHTree built and saved on cache\n");
bvhcache_insert(&mesh->bvhCache, tree, BVHTREE_FROM_VERTICES);
}
@@ -495,15 +495,15 @@ BVHTree *bvhtree_from_mesh_verts(BVHTreeFromMesh *data, DerivedMesh *mesh, float
}
- //Setup BVHTreeFromMesh
+ /* Setup BVHTreeFromMesh */
memset(data, 0, sizeof(*data));
data->tree = tree;
if (data->tree) {
data->cached = TRUE;
- //a NULL nearest callback works fine
- //remeber the min distance to point is the same as the min distance to BV of point
+ /* a NULL nearest callback works fine
+ * remeber the min distance to point is the same as the min distance to BV of point */
data->nearest_callback = NULL;
data->raycast_callback = NULL;
@@ -517,12 +517,12 @@ BVHTree *bvhtree_from_mesh_verts(BVHTreeFromMesh *data, DerivedMesh *mesh, float
return data->tree;
}
-// Builds a bvh tree.. where nodes are the faces of the given mesh.
+/* Builds a bvh tree.. where nodes are the faces of the given mesh. */
BVHTree *bvhtree_from_mesh_faces(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis)
{
BVHTree *tree = bvhcache_find(&mesh->bvhCache, BVHTREE_FROM_FACES);
- //Not in cache
+ /* Not in cache */
if (tree == NULL) {
int i;
int numFaces = mesh->getNumTessFaces(mesh);
@@ -616,7 +616,7 @@ BVHTree *bvhtree_from_mesh_faces(BVHTreeFromMesh *data, DerivedMesh *mesh, float
}
BLI_bvhtree_balance(tree);
- //Save on cache for later use
+ /* Save on cache for later use */
// printf("BVHTree built and saved on cache\n");
bvhcache_insert(&mesh->bvhCache, tree, BVHTREE_FROM_FACES);
}
@@ -627,7 +627,7 @@ BVHTree *bvhtree_from_mesh_faces(BVHTreeFromMesh *data, DerivedMesh *mesh, float
}
- //Setup BVHTreeFromMesh
+ /* Setup BVHTreeFromMesh */
memset(data, 0, sizeof(*data));
data->tree = tree;
@@ -647,12 +647,12 @@ BVHTree *bvhtree_from_mesh_faces(BVHTreeFromMesh *data, DerivedMesh *mesh, float
}
-// Builds a bvh tree.. where nodes are the faces of the given mesh.
+/* Builds a bvh tree.. where nodes are the faces of the given mesh. */
BVHTree *bvhtree_from_mesh_edges(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis)
{
BVHTree *tree = bvhcache_find(&mesh->bvhCache, BVHTREE_FROM_EDGES);
- //Not in cache
+ /* Not in cache */
if (tree == NULL) {
int i;
int numEdges = mesh->getNumEdges(mesh);
@@ -672,7 +672,7 @@ BVHTree *bvhtree_from_mesh_edges(BVHTreeFromMesh *data, DerivedMesh *mesh, float
}
BLI_bvhtree_balance(tree);
- //Save on cache for later use
+ /* Save on cache for later use */
// printf("BVHTree built and saved on cache\n");
bvhcache_insert(&mesh->bvhCache, tree, BVHTREE_FROM_EDGES);
}
@@ -683,7 +683,7 @@ BVHTree *bvhtree_from_mesh_edges(BVHTreeFromMesh *data, DerivedMesh *mesh, float
}
- //Setup BVHTreeFromMesh
+ /* Setup BVHTreeFromMesh */
memset(data, 0, sizeof(*data));
data->tree = tree;
@@ -703,7 +703,7 @@ BVHTree *bvhtree_from_mesh_edges(BVHTreeFromMesh *data, DerivedMesh *mesh, float
}
-// Frees data allocated by a call to bvhtree_from_mesh_*.
+/* Frees data allocated by a call to bvhtree_from_mesh_*. */
void free_bvhtree_from_mesh(struct BVHTreeFromMesh *data)
{
if (data->tree) {
@@ -728,7 +728,7 @@ static void bvhcacheitem_set_if_match(void *_cached, void *_search)
BVHCacheItem *search = (BVHCacheItem *)_search;
if (search->type == cached->type) {
- search->tree = cached->tree;
+ search->tree = cached->tree;
}
}
diff --git a/source/blender/blenkernel/intern/camera.c b/source/blender/blenkernel/intern/camera.c
index ed7ac0e1a32..9118baeae6f 100644
--- a/source/blender/blenkernel/intern/camera.c
+++ b/source/blender/blenkernel/intern/camera.c
@@ -151,7 +151,7 @@ float BKE_camera_object_dof_distance(Object *ob)
Camera *cam = (Camera *)ob->data;
if (ob->type != OB_CAMERA)
return 0.0f;
- if (cam->dof_ob) {
+ if (cam->dof_ob) {
/* too simple, better to return the distance on the view axis only
* return len_v3v3(ob->obmat[3], cam->dof_ob->obmat[3]); */
float mat[4][4], imat[4][4], obmat[4][4];
@@ -262,11 +262,12 @@ void BKE_camera_params_from_view3d(CameraParams *params, View3D *v3d, RegionView
}
else if (rv3d->persp == RV3D_ORTHO) {
/* orthographic view */
+ int sensor_size = BKE_camera_sensor_size(params->sensor_fit, params->sensor_x, params->sensor_y);
params->clipend *= 0.5f; // otherwise too extreme low zbuffer quality
params->clipsta = -params->clipend;
params->is_ortho = TRUE;
- params->ortho_scale = rv3d->dist;
+ params->ortho_scale = rv3d->dist * sensor_size / v3d->lens;
params->zoom = 2.0f;
}
else {
diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c
index b176ed429f8..2e0b3a3c64a 100644
--- a/source/blender/blenkernel/intern/cdderivedmesh.c
+++ b/source/blender/blenkernel/intern/cdderivedmesh.c
@@ -273,6 +273,8 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm)
cddm->pbvh = BLI_pbvh_new();
cddm->pbvh_draw = can_pbvh_draw(ob, dm);
+ pbvh_show_diffuse_color_set(cddm->pbvh, ob->sculpt->show_diffuse_color);
+
BKE_mesh_tessface_ensure(me);
BLI_pbvh_build_mesh(cddm->pbvh, me->mface, me->mvert,
@@ -379,7 +381,7 @@ static void cdDM_drawUVEdges(DerivedMesh *dm)
for (i = 0; i < dm->numTessFaceData; i++, mf++) {
if (!(mf->flag & ME_HIDE)) {
draw = 1;
- }
+ }
else {
draw = 0;
}
@@ -438,7 +440,7 @@ static void cdDM_drawEdges(DerivedMesh *dm, int drawLooseEdges, int drawAllEdges
(drawLooseEdges || !(medge->flag & ME_LOOSEEDGE)))
{
draw = TRUE;
- }
+ }
else {
draw = FALSE;
}
@@ -486,7 +488,7 @@ static void cdDM_drawLooseEdges(DerivedMesh *dm)
for (i = 0; i < dm->numEdgeData; i++, medge++) {
if (medge->flag & ME_LOOSEEDGE) {
draw = 1;
- }
+ }
else {
draw = 0;
}
@@ -552,7 +554,7 @@ static void cdDM_drawFacesSolid(DerivedMesh *dm,
glShadeModel(shademodel = new_shademodel);
glBegin(glmode = new_glmode);
- }
+ }
if (drawCurrentMat) {
if (shademodel == GL_FLAT) {
@@ -612,14 +614,29 @@ static void cdDM_drawFacesTex_common(DerivedMesh *dm,
CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
MVert *mv = cddm->mvert;
MFace *mf = DM_get_tessface_data_layer(dm, CD_MFACE);
- MCol *realcol = dm->getTessFaceDataArray(dm, CD_TEXTURE_MCOL);
float *nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE);
- int i, j, orig, *index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
- int startFace = 0 /*, lastFlag = 0xdeadbeef */ /* UNUSED */;
- MCol *mcol = dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL);
- if (!mcol)
- mcol = dm->getTessFaceDataArray(dm, CD_MCOL);
+ MCol *mcol;
+ int i, orig;
+ int colType, startFace = 0;
+
+ /* double lookup */
+ const int *index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX);
+ if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) {
+ index_mf_to_mpoly = index_mp_to_orig = NULL;
+ }
+
+ colType = CD_TEXTURE_MCOL;
+ mcol = dm->getTessFaceDataArray(dm, colType);
+ if (!mcol) {
+ colType = CD_PREVIEW_MCOL;
+ mcol = dm->getTessFaceDataArray(dm, colType);
+ }
+ if (!mcol) {
+ colType = CD_MCOL;
+ mcol = dm->getTessFaceDataArray(dm, colType);
+ }
cdDM_update_normals_from_pbvh(dm);
@@ -634,8 +651,8 @@ static void cdDM_drawFacesTex_common(DerivedMesh *dm,
draw_option = drawParams(tf ? &tf[i] : NULL, (mcol != NULL), mf->mat_nr);
}
else {
- if (index) {
- orig = *index++;
+ if (index_mf_to_mpoly) {
+ orig = DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, i);
if (orig == ORIGINDEX_NONE) { if (nors) nors += 3; continue; }
if (drawParamsMapped) { draw_option = drawParamsMapped(userData, orig); }
else { if (nors) nors += 3; continue; }
@@ -697,42 +714,11 @@ static void cdDM_drawFacesTex_common(DerivedMesh *dm,
}
}
else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
- MCol *col = realcol;
- if (!col)
- col = mcol;
-
GPU_vertex_setup(dm);
GPU_normal_setup(dm);
GPU_uv_setup(dm);
- if (col != NULL) {
-#if 0
- if (realcol && dm->drawObject->colType == CD_TEXTURE_MCOL) {
- col = 0;
- }
- else if (mcol && dm->drawObject->colType == CD_MCOL) {
- col = 0;
- }
-
- if (col != 0)
-#endif
- {
- unsigned char *colors = MEM_mallocN(dm->getNumTessFaces(dm) * 4 * 3 * sizeof(unsigned char), "cdDM_drawFacesTex_common");
- for (i = 0; i < dm->getNumTessFaces(dm); i++) {
- for (j = 0; j < 4; j++) {
- /* bgr -> rgb is intentional (and stupid), but how its stored internally */
- colors[i * 12 + j * 3] = col[i * 4 + j].b;
- colors[i * 12 + j * 3 + 1] = col[i * 4 + j].g;
- colors[i * 12 + j * 3 + 2] = col[i * 4 + j].r;
- }
- }
- GPU_color3_upload(dm, colors);
- MEM_freeN(colors);
- if (realcol)
- dm->drawObject->colType = CD_TEXTURE_MCOL;
- else if (mcol)
- dm->drawObject->colType = CD_MCOL;
- }
- GPU_color_setup(dm);
+ if (mcol) {
+ GPU_color_setup(dm, colType);
}
if (!GPU_buffer_legacy(dm)) {
@@ -753,15 +739,18 @@ static void cdDM_drawFacesTex_common(DerivedMesh *dm,
draw_option = drawParams(tf ? &tf[actualFace] : NULL, (mcol != NULL), mf[actualFace].mat_nr);
}
else {
- if (index) {
- orig = index[actualFace];
- if (orig == ORIGINDEX_NONE) continue;
- if (drawParamsMapped)
+ if (index_mf_to_mpoly) {
+ orig = DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, actualFace);
+ if (orig == ORIGINDEX_NONE) {
+ continue;
+ }
+ if (drawParamsMapped) {
draw_option = drawParamsMapped(userData, orig);
+ }
}
- else
- if (drawParamsMapped)
+ else if (drawParamsMapped) {
draw_option = drawParamsMapped(userData, actualFace);
+ }
}
/* flush buffer if current triangle isn't drawable or it's last triangle */
@@ -779,7 +768,7 @@ static void cdDM_drawFacesTex_common(DerivedMesh *dm,
int count = (i - startFace + (draw_option != DM_DRAW_OPTION_SKIP ? 1 : 0)) * 3;
if (count) {
- if (col)
+ if (mcol && draw_option != DM_DRAW_OPTION_NO_MCOL)
GPU_color_switch(1);
else
GPU_color_switch(0);
@@ -814,16 +803,32 @@ static void cdDM_drawMappedFaces(DerivedMesh *dm,
CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
MVert *mv = cddm->mvert;
MFace *mf = cddm->mface;
- MCol *mc;
+ MCol *mcol;
float *nors = DM_get_tessface_data_layer(dm, CD_NORMAL);
- int useColors = flag & DM_DRAW_USE_COLORS;
- int i, orig, *index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
+ int colType, useColors = flag & DM_DRAW_USE_COLORS;
+ int i, orig;
+
+
+ /* double lookup */
+ const int *index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX);
+ if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) {
+ index_mf_to_mpoly = index_mp_to_orig = NULL;
+ }
- mc = DM_get_tessface_data_layer(dm, CD_ID_MCOL);
- if (!mc)
- mc = DM_get_tessface_data_layer(dm, CD_PREVIEW_MCOL);
- if (!mc)
- mc = DM_get_tessface_data_layer(dm, CD_MCOL);
+
+ colType = CD_ID_MCOL;
+ mcol = DM_get_tessface_data_layer(dm, colType);
+ if (!mcol) {
+ colType = CD_PREVIEW_MCOL;
+ mcol = DM_get_tessface_data_layer(dm, colType);
+ }
+ if (!mcol) {
+ colType = CD_MCOL;
+ mcol = DM_get_tessface_data_layer(dm, colType);
+ }
+
+ printf("%s: %p(%d/%d)\n", __func__, mcol, CD_ID_MCOL, colType);
cdDM_update_normals_from_pbvh(dm);
@@ -835,7 +840,7 @@ static void cdDM_drawMappedFaces(DerivedMesh *dm,
int drawSmooth = (flag & DM_DRAW_ALWAYS_SMOOTH) ? 1 : (mf->flag & ME_SMOOTH);
DMDrawOption draw_option = DM_DRAW_OPTION_NORMAL;
- orig = (index == NULL) ? i : *index++;
+ orig = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, i) : i;
if (orig == ORIGINDEX_NONE)
draw_option = setMaterial(mf->mat_nr + 1, NULL);
@@ -845,8 +850,8 @@ static void cdDM_drawMappedFaces(DerivedMesh *dm,
if (draw_option != DM_DRAW_OPTION_SKIP) {
unsigned char *cp = NULL;
- if (useColors && mc)
- cp = (unsigned char *)&mc[i * 4];
+ if (useColors && mcol)
+ cp = (unsigned char *)&mcol[i * 4];
/* no need to set shading mode to flat because
* normals are already used to change shading */
@@ -906,8 +911,9 @@ static void cdDM_drawMappedFaces(DerivedMesh *dm,
int prevstart = 0;
GPU_vertex_setup(dm);
GPU_normal_setup(dm);
- if (useColors && mc)
- GPU_color_setup(dm);
+ if (useColors && mcol) {
+ GPU_color_setup(dm, colType);
+ }
if (!GPU_buffer_legacy(dm)) {
int tottri = dm->drawObject->tot_triangle_point / 3;
glShadeModel(GL_SMOOTH);
@@ -934,7 +940,7 @@ static void cdDM_drawMappedFaces(DerivedMesh *dm,
if (i != tottri - 1)
next_actualFace = dm->drawObject->triangle_to_mface[i + 1];
- orig = (index == NULL) ? actualFace : index[actualFace];
+ orig = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, actualFace) : actualFace;
if (orig == ORIGINDEX_NONE)
draw_option = setMaterial(mface->mat_nr + 1, NULL);
@@ -1039,7 +1045,14 @@ static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm,
/* MTFace *tf = dm->getTessFaceDataArray(dm, CD_MTFACE); */ /* UNUSED */
float (*nors)[3] = dm->getTessFaceDataArray(dm, CD_NORMAL);
int a, b, do_draw, matnr, new_matnr;
- int orig, *index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ int orig;
+
+ /* double lookup */
+ const int *index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX);
+ if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) {
+ index_mf_to_mpoly = index_mp_to_orig = NULL;
+ }
cdDM_update_normals_from_pbvh(dm);
@@ -1072,7 +1085,7 @@ static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm,
continue;
}
else if (setDrawOptions) {
- orig = (index) ? index[a] : a;
+ orig = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, a) : a;
if (orig == ORIGINDEX_NONE) {
/* since the material is set by setMaterial(), faces with no
@@ -1176,13 +1189,13 @@ static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm,
datatypes[numdata].size = 2;
datatypes[numdata].type = GL_FLOAT;
numdata++;
- }
+ }
for (b = 0; b < attribs.totmcol; b++) {
datatypes[numdata].index = attribs.mcol[b].gl_index;
datatypes[numdata].size = 4;
datatypes[numdata].type = GL_UNSIGNED_BYTE;
numdata++;
- }
+ }
if (attribs.tottang) {
datatypes[numdata].index = attribs.tang.gl_index;
datatypes[numdata].size = 4;
@@ -1242,7 +1255,7 @@ static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm,
col[0] = cp->b; col[1] = cp->g; col[2] = cp->r; col[3] = cp->a;
copy_v4_v4_char((char *)&varray[elementsize * curface * 3 + offset + elementsize * 2], (char *)col);
offset += sizeof(unsigned char) * 4;
- }
+ }
if (attribs.tottang) {
float *tang = attribs.tang.array[a * 4 + 0];
copy_v4_v4((float *)&varray[elementsize * curface * 3 + offset], tang);
@@ -1283,7 +1296,7 @@ static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm,
col[0] = cp->b; col[1] = cp->g; col[2] = cp->r; col[3] = cp->a;
copy_v4_v4_char((char *)&varray[elementsize * curface * 3 + offset + elementsize * 2], (char *)col);
offset += sizeof(unsigned char) * 4;
- }
+ }
if (attribs.tottang) {
float *tang = attribs.tang.array[a * 4 + 2];
copy_v4_v4((float *)&varray[elementsize * curface * 3 + offset], tang);
@@ -1333,7 +1346,14 @@ static void cdDM_drawMappedFacesMat(DerivedMesh *dm,
MFace *mf = cddm->mface;
float (*nors)[3] = dm->getTessFaceDataArray(dm, CD_NORMAL);
int a, matnr, new_matnr;
- int orig, *index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ int orig;
+
+ /* double lookup */
+ const int *index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX);
+ if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) {
+ index_mf_to_mpoly = index_mp_to_orig = NULL;
+ }
cdDM_update_normals_from_pbvh(dm);
@@ -1362,7 +1382,7 @@ static void cdDM_drawMappedFacesMat(DerivedMesh *dm,
/* skipping faces */
if (setFace) {
- orig = (index) ? index[a] : a;
+ orig = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, a) : a;
if (orig != ORIGINDEX_NONE && !setFace(userData, orig))
continue;
@@ -1525,11 +1545,6 @@ void CDDM_recalc_tessellation_ex(DerivedMesh *dm, const int do_face_nor_cpy)
dm->numTessFaceData, dm->numLoopData, dm->numPolyData,
do_face_nor_cpy);
- if (!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX)) {
- int *polyIndex = CustomData_get_layer(&dm->faceData, CD_POLYINDEX);
- CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_REFERENCE, polyIndex, dm->numTessFaceData);
- }
-
cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
/* Tessellation recreated faceData, and the active layer indices need to get re-propagated
@@ -1641,7 +1656,6 @@ DerivedMesh *CDDM_new(int numVerts, int numEdges, int numTessFaces, int numLoops
CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numTessFaces);
- CustomData_add_layer(&dm->faceData, CD_POLYINDEX, CD_CALLOC, NULL, numTessFaces);
CustomData_add_layer(&dm->polyData, CD_ORIGINDEX, CD_CALLOC, NULL, numPolys);
CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
@@ -1665,7 +1679,6 @@ DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *UNUSED(ob))
DerivedMesh *dm = &cddm->dm;
CustomDataMask mask = CD_MASK_MESH & (~CD_MASK_MDISPS);
int alloctype;
- int *polyindex = NULL;
/* this does a referenced copy, with an exception for fluidsim */
@@ -1680,7 +1693,7 @@ DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *UNUSED(ob))
mesh->totvert);
CustomData_merge(&mesh->edata, &dm->edgeData, mask, alloctype,
mesh->totedge);
- CustomData_merge(&mesh->fdata, &dm->faceData, mask | CD_MASK_POLYINDEX, alloctype,
+ CustomData_merge(&mesh->fdata, &dm->faceData, mask | CD_MASK_ORIGINDEX, alloctype,
mesh->totface);
CustomData_merge(&mesh->ldata, &dm->loopData, mask, alloctype,
mesh->totloop);
@@ -1693,17 +1706,12 @@ DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *UNUSED(ob))
cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
- /* commented since even when CD_POLYINDEX was first added this line fails
+ /* commented since even when CD_ORIGINDEX was first added this line fails
* on the default cube, (after editmode toggle too) - campbell */
#if 0
- BLI_assert(CustomData_has_layer(&cddm->dm.faceData, CD_POLYINDEX));
+ BLI_assert(CustomData_has_layer(&cddm->dm.faceData, CD_ORIGINDEX));
#endif
- polyindex = CustomData_get_layer(&dm->faceData, CD_POLYINDEX);
- if (!CustomData_has_layer(&cddm->dm.faceData, CD_ORIGINDEX)) {
- CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_REFERENCE, polyindex, mesh->totface);
- }
-
return dm;
}
@@ -1789,10 +1797,10 @@ DerivedMesh *CDDM_from_curve_displist(Object *ob, ListBase *dispbase, int **orco
}
static void loops_to_customdata_corners(BMesh *bm, CustomData *facedata,
- int cdindex, BMLoop *l3[3],
+ int cdindex, const BMLoop *l3[3],
int numCol, int numTex)
{
- BMLoop *l;
+ const BMLoop *l;
BMFace *f = l3[0]->f;
MTFace *texface;
MTexPoly *texpoly;
@@ -1835,13 +1843,16 @@ static void loops_to_customdata_corners(BMesh *bm, CustomData *facedata,
}
}
-DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdisps, int use_tessface)
+/* used for both editbmesh and bmesh */
+static DerivedMesh *cddm_from_bmesh_ex(struct BMesh *bm, int use_mdisps,
+ /* EditBMesh vars for use_tessface */
+ int use_tessface,
+ const int em_tottri, const BMLoop *(*em_looptris)[3]
+ )
{
- BMesh *bm = em->bm;
-
DerivedMesh *dm = CDDM_new(bm->totvert,
bm->totedge,
- use_tessface ? em->tottri : 0,
+ use_tessface ? em_tottri : 0,
bm->totloop,
bm->totface);
@@ -1887,7 +1898,7 @@ DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdis
/* add tessellation mface layers */
if (use_tessface) {
- CustomData_from_bmeshpoly(&dm->faceData, &dm->polyData, &dm->loopData, em->tottri);
+ CustomData_from_bmeshpoly(&dm->faceData, &dm->polyData, &dm->loopData, em_tottri);
}
index = dm->getVertDataArray(dm, CD_ORIGINDEX);
@@ -1949,11 +1960,10 @@ DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdis
BM_mesh_elem_index_ensure(bm, BM_FACE);
- polyindex = dm->getTessFaceDataArray(dm, CD_POLYINDEX);
index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
for (i = 0; i < dm->numTessFaceData; i++, index++, polyindex++) {
MFace *mf = &mface[i];
- BMLoop **l = em->looptris[i];
+ const BMLoop **l = em_looptris[i];
efa = l[0]->f;
mf->v1 = BM_elem_index_get(l[0]->v);
@@ -1963,8 +1973,8 @@ DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdis
mf->mat_nr = efa->mat_nr;
mf->flag = BM_face_flag_to_mflag(efa);
- *index = add_orig ? BM_elem_index_get(efa) : *(int *)CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_ORIGINDEX);
- *polyindex = BM_elem_index_get(efa);
+ /* map mfaces to polygons in the same cddm intentionally */
+ *index = BM_elem_index_get(efa);
loops_to_customdata_corners(bm, &dm->faceData, i, l, numCol, numTex);
test_index_face(mf, &dm->faceData, i, 3);
@@ -2003,6 +2013,20 @@ DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdis
return dm;
}
+struct DerivedMesh *CDDM_from_bmesh(struct BMesh *bm, int use_mdisps)
+{
+ return cddm_from_bmesh_ex(bm, use_mdisps, FALSE,
+ /* these vars are for editmesh only */
+ 0, NULL);
+}
+
+DerivedMesh *CDDM_from_editbmesh(BMEditMesh *em, int use_mdisps, int use_tessface)
+{
+ return cddm_from_bmesh_ex(em->bm, use_mdisps,
+ /* editmesh */
+ use_tessface, em->tottri, (const BMLoop *(*)[3])em->looptris);
+}
+
static DerivedMesh *cddm_copy_ex(DerivedMesh *source, int faces_from_tessfaces)
{
CDDerivedMesh *cddm = cdDM_create("CDDM_copy cddm");
@@ -2017,6 +2041,7 @@ static DerivedMesh *cddm_copy_ex(DerivedMesh *source, int faces_from_tessfaces)
source->getVertDataArray(source, CD_ORIGINDEX);
source->getEdgeDataArray(source, CD_ORIGINDEX);
source->getTessFaceDataArray(source, CD_ORIGINDEX);
+ source->getPolyDataArray(source, CD_ORIGINDEX);
/* this initializes dm, and copies all non mvert/medge/mface layers */
DM_from_template(dm, source, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces,
@@ -2071,6 +2096,7 @@ DerivedMesh *CDDM_from_template(DerivedMesh *source,
source->getVertDataArray(source, CD_ORIGINDEX);
source->getEdgeDataArray(source, CD_ORIGINDEX);
source->getTessFaceDataArray(source, CD_ORIGINDEX);
+ source->getPolyDataArray(source, CD_ORIGINDEX);
/* this does a copy of all non mvert/medge/mface layers */
DM_from_template(dm, source, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces, numLoops, numPolys);
@@ -2088,8 +2114,6 @@ DerivedMesh *CDDM_from_template(DerivedMesh *source,
CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
if (!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX))
CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numTessFaces);
- if (!CustomData_get_layer(&dm->faceData, CD_POLYINDEX))
- CustomData_add_layer(&dm->faceData, CD_POLYINDEX, CD_CALLOC, NULL, numTessFaces);
cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
@@ -2154,8 +2178,8 @@ void CDDM_calc_normals_mapping_ex(DerivedMesh *dm, const short only_face_normals
CDDM_recalc_tessellation_ex(dm, FALSE);
}
else {
- /* A tessellation already exists, it should always have a CD_POLYINDEX */
- BLI_assert(CustomData_has_layer(&dm->faceData, CD_POLYINDEX));
+ /* A tessellation already exists, it should always have a CD_ORIGINDEX */
+ BLI_assert(CustomData_has_layer(&dm->faceData, CD_ORIGINDEX));
CustomData_free_layers(&dm->faceData, CD_NORMAL, dm->numTessFaceData);
}
@@ -2165,7 +2189,7 @@ void CDDM_calc_normals_mapping_ex(DerivedMesh *dm, const short only_face_normals
/* calculate face normals */
BKE_mesh_calc_normals_mapping_ex(cddm->mvert, dm->numVertData, CDDM_get_loops(dm), CDDM_get_polys(dm),
dm->numLoopData, dm->numPolyData, NULL, cddm->mface, dm->numTessFaceData,
- CustomData_get_layer(&dm->faceData, CD_POLYINDEX), face_nors,
+ CustomData_get_layer(&dm->faceData, CD_ORIGINDEX), face_nors,
only_face_normals);
CustomData_add_layer(&dm->faceData, CD_NORMAL, CD_ASSIGN,
@@ -2339,7 +2363,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap)
BLI_array_append(oldp, i);
}
- /*create new cddm*/
+ /*create new cddm*/
cddm2 = (CDDerivedMesh *) CDDM_from_template((DerivedMesh *)cddm, BLI_array_count(mvert), BLI_array_count(medge), 0, BLI_array_count(mloop), BLI_array_count(mpoly));
/*update edge indices and copy customdata*/
@@ -2364,7 +2388,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap)
CustomData_copy_data(&dm->loopData, &cddm2->dm.loopData, oldl[i], i, 1);
}
- /*copy vertex customdata*/
+ /*copy vertex customdata*/
mv = mvert;
for (i = 0; i < cddm2->dm.numVertData; i++, mv++) {
CustomData_copy_data(&dm->vertData, &cddm2->dm.vertData, oldv[i], i, 1);
@@ -2439,7 +2463,7 @@ void CDDM_calc_edges_tessface(DerivedMesh *dm)
numEdges = BLI_edgehash_size(eh);
/* write new edges into a temporary CustomData */
- memset(&edgeData, 0, sizeof(edgeData));
+ CustomData_reset(&edgeData);
CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
@@ -2504,7 +2528,7 @@ void CDDM_calc_edges(DerivedMesh *dm)
numEdges = BLI_edgehash_size(eh);
/* write new edges into a temporary CustomData */
- memset(&edgeData, 0, sizeof(edgeData));
+ CustomData_reset(&edgeData);
CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
diff --git a/source/blender/blenkernel/intern/cloth.c b/source/blender/blenkernel/intern/cloth.c
index 4241756a109..f1d73c7777a 100644
--- a/source/blender/blenkernel/intern/cloth.c
+++ b/source/blender/blenkernel/intern/cloth.c
@@ -41,8 +41,6 @@
#include "BLI_utildefines.h"
#include "BLI_linklist.h"
-#include "BLF_translation.h"
-
#include "BKE_cdderivedmesh.h"
#include "BKE_cloth.h"
#include "BKE_effect.h"
@@ -331,7 +329,7 @@ static int do_init_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *resul
cache= clmd->point_cache;
/* initialize simulation data if it didn't exist already */
- if (clmd->clothObject == NULL) {
+ if (clmd->clothObject == NULL) {
if (!cloth_from_object(ob, clmd, result, framenr, 1)) {
BKE_ptcache_invalidate(cache);
return 0;
@@ -773,11 +771,13 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm )
else
verts->goal= 0.0f;
+ /* Reset vertex flags */
+ verts->flags &= ~CLOTH_VERT_FLAG_PINNED;
+ verts->flags &= ~CLOTH_VERT_FLAG_NOSELFCOLL;
+
dvert = dm->getVertData ( dm, i, CD_MDEFORMVERT );
if ( dvert ) {
-
for ( j = 0; j < dvert->totweight; j++ ) {
- verts->flags &= ~CLOTH_VERT_FLAG_PINNED;
if (( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass-1)) && (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )) {
verts->goal = dvert->dw [j].weight;
@@ -789,7 +789,7 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm )
*/
verts->goal = powf(verts->goal, 4.0f);
- if ( verts->goal >=SOFTGOALSNAP )
+ if ( verts->goal >= SOFTGOALSNAP )
verts->flags |= CLOTH_VERT_FLAG_PINNED;
}
@@ -804,7 +804,6 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm )
}
}
- verts->flags &= ~CLOTH_VERT_FLAG_NOSELFCOLL;
if (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF ) {
if ( dvert->dw[j].def_nr == (clmd->coll_parms->vgroup_selfcol-1)) {
if (dvert->dw [j].weight > 0.0f) {
@@ -823,7 +822,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d
int i = 0;
MVert *mvert = NULL;
ClothVertex *verts = NULL;
- float (*shapekey_rest)[3]= NULL;
+ float (*shapekey_rest)[3] = NULL;
float tnull[3] = {0, 0, 0};
Cloth *cloth = NULL;
float maxdist = 0;
@@ -844,7 +843,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d
clmd->clothObject->edgehash = NULL;
}
else if (!clmd->clothObject) {
- modifier_setError(&(clmd->modifier), "%s", TIP_("Out of memory on allocating clmd->clothObject."));
+ modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject");
return 0;
}
@@ -906,7 +905,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d
if ( !cloth_build_springs ( clmd, dm ) ) {
cloth_free_modifier ( clmd );
- modifier_setError(&(clmd->modifier), "%s", TIP_("Can't build springs."));
+ modifier_setError(&(clmd->modifier), "Cannot build springs");
printf("cloth_free_modifier cloth_build_springs\n");
return 0;
}
@@ -948,7 +947,7 @@ static void cloth_from_mesh ( ClothModifierData *clmd, DerivedMesh *dm )
clmd->clothObject->verts = MEM_callocN ( sizeof ( ClothVertex ) * clmd->clothObject->numverts, "clothVertex" );
if ( clmd->clothObject->verts == NULL ) {
cloth_free_modifier ( clmd );
- modifier_setError(&(clmd->modifier), "%s", TIP_("Out of memory on allocating clmd->clothObject->verts."));
+ modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->verts");
printf("cloth_free_modifier clmd->clothObject->verts\n");
return;
}
@@ -958,7 +957,7 @@ static void cloth_from_mesh ( ClothModifierData *clmd, DerivedMesh *dm )
clmd->clothObject->mfaces = MEM_callocN ( sizeof ( MFace ) * clmd->clothObject->numfaces, "clothMFaces" );
if ( clmd->clothObject->mfaces == NULL ) {
cloth_free_modifier ( clmd );
- modifier_setError(&(clmd->modifier), "%s", TIP_("Out of memory on allocating clmd->clothObject->mfaces."));
+ modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->mfaces");
printf("cloth_free_modifier clmd->clothObject->mfaces\n");
return;
}
@@ -1049,29 +1048,25 @@ static void cloth_update_springs( ClothModifierData *clmd )
spring->stiffness = 0.0f;
- if(spring->type == CLOTH_SPRING_TYPE_STRUCTURAL)
- {
+ if (spring->type == CLOTH_SPRING_TYPE_STRUCTURAL) {
spring->stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f;
}
- else if(spring->type == CLOTH_SPRING_TYPE_SHEAR)
- {
+ else if (spring->type == CLOTH_SPRING_TYPE_SHEAR) {
spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
}
- else if(spring->type == CLOTH_SPRING_TYPE_BENDING)
- {
+ else if (spring->type == CLOTH_SPRING_TYPE_BENDING) {
spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
}
- else if(spring->type == CLOTH_SPRING_TYPE_GOAL)
- {
+ else if (spring->type == CLOTH_SPRING_TYPE_GOAL) {
/* Warning: Appending NEW goal springs does not work because implicit solver would need reset! */
/* Activate / Deactivate existing springs */
- if ((!(cloth->verts[spring->ij].flags & CLOTH_VERT_FLAG_PINNED)) && (cloth->verts[spring->ij].goal > ALMOST_ZERO))
+ if ((!(cloth->verts[spring->ij].flags & CLOTH_VERT_FLAG_PINNED)) &&
+ (cloth->verts[spring->ij].goal > ALMOST_ZERO))
{
spring->flags &= ~CLOTH_SPRING_FLAG_DEACTIVATE;
}
- else
- {
+ else {
spring->flags |= CLOTH_SPRING_FLAG_DEACTIVATE;
}
}
diff --git a/source/blender/blenkernel/intern/collision.c b/source/blender/blenkernel/intern/collision.c
index af9bb971d05..b488e683947 100644
--- a/source/blender/blenkernel/intern/collision.c
+++ b/source/blender/blenkernel/intern/collision.c
@@ -161,8 +161,6 @@ void bvhtree_update_from_mvert(BVHTree * bvhtree, MFace *faces, int numfaces, MV
/***********************************
Collision modifier code end
***********************************/
-#define mySWAP(a, b) do { double tmp = b ; b = a ; a = tmp ; } while (0)
-
// w3 is not perfect
static void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3], float p3[3], float *w1, float *w2, float *w3 )
@@ -200,6 +198,9 @@ static void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3
w3[0] = 1.0f - w1[0] - w2[0];
}
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdouble-promotion"
+
DO_INLINE void collision_interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 )
{
zero_v3(to);
@@ -274,7 +275,7 @@ static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionM
/* Decrease in magnitude of relative tangential velocity due to coulomb friction
* in original formula "magrelVel" should be the "change of relative velocity in normal direction" */
- magtangent = minf(clmd->coll_parms->friction * 0.01f * magrelVel, sqrtf(dot_v3v3(vrel_t_pre, vrel_t_pre)));
+ magtangent = min_ff(clmd->coll_parms->friction * 0.01f * magrelVel, sqrtf(dot_v3v3(vrel_t_pre, vrel_t_pre)));
/* Apply friction impulse. */
if ( magtangent > ALMOST_ZERO ) {
@@ -314,8 +315,8 @@ static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionM
/* stay on the safe side and clamp repulse */
if ( impulse > ALMOST_ZERO )
- repulse = MIN2 ( repulse, 5.0*impulse );
- repulse = MAX2 ( impulse, repulse );
+ repulse = min_ff( repulse, 5.0*impulse );
+ repulse = max_ff(impulse, repulse);
impulse = repulse / ( 1.0f + w1*w1 + w2*w2 + w3*w3 ); /* original 2.0 / 0.25 */
VECADDMUL ( i1, collpair->normal, impulse );
@@ -333,12 +334,12 @@ static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionM
* We don't use dt!! */
float spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale;
- float d = clmd->coll_parms->epsilon*8.0f/9.0f + epsilon2*8.0f/9.0f - collpair->distance;
+ float d = clmd->coll_parms->epsilon*8.0f/9.0f + epsilon2*8.0f/9.0f - (float)collpair->distance;
if ( d > ALMOST_ZERO) {
/* stay on the safe side and clamp repulse */
float repulse = d*1.0f/spf;
- float impulse = repulse / ( 3.0 * ( 1.0f + w1*w1 + w2*w2 + w3*w3 )); /* original 2.0 / 0.25 */
+ float impulse = repulse / ( 3.0f * ( 1.0f + w1*w1 + w2*w2 + w3*w3 )); /* original 2.0 / 0.25 */
VECADDMUL ( i1, collpair->normal, impulse );
VECADDMUL ( i2, collpair->normal, impulse );
@@ -370,6 +371,8 @@ static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionM
return result;
}
+#pragma GCC diagnostic pop
+
//Determines collisions on overlap, collisions are written to collpair[i] and collision+number_collision_found is returned
static CollPair* cloth_collision(ModifierData *md1, ModifierData *md2,
BVHTreeOverlap *overlap, CollPair *collpair, float UNUSED(dt))
@@ -460,7 +463,8 @@ static CollPair* cloth_collision(ModifierData *md1, ModifierData *md2,
distance = 2.0 * (double)( epsilon1 + epsilon2 + ALMOST_ZERO );
#endif
- if (distance <= (epsilon1 + epsilon2 + ALMOST_ZERO)) {
+ // distance -1 means no collision result
+ if (distance != -1.0 && (distance <= (double)(epsilon1 + epsilon2 + ALMOST_ZERO))) {
normalize_v3_v3(collpair->normal, collpair->vector);
collpair->distance = distance;
@@ -516,7 +520,7 @@ static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned
if (((modifier_type == eModifierType_Collision) && ob->pd && ob->pd->deflect) || (modifier_type != eModifierType_Collision))
cmd= (CollisionModifierData *)modifiers_findByType(ob, modifier_type);
- if (cmd) {
+ if (cmd) {
/* extend array */
if (*numobj >= *maxobj) {
*maxobj *= 2;
@@ -535,7 +539,7 @@ static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned
/* add objects */
for (go= group->gobject.first; go; go= go->next)
add_collision_object(objs, numobj, maxobj, go->ob, self, level+1, modifier_type);
- }
+ }
}
// return all collision objects in scene
@@ -581,7 +585,7 @@ static void add_collider_cache_object(ListBase **objs, Object *ob, Object *self,
if (ob->pd && ob->pd->deflect)
cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision);
- if (cmd && cmd->bvhtree) {
+ if (cmd && cmd->bvhtree) {
if (*objs == NULL)
*objs = MEM_callocN(sizeof(ListBase), "ColliderCache array");
@@ -739,8 +743,7 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData * clmd, float step, flo
collision_move_object ( collmd, step + dt, step );
}
- do
- {
+ do {
CollPair **collisions, **collisions_index;
ret2 = 0;
@@ -871,7 +874,7 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData * clmd, float step, flo
VECADD ( verts[i].tx, verts[i].tx, temp );
}
else {
- mul_v3_fl(temp, correction * -0.5);
+ mul_v3_fl(temp, correction * -0.5f);
VECADD ( verts[j].tx, verts[j].tx, temp );
sub_v3_v3v3(verts[i].tx, verts[i].tx, temp);
diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c
index 19c8c2cd632..75276adf518 100644
--- a/source/blender/blenkernel/intern/colortools.c
+++ b/source/blender/blenkernel/intern/colortools.c
@@ -65,10 +65,10 @@ void curvemapping_set_defaults(CurveMapping *cumap, int tot, float minx, float m
cumap->flag = CUMA_DO_CLIP;
if (tot == 4) cumap->cur = 3; /* rhms, hack for 'col' curve? */
- clipminx = minf(minx, maxx);
- clipminy = minf(miny, maxy);
- clipmaxx = maxf(minx, maxx);
- clipmaxy = maxf(miny, maxy);
+ clipminx = min_ff(minx, maxx);
+ clipminy = min_ff(miny, maxy);
+ clipmaxx = max_ff(minx, maxx);
+ clipmaxy = max_ff(miny, maxy);
BLI_rctf_init(&cumap->curr, clipminx, clipmaxx, clipminy, clipmaxy);
cumap->clipr = cumap->curr;
@@ -85,7 +85,7 @@ void curvemapping_set_defaults(CurveMapping *cumap, int tot, float minx, float m
cumap->cm[a].curve[0].y = miny;
cumap->cm[a].curve[1].x = maxx;
cumap->cm[a].curve[1].y = maxy;
- }
+ }
cumap->changed_timestamp = 0;
}
@@ -160,7 +160,7 @@ void curvemapping_set_black_white_ex(const float black[3], const float white[3],
int a;
for (a = 0; a < 3; a++) {
- const float delta = maxf(white[a] - black[a], 1e-5f);
+ const float delta = max_ff(white[a] - black[a], 1e-5f);
r_bwmul[a] = 1.0f / delta;
}
}
@@ -182,14 +182,14 @@ void curvemapping_set_black_white(CurveMapping *cumap, const float black[3], con
/* ********** NOTE: requires curvemapping_changed() call after ******** */
/* remove specified point */
-void curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point)
+int curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point)
{
CurveMapPoint *cmp;
int a, b, removed = 0;
/* must have 2 points minimum */
if (cuma->totpoint <= 2)
- return;
+ return FALSE;
cmp = MEM_mallocN((cuma->totpoint) * sizeof(CurveMapPoint), "curve points");
@@ -205,6 +205,7 @@ void curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point)
MEM_freeN(cuma->curve);
cuma->curve = cmp;
cuma->totpoint -= removed;
+ return (removed != 0);
}
/* removes with flag set */
@@ -262,7 +263,7 @@ CurveMapPoint *curvemap_insert(CurveMap *cuma, float x, float y)
return newcmp;
}
-void curvemap_reset(CurveMap *cuma, rctf *clipr, int preset, int slope)
+void curvemap_reset(CurveMap *cuma, const rctf *clipr, int preset, int slope)
{
if (cuma->curve)
MEM_freeN(cuma->curve);
@@ -481,7 +482,7 @@ static float curvemap_calc_extend(const CurveMap *cuma, float x, const float fir
}
/* only creates a table for a single channel in CurveMapping */
-static void curvemap_make_table(CurveMap *cuma, rctf *clipr)
+static void curvemap_make_table(CurveMap *cuma, const rctf *clipr)
{
CurveMapPoint *cmp = cuma->curve;
BezTriple *bezt;
@@ -498,8 +499,8 @@ static void curvemap_make_table(CurveMap *cuma, rctf *clipr)
bezt = MEM_callocN(cuma->totpoint * sizeof(BezTriple), "beztarr");
for (a = 0; a < cuma->totpoint; a++) {
- cuma->mintable = minf(cuma->mintable, cmp[a].x);
- cuma->maxtable = maxf(cuma->maxtable, cmp[a].x);
+ cuma->mintable = min_ff(cuma->mintable, cmp[a].x);
+ cuma->maxtable = max_ff(cuma->maxtable, cmp[a].x);
bezt[a].vec[1][0] = cmp[a].x;
bezt[a].vec[1][1] = cmp[a].y;
if (cmp[a].flag & CUMA_VECTOR)
@@ -555,7 +556,7 @@ static void curvemap_make_table(CurveMap *cuma, rctf *clipr)
sub_v3_v3v3(bezt[a].vec[2], bezt[a].vec[1], vec);
}
}
- }
+ }
/* make the bezier curve */
if (cuma->table)
MEM_freeN(cuma->table);
@@ -679,7 +680,7 @@ void curvemapping_changed(CurveMapping *cumap, int rem_doubles)
CurveMap *cuma = cumap->cm + cumap->cur;
CurveMapPoint *cmp = cuma->curve;
rctf *clipr = &cumap->clipr;
- float thresh = 0.01f * BLI_RCT_SIZE_X(clipr);
+ float thresh = 0.01f * BLI_rctf_size_x(clipr);
float dx = 0.0f, dy = 0.0f;
int a;
@@ -690,13 +691,13 @@ void curvemapping_changed(CurveMapping *cumap, int rem_doubles)
for (a = 0; a < cuma->totpoint; a++) {
if (cmp[a].flag & CUMA_SELECT) {
if (cmp[a].x < clipr->xmin)
- dx = minf(dx, cmp[a].x - clipr->xmin);
+ dx = min_ff(dx, cmp[a].x - clipr->xmin);
else if (cmp[a].x > clipr->xmax)
- dx = maxf(dx, cmp[a].x - clipr->xmax);
+ dx = max_ff(dx, cmp[a].x - clipr->xmax);
if (cmp[a].y < clipr->ymin)
- dy = minf(dy, cmp[a].y - clipr->ymin);
+ dy = min_ff(dy, cmp[a].y - clipr->ymin);
else if (cmp[a].y > clipr->ymax)
- dy = maxf(dy, cmp[a].y - clipr->ymax);
+ dy = max_ff(dy, cmp[a].y - clipr->ymax);
}
}
for (a = 0; a < cuma->totpoint; a++) {
@@ -731,7 +732,7 @@ void curvemapping_changed(CurveMapping *cumap, int rem_doubles)
}
if (a != cuma->totpoint - 1)
curvemap_remove(cuma, 2);
- }
+ }
curvemap_make_table(cuma, clipr);
}
@@ -835,64 +836,6 @@ void curvemapping_evaluate_premulRGB(const CurveMapping *cumap, unsigned char ve
vecout_byte[2] = FTOCHAR(vecout[2]);
}
-
-/* only used for image editor curves */
-void curvemapping_do_ibuf(CurveMapping *cumap, ImBuf *ibuf)
-{
- ImBuf *tmpbuf;
- int pixel;
- float *pix_in;
- float col[3];
- int stride = 4;
- float *pix_out;
-
- if (ibuf == NULL)
- return;
- if (ibuf->rect_float == NULL)
- IMB_float_from_rect(ibuf);
- else if (ibuf->rect == NULL)
- imb_addrectImBuf(ibuf);
-
- if (!ibuf->rect || !ibuf->rect_float)
- return;
-
- /* work on a temp buffer, so can color manage afterwards.
- * No worse off memory wise than comp nodes */
- tmpbuf = IMB_dupImBuf(ibuf);
-
- curvemapping_premultiply(cumap, 0);
-
- pix_in = ibuf->rect_float;
- pix_out = tmpbuf->rect_float;
-
- if (ibuf->channels)
- stride = ibuf->channels;
-
- for (pixel = ibuf->x * ibuf->y; pixel > 0; pixel--, pix_in += stride, pix_out += stride) {
- if (stride < 3) {
- col[0] = curvemap_evaluateF(cumap->cm, *pix_in);
-
- pix_out[1] = pix_out[2] = pix_out[3] = pix_out[0] = col[0];
- }
- else {
- curvemapping_evaluate_premulRGBF(cumap, col, pix_in);
- pix_out[0] = col[0];
- pix_out[1] = col[1];
- pix_out[2] = col[2];
- if (stride > 3)
- pix_out[3] = pix_in[3];
- else
- pix_out[3] = 1.f;
- }
- }
-
- IMB_rect_from_float(tmpbuf);
- SWAP(unsigned int *, tmpbuf->rect, ibuf->rect);
- IMB_freeImBuf(tmpbuf);
-
- curvemapping_premultiply(cumap, 1);
-}
-
int curvemapping_RGBA_does_something(const CurveMapping *cumap)
{
int a;
@@ -1289,9 +1232,9 @@ void BKE_color_managed_display_settings_copy(ColorManagedDisplaySettings *new_se
void BKE_color_managed_view_settings_init(ColorManagedViewSettings *settings)
{
/* OCIO_TODO: use default view transform here when OCIO is completely integrated
- * and proper versioning stuff is added.
- * for now use NONE to be compatible with all current files
- */
+ * and proper versioning stuff is added.
+ * for now use NONE to be compatible with all current files
+ */
BLI_strncpy(settings->view_transform, "Default", sizeof(settings->view_transform));
settings->gamma = 1.0f;
diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c
index 6b9e0921c3b..e300b5e0f19 100644
--- a/source/blender/blenkernel/intern/constraint.c
+++ b/source/blender/blenkernel/intern/constraint.c
@@ -221,51 +221,6 @@ void constraints_clear_evalob(bConstraintOb *cob)
/* -------------- Space-Conversion API -------------- */
-#if 0 /* XXX Old code, does the same as one in armature.c, will remove it later. */
-static void constraint_pchan_diff_mat(bPoseChannel *pchan, float diff_mat[4][4])
-{
- if (pchan->parent) {
- float offs_bone[4][4];
-
- /* construct offs_bone the same way it is done in armature.c */
- copy_m4_m3(offs_bone, pchan->bone->bone_mat);
- copy_v3_v3(offs_bone[3], pchan->bone->head);
- offs_bone[3][1] += pchan->bone->parent->length;
-
- if (pchan->bone->flag & BONE_HINGE) {
- /* pose_mat = par_pose-space_location * chan_mat */
- float tmat[4][4];
-
- /* the rotation of the parent restposition */
- copy_m4_m4(tmat, pchan->bone->parent->arm_mat);
-
- /* the location of actual parent transform */
- copy_v3_v3(tmat[3], offs_bone[3]);
- zero_v3(offs_bone[3]);
- mul_m4_v3(pchan->parent->pose_mat, tmat[3]);
-
- mult_m4_m4m4(diff_mat, tmat, offs_bone);
- }
- else {
- /* pose_mat = par_pose_mat * bone_mat * chan_mat */
- if (pchan->bone->flag & BONE_NO_SCALE) {
- float tmat[4][4];
- copy_m4_m4(tmat, pchan->parent->pose_mat);
- normalize_m4(tmat);
- mult_m4_m4m4(diff_mat, tmat, offs_bone);
- }
- else {
- mult_m4_m4m4(diff_mat, pchan->parent->pose_mat, offs_bone);
- }
- }
- }
- else {
- /* pose_mat = chan_mat * arm_mat */
- copy_m4_m4(diff_mat, pchan->bone->arm_mat);
- }
-}
-#endif
-
/* This function is responsible for the correct transformations/conversions
* of a matrix from one space to another for constraint evaluation.
* For now, this is only implemented for Objects and PoseChannels.
@@ -307,18 +262,6 @@ void constraint_mat_convertspace(Object *ob, bPoseChannel *pchan, float mat[][4]
else if (to == CONSTRAINT_SPACE_LOCAL) {
if (pchan->bone) {
BKE_armature_mat_pose_to_bone(pchan, mat, mat);
-#if 0 /* XXX Old code, will remove it later. */
- constraint_pchan_diff_mat(pchan, diff_mat);
-
- invert_m4_m4(imat, diff_mat);
- mult_m4_m4m4(mat, imat, mat);
-
- /* override with local location */
- if ((pchan->parent) && (pchan->bone->flag & BONE_NO_LOCAL_LOCATION)) {
- BKE_armature_mat_pose_to_bone_ex(ob, pchan, pchan->pose_mat, tempmat);
- copy_v3_v3(mat[3], tempmat[3]);
- }
-#endif
}
}
/* pose to local with parent */
@@ -336,24 +279,19 @@ void constraint_mat_convertspace(Object *ob, bPoseChannel *pchan, float mat[][4]
if (pchan->bone) {
/* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */
BKE_armature_mat_bone_to_pose(pchan, mat, mat);
-#if 0
- constraint_pchan_diff_mat(pchan, diff_mat);
-
- mult_m4_m4m4(mat, diff_mat, mat);
-#endif
}
/* use pose-space as stepping stone for other spaces */
if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_PARLOCAL)) {
/* call self with slightly different values */
constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
- }
+ }
}
break;
case CONSTRAINT_SPACE_PARLOCAL: /* -------------- FROM LOCAL WITH PARENT ---------- */
{
/* local + parent to pose */
- if (pchan->bone) {
+ if (pchan->bone) {
copy_m4_m4(diff_mat, pchan->bone->arm_mat);
mult_m4_m4m4(mat, mat, diff_mat);
}
@@ -432,7 +370,7 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[
/* get DerivedMesh */
if (em) {
/* target is in editmode, so get a special derived mesh */
- dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE);
+ dm = CDDM_from_editbmesh(em, FALSE, FALSE);
freeDM = 1;
}
else {
@@ -604,15 +542,15 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m
float tempmat[4][4], loc[3];
/* interpolate along length of bone */
- interp_v3_v3v3(loc, pchan->pose_head, pchan->pose_tail, headtail);
+ interp_v3_v3v3(loc, pchan->pose_head, pchan->pose_tail, headtail);
/* use interpolated distance for subtarget */
- copy_m4_m4(tempmat, pchan->pose_mat);
+ copy_m4_m4(tempmat, pchan->pose_mat);
copy_v3_v3(tempmat[3], loc);
mult_m4_m4m4(mat, ob->obmat, tempmat);
}
- }
+ }
else
copy_m4_m4(mat, ob->obmat);
@@ -976,11 +914,11 @@ static void vectomat(const float vec[3], const float target_up[3], short axis, s
else negate_v3(n);
/* n specifies the transformation of the track axis */
- if (flags & TARGET_Z_UP) {
+ if (flags & TARGET_Z_UP) {
/* target Z axis is the global up axis */
copy_v3_v3(u, target_up);
}
- else {
+ else {
/* world Z axis is the global up axis */
u[0] = 0;
u[1] = 0;
@@ -1030,12 +968,11 @@ static void trackto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar
if (VALID_CONS_TARGET(ct)) {
float size[3], vec[3];
float totmat[3][3];
- float tmat[4][4];
/* Get size property, since ob->size is only the object's own relative size, not its global one */
mat4_to_size(size, cob->matrix);
- /* Clear the object's rotation */
+ /* Clear the object's rotation */
cob->matrix[0][0] = size[0];
cob->matrix[0][1] = 0;
cob->matrix[0][2] = 0;
@@ -1053,9 +990,8 @@ static void trackto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar
vectomat(vec, ct->matrix[2],
(short)data->reserved1, (short)data->reserved2,
data->flags, totmat);
-
- copy_m4_m4(tmat, cob->matrix);
- mul_m4_m3m4(cob->matrix, totmat, tmat);
+
+ mul_m4_m3m4(cob->matrix, totmat, cob->matrix);
}
}
@@ -1470,7 +1406,7 @@ static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *U
if (data->flag & LIMIT_XMIN) {
if (size[0] < data->xmin)
- size[0] = data->xmin;
+ size[0] = data->xmin;
}
if (data->flag & LIMIT_XMAX) {
if (size[0] > data->xmax)
@@ -1478,7 +1414,7 @@ static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *U
}
if (data->flag & LIMIT_YMIN) {
if (size[1] < data->ymin)
- size[1] = data->ymin;
+ size[1] = data->ymin;
}
if (data->flag & LIMIT_YMAX) {
if (size[1] > data->ymax)
@@ -1486,7 +1422,7 @@ static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *U
}
if (data->flag & LIMIT_ZMIN) {
if (size[2] < data->zmin)
- size[2] = data->zmin;
+ size[2] = data->zmin;
}
if (data->flag & LIMIT_ZMAX) {
if (size[2] > data->zmax)
@@ -2004,7 +1940,7 @@ static void pycon_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintTa
/* this check is to make sure curve objects get updated on file load correctly.*/
if (cu->path == NULL || cu->path->data == NULL) /* only happens on reload file, but violates depsgraph still... fix! */
- BKE_displist_make_curveTypes(cob->scene, ct->tar, 0);
+ BKE_displist_make_curveTypes(cob->scene, ct->tar, 0);
}
/* firstly calculate the matrix the normal way, then let the py-function override
@@ -2281,7 +2217,6 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t
float totmat[3][3];
float tmpmat[3][3];
float invmat[3][3];
- float tmat[4][4];
float mdet;
/* Vector object -> target */
@@ -2509,8 +2444,6 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t
totmat[1][0] = tmpmat[1][0]; totmat[1][1] = tmpmat[1][1]; totmat[1][2] = tmpmat[1][2];
totmat[2][0] = tmpmat[2][0]; totmat[2][1] = tmpmat[2][1]; totmat[2][2] = tmpmat[2][2];
- copy_m4_m4(tmat, cob->matrix);
-
mdet = determinant_m3(totmat[0][0], totmat[0][1], totmat[0][2],
totmat[1][0], totmat[1][1], totmat[1][2],
totmat[2][0], totmat[2][1], totmat[2][2]);
@@ -2519,7 +2452,7 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t
}
/* apply out transformaton to the object */
- mul_m4_m3m4(cob->matrix, totmat, tmat);
+ mul_m4_m3m4(cob->matrix, totmat, cob->matrix);
}
}
@@ -2717,7 +2650,6 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t
if (VALID_CONS_TARGET(ct)) {
float size[3], scale[3], vec[3], xx[3], zz[3], orth[3];
float totmat[3][3];
- float tmat[4][4];
float dist;
/* store scaling before destroying obmat */
@@ -2770,7 +2702,7 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t
default: /* should not happen, but in case*/
return;
} /* switch (data->volmode) */
-
+
/* Clear the object's rotation and scale */
cob->matrix[0][0] = size[0] * scale[0];
cob->matrix[0][1] = 0;
@@ -2793,10 +2725,10 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t
/* othogonal to "new Y" "old X! plane */
cross_v3_v3v3(orth, vec, xx);
normalize_v3(orth);
-
+
/* new Z*/
copy_v3_v3(totmat[2], orth);
-
+
/* we decided to keep X plane*/
cross_v3_v3v3(xx, orth, vec);
normalize_v3_v3(totmat[0], xx);
@@ -2806,18 +2738,17 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t
/* othogonal to "new Y" "old Z! plane */
cross_v3_v3v3(orth, vec, zz);
normalize_v3(orth);
-
+
/* new X */
negate_v3_v3(totmat[0], orth);
-
+
/* we decided to keep Z */
cross_v3_v3v3(zz, orth, vec);
normalize_v3_v3(totmat[2], zz);
break;
} /* switch (data->plane) */
- copy_m4_m4(tmat, cob->matrix);
- mul_m4_m3m4(cob->matrix, totmat, tmat);
+ mul_m4_m3m4(cob->matrix, totmat, cob->matrix);
}
}
@@ -2944,7 +2875,7 @@ static void minmax_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targ
if (data->flag & MINMAX_STICKY) {
if (data->flag & MINMAX_STUCK) {
copy_v3_v3(obmat[3], data->cache);
- }
+ }
else {
copy_v3_v3(data->cache, obmat[3]);
data->flag |= MINMAX_STUCK;
@@ -2954,11 +2885,11 @@ static void minmax_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targ
/* get out of localspace */
mult_m4_m4m4(tmat, ct->matrix, obmat);
copy_m4_m4(cob->matrix, tmat);
- }
- else {
+ }
+ else {
copy_v3_v3(cob->matrix[3], obmat[3]);
}
- }
+ }
else {
data->flag &= ~MINMAX_STUCK;
}
@@ -3298,7 +3229,7 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t
/* extract components of owner's matrix */
copy_v3_v3(loc, cob->matrix[3]);
mat4_to_eulO(eul, cob->rotOrder, cob->matrix);
- mat4_to_size(size, cob->matrix);
+ mat4_to_size(size, cob->matrix);
/* determine where in range current transforms lie */
if (data->expo) {
@@ -3622,7 +3553,7 @@ static void damptrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t
cross_v3_v3v3(raxis, obvec, tarvec);
rangle = dot_v3v3(obvec, tarvec);
- rangle = acos(maxf(-1.0f, minf(1.0f, rangle)));
+ rangle = acos(max_ff(-1.0f, min_ff(1.0f, rangle)));
/* construct rotation matrix from the axis-angle rotation found above
* - this call takes care to make sure that the axis provided is a unit vector first
@@ -4061,32 +3992,36 @@ static void followtrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase
copy_v3_v3(cob->matrix[3], disp);
}
- if (data->depth_ob && data->depth_ob->derivedFinal) {
+ if (data->depth_ob) {
Object *depth_ob = data->depth_ob;
- BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
- BVHTreeRayHit hit;
- float ray_start[3], ray_end[3], ray_nor[3], imat[4][4];
- int result;
+ DerivedMesh *target = object_get_derived_final(depth_ob);
+ if (target) {
+ BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
+ BVHTreeRayHit hit;
+ float ray_start[3], ray_end[3], ray_nor[3], imat[4][4];
+ int result;
- invert_m4_m4(imat, depth_ob->obmat);
+ invert_m4_m4(imat, depth_ob->obmat);
- mul_v3_m4v3(ray_start, imat, camob->obmat[3]);
- mul_v3_m4v3(ray_end, imat, cob->matrix[3]);
+ mul_v3_m4v3(ray_start, imat, camob->obmat[3]);
+ mul_v3_m4v3(ray_end, imat, cob->matrix[3]);
- sub_v3_v3v3(ray_nor, ray_end, ray_start);
+ sub_v3_v3v3(ray_nor, ray_end, ray_start);
- bvhtree_from_mesh_faces(&treeData, depth_ob->derivedFinal, 0.0f, 4, 6);
+ bvhtree_from_mesh_faces(&treeData, target, 0.0f, 4, 6);
- hit.dist = FLT_MAX;
- hit.index = -1;
+ hit.dist = FLT_MAX;
+ hit.index = -1;
- result = BLI_bvhtree_ray_cast(treeData.tree, ray_start, ray_nor, 0.0f, &hit, treeData.raycast_callback, &treeData);
+ result = BLI_bvhtree_ray_cast(treeData.tree, ray_start, ray_nor, 0.0f, &hit, treeData.raycast_callback, &treeData);
- if (result != -1) {
- mul_v3_m4v3(cob->matrix[3], depth_ob->obmat, hit.co);
- }
+ if (result != -1) {
+ mul_v3_m4v3(cob->matrix[3], depth_ob->obmat, hit.co);
+ }
- free_bvhtree_from_mesh(&treeData);
+ free_bvhtree_from_mesh(&treeData);
+ target->release(target);
+ }
}
}
}
@@ -4666,7 +4601,7 @@ short proxylocked_constraints_owner(Object *ob, bPoseChannel *pchan)
else {
/* FIXME: constraints on object-level are not handled well yet */
return 1;
- }
+ }
}
return 0;
@@ -4706,7 +4641,7 @@ void get_constraint_target_matrix(struct Scene *scene, bConstraint *con, int n,
unit_m4(cob->matrix);
unit_m4(cob->startmat);
}
- }
+ }
break;
case CONSTRAINT_OBTYPE_BONE: /* this may occur in some cases */
{
@@ -4842,7 +4777,7 @@ void solve_constraints(ListBase *conlist, bConstraintOb *cob, float ctime)
* since some constraints may not convert the solution back to the input space before blending
* but all are guaranteed to end up in good "worldspace" result
*/
- /* Note: all kind of stuff here before (caused trouble), much easier to just interpolate, or did I miss something? -jahka */
+ /* Note: all kind of stuff here before (caused trouble), much easier to just interpolate, or did I miss something? -jahka (r.32105) */
if (enf < 1.0f) {
float solution[4][4];
copy_m4_m4(solution, cob->matrix);
diff --git a/source/blender/blenkernel/intern/context.c b/source/blender/blenkernel/intern/context.c
index be81c70f261..719ae7357b4 100644
--- a/source/blender/blenkernel/intern/context.c
+++ b/source/blender/blenkernel/intern/context.c
@@ -234,9 +234,8 @@ struct bContextDataResult {
static void *ctx_wm_python_context_get(const bContext *C, const char *member, void *fall_through)
{
#ifdef WITH_PYTHON
- bContextDataResult result;
-
- if (C && CTX_py_dict_get(C)) {
+ if (UNLIKELY(C && CTX_py_dict_get(C))) {
+ bContextDataResult result;
memset(&result, 0, sizeof(bContextDataResult));
BPY_context_member_get((bContext *)C, member, &result);
if (result.ptr.data)
diff --git a/source/blender/blenkernel/intern/curve.c b/source/blender/blenkernel/intern/curve.c
index a2f88781cbb..67aaaceaa38 100644
--- a/source/blender/blenkernel/intern/curve.c
+++ b/source/blender/blenkernel/intern/curve.c
@@ -429,6 +429,33 @@ void BKE_curve_texspace_calc(Curve *cu)
}
}
+int BKE_nurbList_index_get_co(ListBase *nurb, const int index, float r_co[3])
+{
+ Nurb *nu;
+ int tot = 0;
+
+ for (nu = nurb->first; nu; nu = nu->next) {
+ int tot_nu;
+ if (nu->type == CU_BEZIER) {
+ tot_nu = nu->pntsu;
+ if (index - tot < tot_nu) {
+ copy_v3_v3(r_co, nu->bezt[index - tot].vec[1]);
+ return TRUE;
+ }
+ }
+ else {
+ tot_nu = nu->pntsu * nu->pntsv;
+ if (index - tot < tot_nu) {
+ copy_v3_v3(r_co, nu->bp[index - tot].vec);
+ return TRUE;
+ }
+ }
+ tot += tot_nu;
+ }
+
+ return FALSE;
+}
+
int BKE_nurbList_verts_count(ListBase *nurb)
{
Nurb *nu;
@@ -793,8 +820,8 @@ static void basisNurb(float t, short order, short pnts, float *knots, float *bas
/* this is for float inaccuracy */
if (t < knots[0])
t = knots[0];
- else
- if (t > knots[opp2]) t = knots[opp2];
+ else if (t > knots[opp2])
+ t = knots[opp2];
/* this part is order '1' */
o2 = order + 1;
@@ -1023,10 +1050,13 @@ void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu,
MEM_freeN(jend);
}
+/**
+ * \param coord_array Has to be 3 * 4 * pntsu * resolu in size and zero-ed
+ * \param tilt_array set when non-NULL
+ * \param radius_array set when non-NULL
+ */
void BKE_nurb_makeCurve(Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, float *weight_array,
int resolu, int stride)
-/* coord_array has to be 3*4*pntsu*resolu in size and zero-ed
- * tilt_array and radius_array will be written to if valid */
{
BPoint *bp;
float u, ustart, uend, ustep, sumdiv;
@@ -1449,7 +1479,7 @@ void BKE_curve_bevel_make(Scene *scene, Object *ob, ListBase *disp, int forRende
}
}
else if (cu->ext1 == 0.0f && cu->ext2 == 0.0f) {
- ;
+ /* pass */
}
else if (cu->ext2 == 0.0f) {
dl = MEM_callocN(sizeof(DispList), "makebevelcurve2");
@@ -1918,7 +1948,7 @@ static void bevel_list_smooth(BevList *bl, int smooth_iter)
if (bl->poly == -1) { /* check its not cyclic */
/* skip the first point */
- /* bevp0= bevp1; */
+ /* bevp0 = bevp1; */
bevp1 = bevp2;
bevp2++;
nr--;
@@ -1947,7 +1977,7 @@ static void bevel_list_smooth(BevList *bl, int smooth_iter)
interp_qt_qtqt(bevp1->quat, bevp1->quat, q, 0.5);
normalize_qt(bevp1->quat);
- /* bevp0= bevp1; */ /* UNUSED */
+ /* bevp0 = bevp1; */ /* UNUSED */
bevp1 = bevp2;
bevp2++;
}
@@ -2082,7 +2112,7 @@ static void make_bevel_list_3D_tangent(BevList *bl)
BevPoint *bevp2, *bevp1, *bevp0; /* standard for all make_bevel_list_3D_* funcs */
int nr;
- float bevp0_tan[3], cross_tmp[3];
+ float bevp0_tan[3];
bevel_list_calc_bisect(bl);
if (bl->poly == -1) /* check its not cyclic */
@@ -2096,6 +2126,7 @@ static void make_bevel_list_3D_tangent(BevList *bl)
nr = bl->nr;
while (nr--) {
+ float cross_tmp[3];
cross_v3_v3v3(cross_tmp, bevp1->tan, bevp1->dir);
cross_v3_v3v3(bevp1->tan, cross_tmp, bevp1->dir);
normalize_v3(bevp1->tan);
@@ -2123,7 +2154,7 @@ static void make_bevel_list_3D_tangent(BevList *bl)
normalize_v3(cross_tmp);
tri_to_quat(bevp1->quat, zero, cross_tmp, bevp1->tan); /* XXX - could be faster */
- /* bevp0= bevp1; */ /* UNUSED */
+ /* bevp0 = bevp1; */ /* UNUSED */
bevp1 = bevp2;
bevp2++;
}
@@ -2741,7 +2772,7 @@ static void calchandleNurb_intern(BezTriple *bezt, BezTriple *prev, BezTriple *n
if (skip_align) {
/* handles need to be updated during animation and applying stuff like hooks,
- * but in such situatios it's quite difficult to distinguish in which order
+ * but in such situations it's quite difficult to distinguish in which order
* align handles should be aligned so skip them for now */
return;
}
diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c
index 342ee5bba41..93c776ae30e 100644
--- a/source/blender/blenkernel/intern/customdata.c
+++ b/source/blender/blenkernel/intern/customdata.c
@@ -65,11 +65,20 @@
/* number of layers to add when growing a CustomData object */
#define CUSTOMDATA_GROW 5
+/* ensure typemap size is ok */
+BLI_STATIC_ASSERT(sizeof(((CustomData *)NULL)->typemap) /
+ sizeof(((CustomData *)NULL)->typemap[0]) == CD_NUMTYPES,
+ "size mismatch");
+
+
/********************* Layer type information **********************/
typedef struct LayerTypeInfo {
int size; /* the memory size of one element of this layer's data */
- const char *structname; /* name of the struct used, for file writing */
- int structnum; /* number of structs per element, for file writing */
+
+ /** name of the struct used, for file writing */
+ const char *structname;
+ /** number of structs per element, for file writing */
+ int structnum;
/**
* default layer name.
@@ -271,28 +280,6 @@ static void layerInterp_mdeformvert(void **sources, const float *weights,
BLI_linklist_free(dest_dw, linklist_free_simple);
}
-
-static void layerInterp_msticky(void **sources, const float *weights,
- const float *UNUSED(sub_weights), int count, void *dest)
-{
- float co[2], w;
- MSticky *mst;
- int i;
-
- co[0] = co[1] = 0.0f;
- for (i = 0; i < count; i++) {
- w = weights ? weights[i] : 1.0f;
- mst = (MSticky *)sources[i];
-
- madd_v2_v2fl(co, mst->co, w);
- }
-
- /* delay writing to the destination incase dest is in sources */
- mst = (MSticky *)dest;
- copy_v2_v2(mst->co, co);
-}
-
-
static void layerCopy_tface(const void *source, void *dest, int count)
{
const MTFace *source_tf = (const MTFace *)source;
@@ -1055,8 +1042,8 @@ static void layerInterp_mvert_skin(void **sources, const float *weights,
static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
/* 0: CD_MVERT */
{sizeof(MVert), "MVert", 1, NULL, NULL, NULL, NULL, NULL, NULL},
- /* 1: CD_MSTICKY */
- {sizeof(MSticky), "MSticky", 1, NULL, NULL, NULL, layerInterp_msticky, NULL,
+ /* 1: CD_MSTICKY */ /* DEPRECATED */
+ {sizeof(float) * 2, "", 1, NULL, NULL, NULL, NULL, NULL,
NULL},
/* 2: CD_MDEFORMVERT */
{sizeof(MDeformVert), "MDeformVert", 1, NULL, layerCopy_mdeformvert,
@@ -1077,8 +1064,8 @@ static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
/* 8: CD_NORMAL */
/* 3 floats per normal vector */
{sizeof(float) * 3, "vec3f", 1, NULL, NULL, NULL, NULL, NULL, NULL},
- /* 9: CD_POLYINDEX */
- {sizeof(int), "MIntProperty", 1, NULL, NULL, NULL, NULL, NULL, NULL},
+ /* 9: CD_POLYINDEX (deprecated) */
+ {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
/* 10: CD_PROP_FLT */
{sizeof(MFloatProperty), "MFloatProperty", 1, "Float", layerCopy_propFloat, NULL, NULL, NULL},
/* 11: CD_PROP_INT */
@@ -1098,7 +1085,7 @@ static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
layerEqual_mloopuv, layerMultiply_mloopuv, layerInitMinMax_mloopuv,
layerAdd_mloopuv, layerDoMinMax_mloopuv, layerCopyValue_mloopuv},
/* 17: CD_MLOOPCOL */
- {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL,
+ {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL,
layerDefault_mloopcol, layerEqual_mloopcol, layerMultiply_mloopcol, layerInitMinMax_mloopcol,
layerAdd_mloopcol, layerDoMinMax_mloopcol, layerCopyValue_mloopcol},
/* 18: CD_TANGENT */
@@ -1155,7 +1142,7 @@ static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
{sizeof(GridPaintMask), "GridPaintMask", 1, NULL, layerCopy_grid_paint_mask,
layerFree_grid_paint_mask, NULL, NULL, NULL},
/* 36: CD_SKIN_NODE */
- {sizeof(MVertSkin), "MVertSkin", 1, "Skin", NULL, NULL,
+ {sizeof(MVertSkin), "MVertSkin", 1, NULL, NULL, NULL,
layerInterp_mvert_skin, NULL, layerDefault_mvert_skin}
};
@@ -1196,7 +1183,7 @@ const CustomDataMask CD_MASK_DERIVEDMESH =
CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL | CD_MASK_MTEXPOLY | CD_MASK_PREVIEW_MLOOPCOL |
CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORIGSPACE_MLOOP | CD_MASK_ORCO | CD_MASK_TANGENT |
CD_MASK_PREVIEW_MCOL | CD_MASK_NORMAL | CD_MASK_SHAPEKEY | CD_MASK_RECAST |
- CD_MASK_ORIGINDEX | CD_MASK_POLYINDEX | CD_MASK_MVERT_SKIN;
+ CD_MASK_ORIGINDEX | CD_MASK_MVERT_SKIN;
const CustomDataMask CD_MASK_BMESH =
CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL | CD_MASK_MTEXPOLY |
CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_PROP_FLT | CD_MASK_PROP_INT |
@@ -1243,9 +1230,6 @@ void CustomData_update_typemap(CustomData *data)
{
int i, lasttype = -1;
- /* since we cant do in a pre-processor do here as an assert */
- BLI_assert(sizeof(data->typemap) / sizeof(int) >= CD_NUMTYPES);
-
for (i = 0; i < CD_NUMTYPES; i++) {
data->typemap[i] = -1;
}
@@ -1258,6 +1242,13 @@ void CustomData_update_typemap(CustomData *data)
}
}
+static int customdata_typemap_is_valid(const CustomData *data)
+{
+ CustomData data_copy = *data;
+ CustomData_update_typemap(&data_copy);
+ return (memcmp(data->typemap, data_copy.typemap, sizeof(data->typemap)) == 0);
+}
+
void CustomData_merge(const struct CustomData *source, struct CustomData *dest,
CustomDataMask mask, int alloctype, int totelem)
{
@@ -1323,7 +1314,7 @@ void CustomData_merge(const struct CustomData *source, struct CustomData *dest,
void CustomData_copy(const struct CustomData *source, struct CustomData *dest,
CustomDataMask mask, int alloctype, int totelem)
{
- memset(dest, 0, sizeof(*dest));
+ CustomData_reset(dest);
if (source->external)
dest->external = MEM_dupallocN(source->external);
@@ -1354,6 +1345,12 @@ static void CustomData_external_free(CustomData *data)
}
}
+void CustomData_reset(CustomData *data)
+{
+ memset(data, 0, sizeof(*data));
+ fill_vn_i(data->typemap, CD_NUMTYPES, -1);
+}
+
void CustomData_free(CustomData *data, int totelem)
{
int i;
@@ -1365,8 +1362,7 @@ void CustomData_free(CustomData *data, int totelem)
MEM_freeN(data->layers);
CustomData_external_free(data);
-
- memset(data, 0, sizeof(*data));
+ CustomData_reset(data);
}
static void customData_update_offsets(CustomData *data)
@@ -1385,9 +1381,10 @@ static void customData_update_offsets(CustomData *data)
CustomData_update_typemap(data);
}
-int CustomData_get_layer_index(const CustomData *data, int type)
+/* to use when we're in the middle of modifying layers */
+static int CustomData_get_layer_index__notypemap(const CustomData *data, int type)
{
- int i;
+ int i;
for (i = 0; i < data->totlayer; ++i)
if (data->layers[i].type == type)
@@ -1396,11 +1393,21 @@ int CustomData_get_layer_index(const CustomData *data, int type)
return -1;
}
+/* -------------------------------------------------------------------- */
+/* index values to access the layers (offset from the layer start) */
+
+int CustomData_get_layer_index(const CustomData *data, int type)
+{
+ BLI_assert(customdata_typemap_is_valid(data));
+ return data->typemap[type];
+}
+
int CustomData_get_layer_index_n(const struct CustomData *data, int type, int n)
{
int i = CustomData_get_layer_index(data, type);
if (i != -1) {
+ BLI_assert(i + n < data->totlayer);
i = (data->layers[i + n].type == type) ? (i + n) : (-1);
}
@@ -1420,91 +1427,62 @@ int CustomData_get_named_layer_index(const CustomData *data, int type, const cha
int CustomData_get_active_layer_index(const CustomData *data, int type)
{
- if (!data->totlayer)
- return -1;
-
- if (data->typemap[type] != -1) {
- return data->typemap[type] + data->layers[data->typemap[type]].active;
- }
-
- return -1;
+ const int layer_index = data->typemap[type];
+ BLI_assert(customdata_typemap_is_valid(data));
+ return (layer_index != -1) ? layer_index + data->layers[layer_index].active: -1;
}
int CustomData_get_render_layer_index(const CustomData *data, int type)
{
- int i;
-
- for (i = 0; i < data->totlayer; ++i)
- if (data->layers[i].type == type)
- return i + data->layers[i].active_rnd;
-
- return -1;
+ const int layer_index = data->typemap[type];
+ BLI_assert(customdata_typemap_is_valid(data));
+ return (layer_index != -1) ? layer_index + data->layers[layer_index].active_rnd : -1;
}
int CustomData_get_clone_layer_index(const CustomData *data, int type)
{
- int i;
-
- for (i = 0; i < data->totlayer; ++i)
- if (data->layers[i].type == type)
- return i + data->layers[i].active_clone;
-
- return -1;
+ const int layer_index = data->typemap[type];
+ BLI_assert(customdata_typemap_is_valid(data));
+ return (layer_index != -1) ? layer_index + data->layers[layer_index].active_clone : -1;
}
int CustomData_get_stencil_layer_index(const CustomData *data, int type)
{
- int i;
+ const int layer_index = data->typemap[type];
+ BLI_assert(customdata_typemap_is_valid(data));
+ return (layer_index != -1) ? layer_index + data->layers[layer_index].active_mask : -1;
+}
- for (i = 0; i < data->totlayer; ++i)
- if (data->layers[i].type == type)
- return i + data->layers[i].active_mask;
- return -1;
-}
+/* -------------------------------------------------------------------- */
+/* index values per layer type */
int CustomData_get_active_layer(const CustomData *data, int type)
{
- int i;
-
- for (i = 0; i < data->totlayer; ++i)
- if (data->layers[i].type == type)
- return data->layers[i].active;
-
- return -1;
+ const int layer_index = data->typemap[type];
+ BLI_assert(customdata_typemap_is_valid(data));
+ return (layer_index != -1) ? data->layers[layer_index].active : -1;
}
int CustomData_get_render_layer(const CustomData *data, int type)
{
- int i;
-
- for (i = 0; i < data->totlayer; ++i)
- if (data->layers[i].type == type)
- return data->layers[i].active_rnd;
-
- return -1;
+ const int layer_index = data->typemap[type];
+ BLI_assert(customdata_typemap_is_valid(data));
+ return (layer_index != -1) ? data->layers[layer_index].active_rnd : -1;
}
int CustomData_get_clone_layer(const CustomData *data, int type)
{
- int i;
-
- for (i = 0; i < data->totlayer; ++i)
- if (data->layers[i].type == type)
- return data->layers[i].active_clone;
-
- return -1;
+ const int layer_index = data->typemap[type];
+ BLI_assert(customdata_typemap_is_valid(data));
+ return (layer_index != -1) ? data->layers[layer_index].active_clone : -1;
}
int CustomData_get_stencil_layer(const CustomData *data, int type)
{
- int i;
-
- for (i = 0; i < data->totlayer; ++i)
- if (data->layers[i].type == type)
- return data->layers[i].active_mask;
-
- return -1;
+ const int layer_index = data->typemap[type];
+ BLI_assert(customdata_typemap_is_valid(data));
+ return (layer_index != -1) ? data->layers[layer_index].active_mask : -1;
}
void CustomData_set_layer_active(CustomData *data, int type, int n)
@@ -1735,7 +1713,7 @@ int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
/* if layer was last of type in array, set new active layer */
if ((index >= data->totlayer) || (data->layers[index].type != type)) {
- i = CustomData_get_layer_index(data, type);
+ i = CustomData_get_layer_index__notypemap(data, type);
if (i >= 0)
for (; i < data->totlayer && data->layers[i].type == type; i++) {
@@ -1750,7 +1728,6 @@ int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
customData_resize(data, -CUSTOMDATA_GROW);
customData_update_offsets(data);
- CustomData_update_typemap(data);
return 1;
}
@@ -2021,7 +1998,7 @@ void CustomData_interp(const CustomData *source, CustomData *dest,
}
/* if there are no more dest layers, we're done */
- if (dest_i >= dest->totlayer) return;
+ if (dest_i >= dest->totlayer) break;
/* if we found a matching layer, copy the data */
if (dest->layers[dest_i].type == source->layers[src_i].type) {
@@ -2380,7 +2357,9 @@ void CustomData_bmesh_free_block(CustomData *data, void **block)
const LayerTypeInfo *typeInfo;
int i;
- if (!*block) return;
+ if (*block == NULL)
+ return;
+
for (i = 0; i < data->totlayer; ++i) {
if (!(data->layers[i].flag & CD_FLAG_NOFREE)) {
typeInfo = layerType_getInfo(data->layers[i].type);
@@ -2416,7 +2395,7 @@ void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
const LayerTypeInfo *typeInfo;
int dest_i, src_i;
- if (!*dest_block) {
+ if (*dest_block == NULL) {
CustomData_bmesh_alloc_block(dest, dest_block);
if (*dest_block)
memset(*dest_block, 0, dest->totsize);
@@ -2497,10 +2476,49 @@ int CustomData_layer_has_math(struct CustomData *data, int layer_n)
if (typeInfo->equal && typeInfo->add && typeInfo->multiply &&
typeInfo->initminmax && typeInfo->dominmax)
{
- return 1;
+ return TRUE;
}
- return 0;
+ return FALSE;
+}
+
+int CustomData_layer_has_interp(struct CustomData *data, int layer_n)
+{
+ const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[layer_n].type);
+
+ if (typeInfo->interp) {
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+int CustomData_has_math(struct CustomData *data)
+{
+ int i;
+
+ /* interpolates a layer at a time */
+ for (i = 0; i < data->totlayer; ++i) {
+ if (CustomData_layer_has_math(data, i)) {
+ return TRUE;
+ }
+ }
+
+ return FALSE;
+}
+
+int CustomData_has_interp(struct CustomData *data)
+{
+ int i;
+
+ /* interpolates a layer at a time */
+ for (i = 0; i < data->totlayer; ++i) {
+ if (CustomData_layer_has_interp(data, i)) {
+ return TRUE;
+ }
+ }
+
+ return FALSE;
}
/* copies the "value" (e.g. mloopuv uv or mloopcol colors) from one block to
@@ -2600,8 +2618,8 @@ void CustomData_bmesh_set_layer_n(CustomData *data, void *block, int n, void *so
memcpy(dest, source, typeInfo->size);
}
-void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
- float *sub_weights, int count, void *dest_block)
+void CustomData_bmesh_interp(CustomData *data, void **src_blocks, const float *weights,
+ const float *sub_weights, int count, void *dest_block)
{
int i, j;
void *source_buf[SOURCE_BUF_SIZE];
@@ -2636,7 +2654,7 @@ void CustomData_bmesh_set_default(CustomData *data, void **block)
const LayerTypeInfo *typeInfo;
int i;
- if (!*block)
+ if (*block == NULL)
CustomData_bmesh_alloc_block(data, block);
for (i = 0; i < data->totlayer; ++i) {
@@ -2656,7 +2674,7 @@ void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
const LayerTypeInfo *typeInfo;
int dest_i, src_i, src_offset;
- if (!*dest_block)
+ if (*dest_block == NULL)
CustomData_bmesh_alloc_block(dest, dest_block);
/* copies a layer at a time */
@@ -2888,7 +2906,9 @@ void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask
layer = &data->layers[i];
typeInfo = layerType_getInfo(layer->type);
- if (!(mask & CD_TYPE_AS_MASK(layer->type))) ;
+ if (!(mask & CD_TYPE_AS_MASK(layer->type))) {
+ /* pass */
+ }
else if ((layer->flag & CD_FLAG_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) {
if (typeInfo->free)
typeInfo->free(layer->data, totelem, typeInfo->size);
@@ -2914,10 +2934,15 @@ void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int
layer = &data->layers[i];
typeInfo = layerType_getInfo(layer->type);
- if (!(mask & CD_TYPE_AS_MASK(layer->type))) ;
- else if (layer->flag & CD_FLAG_IN_MEMORY) ;
- else if ((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read)
+ if (!(mask & CD_TYPE_AS_MASK(layer->type))) {
+ /* pass */
+ }
+ else if (layer->flag & CD_FLAG_IN_MEMORY) {
+ /* pass */
+ }
+ else if ((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) {
update = 1;
+ }
}
if (!update)
@@ -2935,15 +2960,23 @@ void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int
layer = &data->layers[i];
typeInfo = layerType_getInfo(layer->type);
- if (!(mask & CD_TYPE_AS_MASK(layer->type))) ;
- else if (layer->flag & CD_FLAG_IN_MEMORY) ;
+ if (!(mask & CD_TYPE_AS_MASK(layer->type))) {
+ /* pass */
+ }
+ else if (layer->flag & CD_FLAG_IN_MEMORY) {
+ /* pass */
+ }
else if ((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) {
blay = cdf_layer_find(cdf, layer->type, layer->name);
if (blay) {
if (cdf_read_layer(cdf, blay)) {
- if (typeInfo->read(cdf, layer->data, totelem)) ;
- else break;
+ if (typeInfo->read(cdf, layer->data, totelem)) {
+ /* pass */
+ }
+ else {
+ break;
+ }
layer->flag |= CD_FLAG_IN_MEMORY;
}
else
@@ -2974,9 +3007,12 @@ void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, in
layer = &data->layers[i];
typeInfo = layerType_getInfo(layer->type);
- if (!(mask & CD_TYPE_AS_MASK(layer->type))) ;
- else if ((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write)
+ if (!(mask & CD_TYPE_AS_MASK(layer->type))) {
+ /* pass */
+ }
+ else if ((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
update = 1;
+ }
}
if (!update)
@@ -3017,11 +3053,16 @@ void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, in
blay = cdf_layer_find(cdf, layer->type, layer->name);
if (cdf_write_layer(cdf, blay)) {
- if (typeInfo->write(cdf, layer->data, totelem)) ;
- else break;
+ if (typeInfo->write(cdf, layer->data, totelem)) {
+ /* pass */
+ }
+ else {
+ break;
+ }
}
- else
+ else {
break;
+ }
}
}
diff --git a/source/blender/blenkernel/intern/deform.c b/source/blender/blenkernel/intern/deform.c
index 4110d4565b2..7c13ca388e0 100644
--- a/source/blender/blenkernel/intern/deform.c
+++ b/source/blender/blenkernel/intern/deform.c
@@ -278,7 +278,7 @@ void defvert_normalize_lock_map(MDeformVert *dvert, const char *lock_flags, cons
}
}
- lock_iweight = maxf(0.0f, 1.0f - lock_iweight);
+ lock_iweight = max_ff(0.0f, 1.0f - lock_iweight);
if (tot_weight > 0.0f) {
/* paranoid, should be 1.0 but in case of float error clamp anyway */
@@ -431,7 +431,7 @@ int *defgroup_flip_map_single(Object *ob, int *flip_map_len, int use_default, in
if (strcmp(name, dg->name)) {
flip_num = defgroup_name_index(ob, name);
- if (flip_num >= 0) {
+ if (flip_num != -1) {
map[defgroup] = flip_num;
map[flip_num] = defgroup;
}
@@ -790,3 +790,23 @@ void defvert_clear(MDeformVert *dvert)
dvert->totweight = 0;
}
+
+/**
+ * \return The first group index shared by both deform verts
+ * or -1 if none are found.
+ */
+int defvert_find_shared(const MDeformVert *dvert_a, const MDeformVert *dvert_b)
+{
+ if (dvert_a->totweight && dvert_b->totweight) {
+ MDeformWeight *dw = dvert_a->dw;
+ unsigned int i;
+
+ for (i = dvert_a->totweight; i != 0; i--, dw++) {
+ if (dw->weight > 0.0f && defvert_find_weight(dvert_b, dw->def_nr) > 0.0f) {
+ return dw->def_nr;
+ }
+ }
+ }
+
+ return -1;
+}
diff --git a/source/blender/blenkernel/intern/depsgraph.c b/source/blender/blenkernel/intern/depsgraph.c
index b8d5294eabc..950a0ca3d60 100644
--- a/source/blender/blenkernel/intern/depsgraph.c
+++ b/source/blender/blenkernel/intern/depsgraph.c
@@ -150,8 +150,8 @@ void queue_delete(DagNodeQueue *queue)
MEM_freeN(temp);
}
- MEM_freeN(queue->freenodes);
- MEM_freeN(queue);
+ MEM_freeN(queue->freenodes);
+ MEM_freeN(queue);
}
/* insert in queue, remove in front */
@@ -190,8 +190,8 @@ void push_queue(DagNodeQueue *queue, DagNode *node)
}
queue->freenodes->count = DAGQUEUEALLOC;
- elem = queue->freenodes->first;
- queue->freenodes->first = elem->next;
+ elem = queue->freenodes->first;
+ queue->freenodes->first = elem->next;
}
elem->next = NULL;
elem->node = node;
@@ -211,7 +211,7 @@ void push_stack(DagNodeQueue *queue, DagNode *node)
DagNodeQueueElem *elem;
int i;
- elem = queue->freenodes->first;
+ elem = queue->freenodes->first;
if (elem != NULL) {
queue->freenodes->first = elem->next;
if (queue->freenodes->last == elem) {
@@ -235,8 +235,8 @@ void push_stack(DagNodeQueue *queue, DagNode *node)
}
queue->freenodes->count = DAGQUEUEALLOC;
- elem = queue->freenodes->first;
- queue->freenodes->first = elem->next;
+ elem = queue->freenodes->first;
+ queue->freenodes->first = elem->next;
}
elem->next = queue->first;
elem->node = node;
@@ -302,7 +302,7 @@ DagForest *dag_init(void)
}
/* isdata = object data... */
-// XXX this needs to be extended to be more flexible (so that not only objects are evaluated via depsgraph)...
+/* XXX this needs to be extended to be more flexible (so that not only objects are evaluated via depsgraph)... */
static void dag_add_driver_relation(AnimData *adt, DagForest *dag, DagNode *node, int isdata)
{
FCurve *fcu;
@@ -400,8 +400,7 @@ static void dag_add_material_driver_relations(DagForest *dag, DagNode *node, Mat
}
}
-static void dag_add_collision_field_relation(DagForest *dag, Scene *scene, Object *ob, DagNode *node)
-{
+static void dag_add_collision_field_relation(DagForest *dag, Scene *scene, Object *ob, DagNode *node, int skip_forcefield){
Base *base;
DagNode *node2;
@@ -411,7 +410,9 @@ static void dag_add_collision_field_relation(DagForest *dag, Scene *scene, Objec
if ((base->lay & ob->lay) && base->object->pd) {
Object *ob1 = base->object;
if ((ob1->pd->deflect || ob1->pd->forcefield) && (ob1 != ob)) {
- node2 = dag_get_node(dag, ob1);
+ if (skip_forcefield && ob1->pd->forcefield == skip_forcefield)
+ continue;
+ node2 = dag_get_node(dag, ob1);
dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Field Collision");
}
}
@@ -443,7 +444,6 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O
if (ob->type == OB_ARMATURE) {
if (ob->pose) {
bPoseChannel *pchan;
- bConstraint *con;
for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
for (con = pchan->constraints.first; con; con = con->next) {
@@ -464,7 +464,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O
if (ct->tar->type == OB_MESH)
node3->customdata_mask |= CD_MASK_MDEFORMVERT;
}
- else if (ELEM3(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK))
+ else if (ELEM3(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK))
dag_add_relation(dag, node3, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, cti->name);
else
dag_add_relation(dag, node3, node, DAG_RL_OB_DATA, cti->name);
@@ -501,7 +501,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O
if (ob->adt)
dag_add_driver_relation(ob->adt, dag, node, (ob->type == OB_ARMATURE)); // XXX isdata arg here doesn't give an accurate picture of situation
- key = ob_get_key(ob);
+ key = BKE_key_from_object(ob);
if (key && key->adt)
dag_add_driver_relation(key->adt, dag, node, 1);
@@ -570,12 +570,14 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O
/* softbody collision */
if ((ob->type == OB_MESH) || (ob->type == OB_CURVE) || (ob->type == OB_LATTICE)) {
if (ob->particlesystem.first ||
- modifiers_isModifierEnabled(ob, eModifierType_Softbody) ||
- modifiers_isModifierEnabled(ob, eModifierType_Cloth) ||
- modifiers_isModifierEnabled(ob, eModifierType_Smoke) ||
- modifiers_isModifierEnabled(ob, eModifierType_DynamicPaint))
+ modifiers_isModifierEnabled(ob, eModifierType_Softbody) ||
+ modifiers_isModifierEnabled(ob, eModifierType_Cloth) ||
+ modifiers_isModifierEnabled(ob, eModifierType_DynamicPaint))
{
- dag_add_collision_field_relation(dag, scene, ob, node); /* TODO: use effectorweight->group */
+ dag_add_collision_field_relation(dag, scene, ob, node, 0); /* TODO: use effectorweight->group */
+ }
+ else if (modifiers_isModifierEnabled(ob, eModifierType_Smoke)) {
+ dag_add_collision_field_relation(dag, scene, ob, node, PFIELD_SMOKEFLOW);
}
}
@@ -604,7 +606,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O
if (mom != ob) {
node2 = dag_get_node(dag, mom);
- dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Metaball"); // mom depends on children!
+ dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Metaball"); /* mom depends on children! */
}
}
break;
@@ -816,7 +818,7 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask)
tag_main_idcode(bmain, ID_MA, FALSE);
/* add base node for scene. scene is always the first node in DAG */
- scenenode = dag_add_node(dag, sce);
+ scenenode = dag_add_node(dag, sce);
/* add current scene objects */
for (base = sce->base.first; base; base = base->next) {
@@ -870,7 +872,7 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask)
}
/* cycle detection and solving */
- // solve_cycles(dag);
+ // solve_cycles(dag);
return dag;
}
@@ -879,23 +881,23 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask)
void free_forest(DagForest *Dag)
{ /* remove all nodes and deps */
DagNode *tempN;
- DagAdjList *tempA;
+ DagAdjList *tempA;
DagAdjList *itA;
DagNode *itN = Dag->DagNode.first;
while (itN) {
- itA = itN->child;
+ itA = itN->child;
while (itA) {
tempA = itA;
itA = itA->next;
- MEM_freeN(tempA);
+ MEM_freeN(tempA);
}
- itA = itN->parent;
+ itA = itN->parent;
while (itA) {
tempA = itA;
itA = itA->next;
- MEM_freeN(tempA);
+ MEM_freeN(tempA);
}
tempN = itN;
@@ -919,8 +921,8 @@ DagNode *dag_find_node(DagForest *forest, void *fob)
return NULL;
}
-static int ugly_hack_sorry = 1; // prevent type check
-static int dag_print_dependencies = 0; // debugging
+static int ugly_hack_sorry = 1; /* prevent type check */
+static int dag_print_dependencies = 0; /* debugging */
/* no checking of existence, use dag_find_node first or dag_get_node */
DagNode *dag_add_node(DagForest *forest, void *fob)
@@ -932,7 +934,7 @@ DagNode *dag_add_node(DagForest *forest, void *fob)
node->ob = fob;
node->color = DAG_WHITE;
- if (ugly_hack_sorry) node->type = GS(((ID *) fob)->name); // sorry, done for pose sorting
+ if (ugly_hack_sorry) node->type = GS(((ID *) fob)->name); /* sorry, done for pose sorting */
if (forest->numNodes) {
((DagNode *) forest->DagNode.last)->next = node;
forest->DagNode.last = node;
@@ -1151,7 +1153,7 @@ static void dag_check_cycle(DagForest *dag)
for (node = dag->DagNode.first; node; node = node->next) {
while (node->parent) {
itA = node->parent->next;
- MEM_freeN(node->parent);
+ MEM_freeN(node->parent);
node->parent = itA;
}
}
@@ -1240,7 +1242,7 @@ void graph_bfs(void)
itA = itA->next;
}
if (pos[node->BFS_dist] > node->k) {
- pos[node->BFS_dist] += 1;
+ pos[node->BFS_dist] += 1;
node->k = (float) pos[node->BFS_dist];
}
else {
@@ -1301,7 +1303,7 @@ int pre_and_post_source_BFS(DagForest *dag, short mask, DagNode *source, graph_a
pre_func(node->ob, data);
}
- else { // back or cross edge
+ else { /* back or cross edge */
retval = 1;
}
itA = itA->next;
@@ -1332,7 +1334,7 @@ DagNodeQueue *graph_dfs(void)
/* int is_cycle = 0; */ /* UNUSED */
/*
*fprintf(stderr, "starting DFS\n ------------\n");
- */
+ */
nqueue = queue_create(DAGQUEUEALLOC);
retqueue = queue_create(MainDag->numNodes);
for (i = 0; i < 50; i++)
@@ -1384,7 +1386,7 @@ DagNodeQueue *graph_dfs(void)
break;
}
else {
- if (itA->node->color == DAG_GRAY) { // back edge
+ if (itA->node->color == DAG_GRAY) { /* back edge */
fprintf(stderr, "dfs back edge :%15s %15s\n", ((ID *) node->ob)->name, ((ID *) itA->node->ob)->name);
/* is_cycle = 1; */ /* UNUSED */
}
@@ -1462,7 +1464,7 @@ int pre_and_post_source_DFS(DagForest *dag, short mask, DagNode *source, graph_a
int retval = 0;
/*
* fprintf(stderr, "starting DFS\n ------------\n");
- */
+ */
nqueue = queue_create(DAGQUEUEALLOC);
/* Init
@@ -1516,7 +1518,7 @@ int pre_and_post_source_DFS(DagForest *dag, short mask, DagNode *source, graph_a
// }
}
itA = itA->next;
- }
+ }
if (!skip) {
node = pop_queue(nqueue);
@@ -1535,7 +1537,7 @@ int pre_and_post_source_DFS(DagForest *dag, short mask, DagNode *source, graph_a
}
-// used to get the obs owning a datablock
+/* used to get the obs owning a datablock */
DagNodeQueue *get_obparents(struct DagForest *dag, void *ob)
{
DagNode *node, *node1;
@@ -1546,7 +1548,7 @@ DagNodeQueue *get_obparents(struct DagForest *dag, void *ob)
if (node == NULL) {
return NULL;
}
- else if (node->ancestor_count == 1) { // simple case
+ else if (node->ancestor_count == 1) { /* simple case */
nqueue = queue_create(1);
push_queue(nqueue, node);
}
@@ -1555,7 +1557,7 @@ DagNodeQueue *get_obparents(struct DagForest *dag, void *ob)
node1 = dag->DagNode.first;
do {
- if (node1->DFS_fntm > node->DFS_fntm) { // a parent is finished after child. must check adj list
+ if (node1->DFS_fntm > node->DFS_fntm) { /* a parent is finished after child. must check adj list */
itA = node->child;
while (itA != NULL) {
if ((itA->node == node) && (itA->type == DAG_RL_DATA)) {
@@ -1583,7 +1585,7 @@ DagNodeQueue *get_first_ancestors(struct DagForest *dag, void *ob)
node1 = dag->DagNode.first;
do {
- if (node1->DFS_fntm > node->DFS_fntm) {
+ if (node1->DFS_fntm > node->DFS_fntm) {
itA = node->child;
while (itA != NULL) {
if (itA->node == node) {
@@ -1595,10 +1597,10 @@ DagNodeQueue *get_first_ancestors(struct DagForest *dag, void *ob)
node1 = node1->next;
} while (node1);
- return nqueue;
+ return nqueue;
}
-// standard DFS list
+/* standard DFS list */
DagNodeQueue *get_all_childs(struct DagForest *dag, void *ob)
{
DagNode *node;
@@ -1609,7 +1611,7 @@ DagNodeQueue *get_all_childs(struct DagForest *dag, void *ob)
int skip = 0;
nqueue = queue_create(DAGQUEUEALLOC);
- retqueue = queue_create(dag->numNodes); // was MainDag... why? (ton)
+ retqueue = queue_create(dag->numNodes); /* was MainDag... why? (ton) */
node = dag->DagNode.first;
while (node) {
@@ -1619,8 +1621,8 @@ DagNodeQueue *get_all_childs(struct DagForest *dag, void *ob)
time = 1;
- node = dag_find_node(dag, ob); // could be done in loop above (ton)
- if (node) { // can be null for newly added objects
+ node = dag_find_node(dag, ob); /* could be done in loop above (ton) */
+ if (node) { /* can be null for newly added objects */
node->color = DAG_GRAY;
time++;
@@ -1641,9 +1643,9 @@ DagNodeQueue *get_all_childs(struct DagForest *dag, void *ob)
push_stack(nqueue, itA->node);
skip = 1;
break;
- }
+ }
itA = itA->next;
- }
+ }
if (!skip) {
node = pop_queue(nqueue);
@@ -1671,7 +1673,7 @@ short are_obs_related(struct DagForest *dag, void *ob1, void *ob2)
while (itA != NULL) {
if (itA->node->ob == ob2) {
return itA->node->type;
- }
+ }
itA = itA->next;
}
return DAG_NO_RELATION;
@@ -1699,7 +1701,7 @@ void graph_print_queue(DagNodeQueue *nqueue)
queueElem = nqueue->first;
while (queueElem) {
fprintf(stderr, "** %s %i %i-%i ", ((ID *) queueElem->node->ob)->name, queueElem->node->color, queueElem->node->DFS_dvtm, queueElem->node->DFS_fntm);
- queueElem = queueElem->next;
+ queueElem = queueElem->next;
}
fprintf(stderr, "\n");
}
@@ -1719,7 +1721,7 @@ void graph_print_queue_dist(DagNodeQueue *nqueue)
fputc('|', stderr);
fputc('\n', stderr);
count = 0;
- queueElem = queueElem->next;
+ queueElem = queueElem->next;
}
fprintf(stderr, "\n");
}
@@ -1857,14 +1859,14 @@ void DAG_scene_sort(Main *bmain, Scene *sce)
push_stack(nqueue, itA->node);
skip = 1;
break;
- }
+ }
itA = itA->next;
- }
+ }
if (!skip) {
if (node) {
node = pop_queue(nqueue);
- if (node->ob == sce) // we are done
+ if (node->ob == sce) /* we are done */
break;
node->color = DAG_BLACK;
@@ -1876,7 +1878,7 @@ void DAG_scene_sort(Main *bmain, Scene *sce)
BLI_remlink(&sce->base, base);
BLI_addhead(&tempbase, base);
}
- }
+ }
}
}
@@ -2021,7 +2023,7 @@ static unsigned int flush_layer_node(Scene *sce, DagNode *node, int curtime)
for (itA = node->child; itA; itA = itA->next) {
if (itA->node->type == ID_OB) {
if (itA->node->lasttime != curtime) {
- itA->lay = flush_layer_node(sce, itA->node, curtime); // lay is only set once for each relation
+ itA->lay = flush_layer_node(sce, itA->node, curtime); /* lay is only set once for each relation */
}
else itA->lay = itA->node->lay;
@@ -2069,12 +2071,12 @@ static void dag_scene_flush_layers(Scene *sce, int lay)
Base *base;
int lasttime;
- firstnode = sce->theDag->DagNode.first; // always scene node
+ firstnode = sce->theDag->DagNode.first; /* always scene node */
for (itA = firstnode->child; itA; itA = itA->next)
itA->lay = 0;
- sce->theDag->time++; // so we know which nodes were accessed
+ sce->theDag->time++; /* so we know which nodes were accessed */
lasttime = sce->theDag->time;
/* update layer flags in nodes */
@@ -2146,13 +2148,13 @@ void DAG_scene_flush_update(Main *bmain, Scene *sce, unsigned int lay, const sho
DAG_scene_sort(bmain, sce);
}
- firstnode = sce->theDag->DagNode.first; // always scene node
+ firstnode = sce->theDag->DagNode.first; /* always scene node */
/* first we flush the layer flags */
dag_scene_flush_layers(sce, lay);
/* then we use the relationships + layer info to flush update events */
- sce->theDag->time++; // so we know which nodes were accessed
+ sce->theDag->time++; /* so we know which nodes were accessed */
lasttime = sce->theDag->time;
for (itA = firstnode->child; itA; itA = itA->next)
if (itA->node->lasttime != lasttime && itA->node->type == ID_OB)
@@ -2160,7 +2162,7 @@ void DAG_scene_flush_update(Main *bmain, Scene *sce, unsigned int lay, const sho
/* if update is not due to time change, do pointcache clears */
if (!time) {
- sce->theDag->time++; // so we know which nodes were accessed
+ sce->theDag->time++; /* so we know which nodes were accessed */
lasttime = sce->theDag->time;
for (itA = firstnode->child; itA; itA = itA->next) {
if (itA->node->lasttime != lasttime && itA->node->type == ID_OB) {
@@ -2378,7 +2380,7 @@ static void dag_object_time_update_flags(Object *ob)
}
}
}
- }
+ }
if (ob->recalc & OB_RECALC_OB)
lib_id_recalc_tag(G.main, &ob->id);
@@ -2650,7 +2652,7 @@ static void dag_id_flush_update(Scene *sce, ID *id)
/* set flags based on ShapeKey */
if (idtype == ID_KE) {
for (obt = bmain->object.first; obt; obt = obt->id.next) {
- Key *key = ob_get_key(obt);
+ Key *key = BKE_key_from_object(obt);
if (!(ob && obt == ob) && ((ID *)key == id)) {
obt->flag |= (OB_RECALC_OB | OB_RECALC_DATA);
lib_id_recalc_tag(bmain, &obt->id);
@@ -2928,9 +2930,9 @@ void DAG_pose_sort(Object *ob)
int skip = 0;
dag = dag_init();
- ugly_hack_sorry = 0; // no ID structs
+ ugly_hack_sorry = 0; /* no ID structs */
- rootnode = dag_add_node(dag, NULL); // node->ob becomes NULL
+ rootnode = dag_add_node(dag, NULL); /* node->ob becomes NULL */
/* we add the hierarchy and the constraints */
for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
@@ -2975,7 +2977,7 @@ void DAG_pose_sort(Object *ob)
dag_add_relation(dag, node2, node3, 0, "IK Constraint");
segcount++;
- if (segcount == data->rootbone || segcount > 255) break; // 255 is weak
+ if (segcount == data->rootbone || segcount > 255) break; /* 255 is weak */
parchan = parchan->parent;
}
}
@@ -3018,21 +3020,21 @@ void DAG_pose_sort(Object *ob)
push_stack(nqueue, itA->node);
skip = 1;
break;
- }
+ }
itA = itA->next;
- }
+ }
if (!skip) {
if (node) {
node = pop_queue(nqueue);
- if (node->ob == NULL) // we are done
+ if (node->ob == NULL) /* we are done */
break;
node->color = DAG_BLACK;
/* put node in new list */
BLI_remlink(&pose->chanbase, node->ob);
BLI_addhead(&tempbase, node->ob);
- }
+ }
}
}
diff --git a/source/blender/blenkernel/intern/displist.c b/source/blender/blenkernel/intern/displist.c
index 64959fd3aa1..e13d05d0a2f 100644
--- a/source/blender/blenkernel/intern/displist.c
+++ b/source/blender/blenkernel/intern/displist.c
@@ -299,7 +299,9 @@ static void curve_to_displist(Curve *cu, ListBase *nubase, ListBase *dispbase, i
else
resolu = nu->resolu;
- if (!BKE_nurb_check_valid_u(nu)) ;
+ if (!BKE_nurb_check_valid_u(nu)) {
+ /* pass */
+ }
else if (nu->type == CU_BEZIER) {
/* count */
len = 0;
@@ -1384,8 +1386,8 @@ static void do_makeDispListCurveTypes(Scene *scene, Object *ob, ListBase *dispba
ListBase top_capbase = {NULL, NULL};
for (dlb = dlbev.first; dlb; dlb = dlb->next) {
- const float bevfac1 = minf(cu->bevfac1, cu->bevfac2);
- const float bevfac2 = maxf(cu->bevfac1, cu->bevfac2);
+ const float bevfac1 = min_ff(cu->bevfac1, cu->bevfac2);
+ const float bevfac2 = max_ff(cu->bevfac1, cu->bevfac2);
float firstblend = 0.0f, lastblend = 0.0f;
int i, start, steps;
diff --git a/source/blender/blenkernel/intern/dynamicpaint.c b/source/blender/blenkernel/intern/dynamicpaint.c
index 1cb29b90133..89d728c0419 100644
--- a/source/blender/blenkernel/intern/dynamicpaint.c
+++ b/source/blender/blenkernel/intern/dynamicpaint.c
@@ -32,6 +32,8 @@
#include "BLI_threads.h"
#include "BLI_utildefines.h"
+#include "BLF_translation.h"
+
#include "DNA_anim_types.h"
#include "DNA_armature_types.h"
#include "DNA_constraint_types.h"
@@ -87,6 +89,9 @@
#include <omp.h>
#endif
+/* could enable at some point but for now there are far too many conversions */
+#pragma GCC diagnostic ignored "-Wdouble-promotion"
+
/* precalculated gaussian factors for 5x super sampling */
static float gaussianFactors[5] = {0.996849f,
0.596145f,
@@ -120,8 +125,16 @@ static int neighY[8] = {0, 1, 1, 1, 0, -1, -1, -1};
/* drying limits */
#define MIN_WETNESS 0.001f
#define MAX_WETNESS 5.0f
-/* dissolve macro */
-#define VALUE_DISSOLVE(VALUE, TIME, SCALE, LOG) (VALUE) = (LOG) ? (VALUE) *(pow(MIN_WETNESS, 1.0f / (1.2f * ((float)(TIME)) / (SCALE)))) : (VALUE) -1.0f / (TIME)*(SCALE)
+
+
+/* dissolve inline function */
+BLI_INLINE void value_dissolve(float *r_value, const float time, const float scale, const int is_log)
+{
+ *r_value = (is_log) ?
+ (*r_value) * (powf(MIN_WETNESS, 1.0f / (1.2f * time / scale))) :
+ (*r_value) - 1.0f / time * scale;
+}
+
/***************************** Internal Structs ***************************/
@@ -569,7 +582,7 @@ static void scene_setSubframe(Scene *scene, float subframe)
static int surface_getBrushFlags(DynamicPaintSurface *surface, Scene *scene)
{
Base *base = NULL;
- GroupObject *go = NULL;
+ GroupObject *go = NULL;
Object *brushObj = NULL;
ModifierData *md = NULL;
@@ -757,7 +770,7 @@ static void surfaceGenerateGrid(struct DynamicPaintSurface *surface)
volume = td[0] * td[1] * td[2];
/* determine final grid size by trying to fit average 10.000 points per grid cell */
- dim_factor = (float)pow(volume / ((double)sData->total_points / 10000.0), 1.0 / (double)axis);
+ dim_factor = (float)pow((double)volume / ((double)sData->total_points / 10000.0), 1.0 / (double)axis);
/* define final grid size using dim_factor, use min 3 for active axises */
for (i = 0; i < 3; i++) {
@@ -848,7 +861,7 @@ static void surfaceGenerateGrid(struct DynamicPaintSurface *surface)
grid->s_num = MEM_reallocN(grid->s_num, sizeof(int) * grid_cells);
if (error || !grid->s_num) {
- setError(surface->canvas, "Not enough free memory.");
+ setError(surface->canvas, N_("Not enough free memory"));
freeGrid(sData);
}
}
@@ -1235,7 +1248,7 @@ static void dynamicPaint_allocateSurfaceType(DynamicPaintSurface *surface)
break;
}
- if (sData->type_data == NULL) setError(surface->canvas, "Not enough free memory!");
+ if (sData->type_data == NULL) setError(surface->canvas, N_("Not enough free memory"));
}
static int surface_usesAdjDistance(DynamicPaintSurface *surface)
@@ -1292,7 +1305,7 @@ static void dynamicPaint_initAdjacencyData(DynamicPaintSurface *surface, int for
if (!ad->n_index || !ad->n_num || !ad->n_target || !temp_data) {
dynamicPaint_freeAdjData(sData);
if (temp_data) MEM_freeN(temp_data);
- setError(surface->canvas, "Not enough free memory.");
+ setError(surface->canvas, N_("Not enough free memory"));
return;
}
@@ -1762,10 +1775,10 @@ static DerivedMesh *dynamicPaint_Modifier_apply(DynamicPaintModifierData *pmd,
}
/* apply weights into a vertex group, if doesnt exists add a new layer */
- if (defgrp_index >= 0 && !dvert && (surface->output_name[0] != '\0'))
+ if (defgrp_index != -1 && !dvert && (surface->output_name[0] != '\0'))
dvert = CustomData_add_layer_named(&result->vertData, CD_MDEFORMVERT, CD_CALLOC,
NULL, sData->total_points, surface->output_name);
- if (defgrp_index >= 0 && dvert) {
+ if (defgrp_index != -1 && dvert) {
int i;
for (i = 0; i < sData->total_points; i++) {
MDeformVert *dv = &dvert[i];
@@ -1944,7 +1957,7 @@ static int dynamicPaint_findNeighbourPixel(PaintUVPoint *tempPoints, DerivedMesh
{
/* Note: Current method only uses polygon edges to detect neighboring pixels.
* -> It doesn't always lead to the optimum pixel but is accurate enough
- * and faster/simplier than including possible face tip point links)
+ * and faster/simpler than including possible face tip point links)
*/
int x, y;
@@ -2165,8 +2178,10 @@ int dynamicPaint_createUVSurface(DynamicPaintSurface *surface)
int *final_index;
int aa_samples;
- if (!dm) return setError(canvas, "Canvas mesh not updated.");
- if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ) return setError(canvas, "Can't bake non-\"image sequence\" formats.");
+ if (!dm)
+ return setError(canvas, N_("Canvas mesh not updated"));
+ if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ)
+ return setError(canvas, N_("Cannot bake non-'image sequence' formats"));
numOfFaces = dm->getNumTessFaces(dm);
mface = dm->getTessFaceArray(dm);
@@ -2176,8 +2191,10 @@ int dynamicPaint_createUVSurface(DynamicPaintSurface *surface)
tface = CustomData_get_layer_named(&dm->faceData, CD_MTFACE, uvname);
/* Check for validity */
- if (!tface) return setError(canvas, "No UV data on canvas.");
- if (surface->image_resolution < 16 || surface->image_resolution > 8192) return setError(canvas, "Invalid resolution.");
+ if (!tface)
+ return setError(canvas, N_("No UV data on canvas"));
+ if (surface->image_resolution < 16 || surface->image_resolution > 8192)
+ return setError(canvas, N_("Invalid resolution"));
w = h = surface->image_resolution;
@@ -2189,7 +2206,8 @@ int dynamicPaint_createUVSurface(DynamicPaintSurface *surface)
/* Init data struct */
if (surface->data) dynamicPaint_freeSurfaceData(surface);
sData = surface->data = MEM_callocN(sizeof(PaintSurfaceData), "PaintSurfaceData");
- if (!surface->data) return setError(canvas, "Not enough free memory.");
+ if (!surface->data)
+ return setError(canvas, N_("Not enough free memory"));
aa_samples = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
tempPoints = (struct PaintUVPoint *) MEM_callocN(w * h * sizeof(struct PaintUVPoint), "Temp PaintUVPoint");
@@ -2547,7 +2565,8 @@ int dynamicPaint_createUVSurface(DynamicPaintSurface *surface)
}
}
}
- if (error == 1) setError(canvas, "Not enough free memory.");
+ if (error == 1)
+ setError(canvas, N_("Not enough free memory"));
if (faceBB) MEM_freeN(faceBB);
if (tempPoints) MEM_freeN(tempPoints);
@@ -2598,7 +2617,10 @@ void dynamicPaint_outputSurfaceImage(DynamicPaintSurface *surface, char *filenam
int format = (surface->image_fileformat & MOD_DPAINT_IMGFORMAT_OPENEXR) ? R_IMF_IMTYPE_OPENEXR : R_IMF_IMTYPE_PNG;
char output_file[FILE_MAX];
- if (!sData->type_data) { setError(surface->canvas, "Image save failed: Invalid surface."); return; }
+ if (!sData->type_data) {
+ setError(surface->canvas, N_("Image save failed: invalid surface"));
+ return;
+ }
/* if selected format is openexr, but current build doesnt support one */
#ifndef WITH_OPENEXR
if (format == R_IMF_IMTYPE_OPENEXR) format = R_IMF_IMTYPE_PNG;
@@ -2612,7 +2634,10 @@ void dynamicPaint_outputSurfaceImage(DynamicPaintSurface *surface, char *filenam
/* Init image buffer */
ibuf = IMB_allocImBuf(surface->image_resolution, surface->image_resolution, 32, IB_rectfloat);
- if (ibuf == NULL) { setError(surface->canvas, "Image save failed: Not enough free memory."); return; }
+ if (ibuf == NULL) {
+ setError(surface->canvas, N_("Image save failed: not enough free memory"));
+ return;
+ }
#pragma omp parallel for schedule(static)
for (index = 0; index < sData->total_points; index++) {
@@ -2852,15 +2877,15 @@ static void mesh_faces_nearest_point_dp(void *userdata, int index, const float c
/***************************** Brush Painting Calls ******************************/
-/*
- * Mix color values to canvas point.
+/**
+ * Mix color values to canvas point.
*
- * surface : canvas surface
- * index : surface point index
- * paintFlags : paint object flags
- * paintColor,Alpha,Wetness : to be mixed paint values
- * timescale : value used to adjust time dependand
- * operations when using substeps
+ * \param surface canvas surface
+ * \param index surface point index
+ * \param paintFlags paint object flags
+ * \param paintColor,Alpha,Wetness to be mixed paint values
+ * \param timescale value used to adjust time dependent
+ * operations when using substeps
*/
static void dynamicPaint_mixPaintColors(DynamicPaintSurface *surface, int index, int paintFlags,
const float paintColor[3], float *paintAlpha, float *paintWetness, float *timescale)
@@ -4161,7 +4186,7 @@ static int dynamicPaint_prepareEffectStep(DynamicPaintSurface *surface, Scene *s
pdEndEffectors(&effectors);
}
- /* Get number of required steps using averate point distance
+ /* Get number of required steps using average point distance
* so that just a few ultra close pixels wont up substeps to max */
/* adjust number of required substep by fastest active effect */
@@ -4224,7 +4249,7 @@ static void dynamicPaint_doEffectStep(DynamicPaintSurface *surface, float *force
/* Only continue if surrounding point has higher wetness */
if (ePoint->wetness < pPoint->wetness || ePoint->wetness < MIN_WETNESS) continue;
- w_factor = 1.0f / numOfNeighs *MIN2(ePoint->wetness, 1.0f) * speed_scale;
+ w_factor = 1.0f / numOfNeighs * MIN2(ePoint->wetness, 1.0f) * speed_scale;
CLAMP(w_factor, 0.0f, 1.0f);
/* mix new wetness and color */
@@ -4473,7 +4498,7 @@ static void dynamicPaint_surfacePreStep(DynamicPaintSurface *surface, float time
int i;
float dry_ratio, f_color[4];
float p_wetness = pPoint->wetness;
- VALUE_DISSOLVE(pPoint->wetness, surface->dry_speed, timescale, (surface->flags & MOD_DPAINT_DRY_LOG));
+ value_dissolve(&pPoint->wetness, surface->dry_speed, timescale, (surface->flags & MOD_DPAINT_DRY_LOG));
if (pPoint->wetness < 0.0f) pPoint->wetness = 0.0f;
if (pPoint->wetness < surface->color_dry_threshold) {
@@ -4518,10 +4543,10 @@ static void dynamicPaint_surfacePreStep(DynamicPaintSurface *surface, float time
}
if (surface->flags & MOD_DPAINT_DISSOLVE) {
- VALUE_DISSOLVE(pPoint->alpha, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG));
+ value_dissolve(&pPoint->alpha, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG));
if (pPoint->alpha < 0.0f) pPoint->alpha = 0.0f;
- VALUE_DISSOLVE(pPoint->e_alpha, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG));
+ value_dissolve(&pPoint->e_alpha, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG));
if (pPoint->e_alpha < 0.0f) pPoint->e_alpha = 0.0f;
}
}
@@ -4533,7 +4558,7 @@ static void dynamicPaint_surfacePreStep(DynamicPaintSurface *surface, float time
float *point = &((float *)sData->type_data)[index];
/* log or linear */
- VALUE_DISSOLVE(*point, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG));
+ value_dissolve(point, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG));
if (*point < 0.0f) *point = 0.0f;
}
}
@@ -4649,7 +4674,7 @@ static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, Scene *sc
if (bData->realCoord) MEM_freeN(bData->realCoord);
if (canvas_verts) MEM_freeN(canvas_verts);
- return setError(surface->canvas, "Not enough free memory.");
+ return setError(surface->canvas, N_("Not enough free memory"));
}
new_bdata = 1;
@@ -4811,7 +4836,7 @@ static int dynamicPaint_doStep(Scene *scene, Object *ob, DynamicPaintSurface *su
*/
{
Base *base = NULL;
- GroupObject *go = NULL;
+ GroupObject *go = NULL;
Object *brushObj = NULL;
ModifierData *md = NULL;
@@ -4878,7 +4903,7 @@ static int dynamicPaint_doStep(Scene *scene, Object *ob, DynamicPaintSurface *su
/* Apply brush on the surface depending on it's collision type */
/* Particle brush: */
if (brush->collision == MOD_DPAINT_COL_PSYS) {
- if (brush->psys && brush->psys->part && brush->psys->part->type == PART_EMITTER &&
+ if (brush->psys && brush->psys->part && ELEM(brush->psys->part->type, PART_EMITTER, PART_FLUID) &&
psys_check_enabled(brushObj, brush->psys))
{
@@ -4934,7 +4959,7 @@ static int dynamicPaint_doStep(Scene *scene, Object *ob, DynamicPaintSurface *su
/* Allocate memory for surface previous points to read unchanged values from */
prevPoint = MEM_mallocN(sData->total_points * sizeof(struct PaintPoint), "PaintSurfaceDataCopy");
if (!prevPoint)
- return setError(canvas, "Not enough free memory.");
+ return setError(canvas, N_("Not enough free memory"));
/* Prepare effects and get number of required steps */
steps = dynamicPaint_prepareEffectStep(surface, scene, ob, &force, timescale);
diff --git a/source/blender/blenkernel/intern/editderivedmesh.c b/source/blender/blenkernel/intern/editderivedmesh.c
index befec1907da..8d430eb58b5 100644
--- a/source/blender/blenkernel/intern/editderivedmesh.c
+++ b/source/blender/blenkernel/intern/editderivedmesh.c
@@ -152,7 +152,7 @@ static void BMEdit_RecalcTessellation_intern(BMEditMesh *tm)
BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
/* don't consider two-edged faces */
- if (efa->len < 3) {
+ if (UNLIKELY(efa->len < 3)) {
/* do nothing */
}
diff --git a/source/blender/blenkernel/intern/effect.c b/source/blender/blenkernel/intern/effect.c
index 4f4bafd00b4..1f6db19ac27 100644
--- a/source/blender/blenkernel/intern/effect.c
+++ b/source/blender/blenkernel/intern/effect.c
@@ -54,6 +54,7 @@
#include "BLI_math.h"
#include "BLI_blenlib.h"
+#include "BLI_noise.h"
#include "BLI_jitter.h"
#include "BLI_rand.h"
#include "BLI_utildefines.h"
@@ -84,6 +85,7 @@
#include "BKE_object.h"
#include "BKE_particle.h"
#include "BKE_scene.h"
+#include "BKE_smoke.h"
#include "RE_render_ext.h"
@@ -137,6 +139,9 @@ PartDeflect *object_add_collision_fields(int type)
case PFIELD_TEXTURE:
pd->f_size = 1.0f;
break;
+ case PFIELD_SMOKEFLOW:
+ pd->f_flow = 1.0f;
+ break;
}
pd->flag = PFIELD_DO_LOCATION|PFIELD_DO_ROTATION;
@@ -161,7 +166,7 @@ void free_partdeflect(PartDeflect *pd)
pd->tex->id.us--;
if (pd->rng)
- rng_free(pd->rng);
+ BLI_rng_free(pd->rng);
MEM_freeN(pd);
}
@@ -170,9 +175,9 @@ static void precalculate_effector(EffectorCache *eff)
{
unsigned int cfra = (unsigned int)(eff->scene->r.cfra >= 0 ? eff->scene->r.cfra : -eff->scene->r.cfra);
if (!eff->pd->rng)
- eff->pd->rng = rng_new(eff->pd->seed + cfra);
+ eff->pd->rng = BLI_rng_new(eff->pd->seed + cfra);
else
- rng_srandom(eff->pd->rng, eff->pd->seed + cfra);
+ BLI_rng_srandom(eff->pd->rng, eff->pd->seed + cfra);
if (eff->pd->forcefield == PFIELD_GUIDE && eff->ob->type==OB_CURVE) {
Curve *cu= eff->ob->data;
@@ -200,7 +205,7 @@ static void precalculate_effector(EffectorCache *eff)
float old_vel[3];
BKE_object_where_is_calc_time(eff->scene, eff->ob, cfra - 1.0f);
- copy_v3_v3(old_vel, eff->ob->obmat[3]);
+ copy_v3_v3(old_vel, eff->ob->obmat[3]);
BKE_object_where_is_calc_time(eff->scene, eff->ob, cfra);
sub_v3_v3v3(eff->velocity, eff->ob->obmat[3], old_vel);
}
@@ -450,8 +455,8 @@ static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, Effect
// noise function for wind e.g.
static float wind_func(struct RNG *rng, float strength)
{
- int random = (rng_getInt(rng)+1) % 128; // max 2357
- float force = rng_getFloat(rng) + 1.0f;
+ int random = (BLI_rng_get_int(rng)+1) % 128; // max 2357
+ float force = BLI_rng_get_float(rng) + 1.0f;
float ret;
float sign = 0;
@@ -713,8 +718,8 @@ static void get_effector_tot(EffectorCache *eff, EffectorData *efd, EffectedPoin
if (eff->pd->forcefield == PFIELD_CHARGE) {
/* Only the charge of the effected particle is used for
- * interaction, not fall-offs. If the fall-offs aren't the
- * same this will be unphysical, but for animation this
+ * interaction, not fall-offs. If the fall-offs aren't the
+ * same this will be unphysical, but for animation this
* could be the wanted behavior. If you want physical
* correctness the fall-off should be spherical 2.0 anyways.
*/
@@ -823,7 +828,7 @@ static void do_physical_effector(EffectorCache *eff, EffectorData *efd, Effected
{
PartDeflect *pd = eff->pd;
RNG *rng = pd->rng;
- float force[3]={0, 0, 0};
+ float force[3] = {0, 0, 0};
float temp[3];
float fac;
float strength = pd->f_strength;
@@ -922,12 +927,27 @@ static void do_physical_effector(EffectorCache *eff, EffectorData *efd, Effected
mul_v3_fl(force, -efd->falloff * fac * (strength * fac + damp));
break;
+ case PFIELD_SMOKEFLOW:
+ zero_v3(force);
+ if (pd->f_source) {
+ float density;
+ if ((density = smoke_get_velocity_at(pd->f_source, point->loc, force)) >= 0.0f) {
+ float influence = strength * efd->falloff;
+ if (pd->flag & PFIELD_SMOKE_DENSITY)
+ influence *= density;
+ mul_v3_fl(force, influence);
+ /* apply flow */
+ madd_v3_v3fl(total_force, point->vel, -pd->f_flow * influence);
+ }
+ }
+ break;
+
}
if (pd->flag & PFIELD_DO_LOCATION) {
madd_v3_v3fl(total_force, force, 1.0f/point->vel_to_sec);
- if (ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG)==0 && pd->f_flow != 0.0f) {
+ if (ELEM3(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG, PFIELD_SMOKEFLOW)==0 && pd->f_flow != 0.0f) {
madd_v3_v3fl(total_force, point->vel, -pd->f_flow * efd->falloff);
}
}
@@ -993,12 +1013,14 @@ void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *we
if (efd.falloff > 0.0f)
efd.falloff *= eff_calc_visibility(colliders, eff, &efd, point);
- if (efd.falloff <= 0.0f)
- ; /* don't do anything */
- else if (eff->pd->forcefield == PFIELD_TEXTURE)
+ if (efd.falloff <= 0.0f) {
+ /* don't do anything */
+ }
+ else if (eff->pd->forcefield == PFIELD_TEXTURE) {
do_texture_effector(eff, &efd, point, force);
+ }
else {
- float temp1[3]={0, 0, 0}, temp2[3];
+ float temp1[3] = {0, 0, 0}, temp2[3];
copy_v3_v3(temp1, force);
do_physical_effector(eff, &efd, point, force);
diff --git a/source/blender/blenkernel/intern/fcurve.c b/source/blender/blenkernel/intern/fcurve.c
index 2dbc63e6944..ec61311d89e 100644
--- a/source/blender/blenkernel/intern/fcurve.c
+++ b/source/blender/blenkernel/intern/fcurve.c
@@ -504,14 +504,14 @@ short calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, flo
xmaxv = MAX3(xmaxv, bezt_last->vec[1][0], bezt_last->vec[2][0]);
}
else {
- xminv = minf(xminv, bezt_first->vec[1][0]);
- xmaxv = maxf(xmaxv, bezt_last->vec[1][0]);
+ xminv = min_ff(xminv, bezt_first->vec[1][0]);
+ xmaxv = max_ff(xmaxv, bezt_last->vec[1][0]);
}
}
}
/* only loop over keyframes to find extents for values if needed */
- if (ymin || ymax) {
+ if (ymin || ymax) {
BezTriple *bezt;
for (bezt = fcu->bezt, i = 0; i < fcu->totvert; bezt++, i++) {
@@ -521,8 +521,8 @@ short calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, flo
ymaxv = MAX4(ymaxv, bezt->vec[1][1], bezt->vec[0][1], bezt->vec[2][1]);
}
else {
- yminv = minf(yminv, bezt->vec[1][1]);
- ymaxv = maxf(ymaxv, bezt->vec[1][1]);
+ yminv = min_ff(yminv, bezt->vec[1][1]);
+ ymaxv = max_ff(ymaxv, bezt->vec[1][1]);
}
foundvert = TRUE;
@@ -533,8 +533,8 @@ short calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, flo
else if (fcu->fpt) {
/* frame range can be directly calculated from end verts */
if (xmin || xmax) {
- xminv = minf(xminv, fcu->fpt[0].vec[0]);
- xmaxv = maxf(xmaxv, fcu->fpt[fcu->totvert - 1].vec[0]);
+ xminv = min_ff(xminv, fcu->fpt[0].vec[0]);
+ xmaxv = max_ff(xmaxv, fcu->fpt[fcu->totvert - 1].vec[0]);
}
/* only loop over keyframes to find extents for values if needed */
@@ -591,15 +591,15 @@ void calc_fcurve_range(FCurve *fcu, float *start, float *end,
if (bezt_first) {
BLI_assert(bezt_last != NULL);
- min = minf(min, bezt_first->vec[1][0]);
- max = maxf(max, bezt_last->vec[1][0]);
+ min = min_ff(min, bezt_first->vec[1][0]);
+ max = max_ff(max, bezt_last->vec[1][0]);
foundvert = TRUE;
}
}
else if (fcu->fpt) {
- min = minf(min, fcu->fpt[0].vec[0]);
- max = maxf(max, fcu->fpt[fcu->totvert - 1].vec[0]);
+ min = min_ff(min, fcu->fpt[0].vec[0]);
+ max = max_ff(max, fcu->fpt[fcu->totvert - 1].vec[0]);
foundvert = TRUE;
}
@@ -1039,7 +1039,7 @@ static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar)
if (RNA_path_resolve_full(&id_ptr, dtar->rna_path, &ptr, &prop, &index)) {
if (RNA_property_array_check(prop)) {
/* array */
- if (index < RNA_property_array_length(&ptr, prop)) {
+ if (index < RNA_property_array_length(&ptr, prop)) {
switch (RNA_property_type(prop)) {
case PROP_BOOLEAN:
value = (float)RNA_property_boolean_get_index(&ptr, prop, index);
@@ -1143,7 +1143,7 @@ static float dvar_eval_rotDiff(ChannelDriver *driver, DriverVar *dvar)
/* stop here... */
return 0.0f;
- }
+ }
/* use the final posed locations */
mat4_to_quat(q1, pchan->pose_mat);
@@ -1549,7 +1549,7 @@ ChannelDriver *fcurve_copy_driver(ChannelDriver *driver)
for (dvar = ndriver->variables.first; dvar; dvar = dvar->next) {
/* need to go over all targets so that we don't leave any dangling paths */
DRIVER_TARGETS_LOOPER(dvar)
- {
+ {
/* make a copy of target's rna path if available */
if (dtar->rna_path)
dtar->rna_path = MEM_dupallocN(dtar->rna_path);
@@ -1832,7 +1832,7 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o)
return 1;
}
- return 0;
+ return 0;
}
}
@@ -1916,7 +1916,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime
cvalue = prevbezt->vec[1][1];
}
}
- }
+ }
else {
/* Use the first handle (earlier) of first BezTriple to calculate the
* gradient and thus the value of the curve at evaltime
@@ -1968,7 +1968,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime
cvalue = lastbezt->vec[1][1];
}
}
- }
+ }
else {
/* Use the gradient of the second handle (later) of last BezTriple to calculate the
* gradient and thus the value of the curve at evaltime
diff --git a/source/blender/blenkernel/intern/fluidsim.c b/source/blender/blenkernel/intern/fluidsim.c
index 9be599ac66c..efc9869c5ca 100644
--- a/source/blender/blenkernel/intern/fluidsim.c
+++ b/source/blender/blenkernel/intern/fluidsim.c
@@ -41,7 +41,7 @@
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_object_fluidsim.h"
-#include "DNA_object_force.h" // for pointcache
+#include "DNA_object_force.h" // for pointcache
#include "DNA_object_types.h"
#include "DNA_particle_types.h"
#include "DNA_scene_types.h" // N_T
@@ -66,14 +66,14 @@
//-------------------------------------------------------------------------------
void initElbeemMesh(struct Scene *scene, struct Object *ob,
- int *numVertices, float **vertices,
- int *numTriangles, int **triangles,
- int useGlobalCoords, int modifierIndex)
+ int *numVertices, float **vertices,
+ int *numTriangles, int **triangles,
+ int useGlobalCoords, int modifierIndex)
{
DerivedMesh *dm = NULL;
MVert *mvert;
MFace *mface;
- int countTris=0, i, totvert, totface;
+ int countTris = 0, i, totvert, totface;
float *verts;
int *tris;
@@ -87,35 +87,35 @@ void initElbeemMesh(struct Scene *scene, struct Object *ob,
totface = dm->getNumTessFaces(dm);
*numVertices = totvert;
- verts = MEM_callocN(totvert*3*sizeof(float), "elbeemmesh_vertices");
- for (i=0; i<totvert; i++) {
- copy_v3_v3(&verts[i*3], mvert[i].co);
- if (useGlobalCoords) { mul_m4_v3(ob->obmat, &verts[i*3]); }
+ verts = MEM_callocN(totvert * 3 * sizeof(float), "elbeemmesh_vertices");
+ for (i = 0; i < totvert; i++) {
+ copy_v3_v3(&verts[i * 3], mvert[i].co);
+ if (useGlobalCoords) { mul_m4_v3(ob->obmat, &verts[i * 3]); }
}
*vertices = verts;
- for (i=0; i<totface; i++) {
+ for (i = 0; i < totface; i++) {
countTris++;
if (mface[i].v4) { countTris++; }
}
*numTriangles = countTris;
- tris = MEM_callocN(countTris*3*sizeof(int), "elbeemmesh_triangles");
+ tris = MEM_callocN(countTris * 3 * sizeof(int), "elbeemmesh_triangles");
countTris = 0;
- for (i=0; i<totface; i++) {
+ for (i = 0; i < totface; i++) {
int face[4];
face[0] = mface[i].v1;
face[1] = mface[i].v2;
face[2] = mface[i].v3;
face[3] = mface[i].v4;
- tris[countTris*3+0] = face[0];
- tris[countTris*3+1] = face[1];
- tris[countTris*3+2] = face[2];
+ tris[countTris * 3 + 0] = face[0];
+ tris[countTris * 3 + 1] = face[1];
+ tris[countTris * 3 + 2] = face[2];
countTris++;
if (face[3]) {
- tris[countTris*3+0] = face[0];
- tris[countTris*3+1] = face[2];
- tris[countTris*3+2] = face[3];
+ tris[countTris * 3 + 0] = face[0];
+ tris[countTris * 3 + 1] = face[2];
+ tris[countTris * 3 + 2] = face[3];
countTris++;
}
}
diff --git a/source/blender/blenkernel/intern/fmodifier.c b/source/blender/blenkernel/intern/fmodifier.c
index 538d2469a93..2b393b4d90b 100644
--- a/source/blender/blenkernel/intern/fmodifier.c
+++ b/source/blender/blenkernel/intern/fmodifier.c
@@ -42,16 +42,13 @@
#include "BLF_translation.h"
#include "BLI_blenlib.h"
+#include "BLI_noise.h"
#include "BLI_math.h" /* windows needs for M_PI */
#include "BLI_utildefines.h"
#include "BKE_fcurve.h"
#include "BKE_idprop.h"
-
-#define SMALL -1.0e-10
-#define SELECT 1
-
/* ******************************** F-Modifiers ********************************* */
/* Info ------------------------------- */
@@ -159,7 +156,7 @@ static void fcm_generator_verify(FModifier *fcm)
/* free the old data */
MEM_freeN(data->coefficients);
- }
+ }
/* set the new data */
data->coefficients = nc;
@@ -185,7 +182,7 @@ static void fcm_generator_verify(FModifier *fcm)
/* free the old data */
MEM_freeN(data->coefficients);
- }
+ }
/* set the new data */
data->coefficients = nc;
@@ -279,7 +276,7 @@ static FModifierTypeInfo FMI_GENERATOR = {
/* Built-In Function Generator F-Curve Modifier --------------------------- */
/* This uses the general equation for equations:
- * y = amplitude * fn(phase_multiplier*x + phase_offset) + y_offset
+ * y = amplitude * fn(phase_multiplier * x + phase_offset) + y_offset
*
* where amplitude, phase_multiplier/offset, y_offset are user-defined coefficients,
* x is the evaluation 'time', and 'y' is the resultant value
@@ -319,7 +316,7 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float
* WARNING: must perform special argument validation hereto guard against crashes
*/
switch (data->type) {
- /* simple ones */
+ /* simple ones */
case FCM_GENERATOR_FN_SIN: /* sine wave */
fn = sin;
break;
@@ -1025,7 +1022,7 @@ FModifier *add_fmodifier(ListBase *modifiers, int type)
fcm->data = MEM_callocN(fmi->size, fmi->structName);
/* init custom settings if necessary */
- if (fmi->new_data)
+ if (fmi->new_data)
fmi->new_data(fcm->data);
/* return modifier for further editing */
@@ -1102,7 +1099,7 @@ int remove_fmodifier(ListBase *modifiers, FModifier *fcm)
if (modifiers) {
BLI_freelinkN(modifiers, fcm);
return 1;
- }
+ }
else {
/* XXX this case can probably be removed some day, as it shouldn't happen... */
printf("remove_fmodifier() - no modifier stack given\n");
diff --git a/source/blender/blenkernel/intern/font.c b/source/blender/blenkernel/intern/font.c
index 8b35974ea62..d4634748c71 100644
--- a/source/blender/blenkernel/intern/font.c
+++ b/source/blender/blenkernel/intern/font.c
@@ -177,7 +177,7 @@ static VFontData *vfont_get_data(Main *bmain, VFont *vfont)
}
}
- return vfont->data;
+ return vfont->data;
}
VFont *BKE_vfont_load(Main *bmain, const char *name)
@@ -306,23 +306,23 @@ static void build_underline(Curve *cu, float x1, float y1, float x2, float y2, i
nu2->bp = bp;
nu2->bp[0].vec[0] = x1;
- nu2->bp[0].vec[1] = y1;
+ nu2->bp[0].vec[1] = y1;
nu2->bp[0].vec[2] = 0;
nu2->bp[0].vec[3] = 1.0f;
nu2->bp[1].vec[0] = x2;
nu2->bp[1].vec[1] = y1;
- nu2->bp[1].vec[2] = 0;
+ nu2->bp[1].vec[2] = 0;
nu2->bp[1].vec[3] = 1.0f;
nu2->bp[2].vec[0] = x2;
- nu2->bp[2].vec[1] = y2;
+ nu2->bp[2].vec[1] = y2;
nu2->bp[2].vec[2] = 0;
nu2->bp[2].vec[3] = 1.0f;
nu2->bp[3].vec[0] = x1;
nu2->bp[3].vec[1] = y2;
- nu2->bp[3].vec[2] = 0;
+ nu2->bp[3].vec[2] = 0;
nu2->bp[3].vec[3] = 1.0f;
- BLI_addtail(&(cu->nurb), nu2);
+ BLI_addtail(&(cu->nurb), nu2);
}
@@ -545,7 +545,7 @@ struct CharTrans *BKE_vfont_to_curve(Main *bmain, Scene *scene, Object *ob, int
/* The VFont Data can not be found */
if (!vfd) {
if (mem)
- MEM_freeN(mem);
+ MEM_freeN(mem);
return NULL;
}
@@ -671,7 +671,7 @@ makebreak:
yof -= linedist;
- maxlen = maxf(maxlen, (xof - tb->x / cu->fsize));
+ maxlen = max_ff(maxlen, (xof - tb->x / cu->fsize));
linedata[lnr] = xof - tb->x / cu->fsize;
linedata2[lnr] = cnr;
linedata3[lnr] = tb->w / cu->fsize;
@@ -731,7 +731,7 @@ makebreak:
if (ascii == 32) {
wsfac = cu->wordspace;
wsnr++;
- }
+ }
else {
wsfac = 1.0f;
}
@@ -754,7 +754,7 @@ makebreak:
for (i = 0; i <= slen; i++, tmp++, ct++) {
ascii = *tmp;
if (ascii == '\n' || ascii == '\r' || ct->dobreak) cu->lines++;
- }
+ }
/* linedata is now: width of line
* linedata2 is now: number of characters
@@ -792,7 +792,7 @@ makebreak:
// }
ct++;
}
- }
+ }
else if ((cu->spacemode == CU_JUSTIFY) && (cu->tb[0].w != 0.0f)) {
float curofs = 0.0f;
for (i = 0; i <= slen; i++) {
@@ -928,8 +928,12 @@ makebreak:
* 3: curs down */
ct = chartransdata + cu->pos;
- if ((mode == FO_CURSUP || mode == FO_PAGEUP) && ct->linenr == 0) ;
- else if ((mode == FO_CURSDOWN || mode == FO_PAGEDOWN) && ct->linenr == lnr) ;
+ if ((mode == FO_CURSUP || mode == FO_PAGEUP) && ct->linenr == 0) {
+ /* pass */
+ }
+ else if ((mode == FO_CURSDOWN || mode == FO_PAGEDOWN) && ct->linenr == lnr) {
+ /* pass */
+ }
else {
switch (mode) {
case FO_CURSUP: lnr = ct->linenr - 1; break;
diff --git a/source/blender/blenkernel/intern/gpencil.c b/source/blender/blenkernel/intern/gpencil.c
index 2ec5801746c..a7d0152a799 100644
--- a/source/blender/blenkernel/intern/gpencil.c
+++ b/source/blender/blenkernel/intern/gpencil.c
@@ -87,6 +87,7 @@ void free_gpencil_frames(bGPDlayer *gpl)
free_gpencil_strokes(gpf);
BLI_freelinkN(&gpl->frames, gpf);
}
+ gpl->actframe = NULL;
}
/* Free all of the gp-layers for a viewport (list should be &gpd->layers or so) */
@@ -163,7 +164,7 @@ bGPDframe *gpencil_frame_addnew(bGPDlayer *gpl, int cframe)
}
/* add a new gp-layer and make it the active layer */
-bGPDlayer *gpencil_layer_addnew(bGPdata *gpd)
+bGPDlayer *gpencil_layer_addnew(bGPdata *gpd, const char *name, int setactive)
{
bGPDlayer *gpl;
@@ -182,11 +183,12 @@ bGPDlayer *gpencil_layer_addnew(bGPdata *gpd)
gpl->thickness = 3;
/* auto-name */
- strcpy(gpl->info, "GP_Layer");
+ strcpy(gpl->info, name);
BLI_uniquename(&gpd->layers, gpl, "GP_Layer", '.', offsetof(bGPDlayer, info), sizeof(gpl->info));
/* make this one the active one */
- gpencil_layer_setactive(gpd, gpl);
+ if (setactive)
+ gpencil_layer_setactive(gpd, gpl);
/* return layer */
return gpl;
@@ -509,15 +511,13 @@ void gpencil_layer_setactive(bGPdata *gpd, bGPDlayer *active)
}
/* delete the active gp-layer */
-void gpencil_layer_delactive(bGPdata *gpd)
+void gpencil_layer_delete(bGPdata *gpd, bGPDlayer *gpl)
{
- bGPDlayer *gpl = gpencil_layer_getactive(gpd);
-
/* error checking */
if (ELEM(NULL, gpd, gpl))
return;
- /* free layer */
+ /* free layer */
free_gpencil_frames(gpl);
BLI_freelinkN(&gpd->layers, gpl);
}
diff --git a/source/blender/blenkernel/intern/group.c b/source/blender/blenkernel/intern/group.c
index 500df1b7b75..20d874e7243 100644
--- a/source/blender/blenkernel/intern/group.c
+++ b/source/blender/blenkernel/intern/group.c
@@ -98,7 +98,7 @@ void BKE_group_unlink(Group *group)
base->object->flag &= ~OB_FROMGROUP;
base->flag &= ~OB_FROMGROUP;
}
- }
+ }
for (srl = sce->r.layers.first; srl; srl = srl->next) {
if (srl->light_override == group)
@@ -110,16 +110,6 @@ void BKE_group_unlink(Group *group)
if (ob->dup_group == group) {
ob->dup_group = NULL;
-#if 0 /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
- {
- bActionStrip *strip;
- /* duplicator strips use a group object, we remove it */
- for (strip = ob->nlastrips.first; strip; strip = strip->next) {
- if (strip->object)
- strip->object = NULL;
- }
- }
-#endif
}
for (psys = ob->particlesystem.first; psys; psys = psys->next) {
@@ -383,57 +373,3 @@ void group_handle_recalc_and_update(Scene *scene, Object *UNUSED(parent), Group
}
}
}
-
-#if 0
-Object *group_get_member_with_action(Group *group, bAction *act)
-{
- GroupObject *go;
-
- if (group == NULL || act == NULL) return NULL;
-
- for (go = group->gobject.first; go; go = go->next) {
- if (go->ob) {
- if (go->ob->action == act)
- return go->ob;
- if (go->ob->nlastrips.first) {
- bActionStrip *strip;
-
- for (strip = go->ob->nlastrips.first; strip; strip = strip->next) {
- if (strip->act == act)
- return go->ob;
- }
- }
- }
- }
- return NULL;
-}
-
-/* if group has NLA, we try to map the used objects in NLA to group members */
-/* this assuming that object has received a new group link */
-void group_relink_nla_objects(Object *ob)
-{
- Group *group;
- GroupObject *go;
- bActionStrip *strip;
-
- if (ob == NULL || ob->dup_group == NULL) return;
- group = ob->dup_group;
-
- for (strip = ob->nlastrips.first; strip; strip = strip->next) {
- if (strip->object) {
- for (go = group->gobject.first; go; go = go->next) {
- if (go->ob) {
- if (strcmp(go->ob->id.name, strip->object->id.name) == 0)
- break;
- }
- }
- if (go)
- strip->object = go->ob;
- else
- strip->object = NULL;
- }
-
- }
-}
-
-#endif
diff --git a/source/blender/blenkernel/intern/icons.c b/source/blender/blenkernel/intern/icons.c
index 8a49cba7649..d8c3e260399 100644
--- a/source/blender/blenkernel/intern/icons.c
+++ b/source/blender/blenkernel/intern/icons.c
@@ -65,7 +65,7 @@ static void icon_free(void *val)
Icon *icon = val;
if (icon) {
- if (icon->drawinfo_free) {
+ if (icon->drawinfo_free) {
icon->drawinfo_free(icon->drawinfo);
}
else if (icon->drawinfo) {
@@ -255,7 +255,7 @@ void BKE_icon_changed(int id)
prv->changed_timestamp[i]++;
}
}
- }
+ }
}
int BKE_icon_getid(struct ID *id)
diff --git a/source/blender/blenkernel/intern/idprop.c b/source/blender/blenkernel/intern/idprop.c
index 8229df28ab8..5dd0f08dc71 100644
--- a/source/blender/blenkernel/intern/idprop.c
+++ b/source/blender/blenkernel/intern/idprop.c
@@ -484,7 +484,7 @@ void IDP_ReplaceInGroup(IDProperty *group, IDProperty *prop)
BLI_remlink(&group->data.group, loop);
IDP_FreeProperty(loop);
- MEM_freeN(loop);
+ MEM_freeN(loop);
}
else {
group->len++;
@@ -492,6 +492,30 @@ void IDP_ReplaceInGroup(IDProperty *group, IDProperty *prop)
}
}
+/*
+ * If a property is missing in \a dest, add it.
+ */
+void IDP_MergeGroup(IDProperty *dest, IDProperty *src, const int do_overwrite)
+{
+ IDProperty *prop;
+
+ if (do_overwrite) {
+ for (prop = src->data.group.first; prop; prop = prop->next) {
+ IDProperty *copy = IDP_CopyProperty(prop);
+ IDP_ReplaceInGroup(dest, copy);
+ }
+ }
+ else {
+ for (prop = src->data.group.first; prop; prop = prop->next) {
+ if (IDP_GetPropertyFromGroup(dest, prop->name) == NULL) {
+ IDProperty *copy = IDP_CopyProperty(prop);
+ dest->len++;
+ BLI_addtail(&dest->data.group, copy);
+ }
+ }
+ }
+}
+
/* returns 0 if an id property with the same name exists and it failed,
* or 1 if it succeeded in adding to the group.*/
int IDP_AddToGroup(IDProperty *group, IDProperty *prop)
@@ -608,60 +632,77 @@ IDProperty *IDP_GetProperties(ID *id, int create_if_needed)
}
}
-int IDP_EqualsProperties(IDProperty *prop1, IDProperty *prop2)
+/**
+ * \param is_strict When FALSE treat missing items as a match */
+int IDP_EqualsProperties_ex(IDProperty *prop1, IDProperty *prop2, const int is_strict)
{
if (prop1 == NULL && prop2 == NULL)
return 1;
else if (prop1 == NULL || prop2 == NULL)
- return 0;
+ return is_strict ? 0 : 1;
else if (prop1->type != prop2->type)
return 0;
- if (prop1->type == IDP_INT)
- return (IDP_Int(prop1) == IDP_Int(prop2));
- else if (prop1->type == IDP_FLOAT)
- return (IDP_Float(prop1) == IDP_Float(prop2));
- else if (prop1->type == IDP_DOUBLE)
- return (IDP_Double(prop1) == IDP_Double(prop2));
- else if (prop1->type == IDP_STRING)
- return ((prop1->len == prop2->len) && strncmp(IDP_String(prop1), IDP_String(prop2), prop1->len) == 0);
- else if (prop1->type == IDP_ARRAY) {
- if (prop1->len == prop2->len && prop1->subtype == prop2->subtype)
- return memcmp(IDP_Array(prop1), IDP_Array(prop2), idp_size_table[(int)prop1->subtype] * prop1->len);
- else
- return 0;
- }
- else if (prop1->type == IDP_GROUP) {
- IDProperty *link1, *link2;
-
- if (BLI_countlist(&prop1->data.group) != BLI_countlist(&prop2->data.group))
- return 0;
-
- for (link1 = prop1->data.group.first; link1; link1 = link1->next) {
- link2 = IDP_GetPropertyFromGroup(prop2, link1->name);
-
- if (!IDP_EqualsProperties(link1, link2))
+ switch (prop1->type) {
+ case IDP_INT:
+ return (IDP_Int(prop1) == IDP_Int(prop2));
+ case IDP_FLOAT:
+ return (IDP_Float(prop1) == IDP_Float(prop2));
+ case IDP_DOUBLE:
+ return (IDP_Double(prop1) == IDP_Double(prop2));
+ case IDP_STRING:
+ return ((prop1->len == prop2->len) && strncmp(IDP_String(prop1), IDP_String(prop2), prop1->len) == 0);
+ case IDP_ARRAY:
+ if (prop1->len == prop2->len && prop1->subtype == prop2->subtype) {
+ return memcmp(IDP_Array(prop1), IDP_Array(prop2), idp_size_table[(int)prop1->subtype] * prop1->len);
+ }
+ else {
return 0;
- }
+ }
+ case IDP_GROUP:
+ {
+ IDProperty *link1, *link2;
- return 1;
- }
- else if (prop1->type == IDP_IDPARRAY) {
- IDProperty *array1 = IDP_IDPArray(prop1);
- IDProperty *array2 = IDP_IDPArray(prop2);
- int i;
+ if (is_strict && BLI_countlist(&prop1->data.group) != BLI_countlist(&prop2->data.group))
+ return 0;
- if (prop1->len != prop2->len)
- return 0;
-
- for (i = 0; i < prop1->len; i++)
- if (!IDP_EqualsProperties(&array1[i], &array2[i]))
+ for (link1 = prop1->data.group.first; link1; link1 = link1->next) {
+ link2 = IDP_GetPropertyFromGroup(prop2, link1->name);
+
+ if (!IDP_EqualsProperties_ex(link1, link2, is_strict))
+ return 0;
+ }
+
+ return 1;
+ }
+ case IDP_IDPARRAY:
+ {
+ IDProperty *array1 = IDP_IDPArray(prop1);
+ IDProperty *array2 = IDP_IDPArray(prop2);
+ int i;
+
+ if (prop1->len != prop2->len)
return 0;
+
+ for (i = 0; i < prop1->len; i++)
+ if (!IDP_EqualsProperties(&array1[i], &array2[i]))
+ return 0;
+ return 1;
+ }
+ default:
+ /* should never get here */
+ BLI_assert(0);
+ break;
}
-
+
return 1;
}
+int IDP_EqualsProperties(IDProperty *prop1, IDProperty *prop2)
+{
+ return IDP_EqualsProperties_ex(prop1, prop2, TRUE);
+}
+
/* 'val' is never NULL, don't check */
IDProperty *IDP_New(const int type, const IDPropertyTemplate *val, const char *name)
{
@@ -679,7 +720,7 @@ IDProperty *IDP_New(const int type, const IDPropertyTemplate *val, const char *n
case IDP_DOUBLE:
prop = MEM_callocN(sizeof(IDProperty), "IDProperty float");
*(double *)&prop->data.val = val->d;
- break;
+ break;
case IDP_ARRAY:
{
/* for now, we only support float and int and double arrays */
diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c
index f08af55c36e..ef751ce3493 100644
--- a/source/blender/blenkernel/intern/image.c
+++ b/source/blender/blenkernel/intern/image.c
@@ -603,7 +603,8 @@ Image *BKE_image_load_exists(const char *filepath)
return BKE_image_load(filepath);
}
-static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short gen_type, float color[4])
+static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short gen_type,
+ float color[4], ColorManagedColorspaceSettings *colorspace_settings)
{
ImBuf *ibuf;
unsigned char *rect = NULL;
@@ -612,10 +613,26 @@ static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char
if (floatbuf) {
ibuf = IMB_allocImBuf(width, height, depth, IB_rectfloat);
rect_float = ibuf->rect_float;
+
+ if (colorspace_settings->name[0] == '\0') {
+ const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_FLOAT);
+
+ BLI_strncpy(colorspace_settings->name, colorspace, sizeof(colorspace_settings->name));
+ }
+
+ IMB_colormanagement_check_is_data(ibuf, colorspace_settings->name);
}
else {
ibuf = IMB_allocImBuf(width, height, depth, IB_rect);
rect = (unsigned char *)ibuf->rect;
+
+ if (colorspace_settings->name[0] == '\0') {
+ const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE);
+
+ BLI_strncpy(colorspace_settings->name, colorspace, sizeof(colorspace_settings->name));
+ }
+
+ IMB_colormanagement_assign_rect_colorspace(ibuf, colorspace_settings->name);
}
BLI_strncpy(ibuf->name, name, sizeof(ibuf->name));
@@ -650,7 +667,7 @@ Image *BKE_image_add_generated(unsigned int width, unsigned int height, const ch
ima->gen_type = gen_type;
ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
- ibuf = add_ibuf_size(width, height, ima->name, depth, floatbuf, gen_type, color);
+ ibuf = add_ibuf_size(width, height, ima->name, depth, floatbuf, gen_type, color, &ima->colorspace_settings);
image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
ima->ok = IMA_OK_LOADED;
@@ -1016,7 +1033,7 @@ int BKE_imtype_supports_quality(const char imtype)
return 0;
}
-int BKE_imtype_supports_float(const char imtype)
+int BKE_imtype_requires_linear_float(const char imtype)
{
switch (imtype) {
case R_IMF_IMTYPE_CINEON:
@@ -1046,6 +1063,7 @@ char BKE_imtype_valid_channels(const char imtype)
case R_IMF_IMTYPE_DDS:
case R_IMF_IMTYPE_JP2:
case R_IMF_IMTYPE_QUICKTIME:
+ case R_IMF_IMTYPE_DPX:
chan_flag |= IMA_CHAN_FLAG_ALPHA;
}
@@ -1074,10 +1092,11 @@ char BKE_imtype_valid_depths(const char imtype)
return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
case R_IMF_IMTYPE_MULTILAYER:
return R_IMF_CHAN_DEPTH_32;
- /* eeh, cineone does some strange 10bits per channel */
+ /* eeh, cineon does some strange 10bits per channel */
case R_IMF_IMTYPE_DPX:
+ return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_10 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
case R_IMF_IMTYPE_CINEON:
- return R_IMF_CHAN_DEPTH_12;
+ return R_IMF_CHAN_DEPTH_10;
case R_IMF_IMTYPE_JP2:
return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
/* most formats are 8bit only */
@@ -1227,6 +1246,9 @@ void BKE_imformat_defaults(ImageFormatData *im_format)
im_format->imtype = R_IMF_IMTYPE_PNG;
im_format->quality = 90;
im_format->compress = 90;
+
+ BKE_color_managed_display_settings_init(&im_format->display_settings);
+ BKE_color_managed_view_settings_init(&im_format->view_settings);
}
void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *imbuf)
@@ -1805,9 +1827,33 @@ int BKE_imbuf_write(ImBuf *ibuf, const char *name, ImageFormatData *imf)
#ifdef WITH_CINEON
else if (imtype == R_IMF_IMTYPE_CINEON) {
ibuf->ftype = CINEON;
+ if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
+ ibuf->ftype |= CINEON_LOG;
+ }
+ if (imf->depth == R_IMF_CHAN_DEPTH_16) {
+ ibuf->ftype |= CINEON_16BIT;
+ }
+ else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
+ ibuf->ftype |= CINEON_12BIT;
+ }
+ else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
+ ibuf->ftype |= CINEON_10BIT;
+ }
}
else if (imtype == R_IMF_IMTYPE_DPX) {
ibuf->ftype = DPX;
+ if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
+ ibuf->ftype |= CINEON_LOG;
+ }
+ if (imf->depth == R_IMF_CHAN_DEPTH_16) {
+ ibuf->ftype |= CINEON_16BIT;
+ }
+ else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
+ ibuf->ftype |= CINEON_12BIT;
+ }
+ else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
+ ibuf->ftype |= CINEON_10BIT;
+ }
}
#endif
else if (imtype == R_IMF_IMTYPE_TARGA) {
@@ -2100,6 +2146,15 @@ void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
}
}
break;
+ case IMA_SIGNAL_COLORMANAGE:
+ image_free_buffers(ima);
+
+ ima->ok = 1;
+
+ if (iuser)
+ iuser->ok = 1;
+
+ break;
}
/* don't use notifiers because they are not 100% sure to succeeded
@@ -2201,8 +2256,10 @@ void BKE_image_backup_render(Scene *scene, Image *ima)
/* in that case we have to build a render-result */
static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
{
+ const char *colorspace = ima->colorspace_settings.name;
+ int predivide = ima->flag & IMA_CM_PREDIVIDE;
- ima->rr = RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
+ ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y);
#ifdef WITH_OPENEXR
IMB_exr_close(ibuf->userdata);
@@ -2541,7 +2598,7 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_
*lock_r = re;
}
- /* this gives active layer, composite or seqence result */
+ /* this gives active layer, composite or sequence result */
rect = (unsigned int *)rres.rect32;
rectf = rres.rectf;
rectz = rres.rectz;
@@ -2595,15 +2652,21 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_
/* free rect buffer if float buffer changes, so it can be recreated with
* the updated result, and also in case we got byte buffer from sequencer,
* so we don't keep reference to freed buffer */
-
- /* todo: this fix breaks save buffers render progress
- if (ibuf->rect_float != rectf || rect || !rectf) */
-
if (ibuf->rect_float != rectf || rect)
imb_freerectImBuf(ibuf);
- if (rect)
+ if (rect) {
ibuf->rect = rect;
+ }
+ else {
+ /* byte buffer of render result has been freed, make sure image buffers
+ * does not reference to this buffer anymore
+ * need check for whether byte buffer was allocated and owned by image itself
+ * or if it's reusing buffer from render result
+ */
+ if ((ibuf->mall & IB_rect) == 0)
+ ibuf->rect = NULL;
+ }
if (rectf) {
ibuf->rect_float = rectf;
@@ -2782,7 +2845,8 @@ ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
/* UV testgrid or black or solid etc */
if (ima->gen_x == 0) ima->gen_x = 1024;
if (ima->gen_y == 0) ima->gen_y = 1024;
- ibuf = add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
+ ibuf = add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type,
+ color, &ima->colorspace_settings);
image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
ima->ok = IMA_OK_LOADED;
}
@@ -2998,5 +3062,8 @@ void BKE_image_get_aspect(Image *image, float *aspx, float *aspy)
*aspx = 1.0;
/* x is always 1 */
- *aspy = image->aspy / image->aspx;
+ if (image)
+ *aspy = image->aspy / image->aspx;
+ else
+ *aspy = 1.0f;
}
diff --git a/source/blender/blenkernel/intern/image_gen.c b/source/blender/blenkernel/intern/image_gen.c
index 37572eebed6..468a88775c6 100644
--- a/source/blender/blenkernel/intern/image_gen.c
+++ b/source/blender/blenkernel/intern/image_gen.c
@@ -244,7 +244,7 @@ static void checker_board_color_tint(unsigned char *rect, float *rect_float, int
}
}
- }
+ }
}
static void checker_board_grid_fill(unsigned char *rect, float *rect_float, int width, int height, float blend)
diff --git a/source/blender/blenkernel/intern/implicit.c b/source/blender/blenkernel/intern/implicit.c
index fcc8b4322a0..90cd7bc2df5 100644
--- a/source/blender/blenkernel/intern/implicit.c
+++ b/source/blender/blenkernel/intern/implicit.c
@@ -48,7 +48,9 @@
#include "BKE_global.h"
-#define CLOTH_OPENMP_LIMIT 512
+#ifdef _OPENMP
+# define CLOTH_OPENMP_LIMIT 512
+#endif
#if 0 /* debug timing */
#ifdef _WIN32
@@ -588,7 +590,7 @@ DO_INLINE void mul_bfmatrix_lfvector( float (*to)[3], fmatrix3x3 *from, lfVector
for (i = from[0].vcount; i < from[0].vcount+from[0].scount; i++) {
muladd_fmatrix_fvector(to[from[i].c], from[i].m, fLongVector[from[i].r]);
}
- }
+ }
#pragma omp section
{
for (i = 0; i < from[0].vcount+from[0].scount; i++) {
@@ -621,7 +623,7 @@ DO_INLINE void add_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix
/* process diagonal elements */
for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) {
- add_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ add_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
}
}
@@ -632,7 +634,7 @@ DO_INLINE void addadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmat
/* process diagonal elements */
for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) {
- addadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ addadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
}
}
@@ -643,7 +645,7 @@ DO_INLINE void subadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmat
/* process diagonal elements */
for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) {
- subadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ subadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
}
}
@@ -654,7 +656,7 @@ DO_INLINE void sub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix
/* process diagonal elements */
for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) {
- sub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ sub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
}
}
@@ -665,7 +667,7 @@ DO_INLINE void sub_bfmatrix_Smatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3
/* process diagonal elements */
for (i = 0; i < matrix[0].vcount; i++) {
- sub_fmatrix_fmatrix(to[matrix[i].c].m, from[matrix[i].c].m, matrix[i].m);
+ sub_fmatrix_fmatrix(to[matrix[i].c].m, from[matrix[i].c].m, matrix[i].m);
}
}
@@ -676,7 +678,7 @@ DO_INLINE void addsub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmat
/* process diagonal elements */
for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) {
- addsub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ addsub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
}
}
@@ -689,7 +691,7 @@ DO_INLINE void subadd_bfmatrixS_bfmatrixS( fmatrix3x3 *to, fmatrix3x3 *from, flo
/* process diagonal elements */
for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) {
- subadd_fmatrixS_fmatrixS(to[i].m, from[i].m, aS, matrix[i].m, bS);
+ subadd_fmatrixS_fmatrixS(to[i].m, from[i].m, aS, matrix[i].m, bS);
}
}
@@ -709,7 +711,7 @@ static void update_matrixS(ClothVertex *verts, int numverts, fmatrix3x3 *S)
int i = 0;
/* Clear matrix from old vertex constraints */
- for(i = 0; i < S[0].vcount; i++)
+ for (i = 0; i < S[0].vcount; i++)
S[i].c = S[i].r = 0;
/* Set new vertex constraints */
@@ -747,7 +749,7 @@ int implicit_init(Object *UNUSED(ob), ClothModifierData *clmd)
id = (Implicit_Data *)MEM_callocN(sizeof(Implicit_Data), "implicit vecmat");
cloth->implicit = id;
- /* process diagonal elements */
+ /* process diagonal elements */
id->A = create_bfmatrix(cloth->numverts, cloth->numsprings);
id->dFdV = create_bfmatrix(cloth->numverts, cloth->numsprings);
id->dFdX = create_bfmatrix(cloth->numverts, cloth->numsprings);
@@ -842,41 +844,40 @@ int implicit_free(ClothModifierData *clmd)
DO_INLINE float fb(float length, float L)
{
- float x = length/L;
- return (-11.541f*pow(x, 4)+34.193f*pow(x, 3)-39.083f*pow(x, 2)+23.116f*x-9.713f);
+ float x = length / L;
+ return (-11.541f * powf(x, 4) + 34.193f * powf(x, 3) - 39.083f * powf(x, 2) + 23.116f * x - 9.713f);
}
DO_INLINE float fbderiv(float length, float L)
{
float x = length/L;
- return (-46.164f*pow(x, 3)+102.579f*pow(x, 2)-78.166f*x+23.116f);
+ return (-46.164f * powf(x, 3) + 102.579f * powf(x, 2) - 78.166f * x + 23.116f);
}
DO_INLINE float fbstar(float length, float L, float kb, float cb)
{
- float tempfb = kb * fb(length, L);
-
- float fbstar = cb * (length - L);
+ float tempfb_fl = kb * fb(length, L);
+ float fbstar_fl = cb * (length - L);
- if (tempfb < fbstar)
- return fbstar;
+ if (tempfb_fl < fbstar_fl)
+ return fbstar_fl;
else
- return tempfb;
+ return tempfb_fl;
}
// function to calculae bending spring force (taken from Choi & Co)
DO_INLINE float fbstar_jacobi(float length, float L, float kb, float cb)
{
- float tempfb = kb * fb(length, L);
- float fbstar = cb * (length - L);
+ float tempfb_fl = kb * fb(length, L);
+ float fbstar_fl = cb * (length - L);
- if (tempfb < fbstar) {
+ if (tempfb_fl < fbstar_fl) {
return cb;
}
else {
- return kb * fbderiv(length, L);
- }
+ return kb * fbderiv(length, L);
+ }
}
DO_INLINE void filter(lfVector *V, fmatrix3x3 *S)
@@ -916,7 +917,7 @@ static int cg_filtered(lfVector *ldV, fmatrix3x3 *lA, lfVector *lB, lfVector *z
cp_lfvector(d, r, numverts);
s = dot_lfvector(r, r, numverts);
- starget = s * sqrt(conjgrad_epsilon);
+ starget = s * sqrtf(conjgrad_epsilon);
while (s>starget && conjgrad_loopcount < conjgrad_looplimit) {
// Mul(q, A, d); // q = A*d;
@@ -1147,9 +1148,9 @@ DO_INLINE void dfdx_spring_type1(float to[3][3], float extent[3], float length,
// dir is unit length direction, rest is spring's restlength, k is spring constant.
// return (outerprod(dir, dir)*k + (I - outerprod(dir, dir))*(k - ((k*L)/length)));
float temp[3][3];
- float temp1 = k*(1.0 - (L/length));
+ float temp1 = k * (1.0f - (L / length));
- mul_fvectorT_fvectorS(temp, extent, extent, 1.0 / dot);
+ mul_fvectorT_fvectorS(temp, extent, extent, 1.0f / dot);
sub_fmatrix_fmatrix(to, I, temp);
mul_fmatrix_S(to, temp1);
@@ -1217,7 +1218,7 @@ DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s,
float stretch_force[3] = {0, 0, 0};
float bending_force[3] = {0, 0, 0};
float damping_force[3] = {0, 0, 0};
- float nulldfdx[3][3]={ {0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
+ float nulldfdx[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
float scaling = 0.0;
@@ -1245,7 +1246,7 @@ DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s,
s->flags |= CSPRING_FLAG_DEACTIVATE;
return;
}
- }
+ }
*/
mul_fvector_S(dir, extent, 1.0f/length);
}
@@ -1306,7 +1307,7 @@ DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s,
VECADDS(s->f, s->f, extent, -k);
- mul_fvector_S(damping_force, dir, clmd->sim_parms->goalfrict * 0.01 * dot_v3v3(vel, dir));
+ mul_fvector_S(damping_force, dir, clmd->sim_parms->goalfrict * 0.01f * dot_v3v3(vel, dir));
VECADD(s->f, s->f, damping_force);
// HERE IS THE PROBLEM!!!!
@@ -1317,10 +1318,10 @@ DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s,
if (length < L) {
s->flags |= CLOTH_SPRING_FLAG_NEEDED;
- k = clmd->sim_parms->bending;
+ k = clmd->sim_parms->bending;
- scaling = k + s->stiffness * ABS(clmd->sim_parms->max_bend-k);
- cb = k = scaling / (20.0*(clmd->sim_parms->avg_spring_len + FLT_EPSILON));
+ scaling = k + s->stiffness * ABS(clmd->sim_parms->max_bend-k);
+ cb = k = scaling / (20.0f * (clmd->sim_parms->avg_spring_len + FLT_EPSILON));
mul_fvector_S(bending_force, dir, fbstar(length, L, k, cb));
VECADD(s->f, s->f, bending_force);
@@ -1336,7 +1337,7 @@ DO_INLINE void cloth_apply_spring_force(ClothModifierData *UNUSED(clmd), ClothSp
if (!(s->type & CLOTH_SPRING_TYPE_BENDING)) {
sub_fmatrix_fmatrix(dFdV[s->ij].m, dFdV[s->ij].m, s->dfdv);
sub_fmatrix_fmatrix(dFdV[s->kl].m, dFdV[s->kl].m, s->dfdv);
- add_fmatrix_fmatrix(dFdV[s->matrix_index].m, dFdV[s->matrix_index].m, s->dfdv);
+ add_fmatrix_fmatrix(dFdV[s->matrix_index].m, dFdV[s->matrix_index].m, s->dfdv);
}
VECADD(lF[s->ij], lF[s->ij], s->f);
@@ -1347,7 +1348,7 @@ DO_INLINE void cloth_apply_spring_force(ClothModifierData *UNUSED(clmd), ClothSp
sub_fmatrix_fmatrix(dFdX[s->kl].m, dFdX[s->kl].m, s->dfdx);
sub_fmatrix_fmatrix(dFdX[s->ij].m, dFdX[s->ij].m, s->dfdx);
add_fmatrix_fmatrix(dFdX[s->matrix_index].m, dFdX[s->matrix_index].m, s->dfdx);
- }
+ }
}
@@ -1355,15 +1356,15 @@ static void CalcFloat( float *v1, float *v2, float *v3, float *n)
{
float n1[3], n2[3];
- n1[0]= v1[0]-v2[0];
- n2[0]= v2[0]-v3[0];
- n1[1]= v1[1]-v2[1];
- n2[1]= v2[1]-v3[1];
- n1[2]= v1[2]-v2[2];
- n2[2]= v2[2]-v3[2];
- n[0]= n1[1]*n2[2]-n1[2]*n2[1];
- n[1]= n1[2]*n2[0]-n1[0]*n2[2];
- n[2]= n1[0]*n2[1]-n1[1]*n2[0];
+ n1[0] = v1[0]-v2[0];
+ n2[0] = v2[0]-v3[0];
+ n1[1] = v1[1]-v2[1];
+ n2[1] = v2[1]-v3[1];
+ n1[2] = v1[2]-v2[2];
+ n2[2] = v2[2]-v3[2];
+ n[0] = n1[1]*n2[2]-n1[2]*n2[1];
+ n[1] = n1[2]*n2[0]-n1[0]*n2[2];
+ n[2] = n1[0]*n2[1]-n1[1]*n2[0];
}
static void CalcFloat4( float *v1, float *v2, float *v3, float *v4, float *n)
@@ -1371,17 +1372,17 @@ static void CalcFloat4( float *v1, float *v2, float *v3, float *v4, float *n)
/* real cross! */
float n1[3], n2[3];
- n1[0]= v1[0]-v3[0];
- n1[1]= v1[1]-v3[1];
- n1[2]= v1[2]-v3[2];
+ n1[0] = v1[0]-v3[0];
+ n1[1] = v1[1]-v3[1];
+ n1[2] = v1[2]-v3[2];
- n2[0]= v2[0]-v4[0];
- n2[1]= v2[1]-v4[1];
- n2[2]= v2[2]-v4[2];
+ n2[0] = v2[0]-v4[0];
+ n2[1] = v2[1]-v4[1];
+ n2[2] = v2[2]-v4[2];
- n[0]= n1[1]*n2[2]-n1[2]*n2[1];
- n[1]= n1[2]*n2[0]-n1[0]*n2[2];
- n[2]= n1[0]*n2[1]-n1[1]*n2[0];
+ n[0] = n1[1]*n2[2]-n1[2]*n2[1];
+ n[1] = n1[2]*n2[0]-n1[0]*n2[2];
+ n[2] = n1[0]*n2[1]-n1[1]*n2[0];
}
static float calculateVertexWindForce(float wind[3], float vertexnormal[3])
@@ -1448,7 +1449,7 @@ static void hair_velocity_smoothing(ClothModifierData *clmd, lfVector *lF, lfVec
i = HAIR_GRID_INDEX(lX[v], gmin, gmax, 0);
j = HAIR_GRID_INDEX(lX[v], gmin, gmax, 1);
k = HAIR_GRID_INDEX(lX[v], gmin, gmax, 2);
- if (i < 0 || j < 0 || k < 0 || i > 10 || j >= 10 || k >= 10)
+ if (i < 0 || j < 0 || k < 0 || i >= 10 || j >= 10 || k >= 10)
continue;
grid[i][j][k].velocity[0] += lV[v][0];
@@ -1478,7 +1479,7 @@ static void hair_velocity_smoothing(ClothModifierData *clmd, lfVector *lF, lfVec
colg[i][j][k].velocity[0] += vel[0];
colg[i][j][k].velocity[1] += vel[1];
colg[i][j][k].velocity[2] += vel[2];
- colg[i][j][k].density += 1.0;
+ colg[i][j][k].density += 1.0f;
}
}
}
@@ -1512,7 +1513,7 @@ static void hair_velocity_smoothing(ClothModifierData *clmd, lfVector *lF, lfVec
i = HAIR_GRID_INDEX(lX[v], gmin, gmax, 0);
j = HAIR_GRID_INDEX(lX[v], gmin, gmax, 1);
k = HAIR_GRID_INDEX(lX[v], gmin, gmax, 2);
- if (i < 0 || j < 0 || k < 0 || i > 10 || j >= 10 || k >= 10)
+ if (i < 0 || j < 0 || k < 0 || i >= 10 || j >= 10 || k >= 10)
continue;
lF[v][0] += smoothfac * (grid[i][j][k].velocity[0] - lV[v][0]);
@@ -1543,7 +1544,7 @@ static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), lfVec
lfVector *winvec;
EffectedPoint epoint;
- tm2[0][0]= tm2[1][1]= tm2[2][2]= -spring_air;
+ tm2[0][0] = tm2[1][1] = tm2[2][2] = -spring_air;
/* global acceleration (gravitation) */
if (clmd->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
@@ -1587,11 +1588,11 @@ static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), lfVec
}
for (i = 0; i < cloth->numfaces; i++) {
- float trinormal[3]={0, 0, 0}; // normalized triangle normal
- float triunnormal[3]={0, 0, 0}; // not-normalized-triangle normal
- float tmp[3]={0, 0, 0};
+ float trinormal[3] = {0, 0, 0}; // normalized triangle normal
+ float triunnormal[3] = {0, 0, 0}; // not-normalized-triangle normal
+ float tmp[3] = {0, 0, 0};
float factor = (mfaces[i].v4) ? 0.25 : 1.0 / 3.0;
- factor *= 0.02;
+ factor *= 0.02f;
// calculate face normal
if (mfaces[i].v4)
@@ -1627,9 +1628,9 @@ static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), lfVec
/* Hair has only edges */
if (cloth->numfaces == 0) {
ClothSpring *spring;
- float edgevec[3]={0, 0, 0}; //edge vector
- float edgeunnormal[3]={0, 0, 0}; // not-normalized-edge normal
- float tmp[3]={0, 0, 0};
+ float edgevec[3] = {0, 0, 0}; //edge vector
+ float edgeunnormal[3] = {0, 0, 0}; // not-normalized-edge normal
+ float tmp[3] = {0, 0, 0};
float factor = 0.01;
search = cloth->springs;
@@ -1661,7 +1662,7 @@ static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), lfVec
while (search) {
// only handle active springs
ClothSpring *spring = search->link;
- if( !(spring->flags & CLOTH_SPRING_FLAG_DEACTIVATE))
+ if (!(spring->flags & CLOTH_SPRING_FLAG_DEACTIVATE))
cloth_calc_spring_force(clmd, search->link, lF, lX, lV, dFdV, dFdX, time);
search = search->next;
@@ -1729,8 +1730,8 @@ static int UNUSED_FUNCTION(cloth_calc_helper_forces)(Object *UNUSED(ob), ClothMo
for (i=0; i<cloth->numverts; i++, cv++) {
copy_v3_v3(cos[i], cv->tx);
- if (cv->goal == 1.0f || len_v3v3(initial_cos[i], cv->tx) != 0.0) {
- masses[i] = 1e+10;
+ if (cv->goal == 1.0f || len_squared_v3v3(initial_cos[i], cv->tx) != 0.0f) {
+ masses[i] = 1e+10;
}
else {
masses[i] = cv->mass;
@@ -1757,18 +1758,18 @@ static int UNUSED_FUNCTION(cloth_calc_helper_forces)(Object *UNUSED(ob), ClothMo
normalize_v3(vec);
c = (len - spring->restlen);
- if (c == 0.0)
+ if (c == 0.0f)
continue;
- l = c / ((1.0/masses[v1]) + (1.0/masses[v2]));
+ l = c / ((1.0f / masses[v1]) + (1.0f / masses[v2]));
- mul_v3_fl(vec, -(1.0/masses[v1])*l);
+ mul_v3_fl(vec, -(1.0f / masses[v1]) * l);
add_v3_v3(cos[v1], vec);
sub_v3_v3v3(vec, cos[v2], cos[v1]);
normalize_v3(vec);
- mul_v3_fl(vec, -(1.0/masses[v2])*l);
+ mul_v3_fl(vec, -(1.0f / masses[v2]) * l);
add_v3_v3(cos[v2], vec);
}
}
@@ -1813,7 +1814,7 @@ int implicit_solver(Object *ob, float frame, ClothModifierData *clmd, ListBase *
sub_v3_v3v3(id->V[i], verts[i].xconst, verts[i].xold);
// mul_v3_fl(id->V[i], clmd->sim_parms->stepsPerFrame);
}
- }
+ }
}
while (step < tf) {
@@ -1838,7 +1839,7 @@ int implicit_solver(Object *ob, float frame, ClothModifierData *clmd, ListBase *
mul_fvector_S(tvect, tvect, step+dt);
VECADD(tvect, tvect, verts[i].xold);
copy_v3_v3(id->Xnew[i], tvect);
- }
+ }
}
copy_v3_v3(verts[i].txold, id->X[i]);
@@ -1896,7 +1897,7 @@ int implicit_solver(Object *ob, float frame, ClothModifierData *clmd, ListBase *
cp_lfvector(id->V, id->Vnew, numverts);
// calculate
- cloth_calc_force(clmd, frame, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step+dt, id->M);
+ cloth_calc_force(clmd, frame, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step+dt, id->M);
simulate_implicit_euler(id->Vnew, id->X, id->V, id->F, id->dFdV, id->dFdX, dt / 2.0f, id->A, id->B, id->dV, id->S, id->z, id->olddV, id->P, id->Pinv, id->M, id->bigI);
}
@@ -1945,6 +1946,6 @@ void implicit_set_positions(ClothModifierData *clmd)
copy_v3_v3(id->V[i], verts[i].v);
}
if (G.debug_value > 0)
- printf("implicit_set_positions\n");
+ printf("implicit_set_positions\n");
}
diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c
index b2a9e229be9..59dd02849dd 100644
--- a/source/blender/blenkernel/intern/ipo.c
+++ b/source/blender/blenkernel/intern/ipo.c
@@ -32,7 +32,7 @@
/* NOTE:
*
- * This file is no longer used to provide tools for the depreceated IPO system. Instead, it
+ * This file is no longer used to provide tools for the deprecated IPO system. Instead, it
* is only used to house the conversion code to the new system.
*
* -- Joshua Leung, Jan 2009
@@ -569,7 +569,7 @@ static const char *material_adrcodes_to_paths(int adrcode, int *array_index)
return mtex_adrcodes_to_paths(adrcode, array_index);
}
- return NULL;
+ return NULL;
}
/* Camera Types */
@@ -727,7 +727,7 @@ static const char *world_adrcodes_to_paths(int adrcode, int *array_index)
return mtex_adrcodes_to_paths(adrcode, array_index);
}
- return NULL;
+ return NULL;
}
/* Particle Types */
@@ -873,7 +873,7 @@ static char *get_rna_access(int blocktype, int adrcode, char actname[], char con
propname = "eval_time";
break;
- /* XXX problematic blocktypes */
+ /* XXX problematic blocktypes */
case ID_SEQ: /* sequencer strip */
//SEQ_FAC1:
switch (adrcode) {
@@ -981,21 +981,21 @@ static char *get_rna_access(int blocktype, int adrcode, char actname[], char con
static short adrcode_to_dtar_transchan(short adrcode)
{
switch (adrcode) {
- case OB_LOC_X:
+ case OB_LOC_X:
return DTAR_TRANSCHAN_LOCX;
case OB_LOC_Y:
return DTAR_TRANSCHAN_LOCY;
case OB_LOC_Z:
return DTAR_TRANSCHAN_LOCZ;
- case OB_ROT_X:
+ case OB_ROT_X:
return DTAR_TRANSCHAN_ROTX;
case OB_ROT_Y:
return DTAR_TRANSCHAN_ROTY;
case OB_ROT_Z:
return DTAR_TRANSCHAN_ROTZ;
- case OB_SIZE_X:
+ case OB_SIZE_X:
return DTAR_TRANSCHAN_SCALEX;
case OB_SIZE_Y:
return DTAR_TRANSCHAN_SCALEX;
@@ -1359,8 +1359,8 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i
/* correct values for sequencer curves, that were not locked to frame */
if (seq && (seq->flag & SEQ_IPO_FRAME_LOCKED) == 0) {
- double mul = (seq->enddisp - seq->startdisp) / 100.0f;
- double offset = seq->startdisp;
+ const float mul = (seq->enddisp - seq->startdisp) / 100.0f;
+ const float offset = seq->startdisp;
dst->vec[0][0] *= mul;
dst->vec[0][0] += offset;
@@ -1645,7 +1645,7 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips)
/* by default, we now always extrapolate, while in the past this was optional */
if ((as->flag & ACTSTRIP_HOLDLASTFRAME) == 0)
strip->extendmode = NLASTRIP_EXTEND_NOTHING;
- }
+ }
/* try to add this strip to the current NLA-Track (i.e. the 'last' one on the stack atm) */
if (BKE_nlatrack_add_strip(nlt, strip) == 0) {
@@ -1757,15 +1757,15 @@ void do_versions_ipos_to_animato(Main *main)
{
/* If we have any empty action actuators, assume they were
- converted IPO Actuators using the object IPO */
+ * converted IPO Actuators using the object IPO */
bActuator *act;
bActionActuator *aa;
for (act = ob->actuators.first; act; act = act->next) {
/* Any actuators set to ACT_IPO at this point are actually Action Actuators that
- need this converted IPO to finish converting the actuator. */
+ * need this converted IPO to finish converting the actuator. */
if (act->type == ACT_IPO) {
- aa = (bActionActuator*)act->data;
+ aa = (bActionActuator *)act->data;
aa->act = ob->adt->action;
act->type = ACT_ACTION;
}
@@ -2093,7 +2093,7 @@ void do_versions_ipos_to_animato(Main *main)
bAction *new_act;
/* add a new action for this, and convert all data into that action */
- new_act = add_empty_action(id->name+2);
+ new_act = add_empty_action(id->name + 2);
ipo_to_animato(NULL, ipo, NULL, NULL, NULL, NULL, &new_act->curves, &drivers);
new_act->idroot = ipo->blocktype;
}
diff --git a/source/blender/blenkernel/intern/key.c b/source/blender/blenkernel/intern/key.c
index b79608342dd..782d796b8a7 100644
--- a/source/blender/blenkernel/intern/key.c
+++ b/source/blender/blenkernel/intern/key.c
@@ -94,7 +94,7 @@ void BKE_key_free(Key *key)
}
-void free_key_nolib(Key *key)
+void BKE_key_free_nolib(Key *key)
{
KeyBlock *kb;
@@ -121,7 +121,7 @@ void free_key_nolib(Key *key)
/* from misc_util: flip the bytes from x */
/* #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
-Key *add_key(ID *id) /* common function */
+Key *BKE_key_add(ID *id) /* common function */
{
Key *key;
char *el;
@@ -133,7 +133,7 @@ Key *add_key(ID *id) /* common function */
key->uidgen = 1;
- /* XXX the code here uses some defines which will soon be depreceated... */
+ /* XXX the code here uses some defines which will soon be deprecated... */
switch (GS(id->name)) {
case ID_ME:
el = key->elemstr;
@@ -196,7 +196,7 @@ Key *BKE_key_copy(Key *key)
}
-Key *copy_key_nolib(Key *key)
+Key *BKE_key_copy_nolib(Key *key)
{
Key *keyn;
KeyBlock *kbn, *kb;
@@ -241,7 +241,7 @@ void BKE_key_make_local(Key *key)
* currently being called.
*/
-void sort_keys(Key *key)
+void BKE_key_sort(Key *key)
{
KeyBlock *kb;
KeyBlock *kb2;
@@ -389,7 +389,7 @@ static int setkeys(float fac, ListBase *lb, KeyBlock *k[], float t[4], int cycl)
if (k1->next == NULL) k[0] = k1;
k1 = k1->next;
}
- /* k1= k[1]; */ /* UNUSED */
+ /* k1 = k[1]; */ /* UNUSED */
t[0] = k[0]->pos;
t[1] += dpos;
t[2] = k[2]->pos + dpos;
@@ -609,7 +609,7 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key
}
}
else k1 += start * key->elemsize;
- }
+ }
if (mode == KEY_MODE_BEZTRIPLE) {
elemstr[0] = 1;
@@ -691,8 +691,8 @@ static void cp_cu_key(Curve *cu, Key *key, KeyBlock *actkb, KeyBlock *kb, const
if (nu->bp) {
step = nu->pntsu * nu->pntsv;
- a1 = maxi(a, start);
- a2 = mini(a + step, end);
+ a1 = max_ii(a, start);
+ a2 = min_ii(a + step, end);
if (a1 < a2) cp_key(a1, a2, tot, out, key, actkb, kb, NULL, KEY_MODE_BPOINT);
}
@@ -700,8 +700,8 @@ static void cp_cu_key(Curve *cu, Key *key, KeyBlock *actkb, KeyBlock *kb, const
step = 3 * nu->pntsu;
/* exception because keys prefer to work with complete blocks */
- a1 = maxi(a, start);
- a2 = mini(a + step, end);
+ a1 = max_ii(a, start);
+ a2 = min_ii(a + step, end);
if (a1 < a2) cp_key(a1, a2, tot, out, key, actkb, kb, NULL, KEY_MODE_BEZTRIPLE);
}
@@ -711,7 +711,7 @@ static void cp_cu_key(Curve *cu, Key *key, KeyBlock *actkb, KeyBlock *kb, const
}
}
-void do_rel_key(const int start, int end, const int tot, char *basispoin, Key *key, KeyBlock *actkb, const int mode)
+void BKE_key_evaluate_relative(const int start, int end, const int tot, char *basispoin, Key *key, KeyBlock *actkb, const int mode)
{
KeyBlock *kb;
int *ofsp, ofs[3], elemsize, b;
@@ -1043,7 +1043,7 @@ static float *get_weights_array(Object *ob, char *vgroup)
/* find the group (weak loop-in-loop) */
defgrp_index = defgroup_name_index(ob, vgroup);
- if (defgrp_index >= 0) {
+ if (defgrp_index != -1) {
float *weights;
int i;
@@ -1071,7 +1071,7 @@ static float *get_weights_array(Object *ob, char *vgroup)
static void do_mesh_key(Scene *scene, Object *ob, Key *key, char *out, const int tot)
{
- KeyBlock *k[4], *actkb = ob_get_keyblock(ob);
+ KeyBlock *k[4], *actkb = BKE_keyblock_from_object(ob);
float t[4];
int flag = 0;
@@ -1106,7 +1106,7 @@ static void do_mesh_key(Scene *scene, Object *ob, Key *key, char *out, const int
kb->weights = get_weights_array(ob, kb->vgroup);
}
- do_rel_key(0, tot, tot, (char *)out, key, actkb, KEY_MODE_DUMMY);
+ BKE_key_evaluate_relative(0, tot, tot, (char *)out, key, actkb, KEY_MODE_DUMMY);
for (kb = key->block.first; kb; kb = kb->next) {
if (kb->weights) MEM_freeN(kb->weights);
@@ -1154,11 +1154,11 @@ static void do_rel_cu_key(Curve *cu, Key *key, KeyBlock *actkb, char *out, const
for (a = 0, nu = cu->nurb.first; nu; nu = nu->next, a += step) {
if (nu->bp) {
step = nu->pntsu * nu->pntsv;
- do_rel_key(a, a + step, tot, out, key, actkb, KEY_MODE_BPOINT);
+ BKE_key_evaluate_relative(a, a + step, tot, out, key, actkb, KEY_MODE_BPOINT);
}
else if (nu->bezt) {
step = 3 * nu->pntsu;
- do_rel_key(a, a + step, tot, out, key, actkb, KEY_MODE_BEZTRIPLE);
+ BKE_key_evaluate_relative(a, a + step, tot, out, key, actkb, KEY_MODE_BEZTRIPLE);
}
else {
step = 0;
@@ -1169,7 +1169,7 @@ static void do_rel_cu_key(Curve *cu, Key *key, KeyBlock *actkb, char *out, const
static void do_curve_key(Scene *scene, Object *ob, Key *key, char *out, const int tot)
{
Curve *cu = ob->data;
- KeyBlock *k[4], *actkb = ob_get_keyblock(ob);
+ KeyBlock *k[4], *actkb = BKE_keyblock_from_object(ob);
float t[4];
int flag = 0;
@@ -1217,7 +1217,7 @@ static void do_curve_key(Scene *scene, Object *ob, Key *key, char *out, const in
remain = step;
}
- count = mini(remain, estep);
+ count = min_ii(remain, estep);
if (mode == KEY_MODE_BEZTRIPLE) {
count += 3 - count % 3;
}
@@ -1251,7 +1251,7 @@ static void do_curve_key(Scene *scene, Object *ob, Key *key, char *out, const in
static void do_latt_key(Scene *scene, Object *ob, Key *key, char *out, const int tot)
{
Lattice *lt = ob->data;
- KeyBlock *k[4], *actkb = ob_get_keyblock(ob);
+ KeyBlock *k[4], *actkb = BKE_keyblock_from_object(ob);
float t[4];
int flag;
@@ -1268,7 +1268,7 @@ static void do_latt_key(Scene *scene, Object *ob, Key *key, char *out, const int
do_key(a, a + 1, tot, out, key, actkb, k, t, KEY_MODE_DUMMY);
else
cp_key(a, a + 1, tot, out, key, actkb, k[2], NULL, KEY_MODE_DUMMY);
- }
+ }
}
else {
if (key->type == KEY_RELATIVE) {
@@ -1277,7 +1277,7 @@ static void do_latt_key(Scene *scene, Object *ob, Key *key, char *out, const int
for (kb = key->block.first; kb; kb = kb->next)
kb->weights = get_weights_array(ob, kb->vgroup);
- do_rel_key(0, tot, tot, out, key, actkb, KEY_MODE_DUMMY);
+ BKE_key_evaluate_relative(0, tot, tot, out, key, actkb, KEY_MODE_DUMMY);
for (kb = key->block.first; kb; kb = kb->next) {
if (kb->weights) MEM_freeN(kb->weights);
@@ -1302,8 +1302,8 @@ static void do_latt_key(Scene *scene, Object *ob, Key *key, char *out, const int
/* returns key coordinates (+ tilt) when key applied, NULL otherwise */
float *do_ob_key(Scene *scene, Object *ob)
{
- Key *key = ob_get_key(ob);
- KeyBlock *actkb = ob_get_keyblock(ob);
+ Key *key = BKE_key_from_object(ob);
+ KeyBlock *actkb = BKE_keyblock_from_object(ob);
char *out;
int tot = 0, size = 0;
@@ -1386,7 +1386,7 @@ float *do_ob_key(Scene *scene, Object *ob)
return (float *)out;
}
-Key *ob_get_key(Object *ob)
+Key *BKE_key_from_object(Object *ob)
{
if (ob == NULL) return NULL;
@@ -1405,7 +1405,7 @@ Key *ob_get_key(Object *ob)
return NULL;
}
-KeyBlock *add_keyblock(Key *key, const char *name)
+KeyBlock *BKE_keyblock_add(Key *key, const char *name)
{
KeyBlock *kb;
float curpos = -0.1;
@@ -1439,7 +1439,7 @@ KeyBlock *add_keyblock(Key *key, const char *name)
/**
* \note caller may want to set this to current time, but don't do it here since we need to sort
- * which could cause problems in some cases, see #add_keyblock_ctime */
+ * which could cause problems in some cases, see #BKE_keyblock_add_ctime */
kb->pos = curpos + 0.1f; /* only used for absolute shape keys */
return kb;
@@ -1453,22 +1453,22 @@ KeyBlock *add_keyblock(Key *key, const char *name)
* \param name Optional name for the new keyblock.
* \param do_force always use ctime even for relative keys.
*/
-KeyBlock *add_keyblock_ctime(Key *key, const char *name, const short do_force)
+KeyBlock *BKE_keyblock_add_ctime(Key *key, const char *name, const short do_force)
{
- KeyBlock *kb = add_keyblock(key, name);
+ KeyBlock *kb = BKE_keyblock_add(key, name);
if (do_force || (key->type != KEY_RELATIVE)) {
kb->pos = key->ctime / 100.0f;
- sort_keys(key);
+ BKE_key_sort(key);
}
return kb;
}
/* only the active keyblock */
-KeyBlock *ob_get_keyblock(Object *ob)
+KeyBlock *BKE_keyblock_from_object(Object *ob)
{
- Key *key = ob_get_key(ob);
+ Key *key = BKE_key_from_object(ob);
if (key) {
KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1);
@@ -1478,9 +1478,9 @@ KeyBlock *ob_get_keyblock(Object *ob)
return NULL;
}
-KeyBlock *ob_get_reference_keyblock(Object *ob)
+KeyBlock *BKE_keyblock_from_object_reference(Object *ob)
{
- Key *key = ob_get_key(ob);
+ Key *key = BKE_key_from_object(ob);
if (key)
return key->refkey;
@@ -1489,7 +1489,7 @@ KeyBlock *ob_get_reference_keyblock(Object *ob)
}
/* get the appropriate KeyBlock given an index */
-KeyBlock *key_get_keyblock(Key *key, int index)
+KeyBlock *BKE_keyblock_from_key(Key *key, int index)
{
KeyBlock *kb;
int i;
@@ -1509,18 +1509,29 @@ KeyBlock *key_get_keyblock(Key *key, int index)
}
/* get the appropriate KeyBlock given a name to search for */
-KeyBlock *key_get_named_keyblock(Key *key, const char name[])
+KeyBlock *BKE_keyblock_find_name(Key *key, const char name[])
{
- if (key && name)
- return BLI_findstring(&key->block, name, offsetof(KeyBlock, name));
-
- return NULL;
+ return BLI_findstring(&key->block, name, offsetof(KeyBlock, name));
+}
+
+/**
+ * \brief copy shape-key attributes, but not key data.or name/uid
+ */
+void BKE_keyblock_copy_settings(KeyBlock *kb_dst, const KeyBlock *kb_src)
+{
+ kb_dst->pos = kb_src->pos;
+ kb_dst->curval = kb_src->curval;
+ kb_dst->type = kb_src->type;
+ kb_dst->relative = kb_src->relative;
+ BLI_strncpy(kb_dst->vgroup, kb_src->vgroup, sizeof(kb_dst->vgroup));
+ kb_dst->slidermin = kb_src->slidermin;
+ kb_dst->slidermax = kb_src->slidermax;
}
/* Get RNA-Path for 'value' setting of the given ShapeKey
* NOTE: the user needs to free the returned string once they're finish with it
*/
-char *key_get_curValue_rnaPath(Key *key, KeyBlock *kb)
+char *BKE_keyblock_curval_rnapath_get(Key *key, KeyBlock *kb)
{
PointerRNA ptr;
PropertyRNA *prop;
@@ -1542,7 +1553,7 @@ char *key_get_curValue_rnaPath(Key *key, KeyBlock *kb)
/* conversion functions */
/************************* Lattice ************************/
-void latt_to_key(Lattice *lt, KeyBlock *kb)
+void BKE_key_convert_from_lattice(Lattice *lt, KeyBlock *kb)
{
BPoint *bp;
float *fp;
@@ -1563,7 +1574,7 @@ void latt_to_key(Lattice *lt, KeyBlock *kb)
}
}
-void key_to_latt(KeyBlock *kb, Lattice *lt)
+void BKE_key_convert_to_lattice(KeyBlock *kb, Lattice *lt)
{
BPoint *bp;
float *fp;
@@ -1573,7 +1584,7 @@ void key_to_latt(KeyBlock *kb, Lattice *lt)
fp = kb->data;
tot = lt->pntsu * lt->pntsv * lt->pntsw;
- tot = mini(kb->totelem, tot);
+ tot = min_ii(kb->totelem, tot);
for (a = 0; a < tot; a++, fp += 3, bp++) {
copy_v3_v3(bp->vec, fp);
@@ -1581,7 +1592,7 @@ void key_to_latt(KeyBlock *kb, Lattice *lt)
}
/************************* Curve ************************/
-void curve_to_key(Curve *cu, KeyBlock *kb, ListBase *nurb)
+void BKE_key_convert_from_curve(Curve *cu, KeyBlock *kb, ListBase *nurb)
{
Nurb *nu;
BezTriple *bezt;
@@ -1632,7 +1643,7 @@ void curve_to_key(Curve *cu, KeyBlock *kb, ListBase *nurb)
}
}
-void key_to_curve(KeyBlock *kb, Curve *UNUSED(cu), ListBase *nurb)
+void BKE_key_convert_to_curve(KeyBlock *kb, Curve *UNUSED(cu), ListBase *nurb)
{
Nurb *nu;
BezTriple *bezt;
@@ -1645,7 +1656,7 @@ void key_to_curve(KeyBlock *kb, Curve *UNUSED(cu), ListBase *nurb)
tot = BKE_nurbList_verts_count(nurb);
- tot = mini(kb->totelem, tot);
+ tot = min_ii(kb->totelem, tot);
while (nu && tot > 0) {
@@ -1683,7 +1694,7 @@ void key_to_curve(KeyBlock *kb, Curve *UNUSED(cu), ListBase *nurb)
}
/************************* Mesh ************************/
-void mesh_to_key(Mesh *me, KeyBlock *kb)
+void BKE_key_convert_from_mesh(Mesh *me, KeyBlock *kb)
{
MVert *mvert;
float *fp;
@@ -1704,7 +1715,7 @@ void mesh_to_key(Mesh *me, KeyBlock *kb)
}
}
-void key_to_mesh(KeyBlock *kb, Mesh *me)
+void BKE_key_convert_to_mesh(KeyBlock *kb, Mesh *me)
{
MVert *mvert;
float *fp;
@@ -1713,7 +1724,7 @@ void key_to_mesh(KeyBlock *kb, Mesh *me)
mvert = me->mvert;
fp = kb->data;
- tot = mini(kb->totelem, me->totvert);
+ tot = min_ii(kb->totelem, me->totvert);
for (a = 0; a < tot; a++, fp += 3, mvert++) {
copy_v3_v3(mvert->co, fp);
@@ -1721,7 +1732,7 @@ void key_to_mesh(KeyBlock *kb, Mesh *me)
}
/************************* vert coords ************************/
-float (*key_to_vertcos(Object * ob, KeyBlock * kb))[3]
+float (*BKE_key_convert_to_vertcos(Object * ob, KeyBlock * kb))[3]
{
float (*vertCos)[3], *co;
float *fp = kb->data;
@@ -1743,7 +1754,7 @@ float (*key_to_vertcos(Object * ob, KeyBlock * kb))[3]
if (tot == 0) return NULL;
- vertCos = MEM_callocN(tot * sizeof(*vertCos), "key_to_vertcos vertCos");
+ vertCos = MEM_callocN(tot * sizeof(*vertCos), "BKE_key_convert_to_vertcos vertCos");
/* Copy coords to array */
co = (float *)vertCos;
@@ -1797,7 +1808,7 @@ float (*key_to_vertcos(Object * ob, KeyBlock * kb))[3]
return vertCos;
}
-void vertcos_to_key(Object *ob, KeyBlock *kb, float (*vertCos)[3])
+void BKE_key_convert_from_vertcos(Object *ob, KeyBlock *kb, float (*vertCos)[3])
{
float *co = (float *)vertCos, *fp;
int tot = 0, a, elemsize;
@@ -1826,7 +1837,7 @@ void vertcos_to_key(Object *ob, KeyBlock *kb, float (*vertCos)[3])
return;
}
- fp = kb->data = MEM_callocN(tot * elemsize, "key_to_vertcos vertCos");
+ fp = kb->data = MEM_callocN(tot * elemsize, "BKE_key_convert_to_vertcos vertCos");
/* Copy coords to keyblock */
@@ -1877,7 +1888,7 @@ void vertcos_to_key(Object *ob, KeyBlock *kb, float (*vertCos)[3])
}
}
-void offset_to_key(Object *ob, KeyBlock *kb, float (*ofs)[3])
+void BKE_key_convert_from_offset(Object *ob, KeyBlock *kb, float (*ofs)[3])
{
int a;
float *co = (float *)ofs, *fp = kb->data;
diff --git a/source/blender/blenkernel/intern/lattice.c b/source/blender/blenkernel/intern/lattice.c
index 17e4103c7d3..a15ca7cb5ce 100644
--- a/source/blender/blenkernel/intern/lattice.c
+++ b/source/blender/blenkernel/intern/lattice.c
@@ -64,19 +64,19 @@
#include "BKE_deform.h"
-void calc_lat_fudu(int flag, int res, float *fu, float *du)
+void calc_lat_fudu(int flag, int res, float *r_fu, float *r_du)
{
if (res == 1) {
- *fu = 0.0;
- *du = 0.0;
+ *r_fu = 0.0;
+ *r_du = 0.0;
}
else if (flag & LT_GRID) {
- *fu = -0.5f * (res - 1);
- *du = 1.0f;
+ *r_fu = -0.5f * (res - 1);
+ *r_du = 1.0f;
}
else {
- *fu = -1.0f;
- *du = 2.0f / (res - 1);
+ *r_fu = -1.0f;
+ *r_du = 2.0f / (res - 1);
}
}
@@ -348,7 +348,7 @@ void calc_latt_deform(Object *ob, float co[3], float weight)
int ui, vi, wi, uu, vv, ww;
/* vgroup influence */
- int defgroup_nr = -1;
+ int defgrp_index = -1;
float co_prev[3], weight_blend = 0.0f;
MDeformVert *dvert = BKE_lattice_deform_verts_get(ob);
@@ -357,7 +357,7 @@ void calc_latt_deform(Object *ob, float co[3], float weight)
if (lt->latticedata == NULL) return;
if (lt->vgroup[0] && dvert) {
- defgroup_nr = defgroup_name_index(ob, lt->vgroup);
+ defgrp_index = defgroup_name_index(ob, lt->vgroup);
copy_v3_v3(co_prev, co);
}
@@ -431,8 +431,8 @@ void calc_latt_deform(Object *ob, float co[3], float weight)
madd_v3_v3fl(co, &lt->latticedata[idx_u * 3], u);
- if (defgroup_nr != -1)
- weight_blend += (u * defvert_find_weight(dvert + idx_u, defgroup_nr));
+ if (defgrp_index != -1)
+ weight_blend += (u * defvert_find_weight(dvert + idx_u, defgrp_index));
}
}
}
@@ -440,7 +440,7 @@ void calc_latt_deform(Object *ob, float co[3], float weight)
}
}
- if (defgroup_nr != -1)
+ if (defgrp_index != -1)
interp_v3_v3v3(co, co_prev, co, weight_blend);
}
@@ -669,9 +669,9 @@ void curve_deform_verts(Scene *scene, Object *cuOb, Object *target,
if (vgroup && vgroup[0] && use_vgroups) {
Mesh *me = target->data;
- int index = defgroup_name_index(target, vgroup);
+ const int defgrp_index = defgroup_name_index(target, vgroup);
- if (index != -1 && (me->dvert || dm)) {
+ if (defgrp_index != -1 && (me->dvert || dm)) {
MDeformVert *dvert = me->dvert;
float vec[3];
float weight;
@@ -681,7 +681,7 @@ void curve_deform_verts(Scene *scene, Object *cuOb, Object *target,
dvert = me->dvert;
for (a = 0; a < numVerts; a++, dvert++) {
if (dm) dvert = dm->getVertData(dm, a, CD_MDEFORMVERT);
- weight = defvert_find_weight(dvert, index);
+ weight = defvert_find_weight(dvert, defgrp_index);
if (weight > 0.0f) {
mul_m4_v3(cd.curvespace, vertexCos[a]);
@@ -699,7 +699,7 @@ void curve_deform_verts(Scene *scene, Object *cuOb, Object *target,
for (a = 0; a < numVerts; a++, dvert++) {
if (dm) dvert = dm->getVertData(dm, a, CD_MDEFORMVERT);
- if (defvert_find_weight(dvert, index) > 0.0f) {
+ if (defvert_find_weight(dvert, defgrp_index) > 0.0f) {
mul_m4_v3(cd.curvespace, vertexCos[a]);
minmax_v3v3_v3(cd.dmin, cd.dmax, vertexCos[a]);
}
@@ -709,7 +709,7 @@ void curve_deform_verts(Scene *scene, Object *cuOb, Object *target,
for (a = 0; a < numVerts; a++, dvert++) {
if (dm) dvert = dm->getVertData(dm, a, CD_MDEFORMVERT);
- weight = defvert_find_weight(dvert, index);
+ weight = defvert_find_weight(dvert, defgrp_index);
if (weight > 0.0f) {
/* already in 'cd.curvespace', prev for loop */
@@ -815,16 +815,16 @@ void lattice_deform_verts(Object *laOb, Object *target, DerivedMesh *dm,
if (vgroup && vgroup[0] && use_vgroups) {
Mesh *me = target->data;
- int index = defgroup_name_index(target, vgroup);
+ const int defgrp_index = defgroup_name_index(target, vgroup);
float weight;
- if (index >= 0 && (me->dvert || dm)) {
+ if (defgrp_index >= 0 && (me->dvert || dm)) {
MDeformVert *dvert = me->dvert;
for (a = 0; a < numVerts; a++, dvert++) {
if (dm) dvert = dm->getVertData(dm, a, CD_MDEFORMVERT);
- weight = defvert_find_weight(dvert, index);
+ weight = defvert_find_weight(dvert, defgrp_index);
if (weight > 0.0f)
calc_latt_deform(laOb, vertexCos[a], weight * fac);
@@ -879,9 +879,10 @@ void outside_lattice(Lattice *lt)
for (v = 0; v < lt->pntsv; v++) {
for (u = 0; u < lt->pntsu; u++, bp++) {
- if (u == 0 || v == 0 || w == 0 || u == lt->pntsu - 1 || v == lt->pntsv - 1 || w == lt->pntsw - 1) ;
+ if (u == 0 || v == 0 || w == 0 || u == lt->pntsu - 1 || v == lt->pntsv - 1 || w == lt->pntsw - 1) {
+ /* pass */
+ }
else {
-
bp->hide = 1;
bp->f1 &= ~SELECT;
diff --git a/source/blender/blenkernel/intern/library.c b/source/blender/blenkernel/intern/library.c
index 45364f5aafa..942e71b5052 100644
--- a/source/blender/blenkernel/intern/library.c
+++ b/source/blender/blenkernel/intern/library.c
@@ -796,6 +796,18 @@ static void animdata_dtar_clear_cb(ID *UNUSED(id), AnimData *adt, void *userdata
}
}
+void BKE_libblock_free_data(ID *id)
+{
+ Main *bmain = G.main; /* should eventually be an arg */
+
+ if (id->properties) {
+ IDP_FreeProperty(id->properties);
+ MEM_freeN(id->properties);
+ }
+
+ /* this ID may be a driver target! */
+ BKE_animdata_main_cb(bmain, animdata_dtar_clear_cb, (void *)id);
+}
/* used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c */
void BKE_libblock_free(ListBase *lb, void *idv)
@@ -904,15 +916,9 @@ void BKE_libblock_free(ListBase *lb, void *idv)
break;
}
- if (id->properties) {
- IDP_FreeProperty(id->properties);
- MEM_freeN(id->properties);
- }
-
BLI_remlink(lb, id);
- /* this ID may be a driver target! */
- BKE_animdata_main_cb(bmain, animdata_dtar_clear_cb, (void *)id);
+ BKE_libblock_free_data(id);
MEM_freeN(id);
}
@@ -1200,7 +1206,7 @@ static int check_for_dupid(ListBase *lb, ID *id, char *name)
char left[MAX_ID_NAME + 8], leftest[MAX_ID_NAME + 8];
/* make sure input name is terminated properly */
- /* if ( strlen(name) > MAX_ID_NAME-3 ) name[MAX_ID_NAME-3]= 0; */
+ /* if ( strlen(name) > MAX_ID_NAME-3 ) name[MAX_ID_NAME-3] = 0; */
/* removed since this is only ever called from one place - campbell */
while (1) {
@@ -1547,7 +1553,7 @@ void rename_id(ID *id, const char *name)
BLI_strncpy(id->name + 2, name, sizeof(id->name) - 2);
lb = which_libbase(G.main, GS(id->name) );
- new_id(lb, id, name);
+ new_id(lb, id, name);
}
void name_uiprefix_id(char *name, ID *id)
diff --git a/source/blender/blenkernel/intern/mask.c b/source/blender/blenkernel/intern/mask.c
index 3564071334c..b7f4c4bd61e 100644
--- a/source/blender/blenkernel/intern/mask.c
+++ b/source/blender/blenkernel/intern/mask.c
@@ -378,8 +378,8 @@ float BKE_mask_spline_project_co(MaskSpline *spline, MaskSplinePoint *point,
if (len_squared_v2(v1) > proj_eps_squared) {
ang1 = angle_v2v2(v1, n1);
- if (ang1 > M_PI / 2.0f)
- ang1 = M_PI - ang1;
+ if (ang1 > (float)M_PI / 2.0f)
+ ang1 = (float)M_PI - ang1;
if (ang < 0.0f || ang1 < ang) {
ang = ang1;
@@ -405,8 +405,8 @@ float BKE_mask_spline_project_co(MaskSpline *spline, MaskSplinePoint *point,
if (len_squared_v2(v2) > proj_eps_squared) {
ang2 = angle_v2v2(v2, n2);
- if (ang2 > M_PI / 2.0f)
- ang2 = M_PI - ang2;
+ if (ang2 > (float)M_PI / 2.0f)
+ ang2 = (float)M_PI - ang2;
if (ang2 < ang) {
ang = ang2;
@@ -555,7 +555,7 @@ float BKE_mask_point_weight_scalar(MaskSpline *spline, MaskSplinePoint *point, c
if (!bezt_next) {
return bezt->weight;
}
- else if (u <= 0.0) {
+ else if (u <= 0.0f) {
return bezt->weight;
}
else if (u >= 1.0f) {
@@ -576,7 +576,7 @@ float BKE_mask_point_weight(MaskSpline *spline, MaskSplinePoint *point, const fl
if (!bezt_next) {
return bezt->weight;
}
- else if (u <= 0.0) {
+ else if (u <= 0.0f) {
return bezt->weight;
}
else if (u >= 1.0f) {
@@ -916,19 +916,6 @@ void BKE_mask_free_nolib(Mask *mask)
BKE_mask_layer_free_list(&mask->masklayers);
}
-
-static void ntree_unlink_mask_cb(void *calldata, struct ID *UNUSED(owner_id), struct bNodeTree *ntree)
-{
- ID *id = (ID *)calldata;
- bNode *node;
-
- for (node = ntree->nodes.first; node; node = node->next) {
- if (node->id == id) {
- node->id = NULL;
- }
- }
-}
-
void BKE_mask_free(Main *bmain, Mask *mask)
{
bScreen *scr;
@@ -975,21 +962,11 @@ void BKE_mask_free(Main *bmain, Mask *mask)
}
SEQ_END
}
-
-
- if (scene->nodetree) {
- bNode *node;
- for (node = scene->nodetree->nodes.first; node; node = node->next) {
- if (node->id == &mask->id) {
- node->id = NULL;
- }
- }
- }
}
{
bNodeTreeType *treetype = ntreeGetType(NTREE_COMPOSIT);
- treetype->foreach_nodetree(bmain, (void *)mask, &ntree_unlink_mask_cb);
+ treetype->foreach_nodetree(bmain, (void *)mask, &BKE_node_tree_unlink_id_cb);
}
/* free mask data */
@@ -1548,7 +1525,7 @@ void BKE_mask_parent_init(MaskParent *parent)
}
-/* *** own animation/shapekey implimentation ***
+/* *** own animation/shapekey implementation ***
* BKE_mask_layer_shape_XXX */
int BKE_mask_layer_shape_totvert(MaskLayer *masklay)
@@ -1828,7 +1805,7 @@ static void interp_weights_uv_v2_calc(float r_uv[2], const float pt[2], const fl
float pt_on_line[2];
r_uv[0] = closest_to_line_v2(pt_on_line, pt, pt_a, pt_b);
r_uv[1] = (len_v2v2(pt_on_line, pt) / len_v2v2(pt_a, pt_b)) *
- ((line_point_side_v2(pt_a, pt_b, pt) < 0.0f) ? -1.0 : 1.0); /* this line only sets the sign */
+ ((line_point_side_v2(pt_a, pt_b, pt) < 0.0f) ? -1.0f : 1.0f); /* this line only sets the sign */
}
@@ -1978,5 +1955,5 @@ void BKE_mask_layer_shape_changed_remove(MaskLayer *masklay, int index, int coun
int BKE_mask_get_duration(Mask *mask)
{
- return maxi(1, mask->efra - mask->sfra);
+ return max_ii(1, mask->efra - mask->sfra);
}
diff --git a/source/blender/blenkernel/intern/mask_evaluate.c b/source/blender/blenkernel/intern/mask_evaluate.c
index 4a8601df0b8..e67df9c6419 100644
--- a/source/blender/blenkernel/intern/mask_evaluate.c
+++ b/source/blender/blenkernel/intern/mask_evaluate.c
@@ -69,7 +69,7 @@ unsigned int BKE_mask_spline_resolution(MaskSpline *spline, int width, int heigh
unsigned int i, resol = 1;
if (width != 0 && height != 0) {
- max_segment = 1.0f / (float)maxi(width, height);
+ max_segment = 1.0f / (float)max_ii(width, height);
}
for (i = 0; i < spline->tot_point; i++) {
@@ -131,7 +131,7 @@ unsigned int BKE_mask_spline_feather_resolution(MaskSpline *spline, int width, i
if (u_diff > FLT_EPSILON) {
float jump = fabsf(w_diff / u_diff);
- max_jump = MAX2(max_jump, jump);
+ max_jump = max_ff(max_jump, jump);
}
prev_u = point->uw[j].u;
@@ -418,7 +418,7 @@ void BKE_mask_spline_feather_collapse_inner_loops(MaskSpline *spline, float (*fe
max_delta = MAX2(max_delta_x, max_delta_y);
- buckets_per_side = MIN2(512, 0.9f / max_delta);
+ buckets_per_side = min_ii(512, 0.9f / max_delta);
if (buckets_per_side == 0) {
/* happens when some segment fills the whole bounding box across some of dimension */
diff --git a/source/blender/blenkernel/intern/mask_rasterize.c b/source/blender/blenkernel/intern/mask_rasterize.c
index 00898b0fe10..88393fab79c 100644
--- a/source/blender/blenkernel/intern/mask_rasterize.c
+++ b/source/blender/blenkernel/intern/mask_rasterize.c
@@ -104,7 +104,7 @@
/* for debugging add... */
#ifndef NDEBUG
-/* printf("%u %u %u %u\n", _t[0], _t[1], _t[2], _t[3]); \ */
+/* printf("%u %u %u %u\n", _t[0], _t[1], _t[2], _t[3]); \ */
# define FACE_ASSERT(face, vert_max) \
{ \
unsigned int *_t = face; \
@@ -410,8 +410,8 @@ static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size)
{
MemArena *arena = BLI_memarena_new(1 << 16, __func__);
- const float bucket_dim_x = BLI_RCT_SIZE_X(&layer->bounds);
- const float bucket_dim_y = BLI_RCT_SIZE_Y(&layer->bounds);
+ const float bucket_dim_x = BLI_rctf_size_x(&layer->bounds);
+ const float bucket_dim_y = BLI_rctf_size_y(&layer->bounds);
layer->buckets_x = (bucket_dim_x / pixel_size) / (float)BUCKET_PIXELS_PER_CELL;
layer->buckets_y = (bucket_dim_y / pixel_size) / (float)BUCKET_PIXELS_PER_CELL;
@@ -428,7 +428,7 @@ static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size)
/* width and height of each bucket */
const float bucket_size_x = (bucket_dim_x + FLT_EPSILON) / layer->buckets_x;
const float bucket_size_y = (bucket_dim_y + FLT_EPSILON) / layer->buckets_y;
- const float bucket_max_rad = (maxf(bucket_size_x, bucket_size_y) * M_SQRT2) + FLT_EPSILON;
+ const float bucket_max_rad = (max_ff(bucket_size_x, bucket_size_y) * (float)M_SQRT2) + FLT_EPSILON;
const float bucket_max_rad_squared = bucket_max_rad * bucket_max_rad;
unsigned int *face = &layer->face_array[0][0];
@@ -451,10 +451,10 @@ static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size)
const float *v2 = cos[face[1]];
const float *v3 = cos[face[2]];
- xmin = minf(v1[0], minf(v2[0], v3[0]));
- xmax = maxf(v1[0], maxf(v2[0], v3[0]));
- ymin = minf(v1[1], minf(v2[1], v3[1]));
- ymax = maxf(v1[1], maxf(v2[1], v3[1]));
+ xmin = min_ff(v1[0], min_ff(v2[0], v3[0]));
+ xmax = max_ff(v1[0], max_ff(v2[0], v3[0]));
+ ymin = min_ff(v1[1], min_ff(v2[1], v3[1]));
+ ymax = max_ff(v1[1], max_ff(v2[1], v3[1]));
}
else {
const float *v1 = cos[face[0]];
@@ -462,10 +462,10 @@ static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size)
const float *v3 = cos[face[2]];
const float *v4 = cos[face[3]];
- xmin = minf(v1[0], minf(v2[0], minf(v3[0], v4[0])));
- xmax = maxf(v1[0], maxf(v2[0], maxf(v3[0], v4[0])));
- ymin = minf(v1[1], minf(v2[1], minf(v3[1], v4[1])));
- ymax = maxf(v1[1], maxf(v2[1], maxf(v3[1], v4[1])));
+ xmin = min_ff(v1[0], min_ff(v2[0], min_ff(v3[0], v4[0])));
+ xmax = max_ff(v1[0], max_ff(v2[0], max_ff(v3[0], v4[0])));
+ ymin = min_ff(v1[1], min_ff(v2[1], min_ff(v3[1], v4[1])));
+ ymax = max_ff(v1[1], max_ff(v2[1], max_ff(v3[1], v4[1])));
}
@@ -503,7 +503,7 @@ static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size)
BLI_assert(bucket_index < bucket_tot);
/* check if the bucket intersects with the face */
- /* note: there is a tradeoff here since checking box/tri intersections isn't
+ /* note: there is a trade off here since checking box/tri intersections isn't
* as optimal as it could be, but checking pixels against faces they will never intersect
* with is likely the greater slowdown here - so check if the cell intersects the face */
if (layer_bucket_isect_test(layer, face_index,
@@ -560,7 +560,7 @@ void BKE_maskrasterize_handle_init(MaskRasterHandle *mr_handle, struct Mask *mas
const short do_feather)
{
const rctf default_bounds = {0.0f, 1.0f, 0.0f, 1.0f};
- const float pixel_size = 1.0f / MIN2(width, height);
+ const float pixel_size = 1.0f / (float)min_ii(width, height);
const float asp_xy[2] = {(do_aspect_correct && width > height) ? (float)height / (float)width : 1.0f,
(do_aspect_correct && width < height) ? (float)width / (float)height : 1.0f};
@@ -1208,7 +1208,7 @@ static float maskrasterize_layer_isect(unsigned int *face, float (*cos)[3], cons
/* needs work */
#if 1
- /* quad check fails for bowtie, so keep using 2 tri checks */
+ /* quad check fails for bow-tie, so keep using 2 tri checks */
//if (isect_point_quad_v2(xy, cos[face[0]], cos[face[1]], cos[face[2]], cos[face[3]]))
if (isect_point_tri_v2(xy, cos[face[0]], cos[face[1]], cos[face[2]]) ||
isect_point_tri_v2(xy, cos[face[0]], cos[face[2]], cos[face[3]]))
@@ -1216,7 +1216,7 @@ static float maskrasterize_layer_isect(unsigned int *face, float (*cos)[3], cons
return maskrasterize_layer_z_depth_quad(xy, cos[face[0]], cos[face[1]], cos[face[2]], cos[face[3]]);
}
#elif 1
- /* don't use isect_point_tri_v2_cw because we could have bowtie quads */
+ /* don't use isect_point_tri_v2_cw because we could have bow-tie quads */
if (isect_point_tri_v2(xy, cos[face[0]], cos[face[1]], cos[face[2]])) {
return maskrasterize_layer_z_depth_tri(xy, cos[face[0]], cos[face[1]], cos[face[2]]);
@@ -1335,10 +1335,10 @@ float BKE_maskrasterize_handle_sample(MaskRasterHandle *mr_handle, const float x
value -= value_layer;
break;
case MASK_BLEND_LIGHTEN:
- value = maxf(value, value_layer);
+ value = max_ff(value, value_layer);
break;
case MASK_BLEND_DARKEN:
- value = minf(value, value_layer);
+ value = min_ff(value, value_layer);
break;
case MASK_BLEND_MUL:
value *= value_layer;
diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c
index 7523c59a879..ea317956255 100644
--- a/source/blender/blenkernel/intern/material.c
+++ b/source/blender/blenkernel/intern/material.c
@@ -38,6 +38,7 @@
#include "DNA_anim_types.h"
#include "DNA_curve_types.h"
+#include "DNA_group_types.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
@@ -214,7 +215,7 @@ Material *BKE_material_add(const char *name)
init_material(ma);
- return ma;
+ return ma;
}
/* XXX keep synced with next function */
@@ -903,7 +904,7 @@ short find_material_index(Object *ob, Material *ma)
break;
if (a < *totcolp)
return a + 1;
- return 0;
+ return 0;
}
int object_add_material_slot(Object *ob)
@@ -941,7 +942,7 @@ static void do_init_render_material(Material *ma, int r_mode, float *amb)
if (ma->texco & (TEXCO_ORCO | TEXCO_REFL | TEXCO_NORM | TEXCO_STRAND | TEXCO_STRESS)) needuv = 1;
else if (ma->texco & (TEXCO_GLOB | TEXCO_UV | TEXCO_OBJECT | TEXCO_SPEED)) needuv = 1;
- else if (ma->texco & (TEXCO_LAVECTOR | TEXCO_VIEW | TEXCO_STICKY)) needuv = 1;
+ else if (ma->texco & (TEXCO_LAVECTOR | TEXCO_VIEW)) needuv = 1;
if ((ma->mapto & MAP_NORM) && (mtex->normapspace == MTEX_NSPACE_TANGENT))
needtang = 1;
@@ -969,7 +970,7 @@ static void do_init_render_material(Material *ma, int r_mode, float *amb)
ma->ambr = ma->amb * amb[0];
ma->ambg = ma->amb * amb[1];
ma->ambb = ma->amb * amb[2];
- }
+ }
/* will become or-ed result of all node modes */
ma->mode_l = ma->mode;
ma->mode_l &= ~MA_SHLESS;
@@ -980,6 +981,17 @@ static void do_init_render_material(Material *ma, int r_mode, float *amb)
/* parses the geom+tex nodes */
if (ma->nodetree && ma->use_nodes)
ntreeShaderGetTexcoMode(ma->nodetree, r_mode, &ma->texco, &ma->mode_l);
+
+ /* local group override */
+ if ((ma->shade_flag & MA_GROUP_LOCAL) && ma->id.lib && ma->group && ma->group->id.lib) {
+ Group *group;
+
+ for (group = G.main->group.first; group; group = group->id.next) {
+ if (!group->id.lib && strcmp(group->id.name, ma->group->id.name) == 0) {
+ ma->group = group;
+ }
+ }
+ }
}
static void init_render_nodetree(bNodeTree *ntree, Material *basemat, int r_mode, float *amb)
@@ -1147,7 +1159,7 @@ void material_drivers_update(Scene *scene, Material *ma, float ctime)
/* ****************** */
#if 0 /* UNUSED */
-static char colname_array[125][20]= {
+static char colname_array[125][20] = {
"Black", "DarkRed", "HalfRed", "Red", "Red",
"DarkGreen", "DarkOlive", "Brown", "Chocolate", "OrangeRed",
"HalfGreen", "GreenOlive", "DryOlive", "Goldenrod", "DarkOrange",
@@ -1327,9 +1339,9 @@ void ramp_blend(int type, float r_col[3], const float fac, const float col[3])
r_col[2] = facm * (r_col[2]) + fac * (r_col[2]) / col[2];
break;
case MA_RAMP_DIFF:
- r_col[0] = facm * (r_col[0]) + fac *fabsf(r_col[0] - col[0]);
- r_col[1] = facm * (r_col[1]) + fac *fabsf(r_col[1] - col[1]);
- r_col[2] = facm * (r_col[2]) + fac *fabsf(r_col[2] - col[2]);
+ r_col[0] = facm * (r_col[0]) + fac * fabsf(r_col[0] - col[0]);
+ r_col[1] = facm * (r_col[1]) + fac * fabsf(r_col[1] - col[1]);
+ r_col[2] = facm * (r_col[2]) + fac * fabsf(r_col[2] - col[2]);
break;
case MA_RAMP_DARK:
tmp = col[0] + ((1 - col[0]) * facm);
@@ -1490,7 +1502,7 @@ void ramp_blend(int type, float r_col[3], const float fac, const float col[3])
}
/**
- * \brief copy/paste buffer, if we had a propper py api that would be better
+ * \brief copy/paste buffer, if we had a proper py api that would be better
* \note matcopybuf.nodetree does _NOT_ use ID's
* \todo matcopybuf.nodetree's node->id's are NOT validated, this will crash!
*/
@@ -1603,7 +1615,7 @@ static int encode_tfaceflag(MTFace *tf, int convertall)
/* calculate the flag */
int flag = tf->mode;
- /* options that change the material offline render */
+ /* options that change the material offline render */
if (!convertall) {
flag &= ~TF_OBCOL;
}
@@ -1627,7 +1639,7 @@ static int encode_tfaceflag(MTFace *tf, int convertall)
/* set the material options based in the tface flag */
static void decode_tfaceflag(Material *ma, int flag, int convertall)
{
- int alphablend;
+ int alphablend;
GameSettings *game = &ma->game;
/* flag is shifted in 1 to make 0 != no flag yet (see encode_tfaceflag) */
@@ -1786,13 +1798,13 @@ static short convert_tfacenomaterial(Main *main, Mesh *me, MTFace *tf, int flag)
* for now store the flag into the material and change light/tex/collision
* store the flag as a negative number */
ma->game.flag = -flag;
- id_us_min((ID *)ma);
+ id_us_min((ID *)ma);
}
else printf("Error: Unable to create Material \"%s\" for Mesh \"%s\".", idname + 2, me->id.name + 2);
}
/* set as converted, no need to go bad to this face */
- tf->mode |= TF_CONVERTED;
+ tf->mode |= TF_CONVERTED;
return mat_nr;
}
@@ -1845,7 +1857,7 @@ static void convert_tfacematerial(Main *main, Material *ma)
if (mat_new) {
/* rename the material*/
strcpy(mat_new->id.name, idname);
- id_us_min((ID *)mat_new);
+ id_us_min((ID *)mat_new);
mat_nr = mesh_addmaterial(me, mat_new);
decode_tfaceflag(mat_new, flag, 1);
@@ -2033,7 +2045,7 @@ int do_version_tface(Main *main, int fileload)
nowarning = 0;
}
else
- convert_tfacematerial(main, ma); continue;
+ convert_tfacematerial(main, ma); continue;
}
/* no conflicts in this material - 90% of cases
diff --git a/source/blender/blenkernel/intern/mball.c b/source/blender/blenkernel/intern/mball.c
index 3925c3cc858..805e77cf84f 100644
--- a/source/blender/blenkernel/intern/mball.c
+++ b/source/blender/blenkernel/intern/mball.c
@@ -186,7 +186,7 @@ void BKE_mball_unlink(MetaBall *mb)
/* do not free mball itself */
void BKE_mball_free(MetaBall *mb)
{
- BKE_mball_unlink(mb);
+ BKE_mball_unlink(mb);
if (mb->adt) {
BKE_free_animdata((ID *)mb);
@@ -562,7 +562,7 @@ Object *BKE_mball_basis_find(Scene *scene, Object *basis)
basis = ob;
basisnr = obnr;
}
- }
+ }
}
}
@@ -691,7 +691,7 @@ static float densfunc(MetaElem *ball, float x, float y, float z)
/* *** end deprecated *** */
}
- dist2 = 1.0f - (len_v3(dvec) / ball->rad2);
+ dist2 = 1.0f - (len_squared_v3(dvec) / ball->rad2);
if ((ball->flag & MB_NEGATIVE) == 0) {
return (dist2 < 0.0f) ? -0.5f : (ball->s * dist2 * dist2 * dist2) - 0.5f;
@@ -732,7 +732,7 @@ static octal_node *find_metaball_octal_node(octal_node *node, float x, float y,
return find_metaball_octal_node(node->nodes[2], x, y, z, depth--);
else
return node;
- }
+ }
}
}
else {
@@ -762,7 +762,7 @@ static octal_node *find_metaball_octal_node(octal_node *node, float x, float y,
return find_metaball_octal_node(node->nodes[6], x, y, z, depth--);
else
return node;
- }
+ }
}
}
@@ -861,7 +861,7 @@ static void *new_pgn_element(int size)
}
BLI_freelistN(&lb);
- return NULL;
+ return NULL;
}
size = 4 * ( (size + 3) / 4);
@@ -1319,12 +1319,16 @@ static void addtovertices(VERTICES *vertices, VERTEX v)
static void vnormal(const float point[3], PROCESS *p, float r_no[3])
{
- float delta = 0.2f * p->delta;
- float f = p->function(point[0], point[1], point[2]);
+ const float delta = 0.2f * p->delta;
+ const float f = p->function(point[0], point[1], point[2]);
r_no[0] = p->function(point[0] + delta, point[1], point[2]) - f;
r_no[1] = p->function(point[0], point[1] + delta, point[2]) - f;
r_no[2] = p->function(point[0], point[1], point[2] + delta) - f;
+
+#if 1
+ normalize_v3(r_no);
+#else
f = normalize_v3(r_no);
if (0) {
@@ -1343,6 +1347,7 @@ static void vnormal(const float point[3], PROCESS *p, float r_no[3])
normalize_v3(r_no);
}
}
+#endif
}
@@ -1500,7 +1505,7 @@ static void find_first_points(PROCESS *mbproc, MetaBall *mb, int a)
float f = 0.0f;
ml = G_mb.mainb[a];
- f = 1.0 - (mb->thresh / ml->s);
+ f = 1.0f - (mb->thresh / ml->s);
/* Skip, when Stiffness of MetaElement is too small ... MetaElement can't be
* visible alone ... but still can influence others MetaElements :-) */
@@ -1628,7 +1633,7 @@ static void polygonize(PROCESS *mbproc, MetaBall *mb)
for (a = 0; a < G_mb.totelem; a++) {
/* try to find 8 points on the surface for each MetaElem */
- find_first_points(mbproc, mb, a);
+ find_first_points(mbproc, mb, a);
}
/* polygonize all MetaElems of current MetaBall */
@@ -2038,7 +2043,7 @@ static void subdivide_metaball_octal_node(octal_node *node, float size_x, float
}
- /* ml belongs to the (4)5th node too */
+ /* ml belongs to the (4)5th node too */
if (ml->bb->vec[6][2] >= z) {
fill_metaball_octal_node(node, ml, 4);
}
@@ -2226,7 +2231,7 @@ static void init_metaball_octal_tree(int depth)
}
}
- /* size of first node */
+ /* size of first node */
size[0] = node->x_max - node->x_min;
size[1] = node->y_max - node->y_min;
size[2] = node->z_max - node->z_min;
@@ -2388,7 +2393,7 @@ int BKE_mball_center_bounds(MetaBall *mb, float r_cent[3])
return 0;
}
-void BKE_mball_translate(MetaBall *mb, float offset[3])
+void BKE_mball_translate(MetaBall *mb, const float offset[3])
{
MetaElem *ml;
@@ -2396,3 +2401,32 @@ void BKE_mball_translate(MetaBall *mb, float offset[3])
add_v3_v3(&ml->x, offset);
}
}
+
+/* *** select funcs *** */
+void BKE_mball_select_all(struct MetaBall *mb)
+{
+ MetaElem *ml;
+
+ for (ml = mb->editelems->first; ml; ml = ml->next) {
+ ml->flag |= SELECT;
+ }
+}
+
+void BKE_mball_deselect_all(MetaBall *mb)
+{
+ MetaElem *ml;
+
+ for (ml = mb->editelems->first; ml; ml = ml->next) {
+ ml->flag &= ~SELECT;
+ }
+}
+
+void BKE_mball_select_swap(struct MetaBall *mb)
+{
+ MetaElem *ml;
+
+ for (ml = mb->editelems->first; ml; ml = ml->next) {
+ ml->flag ^= SELECT;
+ }
+}
+
diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c
index 8c3ec7e2e40..6d44473583f 100644
--- a/source/blender/blenkernel/intern/mesh.c
+++ b/source/blender/blenkernel/intern/mesh.c
@@ -367,7 +367,6 @@ void mesh_update_customdata_pointers(Mesh *me, const short do_ensure_tess_cd)
me->mvert = CustomData_get_layer(&me->vdata, CD_MVERT);
me->dvert = CustomData_get_layer(&me->vdata, CD_MDEFORMVERT);
- me->msticky = CustomData_get_layer(&me->vdata, CD_MSTICKY);
me->medge = CustomData_get_layer(&me->edata, CD_MEDGE);
@@ -470,15 +469,17 @@ void free_dverts(MDeformVert *dvert, int totvert)
static void mesh_tessface_clear_intern(Mesh *mesh, int free_customdata)
{
- if (free_customdata)
+ if (free_customdata) {
CustomData_free(&mesh->fdata, mesh->totface);
+ }
+ else {
+ CustomData_reset(&mesh->fdata);
+ }
mesh->mface = NULL;
mesh->mtface = NULL;
mesh->mcol = NULL;
mesh->totface = 0;
-
- memset(&mesh->fdata, 0, sizeof(mesh->fdata));
}
Mesh *BKE_mesh_add(const char *name)
@@ -492,7 +493,13 @@ Mesh *BKE_mesh_add(const char *name)
me->texflag = ME_AUTOSPACE;
me->flag = ME_TWOSIDED;
me->drawflag = ME_DRAWEDGES | ME_DRAWFACES | ME_DRAWCREASES;
-
+
+ CustomData_reset(&me->vdata);
+ CustomData_reset(&me->edata);
+ CustomData_reset(&me->fdata);
+ CustomData_reset(&me->pdata);
+ CustomData_reset(&me->ldata);
+
return me;
}
@@ -577,7 +584,7 @@ static void expand_local_mesh(Mesh *me)
for (i = 0; i < me->pdata.totlayer; i++) {
if (me->pdata.layers[i].type == CD_MTEXPOLY) {
- MTexPoly *txface = (MTexPoly *)me->fdata.layers[i].data;
+ MTexPoly *txface = (MTexPoly *)me->pdata.layers[i].data;
for (a = 0; a < me->totpoly; a++, txface++) {
/* special case: ima always local immediately */
@@ -736,7 +743,7 @@ float *BKE_mesh_orco_verts_get(Object *ob)
/* Get appropriate vertex coordinates */
vcos = MEM_callocN(sizeof(*vcos) * me->totvert, "orco mesh");
mvert = tme->mvert;
- totvert = MIN2(tme->totvert, me->totvert);
+ totvert = min_ii(tme->totvert, me->totvert);
for (a = 0; a < totvert; a++, mvert++) {
copy_v3_v3(vcos[a], mvert->co);
@@ -789,7 +796,7 @@ int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr)
nr--;
}
- /* check corrupt cases, bowtie geometry, cant handle these because edge data wont exist so just return 0 */
+ /* check corrupt cases, bow-tie geometry, cant handle these because edge data wont exist so just return 0 */
if (nr == 3) {
if (
/* real edges */
@@ -1865,7 +1872,7 @@ void BKE_mesh_calc_normals_mapping_ex(MVert *mverts, int numVerts,
/* only calc poly normals */
mp = mpolys;
for (i = 0; i < numPolys; i++, mp++) {
- mesh_calc_poly_normal(mp, mloop + mp->loopstart, mverts, pnors[i]);
+ BKE_mesh_calc_poly_normal(mp, mloop + mp->loopstart, mverts, pnors[i]);
}
}
@@ -1915,7 +1922,7 @@ void BKE_mesh_calc_normals(MVert *mverts, int numVerts, MLoop *mloop, MPoly *mpo
mp = mpolys;
for (i = 0; i < numPolys; i++, mp++) {
- mesh_calc_poly_normal(mp, mloop + mp->loopstart, mverts, pnors[i]);
+ BKE_mesh_calc_poly_normal(mp, mloop + mp->loopstart, mverts, pnors[i]);
ml = mloop + mp->loopstart;
BLI_array_empty(vertcos);
@@ -1944,8 +1951,9 @@ void BKE_mesh_calc_normals(MVert *mverts, int numVerts, MLoop *mloop, MPoly *mpo
MVert *mv = &mverts[i];
float *no = tnorms[i];
- if (normalize_v3(no) == 0.0f)
+ if (UNLIKELY(normalize_v3(no) == 0.0f)) {
normalize_v3_v3(no, mv->co);
+ }
normal_float_to_short_v3(mv->no, no);
}
@@ -1981,8 +1989,9 @@ void BKE_mesh_calc_normals_tessface(MVert *mverts, int numVerts, MFace *mfaces,
MVert *mv = &mverts[i];
float *no = tnorms[i];
- if (normalize_v3(no) == 0.0f)
+ if (UNLIKELY(normalize_v3(no) == 0.0f)) {
normalize_v3_v3(no, mv->co);
+ }
normal_float_to_short_v3(mv->no, no);
}
@@ -2038,11 +2047,11 @@ static void bm_corners_to_loops_ex(ID *id, CustomData *fdata, CustomData *ldata,
MDisps *ld = CustomData_get(ldata, loopstart, CD_MDISPS);
MDisps *fd = CustomData_get(fdata, findex, CD_MDISPS);
float (*disps)[3] = fd->disps;
- int i, tot = mf->v4 ? 4 : 3;
+ int tot = mf->v4 ? 4 : 3;
int side, corners;
if (CustomData_external_test(fdata, CD_MDISPS)) {
- if (id) {
+ if (id && fdata->external) {
CustomData_external_add(ldata, id, CD_MDISPS,
totloop, fdata->external->filename);
}
@@ -2124,8 +2133,6 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, CustomData *fdata, CustomData
/* just in case some of these layers are filled in (can happen with python created meshes) */
CustomData_free(ldata, totloop_i);
CustomData_free(pdata, totpoly_i);
- memset(ldata, 0, sizeof(*ldata));
- memset(pdata, 0, sizeof(*pdata));
totpoly = totface_i;
mpoly = MEM_callocN(sizeof(MPoly) * totpoly, "mpoly converted");
@@ -2162,7 +2169,7 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, CustomData *fdata, CustomData
me->flag &= ~ME_FGON;
}
- polyindex = CustomData_get_layer(fdata, CD_POLYINDEX);
+ polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX);
j = 0; /* current loop index */
ml = mloop;
@@ -2504,12 +2511,9 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata,
ScanFillContext sf_ctx;
ScanFillVert *sf_vert, *sf_vert_last, *sf_vert_first;
ScanFillFace *sf_tri;
- int *mface_orig_index = NULL;
- BLI_array_declare(mface_orig_index);
int *mface_to_poly_map = NULL;
BLI_array_declare(mface_to_poly_map);
int lindex[4]; /* only ever use 3 in this case */
- int *poly_orig_index;
int poly_index, j, mface_index;
const int numTex = CustomData_number_of_layers(pdata, CD_MTEXPOLY);
@@ -2527,7 +2531,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata,
mface_index = 0;
mp = mpoly;
- poly_orig_index = CustomData_get_layer(pdata, CD_ORIGINDEX);
for (poly_index = 0; poly_index < totpoly; poly_index++, mp++) {
if (mp->totloop < 3) {
/* do nothing */
@@ -2547,10 +2550,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata,
mf->v4 = 0; \
mf->mat_nr = mp->mat_nr; \
mf->flag = mp->flag; \
- if (poly_orig_index) { \
- BLI_array_append(mface_orig_index, \
- poly_orig_index[poly_index]); \
- } \
(void)0
/* ALMOST IDENTICAL TO DEFINE ABOVE (see EXCEPTION) */
@@ -2566,10 +2565,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata,
mf->v4 = mp->loopstart + 3; /* EXCEPTION */ \
mf->mat_nr = mp->mat_nr; \
mf->flag = mp->flag; \
- if (poly_orig_index) { \
- BLI_array_append(mface_orig_index, \
- poly_orig_index[poly_index]); \
- } \
mf->edcode |= TESSFACE_IS_QUAD; /* EXCEPTION */ \
(void)0
@@ -2616,9 +2611,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata,
if (totfilltri) {
BLI_array_grow_items(mface_to_poly_map, totfilltri);
BLI_array_grow_items(mface, totfilltri);
- if (poly_orig_index) {
- BLI_array_grow_items(mface_orig_index, totfilltri);
- }
for (sf_tri = sf_ctx.fillfacebase.first; sf_tri; sf_tri = sf_tri->next, mf++) {
mface_to_poly_map[mface_index] = poly_index;
@@ -2637,10 +2629,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata,
mf->edcode |= TESSFACE_SCANFILL; /* tag for sorting loop indices */
#endif
- if (poly_orig_index) {
- mface_orig_index[mface_index] = poly_orig_index[poly_index];
- }
-
mface_index++;
}
}
@@ -2650,7 +2638,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata,
}
CustomData_free(fdata, totface);
- memset(fdata, 0, sizeof(CustomData));
totface = mface_index;
@@ -2658,23 +2645,13 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata,
if (LIKELY((MEM_allocN_len(mface) / sizeof(*mface)) != totface)) {
mface = MEM_reallocN(mface, sizeof(*mface) * totface);
mface_to_poly_map = MEM_reallocN(mface_to_poly_map, sizeof(*mface_to_poly_map) * totface);
- if (mface_orig_index) {
- mface_orig_index = MEM_reallocN(mface_orig_index, sizeof(*mface_orig_index) * totface);
- }
}
CustomData_add_layer(fdata, CD_MFACE, CD_ASSIGN, mface, totface);
- /* CD_POLYINDEX will contain an array of indices from tessfaces to the polygons
+ /* CD_ORIGINDEX will contain an array of indices from tessfaces to the polygons
* they are directly tessellated from */
- CustomData_add_layer(fdata, CD_POLYINDEX, CD_ASSIGN, mface_to_poly_map, totface);
- if (mface_orig_index) {
- /* If polys had a CD_ORIGINDEX layer, then the tessellated faces will get this
- * layer as well, pointing to polys from the original mesh (not the polys
- * that just got tessellated) */
- CustomData_add_layer(fdata, CD_ORIGINDEX, CD_ASSIGN, mface_orig_index, totface);
- }
-
+ CustomData_add_layer(fdata, CD_ORIGINDEX, CD_ASSIGN, mface_to_poly_map, totface);
CustomData_from_bmeshpoly(fdata, pdata, ldata, totface);
if (do_face_nor_cpy) {
@@ -2805,7 +2782,6 @@ int BKE_mesh_mpoly_to_mface(struct CustomData *fdata, struct CustomData *ldata,
}
CustomData_free(fdata, totface);
- memset(fdata, 0, sizeof(CustomData));
totface = k;
@@ -2899,8 +2875,8 @@ static void mesh_calc_ngon_normal(MPoly *mpoly, MLoop *loopstart,
}
}
-void mesh_calc_poly_normal(MPoly *mpoly, MLoop *loopstart,
- MVert *mvarray, float no[3])
+void BKE_mesh_calc_poly_normal(MPoly *mpoly, MLoop *loopstart,
+ MVert *mvarray, float no[3])
{
if (mpoly->totloop > 4) {
mesh_calc_ngon_normal(mpoly, loopstart, mvarray, no);
@@ -3015,7 +2991,7 @@ void BKE_mesh_calc_poly_center(MPoly *mpoly, MLoop *loopstart,
/* note, passing polynormal is only a speedup so we can skip calculating it */
float BKE_mesh_calc_poly_area(MPoly *mpoly, MLoop *loopstart,
- MVert *mvarray, float polynormal[3])
+ MVert *mvarray, const float polynormal[3])
{
if (mpoly->totloop == 3) {
return area_tri_v3(mvarray[loopstart[0].v].co,
@@ -3034,7 +3010,7 @@ float BKE_mesh_calc_poly_area(MPoly *mpoly, MLoop *loopstart,
int i;
MLoop *l_iter = loopstart;
float area, polynorm_local[3], (*vertexcos)[3];
- float *no = polynormal ? polynormal : polynorm_local;
+ const float *no = polynormal ? polynormal : polynorm_local;
BLI_array_fixedstack_declare(vertexcos, BM_NGON_STACK_SIZE, mpoly->totloop, __func__);
/* pack vertex cos into an array for area_poly_v3 */
@@ -3044,7 +3020,7 @@ float BKE_mesh_calc_poly_area(MPoly *mpoly, MLoop *loopstart,
/* need normal for area_poly_v3 as well */
if (polynormal == NULL) {
- mesh_calc_poly_normal(mpoly, loopstart, mvarray, no);
+ BKE_mesh_calc_poly_normal(mpoly, loopstart, mvarray, polynorm_local);
}
/* finally calculate the area */
@@ -3174,6 +3150,32 @@ int BKE_mesh_center_bounds(Mesh *me, float cent[3])
return 0;
}
+int BKE_mesh_center_centroid(Mesh *me, float cent[3])
+{
+ int i = me->totpoly;
+ MPoly *mpoly;
+ float poly_area;
+ float total_area = 0.0f;
+ float poly_cent[3];
+
+ zero_v3(cent);
+
+ /* calculate a weighted average of polygon centroids */
+ for (mpoly = me->mpoly; i--; mpoly++) {
+ BKE_mesh_calc_poly_center(mpoly, me->mloop + mpoly->loopstart, me->mvert, poly_cent);
+ poly_area = BKE_mesh_calc_poly_area(mpoly, me->mloop + mpoly->loopstart, me->mvert, NULL);
+
+ madd_v3_v3fl(cent, poly_cent, poly_area);
+ total_area += poly_area;
+ }
+ /* otherwise we get NAN for 0 polys */
+ if (me->totpoly) {
+ mul_v3_fl(cent, 1.0f / total_area);
+ }
+
+ return (me->totpoly != 0);
+}
+
void BKE_mesh_translate(Mesh *me, float offset[3], int do_keys)
{
int i = me->totvert;
diff --git a/source/blender/blenkernel/intern/mesh_validate.c b/source/blender/blenkernel/intern/mesh_validate.c
index 79e3fc19d20..128b9ae242e 100644
--- a/source/blender/blenkernel/intern/mesh_validate.c
+++ b/source/blender/blenkernel/intern/mesh_validate.c
@@ -228,7 +228,6 @@ int BKE_mesh_validate_arrays(Mesh *mesh,
}
for (i = 1; i < totvert; i++, mv++) {
- int j;
int fix_normal = TRUE;
for (j = 0; j < 3; j++) {
@@ -717,7 +716,6 @@ int BKE_mesh_validate_arrays(Mesh *mesh,
MDeformVert *dv;
for (i = 0, dv = dverts; i < totvert; i++, dv++) {
MDeformWeight *dw;
- unsigned int j;
for (j = 0, dw = dv->dw; j < dv->totweight; j++, dw++) {
/* note, greater then max defgroups is accounted for in our code, but not < 0 */
@@ -914,7 +912,7 @@ void BKE_mesh_calc_edges(Mesh *mesh, int update)
{
CustomData edata;
EdgeHashIterator *ehi;
- MPoly *mp = mesh->mpoly;
+ MPoly *mp;
MEdge *med, *med_orig;
EdgeHash *eh = BLI_edgehash_new();
int i, totedge, totpoly = mesh->totpoly;
@@ -932,7 +930,7 @@ void BKE_mesh_calc_edges(Mesh *mesh, int update)
}
/* mesh loops (bmesh only) */
- for (i = 0; i < totpoly; i++, mp++) {
+ for (mp = mesh->mpoly, i = 0; i < totpoly; mp++, i++) {
MLoop *l = &mesh->mloop[mp->loopstart];
int j, l_prev = (l + (mp->totloop - 1))->v;
for (j = 0; j < mp->totloop; j++, l++) {
@@ -946,7 +944,7 @@ void BKE_mesh_calc_edges(Mesh *mesh, int update)
totedge = BLI_edgehash_size(eh);
/* write new edges into a temporary CustomData */
- memset(&edata, 0, sizeof(edata));
+ CustomData_reset(&edata);
CustomData_add_layer(&edata, CD_MEDGE, CD_CALLOC, NULL, totedge);
med = CustomData_get_layer(&edata, CD_MEDGE);
@@ -970,8 +968,7 @@ void BKE_mesh_calc_edges(Mesh *mesh, int update)
if (mesh->totpoly) {
/* second pass, iterate through all loops again and assign
* the newly created edges to them. */
- MPoly *mp = mesh->mpoly;
- for (i = 0; i < mesh->totpoly; i++, mp++) {
+ for (mp = mesh->mpoly, i = 0; i < mesh->totpoly; mp++, i++) {
MLoop *l = &mesh->mloop[mp->loopstart];
MLoop *l_prev = (l + (mp->totloop - 1));
int j;
diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c
index 65538e5bea2..9c7cbc42bdd 100644
--- a/source/blender/blenkernel/intern/modifier.c
+++ b/source/blender/blenkernel/intern/modifier.c
@@ -55,6 +55,8 @@
#include "BLI_linklist.h"
#include "BLI_string.h"
+#include "BLF_translation.h"
+
#include "BKE_cloth.h"
#include "BKE_key.h"
#include "BKE_multires.h"
@@ -259,12 +261,13 @@ int modifier_nonGeometrical(ModifierData *md)
return (mti->type == eModifierTypeType_NonGeometrical);
}
-void modifier_setError(ModifierData *md, const char *format, ...)
+void modifier_setError(ModifierData *md, const char *_format, ...)
{
char buffer[512];
va_list ap;
+ const char *format = TIP_(_format);
- va_start(ap, format);
+ va_start(ap, _format);
vsnprintf(buffer, sizeof(buffer), format, ap);
va_end(ap);
buffer[sizeof(buffer) - 1] = '\0';
@@ -482,7 +485,7 @@ ModifierData *modifiers_getVirtualModifierList(Object *ob)
}
/* shape key modifier, not yet for curves */
- if (ELEM(ob->type, OB_MESH, OB_LATTICE) && ob_get_key(ob)) {
+ if (ELEM(ob->type, OB_MESH, OB_LATTICE) && BKE_key_from_object(ob)) {
if (ob->type == OB_MESH && (ob->shapeflag & OB_SHAPE_EDIT_MODE))
smd.modifier.mode |= eModifierMode_Editmode | eModifierMode_OnCage;
else
@@ -494,8 +497,8 @@ ModifierData *modifiers_getVirtualModifierList(Object *ob)
return md;
}
-/* Takes an object and returns its first selected armature, else just its
- * armature
+
+/* Takes an object and returns its first selected armature, else just its armature
* This should work for multiple armatures per object
*/
Object *modifiers_isDeformedByArmature(Object *ob)
@@ -518,9 +521,8 @@ Object *modifiers_isDeformedByArmature(Object *ob)
return NULL;
}
-/* Takes an object and returns its first selected lattice, else just its
- * lattice
- * This should work for multiple lattics per object
+/* Takes an object and returns its first selected lattice, else just its lattice
+ * This should work for multiple lattices per object
*/
Object *modifiers_isDeformedByLattice(Object *ob)
{
@@ -542,7 +544,28 @@ Object *modifiers_isDeformedByLattice(Object *ob)
return NULL;
}
-
+/* Takes an object and returns its first selected curve, else just its curve
+ * This should work for multiple curves per object
+ */
+Object *modifiers_isDeformedByCurve(Object *ob)
+{
+ ModifierData *md = modifiers_getVirtualModifierList(ob);
+ CurveModifierData *cmd = NULL;
+
+ /* return the first selected curve, this lets us use multiple curves */
+ for (; md; md = md->next) {
+ if (md->type == eModifierType_Curve) {
+ cmd = (CurveModifierData *) md;
+ if (cmd->object && (cmd->object->flag & SELECT))
+ return cmd->object;
+ }
+ }
+
+ if (cmd) /* if were still here then return the last curve */
+ return cmd->object;
+
+ return NULL;
+}
int modifiers_usesArmature(Object *ob, bArmature *arm)
{
@@ -574,10 +597,12 @@ int modifiers_isCorrectableDeformed(Object *ob)
ModifierData *md = modifiers_getVirtualModifierList(ob);
for (; md; md = md->next) {
- if (ob->mode == OB_MODE_EDIT && (md->mode & eModifierMode_Editmode) == 0) ;
- else
- if (modifier_isCorrectableDeformed(md))
+ if (ob->mode == OB_MODE_EDIT && (md->mode & eModifierMode_Editmode) == 0) {
+ /* pass */
+ }
+ else if (modifier_isCorrectableDeformed(md)) {
return 1;
+ }
}
return 0;
}
diff --git a/source/blender/blenkernel/intern/modifiers_bmesh.c b/source/blender/blenkernel/intern/modifiers_bmesh.c
index 72c3cda9272..98eac9b95af 100644
--- a/source/blender/blenkernel/intern/modifiers_bmesh.c
+++ b/source/blender/blenkernel/intern/modifiers_bmesh.c
@@ -49,12 +49,13 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm)
MLoop *mloop, *ml;
BMVert *v, **vtable, **verts = NULL;
BMEdge *e, **etable, **edges = NULL;
- float has_face_normals;
+ float (*face_normals)[3];
BMFace *f;
BMIter liter;
BLI_array_declare(verts);
BLI_array_declare(edges);
int i, j, k, totvert, totedge /* , totface */ /* UNUSED */ ;
+ int is_init = (bm->totvert == 0) && (bm->totedge == 0) && (bm->totface == 0);
/*merge custom data layout*/
CustomData_bmesh_merge(&dm->vertData, &bm->vdata, CD_MASK_DERIVEDMESH, CD_CALLOC, bm, BM_VERT);
@@ -72,8 +73,8 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm)
BM_data_layer_add(bm, &bm->edata, CD_BWEIGHT);
BM_data_layer_add(bm, &bm->vdata, CD_BWEIGHT);
- vtable = MEM_callocN(sizeof(void **) * totvert, "vert table in BMDM_Copy");
- etable = MEM_callocN(sizeof(void **) * totedge, "edge table in BMDM_Copy");
+ vtable = MEM_callocN(sizeof(void **) * totvert, __func__);
+ etable = MEM_callocN(sizeof(void **) * totedge, __func__);
/*do verts*/
mv = mvert = dm->dupVertArray(dm);
@@ -81,6 +82,7 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm)
v = BM_vert_create(bm, mv->co, NULL);
normal_short_to_float_v3(v->no, mv->no);
v->head.hflag = BM_vert_flag_from_mflag(mv->flag);
+ BM_elem_index_set(v, i); /* set_inline */
CustomData_to_bmesh_block(&dm->vertData, &bm->vdata, i, &v->head.data);
@@ -89,13 +91,16 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm)
vtable[i] = v;
}
MEM_freeN(mvert);
+ if (is_init) bm->elem_index_dirty &= ~BM_VERT;
/*do edges*/
me = medge = dm->dupEdgeArray(dm);
for (i = 0; i < totedge; i++, me++) {
+ //BLI_assert(BM_edge_exists(vtable[me->v1], vtable[me->v2]) == NULL);
e = BM_edge_create(bm, vtable[me->v1], vtable[me->v2], NULL, FALSE);
e->head.hflag = BM_edge_flag_from_mflag(me->flag);
+ BM_elem_index_set(e, i); /* set_inline */
CustomData_to_bmesh_block(&dm->edgeData, &bm->edata, i, &e->head.data);
etable[i] = e;
@@ -106,11 +111,13 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm)
BM_elem_float_data_set(&bm->edata, e, CD_BWEIGHT, (float)me->bweight / 255.0f);
}
MEM_freeN(medge);
+ if (is_init) bm->elem_index_dirty &= ~BM_EDGE;
- /*do faces*/
+ /* do faces */
+ /* note: i_alt is aligned with bmesh faces which may not always align with mpolys */
mp = dm->getPolyArray(dm);
mloop = dm->getLoopArray(dm);
- has_face_normals = CustomData_has_layer(&dm->polyData, CD_NORMAL);
+ face_normals = CustomData_get_layer(&dm->polyData, CD_NORMAL); /* can be NULL */
for (i = 0; i < dm->numPolyData; i++, mp++) {
BMLoop *l;
@@ -129,10 +136,12 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm)
f = BM_face_create_ngon(bm, verts[0], verts[1], edges, mp->totloop, FALSE);
- if (!f)
+ if (UNLIKELY(f == NULL)) {
continue;
+ }
f->head.hflag = BM_face_flag_from_mflag(mp->flag);
+ BM_elem_index_set(f, bm->totface - 1); /* set_inline */
f->mat_nr = mp->mat_nr;
l = BM_iter_new(&liter, bm, BM_LOOPS_OF_FACE, f);
@@ -143,13 +152,14 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm)
CustomData_to_bmesh_block(&dm->polyData, &bm->pdata, i, &f->head.data);
- if (has_face_normals) {
- float *fno;
-
- fno = CustomData_bmesh_get(&bm->pdata, &f->head.data, CD_NORMAL);
- copy_v3_v3(f->no, fno);
+ if (face_normals) {
+ copy_v3_v3(f->no, face_normals[i]);
+ }
+ else {
+ BM_face_normal_update(f);
}
}
+ if (is_init) bm->elem_index_dirty &= ~BM_FACE;
MEM_freeN(vtable);
MEM_freeN(etable);
diff --git a/source/blender/blenkernel/intern/movieclip.c b/source/blender/blenkernel/intern/movieclip.c
index 97d4c150b84..6e8f2697ee1 100644
--- a/source/blender/blenkernel/intern/movieclip.c
+++ b/source/blender/blenkernel/intern/movieclip.c
@@ -52,6 +52,7 @@
#include "DNA_screen_types.h"
#include "DNA_space_types.h"
#include "DNA_movieclip_types.h"
+#include "DNA_node_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "DNA_view3d_types.h"
@@ -71,6 +72,7 @@
#include "BKE_global.h"
#include "BKE_main.h"
#include "BKE_movieclip.h"
+#include "BKE_node.h"
#include "BKE_image.h" /* openanim */
#include "BKE_tracking.h"
@@ -292,11 +294,11 @@ static void movieclip_calc_length(MovieClip *clip)
clip->len = framenr + 1;
}
else {
- for (;; ) {
+ for (;;) {
get_sequence_fname(clip, framenr, name);
if (!BLI_exists(name)) {
- clip->len = framenr + 1;
+ clip->len = framenr;
break;
}
@@ -518,6 +520,24 @@ static void movieclip_load_get_szie(MovieClip *clip)
}
}
+static void detect_clip_source(MovieClip *clip)
+{
+ ImBuf *ibuf;
+ char name[FILE_MAX];
+
+ BLI_strncpy(name, clip->name, sizeof(name));
+ BLI_path_abs(name, G.main->name);
+
+ ibuf = IMB_testiffname(name, IB_rect | IB_multilayer);
+ if (ibuf) {
+ clip->source = MCLIP_SRC_SEQUENCE;
+ IMB_freeImBuf(ibuf);
+ }
+ else {
+ clip->source = MCLIP_SRC_MOVIE;
+ }
+}
+
/* checks if image was already loaded, then returns same image
* otherwise creates new.
* does not load ibuf itself
@@ -563,10 +583,7 @@ MovieClip *BKE_movieclip_file_add(const char *name)
clip = movieclip_alloc(libname);
BLI_strncpy(clip->name, name, sizeof(clip->name));
- if (BLI_testextensie_array(name, imb_ext_movie))
- clip->source = MCLIP_SRC_MOVIE;
- else
- clip->source = MCLIP_SRC_SEQUENCE;
+ detect_clip_source(clip);
movieclip_load_get_szie(clip);
if (clip->lastsize[0]) {
@@ -614,34 +631,27 @@ static ImBuf *get_undistorted_ibuf(MovieClip *clip, struct MovieDistortion *dist
else
undistibuf = BKE_tracking_undistort_frame(&clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f);
- if (undistibuf->userflags & IB_RECT_INVALID) {
- ibuf->userflags &= ~IB_RECT_INVALID;
- IMB_rect_from_float(undistibuf);
- }
-
IMB_scaleImBuf(undistibuf, ibuf->x, ibuf->y);
return undistibuf;
}
-static int need_undistortion_postprocess(MovieClipUser *user, int flag)
+static int need_undistortion_postprocess(MovieClipUser *user)
{
int result = 0;
/* only full undistorted render can be used as on-fly undistorting image */
- if (flag & MCLIP_USE_PROXY) {
- result |= (user->render_size == MCLIP_PROXY_RENDER_SIZE_FULL) &&
- (user->render_flag & MCLIP_PROXY_RENDER_UNDISTORT) != 0;
- }
+ result |= (user->render_size == MCLIP_PROXY_RENDER_SIZE_FULL) &&
+ (user->render_flag & MCLIP_PROXY_RENDER_UNDISTORT) != 0;
return result;
}
-static int need_postprocessed_frame(MovieClipUser *user, int flag, int postprocess_flag)
+static int need_postprocessed_frame(MovieClipUser *user, int postprocess_flag)
{
int result = postprocess_flag;
- result |= need_undistortion_postprocess(user, flag);
+ result |= need_undistortion_postprocess(user);
return result;
}
@@ -688,7 +698,7 @@ static ImBuf *get_postprocessed_cached_frame(MovieClip *clip, MovieClipUser *use
if (cache->postprocessed.flag != postprocess_flag)
return NULL;
- if (need_undistortion_postprocess(user, flag)) {
+ if (need_undistortion_postprocess(user)) {
if (!check_undistortion_cache_flags(clip))
return NULL;
}
@@ -719,7 +729,7 @@ static ImBuf *put_postprocessed_frame_to_cache(MovieClip *clip, MovieClipUser *u
cache->postprocessed.render_flag = 0;
}
- if (need_undistortion_postprocess(user, flag)) {
+ if (need_undistortion_postprocess(user)) {
copy_v2_v2(cache->postprocessed.principal, camera->principal);
copy_v3_v3(&cache->postprocessed.k1, &camera->k1);
cache->postprocessed.undistortion_used = TRUE;
@@ -763,7 +773,7 @@ static ImBuf *movieclip_get_postprocessed_ibuf(MovieClip *clip, MovieClipUser *u
BLI_lock_thread(LOCK_MOVIECLIP);
/* try to obtain cached postprocessed frame first */
- if (need_postprocessed_frame(user, flag, postprocess_flag)) {
+ if (need_postprocessed_frame(user, postprocess_flag)) {
ibuf = get_postprocessed_cached_frame(clip, user, flag, postprocess_flag);
if (!ibuf)
@@ -1087,15 +1097,24 @@ void BKE_movieclip_reload(MovieClip *clip)
clip->tracking.stabilization.ok = FALSE;
/* update clip source */
- if (BLI_testextensie_array(clip->name, imb_ext_movie))
- clip->source = MCLIP_SRC_MOVIE;
- else
- clip->source = MCLIP_SRC_SEQUENCE;
+ detect_clip_source(clip);
clip->lastsize[0] = clip->lastsize[1] = 0;
movieclip_load_get_szie(clip);
movieclip_calc_length(clip);
+
+ /* same as for image update -- don't use notifiers because they are not 100% sure to succeeded
+ * (node trees which are not currently visible wouldn't be refreshed)
+ */
+ {
+ Scene *scene;
+ for (scene = G.main->scene.first; scene; scene = scene->id.next) {
+ if (scene->nodetree) {
+ nodeUpdateID(scene->nodetree, &clip->id);
+ }
+ }
+ }
}
void BKE_movieclip_update_scopes(MovieClip *clip, MovieClipUser *user, MovieClipScopes *scopes)
@@ -1326,6 +1345,11 @@ void BKE_movieclip_unlink(Main *bmain, MovieClip *clip)
}
}
+ {
+ bNodeTreeType *treetype = ntreeGetType(NTREE_COMPOSIT);
+ treetype->foreach_nodetree(bmain, (void *)clip, &BKE_node_tree_unlink_id_cb);
+ }
+
clip->id.us = 0;
}
diff --git a/source/blender/blenkernel/intern/multires.c b/source/blender/blenkernel/intern/multires.c
index 1c06d95a70b..66f2ff12258 100644
--- a/source/blender/blenkernel/intern/multires.c
+++ b/source/blender/blenkernel/intern/multires.c
@@ -666,7 +666,9 @@ static void multires_del_higher(MultiresModifierData *mmd, Object *ob, int lvl)
mdisp->totdisp = totdisp;
mdisp->level = lvl;
- multires_grid_paint_mask_downsample(&gpm[g], lvl);
+ if (gpm) {
+ multires_grid_paint_mask_downsample(&gpm[g], lvl);
+ }
}
}
}
@@ -893,15 +895,16 @@ static void multires_subdivide(MultiresModifierData *mmd, Object *ob, int totlvl
CCGKey highGridKey, lowGridKey;
CCGSubSurf *ss;
int i, numGrids, highGridSize;
+ int has_mask = CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK);
/* create subsurf DM from original mesh at high level */
cddm = CDDM_from_mesh(me, NULL);
DM_set_only_copy(cddm, CD_MASK_BAREMESH);
- highdm = subsurf_dm_create_local(ob, cddm, totlvl, simple, 0, mmd->flags & eMultiresModifierFlag_PlainUv, TRUE);
+ highdm = subsurf_dm_create_local(ob, cddm, totlvl, simple, 0, mmd->flags & eMultiresModifierFlag_PlainUv, has_mask);
ss = ((CCGDerivedMesh *)highdm)->ss;
/* create multires DM from original mesh at low level */
- lowdm = multires_dm_create_local(ob, cddm, lvl, lvl, simple, TRUE);
+ lowdm = multires_dm_create_local(ob, cddm, lvl, lvl, simple, has_mask);
cddm->release(cddm);
/* copy subsurf grids and replace them with low displaced grids */
@@ -1042,7 +1045,7 @@ static void multiresModifier_disp_run(DerivedMesh *dm, Mesh *me, DerivedMesh *dm
k = 0; /*current loop/mdisp index within the mloop array*/
- #pragma omp parallel for private(i) if (totloop*gridSize*gridSize >= CCG_OMP_LIMIT)
+ #pragma omp parallel for private(i) if (totloop * gridSize * gridSize >= CCG_OMP_LIMIT)
for (i = 0; i < totpoly; ++i) {
const int numVerts = mpoly[i].totloop;
@@ -1158,23 +1161,23 @@ void multires_modifier_update_mdisps(struct DerivedMesh *dm)
int totlvl = ccgdm->multires.totlvl;
if (lvl < totlvl) {
- Mesh *me = ob->data;
DerivedMesh *lowdm, *cddm, *highdm;
CCGElem **highGridData, **lowGridData, **subGridData, **gridData, *diffGrid;
CCGKey highGridKey, lowGridKey;
CCGSubSurf *ss;
int i, j, numGrids, highGridSize, lowGridSize;
+ int has_mask = CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK);
/* create subsurf DM from original mesh at high level */
if (ob->derivedDeform) cddm = CDDM_copy(ob->derivedDeform);
else cddm = CDDM_from_mesh(me, NULL);
DM_set_only_copy(cddm, CD_MASK_BAREMESH);
- highdm = subsurf_dm_create_local(ob, cddm, totlvl, mmd->simple, 0, mmd->flags & eMultiresModifierFlag_PlainUv, TRUE);
+ highdm = subsurf_dm_create_local(ob, cddm, totlvl, mmd->simple, 0, mmd->flags & eMultiresModifierFlag_PlainUv, has_mask);
ss = ((CCGDerivedMesh *)highdm)->ss;
/* create multires DM from original mesh and displacements */
- lowdm = multires_dm_create_local(ob, cddm, lvl, totlvl, mmd->simple, TRUE);
+ lowdm = multires_dm_create_local(ob, cddm, lvl, totlvl, mmd->simple, has_mask);
cddm->release(cddm);
/* gather grid data */
@@ -1226,12 +1229,13 @@ void multires_modifier_update_mdisps(struct DerivedMesh *dm)
}
else {
DerivedMesh *cddm, *subdm;
+ int has_mask = CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK);
if (ob->derivedDeform) cddm = CDDM_copy(ob->derivedDeform);
else cddm = CDDM_from_mesh(me, NULL);
DM_set_only_copy(cddm, CD_MASK_BAREMESH);
- subdm = subsurf_dm_create_local(ob, cddm, mmd->totlvl, mmd->simple, 0, mmd->flags & eMultiresModifierFlag_PlainUv, TRUE);
+ subdm = subsurf_dm_create_local(ob, cddm, mmd->totlvl, mmd->simple, 0, mmd->flags & eMultiresModifierFlag_PlainUv, has_mask);
cddm->release(cddm);
multiresModifier_disp_run(dm, me, NULL, CALC_DISPLACEMENTS, subdm->getGridData(subdm), mmd->totlvl);
@@ -1321,7 +1325,7 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to)
k = 0; /*current loop/mdisp index within the mloop array*/
- //#pragma omp parallel for private(i) if (dm->numLoopData*gridSize*gridSize >= CCG_OMP_LIMIT)
+ //#pragma omp parallel for private(i) if (dm->numLoopData * gridSize * gridSize >= CCG_OMP_LIMIT)
for (i = 0; i < dm->numPolyData; ++i) {
const int numVerts = mpoly[i].totloop;
@@ -1626,7 +1630,7 @@ void multires_free(Multires *mr)
}
while (lvl) {
- multires_free_level(lvl);
+ multires_free_level(lvl);
lvl = lvl->next;
}
@@ -2081,8 +2085,8 @@ void multires_load_old(Object *ob, Mesh *me)
CustomData_add_layer(&me->vdata, l->type, CD_REFERENCE, l->data, me->totvert);
for (i = 0, l = me->mr->fdata.layers; i < me->mr->fdata.totlayer; ++i, ++l)
CustomData_add_layer(&me->fdata, l->type, CD_REFERENCE, l->data, me->totface);
- memset(&me->mr->vdata, 0, sizeof(CustomData));
- memset(&me->mr->fdata, 0, sizeof(CustomData));
+ CustomData_reset(&me->mr->vdata);
+ CustomData_reset(&me->mr->fdata);
multires_load_old_vcols(me);
multires_load_old_face_flags(me);
@@ -2107,7 +2111,7 @@ void multires_load_old(Object *ob, Mesh *me)
* reference subsurfed dm with this option, before calling multiresModifier_disp_run(),
* which implicitly expects both subsurfs from its first dm and oldGridData parameters to
* be of the same "format"! */
- dm = multires_make_derived_from_derived(orig, mmd, ob, MULTIRES_ALLOC_PAINT_MASK);
+ dm = multires_make_derived_from_derived(orig, mmd, ob, 0);
multires_load_old_dm(dm, me, mmd->totlvl + 1);
@@ -2196,7 +2200,7 @@ static void multires_apply_smat(Scene *scene, Object *ob, float smat[3][3])
dGridSize = multires_side_tot[high_mmd.totlvl];
dSkip = (dGridSize - 1) / (gridSize - 1);
- #pragma omp parallel for private(i) if (me->totface*gridSize*gridSize*4 >= CCG_OMP_LIMIT)
+ #pragma omp parallel for private(i) if (me->totface * gridSize * gridSize * 4 >= CCG_OMP_LIMIT)
for (i = 0; i < me->totpoly; ++i) {
const int numVerts = mpoly[i].totloop;
MDisps *mdisp = &mdisps[mpoly[i].loopstart];
diff --git a/source/blender/blenkernel/intern/navmesh_conversion.c b/source/blender/blenkernel/intern/navmesh_conversion.c
index a21878d1d7d..3bf5f863557 100644
--- a/source/blender/blenkernel/intern/navmesh_conversion.c
+++ b/source/blender/blenkernel/intern/navmesh_conversion.c
@@ -36,44 +36,44 @@
#include "DNA_meshdata_types.h"
-#include "BKE_navmesh_conversion.h"
-#include "BKE_cdderivedmesh.h"
-
#include "BLI_utildefines.h"
#include "BLI_math.h"
+#include "BKE_navmesh_conversion.h"
+#include "BKE_cdderivedmesh.h"
+
#include "recast-capi.h"
-BLI_INLINE float area2(const float* a, const float* b, const float* c)
+BLI_INLINE float area2(const float *a, const float *b, const float *c)
{
return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]);
}
-BLI_INLINE int left(const float* a, const float* b, const float* c)
+BLI_INLINE int left(const float *a, const float *b, const float *c)
{
return area2(a, b, c) < 0;
}
-int polyNumVerts(const unsigned short* p, const int vertsPerPoly)
+int polyNumVerts(const unsigned short *p, const int vertsPerPoly)
{
int i, nv = 0;
- for (i=0; i<vertsPerPoly; i++) {
- if (p[i]==0xffff)
+ for (i = 0; i < vertsPerPoly; i++) {
+ if (p[i] == 0xffff)
break;
nv++;
}
return nv;
}
-int polyIsConvex(const unsigned short* p, const int vertsPerPoly, const float* verts)
+int polyIsConvex(const unsigned short *p, const int vertsPerPoly, const float *verts)
{
int j, nv = polyNumVerts(p, vertsPerPoly);
- if (nv<3)
+ if (nv < 3)
return 0;
- for (j=0; j<nv; j++) {
- const float* v = &verts[3*p[j]];
- const float* v_next = &verts[3*p[(j+1)%nv]];
- const float* v_prev = &verts[3*p[(nv+j-1)%nv]];
+ for (j = 0; j < nv; j++) {
+ const float *v = &verts[3 * p[j]];
+ const float *v_next = &verts[3 * p[(j + 1) % nv]];
+ const float *v_prev = &verts[3 * p[(nv + j - 1) % nv]];
if (!left(v_prev, v, v_next))
return 0;
@@ -81,7 +81,8 @@ int polyIsConvex(const unsigned short* p, const int vertsPerPoly, const float* v
return 1;
}
-float distPointToSegmentSq(const float* point, const float* a, const float* b)
+/* XXX, could replace with #dist_to_line_segment_v3(), or add a squared version */
+float distPointToSegmentSq(const float point[3], const float a[3], const float b[3])
{
float abx[3], dx[3];
float d, t;
@@ -89,24 +90,24 @@ float distPointToSegmentSq(const float* point, const float* a, const float* b)
sub_v3_v3v3(abx, b, a);
sub_v3_v3v3(dx, point, a);
- d = abx[0]*abx[0]+abx[2]*abx[2];
- t = abx[0]*dx[0]+abx[2]*dx[2];
+ d = abx[0] * abx[0] + abx[2] * abx[2];
+ t = abx[0] * dx[0] + abx[2] * dx[2];
- if (d > 0)
+ if (d > 0.0f)
t /= d;
- if (t < 0)
- t = 0;
- else if (t > 1)
- t = 1;
- dx[0] = a[0] + t*abx[0] - point[0];
- dx[2] = a[2] + t*abx[2] - point[2];
-
- return dx[0]*dx[0] + dx[2]*dx[2];
+ if (t < 0.0f)
+ t = 0.0f;
+ else if (t > 1.0f)
+ t = 1.0f;
+ dx[0] = a[0] + t * abx[0] - point[0];
+ dx[2] = a[2] + t * abx[2] - point[2];
+
+ return dx[0] * dx[0] + dx[2] * dx[2];
}
-int buildRawVertIndicesData(DerivedMesh* dm, int *nverts_r, float **verts_r,
- int *ntris_r, unsigned short **tris_r, int **trisToFacesMap_r,
- int **recastData)
+int buildRawVertIndicesData(DerivedMesh *dm, int *nverts_r, float **verts_r,
+ int *ntris_r, unsigned short **tris_r, int **trisToFacesMap_r,
+ int **recastData)
{
int vi, fi, triIdx;
int nverts, ntris;
@@ -117,49 +118,49 @@ int buildRawVertIndicesData(DerivedMesh* dm, int *nverts_r, float **verts_r,
MFace *faces;
nverts = dm->getNumVerts(dm);
- if (nverts>=0xffff) {
+ if (nverts >= 0xffff) {
printf("Converting navmesh: Error! Too many vertices. Max number of vertices %d\n", 0xffff);
return 0;
}
- verts = MEM_callocN(sizeof(float)*3*nverts, "buildRawVertIndicesData verts");
+ verts = MEM_callocN(sizeof(float) * 3 * nverts, "buildRawVertIndicesData verts");
dm->getVertCos(dm, (float(*)[3])verts);
- //flip coordinates
- for (vi=0; vi<nverts; vi++) {
- SWAP(float, verts[3*vi+1], verts[3*vi+2]);
+ /* flip coordinates */
+ for (vi = 0; vi < nverts; vi++) {
+ SWAP(float, verts[3 * vi + 1], verts[3 * vi + 2]);
}
- //calculate number of tris
+ /* calculate number of tris */
nfaces = dm->getNumTessFaces(dm);
faces = dm->getTessFaceArray(dm);
ntris = nfaces;
- for (fi=0; fi<nfaces; fi++) {
- MFace* face = &faces[fi];
+ for (fi = 0; fi < nfaces; fi++) {
+ MFace *face = &faces[fi];
if (face->v4)
ntris++;
}
- //copy and transform to triangles (reorder on the run)
- trisToFacesMap = MEM_callocN(sizeof(int)*ntris, "buildRawVertIndicesData trisToFacesMap");
- tris = MEM_callocN(sizeof(unsigned short)*3*ntris, "buildRawVertIndicesData tris");
+ /* copy and transform to triangles (reorder on the run) */
+ trisToFacesMap = MEM_callocN(sizeof(int) * ntris, "buildRawVertIndicesData trisToFacesMap");
+ tris = MEM_callocN(sizeof(unsigned short) * 3 * ntris, "buildRawVertIndicesData tris");
tri = tris;
triIdx = 0;
- for (fi=0; fi<nfaces; fi++) {
- MFace* face = &faces[fi];
- tri[3*triIdx+0] = (unsigned short) face->v1;
- tri[3*triIdx+1] = (unsigned short) face->v3;
- tri[3*triIdx+2] = (unsigned short) face->v2;
- trisToFacesMap[triIdx++]=fi;
+ for (fi = 0; fi < nfaces; fi++) {
+ MFace *face = &faces[fi];
+ tri[3 * triIdx + 0] = (unsigned short) face->v1;
+ tri[3 * triIdx + 1] = (unsigned short) face->v3;
+ tri[3 * triIdx + 2] = (unsigned short) face->v2;
+ trisToFacesMap[triIdx++] = fi;
if (face->v4) {
- tri[3*triIdx+0] = (unsigned short) face->v1;
- tri[3*triIdx+1] = (unsigned short) face->v4;
- tri[3*triIdx+2] = (unsigned short) face->v3;
- trisToFacesMap[triIdx++]=fi;
+ tri[3 * triIdx + 0] = (unsigned short) face->v1;
+ tri[3 * triIdx + 1] = (unsigned short) face->v4;
+ tri[3 * triIdx + 2] = (unsigned short) face->v3;
+ trisToFacesMap[triIdx++] = fi;
}
}
- //carefully, recast data is just reference to data in derived mesh
- *recastData = (int*)CustomData_get_layer(&dm->polyData, CD_RECAST);
+ /* carefully, recast data is just reference to data in derived mesh */
+ *recastData = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST);
*nverts_r = nverts;
*verts_r = verts;
@@ -170,122 +171,122 @@ int buildRawVertIndicesData(DerivedMesh* dm, int *nverts_r, float **verts_r,
return 1;
}
-int buildPolygonsByDetailedMeshes(const int vertsPerPoly, const int npolys,
- unsigned short* polys, const unsigned short* dmeshes,
- const float* verts, const unsigned short* dtris,
- const int* dtrisToPolysMap)
+int buildPolygonsByDetailedMeshes(const int vertsPerPoly, const int npolys,
+ unsigned short *polys, const unsigned short *dmeshes,
+ const float *verts, const unsigned short *dtris,
+ const int *dtrisToPolysMap)
{
int polyidx;
int capacity = vertsPerPoly;
- unsigned short* newPoly = MEM_callocN(sizeof(unsigned short)*capacity, "buildPolygonsByDetailedMeshes newPoly");
- memset(newPoly, 0xff, sizeof(unsigned short)*capacity);
+ unsigned short *newPoly = MEM_callocN(sizeof(unsigned short) * capacity, "buildPolygonsByDetailedMeshes newPoly");
+ memset(newPoly, 0xff, sizeof(unsigned short) * capacity);
- for (polyidx=0; polyidx<npolys; polyidx++) {
+ for (polyidx = 0; polyidx < npolys; polyidx++) {
size_t i;
int j, k;
int nv = 0;
- //search border
+ /* search border */
int tri, btri = -1;
int edge, bedge = -1;
- int dtrisNum = dmeshes[polyidx*4+3];
- int dtrisBase = dmeshes[polyidx*4+2];
- unsigned char *traversedTris = MEM_callocN(sizeof(unsigned char)*dtrisNum, "buildPolygonsByDetailedMeshes traversedTris");
- unsigned short* adjustedPoly;
+ int dtrisNum = dmeshes[polyidx * 4 + 3];
+ int dtrisBase = dmeshes[polyidx * 4 + 2];
+ unsigned char *traversedTris = MEM_callocN(sizeof(unsigned char) * dtrisNum, "buildPolygonsByDetailedMeshes traversedTris");
+ unsigned short *adjustedPoly;
int adjustedNv;
int allBorderTraversed;
- for (j=0; j<dtrisNum && btri==-1;j++) {
- int curpolytri = dtrisBase+j;
- for (k=0; k<3; k++) {
- unsigned short neighbortri = dtris[curpolytri*3*2+3+k];
- if ( neighbortri==0xffff || dtrisToPolysMap[neighbortri]!=polyidx+1) {
+ for (j = 0; j < dtrisNum && btri == -1; j++) {
+ int curpolytri = dtrisBase + j;
+ for (k = 0; k < 3; k++) {
+ unsigned short neighbortri = dtris[curpolytri * 3 * 2 + 3 + k];
+ if (neighbortri == 0xffff || dtrisToPolysMap[neighbortri] != polyidx + 1) {
btri = curpolytri;
bedge = k;
break;
}
- }
+ }
}
- if (btri==-1 || bedge==-1) {
- //can't find triangle with border edge
+ if (btri == -1 || bedge == -1) {
+ /* can't find triangle with border edge */
MEM_freeN(traversedTris);
MEM_freeN(newPoly);
return 0;
}
- newPoly[nv++] = dtris[btri*3*2+bedge];
+ newPoly[nv++] = dtris[btri * 3 * 2 + bedge];
tri = btri;
- edge = (bedge+1)%3;
- traversedTris[tri-dtrisBase] = 1;
+ edge = (bedge + 1) % 3;
+ traversedTris[tri - dtrisBase] = 1;
while (tri != btri || edge != bedge) {
- int neighbortri = dtris[tri*3*2+3+edge];
- if (neighbortri==0xffff || dtrisToPolysMap[neighbortri]!=polyidx+1) {
- if (nv==capacity) {
- unsigned short* newPolyBig;
+ int neighbortri = dtris[tri * 3 * 2 + 3 + edge];
+ if (neighbortri == 0xffff || dtrisToPolysMap[neighbortri] != polyidx + 1) {
+ if (nv == capacity) {
+ unsigned short *newPolyBig;
capacity += vertsPerPoly;
- newPolyBig = MEM_callocN(sizeof(unsigned short)*capacity, "buildPolygonsByDetailedMeshes newPolyBig");
- memset(newPolyBig, 0xff, sizeof(unsigned short)*capacity);
- memcpy(newPolyBig, newPoly, sizeof(unsigned short)*nv);
+ newPolyBig = MEM_callocN(sizeof(unsigned short) * capacity, "buildPolygonsByDetailedMeshes newPolyBig");
+ memset(newPolyBig, 0xff, sizeof(unsigned short) * capacity);
+ memcpy(newPolyBig, newPoly, sizeof(unsigned short) * nv);
MEM_freeN(newPoly);
- newPoly = newPolyBig;
+ newPoly = newPolyBig;
}
- newPoly[nv++] = dtris[tri*3*2+edge];
- //move to next edge
- edge = (edge+1)%3;
+ newPoly[nv++] = dtris[tri * 3 * 2 + edge];
+ /* move to next edge */
+ edge = (edge + 1) % 3;
}
else {
- //move to next tri
+ /* move to next tri */
int twinedge = -1;
- for (k=0; k<3; k++) {
- if (dtris[neighbortri*3*2+3+k] == tri) {
+ for (k = 0; k < 3; k++) {
+ if (dtris[neighbortri * 3 * 2 + 3 + k] == tri) {
twinedge = k;
break;
}
}
- if (twinedge==-1) {
+ if (twinedge == -1) {
printf("Converting navmesh: Error! Can't find neighbor edge - invalid adjacency info\n");
MEM_freeN(traversedTris);
goto returnLabel;
}
tri = neighbortri;
- edge = (twinedge+1)%3;
- traversedTris[tri-dtrisBase] = 1;
+ edge = (twinedge + 1) % 3;
+ traversedTris[tri - dtrisBase] = 1;
}
}
- adjustedPoly = MEM_callocN(sizeof(unsigned short)*nv, "buildPolygonsByDetailedMeshes adjustedPoly");
+ adjustedPoly = MEM_callocN(sizeof(unsigned short) * nv, "buildPolygonsByDetailedMeshes adjustedPoly");
adjustedNv = 0;
- for (i=0; i<nv; i++) {
- unsigned short prev = newPoly[(nv+i-1)%nv];
+ for (i = 0; i < nv; i++) {
+ unsigned short prev = newPoly[(nv + i - 1) % nv];
unsigned short cur = newPoly[i];
- unsigned short next = newPoly[(i+1)%nv];
- float distSq = distPointToSegmentSq(&verts[3*cur], &verts[3*prev], &verts[3*next]);
+ unsigned short next = newPoly[(i + 1) % nv];
+ float distSq = distPointToSegmentSq(&verts[3 * cur], &verts[3 * prev], &verts[3 * next]);
static const float tolerance = 0.001f;
- if (distSq>tolerance)
+ if (distSq > tolerance)
adjustedPoly[adjustedNv++] = cur;
}
- memcpy(newPoly, adjustedPoly, adjustedNv*sizeof(unsigned short));
+ memcpy(newPoly, adjustedPoly, adjustedNv * sizeof(unsigned short));
MEM_freeN(adjustedPoly);
nv = adjustedNv;
allBorderTraversed = 1;
- for (i=0; i<dtrisNum; i++) {
- if (traversedTris[i]==0) {
- //check whether it has border edges
- int curpolytri = dtrisBase+i;
- for (k=0; k<3; k++) {
- unsigned short neighbortri = dtris[curpolytri*3*2+3+k];
- if ( neighbortri==0xffff || dtrisToPolysMap[neighbortri]!=polyidx+1) {
+ for (i = 0; i < dtrisNum; i++) {
+ if (traversedTris[i] == 0) {
+ /* check whether it has border edges */
+ int curpolytri = dtrisBase + i;
+ for (k = 0; k < 3; k++) {
+ unsigned short neighbortri = dtris[curpolytri * 3 * 2 + 3 + k];
+ if (neighbortri == 0xffff || dtrisToPolysMap[neighbortri] != polyidx + 1) {
allBorderTraversed = 0;
break;
}
}
- }
+ }
}
- if (nv<=vertsPerPoly && allBorderTraversed) {
- for (i=0; i<nv; i++) {
- polys[polyidx*vertsPerPoly*2+i] = newPoly[i];
+ if (nv <= vertsPerPoly && allBorderTraversed) {
+ for (i = 0; i < nv; i++) {
+ polys[polyidx * vertsPerPoly * 2 + i] = newPoly[i];
}
}
@@ -298,21 +299,20 @@ returnLabel:
return 1;
}
-struct SortContext
-{
- const int* recastData;
- const int* trisToFacesMap;
+struct SortContext {
+ const int *recastData;
+ const int *trisToFacesMap;
};
-static int compareByData(void *ctx, const void * a, const void * b)
+static int compareByData(void *ctx, const void *a, const void *b)
{
- return (((struct SortContext *)ctx)->recastData[((struct SortContext *)ctx)->trisToFacesMap[*(int*)a]] -
- ((struct SortContext *)ctx)->recastData[((struct SortContext *)ctx)->trisToFacesMap[*(int*)b]] );
+ return (((struct SortContext *)ctx)->recastData[((struct SortContext *)ctx)->trisToFacesMap[*(int *)a]] -
+ ((struct SortContext *)ctx)->recastData[((struct SortContext *)ctx)->trisToFacesMap[*(int *)b]]);
}
-int buildNavMeshData(const int nverts, const float* verts,
+int buildNavMeshData(const int nverts, const float *verts,
const int ntris, const unsigned short *tris,
- const int* recastData, const int* trisToFacesMap,
+ const int *recastData, const int *trisToFacesMap,
int *ndtris_r, unsigned short **dtris_r,
int *npolys_r, unsigned short **dmeshes_r, unsigned short **polys_r,
int *vertsPerPoly_r, int **dtrisToPolysMap_r, int **dtrisToTrisMap_r)
@@ -333,86 +333,86 @@ int buildNavMeshData(const int nverts, const float* verts,
return 0;
}
- trisMapping = MEM_callocN(sizeof(int)*ntris, "buildNavMeshData trisMapping");
+ trisMapping = MEM_callocN(sizeof(int) * ntris, "buildNavMeshData trisMapping");
- //sort the triangles by polygon idx
- for (i=0; i<ntris; i++)
- trisMapping[i]=i;
+ /* sort the triangles by polygon idx */
+ for (i = 0; i < ntris; i++)
+ trisMapping[i] = i;
context.recastData = recastData;
context.trisToFacesMap = trisToFacesMap;
recast_qsort(trisMapping, ntris, sizeof(int), &context, compareByData);
- //search first valid triangle - triangle of convex polygon
+ /* search first valid triangle - triangle of convex polygon */
validTriStart = -1;
- for (i=0; i< ntris; i++) {
- if (recastData[trisToFacesMap[trisMapping[i]]]>0) {
+ for (i = 0; i < ntris; i++) {
+ if (recastData[trisToFacesMap[trisMapping[i]]] > 0) {
validTriStart = i;
break;
}
}
- if (validTriStart<0) {
+ if (validTriStart < 0) {
printf("Converting navmesh: Error! No valid polygons in mesh\n");
MEM_freeN(trisMapping);
return 0;
}
- ndtris = ntris-validTriStart;
- //fill dtris to faces mapping
- dtrisToTrisMap = MEM_callocN(sizeof(int)*ndtris, "buildNavMeshData dtrisToTrisMap");
- memcpy(dtrisToTrisMap, &trisMapping[validTriStart], ndtris*sizeof(int));
+ ndtris = ntris - validTriStart;
+ /* fill dtris to faces mapping */
+ dtrisToTrisMap = MEM_callocN(sizeof(int) * ndtris, "buildNavMeshData dtrisToTrisMap");
+ memcpy(dtrisToTrisMap, &trisMapping[validTriStart], ndtris * sizeof(int));
MEM_freeN(trisMapping);
- //create detailed mesh triangles - copy only valid triangles
- //and reserve memory for adjacency info
- dtris = MEM_callocN(sizeof(unsigned short)*3*2*ndtris, "buildNavMeshData dtris");
- memset(dtris, 0xffff, sizeof(unsigned short)*3*2*ndtris);
- for (i=0; i<ndtris; i++) {
- memcpy(dtris+3*2*i, tris+3*dtrisToTrisMap[i], sizeof(unsigned short)*3);
+ /* create detailed mesh triangles - copy only valid triangles
+ * and reserve memory for adjacency info */
+ dtris = MEM_callocN(sizeof(unsigned short) * 3 * 2 * ndtris, "buildNavMeshData dtris");
+ memset(dtris, 0xffff, sizeof(unsigned short) * 3 * 2 * ndtris);
+ for (i = 0; i < ndtris; i++) {
+ memcpy(dtris + 3 * 2 * i, tris + 3 * dtrisToTrisMap[i], sizeof(unsigned short) * 3);
}
- //create new recast data corresponded to dtris and renumber for continuous indices
+ /* create new recast data corresponded to dtris and renumber for continuous indices */
prevPolyIdx = -1;
newPolyIdx = 0;
- dtrisToPolysMap = MEM_callocN(sizeof(int)*ndtris, "buildNavMeshData dtrisToPolysMap");
- for (i=0; i<ndtris; i++) {
+ dtrisToPolysMap = MEM_callocN(sizeof(int) * ndtris, "buildNavMeshData dtrisToPolysMap");
+ for (i = 0; i < ndtris; i++) {
curPolyIdx = recastData[trisToFacesMap[dtrisToTrisMap[i]]];
- if (curPolyIdx!=prevPolyIdx) {
+ if (curPolyIdx != prevPolyIdx) {
newPolyIdx++;
- prevPolyIdx=curPolyIdx;
+ prevPolyIdx = curPolyIdx;
}
dtrisToPolysMap[i] = newPolyIdx;
}
- //build adjacency info for detailed mesh triangles
+ /* build adjacency info for detailed mesh triangles */
recast_buildMeshAdjacency(dtris, ndtris, nverts, 3);
- //create detailed mesh description for each navigation polygon
- npolys = dtrisToPolysMap[ndtris-1];
- dmeshes = MEM_callocN(sizeof(unsigned short)*npolys*4, "buildNavMeshData dmeshes");
- memset(dmeshes, 0, npolys*4*sizeof(unsigned short));
+ /* create detailed mesh description for each navigation polygon */
+ npolys = dtrisToPolysMap[ndtris - 1];
+ dmeshes = MEM_callocN(sizeof(unsigned short) * npolys * 4, "buildNavMeshData dmeshes");
+ memset(dmeshes, 0, npolys * 4 * sizeof(unsigned short));
dmesh = NULL;
prevpolyidx = 0;
- for (i=0; i<ndtris; i++) {
+ for (i = 0; i < ndtris; i++) {
int curpolyidx = dtrisToPolysMap[i];
- if (curpolyidx!=prevpolyidx) {
- if (curpolyidx!=prevpolyidx+1) {
+ if (curpolyidx != prevpolyidx) {
+ if (curpolyidx != prevpolyidx + 1) {
printf("Converting navmesh: Error! Wrong order of detailed mesh faces\n");
return 0;
}
- dmesh = dmesh==NULL ? dmeshes : dmesh+4;
- dmesh[2] = (unsigned short)i; //tbase
- dmesh[3] = 0; //tnum
+ dmesh = dmesh == NULL ? dmeshes : dmesh + 4;
+ dmesh[2] = (unsigned short)i; /* tbase */
+ dmesh[3] = 0; /* tnum */
prevpolyidx = curpolyidx;
}
dmesh[3]++;
}
- //create navigation polygons
+ /* create navigation polygons */
vertsPerPoly = 6;
- polys = MEM_callocN(sizeof(unsigned short)*npolys*vertsPerPoly*2, "buildNavMeshData polys");
- memset(polys, 0xff, sizeof(unsigned short)*vertsPerPoly*2*npolys);
+ polys = MEM_callocN(sizeof(unsigned short) * npolys * vertsPerPoly * 2, "buildNavMeshData polys");
+ memset(polys, 0xff, sizeof(unsigned short) * vertsPerPoly * 2 * npolys);
buildPolygonsByDetailedMeshes(vertsPerPoly, npolys, polys, dmeshes, verts, dtris, dtrisToPolysMap);
@@ -429,16 +429,16 @@ int buildNavMeshData(const int nverts, const float* verts,
}
-int buildNavMeshDataByDerivedMesh(DerivedMesh *dm, int *vertsPerPoly,
- int *nverts, float **verts,
- int *ndtris, unsigned short **dtris,
- int *npolys, unsigned short **dmeshes,
- unsigned short **polys, int **dtrisToPolysMap,
- int **dtrisToTrisMap, int **trisToFacesMap)
+int buildNavMeshDataByDerivedMesh(DerivedMesh *dm, int *vertsPerPoly,
+ int *nverts, float **verts,
+ int *ndtris, unsigned short **dtris,
+ int *npolys, unsigned short **dmeshes,
+ unsigned short **polys, int **dtrisToPolysMap,
+ int **dtrisToTrisMap, int **trisToFacesMap)
{
int res = 1;
- int ntris = 0, *recastData=NULL;
- unsigned short *tris=NULL;
+ int ntris = 0, *recastData = NULL;
+ unsigned short *tris = NULL;
res = buildRawVertIndicesData(dm, nverts, verts, &ntris, &tris, trisToFacesMap, &recastData);
if (!res) {
@@ -447,8 +447,8 @@ int buildNavMeshDataByDerivedMesh(DerivedMesh *dm, int *vertsPerPoly,
}
res = buildNavMeshData(*nverts, *verts, ntris, tris, recastData, *trisToFacesMap,
- ndtris, dtris, npolys, dmeshes, polys, vertsPerPoly,
- dtrisToPolysMap, dtrisToTrisMap);
+ ndtris, dtris, npolys, dmeshes, polys, vertsPerPoly,
+ dtrisToPolysMap, dtrisToTrisMap);
if (!res) {
printf("Converting navmesh: Error! Can't get vertices and indices from mesh\n");
goto exit;
@@ -461,11 +461,11 @@ exit:
return res;
}
-int polyFindVertex(const unsigned short* p, const int vertsPerPoly, unsigned short vertexIdx)
+int polyFindVertex(const unsigned short *p, const int vertsPerPoly, unsigned short vertexIdx)
{
int i, res = -1;
- for (i=0; i<vertsPerPoly; i++) {
- if (p[i]==0xffff)
+ for (i = 0; i < vertsPerPoly; i++) {
+ if (p[i] == 0xffff)
break;
if (p[i] == vertexIdx) {
res = i;
diff --git a/source/blender/blenkernel/intern/nla.c b/source/blender/blenkernel/intern/nla.c
index 9590160c8f3..6f585198524 100644
--- a/source/blender/blenkernel/intern/nla.c
+++ b/source/blender/blenkernel/intern/nla.c
@@ -423,7 +423,7 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short
return strip->actstart;
}
else {
- /* - the 'fmod(..., actlength*scale)' is needed to get the repeats working
+ /* - the 'fmod(..., actlength * scale)' is needed to get the repeats working
* - the '/ scale' is needed to ensure that scaling influences the timing within the repeat
*/
return strip->actend - fmodf(cframe - strip->start, actlength * scale) / scale;
@@ -446,7 +446,7 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short
return strip->actend;
}
else {
- /* - the 'fmod(..., actlength*scale)' is needed to get the repeats working
+ /* - the 'fmod(..., actlength * scale)' is needed to get the repeats working
* - the '/ scale' is needed to ensure that scaling influences the timing within the repeat
*/
return strip->actstart + fmodf(cframe - strip->start, actlength * scale) / scale;
@@ -496,7 +496,7 @@ float nlastrip_get_frame(NlaStrip *strip, float cframe, short mode)
case NLASTRIP_TYPE_CLIP: /* action-clip (default) */
default:
return nlastrip_get_frame_actionclip(strip, cframe, mode);
- }
+ }
}
@@ -1162,7 +1162,7 @@ static short nlastrip_is_first(AnimData *adt, NlaStrip *strip)
if (ns->start < strip->start)
return 0;
}
- }
+ }
/* should be first now */
return 1;
@@ -1491,7 +1491,7 @@ void BKE_nla_action_pushdown(AnimData *adt)
/* add a new NLA strip to the track, which references the active action */
strip = add_nlastrip_to_stack(adt, adt->action);
- /* do other necessary work on strip */
+ /* do other necessary work on strip */
if (strip) {
/* clear reference to action now that we've pushed it onto the stack */
id_us_min(&adt->action->id);
@@ -1545,7 +1545,7 @@ short BKE_nla_tweakmode_enter(AnimData *adt)
/* now try to find active strip */
activeStrip = BKE_nlastrip_find_active(nlt);
break;
- }
+ }
}
/* There are situations where we may have multiple strips selected and we want to enter tweakmode on all
@@ -1563,7 +1563,7 @@ short BKE_nla_tweakmode_enter(AnimData *adt)
activeStrip = BKE_nlastrip_find_active(nlt);
break;
}
- }
+ }
}
if ((activeTrack) && (activeStrip == NULL)) {
/* no active strip in active or last selected track; compromise for first selected (assuming only single)... */
diff --git a/source/blender/blenkernel/intern/node.c b/source/blender/blenkernel/intern/node.c
index ade418e409f..153eb5271c5 100644
--- a/source/blender/blenkernel/intern/node.c
+++ b/source/blender/blenkernel/intern/node.c
@@ -147,6 +147,7 @@ static bNodeSocket *make_socket(bNodeTree *UNUSED(ntree), int in_out, const char
sock->limit = (in_out == SOCK_IN ? 1 : 0xFFF);
sock->type = type;
sock->storage = NULL;
+ sock->flag |= SOCK_COLLAPSED;
sock->default_value = node_socket_make_default_value(type);
node_socket_init_default_value(type, sock->default_value);
@@ -326,10 +327,13 @@ bNode *nodeAddNode(bNodeTree *ntree, struct bNodeTemplate *ntemp)
ntype->initfunc(ntree, node, ntemp);
/* initialize the node name with the node label.
- * note: do this after the initfunc so nodes get
- * their data set which may be used in naming
+ * note: do this after the initfunc so nodes get their data set which may be used in naming
* (node groups for example) */
- BLI_strncpy(node->name, nodeLabel(node), NODE_MAXSTR);
+ /* XXX Do not use nodeLabel() here, it returns translated content, which should *only* be used
+ * in UI, *never* in data...
+ * This solution may be a bit rougher than nodeLabel()'s returned string, but it's simpler
+ * than adding a "no translate" flag to this func (and labelfunc() as well). */
+ BLI_strncpy(node->name, node->typeinfo->name, NODE_MAXSTR);
nodeUniqueName(ntree, node);
ntree->update |= NTREE_UPDATE_NODES;
@@ -343,6 +347,7 @@ bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node)
{
bNode *nnode = MEM_callocN(sizeof(bNode), "dupli node");
bNodeSocket *sock, *oldsock;
+ bNodeLink *link, *oldlink;
*nnode = *node;
/* can be called for nodes outside a node tree (e.g. clipboard) */
@@ -382,6 +387,15 @@ bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node)
sock->cache = NULL;
}
+ BLI_duplicatelist(&nnode->internal_links, &node->internal_links);
+ oldlink = node->internal_links.first;
+ for (link = nnode->internal_links.first; link; link = link->next, oldlink = oldlink->next) {
+ link->fromnode = nnode;
+ link->tonode = nnode;
+ link->fromsock = link->fromsock->new_sock;
+ link->tosock = link->tosock->new_sock;
+ }
+
/* don't increase node->id users, freenode doesn't decrement either */
if (node->typeinfo->copystoragefunc)
@@ -389,7 +403,17 @@ bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node)
node->new_node = nnode;
nnode->new_node = NULL;
- nnode->preview = NULL;
+
+ /* only shader nodes get pleasant preview updating this way, compo uses own system */
+ if (node->preview) {
+ if (ntree->type == NTREE_SHADER) {
+ nnode->preview = MEM_dupallocN(node->preview);
+ if (node->preview->rect)
+ nnode->preview->rect = MEM_dupallocN(node->preview->rect);
+ }
+ else
+ nnode->preview = NULL;
+ }
if (ntree)
ntree->update |= NTREE_UPDATE_NODES;
@@ -520,15 +544,12 @@ void nodeRemSocketLinks(bNodeTree *ntree, bNodeSocket *sock)
void nodeInternalRelink(bNodeTree *ntree, bNode *node)
{
bNodeLink *link, *link_next;
- ListBase intlinks;
- if (!node->typeinfo->internal_connect)
+ if (node->internal_links.first == NULL)
return;
- intlinks = node->typeinfo->internal_connect(ntree, node);
-
/* store link pointers in output sockets, for efficient lookup */
- for (link = intlinks.first; link; link = link->next)
+ for (link = node->internal_links.first; link; link = link->next)
link->tosock->link = link;
/* redirect downstream links */
@@ -562,8 +583,6 @@ void nodeInternalRelink(bNodeTree *ntree, bNode *node)
if (link->tonode == node)
nodeRemLink(ntree, link);
}
-
- BLI_freelistN(&intlinks);
}
void nodeToView(bNode *node, float x, float y, float *rx, float *ry)
@@ -710,7 +729,7 @@ static bNodeTree *ntreeCopyTree_internal(bNodeTree *ntree, const short do_id_use
}
node->new_node = NULL;
- /* nnode= */ nodeCopyNode(newtree, node); /* sets node->new */
+ /* nnode = */ nodeCopyNode(newtree, node); /* sets node->new */
/* make sure we don't copy new nodes again! */
if (node == last)
@@ -815,7 +834,7 @@ void nodeFreePreview(bNode *node)
MEM_freeN(node->preview->rect);
MEM_freeN(node->preview);
node->preview = NULL;
- }
+ }
}
static void node_init_preview(bNode *node, int xsize, int ysize)
@@ -858,7 +877,7 @@ void ntreeInitPreview(bNodeTree *ntree, int xsize, int ysize)
node_init_preview(node, xsize, ysize);
if (node->type == NODE_GROUP && (node->flag & NODE_GROUP_EDIT))
ntreeInitPreview((bNodeTree *)node->id, xsize, ysize);
- }
+ }
}
static void nodeClearPreview(bNode *node)
@@ -880,13 +899,13 @@ void ntreeClearPreview(bNodeTree *ntree)
nodeClearPreview(node);
if (node->type == NODE_GROUP && (node->flag & NODE_GROUP_EDIT))
ntreeClearPreview((bNodeTree *)node->id);
- }
+ }
}
/* hack warning! this function is only used for shader previews, and
* since it gets called multiple times per pixel for Ztransp we only
* add the color once. Preview gets cleared before it starts render though */
-void nodeAddToPreview(bNode *node, float col[4], int x, int y, int do_manage)
+void nodeAddToPreview(bNode *node, const float col[4], int x, int y, int do_manage)
{
bNodePreview *preview = node->preview;
if (preview) {
@@ -985,6 +1004,8 @@ void nodeFreeNode(bNodeTree *ntree, bNode *node)
MEM_freeN(sock);
}
+ BLI_freelistN(&node->internal_links);
+
nodeFreePreview(node);
MEM_freeN(node);
@@ -996,6 +1017,7 @@ void nodeFreeNode(bNodeTree *ntree, bNode *node)
/* do not free ntree itself here, BKE_libblock_free calls this function too */
void ntreeFreeTree_ex(bNodeTree *ntree, const short do_id_user)
{
+ bNodeTree *tntree;
bNode *node, *next;
bNodeSocket *sock;
@@ -1030,9 +1052,18 @@ void ntreeFreeTree_ex(bNodeTree *ntree, const short do_id_user)
next = node->next;
/* ntreeUserIncrefID inline */
+
+ /* XXX, this is correct, however when freeing the entire database
+ * this ends up accessing freed data which isn't properly unlinking
+ * its self from scene nodes, SO - for now prefer invalid usercounts
+ * on free rather then bad memory access - Campbell */
+#if 0
if (do_id_user) {
id_us_min(node->id);
}
+#else
+ (void)do_id_user;
+#endif
nodeFreeNode(ntree, node);
}
@@ -1043,6 +1074,14 @@ void ntreeFreeTree_ex(bNodeTree *ntree, const short do_id_user)
for (sock = ntree->outputs.first; sock; sock = sock->next)
node_socket_free_default_value(sock->type, sock->default_value);
BLI_freelistN(&ntree->outputs);
+
+ /* if ntree is not part of library, free the libblock data explicitly */
+ for (tntree = G.main->nodetree.first; tntree; tntree = tntree->id.next)
+ if (tntree == ntree)
+ break;
+ if (tntree == NULL) {
+ BKE_libblock_free_data(&ntree->id);
+ }
}
/* same as ntreeFreeTree_ex but always manage users */
void ntreeFreeTree(bNodeTree *ntree)
@@ -1545,11 +1584,11 @@ int BKE_node_clipboard_validate(void)
/* lists must be aligned */
BLI_assert(BLI_countlist(&node_clipboard.nodes) ==
- BLI_countlist(&node_clipboard.nodes_extra_info));
+ BLI_countlist(&node_clipboard.nodes_extra_info));
for (node = node_clipboard.nodes.first, node_info = node_clipboard.nodes_extra_info.first;
- node;
- node = node->next, node_info = node_info->next)
+ node;
+ node = node->next, node_info = node_info->next)
{
/* validate the node against the stored node info */
@@ -1629,21 +1668,21 @@ int BKE_node_clipboard_get_type(void)
/* ************** dependency stuff *********** */
/* node is guaranteed to be not checked before */
-static int node_get_deplist_recurs(bNode *node, bNode ***nsort)
+static int node_get_deplist_recurs(bNodeTree *ntree, bNode *node, bNode ***nsort)
{
bNode *fromnode;
- bNodeSocket *sock;
+ bNodeLink *link;
int level = 0xFFF;
node->done = TRUE;
/* check linked nodes */
- for (sock = node->inputs.first; sock; sock = sock->next) {
- if (sock->link) {
- fromnode = sock->link->fromnode;
+ for (link = ntree->links.first; link; link = link->next) {
+ if (link->tonode == node) {
+ fromnode = link->fromnode;
if (fromnode) {
if (fromnode->done == 0)
- fromnode->level = node_get_deplist_recurs(fromnode, nsort);
+ fromnode->level = node_get_deplist_recurs(ntree, fromnode, nsort);
if (fromnode->level <= level)
level = fromnode->level - 1;
}
@@ -1653,7 +1692,7 @@ static int node_get_deplist_recurs(bNode *node, bNode ***nsort)
/* check parent node */
if (node->parent) {
if (node->parent->done == 0)
- node->parent->level = node_get_deplist_recurs(node->parent, nsort);
+ node->parent->level = node_get_deplist_recurs(ntree, node->parent, nsort);
if (node->parent->level <= level)
level = node->parent->level - 1;
}
@@ -1687,7 +1726,7 @@ void ntreeGetDependencyList(struct bNodeTree *ntree, struct bNode ***deplist, in
/* recursive check */
for (node = ntree->nodes.first; node; node = node->next) {
if (node->done == 0) {
- node->level = node_get_deplist_recurs(node, &nsort);
+ node->level = node_get_deplist_recurs(ntree, node, &nsort);
}
}
}
@@ -1705,7 +1744,7 @@ static void ntree_update_node_level(bNodeTree *ntree)
/* recursive check */
for (node = ntree->nodes.first; node; node = node->next) {
if (node->done == 0) {
- node->level = node_get_deplist_recurs(node, NULL);
+ node->level = node_get_deplist_recurs(ntree, node, NULL);
}
}
}
@@ -1804,6 +1843,8 @@ void ntreeUpdateTree(bNodeTree *ntree)
ntreetype->update_node(ntree, node);
else if (node->typeinfo->updatefunc)
node->typeinfo->updatefunc(ntree, node);
+
+ nodeUpdateInternalLinks(ntree, node);
}
}
@@ -1841,6 +1882,9 @@ void nodeUpdate(bNodeTree *ntree, bNode *node)
ntreetype->update_node(ntree, node);
else if (node->typeinfo->updatefunc)
node->typeinfo->updatefunc(ntree, node);
+
+ nodeUpdateInternalLinks(ntree, node);
+
/* clear update flag */
node->update = 0;
}
@@ -1880,9 +1924,21 @@ int nodeUpdateID(bNodeTree *ntree, ID *id)
}
}
+ for (node = ntree->nodes.first; node; node = node->next) {
+ nodeUpdateInternalLinks(ntree, node);
+ }
+
return change;
}
+void nodeUpdateInternalLinks(bNodeTree *ntree, bNode *node)
+{
+ BLI_freelistN(&node->internal_links);
+
+ if (node->typeinfo && node->typeinfo->update_internal_links)
+ node->typeinfo->update_internal_links(ntree, node);
+}
+
/* ************* node type access ********** */
@@ -1955,7 +2011,7 @@ void node_type_base(bNodeTreeType *ttype, bNodeType *ntype, int type, const char
/* Default muting stuff. */
if (ttype)
- ntype->internal_connect = ttype->internal_connect;
+ ntype->update_internal_links = ttype->update_internal_links;
/* default size values */
ntype->width = 140;
@@ -2051,9 +2107,9 @@ void node_type_exec_new(struct bNodeType *ntype,
ntype->newexecfunc = newexecfunc;
}
-void node_type_internal_connect(bNodeType *ntype, ListBase (*internal_connect)(bNodeTree *, bNode *))
+void node_type_internal_links(bNodeType *ntype, void (*update_internal_links)(bNodeTree *, bNode *))
{
- ntype->internal_connect = internal_connect;
+ ntype->update_internal_links = update_internal_links;
}
void node_type_gpu(struct bNodeType *ntype, int (*gpufunc)(struct GPUMaterial *mat, struct bNode *node, struct GPUNodeStack *in, struct GPUNodeStack *out))
@@ -2186,6 +2242,7 @@ static void registerCompositNodes(bNodeTreeType *ttype)
register_node_type_cmp_bokehimage(ttype);
register_node_type_cmp_bokehblur(ttype);
register_node_type_cmp_switch(ttype);
+ register_node_type_cmp_pixelate(ttype);
register_node_type_cmp_mask(ttype);
register_node_type_cmp_trackpos(ttype);
@@ -2234,8 +2291,11 @@ static void registerShaderNodes(bNodeTreeType *ttype)
register_node_type_sh_layer_weight(ttype);
register_node_type_sh_tex_coord(ttype);
register_node_type_sh_particle_info(ttype);
+ register_node_type_sh_bump(ttype);
+ register_node_type_sh_script(ttype);
register_node_type_sh_background(ttype);
+ register_node_type_sh_bsdf_anisotropic(ttype);
register_node_type_sh_bsdf_diffuse(ttype);
register_node_type_sh_bsdf_glossy(ttype);
register_node_type_sh_bsdf_glass(ttype);
diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c
index 5ba56a85c72..0611e84bdf3 100644
--- a/source/blender/blenkernel/intern/object.c
+++ b/source/blender/blenkernel/intern/object.c
@@ -300,11 +300,11 @@ void BKE_object_free(Object *ob)
BKE_object_free_display(ob);
- /* disconnect specific data */
+ /* disconnect specific data, but not for lib data (might be indirect data, can get relinked) */
if (ob->data) {
ID *id = ob->data;
id->us--;
- if (id->us == 0) {
+ if (id->us == 0 && id->lib == NULL) {
switch (ob->type) {
case OB_MESH:
BKE_mesh_unlink((Mesh *)id);
@@ -340,7 +340,7 @@ void BKE_object_free(Object *ob)
BKE_pose_free(ob->pose);
if (ob->mpath)
animviz_free_motionpath(ob->mpath);
- free_properties(&ob->prop);
+ BKE_bproperty_free_list(&ob->prop);
BKE_object_free_modifiers(ob);
free_sensors(&ob->sensors);
@@ -454,7 +454,7 @@ void BKE_object_unlink(Object *ob)
if (pchan->custom == ob)
pchan->custom = NULL;
}
- }
+ }
else if (ELEM(OB_MBALL, ob->type, obt->type)) {
if (BKE_mball_is_basis_for(obt, ob))
obt->recalc |= OB_RECALC_DATA;
@@ -689,8 +689,8 @@ void BKE_object_unlink(Object *ob)
if (so->treestore) {
TreeStoreElem *tselem = so->treestore->data;
- int a;
- for (a = 0; a < so->treestore->usedelem; a++, tselem++) {
+ int i;
+ for (i = 0; i < so->treestore->usedelem; i++, tselem++) {
if (tselem->id == (ID *)ob) tselem->id = NULL;
}
}
@@ -854,7 +854,9 @@ Object *BKE_object_add_only_object(int type, const char *name)
ob->step_height = 0.15f;
ob->jump_speed = 10.0f;
ob->fall_speed = 55.0f;
-
+ ob->col_group = 0x01;
+ ob->col_mask = 0xff;
+
/* NT fluid sim defaults */
ob->fluidsimSettings = NULL;
@@ -889,23 +891,44 @@ Object *BKE_object_add(struct Scene *scene, int type)
return ob;
}
-SoftBody *copy_softbody(SoftBody *sb)
+SoftBody *copy_softbody(SoftBody *sb, int copy_caches)
{
SoftBody *sbn;
if (sb == NULL) return(NULL);
sbn = MEM_dupallocN(sb);
- sbn->totspring = sbn->totpoint = 0;
- sbn->bpoint = NULL;
- sbn->bspring = NULL;
+
+ if (copy_caches == FALSE) {
+ sbn->totspring = sbn->totpoint = 0;
+ sbn->bpoint = NULL;
+ sbn->bspring = NULL;
+ }
+ else {
+ sbn->totspring = sb->totspring;
+ sbn->totpoint = sb->totpoint;
+
+ if (sbn->bpoint) {
+ int i;
+
+ sbn->bpoint = MEM_dupallocN(sbn->bpoint);
+
+ for (i = 0; i < sbn->totpoint; i++) {
+ if (sbn->bpoint[i].springs)
+ sbn->bpoint[i].springs = MEM_dupallocN(sbn->bpoint[i].springs);
+ }
+ }
+
+ if (sb->bspring)
+ sbn->bspring = MEM_dupallocN(sb->bspring);
+ }
sbn->keys = NULL;
sbn->totkey = sbn->totpointkey = 0;
sbn->scratch = NULL;
- sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches);
+ sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, copy_caches);
if (sb->effector_weights)
sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
@@ -978,7 +1001,7 @@ static ParticleSystem *copy_particlesystem(ParticleSystem *psys)
psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
psysn->renderdata = NULL;
- psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches);
+ psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, FALSE);
/* XXX - from reading existing code this seems correct but intended usage of
* pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
@@ -1039,7 +1062,7 @@ void BKE_object_copy_particlesystems(Object *obn, Object *ob)
void BKE_object_copy_softbody(Object *obn, Object *ob)
{
if (ob->soft)
- obn->soft = copy_softbody(ob->soft);
+ obn->soft = copy_softbody(ob->soft, FALSE);
}
static void copy_object_pose(Object *obn, Object *ob)
@@ -1079,12 +1102,12 @@ static void copy_object_pose(Object *obn, Object *ob)
}
}
-static int object_pose_context(Object *ob)
+int BKE_object_pose_context_check(Object *ob)
{
- if ( (ob) &&
- (ob->type == OB_ARMATURE) &&
- (ob->pose) &&
- (ob->mode & OB_MODE_POSE))
+ if ((ob) &&
+ (ob->type == OB_ARMATURE) &&
+ (ob->pose) &&
+ (ob->mode & OB_MODE_POSE))
{
return 1;
}
@@ -1098,12 +1121,12 @@ Object *BKE_object_pose_armature_get(Object *ob)
if (ob == NULL)
return NULL;
- if (object_pose_context(ob))
+ if (BKE_object_pose_context_check(ob))
return ob;
ob = modifiers_isDeformedByArmature(ob);
- if (object_pose_context(ob))
+ if (BKE_object_pose_context_check(ob))
return ob;
return NULL;
@@ -1120,7 +1143,7 @@ void BKE_object_transform_copy(Object *ob_tar, const Object *ob_src)
copy_v3_v3(ob_tar->size, ob_src->size);
}
-Object *BKE_object_copy(Object *ob)
+static Object *object_copy_do(Object *ob, int copy_caches)
{
Object *obn;
ModifierData *md;
@@ -1147,7 +1170,7 @@ Object *BKE_object_copy(Object *ob)
}
obn->prop.first = obn->prop.last = NULL;
- copy_properties(&obn->prop, &ob->prop);
+ BKE_bproperty_copy_list(&obn->prop, &ob->prop);
copy_sensors(&obn->sensors, &ob->sensors);
copy_controllers(&obn->controllers, &ob->controllers);
@@ -1181,7 +1204,7 @@ Object *BKE_object_copy(Object *ob)
if (obn->pd->rng)
obn->pd->rng = MEM_dupallocN(ob->pd->rng);
}
- obn->soft = copy_softbody(ob->soft);
+ obn->soft = copy_softbody(ob->soft, copy_caches);
obn->bsoft = copy_bulletsoftbody(ob->bsoft);
BKE_object_copy_particlesystems(obn, ob);
@@ -1197,6 +1220,18 @@ Object *BKE_object_copy(Object *ob)
return obn;
}
+/* copy objects, will re-initialize cached simulation data */
+Object *BKE_object_copy(Object *ob)
+{
+ return object_copy_do(ob, FALSE);
+}
+
+/* copy objects, will duplicate cached simulation data */
+Object *BKE_object_copy_with_caches(Object *ob)
+{
+ return object_copy_do(ob, TRUE);
+}
+
static void extern_local_object(Object *ob)
{
ParticleSystem *psys;
@@ -1748,7 +1783,7 @@ static void ob_parbone(Object *ob, Object *par, float mat[][4])
/* Make sure the bone is still valid */
pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr);
- if (!pchan) {
+ if (!pchan || !pchan->bone) {
printf("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name + 2, ob->parsubstr);
unit_m4(mat);
return;
@@ -1766,7 +1801,6 @@ static void ob_parbone(Object *ob, Object *par, float mat[][4])
static void give_parvert(Object *par, int nr, float vec[3])
{
BMEditMesh *em;
- int a, count;
zero_v3(vec);
@@ -1795,18 +1829,28 @@ static void give_parvert(Object *par, int nr, float vec[3])
dm = (em) ? em->derivedFinal : par->derivedFinal;
if (dm) {
- MVert *mvert = dm->getVertArray(dm);
- int *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
- int i, vindex, numVerts = dm->getNumVerts(dm);
-
- /* get the average of all verts with (original index == nr) */
- count = 0;
- for (i = 0; i < numVerts; i++) {
- vindex = (index) ? index[i] : i;
-
- if (vindex == nr) {
- add_v3_v3(vec, mvert[i].co);
- count++;
+ int count = 0;
+ int numVerts = dm->getNumVerts(dm);
+
+ if (nr < numVerts) {
+ MVert *mvert = dm->getVertArray(dm);
+ int *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
+ int i;
+
+ /* get the average of all verts with (original index == nr) */
+ if (index) {
+ for (i = 0; i < numVerts; i++) {
+ if (index[i] == nr) {
+ add_v3_v3(vec, mvert[i].co);
+ count++;
+ }
+ }
+ }
+ else {
+ if (nr < numVerts) {
+ add_v3_v3(vec, mvert[nr].co);
+ count++;
+ }
}
}
@@ -1828,71 +1872,31 @@ static void give_parvert(Object *par, int nr, float vec[3])
}
}
else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
- Nurb *nu;
- Curve *cu;
- BPoint *bp;
- BezTriple *bezt;
- int found = 0;
- ListBase *nurbs;
-
- cu = par->data;
- nurbs = BKE_curve_nurbs_get(cu);
- nu = nurbs->first;
-
- count = 0;
- while (nu && !found) {
- if (nu->type == CU_BEZIER) {
- bezt = nu->bezt;
- a = nu->pntsu;
- while (a--) {
- if (count == nr) {
- found = 1;
- copy_v3_v3(vec, bezt->vec[1]);
- break;
- }
- count++;
- bezt++;
- }
- }
- else {
- bp = nu->bp;
- a = nu->pntsu * nu->pntsv;
- while (a--) {
- if (count == nr) {
- found = 1;
- copy_v3_v3(vec, bp->vec);
- break;
- }
- count++;
- bp++;
- }
- }
- nu = nu->next;
- }
+ Curve *cu = par->data;
+ ListBase *nurb = BKE_curve_nurbs_get(cu);;
+ BKE_nurbList_index_get_co(nurb, nr, vec);
}
else if (par->type == OB_LATTICE) {
- Lattice *latt = par->data;
- BPoint *bp;
- DispList *dl = BKE_displist_find(&par->disp, DL_VERTS);
- float *co = dl ? dl->verts : NULL;
-
+ Lattice *latt = par->data;
+ DispList *dl = BKE_displist_find(&par->disp, DL_VERTS);
+ float (*co)[3] = dl ? (float (*)[3])dl->verts : NULL;
+ int tot;
+
if (latt->editlatt) latt = latt->editlatt->latt;
-
- a = latt->pntsu * latt->pntsv * latt->pntsw;
- count = 0;
- bp = latt->def;
- while (a--) {
- if (count == nr) {
- if (co)
- copy_v3_v3(vec, co);
- else
- copy_v3_v3(vec, bp->vec);
- break;
+
+ tot = latt->pntsu * latt->pntsv * latt->pntsw;
+
+ /* ensure dl is correct size */
+ BLI_assert(dl == NULL || dl->nr == tot);
+
+ if (nr < tot) {
+ if (co) {
+ copy_v3_v3(vec, co[nr]);
+ }
+ else {
+ copy_v3_v3(vec, latt->def[nr].vec);
}
- count++;
- if (co) co += 3;
- else bp++;
}
}
}
@@ -2259,7 +2263,7 @@ void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const short u
Curve *cu = ob->data;
/* Use the object bounding box so that modifier output
- gets taken into account */
+ * gets taken into account */
if (ob->bb)
bb = *(ob->bb);
else {
@@ -2298,11 +2302,9 @@ void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const short u
bPoseChannel *pchan;
for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
-
- if ((use_hidden == FALSE) && (PBONE_VISIBLE(arm, pchan->bone) == FALSE)) {
- /* pass */
- }
- else {
+ /* XXX pchan->bone may be NULL for duplicated bones, see duplicateEditBoneObjects() comment
+ * (editarmature.c:2592)... Skip in this case too! */
+ if (pchan->bone && !((use_hidden == FALSE) && (PBONE_VISIBLE(arm, pchan->bone) == FALSE))) {
mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
minmax_v3v3_v3(min_r, max_r, vec);
mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
@@ -2360,7 +2362,7 @@ int BKE_object_minmax_dupli(Scene *scene, Object *ob, float r_min[3], float r_ma
ListBase *lb;
DupliObject *dob;
- lb = object_duplilist(scene, ob);
+ lb = object_duplilist(scene, ob, FALSE);
for (dob = lb->first; dob; dob = dob->next) {
if ((use_hidden == FALSE) && (dob->no_draw != 0)) {
/* pass */
@@ -2437,7 +2439,7 @@ void BKE_scene_foreach_display_point(
ListBase *lb;
DupliObject *dob;
- lb = object_duplilist(scene, ob);
+ lb = object_duplilist(scene, ob, FALSE);
for (dob = lb->first; dob; dob = dob->next) {
if (dob->no_draw == 0) {
BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
@@ -2571,9 +2573,7 @@ void BKE_object_handle_update(Scene *scene, Object *ob)
if (ob->recalc & OB_RECALC_DATA) {
ID *data_id = (ID *)ob->data;
AnimData *adt = BKE_animdata_from_id(data_id);
- float ctime = (float)scene->r.cfra; // XXX this is bad...
- ListBase pidlist;
- PTCacheID *pid;
+ float ctime = (float)scene->r.cfra; /* XXX this is bad... */
if (G.debug & G_DEBUG)
printf("recalcdata %s\n", ob->id.name + 2);
@@ -2696,26 +2696,8 @@ void BKE_object_handle_update(Scene *scene, Object *ob)
psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
}
}
-
- /* check if quick cache is needed */
- BKE_ptcache_ids_from_object(&pidlist, ob, scene, MAX_DUPLI_RECUR);
-
- for (pid = pidlist.first; pid; pid = pid->next) {
- if ((pid->cache->flag & PTCACHE_BAKED) ||
- (pid->cache->flag & PTCACHE_QUICK_CACHE) == 0)
- {
- continue;
- }
-
- if (pid->cache->flag & PTCACHE_OUTDATED || (pid->cache->flag & PTCACHE_SIMULATION_VALID) == 0) {
- scene->physics_settings.quick_cache_step =
- scene->physics_settings.quick_cache_step ?
- mini(scene->physics_settings.quick_cache_step, pid->cache->step) :
- pid->cache->step;
- }
- }
-
- BLI_freelistN(&pidlist);
+
+ /* quick cache removed */
}
/* the no-group proxy case, we call update */
@@ -2899,22 +2881,22 @@ static KeyBlock *insert_meshkey(Scene *scene, Object *ob, const char *name, int
int newkey = 0;
if (key == NULL) {
- key = me->key = add_key((ID *)me);
+ key = me->key = BKE_key_add((ID *)me);
key->type = KEY_RELATIVE;
newkey = 1;
}
if (newkey || from_mix == FALSE) {
/* create from mesh */
- kb = add_keyblock_ctime(key, name, FALSE);
- mesh_to_key(me, kb);
+ kb = BKE_keyblock_add_ctime(key, name, FALSE);
+ BKE_key_convert_from_mesh(me, kb);
}
else {
/* copy from current values */
float *data = do_ob_key(scene, ob);
/* create new block with prepared data */
- kb = add_keyblock_ctime(key, name, FALSE);
+ kb = BKE_keyblock_add_ctime(key, name, FALSE);
kb->data = data;
kb->totelem = me->totvert;
}
@@ -2930,20 +2912,20 @@ static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int
int newkey = 0;
if (key == NULL) {
- key = lt->key = add_key((ID *)lt);
+ key = lt->key = BKE_key_add((ID *)lt);
key->type = KEY_RELATIVE;
newkey = 1;
}
if (newkey || from_mix == FALSE) {
- kb = add_keyblock_ctime(key, name, FALSE);
+ kb = BKE_keyblock_add_ctime(key, name, FALSE);
if (!newkey) {
KeyBlock *basekb = (KeyBlock *)key->block.first;
kb->data = MEM_dupallocN(basekb->data);
kb->totelem = basekb->totelem;
}
else {
- latt_to_key(lt, kb);
+ BKE_key_convert_from_lattice(lt, kb);
}
}
else {
@@ -2951,7 +2933,7 @@ static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int
float *data = do_ob_key(scene, ob);
/* create new block with prepared data */
- kb = add_keyblock_ctime(key, name, FALSE);
+ kb = BKE_keyblock_add_ctime(key, name, FALSE);
kb->totelem = lt->pntsu * lt->pntsv * lt->pntsw;
kb->data = data;
}
@@ -2968,21 +2950,21 @@ static KeyBlock *insert_curvekey(Scene *scene, Object *ob, const char *name, int
int newkey = 0;
if (key == NULL) {
- key = cu->key = add_key((ID *)cu);
+ key = cu->key = BKE_key_add((ID *)cu);
key->type = KEY_RELATIVE;
newkey = 1;
}
if (newkey || from_mix == FALSE) {
/* create from curve */
- kb = add_keyblock_ctime(key, name, FALSE);
+ kb = BKE_keyblock_add_ctime(key, name, FALSE);
if (!newkey) {
KeyBlock *basekb = (KeyBlock *)key->block.first;
kb->data = MEM_dupallocN(basekb->data);
kb->totelem = basekb->totelem;
}
else {
- curve_to_key(cu, kb, lb);
+ BKE_key_convert_from_curve(cu, kb, lb);
}
}
else {
@@ -2990,7 +2972,7 @@ static KeyBlock *insert_curvekey(Scene *scene, Object *ob, const char *name, int
float *data = do_ob_key(scene, ob);
/* create new block with prepared data */
- kb = add_keyblock_ctime(key, name, FALSE);
+ kb = BKE_keyblock_add_ctime(key, name, FALSE);
kb->totelem = BKE_nurbList_verts_count(lb);
kb->data = data;
}
@@ -3020,7 +3002,7 @@ int BKE_object_is_modified(Scene *scene, Object *ob)
{
int flag = 0;
- if (ob_get_key(ob)) {
+ if (BKE_key_from_object(ob)) {
flag |= eModifierMode_Render;
}
else {
diff --git a/source/blender/blenkernel/intern/ocean.c b/source/blender/blenkernel/intern/ocean.c
index 4f3921936e8..7bc736d394e 100644
--- a/source/blender/blenkernel/intern/ocean.c
+++ b/source/blender/blenkernel/intern/ocean.c
@@ -475,7 +475,7 @@ void BKE_ocean_eval_ij(struct Ocean *oc, struct OceanResult *ocr, int i, int j)
if (oc->_do_normals) {
ocr->normal[0] = oc->_N_x[i * oc->_N + j];
- ocr->normal[1] = oc->_N_y /*oc->_N_y[i*oc->_N+j] (MEM01)*/;
+ ocr->normal[1] = oc->_N_y /* oc->_N_y[i * oc->_N + j] (MEM01) */;
ocr->normal[2] = oc->_N_z[i * oc->_N + j];
normalize_v3(ocr->normal);
diff --git a/source/blender/blenkernel/intern/packedFile.c b/source/blender/blenkernel/intern/packedFile.c
index 03342d0f6d1..dec49f417ae 100644
--- a/source/blender/blenkernel/intern/packedFile.c
+++ b/source/blender/blenkernel/intern/packedFile.c
@@ -201,7 +201,7 @@ PackedFile *newPackedFile(ReportList *reports, const char *filename, const char
file = BLI_open(name, O_BINARY | O_RDONLY, 0);
if (file <= 0) {
- BKE_reportf(reports, RPT_ERROR, "Unable to pack file, source path not found: \"%s\"", name);
+ BKE_reportf(reports, RPT_ERROR, "Unable to pack file, source path '%s' not found", name);
}
else {
filelen = BLI_file_descriptor_size(file);
@@ -238,7 +238,8 @@ void packAll(Main *bmain, ReportList *reports)
ima->packedfile = newPackedFile(reports, ima->name, ID_BLEND_PATH(bmain, &ima->id));
}
else if (ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE)) {
- BKE_reportf(reports, RPT_WARNING, "Image '%s' skipped, movies and image sequences not supported.", ima->id.name + 2);
+ BKE_reportf(reports, RPT_WARNING, "Image '%s' skipped, movies and image sequences not supported",
+ ima->id.name + 2);
}
}
}
@@ -310,20 +311,20 @@ int writePackedFile(ReportList *reports, const char *filename, PackedFile *pf, i
file = BLI_open(name, O_BINARY + O_WRONLY + O_CREAT + O_TRUNC, 0666);
if (file >= 0) {
if (write(file, pf->data, pf->size) != pf->size) {
- BKE_reportf(reports, RPT_ERROR, "Error writing file: %s", name);
+ BKE_reportf(reports, RPT_ERROR, "Error writing file '%s'", name);
ret_value = RET_ERROR;
}
close(file);
}
else {
- BKE_reportf(reports, RPT_ERROR, "Error creating file: %s", name);
+ BKE_reportf(reports, RPT_ERROR, "Error creating file '%s'", name);
ret_value = RET_ERROR;
}
if (remove_tmp) {
if (ret_value == RET_ERROR) {
if (BLI_rename(tempname, name) != 0) {
- BKE_reportf(reports, RPT_ERROR, "Error restoring tempfile. Check files: '%s' '%s'", tempname, name);
+ BKE_reportf(reports, RPT_ERROR, "Error restoring temp file (check files '%s' '%s')", tempname, name);
}
}
else {
diff --git a/source/blender/blenkernel/intern/paint.c b/source/blender/blenkernel/intern/paint.c
index 3267253e744..36f96045ced 100644
--- a/source/blender/blenkernel/intern/paint.c
+++ b/source/blender/blenkernel/intern/paint.c
@@ -36,6 +36,7 @@
#include "DNA_meshdata_types.h"
#include "DNA_scene_types.h"
#include "DNA_brush_types.h"
+#include "DNA_space_types.h"
#include "BLI_bitmap.h"
#include "BLI_utildefines.h"
@@ -87,6 +88,7 @@ Paint *paint_get_active(Scene *sce)
Paint *paint_get_active_from_context(const bContext *C)
{
Scene *sce = CTX_data_scene(C);
+ SpaceImage *sima;
if (sce) {
ToolSettings *ts = sce->toolsettings;
@@ -95,12 +97,12 @@ Paint *paint_get_active_from_context(const bContext *C)
if (sce->basact && sce->basact->object)
obact = sce->basact->object;
- if (CTX_wm_space_image(C) != NULL) {
+ if ((sima = CTX_wm_space_image(C)) != NULL) {
if (obact && obact->mode == OB_MODE_EDIT) {
- if (ts->use_uv_sculpt)
- return &ts->uvsculpt->paint;
- else
+ if (sima->mode == SI_MODE_PAINT)
return &ts->imapaint.paint;
+ else if (ts->use_uv_sculpt)
+ return &ts->uvsculpt->paint;
}
else {
return &ts->imapaint.paint;
@@ -190,7 +192,7 @@ void BKE_paint_free(Paint *paint)
}
/* called when copying scene settings, so even if 'src' and 'tar' are the same
- * still do a id_us_plus(), rather then if we were copying betweem 2 existing
+ * still do a id_us_plus(), rather then if we were copying between 2 existing
* scenes where a matching value should decrease the existing user count as
* with paint_brush_set() */
void BKE_paint_copy(Paint *src, Paint *tar)
diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c
index 26952db8fba..d645204d29c 100644
--- a/source/blender/blenkernel/intern/particle.c
+++ b/source/blender/blenkernel/intern/particle.c
@@ -48,6 +48,7 @@
#include "DNA_dynamicpaint_types.h"
#include "BLI_blenlib.h"
+#include "BLI_noise.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
#include "BLI_kdtree.h"
@@ -97,8 +98,8 @@ int count_particles(ParticleSystem *psys)
int tot = 0;
LOOP_SHOWN_PARTICLES {
- if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) ;
- else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) ;
+ if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) {}
+ else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) {}
else tot++;
}
return tot;
@@ -110,13 +111,13 @@ int count_particles_mod(ParticleSystem *psys, int totgr, int cur)
int tot = 0;
LOOP_SHOWN_PARTICLES {
- if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) ;
- else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) ;
+ if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) {}
+ else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) {}
else if (p % totgr == cur) tot++;
}
return tot;
}
-/* we allocate path cache memory in chunks instead of a big continguous
+/* we allocate path cache memory in chunks instead of a big contiguous
* chunk, windows' memory allocater fails to find big blocks of memory often */
#define PATH_CACHE_BUF_SIZE 1024
@@ -335,7 +336,7 @@ void psys_check_group_weights(ParticleSettings *part)
BLI_addtail(&part->dupliweights, dw);
}
- go = go->next;
+ go = go->next;
}
dw = part->dupliweights.first;
@@ -560,7 +561,7 @@ void psys_free(Object *ob, ParticleSystem *psys)
ob->transflag &= ~OB_DUPLIPARTS;
if (psys->part) {
- psys->part->id.us--;
+ psys->part->id.us--;
psys->part = NULL;
}
@@ -617,7 +618,10 @@ typedef struct ParticleRenderData {
int do_simplify;
int timeoffset;
ParticleRenderElem *elems;
- int *origindex;
+
+ /* ORIGINDEX */
+ const int *index_mf_to_mpoly;
+ const int *index_mp_to_orig;
} ParticleRenderData;
static float psys_render_viewport_falloff(double rate, float dist, float width)
@@ -790,9 +794,13 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
float *facearea, (*facecenter)[3], size[3], fac, powrate, scaleclamp;
float co1[3], co2[3], co3[3], co4[3], lambda, arearatio, t, area, viewport;
double vprate;
- int *origindex, *facetotvert;
+ int *facetotvert;
int a, b, totorigface, totface, newtot, skipped;
+ /* double lookup */
+ const int *index_mf_to_mpoly;
+ const int *index_mp_to_orig;
+
if (part->ren_as != PART_DRAW_PATH || !(part->draw & PART_DRAW_REN_STRAND))
return tot;
if (!ctx->sim.psys->renderdata)
@@ -806,13 +814,18 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
mvert = dm->getVertArray(dm);
mface = dm->getTessFaceArray(dm);
- origindex = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
totface = dm->getNumTessFaces(dm);
totorigface = me->totpoly;
if (totface == 0 || totorigface == 0)
return tot;
+ index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX);
+ if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) {
+ index_mf_to_mpoly = index_mp_to_orig = NULL;
+ }
+
facearea = MEM_callocN(sizeof(float) * totorigface, "SimplifyFaceArea");
facecenter = MEM_callocN(sizeof(float[3]) * totorigface, "SimplifyFaceCenter");
facetotvert = MEM_callocN(sizeof(int) * totorigface, "SimplifyFaceArea");
@@ -823,20 +836,22 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
data->do_simplify = TRUE;
data->elems = elems;
- data->origindex = origindex;
+ data->index_mf_to_mpoly = index_mf_to_mpoly;
+ data->index_mp_to_orig = index_mp_to_orig;
/* compute number of children per original face */
for (a = 0; a < tot; a++) {
- b = (origindex) ? origindex[ctx->index[a]] : ctx->index[a];
- if (b != -1)
+ b = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, ctx->index[a]) : ctx->index[a];
+ if (b != ORIGINDEX_NONE) {
elems[b].totchild++;
+ }
}
/* compute areas and centers of original faces */
for (mf = mface, a = 0; a < totface; a++, mf++) {
- b = (origindex) ? origindex[a] : a;
+ b = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, a) : a;
- if (b != -1) {
+ if (b != ORIGINDEX_NONE) {
copy_v3_v3(co1, mvert[mf->v1].co);
copy_v3_v3(co2, mvert[mf->v2].co);
copy_v3_v3(co3, mvert[mf->v3].co);
@@ -898,7 +913,7 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
elem->scalemax = sqrt(elem->scalemax);
/* clamp scaling */
- scaleclamp = MIN2(elem->totchild, 10.0f);
+ scaleclamp = (float)min_ii(elem->totchild, 10);
elem->scalemin = MIN2(scaleclamp, elem->scalemin);
elem->scalemax = MIN2(scaleclamp, elem->scalemax);
@@ -930,8 +945,9 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
skipped = 0;
for (a = 0, newtot = 0; a < tot; a++) {
- b = (origindex) ? origindex[ctx->index[a]] : ctx->index[a];
- if (b != -1) {
+ b = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, ctx->index[a]) : ctx->index[a];
+
+ if (b != ORIGINDEX_NONE) {
if (elems[b].curchild++ < ceil(elems[b].lambda * elems[b].totchild)) {
ctx->index[newtot] = ctx->index[a];
ctx->skip[newtot] = skipped;
@@ -962,10 +978,10 @@ int psys_render_simplify_params(ParticleSystem *psys, ChildParticle *cpa, float
data = psys->renderdata;
if (!data->do_simplify)
return 0;
-
- b = (data->origindex) ? data->origindex[cpa->num] : cpa->num;
- if (b == -1)
+ b = (data->index_mf_to_mpoly) ? DM_origindex_mface_mpoly(data->index_mf_to_mpoly, data->index_mp_to_orig, cpa->num) : cpa->num;
+ if (b == ORIGINDEX_NONE) {
return 0;
+ }
elem = &data->elems[b];
@@ -1403,7 +1419,8 @@ static void interpolate_pathcache(ParticleCacheKey *first, float t, ParticleCach
/************************************************/
/* interpolate a location on a face based on face coordinates */
void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*orcodata)[3],
- float *w, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
+ float w[4], float vec[3], float nor[3], float utan[3], float vtan[3],
+ float orco[3], float ornor[3])
{
float *v1 = 0, *v2 = 0, *v3 = 0, *v4 = 0;
float e1[3], e2[3], s1, s2, t1, t2;
@@ -1622,17 +1639,22 @@ int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, const f
Mesh *me = (Mesh *)ob->data;
MPoly *mpoly;
OrigSpaceFace *osface;
- int *origindex;
int quad, findex, totface;
float uv[2], (*faceuv)[2];
+ /* double lookup */
+ const int *index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX);
+ if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) {
+ index_mf_to_mpoly = index_mp_to_orig = NULL;
+ }
+
mpoly = dm->getPolyArray(dm);
- origindex = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
osface = dm->getTessFaceDataArray(dm, CD_ORIGSPACE);
totface = dm->getNumTessFaces(dm);
- if (osface == NULL || origindex == NULL) {
+ if (osface == NULL || index_mf_to_mpoly == NULL) {
/* Assume we don't need osface data */
if (index < totface) {
//printf("\tNO CD_ORIGSPACE, assuming not needed\n");
@@ -1666,7 +1688,8 @@ int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, const f
}
else { /* if we have no node, try every face */
for (findex = 0; findex < totface; findex++) {
- if (origindex[findex] == index) {
+ const int findex_orig = DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, findex);
+ if (findex_orig == index) {
faceuv = osface[findex].uv;
quad = (mpoly[findex].totloop == 4);
@@ -1746,7 +1769,9 @@ static int psys_map_index_on_dm(DerivedMesh *dm, int from, int index, int index_
}
/* interprets particle data to get a point on a mesh in object space */
-void psys_particle_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, const float fw[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3], float orco[3], float ornor[3])
+void psys_particle_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache,
+ const float fw[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3],
+ float orco[3], float ornor[3])
{
float tmpnor[3], mapfw[4];
float (*orcodata)[3];
@@ -1842,7 +1867,9 @@ ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
/* Particles on a shape */
/************************************************/
/* ready for future use */
-static void psys_particle_on_shape(int UNUSED(distr), int UNUSED(index), float *UNUSED(fuv), float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
+static void psys_particle_on_shape(int UNUSED(distr), int UNUSED(index),
+ float *UNUSED(fuv), float vec[3], float nor[3], float utan[3], float vtan[3],
+ float orco[3], float ornor[3])
{
/* TODO */
float zerovec[3] = {0.0f, 0.0f, 0.0f};
@@ -1868,7 +1895,9 @@ static void psys_particle_on_shape(int UNUSED(distr), int UNUSED(index), float *
/************************************************/
/* Particles on emitter */
/************************************************/
-void psys_particle_on_emitter(ParticleSystemModifierData *psmd, int from, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
+void psys_particle_on_emitter(ParticleSystemModifierData *psmd, int from, int index, int index_dmcache,
+ float fuv[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3],
+ float orco[3], float ornor[3])
{
if (psmd) {
if (psmd->psys->part->distr == PART_DISTR_GRID && psmd->psys->part->from != PART_FROM_VERT) {
@@ -2456,7 +2485,7 @@ static int psys_threads_init_path(ParticleThread *threads, Scene *scene, float c
totthread = 1;
for (i = 0; i < totthread; i++) {
- threads[i].rng_path = rng_new(seed);
+ threads[i].rng_path = BLI_rng_new(seed);
threads[i].tot = totthread;
}
@@ -3298,7 +3327,7 @@ void copy_particle_key(ParticleKey *to, ParticleKey *from, int time)
to->time = to_time;
}
}
-void psys_get_from_key(ParticleKey *key, float *loc, float *vel, float *rot, float *time)
+void psys_get_from_key(ParticleKey *key, float loc[3], float vel[3], float rot[4], float *time)
{
if (loc) copy_v3_v3(loc, key->co);
if (vel) copy_v3_v3(vel, key->vel);
@@ -3776,7 +3805,7 @@ static void get_cpa_texture(DerivedMesh *dm, ParticleSystem *psys, ParticleSetti
ptex->gravity = ptex->field = ptex->time = ptex->clump = ptex->kink =
ptex->effector = ptex->rough1 = ptex->rough2 = ptex->roughe = 1.f;
- ptex->length = 1.0f - part->randlength *PSYS_FRAND(child_index + 26);
+ ptex->length = 1.0f - part->randlength * PSYS_FRAND(child_index + 26);
ptex->length *= part->clength_thres < PSYS_FRAND(child_index + 27) ? part->clength : 1.0f;
for (m = 0; m < MAX_MTEX; m++, mtexp++) {
@@ -3968,7 +3997,7 @@ float psys_get_child_size(ParticleSystem *psys, ChildParticle *cpa, float UNUSED
size *= part->childsize;
if (part->childrandsize != 0.0f)
- size *= 1.0f - part->childrandsize *PSYS_FRAND(cpa - psys->child + 26);
+ size *= 1.0f - part->childrandsize * PSYS_FRAND(cpa - psys->child + 26);
return size;
}
@@ -4319,7 +4348,7 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta
if (pa) {
if (!always) {
if ((cfra < pa->time && (part->flag & PART_UNBORN) == 0) ||
- (cfra > pa->dietime && (part->flag & PART_DIED) == 0))
+ (cfra >= pa->dietime && (part->flag & PART_DIED) == 0))
{
return 0;
}
@@ -4414,7 +4443,9 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta
}
}
-void psys_get_dupli_texture(ParticleSystem *psys, ParticleSettings *part, ParticleSystemModifierData *psmd, ParticleData *pa, ChildParticle *cpa, float *uv, float *orco)
+void psys_get_dupli_texture(ParticleSystem *psys, ParticleSettings *part,
+ ParticleSystemModifierData *psmd, ParticleData *pa, ChildParticle *cpa,
+ float uv[2], float orco[3])
{
MFace *mface;
MTFace *mtface;
@@ -4539,8 +4570,8 @@ void psys_make_billboard(ParticleBillboardData *bb, float xvec[3], float yvec[3]
/* can happen with bad pointcache or physics calculation
* since this becomes geometry, nan's and inf's crash raytrace code.
* better not allow this. */
- if (!finite(bb->vec[0]) || !finite(bb->vec[1]) || !finite(bb->vec[2]) ||
- !finite(bb->vel[0]) || !finite(bb->vel[1]) || !finite(bb->vel[2]) )
+ if ((!finite(bb->vec[0])) || (!finite(bb->vec[1])) || (!finite(bb->vec[2])) ||
+ (!finite(bb->vel[0])) || (!finite(bb->vel[1])) || (!finite(bb->vel[2])) )
{
zero_v3(bb->vec);
zero_v3(bb->vel);
diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c
index 2c0452bc2d1..2b95946f571 100644
--- a/source/blender/blenkernel/intern/particle_system.c
+++ b/source/blender/blenkernel/intern/particle_system.c
@@ -346,7 +346,7 @@ void psys_calc_dmcache(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
if (!dm->deformedOnly) {
/* Will use later to speed up subsurf/derivedmesh */
LinkNode *node, *nodedmelem, **nodearray;
- int totdmelem, totelem, i, *origindex;
+ int totdmelem, totelem, i, *origindex, *origindex_poly = NULL;
if (psys->part->from == PART_FROM_VERT) {
totdmelem= dm->getNumVerts(dm);
@@ -356,23 +356,37 @@ void psys_calc_dmcache(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
else { /* FROM_FACE/FROM_VOLUME */
totdmelem= dm->getNumTessFaces(dm);
totelem= me->totpoly;
- origindex= dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ origindex = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ /* for face lookups we need the poly origindex too */
+ origindex_poly = dm->getPolyDataArray(dm, CD_ORIGINDEX);
+ if (origindex_poly == NULL) {
+ origindex = NULL;
+ }
}
nodedmelem= MEM_callocN(sizeof(LinkNode)*totdmelem, "psys node elems");
nodearray= MEM_callocN(sizeof(LinkNode *)*totelem, "psys node array");
for (i=0, node=nodedmelem; i<totdmelem; i++, origindex++, node++) {
- node->link= SET_INT_IN_POINTER(i);
+ int origindex_final;
+ node->link = SET_INT_IN_POINTER(i);
+
+ origindex_final = *origindex;
- if (*origindex != -1) {
- if (nodearray[*origindex]) {
+ /* if we have a poly source, do an index lookup */
+ if (origindex_poly && origindex_final != ORIGINDEX_NONE) {
+ origindex_final = origindex_poly[origindex_final];
+ }
+
+ if (origindex_final != ORIGINDEX_NONE) {
+ if (nodearray[origindex_final]) {
/* prepend */
- node->next = nodearray[*origindex];
- nodearray[*origindex]= node;
+ node->next = nodearray[origindex_final];
+ nodearray[origindex_final] = node;
+ }
+ else {
+ nodearray[origindex_final] = node;
}
- else
- nodearray[*origindex]= node;
}
}
@@ -556,8 +570,7 @@ static void distribute_grid(DerivedMesh *dm, ParticleSystem *psys)
else /* store number of intersections */
(pa+(int)(lambda*size[a])*a0mul)->hair_index++;
}
-
- if (mface->v4) {
+ else if (mface->v4) {
copy_v3_v3(v4, mvert[mface->v4].co);
if (isect_axial_line_tri_v3(a, co1, co2, v4, v1, v3, &lambda)) {
@@ -632,10 +645,10 @@ static void hammersley_create(float *out, int n, int seed, float amount)
double p, t, offs[2];
int k, kk;
- rng = rng_new(31415926 + n + seed);
- offs[0]= rng_getDouble(rng) + (double)amount;
- offs[1]= rng_getDouble(rng) + (double)amount;
- rng_free(rng);
+ rng = BLI_rng_new(31415926 + n + seed);
+ offs[0] = BLI_rng_get_double(rng) + (double)amount;
+ offs[1] = BLI_rng_get_double(rng) + (double)amount;
+ BLI_rng_free(rng);
for (k = 0; k < n; k++) {
t = 0;
@@ -643,8 +656,8 @@ static void hammersley_create(float *out, int n, int seed, float amount)
if (kk & 1) /* kk mod 2 = 1 */
t += p;
- out[2*k + 0]= fmod((double)k/(double)n + offs[0], 1.0);
- out[2*k + 1]= fmod(t + offs[1], 1.0);
+ out[2*k + 0] = fmod((double)k/(double)n + offs[0], 1.0);
+ out[2*k + 1] = fmod(t + offs[1], 1.0);
}
}
@@ -661,13 +674,13 @@ static void init_mv_jit(float *jit, int num, int seed2, float amount)
rad2= (float)(1.0f/((float)num));
rad3= (float)sqrt((float)num)/((float)num);
- rng = rng_new(31415926 + num + seed2);
+ rng = BLI_rng_new(31415926 + num + seed2);
x= 0;
num2 = 2 * num;
for (i=0; i<num2; i+=2) {
- jit[i]= x + amount*rad1*(0.5f - rng_getFloat(rng));
- jit[i+1]= i/(2.0f*num) + amount*rad1*(0.5f - rng_getFloat(rng));
+ jit[i] = x + amount*rad1*(0.5f - BLI_rng_get_float(rng));
+ jit[i+1] = i/(2.0f*num) + amount*rad1*(0.5f - BLI_rng_get_float(rng));
jit[i]-= (float)floor(jit[i]);
jit[i+1]-= (float)floor(jit[i+1]);
@@ -684,7 +697,7 @@ static void init_mv_jit(float *jit, int num, int seed2, float amount)
BLI_jitterate2(jit, jit2, num, rad2);
}
MEM_freeN(jit2);
- rng_free(rng);
+ BLI_rng_free(rng);
}
static void psys_uv_to_w(float u, float v, int quad, float *w)
@@ -698,21 +711,21 @@ static void psys_uv_to_w(float u, float v, int quad, float *w)
u= 1.0f-u;
}
- vert[0][0]= 0.0f; vert[0][1]= 0.0f; vert[0][2]= 0.0f;
- vert[1][0]= 1.0f; vert[1][1]= 0.0f; vert[1][2]= 0.0f;
- vert[2][0]= 1.0f; vert[2][1]= 1.0f; vert[2][2]= 0.0f;
+ vert[0][0] = 0.0f; vert[0][1] = 0.0f; vert[0][2] = 0.0f;
+ vert[1][0] = 1.0f; vert[1][1] = 0.0f; vert[1][2] = 0.0f;
+ vert[2][0] = 1.0f; vert[2][1] = 1.0f; vert[2][2] = 0.0f;
- co[0]= u;
- co[1]= v;
- co[2]= 0.0f;
+ co[0] = u;
+ co[1] = v;
+ co[2] = 0.0f;
if (quad) {
- vert[3][0]= 0.0f; vert[3][1]= 1.0f; vert[3][2]= 0.0f;
+ vert[3][0] = 0.0f; vert[3][1] = 1.0f; vert[3][2] = 0.0f;
interp_weights_poly_v3( w,vert, 4, co);
}
else {
interp_weights_poly_v3( w,vert, 3, co);
- w[3]= 0.0f;
+ w[3] = 0.0f;
}
}
@@ -797,13 +810,15 @@ static void distribute_threads_exec(ParticleThread *thread, ParticleData *pa, Ch
}
else {
ctx->jitoff[i] = fmod(ctx->jitoff[i],(float)ctx->jitlevel);
- psys_uv_to_w(ctx->jit[2*(int)ctx->jitoff[i]], ctx->jit[2*(int)ctx->jitoff[i]+1], mface->v4, pa->fuv);
- ctx->jitoff[i]++;
+ if (!isnan(ctx->jitoff[i])) {
+ psys_uv_to_w(ctx->jit[2*(int)ctx->jitoff[i]], ctx->jit[2*(int)ctx->jitoff[i]+1], mface->v4, pa->fuv);
+ ctx->jitoff[i]++;
+ }
}
break;
case PART_DISTR_RAND:
- randu= rng_getFloat(thread->rng);
- randv= rng_getFloat(thread->rng);
+ randu= BLI_rng_get_float(thread->rng);
+ randv= BLI_rng_get_float(thread->rng);
rng_skip_tot -= 2;
psys_uv_to_w(randu, randv, mface->v4, pa->fuv);
@@ -879,8 +894,8 @@ static void distribute_threads_exec(ParticleThread *thread, ParticleData *pa, Ch
mf= dm->getTessFaceData(dm, ctx->index[p], CD_MFACE);
- randu= rng_getFloat(thread->rng);
- randv= rng_getFloat(thread->rng);
+ randu= BLI_rng_get_float(thread->rng);
+ randv= BLI_rng_get_float(thread->rng);
rng_skip_tot -= 2;
psys_uv_to_w(randu, randv, mf->v4, cpa->fuv);
@@ -932,7 +947,7 @@ static void distribute_threads_exec(ParticleThread *thread, ParticleData *pa, Ch
}
if (rng_skip_tot > 0) /* should never be below zero */
- rng_skip(thread->rng, rng_skip_tot);
+ BLI_rng_skip(thread->rng, rng_skip_tot);
}
static void *distribute_threads_exec_cb(void *data)
@@ -949,12 +964,12 @@ static void *distribute_threads_exec_cb(void *data)
for (p=0; p<totpart; p++, cpa++) {
if (thread->ctx->skip) /* simplification skip */
- rng_skip(thread->rng, PSYS_RND_DIST_SKIP * thread->ctx->skip[p]);
+ BLI_rng_skip(thread->rng, PSYS_RND_DIST_SKIP * thread->ctx->skip[p]);
if ((p+thread->num) % thread->tot == 0)
distribute_threads_exec(thread, NULL, cpa, p);
else /* thread skip */
- rng_skip(thread->rng, PSYS_RND_DIST_SKIP);
+ BLI_rng_skip(thread->rng, PSYS_RND_DIST_SKIP);
}
}
else {
@@ -971,8 +986,8 @@ static void *distribute_threads_exec_cb(void *data)
static int *COMPARE_ORIG_INDEX = NULL;
static int distribute_compare_orig_index(const void *p1, const void *p2)
{
- int index1 = COMPARE_ORIG_INDEX[*(const int*)p1];
- int index2 = COMPARE_ORIG_INDEX[*(const int*)p2];
+ int index1 = COMPARE_ORIG_INDEX[*(const int *)p1];
+ int index2 = COMPARE_ORIG_INDEX[*(const int *)p2];
if (index1 < index2)
return -1;
@@ -998,7 +1013,7 @@ static void distribute_invalid(Scene *scene, ParticleSystem *psys, int from)
if (psys->child && totchild) {
for (p=0,cpa=psys->child; p<totchild; p++,cpa++) {
- cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]= 0.0;
+ cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3] = 0.0;
cpa->foffset= 0.0f;
cpa->parent=0;
cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
@@ -1009,7 +1024,7 @@ static void distribute_invalid(Scene *scene, ParticleSystem *psys, int from)
else {
PARTICLE_P;
LOOP_PARTICLES {
- pa->fuv[0]=pa->fuv[1]=pa->fuv[2]= pa->fuv[3]= 0.0;
+ pa->fuv[0] = pa->fuv[1] = pa->fuv[2] = pa->fuv[3] = 0.0;
pa->foffset= 0.0f;
pa->num= -1;
}
@@ -1111,7 +1126,7 @@ static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, D
if (from == PART_FROM_VERT) {
MVert *mv= dm->getVertDataArray(dm, CD_MVERT);
- float (*orcodata)[3]= dm->getVertDataArray(dm, CD_ORCO);
+ float (*orcodata)[3] = dm->getVertDataArray(dm, CD_ORCO);
int totvert = dm->getNumVerts(dm);
tree=BLI_kdtree_new(totvert);
@@ -1243,9 +1258,9 @@ static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, D
inv_totweight = (totweight > 0.f ? 1.f/totweight : 0.f);
/* Calculate cumulative weights */
- element_sum[0]= 0.0f;
+ element_sum[0] = 0.0f;
for (i=0; i<totelem; i++)
- element_sum[i+1]= element_sum[i] + element_weight[i] * inv_totweight;
+ element_sum[i+1] = element_sum[i] + element_weight[i] * inv_totweight;
/* Finally assign elements to particles */
if ((part->flag&PART_TRAND) || (part->simplify_flag&PART_SIMPLIFY_ENABLE)) {
@@ -1254,9 +1269,9 @@ static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, D
for (p=0; p<totpart; p++) {
/* In theory element_sum[totelem] should be 1.0, but due to float errors this is not necessarily always true, so scale pos accordingly. */
pos= BLI_frand() * element_sum[totelem];
- particle_element[p]= distribute_binary_search(element_sum, totelem, pos);
- particle_element[p]= MIN2(totelem-1, particle_element[p]);
- jitter_offset[particle_element[p]]= pos;
+ particle_element[p] = distribute_binary_search(element_sum, totelem, pos);
+ particle_element[p] = MIN2(totelem-1, particle_element[p]);
+ jitter_offset[particle_element[p]] = pos;
}
}
else {
@@ -1267,16 +1282,16 @@ static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, D
i= 0;
for (p=0; p<totpart; p++, pos+=step) {
- while ((i < totelem) && (pos > element_sum[i+1]))
+ while ((i < totelem) && (pos > (double)element_sum[i + 1]))
i++;
- particle_element[p]= MIN2(totelem-1, i);
+ particle_element[p] = MIN2(totelem-1, i);
/* avoid zero weight face */
if (p == totpart-1 && element_weight[particle_element[p]] == 0.0f)
- particle_element[p]= particle_element[p-1];
+ particle_element[p] = particle_element[p-1];
- jitter_offset[particle_element[p]]= pos;
+ jitter_offset[particle_element[p]] = pos;
}
}
@@ -1351,7 +1366,7 @@ static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, D
seed= 31415926 + ctx->sim.psys->seed;
for (i=0; i<totthread; i++) {
- threads[i].rng= rng_new(seed);
+ threads[i].rng= BLI_rng_new(seed);
threads[i].tot= totthread;
}
@@ -1490,9 +1505,9 @@ void psys_threads_free(ParticleThread *threads)
/* threads */
for (i=0; i<totthread; i++) {
if (threads[i].rng)
- rng_free(threads[i].rng);
+ BLI_rng_free(threads[i].rng);
if (threads[i].rng_path)
- rng_free(threads[i].rng_path);
+ BLI_rng_free(threads[i].rng_path);
}
MEM_freeN(ctx);
@@ -1581,7 +1596,7 @@ static void get_angular_velocity_vector(short avemode, ParticleKey *state, float
switch (avemode) {
case PART_AVE_VELOCITY:
copy_v3_v3(vec, state->vel);
- break;
+ break;
case PART_AVE_HORIZONTAL:
{
float zvec[3];
@@ -1620,9 +1635,9 @@ void psys_get_birth_coordinates(ParticleSimulationData *sim, ParticleData *pa, P
ParticleSystem *psys = sim->psys;
ParticleSettings *part;
ParticleTexture ptex;
- float fac, phasefac, nor[3]={0,0,0},loc[3],vel[3]={0.0,0.0,0.0},rot[4],q2[4];
- float r_vel[3],r_ave[3],r_rot[4],vec[3],p_vel[3]={0.0,0.0,0.0};
- float x_vec[3]={1.0,0.0,0.0}, utan[3]={0.0,1.0,0.0}, vtan[3]={0.0,0.0,1.0}, rot_vec[3]={0.0,0.0,0.0};
+ float fac, phasefac, nor[3] = {0,0,0},loc[3],vel[3] = {0.0,0.0,0.0},rot[4],q2[4];
+ float r_vel[3],r_ave[3],r_rot[4],vec[3],p_vel[3] = {0.0,0.0,0.0};
+ float x_vec[3] = {1.0,0.0,0.0}, utan[3] = {0.0,1.0,0.0}, vtan[3] = {0.0,0.0,1.0}, rot_vec[3] = {0.0,0.0,0.0};
float q_phase[4];
int p = pa - psys->particles;
part=psys->part;
@@ -2535,7 +2550,7 @@ static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, floa
madd_v3_v3fl(force, vec, -(pressure + near_pressure*q)*q);
/* Viscosity */
- if (visc > 0.f || stiff_visc > 0.f) {
+ if (visc > 0.f || stiff_visc > 0.f) {
sub_v3_v3v3(dv, vel, state->vel);
u = dot_v3v3(vec, dv);
@@ -2734,7 +2749,7 @@ static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, floa
}
static void basic_rotate(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
{
- float rotfac, rot1[4], rot2[4]={1.0,0.0,0.0,0.0}, dtime=dfra*timestep, extrotfac;
+ float rotfac, rot1[4], rot2[4] = {1.0,0.0,0.0,0.0}, dtime=dfra*timestep, extrotfac;
if ((part->flag & PART_ROTATIONS) == 0) {
unit_qt(pa->state.rot);
@@ -3164,8 +3179,7 @@ void BKE_psys_collision_neartest_cb(void *userdata, int index, const BVHTreeRay
if (col->hit == col->current && col->pce.index == index && col->pce.tot == 3)
return;
- do
- {
+ do {
collision = collision_sphere_to_tri(col, ray->radius, &pce, &t);
if (col->pce.inside == 0) {
collision += collision_sphere_to_edges(col, ray->radius, &pce, &t);
@@ -3775,7 +3789,7 @@ static void save_hair(ParticleSimulationData *sim, float UNUSED(cfra))
/* Calculate the speed of the particle relative to the local scale of the
* simulation. This should be called once per particle during a simulation
* step, after the velocity has been updated. element_size defines the scale of
- * the simulation, and is typically the distance to neighbourning particles. */
+ * the simulation, and is typically the distance to neighboring particles. */
static void update_courant_num(ParticleSimulationData *sim, ParticleData *pa,
float dtime, SPHData *sphdata)
{
@@ -4074,7 +4088,7 @@ static void particles_fluid_step(ParticleSimulationData *sim, int UNUSED(cfra))
{
FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(sim->ob, eModifierType_Fluidsim);
- if ( fluidmd && fluidmd->fss) {
+ if ( fluidmd && fluidmd->fss) {
FluidsimSettings *fss= fluidmd->fss;
ParticleSettings *part = psys->part;
ParticleData *pa=NULL;
@@ -4119,7 +4133,7 @@ static void particles_fluid_step(ParticleSimulationData *sim, int UNUSED(cfra))
int ptype=0;
gzread(gzf, &ptype, sizeof( ptype ));
- if (ptype&readMask) {
+ if (ptype & readMask) {
activeParts++;
gzread(gzf, &(pa->size), sizeof(float));
diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c
index 780528f4a0d..f195b3d71b0 100644
--- a/source/blender/blenkernel/intern/pointcache.c
+++ b/source/blender/blenkernel/intern/pointcache.c
@@ -249,9 +249,9 @@ static int ptcache_particle_write(int index, void *psys_v, void **data, int cfr
if (data[BPHYS_DATA_INDEX] && (cfra < pa->time - step || cfra > pa->dietime + step))
return 0;
- times[0]= pa->time;
- times[1]= pa->dietime;
- times[2]= pa->lifetime;
+ times[0] = pa->time;
+ times[1] = pa->dietime;
+ times[2] = pa->lifetime;
PTCACHE_DATA_FROM(data, BPHYS_DATA_INDEX, &index);
PTCACHE_DATA_FROM(data, BPHYS_DATA_LOCATION, pa->state.co);
@@ -532,20 +532,31 @@ static int ptcache_smoke_totpoint(void *smoke_v, int UNUSED(cfra))
SmokeDomainSettings *sds = smd->domain;
if (sds->fluid) {
- return sds->res[0]*sds->res[1]*sds->res[2];
+ return sds->base_res[0]*sds->base_res[1]*sds->base_res[2];
}
else
return 0;
}
+
+#define SMOKE_CACHE_VERSION "1.04"
+
static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v)
{
SmokeModifierData *smd= (SmokeModifierData *)smoke_v;
SmokeDomainSettings *sds = smd->domain;
int ret = 0;
+ int fluid_fields = smoke_get_data_flags(sds);
+
+ /* version header */
+ ptcache_file_write(pf, SMOKE_CACHE_VERSION, 4, sizeof(char));
+ ptcache_file_write(pf, &fluid_fields, 1, sizeof(int));
+ ptcache_file_write(pf, &sds->active_fields, 1, sizeof(int));
+ ptcache_file_write(pf, &sds->res, 3, sizeof(int));
+ ptcache_file_write(pf, &sds->dx, 1, sizeof(float));
if (sds->fluid) {
size_t res = sds->res[0]*sds->res[1]*sds->res[2];
- float dt, dx, *dens, *densold, *heat, *heatold, *vx, *vy, *vz, *vxold, *vyold, *vzold;
+ float dt, dx, *dens, *react, *fuel, *flame, *heat, *heatold, *vx, *vy, *vz, *r, *g, *b;
unsigned char *obstacles;
unsigned int in_len = sizeof(float)*(unsigned int)res;
unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len)*4, "pointcache_lzo_buffer");
@@ -553,22 +564,40 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v)
int mode=1; // light
if (sds->cache_comp == SM_CACHE_HEAVY) mode=2; // heavy
- smoke_export(sds->fluid, &dt, &dx, &dens, &densold, &heat, &heatold, &vx, &vy, &vz, &vxold, &vyold, &vzold, &obstacles);
+ smoke_export(sds->fluid, &dt, &dx, &dens, &react, &flame, &fuel, &heat, &heatold, &vx, &vy, &vz, &r, &g, &b, &obstacles);
ptcache_file_compressed_write(pf, (unsigned char *)sds->shadow, in_len, out, mode);
ptcache_file_compressed_write(pf, (unsigned char *)dens, in_len, out, mode);
- ptcache_file_compressed_write(pf, (unsigned char *)densold, in_len, out, mode);
- ptcache_file_compressed_write(pf, (unsigned char *)heat, in_len, out, mode);
- ptcache_file_compressed_write(pf, (unsigned char *)heatold, in_len, out, mode);
+ if (fluid_fields & SM_ACTIVE_HEAT) {
+ ptcache_file_compressed_write(pf, (unsigned char *)heat, in_len, out, mode);
+ ptcache_file_compressed_write(pf, (unsigned char *)heatold, in_len, out, mode);
+ }
+ if (fluid_fields & SM_ACTIVE_FIRE) {
+ ptcache_file_compressed_write(pf, (unsigned char *)flame, in_len, out, mode);
+ ptcache_file_compressed_write(pf, (unsigned char *)fuel, in_len, out, mode);
+ ptcache_file_compressed_write(pf, (unsigned char *)react, in_len, out, mode);
+ }
+ if (fluid_fields & SM_ACTIVE_COLORS) {
+ ptcache_file_compressed_write(pf, (unsigned char *)r, in_len, out, mode);
+ ptcache_file_compressed_write(pf, (unsigned char *)g, in_len, out, mode);
+ ptcache_file_compressed_write(pf, (unsigned char *)b, in_len, out, mode);
+ }
ptcache_file_compressed_write(pf, (unsigned char *)vx, in_len, out, mode);
ptcache_file_compressed_write(pf, (unsigned char *)vy, in_len, out, mode);
ptcache_file_compressed_write(pf, (unsigned char *)vz, in_len, out, mode);
- ptcache_file_compressed_write(pf, (unsigned char *)vxold, in_len, out, mode);
- ptcache_file_compressed_write(pf, (unsigned char *)vyold, in_len, out, mode);
- ptcache_file_compressed_write(pf, (unsigned char *)vzold, in_len, out, mode);
ptcache_file_compressed_write(pf, (unsigned char *)obstacles, (unsigned int)res, out, mode);
ptcache_file_write(pf, &dt, 1, sizeof(float));
ptcache_file_write(pf, &dx, 1, sizeof(float));
+ ptcache_file_write(pf, &sds->p0, 3, sizeof(float));
+ ptcache_file_write(pf, &sds->p1, 3, sizeof(float));
+ ptcache_file_write(pf, &sds->dp0, 3, sizeof(float));
+ ptcache_file_write(pf, &sds->shift, 3, sizeof(int));
+ ptcache_file_write(pf, &sds->obj_shift_f, 3, sizeof(float));
+ ptcache_file_write(pf, &sds->obmat, 16, sizeof(float));
+ ptcache_file_write(pf, &sds->base_res, 3, sizeof(int));
+ ptcache_file_write(pf, &sds->res_min, 3, sizeof(int));
+ ptcache_file_write(pf, &sds->res_max, 3, sizeof(int));
+ ptcache_file_write(pf, &sds->active_color, 3, sizeof(float));
MEM_freeN(out);
@@ -579,7 +608,7 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v)
int res_big_array[3];
int res_big;
int res = sds->res[0]*sds->res[1]*sds->res[2];
- float *dens, *densold, *tcu, *tcv, *tcw;
+ float *dens, *react, *fuel, *flame, *tcu, *tcv, *tcw, *r, *g, *b;
unsigned int in_len = sizeof(float)*(unsigned int)res;
unsigned int in_len_big;
unsigned char *out;
@@ -593,11 +622,20 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v)
in_len_big = sizeof(float) * (unsigned int)res_big;
- smoke_turbulence_export(sds->wt, &dens, &densold, &tcu, &tcv, &tcw);
+ smoke_turbulence_export(sds->wt, &dens, &react, &flame, &fuel, &r, &g, &b, &tcu, &tcv, &tcw);
out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len_big), "pointcache_lzo_buffer");
ptcache_file_compressed_write(pf, (unsigned char *)dens, in_len_big, out, mode);
- ptcache_file_compressed_write(pf, (unsigned char *)densold, in_len_big, out, mode);
+ if (fluid_fields & SM_ACTIVE_FIRE) {
+ ptcache_file_compressed_write(pf, (unsigned char *)flame, in_len_big, out, mode);
+ ptcache_file_compressed_write(pf, (unsigned char *)fuel, in_len_big, out, mode);
+ ptcache_file_compressed_write(pf, (unsigned char *)react, in_len_big, out, mode);
+ }
+ if (fluid_fields & SM_ACTIVE_COLORS) {
+ ptcache_file_compressed_write(pf, (unsigned char *)r, in_len_big, out, mode);
+ ptcache_file_compressed_write(pf, (unsigned char *)g, in_len_big, out, mode);
+ ptcache_file_compressed_write(pf, (unsigned char *)b, in_len_big, out, mode);
+ }
MEM_freeN(out);
out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len), "pointcache_lzo_buffer");
@@ -615,34 +653,95 @@ static int ptcache_smoke_read(PTCacheFile *pf, void *smoke_v)
{
SmokeModifierData *smd= (SmokeModifierData *)smoke_v;
SmokeDomainSettings *sds = smd->domain;
+ char version[4];
+ int ch_res[3];
+ float ch_dx;
+ int fluid_fields = smoke_get_data_flags(sds);
+ int cache_fields = 0;
+ int active_fields = 0;
+ int reallocate = 0;
+
+ /* version header */
+ ptcache_file_read(pf, version, 4, sizeof(char));
+ if (strncmp(version, SMOKE_CACHE_VERSION, 4)) return 0;
+ /* fluid info */
+ ptcache_file_read(pf, &cache_fields, 1, sizeof(int));
+ ptcache_file_read(pf, &active_fields, 1, sizeof(int));
+ ptcache_file_read(pf, &ch_res, 3, sizeof(int));
+ ptcache_file_read(pf, &ch_dx, 1, sizeof(float));
+
+ /* check if resolution has changed */
+ if (sds->res[0] != ch_res[0] ||
+ sds->res[1] != ch_res[1] ||
+ sds->res[2] != ch_res[2]) {
+ if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN)
+ reallocate = 1;
+ else
+ return 0;
+ }
+ /* check if active fields have changed */
+ if (fluid_fields != cache_fields ||
+ active_fields != sds->active_fields)
+ reallocate = 1;
+
+ /* reallocate fluid if needed*/
+ if (reallocate) {
+ sds->active_fields = active_fields;
+ smoke_reallocate_fluid(sds, ch_dx, ch_res, 1);
+ sds->dx = ch_dx;
+ VECCOPY(sds->res, ch_res);
+ sds->total_cells = ch_res[0]*ch_res[1]*ch_res[2];
+ if (sds->flags & MOD_SMOKE_HIGHRES) {
+ smoke_reallocate_highres_fluid(sds, ch_dx, ch_res, 1);
+ }
+ }
if (sds->fluid) {
size_t res = sds->res[0]*sds->res[1]*sds->res[2];
- float dt, dx, *dens, *densold, *heat, *heatold, *vx, *vy, *vz, *vxold, *vyold, *vzold;
+ float dt, dx, *dens, *react, *fuel, *flame, *heat, *heatold, *vx, *vy, *vz, *r, *g, *b;
unsigned char *obstacles;
unsigned int out_len = (unsigned int)res * sizeof(float);
- smoke_export(sds->fluid, &dt, &dx, &dens, &densold, &heat, &heatold, &vx, &vy, &vz, &vxold, &vyold, &vzold, &obstacles);
+ smoke_export(sds->fluid, &dt, &dx, &dens, &react, &flame, &fuel, &heat, &heatold, &vx, &vy, &vz, &r, &g, &b, &obstacles);
ptcache_file_compressed_read(pf, (unsigned char *)sds->shadow, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)dens, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)densold, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)heat, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)heatold, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)vx, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)vy, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)vz, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)vxold, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)vyold, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)vzold, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)obstacles, (unsigned int)res);
+ ptcache_file_compressed_read(pf, (unsigned char *)dens, out_len);
+ if (cache_fields & SM_ACTIVE_HEAT) {
+ ptcache_file_compressed_read(pf, (unsigned char *)heat, out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)heatold, out_len);
+ }
+ if (cache_fields & SM_ACTIVE_FIRE) {
+ ptcache_file_compressed_read(pf, (unsigned char *)flame, out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)fuel, out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)react, out_len);
+ }
+ if (cache_fields & SM_ACTIVE_COLORS) {
+ ptcache_file_compressed_read(pf, (unsigned char *)r, out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)g, out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)b, out_len);
+ }
+ ptcache_file_compressed_read(pf, (unsigned char *)vx, out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)vy, out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)vz, out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)obstacles, (unsigned int)res);
ptcache_file_read(pf, &dt, 1, sizeof(float));
ptcache_file_read(pf, &dx, 1, sizeof(float));
-
- if (pf->data_types & (1<<BPHYS_DATA_SMOKE_HIGH) && sds->wt) {
+ ptcache_file_read(pf, &sds->p0, 3, sizeof(float));
+ ptcache_file_read(pf, &sds->p1, 3, sizeof(float));
+ ptcache_file_read(pf, &sds->dp0, 3, sizeof(float));
+ ptcache_file_read(pf, &sds->shift, 3, sizeof(int));
+ ptcache_file_read(pf, &sds->obj_shift_f, 3, sizeof(float));
+ ptcache_file_read(pf, &sds->obmat, 16, sizeof(float));
+ ptcache_file_read(pf, &sds->base_res, 3, sizeof(int));
+ ptcache_file_read(pf, &sds->res_min, 3, sizeof(int));
+ ptcache_file_read(pf, &sds->res_max, 3, sizeof(int));
+ ptcache_file_read(pf, &sds->active_color, 3, sizeof(float));
+ }
+
+ if (pf->data_types & (1<<BPHYS_DATA_SMOKE_HIGH) && sds->wt) {
int res = sds->res[0]*sds->res[1]*sds->res[2];
int res_big, res_big_array[3];
- float *dens, *densold, *tcu, *tcv, *tcw;
+ float *dens, *react, *fuel, *flame, *tcu, *tcv, *tcw, *r, *g, *b;
unsigned int out_len = sizeof(float)*(unsigned int)res;
unsigned int out_len_big;
@@ -650,16 +749,23 @@ static int ptcache_smoke_read(PTCacheFile *pf, void *smoke_v)
res_big = res_big_array[0]*res_big_array[1]*res_big_array[2];
out_len_big = sizeof(float) * (unsigned int)res_big;
- smoke_turbulence_export(sds->wt, &dens, &densold, &tcu, &tcv, &tcw);
+ smoke_turbulence_export(sds->wt, &dens, &react, &flame, &fuel, &r, &g, &b, &tcu, &tcv, &tcw);
- ptcache_file_compressed_read(pf, (unsigned char*)dens, out_len_big);
- ptcache_file_compressed_read(pf, (unsigned char*)densold, out_len_big);
+ ptcache_file_compressed_read(pf, (unsigned char *)dens, out_len_big);
+ if (cache_fields & SM_ACTIVE_FIRE) {
+ ptcache_file_compressed_read(pf, (unsigned char *)flame, out_len_big);
+ ptcache_file_compressed_read(pf, (unsigned char *)fuel, out_len_big);
+ }
+ if (cache_fields & SM_ACTIVE_COLORS) {
+ ptcache_file_compressed_read(pf, (unsigned char *)r, out_len_big);
+ ptcache_file_compressed_read(pf, (unsigned char *)g, out_len_big);
+ ptcache_file_compressed_read(pf, (unsigned char *)b, out_len_big);
+ }
- ptcache_file_compressed_read(pf, (unsigned char*)tcu, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)tcv, out_len);
- ptcache_file_compressed_read(pf, (unsigned char*)tcw, out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)tcu, out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)tcv, out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)tcw, out_len);
}
- }
return 1;
}
@@ -753,7 +859,7 @@ static int ptcache_dynamicpaint_read(PTCacheFile *pf, void *dp_v)
return 0;
}
- ptcache_file_compressed_read(pf, (unsigned char*)surface->data->type_data, data_len*surface->data->total_points);
+ ptcache_file_compressed_read(pf, (unsigned char *)surface->data->type_data, data_len*surface->data->total_points);
}
return 1;
@@ -1030,7 +1136,7 @@ void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int dup
ListBase *lb_dupli_ob;
/* don't update the dupli groups, we only wan't their pid's */
- if ((lb_dupli_ob = object_duplilist_ex(scene, ob, FALSE))) {
+ if ((lb_dupli_ob = object_duplilist_ex(scene, ob, FALSE, FALSE))) {
DupliObject *dob;
for (dob= lb_dupli_ob->first; dob; dob= dob->next) {
if (dob->ob != ob) { /* avoids recursive loops with dupliframes: bug 22988 */
@@ -1257,7 +1363,7 @@ static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, uns
if (mode == 1) {
LZO_HEAP_ALLOC(wrkmem, LZO1X_MEM_COMPRESS);
- r = lzo1x_1_compress(in, (lzo_uint)in_len, out, (lzo_uint *)&out_len, wrkmem);
+ r = lzo1x_1_compress(in, (lzo_uint)in_len, out, (lzo_uint *)&out_len, wrkmem);
if (!(r == LZO_E_OK) || (out_len >= in_len))
compressed = 0;
else
@@ -1593,7 +1699,7 @@ static PTCacheMem *ptcache_disk_frame_to_mem(PTCacheID *pid, int cfra)
for (i=0; i<BPHYS_TOT_DATA; i++) {
unsigned int out_len = pm->totpoint*ptcache_data_size[i];
if (pf->data_types & (1<<i))
- ptcache_file_compressed_read(pf, (unsigned char*)(pm->data[i]), out_len);
+ ptcache_file_compressed_read(pf, (unsigned char *)(pm->data[i]), out_len);
}
}
else {
@@ -1624,7 +1730,7 @@ static PTCacheMem *ptcache_disk_frame_to_mem(PTCacheID *pid, int cfra)
extra->data = MEM_callocN(extra->totdata * ptcache_extra_datasize[extra->type], "Pointcache extradata->data");
if (pf->flag & PTCACHE_TYPEFLAG_COMPRESS)
- ptcache_file_compressed_read(pf, (unsigned char*)(extra->data), extra->totdata*ptcache_extra_datasize[extra->type]);
+ ptcache_file_compressed_read(pf, (unsigned char *)(extra->data), extra->totdata*ptcache_extra_datasize[extra->type]);
else
ptcache_file_read(pf, extra->data, extra->totdata, ptcache_extra_datasize[extra->type]);
@@ -1681,7 +1787,7 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm)
if (pm->data[i]) {
unsigned int in_len = pm->totpoint*ptcache_data_size[i];
unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len)*4, "pointcache_lzo_buffer");
- ptcache_file_compressed_write(pf, (unsigned char*)(pm->data[i]), in_len, out, pid->cache->compression);
+ ptcache_file_compressed_write(pf, (unsigned char *)(pm->data[i]), in_len, out, pid->cache->compression);
MEM_freeN(out);
}
}
@@ -1714,7 +1820,7 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm)
if (pid->cache->compression) {
unsigned int in_len = extra->totdata * ptcache_extra_datasize[extra->type];
unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len)*4, "pointcache_lzo_buffer");
- ptcache_file_compressed_write(pf, (unsigned char*)(extra->data), in_len, out, pid->cache->compression);
+ ptcache_file_compressed_write(pf, (unsigned char *)(extra->data), in_len, out, pid->cache->compression);
MEM_freeN(out);
}
else {
@@ -1925,18 +2031,16 @@ int BKE_ptcache_read(PTCacheID *pid, float cfra)
pid->cache->simframe = cfra2;
}
- if ((pid->cache->flag & PTCACHE_QUICK_CACHE)==0) {
- cfrai = (int)cfra;
- /* clear invalid cache frames so that better stuff can be simulated */
- if (pid->cache->flag & PTCACHE_OUTDATED) {
- BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, cfrai);
- }
- else if (pid->cache->flag & PTCACHE_FRAMES_SKIPPED) {
- if (cfra <= pid->cache->last_exact)
- pid->cache->flag &= ~PTCACHE_FRAMES_SKIPPED;
+ cfrai = (int)cfra;
+ /* clear invalid cache frames so that better stuff can be simulated */
+ if (pid->cache->flag & PTCACHE_OUTDATED) {
+ BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, cfrai);
+ }
+ else if (pid->cache->flag & PTCACHE_FRAMES_SKIPPED) {
+ if (cfra <= pid->cache->last_exact)
+ pid->cache->flag &= ~PTCACHE_FRAMES_SKIPPED;
- BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, MAX2(cfrai, pid->cache->last_exact));
- }
+ BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, MAX2(cfrai, pid->cache->last_exact));
}
return ret;
@@ -2167,7 +2271,7 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra)
/* clear all files in the temp dir with the prefix of the ID and the ".bphys" suffix */
switch (mode) {
case PTCACHE_CLEAR_ALL:
- case PTCACHE_CLEAR_BEFORE:
+ case PTCACHE_CLEAR_BEFORE:
case PTCACHE_CLEAR_AFTER:
if (pid->cache->flag & PTCACHE_DISK_CACHE) {
ptcache_path(pid, path);
@@ -2271,7 +2375,7 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra)
}
}
}
- if (pid->cache->cached_frames && cfra>=sta && cfra<=end)
+ if (pid->cache->cached_frames && cfra >= sta && cfra <= end)
pid->cache->cached_frames[cfra-sta] = 0;
break;
}
@@ -2358,7 +2462,7 @@ void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startfra
if (MEM_allocN_len(cache->cached_frames) != sizeof(char) * (cache->endframe-cache->startframe+1)) {
MEM_freeN(cache->cached_frames);
cache->cached_frames = NULL;
- }
+ }
}
if (cache->cached_frames==NULL && cache->endframe > cache->startframe) {
@@ -2431,8 +2535,6 @@ int BKE_ptcache_id_reset(Scene *scene, PTCacheID *pid, int mode)
if (mode == PTCACHE_RESET_DEPSGRAPH) {
if (!(cache->flag & PTCACHE_BAKED) && !BKE_ptcache_get_continue_physics()) {
- if (cache->flag & PTCACHE_QUICK_CACHE)
- clear= 1;
after= 1;
}
@@ -2466,10 +2568,10 @@ int BKE_ptcache_id_reset(Scene *scene, PTCacheID *pid, int mode)
sbFreeSimulation(pid->calldata);
else if (pid->type == PTCACHE_TYPE_PARTICLES)
psys_reset(pid->calldata, PSYS_RESET_DEPSGRAPH);
- else if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN)
+ /*else if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN)
smokeModifier_reset(pid->calldata);
else if (pid->type == PTCACHE_TYPE_SMOKE_HIGHRES)
- smokeModifier_reset_turbulence(pid->calldata);
+ smokeModifier_reset_turbulence(pid->calldata);*/
else if (pid->type == PTCACHE_TYPE_DYNAMICPAINT)
dynamicPaint_clearSurface((DynamicPaintSurface*)pid->calldata);
}
@@ -2496,7 +2598,7 @@ int BKE_ptcache_object_reset(Scene *scene, Object *ob, int mode)
}
for (psys=ob->particlesystem.first; psys; psys=psys->next) {
- /* children or just redo can be calculated without reseting anything */
+ /* children or just redo can be calculated without resetting anything */
if (psys->recalc & PSYS_RECALC_REDO || psys->recalc & PSYS_RECALC_CHILD)
skip = 1;
/* Baked cloth hair has to be checked too, because we don't want to reset */
@@ -2663,36 +2765,65 @@ void BKE_ptcache_free_list(ListBase *ptcaches)
}
}
-static PointCache *ptcache_copy(PointCache *cache)
+static PointCache *ptcache_copy(PointCache *cache, int copy_data)
{
PointCache *ncache;
ncache= MEM_dupallocN(cache);
- /* hmm, should these be copied over instead? */
ncache->mem_cache.first = NULL;
ncache->mem_cache.last = NULL;
- ncache->cached_frames = NULL;
- ncache->edit = NULL;
- ncache->flag= 0;
- ncache->simframe= 0;
+ if (copy_data == FALSE) {
+ ncache->mem_cache.first = NULL;
+ ncache->mem_cache.last = NULL;
+ ncache->cached_frames = NULL;
+
+ ncache->flag= 0;
+ ncache->simframe= 0;
+ }
+ else {
+ PTCacheMem *pm;
+
+ for (pm = cache->mem_cache.first; pm; pm = pm->next) {
+ PTCacheMem *pmn = MEM_dupallocN(pm);
+ int i;
+
+ for (i = 0; i < BPHYS_TOT_DATA; i++) {
+ if (pmn->data[i])
+ pmn->data[i] = MEM_dupallocN(pm->data[i]);
+ }
+
+ BKE_ptcache_mem_pointers_init(pm);
+
+ BLI_addtail(&ncache->mem_cache, pmn);
+ }
+
+ if (ncache->cached_frames)
+ ncache->cached_frames = MEM_dupallocN(cache->cached_frames);
+ }
+
+ /* hmm, should these be copied over instead? */
+ ncache->edit = NULL;
return ncache;
}
+
/* returns first point cache */
-PointCache *BKE_ptcache_copy_list(ListBase *ptcaches_new, ListBase *ptcaches_old)
+PointCache *BKE_ptcache_copy_list(ListBase *ptcaches_new, ListBase *ptcaches_old, int copy_data)
{
PointCache *cache = ptcaches_old->first;
ptcaches_new->first = ptcaches_new->last = NULL;
for (; cache; cache=cache->next)
- BLI_addtail(ptcaches_new, ptcache_copy(cache));
+ BLI_addtail(ptcaches_new, ptcache_copy(cache, copy_data));
return ptcaches_new->first;
}
+/* Disabled this code; this is being called on scene_update_tagged, and that in turn gets called on
+ * every user action changing stuff, and then it runs a complete bake??? (ton) */
/* Baking */
void BKE_ptcache_quick_cache_all(Main *bmain, Scene *scene)
@@ -2876,7 +3007,7 @@ void BKE_ptcache_bake(PTCacheBaker* baker)
}
if ((cache->flag & PTCACHE_REDO_NEEDED || (cache->flag & PTCACHE_SIMULATION_VALID)==0) &&
- ((cache->flag & PTCACHE_QUICK_CACHE)==0 || render || bake))
+ (render || bake))
{
BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
}
@@ -3195,8 +3326,9 @@ void BKE_ptcache_load_external(PTCacheID *pid)
cache->endframe = end;
cache->totpoint = 0;
- if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN)
- ; /*necessary info in every file*/
+ if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN) {
+ /* necessary info in every file */
+ }
/* read totpoint from info file (frame 0) */
else if (info) {
pf= ptcache_file_open(pid, PTCACHE_FILE_READ, 0);
@@ -3244,7 +3376,7 @@ void BKE_ptcache_update_info(PTCacheID *pid)
if (cache->flag & PTCACHE_EXTERNAL) {
int cfra = cache->startframe;
- for (; cfra<=cache->endframe; cfra++) {
+ for (; cfra <= cache->endframe; cfra++) {
if (BKE_ptcache_id_exist(pid, cfra))
totframes++;
}
@@ -3271,7 +3403,7 @@ void BKE_ptcache_update_info(PTCacheID *pid)
else {
int cfra = cache->startframe;
- for (; cfra<=cache->endframe; cfra++) {
+ for (; cfra <= cache->endframe; cfra++) {
if (BKE_ptcache_id_exist(pid, cfra))
totframes++;
}
@@ -3280,7 +3412,7 @@ void BKE_ptcache_update_info(PTCacheID *pid)
}
}
else {
- PTCacheMem *pm = cache->mem_cache.first;
+ PTCacheMem *pm = cache->mem_cache.first;
float bytes = 0.0f;
int i, mb;
diff --git a/source/blender/blenkernel/intern/property.c b/source/blender/blenkernel/intern/property.c
index 46ddce4b51b..8da4f11fed3 100644
--- a/source/blender/blenkernel/intern/property.c
+++ b/source/blender/blenkernel/intern/property.c
@@ -27,9 +27,12 @@
/** \file blender/blenkernel/intern/property.c
* \ingroup bke
+ *
+ * This module deals with bProperty only,
+ * they are used on blender objects in the game engine
+ * (where they get converted into C++ classes - CValue and subclasses)
*/
-
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
@@ -45,7 +48,7 @@
#include "BKE_property.h"
-void free_property(bProperty *prop)
+void BKE_bproperty_free(bProperty *prop)
{
if (prop->poin && prop->poin != &prop->data) MEM_freeN(prop->poin);
@@ -53,17 +56,17 @@ void free_property(bProperty *prop)
}
-void free_properties(ListBase *lb)
+void BKE_bproperty_free_list(ListBase *lb)
{
bProperty *prop;
while ( (prop = lb->first) ) {
BLI_remlink(lb, prop);
- free_property(prop);
+ BKE_bproperty_free(prop);
}
}
-bProperty *copy_property(bProperty *prop)
+bProperty *BKE_bproperty_copy(bProperty *prop)
{
bProperty *propn;
@@ -76,13 +79,13 @@ bProperty *copy_property(bProperty *prop)
return propn;
}
-void copy_properties(ListBase *lbn, ListBase *lbo)
+void BKE_bproperty_copy_list(ListBase *lbn, ListBase *lbo)
{
bProperty *prop, *propn;
- free_properties(lbn); /* in case we are copying to an object with props */
+ BKE_bproperty_free_list(lbn); /* in case we are copying to an object with props */
prop = lbo->first;
while (prop) {
- propn = copy_property(prop);
+ propn = BKE_bproperty_copy(prop);
BLI_addtail(lbn, propn);
prop = prop->next;
}
@@ -90,7 +93,7 @@ void copy_properties(ListBase *lbn, ListBase *lbo)
}
-void init_property(bProperty *prop)
+void BKE_bproperty_init(bProperty *prop)
{
/* also use when property changes type */
@@ -113,22 +116,22 @@ void init_property(bProperty *prop)
}
-bProperty *new_property(int type)
+bProperty *BKE_bproperty_new(int type)
{
bProperty *prop;
prop = MEM_callocN(sizeof(bProperty), "property");
prop->type = type;
- init_property(prop);
+ BKE_bproperty_init(prop);
strcpy(prop->name, "prop");
return prop;
}
-/* used by unique_property() only */
-static bProperty *get_property__internal(bProperty *first, bProperty *self, const char *name)
+/* used by BKE_bproperty_unique() only */
+static bProperty *bproperty_get(bProperty *first, bProperty *self, const char *name)
{
bProperty *p;
for (p = first; p; p = p->next) {
@@ -137,7 +140,7 @@ static bProperty *get_property__internal(bProperty *first, bProperty *self, cons
}
return NULL;
}
-void unique_property(bProperty *first, bProperty *prop, int force)
+void BKE_bproperty_unique(bProperty *first, bProperty *prop, int force)
{
bProperty *p;
@@ -151,13 +154,13 @@ void unique_property(bProperty *first, bProperty *prop, int force)
if (force) {
/* change other names to make them unique */
- while ((p = get_property__internal(first, prop, prop->name))) {
- unique_property(first, p, 0);
+ while ((p = bproperty_get(first, prop, prop->name))) {
+ BKE_bproperty_unique(first, p, 0);
}
}
else {
/* change our own name until its unique */
- if (get_property__internal(first, prop, prop->name)) {
+ if (bproperty_get(first, prop, prop->name)) {
/* there is a collision */
char new_name[sizeof(prop->name)];
char base_name[sizeof(prop->name)];
@@ -175,33 +178,34 @@ void unique_property(bProperty *first, bProperty *prop, int force)
BLI_snprintf(num, sizeof(num), "%d", i++);
BLI_strncpy(new_name, base_name, sizeof(prop->name) - strlen(num));
strcat(new_name, num);
- } while (get_property__internal(first, prop, new_name));
+ } while (bproperty_get(first, prop, new_name));
BLI_strncpy(prop->name, new_name, sizeof(prop->name));
}
}
}
-bProperty *get_ob_property(Object *ob, const char *name)
+bProperty *BKE_bproperty_object_get(Object *ob, const char *name)
{
return BLI_findstring(&ob->prop, name, offsetof(bProperty, name));
}
-void set_ob_property(Object *ob, bProperty *propc)
+void BKE_bproperty_object_set(Object *ob, bProperty *propc)
{
bProperty *prop;
- prop = get_ob_property(ob, propc->name);
+ prop = BKE_bproperty_object_get(ob, propc->name);
if (prop) {
- free_property(prop);
+ BKE_bproperty_free(prop);
BLI_remlink(&ob->prop, prop);
}
- BLI_addtail(&ob->prop, copy_property(propc));
+ BLI_addtail(&ob->prop, BKE_bproperty_copy(propc));
}
/* negative: prop is smaller
* positive: prop is larger
*/
-int compare_property(bProperty *prop, const char *str)
+#if 0 /* UNUSED */
+int BKE_bproperty_cmp(bProperty *prop, const char *str)
{
// extern int Gdfra; /* sector.c */
float fvalue, ftest;
@@ -237,8 +241,9 @@ int compare_property(bProperty *prop, const char *str)
return 0;
}
+#endif
-void set_property(bProperty *prop, const char *str)
+void BKE_bproperty_set(bProperty *prop, const char *str)
{
// extern int Gdfra; /* sector.c */
@@ -262,7 +267,7 @@ void set_property(bProperty *prop, const char *str)
}
-void add_property(bProperty *prop, const char *str)
+void BKE_bproperty_add(bProperty *prop, const char *str)
{
// extern int Gdfra; /* sector.c */
@@ -282,7 +287,7 @@ void add_property(bProperty *prop, const char *str)
}
/* reads value of property, sets it in chars in str */
-void set_property_valstr(bProperty *prop, char *str)
+void BKE_bproperty_set_valstr(bProperty *prop, char *str)
{
// extern int Gdfra; /* sector.c */
@@ -303,11 +308,13 @@ void set_property_valstr(bProperty *prop, char *str)
}
}
+#if 0 /* UNUSED */
void cp_property(bProperty *prop1, bProperty *prop2)
{
char str[128];
- set_property_valstr(prop2, str);
+ BKE_bproperty_set_valstr(prop2, str);
- set_property(prop1, str);
+ BKE_bproperty_set(prop1, str);
}
+#endif
diff --git a/source/blender/blenkernel/intern/report.c b/source/blender/blenkernel/intern/report.c
index 3a66ec23412..d925d736358 100644
--- a/source/blender/blenkernel/intern/report.c
+++ b/source/blender/blenkernel/intern/report.c
@@ -34,6 +34,8 @@
#include "BLI_dynstr.h"
#include "BLI_utildefines.h"
+#include "BLF_translation.h"
+
#include "BKE_report.h"
#include "BKE_global.h" /* G.background only */
@@ -44,15 +46,24 @@
static const char *report_type_str(int type)
{
switch (type) {
- case RPT_DEBUG: return "Debug";
- case RPT_INFO: return "Info";
- case RPT_OPERATOR: return "Operator";
- case RPT_WARNING: return "Warning";
- case RPT_ERROR: return "Error";
- case RPT_ERROR_INVALID_INPUT: return "Invalid Input Error";
- case RPT_ERROR_INVALID_CONTEXT: return "Invalid Context Error";
- case RPT_ERROR_OUT_OF_MEMORY: return "Out Of Memory Error";
- default: return "Undefined Type";
+ case RPT_DEBUG:
+ return TIP_("Debug");
+ case RPT_INFO:
+ return TIP_("Info");
+ case RPT_OPERATOR:
+ return TIP_("Operator");
+ case RPT_WARNING:
+ return TIP_("Warning");
+ case RPT_ERROR:
+ return TIP_("Error");
+ case RPT_ERROR_INVALID_INPUT:
+ return TIP_("Invalid Input Error");
+ case RPT_ERROR_INVALID_CONTEXT:
+ return TIP_("Invalid Context Error");
+ case RPT_ERROR_OUT_OF_MEMORY:
+ return TIP_("Out Of Memory Error");
+ default:
+ return TIP_("Undefined Type");
}
}
@@ -87,10 +98,11 @@ void BKE_reports_clear(ReportList *reports)
reports->list.first = reports->list.last = NULL;
}
-void BKE_report(ReportList *reports, ReportType type, const char *message)
+void BKE_report(ReportList *reports, ReportType type, const char *_message)
{
Report *report;
int len;
+ const char *message = TIP_(_message);
/* in background mode always print otherwise there are cases the errors wont be displayed,
* but still add to the report list since this is used for python exception handling */
@@ -114,14 +126,16 @@ void BKE_report(ReportList *reports, ReportType type, const char *message)
}
}
-void BKE_reportf(ReportList *reports, ReportType type, const char *format, ...)
+void BKE_reportf(ReportList *reports, ReportType type, const char *_format, ...)
{
DynStr *ds;
Report *report;
va_list args;
+ const char *format = TIP_(_format);
if (G.background || !reports || ((reports->flag & RPT_PRINT) && (type >= reports->printlevel))) {
- va_start(args, format);
+ printf("%s: ", report_type_str(type));
+ va_start(args, _format);
vprintf(format, args);
va_end(args);
fprintf(stdout, "\n"); /* otherise each report needs to include a \n */
@@ -132,7 +146,7 @@ void BKE_reportf(ReportList *reports, ReportType type, const char *format, ...)
report = MEM_callocN(sizeof(Report), "Report");
ds = BLI_dynstr_new();
- va_start(args, format);
+ va_start(args, _format);
BLI_dynstr_vappendf(ds, format, args);
va_end(args);
@@ -147,10 +161,11 @@ void BKE_reportf(ReportList *reports, ReportType type, const char *format, ...)
}
}
-void BKE_reports_prepend(ReportList *reports, const char *prepend)
+void BKE_reports_prepend(ReportList *reports, const char *_prepend)
{
Report *report;
DynStr *ds;
+ const char *prepend = TIP_(_prepend);
if (!reports)
return;
@@ -169,18 +184,19 @@ void BKE_reports_prepend(ReportList *reports, const char *prepend)
}
}
-void BKE_reports_prependf(ReportList *reports, const char *prepend, ...)
+void BKE_reports_prependf(ReportList *reports, const char *_prepend, ...)
{
Report *report;
DynStr *ds;
va_list args;
+ const char *prepend = TIP_(_prepend);
if (!reports)
return;
for (report = reports->list.first; report; report = report->next) {
ds = BLI_dynstr_new();
- va_start(args, prepend);
+ va_start(args, _prepend);
BLI_dynstr_vappendf(ds, prepend, args);
va_end(args);
diff --git a/source/blender/blenkernel/intern/sca.c b/source/blender/blenkernel/intern/sca.c
index 7d9d2f02c06..eb4e0d9c679 100644
--- a/source/blender/blenkernel/intern/sca.c
+++ b/source/blender/blenkernel/intern/sca.c
@@ -210,7 +210,7 @@ void unlink_controllers(ListBase *lb)
bController *cont;
for (cont= lb->first; cont; cont= cont->next)
- unlink_controller(cont);
+ unlink_controller(cont);
}
void free_controller(bController *cont)
@@ -536,7 +536,7 @@ void clear_sca_new_poins(void)
ob= G.main->object.first;
while (ob) {
clear_sca_new_poins_ob(ob);
- ob= ob->id.next;
+ ob= ob->id.next;
}
}
@@ -552,7 +552,7 @@ void set_sca_new_poins_ob(Object *ob)
if (sens->flag & SENS_NEW) {
for (a=0; a<sens->totlinks; a++) {
if (sens->links[a] && sens->links[a]->mynew)
- sens->links[a]= sens->links[a]->mynew;
+ sens->links[a] = sens->links[a]->mynew;
}
}
sens= sens->next;
@@ -563,7 +563,7 @@ void set_sca_new_poins_ob(Object *ob)
if (cont->flag & CONT_NEW) {
for (a=0; a<cont->totlinks; a++) {
if ( cont->links[a] && cont->links[a]->mynew)
- cont->links[a]= cont->links[a]->mynew;
+ cont->links[a] = cont->links[a]->mynew;
}
}
cont= cont->next;
@@ -624,7 +624,7 @@ void set_sca_new_poins(void)
ob= G.main->object.first;
while (ob) {
set_sca_new_poins_ob(ob);
- ob= ob->id.next;
+ ob= ob->id.next;
}
}
@@ -696,7 +696,7 @@ void sca_remove_ob_poin(Object *obt, Object *ob)
if (sta->target == ob) sta->target = NULL;
}
act= act->next;
- }
+ }
}
/* ******************** INTERFACE ******************* */
@@ -875,3 +875,20 @@ void unlink_logicbricks(void **poin, void ***ppoin, short *tot)
return;
}
}
+
+const char *sca_state_name_get(Object *ob, short bit)
+{
+ bController *cont;
+ unsigned int mask;
+
+ mask = (1<<bit);
+ cont = ob->controllers.first;
+ while (cont) {
+ if (cont->state_mask & mask) {
+ return cont->name;
+ }
+ cont = cont->next;
+ }
+ return NULL;
+}
+
diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c
index 2dec72560a2..a1918b77a1e 100644
--- a/source/blender/blenkernel/intern/scene.c
+++ b/source/blender/blenkernel/intern/scene.c
@@ -54,6 +54,7 @@
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
#include "BLI_callbacks.h"
+#include "BLI_string.h"
#include "BKE_anim.h"
#include "BKE_animsys.h"
@@ -135,8 +136,6 @@ Scene *BKE_scene_copy(Scene *sce, int type)
MEM_freeN(scen->toolsettings);
}
else {
- ImageFormatData *im_format, *im_formatn;
-
scen = BKE_libblock_copy(&sce->id);
BLI_duplicatelist(&(scen->base), &(sce->base));
@@ -174,11 +173,12 @@ Scene *BKE_scene_copy(Scene *sce, int type)
}
/* copy color management settings */
- im_format = &sce->r.im_format;
- im_formatn = &scen->r.im_format;
-
BKE_color_managed_display_settings_copy(&scen->display_settings, &sce->display_settings);
BKE_color_managed_view_settings_copy(&scen->view_settings, &sce->view_settings);
+ BKE_color_managed_view_settings_copy(&scen->r.im_format.view_settings, &sce->r.im_format.view_settings);
+
+ BLI_strncpy(scen->sequencer_colorspace_settings.name, sce->sequencer_colorspace_settings.name,
+ sizeof(scen->sequencer_colorspace_settings.name));
}
/* tool settings */
@@ -325,7 +325,7 @@ void BKE_scene_free(Scene *sce)
BKE_paint_free(&sce->toolsettings->imapaint.paint);
MEM_freeN(sce->toolsettings);
- sce->toolsettings = NULL;
+ sce->toolsettings = NULL;
}
if (sce->theDag) {
@@ -354,6 +354,7 @@ Scene *BKE_scene_add(const char *name)
Scene *sce;
ParticleEditSettings *pset;
int a;
+ const char *colorspace_name;
sce = BKE_libblock_alloc(&bmain->scene, ID_SCE, name);
sce->lay = sce->layact = 1;
@@ -367,8 +368,8 @@ Scene *BKE_scene_add(const char *name)
sce->r.ysch = 1080;
sce->r.xasp = 1;
sce->r.yasp = 1;
- sce->r.xparts = 8;
- sce->r.yparts = 8;
+ sce->r.tilex = 256;
+ sce->r.tiley = 256;
sce->r.mblur_samples = 1;
sce->r.filtertype = R_FILTER_MITCH;
sce->r.size = 50;
@@ -387,7 +388,7 @@ Scene *BKE_scene_add(const char *name)
sce->r.edgeint = 10;
sce->r.ocres = 128;
- /* OCIO_TODO: for forwards compatibiliy only, so if no tonecurve are used,
+ /* OCIO_TODO: for forwards compatibility only, so if no tonecurve are used,
* images would look in the same way as in current blender
*
* perhaps at some point should be completely deprecated?
@@ -435,7 +436,7 @@ Scene *BKE_scene_add(const char *name)
sce->toolsettings->cornertype = 1;
sce->toolsettings->degr = 90;
sce->toolsettings->step = 9;
- sce->toolsettings->turn = 1;
+ sce->toolsettings->turn = 1;
sce->toolsettings->extr_offs = 1;
sce->toolsettings->doublimit = 0.001;
sce->toolsettings->segments = 32;
@@ -445,6 +446,7 @@ Scene *BKE_scene_add(const char *name)
sce->toolsettings->uvcalc_cubesize = 1.0f;
sce->toolsettings->uvcalc_mapdir = 1;
sce->toolsettings->uvcalc_mapalign = 1;
+ sce->toolsettings->uvcalc_margin = 0.001f;
sce->toolsettings->unwrapper = 1;
sce->toolsettings->select_thresh = 0.01f;
sce->toolsettings->jointrilimit = 0.8f;
@@ -567,8 +569,13 @@ Scene *BKE_scene_add(const char *name)
sound_create_scene(sce);
+ /* color management */
+ colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER);
+
BKE_color_managed_display_settings_init(&sce->display_settings);
BKE_color_managed_view_settings_init(&sce->view_settings);
+ BLI_strncpy(sce->sequencer_colorspace_settings.name, colorspace_name,
+ sizeof(sce->sequencer_colorspace_settings.name));
return sce;
}
@@ -748,7 +755,7 @@ int BKE_scene_base_iter_next(Scene **scene, int val, Base **base, Object **ob)
* this enters eternal loop because of
* makeDispListMBall getting called inside of group_duplilist */
if ((*base)->object->dup_group == NULL) {
- duplilist = object_duplilist((*scene), (*base)->object);
+ duplilist = object_duplilist((*scene), (*base)->object, FALSE);
dupob = duplilist->first;
@@ -951,7 +958,7 @@ float BKE_scene_frame_get_from_ctime(Scene *scene, const float frame)
{
float ctime = frame;
ctime += scene->r.subframe;
- ctime *= scene->r.framelen;
+ ctime *= scene->r.framelen;
return ctime;
}
@@ -1035,7 +1042,7 @@ void BKE_scene_update_tagged(Main *bmain, Scene *scene)
/* flush recalc flags to dependencies */
DAG_ids_flush_tagged(bmain);
- scene->physics_settings.quick_cache_step = 0;
+ /* removed calls to quick_cache, see pointcache.c */
/* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later
* when trying to find materials with drivers that need evaluating [#32017]
@@ -1058,10 +1065,6 @@ void BKE_scene_update_tagged(Main *bmain, Scene *scene)
BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0);
}
- /* quick point cache updates */
- if (scene->physics_settings.quick_cache_step)
- BKE_ptcache_quick_cache_all(bmain, scene);
-
/* notify editors and python about recalc */
BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST);
DAG_ids_check_recalc(bmain, scene, FALSE);
@@ -1110,6 +1113,11 @@ void BKE_scene_update_for_newframe(Main *bmain, Scene *sce, unsigned int lay)
BKE_animsys_evaluate_all_animation(bmain, sce, ctime);
/*...done with recusrive funcs */
+ /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later
+ * when trying to find materials with drivers that need evaluating [#32017]
+ */
+ tag_main_idcode(bmain, ID_MA, FALSE);
+
/* BKE_object_handle_update() on all objects, groups and sets */
scene_update_tagged_recursive(bmain, sce, sce);
@@ -1186,7 +1194,7 @@ int BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *s
int get_render_subsurf_level(RenderData *r, int lvl)
{
if (r->mode & R_SIMPLIFY)
- return MIN2(r->simplify_subsurf, lvl);
+ return min_ii(r->simplify_subsurf, lvl);
else
return lvl;
}
@@ -1202,7 +1210,7 @@ int get_render_child_particle_number(RenderData *r, int num)
int get_render_shadow_samples(RenderData *r, int samples)
{
if ((r->mode & R_SIMPLIFY) && samples > 0)
- return MIN2(r->simplify_shadowsamples, samples);
+ return min_ii(r->simplify_shadowsamples, samples);
else
return samples;
}
@@ -1270,9 +1278,11 @@ void BKE_scene_disable_color_management(Scene *scene)
ColorManagedDisplaySettings *display_settings = &scene->display_settings;
ColorManagedViewSettings *view_settings = &scene->view_settings;
const char *view;
+ const char *none_display_name;
+
+ none_display_name = IMB_colormanagement_display_get_none_name();
- /* NOTE: None display with Default view should always exist in OCIO configuration, otherwise it wouldn't work as expected */
- BLI_strncpy(display_settings->display_device, "None", sizeof(display_settings->display_device));
+ BLI_strncpy(display_settings->display_device, none_display_name, sizeof(display_settings->display_device));
view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
@@ -1280,3 +1290,8 @@ void BKE_scene_disable_color_management(Scene *scene)
BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
}
}
+
+int BKE_scene_check_color_management_enabled(const Scene *scene)
+{
+ return strcmp(scene->display_settings.display_device, "None") != 0;
+}
diff --git a/source/blender/blenkernel/intern/seqeffects.c b/source/blender/blenkernel/intern/seqeffects.c
index eaf3ec384c8..469881020c1 100644
--- a/source/blender/blenkernel/intern/seqeffects.c
+++ b/source/blender/blenkernel/intern/seqeffects.c
@@ -62,14 +62,14 @@ static void slice_get_byte_buffers(const SeqRenderData *context, const ImBuf *ib
{
int offset = 4 * start_line * context->rectx;
- *rect1 = (unsigned char*) ibuf1->rect + offset;
- *rect_out = (unsigned char*) out->rect + offset;
+ *rect1 = (unsigned char *)ibuf1->rect + offset;
+ *rect_out = (unsigned char *)out->rect + offset;
if (ibuf2)
- *rect2 = (unsigned char*) ibuf2->rect + offset;
+ *rect2 = (unsigned char *)ibuf2->rect + offset;
if (ibuf3)
- *rect3 = (unsigned char*) ibuf3->rect + offset;
+ *rect3 = (unsigned char *)ibuf3->rect + offset;
}
static void slice_get_float_buffers(const SeqRenderData *context, const ImBuf *ibuf1, const ImBuf *ibuf2,
@@ -600,7 +600,7 @@ static void makeGammaTables(float gamma)
color_step = 1.0f / RE_GAMMA_TABLE_SIZE;
inv_color_step = (float) RE_GAMMA_TABLE_SIZE;
- /* We could squeeze out the two range tables to gain some memory */
+ /* We could squeeze out the two range tables to gain some memory */
for (i = 0; i < RE_GAMMA_TABLE_SIZE; i++) {
color_domain_table[i] = i * color_step;
gamma_range_table[i] = pow(color_domain_table[i], valid_gamma);
@@ -609,9 +609,9 @@ static void makeGammaTables(float gamma)
/* The end of the table should match 1.0 carefully. In order to avoid
* rounding errors, we just set this explicitly. The last segment may
- * have a different length than the other segments, but our
- * interpolation is insensitive to that
- */
+ * have a different length than the other segments, but our
+ * interpolation is insensitive to that
+ */
color_domain_table[RE_GAMMA_TABLE_SIZE] = 1.0;
gamma_range_table[RE_GAMMA_TABLE_SIZE] = 1.0;
inv_gamma_range_table[RE_GAMMA_TABLE_SIZE] = 1.0;
@@ -1178,7 +1178,7 @@ static void do_mul_effect_float(float facf0, float facf1, int x, int y, float *r
fac3 = facf1;
/* formula:
- * fac*(a*b) + (1-fac)*a => fac*a*(b-1)+a
+ * fac * (a * b) + (1 - fac) * a => fac * a * (b - 1) + a
*/
while (y--) {
@@ -1353,7 +1353,7 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f
hyp2 = fabsf(angle * x + y + (-(yo - posy * 0.5f) - angle * (xo - posx * 0.5f))) * wipezone->pythangle;
}
- hwidth = minf(hwidth, fabsf(b3 - b1) / 2.0f);
+ hwidth = min_ff(hwidth, fabsf(b3 - b1) / 2.0f);
if (b2 < b1 && b2 < b3) {
output = in_band(hwidth, hyp, 0, 1);
@@ -2373,7 +2373,7 @@ static ImBuf *do_solid_color(SeqRenderData context, Sequence *seq, float UNUSED(
rect[1] = col1[1];
rect[2] = col1[2];
rect[3] = 255;
- }
+ }
}
}
@@ -2609,7 +2609,7 @@ static void store_icu_yrange_speed(Sequence *seq, short UNUSED(adrcode), float *
*ymin = 0.0;
*ymax = seq->len;
}
- }
+ }
}
void BKE_sequence_effect_speed_rebuild_map(Scene *scene, Sequence *seq, int force)
diff --git a/source/blender/blenkernel/intern/sequencer.c b/source/blender/blenkernel/intern/sequencer.c
index 8d7ca94ed48..80ea00fc703 100644
--- a/source/blender/blenkernel/intern/sequencer.c
+++ b/source/blender/blenkernel/intern/sequencer.c
@@ -53,6 +53,8 @@
#include "BLI_threads.h"
#include "BLI_utildefines.h"
+#include "BLF_translation.h"
+
#include "BKE_animsys.h"
#include "BKE_global.h"
#include "BKE_image.h"
@@ -313,7 +315,7 @@ void BKE_sequencer_editing_free(Scene *scene)
static void sequencer_imbuf_assign_spaces(Scene *scene, ImBuf *ibuf)
{
- IMB_colormanagement_imbuf_assign_float_space(ibuf, &scene->sequencer_colorspace_settings);
+ IMB_colormanagement_assign_float_colorspace(ibuf, scene->sequencer_colorspace_settings.name);
}
void BKE_sequencer_imbuf_to_sequencer_space(Scene *scene, ImBuf *ibuf, int make_float)
@@ -461,7 +463,7 @@ static void seq_array(Editing *ed, Sequence ***seqarray, int *tot, int use_point
seq_build_array(&ed->seqbase, &array, 0);
}
-void BKE_seqence_iterator_begin(Editing *ed, SeqIterator *iter, int use_pointer)
+void BKE_sequence_iterator_begin(Editing *ed, SeqIterator *iter, int use_pointer)
{
memset(iter, 0, sizeof(*iter));
seq_array(ed, &iter->array, &iter->tot, use_pointer);
@@ -473,7 +475,7 @@ void BKE_seqence_iterator_begin(Editing *ed, SeqIterator *iter, int use_pointer)
}
}
-void BKE_seqence_iterator_next(SeqIterator *iter)
+void BKE_sequence_iterator_next(SeqIterator *iter)
{
if (++iter->cur < iter->tot)
iter->seq = iter->array[iter->cur];
@@ -481,7 +483,7 @@ void BKE_seqence_iterator_next(SeqIterator *iter)
iter->valid = 0;
}
-void BKE_seqence_iterator_end(SeqIterator *iter)
+void BKE_sequence_iterator_end(SeqIterator *iter)
{
if (iter->array)
MEM_freeN(iter->array);
@@ -507,8 +509,8 @@ static void seq_update_sound_bounds_recursive_rec(Scene *scene, Sequence *metase
* since sound is played outside of evaluating the imbufs, */
for (seq = metaseq->seqbase.first; seq; seq = seq->next) {
if (seq->type == SEQ_TYPE_META) {
- seq_update_sound_bounds_recursive_rec(scene, seq, maxi(start, metaseq_start(seq)),
- mini(end, metaseq_end(seq)));
+ seq_update_sound_bounds_recursive_rec(scene, seq, max_ii(start, metaseq_start(seq)),
+ min_ii(end, metaseq_end(seq)));
}
else if (ELEM(seq->type, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SCENE)) {
if (seq->scene_sound) {
@@ -717,7 +719,7 @@ void BKE_sequence_reload_new_file(Scene *scene, Sequence *seq, int lock_range)
#ifdef WITH_AUDASPACE
if (!seq->sound)
return;
- seq->len = ceil(AUD_getInfo(seq->sound->playback_handle).length * FPS);
+ seq->len = ceil((double)AUD_getInfo(seq->sound->playback_handle).length * FPS);
seq->len -= seq->anim_startofs;
seq->len -= seq->anim_endofs;
if (seq->len < 0) {
@@ -843,7 +845,7 @@ static int seqbase_unique_name_recursive_cb(Sequence *seq, void *arg_pt)
return 1;
}
-void BKE_seqence_base_unique_name_recursive(ListBase *seqbasep, Sequence *seq)
+void BKE_sequence_base_unique_name_recursive(ListBase *seqbasep, Sequence *seq)
{
SeqUniqueInfo sui;
char *dot;
@@ -991,7 +993,7 @@ static float give_stripelem_index(Sequence *seq, float cfra)
if (seq->type & SEQ_TYPE_EFFECT) {
end = seq->enddisp;
- }
+ }
if (end < sta) {
return -1;
@@ -1835,8 +1837,6 @@ static ImBuf *input_preprocess(SeqRenderData context, Sequence *seq, float cfra,
StripCrop c = {0};
StripTransform t = {0};
int sx, sy, dx, dy;
- double xscale = 1.0;
- double yscale = 1.0;
if (is_proxy_image) {
double f = seq_rendersize_to_scale_factor(context.preview_render_size);
@@ -1853,14 +1853,6 @@ static ImBuf *input_preprocess(SeqRenderData context, Sequence *seq, float cfra,
t = *seq->strip->transform;
}
- xscale = context.scene->r.xsch ? ((double) context.rectx / (double) context.scene->r.xsch) : 1.0;
- yscale = context.scene->r.ysch ? ((double) context.recty / (double) context.scene->r.ysch) : 1.0;
-
- c.left *= xscale; c.right *= xscale;
- c.top *= yscale; c.bottom *= yscale;
-
- t.xofs *= xscale; t.yofs *= yscale;
-
sx = ibuf->x - c.left - c.right;
sy = ibuf->y - c.top - c.bottom;
dx = sx;
@@ -1892,7 +1884,7 @@ static ImBuf *input_preprocess(SeqRenderData context, Sequence *seq, float cfra,
ibuf = i;
}
- }
+ }
if (seq->flag & SEQ_FLIPX) {
IMB_flipx(ibuf);
@@ -1975,17 +1967,20 @@ static ImBuf *copy_from_ibuf_still(SeqRenderData context, Sequence *seq, float n
static void copy_to_ibuf_still(SeqRenderData context, Sequence *seq, float nr, ImBuf *ibuf)
{
+ /* warning: ibuf may be NULL if the video fails to load */
if (nr == 0 || nr == seq->len - 1) {
/* we have to store a copy, since the passed ibuf
* could be preprocessed afterwards (thereby silently
* changing the cached image... */
ibuf = IMB_dupImBuf(ibuf);
- sequencer_imbuf_assign_spaces(context.scene, ibuf);
+ if (ibuf) {
+ sequencer_imbuf_assign_spaces(context.scene, ibuf);
+ }
if (nr == 0) {
BKE_sequencer_cache_put(context, seq, seq->start, SEQ_STRIPELEM_IBUF_STARTSTILL, ibuf);
- }
+ }
if (nr == seq->len - 1) {
BKE_sequencer_cache_put(context, seq, seq->start, SEQ_STRIPELEM_IBUF_ENDSTILL, ibuf);
@@ -2186,7 +2181,7 @@ static ImBuf *seq_render_movieclip_strip(SeqRenderData context, Sequence *seq, f
memset(&user, 0, sizeof(MovieClipUser));
- BKE_movieclip_user_set_frame(&user, nr + seq->anim_startofs);
+ BKE_movieclip_user_set_frame(&user, nr + seq->anim_startofs + seq->clip->start_frame);
user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
@@ -2344,9 +2339,11 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float
* -jahka
*/
- int rendering = G.is_rendering;
- int doseq;
- int doseq_gl = G.is_rendering ? /*(scene->r.seq_flag & R_SEQ_GL_REND)*/ 0 : /*(scene->r.seq_flag & R_SEQ_GL_PREV)*/ 1;
+ const short is_rendering = G.is_rendering;
+ const int do_seq_gl = G.is_rendering ?
+ 0 /* (context.scene->r.seq_flag & R_SEQ_GL_REND) */ :
+ (context.scene->r.seq_flag & R_SEQ_GL_PREV);
+ int do_seq;
int have_seq = FALSE;
Scene *scene;
@@ -2363,9 +2360,10 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float
oldcfra = scene->r.cfra;
scene->r.cfra = frame;
- if (seq->scene_camera)
+ if (seq->scene_camera) {
camera = seq->scene_camera;
- else {
+ }
+ else {
BKE_scene_camera_switch_update(scene);
camera = scene->camera;
}
@@ -2376,7 +2374,7 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float
}
/* prevent eternal loop */
- doseq = context.scene->r.scemode & R_DOSEQ;
+ do_seq = context.scene->r.scemode & R_DOSEQ;
context.scene->r.scemode &= ~R_DOSEQ;
#ifdef DURIAN_CAMERA_SWITCH
@@ -2386,8 +2384,11 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float
#else
(void)oldmarkers;
#endif
-
- if (sequencer_view3d_cb && BLI_thread_is_main() && doseq_gl && (scene == context.scene || have_seq == 0) && camera) {
+
+ if ((sequencer_view3d_cb && do_seq_gl && camera) &&
+ (BLI_thread_is_main() == TRUE) &&
+ ((have_seq == FALSE) || (scene == context.scene)))
+ {
char err_out[256] = "unknown";
/* for old scened this can be uninitialized,
* should probably be added to do_versions at some point if the functionality stays */
@@ -2407,14 +2408,14 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float
RenderResult rres;
/* XXX: this if can be removed when sequence preview rendering uses the job system */
- if (rendering || context.scene != scene) {
+ if (is_rendering || context.scene != scene) {
if (re == NULL)
re = RE_NewRender(scene->id.name);
RE_BlenderFrame(re, context.bmain, scene, NULL, camera, scene->lay, frame, FALSE);
/* restore previous state after it was toggled on & off by RE_BlenderFrame */
- G.is_rendering = rendering;
+ G.is_rendering = is_rendering;
}
RE_AcquireResultImage(re, &rres);
@@ -2441,7 +2442,7 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float
}
/* restore */
- context.scene->r.scemode |= doseq;
+ context.scene->r.scemode |= do_seq;
scene->r.cfra = oldcfra;
@@ -2583,17 +2584,19 @@ static ImBuf *do_render_strip_uncached(SeqRenderData context, Sequence *seq, flo
case SEQ_TYPE_MOVIECLIP:
{
ibuf = seq_render_movieclip_strip(context, seq, nr);
- sequencer_imbuf_assign_spaces(context.scene, ibuf);
- if (ibuf && use_preprocess) {
+ if (ibuf) {
+ /* duplicate frame so movie cache wouldn't be confused by sequencer's stuff */
ImBuf *i = IMB_dupImBuf(ibuf);
-
IMB_freeImBuf(ibuf);
-
ibuf = i;
+
+ if (ibuf->rect_float)
+ BKE_sequencer_imbuf_to_sequencer_space(context.scene, ibuf, FALSE);
+
+ copy_to_ibuf_still(context, seq, nr, ibuf);
}
- copy_to_ibuf_still(context, seq, nr, ibuf);
break;
}
@@ -2830,7 +2833,7 @@ ImBuf *BKE_sequencer_give_ibuf(SeqRenderData context, float cfra, int chanshown)
count = BLI_countlist(&ed->metastack);
if ((chanshown < 0) && (count > 0)) {
- count = MAX2(count + chanshown, 0);
+ count = max_ii(count + chanshown, 0);
seqbasep = ((MetaStack *)BLI_findlink(&ed->metastack, count))->oldbasep;
}
else {
@@ -3040,10 +3043,27 @@ int BKE_sequence_check_depend(Sequence *seq, Sequence *cur)
return TRUE;
}
+static void sequence_do_invalidate_dependent(Sequence *seq, ListBase *seqbase)
+{
+ Sequence *cur;
+
+ for (cur = seqbase->first; cur; cur = cur->next) {
+ if (cur == seq)
+ continue;
+
+ if (BKE_sequence_check_depend(seq, cur)) {
+ BKE_sequencer_cache_cleanup_sequence(cur);
+ BKE_sequencer_preprocessed_cache_cleanup_sequence(cur);
+ }
+
+ if (cur->seqbase.first)
+ sequence_do_invalidate_dependent(seq, &cur->seqbase);
+ }
+}
+
static void sequence_invalidate_cache(Scene *scene, Sequence *seq, int invalidate_self, int invalidate_preprocess)
{
Editing *ed = scene->ed;
- Sequence *cur;
/* invalidate cache for current sequence */
if (invalidate_self)
@@ -3057,17 +3077,11 @@ static void sequence_invalidate_cache(Scene *scene, Sequence *seq, int invalidat
BKE_sequencer_preprocessed_cache_cleanup_sequence(seq);
/* invalidate cache for all dependent sequences */
- SEQ_BEGIN (ed, cur)
- {
- if (cur == seq)
- continue;
- if (BKE_sequence_check_depend(seq, cur)) {
- BKE_sequencer_cache_cleanup_sequence(cur);
- BKE_sequencer_preprocessed_cache_cleanup_sequence(cur);
- }
- }
- SEQ_END
+ /* NOTE: can not use SEQ_BEGIN/SEQ_END here because that macro will change sequence's depth,
+ * which makes transformation routines work incorrect
+ */
+ sequence_do_invalidate_dependent(seq, &ed->seqbase);
}
void BKE_sequence_invalidate_cache(Scene *scene, Sequence *seq)
@@ -3075,7 +3089,7 @@ void BKE_sequence_invalidate_cache(Scene *scene, Sequence *seq)
sequence_invalidate_cache(scene, seq, TRUE, TRUE);
}
-void BKE_sequence_invalidate_deendent(Scene *scene, Sequence *seq)
+void BKE_sequence_invalidate_dependent(Scene *scene, Sequence *seq)
{
sequence_invalidate_cache(scene, seq, FALSE, TRUE);
}
@@ -3188,7 +3202,7 @@ int BKE_sequence_tx_get_final_left(Sequence *seq, int metaclip)
{
if (metaclip && seq->tmp) {
/* return the range clipped by the parents range */
- return maxi(BKE_sequence_tx_get_final_left(seq, 0), BKE_sequence_tx_get_final_left((Sequence *)seq->tmp, TRUE));
+ return max_ii(BKE_sequence_tx_get_final_left(seq, 0), BKE_sequence_tx_get_final_left((Sequence *)seq->tmp, TRUE));
}
else {
return (seq->start - seq->startstill) + seq->startofs;
@@ -3199,7 +3213,7 @@ int BKE_sequence_tx_get_final_right(Sequence *seq, int metaclip)
{
if (metaclip && seq->tmp) {
/* return the range clipped by the parents range */
- return mini(BKE_sequence_tx_get_final_right(seq, 0), BKE_sequence_tx_get_final_right((Sequence *)seq->tmp, TRUE));
+ return min_ii(BKE_sequence_tx_get_final_right(seq, 0), BKE_sequence_tx_get_final_right((Sequence *)seq->tmp, TRUE));
}
else {
return ((seq->start + seq->len) + seq->endstill) - seq->endofs;
@@ -3451,7 +3465,7 @@ int BKE_sequence_base_shuffle(ListBase *seqbasep, Sequence *test, Scene *evil_sc
for (seq = seqbasep->first; seq; seq = seq->next) {
if (seq->machine == orig_machine)
- new_frame = MAX2(new_frame, seq->enddisp);
+ new_frame = max_ii(new_frame, seq->enddisp);
}
test->machine = orig_machine;
@@ -3476,10 +3490,10 @@ static int shuffle_seq_time_offset_test(ListBase *seqbasep, char dir)
for (seq_other = seqbasep->first; seq_other; seq_other = seq_other->next) {
if (!seq_other->tmp && seq_overlap(seq, seq_other)) {
if (dir == 'L') {
- offset = MIN2(offset, seq_other->startdisp - seq->enddisp);
+ offset = min_ii(offset, seq_other->startdisp - seq->enddisp);
}
else {
- offset = MAX2(offset, seq_other->enddisp - seq->startdisp);
+ offset = max_ii(offset, seq_other->enddisp - seq->startdisp);
}
}
}
@@ -3664,26 +3678,26 @@ int BKE_sequence_swap(Sequence *seq_a, Sequence *seq_b, const char **error_str)
char name[sizeof(seq_a->name)];
if (seq_a->len != seq_b->len) {
- *error_str = "Strips must be the same length";
+ *error_str = N_("Strips must be the same length");
return 0;
}
- /* type checking, could be more advanced but disalow sound vs non-sound copy */
+ /* type checking, could be more advanced but disallow sound vs non-sound copy */
if (seq_a->type != seq_b->type) {
if (seq_a->type == SEQ_TYPE_SOUND_RAM || seq_b->type == SEQ_TYPE_SOUND_RAM) {
- *error_str = "Strips were not compatible";
+ *error_str = N_("Strips were not compatible");
return 0;
}
/* disallow effects to swap with non-effects strips */
if ((seq_a->type & SEQ_TYPE_EFFECT) != (seq_b->type & SEQ_TYPE_EFFECT)) {
- *error_str = "Strips were not compatible";
+ *error_str = N_("Strips were not compatible");
return 0;
}
if ((seq_a->type & SEQ_TYPE_EFFECT) && (seq_b->type & SEQ_TYPE_EFFECT)) {
if (BKE_sequence_effect_get_num_inputs(seq_a->type) != BKE_sequence_effect_get_num_inputs(seq_b->type)) {
- *error_str = "Strips must have the same number of inputs";
+ *error_str = N_("Strips must have the same number of inputs");
return 0;
}
}
@@ -3880,7 +3894,7 @@ static void seq_load_apply(Scene *scene, Sequence *seq, SeqLoadInfo *seq_load)
{
if (seq) {
BLI_strncpy(seq->name + 2, seq_load->name, sizeof(seq->name) - 2);
- BKE_seqence_base_unique_name_recursive(&scene->ed->seqbase, seq);
+ BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seq);
if (seq_load->flag & SEQ_LOAD_FRAME_ADVANCE) {
seq_load->start_frame += (seq->enddisp - seq->startdisp);
@@ -3967,10 +3981,10 @@ Sequence *BKE_sequencer_add_sound_strip(bContext *C, ListBase *seqbasep, SeqLoad
sound = sound_new_file(bmain, seq_load->path); /* handles relative paths */
if (sound == NULL || sound->playback_handle == NULL) {
- /*
+#if 0
if (op)
BKE_report(op->reports, RPT_ERROR, "Unsupported audio format");
- */
+#endif
return NULL;
}
@@ -3979,10 +3993,10 @@ Sequence *BKE_sequencer_add_sound_strip(bContext *C, ListBase *seqbasep, SeqLoad
if (info.specs.channels == AUD_CHANNELS_INVALID) {
sound_delete(bmain, sound);
- /*
+#if 0
if (op)
BKE_report(op->reports, RPT_ERROR, "Unsupported audio format");
- */
+#endif
return NULL;
}
@@ -3991,11 +4005,11 @@ Sequence *BKE_sequencer_add_sound_strip(bContext *C, ListBase *seqbasep, SeqLoad
seq->type = SEQ_TYPE_SOUND_RAM;
seq->sound = sound;
BLI_strncpy(seq->name + 2, "Sound", SEQ_NAME_MAXSTR - 2);
- BKE_seqence_base_unique_name_recursive(&scene->ed->seqbase, seq);
+ BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seq);
/* basic defaults */
seq->strip = strip = MEM_callocN(sizeof(Strip), "strip");
- seq->len = ceil(info.length * FPS);
+ seq->len = (int)ceil((double)info.length * FPS);
strip->us = 1;
/* we only need 1 element to store the filename */
@@ -4051,7 +4065,7 @@ Sequence *BKE_sequencer_add_movie_strip(bContext *C, ListBase *seqbasep, SeqLoad
seq->anim = an;
seq->anim_preseek = IMB_anim_get_preseek(an);
BLI_strncpy(seq->name + 2, "Movie", SEQ_NAME_MAXSTR - 2);
- BKE_seqence_base_unique_name_recursive(&scene->ed->seqbase, seq);
+ BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seq);
/* basic defaults */
seq->strip = strip = MEM_callocN(sizeof(Strip), "strip");
@@ -4163,7 +4177,7 @@ static Sequence *seq_dupli(Scene *scene, Scene *scene_to, Sequence *seq, int dup
}
if (dupe_flag & SEQ_DUPE_UNIQUE_NAME)
- BKE_seqence_base_unique_name_recursive(&scene->ed->seqbase, seqn);
+ BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seqn);
if (dupe_flag & SEQ_DUPE_ANIM)
BKE_sequencer_dupe_animdata(scene, seq->name + 2, seqn->name + 2);
@@ -4218,7 +4232,7 @@ void BKE_sequence_base_dupli_recursive(Scene *scene, Scene *scene_to, ListBase *
/* called on draw, needs to be fast,
* we could cache and use a flag if we want to make checks for file paths resolving for eg. */
-int BKE_seqence_is_valid_check(Sequence *seq)
+int BKE_sequence_is_valid_check(Sequence *seq)
{
switch (seq->type) {
case SEQ_TYPE_MASK:
diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c
index 9a8bcaabe0c..96faec389df 100644
--- a/source/blender/blenkernel/intern/shrinkwrap.c
+++ b/source/blender/blenkernel/intern/shrinkwrap.c
@@ -84,7 +84,7 @@
#endif
/* get derived mesh */
-//TODO is anyfunction that does this? returning the derivedFinal without we caring if its in edit mode or not?
+/* TODO is anyfunction that does this? returning the derivedFinal without we caring if its in edit mode or not? */
DerivedMesh *object_get_derived_final(Object *ob)
{
Mesh *me = ob->data;
@@ -149,7 +149,7 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
return;
}
- //Setup nearest
+ /* Setup nearest */
nearest.index = -1;
nearest.dist = FLT_MAX;
#ifndef __APPLE__
@@ -159,10 +159,12 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
float *co = calc->vertexCos[i];
float tmp_co[3];
float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
- if (weight == 0.0f) continue;
+ if (weight == 0.0f) {
+ continue;
+ }
- //Convert the vertex to tree coordinates
+ /* Convert the vertex to tree coordinates */
if (calc->vert) {
copy_v3_v3(tmp_co, calc->vert[i].co);
}
@@ -171,11 +173,11 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
}
space_transform_apply(&calc->local2target, tmp_co);
- //Use local proximity heuristics (to reduce the nearest search)
- //
- //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
- //so we can initiate the "nearest.dist" with the expected value to that last hit.
- //This will lead in prunning of the search tree.
+ /* Use local proximity heuristics (to reduce the nearest search)
+ *
+ * If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
+ * so we can initiate the "nearest.dist" with the expected value to that last hit.
+ * This will lead in prunning of the search tree. */
if (nearest.index != -1)
nearest.dist = len_squared_v3v3(tmp_co, nearest.co);
else
@@ -184,23 +186,27 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
- //Found the nearest vertex
+ /* Found the nearest vertex */
if (nearest.index != -1) {
- //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
- float dist = sasqrt(nearest.dist);
- if (dist > FLT_EPSILON) weight *= (dist - calc->keepDist) / dist;
+ /* Adjusting the vertex weight,
+ * so that after interpolating it keeps a certain distance from the nearest position */
+ if (nearest.dist > FLT_EPSILON) {
+ const float dist = sqrtf(nearest.dist);
+ weight *= (dist - calc->keepDist) / dist;
+ }
- //Convert the coordinates back to mesh coordinates
+ /* Convert the coordinates back to mesh coordinates */
copy_v3_v3(tmp_co, nearest.co);
space_transform_invert(&calc->local2target, tmp_co);
- interp_v3_v3v3(co, co, tmp_co, weight); //linear interpolation
+ interp_v3_v3v3(co, co, tmp_co, weight); /* linear interpolation */
}
}
free_bvhtree_from_mesh(&treeData);
}
+
/*
* This function raycast a single vertex and updates the hit if the "hit" is considered valid.
* Returns TRUE if "hit" was updated.
@@ -209,16 +215,24 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
* MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (front faces hits are ignored)
* MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (back faces hits are ignored)
*/
-int normal_projection_project_vertex(char options, const float vert[3], const float dir[3], const SpaceTransform *transf, BVHTree *tree, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
+int normal_projection_project_vertex(char options, const float vert[3], const float dir[3],
+ const SpaceTransform *transf,
+ BVHTree *tree, BVHTreeRayHit *hit,
+ BVHTree_RayCastCallback callback, void *userdata)
{
+ /* don't use this because this dist value could be incompatible
+ * this value used by the callback for comparing prev/new dist values.
+ * also, at the moment there is no need to have a corrected 'dist' value */
+// #define USE_DIST_CORRECT
+
float tmp_co[3], tmp_no[3];
const float *co, *no;
BVHTreeRayHit hit_tmp;
- //Copy from hit (we need to convert hit rays from one space coordinates to the other
+ /* Copy from hit (we need to convert hit rays from one space coordinates to the other */
memcpy(&hit_tmp, hit, sizeof(hit_tmp));
- //Apply space transform (TODO readjust dist)
+ /* Apply space transform (TODO readjust dist) */
if (transf) {
copy_v3_v3(tmp_co, vert);
space_transform_apply(transf, tmp_co);
@@ -228,7 +242,9 @@ int normal_projection_project_vertex(char options, const float vert[3], const fl
space_transform_apply_normal(transf, tmp_no);
no = tmp_no;
+#ifdef USE_DIST_CORRECT
hit_tmp.dist *= mat4_to_scale(((SpaceTransform *)transf)->local2target);
+#endif
}
else {
co = vert;
@@ -249,7 +265,7 @@ int normal_projection_project_vertex(char options, const float vert[3], const fl
/* apply backface */
const float dot = dot_v3v3(dir, hit_tmp.no);
if (((options & MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE) && dot <= 0.0f) ||
- ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f))
+ ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f))
{
return FALSE; /* Ignore hit */
}
@@ -258,9 +274,13 @@ int normal_projection_project_vertex(char options, const float vert[3], const fl
if (transf) {
/* Inverting space transform (TODO make coeherent with the initial dist readjust) */
space_transform_invert(transf, hit_tmp.co);
- hit_tmp.dist = len_v3v3((float *)vert, hit_tmp.co);
+#ifdef USE_DIST_CORRECT
+ hit_tmp.dist = len_v3v3(vert, hit_tmp.co);
+#endif
}
+ BLI_assert(hit_tmp.dist <= hit->dist);
+
memcpy(hit, &hit_tmp, sizeof(hit_tmp));
return TRUE;
}
@@ -272,41 +292,46 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
{
int i;
- //Options about projection direction
+ /* Options about projection direction */
const char use_normal = calc->smd->shrinkOpts;
float proj_axis[3] = {0.0f, 0.0f, 0.0f};
- //Raycast and tree stuff
+ /* Raycast and tree stuff */
+
+ /** \note 'hit.dist' is kept in the targets space, this is only used
+ * for finding the best hit, to get the real dist,
+ * measure the len_v3v3() from the input coord to hit.co */
BVHTreeRayHit hit;
BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
- //auxiliary target
+ /* auxiliary target */
DerivedMesh *auxMesh = NULL;
BVHTreeFromMesh auxData = NULL_BVHTreeFromMesh;
SpaceTransform local2aux;
- //If the user doesn't allows to project in any direction of projection axis
- //then theres nothing todo.
+ /* If the user doesn't allows to project in any direction of projection axis
+ * then theres nothing todo. */
if ((use_normal & (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0)
return;
- //Prepare data to retrieve the direction in which we should project each vertex
+ /* Prepare data to retrieve the direction in which we should project each vertex */
if (calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL) {
if (calc->vert == NULL) return;
}
else {
- //The code supports any axis that is a combination of X,Y,Z
- //although currently UI only allows to set the 3 different axis
+ /* The code supports any axis that is a combination of X,Y,Z
+ * although currently UI only allows to set the 3 different axis */
if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS) proj_axis[0] = 1.0f;
if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS) proj_axis[1] = 1.0f;
if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS) proj_axis[2] = 1.0f;
normalize_v3(proj_axis);
- //Invalid projection direction
- if (dot_v3v3(proj_axis, proj_axis) < FLT_EPSILON)
- return;
+ /* Invalid projection direction */
+ if (len_squared_v3(proj_axis) < FLT_EPSILON) {
+ return;
+ }
}
if (calc->smd->auxTarget) {
@@ -316,7 +341,7 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
SPACE_TRANSFORM_SETUP(&local2aux, calc->ob, calc->smd->auxTarget);
}
- //After sucessufuly build the trees, start projection vertexs
+ /* After sucessufuly build the trees, start projection vertexs */
if (bvhtree_from_mesh_faces(&treeData, calc->target, 0.0, 4, 6) &&
(auxMesh == NULL || bvhtree_from_mesh_faces(&auxData, auxMesh, 0.0, 4, 6)))
{
@@ -327,9 +352,11 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
for (i = 0; i < calc->numVerts; ++i) {
float *co = calc->vertexCos[i];
float tmp_co[3], tmp_no[3];
- float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
+ const float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
- if (weight == 0.0f) continue;
+ if (weight == 0.0f) {
+ continue;
+ }
if (calc->vert) {
/* calc->vert contains verts from derivedMesh */
@@ -351,26 +378,36 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
hit.index = -1;
- hit.dist = 10000.0f; //TODO: we should use FLT_MAX here, but sweepsphere code isn't prepared for that
+ hit.dist = 10000.0f; /* TODO: we should use FLT_MAX here, but sweepsphere code isn't prepared for that */
- //Project over positive direction of axis
+ /* Project over positive direction of axis */
if (use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR) {
- if (auxData.tree)
- normal_projection_project_vertex(0, tmp_co, tmp_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
+ if (auxData.tree) {
+ normal_projection_project_vertex(0, tmp_co, tmp_no,
+ &local2aux, auxData.tree, &hit,
+ auxData.raycast_callback, &auxData);
+ }
- normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
+ normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no,
+ &calc->local2target, treeData.tree, &hit,
+ treeData.raycast_callback, &treeData);
}
- //Project over negative direction of axis
- if (use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR && hit.index == -1) {
+ /* Project over negative direction of axis */
+ if (use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR) {
float inv_no[3];
negate_v3_v3(inv_no, tmp_no);
- if (auxData.tree)
- normal_projection_project_vertex(0, tmp_co, inv_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
+ if (auxData.tree) {
+ normal_projection_project_vertex(0, tmp_co, inv_no,
+ &local2aux, auxData.tree, &hit,
+ auxData.raycast_callback, &auxData);
+ }
- normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
+ normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no,
+ &calc->local2target, treeData.tree, &hit,
+ treeData.raycast_callback, &treeData);
}
@@ -381,7 +418,7 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
}
}
- //free data structures
+ /* free data structures */
free_bvhtree_from_mesh(&treeData);
free_bvhtree_from_mesh(&auxData);
}
@@ -399,19 +436,19 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
BVHTreeNearest nearest = NULL_BVHTreeNearest;
- //Create a bvh-tree of the given target
+ /* Create a bvh-tree of the given target */
BENCH(bvhtree_from_mesh_faces(&treeData, calc->target, 0.0, 2, 6));
if (treeData.tree == NULL) {
OUT_OF_MEMORY();
return;
}
- //Setup nearest
+ /* Setup nearest */
nearest.index = -1;
nearest.dist = FLT_MAX;
- //Find the nearest vertex
+ /* Find the nearest vertex */
#ifndef __APPLE__
#pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc,treeData) schedule(static)
#endif
@@ -421,7 +458,7 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
if (weight == 0.0f) continue;
- //Convert the vertex to tree coordinates
+ /* Convert the vertex to tree coordinates */
if (calc->vert) {
copy_v3_v3(tmp_co, calc->vert[i].co);
}
@@ -430,11 +467,11 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
}
space_transform_apply(&calc->local2target, tmp_co);
- //Use local proximity heuristics (to reduce the nearest search)
- //
- //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
- //so we can initiate the "nearest.dist" with the expected value to that last hit.
- //This will lead in prunning of the search tree.
+ /* Use local proximity heuristics (to reduce the nearest search)
+ *
+ * If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
+ * so we can initiate the "nearest.dist" with the expected value to that last hit.
+ * This will lead in prunning of the search tree. */
if (nearest.index != -1)
nearest.dist = len_squared_v3v3(tmp_co, nearest.co);
else
@@ -442,24 +479,28 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
- //Found the nearest vertex
+ /* Found the nearest vertex */
if (nearest.index != -1) {
if (calc->smd->shrinkOpts & MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE) {
- //Make the vertex stay on the front side of the face
+ /* Make the vertex stay on the front side of the face */
madd_v3_v3v3fl(tmp_co, nearest.co, nearest.no, calc->keepDist);
}
else {
- //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
+ /* Adjusting the vertex weight,
+ * so that after interpolating it keeps a certain distance from the nearest position */
float dist = sasqrt(nearest.dist);
- if (dist > FLT_EPSILON)
- interp_v3_v3v3(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist) / dist); //linear interpolation
- else
+ if (dist > FLT_EPSILON) {
+ /* linear interpolation */
+ interp_v3_v3v3(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist) / dist);
+ }
+ else {
copy_v3_v3(tmp_co, nearest.co);
+ }
}
- //Convert the coordinates back to mesh coordinates
+ /* Convert the coordinates back to mesh coordinates */
space_transform_invert(&calc->local2target, tmp_co);
- interp_v3_v3v3(co, co, tmp_co, weight); //linear interpolation
+ interp_v3_v3v3(co, co, tmp_co, weight); /* linear interpolation */
}
}
@@ -467,24 +508,25 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
}
/* Main shrinkwrap function */
-void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
+void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *ss_mesh = NULL;
ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData;
- //remove loop dependencies on derived meshs (TODO should this be done elsewhere?)
+ /* remove loop dependencies on derived meshs (TODO should this be done elsewhere?) */
if (smd->target == ob) smd->target = NULL;
if (smd->auxTarget == ob) smd->auxTarget = NULL;
- //Configure Shrinkwrap calc data
+ /* Configure Shrinkwrap calc data */
calc.smd = smd;
calc.ob = ob;
calc.numVerts = numVerts;
calc.vertexCos = vertexCos;
- //DeformVertex
+ /* DeformVertex */
calc.vgroup = defgroup_name_index(calc.ob, calc.smd->vgroup_name);
if (dm) {
calc.dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
@@ -497,12 +539,12 @@ void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedM
if (smd->target) {
calc.target = object_get_derived_final(smd->target);
- //TODO there might be several "bugs" on non-uniform scales matrixs
- //because it will no longer be nearest surface, not sphere projection
- //because space has been deformed
+ /* TODO there might be several "bugs" on non-uniform scales matrixs
+ * because it will no longer be nearest surface, not sphere projection
+ * because space has been deformed */
SPACE_TRANSFORM_SETUP(&calc.local2target, ob, smd->target);
- //TODO: smd->keepDist is in global units.. must change to local
+ /* TODO: smd->keepDist is in global units.. must change to local */
calc.keepDist = smd->keepDist;
}
@@ -511,15 +553,15 @@ void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedM
calc.vgroup = defgroup_name_index(calc.ob, smd->vgroup_name);
if (dm != NULL && smd->shrinkType == MOD_SHRINKWRAP_PROJECT) {
- //Setup arrays to get vertexs positions, normals and deform weights
+ /* Setup arrays to get vertexs positions, normals and deform weights */
calc.vert = dm->getVertDataArray(dm, CD_MVERT);
calc.dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
- //Using vertexs positions/normals as if a subsurface was applied
+ /* Using vertexs positions/normals as if a subsurface was applied */
if (smd->subsurfLevels) {
SubsurfModifierData ssmd = {{NULL}};
- ssmd.subdivType = ME_CC_SUBSURF; //catmull clark
- ssmd.levels = smd->subsurfLevels; //levels
+ ssmd.subdivType = ME_CC_SUBSURF; /* catmull clark */
+ ssmd.levels = smd->subsurfLevels; /* levels */
ss_mesh = subsurf_make_derived_from_derived(dm, &ssmd, NULL, (ob->mode & OB_MODE_EDIT) ? SUBSURF_IN_EDIT_MODE : 0);
@@ -532,13 +574,13 @@ void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedM
}
}
- //Just to make sure we are not leaving any memory behind
+ /* Just to make sure we are not leaving any memory behind */
assert(ssmd.emCache == NULL);
assert(ssmd.mCache == NULL);
}
}
- //Projecting target defined - lets work!
+ /* Projecting target defined - lets work! */
if (calc.target) {
switch (smd->shrinkType) {
case MOD_SHRINKWRAP_NEAREST_SURFACE:
@@ -555,8 +597,7 @@ void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedM
}
}
- //free memory
+ /* free memory */
if (ss_mesh)
ss_mesh->release(ss_mesh);
}
-
diff --git a/source/blender/blenkernel/intern/smoke.c b/source/blender/blenkernel/intern/smoke.c
index 5e67e094e43..443aed1fc41 100644
--- a/source/blender/blenkernel/intern/smoke.c
+++ b/source/blender/blenkernel/intern/smoke.c
@@ -51,18 +51,7 @@
#include "BLI_kdtree.h"
#include "BLI_kdopbvh.h"
#include "BLI_utildefines.h"
-
-#include "BKE_bvhutils.h"
-#include "BKE_cdderivedmesh.h"
-#include "BKE_collision.h"
-#include "BKE_customdata.h"
-#include "BKE_DerivedMesh.h"
-#include "BKE_effect.h"
-#include "BKE_modifier.h"
-#include "BKE_particle.h"
-#include "BKE_pointcache.h"
-#include "BKE_smoke.h"
-
+#include "BLI_voxel.h"
#include "DNA_customdata_types.h"
#include "DNA_group_types.h"
@@ -75,8 +64,20 @@
#include "DNA_scene_types.h"
#include "DNA_smoke_types.h"
+#include "BKE_bvhutils.h"
+#include "BKE_cdderivedmesh.h"
+#include "BKE_collision.h"
+#include "BKE_customdata.h"
+#include "BKE_deform.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_effect.h"
+#include "BKE_modifier.h"
+#include "BKE_particle.h"
+#include "BKE_pointcache.h"
#include "BKE_smoke.h"
+#include "RE_shader_ext.h"
+
/* UNUSED so far, may be enabled later */
/* #define USE_SMOKE_COLLISION_DM */
@@ -94,38 +95,38 @@ static LARGE_INTEGER liFrequency;
static LARGE_INTEGER liStartTime;
static LARGE_INTEGER liCurrentTime;
-static void tstart ( void )
+static void tstart(void)
{
- QueryPerformanceFrequency ( &liFrequency );
- QueryPerformanceCounter ( &liStartTime );
+ QueryPerformanceFrequency(&liFrequency);
+ QueryPerformanceCounter(&liStartTime);
}
-static void tend ( void )
+static void tend(void)
{
- QueryPerformanceCounter ( &liCurrentTime );
+ QueryPerformanceCounter(&liCurrentTime);
}
-static double UNUSED_FUNCTION(tval)( void )
+static double tval(void)
{
- return ((double)( (liCurrentTime.QuadPart - liStartTime.QuadPart)* (double)1000.0/(double)liFrequency.QuadPart ));
+ return ((double)( (liCurrentTime.QuadPart - liStartTime.QuadPart) * (double)1000.0 / (double)liFrequency.QuadPart));
}
#else
#include <sys/time.h>
static struct timeval _tstart, _tend;
static struct timezone tz;
-static void tstart ( void )
+static void tstart(void)
{
- gettimeofday ( &_tstart, &tz );
+ gettimeofday(&_tstart, &tz);
}
-static void tend ( void )
+static void tend(void)
{
- gettimeofday ( &_tend,&tz );
+ gettimeofday(&_tend, &tz);
}
-static double UNUSED_FUNCTION(tval)( void )
+static double UNUSED_FUNCTION(tval) (void)
{
double t1, t2;
- t1 = ( double ) _tstart.tv_sec*1000 + ( double ) _tstart.tv_usec/ ( 1000 );
- t2 = ( double ) _tend.tv_sec*1000 + ( double ) _tend.tv_usec/ ( 1000 );
- return t2-t1;
+ t1 = ( double ) _tstart.tv_sec * 1000 + ( double ) _tstart.tv_usec / (1000);
+ t2 = ( double ) _tend.tv_sec * 1000 + ( double ) _tend.tv_usec / (1000);
+ return t2 - t1;
}
#endif
@@ -134,608 +135,238 @@ struct Scene;
struct DerivedMesh;
struct SmokeModifierData;
-#define TRI_UVOFFSET (1./4.)
-
// timestep default value for nice appearance 0.1f
#define DT_DEFAULT 0.1f
-/* forward declerations */
-static void calcTriangleDivs(Object *ob, MVert *verts, int numverts, MFace *tris, int numfaces, int numtris, int **tridivs, float cell_len);
-static void get_cell(const float p0[3], const int res[3], float dx, const float pos[3], int cell[3], int correct);
-static void fill_scs_points(Object *ob, DerivedMesh *dm, SmokeCollSettings *scs);
+#define ADD_IF_LOWER_POS(a, b) (MIN2((a) + (b), MAX2((a), (b))))
+#define ADD_IF_LOWER_NEG(a, b) (MAX2((a) + (b), MIN2((a), (b))))
+#define ADD_IF_LOWER(a, b) (((b) > 0) ? ADD_IF_LOWER_POS((a), (b)) : ADD_IF_LOWER_NEG((a), (b)))
#else /* WITH_SMOKE */
/* Stubs to use when smoke is disabled */
-struct WTURBULENCE *smoke_turbulence_init(int *UNUSED(res), int UNUSED(amplify), int UNUSED(noisetype)) { return NULL; }
-// struct FLUID_3D *smoke_init(int *UNUSED(res), float *UNUSED(p0)) { return NULL; }
+struct WTURBULENCE *smoke_turbulence_init(int *UNUSED(res), int UNUSED(amplify), int UNUSED(noisetype), int UNUSED(use_fire), int UNUSED(use_colors)) { return NULL; }
+//struct FLUID_3D *smoke_init(int *UNUSED(res), float *UNUSED(dx), float *UNUSED(dtdef), int UNUSED(use_heat), int UNUSED(use_fire), int UNUSED(use_colors)) { return NULL; }
void smoke_free(struct FLUID_3D *UNUSED(fluid)) {}
float *smoke_get_density(struct FLUID_3D *UNUSED(fluid)) { return NULL; }
void smoke_turbulence_free(struct WTURBULENCE *UNUSED(wt)) {}
void smoke_initWaveletBlenderRNA(struct WTURBULENCE *UNUSED(wt), float *UNUSED(strength)) {}
-void smoke_initBlenderRNA(struct FLUID_3D *UNUSED(fluid), float *UNUSED(alpha), float *UNUSED(beta), float *UNUSED(dt_factor), float *UNUSED(vorticity), int *UNUSED(border_colli)) {}
-long long smoke_get_mem_req(int UNUSED(xres), int UNUSED(yres), int UNUSED(zres), int UNUSED(amplify)) { return 0; }
-void smokeModifier_do(SmokeModifierData *UNUSED(smd), Scene *UNUSED(scene), Object *UNUSED(ob), DerivedMesh *UNUSED(dm)) {}
+void smoke_initBlenderRNA(struct FLUID_3D *UNUSED(fluid), float *UNUSED(alpha), float *UNUSED(beta), float *UNUSED(dt_factor), float *UNUSED(vorticity),
+ int *UNUSED(border_colli), float *UNUSED(burning_rate), float *UNUSED(flame_smoke), float *UNUSED(flame_smoke_color),
+ float *UNUSED(flame_vorticity), float *UNUSED(flame_ignition_temp), float *UNUSED(flame_max_temp)) {}
+struct DerivedMesh *smokeModifier_do(SmokeModifierData *UNUSED(smd), Scene *UNUSED(scene), Object *UNUSED(ob), DerivedMesh *UNUSED(dm)) { return NULL; }
+float smoke_get_velocity_at(struct Object *UNUSED(ob), float UNUSED(position[3]), float UNUSED(velocity[3])) { return 0.0f; }
+void flame_get_spectrum(unsigned char *UNUSED(spec), int UNUSED(width), float UNUSED(t1), float UNUSED(t2)) {}
#endif /* WITH_SMOKE */
#ifdef WITH_SMOKE
-static int smokeModifier_init (SmokeModifierData *smd, Object *ob, Scene *scene, DerivedMesh *dm)
+void smoke_reallocate_fluid(SmokeDomainSettings *sds, float dx, int res[3], int free_old)
{
- if((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain && !smd->domain->fluid)
- {
- size_t i;
- float min[3] = {FLT_MAX, FLT_MAX, FLT_MAX}, max[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};
- float size[3];
- MVert *verts = dm->getVertArray(dm);
- float scale = 0.0;
- int res;
-
- res = smd->domain->maxres;
-
- // get BB of domain
- for(i = 0; i < dm->getNumVerts(dm); i++)
- {
- float tmp[3];
-
- copy_v3_v3(tmp, verts[i].co);
- mul_m4_v3(ob->obmat, tmp);
-
- // min BB
- min[0] = MIN2(min[0], tmp[0]);
- min[1] = MIN2(min[1], tmp[1]);
- min[2] = MIN2(min[2], tmp[2]);
-
- // max BB
- max[0] = MAX2(max[0], tmp[0]);
- max[1] = MAX2(max[1], tmp[1]);
- max[2] = MAX2(max[2], tmp[2]);
- }
-
- copy_v3_v3(smd->domain->p0, min);
- copy_v3_v3(smd->domain->p1, max);
-
- // calc other res with max_res provided
- sub_v3_v3v3(size, max, min);
-
- // prevent crash when initializing a plane as domain
- if((size[0] < FLT_EPSILON) || (size[1] < FLT_EPSILON) || (size[2] < FLT_EPSILON))
- return 0;
-
- if(size[0] > size[1])
- {
- if(size[0] > size[2])
- {
- scale = res / size[0];
- smd->domain->scale = size[0];
- smd->domain->dx = 1.0f / res;
- smd->domain->res[0] = res;
- smd->domain->res[1] = (int)(size[1] * scale + 0.5);
- smd->domain->res[2] = (int)(size[2] * scale + 0.5);
- }
- else {
- scale = res / size[2];
- smd->domain->scale = size[2];
- smd->domain->dx = 1.0f / res;
- smd->domain->res[2] = res;
- smd->domain->res[0] = (int)(size[0] * scale + 0.5);
- smd->domain->res[1] = (int)(size[1] * scale + 0.5);
- }
- }
- else {
- if(size[1] > size[2])
- {
- scale = res / size[1];
- smd->domain->scale = size[1];
- smd->domain->dx = 1.0f / res;
- smd->domain->res[1] = res;
- smd->domain->res[0] = (int)(size[0] * scale + 0.5);
- smd->domain->res[2] = (int)(size[2] * scale + 0.5);
- }
- else {
- scale = res / size[2];
- smd->domain->scale = size[2];
- smd->domain->dx = 1.0f / res;
- smd->domain->res[2] = res;
- smd->domain->res[0] = (int)(size[0] * scale + 0.5);
- smd->domain->res[1] = (int)(size[1] * scale + 0.5);
- }
- }
-
- // TODO: put in failsafe if res<=0 - dg
-
- // dt max is 0.1
- smd->domain->fluid = smoke_init(smd->domain->res, smd->domain->p0, DT_DEFAULT);
- smd->time = scene->r.cfra;
-
- if(smd->domain->flags & MOD_SMOKE_HIGHRES)
- {
- smd->domain->wt = smoke_turbulence_init(smd->domain->res, smd->domain->amplify + 1, smd->domain->noise);
- smd->domain->res_wt[0] = smd->domain->res[0] * (smd->domain->amplify + 1);
- smd->domain->res_wt[1] = smd->domain->res[1] * (smd->domain->amplify + 1);
- smd->domain->res_wt[2] = smd->domain->res[2] * (smd->domain->amplify + 1);
- smd->domain->dx_wt = smd->domain->dx / (smd->domain->amplify + 1);
- }
-
- if(!smd->domain->shadow)
- smd->domain->shadow = MEM_callocN(sizeof(float) * smd->domain->res[0] * smd->domain->res[1] * smd->domain->res[2], "SmokeDomainShadow");
-
- smoke_initBlenderRNA(smd->domain->fluid, &(smd->domain->alpha), &(smd->domain->beta), &(smd->domain->time_scale), &(smd->domain->vorticity), &(smd->domain->border_collisions));
-
- if(smd->domain->wt)
- {
- smoke_initWaveletBlenderRNA(smd->domain->wt, &(smd->domain->strength));
- }
- return 1;
- }
- else if((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow)
- {
- // handle flow object here
- // XXX TODO
-
- smd->time = scene->r.cfra;
-
- return 1;
- }
- else if((smd->type & MOD_SMOKE_TYPE_COLL))
- {
- // todo: delete this when loading colls work -dg
-
- if(!smd->coll)
- {
- smokeModifier_createType(smd);
- }
-
- if(!smd->coll->points)
- {
- // init collision points
- SmokeCollSettings *scs = smd->coll;
-
- smd->time = scene->r.cfra;
-
- // copy obmat
- copy_m4_m4(scs->mat, ob->obmat);
- copy_m4_m4(scs->mat_old, ob->obmat);
-
- DM_ensure_tessface(dm);
- fill_scs_points(ob, dm, scs);
- }
-
- if(!smd->coll->bvhtree)
- {
- smd->coll->bvhtree = NULL; // bvhtree_build_from_smoke ( ob->obmat, dm->getTessFaceArray(dm), dm->getNumTessFaces(dm), dm->getVertArray(dm), dm->getNumVerts(dm), 0.0 );
- }
- return 1;
+ int use_heat = (sds->active_fields & SM_ACTIVE_HEAT);
+ int use_fire = (sds->active_fields & (SM_ACTIVE_HEAT | SM_ACTIVE_FIRE));
+ int use_colors = (sds->active_fields & SM_ACTIVE_COLORS);
+
+ if (free_old && sds->fluid)
+ smoke_free(sds->fluid);
+ if (!MIN3(res[0], res[1], res[2])) {
+ sds->fluid = NULL;
+ return;
}
-
- return 2;
+ sds->fluid = smoke_init(res, dx, DT_DEFAULT, use_heat, use_fire, use_colors);
+ smoke_initBlenderRNA(sds->fluid, &(sds->alpha), &(sds->beta), &(sds->time_scale), &(sds->vorticity), &(sds->border_collisions),
+ &(sds->burning_rate), &(sds->flame_smoke), sds->flame_smoke_color, &(sds->flame_vorticity), &(sds->flame_ignition), &(sds->flame_max_temp));
+
+ /* reallocate shadow buffer */
+ if (sds->shadow)
+ MEM_freeN(sds->shadow);
+ sds->shadow = MEM_callocN(sizeof(float) * res[0] * res[1] * res[2], "SmokeDomainShadow");
}
-static void fill_scs_points(Object *ob, DerivedMesh *dm, SmokeCollSettings *scs)
+void smoke_reallocate_highres_fluid(SmokeDomainSettings *sds, float dx, int res[3], int free_old)
{
- MVert *mvert = dm->getVertArray(dm);
- MFace *mface = dm->getTessFaceArray(dm);
- int i = 0, divs = 0;
-
- // DG TODO: need to do this dynamically according to the domain object!
- float cell_len = scs->dx;
- int newdivs = 0;
- int quads = 0, facecounter = 0;
+ int use_fire = (sds->active_fields & (SM_ACTIVE_HEAT | SM_ACTIVE_FIRE));
+ int use_colors = (sds->active_fields & SM_ACTIVE_COLORS);
- // count quads
- for(i = 0; i < dm->getNumTessFaces(dm); i++)
- {
- if(mface[i].v4)
- quads++;
+ if (free_old && sds->wt)
+ smoke_turbulence_free(sds->wt);
+ if (!MIN3(res[0], res[1], res[2])) {
+ sds->wt = NULL;
+ return;
}
+ sds->wt = smoke_turbulence_init(res, sds->amplify + 1, sds->noise, use_fire, use_colors);
+ sds->res_wt[0] = res[0] * (sds->amplify + 1);
+ sds->res_wt[1] = res[1] * (sds->amplify + 1);
+ sds->res_wt[2] = res[2] * (sds->amplify + 1);
+ sds->dx_wt = dx / (sds->amplify + 1);
+ smoke_initWaveletBlenderRNA(sds->wt, &(sds->strength));
+}
- scs->numtris = dm->getNumTessFaces(dm) + quads;
- scs->tridivs = NULL;
- calcTriangleDivs(ob, mvert, dm->getNumVerts(dm), mface, dm->getNumTessFaces(dm), scs->numtris, &(scs->tridivs), cell_len);
+/* convert global position to domain cell space */
+static void smoke_pos_to_cell(SmokeDomainSettings *sds, float pos[3])
+{
+ mul_m4_v3(sds->imat, pos);
+ sub_v3_v3(pos, sds->p0);
+ pos[0] *= 1.0f / sds->cell_size[0];
+ pos[1] *= 1.0f / sds->cell_size[1];
+ pos[2] *= 1.0f / sds->cell_size[2];
+}
- // count triangle divisions
- for(i = 0; i < dm->getNumTessFaces(dm) + quads; i++)
- {
- divs += (scs->tridivs[3 * i] + 1) * (scs->tridivs[3 * i + 1] + 1) * (scs->tridivs[3 * i + 2] + 1);
- }
+/* set domain resolution and dimensions from object derivedmesh */
+static void smoke_set_domain_from_derivedmesh(SmokeDomainSettings *sds, Object *ob, DerivedMesh *dm)
+{
+ size_t i;
+ float min[3] = {FLT_MAX, FLT_MAX, FLT_MAX}, max[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};
+ float size[3];
+ MVert *verts = dm->getVertArray(dm);
+ float scale = 0.0;
+ int res;
- scs->points = MEM_callocN(sizeof(float) * (dm->getNumVerts(dm) + divs) * 3, "SmokeCollPoints");
- scs->points_old = MEM_callocN(sizeof(float) * (dm->getNumVerts(dm) + divs) * 3, "SmokeCollPointsOld");
+ res = sds->maxres;
- for(i = 0; i < dm->getNumVerts(dm); i++)
+ // get BB of domain
+ for (i = 0; i < dm->getNumVerts(dm); i++)
{
- float tmpvec[3];
- copy_v3_v3(tmpvec, mvert[i].co);
- // mul_m4_v3(ob->obmat, tmpvec); // DG: use local coordinates, we save MAT anyway
- copy_v3_v3(&scs->points[i * 3], tmpvec);
+ // min BB
+ min[0] = MIN2(min[0], verts[i].co[0]);
+ min[1] = MIN2(min[1], verts[i].co[1]);
+ min[2] = MIN2(min[2], verts[i].co[2]);
+
+ // max BB
+ max[0] = MAX2(max[0], verts[i].co[0]);
+ max[1] = MAX2(max[1], verts[i].co[1]);
+ max[2] = MAX2(max[2], verts[i].co[2]);
}
-
- for(i = 0, facecounter = 0; i < dm->getNumTessFaces(dm); i++)
- {
- int again = 0;
- do
- {
- int j, k;
- int divs1 = scs->tridivs[3 * facecounter + 0];
- int divs2 = scs->tridivs[3 * facecounter + 1];
- //int divs3 = scs->tridivs[3 * facecounter + 2];
- float side1[3], side2[3], trinormorg[3], trinorm[3];
-
- if(again == 1 && mface[i].v4)
- {
- sub_v3_v3v3(side1, mvert[ mface[i].v3 ].co, mvert[ mface[i].v1 ].co);
- sub_v3_v3v3(side2, mvert[ mface[i].v4 ].co, mvert[ mface[i].v1 ].co);
- }
- else {
- sub_v3_v3v3(side1, mvert[ mface[i].v2 ].co, mvert[ mface[i].v1 ].co);
- sub_v3_v3v3(side2, mvert[ mface[i].v3 ].co, mvert[ mface[i].v1 ].co);
- }
- cross_v3_v3v3(trinormorg, side1, side2);
- normalize_v3(trinormorg);
- copy_v3_v3(trinorm, trinormorg);
- mul_v3_fl(trinorm, 0.25 * cell_len);
+ /* set domain bounds */
+ copy_v3_v3(sds->p0, min);
+ copy_v3_v3(sds->p1, max);
+ sds->dx = 1.0f / res;
- for(j = 0; j <= divs1; j++)
- {
- for(k = 0; k <= divs2; k++)
- {
- float p1[3], p2[3], p3[3], p[3]={0,0,0};
- const float uf = (float)(j + TRI_UVOFFSET) / (float)(divs1 + 0.0);
- const float vf = (float)(k + TRI_UVOFFSET) / (float)(divs2 + 0.0);
- float tmpvec[3];
-
- if(uf+vf > 1.0)
- {
- // printf("bigger - divs1: %d, divs2: %d\n", divs1, divs2);
- continue;
- }
+ /* calculate domain dimensions */
+ sub_v3_v3v3(size, max, min);
+ copy_v3_v3(sds->cell_size, size);
+ mul_v3_v3(size, ob->size);
+ copy_v3_v3(sds->global_size, size);
+ copy_v3_v3(sds->dp0, min);
- copy_v3_v3(p1, mvert[ mface[i].v1 ].co);
- if(again == 1 && mface[i].v4)
- {
- copy_v3_v3(p2, mvert[ mface[i].v3 ].co);
- copy_v3_v3(p3, mvert[ mface[i].v4 ].co);
- }
- else {
- copy_v3_v3(p2, mvert[ mface[i].v2 ].co);
- copy_v3_v3(p3, mvert[ mface[i].v3 ].co);
- }
+ invert_m4_m4(sds->imat, ob->obmat);
- mul_v3_fl(p1, (1.0-uf-vf));
- mul_v3_fl(p2, uf);
- mul_v3_fl(p3, vf);
-
- add_v3_v3v3(p, p1, p2);
- add_v3_v3(p, p3);
-
- if(newdivs > divs)
- printf("mem problem\n");
-
- // mMovPoints.push_back(p + trinorm);
- add_v3_v3v3(tmpvec, p, trinorm);
- // mul_m4_v3(ob->obmat, tmpvec); // DG: use local coordinates, we save MAT anyway
- copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], tmpvec);
- newdivs++;
-
- if(newdivs > divs)
- printf("mem problem\n");
-
- // mMovPoints.push_back(p - trinorm);
- copy_v3_v3(tmpvec, p);
- sub_v3_v3(tmpvec, trinorm);
- // mul_m4_v3(ob->obmat, tmpvec); // DG: use local coordinates, we save MAT anyway
- copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], tmpvec);
- newdivs++;
- }
- }
-
- if(again == 0 && mface[i].v4)
- again++;
- else
- again = 0;
-
- facecounter++;
+ // prevent crash when initializing a plane as domain
+ if ((size[0] < FLT_EPSILON) || (size[1] < FLT_EPSILON) || (size[2] < FLT_EPSILON))
+ return;
- } while(again!=0);
+ /* define grid resolutions from longest domain side */
+ if (size[0] > MAX2(size[1], size[2])) {
+ scale = res / size[0];
+ sds->scale = size[0] / ob->size[0];
+ sds->base_res[0] = res;
+ sds->base_res[1] = (int)(size[1] * scale + 0.5);
+ sds->base_res[2] = (int)(size[2] * scale + 0.5);
}
-
- scs->numverts = dm->getNumVerts(dm);
- // DG TODO: also save triangle count?
-
- scs->numpoints = dm->getNumVerts(dm) + newdivs;
-
- for(i = 0; i < scs->numpoints * 3; i++)
- {
- scs->points_old[i] = scs->points[i];
+ else if (size[1] > MAX2(size[0], size[2])) {
+ scale = res / size[1];
+ sds->scale = size[1] / ob->size[1];
+ sds->base_res[0] = (int)(size[0] * scale + 0.5);
+ sds->base_res[1] = res;
+ sds->base_res[2] = (int)(size[2] * scale + 0.5);
+ }
+ else {
+ scale = res / size[2];
+ sds->scale = size[2] / ob->size[2];
+ sds->base_res[0] = (int)(size[0] * scale + 0.5);
+ sds->base_res[1] = (int)(size[1] * scale + 0.5);
+ sds->base_res[2] = res;
}
-}
+ /* set cell size */
+ sds->cell_size[0] /= (float)sds->base_res[0];
+ sds->cell_size[1] /= (float)sds->base_res[1];
+ sds->cell_size[2] /= (float)sds->base_res[2];
+}
-static void fill_scs_points_anim(Object *UNUSED(ob), DerivedMesh *dm, SmokeCollSettings *scs)
+static int smokeModifier_init(SmokeModifierData *smd, Object *ob, Scene *scene, DerivedMesh *dm)
{
- MVert *mvert = dm->getVertArray(dm);
- MFace *mface = dm->getTessFaceArray(dm);
- int quads = 0, numtris = 0, facecounter = 0;
- unsigned int i = 0;
- int divs = 0, newdivs = 0;
-
- // DG TODO: need to do this dynamically according to the domain object!
- float cell_len = scs->dx;
-
- // count quads
- for(i = 0; i < dm->getNumTessFaces(dm); i++)
+ if ((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain && !smd->domain->fluid)
{
- if(mface[i].v4)
- quads++;
- }
+ SmokeDomainSettings *sds = smd->domain;
+ int res[3];
+ /* set domain dimensions from derivedmesh */
+ smoke_set_domain_from_derivedmesh(sds, ob, dm);
+ /* reset domain values */
+ zero_v3_int(sds->shift);
+ zero_v3(sds->shift_f);
+ add_v3_fl(sds->shift_f, 0.5f);
+ zero_v3(sds->prev_loc);
+ mul_m4_v3(ob->obmat, sds->prev_loc);
+
+ /* set resolutions */
+ if (smd->domain->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
+ res[0] = res[1] = res[2] = 1; /* use minimum res for adaptive init */
+ }
+ else {
+ VECCOPY(res, sds->base_res);
+ }
+ VECCOPY(sds->res, res);
+ sds->total_cells = sds->res[0] * sds->res[1] * sds->res[2];
+ sds->res_min[0] = sds->res_min[1] = sds->res_min[2] = 0;
+ VECCOPY(sds->res_max, res);
- numtris = dm->getNumTessFaces(dm) + quads;
+ /* allocate fluid */
+ smoke_reallocate_fluid(sds, sds->dx, sds->res, 0);
- // check if mesh changed topology
- if(scs->numtris != numtris)
- return;
- if(scs->numverts != dm->getNumVerts(dm))
- return;
+ smd->time = scene->r.cfra;
- // update new positions
- for(i = 0; i < dm->getNumVerts(dm); i++)
- {
- float tmpvec[3];
- copy_v3_v3(tmpvec, mvert[i].co);
- copy_v3_v3(&scs->points[i * 3], tmpvec);
- }
+ /* allocate highres fluid */
+ if (sds->flags & MOD_SMOKE_HIGHRES) {
+ smoke_reallocate_highres_fluid(sds, sds->dx, sds->res, 0);
+ }
+ /* allocate shadow buffer */
+ if (!sds->shadow)
+ sds->shadow = MEM_callocN(sizeof(float) * sds->res[0] * sds->res[1] * sds->res[2], "SmokeDomainShadow");
- // for every triangle // update div points
- for(i = 0, facecounter = 0; i < dm->getNumTessFaces(dm); i++)
+ return 1;
+ }
+ else if ((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow)
{
- int again = 0;
- do
- {
- int j, k;
- int divs1 = scs->tridivs[3 * facecounter + 0];
- int divs2 = scs->tridivs[3 * facecounter + 1];
- float srcside1[3], srcside2[3], destside1[3], destside2[3], src_trinormorg[3], dest_trinormorg[3], src_trinorm[3], dest_trinorm[3];
-
- if(again == 1 && mface[i].v4)
- {
- sub_v3_v3v3(srcside1, &scs->points_old[mface[i].v3 * 3], &scs->points_old[mface[i].v1 * 3]);
- sub_v3_v3v3(destside1, &scs->points[mface[i].v3 * 3], &scs->points[mface[i].v1 * 3]);
-
- sub_v3_v3v3(srcside2, &scs->points_old[mface[i].v4 * 3], &scs->points_old[mface[i].v1 * 3]);
- sub_v3_v3v3(destside2, &scs->points[mface[i].v4 * 3], &scs->points[mface[i].v1 * 3]);
- }
- else {
- sub_v3_v3v3(srcside1, &scs->points_old[mface[i].v2 * 3], &scs->points_old[mface[i].v1 * 3]);
- sub_v3_v3v3(destside1, &scs->points[mface[i].v2 * 3], &scs->points[mface[i].v1 * 3]);
-
- sub_v3_v3v3(srcside2, &scs->points_old[mface[i].v3 * 3], &scs->points_old[mface[i].v1 * 3]);
- sub_v3_v3v3(destside2, &scs->points[mface[i].v3 * 3], &scs->points[mface[i].v1 * 3]);
- }
-
- cross_v3_v3v3(src_trinormorg, srcside1, srcside2);
- cross_v3_v3v3(dest_trinormorg, destside1, destside2);
-
- normalize_v3(src_trinormorg);
- normalize_v3(dest_trinormorg);
-
- copy_v3_v3(src_trinorm, src_trinormorg);
- copy_v3_v3(dest_trinorm, dest_trinormorg);
-
- mul_v3_fl(src_trinorm, 0.25 * cell_len);
- mul_v3_fl(dest_trinorm, 0.25 * cell_len);
-
- for(j = 0; j <= divs1; j++)
- {
- for(k = 0; k <= divs2; k++)
- {
- float src_p1[3], src_p2[3], src_p3[3], src_p[3]={0,0,0};
- float dest_p1[3], dest_p2[3], dest_p3[3], dest_p[3]={0,0,0};
- const float uf = (float)(j + TRI_UVOFFSET) / (float)(divs1 + 0.0);
- const float vf = (float)(k + TRI_UVOFFSET) / (float)(divs2 + 0.0);
- float src_tmpvec[3], dest_tmpvec[3];
-
- if(uf+vf > 1.0)
- {
- // printf("bigger - divs1: %d, divs2: %d\n", divs1, divs2);
- continue;
- }
-
- copy_v3_v3(src_p1, &scs->points_old[mface[i].v1 * 3]);
- copy_v3_v3(dest_p1, &scs->points[mface[i].v1 * 3]);
- if(again == 1 && mface[i].v4)
- {
- copy_v3_v3(src_p2, &scs->points_old[mface[i].v3 * 3]);
- copy_v3_v3(dest_p2, &scs->points[mface[i].v3 * 3]);
-
- copy_v3_v3(src_p3,&scs->points_old[mface[i].v4 * 3]);
- copy_v3_v3(dest_p3, &scs->points[mface[i].v4 * 3]);
- }
- else {
- copy_v3_v3(src_p2, &scs->points_old[mface[i].v2 * 3]);
- copy_v3_v3(dest_p2, &scs->points[mface[i].v2 * 3]);
- copy_v3_v3(src_p3, &scs->points_old[mface[i].v3 * 3]);
- copy_v3_v3(dest_p3, &scs->points[mface[i].v3 * 3]);
- }
-
- mul_v3_fl(src_p1, (1.0-uf-vf));
- mul_v3_fl(dest_p1, (1.0-uf-vf));
-
- mul_v3_fl(src_p2, uf);
- mul_v3_fl(dest_p2, uf);
-
- mul_v3_fl(src_p3, vf);
- mul_v3_fl(dest_p3, vf);
-
- add_v3_v3v3(src_p, src_p1, src_p2);
- add_v3_v3v3(dest_p, dest_p1, dest_p2);
-
- add_v3_v3(src_p, src_p3);
- add_v3_v3(dest_p, dest_p3);
-
- if(newdivs > divs)
- printf("mem problem\n");
-
- // mMovPoints.push_back(p + trinorm);
- add_v3_v3v3(src_tmpvec, src_p, src_trinorm);
- add_v3_v3v3(dest_tmpvec, dest_p, dest_trinorm);
-
- // mul_m4_v3(ob->obmat, tmpvec); // DG: use local coordinates, we save MAT anyway
- copy_v3_v3(&scs->points_old[3 * (dm->getNumVerts(dm) + newdivs)], src_tmpvec);
- copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], dest_tmpvec);
- newdivs++;
-
- if(newdivs > divs)
- printf("mem problem\n");
-
- // mMovPoints.push_back(p - trinorm);
- copy_v3_v3(src_tmpvec, src_p);
- copy_v3_v3(dest_tmpvec, dest_p);
-
- sub_v3_v3(src_tmpvec, src_trinorm);
- sub_v3_v3(dest_tmpvec, dest_trinorm);
-
- // mul_m4_v3(ob->obmat, tmpvec); // DG: use local coordinates, we save MAT anyway
- copy_v3_v3(&scs->points_old[3 * (dm->getNumVerts(dm) + newdivs)], src_tmpvec);
- copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], dest_tmpvec);
- newdivs++;
- }
- }
-
- if(again == 0 && mface[i].v4)
- again++;
- else
- again = 0;
-
- facecounter++;
+ smd->time = scene->r.cfra;
- } while(again!=0);
+ return 1;
}
-
- // scs->numpoints = dm->getNumVerts(dm) + newdivs;
-
-}
-
-/*! init triangle divisions */
-static void calcTriangleDivs(Object *ob, MVert *verts, int UNUSED(numverts), MFace *faces, int numfaces, int numtris, int **tridivs, float cell_len)
-{
- // mTriangleDivs1.resize( faces.size() );
- // mTriangleDivs2.resize( faces.size() );
- // mTriangleDivs3.resize( faces.size() );
-
- size_t i = 0, facecounter = 0;
- float maxscale[3] = {1,1,1}; // = channelFindMaxVf(mcScale); get max scale value
- float maxpart = ABS(maxscale[0]);
- float scaleFac = 0;
- float fsTri = 0;
- if(ABS(maxscale[1])>maxpart) maxpart = ABS(maxscale[1]);
- if(ABS(maxscale[2])>maxpart) maxpart = ABS(maxscale[2]);
- scaleFac = 1.0 / maxpart;
- // featureSize = mLevel[mMaxRefine].nodeSize
- fsTri = cell_len * 0.75 * scaleFac; // fsTri = cell_len * 0.9;
-
- if(*tridivs)
- MEM_freeN(*tridivs);
-
- *tridivs = MEM_callocN(sizeof(int) * numtris * 3, "Smoke_Tridivs");
-
- for(i = 0, facecounter = 0; i < numfaces; i++)
+ else if ((smd->type & MOD_SMOKE_TYPE_COLL))
{
- float p0[3], p1[3], p2[3];
- float side1[3];
- float side2[3];
- float side3[3];
- int divs1=0, divs2=0, divs3=0;
-
- copy_v3_v3(p0, verts[faces[i].v1].co);
- mul_m4_v3(ob->obmat, p0);
- copy_v3_v3(p1, verts[faces[i].v2].co);
- mul_m4_v3(ob->obmat, p1);
- copy_v3_v3(p2, verts[faces[i].v3].co);
- mul_m4_v3(ob->obmat, p2);
-
- sub_v3_v3v3(side1, p1, p0);
- sub_v3_v3v3(side2, p2, p0);
- sub_v3_v3v3(side3, p1, p2);
-
- if(dot_v3v3(side1, side1) > fsTri*fsTri)
- {
- float tmp = normalize_v3(side1);
- divs1 = (int)ceil(tmp/fsTri);
- }
- if(dot_v3v3(side2, side2) > fsTri*fsTri)
- {
- float tmp = normalize_v3(side2);
- divs2 = (int)ceil(tmp/fsTri);
-
- /*
- // debug
- if(i==0)
- printf("b tmp: %f, fsTri: %f, divs2: %d\n", tmp, fsTri, divs2);
- */
-
+ if (!smd->coll)
+ {
+ smokeModifier_createType(smd);
}
- (*tridivs)[3 * facecounter + 0] = divs1;
- (*tridivs)[3 * facecounter + 1] = divs2;
- (*tridivs)[3 * facecounter + 2] = divs3;
-
- // TODO quad case
- if(faces[i].v4)
- {
- divs1=0, divs2=0, divs3=0;
-
- facecounter++;
-
- copy_v3_v3(p0, verts[faces[i].v3].co);
- mul_m4_v3(ob->obmat, p0);
- copy_v3_v3(p1, verts[faces[i].v4].co);
- mul_m4_v3(ob->obmat, p1);
- copy_v3_v3(p2, verts[faces[i].v1].co);
- mul_m4_v3(ob->obmat, p2);
-
- sub_v3_v3v3(side1, p1, p0);
- sub_v3_v3v3(side2, p2, p0);
- sub_v3_v3v3(side3, p1, p2);
-
- if(dot_v3v3(side1, side1) > fsTri*fsTri)
- {
- float tmp = normalize_v3(side1);
- divs1 = (int)ceil(tmp/fsTri);
- }
- if(dot_v3v3(side2, side2) > fsTri*fsTri)
- {
- float tmp = normalize_v3(side2);
- divs2 = (int)ceil(tmp/fsTri);
- }
+ smd->time = scene->r.cfra;
- (*tridivs)[3 * facecounter + 0] = divs1;
- (*tridivs)[3 * facecounter + 1] = divs2;
- (*tridivs)[3 * facecounter + 2] = divs3;
- }
- facecounter++;
+ return 1;
}
+
+ return 2;
}
#endif /* WITH_SMOKE */
static void smokeModifier_freeDomain(SmokeModifierData *smd)
{
- if(smd->domain)
+ if (smd->domain)
{
- if(smd->domain->shadow)
- MEM_freeN(smd->domain->shadow);
- smd->domain->shadow = NULL;
+ if (smd->domain->shadow)
+ MEM_freeN(smd->domain->shadow);
+ smd->domain->shadow = NULL;
- if(smd->domain->fluid)
+ if (smd->domain->fluid)
smoke_free(smd->domain->fluid);
- if(smd->domain->wt)
+ if (smd->domain->wt)
smoke_turbulence_free(smd->domain->wt);
- if(smd->domain->effector_weights)
- MEM_freeN(smd->domain->effector_weights);
+ if (smd->domain->effector_weights)
+ MEM_freeN(smd->domain->effector_weights);
smd->domain->effector_weights = NULL;
BKE_ptcache_free_list(&(smd->domain->ptcaches[0]));
@@ -748,16 +379,10 @@ static void smokeModifier_freeDomain(SmokeModifierData *smd)
static void smokeModifier_freeFlow(SmokeModifierData *smd)
{
- if(smd->flow)
+ if (smd->flow)
{
-/*
- if(smd->flow->bvh)
- {
- free_bvhtree_from_mesh(smd->flow->bvh);
- MEM_freeN(smd->flow->bvh);
- }
- smd->flow->bvh = NULL;
-*/
+ if (smd->flow->dm) smd->flow->dm->release(smd->flow->dm);
+ if (smd->flow->verts_old) MEM_freeN(smd->flow->verts_old);
MEM_freeN(smd->flow);
smd->flow = NULL;
}
@@ -765,40 +390,22 @@ static void smokeModifier_freeFlow(SmokeModifierData *smd)
static void smokeModifier_freeCollision(SmokeModifierData *smd)
{
- if(smd->coll)
+ if (smd->coll)
{
SmokeCollSettings *scs = smd->coll;
- if(scs->numpoints)
+ if (scs->numverts)
{
- if(scs->points)
+ if (scs->verts_old)
{
- MEM_freeN(scs->points);
- scs->points = NULL;
- }
- if(scs->points_old)
- {
- MEM_freeN(scs->points_old);
- scs->points_old = NULL;
- }
- if(scs->tridivs)
- {
- MEM_freeN(scs->tridivs);
- scs->tridivs = NULL;
+ MEM_freeN(scs->verts_old);
+ scs->verts_old = NULL;
}
}
- if(scs->bvhtree)
- {
- BLI_bvhtree_free(scs->bvhtree);
- scs->bvhtree = NULL;
- }
-
-#ifdef USE_SMOKE_COLLISION_DM
- if(smd->coll->dm)
+ if (smd->coll->dm)
smd->coll->dm->release(smd->coll->dm);
smd->coll->dm = NULL;
-#endif
MEM_freeN(smd->coll);
smd->coll = NULL;
@@ -807,7 +414,7 @@ static void smokeModifier_freeCollision(SmokeModifierData *smd)
void smokeModifier_reset_turbulence(struct SmokeModifierData *smd)
{
- if(smd && smd->domain && smd->domain->wt)
+ if (smd && smd->domain && smd->domain->wt)
{
smoke_turbulence_free(smd->domain->wt);
smd->domain->wt = NULL;
@@ -816,15 +423,15 @@ void smokeModifier_reset_turbulence(struct SmokeModifierData *smd)
void smokeModifier_reset(struct SmokeModifierData *smd)
{
- if(smd)
+ if (smd)
{
- if(smd->domain)
+ if (smd->domain)
{
- if(smd->domain->shadow)
+ if (smd->domain->shadow)
MEM_freeN(smd->domain->shadow);
smd->domain->shadow = NULL;
- if(smd->domain->fluid)
+ if (smd->domain->fluid)
{
smoke_free(smd->domain->fluid);
smd->domain->fluid = NULL;
@@ -833,39 +440,23 @@ void smokeModifier_reset(struct SmokeModifierData *smd)
smokeModifier_reset_turbulence(smd);
smd->time = -1;
-
- // printf("reset domain end\n");
+ smd->domain->total_cells = 0;
+ smd->domain->active_fields = 0;
}
- else if(smd->flow)
+ else if (smd->flow)
{
- /*
- if(smd->flow->bvh)
- {
- free_bvhtree_from_mesh(smd->flow->bvh);
- MEM_freeN(smd->flow->bvh);
- }
- smd->flow->bvh = NULL;
- */
+ if (smd->flow->verts_old) MEM_freeN(smd->flow->verts_old);
+ smd->flow->verts_old = NULL;
+ smd->flow->numverts = 0;
}
- else if(smd->coll)
+ else if (smd->coll)
{
SmokeCollSettings *scs = smd->coll;
- if(scs->numpoints && scs->points)
+ if (scs->numverts && scs->verts_old)
{
- MEM_freeN(scs->points);
- scs->points = NULL;
-
- if(scs->points_old)
- {
- MEM_freeN(scs->points_old);
- scs->points_old = NULL;
- }
- if(scs->tridivs)
- {
- MEM_freeN(scs->tridivs);
- scs->tridivs = NULL;
- }
+ MEM_freeN(scs->verts_old);
+ scs->verts_old = NULL;
}
}
}
@@ -873,7 +464,7 @@ void smokeModifier_reset(struct SmokeModifierData *smd)
void smokeModifier_free(SmokeModifierData *smd)
{
- if(smd)
+ if (smd)
{
smokeModifier_freeDomain(smd);
smokeModifier_freeFlow(smd);
@@ -883,11 +474,11 @@ void smokeModifier_free(SmokeModifierData *smd)
void smokeModifier_createType(struct SmokeModifierData *smd)
{
- if(smd)
+ if (smd)
{
- if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
+ if (smd->type & MOD_SMOKE_TYPE_DOMAIN)
{
- if(smd->domain)
+ if (smd->domain)
smokeModifier_freeDomain(smd);
smd->domain = MEM_callocN(sizeof(SmokeDomainSettings), "SmokeDomain");
@@ -903,13 +494,12 @@ void smokeModifier_createType(struct SmokeModifierData *smd)
smd->domain->ptcaches[1].first = smd->domain->ptcaches[1].last = NULL;
/* set some standard values */
smd->domain->fluid = NULL;
- smd->domain->wt = NULL;
+ smd->domain->wt = NULL;
smd->domain->eff_group = NULL;
smd->domain->fluid_group = NULL;
smd->domain->coll_group = NULL;
smd->domain->maxres = 32;
- smd->domain->amplify = 1;
- smd->domain->omega = 1.0;
+ smd->domain->amplify = 1;
smd->domain->alpha = -0.001;
smd->domain->beta = 0.1;
smd->domain->time_scale = 1.0;
@@ -919,14 +509,28 @@ void smokeModifier_createType(struct SmokeModifierData *smd)
smd->domain->strength = 2.0;
smd->domain->noise = MOD_SMOKE_NOISEWAVE;
smd->domain->diss_speed = 5;
- // init 3dview buffer
+ smd->domain->active_fields = 0;
+
+ smd->domain->adapt_margin = 4;
+ smd->domain->adapt_res = 0;
+ smd->domain->adapt_threshold = 0.02f;
+
+ smd->domain->burning_rate = 0.75f;
+ smd->domain->flame_smoke = 1.0f;
+ smd->domain->flame_vorticity = 0.5f;
+ smd->domain->flame_ignition = 1.25f;
+ smd->domain->flame_max_temp = 1.75f;
+ /* color */
+ smd->domain->flame_smoke_color[0] = 0.7f;
+ smd->domain->flame_smoke_color[1] = 0.7f;
+ smd->domain->flame_smoke_color[2] = 0.7f;
smd->domain->viewsettings = MOD_SMOKE_VIEW_SHOWBIG;
smd->domain->effector_weights = BKE_add_effector_weights(NULL);
}
- else if(smd->type & MOD_SMOKE_TYPE_FLOW)
+ else if (smd->type & MOD_SMOKE_TYPE_FLOW)
{
- if(smd->flow)
+ if (smd->flow)
smokeModifier_freeFlow(smd);
smd->flow = MEM_callocN(sizeof(SmokeFlowSettings), "SmokeFlow");
@@ -934,31 +538,35 @@ void smokeModifier_createType(struct SmokeModifierData *smd)
smd->flow->smd = smd;
/* set some standard values */
- smd->flow->density = 1.0;
- smd->flow->temp = 1.0;
+ smd->flow->density = 1.0f;
+ smd->flow->fuel_amount = 1.0f;
+ smd->flow->temp = 1.0f;
smd->flow->flags = MOD_SMOKE_FLOW_ABSOLUTE;
- smd->flow->vel_multi = 1.0;
+ smd->flow->vel_multi = 1.0f;
+ smd->flow->surface_distance = 1.5f;
+ smd->flow->source = MOD_SMOKE_FLOW_SOURCE_MESH;
+ smd->flow->texture_size = 1.0f;
+
+ smd->flow->color[0] = 0.7f;
+ smd->flow->color[1] = 0.7f;
+ smd->flow->color[2] = 0.7f;
+ smd->flow->dm = NULL;
smd->flow->psys = NULL;
}
- else if(smd->type & MOD_SMOKE_TYPE_COLL)
+ else if (smd->type & MOD_SMOKE_TYPE_COLL)
{
- if(smd->coll)
+ if (smd->coll)
smokeModifier_freeCollision(smd);
smd->coll = MEM_callocN(sizeof(SmokeCollSettings), "SmokeColl");
smd->coll->smd = smd;
- smd->coll->points = NULL;
- smd->coll->points_old = NULL;
- smd->coll->tridivs = NULL;
- smd->coll->vel = NULL;
- smd->coll->numpoints = 0;
- smd->coll->numtris = 0;
- smd->coll->bvhtree = NULL;
+ smd->coll->verts_old = NULL;
+ smd->coll->numverts = 0;
smd->coll->type = 0; // static obstacle
- smd->coll->dx = 1.0f / 50.0f;
+ smd->coll->dm = NULL;
#ifdef USE_SMOKE_COLLISION_DM
smd->coll->dm = NULL;
@@ -971,39 +579,67 @@ void smokeModifier_copy(struct SmokeModifierData *smd, struct SmokeModifierData
{
tsmd->type = smd->type;
tsmd->time = smd->time;
-
+
smokeModifier_createType(tsmd);
if (tsmd->domain) {
- tsmd->domain->maxres = smd->domain->maxres;
- tsmd->domain->amplify = smd->domain->amplify;
- tsmd->domain->omega = smd->domain->omega;
+ tsmd->domain->fluid_group = smd->domain->fluid_group;
+ tsmd->domain->coll_group = smd->domain->coll_group;
+
+ tsmd->domain->adapt_margin = smd->domain->adapt_margin;
+ tsmd->domain->adapt_res = smd->domain->adapt_res;
+ tsmd->domain->adapt_threshold = smd->domain->adapt_threshold;
+
tsmd->domain->alpha = smd->domain->alpha;
tsmd->domain->beta = smd->domain->beta;
+ tsmd->domain->amplify = smd->domain->amplify;
+ tsmd->domain->maxres = smd->domain->maxres;
tsmd->domain->flags = smd->domain->flags;
- tsmd->domain->strength = smd->domain->strength;
+ tsmd->domain->viewsettings = smd->domain->viewsettings;
tsmd->domain->noise = smd->domain->noise;
tsmd->domain->diss_speed = smd->domain->diss_speed;
- tsmd->domain->viewsettings = smd->domain->viewsettings;
- tsmd->domain->fluid_group = smd->domain->fluid_group;
- tsmd->domain->coll_group = smd->domain->coll_group;
+ tsmd->domain->strength = smd->domain->strength;
+
+ tsmd->domain->border_collisions = smd->domain->border_collisions;
tsmd->domain->vorticity = smd->domain->vorticity;
tsmd->domain->time_scale = smd->domain->time_scale;
- tsmd->domain->border_collisions = smd->domain->border_collisions;
-
+
+ tsmd->domain->burning_rate = smd->domain->burning_rate;
+ tsmd->domain->flame_smoke = smd->domain->flame_smoke;
+ tsmd->domain->flame_vorticity = smd->domain->flame_vorticity;
+ tsmd->domain->flame_ignition = smd->domain->flame_ignition;
+ tsmd->domain->flame_max_temp = smd->domain->flame_max_temp;
+ copy_v3_v3(tsmd->domain->flame_smoke_color, smd->domain->flame_smoke_color);
+
MEM_freeN(tsmd->domain->effector_weights);
tsmd->domain->effector_weights = MEM_dupallocN(smd->domain->effector_weights);
- }
+ }
else if (tsmd->flow) {
+ tsmd->flow->psys = smd->flow->psys;
+ tsmd->flow->noise_texture = smd->flow->noise_texture;
+
+ tsmd->flow->vel_multi = smd->flow->vel_multi;
+ tsmd->flow->vel_normal = smd->flow->vel_normal;
+ tsmd->flow->vel_random = smd->flow->vel_random;
+
tsmd->flow->density = smd->flow->density;
+ copy_v3_v3(tsmd->flow->color, smd->flow->color);
+ tsmd->flow->fuel_amount = smd->flow->fuel_amount;
tsmd->flow->temp = smd->flow->temp;
- tsmd->flow->psys = smd->flow->psys;
+ tsmd->flow->volume_density = smd->flow->volume_density;
+ tsmd->flow->surface_distance = smd->flow->surface_distance;
+
+ tsmd->flow->texture_size = smd->flow->texture_size;
+ tsmd->flow->texture_offset = smd->flow->texture_offset;
+ BLI_strncpy(tsmd->flow->uvlayer_name, tsmd->flow->uvlayer_name, sizeof(tsmd->flow->uvlayer_name));
+ tsmd->flow->vgroup_density = smd->flow->vgroup_density;
+
tsmd->flow->type = smd->flow->type;
+ tsmd->flow->source = smd->flow->source;
+ tsmd->flow->texture_type = smd->flow->texture_type;
tsmd->flow->flags = smd->flow->flags;
- tsmd->flow->vel_multi = smd->flow->vel_multi;
}
else if (tsmd->coll) {
- ;
/* leave it as initialized, collision settings is mostly caches */
}
}
@@ -1011,24 +647,24 @@ void smokeModifier_copy(struct SmokeModifierData *smd, struct SmokeModifierData
#ifdef WITH_SMOKE
// forward decleration
-static void smoke_calc_transparency(float *result, float *input, float *p0, float *p1, int res[3], float dx, float *light, bresenham_callback cb, float correct);
+static void smoke_calc_transparency(SmokeDomainSettings *sds, Scene *scene);
static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct);
static int get_lamp(Scene *scene, float *light)
-{
- Base *base_tmp = NULL;
+{
+ Base *base_tmp = NULL;
int found_lamp = 0;
// try to find a lamp, preferably local
- for(base_tmp = scene->base.first; base_tmp; base_tmp= base_tmp->next) {
- if(base_tmp->object->type == OB_LAMP) {
+ for (base_tmp = scene->base.first; base_tmp; base_tmp = base_tmp->next) {
+ if (base_tmp->object->type == OB_LAMP) {
Lamp *la = base_tmp->object->data;
- if(la->type == LA_LOCAL) {
+ if (la->type == LA_LOCAL) {
copy_v3_v3(light, base_tmp->object->obmat[3]);
return 1;
}
- else if(!found_lamp) {
+ else if (!found_lamp) {
copy_v3_v3(light, base_tmp->object->obmat[3]);
found_lamp = 1;
}
@@ -1038,48 +674,131 @@ static int get_lamp(Scene *scene, float *light)
return found_lamp;
}
-static void smoke_calc_domain(Scene *UNUSED(scene), Object *UNUSED(ob), SmokeModifierData *UNUSED(smd))
+static void obstacles_from_derivedmesh(Object *coll_ob, SmokeDomainSettings *sds, SmokeCollSettings *scs, unsigned char *obstacle_map, float *velocityX, float *velocityY, float *velocityZ, float dt)
{
-#if 0
- SmokeDomainSettings *sds = smd->domain;
- GroupObject *go = NULL;
- Base *base = NULL;
-
- /* do collisions, needs to be done before emission, so that smoke isn't emitted inside collision cells */
- if(1)
+ if (!scs->dm) return;
{
- unsigned int i;
- Object **collobjs = NULL;
- unsigned int numcollobj = 0;
- collobjs = get_collisionobjects(scene, ob, sds->coll_group, &numcollobj);
+ DerivedMesh *dm = NULL;
+ MVert *mvert = NULL;
+ MFace *mface = NULL;
+ BVHTreeFromMesh treeData = {0};
+ int numverts, i, z;
+
+ float surface_distance = 0.6;
+
+ float *vert_vel = NULL;
+ int has_velocity = 0;
+
+ tstart();
+
+ dm = CDDM_copy(scs->dm);
+ CDDM_calc_normals(dm);
+ mvert = dm->getVertArray(dm);
+ mface = dm->getTessFaceArray(dm);
+ numverts = dm->getNumVerts(dm);
+
+ // DG TODO
+ // if (scs->type > SM_COLL_STATIC)
+ // if line above is used, the code is in trouble if the object moves but is declared as "does not move"
- for(i = 0; i < numcollobj; i++)
{
- Object *collob= collobjs[i];
- SmokeModifierData *smd2 = (SmokeModifierData*)modifiers_findByType(collob, eModifierType_Smoke);
-
- // check for active smoke modifier
- // if(md && md->mode & (eModifierMode_Realtime | eModifierMode_Render))
- // SmokeModifierData *smd2 = (SmokeModifierData *)md;
-
- if((smd2->type & MOD_SMOKE_TYPE_COLL) && smd2->coll && smd2->coll->points && smd2->coll->points_old)
+ vert_vel = MEM_callocN(sizeof(float) * numverts * 3, "smoke_obs_velocity");
+
+ if (scs->numverts != numverts || !scs->verts_old) {
+ if (scs->verts_old) MEM_freeN(scs->verts_old);
+
+ scs->verts_old = MEM_callocN(sizeof(float) * numverts * 3, "smoke_obs_verts_old");
+ scs->numverts = numverts;
+ }
+ else {
+ has_velocity = 1;
+ }
+ }
+
+ /* Transform collider vertices to
+ * domain grid space for fast lookups */
+ for (i = 0; i < numverts; i++) {
+ float n[3];
+ float co[3];
+
+ /* vert pos */
+ mul_m4_v3(coll_ob->obmat, mvert[i].co);
+ smoke_pos_to_cell(sds, mvert[i].co);
+
+ /* vert normal */
+ normal_short_to_float_v3(n, mvert[i].no);
+ mul_mat3_m4_v3(coll_ob->obmat, n);
+ mul_mat3_m4_v3(sds->imat, n);
+ normalize_v3(n);
+ normal_float_to_short_v3(mvert[i].no, n);
+
+ /* vert velocity */
+ VECADD(co, mvert[i].co, sds->shift);
+ if (has_velocity)
{
- // ??? anything to do here?
+ sub_v3_v3v3(&vert_vel[i * 3], co, &scs->verts_old[i * 3]);
+ mul_v3_fl(&vert_vel[i * 3], sds->dx / dt);
+ }
+ copy_v3_v3(&scs->verts_old[i * 3], co);
+ }
+
+ if (bvhtree_from_mesh_faces(&treeData, dm, 0.0f, 4, 6)) {
+ #pragma omp parallel for schedule(static)
+ for (z = sds->res_min[2]; z < sds->res_max[2]; z++) {
+ int x, y;
+ for (x = sds->res_min[0]; x < sds->res_max[0]; x++)
+ for (y = sds->res_min[1]; y < sds->res_max[1]; y++) {
+ int index = smoke_get_index(x - sds->res_min[0], sds->res[0], y - sds->res_min[1], sds->res[1], z - sds->res_min[2]);
+
+ float ray_start[3] = {(float)x + 0.5f, (float)y + 0.5f, (float)z + 0.5f};
+ BVHTreeNearest nearest = {0};
+ nearest.index = -1;
+ nearest.dist = surface_distance * surface_distance; /* find_nearest uses squared distance */
+
+ /* find the nearest point on the mesh */
+ if (BLI_bvhtree_find_nearest(treeData.tree, ray_start, &nearest, treeData.nearest_callback, &treeData) != -1) {
+ float weights[4];
+ int v1, v2, v3, f_index = nearest.index;
+
+ /* calculate barycentric weights for nearest point */
+ v1 = mface[f_index].v1;
+ v2 = (nearest.flags & BVH_ONQUAD) ? mface[f_index].v3 : mface[f_index].v2;
+ v3 = (nearest.flags & BVH_ONQUAD) ? mface[f_index].v4 : mface[f_index].v3;
+ interp_weights_face_v3(weights, mvert[v1].co, mvert[v2].co, mvert[v3].co, NULL, nearest.co);
+
+ // DG TODO
+ if (has_velocity)
+ {
+ /* apply object velocity */
+ {
+ float hit_vel[3];
+ interp_v3_v3v3v3(hit_vel, &vert_vel[v1 * 3], &vert_vel[v2 * 3], &vert_vel[v3 * 3], weights);
+ velocityX[index] += hit_vel[0];
+ velocityY[index] += hit_vel[1];
+ velocityZ[index] += hit_vel[2];
+ }
+ }
- // TODO: only something to do for ANIMATED obstacles: need to update positions
+ /* tag obstacle cells */
+ obstacle_map[index] = 1;
+ if (has_velocity)
+ obstacle_map[index] |= 8;
+ }
+ }
}
}
+ /* free bvh tree */
+ free_bvhtree_from_mesh(&treeData);
+ dm->release(dm);
- if(collobjs)
- MEM_freeN(collobjs);
+ if (vert_vel) MEM_freeN(vert_vel);
}
-
-#endif
}
/* Animated obstacles: dx_step = ((x_new - x_old) / totalsteps) * substep */
-static void update_obstacles(Scene *scene, Object *ob, SmokeDomainSettings *sds, float dt, int substep, int totalsteps)
+static void update_obstacles(Scene *scene, Object *ob, SmokeDomainSettings *sds, float dt,
+ int UNUSED(substep), int UNUSED(totalsteps))
{
Object **collobjs = NULL;
unsigned int numcollobj = 0;
@@ -1092,24 +811,20 @@ static void update_obstacles(Scene *scene, Object *ob, SmokeDomainSettings *sds,
float *velxOrig = smoke_get_velocity_x(sds->fluid);
float *velyOrig = smoke_get_velocity_y(sds->fluid);
float *velzOrig = smoke_get_velocity_z(sds->fluid);
- // float *density = smoke_get_density(sds->fluid);
+ float *density = smoke_get_density(sds->fluid);
+ float *fuel = smoke_get_fuel(sds->fluid);
+ float *flame = smoke_get_flame(sds->fluid);
+ float *r = smoke_get_color_r(sds->fluid);
+ float *g = smoke_get_color_g(sds->fluid);
+ float *b = smoke_get_color_b(sds->fluid);
unsigned int z;
smoke_get_ob_velocity(sds->fluid, &velx, &vely, &velz);
// TODO: delete old obstacle flags
- for(z = 0; z < sds->res[0] * sds->res[1] * sds->res[2]; z++)
+ for (z = 0; z < sds->res[0] * sds->res[1] * sds->res[2]; z++)
{
- if(obstacles[z])
- {
- // density[z] = 0;
-
- velxOrig[z] = 0;
- velyOrig[z] = 0;
- velzOrig[z] = 0;
- }
-
- if(obstacles[z] & 8) // Do not delete static obstacles
+ if (obstacles[z] & 8) // Do not delete static obstacles
{
obstacles[z] = 0;
}
@@ -1119,410 +834,1064 @@ static void update_obstacles(Scene *scene, Object *ob, SmokeDomainSettings *sds,
velz[z] = 0;
}
+
collobjs = get_collisionobjects(scene, ob, sds->coll_group, &numcollobj, eModifierType_Smoke);
// update obstacle tags in cells
- for(collIndex = 0; collIndex < numcollobj; collIndex++)
+ for (collIndex = 0; collIndex < numcollobj; collIndex++)
{
- Object *collob= collobjs[collIndex];
- SmokeModifierData *smd2 = (SmokeModifierData*)modifiers_findByType(collob, eModifierType_Smoke);
+ Object *collob = collobjs[collIndex];
+ SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke);
// DG TODO: check if modifier is active?
-
- if((smd2->type & MOD_SMOKE_TYPE_COLL) && smd2->coll && smd2->coll->points && smd2->coll->points_old)
+
+ if ((smd2->type & MOD_SMOKE_TYPE_COLL) && smd2->coll)
{
SmokeCollSettings *scs = smd2->coll;
- unsigned int i;
+ obstacles_from_derivedmesh(collob, sds, scs, obstacles, velx, vely, velz, dt);
+ }
+ }
+
+ if (collobjs)
+ MEM_freeN(collobjs);
+
+ /* obstacle cells should not contain any velocity from the smoke simulation */
+ for (z = 0; z < sds->res[0] * sds->res[1] * sds->res[2]; z++)
+ {
+ if (obstacles[z])
+ {
+ velxOrig[z] = 0;
+ velyOrig[z] = 0;
+ velzOrig[z] = 0;
+ density[z] = 0;
+ if (fuel) {
+ fuel[z] = 0;
+ flame[z] = 0;
+ }
+ if (r) {
+ r[z] = 0;
+ g[z] = 0;
+ b[z] = 0;
+ }
+ }
+ }
+}
+
+
+typedef struct EmissionMap {
+ float *influence;
+ float *velocity;
+ int min[3], max[3], res[3];
+ int total_cells, valid;
+} EmissionMap;
+
+static void em_boundInsert(EmissionMap *em, float point[3])
+{
+ int i = 0;
+ if (!em->valid) {
+ VECCOPY(em->min, point);
+ VECCOPY(em->max, point);
+ em->valid = 1;
+ }
+ else {
+ for (; i < 3; i++) {
+ if (point[i] < em->min[i]) em->min[i] = (int)floor(point[i]);
+ if (point[i] > em->max[i]) em->max[i] = (int)ceil(point[i]);
+ }
+ }
+}
- /*
- // DG TODO: support static cobstacles, but basicly we could even support static + rigid with one set of code
- if(scs->type > SM_COLL_STATIC)
- */
+static void clampBoundsInDomain(SmokeDomainSettings *sds, int min[3], int max[3], float *min_vel, float *max_vel, int margin, float dt)
+{
+ int i;
+ for (i = 0; i < 3; i++) {
+ int adapt = (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) ? sds->adapt_res : 0;
+ /* add margin */
+ min[i] -= margin;
+ max[i] += margin;
+
+ /* adapt to velocity */
+ if (min_vel && min_vel[i] < 0.0f) {
+ min[i] += (int)ceil(min_vel[i] * dt);
+ }
+ if (max_vel && max_vel[i] > 0.0f) {
+ max[i] += (int)ceil(max_vel[i] * dt);
+ }
+
+ /* clamp within domain max size */
+ CLAMP(min[i], -adapt, sds->base_res[i] + adapt);
+ CLAMP(max[i], -adapt, sds->base_res[i] + adapt);
+ }
+}
+
+static void em_allocateData(EmissionMap *em, int use_velocity) {
+ int i, res[3];
+
+ for (i = 0; i < 3; i++) {
+ res[i] = em->max[i] - em->min[i];
+ if (res[i] <= 0)
+ return;
+ }
+ em->total_cells = res[0] * res[1] * res[2];
+ copy_v3_v3_int(em->res, res);
- /* Handle collisions */
- for(i = 0; i < scs->numpoints; i++)
+
+ em->influence = MEM_callocN(sizeof(float) * em->total_cells, "smoke_flow_influence");
+ if (use_velocity)
+ em->velocity = MEM_callocN(sizeof(float) * em->total_cells * 3, "smoke_flow_velocity");
+}
+
+static void em_freeData(EmissionMap *em) {
+ if (em->influence)
+ MEM_freeN(em->influence);
+ if (em->velocity)
+ MEM_freeN(em->velocity);
+}
+
+
+static void emit_from_particles(Object *flow_ob, SmokeDomainSettings *sds, SmokeFlowSettings *sfs, EmissionMap *em, Scene *scene, float time, float dt)
+{
+ if (sfs && sfs->psys && sfs->psys->part && ELEM(sfs->psys->part->type, PART_EMITTER, PART_FLUID)) // is particle system selected
+ {
+ ParticleSimulationData sim;
+ ParticleSystem *psys = sfs->psys;
+ float *particle_pos;
+ float *particle_vel;
+ int totpart = psys->totpart, totchild;
+ int p = 0;
+ int valid_particles = 0;
+
+ sim.scene = scene;
+ sim.ob = flow_ob;
+ sim.psys = psys;
+
+ if (psys->part->type == PART_HAIR)
+ {
+ // TODO: PART_HAIR not supported whatsoever
+ totchild = 0;
+ }
+ else
+ totchild = psys->totchild * psys->part->disp / 100;
+
+ particle_pos = MEM_callocN(sizeof(float) * (totpart + totchild) * 3, "smoke_flow_particles");
+ particle_vel = MEM_callocN(sizeof(float) * (totpart + totchild) * 3, "smoke_flow_particles");
+
+ /* calculate local position for each particle */
+ for (p = 0; p < totpart + totchild; p++)
+ {
+ ParticleKey state;
+ float *pos;
+ if (p < totpart) {
+ if (psys->particles[p].flag & (PARS_NO_DISP | PARS_UNEXIST))
+ continue;
+ }
+ else {
+ /* handle child particle */
+ ChildParticle *cpa = &psys->child[p - totpart];
+ if (psys->particles[cpa->parent].flag & (PARS_NO_DISP | PARS_UNEXIST))
+ continue;
+ }
+
+ state.time = time;
+ if (psys_get_particle_state(&sim, p, &state, 0) == 0)
+ continue;
+
+ /* location */
+ pos = &particle_pos[valid_particles * 3];
+ copy_v3_v3(pos, state.co);
+ smoke_pos_to_cell(sds, pos);
+
+ /* velocity */
+ copy_v3_v3(&particle_vel[valid_particles * 3], state.vel);
+ mul_mat3_m4_v3(sds->imat, &particle_vel[valid_particles * 3]);
+
+ /* calculate emission map bounds */
+ em_boundInsert(em, pos);
+ valid_particles++;
+ }
+
+ /* set emission map */
+ clampBoundsInDomain(sds, em->min, em->max, NULL, NULL, 1, dt);
+ em_allocateData(em, sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY);
+
+ for (p = 0; p < valid_particles; p++)
+ {
+ int cell[3];
+ size_t i = 0;
+ size_t index = 0;
+ int badcell = 0;
+
+ /* 1. get corresponding cell */
+ cell[0] = floor(particle_pos[p * 3]) - em->min[0];
+ cell[1] = floor(particle_pos[p * 3 + 1]) - em->min[1];
+ cell[2] = floor(particle_pos[p * 3 + 2]) - em->min[2];
+ /* check if cell is valid (in the domain boundary) */
+ for (i = 0; i < 3; i++) {
+ if ((cell[i] > em->res[i] - 1) || (cell[i] < 0)) {
+ badcell = 1;
+ break;
+ }
+ }
+ if (badcell)
+ continue;
+ /* get cell index */
+ index = smoke_get_index(cell[0], em->res[0], cell[1], em->res[1], cell[2]);
+ /* Add influence to emission map */
+ em->influence[index] = 1.0f;
+ /* Uses particle velocity as initial velocity for smoke */
+ if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && (psys->part->phystype != PART_PHYS_NO))
{
- // 1. get corresponding cell
- int cell[3];
- float pos[3], oldpos[3], vel[3];
- float cPos[3], cOldpos[3]; /* current position in substeps */
- int badcell = 0;
- size_t index;
- int j;
-
- // translate local points into global positions
- copy_v3_v3(cPos, &scs->points[3 * i]);
- mul_m4_v3(scs->mat, cPos);
- copy_v3_v3(pos, cPos);
-
- copy_v3_v3(cOldpos, &scs->points_old[3 * i]);
- mul_m4_v3(scs->mat_old, cOldpos);
- copy_v3_v3(oldpos, cOldpos);
-
- /* support for rigid bodies, armatures etc */
- {
- float tmp[3];
+ VECADDFAC(&em->velocity[index * 3], &em->velocity[index * 3], &particle_vel[p * 3], sfs->vel_multi);
+ }
+ } // particles loop
+
+ /* free data */
+ if (particle_pos)
+ MEM_freeN(particle_pos);
+ if (particle_vel)
+ MEM_freeN(particle_vel);
+ }
+}
- /* x_current = x_old + (x_new - x_old) * step_current / steps_total */
- float mulStep = (float)(((float)substep) / ((float)totalsteps));
+static void get_texture_value(Tex *texture, float tex_co[3], TexResult *texres)
+{
+ int result_type;
+
+ /* no node textures for now */
+ result_type = multitex_ext_safe(texture, tex_co, texres);
+
+ /* if the texture gave an RGB value, we assume it didn't give a valid
+ * intensity, since this is in the context of modifiers don't use perceptual color conversion.
+ * if the texture didn't give an RGB value, copy the intensity across
+ */
+ if (result_type & TEX_RGB) {
+ texres->tin = (1.0f / 3.0f) * (texres->tr + texres->tg + texres->tb);
+ }
+ else {
+ copy_v3_fl(&texres->tr, texres->tin);
+ }
+}
+
+static void emit_from_derivedmesh(Object *flow_ob, SmokeDomainSettings *sds, SmokeFlowSettings *sfs, EmissionMap *em, float dt)
+{
+ if (!sfs->dm) return;
+ {
+ DerivedMesh *dm = sfs->dm;
+ int defgrp_index = sfs->vgroup_density - 1;
+ MDeformVert *dvert = NULL;
+ MVert *mvert = NULL;
+ MVert *mvert_orig = NULL;
+ MFace *mface = NULL;
+ MTFace *tface = NULL;
+ BVHTreeFromMesh treeData = {0};
+ int numOfVerts, i, z;
+ float flow_center[3] = {0};
+
+ float *vert_vel = NULL;
+ int has_velocity = 0;
+
+ CDDM_calc_normals(dm);
+ mvert = dm->getVertArray(dm);
+ mvert_orig = dm->dupVertArray(dm); /* copy original mvert and restore when done */
+ mface = dm->getTessFaceArray(dm);
+ numOfVerts = dm->getNumVerts(dm);
+ dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
+ tface = CustomData_get_layer_named(&dm->faceData, CD_MTFACE, sfs->uvlayer_name);
+
+ if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
+ vert_vel = MEM_callocN(sizeof(float) * numOfVerts * 3, "smoke_flow_velocity");
+
+ if (sfs->numverts != numOfVerts || !sfs->verts_old) {
+ if (sfs->verts_old) MEM_freeN(sfs->verts_old);
+ sfs->verts_old = MEM_callocN(sizeof(float) * numOfVerts * 3, "smoke_flow_verts_old");
+ sfs->numverts = numOfVerts;
+ }
+ else {
+ has_velocity = 1;
+ }
+ }
- sub_v3_v3v3(tmp, cPos, cOldpos);
- mul_v3_fl(tmp, mulStep);
- add_v3_v3(cOldpos, tmp);
+ /* Transform dm vertices to
+ * domain grid space for fast lookups */
+ for (i = 0; i < numOfVerts; i++) {
+ float n[3];
+ /* vert pos */
+ mul_m4_v3(flow_ob->obmat, mvert[i].co);
+ smoke_pos_to_cell(sds, mvert[i].co);
+ /* vert normal */
+ normal_short_to_float_v3(n, mvert[i].no);
+ mul_mat3_m4_v3(flow_ob->obmat, n);
+ mul_mat3_m4_v3(sds->imat, n);
+ normalize_v3(n);
+ normal_float_to_short_v3(mvert[i].no, n);
+ /* vert velocity */
+ if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
+ float co[3];
+ VECADD(co, mvert[i].co, sds->shift);
+ if (has_velocity) {
+ sub_v3_v3v3(&vert_vel[i * 3], co, &sfs->verts_old[i * 3]);
+ mul_v3_fl(&vert_vel[i * 3], sds->dx / dt);
}
+ copy_v3_v3(&sfs->verts_old[i * 3], co);
+ }
- sub_v3_v3v3(vel, pos, oldpos);
- /* Scale velocity to incorperate the object movement during this step */
- mul_v3_fl(vel, 1.0 / (totalsteps * dt * sds->scale));
- // mul_v3_fl(vel, 1.0 / dt);
+ /* calculate emission map bounds */
+ em_boundInsert(em, mvert[i].co);
+ }
+ mul_m4_v3(flow_ob->obmat, flow_center);
+ smoke_pos_to_cell(sds, flow_center);
+
+ /* set emission map */
+ clampBoundsInDomain(sds, em->min, em->max, NULL, NULL, sfs->surface_distance, dt);
+ em_allocateData(em, sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY);
+
+ if (bvhtree_from_mesh_faces(&treeData, dm, 0.0f, 4, 6)) {
+ #pragma omp parallel for schedule(static)
+ for (z = em->min[2]; z < em->max[2]; z++) {
+ int x, y;
+ for (x = em->min[0]; x < em->max[0]; x++)
+ for (y = em->min[1]; y < em->max[1]; y++) {
+ int index = smoke_get_index(x - em->min[0], em->res[0], y - em->min[1], em->res[1], z - em->min[2]);
+
+ float ray_start[3] = {(float)x + 0.5f, (float)y + 0.5f, (float)z + 0.5f};
+ float ray_dir[3] = {1.0f, 0.0f, 0.0f};
+
+ BVHTreeRayHit hit = {0};
+ BVHTreeNearest nearest = {0};
+
+ float volume_factor = 0.0f;
+ float sample_str = 0.0f;
+
+ hit.index = -1;
+ hit.dist = 9999;
+ nearest.index = -1;
+ nearest.dist = sfs->surface_distance * sfs->surface_distance; /* find_nearest uses squared distance */
+
+ /* Check volume collision */
+ if (sfs->volume_density) {
+ if (BLI_bvhtree_ray_cast(treeData.tree, ray_start, ray_dir, 0.0f, &hit, treeData.raycast_callback, &treeData) != -1) {
+ float dot = ray_dir[0] * hit.no[0] + ray_dir[1] * hit.no[1] + ray_dir[2] * hit.no[2];
+ /* If ray and hit face normal are facing same direction
+ * hit point is inside a closed mesh. */
+ if (dot >= 0) {
+ /* Also cast a ray in opposite direction to make sure
+ * point is at least surrounded by two faces */
+ negate_v3(ray_dir);
+ hit.index = -1;
+ hit.dist = 9999;
+
+ BLI_bvhtree_ray_cast(treeData.tree, ray_start, ray_dir, 0.0f, &hit, treeData.raycast_callback, &treeData);
+ if (hit.index != -1) {
+ volume_factor = sfs->volume_density;
+ nearest.dist = hit.dist * hit.dist;
+ }
+ }
+ }
+ }
- // DG TODO: cap velocity to maxVelMag (or maxvel)
+ /* find the nearest point on the mesh */
+ if (BLI_bvhtree_find_nearest(treeData.tree, ray_start, &nearest, treeData.nearest_callback, &treeData) != -1) {
+ float weights[4];
+ int v1, v2, v3, f_index = nearest.index;
+ float n1[3], n2[3], n3[3], hit_normal[3];
+
+ /* emit from surface based on distance */
+ if (sfs->surface_distance) {
+ sample_str = sqrtf(nearest.dist) / sfs->surface_distance;
+ CLAMP(sample_str, 0.0f, 1.0f);
+ sample_str = pow(1.0f - sample_str, 0.5f);
+ }
+ else
+ sample_str = 0.0f;
+
+ /* calculate barycentric weights for nearest point */
+ v1 = mface[f_index].v1;
+ v2 = (nearest.flags & BVH_ONQUAD) ? mface[f_index].v3 : mface[f_index].v2;
+ v3 = (nearest.flags & BVH_ONQUAD) ? mface[f_index].v4 : mface[f_index].v3;
+ interp_weights_face_v3(weights, mvert[v1].co, mvert[v2].co, mvert[v3].co, NULL, nearest.co);
+
+ if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
+ /* apply normal directional velocity */
+ if (sfs->vel_normal) {
+ /* interpolate vertex normal vectors to get nearest point normal */
+ normal_short_to_float_v3(n1, mvert[v1].no);
+ normal_short_to_float_v3(n2, mvert[v2].no);
+ normal_short_to_float_v3(n3, mvert[v3].no);
+ interp_v3_v3v3v3(hit_normal, n1, n2, n3, weights);
+ normalize_v3(hit_normal);
+ /* apply normal directional and random velocity
+ * - TODO: random disabled for now since it doesnt really work well as pressure calc smoothens it out... */
+ em->velocity[index * 3] += hit_normal[0] * sfs->vel_normal * 0.25f;
+ em->velocity[index * 3 + 1] += hit_normal[1] * sfs->vel_normal * 0.25f;
+ em->velocity[index * 3 + 2] += hit_normal[2] * sfs->vel_normal * 0.25f;
+ /* TODO: for fire emitted from mesh surface we can use
+ * Vf = Vs + (Ps/Pf - 1)*S to model gaseous expansion from solid to fuel */
+ }
+ /* apply object velocity */
+ if (has_velocity && sfs->vel_multi) {
+ float hit_vel[3];
+ interp_v3_v3v3v3(hit_vel, &vert_vel[v1 * 3], &vert_vel[v2 * 3], &vert_vel[v3 * 3], weights);
+ em->velocity[index * 3] += hit_vel[0] * sfs->vel_multi;
+ em->velocity[index * 3 + 1] += hit_vel[1] * sfs->vel_multi;
+ em->velocity[index * 3 + 2] += hit_vel[2] * sfs->vel_multi;
+ }
+ }
+
+ /* apply vertex group influence if used */
+ if (defgrp_index != -1 && dvert) {
+ float weight_mask = defvert_find_weight(&dvert[v1], defgrp_index) * weights[0] +
+ defvert_find_weight(&dvert[v2], defgrp_index) * weights[1] +
+ defvert_find_weight(&dvert[v3], defgrp_index) * weights[2];
+ sample_str *= weight_mask;
+ }
+
+ /* apply emission texture */
+ if ((sfs->flags & MOD_SMOKE_FLOW_TEXTUREEMIT) && sfs->noise_texture) {
+ float tex_co[3] = {0};
+ TexResult texres;
+
+ if (sfs->texture_type == MOD_SMOKE_FLOW_TEXTURE_MAP_AUTO) {
+ tex_co[0] = ((float)(x - flow_center[0]) / sds->base_res[0]) / sfs->texture_size;
+ tex_co[1] = ((float)(y - flow_center[1]) / sds->base_res[1]) / sfs->texture_size;
+ tex_co[2] = ((float)(z - flow_center[2]) / sds->base_res[2] - sfs->texture_offset) / sfs->texture_size;
+ }
+ else if (tface) {
+ interp_v2_v2v2v2(tex_co, tface[f_index].uv[0], tface[f_index].uv[(nearest.flags & BVH_ONQUAD) ? 2 : 1],
+ tface[f_index].uv[(nearest.flags & BVH_ONQUAD) ? 3 : 2], weights);
+ /* map between -1.0f and 1.0f */
+ tex_co[0] = tex_co[0] * 2.0f - 1.0f;
+ tex_co[1] = tex_co[1] * 2.0f - 1.0f;
+ tex_co[2] = sfs->texture_offset;
+ }
+ texres.nor = NULL;
+ get_texture_value(sfs->noise_texture, tex_co, &texres);
+ sample_str *= texres.tin;
+ }
+ }
- // oldpos + velocity * dt = newpos
- get_cell(sds->p0, sds->res, sds->dx*sds->scale, cOldpos /* use current position here instead of "pos" */, cell, 0);
+ /* multiply initial velocity by emitter influence */
+ if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
+ mul_v3_fl(&em->velocity[index * 3], sample_str);
+ }
- // check if cell is valid (in the domain boundary)
- for(j = 0; j < 3; j++)
- if((cell[j] > sds->res[j] - 1) || (cell[j] < 0))
- {
- badcell = 1;
- break;
+ /* apply final influence based on volume factor */
+ em->influence[index] = MAX2(volume_factor, sample_str);
}
-
- if(badcell)
- continue;
+ }
+ }
+ /* free bvh tree */
+ free_bvhtree_from_mesh(&treeData);
+ /* restore original mverts */
+ CustomData_set_layer(&dm->vertData, CD_MVERT, mvert_orig);
+ if (mvert)
+ MEM_freeN(mvert);
+
+ if (vert_vel) MEM_freeN(vert_vel);
+ }
+}
- // 2. set cell values (heat, density and velocity)
- index = smoke_get_index(cell[0], sds->res[0], cell[1], sds->res[1], cell[2]);
+static void adjustDomainResolution(SmokeDomainSettings *sds, int new_shift[3], EmissionMap *emaps, unsigned int numflowobj, float dt)
+{
+ int min[3] = {32767, 32767, 32767}, max[3] = {-32767, -32767, -32767}, res[3];
+ int total_cells = 1, res_changed = 0, shift_changed = 0;
+ float min_vel[3], max_vel[3];
+ int x, y, z, i;
+ float *density = smoke_get_density(sds->fluid);
+ float *fuel = smoke_get_fuel(sds->fluid);
+ float *vx = smoke_get_velocity_x(sds->fluid);
+ float *vy = smoke_get_velocity_y(sds->fluid);
+ float *vz = smoke_get_velocity_z(sds->fluid);
+
+ INIT_MINMAX(min_vel, max_vel);
+
+ /* Calculate bounds for current domain content */
+ for (x = sds->res_min[0]; x < sds->res_max[0]; x++)
+ for (y = sds->res_min[1]; y < sds->res_max[1]; y++)
+ for (z = sds->res_min[2]; z < sds->res_max[2]; z++)
+ {
+ int xn = x - new_shift[0];
+ int yn = y - new_shift[1];
+ int zn = z - new_shift[2];
+ int index = smoke_get_index(x - sds->res_min[0], sds->res[0], y - sds->res_min[1], sds->res[1], z - sds->res_min[2]);
+ float max_den = (fuel) ? MAX2(density[index], fuel[index]) : density[index];
+
+ /* content bounds (use shifted coordinates) */
+ if (max_den >= sds->adapt_threshold) {
+ if (min[0] > xn) min[0] = xn;
+ if (min[1] > yn) min[1] = yn;
+ if (min[2] > zn) min[2] = zn;
+ if (max[0] < xn) max[0] = xn;
+ if (max[1] < yn) max[1] = yn;
+ if (max[2] < zn) max[2] = zn;
+ }
+ /* velocity bounds */
+ if (min_vel[0] > vx[index]) min_vel[0] = vx[index];
+ if (min_vel[1] > vy[index]) min_vel[1] = vy[index];
+ if (min_vel[2] > vz[index]) min_vel[2] = vz[index];
+ if (max_vel[0] < vx[index]) max_vel[0] = vx[index];
+ if (max_vel[1] < vy[index]) max_vel[1] = vy[index];
+ if (max_vel[2] < vz[index]) max_vel[2] = vz[index];
+ }
- // Don't overwrite existing obstacles
- if(obstacles[index])
- continue;
-
- // printf("cell[0]: %d, cell[1]: %d, cell[2]: %d\n", cell[0], cell[1], cell[2]);
- // printf("res[0]: %d, res[1]: %d, res[2]: %d, index: %d\n\n", sds->res[0], sds->res[1], sds->res[2], index);
- obstacles[index] = 1 | 8 /* ANIMATED */;
+ /* also apply emission maps */
+ for (i = 0; i < numflowobj; i++)
+ {
+ EmissionMap *em = &emaps[i];
- if(len_v3(vel) > FLT_EPSILON)
+ for (x = em->min[0]; x < em->max[0]; x++)
+ for (y = em->min[1]; y < em->max[1]; y++)
+ for (z = em->min[2]; z < em->max[2]; z++)
{
- // Collision object is moving
-
- velx[index] = vel[0]; // use "+="?
- vely[index] = vel[1];
- velz[index] = vel[2];
+ int index = smoke_get_index(x - em->min[0], em->res[0], y - em->min[1], em->res[1], z - em->min[2]);
+ float max_den = em->influence[index];
+
+ /* density bounds */
+ if (max_den >= sds->adapt_threshold) {
+ if (min[0] > x) min[0] = x;
+ if (min[1] > y) min[1] = y;
+ if (min[2] > z) min[2] = z;
+ if (max[0] < x) max[0] = x;
+ if (max[1] < y) max[1] = y;
+ if (max[2] < z) max[2] = z;
+ }
+ /* velocity bounds */
+ if (em->velocity) {
+ if (min_vel[0] > em->velocity[index * 3]) min_vel[0] = em->velocity[index * 3];
+ if (min_vel[1] > em->velocity[index * 3 + 1]) min_vel[1] = em->velocity[index * 3 + 1];
+ if (min_vel[2] > em->velocity[index * 3 + 2]) min_vel[2] = em->velocity[index * 3 + 2];
+ if (max_vel[0] < em->velocity[index * 3]) max_vel[0] = em->velocity[index * 3];
+ if (max_vel[1] < em->velocity[index * 3 + 1]) max_vel[1] = em->velocity[index * 3 + 1];
+ if (max_vel[2] < em->velocity[index * 3 + 2]) max_vel[2] = em->velocity[index * 3 + 2];
+ }
}
+ }
+
+ /* calculate new bounds based on these values */
+ clampBoundsInDomain(sds, min, max, min_vel, max_vel, sds->adapt_margin + 1, dt);
+
+ for (i = 0; i < 3; i++) {
+ /* calculate new resolution */
+ res[i] = max[i] - min[i];
+ total_cells *= res[i];
+
+ if (new_shift[i])
+ shift_changed = 1;
+
+ /* if no content set minimum dimensions */
+ if (res[i] <= 0) {
+ int j;
+ for (j = 0; j < 3; j++) {
+ min[j] = 0;
+ max[j] = 1;
+ res[j] = 1;
}
+ res_changed = 1;
+ total_cells = 1;
+ break;
}
+ if (min[i] != sds->res_min[i] || max[i] != sds->res_max[i])
+ res_changed = 1;
}
- if(collobjs)
- MEM_freeN(collobjs);
+ if (res_changed || shift_changed) {
+ struct FLUID_3D *fluid_old = sds->fluid;
+ struct WTURBULENCE *turb_old = sds->wt;
+ /* allocate new fluid data */
+ smoke_reallocate_fluid(sds, sds->dx, res, 0);
+ if (sds->flags & MOD_SMOKE_HIGHRES) {
+ smoke_reallocate_highres_fluid(sds, sds->dx, res, 0);
+ }
+
+ /* copy values from old fluid to new */
+ if (sds->total_cells > 1 && total_cells > 1) {
+ /* low res smoke */
+ float *o_dens, *o_react, *o_flame, *o_fuel, *o_heat, *o_heatold, *o_vx, *o_vy, *o_vz, *o_r, *o_g, *o_b;
+ float *n_dens, *n_react, *n_flame, *n_fuel, *n_heat, *n_heatold, *n_vx, *n_vy, *n_vz, *n_r, *n_g, *n_b;
+ float dummy;
+ unsigned char *dummy_p;
+ /* high res smoke */
+ int wt_res_old[3];
+ float *o_wt_dens, *o_wt_react, *o_wt_flame, *o_wt_fuel, *o_wt_tcu, *o_wt_tcv, *o_wt_tcw, *o_wt_r, *o_wt_g, *o_wt_b;
+ float *n_wt_dens, *n_wt_react, *n_wt_flame, *n_wt_fuel, *n_wt_tcu, *n_wt_tcv, *n_wt_tcw, *n_wt_r, *n_wt_g, *n_wt_b;
+
+ smoke_export(fluid_old, &dummy, &dummy, &o_dens, &o_react, &o_flame, &o_fuel, &o_heat, &o_heatold, &o_vx, &o_vy, &o_vz, &o_r, &o_g, &o_b, &dummy_p);
+ smoke_export(sds->fluid, &dummy, &dummy, &n_dens, &n_react, &n_flame, &n_fuel, &n_heat, &n_heatold, &n_vx, &n_vy, &n_vz, &n_r, &n_g, &n_b, &dummy_p);
+
+ if (sds->flags & MOD_SMOKE_HIGHRES) {
+ smoke_turbulence_export(turb_old, &o_wt_dens, &o_wt_react, &o_wt_flame, &o_wt_fuel, &o_wt_r, &o_wt_g, &o_wt_b, &o_wt_tcu, &o_wt_tcv, &o_wt_tcw);
+ smoke_turbulence_get_res(turb_old, wt_res_old);
+ smoke_turbulence_export(sds->wt, &n_wt_dens, &n_wt_react, &n_wt_flame, &n_wt_fuel, &n_wt_r, &n_wt_g, &n_wt_b, &n_wt_tcu, &n_wt_tcv, &n_wt_tcw);
+ }
+
+
+ for (x = sds->res_min[0]; x < sds->res_max[0]; x++)
+ for (y = sds->res_min[1]; y < sds->res_max[1]; y++)
+ for (z = sds->res_min[2]; z < sds->res_max[2]; z++)
+ {
+ /* old grid index */
+ int xo = x - sds->res_min[0];
+ int yo = y - sds->res_min[1];
+ int zo = z - sds->res_min[2];
+ int index_old = smoke_get_index(xo, sds->res[0], yo, sds->res[1], zo);
+ /* new grid index */
+ int xn = x - min[0] - new_shift[0];
+ int yn = y - min[1] - new_shift[1];
+ int zn = z - min[2] - new_shift[2];
+ int index_new = smoke_get_index(xn, res[0], yn, res[1], zn);
+
+ /* skip if outside new domain */
+ if (xn < 0 || xn >= res[0] ||
+ yn < 0 || yn >= res[1] ||
+ zn < 0 || zn >= res[2])
+ continue;
+
+ /* copy data */
+ n_dens[index_new] = o_dens[index_old];
+ /* heat */
+ if (n_heat && o_heat) {
+ n_heat[index_new] = o_heat[index_old];
+ n_heatold[index_new] = o_heatold[index_old];
+ }
+ /* fuel */
+ if (n_fuel && o_fuel) {
+ n_flame[index_new] = o_flame[index_old];
+ n_fuel[index_new] = o_fuel[index_old];
+ n_react[index_new] = o_react[index_old];
+ }
+ /* color */
+ if (o_r && n_r) {
+ n_r[index_new] = o_r[index_old];
+ n_g[index_new] = o_g[index_old];
+ n_b[index_new] = o_b[index_old];
+ }
+ n_vx[index_new] = o_vx[index_old];
+ n_vy[index_new] = o_vy[index_old];
+ n_vz[index_new] = o_vz[index_old];
+
+ if (sds->flags & MOD_SMOKE_HIGHRES && turb_old) {
+ int block_size = sds->amplify + 1;
+ int i, j, k;
+ /* old grid index */
+ int xx_o = xo * block_size;
+ int yy_o = yo * block_size;
+ int zz_o = zo * block_size;
+ /* new grid index */
+ int xx_n = xn * block_size;
+ int yy_n = yn * block_size;
+ int zz_n = zn * block_size;
+
+ n_wt_tcu[index_new] = o_wt_tcu[index_old];
+ n_wt_tcv[index_new] = o_wt_tcv[index_old];
+ n_wt_tcw[index_new] = o_wt_tcw[index_old];
+
+ for (i = 0; i < block_size; i++)
+ for (j = 0; j < block_size; j++)
+ for (k = 0; k < block_size; k++)
+ {
+ int big_index_old = smoke_get_index(xx_o + i, wt_res_old[0], yy_o + j, wt_res_old[1], zz_o + k);
+ int big_index_new = smoke_get_index(xx_n + i, sds->res_wt[0], yy_n + j, sds->res_wt[1], zz_n + k);
+ /* copy data */
+ n_wt_dens[big_index_new] = o_wt_dens[big_index_old];
+ if (n_wt_flame && o_wt_flame) {
+ n_wt_flame[big_index_new] = o_wt_flame[big_index_old];
+ n_wt_fuel[big_index_new] = o_wt_fuel[big_index_old];
+ n_wt_react[big_index_new] = o_wt_react[big_index_old];
+ }
+ if (n_wt_r && o_wt_r) {
+ n_wt_r[big_index_new] = o_wt_r[big_index_old];
+ n_wt_g[big_index_new] = o_wt_g[big_index_old];
+ n_wt_b[big_index_new] = o_wt_b[big_index_old];
+ }
+ }
+ }
+ }
+ }
+ smoke_free(fluid_old);
+ if (turb_old)
+ smoke_turbulence_free(turb_old);
+
+ /* set new domain dimensions */
+ VECCOPY(sds->res_min, min);
+ VECCOPY(sds->res_max, max);
+ VECCOPY(sds->res, res);
+ sds->total_cells = total_cells;
+ }
+}
+
+BLI_INLINE void apply_outflow_fields(int index, float *density, float *heat, float *fuel, float *react, float *color_r, float *color_g, float *color_b)
+{
+ density[index] = 0.f;
+ if (heat) {
+ heat[index] = 0.f;
+ }
+ if (fuel) {
+ fuel[index] = 0.f;
+ react[index] = 0.f;
+ }
+ if (color_r) {
+ color_r[index] = 0.f;
+ color_g[index] = 0.f;
+ color_b[index] = 0.f;
+ }
+}
+
+BLI_INLINE void apply_inflow_fields(SmokeFlowSettings *sfs, float emission_value, int index, float *density, float *heat, float *fuel, float *react, float *color_r, float *color_g, float *color_b)
+{
+ int absolute_flow = (sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE);
+ float dens_old = density[index];
+ // float fuel_old = (fuel) ? fuel[index] : 0.0f; /* UNUSED */
+ float dens_flow = (sfs->type == MOD_SMOKE_FLOW_TYPE_FIRE) ? 0.0f : emission_value * sfs->density;
+ float fuel_flow = emission_value * sfs->fuel_amount;
+ /* add heat */
+ if (heat) {
+ heat[index] = MAX2(emission_value * sfs->temp, heat[index]);
+ }
+ /* absolute */
+ if (absolute_flow) {
+ if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE) {
+ if (dens_flow > density[index])
+ density[index] = dens_flow;
+ }
+ if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && fuel && fuel_flow) {
+ if (fuel_flow > fuel[index])
+ fuel[index] = fuel_flow;
+ }
+ }
+ /* additive */
+ else {
+ if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE) {
+ density[index] += dens_flow;
+ CLAMP(density[index], 0.0f, 1.0f);
+ }
+ if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && fuel && sfs->fuel_amount) {
+ fuel[index] += fuel_flow;
+ CLAMP(fuel[index], 0.0f, 10.0f);
+ }
+ }
+
+ /* set color */
+ if (color_r && dens_flow) {
+ float total_dens = density[index] / (dens_old + dens_flow);
+ color_r[index] = (color_r[index] + sfs->color[0] * dens_flow) * total_dens;
+ color_g[index] = (color_g[index] + sfs->color[1] * dens_flow) * total_dens;
+ color_b[index] = (color_b[index] + sfs->color[2] * dens_flow) * total_dens;
+ }
+
+ /* set fire reaction coordinate */
+ if (fuel && fuel[index]) {
+ /* instead of using 1.0 for all new fuel add slight falloff
+ * to reduce flow blockiness */
+ float value = 1.0f - pow(1.0f - emission_value, 2.0f);
+
+ if (value > react[index]) {
+ float f = fuel_flow / fuel[index];
+ react[index] = value * f + (1.0f - f) * react[index];
+ }
+ }
}
-static void update_flowsfluids(Scene *scene, Object *ob, SmokeDomainSettings *sds, float time)
+static void update_flowsfluids(Scene *scene, Object *ob, SmokeDomainSettings *sds, float time, float dt)
{
Object **flowobjs = NULL;
+ EmissionMap *emaps = NULL;
unsigned int numflowobj = 0;
unsigned int flowIndex;
+ int new_shift[3] = {0};
+ int active_fields = sds->active_fields;
+
+ /* calculate domain shift for current frame if using adaptive domain */
+ if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
+ int total_shift[3];
+ float frame_shift_f[3];
+ float ob_loc[3] = {0};
+
+ mul_m4_v3(ob->obmat, ob_loc);
+
+ VECSUB(frame_shift_f, ob_loc, sds->prev_loc);
+ copy_v3_v3(sds->prev_loc, ob_loc);
+ /* convert global space shift to local "cell" space */
+ mul_mat3_m4_v3(sds->imat, frame_shift_f);
+ frame_shift_f[0] = frame_shift_f[0] / sds->cell_size[0];
+ frame_shift_f[1] = frame_shift_f[1] / sds->cell_size[1];
+ frame_shift_f[2] = frame_shift_f[2] / sds->cell_size[2];
+ /* add to total shift */
+ VECADD(sds->shift_f, sds->shift_f, frame_shift_f);
+ /* convert to integer */
+ total_shift[0] = floor(sds->shift_f[0]);
+ total_shift[1] = floor(sds->shift_f[1]);
+ total_shift[2] = floor(sds->shift_f[2]);
+ VECSUB(new_shift, total_shift, sds->shift);
+ copy_v3_v3_int(sds->shift, total_shift);
+
+ /* calculate new domain boundary points so that smoke doesnt slide on sub-cell movement */
+ sds->p0[0] = sds->dp0[0] - sds->cell_size[0] * (sds->shift_f[0] - total_shift[0] - 0.5f);
+ sds->p0[1] = sds->dp0[1] - sds->cell_size[1] * (sds->shift_f[1] - total_shift[1] - 0.5f);
+ sds->p0[2] = sds->dp0[2] - sds->cell_size[2] * (sds->shift_f[2] - total_shift[2] - 0.5f);
+ sds->p1[0] = sds->p0[0] + sds->cell_size[0] * sds->base_res[0];
+ sds->p1[1] = sds->p0[1] + sds->cell_size[1] * sds->base_res[1];
+ sds->p1[2] = sds->p0[2] + sds->cell_size[2] * sds->base_res[2];
+ }
flowobjs = get_collisionobjects(scene, ob, sds->fluid_group, &numflowobj, eModifierType_Smoke);
- // update obstacle tags in cells
- for(flowIndex = 0; flowIndex < numflowobj; flowIndex++)
+ /* init emission maps for each flow */
+ emaps = MEM_callocN(sizeof(struct EmissionMap) * numflowobj, "smoke_flow_maps");
+
+ /* Prepare flow emission maps */
+ for (flowIndex = 0; flowIndex < numflowobj; flowIndex++)
{
- Object *collob= flowobjs[flowIndex];
- SmokeModifierData *smd2 = (SmokeModifierData*)modifiers_findByType(collob, eModifierType_Smoke);
+ Object *collob = flowobjs[flowIndex];
+ SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke);
// check for initialized smoke object
- if((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)
+ if ((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)
{
// we got nice flow object
SmokeFlowSettings *sfs = smd2->flow;
+ EmissionMap *em = &emaps[flowIndex];
- if(sfs && sfs->psys && sfs->psys->part && sfs->psys->part->type==PART_EMITTER) // is particle system selected
- {
- ParticleSimulationData sim;
- ParticleSystem *psys = sfs->psys;
- int totpart=psys->totpart, totchild;
- int p = 0;
- float *density = smoke_get_density(sds->fluid);
- float *bigdensity = smoke_turbulence_get_density(sds->wt);
- float *heat = smoke_get_heat(sds->fluid);
- float *velocity_x = smoke_get_velocity_x(sds->fluid);
- float *velocity_y = smoke_get_velocity_y(sds->fluid);
- float *velocity_z = smoke_get_velocity_z(sds->fluid);
- unsigned char *obstacle = smoke_get_obstacle(sds->fluid);
- // DG TODO UNUSED unsigned char *obstacleAnim = smoke_get_obstacle_anim(sds->fluid);
- int bigres[3];
- short absolute_flow = (sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE);
- short high_emission_smoothing = bigdensity ? (sds->flags & MOD_SMOKE_HIGH_SMOOTH) : 0;
-
- /*
- * A temporary volume map used to store whole emissive
- * area to be added to smoke density and interpolated
- * for high resolution smoke.
- */
- float *temp_emission_map = NULL;
-
- sim.scene = scene;
- sim.ob = collob;
- sim.psys = psys;
-
- // initialize temp emission map
- if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW))
- {
- int i;
- temp_emission_map = MEM_callocN(sizeof(float) * sds->res[0]*sds->res[1]*sds->res[2], "SmokeTempEmission");
- // set whole volume to 0.0f
- for (i=0; i<sds->res[0]*sds->res[1]*sds->res[2]; i++) {
- temp_emission_map[i] = 0.0f;
- }
- }
+ if (sfs->source == MOD_SMOKE_FLOW_SOURCE_PARTICLES) {
+ emit_from_particles(collob, sds, sfs, em, scene, time, dt);
+ }
+ else {
+ emit_from_derivedmesh(collob, sds, sfs, em, dt);
+ }
- // mostly copied from particle code
- if(psys->part->type==PART_HAIR)
- {
- /*
- if(psys->childcache)
- {
- totchild = psys->totchildcache;
+ /* update required data fields */
+ if (em->total_cells && sfs->type != MOD_SMOKE_FLOW_TYPE_OUTFLOW) {
+ /* activate heat field if flow produces any heat */
+ if (sfs->temp) {
+ active_fields |= SM_ACTIVE_HEAT;
+ }
+ /* activate fuel field if flow adds any fuel */
+ if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && sfs->fuel_amount) {
+ active_fields |= SM_ACTIVE_FIRE;
+ }
+ /* activate color field if flows add smoke with varying colors */
+ if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE && sfs->density) {
+ if (!(active_fields & SM_ACTIVE_COLOR_SET)) {
+ copy_v3_v3(sds->active_color, sfs->color);
+ active_fields |= SM_ACTIVE_COLOR_SET;
+ }
+ else if (!equals_v3v3(sds->active_color, sfs->color)) {
+ active_fields |= SM_ACTIVE_COLORS;
}
- else
- */
-
- // TODO: PART_HAIR not supported whatsoever
- totchild=0;
}
- else
- totchild=psys->totchild*psys->part->disp/100;
+ }
+ }
+ }
- for(p=0; p<totpart+totchild; p++)
- {
- int cell[3];
- size_t i = 0;
- size_t index = 0;
- int badcell = 0;
- ParticleKey state;
+ /* monitor active fields based on domain settings */
+ /* if domain has fire, activate new fields if required */
+ if (active_fields & SM_ACTIVE_FIRE) {
+ /* heat is always needed for fire */
+ active_fields |= SM_ACTIVE_HEAT;
+ /* also activate colors if domain smoke color differs from active color */
+ if (!(active_fields & SM_ACTIVE_COLOR_SET)) {
+ copy_v3_v3(sds->active_color, sds->flame_smoke_color);
+ active_fields |= SM_ACTIVE_COLOR_SET;
+ }
+ else if (!equals_v3v3(sds->active_color, sds->flame_smoke_color)) {
+ active_fields |= SM_ACTIVE_COLORS;
+ }
+ }
- if(p < totpart)
- {
- if(psys->particles[p].flag & (PARS_NO_DISP|PARS_UNEXIST))
- continue;
- }
- else {
- /* handle child particle */
- ChildParticle *cpa = &psys->child[p - totpart];
+ /* Adjust domain size if needed */
+ if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
+ adjustDomainResolution(sds, new_shift, emaps, numflowobj, dt);
+ }
- if(psys->particles[cpa->parent].flag & (PARS_NO_DISP|PARS_UNEXIST))
- continue;
- }
+ /* Initialize new data fields if any */
+ if (active_fields & SM_ACTIVE_HEAT) {
+ smoke_ensure_heat(sds->fluid);
+ }
+ if (active_fields & SM_ACTIVE_FIRE) {
+ smoke_ensure_fire(sds->fluid, sds->wt);
+ }
+ if (active_fields & SM_ACTIVE_COLORS) {
+ /* initialize all smoke with "active_color" */
+ smoke_ensure_colors(sds->fluid, sds->wt, sds->active_color[0], sds->active_color[1], sds->active_color[2]);
+ }
+ sds->active_fields = active_fields;
- state.time = time;
- if(psys_get_particle_state(&sim, p, &state, 0) == 0)
- continue;
+ /* Apply emission data */
+ if (sds->fluid) {
+ for (flowIndex = 0; flowIndex < numflowobj; flowIndex++)
+ {
+ Object *collob = flowobjs[flowIndex];
+ SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke);
- // copy_v3_v3(pos, pa->state.co);
- // mul_m4_v3(ob->imat, pos);
- // 1. get corresponding cell
- get_cell(sds->p0, sds->res, sds->dx*sds->scale, state.co, cell, 0);
- // check if cell is valid (in the domain boundary)
- for(i = 0; i < 3; i++)
- {
- if((cell[i] > sds->res[i] - 1) || (cell[i] < 0))
- {
- badcell = 1;
- break;
- }
- }
- if(badcell)
- continue;
- // 2. set cell values (heat, density and velocity)
- index = smoke_get_index(cell[0], sds->res[0], cell[1], sds->res[1], cell[2]);
- if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW) && !(obstacle[index])) // this is inflow
- {
- // heat[index] += sfs->temp * 0.1;
- // density[index] += sfs->density * 0.1;
- heat[index] = sfs->temp;
-
- // Add emitter density to temp emission map
- temp_emission_map[index] = sfs->density;
-
- // Uses particle velocity as initial velocity for smoke
- if(sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && (psys->part->phystype != PART_PHYS_NO))
- {
- velocity_x[index] = state.vel[0]*sfs->vel_multi;
- velocity_y[index] = state.vel[1]*sfs->vel_multi;
- velocity_z[index] = state.vel[2]*sfs->vel_multi;
- }
- }
- else if(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW) // outflow
- {
- heat[index] = 0.f;
- density[index] = 0.f;
- velocity_x[index] = 0.f;
- velocity_y[index] = 0.f;
- velocity_z[index] = 0.f;
- // we need different handling for the high-res feature
- if(bigdensity)
- {
- // init all surrounding cells according to amplification, too
- int i, j, k;
- smoke_turbulence_get_res(sds->wt, bigres);
-
- for(i = 0; i < sds->amplify + 1; i++)
- for(j = 0; j < sds->amplify + 1; j++)
- for(k = 0; k < sds->amplify + 1; k++)
- {
- index = smoke_get_index((sds->amplify + 1)* cell[0] + i, bigres[0], (sds->amplify + 1)* cell[1] + j, bigres[1], (sds->amplify + 1)* cell[2] + k);
- bigdensity[index] = 0.f;
- }
- }
- }
- } // particles loop
+ // check for initialized smoke object
+ if ((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)
+ {
+ // we got nice flow object
+ SmokeFlowSettings *sfs = smd2->flow;
+ EmissionMap *em = &emaps[flowIndex];
+
+ float *density = smoke_get_density(sds->fluid);
+ float *color_r = smoke_get_color_r(sds->fluid);
+ float *color_g = smoke_get_color_g(sds->fluid);
+ float *color_b = smoke_get_color_b(sds->fluid);
+ float *fuel = smoke_get_fuel(sds->fluid);
+ float *react = smoke_get_react(sds->fluid);
+ float *bigdensity = smoke_turbulence_get_density(sds->wt);
+ float *bigfuel = smoke_turbulence_get_fuel(sds->wt);
+ float *bigreact = smoke_turbulence_get_react(sds->wt);
+ float *bigcolor_r = smoke_turbulence_get_color_r(sds->wt);
+ float *bigcolor_g = smoke_turbulence_get_color_g(sds->wt);
+ float *bigcolor_b = smoke_turbulence_get_color_b(sds->wt);
+ float *heat = smoke_get_heat(sds->fluid);
+ float *velocity_x = smoke_get_velocity_x(sds->fluid);
+ float *velocity_y = smoke_get_velocity_y(sds->fluid);
+ float *velocity_z = smoke_get_velocity_z(sds->fluid);
+ //unsigned char *obstacle = smoke_get_obstacle(sds->fluid);
+ // DG TODO UNUSED unsigned char *obstacleAnim = smoke_get_obstacle_anim(sds->fluid);
+ int bigres[3];
+ short high_emission_smoothing = (sds->flags & MOD_SMOKE_HIGH_SMOOTH);
+ float *velocity_map = em->velocity;
+ float *emission_map = em->influence;
- // apply emission values
- if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW))
- {
- // initialize variables
- int ii, jj, kk, x, y, z, block_size;
- size_t index, index_big;
+ int ii, jj, kk, gx, gy, gz, ex, ey, ez, dx, dy, dz, block_size;
+ size_t e_index, d_index, index_big;
- smoke_turbulence_get_res(sds->wt, bigres);
- block_size = sds->amplify + 1; // high res block size
+ // loop through every emission map cell
+ for (gx = em->min[0]; gx < em->max[0]; gx++)
+ for (gy = em->min[1]; gy < em->max[1]; gy++)
+ for (gz = em->min[2]; gz < em->max[2]; gz++)
+ {
+ /* get emission map index */
+ ex = gx - em->min[0];
+ ey = gy - em->min[1];
+ ez = gz - em->min[2];
+ e_index = smoke_get_index(ex, em->res[0], ey, em->res[1], ez);
+ if (!emission_map[e_index]) continue;
+ /* get domain index */
+ dx = gx - sds->res_min[0];
+ dy = gy - sds->res_min[1];
+ dz = gz - sds->res_min[2];
+ d_index = smoke_get_index(dx, sds->res[0], dy, sds->res[1], dz);
+
+ if (sfs->type == MOD_SMOKE_FLOW_TYPE_OUTFLOW) { // outflow
+ apply_outflow_fields(d_index, density, heat, fuel, react, color_r, color_g, color_b);
+ }
+ else { // inflow
+ apply_inflow_fields(sfs, emission_map[e_index], d_index, density, heat, fuel, react, color_r, color_g, color_b);
+
+ /* initial velocity */
+ if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
+ velocity_x[d_index] = ADD_IF_LOWER(velocity_x[d_index], velocity_map[e_index * 3]);
+ velocity_y[d_index] = ADD_IF_LOWER(velocity_y[d_index], velocity_map[e_index * 3 + 1]);
+ velocity_z[d_index] = ADD_IF_LOWER(velocity_z[d_index], velocity_map[e_index * 3 + 2]);
+ }
+ }
- // loop through every low res cell
- for(x = 0; x < sds->res[0]; x++)
- for(y = 0; y < sds->res[1]; y++)
- for(z = 0; z < sds->res[2]; z++)
- {
+ /* loop through high res blocks if high res enabled */
+ if (bigdensity) {
// neighbor cell emission densities (for high resolution smoke smooth interpolation)
float c000, c001, c010, c011, c100, c101, c110, c111;
- c000 = (x>0 && y>0 && z>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y-1, sds->res[1], z-1)] : 0;
- c001 = (x>0 && y>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y-1, sds->res[1], z)] : 0;
- c010 = (x>0 && z>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y, sds->res[1], z-1)] : 0;
- c011 = (x>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y, sds->res[1], z)] : 0;
+ smoke_turbulence_get_res(sds->wt, bigres);
+ block_size = sds->amplify + 1; // high res block size
- c100 = (y>0 && z>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y-1, sds->res[1], z-1)] : 0;
- c101 = (y>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y-1, sds->res[1], z)] : 0;
- c110 = (z>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y, sds->res[1], z-1)] : 0;
- c111 = temp_emission_map[smoke_get_index(x, sds->res[0], y, sds->res[1], z)]; // this cell
+ c000 = (ex > 0 && ey > 0 && ez > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey - 1, em->res[1], ez - 1)] : 0;
+ c001 = (ex > 0 && ey > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey - 1, em->res[1], ez)] : 0;
+ c010 = (ex > 0 && ez > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey, em->res[1], ez - 1)] : 0;
+ c011 = (ex > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey, em->res[1], ez)] : 0;
- // get cell index
- index = smoke_get_index(x, sds->res[0], y, sds->res[1], z);
+ c100 = (ey > 0 && ez > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey - 1, em->res[1], ez - 1)] : 0;
+ c101 = (ey > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey - 1, em->res[1], ez)] : 0;
+ c110 = (ez > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey, em->res[1], ez - 1)] : 0;
+ c111 = emission_map[smoke_get_index(ex, em->res[0], ey, em->res[1], ez)]; // this cell
- // add emission to low resolution density
- if (absolute_flow)
- {
- if (temp_emission_map[index]>0)
- density[index] = temp_emission_map[index];
- }
- else
- {
- density[index] += temp_emission_map[index];
+ for (ii = 0; ii < block_size; ii++)
+ for (jj = 0; jj < block_size; jj++)
+ for (kk = 0; kk < block_size; kk++)
+ {
- if (density[index]>1)
- density[index]=1.0f;
- }
+ float fx, fy, fz, interpolated_value;
+ int shift_x, shift_y, shift_z;
- smoke_turbulence_get_res(sds->wt, bigres);
- /* loop through high res blocks if high res enabled */
- if (bigdensity)
- for(ii = 0; ii < block_size; ii++)
- for(jj = 0; jj < block_size; jj++)
- for(kk = 0; kk < block_size; kk++)
+ /*
+ * Do volume interpolation if emitter smoothing
+ * is enabled
+ */
+ if (high_emission_smoothing)
{
-
- float fx,fy,fz, interpolated_value;
- int shift_x, shift_y, shift_z;
-
-
- /*
- * Do volume interpolation if emitter smoothing
- * is enabled
- */
- if (high_emission_smoothing)
- {
- // convert block position to relative
- // for interpolation smoothing
- fx = (float)ii/block_size + 0.5f/block_size;
- fy = (float)jj/block_size + 0.5f/block_size;
- fz = (float)kk/block_size + 0.5f/block_size;
-
- // calculate trilinear interpolation
- interpolated_value = c000 * (1-fx) * (1-fy) * (1-fz) +
- c100 * fx * (1-fy) * (1-fz) +
- c010 * (1-fx) * fy * (1-fz) +
- c001 * (1-fx) * (1-fy) * fz +
- c101 * fx * (1-fy) * fz +
- c011 * (1-fx) * fy * fz +
- c110 * fx * fy * (1-fz) +
- c111 * fx * fy * fz;
-
-
- // add some contrast / sharpness
- // depending on hi-res block size
-
- interpolated_value = (interpolated_value-0.4f*sfs->density)*(block_size/2) + 0.4f*sfs->density;
- if (interpolated_value<0.0f) interpolated_value = 0.0f;
- if (interpolated_value>1.0f) interpolated_value = 1.0f;
-
- // shift smoke block index
- // (because pixel center is actually
- // in halfway of the low res block)
- shift_x = (x < 1) ? 0 : block_size/2;
- shift_y = (y < 1) ? 0 : block_size/2;
- shift_z = (z < 1) ? 0 : block_size/2;
- }
- else
- {
- // without interpolation use same low resolution
- // block value for all hi-res blocks
- interpolated_value = c111;
- shift_x = 0;
- shift_y = 0;
- shift_z = 0;
+ /* get relative block position
+ * for interpolation smoothing */
+ fx = (float)ii / block_size + 0.5f / block_size;
+ fy = (float)jj / block_size + 0.5f / block_size;
+ fz = (float)kk / block_size + 0.5f / block_size;
+
+ /* calculate trilinear interpolation */
+ interpolated_value = c000 * (1 - fx) * (1 - fy) * (1 - fz) +
+ c100 * fx * (1 - fy) * (1 - fz) +
+ c010 * (1 - fx) * fy * (1 - fz) +
+ c001 * (1 - fx) * (1 - fy) * fz +
+ c101 * fx * (1 - fy) * fz +
+ c011 * (1 - fx) * fy * fz +
+ c110 * fx * fy * (1 - fz) +
+ c111 * fx * fy * fz;
+
+
+ /* add some contrast / sharpness
+ * depending on hi-res block size */
+ interpolated_value = (interpolated_value - 0.4f) * (block_size / 2) + 0.4f;
+ CLAMP(interpolated_value, 0.0f, 1.0f);
+
+ /* shift smoke block index
+ * (because pixel center is actually
+ * in halfway of the low res block) */
+ shift_x = (dx < 1) ? 0 : block_size / 2;
+ shift_y = (dy < 1) ? 0 : block_size / 2;
+ shift_z = (dz < 1) ? 0 : block_size / 2;
+ }
+ else {
+ /* without interpolation use same low resolution
+ * block value for all hi-res blocks */
+ interpolated_value = c111;
+ shift_x = 0;
+ shift_y = 0;
+ shift_z = 0;
+ }
+
+ /* get shifted index for current high resolution block */
+ index_big = smoke_get_index(block_size * dx + ii - shift_x, bigres[0], block_size * dy + jj - shift_y, bigres[1], block_size * dz + kk - shift_z);
+
+ if (sfs->type == MOD_SMOKE_FLOW_TYPE_OUTFLOW) { // outflow
+ if (interpolated_value) {
+ apply_outflow_fields(index_big, bigdensity, NULL, bigfuel, bigreact, bigcolor_r, bigcolor_g, bigcolor_b);
}
-
- // get shifted index for current high resolution block
- index_big = smoke_get_index(block_size * x + ii - shift_x, bigres[0], block_size * y + jj - shift_y, bigres[1], block_size * z + kk - shift_z);
-
- // add emission data to high resolution density
- if (absolute_flow)
- {
- if (interpolated_value > 0)
- bigdensity[index_big] = interpolated_value;
- }
- else
- {
- bigdensity[index_big] += interpolated_value;
-
- if (bigdensity[index_big]>1)
- bigdensity[index_big]=1.0f;
- }
- } // end of hires loop
-
- } // end of low res loop
-
- // free temporary emission map
- if (temp_emission_map)
- MEM_freeN(temp_emission_map);
-
- } // end emission
- }
+ }
+ else { // inflow
+ apply_inflow_fields(sfs, interpolated_value, index_big, bigdensity, NULL, bigfuel, bigreact, bigcolor_r, bigcolor_g, bigcolor_b);
+ }
+ } // hires loop
+ } // bigdensity
+ } // low res loop
+
+ // free emission maps
+ em_freeData(em);
+
+ } // end emission
}
}
- if(flowobjs)
+ if (flowobjs)
MEM_freeN(flowobjs);
+ if (emaps)
+ MEM_freeN(emaps);
}
static void update_effectors(Scene *scene, Object *ob, SmokeDomainSettings *sds, float UNUSED(dt))
{
- ListBase *effectors = pdInitEffectors(scene, ob, NULL, sds->effector_weights);
+ ListBase *effectors;
+ /* make sure smoke flow influence is 0.0f */
+ sds->effector_weights->weight[PFIELD_SMOKEFLOW] = 0.0f;
+ effectors = pdInitEffectors(scene, ob, NULL, sds->effector_weights);
- if(effectors)
+ if (effectors)
{
float *density = smoke_get_density(sds->fluid);
float *force_x = smoke_get_force_x(sds->fluid);
@@ -1532,76 +1901,113 @@ static void update_effectors(Scene *scene, Object *ob, SmokeDomainSettings *sds,
float *velocity_y = smoke_get_velocity_y(sds->fluid);
float *velocity_z = smoke_get_velocity_z(sds->fluid);
unsigned char *obstacle = smoke_get_obstacle(sds->fluid);
- int x, y, z;
+ int x;
// precalculate wind forces
- for(x = 0; x < sds->res[0]; x++)
- for(y = 0; y < sds->res[1]; y++)
- for(z = 0; z < sds->res[2]; z++)
- {
- EffectedPoint epoint;
- float voxelCenter[3] = {0,0,0}, vel[3] = {0,0,0}, retvel[3] = {0,0,0};
- unsigned int index = smoke_get_index(x, sds->res[0], y, sds->res[1], z);
-
- if((density[index] < FLT_EPSILON) || obstacle[index])
- continue;
-
- vel[0] = velocity_x[index];
- vel[1] = velocity_y[index];
- vel[2] = velocity_z[index];
-
- voxelCenter[0] = sds->p0[0] + sds->dx * sds->scale * x + sds->dx * sds->scale * 0.5;
- voxelCenter[1] = sds->p0[1] + sds->dx * sds->scale * y + sds->dx * sds->scale * 0.5;
- voxelCenter[2] = sds->p0[2] + sds->dx * sds->scale * z + sds->dx * sds->scale * 0.5;
-
- pd_point_from_loc(scene, voxelCenter, vel, index, &epoint);
- pdDoEffectors(effectors, NULL, sds->effector_weights, &epoint, retvel, NULL);
-
- // TODO dg - do in force!
- force_x[index] = MIN2(MAX2(-1.0, retvel[0] * 0.2), 1.0);
- force_y[index] = MIN2(MAX2(-1.0, retvel[1] * 0.2), 1.0);
- force_z[index] = MIN2(MAX2(-1.0, retvel[2] * 0.2), 1.0);
+ #pragma omp parallel for schedule(static)
+ for (x = 0; x < sds->res[0]; x++)
+ {
+ int y, z;
+ for (y = 0; y < sds->res[1]; y++)
+ for (z = 0; z < sds->res[2]; z++)
+ {
+ EffectedPoint epoint;
+ float mag;
+ float voxelCenter[3] = {0, 0, 0}, vel[3] = {0, 0, 0}, retvel[3] = {0, 0, 0};
+ unsigned int index = smoke_get_index(x, sds->res[0], y, sds->res[1], z);
+
+ if ((density[index] < FLT_EPSILON) || obstacle[index])
+ continue;
+
+ vel[0] = velocity_x[index];
+ vel[1] = velocity_y[index];
+ vel[2] = velocity_z[index];
+
+ /* convert vel to global space */
+ mag = len_v3(vel);
+ mul_mat3_m4_v3(sds->obmat, vel);
+ normalize_v3(vel);
+ mul_v3_fl(vel, mag);
+
+ voxelCenter[0] = sds->p0[0] + sds->cell_size[0] * ((float)(x + sds->res_min[0]) + 0.5f);
+ voxelCenter[1] = sds->p0[1] + sds->cell_size[1] * ((float)(y + sds->res_min[1]) + 0.5f);
+ voxelCenter[2] = sds->p0[2] + sds->cell_size[2] * ((float)(z + sds->res_min[2]) + 0.5f);
+ mul_m4_v3(sds->obmat, voxelCenter);
+
+ pd_point_from_loc(scene, voxelCenter, vel, index, &epoint);
+ pdDoEffectors(effectors, NULL, sds->effector_weights, &epoint, retvel, NULL);
+
+ /* convert retvel to local space */
+ mag = len_v3(retvel);
+ mul_mat3_m4_v3(sds->imat, retvel);
+ normalize_v3(retvel);
+ mul_v3_fl(retvel, mag);
+
+ // TODO dg - do in force!
+ force_x[index] = MIN2(MAX2(-1.0, retvel[0] * 0.2), 1.0);
+ force_y[index] = MIN2(MAX2(-1.0, retvel[1] * 0.2), 1.0);
+ force_z[index] = MIN2(MAX2(-1.0, retvel[2] * 0.2), 1.0);
+ }
}
}
pdEndEffectors(&effectors);
}
-static void step(Scene *scene, Object *ob, SmokeModifierData *smd, float fps)
+static void step(Scene *scene, Object *ob, SmokeModifierData *smd, DerivedMesh *domain_dm, float fps)
{
+ SmokeDomainSettings *sds = smd->domain;
/* stability values copied from wturbulence.cpp */
const int maxSubSteps = 25;
float maxVel;
// maxVel should be 1.5 (1.5 cell max movement) * dx (cell size)
- float dt = DT_DEFAULT;
+ float dt;
float maxVelMag = 0.0f;
int totalSubsteps;
int substep = 0;
float dtSubdiv;
+ float gravity[3] = {0.0f, 0.0f, -1.0f};
+ float gravity_mag;
- SmokeDomainSettings *sds = smd->domain;
-
- /* get max velocity and lower the dt value if it is too high */
- size_t size= sds->res[0] * sds->res[1] * sds->res[2];
-
+#if 0 /* UNUSED */
+ /* get max velocity and lower the dt value if it is too high */
+ size_t size = sds->res[0] * sds->res[1] * sds->res[2];
float *velX = smoke_get_velocity_x(sds->fluid);
float *velY = smoke_get_velocity_y(sds->fluid);
float *velZ = smoke_get_velocity_z(sds->fluid);
size_t i;
+#endif
- /* adapt timestep for different framerates, dt = 0.1 is at 25fps */
- dt *= (25.0f / fps);
+ /* update object state */
+ invert_m4_m4(sds->imat, ob->obmat);
+ copy_m4_m4(sds->obmat, ob->obmat);
+ smoke_set_domain_from_derivedmesh(sds, ob, domain_dm);
+ /* use global gravity if enabled */
+ if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
+ copy_v3_v3(gravity, scene->physics_settings.gravity);
+ /* map default value to 1.0 */
+ mul_v3_fl(gravity, 1.0f / 9.810f);
+ }
+ /* convert gravity to domain space */
+ gravity_mag = len_v3(gravity);
+ mul_mat3_m4_v3(sds->imat, gravity);
+ normalize_v3(gravity);
+ mul_v3_fl(gravity, gravity_mag);
+
+ /* adapt timestep for different framerates, dt = 0.1 is at 25fps */
+ dt = DT_DEFAULT * (25.0f / fps);
// maximum timestep/"CFL" constraint: dt < 5.0 *dx / maxVel
maxVel = (sds->dx * 5.0);
- for(i = 0; i < size; i++)
- {
- float vtemp = (velX[i]*velX[i]+velY[i]*velY[i]+velZ[i]*velZ[i]);
- if(vtemp > maxVelMag)
+#if 0
+ for (i = 0; i < size; i++) {
+ float vtemp = (velX[i] * velX[i] + velY[i] * velY[i] + velZ[i] * velZ[i]);
+ if (vtemp > maxVelMag)
maxVelMag = vtemp;
}
+#endif
maxVelMag = sqrt(maxVelMag) * dt * sds->time_scale;
totalSubsteps = (int)((maxVelMag / maxVel) + 1.0f); /* always round up */
@@ -1609,146 +2015,155 @@ static void step(Scene *scene, Object *ob, SmokeModifierData *smd, float fps)
totalSubsteps = (totalSubsteps > maxSubSteps) ? maxSubSteps : totalSubsteps;
/* Disable substeps for now, since it results in numerical instability */
- totalSubsteps = 1.0f;
+ totalSubsteps = 1.0f;
dtSubdiv = (float)dt / (float)totalSubsteps;
// printf("totalSubsteps: %d, maxVelMag: %f, dt: %f\n", totalSubsteps, maxVelMag, dt);
- for(substep = 0; substep < totalSubsteps; substep++)
+ for (substep = 0; substep < totalSubsteps; substep++)
{
// calc animated obstacle velocities
+ update_flowsfluids(scene, ob, sds, smd->time, dtSubdiv);
update_obstacles(scene, ob, sds, dtSubdiv, substep, totalSubsteps);
- update_flowsfluids(scene, ob, sds, smd->time);
- update_effectors(scene, ob, sds, dtSubdiv); // DG TODO? problem --> uses forces instead of velocity, need to check how they need to be changed with variable dt
- smoke_step(sds->fluid, dtSubdiv);
+ if (sds->total_cells > 1) {
+ update_effectors(scene, ob, sds, dtSubdiv); // DG TODO? problem --> uses forces instead of velocity, need to check how they need to be changed with variable dt
+ smoke_step(sds->fluid, gravity, dtSubdiv);
+ }
+ }
+}
- // move animated obstacle: Done in update_obstacles() */
+static DerivedMesh *createDomainGeometry(SmokeDomainSettings *sds, Object *ob)
+{
+ DerivedMesh *result;
+ MVert *mverts;
+ MPoly *mpolys;
+ MLoop *mloops;
+ float min[3];
+ float max[3];
+ float *co;
+ MPoly *mp;
+ MLoop *ml;
+
+ int num_verts = 8;
+ int num_faces = 6;
+ int i;
+ float ob_loc[3] = {0};
+ float ob_cache_loc[3] = {0};
+
+ /* dont generate any mesh if there isnt any content */
+ if (sds->total_cells <= 1) {
+ num_verts = 0;
+ num_faces = 0;
+ }
- // where to delete old obstacles from array? Done in update_obstacles() */
+ result = CDDM_new(num_verts, 0, 0, num_faces * 4, num_faces);
+ mverts = CDDM_get_verts(result);
+ mpolys = CDDM_get_polys(result);
+ mloops = CDDM_get_loops(result);
+
+
+ if (num_verts) {
+ /* volume bounds */
+ VECMADD(min, sds->p0, sds->cell_size, sds->res_min);
+ VECMADD(max, sds->p0, sds->cell_size, sds->res_max);
+
+ /* set vertices */
+ /* top slab */
+ co = mverts[0].co; co[0] = min[0]; co[1] = min[1]; co[2] = max[2];
+ co = mverts[1].co; co[0] = max[0]; co[1] = min[1]; co[2] = max[2];
+ co = mverts[2].co; co[0] = max[0]; co[1] = max[1]; co[2] = max[2];
+ co = mverts[3].co; co[0] = min[0]; co[1] = max[1]; co[2] = max[2];
+ /* bottom slab */
+ co = mverts[4].co; co[0] = min[0]; co[1] = min[1]; co[2] = min[2];
+ co = mverts[5].co; co[0] = max[0]; co[1] = min[1]; co[2] = min[2];
+ co = mverts[6].co; co[0] = max[0]; co[1] = max[1]; co[2] = min[2];
+ co = mverts[7].co; co[0] = min[0]; co[1] = max[1]; co[2] = min[2];
+
+ /* create faces */
+ /* top */
+ mp = &mpolys[0]; ml = &mloops[0 * 4]; mp->loopstart = 0 * 4; mp->totloop = 4;
+ ml[0].v = 0; ml[1].v = 1; ml[2].v = 2; ml[3].v = 3;
+ /* right */
+ mp = &mpolys[1]; ml = &mloops[1 * 4]; mp->loopstart = 1 * 4; mp->totloop = 4;
+ ml[0].v = 2; ml[1].v = 1; ml[2].v = 5; ml[3].v = 6;
+ /* bottom */
+ mp = &mpolys[2]; ml = &mloops[2 * 4]; mp->loopstart = 2 * 4; mp->totloop = 4;
+ ml[0].v = 7; ml[1].v = 6; ml[2].v = 5; ml[3].v = 4;
+ /* left */
+ mp = &mpolys[3]; ml = &mloops[3 * 4]; mp->loopstart = 3 * 4; mp->totloop = 4;
+ ml[0].v = 0; ml[1].v = 3; ml[2].v = 7; ml[3].v = 4;
+ /* front */
+ mp = &mpolys[4]; ml = &mloops[4 * 4]; mp->loopstart = 4 * 4; mp->totloop = 4;
+ ml[0].v = 3; ml[1].v = 2; ml[2].v = 6; ml[3].v = 7;
+ /* back */
+ mp = &mpolys[5]; ml = &mloops[5 * 4]; mp->loopstart = 5 * 4; mp->totloop = 4;
+ ml[0].v = 1; ml[1].v = 0; ml[2].v = 4; ml[3].v = 5;
+
+ /* calculate required shift to match domain's global position
+ * it was originally simulated at (if object moves without smoke step) */
+ invert_m4_m4(ob->imat, ob->obmat);
+ mul_m4_v3(ob->obmat, ob_loc);
+ mul_m4_v3(sds->obmat, ob_cache_loc);
+ VECSUB(sds->obj_shift_f, ob_cache_loc, ob_loc);
+ /* convert shift to local space and apply to vertices */
+ mul_mat3_m4_v3(ob->imat, sds->obj_shift_f);
+ /* apply */
+ for (i = 0; i < num_verts; i++) {
+ add_v3_v3(mverts[i].co, sds->obj_shift_f);
+ }
}
+
+
+ CDDM_calc_edges(result);
+ return result;
}
-void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedMesh *dm)
-{
- if((smd->type & MOD_SMOKE_TYPE_FLOW))
+static void smokeModifier_process(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedMesh *dm)
+{
+ if ((smd->type & MOD_SMOKE_TYPE_FLOW))
{
- if(scene->r.cfra >= smd->time)
+ if (scene->r.cfra >= smd->time)
smokeModifier_init(smd, ob, scene, dm);
- if(scene->r.cfra > smd->time)
+ if (smd->flow->dm) smd->flow->dm->release(smd->flow->dm);
+ smd->flow->dm = CDDM_copy(dm);
+ DM_ensure_tessface(smd->flow->dm);
+
+ if (scene->r.cfra > smd->time)
{
- // XXX TODO
smd->time = scene->r.cfra;
-
- // rigid movement support
- /*
- copy_m4_m4(smd->flow->mat_old, smd->flow->mat);
- copy_m4_m4(smd->flow->mat, ob->obmat);
- */
}
- else if(scene->r.cfra < smd->time)
+ else if (scene->r.cfra < smd->time)
{
smd->time = scene->r.cfra;
smokeModifier_reset(smd);
}
}
- else if(smd->type & MOD_SMOKE_TYPE_COLL)
+ else if (smd->type & MOD_SMOKE_TYPE_COLL)
{
- /* Check if domain resolution changed */
- /* DG TODO: can this be solved more elegant using dependancy graph? */
- {
- SmokeCollSettings *scs = smd->coll;
- Base *base = scene->base.first;
- int changed = 0;
- float dx = FLT_MAX;
- float scale = 1.0f;
- int haveDomain = 0;
-
- for ( ; base; base = base->next)
- {
- SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(base->object, eModifierType_Smoke);
-
- if (smd2 && (smd2->type & MOD_SMOKE_TYPE_DOMAIN) && smd2->domain)
- {
- SmokeDomainSettings *sds = smd2->domain;
-
- if(sds->dx * sds->scale < dx)
- {
- dx = sds->dx;
- scale = sds->scale;
- changed = 1;
- }
-
- haveDomain = 1;
- }
- }
-
- if(!haveDomain)
- return;
-
- if(changed)
- {
- if(dx*scale != scs->dx)
- {
- scs->dx = dx*scale;
- smokeModifier_reset(smd);
- }
- }
- }
-
- if(scene->r.cfra >= smd->time)
+ if (scene->r.cfra >= smd->time)
smokeModifier_init(smd, ob, scene, dm);
- if(scene->r.cfra > smd->time)
+ if (smd->coll)
{
- unsigned int i;
- SmokeCollSettings *scs = smd->coll;
- float *points_old = scs->points_old;
- float *points = scs->points;
- unsigned int numpoints = scs->numpoints;
-
- // XXX TODO <-- DG: what is TODO here?
- smd->time = scene->r.cfra;
-
- // rigid movement support
- copy_m4_m4(scs->mat_old, scs->mat);
- copy_m4_m4(scs->mat, ob->obmat);
-
- if(scs->type != SM_COLL_ANIMATED) // if(not_animated)
- {
- // nothing to do, "mat" is already up to date
- }
- else
- {
- // XXX TODO: need to update positions + divs
-
- if(scs->numverts != dm->getNumVerts(dm))
- {
- // DG TODO: reset modifier?
- return;
- }
+ if (smd->coll->dm)
+ smd->coll->dm->release(smd->coll->dm);
- for(i = 0; i < numpoints * 3; i++)
- {
- points_old[i] = points[i];
- }
-
- DM_ensure_tessface(dm);
- fill_scs_points_anim(ob, dm, scs);
- }
+ smd->coll->dm = CDDM_copy(dm);
+ DM_ensure_tessface(smd->coll->dm);
}
- else if(scene->r.cfra < smd->time)
+
+ smd->time = scene->r.cfra;
+ if (scene->r.cfra < smd->time)
{
- smd->time = scene->r.cfra;
smokeModifier_reset(smd);
}
}
- else if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
+ else if (smd->type & MOD_SMOKE_TYPE_DOMAIN)
{
SmokeDomainSettings *sds = smd->domain;
- float light[3];
PointCache *cache = NULL;
PTCacheID pid;
int startframe, endframe, framenr;
@@ -1762,41 +2177,39 @@ void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedM
BKE_ptcache_id_from_smoke(&pid, ob, smd);
BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, &timescale);
- if(!smd->domain->fluid || framenr == startframe)
+ if (!smd->domain->fluid || framenr == startframe)
{
BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
+ smokeModifier_reset(smd);
BKE_ptcache_validate(cache, framenr);
cache->flag &= ~PTCACHE_REDO_NEEDED;
}
- if(!smd->domain->fluid && (framenr != startframe) && (smd->domain->flags & MOD_SMOKE_FILE_LOAD)==0 && (cache->flag & PTCACHE_BAKED)==0)
+ if (!smd->domain->fluid && (framenr != startframe) && (smd->domain->flags & MOD_SMOKE_FILE_LOAD) == 0 && (cache->flag & PTCACHE_BAKED) == 0)
return;
smd->domain->flags &= ~MOD_SMOKE_FILE_LOAD;
-
CLAMP(framenr, startframe, endframe);
/* If already viewing a pre/after frame, no need to reload */
if ((smd->time == framenr) && (framenr != scene->r.cfra))
return;
- // printf("startframe: %d, framenr: %d\n", startframe, framenr);
-
- if(smokeModifier_init(smd, ob, scene, dm)==0)
+ if (smokeModifier_init(smd, ob, scene, dm) == 0)
{
printf("bad smokeModifier_init\n");
return;
}
/* try to read from cache */
- if(BKE_ptcache_read(&pid, (float)framenr) == PTCACHE_READ_EXACT) {
+ if (BKE_ptcache_read(&pid, (float)framenr) == PTCACHE_READ_EXACT) {
BKE_ptcache_validate(cache, framenr);
smd->time = framenr;
return;
}
-
+
/* only calculate something when we advanced a single frame */
- if(framenr != (int)smd->time+1)
+ if (framenr != (int)smd->time + 1)
return;
/* don't simulate if viewing start frame, but scene frame is not real start frame */
@@ -1805,54 +2218,48 @@ void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedM
tstart();
- smoke_calc_domain(scene, ob, smd);
-
/* if on second frame, write cache for first frame */
- if((int)smd->time == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact==0)) {
+ if ((int)smd->time == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) {
// create shadows straight after domain initialization so we get nice shadows for startframe, too
- if(get_lamp(scene, light))
- smoke_calc_transparency(sds->shadow, smoke_get_density(sds->fluid), sds->p0, sds->p1, sds->res, sds->dx, light, calc_voxel_transp, -7.0*sds->dx);
+ smoke_calc_transparency(sds, scene);
- if(sds->wt)
+ if (sds->wt && sds->total_cells > 1)
{
- if(sds->flags & MOD_SMOKE_DISSOLVE)
+ if (sds->flags & MOD_SMOKE_DISSOLVE)
smoke_dissolve_wavelet(sds->wt, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
smoke_turbulence_step(sds->wt, sds->fluid);
}
BKE_ptcache_write(&pid, startframe);
}
-
+
// set new time
smd->time = scene->r.cfra;
/* do simulation */
- // low res
-
// simulate the actual smoke (c++ code in intern/smoke)
// DG: interesting commenting this line + deactivating loading of noise files
- if(framenr!=startframe)
+ if (framenr != startframe)
{
- if(sds->flags & MOD_SMOKE_DISSOLVE)
+ if (sds->flags & MOD_SMOKE_DISSOLVE)
smoke_dissolve(sds->fluid, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
-
- step(scene, ob, smd, scene->r.frs_sec / scene->r.frs_sec_base);
+
+ step(scene, ob, smd, dm, scene->r.frs_sec / scene->r.frs_sec_base);
}
// create shadows before writing cache so they get stored
- if(get_lamp(scene, light))
- smoke_calc_transparency(sds->shadow, smoke_get_density(sds->fluid), sds->p0, sds->p1, sds->res, sds->dx, light, calc_voxel_transp, -7.0*sds->dx);
+ smoke_calc_transparency(sds, scene);
- if(sds->wt)
+ if (sds->wt)
{
- if(sds->flags & MOD_SMOKE_DISSOLVE)
+ if (sds->flags & MOD_SMOKE_DISSOLVE)
smoke_dissolve_wavelet(sds->wt, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
smoke_turbulence_step(sds->wt, sds->fluid);
}
-
+
BKE_ptcache_validate(cache, framenr);
- if(framenr != startframe)
+ if (framenr != startframe)
BKE_ptcache_write(&pid, framenr);
tend();
@@ -1860,38 +2267,33 @@ void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedM
}
}
-static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct)
-{
- const size_t index = smoke_get_index(pixel[0], res[0], pixel[1], res[1], pixel[2]);
+struct DerivedMesh *smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedMesh *dm){
+ smokeModifier_process(smd, scene, ob, dm);
- // T_ray *= T_vox
- *tRay *= exp(input[index]*correct);
-
- if(result[index] < 0.0f)
+ /* return generated geometry for adaptive domain */
+ if (smd->type & MOD_SMOKE_TYPE_DOMAIN && smd->domain &&
+ smd->domain->flags & MOD_SMOKE_ADAPTIVE_DOMAIN &&
+ smd->domain->base_res[0])
{
-// #pragma omp critical
- result[index] = *tRay;
- }
-
- return *tRay;
+ return createDomainGeometry(smd->domain, ob);
+ }
+ else return CDDM_copy(dm);
}
-long long smoke_get_mem_req(int xres, int yres, int zres, int amplify)
+static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct)
{
- int totalCells = xres * yres * zres;
- int amplifiedCells = totalCells * amplify * amplify * amplify;
-
- // print out memory requirements
- long long int coarseSize = sizeof(float) * totalCells * 22 +
- sizeof(unsigned char) * totalCells;
+ const size_t index = smoke_get_index(pixel[0], res[0], pixel[1], res[1], pixel[2]);
- long long int fineSize = sizeof(float) * amplifiedCells * 7 + // big grids
- sizeof(float) * totalCells * 8 + // small grids
- sizeof(float) * 128 * 128 * 128; // noise tile
+ // T_ray *= T_vox
+ *tRay *= exp(input[index] * correct);
- long long int totalMB = (coarseSize + fineSize) / (1024 * 1024);
+ if (result[index] < 0.0f)
+ {
+// #pragma omp critical
+ result[index] = *tRay;
+ }
- return totalMB;
+ return *tRay;
}
static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, float *tRay, bresenham_callback cb, float *result, float *input, int res[3], float correct)
@@ -1921,7 +2323,7 @@ static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, f
err_1 = dy2 - l;
err_2 = dz2 - l;
for (i = 0; i < l; i++) {
- if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
+ if (cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
break;
if (err_1 > 0) {
pixel[1] += y_inc;
@@ -1935,12 +2337,12 @@ static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, f
err_2 += dz2;
pixel[0] += x_inc;
}
- }
+ }
else if ((m >= l) && (m >= n)) {
err_1 = dx2 - m;
err_2 = dz2 - m;
for (i = 0; i < m; i++) {
- if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
+ if (cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
break;
if (err_1 > 0) {
pixel[0] += x_inc;
@@ -1954,12 +2356,12 @@ static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, f
err_2 += dz2;
pixel[1] += y_inc;
}
- }
+ }
else {
err_1 = dy2 - n;
err_2 = dx2 - n;
for (i = 0; i < n; i++) {
- if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
+ if (cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
break;
if (err_1 > 0) {
pixel[1] += y_inc;
@@ -1977,80 +2379,142 @@ static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, f
cb(result, input, res, pixel, tRay, correct);
}
-static void get_cell(const float p0[3], const int res[3], float dx, const float pos[3], int cell[3], int correct)
+static void smoke_calc_transparency(SmokeDomainSettings *sds, Scene *scene)
{
- float tmp[3];
+ float bv[6] = {0};
+ float light[3];
+ int a, z, slabsize = sds->res[0] * sds->res[1], size = sds->res[0] * sds->res[1] * sds->res[2];
+ float *density = smoke_get_density(sds->fluid);
+ float correct = -7.0 * sds->dx;
- sub_v3_v3v3(tmp, pos, p0);
- mul_v3_fl(tmp, 1.0 / dx);
+ if (!get_lamp(scene, light)) return;
- if (correct) {
- cell[0] = MIN2(res[0] - 1, MAX2(0, (int)floor(tmp[0])));
- cell[1] = MIN2(res[1] - 1, MAX2(0, (int)floor(tmp[1])));
- cell[2] = MIN2(res[2] - 1, MAX2(0, (int)floor(tmp[2])));
- }
- else {
- cell[0] = (int)floor(tmp[0]);
- cell[1] = (int)floor(tmp[1]);
- cell[2] = (int)floor(tmp[2]);
- }
-}
-
-static void smoke_calc_transparency(float *result, float *input, float *p0, float *p1, int res[3], float dx, float *light, bresenham_callback cb, float correct)
-{
- float bv[6];
- int a, z, slabsize=res[0]*res[1], size= res[0]*res[1]*res[2];
+ /* convert light pos to sim cell space */
+ mul_m4_v3(sds->imat, light);
+ light[0] = (light[0] - sds->p0[0]) / sds->cell_size[0] - 0.5f - (float)sds->res_min[0];
+ light[1] = (light[1] - sds->p0[1]) / sds->cell_size[1] - 0.5f - (float)sds->res_min[1];
+ light[2] = (light[2] - sds->p0[2]) / sds->cell_size[2] - 0.5f - (float)sds->res_min[2];
- for(a=0; a<size; a++)
- result[a]= -1.0f;
+ for (a = 0; a < size; a++)
+ sds->shadow[a] = -1.0f;
- bv[0] = p0[0];
- bv[1] = p1[0];
- // y
- bv[2] = p0[1];
- bv[3] = p1[1];
- // z
- bv[4] = p0[2];
- bv[5] = p1[2];
+ /* calculate domain bounds in sim cell space */
+ // 0,2,4 = 0.0f
+ bv[1] = (float)sds->res[0]; // x
+ bv[3] = (float)sds->res[1]; // y
+ bv[5] = (float)sds->res[2]; // z
// #pragma omp parallel for schedule(static,1)
- for(z = 0; z < res[2]; z++)
+ for (z = 0; z < sds->res[2]; z++)
{
- size_t index = z*slabsize;
- int x,y;
+ size_t index = z * slabsize;
+ int x, y;
- for(y = 0; y < res[1]; y++)
- for(x = 0; x < res[0]; x++, index++)
+ for (y = 0; y < sds->res[1]; y++)
+ for (x = 0; x < sds->res[0]; x++, index++)
{
float voxelCenter[3];
float pos[3];
int cell[3];
float tRay = 1.0;
- if(result[index] >= 0.0f)
- continue;
- voxelCenter[0] = p0[0] + dx * x + dx * 0.5;
- voxelCenter[1] = p0[1] + dx * y + dx * 0.5;
- voxelCenter[2] = p0[2] + dx * z + dx * 0.5;
+ if (sds->shadow[index] >= 0.0f)
+ continue;
+ voxelCenter[0] = (float)x;
+ voxelCenter[1] = (float)y;
+ voxelCenter[2] = (float)z;
- // get starting position (in voxel coords)
- if(BLI_bvhtree_bb_raycast(bv, light, voxelCenter, pos) > FLT_EPSILON)
+ // get starting cell (light pos)
+ if (BLI_bvhtree_bb_raycast(bv, light, voxelCenter, pos) > FLT_EPSILON)
{
- // we're ouside
- get_cell(p0, res, dx, pos, cell, 1);
+ // we're ouside -> use point on side of domain
+ cell[0] = (int)floor(pos[0]);
+ cell[1] = (int)floor(pos[1]);
+ cell[2] = (int)floor(pos[2]);
}
else {
- // we're inside
- get_cell(p0, res, dx, light, cell, 1);
+ // we're inside -> use light itself
+ cell[0] = (int)floor(light[0]);
+ cell[1] = (int)floor(light[1]);
+ cell[2] = (int)floor(light[2]);
}
+ /* clamp within grid bounds */
+ CLAMP(cell[0], 0, sds->res[0] - 1);
+ CLAMP(cell[1], 0, sds->res[1] - 1);
+ CLAMP(cell[2], 0, sds->res[2] - 1);
- bresenham_linie_3D(cell[0], cell[1], cell[2], x, y, z, &tRay, cb, result, input, res, correct);
+ bresenham_linie_3D(cell[0], cell[1], cell[2], x, y, z, &tRay, calc_voxel_transp, sds->shadow, density, sds->res, correct);
// convention -> from a RGBA float array, use G value for tRay
// #pragma omp critical
- result[index] = tRay;
+ sds->shadow[index] = tRay;
}
}
}
+/* get smoke velocity and density at given coordinates
+ * returns fluid density or -1.0f if outside domain*/
+float smoke_get_velocity_at(struct Object *ob, float position[3], float velocity[3])
+{
+ SmokeModifierData *smd = (SmokeModifierData *)modifiers_findByType(ob, eModifierType_Smoke);
+ zero_v3(velocity);
+
+ if (smd && (smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain && smd->domain->fluid) {
+ SmokeDomainSettings *sds = smd->domain;
+ float time_mult = 25.f * DT_DEFAULT;
+ float vel_mag;
+ float *velX = smoke_get_velocity_x(sds->fluid);
+ float *velY = smoke_get_velocity_y(sds->fluid);
+ float *velZ = smoke_get_velocity_z(sds->fluid);
+ float density = 0.0f, fuel = 0.0f;
+ float pos[3];
+ copy_v3_v3(pos, position);
+ smoke_pos_to_cell(sds, pos);
+
+ /* check if point is outside domain max bounds */
+ if (pos[0] < sds->res_min[0] || pos[1] < sds->res_min[1] || pos[2] < sds->res_min[2]) return -1.0f;
+ if (pos[0] > sds->res_max[0] || pos[1] > sds->res_max[1] || pos[2] > sds->res_max[2]) return -1.0f;
+
+ /* map pos between 0.0 - 1.0 */
+ pos[0] = (pos[0] - sds->res_min[0]) / ((float)sds->res[0]);
+ pos[1] = (pos[1] - sds->res_min[1]) / ((float)sds->res[1]);
+ pos[2] = (pos[2] - sds->res_min[2]) / ((float)sds->res[2]);
+
+
+ /* check if point is outside active area */
+ if (smd->domain->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
+ if (pos[0] < 0.0f || pos[1] < 0.0f || pos[2] < 0.0f) return 0.0f;
+ if (pos[0] > 1.0f || pos[1] > 1.0f || pos[2] > 1.0f) return 0.0f;
+ }
+
+ /* get interpolated velocity */
+ velocity[0] = BLI_voxel_sample_trilinear(velX, sds->res, pos) * sds->global_size[0] * time_mult;
+ velocity[1] = BLI_voxel_sample_trilinear(velY, sds->res, pos) * sds->global_size[1] * time_mult;
+ velocity[2] = BLI_voxel_sample_trilinear(velZ, sds->res, pos) * sds->global_size[2] * time_mult;
+
+ /* convert velocity direction to global space */
+ vel_mag = len_v3(velocity);
+ mul_mat3_m4_v3(sds->obmat, velocity);
+ normalize_v3(velocity);
+ mul_v3_fl(velocity, vel_mag);
+
+ /* use max value of fuel or smoke density */
+ density = BLI_voxel_sample_trilinear(smoke_get_density(sds->fluid), sds->res, pos);
+ if (smoke_has_fuel(sds->fluid)) {
+ fuel = BLI_voxel_sample_trilinear(smoke_get_fuel(sds->fluid), sds->res, pos);
+ }
+ return MAX2(density, fuel);
+ }
+ return -1.0f;
+}
+
+int smoke_get_data_flags(SmokeDomainSettings *sds) {
+ int flags = 0;
+ if (smoke_has_heat(sds->fluid)) flags |= SM_ACTIVE_HEAT;
+ if (smoke_has_fuel(sds->fluid)) flags |= SM_ACTIVE_FIRE;
+ if (smoke_has_colors(sds->fluid)) flags |= SM_ACTIVE_COLORS;
+
+ return flags;
+}
+
#endif /* WITH_SMOKE */
diff --git a/source/blender/blenkernel/intern/softbody.c b/source/blender/blenkernel/intern/softbody.c
index 4a88bfbfdad..bb0cfe1a5c6 100644
--- a/source/blender/blenkernel/intern/softbody.c
+++ b/source/blender/blenkernel/intern/softbody.c
@@ -143,13 +143,15 @@ typedef struct SB_thread_context {
} SB_thread_context;
#define NLF_BUILD 1
-#define NLF_SOLVE 2
+#if 0
+# define NLF_SOLVE 2
+#endif
#define MID_PRESERVE 1
#define SOFTGOALSNAP 0.999f
/* if bp-> goal is above make it a *forced follow original* and skip all ODE stuff for this bp
- * removes *unnecessary* stiffnes from ODE system
+ * removes *unnecessary* stiffness from ODE system
*/
#define HEUNWARNLIMIT 1 /* 500 would be fine i think for detecting severe *stiff* stuff */
@@ -1168,7 +1170,7 @@ static int sb_detect_face_pointCached(float face_v1[3], float face_v2[3], float
*damp=df*tune*ob->pd->pdef_sbdamp;
- df = 0.01f*exp(- 100.0f*df);
+ df = 0.01f * expf(-100.0f * df);
Vec3PlusStVec(force, -df, d_nvect);
deflected = 3;
}
@@ -1596,7 +1598,7 @@ static void _scan_for_ext_spring_forces(Scene *scene, Object *ob, float timenow,
/*see if we have wind*/
if (do_effector) {
EffectedPoint epoint;
- float speed[3]={0.0f, 0.0f, 0.0f};
+ float speed[3] = {0.0f, 0.0f, 0.0f};
float pos[3];
mid_v3_v3v3(pos, sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos);
mid_v3_v3v3(vel, sb->bpoint[bs->v1].vec, sb->bpoint[bs->v2].vec);
@@ -1747,8 +1749,8 @@ static int sb_detect_vertex_collisionCached(float opco[3], float facenormal[3],
Object *ob= NULL;
GHash *hash;
GHashIterator *ihash;
- float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3], d_nvect[3], dv1[3], ve[3], avel[3]={0.0, 0.0, 0.0},
- vv1[3], vv2[3], vv3[3], vv4[3], coledge[3]={0.0f, 0.0f, 0.0f}, mindistedge = 1000.0f,
+ float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3], d_nvect[3], dv1[3], ve[3], avel[3] = {0.0, 0.0, 0.0},
+ vv1[3], vv2[3], vv3[3], vv4[3], coledge[3] = {0.0f, 0.0f, 0.0f}, mindistedge = 1000.0f,
outerforceaccu[3], innerforceaccu[3],
facedist, /* n_mag, */ /* UNUSED */ force_mag_norm, minx, miny, minz, maxx, maxy, maxz,
innerfacethickness = -0.5f, outerfacethickness = 0.2f,
@@ -2207,7 +2209,7 @@ static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, Object *ob, flo
bp = &sb->bpoint[ifirst];
for (bb=number_of_points_here; bb>0; bb--, bp++) {
/* clear forces accumulator */
- bp->force[0]= bp->force[1]= bp->force[2]= 0.0;
+ bp->force[0] = bp->force[1] = bp->force[2] = 0.0;
/* naive ball self collision */
/* needs to be done if goal snaps or not */
if (do_selfcollision) {
@@ -2302,8 +2304,8 @@ static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, Object *ob, flo
if (do_effector) {
EffectedPoint epoint;
float kd;
- float force[3]= {0.0f, 0.0f, 0.0f};
- float speed[3]= {0.0f, 0.0f, 0.0f};
+ float force[3] = {0.0f, 0.0f, 0.0f};
+ float speed[3] = {0.0f, 0.0f, 0.0f};
float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
pd_point_from_soft(scene, bp->pos, bp->vec, sb->bpoint-bp, &epoint);
pdDoEffectors(do_effector, NULL, sb->effector_weights, &epoint, force, speed);
@@ -2555,7 +2557,7 @@ static void softbody_calc_forces(Scene *scene, Object *ob, float forcetime, floa
for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
/* clear forces accumulator */
- bp->force[0]= bp->force[1]= bp->force[2]= 0.0;
+ bp->force[0] = bp->force[1] = bp->force[2] = 0.0;
if (nl_flags & NLF_BUILD) {
//int ia =3*(sb->totpoint-a);
//int op =3*sb->totpoint;
@@ -2710,8 +2712,8 @@ static void softbody_calc_forces(Scene *scene, Object *ob, float forcetime, floa
/* particle field & vortex */
if (do_effector) {
EffectedPoint epoint;
- float force[3]= {0.0f, 0.0f, 0.0f};
- float speed[3]= {0.0f, 0.0f, 0.0f};
+ float force[3] = {0.0f, 0.0f, 0.0f};
+ float speed[3] = {0.0f, 0.0f, 0.0f};
float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
pd_point_from_soft(scene, bp->pos, bp->vec, sb->bpoint-bp, &epoint);
pdDoEffectors(do_effector, NULL, sb->effector_weights, &epoint, force, speed);
@@ -2903,7 +2905,7 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *
/* or heun ~ 2nd order runge-kutta steps, mode 1, 2 */
SoftBody *sb= ob->soft; /* is supposed to be there */
BodyPoint *bp;
- float dx[3]={0}, dv[3], aabbmin[3], aabbmax[3], cm[3]={0.0f, 0.0f, 0.0f};
+ float dx[3] = {0}, dv[3], aabbmin[3], aabbmax[3], cm[3] = {0.0f, 0.0f, 0.0f};
float timeovermass/*, freezeloc=0.00001f, freezeforce=0.00000000001f*/;
float maxerrpos= 0.0f, maxerrvel = 0.0f;
int a, fuzzy=0;
@@ -3192,7 +3194,7 @@ static void interpolate_exciter(Object *ob, int timescale, int time)
- xxxx_to_softbody(Object *ob) : a full (new) copy, creates SB geometry
*/
-static void get_scalar_from_vertexgroup(Object *ob, int vertID, short groupindex, float *target)
+static void get_scalar_from_vertexgroup(Object *ob, int vertID, int groupindex, float *target)
/* result 0 on success, else indicates error number
-- kind of *inverse* result defintion,
-- but this way we can signal error condition to caller
@@ -3295,7 +3297,7 @@ static void mesh_to_softbody(Scene *scene, Object *ob)
if ((ob->softflag & OB_SB_GOAL) && sb->vertgroup) { /* even this is a deprecated evil hack */
/* I'd like to have it .. if (sb->namedVG_Goal[0]) */
- get_scalar_from_vertexgroup(ob, a, (short) (sb->vertgroup-1), &bp->goal);
+ get_scalar_from_vertexgroup(ob, a, sb->vertgroup - 1, &bp->goal);
/* do this always, regardless successful read from vertex group */
/* this is where '2.5 every thing is animatable' goes wrong in the first place jow_go_for2_5 */
/* 1st coding action to take : move this to frame level */
@@ -3314,10 +3316,10 @@ static void mesh_to_softbody(Scene *scene, Object *ob)
*/
if (sb->namedVG_Mass[0]) {
- int grp= defgroup_name_index (ob, sb->namedVG_Mass);
- /* printf("VGN %s %d\n", sb->namedVG_Mass, grp); */
- if (grp > -1) {
- get_scalar_from_vertexgroup(ob, a, (short) (grp), &bp->mass);
+ int defgrp_index = defgroup_name_index (ob, sb->namedVG_Mass);
+ /* printf("VGN %s %d\n", sb->namedVG_Mass, defgrp_index); */
+ if (defgrp_index != -1) {
+ get_scalar_from_vertexgroup(ob, a, defgrp_index, &bp->mass);
/* 2.5 bp->mass = bp->mass * sb->nodemass; */
/* printf("bp->mass %f\n", bp->mass); */
@@ -3327,10 +3329,10 @@ static void mesh_to_softbody(Scene *scene, Object *ob)
bp->springweight = 1.0f;
if (sb->namedVG_Spring_K[0]) {
- int grp= defgroup_name_index (ob, sb->namedVG_Spring_K);
- //printf("VGN %s %d\n", sb->namedVG_Spring_K, grp);
- if (grp > -1) {
- get_scalar_from_vertexgroup(ob, a, (short) (grp), &bp->springweight);
+ int defgrp_index = defgroup_name_index (ob, sb->namedVG_Spring_K);
+ //printf("VGN %s %d\n", sb->namedVG_Spring_K, defgrp_index);
+ if (defgrp_index != -1) {
+ get_scalar_from_vertexgroup(ob, a, defgrp_index , &bp->springweight);
//printf("bp->springweight %f\n", bp->springweight);
}
@@ -3863,7 +3865,7 @@ static void softbody_reset(Object *ob, SoftBody *sb, float (*vertexCos)[3], int
copy_v3_v3(bp->origS, bp->pos);
copy_v3_v3(bp->origE, bp->pos);
copy_v3_v3(bp->origT, bp->pos);
- bp->vec[0]= bp->vec[1]= bp->vec[2]= 0.0f;
+ bp->vec[0] = bp->vec[1] = bp->vec[2] = 0.0f;
/* the bp->prev*'s are for rolling back from a canceled try to propagate in time
* adaptive step size algo in a nutshell:
@@ -3923,7 +3925,7 @@ static void softbody_step(Scene *scene, Object *ob, SoftBody *sb, float dtime)
sst=PIL_check_seconds_timer();
/* Integration back in time is possible in theory, but pretty useless here.
- * So we refuse to do so. Since we do not know anything about 'outside' canges
+ * So we refuse to do so. Since we do not know anything about 'outside' changes
* especially colliders we refuse to go more than 10 frames.
*/
if (dtime < 0 || dtime > 10.5f) return;
@@ -4006,8 +4008,8 @@ static void softbody_step(Scene *scene, Object *ob, SoftBody *sb, float dtime)
}
loops++;
if (sb->solverflags & SBSO_MONITOR ) {
- sct=PIL_check_seconds_timer();
- if (sct-sst > 0.5f) printf("%3.0f%% \r", 100.0f*timedone/dtime);
+ sct = PIL_check_seconds_timer();
+ if (sct - sst > 0.5) printf("%3.0f%% \r", 100.0f * timedone / dtime);
}
/* ask for user break */
if (SB_localInterruptCallBack && SB_localInterruptCallBack()) break;
@@ -4043,7 +4045,7 @@ static void softbody_step(Scene *scene, Object *ob, SoftBody *sb, float dtime)
if (sb->solverflags & SBSO_MONITOR ) {
sct=PIL_check_seconds_timer();
- if ((sct-sst > 0.5f) || (G.debug & G_DEBUG)) printf(" solver time %f sec %s\n", sct-sst, ob->id.name);
+ if ((sct - sst > 0.5) || (G.debug & G_DEBUG)) printf(" solver time %f sec %s\n", sct-sst, ob->id.name);
}
}
diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c
index f340bcb5b1e..aad205bb5bf 100644
--- a/source/blender/blenkernel/intern/sound.c
+++ b/source/blender/blenkernel/intern/sound.c
@@ -701,7 +701,7 @@ void sound_update_scene(struct Scene *scene)
if (AUD_removeSet(scene->speaker_handles, strip->speaker_handle)) {
if (speaker->sound)
- AUD_moveSequence(strip->speaker_handle, strip->start / FPS, -1, 0);
+ AUD_moveSequence(strip->speaker_handle, (double)strip->start / FPS, -1, 0);
else {
AUD_removeSequence(scene->sound_scene, strip->speaker_handle);
strip->speaker_handle = NULL;
@@ -709,7 +709,9 @@ void sound_update_scene(struct Scene *scene)
}
else {
if (speaker->sound) {
- strip->speaker_handle = AUD_addSequence(scene->sound_scene, speaker->sound->playback_handle, strip->start / FPS, -1, 0);
+ strip->speaker_handle = AUD_addSequence(scene->sound_scene,
+ speaker->sound->playback_handle,
+ (double)strip->start / FPS, -1, 0);
AUD_setRelativeSequence(strip->speaker_handle, 0);
}
}
@@ -792,7 +794,6 @@ void sound_stop_scene(struct Scene *UNUSED(scene)) {}
void sound_seek_scene(struct Main *UNUSED(bmain), struct Scene *UNUSED(scene)) {}
float sound_sync_scene(struct Scene *UNUSED(scene)) { return NAN_FLT; }
int sound_scene_playing(struct Scene *UNUSED(scene)) { return -1; }
-int sound_read_sound_buffer(struct bSound *UNUSED(sound), float *UNUSED(buffer), int UNUSED(length), float UNUSED(start), float UNUSED(end)) { return 0; }
void sound_read_waveform(struct bSound *sound) { (void)sound; }
void sound_init_main(struct Main *bmain) { (void)bmain; }
void sound_set_cfra(int cfra) { (void)cfra; }
diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c
index 555ed5890c8..8a669b89907 100644
--- a/source/blender/blenkernel/intern/subsurf_ccg.c
+++ b/source/blender/blenkernel/intern/subsurf_ccg.c
@@ -513,10 +513,14 @@ static float *get_ss_weights(WeightTable *wtable, int gridCuts, int faceLen)
w2 = (1.0f - fx + fac2 * fx * -fac) * (fy);
w4 = (fx) * (1.0f - fy + -fac2 * fy * fac);
- fac2 = 1.0f - (w1 + w2 + w4);
- fac2 = fac2 / (float)(faceLen - 3);
- for (j = 0; j < faceLen; j++)
- w[j] = fac2;
+ /* these values aren't used for tri's and cause divide by zero */
+ if (faceLen > 3) {
+ fac2 = 1.0f - (w1 + w2 + w4);
+ fac2 = fac2 / (float)(faceLen - 3);
+ for (j = 0; j < faceLen; j++) {
+ w[j] = fac2;
+ }
+ }
w[i] = w1;
w[(i - 1 + faceLen) % faceLen] = w2;
@@ -598,7 +602,7 @@ static void ss_sync_from_derivedmesh(CCGSubSurf *ss, DerivedMesh *dm,
}
mp = mpoly;
- index = DM_get_poly_data_layer(dm, CD_ORIGINDEX);
+ index = (int *)dm->getPolyDataArray(dm, CD_ORIGINDEX);
for (i = 0; i < dm->numPolyData; i++, mp++) {
CCGFace *f;
@@ -2702,6 +2706,30 @@ static void *ccgDM_get_tessface_data_layer(DerivedMesh *dm, int type)
{
if (type == CD_ORIGINDEX) {
/* create origindex on demand to save memory */
+ int *origindex;
+
+ /* Avoid re-creation if the layer exists already */
+ origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
+ if (origindex) {
+ return origindex;
+ }
+
+ DM_add_tessface_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
+ origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
+
+ /* silly loop counting up */
+ range_vn_i(origindex, dm->getNumTessFaces(dm), 0);
+
+ return origindex;
+ }
+
+ return DM_get_tessface_data_layer(dm, type);
+}
+
+static void *ccgDM_get_poly_data_layer(DerivedMesh *dm, int type)
+{
+ if (type == CD_ORIGINDEX) {
+ /* create origindex on demand to save memory */
CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
CCGSubSurf *ss = ccgdm->ss;
int *origindex;
@@ -2709,13 +2737,13 @@ static void *ccgDM_get_tessface_data_layer(DerivedMesh *dm, int type)
int gridFaces = ccgSubSurf_getGridSize(ss) - 1;
/* Avoid re-creation if the layer exists already */
- origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
+ origindex = DM_get_poly_data_layer(dm, CD_ORIGINDEX);
if (origindex) {
return origindex;
}
- DM_add_tessface_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
- origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
+ DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
+ origindex = DM_get_poly_data_layer(dm, CD_ORIGINDEX);
totface = ccgSubSurf_getNumFaces(ss);
@@ -2731,7 +2759,7 @@ static void *ccgDM_get_tessface_data_layer(DerivedMesh *dm, int type)
return origindex;
}
- return DM_get_tessface_data_layer(dm, type);
+ return DM_get_poly_data_layer(dm, type);
}
static void *ccgDM_get_vert_data(DerivedMesh *dm, int index, int type)
@@ -2764,6 +2792,16 @@ static void *ccgDM_get_tessface_data(DerivedMesh *dm, int index, int type)
return DM_get_tessface_data(dm, index, type);
}
+static void *ccgDM_get_poly_data(DerivedMesh *dm, int index, int type)
+{
+ if (type == CD_ORIGINDEX) {
+ /* ensure creation of CD_ORIGINDEX layer */
+ ccgDM_get_tessface_data_layer(dm, type);
+ }
+
+ return DM_get_poly_data(dm, index, type);
+}
+
static int ccgDM_getNumGrids(DerivedMesh *dm)
{
CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
@@ -3016,6 +3054,9 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm)
me->totface, me->totvert, &me->vdata);
}
+ if (ccgdm->pbvh)
+ pbvh_show_diffuse_color_set(ccgdm->pbvh, ob->sculpt->show_diffuse_color);
+
return ccgdm->pbvh;
}
@@ -3091,7 +3132,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
}
/* We absolutely need that layer, else it's no valid tessellated data! */
- polyidx = CustomData_add_layer(&ccgdm->dm.faceData, CD_POLYINDEX, CD_CALLOC,
+ polyidx = CustomData_add_layer(&ccgdm->dm.faceData, CD_ORIGINDEX, CD_CALLOC,
NULL, ccgSubSurf_getNumFinalFaces(ss));
ccgdm->dm.getMinMax = ccgDM_getMinMax;
@@ -3119,9 +3160,11 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
ccgdm->dm.getVertData = ccgDM_get_vert_data;
ccgdm->dm.getEdgeData = ccgDM_get_edge_data;
ccgdm->dm.getTessFaceData = ccgDM_get_tessface_data;
+ ccgdm->dm.getPolyData = ccgDM_get_poly_data;
ccgdm->dm.getVertDataArray = ccgDM_get_vert_data_layer;
ccgdm->dm.getEdgeDataArray = ccgDM_get_edge_data_layer;
ccgdm->dm.getTessFaceDataArray = ccgDM_get_tessface_data_layer;
+ ccgdm->dm.getPolyDataArray = ccgDM_get_poly_data_layer;
ccgdm->dm.getNumGrids = ccgDM_getNumGrids;
ccgdm->dm.getGridSize = ccgDM_getGridSize;
ccgdm->dm.getGridData = ccgDM_getGridData;
@@ -3220,8 +3263,8 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
vertOrigIndex = DM_get_vert_data_layer(&ccgdm->dm, CD_ORIGINDEX);
/*edgeOrigIndex = DM_get_edge_data_layer(&ccgdm->dm, CD_ORIGINDEX);*/
- faceOrigIndex = DM_get_tessface_data_layer(&ccgdm->dm, CD_ORIGINDEX);
+ faceOrigIndex = DM_get_tessface_data_layer(&ccgdm->dm, CD_ORIGINDEX);
polyOrigIndex = DM_get_poly_data_layer(&ccgdm->dm, CD_ORIGINDEX);
#if 0
@@ -3359,7 +3402,8 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
/*set original index data*/
if (faceOrigIndex) {
- *faceOrigIndex = origIndex;
+ /* reference the index in 'polyOrigIndex' */
+ *faceOrigIndex = faceNum;
faceOrigIndex++;
}
if (polyOrigIndex) {
diff --git a/source/blender/blenkernel/intern/text.c b/source/blender/blenkernel/intern/text.c
index 3c89fdba13a..b3497b9932f 100644
--- a/source/blender/blenkernel/intern/text.c
+++ b/source/blender/blenkernel/intern/text.c
@@ -48,18 +48,22 @@
#include "DNA_constraint_types.h"
#include "DNA_controller_types.h"
+#include "DNA_actuator_types.h"
#include "DNA_scene_types.h"
#include "DNA_screen_types.h"
#include "DNA_space_types.h"
#include "DNA_text_types.h"
#include "DNA_userdef_types.h"
#include "DNA_object_types.h"
+#include "DNA_node_types.h"
+#include "DNA_material_types.h"
#include "BKE_depsgraph.h"
#include "BKE_global.h"
#include "BKE_library.h"
#include "BKE_main.h"
#include "BKE_text.h"
+#include "BKE_node.h"
#ifdef WITH_PYTHON
@@ -313,7 +317,7 @@ int BKE_text_reload(Text *text)
fseek(fp, 0L, SEEK_END);
len = ftell(fp);
- fseek(fp, 0L, SEEK_SET);
+ fseek(fp, 0L, SEEK_SET);
text->undo_pos = -1;
@@ -369,7 +373,7 @@ int BKE_text_reload(Text *text)
text->curl = text->sell = text->lines.first;
text->curc = text->selc = 0;
- MEM_freeN(buffer);
+ MEM_freeN(buffer);
return 1;
}
@@ -403,7 +407,7 @@ Text *BKE_text_load(const char *file, const char *relpath)
fseek(fp, 0L, SEEK_END);
len = ftell(fp);
- fseek(fp, 0L, SEEK_SET);
+ fseek(fp, 0L, SEEK_SET);
ta->name = MEM_mallocN(strlen(file) + 1, "text_name");
strcpy(ta->name, file);
@@ -468,7 +472,7 @@ Text *BKE_text_load(const char *file, const char *relpath)
ta->curl = ta->sell = ta->lines.first;
ta->curc = ta->selc = 0;
- MEM_freeN(buffer);
+ MEM_freeN(buffer);
return ta;
}
@@ -528,7 +532,11 @@ void BKE_text_unlink(Main *bmain, Text *text)
SpaceLink *sl;
Object *ob;
bController *cont;
+ bActuator *act;
bConstraint *con;
+ bNodeTree *ntree;
+ bNode *node;
+ Material *mat;
short update;
for (ob = bmain->object.first; ob; ob = ob->id.next) {
@@ -541,6 +549,15 @@ void BKE_text_unlink(Main *bmain, Text *text)
if (pc->text == text) pc->text = NULL;
}
}
+ /* game actuators */
+ for (act = ob->actuators.first; act; act = act->next) {
+ if (act->type == ACT_2DFILTER) {
+ bTwoDFilterActuator *tfa;
+
+ tfa = act->data;
+ if (tfa->text == text) tfa->text = NULL;
+ }
+ }
/* pyconstraints */
update = 0;
@@ -571,6 +588,28 @@ void BKE_text_unlink(Main *bmain, Text *text)
DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
}
+ /* nodes */
+ for (mat = bmain->mat.first; mat; mat = mat->id.next) {
+ ntree = mat->nodetree;
+ if (!ntree)
+ continue;
+ for (node = ntree->nodes.first; node; node = node->next) {
+ if (node->type == SH_NODE_SCRIPT) {
+ Text *ntext = (Text *)node->id;
+ if (ntext == text) node->id = NULL;
+ }
+ }
+ }
+
+ for (ntree = bmain->nodetree.first; ntree; ntree = ntree->id.next) {
+ for (node = ntree->nodes.first; node; node = node->next) {
+ if (node->type == SH_NODE_SCRIPT) {
+ Text *ntext = (Text *)node->id;
+ if (ntext == text) node->id = NULL;
+ }
+ }
+ }
+
/* text space */
for (scr = bmain->screen.first; scr; scr = scr->id.next) {
for (area = scr->areabase.first; area; area = area->next) {
@@ -672,7 +711,7 @@ void txt_clean_text(Text *text)
if (!text->lines.first) {
if (text->lines.last) text->lines.first = text->lines.last;
else text->lines.first = text->lines.last = txt_new_line(NULL);
- }
+ }
if (!text->lines.last) text->lines.last = text->lines.first;
@@ -721,7 +760,7 @@ int txt_get_span(TextLine *from, TextLine *to)
if (!tmp) ret = 0;
}
- return ret;
+ return ret;
}
static void txt_make_dirty(Text *text)
@@ -923,7 +962,7 @@ void txt_move_right(Text *text, short sel)
txt_move_down(text, sel);
*charp = 0;
}
- }
+ }
else {
// do nice right only if there are only spaces
// spaces hardcoded in DNA_text_types.h
@@ -1365,7 +1404,7 @@ int txt_find_string(Text *text, const char *findstr, int wrap, int match_case)
int newc = (int)(s - tl->line);
txt_move_to(text, newl, newc, 0);
txt_move_to(text, newl, newc + strlen(findstr), 1);
- return 1;
+ return 1;
}
else
return 0;
@@ -1447,7 +1486,7 @@ char *txt_sel_to_buf(Text *text)
length += charl;
buf[length] = 0;
- }
+ }
return buf;
}
@@ -1919,6 +1958,7 @@ static unsigned int txt_undo_read_unicode(const char *undo_buf, int *undo_pos, s
break;
case 4: /* 32-bit unicode symbol */
unicode = txt_undo_read_uint32(undo_buf, undo_pos);
+ break;
default:
/* should never happen */
BLI_assert(0);
@@ -1970,6 +2010,7 @@ static unsigned int txt_redo_read_unicode(const char *undo_buf, int *undo_pos, s
break;
case 4: /* 32-bit unicode symbol */
unicode = txt_undo_read_uint32(undo_buf, undo_pos);
+ break;
default:
/* should never happen */
BLI_assert(0);
@@ -2065,7 +2106,7 @@ void txt_do_undo(Text *text)
charp = op - UNDO_BS_1 + 1;
txt_add_char(text, txt_undo_read_unicode(text->undo_buf, &text->undo_pos, charp));
text->undo_pos--;
- break;
+ break;
case UNDO_DEL_1: case UNDO_DEL_2: case UNDO_DEL_3: case UNDO_DEL_4:
charp = op - UNDO_DEL_1 + 1;
@@ -2091,7 +2132,7 @@ void txt_do_undo(Text *text)
txt_curs_first(text, &holdl, &holdc);
holdln = txt_get_span(text->lines.first, holdl);
- txt_insert_buf(text, buf);
+ txt_insert_buf(text, buf);
MEM_freeN(buf);
text->curl = text->lines.first;
@@ -2222,7 +2263,7 @@ void txt_do_redo(Text *text)
unsigned short charp;
char *buf;
- text->undo_pos++;
+ text->undo_pos++;
op = text->undo_buf[text->undo_pos];
if (!op) {
@@ -2338,7 +2379,7 @@ void txt_do_redo(Text *text)
text->undo_pos += linep;
buf[linep] = 0;
- txt_insert_buf(text, buf);
+ txt_insert_buf(text, buf);
MEM_freeN(buf);
text->undo_pos++;
@@ -2356,7 +2397,7 @@ void txt_do_redo(Text *text)
//charp is the first char selected or 0
linep = txt_redo_read_uint32(text->undo_buf, &text->undo_pos);
- //linep is now the first line of the selection
+ //linep is now the first line of the selection
//set the selcetion for this now
text->curc = charp;
text->curl = text->lines.first;
@@ -2463,7 +2504,7 @@ void txt_split_curline(Text *text)
text->curl->format = NULL;
text->curl->len = text->curl->len - text->curc;
- BLI_insertlinkbefore(&text->lines, text->curl, ins);
+ BLI_insertlinkbefore(&text->lines, text->curl, ins);
text->curc = 0;
diff --git a/source/blender/blenkernel/intern/texture.c b/source/blender/blenkernel/intern/texture.c
index bdd9b424f3b..6d0313f6334 100644
--- a/source/blender/blenkernel/intern/texture.c
+++ b/source/blender/blenkernel/intern/texture.c
@@ -571,7 +571,7 @@ void default_mtex(MTex *mtex)
mtex->size[1] = 1.0;
mtex->size[2] = 1.0;
mtex->tex = NULL;
- mtex->texflag = MTEX_3TAP_BUMP | MTEX_BUMP_OBJECTSPACE;
+ mtex->texflag = MTEX_3TAP_BUMP | MTEX_BUMP_OBJECTSPACE | MTEX_MAPTO_BOUNDS;
mtex->colormodel = 0;
mtex->r = 1.0;
mtex->g = 0.0;
@@ -646,7 +646,7 @@ MTex *add_mtex_id(ID *id, int slot)
if (slot == -1) {
/* find first free */
- int i;
+ int i;
for (i = 0; i < MAX_MTEX; i++) {
if (!mtex_ar[i]) {
slot = i;
@@ -909,8 +909,7 @@ void autotexname(Tex *tex)
if (tex->use_nodes) {
new_id(&bmain->tex, (ID *)tex, "Noddy");
}
- else
- if (tex->type == TEX_IMAGE) {
+ else if (tex->type == TEX_IMAGE) {
ima = tex->ima;
if (ima) {
BLI_strncpy(di, ima->name, sizeof(di));
@@ -1073,19 +1072,21 @@ void set_current_material_texture(Material *ma, Tex *newtex)
{
Tex *tex = NULL;
bNode *node;
-
- if (ma && ma->use_nodes && ma->nodetree) {
- node = nodeGetActiveID(ma->nodetree, ID_TE);
- if (node) {
- tex = (Tex *)node->id;
- id_us_min(&tex->id);
+ if ((ma->use_nodes && ma->nodetree) &&
+ (node = nodeGetActiveID(ma->nodetree, ID_TE)))
+ {
+ tex = (Tex *)node->id;
+ id_us_min(&tex->id);
+ if (newtex) {
node->id = &newtex->id;
id_us_plus(&newtex->id);
- ma = NULL;
+ }
+ else {
+ node->id = NULL;
}
}
- if (ma) {
+ else {
int act = (int)ma->texact;
tex = (ma->mtex[act]) ? ma->mtex[act]->tex : NULL;
diff --git a/source/blender/blenkernel/intern/tracking.c b/source/blender/blenkernel/intern/tracking.c
index 97ebc3a90ba..89446a1856f 100644
--- a/source/blender/blenkernel/intern/tracking.c
+++ b/source/blender/blenkernel/intern/tracking.c
@@ -51,6 +51,8 @@
#include "BLI_string.h"
#include "BLI_threads.h"
+#include "BLF_translation.h"
+
#include "BKE_global.h"
#include "BKE_tracking.h"
#include "BKE_movieclip.h"
@@ -169,10 +171,9 @@ void BKE_tracking_settings_init(MovieTracking *tracking)
tracking->settings.default_minimum_correlation = 0.75;
tracking->settings.default_pattern_size = 11;
tracking->settings.default_search_size = 61;
- tracking->settings.keyframe1 = 1;
- tracking->settings.keyframe2 = 30;
tracking->settings.dist = 1;
tracking->settings.object_distance = 1;
+ tracking->settings.reconstruction_success_threshold = 1e-3;
tracking->stabilization.scaleinf = 1.0f;
tracking->stabilization.locinf = 1.0f;
@@ -223,7 +224,7 @@ void BKE_tracking_get_projection_matrix(MovieTracking *tracking, MovieTrackingOb
float viewfac, pixsize, left, right, bottom, top, clipsta, clipend;
float winmat[4][4];
float ycor = 1.0f / tracking->camera.pixel_aspect;
- float shiftx, shifty, winside = MAX2(winx, winy);
+ float shiftx, shifty, winside = (float)min_ii(winx, winy);
BKE_tracking_camera_shift_get(tracking, winx, winy, &shiftx, &shifty);
@@ -335,7 +336,7 @@ static void search_pixel_to_marker_unified(int frame_width, int frame_height,
}
/* Each marker has 5 coordinates associated with it that get warped with
- * tracking: the four corners ("pattern_corners"), and the cernter ("pos").
+ * tracking: the four corners ("pattern_corners"), and the center ("pos").
* This function puts those 5 points into the appropriate frame for tracking
* (the "search" coordinate frame).
*/
@@ -455,7 +456,7 @@ void BKE_tracking_clipboard_paste_tracks(MovieTracking *tracking, MovieTrackingO
/*********************** Tracks *************************/
-static void tracking_marker_insert_disabled(MovieTrackingTrack *track, MovieTrackingMarker *ref_marker,
+static void tracking_marker_insert_disabled(MovieTrackingTrack *track, const MovieTrackingMarker *ref_marker,
int before, int overwrite)
{
MovieTrackingMarker marker_new;
@@ -633,7 +634,7 @@ void BKE_tracking_track_path_clear(MovieTrackingTrack *track, int ref_frame, int
}
}
-void BKE_tracking_tracks_join(MovieTrackingTrack *dst_track, MovieTrackingTrack *src_track)
+void BKE_tracking_tracks_join(MovieTracking *tracking, MovieTrackingTrack *dst_track, MovieTrackingTrack *src_track)
{
int i = 0, a = 0, b = 0, tot;
MovieTrackingMarker *markers;
@@ -736,6 +737,8 @@ void BKE_tracking_tracks_join(MovieTrackingTrack *dst_track, MovieTrackingTrack
dst_track->markersnr = i;
MEM_freeN(markers);
+
+ BKE_tracking_dopesheet_tag_update(tracking);
}
MovieTrackingTrack *BKE_tracking_track_get_named(MovieTracking *tracking, MovieTrackingObject *object, const char *name)
@@ -856,7 +859,7 @@ static void track_mask_gpencil_layer_rasterize(int frame_width, int frame_height
}
/* TODO: add an option to control whether AA is enabled or not */
- PLX_raskterize((float (*)[2])mask_points, stroke->totpoints, mask, mask_width, mask_height, FALSE);
+ PLX_raskterize((float (*)[2])mask_points, stroke->totpoints, mask, mask_width, mask_height);
MEM_freeN(mask_points);
}
@@ -997,8 +1000,8 @@ void BKE_tracking_marker_clamp(MovieTrackingMarker *marker, int event)
if (event == CLAMP_PAT_DIM) {
for (a = 0; a < 2; a++) {
/* search shouldn't be resized smaller than pattern */
- marker->search_min[a] = minf(pat_min[a], marker->search_min[a]);
- marker->search_max[a] = maxf(pat_max[a], marker->search_max[a]);
+ marker->search_min[a] = min_ff(pat_min[a], marker->search_min[a]);
+ marker->search_max[a] = max_ff(pat_max[a], marker->search_max[a]);
}
}
else if (event == CLAMP_PAT_POS) {
@@ -1022,8 +1025,8 @@ void BKE_tracking_marker_clamp(MovieTrackingMarker *marker, int event)
else if (event == CLAMP_SEARCH_DIM) {
for (a = 0; a < 2; a++) {
/* search shouldn't be resized smaller than pattern */
- marker->search_min[a] = minf(pat_min[a], marker->search_min[a]);
- marker->search_max[a] = maxf(pat_max[a], marker->search_max[a]);
+ marker->search_min[a] = min_ff(pat_min[a], marker->search_min[a]);
+ marker->search_max[a] = max_ff(pat_max[a], marker->search_max[a]);
}
}
else if (event == CLAMP_SEARCH_POS) {
@@ -1043,14 +1046,6 @@ void BKE_tracking_marker_clamp(MovieTrackingMarker *marker, int event)
}
}
}
- else if (event == CLAMP_SEARCH_DIM) {
- float dim[2];
- sub_v2_v2v2(dim, pat_max, pat_min);
- for (a = 0; a < 2; a++) {
- marker->search_min[a] = pat_min[a];
- marker->search_max[a] = pat_max[a];
- }
- }
}
MovieTrackingMarker *BKE_tracking_marker_get(MovieTrackingTrack *track, int framenr)
@@ -1187,23 +1182,25 @@ MovieTrackingObject *BKE_tracking_object_add(MovieTracking *tracking, const char
tracking->objectnr = BLI_countlist(&tracking->objects) - 1;
object->scale = 1.0f;
+ object->keyframe1 = 1;
+ object->keyframe2 = 30;
BKE_tracking_object_unique_name(tracking, object);
return object;
}
-void BKE_tracking_object_delete(MovieTracking *tracking, MovieTrackingObject *object)
+int BKE_tracking_object_delete(MovieTracking *tracking, MovieTrackingObject *object)
{
MovieTrackingTrack *track;
int index = BLI_findindex(&tracking->objects, object);
- if (index < 0)
- return;
+ if (index == -1)
+ return FALSE;
if (object->flag & TRACKING_OBJECT_CAMERA) {
/* object used for camera solving can't be deleted */
- return;
+ return FALSE;
}
track = object->tracks.first;
@@ -1219,10 +1216,11 @@ void BKE_tracking_object_delete(MovieTracking *tracking, MovieTrackingObject *ob
tracking->tot_object--;
- if (index > 0)
+ if (index != 0)
tracking->objectnr = index - 1;
else
tracking->objectnr = 0;
+ return TRUE;
}
void BKE_tracking_object_unique_name(MovieTracking *tracking, MovieTrackingObject *object)
@@ -1502,7 +1500,8 @@ ImBuf *BKE_tracking_distortion_exec(MovieDistortion *distortion, MovieTracking *
ibuf->x, ibuf->y, overscan, ibuf->channels);
}
- resibuf->userflags |= IB_RECT_INVALID;
+ if (ibuf->rect)
+ imb_freerectImBuf(ibuf);
}
else {
if (undistort) {
@@ -1520,9 +1519,8 @@ ImBuf *BKE_tracking_distortion_exec(MovieDistortion *distortion, MovieTracking *
(void) overscan;
(void) undistort;
- if (ibuf->rect_float) {
- resibuf->userflags |= IB_RECT_INVALID;
- }
+ if (ibuf->rect_float && ibuf->rect)
+ imb_freerectImBuf(ibuf);
#endif
return resibuf;
@@ -2029,7 +2027,7 @@ static void track_context_free(void *customdata)
{
TrackContext *track_context = (TrackContext *)customdata;
-#if WITH_LIBMV
+#ifdef WITH_LIBMV
if (track_context->search_area)
MEM_freeN(track_context->search_area);
@@ -2144,7 +2142,7 @@ void BKE_tracking_context_sync(MovieTrackingContext *context)
context->sync_frame = newframe;
- tracking->dopesheet.ok = FALSE;
+ BKE_tracking_dopesheet_tag_update(tracking);
}
void BKE_tracking_context_sync_user(const MovieTrackingContext *context, MovieClipUser *user)
@@ -2289,9 +2287,9 @@ static ImBuf *tracking_context_get_reference_ibuf(MovieTrackingContext *context,
return ibuf;
}
-static void track_context_update_reference(MovieTrackingContext *context, TrackContext *track_context,
- MovieTrackingTrack *track, MovieTrackingMarker *marker, int curfra,
- int frame_width, int frame_height)
+static int track_context_update_reference(MovieTrackingContext *context, TrackContext *track_context,
+ MovieTrackingTrack *track, MovieTrackingMarker *marker, int curfra,
+ int frame_width, int frame_height)
{
MovieTrackingMarker *marker_keyed = NULL;
ImBuf *reference_ibuf = NULL;
@@ -2299,6 +2297,10 @@ static void track_context_update_reference(MovieTrackingContext *context, TrackC
/* calculate patch for keyframed position */
reference_ibuf = tracking_context_get_reference_ibuf(context, track, marker, curfra, &marker_keyed);
+
+ if (!reference_ibuf)
+ return FALSE;
+
track_context->marker = *marker_keyed;
if (track_context->search_area) {
@@ -2317,6 +2319,8 @@ static void track_context_update_reference(MovieTrackingContext *context, TrackC
}
IMB_freeImBuf(reference_ibuf);
+
+ return TRUE;
}
static void tracking_configure_tracker(TrackContext *track_context, MovieTrackingTrack *track,
@@ -2345,10 +2349,10 @@ static int tracking_check_marker_margin(MovieTrackingTrack *track, MovieTracking
/* margin from frame boundaries */
BKE_tracking_marker_pattern_minmax(marker, pat_min, pat_max);
sub_v2_v2v2(dim, pat_max, pat_min);
- margin[0] = margin[1] = maxf(dim[0], dim[1]) / 2.0f;
+ margin[0] = margin[1] = max_ff(dim[0], dim[1]) / 2.0f;
- margin[0] = maxf(margin[0], (float)track->margin / frame_width);
- margin[1] = maxf(margin[1], (float)track->margin / frame_height);
+ margin[0] = max_ff(margin[0], (float)track->margin / frame_width);
+ margin[1] = max_ff(margin[1], (float)track->margin / frame_height);
/* do not track markers which are too close to boundary */
if (marker->pos[0] < margin[0] || marker->pos[0] > 1.0f - margin[0] ||
@@ -2402,7 +2406,7 @@ static void tracking_insert_new_marker(MovieTrackingContext *context, MovieTrack
* if so -- create disabled marker before currently tracking "segment"
*/
- tracking_marker_insert_disabled(track, &new_marker, !context->backwards, FALSE);
+ tracking_marker_insert_disabled(track, old_marker, !context->backwards, FALSE);
}
/* insert currently tracked marker */
@@ -2481,8 +2485,12 @@ int BKE_tracking_context_step(MovieTrackingContext *context)
float *patch_new;
if (need_readjust) {
- track_context_update_reference(context, track_context, track, marker,
- curfra, frame_width, frame_height);
+ if (track_context_update_reference(context, track_context, track, marker,
+ curfra, frame_width, frame_height) == FALSE)
+ {
+ /* happens when reference frame fails to be loaded */
+ continue;
+ }
}
/* for now track to the same search area dimension as marker has got for current frame
@@ -2554,6 +2562,9 @@ typedef struct MovieReconstructContext {
TracksMap *tracks_map;
+ float success_threshold;
+ int use_fallback_reconstruction;
+
int sfra, efra;
} MovieReconstructContext;
@@ -2753,10 +2764,11 @@ static int reconstruct_refine_intrinsics_get_flags(MovieTracking *tracking, Movi
return flags;
}
-static int reconstruct_count_tracks_on_both_keyframes(MovieTracking *tracking, ListBase *tracksbase)
+static int reconstruct_count_tracks_on_both_keyframes(MovieTracking *tracking, MovieTrackingObject *object)
{
+ ListBase *tracksbase = BKE_tracking_object_get_tracks(tracking, object);
int tot = 0;
- int frame1 = tracking->settings.keyframe1, frame2 = tracking->settings.keyframe2;
+ int frame1 = object->keyframe1, frame2 = object->keyframe2;
MovieTrackingTrack *track;
track = tracksbase->first;
@@ -2776,15 +2788,13 @@ static int reconstruct_count_tracks_on_both_keyframes(MovieTracking *tracking, L
int BKE_tracking_reconstruction_check(MovieTracking *tracking, MovieTrackingObject *object, char *error_msg, int error_size)
{
-#if WITH_LIBMV
- ListBase *tracksbase = BKE_tracking_object_get_tracks(tracking, object);
-
+#ifdef WITH_LIBMV
if (tracking->settings.motion_flag & TRACKING_MOTION_MODAL) {
/* TODO: check for number of tracks? */
return TRUE;
}
- else if (reconstruct_count_tracks_on_both_keyframes(tracking, tracksbase) < 8) {
- BLI_strncpy(error_msg, "At least 8 common tracks on both of keyframes are needed for reconstruction",
+ else if (reconstruct_count_tracks_on_both_keyframes(tracking, object) < 8) {
+ BLI_strncpy(error_msg, N_("At least 8 common tracks on both of keyframes are needed for reconstruction"),
error_size);
return FALSE;
@@ -2792,7 +2802,7 @@ int BKE_tracking_reconstruction_check(MovieTracking *tracking, MovieTrackingObje
return TRUE;
#else
- BLI_strncpy(error_msg, "Blender is compiled without motion tracking library", error_size);
+ BLI_strncpy(error_msg, N_("Blender is compiled without motion tracking library"), error_size);
(void) tracking;
(void) object;
@@ -2824,6 +2834,9 @@ MovieReconstructContext *BKE_tracking_reconstruction_context_new(MovieTracking *
context->k2 = camera->k2;
context->k3 = camera->k3;
+ context->success_threshold = tracking->settings.reconstruction_success_threshold;
+ context->use_fallback_reconstruction = tracking->settings.reconstruction_flag & TRACKING_USE_FALLBACK_RECONSTRUCTION;
+
context->tracks_map = tracks_map_new(context->object_name, context->is_camera, num_tracks, 0);
track = tracksbase->first;
@@ -2845,10 +2858,10 @@ MovieReconstructContext *BKE_tracking_reconstruction_context_new(MovieTracking *
}
if (first < track->markersnr - 1)
- sfra = MIN2(sfra, first_marker->framenr);
+ sfra = min_ii(sfra, first_marker->framenr);
if (last >= 0)
- efra = MAX2(efra, last_marker->framenr);
+ efra = max_ii(efra, last_marker->framenr);
tracks_map_insert(context->tracks_map, track, NULL);
@@ -2923,12 +2936,18 @@ void BKE_tracking_reconstruction_solve(MovieReconstructContext *context, short *
reconstruct_update_solve_cb, &progressdata);
}
else {
+ struct libmv_reconstructionOptions options;
+
+ options.success_threshold = context->success_threshold;
+ options.use_fallback_reconstruction = context->use_fallback_reconstruction;
+
context->reconstruction = libmv_solveReconstruction(context->tracks,
context->keyframe1, context->keyframe2,
context->refine_flags,
context->focal_length,
context->principal_point[0], context->principal_point[1],
context->k1, context->k2, context->k3,
+ &options,
reconstruct_update_solve_cb, &progressdata);
}
@@ -2950,6 +2969,7 @@ int BKE_tracking_reconstruction_finish(MovieReconstructContext *context, MovieTr
MovieTrackingReconstruction *reconstruction;
tracks_map_merge(context->tracks_map, tracking);
+ BKE_tracking_dopesheet_tag_update(tracking);
if (context->is_camera) {
reconstruction = &tracking->reconstruction;
@@ -3195,8 +3215,8 @@ static float stabilization_calculate_autoscale_factor(MovieTracking *tracking, i
if (track->flag & TRACK_USE_2D_STAB ||
((stab->flag & TRACKING_STABILIZE_ROTATION) && track == stab->rot_track))
{
- sfra = MIN2(sfra, track->markers[0].framenr);
- efra = MAX2(efra, track->markers[track->markersnr - 1].framenr);
+ sfra = min_ii(sfra, track->markers[0].framenr);
+ efra = max_ii(efra, track->markers[track->markersnr - 1].framenr);
}
track = track->next;
@@ -3272,7 +3292,7 @@ static float stabilization_calculate_autoscale_factor(MovieTracking *tracking, i
S = (-w * I - h * J) / (dx * I + dy * J + K);
- scale = maxf(scale, S);
+ scale = max_ff(scale, S);
}
}
}
@@ -3281,7 +3301,7 @@ static float stabilization_calculate_autoscale_factor(MovieTracking *tracking, i
stab->scale = scale;
if (stab->maxscale > 0.0f)
- stab->scale = minf(stab->scale, stab->maxscale);
+ stab->scale = min_ff(stab->scale, stab->maxscale);
}
else {
stab->scale = 1.0f;
@@ -3640,7 +3660,7 @@ static void channels_segments_calc(MovieTrackingDopesheetChannel *channel)
channel->segments[2 * segment] = start_marker->framenr;
channel->segments[2 * segment + 1] = start_marker->framenr + len;
- channel->max_segment = MAX2(channel->max_segment, len);
+ channel->max_segment = max_ii(channel->max_segment, len);
segment++;
}
@@ -3648,7 +3668,7 @@ static void channels_segments_calc(MovieTrackingDopesheetChannel *channel)
}
}
-static void tracking_dopesheet_sort(MovieTracking *tracking, int sort_method, int inverse)
+static void tracking_dopesheet_sort(MovieTracking *tracking, int sort_method, int inverse)
{
MovieTrackingDopesheet *dopesheet = &tracking->dopesheet;
diff --git a/source/blender/blenkernel/intern/unit.c b/source/blender/blenkernel/intern/unit.c
index da5e7ff3db7..84e1f29f6c0 100644
--- a/source/blender/blenkernel/intern/unit.c
+++ b/source/blender/blenkernel/intern/unit.c
@@ -259,7 +259,7 @@ static struct bUnitCollection buNaturalTimeCollecton = {buNaturalTimeDef, 3, 0,
static struct bUnitDef buNaturalRotDef[] = {
- {"degree", "degrees", "°", NULL, "Degrees", M_PI/180.0, 0.0, B_UNIT_DEF_NONE},
+ {"degree", "degrees", "°", NULL, "Degrees", M_PI / 180.0, 0.0, B_UNIT_DEF_NONE},
// {"radian", "radians", "r", NULL, "Radians", 1.0, 0.0, B_UNIT_DEF_NONE},
// {"turn", "turns", "t", NULL, "Turns", 1.0/(M_PI*2.0), 0.0,B_UNIT_DEF_NONE},
{NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
@@ -350,7 +350,7 @@ static int unit_as_string(char *str, int len_max, double value, int prec, bUnitC
/* Add unit prefix and strip zeros */
/* replace trailing zero's with spaces
- * so the number is less complicated but allignment in a button wont
+ * so the number is less complicated but alignment in a button wont
* jump about while dragging */
i = len - 1;
diff --git a/source/blender/blenkernel/intern/world.c b/source/blender/blenkernel/intern/world.c
index 434bfe19c1f..4bde895cf7d 100644
--- a/source/blender/blenkernel/intern/world.c
+++ b/source/blender/blenkernel/intern/world.c
@@ -107,7 +107,7 @@ World *add_world(const char *name)
wrld->ao_indirect_energy = 1.0f;
wrld->ao_indirect_bounces = 1;
wrld->aobias = 0.05f;
- wrld->ao_samp_method = WO_AOSAMP_HAMMERSLEY;
+ wrld->ao_samp_method = WO_AOSAMP_HAMMERSLEY;
wrld->ao_approx_error = 0.25f;
wrld->preview = NULL;
diff --git a/source/blender/blenkernel/intern/writeavi.c b/source/blender/blenkernel/intern/writeavi.c
index dab44b5463c..d4428be3faf 100644
--- a/source/blender/blenkernel/intern/writeavi.c
+++ b/source/blender/blenkernel/intern/writeavi.c
@@ -47,7 +47,11 @@
#include "BKE_report.h"
#include "BKE_writeavi.h"
-#include "AVI_avi.h"
+
+/* ********************** general blender movie support ***************************** */
+
+#ifdef WITH_AVI
+# include "AVI_avi.h"
/* callbacks */
static int start_avi(Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports);
@@ -55,30 +59,31 @@ static void end_avi(void);
static int append_avi(RenderData *rd, int start_frame, int frame, int *pixels,
int rectx, int recty, ReportList *reports);
static void filepath_avi(char *string, RenderData *rd);
-
-/* ********************** general blender movie support ***************************** */
+#endif /* WITH_AVI */
#ifdef WITH_QUICKTIME
-#include "quicktime_export.h"
+# include "quicktime_export.h"
#endif
#ifdef WITH_FFMPEG
-#include "BKE_writeffmpeg.h"
+# include "BKE_writeffmpeg.h"
#endif
#include "BKE_writeframeserver.h"
bMovieHandle *BKE_movie_handle_get(const char imtype)
{
- static bMovieHandle mh;
+ static bMovieHandle mh = {0};
/* set the default handle, as builtin */
+#ifdef WITH_AVI
mh.start_movie = start_avi;
mh.append_movie = append_avi;
mh.end_movie = end_avi;
mh.get_next_frame = NULL;
mh.get_movie_path = filepath_avi;
-
+#endif
+
/* do the platform specific handles */
#ifdef WITH_QUICKTIME
if (imtype == R_IMF_IMTYPE_QUICKTIME) {
@@ -114,6 +119,8 @@ bMovieHandle *BKE_movie_handle_get(const char imtype)
/* ****************************************************************** */
+#ifdef WITH_AVI
+
static AviMovie *avi = NULL;
static void filepath_avi(char *string, RenderData *rd)
@@ -155,7 +162,7 @@ static int start_avi(Scene *scene, RenderData *rd, int rectx, int recty, ReportL
else format = AVI_FORMAT_MJPEG;
if (AVI_open_compress(name, avi, 1, format) != AVI_ERROR_NONE) {
- BKE_report(reports, RPT_ERROR, "Cannot open or start AVI movie file.");
+ BKE_report(reports, RPT_ERROR, "Cannot open or start AVI movie file");
MEM_freeN(avi);
avi = NULL;
return 0;
@@ -168,8 +175,8 @@ static int start_avi(Scene *scene, RenderData *rd, int rectx, int recty, ReportL
avi->interlace = 0;
avi->odd_fields = 0;
-/* avi->interlace= rd->mode & R_FIELDS; */
-/* avi->odd_fields= (rd->mode & R_ODDFIELD)?1:0; */
+/* avi->interlace = rd->mode & R_FIELDS; */
+/* avi->odd_fields = (rd->mode & R_ODDFIELD) ? 1 : 0; */
printf("Created avi: %s\n", name);
return 1;
@@ -219,6 +226,7 @@ static void end_avi(void)
MEM_freeN(avi);
avi = NULL;
}
+#endif /* WITH_AVI */
/* similar to BKE_makepicstring() */
void BKE_movie_filepath_get(char *string, RenderData *rd)
diff --git a/source/blender/blenkernel/intern/writeffmpeg.c b/source/blender/blenkernel/intern/writeffmpeg.c
index 4019eba5177..3a8a14290dc 100644
--- a/source/blender/blenkernel/intern/writeffmpeg.c
+++ b/source/blender/blenkernel/intern/writeffmpeg.c
@@ -289,7 +289,7 @@ static int write_video_frame(RenderData *rd, int cfra, AVFrame *frame, ReportLis
}
if (!success)
- BKE_report(reports, RPT_ERROR, "Error writing frame.");
+ BKE_report(reports, RPT_ERROR, "Error writing frame");
return success;
}
@@ -307,7 +307,7 @@ static AVFrame *generate_video_frame(uint8_t *pixels, ReportList *reports)
if (c->pix_fmt != PIX_FMT_BGR32) {
rgb_frame = alloc_picture(PIX_FMT_BGR32, width, height);
if (!rgb_frame) {
- BKE_report(reports, RPT_ERROR, "Couldn't allocate temporary frame.");
+ BKE_report(reports, RPT_ERROR, "Could not allocate temporary frame");
return NULL;
}
}
@@ -695,12 +695,12 @@ static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, Report
exts = get_file_extensions(ffmpeg_type);
if (!exts) {
- BKE_report(reports, RPT_ERROR, "No valid formats found.");
+ BKE_report(reports, RPT_ERROR, "No valid formats found");
return 0;
}
fmt = av_guess_format(NULL, exts[0], NULL);
if (!fmt) {
- BKE_report(reports, RPT_ERROR, "No valid formats found.");
+ BKE_report(reports, RPT_ERROR, "No valid formats found");
return 0;
}
@@ -795,7 +795,7 @@ static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, Report
if (error[0])
BKE_report(reports, RPT_ERROR, error);
else
- BKE_report(reports, RPT_ERROR, "Error initializing video stream.");
+ BKE_report(reports, RPT_ERROR, "Error initializing video stream");
av_dict_free(&opts);
return 0;
@@ -805,20 +805,20 @@ static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, Report
if (ffmpeg_audio_codec != CODEC_ID_NONE) {
audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of);
if (!audio_stream) {
- BKE_report(reports, RPT_ERROR, "Error initializing audio stream.");
+ BKE_report(reports, RPT_ERROR, "Error initializing audio stream");
av_dict_free(&opts);
return 0;
}
}
if (!(fmt->flags & AVFMT_NOFILE)) {
if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
- BKE_report(reports, RPT_ERROR, "Could not open file for writing.");
+ BKE_report(reports, RPT_ERROR, "Could not open file for writing");
av_dict_free(&opts);
return 0;
}
}
if (avformat_write_header(of, NULL) < 0) {
- BKE_report(reports, RPT_ERROR, "Could not initialize streams. Probably unsupported codec combination.");
+ BKE_report(reports, RPT_ERROR, "Could not initialize streams, probably unsupported codec combination");
av_dict_free(&opts);
return 0;
}
@@ -839,7 +839,7 @@ static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, Report
* inter-frames (H.264 B-frames, for example), it can output the frames
* in a different order from the one it was given.
* For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
- * them in the order 1, 4, 2, 3 - first the two frames used for predition,
+ * them in the order 1, 4, 2, 3 - first the two frames used for prediction,
* and then the bidirectionally-predicted frames. What this means in practice
* is that the encoder may not immediately produce one output frame for each
* input frame. These delayed frames must be flushed before we close the
@@ -914,8 +914,7 @@ void BKE_ffmpeg_filepath_get(char *string, RenderData *rd)
}
while (*fe) {
- if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), *fe) == 0)
- {
+ if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), *fe) == 0) {
break;
}
fe++;
@@ -983,7 +982,7 @@ int BKE_ffmpeg_append(RenderData *rd, int start_frame, int frame, int *pixels, i
PRINT("Writing frame %i, render width=%d, render height=%d\n", frame, rectx, recty);
-// why is this done before writing the video frame and again at end_ffmpeg?
+/* why is this done before writing the video frame and again at end_ffmpeg? */
// write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
if (video_stream) {
@@ -1226,7 +1225,7 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char
while (*param == ' ') param++;
}
- o = my_av_find_opt(&c, name, NULL, 0, 0);
+ o = my_av_find_opt(&c, name, NULL, 0, 0);
if (!o) {
return 0;
}
@@ -1234,7 +1233,7 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char
return 0;
}
if (param && o->type != FF_OPT_TYPE_CONST && o->unit) {
- p = my_av_find_opt(&c, param, o->unit, 0, 0);
+ p = my_av_find_opt(&c, param, o->unit, 0, 0);
if (p) {
prop = BKE_ffmpeg_property_add(rd, (char *) type, p - c.av_class->option, o - c.av_class->option);
}
diff --git a/source/blender/blenkernel/intern/writeframeserver.c b/source/blender/blenkernel/intern/writeframeserver.c
index d8fddb9851a..acbbcb0b043 100644
--- a/source/blender/blenkernel/intern/writeframeserver.c
+++ b/source/blender/blenkernel/intern/writeframeserver.c
@@ -118,13 +118,13 @@ int BKE_frameserver_start(struct Scene *scene, RenderData *UNUSED(rd), int rectx
(void)scene; /* unused */
if (!startup_socket_system()) {
- BKE_report(reports, RPT_ERROR, "Can't startup socket system");
+ BKE_report(reports, RPT_ERROR, "Cannot startup socket system");
return 0;
}
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
shutdown_socket_system();
- BKE_report(reports, RPT_ERROR, "Can't open socket");
+ BKE_report(reports, RPT_ERROR, "Cannot open socket");
return 0;
}
@@ -136,13 +136,13 @@ int BKE_frameserver_start(struct Scene *scene, RenderData *UNUSED(rd), int rectx
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
shutdown_socket_system();
- BKE_report(reports, RPT_ERROR, "Can't bind to socket");
+ BKE_report(reports, RPT_ERROR, "Cannot bind to socket");
return 0;
}
if (listen(sock, SOMAXCONN) < 0) {
shutdown_socket_system();
- BKE_report(reports, RPT_ERROR, "Can't establish listen backlog");
+ BKE_report(reports, RPT_ERROR, "Cannot establish listen backlog");
return 0;
}
connsock = -1;
diff --git a/source/blender/blenkernel/nla_private.h b/source/blender/blenkernel/nla_private.h
index 941a74ec2ab..f068c4c58f0 100644
--- a/source/blender/blenkernel/nla_private.h
+++ b/source/blender/blenkernel/nla_private.h
@@ -85,4 +85,4 @@ NlaEvalStrip *nlastrips_ctime_get_strip(ListBase *list, ListBase *strips, short
void nlastrip_evaluate(PointerRNA *ptr, ListBase *channels, ListBase *modifiers, NlaEvalStrip *nes);
void nladata_flush_channels(ListBase *channels);
-#endif // __NLA_PRIVATE_H__
+#endif /* __NLA_PRIVATE_H__ */
diff --git a/source/blender/blenlib/BLI_blenlib.h b/source/blender/blenlib/BLI_blenlib.h
index 74b477bacaf..03b75975af4 100644
--- a/source/blender/blenlib/BLI_blenlib.h
+++ b/source/blender/blenlib/BLI_blenlib.h
@@ -78,8 +78,6 @@ extern "C" {
#include "BLI_rect.h"
-#include "BLI_noise.h"
-
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenlib/BLI_bpath.h b/source/blender/blenlib/BLI_bpath.h
index 52b839d11a9..a86b362c271 100644
--- a/source/blender/blenlib/BLI_bpath.h
+++ b/source/blender/blenlib/BLI_bpath.h
@@ -64,4 +64,4 @@ void BLI_bpath_missing_files_find(struct Main *bmain, const char *searchpath, st
void BLI_bpath_relative_convert(struct Main *bmain, const char *basedir, struct ReportList *reports);
void BLI_bpath_absolute_convert(struct Main *bmain, const char *basedir, struct ReportList *reports);
-#endif // __BLI_BPATH_H__
+#endif /* __BLI_BPATH_H__ */
diff --git a/source/blender/blenlib/BLI_dlrbTree.h b/source/blender/blenlib/BLI_dlrbTree.h
index 92356b24403..bdde8dbd597 100644
--- a/source/blender/blenlib/BLI_dlrbTree.h
+++ b/source/blender/blenlib/BLI_dlrbTree.h
@@ -46,7 +46,7 @@
/* Basic Layout for a Node */
typedef struct DLRBT_Node {
/* ListBase capabilities */
- struct DLRBT_Node *next, *prev;
+ struct DLRBT_Node *next, *prev;
/* Tree Associativity settings */
struct DLRBT_Node *left, *right;
@@ -158,4 +158,4 @@ void BLI_dlrbTree_insert(DLRBT_Tree *tree, DLRBT_Node *node);
/* ********************************************** */
-#endif // __BLI_DLRBTREE_H__
+#endif /* __BLI_DLRBTREE_H__ */
diff --git a/source/blender/blenlib/BLI_dynstr.h b/source/blender/blenlib/BLI_dynstr.h
index 3b7f2d6bbaf..833c416c1c1 100644
--- a/source/blender/blenlib/BLI_dynstr.h
+++ b/source/blender/blenlib/BLI_dynstr.h
@@ -80,7 +80,11 @@ void BLI_dynstr_appendf(DynStr *ds, const char *format, ...)
__attribute__ ((format(printf, 2, 3)))
#endif
;
-void BLI_dynstr_vappendf(DynStr *ds, const char *format, va_list args);
+void BLI_dynstr_vappendf(DynStr *ds, const char *format, va_list args)
+#ifdef __GNUC__
+__attribute__ ((format(printf, 2, 0)))
+#endif
+;
/**
* Find the length of a DynStr.
@@ -107,7 +111,6 @@ char *BLI_dynstr_get_cstring(DynStr *ds);
*
* \param ds The DynStr of interest.
* \param str The string to fill.
- * \return The contents of \a ds as a c-string.
*/
void BLI_dynstr_get_cstring_ex(DynStr *ds, char *str);
diff --git a/source/blender/blenlib/BLI_endian_switch.h b/source/blender/blenlib/BLI_endian_switch.h
index 7017e7ba789..7cb2790525d 100644
--- a/source/blender/blenlib/BLI_endian_switch.h
+++ b/source/blender/blenlib/BLI_endian_switch.h
@@ -27,16 +27,36 @@
* \ingroup bli
*/
-#include "BLI_endian_switch_inline.h"
+#ifdef __GNUC__
+# define ATTR_ENDIAN_SWITCH \
+ __attribute__((nonnull(1))) \
+ __attribute__((pure))
+#else
+# define ATTR_ENDIAN_SWITCH
+#endif
+
+/* BLI_endian_switch_inline.h */
+BLI_INLINE void BLI_endian_switch_int16(short *val) ATTR_ENDIAN_SWITCH;
+BLI_INLINE void BLI_endian_switch_uint16(unsigned short *val) ATTR_ENDIAN_SWITCH;
+BLI_INLINE void BLI_endian_switch_int32(int *val) ATTR_ENDIAN_SWITCH;
+BLI_INLINE void BLI_endian_switch_uint32(unsigned int *val) ATTR_ENDIAN_SWITCH;
+BLI_INLINE void BLI_endian_switch_float(float *val) ATTR_ENDIAN_SWITCH;
+BLI_INLINE void BLI_endian_switch_int64(int64_t *val) ATTR_ENDIAN_SWITCH;
+BLI_INLINE void BLI_endian_switch_uint64(uint64_t *val) ATTR_ENDIAN_SWITCH;
+BLI_INLINE void BLI_endian_switch_double(double *val) ATTR_ENDIAN_SWITCH;
/* endian_switch.c */
-void BLI_endian_switch_int16_array(short *val, const int size);
-void BLI_endian_switch_uint16_array(unsigned short *val, const int size);
-void BLI_endian_switch_int32_array(int *val, const int size);
-void BLI_endian_switch_uint32_array(unsigned int *val, const int size);
-void BLI_endian_switch_float_array(float *val, const int size);
-void BLI_endian_switch_int64_array(int64_t *val, const int size);
-void BLI_endian_switch_uint64_array(uint64_t *val, const int size);
-void BLI_endian_switch_double_array(double *val, const int size);
+void BLI_endian_switch_int16_array(short *val, const int size) ATTR_ENDIAN_SWITCH;
+void BLI_endian_switch_uint16_array(unsigned short *val, const int size) ATTR_ENDIAN_SWITCH;
+void BLI_endian_switch_int32_array(int *val, const int size) ATTR_ENDIAN_SWITCH;
+void BLI_endian_switch_uint32_array(unsigned int *val, const int size) ATTR_ENDIAN_SWITCH;
+void BLI_endian_switch_float_array(float *val, const int size) ATTR_ENDIAN_SWITCH;
+void BLI_endian_switch_int64_array(int64_t *val, const int size) ATTR_ENDIAN_SWITCH;
+void BLI_endian_switch_uint64_array(uint64_t *val, const int size) ATTR_ENDIAN_SWITCH;
+void BLI_endian_switch_double_array(double *val, const int size) ATTR_ENDIAN_SWITCH;
+
+#include "BLI_endian_switch_inline.h"
+
+#undef ATTR_ENDIAN_SWITCH
#endif /* __BLI_ENDIAN_SWITCH_H__ */
diff --git a/source/blender/blenlib/BLI_endian_switch_inline.h b/source/blender/blenlib/BLI_endian_switch_inline.h
index b747da3b738..4bc6d3828b9 100644
--- a/source/blender/blenlib/BLI_endian_switch_inline.h
+++ b/source/blender/blenlib/BLI_endian_switch_inline.h
@@ -32,85 +32,63 @@
* \ingroup bli
*/
+/* note: using a temp char to switch endian is a lot slower,
+ * use bit shifting instead. */
+/* *** 16 *** */
BLI_INLINE void BLI_endian_switch_int16(short *val)
{
- char *p_i = (char *)val;
- char s_i;
+ short tval = *val;
+ *val = (tval >> 8) |
+ (tval << 8);
- s_i = p_i[0];
- p_i[0] = p_i[1];
- p_i[1] = s_i;
}
-
BLI_INLINE void BLI_endian_switch_uint16(unsigned short *val)
{
- char *p_i = (char *)val;
- char s_i;
-
- s_i = p_i[0];
- p_i[0] = p_i[1];
- p_i[1] = s_i;
+ BLI_endian_switch_int16((short *)val);
}
+
+/* *** 32 *** */
BLI_INLINE void BLI_endian_switch_int32(int *val)
{
- char *p_i = (char *)val;
- char s_i;
+ int tval = *val;
+ *val = ((tval >> 24)) |
+ ((tval << 8) & 0x00ff0000) |
+ ((tval >> 8) & 0x0000ff00) |
+ ((tval << 24));
- s_i = p_i[0]; p_i[0] = p_i[3]; p_i[3] = s_i;
- s_i = p_i[1]; p_i[1] = p_i[2]; p_i[2] = s_i;
}
-
BLI_INLINE void BLI_endian_switch_uint32(unsigned int *val)
{
- char *p_i = (char *)val;
- char s_i;
-
- s_i = p_i[0]; p_i[0] = p_i[3]; p_i[3] = s_i;
- s_i = p_i[1]; p_i[1] = p_i[2]; p_i[2] = s_i;
+ BLI_endian_switch_int32((int *)val);
}
-
BLI_INLINE void BLI_endian_switch_float(float *val)
{
- char *p_i = (char *)val;
- char s_i;
-
- s_i = p_i[0]; p_i[0] = p_i[3]; p_i[3] = s_i;
- s_i = p_i[1]; p_i[1] = p_i[2]; p_i[2] = s_i;
+ BLI_endian_switch_int32((int *)val);
}
+
+/* *** 64 *** */
BLI_INLINE void BLI_endian_switch_int64(int64_t *val)
{
- char *p_i = (char *)val;
- char s_i;
-
- s_i = p_i[0]; p_i[0] = p_i[7]; p_i[7] = s_i;
- s_i = p_i[1]; p_i[1] = p_i[6]; p_i[6] = s_i;
- s_i = p_i[2]; p_i[2] = p_i[5]; p_i[5] = s_i;
- s_i = p_i[3]; p_i[3] = p_i[4]; p_i[4] = s_i;
+ int64_t tval = *val;
+ *val = ((tval >> 56)) |
+ ((tval << 40) & 0x00ff000000000000ll) |
+ ((tval << 24) & 0x0000ff0000000000ll) |
+ ((tval << 8) & 0x000000ff00000000ll) |
+ ((tval >> 8) & 0x00000000ff000000ll) |
+ ((tval >> 24) & 0x0000000000ff0000ll) |
+ ((tval >> 40) & 0x000000000000ff00ll) |
+ ((tval << 56));
}
-
BLI_INLINE void BLI_endian_switch_uint64(uint64_t *val)
{
- char *p_i = (char *)val;
- char s_i;
-
- s_i = p_i[0]; p_i[0] = p_i[7]; p_i[7] = s_i;
- s_i = p_i[1]; p_i[1] = p_i[6]; p_i[6] = s_i;
- s_i = p_i[2]; p_i[2] = p_i[5]; p_i[5] = s_i;
- s_i = p_i[3]; p_i[3] = p_i[4]; p_i[4] = s_i;
+ BLI_endian_switch_int64((int64_t *)val);
}
-
BLI_INLINE void BLI_endian_switch_double(double *val)
{
- char *p_i = (char *)val;
- char s_i;
-
- s_i = p_i[0]; p_i[0] = p_i[7]; p_i[7] = s_i;
- s_i = p_i[1]; p_i[1] = p_i[6]; p_i[6] = s_i;
- s_i = p_i[2]; p_i[2] = p_i[5]; p_i[5] = s_i;
- s_i = p_i[3]; p_i[3] = p_i[4]; p_i[4] = s_i;
+ BLI_endian_switch_int64((int64_t *)val);
}
#endif /* __BLI_ENDIAN_SWITCH_INLINE_H__ */
diff --git a/source/blender/blenlib/BLI_fileops.h b/source/blender/blenlib/BLI_fileops.h
index e8d6336a994..c278370d211 100644
--- a/source/blender/blenlib/BLI_fileops.h
+++ b/source/blender/blenlib/BLI_fileops.h
@@ -96,6 +96,8 @@ void BLI_file_free_lines(struct LinkNode *lines);
# ifndef O_BINARY
# define O_BINARY 0
# endif
+#else
+void BLI_get_short_name(char short_name[256], const char *filename);
#endif
#ifdef __cplusplus
diff --git a/source/blender/blenlib/BLI_fileops_types.h b/source/blender/blenlib/BLI_fileops_types.h
index a19909a8f26..1c6463eb6ea 100644
--- a/source/blender/blenlib/BLI_fileops_types.h
+++ b/source/blender/blenlib/BLI_fileops_types.h
@@ -46,7 +46,7 @@ struct direntry {
mode_t type;
char *relname;
char *path;
-#if (defined(WIN32) || defined(WIN64)) && (_MSC_VER >= 1500)
+#if (defined(WIN32) || defined(WIN64)) && !defined(__MINGW32__) && (_MSC_VER >= 1500)
struct _stat64 s;
#elif defined(__MINGW32__)
struct _stati64 s;
diff --git a/source/blender/blenlib/BLI_heap.h b/source/blender/blenlib/BLI_heap.h
index b378f2bb365..c0941e00c9b 100644
--- a/source/blender/blenlib/BLI_heap.h
+++ b/source/blender/blenlib/BLI_heap.h
@@ -42,6 +42,7 @@ typedef void (*HeapFreeFP)(void *ptr);
/* Creates a new heap. BLI_memarena is used for allocating nodes. Removed nodes
* are recycled, so memory usage will not shrink. */
+Heap *BLI_heap_new_ex(unsigned int tot_reserve);
Heap *BLI_heap_new(void);
void BLI_heap_free(Heap *heap, HeapFreeFP ptrfreefp);
@@ -53,10 +54,10 @@ HeapNode *BLI_heap_insert(Heap *heap, float value, void *ptr);
void BLI_heap_remove(Heap *heap, HeapNode *node);
/* Return 0 if the heap is empty, 1 otherwise. */
-int BLI_heap_empty(Heap *heap);
+int BLI_heap_is_empty(Heap *heap);
/* Return the size of the heap. */
-int BLI_heap_size(Heap *heap);
+unsigned int BLI_heap_size(Heap *heap);
/* Return the top node of the heap. This is the node with the lowest value. */
HeapNode *BLI_heap_top(Heap *heap);
@@ -68,5 +69,4 @@ void *BLI_heap_popmin(Heap *heap);
float BLI_heap_node_value(HeapNode *heap);
void *BLI_heap_node_ptr(HeapNode *heap);
-#endif
-
+#endif /* __BLI_HEAP_H__ */
diff --git a/source/blender/blenlib/BLI_kdopbvh.h b/source/blender/blenlib/BLI_kdopbvh.h
index 985b5af3b94..8441413fba9 100644
--- a/source/blender/blenlib/BLI_kdopbvh.h
+++ b/source/blender/blenlib/BLI_kdopbvh.h
@@ -75,7 +75,7 @@ typedef struct BVHTreeRayHit {
} BVHTreeRayHit;
/* callback must update nearest in case it finds a nearest result */
-typedef void (*BVHTree_NearestPointCallback)(void *userdata, int index, const float *co, BVHTreeNearest *nearest);
+typedef void (*BVHTree_NearestPointCallback)(void *userdata, int index, const float co[3], BVHTreeNearest *nearest);
/* callback must update hit in case it finds a nearest successful hit */
typedef void (*BVHTree_RayCastCallback)(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit);
@@ -87,31 +87,34 @@ BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis);
void BLI_bvhtree_free(BVHTree *tree);
/* construct: first insert points, then call balance */
-int BLI_bvhtree_insert(BVHTree *tree, int index, const float *co, int numpoints);
+int BLI_bvhtree_insert(BVHTree *tree, int index, const float co[3], int numpoints);
void BLI_bvhtree_balance(BVHTree *tree);
/* update: first update points/nodes, then call update_tree to refit the bounding volumes */
-int BLI_bvhtree_update_node(BVHTree *tree, int index, const float *co, const float *co_moving, int numpoints);
+int BLI_bvhtree_update_node(BVHTree *tree, int index, const float co[3], const float co_moving[3], int numpoints);
void BLI_bvhtree_update_tree(BVHTree *tree);
/* collision/overlap: check two trees if they overlap, alloc's *overlap with length of the int return value */
BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, unsigned int *result);
-float BLI_bvhtree_getepsilon(BVHTree *tree);
+float BLI_bvhtree_getepsilon(const BVHTree *tree);
-/* find nearest node to the given coordinates (if nearest is given it will only search nodes where square distance is smaller than nearest->dist) */
-int BLI_bvhtree_find_nearest(BVHTree *tree, const float co[3], BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata);
+/* find nearest node to the given coordinates
+ * (if nearest is given it will only search nodes where square distance is smaller than nearest->dist) */
+int BLI_bvhtree_find_nearest(BVHTree *tree, const float co[3], BVHTreeNearest *nearest,
+ BVHTree_NearestPointCallback callback, void *userdata);
-int BLI_bvhtree_ray_cast(BVHTree *tree, const float co[3], const float *dir, float radius, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata);
+int BLI_bvhtree_ray_cast(BVHTree *tree, const float co[3], const float dir[3], float radius, BVHTreeRayHit *hit,
+ BVHTree_RayCastCallback callback, void *userdata);
-float BLI_bvhtree_bb_raycast(const float *bv, const float light_start[3], const float light_end[3], float pos[3]);
+float BLI_bvhtree_bb_raycast(const float bv[6], const float light_start[3], const float light_end[3], float pos[3]);
/* range query */
-int BLI_bvhtree_range_query(BVHTree *tree, const float co[3], float radius, BVHTree_RangeQuery callback, void *userdata);
+int BLI_bvhtree_range_query(BVHTree *tree, const float co[3], float radius,
+ BVHTree_RangeQuery callback, void *userdata);
#ifdef __cplusplus
}
#endif
-#endif // __BLI_KDOPBVH_H__
-
+#endif /* __BLI_KDOPBVH_H__ */
diff --git a/source/blender/blenlib/BLI_kdtree.h b/source/blender/blenlib/BLI_kdtree.h
index e90566408d4..f9b52f34102 100644
--- a/source/blender/blenlib/BLI_kdtree.h
+++ b/source/blender/blenlib/BLI_kdtree.h
@@ -56,7 +56,7 @@ void BLI_kdtree_balance(KDTree *tree);
/* Find nearest returns index, and -1 if no node is found.
* Find n nearest returns number of points found, with results in nearest.
* Normal is optional, but if given will limit results to points in normal direction from co. */
-int BLI_kdtree_find_nearest(KDTree *tree, float *co, float *nor, KDTreeNearest *nearest);
+int BLI_kdtree_find_nearest(KDTree *tree, const float co[3], const float nor[3], KDTreeNearest *nearest);
int BLI_kdtree_find_n_nearest(KDTree *tree, int n, const float co[3], const float nor[3], KDTreeNearest *nearest);
/* Range search returns number of points found, with results in nearest */
diff --git a/source/blender/blenlib/BLI_lasso.h b/source/blender/blenlib/BLI_lasso.h
index 85a000b000c..a7e90a51e86 100644
--- a/source/blender/blenlib/BLI_lasso.h
+++ b/source/blender/blenlib/BLI_lasso.h
@@ -34,8 +34,8 @@
struct rcti;
-void BLI_lasso_boundbox(struct rcti *rect, int mcords[][2], short moves);
-int BLI_lasso_is_point_inside(int mcords[][2], short moves, const int sx, const int sy, const int error_value);
-int BLI_lasso_is_edge_inside(int mcords[][2], short moves, int x0, int y0, int x1, int y1, const int error_value);
+void BLI_lasso_boundbox(struct rcti *rect, const int mcords[][2], const short moves);
+int BLI_lasso_is_point_inside(const int mcords[][2], const short moves, const int sx, const int sy, const int error_value);
+int BLI_lasso_is_edge_inside(const int mcords[][2], const short moves, int x0, int y0, int x1, int y1, const int error_value);
#endif
diff --git a/source/blender/blenlib/BLI_math_base.h b/source/blender/blenlib/BLI_math_base.h
index 886ed6f495d..2b513cbec41 100644
--- a/source/blender/blenlib/BLI_math_base.h
+++ b/source/blender/blenlib/BLI_math_base.h
@@ -30,8 +30,8 @@
* \ingroup bli
*/
-#ifdef WIN32
-#define _USE_MATH_DEFINES
+#ifdef _MSC_VER
+# define _USE_MATH_DEFINES
#endif
#include <math.h>
@@ -188,8 +188,11 @@ MINLINE float sasqrt(float fac);
MINLINE float interpf(float a, float b, float t);
-MINLINE float minf(float a, float b);
-MINLINE float maxf(float a, float b);
+MINLINE float min_ff(float a, float b);
+MINLINE float max_ff(float a, float b);
+
+MINLINE int min_ii(int a, int b);
+MINLINE int max_ii(int a, int b);
MINLINE float signf(float f);
diff --git a/source/blender/blenlib/BLI_math_color.h b/source/blender/blenlib/BLI_math_color.h
index 6fe5d48d06e..7c8bf88943d 100644
--- a/source/blender/blenlib/BLI_math_color.h
+++ b/source/blender/blenlib/BLI_math_color.h
@@ -115,6 +115,8 @@ void rgba_float_to_uchar(unsigned char col_r[4], const float col_f[4]);
void xyz_to_lab(float x, float y, float z, float *l, float *a, float *b);
+MINLINE int compare_rgb_uchar(const unsigned char a[3], const unsigned char b[3], const int limit);
+
/***************** lift/gamma/gain / ASC-CDL conversion *****************/
void lift_gamma_gain_to_asc_cdl(float *lift, float *gamma, float *gain, float *offset, float *slope, float *power);
diff --git a/source/blender/blenlib/BLI_math_geom.h b/source/blender/blenlib/BLI_math_geom.h
index 107b688b36a..80169e952bf 100644
--- a/source/blender/blenlib/BLI_math_geom.h
+++ b/source/blender/blenlib/BLI_math_geom.h
@@ -95,12 +95,6 @@ int isect_line_sphere_v2(const float l1[2], const float l2[2], const float sp[2]
int isect_seg_seg_v2_point(const float v1[2], const float v2[2], const float v3[2], const float v4[2], float vi[2]);
int isect_seg_seg_v2(const float v1[2], const float v2[2], const float v3[2], const float v4[2]);
-/* Returns the number of point of interests
- * 0 - lines are colinear
- * 1 - lines are coplanar, i1 is set to intersection
- * 2 - i1 and i2 are the nearest points on line 1 (v1, v2) and line 2 (v3, v4) respectively
- * */
-
int isect_line_line_v3(const float v1[3], const float v2[3],
const float v3[3], const float v4[3],
float i1[3], float i2[3]);
@@ -108,35 +102,13 @@ int isect_line_line_strict_v3(const float v1[3], const float v2[3],
const float v3[3], const float v4[3],
float vi[3], float *r_lambda);
-/* if clip is nonzero, will only return true if lambda is >= 0.0
- * (i.e. intersection point is along positive d)*/
int isect_ray_plane_v3(const float p1[3], const float d[3],
const float v0[3], const float v1[3], const float v2[3],
float *r_lambda, const int clip);
-/**
- * Intersect line/plane, optionally treat line as directional (like a ray) with the no_flip argument.
- * \param out The intersection point.
- * \param l1 The first point of the line.
- * \param l2 The second point of the line.
- * \param plane_co A point on the plane to intersect with.
- * \param plane_no The direction of the plane (does not need to be normalized).
- * \param no_flip When true, the intersection point will always be from l1 to l2, even if this is not on the plane.
- */
int isect_line_plane_v3(float out[3], const float l1[3], const float l2[3],
const float plane_co[3], const float plane_no[3], const short no_flip);
-/**
- * Intersect two planes, return a point on the intersection and a vector
- * that runs on the direction of the intersection.
- * Return error code is the same as 'isect_line_line_v3'.
- * \param r_isect_co The resulting intersection point.
- * \param r_isect_no The resulting vector of the intersection.
- * \param plane_a_co The point on the first plane.
- * \param plane_a_no The normal of the first plane.
- * \param plane_b_co The point on the second plane.
- * \param plane_b_no The normal of the second plane.
- */
void isect_plane_plane_v3(float r_isect_co[3], float r_isect_no[3],
const float plane_a_co[3], const float plane_a_no[3],
const float plane_b_co[3], const float plane_b_no[3]);
@@ -250,14 +222,6 @@ void accumulate_vertex_normals_poly(float **vertnos, float polyno[3],
/********************************* Tangents **********************************/
-typedef struct VertexTangent {
- struct VertexTangent *next;
- float tang[3], uv[2];
-} VertexTangent;
-
-float *find_vertex_tangent(VertexTangent *vtang, const float uv[2]);
-void sum_or_add_vertex_tangent(void *arena, VertexTangent **vtang,
- const float tang[3], const float uv[2]);
void tangent_from_uv(float uv1[2], float uv2[2], float uv3[2],
float co1[3], float co2[3], float co3[3], float n[3], float tang[3]);
@@ -291,6 +255,9 @@ float form_factor_hemi_poly(float p[3], float n[3],
void axis_dominant_v3(int *axis_a, int *axis_b, const float axis[3]);
+MINLINE int max_axis_v3(const float vec[3]);
+MINLINE int min_axis_v3(const float vec[3]);
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenlib/BLI_math_matrix.h b/source/blender/blenlib/BLI_math_matrix.h
index 8e9955beb61..9e34631d460 100644
--- a/source/blender/blenlib/BLI_math_matrix.h
+++ b/source/blender/blenlib/BLI_math_matrix.h
@@ -128,6 +128,7 @@ int is_orthonormal_m4(float mat[4][4]);
int is_uniform_scaled_m3(float mat[3][3]);
+void adjoint_m2_m2(float R[2][2], float A[2][2]);
void adjoint_m3_m3(float R[3][3], float A[3][3]);
void adjoint_m4_m4(float R[4][4], float A[4][4]);
diff --git a/source/blender/blenlib/BLI_math_rotation.h b/source/blender/blenlib/BLI_math_rotation.h
index 8a439c7cf7a..652925fbe49 100644
--- a/source/blender/blenlib/BLI_math_rotation.h
+++ b/source/blender/blenlib/BLI_math_rotation.h
@@ -78,6 +78,8 @@ void quat_to_mat4(float mat[4][4], const float q[4]);
void mat3_to_quat(float q[4], float mat[3][3]);
void mat4_to_quat(float q[4], float mat[4][4]);
+void tri_to_quat_ex(float quat[4], const float v1[3], const float v2[3], const float v3[3],
+ const float no_orig[3]);
void tri_to_quat(float q[4], const float a[3], const float b[3], const float c[3]);
void vec_to_quat(float q[4], const float vec[3], short axis, const short upflag);
/* note: v1 and v2 must be normalized */
@@ -105,7 +107,7 @@ void single_axis_angle_to_mat3(float R[3][3], const char axis, const float angle
/****************************** Vector/Rotation ******************************/
/* old axis angle code */
-/* TODO: the following calls should probably be depreceated sometime */
+/* TODO: the following calls should probably be deprecated sometime */
/* conversion */
void vec_rot_to_mat3(float mat[3][3], const float vec[3], const float phi);
diff --git a/source/blender/blenlib/BLI_math_vector.h b/source/blender/blenlib/BLI_math_vector.h
index 6c81ca3f0a9..77c0ec0a88f 100644
--- a/source/blender/blenlib/BLI_math_vector.h
+++ b/source/blender/blenlib/BLI_math_vector.h
@@ -67,6 +67,7 @@ MINLINE void copy_v2_v2_short(short r[2], const short a[2]);
MINLINE void copy_v3_v3_short(short r[3], const short a[3]);
MINLINE void copy_v4_v4_short(short r[4], const short a[4]);
/* int */
+MINLINE void zero_v3_int(int r[3]);
MINLINE void copy_v2_v2_int(int r[2], const int a[2]);
MINLINE void copy_v3_v3_int(int r[3], const int a[3]);
MINLINE void copy_v4_v4_int(int r[4], const int a[4]);
@@ -139,12 +140,16 @@ MINLINE void star_m3_v3(float rmat[3][3], float a[3]);
MINLINE float len_squared_v2(const float v[2]);
MINLINE float len_squared_v3(const float v[3]);
+MINLINE float len_manhattan_v2(const float v[2]);
+MINLINE float len_manhattan_v3(const float v[3]);
MINLINE float len_v2(const float a[2]);
MINLINE float len_v2v2(const float a[2], const float b[2]);
MINLINE float len_squared_v2v2(const float a[2], const float b[2]);
+MINLINE float len_squared_v3v3(const float a[3], const float b[3]);
+MINLINE float len_manhattan_v2v2(const float a[2], const float b[2]);
+MINLINE float len_manhattan_v3v3(const float a[3], const float b[3]);
MINLINE float len_v3(const float a[3]);
MINLINE float len_v3v3(const float a[3], const float b[3]);
-MINLINE float len_squared_v3v3(const float a[3], const float b[3]);
MINLINE float normalize_v2(float r[2]);
MINLINE float normalize_v2_v2(float r[2], const float a[2]);
@@ -173,6 +178,7 @@ MINLINE int is_one_v3(const float a[3]);
MINLINE int equals_v2v2(const float v1[2], const float v2[2]);
MINLINE int equals_v3v3(const float a[3], const float b[3]);
+MINLINE int compare_v2v2(const float a[3], const float b[3], const float limit);
MINLINE int compare_v3v3(const float a[3], const float b[3], const float limit);
MINLINE int compare_len_v3v3(const float a[3], const float b[3], const float limit);
@@ -220,6 +226,7 @@ MINLINE void normal_short_to_float_v3(float r[3], const short n[3]);
MINLINE void normal_float_to_short_v3(short r[3], const float n[3]);
void minmax_v3v3_v3(float min[3], float max[3], const float vec[3]);
+void minmax_v2v2_v2(float min[2], float max[2], const float vec[2]);
void dist_ensure_v3_v3fl(float v1[3], const float v2[3], const float dist);
void dist_ensure_v2_v2fl(float v1[2], const float v2[2], const float dist);
diff --git a/source/blender/blenlib/BLI_pbvh.h b/source/blender/blenlib/BLI_pbvh.h
index 20d04f7881e..9483d068bb9 100644
--- a/source/blender/blenlib/BLI_pbvh.h
+++ b/source/blender/blenlib/BLI_pbvh.h
@@ -233,7 +233,7 @@ void pbvh_vertex_iter_init(PBVH *bvh, PBVHNode *node,
if (vi.grid) { \
vi.co = CCG_elem_co(vi.key, vi.grid); \
vi.fno = CCG_elem_no(vi.key, vi.grid); \
- vi.mask = CCG_elem_mask(vi.key, vi.grid); \
+ vi.mask = vi.key->has_mask ? CCG_elem_mask(vi.key, vi.grid) : NULL; \
vi.grid = CCG_elem_next(vi.key, vi.grid); \
if (vi.gh) { \
if (BLI_BITMAP_GET(vi.gh, vi.gy * vi.gridsize + vi.gx)) \
@@ -263,5 +263,7 @@ void BLI_pbvh_gather_proxies(PBVH *pbvh, PBVHNode ***nodes, int *totnode);
//void BLI_pbvh_node_BB_reset(PBVHNode *node);
//void BLI_pbvh_node_BB_expand(PBVHNode *node, float co[3]);
+void pbvh_show_diffuse_color_set(PBVH *bvh, int show_diffuse_color);
+
#endif /* __BLI_PBVH_H__ */
diff --git a/intern/decimation/intern/LOD_MeshException.h b/source/blender/blenlib/BLI_quadric.h
index 67bd8188c41..aec11ec2b44 100644
--- a/intern/decimation/intern/LOD_MeshException.h
+++ b/source/blender/blenlib/BLI_quadric.h
@@ -18,38 +18,39 @@
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
+ * Contributor(s): Laurence Bourn, Campbell Barton
*
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file decimation/intern/LOD_MeshException.h
- * \ingroup decimation
- */
-
+#ifndef __BLI_QUADRIC_H__
+#define __BLI_QUADRIC_H__
-#ifndef __LOD_MESHEXCEPTION_H__
-#define __LOD_MESHEXCEPTION_H__
-
-class LOD_MeshException {
+/** \file BLI_quadric.h
+ * \ingroup bli
+ */
-public :
+typedef struct Quadric {
+ float a2, ab, ac, ad,
+ b2, bc, bd,
+ c2, cd,
+ d2;
+} Quadric;
- // stick in more error types as you think of them
+/* conversion */
+void BLI_quadric_from_v3_dist(Quadric *q, const float v[3], const float offset);
+void BLI_quadric_to_tensor_m3(const Quadric *q, float m[3][3]);
+void BLI_quadric_to_vector_v3(const Quadric *q, float v[3]);
- enum ExceptionType{
- e_non_manifold,
- e_search_error
- } m_e_type;
+void BLI_quadric_clear(Quadric *q);
- LOD_MeshException (
- ExceptionType type
- ) : m_e_type (type)
- {
- }
-};
+/* math */
+void BLI_quadric_add_qu_qu(Quadric *a, const Quadric *b);
+void BLI_quadric_add_qu_ququ(Quadric *r, const Quadric *a, const Quadric *b);
+void BLI_quadric_mul(Quadric *a, const float scalar);
-#endif
+/* solve */
+float BLI_quadric_evaluate(const Quadric *q, const float v[3]);
+int BLI_quadric_optimize(const Quadric *q, float v[3]);
+#endif /* __BLI_QUADRIC_H__ */
diff --git a/source/blender/blenlib/BLI_rand.h b/source/blender/blenlib/BLI_rand.h
index 7dd6c8575c9..3bc9a3bdb32 100644
--- a/source/blender/blenlib/BLI_rand.h
+++ b/source/blender/blenlib/BLI_rand.h
@@ -40,18 +40,18 @@
struct RNG;
typedef struct RNG RNG;
-struct RNG *rng_new(unsigned int seed);
-void rng_free(struct RNG *rng);
+struct RNG *BLI_rng_new(unsigned int seed);
+void BLI_rng_free(struct RNG *rng);
-void rng_seed(struct RNG *rng, unsigned int seed);
-void rng_srandom(struct RNG *rng, unsigned int seed);
-int rng_getInt(struct RNG *rng);
-double rng_getDouble(struct RNG *rng);
-float rng_getFloat(struct RNG *rng);
-void rng_shuffleArray(struct RNG *rng, void *data, int elemSize, int numElems);
+void BLI_rng_seed(struct RNG *rng, unsigned int seed);
+void BLI_rng_srandom(struct RNG *rng, unsigned int seed);
+int BLI_rng_get_int(struct RNG *rng);
+double BLI_rng_get_double(struct RNG *rng);
+float BLI_rng_get_float(struct RNG *rng);
+void BLI_rng_shuffle_array(struct RNG *rng, void *data, int elemSize, int numElems);
/** Note that skipping is as slow as generating n numbers! */
-void rng_skip(struct RNG *rng, int n);
+void BLI_rng_skip(struct RNG *rng, int n);
/** Seed the random number generator */
void BLI_srand(unsigned int seed);
@@ -94,7 +94,4 @@ int BLI_thread_rand(int thread);
/** Allows up to BLENDER_MAX_THREADS threads to address */
float BLI_thread_frand(int thread);
-
-
-#endif
-
+#endif /* __BLI_RAND_H__ */
diff --git a/source/blender/blenlib/BLI_rect.h b/source/blender/blenlib/BLI_rect.h
index eb9915d6c9b..f84820e94f3 100644
--- a/source/blender/blenlib/BLI_rect.h
+++ b/source/blender/blenlib/BLI_rect.h
@@ -55,6 +55,8 @@ void BLI_rcti_resize(struct rcti *rect, int x, int y);
void BLI_rctf_resize(struct rctf *rect, float x, float y);
void BLI_rctf_interp(struct rctf *rect, const struct rctf *rect_a, const struct rctf *rect_b, const float fac);
//void BLI_rcti_interp(struct rctf *rect, struct rctf *rect_a, struct rctf *rect_b, float fac);
+int BLI_rctf_clamp_pt_v(const struct rctf *rect, float xy[2]);
+int BLI_rcti_clamp_pt_v(const struct rcti *rect, int xy[2]);
int BLI_rctf_compare(const struct rctf *rect_a, const struct rctf *rect_b, const float limit);
int BLI_rcti_compare(const struct rcti *rect_a, const struct rcti *rect_b);
int BLI_rctf_isect(const struct rctf *src1, const struct rctf *src2, struct rctf *dest);
@@ -64,9 +66,7 @@ int BLI_rcti_isect_pt_v(const struct rcti *rect, const int xy[2]);
int BLI_rctf_isect_pt(const struct rctf *rect, const float x, const float y);
int BLI_rctf_isect_pt_v(const struct rctf *rect, const float xy[2]);
int BLI_rcti_isect_segment(const struct rcti *rect, const int s1[2], const int s2[2]);
-#if 0 /* NOT NEEDED YET */
-int BLI_rctf_isect_segment(struct rcti *rect, int s1[2], int s2[2]);
-#endif
+int BLI_rctf_isect_segment(const struct rctf *rect, const float s1[2], const float s2[2]);
void BLI_rctf_union(struct rctf *rctf1, const struct rctf *rctf2);
void BLI_rcti_union(struct rcti *rcti1, const struct rcti *rcti2);
void BLI_rcti_rctf_copy(struct rcti *dst, const struct rctf *src);
@@ -75,14 +75,28 @@ void BLI_rctf_rcti_copy(struct rctf *dst, const struct rcti *src);
void print_rctf(const char *str, const struct rctf *rect);
void print_rcti(const char *str, const struct rcti *rect);
-#define BLI_RCT_SIZE_X(rct) ((rct)->xmax - (rct)->xmin)
-#define BLI_RCT_SIZE_Y(rct) ((rct)->ymax - (rct)->ymin)
+/* hrmf, we need to work out this inline stuff */
+#if defined(_MSC_VER)
+# define BLI_INLINE static __forceinline
+#elif defined(__GNUC__)
+# define BLI_INLINE static inline __attribute((always_inline))
+#else
+/* #warning "MSC/GNUC defines not found, inline non-functional" */
+# define BLI_INLINE static
+#endif
-#define BLI_RCT_CENTER_X(rct) (((rct)->xmin + (rct)->xmax) / 2)
-#define BLI_RCT_CENTER_Y(rct) (((rct)->ymin + (rct)->ymax) / 2)
+#include "DNA_vec_types.h"
+BLI_INLINE float BLI_rcti_cent_x_fl(const struct rcti *rct) { return (float)(rct->xmin + rct->xmax) / 2.0f; }
+BLI_INLINE float BLI_rcti_cent_y_fl(const struct rcti *rct) { return (float)(rct->ymin + rct->ymax) / 2.0f; }
+BLI_INLINE int BLI_rcti_cent_x(const struct rcti *rct) { return (rct->xmin + rct->xmax) / 2; }
+BLI_INLINE int BLI_rcti_cent_y(const struct rcti *rct) { return (rct->ymin + rct->ymax) / 2; }
+BLI_INLINE float BLI_rctf_cent_x(const struct rctf *rct) { return (rct->xmin + rct->xmax) / 2.0f; }
+BLI_INLINE float BLI_rctf_cent_y(const struct rctf *rct) { return (rct->ymin + rct->ymax) / 2.0f; }
-#define BLI_RCT_CENTER_X_FL(rct) ((float)((rct)->xmin + (rct)->xmax) / 2.0f)
-#define BLI_RCT_CENTER_Y_FL(rct) ((float)((rct)->ymin + (rct)->ymax) / 2.0f)
+BLI_INLINE int BLI_rcti_size_x(const struct rcti *rct) { return (rct->xmax - rct->xmin); }
+BLI_INLINE int BLI_rcti_size_y(const struct rcti *rct) { return (rct->ymax - rct->ymin); }
+BLI_INLINE float BLI_rctf_size_x(const struct rctf *rct) { return (rct->xmax - rct->xmin); }
+BLI_INLINE float BLI_rctf_size_y(const struct rctf *rct) { return (rct->ymax - rct->ymin); }
#ifdef __cplusplus
}
diff --git a/source/blender/blenlib/BLI_scanfill.h b/source/blender/blenlib/BLI_scanfill.h
index a6b1943cb4d..892afdd0b27 100644
--- a/source/blender/blenlib/BLI_scanfill.h
+++ b/source/blender/blenlib/BLI_scanfill.h
@@ -103,7 +103,7 @@ void BLI_scanfill_end(ScanFillContext *sf_ctx);
/* These callbacks are needed to make the lib finction properly */
/**
- * Set a function taking a char* as argument to flag errors. If the
+ * Set a function taking a (char *) as argument to flag errors. If the
* callback is not set, the error is discarded.
* \param f The function to use as callback
* \attention used in creator.c
diff --git a/source/blender/blenlib/BLI_string.h b/source/blender/blenlib/BLI_string.h
index b3d0df04eb1..70c89773f02 100644
--- a/source/blender/blenlib/BLI_string.h
+++ b/source/blender/blenlib/BLI_string.h
@@ -74,7 +74,7 @@ __attribute__((nonnull))
* \param str2 second string for append
* \retval Returns dst
*/
-char *BLI_strdupcat(const char *str1, const char *str2)
+char *BLI_strdupcat(const char *__restrict str1, const char *__restrict str2)
#ifdef __GNUC__
__attribute__((warn_unused_result))
__attribute__((nonnull))
@@ -91,7 +91,7 @@ __attribute__((nonnull))
* the size of dst)
* \retval Returns dst
*/
-char *BLI_strncpy(char *dst, const char *src, const size_t maxncpy)
+char *BLI_strncpy(char *__restrict dst, const char *__restrict src, const size_t maxncpy)
#ifdef __GNUC__
__attribute__((nonnull))
#endif
@@ -107,7 +107,7 @@ __attribute__((nonnull))
* Assume that the strings returned must be freed afterwards, and that the inputs will contain
* data we want...
*/
-char *BLI_str_quoted_substrN(const char *str, const char *prefix)
+char *BLI_str_quoted_substrN(const char *__restrict str, const char *__restrict prefix)
#ifdef __GNUC__
__attribute__((warn_unused_result))
__attribute__((nonnull))
@@ -124,7 +124,7 @@ __attribute__((nonnull))
* \param newText The text in the string to find and replace
* \retval Returns the duplicated string
*/
-char *BLI_replacestr(char *str, const char *oldText, const char *newText)
+char *BLI_replacestr(char *__restrict str, const char *__restrict oldText, const char *__restrict newText)
#ifdef __GNUC__
__attribute__((warn_unused_result))
__attribute__((nonnull))
@@ -134,7 +134,7 @@ __attribute__((nonnull))
/*
* Replacement for snprintf
*/
-size_t BLI_snprintf(char *buffer, size_t len, const char *format, ...)
+size_t BLI_snprintf(char *__restrict buffer, size_t len, const char *__restrict format, ...)
#ifdef __GNUC__
__attribute__ ((format(printf, 3, 4)))
__attribute__((nonnull))
@@ -144,13 +144,17 @@ __attribute__((nonnull))
/*
* Replacement for vsnprintf
*/
-size_t BLI_vsnprintf(char *buffer, size_t count, const char *format, va_list arg);
+size_t BLI_vsnprintf(char *__restrict buffer, size_t count, const char *__restrict format, va_list arg)
+#ifdef __GNUC__
+__attribute__ ((format(printf, 3, 0)))
+#endif
+;
/*
* Print formatted string into a newly mallocN'd string
* and return it.
*/
-char *BLI_sprintfN(const char *format, ...)
+char *BLI_sprintfN(const char *__restrict format, ...)
#ifdef __GNUC__
__attribute__ ((format(printf, 1, 2)))
__attribute__((warn_unused_result))
@@ -158,7 +162,7 @@ __attribute__((nonnull))
#endif
;
-size_t BLI_strescape(char *dst, const char *src, const size_t maxlen)
+size_t BLI_strescape(char *__restrict dst, const char *__restrict src, const size_t maxncpy)
#ifdef __GNUC__
__attribute__((nonnull))
#endif
@@ -200,7 +204,7 @@ __attribute__((warn_unused_result))
__attribute__((nonnull))
#endif
;
-size_t BLI_strnlen(const char *str, size_t maxlen)
+size_t BLI_strnlen(const char *str, const size_t maxlen)
#ifdef __GNUC__
__attribute__((warn_unused_result))
__attribute__((nonnull))
@@ -212,12 +216,12 @@ __attribute__((nonnull))
#endif
; /* time var is global */
-void BLI_ascii_strtolower(char *str, int len)
+void BLI_ascii_strtolower(char *str, const size_t len)
#ifdef __GNUC__
__attribute__((nonnull))
#endif
;
-void BLI_ascii_strtoupper(char *str, int len)
+void BLI_ascii_strtoupper(char *str, const size_t len)
#ifdef __GNUC__
__attribute__((nonnull))
#endif
diff --git a/source/blender/blenlib/BLI_string_utf8.h b/source/blender/blenlib/BLI_string_utf8.h
index 56ed4beba53..73f138a750d 100644
--- a/source/blender/blenlib/BLI_string_utf8.h
+++ b/source/blender/blenlib/BLI_string_utf8.h
@@ -31,16 +31,16 @@
extern "C" {
#endif
-char *BLI_strncpy_utf8(char *dst, const char *src, size_t maxncpy);
-char *BLI_strncat_utf8(char *dst, const char *src, size_t maxncpy);
+char *BLI_strncpy_utf8(char *__restrict dst, const char *__restrict src, size_t maxncpy);
+char *BLI_strncat_utf8(char *__restrict dst, const char *__restrict src, size_t maxncpy);
int BLI_utf8_invalid_byte(const char *str, int length);
int BLI_utf8_invalid_strip(char *str, int length);
int BLI_str_utf8_size(const char *p); /* warning, can return -1 on bad chars */
/* copied from glib */
unsigned int BLI_str_utf8_as_unicode(const char *p);
-unsigned int BLI_str_utf8_as_unicode_and_size(const char *p, size_t *index);
-unsigned int BLI_str_utf8_as_unicode_step(const char *p, size_t *index);
+unsigned int BLI_str_utf8_as_unicode_and_size(const char *__restrict p, size_t *__restrict index);
+unsigned int BLI_str_utf8_as_unicode_step(const char *__restrict p, size_t *__restrict index);
size_t BLI_str_utf8_from_unicode(unsigned int c, char *outbuf);
char *BLI_str_find_prev_char_utf8(const char *str, const char *p);
@@ -50,8 +50,9 @@ char *BLI_str_prev_char_utf8(const char *p);
/* wchar_t functions, copied from blenders own font.c originally */
size_t BLI_wstrlen_utf8(const wchar_t *src);
size_t BLI_strlen_utf8(const char *strc);
-size_t BLI_strncpy_wchar_as_utf8(char *dst, const wchar_t *src, const size_t maxcpy);
-size_t BLI_strncpy_wchar_from_utf8(wchar_t *dst, const char *src, const size_t maxcpy);
+size_t BLI_strnlen_utf8(const char *start, const size_t maxlen);
+size_t BLI_strncpy_wchar_as_utf8(char *__restrict dst, const wchar_t *__restrict src, const size_t maxcpy);
+size_t BLI_strncpy_wchar_from_utf8(wchar_t *__restrict dst, const char *__restrict src, const size_t maxcpy);
#define BLI_UTF8_MAX 6
#define BLI_UTF8_ERR ((unsigned int)-1)
diff --git a/source/blender/blenlib/BLI_utildefines.h b/source/blender/blenlib/BLI_utildefines.h
index 29097a4c6c3..056fa916da1 100644
--- a/source/blender/blenlib/BLI_utildefines.h
+++ b/source/blender/blenlib/BLI_utildefines.h
@@ -40,43 +40,22 @@
# define TRUE 1
#endif
-
-#define ELEM(a, b, c) ((a) == (b) || (a) == (c))
-#define ELEM3(a, b, c, d) (ELEM(a, b, c) || (a) == (d) )
-#define ELEM4(a, b, c, d, e) (ELEM(a, b, c) || ELEM(a, d, e) )
-#define ELEM5(a, b, c, d, e, f) (ELEM(a, b, c) || ELEM3(a, d, e, f) )
-#define ELEM6(a, b, c, d, e, f, g) (ELEM(a, b, c) || ELEM4(a, d, e, f, g) )
-#define ELEM7(a, b, c, d, e, f, g, h) (ELEM3(a, b, c, d) || ELEM4(a, e, f, g, h) )
-#define ELEM8(a, b, c, d, e, f, g, h, i) (ELEM4(a, b, c, d, e) || ELEM4(a, f, g, h, i) )
-#define ELEM9(a, b, c, d, e, f, g, h, i, j) (ELEM4(a, b, c, d, e) || ELEM5(a, f, g, h, i, j) )
-#define ELEM10(a, b, c, d, e, f, g, h, i, j, k) (ELEM4(a, b, c, d, e) || ELEM6(a, f, g, h, i, j, k) )
-#define ELEM11(a, b, c, d, e, f, g, h, i, j, k, l) (ELEM4(a, b, c, d, e) || ELEM7(a, f, g, h, i, j, k, l) )
-
-/* shift around elements */
-#define SHIFT3(type, a, b, c) { \
- type tmp; \
- tmp = a; \
- a = c; \
- c = b; \
- b = tmp; \
-} (void)0
-#define SHIFT4(type, a, b, c, d) { \
- type tmp; \
- tmp = a; \
- a = d; \
- d = c; \
- c = b; \
- b = tmp; \
-} (void)0
+/* useful for finding bad use of min/max */
+#if 0
+/* gcc only */
+# define _TYPECHECK(a, b) ((void)(((typeof(a) *)0) == ((typeof(b) *)0)))
+# define MIN2(x, y) (_TYPECHECK(x, y), (((x) < (y) ? (x) : (y))))
+# define MAX2(x, y) (_TYPECHECK(x, y), (((x) > (y) ? (x) : (y))))
+#endif
/* min/max */
-#define MIN2(x, y) ( (x) < (y) ? (x) : (y) )
-#define MIN3(x, y, z) MIN2(MIN2((x), (y)), (z) )
-#define MIN4(x, y, z, a) MIN2(MIN2((x), (y)), MIN2((z), (a)) )
+#define MIN2(x, y) ((x) < (y) ? (x) : (y))
+#define MIN3(x, y, z) (MIN2(MIN2((x), (y)), (z)))
+#define MIN4(x, y, z, a) (MIN2(MIN2((x), (y)), MIN2((z), (a))))
-#define MAX2(x, y) ( (x) > (y) ? (x) : (y) )
-#define MAX3(x, y, z) MAX2(MAX2((x), (y)), (z) )
-#define MAX4(x, y, z, a) MAX2(MAX2((x), (y)), MAX2((z), (a)) )
+#define MAX2(x, y) ((x) > (y) ? (x) : (y))
+#define MAX3(x, y, z) (MAX2(MAX2((x), (y)), (z)))
+#define MAX4(x, y, z, a) (MAX2(MAX2((x), (y)), MAX2((z), (a))))
#define INIT_MINMAX(min, max) { \
(min)[0] = (min)[1] = (min)[2] = 1.0e30f; \
@@ -116,20 +95,28 @@
/* Causes warning:
* incompatible types when assigning to type 'Foo' from type 'Bar'
* ... the compiler optimizes away the temp var */
-#ifndef CHECK_TYPE
#ifdef __GNUC__
#define CHECK_TYPE(var, type) { \
__typeof(var) *__tmp; \
__tmp = (type *)NULL; \
(void)__tmp; \
} (void)0
+
+#define CHECK_TYPE_PAIR(var_a, var_b) { \
+ __typeof(var_a) *__tmp; \
+ __tmp = (__typeof(var_b) *)NULL; \
+ (void)__tmp; \
+} (void)0
#else
-#define CHECK_TYPE(var, type)
-#endif
+# define CHECK_TYPE(var, type)
+# define CHECK_TYPE_PAIR(var_a, var_b)
#endif
-#ifndef SWAP
-# define SWAP(type, a, b) { \
+/* can be used in simple macros */
+#define CHECK_TYPE_INLINE(val, type) \
+ ((void)(((type *)0) != (val)))
+
+#define SWAP(type, a, b) { \
type sw_ap; \
CHECK_TYPE(a, type); \
CHECK_TYPE(b, type); \
@@ -137,7 +124,53 @@
(a) = (b); \
(b) = sw_ap; \
} (void)0
-#endif
+
+/* swap with a temp value */
+#define SWAP_TVAL(tval, a, b) { \
+ CHECK_TYPE_PAIR(tval, a); \
+ CHECK_TYPE_PAIR(tval, b); \
+ (tval) = (a); \
+ (a) = (b); \
+ (b) = (tval); \
+} (void)0
+
+
+#define ELEM(a, b, c) ((a) == (b) || (a) == (c))
+#define ELEM3(a, b, c, d) (ELEM(a, b, c) || (a) == (d) )
+#define ELEM4(a, b, c, d, e) (ELEM(a, b, c) || ELEM(a, d, e) )
+#define ELEM5(a, b, c, d, e, f) (ELEM(a, b, c) || ELEM3(a, d, e, f) )
+#define ELEM6(a, b, c, d, e, f, g) (ELEM(a, b, c) || ELEM4(a, d, e, f, g) )
+#define ELEM7(a, b, c, d, e, f, g, h) (ELEM3(a, b, c, d) || ELEM4(a, e, f, g, h) )
+#define ELEM8(a, b, c, d, e, f, g, h, i) (ELEM4(a, b, c, d, e) || ELEM4(a, f, g, h, i) )
+#define ELEM9(a, b, c, d, e, f, g, h, i, j) (ELEM4(a, b, c, d, e) || ELEM5(a, f, g, h, i, j) )
+#define ELEM10(a, b, c, d, e, f, g, h, i, j, k) (ELEM4(a, b, c, d, e) || ELEM6(a, f, g, h, i, j, k) )
+#define ELEM11(a, b, c, d, e, f, g, h, i, j, k, l) (ELEM4(a, b, c, d, e) || ELEM7(a, f, g, h, i, j, k, l) )
+
+/* shift around elements */
+#define SHIFT3(type, a, b, c) { \
+ type tmp; \
+ CHECK_TYPE(a, type); \
+ CHECK_TYPE(b, type); \
+ CHECK_TYPE(c, type); \
+ tmp = a; \
+ a = c; \
+ c = b; \
+ b = tmp; \
+} (void)0
+
+#define SHIFT4(type, a, b, c, d) { \
+ type tmp; \
+ CHECK_TYPE(a, type); \
+ CHECK_TYPE(b, type); \
+ CHECK_TYPE(c, type); \
+ CHECK_TYPE(d, type); \
+ tmp = a; \
+ a = d; \
+ d = c; \
+ c = b; \
+ b = tmp; \
+} (void)0
+
#define ABS(a) ( (a) < 0 ? (-(a)) : (a) )
@@ -189,6 +222,11 @@
*(v1 + 1) = *(v2 + 1) + *(v3 + 1) * (fac); \
*(v1 + 2) = *(v2 + 2) + *(v3 + 2) * (fac); \
} (void)0
+#define VECMADD(v1, v2, v3, v4) { \
+ *(v1) = *(v2) + *(v3) * (*(v4)); \
+ *(v1 + 1) = *(v2 + 1) + *(v3 + 1) * (*(v4 + 1)); \
+ *(v1 + 2) = *(v2 + 2) + *(v3 + 2) * (*(v4 + 2)); \
+} (void)0
#define VECSUBFAC(v1, v2, v3, fac) { \
*(v1) = *(v2) - *(v3) * (fac); \
*(v1 + 1) = *(v2 + 1) - *(v3 + 1) * (fac); \
@@ -317,6 +355,13 @@
# define BLI_assert(a) (void)0
#endif
+#if (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406)) /* gcc4.6+ only */
+# define BLI_STATIC_ASSERT(a, msg) _Static_assert(a, msg);
+#else
+ /* TODO msvc, clang */
+# define BLI_STATIC_ASSERT(a, msg)
+#endif
+
/* hints for branch pradiction, only use in code that runs a _lot_ where */
#ifdef __GNUC__
# define LIKELY(x) __builtin_expect(!!(x), 1)
@@ -326,4 +371,4 @@
# define UNLIKELY(x) (x)
#endif
-#endif // __BLI_UTILDEFINES_H__
+#endif /* __BLI_UTILDEFINES_H__ */
diff --git a/source/blender/blenlib/BLI_voronoi.h b/source/blender/blenlib/BLI_voronoi.h
index a67b01c5175..68d7398d89b 100644
--- a/source/blender/blenlib/BLI_voronoi.h
+++ b/source/blender/blenlib/BLI_voronoi.h
@@ -49,7 +49,7 @@ typedef struct VoronoiEdge {
float left[2]; /* point on Voronoi place on the left side of edge */
float right[2]; /* point on Voronoi place on the right side of edge */
- float f, g; /* directional coeffitients satisfying equation y = f*x + g (edge lies on this line) */
+ float f, g; /* directional coeffitients satisfying equation y = f * x + g (edge lies on this line) */
/* some edges consist of two parts, so we add the pointer to another part to connect them at the end of an algorithm */
struct VoronoiEdge *neighbour;
diff --git a/source/blender/blenlib/CMakeLists.txt b/source/blender/blenlib/CMakeLists.txt
index 2836174be73..6839f05bfbc 100644
--- a/source/blender/blenlib/CMakeLists.txt
+++ b/source/blender/blenlib/CMakeLists.txt
@@ -78,6 +78,7 @@ set(SRC
intern/noise.c
intern/path_util.c
intern/pbvh.c
+ intern/quadric.c
intern/rand.c
intern/rct.c
intern/scanfill.c
@@ -90,8 +91,8 @@ set(SRC
intern/threads.c
intern/time.c
intern/uvproject.c
- intern/voxel.c
intern/voronoi.c
+ intern/voxel.c
intern/winstuff.c
BLI_args.h
@@ -135,6 +136,7 @@ set(SRC
BLI_noise.h
BLI_path_util.h
BLI_pbvh.h
+ BLI_quadric.h
BLI_rand.h
BLI_rect.h
BLI_scanfill.h
diff --git a/source/blender/blenlib/PIL_time.h b/source/blender/blenlib/PIL_time.h
index 288d2fe78e5..b8f895c5c82 100644
--- a/source/blender/blenlib/PIL_time.h
+++ b/source/blender/blenlib/PIL_time.h
@@ -30,7 +30,6 @@
* \brief Platform independent time functions.
*/
-
#ifndef __PIL_TIME_H__
#define __PIL_TIME_H__
@@ -61,20 +60,24 @@ void PIL_sleep_ms(int ms);
double _timeit_##var = PIL_check_seconds_timer(); \
printf("time start (" #var "): " AT "\n"); \
fflush(stdout); \
- { (void)0 \
-
+ { (void)0
#define TIMEIT_VALUE(var) (float)(PIL_check_seconds_timer() - _timeit_##var)
+#define TIMEIT_VALUE_PRINT(var) \
+ { \
+ printf("time update(" #var "): %.6f" " " AT "\n", TIMEIT_VALUE(var));\
+ fflush(stdout); \
+ } (void)0
#define TIMEIT_END(var) \
} \
- printf("time end (" #var "): %.6f" " " AT "\n", TIMEIT_VALUE(var)); \
+ printf("time end (" #var "): %.6f" " " AT "\n", TIMEIT_VALUE(var)); \
fflush(stdout); \
-} (void)0 \
+} (void)0
#ifdef __cplusplus
}
#endif
-#endif /* !__PIL_TIME_H__ */
+#endif /* !__PIL_TIME_H__ */
diff --git a/source/blender/blenlib/intern/BLI_ghash.c b/source/blender/blenlib/intern/BLI_ghash.c
index 844407f9e06..0cae9bab531 100644
--- a/source/blender/blenlib/intern/BLI_ghash.c
+++ b/source/blender/blenlib/intern/BLI_ghash.c
@@ -135,7 +135,7 @@ int BLI_ghash_remove(GHash *gh, void *key, GHashKeyFreeFP keyfreefp, GHashValFre
BLI_mempool_free(gh->entrypool, e);
/* correct but 'e' isn't used before return */
- /* e= n; *//*UNUSED*/
+ /* e = n; *//*UNUSED*/
if (p) p->next = n;
else gh->buckets[hash] = n;
@@ -165,7 +165,7 @@ void *BLI_ghash_pop(GHash *gh, void *key, GHashKeyFreeFP keyfreefp)
BLI_mempool_free(gh->entrypool, e);
/* correct but 'e' isn't used before return */
- /* e= n; *//*UNUSED*/
+ /* e = n; *//*UNUSED*/
if (p) p->next = n;
else gh->buckets[hash] = n;
diff --git a/source/blender/blenlib/intern/BLI_heap.c b/source/blender/blenlib/intern/BLI_heap.c
index c1175192434..dcc028630e2 100644
--- a/source/blender/blenlib/intern/BLI_heap.c
+++ b/source/blender/blenlib/intern/BLI_heap.c
@@ -40,9 +40,9 @@
/***/
struct HeapNode {
- void *ptr;
- float value;
- int index;
+ void *ptr;
+ float value;
+ unsigned int index;
};
struct Heap {
@@ -54,48 +54,43 @@ struct Heap {
HeapNode **tree;
};
+/* internal functions */
+
#define HEAP_PARENT(i) ((i - 1) >> 1)
#define HEAP_LEFT(i) ((i << 1) + 1)
#define HEAP_RIGHT(i) ((i << 1) + 2)
#define HEAP_COMPARE(a, b) (a->value < b->value)
-#define HEAP_EQUALS(a, b) (a->value == b->value)
-#define HEAP_SWAP(heap, i, j) \
- { \
- SWAP(int, heap->tree[i]->index, heap->tree[j]->index); \
- SWAP(HeapNode *, heap->tree[i], heap->tree[j]); \
- } (void)0
-/***/
+#if 0 /* UNUSED */
+#define HEAP_EQUALS(a, b) (a->value == b->value)
+#endif
-Heap *BLI_heap_new(void)
+BLI_INLINE void heap_swap(Heap *heap, const unsigned int i, const unsigned int j)
{
- Heap *heap = (Heap *)MEM_callocN(sizeof(Heap), __func__);
- heap->bufsize = 1;
- heap->tree = (HeapNode **)MEM_mallocN(sizeof(HeapNode *), "BLIHeapTree");
- heap->arena = BLI_memarena_new(1 << 16, "heap arena");
- return heap;
+#if 0
+ SWAP(unsigned int, heap->tree[i]->index, heap->tree[j]->index);
+ SWAP(HeapNode *, heap->tree[i], heap->tree[j]);
+#else
+ HeapNode **tree = heap->tree;
+ union {
+ unsigned int index;
+ HeapNode *node;
+ } tmp;
+ SWAP_TVAL(tmp.index, tree[i]->index, tree[j]->index);
+ SWAP_TVAL(tmp.node, tree[i], tree[j]);
+#endif
}
-void BLI_heap_free(Heap *heap, HeapFreeFP ptrfreefp)
+static void heap_down(Heap *heap, unsigned int i)
{
- int i;
-
- if (ptrfreefp)
- for (i = 0; i < heap->size; i++)
- ptrfreefp(heap->tree[i]->ptr);
-
- MEM_freeN(heap->tree);
- BLI_memarena_free(heap->arena);
- MEM_freeN(heap);
-}
+ /* size won't change in the loop */
+ const unsigned int size = heap->size;
-static void BLI_heap_down(Heap *heap, int i)
-{
while (1) {
- int size = heap->size, smallest;
- int l = HEAP_LEFT(i);
- int r = HEAP_RIGHT(i);
+ const unsigned int l = HEAP_LEFT(i);
+ const unsigned int r = HEAP_RIGHT(i);
+ unsigned int smallest;
smallest = ((l < size) && HEAP_COMPARE(heap->tree[l], heap->tree[i])) ? l : i;
@@ -105,46 +100,75 @@ static void BLI_heap_down(Heap *heap, int i)
if (smallest == i)
break;
- HEAP_SWAP(heap, i, smallest);
+ heap_swap(heap, i, smallest);
i = smallest;
}
}
-static void BLI_heap_up(Heap *heap, int i)
+static void heap_up(Heap *heap, unsigned int i)
{
while (i > 0) {
- int p = HEAP_PARENT(i);
+ const unsigned int p = HEAP_PARENT(i);
if (HEAP_COMPARE(heap->tree[p], heap->tree[i]))
break;
- HEAP_SWAP(heap, p, i);
+ heap_swap(heap, p, i);
i = p;
}
}
-HeapNode *BLI_heap_insert(Heap *heap, float value, void *ptr)
+
+/***/
+
+/* use when the size of the heap is known in advance */
+Heap *BLI_heap_new_ex(unsigned int tot_reserve)
{
- HeapNode *node;
+ Heap *heap = (Heap *)MEM_callocN(sizeof(Heap), __func__);
+ /* ensure we have at least one so we can keep doubling it */
+ heap->bufsize = MAX2(1, tot_reserve);
+ heap->tree = (HeapNode **)MEM_mallocN(heap->bufsize * sizeof(HeapNode *), "BLIHeapTree");
+ heap->arena = BLI_memarena_new(1 << 16, "heap arena");
- if ((heap->size + 1) > heap->bufsize) {
- int newsize = heap->bufsize * 2;
- HeapNode **newtree;
+ return heap;
+}
+
+Heap *BLI_heap_new(void)
+{
+ return BLI_heap_new_ex(1);
+}
- newtree = (HeapNode **)MEM_mallocN(newsize * sizeof(*newtree), __func__);
- memcpy(newtree, heap->tree, sizeof(HeapNode *) * heap->size);
- MEM_freeN(heap->tree);
+void BLI_heap_free(Heap *heap, HeapFreeFP ptrfreefp)
+{
+ unsigned int i;
- heap->tree = newtree;
- heap->bufsize = newsize;
+ if (ptrfreefp) {
+ for (i = 0; i < heap->size; i++) {
+ ptrfreefp(heap->tree[i]->ptr);
+ }
+ }
+
+ MEM_freeN(heap->tree);
+ BLI_memarena_free(heap->arena);
+ MEM_freeN(heap);
+}
+
+HeapNode *BLI_heap_insert(Heap *heap, float value, void *ptr)
+{
+ HeapNode *node;
+
+ if (UNLIKELY((heap->size + 1) > heap->bufsize)) {
+ heap->bufsize *= 2;
+ heap->tree = MEM_reallocN(heap->tree, heap->bufsize * sizeof(*heap->tree));
}
if (heap->freenodes) {
node = heap->freenodes;
heap->freenodes = (HeapNode *)(((HeapNode *)heap->freenodes)->ptr);
}
- else
+ else {
node = (HeapNode *)BLI_memarena_alloc(heap->arena, sizeof *node);
+ }
node->value = value;
node->ptr = ptr;
@@ -154,17 +178,17 @@ HeapNode *BLI_heap_insert(Heap *heap, float value, void *ptr)
heap->size++;
- BLI_heap_up(heap, heap->size - 1);
+ heap_up(heap, heap->size - 1);
return node;
}
-int BLI_heap_empty(Heap *heap)
+int BLI_heap_is_empty(Heap *heap)
{
return (heap->size == 0);
}
-int BLI_heap_size(Heap *heap)
+unsigned int BLI_heap_size(Heap *heap)
{
return heap->size;
}
@@ -181,13 +205,14 @@ void *BLI_heap_popmin(Heap *heap)
heap->tree[0]->ptr = heap->freenodes;
heap->freenodes = heap->tree[0];
- if (heap->size == 1)
+ if (UNLIKELY(heap->size == 1)) {
heap->size--;
+ }
else {
- HEAP_SWAP(heap, 0, heap->size - 1);
+ heap_swap(heap, 0, heap->size - 1);
heap->size--;
- BLI_heap_down(heap, 0);
+ heap_down(heap, 0);
}
return ptr;
@@ -195,12 +220,12 @@ void *BLI_heap_popmin(Heap *heap)
void BLI_heap_remove(Heap *heap, HeapNode *node)
{
- int i = node->index;
+ unsigned int i = node->index;
while (i > 0) {
- int p = HEAP_PARENT(i);
+ unsigned int p = HEAP_PARENT(i);
- HEAP_SWAP(heap, p, i);
+ heap_swap(heap, p, i);
i = p;
}
diff --git a/source/blender/blenlib/intern/BLI_kdopbvh.c b/source/blender/blenlib/intern/BLI_kdopbvh.c
index 2b3c314131b..70617453eff 100644
--- a/source/blender/blenlib/intern/BLI_kdopbvh.c
+++ b/source/blender/blenlib/intern/BLI_kdopbvh.c
@@ -42,7 +42,8 @@
#endif
#define MAX_TREETYPE 32
-#define DEFAULT_FIND_NEAREST_HEAP_SIZE 1024
+
+typedef unsigned char axis_t;
typedef struct BVHNode {
struct BVHNode **children;
@@ -54,6 +55,7 @@ typedef struct BVHNode {
char main_axis; /* Axis used to split this node */
} BVHNode;
+/* keep under 26 bytes for speed purposes */
struct BVHTree {
BVHNode **nodes;
BVHNode *nodearray; /* pre-alloc branch nodes */
@@ -62,16 +64,21 @@ struct BVHTree {
float epsilon; /* epslion is used for inflation of the k-dop */
int totleaf; /* leafs */
int totbranch;
+ axis_t start_axis, stop_axis; /* KDOP_AXES array indices according to axis */
+ axis_t axis; /* kdop type (6 => OBB, 7 => AABB, ...) */
char tree_type; /* type of tree (4 => quadtree) */
- char axis; /* kdop type (6 => OBB, 7 => AABB, ...) */
- char start_axis, stop_axis; /* KDOP_AXES array indices according to axis */
};
+/* optimization, ensure we stay small */
+BLI_STATIC_ASSERT((sizeof(void *) == 8 && sizeof(BVHTree) <= 48) ||
+ (sizeof(void *) == 4 && sizeof(BVHTree) <= 32),
+ "over sized");
+
typedef struct BVHOverlapData {
BVHTree *tree1, *tree2;
BVHTreeOverlap *overlap;
int i, max_overlap; /* i is number of overlaps */
- int start_axis, stop_axis;
+ axis_t start_axis, stop_axis;
} BVHOverlapData;
typedef struct BVHNearestData {
@@ -114,6 +121,17 @@ static float KDOP_AXES[13][3] = {
{0, 1.0, -1.0}
};
+MINLINE axis_t min_axis(axis_t a, axis_t b)
+{
+ return (a < b) ? a : b;
+}
+MINLINE axis_t max_axis(axis_t a, axis_t b)
+{
+ return (b < a) ? a : b;
+}
+
+#if 0
+
/*
* Generic push and pop heap
*/
@@ -153,7 +171,6 @@ static float KDOP_AXES[13][3] = {
heap[parent] = element; \
} (void)0
-#if 0
static int ADJUST_MEMORY(void *local_memblock, void **memblock, int new_size, int *max_size, int size_per_item)
{
int new_max_size = *max_size * 2;
@@ -269,7 +286,7 @@ static void bvh_heapsort(BVHNode **a, int lo, int hi, int axis)
}
#endif
-static BVHNode *bvh_medianof3(BVHNode **a, int lo, int mid, int hi, int axis) // returns Sortable
+static BVHNode *bvh_medianof3(BVHNode **a, int lo, int mid, int hi, int axis) /* returns Sortable */
{
if ((a[mid])->bv[axis] < (a[lo])->bv[axis]) {
if ((a[hi])->bv[axis] < (a[mid])->bv[axis])
@@ -374,24 +391,25 @@ static void create_kdop_hull(BVHTree *tree, BVHNode *node, const float *co, int
{
float newminmax;
float *bv = node->bv;
- int i, k;
+ int k;
+ axis_t axis_iter;
/* don't init boudings for the moving case */
if (!moving) {
- for (i = tree->start_axis; i < tree->stop_axis; i++) {
- bv[2 * i] = FLT_MAX;
- bv[2 * i + 1] = -FLT_MAX;
+ for (axis_iter = tree->start_axis; axis_iter < tree->stop_axis; axis_iter++) {
+ bv[2 * axis_iter] = FLT_MAX;
+ bv[2 * axis_iter + 1] = -FLT_MAX;
}
}
for (k = 0; k < numpoints; k++) {
/* for all Axes. */
- for (i = tree->start_axis; i < tree->stop_axis; i++) {
- newminmax = dot_v3v3(&co[k * 3], KDOP_AXES[i]);
- if (newminmax < bv[2 * i])
- bv[2 * i] = newminmax;
- if (newminmax > bv[(2 * i) + 1])
- bv[(2 * i) + 1] = newminmax;
+ for (axis_iter = tree->start_axis; axis_iter < tree->stop_axis; axis_iter++) {
+ newminmax = dot_v3v3(&co[k * 3], KDOP_AXES[axis_iter]);
+ if (newminmax < bv[2 * axis_iter])
+ bv[2 * axis_iter] = newminmax;
+ if (newminmax > bv[(2 * axis_iter) + 1])
+ bv[(2 * axis_iter) + 1] = newminmax;
}
}
}
@@ -400,25 +418,25 @@ static void create_kdop_hull(BVHTree *tree, BVHNode *node, const float *co, int
static void refit_kdop_hull(BVHTree *tree, BVHNode *node, int start, int end)
{
float newmin, newmax;
- int i, j;
float *bv = node->bv;
+ int j;
+ axis_t axis_iter;
-
- for (i = tree->start_axis; i < tree->stop_axis; i++) {
- bv[2 * i] = FLT_MAX;
- bv[2 * i + 1] = -FLT_MAX;
+ for (axis_iter = tree->start_axis; axis_iter < tree->stop_axis; axis_iter++) {
+ bv[(2 * axis_iter)] = FLT_MAX;
+ bv[(2 * axis_iter) + 1] = -FLT_MAX;
}
for (j = start; j < end; j++) {
/* for all Axes. */
- for (i = tree->start_axis; i < tree->stop_axis; i++) {
- newmin = tree->nodes[j]->bv[(2 * i)];
- if ((newmin < bv[(2 * i)]))
- bv[(2 * i)] = newmin;
-
- newmax = tree->nodes[j]->bv[(2 * i) + 1];
- if ((newmax > bv[(2 * i) + 1]))
- bv[(2 * i) + 1] = newmax;
+ for (axis_iter = tree->start_axis; axis_iter < tree->stop_axis; axis_iter++) {
+ newmin = tree->nodes[j]->bv[(2 * axis_iter)];
+ if ((newmin < bv[(2 * axis_iter)]))
+ bv[(2 * axis_iter)] = newmin;
+
+ newmax = tree->nodes[j]->bv[(2 * axis_iter) + 1];
+ if ((newmax > bv[(2 * axis_iter) + 1]))
+ bv[(2 * axis_iter) + 1] = newmax;
}
}
@@ -451,23 +469,24 @@ static char get_largest_axis(float *bv)
* join the children on the parent BV */
static void node_join(BVHTree *tree, BVHNode *node)
{
- int i, j;
-
- for (i = tree->start_axis; i < tree->stop_axis; i++) {
- node->bv[2 * i] = FLT_MAX;
- node->bv[2 * i + 1] = -FLT_MAX;
+ int i;
+ axis_t axis_iter;
+
+ for (axis_iter = tree->start_axis; axis_iter < tree->stop_axis; axis_iter++) {
+ node->bv[(2 * axis_iter)] = FLT_MAX;
+ node->bv[(2 * axis_iter) + 1] = -FLT_MAX;
}
for (i = 0; i < tree->tree_type; i++) {
if (node->children[i]) {
- for (j = tree->start_axis; j < tree->stop_axis; j++) {
+ for (axis_iter = tree->start_axis; axis_iter < tree->stop_axis; axis_iter++) {
/* update minimum */
- if (node->children[i]->bv[(2 * j)] < node->bv[(2 * j)])
- node->bv[(2 * j)] = node->children[i]->bv[(2 * j)];
+ if (node->children[i]->bv[(2 * axis_iter)] < node->bv[(2 * axis_iter)])
+ node->bv[(2 * axis_iter)] = node->children[i]->bv[(2 * axis_iter)];
/* update maximum */
- if (node->children[i]->bv[(2 * j) + 1] > node->bv[(2 * j) + 1])
- node->bv[(2 * j) + 1] = node->children[i]->bv[(2 * j) + 1];
+ if (node->children[i]->bv[(2 * axis_iter) + 1] > node->bv[(2 * axis_iter) + 1])
+ node->bv[(2 * axis_iter) + 1] = node->children[i]->bv[(2 * axis_iter) + 1];
}
}
else
@@ -482,10 +501,12 @@ static void node_join(BVHTree *tree, BVHNode *node)
static void bvhtree_print_tree(BVHTree *tree, BVHNode *node, int depth)
{
int i;
+ axis_t axis_iter;
+
for (i = 0; i < depth; i++) printf(" ");
printf(" - %d (%ld): ", node->index, node - tree->nodearray);
- for (i = 2 * tree->start_axis; i < 2 * tree->stop_axis; i++)
- printf("%.3f ", node->bv[i]);
+ for (axis_iter = 2 * tree->start_axis; axis_iter < 2 * tree->stop_axis; axis_iter++)
+ printf("%.3f ", node->bv[axis_iter]);
printf("\n");
for (i = 0; i < tree->tree_type; i++)
@@ -645,10 +666,10 @@ static int implicit_leafs_index(BVHBuildHelper *data, int depth, int child_index
* (looping elements, knowing if its a leaf or not.. etc...)
*/
-// This functions returns the number of branches needed to have the requested number of leafs.
+/* This functions returns the number of branches needed to have the requested number of leafs. */
static int implicit_needed_branches(int tree_type, int leafs)
{
- return maxi(1, (leafs + tree_type - 3) / (tree_type - 1) );
+ return max_ii(1, (leafs + tree_type - 3) / (tree_type - 1) );
}
/*
@@ -705,8 +726,8 @@ static void non_recursive_bvh_div_nodes(BVHTree *tree, BVHNode *branches_array,
BVHNode *tmp = branches_array + 0;
tmp->parent = NULL;
- /*Most of bvhtree code relies on 1-leaf trees having at least one branch
- *We handle that special case here */
+ /* Most of bvhtree code relies on 1-leaf trees having at least one branch
+ * We handle that special case here */
if (num_leafs == 1) {
BVHNode *root = branches_array + 0;
refit_kdop_hull(tree, root, 0, num_leafs);
@@ -724,7 +745,7 @@ static void non_recursive_bvh_div_nodes(BVHTree *tree, BVHNode *branches_array,
/* Loop tree levels (log N) loops */
for (i = 1, depth = 1; i <= num_branches; i = i * tree_type + tree_offset, depth++) {
const int first_of_next_level = i * tree_type + tree_offset;
- const int end_j = MIN2(first_of_next_level, num_branches + 1); /* index of last branch on this level */
+ const int end_j = min_ii(first_of_next_level, num_branches + 1); /* index of last branch on this level */
int j;
/* Loop all branches on this level */
@@ -810,7 +831,7 @@ BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis)
/* tree epsilon must be >= FLT_EPSILON
* so that tangent rays can still hit a bounding volume..
* this bug would show up when casting a ray aligned with a kdop-axis and with an edge of 2 faces */
- epsilon = MAX2(FLT_EPSILON, epsilon);
+ epsilon = max_ff(FLT_EPSILON, epsilon);
if (tree) {
tree->epsilon = epsilon;
@@ -843,7 +864,7 @@ BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis)
}
- //Allocate arrays
+ /* Allocate arrays */
numnodes = maxsize + implicit_needed_branches(tree_type, maxsize) + tree_type;
tree->nodes = (BVHNode **)MEM_callocN(sizeof(BVHNode *) * numnodes, "BVHNodes");
@@ -876,7 +897,7 @@ BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis)
return NULL;
}
- //link the dynamic bv and child links
+ /* link the dynamic bv and child links */
for (i = 0; i < numnodes; i++) {
tree->nodearray[i].bv = tree->nodebv + i * axis;
tree->nodearray[i].children = tree->nodechild + i * tree_type;
@@ -921,9 +942,9 @@ void BLI_bvhtree_balance(BVHTree *tree)
/* bvhtree_info(tree); */
}
-int BLI_bvhtree_insert(BVHTree *tree, int index, const float *co, int numpoints)
+int BLI_bvhtree_insert(BVHTree *tree, int index, const float co[3], int numpoints)
{
- int i;
+ axis_t axis_iter;
BVHNode *node = NULL;
/* insert should only possible as long as tree->totbranch is 0 */
@@ -942,9 +963,9 @@ int BLI_bvhtree_insert(BVHTree *tree, int index, const float *co, int numpoints)
node->index = index;
/* inflate the bv with some epsilon */
- for (i = tree->start_axis; i < tree->stop_axis; i++) {
- node->bv[(2 * i)] -= tree->epsilon; /* minimum */
- node->bv[(2 * i) + 1] += tree->epsilon; /* maximum */
+ for (axis_iter = tree->start_axis; axis_iter < tree->stop_axis; axis_iter++) {
+ node->bv[(2 * axis_iter)] -= tree->epsilon; /* minimum */
+ node->bv[(2 * axis_iter) + 1] += tree->epsilon; /* maximum */
}
return 1;
@@ -952,10 +973,10 @@ int BLI_bvhtree_insert(BVHTree *tree, int index, const float *co, int numpoints)
/* call before BLI_bvhtree_update_tree() */
-int BLI_bvhtree_update_node(BVHTree *tree, int index, const float *co, const float *co_moving, int numpoints)
+int BLI_bvhtree_update_node(BVHTree *tree, int index, const float co[3], const float co_moving[3], int numpoints)
{
- int i;
BVHNode *node = NULL;
+ axis_t axis_iter;
/* check if index exists */
if (index > tree->totleaf)
@@ -968,10 +989,10 @@ int BLI_bvhtree_update_node(BVHTree *tree, int index, const float *co, const flo
if (co_moving)
create_kdop_hull(tree, node, co_moving, numpoints, 1);
- // inflate the bv with some epsilon
- for (i = tree->start_axis; i < tree->stop_axis; i++) {
- node->bv[(2 * i)] -= tree->epsilon; // minimum
- node->bv[(2 * i) + 1] += tree->epsilon; // maximum
+ /* inflate the bv with some epsilon */
+ for (axis_iter = tree->start_axis; axis_iter < tree->stop_axis; axis_iter++) {
+ node->bv[(2 * axis_iter)] -= tree->epsilon; /* minimum */
+ node->bv[(2 * axis_iter) + 1] += tree->epsilon; /* maximum */
}
return 1;
@@ -991,7 +1012,7 @@ void BLI_bvhtree_update_tree(BVHTree *tree)
node_join(tree, *index);
}
-float BLI_bvhtree_getepsilon(BVHTree *tree)
+float BLI_bvhtree_getepsilon(const BVHTree *tree)
{
return tree->epsilon;
}
@@ -1001,7 +1022,7 @@ float BLI_bvhtree_getepsilon(BVHTree *tree)
* BLI_bvhtree_overlap
*
* overlap - is it possible for 2 bv's to collide ? */
-static int tree_overlap(BVHNode *node1, BVHNode *node2, int start_axis, int stop_axis)
+static int tree_overlap(BVHNode *node1, BVHNode *node2, axis_t start_axis, axis_t stop_axis)
{
float *bv1 = node1->bv;
float *bv2 = node2->bv;
@@ -1045,7 +1066,7 @@ static void traverse(BVHOverlapData *data, BVHNode *node1, BVHNode *node2)
data->max_overlap *= 2;
}
- // both leafs, insert overlap!
+ /* both leafs, insert overlap! */
data->overlap[data->i].indexA = node1->index;
data->overlap[data->i].indexB = node2->index;
@@ -1075,27 +1096,31 @@ BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, unsigned int
BVHTreeOverlap *overlap = NULL, *to = NULL;
BVHOverlapData **data;
- // check for compatibility of both trees (can't compare 14-DOP with 18-DOP)
+ /* check for compatibility of both trees (can't compare 14-DOP with 18-DOP) */
if ((tree1->axis != tree2->axis) && (tree1->axis == 14 || tree2->axis == 14) && (tree1->axis == 18 || tree2->axis == 18))
return NULL;
- // fast check root nodes for collision before doing big splitting + traversal
- if (!tree_overlap(tree1->nodes[tree1->totleaf], tree2->nodes[tree2->totleaf], MIN2(tree1->start_axis, tree2->start_axis), MIN2(tree1->stop_axis, tree2->stop_axis)))
+ /* fast check root nodes for collision before doing big splitting + traversal */
+ if (!tree_overlap(tree1->nodes[tree1->totleaf], tree2->nodes[tree2->totleaf],
+ min_axis(tree1->start_axis, tree2->start_axis),
+ min_axis(tree1->stop_axis, tree2->stop_axis)))
+ {
return NULL;
+ }
data = MEM_callocN(sizeof(BVHOverlapData *) * tree1->tree_type, "BVHOverlapData_star");
for (j = 0; j < tree1->tree_type; j++) {
data[j] = (BVHOverlapData *)MEM_callocN(sizeof(BVHOverlapData), "BVHOverlapData");
- // init BVHOverlapData
- data[j]->overlap = (BVHTreeOverlap *)malloc(sizeof(BVHTreeOverlap) * MAX2(tree1->totleaf, tree2->totleaf));
+ /* init BVHOverlapData */
+ data[j]->overlap = (BVHTreeOverlap *)malloc(sizeof(BVHTreeOverlap) * max_ii(tree1->totleaf, tree2->totleaf));
data[j]->tree1 = tree1;
data[j]->tree2 = tree2;
data[j]->max_overlap = MAX2(tree1->totleaf, tree2->totleaf);
data[j]->i = 0;
- data[j]->start_axis = MIN2(tree1->start_axis, tree2->start_axis);
- data[j]->stop_axis = MIN2(tree1->stop_axis, tree2->stop_axis);
+ data[j]->start_axis = min_axis(tree1->start_axis, tree2->start_axis);
+ data[j]->stop_axis = min_axis(tree1->stop_axis, tree2->stop_axis);
}
#pragma omp parallel for private(j) schedule(static)
@@ -1123,13 +1148,13 @@ BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, unsigned int
return overlap;
}
-//Determines the nearest point of the given node BV. Returns the squared distance to that point.
+/* Determines the nearest point of the given node BV. Returns the squared distance to that point. */
static float calc_nearest_point(const float proj[3], BVHNode *node, float *nearest)
{
int i;
const float *bv = node->bv;
- //nearest on AABB hull
+ /* nearest on AABB hull */
for (i = 0; i != 3; i++, bv += 2) {
if (bv[0] > proj[i])
nearest[i] = bv[0];
@@ -1140,7 +1165,7 @@ static float calc_nearest_point(const float proj[3], BVHNode *node, float *neare
}
#if 0
- //nearest on a general hull
+ /* nearest on a general hull */
copy_v3_v3(nearest, data->co);
for (i = data->tree->start_axis; i != data->tree->stop_axis; i++, bv += 2)
{
@@ -1167,9 +1192,7 @@ typedef struct NodeDistance {
} NodeDistance;
-#define NodeDistance_priority(a, b) ( (a).dist < (b).dist)
-
-// TODO: use a priority queue to reduce the number of nodes looked on
+/* TODO: use a priority queue to reduce the number of nodes looked on */
static void dfs_find_nearest_dfs(BVHNearestData *data, BVHNode *node)
{
if (node->totnode == 0) {
@@ -1181,7 +1204,7 @@ static void dfs_find_nearest_dfs(BVHNearestData *data, BVHNode *node)
}
}
else {
- //Better heuristic to pick the closest node to dive on
+ /* Better heuristic to pick the closest node to dive on */
int i;
float nearest[3];
@@ -1211,6 +1234,11 @@ static void dfs_find_nearest_begin(BVHNearestData *data, BVHNode *node)
#if 0
+
+#define DEFAULT_FIND_NEAREST_HEAP_SIZE 1024
+
+#define NodeDistance_priority(a, b) ( (a).dist < (b).dist)
+
static void NodeDistance_push_heap(NodeDistance *heap, int heap_size)
PUSH_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size)
@@ -1256,7 +1284,7 @@ static void bfs_find_nearest(BVHNearestData *data, BVHNode *node)
dfs_find_nearest_dfs(data, child);
}
else {
- //adjust heap size
+ /* adjust heap size */
if ((heap_size >= max_heap_size) &&
ADJUST_MEMORY(default_heap, (void **)&heap, heap_size + 1, &max_heap_size, sizeof(heap[0])) == FALSE)
{
@@ -1296,22 +1324,23 @@ static void bfs_find_nearest(BVHNearestData *data, BVHNode *node)
#endif
-int BLI_bvhtree_find_nearest(BVHTree *tree, const float co[3], BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata)
+int BLI_bvhtree_find_nearest(BVHTree *tree, const float co[3], BVHTreeNearest *nearest,
+ BVHTree_NearestPointCallback callback, void *userdata)
{
- int i;
+ axis_t axis_iter;
BVHNearestData data;
BVHNode *root = tree->nodes[tree->totleaf];
- //init data to search
+ /* init data to search */
data.tree = tree;
data.co = co;
data.callback = callback;
data.userdata = userdata;
- for (i = data.tree->start_axis; i != data.tree->stop_axis; i++) {
- data.proj[i] = dot_v3v3(data.co, KDOP_AXES[i]);
+ for (axis_iter = data.tree->start_axis; axis_iter != data.tree->stop_axis; axis_iter++) {
+ data.proj[axis_iter] = dot_v3v3(data.co, KDOP_AXES[axis_iter]);
}
if (nearest) {
@@ -1343,7 +1372,7 @@ int BLI_bvhtree_find_nearest(BVHTree *tree, const float co[3], BVHTreeNearest *n
/* Determines the distance that the ray must travel to hit the bounding volume of the given node */
-static float ray_nearest_hit(BVHRayCastData *data, const float *bv)
+static float ray_nearest_hit(BVHRayCastData *data, const float bv[6])
{
int i;
@@ -1351,7 +1380,7 @@ static float ray_nearest_hit(BVHRayCastData *data, const float *bv)
for (i = 0; i != 3; i++, bv += 2) {
if (data->ray_dot_axis[i] == 0.0f) {
- //axis aligned ray
+ /* axis aligned ray */
if (data->ray.origin[i] < bv[0] - data->ray.radius ||
data->ray.origin[i] > bv[1] + data->ray.radius)
{
@@ -1466,12 +1495,13 @@ static void iterative_raycast(BVHRayCastData *data, BVHNode *node)
}
else {
node = node->children[0];
- }
+ }
}
}
#endif
-int BLI_bvhtree_ray_cast(BVHTree *tree, const float co[3], const float dir[3], float radius, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
+int BLI_bvhtree_ray_cast(BVHTree *tree, const float co[3], const float dir[3], float radius, BVHTreeRayHit *hit,
+ BVHTree_RayCastCallback callback, void *userdata)
{
int i;
BVHRayCastData data;
@@ -1521,14 +1551,14 @@ int BLI_bvhtree_ray_cast(BVHTree *tree, const float co[3], const float dir[3], f
return data.hit.index;
}
-float BLI_bvhtree_bb_raycast(const float *bv, const float light_start[3], const float light_end[3], float pos[3])
+float BLI_bvhtree_bb_raycast(const float bv[6], const float light_start[3], const float light_end[3], float pos[3])
{
BVHRayCastData data;
float dist = 0.0;
data.hit.dist = FLT_MAX;
- // get light direction
+ /* get light direction */
data.ray.direction[0] = light_end[0] - light_start[0];
data.ray.direction[1] = light_end[1] - light_start[1];
data.ray.direction[2] = light_end[2] - light_start[2];
@@ -1560,7 +1590,7 @@ float BLI_bvhtree_bb_raycast(const float *bv, const float light_start[3], const
typedef struct RangeQueryData {
BVHTree *tree;
const float *center;
- float radius; //squared radius
+ float radius; /* squared radius */
int hits;
@@ -1575,7 +1605,7 @@ static void dfs_range_query(RangeQueryData *data, BVHNode *node)
{
if (node->totnode == 0) {
#if 0 /*UNUSED*/
- //Calculate the node min-coords (if the node was a point then this is the point coordinates)
+ /* Calculate the node min-coords (if the node was a point then this is the point coordinates) */
float co[3];
co[0] = node->bv[0];
co[1] = node->bv[2];
@@ -1588,7 +1618,7 @@ static void dfs_range_query(RangeQueryData *data, BVHNode *node)
float nearest[3];
float dist = calc_nearest_point(data->center, node->children[i], nearest);
if (dist < data->radius) {
- //Its a leaf.. call the callback
+ /* Its a leaf.. call the callback */
if (node->children[i]->totnode == 0) {
data->hits++;
data->callback(data->userdata, node->children[i]->index, dist);
diff --git a/source/blender/blenlib/intern/BLI_kdtree.c b/source/blender/blenlib/intern/BLI_kdtree.c
index 19985c56b84..dd6c25ab6ad 100644
--- a/source/blender/blenlib/intern/BLI_kdtree.c
+++ b/source/blender/blenlib/intern/BLI_kdtree.c
@@ -30,16 +30,12 @@
* \ingroup bli
*/
-
-
#include "MEM_guardedalloc.h"
#include "BLI_math.h"
#include "BLI_kdtree.h"
+#include "BLI_utildefines.h"
-#ifndef SWAP
-# define SWAP(type, a, b) { type sw_ap; sw_ap = (a); (a) = (b); (b) = sw_ap; } (void)0
-#endif
typedef struct KDTreeNode {
struct KDTreeNode *left, *right;
@@ -132,7 +128,7 @@ void BLI_kdtree_balance(KDTree *tree)
tree->root = kdtree_balance(tree->nodes, tree->totnode, 0);
}
-static float squared_distance(const float v2[3], const float v1[3], const float *UNUSED(n1), const float *n2)
+static float squared_distance(const float v2[3], const float v1[3], const float UNUSED(n1[3]), const float n2[3])
{
float d[3], dist;
@@ -152,7 +148,7 @@ static float squared_distance(const float v2[3], const float v1[3], const float
return dist;
}
-int BLI_kdtree_find_nearest(KDTree *tree, float *co, float *nor, KDTreeNearest *nearest)
+int BLI_kdtree_find_nearest(KDTree *tree, const float co[3], const float nor[3], KDTreeNearest *nearest)
{
KDTreeNode *root, *node, *min_node;
KDTreeNode **stack, *defaultstack[100];
diff --git a/source/blender/blenlib/intern/DLRB_tree.c b/source/blender/blenlib/intern/DLRB_tree.c
index 930ab4fc400..688372b3a28 100644
--- a/source/blender/blenlib/intern/DLRB_tree.c
+++ b/source/blender/blenlib/intern/DLRB_tree.c
@@ -364,7 +364,7 @@ static void rotate_right(DLRBT_Tree *tree, DLRBT_Node *root)
root_slot = &root->parent->right;
}
else
- root_slot = ((DLRBT_Node **)&tree->root); /* &((DLRBT_Node*)tree->root); */
+ root_slot = ((DLRBT_Node **)&tree->root); /* &((DLRBT_Node *)tree->root); */
/* - pivot's right child becomes root's left child
* - root now becomes pivot's right child
@@ -502,7 +502,7 @@ void BLI_dlrbTree_insert(DLRBT_Tree *tree, DLRBT_Node *node)
/* ----- */
/* Add the given data to the tree, and return the node added */
-// NOTE: for duplicates, the update_cb is called (if available), and the existing node is returned
+/* NOTE: for duplicates, the update_cb is called (if available), and the existing node is returned */
DLRBT_Node *BLI_dlrbTree_add(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb,
DLRBT_NAlloc_FP new_cb, DLRBT_NUpdate_FP update_cb, void *data)
{
diff --git a/source/blender/blenlib/intern/boxpack2d.c b/source/blender/blenlib/intern/boxpack2d.c
index 5da719cd500..8a97fdcab67 100644
--- a/source/blender/blenlib/intern/boxpack2d.c
+++ b/source/blender/blenlib/intern/boxpack2d.c
@@ -73,7 +73,9 @@ typedef struct BoxVert {
((b)->v[BR]->x = (b)->v[TR]->x)
#define UPDATE_V34Y(b) ((b)->v[TL]->y = (b)->v[TR]->y); \
((b)->v[BR]->y = (b)->v[BL]->y)
-#define UPDATE_V34(b) UPDATE_V34X(b); UPDATE_V34Y(b)
+
+/* UNUSED */
+// #define UPDATE_V34(b) UPDATE_V34X(b); UPDATE_V34Y(b)
#define SET_BOXLEFT(b, f) (b)->v[TR]->x = f + (b)->w; \
(b)->v[BL]->x = f; \
@@ -93,8 +95,8 @@ typedef struct BoxVert {
BOXRIGHT(b1) - EPSILON <= BOXLEFT(b2) || \
BOXTOP(b1) - EPSILON <= BOXBOTTOM(b2))
-#define MIN2(x, y) ((x) < (y) ? (x) : (y))
-#define MAX2(x, y) ((x) > (y) ? (x) : (y))
+/* compiler should inline */
+static float max_ff(const float a, const float b) { return b > a ? b : a; }
#if 0
#define BOXDEBUG(b) \
@@ -131,8 +133,8 @@ static int vertex_sort(const void *p1, const void *p2)
v1 = vertarray + ((int *)p1)[0];
v2 = vertarray + ((int *)p2)[0];
- a1 = MAX2(v1->x + box_width, v1->y + box_height);
- a2 = MAX2(v2->x + box_width, v2->y + box_height);
+ a1 = max_ff(v1->x + box_width, v1->y + box_height);
+ a2 = max_ff(v2->x + box_width, v2->y + box_height);
/* sort largest to smallest */
if (a1 > a2) return 1;
@@ -312,8 +314,8 @@ void BLI_box_pack_2D(BoxPack *boxarray, const int len, float *tot_width, float *
if (!isect) {
/* maintain the total width and height */
- (*tot_width) = MAX2(BOXRIGHT(box), (*tot_width));
- (*tot_height) = MAX2(BOXTOP(box), (*tot_height));
+ (*tot_width) = max_ff(BOXRIGHT(box), (*tot_width));
+ (*tot_height) = max_ff(BOXTOP(box), (*tot_height));
/* Place the box */
vert->free &= ~quad_flags[j];
diff --git a/source/blender/blenlib/intern/bpath.c b/source/blender/blenlib/intern/bpath.c
index be1f4eb3a35..8ae2b941fa8 100644
--- a/source/blender/blenlib/intern/bpath.c
+++ b/source/blender/blenlib/intern/bpath.c
@@ -85,7 +85,7 @@ static int checkMissingFiles_visit_cb(void *userdata, char *UNUSED(path_dst), co
ReportList *reports = (ReportList *)userdata;
if (!BLI_exists(path_src)) {
- BKE_reportf(reports, RPT_WARNING, "Path Not Found \"%s\"", path_src);
+ BKE_reportf(reports, RPT_WARNING, "Path '%s' not found", path_src);
}
return FALSE;
@@ -122,7 +122,7 @@ static int makeFilesRelative_visit_cb(void *userdata, char *path_dst, const char
data->count_changed++;
}
else {
- BKE_reportf(data->reports, RPT_WARNING, "Path cant be made relative \"%s\"", path_src);
+ BKE_reportf(data->reports, RPT_WARNING, "Path '%s' cannot be made relative", path_src);
data->count_failed++;
}
return TRUE;
@@ -144,7 +144,7 @@ void BLI_bpath_relative_convert(Main *bmain, const char *basedir, ReportList *re
BLI_bpath_traverse_main(bmain, makeFilesRelative_visit_cb, 0, (void *)&data);
BKE_reportf(reports, data.count_failed ? RPT_WARNING : RPT_INFO,
- "Total files %d|Changed %d|Failed %d",
+ "Total files %d | Changed %d | Failed %d",
data.count_tot, data.count_changed, data.count_failed);
}
@@ -164,7 +164,7 @@ static int makeFilesAbsolute_visit_cb(void *userdata, char *path_dst, const char
data->count_changed++;
}
else {
- BKE_reportf(data->reports, RPT_WARNING, "Path cant be made absolute \"%s\"", path_src);
+ BKE_reportf(data->reports, RPT_WARNING, "Path '%s' cannot be made absolute", path_src);
data->count_failed++;
}
return TRUE;
@@ -187,13 +187,13 @@ void BLI_bpath_absolute_convert(Main *bmain, const char *basedir, ReportList *re
BLI_bpath_traverse_main(bmain, makeFilesAbsolute_visit_cb, 0, (void *)&data);
BKE_reportf(reports, data.count_failed ? RPT_WARNING : RPT_INFO,
- "Total files %d|Changed %d|Failed %d",
+ "Total files %d | Changed %d | Failed %d",
data.count_tot, data.count_changed, data.count_failed);
}
/**
* find this file recursively, use the biggest file so thumbnails don't get used by mistake
- * \param filename_new: the path will be copied here, caller must initialize as empyu string.
+ * \param filename_new: the path will be copied here, caller must initialize as empty string.
* \param dirname: subdir to search
* \param filename: set this filename
* \param filesize: filesize for the file
@@ -279,13 +279,13 @@ static int findMissingFiles_visit_cb(void *userdata, char *path_dst, const char
if (filesize == -1) { /* could not open dir */
BKE_reportf(data->reports, RPT_WARNING,
- "Could open directory \"%s\"",
+ "Could not open directory '%s'",
BLI_path_basename(data->searchdir));
return FALSE;
}
else if (found == FALSE) {
BKE_reportf(data->reports, RPT_WARNING,
- "Could not find \"%s\" in \"%s\"",
+ "Could not find '%s' in '%s'",
BLI_path_basename((char *)path_src), data->searchdir);
return FALSE;
}
@@ -544,8 +544,8 @@ void BLI_bpath_traverse_id(Main *bmain, ID *id, BPathVisitor visit_cb, const int
case ID_ME:
{
Mesh *me = (Mesh *)id;
- if (me->fdata.external) {
- rewrite_path_fixed(me->fdata.external->filename, visit_cb, absbase, bpath_user_data);
+ if (me->ldata.external) {
+ rewrite_path_fixed(me->ldata.external->filename, visit_cb, absbase, bpath_user_data);
}
}
break;
diff --git a/source/blender/blenlib/intern/edgehash.c b/source/blender/blenlib/intern/edgehash.c
index d58ccbbd48e..4fb48d19239 100644
--- a/source/blender/blenlib/intern/edgehash.c
+++ b/source/blender/blenlib/intern/edgehash.c
@@ -108,7 +108,7 @@ void BLI_edgehash_insert(EdgeHash *eh, unsigned int v0, unsigned int v1, void *v
eh->buckets[hash] = e;
if (++eh->nentries > eh->nbuckets * 3) {
- EdgeEntry *e, **old = eh->buckets;
+ EdgeEntry **old = eh->buckets;
int i, nold = eh->nbuckets;
eh->nbuckets = _ehash_hashsizes[++eh->cursize];
diff --git a/source/blender/blenlib/intern/fileops.c b/source/blender/blenlib/intern/fileops.c
index f3107b565b9..883cdfde426 100644
--- a/source/blender/blenlib/intern/fileops.c
+++ b/source/blender/blenlib/intern/fileops.c
@@ -42,6 +42,9 @@
#include "zlib.h"
#ifdef WIN32
+#ifdef __MINGW32__
+#include <ctype.h>
+#endif
#include <io.h>
# include "BLI_winstuff.h"
# include "BLI_callbacks.h"
@@ -137,6 +140,8 @@ char *BLI_file_ungzip_to_mem(const char *from_file, int *size_r)
}
else break;
}
+
+ gzclose(gzfile);
if (size == 0) {
MEM_freeN(mem);
@@ -207,6 +212,22 @@ FILE *BLI_fopen(const char *filename, const char *mode)
return ufopen(filename, mode);
}
+void BLI_get_short_name(char short_name[256], const char *filename)
+{
+ wchar_t short_name_16[256];
+ int i = 0;
+
+ UTF16_ENCODE(filename);
+
+ GetShortPathNameW(filename_16, short_name_16, 256);
+
+ for (i = 0; i < 256; i++) {
+ short_name[i] = (char)short_name_16[i];
+ }
+
+ UTF16_UN_ENCODE(filename);
+}
+
void *BLI_gzopen(const char *filename, const char *mode)
{
gzFile gzfile;
@@ -215,25 +236,15 @@ void *BLI_gzopen(const char *filename, const char *mode)
return 0;
}
else {
- wchar_t short_name_16[256];
char short_name[256];
- int i = 0;
/* xxx Creates file before transcribing the path */
if (mode[0] == 'w')
fclose(ufopen(filename, "a"));
- UTF16_ENCODE(filename);
-
- GetShortPathNameW(filename_16, short_name_16, 256);
-
- for (i = 0; i < 256; i++) {
- short_name[i] = (char)short_name_16[i];
- }
+ BLI_get_short_name(short_name, filename);
gzfile = gzopen(short_name, mode);
-
- UTF16_UN_ENCODE(filename);
}
return gzfile;
@@ -341,7 +352,7 @@ void BLI_dir_create_recursive(const char *dirname)
{
char *lslash;
char tmp[MAXPATHLEN];
-
+
/* First remove possible slash at the end of the dirname.
* This routine otherwise tries to create
* blah1/blah2/ (with slash) after creating
@@ -349,23 +360,29 @@ void BLI_dir_create_recursive(const char *dirname)
BLI_strncpy(tmp, dirname, sizeof(tmp));
lslash = BLI_last_slash(tmp);
-
- if (lslash == tmp + strlen(tmp) - 1) {
- *lslash = 0;
+
+ if (lslash && (*(lslash + 1) == '\0')) {
+ *lslash = '\0';
}
-
+
+ /* check special case "c:\foo", don't try create "c:", harmless but prints an error below */
+ if (isalpha(tmp[0]) && (tmp[1] == ':') && tmp[2] == '\0') return;
+
if (BLI_exists(tmp)) return;
lslash = BLI_last_slash(tmp);
+
if (lslash) {
/* Split about the last slash and recurse */
*lslash = 0;
BLI_dir_create_recursive(tmp);
}
-
- if (dirname[0]) /* patch, this recursive loop tries to create a nameless directory */
- if (umkdir(dirname) == -1)
+
+ if (dirname[0]) { /* patch, this recursive loop tries to create a nameless directory */
+ if (umkdir(dirname) == -1) {
printf("Unable to create directory %s\n", dirname);
+ }
+ }
}
int BLI_rename(const char *from, const char *to)
@@ -508,8 +525,9 @@ static int recursive_operation(const char *startfrom, const char *startto, Recur
}
if (ret != 0) {
- while (i < n)
- free(dirlist[i]);
+ while (i < n) {
+ free(dirlist[i++]);
+ }
break;
}
}
diff --git a/source/blender/blenlib/intern/freetypefont.c b/source/blender/blenlib/intern/freetypefont.c
index 597a645eb9c..0a87316aa81 100644
--- a/source/blender/blenlib/intern/freetypefont.c
+++ b/source/blender/blenlib/intern/freetypefont.c
@@ -33,8 +33,8 @@
*/
-#ifdef WIN32
-#pragma warning (disable:4244)
+#ifdef _MSC_VER
+# pragma warning (disable:4244)
#endif
#include <ft2build.h>
@@ -58,9 +58,6 @@
#include "DNA_packedFile_types.h"
#include "DNA_curve_types.h"
-#define myMIN_ASCII 32
-#define myMAX_ASCII 255
-
/* local variables */
static FT_Library library;
static FT_Error err;
@@ -274,7 +271,7 @@ static void freetypechar_to_vchar(FT_Face face, FT_ULong charcode, VFontData *vf
(len_squared_v2v2(bezt->vec[1], bezt->vec[2]) > 0.0001f * 0.0001f) &&
(len_squared_v2v2(bezt->vec[0], bezt->vec[2]) > 0.0002f * 0.0001f) &&
(len_squared_v2v2(bezt->vec[0], bezt->vec[2]) >
- maxf(len_squared_v2v2(bezt->vec[0], bezt->vec[1]),
+ max_ff(len_squared_v2v2(bezt->vec[0], bezt->vec[1]),
len_squared_v2v2(bezt->vec[1], bezt->vec[2]))))
{
bezt->h1 = bezt->h2 = HD_ALIGN;
@@ -285,7 +282,7 @@ static void freetypechar_to_vchar(FT_Face face, FT_ULong charcode, VFontData *vf
}
}
if (npoints) MEM_freeN(npoints);
- if (onpoints) MEM_freeN(onpoints);
+ if (onpoints) MEM_freeN(onpoints);
}
}
@@ -407,7 +404,7 @@ static VFontData *objfnt_to_ftvfontdata(PackedFile *pf)
lcode = charcode;
}
- return vfd;
+ return vfd;
}
@@ -476,10 +473,10 @@ VFontData *BLI_vfontdata_from_freetypefont(PackedFile *pf)
VFontData *vfd = NULL;
int success = 0;
- //init Freetype
+ /* init Freetype */
err = FT_Init_FreeType(&library);
if (err) {
- //XXX error("Failed to load the Freetype font library");
+ /* XXX error("Failed to load the Freetype font library"); */
return NULL;
}
@@ -489,7 +486,7 @@ VFontData *BLI_vfontdata_from_freetypefont(PackedFile *pf)
vfd = objfnt_to_ftvfontdata(pf);
}
- //free Freetype
+ /* free Freetype */
FT_Done_FreeType(library);
return vfd;
@@ -521,16 +518,16 @@ int BLI_vfontchar_from_freetypefont(VFont *vfont, unsigned long character)
#if 0
-// Freetype2 Outline struct
+/* Freetype2 Outline struct */
typedef struct FT_Outline_
- {
+{
short n_contours; /* number of contours in glyph */
short n_points; /* number of points in the glyph */
- FT_Vector* points; /* the outline's points */
- char* tags; /* the points flags */
- short* contours; /* the contour end points */
+ FT_Vector *points; /* the outline's points */
+ char *tags; /* the points flags */
+ short *contours; /* the contour end points */
int flags; /* outline masks */
} FT_Outline;
diff --git a/source/blender/blenlib/intern/graph.c b/source/blender/blenlib/intern/graph.c
index 51d7cb58b00..a93bbd97b51 100644
--- a/source/blender/blenlib/intern/graph.c
+++ b/source/blender/blenlib/intern/graph.c
@@ -353,12 +353,12 @@ int BLI_isGraphCyclic(BGraph *graph)
/* Mark all nodes as not visited */
BLI_flagNodes(graph, 0);
- /* detectCycles in subgraphs */
+ /* detectCycles in subgraphs */
for (node = graph->nodes.first; node && value == 0; node = node->next) {
/* only for nodes in subgraphs that haven't been visited yet */
if (node->flag == 0) {
value = value || detectCycle(node, NULL);
- }
+ }
}
return value;
@@ -639,11 +639,11 @@ static void handleRadialSymmetry(BGraph *graph, BNode *root_node, int depth, flo
/* if not dispatching already and on last arc
* Dispatch using current arc as last
- * */
+ */
if (dispatch == 0 && i == total - 1) {
last = i;
dispatch = 1;
- }
+ }
if (dispatch) {
int sub_total = last - first + 1;
@@ -796,7 +796,7 @@ static void markdownSecondarySymmetry(BGraph *graph, BNode *node, int depth, int
/* count the number of branches in this symmetry group
* and determinate the axis of symmetry
- * */
+ */
for (i = 0; i < node->degree; i++) {
BArc *connectedArc = node->arcs[i];
@@ -821,7 +821,7 @@ static void markdownSecondarySymmetry(BGraph *graph, BNode *node, int depth, int
handleRadialSymmetry(graph, node, depth, axis, limit);
}
- /* markdown secondary symetries */
+ /* markdown secondary symetries */
for (i = 0; i < node->degree; i++) {
BArc *connectedArc = node->arcs[i];
@@ -836,7 +836,7 @@ static void markdownSymmetryArc(BGraph *graph, BArc *arc, BNode *node, int level
{
int i;
- /* if arc is null, we start straight from a node */
+ /* if arc is null, we start straight from a node */
if (arc) {
arc->symmetry_level = level;
@@ -875,7 +875,7 @@ static void markdownSymmetryArc(BGraph *graph, BArc *arc, BNode *node, int level
/* not on the symmetry axis */
issymmetryAxis = 0;
break;
- }
+ }
}
}
diff --git a/source/blender/blenlib/intern/lasso.c b/source/blender/blenlib/intern/lasso.c
index 7df4da80e16..5cd8bb813a1 100644
--- a/source/blender/blenlib/intern/lasso.c
+++ b/source/blender/blenlib/intern/lasso.c
@@ -37,7 +37,7 @@
#include "BLI_lasso.h" /* own include */
-void BLI_lasso_boundbox(rcti *rect, int mcords[][2], short moves)
+void BLI_lasso_boundbox(rcti *rect, const int mcords[][2], const short moves)
{
short a;
@@ -53,14 +53,14 @@ void BLI_lasso_boundbox(rcti *rect, int mcords[][2], short moves)
}
-int BLI_lasso_is_point_inside(int mcords[][2], short moves,
+int BLI_lasso_is_point_inside(const int mcords[][2], const short moves,
const int sx, const int sy,
const int error_value)
{
/* we do the angle rule, define that all added angles should be about zero or (2 * PI) */
float angletot = 0.0, dot, ang, cross, fp1[2], fp2[2];
int a;
- int *p1, *p2;
+ const int *p1, *p2;
if (sx == error_value) {
return 0;
@@ -100,7 +100,7 @@ int BLI_lasso_is_point_inside(int mcords[][2], short moves,
}
/* edge version for lasso select. we assume boundbox check was done */
-int BLI_lasso_is_edge_inside(int mcords[][2], short moves,
+int BLI_lasso_is_edge_inside(const int mcords[][2], const short moves,
int x0, int y0, int x1, int y1,
const int error_value)
{
diff --git a/source/blender/blenlib/intern/listbase.c b/source/blender/blenlib/intern/listbase.c
index ad718ed8e11..9f6f409c473 100644
--- a/source/blender/blenlib/intern/listbase.c
+++ b/source/blender/blenlib/intern/listbase.c
@@ -141,7 +141,7 @@ void BLI_insertlink(ListBase *listbase, void *vprevlink, void *vnewlink)
if (listbase == NULL) return;
/* empty list */
- if (listbase->first == NULL) {
+ if (listbase->first == NULL) {
listbase->first = newlink;
listbase->last = newlink;
@@ -149,7 +149,7 @@ void BLI_insertlink(ListBase *listbase, void *vprevlink, void *vnewlink)
}
/* insert before first element */
- if (prevlink == NULL) {
+ if (prevlink == NULL) {
newlink->next = listbase->first;
newlink->prev = NULL;
newlink->next->prev = newlink;
@@ -203,14 +203,14 @@ void BLI_insertlinkafter(ListBase *listbase, void *vprevlink, void *vnewlink)
if (listbase == NULL) return;
/* empty list */
- if (listbase->first == NULL) {
+ if (listbase->first == NULL) {
listbase->first = newlink;
listbase->last = newlink;
return;
}
/* insert at head of list */
- if (prevlink == NULL) {
+ if (prevlink == NULL) {
newlink->prev = NULL;
newlink->next = listbase->first;
((Link *)listbase->first)->prev = newlink;
@@ -238,14 +238,14 @@ void BLI_insertlinkbefore(ListBase *listbase, void *vnextlink, void *vnewlink)
if (listbase == NULL) return;
/* empty list */
- if (listbase->first == NULL) {
+ if (listbase->first == NULL) {
listbase->first = newlink;
listbase->last = newlink;
return;
}
/* insert at end of list */
- if (nextlink == NULL) {
+ if (nextlink == NULL) {
newlink->prev = listbase->last;
newlink->next = NULL;
((Link *)listbase->last)->next = newlink;
diff --git a/source/blender/blenlib/intern/math_base_inline.c b/source/blender/blenlib/intern/math_base_inline.c
index 97fc431d8fa..f27da759482 100644
--- a/source/blender/blenlib/intern/math_base_inline.c
+++ b/source/blender/blenlib/intern/math_base_inline.c
@@ -59,34 +59,34 @@ MINLINE float saacos(float fac)
{
if (fac <= -1.0f) return (float)M_PI;
else if (fac >= 1.0f) return 0.0;
- else return (float)acos(fac);
+ else return acosf(fac);
}
MINLINE float saasin(float fac)
{
if (fac <= -1.0f) return (float)-M_PI / 2.0f;
else if (fac >= 1.0f) return (float)M_PI / 2.0f;
- else return (float)asin(fac);
+ else return asinf(fac);
}
MINLINE float sasqrt(float fac)
{
if (fac <= 0.0f) return 0.0f;
- return (float)sqrt(fac);
+ return sqrtf(fac);
}
MINLINE float saacosf(float fac)
{
if (fac <= -1.0f) return (float)M_PI;
else if (fac >= 1.0f) return 0.0f;
- else return (float)acosf(fac);
+ else return acosf(fac);
}
MINLINE float saasinf(float fac)
{
if (fac <= -1.0f) return (float)-M_PI / 2.0f;
else if (fac >= 1.0f) return (float)M_PI / 2.0f;
- else return (float)asinf(fac);
+ else return asinf(fac);
}
MINLINE float sasqrtf(float fac)
@@ -139,20 +139,20 @@ MINLINE int power_of_2_min_i(int n)
return n;
}
-MINLINE float minf(float a, float b)
+MINLINE float min_ff(float a, float b)
{
return (a < b) ? a : b;
}
-MINLINE float maxf(float a, float b)
+MINLINE float max_ff(float a, float b)
{
return (a > b) ? a : b;
}
-MINLINE int mini(int a, int b)
+MINLINE int min_ii(int a, int b)
{
return (a < b) ? a : b;
}
-MINLINE int maxi(int a, int b)
+MINLINE int max_ii(int a, int b)
{
return (b < a) ? a : b;
}
diff --git a/source/blender/blenlib/intern/math_color_inline.c b/source/blender/blenlib/intern/math_color_inline.c
index 6b90cbfe9c3..f520b2318e5 100644
--- a/source/blender/blenlib/intern/math_color_inline.c
+++ b/source/blender/blenlib/intern/math_color_inline.c
@@ -273,5 +273,20 @@ MINLINE float rgb_to_luma_y(const float rgb[3])
return 0.212671f * rgb[0] + 0.71516f * rgb[1] + 0.072169f * rgb[2];
}
+MINLINE int compare_rgb_uchar(const unsigned char col_a[3], const unsigned char col_b[3], const int limit)
+{
+ int r = (int)col_a[0] - (int)col_b[0];
+ if (ABS(r) < limit) {
+ int g = (int)col_a[1] - (int)col_b[1];
+ if (ABS(g) < limit) {
+ int b = (int)col_a[2] - (int)col_b[2];
+ if (ABS(b) < limit) {
+ return 1;
+ }
+ }
+ }
+
+ return 0;
+}
#endif /* __MATH_COLOR_INLINE_C__ */
diff --git a/source/blender/blenlib/intern/math_geom.c b/source/blender/blenlib/intern/math_geom.c
index 53e9a6b66cb..e10229f11da 100644
--- a/source/blender/blenlib/intern/math_geom.c
+++ b/source/blender/blenlib/intern/math_geom.c
@@ -404,8 +404,8 @@ int isect_seg_seg_v2_point(const float v1[2], const float v2[2], const float v3[
if (u > u2) SWAP(float, u, u2);
if (u > 1.0f + eps || u2 < -eps) return -1; /* non-ovlerlapping segments */
- else if (maxf(0.0f, u) == minf(1.0f, u2)) { /* one common point: can return result */
- interp_v2_v2v2(vi, v1, v2, maxf(0, u));
+ else if (max_ff(0.0f, u) == min_ff(1.0f, u2)) { /* one common point: can return result */
+ interp_v2_v2v2(vi, v1, v2, max_ff(0, u));
return 1;
}
}
@@ -560,7 +560,8 @@ int isect_line_sphere_v2(const float l1[2], const float l2[2],
}
}
-/*
+/**
+ * \return
* -1: collinear
* 1: intersection
*/
@@ -758,6 +759,10 @@ int isect_ray_tri_v3(const float p1[3], const float d[3],
return 1;
}
+/**
+ * if clip is nonzero, will only return true if lambda is >= 0.0
+ * (i.e. intersection point is along positive d)
+ */
int isect_ray_plane_v3(const float p1[3], const float d[3],
const float v0[3], const float v1[3], const float v2[3],
float *r_lambda, const int clip)
@@ -876,6 +881,16 @@ int isect_ray_tri_threshold_v3(const float p1[3], const float d[3],
return 1;
}
+/**
+ * Intersect line/plane, optionally treat line as directional (like a ray) with the no_flip argument.
+ *
+ * \param out The intersection point.
+ * \param l1 The first point of the line.
+ * \param l2 The second point of the line.
+ * \param plane_co A point on the plane to intersect with.
+ * \param plane_no The direction of the plane (does not need to be normalized).
+ * \param no_flip When true, the intersection point will always be from l1 to l2, even if this is not on the plane.
+ */
int isect_line_plane_v3(float out[3],
const float l1[3], const float l2[3],
const float plane_co[3], const float plane_no[3], const short no_flip)
@@ -921,7 +936,20 @@ int isect_line_plane_v3(float out[3],
}
}
-/* note: return normal isn't unit length */
+/**
+ * Intersect two planes, return a point on the intersection and a vector
+ * that runs on the direction of the intersection.
+ * Return error code is the same as 'isect_line_line_v3'.
+ *
+ * \param r_isect_co The resulting intersection point.
+ * \param r_isect_no The resulting vector of the intersection.
+ * \param plane_a_co The point on the first plane.
+ * \param plane_a_no The normal of the first plane.
+ * \param plane_b_co The point on the second plane.
+ * \param plane_b_no The normal of the second plane.
+ *
+ * \note return normal isn't unit length
+ */
void isect_plane_plane_v3(float r_isect_co[3], float r_isect_no[3],
const float plane_a_co[3], const float plane_a_no[3],
const float plane_b_co[3], const float plane_b_no[3])
@@ -939,10 +967,10 @@ void isect_plane_plane_v3(float r_isect_co[3], float r_isect_no[3],
/* "Improved Collision detection and Response" */
static int getLowestRoot(const float a, const float b, const float c, const float maxR, float *root)
{
- // Check if a solution exists
+ /* Check if a solution exists */
float determinant = b * b - 4.0f * a * c;
- // If determinant is negative it means no solutions.
+ /* If determinant is negative it means no solutions. */
if (determinant >= 0.0f) {
/* calculate the two roots: (if determinant == 0 then
* x1==x2 but lets disregard that slight optimization) */
@@ -950,24 +978,24 @@ static int getLowestRoot(const float a, const float b, const float c, const floa
float r1 = (-b - sqrtD) / (2.0f * a);
float r2 = (-b + sqrtD) / (2.0f * a);
- // Sort so x1 <= x2
+ /* Sort so x1 <= x2 */
if (r1 > r2)
SWAP(float, r1, r2);
- // Get lowest root:
+ /* Get lowest root: */
if (r1 > 0.0f && r1 < maxR) {
*root = r1;
return 1;
}
- // It is possible that we want x2 - this can happen
- // if x1 < 0
+ /* It is possible that we want x2 - this can happen */
+ /* if x1 < 0 */
if (r2 > 0.0f && r2 < maxR) {
*root = r2;
return 1;
}
}
- // No (valid) solutions
+ /* No (valid) solutions */
return 0;
}
@@ -1080,7 +1108,7 @@ int isect_sweeping_sphere_tri_v3(const float p1[3], const float p2[3], const flo
}
/*---test edges---*/
- sub_v3_v3v3(e3, v2, v1); //wasnt yet calculated
+ sub_v3_v3v3(e3, v2, v1); /* wasnt yet calculated */
/*e1*/
@@ -1206,11 +1234,12 @@ int isect_axial_line_tri_v3(const int axis, const float p1[3], const float p2[3]
return 1;
}
-/* Returns the number of point of interests
+/**
+ * \return The number of point of interests
* 0 - lines are colinear
* 1 - lines are coplanar, i1 is set to intersection
* 2 - i1 and i2 are the nearest points on line 1 (v1, v2) and line 2 (v3, v4) respectively
- * */
+ */
int isect_line_line_v3(const float v1[3], const float v2[3], const float v3[3], const float v4[3], float i1[3], float i2[3])
{
float a[3], b[3], c[3], ab[3], cb[3], dir1[3], dir2[3];
@@ -1344,7 +1373,7 @@ void isect_ray_aabb_initialize(IsectRayAABBData *data, const float ray_start[3],
/* Adapted from http://www.gamedev.net/community/forums/topic.asp?topic_id=459973 */
int isect_ray_aabb(const IsectRayAABBData *data, const float bb_min[3],
- const float bb_max[3], float *tmin_out)
+ const float bb_max[3], float *tmin_out)
{
float bbox[2][3];
float tmin, tmax, tymin, tymax, tzmin, tzmax;
@@ -1387,7 +1416,7 @@ int isect_ray_aabb(const IsectRayAABBData *data, const float bb_min[3],
}
/* find closest point to p on line through l1,l2 and return lambda,
- * where (0 <= lambda <= 1) when cp is in the line segement l1,l2
+ * where (0 <= lambda <= 1) when cp is in the line segment l1,l2
*/
float closest_to_line_v3(float cp[3], const float p[3], const float l1[3], const float l2[3])
{
@@ -1429,7 +1458,7 @@ float line_point_factor_v2(const float p[2], const float l1[2], const float l2[2
return (dot_v2v2(u, h) / dot_v2v2(u, u));
}
-/* ensyre the distance between these points is no greater then 'dist'
+/* ensure the distance between these points is no greater then 'dist'
* if it is, scale then both into the center */
void limit_dist_v3(float v1[3], float v2[3], const float dist)
{
@@ -1587,7 +1616,7 @@ void isect_point_face_uv_v2(const int isquad,
}
}
-#if 0 // XXX this version used to be used in isect_point_tri_v2_int() and was called IsPointInTri2D
+#if 0 /* XXX this version used to be used in isect_point_tri_v2_int() and was called IsPointInTri2D */
int isect_point_tri_v2(float pt[2], float v1[2], float v2[2], float v3[2])
{
@@ -1672,7 +1701,7 @@ static int point_in_slice(const float p[3], const float v1[3], const float l1[3]
* the room inside usually is rather small compared to R3 though still infinite
* useful for restricting (speeding up) searches
* e.g. all points of triangular prism are within the intersection of 3 'slices'
- * onother trivial case : cube
+ * another trivial case : cube
* but see a 'spat' which is a deformed cube with paired parallel planes needs only 3 slices too
*/
float h, rp[3], cp[3], q[3];
@@ -1777,7 +1806,7 @@ void plot_line_v2v2i(const int p1[2], const int p2[2], int (*callback)(int, int,
signed char ix;
signed char iy;
- // if x1 == x2 or y1 == y2, then it does not matter what we set here
+ /* if x1 == x2 or y1 == y2, then it does not matter what we set here */
int delta_x = (x2 > x1 ? (ix = 1, x2 - x1) : (ix = -1, x1 - x2)) << 1;
int delta_y = (y2 > y1 ? (iy = 1, y2 - y1) : (iy = -1, y1 - y2)) << 1;
@@ -1786,7 +1815,7 @@ void plot_line_v2v2i(const int p1[2], const int p2[2], int (*callback)(int, int,
}
if (delta_x >= delta_y) {
- // error may go below zero
+ /* error may go below zero */
int error = delta_y - (delta_x >> 1);
while (x1 != x2) {
@@ -1795,9 +1824,9 @@ void plot_line_v2v2i(const int p1[2], const int p2[2], int (*callback)(int, int,
y1 += iy;
error -= delta_x;
}
- // else do nothing
+ /* else do nothing */
}
- // else do nothing
+ /* else do nothing */
x1 += ix;
error += delta_y;
@@ -1808,7 +1837,7 @@ void plot_line_v2v2i(const int p1[2], const int p2[2], int (*callback)(int, int,
}
}
else {
- // error may go below zero
+ /* error may go below zero */
int error = delta_x - (delta_y >> 1);
while (y1 != y2) {
@@ -1817,9 +1846,9 @@ void plot_line_v2v2i(const int p1[2], const int p2[2], int (*callback)(int, int,
x1 += ix;
error -= delta_y;
}
- // else do nothing
+ /* else do nothing */
}
- // else do nothing
+ /* else do nothing */
y1 += iy;
error += delta_x;
@@ -1992,8 +2021,8 @@ void barycentric_weights_v2_quad(const float v1[2], const float v2[2], const flo
const float co[2], float w[4])
{
/* note: fabsf() here is not needed for convex quads (and not used in interp_weights_poly_v2).
- * but in the case of concave/bowtie quads for the mask rasterizer it gives unreliable results
- * without adding absf(). If this becomes an issue for more general useage we could have
+ * but in the case of concave/bow-tie quads for the mask rasterizer it gives unreliable results
+ * without adding absf(). If this becomes an issue for more general usage we could have
* this optional or use a different function - Campbell */
#define MEAN_VALUE_HALF_TAN_V2(_area, i1, i2) \
((_area = cross_v2v2(dirs[i1], dirs[i2])) != 0.0f ? \
@@ -2323,18 +2352,18 @@ void resolve_quad_uv(float r_uv[2], const float st[2], const float st0[2], const
(st2[0] * st3[1] - st2[1] * st3[0]) + (st3[0] * st0[1] - st3[1] * st0[0]);
/* X is 2D cross product (determinant)
- * A= (p0-p) X (p0-p3)*/
+ * A = (p0 - p) X (p0 - p3)*/
const double a = (st0[0] - st[0]) * (st0[1] - st3[1]) - (st0[1] - st[1]) * (st0[0] - st3[0]);
- /* B= ( (p0-p) X (p1-p2) + (p1-p) X (p0-p3) ) / 2 */
- const double b = 0.5 * (((st0[0] - st[0]) * (st1[1] - st2[1]) - (st0[1] - st[1]) * (st1[0] - st2[0])) +
- ((st1[0] - st[0]) * (st0[1] - st3[1]) - (st1[1] - st[1]) * (st0[0] - st3[0])));
+ /* B = ( (p0 - p) X (p1 - p2) + (p1 - p) X (p0 - p3) ) / 2 */
+ const double b = 0.5 * (double)(((st0[0] - st[0]) * (st1[1] - st2[1]) - (st0[1] - st[1]) * (st1[0] - st2[0])) +
+ ((st1[0] - st[0]) * (st0[1] - st3[1]) - (st1[1] - st[1]) * (st0[0] - st3[0])));
/* C = (p1-p) X (p1-p2) */
const double fC = (st1[0] - st[0]) * (st1[1] - st2[1]) - (st1[1] - st[1]) * (st1[0] - st2[0]);
const double denom = a - 2 * b + fC;
- // clear outputs
+ /* clear outputs */
zero_v2(r_uv);
if (IS_ZERO(denom) != 0) {
@@ -2364,7 +2393,7 @@ void resolve_quad_uv(float r_uv[2], const float st[2], const float st0[2], const
}
if (IS_ZERO(denom) == 0)
- r_uv[1] = (float)(((1.0f - r_uv[0]) * (st0[i] - st[i]) + r_uv[0] * (st1[i] - st[i])) / denom);
+ r_uv[1] = (float)((double)((1.0f - r_uv[0]) * (st0[i] - st[i]) + r_uv[0] * (st1[i] - st[i])) / denom);
}
}
@@ -2650,7 +2679,7 @@ void accumulate_vertex_normals(float n1[3], float n2[3], float n3[3],
const float *cur_edge = vdiffs[i];
const float fac = saacos(-dot_v3v3(cur_edge, prev_edge));
- // accumulate
+ /* accumulate */
madd_v3_v3fl(vn[i], f_no, fac);
prev_edge = cur_edge;
}
@@ -2691,50 +2720,6 @@ void accumulate_vertex_normals_poly(float **vertnos, float polyno[3],
/********************************* Tangents **********************************/
-/* For normal map tangents we need to detect uv boundaries, and only average
- * tangents in case the uvs are connected. Alternative would be to store 1
- * tangent per face rather than 4 per face vertex, but that's not compatible
- * with games */
-
-
-/* from BKE_mesh.h */
-#define STD_UV_CONNECT_LIMIT 0.0001f
-
-void sum_or_add_vertex_tangent(void *arena, VertexTangent **vtang, const float tang[3], const float uv[2])
-{
- VertexTangent *vt;
-
- /* find a tangent with connected uvs */
- for (vt = *vtang; vt; vt = vt->next) {
- if (fabsf(uv[0] - vt->uv[0]) < STD_UV_CONNECT_LIMIT && fabsf(uv[1] - vt->uv[1]) < STD_UV_CONNECT_LIMIT) {
- add_v3_v3(vt->tang, tang);
- return;
- }
- }
-
- /* if not found, append a new one */
- vt = BLI_memarena_alloc((MemArena *) arena, sizeof(VertexTangent));
- copy_v3_v3(vt->tang, tang);
- vt->uv[0] = uv[0];
- vt->uv[1] = uv[1];
-
- if (*vtang)
- vt->next = *vtang;
- *vtang = vt;
-}
-
-float *find_vertex_tangent(VertexTangent *vtang, const float uv[2])
-{
- VertexTangent *vt;
- static float nulltang[3] = {0.0f, 0.0f, 0.0f};
-
- for (vt = vtang; vt; vt = vt->next)
- if (fabsf(uv[0] - vt->uv[0]) < STD_UV_CONNECT_LIMIT && fabsf(uv[1] - vt->uv[1]) < STD_UV_CONNECT_LIMIT)
- return vt->tang;
-
- return nulltang; /* shouldn't happen, except for nan or so */
-}
-
void tangent_from_uv(float uv1[2], float uv2[2], float uv3[3], float co1[3], float co2[3], float co3[3], float n[3], float tang[3])
{
float s1 = uv2[0] - uv1[0];
diff --git a/source/blender/blenlib/intern/math_geom_inline.c b/source/blender/blenlib/intern/math_geom_inline.c
index 0d4c797cefb..01585c93bc8 100644
--- a/source/blender/blenlib/intern/math_geom_inline.c
+++ b/source/blender/blenlib/intern/math_geom_inline.c
@@ -137,4 +137,24 @@ MINLINE void madd_sh_shfl(float r[9], const float sh[9], const float f)
add_sh_shsh(r, r, tmp);
}
+MINLINE int max_axis_v3(const float vec[3])
+{
+ const float x = vec[0];
+ const float y = vec[1];
+ const float z = vec[2];
+ return ((x > y) ?
+ ((x > z) ? 0 : 2) :
+ ((y > z) ? 1 : 2));
+}
+
+MINLINE int min_axis_v3(const float vec[3])
+{
+ const float x = vec[0];
+ const float y = vec[1];
+ const float z = vec[2];
+ return ((x < y) ?
+ ((x < z) ? 0 : 2) :
+ ((y < z) ? 1 : 2));
+}
+
#endif /* __MATH_GEOM_INLINE_C__ */
diff --git a/source/blender/blenlib/intern/math_matrix.c b/source/blender/blenlib/intern/math_matrix.c
index 3fb3d2b58ff..f622a5ace35 100644
--- a/source/blender/blenlib/intern/math_matrix.c
+++ b/source/blender/blenlib/intern/math_matrix.c
@@ -195,7 +195,7 @@ void mul_m3_m3m3(float m1[][3], float m3_[][3], float m2_[][3])
m1[2][2] = m2[2][0] * m3[0][2] + m2[2][1] * m3[1][2] + m2[2][2] * m3[2][2];
}
-void mul_m4_m4m3(float (*m1)[4], float (*m3_)[4], float (*m2_)[3])
+void mul_m4_m4m3(float m1[][4], float m3_[][4], float m2_[][3])
{
float m2[3][3], m3[4][4];
@@ -215,8 +215,14 @@ void mul_m4_m4m3(float (*m1)[4], float (*m3_)[4], float (*m2_)[3])
}
/* m1 = m2 * m3, ignore the elements on the 4th row/column of m3 */
-void mult_m3_m3m4(float m1[][3], float m3[][4], float m2[][3])
+void mult_m3_m3m4(float m1[][3], float m3_[][4], float m2_[][3])
{
+ float m2[3][3], m3[4][4];
+
+ /* copy so it works when m1 is the same pointer as m2 or m3 */
+ copy_m3_m3(m2, m2_);
+ copy_m4_m4(m3, m3_);
+
/* m1[i][j] = m2[i][k] * m3[k][j] */
m1[0][0] = m2[0][0] * m3[0][0] + m2[0][1] * m3[1][0] + m2[0][2] * m3[2][0];
m1[0][1] = m2[0][0] * m3[0][1] + m2[0][1] * m3[1][1] + m2[0][2] * m3[2][1];
@@ -231,8 +237,14 @@ void mult_m3_m3m4(float m1[][3], float m3[][4], float m2[][3])
m1[2][2] = m2[2][0] * m3[0][2] + m2[2][1] * m3[1][2] + m2[2][2] * m3[2][2];
}
-void mul_m4_m3m4(float (*m1)[4], float (*m3)[3], float (*m2)[4])
+void mul_m4_m3m4(float m1[][4], float m3_[][3], float m2_[][4])
{
+ float m2[4][4], m3[3][3];
+
+ /* copy so it works when m1 is the same pointer as m2 or m3 */
+ copy_m4_m4(m2, m2_);
+ copy_m3_m3(m3, m3_);
+
m1[0][0] = m2[0][0] * m3[0][0] + m2[0][1] * m3[1][0] + m2[0][2] * m3[2][0];
m1[0][1] = m2[0][0] * m3[0][1] + m2[0][1] * m3[1][1] + m2[0][2] * m3[2][1];
m1[0][2] = m2[0][0] * m3[0][2] + m2[0][1] * m3[1][2] + m2[0][2] * m3[2][2];
@@ -591,15 +603,15 @@ int invert_m4_m4(float inverse[4][4], float mat[4][4])
if (temp == 0)
return 0; /* No non-zero pivot */
for (k = 0; k < 4; k++) {
- tempmat[i][k] = (float)(tempmat[i][k] / temp);
- inverse[i][k] = (float)(inverse[i][k] / temp);
+ tempmat[i][k] = (float)((double)tempmat[i][k] / temp);
+ inverse[i][k] = (float)((double)inverse[i][k] / temp);
}
for (j = 0; j < 4; j++) {
if (j != i) {
temp = tempmat[j][i];
for (k = 0; k < 4; k++) {
- tempmat[j][k] -= (float)(tempmat[i][k] * temp);
- inverse[j][k] -= (float)(inverse[i][k] * temp);
+ tempmat[j][k] -= (float)((double)tempmat[i][k] * temp);
+ inverse[j][k] -= (float)((double)inverse[i][k] * temp);
}
}
}
@@ -933,8 +945,18 @@ void normalize_m4_m4(float rmat[][4], float mat[][4])
if (len != 0.0f) rmat[2][3] = mat[2][3] / len;
}
+void adjoint_m2_m2(float m1[][2], float m[][2])
+{
+ BLI_assert(m1 != m);
+ m1[0][0] = m[1][1];
+ m1[0][1] = -m[1][0];
+ m1[1][0] = -m[0][1];
+ m1[1][1] = m[0][0];
+}
+
void adjoint_m3_m3(float m1[][3], float m[][3])
{
+ BLI_assert(m1 != m);
m1[0][0] = m[1][1] * m[2][2] - m[1][2] * m[2][1];
m1[0][1] = -m[0][1] * m[2][2] + m[0][2] * m[2][1];
m1[0][2] = m[0][1] * m[1][2] - m[0][2] * m[1][1];
@@ -1388,7 +1410,7 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
int m = 4;
int n = 4;
int maxiter = 200;
- int nu = minf(m, n);
+ int nu = min_ff(m, n);
float *work = work1;
float *e = work2;
@@ -1396,22 +1418,22 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
int i = 0, j = 0, k = 0, p, pp, iter;
- // Reduce A to bidiagonal form, storing the diagonal elements
- // in s and the super-diagonal elements in e.
+ /* Reduce A to bidiagonal form, storing the diagonal elements
+ * in s and the super-diagonal elements in e. */
- int nct = minf(m - 1, n);
- int nrt = maxf(0, minf(n - 2, m));
+ int nct = min_ff(m - 1, n);
+ int nrt = max_ff(0, min_ff(n - 2, m));
copy_m4_m4(A, A_);
zero_m4(U);
zero_v4(s);
- for (k = 0; k < maxf(nct, nrt); k++) {
+ for (k = 0; k < max_ff(nct, nrt); k++) {
if (k < nct) {
- // Compute the transformation for the k-th column and
- // place the k-th diagonal in s[k].
- // Compute 2-norm of k-th column without under/overflow.
+ /* Compute the transformation for the k-th column and
+ * place the k-th diagonal in s[k].
+ * Compute 2-norm of k-th column without under/overflow. */
s[k] = 0;
for (i = k; i < m; i++) {
s[k] = hypotf(s[k], A[i][k]);
@@ -1432,7 +1454,7 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
for (j = k + 1; j < n; j++) {
if ((k < nct) && (s[k] != 0.0f)) {
- // Apply the transformation.
+ /* Apply the transformation. */
float t = 0;
for (i = k; i < m; i++) {
@@ -1444,24 +1466,24 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
}
}
- // Place the k-th row of A into e for the
- // subsequent calculation of the row transformation.
+ /* Place the k-th row of A into e for the */
+ /* subsequent calculation of the row transformation. */
e[j] = A[k][j];
}
if (k < nct) {
- // Place the transformation in U for subsequent back
- // multiplication.
+ /* Place the transformation in U for subsequent back
+ * multiplication. */
for (i = k; i < m; i++)
U[i][k] = A[i][k];
}
if (k < nrt) {
- // Compute the k-th row transformation and place the
- // k-th super-diagonal in e[k].
- // Compute 2-norm without under/overflow.
+ /* Compute the k-th row transformation and place the
+ * k-th super-diagonal in e[k].
+ * Compute 2-norm without under/overflow. */
e[k] = 0;
for (i = k + 1; i < n; i++) {
e[k] = hypotf(e[k], e[i]);
@@ -1481,7 +1503,7 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
if ((k + 1 < m) & (e[k] != 0.0f)) {
float invek1;
- // Apply the transformation.
+ /* Apply the transformation. */
for (i = k + 1; i < m; i++) {
work[i] = 0.0f;
@@ -1500,17 +1522,17 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
}
}
- // Place the transformation in V for subsequent
- // back multiplication.
+ /* Place the transformation in V for subsequent
+ * back multiplication. */
for (i = k + 1; i < n; i++)
V[i][k] = e[i];
}
}
- // Set up the final bidiagonal matrix or order p.
+ /* Set up the final bidiagonal matrix or order p. */
- p = minf(n, m + 1);
+ p = min_ff(n, m + 1);
if (nct < n) {
s[nct] = A[nct][nct];
}
@@ -1522,7 +1544,7 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
}
e[p - 1] = 0.0f;
- // If required, generate U.
+ /* If required, generate U. */
for (j = nct; j < nu; j++) {
for (i = 0; i < m; i++) {
@@ -1558,7 +1580,7 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
}
}
- // If required, generate V.
+ /* If required, generate V. */
for (k = n - 1; k >= 0; k--) {
if ((k < nrt) & (e[k] != 0.0f)) {
@@ -1579,7 +1601,7 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
V[k][k] = 1.0f;
}
- // Main iteration loop for the singular values.
+ /* Main iteration loop for the singular values. */
pp = p - 1;
iter = 0;
@@ -1587,20 +1609,20 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
while (p > 0) {
int kase = 0;
- // Test for maximum iterations to avoid infinite loop
+ /* Test for maximum iterations to avoid infinite loop */
if (maxiter == 0)
break;
maxiter--;
- // This section of the program inspects for
- // negligible elements in the s and e arrays. On
- // completion the variables kase and k are set as follows.
-
- // kase = 1 if s(p) and e[k - 1] are negligible and k<p
- // kase = 2 if s(k) is negligible and k<p
- // kase = 3 if e[k - 1] is negligible, k<p, and
- // s(k), ..., s(p) are not negligible (qr step).
- // kase = 4 if e(p - 1) is negligible (convergence).
+ /* This section of the program inspects for
+ * negligible elements in the s and e arrays. On
+ * completion the variables kase and k are set as follows.
+ *
+ * kase = 1 if s(p) and e[k - 1] are negligible and k<p
+ * kase = 2 if s(k) is negligible and k<p
+ * kase = 3 if e[k - 1] is negligible, k<p, and
+ * s(k), ..., s(p) are not negligible (qr step).
+ * kase = 4 if e(p - 1) is negligible (convergence). */
for (k = p - 2; k >= -1; k--) {
if (k == -1) {
@@ -1641,11 +1663,11 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
}
k++;
- // Perform the task indicated by kase.
+ /* Perform the task indicated by kase. */
switch (kase) {
- // Deflate negligible s(p).
+ /* Deflate negligible s(p). */
case 1:
{
@@ -1671,7 +1693,7 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
break;
}
- // Split at negligible s(k).
+ /* Split at negligible s(k). */
case 2:
{
@@ -1695,14 +1717,14 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
break;
}
- // Perform one qr step.
+ /* Perform one qr step. */
case 3:
{
- // Calculate the shift.
+ /* Calculate the shift. */
- float scale = maxf(maxf(maxf(maxf(
+ float scale = max_ff(max_ff(max_ff(max_ff(
fabsf(s[p - 1]), fabsf(s[p - 2])), fabsf(e[p - 2])),
fabsf(s[k])), fabsf(e[k]));
float invscale = 1.0f / scale;
@@ -1725,7 +1747,7 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
f = (sk + sp) * (sk - sp) + shift;
g = sk * ek;
- // Chase zeros.
+ /* Chase zeros. */
for (j = k; j < p - 1; j++) {
float t = hypotf(f, g);
@@ -1767,12 +1789,12 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
iter = iter + 1;
break;
}
- // Convergence.
+ /* Convergence. */
case 4:
{
- // Make the singular values positive.
+ /* Make the singular values positive. */
if (s[k] <= 0.0f) {
s[k] = (s[k] < 0.0f ? -s[k] : 0.0f);
@@ -1781,7 +1803,7 @@ void svd_m4(float U[4][4], float s[4], float V[4][4], float A_[4][4])
V[i][k] = -V[i][k];
}
- // Order the singular values.
+ /* Order the singular values. */
while (k < pp) {
float t;
diff --git a/source/blender/blenlib/intern/math_rotation.c b/source/blender/blenlib/intern/math_rotation.c
index f0ed23aabc9..b0c4724e1ec 100644
--- a/source/blender/blenlib/intern/math_rotation.c
+++ b/source/blender/blenlib/intern/math_rotation.c
@@ -35,7 +35,9 @@
/******************************** Quaternions ********************************/
/* used to test is a quat is not normalized (only used for debug prints) */
-#define QUAT_EPSILON 0.0001
+#ifdef DEBUG
+# define QUAT_EPSILON 0.0001
+#endif
/* convenience, avoids setting Y axis everywhere */
void unit_axis_angle(float axis[3], float *angle)
@@ -232,7 +234,7 @@ void quat_to_mat4(float m[][4], const float q[4])
double q0, q1, q2, q3, qda, qdb, qdc, qaa, qab, qac, qbb, qbc, qcc;
#ifdef DEBUG
- if (!((q0 = dot_qtqt(q, q)) == 0.0f || (fabsf(q0 - 1.0) < QUAT_EPSILON))) {
+ if (!((q0 = dot_qtqt(q, q)) == 0.0 || (fabs(q0 - 1.0) < QUAT_EPSILON))) {
fprintf(stderr, "Warning! quat_to_mat4() called with non-normalized: size %.8f *** report a bug ***\n", (float)q0);
}
#endif
@@ -286,9 +288,9 @@ void mat3_to_quat(float q[4], float wmat[][3])
s = sqrt(tr);
q[0] = (float)s;
s = 1.0 / (4.0 * s);
- q[1] = (float)((mat[1][2] - mat[2][1]) * s);
- q[2] = (float)((mat[2][0] - mat[0][2]) * s);
- q[3] = (float)((mat[0][1] - mat[1][0]) * s);
+ q[1] = (float)((double)(mat[1][2] - mat[2][1]) * s);
+ q[2] = (float)((double)(mat[2][0] - mat[0][2]) * s);
+ q[3] = (float)((double)(mat[0][1] - mat[1][0]) * s);
}
else {
if (mat[0][0] > mat[1][1] && mat[0][0] > mat[2][2]) {
@@ -611,13 +613,21 @@ void add_qt_qtqt(float result[4], const float quat1[4], const float quat2[4], co
result[3] = quat1[3] + t * quat2[3];
}
-void tri_to_quat(float quat[4], const float v1[3], const float v2[3], const float v3[3])
+/* same as tri_to_quat() but takes pre-computed normal from the triangle
+ * used for ngons when we know their normal */
+void tri_to_quat_ex(float quat[4], const float v1[3], const float v2[3], const float v3[3],
+ const float no_orig[3])
{
/* imaginary x-axis, y-axis triangle is being rotated */
float vec[3], q1[4], q2[4], n[3], si, co, angle, mat[3][3], imat[3][3];
/* move z-axis to face-normal */
+#if 0
normal_tri_v3(vec, v1, v2, v3);
+#else
+ copy_v3_v3(vec, no_orig);
+ (void)v3;
+#endif
n[0] = vec[1];
n[1] = -vec[0];
@@ -657,6 +667,13 @@ void tri_to_quat(float quat[4], const float v1[3], const float v2[3], const floa
mul_qt_qtqt(quat, q1, q2);
}
+void tri_to_quat(float quat[4], const float v1[3], const float v2[3], const float v3[3])
+{
+ float vec[3];
+ normal_tri_v3(vec, v1, v2, v3);
+ tri_to_quat_ex(quat, v1, v2, v3, vec);
+}
+
void print_qt(const char *str, const float q[4])
{
printf("%s: %.3f %.3f %.3f %.3f\n", str, q[0], q[1], q[2], q[3]);
@@ -780,7 +797,7 @@ void mat3_to_axis_angle(float axis[3], float *angle, float mat[3][3])
float q[4];
/* use quaternions as intermediate representation */
- // TODO: it would be nicer to go straight there...
+ /* TODO: it would be nicer to go straight there... */
mat3_to_quat(q, mat);
quat_to_axis_angle(axis, angle, q);
}
@@ -791,7 +808,7 @@ void mat4_to_axis_angle(float axis[3], float *angle, float mat[4][4])
float q[4];
/* use quaternions as intermediate representation */
- // TODO: it would be nicer to go straight there...
+ /* TODO: it would be nicer to go straight there... */
mat4_to_quat(q, mat);
quat_to_axis_angle(axis, angle, q);
}
@@ -841,7 +858,7 @@ void single_axis_angle_to_mat3(float mat[3][3], const char axis, const float ang
}
/****************************** Vector/Rotation ******************************/
-/* TODO: the following calls should probably be depreceated sometime */
+/* TODO: the following calls should probably be deprecated sometime */
/* TODO, replace use of this function with axis_angle_to_mat3() */
void vec_rot_to_mat3(float mat[][3], const float vec[3], const float phi)
@@ -1060,11 +1077,11 @@ void compatible_eul(float eul[3], const float oldrot[3])
for (i = 0; i < 3; i++) {
deul[i] = eul[i] - oldrot[i];
if (deul[i] > pi_thresh) {
- eul[i] -= floorf(( deul[i] / pi_x2) + 0.5) * pi_x2;
+ eul[i] -= floorf(( deul[i] / pi_x2) + 0.5f) * pi_x2;
deul[i] = eul[i] - oldrot[i];
}
else if (deul[i] < -pi_thresh) {
- eul[i] += floorf((-deul[i] / pi_x2) + 0.5) * pi_x2;
+ eul[i] += floorf((-deul[i] / pi_x2) + 0.5f) * pi_x2;
deul[i] = eul[i] - oldrot[i];
}
}
@@ -1346,7 +1363,7 @@ void mat4_to_compatible_eulO(float eul[3], float oldrot[3], const short order, f
mat3_to_compatible_eulO(eul, oldrot, order, m);
}
/* rotate the given euler by the given angle on the specified axis */
-// NOTE: is this safe to do with different axis orders?
+/* NOTE: is this safe to do with different axis orders? */
void rotate_eulO(float beul[3], const short order, char axis, float ang)
{
@@ -1662,34 +1679,34 @@ void vec_apply_track(float vec[3], short axis)
switch (axis) {
case 0: /* pos-x */
- /* vec[0]= 0.0; */
+ /* vec[0] = 0.0; */
vec[1] = tvec[2];
vec[2] = -tvec[1];
break;
case 1: /* pos-y */
- /* vec[0]= tvec[0]; */
- /* vec[1]= 0.0; */
- /* vec[2]= tvec[2]; */
+ /* vec[0] = tvec[0]; */
+ /* vec[1] = 0.0; */
+ /* vec[2] = tvec[2]; */
break;
case 2: /* pos-z */
- /* vec[0]= tvec[0]; */
- /* vec[1]= tvec[1]; */
- // vec[2]= 0.0; */
+ /* vec[0] = tvec[0]; */
+ /* vec[1] = tvec[1]; */
+ /* vec[2] = 0.0; */
break;
case 3: /* neg-x */
- /* vec[0]= 0.0; */
+ /* vec[0] = 0.0; */
vec[1] = tvec[2];
vec[2] = -tvec[1];
break;
case 4: /* neg-y */
vec[0] = -tvec[2];
- /* vec[1]= 0.0; */
+ /* vec[1] = 0.0; */
vec[2] = tvec[0];
break;
case 5: /* neg-z */
vec[0] = -tvec[0];
vec[1] = -tvec[1];
- /* vec[2]= 0.0; */
+ /* vec[2] = 0.0; */
break;
}
}
diff --git a/source/blender/blenlib/intern/math_vector.c b/source/blender/blenlib/intern/math_vector.c
index 4196bab0474..976895fe6fc 100644
--- a/source/blender/blenlib/intern/math_vector.c
+++ b/source/blender/blenlib/intern/math_vector.c
@@ -451,6 +451,15 @@ void minmax_v3v3_v3(float min[3], float max[3], const float vec[3])
if (max[2] < vec[2]) max[2] = vec[2];
}
+void minmax_v2v2_v2(float min[2], float max[2], const float vec[2])
+{
+ if (min[0] > vec[0]) min[0] = vec[0];
+ if (min[1] > vec[1]) min[1] = vec[1];
+
+ if (max[0] < vec[0]) max[0] = vec[0];
+ if (max[1] < vec[1]) max[1] = vec[1];
+}
+
/** ensure \a v1 is \a dist from \a v2 */
void dist_ensure_v3_v3fl(float v1[3], const float v2[3], const float dist)
{
@@ -483,7 +492,7 @@ double dot_vn_vn(const float *array_src_a, const float *array_src_b, const int s
const float *array_pt_b = array_src_b + (size - 1);
int i = size;
while (i--) {
- d += *(array_pt_a--) * *(array_pt_b--);
+ d += (double)(*(array_pt_a--) * *(array_pt_b--));
}
return d;
}
diff --git a/source/blender/blenlib/intern/math_vector_inline.c b/source/blender/blenlib/intern/math_vector_inline.c
index 0a8f57214d7..191b0e16025 100644
--- a/source/blender/blenlib/intern/math_vector_inline.c
+++ b/source/blender/blenlib/intern/math_vector_inline.c
@@ -121,6 +121,13 @@ MINLINE void copy_v4_v4_char(char r[4], const char a[4])
}
/* short */
+MINLINE void zero_v3_int(int r[3])
+{
+ r[0] = 0;
+ r[1] = 0;
+ r[2] = 0;
+}
+
MINLINE void copy_v2_v2_short(short r[2], const short a[2])
{
r[0] = a[0];
@@ -561,6 +568,16 @@ MINLINE float len_squared_v3(const float v[3])
return v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
}
+MINLINE float len_manhattan_v2(const float v[2])
+{
+ return fabsf(v[0]) + fabsf(v[1]);
+}
+
+MINLINE float len_manhattan_v3(const float v[3])
+{
+ return fabsf(v[0]) + fabsf(v[1]) + fabsf(v[2]);
+}
+
MINLINE float len_v2(const float v[2])
{
return sqrtf(v[0] * v[0] + v[1] * v[1]);
@@ -588,20 +605,36 @@ MINLINE float len_squared_v2v2(const float a[2], const float b[2])
return dot_v2v2(d, d);
}
-MINLINE float len_v3v3(const float a[3], const float b[3])
+MINLINE float len_squared_v3v3(const float a[3], const float b[3])
{
float d[3];
sub_v3_v3v3(d, b, a);
- return len_v3(d);
+ return dot_v3v3(d, d);
}
-MINLINE float len_squared_v3v3(const float a[3], const float b[3])
+MINLINE float len_manhattan_v2v2(const float a[2], const float b[2])
+{
+ float d[2];
+
+ sub_v2_v2v2(d, b, a);
+ return len_manhattan_v2(d);
+}
+
+MINLINE float len_manhattan_v3v3(const float a[3], const float b[3])
{
float d[3];
sub_v3_v3v3(d, b, a);
- return dot_v3v3(d, d);
+ return len_manhattan_v3(d);
+}
+
+MINLINE float len_v3v3(const float a[3], const float b[3])
+{
+ float d[3];
+
+ sub_v3_v3v3(d, b, a);
+ return len_v3(d);
}
MINLINE float normalize_v2_v2(float r[2], const float a[2])
@@ -689,7 +722,7 @@ MINLINE void normal_float_to_short_v3(short out[3], const float in[3])
/********************************* Comparison ********************************/
-MINLINE int is_zero_v2(const float v[3])
+MINLINE int is_zero_v2(const float v[2])
{
return (v[0] == 0 && v[1] == 0);
}
@@ -724,6 +757,15 @@ MINLINE int equals_v4v4(const float v1[4], const float v2[4])
return ((v1[0] == v2[0]) && (v1[1] == v2[1]) && (v1[2] == v2[2]) && (v1[3] == v2[3]));
}
+MINLINE int compare_v2v2(const float v1[2], const float v2[2], const float limit)
+{
+ if (fabsf(v1[0] - v2[0]) < limit)
+ if (fabsf(v1[1] - v2[1]) < limit)
+ return 1;
+
+ return 0;
+}
+
MINLINE int compare_v3v3(const float v1[3], const float v2[3], const float limit)
{
if (fabsf(v1[0] - v2[0]) < limit)
diff --git a/source/blender/blenlib/intern/noise.c b/source/blender/blenlib/intern/noise.c
index bd83c5e018c..fb33d7ce127 100644
--- a/source/blender/blenlib/intern/noise.c
+++ b/source/blender/blenlib/intern/noise.c
@@ -31,9 +31,9 @@
*/
-#ifdef _WIN32
-#pragma warning (disable : 4244) // "conversion from double to float"
-#pragma warning (disable : 4305) // "truncation from const double to float"
+#ifdef _MSC_VER
+# pragma warning (disable:4244) /* "conversion from double to float" */
+# pragma warning (disable:4305) /* "truncation from const double to float" */
#endif
#include <math.h>
@@ -45,7 +45,8 @@ static float noise3_perlin(float vec[3]);
//static float turbulence_perlin(float *point, float lofreq, float hifreq);
//static float turbulencep(float noisesize, float x, float y, float z, int nr);
-#define HASHVEC(x, y, z) hashvectf + 3 * hash[(hash[(hash[(z) & 255] + (y)) & 255] + (x)) & 255]
+/* UNUSED */
+// #define HASHVEC(x, y, z) hashvectf + 3 * hash[(hash[(hash[(z) & 255] + (y)) & 255] + (x)) & 255]
/* needed for voronoi */
#define HASHPNT(x, y, z) hashpntf + 3 * hash[(hash[(hash[(z) & 255] + (y)) & 255] + (x)) & 255]
@@ -300,8 +301,8 @@ static float newPerlin(float x, float y, float z)
u = npfade(x); /* COMPUTE FADE CURVES */
v = npfade(y); /* FOR EACH OF X,Y,Z. */
w = npfade(z);
- A = hash[X ]+Y; AA = hash[A]+Z; AB = hash[A+1]+Z; /* HASH COORDINATES OF */
- B = hash[X+1]+Y; BA = hash[B]+Z; BB = hash[B+1]+Z; /* THE 8 CUBE CORNERS, */
+ A = hash[X ] + Y; AA = hash[A] + Z; AB = hash[A + 1] + Z; /* HASH COORDINATES OF */
+ B = hash[X + 1] + Y; BA = hash[B] + Z; BB = hash[B + 1] + Z; /* THE 8 CUBE CORNERS, */
return lerp(w, lerp(v, lerp(u, grad(hash[AA ], x, y, z ), /* AND ADD */
grad(hash[BA ], x - 1, y, z )), /* BLENDED */
lerp(u, grad(hash[AB ], x, y - 1, z ), /* RESULTS */
diff --git a/source/blender/blenlib/intern/path_util.c b/source/blender/blenlib/intern/path_util.c
index a7a66718445..444daf8817c 100644
--- a/source/blender/blenlib/intern/path_util.c
+++ b/source/blender/blenlib/intern/path_util.c
@@ -47,7 +47,7 @@
#include "BLI_string_utf8.h"
#include "BLI_utildefines.h"
-#include "BKE_blender.h" // BLENDER_VERSION
+#include "BKE_blender.h" /* BLENDER_VERSION */
#include "GHOST_Path-api.h"
@@ -330,7 +330,7 @@ void BLI_cleanup_path(const char *relabase, char *dir)
if (strcmp(dir, ".") == 0) { /* happens for example in FILE_MAIN */
get_default_root(dir);
return;
- }
+ }
while ( (start = strstr(dir, "\\..\\")) ) {
eind = start + strlen("\\..\\") - 1;
@@ -492,7 +492,7 @@ void BLI_path_rel(char *file, const char *relfile)
*/
if (*q != '/') {
while ( (q >= file) && (*q != '/') ) { --q; --p; }
- }
+ }
else if (*p != '/') {
while ( (p >= temp) && (*p != '/') ) { --p; --q; }
}
@@ -544,7 +544,7 @@ int BLI_parent_dir(char *path)
BLI_cleanup_dir(NULL, tmp);
if (!BLI_testextensie(tmp, parent_dir)) {
- BLI_strncpy(path, tmp, sizeof(tmp));
+ BLI_strncpy(path, tmp, sizeof(tmp));
return 1;
}
else {
@@ -691,7 +691,7 @@ int BLI_path_abs(char *path, const char *basepath)
* of paths and solving some problems (and prevent potential future
* ones) -jesterKing. */
BLI_char_switch(tmp, '\\', '/');
- BLI_char_switch(base, '\\', '/');
+ BLI_char_switch(base, '\\', '/');
/* Paths starting with // will get the blend file as their base,
* this isn't standard in any os but is used in blender all over the place */
@@ -1300,7 +1300,7 @@ void BLI_make_file_string(const char *relabase, char *string, const char *dir,
BLI_char_switch(file, '\\', '/');
#endif
- /* Resolve relative references */
+ /* Resolve relative references */
if (relabase && dir[0] == '/' && dir[1] == '/') {
char *lslash;
@@ -1321,7 +1321,7 @@ void BLI_make_file_string(const char *relabase, char *string, const char *dir,
else { /* no drive specified */
/* first option: get the drive from the relabase if it has one */
if (relabase && strlen(relabase) >= 2 && relabase[1] == ':') {
- BLI_strncpy(string, relabase, 3);
+ BLI_strncpy(string, relabase, 3);
string[2] = '\\';
string[3] = '\0';
}
@@ -1337,7 +1337,7 @@ void BLI_make_file_string(const char *relabase, char *string, const char *dir,
strcat(string, dir);
- /* Make sure string ends in one (and only one) slash */
+ /* Make sure string ends in one (and only one) slash */
/* first trim all slashes from the end of the string */
sl = strlen(string);
while (sl > 0 && (string[sl - 1] == '/' || string[sl - 1] == '\\') ) {
@@ -1368,7 +1368,7 @@ int BLI_testextensie(const char *str, const char *ext)
retval = 0;
}
else if (BLI_strcasecmp(ext, str + a - b)) {
- retval = 0;
+ retval = 0;
}
else {
retval = 1;
diff --git a/source/blender/blenlib/intern/pbvh.c b/source/blender/blenlib/intern/pbvh.c
index d3d8d371f60..7637c60ec16 100644
--- a/source/blender/blenlib/intern/pbvh.c
+++ b/source/blender/blenlib/intern/pbvh.c
@@ -157,6 +157,8 @@ struct PBVH {
/* flag are verts/faces deformed */
int deformed;
+
+ int show_diffuse_color;
};
#define STACK_FIXED_DEPTH 100
@@ -189,8 +191,8 @@ static void BB_expand(BB *bb, float co[3])
{
int i;
for (i = 0; i < 3; ++i) {
- bb->bmin[i] = minf(bb->bmin[i], co[i]);
- bb->bmax[i] = maxf(bb->bmax[i], co[i]);
+ bb->bmin[i] = min_ff(bb->bmin[i], co[i]);
+ bb->bmax[i] = max_ff(bb->bmax[i], co[i]);
}
}
@@ -199,8 +201,8 @@ static void BB_expand_with_bb(BB *bb, BB *bb2)
{
int i;
for (i = 0; i < 3; ++i) {
- bb->bmin[i] = minf(bb->bmin[i], bb2->bmin[i]);
- bb->bmax[i] = maxf(bb->bmax[i], bb2->bmax[i]);
+ bb->bmin[i] = min_ff(bb->bmin[i], bb2->bmin[i]);
+ bb->bmax[i] = max_ff(bb->bmax[i], bb2->bmax[i]);
}
}
@@ -663,7 +665,7 @@ void BLI_pbvh_build_grids(PBVH *bvh, CCGElem **grids, DMGridAdjacency *gridadj,
bvh->totgrid = totgrid;
bvh->gridkey = *key;
bvh->grid_hidden = grid_hidden;
- bvh->leaf_limit = maxi(LEAF_LIMIT / ((gridsize - 1) * (gridsize - 1)), 1);
+ bvh->leaf_limit = max_ii(LEAF_LIMIT / ((gridsize - 1) * (gridsize - 1)), 1);
BB_reset(&cb);
@@ -1001,7 +1003,7 @@ static int update_search_cb(PBVHNode *node, void *data_v)
if (node->flag & PBVH_Leaf)
return (node->flag & flag);
-
+
return 1;
}
@@ -1165,7 +1167,8 @@ static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode)
bvh->grid_flag_mats,
node->prim_indices,
node->totprim,
- &bvh->gridkey);
+ &bvh->gridkey,
+ bvh->show_diffuse_color);
break;
case PBVH_FACES:
GPU_update_mesh_buffers(node->draw_buffers,
@@ -1174,7 +1177,9 @@ static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode)
node->uniq_verts +
node->face_verts,
CustomData_get_layer(bvh->vdata,
- CD_PAINT_MASK));
+ CD_PAINT_MASK),
+ node->face_vert_indices,
+ bvh->show_diffuse_color);
break;
}
@@ -1630,9 +1635,9 @@ static PlaneAABBIsect test_planes_aabb(const float bb_min[3],
PlaneAABBIsect ret = ISECT_INSIDE;
int i, axis;
- for (i = 0; i < 4; ++i) {
+ for (i = 0; i < 4; ++i) {
for (axis = 0; axis < 3; ++axis) {
- if (planes[i][axis] > 0) {
+ if (planes[i][axis] > 0) {
vmin[axis] = bb_min[axis];
vmax[axis] = bb_max[axis];
}
@@ -1646,7 +1651,7 @@ static PlaneAABBIsect test_planes_aabb(const float bb_min[3],
return ISECT_OUTSIDE;
else if (dot_v3v3(planes[i], vmax) + planes[i][3] >= 0)
ret = ISECT_INTERSECT;
- }
+ }
return ret;
}
@@ -1667,11 +1672,23 @@ int BLI_pbvh_node_planes_exclude_AABB(PBVHNode *node, void *data)
return test_planes_aabb(bb_min, bb_max, data) != ISECT_INSIDE;
}
+static void pbvh_node_check_diffuse_changed(PBVH *bvh, PBVHNode *node)
+{
+ if (!node->draw_buffers)
+ return;
+
+ if (GPU_buffers_diffuse_changed(node->draw_buffers, bvh->show_diffuse_color))
+ node->flag |= PBVH_UpdateDrawBuffers;
+}
+
void BLI_pbvh_draw(PBVH *bvh, float (*planes)[4], float (*face_nors)[3],
DMSetMaterial setMaterial)
{
PBVHNode **nodes;
- int totnode;
+ int a, totnode;
+
+ for (a = 0; a < bvh->totnode; a++)
+ pbvh_node_check_diffuse_changed(bvh, &bvh->nodes[a]);
BLI_pbvh_search_gather(bvh, update_search_cb, SET_INT_IN_POINTER(PBVH_UpdateNormals | PBVH_UpdateDrawBuffers),
&nodes, &totnode);
@@ -1876,3 +1893,8 @@ void pbvh_vertex_iter_init(PBVH *bvh, PBVHNode *node,
if (!vi->grids)
vi->vmask = CustomData_get_layer(bvh->vdata, CD_PAINT_MASK);
}
+
+void pbvh_show_diffuse_color_set(PBVH *bvh, int show_diffuse_color)
+{
+ bvh->show_diffuse_color = show_diffuse_color;
+}
diff --git a/source/blender/blenlib/intern/quadric.c b/source/blender/blenlib/intern/quadric.c
new file mode 100644
index 00000000000..bb39cb61e78
--- /dev/null
+++ b/source/blender/blenlib/intern/quadric.c
@@ -0,0 +1,131 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * Contributor(s): Laurence Bourn, Campbell Barton
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/blenlib/intern/quadric.c
+ * \ingroup bli
+ *
+ * \note This isn't fully complete,
+ * possible there are other useful functions to add here.
+ *
+ * \note try to follow BLI_math naming convention here.
+ */
+
+//#include <string.h>
+
+#include "BLI_math.h"
+#include "BLI_quadric.h" /* own include */
+
+
+#define QUADRIC_FLT_TOT (sizeof(Quadric) / sizeof(float))
+
+void BLI_quadric_from_v3_dist(Quadric *q, const float v[3], const float offset)
+{
+ q->a2 = v[0] * v[0];
+ q->b2 = v[1] * v[1];
+ q->c2 = v[2] * v[2];
+
+ q->ab = v[0] * v[1];
+ q->ac = v[0] * v[2];
+ q->bc = v[1] * v[2];
+
+ q->ad = v[0] * offset;
+ q->bd = v[1] * offset;
+ q->cd = v[2] * offset;
+
+ q->d2 = offset * offset;
+}
+
+void BLI_quadric_to_tensor_m3(const Quadric *q, float m[3][3])
+{
+ m[0][0] = q->a2;
+ m[0][1] = q->ab;
+ m[0][2] = q->ac;
+
+ m[1][0] = q->ab;
+ m[1][1] = q->b2;
+ m[1][2] = q->bc;
+
+ m[2][0] = q->ac;
+ m[2][1] = q->bc;
+ m[2][2] = q->c2;
+}
+
+void BLI_quadric_to_vector_v3(const Quadric *q, float v[3])
+{
+ v[0] = q->ad;
+ v[1] = q->bd;
+ v[2] = q->cd;
+}
+
+void BLI_quadric_clear(Quadric *q)
+{
+ memset(q, 0, sizeof(*q));
+}
+
+void BLI_quadric_add_qu_qu(Quadric *a, const Quadric *b)
+{
+ add_vn_vn((float *)a, (float *)b, QUADRIC_FLT_TOT);
+}
+
+void BLI_quadric_add_qu_ququ(Quadric *r, const Quadric *a, const Quadric *b)
+{
+ add_vn_vnvn((float *)r, (const float *)a, (const float *)b, QUADRIC_FLT_TOT);
+}
+
+void BLI_quadric_mul(Quadric *a, const float scalar)
+{
+ mul_vn_fl((float *)a, QUADRIC_FLT_TOT, scalar);
+}
+
+float BLI_quadric_evaluate(const Quadric *q, const float v[3])
+{
+ return (v[0] * v[0] * q->a2 + 2.0f * v[0] * v[1] * q->ab + 2.0f * v[0] * v[2] * q->ac + 2.0f * v[0] * q->ad +
+ v[1] * v[1] * q->b2 + 2.0f * v[1] * v[2] * q->bc + 2.0f * v[1] * q->bd +
+ v[2] * v[2] * q->c2 + 2.0f * v[2] * q->cd +
+ q->d2);
+}
+
+int BLI_quadric_optimize(const Quadric *q, float v[3])
+{
+ float m[3][3];
+ float det;
+
+ BLI_quadric_to_tensor_m3(q, m);
+ det = determinant_m3(m[0][0], m[0][1], m[0][2],
+ m[1][0], m[1][1], m[1][2],
+ m[2][0], m[2][1], m[2][2]);
+
+ if (fabsf(det) > FLT_EPSILON) {
+ invert_m3(m);
+ BLI_quadric_to_vector_v3(q, v);
+ mul_m3_v3(m, v);
+ negate_v3(v);
+
+ return TRUE;
+ }
+ else {
+ return FALSE;
+ }
+}
diff --git a/source/blender/blenlib/intern/rand.c b/source/blender/blenlib/intern/rand.c
index 4435e9ce09c..76d17f34b5e 100644
--- a/source/blender/blenlib/intern/rand.c
+++ b/source/blender/blenlib/intern/rand.c
@@ -40,7 +40,7 @@
#include "BLI_threads.h"
#include "BLI_rand.h"
-#if defined(WIN32) && !defined(FREE_WINDOWS)
+#ifdef _MSC_VER
typedef unsigned __int64 r_uint64;
#define MULTIPLIER 0x5DEECE66Di64
@@ -64,51 +64,51 @@ struct RNG {
r_uint64 X;
};
-RNG *rng_new(unsigned int seed)
+RNG *BLI_rng_new(unsigned int seed)
{
RNG *rng = MEM_mallocN(sizeof(*rng), "rng");
- rng_seed(rng, seed);
+ BLI_rng_seed(rng, seed);
return rng;
}
-void rng_free(RNG *rng)
+void BLI_rng_free(RNG *rng)
{
MEM_freeN(rng);
}
-void rng_seed(RNG *rng, unsigned int seed)
+void BLI_rng_seed(RNG *rng, unsigned int seed)
{
rng->X = (((r_uint64) seed) << 16) | LOWSEED;
}
-void rng_srandom(RNG *rng, unsigned int seed)
+void BLI_rng_srandom(RNG *rng, unsigned int seed)
{
- rng_seed(rng, seed + hash[seed & 255]);
- seed = rng_getInt(rng);
- rng_seed(rng, seed + hash[seed & 255]);
- seed = rng_getInt(rng);
- rng_seed(rng, seed + hash[seed & 255]);
+ BLI_rng_seed(rng, seed + hash[seed & 255]);
+ seed = BLI_rng_get_int(rng);
+ BLI_rng_seed(rng, seed + hash[seed & 255]);
+ seed = BLI_rng_get_int(rng);
+ BLI_rng_seed(rng, seed + hash[seed & 255]);
}
-int rng_getInt(RNG *rng)
+int BLI_rng_get_int(RNG *rng)
{
rng->X = (MULTIPLIER * rng->X + ADDEND) & MASK;
return (int) (rng->X >> 17);
}
-double rng_getDouble(RNG *rng)
+double BLI_rng_get_double(RNG *rng)
{
- return (double) rng_getInt(rng) / 0x80000000;
+ return (double) BLI_rng_get_int(rng) / 0x80000000;
}
-float rng_getFloat(RNG *rng)
+float BLI_rng_get_float(RNG *rng)
{
- return (float) rng_getInt(rng) / 0x80000000;
+ return (float) BLI_rng_get_int(rng) / 0x80000000;
}
-void rng_shuffleArray(RNG *rng, void *data, int elemSize, int numElems)
+void BLI_rng_shuffle_array(RNG *rng, void *data, int elemSize, int numElems)
{
int i = numElems;
void *temp;
@@ -122,7 +122,7 @@ void rng_shuffleArray(RNG *rng, void *data, int elemSize, int numElems)
/* XXX Shouldn't it rather be "while (i--) {" ?
* Else we have no guaranty first (0) element has a chance to be shuffled... --mont29 */
while (--i) {
- int j = rng_getInt(rng) % numElems;
+ int j = BLI_rng_get_int(rng) % numElems;
if (i != j) {
void *iElem = (unsigned char *)data + i * elemSize;
void *jElem = (unsigned char *)data + j * elemSize;
@@ -135,12 +135,12 @@ void rng_shuffleArray(RNG *rng, void *data, int elemSize, int numElems)
free(temp);
}
-void rng_skip(RNG *rng, int n)
+void BLI_rng_skip(RNG *rng, int n)
{
int i;
for (i = 0; i < n; i++)
- rng_getInt(rng);
+ BLI_rng_get_int(rng);
}
/***/
@@ -150,28 +150,28 @@ static RNG theBLI_rng = {0};
/* note, this one creates periodical patterns */
void BLI_srand(unsigned int seed)
{
- rng_seed(&theBLI_rng, seed);
+ BLI_rng_seed(&theBLI_rng, seed);
}
/* using hash table to create better seed */
void BLI_srandom(unsigned int seed)
{
- rng_srandom(&theBLI_rng, seed);
+ BLI_rng_srandom(&theBLI_rng, seed);
}
int BLI_rand(void)
{
- return rng_getInt(&theBLI_rng);
+ return BLI_rng_get_int(&theBLI_rng);
}
double BLI_drand(void)
{
- return rng_getDouble(&theBLI_rng);
+ return BLI_rng_get_double(&theBLI_rng);
}
float BLI_frand(void)
{
- return rng_getFloat(&theBLI_rng);
+ return BLI_rng_get_float(&theBLI_rng);
}
void BLI_fillrand(void *addr, int len)
@@ -179,16 +179,16 @@ void BLI_fillrand(void *addr, int len)
RNG rng;
unsigned char *p = addr;
- rng_seed(&rng, (unsigned int) (PIL_check_seconds_timer() * 0x7FFFFFFF));
- while (len--) *p++ = rng_getInt(&rng) & 0xFF;
+ BLI_rng_seed(&rng, (unsigned int) (PIL_check_seconds_timer() * 0x7FFFFFFF));
+ while (len--) *p++ = BLI_rng_get_int(&rng) & 0xFF;
}
void BLI_array_randomize(void *data, int elemSize, int numElems, unsigned int seed)
{
RNG rng;
- rng_seed(&rng, seed);
- rng_shuffleArray(&rng, data, elemSize, numElems);
+ BLI_rng_seed(&rng, seed);
+ BLI_rng_shuffle_array(&rng, data, elemSize, numElems);
}
/* ********* for threaded random ************** */
@@ -200,20 +200,20 @@ void BLI_thread_srandom(int thread, unsigned int seed)
if (thread >= BLENDER_MAX_THREADS)
thread = 0;
- rng_seed(&rng_tab[thread], seed + hash[seed & 255]);
- seed = rng_getInt(&rng_tab[thread]);
- rng_seed(&rng_tab[thread], seed + hash[seed & 255]);
- seed = rng_getInt(&rng_tab[thread]);
- rng_seed(&rng_tab[thread], seed + hash[seed & 255]);
+ BLI_rng_seed(&rng_tab[thread], seed + hash[seed & 255]);
+ seed = BLI_rng_get_int(&rng_tab[thread]);
+ BLI_rng_seed(&rng_tab[thread], seed + hash[seed & 255]);
+ seed = BLI_rng_get_int(&rng_tab[thread]);
+ BLI_rng_seed(&rng_tab[thread], seed + hash[seed & 255]);
}
int BLI_thread_rand(int thread)
{
- return rng_getInt(&rng_tab[thread]);
+ return BLI_rng_get_int(&rng_tab[thread]);
}
float BLI_thread_frand(int thread)
{
- return rng_getFloat(&rng_tab[thread]);
+ return BLI_rng_get_float(&rng_tab[thread]);
}
diff --git a/source/blender/blenlib/intern/rct.c b/source/blender/blenlib/intern/rct.c
index 225ede8a8ef..ee073d5d309 100644
--- a/source/blender/blenlib/intern/rct.c
+++ b/source/blender/blenlib/intern/rct.c
@@ -102,16 +102,28 @@ int BLI_rctf_isect_pt_v(const rctf *rect, const float xy[2])
}
/* based closely on 'isect_line_line_v2_int', but in modified so corner cases are treated as intersections */
-static int isect_segments(const int v1[2], const int v2[2], const int v3[2], const int v4[2])
+static int isect_segments_i(const int v1[2], const int v2[2], const int v3[2], const int v4[2])
{
const double div = (double)((v2[0] - v1[0]) * (v4[1] - v3[1]) - (v2[1] - v1[1]) * (v4[0] - v3[0]));
- if (div == 0.0f) {
+ if (div == 0.0) {
return 1; /* co-linear */
}
else {
const double labda = (double)((v1[1] - v3[1]) * (v4[0] - v3[0]) - (v1[0] - v3[0]) * (v4[1] - v3[1])) / div;
const double mu = (double)((v1[1] - v3[1]) * (v2[0] - v1[0]) - (v1[0] - v3[0]) * (v2[1] - v1[1])) / div;
- return (labda >= 0.0f && labda <= 1.0f && mu >= 0.0f && mu <= 1.0f);
+ return (labda >= 0.0 && labda <= 1.0 && mu >= 0.0 && mu <= 1.0);
+ }
+}
+static int isect_segments_fl(const float v1[2], const float v2[2], const float v3[2], const float v4[2])
+{
+ const double div = (double)((v2[0] - v1[0]) * (v4[1] - v3[1]) - (v2[1] - v1[1]) * (v4[0] - v3[0]));
+ if (div == 0.0) {
+ return 1; /* co-linear */
+ }
+ else {
+ const double labda = (double)((v1[1] - v3[1]) * (v4[0] - v3[0]) - (v1[0] - v3[0]) * (v4[1] - v3[1])) / div;
+ const double mu = (double)((v1[1] - v3[1]) * (v2[0] - v1[0]) - (v1[0] - v3[0]) * (v2[1] - v1[1])) / div;
+ return (labda >= 0.0 && labda <= 1.0 && mu >= 0.0 && mu <= 1.0);
}
}
@@ -134,14 +146,49 @@ int BLI_rcti_isect_segment(const rcti *rect, const int s1[2], const int s2[2])
/* diagonal: [/] */
tvec1[0] = rect->xmin; tvec1[1] = rect->ymin;
tvec2[0] = rect->xmin; tvec2[1] = rect->ymax;
- if (isect_segments(s1, s2, tvec1, tvec2)) {
+ if (isect_segments_i(s1, s2, tvec1, tvec2)) {
return 1;
}
/* diagonal: [\] */
tvec1[0] = rect->xmin; tvec1[1] = rect->ymax;
tvec2[0] = rect->xmax; tvec2[1] = rect->ymin;
- if (isect_segments(s1, s2, tvec1, tvec2)) {
+ if (isect_segments_i(s1, s2, tvec1, tvec2)) {
+ return 1;
+ }
+
+ /* no intersection */
+ return 0;
+ }
+}
+
+int BLI_rctf_isect_segment(const rctf *rect, const float s1[2], const float s2[2])
+{
+ /* first do outside-bounds check for both points of the segment */
+ if (s1[0] < rect->xmin && s2[0] < rect->xmin) return 0;
+ if (s1[0] > rect->xmax && s2[0] > rect->xmax) return 0;
+ if (s1[1] < rect->ymin && s2[1] < rect->ymin) return 0;
+ if (s1[1] > rect->ymax && s2[1] > rect->ymax) return 0;
+
+ /* if either points intersect then we definetly intersect */
+ if (BLI_rctf_isect_pt_v(rect, s1) || BLI_rctf_isect_pt_v(rect, s2)) {
+ return 1;
+ }
+ else {
+ /* both points are outside but may insersect the rect */
+ float tvec1[2];
+ float tvec2[2];
+ /* diagonal: [/] */
+ tvec1[0] = rect->xmin; tvec1[1] = rect->ymin;
+ tvec2[0] = rect->xmin; tvec2[1] = rect->ymax;
+ if (isect_segments_fl(s1, s2, tvec1, tvec2)) {
+ return 1;
+ }
+
+ /* diagonal: [\] */
+ tvec1[0] = rect->xmin; tvec1[1] = rect->ymax;
+ tvec2[0] = rect->xmax; tvec2[1] = rect->ymin;
+ if (isect_segments_fl(s1, s2, tvec1, tvec2)) {
return 1;
}
@@ -252,8 +299,8 @@ void BLI_rctf_translate(rctf *rect, float x, float y)
/* change width & height around the central location */
void BLI_rcti_resize(rcti *rect, int x, int y)
{
- rect->xmin = rect->xmax = BLI_RCT_CENTER_X(rect);
- rect->ymin = rect->ymax = BLI_RCT_CENTER_Y(rect);
+ rect->xmin = rect->xmax = BLI_rcti_cent_x(rect);
+ rect->ymin = rect->ymax = BLI_rcti_cent_y(rect);
rect->xmin -= x / 2;
rect->ymin -= y / 2;
rect->xmax = rect->xmin + x;
@@ -262,8 +309,8 @@ void BLI_rcti_resize(rcti *rect, int x, int y)
void BLI_rctf_resize(rctf *rect, float x, float y)
{
- rect->xmin = rect->xmax = BLI_RCT_CENTER_X(rect);
- rect->ymin = rect->ymax = BLI_RCT_CENTER_Y(rect);
+ rect->xmin = rect->xmax = BLI_rctf_cent_x(rect);
+ rect->ymin = rect->ymax = BLI_rctf_cent_y(rect);
rect->xmin -= x * 0.5f;
rect->ymin -= y * 0.5f;
rect->xmax = rect->xmin + x;
@@ -281,6 +328,27 @@ void BLI_rctf_interp(rctf *rect, const rctf *rect_a, const rctf *rect_b, const f
/* BLI_rcti_interp() not needed yet */
+
+int BLI_rctf_clamp_pt_v(const struct rctf *rect, float xy[2])
+{
+ int change = 0;
+ if (xy[0] < rect->xmin) { xy[0] = rect->xmin; change = 1; }
+ if (xy[0] > rect->xmax) { xy[0] = rect->xmax; change = 1; }
+ if (xy[1] < rect->ymin) { xy[1] = rect->ymin; change = 1; }
+ if (xy[1] > rect->ymax) { xy[1] = rect->ymax; change = 1; }
+ return change;
+}
+
+int BLI_rcti_clamp_pt_v(const struct rcti *rect, int xy[2])
+{
+ int change = 0;
+ if (xy[0] < rect->xmin) { xy[0] = rect->xmin; change = 1; }
+ if (xy[0] > rect->xmax) { xy[0] = rect->xmax; change = 1; }
+ if (xy[1] < rect->ymin) { xy[1] = rect->ymin; change = 1; }
+ if (xy[1] > rect->ymax) { xy[1] = rect->ymax; change = 1; }
+ return change;
+}
+
int BLI_rctf_compare(const struct rctf *rect_a, const struct rctf *rect_b, const float limit)
{
if (fabsf(rect_a->xmin - rect_b->xmin) < limit)
@@ -366,9 +434,9 @@ int BLI_rcti_isect(const rcti *src1, const rcti *src2, rcti *dest)
void BLI_rcti_rctf_copy(rcti *dst, const rctf *src)
{
dst->xmin = floorf(src->xmin + 0.5f);
- dst->xmax = dst->xmin + floorf(BLI_RCT_SIZE_X(src) + 0.5f);
+ dst->xmax = dst->xmin + floorf(BLI_rctf_size_x(src) + 0.5f);
dst->ymin = floorf(src->ymin + 0.5f);
- dst->ymax = dst->ymin + floorf(BLI_RCT_SIZE_Y(src) + 0.5f);
+ dst->ymax = dst->ymin + floorf(BLI_rctf_size_y(src) + 0.5f);
}
void BLI_rctf_rcti_copy(rctf *dst, const rcti *src)
@@ -382,11 +450,11 @@ void BLI_rctf_rcti_copy(rctf *dst, const rcti *src)
void print_rctf(const char *str, const rctf *rect)
{
printf("%s: xmin %.3f, xmax %.3f, ymin %.3f, ymax %.3f (%.3fx%.3f)\n", str,
- rect->xmin, rect->xmax, rect->ymin, rect->ymax, BLI_RCT_SIZE_X(rect), BLI_RCT_SIZE_Y(rect));
+ rect->xmin, rect->xmax, rect->ymin, rect->ymax, BLI_rctf_size_x(rect), BLI_rctf_size_y(rect));
}
void print_rcti(const char *str, const rcti *rect)
{
printf("%s: xmin %d, xmax %d, ymin %d, ymax %d (%dx%d)\n", str,
- rect->xmin, rect->xmax, rect->ymin, rect->ymax, BLI_RCT_SIZE_X(rect), BLI_RCT_SIZE_Y(rect));
+ rect->xmin, rect->xmax, rect->ymin, rect->ymax, BLI_rcti_size_x(rect), BLI_rcti_size_y(rect));
}
diff --git a/source/blender/blenlib/intern/scanfill.c b/source/blender/blenlib/intern/scanfill.c
index 32afaba2b5c..362a87782c6 100644
--- a/source/blender/blenlib/intern/scanfill.c
+++ b/source/blender/blenlib/intern/scanfill.c
@@ -211,7 +211,7 @@ ScanFillVert *BLI_scanfill_vert_add(ScanFillContext *sf_ctx, const float vec[3])
copy_v3_v3(eve->co, vec);
- return eve;
+ return eve;
}
ScanFillEdge *BLI_scanfill_edge_add(ScanFillContext *sf_ctx, ScanFillVert *v1, ScanFillVert *v2)
@@ -521,7 +521,7 @@ static int scanfill(ScanFillContext *sf_ctx, PolyFill *pf)
while (eve) {
printf("vert: %x co: %f %f\n", eve, eve->xy[0], eve->xy[1]);
eve = eve->next;
- }
+ }
eed = sf_ctx->filledgebase.first;
while (eed) {
printf("edge: %x verts: %x %x\n", eed, eed->v1, eed->v2);
@@ -661,8 +661,8 @@ static int scanfill(ScanFillContext *sf_ctx, PolyFill *pf)
/* this happens with a serial of overlapping edges */
if (v1 == v2 || v2 == v3) break;
/* printf("test verts %x %x %x\n",v1,v2,v3); */
- miny = minf(v1->xy[1], v3->xy[1]);
- /* miny= minf(v1->xy[1],v3->xy[1]); */
+ miny = min_ff(v1->xy[1], v3->xy[1]);
+ /* miny = min_ff(v1->xy[1],v3->xy[1]); */
sc1 = sc + 1;
test = 0;
@@ -985,12 +985,12 @@ int BLI_scanfill_calc_ex(ScanFillContext *sf_ctx, const short do_quad_tri_speedu
/* CURRENT STATUS:
- * - eve->f :1= availalble in edges
+ * - eve->f :1 = availalble in edges
* - eve->xs :polynumber
* - eve->h :amount of edges connected to vertex
* - eve->tmp.v :store! original vertex number
*
- * - eed->f :1= boundary edge (optionally set by caller)
+ * - eed->f :1 = boundary edge (optionally set by caller)
* - eed->poly_nr :poly number
*/
diff --git a/source/blender/blenlib/intern/storage.c b/source/blender/blenlib/intern/storage.c
index 0fccd91fc02..1358fdd2a62 100644
--- a/source/blender/blenlib/intern/storage.c
+++ b/source/blender/blenlib/intern/storage.c
@@ -34,7 +34,7 @@
#include <sys/types.h>
#include <stdio.h>
-#include <stdlib.h>
+#include <stdlib.h>
#ifndef WIN32
#include <dirent.h>
@@ -187,7 +187,7 @@ double BLI_dir_free_space(const char *dir)
#endif
#if defined(__sun__) || defined(__sun) || defined(__NetBSD__)
- if (statvfs(name, &disk)) return(-1);
+ if (statvfs(name, &disk)) return(-1);
#elif !defined(__FreeBSD__) && !defined(linux) && (defined(__sparc) || defined(__sparc__))
/* WARNING - This may not be supported by geeneric unix os's - Campbell */
if (statfs(name, &disk, sizeof(struct statfs), 0)) return(-1);
@@ -418,9 +418,9 @@ static void bli_adddirstrings(void)
unsigned int BLI_dir_contents(const char *dirname, struct direntry **filelist)
{
- // reset global variables
- // memory stored in files is free()'d in
- // filesel.c:freefilelist()
+ /* reset global variables
+ * memory stored in files is free()'d in
+ * filesel.c:freefilelist() */
actnum = totnum = 0;
files = NULL;
diff --git a/source/blender/blenlib/intern/string.c b/source/blender/blenlib/intern/string.c
index 8501db7c8b8..ff589764287 100644
--- a/source/blender/blenlib/intern/string.c
+++ b/source/blender/blenlib/intern/string.c
@@ -41,6 +41,8 @@
#include "BLI_dynstr.h"
#include "BLI_string.h"
+#include "BLI_utildefines.h"
+
char *BLI_strdupn(const char *str, const size_t len)
{
char *n = MEM_mallocN(len + 1, "strdup");
@@ -71,6 +73,7 @@ char *BLI_strncpy(char *dst, const char *src, const size_t maxncpy)
{
size_t srclen = strlen(src);
size_t cpylen = (srclen > (maxncpy - 1)) ? (maxncpy - 1) : srclen;
+ BLI_assert(maxncpy != 0);
memcpy(dst, src, cpylen);
dst[cpylen] = '\0';
@@ -130,10 +133,13 @@ char *BLI_sprintfN(const char *format, ...)
* TODO: support more fancy string escaping. current code is primitive
* this basically is an ascii version of PyUnicode_EncodeUnicodeEscape()
* which is a useful reference. */
-size_t BLI_strescape(char *dst, const char *src, const size_t maxlen)
+size_t BLI_strescape(char *dst, const char *src, const size_t maxncpy)
{
size_t len = 0;
- while (len < maxlen) {
+
+ BLI_assert(maxncpy != 0);
+
+ while (len < maxncpy) {
switch (*src) {
case '\0':
goto escape_finish;
@@ -144,7 +150,7 @@ size_t BLI_strescape(char *dst, const char *src, const size_t maxlen)
case '\t':
case '\n':
case '\r':
- if (len + 1 < maxlen) {
+ if (len + 1 < maxncpy) {
*dst++ = '\\';
len++;
}
@@ -296,11 +302,12 @@ char *BLI_strcasestr(const char *s, const char *find)
int BLI_strcasecmp(const char *s1, const char *s2)
{
- int i;
+ register int i;
+ register char c1, c2;
for (i = 0;; i++) {
- char c1 = tolower(s1[i]);
- char c2 = tolower(s2[i]);
+ c1 = tolower(s1[i]);
+ c2 = tolower(s2[i]);
if (c1 < c2) {
return -1;
@@ -318,11 +325,12 @@ int BLI_strcasecmp(const char *s1, const char *s2)
int BLI_strncasecmp(const char *s1, const char *s2, size_t len)
{
- int i;
+ register size_t i;
+ register char c1, c2;
for (i = 0; i < len; i++) {
- char c1 = tolower(s1[i]);
- char c2 = tolower(s2[i]);
+ c1 = tolower(s1[i]);
+ c2 = tolower(s2[i]);
if (c1 < c2) {
return -1;
@@ -341,15 +349,16 @@ int BLI_strncasecmp(const char *s1, const char *s2, size_t len)
/* natural string compare, keeping numbers in order */
int BLI_natstrcmp(const char *s1, const char *s2)
{
- int d1 = 0, d2 = 0;
+ register int d1 = 0, d2 = 0;
+ register char c1, c2;
/* if both chars are numeric, to a strtol().
* then increase string deltas as long they are
* numeric, else do a tolower and char compare */
while (1) {
- char c1 = tolower(s1[d1]);
- char c2 = tolower(s2[d2]);
+ c1 = tolower(s1[d1]);
+ c2 = tolower(s2[d2]);
if (isdigit(c1) && isdigit(c2) ) {
int val1, val2;
@@ -374,7 +383,7 @@ int BLI_natstrcmp(const char *s1, const char *s2)
c2 = tolower(s2[d2]);
}
- /* first check for '.' so "foo.bar" comes before "foo 1.bar" */
+ /* first check for '.' so "foo.bar" comes before "foo 1.bar" */
if (c1 == '.' && c2 != '.')
return -1;
if (c1 != '.' && c2 == '.')
@@ -413,27 +422,26 @@ void BLI_timestr(double _time, char *str)
}
/* determine the length of a fixed-size string */
-size_t BLI_strnlen(const char *str, size_t maxlen)
+size_t BLI_strnlen(const char *str, const size_t maxlen)
{
const char *end = memchr(str, '\0', maxlen);
return end ? (size_t) (end - str) : maxlen;
}
-void BLI_ascii_strtolower(char *str, int len)
+void BLI_ascii_strtolower(char *str, const size_t len)
{
- int i;
+ size_t i;
for (i = 0; i < len; i++)
if (str[i] >= 'A' && str[i] <= 'Z')
str[i] += 'a' - 'A';
}
-void BLI_ascii_strtoupper(char *str, int len)
+void BLI_ascii_strtoupper(char *str, const size_t len)
{
- int i;
+ size_t i;
for (i = 0; i < len; i++)
if (str[i] >= 'a' && str[i] <= 'z')
str[i] -= 'a' - 'A';
}
-
diff --git a/source/blender/blenlib/intern/string_cursor_utf8.c b/source/blender/blenlib/intern/string_cursor_utf8.c
index 422a600e51c..bab144266a4 100644
--- a/source/blender/blenlib/intern/string_cursor_utf8.c
+++ b/source/blender/blenlib/intern/string_cursor_utf8.c
@@ -147,7 +147,7 @@ void BLI_str_cursor_step_utf8(const char *str, size_t maxlen,
int *pos, strCursorJumpDirection direction,
strCursorJumpType jump)
{
- const short pos_prev = *pos;
+ const int pos_prev = *pos;
if (direction == STRCUR_DIR_NEXT) {
BLI_str_cursor_step_next_utf8(str, maxlen, pos);
diff --git a/source/blender/blenlib/intern/string_utf8.c b/source/blender/blenlib/intern/string_utf8.c
index f5c09791a68..0b737e0eff5 100644
--- a/source/blender/blenlib/intern/string_utf8.c
+++ b/source/blender/blenlib/intern/string_utf8.c
@@ -33,8 +33,12 @@
#include <string.h>
#include <wchar.h>
#include <wctype.h>
+#include <stdio.h>
+#include <stdlib.h>
-#include "BLI_string_utf8.h"
+#include "BLI_utildefines.h"
+
+#include "BLI_string_utf8.h" /* own include */
/* from libswish3, originally called u8_isvalid(),
* modified to return the index of the bad character (byte index not utf).
@@ -58,11 +62,11 @@ static const char trailingBytesForUTF8[256] = {
int BLI_utf8_invalid_byte(const char *str, int length)
{
- const unsigned char *p, *pend = (unsigned char*)str + length;
+ const unsigned char *p, *pend = (unsigned char *)str + length;
unsigned char c;
int ab;
- for (p = (unsigned char*)str; p < pend; p++) {
+ for (p = (unsigned char *)str; p < pend; p++) {
c = *p;
if (c < 128)
continue;
@@ -124,15 +128,15 @@ utf8_error:
int BLI_utf8_invalid_strip(char *str, int length)
{
- int bad_char, tot= 0;
+ int bad_char, tot = 0;
- while ((bad_char= BLI_utf8_invalid_byte(str, length)) != -1) {
+ while ((bad_char = BLI_utf8_invalid_byte(str, length)) != -1) {
str += bad_char;
length -= bad_char;
if (length == 0) {
/* last character bad, strip it */
- *str= '\0';
+ *str = '\0';
tot++;
break;
}
@@ -153,22 +157,22 @@ int BLI_utf8_invalid_strip(char *str, int length)
* note: this looks to be at odd's with 'trailingBytesForUTF8',
* need to find out what gives here! - campbell */
static const size_t utf8_skip_data[256] = {
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 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, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 1, 1
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 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, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 1, 1
};
#define BLI_STR_UTF8_CPY(dst, src, maxncpy) \
{ \
size_t utf8_size; \
- while (*src != '\0' && (utf8_size= utf8_skip_data[*src]) < maxncpy) { \
+ while (*src != '\0' && (utf8_size = utf8_skip_data[*src]) < maxncpy) {\
maxncpy -= utf8_size; \
- switch (utf8_size) { \
+ switch (utf8_size) { \
case 6: *dst ++ = *src ++; \
case 5: *dst ++ = *src ++; \
case 4: *dst ++ = *src ++; \
@@ -177,12 +181,14 @@ static const size_t utf8_skip_data[256] = {
case 1: *dst ++ = *src ++; \
} \
} \
- *dst= '\0'; \
+ *dst = '\0'; \
} (void)0
char *BLI_strncpy_utf8(char *dst, const char *src, size_t maxncpy)
{
- char *dst_r= dst;
+ char *dst_r = dst;
+
+ BLI_assert(maxncpy != 0);
/* note: currently we don't attempt to deal with invalid utf8 chars */
BLI_STR_UTF8_CPY(dst, src, maxncpy);
@@ -207,14 +213,17 @@ char *BLI_strncat_utf8(char *dst, const char *src, size_t maxncpy)
/* --------------------------------------------------------------------------*/
/* wchar_t / utf8 functions */
-size_t BLI_strncpy_wchar_as_utf8(char *dst, const wchar_t *src, const size_t maxcpy)
+size_t BLI_strncpy_wchar_as_utf8(char *dst, const wchar_t *src, const size_t maxncpy)
{
size_t len = 0;
- while (*src && len < maxcpy) { /* XXX can still run over the buffer because utf8 size isn't known :| */
+
+ BLI_assert(maxncpy != 0);
+
+ while (*src && len < maxncpy) { /* XXX can still run over the buffer because utf8 size isn't known :| */
len += BLI_str_utf8_from_unicode(*src++, dst + len);
}
- dst[len]= '\0';
+ dst[len] = '\0';
return len;
}
@@ -231,33 +240,56 @@ size_t BLI_wstrlen_utf8(const wchar_t *src)
return len;
}
-// utf8slen
+/* this is very close to 'BLI_str_utf8_size' functionality, perhaps we should de-duplicate */
+/* size of UTF-8 character in bytes */
+static size_t strlen_utf8_char(const char *strc)
+{
+ if ((*strc & 0xe0) == 0xc0) {
+ if ((strc[1] & 0x80) && (strc[1] & 0x40) == 0x00)
+ return 2;
+ }
+ else if ((*strc & 0xf0) == 0xe0) {
+ if ((strc[1] & strc[2] & 0x80) && ((strc[1] | strc[2]) & 0x40) == 0x00)
+ return 3;
+ }
+ else if ((*strc & 0xf8) == 0xf0) {
+ if ((strc[1] & strc[2] & strc[3] & 0x80) && ((strc[1] | strc[2] | strc[3]) & 0x40) == 0x00)
+ return 4;
+ }
+
+ return 1;
+}
+
size_t BLI_strlen_utf8(const char *strc)
{
- int len = 0;
+ int len;
- while (*strc) {
- if ((*strc & 0xe0) == 0xc0) {
- if ((strc[1] & 0x80) && (strc[1] & 0x40) == 0x00)
- strc++;
- }
- else if ((*strc & 0xf0) == 0xe0) {
- if ((strc[1] & strc[2] & 0x80) && ((strc[1] | strc[2]) & 0x40) == 0x00)
- strc += 2;
- }
- else if ((*strc & 0xf8) == 0xf0) {
- if ((strc[1] & strc[2] & strc[3] & 0x80) && ((strc[1] | strc[2] | strc[3]) & 0x40) == 0x00)
- strc += 3;
- }
+ for (len = 0; *strc; len++)
+ strc += strlen_utf8_char(strc);
- strc++;
- len++;
+ return len;
+}
+
+/**
+ * \param start the string to measure the length.
+ * \param maxlen the string length (in bytes)
+ * \return the unicode length (not in bytes!)
+ */
+size_t BLI_strnlen_utf8(const char *start, const size_t maxlen)
+{
+ const char *strc = start;
+ const char *strc_end = start + maxlen;
+
+ size_t len;
+
+ for (len = 0; *strc && strc < strc_end; len++) {
+ strc += strlen_utf8_char(strc);
}
return len;
}
-size_t BLI_strncpy_wchar_from_utf8(wchar_t *dst_w, const char *src_c, const size_t maxcpy)
+size_t BLI_strncpy_wchar_from_utf8(wchar_t *dst_w, const char *src_c, const size_t maxncpy)
{
int len = 0;
@@ -265,16 +297,16 @@ size_t BLI_strncpy_wchar_from_utf8(wchar_t *dst_w, const char *src_c, const size
return 0;
}
- while (*src_c && len < maxcpy) {
- size_t step= 0;
- unsigned int unicode= BLI_str_utf8_as_unicode_and_size(src_c, &step);
+ while (*src_c && len < maxncpy) {
+ size_t step = 0;
+ unsigned int unicode = BLI_str_utf8_as_unicode_and_size(src_c, &step);
if (unicode != BLI_UTF8_ERR) {
- *dst_w= (wchar_t)unicode;
+ *dst_w = (wchar_t)unicode;
src_c += step;
}
else {
*dst_w = '?';
- src_c= BLI_str_find_next_char_utf8(src_c, NULL);
+ src_c = BLI_str_find_next_char_utf8(src_c, NULL);
}
dst_w++;
len++;
@@ -397,13 +429,13 @@ unsigned int BLI_str_utf8_as_unicode_step(const char *p, size_t *index)
unsigned char c;
p += *index;
- c= (unsigned char) *p;
+ c = (unsigned char) *p;
UTF8_COMPUTE (c, mask, len);
if (len == -1) {
/* when called with NULL end, result will never be NULL,
* checks for a NULL character */
- char *p_next= BLI_str_find_next_char_utf8(p, NULL);
+ char *p_next = BLI_str_find_next_char_utf8(p, NULL);
/* will never return the same pointer unless '\0',
* eternal loop is prevented */
*index += (size_t)(p_next - p);
@@ -420,8 +452,8 @@ unsigned int BLI_str_utf8_as_unicode_step(const char *p, size_t *index)
* characters */
UTF8_GET (result, p, i, mask, len, BLI_UTF8_ERR);
if (result == BLI_UTF8_ERR) {
- len= 1;
- result= *p;
+ len = 1;
+ result = *p;
}
/* end warning! */
#else
diff --git a/source/blender/blenlib/intern/time.c b/source/blender/blenlib/intern/time.c
index bf9720fee09..078fc2c295b 100644
--- a/source/blender/blenlib/intern/time.c
+++ b/source/blender/blenlib/intern/time.c
@@ -44,7 +44,7 @@ double PIL_check_seconds_timer(void)
__int64 ifreq;
hasperfcounter = QueryPerformanceFrequency((LARGE_INTEGER *) &ifreq);
perffreq = (double) ifreq;
- }
+ }
if (hasperfcounter) {
__int64 count;
diff --git a/source/blender/blenlib/intern/uvproject.c b/source/blender/blenlib/intern/uvproject.c
index 1b59dc6a3f5..05ebc9500a1 100644
--- a/source/blender/blenlib/intern/uvproject.c
+++ b/source/blender/blenlib/intern/uvproject.c
@@ -105,7 +105,7 @@ void BLI_uvproject_from_view(float target[2], float source[3], float persmat[4][
/* rotmat is the object matrix in this case */
mul_m4_v4(rotmat, pv4);
- /* almost project_short */
+ /* almost ED_view3d_project_short */
mul_m4_v4(persmat, pv4);
if (fabsf(pv4[3]) > 0.00001f) { /* avoid division by zero */
target[0] = winx / 2.0f + (winx / 2.0f) * pv4[0] / pv4[3];
diff --git a/source/blender/blenlib/intern/voronoi.c b/source/blender/blenlib/intern/voronoi.c
index 3030e54eb78..0d411038b3e 100644
--- a/source/blender/blenlib/intern/voronoi.c
+++ b/source/blender/blenlib/intern/voronoi.c
@@ -39,7 +39,7 @@
#include "BLI_voronoi.h"
#include "BLI_utildefines.h"
-#define VORONOI_EPS 1e-2
+#define VORONOI_EPS 1e-2f
enum {
voronoiEventType_Site = 0,
@@ -259,9 +259,9 @@ static float voronoi_getXOfEdge(VoronoiProcess *process, VoronoiParabola *par, f
x2 = (-b - sqrtf(disc)) / (2 * a);
if (p[1] < r[1])
- ry = maxf(x1, x2);
+ ry = max_ff(x1, x2);
else
- ry = minf(x1, x2);
+ ry = min_ff(x1, x2);
return ry;
}
@@ -490,9 +490,9 @@ static void voronoi_finishEdge(VoronoiProcess *process, VoronoiParabola *parabol
}
if (parabola->edge->direction[0] > 0.0f)
- mx = MAX2(process->width, parabola->edge->start[0] + 10);
+ mx = max_ff(process->width, parabola->edge->start[0] + 10);
else
- mx = MIN2(0.0, parabola->edge->start[0] - 10);
+ mx = min_ff(0.0f, parabola->edge->start[0] - 10.0f);
parabola->edge->end[0] = mx;
parabola->edge->end[1] = mx * parabola->edge->f + parabola->edge->g;
diff --git a/source/blender/blenlib/intern/voxel.c b/source/blender/blenlib/intern/voxel.c
index bc775cb8f0c..5d58f9e9231 100644
--- a/source/blender/blenlib/intern/voxel.c
+++ b/source/blender/blenlib/intern/voxel.c
@@ -117,19 +117,19 @@ float BLI_voxel_sample_triquadratic(float *data, const int res[3], const float c
const int zc[3] = {res[0] * res[1] * _clamp(z - 1, 0, res[2] - 1), res[0] * res[1] * _clamp(z, 0, res[2] - 1), res[0] * res[1] * _clamp(z + 1, 0, res[2] - 1)};
const float dx = xf - (float)x, dy = yf - (float)y, dz = zf - (float)z;
- const float u[3] = {dx*(0.5f*dx - 1.f) + 0.5f, dx*(1.f - dx) + 0.5f, 0.5f*dx*dx};
- const float v[3] = {dy*(0.5f*dy - 1.f) + 0.5f, dy*(1.f - dy) + 0.5f, 0.5f*dy*dy};
- const float w[3] = {dz*(0.5f*dz - 1.f) + 0.5f, dz*(1.f - dz) + 0.5f, 0.5f*dz*dz};
+ const float u[3] = {dx * (0.5f * dx - 1.f) + 0.5f, dx * (1.0f - dx) + 0.5f, 0.5f * dx * dx};
+ const float v[3] = {dy * (0.5f * dy - 1.f) + 0.5f, dy * (1.0f - dy) + 0.5f, 0.5f * dy * dy};
+ const float w[3] = {dz * (0.5f * dz - 1.f) + 0.5f, dz * (1.0f - dz) + 0.5f, 0.5f * dz * dz};
return w[0] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[0]] + u[1] * data[xc[1] + yc[0] + zc[0]] + u[2] * data[xc[2] + yc[0] + zc[0]] )
- + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[0]] + u[1] * data[xc[1] + yc[1] + zc[0]] + u[2] * data[xc[2] + yc[1] + zc[0]] )
- + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[0]] + u[1] * data[xc[1] + yc[2] + zc[0]] + u[2] * data[xc[2] + yc[2] + zc[0]] ) )
- + w[1] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[1]] + u[1] * data[xc[1] + yc[0] + zc[1]] + u[2] * data[xc[2] + yc[0] + zc[1]] )
- + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[1]] + u[1] * data[xc[1] + yc[1] + zc[1]] + u[2] * data[xc[2] + yc[1] + zc[1]] )
- + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[1]] + u[1] * data[xc[1] + yc[2] + zc[1]] + u[2] * data[xc[2] + yc[2] + zc[1]] ) )
- + w[2] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[2]] + u[1] * data[xc[1] + yc[0] + zc[2]] + u[2] * data[xc[2] + yc[0] + zc[2]] )
- + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[2]] + u[1] * data[xc[1] + yc[1] + zc[2]] + u[2] * data[xc[2] + yc[1] + zc[2]] )
- + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[2]] + u[1] * data[xc[1] + yc[2] + zc[2]] + u[2] * data[xc[2] + yc[2] + zc[2]] ) );
+ + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[0]] + u[1] * data[xc[1] + yc[1] + zc[0]] + u[2] * data[xc[2] + yc[1] + zc[0]] )
+ + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[0]] + u[1] * data[xc[1] + yc[2] + zc[0]] + u[2] * data[xc[2] + yc[2] + zc[0]] ) )
+ + w[1] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[1]] + u[1] * data[xc[1] + yc[0] + zc[1]] + u[2] * data[xc[2] + yc[0] + zc[1]] )
+ + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[1]] + u[1] * data[xc[1] + yc[1] + zc[1]] + u[2] * data[xc[2] + yc[1] + zc[1]] )
+ + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[1]] + u[1] * data[xc[1] + yc[2] + zc[1]] + u[2] * data[xc[2] + yc[2] + zc[1]] ) )
+ + w[2] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[2]] + u[1] * data[xc[1] + yc[0] + zc[2]] + u[2] * data[xc[2] + yc[0] + zc[2]] )
+ + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[2]] + u[1] * data[xc[1] + yc[1] + zc[2]] + u[2] * data[xc[2] + yc[1] + zc[2]] )
+ + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[2]] + u[1] * data[xc[1] + yc[2] + zc[2]] + u[2] * data[xc[2] + yc[2] + zc[2]] ) );
}
return 0.f;
@@ -179,21 +179,21 @@ float BLI_voxel_sample_tricubic(float *data, const int res[3], const float co[3]
}
return w[0] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[0]] + u[1] * data[xc[1] + yc[0] + zc[0]] + u[2] * data[xc[2] + yc[0] + zc[0]] + u[3] * data[xc[3] + yc[0] + zc[0]] )
- + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[0]] + u[1] * data[xc[1] + yc[1] + zc[0]] + u[2] * data[xc[2] + yc[1] + zc[0]] + u[3] * data[xc[3] + yc[1] + zc[0]] )
- + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[0]] + u[1] * data[xc[1] + yc[2] + zc[0]] + u[2] * data[xc[2] + yc[2] + zc[0]] + u[3] * data[xc[3] + yc[2] + zc[0]] )
- + v[3] * ( u[0] * data[xc[0] + yc[3] + zc[0]] + u[1] * data[xc[1] + yc[3] + zc[0]] + u[2] * data[xc[2] + yc[3] + zc[0]] + u[3] * data[xc[3] + yc[3] + zc[0]] ) )
- + w[1] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[1]] + u[1] * data[xc[1] + yc[0] + zc[1]] + u[2] * data[xc[2] + yc[0] + zc[1]] + u[3] * data[xc[3] + yc[0] + zc[1]] )
- + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[1]] + u[1] * data[xc[1] + yc[1] + zc[1]] + u[2] * data[xc[2] + yc[1] + zc[1]] + u[3] * data[xc[3] + yc[1] + zc[1]] )
- + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[1]] + u[1] * data[xc[1] + yc[2] + zc[1]] + u[2] * data[xc[2] + yc[2] + zc[1]] + u[3] * data[xc[3] + yc[2] + zc[1]] )
- + v[3] * ( u[0] * data[xc[0] + yc[3] + zc[1]] + u[1] * data[xc[1] + yc[3] + zc[1]] + u[2] * data[xc[2] + yc[3] + zc[1]] + u[3] * data[xc[3] + yc[3] + zc[1]] ) )
- + w[2] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[2]] + u[1] * data[xc[1] + yc[0] + zc[2]] + u[2] * data[xc[2] + yc[0] + zc[2]] + u[3] * data[xc[3] + yc[0] + zc[2]] )
- + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[2]] + u[1] * data[xc[1] + yc[1] + zc[2]] + u[2] * data[xc[2] + yc[1] + zc[2]] + u[3] * data[xc[3] + yc[1] + zc[2]] )
- + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[2]] + u[1] * data[xc[1] + yc[2] + zc[2]] + u[2] * data[xc[2] + yc[2] + zc[2]] + u[3] * data[xc[3] + yc[2] + zc[2]] )
- + v[3] * ( u[0] * data[xc[0] + yc[3] + zc[2]] + u[1] * data[xc[1] + yc[3] + zc[2]] + u[2] * data[xc[2] + yc[3] + zc[2]] + u[3] * data[xc[3] + yc[3] + zc[2]] ) )
- + w[3] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[3]] + u[1] * data[xc[1] + yc[0] + zc[3]] + u[2] * data[xc[2] + yc[0] + zc[3]] + u[3] * data[xc[3] + yc[0] + zc[3]] )
- + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[3]] + u[1] * data[xc[1] + yc[1] + zc[3]] + u[2] * data[xc[2] + yc[1] + zc[3]] + u[3] * data[xc[3] + yc[1] + zc[3]] )
- + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[3]] + u[1] * data[xc[1] + yc[2] + zc[3]] + u[2] * data[xc[2] + yc[2] + zc[3]] + u[3] * data[xc[3] + yc[2] + zc[3]] )
- + v[3] * ( u[0] * data[xc[0] + yc[3] + zc[3]] + u[1] * data[xc[1] + yc[3] + zc[3]] + u[2] * data[xc[2] + yc[3] + zc[3]] + u[3] * data[xc[3] + yc[3] + zc[3]] ) );
+ + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[0]] + u[1] * data[xc[1] + yc[1] + zc[0]] + u[2] * data[xc[2] + yc[1] + zc[0]] + u[3] * data[xc[3] + yc[1] + zc[0]] )
+ + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[0]] + u[1] * data[xc[1] + yc[2] + zc[0]] + u[2] * data[xc[2] + yc[2] + zc[0]] + u[3] * data[xc[3] + yc[2] + zc[0]] )
+ + v[3] * ( u[0] * data[xc[0] + yc[3] + zc[0]] + u[1] * data[xc[1] + yc[3] + zc[0]] + u[2] * data[xc[2] + yc[3] + zc[0]] + u[3] * data[xc[3] + yc[3] + zc[0]] ) )
+ + w[1] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[1]] + u[1] * data[xc[1] + yc[0] + zc[1]] + u[2] * data[xc[2] + yc[0] + zc[1]] + u[3] * data[xc[3] + yc[0] + zc[1]] )
+ + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[1]] + u[1] * data[xc[1] + yc[1] + zc[1]] + u[2] * data[xc[2] + yc[1] + zc[1]] + u[3] * data[xc[3] + yc[1] + zc[1]] )
+ + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[1]] + u[1] * data[xc[1] + yc[2] + zc[1]] + u[2] * data[xc[2] + yc[2] + zc[1]] + u[3] * data[xc[3] + yc[2] + zc[1]] )
+ + v[3] * ( u[0] * data[xc[0] + yc[3] + zc[1]] + u[1] * data[xc[1] + yc[3] + zc[1]] + u[2] * data[xc[2] + yc[3] + zc[1]] + u[3] * data[xc[3] + yc[3] + zc[1]] ) )
+ + w[2] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[2]] + u[1] * data[xc[1] + yc[0] + zc[2]] + u[2] * data[xc[2] + yc[0] + zc[2]] + u[3] * data[xc[3] + yc[0] + zc[2]] )
+ + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[2]] + u[1] * data[xc[1] + yc[1] + zc[2]] + u[2] * data[xc[2] + yc[1] + zc[2]] + u[3] * data[xc[3] + yc[1] + zc[2]] )
+ + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[2]] + u[1] * data[xc[1] + yc[2] + zc[2]] + u[2] * data[xc[2] + yc[2] + zc[2]] + u[3] * data[xc[3] + yc[2] + zc[2]] )
+ + v[3] * ( u[0] * data[xc[0] + yc[3] + zc[2]] + u[1] * data[xc[1] + yc[3] + zc[2]] + u[2] * data[xc[2] + yc[3] + zc[2]] + u[3] * data[xc[3] + yc[3] + zc[2]] ) )
+ + w[3] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[3]] + u[1] * data[xc[1] + yc[0] + zc[3]] + u[2] * data[xc[2] + yc[0] + zc[3]] + u[3] * data[xc[3] + yc[0] + zc[3]] )
+ + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[3]] + u[1] * data[xc[1] + yc[1] + zc[3]] + u[2] * data[xc[2] + yc[1] + zc[3]] + u[3] * data[xc[3] + yc[1] + zc[3]] )
+ + v[2] * ( u[0] * data[xc[0] + yc[2] + zc[3]] + u[1] * data[xc[1] + yc[2] + zc[3]] + u[2] * data[xc[2] + yc[2] + zc[3]] + u[3] * data[xc[3] + yc[2] + zc[3]] )
+ + v[3] * ( u[0] * data[xc[0] + yc[3] + zc[3]] + u[1] * data[xc[1] + yc[3] + zc[3]] + u[2] * data[xc[2] + yc[3] + zc[3]] + u[3] * data[xc[3] + yc[3] + zc[3]] ) );
}
return 0.f;
diff --git a/source/blender/blenlib/intern/winstuff.c b/source/blender/blenlib/intern/winstuff.c
index a0b31f8d5b8..68d9d74cca4 100644
--- a/source/blender/blenlib/intern/winstuff.c
+++ b/source/blender/blenlib/intern/winstuff.c
@@ -293,7 +293,7 @@ void get_default_root(char *root)
root[3] = '\0';
if (GetFileAttributes(root) != 0xFFFFFFFF) {
rc = i;
- break;
+ break;
}
}
}
@@ -304,7 +304,7 @@ void get_default_root(char *root)
root[2] = '\\';
root[3] = '\0';
}
- }
+ }
}
}
diff --git a/source/blender/blenloader/CMakeLists.txt b/source/blender/blenloader/CMakeLists.txt
index 74df5211dad..3c5812fa513 100644
--- a/source/blender/blenloader/CMakeLists.txt
+++ b/source/blender/blenloader/CMakeLists.txt
@@ -25,6 +25,7 @@
set(INC
.
+ ../blenfont
../blenkernel
../blenlib
../makesdna
@@ -62,4 +63,8 @@ if(WITH_BUILDINFO)
add_definitions(-DWITH_BUILDINFO)
endif()
+if(WITH_INTERNATIONAL)
+ add_definitions(-DWITH_INTERNATIONAL)
+endif()
+
blender_add_lib(bf_blenloader "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/blenloader/SConscript b/source/blender/blenloader/SConscript
index 20b560744b3..49e8869637e 100644
--- a/source/blender/blenloader/SConscript
+++ b/source/blender/blenloader/SConscript
@@ -3,7 +3,7 @@ Import ('env')
sources = env.Glob('intern/*.c')
-incs = '. #/intern/guardedalloc ../blenlib ../blenkernel'
+incs = '. #/intern/guardedalloc ../blenfont ../blenlib ../blenkernel'
incs += ' ../makesdna ../editors/include'
incs += ' ../render/extern/include ../makesrna ../nodes ../bmesh ../imbuf'
@@ -11,6 +11,9 @@ incs += ' ' + env['BF_ZLIB_INC']
defs = []
+if env['WITH_BF_INTERNATIONAL']:
+ defs.append('WITH_INTERNATIONAL')
+
if env['OURPLATFORM'] in ('win32-vc', 'win64-vc'):
env.BlenderLib ( 'bf_blenloader', sources, Split(incs), defs, libtype=['core','player'], priority = [167,30]) #, cc_compileflags=['/WX'] )
else:
diff --git a/source/blender/blenloader/intern/readblenentry.c b/source/blender/blenloader/intern/readblenentry.c
index e917ccdf342..e9caa337129 100644
--- a/source/blender/blenloader/intern/readblenentry.c
+++ b/source/blender/blenloader/intern/readblenentry.c
@@ -175,7 +175,7 @@ LinkNode *BLO_blendhandle_get_previews(BlendHandle *bh, int ofblocktype, int *to
else if (bhead->code == DATA) {
if (looking) {
if (bhead->SDNAnr == DNA_struct_find_nr(fd->filesdna, "PreviewImage") ) {
- prv = BLO_library_read_struct(fd, bhead, "PreviewImage");
+ prv = BLO_library_read_struct(fd, bhead, "PreviewImage");
if (prv) {
memcpy(new_prv, prv, sizeof(PreviewImage));
if (prv->rect[0]) {
@@ -183,7 +183,7 @@ LinkNode *BLO_blendhandle_get_previews(BlendHandle *bh, int ofblocktype, int *to
new_prv->rect[0] = MEM_callocN(new_prv->w[0] * new_prv->h[0] * sizeof(unsigned int), "prvrect");
bhead = blo_nextbhead(fd, bhead);
rect = (unsigned int *)(bhead + 1);
- memcpy(new_prv->rect[0], rect, bhead->len);
+ memcpy(new_prv->rect[0], rect, bhead->len);
}
else {
new_prv->rect[0] = NULL;
@@ -194,7 +194,7 @@ LinkNode *BLO_blendhandle_get_previews(BlendHandle *bh, int ofblocktype, int *to
new_prv->rect[1] = MEM_callocN(new_prv->w[1] * new_prv->h[1] * sizeof(unsigned int), "prvrect");
bhead = blo_nextbhead(fd, bhead);
rect = (unsigned int *)(bhead + 1);
- memcpy(new_prv->rect[1], rect, bhead->len);
+ memcpy(new_prv->rect[1], rect, bhead->len);
}
else {
new_prv->rect[1] = NULL;
@@ -265,10 +265,10 @@ BlendFileData *BLO_read_from_file(const char *filepath, ReportList *reports)
if (fd) {
fd->reports = reports;
bfd = blo_read_file_internal(fd, filepath);
- blo_freefiledata(fd);
+ blo_freefiledata(fd);
}
- return bfd;
+ return bfd;
}
BlendFileData *BLO_read_from_memory(void *mem, int memsize, ReportList *reports)
@@ -280,10 +280,10 @@ BlendFileData *BLO_read_from_memory(void *mem, int memsize, ReportList *reports)
if (fd) {
fd->reports = reports;
bfd = blo_read_file_internal(fd, "");
- blo_freefiledata(fd);
+ blo_freefiledata(fd);
}
- return bfd;
+ return bfd;
}
BlendFileData *BLO_read_from_memfile(Main *oldmain, const char *filename, MemFile *memfile, ReportList *reports)
@@ -332,10 +332,10 @@ BlendFileData *BLO_read_from_memfile(Main *oldmain, const char *filename, MemFil
}
blo_join_main(&mainlist);
- blo_freefiledata(fd);
+ blo_freefiledata(fd);
}
- return bfd;
+ return bfd;
}
void BLO_blendfiledata_free(BlendFileData *bfd)
diff --git a/source/blender/blenloader/intern/readfile.c b/source/blender/blenloader/intern/readfile.c
index 8656812f90f..2ea3fb75709 100644
--- a/source/blender/blenloader/intern/readfile.c
+++ b/source/blender/blenloader/intern/readfile.c
@@ -105,6 +105,8 @@
#include "BLI_math.h"
#include "BLI_edgehash.h"
+#include "BLF_translation.h"
+
#include "BKE_anim.h"
#include "BKE_action.h"
#include "BKE_armature.h"
@@ -133,7 +135,7 @@
#include "BKE_paint.h"
#include "BKE_particle.h"
#include "BKE_pointcache.h"
-#include "BKE_property.h" // for get_ob_property
+#include "BKE_property.h" // for BKE_bproperty_object_get
#include "BKE_report.h"
#include "BKE_sca.h" // for init_actuator
#include "BKE_scene.h"
@@ -206,7 +208,7 @@
* - join all Mains
* - link all LibBlocks and indirect pointers to libblocks
* - initialize FileGlobal and copy pointers to Global
-*/
+ */
/* also occurs in library.c */
/* GS reads the memory pointed at in a specific ordering. There are,
@@ -248,6 +250,12 @@ static void convert_tface_mt(FileData *fd, Main *main);
* bit kludge but better then doubling up on prints,
* we could alternatively have a versions of a report function which forces printing - campbell
*/
+
+static void BKE_reportf_wrap(ReportList *reports, ReportType type, const char *format, ...)
+#ifdef __GNUC__
+__attribute__ ((format(printf, 3, 4)))
+#endif
+;
static void BKE_reportf_wrap(ReportList *reports, ReportType type, const char *format, ...)
{
char fixed_buf[1024]; /* should be long enough */
@@ -810,7 +818,7 @@ static void decode_blender_header(FileData *fd)
/* is the file saved in a different endian
* than we need ?
*/
- if (((((char*)&remove_this_endian_test)[0]==1)?L_ENDIAN:B_ENDIAN) != ((header[8]=='v')?L_ENDIAN:B_ENDIAN)) {
+ if (((((char *)&remove_this_endian_test)[0] == 1) ? L_ENDIAN : B_ENDIAN) != ((header[8] == 'v') ? L_ENDIAN : B_ENDIAN)) {
fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
}
@@ -932,7 +940,7 @@ static int fd_read_from_memfile(FileData *filedata, void *buffer, unsigned int s
if (chunkoffset+readsize > chunk->size)
readsize= chunk->size-chunkoffset;
- memcpy((char*)buffer + totread, chunk->buf + chunkoffset, readsize);
+ memcpy((char *)buffer + totread, chunk->buf + chunkoffset, readsize);
totread += readsize;
filedata->seek += readsize;
seek += readsize;
@@ -970,13 +978,13 @@ static FileData *blo_decode_and_check(FileData *fd, ReportList *reports)
if (fd->flags & FD_FLAGS_FILE_OK) {
if (!read_file_dna(fd)) {
- BKE_reportf(reports, RPT_ERROR, "Failed to read blend file: \"%s\", incomplete", fd->relabase);
+ BKE_reportf(reports, RPT_ERROR, "Failed to read blend file '%s', incomplete", fd->relabase);
blo_freefiledata(fd);
fd = NULL;
}
- }
+ }
else {
- BKE_reportf(reports, RPT_ERROR, "Failed to read blend file: \"%s\", not a blend file", fd->relabase);
+ BKE_reportf(reports, RPT_ERROR, "Failed to read blend file '%s', not a blend file", fd->relabase);
blo_freefiledata(fd);
fd = NULL;
}
@@ -993,7 +1001,8 @@ FileData *blo_openblenderfile(const char *filepath, ReportList *reports)
gzfile = BLI_gzopen(filepath, "rb");
if (gzfile == (gzFile)Z_NULL) {
- BKE_reportf(reports, RPT_ERROR, "Unable to open \"%s\": %s.", filepath, errno ? strerror(errno) : "Unknown error reading file");
+ BKE_reportf(reports, RPT_WARNING, "Unable to open '%s': %s",
+ filepath, errno ? strerror(errno) : TIP_("unknown error reading file"));
return NULL;
}
else {
@@ -1011,7 +1020,7 @@ FileData *blo_openblenderfile(const char *filepath, ReportList *reports)
FileData *blo_openblendermemory(void *mem, int memsize, ReportList *reports)
{
if (!mem || memsize<SIZEOFBLENDERHEADER) {
- BKE_report(reports, RPT_ERROR, (mem)? "Unable to read": "Unable to open");
+ BKE_report(reports, RPT_WARNING, (mem) ? TIP_("Unable to read"): TIP_("Unable to open"));
return NULL;
}
else {
@@ -1028,7 +1037,7 @@ FileData *blo_openblendermemory(void *mem, int memsize, ReportList *reports)
FileData *blo_openblendermemfile(MemFile *memfile, ReportList *reports)
{
if (!memfile) {
- BKE_report(reports, RPT_ERROR, "Unable to open blend <memory>");
+ BKE_report(reports, RPT_WARNING, "Unable to open blend <memory>");
return NULL;
}
else {
@@ -1120,7 +1129,7 @@ int BLO_is_a_library(const char *path, char *dir, char *group)
/* the last part of the dir is a .blend file, no group follows */
*fd = '/'; /* put back the removed slash separating the dir and the .blend file name */
}
- else {
+ else {
char *gp = fd + 1; // in case we have a .blend file, gp points to the group
/* Find the last slash */
@@ -1284,6 +1293,7 @@ void blo_end_image_pointer_map(FileData *fd, Main *oldmain)
if (NULL == newimaadr(fd, ibuf)) { /* so was restored */
BLI_remlink(&ima->ibufs, ibuf);
ima->bindcode = 0;
+ ima->tpageflag &= ~IMA_GLBIND_IS_DATA;
ima->gputexture = NULL;
}
}
@@ -1622,6 +1632,19 @@ static void IDP_LibLinkProperty(IDProperty *UNUSED(prop), int UNUSED(switch_endi
{
}
+/* ************ READ ID *************** */
+
+static void direct_link_id(FileData *fd, ID *id)
+{
+ /*link direct data of ID properties*/
+ if (id->properties) {
+ id->properties = newdataadr(fd, id->properties);
+ if (id->properties) { /* this case means the data was written incorrectly, it should not happen */
+ IDP_DirectLinkProperty(id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ }
+ }
+}
+
/* ************ READ CurveMapping *************** */
/* cuma itself has been read! */
@@ -1713,7 +1736,7 @@ static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_p
/* Legacy Data Support (for Version Patching) ----------------------------- */
-// XXX depreceated - old animation system
+// XXX deprecated - old animation system
static void lib_link_ipo(FileData *fd, Main *main)
{
Ipo *ipo;
@@ -1730,7 +1753,7 @@ static void lib_link_ipo(FileData *fd, Main *main)
}
}
-// XXX depreceated - old animation system
+// XXX deprecated - old animation system
static void direct_link_ipo(FileData *fd, Ipo *ipo)
{
IpoCurve *icu;
@@ -1744,7 +1767,7 @@ static void direct_link_ipo(FileData *fd, Ipo *ipo)
}
}
-// XXX depreceated - old animation system
+// XXX deprecated - old animation system
static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
{
bActionStrip *strip;
@@ -1759,7 +1782,7 @@ static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
}
}
-// XXX depreceated - old animation system
+// XXX deprecated - old animation system
static void direct_link_nlastrips(FileData *fd, ListBase *strips)
{
bActionStrip *strip;
@@ -1770,7 +1793,7 @@ static void direct_link_nlastrips(FileData *fd, ListBase *strips)
link_list(fd, &strip->modifiers);
}
-// XXX depreceated - old animation system
+// XXX deprecated - old animation system
static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
{
bConstraintChannel *chan;
@@ -1815,7 +1838,7 @@ static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list)
for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
DRIVER_TARGETS_LOOPER(dvar)
- {
+ {
/* only relink if still used */
if (tarIndex < dvar->num_targets)
dtar->id = newlibadr(fd, id->lib, dtar->id);
@@ -1941,12 +1964,12 @@ static void lib_link_action(FileData *fd, Main *main)
if (act->id.flag & LIB_NEED_LINK) {
act->id.flag -= LIB_NEED_LINK;
-// XXX depreceated - old animation system <<<
+// XXX deprecated - old animation system <<<
for (chan=act->chanbase.first; chan; chan=chan->next) {
chan->ipo = newlibadr_us(fd, act->id.lib, chan->ipo);
lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
}
-// >>> XXX depreceated - old animation system
+// >>> XXX deprecated - old animation system
lib_link_fcurves(fd, &act->id, &act->curves);
}
@@ -1955,21 +1978,21 @@ static void lib_link_action(FileData *fd, Main *main)
static void direct_link_action(FileData *fd, bAction *act)
{
- bActionChannel *achan; // XXX depreceated - old animation system
+ bActionChannel *achan; // XXX deprecated - old animation system
bActionGroup *agrp;
link_list(fd, &act->curves);
- link_list(fd, &act->chanbase); // XXX depreceated - old animation system
+ link_list(fd, &act->chanbase); // XXX deprecated - old animation system
link_list(fd, &act->groups);
link_list(fd, &act->markers);
-// XXX depreceated - old animation system <<<
+// XXX deprecated - old animation system <<<
for (achan = act->chanbase.first; achan; achan=achan->next) {
achan->grp = newdataadr(fd, achan->grp);
link_list(fd, &achan->constraintChannels);
}
-// >>> XXX depreceated - old animation system
+// >>> XXX deprecated - old animation system
direct_link_fcurves(fd, &act->curves);
@@ -2390,6 +2413,14 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
link_list(fd, &node->inputs);
link_list(fd, &node->outputs);
+ link_list(fd, &node->internal_links);
+ for (link = node->internal_links.first; link; link = link->next) {
+ link->fromnode = newdataadr(fd, link->fromnode);
+ link->fromsock = newdataadr(fd, link->fromsock);
+ link->tonode = newdataadr(fd, link->tonode);
+ link->tosock = newdataadr(fd, link->tosock);
+ }
+
if (node->type == CMP_NODE_MOVIEDISTORTION) {
node->storage = newmclipadr(fd, node->storage);
}
@@ -2398,8 +2429,18 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
if (node->storage) {
/* could be handlerized at some point */
- if (ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
- direct_link_curvemapping(fd, node->storage);
+ if (ntree->type==NTREE_SHADER) {
+ if (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB) {
+ direct_link_curvemapping(fd, node->storage);
+ }
+ else if (node->type==SH_NODE_SCRIPT) {
+ NodeShaderScript *nss = (NodeShaderScript *) node->storage;
+ nss->bytecode = newdataadr(fd, nss->bytecode);
+ nss->prop = newdataadr(fd, nss->prop);
+ if (nss->prop)
+ IDP_DirectLinkProperty(nss->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ }
+ }
else if (ntree->type==NTREE_COMPOSIT) {
if (ELEM4(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
direct_link_curvemapping(fd, node->storage);
@@ -2482,7 +2523,7 @@ static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
con->type = CONSTRAINT_TYPE_NULL;
}
/* own ipo, all constraints have it */
- con->ipo = newlibadr_us(fd, id->lib, con->ipo); // XXX depreceated - old animation system
+ con->ipo = newlibadr_us(fd, id->lib, con->ipo); // XXX deprecated - old animation system
}
/* relink all ID-blocks used by the constraints */
@@ -2521,8 +2562,13 @@ static void direct_link_constraints(FileData *fd, ListBase *lb)
break;
case CONSTRAINT_TYPE_KINEMATIC:
{
+ bKinematicConstraint *data = con->data;
+
con->lin_error = 0.f;
con->rot_error = 0.f;
+
+ /* version patch for runtime flag, was not cleared in some case */
+ data->flag &= ~CONSTRAINT_IK_AUTO;
}
case CONSTRAINT_TYPE_CHILDOF:
{
@@ -2641,7 +2687,7 @@ static void lib_link_camera(FileData *fd, Main *main)
if (ca->id.flag & LIB_NEED_LINK) {
if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
- ca->ipo = newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX depreceated - old animation system
+ ca->ipo = newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX deprecated - old animation system
ca->dof_ob = newlibadr_us(fd, ca->id.lib, ca->dof_ob);
@@ -2677,7 +2723,7 @@ static void lib_link_lamp(FileData *fd, Main *main)
}
}
- la->ipo = newlibadr_us(fd, la->id.lib, la->ipo); // XXX depreceated - old animation system
+ la->ipo = newlibadr_us(fd, la->id.lib, la->ipo); // XXX deprecated - old animation system
if (la->nodetree)
lib_link_ntree(fd, &la->id, la->nodetree);
@@ -2703,14 +2749,26 @@ static void direct_link_lamp(FileData *fd, Lamp *la)
direct_link_curvemapping(fd, la->curfalloff);
la->nodetree= newdataadr(fd, la->nodetree);
- if (la->nodetree)
+ if (la->nodetree) {
+ direct_link_id(fd, &la->nodetree->id);
direct_link_nodetree(fd, la->nodetree);
+ }
la->preview = direct_link_preview_image(fd, la->preview);
}
/* ************ READ keys ***************** */
+static void do_versions_key_uidgen(Key *key)
+{
+ KeyBlock *block;
+
+ key->uidgen = 1;
+ for (block = key->block.first; block; block = block->next) {
+ block->uid = key->uidgen++;
+ }
+}
+
static void lib_link_key(FileData *fd, Main *main)
{
Key *key;
@@ -2718,18 +2776,13 @@ static void lib_link_key(FileData *fd, Main *main)
for (key = main->key.first; key; key = key->id.next) {
/*check if we need to generate unique ids for the shapekeys*/
if (!key->uidgen) {
- KeyBlock *block;
-
- key->uidgen = 1;
- for (block=key->block.first; block; block=block->next) {
- block->uid = key->uidgen++;
- }
+ do_versions_key_uidgen(key);
}
if (key->id.flag & LIB_NEED_LINK) {
if (key->adt) lib_link_animdata(fd, &key->id, key->adt);
- key->ipo = newlibadr_us(fd, key->id.lib, key->ipo); // XXX depreceated - old animation system
+ key->ipo = newlibadr_us(fd, key->id.lib, key->ipo); // XXX deprecated - old animation system
key->from = newlibadr(fd, key->id.lib, key->from);
key->id.flag -= LIB_NEED_LINK;
@@ -2762,7 +2815,7 @@ static void switch_endian_keyblock(Key *key, KeyBlock *kb)
cp += 2;
}
- data+= elemsize;
+ data += elemsize;
}
}
@@ -2797,9 +2850,9 @@ static void lib_link_mball(FileData *fd, Main *main)
if (mb->adt) lib_link_animdata(fd, &mb->id, mb->adt);
for (a = 0; a < mb->totcol; a++)
- mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
+ mb->mat[a] = newlibadr_us(fd, mb->id.lib, mb->mat[a]);
- mb->ipo = newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX depreceated - old animation system
+ mb->ipo = newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX deprecated - old animation system
mb->id.flag -= LIB_NEED_LINK;
}
@@ -2835,7 +2888,7 @@ static void lib_link_world(FileData *fd, Main *main)
if (wrld->id.flag & LIB_NEED_LINK) {
if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
- wrld->ipo = newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX depreceated - old animation system
+ wrld->ipo = newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX deprecated - old animation system
for (a=0; a < MAX_MTEX; a++) {
mtex = wrld->mtex[a];
@@ -2865,8 +2918,10 @@ static void direct_link_world(FileData *fd, World *wrld)
}
wrld->nodetree = newdataadr(fd, wrld->nodetree);
- if (wrld->nodetree)
+ if (wrld->nodetree) {
+ direct_link_id(fd, &wrld->nodetree->id);
direct_link_nodetree(fd, wrld->nodetree);
+ }
wrld->preview = direct_link_preview_image(fd, wrld->preview);
}
@@ -2989,6 +3044,7 @@ static void direct_link_image(FileData *fd, Image *ima)
/* if not restored, we keep the binded opengl index */
if (ima->ibufs.first == NULL) {
ima->bindcode = 0;
+ ima->tpageflag &= ~IMA_GLBIND_IS_DATA;
ima->gputexture = NULL;
}
@@ -3032,11 +3088,11 @@ static void lib_link_curve(FileData *fd, Main *main)
cu->taperobj = newlibadr(fd, cu->id.lib, cu->taperobj);
cu->textoncurve = newlibadr(fd, cu->id.lib, cu->textoncurve);
cu->vfont = newlibadr_us(fd, cu->id.lib, cu->vfont);
- cu->vfontb = newlibadr_us(fd, cu->id.lib, cu->vfontb);
+ cu->vfontb = newlibadr_us(fd, cu->id.lib, cu->vfontb);
cu->vfonti = newlibadr_us(fd, cu->id.lib, cu->vfonti);
cu->vfontbi = newlibadr_us(fd, cu->id.lib, cu->vfontbi);
- cu->ipo = newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX depreceated - old animation system
+ cu->ipo = newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX deprecated - old animation system
cu->key = newlibadr_us(fd, cu->id.lib, cu->key);
cu->id.flag -= LIB_NEED_LINK;
@@ -3066,7 +3122,7 @@ static void direct_link_curve(FileData *fd, Curve *cu)
cu->mat = newdataadr(fd, cu->mat);
test_pointer_array(fd, (void **)&cu->mat);
cu->str = newdataadr(fd, cu->str);
- cu->strinfo= newdataadr(fd, cu->strinfo);
+ cu->strinfo= newdataadr(fd, cu->strinfo);
cu->tb = newdataadr(fd, cu->tb);
if (cu->vfont == NULL) link_list(fd, &(cu->nurb));
@@ -3077,14 +3133,14 @@ static void direct_link_curve(FileData *fd, Curve *cu)
if (cu->tb) {
memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
MEM_freeN(cu->tb);
- cu->tb = tb;
+ cu->tb = tb;
}
else {
cu->totbox = 1;
cu->actbox = 1;
cu->tb = tb;
cu->tb[0].w = cu->linewidth;
- }
+ }
if (cu->wordspace == 0.0f) cu->wordspace = 1.0f;
}
@@ -3173,8 +3229,10 @@ static void direct_link_texture(FileData *fd, Tex *tex)
tex->ot = newdataadr(fd, tex->ot);
tex->nodetree = newdataadr(fd, tex->nodetree);
- if (tex->nodetree)
+ if (tex->nodetree) {
+ direct_link_id(fd, &tex->nodetree->id);
direct_link_nodetree(fd, tex->nodetree);
+ }
tex->preview = direct_link_preview_image(fd, tex->preview);
@@ -3233,8 +3291,10 @@ static void direct_link_material(FileData *fd, Material *ma)
ma->ramp_spec = newdataadr(fd, ma->ramp_spec);
ma->nodetree = newdataadr(fd, ma->nodetree);
- if (ma->nodetree)
+ if (ma->nodetree) {
+ direct_link_id(fd, &ma->nodetree->id);
direct_link_nodetree(fd, ma->nodetree);
+ }
ma->preview = direct_link_preview_image(fd, ma->preview);
ma->gpumaterial.first = ma->gpumaterial.last = NULL;
@@ -3249,7 +3309,7 @@ static const char *ptcache_data_struct[] = {
"", // BPHYS_DATA_ROTATION
"", // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST */
"", // BPHYS_DATA_SIZE:
- "", // BPHYS_DATA_TIMES:
+ "", // BPHYS_DATA_TIMES:
"BoidData" // case BPHYS_DATA_BOIDS:
};
static void direct_link_pointcache(FileData *fd, PointCache *cache)
@@ -3324,6 +3384,8 @@ static void lib_link_partdeflect(FileData *fd, ID *id, PartDeflect *pd)
{
if (pd && pd->tex)
pd->tex = newlibadr_us(fd, id->lib, pd->tex);
+ if (pd && pd->f_source)
+ pd->f_source = newlibadr_us(fd, id->lib, pd->f_source);
}
static void lib_link_particlesettings(FileData *fd, Main *main)
@@ -3336,7 +3398,7 @@ static void lib_link_particlesettings(FileData *fd, Main *main)
for (part = main->particle.first; part; part = part->id.next) {
if (part->id.flag & LIB_NEED_LINK) {
if (part->adt) lib_link_animdata(fd, &part->id, part->adt);
- part->ipo = newlibadr_us(fd, part->id.lib, part->ipo); // XXX depreceated - old animation system
+ part->ipo = newlibadr_us(fd, part->id.lib, part->ipo); // XXX deprecated - old animation system
part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
@@ -3352,32 +3414,31 @@ static void lib_link_particlesettings(FileData *fd, Main *main)
if (part->dupliweights.first && part->dup_group) {
int index_ok = 0;
/* check for old files without indices (all indexes 0) */
- dw = part->dupliweights.first;
if (part->dupliweights.first == part->dupliweights.last) {
/* special case for only one object in the group */
index_ok = 1;
}
- else {
- for (; dw; dw=dw->next) {
+ else {
+ for (dw = part->dupliweights.first; dw; dw = dw->next) {
if (dw->index > 0) {
index_ok = 1;
break;
}
}
}
-
+
if (index_ok) {
/* if we have indexes, let's use them */
- dw = part->dupliweights.first;
- for (; dw; dw=dw->next) {
+ for (dw = part->dupliweights.first; dw; dw = dw->next) {
GroupObject *go = (GroupObject *)BLI_findlink(&part->dup_group->gobject, dw->index);
- dw->ob = go ? go->ob : NULL;
+ dw->ob = go ? newlibadr(fd, part->id.lib, dw->ob) : NULL;
}
}
else {
/* otherwise try to get objects from own library (won't work on library linked groups) */
- for (; dw; dw=dw->next)
+ for (dw = part->dupliweights.first; dw; dw = dw->next) {
dw->ob = newlibadr(fd, part->id.lib, dw->ob);
+ }
}
}
else {
@@ -3556,10 +3617,10 @@ static void direct_link_particlesystems(FileData *fd, ListBase *particles)
psys->clmd->clothObject = NULL;
psys->clmd->sim_parms= newdataadr(fd, psys->clmd->sim_parms);
- psys->clmd->sim_parms->effector_weights = NULL;
psys->clmd->coll_parms= newdataadr(fd, psys->clmd->coll_parms);
if (psys->clmd->sim_parms) {
+ psys->clmd->sim_parms->effector_weights = NULL;
if (psys->clmd->sim_parms->presets > 10)
psys->clmd->sim_parms->presets = 0;
}
@@ -3594,7 +3655,7 @@ static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
{
- int i;
+ int i;
for (i = 0; i < fdata->totlayer; i++) {
CustomDataLayer *layer = &fdata->layers[i];
@@ -3613,12 +3674,13 @@ static void lib_link_customdata_mtpoly(FileData *fd, Mesh *me, CustomData *pdata
if (layer->type == CD_MTEXPOLY) {
MTexPoly *tf= layer->data;
- int i;
+ int j;
- for (i = 0; i < totface; i++, tf++) {
+ for (j = 0; j < totface; j++, tf++) {
tf->tpage = newlibadr(fd, me->id.lib, tf->tpage);
- if (tf->tpage && tf->tpage->id.us==0)
+ if (tf->tpage && tf->tpage->id.us == 0) {
tf->tpage->id.us = 1;
+ }
}
}
}
@@ -3654,7 +3716,14 @@ static void lib_link_mesh(FileData *fd, Main *main)
if (me->mr && me->mr->levels.first)
lib_link_customdata_mtface(fd, me, &me->mr->fdata,
((MultiresLevel*)me->mr->levels.first)->totface);
-
+ }
+ }
+
+ /* convert texface options to material */
+ convert_tface_mt(fd, main);
+
+ for (me = main->mesh.first; me; me = me->id.next) {
+ if (me->id.flag & LIB_NEED_LINK) {
/*check if we need to convert mfaces to mpolys*/
if (me->totface && !me->totpoly) {
/* temporarily switch main so that reading from
@@ -3666,18 +3735,11 @@ static void lib_link_mesh(FileData *fd, Main *main)
G.main = gmain;
}
- }
- }
-
- /* convert texface options to material */
- convert_tface_mt(fd, main);
- for (me = main->mesh.first; me; me = me->id.next) {
- if (me->id.flag & LIB_NEED_LINK) {
/*
* Re-tessellate, even if the polys were just created from tessfaces, this
* is important because it:
- * - fill the CD_POLYINDEX layer
+ * - fill the CD_ORIGINDEX layer
* - gives consistency of tessface between loading from a file and
* converting an edited BMesh back into a mesh (i.e. it replaces
* quad tessfaces in a loaded mesh immediately, instead of lazily
@@ -3772,7 +3834,7 @@ static void direct_link_customdata(FileData *fd, CustomData *data, int count)
/* annoying workaround for bug [#31079] loading legacy files with
* no polygons _but_ have stale customdata */
if (UNLIKELY(count == 0 && data->layers == NULL && data->totlayer != 0)) {
- memset(data, 0, sizeof(*data));
+ CustomData_reset(data);
return;
}
@@ -3810,7 +3872,6 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh)
mesh->tface = newdataadr(fd, mesh->tface);
mesh->mtface = newdataadr(fd, mesh->mtface);
mesh->mcol = newdataadr(fd, mesh->mcol);
- mesh->msticky = newdataadr(fd, mesh->msticky);
mesh->dvert = newdataadr(fd, mesh->dvert);
mesh->mloopcol = newdataadr(fd, mesh->mloopcol);
mesh->mloopuv = newdataadr(fd, mesh->mloopuv);
@@ -3831,35 +3892,6 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh)
direct_link_customdata(fd, &mesh->ldata, mesh->totloop);
direct_link_customdata(fd, &mesh->pdata, mesh->totpoly);
-
-#ifdef USE_BMESH_FORWARD_COMPAT
- /* NEVER ENABLE THIS CODE INTO BMESH!
- * THIS IS FOR LOADING BMESH INTO OLDER FILES ONLY */
- mesh->mpoly = newdataadr(fd, mesh->mpoly);
- mesh->mloop = newdataadr(fd, mesh->mloop);
-
- direct_link_customdata(fd, &mesh->pdata, mesh->totpoly);
- direct_link_customdata(fd, &mesh->ldata, mesh->totloop);
-
- if (mesh->mpoly) {
- /* be clever and load polygons as mfaces */
- mesh->totface= BKE_mesh_mpoly_to_mface(&mesh->fdata, &mesh->ldata, &mesh->pdata,
- mesh->totface, mesh->totloop, mesh->totpoly);
-
- CustomData_free(&mesh->pdata, mesh->totpoly);
- memset(&mesh->pdata, 0, sizeof(CustomData));
- mesh->totpoly = 0;
-
- CustomData_free(&mesh->ldata, mesh->totloop);
- memset(&mesh->ldata, 0, sizeof(CustomData));
- mesh->totloop = 0;
-
- mesh_update_customdata_pointers(mesh);
- }
-
-#endif
-
-
mesh->bb = NULL;
mesh->edit_btmesh = NULL;
@@ -3927,7 +3959,7 @@ static void lib_link_latt(FileData *fd, Main *main)
if (lt->id.flag & LIB_NEED_LINK) {
if (lt->adt) lib_link_animdata(fd, &lt->id, lt->adt);
- lt->ipo = newlibadr_us(fd, lt->id.lib, lt->ipo); // XXX depreceated - old animation system
+ lt->ipo = newlibadr_us(fd, lt->id.lib, lt->ipo); // XXX deprecated - old animation system
lt->key = newlibadr_us(fd, lt->id.lib, lt->key);
lt->id.flag -= LIB_NEED_LINK;
@@ -3981,10 +4013,10 @@ static void lib_link_object(FileData *fd, Main *main)
if (ob->id.properties) IDP_LibLinkProperty(ob->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
if (ob->adt) lib_link_animdata(fd, &ob->id, ob->adt);
-// XXX depreceated - old animation system <<<
+// XXX deprecated - old animation system <<<
ob->ipo = newlibadr_us(fd, ob->id.lib, ob->ipo);
ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
-// >>> XXX depreceated - old animation system
+// >>> XXX deprecated - old animation system
ob->parent = newlibadr(fd, ob->id.lib, ob->parent);
ob->track = newlibadr(fd, ob->id.lib, ob->track);
@@ -4063,16 +4095,16 @@ static void lib_link_object(FileData *fd, Main *main)
lib_link_pose(fd, ob, ob->pose);
lib_link_constraints(fd, &ob->id, &ob->constraints);
-// XXX depreceated - old animation system <<<
+// XXX deprecated - old animation system <<<
lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels);
lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
-// >>> XXX depreceated - old animation system
+// >>> XXX deprecated - old animation system
for (paf = ob->effect.first; paf; paf = paf->next) {
if (paf->type == EFF_PARTICLE) {
paf->group = newlibadr_us(fd, ob->id.lib, paf->group);
}
- }
+ }
for (sens = ob->sensors.first; sens; sens = sens->next) {
for (a = 0; a < sens->totlinks; a++)
@@ -4336,10 +4368,12 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb)
if (smd->domain->ptcaches[1].first || smd->domain->point_cache[1]) {
if (smd->domain->point_cache[1]) {
PointCache *cache = newdataadr(fd, smd->domain->point_cache[1]);
- if (cache->flag & PTCACHE_FAKE_SMOKE)
- ; /* Smoke was already saved in "new format" and this cache is a fake one. */
- else
+ if (cache->flag & PTCACHE_FAKE_SMOKE) {
+ /* Smoke was already saved in "new format" and this cache is a fake one. */
+ }
+ else {
printf("High resolution smoke cache not available due to pointcache update. Please reset the simulation.\n");
+ }
BKE_ptcache_free(cache);
}
smd->domain->ptcaches[1].first = NULL;
@@ -4352,19 +4386,27 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb)
smd->coll = NULL;
smd->flow = newdataadr(fd, smd->flow);
smd->flow->smd = smd;
+ smd->flow->dm = NULL;
+ smd->flow->verts_old = NULL;
+ smd->flow->numverts = 0;
smd->flow->psys = newdataadr(fd, smd->flow->psys);
}
else if (smd->type == MOD_SMOKE_TYPE_COLL) {
smd->flow = NULL;
smd->domain = NULL;
smd->coll = newdataadr(fd, smd->coll);
- smd->coll->smd = smd;
if (smd->coll) {
- smd->coll->points = NULL;
- smd->coll->numpoints = 0;
+ smd->coll->smd = smd;
+ smd->coll->verts_old = NULL;
+ smd->coll->numverts = 0;
+ smd->coll->dm = NULL;
}
- else
+ else {
smd->type = 0;
+ smd->flow = NULL;
+ smd->domain = NULL;
+ smd->coll = NULL;
+ }
}
}
else if (md->type == eModifierType_DynamicPaint) {
@@ -4527,10 +4569,10 @@ static void direct_link_object(FileData *fd, Object *ob)
direct_link_motionpath(fd, ob->mpath);
link_list(fd, &ob->defbase);
-// XXX depreceated - old animation system <<<
+// XXX deprecated - old animation system <<<
direct_link_nlastrips(fd, &ob->nlastrips);
link_list(fd, &ob->constraintChannels);
-// >>> XXX depreceated - old animation system
+// >>> XXX deprecated - old animation system
ob->mat= newdataadr(fd, ob->mat);
test_pointer_array(fd, (void **)&ob->mat);
@@ -4594,7 +4636,7 @@ static void direct_link_object(FileData *fd, Object *ob)
direct_link_partdeflect(ob->pd);
ob->soft= newdataadr(fd, ob->soft);
if (ob->soft) {
- SoftBody *sb = ob->soft;
+ SoftBody *sb = ob->soft;
sb->bpoint = NULL; // init pointers so it gets rebuilt nicely
sb->bspring = NULL;
@@ -4771,8 +4813,7 @@ static void lib_link_scene(FileData *fd, Main *main)
base->object = newlibadr_us(fd, sce->id.lib, base->object);
if (base->object == NULL) {
- BKE_reportf_wrap(fd->reports, RPT_ERROR,
- "LIB ERROR: Object lost from scene:'%s\'",
+ BKE_reportf_wrap(fd->reports, RPT_WARNING, TIP_("LIB ERROR: object lost from scene: '%s'"),
sce->id.name + 2);
BLI_remlink(&sce->base, base);
if (base == sce->basact) sce->basact = NULL;
@@ -5038,7 +5079,7 @@ static void direct_link_scene(FileData *fd, Scene *sce)
ed->seqbasep = (ListBase *)(poin+offset);
else
ed->seqbasep = &ed->seqbase;
- }
+ }
/* stack */
link_list(fd, &(ed->metastack));
@@ -5072,7 +5113,7 @@ static void direct_link_scene(FileData *fd, Scene *sce)
}
if (sce->r.ffcodecdata.properties) {
sce->r.ffcodecdata.properties = newdataadr(fd, sce->r.ffcodecdata.properties);
- if (sce->r.ffcodecdata.properties) {
+ if (sce->r.ffcodecdata.properties) {
IDP_DirectLinkProperty(sce->r.ffcodecdata.properties,
(fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
}
@@ -5083,8 +5124,10 @@ static void direct_link_scene(FileData *fd, Scene *sce)
link_list(fd, &(sce->r.layers));
sce->nodetree = newdataadr(fd, sce->nodetree);
- if (sce->nodetree)
+ if (sce->nodetree) {
+ direct_link_id(fd, &sce->nodetree->id);
direct_link_nodetree(fd, sce->nodetree);
+ }
direct_link_view_settings(fd, &sce->view_settings);
}
@@ -5998,11 +6041,11 @@ static void direct_link_library(FileData *fd, Library *lib, Main *main)
if (newmain->curlib) {
if (BLI_path_cmp(newmain->curlib->filepath, lib->filepath) == 0) {
BKE_reportf_wrap(fd->reports, RPT_WARNING,
- "Library '%s', '%s' had multiple instances, save and reload!",
+ TIP_("Library '%s', '%s' had multiple instances, save and reload!"),
lib->name, lib->filepath);
change_idid_adr(fd->mainlist, fd, lib, newmain->curlib);
-// change_idid_adr_fd(fd, lib, newmain->curlib);
+/* change_idid_adr_fd(fd, lib, newmain->curlib); */
BLI_remlink(&main->library, lib);
MEM_freeN(lib);
@@ -6016,8 +6059,10 @@ static void direct_link_library(FileData *fd, Library *lib, Main *main)
BLI_strncpy(lib->filepath, lib->name, sizeof(lib->name));
cleanup_path(fd->relabase, lib->filepath);
-// printf("direct_link_library: name %s\n", lib->name);
-// printf("direct_link_library: filename %s\n", lib->filename);
+#if 0
+ printf("direct_link_library: name %s\n", lib->name);
+ printf("direct_link_library: filename %s\n", lib->filename);
+#endif
/* new main */
newmain= MEM_callocN(sizeof(Main), "directlink");
@@ -6120,7 +6165,7 @@ static void lib_link_sound(FileData *fd, Main *main)
for (sound = main->sound.first; sound; sound = sound->id.next) {
if (sound->id.flag & LIB_NEED_LINK) {
sound->id.flag -= LIB_NEED_LINK;
- sound->ipo = newlibadr_us(fd, sound->id.lib, sound->ipo); // XXX depreceated - old animation system
+ sound->ipo = newlibadr_us(fd, sound->id.lib, sound->ipo); // XXX deprecated - old animation system
sound_load(main, sound);
}
@@ -6283,6 +6328,14 @@ static void direct_link_mask(FileData *fd, Mask *mask)
for (masklay_shape = masklay->splines_shapes.first; masklay_shape; masklay_shape = masklay_shape->next) {
masklay_shape->data = newdataadr(fd, masklay_shape->data);
+
+ if (masklay_shape->tot_vert) {
+ if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
+ BLI_endian_switch_float_array(masklay_shape->data,
+ masklay_shape->tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
+
+ }
+ }
}
masklay->act_spline = newdataadr(fd, masklay->act_spline);
@@ -6446,6 +6499,8 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, int flag, ID
bhead = read_data_into_oldnewmap(fd, bhead, allocname);
/* init pointers direct data */
+ direct_link_id(fd, id);
+
switch (GS(id->name)) {
case ID_WM:
direct_link_windowmanager(fd, (wmWindowManager *)id);
@@ -6542,14 +6597,6 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, int flag, ID
break;
}
- /*link direct data of ID properties*/
- if (id->properties) {
- id->properties = newdataadr(fd, id->properties);
- if (id->properties) { /* this case means the data was written incorrectly, it should not happen */
- IDP_DirectLinkProperty(id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
- }
- }
-
oldnewmap_free_unused(fd->datamap);
oldnewmap_clear(fd->datamap);
@@ -6612,7 +6659,7 @@ void convert_tface_mt(FileData *fd, Main *main)
G.main = main;
if (!(do_version_tface(main, 1))) {
- BKE_report(fd->reports, RPT_WARNING, "Texface conversion problem. Error in console");
+ BKE_report(fd->reports, RPT_WARNING, "Texface conversion problem (see error in console)");
}
//XXX hack, material.c uses G.main allover the place, instead of main
@@ -6785,7 +6832,6 @@ static void do_versions_nodetree_socket_use_flags_2_62(bNodeTree *ntree)
static void do_versions_nodetree_multi_file_output_format_2_62_1(Scene *sce, bNodeTree *ntree)
{
bNode *node;
- bNodeSocket *sock;
for (node = ntree->nodes.first; node; node = node->next) {
if (node->type == CMP_NODE_OUTPUT_FILE) {
@@ -6862,6 +6908,7 @@ static void do_versions_nodetree_multi_file_output_format_2_62_1(Scene *sce, bNo
}
else if (node->type==CMP_NODE_OUTPUT_MULTI_FILE__DEPRECATED) {
NodeImageMultiFile *nimf = node->storage;
+ bNodeSocket *sock;
/* CMP_NODE_OUTPUT_MULTI_FILE has been redeclared as CMP_NODE_OUTPUT_FILE */
node->type = CMP_NODE_OUTPUT_FILE;
@@ -7015,6 +7062,20 @@ static void do_version_ntree_dilateerode_264(void *UNUSED(data), ID *UNUSED(id),
}
}
+static void do_version_ntree_defocus_264(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
+{
+ bNode *node;
+
+ for (node = ntree->nodes.first; node; node = node->next) {
+ if (node->type == CMP_NODE_DEFOCUS) {
+ NodeDefocus *data = node->storage;
+ if (data->maxblur == 0.0f) {
+ data->maxblur = 16.0f;
+ }
+ }
+ }
+}
+
static void do_version_ntree_mask_264(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
{
bNode *node;
@@ -7048,6 +7109,68 @@ static void do_version_ntree_keying_despill_balance(void *UNUSED(data), ID *UNUS
}
}
+static void do_version_ntree_tex_coord_from_dupli_264(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
+{
+ bNode *node;
+
+ for (node = ntree->nodes.first; node; node = node->next)
+ if (node->type == SH_NODE_TEX_COORD)
+ node->flag |= NODE_OPTIONS;
+}
+
+static void do_version_node_cleanup_dynamic_sockets_264(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
+{
+ bNode *node;
+ bNodeSocket *sock;
+
+ for (node = ntree->nodes.first; node; node = node->next) {
+ if (!ELEM(node->type, NODE_GROUP, CMP_NODE_IMAGE)) {
+ for (sock = node->inputs.first; sock; sock = sock->next)
+ sock->flag &= ~SOCK_DYNAMIC;
+ for (sock = node->outputs.first; sock; sock = sock->next)
+ sock->flag &= ~SOCK_DYNAMIC;
+ }
+ }
+}
+
+static void do_version_node_fix_internal_links_264(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
+{
+ bNode *node;
+ bNodeLink *link, *nextlink;
+
+ for (node = ntree->nodes.first; node; node = node->next) {
+ for (link = node->internal_links.first; link; link = nextlink) {
+ nextlink = link->next;
+ if (!link->fromnode || !link->fromsock || !link->tonode || !link->tosock) {
+ BLI_remlink(&node->internal_links, link);
+ }
+ }
+ }
+}
+
+static void do_version_logic_264(ListBase *regionbase)
+{
+ ARegion *ar;
+
+ /* view settings for logic changed */
+ for (ar = regionbase->first; ar; ar = ar->next) {
+ if (ar->regiontype == RGN_TYPE_WINDOW) {
+ if (ar->v2d.keeptot == 0) {
+ ar->v2d.maxzoom = 1.5f;
+
+ ar->v2d.keepzoom = V2D_KEEPZOOM | V2D_LIMITZOOM | V2D_KEEPASPECT;
+ ar->v2d.keeptot = V2D_KEEPTOT_BOUNDS;
+ ar->v2d.align = V2D_ALIGN_NO_POS_Y | V2D_ALIGN_NO_NEG_X;
+ ar->v2d.keepofs = V2D_KEEPOFS_Y;
+ }
+ }
+ }
+
+
+}
+
+
+
static void do_versions(FileData *fd, Library *lib, Main *main)
{
/* WATCH IT!!!: pointers from libdata have not been converted */
@@ -7161,9 +7284,9 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
v3d->bundle_drawtype = OB_PLAINAXES;
}
else if (sl->spacetype == SPACE_CLIP) {
- SpaceClip *sc = (SpaceClip *)sl;
- if (sc->scopes.track_preview_height == 0)
- sc->scopes.track_preview_height = 120;
+ SpaceClip *sclip = (SpaceClip *)sl;
+ if (sclip->scopes.track_preview_height == 0)
+ sclip->scopes.track_preview_height = 120;
}
}
}
@@ -7243,10 +7366,10 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
if ( (ob->dsize[i] == 0.0f) || /* simple case, user never touched dsize */
(ob->size[i] == 0.0f)) /* cant scale the dsize to give a non zero result, so fallback to 1.0f */
{
- ob->dscale[i]= 1.0f;
+ ob->dscale[i] = 1.0f;
}
else {
- ob->dscale[i]= (ob->size[i] + ob->dsize[i]) / ob->size[i];
+ ob->dscale[i] = (ob->size[i] + ob->dsize[i]) / ob->size[i];
}
}
}
@@ -7368,11 +7491,11 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
for (ob= main->object.first; ob; ob= ob->id.next) {
if (ob->type == OB_FONT) {
- prop = get_ob_property(ob, "Text");
+ prop = BKE_bproperty_object_get(ob, "Text");
if (prop) {
BKE_reportf_wrap(fd->reports, RPT_WARNING,
- "Game property name conflict in object: \"%s\".\nText objects reserve the "
- "[\"Text\"] game property to change their content through Logic Bricks.",
+ TIP_("Game property name conflict in object '%s':\ntext objects reserve the "
+ "['Text'] game property to change their content through logic bricks"),
ob->id.name + 2);
}
}
@@ -7565,13 +7688,8 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
if (main->versionfile < 263) {
/* Default for old files is to save particle rotations to pointcache */
ParticleSettings *part;
- for (part = main->particle.first; part; part = part->id.next)
+ for (part = main->particle.first; part; part = part->id.next) {
part->flag |= PART_ROTATIONS;
- {
- /* Default for old files is to save particle rotations to pointcache */
- ParticleSettings *part;
- for (part = main->particle.first; part; part = part->id.next)
- part->flag |= PART_ROTATIONS;
}
}
@@ -7766,6 +7884,7 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
if (main->versionfile < 263 || (main->versionfile == 263 && main->subversionfile < 10)) {
{
Scene *scene;
+ bNodeTreeType *ntreetype;
// composite redesign
for (scene=main->scene.first; scene; scene=scene->id.next) {
if (scene->nodetree) {
@@ -7774,6 +7893,11 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
}
}
}
+ ntreetype = ntreeGetType(NTREE_COMPOSIT);
+
+ if (ntreetype && ntreetype->foreach_nodetree)
+ ntreetype->foreach_nodetree(main, NULL, do_version_ntree_defocus_264);
+
}
{
@@ -7920,7 +8044,7 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
}
/* color management pipeline changes compatibility code */
- {
+ if (main->versionfile < 263 || (main->versionfile == 263 && main->subversionfile < 19)) {
Scene *scene;
Image *ima;
int colormanagement_disabled = FALSE;
@@ -7960,6 +8084,260 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
}
}
+ if (main->versionfile < 263 || (main->versionfile == 263 && main->subversionfile < 20)) {
+ Key *key;
+ for (key = main->key.first; key; key = key->id.next) {
+ do_versions_key_uidgen(key);
+ }
+ }
+
+ /* remove texco */
+ if (main->versionfile < 263 || (main->versionfile == 263 && main->subversionfile < 21)) {
+ Material *ma;
+ for (ma = main->mat.first; ma; ma = ma->id.next) {
+ int a;
+ for (a = 0; a < MAX_MTEX; a++) {
+ if (ma->mtex[a]) {
+ if (ma->mtex[a]->texco == TEXCO_STICKY_) {
+ ma->mtex[a]->texco = TEXCO_UV;
+ }
+ }
+ }
+ }
+
+ {
+ Mesh *me;
+ for (me = main->mesh.first; me; me = me->id.next) {
+ CustomData_update_typemap(&me->vdata);
+ CustomData_free_layers(&me->vdata, CD_MSTICKY, me->totvert);
+ }
+ }
+ }
+
+ /* correction for files saved in blender version when BKE_pose_copy_data
+ * didn't copy animation visualization, which lead to deadlocks on motion
+ * path calculation for proxied armatures, see [#32742]
+ */
+ if (main->versionfile < 264) {
+ Object *ob;
+
+ for (ob = main->object.first; ob; ob = ob->id.next) {
+ if (ob->pose) {
+ if (ob->pose->avs.path_step == 0) {
+ animviz_settings_init(&ob->pose->avs);
+ }
+ }
+ }
+ }
+
+ if (main->versionfile < 264 || (main->versionfile == 264 && main->subversionfile < 1)) {
+ bNodeTreeType *ntreetype = ntreeGetType(NTREE_SHADER);
+ bNodeTree *ntree;
+
+ if (ntreetype && ntreetype->foreach_nodetree)
+ ntreetype->foreach_nodetree(main, NULL, do_version_ntree_tex_coord_from_dupli_264);
+
+ for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next)
+ if (ntree->type==NTREE_SHADER)
+ do_version_ntree_tex_coord_from_dupli_264(NULL, NULL, ntree);
+ }
+
+ if (main->versionfile < 264 || (main->versionfile == 264 && main->subversionfile < 2)) {
+ MovieClip *clip;
+
+ for (clip = main->movieclip.first; clip; clip = clip->id.next) {
+ MovieTracking *tracking = &clip->tracking;
+ MovieTrackingObject *tracking_object;
+
+ for (tracking_object = tracking->objects.first;
+ tracking_object;
+ tracking_object = tracking_object->next)
+ {
+ if (tracking_object->keyframe1 == 0 && tracking_object->keyframe2 == 0) {
+ tracking_object->keyframe1 = tracking->settings.keyframe1;
+ tracking_object->keyframe2 = tracking->settings.keyframe2;
+ }
+ }
+ }
+ }
+
+ if (main->versionfile < 264 || (main->versionfile == 264 && main->subversionfile < 3)) {
+ /* smoke branch */
+ {
+ Object *ob;
+
+ for (ob = main->object.first; ob; ob = ob->id.next) {
+ ModifierData *md;
+ for (md = ob->modifiers.first; md; md = md->next) {
+ if (md->type == eModifierType_Smoke) {
+ SmokeModifierData *smd = (SmokeModifierData *)md;
+ if ((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain) {
+ /* keep branch saves if possible */
+ if (!smd->domain->flame_max_temp) {
+ smd->domain->burning_rate = 0.75f;
+ smd->domain->flame_smoke = 1.0f;
+ smd->domain->flame_vorticity = 0.5f;
+ smd->domain->flame_ignition = 1.25f;
+ smd->domain->flame_max_temp = 1.75f;
+ smd->domain->adapt_threshold = 0.02f;
+ smd->domain->adapt_margin = 4;
+ smd->domain->flame_smoke_color[0] = 0.7f;
+ smd->domain->flame_smoke_color[1] = 0.7f;
+ smd->domain->flame_smoke_color[2] = 0.7f;
+ }
+ }
+ else if ((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow) {
+ if (!smd->flow->texture_size) {
+ smd->flow->fuel_amount = 1.0;
+ smd->flow->surface_distance = 1.5;
+ smd->flow->color[0] = 0.7f;
+ smd->flow->color[1] = 0.7f;
+ smd->flow->color[2] = 0.7f;
+ smd->flow->texture_size = 1.0f;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /* render border for viewport */
+ {
+ bScreen *sc;
+
+ for (sc = main->screen.first; sc; sc = sc->id.next) {
+ ScrArea *sa;
+ for (sa = sc->areabase.first; sa; sa = sa->next) {
+ SpaceLink *sl;
+ for (sl = sa->spacedata.first; sl; sl = sl->next) {
+ if (sl->spacetype == SPACE_VIEW3D) {
+ View3D *v3d = (View3D *)sl;
+ if (v3d->render_border.xmin == 0.0f && v3d->render_border.ymin == 0.0f &&
+ v3d->render_border.xmax == 0.0f && v3d->render_border.ymax == 0.0f)
+ {
+ v3d->render_border.xmax = 1.0f;
+ v3d->render_border.ymax = 1.0f;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (main->versionfile < 264 || (main->versionfile == 264 && main->subversionfile < 4)) {
+ /* Fix for old node flags: Apparently the SOCK_DYNAMIC flag has been in use for other
+ * purposes before and then removed and later reused for SOCK_DYNAMIC. This socket should
+ * only be used by certain node types which don't use template lists, cleaning this up here.
+ */
+ bNodeTreeType *ntreetype;
+ bNodeTree *ntree;
+
+ ntreetype = ntreeGetType(NTREE_COMPOSIT);
+ if (ntreetype && ntreetype->foreach_nodetree)
+ ntreetype->foreach_nodetree(main, NULL, do_version_node_cleanup_dynamic_sockets_264);
+ ntreetype = ntreeGetType(NTREE_SHADER);
+ if (ntreetype && ntreetype->foreach_nodetree)
+ ntreetype->foreach_nodetree(main, NULL, do_version_node_cleanup_dynamic_sockets_264);
+ ntreetype = ntreeGetType(NTREE_TEXTURE);
+ if (ntreetype && ntreetype->foreach_nodetree)
+ ntreetype->foreach_nodetree(main, NULL, do_version_node_cleanup_dynamic_sockets_264);
+
+ for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next)
+ do_version_node_cleanup_dynamic_sockets_264(NULL, NULL, ntree);
+ }
+
+ if (main->versionfile < 264 || (main->versionfile == 264 && main->subversionfile < 5)) {
+ /* set a unwrapping margin and ABF by default */
+ Scene *scene;
+
+ for (scene=main->scene.first; scene; scene=scene->id.next) {
+ if (scene->toolsettings->uvcalc_margin == 0.0f) {
+ scene->toolsettings->uvcalc_margin = 0.001f;
+ scene->toolsettings->unwrapper = 0;
+ }
+ }
+ }
+
+ if (main->versionfile < 264 || (main->versionfile == 264 && main->subversionfile < 6)) {
+ /* Fix for bug #32982, internal_links list could get corrupted from r51630 onward.
+ * Simply remove bad internal_links lists to avoid NULL pointers.
+ */
+ bNodeTreeType *ntreetype;
+ bNodeTree *ntree;
+
+ ntreetype = ntreeGetType(NTREE_COMPOSIT);
+ if (ntreetype && ntreetype->foreach_nodetree)
+ ntreetype->foreach_nodetree(main, NULL, do_version_node_fix_internal_links_264);
+ ntreetype = ntreeGetType(NTREE_SHADER);
+ if (ntreetype && ntreetype->foreach_nodetree)
+ ntreetype->foreach_nodetree(main, NULL, do_version_node_fix_internal_links_264);
+ ntreetype = ntreeGetType(NTREE_TEXTURE);
+ if (ntreetype && ntreetype->foreach_nodetree)
+ ntreetype->foreach_nodetree(main, NULL, do_version_node_fix_internal_links_264);
+
+ for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next)
+ do_version_node_fix_internal_links_264(NULL, NULL, ntree);
+
+ }
+
+ if (main->versionfile < 264 || (main->versionfile == 264 && main->subversionfile < 6)) {
+ bScreen *sc;
+
+ for (sc = main->screen.first; sc; sc = sc->id.next) {
+ ScrArea *sa;
+ for (sa = sc->areabase.first; sa; sa = sa->next) {
+ SpaceLink *sl;
+ if ( sa->spacetype == SPACE_LOGIC)
+ do_version_logic_264(&sa->regionbase);
+
+ for (sl = sa->spacedata.first; sl; sl = sl->next) {
+ if (sl->spacetype == SPACE_LOGIC)
+ do_version_logic_264(&sl->regionbase);
+ }
+ }
+ }
+ }
+
+ if (main->versionfile < 264 || (main->versionfile == 264 && main->subversionfile < 7)) {
+ /* convert tiles size from resolution and number of tiles */
+ {
+ Scene *scene;
+
+ for (scene = main->scene.first; scene; scene = scene->id.next) {
+ if (scene->r.tilex == 0 || scene->r.tiley == 1) {
+ /* scene could be set for panoramic rendering, so clamp with the
+ * lowest possible tile size value
+ */
+ scene->r.tilex = max_ii(scene->r.xsch * scene->r.size / scene->r.xparts / 100, 8);
+ scene->r.tiley = max_ii(scene->r.ysch * scene->r.size / scene->r.yparts / 100, 8);
+ }
+ }
+ }
+
+ /* collision masks */
+ {
+ Object *ob;
+ for (ob = main->object.first; ob; ob = ob->id.next) {
+ if (ob->col_group == 0) {
+ ob->col_group = 0x01;
+ ob->col_mask = 0xff;
+ }
+ }
+ }
+
+ /* fallbck resection method settings */
+ {
+ MovieClip *clip;
+
+ for (clip = main->movieclip.first; clip; clip = clip->id.next) {
+ if (clip->tracking.settings.reconstruction_success_threshold == 0.0f) {
+ clip->tracking.settings.reconstruction_success_threshold = 1e-3;
+ }
+ }
+ }
+ }
+
/* WATCH IT!!!: pointers from libdata have not been converted yet here! */
/* WATCH IT 2!: Userdef struct init has to be in editors/interface/resources.c! */
@@ -7988,7 +8366,7 @@ static void lib_link_all(FileData *fd, Main *main)
lib_link_material(fd, main);
lib_link_texture(fd, main);
lib_link_image(fd, main);
- lib_link_ipo(fd, main); // XXX depreceated... still needs to be maintained for version patches still
+ lib_link_ipo(fd, main); // XXX deprecated... still needs to be maintained for version patches still
lib_link_key(fd, main);
lib_link_world(fd, main);
lib_link_lamp(fd, main);
@@ -8324,7 +8702,7 @@ static void expand_doit(FileData *fd, Main *mainvar, void *old)
-// XXX depreceated - old animation system
+// XXX deprecated - old animation system
static void expand_ipo(FileData *fd, Main *mainvar, Ipo *ipo)
{
IpoCurve *icu;
@@ -8334,7 +8712,7 @@ static void expand_ipo(FileData *fd, Main *mainvar, Ipo *ipo)
}
}
-// XXX depreceated - old animation system
+// XXX deprecated - old animation system
static void expand_constraint_channels(FileData *fd, Main *mainvar, ListBase *chanbase)
{
bConstraintChannel *chan;
@@ -8390,7 +8768,7 @@ static void expand_action(FileData *fd, Main *mainvar, bAction *act)
{
bActionChannel *chan;
- // XXX depreceated - old animation system --------------
+ // XXX deprecated - old animation system --------------
for (chan=act->chanbase.first; chan; chan=chan->next) {
expand_doit(fd, mainvar, chan->ipo);
expand_constraint_channels(fd, mainvar, &chan->constraintChannels);
@@ -8480,7 +8858,7 @@ static void expand_group(FileData *fd, Main *mainvar, Group *group)
static void expand_key(FileData *fd, Main *mainvar, Key *key)
{
- expand_doit(fd, mainvar, key->ipo); // XXX depreceated - old animation system
+ expand_doit(fd, mainvar, key->ipo); // XXX deprecated - old animation system
if (key->adt)
expand_animdata(fd, mainvar, key->adt);
@@ -8506,7 +8884,7 @@ static void expand_nodetree(FileData *fd, Main *mainvar, bNodeTree *ntree)
static void expand_texture(FileData *fd, Main *mainvar, Tex *tex)
{
expand_doit(fd, mainvar, tex->ima);
- expand_doit(fd, mainvar, tex->ipo); // XXX depreceated - old animation system
+ expand_doit(fd, mainvar, tex->ipo); // XXX deprecated - old animation system
if (tex->adt)
expand_animdata(fd, mainvar, tex->adt);
@@ -8532,7 +8910,7 @@ static void expand_material(FileData *fd, Main *mainvar, Material *ma)
}
}
- expand_doit(fd, mainvar, ma->ipo); // XXX depreceated - old animation system
+ expand_doit(fd, mainvar, ma->ipo); // XXX deprecated - old animation system
if (ma->adt)
expand_animdata(fd, mainvar, ma->adt);
@@ -8555,7 +8933,7 @@ static void expand_lamp(FileData *fd, Main *mainvar, Lamp *la)
}
}
- expand_doit(fd, mainvar, la->ipo); // XXX depreceated - old animation system
+ expand_doit(fd, mainvar, la->ipo); // XXX deprecated - old animation system
if (la->adt)
expand_animdata(fd, mainvar, la->adt);
@@ -8566,7 +8944,7 @@ static void expand_lamp(FileData *fd, Main *mainvar, Lamp *la)
static void expand_lattice(FileData *fd, Main *mainvar, Lattice *lt)
{
- expand_doit(fd, mainvar, lt->ipo); // XXX depreceated - old animation system
+ expand_doit(fd, mainvar, lt->ipo); // XXX deprecated - old animation system
expand_doit(fd, mainvar, lt->key);
if (lt->adt)
@@ -8585,7 +8963,7 @@ static void expand_world(FileData *fd, Main *mainvar, World *wrld)
}
}
- expand_doit(fd, mainvar, wrld->ipo); // XXX depreceated - old animation system
+ expand_doit(fd, mainvar, wrld->ipo); // XXX deprecated - old animation system
if (wrld->adt)
expand_animdata(fd, mainvar, wrld->adt);
@@ -8616,11 +8994,11 @@ static void expand_curve(FileData *fd, Main *mainvar, Curve *cu)
}
expand_doit(fd, mainvar, cu->vfont);
- expand_doit(fd, mainvar, cu->vfontb);
+ expand_doit(fd, mainvar, cu->vfontb);
expand_doit(fd, mainvar, cu->vfonti);
expand_doit(fd, mainvar, cu->vfontbi);
expand_doit(fd, mainvar, cu->key);
- expand_doit(fd, mainvar, cu->ipo); // XXX depreceated - old animation system
+ expand_doit(fd, mainvar, cu->ipo); // XXX deprecated - old animation system
expand_doit(fd, mainvar, cu->bevobj);
expand_doit(fd, mainvar, cu->taperobj);
expand_doit(fd, mainvar, cu->textoncurve);
@@ -8709,10 +9087,10 @@ static void expand_constraints(FileData *fd, Main *mainvar, ListBase *lb)
id_loop_constraints(lb, expand_constraint_cb, &ced);
- /* depreceated manual expansion stuff */
+ /* deprecated manual expansion stuff */
for (curcon = lb->first; curcon; curcon = curcon->next) {
if (curcon->ipo)
- expand_doit(fd, mainvar, curcon->ipo); // XXX depreceated - old animation system
+ expand_doit(fd, mainvar, curcon->ipo); // XXX deprecated - old animation system
}
}
@@ -8794,7 +9172,7 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
expand_doit(fd, mainvar, ob->gpd);
-// XXX depreceated - old animation system (for version patching only)
+// XXX deprecated - old animation system (for version patching only)
expand_doit(fd, mainvar, ob->ipo);
expand_doit(fd, mainvar, ob->action);
@@ -8805,7 +9183,7 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
expand_doit(fd, mainvar, strip->act);
expand_doit(fd, mainvar, strip->ipo);
}
-// XXX depreceated - old animation system (for version patching only)
+// XXX deprecated - old animation system (for version patching only)
if (ob->adt)
expand_animdata(fd, mainvar, ob->adt);
@@ -8977,7 +9355,7 @@ static void expand_scene(FileData *fd, Main *mainvar, Scene *sce)
static void expand_camera(FileData *fd, Main *mainvar, Camera *ca)
{
- expand_doit(fd, mainvar, ca->ipo); // XXX depreceated - old animation system
+ expand_doit(fd, mainvar, ca->ipo); // XXX deprecated - old animation system
if (ca->adt)
expand_animdata(fd, mainvar, ca->adt);
@@ -8993,7 +9371,7 @@ static void expand_speaker(FileData *fd, Main *mainvar, Speaker *spk)
static void expand_sound(FileData *fd, Main *mainvar, bSound *snd)
{
- expand_doit(fd, mainvar, snd->ipo); // XXX depreceated - old animation system
+ expand_doit(fd, mainvar, snd->ipo); // XXX deprecated - old animation system
}
static void expand_movieclip(FileData *fd, Main *mainvar, MovieClip *clip)
@@ -9096,7 +9474,7 @@ static void expand_main(FileData *fd, Main *mainvar)
expand_armature(fd, mainvar, (bArmature *)id);
break;
case ID_AC:
- expand_action(fd, mainvar, (bAction *)id); // XXX depreceated - old animation system
+ expand_action(fd, mainvar, (bAction *)id); // XXX deprecated - old animation system
break;
case ID_GR:
expand_group(fd, mainvar, (Group *)id);
@@ -9108,7 +9486,7 @@ static void expand_main(FileData *fd, Main *mainvar)
expand_brush(fd, mainvar, (Brush *)id);
break;
case ID_IP:
- expand_ipo(fd, mainvar, (Ipo *)id); // XXX depreceated - old animation system
+ expand_ipo(fd, mainvar, (Ipo *)id); // XXX deprecated - old animation system
break;
case ID_PA:
expand_particlesettings(fd, mainvar, (ParticleSettings *)id);
@@ -9438,7 +9816,7 @@ static void library_append_end(const bContext *C, Main *mainl, FileData **fd, in
if ((*fd)->flags & FD_FLAGS_SWITCH_ENDIAN) {
blo_freefiledata(*fd);
*fd = NULL;
- }
+ }
}
void BLO_library_append_end(const bContext *C, struct Main *mainl, BlendHandle** bh, int idcode, short flag)
@@ -9493,8 +9871,7 @@ static void read_libraries(FileData *basefd, ListBase *mainlist)
if (fd == NULL) {
/* printf and reports for now... its important users know this */
- BKE_reportf_wrap(basefd->reports, RPT_INFO,
- "read library: '%s', '%s'",
+ BKE_reportf_wrap(basefd->reports, RPT_INFO, TIP_("Read library: '%s', '%s'"),
mainptr->curlib->filepath, mainptr->curlib->name);
fd = blo_openblenderfile(mainptr->curlib->filepath, basefd->reports);
@@ -9547,8 +9924,7 @@ static void read_libraries(FileData *basefd, ListBase *mainlist)
else mainptr->curlib->filedata = NULL;
if (fd == NULL) {
- BKE_reportf_wrap(basefd->reports, RPT_ERROR,
- "Can't find lib '%s'",
+ BKE_reportf_wrap(basefd->reports, RPT_WARNING, TIP_("Cannot find lib '%s'"),
mainptr->curlib->filepath);
}
}
@@ -9566,8 +9942,8 @@ static void read_libraries(FileData *basefd, ListBase *mainlist)
append_id_part(fd, mainptr, id, &realid);
if (!realid) {
- BKE_reportf_wrap(fd->reports, RPT_ERROR,
- "LIB ERROR: %s:'%s' missing from '%s'",
+ BKE_reportf_wrap(fd->reports, RPT_WARNING,
+ TIP_("LIB ERROR: %s: '%s' missing from '%s'"),
BKE_idcode_to_name(GS(id->name)),
id->name+2, mainptr->curlib->filepath);
}
@@ -9598,8 +9974,8 @@ static void read_libraries(FileData *basefd, ListBase *mainlist)
idn = id->next;
if (id->flag & LIB_READ) {
BLI_remlink(lbarray[a], id);
- BKE_reportf_wrap(basefd->reports, RPT_ERROR,
- "LIB ERROR: %s:'%s' unread libblock missing from '%s'",
+ BKE_reportf_wrap(basefd->reports, RPT_WARNING,
+ TIP_("LIB ERROR: %s: '%s' unread lib block missing from '%s'"),
BKE_idcode_to_name(GS(id->name)), id->name + 2, mainptr->curlib->filepath);
change_idid_adr(mainlist, basefd, id, NULL);
diff --git a/source/blender/blenloader/intern/runtime.c b/source/blender/blenloader/intern/runtime.c
index eaf725dda9e..5d8a865eea8 100644
--- a/source/blender/blenloader/intern/runtime.c
+++ b/source/blender/blenloader/intern/runtime.c
@@ -91,7 +91,7 @@ cleanup:
if (fd != -1)
close(fd);
- return res;
+ return res;
}
BlendFileData *BLO_read_runtime(const char *path, ReportList *reports)
@@ -104,7 +104,7 @@ BlendFileData *BLO_read_runtime(const char *path, ReportList *reports)
fd = BLI_open(path, O_BINARY | O_RDONLY, 0);
if (fd == -1) {
- BKE_reportf(reports, RPT_ERROR, "Unable to open \"%s\": %s.", path, strerror(errno));
+ BKE_reportf(reports, RPT_ERROR, "Unable to open '%s': %s", path, strerror(errno));
goto cleanup;
}
@@ -115,18 +115,18 @@ BlendFileData *BLO_read_runtime(const char *path, ReportList *reports)
datastart = handle_read_msb_int(fd);
if (datastart == -1) {
- BKE_reportf(reports, RPT_ERROR, "Unable to read \"%s\" (problem seeking)", path);
+ BKE_reportf(reports, RPT_ERROR, "Unable to read '%s' (problem seeking)", path);
goto cleanup;
}
else if (read(fd, buf, 8) != 8) {
- BKE_reportf(reports, RPT_ERROR, "Unable to read \"%s\" (truncated header)", path);
+ BKE_reportf(reports, RPT_ERROR, "Unable to read '%s' (truncated header)", path);
goto cleanup;
}
else if (memcmp(buf, "BRUNTIME", 8) != 0) {
- BKE_reportf(reports, RPT_ERROR, "Unable to read \"%s\" (not a blend file)", path);
+ BKE_reportf(reports, RPT_ERROR, "Unable to read '%s' (not a blend file)", path);
goto cleanup;
}
- else {
+ else {
//printf("starting to read runtime from %s at datastart %d\n", path, datastart);
lseek(fd, datastart, SEEK_SET);
bfd = blo_read_blendafterruntime(fd, path, actualsize - datastart, reports);
diff --git a/source/blender/blenloader/intern/versioning_250.c b/source/blender/blenloader/intern/versioning_250.c
index a4f190c8167..d75339252d9 100644
--- a/source/blender/blenloader/intern/versioning_250.c
+++ b/source/blender/blenloader/intern/versioning_250.c
@@ -32,7 +32,7 @@
#include "zlib.h"
#ifndef WIN32
-# include <unistd.h> // for read close
+# include <unistd.h> /* for read close */
#else
# include <io.h> // for open close read
# include "winsock2.h"
@@ -652,7 +652,7 @@ static void do_versions_seq_unique_name_all_strips(Scene * sce, ListBase *seqbas
Sequence * seq = seqbasep->first;
while (seq) {
- BKE_seqence_base_unique_name_recursive(&sce->ed->seqbase, seq);
+ BKE_sequence_base_unique_name_recursive(&sce->ed->seqbase, seq);
if (seq->seqbase.first) {
do_versions_seq_unique_name_all_strips(sce, &seq->seqbase);
}
@@ -1134,7 +1134,7 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main)
/* Add default gravity to scenes */
for (sce = main->scene.first; sce; sce = sce->id.next) {
if ((sce->physics_settings.flag & PHYS_GLOBAL_GRAVITY) == 0 &&
- len_v3(sce->physics_settings.gravity) == 0.0f)
+ is_zero_v3(sce->physics_settings.gravity))
{
sce->physics_settings.gravity[0] = sce->physics_settings.gravity[1] = 0.0f;
sce->physics_settings.gravity[2] = -9.81f;
@@ -2062,7 +2062,7 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main)
{
brush->add_col[0] = 1.00f;
brush->add_col[1] = 0.39f;
- brush->add_col[2] = 0.39f;
+ brush->add_col[2] = 0.39f;
}
if (brush->sub_col[0] == 0 &&
@@ -2333,7 +2333,7 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main)
for (sc = main->screen.first; sc; sc = sc->id.next) {
if (sc->redraws_flag == 0) {
/* just initialize to default? */
- // XXX: we could also have iterated through areas, and taken them from the first timeline available...
+ /* XXX: we could also have iterated through areas, and taken them from the first timeline available... */
sc->redraws_flag = TIME_ALL_3D_WIN|TIME_ALL_ANIM_WIN;
}
}
diff --git a/source/blender/blenloader/intern/versioning_legacy.c b/source/blender/blenloader/intern/versioning_legacy.c
index 1cc0d4180ab..8a56e3c2ab8 100644
--- a/source/blender/blenloader/intern/versioning_legacy.c
+++ b/source/blender/blenloader/intern/versioning_legacy.c
@@ -92,7 +92,7 @@
#include "BKE_modifier.h"
#include "BKE_particle.h"
#include "BKE_pointcache.h"
-#include "BKE_property.h" // for get_ob_property
+#include "BKE_property.h" // for BKE_bproperty_object_get
#include "BKE_scene.h"
#include "BKE_sequencer.h"
@@ -387,8 +387,6 @@ static void customdata_version_242(Mesh *me)
if (!me->vdata.totlayer) {
CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, me->mvert, me->totvert);
- if (me->msticky)
- CustomData_add_layer(&me->vdata, CD_MSTICKY, CD_ASSIGN, me->msticky, me->totvert);
if (me->dvert)
CustomData_add_layer(&me->vdata, CD_MDEFORMVERT, CD_ASSIGN, me->dvert, me->totvert);
}
@@ -945,7 +943,7 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main)
while (act) {
if (act->type == ACT_IPO) {
ia = act->data;
- prop = get_ob_property(ob, ia->name);
+ prop = BKE_bproperty_object_get(ob, ia->name);
if (prop) {
ia->type = ACT_IPO_FROM_PROP;
}
@@ -1239,7 +1237,7 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main)
TFace *tf = &((TFace*) me->tface)[i];
for (j = 0; j < 4; j++) {
- char *col = (char*) &tf->col[j];
+ char *col = (char *) &tf->col[j];
col[0] = 255;
}
diff --git a/source/blender/blenloader/intern/writefile.c b/source/blender/blenloader/intern/writefile.c
index b8d63b3c5d5..8521b43e437 100644
--- a/source/blender/blenloader/intern/writefile.c
+++ b/source/blender/blenloader/intern/writefile.c
@@ -30,46 +30,46 @@
/*
-FILEFORMAT: IFF-style structure (but not IFF compatible!)
-
-start file:
- BLENDER_V100 12 bytes (versie 1.00)
- V = big endian, v = little endian
- _ = 4 byte pointer, - = 8 byte pointer
-
-datablocks: also see struct BHead
- <bh.code> 4 chars
- <bh.len> int, len data after BHead
- <bh.old> void, old pointer
- <bh.SDNAnr> int
- <bh.nr> int, in case of array: amount of structs
- data
- ...
- ...
-
-Almost all data in Blender are structures. Each struct saved
-gets a BHead header. With BHead the struct can be linked again
-and compared with StructDNA .
-
-WRITE
-
-Preferred writing order: (not really a must, but why would you do it random?)
-Any case: direct data is ALWAYS after the lib block
-
-(Local file data)
-- for each LibBlock
- - write LibBlock
- - write associated direct data
-(External file data)
-- per library
- - write library block
- - per LibBlock
- - write the ID of LibBlock
-- write TEST (128x128, blend file preview, optional)
-- write FileGlobal (some global vars)
-- write SDNA
-- write USER if filename is ~/X.XX/config/startup.blend
-*/
+ * FILEFORMAT: IFF-style structure (but not IFF compatible!)
+ *
+ * start file:
+ * BLENDER_V100 12 bytes (versie 1.00)
+ * V = big endian, v = little endian
+ * _ = 4 byte pointer, - = 8 byte pointer
+ *
+ * datablocks: also see struct BHead
+ * <bh.code> 4 chars
+ * <bh.len> int, len data after BHead
+ * <bh.old> void, old pointer
+ * <bh.SDNAnr> int
+ * <bh.nr> int, in case of array: amount of structs
+ * data
+ * ...
+ * ...
+ *
+ * Almost all data in Blender are structures. Each struct saved
+ * gets a BHead header. With BHead the struct can be linked again
+ * and compared with StructDNA .
+ *
+ * WRITE
+ *
+ * Preferred writing order: (not really a must, but why would you do it random?)
+ * Any case: direct data is ALWAYS after the lib block
+ *
+ * (Local file data)
+ * - for each LibBlock
+ * - write LibBlock
+ * - write associated direct data
+ * (External file data)
+ * - per library
+ * - write library block
+ * - per LibBlock
+ * - write the ID of LibBlock
+ * - write TEST (128x128, blend file preview, optional)
+ * - write FileGlobal (some global vars)
+ * - write SDNA
+ * - write USER if filename is ~/X.XX/config/startup.blend
+ */
#include <math.h>
@@ -197,7 +197,7 @@ static WriteData *writedata_new(int file)
if (wd == NULL) return NULL;
- wd->sdna= DNA_sdna_from_data(DNAstr, DNAlen, 0);
+ wd->sdna = DNA_sdna_from_data(DNAstr, DNAlen, 0);
wd->file= file;
@@ -511,7 +511,7 @@ static void write_fcurves(WriteData *wd, ListBase *fcurves)
writestruct(wd, DATA, "FCurve", 1, fcu);
/* curve data */
- if (fcu->bezt)
+ if (fcu->bezt)
writestruct(wd, DATA, "BezTriple", fcu->totvert, fcu->bezt);
if (fcu->fpt)
writestruct(wd, DATA, "FPoint", fcu->totvert, fcu->fpt);
@@ -720,18 +720,31 @@ static void write_nodetree(WriteData *wd, bNodeTree *ntree)
write_node_socket(wd, sock);
for (sock= node->outputs.first; sock; sock= sock->next)
write_node_socket(wd, sock);
-
+
+ for (link = node->internal_links.first; link; link = link->next)
+ writestruct(wd, DATA, "bNodeLink", 1, link);
if (node->storage) {
/* could be handlerized at some point, now only 1 exception still */
if (ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
write_curvemapping(wd, node->storage);
+ else if (ntree->type==NTREE_SHADER && node->type==SH_NODE_SCRIPT) {
+ NodeShaderScript *nss = (NodeShaderScript *)node->storage;
+ if (nss->bytecode)
+ writedata(wd, DATA, strlen(nss->bytecode)+1, nss->bytecode);
+ /* Write ID Properties -- and copy this comment EXACTLY for easy finding
+ * of library blocks that implement this.*/
+ if (nss->prop)
+ IDP_WriteProperty(nss->prop, wd);
+ writestruct(wd, DATA, node->typeinfo->storagename, 1, node->storage);
+ }
else if (ntree->type==NTREE_COMPOSIT && ELEM4(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
write_curvemapping(wd, node->storage);
else if (ntree->type==NTREE_TEXTURE && (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME) )
write_curvemapping(wd, node->storage);
- else if (ntree->type==NTREE_COMPOSIT && node->type==CMP_NODE_MOVIEDISTORTION)
- /* pass */;
+ else if (ntree->type==NTREE_COMPOSIT && node->type==CMP_NODE_MOVIEDISTORTION) {
+ /* pass */
+ }
else
writestruct(wd, DATA, node->typeinfo->storagename, 1, node->storage);
}
@@ -776,13 +789,16 @@ typedef struct RenderInfo {
char scene_name[MAX_ID_NAME - 2];
} RenderInfo;
-static void write_renderinfo(WriteData *wd, Main *mainvar) /* for renderdeamon */
+/* was for historic render-deamon feature,
+ * now write because it can be easily extracted without
+ * reading the whole blend file */
+static void write_renderinfo(WriteData *wd, Main *mainvar)
{
bScreen *curscreen;
Scene *sce;
RenderInfo data;
- /* XXX in future, handle multiple windows with multiple screnes? */
+ /* XXX in future, handle multiple windows with multiple screens? */
current_screen_compat(mainvar, &curscreen);
for (sce= mainvar->scene.first; sce; sce= sce->id.next) {
@@ -884,7 +900,7 @@ static const char *ptcache_data_struct[] = {
"", // BPHYS_DATA_ROTATION
"", // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST */
"", // BPHYS_DATA_SIZE:
- "", // BPHYS_DATA_TIMES:
+ "", // BPHYS_DATA_TIMES:
"BoidData" // case BPHYS_DATA_BOIDS:
};
static const char *ptcache_extra_struct[] = {
@@ -1237,7 +1253,7 @@ static void write_constraints(WriteData *wd, ListBase *conlist)
break;
case CONSTRAINT_TYPE_SPLINEIK:
{
- bSplineIKConstraint *data= (bSplineIKConstraint*)con->data;
+ bSplineIKConstraint *data = (bSplineIKConstraint *)con->data;
/* write points array */
writedata(wd, DATA, sizeof(float)*(data->numpoints), data->points);
@@ -1325,7 +1341,7 @@ static void write_modifiers(WriteData *wd, ListBase *modbase)
writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
writestruct(wd, DATA, "EffectorWeights", 1, clmd->sim_parms->effector_weights);
write_pointcaches(wd, &clmd->ptcaches);
- }
+ }
else if (md->type==eModifierType_Smoke) {
SmokeModifierData *smd = (SmokeModifierData*) md;
@@ -1355,7 +1371,7 @@ static void write_modifiers(WriteData *wd, ListBase *modbase)
writestruct(wd, DATA, "SmokeFlowSettings", 1, smd->flow);
else if (smd->type & MOD_SMOKE_TYPE_COLL)
writestruct(wd, DATA, "SmokeCollSettings", 1, smd->coll);
- }
+ }
else if (md->type==eModifierType_Fluidsim) {
FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
@@ -1383,7 +1399,7 @@ static void write_modifiers(WriteData *wd, ListBase *modbase)
writestruct(wd, DATA, "ColorBand", 1, pmd->brush->paint_ramp);
writestruct(wd, DATA, "ColorBand", 1, pmd->brush->vel_ramp);
}
- }
+ }
else if (md->type==eModifierType_Collision) {
#if 0
@@ -1603,7 +1619,7 @@ static void write_curves(WriteData *wd, ListBase *idbase)
if (cu->vfont) {
writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
writestruct(wd, DATA, "CharInfo", cu->len+1, cu->strinfo);
- writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);
+ writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);
}
else {
/* is also the order of reading */
@@ -1725,9 +1741,10 @@ static void write_customdata(WriteData *wd, ID *id, int count, CustomData *data,
writestruct(wd, DATA, structname, datasize, layer->data);
}
- else
+ else {
printf("%s error: layer '%s':%d - can't be written to file\n",
__func__, structname, layer->type);
+ }
}
}
@@ -1759,6 +1776,9 @@ static void write_meshs(WriteData *wd, ListBase *idbase)
backup_mesh.totface = mesh->totface;
mesh->totface = 0;
/* -- */
+ backup_mesh.fdata = mesh->fdata;
+ memset(&mesh->fdata, 0, sizeof(mesh->fdata));
+ /* -- */
#endif /* USE_BMESH_SAVE_WITHOUT_MFACE */
writestruct(wd, ID_ME, "Mesh", 1, mesh);
@@ -1782,6 +1802,8 @@ static void write_meshs(WriteData *wd, ListBase *idbase)
mesh->mface = backup_mesh.mface;
/* -- */
mesh->totface = backup_mesh.totface;
+ /* -- */
+ mesh->fdata = backup_mesh.fdata;
#endif /* USE_BMESH_SAVE_WITHOUT_MFACE */
}
@@ -1808,13 +1830,13 @@ static void write_meshs(WriteData *wd, ListBase *idbase)
mesh->totloop = 0;
/* -- */
backup_mesh.fdata = mesh->fdata;
- memset(&mesh->fdata, 0, sizeof(CustomData));
+ CustomData_reset(&mesh->fdata);
/* -- */
backup_mesh.pdata = mesh->pdata;
- memset(&mesh->pdata, 0, sizeof(CustomData));
+ CustomData_reset(&mesh->pdata);
/* -- */
backup_mesh.ldata = mesh->ldata;
- memset(&mesh->ldata, 0, sizeof(CustomData));
+ CustomData_reset(&mesh->ldata);
/* -- */
backup_mesh.edit_btmesh = mesh->edit_btmesh;
mesh->edit_btmesh = NULL;
@@ -2021,7 +2043,7 @@ static void write_materials(WriteData *wd, ListBase *idbase)
write_nodetree(wd, ma->nodetree);
}
- write_previews(wd, ma->preview);
+ write_previews(wd, ma->preview);
}
ma= ma->id.next;
}
@@ -2077,7 +2099,7 @@ static void write_lamps(WriteData *wd, ListBase *idbase)
}
if (la->curfalloff)
- write_curvemapping(wd, la->curfalloff);
+ write_curvemapping(wd, la->curfalloff);
/* nodetree is integral part of lamps, no libdata */
if (la->nodetree) {
@@ -2300,7 +2322,7 @@ static void write_gpencils(WriteData *wd, ListBase *lb)
/* write strokes */
for (gps= gpf->strokes.first; gps; gps= gps->next) {
writestruct(wd, DATA, "bGPDstroke", 1, gps);
- writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);
+ writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);
}
}
}
@@ -2536,7 +2558,7 @@ static void write_bone(WriteData *wd, Bone *bone)
Bone* cbone;
// PATCH for upward compatibility after 2.37+ armature recode
- bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
+ bone->size[0] = bone->size[1] = bone->size[2] = 1.0f;
// Write this bone
writestruct(wd, DATA, "Bone", 1, bone);
@@ -2995,7 +3017,7 @@ static int do_history(const char *name, ReportList *reports)
if (BLI_rename(tempname1, tempname2)) {
BKE_report(reports, RPT_ERROR, "Unable to make version backup");
return 1;
- }
+ }
hisnr--;
}
@@ -3022,7 +3044,7 @@ int BLO_write_file(Main *mainvar, const char *filepath, int write_flags, ReportL
file = BLI_open(tempname, O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
if (file == -1) {
- BKE_reportf(reports, RPT_ERROR, "Can't open file %s for writing: %s.", tempname, strerror(errno));
+ BKE_reportf(reports, RPT_ERROR, "Cannot open file %s for writing: %s", tempname, strerror(errno));
return 0;
}
@@ -3070,10 +3092,10 @@ int BLO_write_file(Main *mainvar, const char *filepath, int write_flags, ReportL
/* file save to temporary file was successful */
/* now do reverse file history (move .blend1 -> .blend2, .blend -> .blend1) */
- if (write_flags & G_FILE_HISTORY) {
+ if (write_flags & G_FILE_HISTORY) {
int err_hist = do_history(filepath, reports);
if (err_hist) {
- BKE_report(reports, RPT_ERROR, "Version backup failed. File saved with @");
+ BKE_report(reports, RPT_ERROR, "Version backup failed (file saved with @)");
return 0;
}
}
@@ -3090,23 +3112,23 @@ int BLO_write_file(Main *mainvar, const char *filepath, int write_flags, ReportL
if (0==ret) {
/* now rename to real file name, and delete temp @ file too */
if (BLI_rename(gzname, filepath) != 0) {
- BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @.");
+ BKE_report(reports, RPT_ERROR, "Cannot change old file (file saved with @)");
return 0;
}
BLI_delete(tempname, 0, 0);
}
else if (-1==ret) {
- BKE_report(reports, RPT_ERROR, "Failed opening .gz file.");
+ BKE_report(reports, RPT_ERROR, "Failed opening .gz file");
return 0;
}
else if (-2==ret) {
- BKE_report(reports, RPT_ERROR, "Failed opening .blend file for compression.");
+ BKE_report(reports, RPT_ERROR, "Failed opening .blend file for compression");
return 0;
}
}
else if (BLI_rename(tempname, filepath) != 0) {
- BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @");
+ BKE_report(reports, RPT_ERROR, "Cannot change old file (file saved with @)");
return 0;
}
diff --git a/source/blender/bmesh/CMakeLists.txt b/source/blender/bmesh/CMakeLists.txt
index 4bce7a6ff51..d7858ebbc0d 100644
--- a/source/blender/bmesh/CMakeLists.txt
+++ b/source/blender/bmesh/CMakeLists.txt
@@ -1,4 +1,3 @@
-# $Id: CMakeLists.txt 31746 2010-09-04 05:31:25Z joeedh $
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
@@ -26,10 +25,13 @@
set(INC
.
+ ../blenfont
../blenkernel
../blenlib
../makesdna
../../../intern/guardedalloc
+ ../../../extern/bullet2/src
+ ../../../intern/opennl/extern
)
set(INC_SYS
@@ -52,9 +54,13 @@ set(SRC
operators/bmo_mirror.c
operators/bmo_primitive.c
operators/bmo_removedoubles.c
+ operators/bmo_similar.c
+ operators/bmo_smooth_laplacian.c
+ operators/bmo_symmetrize.c
operators/bmo_subdivide.c
operators/bmo_subdivide.h
operators/bmo_triangulate.c
+ operators/bmo_unsubdivide.c
operators/bmo_utils.c
operators/bmo_wireframe.c
@@ -62,6 +68,10 @@ set(SRC
intern/bmesh_construct.h
intern/bmesh_core.c
intern/bmesh_core.h
+ intern/bmesh_decimate_collapse.c
+ intern/bmesh_decimate_dissolve.c
+ intern/bmesh_decimate_unsubdivide.c
+ intern/bmesh_decimate.h
intern/bmesh_inline.h
intern/bmesh_interp.c
intern/bmesh_interp.h
@@ -108,4 +118,12 @@ if(MSVC)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /WX")
endif()
+if(WITH_BULLET)
+ add_definitions(-DWITH_BULLET)
+endif()
+
+if(WITH_INTERNATIONAL)
+ add_definitions(-DWITH_INTERNATIONAL)
+endif()
+
blender_add_lib(bf_bmesh "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/bmesh/SConscript b/source/blender/bmesh/SConscript
index fb00aef4d78..6765d57cb3e 100644
--- a/source/blender/bmesh/SConscript
+++ b/source/blender/bmesh/SConscript
@@ -9,11 +9,20 @@ sources += env.Glob('tools/*.c')
incs = [
'./',
+ '../blenfont',
'../blenlib',
'../makesdna',
'../blenkernel',
'#/intern/guardedalloc',
- ]
+ '#/extern/bullet2/src',
+ '#/intern/opennl/extern', ]
defs = []
+
+if env['WITH_BF_BULLET']:
+ defs.append('WITH_BULLET')
+
+if env['WITH_BF_INTERNATIONAL']:
+ defs.append('WITH_INTERNATIONAL')
+
env.BlenderLib ( libname = 'bf_bmesh', sources = sources, includes = Split(incs), libtype = ['core','player'], defines=defs, priority=[100, 100], compileflags=cflags )
diff --git a/source/blender/bmesh/bmesh.h b/source/blender/bmesh/bmesh.h
index 955b1a729c5..a672ec0b6a7 100644
--- a/source/blender/bmesh/bmesh.h
+++ b/source/blender/bmesh/bmesh.h
@@ -252,6 +252,7 @@ extern "C" {
#include "intern/bmesh_construct.h"
#include "intern/bmesh_core.h"
+#include "intern/bmesh_decimate.h"
#include "intern/bmesh_interp.h"
#include "intern/bmesh_iterators.h"
#include "intern/bmesh_marking.h"
diff --git a/source/blender/bmesh/bmesh_class.h b/source/blender/bmesh/bmesh_class.h
index 3bd99b748f6..cff7da78ef2 100644
--- a/source/blender/bmesh/bmesh_class.h
+++ b/source/blender/bmesh/bmesh_class.h
@@ -225,9 +225,8 @@ enum {
BM_ELEM_DRAW = (1 << 5), /* edge display */
- /* we have 1 spare flag which is awesome but since we're limited to 8
- * only add new flags with care! - campbell */
- /* BM_ELEM_SPARE = (1 << 6), */
+ /* spare tag, assumed dirty, use define in each function to name based on use */
+ // _BM_ELEM_TAG_ALT = (1 << 6), // UNUSED
BM_ELEM_INTERNAL_TAG = (1 << 7) /* for low level internal API tagging,
* since tools may want to tag verts and
diff --git a/source/blender/bmesh/intern/bmesh_construct.c b/source/blender/bmesh/intern/bmesh_construct.c
index 4740140187d..d86a26e19ac 100644
--- a/source/blender/bmesh/intern/bmesh_construct.c
+++ b/source/blender/bmesh/intern/bmesh_construct.c
@@ -380,7 +380,7 @@ BMFace *BM_face_create_ngon_vcloud(BMesh *bm, BMVert **vert_arr, int totv, int n
}
sub_v3_v3v3(far_vec, far, cent);
- far_dist = len_v3(far_vec); /* real dist */
+ // far_dist = len_v3(far_vec); /* real dist */ /* UNUSED */
/* --- */
@@ -725,6 +725,7 @@ static void bm_vert_attrs_copy(BMesh *source_mesh, BMesh *target_mesh,
const BMVert *source_vertex, BMVert *target_vertex)
{
if ((source_mesh == target_mesh) && (source_vertex == target_vertex)) {
+ BLI_assert(!"BMVert: source and targer match");
return;
}
copy_v3_v3(target_vertex->no, source_vertex->no);
@@ -737,6 +738,7 @@ static void bm_edge_attrs_copy(BMesh *source_mesh, BMesh *target_mesh,
const BMEdge *source_edge, BMEdge *target_edge)
{
if ((source_mesh == target_mesh) && (source_edge == target_edge)) {
+ BLI_assert(!"BMEdge: source and targer match");
return;
}
CustomData_bmesh_free_block(&target_mesh->edata, &target_edge->head.data);
@@ -748,6 +750,7 @@ static void bm_loop_attrs_copy(BMesh *source_mesh, BMesh *target_mesh,
const BMLoop *source_loop, BMLoop *target_loop)
{
if ((source_mesh == target_mesh) && (source_loop == target_loop)) {
+ BLI_assert(!"BMLoop: source and targer match");
return;
}
CustomData_bmesh_free_block(&target_mesh->ldata, &target_loop->head.data);
@@ -759,6 +762,7 @@ static void bm_face_attrs_copy(BMesh *source_mesh, BMesh *target_mesh,
const BMFace *source_face, BMFace *target_face)
{
if ((source_mesh == target_mesh) && (source_face == target_face)) {
+ BLI_assert(!"BMFace: source and targer match");
return;
}
copy_v3_v3(target_face->no, source_face->no);
@@ -781,8 +785,10 @@ void BM_elem_attrs_copy(BMesh *source_mesh, BMesh *target_mesh, const void *sour
BLI_assert(sheader->htype == theader->htype);
- if (sheader->htype != theader->htype)
+ if (sheader->htype != theader->htype) {
+ BLI_assert(!"type mismatch");
return;
+ }
/* First we copy select */
if (BM_elem_flag_test((BMElem *)sheader, BM_ELEM_SELECT)) {
@@ -902,8 +908,9 @@ BMesh *BM_mesh_copy(BMesh *bm_old)
}
f2 = BM_face_create_ngon(bm_new, v, v2, edges, f->len, FALSE);
- if (!f2)
+ if (UNLIKELY(f2 == NULL)) {
continue;
+ }
/* use totface in case adding some faces fails */
BM_elem_index_set(f2, (bm_new->totface - 1)); /* set_inline */
diff --git a/source/blender/bmesh/intern/bmesh_core.c b/source/blender/bmesh/intern/bmesh_core.c
index f03ce9b8543..0910dd82701 100644
--- a/source/blender/bmesh/intern/bmesh_core.c
+++ b/source/blender/bmesh/intern/bmesh_core.c
@@ -28,12 +28,13 @@
#include "MEM_guardedalloc.h"
#include "BLI_math_vector.h"
-
-#include "BKE_DerivedMesh.h"
-
#include "BLI_listbase.h"
#include "BLI_array.h"
+#include "BLF_translation.h"
+
+#include "BKE_DerivedMesh.h"
+
#include "bmesh.h"
#include "intern/bmesh_private.h"
@@ -810,7 +811,7 @@ static int bm_loop_reverse_loop(BMesh *bm, BMFace *f
int bmesh_loop_reverse(BMesh *bm, BMFace *f)
{
#ifdef USE_BMESH_HOLES
- return bmesh_loop_reverse_loop(bm, f, f->loops.first);
+ return bm_loop_reverse_loop(bm, f, f->loops.first);
#else
return bm_loop_reverse_loop(bm, f);
#endif
@@ -836,8 +837,6 @@ static void bm_elements_systag_disable(void *veles, int tot, int flag)
}
}
-#define FACE_MARK (1 << 10)
-
static int count_flagged_radial(BMesh *bm, BMLoop *l, int flag)
{
BMLoop *l2 = l;
@@ -962,7 +961,7 @@ BMFace *BM_faces_join(BMesh *bm, BMFace **faces, int totface, const short do_del
int rlen = count_flagged_radial(bm, l_iter, _FLAG_JF);
if (rlen > 2) {
- err = "Input faces do not form a contiguous manifold region";
+ err = N_("Input faces do not form a contiguous manifold region");
goto error;
}
else if (rlen == 1) {
@@ -1023,9 +1022,9 @@ BMFace *BM_faces_join(BMesh *bm, BMFace **faces, int totface, const short do_del
/* create region face */
newf = BM_face_create_ngon(bm, v1, v2, edges, tote, FALSE);
- if (!newf || BMO_error_occurred(bm)) {
+ if (UNLIKELY(!newf || BMO_error_occurred(bm))) {
if (!BMO_error_occurred(bm))
- err = "Invalid boundary region to join faces";
+ err = N_("Invalid boundary region to join faces");
goto error;
}
@@ -1145,6 +1144,8 @@ static BMFace *bm_face_create__sfme(BMesh *bm, BMFace *UNUSED(example))
/**
* \brief Split Face Make Edge (SFME)
*
+ * \warning this is a low level function, most likely you want to use #BM_face_split()
+ *
* Takes as input two vertices in a single face. An edge is created which divides the original face
* into two distinct regions. One of the regions is assigned to the original face and it is closed off.
* The second region has a new face assigned to it.
@@ -1188,13 +1189,15 @@ BMFace *bmesh_sfme(BMesh *bm, BMFace *f, BMVert *v1, BMVert *v2,
{
#ifdef USE_BMESH_HOLES
BMLoopList *lst, *lst2;
+#else
+ int first_loop_f1;
#endif
BMFace *f2;
BMLoop *l_iter, *l_first;
BMLoop *v1loop = NULL, *v2loop = NULL, *f1loop = NULL, *f2loop = NULL;
BMEdge *e;
- int i, len, f1len, f2len, first_loop_f1;
+ int i, len, f1len, f2len;
/* verify that v1 and v2 are in face */
len = f->len;
@@ -1605,10 +1608,10 @@ BMEdge *bmesh_jekv(BMesh *bm, BMEdge *ke, BMVert *kv, const short check_edge_dou
BMESH_ASSERT(edok != FALSE);
}
- /* deallocate edg */
+ /* deallocate edge */
bm_kill_only_edge(bm, ke);
- /* deallocate verte */
+ /* deallocate vertex */
bm_kill_only_vert(bm, kv);
/* Validate disk cycle lengths of ov, tv are unchanged */
@@ -1617,7 +1620,7 @@ BMEdge *bmesh_jekv(BMesh *bm, BMEdge *ke, BMVert *kv, const short check_edge_dou
edok = bmesh_disk_validate(valence2, tv->e, tv);
BMESH_ASSERT(edok != FALSE);
- /* Validate loop cycle of all faces attached to oe */
+ /* Validate loop cycle of all faces attached to 'oe' */
for (i = 0, l = oe->l; i < radlen; i++, l = l->radial_next) {
BMESH_ASSERT(l->e == oe);
edok = bmesh_verts_in_edge(l->v, l->next->v, oe);
@@ -1798,8 +1801,12 @@ BMFace *bmesh_jfke(BMesh *bm, BMFace *f1, BMFace *f2, BMEdge *e)
* Merges two verts into one (\a v into \a vtarget).
*
* \return Success
+ *
+ * \warning This does't work for collapsing edges,
+ * where \a v and \a vtarget are connected by an edge
+ * (assert checks for this case).
*/
-int BM_vert_splice(BMesh *bm, BMVert *v, BMVert *vtarget)
+int BM_vert_splice(BMesh *bm, BMVert *v, BMVert *v_target)
{
BMEdge *e;
@@ -1807,26 +1814,29 @@ int BM_vert_splice(BMesh *bm, BMVert *v, BMVert *vtarget)
int i, loops_tot;
/* verts already spliced */
- if (v == vtarget) {
+ if (v == v_target) {
return FALSE;
}
/* we can't modify the vert while iterating so first allocate an array of loops */
loops = BM_iter_as_arrayN(bm, BM_LOOPS_OF_VERT, v, &loops_tot);
- for (i = 0; i < loops_tot; i++) {
- loops[i]->v = vtarget;
+ if (loops) {
+ for (i = 0; i < loops_tot; i++) {
+ loops[i]->v = v_target;
+ }
+ MEM_freeN(loops);
}
- MEM_freeN(loops);
/* move all the edges from v's disk to vtarget's disk */
while ((e = v->e)) {
bmesh_disk_edge_remove(e, v);
- bmesh_edge_swapverts(e, v, vtarget);
- bmesh_disk_edge_append(e, vtarget);
+ bmesh_edge_swapverts(e, v, v_target);
+ bmesh_disk_edge_append(e, v_target);
+ BLI_assert(e->v1 != e->v2);
}
BM_CHECK_ELEMENT(v);
- BM_CHECK_ELEMENT(vtarget);
+ BM_CHECK_ELEMENT(v_target);
/* v is unused now, and can be killed */
BM_vert_kill(bm, v);
@@ -1992,27 +2002,32 @@ int BM_vert_separate(BMesh *bm, BMVert *v, BMVert ***r_vout, int *r_vout_len,
*
* \note Edges must already have the same vertices.
*/
-int BM_edge_splice(BMesh *bm, BMEdge *e, BMEdge *etarget)
+int BM_edge_splice(BMesh *bm, BMEdge *e, BMEdge *e_target)
{
BMLoop *l;
- if (!BM_vert_in_edge(e, etarget->v1) || !BM_vert_in_edge(e, etarget->v2)) {
+ if (!BM_vert_in_edge(e, e_target->v1) || !BM_vert_in_edge(e, e_target->v2)) {
/* not the same vertices can't splice */
+
+ /* the caller should really make sure this doesn't happen ever
+ * so assert on release builds */
+ BLI_assert(0);
+
return FALSE;
}
while (e->l) {
l = e->l;
- BLI_assert(BM_vert_in_edge(etarget, l->v));
- BLI_assert(BM_vert_in_edge(etarget, l->next->v));
+ BLI_assert(BM_vert_in_edge(e_target, l->v));
+ BLI_assert(BM_vert_in_edge(e_target, l->next->v));
bmesh_radial_loop_remove(l, e);
- bmesh_radial_append(etarget, l);
+ bmesh_radial_append(e_target, l);
}
BLI_assert(bmesh_radial_length(e->l) == 0);
BM_CHECK_ELEMENT(e);
- BM_CHECK_ELEMENT(etarget);
+ BM_CHECK_ELEMENT(e_target);
/* removes from disks too */
BM_edge_kill(bm, e);
diff --git a/source/blender/bmesh/intern/bmesh_core.h b/source/blender/bmesh/intern/bmesh_core.h
index 491287993df..0667ed9ea1c 100644
--- a/source/blender/bmesh/intern/bmesh_core.h
+++ b/source/blender/bmesh/intern/bmesh_core.h
@@ -41,8 +41,8 @@ void BM_edge_kill(BMesh *bm, BMEdge *e);
void BM_vert_kill(BMesh *bm, BMVert *v);
int bmesh_edge_separate(BMesh *bm, BMEdge *e, BMLoop *l_sep);
-int BM_edge_splice(BMesh *bm, BMEdge *e, BMEdge *etarget);
-int BM_vert_splice(BMesh *bm, BMVert *v, BMVert *vtarget);
+int BM_edge_splice(BMesh *bm, BMEdge *e, BMEdge *e_target);
+int BM_vert_splice(BMesh *bm, BMVert *v, BMVert *v_target);
int bmesh_vert_separate(BMesh *bm, BMVert *v, BMVert ***r_vout, int *r_vout_len);
diff --git a/source/blender/bmesh/intern/bmesh_decimate.h b/source/blender/bmesh/intern/bmesh_decimate.h
new file mode 100644
index 00000000000..04dc0cfd2ea
--- /dev/null
+++ b/source/blender/bmesh/intern/bmesh_decimate.h
@@ -0,0 +1,41 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Campbell Barton
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __BMESH_DECIMATE_H__
+#define __BMESH_DECIMATE_H__
+
+/** \file blender/bmesh/intern/bmesh_decimate.h
+ * \ingroup bmesh
+ */
+
+void BM_mesh_decimate_collapse(BMesh *bm, const float factor, float *vweights, const int do_triangulate);
+
+void BM_mesh_decimate_unsubdivide_ex(BMesh *bm, const int iterations, const int tag_only);
+void BM_mesh_decimate_unsubdivide(BMesh *bm, const int iterations);
+
+void BM_mesh_decimate_dissolve_ex(BMesh *bm, const float angle_limit, const int do_dissolve_boundaries,
+ BMVert **vinput_arr, const int vinput_len,
+ BMEdge **einput_arr, const int einput_len);
+void BM_mesh_decimate_dissolve(BMesh *bm, const float angle_limit, const int do_dissolve_boundaries);
+
+
+#endif /* __BMESH_DECIMATE_H__ */
diff --git a/source/blender/bmesh/intern/bmesh_decimate_collapse.c b/source/blender/bmesh/intern/bmesh_decimate_collapse.c
new file mode 100644
index 00000000000..feeb2a926f3
--- /dev/null
+++ b/source/blender/bmesh/intern/bmesh_decimate_collapse.c
@@ -0,0 +1,949 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Campbell Barton
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/bmesh/intern/bmesh_decimate_collapse.c
+ * \ingroup bmesh
+ *
+ * BMesh decimator that uses an edge collapse method.
+ */
+
+#include <stddef.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_scene_types.h"
+
+#include "BLI_math.h"
+#include "BLI_quadric.h"
+#include "BLI_heap.h"
+
+#include "BKE_customdata.h"
+
+#include "bmesh.h"
+#include "bmesh_structure.h"
+#include "bmesh_decimate.h" /* own include */
+
+/* defines for testing */
+#define USE_CUSTOMDATA
+#define USE_TRIANGULATE
+
+/* these checks are for rare cases that we can't avoid since they are valid meshes still */
+#define USE_SAFETY_CHECKS
+
+#define BOUNDARY_PRESERVE_WEIGHT 100.0f
+
+typedef enum CD_UseFlag {
+ CD_DO_VERT = (1 << 0),
+ CD_DO_EDGE = (1 << 1),
+ CD_DO_LOOP = (1 << 2)
+} CD_UseFlag;
+
+
+/* BMesh Helper Functions
+ * ********************** */
+
+/**
+ * \param vquadrics must be calloc'd
+ */
+static void bm_decim_build_quadrics(BMesh *bm, Quadric *vquadrics)
+{
+ BMIter iter;
+ BMFace *f;
+ BMEdge *e;
+
+ BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
+ BMLoop *l_first;
+ BMLoop *l_iter;
+
+ const float *co = BM_FACE_FIRST_LOOP(f)->v->co;
+ const float *no = f->no;
+ const float offset = -dot_v3v3(no, co);
+ Quadric q;
+
+ BLI_quadric_from_v3_dist(&q, no, offset);
+
+ l_iter = l_first = BM_FACE_FIRST_LOOP(f);
+ do {
+ BLI_quadric_add_qu_qu(&vquadrics[BM_elem_index_get(l_iter->v)], &q);
+ } while ((l_iter = l_iter->next) != l_first);
+ }
+
+ /* boundary edges */
+ BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
+ if (UNLIKELY(BM_edge_is_boundary(e))) {
+ float edge_vector[3];
+ float edge_cross[3];
+ sub_v3_v3v3(edge_vector, e->v2->co, e->v1->co);
+ f = e->l->f;
+ cross_v3_v3v3(edge_cross, edge_vector, f->no);
+
+ if (fabsf(normalize_v3(edge_cross)) > FLT_EPSILON) {
+ Quadric q;
+ BLI_quadric_from_v3_dist(&q, edge_cross, -dot_v3v3(edge_cross, e->v1->co));
+ BLI_quadric_mul(&q, BOUNDARY_PRESERVE_WEIGHT);
+
+ BLI_quadric_add_qu_qu(&vquadrics[BM_elem_index_get(e->v1)], &q);
+ BLI_quadric_add_qu_qu(&vquadrics[BM_elem_index_get(e->v2)], &q);
+ }
+ }
+ }
+}
+
+
+static void bm_decim_calc_target_co(BMEdge *e, float optimize_co[3],
+ const Quadric *vquadrics)
+{
+ /* compute an edge contration target for edge 'e'
+ * this is computed by summing it's vertices quadrics and
+ * optimizing the result. */
+ Quadric q;
+
+ BLI_quadric_add_qu_ququ(&q,
+ &vquadrics[BM_elem_index_get(e->v1)],
+ &vquadrics[BM_elem_index_get(e->v2)]);
+
+
+ if (BLI_quadric_optimize(&q, optimize_co)) {
+ return; /* all is good */
+ }
+ else {
+ mid_v3_v3v3(optimize_co, e->v1->co, e->v2->co);
+ }
+}
+
+static void bm_decim_build_edge_cost_single(BMEdge *e,
+ const Quadric *vquadrics, const float *vweights,
+ Heap *eheap, HeapNode **eheap_table)
+{
+ const Quadric *q1, *q2;
+ float optimize_co[3];
+ float cost;
+
+ if (eheap_table[BM_elem_index_get(e)]) {
+ BLI_heap_remove(eheap, eheap_table[BM_elem_index_get(e)]);
+ }
+
+ /* check we can collapse, some edges we better not touch */
+ if (BM_edge_is_boundary(e)) {
+ if (e->l->f->len == 3) {
+ /* pass */
+ }
+ else {
+ /* only collapse tri's */
+ eheap_table[BM_elem_index_get(e)] = NULL;
+ return;
+ }
+ }
+ else if (BM_edge_is_manifold(e)) {
+ if ((e->l->f->len == 3) && (e->l->radial_next->f->len == 3)) {
+ /* pass */
+ }
+ else {
+ /* only collapse tri's */
+ eheap_table[BM_elem_index_get(e)] = NULL;
+ return;
+ }
+ }
+ else {
+ eheap_table[BM_elem_index_get(e)] = NULL;
+ return;
+ }
+
+ if (vweights) {
+ if ((vweights[BM_elem_index_get(e->v1)] < FLT_EPSILON) &&
+ (vweights[BM_elem_index_get(e->v2)] < FLT_EPSILON))
+ {
+ /* skip collapsing this edge */
+ eheap_table[BM_elem_index_get(e)] = NULL;
+ return;
+ }
+ }
+ /* end sanity check */
+
+
+ bm_decim_calc_target_co(e, optimize_co, vquadrics);
+
+ q1 = &vquadrics[BM_elem_index_get(e->v1)];
+ q2 = &vquadrics[BM_elem_index_get(e->v2)];
+
+ if (vweights == NULL) {
+ cost = (BLI_quadric_evaluate(q1, optimize_co) +
+ BLI_quadric_evaluate(q2, optimize_co));
+ }
+ else {
+ cost = ((BLI_quadric_evaluate(q1, optimize_co) * vweights[BM_elem_index_get(e->v1)]) +
+ (BLI_quadric_evaluate(q2, optimize_co) * vweights[BM_elem_index_get(e->v2)]));
+ }
+ // print("COST %.12f\n");
+
+ eheap_table[BM_elem_index_get(e)] = BLI_heap_insert(eheap, cost, e);
+}
+
+static void bm_decim_build_edge_cost(BMesh *bm,
+ const Quadric *vquadrics, const float *vweights,
+ Heap *eheap, HeapNode **eheap_table)
+{
+ BMIter iter;
+ BMEdge *e;
+ unsigned int i;
+
+ BM_ITER_MESH_INDEX (e, &iter, bm, BM_EDGES_OF_MESH, i) {
+ eheap_table[i] = NULL; /* keep sanity check happy */
+ bm_decim_build_edge_cost_single(e, vquadrics, vweights, eheap, eheap_table);
+ }
+}
+
+#ifdef USE_TRIANGULATE
+/* Temp Triangulation
+ * ****************** */
+
+/**
+ * To keep things simple we can only collapse edges on triangulated data
+ * (limitation with edge collapse and error calculation functions).
+ *
+ * But to avoid annoying users by only giving triangle results, we can
+ * triangulate, keeping a reference between the faces, then join after
+ * if the edges don't collapse, this will also allow more choices when
+ * collapsing edges so even has some advantage over decimating quads
+ * directly.
+ *
+ * \return TRUE if any faces were triangulated.
+ */
+
+static int bm_decim_triangulate_begin(BMesh *bm)
+{
+ BMIter iter;
+ BMFace *f;
+ // int has_quad; // could optimize this a little
+ int has_cut = FALSE;
+
+ BLI_assert((bm->elem_index_dirty & BM_VERT) == 0);
+
+ /* first clear loop index values */
+ BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
+ BMLoop *l_iter;
+ BMLoop *l_first;
+
+ l_iter = l_first = BM_FACE_FIRST_LOOP(f);
+ do {
+ BM_elem_index_set(l_iter, -1);
+ } while ((l_iter = l_iter->next) != l_first);
+
+ // has_quad |= (f->len == 4)
+ }
+
+ /* adding new faces as we loop over faces
+ * is normally best avoided, however in this case its not so bad because any face touched twice
+ * will already be triangulated*/
+ BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
+ if (f->len == 4) {
+ BMLoop *f_l[4];
+ BMLoop *l_a, *l_b;
+
+ {
+ BMLoop *l_iter = BM_FACE_FIRST_LOOP(f);
+
+ f_l[0] = l_iter; l_iter = l_iter->next;
+ f_l[1] = l_iter; l_iter = l_iter->next;
+ f_l[2] = l_iter; l_iter = l_iter->next;
+ f_l[3] = l_iter;
+ }
+
+ if (len_squared_v3v3(f_l[0]->v->co, f_l[2]->v->co) <
+ len_squared_v3v3(f_l[1]->v->co, f_l[3]->v->co))
+ {
+ l_a = f_l[0];
+ l_b = f_l[2];
+ }
+ else {
+ l_a = f_l[1];
+ l_b = f_l[3];
+ }
+
+#ifdef USE_SAFETY_CHECKS
+ if (BM_edge_exists(l_a->v, l_b->v) == FALSE)
+#endif
+ {
+ BMFace *f_new;
+ BMLoop *l_new;
+
+ /* warning, NO_DOUBLE option here isn't handled as nice as it could be
+ * - if there is a quad that has a free standing edge joining it along
+ * where we want to split the face, there isnt a good way we can handle this.
+ * currently that edge will get removed when joining the tris back into a quad. */
+ f_new = BM_face_split(bm, f, l_a->v, l_b->v, &l_new, NULL, FALSE);
+
+ if (f_new) {
+ /* the value of this doesn't matter, only that the 2 loops match and have unique values */
+ const int f_index = BM_elem_index_get(f);
+
+ /* since we just split theres only ever 2 loops */
+ BLI_assert(BM_edge_is_manifold(l_new->e));
+
+ BM_elem_index_set(l_new, f_index);
+ BM_elem_index_set(l_new->radial_next, f_index);
+
+ BM_face_normal_update(f);
+ BM_face_normal_update(f_new);
+
+ has_cut = TRUE;
+ }
+ }
+ }
+ }
+
+ BLI_assert((bm->elem_index_dirty & BM_VERT) == 0);
+
+ if (has_cut) {
+ /* now triangulation is done we need to correct index values */
+ BM_mesh_elem_index_ensure(bm, BM_EDGE | BM_FACE);
+ }
+
+ return has_cut;
+}
+
+static void bm_decim_triangulate_end(BMesh *bm)
+{
+ /* decimation finished, now re-join */
+ BMIter iter;
+ BMEdge *e;
+
+ /* boundary edges */
+ BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
+ BMLoop *l_a, *l_b;
+ if (BM_edge_loop_pair(e, &l_a, &l_b)) {
+ const int l_a_index = BM_elem_index_get(l_a);
+ if (l_a_index != -1) {
+ const int l_b_index = BM_elem_index_get(l_b);
+ if (l_a_index == l_b_index) {
+ if (LIKELY(l_a->f->len == 3 && l_b->f->len == 3)) {
+ if (l_a->v != l_b->v) { /* if this is the case, faces have become flipped */
+ /* check we are not making a degenerate quad */
+ BMVert *vquad[4] = {
+ e->v1,
+ BM_vert_in_edge(e, l_a->next->v) ? l_a->prev->v : l_a->next->v,
+ e->v2,
+ BM_vert_in_edge(e, l_b->next->v) ? l_b->prev->v : l_b->next->v,
+ };
+
+ BLI_assert(ELEM3(vquad[0], vquad[1], vquad[2], vquad[3]) == FALSE);
+ BLI_assert(ELEM3(vquad[1], vquad[0], vquad[2], vquad[3]) == FALSE);
+ BLI_assert(ELEM3(vquad[2], vquad[1], vquad[0], vquad[3]) == FALSE);
+ BLI_assert(ELEM3(vquad[3], vquad[1], vquad[2], vquad[0]) == FALSE);
+
+ if (is_quad_convex_v3(vquad[0]->co, vquad[1]->co, vquad[2]->co, vquad[3]->co)) {
+ /* highly unlikely to fail, but prevents possible double-ups */
+ BMFace *f[2] = {l_a->f, l_b->f};
+ BM_faces_join(bm, f, 2, TRUE);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+#endif /* USE_TRIANGULATE */
+
+/* Edge Collapse Functions
+ * *********************** */
+
+#ifdef USE_CUSTOMDATA
+
+/**
+ * \param v is the target to merge into.
+ */
+static void bm_edge_collapse_loop_customdata(BMesh *bm, BMLoop *l, BMVert *v_clear, BMVert *v_other,
+ const float customdata_fac)
+{
+ /* these don't need to be updated, since they will get removed when the edge collapses */
+ BMLoop *l_clear, *l_other;
+ const int is_manifold = BM_edge_is_manifold(l->e);
+ int side;
+
+ /* l defines the vert to collapse into */
+
+ /* first find the loop of 'v_other' thats attached to the face of 'l' */
+ if (l->v == v_clear) {
+ l_clear = l;
+ l_other = l->next;
+ }
+ else {
+ l_clear = l->next;
+ l_other = l;
+ }
+
+ BLI_assert(l_clear->v == v_clear);
+ BLI_assert(l_other->v == v_other);
+ (void)v_other; /* quiet warnings for release */
+
+ /* now we have both corners of the face 'l->f' */
+ for (side = 0; side < 2; side++) {
+ int is_seam = FALSE;
+ void *src[2];
+ BMFace *f_exit = is_manifold ? l->radial_next->f : NULL;
+ BMEdge *e_prev = l->e;
+ BMLoop *l_first;
+ BMLoop *l_iter;
+ float w[2];
+
+ if (side == 0) {
+ l_iter = l_first = l_clear;
+ src[0] = l_clear->head.data;
+ src[1] = l_other->head.data;
+
+ w[0] = customdata_fac;
+ w[1] = 1.0f - customdata_fac;
+ }
+ else {
+ l_iter = l_first = l_other;
+ src[0] = l_other->head.data;
+ src[1] = l_clear->head.data;
+
+ w[0] = 1.0f - customdata_fac;
+ w[1] = customdata_fac;
+ }
+
+ // print_v2("weights", w);
+
+ /* WATCH IT! - should NOT reference (_clear or _other) vars for this while loop */
+
+ /* walk around the fan using 'e_prev' */
+ while (((l_iter = BM_vert_step_fan_loop(l_iter, &e_prev)) != l_first) && (l_iter != NULL)) {
+ int i;
+ /* quit once we hit the opposite face, if we have one */
+ if (f_exit && UNLIKELY(f_exit == l_iter->f)) {
+ break;
+ }
+
+ /* break out unless we find a match */
+ is_seam = TRUE;
+
+ /* ok. we have a loop. now be smart with it! */
+ for (i = 0; i < bm->ldata.totlayer; i++) {
+ if (CustomData_layer_has_math(&bm->ldata, i)) {
+ const int offset = bm->ldata.layers[i].offset;
+ const int type = bm->ldata.layers[i].type;
+ void *cd_src, *cd_iter;
+
+ /* todo, make nicer macros for this */
+ cd_src = (char *)src[0] + offset;
+ // cd_dst = (char *)src[1] + offset; // UNUSED
+ cd_iter = (char *)l_iter->head.data + offset;
+
+ /* detect seams */
+ if (CustomData_data_equals(type, cd_src, cd_iter)) {
+ CustomData_bmesh_interp(&bm->ldata, src, w, NULL, 2, l_iter->head.data);
+ is_seam = FALSE;
+ }
+ }
+ }
+
+ if (is_seam) {
+ break;
+ }
+ }
+ }
+}
+#endif /* USE_CUSTOMDATA */
+
+/**
+ * Check if the collapse will result in a degenerate mesh,
+ * that is - duplicate edges or faces.
+ *
+ * This situation could be checked for when calculating collapse cost
+ * however its quite slow and a degenerate collapse could eventuate
+ * after the cost is calculated, so instead, check just before collapsing.
+ */
+
+static void bm_edge_tag_enable(BMEdge *e)
+{
+ BM_elem_flag_enable(e->v1, BM_ELEM_TAG);
+ BM_elem_flag_enable(e->v2, BM_ELEM_TAG);
+ if (e->l) {
+ BM_elem_flag_enable(e->l->f, BM_ELEM_TAG);
+ if (e->l != e->l->radial_next) {
+ BM_elem_flag_enable(e->l->radial_next->f, BM_ELEM_TAG);
+ }
+ }
+}
+
+static void bm_edge_tag_disable(BMEdge *e)
+{
+ BM_elem_flag_disable(e->v1, BM_ELEM_TAG);
+ BM_elem_flag_disable(e->v2, BM_ELEM_TAG);
+ if (e->l) {
+ BM_elem_flag_disable(e->l->f, BM_ELEM_TAG);
+ if (e->l != e->l->radial_next) {
+ BM_elem_flag_disable(e->l->radial_next->f, BM_ELEM_TAG);
+ }
+ }
+}
+
+static int bm_edge_tag_test(BMEdge *e)
+{
+ /* is the edge or one of its faces tagged? */
+ return (BM_elem_flag_test(e->v1, BM_ELEM_TAG) ||
+ BM_elem_flag_test(e->v2, BM_ELEM_TAG) ||
+ (e->l && (BM_elem_flag_test(e->l->f, BM_ELEM_TAG) ||
+ (e->l != e->l->radial_next &&
+ BM_elem_flag_test(e->l->radial_next->f, BM_ELEM_TAG))))
+ );
+}
+
+/* takes the edges loop */
+BLI_INLINE int bm_edge_is_manifold_or_boundary(BMLoop *l)
+{
+#if 0
+ /* less optimized version of check below */
+ return (BM_edge_is_manifold(l->e) || BM_edge_is_boundary(l->e);
+#else
+ /* if the edge is a boundary it points to its self, else this must be a manifold */
+ return LIKELY(l) && LIKELY(l->radial_next->radial_next == l);
+#endif
+}
+
+static int bm_edge_collapse_is_degenerate(BMEdge *e_first)
+{
+ /* simply check that there is no overlap between faces and edges of each vert,
+ * (excluding the 2 faces attached to 'e' and 'e' its self) */
+
+ BMEdge *e_iter;
+
+ /* clear flags on both disks */
+ e_iter = e_first;
+ do {
+ if (!bm_edge_is_manifold_or_boundary(e_iter->l)) {
+ return TRUE;
+ }
+ bm_edge_tag_disable(e_iter);
+ } while ((e_iter = bmesh_disk_edge_next(e_iter, e_first->v1)) != e_first);
+
+ e_iter = e_first;
+ do {
+ if (!bm_edge_is_manifold_or_boundary(e_iter->l)) {
+ return TRUE;
+ }
+ bm_edge_tag_disable(e_iter);
+ } while ((e_iter = bmesh_disk_edge_next(e_iter, e_first->v2)) != e_first);
+
+ /* now enable one side... */
+ e_iter = e_first;
+ do {
+ bm_edge_tag_enable(e_iter);
+ } while ((e_iter = bmesh_disk_edge_next(e_iter, e_first->v1)) != e_first);
+
+ /* ... except for the edge we will collapse, we know thats shared,
+ * disable this to avoid false positive. We could be smart and never enable these
+ * face/edge tags in the first place but easier to do this */
+ // bm_edge_tag_disable(e_first);
+ /* do inline... */
+ {
+#if 0
+ BMIter iter;
+ BMIter liter;
+ BMLoop *l;
+ BMVert *v;
+ BM_ITER_ELEM (l, &liter, e_first, BM_LOOPS_OF_EDGE) {
+ BM_elem_flag_disable(l->f, BM_ELEM_TAG);
+ BM_ITER_ELEM (v, &iter, l->f, BM_VERTS_OF_FACE) {
+ BM_elem_flag_disable(v, BM_ELEM_TAG);
+ }
+ }
+#else
+ /* we know each face is a triangle, no looping/iterators needed here */
+
+ BMLoop *l_radial;
+ BMLoop *l_face;
+
+ l_radial = e_first->l;
+ l_face = l_radial;
+ BLI_assert(l_face->f->len == 3);
+ BM_elem_flag_disable(l_face->f, BM_ELEM_TAG);
+ BM_elem_flag_disable((l_face = l_radial)->v, BM_ELEM_TAG);
+ BM_elem_flag_disable((l_face = l_face->next)->v, BM_ELEM_TAG);
+ BM_elem_flag_disable(( l_face->next)->v, BM_ELEM_TAG);
+ l_face = l_radial->radial_next;
+ if (l_radial != l_face) {
+ BLI_assert(l_face->f->len == 3);
+ BM_elem_flag_disable(l_face->f, BM_ELEM_TAG);
+ BM_elem_flag_disable((l_face = l_radial->radial_next)->v, BM_ELEM_TAG);
+ BM_elem_flag_disable((l_face = l_face->next)->v, BM_ELEM_TAG);
+ BM_elem_flag_disable(( l_face->next)->v, BM_ELEM_TAG);
+ }
+#endif
+ }
+
+ /* and check for overlap */
+ e_iter = e_first;
+ do {
+ if (bm_edge_tag_test(e_iter)) {
+ return TRUE;
+ }
+ } while ((e_iter = bmesh_disk_edge_next(e_iter, e_first->v2)) != e_first);
+
+ return FALSE;
+}
+
+/**
+ * special, highly limited edge collapse function
+ * intended for speed over flexibiliy.
+ * can only collapse edges connected to (1, 2) tris.
+ *
+ * Important - dont add vert/edge/face data on collapsing!
+ *
+ * \param e_clear_other let caller know what edges we remove besides \a e_clear
+ * \param customdata_flag merge factor, scales from 0 - 1 ('v_clear' -> 'v_other')
+ */
+static int bm_edge_collapse(BMesh *bm, BMEdge *e_clear, BMVert *v_clear, int r_e_clear_other[2],
+#ifdef USE_CUSTOMDATA
+ const CD_UseFlag customdata_flag,
+ const float customdata_fac
+#else
+ const CD_UseFlag UNUSED(customdata_flag),
+ const float UNUSED(customdata_fac)
+#endif
+ )
+{
+ BMVert *v_other;
+
+ /* disallow collapsing which results in degenerate cases */
+ if (bm_edge_collapse_is_degenerate(e_clear)) {
+ return FALSE;
+ }
+
+ v_other = BM_edge_other_vert(e_clear, v_clear);
+ BLI_assert(v_other != NULL);
+
+ if (BM_edge_is_manifold(e_clear)) {
+ BMLoop *l_a, *l_b;
+ BMEdge *e_a_other[2], *e_b_other[2];
+ int ok;
+
+ ok = BM_edge_loop_pair(e_clear, &l_a, &l_b);
+
+ BLI_assert(ok == TRUE);
+ BLI_assert(l_a->f->len == 3);
+ BLI_assert(l_b->f->len == 3);
+
+ /* keep 'v_clear' 0th */
+ if (BM_vert_in_edge(l_a->prev->e, v_clear)) {
+ e_a_other[0] = l_a->prev->e;
+ e_a_other[1] = l_a->next->e;
+ }
+ else {
+ e_a_other[1] = l_a->prev->e;
+ e_a_other[0] = l_a->next->e;
+ }
+
+ if (BM_vert_in_edge(l_b->prev->e, v_clear)) {
+ e_b_other[0] = l_b->prev->e;
+ e_b_other[1] = l_b->next->e;
+ }
+ else {
+ e_b_other[1] = l_b->prev->e;
+ e_b_other[0] = l_b->next->e;
+ }
+
+ BLI_assert(BM_edge_share_vert(e_a_other[0], e_b_other[0]));
+ BLI_assert(BM_edge_share_vert(e_a_other[1], e_b_other[1]));
+
+ /* we could assert this case, but better just bail out */
+#if 0
+ BLI_assert(e_a_other[0] != e_b_other[0]);
+ BLI_assert(e_a_other[0] != e_b_other[1]);
+ BLI_assert(e_b_other[0] != e_a_other[0]);
+ BLI_assert(e_b_other[0] != e_a_other[1]);
+#endif
+ /* not totally common but we want to avoid */
+ if (ELEM(e_a_other[0], e_b_other[0], e_b_other[1]) ||
+ ELEM(e_a_other[1], e_b_other[0], e_b_other[1]))
+ {
+ return FALSE;
+ }
+
+ r_e_clear_other[0] = BM_elem_index_get(e_a_other[0]);
+ r_e_clear_other[1] = BM_elem_index_get(e_b_other[0]);
+
+#ifdef USE_CUSTOMDATA
+ /* before killing, do customdata */
+ if (customdata_flag & CD_DO_VERT) {
+ BM_data_interp_from_verts(bm, v_other, v_clear, v_other, customdata_fac);
+ }
+ if (customdata_flag & CD_DO_EDGE) {
+ BM_data_interp_from_edges(bm, e_a_other[1], e_a_other[0], e_a_other[1], customdata_fac);
+ BM_data_interp_from_edges(bm, e_b_other[1], e_b_other[0], e_b_other[1], customdata_fac);
+ }
+ if (customdata_flag & CD_DO_LOOP) {
+ bm_edge_collapse_loop_customdata(bm, e_clear->l, v_clear, v_other, customdata_fac);
+ bm_edge_collapse_loop_customdata(bm, e_clear->l->radial_next, v_clear, v_other, customdata_fac);
+ }
+#endif
+
+ BM_edge_kill(bm, e_clear);
+
+ BM_vert_splice(bm, v_clear, v_other);
+
+ BM_edge_splice(bm, e_a_other[0], e_a_other[1]);
+ BM_edge_splice(bm, e_b_other[0], e_b_other[1]);
+
+ // BM_mesh_validate(bm);
+
+ return TRUE;
+ }
+ else if (BM_edge_is_boundary(e_clear)) {
+ /* same as above but only one triangle */
+ BMLoop *l_a;
+ BMEdge *e_a_other[2];
+
+ l_a = e_clear->l;
+
+ BLI_assert(l_a->f->len == 3);
+
+ /* keep 'v_clear' 0th */
+ if (BM_vert_in_edge(l_a->prev->e, v_clear)) {
+ e_a_other[0] = l_a->prev->e;
+ e_a_other[1] = l_a->next->e;
+ }
+ else {
+ e_a_other[1] = l_a->prev->e;
+ e_a_other[0] = l_a->next->e;
+ }
+
+ r_e_clear_other[0] = BM_elem_index_get(e_a_other[0]);
+ r_e_clear_other[1] = -1;
+
+#ifdef USE_CUSTOMDATA
+ /* before killing, do customdata */
+ if (customdata_flag & CD_DO_VERT) {
+ BM_data_interp_from_verts(bm, v_other, v_clear, v_other, customdata_fac);
+ }
+ if (customdata_flag & CD_DO_EDGE) {
+ BM_data_interp_from_edges(bm, e_a_other[1], e_a_other[0], e_a_other[1], customdata_fac);
+ }
+ if (customdata_flag & CD_DO_LOOP) {
+ bm_edge_collapse_loop_customdata(bm, e_clear->l, v_clear, v_other, customdata_fac);
+ }
+#endif
+
+ BM_edge_kill(bm, e_clear);
+
+ BM_vert_splice(bm, v_clear, v_other);
+
+ BM_edge_splice(bm, e_a_other[0], e_a_other[1]);
+
+ // BM_mesh_validate(bm);
+
+ return TRUE;
+ }
+ else {
+ return FALSE;
+ }
+}
+
+
+/* collapse e the edge, removing e->v2 */
+static void bm_decim_edge_collapse(BMesh *bm, BMEdge *e,
+ Quadric *vquadrics, float *vweights,
+ Heap *eheap, HeapNode **eheap_table,
+ const CD_UseFlag customdata_flag)
+{
+ int e_clear_other[2];
+ BMVert *v_other = e->v1;
+ int v_clear_index = BM_elem_index_get(e->v2); /* the vert is removed so only store the index */
+ float optimize_co[3];
+ float customdata_fac;
+
+ bm_decim_calc_target_co(e, optimize_co, vquadrics);
+
+ /* use for customdata merging */
+ if (LIKELY(compare_v3v3(e->v1->co, e->v2->co, FLT_EPSILON) == FALSE)) {
+ customdata_fac = line_point_factor_v3(optimize_co, e->v1->co, e->v2->co);
+
+#if 0
+ /* simple test for stupid collapse */
+ if (customdata_fac < 0.0 - FLT_EPSILON || customdata_fac > 1.0f + FLT_EPSILON) {
+ return;
+ }
+#endif
+ }
+ else {
+ /* avoid divide by zero */
+ customdata_fac = 0.5f;
+ }
+
+ if (bm_edge_collapse(bm, e, e->v2, e_clear_other, customdata_flag, customdata_fac)) {
+ /* update collapse info */
+ int i;
+
+ if (vweights) {
+ const int fac = CLAMPIS(customdata_fac, 0.0f, 1.0f);
+ vweights[BM_elem_index_get(v_other)] = (vweights[v_clear_index] * (1.0f - fac)) +
+ (vweights[BM_elem_index_get(v_other)] * fac);
+ }
+
+ e = NULL; /* paranoid safety check */
+
+ copy_v3_v3(v_other->co, optimize_co);
+
+ /* remove eheap */
+ for (i = 0; i < 2; i++) {
+ /* highly unlikely 'eheap_table[ke_other[i]]' would be NULL, but do for sanity sake */
+ if ((e_clear_other[i] != -1) && (eheap_table[e_clear_other[i]] != NULL)) {
+ BLI_heap_remove(eheap, eheap_table[e_clear_other[i]]);
+ eheap_table[e_clear_other[i]] = NULL;
+ }
+ }
+
+ /* update vertex quadric, add kept vertex from killed vertex */
+ BLI_quadric_add_qu_qu(&vquadrics[BM_elem_index_get(v_other)], &vquadrics[v_clear_index]);
+
+ /* update connected normals */
+
+ /* in fact face normals are not used for progressive updates, no need to update them */
+ // BM_vert_normal_update_all(v);
+ BM_vert_normal_update(v_other);
+
+ /* update error costs and the eheap */
+ if (LIKELY(v_other->e)) {
+ BMEdge *e_iter;
+ BMEdge *e_first;
+ e_iter = e_first = v_other->e;
+ do {
+ BLI_assert(BM_edge_find_double(e_iter) == NULL);
+ bm_decim_build_edge_cost_single(e_iter, vquadrics, vweights, eheap, eheap_table);
+ } while ((e_iter = bmesh_disk_edge_next(e_iter, v_other)) != e_first);
+ }
+
+#if 0
+ /* optional, update edges around the vertex face fan */
+ {
+ BMIter liter;
+ BMLoop *l;
+ BM_ITER_ELEM (l, &liter, v_other, BM_LOOPS_OF_VERT) {
+ if (l->f->len == 3) {
+ BMEdge *e_outer;
+ if (BM_vert_in_edge(l->prev->e, l->v))
+ e_outer = l->next->e;
+ else
+ e_outer = l->prev->e;
+
+ BLI_assert(BM_vert_in_edge(e_outer, l->v) == FALSE);
+
+ bm_decim_build_edge_cost_single(e_outer, vquadrics, eheap, eheap_table);
+ }
+ }
+ }
+ /* end optional update */
+#endif
+ }
+}
+
+
+/* Main Decimate Function
+ * ********************** */
+
+/**
+ * \brief BM_mesh_decimate
+ * \param bm The mesh
+ * \param factor face count multiplier [0 - 1]
+ * \param vertex_weights Optional array of vertex aligned weights [0 - 1],
+ * a vertex group is the usual source for this.
+ */
+void BM_mesh_decimate_collapse(BMesh *bm, const float factor, float *vweights, const int do_triangulate)
+{
+ Heap *eheap; /* edge heap */
+ HeapNode **eheap_table; /* edge index aligned table pointing to the eheap */
+ Quadric *vquadrics; /* vert index aligned quadrics */
+ int tot_edge_orig;
+ int face_tot_target;
+ int use_triangulate;
+
+ CD_UseFlag customdata_flag = 0;
+
+#ifdef USE_TRIANGULATE
+ /* temp convert quads to triangles */
+ use_triangulate = bm_decim_triangulate_begin(bm);
+#endif
+
+
+ /* alloc vars */
+ vquadrics = MEM_callocN(sizeof(Quadric) * bm->totvert, __func__);
+ /* since some edges may be degenerate, we might be over allocing a little here */
+ eheap = BLI_heap_new_ex(bm->totedge);
+ eheap_table = MEM_callocN(sizeof(HeapNode *) * bm->totedge, __func__);
+ tot_edge_orig = bm->totedge;
+
+
+ /* build initial edge collapse cost data */
+ bm_decim_build_quadrics(bm, vquadrics);
+
+ bm_decim_build_edge_cost(bm, vquadrics, vweights, eheap, eheap_table);
+
+ face_tot_target = bm->totface * factor;
+ bm->elem_index_dirty |= BM_FACE | BM_EDGE | BM_VERT;
+
+
+#ifdef USE_CUSTOMDATA
+ /* initialize customdata flag, we only need math for loops */
+ if (CustomData_has_interp(&bm->vdata)) customdata_flag |= CD_DO_VERT;
+ if (CustomData_has_interp(&bm->edata)) customdata_flag |= CD_DO_EDGE;
+ if (CustomData_has_math(&bm->ldata)) customdata_flag |= CD_DO_LOOP;
+#endif
+
+ /* iterative edge collapse and maintain the eheap */
+ while ((bm->totface > face_tot_target) && (BLI_heap_is_empty(eheap) == FALSE)) {
+ // const float value = BLI_heap_node_value(BLI_heap_top(eheap));
+ BMEdge *e = BLI_heap_popmin(eheap);
+ BLI_assert(BM_elem_index_get(e) < tot_edge_orig); /* handy to detect corruptions elsewhere */
+
+ // printf("COST %.10f\n", value);
+
+ /* under normal conditions wont be accessed again,
+ * but NULL just incase so we don't use freed node */
+ eheap_table[BM_elem_index_get(e)] = NULL;
+
+ bm_decim_edge_collapse(bm, e, vquadrics, vweights, eheap, eheap_table, customdata_flag);
+ }
+
+
+#ifdef USE_TRIANGULATE
+ if (do_triangulate == FALSE) {
+ /* its possible we only had triangles, skip this step in that case */
+ if (LIKELY(use_triangulate)) {
+ /* temp convert quads to triangles */
+ bm_decim_triangulate_end(bm);
+ }
+ }
+#endif
+
+ /* free vars */
+ MEM_freeN(vquadrics);
+ MEM_freeN(eheap_table);
+ BLI_heap_free(eheap, NULL);
+
+ /* testing only */
+ // BM_mesh_validate(bm);
+
+ (void)tot_edge_orig; /* quiet release build warning */
+}
diff --git a/source/blender/bmesh/intern/bmesh_decimate_dissolve.c b/source/blender/bmesh/intern/bmesh_decimate_dissolve.c
new file mode 100644
index 00000000000..d1371a18160
--- /dev/null
+++ b/source/blender/bmesh/intern/bmesh_decimate_dissolve.c
@@ -0,0 +1,243 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Campbell Barton
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/bmesh/intern/bmesh_decimate_dissolve.c
+ * \ingroup bmesh
+ *
+ * BMesh decimator that dissolves flat areas into polygons (ngons).
+ */
+
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_math.h"
+
+#include "bmesh.h"
+#include "bmesh_decimate.h" /* own include */
+
+#define UNIT_TO_ANGLE DEG2RADF(90.0f)
+#define ANGLE_TO_UNIT (1.0f / UNIT_TO_ANGLE)
+
+/* multiply vertex edge angle by face angle
+ * this means we are not left with sharp corners between _almost_ planer faces
+ * convert angles [0-PI/2] -> [0-1], multiply together, then convert back to radians. */
+static float bm_vert_edge_face_angle(BMVert *v)
+{
+ const float angle = BM_vert_calc_edge_angle(v);
+ /* note: could be either edge, it doesn't matter */
+ if (v->e && BM_edge_is_manifold(v->e)) {
+ return ((angle * ANGLE_TO_UNIT) * (BM_edge_calc_face_angle(v->e) * ANGLE_TO_UNIT)) * UNIT_TO_ANGLE;
+ }
+ else {
+ return angle;
+ }
+}
+
+#undef UNIT_TO_ANGLE
+#undef ANGLE_TO_UNIT
+
+typedef struct DissolveElemWeight {
+ BMHeader *ele;
+ float weight;
+} DissolveElemWeight;
+
+static int dissolve_elem_cmp(const void *a1, const void *a2)
+{
+ const struct DissolveElemWeight *d1 = a1, *d2 = a2;
+
+ if (d1->weight > d2->weight) return 1;
+ else if (d1->weight < d2->weight) return -1;
+ return 0;
+}
+
+/**
+ * \param do_all_verts Collapse all verts between 2 faces - don't check their edge angle.
+ */
+void BM_mesh_decimate_dissolve_ex(BMesh *bm, const float angle_limit, const int do_dissolve_boundaries,
+ BMVert **vinput_arr, const int vinput_len,
+ BMEdge **einput_arr, const int einput_len)
+{
+ const float angle_max = (float)M_PI / 2.0f;
+ DissolveElemWeight *weight_elems = MEM_mallocN(max_ii(einput_len, vinput_len) *
+ sizeof(DissolveElemWeight), __func__);
+ int i, tot_found;
+
+ BMIter iter;
+ BMEdge *e_iter;
+ BMEdge **earray;
+
+ int *vert_reverse_lookup;
+
+ /* --- first edges --- */
+
+ /* wire -> tag */
+ BM_ITER_MESH (e_iter, &iter, bm, BM_EDGES_OF_MESH) {
+ BM_elem_flag_set(e_iter, BM_ELEM_TAG, BM_edge_is_wire(e_iter));
+ }
+
+ /* go through and split edge */
+ for (i = 0, tot_found = 0; i < einput_len; i++) {
+ BMEdge *e = einput_arr[i];
+ const float angle = BM_edge_calc_face_angle(e);
+
+ if (angle < angle_limit) {
+ tot_found++;
+ }
+ weight_elems[i].ele = (BMHeader *)e;
+ weight_elems[i].weight = angle;
+ }
+
+ if (tot_found != 0) {
+ qsort(weight_elems, einput_len, sizeof(DissolveElemWeight), dissolve_elem_cmp);
+
+ for (i = 0; i < tot_found; i++) {
+ BMEdge *e = (BMEdge *)weight_elems[i].ele;
+
+ if (/* may have become non-manifold */
+ BM_edge_is_manifold(e) &&
+ /* check twice because cumulative effect could dissolve over angle limit */
+ (BM_edge_calc_face_angle(e) < angle_limit))
+ {
+ BMFace *nf = BM_faces_join_pair(bm, e->l->f,
+ e->l->radial_next->f,
+ e,
+ FALSE); /* join faces */
+
+ /* there may be some errors, we don't mind, just move on */
+ if (nf) {
+ BM_face_normal_update(nf);
+ }
+ else {
+ BMO_error_clear(bm);
+ }
+ }
+ }
+ }
+
+ /* prepare for cleanup */
+ BM_mesh_elem_index_ensure(bm, BM_VERT);
+ vert_reverse_lookup = MEM_mallocN(sizeof(int) * bm->totvert, __func__);
+ fill_vn_i(vert_reverse_lookup, bm->totvert, -1);
+ for (i = 0, tot_found = 0; i < vinput_len; i++) {
+ BMVert *v = vinput_arr[i];
+ vert_reverse_lookup[BM_elem_index_get(v)] = i;
+ }
+
+ /* --- cleanup --- */
+ earray = MEM_mallocN(sizeof(BMEdge *) * bm->totedge, __func__);
+ BM_ITER_MESH_INDEX (e_iter, &iter, bm, BM_EDGES_OF_MESH, i) {
+ earray[i] = e_iter;
+ }
+ /* remove all edges/verts left behind from dissolving, NULL'ing the vertex array so we dont re-use */
+ for (i = bm->totedge - 1; i != -1; i--) {
+ e_iter = earray[i];
+
+ if (BM_edge_is_wire(e_iter) && (BM_elem_flag_test(e_iter, BM_ELEM_TAG) == FALSE)) {
+ /* edge has become wire */
+ int vidx_reverse;
+ BMVert *v1 = e_iter->v1;
+ BMVert *v2 = e_iter->v2;
+ BM_edge_kill(bm, e_iter);
+ if (v1->e == NULL) {
+ vidx_reverse = vert_reverse_lookup[BM_elem_index_get(v1)];
+ if (vidx_reverse != -1) vinput_arr[vidx_reverse] = NULL;
+ BM_vert_kill(bm, v1);
+ }
+ if (v2->e == NULL) {
+ vidx_reverse = vert_reverse_lookup[BM_elem_index_get(v2)];
+ if (vidx_reverse != -1) vinput_arr[vidx_reverse] = NULL;
+ BM_vert_kill(bm, v2);
+ }
+ }
+ }
+ MEM_freeN(vert_reverse_lookup);
+
+ MEM_freeN(earray);
+
+
+ /* --- second verts --- */
+ if (do_dissolve_boundaries) {
+ /* simple version of the branch below, sincve we will dissolve _all_ verts that use 2 edges */
+ for (i = 0; i < vinput_len; i++) {
+ BMVert *v = vinput_arr[i];
+ if (LIKELY(v != NULL) &&
+ BM_vert_edge_count(v) == 2)
+ {
+ BM_vert_collapse_edge(bm, v->e, v, TRUE); /* join edges */
+ }
+ }
+ }
+ else {
+ for (i = 0, tot_found = 0; i < vinput_len; i++) {
+ BMVert *v = vinput_arr[i];
+ const float angle = v ? bm_vert_edge_face_angle(v) : angle_limit;
+
+ if (angle < angle_limit) {
+ weight_elems[i].ele = (BMHeader *)v;
+ weight_elems[i].weight = angle;
+ tot_found++;
+ }
+ else {
+ weight_elems[i].ele = NULL;
+ weight_elems[i].weight = angle_max;
+ }
+ }
+
+ if (tot_found != 0) {
+ qsort(weight_elems, vinput_len, sizeof(DissolveElemWeight), dissolve_elem_cmp);
+
+ for (i = 0; i < tot_found; i++) {
+ BMVert *v = (BMVert *)weight_elems[i].ele;
+ if (LIKELY(v != NULL) &&
+ /* topology changes may cause this to be un-collapsable */
+ (BM_vert_edge_count(v) == 2) &&
+ /* check twice because cumulative effect could dissolve over angle limit */
+ bm_vert_edge_face_angle(v) < angle_limit)
+ {
+ BMEdge *ne = BM_vert_collapse_edge(bm, v->e, v, TRUE); /* join edges */
+
+ if (ne && ne->l) {
+ BM_edge_normals_update(ne);
+ }
+ }
+ }
+ }
+ }
+
+ MEM_freeN(weight_elems);
+}
+
+void BM_mesh_decimate_dissolve(BMesh *bm, const float angle_limit, const int do_dissolve_boundaries)
+{
+ int vinput_len;
+ int einput_len;
+
+ BMVert **vinput_arr = BM_iter_as_arrayN(bm, BM_VERTS_OF_MESH, NULL, &vinput_len);
+ BMEdge **einput_arr = BM_iter_as_arrayN(bm, BM_EDGES_OF_MESH, NULL, &einput_len);
+
+ BM_mesh_decimate_dissolve_ex(bm, angle_limit, do_dissolve_boundaries,
+ vinput_arr, vinput_len,
+ einput_arr, einput_len);
+
+ MEM_freeN(vinput_arr);
+ MEM_freeN(einput_arr);
+}
diff --git a/source/blender/bmesh/intern/bmesh_decimate_unsubdivide.c b/source/blender/bmesh/intern/bmesh_decimate_unsubdivide.c
new file mode 100644
index 00000000000..68c0652d2c4
--- /dev/null
+++ b/source/blender/bmesh/intern/bmesh_decimate_unsubdivide.c
@@ -0,0 +1,344 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Campbell Barton
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/bmesh/intern/bmesh_decimate_unsubdivide.c
+ * \ingroup bmesh
+ *
+ * BMesh decimator that uses a grid un-subdivide method.
+ */
+
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_math.h"
+
+#include "bmesh.h"
+
+#include "intern/bmesh_operators_private.h" /* own include */
+
+
+static int bm_vert_dissolve_fan_test(BMVert *v)
+{
+ /* check if we should walk over these verts */
+ BMIter iter;
+ BMEdge *e;
+
+ unsigned int tot_edge = 0;
+ unsigned int tot_edge_boundary = 0;
+ unsigned int tot_edge_manifold = 0;
+ unsigned int tot_edge_wire = 0;
+
+ BM_ITER_ELEM (e, &iter, v, BM_EDGES_OF_VERT) {
+ if (BM_edge_is_boundary(e)) {
+ tot_edge_boundary++;
+ }
+ else if (BM_edge_is_manifold(e)) {
+ tot_edge_manifold++;
+ }
+ else if (BM_edge_is_wire(e)) {
+ tot_edge_wire++;
+ }
+ tot_edge++;
+ }
+
+ if ((tot_edge == 4) && (tot_edge_boundary == 0) && (tot_edge_manifold == 4)) {
+ return TRUE;
+ }
+ else if ((tot_edge == 3) && (tot_edge_boundary == 0) && (tot_edge_manifold == 3)) {
+ return TRUE;
+ }
+ else if ((tot_edge == 3) && (tot_edge_boundary == 2) && (tot_edge_manifold == 1)) {
+ return TRUE;
+ }
+ else if ((tot_edge == 2) && (tot_edge_wire == 2)) {
+ return TRUE;
+ }
+ return FALSE;
+}
+
+static int bm_vert_dissolve_fan(BMesh *bm, BMVert *v)
+{
+ /* collapse under 2 conditions.
+ * - vert connects to 4 manifold edges (and 4 faces).
+ * - vert connecrs to 1 manifold edge, 2 boundary edges (and 2 faces).
+ *
+ * This covers boundary verts of a quad grid and center verts.
+ * note that surrounding faces dont have to be quads.
+ */
+
+ BMIter iter;
+ BMEdge *e;
+
+ unsigned int tot_loop = 0;
+ unsigned int tot_edge = 0;
+ unsigned int tot_edge_boundary = 0;
+ unsigned int tot_edge_manifold = 0;
+ unsigned int tot_edge_wire = 0;
+
+ BM_ITER_ELEM (e, &iter, v, BM_EDGES_OF_VERT) {
+ if (BM_edge_is_boundary(e)) {
+ tot_edge_boundary++;
+ }
+ else if (BM_edge_is_manifold(e)) {
+ tot_edge_manifold++;
+ }
+ else if (BM_edge_is_wire(e)) {
+ tot_edge_wire++;
+ }
+ tot_edge++;
+ }
+
+ if (tot_edge == 2) {
+ /* check for 2 wire verts only */
+ if (tot_edge_wire == 2) {
+ return (BM_vert_collapse_edge(bm, v->e, v, TRUE) != NULL);
+ }
+ }
+ else if (tot_edge == 4) {
+ /* check for 4 faces surrounding */
+ if (tot_edge_boundary == 0 && tot_edge_manifold == 4) {
+ /* good to go! */
+ tot_loop = 4;
+ }
+ }
+ else if (tot_edge == 3) {
+ /* check for 2 faces surrounding at a boundary */
+ if (tot_edge_boundary == 2 && tot_edge_manifold == 1) {
+ /* good to go! */
+ tot_loop = 2;
+ }
+ else if (tot_edge_boundary == 0 && tot_edge_manifold == 3) {
+ /* good to go! */
+ tot_loop = 3;
+ }
+ }
+
+ if (tot_loop) {
+ BMLoop *f_loop[4];
+ unsigned int i;
+
+ /* ensure there are exactly tot_loop loops */
+ BLI_assert(BM_iter_at_index(bm, BM_LOOPS_OF_VERT, v, tot_loop) == NULL);
+ BM_iter_as_array(bm, BM_LOOPS_OF_VERT, v, (void **)f_loop, tot_loop);
+
+ for (i = 0; i < tot_loop; i++) {
+ BMLoop *l = f_loop[i];
+ if (l->f->len > 3) {
+ BMLoop *l_new;
+ BLI_assert(l->prev->v != l->next->v);
+ BM_face_split(bm, l->f, l->prev->v, l->next->v, &l_new, NULL, TRUE);
+ BM_elem_flag_merge_into(l_new->e, l->e, l->prev->e);
+ }
+ }
+
+ return BM_vert_dissolve(bm, v);
+ }
+
+ return FALSE;
+}
+
+enum {
+ VERT_INDEX_DO_COLLAPSE = -1,
+ VERT_INDEX_INIT = 0,
+ VERT_INDEX_IGNORE = 1
+};
+
+// #define USE_WALKER /* gives uneven results, disable for now */
+
+/* - BMVert.flag & BM_ELEM_TAG: shows we touched this vert
+ * - BMVert.index == -1: shows we will remove this vert
+ */
+
+/**
+ * \param tag_only so we can call this from an operator */
+void BM_mesh_decimate_unsubdivide_ex(BMesh *bm, const int iterations, const int tag_only)
+{
+#ifdef USE_WALKER
+# define ELE_VERT_TAG 1
+#else
+ BMVert **vert_seek_a = MEM_mallocN(sizeof(BMVert *) * bm->totvert, __func__);
+ BMVert **vert_seek_b = MEM_mallocN(sizeof(BMVert *) * bm->totvert, __func__);
+ unsigned vert_seek_a_tot = 0;
+ unsigned vert_seek_b_tot = 0;
+#endif
+
+ BMVert *v;
+ BMIter iter;
+
+ const unsigned int offset = 0;
+ const unsigned int nth = 2;
+
+ int iter_step;
+
+ /* if tag_only is set, we assyme the caller knows what verts to tag
+ * needed for the operator */
+ if (tag_only == FALSE) {
+ BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
+ BM_elem_flag_enable(v, BM_ELEM_TAG);
+ }
+ }
+
+ for (iter_step = 0; iter_step < iterations; iter_step++) {
+ int iter_done;
+
+ BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
+ if (BM_elem_flag_test(v, BM_ELEM_TAG) && bm_vert_dissolve_fan_test(v)) {
+#ifdef USE_WALKER
+ BMO_elem_flag_enable(bm, v, ELE_VERT_TAG);
+#endif
+ BM_elem_index_set(v, VERT_INDEX_INIT); /* set_dirty! */
+ }
+ else {
+ BM_elem_index_set(v, VERT_INDEX_IGNORE); /* set_dirty! */
+ }
+ }
+ /* done with selecting tagged verts */
+
+
+ /* main loop, keep tagging until we can't tag any more islands */
+ while (TRUE) {
+#ifdef USE_WALKER
+ BMWalker walker;
+#else
+ unsigned int depth = 1;
+ unsigned int i;
+#endif
+ BMVert *v_first = NULL;
+ BMVert *v;
+
+ /* we could avoid iterating from the start each time */
+ BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
+ if (v->e && (BM_elem_index_get(v) == VERT_INDEX_INIT)) {
+#ifdef USE_WALKER
+ if (BMO_elem_flag_test(bm, v, ELE_VERT_TAG))
+#endif
+ {
+ /* check again incase the topology changed */
+ if (bm_vert_dissolve_fan_test(v)) {
+ v_first = v;
+ }
+ break;
+ }
+ }
+ }
+ if (v_first == NULL) {
+ break;
+ }
+
+#ifdef USE_WALKER
+ /* Walk over selected elements starting at active */
+ BMW_init(&walker, bm, BMW_CONNECTED_VERTEX,
+ ELE_VERT_TAG, BMW_MASK_NOP, BMW_MASK_NOP,
+ BMW_FLAG_NOP, /* don't use BMW_FLAG_TEST_HIDDEN here since we want to desel all */
+ BMW_NIL_LAY);
+
+ BLI_assert(walker.order == BMW_BREADTH_FIRST);
+ for (v = BMW_begin(&walker, v_first); v != NULL; v = BMW_step(&walker)) {
+ /* Deselect elements that aren't at "nth" depth from active */
+ if (BM_elem_index_get(v) == VERT_INDEX_INIT) {
+ if ((offset + BMW_current_depth(&walker)) % nth) {
+ /* tag for removal */
+ BM_elem_index_set(v, VERT_INDEX_DO_COLLAPSE); /* set_dirty! */
+ }
+ else {
+ /* works better to allow these verts to be checked again */
+ //BM_elem_index_set(v, VERT_INDEX_IGNORE); /* set_dirty! */
+ }
+ }
+ }
+ BMW_end(&walker);
+#else
+
+ BM_elem_index_set(v_first, (offset + depth) % nth ? VERT_INDEX_IGNORE : VERT_INDEX_DO_COLLAPSE); /* set_dirty! */
+
+ vert_seek_b_tot = 0;
+ vert_seek_b[vert_seek_b_tot++] = v_first;
+
+ while (TRUE) {
+ BMEdge *e;
+
+ if ((offset + depth) % nth) {
+ vert_seek_a_tot = 0;
+ for (i = 0; i < vert_seek_b_tot; i++) {
+ v = vert_seek_b[i];
+ BLI_assert(BM_elem_index_get(v) == VERT_INDEX_IGNORE);
+ BM_ITER_ELEM (e, &iter, v, BM_EDGES_OF_VERT) {
+ BMVert *v_other = BM_edge_other_vert(e, v);
+ if (BM_elem_index_get(v_other) == VERT_INDEX_INIT) {
+ BM_elem_index_set(v_other, VERT_INDEX_DO_COLLAPSE); /* set_dirty! */
+ vert_seek_a[vert_seek_a_tot++] = v_other;
+ }
+ }
+ }
+ if (vert_seek_a_tot == 0) {
+ break;
+ }
+ }
+ else {
+ vert_seek_b_tot = 0;
+ for (i = 0; i < vert_seek_a_tot; i++) {
+ v = vert_seek_a[i];
+ BLI_assert(BM_elem_index_get(v) == VERT_INDEX_DO_COLLAPSE);
+ BM_ITER_ELEM (e, &iter, v, BM_EDGES_OF_VERT) {
+ BMVert *v_other = BM_edge_other_vert(e, v);
+ if (BM_elem_index_get(v_other) == VERT_INDEX_INIT) {
+ BM_elem_index_set(v_other, VERT_INDEX_IGNORE); /* set_dirty! */
+ vert_seek_b[vert_seek_b_tot++] = v_other;
+ }
+ }
+ }
+ if (vert_seek_b_tot == 0) {
+ break;
+ }
+ }
+
+ depth++;
+ }
+#endif /* USE_WALKER */
+
+ }
+
+ /* now we tagged all verts -1 for removal, lets loop over and rebuild faces */
+ iter_done = FALSE;
+ BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
+ if (BM_elem_index_get(v) == VERT_INDEX_DO_COLLAPSE) {
+ iter_done |= bm_vert_dissolve_fan(bm, v);
+ }
+ }
+
+ if (iter_done == FALSE) {
+ break;
+ }
+ }
+
+ bm->elem_index_dirty |= BM_VERT;
+
+#ifndef USE_WALKER
+ MEM_freeN(vert_seek_a);
+ MEM_freeN(vert_seek_b);
+#endif
+}
+
+void BM_mesh_decimate_unsubdivide(BMesh *bm, const int iterations)
+{
+ BM_mesh_decimate_unsubdivide_ex(bm, iterations, FALSE);
+}
diff --git a/source/blender/bmesh/intern/bmesh_inline.h b/source/blender/bmesh/intern/bmesh_inline.h
index 400f4a55b0e..04b214f725a 100644
--- a/source/blender/bmesh/intern/bmesh_inline.h
+++ b/source/blender/bmesh/intern/bmesh_inline.h
@@ -37,6 +37,7 @@
#define BM_elem_flag_set( ele, hflag, val) _bm_elem_flag_set (&(ele)->head, hflag, val)
#define BM_elem_flag_toggle( ele, hflag) _bm_elem_flag_toggle (&(ele)->head, hflag)
#define BM_elem_flag_merge( ele_a, ele_b) _bm_elem_flag_merge (&(ele_a)->head, &(ele_b)->head)
+#define BM_elem_flag_merge_into(ele, ele_a, ele_b)_bm_elem_flag_merge_into (&(ele)->head, &(ele_a)->head, &(ele_b)->head)
BLI_INLINE char _bm_elem_flag_test(const BMHeader *head, const char hflag)
{
@@ -74,6 +75,11 @@ BLI_INLINE void _bm_elem_flag_merge(BMHeader *head_a, BMHeader *head_b)
head_a->hflag = head_b->hflag = head_a->hflag | head_b->hflag;
}
+BLI_INLINE void _bm_elem_flag_merge_into(BMHeader *head, const BMHeader *head_a, const BMHeader *head_b)
+{
+ head->hflag = head_a->hflag | head_b->hflag;
+}
+
/**
* notes on #BM_elem_index_set(...) usage,
* Set index is sometimes abused as temp storage, other times we cant be
diff --git a/source/blender/bmesh/intern/bmesh_interp.c b/source/blender/bmesh/intern/bmesh_interp.c
index 9033436d1b2..508b3b8fcdf 100644
--- a/source/blender/bmesh/intern/bmesh_interp.c
+++ b/source/blender/bmesh/intern/bmesh_interp.c
@@ -224,10 +224,8 @@ static int compute_mdisp_quad(BMLoop *l, float v1[3], float v2[3], float v3[3],
/* computer center */
BM_face_calc_center_mean(l->f, cent);
- add_v3_v3v3(p, l->prev->v->co, l->v->co);
- mul_v3_fl(p, 0.5);
- add_v3_v3v3(n, l->next->v->co, l->v->co);
- mul_v3_fl(n, 0.5);
+ mid_v3_v3v3(p, l->prev->v->co, l->v->co);
+ mid_v3_v3v3(n, l->next->v->co, l->v->co);
copy_v3_v3(v1, cent);
copy_v3_v3(v2, p);
@@ -257,7 +255,7 @@ static float quad_coord(float aa[3], float bb[3], float cc[3], float dd[3], int
f1 = fabsf(f1);
f2 = fabsf(f2);
- f1 = minf(f1, f2);
+ f1 = min_ff(f1, f2);
CLAMP(f1, 0.0f, 1.0f + FLT_EPSILON);
}
else {
@@ -345,9 +343,9 @@ static int mdisp_in_mdispquad(BMLoop *l, BMLoop *tl, float p[3], float *x, float
float v1[3], v2[3], c[3], v3[3], v4[3], e1[3], e2[3];
float eps = FLT_EPSILON * 4000;
- if (len_v3(l->v->no) == 0.0f)
+ if (is_zero_v3(l->v->no))
BM_vert_normal_update_all(l->v);
- if (len_v3(tl->v->no) == 0.0f)
+ if (is_zero_v3(tl->v->no))
BM_vert_normal_update_all(tl->v);
compute_mdisp_quad(tl, v1, v2, v3, v4, e1, e2);
@@ -424,7 +422,7 @@ static void bm_loop_interp_mdisps(BMesh *bm, BMLoop *target, BMFace *source)
float axis_x[3], axis_y[3];
/* ignore 2-edged faces */
- if (target->f->len < 3)
+ if (UNLIKELY(target->f->len < 3))
return;
if (!CustomData_has_layer(&bm->ldata, CD_MDISPS))
@@ -490,7 +488,7 @@ static void bm_loop_interp_mdisps(BMesh *bm, BMLoop *target, BMFace *source)
}
/**
- * smoothes boundaries between multires grids,
+ * smooths boundaries between multires grids,
* including some borders in adjacent faces
*/
void BM_face_multires_bounds_smooth(BMesh *bm, BMFace *f)
@@ -525,8 +523,7 @@ void BM_face_multires_bounds_smooth(BMesh *bm, BMFace *f)
sides = (int)sqrt(mdp->totdisp);
for (y = 0; y < sides; y++) {
- add_v3_v3v3(co1, mdn->disps[y * sides], mdl->disps[y]);
- mul_v3_fl(co1, 0.5);
+ mid_v3_v3v3(co1, mdn->disps[y * sides], mdl->disps[y]);
copy_v3_v3(mdn->disps[y * sides], co1);
copy_v3_v3(mdl->disps[y], co1);
diff --git a/source/blender/bmesh/intern/bmesh_iterators.c b/source/blender/bmesh/intern/bmesh_iterators.c
index 726127fdcad..1cb95d94e9b 100644
--- a/source/blender/bmesh/intern/bmesh_iterators.c
+++ b/source/blender/bmesh/intern/bmesh_iterators.c
@@ -120,6 +120,21 @@ void *BM_iter_as_arrayN(BMesh *bm, const char itype, void *data, int *r_len)
{
BMIter iter;
+ /* we can't rely on coun't being set */
+ switch (itype) {
+ case BM_VERTS_OF_MESH:
+ iter.count = bm->totvert;
+ break;
+ case BM_EDGES_OF_MESH:
+ iter.count = bm->totedge;
+ break;
+ case BM_FACES_OF_MESH:
+ iter.count = bm->totface;
+ break;
+ default:
+ break;
+ }
+
if (BM_iter_init(&iter, bm, itype, data) && iter.count > 0) {
BMElem *ele;
BMElem **array = MEM_mallocN(sizeof(ele) * iter.count, __func__);
@@ -190,10 +205,10 @@ int BM_iter_mesh_count_flag(const char itype, BMesh *bm, const char hflag, const
*/
static void init_iterator(BMIter *iter)
{
- iter->firstvert = iter->nextvert = NULL;
- iter->firstedge = iter->nextedge = NULL;
- iter->firstloop = iter->nextloop = NULL;
- iter->firstpoly = iter->nextpoly = NULL;
+// iter->v_first = iter->v_next = NULL; // UNUSED
+ iter->e_first = iter->e_next = NULL;
+ iter->l_first = iter->l_next = NULL;
+// iter->f_first = iter->f_next = NULL; // UNUSED
iter->ldata = NULL;
}
@@ -229,6 +244,7 @@ void *bmiter__vert_of_mesh_step(BMIter *iter)
void bmiter__edge_of_mesh_begin(BMIter *iter)
{
BLI_mempool_iternew(iter->bm->epool, &iter->pooliter);
+ iter->count = iter->bm->totedge; /* */
}
void *bmiter__edge_of_mesh_step(BMIter *iter)
@@ -256,19 +272,19 @@ void bmiter__edge_of_vert_begin(BMIter *iter)
{
init_iterator(iter);
if (iter->vdata->e) {
- iter->firstedge = iter->vdata->e;
- iter->nextedge = iter->vdata->e;
+ iter->e_first = iter->vdata->e;
+ iter->e_next = iter->vdata->e;
}
}
void *bmiter__edge_of_vert_step(BMIter *iter)
{
- BMEdge *current = iter->nextedge;
+ BMEdge *current = iter->e_next;
- if (iter->nextedge)
- iter->nextedge = bmesh_disk_edge_next(iter->nextedge, iter->vdata);
+ if (iter->e_next)
+ iter->e_next = bmesh_disk_edge_next(iter->e_next, iter->vdata);
- if (iter->nextedge == iter->firstedge) iter->nextedge = NULL;
+ if (iter->e_next == iter->e_first) iter->e_next = NULL;
return current;
}
@@ -284,27 +300,27 @@ void bmiter__face_of_vert_begin(BMIter *iter)
if (iter->vdata->e)
iter->count = bmesh_disk_facevert_count(iter->vdata);
if (iter->count) {
- iter->firstedge = bmesh_disk_faceedge_find_first(iter->vdata->e, iter->vdata);
- iter->nextedge = iter->firstedge;
- iter->firstloop = bmesh_radial_faceloop_find_first(iter->firstedge->l, iter->vdata);
- iter->nextloop = iter->firstloop;
+ iter->e_first = bmesh_disk_faceedge_find_first(iter->vdata->e, iter->vdata);
+ iter->e_next = iter->e_first;
+ iter->l_first = bmesh_radial_faceloop_find_first(iter->e_first->l, iter->vdata);
+ iter->l_next = iter->l_first;
}
}
void *bmiter__face_of_vert_step(BMIter *iter)
{
- BMLoop *current = iter->nextloop;
+ BMLoop *current = iter->l_next;
- if (iter->count && iter->nextloop) {
+ if (iter->count && iter->l_next) {
iter->count--;
- iter->nextloop = bmesh_radial_faceloop_find_next(iter->nextloop, iter->vdata);
- if (iter->nextloop == iter->firstloop) {
- iter->nextedge = bmesh_disk_faceedge_find_next(iter->nextedge, iter->vdata);
- iter->firstloop = bmesh_radial_faceloop_find_first(iter->nextedge->l, iter->vdata);
- iter->nextloop = iter->firstloop;
+ iter->l_next = bmesh_radial_faceloop_find_next(iter->l_next, iter->vdata);
+ if (iter->l_next == iter->l_first) {
+ iter->e_next = bmesh_disk_faceedge_find_next(iter->e_next, iter->vdata);
+ iter->l_first = bmesh_radial_faceloop_find_first(iter->e_next->l, iter->vdata);
+ iter->l_next = iter->l_first;
}
}
- if (!iter->count) iter->nextloop = NULL;
+ if (!iter->count) iter->l_next = NULL;
return current ? current->f : NULL;
}
@@ -322,27 +338,27 @@ void bmiter__loop_of_vert_begin(BMIter *iter)
if (iter->vdata->e)
iter->count = bmesh_disk_facevert_count(iter->vdata);
if (iter->count) {
- iter->firstedge = bmesh_disk_faceedge_find_first(iter->vdata->e, iter->vdata);
- iter->nextedge = iter->firstedge;
- iter->firstloop = bmesh_radial_faceloop_find_first(iter->firstedge->l, iter->vdata);
- iter->nextloop = iter->firstloop;
+ iter->e_first = bmesh_disk_faceedge_find_first(iter->vdata->e, iter->vdata);
+ iter->e_next = iter->e_first;
+ iter->l_first = bmesh_radial_faceloop_find_first(iter->e_first->l, iter->vdata);
+ iter->l_next = iter->l_first;
}
}
void *bmiter__loop_of_vert_step(BMIter *iter)
{
- BMLoop *current = iter->nextloop;
+ BMLoop *current = iter->l_next;
if (iter->count) {
iter->count--;
- iter->nextloop = bmesh_radial_faceloop_find_next(iter->nextloop, iter->vdata);
- if (iter->nextloop == iter->firstloop) {
- iter->nextedge = bmesh_disk_faceedge_find_next(iter->nextedge, iter->vdata);
- iter->firstloop = bmesh_radial_faceloop_find_first(iter->nextedge->l, iter->vdata);
- iter->nextloop = iter->firstloop;
+ iter->l_next = bmesh_radial_faceloop_find_next(iter->l_next, iter->vdata);
+ if (iter->l_next == iter->l_first) {
+ iter->e_next = bmesh_disk_faceedge_find_next(iter->e_next, iter->vdata);
+ iter->l_first = bmesh_radial_faceloop_find_first(iter->e_next->l, iter->vdata);
+ iter->l_next = iter->l_first;
}
}
- if (!iter->count) iter->nextloop = NULL;
+ if (!iter->count) iter->l_next = NULL;
if (current) {
@@ -362,19 +378,19 @@ void bmiter__loops_of_edge_begin(BMIter *iter)
/* note sure why this sets ldata ... */
init_iterator(iter);
- iter->firstloop = iter->nextloop = l;
+ iter->l_first = iter->l_next = l;
}
void *bmiter__loops_of_edge_step(BMIter *iter)
{
- BMLoop *current = iter->nextloop;
+ BMLoop *current = iter->l_next;
- if (iter->nextloop) {
- iter->nextloop = iter->nextloop->radial_next;
+ if (iter->l_next) {
+ iter->l_next = iter->l_next->radial_next;
}
- if (iter->nextloop == iter->firstloop) {
- iter->nextloop = NULL;
+ if (iter->l_next == iter->l_first) {
+ iter->l_next = NULL;
}
if (current) {
@@ -393,23 +409,23 @@ void bmiter__loops_of_loop_begin(BMIter *iter)
/* note sure why this sets ldata ... */
init_iterator(iter);
- iter->firstloop = l;
- iter->nextloop = iter->firstloop->radial_next;
+ iter->l_first = l;
+ iter->l_next = iter->l_first->radial_next;
- if (iter->nextloop == iter->firstloop)
- iter->nextloop = NULL;
+ if (iter->l_next == iter->l_first)
+ iter->l_next = NULL;
}
void *bmiter__loops_of_loop_step(BMIter *iter)
{
- BMLoop *current = iter->nextloop;
+ BMLoop *current = iter->l_next;
- if (iter->nextloop) {
- iter->nextloop = iter->nextloop->radial_next;
+ if (iter->l_next) {
+ iter->l_next = iter->l_next->radial_next;
}
- if (iter->nextloop == iter->firstloop) {
- iter->nextloop = NULL;
+ if (iter->l_next == iter->l_first) {
+ iter->l_next = NULL;
}
if (current) {
@@ -428,20 +444,20 @@ void bmiter__face_of_edge_begin(BMIter *iter)
init_iterator(iter);
if (iter->edata->l) {
- iter->firstloop = iter->edata->l;
- iter->nextloop = iter->edata->l;
+ iter->l_first = iter->edata->l;
+ iter->l_next = iter->edata->l;
}
}
void *bmiter__face_of_edge_step(BMIter *iter)
{
- BMLoop *current = iter->nextloop;
+ BMLoop *current = iter->l_next;
- if (iter->nextloop) {
- iter->nextloop = iter->nextloop->radial_next;
+ if (iter->l_next) {
+ iter->l_next = iter->l_next->radial_next;
}
- if (iter->nextloop == iter->firstloop) iter->nextloop = NULL;
+ if (iter->l_next == iter->l_first) iter->l_next = NULL;
return current ? current->f : NULL;
}
@@ -476,15 +492,15 @@ void *bmiter__vert_of_edge_step(BMIter *iter)
void bmiter__vert_of_face_begin(BMIter *iter)
{
init_iterator(iter);
- iter->firstloop = iter->nextloop = BM_FACE_FIRST_LOOP(iter->pdata);
+ iter->l_first = iter->l_next = BM_FACE_FIRST_LOOP(iter->pdata);
}
void *bmiter__vert_of_face_step(BMIter *iter)
{
- BMLoop *current = iter->nextloop;
+ BMLoop *current = iter->l_next;
- if (iter->nextloop) iter->nextloop = iter->nextloop->next;
- if (iter->nextloop == iter->firstloop) iter->nextloop = NULL;
+ if (iter->l_next) iter->l_next = iter->l_next->next;
+ if (iter->l_next == iter->l_first) iter->l_next = NULL;
return current ? current->v : NULL;
}
@@ -496,15 +512,15 @@ void *bmiter__vert_of_face_step(BMIter *iter)
void bmiter__edge_of_face_begin(BMIter *iter)
{
init_iterator(iter);
- iter->firstloop = iter->nextloop = BM_FACE_FIRST_LOOP(iter->pdata);
+ iter->l_first = iter->l_next = BM_FACE_FIRST_LOOP(iter->pdata);
}
void *bmiter__edge_of_face_step(BMIter *iter)
{
- BMLoop *current = iter->nextloop;
+ BMLoop *current = iter->l_next;
- if (iter->nextloop) iter->nextloop = iter->nextloop->next;
- if (iter->nextloop == iter->firstloop) iter->nextloop = NULL;
+ if (iter->l_next) iter->l_next = iter->l_next->next;
+ if (iter->l_next == iter->l_first) iter->l_next = NULL;
return current ? current->e : NULL;
}
@@ -516,15 +532,15 @@ void *bmiter__edge_of_face_step(BMIter *iter)
void bmiter__loop_of_face_begin(BMIter *iter)
{
init_iterator(iter);
- iter->firstloop = iter->nextloop = BM_FACE_FIRST_LOOP(iter->pdata);
+ iter->l_first = iter->l_next = BM_FACE_FIRST_LOOP(iter->pdata);
}
void *bmiter__loop_of_face_step(BMIter *iter)
{
- BMLoop *current = iter->nextloop;
+ BMLoop *current = iter->l_next;
- if (iter->nextloop) iter->nextloop = iter->nextloop->next;
- if (iter->nextloop == iter->firstloop) iter->nextloop = NULL;
+ if (iter->l_next) iter->l_next = iter->l_next->next;
+ if (iter->l_next == iter->l_first) iter->l_next = NULL;
return current;
}
diff --git a/source/blender/bmesh/intern/bmesh_iterators.h b/source/blender/bmesh/intern/bmesh_iterators.h
index 8d0eeca31ed..3c42b3d610c 100644
--- a/source/blender/bmesh/intern/bmesh_iterators.h
+++ b/source/blender/bmesh/intern/bmesh_iterators.h
@@ -95,23 +95,27 @@ extern const char bm_iter_itype_htype_map[BM_ITYPE_MAX];
for (ele = BM_iter_new(iter, NULL, itype, data), indexvar = 0; ele; ele = BM_iter_step(iter), (indexvar)++)
/* Iterator Structure */
+/* note: some of these vars are not used,
+ * so they have beem commented to save stack space since this struct is used all over */
typedef struct BMIter {
BLI_mempool_iter pooliter;
- BMVert *firstvert, *nextvert, *vdata;
- BMEdge *firstedge, *nextedge, *edata;
- BMLoop *firstloop, *nextloop, *ldata, *l;
- BMFace *firstpoly, *nextpoly, *pdata;
+ BMVert /* *v_first, *v_next, */ *vdata;
+ BMEdge *e_first, *e_next, *edata;
+ BMLoop *l_first, *l_next, *ldata;
+ BMFace /* *f_first, *f_next, */ *pdata;
BMesh *bm;
void (*begin)(struct BMIter *iter);
void *(*step)(struct BMIter *iter);
+ /*
union {
void *p;
int i;
long l;
float f;
} filter;
- int count;
+ */
+ int count; /* note, only some iterators set this, don't rely on it */
char itype;
} BMIter;
diff --git a/source/blender/bmesh/intern/bmesh_marking.c b/source/blender/bmesh/intern/bmesh_marking.c
index c0439311104..9af65d7dd7e 100644
--- a/source/blender/bmesh/intern/bmesh_marking.c
+++ b/source/blender/bmesh/intern/bmesh_marking.c
@@ -584,8 +584,7 @@ void BM_editselection_center(BMEditSelection *ese, float r_center[3])
}
else if (ese->htype == BM_EDGE) {
BMEdge *eed = (BMEdge *)ese->ele;
- add_v3_v3v3(r_center, eed->v1->co, eed->v2->co);
- mul_v3_fl(r_center, 0.5);
+ mid_v3_v3v3(r_center, eed->v1->co, eed->v2->co);
}
else if (ese->htype == BM_FACE) {
BMFace *efa = (BMFace *)ese->ele;
@@ -672,7 +671,7 @@ void BM_editselection_plane(BMEditSelection *ese, float r_plane[3])
* we cant make a crossvec from a vec thats the same as the vec
* unlikely but possible, so make sure if the normal is (0, 0, 1)
* that vec isn't the same or in the same direction even. */
- if (efa->len < 3) {
+ if (UNLIKELY(efa->len < 3)) {
/* crappy fallback method */
if (efa->no[0] < 0.5f) vec[0] = 1.0f;
else if (efa->no[1] < 0.5f) vec[1] = 1.0f;
diff --git a/source/blender/bmesh/intern/bmesh_mesh.c b/source/blender/bmesh/intern/bmesh_mesh.c
index cf593627e8d..d3e3bcd3556 100644
--- a/source/blender/bmesh/intern/bmesh_mesh.c
+++ b/source/blender/bmesh/intern/bmesh_mesh.c
@@ -57,7 +57,7 @@ static void bm_mempool_init(BMesh *bm, const BMAllocTemplate *allocsize)
bm_mesh_chunksize_default.totface, BLI_MEMPOOL_ALLOW_ITER);
#ifdef USE_BMESH_HOLES
- bm->looplistpool = BLI_mempool_create(sizeof(BMLoopList), allocsize[3], allocsize[3], FALSE, FALSE);
+ bm->looplistpool = BLI_mempool_create(sizeof(BMLoopList), 512, 512, 0);
#endif
/* allocate one flag pool that we don't get rid of. */
@@ -85,6 +85,11 @@ BMesh *BM_mesh_create(BMAllocTemplate *allocsize)
bm->stackdepth = 1;
bm->totflags = 1;
+ CustomData_reset(&bm->vdata);
+ CustomData_reset(&bm->edata);
+ CustomData_reset(&bm->ldata);
+ CustomData_reset(&bm->pdata);
+
return bm;
}
@@ -282,7 +287,7 @@ void BM_mesh_normals_update(BMesh *bm, const short skip_hidden)
if (skip_hidden && BM_elem_flag_test(v, BM_ELEM_HIDDEN))
continue;
- if (normalize_v3(v->no) == 0.0f) {
+ if (UNLIKELY(normalize_v3(v->no) == 0.0f)) {
normalize_v3_v3(v->no, v->co);
}
}
@@ -295,7 +300,7 @@ static void UNUSED_FUNCTION(bm_mdisps_space_set)(Object *ob, BMesh *bm, int from
/* switch multires data out of tangent space */
if (CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
BMEditMesh *em = BMEdit_Create(bm, FALSE);
- DerivedMesh *dm = CDDM_from_BMEditMesh(em, NULL, TRUE, FALSE);
+ DerivedMesh *dm = CDDM_from_editbmesh(em, TRUE, FALSE);
MDisps *mdisps;
BMFace *f;
BMIter iter;
@@ -356,7 +361,7 @@ void bmesh_edit_begin(BMesh *UNUSED(bm), int UNUSED(type_flag))
* (loop cuts, edge subdivides, etc) are not reflected in the higher levels of
* the mesh at all, which doesn't seem right. Turning off completely for now,
* until this is shown to be better for certain types of mesh edits. */
-#if BMOP_UNTAN_MULTIRES_ENABLED
+#ifdef BMOP_UNTAN_MULTIRES_ENABLED
/* switch multires data out of tangent space */
if ((type_flag & BMO_OP_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
bmesh_mdisps_space_set(bm, MULTIRES_SPACE_TANGENT, MULTIRES_SPACE_ABSOLUTE);
@@ -374,7 +379,7 @@ void bmesh_edit_begin(BMesh *UNUSED(bm), int UNUSED(type_flag))
void bmesh_edit_end(BMesh *bm, int UNUSED(flag))
{
/* BMO_OP_FLAG_UNTAN_MULTIRES disabled for now, see comment above in bmesh_edit_begin. */
-#if BMOP_UNTAN_MULTIRES_ENABLED
+#ifdef BMOP_UNTAN_MULTIRES_ENABLED
/* switch multires data into tangent space */
if ((flag & BMO_OP_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
/* set normals to their previous winding */
@@ -665,7 +670,7 @@ void BM_mesh_remap(BMesh *bm, int *vert_idx, int *edge_idx, int *face_idx)
/* Verts' pointers, only edge pointers... */
if (eptr_map) {
BM_ITER_MESH (ve, &iter, bm, BM_VERTS_OF_MESH) {
-/* printf("Vert e: %p -> %p\n", ve->e, BLI_ghash_lookup(eptr_map, (const void*)ve->e));*/
+/* printf("Vert e: %p -> %p\n", ve->e, BLI_ghash_lookup(eptr_map, (const void *)ve->e));*/
ve->e = BLI_ghash_lookup(eptr_map, (const void *)ve->e);
}
}
@@ -675,20 +680,20 @@ void BM_mesh_remap(BMesh *bm, int *vert_idx, int *edge_idx, int *face_idx)
if (vptr_map || eptr_map) {
BM_ITER_MESH (ed, &iter, bm, BM_EDGES_OF_MESH) {
if (vptr_map) {
-/* printf("Edge v1: %p -> %p\n", ed->v1, BLI_ghash_lookup(vptr_map, (const void*)ed->v1));*/
-/* printf("Edge v2: %p -> %p\n", ed->v2, BLI_ghash_lookup(vptr_map, (const void*)ed->v2));*/
+/* printf("Edge v1: %p -> %p\n", ed->v1, BLI_ghash_lookup(vptr_map, (const void *)ed->v1));*/
+/* printf("Edge v2: %p -> %p\n", ed->v2, BLI_ghash_lookup(vptr_map, (const void* )ed->v2));*/
ed->v1 = BLI_ghash_lookup(vptr_map, (const void *)ed->v1);
ed->v2 = BLI_ghash_lookup(vptr_map, (const void *)ed->v2);
}
if (eptr_map) {
/* printf("Edge v1_disk_link prev: %p -> %p\n", ed->v1_disk_link.prev,*/
-/* BLI_ghash_lookup(eptr_map, (const void*)ed->v1_disk_link.prev));*/
+/* BLI_ghash_lookup(eptr_map, (const void *)ed->v1_disk_link.prev));*/
/* printf("Edge v1_disk_link next: %p -> %p\n", ed->v1_disk_link.next,*/
-/* BLI_ghash_lookup(eptr_map, (const void*)ed->v1_disk_link.next));*/
+/* BLI_ghash_lookup(eptr_map, (const void *)ed->v1_disk_link.next));*/
/* printf("Edge v2_disk_link prev: %p -> %p\n", ed->v2_disk_link.prev,*/
-/* BLI_ghash_lookup(eptr_map, (const void*)ed->v2_disk_link.prev));*/
+/* BLI_ghash_lookup(eptr_map, (const void *)ed->v2_disk_link.prev));*/
/* printf("Edge v2_disk_link next: %p -> %p\n", ed->v2_disk_link.next,*/
-/* BLI_ghash_lookup(eptr_map, (const void*)ed->v2_disk_link.next));*/
+/* BLI_ghash_lookup(eptr_map, (const void *)ed->v2_disk_link.next));*/
ed->v1_disk_link.prev = BLI_ghash_lookup(eptr_map, (const void *)ed->v1_disk_link.prev);
ed->v1_disk_link.next = BLI_ghash_lookup(eptr_map, (const void *)ed->v1_disk_link.next);
ed->v2_disk_link.prev = BLI_ghash_lookup(eptr_map, (const void *)ed->v2_disk_link.prev);
@@ -701,15 +706,15 @@ void BM_mesh_remap(BMesh *bm, int *vert_idx, int *edge_idx, int *face_idx)
BM_ITER_MESH (fa, &iter, bm, BM_FACES_OF_MESH) {
BM_ITER_ELEM (lo, &iterl, fa, BM_LOOPS_OF_FACE) {
if (vptr_map) {
-/* printf("Loop v: %p -> %p\n", lo->v, BLI_ghash_lookup(vptr_map, (const void*)lo->v));*/
+/* printf("Loop v: %p -> %p\n", lo->v, BLI_ghash_lookup(vptr_map, (const void *)lo->v));*/
lo->v = BLI_ghash_lookup(vptr_map, (const void *)lo->v);
}
if (eptr_map) {
-/* printf("Loop e: %p -> %p\n", lo->e, BLI_ghash_lookup(eptr_map, (const void*)lo->e));*/
+/* printf("Loop e: %p -> %p\n", lo->e, BLI_ghash_lookup(eptr_map, (const void *)lo->e));*/
lo->e = BLI_ghash_lookup(eptr_map, (const void *)lo->e);
}
if (fptr_map) {
-/* printf("Loop f: %p -> %p\n", lo->f, BLI_ghash_lookup(fptr_map, (const void*)lo->f));*/
+/* printf("Loop f: %p -> %p\n", lo->f, BLI_ghash_lookup(fptr_map, (const void *)lo->f));*/
lo->f = BLI_ghash_lookup(fptr_map, (const void *)lo->f);
}
}
diff --git a/source/blender/bmesh/intern/bmesh_mesh_conv.c b/source/blender/bmesh/intern/bmesh_mesh_conv.c
index 51c8b5d3bd8..62abf43829b 100644
--- a/source/blender/bmesh/intern/bmesh_mesh_conv.c
+++ b/source/blender/bmesh/intern/bmesh_mesh_conv.c
@@ -314,7 +314,7 @@ void BM_mesh_bm_from_me(BMesh *bm, Mesh *me, int set_key, int act_key_nr)
f = BM_face_create(bm, verts, fedges, mpoly->totloop, FALSE);
- if (!f) {
+ if (UNLIKELY(f == NULL)) {
printf("%s: Warning! Bad face in mesh"
" \"%s\" at index %d!, skipping\n",
__func__, me->id.name + 2, i);
@@ -536,7 +536,9 @@ void BM_mesh_bm_to_me(BMesh *bm, Mesh *me, int dotess)
oldverts = me->mvert;
/* don't free this yet */
- CustomData_set_layer(&me->vdata, CD_MVERT, NULL);
+ if (oldverts) {
+ CustomData_set_layer(&me->vdata, CD_MVERT, NULL);
+ }
/* free custom data */
CustomData_free(&me->vdata, me->totvert);
@@ -758,7 +760,7 @@ void BM_mesh_bm_to_me(BMesh *bm, Mesh *me, int dotess)
}
if (!currkey) {
- currkey = add_keyblock(me->key, bm->vdata.layers[i].name);
+ currkey = BKE_keyblock_add(me->key, bm->vdata.layers[i].name);
currkey->uid = bm->vdata.layers[i].uid;
}
diff --git a/source/blender/bmesh/intern/bmesh_mods.c b/source/blender/bmesh/intern/bmesh_mods.c
index 73e2d83520c..62374d8b7bb 100644
--- a/source/blender/bmesh/intern/bmesh_mods.c
+++ b/source/blender/bmesh/intern/bmesh_mods.c
@@ -130,6 +130,7 @@ int BM_disk_dissolve(BMesh *bm, BMVert *v)
/* this code for handling 2 and 3-valence verts
* may be totally bad */
if (keepedge == NULL && len == 3) {
+#if 0
/* handle specific case for three-valence. solve it by
* increasing valence to four. this may be hackish. . */
BMLoop *loop = e->l;
@@ -140,6 +141,13 @@ int BM_disk_dissolve(BMesh *bm, BMVert *v)
if (!BM_disk_dissolve(bm, v)) {
return FALSE;
}
+#else
+ BM_faces_join_pair(bm, e->l->f, e->l->radial_next->f, e, TRUE);
+
+ if (!BM_vert_collapse_faces(bm, v->e, v, 1.0, FALSE, TRUE)) {
+ return FALSE;
+ }
+#endif
return TRUE;
}
else if (keepedge == NULL && len == 2) {
@@ -188,8 +196,9 @@ int BM_disk_dissolve(BMesh *bm, BMVert *v)
} while (e != v->e);
}
- /* collapse the verte */
- e = BM_vert_collapse_faces(bm, baseedge, v, 1.0, TRUE, TRUE);
+ /* collapse the vertex */
+ /* note, the baseedge can be a boundary of manifold, use this as join_faces arg */
+ e = BM_vert_collapse_faces(bm, baseedge, v, 1.0, !BM_edge_is_boundary(baseedge), TRUE);
if (!e) {
return FALSE;
@@ -428,7 +437,7 @@ BMFace *BM_face_split_n(BMesh *bm, BMFace *f, BMVert *v1, BMVert *v2, float cos[
/* bmesh_semv returns in newe the edge going from newv to tv */
copy_v3_v3(newv->co, cos[i]);
- /* interpolate the loop data for the loops with v==newv, using orig face */
+ /* interpolate the loop data for the loops with (v == newv), using orig face */
for (j = 0; j < 2; j++) {
BMEdge *e_iter = (j == 0) ? e : newe;
BMLoop *l_iter = e_iter->l;
@@ -461,9 +470,6 @@ BMFace *BM_face_split_n(BMesh *bm, BMFace *f, BMVert *v1, BMVert *v2, float cos[
* both collapse a vertex and return a new edge.
* Except this takes a factor and merges custom data.
*
- * BMESH_TODO:
- * Insert error checking for KV valance.
- *
* \param bm The bmesh
* \param ke The edge to collapse
* \param kv The vertex to collapse into the edge
@@ -558,7 +564,7 @@ BMEdge *BM_vert_collapse_faces(BMesh *bm, BMEdge *ke, BMVert *kv, float fac,
/* cant kill data we loop on, build a list and remove those */
BLI_array_empty(bad_faces);
BM_ITER_ELEM (f, &fiter, verts[i], BM_FACES_OF_VERT) {
- if (f->len < 3) {
+ if (UNLIKELY(f->len < 3)) {
BLI_array_append(bad_faces, f);
}
}
diff --git a/source/blender/bmesh/intern/bmesh_opdefines.c b/source/blender/bmesh/intern/bmesh_opdefines.c
index 362157ad71b..31698f0abc1 100644
--- a/source/blender/bmesh/intern/bmesh_opdefines.c
+++ b/source/blender/bmesh/intern/bmesh_opdefines.c
@@ -114,6 +114,26 @@ static BMOpDefine bmo_smooth_vert_def = {
};
/*
+ * Vertext Smooth Laplacian
+ * Smooths vertices by using Laplacian smoothing propose by.
+ * Desbrun, et al. Implicit Fairing of Irregular Meshes using Diffusion and Curvature Flow
+*/
+static BMOpDefine bmo_smooth_laplacian_vert_def = {
+ "smooth_laplacian_vert",
+ {{BMO_OP_SLOT_ELEMENT_BUF, "verts"}, //input vertices
+ {BMO_OP_SLOT_FLT, "lambda"}, //lambda param
+ {BMO_OP_SLOT_FLT, "lambda_border"}, //lambda param in border
+ {BMO_OP_SLOT_BOOL, "use_x"}, //Smooth object along X axis
+ {BMO_OP_SLOT_BOOL, "use_y"}, //Smooth object along Y axis
+ {BMO_OP_SLOT_BOOL, "use_z"}, //Smooth object along Z axis
+ {BMO_OP_SLOT_BOOL, "volume_preservation"}, //Apply volume preservation after smooth
+ {0} /* null-terminating sentinel */,
+ },
+ bmo_smooth_laplacian_vert_exec,
+ 0
+};
+
+/*
* Right-Hand Faces
*
* Computes an "outside" normal for the specified input faces.
@@ -679,6 +699,7 @@ static BMOpDefine bmo_dissolve_faces_def = {
static BMOpDefine bmo_dissolve_limit_def = {
"dissolve_limit",
{{BMO_OP_SLOT_FLT, "angle_limit"}, /* total rotation angle (degrees) */
+ {BMO_OP_SLOT_BOOL, "use_dissolve_boundaries"},
{BMO_OP_SLOT_ELEMENT_BUF, "verts"},
{BMO_OP_SLOT_ELEMENT_BUF, "edges"},
{0} /* null-terminating sentinel */},
@@ -698,6 +719,15 @@ static BMOpDefine bmo_triangulate_def = {
BMO_OP_FLAG_UNTAN_MULTIRES
};
+static BMOpDefine bmo_unsubdivide_def = {
+ "unsubdivide",
+ {{BMO_OP_SLOT_ELEMENT_BUF, "verts"}, /* input vertices */
+ {BMO_OP_SLOT_INT, "iterations"},
+ {0} /* null-terminating sentinel */},
+ bmo_unsubdivide_exec,
+ BMO_OP_FLAG_UNTAN_MULTIRES
+};
+
static BMOpDefine bmo_subdivide_edges_def = {
"subdivide_edges",
{{BMO_OP_SLOT_ELEMENT_BUF, "edges"},
@@ -792,10 +822,11 @@ static BMOpDefine bmo_spin_def = {
*/
static BMOpDefine bmo_similar_faces_def = {
"similar_faces",
- {{BMO_OP_SLOT_ELEMENT_BUF, "faces"}, /* input faces */
- {BMO_OP_SLOT_ELEMENT_BUF, "faceout"}, /* output faces */
- {BMO_OP_SLOT_INT, "type"}, /* type of selection */
- {BMO_OP_SLOT_FLT, "thresh"}, /* threshold of selection */
+ {{BMO_OP_SLOT_ELEMENT_BUF, "faces"}, /* input faces */
+ {BMO_OP_SLOT_ELEMENT_BUF, "faceout"}, /* output faces */
+ {BMO_OP_SLOT_INT, "type"}, /* type of selection */
+ {BMO_OP_SLOT_FLT, "thresh"}, /* threshold of selection */
+ {BMO_OP_SLOT_INT, "compare"}, /* comparison method */
{0} /* null-terminating sentinel */},
bmo_similar_faces_exec,
0
@@ -808,10 +839,11 @@ static BMOpDefine bmo_similar_faces_def = {
*/
static BMOpDefine bmo_similar_edges_def = {
"similar_edges",
- {{BMO_OP_SLOT_ELEMENT_BUF, "edges"}, /* input edges */
- {BMO_OP_SLOT_ELEMENT_BUF, "edgeout"}, /* output edges */
- {BMO_OP_SLOT_INT, "type"}, /* type of selection */
- {BMO_OP_SLOT_FLT, "thresh"}, /* threshold of selection */
+ {{BMO_OP_SLOT_ELEMENT_BUF, "edges"}, /* input edges */
+ {BMO_OP_SLOT_ELEMENT_BUF, "edgeout"}, /* output edges */
+ {BMO_OP_SLOT_INT, "type"}, /* type of selection */
+ {BMO_OP_SLOT_FLT, "thresh"}, /* threshold of selection */
+ {BMO_OP_SLOT_INT, "compare"}, /* comparison method */
{0} /* null-terminating sentinel */},
bmo_similar_edges_exec,
0
@@ -824,10 +856,11 @@ static BMOpDefine bmo_similar_edges_def = {
*/
static BMOpDefine bmo_similar_verts_def = {
"similar_verts",
- {{BMO_OP_SLOT_ELEMENT_BUF, "verts"}, /* input vertices */
- {BMO_OP_SLOT_ELEMENT_BUF, "vertout"}, /* output vertices */
- {BMO_OP_SLOT_INT, "type"}, /* type of selection */
- {BMO_OP_SLOT_FLT, "thresh"}, /* threshold of selection */
+ {{BMO_OP_SLOT_ELEMENT_BUF, "verts"}, /* input vertices */
+ {BMO_OP_SLOT_ELEMENT_BUF, "vertout"}, /* output vertices */
+ {BMO_OP_SLOT_INT, "type"}, /* type of selection */
+ {BMO_OP_SLOT_FLT, "thresh"}, /* threshold of selection */
+ {BMO_OP_SLOT_INT, "compare"}, /* comparison method */
{0} /* null-terminating sentinel */},
bmo_similar_verts_exec,
0
@@ -1152,6 +1185,7 @@ static BMOpDefine bmo_slide_vert_def = {
BMO_OP_FLAG_UNTAN_MULTIRES
};
+#ifdef WITH_BULLET
/*
* Convex Hull
*
@@ -1181,6 +1215,30 @@ static BMOpDefine bmo_convex_hull_def = {
bmo_convex_hull_exec,
0
};
+#endif
+
+/*
+ * Symmetrize
+ *
+ * Mekes the mesh elements in the "input" slot symmetrical. Unlike
+ * normal mirroring, it only copies in one direction, as specified by
+ * the "direction" slot. The edges and faces that cross the plane of
+ * symmetry are split as needed to enforce symmetry.
+ *
+ * All new vertices, edges, and faces are added to the "geomout" slot.
+ */
+static BMOpDefine bmo_symmetrize_def = {
+ "symmetrize",
+ {{BMO_OP_SLOT_ELEMENT_BUF, "input"},
+ {BMO_OP_SLOT_INT, "direction"},
+
+ /* Outputs */
+ {BMO_OP_SLOT_ELEMENT_BUF, "geomout"},
+
+ {0} /* null-terminating sentinel */},
+ bmo_symmetrize_exec,
+ 0
+};
BMOpDefine *opdefines[] = {
&bmo_automerge_def,
@@ -1194,7 +1252,9 @@ BMOpDefine *opdefines[] = {
&bmo_collapse_uvs_def,
&bmo_connect_verts_def,
&bmo_contextual_create_def,
+#ifdef WITH_BULLET
&bmo_convex_hull_def,
+#endif
&bmo_create_circle_def,
&bmo_create_cone_def,
&bmo_create_cube_def,
@@ -1241,15 +1301,18 @@ BMOpDefine *opdefines[] = {
&bmo_similar_verts_def,
&bmo_slide_vert_def,
&bmo_smooth_vert_def,
+ &bmo_smooth_laplacian_vert_def,
&bmo_solidify_def,
&bmo_spin_def,
&bmo_split_def,
&bmo_split_edges_def,
&bmo_subdivide_edges_def,
+ &bmo_symmetrize_def,
&bmo_transform_def,
&bmo_translate_def,
&bmo_triangle_fill_def,
&bmo_triangulate_def,
+ &bmo_unsubdivide_def,
&bmo_weld_verts_def,
&bmo_wireframe_def,
diff --git a/source/blender/bmesh/intern/bmesh_operator_api.h b/source/blender/bmesh/intern/bmesh_operator_api.h
index 0674103162c..a2f4cdc8c6a 100644
--- a/source/blender/bmesh/intern/bmesh_operator_api.h
+++ b/source/blender/bmesh/intern/bmesh_operator_api.h
@@ -266,6 +266,16 @@ enum {
DEL_ONLYTAGGED
};
+typedef enum {
+ BMO_SYMMETRIZE_NEGATIVE_X,
+ BMO_SYMMETRIZE_NEGATIVE_Y,
+ BMO_SYMMETRIZE_NEGATIVE_Z,
+
+ BMO_SYMMETRIZE_POSITIVE_X,
+ BMO_SYMMETRIZE_POSITIVE_Y,
+ BMO_SYMMETRIZE_POSITIVE_Z,
+} BMO_SymmDirection;
+
void BMO_op_flag_enable(BMesh *bm, BMOperator *op, const int op_flag);
void BMO_op_flag_disable(BMesh *bm, BMOperator *op, const int op_flag);
diff --git a/source/blender/bmesh/intern/bmesh_operators.c b/source/blender/bmesh/intern/bmesh_operators.c
index 53b95c97c8b..2413f3a7be0 100644
--- a/source/blender/bmesh/intern/bmesh_operators.c
+++ b/source/blender/bmesh/intern/bmesh_operators.c
@@ -36,6 +36,8 @@
#include "BLI_listbase.h"
#include "BLI_array.h"
+#include "BLF_translation.h"
+
#include "bmesh.h"
#include "intern/bmesh_private.h"
@@ -49,16 +51,16 @@ static int bmo_opname_to_opcode(const char *opname);
static const char *bmo_error_messages[] = {
NULL,
- "Self intersection error",
- "Could not dissolve vert",
- "Could not connect vertices",
- "Could not traverse mesh",
- "Could not dissolve faces",
- "Could not dissolve vertices",
- "Tessellation error",
- "Can not deal with non-manifold geometry",
- "Invalid selection",
- "Internal mesh error",
+ N_("Self intersection error"),
+ N_("Could not dissolve vert"),
+ N_("Could not connect vertices"),
+ N_("Could not traverse mesh"),
+ N_("Could not dissolve faces"),
+ N_("Could not dissolve vertices"),
+ N_("Tessellation error"),
+ N_("Cannot deal with non-manifold geometry"),
+ N_("Invalid selection"),
+ N_("Internal mesh error"),
};
@@ -1024,7 +1026,7 @@ static void bmo_flag_layer_alloc(BMesh *bm)
int i;
BMIter iter;
- BLI_mempool *oldpool = bm->toolflagpool; /* old flag pool */
+ BLI_mempool *oldpool = bm->toolflagpool; /* old flag pool */
BLI_mempool *newpool;
void *oldflags;
@@ -1241,7 +1243,9 @@ void BMO_error_raise(BMesh *bm, BMOperator *owner, int errcode, const char *msg)
BMOpError *err = MEM_callocN(sizeof(BMOpError), "bmop_error");
err->errorcode = errcode;
- if (!msg) msg = bmo_error_messages[errcode];
+ if (!msg) {
+ msg = bmo_error_messages[errcode];
+ }
err->msg = msg;
err->op = owner;
@@ -1253,7 +1257,7 @@ int BMO_error_occurred(BMesh *bm)
return bm->errorstack.first != NULL;
}
-/* returns error code or 0 if no erro */
+/* returns error code or 0 if no error */
int BMO_error_get(BMesh *bm, const char **msg, BMOperator **op)
{
BMOpError *err = bm->errorstack.first;
diff --git a/source/blender/bmesh/intern/bmesh_operators.h b/source/blender/bmesh/intern/bmesh_operators.h
index b1da8ecb275..14da93302b9 100644
--- a/source/blender/bmesh/intern/bmesh_operators.h
+++ b/source/blender/bmesh/intern/bmesh_operators.h
@@ -46,11 +46,18 @@ enum {
SUBDIV_SELECT_LOOPCUT
};
+enum {
+ SIM_CMP_EQ = 0,
+ SIM_CMP_GT,
+ SIM_CMP_LT
+};
+
/* similar face selection slot values */
enum {
SIMFACE_MATERIAL = 201,
SIMFACE_IMAGE,
SIMFACE_AREA,
+ SIMFACE_SIDES,
SIMFACE_PERIMETER,
SIMFACE_NORMAL,
SIMFACE_COPLANAR
diff --git a/source/blender/bmesh/intern/bmesh_operators_private.h b/source/blender/bmesh/intern/bmesh_operators_private.h
index dc1bdaa4689..65c9cf0c421 100644
--- a/source/blender/bmesh/intern/bmesh_operators_private.h
+++ b/source/blender/bmesh/intern/bmesh_operators_private.h
@@ -91,15 +91,18 @@ void bmo_similar_faces_exec(BMesh *bm, BMOperator *op);
void bmo_similar_verts_exec(BMesh *bm, BMOperator *op);
void bmo_slide_vert_exec(BMesh *bm, BMOperator *op);
void bmo_smooth_vert_exec(BMesh *bm, BMOperator *op);
+void bmo_smooth_laplacian_vert_exec(BMesh *bm, BMOperator *op);
void bmo_solidify_face_region_exec(BMesh *bm, BMOperator *op);
void bmo_spin_exec(BMesh *bm, BMOperator *op);
void bmo_split_edges_exec(BMesh *bm, BMOperator *op);
void bmo_split_exec(BMesh *bm, BMOperator *op);
void bmo_subdivide_edges_exec(BMesh *bm, BMOperator *op);
+void bmo_symmetrize_exec(BMesh *bm, BMOperator *op);
void bmo_transform_exec(BMesh *bm, BMOperator *op);
void bmo_translate_exec(BMesh *bm, BMOperator *op);
void bmo_triangle_fill_exec(BMesh *bm, BMOperator *op);
void bmo_triangulate_exec(BMesh *bm, BMOperator *op);
+void bmo_unsubdivide_exec(BMesh *bm, BMOperator *op);
void bmo_weld_verts_exec(BMesh *bm, BMOperator *op);
void bmo_wireframe_exec(BMesh *bm, BMOperator *op);
diff --git a/source/blender/bmesh/intern/bmesh_polygon.c b/source/blender/bmesh/intern/bmesh_polygon.c
index eb2b7721bdc..98edceb30a2 100644
--- a/source/blender/bmesh/intern/bmesh_polygon.c
+++ b/source/blender/bmesh/intern/bmesh_polygon.c
@@ -313,7 +313,7 @@ void poly_rotate_plane(const float normal[3], float (*verts)[3], const int nvert
float up[3] = {0.0f, 0.0f, 1.0f}, axis[3], q[4];
float mat[3][3];
- double angle;
+ float angle;
int i;
cross_v3_v3v3(axis, normal, up);
@@ -329,7 +329,7 @@ void poly_rotate_plane(const float normal[3], float (*verts)[3], const int nvert
axis[2] = 0.0f;
}
- axis_angle_to_quat(q, axis, (float)angle);
+ axis_angle_to_quat(q, axis, angle);
quat_to_mat3(mat, q);
for (i = 0; i < nverts; i++)
@@ -507,8 +507,8 @@ static int line_crosses_v2f(const float v1[2], const float v2[2], const float v3
#define GETMIN2_AXIS(a, b, ma, mb, axis) \
{ \
- ma[axis] = minf(a[axis], b[axis]); \
- mb[axis] = maxf(a[axis], b[axis]); \
+ ma[axis] = min_ff(a[axis], b[axis]); \
+ mb[axis] = max_ff(a[axis], b[axis]); \
} (void)0
#define GETMIN2(a, b, ma, mb) \
@@ -994,8 +994,8 @@ void BM_face_legal_splits(BMesh *bm, BMFace *f, BMLoop *(*loops)[2], int len)
for (i = 0, l = BM_FACE_FIRST_LOOP(f); i < f->len; i++, l = l->next) {
p1 = projverts[i];
- out[0] = maxf(out[0], p1[0]);
- out[1] = maxf(out[1], p1[1]);
+ out[0] = max_ff(out[0], p1[0]);
+ out[1] = max_ff(out[1], p1[1]);
/* out[2] = 0.0f; */ /* keep at zero */
p1[2] = 0.0f;
diff --git a/source/blender/bmesh/intern/bmesh_queries.c b/source/blender/bmesh/intern/bmesh_queries.c
index d850eb34477..4b07dd74eef 100644
--- a/source/blender/bmesh/intern/bmesh_queries.c
+++ b/source/blender/bmesh/intern/bmesh_queries.c
@@ -298,6 +298,14 @@ int BM_edge_in_face(BMFace *f, BMEdge *e)
}
/**
+ * Returns whether or not a given edge is is part of a given loop.
+ */
+int BM_edge_in_loop(BMEdge *e, BMLoop *l)
+{
+ return (l->e == e || l->prev->e == e);
+}
+
+/**
* Returns whether or not two vertices are in
* a given edge
*/
@@ -316,6 +324,96 @@ BMVert *BM_edge_other_vert(BMEdge *e, BMVert *v)
}
/**
+ * Given a edge and a loop (assumes the edge is manifold). returns
+ * the other faces loop, sharing the same vertex.
+ *
+ * <pre>
+ * +-------------------+
+ * | |
+ * | |
+ * |l_other <-- return |
+ * +-------------------+ <-- A manifold edge between 2 faces
+ * |l e <-- edge |
+ * |^ <-------- loop |
+ * | |
+ * +-------------------+
+ * </pre>
+ */
+BMLoop *BM_edge_other_loop(BMEdge *e, BMLoop *l)
+{
+ BMLoop *l_other;
+
+ // BLI_assert(BM_edge_is_manifold(e)); // TOO strict, just check if we have another radial face
+ BLI_assert(e->l && e->l->radial_next != e->l);
+ BLI_assert(BM_vert_in_edge(e, l->v));
+
+ l_other = (l->e == e) ? l : l->prev;
+ l_other = l_other->radial_next;
+ BLI_assert(l_other->e == e);
+
+ if (l_other->v == l->v) {
+ /* pass */
+ }
+ else if (l_other->next->v == l->v) {
+ l_other = l_other->next;
+ }
+ else {
+ BLI_assert(0);
+ }
+
+ return l_other;
+}
+
+/**
+ * Utility function to step around a fan of loops,
+ * using an edge to mark the previous side.
+ *
+ * \note all edges must be manifold,
+ * once a non manifold edge is hit, return NULL.
+ *
+ * <pre>
+ * ,.,-->|
+ * _,-' |
+ * ,' | (notice how 'e_step'
+ * / | and 'l' define the
+ * / | direction the arrow
+ * | return | points).
+ * | loop --> |
+ * ---------------------+---------------------
+ * ^ l --> |
+ * | |
+ * assign e_step |
+ * |
+ * begin e_step ----> |
+ * |
+ * </pre>
+ */
+
+BMLoop *BM_vert_step_fan_loop(BMLoop *l, BMEdge **e_step)
+{
+ BMEdge *e_prev = *e_step;
+ BMEdge *e_next;
+ if (l->e == e_prev) {
+ e_next = l->prev->e;
+ }
+ else if (l->prev->e == e_prev) {
+ e_next = l->e;
+ }
+ else {
+ BLI_assert(0);
+ }
+
+ if (BM_edge_is_manifold(e_next)) {
+ return BM_edge_other_loop((*e_step = e_next), l);
+ }
+ else {
+ return NULL;
+ }
+}
+
+
+
+/**
* The function takes a vertex at the center of a fan and returns the opposite edge in the fan.
* All edges in the fan must be manifold, otherwise return NULL.
*
@@ -1018,6 +1116,28 @@ BMEdge *BM_edge_exists(BMVert *v1, BMVert *v2)
}
/**
+ * Returns an edge sharing the same vertices as this one.
+ * This isn't an invalid state but tools should clean up these cases before
+ * returning the mesh to the user.
+ */
+BMEdge *BM_edge_find_double(BMEdge *e)
+{
+ BMVert *v = e->v1;
+ BMVert *v_other = e->v2;
+
+ BMEdge *e_iter;
+
+ e_iter = e;
+ while ((e_iter = bmesh_disk_edge_next(e_iter, v)) != e) {
+ if (UNLIKELY(BM_vert_in_edge(e_iter, v_other))) {
+ return e_iter;
+ }
+ }
+
+ return NULL;
+}
+
+/**
* Given a set of vertices \a varr, find out if
* all those vertices overlap an existing face.
*
diff --git a/source/blender/bmesh/intern/bmesh_queries.h b/source/blender/bmesh/intern/bmesh_queries.h
index 36ffc296759..34d0747676c 100644
--- a/source/blender/bmesh/intern/bmesh_queries.h
+++ b/source/blender/bmesh/intern/bmesh_queries.h
@@ -31,6 +31,7 @@ int BM_vert_in_face(BMFace *f, BMVert *v);
int BM_verts_in_face(BMesh *bm, BMFace *f, BMVert **varr, int len);
int BM_edge_in_face(BMFace *f, BMEdge *e);
+int BM_edge_in_loop(BMEdge *e, BMLoop *l);
int BM_vert_in_edge(BMEdge *e, BMVert *v);
int BM_verts_in_edge(BMVert *v1, BMVert *v2, BMEdge *e);
@@ -39,9 +40,11 @@ float BM_edge_calc_length(BMEdge *e);
int BM_edge_face_pair(BMEdge *e, BMFace **r_fa, BMFace **r_fb);
int BM_edge_loop_pair(BMEdge *e, BMLoop **r_la, BMLoop **r_lb);
BMVert *BM_edge_other_vert(BMEdge *e, BMVert *v);
+BMLoop *BM_edge_other_loop(BMEdge *e, BMLoop *l);
BMLoop *BM_face_other_edge_loop(BMFace *f, BMEdge *e, BMVert *v);
BMLoop *BM_face_other_vert_loop(BMFace *f, BMVert *v_prev, BMVert *v);
BMLoop *BM_loop_other_vert_loop(BMLoop *l, BMVert *v);
+BMLoop *BM_vert_step_fan_loop(BMLoop *l, BMEdge **e_step);
BMLoop *BM_vert_find_first_loop(BMVert *v);
int BM_vert_edge_count_nonwire(BMVert *v);
@@ -72,6 +75,7 @@ BMLoop *BM_face_find_shortest_loop(BMFace *f);
BMLoop *BM_face_find_longest_loop(BMFace *f);
BMEdge *BM_edge_exists(BMVert *v1, BMVert *v2);
+BMEdge *BM_edge_find_double(BMEdge *e);
int BM_face_exists_overlap(BMesh *bm, BMVert **varr, int len, BMFace **r_existface);
diff --git a/source/blender/bmesh/intern/bmesh_walkers_impl.c b/source/blender/bmesh/intern/bmesh_walkers_impl.c
index a72bfe47127..bb013e6428e 100644
--- a/source/blender/bmesh/intern/bmesh_walkers_impl.c
+++ b/source/blender/bmesh/intern/bmesh_walkers_impl.c
@@ -303,8 +303,7 @@ static void *bmw_IslandboundWalker_step(BMWalker *walker)
if (!BM_vert_is_manifold(v)) {
BMW_reset(walker);
BMO_error_raise(walker->bm, NULL, BMERR_WALKER_FAILED,
- "Non-manifold vert "
- "while searching region boundary");
+ "Non-manifold vert while searching region boundary");
return NULL;
}
@@ -499,7 +498,7 @@ static void *bmw_LoopWalker_step(BMWalker *walker)
BMEdge *e = lwalk->cur, *nexte = NULL;
BMLoop *l;
BMVert *v;
- int i;
+ int i = 0;
owalk = *lwalk;
BMW_state_remove(walker);
@@ -534,7 +533,7 @@ static void *bmw_LoopWalker_step(BMWalker *walker)
}
else if (l) { /* NORMAL EDGE WITH FACES */
int vert_edge_tot;
- int stopi;
+ int stopi = 0;
v = BM_edge_other_vert(e, lwalk->lastv);
@@ -599,7 +598,7 @@ static void *bmw_LoopWalker_step(BMWalker *walker)
}
}
}
- else { /* WIRE EDGE */
+ else { /* WIRE EDGE */
BMIter eiter;
/* match trunk: mark all connected wire edges */
diff --git a/source/blender/bmesh/operators/bmo_bevel.c b/source/blender/bmesh/operators/bmo_bevel.c
index 8210ea973e6..c5120571755 100644
--- a/source/blender/bmesh/operators/bmo_bevel.c
+++ b/source/blender/bmesh/operators/bmo_bevel.c
@@ -126,7 +126,7 @@ static void calc_corner_co(BMLoop *l, const float fac, float r_co[3],
* gives nicer, move even output.
*
* Use the minimum rather then the middle value so skinny faces don't flip along the short axis */
- float min_fac = minf(normalize_v3(l_vec_prev), normalize_v3(l_vec_next));
+ float min_fac = min_ff(normalize_v3(l_vec_prev), normalize_v3(l_vec_next));
float angle;
if (do_even) {
@@ -233,7 +233,7 @@ void bmo_bevel_exec(BMesh *bm, BMOperator *op)
}
#if 0
- //a bit of cleaner code that, alas, doens't work.
+ /* a bit of cleaner code that, alas, doens't work. */
/* build edge tag */
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
if (BMO_elem_flag_test(bm, e->v1, BEVEL_FLAG) || BMO_elem_flag_test(bm, e->v2, BEVEL_FLAG)) {
@@ -475,7 +475,7 @@ void bmo_bevel_exec(BMesh *bm, BMOperator *op)
BLI_array_append(edges, e);
f = BM_face_create_ngon(bm, verts[0], verts[1], edges, BLI_array_count(edges), FALSE);
- if (!f) {
+ if (UNLIKELY(f == NULL)) {
printf("%s: could not make face!\n", __func__);
continue;
}
@@ -592,7 +592,7 @@ void bmo_bevel_exec(BMesh *bm, BMOperator *op)
*d3 = (d1 + d2) * 0.5f;
}
- if (!f) {
+ if (UNLIKELY(f == NULL)) {
fprintf(stderr, "%s: face index out of range! (bmesh internal error)\n", __func__);
continue;
}
@@ -771,7 +771,7 @@ void bmo_bevel_exec(BMesh *bm, BMOperator *op)
continue;
f = BM_face_create_ngon(bm, lastv, vstart, edges, BLI_array_count(edges), FALSE);
- if (!f) {
+ if (UNLIKELY(f == NULL)) {
fprintf(stderr, "%s: in bevel vert fill! (bmesh internal error)\n", __func__);
}
else {
diff --git a/source/blender/bmesh/operators/bmo_connect.c b/source/blender/bmesh/operators/bmo_connect.c
index 1987294fc42..ebd848ff8b2 100644
--- a/source/blender/bmesh/operators/bmo_connect.c
+++ b/source/blender/bmesh/operators/bmo_connect.c
@@ -380,8 +380,9 @@ void bmo_bridge_loops_exec(BMesh *bm, BMOperator *op)
/* compute summed length between vertices in forward direction */
len = 0.0f;
- for (j = 0; j < lenv2; j++)
- len += len_v3v3(vv1[clamp_index(i+j, lenv1)]->co, vv2[j]->co);
+ for (j = 0; j < lenv2; j++) {
+ len += len_v3v3(vv1[clamp_index(i + j, lenv1)]->co, vv2[j]->co);
+ }
if (len < min) {
min = len;
@@ -390,8 +391,9 @@ void bmo_bridge_loops_exec(BMesh *bm, BMOperator *op)
/* compute summed length between vertices in backward direction */
len = 0.0f;
- for (j = 0; j < lenv2; j++)
- len += len_v3v3(vv1[clamp_index(i-j, lenv1)]->co, vv2[j]->co);
+ for (j = 0; j < lenv2; j++) {
+ len += len_v3v3(vv1[clamp_index(i - j, lenv1)]->co, vv2[j]->co);
+ }
if (len < min) {
min = len;
@@ -423,8 +425,8 @@ void bmo_bridge_loops_exec(BMesh *bm, BMOperator *op)
/* merge loops of bridge faces */
if (use_merge) {
- const int vert_len = mini(BLI_array_count(vv1), BLI_array_count(vv2)) - ((cl1 || cl2) ? 1 : 0);
- const int edge_len = mini(BLI_array_count(ee1), BLI_array_count(ee2));
+ const int vert_len = min_ii(BLI_array_count(vv1), BLI_array_count(vv2)) - ((cl1 || cl2) ? 1 : 0);
+ const int edge_len = min_ii(BLI_array_count(ee1), BLI_array_count(ee2));
if (merge_factor <= 0.0f) {
/* 2 --> 1 */
@@ -504,7 +506,7 @@ void bmo_bridge_loops_exec(BMesh *bm, BMOperator *op)
vv2[i2next],
vv1[i1next],
f_example, TRUE);
- if (!f || f->len != 4) {
+ if (UNLIKELY((f == NULL) || (f->len != 4))) {
fprintf(stderr, "%s: in bridge! (bmesh internal error)\n", __func__);
}
else {
diff --git a/source/blender/bmesh/operators/bmo_create.c b/source/blender/bmesh/operators/bmo_create.c
index 4723b631c5f..bd1c0f809bd 100644
--- a/source/blender/bmesh/operators/bmo_create.c
+++ b/source/blender/bmesh/operators/bmo_create.c
@@ -84,7 +84,7 @@ static int count_edge_faces(BMesh *bm, BMEdge *e);
BLI_INLINE BMDiskLink *rs_edge_link_get(BMEdge *e, BMVert *v, EdgeData *e_data)
{
return v == ((BMEdge *)e)->v1 ? &(((EdgeData *)e_data)->v1_disk_link) :
- &(((EdgeData *)e_data)->v2_disk_link) ;
+ &(((EdgeData *)e_data)->v2_disk_link);
}
static int rotsys_append_edge(BMEdge *e, BMVert *v,
@@ -275,8 +275,9 @@ static int UNUSED_FUNCTION(rotsys_fill_faces)(BMesh *bm, EdgeData *edata, VertDa
continue;
f = BM_face_create_ngon(bm, verts[0], verts[1], edges, BLI_array_count(edges), TRUE);
- if (!f)
+ if (UNLIKELY(f == NULL)) {
continue;
+ }
}
}
@@ -364,8 +365,6 @@ static void init_rotsys(BMesh *bm, EdgeData *edata, VertData *vdata)
/* BLI_array_staticdeclare(verts, BM_NGON_STACK_SIZE); */ /* UNUSE */
int i;
-#define SIGN(n) ((n) < 0.0f)
-
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
BMIter eiter;
float no[3], cent[3];
@@ -1225,7 +1224,7 @@ void bmo_edgenet_prepare(BMesh *bm, BMOperator *op)
v4 = BM_vert_in_edge(edges2[i - 1], edges2[i]->v1) ? edges2[i]->v2 : edges2[i]->v1;
}
- /* if there is ever bowtie quads between two edges the problem is here! [#30367] */
+ /* if there is ever bow-tie quads between two edges the problem is here! [#30367] */
#if 0
normal_tri_v3(dvec1, v1->co, v2->co, v4->co);
normal_tri_v3(dvec2, v1->co, v4->co, v3->co);
diff --git a/source/blender/bmesh/operators/bmo_dissolve.c b/source/blender/bmesh/operators/bmo_dissolve.c
index 84f6cb27b3b..9addb1b1657 100644
--- a/source/blender/bmesh/operators/bmo_dissolve.c
+++ b/source/blender/bmesh/operators/bmo_dissolve.c
@@ -477,182 +477,15 @@ void dummy_exec(BMesh *bm, BMOperator *op)
#endif
/* Limited Dissolve */
-
-#define UNIT_TO_ANGLE DEG2RADF(90.0f)
-#define ANGLE_TO_UNIT (1.0f / UNIT_TO_ANGLE)
-
-/* multiply vertex edge angle by face angle
- * this means we are not left with sharp corners between _almost_ planer faces
- * convert angles [0-PI/2] -> [0-1], multiply together, then convert back to radians. */
-static float bm_vert_edge_face_angle(BMVert *v)
-{
- const float angle = BM_vert_calc_edge_angle(v);
- /* note: could be either edge, it doesn't matter */
- if (v->e && BM_edge_is_manifold(v->e)) {
- return ((angle * ANGLE_TO_UNIT) * (BM_edge_calc_face_angle(v->e) * ANGLE_TO_UNIT)) * UNIT_TO_ANGLE;
- }
- else {
- return angle;
- }
-}
-
-#undef UNIT_TO_ANGLE
-#undef ANGLE_TO_UNIT
-
-typedef struct DissolveElemWeight {
- BMHeader *ele;
- float weight;
-} DissolveElemWeight;
-
-static int dissolve_elem_cmp(const void *a1, const void *a2)
-{
- const struct DissolveElemWeight *d1 = a1, *d2 = a2;
-
- if (d1->weight > d2->weight) return 1;
- else if (d1->weight < d2->weight) return -1;
- return 0;
-}
-
void bmo_dissolve_limit_exec(BMesh *bm, BMOperator *op)
{
BMOpSlot *einput = BMO_slot_get(op, "edges");
BMOpSlot *vinput = BMO_slot_get(op, "verts");
const float angle_max = (float)M_PI / 2.0f;
- const float angle_limit = minf(angle_max, BMO_slot_float_get(op, "angle_limit"));
- DissolveElemWeight *weight_elems = MEM_mallocN(MAX2(einput->len, vinput->len) *
- sizeof(DissolveElemWeight), __func__);
- int i, tot_found;
-
- BMIter iter;
- BMEdge *e_iter;
- BMEdge **earray;
-
- int *vert_reverse_lookup;
-
- BMEdge **einput_arr = (BMEdge **)einput->data.p;
- BMVert **vinput_arr = (BMVert **)vinput->data.p;
-
- /* --- first edges --- */
-
- /* wire -> tag */
- BM_ITER_MESH (e_iter, &iter, bm, BM_EDGES_OF_MESH) {
- BM_elem_flag_set(e_iter, BM_ELEM_TAG, BM_edge_is_wire(e_iter));
- }
-
- /* go through and split edge */
- for (i = 0, tot_found = 0; i < einput->len; i++) {
- BMEdge *e = einput_arr[i];
- const float angle = BM_edge_calc_face_angle(e);
-
- if (angle < angle_limit) {
- tot_found++;
- }
- weight_elems[i].ele = (BMHeader *)e;
- weight_elems[i].weight = angle;
- }
-
- if (tot_found != 0) {
- qsort(weight_elems, einput->len, sizeof(DissolveElemWeight), dissolve_elem_cmp);
-
- for (i = 0; i < tot_found; i++) {
- BMEdge *e = (BMEdge *)weight_elems[i].ele;
-
- if (/* may have become non-manifold */
- BM_edge_is_manifold(e) &&
- /* check twice because cumulative effect could dissolve over angle limit */
- (BM_edge_calc_face_angle(e) < angle_limit))
- {
- BMFace *nf = BM_faces_join_pair(bm, e->l->f,
- e->l->radial_next->f,
- e,
- FALSE); /* join faces */
-
- /* there may be some errors, we don't mind, just move on */
- if (nf) {
- BM_face_normal_update(nf);
- }
- else {
- BMO_error_clear(bm);
- }
- }
- }
- }
-
- /* prepare for cleanup */
- BM_mesh_elem_index_ensure(bm, BM_VERT);
- vert_reverse_lookup = MEM_mallocN(sizeof(int) * bm->totvert, __func__);
- fill_vn_i(vert_reverse_lookup, bm->totvert, -1);
- for (i = 0, tot_found = 0; i < vinput->len; i++) {
- BMVert *v = vinput_arr[i];
- vert_reverse_lookup[BM_elem_index_get(v)] = i;
- }
-
- /* --- cleanup --- */
- earray = MEM_mallocN(sizeof(BMEdge *) * bm->totedge, __func__);
- BM_ITER_MESH_INDEX (e_iter, &iter, bm, BM_EDGES_OF_MESH, i) {
- earray[i] = e_iter;
- }
- /* remove all edges/verts left behind from dissolving, NULL'ing the vertex array so we dont re-use */
- for (i = bm->totedge - 1; i != -1; i--) {
- e_iter = earray[i];
-
- if (BM_edge_is_wire(e_iter) && (BM_elem_flag_test(e_iter, BM_ELEM_TAG) == FALSE)) {
- /* edge has become wire */
- int vidx_reverse;
- BMVert *v1 = e_iter->v1;
- BMVert *v2 = e_iter->v2;
- BM_edge_kill(bm, e_iter);
- if (v1->e == NULL) {
- vidx_reverse = vert_reverse_lookup[BM_elem_index_get(v1)];
- if (vidx_reverse != -1) vinput_arr[vidx_reverse] = NULL;
- BM_vert_kill(bm, v1);
- }
- if (v2->e == NULL) {
- vidx_reverse = vert_reverse_lookup[BM_elem_index_get(v2)];
- if (vidx_reverse != -1) vinput_arr[vidx_reverse] = NULL;
- BM_vert_kill(bm, v2);
- }
- }
- }
- MEM_freeN(vert_reverse_lookup);
-
- MEM_freeN(earray);
-
-
- /* --- second verts --- */
- for (i = 0, tot_found = 0; i < vinput->len; i++) {
- BMVert *v = vinput_arr[i];
- const float angle = v ? bm_vert_edge_face_angle(v) : angle_limit;
-
- if (angle < angle_limit) {
- weight_elems[i].ele = (BMHeader *)v;
- weight_elems[i].weight = angle;
- tot_found++;
- }
- else {
- weight_elems[i].ele = NULL;
- weight_elems[i].weight = angle_max;
- }
- }
-
- if (tot_found != 0) {
- qsort(weight_elems, vinput->len, sizeof(DissolveElemWeight), dissolve_elem_cmp);
-
- for (i = 0; i < tot_found; i++) {
- BMVert *v = (BMVert *)weight_elems[i].ele;
- if (/* topology changes may cause this to be un-collapsable */
- (BM_vert_edge_count(v) == 2) &&
- /* check twice because cumulative effect could dissolve over angle limit */
- bm_vert_edge_face_angle(v) < angle_limit)
- {
- BMEdge *ne = BM_vert_collapse_edge(bm, v->e, v, TRUE); /* join edges */
-
- if (ne && ne->l) {
- BM_edge_normals_update(ne);
- }
- }
- }
- }
+ const float angle_limit = min_ff(angle_max, BMO_slot_float_get(op, "angle_limit"));
+ const int do_dissolve_boundaries = BMO_slot_bool_get(op, "use_dissolve_boundaries");
- MEM_freeN(weight_elems);
+ BM_mesh_decimate_dissolve_ex(bm, angle_limit, do_dissolve_boundaries,
+ vinput->data.p, vinput->len,
+ einput->data.p, einput->len);
}
diff --git a/source/blender/bmesh/operators/bmo_dupe.c b/source/blender/bmesh/operators/bmo_dupe.c
index 4d4d7e30a4e..32270007a0b 100644
--- a/source/blender/bmesh/operators/bmo_dupe.c
+++ b/source/blender/bmesh/operators/bmo_dupe.c
@@ -37,7 +37,7 @@
#define DUPE_INPUT 1 /* input from operator */
#define DUPE_NEW 2
#define DUPE_DONE 4
-#define DUPE_MAPPED 8
+// #define DUPE_MAPPED 8 // UNUSED
/**
* COPY VERTEX
diff --git a/source/blender/bmesh/operators/bmo_extrude.c b/source/blender/bmesh/operators/bmo_extrude.c
index c8be7c9ce34..627351ead11 100644
--- a/source/blender/bmesh/operators/bmo_extrude.c
+++ b/source/blender/bmesh/operators/bmo_extrude.c
@@ -87,8 +87,8 @@ void bmo_extrude_discrete_faces_exec(BMesh *bm, BMOperator *op)
BMO_elem_flag_enable(bm, f, EXT_DEL);
f2 = BM_face_create_ngon(bm, firstv, BM_edge_other_vert(edges[0], firstv), edges, f->len, FALSE);
- if (!f2) {
- BMO_error_raise(bm, op, BMERR_MESH_ERROR, "Extrude failed; could not create face");
+ if (UNLIKELY(f2 == NULL)) {
+ BMO_error_raise(bm, op, BMERR_MESH_ERROR, "Extrude failed: could not create face");
BLI_array_free(edges);
return;
}
@@ -104,6 +104,7 @@ void bmo_extrude_discrete_faces_exec(BMesh *bm, BMOperator *op)
l4 = l2->next;
f3 = BM_face_create_quad_tri(bm, l3->v, l4->v, l2->v, l->v, f, FALSE);
+ /* XXX, no error check here, why? - Campbell */
l_tmp = BM_FACE_FIRST_LOOP(f3);
@@ -131,46 +132,36 @@ void bmo_extrude_discrete_faces_exec(BMesh *bm, BMOperator *op)
* This function won't crash if its not but won't work right either.
* \a e_b is the new edge.
*
- * \note this function could be exposed as an api call if other areas need it,
- * so far only extrude does.
+ * \note The edge this face comes from needs to be from the first and second verts fo the face.
+ * The caller must ensure this else we will copy from the wrong source.
*/
-static void bm_extrude_copy_face_loop_attributes(BMesh *bm, BMFace *f, BMEdge *e_a, BMEdge *e_b)
+static void bm_extrude_copy_face_loop_attributes(BMesh *bm, BMFace *f)
{
- /* 'a' is the starting edge #e, 'b' is the final edge #newedge */
- BMLoop *l_dst_a = BM_face_edge_share_loop(f, e_a);
- BMLoop *l_dst_b = BM_face_edge_share_loop(f, e_b);
- /* we could only have a face on one-or the other edges,
- * check if either side of the face has an adjacent face */
- BMLoop *l_src_1;
- BMLoop *l_src_2;
-
- /* there is no l_src_b */
-
- /* sanity */
- BLI_assert(l_dst_a->f == l_dst_b->f);
-
- if (l_dst_a != l_dst_a->radial_next) {
- l_src_1 = l_dst_a->radial_next;
- l_src_2 = l_src_1->next;
- }
- else if (l_dst_b != l_dst_b->radial_next) {
- l_src_2 = l_dst_b->radial_next;
- l_src_1 = l_src_2->next;
- }
- else {
- /* no new faces on either edge, nothing to copy from */
+ /* edge we are extruded from */
+ BMLoop *l_first_0 = BM_FACE_FIRST_LOOP(f);
+ BMLoop *l_first_1 = l_first_0->next;
+ BMLoop *l_first_2 = l_first_1->next;
+ BMLoop *l_first_3 = l_first_2->next;
+
+ BMLoop *l_other_0;
+ BMLoop *l_other_1;
+
+ if (UNLIKELY(l_first_0 == l_first_0->radial_next)) {
return;
}
- BM_elem_attrs_copy(bm, bm, l_src_1->f, l_dst_a->f);
- BM_elem_flag_disable(f, BM_ELEM_HIDDEN); /* possibly we copy from a hidden face */
+ l_other_0 = BM_edge_other_loop(l_first_0->e, l_first_0);
+ l_other_1 = BM_edge_other_loop(l_first_0->e, l_first_1);
/* copy data */
- BM_elem_attrs_copy(bm, bm, l_src_2, l_dst_a);
- BM_elem_attrs_copy(bm, bm, l_src_2, l_dst_b->next);
+ BM_elem_attrs_copy(bm, bm, l_other_0->f, f);
+ BM_elem_flag_disable(f, BM_ELEM_HIDDEN); /* possibly we copy from a hidden face */
- BM_elem_attrs_copy(bm, bm, l_src_1, l_dst_a->next);
- BM_elem_attrs_copy(bm, bm, l_src_1, l_dst_b);
+ BM_elem_attrs_copy(bm, bm, l_other_0, l_first_0);
+ BM_elem_attrs_copy(bm, bm, l_other_0, l_first_3);
+
+ BM_elem_attrs_copy(bm, bm, l_other_1, l_first_1);
+ BM_elem_attrs_copy(bm, bm, l_other_1, l_first_2);
}
/* Disable the skin root flag on the input vert, assumes that the vert
@@ -187,9 +178,8 @@ void bmo_extrude_edge_only_exec(BMesh *bm, BMOperator *op)
{
BMOIter siter;
BMOperator dupeop;
- BMVert *v1, *v2, *v3, *v4;
- BMEdge *e, *e2;
BMFace *f;
+ BMEdge *e, *e_new;
BMO_ITER (e, &siter, bm, op, "edges", BM_EDGE) {
BMO_elem_flag_enable(bm, e, EXT_INPUT);
@@ -202,33 +192,34 @@ void bmo_extrude_edge_only_exec(BMesh *bm, BMOperator *op)
/* disable root flag on all new skin nodes */
if (CustomData_has_layer(&bm->vdata, CD_MVERT_SKIN)) {
- BMO_ITER(v1, &siter, bm, &dupeop, "newout", BM_VERT) {
- bm_extrude_disable_skin_root(bm, v1);
+ BMVert *v;
+ BMO_ITER(v, &siter, bm, &dupeop, "newout", BM_VERT) {
+ bm_extrude_disable_skin_root(bm, v);
}
}
for (e = BMO_iter_new(&siter, bm, &dupeop, "boundarymap", 0); e; e = BMO_iter_step(&siter)) {
- e2 = BMO_iter_map_value(&siter);
- e2 = *(BMEdge **)e2;
+ BMVert *f_verts[4];
+ e_new = *(BMEdge **)BMO_iter_map_value(&siter);
if (e->l && e->v1 != e->l->v) {
- v1 = e->v1;
- v2 = e->v2;
- v3 = e2->v2;
- v4 = e2->v1;
+ f_verts[0] = e->v1;
+ f_verts[1] = e->v2;
+ f_verts[2] = e_new->v2;
+ f_verts[3] = e_new->v1;
}
else {
- v1 = e2->v1;
- v2 = e2->v2;
- v3 = e->v2;
- v4 = e->v1;
+ f_verts[0] = e->v2;
+ f_verts[1] = e->v1;
+ f_verts[2] = e_new->v1;
+ f_verts[3] = e_new->v2;
}
/* not sure what to do about example face, pass NULL for now */
- f = BM_face_create_quad_tri(bm, v1, v2, v3, v4, NULL, FALSE);
- bm_extrude_copy_face_loop_attributes(bm, f, e, e2);
+ f = BM_face_create_quad_tri_v(bm, f_verts, 4, NULL, FALSE);
+ bm_extrude_copy_face_loop_attributes(bm, f);
if (BMO_elem_flag_test(bm, e, EXT_INPUT))
- e = e2;
+ e = e_new;
BMO_elem_flag_enable(bm, f, EXT_KEEP);
BMO_elem_flag_enable(bm, e, EXT_KEEP);
@@ -269,8 +260,8 @@ void bmo_extrude_face_region_exec(BMesh *bm, BMOperator *op)
BMOperator dupeop, delop;
BMOIter siter;
BMIter iter, fiter, viter;
- BMEdge *e, *newedge;
- BMVert *verts[4], *v, *v2;
+ BMEdge *e, *e_new;
+ BMVert *v, *v2;
BMFace *f;
int found, fwd, delorig = FALSE;
@@ -377,6 +368,7 @@ void bmo_extrude_face_region_exec(BMesh *bm, BMOperator *op)
BMO_slot_copy(&dupeop, op, "newout", "geomout");
for (e = BMO_iter_new(&siter, bm, &dupeop, "boundarymap", 0); e; e = BMO_iter_step(&siter)) {
+ BMVert *f_verts[4];
/* this should always be wire, so this is mainly a speedup to avoid map lookup */
if (BM_edge_is_wire(e) && BMO_slot_map_contains(bm, op, "exclude", e)) {
@@ -395,37 +387,37 @@ void bmo_extrude_face_region_exec(BMesh *bm, BMOperator *op)
continue;
}
- newedge = *(BMEdge **)BMO_iter_map_value(&siter);
+ e_new = *(BMEdge **)BMO_iter_map_value(&siter);
- if (!newedge) {
+ if (!e_new) {
continue;
}
/* orient loop to give same normal as a loop of newedge
* if it exists (will be an extruded face),
* else same normal as a loop of e, if it exists */
- if (!newedge->l)
+ if (!e_new->l)
fwd = !e->l || !(e->l->v == e->v1);
else
- fwd = (newedge->l->v == newedge->v1);
+ fwd = (e_new->l->v == e_new->v1);
if (fwd) {
- verts[0] = e->v1;
- verts[1] = e->v2;
- verts[2] = newedge->v2;
- verts[3] = newedge->v1;
+ f_verts[0] = e->v1;
+ f_verts[1] = e->v2;
+ f_verts[2] = e_new->v2;
+ f_verts[3] = e_new->v1;
}
else {
- verts[3] = e->v1;
- verts[2] = e->v2;
- verts[1] = newedge->v2;
- verts[0] = newedge->v1;
+ f_verts[0] = e->v2;
+ f_verts[1] = e->v1;
+ f_verts[2] = e_new->v1;
+ f_verts[3] = e_new->v2;
}
/* not sure what to do about example face, pass NULL for now */
- f = BM_face_create_quad_tri_v(bm, verts, 4, NULL, FALSE);
- bm_extrude_copy_face_loop_attributes(bm, f, e, newedge);
+ f = BM_face_create_quad_tri_v(bm, f_verts, 4, NULL, FALSE);
+ bm_extrude_copy_face_loop_attributes(bm, f);
}
/* link isolated vert */
diff --git a/source/blender/bmesh/operators/bmo_hull.c b/source/blender/bmesh/operators/bmo_hull.c
index d97d901777c..013b6183f84 100644
--- a/source/blender/bmesh/operators/bmo_hull.c
+++ b/source/blender/bmesh/operators/bmo_hull.c
@@ -24,19 +24,17 @@
* \ingroup bmesh
*/
+#ifdef WITH_BULLET
+
#include "MEM_guardedalloc.h"
+#include "BLI_array.h"
#include "BLI_ghash.h"
#include "BLI_listbase.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
-/*XXX: This operator doesn't work well (at all?) for flat surfaces with
- * >3 sides - creating overlapping faces at times.
- * An easy workaround is to add in some noise but this is
- * weak and unreliable, ideally this would detect flat surfaces
- * (possibly making them into ngons) - see
- */
+#include "Bullet-C-Api.h"
/* XXX: using 128 for totelem and pchunk of mempool, no idea what good
* values would be though */
@@ -46,21 +44,15 @@
#include "intern/bmesh_operators_private.h" /* own include */
-#define HULL_EPSILON_FLT 0.0001f
-/* values above 0.0001 cause errors, see below for details, don't increase
- * without checking against bug [#32027] */
-#define HULL_EPSILON_DOT_FLT 0.00000001f
-
/* Internal operator flags */
typedef enum {
HULL_FLAG_INPUT = (1 << 0),
- HULL_FLAG_TETRA_VERT = (1 << 1),
- HULL_FLAG_INTERIOR_ELE = (1 << 2),
- HULL_FLAG_OUTPUT_GEOM = (1 << 3),
+ HULL_FLAG_INTERIOR_ELE = (1 << 1),
+ HULL_FLAG_OUTPUT_GEOM = (1 << 2),
- HULL_FLAG_DEL = (1 << 4),
- HULL_FLAG_HOLE = (1 << 5)
+ HULL_FLAG_DEL = (1 << 3),
+ HULL_FLAG_HOLE = (1 << 4)
} HullFlags;
/* Store hull triangles separate from BMesh faces until the end; this
@@ -72,63 +64,6 @@ typedef struct HullTriangle {
int skip;
} HullTriangle;
-/* These edges define the hole created in the hull by deleting faces
- * that can "see" a new vertex (the boundary edges then form the edge
- * of a new triangle fan that has the new vertex as its center) */
-typedef struct HullBoundaryEdge {
- struct HullBoundaryEdge *next, *prev;
- BMVert *v[2];
-} HullBoundaryEdge;
-
-
-
-/*************************** Boundary Edges ***************************/
-
-static int edge_match(BMVert *e1_v1, BMVert *e1_v2, BMVert *e2[2])
-{
- return (e1_v1 == e2[0] && e1_v2 == e2[1]) ||
- (e1_v1 == e2[1] && e1_v2 == e2[0]);
-}
-
-/* Returns true if the edge (e1, e2) is already in edges; that edge is
- * deleted here as well. if not found just returns 0 */
-static int check_for_dup(ListBase *edges, BLI_mempool *pool,
- BMVert *v1, BMVert *v2)
-{
- HullBoundaryEdge *e, *e_next;
-
- for (e = edges->first; e; e = e_next) {
- e_next = e->next;
-
- if (edge_match(v1, v2, e->v)) {
- /* remove the interior edge */
- BLI_remlink(edges, e);
- BLI_mempool_free(pool, e);
- return 1;
- }
- }
-
- return 0;
-}
-
-static void expand_boundary_edges(ListBase *edges, BLI_mempool *edge_pool,
- const HullTriangle *t)
-{
- HullBoundaryEdge *e_new;
- int i;
-
- /* Insert each triangle edge into the boundary list; if any of
- * its edges are already in there, remove the edge entirely */
- for (i = 0; i < 3; i++) {
- if (!check_for_dup(edges, edge_pool, t->v[i], t->v[(i + 1) % 3])) {
- e_new = BLI_mempool_calloc(edge_pool);
- e_new->v[0] = t->v[i];
- e_new->v[1] = t->v[(i + 1) % 3];
- BLI_addtail(edges, e_new);
- }
- }
-}
-
/*************************** Hull Triangles ***************************/
@@ -152,75 +87,6 @@ static void hull_add_triangle(BMesh *bm, GHash *hull_triangles, BLI_mempool *poo
normal_tri_v3(t->no, v1->co, v2->co, v3->co);
}
-static int hull_point_tri_side(const HullTriangle *t, const float co[3])
-{
- /* Added epsilon to fix bug [#31941], improves output when some
- * vertices are nearly coplanar. Might need further tweaking for
- * other cases though.
- * ...
- * Update: epsilon of 0.0001 causes [#32027], use HULL_EPSILON_DOT_FLT
- * and give it a much smaller value
- * */
- float p[3], d;
- sub_v3_v3v3(p, co, t->v[0]->co);
- d = dot_v3v3(t->no, p);
- if (d < -HULL_EPSILON_DOT_FLT) return -1;
- else if (d > HULL_EPSILON_DOT_FLT) return 1;
- else return 0;
-}
-
-/* Get all hull triangles that vertex 'v' is outside of */
-static GHash *hull_triangles_v_outside(GHash *hull_triangles, const BMVert *v)
-{
- GHash *outside;
- GHashIterator iter;
-
- outside = BLI_ghash_ptr_new("outside");
-
- GHASH_ITER (iter, hull_triangles) {
- HullTriangle *t = BLI_ghashIterator_getKey(&iter);
-
- if (hull_point_tri_side(t, v->co) > 0)
- BLI_ghash_insert(outside, t, NULL);
- }
-
- return outside;
-}
-
-/* For vertex 'v', find which triangles must be deleted to extend the
- * hull; find the boundary edges of that hole so that it can be filled
- * with connections to the new vertex, and update the hull_triangles
- * to delete the marked triangles */
-static void add_point(BMesh *bm, GHash *hull_triangles, BLI_mempool *hull_pool,
- BLI_mempool *edge_pool, GHash *outside, BMVert *v)
-{
- ListBase edges = {NULL, NULL};
- HullBoundaryEdge *e, *e_next;
- GHashIterator iter;
-
- GHASH_ITER (iter, outside) {
- HullTriangle *t = BLI_ghashIterator_getKey(&iter);
- int i;
-
- expand_boundary_edges(&edges, edge_pool, t);
-
- /* Mark triangle's vertices as interior */
- for (i = 0; i < 3; i++)
- BMO_elem_flag_enable(bm, t->v[i], HULL_FLAG_INTERIOR_ELE);
-
- /* Delete the triangle */
- BLI_ghash_remove(hull_triangles, t, NULL, NULL);
- BLI_mempool_free(hull_pool, t);
- }
-
- /* Fill hole boundary with triangles to new point */
- for (e = edges.first; e; e = e_next) {
- e_next = e->next;
- hull_add_triangle(bm, hull_triangles, hull_pool, e->v[0], e->v[1], v);
- BLI_mempool_free(edge_pool, e);
- }
-}
-
static BMFace *hull_find_example_face(BMesh *bm, BMEdge *e)
{
BMIter iter;
@@ -243,6 +109,7 @@ static void hull_output_triangles(BMesh *bm, GHash *hull_triangles)
GHASH_ITER (iter, hull_triangles) {
HullTriangle *t = BLI_ghashIterator_getKey(&iter);
+ int i;
if (!t->skip) {
BMEdge *edges[3] = {
@@ -251,25 +118,53 @@ static void hull_output_triangles(BMesh *bm, GHash *hull_triangles)
BM_edge_create(bm, t->v[2], t->v[0], NULL, TRUE)
};
BMFace *f, *example = NULL;
- int i;
- /* Look for an adjacent face that existed before the hull */
- for (i = 0; i < 3; i++) {
- if (!example)
- example = hull_find_example_face(bm, edges[i]);
+ if (BM_face_exists(bm, t->v, 3, &f)) {
+ /* If the operator is run with "use_existing_faces"
+ * disabled, but an output face in the hull is the
+ * same as a face in the existing mesh, it should not
+ * be marked as unused or interior. */
+ BMO_elem_flag_enable(bm, f, HULL_FLAG_OUTPUT_GEOM);
+ BMO_elem_flag_disable(bm, f, HULL_FLAG_HOLE);
+ BMO_elem_flag_disable(bm, f, HULL_FLAG_INTERIOR_ELE);
}
+ else {
+ /* Look for an adjacent face that existed before the hull */
+ for (i = 0; i < 3; i++) {
+ if (!example)
+ example = hull_find_example_face(bm, edges[i]);
+ }
- f = BM_face_create_quad_tri_v(bm, t->v, 3, example, FALSE);
- BM_face_copy_shared(bm, f);
-
- /* Mark face/verts/edges for 'geomout' slot and select */
+ /* Create new hull face */
+ f = BM_face_create_quad_tri_v(bm, t->v, 3, example, TRUE);
+ BM_face_copy_shared(bm, f);
+ }
+ /* Mark face for 'geomout' slot and select */
BMO_elem_flag_enable(bm, f, HULL_FLAG_OUTPUT_GEOM);
BM_face_select_set(bm, f, TRUE);
+
+ /* Mark edges for 'geomout' slot */
for (i = 0; i < 3; i++) {
- BMO_elem_flag_enable(bm, t->v[i], HULL_FLAG_OUTPUT_GEOM);
BMO_elem_flag_enable(bm, edges[i], HULL_FLAG_OUTPUT_GEOM);
}
}
+ else {
+ /* Mark input edges for 'geomout' slot */
+ for (i = 0; i < 3; i++) {
+ const int next = (i == 2 ? 0 : i + 1);
+ BMEdge *e = BM_edge_exists(t->v[i], t->v[next]);
+ if (e &&
+ BMO_elem_flag_test(bm, e, HULL_FLAG_INPUT) &&
+ !BMO_elem_flag_test(bm, e, HULL_FLAG_HOLE)) {
+ BMO_elem_flag_enable(bm, e, HULL_FLAG_OUTPUT_GEOM);
+ }
+ }
+ }
+
+ /* Mark verts for 'geomout' slot */
+ for (i = 0; i < 3; i++) {
+ BMO_elem_flag_enable(bm, t->v[i], HULL_FLAG_OUTPUT_GEOM);
+ }
}
}
@@ -362,158 +257,6 @@ static void hull_final_edges_free(HullFinalEdges *final_edges)
-/************************* Initial Tetrahedron ************************/
-
-static void hull_add_tetrahedron(BMesh *bm, GHash *hull_triangles, BLI_mempool *pool,
- BMVert *tetra[4])
-{
- float center[3];
- int i, indices[4][3] = {
- {0, 1, 2},
- {0, 2, 3},
- {1, 0, 3},
- {2, 1, 3}
- };
-
- /* Calculate center */
- zero_v3(center);
- for (i = 0; i < 4; i++)
- add_v3_v3(center, tetra[i]->co);
- mul_v3_fl(center, 0.25f);
-
- for (i = 0; i < 4; i++) {
- BMVert *v1 = tetra[indices[i][0]];
- BMVert *v2 = tetra[indices[i][1]];
- BMVert *v3 = tetra[indices[i][2]];
- float no[3], d[3];
-
- normal_tri_v3(no, v1->co, v2->co, v3->co);
- sub_v3_v3v3(d, center, v1->co);
- if (dot_v3v3(no, d) > 0)
- SWAP(BMVert *, v1, v3);
-
- hull_add_triangle(bm, hull_triangles, pool, v1, v2, v3);
- }
-}
-
-/* For each axis, get the minimum and maximum input vertices */
-static void hull_get_min_max(BMesh *bm, BMOperator *op,
- BMVert *min[3], BMVert *max[3])
-{
- BMOIter oiter;
- BMVert *v;
-
- min[0] = min[1] = min[2] = NULL;
- max[0] = max[1] = max[2] = NULL;
-
- BMO_ITER (v, &oiter, bm, op, "input", BM_VERT) {
- int i;
-
- for (i = 0; i < 3; i++) {
- if (!min[i] || v->co[i] < min[i]->co[i])
- min[i] = v;
- if (!max[i] || v->co[i] > max[i]->co[i])
- max[i] = v;
- }
- }
-}
-
-/* Returns true if input is coplanar */
-static int hull_find_large_tetrahedron(BMesh *bm, BMOperator *op,
- BMVert *tetra[4])
-{
- BMVert *min[3], *max[3], *v;
- BMOIter oiter;
- float widest_axis_len, largest_dist, plane_normal[3];
- int i, j, widest_axis;
-
- tetra[0] = tetra[1] = tetra[2] = tetra[3] = NULL;
- hull_get_min_max(bm, op, min, max);
-
- /* Check for flat axis */
- for (i = 0; i < 3; i++) {
- if (min[i] == max[i]) {
- return TRUE;
- }
- }
-
- /* Find widest axis */
- widest_axis_len = 0.0f;
- widest_axis = 0; /* set here in the unlikey case this isn't set below */
- for (i = 0; i < 3; i++) {
- float len = (max[i]->co[i] - min[i]->co[i]);
- if (len >= widest_axis_len) {
- widest_axis_len = len;
- widest_axis = i;
- }
- }
-
- /* Use widest axis for first two points */
- tetra[0] = min[widest_axis];
- tetra[1] = max[widest_axis];
- BMO_elem_flag_enable(bm, tetra[0], HULL_FLAG_TETRA_VERT);
- BMO_elem_flag_enable(bm, tetra[1], HULL_FLAG_TETRA_VERT);
-
- /* Choose third vertex farthest from existing line segment */
- largest_dist = 0;
- for (i = 0; i < 3; i++) {
- BMVert *v;
- float dist;
-
- if (i == widest_axis)
- continue;
-
- v = min[i];
- for (j = 0; j < 2; j++) {
- dist = dist_to_line_segment_v3(v->co, tetra[0]->co, tetra[1]->co);
- if (dist > largest_dist) {
- largest_dist = dist;
- tetra[2] = v;
- }
-
- v = max[i];
- }
- }
-
- if (tetra[2]) {
- BMO_elem_flag_enable(bm, tetra[2], HULL_FLAG_TETRA_VERT);
- }
- else {
- return TRUE;
- }
-
- /* Check for colinear vertices */
- if (largest_dist < HULL_EPSILON_FLT)
- return TRUE;
-
- /* Choose fourth point farthest from existing plane */
- largest_dist = 0;
- normal_tri_v3(plane_normal, tetra[0]->co, tetra[1]->co, tetra[2]->co);
- BMO_ITER (v, &oiter, bm, op, "input", BM_VERT) {
- if (!BMO_elem_flag_test(bm, v, HULL_FLAG_TETRA_VERT)) {
- float dist = fabsf(dist_to_plane_v3(v->co, tetra[0]->co, plane_normal));
- if (dist > largest_dist) {
- largest_dist = dist;
- tetra[3] = v;
- }
- }
- }
-
- if (tetra[3]) {
- BMO_elem_flag_enable(bm, tetra[3], HULL_FLAG_TETRA_VERT);
- }
- else {
- return TRUE;
- }
-
- if (largest_dist < HULL_EPSILON_FLT)
- return TRUE;
-
- return FALSE;
-}
-
-
-
/**************************** Final Output ****************************/
static void hull_remove_overlapping(BMesh *bm, GHash *hull_triangles,
@@ -650,44 +393,175 @@ static void hull_tag_holes(BMesh *bm, BMOperator *op)
}
}
- /* Mark edges too if all adjacent faces are holes */
+ /* Mark edges too if all adjacent faces are holes and the edge is
+ * not already isolated */
BMO_ITER (e, &oiter, bm, op, "input", BM_EDGE) {
int hole = TRUE;
+ int any_faces = FALSE;
BM_ITER_ELEM (f, &iter, e, BM_FACES_OF_EDGE) {
+ any_faces = TRUE;
if (!BMO_elem_flag_test(bm, f, HULL_FLAG_HOLE)) {
hole = FALSE;
break;
}
}
- if (hole)
+ if (hole && any_faces)
BMO_elem_flag_enable(bm, e, HULL_FLAG_HOLE);
}
}
+static int hull_input_vert_count(BMesh *bm, BMOperator *op)
+{
+ BMOIter oiter;
+ BMVert *v;
+ int count = 0;
+
+ BMO_ITER (v, &oiter, bm, op, "input", BM_VERT) {
+ count++;
+ }
+
+ return count;
+}
+
+static BMVert **hull_input_verts_copy(BMesh *bm, BMOperator *op,
+ const int num_input_verts)
+{
+ BMOIter oiter;
+ BMVert *v;
+ BMVert **input_verts = MEM_callocN(sizeof(*input_verts) *
+ num_input_verts, AT);
+ int i = 0;
+
+ BMO_ITER (v, &oiter, bm, op, "input", BM_VERT) {
+ input_verts[i++] = v;
+ }
+
+ return input_verts;
+}
+
+static float (*hull_verts_for_bullet(BMVert **input_verts,
+ const int num_input_verts))[3]
+{
+ float (*coords)[3] = MEM_callocN(sizeof(*coords) * num_input_verts, AT);
+ int i;
+
+ for (i = 0; i < num_input_verts; i++) {
+ copy_v3_v3(coords[i], input_verts[i]->co);
+ }
+
+ return coords;
+}
+
+static BMVert **hull_verts_from_bullet(plConvexHull hull,
+ BMVert **input_verts,
+ const int num_input_verts)
+{
+ const int num_verts = plConvexHullNumVertices(hull);
+ BMVert **hull_verts = MEM_mallocN(sizeof(*hull_verts) *
+ num_verts, AT);
+ int i;
+
+ for (i = 0; i < num_verts; i++) {
+ float co[3];
+ int original_index;
+ plConvexHullGetVertex(hull, i, co, &original_index);
+
+ if (original_index >= 0 && original_index < num_input_verts) {
+ hull_verts[i] = input_verts[original_index];
+ }
+ else
+ BLI_assert(!"Unexpected new vertex in hull output");
+ }
+
+ return hull_verts;
+}
+
+static void hull_from_bullet(BMesh *bm, BMOperator *op,
+ GHash *hull_triangles,
+ BLI_mempool *pool)
+{
+ int *fvi = NULL;
+ BLI_array_declare(fvi);
+
+ BMVert **input_verts;
+ float (*coords)[3];
+ BMVert **hull_verts;
+
+ plConvexHull hull;
+ int i, count = 0;
+
+ const int num_input_verts = hull_input_vert_count(bm, op);
+
+ input_verts = hull_input_verts_copy(bm, op, num_input_verts);
+ coords = hull_verts_for_bullet(input_verts, num_input_verts);
+
+ hull = plConvexHullCompute(coords, num_input_verts);
+ hull_verts = hull_verts_from_bullet(hull, input_verts, num_input_verts);
+
+ count = plConvexHullNumFaces(hull);
+ for (i = 0; i < count; i++) {
+ const int len = plConvexHullGetFaceSize(hull, i);
+
+ if (len > 2) {
+ BMVert *fv[3];
+ int j;
+
+ /* Get face vertex indices */
+ BLI_array_empty(fvi);
+ BLI_array_grow_items(fvi, len);
+ plConvexHullGetFaceVertices(hull, i, fvi);
+
+ /* Note: here we throw away any NGons from Bullet and turn
+ * them into triangle fans. Would be nice to use these
+ * directly, but will have to wait until HullTriangle goes
+ * away (TODO) */
+ fv[0] = hull_verts[fvi[0]];
+ for (j = 2; j < len; j++) {
+ fv[1] = hull_verts[fvi[j - 1]];
+ fv[2] = hull_verts[fvi[j]];
+
+ hull_add_triangle(bm, hull_triangles, pool,
+ fv[0], fv[1], fv[2]);
+ }
+ }
+ }
+
+ BLI_array_free(fvi);
+ MEM_freeN(hull_verts);
+ MEM_freeN(coords);
+ MEM_freeN(input_verts);
+}
+
+/* Check that there are at least three vertices in the input */
+static int hull_num_input_verts_is_ok(BMesh *bm, BMOperator *op)
+{
+ BMOIter oiter;
+ BMVert *v;
+ int partial_num_verts = 0;
+
+ BMO_ITER (v, &oiter, bm, op, "input", BM_VERT) {
+ partial_num_verts++;
+ if (partial_num_verts >= 3)
+ break;
+ }
+
+ return (partial_num_verts >= 3);
+}
+
void bmo_convex_hull_exec(BMesh *bm, BMOperator *op)
{
HullFinalEdges *final_edges;
- BLI_mempool *hull_pool, *edge_pool;
- BMVert *v, *tetra[4];
+ BLI_mempool *hull_pool;
BMElemF *ele;
BMOIter oiter;
GHash *hull_triangles;
- /* Verify that at least four verts in the input */
- if (BMO_slot_get(op, "input")->len < 4) {
- BMO_error_raise(bm, op, BMERR_CONVEX_HULL_FAILED,
- "Requires at least four vertices");
- return;
- }
-
- /* Initialize the convex hull by building a tetrahedron. A
- * degenerate tetrahedron can cause problems, so report error and
- * fail if the result is coplanar */
- if (hull_find_large_tetrahedron(bm, op, tetra)) {
+ /* Verify that at least three verts in the input */
+ if (!hull_num_input_verts_is_ok(bm, op)) {
BMO_error_raise(bm, op, BMERR_CONVEX_HULL_FAILED,
- "Input vertices are coplanar");
+ "Requires at least three vertices");
return;
}
@@ -700,26 +574,11 @@ void bmo_convex_hull_exec(BMesh *bm, BMOperator *op)
BMO_elem_flag_enable(bm, ele, HULL_FLAG_INTERIOR_ELE);
}
- edge_pool = BLI_mempool_create(sizeof(HullBoundaryEdge), 128, 128, 0);
hull_pool = BLI_mempool_create(sizeof(HullTriangle), 128, 128, 0);
hull_triangles = BLI_ghash_ptr_new("hull_triangles");
- /* Add tetrahedron triangles */
- hull_add_tetrahedron(bm, hull_triangles, hull_pool, tetra);
+ hull_from_bullet(bm, op, hull_triangles, hull_pool);
- /* Expand hull to cover new vertices outside the existing hull */
- BMO_ITER (v, &oiter, bm, op, "input", BM_VERT) {
- if (!BMO_elem_flag_test(bm, v, HULL_FLAG_TETRA_VERT)) {
- GHash *outside = hull_triangles_v_outside(hull_triangles, v);
- if (BLI_ghash_size(outside)) {
- /* Expand hull and delete interior triangles */
- add_point(bm, hull_triangles, hull_pool, edge_pool, outside, v);
- }
- BLI_ghash_free(outside, NULL, NULL);
- }
- }
-
- BLI_mempool_destroy(edge_pool);
final_edges = hull_final_edges(hull_triangles);
hull_mark_interior_elements(bm, op, final_edges);
@@ -762,3 +621,5 @@ void bmo_convex_hull_exec(BMesh *bm, BMOperator *op)
BMO_slot_buffer_from_enabled_flag(bm, op, "geomout", BM_ALL,
HULL_FLAG_OUTPUT_GEOM);
}
+
+#endif /* WITH_BULLET */
diff --git a/source/blender/bmesh/operators/bmo_join_triangles.c b/source/blender/bmesh/operators/bmo_join_triangles.c
index d780e309118..3dbc0d0a5eb 100644
--- a/source/blender/bmesh/operators/bmo_join_triangles.c
+++ b/source/blender/bmesh/operators/bmo_join_triangles.c
@@ -37,11 +37,6 @@
#include "intern/bmesh_operators_private.h" /* own include */
-/* Bitflags for edges */
-#define T2QDELETE 1
-#define T2QCOMPLEX 2
-#define T2QJOIN 4
-
/* assumes edges are validated before reaching this poin */
static float measure_facepair(BMVert *v1, BMVert *v2,
BMVert *v3, BMVert *v4, float limit)
@@ -110,93 +105,73 @@ static float measure_facepair(BMVert *v1, BMVert *v2,
#define T2QUV_LIMIT 0.005f
#define T2QCOL_LIMIT 3
-static int compareFaceAttribs(BMesh *bm, BMEdge *e, int douvs, int dovcols)
+static int bm_edge_faces_cmp(BMesh *bm, BMEdge *e, const int do_uv, const int do_tf, const int do_vcol)
{
- MTexPoly *tp1, *tp2;
- MLoopCol *lcol1, *lcol2, *lcol3, *lcol4;
- MLoopUV *luv1, *luv2, *luv3, *luv4;
- BMLoop *l1, *l2, *l3, *l4;
- int mergeok_uvs = !douvs, mergeok_vcols = !dovcols;
-
- l1 = e->l;
- l3 = e->l->radial_next;
+ /* first get loops */
+ BMLoop *l[4];
+
+ l[0] = e->l;
+ l[2] = e->l->radial_next;
- /* match up loops on each side of an edge corresponding to each ver */
- if (l1->v == l3->v) {
- l2 = l1->next;
- l4 = l2->next;
+ /* match up loops on each side of an edge corresponding to each vert */
+ if (l[0]->v == l[2]->v) {
+ l[1] = l[0]->next;
+ l[3] = l[1]->next;
}
else {
- l2 = l1->next;
+ l[1] = l[0]->next;
- l4 = l3;
- l3 = l4->next;
+ l[3] = l[2];
+ l[2] = l[3]->next;
}
- lcol1 = CustomData_bmesh_get(&bm->ldata, l1->head.data, CD_MLOOPCOL);
- lcol2 = CustomData_bmesh_get(&bm->ldata, l1->head.data, CD_MLOOPCOL);
- lcol3 = CustomData_bmesh_get(&bm->ldata, l1->head.data, CD_MLOOPCOL);
- lcol4 = CustomData_bmesh_get(&bm->ldata, l1->head.data, CD_MLOOPCOL);
-
- luv1 = CustomData_bmesh_get(&bm->ldata, l1->head.data, CD_MLOOPUV);
- luv2 = CustomData_bmesh_get(&bm->ldata, l1->head.data, CD_MLOOPUV);
- luv3 = CustomData_bmesh_get(&bm->ldata, l1->head.data, CD_MLOOPUV);
- luv4 = CustomData_bmesh_get(&bm->ldata, l1->head.data, CD_MLOOPUV);
-
- tp1 = CustomData_bmesh_get(&bm->pdata, l1->f->head.data, CD_MTEXPOLY);
- tp2 = CustomData_bmesh_get(&bm->pdata, l2->f->head.data, CD_MTEXPOLY);
-
- if (!lcol1)
- mergeok_vcols = 1;
-
- if (!luv1)
- mergeok_uvs = 1;
-
- /* compare faceedges for each face attribute. Additional per face attributes can be added late */
-
- /* do VCOL */
- if (lcol1 && dovcols) {
- char *cols[4] = {(char *)lcol1, (char *)lcol2, (char *)lcol3, (char *)lcol4};
- int i;
-
- for (i = 0; i < 3; i++) {
- if (cols[0][i] + T2QCOL_LIMIT < cols[2][i] - T2QCOL_LIMIT)
- break;
- if (cols[1][i] + T2QCOL_LIMIT < cols[3][i] - T2QCOL_LIMIT)
- break;
+ /* Test UV's */
+ if (do_uv) {
+ const MLoopUV *luv[4] = {
+ CustomData_bmesh_get(&bm->ldata, l[0]->head.data, CD_MLOOPUV),
+ CustomData_bmesh_get(&bm->ldata, l[1]->head.data, CD_MLOOPUV),
+ CustomData_bmesh_get(&bm->ldata, l[2]->head.data, CD_MLOOPUV),
+ CustomData_bmesh_get(&bm->ldata, l[3]->head.data, CD_MLOOPUV),
+ };
+
+ /* do UV */
+ if (luv[0] && (!compare_v2v2(luv[0]->uv, luv[2]->uv, T2QUV_LIMIT) ||
+ !compare_v2v2(luv[1]->uv, luv[3]->uv, T2QUV_LIMIT)))
+ {
+ return FALSE;
}
-
- if (i == 3)
- mergeok_vcols = 1;
}
- /* do UV */
- if (luv1 && douvs) {
- if (tp1->tpage != tp2->tpage) {
- /* do nothing */
- }
- else {
- int i;
+ if (do_tf) {
+ const MTexPoly *tp[2] = {
+ CustomData_bmesh_get(&bm->pdata, l[0]->f->head.data, CD_MTEXPOLY),
+ CustomData_bmesh_get(&bm->pdata, l[1]->f->head.data, CD_MTEXPOLY),
+ };
- for (i = 0; i < 2; i++) {
- if (luv1->uv[0] + T2QUV_LIMIT > luv3->uv[0] && luv1->uv[0] - T2QUV_LIMIT < luv3->uv[0] &&
- luv1->uv[1] + T2QUV_LIMIT > luv3->uv[1] && luv1->uv[1] - T2QUV_LIMIT < luv3->uv[1])
- {
- if (luv2->uv[0] + T2QUV_LIMIT > luv4->uv[0] && luv2->uv[0] - T2QUV_LIMIT < luv4->uv[0] &&
- luv2->uv[1] + T2QUV_LIMIT > luv4->uv[1] && luv2->uv[1] - T2QUV_LIMIT < luv4->uv[1])
- {
- mergeok_uvs = 1;
- }
- }
- }
+ if (tp[0] && (tp[0]->tpage != tp[1]->tpage)) {
+ return FALSE;
}
}
- if (douvs == mergeok_uvs && dovcols == mergeok_vcols) {
- return TRUE;
+ /* Test Vertex Colors */
+ if (do_vcol) {
+ const MLoopCol *lcol[4] = {
+ CustomData_bmesh_get(&bm->ldata, l[0]->head.data, CD_MLOOPCOL),
+ CustomData_bmesh_get(&bm->ldata, l[1]->head.data, CD_MLOOPCOL),
+ CustomData_bmesh_get(&bm->ldata, l[2]->head.data, CD_MLOOPCOL),
+ CustomData_bmesh_get(&bm->ldata, l[3]->head.data, CD_MLOOPCOL),
+ };
+
+ if (lcol[0]) {
+ if (!compare_rgb_uchar((unsigned char *)&lcol[0]->r, (unsigned char *)&lcol[2]->r, T2QCOL_LIMIT) ||
+ !compare_rgb_uchar((unsigned char *)&lcol[1]->r, (unsigned char *)&lcol[3]->r, T2QCOL_LIMIT))
+ {
+ return FALSE;
+ }
+ }
}
- return FALSE;
+ return TRUE;
}
typedef struct JoinEdge {
@@ -224,28 +199,30 @@ void bmo_join_triangles_exec(BMesh *bm, BMOperator *op)
{
BMIter iter, liter;
BMOIter siter;
- BMFace *f1, *f2;
+ BMFace *f;
BMLoop *l;
BMEdge *e;
BLI_array_declare(jedges);
JoinEdge *jedges = NULL;
- int dosharp = BMO_slot_bool_get(op, "cmp_sharp");
- int douvs = BMO_slot_bool_get(op, "cmp_uvs");
- int dovcols = BMO_slot_bool_get(op, "cmp_vcols");
- int domat = BMO_slot_bool_get(op, "cmp_materials");
- float limit = BMO_slot_float_get(op, "limit");
+ int do_sharp = BMO_slot_bool_get(op, "cmp_sharp");
+ int do_uv = BMO_slot_bool_get(op, "cmp_uvs");
+ int do_tf = do_uv; /* texture face, make make its own option eventually */
+ int do_vcol = BMO_slot_bool_get(op, "cmp_vcols");
+ int do_mat = BMO_slot_bool_get(op, "cmp_materials");
+ float limit = BMO_slot_float_get(op, "limit");
int i, totedge;
/* flag all edges of all input face */
- BMO_ITER (f1, &siter, bm, op, "faces", BM_FACE) {
- BMO_elem_flag_enable(bm, f1, FACE_INPUT);
- BM_ITER_ELEM (l, &liter, f1, BM_LOOPS_OF_FACE) {
+ BMO_ITER (f, &siter, bm, op, "faces", BM_FACE) {
+ BMO_elem_flag_enable(bm, f, FACE_INPUT);
+ BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
BMO_elem_flag_enable(bm, l->e, EDGE_MARK);
}
}
/* unflag edges that are invalid; e.g. aren't surrounded by triangle */
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
+ BMFace *f1, *f2;
if (!BMO_elem_flag_test(bm, e, EDGE_MARK))
continue;
@@ -282,13 +259,13 @@ void bmo_join_triangles_exec(BMesh *bm, BMOperator *op)
v3 = e->l->next->v;
v4 = e->l->radial_next->prev->v;
- if (dosharp && !BM_elem_flag_test(e, BM_ELEM_SMOOTH))
+ if (do_sharp && !BM_elem_flag_test(e, BM_ELEM_SMOOTH))
continue;
-
- if ((douvs || dovcols) && compareFaceAttribs(bm, e, douvs, dovcols))
+
+ if (do_mat && f1->mat_nr != f2->mat_nr)
continue;
- if (domat && f1->mat_nr != f2->mat_nr)
+ if ((do_uv || do_tf || do_vcol) && (bm_edge_faces_cmp(bm, e, do_uv, do_tf, do_vcol) == FALSE))
continue;
measure = measure_facepair(v1, v2, v3, v4, limit);
@@ -324,6 +301,8 @@ void bmo_join_triangles_exec(BMesh *bm, BMOperator *op)
}
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
+ BMFace *f1, *f2;
+
if (!BMO_elem_flag_test(bm, e, EDGE_CHOSEN))
continue;
@@ -334,6 +313,8 @@ void bmo_join_triangles_exec(BMesh *bm, BMOperator *op)
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
if (BMO_elem_flag_test(bm, e, EDGE_MARK)) {
+ BMFace *f1, *f2;
+
/* ok, this edge wasn't merged, check if it's
* in a 2-tri-pair island, and if so merg */
diff --git a/source/blender/bmesh/operators/bmo_primitive.c b/source/blender/bmesh/operators/bmo_primitive.c
index 70173d942a1..d7b163cb760 100644
--- a/source/blender/bmesh/operators/bmo_primitive.c
+++ b/source/blender/bmesh/operators/bmo_primitive.c
@@ -309,7 +309,7 @@ void bmo_create_uvsphere_exec(BMesh *bm, BMOperator *op)
phid /= 2;
for (a = 0; a <= tot; a++) {
/* Going in this direction, then edge extruding, makes normals face outward */
- vec[0] = -dia *sinf(phi);
+ vec[0] = -dia * sinf(phi);
vec[1] = 0.0;
vec[2] = dia * cosf(phi);
eve = BM_vert_create(bm, vec, NULL);
@@ -354,7 +354,7 @@ void bmo_create_uvsphere_exec(BMesh *bm, BMOperator *op)
{
float len, len2, vec2[3];
- len = 2 *dia *sinf(phid / 2.0f);
+ len = 2 *dia * sinf(phid / 2.0f);
/* length of one segment in shortest parallen */
vec[0] = dia * sinf(phid);
@@ -365,7 +365,7 @@ void bmo_create_uvsphere_exec(BMesh *bm, BMOperator *op)
len2 = len_v3v3(vec, vec2);
/* use shortest segment length divided by 3 as merge threshold */
- BMO_op_callf(bm, op->flag, "remove_doubles verts=%fv dist=%f", VERT_MARK, MIN2(len, len2) / 3.0f);
+ BMO_op_callf(bm, op->flag, "remove_doubles verts=%fv dist=%f", VERT_MARK, min_ff(len, len2) / 3.0f);
}
/* and now do imat */
@@ -517,16 +517,16 @@ void bmo_create_circle_exec(BMesh *bm, BMOperator *op)
phi = 0;
if (cap_ends) {
- vec[0] = vec[1] = 0.0f;
- vec[2] = 0.0;
+ zero_v3(vec);
mul_m4_v3(mat, vec);
cent1 = BM_vert_create(bm, vec, NULL);
+ BMO_elem_flag_enable(bm, cent1, VERT_MARK);
}
for (a = 0; a < segs; a++, phi += phid) {
/* Going this way ends up with normal(s) upward */
- vec[0] = -dia *sinf(phi);
+ vec[0] = -dia * sinf(phi);
vec[1] = dia * cosf(phi);
vec[2] = 0.0f;
mul_m4_v3(mat, vec);
diff --git a/source/blender/bmesh/operators/bmo_removedoubles.c b/source/blender/bmesh/operators/bmo_removedoubles.c
index 0caa766c0f0..cd792f911a9 100644
--- a/source/blender/bmesh/operators/bmo_removedoubles.c
+++ b/source/blender/bmesh/operators/bmo_removedoubles.c
@@ -244,11 +244,11 @@ static int vergaverco(const void *e1, const void *e2)
else return 0;
}
-#define VERT_TESTED 1
+// #define VERT_TESTED 1 // UNUSED
#define VERT_DOUBLE 2
#define VERT_TARGET 4
#define VERT_KEEP 8
-#define VERT_MARK 16
+// #define VERT_MARK 16 // UNUSED
#define VERT_IN 32
#define EDGE_MARK 1
@@ -371,7 +371,7 @@ void bmo_collapse_exec(BMesh *bm, BMOperator *op)
BMIter iter;
BMEdge *e, **edges = NULL;
BLI_array_declare(edges);
- float min[3], max[3];
+ float min[3], max[3], center[3];
int i, tot;
BMO_op_callf(bm, op->flag, "collapse_uvs edges=%s", op, "edges");
@@ -400,13 +400,12 @@ void bmo_collapse_exec(BMesh *bm, BMOperator *op)
minmax_v3v3_v3(min, max, e->v2->co);
}
- add_v3_v3v3(min, min, max);
- mul_v3_fl(min, 0.5f);
+ mid_v3_v3v3(center, min, max);
/* snap edges to a point. for initial testing purposes anyway */
for (i = 0; i < tot; i++) {
- copy_v3_v3(edges[i]->v1->co, min);
- copy_v3_v3(edges[i]->v2->co, min);
+ copy_v3_v3(edges[i]->v1->co, center);
+ copy_v3_v3(edges[i]->v2->co, center);
if (edges[i]->v1 != edges[0]->v1)
BMO_slot_map_ptr_insert(bm, &weldop, "targetmap", edges[i]->v1, edges[0]->v1);
diff --git a/source/blender/bmesh/operators/bmo_similar.c b/source/blender/bmesh/operators/bmo_similar.c
new file mode 100644
index 00000000000..df03e50d2c4
--- /dev/null
+++ b/source/blender/bmesh/operators/bmo_similar.c
@@ -0,0 +1,614 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Joseph Eagar, Campbell Barton
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/bmesh/operators/bmo_similar.c
+ * \ingroup bmesh
+ *
+ * bmesh operators to select based on
+ * comparisons with the existing selection.
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_object_types.h"
+#include "DNA_meshdata_types.h"
+
+#include "BLI_math.h"
+
+#include "BKE_customdata.h"
+#include "BKE_deform.h"
+
+#include "bmesh.h"
+
+#include "intern/bmesh_operators_private.h" /* own include */
+
+/* in fact these could all be the same */
+
+/*
+ * extra face data (computed data)
+ */
+typedef struct SimSel_FaceExt {
+ BMFace *f; /* the face */
+ float c[3]; /* center */
+ union {
+ float area; /* area */
+ float perim; /* perimeter */
+ float d; /* 4th component of plane (the first three being the normal) */
+ struct Image *t; /* image pointer */
+ };
+} SimSel_FaceExt;
+
+static int bm_sel_similar_cmp_fl(const float delta, const float thresh, const int compare)
+{
+ switch (compare) {
+ case SIM_CMP_EQ:
+ return (fabsf(delta) <= thresh);
+ case SIM_CMP_GT:
+ return ((delta + thresh) >= 0.0f);
+ case SIM_CMP_LT:
+ return ((delta - thresh) <= 0.0f);
+ default:
+ BLI_assert(0);
+ return 0;
+ }
+}
+
+static int bm_sel_similar_cmp_i(const int delta, const int compare)
+{
+ switch (compare) {
+ case SIM_CMP_EQ:
+ return (delta == 0);
+ case SIM_CMP_GT:
+ return (delta > 0);
+ case SIM_CMP_LT:
+ return (delta < 0);
+ default:
+ BLI_assert(0);
+ return 0;
+ }
+}
+
+/*
+ * Select similar faces, the choices are in the enum in source/blender/bmesh/bmesh_operators.h
+ * We select either similar faces based on material, image, area, perimeter, normal, or the coplanar faces
+ */
+void bmo_similar_faces_exec(BMesh *bm, BMOperator *op)
+{
+#define FACE_MARK 1
+
+ BMIter fm_iter;
+ BMFace *fs, *fm;
+ BMOIter fs_iter;
+ int num_sels = 0, num_total = 0, i = 0, idx = 0;
+ float angle = 0.0f;
+ SimSel_FaceExt *f_ext = NULL;
+ int *indices = NULL;
+ float t_no[3]; /* temporary normal */
+ const int type = BMO_slot_int_get(op, "type");
+ const float thresh = BMO_slot_float_get(op, "thresh");
+ const float thresh_radians = thresh * (float)M_PI;
+ const int compare = BMO_slot_int_get(op, "compare");
+
+ /* initial_elem - other_elem */
+ float delta_fl;
+ int delta_i;
+
+ num_total = BM_mesh_elem_count(bm, BM_FACE);
+
+ /*
+ * The first thing to do is to iterate through all the the selected items and mark them since
+ * they will be in the selection anyway.
+ * This will increase performance, (especially when the number of originally selected faces is high)
+ * so the overall complexity will be less than $O(mn)$ where is the total number of selected faces,
+ * and n is the total number of faces
+ */
+ BMO_ITER (fs, &fs_iter, bm, op, "faces", BM_FACE) {
+ if (!BMO_elem_flag_test(bm, fs, FACE_MARK)) { /* is this really needed ? */
+ BMO_elem_flag_enable(bm, fs, FACE_MARK);
+ num_sels++;
+ }
+ }
+
+ /* allocate memory for the selected faces indices and for all temporary faces */
+ indices = (int *)MEM_callocN(sizeof(int) * num_sels, "face indices util.c");
+ f_ext = (SimSel_FaceExt *)MEM_callocN(sizeof(SimSel_FaceExt) * num_total, "f_ext util.c");
+
+ /* loop through all the faces and fill the faces/indices structure */
+ BM_ITER_MESH (fm, &fm_iter, bm, BM_FACES_OF_MESH) {
+ f_ext[i].f = fm;
+ if (BMO_elem_flag_test(bm, fm, FACE_MARK)) {
+ indices[idx] = i;
+ idx++;
+ }
+ i++;
+ }
+
+ /*
+ * Save us some computation burden: In case of perimeter/area/coplanar selection we compute
+ * only once.
+ */
+ if (type == SIMFACE_PERIMETER || type == SIMFACE_AREA || type == SIMFACE_COPLANAR || type == SIMFACE_IMAGE) {
+ for (i = 0; i < num_total; i++) {
+ switch (type) {
+ case SIMFACE_PERIMETER:
+ /* set the perimeter */
+ f_ext[i].perim = BM_face_calc_perimeter(f_ext[i].f);
+ break;
+
+ case SIMFACE_COPLANAR:
+ /* compute the center of the polygon */
+ BM_face_calc_center_mean(f_ext[i].f, f_ext[i].c);
+
+ /* normalize the polygon normal */
+ copy_v3_v3(t_no, f_ext[i].f->no);
+ normalize_v3(t_no);
+
+ /* compute the plane distance */
+ f_ext[i].d = dot_v3v3(t_no, f_ext[i].c);
+ break;
+
+ case SIMFACE_AREA:
+ f_ext[i].area = BM_face_calc_area(f_ext[i].f);
+ break;
+
+ case SIMFACE_IMAGE:
+ f_ext[i].t = NULL;
+ if (CustomData_has_layer(&(bm->pdata), CD_MTEXPOLY)) {
+ MTexPoly *mtpoly = CustomData_bmesh_get(&bm->pdata, f_ext[i].f->head.data, CD_MTEXPOLY);
+ f_ext[i].t = mtpoly->tpage;
+ }
+ break;
+ }
+ }
+ }
+
+ /* now select the rest (if any) */
+ for (i = 0; i < num_total; i++) {
+ fm = f_ext[i].f;
+ if (!BMO_elem_flag_test(bm, fm, FACE_MARK) && !BM_elem_flag_test(fm, BM_ELEM_HIDDEN)) {
+ int cont = TRUE;
+ for (idx = 0; idx < num_sels && cont == TRUE; idx++) {
+ fs = f_ext[indices[idx]].f;
+ switch (type) {
+ case SIMFACE_MATERIAL:
+ if (fm->mat_nr == fs->mat_nr) {
+ BMO_elem_flag_enable(bm, fm, FACE_MARK);
+ cont = FALSE;
+ }
+ break;
+
+ case SIMFACE_IMAGE:
+ if (f_ext[i].t == f_ext[indices[idx]].t) {
+ BMO_elem_flag_enable(bm, fm, FACE_MARK);
+ cont = FALSE;
+ }
+ break;
+
+ case SIMFACE_NORMAL:
+ angle = angle_normalized_v3v3(fs->no, fm->no); /* if the angle between the normals -> 0 */
+ if (angle <= thresh_radians) {
+ BMO_elem_flag_enable(bm, fm, FACE_MARK);
+ cont = FALSE;
+ }
+ break;
+
+ case SIMFACE_COPLANAR:
+ angle = angle_normalized_v3v3(fs->no, fm->no); /* angle -> 0 */
+ if (angle <= thresh_radians) { /* and dot product difference -> 0 */
+ delta_fl = f_ext[i].d - f_ext[indices[idx]].d;
+ if (bm_sel_similar_cmp_fl(delta_fl, thresh, compare)) {
+ BMO_elem_flag_enable(bm, fm, FACE_MARK);
+ cont = FALSE;
+ }
+ }
+ break;
+
+ case SIMFACE_AREA:
+ delta_fl = f_ext[i].area - f_ext[indices[idx]].area;
+ if (bm_sel_similar_cmp_fl(delta_fl, thresh, compare)) {
+ BMO_elem_flag_enable(bm, fm, FACE_MARK);
+ cont = FALSE;
+ }
+ break;
+
+ case SIMFACE_SIDES:
+ delta_i = fm->len - fs->len;
+ if (bm_sel_similar_cmp_i(delta_i, compare)) {
+ BMO_elem_flag_enable(bm, fm, FACE_MARK);
+ cont = FALSE;
+ }
+ break;
+
+ case SIMFACE_PERIMETER:
+ delta_fl = f_ext[i].perim - f_ext[indices[idx]].perim;
+ if (bm_sel_similar_cmp_fl(delta_fl, thresh, compare)) {
+ BMO_elem_flag_enable(bm, fm, FACE_MARK);
+ cont = FALSE;
+ }
+ break;
+ default:
+ BLI_assert(0);
+ }
+ }
+ }
+ }
+
+ MEM_freeN(f_ext);
+ MEM_freeN(indices);
+
+ /* transfer all marked faces to the output slot */
+ BMO_slot_buffer_from_enabled_flag(bm, op, "faceout", BM_FACE, FACE_MARK);
+#undef FACE_MARK
+}
+
+/**************************************************************************** *
+ * Similar Edges
+ **************************************************************************** */
+
+/*
+ * extra edge information
+ */
+typedef struct SimSel_EdgeExt {
+ BMEdge *e;
+ union {
+ float dir[3];
+ float angle; /* angle between the face */
+ };
+
+ union {
+ float length; /* edge length */
+ int faces; /* faces count */
+ };
+} SimSel_EdgeExt;
+
+/*
+ * select similar edges: the choices are in the enum in source/blender/bmesh/bmesh_operators.h
+ * choices are length, direction, face, ...
+ */
+void bmo_similar_edges_exec(BMesh *bm, BMOperator *op)
+{
+#define EDGE_MARK 1
+
+ BMOIter es_iter; /* selected edges iterator */
+ BMIter e_iter; /* mesh edges iterator */
+ BMEdge *es; /* selected edge */
+ BMEdge *e; /* mesh edge */
+ int idx = 0, i = 0 /* , f = 0 */;
+ int *indices = NULL;
+ SimSel_EdgeExt *e_ext = NULL;
+ // float *angles = NULL;
+ float angle;
+
+ int num_sels = 0, num_total = 0;
+ const int type = BMO_slot_int_get(op, "type");
+ const float thresh = BMO_slot_float_get(op, "thresh");
+ const int compare = BMO_slot_int_get(op, "compare");
+
+ /* initial_elem - other_elem */
+ float delta_fl;
+ int delta_i;
+
+ /* sanity checks that the data we need is available */
+ switch (type) {
+ case SIMEDGE_CREASE:
+ if (!CustomData_has_layer(&bm->edata, CD_CREASE)) {
+ return;
+ }
+ break;
+ case SIMEDGE_BEVEL:
+ if (!CustomData_has_layer(&bm->edata, CD_BWEIGHT)) {
+ return;
+ }
+ break;
+ }
+
+ num_total = BM_mesh_elem_count(bm, BM_EDGE);
+
+ /* iterate through all selected edges and mark them */
+ BMO_ITER (es, &es_iter, bm, op, "edges", BM_EDGE) {
+ BMO_elem_flag_enable(bm, es, EDGE_MARK);
+ num_sels++;
+ }
+
+ /* allocate memory for the selected edges indices and for all temporary edges */
+ indices = (int *)MEM_callocN(sizeof(int) * num_sels, __func__);
+ e_ext = (SimSel_EdgeExt *)MEM_callocN(sizeof(SimSel_EdgeExt) * num_total, __func__);
+
+ /* loop through all the edges and fill the edges/indices structure */
+ BM_ITER_MESH (e, &e_iter, bm, BM_EDGES_OF_MESH) {
+ e_ext[i].e = e;
+ if (BMO_elem_flag_test(bm, e, EDGE_MARK)) {
+ indices[idx] = i;
+ idx++;
+ }
+ i++;
+ }
+
+ /* save us some computation time by doing heavy computation once */
+ if (type == SIMEDGE_LENGTH || type == SIMEDGE_FACE || type == SIMEDGE_DIR || type == SIMEDGE_FACE_ANGLE) {
+ for (i = 0; i < num_total; i++) {
+ switch (type) {
+ case SIMEDGE_LENGTH: /* compute the length of the edge */
+ e_ext[i].length = len_v3v3(e_ext[i].e->v1->co, e_ext[i].e->v2->co);
+ break;
+
+ case SIMEDGE_DIR: /* compute the direction */
+ sub_v3_v3v3(e_ext[i].dir, e_ext[i].e->v1->co, e_ext[i].e->v2->co);
+ normalize_v3(e_ext[i].dir);
+ break;
+
+ case SIMEDGE_FACE: /* count the faces around the edge */
+ e_ext[i].faces = BM_edge_face_count(e_ext[i].e);
+ break;
+
+ case SIMEDGE_FACE_ANGLE:
+ e_ext[i].faces = BM_edge_face_count(e_ext[i].e);
+ if (e_ext[i].faces == 2)
+ e_ext[i].angle = BM_edge_calc_face_angle(e_ext[i].e);
+ break;
+ }
+ }
+ }
+
+ /* select the edges if any */
+ for (i = 0; i < num_total; i++) {
+ e = e_ext[i].e;
+ if (!BMO_elem_flag_test(bm, e, EDGE_MARK) && !BM_elem_flag_test(e, BM_ELEM_HIDDEN)) {
+ int cont = TRUE;
+ for (idx = 0; idx < num_sels && cont == TRUE; idx++) {
+ es = e_ext[indices[idx]].e;
+ switch (type) {
+ case SIMEDGE_LENGTH:
+ delta_fl = e_ext[i].length - e_ext[indices[idx]].length;
+ if (bm_sel_similar_cmp_fl(delta_fl, thresh, compare)) {
+ BMO_elem_flag_enable(bm, e, EDGE_MARK);
+ cont = FALSE;
+ }
+ break;
+
+ case SIMEDGE_DIR:
+ /* compute the angle between the two edges */
+ angle = angle_normalized_v3v3(e_ext[i].dir, e_ext[indices[idx]].dir);
+
+ if (angle > (float)(M_PI / 2.0)) /* use the smallest angle between the edges */
+ angle = fabsf(angle - (float)M_PI);
+
+ if (angle / (float)(M_PI / 2.0) <= thresh) {
+ BMO_elem_flag_enable(bm, e, EDGE_MARK);
+ cont = FALSE;
+ }
+ break;
+
+ case SIMEDGE_FACE:
+ delta_i = e_ext[i].faces - e_ext[indices[idx]].faces;
+ if (bm_sel_similar_cmp_i(delta_i, compare)) {
+ BMO_elem_flag_enable(bm, e, EDGE_MARK);
+ cont = FALSE;
+ }
+ break;
+
+ case SIMEDGE_FACE_ANGLE:
+ if (e_ext[i].faces == 2) {
+ if (e_ext[indices[idx]].faces == 2) {
+ if (fabsf(e_ext[i].angle - e_ext[indices[idx]].angle) <= thresh) {
+ BMO_elem_flag_enable(bm, e, EDGE_MARK);
+ cont = FALSE;
+ }
+ }
+ }
+ else {
+ cont = FALSE;
+ }
+ break;
+
+ case SIMEDGE_CREASE:
+ {
+ float *c1, *c2;
+
+ c1 = CustomData_bmesh_get(&bm->edata, e->head.data, CD_CREASE);
+ c2 = CustomData_bmesh_get(&bm->edata, es->head.data, CD_CREASE);
+ delta_fl = *c1 - *c2;
+
+ if (bm_sel_similar_cmp_fl(delta_fl, thresh, compare)) {
+ BMO_elem_flag_enable(bm, e, EDGE_MARK);
+ cont = FALSE;
+ }
+ }
+ break;
+
+ case SIMEDGE_BEVEL:
+ {
+ float *c1, *c2;
+
+ c1 = CustomData_bmesh_get(&bm->edata, e->head.data, CD_BWEIGHT);
+ c2 = CustomData_bmesh_get(&bm->edata, es->head.data, CD_BWEIGHT);
+ delta_fl = *c1 - *c2;
+
+ if (bm_sel_similar_cmp_fl(delta_fl, thresh, compare)) {
+ BMO_elem_flag_enable(bm, e, EDGE_MARK);
+ cont = FALSE;
+ }
+ }
+ break;
+
+ case SIMEDGE_SEAM:
+ if (BM_elem_flag_test(e, BM_ELEM_SEAM) == BM_elem_flag_test(es, BM_ELEM_SEAM)) {
+ BMO_elem_flag_enable(bm, e, EDGE_MARK);
+ cont = FALSE;
+ }
+ break;
+
+ case SIMEDGE_SHARP:
+ if (BM_elem_flag_test(e, BM_ELEM_SMOOTH) == BM_elem_flag_test(es, BM_ELEM_SMOOTH)) {
+ BMO_elem_flag_enable(bm, e, EDGE_MARK);
+ cont = FALSE;
+ }
+ break;
+ default:
+ BLI_assert(0);
+ }
+ }
+ }
+ }
+
+ MEM_freeN(e_ext);
+ MEM_freeN(indices);
+
+ /* transfer all marked edges to the output slot */
+ BMO_slot_buffer_from_enabled_flag(bm, op, "edgeout", BM_EDGE, EDGE_MARK);
+
+#undef EDGE_MARK
+}
+
+/**************************************************************************** *
+ * Similar Vertices
+ **************************************************************************** */
+
+typedef struct SimSel_VertExt {
+ BMVert *v;
+ union {
+ int num_faces; /* adjacent faces */
+ int num_edges; /* adjacent edges */
+ MDeformVert *dvert; /* deform vertex */
+ };
+} SimSel_VertExt;
+
+/*
+ * select similar vertices: the choices are in the enum in source/blender/bmesh/bmesh_operators.h
+ * choices are normal, face, vertex group...
+ */
+void bmo_similar_verts_exec(BMesh *bm, BMOperator *op)
+{
+#define VERT_MARK 1
+
+ BMOIter vs_iter; /* selected verts iterator */
+ BMIter v_iter; /* mesh verts iterator */
+ BMVert *vs; /* selected vertex */
+ BMVert *v; /* mesh vertex */
+ SimSel_VertExt *v_ext = NULL;
+ int *indices = NULL;
+ int num_total = 0, num_sels = 0, i = 0, idx = 0;
+ const int type = BMO_slot_int_get(op, "type");
+ const float thresh = BMO_slot_float_get(op, "thresh");
+ const float thresh_radians = thresh * (float)M_PI;
+ const int compare = BMO_slot_int_get(op, "compare");
+
+ /* initial_elem - other_elem */
+// float delta_fl;
+ int delta_i;
+
+ num_total = BM_mesh_elem_count(bm, BM_VERT);
+
+ /* iterate through all selected edges and mark them */
+ BMO_ITER (vs, &vs_iter, bm, op, "verts", BM_VERT) {
+ BMO_elem_flag_enable(bm, vs, VERT_MARK);
+ num_sels++;
+ }
+
+ /* allocate memory for the selected vertices indices and for all temporary vertices */
+ indices = (int *)MEM_mallocN(sizeof(int) * num_sels, "vertex indices");
+ v_ext = (SimSel_VertExt *)MEM_mallocN(sizeof(SimSel_VertExt) * num_total, "vertex extra");
+
+ /* loop through all the vertices and fill the vertices/indices structure */
+ BM_ITER_MESH (v, &v_iter, bm, BM_VERTS_OF_MESH) {
+ v_ext[i].v = v;
+ if (BMO_elem_flag_test(bm, v, VERT_MARK)) {
+ indices[idx] = i;
+ idx++;
+ }
+
+ switch (type) {
+ case SIMVERT_FACE:
+ /* calling BM_vert_face_count every time is time consumming, so call it only once per vertex */
+ v_ext[i].num_faces = BM_vert_face_count(v);
+ break;
+
+ case SIMVERT_VGROUP:
+ if (CustomData_has_layer(&(bm->vdata), CD_MDEFORMVERT)) {
+ v_ext[i].dvert = CustomData_bmesh_get(&bm->vdata, v_ext[i].v->head.data, CD_MDEFORMVERT);
+ }
+ else {
+ v_ext[i].dvert = NULL;
+ }
+ break;
+ case SIMVERT_EDGE:
+ v_ext[i].num_edges = BM_vert_edge_count(v);
+ break;
+ }
+
+ i++;
+ }
+
+ /* select the vertices if any */
+ for (i = 0; i < num_total; i++) {
+ v = v_ext[i].v;
+ if (!BMO_elem_flag_test(bm, v, VERT_MARK) && !BM_elem_flag_test(v, BM_ELEM_HIDDEN)) {
+ int cont = TRUE;
+ for (idx = 0; idx < num_sels && cont == TRUE; idx++) {
+ vs = v_ext[indices[idx]].v;
+ switch (type) {
+ case SIMVERT_NORMAL:
+ /* compare the angle between the normals */
+ if (angle_normalized_v3v3(v->no, vs->no) <= thresh_radians) {
+ BMO_elem_flag_enable(bm, v, VERT_MARK);
+ cont = FALSE;
+ }
+ break;
+ case SIMVERT_FACE:
+ /* number of adjacent faces */
+ delta_i = v_ext[i].num_faces - v_ext[indices[idx]].num_faces;
+ if (bm_sel_similar_cmp_i(delta_i, compare)) {
+ BMO_elem_flag_enable(bm, v, VERT_MARK);
+ cont = FALSE;
+ }
+ break;
+
+ case SIMVERT_VGROUP:
+ if (v_ext[i].dvert != NULL && v_ext[indices[idx]].dvert != NULL) {
+ if (defvert_find_shared(v_ext[i].dvert, v_ext[indices[idx]].dvert) != -1) {
+ BMO_elem_flag_enable(bm, v, VERT_MARK);
+ cont = FALSE;
+ }
+ }
+ break;
+ case SIMVERT_EDGE:
+ /* number of adjacent edges */
+ delta_i = v_ext[i].num_edges - v_ext[indices[idx]].num_edges;
+ if (bm_sel_similar_cmp_i(delta_i, compare)) {
+ BMO_elem_flag_enable(bm, v, VERT_MARK);
+ cont = FALSE;
+ }
+ break;
+ default:
+ BLI_assert(0);
+ }
+ }
+ }
+ }
+
+ MEM_freeN(indices);
+ MEM_freeN(v_ext);
+
+ BMO_slot_buffer_from_enabled_flag(bm, op, "vertout", BM_VERT, VERT_MARK);
+
+#undef VERT_MARK
+}
diff --git a/source/blender/bmesh/operators/bmo_slide.c b/source/blender/bmesh/operators/bmo_slide.c
index 0036f095d00..6db76119205 100644
--- a/source/blender/bmesh/operators/bmo_slide.c
+++ b/source/blender/bmesh/operators/bmo_slide.c
@@ -63,7 +63,7 @@ void bmo_slide_vert_exec(BMesh *bm, BMOperator *op)
if (G.debug & G_DEBUG) {
fprintf(stderr, "slide_vert: No vertex selected...");
}
- BMO_error_raise(bm, op, BMERR_INVALID_SELECTION, "Vertex Slide Error: Invalid selection.");
+ BMO_error_raise(bm, op, BMERR_INVALID_SELECTION, "Vertex Slide error: invalid selection");
return;
}
@@ -83,7 +83,7 @@ void bmo_slide_vert_exec(BMesh *bm, BMOperator *op)
if (G.debug & G_DEBUG) {
fprintf(stderr, "slide_vert: select a single edge\n");
}
- BMO_error_raise(bm, op, BMERR_INVALID_SELECTION, "Vertex Slide Error: Invalid selection.");
+ BMO_error_raise(bm, op, BMERR_INVALID_SELECTION, "Vertex Slide error: invalid selection");
return;
}
diff --git a/source/blender/bmesh/operators/bmo_smooth_laplacian.c b/source/blender/bmesh/operators/bmo_smooth_laplacian.c
new file mode 100644
index 00000000000..51b9adb5de3
--- /dev/null
+++ b/source/blender/bmesh/operators/bmo_smooth_laplacian.c
@@ -0,0 +1,619 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Alexander Pinzon
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/bmesh/operators/bmo_smooth_laplacian.c
+ * \ingroup bmesh
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_meshdata_types.h"
+
+#include "BLI_array.h"
+#include "BLI_heap.h"
+#include "BLI_math.h"
+#include "BLI_math_geom.h"
+#include "BLI_smallhash.h"
+
+#include "BKE_customdata.h"
+#include "BKE_mesh.h"
+
+#include "bmesh.h"
+
+#include "ONL_opennl.h"
+
+#include "intern/bmesh_operators_private.h" /* own include */
+
+#define SMOOTH_LAPLACIAN_AREA_FACTOR 4.0f
+#define SMOOTH_LAPLACIAN_EDGE_FACTOR 2.0f
+#define SMOOTH_LAPLACIAN_MAX_EDGE_PERCENTAGE 1.8f
+#define SMOOTH_LAPLACIAN_MIN_EDGE_PERCENTAGE 0.15f
+
+struct BLaplacianSystem {
+ float *eweights; /* Length weights per Edge */
+ float (*fweights)[3]; /* Cotangent weights per face */
+ float *ring_areas; /* Total area per ring*/
+ float *vlengths; /* Total sum of lengths(edges) per vertice*/
+ float *vweights; /* Total sum of weights per vertice*/
+ int numEdges; /* Number of edges*/
+ int numFaces; /* Number of faces*/
+ int numVerts; /* Number of verts*/
+ short *zerola; /* Is zero area or length*/
+
+ /* Pointers to data*/
+ BMesh *bm;
+ BMOperator *op;
+ NLContext *context;
+
+ /*Data*/
+ float min_area;
+};
+typedef struct BLaplacianSystem LaplacianSystem;
+
+static float compute_volume(BMesh *bm);
+static float cotan_weight(float *v1, float *v2, float *v3);
+static int vert_is_boundary(BMVert *v);
+static LaplacianSystem *init_laplacian_system(int a_numEdges, int a_numFaces, int a_numVerts);
+static void init_laplacian_matrix(LaplacianSystem *sys);
+static void delete_laplacian_system(LaplacianSystem *sys);
+static void delete_void_pointer(void *data);
+static void fill_laplacian_matrix(LaplacianSystem *sys);
+static void memset_laplacian_system(LaplacianSystem *sys, int val);
+static void validate_solution(LaplacianSystem *sys, int usex, int usey, int usez, int volumepreservation);
+static void volume_preservation(BMesh *bm, BMOperator *op, float vini, float vend, int usex, int usey, int usez);
+
+static void delete_void_pointer(void *data)
+{
+ if (data) {
+ MEM_freeN(data);
+ data = NULL;
+ }
+}
+
+static void delete_laplacian_system(LaplacianSystem *sys)
+{
+ delete_void_pointer(sys->eweights);
+ delete_void_pointer(sys->fweights);
+ delete_void_pointer(sys->ring_areas);
+ delete_void_pointer(sys->vlengths);
+ delete_void_pointer(sys->vweights);
+ delete_void_pointer(sys->zerola);
+ if (sys->context) {
+ nlDeleteContext(sys->context);
+ }
+ sys->bm = NULL;
+ sys->op = NULL;
+ MEM_freeN(sys);
+}
+
+static void memset_laplacian_system(LaplacianSystem *sys, int val)
+{
+ memset(sys->eweights, val, sizeof(float) * sys->numEdges);
+ memset(sys->fweights, val, sizeof(float) * sys->numFaces * 3);
+ memset(sys->ring_areas, val, sizeof(float) * sys->numVerts);
+ memset(sys->vlengths, val, sizeof(float) * sys->numVerts);
+ memset(sys->vweights, val, sizeof(float) * sys->numVerts);
+ memset(sys->zerola, val, sizeof(short) * sys->numVerts);
+}
+
+static LaplacianSystem *init_laplacian_system(int a_numEdges, int a_numFaces, int a_numVerts)
+{
+ LaplacianSystem *sys;
+ sys = MEM_callocN(sizeof(LaplacianSystem), "ModLaplSmoothSystem");
+ sys->numEdges = a_numEdges;
+ sys->numFaces = a_numFaces;
+ sys->numVerts = a_numVerts;
+
+ sys->eweights = MEM_callocN(sizeof(float) * sys->numEdges, "ModLaplSmoothEWeight");
+ if (!sys->eweights) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->fweights = MEM_callocN(sizeof(float) * 3 * sys->numFaces, "ModLaplSmoothFWeight");
+ if (!sys->fweights) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->ring_areas = MEM_callocN(sizeof(float) * sys->numVerts, "ModLaplSmoothRingAreas");
+ if (!sys->ring_areas) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->vlengths = MEM_callocN(sizeof(float) * sys->numVerts, "ModLaplSmoothVlengths");
+ if (!sys->vlengths) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->vweights = MEM_callocN(sizeof(float) * sys->numVerts, "ModLaplSmoothVweights");
+ if (!sys->vweights) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->zerola = MEM_callocN(sizeof(short) * sys->numVerts, "ModLaplSmoothZeloa");
+ if (!sys->zerola) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ return sys;
+}
+
+/* Compute weigth between vertice v_i and all your neighbors
+ * weight between v_i and v_neighbor
+ * Wij = cot(alpha) + cot(beta) / (4.0 * total area of all faces * sum all weight)
+ * v_i *
+ * / | \
+ * / | \
+ * v_beta* | * v_alpha
+ * \ | /
+ * \ | /
+ * * v_neighbor
+ */
+
+static void init_laplacian_matrix(LaplacianSystem *sys)
+{
+ float areaf;
+ float *v1, *v2, *v3, *v4;
+ float w1, w2, w3, w4;
+ int i, j;
+ int has_4_vert;
+ unsigned int idv1, idv2, idv3, idv4, idv[4];
+ BMEdge *e;
+ BMFace *f;
+ BMIter eiter;
+ BMIter fiter;
+ BMIter vi;
+ BMVert *vn;
+ BMVert *vf[4];
+
+ BM_ITER_MESH_INDEX (e, &eiter, sys->bm, BM_EDGES_OF_MESH, j) {
+ if (!BM_elem_flag_test(e, BM_ELEM_SELECT) && BM_edge_is_boundary(e)) {
+ v1 = e->v1->co;
+ v2 = e->v2->co;
+ idv1 = BM_elem_index_get(e->v1);
+ idv2 = BM_elem_index_get(e->v2);
+
+ w1 = len_v3v3(v1, v2);
+ if (w1 > sys->min_area) {
+ w1 = 1.0f / w1;
+ i = BM_elem_index_get(e);
+ sys->eweights[i] = w1;
+ sys->vlengths[idv1] += w1;
+ sys->vlengths[idv2] += w1;
+ }
+ else {
+ sys->zerola[idv1] = 1;
+ sys->zerola[idv2] = 1;
+ }
+ }
+ }
+
+ BM_ITER_MESH (f, &fiter, sys->bm, BM_FACES_OF_MESH) {
+ if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
+
+ BM_ITER_ELEM_INDEX (vn, &vi, f, BM_VERTS_OF_FACE, i) {
+ vf[i] = vn;
+ }
+ has_4_vert = (i == 4) ? 1 : 0;
+ idv1 = BM_elem_index_get(vf[0]);
+ idv2 = BM_elem_index_get(vf[1]);
+ idv3 = BM_elem_index_get(vf[2]);
+ idv4 = has_4_vert ? BM_elem_index_get(vf[3]) : 0;
+
+ v1 = vf[0]->co;
+ v2 = vf[1]->co;
+ v3 = vf[2]->co;
+ v4 = has_4_vert ? vf[3]->co : 0;
+
+ if (has_4_vert) {
+ areaf = area_quad_v3(v1, v2, v3, v4);
+ }
+ else {
+ areaf = area_tri_v3(v1, v2, v3);
+ }
+
+ if (fabsf(areaf) < sys->min_area) {
+ sys->zerola[idv1] = 1;
+ sys->zerola[idv2] = 1;
+ sys->zerola[idv3] = 1;
+ if (has_4_vert) sys->zerola[idv4] = 1;
+ }
+
+ sys->ring_areas[idv1] += areaf;
+ sys->ring_areas[idv2] += areaf;
+ sys->ring_areas[idv3] += areaf;
+ if (has_4_vert) sys->ring_areas[idv4] += areaf;
+
+ if (has_4_vert) {
+
+ idv[0] = idv1;
+ idv[1] = idv2;
+ idv[2] = idv3;
+ idv[3] = idv4;
+
+ for (j = 0; j < 4; j++) {
+ idv1 = idv[j];
+ idv2 = idv[(j + 1) % 4];
+ idv3 = idv[(j + 2) % 4];
+ idv4 = idv[(j + 3) % 4];
+
+ v1 = vf[j]->co;
+ v2 = vf[(j + 1) % 4]->co;
+ v3 = vf[(j + 2) % 4]->co;
+ v4 = vf[(j + 3) % 4]->co;
+
+ w2 = cotan_weight(v4, v1, v2) + cotan_weight(v3, v1, v2);
+ w3 = cotan_weight(v2, v3, v1) + cotan_weight(v4, v1, v3);
+ w4 = cotan_weight(v2, v4, v1) + cotan_weight(v3, v4, v1);
+
+ sys->vweights[idv1] += (w2 + w3 + w4) / 4.0f;
+ }
+ }
+ else {
+ i = BM_elem_index_get(f);
+
+ w1 = cotan_weight(v1, v2, v3);
+ w2 = cotan_weight(v2, v3, v1);
+ w3 = cotan_weight(v3, v1, v2);
+
+ sys->fweights[i][0] += w1;
+ sys->fweights[i][1] += w2;
+ sys->fweights[i][2] += w3;
+
+ sys->vweights[idv1] += w2 + w3;
+ sys->vweights[idv2] += w1 + w3;
+ sys->vweights[idv3] += w1 + w2;
+ }
+ }
+ }
+}
+
+static void fill_laplacian_matrix(LaplacianSystem *sys)
+{
+ float *v1, *v2, *v3, *v4;
+ float w2, w3, w4;
+ int i, j;
+ int has_4_vert;
+ unsigned int idv1, idv2, idv3, idv4, idv[4];
+
+ BMEdge *e;
+ BMFace *f;
+ BMIter eiter;
+ BMIter fiter;
+ BMIter vi;
+ BMVert *vn;
+ BMVert *vf[4];
+
+ BM_ITER_MESH (f, &fiter, sys->bm, BM_FACES_OF_MESH) {
+ if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
+ BM_ITER_ELEM_INDEX (vn, &vi, f, BM_VERTS_OF_FACE, i) {
+ vf[i] = vn;
+ }
+ has_4_vert = (i == 4) ? 1 : 0;
+ if (has_4_vert) {
+ idv[0] = BM_elem_index_get(vf[0]);
+ idv[1] = BM_elem_index_get(vf[1]);
+ idv[2] = BM_elem_index_get(vf[2]);
+ idv[3] = BM_elem_index_get(vf[3]);
+ for (j = 0; j < 4; j++) {
+ idv1 = idv[j];
+ idv2 = idv[(j + 1) % 4];
+ idv3 = idv[(j + 2) % 4];
+ idv4 = idv[(j + 3) % 4];
+
+ v1 = vf[j]->co;
+ v2 = vf[(j + 1) % 4]->co;
+ v3 = vf[(j + 2) % 4]->co;
+ v4 = vf[(j + 3) % 4]->co;
+
+ w2 = cotan_weight(v4, v1, v2) + cotan_weight(v3, v1, v2);
+ w3 = cotan_weight(v2, v3, v1) + cotan_weight(v4, v1, v3);
+ w4 = cotan_weight(v2, v4, v1) + cotan_weight(v3, v4, v1);
+
+ w2 = w2 / 4.0f;
+ w3 = w3 / 4.0f;
+ w4 = w4 / 4.0f;
+
+ if (!vert_is_boundary(vf[j]) && sys->zerola[idv1] == 0) {
+ nlMatrixAdd(idv1, idv2, w2 * sys->vweights[idv1]);
+ nlMatrixAdd(idv1, idv3, w3 * sys->vweights[idv1]);
+ nlMatrixAdd(idv1, idv4, w4 * sys->vweights[idv1]);
+ }
+ }
+ }
+ else {
+ idv1 = BM_elem_index_get(vf[0]);
+ idv2 = BM_elem_index_get(vf[1]);
+ idv3 = BM_elem_index_get(vf[2]);
+ /* Is ring if number of faces == number of edges around vertice*/
+ i = BM_elem_index_get(f);
+ if (!vert_is_boundary(vf[0]) && sys->zerola[idv1] == 0) {
+ nlMatrixAdd(idv1, idv2, sys->fweights[i][2] * sys->vweights[idv1]);
+ nlMatrixAdd(idv1, idv3, sys->fweights[i][1] * sys->vweights[idv1]);
+ }
+ if (!vert_is_boundary(vf[1]) && sys->zerola[idv2] == 0) {
+ nlMatrixAdd(idv2, idv1, sys->fweights[i][2] * sys->vweights[idv2]);
+ nlMatrixAdd(idv2, idv3, sys->fweights[i][0] * sys->vweights[idv2]);
+ }
+ if (!vert_is_boundary(vf[2]) && sys->zerola[idv3] == 0) {
+ nlMatrixAdd(idv3, idv1, sys->fweights[i][1] * sys->vweights[idv3]);
+ nlMatrixAdd(idv3, idv2, sys->fweights[i][0] * sys->vweights[idv3]);
+ }
+ }
+ }
+ }
+ BM_ITER_MESH (e, &eiter, sys->bm, BM_EDGES_OF_MESH) {
+ if (!BM_elem_flag_test(e, BM_ELEM_SELECT) && BM_edge_is_boundary(e) ) {
+ v1 = e->v1->co;
+ v2 = e->v2->co;
+ idv1 = BM_elem_index_get(e->v1);
+ idv2 = BM_elem_index_get(e->v2);
+ if (sys->zerola[idv1] == 0 && sys->zerola[idv2] == 0) {
+ i = BM_elem_index_get(e);
+ nlMatrixAdd(idv1, idv2, sys->eweights[i] * sys->vlengths[idv1]);
+ nlMatrixAdd(idv2, idv1, sys->eweights[i] * sys->vlengths[idv2]);
+ }
+ }
+ }
+}
+
+static float cotan_weight(float *v1, float *v2, float *v3)
+{
+ float a[3], b[3], c[3], clen;
+
+ sub_v3_v3v3(a, v2, v1);
+ sub_v3_v3v3(b, v3, v1);
+ cross_v3_v3v3(c, a, b);
+
+ clen = len_v3(c);
+
+ if (clen == 0.0f)
+ return 0.0f;
+
+ return dot_v3v3(a, b) / clen;
+}
+
+static int vert_is_boundary(BMVert *v)
+{
+ BMEdge *ed;
+ BMFace *f;
+ BMIter ei;
+ BMIter fi;
+ BM_ITER_ELEM (ed, &ei, v, BM_EDGES_OF_VERT) {
+ if (BM_edge_is_boundary(ed)) {
+ return 1;
+ }
+ }
+ BM_ITER_ELEM (f, &fi, v, BM_FACES_OF_VERT) {
+ if (!BM_elem_flag_test(f, BM_ELEM_SELECT)) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static float compute_volume(BMesh *bm)
+{
+ float vol = 0.0f;
+ float x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4;
+ int i;
+ BMFace *f;
+ BMIter fiter;
+ BMIter vi;
+ BMVert *vn;
+ BMVert *vf[4];
+
+ BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
+ BM_ITER_ELEM_INDEX (vn, &vi, f, BM_VERTS_OF_FACE, i) {
+ vf[i] = vn;
+ }
+ x1 = vf[0]->co[0];
+ y1 = vf[0]->co[1];
+ z1 = vf[0]->co[2];
+
+ x2 = vf[1]->co[0];
+ y2 = vf[1]->co[1];
+ z2 = vf[1]->co[2];
+
+ x3 = vf[2]->co[0];
+ y3 = vf[2]->co[1];
+ z3 = vf[2]->co[2];
+
+ vol += (1.0f / 6.0f) * (0.0f - x3 * y2 * z1 + x2 * y3 * z1 + x3 * y1 * z2 - x1 * y3 * z2 - x2 * y1 * z3 + x1 * y2 * z3);
+
+ if (i == 4) {
+ x4 = vf[3]->co[0];
+ y4 = vf[3]->co[1];
+ z4 = vf[3]->co[2];
+ vol += (1.0f / 6.0f) * (x1 * y3 * z4 - x1 * y4 * z3 - x3 * y1 * z4 + x3 * z1 * y4 + y1 * x4 * z3 - x4 * y3 * z1);
+ }
+ }
+ return fabs(vol);
+}
+
+static void volume_preservation(BMesh *bm, BMOperator *op, float vini, float vend, int usex, int usey, int usez)
+{
+ float beta;
+ BMOIter siter;
+ BMVert *v;
+
+ if (vend != 0.0f) {
+ beta = pow(vini / vend, 1.0f / 3.0f);
+ BMO_ITER (v, &siter, bm, op, "verts", BM_VERT) {
+ if (usex) {
+ v->co[0] *= beta;
+ }
+ if (usey) {
+ v->co[1] *= beta;
+ }
+ if (usez) {
+ v->co[2] *= beta;
+ }
+
+ }
+ }
+}
+
+static void validate_solution(LaplacianSystem *sys, int usex, int usey, int usez, int volumepreservation)
+{
+ int m_vertex_id;
+ float leni, lene;
+ float vini, vend;
+ float *vi1, *vi2, ve1[3], ve2[3];
+ unsigned int idv1, idv2;
+ BMOIter siter;
+ BMVert *v;
+ BMEdge *e;
+ BMIter eiter;
+
+ BM_ITER_MESH (e, &eiter, sys->bm, BM_EDGES_OF_MESH) {
+ idv1 = BM_elem_index_get(e->v1);
+ idv2 = BM_elem_index_get(e->v2);
+ vi1 = e->v1->co;
+ vi2 = e->v2->co;
+ ve1[0] = nlGetVariable(0, idv1);
+ ve1[1] = nlGetVariable(1, idv1);
+ ve1[2] = nlGetVariable(2, idv1);
+ ve2[0] = nlGetVariable(0, idv2);
+ ve2[1] = nlGetVariable(1, idv2);
+ ve2[2] = nlGetVariable(2, idv2);
+ leni = len_v3v3(vi1, vi2);
+ lene = len_v3v3(ve1, ve2);
+ if (lene > leni * SMOOTH_LAPLACIAN_MAX_EDGE_PERCENTAGE || lene < leni * SMOOTH_LAPLACIAN_MIN_EDGE_PERCENTAGE) {
+ sys->zerola[idv1] = 1;
+ sys->zerola[idv2] = 1;
+ }
+ }
+
+ if (volumepreservation) {
+ vini = compute_volume(sys->bm);
+ }
+ BMO_ITER (v, &siter, sys->bm, sys->op, "verts", BM_VERT) {
+ m_vertex_id = BM_elem_index_get(v);
+ if (sys->zerola[m_vertex_id] == 0) {
+ if (usex) {
+ v->co[0] = nlGetVariable(0, m_vertex_id);
+ }
+ if (usey) {
+ v->co[1] = nlGetVariable(1, m_vertex_id);
+ }
+ if (usez) {
+ v->co[2] = nlGetVariable(2, m_vertex_id);
+ }
+ }
+ }
+ if (volumepreservation) {
+ vend = compute_volume(sys->bm);
+ volume_preservation(sys->bm, sys->op, vini, vend, usex, usey, usez);
+ }
+
+}
+
+void bmo_smooth_laplacian_vert_exec(BMesh *bm, BMOperator *op)
+{
+ int i;
+ int m_vertex_id;
+ int usex, usey, usez, volumepreservation;
+ float lambda, lambda_border;
+ float w;
+ BMOIter siter;
+ BMVert *v;
+ LaplacianSystem *sys;
+
+ sys = init_laplacian_system(bm->totedge, bm->totface, bm->totvert);
+ if (!sys) return;
+ sys->bm = bm;
+ sys->op = op;
+
+ memset_laplacian_system(sys, 0);
+
+ BM_mesh_elem_index_ensure(bm, BM_VERT);
+ lambda = BMO_slot_float_get(op, "lambda");
+ lambda_border = BMO_slot_float_get(op, "lambda_border");
+ sys->min_area = 0.00001f;
+ usex = BMO_slot_bool_get(op, "use_x");
+ usey = BMO_slot_bool_get(op, "use_y");
+ usez = BMO_slot_bool_get(op, "use_z");
+ volumepreservation = BMO_slot_bool_get(op, "volume_preservation");
+
+
+ nlNewContext();
+ sys->context = nlGetCurrent();
+
+ nlSolverParameteri(NL_NB_VARIABLES, bm->totvert);
+ nlSolverParameteri(NL_LEAST_SQUARES, NL_TRUE);
+ nlSolverParameteri(NL_NB_ROWS, bm->totvert);
+ nlSolverParameteri(NL_NB_RIGHT_HAND_SIDES, 3);
+
+ nlBegin(NL_SYSTEM);
+ for (i = 0; i < bm->totvert; i++) {
+ nlLockVariable(i);
+ }
+ BMO_ITER (v, &siter, bm, op, "verts", BM_VERT) {
+ m_vertex_id = BM_elem_index_get(v);
+ nlUnlockVariable(m_vertex_id);
+ nlSetVariable(0, m_vertex_id, v->co[0]);
+ nlSetVariable(1, m_vertex_id, v->co[1]);
+ nlSetVariable(2, m_vertex_id, v->co[2]);
+ }
+
+ nlBegin(NL_MATRIX);
+ init_laplacian_matrix(sys);
+ BMO_ITER (v, &siter, bm, op, "verts", BM_VERT) {
+ m_vertex_id = BM_elem_index_get(v);
+ nlRightHandSideAdd(0, m_vertex_id, v->co[0]);
+ nlRightHandSideAdd(1, m_vertex_id, v->co[1]);
+ nlRightHandSideAdd(2, m_vertex_id, v->co[2]);
+ i = m_vertex_id;
+ if (sys->zerola[i] == 0) {
+ w = sys->vweights[i] * sys->ring_areas[i];
+ sys->vweights[i] = (w == 0.0f) ? 0.0f : -lambda / (4.0f * w);
+ w = sys->vlengths[i];
+ sys->vlengths[i] = (w == 0.0f) ? 0.0f : -lambda_border * 2.0f / w;
+
+ if (!vert_is_boundary(v)) {
+ nlMatrixAdd(i, i, 1.0f + lambda / (4.0f * sys->ring_areas[i]));
+ }
+ else {
+ nlMatrixAdd(i, i, 1.0f + lambda_border * 2.0f);
+ }
+ }
+ else {
+ nlMatrixAdd(i, i, 1.0f);
+ }
+ }
+ fill_laplacian_matrix(sys);
+
+ nlEnd(NL_MATRIX);
+ nlEnd(NL_SYSTEM);
+
+ if (nlSolveAdvanced(NULL, NL_TRUE) ) {
+ validate_solution(sys, usex, usey, usez, volumepreservation);
+ }
+
+ delete_laplacian_system(sys);
+}
diff --git a/source/blender/bmesh/operators/bmo_subdivide.c b/source/blender/bmesh/operators/bmo_subdivide.c
index b239be1c83b..346daf830d0 100644
--- a/source/blender/bmesh/operators/bmo_subdivide.c
+++ b/source/blender/bmesh/operators/bmo_subdivide.c
@@ -53,6 +53,9 @@
#define ELE_INNER 8
#define ELE_SPLIT 16
+/* see bug [#32665], 0.00005 means a we get face splits at a little under 1.0 degrees */
+#define FLT_FACE_SPLIT_EPSILON 0.00005f
+
/*
* NOTE: beauty has been renamed to flag!
*/
@@ -823,16 +826,12 @@ void bmo_subdivide_edges_exec(BMesh *bm, BMOperator *op)
/* make sure the two edges have a valid angle to each other */
if (totesel == 2 && BM_edge_share_vert_count(e1, e2)) {
- float angle;
-
sub_v3_v3v3(vec1, e1->v2->co, e1->v1->co);
sub_v3_v3v3(vec2, e2->v2->co, e2->v1->co);
normalize_v3(vec1);
normalize_v3(vec2);
- angle = dot_v3v3(vec1, vec2);
- angle = fabsf(angle);
- if (fabsf(angle - 1.0f) < 0.01f) {
+ if (fabsf(dot_v3v3(vec1, vec2)) > 1.0f - FLT_FACE_SPLIT_EPSILON) {
totesel = 0;
}
}
@@ -983,7 +982,7 @@ void bmo_subdivide_edges_exec(BMesh *bm, BMOperator *op)
* This edge pair could be used by more then one face,
* in this case it used to (2.63), split both faces along the same verts
* while it could be calculated which face should do the split,
- * its ambigious, so in this case we're better off to skip them as exceptional cases
+ * it's ambiguous, so in this case we're better off to skip them as exceptional cases
* and not try to be clever guessing which face to cut up.
*
* To avoid this case we need to check:
diff --git a/source/blender/bmesh/operators/bmo_symmetrize.c b/source/blender/bmesh/operators/bmo_symmetrize.c
new file mode 100644
index 00000000000..a428405fb8b
--- /dev/null
+++ b/source/blender/bmesh/operators/bmo_symmetrize.c
@@ -0,0 +1,663 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Nicholas Bishop
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_array.h"
+#include "BLI_math.h"
+#include "BLI_utildefines.h"
+
+#include "bmesh.h"
+#include "intern/bmesh_operators_private.h"
+
+enum {
+ SYMM_OUTPUT_GEOM = (1 << 0)
+};
+
+/* Note: don't think there's much need to make these user-adjustable? */
+#define SYMM_AXIS_THRESHOLD 0.00002f
+#define SYMM_VERT_THRESHOLD 0.00002f
+
+typedef enum {
+ /* Coordinate lies on the side being copied from */
+ SYMM_SIDE_KEEP,
+ /* Coordinate lies on the side being copied from and within the
+ * axis threshold */
+ SYMM_SIDE_AXIS,
+ /* Coordinate lies on the side being copied to */
+ SYMM_SIDE_KILL
+} SymmSide;
+
+typedef struct {
+ BMesh *bm;
+ BMOperator *op;
+
+ int axis;
+ BMO_SymmDirection direction;
+
+ /* Maps from input vertices to their mirrors. If the vertex
+ * doesn't have a mirror, it's not in this map. If the vertex is
+ * within the axis threshold, it's mapped to itself. */
+ GHash *vert_symm_map;
+
+ /* Edges that cross the symmetry plane and are asymmetric get
+ * split. This map goes from input edges to output vertices. If an
+ * edge is not split, it's not in this map. */
+ GHash *edge_split_map;
+} Symm;
+
+/* Return which side the coordinate lies on */
+static SymmSide symm_co_side(const Symm *symm,
+ const float *co)
+{
+ float comp = co[symm->axis];
+ if (ELEM3(symm->direction,
+ BMO_SYMMETRIZE_NEGATIVE_X,
+ BMO_SYMMETRIZE_NEGATIVE_Y,
+ BMO_SYMMETRIZE_NEGATIVE_Z))
+ {
+ comp = -comp;
+ }
+
+ if (comp >= 0) {
+ if (comp < SYMM_AXIS_THRESHOLD)
+ return SYMM_SIDE_AXIS;
+ else
+ return SYMM_SIDE_KEEP;
+ }
+ else
+ return SYMM_SIDE_KILL;
+}
+
+/* Output vertices and the vert_map array */
+static void symm_verts_mirror(Symm *symm)
+{
+ BMOIter oiter;
+ BMVert *src_v, *dst_v;
+
+ symm->vert_symm_map = BLI_ghash_ptr_new(AT);
+
+ BMO_ITER (src_v, &oiter, symm->bm, symm->op, "input", BM_VERT) {
+ SymmSide side = symm_co_side(symm, src_v->co);
+ float co[3];
+
+ switch (side) {
+ case SYMM_SIDE_KEEP:
+ /* The vertex is outside the axis area; output its mirror */
+ copy_v3_v3(co, src_v->co);
+ co[symm->axis] = -co[symm->axis];
+
+ dst_v = BM_vert_create(symm->bm, co, src_v);
+ BMO_elem_flag_enable(symm->bm, dst_v, SYMM_OUTPUT_GEOM);
+ BLI_ghash_insert(symm->vert_symm_map, src_v, dst_v);
+ break;
+
+ case SYMM_SIDE_AXIS:
+ /* The vertex is within the axis area, snap to center */
+ src_v->co[symm->axis] = 0;
+ /* Vertex isn't copied, map to itself */
+ BLI_ghash_insert(symm->vert_symm_map, src_v, src_v);
+ break;
+
+ case SYMM_SIDE_KILL:
+ /* The vertex does not lie in the half-space being
+ * copied from, nothing to do */
+ break;
+ }
+ }
+}
+
+static int symm_edge_crosses_axis(const Symm *symm, const BMEdge *e)
+{
+ const int sides[2] = {symm_co_side(symm, e->v1->co),
+ symm_co_side(symm, e->v2->co)};
+
+ return ((sides[0] != SYMM_SIDE_AXIS) &&
+ (sides[1] != SYMM_SIDE_AXIS) &&
+ (sides[0] != sides[1]));
+}
+
+/* Output edge split vertices for asymmetric edges and the edge_splits
+ * mapping array */
+static void symm_split_asymmetric_edges(Symm *symm)
+{
+ BMOIter oiter;
+ BMEdge *e;
+
+ symm->edge_split_map = BLI_ghash_ptr_new(AT);
+
+ BMO_ITER (e, &oiter, symm->bm, symm->op, "input", BM_EDGE) {
+ float flipped[3];
+
+ copy_v3_v3(flipped, e->v1->co);
+ flipped[symm->axis] = -flipped[symm->axis];
+
+ if (symm_edge_crosses_axis(symm, e) &&
+ (!compare_v3v3(e->v2->co, flipped, SYMM_VERT_THRESHOLD)))
+ {
+ /* Endpoints lie on opposite sides and are asymmetric */
+
+ BMVert *v;
+ float lambda = 0, edge_dir[3], co[3];
+ float plane_co[3][3][3] = {
+ /* axis == 0 */
+ {{0, 0, 0}, {0, 1, 0}, {0, 0, 1}},
+ /* axis == 1 */
+ {{0, 0, 0}, {1, 0, 0}, {0, 0, 1}},
+ /* axis == 2 */
+ {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}},
+ };
+ int r;
+
+ /* Find intersection of edge with symmetry plane */
+ sub_v3_v3v3(edge_dir, e->v2->co, e->v1->co);
+ normalize_v3(edge_dir);
+ r = isect_ray_plane_v3(e->v1->co,
+ edge_dir,
+ plane_co[symm->axis][0],
+ plane_co[symm->axis][1],
+ plane_co[symm->axis][2],
+ &lambda, TRUE);
+ BLI_assert(r);
+
+ madd_v3_v3v3fl(co, e->v1->co, edge_dir, lambda);
+ co[symm->axis] = 0;
+
+ /* Edge is asymmetric, split it with a new vertex */
+ v = BM_vert_create(symm->bm, co, e->v1);
+ BMO_elem_flag_enable(symm->bm, v, SYMM_OUTPUT_GEOM);
+ BLI_ghash_insert(symm->edge_split_map, e, v);
+ }
+ }
+}
+
+static void symm_mirror_edges(Symm *symm)
+{
+ BMOIter oiter;
+ BMEdge *e;
+
+ BMO_ITER (e, &oiter, symm->bm, symm->op, "input", BM_EDGE) {
+ BMVert *v1 = NULL, *v2 = NULL;
+ BMEdge *e_new;
+
+ v1 = BLI_ghash_lookup(symm->vert_symm_map, e->v1);
+ v2 = BLI_ghash_lookup(symm->vert_symm_map, e->v2);
+
+ if (v1 && v2) {
+ e_new = BM_edge_create(symm->bm, v1, v2, e, TRUE);
+ BMO_elem_flag_enable(symm->bm, e_new, SYMM_OUTPUT_GEOM);
+ }
+ else if (v1 || v2) {
+ if (BLI_ghash_haskey(symm->edge_split_map, e)) {
+ BMVert *v_split = BLI_ghash_lookup(symm->edge_split_map, e);
+
+ /* Output the keep side of the split edge */
+ if (!v1) {
+ e_new = BM_edge_create(symm->bm, v_split, e->v2, e, TRUE);
+ BMO_elem_flag_enable(symm->bm, e_new, SYMM_OUTPUT_GEOM);
+ v1 = v_split;
+ }
+ else {
+ e_new = BM_edge_create(symm->bm, e->v1, v_split, e, TRUE);
+ BMO_elem_flag_enable(symm->bm, e_new, SYMM_OUTPUT_GEOM);
+ v2 = v_split;
+ }
+
+ /* Output the kill side of the split edge */
+ e_new = BM_edge_create(symm->bm, v1, v2, e, TRUE);
+ BMO_elem_flag_enable(symm->bm, e_new, SYMM_OUTPUT_GEOM);
+ }
+ }
+ }
+}
+
+/****************************** SymmPoly ******************************/
+
+typedef struct {
+ /* Indices into the source mvert array (or -1 if not in that array) */
+ BMVert **src_verts;
+ /* Indices into the destination mvert array, these are vertices
+ * created by an edge split (-1 for vertices not created by edge
+ * split) */
+ BMVert **edge_verts;
+
+ /* Number of vertices in the polygon */
+ int len;
+
+ /* True only if none of the polygon's edges were split */
+ int already_symmetric;
+} SymmPoly;
+
+static void symm_poly_with_splits(const Symm *symm,
+ BMFace *f,
+ SymmPoly *out)
+{
+ BMIter iter;
+ BMLoop *l;
+ int i;
+
+ /* Count vertices and check for edge splits */
+ out->len = f->len;
+ out->already_symmetric = TRUE;
+ BM_ITER_ELEM (l, &iter, f, BM_LOOPS_OF_FACE) {
+ if (BLI_ghash_haskey(symm->edge_split_map, l->e)) {
+ out->len++;
+ out->already_symmetric = FALSE;
+ }
+ }
+
+ i = 0;
+ BM_ITER_ELEM (l, &iter, f, BM_LOOPS_OF_FACE) {
+ BMVert *split = BLI_ghash_lookup(symm->edge_split_map, l->e);
+
+ out->src_verts[i] = l->v;
+ out->edge_verts[i] = NULL;
+ i++;
+
+ if (split) {
+ out->src_verts[i] = NULL;
+ out->edge_verts[i] = split;
+ i++;
+ }
+ }
+}
+
+static const float *symm_poly_co(const SymmPoly *sp, int v)
+{
+ if (sp->src_verts[v])
+ return sp->src_verts[v]->co;
+ else if (sp->edge_verts[v])
+ return sp->edge_verts[v]->co;
+ else
+ return NULL;
+}
+
+static SymmSide symm_poly_co_side(const Symm *symm,
+ const SymmPoly *sp,
+ int v)
+{
+ return symm_co_side(symm, symm_poly_co(sp, v));
+}
+
+/* Return the index of the vertex in the destination array at corner
+ * 'v' of the polygon, or -1 if not in that array */
+static BMVert *symm_poly_dst(const SymmPoly *sp, int v)
+{
+ if (sp->edge_verts[v])
+ return sp->edge_verts[v];
+ else if (sp->src_verts[v])
+ return sp->src_verts[v];
+ else
+ return NULL;
+}
+
+/* Same as above, but returns the index of the mirror if available, or
+ * the same index if on the axis, or -1 otherwise */
+static BMVert *symm_poly_mirror_dst(const Symm *symm,
+ const SymmPoly *sp,
+ int v)
+{
+ if (sp->edge_verts[v])
+ return sp->edge_verts[v];
+ else if (sp->src_verts[v]) {
+ if (BLI_ghash_haskey(symm->vert_symm_map, sp->src_verts[v]))
+ return BLI_ghash_lookup(symm->vert_symm_map, sp->src_verts[v]);
+ else
+ return sp->src_verts[v];
+ }
+ else
+ return NULL;
+}
+
+static int symm_poly_next_crossing(const Symm *symm,
+ const SymmPoly *sp,
+ int start,
+ int *l1,
+ int *l2)
+{
+ int i;
+
+ for (i = 0; i < sp->len; i++) {
+ (*l1) = (start + i) % sp->len;
+ (*l2) = ((*l1) + 1) % sp->len;
+
+ if ((symm_poly_co_side(symm, sp, *l1) == SYMM_SIDE_KILL) ^
+ (symm_poly_co_side(symm, sp, *l2) == SYMM_SIDE_KILL))
+ {
+ return TRUE;
+ }
+ }
+
+ BLI_assert(!"symm_poly_next_crossing failed");
+ return FALSE;
+}
+
+static BMFace *symm_face_create_v(BMesh *bm, BMVert **fv, BMEdge **fe, int len)
+{
+ BMFace *f_new;
+ int i;
+
+ for (i = 0; i < len; i++) {
+ int j = (i + 1) % len;
+ fe[i] = BM_edge_exists(fv[i], fv[j]);
+ if (!fe[i]) {
+ fe[i] = BM_edge_create(bm, fv[i], fv[j], NULL, FALSE);
+ BMO_elem_flag_enable(bm, fe[i], SYMM_OUTPUT_GEOM);
+ }
+ }
+ f_new = BM_face_create(bm, fv, fe, len, TRUE);
+ BM_face_select_set(bm, f_new, TRUE);
+ BMO_elem_flag_enable(bm, f_new, SYMM_OUTPUT_GEOM);
+ return f_new;
+}
+
+static void symm_mesh_output_poly_zero_splits(Symm *symm,
+ SymmPoly *sp,
+ BMVert **fv,
+ BMEdge **fe,
+ int segment_len,
+ int start)
+{
+ int i, j;
+
+ j = 0;
+
+ /* Output the keep side of the input polygon */
+ for (i = 0; i < segment_len; i++) {
+ const int offset = (start + i) % sp->len;
+ BLI_assert(sp->src_verts[offset]);
+ fv[j++] = sp->src_verts[offset];
+ }
+
+ /* Output the kill side of the polygon */
+ for (i = segment_len - 1; i >= 0; i--) {
+ const int offset = (start + i) % sp->len;
+
+ if (symm_poly_co_side(symm, sp, offset) == SYMM_SIDE_KEEP) {
+ BLI_assert(sp->src_verts[offset]);
+ fv[j++] = BLI_ghash_lookup(symm->vert_symm_map,
+ sp->src_verts[offset]);
+ }
+ }
+
+ symm_face_create_v(symm->bm, fv, fe, j);
+}
+
+static void symm_mesh_output_poly_with_splits(Symm *symm,
+ SymmPoly *sp,
+ BMVert **fv,
+ BMEdge **fe,
+ int segment_len,
+ int start)
+{
+ int i;
+
+ /* Output the keep side of the input polygon */
+
+ for (i = 0; i < segment_len; i++) {
+ const int offset = (start + i) % sp->len;
+ BMVert *v = symm_poly_dst(sp, offset);
+
+ BLI_assert(v);
+
+ fv[i] = v;
+ }
+
+ symm_face_create_v(symm->bm, fv, fe, segment_len);
+
+ /* Output the kill side of the input polygon */
+
+ for (i = 0; i < segment_len; i++) {
+ const int offset = (start + i) % sp->len;
+ BMVert *v = symm_poly_mirror_dst(symm, sp, offset);
+
+ fv[segment_len - i - 1] = v;
+
+ }
+
+ symm_face_create_v(symm->bm, fv, fe, segment_len);
+}
+
+static void symm_mirror_polygons(Symm *symm)
+{
+ BMOIter oiter;
+ BMFace *f;
+ BMVert **pv = NULL;
+ BMVert **fv = NULL;
+ BMEdge **fe = NULL;
+ BLI_array_declare(pv);
+ BLI_array_declare(fv);
+ BLI_array_declare(fe);
+
+ BMO_ITER (f, &oiter, symm->bm, symm->op, "input", BM_FACE) {
+ BMIter iter;
+ BMLoop *l;
+ int mirror_all = TRUE, ignore_all = TRUE;
+
+ /* Check if entire polygon can be mirrored or ignored */
+ BM_ITER_ELEM (l, &iter, f, BM_LOOPS_OF_FACE) {
+ const SymmSide side = symm_co_side(symm, l->v->co);
+ if (side == SYMM_SIDE_KILL)
+ mirror_all = FALSE;
+ else if (side == SYMM_SIDE_KEEP)
+ ignore_all = FALSE;
+ }
+
+ if (mirror_all) {
+ int i;
+
+ /* Make a mirrored copy of the polygon */
+
+ BLI_array_empty(fv);
+ BLI_array_empty(fe);
+ BLI_array_grow_items(fv, f->len);
+ BLI_array_grow_items(fe, f->len);
+
+ i = f->len;
+ BM_ITER_ELEM (l, &iter, f, BM_LOOPS_OF_FACE) {
+ i--;
+
+ if (symm_co_side(symm, l->v->co) == SYMM_SIDE_KEEP)
+ fv[i] = BLI_ghash_lookup(symm->vert_symm_map, l->v);
+ else
+ fv[i] = l->v;
+ }
+
+ symm_face_create_v(symm->bm, fv, fe, f->len);
+ }
+ else if (ignore_all) {
+ BM_face_kill(symm->bm, f);
+ }
+ else {
+ SymmPoly sp;
+ int l1, l2, l3, l4;
+ int double_l2, double_l3;
+ int segment_len;
+
+ BLI_array_empty(pv);
+ BLI_array_grow_items(pv, f->len * 4);
+ sp.src_verts = pv;
+ sp.edge_verts = pv + f->len * 2;
+ symm_poly_with_splits(symm, f, &sp);
+
+ /* Find first loop edge crossing the axis */
+ symm_poly_next_crossing(symm, &sp, 0, &l1, &l2);
+
+ /* If crossing isn't kill to keep, find the next one */
+ if (symm_poly_co_side(symm, &sp, l1) != SYMM_SIDE_KILL) {
+ symm_poly_next_crossing(symm, &sp, l2, &l1, &l2);
+ }
+
+ /* Find next crossing (keep to kill) */
+ symm_poly_next_crossing(symm, &sp, l2, &l3, &l4);
+
+ if (l2 == l3)
+ segment_len = 0;
+ else if (l2 < l3)
+ segment_len = l3 - l2 + 1;
+ else
+ segment_len = (sp.len - l2 + 1) + l3;
+
+ double_l2 = symm_poly_co_side(symm, &sp, l2) == SYMM_SIDE_KEEP;
+ double_l3 = symm_poly_co_side(symm, &sp, l3) == SYMM_SIDE_KEEP;
+
+ /* Calculate number of new polygons/loops */
+ if (segment_len == 0) {
+ }
+ else if (sp.already_symmetric) {
+ int new_loops;
+
+ if (double_l2 && double_l3)
+ new_loops = segment_len * 2;
+ else if (!double_l2 && !double_l3)
+ new_loops = segment_len * 2 - 2;
+ else
+ new_loops = segment_len * 2 - 1;
+
+ BLI_array_empty(fv);
+ BLI_array_empty(fe);
+ BLI_array_grow_items(fv, new_loops);
+ BLI_array_grow_items(fe, new_loops);
+
+ symm_mesh_output_poly_zero_splits(symm, &sp,
+ fv, fe,
+ segment_len, l2);
+ BM_face_kill(symm->bm, f);
+ }
+ else if (!double_l2 && !double_l3) {
+ BLI_array_empty(fv);
+ BLI_array_empty(fe);
+ BLI_array_grow_items(fv, segment_len);
+ BLI_array_grow_items(fe, segment_len);
+
+ symm_mesh_output_poly_with_splits(symm, &sp,
+ fv, fe,
+ segment_len,
+ l2);
+
+ BM_face_kill(symm->bm, f);
+ }
+ else {
+ BLI_array_empty(fv);
+ BLI_array_empty(fe);
+ BLI_array_grow_items(fv, segment_len);
+ BLI_array_grow_items(fe, segment_len);
+
+ symm_mesh_output_poly_with_splits(symm, &sp,
+ fv, fe,
+ segment_len,
+ l2);
+
+ BM_face_kill(symm->bm, f);
+
+ /* Output bridge triangle */
+
+ BLI_array_empty(fv);
+ BLI_array_empty(fe);
+ BLI_array_grow_items(fv, 3);
+ BLI_array_grow_items(fe, 3);
+
+ if (double_l2) {
+ fv[0] = symm_poly_dst(&sp, l2);
+ fv[1] = symm_poly_mirror_dst(symm, &sp, l2);
+ fv[2] = symm_poly_dst(&sp, l3);
+ }
+ else if (double_l3) {
+ fv[0] = symm_poly_dst(&sp, l3);
+ fv[1] = symm_poly_mirror_dst(symm, &sp, l3);
+ fv[2] = symm_poly_dst(&sp, l2);
+ }
+
+ BLI_assert(fv[0] && fv[1] && fv[2]);
+
+ symm_face_create_v(symm->bm, fv, fe, 3);
+ }
+ }
+ }
+
+ BLI_array_free(pv);
+ BLI_array_free(fv);
+ BLI_array_free(fe);
+}
+
+/* Remove unused edges and vertices from the side being copied to */
+static void symm_kill_unused(Symm *symm)
+{
+ BMOIter oiter;
+ BMEdge *e;
+ BMVert *v;
+
+ /* Kill unused edges */
+ BMO_ITER (e, &oiter, symm->bm, symm->op, "input", BM_EDGE) {
+ const int crosses = symm_edge_crosses_axis(symm, e);
+ const int symmetric = (crosses &&
+ (!BLI_ghash_haskey(symm->edge_split_map, e)));
+
+ if (((symm_co_side(symm, e->v1->co) == SYMM_SIDE_KILL) ||
+ (symm_co_side(symm, e->v2->co) == SYMM_SIDE_KILL)) &&
+ !symmetric)
+ {
+ /* The edge might be used by a face outside the input set */
+ if (BM_edge_face_count(e) == 0)
+ BM_edge_kill(symm->bm, e);
+ }
+ }
+
+ /* Kill unused vertices */
+ BMO_ITER (v, &oiter, symm->bm, symm->op, "input", BM_VERT) {
+ if (symm_co_side(symm, v->co) == SYMM_SIDE_KILL) {
+ if (BM_vert_edge_count(v) == 0)
+ BM_vert_kill(symm->bm, v);
+ }
+ }
+}
+
+void bmo_symmetrize_exec(BMesh *bm, BMOperator *op)
+{
+ Symm symm;
+ BMO_SymmDirection direction = BMO_slot_int_get(op, "direction");
+
+ symm.bm = bm;
+ symm.op = op;
+ symm.axis = (ELEM(direction,
+ BMO_SYMMETRIZE_NEGATIVE_X,
+ BMO_SYMMETRIZE_POSITIVE_X) ? 0 :
+ ELEM(direction,
+ BMO_SYMMETRIZE_NEGATIVE_Y,
+ BMO_SYMMETRIZE_POSITIVE_Y) ? 1 :
+ ELEM(direction,
+ BMO_SYMMETRIZE_NEGATIVE_Z,
+ BMO_SYMMETRIZE_POSITIVE_Z) ? 2 : 0);
+ symm.direction = direction;
+
+ symm_verts_mirror(&symm);
+ symm_split_asymmetric_edges(&symm);
+ symm_mirror_edges(&symm);
+ symm_mirror_polygons(&symm);
+ symm_kill_unused(&symm);
+
+ BLI_ghash_free(symm.vert_symm_map, NULL, NULL);
+ BLI_ghash_free(symm.edge_split_map, NULL, NULL);
+
+ BMO_slot_buffer_from_enabled_flag(bm, op, "geomout", BM_ALL,
+ SYMM_OUTPUT_GEOM);
+}
diff --git a/source/blender/bmesh/operators/bmo_unsubdivide.c b/source/blender/bmesh/operators/bmo_unsubdivide.c
new file mode 100644
index 00000000000..3d44feac380
--- /dev/null
+++ b/source/blender/bmesh/operators/bmo_unsubdivide.c
@@ -0,0 +1,59 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Campbell Barton
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/bmesh/operators/bmo_unsubdivide.c
+ * \ingroup bmesh
+ */
+
+#include "BLI_math.h"
+#include "BLI_utildefines.h"
+
+#include "bmesh.h"
+
+#include "intern/bmesh_operators_private.h" /* own include */
+
+/* - BMVert.flag & BM_ELEM_TAG: shows we touched this vert
+ * - BMVert.index == -1: shows we will remove this vert
+ */
+void bmo_unsubdivide_exec(BMesh *bm, BMOperator *op)
+{
+ BMVert *v;
+ BMIter iter;
+
+ const int iterations = max_ii(1, BMO_slot_int_get(op, "iterations"));
+
+ BMOpSlot *vinput = BMO_slot_get(op, "verts");
+ BMVert **vinput_arr = (BMVert **)vinput->data.p;
+ int v_index;
+
+ /* tag verts */
+ BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
+ BM_elem_flag_disable(v, BM_ELEM_TAG);
+ }
+ for (v_index = 0; v_index < vinput->len; v_index++) {
+ v = vinput_arr[v_index];
+ BM_elem_flag_enable(v, BM_ELEM_TAG);
+ }
+
+ /* do all the real work here */
+ BM_mesh_decimate_unsubdivide_ex(bm, iterations, TRUE);
+}
diff --git a/source/blender/bmesh/operators/bmo_utils.c b/source/blender/bmesh/operators/bmo_utils.c
index 88ed1250264..e311b383b86 100644
--- a/source/blender/bmesh/operators/bmo_utils.c
+++ b/source/blender/bmesh/operators/bmo_utils.c
@@ -479,550 +479,15 @@ void bmo_smooth_vert_exec(BMesh *bm, BMOperator *op)
BLI_array_free(cos);
}
-/*
- * compute the fake surface of an ngon
- * This is done by decomposing the ngon into triangles who share the centroid of the ngon
- * while this method is far from being exact, it should guarantee an invariance.
- *
- * NOTE: This should probably go to bmesh_polygon.c
- */
-static float ngon_fake_area(BMFace *f)
-{
- BMIter liter;
- BMLoop *l;
- int num_verts = 0;
- float v[3], sv[3], c[3];
- float area = 0.0f;
-
- BM_face_calc_center_mean(f, c);
-
- BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
- if (num_verts == 0) {
- copy_v3_v3(v, l->v->co);
- copy_v3_v3(sv, l->v->co);
- num_verts++;
- }
- else {
- area += area_tri_v3(v, c, l->v->co);
- copy_v3_v3(v, l->v->co);
- num_verts++;
- }
- }
-
- area += area_tri_v3(v, c, sv);
-
- return area;
-}
-
-/*
- * extra face data (computed data)
- */
-typedef struct SimSel_FaceExt {
- BMFace *f; /* the face */
- float c[3]; /* center */
- union {
- float area; /* area */
- float perim; /* perimeter */
- float d; /* 4th component of plane (the first three being the normal) */
- struct Image *t; /* image pointer */
- };
-} SimSel_FaceExt;
-
-/*
- * Select similar faces, the choices are in the enum in source/blender/bmesh/bmesh_operators.h
- * We select either similar faces based on material, image, area, perimeter, normal, or the coplanar faces
- */
-void bmo_similar_faces_exec(BMesh *bm, BMOperator *op)
-{
- BMIter fm_iter;
- BMFace *fs, *fm;
- BMOIter fs_iter;
- int num_sels = 0, num_total = 0, i = 0, idx = 0;
- float angle = 0.0f;
- SimSel_FaceExt *f_ext = NULL;
- int *indices = NULL;
- float t_no[3]; /* temporary normal */
- int type = BMO_slot_int_get(op, "type");
- const float thresh = BMO_slot_float_get(op, "thresh");
- const float thresh_radians = thresh * (float)M_PI;
-
- num_total = BM_mesh_elem_count(bm, BM_FACE);
-
- /*
- * The first thing to do is to iterate through all the the selected items and mark them since
- * they will be in the selection anyway.
- * This will increase performance, (especially when the number of originally selected faces is high)
- * so the overall complexity will be less than $O(mn)$ where is the total number of selected faces,
- * and n is the total number of faces
- */
- BMO_ITER (fs, &fs_iter, bm, op, "faces", BM_FACE) {
- if (!BMO_elem_flag_test(bm, fs, FACE_MARK)) { /* is this really needed ? */
- BMO_elem_flag_enable(bm, fs, FACE_MARK);
- num_sels++;
- }
- }
-
- /* allocate memory for the selected faces indices and for all temporary faces */
- indices = (int *)MEM_callocN(sizeof(int) * num_sels, "face indices util.c");
- f_ext = (SimSel_FaceExt *)MEM_callocN(sizeof(SimSel_FaceExt) * num_total, "f_ext util.c");
-
- /* loop through all the faces and fill the faces/indices structure */
- BM_ITER_MESH (fm, &fm_iter, bm, BM_FACES_OF_MESH) {
- f_ext[i].f = fm;
- if (BMO_elem_flag_test(bm, fm, FACE_MARK)) {
- indices[idx] = i;
- idx++;
- }
- i++;
- }
-
- /*
- * Save us some computation burden: In case of perimeter/area/coplanar selection we compute
- * only once.
- */
- if (type == SIMFACE_PERIMETER || type == SIMFACE_AREA || type == SIMFACE_COPLANAR || type == SIMFACE_IMAGE) {
- for (i = 0; i < num_total; i++) {
- switch (type) {
- case SIMFACE_PERIMETER:
- /* set the perimeter */
- f_ext[i].perim = BM_face_calc_perimeter(f_ext[i].f);
- break;
-
- case SIMFACE_COPLANAR:
- /* compute the center of the polygon */
- BM_face_calc_center_mean(f_ext[i].f, f_ext[i].c);
-
- /* normalize the polygon normal */
- copy_v3_v3(t_no, f_ext[i].f->no);
- normalize_v3(t_no);
-
- /* compute the plane distance */
- f_ext[i].d = dot_v3v3(t_no, f_ext[i].c);
- break;
-
- case SIMFACE_AREA:
- f_ext[i].area = ngon_fake_area(f_ext[i].f);
- break;
-
- case SIMFACE_IMAGE:
- f_ext[i].t = NULL;
- if (CustomData_has_layer(&(bm->pdata), CD_MTEXPOLY)) {
- MTexPoly *mtpoly = CustomData_bmesh_get(&bm->pdata, f_ext[i].f->head.data, CD_MTEXPOLY);
- f_ext[i].t = mtpoly->tpage;
- }
- break;
- }
- }
- }
-
- /* now select the rest (if any) */
- for (i = 0; i < num_total; i++) {
- fm = f_ext[i].f;
- if (!BMO_elem_flag_test(bm, fm, FACE_MARK) && !BM_elem_flag_test(fm, BM_ELEM_HIDDEN)) {
- int cont = TRUE;
- for (idx = 0; idx < num_sels && cont == TRUE; idx++) {
- fs = f_ext[indices[idx]].f;
- switch (type) {
- case SIMFACE_MATERIAL:
- if (fm->mat_nr == fs->mat_nr) {
- BMO_elem_flag_enable(bm, fm, FACE_MARK);
- cont = FALSE;
- }
- break;
-
- case SIMFACE_IMAGE:
- if (f_ext[i].t == f_ext[indices[idx]].t) {
- BMO_elem_flag_enable(bm, fm, FACE_MARK);
- cont = FALSE;
- }
- break;
-
- case SIMFACE_NORMAL:
- angle = angle_normalized_v3v3(fs->no, fm->no); /* if the angle between the normals -> 0 */
- if (angle <= thresh_radians) {
- BMO_elem_flag_enable(bm, fm, FACE_MARK);
- cont = FALSE;
- }
- break;
-
- case SIMFACE_COPLANAR:
- angle = angle_normalized_v3v3(fs->no, fm->no); /* angle -> 0 */
- if (angle <= thresh_radians) { /* and dot product difference -> 0 */
- if (fabsf(f_ext[i].d - f_ext[indices[idx]].d) <= thresh) {
- BMO_elem_flag_enable(bm, fm, FACE_MARK);
- cont = FALSE;
- }
- }
- break;
-
- case SIMFACE_AREA:
- if (fabsf(f_ext[i].area - f_ext[indices[idx]].area) <= thresh) {
- BMO_elem_flag_enable(bm, fm, FACE_MARK);
- cont = FALSE;
- }
- break;
-
- case SIMFACE_PERIMETER:
- if (fabsf(f_ext[i].perim - f_ext[indices[idx]].perim) <= thresh) {
- BMO_elem_flag_enable(bm, fm, FACE_MARK);
- cont = FALSE;
- }
- break;
- }
- }
- }
- }
-
- MEM_freeN(f_ext);
- MEM_freeN(indices);
-
- /* transfer all marked faces to the output slot */
- BMO_slot_buffer_from_enabled_flag(bm, op, "faceout", BM_FACE, FACE_MARK);
-}
-
-/**************************************************************************** *
- * Similar Edges
- **************************************************************************** */
-#define EDGE_MARK 1
-
-/*
- * extra edge information
- */
-typedef struct SimSel_EdgeExt {
- BMEdge *e;
- union {
- float dir[3];
- float angle; /* angle between the face */
- };
-
- union {
- float length; /* edge length */
- int faces; /* faces count */
- };
-} SimSel_EdgeExt;
-
-/*
- * select similar edges: the choices are in the enum in source/blender/bmesh/bmesh_operators.h
- * choices are length, direction, face, ...
- */
-void bmo_similar_edges_exec(BMesh *bm, BMOperator *op)
-{
- BMOIter es_iter; /* selected edges iterator */
- BMIter e_iter; /* mesh edges iterator */
- BMEdge *es; /* selected edge */
- BMEdge *e; /* mesh edge */
- int idx = 0, i = 0 /* , f = 0 */;
- int *indices = NULL;
- SimSel_EdgeExt *e_ext = NULL;
- // float *angles = NULL;
- float angle;
-
- int num_sels = 0, num_total = 0;
- int type = BMO_slot_int_get(op, "type");
- const float thresh = BMO_slot_float_get(op, "thresh");
-
- /* sanity checks that the data we need is available */
- switch (type) {
- case SIMEDGE_CREASE:
- if (!CustomData_has_layer(&bm->edata, CD_CREASE)) {
- return;
- }
- break;
- case SIMEDGE_BEVEL:
- if (!CustomData_has_layer(&bm->edata, CD_BWEIGHT)) {
- return;
- }
- break;
- }
-
- num_total = BM_mesh_elem_count(bm, BM_EDGE);
-
- /* iterate through all selected edges and mark them */
- BMO_ITER (es, &es_iter, bm, op, "edges", BM_EDGE) {
- BMO_elem_flag_enable(bm, es, EDGE_MARK);
- num_sels++;
- }
-
- /* allocate memory for the selected edges indices and for all temporary edges */
- indices = (int *)MEM_callocN(sizeof(int) * num_sels, __func__);
- e_ext = (SimSel_EdgeExt *)MEM_callocN(sizeof(SimSel_EdgeExt) * num_total, __func__);
-
- /* loop through all the edges and fill the edges/indices structure */
- BM_ITER_MESH (e, &e_iter, bm, BM_EDGES_OF_MESH) {
- e_ext[i].e = e;
- if (BMO_elem_flag_test(bm, e, EDGE_MARK)) {
- indices[idx] = i;
- idx++;
- }
- i++;
- }
-
- /* save us some computation time by doing heavy computation once */
- if (type == SIMEDGE_LENGTH || type == SIMEDGE_FACE || type == SIMEDGE_DIR || type == SIMEDGE_FACE_ANGLE) {
- for (i = 0; i < num_total; i++) {
- switch (type) {
- case SIMEDGE_LENGTH: /* compute the length of the edge */
- e_ext[i].length = len_v3v3(e_ext[i].e->v1->co, e_ext[i].e->v2->co);
- break;
-
- case SIMEDGE_DIR: /* compute the direction */
- sub_v3_v3v3(e_ext[i].dir, e_ext[i].e->v1->co, e_ext[i].e->v2->co);
- normalize_v3(e_ext[i].dir);
- break;
-
- case SIMEDGE_FACE: /* count the faces around the edge */
- e_ext[i].faces = BM_edge_face_count(e_ext[i].e);
- break;
-
- case SIMEDGE_FACE_ANGLE:
- e_ext[i].faces = BM_edge_face_count(e_ext[i].e);
- if (e_ext[i].faces == 2)
- e_ext[i].angle = BM_edge_calc_face_angle(e_ext[i].e);
- break;
- }
- }
- }
-
- /* select the edges if any */
- for (i = 0; i < num_total; i++) {
- e = e_ext[i].e;
- if (!BMO_elem_flag_test(bm, e, EDGE_MARK) && !BM_elem_flag_test(e, BM_ELEM_HIDDEN)) {
- int cont = TRUE;
- for (idx = 0; idx < num_sels && cont == TRUE; idx++) {
- es = e_ext[indices[idx]].e;
- switch (type) {
- case SIMEDGE_LENGTH:
- if (fabsf(e_ext[i].length - e_ext[indices[idx]].length) <= thresh) {
- BMO_elem_flag_enable(bm, e, EDGE_MARK);
- cont = FALSE;
- }
- break;
-
- case SIMEDGE_DIR:
- /* compute the angle between the two edges */
- angle = angle_normalized_v3v3(e_ext[i].dir, e_ext[indices[idx]].dir);
-
- if (angle > (float)(M_PI / 2.0)) /* use the smallest angle between the edges */
- angle = fabsf(angle - (float)M_PI);
-
- if (angle / (float)(M_PI / 2.0) <= thresh) {
- BMO_elem_flag_enable(bm, e, EDGE_MARK);
- cont = FALSE;
- }
- break;
-
- case SIMEDGE_FACE:
- if (e_ext[i].faces == e_ext[indices[idx]].faces) {
- BMO_elem_flag_enable(bm, e, EDGE_MARK);
- cont = FALSE;
- }
- break;
-
- case SIMEDGE_FACE_ANGLE:
- if (e_ext[i].faces == 2) {
- if (e_ext[indices[idx]].faces == 2) {
- if (fabsf(e_ext[i].angle - e_ext[indices[idx]].angle) <= thresh) {
- BMO_elem_flag_enable(bm, e, EDGE_MARK);
- cont = FALSE;
- }
- }
- }
- else {
- cont = FALSE;
- }
- break;
-
- case SIMEDGE_CREASE:
- {
- float *c1, *c2;
-
- c1 = CustomData_bmesh_get(&bm->edata, e->head.data, CD_CREASE);
- c2 = CustomData_bmesh_get(&bm->edata, es->head.data, CD_CREASE);
-
- if (fabsf(*c1 - *c2) <= thresh) {
- BMO_elem_flag_enable(bm, e, EDGE_MARK);
- cont = FALSE;
- }
- }
- break;
-
- case SIMEDGE_BEVEL:
- {
- float *c1, *c2;
-
- c1 = CustomData_bmesh_get(&bm->edata, e->head.data, CD_BWEIGHT);
- c2 = CustomData_bmesh_get(&bm->edata, es->head.data, CD_BWEIGHT);
-
- if (fabsf(*c1 - *c2) <= thresh) {
- BMO_elem_flag_enable(bm, e, EDGE_MARK);
- cont = FALSE;
- }
- }
- break;
-
- case SIMEDGE_SEAM:
- if (BM_elem_flag_test(e, BM_ELEM_SEAM) == BM_elem_flag_test(es, BM_ELEM_SEAM)) {
- BMO_elem_flag_enable(bm, e, EDGE_MARK);
- cont = FALSE;
- }
- break;
-
- case SIMEDGE_SHARP:
- if (BM_elem_flag_test(e, BM_ELEM_SMOOTH) == BM_elem_flag_test(es, BM_ELEM_SMOOTH)) {
- BMO_elem_flag_enable(bm, e, EDGE_MARK);
- cont = FALSE;
- }
- break;
- }
- }
- }
- }
-
- MEM_freeN(e_ext);
- MEM_freeN(indices);
-
- /* transfer all marked edges to the output slot */
- BMO_slot_buffer_from_enabled_flag(bm, op, "edgeout", BM_EDGE, EDGE_MARK);
-}
-
-/**************************************************************************** *
- * Similar Vertices
- **************************************************************************** */
-#define VERT_MARK 1
-
-typedef struct SimSel_VertExt {
- BMVert *v;
- union {
- int num_faces; /* adjacent faces */
- int num_edges; /* adjacent edges */
- MDeformVert *dvert; /* deform vertex */
- };
-} SimSel_VertExt;
-
-/*
- * select similar vertices: the choices are in the enum in source/blender/bmesh/bmesh_operators.h
- * choices are normal, face, vertex group...
- */
-void bmo_similar_verts_exec(BMesh *bm, BMOperator *op)
-{
- BMOIter vs_iter; /* selected verts iterator */
- BMIter v_iter; /* mesh verts iterator */
- BMVert *vs; /* selected vertex */
- BMVert *v; /* mesh vertex */
- SimSel_VertExt *v_ext = NULL;
- int *indices = NULL;
- int num_total = 0, num_sels = 0, i = 0, idx = 0;
- int type = BMO_slot_int_get(op, "type");
- const float thresh = BMO_slot_float_get(op, "thresh");
- const float thresh_radians = thresh * (float)M_PI;
-
- num_total = BM_mesh_elem_count(bm, BM_VERT);
-
- /* iterate through all selected edges and mark them */
- BMO_ITER (vs, &vs_iter, bm, op, "verts", BM_VERT) {
- BMO_elem_flag_enable(bm, vs, VERT_MARK);
- num_sels++;
- }
-
- /* allocate memory for the selected vertices indices and for all temporary vertices */
- indices = (int *)MEM_mallocN(sizeof(int) * num_sels, "vertex indices");
- v_ext = (SimSel_VertExt *)MEM_mallocN(sizeof(SimSel_VertExt) * num_total, "vertex extra");
-
- /* loop through all the vertices and fill the vertices/indices structure */
- BM_ITER_MESH (v, &v_iter, bm, BM_VERTS_OF_MESH) {
- v_ext[i].v = v;
- if (BMO_elem_flag_test(bm, v, VERT_MARK)) {
- indices[idx] = i;
- idx++;
- }
-
- switch (type) {
- case SIMVERT_FACE:
- /* calling BM_vert_face_count every time is time consumming, so call it only once per vertex */
- v_ext[i].num_faces = BM_vert_face_count(v);
- break;
-
- case SIMVERT_VGROUP:
- if (CustomData_has_layer(&(bm->vdata), CD_MDEFORMVERT)) {
- v_ext[i].dvert = CustomData_bmesh_get(&bm->vdata, v_ext[i].v->head.data, CD_MDEFORMVERT);
- }
- else {
- v_ext[i].dvert = NULL;
- }
- break;
- case SIMVERT_EDGE:
- v_ext[i].num_edges = BM_vert_edge_count(v);
- break;
- }
-
- i++;
- }
-
- /* select the vertices if any */
- for (i = 0; i < num_total; i++) {
- v = v_ext[i].v;
- if (!BMO_elem_flag_test(bm, v, VERT_MARK) && !BM_elem_flag_test(v, BM_ELEM_HIDDEN)) {
- int cont = TRUE;
- for (idx = 0; idx < num_sels && cont == TRUE; idx++) {
- vs = v_ext[indices[idx]].v;
- switch (type) {
- case SIMVERT_NORMAL:
- /* compare the angle between the normals */
- if (angle_normalized_v3v3(v->no, vs->no) <= thresh_radians) {
- BMO_elem_flag_enable(bm, v, VERT_MARK);
- cont = FALSE;
- }
- break;
- case SIMVERT_FACE:
- /* number of adjacent faces */
- if (v_ext[i].num_faces == v_ext[indices[idx]].num_faces) {
- BMO_elem_flag_enable(bm, v, VERT_MARK);
- cont = FALSE;
- }
- break;
-
- case SIMVERT_VGROUP:
- if (v_ext[i].dvert != NULL && v_ext[indices[idx]].dvert != NULL) {
- int v1, v2;
- for (v1 = 0; v1 < v_ext[i].dvert->totweight && cont == 1; v1++) {
- for (v2 = 0; v2 < v_ext[indices[idx]].dvert->totweight; v2++) {
- if (v_ext[i].dvert->dw[v1].def_nr == v_ext[indices[idx]].dvert->dw[v2].def_nr) {
- BMO_elem_flag_enable(bm, v, VERT_MARK);
- cont = FALSE;
- break;
- }
- }
- }
- }
- break;
- case SIMVERT_EDGE:
- /* number of adjacent edges */
- if (v_ext[i].num_edges == v_ext[indices[idx]].num_edges) {
- BMO_elem_flag_enable(bm, v, VERT_MARK);
- cont = FALSE;
- }
- break;
- }
- }
- }
- }
-
- MEM_freeN(indices);
- MEM_freeN(v_ext);
-
- BMO_slot_buffer_from_enabled_flag(bm, op, "vertout", BM_VERT, VERT_MARK);
-}
-
/**************************************************************************** *
* Cycle UVs for a face
**************************************************************************** */
void bmo_rotate_uvs_exec(BMesh *bm, BMOperator *op)
{
- BMOIter fs_iter; /* selected faces iterator */
- BMFace *fs; /* current face */
- BMIter l_iter; /* iteration loop */
- // int n;
+ BMOIter fs_iter; /* selected faces iterator */
+ BMFace *fs; /* current face */
+ BMIter l_iter; /* iteration loop */
int dir = BMO_slot_int_get(op, "dir");
@@ -1077,7 +542,6 @@ void bmo_rotate_uvs_exec(BMesh *bm, BMOperator *op)
}
}
}
-
}
/**************************************************************************** *
@@ -1126,10 +590,9 @@ void bmo_reverse_uvs_exec(BMesh *bm, BMOperator *op)
void bmo_rotate_colors_exec(BMesh *bm, BMOperator *op)
{
- BMOIter fs_iter; /* selected faces iterator */
- BMFace *fs; /* current face */
- BMIter l_iter; /* iteration loop */
- // int n;
+ BMOIter fs_iter; /* selected faces iterator */
+ BMFace *fs; /* current face */
+ BMIter l_iter; /* iteration loop */
int dir = BMO_slot_int_get(op, "dir");
@@ -1234,6 +697,8 @@ typedef struct ElemNode {
HeapNode *hn; /* heap node */
} ElemNode;
+#define VERT_MARK 1
+
void bmo_shortest_path_exec(BMesh *bm, BMOperator *op)
{
BMOIter vs_iter /* , vs2_iter */; /* selected verts iterator */
@@ -1245,7 +710,7 @@ void bmo_shortest_path_exec(BMesh *bm, BMOperator *op)
ElemNode *vert_list = NULL;
int num_total = 0 /*, num_sels = 0 */, i = 0;
- int type = BMO_slot_int_get(op, "type");
+ const int type = BMO_slot_int_get(op, "type");
BMO_ITER (vs, &vs_iter, bm, op, "startv", BM_VERT) {
sv = vs;
@@ -1284,7 +749,7 @@ void bmo_shortest_path_exec(BMesh *bm, BMOperator *op)
vert_list[i].hn = BLI_heap_insert(h, vert_list[i].weight, vert_list[i].v);
}
- while (!BLI_heap_empty(h)) {
+ while (!BLI_heap_is_empty(h)) {
BMEdge *e;
BMIter e_i;
float v_weight;
diff --git a/source/blender/bmesh/tools/BME_bevel.c b/source/blender/bmesh/tools/BME_bevel.c
index 98f270abd16..a632a4446ed 100644
--- a/source/blender/bmesh/tools/BME_bevel.c
+++ b/source/blender/bmesh/tools/BME_bevel.c
@@ -1096,10 +1096,9 @@ static BMesh *BME_bevel_mesh(BMesh *bm, float value, int UNUSED(res), int option
return bm;
}
-BMesh *BME_bevel(BMEditMesh *em, float value, int res, int options, int defgrp_index, float angle,
- BME_TransData_Head **rtd, int do_tessface)
+BMesh *BME_bevel(BMesh *bm, float value, int res, int options, int defgrp_index, float angle,
+ BME_TransData_Head **rtd)
{
- BMesh *bm = em->bm;
BMVert *v;
BMIter iter;
@@ -1126,12 +1125,6 @@ BMesh *BME_bevel(BMEditMesh *em, float value, int res, int options, int defgrp_i
BMO_pop(bm);
}
- /* possibly needed when running as a tool (which is no longer functional)
- * but keep as an option for now */
- if (do_tessface) {
- BMEdit_RecalcTessellation(em);
- }
-
/* interactive preview? */
if (rtd) {
*rtd = td;
diff --git a/source/blender/collada/AnimationExporter.cpp b/source/blender/collada/AnimationExporter.cpp
index 0e8ead61437..26b5edf7ea6 100644
--- a/source/blender/collada/AnimationExporter.cpp
+++ b/source/blender/collada/AnimationExporter.cpp
@@ -184,7 +184,7 @@ std::string AnimationExporter::getObjectBoneName(Object *ob, const FCurve *fcu)
if (boneName != NULL)
return /*id_name(ob) + "_" +*/ std::string(boneName);
- else
+ else
return id_name(ob);
}
@@ -265,7 +265,7 @@ void AnimationExporter::dae_animation(Object *ob, FCurve *fcu, char *transformNa
MEM_freeN(eul);
MEM_freeN(eul_axis);
}
- else if(!strcmp(transformName, "lens") && (ob->type == OB_CAMERA)) {
+ else if (!strcmp(transformName, "lens") && (ob->type == OB_CAMERA)) {
output_id = create_lens_source_from_fcurve((Camera *) ob->data, COLLADASW::InputSemantic::OUTPUT, fcu, anim_id);
}
else {
@@ -584,8 +584,8 @@ void AnimationExporter::get_source_values(BezTriple *bezt, COLLADASW::InputSeman
values[0] = convert_time(bezt->vec[0][0]);
if (bezt->ipo != BEZT_IPO_BEZ) {
// We're in a mixed interpolation scenario, set zero as it's irrelevant but value might contain unused data
- values[0] = 0;
- values[1] = 0;
+ values[0] = 0;
+ values[1] = 0;
}
else if (is_rotation) {
values[1] = RAD2DEGF(bezt->vec[0][1]);
@@ -600,8 +600,8 @@ void AnimationExporter::get_source_values(BezTriple *bezt, COLLADASW::InputSeman
values[0] = convert_time(bezt->vec[2][0]);
if (bezt->ipo != BEZT_IPO_BEZ) {
// We're in a mixed interpolation scenario, set zero as it's irrelevant but value might contain unused data
- values[0] = 0;
- values[1] = 0;
+ values[0] = 0;
+ values[1] = 0;
}
else if (is_rotation) {
values[1] = RAD2DEGF(bezt->vec[2][1]);
@@ -634,11 +634,11 @@ std::string AnimationExporter::create_source_from_fcurve(COLLADASW::InputSemanti
switch (semantic) {
case COLLADASW::InputSemantic::INPUT:
case COLLADASW::InputSemantic::OUTPUT:
- source.setAccessorStride(1);
+ source.setAccessorStride(1);
break;
case COLLADASW::InputSemantic::IN_TANGENT:
case COLLADASW::InputSemantic::OUT_TANGENT:
- source.setAccessorStride(2);
+ source.setAccessorStride(2);
break;
default:
break;
@@ -1082,13 +1082,13 @@ std::string AnimationExporter::get_transform_sid(char *rna_path, int tm_type, co
break;
case 6:
tm_name = "diffuse";
- break;
+ break;
case 7:
tm_name = "transparency";
- break;
+ break;
case 8:
tm_name = "index_of_refraction";
- break;
+ break;
default:
tm_name = "";
diff --git a/source/blender/collada/AnimationExporter.h b/source/blender/collada/AnimationExporter.h
index 7fd39765cc9..349930dea8f 100644
--- a/source/blender/collada/AnimationExporter.h
+++ b/source/blender/collada/AnimationExporter.h
@@ -35,10 +35,19 @@ extern "C"
#include "DNA_armature_types.h"
#include "DNA_material_types.h"
+#include "BLI_math.h"
+#include "BLI_string.h"
+#include "BLI_listbase.h"
+#include "BLI_utildefines.h"
+
#include "BKE_DerivedMesh.h"
#include "BKE_fcurve.h"
#include "BKE_animsys.h"
#include "BKE_scene.h"
+#include "BKE_action.h" // pose functions
+#include "BKE_armature.h"
+#include "BKE_object.h"
+
#ifdef NAN_BUILDINFO
extern char build_rev[];
#endif
@@ -46,14 +55,6 @@ extern char build_rev[];
#include "MEM_guardedalloc.h"
-#include "BKE_action.h" // pose functions
-#include "BKE_armature.h"
-#include "BKE_object.h"
-
-#include "BLI_math.h"
-#include "BLI_string.h"
-#include "BLI_listbase.h"
-
#include "RNA_access.h"
#include "COLLADASWSource.h"
@@ -122,7 +123,7 @@ protected:
float convert_angle(float angle);
- std::string get_semantic_suffix(COLLADASW::InputSemantic::Semantics semantic);
+ std::string get_semantic_suffix(COLLADASW::InputSemantic::Semantics semantic);
void add_source_parameters(COLLADASW::SourceBase::ParameterNameList& param,
COLLADASW::InputSemantic::Semantics semantic, bool is_rot, const char *axis, bool transform);
diff --git a/source/blender/collada/AnimationImporter.cpp b/source/blender/collada/AnimationImporter.cpp
index b2748a55b6a..374f6385ea7 100644
--- a/source/blender/collada/AnimationImporter.cpp
+++ b/source/blender/collada/AnimationImporter.cpp
@@ -136,7 +136,7 @@ void AnimationImporter::animation_to_fcurves(COLLADAFW::AnimationCurve *curve)
bez.ipo = BEZT_IPO_BEZ;
else
bez.ipo = BEZT_IPO_CONST;
- //bez.h1 = bez.h2 = HD_AUTO;
+ //bez.h1 = bez.h2 = HD_AUTO;
}
else {
bez.h1 = bez.h2 = HD_AUTO;
@@ -617,7 +617,7 @@ void AnimationImporter:: Assign_color_animations(const COLLADAFW::UniqueId& list
//Add the curves of the current animation to the object
for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
FCurve *fcu = *iter;
- BLI_addtail(AnimCurves, fcu);
+ BLI_addtail(AnimCurves, fcu);
}
}
@@ -854,14 +854,13 @@ static const double get_aspect_ratio(const COLLADAFW::Camera *camera)
{
double aspect = camera->getAspectRatio().getValue();
- if(aspect == 0)
- {
+ if (aspect == 0) {
const double yfov = camera->getYFov().getValue();
- if(yfov == 0)
- aspect=1; // assume yfov and xfov are equal
- else
- {
+ if (yfov == 0) {
+ aspect = 1; // assume yfov and xfov are equal
+ }
+ else {
const double xfov = camera->getXFov().getValue();
if (xfov==0)
aspect = 1;
@@ -885,7 +884,7 @@ void AnimationImporter::translate_Animations(COLLADAFW::Node *node,
COLLADAFW::Node *root = root_map.find(uid) == root_map.end() ? node : root_map[uid];
Object *ob;
- if(is_joint)
+ if (is_joint)
ob = armature_importer->get_armature_for_joint(root);
else
ob = object_map.find(uid) == object_map.end() ? NULL : object_map.find(uid)->second;
@@ -938,7 +937,7 @@ void AnimationImporter::translate_Animations(COLLADAFW::Node *node,
if (is_matrix) {
apply_matrix_curves(ob, animcurves, root, node, transform);
}
- else {
+ else {
if (is_joint) {
@@ -1094,7 +1093,7 @@ void AnimationImporter::translate_Animations(COLLADAFW::Node *node,
}
}
}
- }
+ }
}
}
@@ -1114,8 +1113,8 @@ void AnimationImporter::add_bone_animation_sampled(Object *ob, std::vector<FCurv
for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
FCurve *fcu = *iter;
- fcurve_deg_to_rad(fcu);
- }
+ fcurve_deg_to_rad(fcu);
+ }
}
diff --git a/source/blender/collada/AnimationImporter.h b/source/blender/collada/AnimationImporter.h
index db61692484b..293b992f219 100644
--- a/source/blender/collada/AnimationImporter.h
+++ b/source/blender/collada/AnimationImporter.h
@@ -169,7 +169,7 @@ public:
int setAnimType ( const COLLADAFW::Animatable * prop, int type, int addition);
- void modify_fcurve(std::vector<FCurve*>* curves, const char* rna_path, int array_index );
+ void modify_fcurve(std::vector<FCurve*>* curves, const char *rna_path, int array_index );
void unused_fcurve(std::vector<FCurve*>* curves );
// prerequisites:
// animlist_map - map animlist id -> animlist
diff --git a/source/blender/collada/ArmatureExporter.cpp b/source/blender/collada/ArmatureExporter.cpp
index 30e9baccbf1..134fd639a73 100644
--- a/source/blender/collada/ArmatureExporter.cpp
+++ b/source/blender/collada/ArmatureExporter.cpp
@@ -346,7 +346,7 @@ void ArmatureExporter::export_controller(Object *ob, Object *ob_arm)
if (this->export_settings->apply_modifiers) {
me = bc_to_mesh_apply_modifiers(scene, ob, this->export_settings->export_mesh_type);
- }
+ }
else {
me = (Mesh *)ob->data;
}
diff --git a/source/blender/collada/ArmatureImporter.h b/source/blender/collada/ArmatureImporter.h
index eead45353af..a6b37287479 100644
--- a/source/blender/collada/ArmatureImporter.h
+++ b/source/blender/collada/ArmatureImporter.h
@@ -104,7 +104,7 @@ private:
#endif
void create_bone(SkinInfo& skin, COLLADAFW::Node *node, EditBone *parent, int totchild,
- float parent_mat[][4], bArmature *arm);
+ float parent_mat[][4], bArmature *arm);
void create_unskinned_bone(COLLADAFW::Node *node, EditBone *parent, int totchild,
float parent_mat[][4], Object * ob_arm);
diff --git a/source/blender/collada/CMakeLists.txt b/source/blender/collada/CMakeLists.txt
index 3b7a38eb950..0091df3c502 100644
--- a/source/blender/collada/CMakeLists.txt
+++ b/source/blender/collada/CMakeLists.txt
@@ -70,7 +70,7 @@ set(SRC
collada_utils.cpp
AnimationImporter.h
- AnimationExporter.h
+ AnimationExporter.h
ArmatureExporter.h
ArmatureImporter.h
CameraExporter.h
diff --git a/source/blender/collada/DocumentExporter.cpp b/source/blender/collada/DocumentExporter.cpp
index 7683ec1e9cd..c491326519f 100644
--- a/source/blender/collada/DocumentExporter.cpp
+++ b/source/blender/collada/DocumentExporter.cpp
@@ -79,36 +79,38 @@ extern "C"
#include "DNA_modifier_types.h"
#include "DNA_userdef_types.h"
-#include "BKE_DerivedMesh.h"
-#include "BKE_fcurve.h"
-#include "BKE_animsys.h"
#include "BLI_path_util.h"
#include "BLI_fileops.h"
-#include "ED_keyframing.h"
-#ifdef WITH_BUILDINFO
-extern char build_rev[];
-#endif
-
-#include "MEM_guardedalloc.h"
+#include "BLI_math.h"
+#include "BLI_string.h"
+#include "BLI_listbase.h"
+#include "BLI_utildefines.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_action.h" // pose functions
+#include "BKE_animsys.h"
+#include "BKE_armature.h"
#include "BKE_blender.h" // version info
-#include "BKE_scene.h"
+#include "BKE_fcurve.h"
#include "BKE_global.h"
+#include "BKE_image.h"
#include "BKE_main.h"
#include "BKE_material.h"
-#include "BKE_action.h" // pose functions
-#include "BKE_armature.h"
-#include "BKE_image.h"
#include "BKE_object.h"
+#include "BKE_scene.h"
-#include "BLI_math.h"
-#include "BLI_string.h"
-#include "BLI_listbase.h"
+#include "ED_keyframing.h"
+#ifdef WITH_BUILDINFO
+extern char build_rev[];
+#endif
+
+#include "MEM_guardedalloc.h"
#include "RNA_access.h"
}
#include "collada_internal.h"
+#include "collada_utils.h"
#include "DocumentExporter.h"
extern bool bc_has_object_type(LinkNode *export_set, short obtype);
@@ -160,7 +162,7 @@ void DocumentExporter::exportCurrentScene(Scene *sce)
clear_global_id_map();
COLLADABU::NativeString native_filename =
- COLLADABU::NativeString(std::string(this->export_settings->filepath));
+ COLLADABU::NativeString(std::string(this->export_settings->filepath), COLLADABU::NativeString::ENCODING_UTF8);
COLLADASW::StreamWriter sw(native_filename);
fprintf(stdout, "Collada export: %s\n", this->export_settings->filepath);
diff --git a/source/blender/collada/DocumentExporter.h b/source/blender/collada/DocumentExporter.h
index 05620087d76..84c0610282e 100644
--- a/source/blender/collada/DocumentExporter.h
+++ b/source/blender/collada/DocumentExporter.h
@@ -40,7 +40,7 @@ class DocumentExporter
public:
DocumentExporter(const ExportSettings *export_settings);
void exportCurrentScene(Scene *sce);
- void exportScenes(const char* filename);
+ void exportScenes(const char *filename);
private:
const ExportSettings *export_settings;
};
diff --git a/source/blender/collada/DocumentImporter.cpp b/source/blender/collada/DocumentImporter.cpp
index f29933ea0c1..1c4f0974c6d 100644
--- a/source/blender/collada/DocumentImporter.cpp
+++ b/source/blender/collada/DocumentImporter.cpp
@@ -88,8 +88,8 @@ extern "C" {
/*
- COLLADA Importer limitations:
- - no multiple scene import, all objects are added to active scene
+ * COLLADA Importer limitations:
+ * - no multiple scene import, all objects are added to active scene
*/
// #define COLLADA_DEBUG
@@ -210,7 +210,7 @@ void DocumentImporter::finish()
}
- mesh_importer.optimize_material_assignements();
+ mesh_importer.optimize_material_assignments();
armature_importer.set_tags_map(this->uid_tags_map);
armature_importer.make_armatures(mContext);
@@ -311,7 +311,7 @@ bool DocumentImporter::writeScene(const COLLADAFW::Scene *scene)
Object *DocumentImporter::create_camera_object(COLLADAFW::InstanceCamera *camera, Scene *sce)
{
const COLLADAFW::UniqueId& cam_uid = camera->getInstanciatedObjectId();
- if (uid_camera_map.find(cam_uid) == uid_camera_map.end()) {
+ if (uid_camera_map.find(cam_uid) == uid_camera_map.end()) {
// fprintf(stderr, "Couldn't find camera by UID.\n");
return NULL;
}
@@ -329,7 +329,7 @@ Object *DocumentImporter::create_camera_object(COLLADAFW::InstanceCamera *camera
Object *DocumentImporter::create_lamp_object(COLLADAFW::InstanceLight *lamp, Scene *sce)
{
const COLLADAFW::UniqueId& lamp_uid = lamp->getInstanciatedObjectId();
- if (uid_lamp_map.find(lamp_uid) == uid_lamp_map.end()) {
+ if (uid_lamp_map.find(lamp_uid) == uid_lamp_map.end()) {
fprintf(stderr, "Couldn't find lamp by UID.\n");
return NULL;
}
@@ -524,7 +524,7 @@ void DocumentImporter::write_node(COLLADAFW::Node *node, COLLADAFW::Node *parent
}
// if node has child nodes write them
COLLADAFW::NodePointerArray &child_nodes = node->getChildNodes();
- for (unsigned int i = 0; i < child_nodes.getCount(); i++) {
+ for (unsigned int i = 0; i < child_nodes.getCount(); i++) {
write_node(child_nodes[i], node, sce, ob, is_library_node);
}
}
@@ -878,7 +878,7 @@ bool DocumentImporter::writeCamera(const COLLADAFW::Camera *camera)
}
break;
/* XXX correct way to do following four is probably to get also render
- size and determine proper settings from that somehow */
+ * size and determine proper settings from that somehow */
case COLLADAFW::Camera::ASPECTRATIO_AND_X:
case COLLADAFW::Camera::SINGLE_X:
case COLLADAFW::Camera::X_AND_Y:
diff --git a/source/blender/collada/DocumentImporter.h b/source/blender/collada/DocumentImporter.h
index 13f23b23388..e878a5a5b48 100644
--- a/source/blender/collada/DocumentImporter.h
+++ b/source/blender/collada/DocumentImporter.h
@@ -78,8 +78,9 @@ public:
void write_profile_COMMON(COLLADAFW::EffectCommon*, Material*);
void translate_anim_recursive(COLLADAFW::Node*, COLLADAFW::Node*, Object*);
- /** This method will be called if an error in the loading process occurred and the loader cannot
- continue to load. The writer should undo all operations that have been performed.
+ /**
+ * This method will be called if an error in the loading process occurred and the loader cannot
+ * continue to load. The writer should undo all operations that have been performed.
\param errorMessage A message containing informations about the error that occurred.
*/
void cancel(const COLLADAFW::String& errorMessage);
diff --git a/source/blender/collada/EffectExporter.cpp b/source/blender/collada/EffectExporter.cpp
index dd59fb9fb91..e4a654dc99a 100644
--- a/source/blender/collada/EffectExporter.cpp
+++ b/source/blender/collada/EffectExporter.cpp
@@ -255,7 +255,7 @@ void EffectsExporter::operator()(Material *ma, Object *ob)
if (ep.getShaderType() != COLLADASW::EffectProfile::LAMBERT) {
cot = getcol(ma->specr * ma->spec, ma->specg * ma->spec, ma->specb * ma->spec, 1.0f);
ep.setSpecular(cot, false, "specular");
- }
+ }
// XXX make this more readable if possible
@@ -381,7 +381,7 @@ void EffectsExporter::operator()(Material *ma, Object *ob)
}
std::set<Image *>::iterator uv_t_iter;
- for(uv_t_iter = uv_textures.begin(); uv_t_iter != uv_textures.end(); uv_t_iter++ ) {
+ for (uv_t_iter = uv_textures.begin(); uv_t_iter != uv_textures.end(); uv_t_iter++ ) {
Image *ima = *uv_t_iter;
std::string key(id_name(ima));
key = translate_id(key);
@@ -405,7 +405,7 @@ void EffectsExporter::operator()(Material *ma, Object *ob)
ep.closeProfile();
if (twoSided)
mSW->appendTextBlock("<extra><technique profile=\"MAX3D\"><double_sided>1</double_sided></technique></extra>");
- closeEffect();
+ closeEffect();
}
COLLADASW::ColorOrTexture EffectsExporter::createTexture(Image *ima,
diff --git a/source/blender/collada/GeometryExporter.cpp b/source/blender/collada/GeometryExporter.cpp
index 27700444ba9..f33f0fa110d 100644
--- a/source/blender/collada/GeometryExporter.cpp
+++ b/source/blender/collada/GeometryExporter.cpp
@@ -38,6 +38,8 @@
#include "DNA_meshdata_types.h"
extern "C" {
+ #include "BLI_utildefines.h"
+
#include "BKE_DerivedMesh.h"
#include "BKE_main.h"
#include "BKE_global.h"
@@ -78,7 +80,7 @@ void GeometryExporter::operator()(Object *ob)
Mesh *me;
if (this->export_settings->apply_modifiers) {
me = bc_to_mesh_apply_modifiers(mScene, ob, this->export_settings->export_mesh_type);
- }
+ }
else {
me = (Mesh *)ob->data;
}
@@ -358,13 +360,13 @@ void GeometryExporter::createVertsSource(std::string geom_id, Mesh *me)
param.push_back("X");
param.push_back("Y");
param.push_back("Z");
- /*main function, it creates <source id = "">, <float_array id = ""
- count = ""> */
+ /* main function, it creates <source id = "">, <float_array id = ""
+ * count = ""> */
source.prepareToAppendValues();
//appends data to <float_array>
int i = 0;
for (i = 0; i < totverts; i++) {
- source.appendValues(verts[i].co[0], verts[i].co[1], verts[i].co[2]);
+ source.appendValues(verts[i].co[0], verts[i].co[1], verts[i].co[2]);
}
source.finish();
diff --git a/source/blender/collada/ImageExporter.cpp b/source/blender/collada/ImageExporter.cpp
index f1f1efdbd33..2e0c0f1ea57 100644
--- a/source/blender/collada/ImageExporter.cpp
+++ b/source/blender/collada/ImageExporter.cpp
@@ -62,7 +62,7 @@ void ImagesExporter::export_UV_Image(Image *image, bool use_copies)
if (not_yet_exported) {
ImBuf *imbuf = BKE_image_get_ibuf(image, NULL);
- if(!imbuf) {
+ if (!imbuf) {
fprintf(stderr, "Collada export: image does not exist:\n%s\n", image->name);
return;
}
@@ -103,7 +103,7 @@ void ImagesExporter::export_UV_Image(Image *image, bool use_copies)
// So we have to export it. The export will keep the image state intact,
// so the exported file will not be associated with the image.
- if (BKE_imbuf_write_as(imbuf, export_path, &imageFormat, image->colorspace_settings.name, true) == 0) {
+ if (BKE_imbuf_write_as(imbuf, export_path, &imageFormat, true) == 0) {
fprintf(stderr, "Collada export: Cannot export image to:\n%s\n", export_path);
return;
}
diff --git a/source/blender/collada/MeshImporter.cpp b/source/blender/collada/MeshImporter.cpp
index cf211e2fbb1..8337a977b3b 100644
--- a/source/blender/collada/MeshImporter.cpp
+++ b/source/blender/collada/MeshImporter.cpp
@@ -478,7 +478,7 @@ void MeshImporter::allocate_face_data(COLLADAFW::Mesh *mesh, Mesh *me, int new_t
int total_facecount = 0;
// collect edge_count and face_count from all parts
- for (int i = 0; i < prim_arr.getCount(); i++) {
+ for (int i = 0; i < prim_arr.getCount(); i++) {
COLLADAFW::MeshPrimitive *mp = prim_arr[i];
int type = mp->getPrimitiveType();
switch (type) {
@@ -506,7 +506,7 @@ unsigned int MeshImporter::get_loose_edge_count(COLLADAFW::Mesh *mesh) {
int loose_edge_count = 0;
// collect edge_count and face_count from all parts
- for (int i = 0; i < prim_arr.getCount(); i++) {
+ for (int i = 0; i < prim_arr.getCount(); i++) {
COLLADAFW::MeshPrimitive *mp = prim_arr[i];
int type = mp->getPrimitiveType();
switch (type) {
@@ -998,7 +998,7 @@ static bool bc_has_same_material_configuration(Object *ob1, Object *ob2)
if (ob1->totcol != ob2->totcol) return false; // not same number of materials
if (ob1->totcol == 0) return false; // no material at all
- for(int index=0; index < ob1->totcol; index++) {
+ for (int index=0; index < ob1->totcol; index++) {
if (ob1->matbits[index] != ob2->matbits[index]) return false; // shouldn't happen
if (ob1->matbits[index] == 0) return false; // shouldn't happen
if (ob1->mat[index] != ob2->mat[index]) return false; // different material assignment
@@ -1061,7 +1061,7 @@ std::vector<Object *> MeshImporter::get_all_users_of(Mesh *reference_mesh)
*
* During import all materials have been assigned to Object.
* Now we iterate over the imported objects and optimize
- * the assignements as follows:
+ * the assignments as follows:
*
* for each imported geometry:
* if number of users is 1:
@@ -1075,7 +1075,7 @@ std::vector<Object *> MeshImporter::get_all_users_of(Mesh *reference_mesh)
* adjust all other users accordingly.
*
**/
-void MeshImporter::optimize_material_assignements()
+void MeshImporter::optimize_material_assignments()
{
for (std::vector<Object *>::iterator it = imported_objects.begin();
it != imported_objects.end(); ++it)
@@ -1119,7 +1119,7 @@ void MeshImporter::optimize_material_assignements()
* come along with different materials. So we first create the objects
* and assign the materials to Object, then in a later cleanup we decide
* which materials shall be moved to the created geometries. Also see
- * optimize_material_assignements() above.
+ * optimize_material_assignments() above.
*/
MTFace *MeshImporter::assign_material_to_geom(COLLADAFW::MaterialBinding cmaterial,
std::map<COLLADAFW::UniqueId, Material *>& uid_material_map,
diff --git a/source/blender/collada/MeshImporter.h b/source/blender/collada/MeshImporter.h
index 2cac26d5329..746b0738108 100644
--- a/source/blender/collada/MeshImporter.h
+++ b/source/blender/collada/MeshImporter.h
@@ -106,10 +106,10 @@ private:
#endif
void set_face_uv(MTFace *mtface, UVDataWrapper &uvs,
- COLLADAFW::IndexList& index_list, unsigned int *tris_indices);
+ COLLADAFW::IndexList& index_list, unsigned int *tris_indices);
void set_face_uv(MTFace *mtface, UVDataWrapper &uvs,
- COLLADAFW::IndexList& index_list, int index, bool quad);
+ COLLADAFW::IndexList& index_list, int index, bool quad);
#ifdef COLLADA_DEBUG
void print_index_list(COLLADAFW::IndexList& index_list);
@@ -132,7 +132,7 @@ private:
CustomData create_edge_custom_data(EdgeHash *eh);
- void allocate_face_data(COLLADAFW::Mesh *mesh, Mesh *me, int new_tris);
+ void allocate_face_data(COLLADAFW::Mesh *mesh, Mesh *me, int new_tris);
// TODO: import uv set names
void read_faces(COLLADAFW::Mesh *mesh, Mesh *me, int new_tris);
@@ -153,22 +153,22 @@ public:
virtual Object *get_object_by_geom_uid(const COLLADAFW::UniqueId& geom_uid);
MTex *assign_textures_to_uvlayer(COLLADAFW::TextureCoordinateBinding &ctexture,
- Mesh *me, TexIndexTextureArrayMap& texindex_texarray_map,
- MTex *color_texture);
+ Mesh *me, TexIndexTextureArrayMap& texindex_texarray_map,
+ MTex *color_texture);
- void optimize_material_assignements();
+ void optimize_material_assignments();
MTFace *assign_material_to_geom(COLLADAFW::MaterialBinding cmaterial,
- std::map<COLLADAFW::UniqueId, Material*>& uid_material_map,
- Object *ob, const COLLADAFW::UniqueId *geom_uid,
- MTex **color_texture, char *layername, MTFace *texture_face,
- std::map<Material*, TexIndexTextureArrayMap>& material_texture_mapping_map, short mat_index);
+ std::map<COLLADAFW::UniqueId, Material*>& uid_material_map,
+ Object *ob, const COLLADAFW::UniqueId *geom_uid,
+ MTex **color_texture, char *layername, MTFace *texture_face,
+ std::map<Material*, TexIndexTextureArrayMap>& material_texture_mapping_map, short mat_index);
Object *create_mesh_object(COLLADAFW::Node *node, COLLADAFW::InstanceGeometry *geom,
- bool isController,
- std::map<COLLADAFW::UniqueId, Material*>& uid_material_map,
- std::map<Material*, TexIndexTextureArrayMap>& material_texture_mapping_map);
+ bool isController,
+ std::map<COLLADAFW::UniqueId, Material*>& uid_material_map,
+ std::map<Material*, TexIndexTextureArrayMap>& material_texture_mapping_map);
// create a mesh storing a pointer in a map so it can be retrieved later by geometry UID
bool write_geometry(const COLLADAFW::Geometry* geom);
diff --git a/source/blender/collada/SceneExporter.cpp b/source/blender/collada/SceneExporter.cpp
index 4aaff024cac..6d239ae0fb1 100644
--- a/source/blender/collada/SceneExporter.cpp
+++ b/source/blender/collada/SceneExporter.cpp
@@ -24,9 +24,13 @@
* \ingroup collada
*/
+extern "C" {
+ #include "BLI_utildefines.h"
+ #include "BKE_object.h"
+}
+
#include "SceneExporter.h"
#include "collada_utils.h"
-#include "BKE_object.h"
SceneExporter::SceneExporter(COLLADASW::StreamWriter *sw, ArmatureExporter *arm, const ExportSettings *export_settings)
: COLLADASW::LibraryVisualScenes(sw), arm_exporter(arm), export_settings(export_settings)
diff --git a/source/blender/collada/collada.cpp b/source/blender/collada/collada.cpp
index f7e0f75ec5c..fbb18887d1b 100644
--- a/source/blender/collada/collada.cpp
+++ b/source/blender/collada/collada.cpp
@@ -76,6 +76,7 @@ int collada_export(Scene *sce,
if (!BLI_exists(filepath)) {
BLI_make_existing_file(filepath); /* makes the dir if its not there */
if (BLI_file_touch(filepath) == 0) {
+ fprintf(stdout, "Collada export: Can not create: %s\n", filepath);
return 0;
}
}
diff --git a/source/blender/collada/collada_internal.h b/source/blender/collada/collada_internal.h
index c1f75f996ce..6eec6a1675e 100644
--- a/source/blender/collada/collada_internal.h
+++ b/source/blender/collada/collada_internal.h
@@ -88,6 +88,7 @@ extern std::string translate_id(const std::string &id);
extern std::string id_name(void *id);
+extern std::string get_geometry_id(Object *ob);
extern std::string get_geometry_id(Object *ob, bool use_instantiation);
extern std::string get_light_id(Object *ob);
diff --git a/source/blender/collada/collada_utils.cpp b/source/blender/collada/collada_utils.cpp
index 018d66c6f55..35844b549de 100644
--- a/source/blender/collada/collada_utils.cpp
+++ b/source/blender/collada/collada_utils.cpp
@@ -35,7 +35,6 @@
#include "collada_utils.h"
extern "C" {
-
#include "DNA_modifier_types.h"
#include "DNA_customdata_types.h"
#include "DNA_object_types.h"
@@ -44,6 +43,7 @@ extern "C" {
#include "DNA_armature_types.h"
#include "BLI_math.h"
+#include "BLI_linklist.h"
#include "BKE_context.h"
#include "BKE_customdata.h"
@@ -51,10 +51,7 @@ extern "C" {
#include "BKE_object.h"
#include "BKE_mesh.h"
#include "BKE_scene.h"
-
#include "BKE_DerivedMesh.h"
-#include "BLI_linklist.h"
-
#include "WM_api.h" // XXX hrm, see if we can do without this
#include "WM_types.h"
diff --git a/source/blender/collada/collada_utils.h b/source/blender/collada/collada_utils.h
index b52115722fe..b8990c3fcdd 100644
--- a/source/blender/collada/collada_utils.h
+++ b/source/blender/collada/collada_utils.h
@@ -35,18 +35,19 @@
#include <vector>
#include <map>
+extern "C" {
#include "DNA_object_types.h"
#include "DNA_mesh_types.h"
#include "DNA_customdata_types.h"
#include "DNA_texture_types.h"
-#include "BKE_context.h"
-#include "BKE_object.h"
-
#include "DNA_scene_types.h"
-extern "C" {
-#include "BKE_DerivedMesh.h"
#include "BLI_linklist.h"
+#include "BLI_utildefines.h"
+
+#include "BKE_context.h"
+#include "BKE_object.h"
+#include "BKE_DerivedMesh.h"
}
#include "ExportSettings.h"
diff --git a/source/blender/compositor/CMakeLists.txt b/source/blender/compositor/CMakeLists.txt
index 9932ed17378..b3e76a287ea 100644
--- a/source/blender/compositor/CMakeLists.txt
+++ b/source/blender/compositor/CMakeLists.txt
@@ -1,4 +1,3 @@
-# $Id: CMakeLists.txt 14444 2008-04-16 22:40:48Z hos $
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
@@ -272,6 +271,11 @@ set(SRC
operations/COM_NormalizeOperation.cpp
operations/COM_NormalizeOperation.h
+ nodes/COM_PixelateNode.cpp
+ nodes/COM_PixelateNode.h
+ operations/COM_PixelateOperation.cpp
+ operations/COM_PixelateOperation.h
+
# Filter nodes
nodes/COM_BilateralBlurNode.cpp
nodes/COM_BilateralBlurNode.h
@@ -650,6 +654,6 @@ list(APPEND INC
${CMAKE_CURRENT_BINARY_DIR}/operations
)
data_to_c(${CMAKE_CURRENT_SOURCE_DIR}/operations/COM_OpenCLKernels.cl
- ${CMAKE_CURRENT_BINARY_DIR}/operations/COM_OpenCLKernels.cl.h SRC)
+ ${CMAKE_CURRENT_BINARY_DIR}/operations/COM_OpenCLKernels.cl.h SRC)
blender_add_lib(bf_compositor "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/compositor/intern/COM_Converter.cpp b/source/blender/compositor/intern/COM_Converter.cpp
index 71067ac8f15..2b09c9d5b8c 100644
--- a/source/blender/compositor/intern/COM_Converter.cpp
+++ b/source/blender/compositor/intern/COM_Converter.cpp
@@ -119,6 +119,7 @@
#include "COM_ViewLevelsNode.h"
#include "COM_ViewerNode.h"
#include "COM_ZCombineNode.h"
+#include "COM_PixelateNode.h"
Node *Converter::convert(bNode *b_node, bool fast)
{
@@ -390,6 +391,9 @@ Node *Converter::convert(bNode *b_node, bool fast)
node = new TrackPositionNode(b_node);
break;
/* not inplemented yet */
+ case CMP_NODE_PIXELATE:
+ node = new PixelateNode(b_node);
+ break;
default:
node = new MuteNode(b_node);
break;
diff --git a/source/blender/compositor/intern/COM_ExecutionGroup.cpp b/source/blender/compositor/intern/COM_ExecutionGroup.cpp
index 5c891705089..0553aebbba6 100644
--- a/source/blender/compositor/intern/COM_ExecutionGroup.cpp
+++ b/source/blender/compositor/intern/COM_ExecutionGroup.cpp
@@ -204,7 +204,7 @@ void ExecutionGroup::determineNumberOfChunks()
this->m_numberOfXChunks = 1;
this->m_numberOfYChunks = 1;
this->m_numberOfChunks = 1;
- }
+ }
else {
const float chunkSizef = this->m_chunkSize;
this->m_numberOfXChunks = ceil(this->m_width / chunkSizef);
@@ -475,10 +475,10 @@ bool ExecutionGroup::scheduleAreaWhenPossible(ExecutionSystem *graph, rcti *area
int maxxchunk = ceil((area->xmax - 1) / chunkSizef);
int minychunk = floor(area->ymin / chunkSizef);
int maxychunk = ceil((area->ymax - 1) / chunkSizef);
- minxchunk = MAX2(minxchunk, 0);
- minychunk = MAX2(minychunk, 0);
- maxxchunk = MIN2(maxxchunk, this->m_numberOfXChunks);
- maxychunk = MIN2(maxychunk, this->m_numberOfYChunks);
+ minxchunk = max(minxchunk, 0);
+ minychunk = max(minychunk, 0);
+ maxxchunk = min(maxxchunk, (int)this->m_numberOfXChunks);
+ maxychunk = min(maxychunk, (int)this->m_numberOfYChunks);
bool result = true;
for (indexx = minxchunk; indexx < maxxchunk; indexx++) {
diff --git a/source/blender/compositor/intern/COM_ExecutionSystem.cpp b/source/blender/compositor/intern/COM_ExecutionSystem.cpp
index a13717c9d86..c6e0f6c2cfb 100644
--- a/source/blender/compositor/intern/COM_ExecutionSystem.cpp
+++ b/source/blender/compositor/intern/COM_ExecutionSystem.cpp
@@ -25,6 +25,7 @@
#include <sstream>
#include "PIL_time.h"
+#include "BLI_utildefines.h"
#include "BKE_node.h"
#include "COM_Converter.h"
@@ -50,7 +51,7 @@ ExecutionSystem::ExecutionSystem(RenderData *rd, bNodeTree *editingtree, bool re
this->m_context.setbNodeTree(editingtree);
this->m_context.setFastCalculation(fastcalculation);
bNode *gnode;
- for (gnode = (bNode *)editingtree->nodes.first; gnode; gnode = (bNode *)gnode->next) {
+ for (gnode = (bNode *)editingtree->nodes.first; gnode; gnode = gnode->next) {
if (gnode->type == NODE_GROUP && gnode->typeinfo->group_edit_get(gnode)) {
this->m_context.setActivegNode(gnode);
break;
@@ -240,12 +241,32 @@ void ExecutionSystem::addReadWriteBufferOperations(NodeOperation *operation)
}
}
+#ifndef NDEBUG
+/* if this fails, there are still connection to/from this node,
+ * which have not been properly relinked to operations!
+ */
+static void debug_check_node_connections(Node *node)
+{
+ for (int i = 0; i < node->getNumberOfInputSockets(); ++i) {
+ BLI_assert(!node->getInputSocket(i)->isConnected());
+ }
+ for (int i = 0; i < node->getNumberOfOutputSockets(); ++i) {
+ BLI_assert(!node->getOutputSocket(i)->isConnected());
+ }
+}
+#else
+/* stub */
+#define debug_check_node_connections(node)
+#endif
+
void ExecutionSystem::convertToOperations()
{
unsigned int index;
for (index = 0; index < this->m_nodes.size(); index++) {
Node *node = (Node *)this->m_nodes[index];
node->convertToOperations(this, &this->m_context);
+
+ debug_check_node_connections(node);
}
for (index = 0; index < this->m_connections.size(); index++) {
@@ -315,6 +336,16 @@ void ExecutionSystem::addSocketConnection(SocketConnection *connection)
this->m_connections.push_back(connection);
}
+void ExecutionSystem::removeSocketConnection(SocketConnection *connection)
+{
+ for (vector<SocketConnection *>::iterator it = m_connections.begin(); it != m_connections.end(); ++it) {
+ if (*it == connection) {
+ this->m_connections.erase(it);
+ return;
+ }
+ }
+}
+
void ExecutionSystem::findOutputExecutionGroup(vector<ExecutionGroup *> *result, CompositorPriority priority) const
{
diff --git a/source/blender/compositor/intern/COM_ExecutionSystem.h b/source/blender/compositor/intern/COM_ExecutionSystem.h
index 56a60bf7a03..25f06108d96 100644
--- a/source/blender/compositor/intern/COM_ExecutionSystem.h
+++ b/source/blender/compositor/intern/COM_ExecutionSystem.h
@@ -189,6 +189,11 @@ public:
void addSocketConnection(SocketConnection *connection);
/**
+ * Remove a socket connection from the system.
+ */
+ void removeSocketConnection(SocketConnection *connection);
+
+ /**
* @brief Convert all nodes to operations
*/
void convertToOperations();
diff --git a/source/blender/compositor/intern/COM_ExecutionSystemHelper.cpp b/source/blender/compositor/intern/COM_ExecutionSystemHelper.cpp
index bedbfc72722..506bd42ace3 100644
--- a/source/blender/compositor/intern/COM_ExecutionSystemHelper.cpp
+++ b/source/blender/compositor/intern/COM_ExecutionSystemHelper.cpp
@@ -49,8 +49,9 @@ void ExecutionSystemHelper::addbNodeTree(ExecutionSystem &system, int nodes_star
/* add all nodes of the tree to the node list */
bNode *node = (bNode *)tree->nodes.first;
while (node != NULL) {
- addNode(nodes, node, isActiveGroup, system.getContext().isFastCalculation());
- node = (bNode *)node->next;
+ Node *nnode = addNode(nodes, node, isActiveGroup, system.getContext().isFastCalculation());
+ nnode->setbNodeGroup(groupnode);
+ node = node->next;
}
NodeRange node_range(nodes.begin() + nodes_start, nodes.end());
@@ -59,7 +60,7 @@ void ExecutionSystemHelper::addbNodeTree(ExecutionSystem &system, int nodes_star
bNodeLink *nodelink = (bNodeLink *)tree->links.first;
while (nodelink != NULL) {
addNodeLink(node_range, links, nodelink);
- nodelink = (bNodeLink *)nodelink->next;
+ nodelink = nodelink->next;
}
/* Expand group nodes */
diff --git a/source/blender/compositor/intern/COM_InputSocket.cpp b/source/blender/compositor/intern/COM_InputSocket.cpp
index a9c280e0367..2493d4e5a27 100644
--- a/source/blender/compositor/intern/COM_InputSocket.cpp
+++ b/source/blender/compositor/intern/COM_InputSocket.cpp
@@ -122,6 +122,17 @@ void InputSocket::relinkConnections(InputSocket *relinkToSocket, int editorNode
}
}
+void InputSocket::unlinkConnections(ExecutionSystem *system)
+{
+ SocketConnection *connection = getConnection();
+ if (connection) {
+ system->removeSocketConnection(connection);
+ connection->getFromSocket()->removeConnection(connection);
+ setConnection(NULL);
+ delete connection;
+ }
+}
+
bool InputSocket::isStatic()
{
if (isConnected()) {
diff --git a/source/blender/compositor/intern/COM_InputSocket.h b/source/blender/compositor/intern/COM_InputSocket.h
index 259479015aa..5cd4cf3beb7 100644
--- a/source/blender/compositor/intern/COM_InputSocket.h
+++ b/source/blender/compositor/intern/COM_InputSocket.h
@@ -87,17 +87,11 @@ public:
/**
* @brief determine the resolution of this data going through this socket
* @param resolution the result of this operation
- * @param preferredResolution the preferrable resolution as no resolution could be determined
+ * @param preferredResolution the preferable resolution as no resolution could be determined
*/
void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]);
/**
- * @brief Notifies the Input of the data type (via a SocketConnection)
- * @param datatype the datatype to evaluate
- */
- void notifyActualInputType(DataType datatype);
-
- /**
* @brief move all connections of this input socket to another socket
* only use this method when already checked the availability of a SocketConnection
* @param relinkToSocket the socket to move to connections to
@@ -114,7 +108,8 @@ public:
void relinkConnections(InputSocket *relinkToSocket, int editorNodeInputSocketIndex, ExecutionSystem *system);
/**
- * @brief move all connections of this input socket to another socket
+ * @brief add a connection of this input socket to another socket
+ * @warning make sure to remove the original connection with \a unlinkConnections afterward.
* @param relinkToSocket the socket to move to connections to
* @param editorNodeInputSocketIndex index of the socket number of the bNode (used to retrieve the value for autoconnection)
* @param system ExecutionSystem to update to
@@ -122,6 +117,13 @@ public:
void relinkConnectionsDuplicate(InputSocket *relinkToSocket, int editorNodeInputSocketIndex, ExecutionSystem *system);
/**
+ * @brief remove all connections of this input socket.
+ * @warning \a relinkConnectionsDuplicate should be used to ensure this socket is still connected.
+ * @param system ExecutionSystem to update to
+ */
+ void unlinkConnections(ExecutionSystem *system);
+
+ /**
* @brief set the resize mode
* @param resizeMode the new resize mode.
*/
diff --git a/source/blender/compositor/intern/COM_MemoryBuffer.cpp b/source/blender/compositor/intern/COM_MemoryBuffer.cpp
index 0994f3f8890..357a4c1d4c0 100644
--- a/source/blender/compositor/intern/COM_MemoryBuffer.cpp
+++ b/source/blender/compositor/intern/COM_MemoryBuffer.cpp
@@ -160,7 +160,7 @@ void MemoryBuffer::writePixel(int x, int y, const float color[4])
if (x >= this->m_rect.xmin && x < this->m_rect.xmax &&
y >= this->m_rect.ymin && y < this->m_rect.ymax)
{
- const int offset = (this->m_chunkWidth * (y-this->m_rect.ymin) + x-this->m_rect.xmin) * COM_NUMBER_OF_CHANNELS;
+ const int offset = (this->m_chunkWidth * (y - this->m_rect.ymin) + x - this->m_rect.xmin) * COM_NUMBER_OF_CHANNELS;
copy_v4_v4(&this->m_buffer[offset], color);
}
}
@@ -170,7 +170,7 @@ void MemoryBuffer::addPixel(int x, int y, const float color[4])
if (x >= this->m_rect.xmin && x < this->m_rect.xmax &&
y >= this->m_rect.ymin && y < this->m_rect.ymax)
{
- const int offset = (this->m_chunkWidth * (y-this->m_rect.ymin) + x-this->m_rect.xmin) * COM_NUMBER_OF_CHANNELS;
+ const int offset = (this->m_chunkWidth * (y - this->m_rect.ymin) + x - this->m_rect.xmin) * COM_NUMBER_OF_CHANNELS;
add_v4_v4(&this->m_buffer[offset], color);
}
}
@@ -253,7 +253,7 @@ static void imp2radangle(float A, float B, float C, float F, float *a, float *b,
}
}
-float clipuv(float x, float limit)
+static float clipuv(float x, float limit)
{
x = (x < 0) ? 0 : ((x >= limit) ? (limit - 1) : x);
return x;
diff --git a/source/blender/compositor/intern/COM_Node.cpp b/source/blender/compositor/intern/COM_Node.cpp
index 5922b0e6b08..300d7ef1952 100644
--- a/source/blender/compositor/intern/COM_Node.cpp
+++ b/source/blender/compositor/intern/COM_Node.cpp
@@ -51,7 +51,7 @@ Node::Node(bNode *editorNode, bool create_sockets): NodeBase()
if (input->type == SOCK_VECTOR) dt = COM_DT_VECTOR;
this->addInputSocket(dt, (InputSocketResizeMode)input->resizemode, input);
- input = (bNodeSocket *)input->next;
+ input = input->next;
}
bNodeSocket *output = (bNodeSocket *)editorNode->outputs.first;
while (output != NULL) {
@@ -60,14 +60,14 @@ Node::Node(bNode *editorNode, bool create_sockets): NodeBase()
if (output->type == SOCK_VECTOR) dt = COM_DT_VECTOR;
this->addOutputSocket(dt, output);
- output = (bNodeSocket *)output->next;
+ output = output->next;
}
}
}
void Node::addSetValueOperation(ExecutionSystem *graph, InputSocket *inputsocket, int editorNodeInputSocketIndex)
{
- bNodeSocket *bSock = (bNodeSocket *)this->getEditorInputSocket(editorNodeInputSocketIndex);
+ bNodeSocket *bSock = this->getEditorInputSocket(editorNodeInputSocketIndex);
SetValueOperation *operation = new SetValueOperation();
bNodeSocketValueFloat *val = (bNodeSocketValueFloat *)bSock->default_value;
operation->setValue(val->value);
@@ -114,7 +114,7 @@ SocketConnection *Node::addLink(ExecutionSystem *graph, OutputSocket *outputSock
void Node::addSetColorOperation(ExecutionSystem *graph, InputSocket *inputsocket, int editorNodeInputSocketIndex)
{
- bNodeSocket *bSock = (bNodeSocket *)this->getEditorInputSocket(editorNodeInputSocketIndex);
+ bNodeSocket *bSock = this->getEditorInputSocket(editorNodeInputSocketIndex);
SetColorOperation *operation = new SetColorOperation();
bNodeSocketValueRGBA *val = (bNodeSocketValueRGBA *)bSock->default_value;
operation->setChannel1(val->value[0]);
@@ -127,7 +127,7 @@ void Node::addSetColorOperation(ExecutionSystem *graph, InputSocket *inputsocket
void Node::addSetVectorOperation(ExecutionSystem *graph, InputSocket *inputsocket, int editorNodeInputSocketIndex)
{
- bNodeSocket *bSock = (bNodeSocket *)this->getEditorInputSocket(editorNodeInputSocketIndex);
+ bNodeSocket *bSock = this->getEditorInputSocket(editorNodeInputSocketIndex);
bNodeSocketValueVector *val = (bNodeSocketValueVector *)bSock->default_value;
SetVectorOperation *operation = new SetVectorOperation();
operation->setX(val->value[0]);
diff --git a/source/blender/compositor/intern/COM_Node.h b/source/blender/compositor/intern/COM_Node.h
index bfccd069ad1..468a95ed434 100644
--- a/source/blender/compositor/intern/COM_Node.h
+++ b/source/blender/compositor/intern/COM_Node.h
@@ -20,8 +20,8 @@
* Monique Dewanchand
*/
-#ifndef _COM_Node_h
-#define _COM_Node_h
+#ifndef __COM_NODE_H__
+#define __COM_NODE_H__
#include "COM_NodeBase.h"
#include "COM_InputSocket.h"
@@ -53,6 +53,12 @@ private:
* @brief Is this node part of the active group
*/
bool m_inActiveGroup;
+
+ /**
+ * @brief The group node this node belongs to.
+ * @note: used to find the links in the current subtree for muting nodes
+ */
+ bNode* m_bNodeGroup;
public:
Node(bNode *editorNode, bool create_sockets = true);
@@ -134,6 +140,9 @@ public:
* @param socket
*/
OutputSocket *findOutputSocketBybNodeSocket(bNodeSocket *socket);
+
+ inline void setbNodeGroup(bNode* group) {this->m_bNodeGroup = group;}
+ inline bNode* getbNodeGroup() {return this->m_bNodeGroup;}
protected:
void addPreviewOperation(ExecutionSystem *system, CompositorContext *context, InputSocket *inputSocket);
void addPreviewOperation(ExecutionSystem *system, CompositorContext *context, OutputSocket *outputSocket);
@@ -143,4 +152,4 @@ protected:
private:
};
-#endif
+#endif /* __COM_NODE_H__ */
diff --git a/source/blender/compositor/intern/COM_NodeBase.h b/source/blender/compositor/intern/COM_NodeBase.h
index b55e444be80..e386b5e08a0 100644
--- a/source/blender/compositor/intern/COM_NodeBase.h
+++ b/source/blender/compositor/intern/COM_NodeBase.h
@@ -20,8 +20,8 @@
* Monique Dewanchand
*/
-#ifndef _COM_NodeBase_h
-#define _COM_NodeBase_h
+#ifndef __COM_NODEBASE_H__
+#define __COM_NODEBASE_H__
#include "COM_InputSocket.h"
#include "COM_OutputSocket.h"
@@ -97,7 +97,7 @@ public:
* @return [true:false]
* @see NodeOperation
*/
- virtual const int isOperation() const { return false; }
+ virtual const bool isOperation() const { return false; }
/**
* @brief check if this is an input node
@@ -166,4 +166,4 @@ protected:
#endif
};
-#endif
+#endif /* __COM_NODEBASE_H__ */
diff --git a/source/blender/compositor/intern/COM_NodeOperation.cpp b/source/blender/compositor/intern/COM_NodeOperation.cpp
index 4ae114bd031..a05c37e1b09 100644
--- a/source/blender/compositor/intern/COM_NodeOperation.cpp
+++ b/source/blender/compositor/intern/COM_NodeOperation.cpp
@@ -126,7 +126,7 @@ bool NodeOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOper
else {
rcti tempOutput;
bool first = true;
- for (int i = 0 ; i < getNumberOfInputSockets() ; i ++) {
+ for (int i = 0; i < getNumberOfInputSockets(); i ++) {
NodeOperation * inputOperation = this->getInputOperation(i);
if (inputOperation && inputOperation->determineDependingAreaOfInterest(input, readOperation, &tempOutput)) {
if (first) {
@@ -137,10 +137,10 @@ bool NodeOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOper
first = false;
}
else {
- output->xmin = MIN2(output->xmin, tempOutput.xmin);
- output->ymin = MIN2(output->ymin, tempOutput.ymin);
- output->xmax = MAX2(output->xmax, tempOutput.xmax);
- output->ymax = MAX2(output->ymax, tempOutput.ymax);
+ output->xmin = min(output->xmin, tempOutput.xmin);
+ output->ymin = min(output->ymin, tempOutput.ymin);
+ output->xmax = max(output->xmax, tempOutput.xmax);
+ output->ymax = max(output->ymax, tempOutput.ymax);
}
}
}
diff --git a/source/blender/compositor/intern/COM_NodeOperation.h b/source/blender/compositor/intern/COM_NodeOperation.h
index 93a19529d34..42d90eca38f 100644
--- a/source/blender/compositor/intern/COM_NodeOperation.h
+++ b/source/blender/compositor/intern/COM_NodeOperation.h
@@ -88,13 +88,13 @@ public:
* @return [true:false]
* @see NodeBase
*/
- const int isOperation() const { return true; }
+ const bool isOperation() const { return true; }
/**
* @brief determine the resolution of this node
* @note this method will not set the resolution, this is the responsibility of the caller
* @param resolution the result of this operation
- * @param preferredResolution the preferrable resolution as no resolution could be determined
+ * @param preferredResolution the preferable resolution as no resolution could be determined
*/
virtual void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]);
@@ -163,7 +163,10 @@ public:
* @param clMemToCleanUp all created cl_mem references must be added to this list. Framework will clean this after execution
* @param clKernelsToCleanUp all created cl_kernel references must be added to this list. Framework will clean this after execution
*/
- virtual void executeOpenCL(OpenCLDevice *device, MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, MemoryBuffer **inputMemoryBuffers, list<cl_mem> *clMemToCleanUp, list<cl_kernel> *clKernelsToCleanUp) {}
+ virtual void executeOpenCL(OpenCLDevice *device,
+ MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer,
+ MemoryBuffer **inputMemoryBuffers, list<cl_mem> *clMemToCleanUp,
+ list<cl_kernel> *clKernelsToCleanUp) {}
virtual void deinitExecution();
bool isResolutionSet() {
diff --git a/source/blender/compositor/intern/COM_OpenCLDevice.cpp b/source/blender/compositor/intern/COM_OpenCLDevice.cpp
index d23ed245844..d5da079c9fd 100644
--- a/source/blender/compositor/intern/COM_OpenCLDevice.cpp
+++ b/source/blender/compositor/intern/COM_OpenCLDevice.cpp
@@ -74,7 +74,7 @@ cl_mem OpenCLDevice::COM_clAttachMemoryBufferToKernelParameter(cl_kernel kernel,
{
cl_int error;
- MemoryBuffer *result = (MemoryBuffer *)reader->getInputMemoryBuffer(inputMemoryBuffers);
+ MemoryBuffer *result = reader->getInputMemoryBuffer(inputMemoryBuffers);
const cl_image_format imageFormat = {
CL_RGBA,
diff --git a/source/blender/compositor/intern/COM_OutputSocket.cpp b/source/blender/compositor/intern/COM_OutputSocket.cpp
index f23a48979da..50e9b75b072 100644
--- a/source/blender/compositor/intern/COM_OutputSocket.cpp
+++ b/source/blender/compositor/intern/COM_OutputSocket.cpp
@@ -54,6 +54,16 @@ void OutputSocket::addConnection(SocketConnection *connection)
this->m_connections.push_back(connection);
}
+void OutputSocket::removeConnection(SocketConnection *connection)
+{
+ for (vector<SocketConnection *>::iterator it = m_connections.begin(); it != m_connections.end(); ++it) {
+ if (*it == connection) {
+ m_connections.erase(it);
+ return;
+ }
+ }
+}
+
void OutputSocket::relinkConnections(OutputSocket *relinkToSocket, bool single)
{
if (isConnected()) {
diff --git a/source/blender/compositor/intern/COM_OutputSocket.h b/source/blender/compositor/intern/COM_OutputSocket.h
index dc5ca27cbda..709005a6de0 100644
--- a/source/blender/compositor/intern/COM_OutputSocket.h
+++ b/source/blender/compositor/intern/COM_OutputSocket.h
@@ -50,6 +50,7 @@ public:
OutputSocket(DataType datatype, int inputSocketDataTypeDeterminatorIndex);
OutputSocket(OutputSocket *from);
void addConnection(SocketConnection *connection);
+ void removeConnection(SocketConnection *connection);
SocketConnection *getConnection(unsigned int index) { return this->m_connections[index]; }
const int isConnected() const;
int isOutputSocket() const;
@@ -57,14 +58,14 @@ public:
/**
* @brief determine the resolution of this socket
* @param resolution the result of this operation
- * @param preferredResolution the preferrable resolution as no resolution could be determined
+ * @param preferredResolution the preferable resolution as no resolution could be determined
*/
void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]);
/**
* @brief determine the actual data type and channel info.
*/
- void relinkConnections(OutputSocket *relinkToSocket) { this->relinkConnections(relinkToSocket, false); };
+ void relinkConnections(OutputSocket *relinkToSocket) { this->relinkConnections(relinkToSocket, false); }
void relinkConnections(OutputSocket *relinkToSocket, bool single);
const int getNumberOfConnections() { return this->m_connections.size(); }
diff --git a/source/blender/compositor/intern/COM_WorkScheduler.cpp b/source/blender/compositor/intern/COM_WorkScheduler.cpp
index f732a40e768..724abb59bcf 100644
--- a/source/blender/compositor/intern/COM_WorkScheduler.cpp
+++ b/source/blender/compositor/intern/COM_WorkScheduler.cpp
@@ -25,6 +25,7 @@
#include "BKE_global.h"
+#include "COM_compositor.h"
#include "COM_WorkScheduler.h"
#include "COM_CPUDevice.h"
#include "COM_OpenCLDevice.h"
@@ -105,13 +106,11 @@ void **g_highlightedNodesRead;
void COM_startReadHighlights()
{
- if (!g_highlightInitialized)
- {
+ if (!g_highlightInitialized) {
return;
}
- if (g_highlightedNodesRead)
- {
+ if (g_highlightedNodesRead) {
MEM_freeN(g_highlightedNodesRead);
}
@@ -265,7 +264,7 @@ bool WorkScheduler::hasGPUDevices()
#endif
}
-extern void clContextError(const char *errinfo, const void *private_info, size_t cb, void *user_data)
+static void clContextError(const char *errinfo, const void *private_info, size_t cb, void *user_data)
{
printf("OPENCL error: %s\n", errinfo);
}
@@ -331,10 +330,10 @@ void WorkScheduler::initialize(bool use_opencl)
const char *cl_str[2] = {datatoc_COM_OpenCLKernels_cl, NULL};
g_program = clCreateProgramWithSource(g_context, 1, cl_str, 0, &error);
error = clBuildProgram(g_program, numberOfDevices, cldevices, 0, 0, 0);
- if (error != CL_SUCCESS) {
+ if (error != CL_SUCCESS) {
cl_int error2;
size_t ret_val_size = 0;
- printf("CLERROR[%d]: %s\n", error, clewErrorString(error));
+ printf("CLERROR[%d]: %s\n", error, clewErrorString(error));
error2 = clGetProgramBuildInfo(g_program, cldevices[0], CL_PROGRAM_BUILD_LOG, 0, NULL, &ret_val_size);
if (error2 != CL_SUCCESS) { printf("CLERROR[%d]: %s\n", error, clewErrorString(error)); }
char *build_log = (char *)MEM_mallocN(sizeof(char) * ret_val_size + 1, __func__);
diff --git a/source/blender/compositor/intern/COM_compositor.cpp b/source/blender/compositor/intern/COM_compositor.cpp
index 5cfcd83f8f1..49ab9db5dd8 100644
--- a/source/blender/compositor/intern/COM_compositor.cpp
+++ b/source/blender/compositor/intern/COM_compositor.cpp
@@ -37,7 +37,7 @@ extern "C" {
static ThreadMutex s_compositorMutex;
static char is_compositorMutex_init = FALSE;
-void intern_freeCompositorCaches()
+static void intern_freeCompositorCaches()
{
deintializeDistortionCache();
}
@@ -93,7 +93,7 @@ void COM_execute(RenderData *rd, bNodeTree *editingtree, int rendering,
BLI_mutex_unlock(&s_compositorMutex);
}
-void COM_freeCaches()
+static void UNUSED_FUNCTION(COM_freeCaches)()
{
if (is_compositorMutex_init) {
BLI_mutex_lock(&s_compositorMutex);
@@ -102,7 +102,7 @@ void COM_freeCaches()
}
}
-void COM_deinitialize()
+void COM_deinitialize()
{
if (is_compositorMutex_init) {
BLI_mutex_lock(&s_compositorMutex);
diff --git a/source/blender/compositor/nodes/COM_ChannelMatteNode.h b/source/blender/compositor/nodes/COM_ChannelMatteNode.h
index 4efb06c9f87..29c6000a245 100644
--- a/source/blender/compositor/nodes/COM_ChannelMatteNode.h
+++ b/source/blender/compositor/nodes/COM_ChannelMatteNode.h
@@ -34,4 +34,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // COM_ChannelMatteNODE_H
+#endif /* COM_ChannelMatteNODE_H */
diff --git a/source/blender/compositor/nodes/COM_ChromaMatteNode.h b/source/blender/compositor/nodes/COM_ChromaMatteNode.h
index ddd350aab40..bf5302ccdbb 100644
--- a/source/blender/compositor/nodes/COM_ChromaMatteNode.h
+++ b/source/blender/compositor/nodes/COM_ChromaMatteNode.h
@@ -34,4 +34,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // COM_ChromaMatteNODE_H
+#endif /* COM_ChromaMatteNODE_H */
diff --git a/source/blender/compositor/nodes/COM_ColorBalanceNode.h b/source/blender/compositor/nodes/COM_ColorBalanceNode.h
index cdad02fc831..30d22ef2e63 100644
--- a/source/blender/compositor/nodes/COM_ColorBalanceNode.h
+++ b/source/blender/compositor/nodes/COM_ColorBalanceNode.h
@@ -35,4 +35,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // COM_ColorBalanceNODE_H
+#endif /* COM_ColorBalanceNODE_H */
diff --git a/source/blender/compositor/nodes/COM_ColorMatteNode.h b/source/blender/compositor/nodes/COM_ColorMatteNode.h
index 92a4fa79408..3386476bc85 100644
--- a/source/blender/compositor/nodes/COM_ColorMatteNode.h
+++ b/source/blender/compositor/nodes/COM_ColorMatteNode.h
@@ -34,4 +34,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // COM_ColorMatteNODE_H
+#endif /* COM_ColorMatteNODE_H */
diff --git a/source/blender/compositor/nodes/COM_ColorRampNode.h b/source/blender/compositor/nodes/COM_ColorRampNode.h
index 6c256c09e68..3f00e1c2190 100644
--- a/source/blender/compositor/nodes/COM_ColorRampNode.h
+++ b/source/blender/compositor/nodes/COM_ColorRampNode.h
@@ -35,4 +35,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // COM_ColorRampNODE_H
+#endif /* COM_ColorRampNODE_H */
diff --git a/source/blender/compositor/nodes/COM_ColorSpillNode.h b/source/blender/compositor/nodes/COM_ColorSpillNode.h
index 1d976fc65ae..01722fac826 100644
--- a/source/blender/compositor/nodes/COM_ColorSpillNode.h
+++ b/source/blender/compositor/nodes/COM_ColorSpillNode.h
@@ -35,4 +35,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // COM_ColorSpillNODE_H
+#endif /* COM_ColorSpillNODE_H */
diff --git a/source/blender/compositor/nodes/COM_ConvertAlphaNode.cpp b/source/blender/compositor/nodes/COM_ConvertAlphaNode.cpp
index 70aeee8fc27..254dfb7b9c7 100644
--- a/source/blender/compositor/nodes/COM_ConvertAlphaNode.cpp
+++ b/source/blender/compositor/nodes/COM_ConvertAlphaNode.cpp
@@ -35,7 +35,7 @@ void ConvertAlphaNode::convertToOperations(ExecutionSystem *graph, CompositorCon
}
else {
operation = new ConvertKeyToPremulOperation();
- }
+ }
this->getInputSocket(0)->relinkConnections(operation->getInputSocket(0), 0, graph);
this->getOutputSocket(0)->relinkConnections(operation->getOutputSocket());
diff --git a/source/blender/compositor/nodes/COM_CropNode.cpp b/source/blender/compositor/nodes/COM_CropNode.cpp
index b80a3e088f2..f09bb7e1c26 100644
--- a/source/blender/compositor/nodes/COM_CropNode.cpp
+++ b/source/blender/compositor/nodes/COM_CropNode.cpp
@@ -40,7 +40,7 @@ void CropNode::convertToOperations(ExecutionSystem *graph, CompositorContext *co
operation = new CropImageOperation();
}
else {
- operation = new CropOperation();
+ operation = new CropOperation();
}
operation->setCropSettings(cropSettings);
operation->setRelative(relative);
diff --git a/source/blender/compositor/nodes/COM_DifferenceMatteNode.h b/source/blender/compositor/nodes/COM_DifferenceMatteNode.h
index 191b7361c3c..0b571889571 100644
--- a/source/blender/compositor/nodes/COM_DifferenceMatteNode.h
+++ b/source/blender/compositor/nodes/COM_DifferenceMatteNode.h
@@ -35,4 +35,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // COM_DifferenceMatteNODE_H
+#endif /* COM_DifferenceMatteNODE_H */
diff --git a/source/blender/compositor/nodes/COM_DilateErodeNode.cpp b/source/blender/compositor/nodes/COM_DilateErodeNode.cpp
index 5bd2f78d8a6..0fb7ea7d264 100644
--- a/source/blender/compositor/nodes/COM_DilateErodeNode.cpp
+++ b/source/blender/compositor/nodes/COM_DilateErodeNode.cpp
@@ -79,7 +79,7 @@ void DilateErodeNode::convertToOperations(ExecutionSystem *graph, CompositorCont
CompositorQuality quality = context->getQuality();
/* initialize node data */
- NodeBlurData *data = (NodeBlurData *)&this->m_alpha_blur;
+ NodeBlurData *data = &this->m_alpha_blur;
memset(data, 0, sizeof(*data));
data->filtertype = R_FILTER_GAUSS;
@@ -95,6 +95,7 @@ void DilateErodeNode::convertToOperations(ExecutionSystem *graph, CompositorCont
operationx->setbNode(editorNode);
operationx->setData(data);
operationx->setQuality(quality);
+ operationx->setFalloff(PROP_SMOOTH);
this->getInputSocket(0)->relinkConnections(operationx->getInputSocket(0), 0, graph);
// this->getInputSocket(1)->relinkConnections(operationx->getInputSocket(1), 1, graph); // no size input yet
graph->addOperation(operationx);
@@ -102,6 +103,7 @@ void DilateErodeNode::convertToOperations(ExecutionSystem *graph, CompositorCont
operationy->setbNode(editorNode);
operationy->setData(data);
operationy->setQuality(quality);
+ operationy->setFalloff(PROP_SMOOTH);
this->getOutputSocket(0)->relinkConnections(operationy->getOutputSocket());
graph->addOperation(operationy);
addLink(graph, operationx->getOutputSocket(), operationy->getInputSocket(0));
diff --git a/source/blender/compositor/nodes/COM_DistanceMatteNode.h b/source/blender/compositor/nodes/COM_DistanceMatteNode.h
index 4e6682424e8..46ceae7c4f4 100644
--- a/source/blender/compositor/nodes/COM_DistanceMatteNode.h
+++ b/source/blender/compositor/nodes/COM_DistanceMatteNode.h
@@ -34,4 +34,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // COM_DistanceMatteNODE_H
+#endif /* COM_DistanceMatteNODE_H */
diff --git a/source/blender/compositor/nodes/COM_FilterNode.h b/source/blender/compositor/nodes/COM_FilterNode.h
index d65166944d8..9be3bb02494 100644
--- a/source/blender/compositor/nodes/COM_FilterNode.h
+++ b/source/blender/compositor/nodes/COM_FilterNode.h
@@ -20,8 +20,8 @@
* Monique Dewanchand
*/
-#ifndef _COM_FilterNode_h_
-#define _COM_FilterNode_h_
+#ifndef __COM_FILTERNODE_H__
+#define __COM_FILTERNODE_H__
#include "COM_Node.h"
@@ -35,4 +35,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // _COM_FilterNode_h_
+#endif /* __COM_FILTERNODE_H__ */
diff --git a/source/blender/compositor/nodes/COM_HueSaturationValueNode.cpp b/source/blender/compositor/nodes/COM_HueSaturationValueNode.cpp
index 9b55b809212..29e10db0758 100644
--- a/source/blender/compositor/nodes/COM_HueSaturationValueNode.cpp
+++ b/source/blender/compositor/nodes/COM_HueSaturationValueNode.cpp
@@ -50,7 +50,7 @@ void HueSaturationValueNode::convertToOperations(ExecutionSystem *graph, Composi
ChangeHSVOperation *changeHSV = new ChangeHSVOperation();
MixBlendOperation *blend = new MixBlendOperation();
- colorSocket->relinkConnections(rgbToHSV->getInputSocket(0), 0, graph);
+ colorSocket->relinkConnections(rgbToHSV->getInputSocket(0), 1, graph);
addLink(graph, rgbToHSV->getOutputSocket(), changeHSV->getInputSocket(0));
addLink(graph, changeHSV->getOutputSocket(), hsvToRGB->getInputSocket(0));
addLink(graph, hsvToRGB->getOutputSocket(), blend->getInputSocket(2));
diff --git a/source/blender/compositor/nodes/COM_KeyingNode.cpp b/source/blender/compositor/nodes/COM_KeyingNode.cpp
index 6bc9afba32c..51ea2913e65 100644
--- a/source/blender/compositor/nodes/COM_KeyingNode.cpp
+++ b/source/blender/compositor/nodes/COM_KeyingNode.cpp
@@ -151,7 +151,7 @@ OutputSocket *KeyingNode::setupFeather(ExecutionSystem *graph, CompositorContext
CompositorQuality quality = context->getQuality();
/* initialize node data */
- NodeBlurData *data = (NodeBlurData *)&this->m_alpha_blur;
+ NodeBlurData *data = &this->m_alpha_blur;
memset(data, 0, sizeof(*data));
data->filtertype = R_FILTER_GAUSS;
diff --git a/source/blender/compositor/nodes/COM_LuminanceMatteNode.h b/source/blender/compositor/nodes/COM_LuminanceMatteNode.h
index 37f3c31113f..a71e68cf636 100644
--- a/source/blender/compositor/nodes/COM_LuminanceMatteNode.h
+++ b/source/blender/compositor/nodes/COM_LuminanceMatteNode.h
@@ -19,8 +19,8 @@
* Dalai Felinto
*/
-#ifndef _COM_LuminanceMatteNode_h_
-#define _COM_LuminanceMatteNode_h_
+#ifndef __COM_LUMINANCEMATTENODE_H__
+#define __COM_LUMINANCEMATTENODE_H__
#include "COM_Node.h"
@@ -34,4 +34,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // _COM_LuminanceMatteNode_h_
+#endif /* __COM_LUMINANCEMATTENODE_H__ */
diff --git a/source/blender/compositor/nodes/COM_MapValueNode.h b/source/blender/compositor/nodes/COM_MapValueNode.h
index 22aa5459ec0..bd8e3d08e9c 100644
--- a/source/blender/compositor/nodes/COM_MapValueNode.h
+++ b/source/blender/compositor/nodes/COM_MapValueNode.h
@@ -20,8 +20,8 @@
* Monique Dewanchand
*/
-#ifndef _COM_MapValueNode_h_
-#define _COM_MapValueNode_h_
+#ifndef __COM_MAPVALUENODE_H__
+#define __COM_MAPVALUENODE_H__
#include "COM_Node.h"
#include "DNA_node_types.h"
@@ -35,4 +35,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // _COM_MapValueNode_h_
+#endif /* __COM_MAPVALUENODE_H__ */
diff --git a/source/blender/compositor/nodes/COM_MaskNode.h b/source/blender/compositor/nodes/COM_MaskNode.h
index cdd5d3c362e..9ef3e5deb50 100644
--- a/source/blender/compositor/nodes/COM_MaskNode.h
+++ b/source/blender/compositor/nodes/COM_MaskNode.h
@@ -21,8 +21,8 @@
* Sergey Sharybin
*/
-#ifndef _COM_MaskNode_h_
-#define _COM_MaskNode_h_
+#ifndef __COM_MASKNODE_H__
+#define __COM_MASKNODE_H__
#include "COM_Node.h"
#include "DNA_node_types.h"
@@ -38,4 +38,4 @@ public:
};
-#endif // _COM_MaskNode_h_
+#endif /* __COM_MASKNODE_H__ */
diff --git a/source/blender/compositor/nodes/COM_MovieClipNode.h b/source/blender/compositor/nodes/COM_MovieClipNode.h
index 52ea11ea8e9..2fb38860a34 100644
--- a/source/blender/compositor/nodes/COM_MovieClipNode.h
+++ b/source/blender/compositor/nodes/COM_MovieClipNode.h
@@ -20,8 +20,8 @@
* Monique Dewanchand
*/
-#ifndef _COM_MovieClipNode_h_
-#define _COM_MovieClipNode_h_
+#ifndef __COM_MOVIECLIPNODE_H__
+#define __COM_MOVIECLIPNODE_H__
#include "COM_Node.h"
#include "DNA_node_types.h"
@@ -36,4 +36,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // _COM_MovieClipNode_h_
+#endif /* __COM_MOVIECLIPNODE_H__ */
diff --git a/source/blender/compositor/nodes/COM_MuteNode.cpp b/source/blender/compositor/nodes/COM_MuteNode.cpp
index eb2da147eca..4502dcf469c 100644
--- a/source/blender/compositor/nodes/COM_MuteNode.cpp
+++ b/source/blender/compositor/nodes/COM_MuteNode.cpp
@@ -108,20 +108,16 @@ void MuteNode::convertToOperations(ExecutionSystem *graph, CompositorContext *co
/* mute node is also used for unknown nodes and couple of nodes in fast mode
* can't use generic routines in that case
*/
- if ((editorNode->flag & NODE_MUTED) && editorNode->typeinfo->internal_connect) {
+ if (editorNode->flag & NODE_MUTED) {
vector<InputSocket *> &inputsockets = this->getInputSockets();
vector<OutputSocket *> relinkedsockets;
- bNodeTree *editorTree = (bNodeTree *) context->getbNodeTree();
SocketMap socketMap;
- ListBase intlinks;
bNodeLink *link;
- intlinks = editorNode->typeinfo->internal_connect(editorTree, editorNode);
-
this->fillSocketMap<OutputSocket>(outputsockets, socketMap);
this->fillSocketMap<InputSocket>(inputsockets, socketMap);
- for (link = (bNodeLink *) intlinks.first; link; link = link->next) {
+ for (link = (bNodeLink *) editorNode->internal_links.first; link; link = link->next) {
if (link->fromnode == editorNode) {
InputSocket *fromSocket = (InputSocket *) socketMap.find(link->fromsock)->second;
OutputSocket *toSocket = (OutputSocket *) socketMap.find(link->tosock)->second;
@@ -163,8 +159,6 @@ void MuteNode::convertToOperations(ExecutionSystem *graph, CompositorContext *co
createDefaultOutput(graph, output);
}
}
-
- BLI_freelistN(&intlinks);
}
else {
for (unsigned int index = 0; index < outputsockets.size(); index++) {
diff --git a/source/blender/compositor/nodes/COM_NormalNode.h b/source/blender/compositor/nodes/COM_NormalNode.h
index 660d90040bd..64d4e3a3656 100644
--- a/source/blender/compositor/nodes/COM_NormalNode.h
+++ b/source/blender/compositor/nodes/COM_NormalNode.h
@@ -35,4 +35,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // COM_NormalNODE_H
+#endif /* COM_NormalNODE_H */
diff --git a/source/blender/compositor/nodes/COM_PixelateNode.cpp b/source/blender/compositor/nodes/COM_PixelateNode.cpp
new file mode 100644
index 00000000000..f1c7c616a30
--- /dev/null
+++ b/source/blender/compositor/nodes/COM_PixelateNode.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2011, Blender Foundation.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor:
+ * Jeroen Bakker
+ * Monique Dewanchand
+ */
+
+#include "COM_PixelateNode.h"
+
+#include "COM_PixelateOperation.h"
+#include "COM_ExecutionSystem.h"
+
+PixelateNode::PixelateNode(bNode *editorNode) : Node(editorNode)
+{
+ /* pass */
+}
+
+void PixelateNode::convertToOperations(ExecutionSystem *graph, CompositorContext *context)
+{
+ InputSocket *inputSocket = this->getInputSocket(0);
+ OutputSocket *outputSocket = this->getOutputSocket(0);
+ DataType datatype = inputSocket->getDataType();
+ if (inputSocket->isConnected()) {
+ SocketConnection * connection = inputSocket->getConnection();
+ OutputSocket* otherOutputSocket = connection->getFromSocket();
+ datatype = otherOutputSocket->getDataType();
+ }
+
+ PixelateOperation *operation = new PixelateOperation(datatype);
+ inputSocket->relinkConnections(operation->getInputSocket(0), 0, graph);
+ outputSocket->relinkConnections(operation->getOutputSocket(0));
+ graph->addOperation(operation);
+}
diff --git a/source/blender/compositor/nodes/COM_PixelateNode.h b/source/blender/compositor/nodes/COM_PixelateNode.h
new file mode 100644
index 00000000000..c142d2d7a5b
--- /dev/null
+++ b/source/blender/compositor/nodes/COM_PixelateNode.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2011, Blender Foundation.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor:
+ * Jeroen Bakker
+ * Monique Dewanchand
+ */
+
+#ifndef _COM_PixelateNode_h_
+#define _COM_PixelateNode_h_
+
+#include "COM_Node.h"
+
+/**
+ * @brief PixelateNode
+ * @ingroup Node
+ */
+class PixelateNode : public Node {
+public:
+ PixelateNode(bNode *editorNode);
+ void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
+};
+
+#endif
diff --git a/source/blender/compositor/nodes/COM_SeparateRGBANode.cpp b/source/blender/compositor/nodes/COM_SeparateRGBANode.cpp
index 67ac6ffc388..7fcdebadb46 100644
--- a/source/blender/compositor/nodes/COM_SeparateRGBANode.cpp
+++ b/source/blender/compositor/nodes/COM_SeparateRGBANode.cpp
@@ -70,4 +70,7 @@ void SeparateRGBANode::convertToOperations(ExecutionSystem *graph, CompositorCon
outputASocket->relinkConnections(operation->getOutputSocket(0));
graph->addOperation(operation);
}
+
+ /* remove the original connection to the node, this has been duplicated for all operations */
+ imageSocket->unlinkConnections(graph);
}
diff --git a/source/blender/compositor/nodes/COM_TransformNode.h b/source/blender/compositor/nodes/COM_TransformNode.h
index 57a7a0229ec..666f2da775e 100644
--- a/source/blender/compositor/nodes/COM_TransformNode.h
+++ b/source/blender/compositor/nodes/COM_TransformNode.h
@@ -20,8 +20,8 @@
* Monique Dewanchand
*/
-#ifndef _COM_TransformNode_h_
-#define _COM_TransformNode_h_
+#ifndef __COM_TRANSFORMNODE_H__
+#define __COM_TRANSFORMNODE_H__
#include "COM_Node.h"
#include "DNA_node_types.h"
@@ -36,4 +36,4 @@ public:
void convertToOperations(ExecutionSystem *graph, CompositorContext *context);
};
-#endif // _COM_TransformNode_h_
+#endif /* __COM_TRANSFORMNODE_H__ */
diff --git a/source/blender/compositor/nodes/COM_ViewLevelsNode.cpp b/source/blender/compositor/nodes/COM_ViewLevelsNode.cpp
index 6bb873e0dec..a515bfc7f47 100644
--- a/source/blender/compositor/nodes/COM_ViewLevelsNode.cpp
+++ b/source/blender/compositor/nodes/COM_ViewLevelsNode.cpp
@@ -24,6 +24,7 @@
#include "COM_ExecutionSystem.h"
#include "COM_CalculateMeanOperation.h"
#include "COM_CalculateStandardDeviationOperation.h"
+#include "COM_SetValueOperation.h"
ViewLevelsNode::ViewLevelsNode(bNode *editorNode) : Node(editorNode)
{
@@ -64,5 +65,18 @@ void ViewLevelsNode::convertToOperations(ExecutionSystem *graph, CompositorConte
graph->addOperation(operation);
}
}
+ else {
+ SetValueOperation *meanOutput = new SetValueOperation();
+ SetValueOperation *stdDevOutput = new SetValueOperation();
+
+ meanOutput->setValue(0.0f);
+ stdDevOutput->setValue(0.0f);
+
+ this->getOutputSocket(0)->relinkConnections(meanOutput->getOutputSocket());
+ this->getOutputSocket(1)->relinkConnections(stdDevOutput->getOutputSocket());
+
+ graph->addOperation(meanOutput);
+ graph->addOperation(stdDevOutput);
+ }
}
diff --git a/source/blender/compositor/nodes/COM_ViewerNode.cpp b/source/blender/compositor/nodes/COM_ViewerNode.cpp
index d67e9e274b0..f44470a9b9a 100644
--- a/source/blender/compositor/nodes/COM_ViewerNode.cpp
+++ b/source/blender/compositor/nodes/COM_ViewerNode.cpp
@@ -52,8 +52,7 @@ void ViewerNode::convertToOperations(ExecutionSystem *graph, CompositorContext *
viewerOperation->setDisplaySettings(context->getDisplaySettings());
viewerOperation->setResolutionInputSocketIndex(0);
- if (!imageSocket->isConnected())
- {
+ if (!imageSocket->isConnected()) {
if (alphaSocket->isConnected()) {
viewerOperation->setResolutionInputSocketIndex(1);
}
diff --git a/source/blender/compositor/operations/COM_BokehBlurOperation.h b/source/blender/compositor/operations/COM_BokehBlurOperation.h
index 37483d3dc69..74ca6b7b058 100644
--- a/source/blender/compositor/operations/COM_BokehBlurOperation.h
+++ b/source/blender/compositor/operations/COM_BokehBlurOperation.h
@@ -59,6 +59,9 @@ public:
void setSize(float size) { this->m_size = size; this->m_sizeavailable = true; }
- void executeOpenCL(OpenCLDevice *device, MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, MemoryBuffer **inputMemoryBuffers, list<cl_mem> *clMemToCleanUp, list<cl_kernel> *clKernelsToCleanUp);
+ void executeOpenCL(OpenCLDevice *device,
+ MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer,
+ MemoryBuffer **inputMemoryBuffers, list<cl_mem> *clMemToCleanUp,
+ list<cl_kernel> *clKernelsToCleanUp);
};
#endif
diff --git a/source/blender/compositor/operations/COM_ColorSpillOperation.cpp b/source/blender/compositor/operations/COM_ColorSpillOperation.cpp
index 152b10709fb..a8e8cb98564 100644
--- a/source/blender/compositor/operations/COM_ColorSpillOperation.cpp
+++ b/source/blender/compositor/operations/COM_ColorSpillOperation.cpp
@@ -100,7 +100,7 @@ void ColorSpillOperation::executePixel(float output[4], float x, float y, PixelS
}
else {
copy_v4_v4(output, input);
- }
+ }
}
float ColorSpillOperation::calculateMapValue(float fac, float *input)
{
diff --git a/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.cpp b/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.cpp
index 88289f12ebb..f39a28b87a8 100644
--- a/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.cpp
+++ b/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.cpp
@@ -64,8 +64,8 @@ void ConvertDepthToRadiusOperation::initExecution()
this->m_inverseFocalDistance = 1.0f / focalDistance;
this->m_aspect = (this->getWidth() > this->getHeight()) ? (this->getHeight() / (float)this->getWidth()) : (this->getWidth() / (float)this->getHeight());
this->m_aperture = 0.5f * (this->m_cam_lens / (this->m_aspect * cam_sensor)) / this->m_fStop;
- float minsz = min(getWidth(), getHeight());
- this->m_dof_sp = (float)minsz / ((cam_sensor / 2.0f) / this->m_cam_lens); // <- == aspect * MIN2(img->x, img->y) / tan(0.5f * fov);
+ const float minsz = min(getWidth(), getHeight());
+ this->m_dof_sp = minsz / ((cam_sensor / 2.0f) / this->m_cam_lens); // <- == aspect * min(img->x, img->y) / tan(0.5f * fov);
if (this->m_blurPostOperation) {
m_blurPostOperation->setSigma(min(m_aperture * 128.0f, this->m_maxRadius));
diff --git a/source/blender/compositor/operations/COM_CropOperation.cpp b/source/blender/compositor/operations/COM_CropOperation.cpp
index c33bd2544ac..16c19f3ebaa 100644
--- a/source/blender/compositor/operations/COM_CropOperation.cpp
+++ b/source/blender/compositor/operations/COM_CropOperation.cpp
@@ -36,25 +36,28 @@ void CropBaseOperation::updateArea()
SocketReader *inputReference = this->getInputSocketReader(0);
float width = inputReference->getWidth();
float height = inputReference->getHeight();
- if (this->m_relative) {
- this->m_settings->x1 = width * this->m_settings->fac_x1;
- this->m_settings->x2 = width * this->m_settings->fac_x2;
- this->m_settings->y1 = height * this->m_settings->fac_y1;
- this->m_settings->y2 = height * this->m_settings->fac_y2;
- }
- if (width <= this->m_settings->x1 + 1)
- this->m_settings->x1 = width - 1;
- if (height <= this->m_settings->y1 + 1)
- this->m_settings->y1 = height - 1;
- if (width <= this->m_settings->x2 + 1)
- this->m_settings->x2 = width - 1;
- if (height <= this->m_settings->y2 + 1)
- this->m_settings->y2 = height - 1;
- this->m_xmax = MAX2(this->m_settings->x1, this->m_settings->x2) + 1;
- this->m_xmin = MIN2(this->m_settings->x1, this->m_settings->x2);
- this->m_ymax = MAX2(this->m_settings->y1, this->m_settings->y2) + 1;
- this->m_ymin = MIN2(this->m_settings->y1, this->m_settings->y2);
+ if (width > 0.0f && height > 0.0f) {
+ if (this->m_relative) {
+ this->m_settings->x1 = width * this->m_settings->fac_x1;
+ this->m_settings->x2 = width * this->m_settings->fac_x2;
+ this->m_settings->y1 = height * this->m_settings->fac_y1;
+ this->m_settings->y2 = height * this->m_settings->fac_y2;
+ }
+ if (width <= this->m_settings->x1 + 1)
+ this->m_settings->x1 = width - 1;
+ if (height <= this->m_settings->y1 + 1)
+ this->m_settings->y1 = height - 1;
+ if (width <= this->m_settings->x2 + 1)
+ this->m_settings->x2 = width - 1;
+ if (height <= this->m_settings->y2 + 1)
+ this->m_settings->y2 = height - 1;
+
+ this->m_xmax = max(this->m_settings->x1, this->m_settings->x2) + 1;
+ this->m_xmin = min(this->m_settings->x1, this->m_settings->x2);
+ this->m_ymax = max(this->m_settings->y1, this->m_settings->y2) + 1;
+ this->m_ymin = min(this->m_settings->y1, this->m_settings->y2);
+ }
}
void CropBaseOperation::initExecution()
@@ -110,5 +113,10 @@ void CropImageOperation::determineResolution(unsigned int resolution[2], unsigne
void CropImageOperation::executePixel(float output[4], float x, float y, PixelSampler sampler)
{
- this->m_inputOperation->read(output, (x + this->m_xmin), (y + this->m_ymin), sampler);
+ if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) {
+ this->m_inputOperation->read(output, (x + this->m_xmin), (y + this->m_ymin), sampler);
+ }
+ else {
+ zero_v4(output);
+ }
}
diff --git a/source/blender/compositor/operations/COM_CropOperation.h b/source/blender/compositor/operations/COM_CropOperation.h
index ddc7f855bf1..d2f2b15aa36 100644
--- a/source/blender/compositor/operations/COM_CropOperation.h
+++ b/source/blender/compositor/operations/COM_CropOperation.h
@@ -37,7 +37,7 @@ protected:
void updateArea();
public:
- CropBaseOperation();
+ CropBaseOperation();
void initExecution();
void deinitExecution();
void setCropSettings(NodeTwoXYs *settings) { this->m_settings = settings; }
diff --git a/source/blender/compositor/operations/COM_DespeckleOperation.h b/source/blender/compositor/operations/COM_DespeckleOperation.h
index 5b79d7cb7e0..99635e61544 100644
--- a/source/blender/compositor/operations/COM_DespeckleOperation.h
+++ b/source/blender/compositor/operations/COM_DespeckleOperation.h
@@ -27,8 +27,8 @@ private:
float m_threshold;
float m_threshold_neighbour;
- int m_filterWidth;
- int m_filterHeight;
+ // int m_filterWidth;
+ // int m_filterHeight;
protected:
SocketReader *m_inputOperation;
diff --git a/source/blender/compositor/operations/COM_DilateErodeOperation.cpp b/source/blender/compositor/operations/COM_DilateErodeOperation.cpp
index c4b4452fbb0..f0fffa770f8 100644
--- a/source/blender/compositor/operations/COM_DilateErodeOperation.cpp
+++ b/source/blender/compositor/operations/COM_DilateErodeOperation.cpp
@@ -79,7 +79,7 @@ void DilateErodeThresholdOperation::executePixel(float output[4], int x, int y,
const int miny = max(y - this->m_scope, rect->ymin);
const int maxx = min(x + this->m_scope, rect->xmax);
const int maxy = min(y + this->m_scope, rect->ymax);
- const int bufferWidth = BLI_RCT_SIZE_X(rect);
+ const int bufferWidth = BLI_rcti_size_x(rect);
int offset;
this->m_inputProgram->read(inputValue, x, y, NULL);
@@ -199,7 +199,7 @@ void DilateDistanceOperation::executePixel(float output[4], int x, int y, void *
const int miny = max(y - this->m_scope, rect->ymin);
const int maxx = min(x + this->m_scope, rect->xmax);
const int maxy = min(y + this->m_scope, rect->ymax);
- const int bufferWidth = BLI_RCT_SIZE_X(rect);
+ const int bufferWidth = BLI_rcti_size_x(rect);
int offset;
float value = 0.0f;
@@ -273,7 +273,7 @@ void ErodeDistanceOperation::executePixel(float output[4], int x, int y, void *d
const int miny = max(y - this->m_scope, rect->ymin);
const int maxx = min(x + this->m_scope, rect->xmax);
const int maxy = min(y + this->m_scope, rect->ymax);
- const int bufferWidth = BLI_RCT_SIZE_X(rect);
+ const int bufferWidth = BLI_rcti_size_x(rect);
int offset;
float value = 1.0f;
@@ -344,28 +344,28 @@ void *DilateStepOperation::initializeTileData(rcti *rect)
for (y = 0; y < bheight; y++) {
for (x = 0; x < bwidth - 1; x++) {
p = rectf + (bwidth * y + x);
- *p = MAX2(*p, *(p + 1));
+ *p = max(*p, *(p + 1));
}
}
for (y = 0; y < bheight; y++) {
for (x = bwidth - 1; x >= 1; x--) {
p = rectf + (bwidth * y + x);
- *p = MAX2(*p, *(p - 1));
+ *p = max(*p, *(p - 1));
}
}
for (x = 0; x < bwidth; x++) {
for (y = 0; y < bheight - 1; y++) {
p = rectf + (bwidth * y + x);
- *p = MAX2(*p, *(p + bwidth));
+ *p = max(*p, *(p + bwidth));
}
}
for (x = 0; x < bwidth; x++) {
for (y = bheight - 1; y >= 1; y--) {
p = rectf + (bwidth * y + x);
- *p = MAX2(*p, *(p - bwidth));
+ *p = max(*p, *(p - bwidth));
}
}
}
diff --git a/source/blender/compositor/operations/COM_DisplaceOperation.cpp b/source/blender/compositor/operations/COM_DisplaceOperation.cpp
index 31608c88274..1723da11f21 100644
--- a/source/blender/compositor/operations/COM_DisplaceOperation.cpp
+++ b/source/blender/compositor/operations/COM_DisplaceOperation.cpp
@@ -92,8 +92,8 @@ void DisplaceOperation::executePixel(float output[4], int x, int y, void *data)
dxt = p_dx - d_dx;
dyt = p_dy - d_dy;
- dxt = signf(dxt) * maxf(fabsf(dxt), DISPLACE_EPSILON) / this->getWidth();
- dyt = signf(dyt) * maxf(fabsf(dyt), DISPLACE_EPSILON) / this->getHeight();
+ dxt = signf(dxt) * max_ff(fabsf(dxt), DISPLACE_EPSILON) / this->getWidth();
+ dyt = signf(dyt) * max_ff(fabsf(dyt), DISPLACE_EPSILON) / this->getHeight();
/* EWA filtering (without nearest it gets blurry with NO distortion) */
this->m_inputColorProgram->read(output, u, v, dxt, dyt, COM_PS_NEAREST);
diff --git a/source/blender/compositor/operations/COM_DisplaceSimpleOperation.cpp b/source/blender/compositor/operations/COM_DisplaceSimpleOperation.cpp
index 560bbbdd244..c8ebb845bb6 100644
--- a/source/blender/compositor/operations/COM_DisplaceSimpleOperation.cpp
+++ b/source/blender/compositor/operations/COM_DisplaceSimpleOperation.cpp
@@ -51,7 +51,7 @@ void DisplaceSimpleOperation::initExecution()
/* minimum distance (in pixels) a pixel has to be displaced
* in order to take effect */
-#define DISPLACE_EPSILON 0.01f
+// #define DISPLACE_EPSILON 0.01f
void DisplaceSimpleOperation::executePixel(float output[4], float x, float y, PixelSampler sampler)
{
diff --git a/source/blender/compositor/operations/COM_FastGaussianBlurOperation.cpp b/source/blender/compositor/operations/COM_FastGaussianBlurOperation.cpp
index 2b2928c98db..4bdb2591cb7 100644
--- a/source/blender/compositor/operations/COM_FastGaussianBlurOperation.cpp
+++ b/source/blender/compositor/operations/COM_FastGaussianBlurOperation.cpp
@@ -128,8 +128,8 @@ void FastGaussianBlurOperation::IIR_gauss(MemoryBuffer *src, float sigma, unsign
// XXX The YVV macro defined below explicitly expects sources of at least 3x3 pixels,
// so just skiping blur along faulty direction if src's def is below that limit!
- if (src_width < 3) xy &= ~(int) 1;
- if (src_height < 3) xy &= ~(int) 2;
+ if (src_width < 3) xy &= ~1;
+ if (src_height < 3) xy &= ~2;
if (xy < 1) return;
// see "Recursive Gabor Filtering" by Young/VanVliet
@@ -190,7 +190,7 @@ void FastGaussianBlurOperation::IIR_gauss(MemoryBuffer *src, float sigma, unsign
} (void)0
// intermediate buffers
- sz = MAX2(src_width, src_height);
+ sz = max(src_width, src_height);
X = (double *)MEM_callocN(sz * sizeof(double), "IIR_gauss X buf");
Y = (double *)MEM_callocN(sz * sizeof(double), "IIR_gauss Y buf");
W = (double *)MEM_callocN(sz * sizeof(double), "IIR_gauss W buf");
diff --git a/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.cpp
index 8c5e5faf12a..0efead77cd4 100644
--- a/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.cpp
+++ b/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.cpp
@@ -102,12 +102,12 @@ void GaussianAlphaXBlurOperation::executePixel(float output[4], int x, int y, vo
int bufferstarty = inputBuffer->getRect()->ymin;
int miny = y;
- int maxy = y;
+ // int maxy = y; // UNUSED
int minx = x - this->m_rad;
- int maxx = x + this->m_rad;
+ int maxx = x + this->m_rad; // UNUSED
miny = max(miny, inputBuffer->getRect()->ymin);
minx = max(minx, inputBuffer->getRect()->xmin);
- maxy = min(maxy, inputBuffer->getRect()->ymax);
+ // maxy = min(maxy, inputBuffer->getRect()->ymax);
maxx = min(maxx, inputBuffer->getRect()->xmax);
/* *** this is the main part which is different to 'GaussianXBlurOperation' *** */
@@ -123,7 +123,7 @@ void GaussianAlphaXBlurOperation::executePixel(float output[4], int x, int y, vo
float value_max = finv_test(buffer[(x * 4) + (y * 4 * bufferwidth)], do_invert); /* init with the current color to avoid unneeded lookups */
float distfacinv_max = 1.0f; /* 0 to 1 */
- for (int nx = minx; nx < maxx; nx += step) {
+ for (int nx = minx; nx <= maxx; nx += step) {
const int index = (nx - x) + this->m_rad;
float value = finv_test(buffer[bufferindex], do_invert);
float multiplier;
diff --git a/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.cpp
index 197715595ed..1f9cc8e461a 100644
--- a/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.cpp
+++ b/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.cpp
@@ -104,11 +104,11 @@ void GaussianAlphaYBlurOperation::executePixel(float output[4], int x, int y, vo
int miny = y - this->m_rad;
int maxy = y + this->m_rad;
int minx = x;
- int maxx = x;
+ // int maxx = x; // UNUSED
miny = max(miny, inputBuffer->getRect()->ymin);
minx = max(minx, inputBuffer->getRect()->xmin);
- maxy = min(maxy, inputBuffer->getRect()->ymax);
- maxx = min(maxx, inputBuffer->getRect()->xmax);
+ maxy = min(maxy, inputBuffer->getRect()->ymax - 1);
+ // maxx = min(maxx, inputBuffer->getRect()->xmax);
/* *** this is the main part which is different to 'GaussianYBlurOperation' *** */
int step = getStep();
@@ -121,7 +121,7 @@ void GaussianAlphaYBlurOperation::executePixel(float output[4], int x, int y, vo
float value_max = finv_test(buffer[(x * 4) + (y * 4 * bufferwidth)], do_invert); /* init with the current color to avoid unneeded lookups */
float distfacinv_max = 1.0f; /* 0 to 1 */
- for (int ny = miny; ny < maxy; ny += step) {
+ for (int ny = miny; ny <= maxy; ny += step) {
int bufferindex = ((minx - bufferstartx) * 4) + ((ny - bufferstarty) * 4 * bufferwidth);
const int index = (ny - y) + this->m_rad;
diff --git a/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.cpp
index a9bcb2dd752..2d662c1061e 100644
--- a/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.cpp
+++ b/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.cpp
@@ -236,7 +236,7 @@ void GaussianBlurReferenceOperation::initExecution()
/* horizontal */
m_radx = (float)this->m_data->sizex;
- int imgx = getWidth()/2;
+ int imgx = getWidth() / 2;
if (m_radx > imgx)
m_radx = imgx;
else if (m_radx < 1)
@@ -245,7 +245,7 @@ void GaussianBlurReferenceOperation::initExecution()
/* vertical */
m_rady = (float)this->m_data->sizey;
- int imgy = getHeight()/2;
+ int imgy = getHeight() / 2;
if (m_rady > imgy)
m_rady = imgy;
else if (m_rady < 1)
@@ -257,7 +257,7 @@ void GaussianBlurReferenceOperation::initExecution()
void GaussianBlurReferenceOperation::updateGauss()
{
int i;
- int x = MAX2(m_radx, m_rady);
+ int x = max(m_radx, m_rady);
this->m_maintabs = (float **)MEM_mallocN(x * sizeof(float *), "gauss array");
for (i = 0; i < x; i++) {
m_maintabs[i] = make_gausstab(i + 1);
@@ -327,11 +327,11 @@ void GaussianBlurReferenceOperation::executePixel(float output[4], int x, int y,
void GaussianBlurReferenceOperation::deinitExecution()
{
int x, i;
- x = MAX2(m_radx, m_rady);
+ x = max(this->m_radx, this->m_rady);
for (i = 0; i < x; i++) {
- MEM_freeN(m_maintabs[i]);
+ MEM_freeN(this->m_maintabs[i]);
}
- MEM_freeN(m_maintabs);
+ MEM_freeN(this->m_maintabs);
BlurBaseOperation::deinitExecution();
}
@@ -344,8 +344,8 @@ bool GaussianBlurReferenceOperation::determineDependingAreaOfInterest(rcti *inpu
return true;
}
else {
- int addx = this->m_data->sizex+2;
- int addy = this->m_data->sizey+2;
+ int addx = this->m_data->sizex + 2;
+ int addy = this->m_data->sizey + 2;
newInput.xmax = input->xmax + addx;
newInput.xmin = input->xmin - addx;
newInput.ymax = input->ymax + addy;
diff --git a/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp
index 984119b926a..573a19466e8 100644
--- a/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp
+++ b/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp
@@ -85,18 +85,18 @@ void GaussianXBlurOperation::executePixel(float output[4], int x, int y, void *d
int bufferstarty = inputBuffer->getRect()->ymin;
int miny = y;
- int maxy = y;
+ // int maxy = y; // UNUSED
int minx = x - this->m_rad;
int maxx = x + this->m_rad;
miny = max(miny, inputBuffer->getRect()->ymin);
minx = max(minx, inputBuffer->getRect()->xmin);
- maxy = min(maxy, inputBuffer->getRect()->ymax);
- maxx = min(maxx, inputBuffer->getRect()->xmax);
+ // maxy = min(maxy, inputBuffer->getRect()->ymax);
+ maxx = min(maxx, inputBuffer->getRect()->xmax - 1);
int step = getStep();
int offsetadd = getOffsetAdd();
int bufferindex = ((minx - bufferstartx) * 4) + ((miny - bufferstarty) * 4 * bufferwidth);
- for (int nx = minx, index = (minx - x) + this->m_rad; nx < maxx; nx += step, index += step) {
+ for (int nx = minx, index = (minx - x) + this->m_rad; nx <= maxx; nx += step, index += step) {
const float multiplier = this->m_gausstab[index];
madd_v4_v4fl(color_accum, &buffer[bufferindex], multiplier);
multiplier_accum += multiplier;
@@ -108,8 +108,10 @@ void GaussianXBlurOperation::executePixel(float output[4], int x, int y, void *d
void GaussianXBlurOperation::deinitExecution()
{
BlurBaseOperation::deinitExecution();
- MEM_freeN(this->m_gausstab);
- this->m_gausstab = NULL;
+ if (this->m_gausstab) {
+ MEM_freeN(this->m_gausstab);
+ this->m_gausstab = NULL;
+ }
deinitMutex();
}
diff --git a/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp
index 192bc29e1ae..0c0a4d8aa4f 100644
--- a/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp
+++ b/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp
@@ -87,16 +87,16 @@ void GaussianYBlurOperation::executePixel(float output[4], int x, int y, void *d
int miny = y - this->m_rad;
int maxy = y + this->m_rad;
int minx = x;
- int maxx = x;
+ // int maxx = x; // UNUSED
miny = max(miny, inputBuffer->getRect()->ymin);
minx = max(minx, inputBuffer->getRect()->xmin);
- maxy = min(maxy, inputBuffer->getRect()->ymax);
- maxx = min(maxx, inputBuffer->getRect()->xmax);
+ maxy = min(maxy, inputBuffer->getRect()->ymax - 1);
+ // maxx = min(maxx, inputBuffer->getRect()->xmax);
int index;
int step = getStep();
- const int bufferIndexx = ((minx - bufferstartx) * 4) ;
- for (int ny = miny; ny < maxy; ny += step) {
+ const int bufferIndexx = ((minx - bufferstartx) * 4);
+ for (int ny = miny; ny <= maxy; ny += step) {
index = (ny - y) + this->m_rad;
int bufferindex = bufferIndexx + ((ny - bufferstarty) * 4 * bufferwidth);
const float multiplier = this->m_gausstab[index];
@@ -109,8 +109,10 @@ void GaussianYBlurOperation::executePixel(float output[4], int x, int y, void *d
void GaussianYBlurOperation::deinitExecution()
{
BlurBaseOperation::deinitExecution();
- MEM_freeN(this->m_gausstab);
- this->m_gausstab = NULL;
+ if (this->m_gausstab) {
+ MEM_freeN(this->m_gausstab);
+ this->m_gausstab = NULL;
+ }
deinitMutex();
}
diff --git a/source/blender/compositor/operations/COM_GlareFogGlowOperation.cpp b/source/blender/compositor/operations/COM_GlareFogGlowOperation.cpp
index 7f7429bf2e6..592ad114113 100644
--- a/source/blender/compositor/operations/COM_GlareFogGlowOperation.cpp
+++ b/source/blender/compositor/operations/COM_GlareFogGlowOperation.cpp
@@ -86,8 +86,8 @@ static void FHT(fREAL *data, unsigned int M, unsigned int inverse)
fREAL *data_nbd = &data_n[bd];
fREAL *data_bd = &data[bd];
for (k = bl; k < len; k += istep) {
- t1 = fc * data_n[k] + fs * data_nbd[k];
- t2 = fs * data_n[k] - fc * data_nbd[k];
+ t1 = fc * (double)data_n[k] + fs * (double)data_nbd[k];
+ t2 = fs * (double)data_n[k] - fc * (double)data_nbd[k];
data_n[k] = data[k] - t1;
data_nbd[k] = data_bd[k] - t2;
data[k] += t1;
@@ -244,7 +244,7 @@ static void fht_convolve(fREAL *d1, fREAL *d2, unsigned int M, unsigned int N)
}
//------------------------------------------------------------------------------
-void convolve(float *dst, MemoryBuffer *in1, MemoryBuffer *in2)
+static void convolve(float *dst, MemoryBuffer *in1, MemoryBuffer *in2)
{
fREAL *data1, *data2, *fp;
unsigned int w2, h2, hw, hh, log2_w, log2_h;
@@ -395,7 +395,7 @@ void GlareFogGlowOperation::generateGlare(float *data, MemoryBuffer *inputTile,
// linear window good enough here, visual result counts, not scientific analysis
//w = (1.f-fabs(u))*(1.f-fabs(v));
// actually, Hanning window is ok, cos^2 for some reason is slower
- w = (0.5f + 0.5f * cos((double)u * M_PI)) * (0.5f + 0.5f * cos((double)v * M_PI));
+ w = (0.5f + 0.5f * cosf(u * (float)M_PI)) * (0.5f + 0.5f * cosf(v * (float)M_PI));
mul_v3_fl(fcol, w);
ckrn->writePixel(x, y, fcol);
}
diff --git a/source/blender/compositor/operations/COM_GlareGhostOperation.cpp b/source/blender/compositor/operations/COM_GlareGhostOperation.cpp
index ace04237b29..c4f8b3a0ddb 100644
--- a/source/blender/compositor/operations/COM_GlareGhostOperation.cpp
+++ b/source/blender/compositor/operations/COM_GlareGhostOperation.cpp
@@ -79,9 +79,9 @@ void GlareGhostOperation::generateGlare(float *data, MemoryBuffer *inputTile, No
sc = 2.13;
isc = -0.97;
for (y = 0; y < gbuf->getHeight() && (!breaked); y++) {
- v = (float)(y + 0.5f) / (float)gbuf->getHeight();
+ v = ((float)y + 0.5f) / (float)gbuf->getHeight();
for (x = 0; x < gbuf->getWidth(); x++) {
- u = (float)(x + 0.5f) / (float)gbuf->getWidth();
+ u = ((float)x + 0.5f) / (float)gbuf->getWidth();
s = (u - 0.5f) * sc + 0.5f, t = (v - 0.5f) * sc + 0.5f;
tbuf1->readCubic(c, s * gbuf->getWidth(), t * gbuf->getHeight());
sm = smoothMask(s, t);
@@ -100,9 +100,9 @@ void GlareGhostOperation::generateGlare(float *data, MemoryBuffer *inputTile, No
memset(tbuf1->getBuffer(), 0, tbuf1->getWidth() * tbuf1->getHeight() * COM_NUMBER_OF_CHANNELS * sizeof(float));
for (n = 1; n < settings->iter && (!breaked); n++) {
for (y = 0; y < gbuf->getHeight() && (!breaked); y++) {
- v = (float)(y + 0.5f) / (float)gbuf->getHeight();
+ v = ((float)y + 0.5f) / (float)gbuf->getHeight();
for (x = 0; x < gbuf->getWidth(); x++) {
- u = (float)(x + 0.5f) / (float)gbuf->getWidth();
+ u = ((float)x + 0.5f) / (float)gbuf->getWidth();
tc[0] = tc[1] = tc[2] = 0.f;
for (p = 0; p < 4; p++) {
np = (n << 2) + p;
diff --git a/source/blender/compositor/operations/COM_GlareStreaksOperation.cpp b/source/blender/compositor/operations/COM_GlareStreaksOperation.cpp
index 9125783c222..60d37fb8145 100644
--- a/source/blender/compositor/operations/COM_GlareStreaksOperation.cpp
+++ b/source/blender/compositor/operations/COM_GlareStreaksOperation.cpp
@@ -81,11 +81,9 @@ void GlareStreaksOperation::generateGlare(float *data, MemoryBuffer *inputTile,
float *sourcebuffer = tsrc->getBuffer();
float factor = 1.f / (float)(6 - settings->iter);
- for (int i = 0; i < size4; i++) {
- data[i] += sourcebuffer[i] * factor;
- }
- for (int i = 0; i < size; i++) {
- data[i * 4 + 3] = 1.0f;
+ for (int i = 0; i < size4; i += 4) {
+ madd_v3_v3fl(&data[i], &sourcebuffer[i], factor);
+ data[i + 3] = 1.0f;
}
tdst->clear();
diff --git a/source/blender/compositor/operations/COM_InpaintOperation.cpp b/source/blender/compositor/operations/COM_InpaintOperation.cpp
index 70d4d987c81..81ca06cfff0 100644
--- a/source/blender/compositor/operations/COM_InpaintOperation.cpp
+++ b/source/blender/compositor/operations/COM_InpaintOperation.cpp
@@ -133,9 +133,9 @@ void InpaintSimpleOperation::calc_manhatten_distance()
if (this->get_pixel(i, j)[3] < 1.0f) {
r = width + height;
if (i > 0)
- r = mini(r, m[j * width + i - 1] + 1);
+ r = min_ii(r, m[j * width + i - 1] + 1);
if (j > 0)
- r = mini(r, m[(j - 1) * width + i] + 1);
+ r = min_ii(r, m[(j - 1) * width + i] + 1);
}
m[j * width + i] = r;
}
@@ -146,9 +146,9 @@ void InpaintSimpleOperation::calc_manhatten_distance()
int r = m[j * width + i];
if (i + 1 < width)
- r = mini(r, m[j * width + i + 1] + 1);
+ r = min_ii(r, m[j * width + i + 1] + 1);
if (j + 1 < height)
- r = mini(r, m[(j + 1) * width + i] + 1);
+ r = min_ii(r, m[(j + 1) * width + i] + 1);
m[j * width + i] = r;
diff --git a/source/blender/compositor/operations/COM_KeyingDespillOperation.cpp b/source/blender/compositor/operations/COM_KeyingDespillOperation.cpp
index 4426666f100..01f5c032730 100644
--- a/source/blender/compositor/operations/COM_KeyingDespillOperation.cpp
+++ b/source/blender/compositor/operations/COM_KeyingDespillOperation.cpp
@@ -28,18 +28,6 @@
#include "BLI_listbase.h"
#include "BLI_math.h"
-static int get_pixel_primary_channel(float *pixel)
-{
- float max_value = MAX3(pixel[0], pixel[1], pixel[2]);
-
- if (max_value == pixel[0])
- return 0;
- else if (max_value == pixel[1])
- return 1;
-
- return 2;
-}
-
KeyingDespillOperation::KeyingDespillOperation() : NodeOperation()
{
this->addInputSocket(COM_DT_COLOR);
@@ -73,12 +61,12 @@ void KeyingDespillOperation::executePixel(float output[4], float x, float y, Pix
this->m_pixelReader->read(pixelColor, x, y, sampler);
this->m_screenReader->read(screenColor, x, y, sampler);
- int screen_primary_channel = get_pixel_primary_channel(screenColor);
- int other_1 = (screen_primary_channel + 1) % 3;
- int other_2 = (screen_primary_channel + 2) % 3;
+ const int screen_primary_channel = max_axis_v3(screenColor);
+ const int other_1 = (screen_primary_channel + 1) % 3;
+ const int other_2 = (screen_primary_channel + 2) % 3;
- int min_channel = MIN2(other_1, other_2);
- int max_channel = MAX2(other_1, other_2);
+ const int min_channel = min(other_1, other_2);
+ const int max_channel = max(other_1, other_2);
float average_value, amount;
@@ -87,7 +75,8 @@ void KeyingDespillOperation::executePixel(float output[4], float x, float y, Pix
copy_v4_v4(output, pixelColor);
- if (this->m_despillFactor * amount > 0) {
- output[screen_primary_channel] = pixelColor[screen_primary_channel] - this->m_despillFactor * amount;
+ const float amount_despill = this->m_despillFactor * amount;
+ if (amount_despill > 0.0f) {
+ output[screen_primary_channel] = pixelColor[screen_primary_channel] - amount_despill;
}
}
diff --git a/source/blender/compositor/operations/COM_KeyingOperation.cpp b/source/blender/compositor/operations/COM_KeyingOperation.cpp
index 35138cf0b92..baeacb56744 100644
--- a/source/blender/compositor/operations/COM_KeyingOperation.cpp
+++ b/source/blender/compositor/operations/COM_KeyingOperation.cpp
@@ -28,27 +28,15 @@
#include "BLI_listbase.h"
#include "BLI_math.h"
-static int get_pixel_primary_channel(float pixelColor[4])
+static float get_pixel_saturation(const float pixelColor[4], float screen_balance, int primary_channel)
{
- float max_value = MAX3(pixelColor[0], pixelColor[1], pixelColor[2]);
+ const int other_1 = (primary_channel + 1) % 3;
+ const int other_2 = (primary_channel + 2) % 3;
- if (max_value == pixelColor[0])
- return 0;
- else if (max_value == pixelColor[1])
- return 1;
+ const int min_channel = min(other_1, other_2);
+ const int max_channel = max(other_1, other_2);
- return 2;
-}
-
-static float get_pixel_saturation(float pixelColor[4], float screen_balance, int primary_channel)
-{
- int other_1 = (primary_channel + 1) % 3;
- int other_2 = (primary_channel + 2) % 3;
-
- int min_channel = MIN2(other_1, other_2);
- int max_channel = MAX2(other_1, other_2);
-
- float val = screen_balance * pixelColor[min_channel] + (1.0f - screen_balance) * pixelColor[max_channel];
+ const float val = screen_balance * pixelColor[min_channel] + (1.0f - screen_balance) * pixelColor[max_channel];
return (pixelColor[primary_channel] - val) * fabsf(1.0f - val);
}
@@ -85,13 +73,13 @@ void KeyingOperation::executePixel(float output[4], float x, float y, PixelSampl
this->m_pixelReader->read(pixelColor, x, y, sampler);
this->m_screenReader->read(screenColor, x, y, sampler);
- int primary_channel = get_pixel_primary_channel(screenColor);
+ const int primary_channel = max_axis_v3(screenColor);
if (pixelColor[primary_channel] > 1.0f) {
/* overexposure doesn't happen on screen itself and usually happens
* on light sources in the shot, this need to be checked separately
* because saturation and falloff calculation is based on the fact
- * that pixels are not overexposured
+ * that pixels are not overexposed
*/
output[0] = 1.0f;
}
diff --git a/source/blender/compositor/operations/COM_MapUVOperation.cpp b/source/blender/compositor/operations/COM_MapUVOperation.cpp
index fe6ebcebf97..1fa484ea2b6 100644
--- a/source/blender/compositor/operations/COM_MapUVOperation.cpp
+++ b/source/blender/compositor/operations/COM_MapUVOperation.cpp
@@ -24,7 +24,7 @@
MapUVOperation::MapUVOperation() : NodeOperation()
{
- this->addInputSocket(COM_DT_COLOR);
+ this->addInputSocket(COM_DT_COLOR, COM_SC_NO_RESIZE);
this->addInputSocket(COM_DT_VECTOR);
this->addOutputSocket(COM_DT_COLOR);
this->m_alpha = 0.0f;
diff --git a/source/blender/compositor/operations/COM_MaskOperation.cpp b/source/blender/compositor/operations/COM_MaskOperation.cpp
index 36b3f2023ae..ba1059c4eb5 100644
--- a/source/blender/compositor/operations/COM_MaskOperation.cpp
+++ b/source/blender/compositor/operations/COM_MaskOperation.cpp
@@ -73,7 +73,7 @@ void MaskOperation::initExecution()
for (masklay = (MaskLayer *)mask_temp->masklayers.first;
masklay;
- masklay = (MaskLayer *)masklay->next)
+ masklay = masklay->next)
{
masklay_shape = BKE_mask_layer_shape_varify_frame(masklay, this->m_frame_number);
BKE_mask_layer_shape_from_mask(masklay, masklay_shape);
diff --git a/source/blender/compositor/operations/COM_MathBaseOperation.h b/source/blender/compositor/operations/COM_MathBaseOperation.h
index b492d06a697..febfa9662c6 100644
--- a/source/blender/compositor/operations/COM_MathBaseOperation.h
+++ b/source/blender/compositor/operations/COM_MathBaseOperation.h
@@ -45,7 +45,7 @@ protected:
*/
MathBaseOperation();
- void clampIfNeeded(float *color);
+ void clampIfNeeded(float color[4]);
public:
/**
* the inner loop of this program
diff --git a/source/blender/compositor/operations/COM_MixBaseOperation.h b/source/blender/compositor/operations/COM_MixBaseOperation.h
index 4b466d193d6..88d1d00c2bf 100644
--- a/source/blender/compositor/operations/COM_MixBaseOperation.h
+++ b/source/blender/compositor/operations/COM_MixBaseOperation.h
@@ -40,7 +40,7 @@ protected:
bool m_valueAlphaMultiply;
bool m_useClamp;
- inline void clampIfNeeded(float *color)
+ inline void clampIfNeeded(float color[4])
{
if (m_useClamp) {
CLAMP(color[0], 0.0f, 1.0f);
diff --git a/source/blender/compositor/operations/COM_MixColorOperation.cpp b/source/blender/compositor/operations/COM_MixColorOperation.cpp
index f8aca92abc7..56aca27eaef 100644
--- a/source/blender/compositor/operations/COM_MixColorOperation.cpp
+++ b/source/blender/compositor/operations/COM_MixColorOperation.cpp
@@ -53,9 +53,12 @@ void MixColorOperation::executePixel(float output[4], float x, float y, PixelSam
float tmpr, tmpg, tmpb;
rgb_to_hsv(inputColor1[0], inputColor1[1], inputColor1[2], &rH, &rS, &rV);
hsv_to_rgb(colH, colS, rV, &tmpr, &tmpg, &tmpb);
- output[0] = valuem * (inputColor1[0]) + value * tmpr;
- output[1] = valuem * (inputColor1[1]) + value * tmpg;
- output[2] = valuem * (inputColor1[2]) + value * tmpb;
+ output[0] = (valuem * inputColor1[0]) + (value * tmpr);
+ output[1] = (valuem * inputColor1[1]) + (value * tmpg);
+ output[2] = (valuem * inputColor1[2]) + (value * tmpb);
+ }
+ else {
+ copy_v3_v3(output, inputColor1);
}
output[3] = inputColor1[3];
diff --git a/source/blender/compositor/operations/COM_MixGlareOperation.cpp b/source/blender/compositor/operations/COM_MixGlareOperation.cpp
index b6a9aa3da3c..1c6555206da 100644
--- a/source/blender/compositor/operations/COM_MixGlareOperation.cpp
+++ b/source/blender/compositor/operations/COM_MixGlareOperation.cpp
@@ -40,9 +40,13 @@ void MixGlareOperation::executePixel(float output[4], float x, float y, PixelSam
value = inputValue[0];
float mf = 2.f - 2.f * fabsf(value - 0.5f);
- output[0] = mf * ((inputColor1[0]) + value * (inputColor2[0] - inputColor1[0]));
- output[1] = mf * ((inputColor1[1]) + value * (inputColor2[1] - inputColor1[1]));
- output[2] = mf * ((inputColor1[2]) + value * (inputColor2[2] - inputColor1[2]));
+ if (inputColor1[0] < 0.0f) inputColor1[0] = 0.0f;
+ if (inputColor1[1] < 0.0f) inputColor1[1] = 0.0f;
+ if (inputColor1[2] < 0.0f) inputColor1[2] = 0.0f;
+
+ output[0] = mf * max(inputColor1[0] + value * (inputColor2[0] - inputColor1[0]), 0.0f);
+ output[1] = mf * max(inputColor1[1] + value * (inputColor2[1] - inputColor1[1]), 0.0f);
+ output[2] = mf * max(inputColor1[2] + value * (inputColor2[2] - inputColor1[2]), 0.0f);
output[3] = inputColor1[3];
clampIfNeeded(output);
diff --git a/source/blender/compositor/operations/COM_MovieDistortionOperation.cpp b/source/blender/compositor/operations/COM_MovieDistortionOperation.cpp
index a3e00e9325b..df48c7a6716 100644
--- a/source/blender/compositor/operations/COM_MovieDistortionOperation.cpp
+++ b/source/blender/compositor/operations/COM_MovieDistortionOperation.cpp
@@ -33,8 +33,7 @@ vector<DistortionCache *> s_cache;
void deintializeDistortionCache(void)
{
- while (s_cache.size()>0)
- {
+ while (s_cache.size() > 0) {
DistortionCache * cache = s_cache.back();
s_cache.pop_back();
delete cache;
@@ -61,8 +60,7 @@ void MovieDistortionOperation::initExecution()
BKE_movieclip_user_set_frame(&clipUser, this->m_framenumber);
BKE_movieclip_get_size(this->m_movieClip, &clipUser, &calibration_width, &calibration_height);
- for (unsigned int i = 0; i < s_cache.size(); i++)
- {
+ for (unsigned int i = 0; i < s_cache.size(); i++) {
DistortionCache *c = (DistortionCache *)s_cache[i];
if (c->isCacheFor(this->m_movieClip, this->m_width, this->m_height,
calibration_width, calibration_height, this->m_distortion))
@@ -86,15 +84,12 @@ void MovieDistortionOperation::deinitExecution()
{
this->m_inputOperation = NULL;
this->m_movieClip = NULL;
- while (s_cache.size() > COM_DISTORTIONCACHE_MAXSIZE)
- {
+ while (s_cache.size() > COM_DISTORTIONCACHE_MAXSIZE) {
double minTime = PIL_check_seconds_timer();
vector<DistortionCache*>::iterator minTimeIterator = s_cache.begin();
- for (vector<DistortionCache*>::iterator it = s_cache.begin(); it < s_cache.end(); it ++)
- {
+ for (vector<DistortionCache*>::iterator it = s_cache.begin(); it < s_cache.end(); it ++) {
DistortionCache * cache = *it;
- if (cache->getTimeLastUsage()<minTime)
- {
+ if (cache->getTimeLastUsage() < minTime) {
minTime = cache->getTimeLastUsage();
minTimeIterator = it;
}
@@ -111,7 +106,7 @@ void MovieDistortionOperation::executePixel(float output[4], float x, float y, P
float u, v;
this->m_cache->getUV(&this->m_movieClip->tracking, x, y, &u, &v);
this->m_inputOperation->read(output, u, v, sampler);
- }
+ }
else {
this->m_inputOperation->read(output, x, y, sampler);
}
diff --git a/source/blender/compositor/operations/COM_MovieDistortionOperation.h b/source/blender/compositor/operations/COM_MovieDistortionOperation.h
index f3eeb2f48ba..93cc555fdbc 100644
--- a/source/blender/compositor/operations/COM_MovieDistortionOperation.h
+++ b/source/blender/compositor/operations/COM_MovieDistortionOperation.h
@@ -115,10 +115,10 @@ public:
if (!this->m_bufferCalculated[offset]) {
//float overscan = 0.0f;
- float w = (float)this->m_width /* / (1 + overscan) */;
- float h = (float)this->m_height /* / (1 + overscan) */;
- float aspx = (float)w / this->m_calibration_width;
- float aspy = (float)h / this->m_calibration_height;
+ const float w = (float)this->m_width /* / (1 + overscan) */;
+ const float h = (float)this->m_height /* / (1 + overscan) */;
+ const float aspx = w / (float)this->m_calibration_width;
+ const float aspy = h / (float)this->m_calibration_height;
float in[2];
float out[2];
diff --git a/source/blender/compositor/operations/COM_OpenCLKernels.cl b/source/blender/compositor/operations/COM_OpenCLKernels.cl
index 4d366a864c4..36205bb94cc 100644
--- a/source/blender/compositor/operations/COM_OpenCLKernels.cl
+++ b/source/blender/compositor/operations/COM_OpenCLKernels.cl
@@ -33,7 +33,7 @@ __kernel void bokehBlurKernel(__read_only image2d_t boundingBox, __read_only ima
__read_only image2d_t bokehImage, __write_only image2d_t output,
int2 offsetInput, int2 offsetOutput, int radius, int step, int2 dimension, int2 offset)
{
- int2 coords = {get_global_id(0), get_global_id(1)};
+ int2 coords = {get_global_id(0), get_global_id(1)};
coords += offset;
float tempBoundingBox;
float4 color = {0.0f,0.0f,0.0f,0.0f};
@@ -54,10 +54,10 @@ __kernel void bokehBlurKernel(__read_only image2d_t boundingBox, __read_only ima
float2 uv;
int2 inputXy;
- for (ny = minXY.y, inputXy.y = ny - offsetInput.y ; ny < maxXY.y ; ny +=step, inputXy.y+=step) {
+ for (ny = minXY.y, inputXy.y = ny - offsetInput.y ; ny < maxXY.y ; ny += step, inputXy.y += step) {
uv.y = ((realCoordinate.y-ny)/radius2)*bokehImageDim.y+bokehImageCenter.y;
- for (nx = minXY.x, inputXy.x = nx - offsetInput.x; nx < maxXY.x ; nx +=step, inputXy.x+=step) {
+ for (nx = minXY.x, inputXy.x = nx - offsetInput.x; nx < maxXY.x ; nx += step, inputXy.x += step) {
uv.x = ((realCoordinate.x-nx)/radius2)*bokehImageDim.x+bokehImageCenter.x;
bokeh = read_imagef(bokehImage, SAMPLER_NEAREST, uv);
color += bokeh * read_imagef(inputImage, SAMPLER_NEAREST, inputXy);
@@ -124,7 +124,7 @@ __kernel void defocusKernel(__read_only image2d_t inputImage, __read_only image2
}
}
}
- }
+ }
}
color = color_accum * (1.0f / multiplier_accum);
@@ -148,7 +148,7 @@ __kernel void dilateKernel(__read_only image2d_t inputImage, __write_only image
int2 offsetInput, int2 offsetOutput, int scope, int distanceSquared, int2 dimension,
int2 offset)
{
- int2 coords = {get_global_id(0), get_global_id(1)};
+ int2 coords = {get_global_id(0), get_global_id(1)};
coords += offset;
const int2 realCoordinate = coords + offsetOutput;
@@ -179,7 +179,7 @@ __kernel void erodeKernel(__read_only image2d_t inputImage, __write_only image2
int2 offsetInput, int2 offsetOutput, int scope, int distanceSquared, int2 dimension,
int2 offset)
{
- int2 coords = {get_global_id(0), get_global_id(1)};
+ int2 coords = {get_global_id(0), get_global_id(1)};
coords += offset;
const int2 realCoordinate = coords + offsetOutput;
@@ -210,7 +210,7 @@ __kernel void directionalBlurKernel(__read_only image2d_t inputImage, __write_o
int2 offsetOutput, int iterations, float scale, float rotation, float2 translate,
float2 center, int2 offset)
{
- int2 coords = {get_global_id(0), get_global_id(1)};
+ int2 coords = {get_global_id(0), get_global_id(1)};
coords += offset;
const int2 realCoordinate = coords + offsetOutput;
diff --git a/source/blender/compositor/operations/COM_OutputFileOperation.cpp b/source/blender/compositor/operations/COM_OutputFileOperation.cpp
index 21ecfdb5272..7d05202df96 100644
--- a/source/blender/compositor/operations/COM_OutputFileOperation.cpp
+++ b/source/blender/compositor/operations/COM_OutputFileOperation.cpp
@@ -94,8 +94,8 @@ static void write_buffer_rect(rcti *rect, const bNodeTree *tree,
OutputSingleLayerOperation::OutputSingleLayerOperation(
- const RenderData *rd, const bNodeTree *tree, DataType datatype, ImageFormatData *format, const char *path,
- const ColorManagedViewSettings *viewSettings, const ColorManagedDisplaySettings *displaySettings)
+ const RenderData *rd, const bNodeTree *tree, DataType datatype, ImageFormatData *format, const char *path,
+ const ColorManagedViewSettings *viewSettings, const ColorManagedDisplaySettings *displaySettings)
{
this->m_rd = rd;
this->m_tree = tree;
@@ -129,7 +129,7 @@ void OutputSingleLayerOperation::deinitExecution()
if (this->getWidth() * this->getHeight() != 0) {
int size = get_datatype_size(this->m_datatype);
- ImBuf *ibuf = IMB_allocImBuf(this->getWidth(), this->getHeight(), size * 8, 0);
+ ImBuf *ibuf = IMB_allocImBuf(this->getWidth(), this->getHeight(), this->m_format->planes, 0);
Main *bmain = G.main; /* TODO, have this passed along */
char filename[FILE_MAX];
@@ -138,8 +138,9 @@ void OutputSingleLayerOperation::deinitExecution()
ibuf->mall |= IB_rectfloat;
ibuf->dither = this->m_rd->dither_intensity;
- IMB_display_buffer_to_imbuf_rect(ibuf, m_viewSettings, m_displaySettings);
-
+ IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, m_viewSettings, m_displaySettings,
+ this->m_format);
+
BKE_makepicstring(filename, this->m_path, bmain->name, this->m_rd->cfra, this->m_format->imtype,
(this->m_rd->scemode & R_EXTENSION), true);
@@ -148,7 +149,7 @@ void OutputSingleLayerOperation::deinitExecution()
else
printf("Saved: %s\n", filename);
- IMB_freeImBuf(ibuf);
+ IMB_freeImBuf(ibuf);
}
this->m_outputBuffer = NULL;
this->m_imageInput = NULL;
diff --git a/source/blender/compositor/operations/COM_PixelateOperation.cpp b/source/blender/compositor/operations/COM_PixelateOperation.cpp
new file mode 100644
index 00000000000..89e7f0093a1
--- /dev/null
+++ b/source/blender/compositor/operations/COM_PixelateOperation.cpp
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2011, Blender Foundation.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor:
+ * Jeroen Bakker
+ * Monique Dewanchand
+ */
+
+#include "COM_PixelateOperation.h"
+
+PixelateOperation::PixelateOperation(DataType datatype) : NodeOperation()
+{
+ this->addInputSocket(datatype);
+ this->addOutputSocket(datatype);
+ this->setResolutionInputSocketIndex(0);
+ this->m_inputOperation = NULL;
+}
+
+void PixelateOperation::initExecution()
+{
+ this->m_inputOperation = this->getInputSocketReader(0);
+}
+
+void PixelateOperation::deinitExecution()
+{
+ this->m_inputOperation = NULL;
+}
+
+void PixelateOperation::executePixel(float output[4], float x, float y, PixelSampler sampler)
+{
+ float nx = round(x);
+ float ny = round(y);
+ this->m_inputOperation->read(output, nx, ny, sampler);
+}
+
diff --git a/source/blender/compositor/operations/COM_PixelateOperation.h b/source/blender/compositor/operations/COM_PixelateOperation.h
new file mode 100644
index 00000000000..b16b21b2ec1
--- /dev/null
+++ b/source/blender/compositor/operations/COM_PixelateOperation.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2011, Blender Foundation.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor:
+ * Jeroen Bakker
+ * Monique Dewanchand
+ */
+
+#ifndef _COM_PixelateOperation_h_
+#define _COM_PixelateOperation_h_
+
+#include "COM_NodeOperation.h"
+
+/**
+ * @brief Pixelate operation
+ *
+ * The Tile compositor is by default sub-pixel accurate.
+ * For some setups you don want this.
+ * This operation will remove the sub-pixel accuracy
+ */
+class PixelateOperation : public NodeOperation {
+private:
+ /**
+ * @brief cached refeerence to the input operation
+ */
+ SocketReader *m_inputOperation;
+public:
+ /**
+ * @brief PixelateOperation
+ * @param dataType the datatype to create this operator for (saves datatype conversions)
+ */
+ PixelateOperation(DataType dataType);
+
+ /**
+ * @brief initialization of the execution
+ */
+ void initExecution();
+
+ /**
+ * @brief de-initialization of the execution
+ */
+ void deinitExecution();
+
+ /**
+ * @brief executePixel
+ * @param output result
+ * @param x x-coordinate
+ * @param y y-coordinate
+ * @param sampler sampler
+ */
+ void executePixel(float output[4], float x, float y, PixelSampler sampler);
+};
+
+#endif
diff --git a/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.cpp b/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.cpp
index d92fe04eb15..5cc02a1ed65 100644
--- a/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.cpp
+++ b/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.cpp
@@ -81,7 +81,7 @@ bool ProjectorLensDistortionOperation::determineDependingAreaOfInterest(rcti *in
}
else {
rcti dispInput;
- BLI_rcti_init(&dispInput, 0,5,0,5);
+ BLI_rcti_init(&dispInput, 0, 5, 0, 5);
if (this->getInputOperation(1)->determineDependingAreaOfInterest(&dispInput, readOperation, output)) {
return true;
}
@@ -104,7 +104,7 @@ void ProjectorLensDistortionOperation::updateDispersion()
float result[4];
this->getInputSocketReader(1)->read(result, 1, 1, COM_PS_NEAREST);
this->m_dispersion = result[0];
- this->m_kr = 0.25f * maxf(minf(this->m_dispersion, 1.0f), 0.0f);
+ this->m_kr = 0.25f * max_ff(min_ff(this->m_dispersion, 1.0f), 0.0f);
this->m_kr2 = this->m_kr * 20;
this->m_dispersionAvailable = true;
}
diff --git a/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp b/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp
index 193ab669f40..d2c6c833e2e 100644
--- a/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp
+++ b/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp
@@ -98,7 +98,7 @@ void ScreenLensDistortionOperation::executePixel(float output[4], int x, int y,
const float sd = 1.0f / (float)ds;
for (z = 0; z < ds; ++z) {
- const float tz = ((float)z + (jit ? BLI_frand() : 0.5f)) * sd;
+ const float tz = (z + (jit ? BLI_frand() : 0.5f)) * sd;
t = 1.0f - (this->m_kr4 + tz * this->m_drg) * uv_dot;
d = 1.0f / (1.0f + sqrtf(t));
const float nx = (u * d + 0.5f) * width - 0.5f;
@@ -116,7 +116,7 @@ void ScreenLensDistortionOperation::executePixel(float output[4], int x, int y,
const float sd = 1.0f / (float)ds;
for (z = 0; z < ds; ++z) {
- const float tz = ((float)z + (jit ? BLI_frand() : 0.5f)) * sd;
+ const float tz = (z + (jit ? BLI_frand() : 0.5f)) * sd;
t = 1.0f - (this->m_kg4 + tz * this->m_dgb) * uv_dot;
d = 1.0f / (1.0f + sqrtf(t));
const float nx = (u * d + 0.5f) * width - 0.5f;
@@ -226,7 +226,7 @@ bool ScreenLensDistortionOperation::determineDependingAreaOfInterest(rcti *input
UPDATE_INPUT;
determineUV(coords, input->xmax, input->ymin);
UPDATE_INPUT;
- }
+ }
else {
determineUV(coords, input->xmin, input->ymin, 1.0f, 1.0f);
newInput.xmin = coords[0];
@@ -268,11 +268,11 @@ bool ScreenLensDistortionOperation::determineDependingAreaOfInterest(rcti *input
void ScreenLensDistortionOperation::updateVariables(float distortion, float dispersion)
{
- this->m_kg = maxf(minf(distortion, 1.0f), -0.999f);
+ this->m_kg = max_ff(min_ff(distortion, 1.0f), -0.999f);
// smaller dispersion range for somewhat more control
- const float d = 0.25f * maxf(minf(dispersion, 1.0f), 0.0f);
- this->m_kr = maxf(minf((this->m_kg + d), 1.0f), -0.999f);
- this->m_kb = maxf(minf((this->m_kg - d), 1.0f), -0.999f);
+ const float d = 0.25f * max_ff(min_ff(dispersion, 1.0f), 0.0f);
+ this->m_kr = max_ff(min_ff((this->m_kg + d), 1.0f), -0.999f);
+ this->m_kb = max_ff(min_ff((this->m_kg - d), 1.0f), -0.999f);
this->m_maxk = MAX3(this->m_kr, this->m_kg, this->m_kb);
this->m_sc = (this->m_data->fit && (this->m_maxk > 0.0f)) ? (1.0f / (1.0f + 2.0f * this->m_maxk)) :
(1.0f / (1.0f + this->m_maxk));
diff --git a/source/blender/compositor/operations/COM_TrackPositionOperation.h b/source/blender/compositor/operations/COM_TrackPositionOperation.h
index 3a9e6f25cd9..b934719a92b 100644
--- a/source/blender/compositor/operations/COM_TrackPositionOperation.h
+++ b/source/blender/compositor/operations/COM_TrackPositionOperation.h
@@ -35,8 +35,8 @@
#include "BLI_listbase.h"
/**
- * Class with implementation of green screen gradient rasterization
- */
+ * Class with implementation of green screen gradient rasterization
+ */
class TrackPositionOperation : public NodeOperation {
protected:
enum {
@@ -58,8 +58,8 @@ protected:
float m_relativePos[2];
/**
- * Determine the output resolution. The resolution is retrieved from the Renderer
- */
+ * Determine the output resolution. The resolution is retrieved from the Renderer
+ */
void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]);
public:
diff --git a/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp b/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp
index 7ccc91072bc..61720c7676d 100644
--- a/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp
+++ b/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp
@@ -118,7 +118,7 @@ void VariableSizeBokehBlurOperation::executePixel(float output[4], int x, int y,
#ifdef COM_DEFOCUS_SEARCH
float search[4];
- this->m_inputSearchProgram->read(search, x/InverseSearchRadiusOperation::DIVIDER, y / InverseSearchRadiusOperation::DIVIDER, NULL);
+ this->m_inputSearchProgram->read(search, x / InverseSearchRadiusOperation::DIVIDER, y / InverseSearchRadiusOperation::DIVIDER, NULL);
int minx = search[0];
int miny = search[1];
int maxx = search[2];
@@ -192,13 +192,13 @@ void VariableSizeBokehBlurOperation::executeOpenCL(OpenCLDevice *device,
cl_int maxBlur;
cl_float threshold = this->m_threshold;
- MemoryBuffer *sizeMemoryBuffer = (MemoryBuffer *)this->m_inputSizeProgram->getInputMemoryBuffer(inputMemoryBuffers);
+ MemoryBuffer *sizeMemoryBuffer = this->m_inputSizeProgram->getInputMemoryBuffer(inputMemoryBuffers);
const float max_dim = max(m_width, m_height);
cl_float scalar = this->m_do_size_scale ? (max_dim / 100.0f) : 1.0f;
maxBlur = (cl_int)sizeMemoryBuffer->getMaximumValue() * scalar;
- maxBlur = MIN2(maxBlur, this->m_maxBlur);
+ maxBlur = min(maxBlur, this->m_maxBlur);
device->COM_clAttachMemoryBufferToKernelParameter(defocusKernel, 0, -1, clMemToCleanUp, inputMemoryBuffers, this->m_inputProgram);
device->COM_clAttachMemoryBufferToKernelParameter(defocusKernel, 1, -1, clMemToCleanUp, inputMemoryBuffers, this->m_inputBokehProgram);
@@ -298,9 +298,9 @@ voi *InverseSearchRadiusOperation::initializeTileData(rcti *rect)
int rx = x * DIVIDER;
int ry = y * DIVIDER;
buffer[offset] = MAX2(rx - m_maxBlur, 0);
- buffer[offset+1] = MAX2(ry- m_maxBlur, 0);
- buffer[offset+2] = MIN2(rx+DIVIDER + m_maxBlur, width);
- buffer[offset+3] = MIN2(ry+DIVIDER + m_maxBlur, height);
+ buffer[offset + 1] = MAX2(ry - m_maxBlur, 0);
+ buffer[offset + 2] = MIN2(rx + DIVIDER + m_maxBlur, width);
+ buffer[offset + 3] = MIN2(ry + DIVIDER + m_maxBlur, height);
offset += 4;
}
}
diff --git a/source/blender/compositor/operations/COM_ViewerBaseOperation.cpp b/source/blender/compositor/operations/COM_ViewerBaseOperation.cpp
index d9ca131721f..4d4c1199f3e 100644
--- a/source/blender/compositor/operations/COM_ViewerBaseOperation.cpp
+++ b/source/blender/compositor/operations/COM_ViewerBaseOperation.cpp
@@ -79,8 +79,7 @@ void ViewerBaseOperation::initImage()
BLI_unlock_thread(LOCK_DRAW_IMAGE);
}
- if (m_doDepthBuffer)
- {
+ if (m_doDepthBuffer) {
addzbuffloatImBuf(ibuf);
}
BLI_unlock_thread(LOCK_DRAW_IMAGE);
@@ -96,8 +95,7 @@ void ViewerBaseOperation::initImage()
*/
this->m_ibuf = ibuf;
- if (m_doDepthBuffer)
- {
+ if (m_doDepthBuffer) {
this->m_depthBuffer = ibuf->zbuf_float;
}
@@ -107,7 +105,7 @@ void ViewerBaseOperation:: updateImage(rcti *rect)
{
IMB_partial_display_buffer_update(this->m_ibuf, this->m_outputBuffer, NULL, getWidth(), 0, 0,
this->m_viewSettings, this->m_displaySettings,
- rect->xmin, rect->ymin, rect->xmax, rect->ymax);
+ rect->xmin, rect->ymin, rect->xmax, rect->ymax, FALSE);
WM_main_add_notifier(NC_WINDOW | ND_DRAW, NULL);
}
diff --git a/source/blender/compositor/operations/COM_ViewerOperation.cpp b/source/blender/compositor/operations/COM_ViewerOperation.cpp
index 576d5da4d74..d1ac7d74ead 100644
--- a/source/blender/compositor/operations/COM_ViewerOperation.cpp
+++ b/source/blender/compositor/operations/COM_ViewerOperation.cpp
@@ -96,7 +96,7 @@ void ViewerOperation::executeRegion(rcti *rect, unsigned int tileNumber)
if (m_depthInput) {
this->m_depthInput->read(depth, x, y, COM_PS_NEAREST);
depthbuffer[offset] = depth[0];
- }
+ }
offset ++;
offset4 += 4;
diff --git a/source/blender/compositor/operations/COM_WriteBufferOperation.cpp b/source/blender/compositor/operations/COM_WriteBufferOperation.cpp
index 273c10b60ac..17c8f4d9fd1 100644
--- a/source/blender/compositor/operations/COM_WriteBufferOperation.cpp
+++ b/source/blender/compositor/operations/COM_WriteBufferOperation.cpp
@@ -110,7 +110,8 @@ void WriteBufferOperation::executeRegion(rcti *rect, unsigned int tileNumber)
memoryBuffer->setCreatedState();
}
-void WriteBufferOperation::executeOpenCLRegion(OpenCLDevice *device, rcti *rect, unsigned int chunkNumber, MemoryBuffer **inputMemoryBuffers, MemoryBuffer *outputBuffer)
+void WriteBufferOperation::executeOpenCLRegion(OpenCLDevice *device, rcti *rect, unsigned int chunkNumber,
+ MemoryBuffer **inputMemoryBuffers, MemoryBuffer *outputBuffer)
{
float *outputFloatBuffer = outputBuffer->getBuffer();
cl_int error;
diff --git a/source/blender/compositor/operations/COM_ZCombineOperation.cpp b/source/blender/compositor/operations/COM_ZCombineOperation.cpp
index 7e23e7290f8..5e4f90b0269 100644
--- a/source/blender/compositor/operations/COM_ZCombineOperation.cpp
+++ b/source/blender/compositor/operations/COM_ZCombineOperation.cpp
@@ -69,7 +69,7 @@ void ZCombineAlphaOperation::executePixel(float output[4], float x, float y, Pix
this->m_depth1Reader->read(depth1, x, y, sampler);
this->m_depth2Reader->read(depth2, x, y, sampler);
- if (depth1[0] < depth2[0]) {
+ if (depth1[0] <= depth2[0]) {
this->m_image1Reader->read(color1, x, y, sampler);
this->m_image2Reader->read(color2, x, y, sampler);
}
@@ -79,10 +79,10 @@ void ZCombineAlphaOperation::executePixel(float output[4], float x, float y, Pix
}
float fac = color1[3];
float ifac = 1.0f - fac;
- output[0] = color1[0] + ifac * color2[0];
- output[1] = color1[1] + ifac * color2[1];
- output[2] = color1[2] + ifac * color2[2];
- output[3] = MAX2(color1[3], color2[3]);
+ output[0] = fac * color1[0] + ifac * color2[0];
+ output[1] = fac * color1[1] + ifac * color2[1];
+ output[2] = fac * color1[2] + ifac * color2[2];
+ output[3] = max(color1[3], color2[3]);
}
void ZCombineOperation::deinitExecution()
diff --git a/source/blender/datatoc/datatoc.c b/source/blender/datatoc/datatoc.c
index a7da037ff16..379658bb4c4 100644
--- a/source/blender/datatoc/datatoc.c
+++ b/source/blender/datatoc/datatoc.c
@@ -49,7 +49,6 @@ static char *basename(char *string)
int main(int argc, char **argv)
{
FILE *fpin, *fpout;
- char sizest[256];
long size;
int i;
@@ -79,8 +78,6 @@ int main(int argc, char **argv)
for (i = 0; i < (int)strlen(argv[1]); i++)
if (argv[1][i] == '.') argv[1][i] = '_';
- sprintf(sizest, "%d", (int)size);
-
fpout = fopen(argv[2], "w");
if (!fpout) {
fprintf(stderr, "Unable to open output <%s>\n", argv[2]);
@@ -88,7 +85,7 @@ int main(int argc, char **argv)
}
fprintf(fpout, "/* DataToC output of file <%s> */\n\n", argv[1]);
- fprintf(fpout, "int datatoc_%s_size = %s;\n", argv[1], sizest);
+ fprintf(fpout, "int datatoc_%s_size = %d;\n", argv[1], (int)size);
fprintf(fpout, "char datatoc_%s[] = {\n", argv[1]);
while (size--) {
/* if we want to open in an editor
diff --git a/source/blender/editors/animation/anim_channels_defines.c b/source/blender/editors/animation/anim_channels_defines.c
index 86f729502bb..9ceecd60bef 100644
--- a/source/blender/editors/animation/anim_channels_defines.c
+++ b/source/blender/editors/animation/anim_channels_defines.c
@@ -84,6 +84,7 @@
/* size of indent steps */
#define INDENT_STEP_SIZE 7
+/* size of string buffers used for animation channel displayed names */
#define ANIM_CHAN_NAME_SIZE 256
/* get the pointer used for some flag */
@@ -292,7 +293,7 @@ static short acf_nodetree_rootType_offset(bNodeTree *ntree)
}
}
- // unknown
+ /* unknown */
return 0;
}
@@ -422,7 +423,7 @@ static void acf_summary_name(bAnimListElem *UNUSED(ale), char *name)
BLI_strncpy(name, "DopeSheet Summary", ANIM_CHAN_NAME_SIZE);
}
-// TODO: this is really a temp icon I think
+// FIXME: this is really a temp icon I think
static int acf_summary_icon(bAnimListElem *UNUSED(ale))
{
return ICON_BORDERMOVE;
@@ -601,7 +602,6 @@ static int acf_object_icon(bAnimListElem *ale)
Object *ob = base->object;
/* icon depends on object-type */
-
switch (ob->type) {
case OB_LAMP:
return ICON_OUTLINER_OB_LAMP;
@@ -628,7 +628,6 @@ static int acf_object_icon(bAnimListElem *ale)
default:
return ICON_OBJECT_DATA;
}
-
}
/* name for object */
@@ -753,7 +752,7 @@ static void acf_group_color(bAnimContext *ac, bAnimListElem *ale, float r_color[
/* highlight only for active */
if (ale->flag & AGRP_ACTIVE)
- copy_v3_v3_char((char *)cp, agrp->cs.active);
+ copy_v3_v3_char((char *)cp, agrp->cs.select);
else
copy_v3_v3_char((char *)cp, agrp->cs.solid);
@@ -1187,7 +1186,7 @@ static void *acf_dsmat_setting_ptr(bAnimListElem *ale, int setting, short *type)
if (ma->adt)
return GET_ACF_FLAG_PTR(ma->adt->flag, type);
else
- return NULL;
+ return NULL;
default: /* unsupported */
return NULL;
@@ -1264,7 +1263,7 @@ static void *acf_dslam_setting_ptr(bAnimListElem *ale, int setting, short *type)
if (la->adt)
return GET_ACF_FLAG_PTR(la->adt->flag, type);
else
- return NULL;
+ return NULL;
default: /* unsupported */
return NULL;
@@ -1348,7 +1347,7 @@ static void *acf_dstex_setting_ptr(bAnimListElem *ale, int setting, short *type)
if (tex->adt)
return GET_ACF_FLAG_PTR(tex->adt->flag, type);
else
- return NULL;
+ return NULL;
default: /* unsupported */
return NULL;
@@ -2178,7 +2177,7 @@ static int acf_dsspk_setting_flag(bAnimContext *UNUSED(ac), int setting, short *
{
/* clear extra return data first */
*neg = 0;
-
+
switch (setting) {
case ACHANNEL_SETTING_EXPAND: /* expanded */
return SPK_DS_EXPAND;
@@ -2202,10 +2201,10 @@ static int acf_dsspk_setting_flag(bAnimContext *UNUSED(ac), int setting, short *
static void *acf_dsspk_setting_ptr(bAnimListElem *ale, int setting, short *type)
{
Speaker *spk = (Speaker *)ale->data;
-
+
/* clear extra return data first */
*type = 0;
-
+
switch (setting) {
case ACHANNEL_SETTING_EXPAND: /* expanded */
return GET_ACF_FLAG_PTR(spk->flag, type);
@@ -2477,7 +2476,7 @@ static int acf_gpl_setting_flag(bAnimContext *UNUSED(ac), int setting, short *ne
return GP_LAYER_HIDE;
case ACHANNEL_SETTING_PROTECT: /* protected */
- // *neg = 1; - if we change this to edtiability
+ // *neg = 1; - if we change this to editability
return GP_LAYER_LOCKED;
default: /* unsupported */
@@ -2526,7 +2525,7 @@ static void acf_mask_color(bAnimContext *UNUSED(ac), bAnimListElem *UNUSED(ale),
// TODO: just get this from RNA?
static int acf_mask_icon(bAnimListElem *UNUSED(ale))
{
- return ICON_GREASEPENCIL; // MASK_TODO - need real icon
+ return ICON_MOD_MASK;
}
/* check if some setting exists for this channel */
@@ -2573,15 +2572,15 @@ static void *acf_mask_setting_ptr(bAnimListElem *ale, int UNUSED(setting), short
/* mask datablock type define */
static bAnimChannelType ACF_MASKDATA =
{
- "Mask Datablock", /* type name */
+ "Mask Datablock", /* type name */
acf_mask_color, /* backdrop color */
- acf_group_backdrop, /* backdrop */
- acf_generic_indention_0, /* indent level */
- acf_generic_group_offset, /* offset */
+ acf_group_backdrop, /* backdrop */
+ acf_generic_indention_0, /* indent level */
+ acf_generic_group_offset, /* offset */
- acf_generic_idblock_name, /* name */
- acf_generic_idfill_nameprop, /* name prop */
+ acf_generic_idblock_name, /* name */
+ acf_generic_idfill_nameprop, /* name prop */
acf_mask_icon, /* icon */
acf_mask_setting_valid, /* has setting */
@@ -2642,7 +2641,7 @@ static int acf_masklay_setting_flag(bAnimContext *UNUSED(ac), int setting, short
// return GP_LAYER_HIDE;
case ACHANNEL_SETTING_PROTECT: /* protected */
- // *neg = 1; - if we change this to edtiability
+ // *neg = 1; - if we change this to editability
return MASK_LAYERFLAG_LOCKED;
default: /* unsupported */
@@ -2654,7 +2653,7 @@ static int acf_masklay_setting_flag(bAnimContext *UNUSED(ac), int setting, short
static void *acf_masklay_setting_ptr(bAnimListElem *ale, int UNUSED(setting), short *type)
{
MaskLayer *masklay = (MaskLayer *)ale->data;
-
+
/* all flags are just in agrp->flag for now... */
return GET_ACF_FLAG_PTR(masklay->flag, type);
}
@@ -2662,20 +2661,20 @@ static void *acf_masklay_setting_ptr(bAnimListElem *ale, int UNUSED(setting), sh
/* grease pencil layer type define */
static bAnimChannelType ACF_MASKLAYER =
{
- "Mask Layer", /* type name */
-
+ "Mask Layer", /* type name */
+
acf_generic_channel_color, /* backdrop color */
acf_generic_channel_backdrop, /* backdrop */
acf_generic_indention_flexible, /* indent level */
acf_generic_group_offset, /* offset */
-
- acf_masklay_name, /* name */
- acf_masklay_name_prop, /* name prop */
+
+ acf_masklay_name, /* name */
+ acf_masklay_name_prop, /* name prop */
NULL, /* icon */
-
- acf_masklay_setting_valid, /* has setting */
- acf_masklay_setting_flag, /* flag for setting */
- acf_masklay_setting_ptr /* pointer for setting */
+
+ acf_masklay_setting_valid, /* has setting */
+ acf_masklay_setting_flag, /* flag for setting */
+ acf_masklay_setting_ptr /* pointer for setting */
};
@@ -2776,7 +2775,7 @@ void ANIM_channel_debug_print_info(bAnimListElem *ale, short indent_level)
acf->name(ale, name);
else
BLI_strncpy(name, "<No name>", sizeof(name));
-
+
/* print type name + ui name */
printf("ChanType: <%s> Name: \"%s\"\n", acf->channel_type_name, name);
}
@@ -2920,7 +2919,6 @@ void ANIM_channel_setting_set(bAnimContext *ac, bAnimListElem *ale, int setting,
#define RENAME_TEXT_WIDTH 100
/* Draw the given channel */
-// TODO: make this use UI controls for the buttons
void ANIM_channel_draw(bAnimContext *ac, bAnimListElem *ale, float yminc, float ymaxc)
{
bAnimChannelType *acf = ANIM_channel_get_typeinfo(ale);
@@ -3010,20 +3008,20 @@ void ANIM_channel_draw(bAnimContext *ac, bAnimListElem *ale, float yminc, float
/* TODO: when renaming, we might not want to draw this, especially if name happens to be longer than channel */
if (acf->name) {
char name[ANIM_CHAN_NAME_SIZE]; /* hopefully this will be enough! */
-
+
/* set text color */
/* XXX: if active, highlight differently? */
if (selected)
UI_ThemeColor(TH_TEXT_HI);
else
UI_ThemeColor(TH_TEXT);
-
+
/* get name */
acf->name(ale, name);
-
+
offset += 3;
UI_DrawString(offset, ytext, name);
-
+
/* draw red underline if channel is disabled */
if ((ale->type == ANIMTYPE_FCURVE) && (ale->flag & FCURVE_DISABLED)) {
/* FIXME: replace hardcoded color here, and check on extents! */
@@ -3068,7 +3066,7 @@ void ANIM_channel_draw(bAnimContext *ac, bAnimListElem *ale, float yminc, float
}
/* check if there's enough space for the toggles if the sliders are drawn too */
- if (!(draw_sliders) || (BLI_RCT_SIZE_X(&v2d->mask) > ACHANNEL_BUTTON_WIDTH / 2) ) {
+ if (!(draw_sliders) || (BLI_rcti_size_x(&v2d->mask) > ACHANNEL_BUTTON_WIDTH / 2) ) {
/* protect... */
if (acf->has_setting(ac, ale, ACHANNEL_SETTING_PROTECT))
offset += ICON_WIDTH;
@@ -3153,7 +3151,6 @@ static void achannel_setting_rename_done_cb(bContext *C, void *ads_poin, void *U
ads->renameIndex = 0;
/* send notifiers */
- // XXX: right notifier?
WM_event_add_notifier(C, NC_ANIMATION | ND_ANIMCHAN | NA_RENAME, NULL);
}
@@ -3199,7 +3196,7 @@ static void achannel_setting_slider_shapekey_cb(bContext *C, void *key_poin, voi
{
Key *key = (Key *)key_poin;
KeyBlock *kb = (KeyBlock *)kb_poin;
- char *rna_path = key_get_curValue_rnaPath(key, kb);
+ char *rna_path = BKE_keyblock_curval_rnapath_get(key, kb);
ReportList *reports = CTX_wm_reports(C);
Scene *scene = CTX_data_scene(C);
@@ -3254,7 +3251,7 @@ static void draw_setting_widget(bAnimContext *ac, bAnimListElem *ale, bAnimChann
/* get the flag and the pointer to that flag */
flag = acf->setting_flag(ac, setting, &negflag);
ptr = acf->setting_ptr(ale, setting, &ptrsize);
- /* enabled= ANIM_channel_setting_get(ac, ale, setting); */ /* UNUSED */
+ /* enabled = ANIM_channel_setting_get(ac, ale, setting); */ /* UNUSED */
/* get the base icon for the setting */
switch (setting) {
@@ -3269,13 +3266,13 @@ static void draw_setting_widget(bAnimContext *ac, bAnimListElem *ale, bAnimChann
break;
case ACHANNEL_SETTING_EXPAND: /* expanded triangle */
- //icon= ((enabled)? ICON_TRIA_DOWN : ICON_TRIA_RIGHT);
+ //icon = ((enabled)? ICON_TRIA_DOWN : ICON_TRIA_RIGHT);
icon = ICON_TRIA_RIGHT;
tooltip = "Make channels grouped under this channel visible";
break;
case ACHANNEL_SETTING_SOLO: /* NLA Tracks only */
- //icon= ((enabled)? ICON_LAYER_ACTIVE : ICON_LAYER_USED);
+ //icon = ((enabled)? ICON_LAYER_ACTIVE : ICON_LAYER_USED);
icon = ICON_LAYER_USED;
tooltip = "NLA Track is the only one evaluated for the AnimData block it belongs to";
break;
@@ -3284,13 +3281,13 @@ static void draw_setting_widget(bAnimContext *ac, bAnimListElem *ale, bAnimChann
case ACHANNEL_SETTING_PROTECT: /* protected lock */
// TODO: what about when there's no protect needed?
- //icon= ((enabled)? ICON_LOCKED : ICON_UNLOCKED);
+ //icon = ((enabled)? ICON_LOCKED : ICON_UNLOCKED);
icon = ICON_UNLOCKED;
tooltip = "Editability of keyframes for this channel";
break;
case ACHANNEL_SETTING_MUTE: /* muted speaker */
- //icon= ((enabled)? ICON_MUTE_IPO_ON : ICON_MUTE_IPO_OFF);
+ //icon = ((enabled)? ICON_MUTE_IPO_ON : ICON_MUTE_IPO_OFF);
icon = ICON_MUTE_IPO_OFF;
if (ale->type == ALE_FCURVE)
@@ -3373,7 +3370,7 @@ void ANIM_channel_draw_widgets(bContext *C, bAnimContext *ac, bAnimListElem *ale
y = (ymaxc - yminc) / 2 + yminc;
ymid = y - 7;
/* y-coordinates for text is only 4 down from middle */
- /* ytext= y - 4; */
+ /* ytext = y - 4; */
/* no button backdrop behind icons */
uiBlockSetEmboss(block, UI_EMBOSSN);
@@ -3437,7 +3434,6 @@ void ANIM_channel_draw_widgets(bContext *C, bAnimContext *ac, bAnimListElem *ale
offset = 0;
// TODO: when drawing sliders, make those draw instead of these toggles if not enough space
-
if (v2d) {
short draw_sliders = 0;
@@ -3460,7 +3456,7 @@ void ANIM_channel_draw_widgets(bContext *C, bAnimContext *ac, bAnimListElem *ale
}
/* check if there's enough space for the toggles if the sliders are drawn too */
- if (!(draw_sliders) || (BLI_RCT_SIZE_X(&v2d->mask) > ACHANNEL_BUTTON_WIDTH / 2) ) {
+ if (!(draw_sliders) || (BLI_rcti_size_x(&v2d->mask) > ACHANNEL_BUTTON_WIDTH / 2) ) {
/* protect... */
if (acf->has_setting(ac, ale, ACHANNEL_SETTING_PROTECT)) {
offset += ICON_WIDTH;
@@ -3507,7 +3503,7 @@ void ANIM_channel_draw_widgets(bContext *C, bAnimContext *ac, bAnimListElem *ale
KeyBlock *kb = (KeyBlock *)ale->data;
Key *key = (Key *)ale->id;
- rna_path = key_get_curValue_rnaPath(key, kb);
+ rna_path = BKE_keyblock_curval_rnapath_get(key, kb);
free_path = 1;
}
diff --git a/source/blender/editors/animation/anim_channels_edit.c b/source/blender/editors/animation/anim_channels_edit.c
index d35f39a48e0..f19dbe740bc 100644
--- a/source/blender/editors/animation/anim_channels_edit.c
+++ b/source/blender/editors/animation/anim_channels_edit.c
@@ -464,7 +464,7 @@ void ANIM_flush_setting_anim_channels(bAnimContext *ac, ListBase *anim_data, bAn
/* store this level as the 'old' level now */
prevLevel = level;
- }
+ }
/* if the level is 'greater than' (i.e. less important) than the previous level... */
else if (level > prevLevel) {
/* if previous level was a base-level (i.e. 0 offset / root of one hierarchy),
@@ -600,7 +600,7 @@ static int animedit_poll_channels_nla_tweakmode_off(bContext *C)
if (ELEM3(sa->spacetype, SPACE_ACTION, SPACE_IPO, SPACE_NLA) == 0)
return 0;
- /* NLA TweakMode test */
+ /* NLA TweakMode test */
if (sa->spacetype == SPACE_NLA) {
if ((scene == NULL) || (scene->flag & SCE_NLA_EDIT_ON))
return 0;
@@ -794,7 +794,7 @@ static void rearrange_animchannel_add_to_islands(ListBase *islands, ListBase *sr
FCurve *fcu = (FCurve *)channel;
is_sel = SEL_FCU(fcu);
- }
+ }
break;
case ANIMTYPE_NLATRACK:
{
@@ -910,7 +910,7 @@ static void rearrange_nla_channels(bAnimContext *UNUSED(ac), AnimData *adt, shor
if (rearrange_func == NULL)
return;
- /* only consider NLA data if it's accessible */
+ /* only consider NLA data if it's accessible */
//if (EXPANDED_DRVD(adt) == 0)
// return;
@@ -931,7 +931,7 @@ static void rearrange_driver_channels(bAnimContext *UNUSED(ac), AnimData *adt, s
if (rearrange_func == NULL)
return;
- /* only consider drivers if they're accessible */
+ /* only consider drivers if they're accessible */
if (EXPANDED_DRVD(adt) == 0)
return;
@@ -2206,7 +2206,7 @@ static int mouse_anim_channels(bAnimContext *ac, float UNUSED(x), int channel_in
}
notifierFlags |= (ND_ANIMCHAN | NA_SELECTED);
- }
+ }
break;
case ANIMTYPE_GROUP:
@@ -2219,7 +2219,7 @@ static int mouse_anim_channels(bAnimContext *ac, float UNUSED(x), int channel_in
agrp->flag ^= AGRP_SELECTED;
}
else if (selectmode == -1) {
- /* select all in group (and deselect everthing else) */
+ /* select all in group (and deselect everthing else) */
FCurve *fcu;
/* deselect all other channels */
@@ -2228,7 +2228,7 @@ static int mouse_anim_channels(bAnimContext *ac, float UNUSED(x), int channel_in
/* only select channels in group and group itself */
for (fcu = agrp->channels.first; fcu && fcu->grp == agrp; fcu = fcu->next)
fcu->flag |= FCURVE_SELECTED;
- agrp->flag |= AGRP_SELECTED;
+ agrp->flag |= AGRP_SELECTED;
}
else {
/* select group by itself */
@@ -2306,7 +2306,7 @@ static int mouse_anim_channels(bAnimContext *ac, float UNUSED(x), int channel_in
/* invert selection status of this layer only */
gpl->flag ^= GP_LAYER_SELECT;
}
- else {
+ else {
/* select layer by itself */
ANIM_deselect_anim_channels(ac, ac->data, ac->datatype, 0, ACHANNEL_SETFLAG_CLEAR);
gpl->flag |= GP_LAYER_SELECT;
diff --git a/source/blender/editors/animation/anim_deps.c b/source/blender/editors/animation/anim_deps.c
index 6ce9fc638be..98071fafc1e 100644
--- a/source/blender/editors/animation/anim_deps.c
+++ b/source/blender/editors/animation/anim_deps.c
@@ -142,7 +142,6 @@ static void animchan_sync_group(bAnimContext *ac, bAnimListElem *ale, bActionGro
/* check if there are bones, and whether the name matches any
* NOTE: this feature will only really work if groups by default contain the F-Curves for a single bone
*/
- // TODO: if bone gets renamed, it would be best to be able to rename the group
if (ob->pose) {
bPoseChannel *pchan = BKE_pose_channel_find_name(ob->pose, agrp->name);
bArmature *arm = ob->data;
@@ -319,7 +318,6 @@ void ANIM_sync_animchannels_to_data(const bContext *C)
FCurve *active_fcurve = NULL;
/* get animation context info for filtering the channels */
- // TODO: check on whether we need to set the area specially instead, since active area might not be ok?
if (ANIM_animdata_get_context(C, &ac) == 0)
return;
diff --git a/source/blender/editors/animation/anim_draw.c b/source/blender/editors/animation/anim_draw.c
index 620f5de9db7..01c0a95e200 100644
--- a/source/blender/editors/animation/anim_draw.c
+++ b/source/blender/editors/animation/anim_draw.c
@@ -261,8 +261,8 @@ void ANIM_draw_previewrange(const bContext *C, View2D *v2d)
/* only draw two separate 'curtains' if there's no overlap between them */
if (PSFRA < PEFRA) {
glRectf(v2d->cur.xmin, v2d->cur.ymin, (float)PSFRA, v2d->cur.ymax);
- glRectf((float)PEFRA, v2d->cur.ymin, v2d->cur.xmax, v2d->cur.ymax);
- }
+ glRectf((float)PEFRA, v2d->cur.ymin, v2d->cur.xmax, v2d->cur.ymax);
+ }
else {
glRectf(v2d->cur.xmin, v2d->cur.ymin, v2d->cur.xmax, v2d->cur.ymax);
}
diff --git a/source/blender/editors/animation/anim_filter.c b/source/blender/editors/animation/anim_filter.c
index 209414550e3..721b3473792 100644
--- a/source/blender/editors/animation/anim_filter.c
+++ b/source/blender/editors/animation/anim_filter.c
@@ -99,7 +99,7 @@
/* ----------- Private Stuff - Action Editor ------------- */
/* Get shapekey data being edited (for Action Editor -> ShapeKey mode) */
-/* Note: there's a similar function in key.c (ob_get_key) */
+/* Note: there's a similar function in key.c (BKE_key_from_object) */
static Key *actedit_get_shapekeys(bAnimContext *ac)
{
Scene *scene = ac->scene;
@@ -114,7 +114,7 @@ static Key *actedit_get_shapekeys(bAnimContext *ac)
//if (saction->pin) return NULL;
/* shapekey data is stored with geometry data */
- key = ob_get_key(ob);
+ key = BKE_key_from_object(ob);
if (key) {
if (key->type == KEY_RELATIVE)
@@ -163,30 +163,30 @@ static short actedit_get_context(bAnimContext *ac, SpaceAction *saction)
ac->mode = saction->mode;
return 1;
-
+
case SACTCONT_GPENCIL: /* Grease Pencil */ /* XXX review how this mode is handled... */
/* update scene-pointer (no need to check for pinning yet, as not implemented) */
saction->ads.source = (ID *)ac->scene;
-
+
ac->datatype = ANIMCONT_GPENCIL;
ac->data = &saction->ads;
-
+
ac->mode = saction->mode;
return 1;
-
- case SACTCONT_MASK: /* Grease Pencil */ /* XXX review how this mode is handled... */
- /* update scene-pointer (no need to check for pinning yet, as not implemented) */
+
+ case SACTCONT_MASK: /* Mask */ /* XXX review how this mode is handled... */
{
/* TODO, other methods to get the mask */
// Sequence *seq = BKE_sequencer_active_get(ac->scene);
//MovieClip *clip = ac->scene->clip;
// struct Mask *mask = seq ? seq->mask : NULL;
-
+
+ /* update scene-pointer (no need to check for pinning yet, as not implemented) */
saction->ads.source = (ID *)ac->scene;
-
+
ac->datatype = ANIMCONT_MASK;
ac->data = &saction->ads;
-
+
ac->mode = saction->mode;
return 1;
}
@@ -682,18 +682,18 @@ static bAnimListElem *make_new_animlistelem(void *data, short datatype, ID *owne
ale->datatype = ALE_ACT;
ale->adt = BKE_animdata_from_id(data);
- }
+ }
break;
case ANIMTYPE_DSSPK:
{
Speaker *spk = (Speaker *)data;
AnimData *adt = spk->adt;
-
+
ale->flag = FILTER_SPK_OBJD(spk);
-
+
ale->key_data = (adt) ? adt->action : NULL;
ale->datatype = ALE_ACT;
-
+
ale->adt = BKE_animdata_from_id(data);
}
break;
@@ -799,7 +799,7 @@ static bAnimListElem *make_new_animlistelem(void *data, short datatype, ID *owne
/* the corresponding keyframes are from the animdata */
if (ale->adt && ale->adt->action) {
bAction *act = ale->adt->action;
- char *rna_path = key_get_curValue_rnaPath(key, kb);
+ char *rna_path = BKE_keyblock_curval_rnapath_get(key, kb);
/* try to find the F-Curve which corresponds to this exactly,
* then free the MEM_alloc'd string
@@ -811,7 +811,7 @@ static bAnimListElem *make_new_animlistelem(void *data, short datatype, ID *owne
}
ale->datatype = (ale->key_data) ? ALE_FCURVE : ALE_NONE;
}
- }
+ }
break;
case ANIMTYPE_GPLAYER:
@@ -824,18 +824,18 @@ static bAnimListElem *make_new_animlistelem(void *data, short datatype, ID *owne
ale->datatype = ALE_GPFRAME;
}
break;
-
+
case ANIMTYPE_MASKLAYER:
{
MaskLayer *masklay = (MaskLayer *)data;
-
+
ale->flag = masklay->flag;
-
+
ale->key_data = NULL;
ale->datatype = ALE_MASKLAY;
}
break;
-
+
case ANIMTYPE_NLATRACK:
{
NlaTrack *nlt = (NlaTrack *)data;
@@ -980,6 +980,27 @@ static short skip_fcurve_with_name(bDopeSheet *ads, FCurve *fcu, ID *owner_id)
return 1;
}
+/* Check if F-Curve has errors and/or is disabled
+ * > returns: (bool) True if F-Curve has errors/is disabled
+ */
+static short fcurve_has_errors(FCurve *fcu)
+{
+ /* F-Curve disabled - path eval error */
+ if (fcu->flag & FCURVE_DISABLED) {
+ return 1;
+ }
+
+ /* driver? */
+ if (fcu->driver) {
+ /* for now, just check if the entire thing got disabled... */
+ if (fcu->driver->flag & DRIVER_FLAG_INVALID)
+ return 1;
+ }
+
+ /* no errors found */
+ return 0;
+}
+
/* find the next F-Curve that is usable for inclusion */
static FCurve *animfilter_fcurve_next(bDopeSheet *ads, FCurve *first, bActionGroup *grp, int filter_mode, ID *owner_id)
{
@@ -1002,7 +1023,7 @@ static FCurve *animfilter_fcurve_next(bDopeSheet *ads, FCurve *first, bActionGro
if (skip_fcurve_selected_data(ads, fcu, owner_id, filter_mode))
continue;
}
- }
+ }
/* only include if visible (Graph Editor check, not channels check) */
if (!(filter_mode & ANIMFILTER_CURVE_VISIBLE) || (fcu->flag & FCURVE_VISIBLE)) {
@@ -1018,6 +1039,13 @@ static FCurve *animfilter_fcurve_next(bDopeSheet *ads, FCurve *first, bActionGro
continue;
}
+ /* error-based filtering... */
+ if ((ads) && (ads->filterflag & ADS_FILTER_ONLY_ERRORS)) {
+ /* skip if no errors... */
+ if (fcurve_has_errors(fcu) == 0)
+ continue;
+ }
+
/* this F-Curve can be used, so return it */
return fcu;
}
@@ -1138,7 +1166,6 @@ static size_t animfilter_action(bAnimContext *ac, ListBase *anim_data, bDopeShee
/* don't include anything from this action if it is linked in from another file,
* and we're getting stuff for editing...
*/
- // TODO: need a way of tagging other channels that may also be affected...
if ((filter_mode & ANIMFILTER_FOREDIT) && (act->id.lib))
return 0;
@@ -1184,7 +1211,7 @@ static size_t animfilter_nla(bAnimContext *UNUSED(ac), ListBase *anim_data, bDop
*/
if (!(ads->filterflag & ADS_FILTER_NLA_NOACT) || (adt->action)) {
/* there isn't really anything editable here, so skip if need editable */
- if ((filter_mode & ANIMFILTER_FOREDIT) == 0) {
+ if ((filter_mode & ANIMFILTER_FOREDIT) == 0) {
/* just add the action track now (this MUST appear for drawing)
* - as AnimData may not have an action, we pass a dummy pointer just to get the list elem created, then
* overwrite this with the real value - REVIEW THIS...
@@ -1240,11 +1267,11 @@ static size_t animfilter_block_data(bAnimContext *ac, ListBase *anim_data, bDope
{
AnimData *adt = BKE_animdata_from_id(id);
size_t items = 0;
-
+
/* image object datablocks have no anim-data so check for NULL */
if (adt) {
IdAdtTemplate *iat = (IdAdtTemplate *)id;
-
+
/* NOTE: this macro is used instead of inlining the logic here, since this sort of filtering is still needed
* in a few places in he rest of the code still - notably for the few cases where special mode-based
* different types of data expanders are required.
@@ -1265,7 +1292,7 @@ static size_t animfilter_block_data(bAnimContext *ac, ListBase *anim_data, bDope
}
);
}
-
+
return items;
}
@@ -1283,7 +1310,6 @@ static size_t animdata_filter_shapekey(bAnimContext *ac, ListBase *anim_data, Ke
/* loop through the channels adding ShapeKeys as appropriate */
for (kb = key->block.first; kb; kb = kb->next) {
/* skip the first one, since that's the non-animatable basis */
- // XXX maybe in future this may become handy?
if (kb == key->block.first) continue;
/* only work with this channel and its subchannels if it is editable */
@@ -1597,7 +1623,6 @@ static size_t animdata_filter_ds_material(bAnimContext *ac, ListBase *anim_data,
/* did we find anything? */
if (tmp_items) {
/* include material-expand widget first */
- // hmm... do we need to store the index of this material in the array anywhere?
if (filter_mode & ANIMFILTER_LIST_CHANNELS) {
/* check if filtering by active status */
if (ANIMCHANNEL_ACTIVEOK(ma)) {
@@ -1809,11 +1834,11 @@ static size_t animdata_filter_ds_obdata(bAnimContext *ac, ListBase *anim_data, b
{
Lamp *la = ob->data;
bNodeTree *ntree = la->nodetree;
-
+
/* nodetree */
if ((ntree) && !(ads->filterflag & ADS_FILTER_NONTREE))
tmp_items += animdata_filter_ds_nodetree(ac, &tmp_data, ads, &la->id, ntree, filter_mode);
-
+
/* textures */
if (!(ads->filterflag & ADS_FILTER_NOTEX))
tmp_items += animdata_filter_ds_textures(ac, &tmp_data, ads, &la->id, filter_mode);
@@ -1943,7 +1968,7 @@ static size_t animdata_filter_dopesheet_ob(bAnimContext *ac, ListBase *anim_data
/* filter data contained under object first */
BEGIN_ANIMFILTER_SUBCHANNELS(EXPANDED_OBJC(ob))
{
- Key *key = ob_get_key(ob);
+ Key *key = BKE_key_from_object(ob);
/* object-level animation */
if ((ob->adt) && !(ads->filterflag & ADS_FILTER_NOOBJ)) {
@@ -2277,7 +2302,7 @@ static size_t animdata_filter_animchan(bAnimContext *ac, ListBase *anim_data, bD
size_t items = 0;
/* data to filter depends on channel type */
- // XXX: only common channel-types have been handled for now
+ /* NOTE: only common channel-types have been handled for now. More can be added as necessary */
switch (channel->type) {
case ANIMTYPE_SUMMARY:
items += animdata_filter_dopesheet(ac, anim_data, ads, filter_mode);
@@ -2290,6 +2315,10 @@ static size_t animdata_filter_animchan(bAnimContext *ac, ListBase *anim_data, bD
case ANIMTYPE_OBJECT:
items += animdata_filter_dopesheet_ob(ac, anim_data, ads, channel->data, filter_mode);
break;
+
+ default:
+ printf("ERROR: Unsupported channel type (%d) in animdata_filter_animchan()\n", channel->type);
+ break;
}
return items;
@@ -2414,9 +2443,9 @@ size_t ANIM_animdata_filter(bAnimContext *ac, ListBase *anim_data, int filter_mo
}
break;
- case ANIMCONT_FCURVES: /* Graph Editor -> FCurves/Animation Editing */
+ case ANIMCONT_FCURVES: /* Graph Editor -> F-Curves/Animation Editing */
case ANIMCONT_DRIVERS: /* Graph Editor -> Drivers Editing */
- case ANIMCONT_NLA: /* NLA Editor */
+ case ANIMCONT_NLA: /* NLA Editor */
{
/* all of these editors use the basic DopeSheet data for filtering options, but don't have all the same features */
items = animdata_filter_dopesheet(ac, anim_data, data, filter_mode);
diff --git a/source/blender/editors/animation/anim_intern.h b/source/blender/editors/animation/anim_intern.h
index cf84eb04b10..54c7f7ea30f 100644
--- a/source/blender/editors/animation/anim_intern.h
+++ b/source/blender/editors/animation/anim_intern.h
@@ -50,7 +50,9 @@ void ANIM_OT_keyframe_delete(struct wmOperatorType *ot);
* required for each space.
*/
void ANIM_OT_keyframe_insert_menu(struct wmOperatorType *ot);
+
void ANIM_OT_keyframe_delete_v3d(struct wmOperatorType *ot);
+void ANIM_OT_keyframe_clear_v3d(struct wmOperatorType *ot);
/* Keyframe managment operators for UI buttons (RMB menu). */
void ANIM_OT_keyframe_insert_button(struct wmOperatorType *ot);
@@ -80,4 +82,4 @@ void ANIM_OT_driver_button_remove(struct wmOperatorType *ot);
void ANIM_OT_copy_driver_button(struct wmOperatorType *ot);
void ANIM_OT_paste_driver_button(struct wmOperatorType *ot);
-#endif // __ANIM_INTERN_H__
+#endif /* __ANIM_INTERN_H__ */
diff --git a/source/blender/editors/animation/anim_ipo_utils.c b/source/blender/editors/animation/anim_ipo_utils.c
index 5295950546d..d8e3349e998 100644
--- a/source/blender/editors/animation/anim_ipo_utils.c
+++ b/source/blender/editors/animation/anim_ipo_utils.c
@@ -89,7 +89,7 @@ int getname_anim_fcurve(char *name, ID *id, FCurve *fcu)
* i.e. Bone1.Location.X, or Object.Location.X
* 2) <array-index> <property-name> (<struct name>)
* i.e. X Location (Bone1), or X Location (Object)
- *
+ *
* Currently, option 2 is in use, to try and make it easier to quickly identify F-Curves (it does have
* problems with looking rather odd though). Option 1 is better in terms of revealing a consistent sense of
* hierarchy though, which isn't so clear with option 2.
diff --git a/source/blender/editors/animation/anim_markers.c b/source/blender/editors/animation/anim_markers.c
index 445b684c261..852f3fa5469 100644
--- a/source/blender/editors/animation/anim_markers.c
+++ b/source/blender/editors/animation/anim_markers.c
@@ -150,7 +150,7 @@ int ED_markers_post_apply_transform(ListBase *markers, Scene *scene, int mode, f
break;
case TFM_TIME_SCALE:
- {
+ {
/* rescale the distance between the marker and the current frame */
marker->frame = cfra + (int)floorf(((float)(marker->frame - cfra) * value) + 0.5f);
changed++;
@@ -249,7 +249,7 @@ void ED_markers_get_minmax(ListBase *markers, short sel, float *first, float *la
min = (float)marker->frame;
if (marker->frame > max)
max = (float)marker->frame;
- }
+ }
}
}
@@ -278,7 +278,7 @@ static void add_marker_to_cfra_elem(ListBase *lb, TimeMarker *marker, short only
return;
}
else if (ce->cfra > marker->frame) break;
- }
+ }
cen = MEM_callocN(sizeof(CfraElem), "add_to_cfra_elem");
if (ce) BLI_insertlinkbefore(lb, ce, cen);
@@ -354,13 +354,13 @@ static void draw_marker(View2D *v2d, TimeMarker *marker, int cfra, int flag)
xpos = marker->frame;
/* no time correction for framelen! space is drawn with old values */
- ypixels = BLI_RCT_SIZE_Y(&v2d->mask);
+ ypixels = BLI_rcti_size_y(&v2d->mask);
UI_view2d_getscale(v2d, &xscale, &yscale);
glScalef(1.0f / xscale, 1.0f, 1.0f);
glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
/* vertical line - dotted */
#ifdef DURIAN_CAMERA_SWITCH
@@ -504,7 +504,7 @@ static int ed_markers_poll_markers_exist(bContext *C)
* "custom"/third-tier invoke() callback supplied as the last arg (which would normally
* be the operator's invoke() callback elsewhere)
*
- * < invoke_func: (fn(bContext*, wmOperator*, wmEvent*)=int) "standard" invoke function
+ * < invoke_func: (fn(bContext *, wmOperator *, wmEvent *)=int) "standard" invoke function
* that operator would otherwise have used. If NULL, the operator's standard
* exec() callback will be called instead in the appropriate places.
*/
@@ -522,7 +522,7 @@ static int ed_markers_opwrap_invoke_custom(bContext *C, wmOperator *op, wmEvent
else if (op->type->exec)
retval = op->type->exec(C, op);
else
- BKE_report(op->reports, RPT_ERROR, "Programming error: operator doesn't actually have code to do anything!");
+ BKE_report(op->reports, RPT_ERROR, "Programming error: operator does not actually have code to do anything!");
/* return status modifications - for now, make this spacetype dependent as above */
if (sa->spacetype != SPACE_TIME) {
@@ -726,7 +726,7 @@ static int ed_marker_move_cancel(bContext *C, wmOperator *op)
{
RNA_int_set(op->ptr, "frames", 0);
ed_marker_move_apply(op);
- ed_marker_move_exit(C, op);
+ ed_marker_move_exit(C, op);
WM_event_add_notifier(C, NC_SCENE | ND_MARKERS, NULL);
WM_event_add_notifier(C, NC_ANIMATION | ND_MARKERS, NULL);
@@ -773,7 +773,7 @@ static int ed_marker_move_modal(bContext *C, wmOperator *op, wmEvent *evt)
if (hasNumInput(&mm->num))
break;
- dx = BLI_RCT_SIZE_X(&v2d->cur) / BLI_RCT_SIZE_X(&v2d->mask);
+ dx = BLI_rctf_size_x(&v2d->cur) / BLI_rcti_size_x(&v2d->mask);
if (evt->x != mm->evtx) { /* XXX maybe init for first time */
int a, offs, totmark = 0;
@@ -821,7 +821,7 @@ static int ed_marker_move_modal(bContext *C, wmOperator *op, wmEvent *evt)
}
else {
/* we only print the offset */
- if (mm->slink->spacetype == SPACE_TIME) {
+ if (mm->slink->spacetype == SPACE_TIME) {
SpaceTime *stime = (SpaceTime *)mm->slink;
if (stime->flag & TIME_DRAWFRAMES)
BLI_snprintf(str, sizeof(str), "Marker offset %d ", offs);
@@ -1030,7 +1030,7 @@ static int ed_marker_select(bContext *C, wmEvent *evt, int extend, int camera)
x = evt->x - ar->winrct.xmin;
y = evt->y - ar->winrct.ymin;
- UI_view2d_region_to_view(v2d, x, y, &viewx, NULL);
+ UI_view2d_region_to_view(v2d, x, y, &viewx, NULL);
cfra = ED_markers_find_nearest_marker_time(markers, viewx);
@@ -1377,7 +1377,7 @@ static int ed_marker_make_links_scene_exec(bContext *C, wmOperator *op)
}
if (scene_to == CTX_data_scene(C)) {
- BKE_report(op->reports, RPT_ERROR, "Can't re-link markers into the same scene");
+ BKE_report(op->reports, RPT_ERROR, "Cannot re-link markers into the same scene");
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/animation/anim_ops.c b/source/blender/editors/animation/anim_ops.c
index e24a4d49a05..ca036a8540e 100644
--- a/source/blender/editors/animation/anim_ops.c
+++ b/source/blender/editors/animation/anim_ops.c
@@ -172,7 +172,7 @@ static void ANIM_OT_change_frame(wmOperatorType *ot)
ot->poll = change_frame_poll;
/* flags */
- ot->flag = OPTYPE_BLOCKING | OPTYPE_UNDO;
+ ot->flag = OPTYPE_BLOCKING | OPTYPE_UNDO | OPTYPE_GRAB_POINTER;
/* rna */
RNA_def_int(ot->srna, "frame", 0, MINAFRAME, MAXFRAME, "Frame", "", MINAFRAME, MAXFRAME);
@@ -290,6 +290,7 @@ void ED_operatortypes_anim(void)
WM_operatortype_append(ANIM_OT_keyframe_delete);
WM_operatortype_append(ANIM_OT_keyframe_insert_menu);
WM_operatortype_append(ANIM_OT_keyframe_delete_v3d);
+ WM_operatortype_append(ANIM_OT_keyframe_clear_v3d);
WM_operatortype_append(ANIM_OT_keyframe_insert_button);
WM_operatortype_append(ANIM_OT_keyframe_delete_button);
WM_operatortype_append(ANIM_OT_keyframe_clear_button);
diff --git a/source/blender/editors/animation/drivers.c b/source/blender/editors/animation/drivers.c
index 672e11ac613..25833c13925 100644
--- a/source/blender/editors/animation/drivers.c
+++ b/source/blender/editors/animation/drivers.c
@@ -91,7 +91,7 @@ FCurve *verify_driver_fcurve(ID *id, const char rna_path[], const int array_inde
adt = BKE_animdata_from_id(id);
if ((adt == NULL) && (add))
adt = BKE_id_add_animdata(id);
- if (adt == NULL) {
+ if (adt == NULL) {
/* if still none (as not allowed to add, or ID doesn't have animdata for some reason) */
return NULL;
}
@@ -147,7 +147,7 @@ short ANIM_add_driver(ReportList *reports, ID *id, const char rna_path[], int ar
RNA_id_pointer_create(id, &id_ptr);
if ((RNA_path_resolve(&id_ptr, rna_path, &ptr, &prop) == 0) || (prop == NULL)) {
BKE_reportf(reports, RPT_ERROR,
- "Could not add Driver, as RNA Path is invalid for the given ID (ID = %s, Path = %s)",
+ "Could not add driver, as RNA path is invalid for the given ID (ID = %s, path = %s)",
id->name, rna_path);
return 0;
}
@@ -310,7 +310,7 @@ short ANIM_copy_driver(ReportList *reports, ID *id, const char rna_path[], int a
RNA_id_pointer_create(id, &id_ptr);
if ((RNA_path_resolve(&id_ptr, rna_path, &ptr, &prop) == 0) || (prop == NULL)) {
BKE_reportf(reports, RPT_ERROR,
- "Could not find Driver to copy, as RNA Path is invalid for the given ID (ID = %s, Path = %s)",
+ "Could not find driver to copy, as RNA path is invalid for the given ID (ID = %s, path = %s)",
id->name, rna_path);
return 0;
}
@@ -357,14 +357,14 @@ short ANIM_paste_driver(ReportList *reports, ID *id, const char rna_path[], int
RNA_id_pointer_create(id, &id_ptr);
if ((RNA_path_resolve(&id_ptr, rna_path, &ptr, &prop) == 0) || (prop == NULL)) {
BKE_reportf(reports, RPT_ERROR,
- "Could not paste Driver, as RNA Path is invalid for the given ID (ID = %s, Path = %s)",
+ "Could not paste driver, as RNA path is invalid for the given ID (ID = %s, path = %s)",
id->name, rna_path);
return 0;
}
/* if the buffer is empty, cannot paste... */
if (channeldriver_copypaste_buf == NULL) {
- BKE_report(reports, RPT_ERROR, "Paste Driver: No Driver to paste");
+ BKE_report(reports, RPT_ERROR, "Paste driver: no driver to paste");
return 0;
}
@@ -478,7 +478,7 @@ static int add_driver_button_exec(bContext *C, wmOperator *op)
char *path = get_driver_path_hack(C, &ptr, prop);
short flags = CREATEDRIVER_WITH_DEFAULT_DVAR;
- if (path) {
+ if (path) {
success += ANIM_add_driver(op->reports, ptr.id.data, path, index, flags, DRIVER_TYPE_PYTHON);
MEM_freeN(path);
diff --git a/source/blender/editors/animation/fmodifier_ui.c b/source/blender/editors/animation/fmodifier_ui.c
index e254fb7a3c4..79a4c9a769d 100644
--- a/source/blender/editors/animation/fmodifier_ui.c
+++ b/source/blender/editors/animation/fmodifier_ui.c
@@ -74,13 +74,6 @@
#define B_REDR 1
#define B_FMODIFIER_REDRAW 20
-/* macro for use here to draw background box and set height */
-// XXX for now, roundbox has it's callback func set to NULL to not intercept events
-#define DRAW_BACKDROP(height) \
- { \
- uiDefBut(block, ROUNDBOX, B_REDR, "", -3, yco - height, width + 3, height - 1, NULL, 5.0, 0.0, 12.0, (float)rb_col, ""); \
- } (void)0
-
/* callback to verify modifier data */
static void validate_fmodifier_cb(bContext *UNUSED(C), void *fcm_v, void *UNUSED(arg))
{
@@ -118,6 +111,7 @@ static void draw_modifier__generator(uiLayout *layout, ID *id, FModifier *fcm, s
uiBlock *block;
uiBut *but;
PointerRNA ptr;
+ short bwidth = width - 30; /* max button width */
/* init the RNA-pointer */
RNA_pointer_create(id, &RNA_FModifierFunctionGenerator, fcm, &ptr);
@@ -126,10 +120,10 @@ static void draw_modifier__generator(uiLayout *layout, ID *id, FModifier *fcm, s
/* col = uiLayoutColumn(layout, TRUE); */ /* UNUSED */
block = uiLayoutGetBlock(layout);
uiBlockBeginAlign(block);
- but = uiDefButR(block, MENU, B_FMODIFIER_REDRAW, NULL, 0, 0, width - 30, UI_UNIT_Y, &ptr, "mode", -1, 0, 0, -1, -1, NULL);
+ but = uiDefButR(block, MENU, B_FMODIFIER_REDRAW, NULL, 0, 0, bwidth, UI_UNIT_Y, &ptr, "mode", -1, 0, 0, -1, -1, NULL);
uiButSetFunc(but, validate_fmodifier_cb, fcm, NULL);
-
- uiDefButR(block, TOG, B_FMODIFIER_REDRAW, NULL, 0, 0, width - 30, UI_UNIT_Y, &ptr, "use_additive", -1, 0, 0, -1, -1, NULL);
+
+ uiDefButR(block, TOG, B_FMODIFIER_REDRAW, NULL, 0, 0, bwidth, UI_UNIT_Y, &ptr, "use_additive", -1, 0, 0, -1, -1, NULL);
uiBlockEndAlign(block);
/* now add settings for individual modes */
@@ -139,50 +133,62 @@ static void draw_modifier__generator(uiLayout *layout, ID *id, FModifier *fcm, s
float *cp = NULL;
char xval[32];
unsigned int i;
+ int maxXWidth;
/* draw polynomial order selector */
row = uiLayoutRow(layout, FALSE);
block = uiLayoutGetBlock(row);
- but = uiDefButI(block, NUM, B_FMODIFIER_REDRAW, IFACE_("Poly Order:"), 10, 0, width - 30, 19,
+ but = uiDefButI(block, NUM, B_FMODIFIER_REDRAW, IFACE_("Poly Order:"), 10, 0, bwidth, 20,
&data->poly_order, 1, 100, 0, 0,
TIP_("'Order' of the Polynomial (for a polynomial with n terms, 'order' is n-1)"));
uiButSetFunc(but, validate_fmodifier_cb, fcm, NULL);
+ /* calculate maximum width of label for "x^n" labels */
+ if (data->arraysize > 2) {
+ BLI_snprintf(xval, sizeof(xval), "x^%u", data->arraysize);
+ maxXWidth = UI_GetStringWidth(xval) + 10; /* XXX: UI_GetStringWidth is not accurate */
+ }
+ else {
+ /* basic size (just "x") */
+ maxXWidth = 15;
+ }
+
/* draw controls for each coefficient and a + sign at end of row */
row = uiLayoutRow(layout, TRUE);
block = uiLayoutGetBlock(row);
cp = data->coefficients;
for (i = 0; (i < data->arraysize) && (cp); i++, cp++) {
- /* To align with first line */
+ /* To align with first line... */
if (i)
- uiDefBut(block, LABEL, 1, " ", 0, 0, 50, 20, NULL, 0.0, 0.0, 0, 0, "");
+ uiDefBut(block, LABEL, 1, " ", 0, 0, 40, 20, NULL, 0.0, 0.0, 0, 0, "");
else
- uiDefBut(block, LABEL, 1, "y =", 0, 0, 50, 20, NULL, 0.0, 0.0, 0, 0, "");
+ uiDefBut(block, LABEL, 1, "y =", 0, 0, 40, 20, NULL, 0.0, 0.0, 0, 0, "");
+
/* coefficient */
- uiDefButF(block, NUM, B_FMODIFIER_REDRAW, "", 0, 0, 150, 20, cp, -UI_FLT_MAX, UI_FLT_MAX,
+ uiDefButF(block, NUM, B_FMODIFIER_REDRAW, "", 0, 0, bwidth / 2, 20, cp, -UI_FLT_MAX, UI_FLT_MAX,
10, 3, TIP_("Coefficient for polynomial"));
/* 'x' param (and '+' if necessary) */
if (i == 0)
- strcpy(xval, "");
+ BLI_strncpy(xval, "", sizeof(xval));
else if (i == 1)
- strcpy(xval, "x");
+ BLI_strncpy(xval, "x", sizeof(xval));
else
- sprintf(xval, "x^%u", i);
- uiDefBut(block, LABEL, 1, xval, 0, 0, 50, 20, NULL, 0.0, 0.0, 0, 0, TIP_("Power of x"));
+ BLI_snprintf(xval, sizeof(xval), "x^%u", i);
+ uiDefBut(block, LABEL, 1, xval, 0, 0, maxXWidth, 20, NULL, 0.0, 0.0, 0, 0, TIP_("Power of x"));
if ( (i != (data->arraysize - 1)) || ((i == 0) && data->arraysize == 2) ) {
- uiDefBut(block, LABEL, 1, "+", 0, 0, 30, 20, NULL, 0.0, 0.0, 0, 0, "");
+ uiDefBut(block, LABEL, 1, "+", 0, 0, 20, 20, NULL, 0.0, 0.0, 0, 0, "");
/* next coefficient on a new row */
row = uiLayoutRow(layout, TRUE);
block = uiLayoutGetBlock(row);
}
else {
- /* For alignement in UI! */
- uiDefBut(block, LABEL, 1, " ", 0, 0, 30, 20, NULL, 0.0, 0.0, 0, 0, "");
+ /* For alignment in UI! */
+ uiDefBut(block, LABEL, 1, " ", 0, 0, 20, 20, NULL, 0.0, 0.0, 0, 0, "");
}
}
break;
diff --git a/source/blender/editors/animation/keyframes_draw.c b/source/blender/editors/animation/keyframes_draw.c
index 6c9105dde69..e520a95aa95 100644
--- a/source/blender/editors/animation/keyframes_draw.c
+++ b/source/blender/editors/animation/keyframes_draw.c
@@ -322,7 +322,7 @@ static void nupdate_abk_bezt(void *node, void *data)
/* just add the BezTriple to the buffer if there's space, or allocate a new one */
if (abk->numBezts >= MAX_ABK_BUFSIZE) {
// TODO: need to allocate new array to cater...
- //bezts_extra= MEM_callocN(...);
+ //bezts_extra = MEM_callocN(...);
if (G.debug & G_DEBUG)
printf("FIXME: nupdate_abk_bezt() missing case for too many overlapping BezTriples\n");
}
@@ -345,7 +345,7 @@ static BezTriple *abk_get_bezt_with_value(ActBeztColumn *abk, float value)
return NULL;
/* look over each BezTriple in this container */
- for (i = 0; i < abk->numBezts; i++) {
+ for (i = 0; i < abk->numBezts; i++) {
/* only do exact match for now... */
if (/*i >= MAX_ABK_BUFSIZE*/ 0) {
// TODO: this case needs special handling
@@ -582,7 +582,7 @@ void draw_keyframe_shape(float x, float y, float xscale, float hsize, short sel,
}
/* tweak size of keyframe shape according to type of keyframe
- * - 'proper' keyframes have key_type=0, so get drawn at full size
+ * - 'proper' keyframes have key_type = 0, so get drawn at full size
*/
hsize -= 0.5f * key_type;
@@ -960,7 +960,7 @@ void fcurve_to_keylist(AnimData *adt, FCurve *fcu, DLRBT_Tree *keys, DLRBT_Tree
if (fcu && fcu->totvert && fcu->bezt) {
/* apply NLA-mapping (if applicable) */
- if (adt)
+ if (adt)
ANIM_nla_mapping_apply_fcurve(adt, fcu, 0, 0);
/* if getting long keyframes too, grab the BezTriples in a BST for
diff --git a/source/blender/editors/animation/keyframes_edit.c b/source/blender/editors/animation/keyframes_edit.c
index b277d0eccb5..015c2667a93 100644
--- a/source/blender/editors/animation/keyframes_edit.c
+++ b/source/blender/editors/animation/keyframes_edit.c
@@ -154,7 +154,7 @@ short ANIM_fcurve_keyframes_loop(KeyframeEditData *ked, FCurve *fcu, KeyframeEdi
if (fcu_cb)
fcu_cb(fcu);
- /* done */
+ /* done */
return 0;
}
@@ -639,7 +639,7 @@ static short snap_bezier_horizontal(KeyframeEditData *UNUSED(ked), BezTriple *be
if (ELEM3(bezt->h1, HD_AUTO, HD_AUTO_ANIM, HD_VECT)) bezt->h1 = HD_ALIGN;
if (ELEM3(bezt->h2, HD_AUTO, HD_AUTO_ANIM, HD_VECT)) bezt->h2 = HD_ALIGN;
}
- return 0;
+ return 0;
}
/* value to snap to is stored in the custom data -> first float value slot */
@@ -880,7 +880,7 @@ KeyframeEditFunc ANIM_editkeyframes_ipo(short code)
switch (code) {
case BEZT_IPO_CONST: /* constant */
return set_bezt_constant;
- case BEZT_IPO_LIN: /* linear */
+ case BEZT_IPO_LIN: /* linear */
return set_bezt_linear;
default: /* bezier */
return set_bezt_bezier;
@@ -930,7 +930,7 @@ KeyframeEditFunc ANIM_editkeyframes_keytype(short code)
case BEZT_KEYTYPE_JITTER: /* jitter keyframe */
return set_keytype_jitter;
- case BEZT_KEYTYPE_KEYFRAME: /* proper keyframe */
+ case BEZT_KEYTYPE_KEYFRAME: /* proper keyframe */
default:
return set_keytype_keyframe;
}
diff --git a/source/blender/editors/animation/keyframes_general.c b/source/blender/editors/animation/keyframes_general.c
index b5c0555bf63..9249b912da6 100644
--- a/source/blender/editors/animation/keyframes_general.c
+++ b/source/blender/editors/animation/keyframes_general.c
@@ -188,7 +188,7 @@ void clean_fcurve(FCurve *fcu, float thresh)
/* make a copy of the old BezTriples, and clear F-Curve */
old_bezts = fcu->bezt;
- totCount = fcu->totvert;
+ totCount = fcu->totvert;
fcu->bezt = NULL;
fcu->totvert = 0;
@@ -256,7 +256,7 @@ void clean_fcurve(FCurve *fcu, float thresh)
insert_vert_fcurve(fcu, cur[0], cur[1], 0);
}
}
- else {
+ else {
/* add if value doesn't equal that of previous */
if (IS_EQT(cur[1], prev[1], thresh) == 0) {
/* add new keyframe */
diff --git a/source/blender/editors/animation/keyframing.c b/source/blender/editors/animation/keyframing.c
index 5e0459bea90..8ba330e7c3c 100644
--- a/source/blender/editors/animation/keyframing.c
+++ b/source/blender/editors/animation/keyframing.c
@@ -43,6 +43,8 @@
#include "BLI_dynstr.h"
#include "BLI_utildefines.h"
+#include "BLF_translation.h"
+
#include "DNA_anim_types.h"
#include "DNA_armature_types.h"
#include "DNA_constraint_types.h"
@@ -106,7 +108,7 @@ short ANIM_get_keyframing_flags(Scene *scene, short incl_mode)
}
/* only if including settings from the autokeying mode... */
- if (incl_mode) {
+ if (incl_mode) {
/* keyframing mode - only replace existing keyframes */
if (IS_AUTOKEY_MODE(scene, EDITKEYS))
flag |= INSERTKEY_REPLACE;
@@ -129,7 +131,7 @@ bAction *verify_adt_action(ID *id, short add)
adt = BKE_animdata_from_id(id);
if ((adt == NULL) && (add))
adt = BKE_id_add_animdata(id);
- if (adt == NULL) {
+ if (adt == NULL) {
/* if still none (as not allowed to add, or ID doesn't have animdata for some reason) */
printf("ERROR: Couldn't add AnimData (ID = %s)\n", (id) ? (id->name) : "<None>");
return NULL;
@@ -238,7 +240,7 @@ int insert_bezt_fcurve(FCurve *fcu, BezTriple *bezt, short flag)
i = binarysearch_bezt_index(fcu->bezt, bezt->vec[1][0], fcu->totvert, &replace);
/* replace an existing keyframe? */
- if (replace) {
+ if (replace) {
/* sanity check: 'i' may in rare cases exceed arraylen */
if ((i >= 0) && (i < fcu->totvert)) {
/* just change the values when replacing, so as to not overwrite handles */
@@ -410,12 +412,12 @@ static short new_key_needed(FCurve *fcu, float cFrame, float nValue)
float prevPosi = 0.0f, prevVal = 0.0f;
float beztPosi = 0.0f, beztVal = 0.0f;
- /* get current time+value */
+ /* get current time+value */
beztPosi = bezt->vec[1][0];
beztVal = bezt->vec[1][1];
if (prev) {
- /* there is a keyframe before the one currently being examined */
+ /* there is a keyframe before the one currently being examined */
/* get previous time+value */
prevPosi = prev->vec[1][0];
@@ -477,10 +479,10 @@ static short new_key_needed(FCurve *fcu, float cFrame, float nValue)
/* Frame in which to add a new-keyframe occurs after all other keys
* -> If there are at least two existing keyframes, then if the values of the
- * last two keyframes and the new-keyframe match, the last existing keyframe
- * gets deleted as it is no longer required.
+ * last two keyframes and the new-keyframe match, the last existing keyframe
+ * gets deleted as it is no longer required.
* -> Otherwise, a keyframe is just added. 1.0 is added so that fake-2nd-to-last
- * keyframe is not equal to last keyframe.
+ * keyframe is not equal to last keyframe.
*/
bezt = (fcu->bezt + (fcu->totvert - 1));
valA = bezt->vec[1][1];
@@ -787,14 +789,15 @@ short insert_keyframe_direct(ReportList *reports, PointerRNA ptr, PropertyRNA *p
/* F-Curve not editable? */
if (fcurve_is_keyframable(fcu) == 0) {
BKE_reportf(reports, RPT_ERROR,
- "F-Curve with path = '%s' [%d] cannot be keyframed. Ensure that it is not locked or sampled. Also, try removing F-Modifiers",
+ "F-Curve with path '%s[%d]' cannot be keyframed, ensure that it is not locked or sampled, "
+ "and try removing F-Modifiers",
fcu->rna_path, fcu->array_index);
return 0;
}
/* if no property given yet, try to validate from F-Curve info */
if ((ptr.id.data == NULL) && (ptr.data == NULL)) {
- BKE_report(reports, RPT_ERROR, "No RNA-pointer available to retrieve values for keyframing from");
+ BKE_report(reports, RPT_ERROR, "No RNA pointer available to retrieve values for keyframing from");
return 0;
}
if (prop == NULL) {
@@ -803,10 +806,10 @@ short insert_keyframe_direct(ReportList *reports, PointerRNA ptr, PropertyRNA *p
/* try to get property we should be affecting */
if ((RNA_path_resolve(&ptr, fcu->rna_path, &tmp_ptr, &prop) == 0) || (prop == NULL)) {
/* property not found... */
- const char *idname = (ptr.id.data) ? ((ID *)ptr.id.data)->name : "<No ID-Pointer>";
+ const char *idname = (ptr.id.data) ? ((ID *)ptr.id.data)->name : TIP_("<No ID pointer>");
BKE_reportf(reports, RPT_ERROR,
- "Could not insert keyframe, as RNA Path is invalid for the given ID (ID = %s, Path = %s)",
+ "Could not insert keyframe, as RNA path is invalid for the given ID (ID = %s, path = %s)",
idname, fcu->rna_path);
return 0;
}
@@ -906,15 +909,15 @@ short insert_keyframe(ReportList *reports, ID *id, bAction *act, const char grou
/* validate pointer first - exit if failure */
if (id == NULL) {
- BKE_reportf(reports, RPT_ERROR, "No ID-block to insert keyframe in (Path = %s)", rna_path);
+ BKE_reportf(reports, RPT_ERROR, "No ID block to insert keyframe in (path = %s)", rna_path);
return 0;
}
RNA_id_pointer_create(id, &id_ptr);
if ((RNA_path_resolve(&id_ptr, rna_path, &ptr, &prop) == 0) || (prop == NULL)) {
BKE_reportf(reports, RPT_ERROR,
- "Could not insert keyframe, as RNA Path is invalid for the given ID (ID = %s, Path = %s)",
- (id) ? id->name : "<Missing ID-Block>", rna_path);
+ "Could not insert keyframe, as RNA path is invalid for the given ID (ID = %s, path = %s)",
+ (id) ? id->name : TIP_("<Missing ID block>"), rna_path);
return 0;
}
@@ -927,7 +930,7 @@ short insert_keyframe(ReportList *reports, ID *id, bAction *act, const char grou
if (act == NULL) {
BKE_reportf(reports, RPT_ERROR,
- "Could not insert keyframe, as this type does not support animation data (ID = %s, Path = %s)",
+ "Could not insert keyframe, as this type does not support animation data (ID = %s, path = %s)",
id->name, rna_path);
return 0;
}
@@ -937,7 +940,7 @@ short insert_keyframe(ReportList *reports, ID *id, bAction *act, const char grou
}
/* key entire array convenience method */
- if (array_index == -1) {
+ if (array_index == -1) {
array_index = 0;
array_index_max = RNA_property_array_length(&ptr, prop);
@@ -997,14 +1000,16 @@ short delete_keyframe(ReportList *reports, ID *id, bAction *act, const char grou
/* sanity checks */
if (ELEM(NULL, id, adt)) {
- BKE_report(reports, RPT_ERROR, "No ID-Block and/Or AnimData to delete keyframe from");
+ BKE_report(reports, RPT_ERROR, "No ID block and/or AnimData to delete keyframe from");
return 0;
}
/* validate pointer first - exit if failure */
RNA_id_pointer_create(id, &id_ptr);
if ((RNA_path_resolve(&id_ptr, rna_path, &ptr, &prop) == 0) || (prop == NULL)) {
- BKE_reportf(reports, RPT_ERROR, "Could not delete keyframe, as RNA Path is invalid for the given ID (ID = %s, Path = %s)", id->name, rna_path);
+ BKE_reportf(reports, RPT_ERROR,
+ "Could not delete keyframe, as RNA path is invalid for the given ID (ID = %s, path = %s)",
+ id->name, rna_path);
return 0;
}
@@ -1023,13 +1028,13 @@ short delete_keyframe(ReportList *reports, ID *id, bAction *act, const char grou
cfra = BKE_nla_tweakedit_remap(adt, cfra, NLATIME_CONVERT_UNMAP);
}
else {
- BKE_reportf(reports, RPT_ERROR, "No Action to delete keyframes from for ID = %s\n", id->name);
+ BKE_reportf(reports, RPT_ERROR, "No action to delete keyframes from for ID = %s", id->name);
return 0;
}
}
/* key entire array convenience method */
- if (array_index == -1) {
+ if (array_index == -1) {
array_index = 0;
array_index_max = RNA_property_array_length(&ptr, prop);
@@ -1059,7 +1064,7 @@ short delete_keyframe(ReportList *reports, ID *id, bAction *act, const char grou
/* try to find index of beztriple to get rid of */
i = binarysearch_bezt_index(fcu->bezt, cfra, fcu->totvert, &found);
- if (found) {
+ if (found) {
/* delete the key at the index (will sanity check + do recalc afterwards) */
delete_fcurve_key(fcu, i, 1);
@@ -1096,14 +1101,16 @@ static short clear_keyframe(ReportList *reports, ID *id, bAction *act, const cha
/* sanity checks */
if (ELEM(NULL, id, adt)) {
- BKE_report(reports, RPT_ERROR, "No ID-Block and/Or AnimData to delete keyframe from");
+ BKE_report(reports, RPT_ERROR, "No ID block and/or AnimData to delete keyframe from");
return 0;
}
/* validate pointer first - exit if failure */
RNA_id_pointer_create(id, &id_ptr);
if ((RNA_path_resolve(&id_ptr, rna_path, &ptr, &prop) == 0) || (prop == NULL)) {
- BKE_reportf(reports, RPT_ERROR, "Could not clear keyframe, as RNA Path is invalid for the given ID (ID = %s, Path = %s)", id->name, rna_path);
+ BKE_reportf(reports, RPT_ERROR,
+ "Could not clear keyframe, as RNA path is invalid for the given ID (ID = %s, path = %s)",
+ id->name, rna_path);
return 0;
}
@@ -1119,7 +1126,7 @@ static short clear_keyframe(ReportList *reports, ID *id, bAction *act, const cha
act = adt->action;
}
else {
- BKE_reportf(reports, RPT_ERROR, "No Action to delete keyframes from for ID = %s\n", id->name);
+ BKE_reportf(reports, RPT_ERROR, "No action to delete keyframes from for ID = %s", id->name);
return 0;
}
}
@@ -1186,10 +1193,9 @@ static int modify_key_op_poll(bContext *C)
/* if Outliner, don't allow in some views */
if (so) {
- if (ELEM4(so->outlinevis, SO_GROUPS, SO_LIBRARIES, SO_VERSE_SESSION, SO_VERSE_SESSION))
- return 0;
- if (ELEM3(so->outlinevis, SO_SEQUENCE, SO_USERDEF, SO_KEYMAP))
+ if (ELEM5(so->outlinevis, SO_GROUPS, SO_LIBRARIES, SO_SEQUENCE, SO_USERDEF, SO_KEYMAP)) {
return 0;
+ }
}
/* TODO: checks for other space types can be added here */
@@ -1223,30 +1229,30 @@ static int insert_key_exec(bContext *C, wmOperator *op)
/* report failures */
if (ks == NULL) {
- BKE_report(op->reports, RPT_ERROR, "No active Keying Set");
+ BKE_report(op->reports, RPT_ERROR, "No active keying set");
return OPERATOR_CANCELLED;
}
/* try to insert keyframes for the channels specified by KeyingSet */
success = ANIM_apply_keyingset(C, NULL, NULL, ks, MODIFYKEY_MODE_INSERT, cfra);
if (G.debug & G_DEBUG)
- BKE_reportf(op->reports, RPT_INFO, "KeyingSet '%s' - Successfully added %d Keyframes\n", ks->name, success);
+ BKE_reportf(op->reports, RPT_INFO, "Keying set '%s' - successfully added %d keyframes", ks->name, success);
/* report failure or do updates? */
if (success == MODIFYKEY_INVALID_CONTEXT) {
- BKE_report(op->reports, RPT_ERROR, "No suitable context info for active Keying Set");
+ BKE_report(op->reports, RPT_ERROR, "No suitable context info for active keying set");
return OPERATOR_CANCELLED;
}
else if (success) {
/* if the appropriate properties have been set, make a note that we've inserted something */
if (RNA_boolean_get(op->ptr, "confirm_success"))
- BKE_reportf(op->reports, RPT_INFO, "Successfully added %d Keyframes for KeyingSet '%s'", success, ks->name);
+ BKE_reportf(op->reports, RPT_INFO, "Successfully added %d keyframes for keying set '%s'", success, ks->name);
/* send notifiers that keyframes have been changed */
WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, NULL);
}
else
- BKE_report(op->reports, RPT_WARNING, "Keying Set failed to insert any keyframes");
+ BKE_report(op->reports, RPT_WARNING, "Keying set failed to insert any keyframes");
/* send updates */
DAG_ids_flush_update(bmain, 0);
@@ -1390,19 +1396,19 @@ static int delete_key_exec(bContext *C, wmOperator *op)
/* report failure or do updates? */
if (success == MODIFYKEY_INVALID_CONTEXT) {
- BKE_report(op->reports, RPT_ERROR, "No suitable context info for active Keying Set");
+ BKE_report(op->reports, RPT_ERROR, "No suitable context info for active keying set");
return OPERATOR_CANCELLED;
}
else if (success) {
/* if the appropriate properties have been set, make a note that we've inserted something */
if (RNA_boolean_get(op->ptr, "confirm_success"))
- BKE_reportf(op->reports, RPT_INFO, "Successfully removed %d Keyframes for KeyingSet '%s'", success, ks->name);
+ BKE_reportf(op->reports, RPT_INFO, "Successfully removed %d keyframes for keying set '%s'", success, ks->name);
/* send notifiers that keyframes have been changed */
WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, NULL);
}
else
- BKE_report(op->reports, RPT_WARNING, "Keying Set failed to remove any keyframes");
+ BKE_report(op->reports, RPT_WARNING, "Keying set failed to remove any keyframes");
/* send updates */
DAG_ids_flush_update(bmain, 0);
@@ -1440,46 +1446,122 @@ void ANIM_OT_keyframe_delete(wmOperatorType *ot)
}
/* Delete Key Operator ------------------------ */
-
-/* XXX WARNING:
- * This is currently just a basic operator, which work in 3d-view context on objects only.
- * Should this be kept? It does have advantages over a version which requires selecting a keyingset to use...
- * -- Joshua Leung, Jan 2009
+/* NOTE: Although this version is simpler than the more generic version for KeyingSets,
+ * it is more useful for animators working in the 3D view.
*/
+static int clear_anim_v3d_exec(bContext *C, wmOperator *UNUSED(op))
+{
+ Main *bmain = CTX_data_main(C);
+
+ CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
+ {
+ /* just those in active action... */
+ if ((ob->adt) && (ob->adt->action)) {
+ AnimData *adt = ob->adt;
+ bAction *act = adt->action;
+ FCurve *fcu, *fcn;
+
+ for (fcu = act->curves.first; fcu; fcu = fcn) {
+ short can_delete = FALSE;
+
+ fcn = fcu->next;
+
+ /* in pose mode, only delete the F-Curve if it belongs to a selected bone */
+ if (ob->mode & OB_MODE_POSE) {
+ if ((fcu->rna_path) && strstr(fcu->rna_path, "pose.bones[")) {
+ bPoseChannel *pchan;
+ char *bone_name;
+
+ /* get bone-name, and check if this bone is selected */
+ bone_name = BLI_str_quoted_substrN(fcu->rna_path, "pose.bones[");
+ pchan = BKE_pose_channel_find_name(ob->pose, bone_name);
+ if (bone_name) MEM_freeN(bone_name);
+
+ /* delete if bone is selected*/
+ if ((pchan) && (pchan->bone)) {
+ if (pchan->bone->flag & BONE_SELECTED)
+ can_delete = TRUE;
+ }
+ }
+ }
+ else {
+ /* object mode - all of Object's F-Curves are affected */
+ can_delete = TRUE;
+ }
+
+ /* delete F-Curve completely */
+ if (can_delete) {
+ ANIM_fcurve_delete_from_animdata(NULL, adt, fcu);
+ }
+ }
+ }
+
+ /* update... */
+ ob->recalc |= OB_RECALC_OB;
+ }
+ CTX_DATA_END;
+
+ /* send updates */
+ DAG_ids_flush_update(bmain, 0);
+ WM_event_add_notifier(C, NC_OBJECT | ND_KEYS, NULL);
+
+ return OPERATOR_FINISHED;
+}
+
+void ANIM_OT_keyframe_clear_v3d(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Remove Animation";
+ ot->description = "Remove all keyframe animation for selected objects";
+ ot->idname = "ANIM_OT_keyframe_clear_v3d";
+
+ /* callbacks */
+ ot->invoke = WM_operator_confirm;
+ ot->exec = clear_anim_v3d_exec;
+
+ ot->poll = ED_operator_areaactive;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+}
+
+
static int delete_key_v3d_exec(bContext *C, wmOperator *op)
{
Main *bmain = CTX_data_main(C);
Scene *scene = CTX_data_scene(C);
- float cfra = (float)CFRA; // XXX for now, don't bother about all the yucky offset crap
+ float cfra = (float)CFRA;
- // XXX more comprehensive tests will be needed
CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
{
- ID *id = (ID *)ob;
- FCurve *fcu, *fcn;
- short success = 0;
+ ID *id = &ob->id;
+ int success = 0;
- /* loop through all curves in animdata and delete keys on this frame */
+ /* just those in active action... */
if ((ob->adt) && (ob->adt->action)) {
AnimData *adt = ob->adt;
bAction *act = adt->action;
+ FCurve *fcu, *fcn;
for (fcu = act->curves.first; fcu; fcu = fcn) {
fcn = fcu->next;
+
+ /* delete keyframes on current frame
+ * WARNING: this can delete the next F-Curve, hence the "fcn" copying
+ */
success += delete_keyframe(op->reports, id, NULL, NULL, fcu->rna_path, fcu->array_index, cfra, 0);
}
}
- BKE_reportf(op->reports, RPT_INFO, "Ob '%s' - Successfully had %d keyframes removed", id->name + 2, success);
-
+ /* report success (or failure) */
+ BKE_reportf(op->reports, RPT_INFO, "Object '%s' successfully had %d keyframes removed", id->name + 2, success);
ob->recalc |= OB_RECALC_OB;
}
CTX_DATA_END;
/* send updates */
DAG_ids_flush_update(bmain, 0);
-
WM_event_add_notifier(C, NC_OBJECT | ND_KEYS, NULL);
return OPERATOR_FINISHED;
@@ -1489,7 +1571,7 @@ void ANIM_OT_keyframe_delete_v3d(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Delete Keyframe";
- ot->description = "Remove keyframes on current frame for selected object";
+ ot->description = "Remove keyframes on current frame for selected objects";
ot->idname = "ANIM_OT_keyframe_delete_v3d";
/* callbacks */
@@ -1512,7 +1594,7 @@ static int insert_key_button_exec(bContext *C, wmOperator *op)
PointerRNA ptr = {{NULL}};
PropertyRNA *prop = NULL;
char *path;
- float cfra = (float)CFRA; // XXX for now, don't bother about all the yucky offset crap
+ float cfra = (float)CFRA;
short success = 0;
int a, index, length, all = RNA_boolean_get(op->ptr, "all");
short flag = 0;
@@ -1551,7 +1633,7 @@ static int insert_key_button_exec(bContext *C, wmOperator *op)
else {
if (G.debug & G_DEBUG)
printf("Button Insert-Key: no path to property\n");
- BKE_report(op->reports, RPT_WARNING, "Failed to resolve path to property. Try using a Keying Set instead");
+ BKE_report(op->reports, RPT_WARNING, "Failed to resolve path to property, try using a keying set instead");
}
}
else if (G.debug & G_DEBUG) {
@@ -1683,20 +1765,20 @@ static int clear_key_button_exec(bContext *C, wmOperator *op)
if (ptr.id.data && ptr.data && prop) {
path = RNA_path_from_ID_to_property(&ptr, prop);
-
+
if (path) {
if (all) {
length = RNA_property_array_length(&ptr, prop);
-
+
if (length) index = 0;
else length = 1;
}
else
length = 1;
-
+
for (a = 0; a < length; a++)
success += clear_keyframe(op->reports, ptr.id.data, NULL, NULL, path, index + a, 0);
-
+
MEM_freeN(path);
}
else if (G.debug & G_DEBUG)
@@ -1710,9 +1792,9 @@ static int clear_key_button_exec(bContext *C, wmOperator *op)
if (success) {
/* send updates */
uiContextAnimUpdate(C);
-
+
DAG_ids_flush_update(bmain, 0);
-
+
/* send notifiers that keyframes have been changed */
WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, NULL);
}
@@ -1781,7 +1863,7 @@ short fcurve_frame_has_keyframe(FCurve *fcu, float frame, short filter)
/* binarysearch_bezt_index will set replace to be 0 or 1
* - obviously, 1 represents a match
*/
- if (replace) {
+ if (replace) {
/* sanity check: 'i' may in rare cases exceed arraylen */
if ((i >= 0) && (i < fcu->totvert))
return 1;
@@ -1836,7 +1918,7 @@ static short object_frame_has_keyframe(Object *ob, float frame, short filter)
/* try shapekey keyframes (if available, and allowed by filter) */
if (!(filter & ANIMFILTER_KEYS_LOCAL) && !(filter & ANIMFILTER_KEYS_NOSKEY) ) {
- Key *key = ob_get_key(ob);
+ Key *key = BKE_key_from_object(ob);
/* shapekeys can have keyframes ('Relative Shape Keys')
* or depend on time (old 'Absolute Shape Keys')
diff --git a/source/blender/editors/animation/keyingsets.c b/source/blender/editors/animation/keyingsets.c
index 04fd7f677b0..ae7abd82600 100644
--- a/source/blender/editors/animation/keyingsets.c
+++ b/source/blender/editors/animation/keyingsets.c
@@ -161,11 +161,11 @@ static int remove_active_keyingset_exec(bContext *C, wmOperator *op)
* - return error if it doesn't exist
*/
if (scene->active_keyingset == 0) {
- BKE_report(op->reports, RPT_ERROR, "No active Keying Set to remove");
+ BKE_report(op->reports, RPT_ERROR, "No active keying set to remove");
return OPERATOR_CANCELLED;
}
else if (scene->active_keyingset < 0) {
- BKE_report(op->reports, RPT_ERROR, "Cannot remove built in Keying Set");
+ BKE_report(op->reports, RPT_ERROR, "Cannot remove built in keying set");
return OPERATOR_CANCELLED;
}
else
@@ -209,7 +209,7 @@ static int add_empty_ks_path_exec(bContext *C, wmOperator *op)
* - return error if it doesn't exist
*/
if (scene->active_keyingset == 0) {
- BKE_report(op->reports, RPT_ERROR, "No active Keying Set to add empty path to");
+ BKE_report(op->reports, RPT_ERROR, "No active keying set to add empty path to");
return OPERATOR_CANCELLED;
}
else
@@ -258,12 +258,12 @@ static int remove_active_ks_path_exec(bContext *C, wmOperator *op)
ks->active_path--;
}
else {
- BKE_report(op->reports, RPT_ERROR, "No active Keying Set Path to remove");
+ BKE_report(op->reports, RPT_ERROR, "No active keying set path to remove");
return OPERATOR_CANCELLED;
}
}
else {
- BKE_report(op->reports, RPT_ERROR, "No active Keying Set to remove a path from");
+ BKE_report(op->reports, RPT_ERROR, "No active keying set to remove a path from");
return OPERATOR_CANCELLED;
}
@@ -322,7 +322,7 @@ static int add_keyingset_button_exec(bContext *C, wmOperator *op)
scene->active_keyingset = BLI_countlist(&scene->keyingsets);
}
else if (scene->active_keyingset < 0) {
- BKE_report(op->reports, RPT_ERROR, "Cannot add property to built in Keying Set");
+ BKE_report(op->reports, RPT_ERROR, "Cannot add property to built in keying set");
return OPERATOR_CANCELLED;
}
else
@@ -377,7 +377,7 @@ void ANIM_OT_keyingset_button_add(wmOperatorType *ot)
/* callbacks */
ot->exec = add_keyingset_button_exec;
- //op->poll= ???
+ //op->poll = ???
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -404,11 +404,11 @@ static int remove_keyingset_button_exec(bContext *C, wmOperator *op)
* - return error if it doesn't exist
*/
if (scene->active_keyingset == 0) {
- BKE_report(op->reports, RPT_ERROR, "No active Keying Set to remove property from");
+ BKE_report(op->reports, RPT_ERROR, "No active keying set to remove property from");
return OPERATOR_CANCELLED;
}
else if (scene->active_keyingset < 0) {
- BKE_report(op->reports, RPT_ERROR, "Cannot remove property from built in Keying Set");
+ BKE_report(op->reports, RPT_ERROR, "Cannot remove property from built in keying set");
return OPERATOR_CANCELLED;
}
else
@@ -457,7 +457,7 @@ void ANIM_OT_keyingset_button_remove(wmOperatorType *ot)
/* callbacks */
ot->exec = remove_keyingset_button_exec;
- //op->poll= ???
+ //op->poll = ???
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -947,7 +947,7 @@ int ANIM_apply_keyingset(bContext *C, ListBase *dsources, bAction *act, KeyingSe
/* skip path if no ID pointer is specified */
if (ksp->id == NULL) {
BKE_reportf(reports, RPT_WARNING,
- "Skipping path in Keying Set, as it has no ID (KS = '%s', Path = '%s'[%d])",
+ "Skipping path in keying set, as it has no ID (KS = '%s', path = '%s[%d]')",
ks->name, ksp->rna_path, ksp->array_index);
continue;
}
diff --git a/source/blender/editors/armature/armature_ops.c b/source/blender/editors/armature/armature_ops.c
index c19904d39ac..7c5b75e56ae 100644
--- a/source/blender/editors/armature/armature_ops.c
+++ b/source/blender/editors/armature/armature_ops.c
@@ -88,7 +88,7 @@ void ED_operatortypes_armature(void)
WM_operatortype_append(ARMATURE_OT_armature_layers);
WM_operatortype_append(ARMATURE_OT_bone_layers);
- /* SKETCH */
+ /* SKETCH */
WM_operatortype_append(SKETCH_OT_gesture);
WM_operatortype_append(SKETCH_OT_delete);
WM_operatortype_append(SKETCH_OT_draw_stroke);
@@ -221,7 +221,7 @@ void ED_keymap_armature(wmKeyConfig *keyconf)
/* Already part of view3d select */
//WM_keymap_add_item(keymap, "SKETCH_OT_select", SELECTMOUSE, KM_PRESS, 0, 0);
- /* sketch poll checks mode */
+ /* sketch poll checks mode */
WM_keymap_add_item(keymap, "SKETCH_OT_gesture", LEFTMOUSE, KM_PRESS, KM_SHIFT, 0);
WM_keymap_add_item(keymap, "SKETCH_OT_draw_stroke", LEFTMOUSE, KM_PRESS, 0, 0);
kmi = WM_keymap_add_item(keymap, "SKETCH_OT_draw_stroke", LEFTMOUSE, KM_PRESS, KM_CTRL, 0);
diff --git a/source/blender/editors/armature/editarmature.c b/source/blender/editors/armature/editarmature.c
index cb52d88f985..48da23d5e8d 100644
--- a/source/blender/editors/armature/editarmature.c
+++ b/source/blender/editors/armature/editarmature.c
@@ -117,14 +117,14 @@ void ED_armature_sync_selection(ListBase *edbo)
else
ebo->flag &= ~BONE_SELECTED;
}
- }
+ }
}
void ED_armature_validate_active(struct bArmature *arm)
{
EditBone *ebone = arm->act_edbone;
- if (ebone) {
+ if (ebone) {
if (ebone->flag & BONE_HIDDEN_A)
arm->act_edbone = NULL;
}
@@ -304,7 +304,7 @@ EditBone *make_boneList(ListBase *edbo, ListBase *bones, EditBone *parent, Bone
eBone->ease2 = curBone->ease2;
eBone->rad_head = curBone->rad_head;
eBone->rad_tail = curBone->rad_tail;
- eBone->segments = curBone->segments;
+ eBone->segments = curBone->segments;
eBone->layer = curBone->layer;
if (curBone->prop)
@@ -654,17 +654,19 @@ static int apply_armature_pose2bones_exec(bContext *C, wmOperator *op)
if (ob->type != OB_ARMATURE)
return OPERATOR_CANCELLED;
if (BKE_object_obdata_is_libdata(ob)) {
- BKE_report(op->reports, RPT_ERROR, "Cannot apply pose to lib-linked armature"); //error_libdata();
+ BKE_report(op->reports, RPT_ERROR, "Cannot apply pose to lib-linked armature"); /* error_libdata(); */
return OPERATOR_CANCELLED;
}
/* helpful warnings... */
/* TODO: add warnings to be careful about actions, applying deforms first, etc. */
if (ob->adt && ob->adt->action)
- BKE_report(op->reports, RPT_WARNING, "Actions on this armature will be destroyed by this new rest pose as the transforms stored are relative to the old rest pose");
+ BKE_report(op->reports, RPT_WARNING,
+ "Actions on this armature will be destroyed by this new rest pose as the "
+ "transforms stored are relative to the old rest pose");
/* Get editbones of active armature to alter */
- ED_armature_to_edit(ob);
+ ED_armature_to_edit(ob);
/* get pose of active object and move it out of posemode */
pose = ob->pose;
@@ -895,7 +897,7 @@ static void joined_armature_fix_links(Object *tarArm, Object *srcArm, bPoseChann
/* make tar armature be new parent */
ob->parent = tarArm;
}
- }
+ }
}
/* join armature exec is exported for use in object->join objects operator... */
@@ -1111,7 +1113,7 @@ static void separated_armature_fix_links(Object *origArm, Object *newArm)
}
}
}
- }
+ }
}
/* Helper function for armature separating - remove certain bones from the given armature
@@ -1438,7 +1440,7 @@ static int pose_select_connected_invoke(bContext *C, wmOperator *op, wmEvent *ev
/* Select parents */
for (curBone = bone; curBone; curBone = next) {
/* ignore bone if cannot be selected */
- if ((curBone->flag & BONE_UNSELECTABLE) == 0) {
+ if ((curBone->flag & BONE_UNSELECTABLE) == 0) {
// XXX old cruft! use notifiers instead
//select_actionchannel_by_name (ob->action, curBone->name, !(shift));
@@ -1491,7 +1493,7 @@ void POSE_OT_select_linked(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- /* props */
+ /* props */
RNA_def_boolean(ot->srna, "extend", FALSE, "Extend", "Extend selection instead of deselecting everything first");
}
@@ -1548,7 +1550,7 @@ static int armature_select_linked_invoke(bContext *C, wmOperator *op, wmEvent *e
bone = curBone;
break;
}
- else {
+ else {
bone = NULL;
break;
}
@@ -1591,7 +1593,8 @@ void ARMATURE_OT_select_linked(wmOperatorType *ot)
/* does bones and points */
/* note that BONE ROOT only gets drawn for root bones (or without IK) */
-static EditBone *get_nearest_editbonepoint(ViewContext *vc, const int mval[2], ListBase *edbo, int findunsel, int *selmask)
+static EditBone *get_nearest_editbonepoint(ViewContext *vc, const int mval[2],
+ ListBase *edbo, int findunsel, int *selmask)
{
EditBone *ebone;
rcti rect;
@@ -1831,7 +1834,7 @@ void ED_armature_deselect_all_visible(Object *obedit)
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
/* first and foremost, bone must be visible and selected */
- if (EBONE_VISIBLE(arm, ebone) && (ebone->flag & BONE_UNSELECTABLE) == 0) {
+ if (EBONE_SELECTABLE(arm, ebone)) {
ebone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
}
}
@@ -2096,7 +2099,7 @@ static int armature_calc_roll_exec(bContext *C, wmOperator *op)
}
sub_v3_v3v3(nor, ebone->tail, ebone->head);
- vec_roll_to_mat3(nor, ebone->roll, mat);
+ vec_roll_to_mat3(nor, ebone->roll, mat);
copy_v3_v3(vec, mat[2]);
}
else { /* Axis */
@@ -2556,7 +2559,8 @@ void updateDuplicateSubtarget(EditBone *dupBone, ListBase *editbones, Object *ob
}
-EditBone *duplicateEditBoneObjects(EditBone *curBone, const char *name, ListBase *editbones, Object *src_ob, Object *dst_ob)
+EditBone *duplicateEditBoneObjects(EditBone *curBone, const char *name, ListBase *editbones,
+ Object *src_ob, Object *dst_ob)
{
EditBone *eBone = MEM_mallocN(sizeof(EditBone), "addup_editbone");
@@ -2683,7 +2687,7 @@ static int armature_duplicate_selected_exec(bContext *C, wmOperator *UNUSED(op))
updateDuplicateSubtarget(eBone, arm->edbo, obedit);
}
}
- }
+ }
/* correct the active bone */
if (arm->act_edbone) {
@@ -2798,7 +2802,7 @@ static void fill_add_joint(EditBone *ebo, short eb_tail, ListBase *points)
}
for (ebp = points->first; ebp; ebp = ebp->next) {
- if (equals_v3v3(ebp->vec, vec)) {
+ if (equals_v3v3(ebp->vec, vec)) {
if (eb_tail) {
if ((ebp->head_owner) && (ebp->head_owner->parent == ebo)) {
/* so this bone's tail owner is this bone */
@@ -2882,7 +2886,7 @@ static int armature_fill_bones_exec(bContext *C, wmOperator *op)
mul_v3_m4v3(curs, obedit->imat, give_cursor(scene, v3d));
/* Create a bone */
- /* newbone= */ add_points_bone(obedit, ebp->vec, curs);
+ /* newbone = */ add_points_bone(obedit, ebp->vec, curs);
}
else if (count == 2) {
EditBonePoint *ebp, *ebp2;
@@ -2965,8 +2969,8 @@ static int armature_fill_bones_exec(bContext *C, wmOperator *op)
}
}
else {
- // FIXME.. figure out a method for multiple bones
- BKE_reportf(op->reports, RPT_ERROR, "Too many points selected: %d\n", count);
+ /* FIXME.. figure out a method for multiple bones */
+ BKE_reportf(op->reports, RPT_ERROR, "Too many points selected: %d", count);
BLI_freelistN(&points);
return OPERATOR_CANCELLED;
}
@@ -3036,7 +3040,8 @@ static void bones_merge(Object *obedit, EditBone *start, EditBone *end, EditBone
newbone->parent = start->parent;
/* TODO, copy more things to the new bone */
- newbone->flag = start->flag & (BONE_HINGE | BONE_NO_DEFORM | BONE_NO_SCALE | BONE_NO_CYCLICOFFSET | BONE_NO_LOCAL_LOCATION | BONE_DONE);
+ newbone->flag = start->flag & (BONE_HINGE | BONE_NO_DEFORM | BONE_NO_SCALE |
+ BONE_NO_CYCLICOFFSET | BONE_NO_LOCAL_LOCATION | BONE_DONE);
/* step 2a: reparent any side chains which may be parented to any bone in the chain of bones to merge
* - potentially several tips for side chains leading to some tree exist...
@@ -3145,7 +3150,7 @@ static int armature_merge_exec(bContext *C, wmOperator *op)
/* put back link */
BLI_insertlinkbefore(&chains, nchain, chain);
- }
+ }
armature_tag_unselect(arm);
@@ -3296,7 +3301,9 @@ static void hide_unselected_armature_bones(Scene *scene)
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
bArmature *arm = obedit->data;
if (EBONE_VISIBLE(arm, ebone)) {
- if (ebone->flag & (BONE_TIPSEL | BONE_SELECTED | BONE_ROOTSEL)) ;
+ if (ebone->flag & (BONE_TIPSEL | BONE_SELECTED | BONE_ROOTSEL)) {
+ /* pass */
+ }
else {
ebone->flag |= BONE_HIDDEN_A;
}
@@ -3357,12 +3364,17 @@ static int armature_extrude_exec(bContext *C, wmOperator *op)
if (EBONE_VISIBLE(arm, ebone)) {
/* we extrude per definition the tip */
do_extrude = FALSE;
- if (ebone->flag & (BONE_TIPSEL | BONE_SELECTED))
+ if (ebone->flag & (BONE_TIPSEL | BONE_SELECTED)) {
do_extrude = TRUE;
+ }
else if (ebone->flag & BONE_ROOTSEL) {
/* but, a bone with parent deselected we do the root... */
- if (ebone->parent && (ebone->parent->flag & BONE_TIPSEL)) ;
- else do_extrude = 2;
+ if (ebone->parent && (ebone->parent->flag & BONE_TIPSEL)) {
+ /* pass */
+ }
+ else {
+ do_extrude = 2;
+ }
}
if (do_extrude) {
@@ -3447,7 +3459,7 @@ static int armature_extrude_exec(bContext *C, wmOperator *op)
/* Deselect the old bone */
ebone->flag &= ~(BONE_TIPSEL | BONE_SELECTED | BONE_ROOTSEL);
- }
+ }
}
/* if only one bone, make this one active */
if (totbone == 1 && first) arm->act_edbone = first;
@@ -3671,7 +3683,7 @@ static int armature_switch_direction_exec(bContext *C, wmOperator *UNUSED(op))
parent = ebo->parent;
/* only if selected and editable */
- if (EBONE_VISIBLE(arm, ebo) && EBONE_EDITABLE(ebo)) {
+ if (EBONE_VISIBLE(arm, ebo) && EBONE_EDITABLE(ebo)) {
/* swap head and tail coordinates */
SWAP(float, ebo->head[0], ebo->tail[0]);
SWAP(float, ebo->head[1], ebo->tail[1]);
@@ -3711,7 +3723,7 @@ static int armature_switch_direction_exec(bContext *C, wmOperator *UNUSED(op))
}
/* free chains */
- BLI_freelistN(&chains);
+ BLI_freelistN(&chains);
armature_tag_unselect(arm);
@@ -3768,7 +3780,7 @@ static void bone_connect_to_new_parent(ListBase *edbo, EditBone *selbone, EditBo
}
}
- if (mode == ARM_PAR_CONNECT) {
+ if (mode == ARM_PAR_CONNECT) {
/* Connected: Child bones will be moved to the parent tip */
selbone->flag |= BONE_CONNECTED;
sub_v3_v3v3(offset, actbone->tail, selbone->head);
@@ -3813,7 +3825,7 @@ static int armature_parent_set_exec(bContext *C, wmOperator *op)
/* there must be an active bone */
if (actbone == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Operation requires an Active Bone");
+ BKE_report(op->reports, RPT_ERROR, "Operation requires an active bone");
return OPERATOR_CANCELLED;
}
else if (arm->flag & ARM_MIRROR_EDIT) {
@@ -3883,7 +3895,7 @@ static int armature_parent_set_invoke(bContext *C, wmOperator *UNUSED(op), wmEve
{
if (ebone != actbone) {
if (ebone->parent != actbone) allchildbones = 1;
- }
+ }
}
CTX_DATA_END;
@@ -3891,7 +3903,7 @@ static int armature_parent_set_invoke(bContext *C, wmOperator *UNUSED(op), wmEve
/* ob becomes parent, make the associated menus */
if (allchildbones)
- uiItemEnumO(layout, "ARMATURE_OT_parent_set", NULL, 0, "type", ARM_PAR_OFFSET);
+ uiItemEnumO(layout, "ARMATURE_OT_parent_set", NULL, 0, "type", ARM_PAR_OFFSET);
uiPupMenuEnd(C, pup);
@@ -3984,7 +3996,7 @@ static int armature_select_inverse_exec(bContext *C, wmOperator *UNUSED(op))
ebone->flag ^= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
}
}
- CTX_DATA_END;
+ CTX_DATA_END;
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, NULL);
@@ -4045,7 +4057,7 @@ static int armature_de_select_all_exec(bContext *C, wmOperator *op)
}
}
}
- CTX_DATA_END;
+ CTX_DATA_END;
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, NULL);
@@ -4106,7 +4118,7 @@ static void select_similar_length(bArmature *arm, EditBone *ebone_act, const flo
const float len_max = ebone_act->length * (1.0f + thresh);
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
- if (EBONE_VISIBLE(arm, ebone) && (ebone->flag & BONE_UNSELECTABLE) == 0) {
+ if (EBONE_SELECTABLE(arm, ebone)) {
if ((ebone->length >= len_min) &&
(ebone->length <= len_max))
{
@@ -4123,7 +4135,7 @@ static void select_similar_direction(bArmature *arm, EditBone *ebone_act, const
sub_v3_v3v3(dir_act, ebone_act->head, ebone_act->tail);
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
- if (EBONE_VISIBLE(arm, ebone) && (ebone->flag & BONE_UNSELECTABLE) == 0) {
+ if (EBONE_SELECTABLE(arm, ebone)) {
float dir[3];
sub_v3_v3v3(dir, ebone->head, ebone->tail);
@@ -4139,7 +4151,7 @@ static void select_similar_layer(bArmature *arm, EditBone *ebone_act)
EditBone *ebone;
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
- if (EBONE_VISIBLE(arm, ebone) && (ebone->flag & BONE_UNSELECTABLE) == 0) {
+ if (EBONE_SELECTABLE(arm, ebone)) {
if (ebone->layer & ebone_act->layer) {
ED_armature_edit_bone_select(ebone);
}
@@ -4161,7 +4173,7 @@ static void select_similar_prefix(bArmature *arm, EditBone *ebone_act)
/* Find matches */
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
- if (EBONE_VISIBLE(arm, ebone) && (ebone->flag & BONE_UNSELECTABLE) == 0) {
+ if (EBONE_SELECTABLE(arm, ebone)) {
char prefix_other[MAX_VGROUP_NAME];
BKE_deform_split_prefix(ebone->name, prefix_other, body_tmp);
if (!strcmp(prefix_act, prefix_other)) {
@@ -4185,7 +4197,7 @@ static void select_similar_suffix(bArmature *arm, EditBone *ebone_act)
/* Find matches */
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
- if (EBONE_VISIBLE(arm, ebone) && (ebone->flag & BONE_UNSELECTABLE) == 0) {
+ if (EBONE_SELECTABLE(arm, ebone)) {
char suffix_other[MAX_VGROUP_NAME];
BKE_deform_split_suffix(ebone->name, body_tmp, suffix_other);
if (!strcmp(suffix_act, suffix_other)) {
@@ -4207,7 +4219,7 @@ static int armature_select_similar_exec(bContext *C, wmOperator *op)
/* Check for active bone */
if (ebone_act == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Operation requires an Active Bone");
+ BKE_report(op->reports, RPT_ERROR, "Operation requires an active bone");
return OPERATOR_CANCELLED;
}
@@ -4270,7 +4282,7 @@ static int armature_select_hierarchy_exec(bContext *C, wmOperator *op)
for (curbone = arm->edbo->first; curbone; curbone = curbone->next) {
/* only work on bone if it is visible and its selection can change */
- if (EBONE_VISIBLE(arm, curbone) && (curbone->flag & BONE_UNSELECTABLE) == 0) {
+ if (EBONE_SELECTABLE(arm, curbone)) {
if (curbone == arm->act_edbone) {
if (direction == BONE_SELECT_PARENT) {
if (curbone->parent == NULL) continue;
@@ -4285,12 +4297,12 @@ static int armature_select_hierarchy_exec(bContext *C, wmOperator *op)
break;
}
- }
+ }
else { // BONE_SELECT_CHILD
chbone = editbone_get_child(arm, curbone, 1);
if (chbone == NULL) continue;
- if (EBONE_VISIBLE(arm, chbone) && (chbone->flag & BONE_UNSELECTABLE) == 0) {
+ if (EBONE_SELECTABLE(arm, chbone)) {
chbone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
arm->act_edbone = chbone;
@@ -4399,7 +4411,7 @@ static int armature_align_bones_exec(bContext *C, wmOperator *op)
/* there must be an active bone */
if (actbone == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Operation requires an Active Bone");
+ BKE_report(op->reports, RPT_ERROR, "Operation requires an active bone");
return OPERATOR_CANCELLED;
}
else if (arm->flag & ARM_MIRROR_EDIT) {
@@ -4476,7 +4488,8 @@ void ARMATURE_OT_align(wmOperatorType *ot)
/* ***************** Pose tools ********************* */
-// XXX bone_looper is only to be used when we want to access settings (i.e. editability/visibility/selected) that context doesn't offer
+/* XXX bone_looper is only to be used when we want to access settings
+ * (i.e. editability/visibility/selected) that context doesn't offer */
static int bone_looper(Object *ob, Bone *bone, void *data,
int (*bone_func)(Object *, Bone *, void *))
{
@@ -4506,7 +4519,8 @@ static int bone_looper(Object *ob, Bone *bone, void *data,
/* called from editview.c, for mode-less pose selection */
/* assumes scene obact and basact is still on old situation */
-int ED_do_pose_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, short hits, short extend, short deselect, short toggle)
+int ED_do_pose_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, short hits,
+ short extend, short deselect, short toggle)
{
Object *ob = base->object;
Bone *nearBone;
@@ -4554,7 +4568,7 @@ int ED_do_pose_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, shor
nearBone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
arm->act_bone = nearBone;
}
- }
+ }
}
if (ob_act) {
@@ -4752,7 +4766,9 @@ static void add_vgroups__mapFunc(void *userData, int index, const float co[3],
copy_v3_v3(verts[index], co);
}
-static void envelope_bone_weighting(Object *ob, Mesh *mesh, float (*verts)[3], int numbones, Bone **bonelist, bDeformGroup **dgrouplist, bDeformGroup **dgroupflip, float (*root)[3], float (*tip)[3], int *selected, float scale)
+static void envelope_bone_weighting(Object *ob, Mesh *mesh, float (*verts)[3], int numbones, Bone **bonelist,
+ bDeformGroup **dgrouplist, bDeformGroup **dgroupflip,
+ float (*root)[3], float (*tip)[3], int *selected, float scale)
{
/* Create vertex group weights from envelopes */
@@ -4842,7 +4858,7 @@ static void add_verts_to_dgroups(ReportList *reports, Scene *scene, Object *ob,
bone_looper(ob, arm->bonebase.first, &looper_data, bone_skinnable_cb);
/* create an array of pointers to the deform groups that
- * coorespond to the skinnable bones (creating them
+ * correspond to the skinnable bones (creating them
* as necessary. */
dgrouplist = MEM_callocN(numbones * sizeof(bDeformGroup *), "dgrouplist");
dgroupflip = MEM_callocN(numbones * sizeof(bDeformGroup *), "dgroupflip");
@@ -5104,7 +5120,7 @@ static void pchan_clear_rot(bPoseChannel *pchan)
}
}
} /* Duplicated in source/blender/editors/object/object_transform.c */
- else {
+ else {
if (pchan->rotmode == ROT_MODE_QUAT) {
unit_qt(pchan->quat);
}
@@ -5138,7 +5154,7 @@ static int pose_clear_transform_generic_exec(bContext *C, wmOperator *op,
/* sanity checks */
if (ELEM(NULL, clear_func, default_ksName)) {
- BKE_report(op->reports, RPT_ERROR, "Programming error: missing clear transform func or Keying Set Name");
+ BKE_report(op->reports, RPT_ERROR, "Programming error: missing clear transform function or keying set name");
return OPERATOR_CANCELLED;
}
@@ -5530,7 +5546,7 @@ static void constraint_bone_name_fix(Object *ob, ListBase *conlist, char *oldnam
if (cti->flush_constraint_targets)
cti->flush_constraint_targets(curcon, &targets, 0);
- }
+ }
}
}
@@ -5617,7 +5633,7 @@ void ED_armature_bone_rename(bArmature *arm, const char *oldnamep, const char *n
}
}
- if (modifiers_usesArmature(ob, arm)) {
+ if (modifiers_usesArmature(ob, arm)) {
bDeformGroup *dg = defgroup_find_name(ob, oldname);
if (dg) {
BLI_strncpy(dg->name, newname, MAXBONENAME);
@@ -5945,7 +5961,7 @@ float arcLengthRatio(ReebArc *arc)
embedLength = arcLength;
}
- return embedLength / arcLength;
+ return embedLength / arcLength;
}
EditBone *test_subdivideByLength(Scene *scene, Object *obedit, ReebArc *arc, ReebNode *head, ReebNode *tail)
@@ -6046,7 +6062,7 @@ void generateSkeletonFromReebGraph(Scene *scene, ReebGraph *rg)
arc->flag = 1; /* mark arc direction */
}
- /* Loop over subdivision methods */
+ /* Loop over subdivision methods */
for (i = 0; lastBone == NULL && i < SKGEN_SUB_TOTAL; i++) {
switch (scene->toolsettings->skgen_subdivisions[i]) {
case SKGEN_SUB_LENGTH:
diff --git a/source/blender/editors/armature/editarmature_generate.c b/source/blender/editors/armature/editarmature_generate.c
index 23dd3b15476..d9c7e78c01e 100644
--- a/source/blender/editors/armature/editarmature_generate.c
+++ b/source/blender/editors/armature/editarmature_generate.c
@@ -55,7 +55,7 @@ void setBoneRollFromNormal(EditBone *bone, const float no[3], float UNUSED(invma
if (no != NULL && !is_zero_v3(no)) {
float normal[3];
- copy_v3_v3(normal, no);
+ copy_v3_v3(normal, no);
mul_m3_v3(tmat, normal);
bone->roll = ED_rollBoneToVector(bone, normal, FALSE);
diff --git a/source/blender/editors/armature/editarmature_retarget.c b/source/blender/editors/armature/editarmature_retarget.c
index fad06f0d020..68cfc7fb8c0 100644
--- a/source/blender/editors/armature/editarmature_retarget.c
+++ b/source/blender/editors/armature/editarmature_retarget.c
@@ -191,7 +191,7 @@ static float rollBoneByQuatJoint(RigEdge *edge, RigEdge *previous, float qrot[4]
if (previous->bone) {
sub_v3_v3v3(vec_first, previous->bone->tail, previous->bone->head);
- }
+ }
else if (previous->prev->bone) {
sub_v3_v3v3(vec_first, edge->bone->head, previous->prev->bone->tail);
}
@@ -653,7 +653,7 @@ static int RIG_parentControl(RigControl *ctrl, EditBone *link)
sub_v3_v3v3(offset, ctrl->bone->head, link->head);
- /* if root matches, check for direction too */
+ /* if root matches, check for direction too */
if (dot_v3v3(offset, offset) < 0.0001f) {
float vbone[3], vparent[3];
@@ -802,7 +802,7 @@ static void RIG_reconnectControlBones(RigGraph *rg)
}
}
- /* if not found yet, check child */
+ /* if not found yet, check child */
if (found == 0) {
RigArc *arc;
RigArc *best_arc = NULL;
@@ -863,7 +863,7 @@ static void RIG_reconnectControlBones(RigGraph *rg)
/* SET bone link to ctrl corresponding to pchan */
RigControl *link = BLI_ghash_lookup(rg->controls_map, pchan->name);
- /* if owner is a control bone, link with it */
+ /* if owner is a control bone, link with it */
if (link && link->link) {
RIG_parentControl(ctrl, link->bone);
found = 1;
@@ -876,7 +876,7 @@ static void RIG_reconnectControlBones(RigGraph *rg)
cti->flush_constraint_targets(con, &targets, 0);
}
}
- }
+ }
if (found == 0) {
/* check if parent is already linked */
@@ -1319,12 +1319,12 @@ void RIG_printArc(RigGraph *rg, RigArc *arc)
for (edge = arc->edges.first; edge; edge = edge->next) {
printf("\tinner joints %0.3f %0.3f %0.3f\n", edge->tail[0], edge->tail[1], edge->tail[2]);
printf("\t\tlength %f\n", edge->length);
- printf("\t\tangle %f\n", edge->angle * 180 / M_PI);
+ printf("\t\tangle %f\n", edge->angle * (float)(180 / M_PI));
if (edge->bone) {
printf("\t\t%s\n", edge->bone->name);
RIG_printLinkedCtrl(rg, edge->bone, 3);
}
- }
+ }
printf("symmetry level: %i flag: %i group %i\n", arc->symmetry_level, arc->symmetry_flag, arc->symmetry_group);
RIG_printNode((RigNode *)arc->tail, "tail");
@@ -1336,7 +1336,7 @@ void RIG_printGraph(RigGraph *rg)
printf("---- ARCS ----\n");
for (arc = rg->arcs.first; arc; arc = arc->next) {
- RIG_printArc(rg, arc);
+ RIG_printArc(rg, arc);
printf("\n");
}
@@ -1345,7 +1345,7 @@ void RIG_printGraph(RigGraph *rg)
}
else {
printf("HEAD NODE: NONE\n");
- }
+ }
}
/*******************************************************************************************************/
@@ -1584,7 +1584,7 @@ static void finalizeControl(RigGraph *rigg, RigControl *ctrl, float resize)
repositionTailControl(rigg, ctrl_child);
}
}
- }
+ }
}
static void repositionTailControl(RigGraph *rigg, RigControl *ctrl)
@@ -1840,7 +1840,7 @@ static float calcCostAngleLengthDistance(BArcIterator *iter, float **UNUSED(vec_
length2 = normalize_v3(vec_second);
- /* Angle cost */
+ /* Angle cost */
if (edge->prev) {
sub_v3_v3v3(vec_first, vec1, vec0);
normalize_v3(vec_first);
@@ -1962,7 +1962,6 @@ static void retargetArctoArcAggresive(bContext *C, RigGraph *rigg, RigArc *iarc,
ReebArcIterator arc_iter;
BArcIterator *iter = (BArcIterator *)&arc_iter;
RigEdge *edge;
- EmbedBucket *bucket = NULL;
ReebNode *node_start, *node_end;
ReebArc *earc = iarc->link_mesh;
float angle_weight = 1.0; // GET FROM CONTEXT
@@ -1996,8 +1995,6 @@ static void retargetArctoArcAggresive(bContext *C, RigGraph *rigg, RigArc *iarc,
/* equal number of joints and potential position, just fill them in */
if (nb_joints == earc->bcount) {
- int i;
-
/* init with first values */
for (i = 0; i < nb_joints; i++) {
best_positions[i] = i + 1;
@@ -2011,7 +2008,6 @@ static void retargetArctoArcAggresive(bContext *C, RigGraph *rigg, RigArc *iarc,
MemoNode *result;
#endif
float **positions_cache = MEM_callocN(sizeof(float *) * (nb_positions + 2), "positions cache");
- int i;
positions_cache[0] = node_start->p;
positions_cache[nb_positions + 1] = node_end->p;
@@ -2053,7 +2049,7 @@ static void retargetArctoArcAggresive(bContext *C, RigGraph *rigg, RigArc *iarc,
{
float *no = NULL;
if (i < nb_joints) {
- bucket = IT_peek(iter, best_positions[i]);
+ EmbedBucket *bucket = IT_peek(iter, best_positions[i]);
vec1 = bucket->p;
no = bucket->no;
}
@@ -2139,7 +2135,7 @@ static void retargetArctoArcLength(bContext *C, RigGraph *rigg, RigArc *iarc, Ri
no = node_end->no;
}
- /* no need to move virtual edges (space between unconnected bones) */
+ /* no need to move virtual edges (space between unconnected bones) */
if (edge->bone) {
repositionBone(C, rigg, edge, vec0, vec1, no);
}
@@ -2177,7 +2173,7 @@ void *exec_retargetArctoArc(void *param)
RetargetParam *p = (RetargetParam *)param;
RigGraph *rigg = p->rigg;
RigArc *iarc = p->iarc;
- bContext *C = p->context;
+ bContext *C = p->context;
RigNode *inode_start = p->inode_start;
ReebArc *earc = iarc->link_mesh;
@@ -2226,7 +2222,7 @@ static void matchMultiResolutionNode(RigGraph *rigg, RigNode *inode, ReebNode *t
enode = enode->link_down;
reebg = BIF_graphForMultiNode(rigg->link_mesh, enode); /* replace with call to link_down once that exists */
eshape = BLI_subtreeShape((BGraph *)reebg, (BNode *)enode, NULL, 0) % SHAPE_LEVELS;
- }
+ }
}
static void markMultiResolutionChildArc(ReebNode *end_enode, ReebNode *enode)
@@ -2277,7 +2273,7 @@ static void matchMultiResolutionArc(RigGraph *rigg, RigNode *start_node, RigArc
reebg = reebg->link_up;
enode = next_earc->head;
eshape = BLI_subtreeShape((BGraph *)reebg, (BNode *)enode, (BArc *)next_earc, 1) % SHAPE_LEVELS;
- }
+ }
next_earc->flag = ARC_USED;
next_iarc->link_mesh = next_earc;
@@ -2307,7 +2303,7 @@ static void matchMultiResolutionStartingNode(RigGraph *rigg, ReebGraph *reebg, R
enode = reebg->nodes.first;
eshape = BLI_subtreeShape((BGraph *)reebg, (BNode *)enode, NULL, 0) % SHAPE_LEVELS;
- }
+ }
inode->link_mesh = enode;
}
@@ -2604,7 +2600,7 @@ void BIF_retargetArmature(bContext *C)
ED_undo_push(C, "Retarget Skeleton");
- // XXX
+ // XXX
// allqueue(REDRAWVIEW3D, 0);
}
diff --git a/source/blender/editors/armature/editarmature_sketch.c b/source/blender/editors/armature/editarmature_sketch.c
index 78d3d8dc64d..da8fc328343 100644
--- a/source/blender/editors/armature/editarmature_sketch.c
+++ b/source/blender/editors/armature/editarmature_sketch.c
@@ -41,6 +41,8 @@
#include "BLI_graph.h"
#include "BLI_ghash.h"
+#include "BLF_translation.h"
+
#include "BKE_context.h"
#include "BKE_sketch.h"
@@ -175,7 +177,7 @@ void BIF_makeListTemplates(const bContext *C)
const char *BIF_listTemplates(const bContext *UNUSED(C))
{
GHashIterator ghi;
- char menu_header[] = "Template%t|None%x0|";
+ const char *menu_header = IFACE_("Template %t|None %x0|");
char *p;
if (TEMPLATES_MENU != NULL) {
@@ -194,7 +196,7 @@ const char *BIF_listTemplates(const bContext *UNUSED(C))
Object *ob = BLI_ghashIterator_getValue(&ghi);
int key = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(&ghi));
- p += sprintf(p, "|%s%%x%i", ob->id.name + 2, key);
+ p += sprintf(p, "|%s %%x%i", ob->id.name + 2, key);
BLI_ghashIterator_step(&ghi);
}
@@ -438,7 +440,7 @@ static void sk_cancelStroke(SK_Sketch *sketch)
static float sk_clampPointSize(SK_Point *pt, float size)
{
- return MAX2(size * pt->size, size / 2);
+ return max_ff(size * pt->size, size / 2);
}
static void sk_drawPoint(GLUquadric *quad, SK_Point *pt, float size)
@@ -644,16 +646,17 @@ static SK_Point *sk_snapPointStroke(bContext *C, SK_Stroke *stk, int mval[2], in
short pval[2];
int pdist;
- project_short_noclip(ar, stk->points[i].p, pval);
+ if (ED_view3d_project_short_global(ar, stk->points[i].p, pval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
- pdist = ABS(pval[0] - mval[0]) + ABS(pval[1] - mval[1]);
+ pdist = ABS(pval[0] - mval[0]) + ABS(pval[1] - mval[1]);
- if (pdist < *dist) {
- *dist = pdist;
- pt = stk->points + i;
+ if (pdist < *dist) {
+ *dist = pdist;
+ pt = stk->points + i;
- if (index != NULL) {
- *index = i;
+ if (index != NULL) {
+ *index = i;
+ }
}
}
}
@@ -679,32 +682,34 @@ static SK_Point *sk_snapPointArmature(bContext *C, Object *ob, ListBase *ebones,
{
copy_v3_v3(vec, bone->head);
mul_m4_v3(ob->obmat, vec);
- project_short_noclip(ar, vec, pval);
+ if (ED_view3d_project_short_noclip(ar, vec, pval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
- pdist = ABS(pval[0] - mval[0]) + ABS(pval[1] - mval[1]);
+ pdist = ABS(pval[0] - mval[0]) + ABS(pval[1] - mval[1]);
- if (pdist < *dist)
- {
- *dist = pdist;
- pt = &boneSnap;
- copy_v3_v3(pt->p, vec);
- pt->type = PT_EXACT;
+ if (pdist < *dist)
+ {
+ *dist = pdist;
+ pt = &boneSnap;
+ copy_v3_v3(pt->p, vec);
+ pt->type = PT_EXACT;
+ }
}
}
copy_v3_v3(vec, bone->tail);
mul_m4_v3(ob->obmat, vec);
- project_short_noclip(ar, vec, pval);
+ if (ED_view3d_project_short_noclip(ar, vec, pval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
- pdist = ABS(pval[0] - mval[0]) + ABS(pval[1] - mval[1]);
+ pdist = ABS(pval[0] - mval[0]) + ABS(pval[1] - mval[1]);
- if (pdist < *dist)
- {
- *dist = pdist;
- pt = &boneSnap;
- copy_v3_v3(pt->p, vec);
- pt->type = PT_EXACT;
+ if (pdist < *dist)
+ {
+ *dist = pdist;
+ pt = &boneSnap;
+ copy_v3_v3(pt->p, vec);
+ pt->type = PT_EXACT;
+ }
}
}
@@ -905,9 +910,9 @@ static void sk_interpolateDepth(bContext *C, SK_Stroke *stk, int start, int end,
for (i = start; i <= end; i++) {
float ray_start[3], ray_normal[3];
float delta = len_v3v3(stk->points[i].p, stk->points[i + 1].p);
- float pval[2];
+ float pval[2] = {0, 0};
- project_float(ar, stk->points[i].p, pval);
+ ED_view3d_project_float_global(ar, stk->points[i].p, pval, V3D_PROJ_TEST_NOP);
ED_view3d_win_to_ray(ar, v3d, pval, ray_start, ray_normal);
mul_v3_fl(ray_normal, distance * progress / length);
@@ -934,10 +939,14 @@ static void sk_projectDrawPoint(bContext *C, float vec[3], SK_Stroke *stk, SK_Dr
initgrabz(ar->regiondata, fp[0], fp[1], fp[2]);
/* method taken from editview.c - mouse_cursor() */
- project_short_noclip(ar, fp, cval);
- VECSUB2D(mval_f, cval, dd->mval);
- ED_view3d_win_to_delta(ar, mval_f, dvec);
- sub_v3_v3v3(vec, fp, dvec);
+ if (ED_view3d_project_short_global(ar, fp, cval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ VECSUB2D(mval_f, cval, dd->mval);
+ ED_view3d_win_to_delta(ar, mval_f, dvec);
+ sub_v3_v3v3(vec, fp, dvec);
+ }
+ else {
+ zero_v3(vec);
+ }
}
static int sk_getStrokeDrawPoint(bContext *C, SK_Point *pt, SK_Sketch *UNUSED(sketch), SK_Stroke *stk, SK_DrawData *dd)
@@ -1453,8 +1462,8 @@ static int sk_getSelfIntersections(bContext *C, ListBase *list, SK_Stroke *gestu
float s_p2[3] = {0, 0, 0};
int g_i;
- project_float(ar, gesture->points[s_i].p, s_p1);
- project_float(ar, gesture->points[s_i + 1].p, s_p2);
+ ED_view3d_project_float_global(ar, gesture->points[s_i].p, s_p1, V3D_PROJ_TEST_NOP);
+ ED_view3d_project_float_global(ar, gesture->points[s_i + 1].p, s_p2, V3D_PROJ_TEST_NOP);
/* start checking from second next, because two consecutive cannot intersect */
for (g_i = s_i + 2; g_i < gesture->nb_points - 1; g_i++) {
@@ -1463,8 +1472,8 @@ static int sk_getSelfIntersections(bContext *C, ListBase *list, SK_Stroke *gestu
float vi[3];
float lambda;
- project_float(ar, gesture->points[g_i].p, g_p1);
- project_float(ar, gesture->points[g_i + 1].p, g_p2);
+ ED_view3d_project_float_global(ar, gesture->points[g_i].p, g_p1, V3D_PROJ_TEST_NOP);
+ ED_view3d_project_float_global(ar, gesture->points[g_i + 1].p, g_p2, V3D_PROJ_TEST_NOP);
if (isect_line_line_strict_v3(s_p1, s_p2, g_p1, g_p2, vi, &lambda)) {
SK_Intersection *isect = MEM_callocN(sizeof(SK_Intersection), "Intersection");
@@ -1531,8 +1540,8 @@ static int sk_getIntersections(bContext *C, ListBase *list, SK_Sketch *sketch, S
float s_p2[3] = {0, 0, 0};
int g_i;
- project_float(ar, stk->points[s_i].p, s_p1);
- project_float(ar, stk->points[s_i + 1].p, s_p2);
+ ED_view3d_project_float_global(ar, stk->points[s_i].p, s_p1, V3D_PROJ_TEST_NOP);
+ ED_view3d_project_float_global(ar, stk->points[s_i + 1].p, s_p2, V3D_PROJ_TEST_NOP);
for (g_i = 0; g_i < gesture->nb_points - 1; g_i++) {
float g_p1[3] = {0, 0, 0};
@@ -1540,8 +1549,8 @@ static int sk_getIntersections(bContext *C, ListBase *list, SK_Sketch *sketch, S
float vi[3];
float lambda;
- project_float(ar, gesture->points[g_i].p, g_p1);
- project_float(ar, gesture->points[g_i + 1].p, g_p2);
+ ED_view3d_project_float_global(ar, gesture->points[g_i].p, g_p1, V3D_PROJ_TEST_NOP);
+ ED_view3d_project_float_global(ar, gesture->points[g_i + 1].p, g_p2, V3D_PROJ_TEST_NOP);
if (isect_line_line_strict_v3(s_p1, s_p2, g_p1, g_p2, vi, &lambda)) {
SK_Intersection *isect = MEM_callocN(sizeof(SK_Intersection), "Intersection");
@@ -1717,8 +1726,8 @@ void sk_applyCommandGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UN
SK_Intersection *isect;
int command = 1;
-// XXX
-// command = pupmenu("Action %t|Flatten %x1|Straighten %x2|Polygonize %x3");
+/* XXX */
+/* command = pupmenu("Action %t|Flatten %x1|Straighten %x2|Polygonize %x3"); */
if (command < 1) return;
for (isect = gest->intersections.first; isect; isect = isect->next) {
@@ -1784,33 +1793,35 @@ int sk_detectMergeGesture(bContext *C, SK_Gesture *gest, SK_Sketch *UNUSED(sketc
short start_val[2], end_val[2];
short dist;
- project_short_noclip(ar, gest->stk->points[0].p, start_val);
- project_short_noclip(ar, sk_lastStrokePoint(gest->stk)->p, end_val);
+ if ((ED_view3d_project_short_global(ar, gest->stk->points[0].p, start_val, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
+ (ED_view3d_project_short_global(ar, sk_lastStrokePoint(gest->stk)->p, end_val, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
+ {
- dist = MAX2(ABS(start_val[0] - end_val[0]), ABS(start_val[1] - end_val[1]));
+ dist = MAX2(ABS(start_val[0] - end_val[0]), ABS(start_val[1] - end_val[1]));
- /* if gesture is a circle */
- if (dist <= 20) {
- SK_Intersection *isect;
+ /* if gesture is a circle */
+ if (dist <= 20) {
+ SK_Intersection *isect;
- /* check if it circled around an exact point */
- for (isect = gest->intersections.first; isect; isect = isect->next) {
- /* only delete strokes that are crossed twice */
- if (isect->next && isect->next->stroke == isect->stroke) {
- int start_index, end_index;
- int i;
+ /* check if it circled around an exact point */
+ for (isect = gest->intersections.first; isect; isect = isect->next) {
+ /* only delete strokes that are crossed twice */
+ if (isect->next && isect->next->stroke == isect->stroke) {
+ int start_index, end_index;
+ int i;
- start_index = MIN2(isect->after, isect->next->after);
- end_index = MAX2(isect->before, isect->next->before);
+ start_index = MIN2(isect->after, isect->next->after);
+ end_index = MAX2(isect->before, isect->next->before);
- for (i = start_index; i <= end_index; i++) {
- if (isect->stroke->points[i].type == PT_EXACT) {
- return 1; /* at least one exact point found, stop detect here */
+ for (i = start_index; i <= end_index; i++) {
+ if (isect->stroke->points[i].type == PT_EXACT) {
+ return 1; /* at least one exact point found, stop detect here */
+ }
}
- }
- /* skip next */
- isect = isect->next;
+ /* skip next */
+ isect = isect->next;
+ }
}
}
}
diff --git a/source/blender/editors/armature/meshlaplacian.c b/source/blender/editors/armature/meshlaplacian.c
index 346ed0002bd..9152ea8e198 100644
--- a/source/blender/editors/armature/meshlaplacian.c
+++ b/source/blender/editors/armature/meshlaplacian.c
@@ -53,7 +53,6 @@
#include "BKE_modifier.h"
#include "BKE_mesh.h"
-
#ifdef RIGID_DEFORM
#include "BLI_polardecomp.h"
#endif
@@ -563,7 +562,7 @@ static void heat_set_H(LaplacianSystem *sys, int vertex)
/* compute H entry */
if (numclosest > 0) {
- mindist = maxf(mindist, 1e-4f);
+ mindist = max_ff(mindist, 1e-4f);
h = numclosest * C_WEIGHT / (mindist * mindist);
}
else
@@ -794,7 +793,7 @@ void heat_bone_weighting(Object *ob, Mesh *me, float (*verts)[3], int numsource,
}
}
else if (*err_str == NULL) {
- *err_str = "Bone Heat Weighting: failed to find solution for one or more bones";
+ *err_str = N_("Bone Heat Weighting: failed to find solution for one or more bones");
break;
}
@@ -1113,6 +1112,9 @@ typedef struct MeshDeformBind {
/* direct solver */
int *varidx;
+
+ BVHTree *bvhtree;
+ BVHTreeFromMesh bvhdata;
} MeshDeformBind;
typedef struct MeshDeformIsect {
@@ -1130,8 +1132,9 @@ typedef struct MeshDeformIsect {
/* our own triangle intersection, so we can fully control the epsilons and
* prevent corner case from going wrong*/
-static int meshdeform_tri_intersect(float orig[3], float end[3], float vert0[3],
- float vert1[3], float vert2[3], float *isectco, float *uvw)
+static int meshdeform_tri_intersect(const float orig[3], const float end[3], const float vert0[3],
+ const float vert1[3], const float vert2[3],
+ float r_isectco[3], float r_uvw[3])
{
float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
float det, inv_det, u, v, dir[3], isectdir[3];
@@ -1148,8 +1151,10 @@ static int meshdeform_tri_intersect(float orig[3], float end[3], float vert0[3],
/* if determinant is near zero, ray lies in plane of triangle */
det = dot_v3v3(edge1, pvec);
- if (det == 0.0f)
+ if (UNLIKELY(det == 0.0f)) {
return 0;
+ }
+
inv_det = 1.0f / det;
/* calculate distance from vert0 to ray origin */
@@ -1168,16 +1173,16 @@ static int meshdeform_tri_intersect(float orig[3], float end[3], float vert0[3],
if (v < -EPSILON || u + v > 1.0f + EPSILON)
return 0;
- isectco[0] = (1.0f - u - v) * vert0[0] + u * vert1[0] + v * vert2[0];
- isectco[1] = (1.0f - u - v) * vert0[1] + u * vert1[1] + v * vert2[1];
- isectco[2] = (1.0f - u - v) * vert0[2] + u * vert1[2] + v * vert2[2];
+ r_isectco[0] = (1.0f - u - v) * vert0[0] + u * vert1[0] + v * vert2[0];
+ r_isectco[1] = (1.0f - u - v) * vert0[1] + u * vert1[1] + v * vert2[1];
+ r_isectco[2] = (1.0f - u - v) * vert0[2] + u * vert1[2] + v * vert2[2];
- uvw[0] = 1.0f - u - v;
- uvw[1] = u;
- uvw[2] = v;
+ r_uvw[0] = 1.0f - u - v;
+ r_uvw[1] = u;
+ r_uvw[2] = v;
/* check if it is within the length of the line segment */
- sub_v3_v3v3(isectdir, isectco, orig);
+ sub_v3_v3v3(isectdir, r_isectco, orig);
if (dot_v3v3(dir, isectdir) < -EPSILON)
return 0;
@@ -1188,83 +1193,79 @@ static int meshdeform_tri_intersect(float orig[3], float end[3], float vert0[3],
return 1;
}
-static int meshdeform_intersect(MeshDeformBind *mdb, MeshDeformIsect *isec)
+static void harmonic_ray_callback(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
{
- MFace *mface;
- float face[4][3], co[3], uvw[3], len, nor[3], end[3];
- int f, hit, is = 0, totface;
-
- isec->labda = 1e10;
-
- mface = mdb->cagedm->getTessFaceArray(mdb->cagedm);
- totface = mdb->cagedm->getNumTessFaces(mdb->cagedm);
-
+ void **data = userdata;
+ MeshDeformBind *mdb = data[1];
+ MFace *mface = data[0], *mf;
+ MeshDeformIsect *isec = data[2];
+ float no[3], co[3], end[3], uvw[3], dist, face[4][3];
+
+ mf = mface + index;
+
+ copy_v3_v3(face[0], mdb->cagecos[mf->v1]);
+ copy_v3_v3(face[1], mdb->cagecos[mf->v2]);
+ copy_v3_v3(face[2], mdb->cagecos[mf->v3]);
+ if (mf->v4)
+ copy_v3_v3(face[3], mdb->cagecos[mf->v4]);
+
add_v3_v3v3(end, isec->start, isec->vec);
-
- for (f = 0; f < totface; f++, mface++) {
- copy_v3_v3(face[0], mdb->cagecos[mface->v1]);
- copy_v3_v3(face[1], mdb->cagecos[mface->v2]);
- copy_v3_v3(face[2], mdb->cagecos[mface->v3]);
-
- if (mface->v4) {
- copy_v3_v3(face[3], mdb->cagecos[mface->v4]);
- hit = meshdeform_tri_intersect(isec->start, end, face[0], face[1], face[2], co, uvw);
-
- if (hit) {
- normal_tri_v3(nor, face[0], face[1], face[2]);
- }
- else {
- hit = meshdeform_tri_intersect(isec->start, end, face[0], face[2], face[3], co, uvw);
- normal_tri_v3(nor, face[0], face[2], face[3]);
- }
- }
- else {
- hit = meshdeform_tri_intersect(isec->start, end, face[0], face[1], face[2], co, uvw);
- normal_tri_v3(nor, face[0], face[1], face[2]);
- }
-
- if (hit) {
- len = len_v3v3(isec->start, co) / len_v3v3(isec->start, end);
- if (len < isec->labda) {
- isec->labda = len;
- isec->face = mface;
- isec->isect = (dot_v3v3(isec->vec, nor) <= 0.0f);
- is = 1;
- }
- }
+
+ if (!meshdeform_tri_intersect(ray->origin, end, face[0], face[1], face[2], co, uvw))
+ if (!mf->v4 || !meshdeform_tri_intersect(ray->origin, end, face[0], face[2], face[3], co, uvw))
+ return;
+
+ if (!mf->v4)
+ normal_tri_v3(no, face[0], face[1], face[2]);
+ else
+ normal_quad_v3(no, face[0], face[1], face[2], face[3]);
+
+ dist = len_v3v3(ray->origin, co) / len_v3(isec->vec);
+ if (dist < hit->dist) {
+ hit->index = index;
+ hit->dist = dist;
+ copy_v3_v3(hit->co, co);
+
+ isec->isect = (dot_v3v3(no, ray->direction) <= 0.0f);
+ isec->labda = dist;
+ isec->face = mf;
}
-
- return is;
}
static MDefBoundIsect *meshdeform_ray_tree_intersect(MeshDeformBind *mdb, float *co1, float *co2)
{
MDefBoundIsect *isect;
- MeshDeformIsect isec;
+ BVHTreeRayHit hit;
+ MeshDeformIsect isect_mdef;
float (*cagecos)[3];
- MFace *mface;
+ void *data[3] = {mdb->cagedm->getTessFaceArray(mdb->cagedm), mdb, &isect_mdef};
+ MFace *mface1 = data[0], *mface;
float vert[4][3], len, end[3];
static float epsilon[3] = {0, 0, 0}; //1e-4, 1e-4, 1e-4};
/* setup isec */
- memset(&isec, 0, sizeof(isec));
- isec.labda = 1e10f;
+ memset(&isect_mdef, 0, sizeof(isect_mdef));
+ isect_mdef.labda = 1e10f;
- add_v3_v3v3(isec.start, co1, epsilon);
+ add_v3_v3v3(isect_mdef.start, co1, epsilon);
add_v3_v3v3(end, co2, epsilon);
- sub_v3_v3v3(isec.vec, end, isec.start);
+ sub_v3_v3v3(isect_mdef.vec, end, isect_mdef.start);
- if (meshdeform_intersect(mdb, &isec)) {
- len = isec.labda;
- mface = (MFace *)isec.face;
+ hit.index = -1;
+ hit.dist = FLT_MAX;
+ if (BLI_bvhtree_ray_cast(mdb->bvhtree, isect_mdef.start, isect_mdef.vec,
+ 0.0, &hit, harmonic_ray_callback, data) != -1)
+ {
+ len = isect_mdef.labda;
+ isect_mdef.face = mface = mface1 + hit.index;
/* create MDefBoundIsect */
isect = BLI_memarena_alloc(mdb->memarena, sizeof(*isect));
/* compute intersection coordinate */
- isect->co[0] = co1[0] + isec.vec[0] * len;
- isect->co[1] = co1[1] + isec.vec[1] * len;
- isect->co[2] = co1[2] + isec.vec[2] * len;
+ isect->co[0] = co1[0] + isect_mdef.vec[0] * len;
+ isect->co[1] = co1[1] + isect_mdef.vec[1] * len;
+ isect->co[2] = co1[2] + isect_mdef.vec[2] * len;
isect->len = len_v3v3(co1, isect->co);
if (isect->len < MESHDEFORM_LEN_THRESHOLD)
@@ -1276,7 +1277,7 @@ static MDefBoundIsect *meshdeform_ray_tree_intersect(MeshDeformBind *mdb, float
isect->v[3] = mface->v4;
isect->nvert = (mface->v4) ? 4 : 3;
- isect->facing = isec.isect;
+ isect->facing = isect_mdef.isect;
/* compute mean value coordinates for interpolation */
cagecos = mdb->cagecos;
@@ -1720,7 +1721,7 @@ static void meshdeform_matrix_solve(MeshDeformModifierData *mmd, MeshDeformBind
}
}
else {
- modifier_setError(&mmd->modifier, "%s", TIP_("Failed to find bind solution (increase precision?)."));
+ modifier_setError(&mmd->modifier, "Failed to find bind solution (increase precision?)");
error("Mesh Deform: failed to find bind solution.");
break;
}
@@ -1766,7 +1767,7 @@ static void harmonic_coordinates_bind(Scene *UNUSED(scene), MeshDeformModifierDa
mdb->totalphi = MEM_callocN(sizeof(float) * mdb->size3, "MeshDeformBindTotalPhi");
mdb->boundisect = MEM_callocN(sizeof(*mdb->boundisect) * mdb->size3, "MDefBoundIsect");
mdb->semibound = MEM_callocN(sizeof(int) * mdb->size3, "MDefSemiBound");
-
+ mdb->bvhtree = bvhtree_from_mesh_faces(&mdb->bvhdata, mdb->cagedm, FLT_EPSILON*100, 4, 6);
mdb->inside = MEM_callocN(sizeof(int) * mdb->totvert, "MDefInside");
if (mmd->flag & MOD_MDEF_DYNAMIC_BIND)
@@ -1882,6 +1883,7 @@ static void harmonic_coordinates_bind(Scene *UNUSED(scene), MeshDeformModifierDa
MEM_freeN(mdb->boundisect);
MEM_freeN(mdb->semibound);
BLI_memarena_free(mdb->memarena);
+ free_bvhtree_from_mesh(&mdb->bvhdata);
}
#if 0
diff --git a/source/blender/editors/armature/poseSlide.c b/source/blender/editors/armature/poseSlide.c
index cdcb3ab4683..3fd65de6c04 100644
--- a/source/blender/editors/armature/poseSlide.c
+++ b/source/blender/editors/armature/poseSlide.c
@@ -105,7 +105,7 @@ typedef struct tPoseSlideOp {
int nextFrame; /* frame after current frame (blend-to) */
int mode; /* sliding mode (ePoseSlide_Modes) */
- int flag; // unused for now, but can later get used for storing runtime settings....
+ int flag; /* unused for now, but can later get used for storing runtime settings.... */
float percentage; /* 0-1 value for determining the influence of whatever is relevant */
} tPoseSlideOp;
@@ -486,7 +486,7 @@ static void pose_slide_apply(bContext *C, tPoseSlideOp *pso)
pose_slide_apply_vec3(pso, pfl, pchan->eul, "rotation_euler");
}
else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
- // TODO: need to figure out how to do this!
+ /* TODO: need to figure out how to do this! */
}
else {
/* quaternions - use quaternion blending */
@@ -538,7 +538,7 @@ static void pose_slide_draw_status(tPoseSlideOp *pso)
break;
default:
- // unknown
+ /* unknown */
strcpy(mode_str, "Sliding-Tool");
break;
}
@@ -606,7 +606,7 @@ static int pose_slide_invoke_common(bContext *C, wmOperator *op, tPoseSlideOp *p
}
/* initial apply for operator... */
- // TODO: need to calculate percentage for initial round too...
+ /* TODO: need to calculate percentage for initial round too... */
pose_slide_apply(C, pso);
/* depsgraph updates + redraws */
@@ -631,6 +631,7 @@ static int pose_slide_modal(bContext *C, wmOperator *op, wmEvent *evt)
switch (evt->type) {
case LEFTMOUSE: /* confirm */
+ case RETKEY:
{
/* return to normal cursor and header status */
ED_area_headerprint(pso->sa, NULL);
@@ -1151,7 +1152,7 @@ static void pose_propagate_fcurve(wmOperator *op, Object *ob, FCurve *fcu,
}
/* just flatten handles, since values will now be the same either side... */
- // TODO: perhaps a fade-out modulation of the value is required here (optional once again)?
+ /* TODO: perhaps a fade-out modulation of the value is required here (optional once again)? */
bezt->vec[0][1] = bezt->vec[1][1] = bezt->vec[2][1] = refVal;
/* select keyframe to indicate that it's been changed */
@@ -1246,13 +1247,13 @@ void POSE_OT_propagate(wmOperatorType *ot)
/* callbacks */
ot->exec = pose_propagate_exec;
- ot->poll = ED_operator_posemode; // XXX: needs selected bones!
+ ot->poll = ED_operator_posemode; /* XXX: needs selected bones! */
/* flag */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
- // TODO: add "fade out" control for tapering off amount of propagation as time goes by?
+ /* TODO: add "fade out" control for tapering off amount of propagation as time goes by? */
ot->prop = RNA_def_enum(ot->srna, "mode", terminate_items, POSE_PROPAGATE_SMART_HOLDS, "Terminate Mode", "Method used to determine when to stop propagating pose to keyframes");
RNA_def_float(ot->srna, "end_frame", 250.0, FLT_MIN, FLT_MAX, "End Frame", "Frame to stop propagating frames to (for 'Before Frame' mode)", 1.0, 250.0);
}
diff --git a/source/blender/editors/armature/poseUtils.c b/source/blender/editors/armature/poseUtils.c
index e2e3c49e7e0..f3c32399ad6 100644
--- a/source/blender/editors/armature/poseUtils.c
+++ b/source/blender/editors/armature/poseUtils.c
@@ -274,7 +274,7 @@ LinkData *poseAnim_mapping_getNextFCurve(ListBase *fcuLinks, LinkData *prev, con
/* check if paths match */
if (strcmp(path, fcu->rna_path) == 0)
return ld;
- }
+ }
/* none found */
return NULL;
diff --git a/source/blender/editors/armature/poselib.c b/source/blender/editors/armature/poselib.c
index eea7424c59a..ae3d496b641 100644
--- a/source/blender/editors/armature/poselib.c
+++ b/source/blender/editors/armature/poselib.c
@@ -298,7 +298,7 @@ static int poselib_sanitize_exec(bContext *C, wmOperator *op)
/* validate action */
if (act == NULL) {
- BKE_report(op->reports, RPT_WARNING, "No Action to validate");
+ BKE_report(op->reports, RPT_WARNING, "No action to validate");
return OPERATOR_CANCELLED;
}
@@ -547,7 +547,7 @@ static int poselib_remove_exec(bContext *C, wmOperator *op)
/* check if valid poselib */
if (act == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
+ BKE_report(op->reports, RPT_ERROR, "Object does not have pose lib data");
return OPERATOR_CANCELLED;
}
@@ -562,7 +562,7 @@ static int poselib_remove_exec(bContext *C, wmOperator *op)
/* get index (and pointer) of pose to remove */
marker = BLI_findlink(&act->markers, marker_index);
if (marker == NULL) {
- BKE_reportf(op->reports, RPT_ERROR, "Invalid Pose specified %d", marker_index);
+ BKE_reportf(op->reports, RPT_ERROR, "Invalid pose specified %d", marker_index);
return OPERATOR_CANCELLED;
}
@@ -628,14 +628,14 @@ static int poselib_rename_invoke(bContext *C, wmOperator *op, wmEvent *evt)
/* check if valid poselib */
if (act == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
+ BKE_report(op->reports, RPT_ERROR, "Object does not have pose lib data");
return OPERATOR_CANCELLED;
}
/* get index (and pointer) of pose to remove */
marker = BLI_findlink(&act->markers, act->active_marker - 1);
if (marker == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Invalid index for Pose");
+ BKE_report(op->reports, RPT_ERROR, "Invalid index for pose");
return OPERATOR_CANCELLED;
}
else {
@@ -657,14 +657,14 @@ static int poselib_rename_exec(bContext *C, wmOperator *op)
/* check if valid poselib */
if (act == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
+ BKE_report(op->reports, RPT_ERROR, "Object does not have pose lib data");
return OPERATOR_CANCELLED;
}
/* get index (and pointer) of pose to remove */
marker = BLI_findlink(&act->markers, RNA_int_get(op->ptr, "pose"));
if (marker == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Invalid index for Pose");
+ BKE_report(op->reports, RPT_ERROR, "Invalid index for pose");
return OPERATOR_CANCELLED;
}
@@ -871,7 +871,7 @@ static void poselib_apply_pose(tPoseLib_PreviewData *pld)
if (pld->marker)
frame = pld->marker->frame;
else
- return;
+ return;
/* init settings for testing groups for keyframes */
@@ -887,7 +887,7 @@ static void poselib_apply_pose(tPoseLib_PreviewData *pld)
/* has keyframe on this frame, so try to get a PoseChannel with this name */
pchan = BKE_pose_channel_find_name(pose, agrp->name);
- if (pchan) {
+ if (pchan) {
short ok = 0;
/* check if this bone should get any animation applied */
@@ -1079,7 +1079,7 @@ static void poselib_preview_get_next(tPoseLib_PreviewData *pld, int step)
}
/* check if any matches */
- if (pld->searchp.first == NULL) {
+ if (pld->searchp.first == NULL) {
pld->marker = NULL;
return;
}
@@ -1152,7 +1152,7 @@ static void poselib_preview_handle_search(tPoseLib_PreviewData *pld, unsigned sh
poselib_preview_get_next(pld, 1);
pld->redraw = PL_PREVIEW_REDRAWALL;
return;
- }
+ }
break;
case DELKEY:
@@ -1424,12 +1424,12 @@ static void poselib_preview_init_data(bContext *C, wmOperator *op)
/* check if valid poselib */
if (ELEM3(NULL, pld->ob, pld->pose, pld->arm)) {
- BKE_report(op->reports, RPT_ERROR, "PoseLib is only for Armatures in PoseMode");
+ BKE_report(op->reports, RPT_ERROR, "Pose lib is only for armatures in pose mode");
pld->state = PL_PREVIEW_ERROR;
return;
}
if (pld->act == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Object doesn't have a valid PoseLib");
+ BKE_report(op->reports, RPT_ERROR, "Object does not have a valid pose lib");
pld->state = PL_PREVIEW_ERROR;
return;
}
@@ -1438,10 +1438,10 @@ static void poselib_preview_init_data(bContext *C, wmOperator *op)
/* just use first one then... */
pld->marker = pld->act->markers.first;
if (pose_index > -2)
- BKE_report(op->reports, RPT_WARNING, "PoseLib had no active pose");
+ BKE_report(op->reports, RPT_WARNING, "Pose lib had no active pose");
}
else {
- BKE_report(op->reports, RPT_ERROR, "PoseLib has no poses to preview/apply");
+ BKE_report(op->reports, RPT_ERROR, "Pose lib has no poses to preview/apply");
pld->state = PL_PREVIEW_ERROR;
return;
}
@@ -1639,7 +1639,7 @@ void POSELIB_OT_browse_interactive(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
- /* properties */
+ /* properties */
// TODO: make the pose_index into a proper enum instead of a cryptic int...
ot->prop = RNA_def_int(ot->srna, "pose_index", -1, -2, INT_MAX, "Pose", "Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)", 0, INT_MAX);
diff --git a/source/blender/editors/armature/poseobject.c b/source/blender/editors/armature/poseobject.c
index ac1766aff69..576e5983d16 100644
--- a/source/blender/editors/armature/poseobject.c
+++ b/source/blender/editors/armature/poseobject.c
@@ -81,6 +81,23 @@
#include "armature_intern.h"
+/* matches logic with ED_operator_posemode_context() */
+Object *ED_pose_object_from_context(bContext *C)
+{
+ ScrArea *sa = CTX_wm_area(C);
+ Object *ob;
+
+ /* since this call may also be used from the buttons window, we need to check for where to get the object */
+ if (sa && sa->spacetype == SPACE_BUTS) {
+ ob = ED_object_context(C);
+ }
+ else {
+ ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
+ }
+
+ return ob;
+}
+
/* This function is used to process the necessary updates for */
void ED_armature_enter_posemode(bContext *C, Base *base)
{
@@ -88,7 +105,7 @@ void ED_armature_enter_posemode(bContext *C, Base *base)
Object *ob = base->object;
if (ob->id.lib) {
- BKE_report(reports, RPT_WARNING, "Can't pose libdata");
+ BKE_report(reports, RPT_WARNING, "Cannot pose libdata");
return;
}
@@ -117,7 +134,7 @@ void ED_armature_exit_posemode(bContext *C, Base *base)
ob->mode &= ~OB_MODE_POSE;
WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_OBJECT, NULL);
- }
+ }
}
/* if a selected or active bone is protected, throw error (oonly if warn == 1) and return 1 */
@@ -475,7 +492,7 @@ static int pose_select_hierarchy_exec(bContext *C, wmOperator *op)
if (pchan->parent == NULL) continue;
else pabone = pchan->parent->bone;
- if (PBONE_VISIBLE(arm, pabone)) {
+ if (PBONE_SELECTABLE(arm, pabone)) {
if (!add_to_sel) curbone->flag &= ~BONE_SELECTED;
pabone->flag |= BONE_SELECTED;
arm->act_bone = pabone;
@@ -483,7 +500,7 @@ static int pose_select_hierarchy_exec(bContext *C, wmOperator *op)
found = 1;
break;
}
- }
+ }
else { /* direction == BONE_SELECT_CHILD */
/* the child member is only assigned to connected bones, see [#30340] */
#if 0
@@ -497,7 +514,7 @@ static int pose_select_hierarchy_exec(bContext *C, wmOperator *op)
for (pchan_child = ob->pose->chanbase.first; pchan_child; pchan_child = pchan_child->next) {
/* possible we have multiple children, some invisible */
- if (PBONE_VISIBLE(arm, pchan_child->bone)) {
+ if (PBONE_SELECTABLE(arm, pchan_child->bone)) {
if (pchan_child->parent == pchan) {
chbone = pchan_child->bone;
break;
@@ -509,7 +526,7 @@ static int pose_select_hierarchy_exec(bContext *C, wmOperator *op)
if (chbone == NULL) continue;
#endif
- if (PBONE_VISIBLE(arm, chbone)) {
+ if (PBONE_SELECTABLE(arm, chbone)) {
if (!add_to_sel) curbone->flag &= ~BONE_SELECTED;
chbone->flag |= BONE_SELECTED;
arm->act_bone = chbone;
@@ -702,9 +719,7 @@ static int pose_select_same_keyingset(bContext *C, Object *ob, short extend)
if (pchan) {
/* select if bone is visible and can be affected */
- if ((PBONE_VISIBLE(arm, pchan->bone)) &&
- (pchan->bone->flag & BONE_UNSELECTABLE) == 0)
- {
+ if (PBONE_SELECTABLE(arm, pchan->bone)) {
pchan->bone->flag |= BONE_SELECTED;
changed = 1;
}
@@ -871,16 +886,16 @@ static void pose_copy_menu(Scene *scene)
if (pose_has_protected_selected(ob, 0)) {
i = BLI_countlist(&(pchanact->constraints)); /* if there are 24 or less, allow for the user to select constraints */
if (i < 25)
- nr = pupmenu("Copy Pose Attributes %t|Local Location%x1|Local Rotation%x2|Local Size%x3|%l|Visual Location %x9|Visual Rotation%x10|Visual Size%x11|%l|Constraints (All)%x4|Constraints...%x5");
+ nr = pupmenu("Copy Pose Attributes %t|Local Location %x1|Local Rotation %x2|Local Size %x3|%l|Visual Location %x9|Visual Rotation %x10|Visual Size %x11|%l|Constraints (All) %x4|Constraints... %x5");
else
- nr = pupmenu("Copy Pose Attributes %t|Local Location%x1|Local Rotation%x2|Local Size%x3|%l|Visual Location %x9|Visual Rotation%x10|Visual Size%x11|%l|Constraints (All)%x4");
+ nr = pupmenu("Copy Pose Attributes %t|Local Location %x1|Local Rotation %x2|Local Size %x3|%l|Visual Location %x9|Visual Rotation %x10|Visual Size %x11|%l|Constraints (All) %x4");
}
else {
i = BLI_countlist(&(pchanact->constraints)); /* if there are 24 or less, allow for the user to select constraints */
if (i < 25)
- nr = pupmenu("Copy Pose Attributes %t|Local Location%x1|Local Rotation%x2|Local Size%x3|%l|Visual Location %x9|Visual Rotation%x10|Visual Size%x11|%l|Constraints (All)%x4|Constraints...%x5|%l|Transform Locks%x6|IK Limits%x7|Bone Shape%x8");
+ nr = pupmenu("Copy Pose Attributes %t|Local Location %x1|Local Rotation %x2|Local Size %x3|%l|Visual Location %x9|Visual Rotation %x10|Visual Size %x11|%l|Constraints (All) %x4|Constraints... %x5|%l|Transform Locks %x6|IK Limits %x7|Bone Shape %x8");
else
- nr = pupmenu("Copy Pose Attributes %t|Local Location%x1|Local Rotation%x2|Local Size%x3|%l|Visual Location %x9|Visual Rotation%x10|Visual Size%x11|%l|Constraints (All)%x4|%l|Transform Locks%x6|IK Limits%x7|Bone Shape%x8");
+ nr = pupmenu("Copy Pose Attributes %t|Local Location %x1|Local Rotation %x2|Local Size %x3|%l|Visual Location %x9|Visual Rotation %x10|Visual Size %x11|%l|Constraints (All) %x4|%l|Transform Locks %x6|IK Limits %x7|Bone Shape %x8");
}
if (nr <= 0)
@@ -977,7 +992,7 @@ static void pose_copy_menu(Scene *scene)
}
}
}
- }
+ }
else { /* constraints, optional (note: max we can have is 24 constraints) */
bConstraint *con, *con_back;
int const_toggle[24] = {0}; /* XXX, initialize as 0 to quiet errors */
@@ -1003,7 +1018,7 @@ static void pose_copy_menu(Scene *scene)
con_back = con->next;
BLI_freelinkN(&const_copy, con);
con = con_back;
- }
+ }
else
con = con->next;
}
@@ -1020,7 +1035,7 @@ static void pose_copy_menu(Scene *scene)
* appending to list of constraints for this channel
*/
copy_constraints(&tmp_constraints, &const_copy, TRUE);
- if ((ob->proxy) && (pchan->bone->layer & arm->layer_protected)) {
+ if ((ob->proxy) && (pchan->bone->layer & arm->layer_protected)) {
/* add proxy-local tags */
for (con = tmp_constraints.first; con; con = con->next)
con->flag |= CONSTRAINT_PROXY_LOCAL;
@@ -1082,7 +1097,7 @@ static void set_pose_keys(Object *ob)
for (chan = ob->pose->chanbase.first; chan; chan = chan->next) {
Bone *bone = chan->bone;
if ((bone) && (bone->flag & BONE_SELECTED) && (arm->layer & bone->layer))
- chan->flag |= POSE_KEY;
+ chan->flag |= POSE_KEY;
else
chan->flag &= ~POSE_KEY;
}
@@ -1221,7 +1236,7 @@ static int pose_copy_exec(bContext *C, wmOperator *op)
/* sanity checking */
if (ELEM(NULL, ob, ob->pose)) {
- BKE_report(op->reports, RPT_ERROR, "No Pose to Copy");
+ BKE_report(op->reports, RPT_ERROR, "No pose to copy");
return OPERATOR_CANCELLED;
}
@@ -1331,15 +1346,8 @@ void POSE_OT_paste(wmOperatorType *ot)
static int pose_group_add_exec(bContext *C, wmOperator *UNUSED(op))
{
- ScrArea *sa = CTX_wm_area(C);
- Object *ob;
-
- /* since this call may also be used from the buttons window, we need to check for where to get the object */
- if (sa->spacetype == SPACE_BUTS)
- ob = ED_object_context(C);
- else
- ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
-
+ Object *ob = ED_pose_object_from_context(C);
+
/* only continue if there's an object */
if (ob == NULL)
return OPERATOR_CANCELLED;
@@ -1362,7 +1370,7 @@ void POSE_OT_group_add(wmOperatorType *ot)
/* api callbacks */
ot->exec = pose_group_add_exec;
- ot->poll = ED_operator_posemode;
+ ot->poll = ED_operator_posemode_context;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1371,14 +1379,7 @@ void POSE_OT_group_add(wmOperatorType *ot)
static int pose_group_remove_exec(bContext *C, wmOperator *UNUSED(op))
{
- ScrArea *sa = CTX_wm_area(C);
- Object *ob;
-
- /* since this call may also be used from the buttons window, we need to check for where to get the object */
- if (sa->spacetype == SPACE_BUTS)
- ob = ED_object_context(C);
- else
- ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
+ Object *ob = ED_pose_object_from_context(C);
/* only continue if there's an object */
if (ob == NULL)
@@ -1398,11 +1399,11 @@ void POSE_OT_group_remove(wmOperatorType *ot)
/* identifiers */
ot->name = "Remove Bone Group";
ot->idname = "POSE_OT_group_remove";
- ot->description = "Removes the active bone group";
+ ot->description = "Remove the active bone group";
/* api callbacks */
ot->exec = pose_group_remove_exec;
- ot->poll = ED_operator_posemode;
+ ot->poll = ED_operator_posemode_context;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1413,8 +1414,7 @@ void POSE_OT_group_remove(wmOperatorType *ot)
/* invoke callback which presents a list of bone-groups for the user to choose from */
static int pose_groups_menu_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(evt))
{
- ScrArea *sa = CTX_wm_area(C);
- Object *ob;
+ Object *ob = ED_pose_object_from_context(C);
bPose *pose;
uiPopupMenu *pup;
@@ -1422,12 +1422,6 @@ static int pose_groups_menu_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(
bActionGroup *grp;
int i;
- /* since this call may also be used from the buttons window, we need to check for where to get the object */
- if (sa->spacetype == SPACE_BUTS)
- ob = ED_object_context(C);
- else
- ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
-
/* only continue if there's an object, and a pose there too */
if (ELEM(NULL, ob, ob->pose))
return OPERATOR_CANCELLED;
@@ -1466,17 +1460,10 @@ static int pose_groups_menu_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(
/* Assign selected pchans to the bone group that the user selects */
static int pose_group_assign_exec(bContext *C, wmOperator *op)
{
- ScrArea *sa = CTX_wm_area(C);
- Object *ob;
+ Object *ob = ED_pose_object_from_context(C);
bPose *pose;
short done = FALSE;
-
- /* since this call may also be used from the buttons window, we need to check for where to get the object */
- if (sa->spacetype == SPACE_BUTS)
- ob = ED_object_context(C);
- else
- ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
-
+
/* only continue if there's an object, and a pose there too */
if (ELEM(NULL, ob, ob->pose))
return OPERATOR_CANCELLED;
@@ -1518,28 +1505,21 @@ void POSE_OT_group_assign(wmOperatorType *ot)
/* api callbacks */
ot->invoke = pose_groups_menu_invoke;
ot->exec = pose_group_assign_exec;
- ot->poll = ED_operator_posemode;
+ ot->poll = ED_operator_posemode_context;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
- RNA_def_int(ot->srna, "type", 0, 0, 10, "Bone Group Index", "", 0, INT_MAX);
+ RNA_def_int(ot->srna, "type", 0, 0, INT_MAX, "Bone Group Index", "", 0, 10);
}
static int pose_group_unassign_exec(bContext *C, wmOperator *UNUSED(op))
{
- ScrArea *sa = CTX_wm_area(C);
- Object *ob;
+ Object *ob = ED_pose_object_from_context(C);
short done = FALSE;
- /* since this call may also be used from the buttons window, we need to check for where to get the object */
- if (sa->spacetype == SPACE_BUTS)
- ob = ED_object_context(C);
- else
- ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
-
/* only continue if there's an object, and a pose there too */
if (ELEM(NULL, ob, ob->pose))
return OPERATOR_CANCELLED;
@@ -1573,7 +1553,7 @@ void POSE_OT_group_unassign(wmOperatorType *ot)
/* api callbacks */
ot->exec = pose_group_unassign_exec;
- ot->poll = ED_operator_posemode;
+ ot->poll = ED_operator_posemode_context;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1581,7 +1561,7 @@ void POSE_OT_group_unassign(wmOperatorType *ot)
static int group_move_exec(bContext *C, wmOperator *op)
{
- Object *ob = ED_object_context(C);
+ Object *ob = ED_pose_object_from_context(C);
bPose *pose = (ob) ? ob->pose : NULL;
bPoseChannel *pchan;
bActionGroup *grp;
@@ -1654,7 +1634,7 @@ void POSE_OT_group_move(wmOperatorType *ot)
/* api callbacks */
ot->exec = group_move_exec;
- ot->poll = ED_operator_posemode;
+ ot->poll = ED_operator_posemode_context;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1679,7 +1659,7 @@ static int compare_agroup(const void *sgrp_a_ptr, const void *sgrp_b_ptr)
static int group_sort_exec(bContext *C, wmOperator *UNUSED(op))
{
- Object *ob = ED_object_context(C);
+ Object *ob = ED_pose_object_from_context(C);
bPose *pose = (ob) ? ob->pose : NULL;
bPoseChannel *pchan;
tSortActionGroup *agrp_array;
@@ -1738,7 +1718,7 @@ void POSE_OT_group_sort(wmOperatorType *ot)
/* api callbacks */
ot->exec = group_sort_exec;
- ot->poll = ED_operator_posemode;
+ ot->poll = ED_operator_posemode_context;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1766,14 +1746,7 @@ static void pose_group_select(bContext *C, Object *ob, int select)
static int pose_group_select_exec(bContext *C, wmOperator *UNUSED(op))
{
- ScrArea *sa = CTX_wm_area(C);
- Object *ob;
-
- /* since this call may also be used from the buttons window, we need to check for where to get the object */
- if (sa->spacetype == SPACE_BUTS)
- ob = ED_object_context(C);
- else
- ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
+ Object *ob = ED_pose_object_from_context(C);
/* only continue if there's an object, and a pose there too */
if (ELEM(NULL, ob, ob->pose))
@@ -1796,7 +1769,7 @@ void POSE_OT_group_select(wmOperatorType *ot)
/* api callbacks */
ot->exec = pose_group_select_exec;
- ot->poll = ED_operator_posemode;
+ ot->poll = ED_operator_posemode_context;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1804,14 +1777,7 @@ void POSE_OT_group_select(wmOperatorType *ot)
static int pose_group_deselect_exec(bContext *C, wmOperator *UNUSED(op))
{
- ScrArea *sa = CTX_wm_area(C);
- Object *ob;
-
- /* since this call may also be used from the buttons window, we need to check for where to get the object */
- if (sa->spacetype == SPACE_BUTS)
- ob = ED_object_context(C);
- else
- ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
+ Object *ob = ED_pose_object_from_context(C);
/* only continue if there's an object, and a pose there too */
if (ELEM(NULL, ob, ob->pose))
@@ -1834,7 +1800,7 @@ void POSE_OT_group_deselect(wmOperatorType *ot)
/* api callbacks */
ot->exec = pose_group_deselect_exec;
- ot->poll = ED_operator_posemode;
+ ot->poll = ED_operator_posemode_context;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1950,7 +1916,7 @@ static int pose_bone_rotmode_exec(bContext *C, wmOperator *op)
Object *ob = CTX_data_active_object(C);
int mode = RNA_enum_get(op->ptr, "type");
- /* set rotation mode of selected bones */
+ /* set rotation mode of selected bones */
CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones)
{
pchan->rotmode = mode;
@@ -2134,7 +2100,7 @@ static int pose_bone_layers_invoke(bContext *C, wmOperator *op, wmEvent *evt)
{
int layers[32] = {0}; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */
- /* get layers that are active already */
+ /* get layers that are active already */
CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones)
{
short bit;
@@ -2333,10 +2299,10 @@ static int pose_clear_user_transforms_exec(bContext *C, wmOperator *op)
* just pose values should change, so this should be fine
*/
bPose *dummyPose = NULL;
- Object workob = {{0}};
+ Object workob = {{0}};
bPoseChannel *pchan;
- /* execute animation step for current frame using a dummy copy of the pose */
+ /* execute animation step for current frame using a dummy copy of the pose */
BKE_pose_copy_data(&dummyPose, ob->pose, 0);
BLI_strncpy(workob.id.name, "OB<ClearTfmWorkOb>", sizeof(workob.id.name));
diff --git a/source/blender/editors/armature/reeb.c b/source/blender/editors/armature/reeb.c
index 00f88a69fb6..b1bf13db69b 100644
--- a/source/blender/editors/armature/reeb.c
+++ b/source/blender/editors/armature/reeb.c
@@ -340,7 +340,7 @@ static ReebArc *copyArc(ReebGraph *rg, ReebArc *arc)
cp_arc->edges.first = NULL;
cp_arc->edges.last = NULL;
- /* copy buckets */
+ /* copy buckets */
cp_arc->buckets = MEM_callocN(sizeof(EmbedBucket) * cp_arc->bcount, "embed bucket");
memcpy(cp_arc->buckets, arc->buckets, sizeof(EmbedBucket) * cp_arc->bcount);
@@ -377,7 +377,7 @@ static ReebGraph *copyReebGraph(ReebGraph *rg, int level)
cp_rg->link_up = rg;
cp_rg->multi_level = level;
- /* Copy nodes */
+ /* Copy nodes */
for (node = rg->nodes.first; node; node = node->next)
{
ReebNode *cp_node = copyNode(cp_rg, node);
@@ -889,7 +889,7 @@ static void calculateArcLength(ReebArc *arc)
vec0 = vec1;
}
- arc->length += len_v3v3(arc->tail->p, vec1);
+ arc->length += len_v3v3(arc->tail->p, vec1);
}
static void calculateGraphLength(ReebGraph *rg)
@@ -948,7 +948,7 @@ void REEB_RadialSymmetry(BNode *root_node, RadialArc *ring, int count)
bucket1 = IT_next(iter1);
bucket2 = IT_next(iter2);
- /* Make sure they both start at the same value */
+ /* Make sure they both start at the same value */
while (bucket1 && bucket2 && bucket1->val < bucket2->val) {
bucket1 = IT_next(iter1);
}
@@ -1005,7 +1005,7 @@ void REEB_RadialSymmetry(BNode *root_node, RadialArc *ring, int count)
bucket1 = IT_next(iter1);
bucket2 = IT_next(iter2);
- /* Make sure they both start at the same value */
+ /* Make sure they both start at the same value */
while (bucket1 && bucket1->val < bucket2->val) {
bucket1 = IT_next(iter1);
}
@@ -1016,7 +1016,7 @@ void REEB_RadialSymmetry(BNode *root_node, RadialArc *ring, int count)
for (; bucket1 && bucket2; bucket1 = IT_next(iter1), bucket2 = IT_next(iter2)) {
- /* copy and mirror back to bucket2 */
+ /* copy and mirror back to bucket2 */
bucket2->nv = bucket1->nv;
copy_v3_v3(bucket2->p, bucket1->p);
BLI_mirrorAlongAxis(bucket2->p, node->p, normal);
@@ -1062,7 +1062,7 @@ void REEB_AxialSymmetry(BNode *root_node, BNode *node1, BNode *node2, struct BAr
bucket1 = IT_next(iter1);
bucket2 = IT_next(iter2);
- /* Make sure they both start at the same value */
+ /* Make sure they both start at the same value */
while (bucket1 && bucket1->val < bucket2->val) {
bucket1 = IT_next(iter1);
}
@@ -1080,7 +1080,7 @@ void REEB_AxialSymmetry(BNode *root_node, BNode *node1, BNode *node2, struct BAr
/* add bucket2 in bucket1 */
interp_v3_v3v3(bucket1->p, bucket1->p, bucket2->p, (float)bucket2->nv / (float)(bucket1->nv));
- /* copy and mirror back to bucket2 */
+ /* copy and mirror back to bucket2 */
bucket2->nv = bucket1->nv;
copy_v3_v3(bucket2->p, bucket1->p);
BLI_mirrorAlongAxis(bucket2->p, root_node->p, nor);
@@ -1212,7 +1212,7 @@ static void reweightArc(ReebGraph *rg, ReebArc *arc, ReebNode *start_node, float
reweightArc(rg, next_arc, node, end_weight);
}
- /* update only if needed */
+ /* update only if needed */
if (arc->head->weight != start_weight || arc->tail->weight != end_weight)
{
old_weight = arc->head->weight; /* backup head weight, other arcs need it intact, it will be fixed by the source arc */
@@ -1318,7 +1318,7 @@ static int joinSubgraphsEnds(ReebGraph *rg, float threshold, int nb_subgraphs)
}
joined = 1;
- }
+ }
}
return joined;
@@ -1450,7 +1450,7 @@ static void filterArc(ReebGraph *rg, ReebNode *newNode, ReebNode *removedNode, R
arc->tail = newNode;
}
- // Remove looped arcs
+ // Remove looped arcs
if (arc->head == arc->tail) {
// v1 or v2 was already newNode, since we're removing an arc, decrement degree
NodeDegreeDecrement(rg, newNode);
@@ -1648,7 +1648,7 @@ int filterSmartReebGraph(ReebGraph *UNUSED(rg), float UNUSED(threshold))
BLI_sortlist(&rg->arcs, compareArcs);
#ifdef DEBUG_REEB
- {
+ {
EditFace *efa;
for (efa = G.editMesh->faces.first; efa; efa = efa->next) {
efa->tmp.fp = -1;
@@ -1731,7 +1731,7 @@ int filterSmartReebGraph(ReebGraph *UNUSED(rg), float UNUSED(threshold))
efa->tmp.fp = saacos(fabs(angle));
#endif
#else
- add_v3_v3(avg_vec, efa->n);
+ add_v3_v3(avg_vec, efa->n);
#endif
}
@@ -1873,7 +1873,7 @@ static int compareVerts(const void *a, const void *b)
value = 1;
}
- return value;
+ return value;
}
static void spreadWeight(EditMesh *em)
@@ -1947,7 +1947,7 @@ void REEB_exportGraph(ReebGraph *rg, int count)
fprintf(f, "angle %0.3f %0.3f %0.3f %0.3f %i\n", p[0], p[1], p[2], arc->angle, BLI_ghash_size(arc->faces));
exportNode(f, "v2", arc->tail);
- }
+ }
fclose(f);
}
@@ -1983,7 +1983,7 @@ void removeNormalNodes(ReebGraph *rg)
/* If arcs are one after the other */
if (arc->head == connectedArc->tail) {
- /* remove furthest arc */
+ /* remove furthest arc */
if (arc->tail->weight < connectedArc->head->weight) {
mergeConnectedArcs(rg, arc, connectedArc);
nextArc = arc->next;
@@ -2006,7 +2006,7 @@ void removeNormalNodes(ReebGraph *rg)
/* If arcs are one after the other */
if (arc->tail == connectedArc->head) {
- /* remove furthest arc */
+ /* remove furthest arc */
if (arc->head->weight < connectedArc->tail->weight) {
mergeConnectedArcs(rg, arc, connectedArc);
nextArc = arc->next;
@@ -2092,7 +2092,7 @@ void mergeArcEdges(ReebGraph *rg, ReebArc *aDst, ReebArc *aSrc, MergeDirection d
newEdge->nextEdge = e;
- // if edge was the first in the list, point the edit edge to the new reeb edge instead.
+ // if edge was the first in the list, point the edit edge to the new reeb edge instead.
if (*p == e) {
*p = (void *)newEdge;
}
@@ -2289,12 +2289,12 @@ static ReebEdge *createArc(ReebGraph *rg, ReebNode *node1, ReebNode *node2)
arc->faces = BLI_ghash_ptr_new("createArc gh");
if (node1->weight <= node2->weight) {
- v1 = node1;
- v2 = node2;
+ v1 = node1;
+ v2 = node2;
}
else {
- v1 = node2;
- v2 = node1;
+ v1 = node2;
+ v2 = node1;
}
arc->head = v1;
@@ -2857,7 +2857,7 @@ int weightFromDistance(EditMesh *em, EdgeIndex *indexed_edges)
/* Apply dijkstra spf for each selected vert */
for (eve = em->verts.first; eve; eve = eve->next) {
if (eve->f & SELECT) {
- shortestPathsFromVert(em, eve, indexed_edges);
+ shortestPathsFromVert(em, eve, indexed_edges);
}
}
@@ -2927,7 +2927,7 @@ static void initIteratorFct(ReebArcIterator *iter)
iter->next = nextBucket;
iter->nextN = nextNBucket;
iter->previous = previousBucket;
- iter->stopped = iteratorStopped;
+ iter->stopped = iteratorStopped;
}
static void setIteratorValues(ReebArcIterator *iter, EmbedBucket *bucket)
@@ -3419,7 +3419,7 @@ void REEB_draw()
if (G.scene->toolsettings->skgen_options & SKGEN_DISP_EMBED)
{
- glColor3f(1, 1, 1);
+ glColor3f(1, 1, 1);
glBegin(GL_POINTS);
glVertex3fv(arc->head->p);
glVertex3fv(arc->tail->p);
diff --git a/source/blender/editors/armature/reeb.h b/source/blender/editors/armature/reeb.h
index bb8b3003baf..b0e1fd3ae34 100644
--- a/source/blender/editors/armature/reeb.h
+++ b/source/blender/editors/armature/reeb.h
@@ -114,7 +114,7 @@ typedef struct ReebArc {
int bcount;
struct EmbedBucket *buckets;
- struct GHash *faces;
+ struct GHash *faces;
float angle;
struct ReebArc *link_up; /* for multi resolution filtering, points to higher levels */
} ReebArc;
diff --git a/source/blender/editors/curve/editcurve.c b/source/blender/editors/curve/editcurve.c
index d780429784f..485d73974cd 100644
--- a/source/blender/editors/curve/editcurve.c
+++ b/source/blender/editors/curve/editcurve.c
@@ -162,9 +162,9 @@ static short select_beztriple(BezTriple *bezt, short selstatus, short flag, shor
bezt->f1 |= flag;
bezt->f2 |= flag;
bezt->f3 |= flag;
- return 1;
+ return 1;
}
- else { /* deselects */
+ else { /* deselects */
bezt->f1 &= ~flag;
bezt->f2 &= ~flag;
bezt->f3 &= ~flag;
@@ -1233,12 +1233,12 @@ void make_editNurb(Object *obedit)
set_actNurb(obedit, NULL);
if (ELEM(obedit->type, OB_CURVE, OB_SURF)) {
- actkey = ob_get_keyblock(obedit);
+ actkey = BKE_keyblock_from_object(obedit);
if (actkey) {
// XXX strcpy(G.editModeTitleExtra, "(Key) ");
undo_editmode_clear();
- key_to_curve(actkey, cu, &cu->nurb);
+ BKE_key_convert_to_curve(actkey, cu, &cu->nurb);
}
if (editnurb) {
@@ -1361,7 +1361,7 @@ static int separate_exec(bContext *C, wmOperator *op)
oldedit = oldcu->editnurb;
if (oldcu->key) {
- BKE_report(op->reports, RPT_ERROR, "Can't separate a curve with vertex keys");
+ BKE_report(op->reports, RPT_ERROR, "Cannot separate a curve with vertex keys");
return OPERATOR_CANCELLED;
}
@@ -1579,8 +1579,9 @@ static int deleteflagNurb(bContext *C, wmOperator *UNUSED(op), int flag)
BPoint *bp, *bpn, *newbp;
int a, b, newu, newv, sel;
- if (obedit->type == OB_SURF) ;
- else return OPERATOR_CANCELLED;
+ if (obedit->type != OB_SURF) {
+ return OPERATOR_CANCELLED;
+ }
cu->lastsel = NULL;
@@ -1593,8 +1594,12 @@ static int deleteflagNurb(bContext *C, wmOperator *UNUSED(op), int flag)
a = nu->pntsu * nu->pntsv;
while (a) {
a--;
- if (bp->f1 & flag) ;
- else break;
+ if (bp->f1 & flag) {
+ /* pass */
+ }
+ else {
+ break;
+ }
bp++;
}
if (a == 0) {
@@ -1715,8 +1720,12 @@ static short extrudeflagNurb(EditNurb *editnurb, int flag)
bp = nu->bp;
a = nu->pntsu;
while (a) {
- if (bp->f1 & flag) ;
- else break;
+ if (bp->f1 & flag) {
+ /* pass */
+ }
+ else {
+ break;
+ }
bp++;
a--;
}
@@ -2054,7 +2063,7 @@ static int set_goal_weight_exec(bContext *C, wmOperator *op)
bp->weight = weight;
}
}
- }
+ }
DAG_id_tag_update(obedit->data, 0);
WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
@@ -2106,7 +2115,7 @@ static int set_radius_exec(bContext *C, wmOperator *op)
bp->radius = radius;
}
}
- }
+ }
WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
DAG_id_tag_update(obedit->data, 0);
@@ -2399,7 +2408,7 @@ static void select_adjacent_cp(ListBase *editnurb, short next, short cont, short
for (nu = editnurb->first; nu; nu = nu->next) {
lastsel = 0;
- if (nu->type == CU_BEZIER) {
+ if (nu->type == CU_BEZIER) {
a = nu->pntsu;
bezt = nu->bezt;
if (next < 0) bezt = &nu->bezt[a - 1];
@@ -2416,7 +2425,7 @@ static void select_adjacent_cp(ListBase *editnurb, short next, short cont, short
bezt += next;
lastsel = 0;
}
- /* move around in zigzag way so that we go through each */
+ /* move around in zigzag way so that we go through each */
bezt -= (next - next / abs(next));
}
}
@@ -2431,7 +2440,7 @@ static void select_adjacent_cp(ListBase *editnurb, short next, short cont, short
if (!(bp->f1 & SELECT) || (selstatus == 0)) {
short sel = select_bpoint(bp, selstatus, 1, VISIBLE);
if ((sel == 1) && (cont == 0)) lastsel = 1;
- }
+ }
}
else {
bp += next;
@@ -2697,7 +2706,7 @@ static int hide_exec(bContext *C, wmOperator *op)
DAG_id_tag_update(obedit->data, 0);
WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
- return OPERATOR_FINISHED;
+ return OPERATOR_FINISHED;
}
void CURVE_OT_hide(wmOperatorType *ot)
@@ -2758,7 +2767,7 @@ static int reveal_exec(bContext *C, wmOperator *UNUSED(op))
DAG_id_tag_update(obedit->data, 0);
WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
- return OPERATOR_FINISHED;
+ return OPERATOR_FINISHED;
}
void CURVE_OT_reveal(wmOperatorType *ot)
@@ -3082,7 +3091,7 @@ static void subdividenurb(Object *obedit, int number_cuts)
nu->pntsv = (number_cuts + 1) * nu->pntsv - number_cuts;
BKE_nurb_knot_calc_u(nu);
BKE_nurb_knot_calc_v(nu);
- } /* End of 'if (sel == nu->pntsu*nu->pntsv)' (subdivide entire NURB) */
+ } /* End of 'if (sel == nu->pntsu * nu->pntsv)' (subdivide entire NURB) */
else {
/* subdivide in v direction? */
sel = 0;
@@ -3191,7 +3200,7 @@ static int subdivide_exec(bContext *C, wmOperator *op)
WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
DAG_id_tag_update(obedit->data, 0);
- return OPERATOR_FINISHED;
+ return OPERATOR_FINISHED;
}
void CURVE_OT_subdivide(wmOperatorType *ot)
@@ -3217,12 +3226,12 @@ void CURVE_OT_subdivide(wmOperatorType *ot)
/******************** find nearest ************************/
-static void findnearestNurbvert__doClosest(void *userData, Nurb *nu, BPoint *bp, BezTriple *bezt, int beztindex, int x, int y)
+static void findnearestNurbvert__doClosest(void *userData, Nurb *nu, BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
{
- struct { BPoint *bp; BezTriple *bezt; Nurb *nurb; int dist, hpoint, select, mval[2]; } *data = userData;
+ struct { BPoint *bp; BezTriple *bezt; Nurb *nurb; float dist; int hpoint, select; float mval_fl[2]; } *data = userData;
short flag;
- short temp;
+ float dist_test;
if (bp) {
flag = bp->f1;
@@ -3239,12 +3248,12 @@ static void findnearestNurbvert__doClosest(void *userData, Nurb *nu, BPoint *bp,
}
}
- temp = abs(data->mval[0] - x) + abs(data->mval[1] - y);
- if ((flag & 1) == data->select) temp += 5;
- if (bezt && beztindex == 1) temp += 3; /* middle points get a small disadvantage */
+ dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
+ if ((flag & SELECT) == data->select) dist_test += 5.0f;
+ if (bezt && beztindex == 1) dist_test += 3.0f; /* middle points get a small disadvantage */
- if (temp < data->dist) {
- data->dist = temp;
+ if (dist_test < data->dist) {
+ data->dist = dist_test;
data->bp = bp;
data->bezt = bezt;
@@ -3258,16 +3267,16 @@ static short findnearestNurbvert(ViewContext *vc, short sel, const int mval[2],
/* (sel == 1): selected gets a disadvantage */
/* in nurb and bezt or bp the nearest is written */
/* return 0 1 2: handlepunt */
- struct { BPoint *bp; BezTriple *bezt; Nurb *nurb; int dist, hpoint, select, mval[2]; } data = {NULL};
+ struct { BPoint *bp; BezTriple *bezt; Nurb *nurb; float dist; int hpoint, select; float mval_fl[2]; } data = {NULL};
data.dist = 100;
data.hpoint = 0;
data.select = sel;
- data.mval[0] = mval[0];
- data.mval[1] = mval[1];
+ data.mval_fl[0] = mval[0];
+ data.mval_fl[1] = mval[1];
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
- nurbs_foreachScreenVert(vc, findnearestNurbvert__doClosest, &data);
+ nurbs_foreachScreenVert(vc, findnearestNurbvert__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
*nurb = data.nurb;
*bezt = data.bezt;
@@ -3492,7 +3501,7 @@ static int set_spline_type_exec(bContext *C, wmOperator *op)
int changed = 0, type = RNA_enum_get(op->ptr, "type");
if (type == CU_CARDINAL || type == CU_BSPLINE) {
- BKE_report(op->reports, RPT_ERROR, "Not implemented yet");
+ BKE_report(op->reports, RPT_ERROR, "Not yet implemented");
return OPERATOR_CANCELLED;
}
@@ -3762,20 +3771,28 @@ static void merge_2_nurb(wmOperator *op, ListBase *editnurb, Nurb *nu1, Nurb *nu
/* first nurbs: u = resolu-1 selected */
- if (is_u_selected(nu1, nu1->pntsu - 1) ) ;
+ if (is_u_selected(nu1, nu1->pntsu - 1) ) {
+ /* pass */
+ }
else {
/* For 2D curves blender uses (orderv = 0). It doesn't make any sense mathematically. */
/* but after rotating (orderu = 0) will be confusing. */
if (nu1->orderv == 0) nu1->orderv = 1;
rotate_direction_nurb(nu1);
- if (is_u_selected(nu1, nu1->pntsu - 1)) ;
+ if (is_u_selected(nu1, nu1->pntsu - 1)) {
+ /* pass */
+ }
else {
rotate_direction_nurb(nu1);
- if (is_u_selected(nu1, nu1->pntsu - 1)) ;
+ if (is_u_selected(nu1, nu1->pntsu - 1)) {
+ /* pass */
+ }
else {
rotate_direction_nurb(nu1);
- if (is_u_selected(nu1, nu1->pntsu - 1)) ;
+ if (is_u_selected(nu1, nu1->pntsu - 1)) {
+ /* pass */
+ }
else {
/* rotate again, now its OK! */
if (nu1->pntsv != 1) rotate_direction_nurb(nu1);
@@ -3786,17 +3803,25 @@ static void merge_2_nurb(wmOperator *op, ListBase *editnurb, Nurb *nu1, Nurb *nu
}
/* 2nd nurbs: u = 0 selected */
- if (is_u_selected(nu2, 0) ) ;
+ if (is_u_selected(nu2, 0) ) {
+ /* pass */
+ }
else {
if (nu2->orderv == 0) nu2->orderv = 1;
rotate_direction_nurb(nu2);
- if (is_u_selected(nu2, 0)) ;
+ if (is_u_selected(nu2, 0)) {
+ /* pass */
+ }
else {
rotate_direction_nurb(nu2);
- if (is_u_selected(nu2, 0)) ;
+ if (is_u_selected(nu2, 0)) {
+ /* pass */
+ }
else {
rotate_direction_nurb(nu2);
- if (is_u_selected(nu2, 0)) ;
+ if (is_u_selected(nu2, 0)) {
+ /* pass */
+ }
else {
/* rotate again, now its OK! */
if (nu1->pntsu == 1) rotate_direction_nurb(nu1);
@@ -3808,7 +3833,7 @@ static void merge_2_nurb(wmOperator *op, ListBase *editnurb, Nurb *nu1, Nurb *nu
}
if (nu1->pntsv != nu2->pntsv) {
- BKE_report(op->reports, RPT_ERROR, "Resolution doesn't match");
+ BKE_report(op->reports, RPT_ERROR, "Resolution does not match");
return;
}
@@ -3892,21 +3917,33 @@ static int merge_nurb(bContext *C, wmOperator *op)
/* resolution match, to avoid uv rotations */
if (nus1->nu->pntsv == 1) {
- if (nus1->nu->pntsu == nus2->nu->pntsu || nus1->nu->pntsu == nus2->nu->pntsv) ;
- else ok = 0;
+ if (nus1->nu->pntsu == nus2->nu->pntsu || nus1->nu->pntsu == nus2->nu->pntsv) {
+ /* pass */
+ }
+ else {
+ ok = 0;
+ }
}
else if (nus2->nu->pntsv == 1) {
- if (nus2->nu->pntsu == nus1->nu->pntsu || nus2->nu->pntsu == nus1->nu->pntsv) ;
- else ok = 0;
+ if (nus2->nu->pntsu == nus1->nu->pntsu || nus2->nu->pntsu == nus1->nu->pntsv) {
+ /* pass */
+ }
+ else {
+ ok = 0;
+ }
+ }
+ else if (nus1->nu->pntsu == nus2->nu->pntsu || nus1->nu->pntsv == nus2->nu->pntsv) {
+ /* pass */
+ }
+ else if (nus1->nu->pntsu == nus2->nu->pntsv || nus1->nu->pntsv == nus2->nu->pntsu) {
+ /* pass */
}
- else if (nus1->nu->pntsu == nus2->nu->pntsu || nus1->nu->pntsv == nus2->nu->pntsv) ;
- else if (nus1->nu->pntsu == nus2->nu->pntsv || nus1->nu->pntsv == nus2->nu->pntsu) ;
else {
ok = 0;
}
if (ok == 0) {
- BKE_report(op->reports, RPT_ERROR, "Resolution doesn't match");
+ BKE_report(op->reports, RPT_ERROR, "Resolution does not match");
BLI_freelistN(&nsortbase);
return OPERATOR_CANCELLED;
}
@@ -3949,8 +3986,12 @@ static int make_segment_exec(bContext *C, wmOperator *op)
if (isNurbsel_count(cu, nu) == 1) {
/* only 1 selected, not first or last, a little complex, but intuitive */
if (nu->pntsv == 1) {
- if ( (nu->bp->f1 & SELECT) || (nu->bp[nu->pntsu - 1].f1 & SELECT)) ;
- else break;
+ if ( (nu->bp->f1 & SELECT) || (nu->bp[nu->pntsu - 1].f1 & SELECT)) {
+ /* pass */
+ }
+ else {
+ break;
+ }
}
}
}
@@ -4082,7 +4123,7 @@ static int make_segment_exec(bContext *C, wmOperator *op)
}
if (!ok) {
- BKE_report(op->reports, RPT_ERROR, "Can't make segment");
+ BKE_report(op->reports, RPT_ERROR, "Cannot make segment");
return OPERATOR_CANCELLED;
}
@@ -4335,7 +4376,7 @@ static int spin_exec(bContext *C, wmOperator *op)
unit_m4(viewmat);
if (!spin_nurb(viewmat, obedit, axis, cent)) {
- BKE_report(op->reports, RPT_ERROR, "Can't spin");
+ BKE_report(op->reports, RPT_ERROR, "Cannot spin");
return OPERATOR_CANCELLED;
}
@@ -4380,7 +4421,7 @@ void CURVE_OT_spin(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
RNA_def_float_vector_xyz(ot->srna, "center", 3, NULL, -FLT_MAX, FLT_MAX, "Center", "Center in global view space", -FLT_MAX, FLT_MAX);
- RNA_def_float_vector(ot->srna, "axis", 3, NULL, -1.0f, 1.0f, "Axis", "Axis in global view space", -FLT_MAX, FLT_MAX);
+ RNA_def_float_vector(ot->srna, "axis", 3, NULL, -FLT_MAX, FLT_MAX, "Axis", "Axis in global view space", -1.0f, 1.0f);
}
/***************** add vertex operator **********************/
@@ -5211,10 +5252,10 @@ static int select_more_exec(bContext *C, wmOperator *UNUSED(op))
tempbp = bp + 1;
if (!(tempbp->f1 & SELECT)) sel = select_bpoint(tempbp, SELECT, 1, VISIBLE);
if (sel) {
- bp++;
+ bp++;
a--;
}
- }
+ }
}
bp++;
@@ -5272,8 +5313,8 @@ static int select_less_exec(bContext *C, wmOperator *UNUSED(op))
if ((bp->hide == 0) && (bp->f1 & SELECT)) {
sel = 0;
- /* check if neighbors have been selected */
- /* edges of surface are an exception */
+ /* check if neighbors have been selected */
+ /* edges of surface are an exception */
if ((a + 1) % nu->pntsu == 0) sel++;
else {
bp--;
@@ -5305,7 +5346,7 @@ static int select_less_exec(bContext *C, wmOperator *UNUSED(op))
if (sel != 4) {
select_bpoint(bp, DESELECT, 1, VISIBLE);
selbpoints[a] = 1;
- }
+ }
}
else lastsel = 0;
@@ -5319,7 +5360,7 @@ static int select_less_exec(bContext *C, wmOperator *UNUSED(op))
for (nu = editnurb->first; nu; nu = nu->next) {
lastsel = 0;
/* check what type of curve/nurb it is */
- if (nu->type == CU_BEZIER) {
+ if (nu->type == CU_BEZIER) {
a = nu->pntsu;
bezt = nu->bezt;
while (a--) {
@@ -5327,10 +5368,10 @@ static int select_less_exec(bContext *C, wmOperator *UNUSED(op))
if (lastsel == 1) sel = 1;
else sel = 0;
- /* check if neighbors have been selected */
- /* first and last are exceptions */
+ /* check if neighbors have been selected */
+ /* first and last are exceptions */
if (a == nu->pntsu - 1) sel++;
- else {
+ else {
bezt--;
if ((bezt->hide == 0) && (bezt->f2 & SELECT)) sel++;
bezt++;
@@ -5344,14 +5385,14 @@ static int select_less_exec(bContext *C, wmOperator *UNUSED(op))
}
if (sel != 2) {
- select_beztriple(bezt, DESELECT, 1, VISIBLE);
+ select_beztriple(bezt, DESELECT, 1, VISIBLE);
lastsel = 1;
}
else lastsel = 0;
}
else lastsel = 0;
- bezt++;
+ bezt++;
}
}
else {
@@ -5362,9 +5403,9 @@ static int select_less_exec(bContext *C, wmOperator *UNUSED(op))
if (lastsel != 0) sel = 1;
else sel = 0;
- /* first and last are exceptions */
+ /* first and last are exceptions */
if (a == nu->pntsu * nu->pntsv - 1) sel++;
- else {
+ else {
bp--;
if ((bp->hide == 0) && (bp->f1 & SELECT)) sel++;
bp++;
@@ -5378,9 +5419,9 @@ static int select_less_exec(bContext *C, wmOperator *UNUSED(op))
}
if (sel != 2) {
- select_bpoint(bp, DESELECT, 1, VISIBLE);
+ select_bpoint(bp, DESELECT, 1, VISIBLE);
lastsel = 1;
- }
+ }
else lastsel = 0;
}
else lastsel = 0;
@@ -5441,7 +5482,7 @@ static void selectrandom_curve(ListBase *editnurb, float randfac)
select_bpoint(bp, SELECT, 1, VISIBLE);
bp++;
}
- }
+ }
}
}
@@ -5583,10 +5624,10 @@ static int select_nth_exec(bContext *C, wmOperator *op)
if (!CU_select_nth(obedit, nth)) {
if (obedit->type == OB_SURF) {
- BKE_report(op->reports, RPT_ERROR, "Surface hasn't got active point");
+ BKE_report(op->reports, RPT_ERROR, "Surface has not got active point");
}
else {
- BKE_report(op->reports, RPT_ERROR, "Curve hasn't got active point");
+ BKE_report(op->reports, RPT_ERROR, "Curve has not got active point");
}
return OPERATOR_CANCELLED;
@@ -5600,8 +5641,8 @@ static int select_nth_exec(bContext *C, wmOperator *op)
void CURVE_OT_select_nth(wmOperatorType *ot)
{
/* identifiers */
- ot->name = "Select Nth";
- ot->description = "";
+ ot->name = "Checker Deselect";
+ ot->description = "Deselect every other vertex";
ot->idname = "CURVE_OT_select_nth";
/* api callbacks */
@@ -5611,7 +5652,7 @@ void CURVE_OT_select_nth(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- RNA_def_int(ot->srna, "nth", 2, 2, 100, "Nth Selection", "", 1, INT_MAX);
+ RNA_def_int(ot->srna, "nth", 2, 2, INT_MAX, "Nth Selection", "", 2, 100);
}
/********************** add duplicate operator *********************/
@@ -5684,8 +5725,12 @@ static int delete_exec(bContext *C, wmOperator *op)
a = nu->pntsu;
if (a) {
while (a) {
- if (BEZSELECTED_HIDDENHANDLES(cu, bezt) ) ;
- else break;
+ if (BEZSELECTED_HIDDENHANDLES(cu, bezt)) {
+ /* pass */
+ }
+ else {
+ break;
+ }
a--;
bezt++;
}
@@ -5704,8 +5749,12 @@ static int delete_exec(bContext *C, wmOperator *op)
a = nu->pntsu * nu->pntsv;
if (a) {
while (a) {
- if (bp->f1 & SELECT) ;
- else break;
+ if (bp->f1 & SELECT) {
+ /* pass */
+ }
+ else {
+ break;
+ }
a--;
bp++;
}
@@ -6070,7 +6119,7 @@ void CURVE_OT_shade_flat(wmOperatorType *ot)
}
/************** join operator, to be used externally? ****************/
-
+/* TODO: shape keys - as with meshes */
int join_curve_exec(bContext *C, wmOperator *UNUSED(op))
{
Main *bmain = CTX_data_main(C);
@@ -6191,10 +6240,9 @@ static const char *get_surf_defname(int type)
}
-Nurb *add_nurbs_primitive(bContext *C, float mat[4][4], int type, int newob)
+Nurb *add_nurbs_primitive(bContext *C, Object *obedit, float mat[4][4], int type, int newob)
{
static int xzproj = 0; /* this function calls itself... */
- Object *obedit = CTX_data_edit_object(C);
ListBase *editnurb = object_editcurve_get(obedit);
View3D *v3d = CTX_wm_view3d(C);
RegionView3D *rv3d = ED_view3d_context_rv3d(C);
@@ -6431,19 +6479,14 @@ Nurb *add_nurbs_primitive(bContext *C, float mat[4][4], int type, int newob)
break;
case CU_PRIM_TUBE: /* Cylinder */
if (cutype == CU_NURBS) {
- nu = add_nurbs_primitive(C, mat, CU_NURBS | CU_PRIM_CIRCLE, 0); /* circle */
+ nu = add_nurbs_primitive(C, obedit, mat, CU_NURBS | CU_PRIM_CIRCLE, 0); /* circle */
nu->resolu = cu->resolu;
nu->flag = CU_SMOOTH;
BLI_addtail(editnurb, nu); /* temporal for extrude and translate */
vec[0] = vec[1] = 0.0;
vec[2] = -grid;
- if (newob && (U.flag & USER_ADD_VIEWALIGNED) == 0) {
- /* pass */
- }
- else {
- mul_mat3_m4_v3(mat, vec);
- }
+ mul_mat3_m4_v3(mat, vec);
translateflagNurb(editnurb, 1, vec);
extrudeflagNurb(cu->editnurb, 1);
@@ -6510,7 +6553,7 @@ Nurb *add_nurbs_primitive(bContext *C, float mat[4][4], int type, int newob)
float tmp_vec[3] = {0.f, 0.f, 1.f};
xzproj = 1;
- nu = add_nurbs_primitive(C, mat, CU_NURBS | CU_PRIM_CIRCLE, 0); /* circle */
+ nu = add_nurbs_primitive(C, obedit, mat, CU_NURBS | CU_PRIM_CIRCLE, 0); /* circle */
xzproj = 0;
nu->resolu = cu->resolu;
nu->resolv = cu->resolv;
@@ -6568,29 +6611,28 @@ static int curvesurf_prim_add(bContext *C, wmOperator *op, int type, int isSurf)
if (!isSurf) { /* adding curve */
if (obedit == NULL || obedit->type != OB_CURVE) {
Curve *cu;
-
+
obedit = ED_object_add_type(C, OB_CURVE, loc, rot, TRUE, layer);
newob = 1;
cu = (Curve *)obedit->data;
cu->flag |= CU_DEFORM_FILL;
-
+
if (type & CU_PRIM_PATH)
cu->flag |= CU_PATH | CU_3D;
- }
+ }
else DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
- }
+ }
else { /* adding surface */
if (obedit == NULL || obedit->type != OB_SURF) {
obedit = ED_object_add_type(C, OB_SURF, loc, rot, TRUE, layer);
newob = 1;
- }
+ }
else DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
}
/* rename here, the undo stack checks name for valid undo pushes */
if (newob) {
-
if (obedit->type == OB_CURVE) {
rename_id((ID *)obedit, get_curve_defname(type));
rename_id((ID *)obedit->data, get_curve_defname(type));
@@ -6600,14 +6642,14 @@ static int curvesurf_prim_add(bContext *C, wmOperator *op, int type, int isSurf)
rename_id((ID *)obedit->data, get_surf_defname(type));
}
}
-
+
/* ED_object_add_type doesnt do an undo, is needed for redo operator on primitive */
if (newob && enter_editmode)
ED_undo_push(C, "Enter Editmode");
-
- ED_object_new_primitive_matrix(C, obedit, loc, rot, mat);
- nu = add_nurbs_primitive(C, mat, type, newob);
+ ED_object_new_primitive_matrix(C, obedit, loc, rot, mat, TRUE);
+
+ nu = add_nurbs_primitive(C, obedit, mat, type, newob);
editnurb = object_editcurve_get(obedit);
BLI_addtail(editnurb, nu);
@@ -6644,12 +6686,11 @@ void CURVE_OT_primitive_bezier_curve_add(wmOperatorType *ot)
ot->name = "Add Bezier";
ot->description = "Construct a Bezier Curve";
ot->idname = "CURVE_OT_primitive_bezier_curve_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_bezier_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -6667,12 +6708,11 @@ void CURVE_OT_primitive_bezier_circle_add(wmOperatorType *ot)
ot->name = "Add Bezier Circle";
ot->description = "Construct a Bezier Circle";
ot->idname = "CURVE_OT_primitive_bezier_circle_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_bezier_circle_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -6690,12 +6730,11 @@ void CURVE_OT_primitive_nurbs_curve_add(wmOperatorType *ot)
ot->name = "Add Nurbs Curve";
ot->description = "Construct a Nurbs Curve";
ot->idname = "CURVE_OT_primitive_nurbs_curve_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_nurbs_curve_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -6713,12 +6752,11 @@ void CURVE_OT_primitive_nurbs_circle_add(wmOperatorType *ot)
ot->name = "Add Nurbs Circle";
ot->description = "Construct a Nurbs Circle";
ot->idname = "CURVE_OT_primitive_nurbs_circle_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_nurbs_circle_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -6736,12 +6774,11 @@ void CURVE_OT_primitive_nurbs_path_add(wmOperatorType *ot)
ot->name = "Add Path";
ot->description = "Construct a Path";
ot->idname = "CURVE_OT_primitive_nurbs_path_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_curve_path_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -6760,12 +6797,11 @@ void SURFACE_OT_primitive_nurbs_surface_curve_add(wmOperatorType *ot)
ot->name = "Add Surface Curve";
ot->description = "Construct a Nurbs surface Curve";
ot->idname = "SURFACE_OT_primitive_nurbs_surface_curve_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_nurbs_surface_curve_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -6783,12 +6819,11 @@ void SURFACE_OT_primitive_nurbs_surface_circle_add(wmOperatorType *ot)
ot->name = "Add Surface Circle";
ot->description = "Construct a Nurbs surface Circle";
ot->idname = "SURFACE_OT_primitive_nurbs_surface_circle_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_nurbs_surface_circle_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -6806,12 +6841,11 @@ void SURFACE_OT_primitive_nurbs_surface_surface_add(wmOperatorType *ot)
ot->name = "Add Surface Patch";
ot->description = "Construct a Nurbs surface Patch";
ot->idname = "SURFACE_OT_primitive_nurbs_surface_surface_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_nurbs_surface_surface_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -6829,12 +6863,11 @@ void SURFACE_OT_primitive_nurbs_surface_cylinder_add(wmOperatorType *ot)
ot->name = "Add Surface Cylinder";
ot->description = "Construct a Nurbs surface Cylinder";
ot->idname = "SURFACE_OT_primitive_nurbs_surface_cylinder_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_nurbs_surface_cylinder_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -6852,12 +6885,11 @@ void SURFACE_OT_primitive_nurbs_surface_sphere_add(wmOperatorType *ot)
ot->name = "Add Surface Sphere";
ot->description = "Construct a Nurbs surface Sphere";
ot->idname = "SURFACE_OT_primitive_nurbs_surface_sphere_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_nurbs_surface_sphere_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -6875,12 +6907,11 @@ void SURFACE_OT_primitive_nurbs_surface_torus_add(wmOperatorType *ot)
ot->name = "Add Surface Torus";
ot->description = "Construct a Nurbs surface Torus";
ot->idname = "SURFACE_OT_primitive_nurbs_surface_torus_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_nurbs_surface_torus_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
diff --git a/source/blender/editors/curve/editfont.c b/source/blender/editors/curve/editfont.c
index b11d640256c..fd87e6752f2 100644
--- a/source/blender/editors/curve/editfont.c
+++ b/source/blender/editors/curve/editfont.c
@@ -94,7 +94,8 @@ static char findaccent(char char1, unsigned int code)
}
else if (char1 == 'c') {
if (code == ',') new = 231;
- if (code == '|') new = 162;
+ else if (code == '|') new = 162;
+ else if (code == 'o') new = 169;
}
else if (char1 == 'e') {
if (code == '`') new = 232;
@@ -120,10 +121,18 @@ static char findaccent(char char1, unsigned int code)
else if (code == '/') new = 248;
else if (code == '-') new = 186;
else if (code == 'e') new = 143;
+ else if (code == 'c') new = 169;
+ else if (code == 'r') new = 174;
+ }
+ else if (char1 == 'r') {
+ if (code == 'o') new = 174;
}
else if (char1 == 's') {
if (code == 's') new = 167;
}
+ else if (char1 == 't') {
+ if (code == 'm') new = 153;
+ }
else if (char1 == 'u') {
if (code == '`') new = 249;
else if (code == 39) new = 250;
@@ -310,7 +319,7 @@ static int insert_lorem_exec(bContext *C, wmOperator *UNUSED(op))
lastlorem = ED_lorem;
insert_into_textbuf(obedit, '\n');
- insert_into_textbuf(obedit, '\n');
+ insert_into_textbuf(obedit, '\n');
DAG_id_tag_update(obedit->data, 0);
WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
@@ -441,8 +450,9 @@ static void txt_add_object(bContext *C, TextLine *firstline, int totline, float
obedit = BKE_object_add(scene, OB_FONT);
base = scene->basact;
-
- ED_object_base_init_transform(C, base, NULL, rot); /* seems to assume view align ? TODO - look into this, could be an operator option */
+ /* seems to assume view align ? TODO - look into this, could be an operator option */
+ ED_object_base_init_transform(C, base, NULL, rot);
+
BKE_object_where_is_calc(scene, obedit);
obedit->loc[0] += offset[0];
@@ -457,7 +467,7 @@ static void txt_add_object(bContext *C, TextLine *firstline, int totline, float
nchars += strlen(tmp->line) + 1;
if (cu->str) MEM_freeN(cu->str);
- if (cu->strinfo) MEM_freeN(cu->strinfo);
+ if (cu->strinfo) MEM_freeN(cu->strinfo);
cu->str = MEM_callocN(nchars + 4, "str");
cu->strinfo = MEM_callocN((nchars + 4) * sizeof(CharInfo), "strinfo");
@@ -756,7 +766,7 @@ static int paste_selection(Object *obedit, ReportList *reports)
/* Verify that the copy buffer => [copy buffer len] + cu->len < MAXTEXT */
if (cu->len + len <= MAXTEXT) {
- if (len) {
+ if (len) {
int size = (cu->len * sizeof(wchar_t)) - (cu->pos * sizeof(wchar_t)) + sizeof(wchar_t);
memmove(ef->textbuf + cu->pos + len, ef->textbuf + cu->pos, size);
memcpy(ef->textbuf + cu->pos, ef->copybuf, len * sizeof(wchar_t));
@@ -834,7 +844,7 @@ static int move_cursor(bContext *C, int type, int select)
if (ef->textbuf[cu->pos - 1] == '\n') break;
if (ef->textbufinfo[cu->pos - 1].flag & CU_CHINFO_WRAP) break;
cu->pos--;
- }
+ }
cursmove = FO_CURS;
break;
@@ -867,7 +877,7 @@ static int move_cursor(bContext *C, int type, int select)
cursmove = FO_CURS;
break;
- case NEXT_CHAR:
+ case NEXT_CHAR:
if ((select) && (cu->selstart == 0)) cu->selstart = cu->selend = cu->pos + 1;
cu->pos++;
cursmove = FO_CURS;
@@ -1250,8 +1260,12 @@ static int insert_text_invoke(bContext *C, wmOperator *op, wmEvent *evt)
else
ascii = 9;
}
- else if (event == BACKSPACEKEY)
- ascii = 0;
+
+ if (event == BACKSPACEKEY) {
+ if (alt && cu->len != 0 && cu->pos > 0)
+ accentcode = 1;
+ return OPERATOR_PASS_THROUGH;
+ }
if (val && (ascii || evt->utf8_buf[0])) {
/* handle case like TAB (== 9) */
@@ -1262,44 +1276,18 @@ static int insert_text_invoke(bContext *C, wmOperator *op, wmEvent *evt)
(evt->utf8_buf[0]))
{
- if (evt->utf8_buf[0]) {
- BLI_strncpy_wchar_from_utf8(inserted_text, evt->utf8_buf, 1);
- ascii = inserted_text[0];
- insert_into_textbuf(obedit, ascii);
- accentcode = 0;
- }
- else if (accentcode) {
+ if (accentcode) {
if (cu->pos > 0) {
inserted_text[0] = findaccent(ef->textbuf[cu->pos - 1], ascii);
ef->textbuf[cu->pos - 1] = inserted_text[0];
}
accentcode = 0;
}
- else if (cu->len < MAXTEXT - 1) {
- if (alt) {
- /* might become obsolete, apple has default values for this, other OS's too? */
- if (ascii == 't') ascii = 137;
- else if (ascii == 'c') ascii = 169;
- else if (ascii == 'f') ascii = 164;
- else if (ascii == 'g') ascii = 176;
- else if (ascii == 'l') ascii = 163;
- else if (ascii == 'r') ascii = 174;
- else if (ascii == 's') ascii = 223;
- else if (ascii == 'y') ascii = 165;
- else if (ascii == '.') ascii = 138;
- else if (ascii == '1') ascii = 185;
- else if (ascii == '2') ascii = 178;
- else if (ascii == '3') ascii = 179;
- else if (ascii == '%') ascii = 139;
- else if (ascii == '?') ascii = 191;
- else if (ascii == '!') ascii = 161;
- else if (ascii == 'x') ascii = 215;
- else if (ascii == '>') ascii = 187;
- else if (ascii == '<') ascii = 171;
- }
-
- inserted_text[0] = ascii;
+ else if (evt->utf8_buf[0]) {
+ BLI_strncpy_wchar_from_utf8(inserted_text, evt->utf8_buf, 1);
+ ascii = inserted_text[0];
insert_into_textbuf(obedit, ascii);
+ accentcode = 0;
}
kill_selection(obedit, 1);
@@ -1311,12 +1299,6 @@ static int insert_text_invoke(bContext *C, wmOperator *op, wmEvent *evt)
text_update_edited(C, scene, obedit, 1, FO_EDIT);
}
}
- else if (val && event == BACKSPACEKEY) {
- if (alt && cu->len != 0 && cu->pos > 0)
- accentcode = 1;
-
- return OPERATOR_PASS_THROUGH;
- }
else
return OPERATOR_PASS_THROUGH;
@@ -1329,7 +1311,8 @@ static int insert_text_invoke(bContext *C, wmOperator *op, wmEvent *evt)
}
/* reset property? */
- accentcode = 0;
+ if (val == 0)
+ accentcode = 0;
return OPERATOR_FINISHED;
}
diff --git a/source/blender/editors/gpencil/drawgpencil.c b/source/blender/editors/gpencil/drawgpencil.c
index 5a94d54f329..11e07584405 100644
--- a/source/blender/editors/gpencil/drawgpencil.c
+++ b/source/blender/editors/gpencil/drawgpencil.c
@@ -98,8 +98,8 @@ static void gp_draw_stroke_buffer(tGPspoint *points, int totpoints, short thickn
if (dflag & (GP_DRAWDATA_ONLY3D | GP_DRAWDATA_ONLYV2D))
return;
- /* if drawing a single point, draw it larger */
- if (totpoints == 1) {
+ /* if drawing a single point, draw it larger */
+ if (totpoints == 1) {
/* draw point */
glBegin(GL_POINTS);
glVertex2iv(&points->x);
@@ -149,7 +149,8 @@ static void gp_draw_stroke_buffer(tGPspoint *points, int totpoints, short thickn
/* ----- Existing Strokes Drawing (3D and Point) ------ */
/* draw a given stroke - just a single dot (only one point) */
-static void gp_draw_stroke_point(bGPDspoint *points, short thickness, short dflag, short sflag, int offsx, int offsy, int winx, int winy)
+static void gp_draw_stroke_point(bGPDspoint *points, short thickness, short dflag, short sflag,
+ int offsx, int offsy, int winx, int winy)
{
/* draw point */
if (sflag & GP_STROKE_3DSPACE) {
@@ -314,7 +315,7 @@ static void gp_draw_stroke(bGPDspoint *points, int totpoints, short thickness_s,
s0[1] = (pt1->y / 100 * winy) + offsy;
s1[0] = (pt2->x / 100 * winx) + offsx;
s1[1] = (pt2->y / 100 * winy) + offsy;
- }
+ }
/* calculate gradient and normal - 'angle'=(ny/nx) */
m1[1] = s1[1] - s0[1];
@@ -330,7 +331,7 @@ static void gp_draw_stroke(bGPDspoint *points, int totpoints, short thickness_s,
if (i == 0) {
/* draw start cap first
* - make points slightly closer to center (about halfway across)
- */
+ */
mt[0] = m2[0] * pthick * 0.5f;
mt[1] = m2[1] * pthick * 0.5f;
sc[0] = s0[0] - (m1[0] * pthick * 0.75f);
@@ -381,7 +382,7 @@ static void gp_draw_stroke(bGPDspoint *points, int totpoints, short thickness_s,
if (((athick * 2.0f) < pthick) && (IS_EQF(athick, pthick) == 0)) {
mt[0] += (mb[0] * dfac);
mt[1] += (mb[1] * dfac);
- }
+ }
/* calculate points for start of segment */
t0[0] = s0[0] - mt[0];
@@ -419,7 +420,7 @@ static void gp_draw_stroke(bGPDspoint *points, int totpoints, short thickness_s,
/* draw end cap as last step
* - make points slightly closer to center (about halfway across)
- */
+ */
mt[0] = m2[0] * pthick * 0.5f;
mt[1] = m2[1] * pthick * 0.5f;
sc[0] = s1[0] + (m1[0] * pthick * 0.75f);
@@ -508,7 +509,8 @@ static void gp_draw_strokes(bGPDframe *gpf, int offsx, int offsy, int winx, int
glDepthMask(0);
glEnable(GL_DEPTH_TEST);
- /* first arg is normally rv3d->dist, but this isn't available here and seems to work quite well without */
+ /* first arg is normally rv3d->dist, but this isn't
+ * available here and seems to work quite well without */
bglPolygonOffset(1.0f, 1.0f);
#if 0
glEnable(GL_POLYGON_OFFSET_LINE);
@@ -529,7 +531,7 @@ static void gp_draw_strokes(bGPDframe *gpf, int offsx, int offsy, int winx, int
#endif
}
}
- else if (gps->totpoints > 1)
+ else if (gps->totpoints > 1)
gp_draw_stroke(gps->points, gps->totpoints, lthick, dflag, gps->flag, debug, offsx, offsy, winx, winy);
}
}
@@ -579,7 +581,8 @@ static void gp_draw_data(bGPdata *gpd, int offsx, int offsy, int winx, int winy,
/* draw 'onionskins' (frame left + right) */
if (gpl->flag & GP_LAYER_ONIONSKIN) {
- /* drawing method - only immediately surrounding (gstep = 0), or within a frame range on either side (gstep > 0)*/
+ /* drawing method - only immediately surrounding (gstep = 0),
+ * or within a frame range on either side (gstep > 0)*/
if (gpl->gstep) {
bGPDframe *gf;
float fac;
@@ -608,7 +611,7 @@ static void gp_draw_data(bGPdata *gpd, int offsx, int offsy, int winx, int winy,
}
else
break;
- }
+ }
/* restore alpha */
glColor4fv(color);
@@ -640,7 +643,8 @@ static void gp_draw_data(bGPdata *gpd, int offsx, int offsy, int winx, int winy,
if (ED_gpencil_session_active() && (gpl->flag & GP_LAYER_ACTIVE) &&
(gpf->flag & GP_FRAME_PAINT))
{
- /* Buffer stroke needs to be drawn with a different linestyle to help differentiate them from normal strokes. */
+ /* Buffer stroke needs to be drawn with a different linestyle
+ * to help differentiate them from normal strokes. */
gp_draw_stroke_buffer(gpd->sbuffer, gpd->sbuffer_size, lthick, dflag, gpd->sbuffer_sflag);
}
}
@@ -657,11 +661,11 @@ static void gp_draw_data(bGPdata *gpd, int offsx, int offsy, int winx, int winy,
/* ----- Grease Pencil Sketches Drawing API ------ */
-// ............................
-// XXX
-// We need to review the calls below, since they may be/are not that suitable for
-// the new ways that we intend to be drawing data...
-// ............................
+/* ............................
+ * XXX
+ * We need to review the calls below, since they may be/are not that suitable for
+ * the new ways that we intend to be drawing data...
+ * ............................ */
/* draw grease-pencil sketches to specified 2d-view that uses ibuf corrections */
void draw_gpencil_2dimage(const bContext *C)
@@ -724,8 +728,8 @@ void draw_gpencil_2dimage(const bContext *C)
}
/* draw grease-pencil sketches to specified 2d-view assuming that matrices are already set correctly
- * Note: this gets called twice - first time with onlyv2d=1 to draw 'canvas' strokes, second time with onlyv2d=0 for screen-aligned strokes
- */
+ * Note: this gets called twice - first time with onlyv2d=1 to draw 'canvas' strokes,
+ * second time with onlyv2d=0 for screen-aligned strokes */
void draw_gpencil_view2d(const bContext *C, short onlyv2d)
{
ScrArea *sa = CTX_wm_area(C);
@@ -750,15 +754,14 @@ void draw_gpencil_view2d(const bContext *C, short onlyv2d)
}
/* draw grease-pencil sketches to specified 3d-view assuming that matrices are already set correctly
- * Note: this gets called twice - first time with only3d=1 to draw 3d-strokes, second time with only3d=0 for screen-aligned strokes
- */
-
+ * Note: this gets called twice - first time with only3d=1 to draw 3d-strokes,
+ * second time with only3d=0 for screen-aligned strokes */
void draw_gpencil_view3d(Scene *scene, View3D *v3d, ARegion *ar, short only3d)
{
bGPdata *gpd;
int dflag = 0;
- rcti rect;
RegionView3D *rv3d = ar->regiondata;
+ int offsx, offsy, winx, winy;
/* check that we have grease-pencil stuff to draw */
gpd = gpencil_data_get_active_v3d(scene); // XXX
@@ -769,19 +772,23 @@ void draw_gpencil_view3d(Scene *scene, View3D *v3d, ARegion *ar, short only3d)
if ((rv3d->persp == RV3D_CAMOB) && !(G.f & G_RENDER_OGL)) {
rctf rectf;
ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &rectf, TRUE); /* no shift */
- BLI_rcti_rctf_copy(&rect, &rectf);
+
+ offsx = floorf(rectf.xmin + 0.5f);
+ offsy = floorf(rectf.ymin + 0.5f);
+ winx = floorf((rectf.xmax - rectf.xmin) + 0.5f);
+ winy = floorf((rectf.ymax - rectf.ymin) + 0.5f);
}
else {
- rect.xmin = 0;
- rect.ymin = 0;
- rect.xmax = ar->winx;
- rect.ymax = ar->winy;
+ offsx = 0;
+ offsy = 0;
+ winx = ar->winx;
+ winy = ar->winy;
}
/* draw it! */
if (only3d) dflag |= (GP_DRAWDATA_ONLY3D | GP_DRAWDATA_NOSTATUS);
- gp_draw_data(gpd, rect.xmin, rect.ymin, rect.xmax, rect.ymax, CFRA, dflag);
+ gp_draw_data(gpd, offsx, offsy, winx, winy, CFRA, dflag);
}
/* ************************************************** */
diff --git a/source/blender/editors/gpencil/editaction_gpencil.c b/source/blender/editors/gpencil/editaction_gpencil.c
index b69db0040b5..a59a3f7a5ec 100644
--- a/source/blender/editors/gpencil/editaction_gpencil.c
+++ b/source/blender/editors/gpencil/editaction_gpencil.c
@@ -393,7 +393,7 @@ void paste_gpdata(Scene *scene)
ScrArea *sa;
/* get area that gp-data comes from */
- //sa= gpencil_data_findowner((bGPdata *)ale->owner);
+ //sa = gpencil_data_findowner((bGPdata *)ale->owner);
sa = NULL;
/* this should be the right frame... as it may be a pre-existing frame,
diff --git a/source/blender/editors/gpencil/gpencil_buttons.c b/source/blender/editors/gpencil/gpencil_buttons.c
index d90ec02b0c1..8a3c996a481 100644
--- a/source/blender/editors/gpencil/gpencil_buttons.c
+++ b/source/blender/editors/gpencil/gpencil_buttons.c
@@ -75,17 +75,15 @@ static void gp_ui_activelayer_cb(bContext *C, void *gpd, void *gpl)
/* make sure the layer we want to remove is the active one */
gpencil_layer_setactive(gpd, gpl);
- WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL); /* XXX please work! */
+ WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
}
/* delete 'active' layer */
static void gp_ui_dellayer_cb(bContext *C, void *gpd, void *gpl)
{
- /* make sure the layer we want to remove is the active one */
- gpencil_layer_setactive(gpd, gpl);
- gpencil_layer_delactive(gpd);
+ gpencil_layer_delete((bGPdata *)gpd, (bGPDlayer *)gpl);
- WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL); /* XXX please work! */
+ WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
}
diff --git a/source/blender/editors/gpencil/gpencil_edit.c b/source/blender/editors/gpencil/gpencil_edit.c
index 5d67b63af18..ed8a1ea8280 100644
--- a/source/blender/editors/gpencil/gpencil_edit.c
+++ b/source/blender/editors/gpencil/gpencil_edit.c
@@ -212,7 +212,7 @@ static int gp_data_add_exec(bContext *C, wmOperator *op)
bGPdata **gpd_ptr = gpencil_data_get_pointers(C, NULL);
if (gpd_ptr == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Nowhere for Grease Pencil data to go");
+ BKE_report(op->reports, RPT_ERROR, "Nowhere for grease pencil data to go");
return OPERATOR_CANCELLED;
}
else {
@@ -224,7 +224,7 @@ static int gp_data_add_exec(bContext *C, wmOperator *op)
}
/* notifiers */
- WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL); // XXX need a nicer one that will work
+ WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
return OPERATOR_FINISHED;
}
@@ -260,7 +260,7 @@ static int gp_data_unlink_exec(bContext *C, wmOperator *op)
bGPdata **gpd_ptr = gpencil_data_get_pointers(C, NULL);
if (gpd_ptr == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Nowhere for Grease Pencil data to go");
+ BKE_report(op->reports, RPT_ERROR, "Nowhere for grease pencil data to go");
return OPERATOR_CANCELLED;
}
else {
@@ -272,7 +272,7 @@ static int gp_data_unlink_exec(bContext *C, wmOperator *op)
}
/* notifiers */
- WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL); // XXX need a nicer one that will work
+ WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
return OPERATOR_FINISHED;
}
@@ -299,17 +299,17 @@ static int gp_layer_add_exec(bContext *C, wmOperator *op)
/* if there's no existing Grease-Pencil data there, add some */
if (gpd_ptr == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Nowhere for Grease Pencil data to go");
+ BKE_report(op->reports, RPT_ERROR, "Nowhere for grease pencil data to go");
return OPERATOR_CANCELLED;
}
if (*gpd_ptr == NULL)
*gpd_ptr = gpencil_data_addnew("GPencil");
/* add new layer now */
- gpencil_layer_addnew(*gpd_ptr);
+ gpencil_layer_addnew(*gpd_ptr, "GP_Layer", 1);
/* notifiers */
- WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL); // XXX please work!
+ WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
return OPERATOR_FINISHED;
}
@@ -348,7 +348,7 @@ static int gp_actframe_delete_exec(bContext *C, wmOperator *op)
/* if there's no existing Grease-Pencil data there, add some */
if (gpd == NULL) {
- BKE_report(op->reports, RPT_ERROR, "No Grease Pencil data");
+ BKE_report(op->reports, RPT_ERROR, "No grease pencil data");
return OPERATOR_CANCELLED;
}
if (ELEM(NULL, gpl, gpf)) {
@@ -360,7 +360,7 @@ static int gp_actframe_delete_exec(bContext *C, wmOperator *op)
gpencil_layer_delframe(gpl, gpf);
/* notifiers */
- WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL); // XXX please work!
+ WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
return OPERATOR_FINISHED;
}
@@ -422,8 +422,8 @@ static void gp_strokepoint_convertcoords(bContext *C, bGPDstroke *gps, bGPDspoin
}
else {
if (subrect) {
- mvalf[0] = (((float)pt->x / 100.0f) * BLI_RCT_SIZE_X(subrect)) + subrect->xmin;
- mvalf[1] = (((float)pt->y / 100.0f) * BLI_RCT_SIZE_Y(subrect)) + subrect->ymin;
+ mvalf[0] = (((float)pt->x / 100.0f) * BLI_rctf_size_x(subrect)) + subrect->xmin;
+ mvalf[1] = (((float)pt->y / 100.0f) * BLI_rctf_size_y(subrect)) + subrect->ymin;
}
else {
mvalf[0] = (float)pt->x / 100.0f * ar->winx;
@@ -634,7 +634,7 @@ static int gp_convert_layer_exec(bContext *C, wmOperator *op)
/* check if there's data to work with */
if (gpd == NULL) {
- BKE_report(op->reports, RPT_ERROR, "No Grease Pencil data to work on");
+ BKE_report(op->reports, RPT_ERROR, "No grease pencil data to work on");
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/gpencil/gpencil_paint.c b/source/blender/editors/gpencil/gpencil_paint.c
index 4e281b96fc3..9bfd89075af 100644
--- a/source/blender/editors/gpencil/gpencil_paint.c
+++ b/source/blender/editors/gpencil/gpencil_paint.c
@@ -278,11 +278,15 @@ static void gp_stroke_convertcoords(tGPsdata *p, const int mval[2], float out[3]
gp_get_3d_reference(p, rvec);
/* method taken from editview.c - mouse_cursor() */
- project_int_noclip(p->ar, rvec, mval_prj);
-
- VECSUB2D(mval_f, mval_prj, mval);
- ED_view3d_win_to_delta(p->ar, mval_f, dvec);
- sub_v3_v3v3(out, rvec, dvec);
+ /* TODO, use ED_view3d_project_float_global */
+ if (ED_view3d_project_int_global(p->ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ VECSUB2D(mval_f, mval_prj, mval);
+ ED_view3d_win_to_delta(p->ar, mval_f, dvec);
+ sub_v3_v3v3(out, rvec, dvec);
+ }
+ else {
+ zero_v3(out);
+ }
}
}
@@ -299,8 +303,8 @@ static void gp_stroke_convertcoords(tGPsdata *p, const int mval[2], float out[3]
out[1] = (float)(mval[1]) / (float)(p->ar->winy) * 100;
}
else { /* camera view, use subrect */
- out[0] = ((mval[0] - p->subrect->xmin) / BLI_RCT_SIZE_X(p->subrect)) * 100;
- out[1] = ((mval[1] - p->subrect->ymin) / BLI_RCT_SIZE_Y(p->subrect)) * 100;
+ out[0] = ((mval[0] - p->subrect->xmin) / BLI_rctf_size_x(p->subrect)) * 100;
+ out[1] = ((mval[1] - p->subrect->ymin) / BLI_rctf_size_y(p->subrect)) * 100;
}
}
}
@@ -391,8 +395,10 @@ static short gp_stroke_addpoint(tGPsdata *p, const int mval[2], float pressure)
pts = &gps->points[gps->totpoints - 1];
- /* special case for poly lines: normally, depth is needed only when creating new stroke from buffer,
- * but poly lines are converting to stroke instantly, so initialize depth buffer before converting coordinates
+ /* special case for poly lines: normally,
+ * depth is needed only when creating new stroke from buffer,
+ * but poly lines are converting to stroke instantly,
+ * so initialize depth buffer before converting coordinates
*/
if (gpencil_project_check(p)) {
View3D *v3d = p->sa->spacedata.first;
@@ -530,7 +536,7 @@ static void gp_stroke_simplify(tGPsdata *p)
j += 2;
}
- }
+ }
/* free old buffer */
MEM_freeN(old_points);
@@ -781,13 +787,49 @@ static short gp_stroke_eraser_strokeinside(const int mval[], const int UNUSED(mv
int rad, int x0, int y0, int x1, int y1)
{
/* simple within-radius check for now */
- if (edge_inside_circle(mval[0], mval[1], rad, x0, y0, x1, y1))
- return 1;
+ const float mval_fl[2] = {mval[0], mval[1]};
+ const float screen_co_a[2] = {x0, y0};
+ const float screen_co_b[2] = {x1, y1};
+
+ if (edge_inside_circle(mval_fl, rad, screen_co_a, screen_co_b)) {
+ return TRUE;
+ }
/* not inside */
- return 0;
+ return FALSE;
}
+static void gp_point_to_xy(ARegion *ar, View2D *v2d, rctf *subrect, bGPDstroke *gps, bGPDspoint *pt,
+ int *r_x, int *r_y)
+{
+ int xyval[2];
+
+ if (gps->flag & GP_STROKE_3DSPACE) {
+ if (ED_view3d_project_int_global(ar, &pt->x, xyval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ *r_x = xyval[0];
+ *r_y = xyval[1];
+ }
+ else {
+ *r_x = V2D_IS_CLIPPED;
+ *r_y = V2D_IS_CLIPPED;
+ }
+ }
+ else if (gps->flag & GP_STROKE_2DSPACE) {
+ UI_view2d_view_to_region(v2d, pt->x, pt->y, r_x, r_y);
+ }
+ else {
+ if (subrect == NULL) { /* normal 3D view */
+ *r_x = (int)(pt->x / 100 * ar->winx);
+ *r_y = (int)(pt->y / 100 * ar->winy);
+ }
+ else { /* camera view, use subrect */
+ *r_x = (int)((pt->x / 100) * BLI_rctf_size_x(subrect)) + subrect->xmin;
+ *r_y = (int)((pt->y / 100) * BLI_rctf_size_y(subrect)) + subrect->ymin;
+ }
+ }
+}
+
+
/* eraser tool - evaluation per stroke */
// TODO: this could really do with some optimization (KD-Tree/BVH?)
static void gp_stroke_eraser_dostroke(tGPsdata *p,
@@ -796,7 +838,6 @@ static void gp_stroke_eraser_dostroke(tGPsdata *p,
{
bGPDspoint *pt1, *pt2;
int x0 = 0, y0 = 0, x1 = 0, y1 = 0;
- int xyval[2];
int i;
if (gps->totpoints == 0) {
@@ -806,28 +847,11 @@ static void gp_stroke_eraser_dostroke(tGPsdata *p,
BLI_freelinkN(&gpf->strokes, gps);
}
else if (gps->totpoints == 1) {
- /* get coordinates */
- if (gps->flag & GP_STROKE_3DSPACE) {
- project_int(p->ar, &gps->points->x, xyval);
- x0 = xyval[0];
- y0 = xyval[1];
- }
- else if (gps->flag & GP_STROKE_2DSPACE) {
- UI_view2d_view_to_region(p->v2d, gps->points->x, gps->points->y, &x0, &y0);
- }
- else {
- if (p->subrect == NULL) { /* normal 3D view */
- x0 = (int)(gps->points->x / 100 * p->ar->winx);
- y0 = (int)(gps->points->y / 100 * p->ar->winy);
- }
- else { /* camera view, use subrect */
- x0 = (int)((gps->points->x / 100) * BLI_RCT_SIZE_X(p->subrect)) + p->subrect->xmin;
- y0 = (int)((gps->points->y / 100) * BLI_RCT_SIZE_Y(p->subrect)) + p->subrect->ymin;
- }
- }
+ gp_point_to_xy(p->ar, p->v2d, p->subrect, gps, gps->points, &x0, &y0);
/* do boundbox check first */
- if (BLI_rcti_isect_pt(rect, x0, y0)) {
+
+ if ((!ELEM(V2D_IS_CLIPPED, x0, y0)) && BLI_rcti_isect_pt(rect, x0, y0)) {
/* only check if point is inside */
if (((x0 - mval[0]) * (x0 - mval[0]) + (y0 - mval[1]) * (y0 - mval[1])) <= rad * rad) {
/* free stroke */
@@ -836,7 +860,7 @@ static void gp_stroke_eraser_dostroke(tGPsdata *p,
}
}
}
- else {
+ else {
/* loop over the points in the stroke, checking for intersections
* - an intersection will require the stroke to be split
*/
@@ -844,39 +868,13 @@ static void gp_stroke_eraser_dostroke(tGPsdata *p,
/* get points to work with */
pt1 = gps->points + i;
pt2 = gps->points + i + 1;
-
- /* get coordinates */
- if (gps->flag & GP_STROKE_3DSPACE) {
- project_int(p->ar, &pt1->x, xyval);
- x0 = xyval[0];
- y0 = xyval[1];
-
- project_int(p->ar, &pt2->x, xyval);
- x1 = xyval[0];
- y1 = xyval[1];
- }
- else if (gps->flag & GP_STROKE_2DSPACE) {
- UI_view2d_view_to_region(p->v2d, pt1->x, pt1->y, &x0, &y0);
-
- UI_view2d_view_to_region(p->v2d, pt2->x, pt2->y, &x1, &y1);
- }
- else {
- if (p->subrect == NULL) { /* normal 3D view */
- x0 = (int)(pt1->x / 100 * p->ar->winx);
- y0 = (int)(pt1->y / 100 * p->ar->winy);
- x1 = (int)(pt2->x / 100 * p->ar->winx);
- y1 = (int)(pt2->y / 100 * p->ar->winy);
- }
- else { /* camera view, use subrect */
- x0 = (int)((pt1->x / 100) * BLI_RCT_SIZE_X(p->subrect)) + p->subrect->xmin;
- y0 = (int)((pt1->y / 100) * BLI_RCT_SIZE_Y(p->subrect)) + p->subrect->ymin;
- x1 = (int)((pt2->x / 100) * BLI_RCT_SIZE_X(p->subrect)) + p->subrect->xmin;
- y1 = (int)((pt2->y / 100) * BLI_RCT_SIZE_Y(p->subrect)) + p->subrect->ymin;
- }
- }
-
+
+ gp_point_to_xy(p->ar, p->v2d, p->subrect, gps, pt1, &x0, &y0);
+ gp_point_to_xy(p->ar, p->v2d, p->subrect, gps, pt2, &x1, &y1);
+
/* check that point segment of the boundbox of the eraser stroke */
- if (BLI_rcti_isect_pt(rect, x0, y0) || BLI_rcti_isect_pt(rect, x1, y1)) {
+ if (((!ELEM(V2D_IS_CLIPPED, x0, y0)) && BLI_rcti_isect_pt(rect, x0, y0)) ||
+ ((!ELEM(V2D_IS_CLIPPED, x1, y1)) && BLI_rcti_isect_pt(rect, x1, y1))) {
/* check if point segment of stroke had anything to do with
* eraser region (either within stroke painted, or on its lines)
* - this assumes that linewidth is irrelevant
@@ -961,8 +959,8 @@ static int gp_session_initdata(bContext *C, tGPsdata *p)
/* supported views first */
case SPACE_VIEW3D:
{
- // View3D *v3d= curarea->spacedata.first;
- // RegionView3D *rv3d= ar->regiondata;
+ // View3D *v3d = curarea->spacedata.first;
+ // RegionView3D *rv3d = ar->regiondata;
/* set current area
* - must verify that region data is 3D-view (and not something else)
@@ -981,7 +979,7 @@ static int gp_session_initdata(bContext *C, tGPsdata *p)
case SPACE_NODE:
{
- //SpaceNode *snode= curarea->spacedata.first;
+ //SpaceNode *snode = curarea->spacedata.first;
/* set current area */
p->sa = curarea;
@@ -1009,7 +1007,7 @@ static int gp_session_initdata(bContext *C, tGPsdata *p)
break;
case SPACE_IMAGE:
{
- //SpaceImage *sima= curarea->spacedata.first;
+ //SpaceImage *sima = curarea->spacedata.first;
/* set the current area */
p->sa = curarea;
@@ -1125,7 +1123,7 @@ static void gp_paint_initstroke(tGPsdata *p, short paintmode)
/* get active layer (or add a new one if non-existent) */
p->gpl = gpencil_layer_getactive(p->gpd);
if (p->gpl == NULL) {
- p->gpl = gpencil_layer_addnew(p->gpd);
+ p->gpl = gpencil_layer_addnew(p->gpd, "GP_Layer", 1);
if (p->custom_color[3])
copy_v3_v3(p->gpl->color, p->custom_color);
@@ -1212,7 +1210,7 @@ static void gp_paint_initstroke(tGPsdata *p, short paintmode)
/* make strokes be drawn in screen space */
p->gpd->sbuffer_sflag &= ~GP_STROKE_2DSPACE;
p->gpd->flag &= ~GP_DATA_VIEWALIGN;
- }
+ }
else
p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
}
@@ -1344,7 +1342,7 @@ static void gpencil_draw_exit(bContext *C, wmOperator *op)
gp_session_cleanup(p);
/* finally, free the temp data */
- MEM_freeN(p);
+ MEM_freeN(p);
}
op->customdata = NULL;
@@ -1405,13 +1403,17 @@ static void gpencil_draw_status_indicators(tGPsdata *p)
/* print status info */
switch (p->paintmode) {
case GP_PAINTMODE_ERASER:
- ED_area_headerprint(p->sa, "Grease Pencil Erase Session: Hold and drag LMB or RMB to erase | ESC/Enter to end");
+ ED_area_headerprint(p->sa,
+ "Grease Pencil Erase Session: Hold and drag LMB or RMB to erase |"
+ " ESC/Enter to end");
break;
case GP_PAINTMODE_DRAW_STRAIGHT:
- ED_area_headerprint(p->sa, "Grease Pencil Line Session: Hold and drag LMB to draw | ESC/Enter to end");
+ ED_area_headerprint(p->sa, "Grease Pencil Line Session: Hold and drag LMB to draw | "
+ "ESC/Enter to end");
break;
case GP_PAINTMODE_DRAW:
- ED_area_headerprint(p->sa, "Grease Pencil Freehand Session: Hold and drag LMB to draw | ESC/Enter to end");
+ ED_area_headerprint(p->sa, "Grease Pencil Freehand Session: Hold and drag LMB to draw | "
+ "ESC/Enter to end");
break;
default: /* unhandled future cases */
@@ -1598,7 +1600,7 @@ static int gpencil_draw_exec(bContext *C, wmOperator *op)
gpencil_draw_exit(C, op);
/* refreshes */
- WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL); // XXX need a nicer one that will work
+ WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
/* done */
return OPERATOR_FINISHED;
@@ -1646,7 +1648,7 @@ static int gpencil_draw_invoke(bContext *C, wmOperator *op, wmEvent *event)
* painting should start immediately. Otherwise, this was called from a toolbar, in which
* case we should wait for the mouse to be clicked.
*/
- if (event->type) {
+ if (event->val == KM_PRESS) {
/* hotkey invoked - start drawing */
//printf("\tGP - set first spot\n");
p->status = GP_STATUS_PAINTING;
@@ -1659,7 +1661,7 @@ static int gpencil_draw_invoke(bContext *C, wmOperator *op, wmEvent *event)
//printf("\tGP - hotkey invoked... waiting for click-drag\n");
}
- WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL, NULL);
+ WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
/* add a modal handler for this operator, so that we can then draw continuous strokes */
WM_event_add_modal_handler(C, op);
return OPERATOR_RUNNING_MODAL;
@@ -1687,7 +1689,8 @@ static tGPsdata *gpencil_stroke_begin(bContext *C, wmOperator *op)
//printf("\t\tGP - start stroke\n");
/* we may need to set up paint env again if we're resuming */
- /* XXX: watch it with the paintmode! in future, it'd be nice to allow changing paint-mode when in sketching-sessions */
+ /* XXX: watch it with the paintmode! in future,
+ * it'd be nice to allow changing paint-mode when in sketching-sessions */
/* XXX: with tablet events, we may event want to check for eraser here, for nicer tablet support */
if (gp_session_initdata(C, p))
@@ -1720,7 +1723,7 @@ static void gpencil_stroke_end(wmOperator *op)
static int gpencil_draw_modal(bContext *C, wmOperator *op, wmEvent *event)
{
tGPsdata *p = op->customdata;
- int estate = OPERATOR_PASS_THROUGH; /* default exit state - not handled, so let others have a share of the pie */
+ int estate = OPERATOR_RUNNING_MODAL; /* default exit state - we don't pass on events, GP is used with key-modifiers */
/* if (event->type == NDOF_MOTION)
* return OPERATOR_PASS_THROUGH;
@@ -1736,25 +1739,32 @@ static int gpencil_draw_modal(bContext *C, wmOperator *op, wmEvent *event)
//printf("\tGP - handle modal event...\n");
- /* exit painting mode (and/or end current stroke) */
- if (ELEM5(event->type, RETKEY, PADENTER, ESCKEY, SPACEKEY, RIGHTMOUSE)) {
+ /* exit painting mode (and/or end current stroke)
+ * NOTE: cannot do RIGHTMOUSE (as is standard for cancelling) as that would break polyline [#32647]
+ */
+ if (ELEM4(event->type, RETKEY, PADENTER, ESCKEY, SPACEKEY)) {
/* exit() ends the current stroke before cleaning up */
//printf("\t\tGP - end of paint op + end of stroke\n");
p->status = GP_STATUS_DONE;
estate = OPERATOR_FINISHED;
}
- /* toggle painting mode upon mouse-button movement */
- if (event->type == LEFTMOUSE) {
+ /* toggle painting mode upon mouse-button movement
+ * - LEFTMOUSE = standard drawing (all) / straight line drawing (all) / polyline (toolbox only)
+ * - RIGHTMOUSE = polyline (hotkey) / eraser (all)
+ * (Disabling RIGHTMOUSE case here results in bugs like [#32647])
+ */
+ if (ELEM(event->type, LEFTMOUSE, RIGHTMOUSE)) {
/* if painting, end stroke */
if (p->status == GP_STATUS_PAINTING) {
int sketch = 0;
+
/* basically, this should be mouse-button up = end stroke
* BUT what happens next depends on whether we 'painting sessions' is enabled
*/
sketch |= GPENCIL_SKETCH_SESSIONS_ON(p->scene);
/* polyline drawing is also 'sketching' -- all knots should be added during one session */
- sketch |= p->paintmode == GP_PAINTMODE_DRAW_POLY;
+ sketch |= (p->paintmode == GP_PAINTMODE_DRAW_POLY);
if (sketch) {
/* end stroke only, and then wait to resume painting soon */
@@ -1765,7 +1775,7 @@ static int gpencil_draw_modal(bContext *C, wmOperator *op, wmEvent *event)
estate = OPERATOR_RUNNING_MODAL;
/* stroke could be smoothed, send notifier to refresh screen */
- WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL);
+ WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
}
else {
//printf("\t\tGP - end of stroke + op\n");
@@ -1780,7 +1790,7 @@ static int gpencil_draw_modal(bContext *C, wmOperator *op, wmEvent *event)
if (p->status == GP_STATUS_ERROR) {
estate = OPERATOR_CANCELLED;
}
- }
+ }
else {
p->status = GP_STATUS_IDLING;
}
@@ -1855,7 +1865,7 @@ static int gpencil_draw_modal(bContext *C, wmOperator *op, wmEvent *event)
case OPERATOR_FINISHED:
/* one last flush before we're done */
gpencil_draw_exit(C, op);
- WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL); // XXX need a nicer one that will work
+ WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
break;
case OPERATOR_CANCELLED:
@@ -1864,7 +1874,10 @@ static int gpencil_draw_modal(bContext *C, wmOperator *op, wmEvent *event)
case OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH:
/* event doesn't need to be handled */
- //printf("unhandled event -> %d (mmb? = %d | mmv? = %d)\n", event->type, event->type == MIDDLEMOUSE, event->type==MOUSEMOVE);
+#if 0
+ printf("unhandled event -> %d (mmb? = %d | mmv? = %d)\n",
+ event->type, event->type == MIDDLEMOUSE, event->type==MOUSEMOVE);
+#endif
break;
}
@@ -1875,10 +1888,10 @@ static int gpencil_draw_modal(bContext *C, wmOperator *op, wmEvent *event)
/* ------------------------------- */
static EnumPropertyItem prop_gpencil_drawmodes[] = {
- {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", ""},
- {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", ""},
- {GP_PAINTMODE_DRAW_POLY, "DRAW_POLY", 0, "Draw Poly Line", ""},
- {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", ""},
+ {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", "Draw freehand stroke(s)"},
+ {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", "Draw straight line segment(s)"},
+ {GP_PAINTMODE_DRAW_POLY, "DRAW_POLY", 0, "Draw Poly Line", "Click to place endpoints of straight line segments (connected)"},
+ {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", "Erase Grease Pencil strokes"},
{0, NULL, 0, NULL, NULL}
};
@@ -1900,7 +1913,7 @@ void GPENCIL_OT_draw(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
/* settings for drawing */
- RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to interpret mouse movements");
+ ot->prop = RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to interpret mouse movements");
RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
}
diff --git a/source/blender/editors/gpencil/gpencil_undo.c b/source/blender/editors/gpencil/gpencil_undo.c
index fa9f5196866..3d2cd260fb9 100644
--- a/source/blender/editors/gpencil/gpencil_undo.c
+++ b/source/blender/editors/gpencil/gpencil_undo.c
@@ -111,7 +111,7 @@ int ED_undo_gpencil_step(bContext *C, int step, const char *name)
}
}
- WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL);
+ WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
return OPERATOR_FINISHED;
}
diff --git a/source/blender/editors/include/ED_anim_api.h b/source/blender/editors/include/ED_anim_api.h
index e1401a8ff88..8d7ae3aad6a 100644
--- a/source/blender/editors/include/ED_anim_api.h
+++ b/source/blender/editors/include/ED_anim_api.h
@@ -232,28 +232,28 @@ typedef enum eAnimFilter_Flags {
/* Dopesheet only */
/* 'Scene' channels */
-#define SEL_SCEC(sce) ((sce->flag & SCE_DS_SELECTED))
-#define EXPANDED_SCEC(sce) ((sce->flag & SCE_DS_COLLAPSED) == 0)
+#define SEL_SCEC(sce) (CHECK_TYPE_INLINE(sce, Scene), ((sce->flag & SCE_DS_SELECTED)))
+#define EXPANDED_SCEC(sce) (CHECK_TYPE_INLINE(sce, Scene), ((sce->flag & SCE_DS_COLLAPSED) == 0))
/* 'Sub-Scene' channels (flags stored in Data block) */
-#define FILTER_WOR_SCED(wo) ((wo->flag & WO_DS_EXPAND))
+#define FILTER_WOR_SCED(wo) (CHECK_TYPE_INLINE(wo, World), (wo->flag & WO_DS_EXPAND))
/* 'Object' channels */
-#define SEL_OBJC(base) ((base->flag & SELECT))
-#define EXPANDED_OBJC(ob) ((ob->nlaflag & OB_ADS_COLLAPSED) == 0)
+#define SEL_OBJC(base) (CHECK_TYPE_INLINE(base, Base), ((base->flag & SELECT)))
+#define EXPANDED_OBJC(ob) (CHECK_TYPE_INLINE(ob, Object), ((ob->nlaflag & OB_ADS_COLLAPSED) == 0))
/* 'Sub-object' channels (flags stored in Data block) */
-#define FILTER_SKE_OBJD(key) ((key->flag & KEY_DS_EXPAND))
-#define FILTER_MAT_OBJD(ma) ((ma->flag & MA_DS_EXPAND))
-#define FILTER_LAM_OBJD(la) ((la->flag & LA_DS_EXPAND))
-#define FILTER_CAM_OBJD(ca) ((ca->flag & CAM_DS_EXPAND))
-#define FILTER_CUR_OBJD(cu) ((cu->flag & CU_DS_EXPAND))
-#define FILTER_PART_OBJD(part) ((part->flag & PART_DS_EXPAND))
-#define FILTER_MBALL_OBJD(mb) ((mb->flag2 & MB_DS_EXPAND))
-#define FILTER_ARM_OBJD(arm) ((arm->flag & ARM_DS_EXPAND))
-#define FILTER_MESH_OBJD(me) ((me->flag & ME_DS_EXPAND))
-#define FILTER_LATTICE_OBJD(lt) ((lt->flag & LT_DS_EXPAND))
-#define FILTER_SPK_OBJD(spk) ((spk->flag & SPK_DS_EXPAND))
+#define FILTER_SKE_OBJD(key) (CHECK_TYPE_INLINE(key, Key), ((key->flag & KEY_DS_EXPAND)))
+#define FILTER_MAT_OBJD(ma) (CHECK_TYPE_INLINE(ma, Material), ((ma->flag & MA_DS_EXPAND)))
+#define FILTER_LAM_OBJD(la) (CHECK_TYPE_INLINE(la, Lamp), ((la->flag & LA_DS_EXPAND)))
+#define FILTER_CAM_OBJD(ca) (CHECK_TYPE_INLINE(ca, Camera), ((ca->flag & CAM_DS_EXPAND)))
+#define FILTER_CUR_OBJD(cu) (CHECK_TYPE_INLINE(cu, Curve), ((cu->flag & CU_DS_EXPAND)))
+#define FILTER_PART_OBJD(part) (CHECK_TYPE_INLINE(part, ParticleSettings), ((part->flag & PART_DS_EXPAND)))
+#define FILTER_MBALL_OBJD(mb) (CHECK_TYPE_INLINE(mb, MetaBall), ((mb->flag2 & MB_DS_EXPAND)))
+#define FILTER_ARM_OBJD(arm) (CHECK_TYPE_INLINE(arm, bArmature), ((arm->flag & ARM_DS_EXPAND)))
+#define FILTER_MESH_OBJD(me) (CHECK_TYPE_INLINE(me, Mesh), ((me->flag & ME_DS_EXPAND)))
+#define FILTER_LATTICE_OBJD(lt) (CHECK_TYPE_INLINE(lt, Lattice), ((lt->flag & LT_DS_EXPAND)))
+#define FILTER_SPK_OBJD(spk) (CHECK_TYPE_INLINE(spk, Speaker), ((spk->flag & SPK_DS_EXPAND)))
/* Variable use expanders */
-#define FILTER_NTREE_DATA(ntree) ((ntree->flag & NTREE_DS_EXPAND))
-#define FILTER_TEX_DATA(tex) ((tex->flag & TEX_DS_EXPAND))
+#define FILTER_NTREE_DATA(ntree) (CHECK_TYPE_INLINE(ntree, bNodeTree), ((ntree->flag & NTREE_DS_EXPAND)))
+#define FILTER_TEX_DATA(tex) (CHECK_TYPE_INLINE(tex, Tex), ((tex->flag & TEX_DS_EXPAND)))
/* 'Sub-object/Action' channels (flags stored in Action) */
#define SEL_ACTC(actc) ((actc->flag & ACT_SELECTED))
diff --git a/source/blender/editors/include/ED_armature.h b/source/blender/editors/include/ED_armature.h
index 07f3498580c..efd10f3cb6b 100644
--- a/source/blender/editors/include/ED_armature.h
+++ b/source/blender/editors/include/ED_armature.h
@@ -93,8 +93,18 @@ typedef struct EditBone {
#define BONESEL_NOSEL (1 << 31) /* Indicates a negative number */
/* useful macros */
-#define EBONE_VISIBLE(arm, ebone) (((arm)->layer & (ebone)->layer) && !((ebone)->flag & BONE_HIDDEN_A))
-#define EBONE_EDITABLE(ebone) (((ebone)->flag & BONE_SELECTED) && !((ebone)->flag & BONE_EDITMODE_LOCKED))
+#define EBONE_VISIBLE(arm, ebone) ( \
+ CHECK_TYPE_INLINE(arm, bArmature), \
+ CHECK_TYPE_INLINE(ebone, EditBone), \
+ (((arm)->layer & (ebone)->layer) && !((ebone)->flag & BONE_HIDDEN_A)) \
+ )
+
+#define EBONE_SELECTABLE(arm, ebone) (EBONE_VISIBLE(arm, ebone) && !(ebone->flag & BONE_UNSELECTABLE))
+
+#define EBONE_EDITABLE(ebone) ( \
+ CHECK_TYPE_INLINE(ebone, EditBone), \
+ (((ebone)->flag & BONE_SELECTED) && !((ebone)->flag & BONE_EDITMODE_LOCKED)) \
+ )
/* used in bone_select_hierachy() */
#define BONE_SELECT_PARENT 0
@@ -148,6 +158,7 @@ void ED_armature_enter_posemode(struct bContext *C, struct Base *base);
int ED_pose_channel_in_IK_chain(struct Object *ob, struct bPoseChannel *pchan);
void ED_pose_deselectall(struct Object *ob, int test);
void ED_pose_recalculate_paths(struct Scene *scene, struct Object *ob);
+struct Object *ED_pose_object_from_context(struct bContext *C);
/* sketch */
diff --git a/source/blender/editors/include/ED_curve.h b/source/blender/editors/include/ED_curve.h
index ac8d82e9060..d66cc49a5d0 100644
--- a/source/blender/editors/include/ED_curve.h
+++ b/source/blender/editors/include/ED_curve.h
@@ -67,7 +67,7 @@ void BKE_curve_editNurb_free(struct Curve *cu);
int mouse_nurb(struct bContext *C, const int mval[2], int extend, int deselect, int toggle);
-struct Nurb *add_nurbs_primitive(struct bContext *C, float mat[4][4], int type, int newob);
+struct Nurb *add_nurbs_primitive(struct bContext *C, struct Object *obedit, float mat[4][4], int type, int newob);
int isNurbsel(struct Nurb *nu);
void ED_nurb_set_spline_type(struct Nurb *nu, int type);
diff --git a/source/blender/editors/include/ED_keyframes_draw.h b/source/blender/editors/include/ED_keyframes_draw.h
index 8a65699f404..ffee46e30c6 100644
--- a/source/blender/editors/include/ED_keyframes_draw.h
+++ b/source/blender/editors/include/ED_keyframes_draw.h
@@ -157,4 +157,3 @@ short compare_ab_cfraPtr(void *node, void *data);
short actkeyblock_is_valid(ActKeyBlock *ab, struct DLRBT_Tree *keys);
#endif /* __ED_KEYFRAMES_DRAW_H__ */
-
diff --git a/source/blender/editors/include/ED_mask.h b/source/blender/editors/include/ED_mask.h
index dc40b687dfd..46ed9798d32 100644
--- a/source/blender/editors/include/ED_mask.h
+++ b/source/blender/editors/include/ED_mask.h
@@ -88,8 +88,8 @@ void free_gpcopybuf(void);
void copy_gpdata(void);
void paste_gpdata(void);
- void snap_masklayer_frames(struct MaskLayer *masklay, short mode);
- void mirror_masklayer_frames(struct MaskLayer *masklay, short mode);
+void snap_masklayer_frames(struct MaskLayer *masklay, short mode);
+void mirror_masklayer_frames(struct MaskLayer *masklay, short mode);
#endif
#endif /* __ED_MASK_H__ */
diff --git a/source/blender/editors/include/ED_mball.h b/source/blender/editors/include/ED_mball.h
index b4b739e4d06..1321765588d 100644
--- a/source/blender/editors/include/ED_mball.h
+++ b/source/blender/editors/include/ED_mball.h
@@ -38,7 +38,7 @@ struct wmKeyConfig;
void ED_operatortypes_metaball(void);
void ED_keymap_metaball(struct wmKeyConfig *keyconf);
-struct MetaElem *add_metaball_primitive(struct bContext *C, float mat[4][4], int type, int newname);
+struct MetaElem *add_metaball_primitive(struct bContext *C, struct Object *obedit, float mat[4][4], float dia, int type, int newname);
int mouse_mball(struct bContext *C, const int mval[2], int extend, int deselect, int toggle);
diff --git a/source/blender/editors/include/ED_mesh.h b/source/blender/editors/include/ED_mesh.h
index 1d4fbe81e02..5ffcfbd94f0 100644
--- a/source/blender/editors/include/ED_mesh.h
+++ b/source/blender/editors/include/ED_mesh.h
@@ -61,6 +61,7 @@ struct BMEditMesh;
struct BMEditSelection;
struct BMesh;
struct BMVert;
+struct BMLoop;
struct MLoopCol;
struct BMEdge;
struct BMFace;
@@ -79,6 +80,7 @@ struct BMVert *EDBM_verts_mirror_get(struct BMEditMesh *em, struct BMVert *v);
void EDBM_verts_mirror_cache_clear(struct BMEditMesh *em, struct BMVert *v);
void EDBM_verts_mirror_cache_end(struct BMEditMesh *em);
+void EDBM_mesh_ensure_valid_dm_hack(struct Scene *scene, struct BMEditMesh *em);
void EDBM_mesh_normals_update(struct BMEditMesh *em);
void EDBM_mesh_clear(struct BMEditMesh *em);
@@ -117,6 +119,7 @@ void EDBM_update_generic(struct bContext *C, struct BMEditMesh *em, const short
struct UvElementMap *EDBM_uv_element_map_create(struct BMEditMesh *em, int selected, int doIslands);
void EDBM_uv_element_map_free(struct UvElementMap *vmap);
+struct UvElement *ED_uv_element_get(struct UvElementMap *map, struct BMFace *efa, struct BMLoop *l);
int EDBM_mtexpoly_check(struct BMEditMesh *em);
struct MTexPoly *EDBM_mtexpoly_active_get(struct BMEditMesh *em, struct BMFace **r_act_efa, int sloppy, int selected);
@@ -137,18 +140,18 @@ int EDBM_backbuf_border_init(struct ViewContext *vc, short xmin, short ymin, sh
int EDBM_backbuf_check(unsigned int index);
void EDBM_backbuf_free(void);
-int EDBM_backbuf_border_mask_init(struct ViewContext *vc, int mcords[][2], short tot,
+int EDBM_backbuf_border_mask_init(struct ViewContext *vc, const int mcords[][2], short tot,
short xmin, short ymin, short xmax, short ymax);
int EDBM_backbuf_circle_init(struct ViewContext *vc, short xs, short ys, short rads);
-struct BMVert *EDBM_vert_find_nearest(struct ViewContext *vc, int *dist, short sel, short strict);
-struct BMEdge *EDBM_edge_find_nearest(struct ViewContext *vc, int *dist);
-struct BMFace *EDBM_face_find_nearest(struct ViewContext *vc, int *dist);
+struct BMVert *EDBM_vert_find_nearest(struct ViewContext *vc, float *r_dist, const short sel, const short strict);
+struct BMEdge *EDBM_edge_find_nearest(struct ViewContext *vc, float *r_dist);
+struct BMFace *EDBM_face_find_nearest(struct ViewContext *vc, float *r_dist);
int EDBM_select_pick(struct bContext *C, const int mval[2], short extend, short deselect, short toggle);
void EDBM_selectmode_set(struct BMEditMesh *em);
-void EDBM_selectmode_convert(struct BMEditMesh *em, short oldmode, const short selectmode);
+void EDBM_selectmode_convert(struct BMEditMesh *em, const short selectmode_old, const short selectmode_new);
void EDBM_deselect_by_material(struct BMEditMesh *em, const short index, const short select);
@@ -173,7 +176,7 @@ void ED_spacetypes_init(void);
/* editmesh_tools.c (could be moved) */
-void EMBM_project_snap_verts(struct bContext *C, struct ARegion *ar, struct Object *obedit, struct BMEditMesh *em);
+void EMBM_project_snap_verts(struct bContext *C, struct ARegion *ar, struct BMEditMesh *em);
/* editface.c */
@@ -247,7 +250,7 @@ void ED_mesh_update(struct Mesh *mesh, struct bContext *C, int calc_edges, int c
int ED_mesh_uv_texture_add(struct bContext *C, struct Mesh *me, const char *name, int active_set);
int ED_mesh_uv_texture_remove(struct bContext *C, struct Object *ob, struct Mesh *me);
int ED_mesh_uv_loop_reset(struct bContext *C, struct Mesh *me);
-int ED_mesh_uv_loop_reset_ex(struct bContext *C, struct Mesh *me, const int layernum);
+int ED_mesh_uv_loop_reset_ex(struct Mesh *me, const int layernum);
int ED_mesh_color_add(struct bContext *C, struct Scene *scene, struct Object *ob, struct Mesh *me, const char *name, int active_set);
int ED_mesh_color_remove(struct bContext *C, struct Object *ob, struct Mesh *me);
int ED_mesh_color_remove_named(struct bContext *C, struct Object *ob, struct Mesh *me, const char *name);
diff --git a/source/blender/editors/include/ED_object.h b/source/blender/editors/include/ED_object.h
index a08db8072f2..0d0b8d8e797 100644
--- a/source/blender/editors/include/ED_object.h
+++ b/source/blender/editors/include/ED_object.h
@@ -35,22 +35,31 @@
extern "C" {
#endif
+struct BMEdge;
+struct BMFace;
+struct BMVert;
+struct BPoint;
struct Base;
-struct bConstraint;
-struct bContext;
-struct bPoseChannel;
+struct BezTriple;
struct Curve;
+struct EditBone;
struct EnumPropertyItem;
struct ID;
struct KeyBlock;
struct Lattice;
struct Main;
struct Mesh;
+struct MetaElem;
struct ModifierData;
+struct Nurb;
struct Object;
struct ReportList;
struct Scene;
struct View3D;
+struct ViewContext;
+struct bConstraint;
+struct bContext;
+struct bPoseChannel;
struct wmEvent;
struct wmKeyConfig;
struct wmKeyMap;
@@ -82,11 +91,13 @@ typedef enum eParentType {
PAR_TRIA
} eParentType;
+#ifdef __RNA_TYPES_H__
extern struct EnumPropertyItem prop_clear_parent_types[];
extern struct EnumPropertyItem prop_make_parent_types[];
+#endif
int ED_object_parent_set(struct ReportList *reports, struct Main *bmain, struct Scene *scene, struct Object *ob,
- struct Object *par, int partype, int xmirror);
+ struct Object *par, int partype, int xmirror, int keep_transform);
void ED_object_parent_clear(struct Object *ob, int type);
struct Base *ED_object_scene_link(struct Scene *scene, struct Object *ob);
@@ -123,10 +134,10 @@ void ED_object_location_from_view(struct bContext *C, float loc[3]);
void ED_object_rotation_from_view(struct bContext *C, float rot[3]);
void ED_object_base_init_transform(struct bContext *C, struct Base *base, const float loc[3], const float rot[3]);
float ED_object_new_primitive_matrix(struct bContext *C, struct Object *editob,
- const float loc[3], const float rot[3], float primmat[][4]);
+ const float loc[3], const float rot[3], float primmat[][4],
+ int apply_diameter);
void ED_object_add_generic_props(struct wmOperatorType *ot, int do_editmode);
-int ED_object_add_generic_invoke(struct bContext *C, struct wmOperator *op, struct wmEvent *event);
int ED_object_add_generic_get_opts(struct bContext *C, struct wmOperator *op, float loc[3], float rot[3],
int *enter_editmode, unsigned int *layer, int *is_view_aligned);
@@ -184,7 +195,7 @@ int ED_object_iter_other(struct Main *bmain, struct Object *orig_ob, int include
int ED_object_multires_update_totlevels_cb(struct Object *ob, void *totlevel_v);
-/* ibject_select.c */
+/* object_select.c */
void ED_object_select_linked_by_id(struct bContext *C, struct ID *id);
#ifdef __cplusplus
@@ -192,4 +203,3 @@ void ED_object_select_linked_by_id(struct bContext *C, struct ID *id);
#endif
#endif /* __ED_OBJECT_H__ */
-
diff --git a/source/blender/editors/include/ED_particle.h b/source/blender/editors/include/ED_particle.h
index 0076b08da99..dee97c7882a 100644
--- a/source/blender/editors/include/ED_particle.h
+++ b/source/blender/editors/include/ED_particle.h
@@ -61,7 +61,7 @@ void PE_update_object(struct Scene *scene, struct Object *ob, int useflag);
int PE_mouse_particles(struct bContext *C, const int mval[2], int extend, int deselect, int toggle);
int PE_border_select(struct bContext *C, struct rcti *rect, int select, int extend);
int PE_circle_select(struct bContext *C, int selecting, const int mval[2], float rad);
-int PE_lasso_select(struct bContext *C, int mcords[][2], short moves, short extend, short select);
+int PE_lasso_select(struct bContext *C, const int mcords[][2], const short moves, short extend, short select);
void PE_deselect_all_visible(struct PTCacheEdit *edit);
/* undo */
diff --git a/source/blender/editors/include/ED_screen.h b/source/blender/editors/include/ED_screen.h
index fc20bdfb9c5..860d176ffb3 100644
--- a/source/blender/editors/include/ED_screen.h
+++ b/source/blender/editors/include/ED_screen.h
@@ -111,6 +111,7 @@ ScrArea *ED_screen_full_newspace(struct bContext *C, ScrArea *sa, int type);
void ED_screen_full_prevspace(struct bContext *C, ScrArea *sa);
void ED_screen_full_restore(struct bContext *C, ScrArea *sa);
struct ScrArea *ED_screen_full_toggle(struct bContext *C, struct wmWindow *win, struct ScrArea *sa);
+void ED_screens_header_tools_menu_create(struct bContext *C, struct uiLayout *layout, void *arg);
/* anim */
void ED_update_for_newframe(struct Main *bmain, struct Scene *scene, int mute);
@@ -170,6 +171,7 @@ int ED_operator_editmball(struct bContext *C);
int ED_operator_uvedit(struct bContext *C);
int ED_operator_uvmap(struct bContext *C);
int ED_operator_posemode_exclusive(struct bContext *C);
+int ED_operator_posemode_context(struct bContext *C);
int ED_operator_posemode(struct bContext *C);
int ED_operator_mask(struct bContext *C);
diff --git a/source/blender/editors/include/ED_screen_types.h b/source/blender/editors/include/ED_screen_types.h
index 527ebb6c3ef..9f42fd042c3 100644
--- a/source/blender/editors/include/ED_screen_types.h
+++ b/source/blender/editors/include/ED_screen_types.h
@@ -94,7 +94,7 @@ typedef struct AZone {
/* for draw */
short x1, y1, x2, y2;
/* for clip */
- rcti rect;
+ rcti rect;
} AZone;
/* actionzone type */
diff --git a/source/blender/editors/include/ED_sculpt.h b/source/blender/editors/include/ED_sculpt.h
index e908868df75..0381ecc1fb3 100644
--- a/source/blender/editors/include/ED_sculpt.h
+++ b/source/blender/editors/include/ED_sculpt.h
@@ -45,8 +45,12 @@ void sculpt_get_redraw_planes(float planes[4][4], struct ARegion *ar,
void ED_sculpt_force_update(struct bContext *C);
float *ED_sculpt_get_last_stroke(struct Object *ob);
int ED_sculpt_minmax(struct bContext *C, float min[3], float max[3]);
-void ED_sculpt_mask_layers_ensure(struct Object *ob,
+int ED_sculpt_mask_layers_ensure(struct Object *ob,
struct MultiresModifierData *mmd);
+enum {
+ ED_SCULPT_MASK_LAYER_CALC_VERT = (1 << 0),
+ ED_SCULPT_MASK_LAYER_CALC_LOOP = (1 << 1)
+};
/* paint_ops.c */
void ED_operatortypes_paint(void);
diff --git a/source/blender/editors/include/ED_view3d.h b/source/blender/editors/include/ED_view3d.h
index b1bccfa32c5..bd85e93f1af 100644
--- a/source/blender/editors/include/ED_view3d.h
+++ b/source/blender/editors/include/ED_view3d.h
@@ -37,20 +37,26 @@ struct BMEdge;
struct BMFace;
struct BMVert;
struct BPoint;
+struct Base;
struct BezTriple;
struct BezTriple;
struct BoundBox;
+struct EditBone;
struct ImBuf;
struct MVert;
struct Main;
+struct MetaElem;
struct Nurb;
struct Nurb;
struct Object;
struct RegionView3D;
struct Scene;
+struct ScrArea;
struct View3D;
struct ViewContext;
struct bContext;
+struct bPoseChannel;
+struct bScreen;
struct bglMats;
struct rcti;
struct wmOperator;
@@ -78,159 +84,134 @@ typedef struct ViewDepths {
char damaged;
} ViewDepths;
-/* enum for passing to foreach functions to test RV3D_CLIPPING */
-typedef enum eV3DClipTest {
- V3D_CLIP_TEST_OFF = 0, /* clipping is off */
- V3D_CLIP_TEST_RV3D_CLIPPING = 1, /* clip single points */
- V3D_CLIP_TEST_REGION = 2 /* use for edges to check if both verts are in the view, but not RV3D_CLIPPING */
-} eV3DClipTest;
-
float *give_cursor(struct Scene *scene, struct View3D *v3d);
-int initgrabz(struct RegionView3D *rv3d, float x, float y, float z);
-
-/**
- * Calculate a 3d location from 2d window coordinates.
- * \param ar The region (used for the window width and height).
- * \param depth_pt The reference location used to calculate the Z depth.
- * \param mval The area relative location (such as event->mval converted to floats).
- * \param out The resulting world-space location.
- */
-void ED_view3d_win_to_3d(struct ARegion *ar, const float depth_pt[3], const float mval[2], float out[3]);
-
-/**
- * Calculate a 3d difference vector from 2d window offset.
- * note that initgrabz() must be called first to determine
- * the depth used to calculate the delta.
- * \param ar The region (used for the window width and height).
- * \param mval The area relative 2d difference (such as event->mval[0] - other_x).
- * \param out The resulting world-space delta.
- */
-void ED_view3d_win_to_delta(struct ARegion *ar, const float mval[2], float out[3]);
-
-/**
- * Calculate a 3d direction vector from 2d window coordinates.
- * This direction vector starts and the view in the direction of the 2d window coordinates.
- * In orthographic view all window coordinates yield the same vector.
- * \param ar The region (used for the window width and height).
- * \param mval The area relative 2d location (such as event->mval converted to floats).
- * \param out The resulting normalized world-space direction vector.
- */
-void ED_view3d_win_to_vector(struct ARegion *ar, const float mval[2], float out[3]);
-
-/**
- * Calculate a 3d segment from 2d window coordinates.
- * This ray_start is located at the viewpoint, ray_end is a far point.
- * ray_start and ray_end are clipped by the view near and far limits
- * so points along this line are always in view.
- * In orthographic view all resulting segments will be parallel.
- * \param ar The region (used for the window width and height).
- * \param v3d The 3d viewport (used for near and far clipping range).
- * \param mval The area relative 2d location (such as event->mval, converted into float[2]).
- * \param ray_start The world-space starting point of the segment.
- * \param ray_end The world-space end point of the segment.
- */
-void ED_view3d_win_to_segment_clip(struct ARegion *ar, struct View3D *v3d, const float mval[2], float ray_start[3], float ray_end[3]);
-
-/**
- * Calculate a 3d viewpoint and direction vector from 2d window coordinates.
- * This ray_start is located at the viewpoint, ray_normal is the direction towards mval.
- * ray_start is clipped by the view near limit so points in front of it are always in view.
- * In orthographic view the resulting ray_normal will match the view vector.
- * \param ar The region (used for the window width and height).
- * \param v3d The 3d viewport (used for near clipping value).
- * \param mval The area relative 2d location (such as event->mval, converted into float[2]).
- * \param ray_start The world-space starting point of the segment.
- * \param ray_normal The normalized world-space direction of towards mval.
- */
-void ED_view3d_win_to_ray(struct ARegion *ar, struct View3D *v3d, const float mval[2], float ray_start[3], float ray_normal[3]);
-
-/**
- * Calculate a normalized 3d direction vector from the viewpoint towards a global location.
- * In orthographic view the resulting vector will match the view vector.
- * \param rv3d The region (used for the window width and height).
- * \param coord The world-space location.
- * \param vec The resulting normalized vector.
- */
-void ED_view3d_global_to_vector(struct RegionView3D *rv3d, const float coord[3], float vec[3]);
-
-/**
- * Calculate the view transformation matrix from RegionView3D input.
- * The resulting matrix is equivalent to RegionView3D.viewinv
- * \param mat The view 4x4 transformation matrix to calculate.
- * \param ofs The view offset, normally from RegionView3D.ofs.
- * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
- * \param dist The view distance from ofs, normally from RegionView3D.dist.
- */
void ED_view3d_to_m4(float mat[][4], const float ofs[3], const float quat[4], const float dist);
-
-/**
- * Set the view transformation from a 4x4 matrix.
- * \param mat The view 4x4 transformation matrix to assign.
- * \param ofs The view offset, normally from RegionView3D.ofs.
- * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
- * \param dist The view distance from ofs, normally from RegionView3D.dist.
- */
void ED_view3d_from_m4(float mat[][4], float ofs[3], float quat[4], float *dist);
-/**
- * Set the RegionView3D members from an objects transformation and optionally lens.
- * \param ob The object to set the view to.
- * \param ofs The view offset to be set, normally from RegionView3D.ofs.
- * \param quat The view rotation to be set, quaternion normally from RegionView3D.viewquat.
- * \param dist The view distance from ofs to be set, normally from RegionView3D.dist.
- * \param lens The view lens angle set for cameras and lamps, normally from View3D.lens.
- */
void ED_view3d_from_object(struct Object *ob, float ofs[3], float quat[4], float *dist, float *lens);
-
-/**
- * Set the object transformation from RegionView3D members.
- * \param ob The object which has the transformation assigned.
- * \param ofs The view offset, normally from RegionView3D.ofs.
- * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
- * \param dist The view distance from ofs, normally from RegionView3D.dist.
- */
void ED_view3d_to_object(struct Object *ob, const float ofs[3], const float quat[4], const float dist);
-//#if 0 /* UNUSED */
-void view3d_unproject(struct bglMats *mats, float out[3], const short x, const short y, const float z);
-//#endif
-
/* Depth buffer */
-void ED_view3d_depth_update(struct ARegion *ar);
+void ED_view3d_depth_update(struct ARegion *ar);
float ED_view3d_depth_read_cached(struct ViewContext *vc, int x, int y);
-void ED_view3d_depth_tag_update(struct RegionView3D *rv3d);
+void ED_view3d_depth_tag_update(struct RegionView3D *rv3d);
/* Projection */
#define IS_CLIPPED 12000
-void ED_view3d_calc_clipping(struct BoundBox *bb, float planes[4][4], struct bglMats *mats, const struct rcti *rect);
+/* TODO, these functions work quite differently, we should make them behave in a uniform way
+ * otherwise we can't be sure bugs are not added when we need to move from short->float types for eg
+ * - Campbell */
+
+
+/* return values for ED_view3d_project_...() */
+typedef enum {
+ V3D_PROJ_RET_OK = 0,
+ V3D_PROJ_RET_CLIP_NEAR = 1, /* can't avoid this when in perspective mode, (can't avoid) */
+ V3D_PROJ_RET_CLIP_BB = 2, /* bounding box clip - RV3D_CLIPPING */
+ V3D_PROJ_RET_CLIP_WIN = 3, /* outside window bounds */
+ V3D_PROJ_RET_OVERFLOW = 4 /* outside range (mainly for short), (can't avoid) */
+} eV3DProjStatus;
+
+/* some clipping tests are optional */
+typedef enum {
+ V3D_PROJ_TEST_NOP = 0,
+ V3D_PROJ_TEST_CLIP_BB = (1 << 0),
+ V3D_PROJ_TEST_CLIP_WIN = (1 << 1),
+} eV3DProjTest;
+
+#define V3D_PROJ_TEST_CLIP_DEFAULT (V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN)
+#define V3D_PROJ_TEST_ALL (V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN)
+
+
+/* view3d_iterators.c */
+
+/* foreach iterators */
+void mesh_foreachScreenVert(
+ struct ViewContext *vc,
+ void (*func)(void *userData, struct BMVert *eve, const float screen_co[2], int index),
+ void *userData, const eV3DProjTest clip_flag);
+void mesh_foreachScreenEdge(
+ struct ViewContext *vc,
+ void (*func)(void *userData, struct BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2],
+ int index),
+ void *userData, const eV3DProjTest clip_flag);
+void mesh_foreachScreenFace(
+ struct ViewContext *vc,
+ void (*func)(void *userData, struct BMFace *efa, const float screen_co[2], int index),
+ void *userData, const eV3DProjTest clip_flag);
+void nurbs_foreachScreenVert(
+ struct ViewContext *vc,
+ void (*func)(void *userData, struct Nurb *nu, struct BPoint *bp, struct BezTriple *bezt,
+ int beztindex, const float screen_co[2]),
+ void *userData, const eV3DProjTest clip_flag);
+void mball_foreachScreenElem(
+ struct ViewContext *vc,
+ void (*func)(void *userData, struct MetaElem *ml, const float screen_co[2]),
+ void *userData, const eV3DProjTest clip_flag);
+void lattice_foreachScreenVert(
+ struct ViewContext *vc,
+ void (*func)(void *userData, struct BPoint *bp,
+ const float screen_co[2]),
+ void *userData, const eV3DProjTest clip_flag);
+void armature_foreachScreenBone(
+ struct ViewContext *vc,
+ void (*func)(void *userData, struct EditBone *ebone,
+ const float screen_co_a[2], const float screen_co_b[2]),
+ void *userData, const eV3DProjTest clip_flag);
+void pose_foreachScreenBone(
+ struct ViewContext *vc,
+ void (*func)(void *userData, struct bPoseChannel *pchan,
+ const float screen_co_a[2], const float screen_co_b[2]),
+ void *userData, const eV3DProjTest clip_flag);
+/* *** end iterators *** */
+
+
+/* view3d_project.c */
+void ED_view3d_project_float_v2_m4(const struct ARegion *a, const float co[3], float r_co[2], float mat[4][4]);
+void ED_view3d_project_float_v3_m4(struct ARegion *a, const float co[3], float r_co[3], float mat[4][4]);
+
+eV3DProjStatus ED_view3d_project_base(struct ARegion *ar, struct Base *base);
+
+/* *** short *** */
+eV3DProjStatus ED_view3d_project_short_ex(struct ARegion *ar, float perspmat[4][4], const int is_local,
+ const float co[3], short r_co[2], const eV3DProjTest flag);
+eV3DProjStatus ED_view3d_project_short_global(struct ARegion *ar, const float co[3], short r_co[2], const eV3DProjTest flag);
+eV3DProjStatus ED_view3d_project_short_object(struct ARegion *ar, const float co[3], short r_co[2], const eV3DProjTest flag);
+
+/* *** int *** */
+eV3DProjStatus ED_view3d_project_int_ex(struct ARegion *ar, float perspmat[4][4], const int is_local,
+ const float co[3], int r_co[2], const eV3DProjTest flag);
+eV3DProjStatus ED_view3d_project_int_global(struct ARegion *ar, const float co[3], int r_co[2], const eV3DProjTest flag);
+eV3DProjStatus ED_view3d_project_int_object(struct ARegion *ar, const float co[3], int r_co[2], const eV3DProjTest flag);
+
+/* *** float *** */
+eV3DProjStatus ED_view3d_project_float_ex(struct ARegion *ar, float perspmat[4][4], const int is_local,
+ const float co[3], float r_co[2], const eV3DProjTest flag);
+eV3DProjStatus ED_view3d_project_float_global(struct ARegion *ar, const float co[3], float r_co[2], const eV3DProjTest flag);
+eV3DProjStatus ED_view3d_project_float_object(struct ARegion *ar, const float co[3], float r_co[2], const eV3DProjTest flag);
-void project_short(struct ARegion *ar, const float vec[3], short adr[2]);
-void project_short_noclip(struct ARegion *ar, const float vec[3], short adr[2]);
+int initgrabz(struct RegionView3D *rv3d, float x, float y, float z);
+void ED_view3d_win_to_ray(struct ARegion *ar, struct View3D *v3d, const float mval[2], float ray_start[3], float ray_normal[3]);
+void ED_view3d_global_to_vector(struct RegionView3D *rv3d, const float coord[3], float vec[3]);
+void ED_view3d_win_to_3d(struct ARegion *ar, const float depth_pt[3], const float mval[2], float out[3]);
+void ED_view3d_win_to_delta(struct ARegion *ar, const float mval[2], float out[3]);
+void ED_view3d_win_to_vector(struct ARegion *ar, const float mval[2], float out[3]);
+void ED_view3d_win_to_segment_clip(struct ARegion *ar, struct View3D *v3d, const float mval[2], float ray_start[3], float ray_end[3]);
+void ED_view3d_ob_project_mat_get(struct RegionView3D *v3d, struct Object *ob, float pmat[4][4]);
+void ED_view3d_unproject(struct bglMats *mats, float out[3], const float x, const float y, const float z);
-void project_int(struct ARegion *ar, const float vec[3], int adr[2]);
-void project_int_noclip(struct ARegion *ar, const float vec[3], int adr[2]);
+/* end */
-void apply_project_float(float persmat[4][4], int winx, int winy, const float vec[], float adr[2]);
-void project_float(struct ARegion *ar, const float vec[3], float adr[2]);
-void project_float_noclip(struct ARegion *ar, const float vec[3], float adr[2]);
-int ED_view3d_clip_range_get(struct View3D *v3d, struct RegionView3D *rv3d, float *clipsta, float *clipend);
-int ED_view3d_viewplane_get(struct View3D *v3d, struct RegionView3D *rv3d, int winxi, int winyi, struct rctf *viewplane, float *clipsta, float *clipend);
-void ED_view3d_ob_project_mat_get(struct RegionView3D *v3d, struct Object *ob, float pmat[4][4]);
+
+int ED_view3d_clip_range_get(struct View3D *v3d, struct RegionView3D *rv3d, float *clipsta, float *clipend);
+int ED_view3d_viewplane_get(struct View3D *v3d, struct RegionView3D *rv3d, int winxi, int winyi, struct rctf *viewplane, float *clipsta, float *clipend);
void ED_view3d_calc_camera_border(struct Scene *scene, struct ARegion *ar, struct View3D *v3d, struct RegionView3D *rv3d, struct rctf *viewborder_r, short no_shift);
-void ED_view3d_project_float_v2(const struct ARegion *a, const float vec[3], float adr[2], float mat[4][4]);
-void ED_view3d_project_float_v3(struct ARegion *a, const float vec[3], float adr[3], float mat[4][4]);
void ED_view3d_calc_camera_border_size(struct Scene *scene, struct ARegion *ar, struct View3D *v3d, struct RegionView3D *rv3d, float size_r[2]);
-/* drawobject.c iterators */
-void mesh_foreachScreenVert(struct ViewContext *vc, void (*func)(void *userData, struct BMVert *eve, int x, int y, int index), void *userData, eV3DClipTest clipVerts);
-void mesh_foreachScreenEdge(struct ViewContext *vc, void (*func)(void *userData, struct BMEdge *eed, int x0, int y0, int x1, int y1, int index), void *userData, eV3DClipTest clipVerts);
-void mesh_foreachScreenFace(struct ViewContext *vc, void (*func)(void *userData, struct BMFace *efa, int x, int y, int index), void *userData);
-void nurbs_foreachScreenVert(struct ViewContext *vc, void (*func)(void *userData, struct Nurb *nu, struct BPoint *bp, struct BezTriple *bezt, int beztindex, int x, int y), void *userData);
-void lattice_foreachScreenVert(struct ViewContext *vc, void (*func)(void *userData, struct BPoint *bp, int x, int y), void *userData);
-
+void ED_view3d_clipping_calc(struct BoundBox *bb, float planes[4][4], struct bglMats *mats, const struct rcti *rect);
void ED_view3d_clipping_local(struct RegionView3D *rv3d, float mat[][4]);
int ED_view3d_clipping_test(struct RegionView3D *rv3d, const float vec[3], const int is_local);
void ED_view3d_clipping_set(struct RegionView3D *rv3d);
@@ -244,7 +225,8 @@ void drawcircball(int mode, const float cent[3], float rad, float tmat[][4]);
/* backbuffer select and draw support */
void view3d_validate_backbuf(struct ViewContext *vc);
struct ImBuf *view3d_read_backbuf(struct ViewContext *vc, short xmin, short ymin, short xmax, short ymax);
-unsigned int view3d_sample_backbuf_rect(struct ViewContext *vc, const int mval[2], int size, unsigned int min, unsigned int max, int *dist, short strict,
+unsigned int view3d_sample_backbuf_rect(struct ViewContext *vc, const int mval[2], int size,
+ unsigned int min, unsigned int max, float *dist, short strict,
void *handle, unsigned int (*indextest)(void *handle, unsigned int index));
unsigned int view3d_sample_backbuf(struct ViewContext *vc, int x, int y);
@@ -268,7 +250,7 @@ int view3d_get_view_aligned_coordinate(struct ViewContext *vc, float fp[3], cons
void view3d_get_transformation(const struct ARegion *ar, struct RegionView3D *rv3d, struct Object *ob, struct bglMats *mats);
/* XXX should move to BLI_math */
-int edge_inside_circle(int centx, int centy, int rad, int x1, int y1, int x2, int y2);
+int edge_inside_circle(const float cent[2], float radius, const float screen_co_a[2], const float screen_co_b[2]);
/* get 3d region from context, also if mouse is in header or toolbar */
struct RegionView3D *ED_view3d_context_rv3d(struct bContext *C);
@@ -281,6 +263,7 @@ void ED_view3d_init_mats_rv3d_gl(struct Object *ob, struct RegionView3D *rv3d);
int ED_view3d_scene_layer_set(int lay, const int *values, int *active);
int ED_view3d_context_activate(struct bContext *C);
+void ED_view3d_draw_offscreen_init(struct Scene *scene, struct View3D *v3d);
void ED_view3d_draw_offscreen(struct Scene *scene, struct View3D *v3d, struct ARegion *ar,
int winx, int winy, float viewmat[][4], float winmat[][4], int do_bgpic, int colormanage_background);
@@ -312,6 +295,7 @@ struct BGpic *ED_view3D_background_image_new(struct View3D *v3d);
void ED_view3D_background_image_remove(struct View3D *v3d, struct BGpic *bgpic);
void ED_view3D_background_image_clear(struct View3D *v3d);
+float ED_view3d_offset_distance(float mat[4][4], float ofs[3]);
float ED_view3d_grid_scale(struct Scene *scene, struct View3D *v3d, const char **grid_unit);
/* view matrix properties utilities */
diff --git a/source/blender/editors/include/UI_icons.h b/source/blender/editors/include/UI_icons.h
index ef7b8ed3a41..e400e44e944 100644
--- a/source/blender/editors/include/UI_icons.h
+++ b/source/blender/editors/include/UI_icons.h
@@ -94,7 +94,7 @@ DEF_ICON(LINK)
DEF_ICON(INLINK)
DEF_ICON(PLUGIN)
- /* various ui */
+ /* various ui */
DEF_ICON(HELP)
DEF_ICON(GHOST_ENABLED)
DEF_ICON(COLOR)
@@ -450,8 +450,8 @@ DEF_ICON(FORCE_CURVE)
DEF_ICON(FORCE_BOID)
DEF_ICON(FORCE_TURBULENCE)
DEF_ICON(FORCE_DRAG)
+DEF_ICON(FORCE_SMOKEFLOW)
#ifndef DEF_ICON_BLANK_SKIP
- DEF_ICON(BLANK672)
DEF_ICON(BLANK673)
DEF_ICON(BLANK674)
DEF_ICON(BLANK675)
@@ -799,13 +799,12 @@ DEF_ICON(NDOF_TRANS)
DEF_ICON(LAYER_USED)
DEF_ICON(LAYER_ACTIVE)
#ifndef DEF_ICON_BLANK_SKIP
+ /* available */
DEF_ICON(BLANK254)
DEF_ICON(BLANK255)
DEF_ICON(BLANK256)
DEF_ICON(BLANK257)
DEF_ICON(BLANK257b)
-
- /* available */
DEF_ICON(BLANK258)
DEF_ICON(BLANK259)
DEF_ICON(BLANK260)
@@ -890,8 +889,8 @@ DEF_ICON(FORWARD)
DEF_ICON(BLANK313)
DEF_ICON(BLANK314)
DEF_ICON(BLANK315)
- DEF_ICON(BLANK316)
#endif
+DEF_ICON(FILE_BACKUP)
DEF_ICON(DISK_DRIVE)
/* SHADING / TEXT */
diff --git a/source/blender/editors/include/UI_interface.h b/source/blender/editors/include/UI_interface.h
index 917153c9199..ed4b4ae027f 100644
--- a/source/blender/editors/include/UI_interface.h
+++ b/source/blender/editors/include/UI_interface.h
@@ -106,9 +106,9 @@ typedef struct uiLayout uiLayout;
/* uiBlock->flag (controls) */
#define UI_BLOCK_LOOP 1
#define UI_BLOCK_REDRAW 2
-#define UI_BLOCK_RET_1 4 /* XXX 2.5 not implemented */
+#define UI_BLOCK_SEARCH_MENU 4
#define UI_BLOCK_NUMSELECT 8
-/*#define UI_BLOCK_ENTER_OK 16*/ /*UNUSED*/
+#define UI_BLOCK_NO_WIN_CLIP 16 /* don't apply window clipping */ /* was UI_BLOCK_ENTER_OK */
#define UI_BLOCK_CLIPBOTTOM 32
#define UI_BLOCK_CLIPTOP 64
#define UI_BLOCK_MOVEMOUSE_QUIT 128
@@ -120,11 +120,12 @@ typedef struct uiLayout uiLayout;
#define UI_BLOCK_CLIP_EVENTS 8192 /* stop handling mouse events */
/* uiPopupBlockHandle->menuretval */
-#define UI_RETURN_CANCEL 1 /* cancel all menus cascading */
-#define UI_RETURN_OK 2 /* choice made */
-#define UI_RETURN_OUT 4 /* left the menu */
-#define UI_RETURN_UPDATE 8 /* update the button that opened */
-#define UI_RETURN_POPUP_OK 16 /* popup is ok to be handled */
+#define UI_RETURN_CANCEL 1 /* cancel all menus cascading */
+#define UI_RETURN_OK 2 /* choice made */
+#define UI_RETURN_OUT 4 /* left the menu */
+#define UI_RETURN_OUT_PARENT 8 /* let the parent handle this event */
+#define UI_RETURN_UPDATE 16 /* update the button that opened */
+#define UI_RETURN_POPUP_OK 32 /* popup is ok to be handled */
/* block->flag bits 12-15 are identical to but->flag bits */
@@ -420,7 +421,6 @@ void uiBlockSetDirection(uiBlock *block, int direction);
void uiBlockFlipOrder(uiBlock *block);
void uiBlockSetFlag(uiBlock *block, int flag);
void uiBlockClearFlag(uiBlock *block, int flag);
-void uiBlockSetXOfs(uiBlock *block, int xofs);
int uiButGetRetVal(uiBut *but);
@@ -810,6 +810,8 @@ void uiTemplateCurveMapping(uiLayout *layout, struct PointerRNA *ptr, const char
void uiTemplateColorWheel(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int value_slider, int lock, int lock_luminosity, int cubic);
void uiTemplateLayers(uiLayout *layout, struct PointerRNA *ptr, const char *propname,
PointerRNA *used_ptr, const char *used_propname, int active_layer);
+void uiTemplateGameStates(uiLayout *layout, struct PointerRNA *ptr, const char *propname,
+ PointerRNA *used_ptr, const char *used_propname, int active_state);
void uiTemplateImage(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, struct PointerRNA *userptr, int compact);
void uiTemplateImageSettings(uiLayout *layout, struct PointerRNA *imfptr, int color_management);
void uiTemplateImageLayers(uiLayout *layout, struct bContext *C, struct Image *ima, struct ImageUser *iuser);
diff --git a/source/blender/editors/include/UI_view2d.h b/source/blender/editors/include/UI_view2d.h
index 792c96fe7c8..24759fa778a 100644
--- a/source/blender/editors/include/UI_view2d.h
+++ b/source/blender/editors/include/UI_view2d.h
@@ -163,7 +163,8 @@ void UI_view2d_view_orthoSpecial(struct ARegion *ar, struct View2D *v2d, short x
void UI_view2d_view_restore(const struct bContext *C);
/* grid drawing */
-View2DGrid *UI_view2d_grid_calc(struct Scene *scene, struct View2D *v2d, short xunits, short xclamp, short yunits, short yclamp, int winx, int winy);
+View2DGrid *UI_view2d_grid_calc(struct Scene *scene, struct View2D *v2d,
+ short xunits, short xclamp, short yunits, short yclamp, int winx, int winy);
void UI_view2d_grid_draw(struct View2D *v2d, View2DGrid *grid, int flag);
void UI_view2d_constant_grid_draw(struct View2D *v2d);
void UI_view2d_multi_grid_draw(struct View2D *v2d, float step, int level_size, int totlevels);
@@ -171,14 +172,21 @@ void UI_view2d_grid_size(View2DGrid *grid, float *r_dx, float *r_dy);
void UI_view2d_grid_free(View2DGrid *grid);
/* scrollbar drawing */
-View2DScrollers *UI_view2d_scrollers_calc(const struct bContext *C, struct View2D *v2d, short xunits, short xclamp, short yunits, short yclamp);
+View2DScrollers *UI_view2d_scrollers_calc(const struct bContext *C, struct View2D *v2d,
+ short xunits, short xclamp, short yunits, short yclamp);
void UI_view2d_scrollers_draw(const struct bContext *C, struct View2D *v2d, View2DScrollers *scrollers);
void UI_view2d_scrollers_free(View2DScrollers *scrollers);
/* list view tools */
-void UI_view2d_listview_cell_to_view(struct View2D *v2d, short columnwidth, short rowheight, float startx, float starty, int column, int row, struct rctf *rect);
-void UI_view2d_listview_view_to_cell(struct View2D *v2d, short columnwidth, short rowheight, float startx, float starty, float viewx, float viewy, int *column, int *row);
-void UI_view2d_listview_visible_cells(struct View2D *v2d, short columnwidth, short rowheight, float startx, float starty, int *column_min, int *column_max, int *row_min, int *row_max);
+void UI_view2d_listview_cell_to_view(struct View2D *v2d, short columnwidth, short rowheight,
+ float startx, float starty, int column, int row,
+ struct rctf *rect);
+void UI_view2d_listview_view_to_cell(struct View2D *v2d, short columnwidth, short rowheight,
+ float startx, float starty, float viewx, float viewy,
+ int *column, int *row);
+void UI_view2d_listview_visible_cells(struct View2D *v2d, short columnwidth, short rowheight,
+ float startx, float starty, int *column_min, int *column_max,
+ int *row_min, int *row_max);
/* coordinate conversion */
void UI_view2d_region_to_view(struct View2D *v2d, int x, int y, float *viewx, float *viewy);
diff --git a/source/blender/editors/interface/interface.c b/source/blender/editors/interface/interface.c
index 742aed4fbb1..b8e4fec1259 100644
--- a/source/blender/editors/interface/interface.c
+++ b/source/blender/editors/interface/interface.c
@@ -79,10 +79,6 @@
#include "interface_intern.h"
-#define MENU_WIDTH 120
-#define MENU_ITEM_HEIGHT 20
-#define MENU_SEP_HEIGHT 6
-
#define PRECISION_FLOAT_MAX 6
#define PRECISION_FLOAT_MAX_POW 1000000 /* pow(10, PRECISION_FLOAT_MAX) */
@@ -106,8 +102,8 @@ void ui_block_to_window_fl(const ARegion *ar, uiBlock *block, float *x, float *y
float gx, gy;
int sx, sy, getsizex, getsizey;
- getsizex = BLI_RCT_SIZE_X(&ar->winrct) + 1;
- getsizey = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
+ getsizex = BLI_rcti_size_x(&ar->winrct) + 1;
+ getsizey = BLI_rcti_size_y(&ar->winrct) + 1;
sx = ar->winrct.xmin;
sy = ar->winrct.ymin;
@@ -152,8 +148,8 @@ void ui_window_to_block_fl(const ARegion *ar, uiBlock *block, float *x, float *y
float a, b, c, d, e, f, px, py;
int sx, sy, getsizex, getsizey;
- getsizex = BLI_RCT_SIZE_X(&ar->winrct) + 1;
- getsizey = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
+ getsizex = BLI_rcti_size_x(&ar->winrct) + 1;
+ getsizey = BLI_rcti_size_y(&ar->winrct) + 1;
sx = ar->winrct.xmin;
sy = ar->winrct.ymin;
@@ -242,7 +238,7 @@ static void ui_text_bounds_block(uiBlock *block, float offset)
bt->rect.xmax = bt->rect.xmin + i + block->bounds;
if (col == lastcol) {
- bt->rect.xmax = maxf(bt->rect.xmax, offset + block->minbounds);
+ bt->rect.xmax = max_ff(bt->rect.xmax, offset + block->minbounds);
}
ui_check_but(bt); /* clips text again */
@@ -279,7 +275,7 @@ void ui_bounds_block(uiBlock *block)
block->rect.ymax += block->bounds;
}
- block->rect.xmax = block->rect.xmin + maxf(BLI_RCT_SIZE_X(&block->rect), block->minbounds);
+ block->rect.xmax = block->rect.xmin + max_ff(BLI_rctf_size_x(&block->rect), block->minbounds);
/* hardcoded exception... but that one is annoying with larger safety */
bt = block->buttons.first;
@@ -307,8 +303,8 @@ static void ui_centered_bounds_block(const bContext *C, uiBlock *block)
ui_bounds_block(block);
- width = BLI_RCT_SIZE_X(&block->rect);
- height = BLI_RCT_SIZE_Y(&block->rect);
+ width = BLI_rctf_size_x(&block->rect);
+ height = BLI_rctf_size_y(&block->rect);
startx = (xmax * 0.5f) - (width * 0.5f);
starty = (ymax * 0.5f) - (height * 0.5f);
@@ -332,8 +328,8 @@ static void ui_popup_bounds_block(const bContext *C, uiBlock *block, eBlockBound
wm_window_get_size(window, &xmax, &ymax);
- oldwidth = BLI_RCT_SIZE_X(&block->rect);
- oldheight = BLI_RCT_SIZE_Y(&block->rect);
+ oldwidth = BLI_rctf_size_x(&block->rect);
+ oldheight = BLI_rctf_size_y(&block->rect);
/* first we ensure wide enough text bounds */
if (bounds_calc == UI_BLOCK_BOUNDS_POPUP_MENU) {
@@ -348,8 +344,8 @@ static void ui_popup_bounds_block(const bContext *C, uiBlock *block, eBlockBound
ui_bounds_block(block);
/* and we adjust the position to fit within window */
- width = BLI_RCT_SIZE_X(&block->rect);
- height = BLI_RCT_SIZE_Y(&block->rect);
+ width = BLI_rctf_size_x(&block->rect);
+ height = BLI_rctf_size_y(&block->rect);
/* avoid divide by zero below, caused by calling with no UI, but better not crash */
oldwidth = oldwidth > 0 ? oldwidth : MAX2(1, width);
@@ -495,10 +491,10 @@ static void ui_draw_linkline(uiLinkLine *line, int highlightActiveLines)
if (line->from == NULL || line->to == NULL) return;
- rect.xmin = BLI_RCT_CENTER_X(&line->from->rect);
- rect.ymin = BLI_RCT_CENTER_Y(&line->from->rect);
- rect.xmax = BLI_RCT_CENTER_X(&line->to->rect);
- rect.ymax = BLI_RCT_CENTER_Y(&line->to->rect);
+ rect.xmin = BLI_rctf_cent_x(&line->from->rect);
+ rect.ymin = BLI_rctf_cent_y(&line->from->rect);
+ rect.xmax = BLI_rctf_cent_x(&line->to->rect);
+ rect.ymax = BLI_rctf_cent_y(&line->to->rect);
if (line->flag & UI_SELECT)
glColor3ub(100, 100, 100);
@@ -531,7 +527,7 @@ static void ui_draw_links(uiBlock *block)
foundselectline = TRUE;
}
}
- }
+ }
/* Draw any active lines (lines with either button being hovered over).
* Do this last so they appear on top of inactive lines. */
@@ -543,7 +539,7 @@ static void ui_draw_links(uiBlock *block)
ui_draw_linkline(line, !foundselectline);
}
}
- }
+ }
}
}
@@ -585,7 +581,7 @@ static void ui_but_update_linklines(uiBlock *block, uiBut *oldbut, uiBut *newbut
if (line->from == newbut)
line->from = oldbut;
}
- }
+ }
/* check all other button links */
for (but = block->buttons.first; but; but = but->next) {
@@ -614,28 +610,28 @@ static int ui_but_update_from_old_block(const bContext *C, uiBlock *block, uiBut
if (ui_but_equals_old(oldbut, but)) {
if (oldbut->active) {
#if 0
-// but->flag= oldbut->flag;
+// but->flag = oldbut->flag;
#else
/* exception! redalert flag can't be update from old button.
* perhaps it should only copy specific flags rather than all. */
-// but->flag= (oldbut->flag & ~UI_BUT_REDALERT) | (but->flag & UI_BUT_REDALERT);
+// but->flag = (oldbut->flag & ~UI_BUT_REDALERT) | (but->flag & UI_BUT_REDALERT);
#endif
-// but->active= oldbut->active;
-// but->pos= oldbut->pos;
-// but->ofs= oldbut->ofs;
-// but->editstr= oldbut->editstr;
-// but->editval= oldbut->editval;
-// but->editvec= oldbut->editvec;
-// but->editcoba= oldbut->editcoba;
-// but->editcumap= oldbut->editcumap;
-// but->selsta= oldbut->selsta;
-// but->selend= oldbut->selend;
-// but->softmin= oldbut->softmin;
-// but->softmax= oldbut->softmax;
-// but->linkto[0]= oldbut->linkto[0];
-// but->linkto[1]= oldbut->linkto[1];
+// but->active = oldbut->active;
+// but->pos = oldbut->pos;
+// but->ofs = oldbut->ofs;
+// but->editstr = oldbut->editstr;
+// but->editval = oldbut->editval;
+// but->editvec = oldbut->editvec;
+// but->editcoba = oldbut->editcoba;
+// but->editcumap = oldbut->editcumap;
+// but->selsta = oldbut->selsta;
+// but->selend = oldbut->selend;
+// but->softmin = oldbut->softmin;
+// but->softmax = oldbut->softmax;
+// but->linkto[0] = oldbut->linkto[0];
+// but->linkto[1] = oldbut->linkto[1];
found = 1;
-// oldbut->active= NULL;
+// oldbut->active = NULL;
/* move button over from oldblock to new block */
BLI_remlink(&oldblock->buttons, oldbut);
@@ -1000,24 +996,20 @@ void ui_fontscale(short *points, float aspect)
/* project button or block (but==NULL) to pixels in regionspace */
static void ui_but_to_pixelrect(rcti *rect, const ARegion *ar, uiBlock *block, uiBut *but)
{
- float gx, gy;
- float getsizex, getsizey;
+ rctf rectf = (but)? but->rect: block->rect;
- getsizex = ar->winx;
- getsizey = ar->winy;
+ ui_block_to_window_fl(ar, block, &rectf.xmin, &rectf.ymin);
+ ui_block_to_window_fl(ar, block, &rectf.xmax, &rectf.ymax);
- gx = (but ? but->rect.xmin : block->rect.xmin) + (block->panel ? block->panel->ofsx : 0.0f);
- gy = (but ? but->rect.ymin : block->rect.ymin) + (block->panel ? block->panel->ofsy : 0.0f);
-
- rect->xmin = floorf(getsizex * (0.5f + 0.5f * (gx * block->winmat[0][0] + gy * block->winmat[1][0] + block->winmat[3][0])));
- rect->ymin = floorf(getsizey * (0.5f + 0.5f * (gx * block->winmat[0][1] + gy * block->winmat[1][1] + block->winmat[3][1])));
-
- gx = (but ? but->rect.xmax : block->rect.xmax) + (block->panel ? block->panel->ofsx : 0.0f);
- gy = (but ? but->rect.ymax : block->rect.ymax) + (block->panel ? block->panel->ofsy : 0.0f);
-
- rect->xmax = floorf(getsizex * (0.5f + 0.5f * (gx * block->winmat[0][0] + gy * block->winmat[1][0] + block->winmat[3][0])));
- rect->ymax = floorf(getsizey * (0.5f + 0.5f * (gx * block->winmat[0][1] + gy * block->winmat[1][1] + block->winmat[3][1])));
+ rectf.xmin -= ar->winrct.xmin;
+ rectf.ymin -= ar->winrct.ymin;
+ rectf.xmax -= ar->winrct.xmin;
+ rectf.ymax -= ar->winrct.ymin;
+ rect->xmin = floorf(rectf.xmin);
+ rect->ymin = floorf(rectf.ymin);
+ rect->xmax = floorf(rectf.xmax);
+ rect->ymax = floorf(rectf.ymax);
}
/* uses local copy of style, to scale things down, and allow widgets to change stuff */
@@ -1160,9 +1152,15 @@ static void ui_is_but_sel(uiBut *but, double *value)
}
}
- if (is_push == 2) ;
- else if (is_push == 1) but->flag |= UI_SELECT;
- else but->flag &= ~UI_SELECT;
+ if (is_push == 2) {
+ /* pass */
+ }
+ else if (is_push == 1) {
+ but->flag |= UI_SELECT;
+ }
+ else {
+ but->flag &= ~UI_SELECT;
+ }
}
static uiBut *ui_find_inlink(uiBlock *block, void *poin)
@@ -1272,7 +1270,7 @@ void ui_delete_linkline(uiLinkLine *line, uiBut *but)
(*(link->ppoin))[b] = (*(link->ppoin))[a];
b++;
}
- }
+ }
(*(link->totlink))--;
}
}
@@ -1305,7 +1303,7 @@ void ui_get_but_vectorf(uiBut *but, float vec[3])
if (RNA_property_type(prop) == PROP_FLOAT) {
tot = RNA_property_array_length(&but->rnapoin, prop);
- tot = MIN2(tot, 3);
+ tot = min_ii(tot, 3);
for (a = 0; a < tot; a++)
vec[a] = RNA_property_float_get_index(&but->rnapoin, prop, a);
@@ -1350,7 +1348,7 @@ void ui_set_but_vectorf(uiBut *but, const float vec[3])
int a;
tot = RNA_property_array_length(&but->rnapoin, prop);
- tot = MIN2(tot, 3);
+ tot = min_ii(tot, 3);
for (a = 0; a < tot; a++) {
RNA_property_float_set_index(&but->rnapoin, prop, a, vec[a]);
@@ -1393,7 +1391,7 @@ int ui_is_but_unit(uiBut *but)
return 0;
#endif
- /* for now disable time unit conversion */
+ /* for now disable time unit conversion */
if (unit_type == PROP_UNIT_TIME)
return 0;
@@ -1466,16 +1464,16 @@ double ui_get_but_val(uiBut *but)
case 'S': value = hsv[1]; break;
case 'V': value = hsv[2]; break;
}
- }
+ }
else if (but->pointype == UI_BUT_POIN_CHAR) {
value = *(char *)but->poin;
}
else if (but->pointype == UI_BUT_POIN_SHORT) {
value = *(short *)but->poin;
- }
+ }
else if (but->pointype == UI_BUT_POIN_INT) {
value = *(int *)but->poin;
- }
+ }
else if (but->pointype == UI_BUT_POIN_FLOAT) {
value = *(float *)but->poin;
}
@@ -1530,7 +1528,9 @@ void ui_set_but_val(uiBut *but, double value)
* so leave this unset */
value = UI_BUT_VALUE_UNSET;
}
- else if (but->pointype == 0) ;
+ else if (but->pointype == 0) {
+ /* pass */
+ }
else if (but->type == HSVSLI) {
float *fp, hsv[3];
@@ -1697,7 +1697,7 @@ void ui_get_but_string(uiBut *but, char *str, size_t maxlen)
}
else if (buf && buf != str) {
/* string was too long, we have to truncate */
- memcpy(str, buf, MIN2(maxlen, buf_len + 1));
+ memcpy(str, buf, MIN2(maxlen, (size_t)buf_len + 1));
MEM_freeN(buf);
}
}
@@ -1723,8 +1723,9 @@ void ui_get_but_string(uiBut *but, char *str, size_t maxlen)
BLI_strncpy(str, but->poin, maxlen);
return;
}
- else if (ui_but_anim_expression_get(but, str, maxlen))
- ; /* driver expression */
+ else if (ui_but_anim_expression_get(but, str, maxlen)) {
+ /* driver expression */
+ }
else {
/* number editing */
double value;
@@ -1946,8 +1947,8 @@ void ui_set_but_soft_range(uiBut *but, double value)
RNA_property_int_ui_range(&but->rnapoin, but->rnaprop, &imin, &imax, &istep);
softmin = (imin == INT_MIN) ? -1e4 : imin;
softmax = (imin == INT_MAX) ? 1e4 : imax;
- /*step= istep;*/ /*UNUSED*/
- /*precision= 1;*/ /*UNUSED*/
+ /*step = istep;*/ /*UNUSED*/
+ /*precision = 1;*/ /*UNUSED*/
if (array_len >= 2) {
int value_range[2];
@@ -1963,8 +1964,8 @@ void ui_set_but_soft_range(uiBut *but, double value)
RNA_property_float_ui_range(&but->rnapoin, but->rnaprop, &fmin, &fmax, &fstep, &fprecision);
softmin = (fmin == -FLT_MAX) ? (float)-1e4 : fmin;
softmax = (fmax == FLT_MAX) ? (float)1e4 : fmax;
- /*step= fstep;*/ /*UNUSED*/
- /*precision= fprecision;*/ /*UNUSED*/
+ /*step = fstep;*/ /*UNUSED*/
+ /*precision = fprecision;*/ /*UNUSED*/
if (array_len >= 2) {
float value_range[2];
@@ -2005,7 +2006,7 @@ void ui_set_but_soft_range(uiBut *but, double value)
static void ui_free_link(uiLink *link)
{
- if (link) {
+ if (link) {
BLI_freelistN(&link->lines);
MEM_freeN(link);
}
@@ -2054,7 +2055,7 @@ void uiFreeBlock(const bContext *C, uiBlock *block)
uiBut *but;
while ( (but = block->buttons.first) ) {
- BLI_remlink(&block->buttons, but);
+ BLI_remlink(&block->buttons, but);
ui_free_but(C, but);
}
@@ -2164,8 +2165,6 @@ uiBlock *uiBeginBlock(const bContext *C, ARegion *region, const char *name, shor
wm_subwindow_getmatrix(window, region->swinid, block->winmat);
wm_subwindow_getsize(window, region->swinid, &getsizex, &getsizey);
- /* TODO - investigate why block->winmat[0][0] is negative
- * in the image view when viewRedrawForce is called */
block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
}
else {
@@ -2257,7 +2256,7 @@ void ui_check_but(uiBut *but)
/* safety is 4 to enable small number buttons (like 'users') */
- // okwidth= -4 + (BLI_RCT_SIZE_X(&but->rect)); // UNUSED
+ // okwidth = -4 + (BLI_rcti_size_x(&but->rect)); // UNUSED
/* name: */
switch (but->type) {
@@ -2265,7 +2264,7 @@ void ui_check_but(uiBut *but)
case MENU:
case ICONTEXTROW:
- if (BLI_RCT_SIZE_X(&but->rect) > 24.0f) {
+ if (BLI_rctf_size_x(&but->rect) > 24.0f) {
UI_GET_BUT_VALUE_INIT(but, value);
ui_set_name_menu(but, (int)value);
}
@@ -2399,7 +2398,7 @@ void uiBlockBeginAlign(uiBlock *block)
/* if other align was active, end it */
if (block->flag & UI_BUT_ALIGN) uiBlockEndAlign(block);
- block->flag |= UI_BUT_ALIGN_DOWN;
+ block->flag |= UI_BUT_ALIGN_DOWN;
block->alignnr++;
/* buttons declared after this call will get this align nr */ // XXX flag?
@@ -2440,7 +2439,7 @@ static void ui_block_do_align_but(uiBut *first, short nr)
}
}
- /* rows==0: 1 row, cols==0: 1 column */
+ /* rows == 0: 1 row, cols == 0: 1 column */
/* note; how it uses 'flag' in loop below (either set it, or OR it) is confusing */
for (but = first, prev = NULL; but && but->alignnr == nr; prev = but, but = but->next) {
@@ -2484,7 +2483,9 @@ static void ui_block_do_align_but(uiBut *first, short nr)
if (rows > 0) {
uiBut *bt = but;
while (bt && bt->alignnr == nr) {
- if (bt->next && bt->next->alignnr == nr && buts_are_horiz(bt, bt->next) == 0) break;
+ if (bt->next && bt->next->alignnr == nr && buts_are_horiz(bt, bt->next) == 0) {
+ break;
+ }
bt = bt->next;
}
if (bt == NULL || bt->alignnr != nr) flag = UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_RIGHT;
@@ -2572,7 +2573,9 @@ void ui_block_do_align(uiBlock *block)
ui_block_do_align_but(but, nr);
/* skip with same number */
- for (; but && but->alignnr == nr; but = but->next) ;
+ for (; but && but->alignnr == nr; but = but->next) {
+ /* pass */
+ }
if (!but) {
break;
@@ -2621,6 +2624,9 @@ static uiBut *ui_def_but(uiBlock *block, int type, int retval, const char *str,
uiBut *but;
int slen;
+ BLI_assert(width >= 0);
+ BLI_assert(height >= 0);
+
/* we could do some more error checks here */
if ((type & BUTTYPE) == LABEL) {
BLI_assert((poin != NULL || min != 0.0f || max != 0.0f || (a1 == 0.0f && a2 != 0.0f) || (a1 != 0.0f && a1 != 1.0f)) == FALSE);
@@ -2713,9 +2719,8 @@ static uiBut *ui_def_but(uiBlock *block, int type, int retval, const char *str,
}
/* keep track of UI_interface.h */
- if (ELEM7(but->type, BLOCK, BUT, LABEL, PULLDOWN, ROUNDBOX, LISTBOX, BUTM)) ;
- else if (ELEM(but->type, SCROLL, SEPR /* , FTPREVIEW */ )) ;
- else if (but->type >= SEARCH_MENU) ;
+ if (ELEM9(but->type, BLOCK, BUT, LABEL, PULLDOWN, ROUNDBOX, LISTBOX, BUTM, SCROLL, SEPR /* , FTPREVIEW */)) {}
+ else if (but->type >= SEARCH_MENU) {}
else but->flag |= UI_BUT_UNDO;
BLI_addtail(&block->buttons, but);
@@ -2749,7 +2754,7 @@ static uiBut *ui_def_but(uiBlock *block, int type, int retval, const char *str,
static uiBut *ui_def_but_rna(uiBlock *block, int type, int retval, const char *str,
- int x, int y, short width, short height,
+ int x, int y, short width, short height,
PointerRNA *ptr, PropertyRNA *prop, int index,
float min, float max, float a1, float a2, const char *tip)
{
@@ -3422,11 +3427,6 @@ void uiBlockClearFlag(uiBlock *block, int flag)
block->flag &= ~flag;
}
-void uiBlockSetXOfs(uiBlock *block, int xofs)
-{
- block->xofs = xofs;
-}
-
void uiButSetFlag(uiBut *but, int flag)
{
but->flag |= flag;
@@ -3788,15 +3788,16 @@ void uiButGetStrInfo(bContext *C, uiBut *but, int nbr, ...)
if (type == BUT_GET_LABEL) {
if (but->str) {
/* Menu labels can have some complex formating stuff marked by pipes or %t, we don't want those here! */
- const char *tc;
-
- if (but->type == MENU)
- tc = strstr(but->str, "%t");
- else
- tc = strchr(but->str, '|');
-
- if (tc)
- tmp = BLI_strdupn(but->str, tc - but->str);
+ const char *tc1, *tc2;
+
+ tc1 = strstr(but->str, "%t");
+ tc2 = strstr(but->str, "|"); /* XXX For some reason strchr seems to not work here? */
+
+ if (tc2 && (!tc1 || tc1 > tc2))
+ tc1 = tc2;
+
+ if (tc1)
+ tmp = BLI_strdupn(but->str, tc1 - but->str);
else
tmp = BLI_strdup(but->str);
}
@@ -3872,12 +3873,41 @@ void uiButGetStrInfo(bContext *C, uiBut *but, int nbr, ...)
}
}
else if (ELEM3(type, BUT_GET_RNAENUM_IDENTIFIER, BUT_GET_RNAENUM_LABEL, BUT_GET_RNAENUM_TIP)) {
+ PointerRNA *ptr = NULL;
+ PropertyRNA *prop = NULL;
+ int value = 0;
+
+ /* get the enum property... */
if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_ENUM) {
+ /* enum property */
+ ptr = &but->rnapoin;
+ prop = but->rnaprop;
+ value = (but->type == ROW) ? (int)but->hardmax : (int)ui_get_but_val(but);
+ }
+ else if (but->optype) {
+ PointerRNA *opptr = uiButGetOperatorPtrRNA(but);
+ wmOperatorType *ot = but->optype;
+
+ /* if the default property of the operator is enum and it is set,
+ * fetch the tooltip of the selected value so that "Snap" and "Mirror"
+ * operator menus in the Anim Editors will show tooltips for the different
+ * operations instead of the meaningless generic operator tooltip
+ */
+ if (ot->prop && RNA_property_type(ot->prop) == PROP_ENUM) {
+ if (RNA_struct_contains_property(opptr, ot->prop)) {
+ ptr = opptr;
+ prop = ot->prop;
+ value = RNA_property_enum_get(opptr, ot->prop);
+ }
+ }
+ }
+
+ /* get strings from matching enum item */
+ if (ptr && prop) {
if (!item) {
int i;
- int value = (but->type == ROW) ? (int)but->hardmax : (int)ui_get_but_val(but);
- RNA_property_enum_items_gettexted(C, &but->rnapoin, but->rnaprop, &items, &totitems, &free_items);
-
+
+ RNA_property_enum_items_gettexted(C, ptr, prop, &items, &totitems, &free_items);
for (i = 0, item = items; i < totitems; i++, item++) {
if (item->identifier[0] && item->value == value)
break;
diff --git a/source/blender/editors/interface/interface_draw.c b/source/blender/editors/interface/interface_draw.c
index f535c3c3e2a..469bd11215e 100644
--- a/source/blender/editors/interface/interface_draw.c
+++ b/source/blender/editors/interface/interface_draw.c
@@ -60,8 +60,6 @@
/* own include */
#include "interface_intern.h"
-#define UI_DISABLED_ALPHA_OFFS -160
-
static int roundboxtype = UI_CNR_ALL;
void uiSetRoundBox(int type)
@@ -86,7 +84,7 @@ void uiDrawBox(int mode, float minx, float miny, float maxx, float maxy, float r
/* mult */
for (a = 0; a < 7; a++) {
- vec[a][0] *= rad; vec[a][1] *= rad;
+ mul_v2_fl(vec[a], rad);
}
glBegin(mode);
@@ -157,18 +155,18 @@ void uiDrawBoxShade(int mode, float minx, float miny, float maxx, float maxy, fl
/* mult */
for (a = 0; a < 7; a++) {
- vec[a][0] *= rad; vec[a][1] *= rad;
+ mul_v2_fl(vec[a], rad);
}
/* get current color, needs to be outside of glBegin/End */
glGetFloatv(GL_CURRENT_COLOR, color);
- /* 'shade' defines strength of shading */
- coltop[0] = color[0] + shadetop; if (coltop[0] > 1.0f) coltop[0] = 1.0f;
- coltop[1] = color[1] + shadetop; if (coltop[1] > 1.0f) coltop[1] = 1.0f;
- coltop[2] = color[2] + shadetop; if (coltop[2] > 1.0f) coltop[2] = 1.0f;
- coldown[0] = color[0] + shadedown; if (coldown[0] < 0.0f) coldown[0] = 0.0f;
- coldown[1] = color[1] + shadedown; if (coldown[1] < 0.0f) coldown[1] = 0.0f;
- coldown[2] = color[2] + shadedown; if (coldown[2] < 0.0f) coldown[2] = 0.0f;
+ /* 'shade' defines strength of shading */
+ coltop[0] = min_ff(1.0f, color[0] + shadetop);
+ coltop[1] = min_ff(1.0f, color[1] + shadetop);
+ coltop[2] = min_ff(1.0f, color[2] + shadetop);
+ coldown[0] = max_ff(0.0f, color[0] + shadedown);
+ coldown[1] = max_ff(0.0f, color[1] + shadedown);
+ coldown[2] = max_ff(0.0f, color[2] + shadedown);
glShadeModel(GL_SMOOTH);
glBegin(mode);
@@ -266,18 +264,18 @@ void uiDrawBoxVerticalShade(int mode, float minx, float miny, float maxx, float
/* mult */
for (a = 0; a < 7; a++) {
- vec[a][0] *= rad; vec[a][1] *= rad;
+ mul_v2_fl(vec[a], rad);
}
/* get current color, needs to be outside of glBegin/End */
glGetFloatv(GL_CURRENT_COLOR, color);
- /* 'shade' defines strength of shading */
- colLeft[0] = color[0] + shadeLeft; if (colLeft[0] > 1.0f) colLeft[0] = 1.0f;
- colLeft[1] = color[1] + shadeLeft; if (colLeft[1] > 1.0f) colLeft[1] = 1.0f;
- colLeft[2] = color[2] + shadeLeft; if (colLeft[2] > 1.0f) colLeft[2] = 1.0f;
- colRight[0] = color[0] + shadeRight; if (colRight[0] < 0.0f) colRight[0] = 0.0f;
- colRight[1] = color[1] + shadeRight; if (colRight[1] < 0.0f) colRight[1] = 0.0f;
- colRight[2] = color[2] + shadeRight; if (colRight[2] < 0.0f) colRight[2] = 0.0f;
+ /* 'shade' defines strength of shading */
+ colLeft[0] = min_ff(1.0f, color[0] + shadeLeft);
+ colLeft[1] = min_ff(1.0f, color[1] + shadeLeft);
+ colLeft[2] = min_ff(1.0f, color[2] + shadeLeft);
+ colRight[0] = max_ff(0.0f, color[0] + shadeRight);
+ colRight[1] = max_ff(0.0f, color[1] + shadeRight);
+ colRight[2] = max_ff(0.0f, color[2] + shadeRight);
glShadeModel(GL_SMOOTH);
glBegin(mode);
@@ -440,8 +438,8 @@ void ui_draw_but_IMAGE(ARegion *UNUSED(ar), uiBut *but, uiWidgetColors *UNUSED(w
//glColor4f(1.0, 0.f, 0.f, 1.f);
//fdrawbox(rect->xmin, rect->ymin, rect->xmax, rect->ymax)
- w = BLI_RCT_SIZE_X(rect);
- h = BLI_RCT_SIZE_Y(rect);
+ w = BLI_rcti_size_x(rect);
+ h = BLI_rcti_size_y(rect);
/* prevent drawing outside widget area */
glGetIntegerv(GL_SCISSOR_BOX, scissor);
glScissor(ar->winrct.xmin + rect->xmin, ar->winrct.ymin + rect->ymin, w, h);
@@ -494,8 +492,8 @@ static void ui_draw_but_CHARTAB(uiBut *but)
charmax = G.charmax = 0xffff;
/* Calculate the size of the button */
- width = abs(BLI_RCT_SIZE_X(rect));
- height = abs(BLI_RCT_SIZE_Y(rect));
+ width = abs(BLI_rcti_size_x(rect));
+ height = abs(BLI_rcti_size_y(rect));
butw = floor(width / 12);
buth = floor(height / 6);
@@ -512,7 +510,7 @@ static void ui_draw_but_CHARTAB(uiBut *but)
if (G.selfont && BKE_vfont_is_builtin(G.selfont) == FALSE) {
/* Is the font file packed, if so then use the packed file */
if (G.selfont->packedfile) {
- pf = G.selfont->packedfile;
+ pf = G.selfont->packedfile;
FTF_SetFont(pf->data, pf->size, 14.0);
}
else {
@@ -601,7 +599,8 @@ static void ui_draw_but_CHARTAB(uiBut *but)
}
/* Calculate the next position and character */
- sx += butw; ex += butw;
+ sx += butw;
+ ex += butw;
cs++;
}
/* Add the y position and reset x position */
@@ -609,7 +608,7 @@ static void ui_draw_but_CHARTAB(uiBut *but)
ey -= buth;
sx = rect->xmin;
ex = rect->xmin + butw;
- }
+ }
glShadeModel(GL_FLAT);
/* Return Font Settings to original */
@@ -633,7 +632,7 @@ static void ui_draw_but_CHARTAB(uiBut *but)
#endif /* WITH_INTERNATIONAL */
#endif
-static void draw_scope_end(rctf *rect, GLint *scissor)
+static void draw_scope_end(const rctf *rect, GLint *scissor)
{
float scaler_x1, scaler_x2;
@@ -643,8 +642,8 @@ static void draw_scope_end(rctf *rect, GLint *scissor)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
/* scale widget */
- scaler_x1 = rect->xmin + BLI_RCT_SIZE_X(rect) / 2 - SCOPE_RESIZE_PAD;
- scaler_x2 = rect->xmin + BLI_RCT_SIZE_X(rect) / 2 + SCOPE_RESIZE_PAD;
+ scaler_x1 = rect->xmin + BLI_rctf_size_x(rect) / 2 - SCOPE_RESIZE_PAD;
+ scaler_x2 = rect->xmin + BLI_rctf_size_x(rect) / 2 + SCOPE_RESIZE_PAD;
glColor4f(0.f, 0.f, 0.f, 0.25f);
fdrawline(scaler_x1, rect->ymin - 4, scaler_x2, rect->ymin - 4);
@@ -733,8 +732,8 @@ void ui_draw_but_HISTOGRAM(ARegion *ar, uiBut *but, uiWidgetColors *UNUSED(wcol)
rect.ymin = (float)recti->ymin + SCOPE_RESIZE_PAD + 2;
rect.ymax = (float)recti->ymax - 1;
- w = BLI_RCT_SIZE_X(&rect);
- h = BLI_RCT_SIZE_Y(&rect) * hist->ymax;
+ w = BLI_rctf_size_x(&rect);
+ h = BLI_rctf_size_y(&rect) * hist->ymax;
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
@@ -806,9 +805,9 @@ void ui_draw_but_WAVEFORM(ARegion *ar, uiBut *but, uiWidgetColors *UNUSED(wcol),
if (scopes->wavefrm_yfac < 0.5f)
scopes->wavefrm_yfac = 0.98f;
- w = BLI_RCT_SIZE_X(&rect) - 7;
- h = BLI_RCT_SIZE_Y(&rect) * scopes->wavefrm_yfac;
- yofs = rect.ymin + (BLI_RCT_SIZE_Y(&rect) - h) / 2.0f;
+ w = BLI_rctf_size_x(&rect) - 7;
+ h = BLI_rctf_size_y(&rect) * scopes->wavefrm_yfac;
+ yofs = rect.ymin + (BLI_rctf_size_y(&rect) - h) / 2.0f;
w3 = w / 3.0f;
/* log scale for alpha */
@@ -955,12 +954,12 @@ void ui_draw_but_WAVEFORM(ARegion *ar, uiBut *but, uiWidgetColors *UNUSED(wcol),
static float polar_to_x(float center, float diam, float ampli, float angle)
{
- return center + diam *ampli *cosf(angle);
+ return center + diam *ampli * cosf(angle);
}
static float polar_to_y(float center, float diam, float ampli, float angle)
{
- return center + diam *ampli *sinf(angle);
+ return center + diam *ampli * sinf(angle);
}
static void vectorscope_draw_target(float centerx, float centery, float diam, const float colf[3])
@@ -1034,8 +1033,8 @@ void ui_draw_but_VECTORSCOPE(ARegion *ar, uiBut *but, uiWidgetColors *UNUSED(wco
rect.ymin = (float)recti->ymin + SCOPE_RESIZE_PAD + 2;
rect.ymax = (float)recti->ymax - 1;
- w = BLI_RCT_SIZE_X(&rect);
- h = BLI_RCT_SIZE_Y(&rect);
+ w = BLI_rctf_size_x(&rect);
+ h = BLI_rctf_size_y(&rect);
centerx = rect.xmin + w / 2;
centery = rect.ymin + h / 2;
diam = (w < h) ? w : h;
@@ -1146,8 +1145,9 @@ void ui_draw_but_COLORBAND(uiBut *but, uiWidgetColors *UNUSED(wcol), rcti *rect)
glBegin(GL_QUAD_STRIP);
glColor4fv(&cbd->r);
- glVertex2fv(v1); glVertex2fv(v2);
-
+ glVertex2fv(v1);
+ glVertex2fv(v2);
+
for (a = 1; a <= sizex; a++) {
pos = ((float)a) / (sizex - 1);
do_colorband(coba, pos, colf);
@@ -1157,7 +1157,8 @@ void ui_draw_but_COLORBAND(uiBut *but, uiWidgetColors *UNUSED(wcol), rcti *rect)
v1[0] = v2[0] = x1 + a;
glColor4fv(colf);
- glVertex2fv(v1); glVertex2fv(v2);
+ glVertex2fv(v1);
+ glVertex2fv(v2);
}
glEnd();
@@ -1220,7 +1221,7 @@ void ui_draw_but_COLORBAND(uiBut *but, uiWidgetColors *UNUSED(wcol), rcti *rect)
glColor3ub(255, 255, 255);
glVertex2fv(v2);
glVertex2fv(v3);
- }
+ }
}
glEnd();
@@ -1244,7 +1245,8 @@ void ui_draw_but_NORMAL(uiBut *but, uiWidgetColors *wcol, rcti *rect)
/* sphere color */
glMaterialfv(GL_FRONT, GL_DIFFUSE, diffn);
- glCullFace(GL_BACK); glEnable(GL_CULL_FACE);
+ glCullFace(GL_BACK);
+ glEnable(GL_CULL_FACE);
/* disable blender light */
for (a = 0; a < 8; a++) {
@@ -1267,12 +1269,12 @@ void ui_draw_but_NORMAL(uiBut *but, uiWidgetColors *wcol, rcti *rect)
/* transform to button */
glPushMatrix();
- glTranslatef(rect->xmin + 0.5f * BLI_RCT_SIZE_X(rect), rect->ymin + 0.5f * BLI_RCT_SIZE_Y(rect), 0.0f);
+ glTranslatef(rect->xmin + 0.5f * BLI_rcti_size_x(rect), rect->ymin + 0.5f * BLI_rcti_size_y(rect), 0.0f);
- if (BLI_RCT_SIZE_X(rect) < BLI_RCT_SIZE_Y(rect))
- size = BLI_RCT_SIZE_X(rect) / 200.f;
+ if (BLI_rcti_size_x(rect) < BLI_rcti_size_y(rect))
+ size = BLI_rcti_size_x(rect) / 200.f;
else
- size = BLI_RCT_SIZE_Y(rect) / 200.f;
+ size = BLI_rcti_size_y(rect) / 200.f;
glScalef(size, size, size);
@@ -1378,12 +1380,12 @@ void ui_draw_but_CURVE(ARegion *ar, uiBut *but, uiWidgetColors *wcol, rcti *rect
BLI_rcti_isect(&scissor_new, &ar->winrct, &scissor_new);
glScissor(scissor_new.xmin,
scissor_new.ymin,
- BLI_RCT_SIZE_X(&scissor_new),
- BLI_RCT_SIZE_Y(&scissor_new));
+ BLI_rcti_size_x(&scissor_new),
+ BLI_rcti_size_y(&scissor_new));
/* calculate offset and zoom */
- zoomx = (BLI_RCT_SIZE_X(rect) - 2.0f * but->aspect) / BLI_RCT_SIZE_X(&cumap->curr);
- zoomy = (BLI_RCT_SIZE_Y(rect) - 2.0f * but->aspect) / BLI_RCT_SIZE_Y(&cumap->curr);
+ zoomx = (BLI_rcti_size_x(rect) - 2.0f * but->aspect) / BLI_rctf_size_x(&cumap->curr);
+ zoomy = (BLI_rcti_size_y(rect) - 2.0f * but->aspect) / BLI_rctf_size_y(&cumap->curr);
offsx = cumap->curr.xmin - but->aspect / zoomx;
offsy = cumap->curr.ymin - but->aspect / zoomy;
@@ -1561,8 +1563,8 @@ void ui_draw_but_TRACKPREVIEW(ARegion *ar, uiBut *but, uiWidgetColors *UNUSED(wc
rect.ymin = (float)recti->ymin + SCOPE_RESIZE_PAD + 2;
rect.ymax = (float)recti->ymax - 1;
- width = BLI_RCT_SIZE_X(&rect) + 1;
- height = BLI_RCT_SIZE_Y(&rect);
+ width = BLI_rctf_size_x(&rect) + 1;
+ height = BLI_rctf_size_y(&rect);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
@@ -1637,8 +1639,8 @@ void ui_draw_but_TRACKPREVIEW(ARegion *ar, uiBut *but, uiWidgetColors *UNUSED(wc
glTranslatef(rect.xmin + track_pos[0], rect.ymin + track_pos[1], 0.f);
glScissor(ar->winrct.xmin + rect.xmin,
ar->winrct.ymin + rect.ymin,
- BLI_RCT_SIZE_X(&rect),
- BLI_RCT_SIZE_Y(&rect));
+ BLI_rctf_size_x(&rect),
+ BLI_rctf_size_y(&rect));
for (a = 0; a < 2; a++) {
if (a == 1) {
@@ -1705,7 +1707,7 @@ static void ui_shadowbox(float minx, float miny, float maxx, float maxy, float s
glVertex2f(maxx, miny - shadsize);
glEnd();
- /* bottom quad */
+ /* bottom quad */
glBegin(GL_POLYGON);
glColor4ub(0, 0, 0, alpha);
glVertex2f(minx + 0.3f * shadsize, miny);
@@ -1729,7 +1731,7 @@ void uiDrawBoxShadow(unsigned char alpha, float minx, float miny, float maxx, fl
}
-void ui_dropshadow(rctf *rct, float radius, float aspect, float alpha, int UNUSED(select))
+void ui_dropshadow(const rctf *rct, float radius, float aspect, float alpha, int UNUSED(select))
{
int i;
float rad;
@@ -1738,8 +1740,8 @@ void ui_dropshadow(rctf *rct, float radius, float aspect, float alpha, int UNUSE
glEnable(GL_BLEND);
- if (radius > (BLI_RCT_SIZE_Y(rct) - 10.0f) / 2.0f)
- rad = (BLI_RCT_SIZE_Y(rct) - 10.0f) / 2.0f;
+ if (radius > (BLI_rctf_size_y(rct) - 10.0f) / 2.0f)
+ rad = (BLI_rctf_size_y(rct) - 10.0f) / 2.0f;
else
rad = radius;
diff --git a/source/blender/editors/interface/interface_handlers.c b/source/blender/editors/interface/interface_handlers.c
index f7b22098835..6d262daab12 100644
--- a/source/blender/editors/interface/interface_handlers.c
+++ b/source/blender/editors/interface/interface_handlers.c
@@ -78,6 +78,9 @@
#include "WM_api.h"
#include "WM_types.h"
+/* place the mouse at the scaled down location when un-grabbing */
+#define USE_CONT_MOUSE_CORRECT
+
/* proto */
static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to);
static void ui_add_link(bContext *C, uiBut *from, uiBut *to);
@@ -152,6 +155,12 @@ typedef struct uiHandleButtonData {
float dragf, dragfstart;
CBData *dragcbd;
+#ifdef USE_CONT_MOUSE_CORRECT
+ /* when ungrabbing buttons which are #ui_is_a_warp_but(), we may want to position them
+ * FLT_MAX signifies do-nothing, use #ui_block_to_window_fl() to get this into a usable space */
+ float ungrab_mval[2];
+#endif
+
/* menu open (watch uiFreeActiveButtons) */
uiPopupBlockHandle *menu;
int menuretval;
@@ -695,12 +704,14 @@ static int ui_but_mouse_inside_icon(uiBut *but, ARegion *ar, wmEvent *event)
BLI_rcti_rctf_copy(&rect, &but->rect);
- if (but->imb) ; /* use button size itself */
+ if (but->imb) {
+ /* use button size itself */
+ }
else if (but->flag & UI_ICON_LEFT) {
- rect.xmax = rect.xmin + (BLI_RCT_SIZE_Y(&rect));
+ rect.xmax = rect.xmin + (BLI_rcti_size_y(&rect));
}
else {
- int delta = BLI_RCT_SIZE_X(&rect) - BLI_RCT_SIZE_Y(&rect);
+ int delta = BLI_rcti_size_x(&rect) - BLI_rcti_size_y(&rect);
rect.xmin += delta / 2;
rect.xmax -= delta / 2;
}
@@ -721,7 +732,7 @@ static int ui_but_start_drag(bContext *C, uiBut *but, uiHandleButtonData *data,
drag = WM_event_start_drag(C, but->icon, but->dragtype, but->dragpoin, ui_get_but_val(but));
if (but->imb)
- WM_event_drag_image(drag, but->imb, but->imb_scale, BLI_RCT_SIZE_X(&but->rect), BLI_RCT_SIZE_Y(&but->rect));
+ WM_event_drag_image(drag, but->imb, but->imb_scale, BLI_rctf_size_x(&but->rect), BLI_rctf_size_y(&but->rect));
return 1;
}
@@ -763,7 +774,7 @@ static void ui_delete_active_linkline(uiBlock *block)
(*(link->ppoin))[b] = (*(link->ppoin))[a];
b++;
}
- }
+ }
(*(link->totlink))--;
}
}
@@ -808,6 +819,8 @@ static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to)
uiLink *link = from->link;
+ PointerRNA props_ptr, object_ptr;
+
if (link->ppoin)
sens_from_links = (bController ***)(link->ppoin);
else return;
@@ -836,9 +849,15 @@ static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to)
/* only works if the sensor and the actuator are from the same object */
if (!act_iter) return;
+
+ /* in case the linked controller is not the active one */
+ RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr);
+
+ WM_operator_properties_create(&props_ptr, "LOGIC_OT_controller_add");
+ RNA_string_set(&props_ptr, "object", ob->id.name + 2);
/* (3) add a new controller */
- if (WM_operator_name_call(C, "LOGIC_OT_controller_add", WM_OP_EXEC_DEFAULT, NULL) & OPERATOR_FINISHED) {
+ if (WM_operator_name_call(C, "LOGIC_OT_controller_add", WM_OP_EXEC_DEFAULT, &props_ptr) & OPERATOR_FINISHED) {
cont = (bController *)ob->controllers.last;
cont->type = CONT_LOGIC_AND; /* Quick fix to make sure we always have an AND controller. It might be nicer to make sure the operator gives us the right one though... */
@@ -858,6 +877,7 @@ static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to)
MEM_freeN(tmp_but->link);
MEM_freeN(tmp_but);
}
+ WM_operator_properties_free(&props_ptr);
}
static void ui_add_link(bContext *C, uiBut *from, uiBut *to)
@@ -1043,7 +1063,7 @@ static void ui_apply_button(bContext *C, uiBlock *block, uiBut *but, uiHandleBut
break;
case HSVSLI:
break;
- case TOG3:
+ case TOG3:
ui_apply_but_TOG3(C, but, data);
break;
case MENU:
@@ -1089,10 +1109,10 @@ static void ui_apply_button(bContext *C, uiBlock *block, uiBut *but, uiHandleBut
case INLINK:
ui_apply_but_LINK(C, but, data);
break;
- case BUT_IMAGE:
+ case BUT_IMAGE:
ui_apply_but_IMAGE(C, but, data);
break;
- case HISTOGRAM:
+ case HISTOGRAM:
ui_apply_but_HISTOGRAM(C, but, data);
break;
case WAVEFORM:
@@ -1166,7 +1186,9 @@ static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data,
/* numeric value */
if (ELEM4(but->type, NUM, NUMABS, NUMSLI, HSVSLI)) {
- if (but->poin == NULL && but->rnapoin.data == NULL) ;
+ if (but->poin == NULL && but->rnapoin.data == NULL) {
+ /* pass */
+ }
else if (mode == 'c') {
ui_get_but_string(but, buf, sizeof(buf));
WM_clipboard_text_set(buf, 0);
@@ -1187,7 +1209,9 @@ static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data,
else if (but->type == COLOR) {
float rgb[3];
- if (but->poin == NULL && but->rnapoin.data == NULL) ;
+ if (but->poin == NULL && but->rnapoin.data == NULL) {
+ /* pass */
+ }
else if (mode == 'c') {
ui_get_but_vectorf(but, rgb);
@@ -1216,7 +1240,9 @@ static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data,
else if (ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
uiHandleButtonData *active_data = but->active;
- if (but->poin == NULL && but->rnapoin.data == NULL) ;
+ if (but->poin == NULL && but->rnapoin.data == NULL) {
+ /* pass */
+ }
else if (mode == 'c') {
button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
BLI_strncpy(buf, active_data->str, UI_MAX_DRAW_STR);
@@ -1273,6 +1299,71 @@ static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data,
}
}
+/* ************************ password text ******************************
+ *
+ * Functions to convert password strings that should not be displayed
+ * to asterisk representation (e.g. mysecretpasswd -> *************)
+ *
+ * It converts every UTF-8 character to an asterisk, and also remaps
+ * the cursor position and selection start/end.
+ *
+ * Note: remaping is used, because password could contain UTF-8 characters.
+ *
+ */
+
+static int ui_text_position_from_hidden(uiBut *but, int pos)
+{
+ const char *strpos;
+ int i;
+
+ for (i = 0, strpos = but->drawstr; i < pos; i++)
+ strpos = BLI_str_find_next_char_utf8(strpos, NULL);
+
+ return (strpos - but->drawstr);
+}
+
+static int ui_text_position_to_hidden(uiBut *but, int pos)
+{
+ return BLI_strnlen_utf8(but->drawstr, pos);
+}
+
+void ui_button_text_password_hide(char password_str[UI_MAX_DRAW_STR], uiBut *but, int restore)
+{
+ if (!(but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_PASSWORD))
+ return;
+
+ if (restore) {
+ /* restore original string */
+ BLI_strncpy(but->drawstr, password_str, UI_MAX_DRAW_STR);
+
+ /* remap cursor positions */
+ if (but->pos >= 0) {
+ but->pos = ui_text_position_from_hidden(but, but->pos);
+ but->selsta = ui_text_position_from_hidden(but, but->selsta);
+ but->selend = ui_text_position_from_hidden(but, but->selend);
+ }
+ }
+ else {
+ /* convert text to hidden test using asterisks (e.g. pass -> ****) */
+ int i, len = BLI_strlen_utf8(but->drawstr);
+
+ /* remap cursor positions */
+ if (but->pos >= 0) {
+ but->pos = ui_text_position_to_hidden(but, but->pos);
+ but->selsta = ui_text_position_to_hidden(but, but->selsta);
+ but->selend = ui_text_position_to_hidden(but, but->selend);
+ }
+
+ /* save original string */
+ BLI_strncpy(password_str, but->drawstr, UI_MAX_DRAW_STR);
+
+ for (i = 0; i < len; i++)
+ but->drawstr[i] = '*';
+ but->drawstr[i] = '\0';
+ }
+}
+
+
/* ************* in-button text selection/editing ************* */
@@ -1296,20 +1387,22 @@ static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, sho
uiStyle *style = UI_GetStyle(); // XXX pass on as arg
uiFontStyle *fstyle = &style->widget;
int startx = but->rect.xmin;
- char *origstr;
+ char *origstr, password_str[UI_MAX_DRAW_STR];
uiStyleFontSet(fstyle);
if (fstyle->kerning == 1) /* for BLF_width */
BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
+ ui_button_text_password_hide(password_str, but, FALSE);
+
origstr = MEM_callocN(sizeof(char) * data->maxlen, "ui_textedit origstr");
BLI_strncpy(origstr, but->drawstr, data->maxlen);
/* XXX solve generic */
if (but->type == NUM || but->type == NUMSLI)
- startx += (int)(0.5f * (BLI_RCT_SIZE_Y(&but->rect)));
+ startx += (int)(0.5f * (BLI_rctf_size_y(&but->rect)));
else if (ELEM(but->type, TEX, SEARCH_MENU)) {
startx += 5;
if (but->flag & UI_HAS_ICON)
@@ -1317,7 +1410,7 @@ static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, sho
}
/* mouse dragged outside the widget to the left */
- if (x < startx && but->ofs > 0) {
+ if (x < startx && but->ofs > 0) {
int i = but->ofs;
origstr[but->ofs] = 0;
@@ -1350,7 +1443,7 @@ static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, sho
while (TRUE) {
/* XXX does not take zoom level into account */
- cdist = startx + aspect_sqrt *BLF_width(fstyle->uifont_id, origstr + but->ofs);
+ cdist = startx + aspect_sqrt * BLF_width(fstyle->uifont_id, origstr + but->ofs);
/* check if position is found */
if (cdist < x) {
@@ -1381,18 +1474,20 @@ static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, sho
if (fstyle->kerning == 1)
BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
+ ui_button_text_password_hide(password_str, but, TRUE);
+
MEM_freeN(origstr);
}
static void ui_textedit_set_cursor_select(uiBut *but, uiHandleButtonData *data, short x)
{
- if (x > data->selstartx) data->selextend = EXTEND_RIGHT;
+ if (x > data->selstartx) data->selextend = EXTEND_RIGHT;
else if (x < data->selstartx) data->selextend = EXTEND_LEFT;
ui_textedit_set_cursor_pos(but, data, x);
- if (data->selextend == EXTEND_RIGHT) but->selend = but->pos;
- if (data->selextend == EXTEND_LEFT) but->selsta = but->pos;
+ if (data->selextend == EXTEND_RIGHT) but->selend = but->pos;
+ else if (data->selextend == EXTEND_LEFT) but->selsta = but->pos;
ui_check_but(but);
}
@@ -1561,7 +1656,7 @@ static int ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int directio
but->pos -= step;
changed = 1;
}
- }
+ }
}
return changed;
@@ -1596,6 +1691,7 @@ static int ui_textedit_copypaste(uiBut *but, uiHandleButtonData *data, int paste
/* paste */
if (paste) {
+ /* TODO, ensure UTF8 ui_is_but_utf8() - campbell */
/* extract the first line from the clipboard */
p = pbuf = WM_clipboard_text_get(0);
@@ -1649,7 +1745,7 @@ static int ui_textedit_copypaste(uiBut *but, uiHandleButtonData *data, int paste
if (cut)
if ((but->selend - but->selsta) > 0)
changed = ui_textedit_delete_selection(but, data);
- }
+ }
return changed;
}
@@ -1688,7 +1784,7 @@ static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
/* optional searchbox */
if (but->type == SEARCH_MENU) {
data->searchbox = ui_searchbox_create(C, data->region, but);
- ui_searchbox_update(C, data->searchbox, but, 1); /* 1= reset */
+ ui_searchbox_update(C, data->searchbox, but, 1); /* 1 = reset */
}
ui_check_but(but);
@@ -1955,8 +2051,12 @@ static void ui_do_but_textedit(bContext *C, uiBlock *block, uiBut *but, uiHandle
if (changed) {
/* only update when typing for TAB key */
- if (update && data->interactive) ui_apply_button(C, block, but, data, 1);
- else ui_check_but(but);
+ if (update && data->interactive) {
+ ui_apply_button(C, block, but, data, 1);
+ }
+ else {
+ ui_check_but(but);
+ }
but->changed = TRUE;
if (data->searchbox)
@@ -2047,8 +2147,12 @@ static void ui_numedit_end(uiBut *but, uiHandleButtonData *data)
static void ui_numedit_apply(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
{
- if (data->interactive) ui_apply_button(C, block, but, data, 1);
- else ui_check_but(but);
+ if (data->interactive) {
+ ui_apply_button(C, block, but, data, 1);
+ }
+ else {
+ ui_check_but(but);
+ }
ED_region_tag_redraw(data->region);
}
@@ -2122,7 +2226,7 @@ static void ui_blockopen_begin(bContext *C, uiBut *but, uiHandleButtonData *data
}
/* this makes adjacent blocks auto open from now on */
- //if (but->block->auto_open ==0 ) but->block->auto_open = 1;
+ //if (but->block->auto_open == 0) but->block->auto_open = 1;
}
static void ui_blockopen_end(bContext *C, uiBut *but, uiHandleButtonData *data)
@@ -2140,6 +2244,16 @@ static void ui_blockopen_end(bContext *C, uiBut *but, uiHandleButtonData *data)
}
}
+int ui_button_open_menu_direction(uiBut *but)
+{
+ uiHandleButtonData *data = but->active;
+
+ if (data && data->menu)
+ return data->menu->direction;
+
+ return 0;
+}
+
/* ***************** events for different button types *************** */
static int ui_do_but_BUT(bContext *C, uiBut *but, uiHandleButtonData *data, wmEvent *event)
@@ -2209,7 +2323,7 @@ static int ui_do_but_HOTKEYEVT(bContext *C, uiBut *but, uiHandleButtonData *data
ED_region_tag_redraw(data->region);
if (event->val == KM_PRESS) {
- if (ISHOTKEY(event->type)) {
+ if (ISHOTKEY(event->type)) {
if (WM_key_event_string(event->type)[0])
ui_set_but_val(but, event->type);
@@ -2260,7 +2374,9 @@ static int ui_do_but_TEX(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
{
if (data->state == BUTTON_STATE_HIGHLIGHT) {
if (ELEM(event->type, LEFTMOUSE, EVT_BUT_OPEN) && event->val == KM_PRESS) {
- if (but->dt == UI_EMBOSSN && !event->ctrl) ;
+ if (but->dt == UI_EMBOSSN && !event->ctrl) {
+ /* pass */
+ }
else {
button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
return WM_UI_HANDLER_BREAK;
@@ -2373,14 +2489,14 @@ static float ui_numedit_apply_snapf(uiBut *but, float tempf, float softmin, floa
}
if (snap == 1) {
- if (softrange < 2.10f) tempf = 0.1f * floorf(10.0f * tempf);
+ if (softrange < 2.10f) tempf = 0.1f * floorf(10.0f * tempf);
else if (softrange < 21.0f) tempf = floorf(tempf);
- else tempf = 10.0f * floorf(tempf / 10.0f);
+ else tempf = 10.0f * floorf(tempf / 10.0f);
}
else if (snap == 2) {
- if (softrange < 2.10f) tempf = 0.01f * floorf(100.0f * tempf);
- else if (softrange < 21.0f) tempf = 0.1f * floorf(10.0f * tempf);
- else tempf = floor(tempf);
+ if (softrange < 2.10f) tempf = 0.01f * floorf(100.0f * tempf);
+ else if (softrange < 21.0f) tempf = 0.1f * floorf(10.0f * tempf);
+ else tempf = floor(tempf);
}
if (fac != 1.0f)
@@ -2459,9 +2575,9 @@ static int ui_numedit_but_NUM(uiBut *but, uiHandleButtonData *data, float fac, i
}
}
else {
- if (softrange > 256) fac = 1.0; /* 1px == 1 */
- else if (softrange > 32) fac = 1.0 / 2.0; /* 2px == 1 */
- else fac = 1.0 / 16.0; /* 16px == 1? */
+ if (softrange > 256) fac = 1.0; /* 1px == 1 */
+ else if (softrange > 32) fac = 1.0 / 2.0; /* 2px == 1 */
+ else fac = 1.0 / 16.0; /* 16px == 1? */
temp = data->startvalue + (((double)mx - data->dragstartx) * (double)fac);
temp = ui_numedit_apply_snap(temp, softmin, softmax, snap);
@@ -2493,10 +2609,9 @@ static int ui_numedit_but_NUM(uiBut *but, uiHandleButtonData *data, float fac, i
deler = 500;
if (!ui_is_but_float(but)) {
/* prevent large ranges from getting too out of control */
- if (softrange > 600) deler = powf(softrange, 0.75);
-
- if (softrange < 100) deler = 200.0;
- if (softrange < 25) deler = 50.0;
+ if (softrange > 600) deler = powf(softrange, 0.75);
+ else if (softrange < 100) deler = 200.0;
+ else if (softrange < 25) deler = 50.0;
}
deler /= fac;
@@ -2582,8 +2697,9 @@ static int ui_do_but_NUM(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
retval = WM_UI_HANDLER_BREAK;
}
- else if (ELEM(event->type, PADENTER, RETKEY) && event->val == KM_PRESS)
+ else if (ELEM(event->type, PADENTER, RETKEY) && event->val == KM_PRESS) {
click = 1;
+ }
else if (event->type == MINUSKEY && event->val == KM_PRESS) {
button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
data->value = -data->value;
@@ -2611,7 +2727,7 @@ static int ui_do_but_NUM(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
fac = 1.0f;
if (event->shift) fac /= 10.0f;
- if (event->alt) fac /= 20.0f;
+ if (event->alt) fac /= 20.0f;
snap = (event->ctrl) ? (event->shift) ? 2 : 1 : 0;
@@ -2639,7 +2755,7 @@ static int ui_do_but_NUM(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
softmax = but->softmax;
if (!ui_is_but_float(but)) {
- if (mx < (but->rect.xmin + BLI_RCT_SIZE_X(&but->rect) / 3 - 3)) {
+ if (mx < (but->rect.xmin + BLI_rctf_size_x(&but->rect) / 3 - 3)) {
button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
temp = (int)data->value - 1;
@@ -2650,7 +2766,7 @@ static int ui_do_but_NUM(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
button_activate_state(C, but, BUTTON_STATE_EXIT);
}
- else if (mx > (but->rect.xmin + (2 * BLI_RCT_SIZE_X(&but->rect) / 3) + 3)) {
+ else if (mx > (but->rect.xmin + (2 * BLI_rctf_size_x(&but->rect) / 3) + 3)) {
button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
temp = (int)data->value + 1;
@@ -2661,11 +2777,12 @@ static int ui_do_but_NUM(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
button_activate_state(C, but, BUTTON_STATE_EXIT);
}
- else
+ else {
button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
+ }
}
else {
- if (mx < (but->rect.xmin + BLI_RCT_SIZE_X(&but->rect) / 3 - 3)) {
+ if (mx < (but->rect.xmin + BLI_rctf_size_x(&but->rect) / 3 - 3)) {
button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
tempf = (float)data->value - 0.01f * but->a1;
@@ -2674,7 +2791,7 @@ static int ui_do_but_NUM(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
button_activate_state(C, but, BUTTON_STATE_EXIT);
}
- else if (mx > but->rect.xmin + (2 * (BLI_RCT_SIZE_X(&but->rect) / 3) + 3)) {
+ else if (mx > but->rect.xmin + (2 * (BLI_rctf_size_x(&but->rect) / 3) + 3)) {
button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
tempf = (float)data->value + 0.01f * but->a1;
@@ -2683,8 +2800,9 @@ static int ui_do_but_NUM(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
button_activate_state(C, but, BUTTON_STATE_EXIT);
}
- else
+ else {
button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
+ }
}
retval = WM_UI_HANDLER_BREAK;
@@ -2702,14 +2820,20 @@ static int ui_numedit_but_SLI(uiBut *but, uiHandleButtonData *data, const short
softmax = but->softmax;
softrange = softmax - softmin;
- if (but->type == NUMSLI) deler = (BLI_RCT_SIZE_X(&but->rect) - 5.0f * but->aspect);
- else if (but->type == HSVSLI) deler = (BLI_RCT_SIZE_X(&but->rect) / 2.0f - 5.0f * but->aspect);
+ if (but->type == NUMSLI) {
+ deler = (BLI_rctf_size_x(&but->rect) - 5.0f * but->aspect);
+ }
+ else if (but->type == HSVSLI) {
+ deler = (BLI_rctf_size_x(&but->rect) / 2.0f - 5.0f * but->aspect);
+ }
else if (but->type == SCROLL) {
- int horizontal = (BLI_RCT_SIZE_X(&but->rect) > BLI_RCT_SIZE_Y(&but->rect));
- float size = (horizontal) ? BLI_RCT_SIZE_X(&but->rect) : -BLI_RCT_SIZE_Y(&but->rect);
+ int horizontal = (BLI_rctf_size_x(&but->rect) > BLI_rctf_size_y(&but->rect));
+ float size = (horizontal) ? BLI_rctf_size_x(&but->rect) : -BLI_rctf_size_y(&but->rect);
deler = size * (but->softmax - but->softmin) / (but->softmax - but->softmin + but->a1);
}
- else deler = (BLI_RCT_SIZE_X(&but->rect) - 5.0f * but->aspect);
+ else {
+ deler = (BLI_rctf_size_x(&but->rect) - 5.0f * but->aspect);
+ }
f = (float)(mx - data->dragstartx) / deler + data->dragfstart;
@@ -2721,19 +2845,21 @@ static int ui_numedit_but_SLI(uiBut *but, uiHandleButtonData *data, const short
temp = floorf(tempf + 0.5f);
if (ctrl) {
- if (tempf == softmin || tempf == softmax) ;
+ if (tempf == softmin || tempf == softmax) {
+ /* pass */
+ }
else if (ui_is_but_float(but)) {
if (shift) {
- if (tempf == softmin || tempf == softmax) ;
+ if (tempf == softmin || tempf == softmax) {}
else if (softmax - softmin < 2.10f) tempf = 0.01f * floorf(100.0f * tempf);
- else if (softmax - softmin < 21.0f) tempf = 0.1f * floorf(10.0f * tempf);
- else tempf = floorf(tempf);
+ else if (softmax - softmin < 21.0f) tempf = 0.1f * floorf(10.0f * tempf);
+ else tempf = floorf(tempf);
}
else {
- if (softmax - softmin < 2.10f) tempf = 0.1f * floorf(10.0f * tempf);
+ if (softmax - softmin < 2.10f) tempf = 0.1f * floorf(10.0f * tempf);
else if (softmax - softmin < 21.0f) tempf = floorf(tempf);
- else tempf = 10.0f * floorf(tempf / 10.0f);
+ else tempf = 10.0f * floorf(tempf / 10.0f);
}
}
else {
@@ -2792,7 +2918,7 @@ static int ui_do_but_SLI(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
}
/* alt-click on sides to get "arrows" like in NUM buttons, and match wheel usage above */
else if (event->type == LEFTMOUSE && event->alt) {
- int halfpos = BLI_RCT_CENTER_X(&but->rect);
+ int halfpos = BLI_rctf_cent_x(&but->rect);
click = 2;
if (mx < halfpos)
mx = but->rect.xmin;
@@ -2805,8 +2931,9 @@ static int ui_do_but_SLI(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
retval = WM_UI_HANDLER_BREAK;
}
- else if (ELEM(event->type, PADENTER, RETKEY) && event->val == KM_PRESS)
+ else if (ELEM(event->type, PADENTER, RETKEY) && event->val == KM_PRESS) {
click = 1;
+ }
else if (event->type == MINUSKEY && event->val == KM_PRESS) {
button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
data->value = -data->value;
@@ -2859,12 +2986,12 @@ static int ui_do_but_SLI(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
#if 0
if (but->type == SLI) {
- f = (float)(mx - but->rect.xmin) / (BLI_RCT_SIZE_X(&but->rect)); /* same as below */
+ f = (float)(mx - but->rect.xmin) / (BLI_rctf_size_x(&but->rect)); /* same as below */
}
else
#endif
{
- f = (float)(mx - but->rect.xmin) / (BLI_RCT_SIZE_X(&but->rect));
+ f = (float)(mx - but->rect.xmin) / (BLI_rctf_size_x(&but->rect));
}
f = softmin + f * softrange;
@@ -2877,7 +3004,7 @@ static int ui_do_but_SLI(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
data->value = temp;
else
data->cancel = TRUE;
- }
+ }
else {
if (f < tempf) tempf -= 0.01f;
else tempf += 0.01f;
@@ -2903,9 +3030,9 @@ static int ui_do_but_SLI(bContext *C, uiBlock *block, uiBut *but, uiHandleButton
static int ui_do_but_SCROLL(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, wmEvent *event)
{
- int mx, my /*, click= 0 */;
+ int mx, my /*, click = 0 */;
int retval = WM_UI_HANDLER_CONTINUE;
- int horizontal = (BLI_RCT_SIZE_X(&but->rect) > BLI_RCT_SIZE_Y(&but->rect));
+ int horizontal = (BLI_rctf_size_x(&but->rect) > BLI_rctf_size_y(&but->rect));
mx = event->x;
my = event->y;
@@ -3063,7 +3190,7 @@ static int ui_numedit_but_NORMAL(uiBut *but, uiHandleButtonData *data, int mx, i
* else we'll get a harmless but annoying jump when first clicking */
fp = data->origvec;
- rad = BLI_RCT_SIZE_X(&but->rect);
+ rad = BLI_rctf_size_x(&but->rect);
radsq = rad * rad;
if (fp[2] > 0.0f) {
@@ -3076,7 +3203,9 @@ static int ui_numedit_but_NORMAL(uiBut *but, uiHandleButtonData *data, int mx, i
mdx = 2.0f * mrad * fp[0] - (rad * fp[0]);
mdy = 2.0f * mrad * fp[1] - (rad * fp[1]);
}
- else mdx = mdy = 0;
+ else {
+ mdx = mdy = 0;
+ }
dx = (float)(mx + mdx - data->dragstartx);
dy = (float)(my + mdy - data->dragstarty);
@@ -3140,8 +3269,9 @@ static int ui_do_but_NORMAL(bContext *C, uiBlock *block, uiBut *but, uiHandleBut
ui_numedit_apply(C, block, but, data);
}
}
- else if (event->type == LEFTMOUSE && event->val != KM_PRESS)
+ else if (event->type == LEFTMOUSE && event->val != KM_PRESS) {
button_activate_state(C, but, BUTTON_STATE_EXIT);
+ }
return WM_UI_HANDLER_BREAK;
}
@@ -3160,6 +3290,15 @@ static int ui_numedit_but_HSVCUBE(uiBut *but, uiHandleButtonData *data, int mx,
ui_mouse_scale_warp(data, mx, my, &mx_fl, &my_fl, shift);
+#ifdef USE_CONT_MOUSE_CORRECT
+ if (ui_is_a_warp_but(but)) {
+ /* OK but can go outside bounds */
+ data->ungrab_mval[0] = mx_fl;
+ data->ungrab_mval[1] = my_fl;
+ BLI_rctf_clamp_pt_v(&but->rect, data->ungrab_mval);
+ }
+#endif
+
if (but->rnaprop) {
if (RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
color_profile = FALSE;
@@ -3173,8 +3312,8 @@ static int ui_numedit_but_HSVCUBE(uiBut *but, uiHandleButtonData *data, int mx,
rgb_to_hsv_compat_v(rgb, hsv);
/* relative position within box */
- x = ((float)mx_fl - but->rect.xmin) / BLI_RCT_SIZE_X(&but->rect);
- y = ((float)my_fl - but->rect.ymin) / BLI_RCT_SIZE_Y(&but->rect);
+ x = ((float)mx_fl - but->rect.xmin) / BLI_rctf_size_x(&but->rect);
+ y = ((float)my_fl - but->rect.ymin) / BLI_rctf_size_y(&but->rect);
CLAMP(x, 0.0f, 1.0f);
CLAMP(y, 0.0f, 1.0f);
@@ -3266,7 +3405,7 @@ static void ui_ndofedit_but_HSVCUBE(uiBut *but, uiHandleButtonData *data, wmNDOF
case UI_GRAD_V:
hsv[2] += ndof->ry * sensitivity;
break;
- case UI_GRAD_V_ALT:
+ case UI_GRAD_V_ALT:
/* vertical 'value' strip */
/* exception only for value strip - use the range set in but->min/max */
@@ -3364,8 +3503,9 @@ static int ui_do_but_HSVCUBE(bContext *C, uiBlock *block, uiBut *but, uiHandleBu
ui_numedit_apply(C, block, but, data);
}
}
- else if (event->type == LEFTMOUSE && event->val != KM_PRESS)
+ else if (event->type == LEFTMOUSE && event->val != KM_PRESS) {
button_activate_state(C, but, BUTTON_STATE_EXIT);
+ }
return WM_UI_HANDLER_BREAK;
}
@@ -3383,6 +3523,22 @@ static int ui_numedit_but_HSVCIRCLE(uiBut *but, uiHandleButtonData *data, float
ui_mouse_scale_warp(data, mx, my, &mx_fl, &my_fl, shift);
+#ifdef USE_CONT_MOUSE_CORRECT
+ if (ui_is_a_warp_but(but)) {
+ /* OK but can go outside bounds */
+ data->ungrab_mval[0] = mx_fl;
+ data->ungrab_mval[1] = my_fl;
+ { /* clamp */
+ const float radius = min_ff(BLI_rctf_size_x(&but->rect), BLI_rctf_size_y(&but->rect)) / 2.0f;
+ const float cent[2] = {BLI_rctf_cent_x(&but->rect), BLI_rctf_cent_y(&but->rect)};
+ const float len = len_v2v2(cent, data->ungrab_mval);
+ if (len > radius) {
+ dist_ensure_v2_v2fl(data->ungrab_mval, cent, radius);
+ }
+ }
+ }
+#endif
+
BLI_rcti_rctf_copy(&rect, &but->rect);
ui_get_but_vectorf(but, rgb);
@@ -3575,7 +3731,7 @@ static int ui_numedit_but_COLORBAND(uiBut *but, uiHandleButtonData *data, int mx
if (data->draglastx == mx)
return changed;
- dx = ((float)(mx - data->draglastx)) / BLI_RCT_SIZE_X(&but->rect);
+ dx = ((float)(mx - data->draglastx)) / BLI_rctf_size_x(&but->rect);
data->dragcbd->pos += dx;
CLAMP(data->dragcbd->pos, 0.0f, 1.0f);
@@ -3604,7 +3760,7 @@ static int ui_do_but_COLORBAND(bContext *C, uiBlock *block, uiBut *but, uiHandle
if (event->ctrl) {
/* insert new key on mouse location */
- float pos = ((float)(mx - but->rect.xmin)) / BLI_RCT_SIZE_X(&but->rect);
+ float pos = ((float)(mx - but->rect.xmin)) / BLI_rctf_size_x(&but->rect);
colorband_element_add(coba, pos);
button_activate_state(C, but, BUTTON_STATE_EXIT);
}
@@ -3616,7 +3772,7 @@ static int ui_do_but_COLORBAND(bContext *C, uiBlock *block, uiBut *but, uiHandle
/* activate new key when mouse is close */
for (a = 0, cbd = coba->data; a < coba->tot; a++, cbd++) {
- xco = but->rect.xmin + (cbd->pos * BLI_RCT_SIZE_X(&but->rect));
+ xco = but->rect.xmin + (cbd->pos * BLI_rctf_size_x(&but->rect));
xco = ABS(xco - mx);
if (a == coba->cur) xco += 5; // selected one disadvantage
if (xco < mindist) {
@@ -3639,8 +3795,9 @@ static int ui_do_but_COLORBAND(bContext *C, uiBlock *block, uiBut *but, uiHandle
ui_numedit_apply(C, block, but, data);
}
}
- else if (event->type == LEFTMOUSE && event->val != KM_PRESS)
+ else if (event->type == LEFTMOUSE && event->val != KM_PRESS) {
button_activate_state(C, but, BUTTON_STATE_EXIT);
+ }
return WM_UI_HANDLER_BREAK;
}
@@ -3657,10 +3814,10 @@ static int ui_numedit_but_CURVE(uiBut *but, uiHandleButtonData *data, int snap,
float fx, fy, zoomx, zoomy /*, offsx, offsy */ /* UNUSED */;
int a, changed = 0;
- zoomx = BLI_RCT_SIZE_X(&but->rect) / BLI_RCT_SIZE_X(&cumap->curr);
- zoomy = BLI_RCT_SIZE_Y(&but->rect) / BLI_RCT_SIZE_Y(&cumap->curr);
- /* offsx= cumap->curr.xmin; */
- /* offsy= cumap->curr.ymin; */
+ zoomx = BLI_rctf_size_x(&but->rect) / BLI_rctf_size_x(&cumap->curr);
+ zoomy = BLI_rctf_size_y(&but->rect) / BLI_rctf_size_y(&cumap->curr);
+ /* offsx = cumap->curr.xmin; */
+ /* offsy = cumap->curr.ymin; */
if (snap) {
float d[2];
@@ -3673,9 +3830,10 @@ static int ui_numedit_but_CURVE(uiBut *but, uiHandleButtonData *data, int snap,
}
if (data->dragsel != -1) {
+ CurveMapPoint *cmp_last = NULL;
const float mval_factor = ui_mouse_scale_warp_factor(shift);
int moved_point = 0; /* for ctrl grid, can't use orig coords because of sorting */
-
+
fx = (mx - data->draglastx) / zoomx;
fy = (my - data->draglasty) / zoomy;
@@ -3693,6 +3851,8 @@ static int ui_numedit_but_CURVE(uiBut *but, uiHandleButtonData *data, int snap,
}
if (cmp[a].x != origx || cmp[a].y != origy)
moved_point = 1;
+
+ cmp_last = &cmp[a];
}
}
@@ -3702,6 +3862,18 @@ static int ui_numedit_but_CURVE(uiBut *but, uiHandleButtonData *data, int snap,
data->draglastx = mx;
data->draglasty = my;
changed = 1;
+
+#ifdef USE_CONT_MOUSE_CORRECT
+ /* note: using 'cmp_last' is weak since there may be multiple points selected,
+ * but in practice this isnt really an issue */
+ if (ui_is_a_warp_but(but)) {
+ /* OK but can go outside bounds */
+ data->ungrab_mval[0] = but->rect.xmin + ((cmp_last->x - cumap->curr.xmin) * zoomx);
+ data->ungrab_mval[1] = but->rect.ymin + ((cmp_last->y - cumap->curr.ymin) * zoomy);
+ BLI_rctf_clamp_pt_v(&but->rect, data->ungrab_mval);
+ }
+#endif
+
}
data->dragchange = 1; /* mark for selection */
@@ -3753,8 +3925,8 @@ static int ui_do_but_CURVE(bContext *C, uiBlock *block, uiBut *but, uiHandleButt
float dist, mindist = 200.0f; // 14 pixels radius
int sel = -1;
- zoomx = BLI_RCT_SIZE_X(&but->rect) / BLI_RCT_SIZE_X(&cumap->curr);
- zoomy = BLI_RCT_SIZE_Y(&but->rect) / BLI_RCT_SIZE_Y(&cumap->curr);
+ zoomx = BLI_rctf_size_x(&but->rect) / BLI_rctf_size_x(&cumap->curr);
+ zoomy = BLI_rctf_size_y(&but->rect) / BLI_rctf_size_y(&cumap->curr);
offsx = cumap->curr.xmin;
offsy = cumap->curr.ymin;
@@ -3801,7 +3973,7 @@ static int ui_do_but_CURVE(bContext *C, uiBlock *block, uiBut *but, uiHandleButt
changed = 1;
- /* reset cmp back to the curve points again, rather than drawing segments */
+ /* reset cmp back to the curve points again, rather than drawing segments */
cmp = cuma->curve;
/* find newly added point and make it 'sel' */
@@ -3818,12 +3990,14 @@ static int ui_do_but_CURVE(bContext *C, uiBlock *block, uiBut *but, uiHandleButt
/* ok, we move a point */
/* deselect all if this one is deselect. except if we hold shift */
if (event->shift == FALSE) {
- for (a = 0; a < cuma->totpoint; a++)
+ for (a = 0; a < cuma->totpoint; a++) {
cmp[a].flag &= ~CUMA_SELECT;
+ }
cmp[sel].flag |= CUMA_SELECT;
}
- else
+ else {
cmp[sel].flag ^= CUMA_SELECT;
+ }
}
else {
/* move the view */
@@ -3899,11 +4073,11 @@ static int ui_numedit_but_HISTOGRAM(uiBut *but, uiHandleButtonData *data, int mx
if (in_scope_resize_zone(but, data->dragstartx, data->dragstarty)) {
/* resize histogram widget itself */
- hist->height = BLI_RCT_SIZE_Y(&but->rect) + (data->dragstarty - my);
+ hist->height = BLI_rctf_size_y(&but->rect) + (data->dragstarty - my);
}
else {
/* scale histogram values (dy / 10 for better control) */
- const float yfac = minf(powf(hist->ymax, 2.0f), 1.0f) * 0.5f;
+ const float yfac = min_ff(powf(hist->ymax, 2.0f), 1.0f) * 0.5f;
hist->ymax += (dy * 0.1f) * yfac;
/* 0.1 allows us to see HDR colors up to 10 */
@@ -3973,7 +4147,7 @@ static int ui_numedit_but_WAVEFORM(uiBut *but, uiHandleButtonData *data, int mx,
Scopes *scopes = (Scopes *)but->poin;
/* rcti rect; */
int changed = 1;
- float /* dx, */ dy /* , yfac=1.f */; /* UNUSED */
+ float /* dx, */ dy /* , yfac =1.0f */; /* UNUSED */
/* BLI_rcti_rctf_copy(&rect, &but->rect); */
@@ -3983,7 +4157,7 @@ static int ui_numedit_but_WAVEFORM(uiBut *but, uiHandleButtonData *data, int mx,
if (in_scope_resize_zone(but, data->dragstartx, data->dragstarty)) {
/* resize waveform widget itself */
- scopes->wavefrm_height = BLI_RCT_SIZE_Y(&but->rect) + (data->dragstarty - my);
+ scopes->wavefrm_height = BLI_rctf_size_y(&but->rect) + (data->dragstarty - my);
}
else {
/* scale waveform values */
@@ -4065,7 +4239,7 @@ static int ui_numedit_but_VECTORSCOPE(uiBut *but, uiHandleButtonData *data, int
if (in_scope_resize_zone(but, data->dragstartx, data->dragstarty)) {
/* resize vectorscope widget itself */
- scopes->vecscope_height = BLI_RCT_SIZE_Y(&but->rect) + (data->dragstarty - my);
+ scopes->vecscope_height = BLI_rctf_size_y(&but->rect) + (data->dragstarty - my);
}
data->draglastx = mx;
@@ -4135,8 +4309,8 @@ static int ui_do_but_CHARTAB(bContext *UNUSED(C), uiBlock *UNUSED(block), uiBut
if (data->state == BUTTON_STATE_HIGHLIGHT) {
if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
/* Calculate the size of the button */
- width = abs(BLI_RCT_SIZE_X(&but->rect));
- height = abs(BLI_RCT_SIZE_Y(&but->rect));
+ width = abs(BLI_rctf_size_x(&but->rect));
+ height = abs(BLI_rctf_size_y(&but->rect));
butw = floor(width / 12);
buth = floor(height / 6);
@@ -4268,7 +4442,7 @@ static int ui_numedit_but_TRACKPREVIEW(bContext *C, uiBut *but, uiHandleButtonDa
if (in_scope_resize_zone(but, data->dragstartx, data->dragstarty)) {
/* resize preview widget itself */
- scopes->track_preview_height = BLI_RCT_SIZE_Y(&but->rect) + (data->dragstarty - my);
+ scopes->track_preview_height = BLI_rctf_size_y(&but->rect) + (data->dragstarty - my);
}
else {
if (!scopes->track_locked) {
@@ -4276,8 +4450,8 @@ static int ui_numedit_but_TRACKPREVIEW(bContext *C, uiBut *but, uiHandleButtonDa
scopes->marker = BKE_tracking_marker_ensure(scopes->track, scopes->framenr);
scopes->marker->flag &= ~(MARKER_DISABLED | MARKER_TRACKED);
- scopes->marker->pos[0] += -dx * scopes->slide_scale[0] / BLI_RCT_SIZE_X(&but->block->rect);
- scopes->marker->pos[1] += -dy * scopes->slide_scale[1] / BLI_RCT_SIZE_Y(&but->block->rect);
+ scopes->marker->pos[0] += -dx * scopes->slide_scale[0] / BLI_rctf_size_x(&but->block->rect);
+ scopes->marker->pos[1] += -dy * scopes->slide_scale[1] / BLI_rctf_size_y(&but->block->rect);
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
}
@@ -4403,11 +4577,11 @@ static uiBlock *menu_add_shortcut(bContext *C, ARegion *ar, void *arg)
int kmi_id;
/* XXX this guess_opname can potentially return a different keymap than being found on adding later... */
- km = WM_keymap_guess_opname(C, but->optype->idname);
+ km = WM_keymap_guess_opname(C, but->optype->idname);
kmi = WM_keymap_add_item(km, but->optype->idname, AKEY, KM_PRESS, 0, 0);
kmi_id = kmi->id;
- /* copy properties, prop can be NULL for reset */
+ /* copy properties, prop can be NULL for reset */
if (prop)
prop = IDP_CopyProperty(prop);
WM_keymap_properties_reset(kmi, prop);
@@ -4415,14 +4589,13 @@ static uiBlock *menu_add_shortcut(bContext *C, ARegion *ar, void *arg)
/* update and get pointers again */
WM_keyconfig_update(wm);
- km = WM_keymap_guess_opname(C, but->optype->idname);
+ km = WM_keymap_guess_opname(C, but->optype->idname);
kmi = WM_keymap_item_find_id(km, kmi_id);
RNA_pointer_create(&wm->id, &RNA_KeyMapItem, kmi, &ptr);
block = uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
uiBlockSetHandleFunc(block, but_shortcut_name_func, but);
- uiBlockSetFlag(block, UI_BLOCK_RET_1);
uiBlockSetDirection(block, UI_CENTER);
layout = uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, 200, 20, style);
@@ -4466,6 +4639,7 @@ static void popup_add_shortcut_func(bContext *C, void *arg1, void *UNUSED(arg2))
static int ui_but_menu(bContext *C, uiBut *but)
{
+ ARegion *ar = CTX_wm_region(C);
uiPopupMenu *pup;
uiLayout *layout;
int length;
@@ -4477,17 +4651,8 @@ static int ui_but_menu(bContext *C, uiBut *but)
button_timers_tooltip_remove(C, but);
-#if 0
- if (but->rnaprop)
- name = RNA_property_ui_name(but->rnaprop);
- else if (but->optype && but->optype->srna)
- name = RNA_struct_ui_name(but->optype->srna);
- else
- name = IFACE_("<needs_name>"); // XXX - should never happen.
-#else
uiButGetStrInfo(C, but, 1, &label);
name = label.strinfo;
-#endif
pup = uiPupMenuBegin(C, name, ICON_NONE);
layout = uiPupMenuLayout(pup);
@@ -4531,7 +4696,9 @@ static int ui_but_menu(bContext *C, uiBut *but)
}
- else if (but->flag & UI_BUT_DRIVEN) ;
+ else if (but->flag & UI_BUT_DRIVEN) {
+ /* pass */
+ }
else if (is_anim) {
if (length) {
uiItemBooleanO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Insert Keyframes"),
@@ -4539,9 +4706,10 @@ static int ui_but_menu(bContext *C, uiBut *but)
uiItemBooleanO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Insert Single Keyframe"),
ICON_NONE, "ANIM_OT_keyframe_insert_button", "all", 0);
}
- else
+ else {
uiItemBooleanO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Insert Keyframe"),
ICON_NONE, "ANIM_OT_keyframe_insert_button", "all", 0);
+ }
}
if (but->flag & UI_BUT_ANIMATED) {
@@ -4567,17 +4735,21 @@ static int ui_but_menu(bContext *C, uiBut *but)
uiItemBooleanO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Single Driver"),
ICON_NONE, "ANIM_OT_driver_button_remove", "all", 0);
}
- else
+ else {
uiItemBooleanO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Driver"),
ICON_NONE, "ANIM_OT_driver_button_remove", "all", 0);
+ }
uiItemO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Copy Driver"),
ICON_NONE, "ANIM_OT_copy_driver_button");
- if (ANIM_driver_can_paste())
+ if (ANIM_driver_can_paste()) {
uiItemO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Paste Driver"),
ICON_NONE, "ANIM_OT_paste_driver_button");
+ }
+ }
+ else if (but->flag & (UI_BUT_ANIMATED_KEY | UI_BUT_ANIMATED)) {
+ /* pass */
}
- else if (but->flag & (UI_BUT_ANIMATED_KEY | UI_BUT_ANIMATED)) ;
else if (is_anim) {
uiItemS(layout);
@@ -4587,13 +4759,15 @@ static int ui_but_menu(bContext *C, uiBut *but)
uiItemBooleanO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Add Single Driver"),
ICON_NONE, "ANIM_OT_driver_button_add", "all", 0);
}
- else
+ else {
uiItemBooleanO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Add Driver"),
ICON_NONE, "ANIM_OT_driver_button_add", "all", 0);
+ }
- if (ANIM_driver_can_paste())
+ if (ANIM_driver_can_paste()) {
uiItemO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Paste Driver"),
ICON_NONE, "ANIM_OT_paste_driver_button");
+ }
}
/* Keying Sets */
@@ -4621,8 +4795,8 @@ static int ui_but_menu(bContext *C, uiBut *but)
/* Property Operators */
- /*Copy Property Value
- *Paste Property Value */
+ /* Copy Property Value
+ * Paste Property Value */
if (length) {
uiItemBooleanO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Reset All to Default Values"),
@@ -4630,9 +4804,10 @@ static int ui_but_menu(bContext *C, uiBut *but)
uiItemBooleanO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Reset Single to Default Value"),
ICON_NONE, "UI_OT_reset_default_button", "all", 0);
}
- else
+ else {
uiItemO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Reset to Default Value"),
ICON_NONE, "UI_OT_reset_default_button");
+ }
uiItemO(layout, CTX_IFACE_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Copy Data Path"),
ICON_NONE, "UI_OT_copy_data_path_button");
@@ -4679,7 +4854,12 @@ static int ui_but_menu(bContext *C, uiBut *but)
uiItemS(layout);
}
-
+ /* Show header tools for header buttons. */
+ if (ar->regiontype == RGN_TYPE_HEADER) {
+ uiItemMenuF(layout, IFACE_("Header"), ICON_NONE, ED_screens_header_tools_menu_create, NULL);
+ uiItemS(layout);
+ }
+
{ /* Docs */
char buf[512];
PointerRNA ptr_props;
@@ -4753,14 +4933,10 @@ static int ui_do_button(bContext *C, uiBlock *block, uiBut *but, wmEvent *event)
if (but->flag & UI_BUT_DISABLED)
return WM_UI_HANDLER_CONTINUE;
- if ((data->state == BUTTON_STATE_HIGHLIGHT) &&
- /* check prevval because of modal operators [#24016],
- * modifier check is to allow Ctrl+C for copy.
- * if this causes other problems, remove this check and suffer the bug :) - campbell */
- ((event->prevval != KM_PRESS) || (ISKEYMODIFIER(event->prevtype)) || (event->type == EVT_DROP)))
- {
+ if ((data->state == BUTTON_STATE_HIGHLIGHT) || (event->type == EVT_DROP)) {
/* handle copy-paste */
if (ELEM(event->type, CKEY, VKEY) && event->val == KM_PRESS && (event->ctrl || event->oskey)) {
+
ui_but_copy_paste(C, but, data, (event->type == CKEY) ? 'c' : 'v');
return WM_UI_HANDLER_BREAK;
}
@@ -4842,7 +5018,7 @@ static int ui_do_button(bContext *C, uiBlock *block, uiBut *but, wmEvent *event)
button_activate_state(C, but, BUTTON_STATE_EXIT);
return WM_UI_HANDLER_BREAK;
}
- }
+ }
else if (but->pointype && but->poin == NULL) {
/* there's a pointer needed */
BKE_reportf(NULL, RPT_WARNING, "DoButton pointer error: %s", but->str);
@@ -5237,12 +5413,7 @@ static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState s
/* automatic open pulldown block timer */
if (ELEM3(but->type, BLOCK, PULLDOWN, ICONTEXTROW)) {
- if ((data->used_mouse == TRUE) &&
- (data->autoopentimer == FALSE) &&
- /* don't popup the first time,
- * see description on this member for info */
- (but->block->auto_is_first_event == FALSE))
- {
+ if (data->used_mouse && !data->autoopentimer) {
int time;
if (but->block->auto_open == TRUE) { /* test for toolbox */
@@ -5262,8 +5433,6 @@ static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState s
data->autoopentimer = WM_event_add_timer(data->wm, data->window, TIMER, 0.02 * (double)time);
}
}
-
- but->block->auto_is_first_event = FALSE;
}
}
else {
@@ -5287,8 +5456,24 @@ static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState s
}
else if (data->state == BUTTON_STATE_NUM_EDITING) {
ui_numedit_end(but, data);
- if (ui_is_a_warp_but(but))
- WM_cursor_grab_disable(CTX_wm_window(C));
+ if (ui_is_a_warp_but(but)) {
+
+#ifdef USE_CONT_MOUSE_CORRECT
+ if (data->ungrab_mval[0] != FLT_MAX) {
+ int mouse_ungrab_xy[2];
+ ui_block_to_window_fl(data->region, but->block, &data->ungrab_mval[0], &data->ungrab_mval[1]);
+ mouse_ungrab_xy[0] = data->ungrab_mval[0];
+ mouse_ungrab_xy[1] = data->ungrab_mval[1];
+
+ WM_cursor_grab_disable(data->window, mouse_ungrab_xy);
+ }
+ else {
+ WM_cursor_grab_disable(data->window, NULL);
+ }
+#else
+ WM_cursor_grab_disable(data->window, );
+#endif
+ }
}
/* menu open */
if (state == BUTTON_STATE_MENU_OPEN)
@@ -5351,6 +5536,10 @@ static void button_activate_init(bContext *C, ARegion *ar, uiBut *but, uiButtonA
data->window = CTX_wm_window(C);
data->region = ar;
+#ifdef USE_CONT_MOUSE_CORRECT
+ copy_v2_fl(data->ungrab_mval, FLT_MAX);
+#endif
+
if (ELEM(but->type, BUT_CURVE, SEARCH_MENU)) {
/* XXX curve is temp */
}
@@ -5632,20 +5821,24 @@ void uiContextAnimUpdate(const bContext *C)
ui_but_anim_flag(but, (scene) ? scene->r.cfra : 0.0f);
ED_region_tag_redraw(ar);
- if (but->active)
+ if (but->active) {
activebut = but;
- else if (!activebut && (but->flag & UI_BUT_LAST_ACTIVE))
+ }
+ else if (!activebut && (but->flag & UI_BUT_LAST_ACTIVE)) {
activebut = but;
+ }
}
}
if (activebut) {
/* always recurse into opened menu, so all buttons update (like colorpicker) */
uiHandleButtonData *data = activebut->active;
- if (data && data->menu)
+ if (data && data->menu) {
ar = data->menu->region;
- else
+ }
+ else {
return;
+ }
}
else {
/* no active button */
@@ -5675,8 +5868,9 @@ static int ui_handle_button_over(bContext *C, wmEvent *event, ARegion *ar)
if (event->type == MOUSEMOVE) {
but = ui_but_find_mouse_over(ar, event->x, event->y);
- if (but)
+ if (but) {
button_activate_init(C, ar, but, BUTTON_ACTIVATE_OVER);
+ }
}
else if (event->type == EVT_BUT_OPEN) {
but = uit_but_find_open_event(ar, event);
@@ -5897,7 +6091,7 @@ static int ui_handle_button_event(bContext *C, wmEvent *event, uiBut *but)
}
else {
retval = ui_do_button(C, block, but, event);
- // retval= WM_UI_HANDLER_BREAK; XXX why ?
+ // retval = WM_UI_HANDLER_BREAK; XXX why ?
}
if (data->state == BUTTON_STATE_EXIT) {
@@ -6113,73 +6307,81 @@ static char ui_menu_scroll_test(uiBlock *block, int my)
{
if (block->flag & (UI_BLOCK_CLIPTOP | UI_BLOCK_CLIPBOTTOM)) {
if (block->flag & UI_BLOCK_CLIPTOP)
- if (my > block->rect.ymax - 14)
+ if (my > block->rect.ymax - UI_MENU_SCROLL_MOUSE)
return 't';
if (block->flag & UI_BLOCK_CLIPBOTTOM)
- if (my < block->rect.ymin + 14)
+ if (my < block->rect.ymin + UI_MENU_SCROLL_MOUSE)
return 'b';
}
return 0;
}
-static int ui_menu_scroll(ARegion *ar, uiBlock *block, int my)
+static int ui_menu_scroll(ARegion *ar, uiBlock *block, int my, uiBut *to_bt)
{
- char test = ui_menu_scroll_test(block, my);
-
- if (test) {
- uiBut *b1 = block->buttons.first;
- uiBut *b2 = block->buttons.last;
- uiBut *bnext;
- uiBut *bprev;
- int dy = 0;
-
- /* get first and last visible buttons */
- while (b1 && ui_but_next(b1) && (b1->flag & UI_SCROLLED))
- b1 = ui_but_next(b1);
- while (b2 && ui_but_prev(b2) && (b2->flag & UI_SCROLLED))
- b2 = ui_but_prev(b2);
- /* skips separators */
- bnext = ui_but_next(b1);
- bprev = ui_but_prev(b2);
+ uiBut *bt;
+ float dy = 0.0f;
+
+ if (to_bt) {
+ /* scroll to activated button */
+ if (block->flag & UI_BLOCK_CLIPTOP) {
+ if (to_bt->rect.ymax > block->rect.ymax - UI_MENU_SCROLL_ARROW)
+ dy = block->rect.ymax - to_bt->rect.ymax - UI_MENU_SCROLL_ARROW;
+ }
+ if (block->flag & UI_BLOCK_CLIPBOTTOM) {
+ if (to_bt->rect.ymin < block->rect.ymin + UI_MENU_SCROLL_ARROW)
+ dy = block->rect.ymin - to_bt->rect.ymin + UI_MENU_SCROLL_ARROW;
+ }
+ }
+ else {
+ /* scroll when mouse over arrow buttons */
+ char test = ui_menu_scroll_test(block, my);
+
+ if (test == 't')
+ dy = -UI_UNIT_Y; /* scroll to the top */
+ else if (test == 'b')
+ dy = UI_UNIT_Y; /* scroll to the bottom */
+ }
+
+ if (dy != 0.0f) {
+ if (dy < 0.0f) {
+ /* stop at top item, extra 0.5 unit Y makes it snap nicer */
+ float ymax = -FLT_MAX;
+
+ for (bt = block->buttons.first; bt; bt = bt->next)
+ ymax = max_ff(ymax, bt->rect.ymax);
+
+ if (ymax + dy - UI_UNIT_Y*0.5f < block->rect.ymax - UI_MENU_SCROLL_PAD)
+ dy = block->rect.ymax - ymax - UI_MENU_SCROLL_PAD;
+ }
+ else {
+ /* stop at bottom item, extra 0.5 unit Y makes it snap nicer */
+ float ymin = FLT_MAX;
+
+ for (bt = block->buttons.first; bt; bt = bt->next)
+ ymin = min_ff(ymin, bt->rect.ymin);
+
+ if (ymin + dy + UI_UNIT_Y*0.5f > block->rect.ymin + UI_MENU_SCROLL_PAD)
+ dy = block->rect.ymin - ymin + UI_MENU_SCROLL_PAD;
+ }
+
+ /* apply scroll offset */
+ for (bt = block->buttons.first; bt; bt = bt->next) {
+ bt->rect.ymin += dy;
+ bt->rect.ymax += dy;
+ }
+
+ /* set flags again */
+ ui_popup_block_scrolltest(block);
- if (bnext == NULL || bprev == NULL)
- return 0;
+ ED_region_tag_redraw(ar);
- if (test == 't') {
- /* bottom button is first button */
- if (b1->rect.ymin < b2->rect.ymin)
- dy = bnext->rect.ymin - b1->rect.ymin;
- /* bottom button is last button */
- else
- dy = bprev->rect.ymin - b2->rect.ymin;
- }
- else if (test == 'b') {
- /* bottom button is first button */
- if (b1->rect.ymin < b2->rect.ymin)
- dy = b1->rect.ymin - bnext->rect.ymin;
- /* bottom button is last button */
- else
- dy = b2->rect.ymin - bprev->rect.ymin;
- }
- if (dy) {
-
- for (b1 = block->buttons.first; b1; b1 = b1->next) {
- b1->rect.ymin -= dy;
- b1->rect.ymax -= dy;
- }
- /* set flags again */
- ui_popup_block_scrolltest(block);
-
- ED_region_tag_redraw(ar);
-
- return 1;
- }
+ return 1;
}
return 0;
}
-static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle *menu, int UNUSED(topmenu))
+static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle *menu, int level)
{
ARegion *ar;
uiBlock *block;
@@ -6209,7 +6411,7 @@ static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle
}
else if (event->type == TIMER) {
if (event->customdata == menu->scrolltimer)
- ui_menu_scroll(ar, block, my);
+ ui_menu_scroll(ar, block, my, NULL);
}
else {
/* for ui_mouse_motion_towards_block */
@@ -6224,10 +6426,22 @@ static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle
}
/* first block own event func */
- if (block->block_event_func && block->block_event_func(C, block, event)) ;
- /* events not for active search menu button */
+ if (block->block_event_func && block->block_event_func(C, block, event)) {
+ /* pass */
+ } /* events not for active search menu button */
else if (but == NULL || but->type != SEARCH_MENU) {
switch (event->type) {
+
+
+ /* let the parent menu get the event */
+#define PASS_EVENT_TO_PARENT_IF_NONACTIVE \
+ if ((level != 0) && (but == NULL)) { \
+ menu->menuretval = UI_RETURN_OUT | UI_RETURN_OUT_PARENT; \
+ BLI_assert(retval == WM_UI_HANDLER_CONTINUE); \
+ break; \
+ } (void)0
+
+
/* closing sublevels of pulldowns */
case LEFTARROWKEY:
if (event->val == KM_PRESS && (block->flag & UI_BLOCK_LOOP))
@@ -6238,8 +6452,11 @@ static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle
break;
/* opening sublevels of pulldowns */
- case RIGHTARROWKEY:
+ case RIGHTARROWKEY:
if (event->val == KM_PRESS && (block->flag & UI_BLOCK_LOOP)) {
+
+ PASS_EVENT_TO_PARENT_IF_NONACTIVE;
+
but = ui_but_find_activated(ar);
if (!but) {
@@ -6265,6 +6482,9 @@ static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle
}
else if (inside || (block->flag & UI_BLOCK_LOOP)) {
if (event->val == KM_PRESS) {
+
+ PASS_EVENT_TO_PARENT_IF_NONACTIVE;
+
but = ui_but_find_activated(ar);
if (but) {
/* is there a situation where UI_LEFT or UI_RIGHT would also change navigation direction? */
@@ -6286,8 +6506,10 @@ static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle
but = ui_but_next(but);
}
- if (but)
+ if (but) {
ui_handle_button_activate(C, ar, but, BUTTON_ACTIVATE);
+ ui_menu_scroll(ar, block, my, but);
+ }
}
if (!but) {
@@ -6313,6 +6535,7 @@ static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle
if (bt) {
ui_handle_button_activate(C, ar, bt, BUTTON_ACTIVATE);
+ ui_menu_scroll(ar, block, my, bt);
}
}
}
@@ -6344,6 +6567,9 @@ static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle
if (act == 0) act = 10;
if ((block->flag & UI_BLOCK_NUMSELECT) && event->val == KM_PRESS) {
+
+ PASS_EVENT_TO_PARENT_IF_NONACTIVE;
+
if (event->alt) act += 10;
count = 0;
@@ -6416,11 +6642,13 @@ static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle
case YKEY:
case ZKEY:
{
- if ((event->val == KM_PRESS) &&
+ if ((event->val == KM_PRESS || event->val == KM_DBL_CLICK) &&
(event->shift == FALSE) &&
(event->ctrl == FALSE) &&
(event->oskey == FALSE))
{
+ PASS_EVENT_TO_PARENT_IF_NONACTIVE;
+
for (but = block->buttons.first; but; but = but->next) {
if (but->menu_key == event->type) {
@@ -6468,7 +6696,9 @@ static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle
}
}
- if (menu->menuretval) ;
+ if (menu->menuretval) {
+ /* pass */
+ }
else if (event->type == ESCKEY && event->val == KM_PRESS) {
/* esc cancels this and all preceding menus */
menu->menuretval = UI_RETURN_CANCEL;
@@ -6510,6 +6740,10 @@ static int ui_handle_menu_event(bContext *C, wmEvent *event, uiPopupBlockHandle
retval = WM_UI_HANDLER_BREAK;
}
}
+
+ /* end switch */
+#undef PASS_EVENT_TO_PARENT_IF_NONACTIVE
+
}
}
@@ -6598,7 +6832,7 @@ static int ui_handle_menu_return_submenu(bContext *C, wmEvent *event, uiPopupBlo
return WM_UI_HANDLER_BREAK;
}
-static int ui_handle_menus_recursive(bContext *C, wmEvent *event, uiPopupBlockHandle *menu)
+static int ui_handle_menus_recursive(bContext *C, wmEvent *event, uiPopupBlockHandle *menu, int level)
{
uiBut *but;
uiHandleButtonData *data;
@@ -6611,14 +6845,24 @@ static int ui_handle_menus_recursive(bContext *C, wmEvent *event, uiPopupBlockHa
submenu = (data) ? data->menu : NULL;
if (submenu)
- retval = ui_handle_menus_recursive(C, event, submenu);
+ retval = ui_handle_menus_recursive(C, event, submenu, level + 1);
/* now handle events for our own menu */
if (retval == WM_UI_HANDLER_CONTINUE || event->type == TIMER) {
- if (submenu && submenu->menuretval)
+ if (submenu && submenu->menuretval) {
+ int do_ret_out_parent = (submenu->menuretval & UI_RETURN_OUT_PARENT);
retval = ui_handle_menu_return_submenu(C, event, menu);
- else
- retval = ui_handle_menu_event(C, event, menu, (submenu == NULL));
+ submenu = NULL; /* hint not to use this, it may be freed by call above */
+ (void)submenu;
+ /* we may wan't to quit the submenu and handle the even in this menu,
+ * if its important to use it, check 'data->menu' first */
+ if ((retval == WM_UI_HANDLER_BREAK) && do_ret_out_parent) {
+ retval = ui_handle_menu_event(C, event, menu, level);
+ }
+ }
+ else {
+ retval = ui_handle_menu_event(C, event, menu, level); /* same as above */
+ }
}
return retval;
@@ -6706,7 +6950,7 @@ static int ui_handler_region_menu(bContext *C, wmEvent *event, void *UNUSED(user
if (data->state == BUTTON_STATE_MENU_OPEN) {
/* handle events for menus and their buttons recursively,
* this will handle events from the top to the bottom menu */
- retval = ui_handle_menus_recursive(C, event, data->menu);
+ retval = ui_handle_menus_recursive(C, event, data->menu, 0);
/* handle events for the activated button */
if (retval == WM_UI_HANDLER_CONTINUE || event->type == TIMER) {
@@ -6750,7 +6994,7 @@ static int ui_handler_popup(bContext *C, wmEvent *event, void *userdata)
retval = WM_UI_HANDLER_CONTINUE;
}
- ui_handle_menus_recursive(C, event, menu);
+ ui_handle_menus_recursive(C, event, menu, 0);
/* free if done, does not free handle itself */
if (menu->menuretval) {
diff --git a/source/blender/editors/interface/interface_icons.c b/source/blender/editors/interface/interface_icons.c
index 0921107b8e6..bb0cc1176d8 100644
--- a/source/blender/editors/interface/interface_icons.c
+++ b/source/blender/editors/interface/interface_icons.c
@@ -142,7 +142,7 @@ static void def_internal_icon(ImBuf *bbuf, int icon_id, int xofs, int yofs, int
new_icon = MEM_callocN(sizeof(Icon), "texicon");
new_icon->obj = NULL; /* icon is not for library object */
- new_icon->type = 0;
+ new_icon->type = 0;
di = MEM_callocN(sizeof(DrawInfo), "drawinfo");
di->type = type;
@@ -852,7 +852,7 @@ static void icon_set_image(bContext *C, ID *id, PreviewImage *prv_img, enum eIco
if (G.debug & G_DEBUG)
printf("%s: no preview image for this ID: %s\n", __func__, id->name);
return;
- }
+ }
icon_create_rect(prv_img, size);
@@ -982,8 +982,8 @@ static void icon_draw_size(float x, float y, int icon_id, float aspect, float al
if (!di) {
di = icon_create_drawinfo();
- icon->drawinfo = di;
- icon->drawinfo_free = UI_icons_free_drawinfo;
+ icon->drawinfo = di;
+ icon->drawinfo_free = UI_icons_free_drawinfo;
}
/* scale width and height according to aspect */
@@ -994,13 +994,13 @@ static void icon_draw_size(float x, float y, int icon_id, float aspect, float al
/* vector icons use the uiBlock transformation, they are not drawn
* with untransformed coordinates like the other icons */
di->data.vector.func((int)x, (int)y, ICON_DEFAULT_HEIGHT, ICON_DEFAULT_HEIGHT, 1.0f);
- }
+ }
else if (di->type == ICON_TYPE_TEXTURE) {
icon_draw_texture(x, y, (float)w, (float)h, di->data.texture.x, di->data.texture.y,
di->data.texture.w, di->data.texture.h, alpha, rgb);
}
else if (di->type == ICON_TYPE_BUFFER) {
- /* it is a builtin icon */
+ /* it is a builtin icon */
iimg = di->data.buffer.image;
if (!iimg->rect) return; /* something has gone wrong! */
@@ -1010,7 +1010,7 @@ static void icon_draw_size(float x, float y, int icon_id, float aspect, float al
else if (di->type == ICON_TYPE_PREVIEW) {
PreviewImage *pi = BKE_previewimg_get((ID *)icon->obj);
- if (pi) {
+ if (pi) {
/* no create icon on this level in code */
if (!pi->rect[size]) return; /* something has gone wrong! */
diff --git a/source/blender/editors/interface/interface_intern.h b/source/blender/editors/interface/interface_intern.h
index 928e1671cee..16159e0f73a 100644
--- a/source/blender/editors/interface/interface_intern.h
+++ b/source/blender/editors/interface/interface_intern.h
@@ -97,6 +97,11 @@ typedef enum {
UI_WTYPE_PROGRESSBAR
} uiWidgetTypeEnum;
+/* menu scrolling */
+#define UI_MENU_SCROLL_ARROW 12
+#define UI_MENU_SCROLL_MOUSE (UI_MENU_SCROLL_ARROW + 2)
+#define UI_MENU_SCROLL_PAD 4
+
/* panel limits */
#define UI_PANEL_MINX 100
#define UI_PANEL_MINY 70
@@ -160,7 +165,8 @@ struct uiBut {
int flag, drawflag;
eButType type;
eButPointerType pointype;
- short bit, bitnr, retval, strwidth, ofs, pos, selsta, selend, alignnr;
+ short bit, bitnr, retval, strwidth, alignnr;
+ short ofs, pos, selsta, selend;
char *str;
char strdata[UI_MAX_NAME_STR];
@@ -305,17 +311,7 @@ struct uiBlock {
char direction;
char dt; /* drawtype: UI_EMBOSS, UI_EMBOSSN ... etc, copied to buttons */
char auto_open;
-
- /* this setting is used so newly opened menu's dont popout the first item under the mouse,
- * the reasoning behind this is because of muscle memory for opening menus.
- *
- * Without this, the first time opening a Submenu and activating an item in it will be 2 steps,
- * but the second time the same item is accessed the menu memory would auto activate the
- * last used menu and the key intended to select that submenu ends up being passed into the submenu.
- * - Campbell
- */
- char auto_is_first_event;
- char _pad[6];
+ char _pad[7];
double auto_open_last;
const char *lockstr;
@@ -325,7 +321,6 @@ struct uiBlock {
char tooltipdisabled; /* to avoid tooltip after click */
char endblock; /* uiEndBlock done? */
- float xofs, yofs; /* offset to parent button */
eBlockBoundsCalc bounds_type; /* for doing delayed */
int mx, my;
int bounds, minbounds; /* for doing delayed */
@@ -375,7 +370,8 @@ extern void ui_set_but_hsv(uiBut *but);
extern void ui_get_but_vectorf(uiBut *but, float vec[3]);
extern void ui_set_but_vectorf(uiBut *but, const float vec[3]);
-extern void ui_hsvcircle_vals_from_pos(float *valrad, float *valdist, rcti *rect, float mx, float my);
+extern void ui_hsvcircle_vals_from_pos(float *val_rad, float *val_dist, const rcti *rect,
+ const float mx, const float my);
extern void ui_get_but_string(uiBut *but, char *str, size_t maxlen);
extern void ui_convert_to_unit_alt_name(uiBut *but, char *str, size_t maxlen);
@@ -428,6 +424,9 @@ struct uiPopupBlockHandle {
int menuretval;
float retvalue;
float retvec[4];
+
+ /* menu direction */
+ int direction;
};
uiBlock *ui_block_func_COLOR(struct bContext *C, uiPopupBlockHandle *handle, void *arg_but);
@@ -473,7 +472,7 @@ extern int ui_handler_panel_region(struct bContext *C, struct wmEvent *event);
extern void ui_draw_aligned_panel(struct uiStyle *style, uiBlock *block, rcti *rect);
/* interface_draw.c */
-extern void ui_dropshadow(rctf *rct, float radius, float aspect, float alpha, int select);
+extern void ui_dropshadow(const rctf *rct, float radius, float aspect, float alpha, int select);
void ui_draw_gradient(rcti *rect, const float hsv[3], const int type, const float alpha);
@@ -490,6 +489,8 @@ void ui_draw_but_TRACKPREVIEW(ARegion *ar, uiBut *but, struct uiWidgetColors *wc
extern void ui_button_activate_do(struct bContext *C, struct ARegion *ar, uiBut *but);
extern void ui_button_active_free(const struct bContext *C, uiBut *but);
extern int ui_button_is_active(struct ARegion *ar);
+extern int ui_button_open_menu_direction(uiBut *but);
+extern void ui_button_text_password_hide(char password_str[UI_MAX_DRAW_STR], uiBut *but, int restore);
/* interface_widgets.c */
void ui_draw_anti_tria(float x1, float y1, float x2, float y2, float x3, float y3);
@@ -509,7 +510,7 @@ void ui_widget_color_init(struct ThemeUI *tui);
void ui_draw_menu_item(struct uiFontStyle *fstyle, rcti *rect, const char *name, int iconid, int state);
void ui_draw_preview_item(struct uiFontStyle *fstyle, rcti *rect, const char *name, int iconid, int state);
-extern unsigned char checker_stipple_sml[];
+extern unsigned char checker_stipple_sml[32 * 32 / 8];
/* used for transp checkers */
#define UI_TRANSP_DARK 100
#define UI_TRANSP_LIGHT 160
diff --git a/source/blender/editors/interface/interface_layout.c b/source/blender/editors/interface/interface_layout.c
index 803fd928085..5170fc7d51b 100644
--- a/source/blender/editors/interface/interface_layout.c
+++ b/source/blender/editors/interface/interface_layout.c
@@ -41,6 +41,7 @@
#include "BLI_string.h"
#include "BLI_rect.h"
#include "BLI_utildefines.h"
+#include "BLI_math.h"
#include "BLF_translation.h"
@@ -239,10 +240,8 @@ static void ui_item_size(uiItem *item, int *r_w, int *r_h)
if (item->type == ITEM_BUTTON) {
uiButtonItem *bitem = (uiButtonItem *)item;
-
-
- if (r_w) *r_w = BLI_RCT_SIZE_X(&bitem->but->rect);
- if (r_h) *r_h = BLI_RCT_SIZE_Y(&bitem->but->rect);
+ if (r_w) *r_w = BLI_rctf_size_x(&bitem->but->rect);
+ if (r_h) *r_h = BLI_rctf_size_y(&bitem->but->rect);
}
else {
uiLayout *litem = (uiLayout *)item;
@@ -837,8 +836,9 @@ void uiItemsFullEnumO(uiLayout *layout, const char *opname, const char *propname
bt = block->buttons.last;
bt->flag = UI_TEXT_LEFT;
}
- else /* XXX bug here, collums draw bottom item badly */
+ else { /* XXX bug here, colums draw bottom item badly */
uiItemS(column);
+ }
}
}
@@ -1314,7 +1314,7 @@ static void rna_search_cb(const struct bContext *C, void *arg_but, const char *s
BLI_addtail(items_list, cis);
}
MEM_freeN(name);
- }
+ }
i++;
}
@@ -1377,7 +1377,7 @@ void ui_but_add_search(uiBut *but, PointerRNA *ptr, PropertyRNA *prop, PointerRN
/* turn button into search button */
if (searchprop) {
but->type = SEARCH_MENU;
- but->hardmax = MAX2(but->hardmax, 256);
+ but->hardmax = MAX2(but->hardmax, 256.0f);
but->rnasearchpoin = *searchptr;
but->rnasearchprop = searchprop;
but->flag |= UI_ICON_LEFT | UI_TEXT_LEFT;
@@ -1450,6 +1450,11 @@ static void ui_item_menutype_func(bContext *C, uiLayout *layout, void *arg_mt)
menu.type = mt;
menu.layout = layout;
+
+ if (G.debug & G_DEBUG_WM) {
+ printf("%s: opening menu \"%s\"\n", __func__, mt->idname);
+ }
+
mt->draw(C, &menu);
}
@@ -1709,7 +1714,7 @@ static void ui_litem_layout_row(uiLayout *litem)
int x, y, w, tot, totw, neww, itemw, minw, itemh, offset;
int fixedw, freew, fixedx, freex, flag = 0, lastw = 0;
- /* x= litem->x; */ /* UNUSED */
+ /* x = litem->x; */ /* UNUSED */
y = litem->y;
w = litem->w;
totw = 0;
@@ -1933,8 +1938,8 @@ static void ui_litem_estimate_column_flow(uiLayout *litem)
return;
}
- flow->totcol = MAX2(litem->root->emw / maxw, 1);
- flow->totcol = MIN2(flow->totcol, totitem);
+ flow->totcol = max_ii(litem->root->emw / maxw, 1);
+ flow->totcol = min_ii(flow->totcol, totitem);
}
else
flow->totcol = flow->number;
@@ -2008,7 +2013,7 @@ static void ui_litem_layout_column_flow(uiLayout *litem)
emy -= itemh;
ui_item_position(item, x + offset, y, itemw, itemh);
y -= style->buttonspacey;
- miny = MIN2(miny, y);
+ miny = min_ii(miny, y);
/* decide to go to next one */
if (col < flow->totcol - 1 && emy <= -emh) {
@@ -2039,8 +2044,8 @@ static void ui_litem_estimate_absolute(uiLayout *litem)
ui_item_offset(item, &itemx, &itemy);
ui_item_size(item, &itemw, &itemh);
- minx = MIN2(minx, itemx);
- miny = MIN2(miny, itemy);
+ minx = min_ii(minx, itemx);
+ miny = min_ii(miny, itemy);
litem->w = MAX2(litem->w, itemx + itemw);
litem->h = MAX2(litem->h, itemy + itemh);
@@ -2065,11 +2070,11 @@ static void ui_litem_layout_absolute(uiLayout *litem)
ui_item_offset(item, &itemx, &itemy);
ui_item_size(item, &itemw, &itemh);
- minx = MIN2(minx, itemx);
- miny = MIN2(miny, itemy);
+ minx = min_ii(minx, itemx);
+ miny = min_ii(miny, itemy);
- totw = MAX2(totw, itemx + itemw);
- toth = MAX2(toth, itemy + itemh);
+ totw = max_ii(totw, itemx + itemw);
+ toth = max_ii(toth, itemy + itemh);
}
totw -= minx;
@@ -2517,8 +2522,12 @@ static void ui_item_align(uiLayout *litem, short nr)
if (!bitem->but->alignnr)
bitem->but->alignnr = nr;
}
- else if (item->type == ITEM_LAYOUT_ABSOLUTE) ;
- else if (item->type == ITEM_LAYOUT_OVERLAP) ;
+ else if (item->type == ITEM_LAYOUT_ABSOLUTE) {
+ /* pass */
+ }
+ else if (item->type == ITEM_LAYOUT_OVERLAP) {
+ /* pass */
+ }
else if (item->type == ITEM_LAYOUT_BOX) {
box = (uiLayoutItemBx *)item;
box->roundbox->alignnr = nr;
@@ -2872,12 +2881,12 @@ void uiLayoutOperatorButs(const bContext *C, uiLayout *layout, wmOperator *op,
WM_operator_properties_create(&op_ptr, "WM_OT_operator_preset_add");
RNA_string_set(&op_ptr, "operator", op->type->idname);
- op_ptr = uiItemFullO(row, "WM_OT_operator_preset_add", "", ICON_ZOOMIN, op_ptr.data, WM_OP_INVOKE_DEFAULT, 0);
+ uiItemFullO(row, "WM_OT_operator_preset_add", "", ICON_ZOOMIN, op_ptr.data, WM_OP_INVOKE_DEFAULT, 0);
WM_operator_properties_create(&op_ptr, "WM_OT_operator_preset_add");
RNA_string_set(&op_ptr, "operator", op->type->idname);
RNA_boolean_set(&op_ptr, "remove_active", TRUE);
- op_ptr = uiItemFullO(row, "WM_OT_operator_preset_add", "", ICON_ZOOMOUT, op_ptr.data, WM_OP_INVOKE_DEFAULT, 0);
+ uiItemFullO(row, "WM_OT_operator_preset_add", "", ICON_ZOOMOUT, op_ptr.data, WM_OP_INVOKE_DEFAULT, 0);
}
if (op->type->ui) {
diff --git a/source/blender/editors/interface/interface_ops.c b/source/blender/editors/interface/interface_ops.c
index ded5887f7f2..e7a5f993d32 100644
--- a/source/blender/editors/interface/interface_ops.c
+++ b/source/blender/editors/interface/interface_ops.c
@@ -216,7 +216,7 @@ static void eyedropper_color_set(bContext *C, Eyedropper *eye, const float col[3
/* set sample from accumulated values */
static void eyedropper_color_set_accum(bContext *C, Eyedropper *eye)
{
- float col[4];
+ float col[3];
mul_v3_v3fl(col, eye->accum_col, 1.0f / (float)eye->accum_tot);
eyedropper_color_set(C, eye, col);
}
@@ -807,8 +807,7 @@ static int editsource_text_edit(bContext *C, wmOperator *op,
}
if (text == NULL) {
- BKE_reportf(op->reports, RPT_WARNING,
- "file: '%s' can't be opened", filepath);
+ BKE_reportf(op->reports, RPT_WARNING, "File '%s' cannot be opened", filepath);
return OPERATOR_CANCELLED;
}
else {
@@ -820,8 +819,7 @@ static int editsource_text_edit(bContext *C, wmOperator *op,
st->text = text;
}
else {
- BKE_reportf(op->reports, RPT_INFO,
- "See '%s' in the text editor", text->id.name + 2);
+ BKE_reportf(op->reports, RPT_INFO, "See '%s' in the text editor", text->id.name + 2);
}
txt_move_toline(text, line - 1, FALSE);
@@ -857,8 +855,8 @@ static int editsource_exec(bContext *C, wmOperator *op)
!BLI_ghashIterator_isDone(&ghi);
BLI_ghashIterator_step(&ghi))
{
- uiBut *but = BLI_ghashIterator_getKey(&ghi);
- if (but && ui_editsource_uibut_match(&ui_editsource_info->but_orig, but)) {
+ uiBut *but_key = BLI_ghashIterator_getKey(&ghi);
+ if (but_key && ui_editsource_uibut_match(&ui_editsource_info->but_orig, but_key)) {
but_store = BLI_ghashIterator_getValue(&ghi);
break;
}
@@ -872,14 +870,12 @@ static int editsource_exec(bContext *C, wmOperator *op)
but_store->py_dbg_ln);
}
else {
- BKE_report(op->reports, RPT_ERROR,
- "Active button isn't from a script, cant edit source.");
+ BKE_report(op->reports, RPT_ERROR, "Active button is not from a script, cannot edit source");
ret = OPERATOR_CANCELLED;
}
}
else {
- BKE_report(op->reports, RPT_ERROR,
- "Active button match can't be found.");
+ BKE_report(op->reports, RPT_ERROR, "Active button match cannot be found");
ret = OPERATOR_CANCELLED;
}
@@ -915,20 +911,41 @@ static void UI_OT_editsource(wmOperatorType *ot)
static void edittranslation_find_po_file(const char *root, const char *uilng, char *path, const size_t maxlen)
{
char tstr[32]; /* Should be more than enough! */
+
/* First, full lang code. */
BLI_snprintf(tstr, sizeof(tstr), "%s.po", uilng);
BLI_join_dirfile(path, maxlen, root, uilng);
BLI_join_dirfile(path, maxlen, path, tstr);
if (BLI_is_file(path))
return;
+
/* Now try without the second iso code part (_ES in es_ES). */
- strncpy(tstr, uilng, 2);
- BLI_strncpy(tstr + 2, uilng + 5, sizeof(tstr) - 2); /* Because of some codes like sr_SR@latin... */
- BLI_join_dirfile(path, maxlen, root, tstr);
- strcat(tstr, ".po");
- BLI_join_dirfile(path, maxlen, path, tstr);
- if (BLI_is_file(path))
- return;
+ {
+ char *tc = NULL;
+ size_t szt = 0;
+ tstr[0] = '\0';
+
+ tc = strchr(uilng, '_');
+ if (tc) {
+ szt = tc - uilng;
+ if (szt < sizeof(tstr)) /* Paranoid, should always be true! */
+ BLI_strncpy(tstr, uilng, szt + 1); /* +1 for '\0' char! */
+ }
+ if (tstr[0]) {
+ /* Because of some codes like sr_SR@latin... */
+ tc = strchr(uilng, '@');
+ if (tc)
+ BLI_strncpy(tstr + szt, tc, sizeof(tstr) - szt);
+
+ BLI_join_dirfile(path, maxlen, root, tstr);
+ strcat(tstr, ".po");
+ BLI_join_dirfile(path, maxlen, path, tstr);
+ if (BLI_is_file(path))
+ return;
+ }
+ }
+
+ /* Else no po file! */
path[0] = '\0';
}
@@ -956,20 +973,20 @@ static int edittranslation_exec(bContext *C, wmOperator *op)
uiStringInfo rna_ctxt = {BUT_GET_RNA_LABEL_CONTEXT, NULL};
if (!BLI_is_dir(root)) {
- BKE_report(op->reports, RPT_ERROR, "Please set your User Preferences' \"Translation Branches "
- "Directory\" path to a valid directory.");
+ BKE_report(op->reports, RPT_ERROR, "Please set your User Preferences' 'Translation Branches "
+ "Directory' path to a valid directory");
return OPERATOR_CANCELLED;
}
if (!WM_operatortype_find(EDTSRC_I18N_OP_NAME, 0)) {
- BKE_reportf(op->reports, RPT_ERROR, "Could not find operator \"%s\"! Please enable ui_translate addon "
- "in the User Preferences.", EDTSRC_I18N_OP_NAME);
+ BKE_reportf(op->reports, RPT_ERROR, "Could not find operator '%s'! Please enable ui_translate addon "
+ "in the User Preferences", EDTSRC_I18N_OP_NAME);
return OPERATOR_CANCELLED;
}
/* Try to find a valid po file for current language... */
edittranslation_find_po_file(root, uilng, popath, FILE_MAX);
- printf("po path: %s\n", popath);
+/* printf("po path: %s\n", popath);*/
if (popath[0] == '\0') {
- BKE_reportf(op->reports, RPT_ERROR, "No valid po found for language '%s' under %s.", uilng, root);
+ BKE_reportf(op->reports, RPT_ERROR, "No valid po found for language '%s' under %s", uilng, root);
return OPERATOR_CANCELLED;
}
@@ -1021,14 +1038,6 @@ static int edittranslation_exec(bContext *C, wmOperator *op)
}
}
-#if 0
-static int edittranslation_poll(bContext *UNUSED(C))
-{
- /* We need the i18n py addon to be enabled! */
- return WM_operatortype_find(EDTSRC_I18N_OP_NAME, 0) ? TRUE : FALSE;
-}
-#endif
-
static void UI_OT_edittranslation_init(wmOperatorType *ot)
{
/* identifiers */
@@ -1038,7 +1047,6 @@ static void UI_OT_edittranslation_init(wmOperatorType *ot)
/* callbacks */
ot->exec = edittranslation_exec;
-/* ot->poll = edittranslation_poll;*/
}
#endif /* WITH_PYTHON */
diff --git a/source/blender/editors/interface/interface_panel.c b/source/blender/editors/interface/interface_panel.c
index fa3e04d1351..2b170ea546b 100644
--- a/source/blender/editors/interface/interface_panel.c
+++ b/source/blender/editors/interface/interface_panel.c
@@ -240,7 +240,7 @@ Panel *uiBeginPanel(ScrArea *sa, ARegion *ar, uiBlock *block, PanelType *pt, int
}
}
}
- }
+ }
}
}
@@ -357,14 +357,14 @@ void UI_DrawTriIcon(float x, float y, char dir)
}
/* triangle 'icon' inside rect */
-static void ui_draw_tria_rect(rctf *rect, char dir)
+static void ui_draw_tria_rect(const rctf *rect, char dir)
{
if (dir == 'h') {
- float half = 0.5f * BLI_RCT_SIZE_Y(rect);
+ float half = 0.5f * BLI_rctf_size_y(rect);
ui_draw_anti_tria(rect->xmin, rect->ymin, rect->xmin, rect->ymax, rect->xmax, rect->ymin + half);
}
else {
- float half = 0.5f * BLI_RCT_SIZE_X(rect);
+ float half = 0.5f * BLI_rctf_size_x(rect);
ui_draw_anti_tria(rect->xmin, rect->ymax, rect->xmax, rect->ymax, rect->xmin + half, rect->ymin);
}
}
@@ -479,12 +479,12 @@ static void ui_draw_aligned_panel_header(uiStyle *style, uiBlock *block, rcti *r
}
}
-static void rectf_scale(rctf *rect, float scale)
+static void rectf_scale(rctf *rect, const float scale)
{
- float centx = 0.5f * (rect->xmin + rect->xmax);
- float centy = 0.5f * (rect->ymin + rect->ymax);
- float sizex = 0.5f * scale * BLI_RCT_SIZE_X(rect);
- float sizey = 0.5f * scale * BLI_RCT_SIZE_Y(rect);
+ float centx = BLI_rctf_cent_x(rect);
+ float centy = BLI_rctf_cent_y(rect);
+ float sizex = BLI_rctf_size_x(rect) * 0.5f * scale;
+ float sizey = BLI_rctf_size_y(rect) * 0.5f * scale;
rect->xmin = centx - sizex;
rect->xmax = centx + sizex;
@@ -545,9 +545,9 @@ void ui_draw_aligned_panel(uiStyle *style, uiBlock *block, rcti *rect)
if (!(panel->flag & PNL_CLOSEDX)) {
ui_draw_aligned_panel_header(style, block, &headrect, 'h');
- /* itemrect smaller */
+ /* itemrect smaller */
itemrect.xmax = headrect.xmax - 5.0f / block->aspect;
- itemrect.xmin = itemrect.xmax - BLI_RCT_SIZE_Y(&headrect);
+ itemrect.xmin = itemrect.xmax - BLI_rcti_size_y(&headrect);
itemrect.ymin = headrect.ymin;
itemrect.ymax = headrect.ymax;
@@ -594,9 +594,9 @@ void ui_draw_aligned_panel(uiStyle *style, uiBlock *block, rcti *rect)
/* draw collapse icon */
UI_ThemeColor(TH_TEXT);
- /* itemrect smaller */
+ /* itemrect smaller */
itemrect.xmin = headrect.xmin + 5.0f / block->aspect;
- itemrect.xmax = itemrect.xmin + BLI_RCT_SIZE_Y(&headrect);
+ itemrect.xmax = itemrect.xmin + BLI_rcti_size_y(&headrect);
itemrect.ymin = headrect.ymin;
itemrect.ymax = headrect.ymax;
@@ -814,8 +814,8 @@ static void ui_panels_size(ScrArea *sa, ARegion *ar, int *x, int *y)
pa_sizey = pa->ofsy + get_panel_size_y(pa);
}
- sizex = MAX2(sizex, pa_sizex);
- sizey = MIN2(sizey, pa_sizey);
+ sizex = max_ii(sizex, pa_sizex);
+ sizey = min_ii(sizey, pa_sizey);
}
}
@@ -831,7 +831,7 @@ static void ui_do_animate(const bContext *C, Panel *panel)
float fac;
fac = (PIL_check_seconds_timer() - data->starttime) / ANIMATION_TIME;
- fac = minf(sqrt(fac), 1.0f);
+ fac = min_ff(sqrt(fac), 1.0f);
/* for max 1 second, interpolate positions */
if (uiAlignPanelStep(sa, ar, fac, 0)) {
@@ -895,7 +895,7 @@ void uiEndPanels(const bContext *C, ARegion *ar, int *x, int *y)
panew->paneltab = NULL;
ED_region_tag_redraw(ar); /* the buttons panew were not made */
}
- }
+ }
}
/* re-align, possibly with animation */
@@ -985,8 +985,8 @@ static void ui_do_drag(const bContext *C, wmEvent *event, Panel *panel)
dx = (event->x - data->startx) & ~(PNL_GRID - 1);
dy = (event->y - data->starty) & ~(PNL_GRID - 1);
- dx *= (float)BLI_RCT_SIZE_X(&ar->v2d.cur) / (float)BLI_RCT_SIZE_X(&ar->winrct);
- dy *= (float)BLI_RCT_SIZE_Y(&ar->v2d.cur) / (float)BLI_RCT_SIZE_Y(&ar->winrct);
+ dx *= (float)BLI_rctf_size_x(&ar->v2d.cur) / (float)BLI_rcti_size_x(&ar->winrct);
+ dy *= (float)BLI_rctf_size_y(&ar->v2d.cur) / (float)BLI_rcti_size_y(&ar->winrct);
if (data->state == PANEL_STATE_DRAG_SCALE) {
panel->sizex = MAX2(data->startsizex + dx, UI_PANEL_MINX);
@@ -1200,7 +1200,7 @@ int ui_handler_panel_region(bContext *C, wmEvent *event)
ED_region_tag_redraw(ar);
retval = WM_UI_HANDLER_BREAK;
- }
+ }
}
}
#endif
diff --git a/source/blender/editors/interface/interface_regions.c b/source/blender/editors/interface/interface_regions.c
index dc9347b3852..28e361ccf5a 100644
--- a/source/blender/editors/interface/interface_regions.c
+++ b/source/blender/editors/interface/interface_regions.c
@@ -46,6 +46,7 @@
#include "BKE_context.h"
#include "BKE_screen.h"
+#include "BKE_global.h"
#include "WM_api.h"
#include "WM_types.h"
@@ -70,7 +71,6 @@
#include "interface_intern.h"
-#define MENU_SEPR_HEIGHT 6
#define B_NOP -1
#define MENU_SHADOW_SIDE 8
#define MENU_SHADOW_BOTTOM 10
@@ -153,7 +153,7 @@ static void menudata_free(MenuData *md)
* if %xNN is given then NN is the return value if
* that option is selected otherwise the return value
* is the index of the option (starting with 1). %l
- * indicates a seperator, sss%l indicates a label and
+ * indicates a separator, sss%l indicates a label and
* new column.
*
* \param str String to be parsed.
@@ -214,7 +214,7 @@ static MenuData *decompose_menu_string(const char *str)
else {
menudata_add_item(md, nitem, nretval, nicon, 0);
nretval = md->nitems + 1;
- }
+ }
nitem = NULL;
nicon = 0;
@@ -393,7 +393,7 @@ static void ui_tooltip_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
/* draw text */
uiStyleFontSet(&data->fstyle);
- bbox.ymax = bbox.ymax - 0.5f * (BLI_RCT_SIZE_Y(&bbox) - data->toth);
+ bbox.ymax = bbox.ymax - 0.5f * (BLI_rcti_size_y(&bbox) - data->toth);
bbox.ymin = bbox.ymax - data->lineh;
for (i = 0; i < data->totline; i++) {
@@ -671,7 +671,7 @@ ARegion *ui_tooltip_create(bContext *C, ARegion *butregion, uiBut *but)
for (a = 0, fontw = 0, fonth = 0; a < data->totline; a++) {
w = BLF_width(data->fstyle.uifont_id, data->lines[a]);
- fontw = MAX2(fontw, w);
+ fontw = max_ff(fontw, (float)w);
fonth += (a == 0) ? h : h + TIP_MARGIN_Y;
}
@@ -732,9 +732,9 @@ ARegion *ui_tooltip_create(bContext *C, ARegion *butregion, uiBut *but)
/* widget rect, in region coords */
data->bbox.xmin = MENU_SHADOW_SIDE;
- data->bbox.xmax = BLI_RCT_SIZE_X(&rect_i) + MENU_SHADOW_SIDE;
+ data->bbox.xmax = BLI_rcti_size_x(&rect_i) + MENU_SHADOW_SIDE;
data->bbox.ymin = MENU_SHADOW_BOTTOM;
- data->bbox.ymax = BLI_RCT_SIZE_Y(&rect_i) + MENU_SHADOW_BOTTOM;
+ data->bbox.ymax = BLI_rcti_size_y(&rect_i) + MENU_SHADOW_BOTTOM;
/* region bigger for shadow */
ar->winrct.xmin = rect_i.xmin - MENU_SHADOW_SIDE;
@@ -867,8 +867,8 @@ static void ui_searchbox_butrect(rcti *rect, uiSearchboxData *data, int itemnr)
{
/* thumbnail preview */
if (data->preview) {
- int butw = BLI_RCT_SIZE_X(&data->bbox) / data->prv_cols;
- int buth = (BLI_RCT_SIZE_Y(&data->bbox) - 2 * MENU_TOP) / data->prv_rows;
+ int butw = BLI_rcti_size_x(&data->bbox) / data->prv_cols;
+ int buth = (BLI_rcti_size_y(&data->bbox) - 2 * MENU_TOP) / data->prv_rows;
int row, col;
*rect = data->bbox;
@@ -884,7 +884,7 @@ static void ui_searchbox_butrect(rcti *rect, uiSearchboxData *data, int itemnr)
}
/* list view */
else {
- int buth = (BLI_RCT_SIZE_Y(&data->bbox) - 2 * MENU_TOP) / SEARCH_ITEMS;
+ int buth = (BLI_rcti_size_y(&data->bbox) - 2 * MENU_TOP) / SEARCH_ITEMS;
*rect = data->bbox;
rect->xmin = data->bbox.xmin + 3.0f;
@@ -1097,13 +1097,13 @@ static void ui_searchbox_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
if (data->items.more) {
ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
glEnable(GL_BLEND);
- UI_icon_draw((BLI_RCT_SIZE_X(&rect)) / 2, rect.ymin - 9, ICON_TRIA_DOWN);
+ UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymin - 9, ICON_TRIA_DOWN);
glDisable(GL_BLEND);
}
if (data->items.offset) {
ui_searchbox_butrect(&rect, data, 0);
glEnable(GL_BLEND);
- UI_icon_draw((BLI_RCT_SIZE_X(&rect)) / 2, rect.ymax - 7, ICON_TRIA_UP);
+ UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymax - 7, ICON_TRIA_UP);
glDisable(GL_BLEND);
}
}
@@ -1160,7 +1160,7 @@ ARegion *ui_searchbox_create(bContext *C, ARegion *butregion, uiBut *but)
/* special case, hardcoded feature, not draw backdrop when called from menus,
* assume for design that popup already added it */
- if (but->block->flag & UI_BLOCK_LOOP)
+ if (but->block->flag & UI_BLOCK_SEARCH_MENU)
data->noback = 1;
if (but->a1 > 0 && but->a2 > 0) {
@@ -1170,7 +1170,7 @@ ARegion *ui_searchbox_create(bContext *C, ARegion *butregion, uiBut *but)
}
/* compute position */
- if (but->block->flag & UI_BLOCK_LOOP) {
+ if (but->block->flag & UI_BLOCK_SEARCH_MENU) {
/* this case is search menu inside other menu */
/* we copy region size */
@@ -1178,16 +1178,16 @@ ARegion *ui_searchbox_create(bContext *C, ARegion *butregion, uiBut *but)
/* widget rect, in region coords */
data->bbox.xmin = MENU_SHADOW_SIDE;
- data->bbox.xmax = BLI_RCT_SIZE_X(&ar->winrct) - MENU_SHADOW_SIDE;
+ data->bbox.xmax = BLI_rcti_size_x(&ar->winrct) - MENU_SHADOW_SIDE;
data->bbox.ymin = MENU_SHADOW_BOTTOM;
- data->bbox.ymax = BLI_RCT_SIZE_Y(&ar->winrct) - MENU_SHADOW_BOTTOM;
+ data->bbox.ymax = BLI_rcti_size_y(&ar->winrct) - MENU_SHADOW_BOTTOM;
/* check if button is lower half */
- if (but->rect.ymax < BLI_RCT_CENTER_Y(&but->block->rect)) {
- data->bbox.ymin += BLI_RCT_SIZE_Y(&but->rect);
+ if (but->rect.ymax < BLI_rctf_cent_y(&but->block->rect)) {
+ data->bbox.ymin += BLI_rctf_size_y(&but->rect);
}
else {
- data->bbox.ymax -= BLI_RCT_SIZE_Y(&but->rect);
+ data->bbox.ymax -= BLI_rctf_size_y(&but->rect);
}
}
else {
@@ -1202,7 +1202,7 @@ ARegion *ui_searchbox_create(bContext *C, ARegion *butregion, uiBut *but)
BLI_rctf_translate(&rect_fl, ofsx, ofsy);
/* minimal width */
- if (BLI_RCT_SIZE_X(&rect_fl) < 150) {
+ if (BLI_rctf_size_x(&rect_fl) < 150) {
rect_fl.xmax = rect_fl.xmin + 150; /* XXX arbitrary */
}
@@ -1235,15 +1235,15 @@ ARegion *ui_searchbox_create(bContext *C, ARegion *butregion, uiBut *but)
UI_view2d_to_region_no_clip(&butregion->v2d, 0, but->rect.ymax + ofsy, NULL, &newy1);
newy1 += butregion->winrct.ymin;
- rect_i.ymax = BLI_RCT_SIZE_Y(&rect_i) + newy1;
+ rect_i.ymax = BLI_rcti_size_y(&rect_i) + newy1;
rect_i.ymin = newy1;
}
/* widget rect, in region coords */
data->bbox.xmin = MENU_SHADOW_SIDE;
- data->bbox.xmax = BLI_RCT_SIZE_X(&rect_i) + MENU_SHADOW_SIDE;
+ data->bbox.xmax = BLI_rcti_size_x(&rect_i) + MENU_SHADOW_SIDE;
data->bbox.ymin = MENU_SHADOW_BOTTOM;
- data->bbox.ymax = BLI_RCT_SIZE_Y(&rect_i) + MENU_SHADOW_BOTTOM;
+ data->bbox.ymax = BLI_rcti_size_y(&rect_i) + MENU_SHADOW_BOTTOM;
/* region bigger for shadow */
ar->winrct.xmin = rect_i.xmin - MENU_SHADOW_SIDE;
@@ -1342,6 +1342,14 @@ static void ui_block_position(wmWindow *window, ARegion *butregion, uiBut *but,
ui_block_to_window_fl(butregion, but->block, &butrct.xmin, &butrct.ymin);
ui_block_to_window_fl(butregion, but->block, &butrct.xmax, &butrct.ymax);
+ /* widget_roundbox_set has this correction too, keep in sync */
+ if (but->type != PULLDOWN) {
+ if (but->flag & UI_BUT_ALIGN_TOP)
+ butrct.ymax += 1.0f;
+ if (but->flag & UI_BUT_ALIGN_LEFT)
+ butrct.xmin -= 1.0f;
+ }
+
/* calc block rect */
if (block->rect.xmin == 0.0f && block->rect.xmax == 0.0f) {
if (block->buttons.first) {
@@ -1358,15 +1366,15 @@ static void ui_block_position(wmWindow *window, ARegion *butregion, uiBut *but,
}
}
- /* aspect = (float)(BLI_RCT_SIZE_X(&block->rect) + 4);*/ /*UNUSED*/
+ /* aspect = (float)(BLI_rcti_size_x(&block->rect) + 4);*/ /*UNUSED*/
ui_block_to_window_fl(butregion, but->block, &block->rect.xmin, &block->rect.ymin);
ui_block_to_window_fl(butregion, but->block, &block->rect.xmax, &block->rect.ymax);
//block->rect.xmin -= 2.0; block->rect.ymin -= 2.0;
//block->rect.xmax += 2.0; block->rect.ymax += 2.0;
- xsize = BLI_RCT_SIZE_X(&block->rect) + 4; /* 4 for shadow */
- ysize = BLI_RCT_SIZE_Y(&block->rect) + 4;
+ xsize = BLI_rctf_size_x(&block->rect) + 4; /* 4 for shadow */
+ ysize = BLI_rctf_size_y(&block->rect) + 4;
/* aspect /= (float)xsize;*/ /*UNUSED*/
{
@@ -1456,7 +1464,7 @@ static void ui_block_position(wmWindow *window, ARegion *butregion, uiBut *but,
if (top == 0 && down == 0) {
if (dir1 == UI_LEFT || dir1 == UI_RIGHT) {
/* align with bottom of screen */
- // yof= ysize; (not with menu scrolls)
+ // yof = ysize; (not with menu scrolls)
}
}
@@ -1468,9 +1476,6 @@ static void ui_block_position(wmWindow *window, ARegion *butregion, uiBut *but,
}
}
- /* apply requested offset in the block */
- xof += block->xofs / block->aspect;
- yof += block->yofs / block->aspect;
#if 0
/* clamp to window bounds, could be made into an option if its ever annoying */
if ( (offscreen = (block->rect.ymin + yof)) < 0) yof -= offscreen; /* bottom */
@@ -1497,8 +1502,8 @@ static void ui_block_position(wmWindow *window, ARegion *butregion, uiBut *but,
/* safety calculus */
{
- const float midx = BLI_RCT_CENTER_X(&butrct);
- const float midy = BLI_RCT_CENTER_Y(&butrct);
+ const float midx = BLI_rctf_cent_x(&butrct);
+ const float midy = BLI_rctf_cent_y(&butrct);
/* when you are outside parent button, safety there should be smaller */
@@ -1544,7 +1549,11 @@ static void ui_block_region_draw(const bContext *C, ARegion *ar)
static void ui_popup_block_clip(wmWindow *window, uiBlock *block)
{
int winx, winy;
-
+
+ if (block->flag & UI_BLOCK_NO_WIN_CLIP) {
+ return;
+ }
+
wm_window_get_size(window, &winx, &winy);
if (block->rect.xmin < MENU_SHADOW_SIDE)
@@ -1561,8 +1570,6 @@ static void ui_popup_block_clip(wmWindow *window, uiBlock *block)
void ui_popup_block_scrolltest(uiBlock *block)
{
uiBut *bt;
- /* Knowing direction is necessary for multi-column menus... */
- int is_flip = (block->direction & UI_TOP) && !(block->flag & UI_BLOCK_NO_FLIP);
block->flag &= ~(UI_BLOCK_CLIPBOTTOM | UI_BLOCK_CLIPTOP);
@@ -1572,29 +1579,27 @@ void ui_popup_block_scrolltest(uiBlock *block)
if (block->buttons.first == block->buttons.last)
return;
- /* mark buttons that are outside boundary and the ones next to it for arrow(s) */
+ /* mark buttons that are outside boundary */
for (bt = block->buttons.first; bt; bt = bt->next) {
if (bt->rect.ymin < block->rect.ymin) {
bt->flag |= UI_SCROLLED;
block->flag |= UI_BLOCK_CLIPBOTTOM;
- /* make space for arrow */
- if (bt->rect.ymax < block->rect.ymin + 10) {
- if (is_flip && bt->next && bt->next->rect.ymin > bt->rect.ymin)
- bt->next->flag |= UI_SCROLLED;
- else if (!is_flip && bt->prev && bt->prev->rect.ymin > bt->rect.ymin)
- bt->prev->flag |= UI_SCROLLED;
- }
}
if (bt->rect.ymax > block->rect.ymax) {
bt->flag |= UI_SCROLLED;
block->flag |= UI_BLOCK_CLIPTOP;
- /* make space for arrow */
- if (bt->rect.ymin > block->rect.ymax - 10) {
- if (!is_flip && bt->next && bt->next->rect.ymax < bt->rect.ymax)
- bt->next->flag |= UI_SCROLLED;
- else if (is_flip && bt->prev && bt->prev->rect.ymax < bt->rect.ymax)
- bt->prev->flag |= UI_SCROLLED;
- }
+ }
+ }
+
+ /* mark buttons overlapping arrows, if we have them */
+ for (bt = block->buttons.first; bt; bt = bt->next) {
+ if (block->flag & UI_BLOCK_CLIPBOTTOM) {
+ if (bt->rect.ymin < block->rect.ymin + UI_MENU_SCROLL_ARROW)
+ bt->flag |= UI_SCROLLED;
+ }
+ if (block->flag & UI_BLOCK_CLIPTOP) {
+ if (bt->rect.ymax > block->rect.ymax - UI_MENU_SCROLL_ARROW)
+ bt->flag |= UI_SCROLLED;
}
}
}
@@ -1660,12 +1665,10 @@ uiPopupBlockHandle *ui_popup_block_create(bContext *C, ARegion *butregion, uiBut
/* if this is being created from a button */
if (but) {
- if (ELEM(but->type, BLOCK, PULLDOWN))
- block->xofs = -2; /* for proper alignment */
-
block->aspect = but->block->aspect;
ui_block_position(window, butregion, but, block);
+ handle->direction = block->direction;
}
else {
/* keep a list of these, needed for pulldown menus */
@@ -1874,12 +1877,6 @@ static void ui_warp_pointer(int x, int y)
/********************* Color Button ****************/
-/* picker sizes S hsize, F full size, D spacer, B button/pallette height */
-#define SPICK 110.0
-#define FPICK 180.0
-#define DPICK 6.0
-#define BPICK 24.0
-
/* for picker, while editing hsv */
void ui_set_but_hsv(uiBut *but)
{
@@ -1954,7 +1951,7 @@ static void ui_update_block_buts_rgb(uiBlock *block, const float rgb[3])
else if (bt->str[0] == 'V') {
ui_set_but_val(bt, hsv[2]);
}
- }
+ }
ui_check_but(bt);
}
@@ -2053,10 +2050,6 @@ static void do_picker_new_mode_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(a
picker_new_hide_reveal(bt->block, colormode);
}
-/* picker sizes S hsize, F full size, D spacer, B button/pallette height */
-#define SPICK1 150.0
-#define DPICK1 6.0
-
#define PICKER_H 150
#define PICKER_W 150
#define PICKER_SPACE 6
@@ -2094,7 +2087,7 @@ static void square_picker(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop, in
/* a HS circle, V slider, rgb/hsv/hex sliders */
-static void uiBlockPicker(uiBlock *block, float rgba[4], PointerRNA *ptr, PropertyRNA *prop)
+static void uiBlockPicker(uiBlock *block, float rgba[4], PointerRNA *ptr, PropertyRNA *prop, int show_picker)
{
static short colormode = 0; /* temp? 0=rgb, 1=hsv, 2=hex */
uiBut *bt;
@@ -2155,8 +2148,10 @@ static void uiBlockPicker(uiBlock *block, float rgba[4], PointerRNA *ptr, Proper
uiButSetFunc(bt, do_picker_new_mode_cb, bt, NULL);
uiBlockEndAlign(block);
- bt = uiDefIconButO(block, BUT, "UI_OT_eyedropper", WM_OP_INVOKE_DEFAULT, ICON_EYEDROPPER, butwidth + 10, -60, UI_UNIT_X, UI_UNIT_Y, NULL);
- uiButSetFunc(bt, close_popup_cb, bt, NULL);
+ if (show_picker) {
+ bt = uiDefIconButO(block, BUT, "UI_OT_eyedropper", WM_OP_INVOKE_DEFAULT, ICON_EYEDROPPER, butwidth + 10, -60, UI_UNIT_X, UI_UNIT_Y, NULL);
+ uiButSetFunc(bt, close_popup_cb, bt, NULL);
+ }
/* RGB values */
uiBlockBeginAlign(block);
@@ -2241,6 +2236,7 @@ uiBlock *ui_block_func_COLOR(bContext *C, uiPopupBlockHandle *handle, void *arg_
{
uiBut *but = arg_but;
uiBlock *block;
+ int show_picker = TRUE;
block = uiBeginBlock(C, handle->region, __func__, UI_EMBOSS);
@@ -2249,12 +2245,20 @@ uiBlock *ui_block_func_COLOR(bContext *C, uiPopupBlockHandle *handle, void *arg_
block->color_profile = FALSE;
}
}
+
+ if (but->block) {
+ /* if color block is invoked from a popup we wouldn't be able to set color properly
+ * this is because color picker will close popups first and then will try to figure
+ * out active button RNA, and of course it'll fail
+ */
+ show_picker = (but->block->flag & UI_BLOCK_POPUP) == 0;
+ }
uiBlockSetFlag(block, UI_BLOCK_MOVEMOUSE_QUIT);
copy_v3_v3(handle->retvec, but->editvec);
- uiBlockPicker(block, handle->retvec, &but->rnapoin, but->rnaprop);
+ uiBlockPicker(block, handle->retvec, &but->rnapoin, but->rnaprop, show_picker);
block->flag = UI_BLOCK_LOOP | UI_BLOCK_REDRAW | UI_BLOCK_KEEP_OPEN | UI_BLOCK_OUT_1;
uiBoundsBlock(block, 10);
@@ -2343,7 +2347,7 @@ static uiBlock *ui_block_func_POPUP(bContext *C, uiPopupBlockHandle *handle, voi
if (pup->but) {
/* minimum width to enforece */
- minwidth = BLI_RCT_SIZE_X(&pup->but->rect);
+ minwidth = BLI_rctf_size_x(&pup->but->rect);
if (pup->but->type == PULLDOWN || pup->but->menu_create_func) {
direction = UI_DOWN;
@@ -2374,7 +2378,7 @@ static uiBlock *ui_block_func_POPUP(bContext *C, uiPopupBlockHandle *handle, voi
uiBlockSetFlag(block, UI_BLOCK_MOVEMOUSE_QUIT);
if (pup->popup) {
- uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_REDRAW | UI_BLOCK_NUMSELECT | UI_BLOCK_RET_1);
+ uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_REDRAW | UI_BLOCK_NUMSELECT);
uiBlockSetDirection(block, direction);
/* offset the mouse position, possibly based on earlier selection */
@@ -2385,7 +2389,7 @@ static uiBlock *ui_block_func_POPUP(bContext *C, uiPopupBlockHandle *handle, voi
* button, so it doesn't overlap the text too much, also note
* the offset is negative because we are inverse moving the
* block to be under the mouse */
- offset[0] = -(bt->rect.xmin + 0.8f * BLI_RCT_SIZE_X(&bt->rect));
+ offset[0] = -(bt->rect.xmin + 0.8f * BLI_rctf_size_x(&bt->rect));
offset[1] = -(bt->rect.ymin + 0.5f * UI_UNIT_Y);
}
else {
@@ -2393,7 +2397,7 @@ static uiBlock *ui_block_func_POPUP(bContext *C, uiPopupBlockHandle *handle, voi
* on the first item */
offset[0] = 0;
for (bt = block->buttons.first; bt; bt = bt->next)
- offset[0] = mini(offset[0], -(bt->rect.xmin + 0.8f * BLI_RCT_SIZE_X(&bt->rect)));
+ offset[0] = min_ii(offset[0], -(bt->rect.xmin + 0.8f * BLI_rctf_size_x(&bt->rect)));
offset[1] = 1.5 * UI_UNIT_Y;
}
@@ -2502,8 +2506,10 @@ uiPopupMenu *uiPupMenuBegin(bContext *C, const char *title, int icon)
pup->block = uiBeginBlock(C, NULL, __func__, UI_EMBOSSP);
pup->block->flag |= UI_BLOCK_POPUP_MEMORY;
pup->block->puphash = ui_popup_menu_hash(title);
- pup->block->auto_is_first_event = TRUE;
pup->layout = uiBlockLayout(pup->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_MENU, 0, 0, 200, 0, style);
+
+ /* note, this intentionally differs from the menu & submenu default because many operators
+ * use popups like this to select one of their options - where having invoke doesn't make sense */
uiLayoutSetOperatorContext(pup->layout, WM_OP_EXEC_REGION_WIN);
/* create in advance so we can let buttons point to retval already */
@@ -2576,6 +2582,11 @@ static void confirm_cancel_operator(void *opv)
}
static void vconfirm_opname(bContext *C, const char *opname, const char *title, const char *itemfmt, va_list ap)
+#ifdef __GNUC__
+__attribute__ ((format(printf, 4, 0)))
+#endif
+;
+static void vconfirm_opname(bContext *C, const char *opname, const char *title, const char *itemfmt, va_list ap)
{
uiPopupBlockHandle *handle;
char *s, buf[512];
@@ -2667,14 +2678,18 @@ void uiPupMenuReports(bContext *C, ReportList *reports)
ds = BLI_dynstr_new();
for (report = reports->list.first; report; report = report->next) {
- if (report->type < reports->printlevel)
- ; /* pass */
- else if (report->type >= RPT_ERROR)
+ if (report->type < reports->printlevel) {
+ /* pass */
+ }
+ else if (report->type >= RPT_ERROR) {
BLI_dynstr_appendf(ds, "Error %%i%d%%t|%s", ICON_ERROR, report->message);
- else if (report->type >= RPT_WARNING)
+ }
+ else if (report->type >= RPT_WARNING) {
BLI_dynstr_appendf(ds, "Warning %%i%d%%t|%s", ICON_ERROR, report->message);
- else if (report->type >= RPT_INFO)
+ }
+ else if (report->type >= RPT_INFO) {
BLI_dynstr_appendf(ds, "Info %%i%d%%t|%s", ICON_INFO, report->message);
+ }
}
str = BLI_dynstr_get_cstring(ds);
@@ -2706,6 +2721,10 @@ void uiPupMenuInvoke(bContext *C, const char *idname)
menu.layout = layout;
menu.type = mt;
+ if (G.debug & G_DEBUG_WM) {
+ printf("%s: opening menu \"%s\"\n", __func__, idname);
+ }
+
mt->draw(C, &menu);
uiPupMenuEnd(C, pup);
diff --git a/source/blender/editors/interface/interface_style.c b/source/blender/editors/interface/interface_style.c
index b16250021d3..7e7db6aeaaa 100644
--- a/source/blender/editors/interface/interface_style.c
+++ b/source/blender/editors/interface/interface_style.c
@@ -152,17 +152,17 @@ void uiStyleFontDrawExt(uiFontStyle *fs, rcti *rect, const char *str,
uiStyleFontSet(fs);
height = BLF_ascender(fs->uifont_id);
- yofs = ceil(0.5f * (BLI_RCT_SIZE_Y(rect) - height));
+ yofs = ceil(0.5f * (BLI_rcti_size_y(rect) - height));
if (fs->align == UI_STYLE_TEXT_CENTER) {
- xofs = floor(0.5f * (BLI_RCT_SIZE_X(rect) - BLF_width(fs->uifont_id, str)));
+ xofs = floor(0.5f * (BLI_rcti_size_x(rect) - BLF_width(fs->uifont_id, str)));
/* don't center text if it chops off the start of the text, 2 gives some margin */
if (xofs < 2) {
xofs = 2;
}
}
else if (fs->align == UI_STYLE_TEXT_RIGHT) {
- xofs = BLI_RCT_SIZE_X(rect) - BLF_width(fs->uifont_id, str) - 1;
+ xofs = BLI_rcti_size_x(rect) - BLF_width(fs->uifont_id, str) - 1;
}
/* clip is very strict, so we give it some space */
@@ -209,7 +209,7 @@ void uiStyleFontDrawRotated(uiFontStyle *fs, rcti *rect, const char *str)
height = BLF_ascender(fs->uifont_id);
/* becomes x-offset when rotated */
- xofs = ceil(0.5f * (BLI_RCT_SIZE_Y(rect) - height));
+ xofs = ceil(0.5f * (BLI_rcti_size_y(rect) - height));
/* ignore UI_STYLE, always aligned to top */
@@ -219,8 +219,8 @@ void uiStyleFontDrawRotated(uiFontStyle *fs, rcti *rect, const char *str)
angle = 90.0f;
/* translate rect to vertical */
- txtrect.xmin = rect->xmin - BLI_RCT_SIZE_Y(rect);
- txtrect.ymin = rect->ymin - BLI_RCT_SIZE_X(rect);
+ txtrect.xmin = rect->xmin - BLI_rcti_size_y(rect);
+ txtrect.ymin = rect->ymin - BLI_rcti_size_x(rect);
txtrect.xmax = rect->xmin;
txtrect.ymax = rect->ymin;
@@ -348,7 +348,7 @@ void uiStyleInit(void)
#else
font->blf_id = BLF_load_mem("default", (unsigned char *)datatoc_bfont_ttf, datatoc_bfont_ttf_size);
#endif
- }
+ }
else {
font->blf_id = BLF_load(font->filename);
if (font->blf_id == -1)
diff --git a/source/blender/editors/interface/interface_templates.c b/source/blender/editors/interface/interface_templates.c
index 79b9d313775..24aca0c037d 100644
--- a/source/blender/editors/interface/interface_templates.c
+++ b/source/blender/editors/interface/interface_templates.c
@@ -35,6 +35,7 @@
#include "DNA_dynamicpaint_types.h"
#include "DNA_key_types.h"
#include "DNA_scene_types.h"
+#include "DNA_object_types.h"
#include "DNA_userdef_types.h"
#include "BLI_utildefines.h"
@@ -56,6 +57,7 @@
#include "BKE_texture.h"
#include "BKE_report.h"
#include "BKE_displist.h"
+#include "BKE_sca.h"
#include "BKE_scene.h"
#include "ED_screen.h"
@@ -173,7 +175,7 @@ static uiBlock *id_search_menu(bContext *C, ARegion *ar, void *arg_litem)
idptr = RNA_property_pointer_get(&template.ptr, template.prop);
block = uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
- uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_REDRAW | UI_BLOCK_RET_1);
+ uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_REDRAW | UI_BLOCK_SEARCH_MENU);
/* preview thumbnails */
if (template.prv_rows > 0 && template.prv_cols > 0) {
@@ -197,7 +199,7 @@ static uiBlock *id_search_menu(bContext *C, ARegion *ar, void *arg_litem)
uiBoundsBlock(block, 6);
- uiBlockSetDirection(block, UI_DOWN);
+ uiBlockSetDirection(block, UI_DOWN);
uiEndBlock(C, block);
/* give search-field focus */
@@ -360,6 +362,7 @@ static void template_ID(bContext *C, uiLayout *layout, TemplateID *template, Str
type = idptr.type;
if (flag & UI_ID_PREVIEWS) {
+ template->preview = TRUE;
but = uiDefBlockButN(block, id_search_menu, MEM_dupallocN(template), "", 0, 0, UI_UNIT_X * 6, UI_UNIT_Y * 6,
TIP_(template_id_browse_tip(type)));
@@ -372,7 +375,6 @@ static void template_ID(bContext *C, uiLayout *layout, TemplateID *template, Str
uiButSetFlag(but, UI_BUT_DISABLED);
uiLayoutRow(layout, TRUE);
- template->preview = 1;
}
else if (flag & UI_ID_BROWSE) {
but = uiDefBlockButN(block, id_search_menu, MEM_dupallocN(template), "", 0, 0, UI_UNIT_X * 1.6, UI_UNIT_Y,
@@ -398,7 +400,7 @@ static void template_ID(bContext *C, uiLayout *layout, TemplateID *template, Str
//text_idbutton(id, name);
name[0] = '\0';
- but = uiDefButR(block, TEX, 0, name, 0, 0, UI_UNIT_X * 6, UI_UNIT_Y, &idptr, "name", -1, 0, 0, -1, -1, NULL);
+ but = uiDefButR(block, TEX, 0, name, 0, 0, UI_UNIT_X * 6, UI_UNIT_Y, &idptr, "name", -1, 0, 0, -1, -1, RNA_struct_ui_description(type));
uiButSetNFunc(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_RENAME));
if (user_alert) uiButSetFlag(but, UI_BUT_REDALERT);
@@ -427,8 +429,15 @@ static void template_ID(bContext *C, uiLayout *layout, TemplateID *template, Str
TIP_("Display number of users of this data (click to make a single-user copy)"));
uiButSetNFunc(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_ALONE));
- if (!id_copy(id, NULL, 1 /* test only */) || (idfrom && idfrom->lib) || !editable)
+ if (/* test only */
+ (id_copy(id, NULL, 1) == FALSE) ||
+ (idfrom && idfrom->lib) ||
+ (editable == FALSE) ||
+ /* object in editmode - don't change data */
+ (idfrom && GS(idfrom->name) == ID_OB && (((Object *)idfrom)->mode & OB_MODE_EDIT)))
+ {
uiButSetFlag(but, UI_BUT_DISABLED);
+ }
}
if (user_alert) uiButSetFlag(but, UI_BUT_REDALERT);
@@ -571,7 +580,7 @@ void uiTemplateAnyID(uiLayout *layout, PointerRNA *ptr, const char *propname, co
RNA_warning("pointer property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
return;
}
- if (!propType || RNA_property_type(propType) != PROP_ENUM) {
+ if (!propType || RNA_property_type(propType) != PROP_ENUM) {
RNA_warning("pointer-type property not found: %s.%s", RNA_struct_identifier(ptr->type), proptypename);
return;
}
@@ -929,28 +938,26 @@ uiLayout *uiTemplateModifier(uiLayout *layout, bContext *C, PointerRNA *ptr)
#include "BKE_action.h"
#include "BKE_constraint.h"
-#define REDRAWIPO 1
-#define REDRAWNLA 2
-#define REDRAWBUTSOBJECT 3
-#define REDRAWACTION 4
#define B_CONSTRAINT_TEST 5
-#define B_CONSTRAINT_CHANGETARGET 6
-#define REMAKEIPO 8
-#define B_DIFF 9
+// #define B_CONSTRAINT_CHANGETARGET 6
static void do_constraint_panels(bContext *C, void *ob_pt, int event)
{
- Main *bmain = CTX_data_main(C);
- Scene *scene = CTX_data_scene(C);
Object *ob = (Object *)ob_pt;
switch (event) {
case B_CONSTRAINT_TEST:
break; /* no handling */
+#if 0 /* UNUSED */
case B_CONSTRAINT_CHANGETARGET:
+ {
+ Main *bmain = CTX_data_main(C);
+ Scene *scene = CTX_data_scene(C);
if (ob->pose) ob->pose->flag |= POSE_RECALC; /* checks & sorts pose channels */
DAG_scene_sort(bmain, scene);
break;
+ }
+#endif
default:
break;
}
@@ -1214,7 +1221,7 @@ void uiTemplatePreview(uiLayout *layout, ID *id, int show_buttons, ID *parent, M
else ma = (Material *)pparent;
/* Create RNA Pointer */
- RNA_pointer_create(id, &RNA_Material, ma, &material_ptr);
+ RNA_pointer_create(&ma->id, &RNA_Material, ma, &material_ptr);
col = uiLayoutColumn(row, TRUE);
uiLayoutSetScaleX(col, 1.5);
@@ -1262,8 +1269,6 @@ static void rna_update_cb(bContext *C, void *arg_cb, void *UNUSED(arg))
RNA_property_update(C, &cb->ptr, cb->prop);
}
-#define B_BANDCOL 1
-
static void colorband_add_cb(bContext *C, void *cb_v, void *coba_v)
{
ColorBand *coba = coba_v;
@@ -1276,7 +1281,7 @@ static void colorband_add_cb(bContext *C, void *cb_v, void *coba_v)
if (colorband_element_add(coba, pos)) {
rna_update_cb(C, cb_v, NULL);
- ED_undo_push(C, "Add colorband");
+ ED_undo_push(C, "Add colorband");
}
}
@@ -1379,7 +1384,7 @@ static void colorband_buttons_large(uiLayout *layout, uiBlock *block, ColorBand
static void colorband_buttons_small(uiLayout *layout, uiBlock *block, ColorBand *coba, rctf *butr, RNAUpdateCb *cb)
{
uiBut *bt;
- float unit = BLI_RCT_SIZE_X(butr) / 14.0f;
+ float unit = BLI_rctf_size_x(butr) / 14.0f;
float xs = butr->xmin;
uiBlockBeginAlign(block);
@@ -1400,12 +1405,12 @@ static void colorband_buttons_small(uiLayout *layout, uiBlock *block, ColorBand
uiItemR(layout, &ptr, "color", 0, "", ICON_NONE);
}
- bt = uiDefButS(block, MENU, 0, TIP_("Interpolation %t|Ease %x1|Cardinal %x3|Linear %x0|B-Spline %x2|Constant %x4"),
+ bt = uiDefButS(block, MENU, 0, IFACE_("Interpolation %t|Ease %x1|Cardinal %x3|Linear %x0|B-Spline %x2|Constant %x4"),
xs + 10.0f * unit, butr->ymin + UI_UNIT_Y, unit * 4, UI_UNIT_Y, &coba->ipotype, 0.0, 0.0, 0, 0,
TIP_("Set interpolation between color stops"));
uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
- bt = uiDefBut(block, BUT_COLORBAND, 0, "", xs, butr->ymin, BLI_RCT_SIZE_X(butr), UI_UNIT_Y, coba, 0, 0, 0, 0, "");
+ bt = uiDefBut(block, BUT_COLORBAND, 0, "", xs, butr->ymin, BLI_rctf_size_x(butr), UI_UNIT_Y, coba, 0, 0, 0, 0, "");
uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
uiBlockEndAlign(block);
@@ -1480,7 +1485,7 @@ void uiTemplateHistogram(uiLayout *layout, PointerRNA *ptr, const char *propname
hist->height = (hist->height <= UI_UNIT_Y) ? UI_UNIT_Y : hist->height;
- bt = uiDefBut(block, HISTOGRAM, 0, "", rect.xmin, rect.ymin, BLI_RCT_SIZE_X(&rect), hist->height, hist, 0, 0, 0, 0, "");
+ bt = uiDefBut(block, HISTOGRAM, 0, "", rect.xmin, rect.ymin, BLI_rctf_size_x(&rect), hist->height, hist, 0, 0, 0, 0, "");
uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
MEM_freeN(cb);
@@ -1517,7 +1522,7 @@ void uiTemplateWaveform(uiLayout *layout, PointerRNA *ptr, const char *propname)
scopes->wavefrm_height = (scopes->wavefrm_height <= UI_UNIT_Y) ? UI_UNIT_Y : scopes->wavefrm_height;
- bt = uiDefBut(block, WAVEFORM, 0, "", rect.xmin, rect.ymin, BLI_RCT_SIZE_X(&rect), scopes->wavefrm_height, scopes, 0, 0, 0, 0, "");
+ bt = uiDefBut(block, WAVEFORM, 0, "", rect.xmin, rect.ymin, BLI_rctf_size_x(&rect), scopes->wavefrm_height, scopes, 0, 0, 0, 0, "");
(void)bt; /* UNUSED */
MEM_freeN(cb);
@@ -1554,7 +1559,7 @@ void uiTemplateVectorscope(uiLayout *layout, PointerRNA *ptr, const char *propna
scopes->vecscope_height = (scopes->vecscope_height <= UI_UNIT_Y) ? UI_UNIT_Y : scopes->vecscope_height;
- bt = uiDefBut(block, VECTORSCOPE, 0, "", rect.xmin, rect.ymin, BLI_RCT_SIZE_X(&rect), scopes->vecscope_height, scopes, 0, 0, 0, 0, "");
+ bt = uiDefBut(block, VECTORSCOPE, 0, "", rect.xmin, rect.ymin, BLI_rctf_size_x(&rect), scopes->vecscope_height, scopes, 0, 0, 0, 0, "");
uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
MEM_freeN(cb);
@@ -1569,11 +1574,11 @@ static void curvemap_buttons_zoom_in(bContext *C, void *cumap_v, void *UNUSED(ar
float d;
/* we allow 20 times zoom */
- if (BLI_RCT_SIZE_X(&cumap->curr) > 0.04f * BLI_RCT_SIZE_X(&cumap->clipr)) {
- d = 0.1154f * BLI_RCT_SIZE_X(&cumap->curr);
+ if (BLI_rctf_size_x(&cumap->curr) > 0.04f * BLI_rctf_size_x(&cumap->clipr)) {
+ d = 0.1154f * BLI_rctf_size_x(&cumap->curr);
cumap->curr.xmin += d;
cumap->curr.xmax -= d;
- d = 0.1154f * BLI_RCT_SIZE_Y(&cumap->curr);
+ d = 0.1154f * BLI_rctf_size_y(&cumap->curr);
cumap->curr.ymin += d;
cumap->curr.ymax -= d;
}
@@ -1587,8 +1592,8 @@ static void curvemap_buttons_zoom_out(bContext *C, void *cumap_v, void *UNUSED(u
float d, d1;
/* we allow 20 times zoom, but don't view outside clip */
- if (BLI_RCT_SIZE_X(&cumap->curr) < 20.0f * BLI_RCT_SIZE_X(&cumap->clipr)) {
- d = d1 = 0.15f * BLI_RCT_SIZE_X(&cumap->curr);
+ if (BLI_rctf_size_x(&cumap->curr) < 20.0f * BLI_rctf_size_x(&cumap->clipr)) {
+ d = d1 = 0.15f * BLI_rctf_size_x(&cumap->curr);
if (cumap->flag & CUMA_DO_CLIP)
if (cumap->curr.xmin - d < cumap->clipr.xmin)
@@ -1601,7 +1606,7 @@ static void curvemap_buttons_zoom_out(bContext *C, void *cumap_v, void *UNUSED(u
d1 = -cumap->curr.xmax + cumap->clipr.xmax;
cumap->curr.xmax += d1;
- d = d1 = 0.15f * BLI_RCT_SIZE_Y(&cumap->curr);
+ d = d1 = 0.15f * BLI_rctf_size_y(&cumap->curr);
if (cumap->flag & CUMA_DO_CLIP)
if (cumap->curr.ymin - d < cumap->clipr.ymin)
@@ -1744,11 +1749,11 @@ static void curvemap_buttons_redraw(bContext *C, void *UNUSED(arg1), void *UNUSE
ED_region_tag_redraw(CTX_wm_region(C));
}
-static void curvemap_buttons_update(bContext *UNUSED(C), void *UNUSED(arg1), void *cumap_v)
+static void curvemap_buttons_update(bContext *C, void *arg1_v, void *cumap_v)
{
CurveMapping *cumap = cumap_v;
-
curvemapping_changed(cumap, TRUE);
+ rna_update_cb(C, arg1_v, NULL);
}
static void curvemap_buttons_reset(bContext *C, void *cb_v, void *cumap_v)
@@ -1869,7 +1874,7 @@ static void curvemap_buttons_layout(uiLayout *layout, PointerRNA *ptr, char labe
uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
- if (cumap->flag & CUMA_DO_CLIP) icon = ICON_CLIPUV_HLT; else icon = ICON_CLIPUV_DEHLT;
+ icon = (cumap->flag & CUMA_DO_CLIP) ? ICON_CLIPUV_HLT : ICON_CLIPUV_DEHLT;
bt = uiDefIconBlockBut(block, curvemap_clipping_func, cumap, 0, icon, 0, 0, dx, dx, TIP_("Clipping Options"));
uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
@@ -1895,9 +1900,9 @@ static void curvemap_buttons_layout(uiLayout *layout, PointerRNA *ptr, char labe
if (cmp) {
uiLayoutRow(layout, TRUE);
- uiBlockSetNFunc(block, curvemap_buttons_update, NULL, cumap);
- uiDefButF(block, NUM, 0, "X", 0, 2 * UI_UNIT_Y, UI_UNIT_X * 10, UI_UNIT_Y, &cmp->x, 0.0f, 1.0f, 1, 5, "");
- uiDefButF(block, NUM, 0, "Y", 0, 1 * UI_UNIT_Y, UI_UNIT_X * 10, UI_UNIT_Y, &cmp->y, 0.0f, 1.0f, 1, 5, "");
+ uiBlockSetNFunc(block, curvemap_buttons_update, MEM_dupallocN(cb), cumap);
+ bt = uiDefButF(block, NUM, 0, "X", 0, 2 * UI_UNIT_Y, UI_UNIT_X * 10, UI_UNIT_Y, &cmp->x, 0.0f, 1.0f, 1, 5, "");
+ bt = uiDefButF(block, NUM, 0, "Y", 0, 1 * UI_UNIT_Y, UI_UNIT_X * 10, UI_UNIT_Y, &cmp->y, 0.0f, 1.0f, 1, 5, "");
}
/* black/white levels */
@@ -2085,6 +2090,74 @@ void uiTemplateLayers(uiLayout *layout, PointerRNA *ptr, const char *propname,
}
}
+void uiTemplateGameStates(uiLayout *layout, PointerRNA *ptr, const char *propname,
+ PointerRNA *used_ptr, const char *used_propname, int active_state)
+{
+ uiLayout *uRow, *uCol;
+ PropertyRNA *prop, *used_prop = NULL;
+ int groups, cols, states;
+ int group, col, state, row;
+ int cols_per_group = 5;
+ Object *ob = (Object *)ptr->id.data;
+
+ prop = RNA_struct_find_property(ptr, propname);
+ if (!prop) {
+ RNA_warning("states property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
+ return;
+ }
+
+ /* the number of states determines the way we group them
+ * - we want 2 rows only (for now)
+ * - the number of columns (cols) is the total number of buttons per row
+ * the 'remainder' is added to this, as it will be ok to have first row slightly wider if need be
+ * - for now, only split into groups if group will have at least 5 items
+ */
+ states = RNA_property_array_length(ptr, prop);
+ cols = (states / 2) + (states % 2);
+ groups = ((cols / 2) < cols_per_group) ? (1) : (cols / cols_per_group);
+
+ if (used_ptr && used_propname) {
+ used_prop = RNA_struct_find_property(used_ptr, used_propname);
+ if (!used_prop) {
+ RNA_warning("used layers property not found: %s.%s", RNA_struct_identifier(ptr->type), used_propname);
+ return;
+ }
+
+ if (RNA_property_array_length(used_ptr, used_prop) < states)
+ used_prop = NULL;
+ }
+
+ /* layers are laid out going across rows, with the columns being divided into groups */
+
+ for (group = 0; group < groups; group++) {
+ uCol = uiLayoutColumn(layout, TRUE);
+
+ for (row = 0; row < 2; row++) {
+ uiBlock *block;
+ uiBut *but;
+
+ uRow = uiLayoutRow(uCol, TRUE);
+ block = uiLayoutGetBlock(uRow);
+ state = groups * cols_per_group * row + cols_per_group * group;
+
+ /* add layers as toggle buts */
+ for (col = 0; (col < cols_per_group) && (state < states); col++, state++) {
+ int icon = 0;
+ int butlay = 1 << state;
+
+ if (active_state & butlay)
+ icon = ICON_LAYER_ACTIVE;
+ else if (used_prop && RNA_property_boolean_get_index(used_ptr, used_prop, state))
+ icon = ICON_LAYER_USED;
+
+ but = uiDefIconButR_prop(block, ICONTOG, 0, icon, 0, 0, UI_UNIT_X / 2, UI_UNIT_Y / 2, ptr, prop, state, 0, 0, -1, -1, sca_state_name_get(ob, state));
+ uiButSetFunc(but, handle_layer_buttons, but, SET_INT_IN_POINTER(state));
+ but->type = TOG;
+ }
+ }
+ }
+}
+
/************************* List Template **************************/
@@ -2671,7 +2744,7 @@ void uiTemplateRunningJobs(uiLayout *layout, bContext *C)
uiDefIconTextBut(block, BUT, B_STOPCAST, ICON_CANCEL, IFACE_("Capture"), 0, 0, 85, UI_UNIT_Y, NULL, 0.0f, 0.0f, 0, 0,
TIP_("Stop screencast"));
if (screen->animtimer)
- uiDefIconTextBut(block, BUT, B_STOPANIM, ICON_CANCEL, TIP_("Anim Player"), 0, 0, 100, UI_UNIT_Y, NULL, 0.0f, 0.0f, 0, 0,
+ uiDefIconTextBut(block, BUT, B_STOPANIM, ICON_CANCEL, IFACE_("Anim Player"), 0, 0, 100, UI_UNIT_Y, NULL, 0.0f, 0.0f, 0, 0,
TIP_("Stop animation playback"));
}
@@ -2701,8 +2774,8 @@ void uiTemplateReportsBanner(uiLayout *layout, bContext *C)
block = uiLayoutGetBlock(ui_abs);
width = BLF_width(style->widget.uifont_id, report->message);
- width = MIN2(rti->widthfac * width, width);
- width = MAX2(width, 10);
+ width = min_ii((int)(rti->widthfac * width), width);
+ width = max_ii(width, 10);
/* make a box around the report to make it stand out */
uiBlockBeginAlign(block);
diff --git a/source/blender/editors/interface/interface_widgets.c b/source/blender/editors/interface/interface_widgets.c
index 8a7f2d9ca47..f41abce947e 100644
--- a/source/blender/editors/interface/interface_widgets.c
+++ b/source/blender/editors/interface/interface_widgets.c
@@ -259,8 +259,8 @@ static int round_box_shadow_edges(float (*vert)[2], rcti *rect, float rad, int r
rad += step;
- if (2.0f * rad > BLI_RCT_SIZE_Y(rect))
- rad = 0.5f * BLI_RCT_SIZE_Y(rect);
+ if (2.0f * rad > BLI_rcti_size_y(rect))
+ rad = 0.5f * BLI_rcti_size_y(rect);
minx = rect->xmin - step;
miny = rect->ymin - step;
@@ -345,8 +345,8 @@ static void round_box__edges(uiWidgetBase *wt, int roundboxalign, rcti *rect, fl
const int vnum = ((roundboxalign & (UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT)) == (UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT) ||
(roundboxalign & (UI_CNR_TOP_RIGHT | UI_CNR_BOTTOM_RIGHT)) == (UI_CNR_TOP_RIGHT | UI_CNR_BOTTOM_RIGHT)) ? 1 : 2;
- minsize = mini(BLI_RCT_SIZE_X(rect) * hnum,
- BLI_RCT_SIZE_Y(rect) * vnum);
+ minsize = min_ii(BLI_rcti_size_x(rect) * hnum,
+ BLI_rcti_size_y(rect) * vnum);
if (2.0f * rad > minsize)
rad = 0.5f * minsize;
@@ -491,7 +491,7 @@ static void widget_num_tria(uiWidgetTrias *tria, rcti *rect, float triasize, cha
float centx, centy, sizex, sizey, minsize;
int a, i1 = 0, i2 = 1;
- minsize = mini(BLI_RCT_SIZE_X(rect), BLI_RCT_SIZE_Y(rect));
+ minsize = min_ii(BLI_rcti_size_x(rect), BLI_rcti_size_y(rect));
/* center position and size */
centx = (float)rect->xmin + 0.5f * minsize;
@@ -501,16 +501,16 @@ static void widget_num_tria(uiWidgetTrias *tria, rcti *rect, float triasize, cha
if (where == 'r') {
centx = (float)rect->xmax - 0.5f * minsize;
sizex = -sizex;
- }
+ }
else if (where == 't') {
centy = (float)rect->ymax - 0.5f * minsize;
sizey = -sizey;
i2 = 0; i1 = 1;
- }
+ }
else if (where == 'b') {
sizex = -sizex;
i2 = 0; i1 = 1;
- }
+ }
for (a = 0; a < 3; a++) {
tria->vec[a][0] = sizex * num_tria_vert[a][i1] + centx;
@@ -526,7 +526,7 @@ static void widget_scroll_circle(uiWidgetTrias *tria, rcti *rect, float triasize
float centx, centy, sizex, sizey, minsize;
int a, i1 = 0, i2 = 1;
- minsize = mini(BLI_RCT_SIZE_X(rect), BLI_RCT_SIZE_Y(rect));
+ minsize = min_ii(BLI_rcti_size_x(rect), BLI_rcti_size_y(rect));
/* center position and size */
centx = (float)rect->xmin + 0.5f * minsize;
@@ -536,16 +536,16 @@ static void widget_scroll_circle(uiWidgetTrias *tria, rcti *rect, float triasize
if (where == 'r') {
centx = (float)rect->xmax - 0.5f * minsize;
sizex = -sizex;
- }
+ }
else if (where == 't') {
centy = (float)rect->ymax - 0.5f * minsize;
sizey = -sizey;
i2 = 0; i1 = 1;
- }
+ }
else if (where == 'b') {
sizex = -sizex;
i2 = 0; i1 = 1;
- }
+ }
for (a = 0; a < 16; a++) {
tria->vec[a][0] = sizex * scroll_circle_vert[a][i1] + centx;
@@ -570,14 +570,14 @@ static void widget_menu_trias(uiWidgetTrias *tria, rcti *rect)
int a;
/* center position and size */
- centx = rect->xmax - 0.5f * BLI_RCT_SIZE_Y(rect);
- centy = rect->ymin + 0.5f * BLI_RCT_SIZE_Y(rect);
- size = 0.4f * BLI_RCT_SIZE_Y(rect);
+ centx = rect->xmax - 0.5f * BLI_rcti_size_y(rect);
+ centy = rect->ymin + 0.5f * BLI_rcti_size_y(rect);
+ size = 0.4f * (float)BLI_rcti_size_y(rect);
/* XXX exception */
- asp = ((float)BLI_RCT_SIZE_X(rect)) / ((float)BLI_RCT_SIZE_Y(rect));
+ asp = ((float)BLI_rcti_size_x(rect)) / ((float)BLI_rcti_size_y(rect));
if (asp > 1.2f && asp < 2.6f)
- centx = rect->xmax - 0.3f * BLI_RCT_SIZE_Y(rect);
+ centx = rect->xmax - 0.4f * (float)BLI_rcti_size_y(rect);
for (a = 0; a < 6; a++) {
tria->vec[a][0] = size * menu_tria_vert[a][0] + centx;
@@ -594,9 +594,9 @@ static void widget_check_trias(uiWidgetTrias *tria, rcti *rect)
int a;
/* center position and size */
- centx = rect->xmin + 0.5f * BLI_RCT_SIZE_Y(rect);
- centy = rect->ymin + 0.5f * BLI_RCT_SIZE_Y(rect);
- size = 0.5f * BLI_RCT_SIZE_Y(rect);
+ centx = rect->xmin + 0.5f * BLI_rcti_size_y(rect);
+ centy = rect->ymin + 0.5f * BLI_rcti_size_y(rect);
+ size = 0.5f * BLI_rcti_size_y(rect);
for (a = 0; a < 6; a++) {
tria->vec[a][0] = size * check_tria_vert[a][0] + centx;
@@ -840,8 +840,8 @@ static void widget_draw_preview(BIFIconID icon, float UNUSED(alpha), rcti *rect)
if (icon == ICON_NONE)
return;
- w = BLI_RCT_SIZE_X(rect);
- h = BLI_RCT_SIZE_Y(rect);
+ w = BLI_rcti_size_x(rect);
+ h = BLI_rcti_size_y(rect);
size = MIN2(w, h);
size -= PREVIEW_PAD * 2; /* padding */
@@ -878,7 +878,7 @@ static void widget_draw_icon(uiBut *but, BIFIconID icon, float alpha, rcti *rect
aspect = but->block->aspect;
if (aspect != but->aspect) {
/* prevent scaling up icon in pupmenu */
- if (aspect < 1.0f) {
+ if (aspect < 1.0f) {
height = UI_DPI_ICON_SIZE;
aspect = 1.0f;
@@ -891,8 +891,8 @@ static void widget_draw_icon(uiBut *but, BIFIconID icon, float alpha, rcti *rect
/* calculate blend color */
if (ELEM4(but->type, TOG, ROW, TOGN, LISTROW)) {
- if (but->flag & UI_SELECT) ;
- else if (but->flag & UI_ACTIVE) ;
+ if (but->flag & UI_SELECT) {}
+ else if (but->flag & UI_ACTIVE) {}
else alpha = 0.5f;
}
@@ -965,76 +965,110 @@ static void ui_text_clip_give_next_off(uiBut *but)
but->ofs += bytes;
}
-/* sets but->ofs to make sure text is correctly visible */
-static void ui_text_leftclip(uiFontStyle *fstyle, uiBut *but, rcti *rect)
+/**
+ * Cut off the start of the text to fit into the width of \a rect
+ *
+ * \note Sets but->ofs to make sure text is correctly visible.
+ * \note Clips right in some cases, this function could be cleaned up.
+ */
+static void ui_text_clip_left(uiFontStyle *fstyle, uiBut *but, rcti *rect)
{
int border = (but->flag & UI_BUT_ALIGN_RIGHT) ? 8 : 10;
- int okwidth = BLI_RCT_SIZE_X(rect) - border;
-
+ int okwidth = BLI_rcti_size_x(rect) - border;
if (but->flag & UI_HAS_ICON) okwidth -= UI_DPI_ICON_SIZE;
-
+
/* need to set this first */
uiStyleFontSet(fstyle);
if (fstyle->kerning == 1) /* for BLF_width */
BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
- /* if text editing we define ofs dynamically */
- if (but->editstr && but->pos >= 0) {
- if (but->ofs > but->pos)
- but->ofs = but->pos;
+ but->ofs = 0;
+ but->strwidth = BLF_width(fstyle->uifont_id, but->drawstr);
+
+ while (but->strwidth > okwidth) {
+ ui_text_clip_give_next_off(but);
+ but->strwidth = BLF_width(fstyle->uifont_id, but->drawstr + but->ofs);
+ if (but->strwidth < 10) break;
+ }
- if (BLF_width(fstyle->uifont_id, but->drawstr) <= okwidth)
- but->ofs = 0;
+ if (fstyle->kerning == 1) {
+ BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
}
- else but->ofs = 0;
-
+}
+
+/**
+ * Cut off the text, taking into account the cursor location (text display while editing).
+ */
+static void ui_text_clip_cursor(uiFontStyle *fstyle, uiBut *but, rcti *rect)
+{
+ int border = (but->flag & UI_BUT_ALIGN_RIGHT) ? 8 : 10;
+ int okwidth = BLI_rcti_size_x(rect) - border;
+ if (but->flag & UI_HAS_ICON) okwidth -= UI_DPI_ICON_SIZE;
+
+ BLI_assert(but->editstr && but->pos >= 0);
+
+ /* need to set this first */
+ uiStyleFontSet(fstyle);
+
+ if (fstyle->kerning == 1) /* for BLF_width */
+ BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
+
+ /* define ofs dynamically */
+ if (but->ofs > but->pos)
+ but->ofs = but->pos;
+
+ if (BLF_width(fstyle->uifont_id, but->drawstr) <= okwidth)
+ but->ofs = 0;
+
but->strwidth = BLF_width(fstyle->uifont_id, but->drawstr + but->ofs);
-
+
while (but->strwidth > okwidth) {
-
- /* textbut exception, clip right when... */
- if (but->editstr && but->pos >= 0) {
- float width;
- char buf[UI_MAX_DRAW_STR];
-
- /* copy draw string */
- BLI_strncpy_utf8(buf, but->drawstr, sizeof(buf));
- /* string position of cursor */
- buf[but->pos] = 0;
- width = BLF_width(fstyle->uifont_id, buf + but->ofs);
-
- /* if cursor is at 20 pixels of right side button we clip left */
- if (width > okwidth - 20)
- ui_text_clip_give_next_off(but);
- else {
- int len, bytes;
- /* shift string to the left */
- if (width < 20 && but->ofs > 0)
- ui_text_clip_give_prev_off(but);
- len = strlen(but->drawstr);
- bytes = BLI_str_utf8_size(BLI_str_find_prev_char_utf8(but->drawstr, but->drawstr + len));
- but->drawstr[len - bytes] = 0;
- }
- }
- else
+ float width;
+ char buf[UI_MAX_DRAW_STR];
+
+ /* copy draw string */
+ BLI_strncpy_utf8(buf, but->drawstr, sizeof(buf));
+ /* string position of cursor */
+ buf[but->pos] = 0;
+ width = BLF_width(fstyle->uifont_id, buf + but->ofs);
+
+ /* if cursor is at 20 pixels of right side button we clip left */
+ if (width > okwidth - 20) {
ui_text_clip_give_next_off(but);
+ }
+ else {
+ int len, bytes;
+ /* shift string to the left */
+ if (width < 20 && but->ofs > 0)
+ ui_text_clip_give_prev_off(but);
+ len = strlen(but->drawstr);
+ bytes = BLI_str_utf8_size(BLI_str_find_prev_char_utf8(but->drawstr, but->drawstr + len));
+ but->drawstr[len - bytes] = 0;
+ }
but->strwidth = BLF_width(fstyle->uifont_id, but->drawstr + but->ofs);
-
+
if (but->strwidth < 10) break;
}
-
- if (fstyle->kerning == 1)
+
+ if (fstyle->kerning == 1) {
BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
+ }
}
-static void ui_text_label_rightclip(uiFontStyle *fstyle, uiBut *but, rcti *rect)
+/**
+ * Cut off the end of text to fit into the width of \a rect.
+ *
+ * \note deals with ': ' especially for number buttons
+ */
+static void ui_text_clip_right_label(uiFontStyle *fstyle, uiBut *but, rcti *rect)
{
int border = (but->flag & UI_BUT_ALIGN_RIGHT) ? 8 : 10;
- int okwidth = BLI_RCT_SIZE_X(rect) - border;
+ int okwidth = BLI_rcti_size_x(rect) - border;
char *cpoin = NULL;
- char *cpend = but->drawstr + strlen(but->drawstr);
+ int drawstr_len = strlen(but->drawstr);
+ char *cpend = but->drawstr + drawstr_len;
/* need to set this first */
uiStyleFontSet(fstyle);
@@ -1045,6 +1079,13 @@ static void ui_text_label_rightclip(uiFontStyle *fstyle, uiBut *but, rcti *rect)
but->strwidth = BLF_width(fstyle->uifont_id, but->drawstr);
but->ofs = 0;
+
+ /* First shorten num-buttopns eg,
+ * Translucency: 0.000
+ * becomes
+ * Trans: 0.000
+ */
+
/* find the space after ':' separator */
cpoin = strrchr(but->drawstr, ':');
@@ -1057,8 +1098,11 @@ static void ui_text_label_rightclip(uiFontStyle *fstyle, uiBut *but, rcti *rect)
int bytes = cp2 - prev_utf8;
/* shift the text after and including cp2 back by 1 char, +1 to include null terminator */
- memmove(cp2 - bytes, cp2, strlen(cp2) + 1);
+ memmove(cp2 - bytes, cp2, drawstr_len + 1);
cp2 -= bytes;
+
+ drawstr_len -= bytes;
+ // BLI_assert(strlen(but->drawstr) == drawstr_len);
but->strwidth = BLF_width(fstyle->uifont_id, but->drawstr + but->ofs);
if (but->strwidth < 10) break;
@@ -1074,14 +1118,17 @@ static void ui_text_label_rightclip(uiFontStyle *fstyle, uiBut *but, rcti *rect)
}
+
+ /* Now just remove trailing chars */
/* once the label's gone, chop off the least significant digits */
while (but->strwidth > okwidth) {
- int len = strlen(but->drawstr);
- int bytes = BLI_str_utf8_size(BLI_str_find_prev_char_utf8(but->drawstr, but->drawstr + len));
+ int bytes = BLI_str_utf8_size(BLI_str_find_prev_char_utf8(but->drawstr, but->drawstr + drawstr_len));
if (bytes < 0)
bytes = 1;
- but->drawstr[len - bytes] = 0;
+ drawstr_len -= bytes;
+ but->drawstr[drawstr_len] = 0;
+ // BLI_assert(strlen(but->drawstr) == drawstr_len);
but->strwidth = BLF_width(fstyle->uifont_id, but->drawstr + but->ofs);
if (but->strwidth < 10) break;
@@ -1229,30 +1276,34 @@ static void widget_draw_text(uiFontStyle *fstyle, uiWidgetColors *wcol, uiBut *b
/* draws text and icons for buttons */
static void widget_draw_text_icon(uiFontStyle *fstyle, uiWidgetColors *wcol, uiBut *but, rcti *rect)
{
-
- if (but == NULL) return;
+ char password_str[UI_MAX_DRAW_STR];
+
+ if (but == NULL)
+ return;
+
+ ui_button_text_password_hide(password_str, but, FALSE);
/* clip but->drawstr to fit in available space */
if (but->editstr && but->pos >= 0) {
- ui_text_leftclip(fstyle, but, rect);
+ ui_text_clip_cursor(fstyle, but, rect);
}
else if (ELEM4(but->type, NUM, NUMABS, NUMSLI, SLI)) {
- ui_text_label_rightclip(fstyle, but, rect);
+ ui_text_clip_right_label(fstyle, but, rect);
}
else if (ELEM(but->type, TEX, SEARCH_MENU)) {
- ui_text_leftclip(fstyle, but, rect);
+ ui_text_clip_left(fstyle, but, rect);
}
else if ((but->block->flag & UI_BLOCK_LOOP) && (but->type == BUT)) {
- ui_text_leftclip(fstyle, but, rect);
+ ui_text_clip_left(fstyle, but, rect);
}
else but->ofs = 0;
-
+
/* check for button text label */
if (but->type == ICONTEXTROW) {
widget_draw_icon(but, (BIFIconID) (but->icon + but->iconadd), 1.0f, rect);
}
else {
-
+
if (but->type == BUT_TOGDUAL) {
int dualset = 0;
if (but->pointype == UI_BUT_POIN_SHORT) {
@@ -1261,34 +1312,36 @@ static void widget_draw_text_icon(uiFontStyle *fstyle, uiWidgetColors *wcol, uiB
else if (but->pointype == UI_BUT_POIN_INT) {
dualset = UI_BITBUT_TEST(*(((int *)but->poin) + 1), but->bitnr);
}
-
+
widget_draw_icon(but, ICON_DOT, dualset ? 1.0f : 0.25f, rect);
}
else if (but->type == MENU && (but->flag & UI_BUT_NODE_LINK)) {
int tmp = rect->xmin;
- rect->xmin = rect->xmax - BLI_RCT_SIZE_Y(rect) - 1;
+ rect->xmin = rect->xmax - BLI_rcti_size_y(rect) - 1;
widget_draw_icon(but, ICON_LAYER_USED, 1.0f, rect);
rect->xmin = tmp;
}
-
+
/* If there's an icon too (made with uiDefIconTextBut) then draw the icon
* and offset the text label to accommodate it */
-
+
if (but->flag & UI_HAS_ICON) {
widget_draw_icon(but, but->icon + but->iconadd, 1.0f, rect);
-
+
rect->xmin += (int)((float)UI_icon_get_width(but->icon + but->iconadd) * UI_DPI_ICON_FAC);
-
- if (but->editstr || (but->flag & UI_TEXT_LEFT))
+
+ if (but->editstr || (but->flag & UI_TEXT_LEFT))
rect->xmin += 5;
}
- else if ((but->flag & UI_TEXT_LEFT))
+ else if ((but->flag & UI_TEXT_LEFT))
rect->xmin += 5;
-
+
/* always draw text for textbutton cursor */
widget_draw_text(fstyle, wcol, but, rect);
}
+
+ ui_button_text_password_hide(password_str, but, TRUE);
}
@@ -1761,8 +1814,8 @@ static void widget_softshadow(rcti *rect, int roundboxalign, float radin, float
float quad_strip[WIDGET_SIZE_MAX * 2][2];
/* prevent tooltips to not show round shadow */
- if (2.0f * radout > 0.2f * BLI_RCT_SIZE_Y(&rect1))
- rect1.ymax -= 0.2f * BLI_RCT_SIZE_Y(&rect1);
+ if (2.0f * radout > 0.2f * BLI_rcti_size_y(&rect1))
+ rect1.ymax -= 0.2f * BLI_rcti_size_y(&rect1);
else
rect1.ymax -= 2.0f * radout;
@@ -1804,7 +1857,7 @@ static void widget_menu_back(uiWidgetColors *wcol, rcti *rect, int flag, int dir
else if (direction == UI_DOWN) {
roundboxalign = (UI_CNR_BOTTOM_RIGHT | UI_CNR_BOTTOM_LEFT);
rect->ymin -= 4.0;
- }
+ }
else if (direction == UI_TOP) {
roundboxalign = UI_CNR_TOP_LEFT | UI_CNR_TOP_RIGHT;
rect->ymax += 4.0;
@@ -1841,53 +1894,47 @@ static void ui_hsv_cursor(float x, float y)
}
-void ui_hsvcircle_vals_from_pos(float *valrad, float *valdist, rcti *rect, float mx, float my)
+void ui_hsvcircle_vals_from_pos(float *val_rad, float *val_dist, const rcti *rect,
+ const float mx, const float my)
{
/* duplication of code... well, simple is better now */
- float centx = BLI_RCT_CENTER_X_FL(rect);
- float centy = BLI_RCT_CENTER_Y_FL(rect);
- float radius, dist;
-
- if (BLI_RCT_SIZE_X(rect) > BLI_RCT_SIZE_Y(rect))
- radius = (float)BLI_RCT_SIZE_Y(rect) / 2;
- else
- radius = (float)BLI_RCT_SIZE_X(rect) / 2;
+ const float centx = BLI_rcti_cent_x_fl(rect);
+ const float centy = BLI_rcti_cent_y_fl(rect);
+ const float radius = (float)min_ii(BLI_rcti_size_x(rect), BLI_rcti_size_y(rect)) / 2.0f;
+ const float m_delta[2] = {mx - centx, my - centy};
+ const float dist_squared = len_squared_v2(m_delta);
- mx -= centx;
- my -= centy;
- dist = sqrt(mx * mx + my * my);
- if (dist < radius)
- *valdist = dist / radius;
- else
- *valdist = 1.0f;
-
- *valrad = atan2f(mx, my) / (2.0f * (float)M_PI) + 0.5f;
+ *val_dist = (dist_squared < (radius * radius)) ? sqrtf(dist_squared) / radius : 1.0f;
+ *val_rad = atan2f(m_delta[0], m_delta[1]) / (2.0f * (float)M_PI) + 0.5f;
}
-static void ui_draw_but_HSVCIRCLE(uiBut *but, uiWidgetColors *wcol, rcti *rect)
+static void ui_draw_but_HSVCIRCLE(uiBut *but, uiWidgetColors *wcol, const rcti *rect)
{
+ const int tot = 32;
+ const float radstep = 2.0f * (float)M_PI / (float)tot;
+
+ const float centx = BLI_rcti_cent_x_fl(rect);
+ const float centy = BLI_rcti_cent_y_fl(rect);
+ float radius = (float)min_ii(BLI_rcti_size_x(rect), BLI_rcti_size_y(rect)) / 2.0f;
+
/* gouraud triangle fan */
- float radstep, ang = 0.0f;
- float centx, centy, radius, cursor_radius;
+ const float *hsv_ptr = ui_block_hsv_get(but->block);
+ float ang = 0.0f;
+ float cursor_radius;
float rgb[3], hsvo[3], hsv[3], col[3], colcent[3];
- int a, tot = 32;
+ int a;
int color_profile = but->block->color_profile;
if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
color_profile = FALSE;
- radstep = 2.0f * (float)M_PI / (float)tot;
- centx = BLI_RCT_CENTER_X_FL(rect);
- centy = BLI_RCT_CENTER_Y_FL(rect);
-
- if (BLI_RCT_SIZE_X(rect) > BLI_RCT_SIZE_Y(rect))
- radius = (float)BLI_RCT_SIZE_Y(rect) / 2;
- else
- radius = (float)BLI_RCT_SIZE_X(rect) / 2;
-
/* color */
ui_get_but_vectorf(but, rgb);
- /* copy_v3_v3(hsv, ui_block_hsv_get(but->block)); */ /* UNUSED */
+
+ /* since we use compat functions on both 'hsv' and 'hsvo', they need to be initialized */
+ hsvo[0] = hsv[0] = hsv_ptr[0];
+ hsvo[1] = hsv[1] = hsv_ptr[1];
+ hsvo[2] = hsv[2] = hsv_ptr[2];
rgb_to_hsv_compat_v(rgb, hsvo);
@@ -1953,7 +2000,7 @@ static void ui_draw_but_HSVCIRCLE(uiBut *but, uiWidgetColors *wcol, rcti *rect)
/* draws in resolution of 20x4 colors */
void ui_draw_gradient(rcti *rect, const float hsv[3], const int type, const float alpha)
{
- const float color_step = (type == UI_GRAD_H) ? 0.02 : 0.05f;
+ const float color_step = (type == UI_GRAD_H) ? 0.02f : 0.05f;
int a;
float h = hsv[0], s = hsv[1], v = hsv[2];
float dx, dy, sx1, sx2, sy;
@@ -2062,10 +2109,10 @@ void ui_draw_gradient(rcti *rect, const float hsv[3], const int type, const floa
}
/* rect */
- sx1 = rect->xmin + dx * BLI_RCT_SIZE_X(rect);
- sx2 = rect->xmin + (dx + color_step) * BLI_RCT_SIZE_X(rect);
+ sx1 = rect->xmin + dx * BLI_rcti_size_x(rect);
+ sx2 = rect->xmin + (dx + color_step) * BLI_rcti_size_x(rect);
sy = rect->ymin;
- dy = BLI_RCT_SIZE_Y(rect) / 3.0;
+ dy = BLI_rcti_size_y(rect) / 3.0;
glBegin(GL_QUADS);
for (a = 0; a < 3; a++, sy += dy) {
@@ -2120,8 +2167,8 @@ static void ui_draw_but_HSVCUBE(uiBut *but, rcti *rect)
}
/* cursor */
- x = rect->xmin + x * BLI_RCT_SIZE_X(rect);
- y = rect->ymin + y * BLI_RCT_SIZE_Y(rect);
+ x = rect->xmin + x * BLI_rcti_size_x(rect);
+ y = rect->ymin + y * BLI_rcti_size_y(rect);
CLAMP(x, rect->xmin + 3.0f, rect->xmax - 3.0f);
CLAMP(y, rect->ymin + 3.0f, rect->ymax - 3.0f);
@@ -2136,7 +2183,7 @@ static void ui_draw_but_HSVCUBE(uiBut *but, rcti *rect)
static void ui_draw_but_HSV_v(uiBut *but, rcti *rect)
{
uiWidgetBase wtb;
- float rad = 0.5f * BLI_RCT_SIZE_X(rect);
+ float rad = 0.5f * BLI_rcti_size_x(rect);
float x, y;
float rgb[3], hsv[3], v, range;
int color_profile = but->block->color_profile;
@@ -2171,8 +2218,8 @@ static void ui_draw_but_HSV_v(uiBut *but, rcti *rect)
widgetbase_draw(&wtb, &wcol_tmp);
/* cursor */
- x = rect->xmin + 0.5f * BLI_RCT_SIZE_X(rect);
- y = rect->ymin + v * BLI_RCT_SIZE_Y(rect);
+ x = rect->xmin + 0.5f * BLI_rcti_size_x(rect);
+ y = rect->ymin + v * BLI_rcti_size_y(rect);
CLAMP(y, rect->ymin + 3.0f, rect->ymax - 3.0f);
ui_hsv_cursor(x, y);
@@ -2183,7 +2230,7 @@ static void ui_draw_but_HSV_v(uiBut *but, rcti *rect)
/* ************ separator, for menus etc ***************** */
static void ui_draw_separator(rcti *rect, uiWidgetColors *wcol)
{
- int y = rect->ymin + BLI_RCT_SIZE_Y(rect) / 2 - 1;
+ int y = rect->ymin + BLI_rcti_size_y(rect) / 2 - 1;
unsigned char col[4];
col[0] = wcol->text[0];
@@ -2202,7 +2249,7 @@ static void ui_draw_separator(rcti *rect, uiWidgetColors *wcol)
static void widget_numbut(uiWidgetColors *wcol, rcti *rect, int state, int roundboxalign)
{
uiWidgetBase wtb;
- float rad = 0.5f * BLI_RCT_SIZE_Y(rect);
+ float rad = 0.5f * BLI_rcti_size_y(rect);
float textofs = rad * 0.75f;
if (state & UI_SELECT)
@@ -2283,12 +2330,12 @@ void uiWidgetScrollDraw(uiWidgetColors *wcol, rcti *rect, rcti *slider, int stat
widget_init(&wtb);
/* determine horizontal/vertical */
- horizontal = (BLI_RCT_SIZE_X(rect) > BLI_RCT_SIZE_Y(rect));
+ horizontal = (BLI_rcti_size_x(rect) > BLI_rcti_size_y(rect));
if (horizontal)
- rad = 0.5f * BLI_RCT_SIZE_Y(rect);
+ rad = 0.5f * BLI_rcti_size_y(rect);
else
- rad = 0.5f * BLI_RCT_SIZE_X(rect);
+ rad = 0.5f * BLI_rcti_size_x(rect);
wtb.shadedir = (horizontal) ? 1 : 0;
@@ -2300,7 +2347,7 @@ void uiWidgetScrollDraw(uiWidgetColors *wcol, rcti *rect, rcti *slider, int stat
widgetbase_draw(&wtb, wcol);
/* slider */
- if ((BLI_RCT_SIZE_X(slider) < 2) || (BLI_RCT_SIZE_Y(slider) < 2)) {
+ if ((BLI_rcti_size_x(slider) < 2) || (BLI_rcti_size_y(slider) < 2)) {
/* pass */
}
else {
@@ -2322,7 +2369,7 @@ void uiWidgetScrollDraw(uiWidgetColors *wcol, rcti *rect, rcti *slider, int stat
wtb.emboss = 0; /* only emboss once */
/* exception for progress bar */
- if (state & UI_SCROLL_NO_OUTLINE)
+ if (state & UI_SCROLL_NO_OUTLINE)
SWAP(short, outline, wtb.outline);
round_box_edges(&wtb, UI_CNR_ALL, slider, rad);
@@ -2346,7 +2393,7 @@ void uiWidgetScrollDraw(uiWidgetColors *wcol, rcti *rect, rcti *slider, int stat
if (state & UI_SCROLL_NO_OUTLINE)
SWAP(short, outline, wtb.outline);
- }
+ }
}
static void widget_scroll(uiBut *but, uiWidgetColors *wcol, rcti *rect, int state, int UNUSED(roundboxalign))
@@ -2360,45 +2407,45 @@ static void widget_scroll(uiBut *but, uiWidgetColors *wcol, rcti *rect, int stat
value = ui_get_but_val(but);
size = (but->softmax + but->a1 - but->softmin);
- size = MAX2(size, 2);
+ size = max_ff(size, 2.0f);
/* position */
rect1 = *rect;
/* determine horizontal/vertical */
- horizontal = (BLI_RCT_SIZE_X(rect) > BLI_RCT_SIZE_Y(rect));
+ horizontal = (BLI_rcti_size_x(rect) > BLI_rcti_size_y(rect));
if (horizontal) {
- fac = BLI_RCT_SIZE_X(rect) / size;
+ fac = BLI_rcti_size_x(rect) / size;
rect1.xmin = rect1.xmin + ceilf(fac * ((float)value - but->softmin));
rect1.xmax = rect1.xmin + ceilf(fac * (but->a1 - but->softmin));
/* ensure minimium size */
- min = BLI_RCT_SIZE_Y(rect);
+ min = BLI_rcti_size_y(rect);
- if (BLI_RCT_SIZE_X(&rect1) < min) {
+ if (BLI_rcti_size_x(&rect1) < min) {
rect1.xmax = rect1.xmin + min;
if (rect1.xmax > rect->xmax) {
rect1.xmax = rect->xmax;
- rect1.xmin = maxi(rect1.xmax - min, rect->xmin);
+ rect1.xmin = max_ii(rect1.xmax - min, rect->xmin);
}
}
}
else {
- fac = BLI_RCT_SIZE_Y(rect) / size;
+ fac = BLI_rcti_size_y(rect) / size;
rect1.ymax = rect1.ymax - ceilf(fac * ((float)value - but->softmin));
rect1.ymin = rect1.ymax - ceilf(fac * (but->a1 - but->softmin));
/* ensure minimium size */
- min = BLI_RCT_SIZE_X(rect);
+ min = BLI_rcti_size_x(rect);
- if (BLI_RCT_SIZE_Y(&rect1) < min) {
+ if (BLI_rcti_size_y(&rect1) < min) {
rect1.ymax = rect1.ymin + min;
if (rect1.ymax > rect->ymax) {
rect1.ymax = rect->ymax;
- rect1.ymin = MAX2(rect1.ymax - min, rect->ymin);
+ rect1.ymin = max_ii(rect1.ymax - min, rect->ymin);
}
}
}
@@ -2421,10 +2468,10 @@ static void widget_progressbar(uiBut *but, uiWidgetColors *wcol, rcti *rect, int
rect_prog.ymax = rect_prog.ymin + 4;
rect_bar.ymax = rect_bar.ymin + 4;
- w = value * BLI_RCT_SIZE_X(&rect_prog);
+ w = value * BLI_rcti_size_x(&rect_prog);
/* ensure minimium size */
- min = BLI_RCT_SIZE_Y(&rect_prog);
+ min = BLI_rcti_size_y(&rect_prog);
w = MAX2(w, min);
rect_bar.xmax = rect_bar.xmin + w;
@@ -2444,8 +2491,8 @@ static void widget_link(uiBut *but, uiWidgetColors *UNUSED(wcol), rcti *rect, in
UI_ThemeColor(TH_TEXT_HI);
- rectlink.xmin = BLI_RCT_CENTER_X(rect);
- rectlink.ymin = BLI_RCT_CENTER_Y(rect);
+ rectlink.xmin = BLI_rcti_cent_x(rect);
+ rectlink.ymin = BLI_rcti_cent_y(rect);
rectlink.xmax = but->linkto[0];
rectlink.ymax = but->linkto[1];
@@ -2467,7 +2514,7 @@ static void widget_numslider(uiBut *but, uiWidgetColors *wcol, rcti *rect, int s
/* backdrop first */
/* fully rounded */
- offs = 0.5f * BLI_RCT_SIZE_Y(rect);
+ offs = 0.5f * BLI_rcti_size_y(rect);
toffs = offs * 0.75f;
round_box_edges(&wtb, roundboxalign, rect, offs);
@@ -2488,7 +2535,7 @@ static void widget_numslider(uiBut *but, uiWidgetColors *wcol, rcti *rect, int s
rect1 = *rect;
value = ui_get_but_val(but);
- fac = ((float)value - but->softmin) * (BLI_RCT_SIZE_X(&rect1) - offs) / (but->softmax - but->softmin);
+ fac = ((float)value - but->softmin) * (BLI_rcti_size_x(&rect1) - offs) / (but->softmax - but->softmin);
/* left part of slider, always rounded */
rect1.xmax = rect1.xmin + ceil(offs + 1.0f);
@@ -2585,7 +2632,7 @@ static void widget_icon_has_anim(uiBut *UNUSED(but), uiWidgetColors *wcol, rcti
/* rounded */
round_box_edges(&wtb, UI_CNR_ALL, rect, 10.0f);
widgetbase_draw(&wtb, wcol);
- }
+ }
}
@@ -2620,8 +2667,8 @@ static void widget_menubut(uiWidgetColors *wcol, rcti *rect, int UNUSED(state),
widgetbase_draw(&wtb, wcol);
- /* text space */
- rect->xmax -= BLI_RCT_SIZE_Y(rect);
+ /* text space, arrows are about 0.6 height of button */
+ rect->xmax -= (6 * BLI_rcti_size_y(rect)) / 10;
}
static void widget_menuiconbut(uiWidgetColors *wcol, rcti *rect, int UNUSED(state), int roundboxalign)
@@ -2660,16 +2707,16 @@ static void widget_menunodebut(uiWidgetColors *wcol, rcti *rect, int UNUSED(stat
*wcol = wcol_backup;
}
-static void widget_pulldownbut(uiWidgetColors *wcol, rcti *rect, int state, int UNUSED(roundboxalign))
+static void widget_pulldownbut(uiWidgetColors *wcol, rcti *rect, int state, int roundboxalign)
{
if (state & UI_ACTIVE) {
uiWidgetBase wtb;
- float rad = 0.5f * BLI_RCT_SIZE_Y(rect); /* 4.0f */
-
+ float rad = 0.25f * BLI_rcti_size_y(rect); /* 4.0f */
+
widget_init(&wtb);
-
+
/* half rounded */
- round_box_edges(&wtb, UI_CNR_ALL, rect, rad);
+ round_box_edges(&wtb, roundboxalign, rect, rad);
widgetbase_draw(&wtb, wcol);
}
@@ -2710,10 +2757,10 @@ static void widget_optionbut(uiWidgetColors *wcol, rcti *rect, int state, int UN
widget_init(&wtb);
/* square */
- recttemp.xmax = recttemp.xmin + BLI_RCT_SIZE_Y(&recttemp);
+ recttemp.xmax = recttemp.xmin + BLI_rcti_size_y(&recttemp);
/* smaller */
- delta = 1 + BLI_RCT_SIZE_Y(&recttemp) / 8;
+ delta = 1 + BLI_rcti_size_y(&recttemp) / 8;
recttemp.xmin += delta;
recttemp.ymin += delta;
recttemp.xmax -= delta;
@@ -2730,7 +2777,7 @@ static void widget_optionbut(uiWidgetColors *wcol, rcti *rect, int state, int UN
widgetbase_draw(&wtb, wcol);
/* text space */
- rect->xmin += BLI_RCT_SIZE_Y(rect) * 0.7 + delta;
+ rect->xmin += BLI_rcti_size_y(rect) * 0.7 + delta;
}
@@ -2792,7 +2839,7 @@ static void widget_but(uiWidgetColors *wcol, rcti *rect, int UNUSED(state), int
static void widget_roundbut(uiWidgetColors *wcol, rcti *rect, int UNUSED(state), int roundboxalign)
{
uiWidgetBase wtb;
- float rad = 5.0f; /* 0.5f * BLI_RCT_SIZE_Y(rect); */
+ float rad = 5.0f; /* 0.5f * BLI_rcti_size_y(rect); */
widget_init(&wtb);
@@ -3006,9 +3053,12 @@ static uiWidgetType *widget_type(uiWidgetTypeEnum type)
static int widget_roundbox_set(uiBut *but, rcti *rect)
{
+ int roundbox = UI_CNR_ALL;
+
/* alignment */
- if (but->flag & UI_BUT_ALIGN) {
+ if ((but->flag & UI_BUT_ALIGN) && but->type != PULLDOWN) {
+ /* ui_block_position has this correction too, keep in sync */
if (but->flag & UI_BUT_ALIGN_TOP)
rect->ymax += 1;
if (but->flag & UI_BUT_ALIGN_LEFT)
@@ -3016,27 +3066,46 @@ static int widget_roundbox_set(uiBut *but, rcti *rect)
switch (but->flag & UI_BUT_ALIGN) {
case UI_BUT_ALIGN_TOP:
- return UI_CNR_BOTTOM_LEFT | UI_CNR_BOTTOM_RIGHT;
+ roundbox = UI_CNR_BOTTOM_LEFT | UI_CNR_BOTTOM_RIGHT;
+ break;
case UI_BUT_ALIGN_DOWN:
- return UI_CNR_TOP_LEFT | UI_CNR_TOP_RIGHT;
+ roundbox = UI_CNR_TOP_LEFT | UI_CNR_TOP_RIGHT;
+ break;
case UI_BUT_ALIGN_LEFT:
- return UI_CNR_TOP_RIGHT | UI_CNR_BOTTOM_RIGHT;
+ roundbox = UI_CNR_TOP_RIGHT | UI_CNR_BOTTOM_RIGHT;
+ break;
case UI_BUT_ALIGN_RIGHT:
- return UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT;
+ roundbox = UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT;
+ break;
case UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_RIGHT:
- return UI_CNR_TOP_LEFT;
+ roundbox = UI_CNR_TOP_LEFT;
+ break;
case UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_LEFT:
- return UI_CNR_TOP_RIGHT;
+ roundbox = UI_CNR_TOP_RIGHT;
+ break;
case UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_RIGHT:
- return UI_CNR_BOTTOM_LEFT;
+ roundbox = UI_CNR_BOTTOM_LEFT;
+ break;
case UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_LEFT:
- return UI_CNR_BOTTOM_RIGHT;
+ roundbox = UI_CNR_BOTTOM_RIGHT;
+ break;
default:
- return 0;
+ roundbox = 0;
+ break;
}
}
- return UI_CNR_ALL;
+ /* align with open menu */
+ if (but->active) {
+ int direction = ui_button_open_menu_direction(but);
+
+ if (direction == UI_TOP) roundbox &= ~(UI_CNR_TOP_RIGHT | UI_CNR_TOP_LEFT);
+ else if (direction == UI_DOWN) roundbox &= ~(UI_CNR_BOTTOM_RIGHT | UI_CNR_BOTTOM_LEFT);
+ else if (direction == UI_LEFT) roundbox &= ~(UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT);
+ else if (direction == UI_RIGHT) roundbox &= ~(UI_CNR_TOP_RIGHT | UI_CNR_BOTTOM_RIGHT);
+ }
+
+ return roundbox;
}
/* conversion from old to new buttons, so still messy */
@@ -3275,14 +3344,14 @@ void ui_draw_menu_back(uiStyle *UNUSED(style), uiBlock *block, rcti *rect)
if (block->flag & UI_BLOCK_CLIPTOP) {
/* XXX no scaling for UI here yet */
glColor3ubv((unsigned char *)wt->wcol.text);
- UI_DrawTriIcon(BLI_RCT_CENTER_X(rect), rect->ymax - 8, 't');
+ UI_DrawTriIcon(BLI_rcti_cent_x(rect), rect->ymax - 8, 't');
}
if (block->flag & UI_BLOCK_CLIPBOTTOM) {
/* XXX no scaling for UI here yet */
glColor3ubv((unsigned char *)wt->wcol.text);
- UI_DrawTriIcon(BLI_RCT_CENTER_X(rect), rect->ymin + 10, 'v');
+ UI_DrawTriIcon(BLI_rcti_cent_x(rect), rect->ymin + 10, 'v');
}
- }
+ }
}
uiWidgetColors *ui_tooltip_get_theme(void)
diff --git a/source/blender/editors/interface/resources.c b/source/blender/editors/interface/resources.c
index b379a2e7b4c..e03a2887866 100644
--- a/source/blender/editors/interface/resources.c
+++ b/source/blender/editors/interface/resources.c
@@ -651,7 +651,7 @@ void ui_theme_init_default(void)
strcpy(btheme->name, "Default");
}
- UI_SetTheme(0, 0); // make sure the global used in this file is set
+ UI_SetTheme(0, 0); /* make sure the global used in this file is set */
/* UI buttons */
ui_widget_color_init(&btheme->tui);
@@ -808,9 +808,9 @@ void ui_theme_init_default(void)
rgba_char_args_set_fl(btheme->tfile.list, 0.4, 0.4, 0.4, 1);
rgba_char_args_set(btheme->tfile.text, 250, 250, 250, 255);
rgba_char_args_set(btheme->tfile.text_hi, 15, 15, 15, 255);
- rgba_char_args_set(btheme->tfile.panel, 145, 145, 145, 255); // bookmark/ui regions
- rgba_char_args_set(btheme->tfile.active, 130, 130, 130, 255); // selected files
- rgba_char_args_set(btheme->tfile.hilite, 255, 140, 25, 255); // selected files
+ rgba_char_args_set(btheme->tfile.panel, 145, 145, 145, 255); /* bookmark/ui regions */
+ rgba_char_args_set(btheme->tfile.active, 130, 130, 130, 255); /* selected files */
+ rgba_char_args_set(btheme->tfile.hilite, 255, 140, 25, 255); /* selected files */
rgba_char_args_set(btheme->tfile.grid, 250, 250, 250, 255);
rgba_char_args_set(btheme->tfile.image, 250, 250, 250, 255);
@@ -891,7 +891,7 @@ void ui_theme_init_default(void)
btheme->ttime = btheme->tv3d;
rgba_char_args_set_fl(btheme->ttime.back, 0.45, 0.45, 0.45, 1.0);
rgba_char_args_set_fl(btheme->ttime.grid, 0.36, 0.36, 0.36, 1.0);
- rgba_char_args_set(btheme->ttime.shade1, 173, 173, 173, 255); // sliders
+ rgba_char_args_set(btheme->ttime.shade1, 173, 173, 173, 255); /* sliders */
/* space node, re-uses syntax color storage */
btheme->tnode = btheme->tv3d;
@@ -901,6 +901,7 @@ void ui_theme_init_default(void)
rgba_char_args_set(btheme->tnode.syntaxb, 108, 105, 111, 255); /* operator */
rgba_char_args_set(btheme->tnode.syntaxv, 104, 106, 117, 255); /* generator */
rgba_char_args_set(btheme->tnode.syntaxc, 105, 117, 110, 255); /* group */
+ rgba_char_args_set(btheme->tnode.movie, 155, 155, 155, 160); /* frame */
btheme->tnode.noodle_curving = 5;
/* space logic */
@@ -931,7 +932,7 @@ void ui_theme_init_default(void)
void UI_SetTheme(int spacetype, int regionid)
{
- if (spacetype == 0) { // called for safety, when delete themes
+ if (spacetype == 0) { /* called for safety, when delete themes */
theme_active = U.themes.first;
theme_spacetype = SPACE_VIEW3D;
theme_regionid = RGN_TYPE_WINDOW;
@@ -949,7 +950,7 @@ bTheme *UI_GetTheme(void)
return U.themes.first;
}
-// for space windows only
+/* for space windows only */
void UI_ThemeColor(int colorid)
{
const unsigned char *cp;
@@ -959,7 +960,7 @@ void UI_ThemeColor(int colorid)
}
-// plus alpha
+/* plus alpha */
void UI_ThemeColor4(int colorid)
{
const unsigned char *cp;
@@ -969,7 +970,7 @@ void UI_ThemeColor4(int colorid)
}
-// set the color with offset for shades
+/* set the color with offset for shades */
void UI_ThemeColorShade(int colorid, int offset)
{
int r, g, b;
@@ -1002,7 +1003,7 @@ void UI_ThemeColorShadeAlpha(int colorid, int coloffset, int alphaoffset)
glColor4ub(r, g, b, a);
}
-// blend between to theme colors, and set it
+/* blend between to theme colors, and set it */
void UI_ThemeColorBlend(int colorid1, int colorid2, float fac)
{
int r, g, b;
@@ -1019,7 +1020,7 @@ void UI_ThemeColorBlend(int colorid1, int colorid2, float fac)
glColor3ub(r, g, b);
}
-// blend between to theme colors, shade it, and set it
+/* blend between to theme colors, shade it, and set it */
void UI_ThemeColorBlendShade(int colorid1, int colorid2, float fac, int offset)
{
int r, g, b;
@@ -1040,7 +1041,7 @@ void UI_ThemeColorBlendShade(int colorid1, int colorid2, float fac, int offset)
glColor3ub(r, g, b);
}
-// blend between to theme colors, shade it, and set it
+/* blend between to theme colors, shade it, and set it */
void UI_ThemeColorBlendShadeAlpha(int colorid1, int colorid2, float fac, int offset, int alphaoffset)
{
int r, g, b, a;
@@ -1064,7 +1065,7 @@ void UI_ThemeColorBlendShadeAlpha(int colorid1, int colorid2, float fac, int off
}
-// get individual values, not scaled
+/* get individual values, not scaled */
float UI_GetThemeValuef(int colorid)
{
const unsigned char *cp;
@@ -1074,7 +1075,7 @@ float UI_GetThemeValuef(int colorid)
}
-// get individual values, not scaled
+/* get individual values, not scaled */
int UI_GetThemeValue(int colorid)
{
const unsigned char *cp;
@@ -1085,7 +1086,7 @@ int UI_GetThemeValue(int colorid)
}
-// get the color, range 0.0-1.0
+/* get the color, range 0.0-1.0 */
void UI_GetThemeColor3fv(int colorid, float col[3])
{
const unsigned char *cp;
@@ -1107,7 +1108,7 @@ void UI_GetThemeColor4fv(int colorid, float col[4])
col[3] = ((float)cp[3]) / 255.0f;
}
-// get the color, range 0.0-1.0, complete with shading offset
+/* get the color, range 0.0-1.0, complete with shading offset */
void UI_GetThemeColorShade3fv(int colorid, int offset, float col[3])
{
int r, g, b;
@@ -1146,7 +1147,7 @@ void UI_GetThemeColorShade3ubv(int colorid, int offset, unsigned char col[3])
col[2] = b;
}
-// get the color, in char pointer
+/* get the color, in char pointer */
void UI_GetThemeColor3ubv(int colorid, unsigned char col[3])
{
const unsigned char *cp;
@@ -1157,7 +1158,7 @@ void UI_GetThemeColor3ubv(int colorid, unsigned char col[3])
col[2] = cp[2];
}
-// get the color, in char pointer
+/* get the color, in char pointer */
void UI_GetThemeColor4ubv(int colorid, unsigned char col[4])
{
const unsigned char *cp;
@@ -1180,7 +1181,7 @@ void UI_GetThemeColorType4ubv(int colorid, int spacetype, char col[4])
col[3] = cp[3];
}
-// blends and shades between two char color pointers
+/* blends and shades between two char color pointers */
void UI_ColorPtrBlendShade3ubv(const unsigned char cp1[3], const unsigned char cp2[3], float fac, int offset)
{
int r, g, b;
@@ -1213,7 +1214,7 @@ void UI_GetColorPtrShade3ubv(const unsigned char cp[3], unsigned char col[3], in
col[2] = b;
}
-// get a 3 byte color, blended and shaded between two other char color pointers
+/* get a 3 byte color, blended and shaded between two other char color pointers */
void UI_GetColorPtrBlendShade3ubv(const unsigned char cp1[3], const unsigned char cp2[3], unsigned char col[3],
float fac, int offset)
{
@@ -1359,7 +1360,7 @@ void init_userdef_do_versions(void)
btheme->ttime = btheme->tv3d;
rgba_char_args_set_fl(btheme->ttime.back, 0.45, 0.45, 0.45, 1.0);
rgba_char_args_set_fl(btheme->ttime.grid, 0.36, 0.36, 0.36, 1.0);
- rgba_char_args_set(btheme->ttime.shade1, 173, 173, 173, 255); // sliders
+ rgba_char_args_set(btheme->ttime.shade1, 173, 173, 173, 255); /* sliders */
}
if (btheme->text.syntaxn[3] == 0) {
rgba_char_args_set(btheme->text.syntaxn, 0, 0, 200, 255); /* Numbers Blue*/
@@ -1934,6 +1935,18 @@ void init_userdef_do_versions(void)
}
}
+ if (bmain->versionfile < 263 || (bmain->versionfile == 263 && bmain->subversionfile < 22)) {
+ bTheme *btheme;
+
+ for (btheme = U.themes.first; btheme; btheme = btheme->next) {
+ if (btheme->tipo.lastsel_point[3] == 0)
+ rgba_char_args_set(btheme->tipo.lastsel_point, 0xff, 0xff, 0xff, 255);
+
+ if (btheme->tv3d.skin_root[3] == 0)
+ rgba_char_args_set(btheme->tv3d.skin_root, 180, 77, 77, 255);
+ }
+ }
+
/* GL Texture Garbage Collection (variable abused above!) */
if (U.textimeout == 0) {
U.texcollectrate = 60;
@@ -1969,7 +1982,10 @@ void init_userdef_do_versions(void)
}
if (U.ndof_orbit_sensitivity == 0.0f) {
- U.ndof_orbit_sensitivity = 1.0f;
+ U.ndof_orbit_sensitivity = U.ndof_sensitivity;
+
+ if (!(U.flag & USER_TRACKBALL))
+ U.ndof_flag |= NDOF_TURNTABLE;
}
if (U.tweak_threshold == 0)
U.tweak_threshold = 10;
diff --git a/source/blender/editors/interface/view2d.c b/source/blender/editors/interface/view2d.c
index 9c71746d045..f1a3f59bc22 100644
--- a/source/blender/editors/interface/view2d.c
+++ b/source/blender/editors/interface/view2d.c
@@ -96,11 +96,11 @@ static void view2d_masks(View2D *v2d)
/* check size if: */
if (v2d->scroll & V2D_SCROLL_HORIZONTAL)
if (!(v2d->scroll & V2D_SCROLL_SCALE_HORIZONTAL))
- if (BLI_RCT_SIZE_X(&v2d->tot) <= BLI_RCT_SIZE_X(&v2d->cur))
+ if (BLI_rctf_size_x(&v2d->tot) <= BLI_rcti_size_x(&v2d->cur))
v2d->scroll |= V2D_SCROLL_HORIZONTAL_HIDE;
if (v2d->scroll & V2D_SCROLL_VERTICAL)
if (!(v2d->scroll & V2D_SCROLL_SCALE_VERTICAL))
- if (BLI_RCT_SIZE_Y(&v2d->tot) <= BLI_RCT_SIZE_Y(&v2d->cur))
+ if (BLI_rctf_size_y(&v2d->tot) <= BLI_rctf_size_y(&v2d->cur))
v2d->scroll |= V2D_SCROLL_VERTICAL_HIDE;
#endif
scroll = view2d_scroll_mapped(v2d->scroll);
@@ -299,7 +299,7 @@ void UI_view2d_region_reinit(View2D *v2d, short type, int winx, int winy)
/* other view types are completely defined using their own settings already */
default:
/* we don't do anything here, as settings should be fine, but just make sure that rect */
- break;
+ break;
}
}
@@ -328,8 +328,8 @@ void UI_view2d_curRect_validate_resize(View2D *v2d, int resize)
rctf *cur, *tot;
/* use mask as size of region that View2D resides in, as it takes into account scrollbars already */
- winx = (float)(BLI_RCT_SIZE_X(&v2d->mask) + 1);
- winy = (float)(BLI_RCT_SIZE_Y(&v2d->mask) + 1);
+ winx = (float)(BLI_rcti_size_x(&v2d->mask) + 1);
+ winy = (float)(BLI_rcti_size_y(&v2d->mask) + 1);
/* get pointers to rcts for less typing */
cur = &v2d->cur;
@@ -347,10 +347,10 @@ void UI_view2d_curRect_validate_resize(View2D *v2d, int resize)
* - firstly, we calculate the sizes of the rects
* - curwidth and curheight are saved as reference... modify width and height values here
*/
- totwidth = BLI_RCT_SIZE_X(tot);
- totheight = BLI_RCT_SIZE_Y(tot);
- curwidth = width = BLI_RCT_SIZE_X(cur);
- curheight = height = BLI_RCT_SIZE_Y(cur);
+ totwidth = BLI_rctf_size_x(tot);
+ totheight = BLI_rctf_size_y(tot);
+ curwidth = width = BLI_rctf_size_x(cur);
+ curheight = height = BLI_rctf_size_y(cur);
/* if zoom is locked, size on the appropriate axis is reset to mask size */
if (v2d->keepzoom & V2D_LOCKZOOM_X)
@@ -476,8 +476,14 @@ void UI_view2d_curRect_validate_resize(View2D *v2d, int resize)
if (winy < v2d->oldwiny) {
float temp = v2d->oldwiny - winy;
- cur->ymin += temp;
- cur->ymax += temp;
+ if (v2d->align & V2D_ALIGN_NO_NEG_Y) {
+ cur->ymin -= temp;
+ cur->ymax -= temp;
+ }
+ else { /* Assume V2D_ALIGN_NO_POS_Y or combination */
+ cur->ymin += temp;
+ cur->ymax += temp;
+ }
}
}
@@ -499,16 +505,16 @@ void UI_view2d_curRect_validate_resize(View2D *v2d, int resize)
/* resize from centerpoint, unless otherwise specified */
if (width != curwidth) {
if (v2d->keepofs & V2D_LOCKOFS_X) {
- cur->xmax += width - BLI_RCT_SIZE_X(cur);
+ cur->xmax += width - BLI_rctf_size_x(cur);
}
else if (v2d->keepofs & V2D_KEEPOFS_X) {
if (v2d->align & V2D_ALIGN_NO_POS_X)
- cur->xmin -= width - BLI_RCT_SIZE_X(cur);
+ cur->xmin -= width - BLI_rctf_size_x(cur);
else
- cur->xmax += width - BLI_RCT_SIZE_X(cur);
+ cur->xmax += width - BLI_rctf_size_x(cur);
}
else {
- temp = BLI_RCT_CENTER_X(cur);
+ temp = BLI_rctf_cent_x(cur);
dh = width * 0.5f;
cur->xmin = temp - dh;
@@ -517,16 +523,16 @@ void UI_view2d_curRect_validate_resize(View2D *v2d, int resize)
}
if (height != curheight) {
if (v2d->keepofs & V2D_LOCKOFS_Y) {
- cur->ymax += height - BLI_RCT_SIZE_Y(cur);
+ cur->ymax += height - BLI_rctf_size_y(cur);
}
else if (v2d->keepofs & V2D_KEEPOFS_Y) {
if (v2d->align & V2D_ALIGN_NO_POS_Y)
- cur->ymin -= height - BLI_RCT_SIZE_Y(cur);
+ cur->ymin -= height - BLI_rctf_size_y(cur);
else
- cur->ymax += height - BLI_RCT_SIZE_Y(cur);
+ cur->ymax += height - BLI_rctf_size_y(cur);
}
else {
- temp = BLI_RCT_CENTER_Y(cur);
+ temp = BLI_rctf_cent_y(cur);
dh = height * 0.5f;
cur->ymin = temp - dh;
@@ -540,8 +546,8 @@ void UI_view2d_curRect_validate_resize(View2D *v2d, int resize)
float temp, diff;
/* recalculate extents of cur */
- curwidth = BLI_RCT_SIZE_X(cur);
- curheight = BLI_RCT_SIZE_Y(cur);
+ curwidth = BLI_rctf_size_x(cur);
+ curheight = BLI_rctf_size_y(cur);
/* width */
if ((curwidth > totwidth) && !(v2d->keepzoom & (V2D_KEEPZOOM | V2D_LOCKZOOM_X | V2D_LIMITZOOM))) {
@@ -592,8 +598,8 @@ void UI_view2d_curRect_validate_resize(View2D *v2d, int resize)
*/
if ((cur->xmin < tot->xmin) && (cur->xmax > tot->xmax)) {
/* outside boundaries on both sides, so take middle-point of tot, and place in balanced way */
- temp = BLI_RCT_CENTER_X(tot);
- diff = curheight * 0.5f;
+ temp = BLI_rctf_cent_x(tot);
+ diff = curwidth * 0.5f;
cur->xmin = temp - diff;
cur->xmax = temp + diff;
@@ -642,7 +648,7 @@ void UI_view2d_curRect_validate_resize(View2D *v2d, int resize)
*/
if ((cur->ymin < tot->ymin) && (cur->ymax > tot->ymax)) {
/* outside boundaries on both sides, so take middle-point of tot, and place in balanced way */
- temp = BLI_RCT_CENTER_Y(tot);
+ temp = BLI_rctf_cent_y(tot);
diff = curheight * 0.5f;
cur->ymin = temp - diff;
@@ -791,8 +797,8 @@ void UI_view2d_curRect_reset(View2D *v2d)
float width, height;
/* assume width and height of 'cur' rect by default, should be same size as mask */
- width = (float)(BLI_RCT_SIZE_X(&v2d->mask) + 1);
- height = (float)(BLI_RCT_SIZE_Y(&v2d->mask) + 1);
+ width = (float)(BLI_rcti_size_x(&v2d->mask) + 1);
+ height = (float)(BLI_rcti_size_y(&v2d->mask) + 1);
/* handle width - posx and negx flags are mutually exclusive, so watch out */
if ((v2d->align & V2D_ALIGN_NO_POS_X) && !(v2d->align & V2D_ALIGN_NO_NEG_X)) {
@@ -958,8 +964,8 @@ static void view2d_map_cur_using_mask(View2D *v2d, rctf *curmasked)
*curmasked = v2d->cur;
if (view2d_scroll_mapped(v2d->scroll)) {
- float dx = BLI_RCT_SIZE_X(&v2d->cur) / ((float)(BLI_RCT_SIZE_X(&v2d->mask) + 1));
- float dy = BLI_RCT_SIZE_Y(&v2d->cur) / ((float)(BLI_RCT_SIZE_Y(&v2d->mask) + 1));
+ float dx = BLI_rctf_size_x(&v2d->cur) / ((float)(BLI_rcti_size_x(&v2d->mask) + 1));
+ float dy = BLI_rctf_size_y(&v2d->cur) / ((float)(BLI_rcti_size_y(&v2d->mask) + 1));
if (v2d->mask.xmin != 0)
curmasked->xmin -= dx * (float)v2d->mask.xmin;
@@ -985,14 +991,13 @@ void UI_view2d_view_ortho(View2D *v2d)
*/
/* XXX brecht: instead of zero at least use a tiny offset, otherwise
* pixel rounding is effectively random due to float inaccuracy */
- xofs = 0.001f * BLI_RCT_SIZE_X(&v2d->cur) / BLI_RCT_SIZE_X(&v2d->mask);
- yofs = 0.001f * BLI_RCT_SIZE_Y(&v2d->cur) / BLI_RCT_SIZE_Y(&v2d->mask);
+ xofs = 0.001f * BLI_rctf_size_x(&v2d->cur) / BLI_rcti_size_x(&v2d->mask);
+ yofs = 0.001f * BLI_rctf_size_y(&v2d->cur) / BLI_rcti_size_y(&v2d->mask);
/* apply mask-based adjustments to cur rect (due to scrollers), to eliminate scaling artifacts */
view2d_map_cur_using_mask(v2d, &curmasked);
-
- curmasked.xmin -= xofs; curmasked.xmax -= xofs;
- curmasked.ymin -= yofs; curmasked.ymax -= yofs;
+
+ BLI_rctf_translate(&curmasked, -xofs, -yofs);
/* XXX ton: this flag set by outliner, for icons */
if (v2d->flag & V2D_PIXELOFS_X) {
@@ -1044,8 +1049,8 @@ void UI_view2d_view_orthoSpecial(ARegion *ar, View2D *v2d, short xaxis)
void UI_view2d_view_restore(const bContext *C)
{
ARegion *ar = CTX_wm_region(C);
- int width = BLI_RCT_SIZE_X(&ar->winrct) + 1;
- int height = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
+ int width = BLI_rcti_size_x(&ar->winrct) + 1;
+ int height = BLI_rcti_size_y(&ar->winrct) + 1;
wmOrtho2(0.0f, (float)width, 0.0f, (float)height);
glLoadIdentity();
@@ -1090,7 +1095,7 @@ static void step_to_grid(float *step, int *power, int unit)
}
/* prevents printing 1.0 2.0 3.0 etc */
- if (rem == 1.0f) (*power)++;
+ if (rem == 1.0f) (*power)++;
}
else {
if (rem < 2.0f) rem = 2.0f;
@@ -1101,7 +1106,7 @@ static void step_to_grid(float *step, int *power, int unit)
(*power)++;
/* prevents printing 1.0, 2.0, 3.0, etc. */
- if (rem == 10.0f) (*power)++;
+ if (rem == 10.0f) (*power)++;
}
}
@@ -1117,7 +1122,8 @@ static void step_to_grid(float *step, int *power, int unit)
* - winx = width of region we're drawing to, note: not used but keeping for completeness.
* - winy = height of region we're drawing into
*/
-View2DGrid *UI_view2d_grid_calc(Scene *scene, View2D *v2d, short xunits, short xclamp, short yunits, short yclamp, int UNUSED(winx), int winy)
+View2DGrid *UI_view2d_grid_calc(Scene *scene, View2D *v2d,
+ short xunits, short xclamp, short yunits, short yclamp, int UNUSED(winx), int winy)
{
View2DGrid *grid;
@@ -1140,8 +1146,8 @@ View2DGrid *UI_view2d_grid_calc(Scene *scene, View2D *v2d, short xunits, short x
/* calculate x-axis grid scale (only if both args are valid) */
if (ELEM(V2D_ARG_DUMMY, xunits, xclamp) == 0) {
- space = BLI_RCT_SIZE_X(&v2d->cur);
- pixels = (float)BLI_RCT_SIZE_X(&v2d->mask);
+ space = BLI_rctf_size_x(&v2d->cur);
+ pixels = (float)BLI_rcti_size_x(&v2d->mask);
if (pixels != 0.0f) {
grid->dx = (U.v2d_min_gridsize * space) / (seconddiv * pixels);
@@ -1158,7 +1164,7 @@ View2DGrid *UI_view2d_grid_calc(Scene *scene, View2D *v2d, short xunits, short x
/* calculate y-axis grid scale (only if both args are valid) */
if (ELEM(V2D_ARG_DUMMY, yunits, yclamp) == 0) {
- space = BLI_RCT_SIZE_Y(&v2d->cur);
+ space = BLI_rctf_size_y(&v2d->cur);
pixels = (float)winy;
grid->dy = U.v2d_min_gridsize * space / pixels;
@@ -1206,7 +1212,7 @@ void UI_view2d_grid_draw(View2D *v2d, View2DGrid *grid, int flag)
vec2[1] = v2d->cur.ymax;
/* minor gridlines */
- step = (BLI_RCT_SIZE_X(&v2d->mask) + 1) / U.v2d_min_gridsize;
+ step = (BLI_rcti_size_x(&v2d->mask) + 1) / U.v2d_min_gridsize;
UI_ThemeColor(TH_GRID);
for (a = 0; a < step; a++) {
@@ -1240,7 +1246,7 @@ void UI_view2d_grid_draw(View2D *v2d, View2DGrid *grid, int flag)
vec1[0] = grid->startx;
vec2[0] = v2d->cur.xmax;
- step = (BLI_RCT_SIZE_Y(&v2d->mask) + 1) / U.v2d_min_gridsize;
+ step = (BLI_rcti_size_y(&v2d->mask) + 1) / U.v2d_min_gridsize;
UI_ThemeColor(TH_GRID);
for (a = 0; a <= step; a++) {
@@ -1256,7 +1262,7 @@ void UI_view2d_grid_draw(View2D *v2d, View2DGrid *grid, int flag)
vec2[1] = vec1[1] -= 0.5f * grid->dy;
step++;
- if (flag & V2D_HORIZONTAL_FINELINES) {
+ if (flag & V2D_HORIZONTAL_FINELINES) {
UI_ThemeColorShade(TH_GRID, 16);
for (a = 0; a < step; a++) {
glBegin(GL_LINE_STRIP);
@@ -1414,7 +1420,8 @@ struct View2DScrollers {
};
/* Calculate relevant scroller properties */
-View2DScrollers *UI_view2d_scrollers_calc(const bContext *C, View2D *v2d, short xunits, short xclamp, short yunits, short yclamp)
+View2DScrollers *UI_view2d_scrollers_calc(const bContext *C, View2D *v2d,
+ short xunits, short xclamp, short yunits, short yclamp)
{
View2DScrollers *scrollers;
rcti vert, hor;
@@ -1457,8 +1464,8 @@ View2DScrollers *UI_view2d_scrollers_calc(const bContext *C, View2D *v2d, short
/* horizontal scrollers */
if (scroll & V2D_SCROLL_HORIZONTAL) {
/* scroller 'button' extents */
- totsize = BLI_RCT_SIZE_X(&v2d->tot);
- scrollsize = (float)BLI_RCT_SIZE_X(&hor);
+ totsize = BLI_rctf_size_x(&v2d->tot);
+ scrollsize = (float)BLI_rcti_size_x(&hor);
if (totsize == 0.0f) totsize = 1.0f; /* avoid divide by zero */
fac1 = (v2d->cur.xmin - v2d->tot.xmin) / totsize;
@@ -1486,7 +1493,7 @@ View2DScrollers *UI_view2d_scrollers_calc(const bContext *C, View2D *v2d, short
/* check whether sliders can disappear due to the full-range being used */
if (v2d->keeptot) {
- if ((fac1 <= 0.0f) && (fac2 >= 1.0f)) {
+ if ((fac1 <= 0.0f) && (fac2 >= 1.0f)) {
v2d->scroll |= V2D_SCROLL_HORIZONTAL_FULLR;
scrollers->horfull = 1;
}
@@ -1498,8 +1505,8 @@ View2DScrollers *UI_view2d_scrollers_calc(const bContext *C, View2D *v2d, short
/* vertical scrollers */
if (scroll & V2D_SCROLL_VERTICAL) {
/* scroller 'button' extents */
- totsize = BLI_RCT_SIZE_Y(&v2d->tot);
- scrollsize = (float)BLI_RCT_SIZE_Y(&vert);
+ totsize = BLI_rctf_size_y(&v2d->tot);
+ scrollsize = (float)BLI_rcti_size_y(&vert);
if (totsize == 0.0f) totsize = 1.0f; /* avoid divide by zero */
fac1 = (v2d->cur.ymin - v2d->tot.ymin) / totsize;
@@ -1528,7 +1535,7 @@ View2DScrollers *UI_view2d_scrollers_calc(const bContext *C, View2D *v2d, short
/* check whether sliders can disappear due to the full-range being used */
if (v2d->keeptot) {
- if ((fac1 <= 0.0f) && (fac2 >= 1.0f)) {
+ if ((fac1 <= 0.0f) && (fac2 >= 1.0f)) {
v2d->scroll |= V2D_SCROLL_VERTICAL_FULLR;
scrollers->vertfull = 1;
}
@@ -1547,7 +1554,7 @@ View2DScrollers *UI_view2d_scrollers_calc(const bContext *C, View2D *v2d, short
scrollers->grid = UI_view2d_grid_calc(CTX_data_scene(C), v2d,
xunits, xclamp, yunits, yclamp,
- BLI_RCT_SIZE_X(&hor), BLI_RCT_SIZE_Y(&vert));
+ BLI_rcti_size_x(&hor), BLI_rcti_size_y(&vert));
}
/* return scrollers */
@@ -1631,7 +1638,7 @@ void UI_view2d_scrollers_draw(const bContext *C, View2D *v2d, View2DScrollers *v
*/
if ((v2d->keepzoom & V2D_LOCKZOOM_X) == 0 &&
(v2d->scroll & V2D_SCROLL_SCALE_HORIZONTAL) &&
- (BLI_RCT_SIZE_X(&slider) > V2D_SCROLLER_HANDLE_SIZE))
+ (BLI_rcti_size_x(&slider) > V2D_SCROLLER_HANDLE_SIZE))
{
state |= UI_SCROLL_ARROWS;
}
@@ -1651,11 +1658,11 @@ void UI_view2d_scrollers_draw(const bContext *C, View2D *v2d, View2DScrollers *v
* - fac is x-coordinate to draw to
* - dfac is gap between scale markings
*/
- fac = (grid->startx - v2d->cur.xmin) / BLI_RCT_SIZE_X(&v2d->cur);
- fac = (float)hor.xmin + fac * BLI_RCT_SIZE_X(&hor);
+ fac = (grid->startx - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
+ fac = (float)hor.xmin + fac * BLI_rcti_size_x(&hor);
- dfac = grid->dx / BLI_RCT_SIZE_X(&v2d->cur);
- dfac = dfac * BLI_RCT_SIZE_X(&hor);
+ dfac = grid->dx / BLI_rctf_size_x(&v2d->cur);
+ dfac = dfac * BLI_rcti_size_x(&hor);
/* set starting value, and text color */
UI_ThemeColor(TH_TEXT);
@@ -1681,7 +1688,7 @@ void UI_view2d_scrollers_draw(const bContext *C, View2D *v2d, View2DScrollers *v
if (fac < hor.xmin + 10)
continue;
- switch (vs->xunits) {
+ switch (vs->xunits) {
case V2D_UNIT_FRAMES: /* frames (as whole numbers)*/
scroll_printstr(scene, fac, h, val, grid->powerx, V2D_UNIT_FRAMES, 'h');
break;
@@ -1742,7 +1749,7 @@ void UI_view2d_scrollers_draw(const bContext *C, View2D *v2d, View2DScrollers *v
*/
if ((v2d->keepzoom & V2D_LOCKZOOM_Y) == 0 &&
(v2d->scroll & V2D_SCROLL_SCALE_VERTICAL) &&
- (BLI_RCT_SIZE_Y(&slider) > V2D_SCROLLER_HANDLE_SIZE))
+ (BLI_rcti_size_y(&slider) > V2D_SCROLLER_HANDLE_SIZE))
{
state |= UI_SCROLL_ARROWS;
}
@@ -1765,11 +1772,11 @@ void UI_view2d_scrollers_draw(const bContext *C, View2D *v2d, View2DScrollers *v
* - these involve a correction for horizontal scrollbar
* NOTE: it's assumed that that scrollbar is there if this is involved!
*/
- fac = (grid->starty - v2d->cur.ymin) / BLI_RCT_SIZE_Y(&v2d->cur);
- fac = vert.ymin + fac * BLI_RCT_SIZE_Y(&vert);
+ fac = (grid->starty - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
+ fac = vert.ymin + fac * BLI_rcti_size_y(&vert);
- dfac = grid->dy / BLI_RCT_SIZE_Y(&v2d->cur);
- dfac = dfac * BLI_RCT_SIZE_Y(&vert);
+ dfac = grid->dy / BLI_rctf_size_y(&v2d->cur);
+ dfac = dfac * BLI_rcti_size_y(&vert);
/* set starting value, and text color */
UI_ThemeColor(TH_TEXT);
@@ -1796,7 +1803,7 @@ void UI_view2d_scrollers_draw(const bContext *C, View2D *v2d, View2DScrollers *v
BLF_disable_default(BLF_ROTATION);
}
- }
+ }
}
}
@@ -1823,7 +1830,9 @@ void UI_view2d_scrollers_free(View2DScrollers *scrollers)
* - column, row = the 2d-coordinates (in 2D-view / 'tot' rect space) the cell exists at
* - rect = coordinates of the cell (passed as single var instead of 4 separate, as it's more useful this way)
*/
-void UI_view2d_listview_cell_to_view(View2D *v2d, short columnwidth, short rowheight, float startx, float starty, int column, int row, rctf *rect)
+void UI_view2d_listview_cell_to_view(View2D *v2d, short columnwidth, short rowheight,
+ float startx, float starty,
+ int column, int row, rctf *rect)
{
/* sanity checks */
if (ELEM(NULL, v2d, rect)) {
@@ -1927,17 +1936,17 @@ void UI_view2d_region_to_view(View2D *v2d, int x, int y, float *r_viewx, float *
float div, ofs;
if (r_viewx) {
- div = (float)BLI_RCT_SIZE_X(&v2d->mask);
+ div = (float)BLI_rcti_size_x(&v2d->mask);
ofs = (float)v2d->mask.xmin;
- *r_viewx = v2d->cur.xmin + BLI_RCT_SIZE_X(&v2d->cur) * ((float)x - ofs) / div;
+ *r_viewx = v2d->cur.xmin + BLI_rctf_size_x(&v2d->cur) * ((float)x - ofs) / div;
}
if (r_viewy) {
- div = (float)BLI_RCT_SIZE_Y(&v2d->mask);
+ div = (float)BLI_rcti_size_y(&v2d->mask);
ofs = (float)v2d->mask.ymin;
- *r_viewy = v2d->cur.ymin + BLI_RCT_SIZE_Y(&v2d->cur) * ((float)y - ofs) / div;
+ *r_viewy = v2d->cur.ymin + BLI_rctf_size_y(&v2d->cur) * ((float)y - ofs) / div;
}
}
@@ -1956,15 +1965,15 @@ void UI_view2d_view_to_region(View2D *v2d, float x, float y, int *regionx, int *
*regiony = V2D_IS_CLIPPED;
/* express given coordinates as proportional values */
- x = (x - v2d->cur.xmin) / BLI_RCT_SIZE_X(&v2d->cur);
- y = (y - v2d->cur.ymin) / BLI_RCT_SIZE_Y(&v2d->cur);
+ x = (x - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
+ y = (y - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
/* check if values are within bounds */
if ((x >= 0.0f) && (x <= 1.0f) && (y >= 0.0f) && (y <= 1.0f)) {
if (regionx)
- *regionx = (int)(v2d->mask.xmin + x * BLI_RCT_SIZE_X(&v2d->mask));
+ *regionx = (int)(v2d->mask.xmin + x * BLI_rcti_size_x(&v2d->mask));
if (regiony)
- *regiony = (int)(v2d->mask.ymin + y * BLI_RCT_SIZE_Y(&v2d->mask));
+ *regiony = (int)(v2d->mask.ymin + y * BLI_rcti_size_y(&v2d->mask));
}
}
@@ -1977,12 +1986,12 @@ void UI_view2d_view_to_region(View2D *v2d, float x, float y, int *regionx, int *
void UI_view2d_to_region_no_clip(View2D *v2d, float x, float y, int *regionx, int *regiony)
{
/* step 1: express given coordinates as proportional values */
- x = (x - v2d->cur.xmin) / BLI_RCT_SIZE_X(&v2d->cur);
- y = (y - v2d->cur.ymin) / BLI_RCT_SIZE_Y(&v2d->cur);
+ x = (x - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
+ y = (y - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
/* step 2: convert proportional distances to screen coordinates */
- x = v2d->mask.xmin + x * BLI_RCT_SIZE_X(&v2d->mask);
- y = v2d->mask.ymin + y * BLI_RCT_SIZE_Y(&v2d->mask);
+ x = v2d->mask.xmin + x * BLI_rcti_size_x(&v2d->mask);
+ y = v2d->mask.ymin + y * BLI_rcti_size_y(&v2d->mask);
/* although we don't clamp to lie within region bounds, we must avoid exceeding size of ints */
if (regionx) {
@@ -2035,8 +2044,8 @@ View2D *UI_view2d_fromcontext_rwin(const bContext *C)
*/
void UI_view2d_getscale(View2D *v2d, float *x, float *y)
{
- if (x) *x = BLI_RCT_SIZE_X(&v2d->mask) / BLI_RCT_SIZE_X(&v2d->cur);
- if (y) *y = BLI_RCT_SIZE_Y(&v2d->mask) / BLI_RCT_SIZE_Y(&v2d->cur);
+ if (x) *x = BLI_rcti_size_x(&v2d->mask) / BLI_rctf_size_x(&v2d->cur);
+ if (y) *y = BLI_rcti_size_y(&v2d->mask) / BLI_rctf_size_y(&v2d->cur);
}
/* Check if mouse is within scrollers
@@ -2063,7 +2072,7 @@ short UI_view2d_mouse_in_scrollers(const bContext *C, View2D *v2d, int x, int y)
}
if (scroll & V2D_SCROLL_VERTICAL) {
if (IN_2D_VERT_SCROLL(v2d, co)) return 'v';
- }
+ }
/* not found */
return 0;
@@ -2142,7 +2151,7 @@ void UI_view2d_text_cache_draw(ARegion *ar)
const char *str = (const char *)(v2s + 1);
int xofs = 0, yofs;
- yofs = ceil(0.5f * (BLI_RCT_SIZE_Y(&v2s->rect) - default_height));
+ yofs = ceil(0.5f * (BLI_rcti_size_y(&v2s->rect) - default_height));
if (yofs < 1) yofs = 1;
if (col_pack_prev != v2s->col.pack) {
diff --git a/source/blender/editors/interface/view2d_ops.c b/source/blender/editors/interface/view2d_ops.c
index 99313edc289..48a1f8bf0f3 100644
--- a/source/blender/editors/interface/view2d_ops.c
+++ b/source/blender/editors/interface/view2d_ops.c
@@ -119,10 +119,10 @@ static int view_pan_init(bContext *C, wmOperator *op)
vpd->ar = ar;
/* calculate translation factor - based on size of view */
- winx = (float)(BLI_RCT_SIZE_X(&ar->winrct) + 1);
- winy = (float)(BLI_RCT_SIZE_Y(&ar->winrct) + 1);
- vpd->facx = (BLI_RCT_SIZE_X(&v2d->cur)) / winx;
- vpd->facy = (BLI_RCT_SIZE_Y(&v2d->cur)) / winy;
+ winx = (float)(BLI_rcti_size_x(&ar->winrct) + 1);
+ winy = (float)(BLI_rcti_size_y(&ar->winrct) + 1);
+ vpd->facx = (BLI_rctf_size_x(&v2d->cur)) / winx;
+ vpd->facy = (BLI_rctf_size_y(&v2d->cur)) / winy;
return 1;
}
@@ -471,7 +471,7 @@ static int view_scrollup_exec(bContext *C, wmOperator *op)
if (RNA_boolean_get(op->ptr, "page")) {
ARegion *ar = CTX_wm_region(C);
- RNA_int_set(op->ptr, "deltay", BLI_RCT_SIZE_Y(&ar->v2d.mask));
+ RNA_int_set(op->ptr, "deltay", BLI_rcti_size_y(&ar->v2d.mask));
}
/* apply movement, then we're done */
@@ -590,12 +590,12 @@ static void view_zoomstep_apply(bContext *C, wmOperator *op)
facy = RNA_float_get(op->ptr, "zoomfacy");
if (facx >= 0.0f) {
- dx = BLI_RCT_SIZE_X(&v2d->cur) * facx;
- dy = BLI_RCT_SIZE_Y(&v2d->cur) * facy;
+ dx = BLI_rctf_size_x(&v2d->cur) * facx;
+ dy = BLI_rctf_size_y(&v2d->cur) * facy;
}
else {
- dx = (BLI_RCT_SIZE_X(&v2d->cur) / (1.0f + 2.0f * facx)) * facx;
- dy = (BLI_RCT_SIZE_Y(&v2d->cur) / (1.0f + 2.0f * facy)) * facy;
+ dx = (BLI_rctf_size_x(&v2d->cur) / (1.0f + 2.0f * facx)) * facx;
+ dy = (BLI_rctf_size_y(&v2d->cur) / (1.0f + 2.0f * facy)) * facy;
}
/* only resize view on an axis if change is allowed */
@@ -611,7 +611,7 @@ static void view_zoomstep_apply(bContext *C, wmOperator *op)
}
else {
if (U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
- float mval_fac = (vzd->mx_2d - v2d->cur.xmin) / BLI_RCT_SIZE_X(&v2d->cur);
+ float mval_fac = (vzd->mx_2d - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
float mval_faci = 1.0f - mval_fac;
float ofs = (mval_fac * dx) - (mval_faci * dx);
@@ -636,13 +636,13 @@ static void view_zoomstep_apply(bContext *C, wmOperator *op)
}
else {
if (U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
- float mval_fac = (vzd->my_2d - v2d->cur.ymin) / BLI_RCT_SIZE_Y(&v2d->cur);
+ float mval_fac = (vzd->my_2d - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
float mval_faci = 1.0f - mval_fac;
float ofs = (mval_fac * dy) - (mval_faci * dy);
v2d->cur.ymin += ofs + dy;
v2d->cur.ymax += ofs - dy;
- }
+ }
else {
v2d->cur.ymin += dy;
v2d->cur.ymax -= dy;
@@ -827,6 +827,11 @@ static void view_zoomdrag_apply(bContext *C, wmOperator *op)
dx = RNA_float_get(op->ptr, "deltax");
dy = RNA_float_get(op->ptr, "deltay");
+ if (U.uiflag & USER_ZOOM_INVERT) {
+ dx *= -1;
+ dy *= -1;
+ }
+
/* continuous zoom shouldn't move that fast... */
if (U.viewzoom == USER_ZOOM_CONT) { // XXX store this setting as RNA prop?
double time = PIL_check_seconds_timer();
@@ -845,7 +850,7 @@ static void view_zoomdrag_apply(bContext *C, wmOperator *op)
}
else {
if (U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
- float mval_fac = (vzd->mx_2d - v2d->cur.xmin) / BLI_RCT_SIZE_X(&v2d->cur);
+ float mval_fac = (vzd->mx_2d - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
float mval_faci = 1.0f - mval_fac;
float ofs = (mval_fac * dx) - (mval_faci * dx);
@@ -864,7 +869,7 @@ static void view_zoomdrag_apply(bContext *C, wmOperator *op)
}
else {
if (U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
- float mval_fac = (vzd->my_2d - v2d->cur.ymin) / BLI_RCT_SIZE_Y(&v2d->cur);
+ float mval_fac = (vzd->my_2d - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
float mval_faci = 1.0f - mval_fac;
float ofs = (mval_fac * dy) - (mval_faci * dy);
@@ -942,8 +947,8 @@ static int view_zoomdrag_invoke(bContext *C, wmOperator *op, wmEvent *event)
* with magnify information that is stored in x axis
*/
fac = 0.01f * (event->x - event->prevx);
- dx = fac * BLI_RCT_SIZE_X(&v2d->cur) / 10.0f;
- dy = fac * BLI_RCT_SIZE_Y(&v2d->cur) / 10.0f;
+ dx = fac * BLI_rctf_size_x(&v2d->cur) / 10.0f;
+ dy = fac * BLI_rctf_size_y(&v2d->cur) / 10.0f;
RNA_float_set(op->ptr, "deltax", dx);
RNA_float_set(op->ptr, "deltay", dy);
@@ -951,7 +956,7 @@ static int view_zoomdrag_invoke(bContext *C, wmOperator *op, wmEvent *event)
view_zoomdrag_apply(C, op);
view_zoomdrag_exit(C, op);
return OPERATOR_FINISHED;
- }
+ }
/* set initial settings */
vzd->lastx = event->x;
@@ -1009,14 +1014,14 @@ static int view_zoomdrag_modal(bContext *C, wmOperator *op, wmEvent *event)
float dist;
/* x-axis transform */
- dist = BLI_RCT_SIZE_X(&v2d->mask) / 2.0f;
+ dist = BLI_rcti_size_x(&v2d->mask) / 2.0f;
dx = 1.0f - (fabsf(vzd->lastx - dist) + 2.0f) / (fabsf(event->x - dist) + 2.0f);
- dx *= 0.5f * BLI_RCT_SIZE_X(&v2d->cur);
+ dx *= 0.5f * BLI_rctf_size_x(&v2d->cur);
/* y-axis transform */
- dist = BLI_RCT_SIZE_Y(&v2d->mask) / 2.0f;
+ dist = BLI_rcti_size_y(&v2d->mask) / 2.0f;
dy = 1.0f - (fabsf(vzd->lasty - dist) + 2.0f) / (fabsf(event->y - dist) + 2.0f);
- dy *= 0.5f * BLI_RCT_SIZE_Y(&v2d->cur);
+ dy *= 0.5f * BLI_rctf_size_y(&v2d->cur);
}
else {
/* 'continuous' or 'dolly' */
@@ -1024,11 +1029,11 @@ static int view_zoomdrag_modal(bContext *C, wmOperator *op, wmEvent *event)
/* x-axis transform */
fac = 0.01f * (event->x - vzd->lastx);
- dx = fac * BLI_RCT_SIZE_X(&v2d->cur);
+ dx = fac * BLI_rctf_size_x(&v2d->cur);
/* y-axis transform */
fac = 0.01f * (event->y - vzd->lasty);
- dy = fac * BLI_RCT_SIZE_Y(&v2d->cur);
+ dy = fac * BLI_rctf_size_y(&v2d->cur);
#if 0
/* continuous zoom shouldn't move that fast... */
if (U.viewzoom == USER_ZOOM_CONT) { // XXX store this setting as RNA prop?
@@ -1046,6 +1051,7 @@ static int view_zoomdrag_modal(bContext *C, wmOperator *op, wmEvent *event)
/* set transform amount, and add current deltas to stored total delta (for redo) */
RNA_float_set(op->ptr, "deltax", dx);
RNA_float_set(op->ptr, "deltay", dy);
+
vzd->dx += dx;
vzd->dy += dy;
@@ -1059,7 +1065,7 @@ static int view_zoomdrag_modal(bContext *C, wmOperator *op, wmEvent *event)
/* apply zooming */
view_zoomdrag_apply(C, op);
- }
+ }
else if (event->type == vzd->invoke_event || event->type == ESCKEY) {
if (event->val == KM_RELEASE) {
@@ -1161,17 +1167,17 @@ static int view_borderzoom_exec(bContext *C, wmOperator *op)
/* TODO: is this zoom factor calculation valid? It seems to produce same results everytime... */
if ((v2d->keepzoom & V2D_LOCKZOOM_X) == 0) {
- size = BLI_RCT_SIZE_X(&cur_new);
- zoom = size / BLI_RCT_SIZE_X(&rect);
- center = BLI_RCT_CENTER_X(&cur_new);
+ size = BLI_rctf_size_x(&cur_new);
+ zoom = size / BLI_rctf_size_x(&rect);
+ center = BLI_rctf_cent_x(&cur_new);
cur_new.xmin = center - (size * zoom);
cur_new.xmax = center + (size * zoom);
}
if ((v2d->keepzoom & V2D_LOCKZOOM_Y) == 0) {
- size = BLI_RCT_SIZE_Y(&cur_new);
- zoom = size / BLI_RCT_SIZE_Y(&rect);
- center = BLI_RCT_CENTER_Y(&cur_new);
+ size = BLI_rctf_size_y(&cur_new);
+ zoom = size / BLI_rctf_size_y(&rect);
+ center = BLI_rctf_cent_y(&cur_new);
cur_new.ymin = center - (size * zoom);
cur_new.ymax = center + (size * zoom);
@@ -1221,14 +1227,14 @@ struct SmoothView2DStore {
*/
static float smooth_view_rect_to_fac(const rctf *rect_a, const rctf *rect_b)
{
- float size_a[2] = {BLI_RCT_SIZE_X(rect_a),
- BLI_RCT_SIZE_Y(rect_a)};
- float size_b[2] = {BLI_RCT_SIZE_X(rect_b),
- BLI_RCT_SIZE_Y(rect_b)};
- float cent_a[2] = {BLI_RCT_CENTER_X(rect_a),
- BLI_RCT_CENTER_Y(rect_a)};
- float cent_b[2] = {BLI_RCT_CENTER_X(rect_b),
- BLI_RCT_CENTER_Y(rect_b)};
+ float size_a[2] = {BLI_rctf_size_x(rect_a),
+ BLI_rctf_size_y(rect_a)};
+ float size_b[2] = {BLI_rctf_size_x(rect_b),
+ BLI_rctf_size_y(rect_b)};
+ float cent_a[2] = {BLI_rctf_cent_x(rect_a),
+ BLI_rctf_cent_y(rect_a)};
+ float cent_b[2] = {BLI_rctf_cent_x(rect_b),
+ BLI_rctf_cent_y(rect_b)};
float fac_max = 0.0f;
float tfac;
@@ -1237,16 +1243,16 @@ static float smooth_view_rect_to_fac(const rctf *rect_a, const rctf *rect_b)
for (i = 0; i < 2; i++) {
/* axis translation normalized to scale */
- tfac = fabsf(cent_a[i] - cent_b[i]) / minf(size_a[i], size_b[i]);
- fac_max = maxf(fac_max, tfac);
+ tfac = fabsf(cent_a[i] - cent_b[i]) / min_ff(size_a[i], size_b[i]);
+ fac_max = max_ff(fac_max, tfac);
if (fac_max >= 1.0f) break;
/* axis scale difference, x2 so doubling or half gives 1.0f */
- tfac = (1.0f - (minf(size_a[i], size_b[i]) / maxf(size_a[i], size_b[i]))) * 2.0f;
- fac_max = maxf(fac_max, tfac);
+ tfac = (1.0f - (min_ff(size_a[i], size_b[i]) / max_ff(size_a[i], size_b[i]))) * 2.0f;
+ fac_max = max_ff(fac_max, tfac);
if (fac_max >= 1.0f) break;
}
- return minf(fac_max, 1.0f);
+ return min_ff(fac_max, 1.0f);
}
/* will start timer if appropriate */
@@ -1273,11 +1279,10 @@ void UI_view2d_smooth_view(bContext *C, ARegion *ar,
}
if (C && U.smooth_viewtx && fac > FLT_EPSILON) {
- int changed = 0; /* zero means no difference */
+ int changed = FALSE;
if (BLI_rctf_compare(&sms.new_cur, &v2d->cur, FLT_EPSILON) == FALSE)
- changed = 1;
- changed=1;
+ changed = TRUE;
/* The new view is different from the old one
* so animate the view */
@@ -1464,7 +1469,7 @@ static short mouse_in_scroller_handle(int mouse, int sc_min, int sc_max, int sh_
else if (in_min)
return SCROLLHANDLE_MIN;
else if (out_min)
- return SCROLLHANDLE_MIN_OUTSIDE;
+ return SCROLLHANDLE_MIN_OUTSIDE;
else if (out_max)
return SCROLLHANDLE_MAX_OUTSIDE;
@@ -1479,6 +1484,7 @@ static void scroller_activate_init(bContext *C, wmOperator *op, wmEvent *event,
View2DScrollers *scrollers;
ARegion *ar = CTX_wm_region(C);
View2D *v2d = &ar->v2d;
+ rctf tot_cur_union;
float mask_size;
/* set custom-data for operator */
@@ -1498,14 +1504,20 @@ static void scroller_activate_init(bContext *C, wmOperator *op, wmEvent *event,
*/
scrollers = UI_view2d_scrollers_calc(C, v2d, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY);
+ /* use a union of 'cur' & 'tot' incase the current view is far outside 'tot'.
+ * In this cases moving the scroll bars has far too little effect and the view can get stuck [#31476] */
+ tot_cur_union = v2d->tot;
+ BLI_rctf_union(&tot_cur_union, &v2d->cur);
if (in_scroller == 'h') {
/* horizontal scroller - calculate adjustment factor first */
- mask_size = (float)BLI_RCT_SIZE_X(&v2d->hor);
- vsm->fac = BLI_RCT_SIZE_X(&v2d->tot) / mask_size;
+ mask_size = (float)BLI_rcti_size_x(&v2d->hor);
+ vsm->fac = BLI_rctf_size_x(&tot_cur_union) / mask_size;
/* get 'zone' (i.e. which part of scroller is activated) */
- vsm->zone = mouse_in_scroller_handle(event->mval[0], v2d->hor.xmin, v2d->hor.xmax, scrollers->hor_min, scrollers->hor_max);
+ vsm->zone = mouse_in_scroller_handle(event->mval[0],
+ v2d->hor.xmin, v2d->hor.xmax,
+ scrollers->hor_min, scrollers->hor_max);
if ((v2d->keepzoom & V2D_LOCKZOOM_X) && ELEM(vsm->zone, SCROLLHANDLE_MIN, SCROLLHANDLE_MAX)) {
/* default to scroll, as handles not usable */
@@ -1517,11 +1529,13 @@ static void scroller_activate_init(bContext *C, wmOperator *op, wmEvent *event,
}
else {
/* vertical scroller - calculate adjustment factor first */
- mask_size = (float)BLI_RCT_SIZE_Y(&v2d->vert);
- vsm->fac = BLI_RCT_SIZE_Y(&v2d->tot) / mask_size;
+ mask_size = (float)BLI_rcti_size_y(&v2d->vert);
+ vsm->fac = BLI_rctf_size_y(&tot_cur_union) / mask_size;
/* get 'zone' (i.e. which part of scroller is activated) */
- vsm->zone = mouse_in_scroller_handle(event->mval[1], v2d->vert.ymin, v2d->vert.ymax, scrollers->vert_min, scrollers->vert_max);
+ vsm->zone = mouse_in_scroller_handle(event->mval[1],
+ v2d->vert.ymin, v2d->vert.ymax,
+ scrollers->vert_min, scrollers->vert_max);
if ((v2d->keepzoom & V2D_LOCKZOOM_Y) && ELEM(vsm->zone, SCROLLHANDLE_MIN, SCROLLHANDLE_MAX)) {
/* default to scroll, as handles not usable */
@@ -1529,7 +1543,7 @@ static void scroller_activate_init(bContext *C, wmOperator *op, wmEvent *event,
}
vsm->scrollbarwidth = scrollers->vert_max - scrollers->vert_min;
- vsm->scrollbar_orig = ((scrollers->vert_max + scrollers->vert_min) / 2) + +ar->winrct.ymin;
+ vsm->scrollbar_orig = ((scrollers->vert_max + scrollers->vert_min) / 2) + ar->winrct.ymin;
}
UI_view2d_scrollers_free(scrollers);
@@ -1737,7 +1751,7 @@ static int scroller_activate_invoke(bContext *C, wmOperator *op, wmEvent *event)
/* can't catch this event for ourselves, so let it go to someone else? */
return OPERATOR_PASS_THROUGH;
- }
+ }
}
/* zone is also inappropriate if scroller is not visible... */
@@ -1798,8 +1812,8 @@ static int reset_exec(bContext *C, wmOperator *UNUSED(op))
int winx, winy;
/* zoom 1.0 */
- winx = (float)(BLI_RCT_SIZE_X(&v2d->mask) + 1);
- winy = (float)(BLI_RCT_SIZE_Y(&v2d->mask) + 1);
+ winx = (float)(BLI_rcti_size_x(&v2d->mask) + 1);
+ winy = (float)(BLI_rcti_size_y(&v2d->mask) + 1);
v2d->cur.xmax = v2d->cur.xmin + winx;
v2d->cur.ymax = v2d->cur.ymin + winy;
diff --git a/source/blender/editors/io/io_collada.c b/source/blender/editors/io/io_collada.c
index 0e6b8f77528..ba93206e63a 100644
--- a/source/blender/editors/io/io_collada.c
+++ b/source/blender/editors/io/io_collada.c
@@ -54,6 +54,8 @@
#include "../../collada/collada.h"
+#include "io_collada.h"
+
static int wm_collada_export_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
{
if (!RNA_struct_property_is_set(op->ptr, "filepath")) {
@@ -121,32 +123,32 @@ static int wm_collada_export_exec(bContext *C, wmOperator *op)
/* get editmode results */
ED_object_exit_editmode(C, 0); /* 0 = does not exit editmode */
- if (collada_export(
- CTX_data_scene(C),
- filepath,
- apply_modifiers,
- export_mesh_type,
- selected,
- include_children,
- include_armatures,
- deform_bones_only,
-
- active_uv_only,
- include_uv_textures,
- include_material_textures,
- use_texture_copies,
-
- use_object_instantiation,
- sort_by_name,
- second_life)) {
+ if (collada_export(CTX_data_scene(C),
+ filepath,
+ apply_modifiers,
+ export_mesh_type,
+ selected,
+ include_children,
+ include_armatures,
+ deform_bones_only,
+
+ active_uv_only,
+ include_uv_textures,
+ include_material_textures,
+ use_texture_copies,
+
+ use_object_instantiation,
+ sort_by_name,
+ second_life)) {
return OPERATOR_FINISHED;
}
else {
+ BKE_report(op->reports, RPT_WARNING, "Export file not created");
return OPERATOR_CANCELLED;
}
}
-void uiCollada_exportSettings(uiLayout *layout, PointerRNA *imfptr)
+static void uiCollada_exportSettings(uiLayout *layout, PointerRNA *imfptr)
{
uiLayout *box, *row, *col, *split;
@@ -233,7 +235,7 @@ void WM_OT_collada_export(wmOperatorType *ot)
ot->name = "Export COLLADA";
ot->description = "Save a Collada file";
ot->idname = "WM_OT_collada_export";
-
+
ot->invoke = wm_collada_export_invoke;
ot->exec = wm_collada_export_exec;
ot->poll = WM_operator_winactive;
@@ -241,7 +243,7 @@ void WM_OT_collada_export(wmOperatorType *ot)
ot->flag |= OPTYPE_PRESET;
ot->ui = wm_collada_export_draw;
-
+
WM_operator_properties_filesel(ot, FOLDERFILE | COLLADAFILE, FILE_BLENDER, FILE_SAVE,
WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY);
@@ -296,7 +298,7 @@ void WM_OT_collada_export(wmOperatorType *ot)
static int wm_collada_import_exec(bContext *C, wmOperator *op)
{
char filename[FILE_MAX];
-
+
if (!RNA_struct_property_is_set(op->ptr, "filepath")) {
BKE_report(op->reports, RPT_ERROR, "No filename given");
return OPERATOR_CANCELLED;
@@ -304,9 +306,9 @@ static int wm_collada_import_exec(bContext *C, wmOperator *op)
RNA_string_get(op->ptr, "filepath", filename);
if (collada_import(C, filename)) return OPERATOR_FINISHED;
-
- BKE_report(op->reports, RPT_ERROR, "Errors found during parsing COLLADA document. Please see console for error log.");
-
+
+ BKE_report(op->reports, RPT_ERROR, "Errors found during parsing COLLADA document (see console for details)");
+
return OPERATOR_FINISHED;
}
@@ -315,11 +317,11 @@ void WM_OT_collada_import(wmOperatorType *ot)
ot->name = "Import COLLADA";
ot->description = "Load a Collada file";
ot->idname = "WM_OT_collada_import";
-
+
ot->invoke = WM_operator_filesel;
ot->exec = wm_collada_import_exec;
ot->poll = WM_operator_winactive;
-
+
WM_operator_properties_filesel(ot, FOLDERFILE | COLLADAFILE, FILE_BLENDER, FILE_OPENFILE,
WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY);
}
diff --git a/source/blender/editors/mask/CMakeLists.txt b/source/blender/editors/mask/CMakeLists.txt
index 57be5a2234a..25fb9cb6430 100644
--- a/source/blender/editors/mask/CMakeLists.txt
+++ b/source/blender/editors/mask/CMakeLists.txt
@@ -30,10 +30,10 @@ set(INC
../../makesrna
../../windowmanager
../../../../intern/guardedalloc
- ${GLEW_INCLUDE_PATH}
)
set(INC_SYS
+ ${GLEW_INCLUDE_PATH}
)
set(SRC
diff --git a/source/blender/editors/mask/mask_add.c b/source/blender/editors/mask/mask_add.c
index 7fe1ac09df6..e43c8a2b53b 100644
--- a/source/blender/editors/mask/mask_add.c
+++ b/source/blender/editors/mask/mask_add.c
@@ -46,6 +46,7 @@
#include "WM_types.h"
#include "ED_mask.h" /* own include */
+#include "ED_screen.h"
#include "RNA_access.h"
#include "RNA_define.h"
@@ -64,7 +65,7 @@ static int find_nearest_diff_point(const bContext *C, Mask *mask, const float no
MaskLayer *masklay, *point_masklay;
MaskSpline *point_spline;
MaskSplinePoint *point = NULL;
- float dist, co[2];
+ float dist = FLT_MAX, co[2];
int width, height;
float u;
float scalex, scaley;
@@ -97,7 +98,7 @@ static int find_nearest_diff_point(const bContext *C, Mask *mask, const float no
&tot_diff_point);
if (diff_points) {
- int i, tot_point;
+ int j, tot_point;
unsigned int tot_feather_point;
float *feather_points = NULL, *points;
@@ -114,26 +115,26 @@ static int find_nearest_diff_point(const bContext *C, Mask *mask, const float no
tot_point = tot_diff_point;
}
- for (i = 0; i < tot_point - 1; i++) {
+ for (j = 0; j < tot_point - 1; j++) {
float cur_dist, a[2], b[2];
- a[0] = points[2 * i] * scalex;
- a[1] = points[2 * i + 1] * scaley;
+ a[0] = points[2 * j] * scalex;
+ a[1] = points[2 * j + 1] * scaley;
- b[0] = points[2 * i + 2] * scalex;
- b[1] = points[2 * i + 3] * scaley;
+ b[0] = points[2 * j + 2] * scalex;
+ b[1] = points[2 * j + 3] * scaley;
cur_dist = dist_to_line_segment_v2(co, a, b);
- if (point == NULL || cur_dist < dist) {
+ if (cur_dist < dist) {
if (tangent)
- sub_v2_v2v2(tangent, &diff_points[2 * i + 2], &diff_points[2 * i]);
+ sub_v2_v2v2(tangent, &diff_points[2 * j + 2], &diff_points[2 * j]);
point_masklay = masklay;
point_spline = spline;
point = use_deform ? &spline->points[(cur_point - spline->points_deform)] : cur_point;
dist = cur_dist;
- u = (float)i / tot_point;
+ u = (float)j / tot_point;
}
}
@@ -562,6 +563,11 @@ static int add_vertex_exec(bContext *C, wmOperator *op)
float co[2];
+ if (mask == NULL) {
+ /* if there's no active mask, create one */
+ mask = ED_mask_new(C, NULL);
+ }
+
masklay = BKE_mask_layer_active(mask);
if (masklay && masklay->restrictflag & (MASK_RESTRICT_VIEW | MASK_RESTRICT_SELECT)) {
@@ -647,7 +653,7 @@ void MASK_OT_add_vertex(wmOperatorType *ot)
/* api callbacks */
ot->exec = add_vertex_exec;
ot->invoke = add_vertex_invoke;
- ot->poll = ED_maskedit_mask_poll;
+ ot->poll = ED_operator_mask;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
diff --git a/source/blender/editors/mask/mask_draw.c b/source/blender/editors/mask/mask_draw.c
index 655458bd4cb..74cdf4c2a11 100644
--- a/source/blender/editors/mask/mask_draw.c
+++ b/source/blender/editors/mask/mask_draw.c
@@ -20,6 +20,7 @@
*
*
* Contributor(s): Blender Foundation,
+ * Campbell Barton,
* Sergey Sharybin
*
* ***** END GPL LICENSE BLOCK *****
@@ -41,7 +42,9 @@
#include "DNA_mask_types.h"
#include "DNA_screen_types.h"
#include "DNA_object_types.h" /* SELECT */
+#include "DNA_space_types.h"
+#include "ED_clip.h"
#include "ED_mask.h" /* own include */
#include "ED_space_api.h"
#include "BIF_gl.h"
@@ -120,13 +123,22 @@ static void draw_spline_parents(MaskLayer *UNUSED(masklay), MaskSpline *spline)
}
#endif
+static void mask_point_undistort_pos(SpaceClip *sc, float r_co[2], float co[2])
+{
+ BKE_mask_coord_to_movieclip(sc->clip, &sc->user, r_co, co);
+ ED_clip_point_undistorted_pos(sc, r_co, r_co);
+ BKE_mask_coord_from_movieclip(sc->clip, &sc->user, r_co, r_co);
+}
+
/* return non-zero if spline is selected */
-static void draw_spline_points(MaskLayer *masklay, MaskSpline *spline,
+static void draw_spline_points(const bContext *C, MaskLayer *masklay, MaskSpline *spline,
const char UNUSED(draw_flag), const char draw_type)
{
const int is_spline_sel = (spline->flag & SELECT) && (masklay->restrictflag & MASK_RESTRICT_SELECT) == 0;
unsigned char rgb_spline[4];
MaskSplinePoint *points_array = BKE_mask_spline_point_array(spline);
+ SpaceClip *sc = CTX_wm_space_clip(C);
+ int undistort = FALSE;
int i, hsize, tot_feather_point;
float (*feather_points)[2], (*fp)[2];
@@ -134,6 +146,9 @@ static void draw_spline_points(MaskLayer *masklay, MaskSpline *spline,
if (!spline->tot_point)
return;
+ if (sc)
+ undistort = sc->clip && sc->user.render_flag & MCLIP_PROXY_RENDER_UNDISTORT;
+
/* TODO, add this to sequence editor */
hsize = 4; /* UI_GetThemeValuef(TH_HANDLE_VERTEX_SIZE); */
@@ -151,8 +166,14 @@ static void draw_spline_points(MaskLayer *masklay, MaskSpline *spline,
int j;
for (j = 0; j < point->tot_uw + 1; j++) {
+ float feather_point[2];
int sel = FALSE;
+ copy_v2_v2(feather_point, *fp);
+
+ if (undistort)
+ mask_point_undistort_pos(sc, feather_point, feather_point);
+
if (j == 0) {
sel = MASKPOINT_ISSEL_ANY(point);
}
@@ -171,7 +192,7 @@ static void draw_spline_points(MaskLayer *masklay, MaskSpline *spline,
}
glBegin(GL_POINTS);
- glVertex2fv(*fp);
+ glVertex2fv(feather_point);
glEnd();
fp++;
@@ -188,11 +209,17 @@ static void draw_spline_points(MaskLayer *masklay, MaskSpline *spline,
BezTriple *bezt = &point_deform->bezt;
float handle[2];
- float *vert = bezt->vec[1];
+ float vert[2];
int has_handle = BKE_mask_point_has_handle(point);
+ copy_v2_v2(vert, bezt->vec[1]);
BKE_mask_point_handle(point_deform, handle);
+ if (undistort) {
+ mask_point_undistort_pos(sc, vert, vert);
+ mask_point_undistort_pos(sc, handle, handle);
+ }
+
/* draw handle segment */
if (has_handle) {
@@ -202,16 +229,16 @@ static void draw_spline_points(MaskLayer *masklay, MaskSpline *spline,
glLineWidth(3);
glColor4ubv(rgb_gray);
glBegin(GL_LINES);
- glVertex3fv(vert);
- glVertex3fv(handle);
+ glVertex2fv(vert);
+ glVertex2fv(handle);
glEnd();
glLineWidth(1);
}
glColor3ubv(rgb_spline);
glBegin(GL_LINES);
- glVertex3fv(vert);
- glVertex3fv(handle);
+ glVertex2fv(vert);
+ glVertex2fv(handle);
glEnd();
}
@@ -226,7 +253,7 @@ static void draw_spline_points(MaskLayer *masklay, MaskSpline *spline,
glColor3f(0.5f, 0.5f, 0.0f);
glBegin(GL_POINTS);
- glVertex3fv(vert);
+ glVertex2fv(vert);
glEnd();
/* draw handle points */
@@ -242,7 +269,7 @@ static void draw_spline_points(MaskLayer *masklay, MaskSpline *spline,
}
glBegin(GL_POINTS);
- glVertex3fv(handle);
+ glVertex2fv(handle);
glEnd();
}
}
@@ -265,7 +292,7 @@ static void mask_color_active_tint(unsigned char r_rgb[4], const unsigned char r
}
}
-static void mask_draw_curve_type(MaskSpline *spline, float (*points)[2], int tot_point,
+static void mask_draw_curve_type(const bContext *C, MaskSpline *spline, float (*orig_points)[2], int tot_point,
const short is_feather, const short is_smooth, const short is_active,
const unsigned char rgb_spline[4], const char draw_type)
{
@@ -273,6 +300,22 @@ static void mask_draw_curve_type(MaskSpline *spline, float (*points)[2], int tot
const unsigned char rgb_black[4] = {0x00, 0x00, 0x00, 0xff};
// const unsigned char rgb_white[4] = {0xff, 0xff, 0xff, 0xff};
unsigned char rgb_tmp[4];
+ SpaceClip *sc = CTX_wm_space_clip(C);
+ float (*points)[2] = orig_points;
+
+ if (sc) {
+ int undistort = sc->clip && sc->user.render_flag & MCLIP_PROXY_RENDER_UNDISTORT;
+
+ if (undistort) {
+ int i;
+
+ points = MEM_callocN(2 * tot_point * sizeof(float), "undistorthed mask curve");
+
+ for (i = 0; i < tot_point; i++) {
+ mask_point_undistort_pos(sc, points[i], orig_points[i]);
+ }
+ }
+ }
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, points);
@@ -347,8 +390,6 @@ static void mask_draw_curve_type(MaskSpline *spline, float (*points)[2], int tot
glVertexPointer(2, GL_FLOAT, 0, points);
glDrawArrays(draw_method, 0, tot_point);
- glDrawArrays(draw_method, 0, tot_point);
-
if (is_smooth == FALSE && is_feather) {
glDisable(GL_BLEND);
}
@@ -358,14 +399,16 @@ static void mask_draw_curve_type(MaskSpline *spline, float (*points)[2], int tot
glDisableClientState(GL_VERTEX_ARRAY);
+ if (points != orig_points)
+ MEM_freeN(points);
}
-static void draw_spline_curve(MaskLayer *masklay, MaskSpline *spline,
+static void draw_spline_curve(const bContext *C, MaskLayer *masklay, MaskSpline *spline,
const char draw_flag, const char draw_type,
const short is_active,
int width, int height)
{
- const unsigned int resol = maxi(BKE_mask_spline_feather_resolution(spline, width, height),
+ const unsigned int resol = max_ii(BKE_mask_spline_feather_resolution(spline, width, height),
BKE_mask_spline_resolution(spline, width, height));
unsigned char rgb_tmp[4];
@@ -395,7 +438,7 @@ static void draw_spline_curve(MaskLayer *masklay, MaskSpline *spline,
/* draw feather */
mask_spline_feather_color_get(masklay, spline, is_spline_sel, rgb_tmp);
- mask_draw_curve_type(spline, feather_points, tot_feather_point,
+ mask_draw_curve_type(C, spline, feather_points, tot_feather_point,
TRUE, is_smooth, is_active,
rgb_tmp, draw_type);
@@ -414,7 +457,7 @@ static void draw_spline_curve(MaskLayer *masklay, MaskSpline *spline,
}
/* same as above */
- mask_draw_curve_type(spline, feather_points, tot_feather_point,
+ mask_draw_curve_type(C, spline, feather_points, tot_feather_point,
TRUE, is_smooth, is_active,
rgb_tmp, draw_type);
}
@@ -423,7 +466,7 @@ static void draw_spline_curve(MaskLayer *masklay, MaskSpline *spline,
/* draw main curve */
mask_spline_color_get(masklay, spline, is_spline_sel, rgb_tmp);
- mask_draw_curve_type(spline, diff_points, tot_diff_point,
+ mask_draw_curve_type(C, spline, diff_points, tot_diff_point,
FALSE, is_smooth, is_active,
rgb_tmp, draw_type);
MEM_freeN(diff_points);
@@ -436,7 +479,7 @@ static void draw_spline_curve(MaskLayer *masklay, MaskSpline *spline,
(void)draw_type;
}
-static void draw_masklays(Mask *mask, const char draw_flag, const char draw_type,
+static void draw_masklays(const bContext *C, Mask *mask, const char draw_flag, const char draw_type,
int width, int height)
{
MaskLayer *masklay;
@@ -453,13 +496,13 @@ static void draw_masklays(Mask *mask, const char draw_flag, const char draw_type
for (spline = masklay->splines.first; spline; spline = spline->next) {
/* draw curve itself first... */
- draw_spline_curve(masklay, spline, draw_flag, draw_type, is_active, width, height);
+ draw_spline_curve(C, masklay, spline, draw_flag, draw_type, is_active, width, height);
// draw_spline_parents(masklay, spline);
if (!(masklay->restrictflag & MASK_RESTRICT_SELECT)) {
/* ...and then handles over the curve so they're nicely visible */
- draw_spline_points(masklay, spline, draw_flag, draw_type);
+ draw_spline_points(C, masklay, spline, draw_flag, draw_type);
}
/* show undeform for testing */
@@ -467,9 +510,9 @@ static void draw_masklays(Mask *mask, const char draw_flag, const char draw_type
void *back = spline->points_deform;
spline->points_deform = NULL;
- draw_spline_curve(masklay, spline, draw_flag, draw_type, is_active, width, height);
+ draw_spline_curve(C, masklay, spline, draw_flag, draw_type, is_active, width, height);
// draw_spline_parents(masklay, spline);
- draw_spline_points(masklay, spline, draw_flag, draw_type);
+ draw_spline_points(C, masklay, spline, draw_flag, draw_type);
spline->points_deform = back;
}
}
@@ -489,7 +532,7 @@ void ED_mask_draw(const bContext *C,
ED_mask_get_size(sa, &width, &height);
- draw_masklays(mask, draw_flag, draw_type, width, height);
+ draw_masklays(C, mask, draw_flag, draw_type, width, height);
}
/* sets up the opengl context.
@@ -500,7 +543,7 @@ void ED_mask_draw_region(Mask *mask, ARegion *ar,
const float aspx, const float aspy,
const short do_scale_applied, const short do_post_draw,
float stabmat[4][4], /* optional - only used by clip */
- const bContext *C /* optional - only used when do_post_draw is set */
+ const bContext *C /* optional - only used when do_post_draw is set or called from clip editor */
)
{
struct View2D *v2d = &ar->v2d;
@@ -520,12 +563,12 @@ void ED_mask_draw_region(Mask *mask, ARegion *ar,
UI_view2d_to_region_no_clip(&ar->v2d, 0.0f, 0.0f, &x, &y);
- /* w = BLI_RCT_SIZE_X(&v2d->tot); */
- /* h = BLI_RCT_SIZE_Y(&v2d->tot);/*/
+ /* w = BLI_rctf_size_x(&v2d->tot); */
+ /* h = BLI_rctf_size_y(&v2d->tot);/*/
- zoomx = (float)(BLI_RCT_SIZE_X(&ar->winrct) + 1) / (float)(BLI_RCT_SIZE_X(&ar->v2d.cur));
- zoomy = (float)(BLI_RCT_SIZE_Y(&ar->winrct) + 1) / (float)(BLI_RCT_SIZE_Y(&ar->v2d.cur));
+ zoomx = (float)(BLI_rcti_size_x(&ar->winrct) + 1) / BLI_rctf_size_x(&ar->v2d.cur);
+ zoomy = (float)(BLI_rcti_size_y(&ar->winrct) + 1) / BLI_rctf_size_y(&ar->v2d.cur);
if (do_scale_applied) {
zoomx /= width;
@@ -536,7 +579,7 @@ void ED_mask_draw_region(Mask *mask, ARegion *ar,
y += v2d->tot.ymin * zoomy;
/* frame the image */
- maxdim = maxf(width, height);
+ maxdim = max_ff(width, height);
if (width == height) {
xofs = yofs = 0;
}
@@ -559,7 +602,7 @@ void ED_mask_draw_region(Mask *mask, ARegion *ar,
}
/* draw! */
- draw_masklays(mask, draw_flag, draw_type, width, height);
+ draw_masklays(C, mask, draw_flag, draw_type, width, height);
if (do_post_draw) {
ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
diff --git a/source/blender/editors/mask/mask_edit.c b/source/blender/editors/mask/mask_edit.c
index 39a19bdaa5f..18384ad9de4 100644
--- a/source/blender/editors/mask/mask_edit.c
+++ b/source/blender/editors/mask/mask_edit.c
@@ -436,8 +436,8 @@ void ED_keymap_mask(wmKeyConfig *keyconf)
ED_keymap_proportional_maskmode(keyconf, keymap);
/* geometry */
- WM_keymap_add_item(keymap, "MASK_OT_add_vertex_slide", LEFTMOUSE, KM_PRESS, KM_CTRL, 0);
- WM_keymap_add_item(keymap, "MASK_OT_add_feather_vertex_slide", LEFTMOUSE, KM_PRESS, KM_SHIFT, 0);
+ WM_keymap_add_item(keymap, "MASK_OT_add_vertex_slide", ACTIONMOUSE, KM_PRESS, KM_CTRL, 0);
+ WM_keymap_add_item(keymap, "MASK_OT_add_feather_vertex_slide", ACTIONMOUSE, KM_PRESS, KM_SHIFT, 0);
WM_keymap_add_item(keymap, "MASK_OT_delete", XKEY, KM_PRESS, 0, 0);
WM_keymap_add_item(keymap, "MASK_OT_delete", DELKEY, KM_PRESS, 0, 0);
@@ -486,7 +486,7 @@ void ED_keymap_mask(wmKeyConfig *keyconf)
/* shape */
WM_keymap_add_item(keymap, "MASK_OT_cyclic_toggle", CKEY, KM_PRESS, KM_ALT, 0);
- WM_keymap_add_item(keymap, "MASK_OT_slide_point", LEFTMOUSE, KM_PRESS, 0, 0);
+ WM_keymap_add_item(keymap, "MASK_OT_slide_point", ACTIONMOUSE, KM_PRESS, 0, 0);
WM_keymap_add_item(keymap, "MASK_OT_handle_type_set", VKEY, KM_PRESS, 0, 0);
WM_keymap_add_item(keymap, "MASK_OT_normals_make_consistent", NKEY, KM_PRESS, KM_CTRL, 0);
// WM_keymap_add_item(keymap, "MASK_OT_feather_weight_clear", SKEY, KM_PRESS, KM_ALT, 0);
diff --git a/source/blender/editors/mask/mask_intern.h b/source/blender/editors/mask/mask_intern.h
index ffd4afca182..fcfcfb237e9 100644
--- a/source/blender/editors/mask/mask_intern.h
+++ b/source/blender/editors/mask/mask_intern.h
@@ -33,6 +33,7 @@
#define __MASK_INTERN_H__
struct bContext;
+struct Mask;
struct wmEvent;
struct wmOperatorType;
@@ -43,6 +44,8 @@ void MASK_OT_add_vertex(struct wmOperatorType *ot);
void MASK_OT_add_feather_vertex(struct wmOperatorType *ot);
/* mask_ops.c */
+struct Mask *ED_mask_new(struct bContext *C, const char *name);
+
void MASK_OT_new(struct wmOperatorType *ot);
void MASK_OT_layer_new(struct wmOperatorType *ot);
void MASK_OT_layer_remove(struct wmOperatorType *ot);
diff --git a/source/blender/editors/mask/mask_ops.c b/source/blender/editors/mask/mask_ops.c
index 88fbb91edfb..35f85f3faee 100644
--- a/source/blender/editors/mask/mask_ops.c
+++ b/source/blender/editors/mask/mask_ops.c
@@ -258,13 +258,10 @@ int ED_mask_feather_find_nearest(const bContext *C, Mask *mask, float normal_co[
/******************** create new mask *********************/
-static int mask_new_exec(bContext *C, wmOperator *op)
+Mask *ED_mask_new(bContext *C, const char *name)
{
ScrArea *sa = CTX_wm_area(C);
Mask *mask;
- char name[MAX_ID_NAME - 2];
-
- RNA_string_get(op->ptr, "name", name);
mask = BKE_mask_new(name);
@@ -290,6 +287,17 @@ static int mask_new_exec(bContext *C, wmOperator *op)
}
}
+ return mask;
+}
+
+static int mask_new_exec(bContext *C, wmOperator *op)
+{
+ char name[MAX_ID_NAME - 2];
+
+ RNA_string_get(op->ptr, "name", name);
+
+ ED_mask_new(C, name);
+
return OPERATOR_FINISHED;
}
@@ -483,15 +491,15 @@ static void *slide_point_customdata(bContext *C, wmOperator *op, wmEvent *event)
customdata->uw = uw;
if (uw) {
- float co[2];
+ float co_uw[2];
float weight_scalar = BKE_mask_point_weight_scalar(spline, point, uw->u);
customdata->weight = uw->w;
customdata->weight_scalar = weight_scalar;
- BKE_mask_point_segment_co(spline, point, uw->u, co);
+ BKE_mask_point_segment_co(spline, point, uw->u, co_uw);
BKE_mask_point_normal(spline, point, uw->u, customdata->no);
- madd_v2_v2v2fl(customdata->feather, co, customdata->no, uw->w * weight_scalar);
+ madd_v2_v2v2fl(customdata->feather, co_uw, customdata->no, uw->w * weight_scalar);
}
else {
BezTriple *bezt = &point->bezt;
diff --git a/source/blender/editors/mask/mask_select.c b/source/blender/editors/mask/mask_select.c
index ace427f65ab..cd1a47754f8 100644
--- a/source/blender/editors/mask/mask_select.c
+++ b/source/blender/editors/mask/mask_select.c
@@ -34,6 +34,7 @@
#include "BLI_utildefines.h"
#include "BLI_rect.h"
#include "BLI_lasso.h"
+#include "BLI_math.h"
#include "BKE_context.h"
#include "BKE_mask.h"
@@ -148,7 +149,7 @@ void ED_mask_select_toggle_all(Mask *mask, int action)
}
if (action == SEL_INVERT) {
- /* we don't have generic functons for this, its restricted to this operator
+ /* we don't have generic functions for this, its restricted to this operator
* if one day we need to re-use such functionality, they can be split out */
MaskSpline *spline;
@@ -485,7 +486,7 @@ void MASK_OT_select_border(wmOperatorType *ot)
WM_operator_properties_gesture_border(ot, TRUE);
}
-static int do_lasso_select_mask(bContext *C, int mcords[][2], short moves, short select)
+static int do_lasso_select_mask(bContext *C, const int mcords[][2], short moves, short select)
{
ScrArea *sa = CTX_wm_area(C);
ARegion *ar = CTX_wm_region(C);
@@ -549,7 +550,7 @@ static int do_lasso_select_mask(bContext *C, int mcords[][2], short moves, short
static int clip_lasso_select_exec(bContext *C, wmOperator *op)
{
int mcords_tot;
- int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
+ const int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
if (mcords) {
short select;
@@ -557,7 +558,7 @@ static int clip_lasso_select_exec(bContext *C, wmOperator *op)
select = !RNA_boolean_get(op->ptr, "deselect");
do_lasso_select_mask(C, mcords, mcords_tot, select);
- MEM_freeN(mcords);
+ MEM_freeN((void *)mcords);
return OPERATOR_FINISHED;
}
@@ -622,7 +623,7 @@ static int circle_select_exec(bContext *C, wmOperator *op)
/* compute ellipse and position in unified coordinates */
ED_mask_get_size(sa, &width, &height);
ED_mask_zoom(sa, ar, &zoomx, &zoomy);
- width = height = MAX2(width, height);
+ width = height = max_ii(width, height);
ellipse[0] = width * zoomx / radius;
ellipse[1] = height * zoomy / radius;
diff --git a/source/blender/editors/mesh/CMakeLists.txt b/source/blender/editors/mesh/CMakeLists.txt
index 246c323213c..c51d2cfb2e5 100644
--- a/source/blender/editors/mesh/CMakeLists.txt
+++ b/source/blender/editors/mesh/CMakeLists.txt
@@ -21,6 +21,7 @@
set(INC
../include
../uvedit
+ ../../blenfont
../../blenkernel
../../blenlib
../../blenloader
@@ -68,4 +69,12 @@ if(WITH_GAMEENGINE)
)
endif()
+if(WITH_INTERNATIONAL)
+ add_definitions(-DWITH_INTERNATIONAL)
+endif()
+
+if(WITH_BULLET)
+ add_definitions(-DWITH_BULLET)
+endif()
+
blender_add_lib(bf_editor_mesh "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/editors/mesh/SConscript b/source/blender/editors/mesh/SConscript
index b3aba977b21..91ffdc91685 100644
--- a/source/blender/editors/mesh/SConscript
+++ b/source/blender/editors/mesh/SConscript
@@ -5,7 +5,7 @@ sources = env.Glob('*.c')
defs = []
-incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
+incs = '../include ../../blenfont ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
incs += ' ../../windowmanager #/intern/guardedalloc #/extern/glew/include'
incs += ' ../../gpu ../../blenloader'
incs += ' ../../makesrna ../../render/extern/include #/intern/elbeem/extern'
@@ -24,4 +24,10 @@ if env['WITH_BF_GAMEENGINE']:
else:
sources.remove('mesh_navmesh.c')
+if env['WITH_BF_INTERNATIONAL']:
+ defs.append('WITH_INTERNATIONAL')
+
+if env['WITH_BF_BULLET']:
+ defs.append('WITH_BULLET')
+
env.BlenderLib ( 'bf_editors_mesh', sources, Split(incs), defs, libtype=['core'], priority=[45] )
diff --git a/source/blender/editors/mesh/editface.c b/source/blender/editors/mesh/editface.c
index 94e10b53b29..4350c005f95 100644
--- a/source/blender/editors/mesh/editface.c
+++ b/source/blender/editors/mesh/editface.c
@@ -85,7 +85,7 @@ void paintface_flush_flags(Object *ob)
* - Final derived polys => Final derived tessfaces
*/
- if ((index_array = CustomData_get_layer(&me->fdata, CD_POLYINDEX))) {
+ if ((index_array = CustomData_get_layer(&me->fdata, CD_ORIGINDEX))) {
faces = me->mface;
totface = me->totface;
@@ -109,7 +109,7 @@ void paintface_flush_flags(Object *ob)
}
}
- if ((index_array = CustomData_get_layer(&dm->faceData, CD_POLYINDEX))) {
+ if ((index_array = CustomData_get_layer(&dm->faceData, CD_ORIGINDEX))) {
polys = dm->getPolyArray(dm);
faces = dm->getTessFaceArray(dm);
totface = dm->getNumTessFaces(dm);
@@ -214,7 +214,9 @@ static void select_linked_tfaces_with_seams(int mode, Mesh *me, unsigned int ind
/* fill array by selection */
mp = me->mpoly;
for (a = 0; a < me->totpoly; a++, mp++) {
- if (mp->flag & ME_HIDE) ;
+ if (mp->flag & ME_HIDE) {
+ /* pass */
+ }
else if (mp->flag & ME_FACE_SEL) {
hash_add_face(ehash, mp, me->mloop + mp->loopstart);
linkflag[a] = 1;
@@ -426,7 +428,7 @@ void seam_mark_clear_tface(Scene *scene, short mode)
if (me == 0 || me->totpoly == 0) return;
if (mode == 0)
- mode = pupmenu("Seams%t|Mark Border Seam %x1|Clear Seam %x2");
+ mode = pupmenu("Seams %t|Mark Border Seam %x1|Clear Seam %x2");
if (mode != 1 && mode != 2)
return;
@@ -533,8 +535,8 @@ int do_paintface_box_select(ViewContext *vc, rcti *rect, int select, int extend)
unsigned int *rt;
char *selar;
int a, index;
- int sx = BLI_RCT_SIZE_X(rect) + 1;
- int sy = BLI_RCT_SIZE_Y(rect) + 1;
+ int sx = BLI_rcti_size_x(rect) + 1;
+ int sy = BLI_rcti_size_y(rect) + 1;
me = BKE_mesh_from_object(ob);
@@ -572,7 +574,9 @@ int do_paintface_box_select(ViewContext *vc, rcti *rect, int select, int extend)
mpoly = me->mpoly;
for (a = 1; a <= me->totpoly; a++, mpoly++) {
if (selar[a]) {
- if (mpoly->flag & ME_HIDE) ;
+ if (mpoly->flag & ME_HIDE) {
+ /* pass */
+ }
else {
if (select) mpoly->flag |= ME_FACE_SEL;
else mpoly->flag &= ~ME_FACE_SEL;
diff --git a/source/blender/editors/mesh/editmesh_add.c b/source/blender/editors/mesh/editmesh_add.c
index 8b032bb1a3d..70b359d3e28 100644
--- a/source/blender/editors/mesh/editmesh_add.c
+++ b/source/blender/editors/mesh/editmesh_add.c
@@ -55,16 +55,16 @@
/* ********* add primitive operators ************* */
-static void make_prim_init(bContext *C, const char *idname,
- float *dia, float mat[][4],
- int *state, const float loc[3], const float rot[3], const unsigned int layer)
+static Object *make_prim_init(bContext *C, const char *idname,
+ float *dia, float mat[][4],
+ int *state, const float loc[3], const float rot[3], const unsigned int layer)
{
Object *obedit = CTX_data_edit_object(C);
*state = 0;
if (obedit == NULL || obedit->type != OB_MESH) {
obedit = ED_object_add_type(C, OB_MESH, loc, rot, FALSE, layer);
-
+
rename_id((ID *)obedit, idname);
rename_id((ID *)obedit->data, idname);
@@ -73,12 +73,13 @@ static void make_prim_init(bContext *C, const char *idname,
*state = 1;
}
- *dia = ED_object_new_primitive_matrix(C, obedit, loc, rot, mat);
+ *dia = ED_object_new_primitive_matrix(C, obedit, loc, rot, mat, FALSE);
+
+ return obedit;
}
-static void make_prim_finish(bContext *C, int *state, int enter_editmode)
+static void make_prim_finish(bContext *C, Object *obedit, int *state, int enter_editmode)
{
- Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BMEdit_FromObject(obedit);
/* Primitive has all verts selected, use vert select flush
@@ -102,11 +103,9 @@ static int add_primitive_plane_exec(bContext *C, wmOperator *op)
int enter_editmode;
int state;
unsigned int layer;
-
- ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
- make_prim_init(C, "Plane", &dia, mat, &state, loc, rot, layer);
- obedit = CTX_data_edit_object(C);
+ ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
+ obedit = make_prim_init(C, "Plane", &dia, mat, &state, loc, rot, layer);
em = BMEdit_FromObject(obedit);
if (!EDBM_op_call_and_selectf(em, op, "vertout",
@@ -115,7 +114,7 @@ static int add_primitive_plane_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
- make_prim_finish(C, &state, enter_editmode);
+ make_prim_finish(C, obedit, &state, enter_editmode);
return OPERATOR_FINISHED;
}
@@ -126,12 +125,11 @@ void MESH_OT_primitive_plane_add(wmOperatorType *ot)
ot->name = "Add Plane";
ot->description = "Construct a filled planar mesh with 4 vertices";
ot->idname = "MESH_OT_primitive_plane_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_plane_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -146,19 +144,17 @@ static int add_primitive_cube_exec(bContext *C, wmOperator *op)
int enter_editmode;
int state;
unsigned int layer;
-
- ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
- make_prim_init(C, "Cube", &dia, mat, &state, loc, rot, layer);
- obedit = CTX_data_edit_object(C);
+ ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
+ obedit = make_prim_init(C, "Cube", &dia, mat, &state, loc, rot, layer);
em = BMEdit_FromObject(obedit);
if (!EDBM_op_call_and_selectf(em, op, "vertout", "create_cube mat=%m4 size=%f", mat, dia * 2.0f)) {
return OPERATOR_CANCELLED;
}
-
+
/* BMESH_TODO make plane side this: M_SQRT2 - plane (diameter of 1.41 makes it unit size) */
- make_prim_finish(C, &state, enter_editmode);
+ make_prim_finish(C, obedit, &state, enter_editmode);
return OPERATOR_FINISHED;
}
@@ -169,12 +165,11 @@ void MESH_OT_primitive_cube_add(wmOperatorType *ot)
ot->name = "Add Cube";
ot->description = "Construct a cube mesh";
ot->idname = "MESH_OT_primitive_cube_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_cube_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -195,26 +190,24 @@ static int add_primitive_circle_exec(bContext *C, wmOperator *op)
int enter_editmode;
int state, cap_end, cap_tri;
unsigned int layer;
-
+
cap_end = RNA_enum_get(op->ptr, "fill_type");
cap_tri = (cap_end == 2);
-
- ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
- make_prim_init(C, "Circle", &dia, mat, &state, loc, rot, layer);
- obedit = CTX_data_edit_object(C);
+ ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
+ obedit = make_prim_init(C, "Circle", &dia, mat, &state, loc, rot, layer);
em = BMEdit_FromObject(obedit);
if (!EDBM_op_call_and_selectf(em, op, "vertout",
"create_circle segments=%i diameter=%f cap_ends=%b cap_tris=%b mat=%m4",
- RNA_int_get(op->ptr, "vertices"), RNA_float_get(op->ptr, "radius"),
+ RNA_int_get(op->ptr, "vertices"), RNA_float_get(op->ptr, "radius") * dia,
cap_end, cap_tri, mat))
{
return OPERATOR_CANCELLED;
}
-
- make_prim_finish(C, &state, enter_editmode);
-
+
+ make_prim_finish(C, obedit, &state, enter_editmode);
+
return OPERATOR_FINISHED;
}
@@ -226,15 +219,14 @@ void MESH_OT_primitive_circle_add(wmOperatorType *ot)
ot->name = "Add Circle";
ot->description = "Construct a circle mesh";
ot->idname = "MESH_OT_primitive_circle_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_circle_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* props */
RNA_def_int(ot->srna, "vertices", 32, 3, INT_MAX, "Vertices", "", 3, 500);
prop = RNA_def_float(ot->srna, "radius", 1.0f, 0.0, FLT_MAX, "Radius", "", 0.001, 100.00);
@@ -252,30 +244,28 @@ static int add_primitive_cylinder_exec(bContext *C, wmOperator *op)
int enter_editmode;
int state, cap_end, cap_tri;
unsigned int layer;
-
+
cap_end = RNA_enum_get(op->ptr, "end_fill_type");
cap_tri = (cap_end == 2);
-
- ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
- make_prim_init(C, "Cylinder", &dia, mat, &state, loc, rot, layer);
- obedit = CTX_data_edit_object(C);
+ ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
+ obedit = make_prim_init(C, "Cylinder", &dia, mat, &state, loc, rot, layer);
em = BMEdit_FromObject(obedit);
if (!EDBM_op_call_and_selectf(
em, op, "vertout",
"create_cone segments=%i diameter1=%f diameter2=%f cap_ends=%b cap_tris=%b depth=%f mat=%m4",
RNA_int_get(op->ptr, "vertices"),
- RNA_float_get(op->ptr, "radius"),
- RNA_float_get(op->ptr, "radius"),
+ RNA_float_get(op->ptr, "radius") * dia,
+ RNA_float_get(op->ptr, "radius") * dia,
cap_end, cap_tri,
- RNA_float_get(op->ptr, "depth"), mat))
+ RNA_float_get(op->ptr, "depth") * dia, mat))
{
return OPERATOR_CANCELLED;
}
-
- make_prim_finish(C, &state, enter_editmode);
-
+
+ make_prim_finish(C, obedit, &state, enter_editmode);
+
return OPERATOR_FINISHED;
}
@@ -287,15 +277,14 @@ void MESH_OT_primitive_cylinder_add(wmOperatorType *ot)
ot->name = "Add Cylinder";
ot->description = "Construct a cylinder mesh";
ot->idname = "MESH_OT_primitive_cylinder_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_cylinder_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* props */
RNA_def_int(ot->srna, "vertices", 32, 3, INT_MAX, "Vertices", "", 3, 500);
prop = RNA_def_float(ot->srna, "radius", 1.0f, 0.0, FLT_MAX, "Radius", "", 0.001, 100.00);
@@ -315,26 +304,24 @@ static int add_primitive_cone_exec(bContext *C, wmOperator *op)
int enter_editmode;
int state, cap_end, cap_tri;
unsigned int layer;
-
+
cap_end = RNA_enum_get(op->ptr, "end_fill_type");
cap_tri = (cap_end == 2);
-
- ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
- make_prim_init(C, "Cone", &dia, mat, &state, loc, rot, layer);
- obedit = CTX_data_edit_object(C);
+ ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
+ obedit = make_prim_init(C, "Cone", &dia, mat, &state, loc, rot, layer);
em = BMEdit_FromObject(obedit);
if (!EDBM_op_call_and_selectf(
em, op, "vertout",
"create_cone segments=%i diameter1=%f diameter2=%f cap_ends=%b cap_tris=%b depth=%f mat=%m4",
- RNA_int_get(op->ptr, "vertices"), RNA_float_get(op->ptr, "radius1"),
- RNA_float_get(op->ptr, "radius2"), cap_end, cap_tri, RNA_float_get(op->ptr, "depth"), mat))
+ RNA_int_get(op->ptr, "vertices"), RNA_float_get(op->ptr, "radius1") * dia,
+ RNA_float_get(op->ptr, "radius2") * dia, cap_end, cap_tri, RNA_float_get(op->ptr, "depth") * dia, mat))
{
return OPERATOR_CANCELLED;
}
-
- make_prim_finish(C, &state, enter_editmode);
+
+ make_prim_finish(C, obedit, &state, enter_editmode);
return OPERATOR_FINISHED;
}
@@ -347,15 +334,14 @@ void MESH_OT_primitive_cone_add(wmOperatorType *ot)
ot->name = "Add Cone";
ot->description = "Construct a conic mesh";
ot->idname = "MESH_OT_primitive_cone_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_cone_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* props */
RNA_def_int(ot->srna, "vertices", 32, 3, INT_MAX, "Vertices", "", 3, 500);
prop = RNA_def_float(ot->srna, "radius1", 1.0f, 0.0, FLT_MAX, "Radius 1", "", 0.001, 100.00);
@@ -377,11 +363,9 @@ static int add_primitive_grid_exec(bContext *C, wmOperator *op)
int enter_editmode;
int state;
unsigned int layer;
-
- ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
- make_prim_init(C, "Grid", &dia, mat, &state, loc, rot, layer);
- obedit = CTX_data_edit_object(C);
+ ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
+ obedit = make_prim_init(C, "Grid", &dia, mat, &state, loc, rot, layer);
em = BMEdit_FromObject(obedit);
if (!EDBM_op_call_and_selectf(em, op, "vertout",
@@ -392,8 +376,9 @@ static int add_primitive_grid_exec(bContext *C, wmOperator *op)
{
return OPERATOR_CANCELLED;
}
-
- make_prim_finish(C, &state, enter_editmode);
+
+ make_prim_finish(C, obedit, &state, enter_editmode);
+
return OPERATOR_FINISHED;
}
@@ -405,15 +390,14 @@ void MESH_OT_primitive_grid_add(wmOperatorType *ot)
ot->name = "Add Grid";
ot->description = "Construct a grid mesh";
ot->idname = "MESH_OT_primitive_grid_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_grid_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* props */
RNA_def_int(ot->srna, "x_subdivisions", 10, 3, INT_MAX, "X Subdivisions", "", 3, 1000);
RNA_def_int(ot->srna, "y_subdivisions", 10, 3, INT_MAX, "Y Subdivisions", "", 3, 1000);
@@ -431,21 +415,24 @@ static int add_primitive_monkey_exec(bContext *C, wmOperator *op)
int enter_editmode;
int state, view_aligned;
unsigned int layer;
-
+
ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, &view_aligned);
if (!view_aligned)
rot[0] += (float)M_PI / 2.0f;
-
- make_prim_init(C, "Monkey", &dia, mat, &state, loc, rot, layer);
- obedit = CTX_data_edit_object(C);
+ obedit = make_prim_init(C, "Monkey", &dia, mat, &state, loc, rot, layer);
+ mat[0][0] *= dia;
+ mat[1][1] *= dia;
+ mat[2][2] *= dia;
+
em = BMEdit_FromObject(obedit);
if (!EDBM_op_call_and_selectf(em, op, "vertout", "create_monkey mat=%m4", mat)) {
return OPERATOR_CANCELLED;
}
-
- make_prim_finish(C, &state, enter_editmode);
+
+ make_prim_finish(C, obedit, &state, enter_editmode);
+
return OPERATOR_FINISHED;
}
@@ -455,12 +442,11 @@ void MESH_OT_primitive_monkey_add(wmOperatorType *ot)
ot->name = "Add Monkey";
ot->description = "Construct a Suzanne mesh";
ot->idname = "MESH_OT_primitive_monkey_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_monkey_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -475,24 +461,22 @@ static int add_primitive_uvsphere_exec(bContext *C, wmOperator *op)
int enter_editmode;
int state;
unsigned int layer;
-
- ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
- make_prim_init(C, "Sphere", &dia, mat, &state, loc, rot, layer);
- obedit = CTX_data_edit_object(C);
+ ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
+ obedit = make_prim_init(C, "Sphere", &dia, mat, &state, loc, rot, layer);
em = BMEdit_FromObject(obedit);
if (!EDBM_op_call_and_selectf(em, op, "vertout",
"create_uvsphere segments=%i revolutions=%i diameter=%f mat=%m4",
RNA_int_get(op->ptr, "segments"), RNA_int_get(op->ptr, "ring_count"),
- RNA_float_get(op->ptr, "size"), mat))
+ RNA_float_get(op->ptr, "size") * dia, mat))
{
return OPERATOR_CANCELLED;
}
-
- make_prim_finish(C, &state, enter_editmode);
- return OPERATOR_FINISHED;
+ make_prim_finish(C, obedit, &state, enter_editmode);
+
+ return OPERATOR_FINISHED;
}
void MESH_OT_primitive_uv_sphere_add(wmOperatorType *ot)
@@ -503,15 +487,14 @@ void MESH_OT_primitive_uv_sphere_add(wmOperatorType *ot)
ot->name = "Add UV Sphere";
ot->description = "Construct a UV sphere mesh";
ot->idname = "MESH_OT_primitive_uv_sphere_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_uvsphere_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* props */
RNA_def_int(ot->srna, "segments", 32, 3, INT_MAX, "Segments", "", 3, 500);
RNA_def_int(ot->srna, "ring_count", 16, 3, INT_MAX, "Rings", "", 3, 500);
@@ -529,25 +512,23 @@ static int add_primitive_icosphere_exec(bContext *C, wmOperator *op)
int enter_editmode;
int state;
unsigned int layer;
-
- ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
- make_prim_init(C, "Icosphere", &dia, mat, &state, loc, rot, layer);
- obedit = CTX_data_edit_object(C);
+ ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL);
+ obedit = make_prim_init(C, "Icosphere", &dia, mat, &state, loc, rot, layer);
em = BMEdit_FromObject(obedit);
if (!EDBM_op_call_and_selectf(
em, op, "vertout",
"create_icosphere subdivisions=%i diameter=%f mat=%m4",
RNA_int_get(op->ptr, "subdivisions"),
- RNA_float_get(op->ptr, "size"), mat))
+ RNA_float_get(op->ptr, "size") * dia, mat))
{
return OPERATOR_CANCELLED;
}
-
- make_prim_finish(C, &state, enter_editmode);
- return OPERATOR_FINISHED;
+ make_prim_finish(C, obedit, &state, enter_editmode);
+
+ return OPERATOR_FINISHED;
}
void MESH_OT_primitive_ico_sphere_add(wmOperatorType *ot)
@@ -558,15 +539,14 @@ void MESH_OT_primitive_ico_sphere_add(wmOperatorType *ot)
ot->name = "Add Ico Sphere";
ot->description = "Construct an Icosphere mesh";
ot->idname = "MESH_OT_primitive_ico_sphere_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = add_primitive_icosphere_exec;
ot->poll = ED_operator_scene_editable;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* props */
RNA_def_int(ot->srna, "subdivisions", 2, 1, INT_MAX, "Subdivisions", "", 1, 8);
prop = RNA_def_float(ot->srna, "size", 1.0f, 0.0f, FLT_MAX, "Size", "", 0.001f, 100.00);
diff --git a/source/blender/editors/mesh/editmesh_bvh.c b/source/blender/editors/mesh/editmesh_bvh.c
index 0b7d396b696..468d0d8d8c6 100644
--- a/source/blender/editors/mesh/editmesh_bvh.c
+++ b/source/blender/editors/mesh/editmesh_bvh.c
@@ -309,7 +309,7 @@ static void vertsearchcallback(void *userdata, int index, const float *UNUSED(co
}
}
-BMVert *BMBVH_FindClosestVert(BMBVHTree *tree, const float co[3], float maxdist)
+BMVert *BMBVH_FindClosestVert(BMBVHTree *tree, const float co[3], const float maxdist)
{
BVHTreeNearest hit;
@@ -325,7 +325,7 @@ BMVert *BMBVH_FindClosestVert(BMBVHTree *tree, const float co[3], float maxdist)
float dist, curdist = tree->maxdist, v[3];
int cur = 0, i;
- maxdist = tree->maxdist;
+ /* maxdist = tree->maxdist; */ /* UNUSED */
for (i = 0; i < 3; i++) {
sub_v3_v3v3(v, hit.co, ls[i]->v->co);
@@ -371,9 +371,9 @@ int BMBVH_VertVisible(BMBVHTree *tree, BMEdge *e, RegionView3D *r3d)
}
#endif
-static BMFace *edge_ray_cast(BMBVHTree *tree, const float co[3], const float dir[3], float *hitout, BMEdge *e)
+static BMFace *edge_ray_cast(BMBVHTree *tree, const float co[3], const float dir[3], float *r_hitout, BMEdge *e)
{
- BMFace *f = BMBVH_RayCast(tree, co, dir, hitout, NULL);
+ BMFace *f = BMBVH_RayCast(tree, co, dir, r_hitout, NULL);
if (f && BM_edge_in_face(f, e))
return NULL;
@@ -392,7 +392,7 @@ static void scale_point(float c1[3], const float p[3], const float s)
int BMBVH_EdgeVisible(BMBVHTree *tree, BMEdge *e, ARegion *ar, View3D *v3d, Object *obedit)
{
BMFace *f;
- float co1[3], co2[3], co3[3], dir1[4], dir2[4], dir3[4];
+ float co1[3], co2[3], co3[3], dir1[3], dir2[3], dir3[3];
float origin[3], invmat[4][4];
float epsilon = 0.01f;
float end[3];
@@ -405,8 +405,7 @@ int BMBVH_EdgeVisible(BMBVHTree *tree, BMEdge *e, ARegion *ar, View3D *v3d, Obje
mul_m4_v3(invmat, origin);
copy_v3_v3(co1, e->v1->co);
- add_v3_v3v3(co2, e->v1->co, e->v2->co);
- mul_v3_fl(co2, 0.5f);
+ mid_v3_v3v3(co2, e->v1->co, e->v2->co);
copy_v3_v3(co3, e->v2->co);
scale_point(co1, co2, 0.99);
diff --git a/source/blender/editors/mesh/editmesh_knife.c b/source/blender/editors/mesh/editmesh_knife.c
index 7ecfb712c18..82447cc0168 100644
--- a/source/blender/editors/mesh/editmesh_knife.c
+++ b/source/blender/editors/mesh/editmesh_knife.c
@@ -29,7 +29,9 @@
* \ingroup edmesh
*/
-#define _USE_MATH_DEFINES
+#ifdef _MSC_VER
+# define _USE_MATH_DEFINES
+#endif
#include "MEM_guardedalloc.h"
@@ -71,6 +73,9 @@
#define KMAXDIST 10 /* max mouse distance from edge before not detecting it */
+#define KNIFE_FLT_EPS 0.00001f
+#define KNIFE_FLT_EPS_SQUARED (KNIFE_FLT_EPS * KNIFE_FLT_EPS)
+
typedef struct KnifeColors {
unsigned char line[3];
unsigned char edge[3];
@@ -176,6 +181,7 @@ typedef struct KnifeTool_OpData {
char select_result; /* set on initialization */
short is_ortho;
+ float ortho_extent;
float clipsta, clipend;
enum {
@@ -222,7 +228,7 @@ static void knife_update_header(bContext *C, KnifeTool_OpData *kcd)
static void knife_project_v3(KnifeTool_OpData *kcd, const float co[3], float sco[3])
{
- ED_view3d_project_float_v3(kcd->ar, co, sco, kcd->projmat);
+ ED_view3d_project_float_v3_m4(kcd->ar, co, sco, kcd->projmat);
}
static void knife_pos_data_clear(KnifePosData *kpd)
@@ -428,7 +434,7 @@ static KnifeVert *knife_split_edge(KnifeTool_OpData *kcd, KnifeEdge *kfe, float
float perc, cageco[3], l12;
l12 = len_v3v3(kfe->v1->co, kfe->v2->co);
- if (l12 < FLT_EPSILON * 80) {
+ if (l12 < KNIFE_FLT_EPS) {
copy_v3_v3(cageco, kfe->v1->cageco);
}
else {
@@ -444,8 +450,8 @@ static KnifeVert *knife_split_edge(KnifeTool_OpData *kcd, KnifeEdge *kfe, float
}
else {
/* kfe cuts across an existing face.
- If v1 and v2 are in multiple faces together (e.g., if they
- are in doubled polys) then this arbitrarily chooses one of them */
+ * If v1 and v2 are in multiple faces together (e.g., if they
+ * are in doubled polys) then this arbitrarily chooses one of them */
f = knife_find_common_face(&kfe->v1->faces, &kfe->v2->faces);
if (f)
knife_append_list(kcd, &newkfe->v2->faces, f);
@@ -564,7 +570,9 @@ static int find_connected_linehit(KnifeTool_OpData *kcd, int testi, BMFace *f, i
if (testi >= 0 && testi < kcd->totlinehit) {
if (knife_find_common_face(&kcd->linehits[testi].kfe->faces,
&kcd->linehits[i].kfe->faces))
+ {
return i;
+ }
}
else if (f) {
if (find_ref(&kcd->linehits[i].kfe->faces, f))
@@ -585,7 +593,7 @@ static void knife_sort_linehits(KnifeTool_OpData *kcd)
* successor faces connected to the linehits at either end of the range */
for (i = 0; i < kcd->totlinehit - 1; i = nexti) {
for (j = i + 1; j < kcd->totlinehit; j++) {
- if (fabsf(kcd->linehits[j].l - kcd->linehits[i].l) > 80 * FLT_EPSILON)
+ if (fabsf(kcd->linehits[j].l - kcd->linehits[i].l) > KNIFE_FLT_EPS)
break;
}
nexti = j;
@@ -793,7 +801,7 @@ static void knife_add_cut(KnifeTool_OpData *kcd)
for (i = 0; i < kcd->totlinehit; i++, (lastlh = lh), lh++) {
BMFace *f = lastlh ? lastlh->f : lh->f;
- if (lastlh && len_v3v3(lastlh->hit, lh->hit) == 0.0f) {
+ if (lastlh && len_squared_v3v3(lastlh->hit, lh->hit) == 0.0f) {
if (!firstlh)
firstlh = lastlh;
continue;
@@ -812,13 +820,13 @@ static void knife_add_cut(KnifeTool_OpData *kcd)
lastlh = firstlh = NULL;
}
- if (len_v3v3(kcd->prev.cage, lh->realhit) < FLT_EPSILON * 80)
+ if (len_squared_v3v3(kcd->prev.cage, lh->realhit) < KNIFE_FLT_EPS_SQUARED)
continue;
- if (len_v3v3(kcd->curr.cage, lh->realhit) < FLT_EPSILON * 80)
+ if (len_squared_v3v3(kcd->curr.cage, lh->realhit) < KNIFE_FLT_EPS_SQUARED)
continue;
/* first linehit may be down face parallel to view */
- if (!lastlh && fabsf(lh->l) < FLT_EPSILON * 80)
+ if (!lastlh && fabsf(lh->l) < KNIFE_FLT_EPS)
continue;
if (kcd->prev.is_space) {
@@ -839,7 +847,7 @@ static void knife_add_cut(KnifeTool_OpData *kcd)
copy_v3_v3(kcd->curr.cage, lh->cagehit);
/* don't draw edges down faces parallel to view */
- if (lastlh && fabsf(lastlh->l - lh->l) < FLT_EPSILON * 80) {
+ if (lastlh && fabsf(lastlh->l - lh->l) < KNIFE_FLT_EPS) {
kcd->prev = kcd->curr;
continue;
}
@@ -1040,6 +1048,9 @@ static void knifetool_draw(const bContext *C, ARegion *UNUSED(ar), void *arg)
}
if (kcd->totlinehit > 0) {
+ const float vthresh4 = kcd->vthresh / 4.0f;
+ const float vthresh4_squared = vthresh4 * vthresh4;
+
BMEdgeHit *lh;
int i;
@@ -1058,12 +1069,12 @@ static void knifetool_draw(const bContext *C, ARegion *UNUSED(ar), void *arg)
knife_project_v3(kcd, lh->kfe->v2->cageco, sv2);
knife_project_v3(kcd, lh->cagehit, lh->schit);
- if (len_v2v2(lh->schit, sv1) < kcd->vthresh / 4.0f) {
+ if (len_squared_v2v2(lh->schit, sv1) < vthresh4_squared) {
copy_v3_v3(lh->cagehit, lh->kfe->v1->cageco);
glVertex3fv(lh->cagehit);
lh->v = lh->kfe->v1;
}
- else if (len_v2v2(lh->schit, sv2) < kcd->vthresh / 4.0f) {
+ else if (len_squared_v2v2(lh->schit, sv2) < vthresh4_squared) {
copy_v3_v3(lh->cagehit, lh->kfe->v2->cageco);
glVertex3fv(lh->cagehit);
lh->v = lh->kfe->v2;
@@ -1132,11 +1143,11 @@ static void knifetool_draw(const bContext *C, ARegion *UNUSED(ar), void *arg)
static float len_v3_tri_side_max(const float v1[3], const float v2[3], const float v3[3])
{
- const float s1 = len_v3v3(v1, v2);
- const float s2 = len_v3v3(v2, v3);
- const float s3 = len_v3v3(v3, v1);
+ const float s1 = len_squared_v3v3(v1, v2);
+ const float s2 = len_squared_v3v3(v2, v3);
+ const float s3 = len_squared_v3v3(v3, v1);
- return MAX3(s1, s2, s3);
+ return sqrtf(MAX3(s1, s2, s3));
}
static BMEdgeHit *knife_edge_tri_isect(KnifeTool_OpData *kcd, BMBVHTree *bmtree,
@@ -1154,7 +1165,7 @@ static BMEdgeHit *knife_edge_tri_isect(KnifeTool_OpData *kcd, BMBVHTree *bmtree,
/* for comparing distances, error of intersection depends on triangle scale.
* need to scale down before squaring for accurate comparison */
- const float depsilon = 50 *FLT_EPSILON *len_v3_tri_side_max(v1, v2, v3);
+ const float depsilon = (FLT_EPSILON / 2.0f) * len_v3_tri_side_max(v1, v2, v3);
const float depsilon_squared = depsilon * depsilon;
copy_v3_v3(cos + 0, v1);
@@ -1203,7 +1214,7 @@ static BMEdgeHit *knife_edge_tri_isect(KnifeTool_OpData *kcd, BMBVHTree *bmtree,
}
knife_project_v3(kcd, p, sp);
- view3d_unproject(mats, view, sp[0], sp[1], 0.0f);
+ ED_view3d_unproject(mats, view, sp[0], sp[1], 0.0f);
mul_m4_v3(kcd->ob->imat, view);
if (kcd->cut_through) {
@@ -1301,6 +1312,22 @@ static void knife_bgl_get_mats(KnifeTool_OpData *UNUSED(kcd), bglMats *mats)
//copy_m4_m4(mats->projection, kcd->vc.rv3d->winmat);
}
+/* Calculate maximum excursion (doubled) from (0,0,0) of mesh */
+static void calc_ortho_extent(KnifeTool_OpData *kcd)
+{
+ BMIter iter;
+ BMVert *v;
+ BMesh* bm = kcd->em->bm;
+ float max_xyz = 0.0f;
+ int i;
+
+ BM_ITER_MESH(v, &iter, bm, BM_VERTS_OF_MESH) {
+ for (i = 0; i < 3; i++)
+ max_xyz = max_ff(max_xyz, fabs(v->co[i]));
+ }
+ kcd->ortho_extent = 2 * max_xyz;
+}
+
/* Finds visible (or all, if cutting through) edges that intersects the current screen drag line */
static void knife_find_line_hits(KnifeTool_OpData *kcd)
{
@@ -1343,8 +1370,10 @@ static void knife_find_line_hits(KnifeTool_OpData *kcd)
* (which may involve using doubles everywhere!),
* limit the distance between these points */
if (kcd->is_ortho) {
- limit_dist_v3(v1, v3, 200.0f);
- limit_dist_v3(v2, v4, 200.0f);
+ if (kcd->ortho_extent == 0.0f)
+ calc_ortho_extent(kcd);
+ limit_dist_v3(v1, v3, kcd->ortho_extent + 10.0f);
+ limit_dist_v3(v2, v4, kcd->ortho_extent + 10.0f);
}
BLI_smallhash_init(ehash);
@@ -1386,7 +1415,7 @@ static void knife_input_ray_cast(KnifeTool_OpData *kcd, const int mval_i[2],
mval[1] = (float)mval_i[1];
/* unproject to find view ray */
- view3d_unproject(&mats, r_origin, mval[0], mval[1], 0.0f);
+ ED_view3d_unproject(&mats, r_origin, mval[0], mval[1], 0.0f);
if (kcd->is_ortho) {
negate_v3_v3(r_ray, kcd->vc.rv3d->viewinv[2]);
@@ -1408,7 +1437,7 @@ static void knife_input_ray_cast(KnifeTool_OpData *kcd, const int mval_i[2],
static BMFace *knife_find_closest_face(KnifeTool_OpData *kcd, float co[3], float cageco[3], int *is_space)
{
BMFace *f;
- int dist = KMAXDIST;
+ float dist = KMAXDIST;
float origin[3];
float ray[3];
@@ -1496,7 +1525,7 @@ static float knife_snap_size(KnifeTool_OpData *kcd, float maxsize)
if (density < 1.0f)
density = 1.0f;
- return minf(maxsize / (density * 0.5f), maxsize);
+ return min_ff(maxsize / (density * 0.5f), maxsize);
}
/* p is closest point on edge to the mouse cursor */
@@ -1753,6 +1782,9 @@ static int knife_update_active(KnifeTool_OpData *kcd)
return 1;
}
+#define SCANFILL_CUTS 0
+#if SCANFILL_CUTS
+
#define MARK 4
#define DEL 8
#define VERT_ON_EDGE 16
@@ -1761,9 +1793,6 @@ static int knife_update_active(KnifeTool_OpData *kcd)
#define BOUNDARY 128
#define FACE_NEW 256
-#define SCANFILL_CUTS 0
-#if SCANFILL_CUTS
-
typedef struct facenet_entry {
struct facenet_entry *next, *prev;
KnifeEdge *kfe;
@@ -1981,7 +2010,7 @@ static void knifenet_fill_faces(KnifeTool_OpData *kcd)
ScanFillFace *sf_tri;
ScanFillVert *sf_vert, *sf_vert_last;
int j;
- float rndscale = FLT_EPSILON * 25;
+ float rndscale = (KNIFE_FLT_EPS / 4.0f);
f = faces[i];
BLI_smallhash_init(hash);
@@ -3054,14 +3083,9 @@ wmKeyMap *knifetool_modal_keymap(wmKeyConfig *keyconf)
static int knifetool_modal(bContext *C, wmOperator *op, wmEvent *event)
{
- Object *obedit;
+ Object *obedit = CTX_data_edit_object(C);
KnifeTool_OpData *kcd = op->customdata;
- if (!C) {
- return OPERATOR_FINISHED;
- }
-
- obedit = CTX_data_edit_object(C);
if (!obedit || obedit->type != OB_MESH || BMEdit_FromObject(obedit) != kcd->em) {
knifetool_exit(C, op);
ED_area_headerprint(CTX_wm_area(C), NULL);
@@ -3125,6 +3149,7 @@ static int knifetool_modal(bContext *C, wmOperator *op, wmEvent *event)
break;
case KNF_MODAL_CUT_THROUGH_TOGGLE:
kcd->cut_through = !kcd->cut_through;
+ knifetool_update_mval(kcd, event->mval); /* refresh knife path */
knife_update_header(C, kcd);
break;
case KNF_MODAL_NEW_CUT:
diff --git a/source/blender/editors/mesh/editmesh_loopcut.c b/source/blender/editors/mesh/editmesh_loopcut.c
index 60c5244ddbc..8e5c89adfca 100644
--- a/source/blender/editors/mesh/editmesh_loopcut.c
+++ b/source/blender/editors/mesh/editmesh_loopcut.c
@@ -29,7 +29,9 @@
*/
#include <float.h>
-#define _USE_MATH_DEFINES
+#ifdef _MSC_VER
+# define _USE_MATH_DEFINES
+#endif
#include <math.h>
#include <string.h>
#include <ctype.h>
@@ -371,11 +373,12 @@ static void ringsel_exit(bContext *UNUSED(C), wmOperator *op)
op->customdata = NULL;
}
+
/* called when modal loop selection gets set up... */
static int ringsel_init(bContext *C, wmOperator *op, int do_cut)
{
RingSelOpData *lcd;
-
+
/* alloc new customdata */
lcd = op->customdata = MEM_callocN(sizeof(RingSelOpData), "ringsel Modal Op Data");
@@ -390,7 +393,10 @@ static int ringsel_init(bContext *C, wmOperator *op, int do_cut)
initNumInput(&lcd->num);
lcd->num.idx_max = 0;
lcd->num.flag |= NUM_NO_NEGATIVE | NUM_NO_FRACTION;
-
+
+ /* XXX, temp, workaround for [# ] */
+ EDBM_mesh_ensure_valid_dm_hack(CTX_data_scene(C), lcd->em);
+
em_setup_viewcontext(C, &lcd->vc);
ED_region_tag_redraw(lcd->ar);
@@ -410,10 +416,10 @@ static int ringcut_invoke(bContext *C, wmOperator *op, wmEvent *evt)
Object *obedit = CTX_data_edit_object(C);
RingSelOpData *lcd;
BMEdge *edge;
- int dist = 75;
+ float dist = 75.0f;
if (modifiers_isDeformedByLattice(obedit) || modifiers_isDeformedByArmature(obedit))
- BKE_report(op->reports, RPT_WARNING, "Loop cut doesn't work well on deformed edit mesh display");
+ BKE_report(op->reports, RPT_WARNING, "Loop cut does not work well on deformed edit mesh display");
view3d_operator_needs_opengl(C);
@@ -499,7 +505,7 @@ static int loopcut_modal(bContext *C, wmOperator *op, wmEvent *event)
if (event->val == KM_RELEASE)
break;
- cuts = MAX2(cuts - 1, 0);
+ cuts = max_ii(cuts - 1, 0);
RNA_int_set(op->ptr, "number_cuts", cuts);
ringsel_find_edge(lcd, cuts);
show_cuts = TRUE;
@@ -507,7 +513,7 @@ static int loopcut_modal(bContext *C, wmOperator *op, wmEvent *event)
ED_region_tag_redraw(lcd->ar);
break;
case MOUSEMOVE: { /* mouse moved somewhere to select another loop */
- int dist = 75;
+ float dist = 75.0f;
BMEdge *edge;
lcd->vc.mval[0] = event->mval[0];
@@ -521,7 +527,7 @@ static int loopcut_modal(bContext *C, wmOperator *op, wmEvent *event)
ED_region_tag_redraw(lcd->ar);
break;
- }
+ }
}
/* using the keyboard to input the number of cuts */
diff --git a/source/blender/editors/mesh/editmesh_rip.c b/source/blender/editors/mesh/editmesh_rip.c
index 4d4a890300f..6379bdbc0ca 100644
--- a/source/blender/editors/mesh/editmesh_rip.c
+++ b/source/blender/editors/mesh/editmesh_rip.c
@@ -55,19 +55,59 @@
#include "mesh_intern.h"
-/* helper to find edge for edge_rip */
-static float edbm_rip_rip_edgedist(ARegion *ar, float mat[][4],
- const float co1[3], const float co2[2], const float mvalf[2])
+/**
+ * helper to find edge for edge_rip,
+ *
+ * \param inset is used so we get some useful distance
+ * when comparing multiple edges that meet at the same
+ * point and would result in teh same distance.
+ */
+#define INSET_DEFAULT 0.00001f
+static float edbm_rip_edgedist(ARegion *ar, float mat[][4],
+ const float co1[3], const float co2[3], const float mvalf[2],
+ const float inset)
{
- float vec1[3], vec2[3];
+ float vec1[2], vec2[2];
- ED_view3d_project_float_v2(ar, co1, vec1, mat);
- ED_view3d_project_float_v2(ar, co2, vec2, mat);
+ ED_view3d_project_float_v2_m4(ar, co1, vec1, mat);
+ ED_view3d_project_float_v2_m4(ar, co2, vec2, mat);
+
+ if (inset != 0.0f) {
+ const float dist = inset / len_v2v2(vec1, vec2);
+ interp_v2_v2v2(vec1, vec1, vec2, dist);
+ interp_v2_v2v2(vec2, vec2, vec1, dist);
+ }
/* TODO: use dist_squared_to_line_segment_v2() looks like we only ever use for comparison */
return dist_to_line_segment_v2(mvalf, vec1, vec2);
}
+#if 0
+static float edbm_rip_linedist(ARegion *ar, float mat[][4],
+ const float co1[3], const float co2[3], const float mvalf[2])
+{
+ float vec1[2], vec2[2];
+
+ ED_view3d_project_float_v2_m4(ar, co1, vec1, mat);
+ ED_view3d_project_float_v2_m4(ar, co2, vec2, mat);
+
+ return dist_to_line_v2(mvalf, vec1, vec2);
+}
+#endif
+
+/* calculaters a point along the loop tangent which can be used to measure against edges */
+static void edbm_calc_loop_co(BMLoop *l, float l_mid_co[3])
+{
+ BM_loop_calc_face_tangent(l, l_mid_co);
+
+ /* scale to average of surrounding edge size, only needs to be approx, but should
+ * be roughly equivalent to the check below which uses the middle of the edge. */
+ mul_v3_fl(l_mid_co, (BM_edge_calc_length(l->e) + BM_edge_calc_length(l->prev->e)) / 2.0f);
+
+ add_v3_v3(l_mid_co, l->v->co);
+}
+
+
static float edbm_rip_edge_side_measure(BMEdge *e, BMLoop *e_l,
ARegion *ar,
float projectMat[4][4], const float fmval[2])
@@ -97,11 +137,11 @@ static float edbm_rip_edge_side_measure(BMEdge *e, BMLoop *e_l,
mid_v3_v3v3(cent, v1_other->co, v2_other->co);
mid_v3_v3v3(mid, e->v1->co, e->v2->co);
- ED_view3d_project_float_v2(ar, cent, cent, projectMat);
- ED_view3d_project_float_v2(ar, mid, mid, projectMat);
+ ED_view3d_project_float_v2_m4(ar, cent, cent, projectMat);
+ ED_view3d_project_float_v2_m4(ar, mid, mid, projectMat);
- ED_view3d_project_float_v2(ar, e->v1->co, e_v1_co, projectMat);
- ED_view3d_project_float_v2(ar, e->v2->co, e_v2_co, projectMat);
+ ED_view3d_project_float_v2_m4(ar, e->v1->co, e_v1_co, projectMat);
+ ED_view3d_project_float_v2_m4(ar, e->v2->co, e_v2_co, projectMat);
sub_v2_v2v2(vec, cent, mid);
normalize_v2(vec);
@@ -237,7 +277,6 @@ static EdgeLoopPair *edbm_ripsel_looptag_helper(BMesh *bm)
uid_start = uid;
while ((e = edbm_ripsel_edge_mark_step(v_step, uid))) {
- BM_elem_flag_disable(e, BM_ELEM_SMOOTH);
v_step = BM_edge_other_vert((e_step = e), v_step);
uid++; /* only different line */
tot++;
@@ -254,7 +293,6 @@ static EdgeLoopPair *edbm_ripsel_looptag_helper(BMesh *bm)
v_step = e_first->v1;
while ((e = edbm_ripsel_edge_mark_step(v_step, uid))) {
- BM_elem_flag_disable(e, BM_ELEM_SMOOTH);
v_step = BM_edge_other_vert((e_step = e), v_step);
uid--; /* only different line */
tot++;
@@ -344,6 +382,145 @@ static void edbm_ripsel_deselect_helper(BMesh *bm, EdgeLoopPair *eloop_pairs,
}
/* --- end 'ripsel' selection handling code --- */
+
+/* --- face-fill code --- */
+/**
+ * return an un-ordered array of loop pairs
+ * use for rebuilding face-fill
+ *
+ * \note the method currenly used fails for edges with 3+ face users and gives
+ * nasty holes in the mesh, there isnt a good way of knowing ahead of time
+ * which loops will be split apart (its possible to figure out but quite involved).
+ * So for now this is a known limitation of current rip-fill option.
+ */
+
+typedef struct UnorderedLoopPair {
+ BMLoop *l_pair[2];
+ char flag;
+} UnorderedLoopPair;
+enum {
+ ULP_FLIP_0 = (1 << 0),
+ ULP_FLIP_1 = (1 << 1)
+};
+
+static UnorderedLoopPair *edbm_tagged_loop_pairs_to_fill(BMesh *bm)
+{
+ BMIter iter;
+ BMEdge *e;
+
+ unsigned int total_tag = 0;
+ /* count tags, could be pre-calculated */
+ BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
+ if (BM_elem_flag_test(e, BM_ELEM_TAG)) {
+ total_tag++;
+ }
+ }
+
+ if (total_tag) {
+ UnorderedLoopPair *uloop_pairs = MEM_mallocN(total_tag * sizeof(UnorderedLoopPair), __func__);
+ UnorderedLoopPair *ulp = uloop_pairs;
+
+ BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
+ if (BM_elem_flag_test(e, BM_ELEM_TAG)) {
+ BMLoop *l1, *l2;
+ if (BM_edge_loop_pair(e, &l1, &l2)) {
+ BMVert *v_cmp = l1->e->v1;
+ ulp->flag = (((l1->v != v_cmp) ? ULP_FLIP_0 : 0) |
+ ((l2->v == v_cmp) ? ULP_FLIP_1 : 0));
+ }
+ else {
+ ulp->flag = 0;
+ }
+ ulp->l_pair[0] = l1;
+ ulp->l_pair[1] = l2;
+
+ ulp++;
+ }
+ }
+
+ return uloop_pairs;
+ }
+ else {
+ return NULL;
+ }
+}
+
+static void edbm_tagged_loop_pairs_do_fill_faces(BMesh *bm, UnorderedLoopPair *uloop_pairs)
+{
+ UnorderedLoopPair *ulp;
+ unsigned int total_tag = MEM_allocN_len(uloop_pairs) / sizeof(UnorderedLoopPair);
+ unsigned int i;
+
+ for (i = 0, ulp = uloop_pairs; i < total_tag; i++, ulp++) {
+ if ((ulp->l_pair[0] && ulp->l_pair[1]) &&
+ (ulp->l_pair[0]->e != ulp->l_pair[1]->e))
+ {
+ /* time has come to make a face! */
+ BMVert *v_shared = BM_edge_share_vert(ulp->l_pair[0]->e, ulp->l_pair[1]->e);
+ BMFace *f, *f_example = ulp->l_pair[0]->f;
+ BMLoop *l_iter;
+ BMVert *f_verts[4];
+
+ if (v_shared == NULL) {
+ /* quad */
+ f_verts[0] = ulp->l_pair[0]->e->v1;
+ f_verts[1] = ulp->l_pair[1]->e->v1;
+ f_verts[2] = ulp->l_pair[1]->e->v2;
+ f_verts[3] = ulp->l_pair[0]->e->v2;
+
+ if (ulp->flag & ULP_FLIP_0) {
+ SWAP(BMVert *, f_verts[0], f_verts[3]);
+ }
+ if (ulp->flag & ULP_FLIP_1) {
+ SWAP(BMVert *, f_verts[1], f_verts[2]);
+ }
+ }
+ else {
+ /* tri */
+ f_verts[0] = v_shared;
+ f_verts[1] = BM_edge_other_vert(ulp->l_pair[0]->e, v_shared);
+ f_verts[2] = BM_edge_other_vert(ulp->l_pair[1]->e, v_shared);
+ f_verts[3] = NULL;
+
+ /* don't use the flip flags */
+ if (v_shared == ulp->l_pair[0]->v) {
+ SWAP(BMVert *, f_verts[0], f_verts[1]);
+ }
+ }
+
+ /* face should never exist */
+ BLI_assert(BM_face_exists(bm, f_verts, f_verts[3] ? 4 : 3, &f) == FALSE);
+
+ f = BM_face_create_quad_tri_v(bm, f_verts, f_verts[3] ? 4 : 3, f_example, FALSE);
+
+ l_iter = BM_FACE_FIRST_LOOP(f);
+
+ if (f_verts[3]) {
+ BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[0]->e, l_iter), l_iter); l_iter = l_iter->next;
+ BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[1]->e, l_iter), l_iter); l_iter = l_iter->next;
+ BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[1]->e, l_iter), l_iter); l_iter = l_iter->next;
+ BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[0]->e, l_iter), l_iter);
+ }
+ else {
+ if (v_shared == f_verts[0]) {
+ BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[0]->e, l_iter), l_iter); l_iter = l_iter->next;
+ BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[0]->e, l_iter), l_iter); l_iter = l_iter->next;
+ BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[1]->e, l_iter), l_iter);
+ }
+ else {
+ BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[0]->e, l_iter), l_iter); l_iter = l_iter->next;
+ BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[0]->e, l_iter), l_iter); l_iter = l_iter->next;
+ BM_elem_attrs_copy(bm, bm, BM_edge_other_loop(ulp->l_pair[1]->e, l_iter), l_iter);
+ }
+ }
+
+ }
+ }
+}
+
+/* --- end 'face-fill' code --- */
+
+
static int edbm_rip_call_edgesplit(BMEditMesh *em, wmOperator *op)
{
BMOperator bmop;
@@ -366,6 +543,8 @@ static int edbm_rip_call_edgesplit(BMEditMesh *em, wmOperator *op)
*/
static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
{
+ const int do_fill = RNA_boolean_get(op->ptr, "use_fill");
+ UnorderedLoopPair *fill_uloop_pairs = NULL;
Object *obedit = CTX_data_edit_object(C);
ARegion *ar = CTX_wm_region(C);
RegionView3D *rv3d = CTX_wm_region_view3d(C);
@@ -388,7 +567,7 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
ED_view3d_ob_project_mat_get(rv3d, obedit, projectMat);
/* find selected vert - same some time and check history first */
- if (BM_select_history_active_get(em->bm, &ese) && ese.htype == BM_VERT) {
+ if (BM_select_history_active_get(bm, &ese) && ese.htype == BM_VERT) {
v = (BMVert *)ese.ele;
}
else {
@@ -417,7 +596,7 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
totboundary_edge += (is_boundary != 0 || BM_edge_is_wire(e));
if (!BM_elem_flag_test(e, BM_ELEM_HIDDEN)) {
if (is_boundary == FALSE && BM_edge_is_manifold(e)) {
- d = edbm_rip_rip_edgedist(ar, projectMat, e->v1->co, e->v2->co, fmval);
+ d = edbm_rip_edgedist(ar, projectMat, e->v1->co, e->v2->co, fmval, INSET_DEFAULT);
if (d < dist) {
dist = d;
e2 = e;
@@ -426,6 +605,42 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
}
}
+ /* if we are ripping a single vertex from 3 faces,
+ * then measure the distance to the face corner as well as the edge */
+ if (BM_vert_face_count(v) == 3 &&
+ BM_vert_edge_count(v) == 3)
+ {
+ BMEdge *e_all[3];
+ BMLoop *l_all[3];
+ int i1, i2;
+
+ BM_iter_as_array(bm, BM_EDGES_OF_VERT, v, (void **)e_all, 3);
+ BM_iter_as_array(bm, BM_LOOPS_OF_VERT, v, (void **)l_all, 3);
+
+ /* not do a loop similar to the one above, but test against loops */
+ for (i1 = 0; i1 < 3; i1++) {
+ /* consider wire as boundary for this purpose,
+ * otherwise we can't a face away from a wire edge */
+ float l_mid_co[3];
+ l = l_all[i1];
+ edbm_calc_loop_co(l, l_mid_co);
+ d = edbm_rip_edgedist(ar, projectMat, l->v->co, l_mid_co, fmval, INSET_DEFAULT);
+
+ if (d < dist) {
+ dist = d;
+
+ /* find the edge that is not in this loop */
+ e2 = NULL;
+ for (i2 = 0; i2 < 3; i2++) {
+ if (!BM_edge_in_loop(e_all[i2], l)) {
+ e2 = e_all[i2];
+ break;
+ }
+ }
+ BLI_assert(e2 != NULL);
+ }
+ }
+ }
}
/* should we go ahead with edge rip or do we need to do special case, split off vertex?:
@@ -459,7 +674,7 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
int vi_best = 0;
if (ese.ele) {
- BM_select_history_remove(em->bm, ese.ele);
+ BM_select_history_remove(bm, ese.ele);
}
dist = FLT_MAX;
@@ -473,14 +688,9 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
BM_ITER_ELEM (l, &iter, vout[i], BM_LOOPS_OF_VERT) {
if (!BM_elem_flag_test(l->f, BM_ELEM_HIDDEN)) {
float l_mid_co[3];
- BM_loop_calc_face_tangent(l, l_mid_co);
+ edbm_calc_loop_co(l, l_mid_co);
- /* scale to average of surrounding edge size, only needs to be approx, but should
- * be roughly equivalent to the check below which uses the middle of the edge. */
- mul_v3_fl(l_mid_co, (BM_edge_calc_length(l->e) + BM_edge_calc_length(l->prev->e)) / 2.0f);
- add_v3_v3(l_mid_co, v->co);
-
- d = edbm_rip_rip_edgedist(ar, projectMat, v->co, l_mid_co, fmval);
+ d = edbm_rip_edgedist(ar, projectMat, v->co, l_mid_co, fmval, INSET_DEFAULT);
if (d < dist) {
dist = d;
@@ -496,7 +706,7 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
float e_mid_co[3];
mid_v3_v3v3(e_mid_co, e->v1->co, e->v2->co);
- d = edbm_rip_rip_edgedist(ar, projectMat, v->co, e_mid_co, fmval);
+ d = edbm_rip_edgedist(ar, projectMat, v->co, e_mid_co, fmval, INSET_DEFAULT);
if (d < dist) {
dist = d;
@@ -512,7 +722,7 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
BM_vert_select_set(bm, v, TRUE);
if (ese.ele) {
- BM_select_history_store(em->bm, v);
+ BM_select_history_store(bm, v);
}
/* splice all others back together */
@@ -543,39 +753,65 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
return OPERATOR_CANCELLED;
}
+ /* *** Execute the split! *** */
+ /* unlike edge split, for single vertex split we only use the operator in one of the cases
+ * but both allocate fill */
+
/* rip two adjacent edges */
if (BM_edge_is_boundary(e2) || BM_vert_face_count(v) == 2) {
+ /* Don't run the edge split operator in this case */
+
+ BM_elem_flag_enable(e2, BM_ELEM_TAG); /* only for face-fill (we don't call the operator) */
+
+ /* keep directly before edgesplit */
+ if (do_fill) {
+ fill_uloop_pairs = edbm_tagged_loop_pairs_to_fill(bm);
+ }
+
l = e2->l;
ripvert = BM_face_vert_separate(bm, l->f, v);
BLI_assert(ripvert);
if (!ripvert) {
+ if (fill_uloop_pairs) MEM_freeN(fill_uloop_pairs);
return OPERATOR_CANCELLED;
}
}
- else if (BM_edge_is_manifold(e2)) {
- l = e2->l;
- e = BM_face_other_edge_loop(l->f, e2, v)->e;
- BM_elem_flag_enable(e, BM_ELEM_TAG);
+ else {
+ if (BM_edge_is_manifold(e2)) {
+ l = e2->l;
+ e = BM_face_other_edge_loop(l->f, e2, v)->e;
+ BM_elem_flag_enable(e, BM_ELEM_TAG);
+
+ l = e2->l->radial_next;
+ e = BM_face_other_edge_loop(l->f, e2, v)->e;
+ BM_elem_flag_enable(e, BM_ELEM_TAG);
+ }
+ else {
+ /* looks like there are no split edges, we could just return/report-error? - Campbell */
+ }
+
+ /* keep directly before edgesplit */
+ if (do_fill) {
+ fill_uloop_pairs = edbm_tagged_loop_pairs_to_fill(bm);
+ }
- l = e2->l->radial_next;
- e = BM_face_other_edge_loop(l->f, e2, v)->e;
- BM_elem_flag_enable(e, BM_ELEM_TAG);
+ if (!edbm_rip_call_edgesplit(em, op)) {
+ if (fill_uloop_pairs) MEM_freeN(fill_uloop_pairs);
+ return OPERATOR_CANCELLED;
+ }
}
dist = FLT_MAX;
- if (!edbm_rip_call_edgesplit(em, op)) {
- return OPERATOR_CANCELLED;
- }
- else {
+ {
/* --- select which vert --- */
BMVert *v_best = NULL;
float l_prev_co[3], l_next_co[3], l_corner_co[3];
float scale;
dist = FLT_MAX;
- BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
+ BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
/* disable by default, re-enable winner at end */
BM_vert_select_set(bm, v, FALSE);
@@ -593,7 +829,7 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
add_v3_v3v3(l_corner_co, l_prev_co, l_next_co);
add_v3_v3(l_corner_co, l->v->co);
- d = edbm_rip_rip_edgedist(ar, projectMat, l->v->co, l_corner_co, fmval);
+ d = edbm_rip_edgedist(ar, projectMat, l->v->co, l_corner_co, fmval, INSET_DEFAULT);
if (d < dist) {
v_best = v;
dist = d;
@@ -605,11 +841,17 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
if (v_best) {
BM_vert_select_set(bm, v_best, TRUE);
if (ese.ele) {
- BM_select_history_store(em->bm, v_best);
+ BM_select_history_store(bm, v_best);
}
}
}
+ if (do_fill && fill_uloop_pairs) {
+ edbm_tagged_loop_pairs_do_fill_faces(bm, fill_uloop_pairs);
+ MEM_freeN(fill_uloop_pairs);
+ }
+
+
if (totvert_orig == bm->totvert) {
BKE_report(op->reports, RPT_ERROR, "No vertices could be ripped");
return OPERATOR_CANCELLED;
@@ -623,6 +865,8 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, wmEvent *event)
*/
static int edbm_rip_invoke__edge(bContext *C, wmOperator *op, wmEvent *event)
{
+ const int do_fill = RNA_boolean_get(op->ptr, "use_fill");
+ UnorderedLoopPair *fill_uloop_pairs = NULL;
Object *obedit = CTX_data_edit_object(C);
ARegion *ar = CTX_wm_region(C);
RegionView3D *rv3d = CTX_wm_region_view3d(C);
@@ -633,25 +877,25 @@ static int edbm_rip_invoke__edge(bContext *C, wmOperator *op, wmEvent *event)
BMEdge *e, *e2;
BMVert *v;
const int totedge_orig = bm->totedge;
- int i;
float projectMat[4][4], fmval[3] = {event->mval[0], event->mval[1]};
- int totedge;
- int all_minifold;
-
EdgeLoopPair *eloop_pairs;
ED_view3d_ob_project_mat_get(rv3d, obedit, projectMat);
- /* important this runs on the original selection, before tempering with tagging */
+ /* important this runs on the original selection, before tampering with tagging */
eloop_pairs = edbm_ripsel_looptag_helper(bm);
/* expand edge selection */
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
+ int all_manifold;
+ int totedge_manifold; /* manifold, visible edges */
+ int i;
+
e2 = NULL;
i = 0;
- totedge = 0;
- all_minifold = TRUE;
+ totedge_manifold = 0;
+ all_manifold = TRUE;
BM_ITER_ELEM (e, &eiter, v, BM_EDGES_OF_VERT) {
if (!BM_edge_is_wire(e) &&
@@ -663,22 +907,25 @@ static int edbm_rip_invoke__edge(bContext *C, wmOperator *op, wmEvent *event)
e2 = e;
i++;
}
- totedge++;
+ totedge_manifold++;
}
/** #BM_vert_other_disk_edge has no hidden checks so don't check hidden here */
- if ((all_minifold == TRUE) && (BM_edge_is_manifold(e) == FALSE)) {
- all_minifold = FALSE;
+ if ((all_manifold == TRUE) && (BM_edge_is_manifold(e) == FALSE)) {
+ all_manifold = FALSE;
}
}
/* single edge, extend */
if (i == 1 && e2->l) {
- if ((totedge == 4) || (all_minifold == FALSE)) {
+ /* note: if the case of 3 edges has one change in loop stepping,
+ * if this becomes more involved we may be better off splitting
+ * the 3 edge case into its own else-if branch */
+ if ((totedge_manifold == 4 || totedge_manifold == 3) || (all_manifold == FALSE)) {
BMLoop *l_a = e2->l;
BMLoop *l_b = l_a->radial_next;
- /* find the best face to follow, this what the edge won't point away from
+ /* find the best face to follow, this way the edge won't point away from
* the mouse when there are more then 4 (takes the shortest face fan around) */
l = (edbm_rip_edge_side_measure(e2, l_a, ar, projectMat, fmval) <
edbm_rip_edge_side_measure(e2, l_b, ar, projectMat, fmval)) ? l_a : l_b;
@@ -688,9 +935,12 @@ static int edbm_rip_invoke__edge(bContext *C, wmOperator *op, wmEvent *event)
* not crashing but adds duplicate edge. */
if (BM_edge_is_manifold(l->e)) {
l = l->radial_next;
- l = BM_face_other_edge_loop(l->f, l->e, v);
+
+ if (totedge_manifold != 3)
+ l = BM_face_other_edge_loop(l->f, l->e, v);
if (l) {
+ BLI_assert(!BM_elem_flag_test(l->e, BM_ELEM_TAG));
BM_elem_flag_enable(l->e, BM_ELEM_TAG);
}
}
@@ -699,13 +949,20 @@ static int edbm_rip_invoke__edge(bContext *C, wmOperator *op, wmEvent *event)
e = BM_vert_other_disk_edge(v, e2);
if (e) {
+ BLI_assert(!BM_elem_flag_test(e, BM_ELEM_TAG));
BM_elem_flag_enable(e, BM_ELEM_TAG);
}
}
}
}
+ /* keep directly before edgesplit */
+ if (do_fill) {
+ fill_uloop_pairs = edbm_tagged_loop_pairs_to_fill(bm);
+ }
+
if (!edbm_rip_call_edgesplit(em, op)) {
+ if (fill_uloop_pairs) MEM_freeN(fill_uloop_pairs);
return OPERATOR_CANCELLED;
}
@@ -718,6 +975,11 @@ static int edbm_rip_invoke__edge(bContext *C, wmOperator *op, wmEvent *event)
ar, projectMat, fmval);
MEM_freeN(eloop_pairs);
+ if (do_fill && fill_uloop_pairs) {
+ edbm_tagged_loop_pairs_do_fill_faces(bm, fill_uloop_pairs);
+ MEM_freeN(fill_uloop_pairs);
+ }
+
if (totedge_orig == bm->totedge) {
BKE_report(op->reports, RPT_ERROR, "No edges could be ripped");
return OPERATOR_CANCELLED;
@@ -740,12 +1002,12 @@ static int edbm_rip_invoke(bContext *C, wmOperator *op, wmEvent *event)
int ret;
/* running in face mode hardly makes sense, so convert to region loop and rip */
- if (em->bm->totfacesel) {
+ if (bm->totfacesel) {
/* highly nifty but hard to support since the operator can fail and we're left
* with modified selection */
// WM_operator_name_call(C, "MESH_OT_region_to_loop", WM_OP_INVOKE_DEFAULT, NULL);
- BKE_report(op->reports, RPT_ERROR, "Can't rip selected faces");
+ BKE_report(op->reports, RPT_ERROR, "Cannot rip selected faces");
return OPERATOR_CANCELLED;
}
@@ -760,7 +1022,7 @@ static int edbm_rip_invoke(bContext *C, wmOperator *op, wmEvent *event)
*/
/* BM_ELEM_SELECT --> BM_ELEM_TAG */
- BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
+ BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
BM_elem_flag_set(e, BM_ELEM_TAG, BM_elem_flag_test(e, BM_ELEM_SELECT));
}
@@ -804,5 +1066,6 @@ void MESH_OT_rip(wmOperatorType *ot)
/* to give to transform */
Transform_Properties(ot, P_PROPORTIONAL);
- RNA_def_boolean(ot->srna, "mirror", 0, "Mirror Editing", "");
+ RNA_def_boolean(ot->srna, "mirror", FALSE, "Mirror Editing", "");
+ RNA_def_boolean(ot->srna, "use_fill", FALSE, "Fill", "Fill the ripped region");
}
diff --git a/source/blender/editors/mesh/editmesh_select.c b/source/blender/editors/mesh/editmesh_select.c
index 81776ff7f4f..0379068afd9 100644
--- a/source/blender/editors/mesh/editmesh_select.c
+++ b/source/blender/editors/mesh/editmesh_select.c
@@ -57,6 +57,7 @@
#include "ED_mesh.h"
#include "ED_screen.h"
#include "ED_uvedit.h"
+#include "ED_object.h"
#include "ED_view3d.h"
#include "BIF_gl.h"
@@ -131,7 +132,7 @@ unsigned int bm_solidoffs = 0, bm_wireoffs = 0, bm_vertoffs = 0; /* set in dr
static char *selbuf = NULL;
/* opengl doesn't support concave... */
-static void draw_triangulated(int mcords[][2], short tot)
+static void draw_triangulated(const int mcords[][2], const short tot)
{
ListBase lb = {NULL, NULL};
DispList *dl;
@@ -227,7 +228,7 @@ void EDBM_backbuf_free(void)
* - grab again and compare
* returns 'OK'
*/
-int EDBM_backbuf_border_mask_init(ViewContext *vc, int mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
+int EDBM_backbuf_border_mask_init(ViewContext *vc, const int mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
{
unsigned int *dr, *drm;
struct ImBuf *buf, *bufmask;
@@ -330,9 +331,9 @@ int EDBM_backbuf_circle_init(ViewContext *vc, short xs, short ys, short rads)
}
-static void findnearestvert__doClosest(void *userData, BMVert *eve, int x, int y, int index)
+static void findnearestvert__doClosest(void *userData, BMVert *eve, const float screen_co[2], int index)
{
- struct { short mval[2], pass, select, strict; int dist, lastIndex, closestIndex; BMVert *closest; } *data = userData;
+ struct { float mval_fl[2], pass, select, strict; float dist, lastIndex, closestIndex; BMVert *closest; } *data = userData;
if (data->pass == 0) {
if (index <= data->lastIndex)
@@ -344,18 +345,18 @@ static void findnearestvert__doClosest(void *userData, BMVert *eve, int x, int y
}
if (data->dist > 3) {
- int temp = abs(data->mval[0] - x) + abs(data->mval[1] - y);
+ float dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
if (BM_elem_flag_test(eve, BM_ELEM_SELECT) == data->select) {
if (data->strict == 1) {
return;
}
else {
- temp += 5;
+ dist_test += 5;
}
}
- if (temp < data->dist) {
- data->dist = temp;
+ if (dist_test < data->dist) {
+ data->dist = dist_test;
data->closest = eve;
data->closestIndex = index;
}
@@ -382,10 +383,10 @@ static unsigned int findnearestvert__backbufIndextest(void *handle, unsigned int
* if 0, unselected vertice are given the bias
* strict: if 1, the vertice corresponding to the sel parameter are ignored and not just biased
*/
-BMVert *EDBM_vert_find_nearest(ViewContext *vc, int *dist, short sel, short strict)
+BMVert *EDBM_vert_find_nearest(ViewContext *vc, float *r_dist, const short sel, const short strict)
{
if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
- int distance;
+ float distance;
unsigned int index;
BMVert *eve;
@@ -400,8 +401,8 @@ BMVert *EDBM_vert_find_nearest(ViewContext *vc, int *dist, short sel, short stri
eve = BM_vert_at_index(vc->em->bm, index - 1);
- if (eve && distance < *dist) {
- *dist = distance;
+ if (eve && distance < *r_dist) {
+ *r_dist = distance;
return eve;
}
else {
@@ -410,7 +411,7 @@ BMVert *EDBM_vert_find_nearest(ViewContext *vc, int *dist, short sel, short stri
}
else {
- struct { short mval[2], pass, select, strict; int dist, lastIndex, closestIndex; BMVert *closest; } data;
+ struct { float mval_fl[2], pass, select, strict; float dist, lastIndex, closestIndex; BMVert *closest; } data;
static int lastSelectedIndex = 0;
static BMVert *lastSelected = NULL;
@@ -420,10 +421,10 @@ BMVert *EDBM_vert_find_nearest(ViewContext *vc, int *dist, short sel, short stri
}
data.lastIndex = lastSelectedIndex;
- data.mval[0] = vc->mval[0];
- data.mval[1] = vc->mval[1];
+ data.mval_fl[0] = vc->mval[0];
+ data.mval_fl[1] = vc->mval[1];
data.select = sel;
- data.dist = *dist;
+ data.dist = *r_dist;
data.strict = strict;
data.closest = NULL;
data.closestIndex = 0;
@@ -432,14 +433,14 @@ BMVert *EDBM_vert_find_nearest(ViewContext *vc, int *dist, short sel, short stri
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
- mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_CLIP_TEST_RV3D_CLIPPING);
+ mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
if (data.dist > 3) {
data.pass = 1;
- mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_CLIP_TEST_RV3D_CLIPPING);
+ mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
- *dist = data.dist;
+ *r_dist = data.dist;
lastSelected = data.closest;
lastSelectedIndex = data.closestIndex;
@@ -448,7 +449,7 @@ BMVert *EDBM_vert_find_nearest(ViewContext *vc, int *dist, short sel, short stri
}
/* returns labda for closest distance v1 to line-piece v2 - v3 */
-float labda_PdistVL2Dfl(const float v1[3], const float v2[3], const float v3[3])
+float labda_PdistVL2Dfl(const float v1[2], const float v2[2], const float v3[2])
{
float rc[2], len;
@@ -462,18 +463,12 @@ float labda_PdistVL2Dfl(const float v1[3], const float v2[3], const float v3[3])
}
/* note; uses v3d, so needs active 3d window */
-static void findnearestedge__doClosest(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int UNUSED(index))
+static void findnearestedge__doClosest(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int UNUSED(index))
{
- struct { ViewContext vc; float mval[2]; int dist; BMEdge *closest; } *data = userData;
- float v1[2], v2[2];
+ struct { ViewContext vc; float mval_fl[2]; float dist; BMEdge *closest; } *data = userData;
int distance;
-
- v1[0] = x0;
- v1[1] = y0;
- v2[0] = x1;
- v2[1] = y1;
-
- distance = dist_to_line_segment_v2(data->mval, v1, v2);
+
+ distance = dist_to_line_segment_v2(data->mval_fl, screen_co_a, screen_co_b);
if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
distance += 5;
@@ -481,13 +476,12 @@ static void findnearestedge__doClosest(void *userData, BMEdge *eed, int x0, int
if (distance < data->dist) {
if (data->vc.rv3d->rflag & RV3D_CLIPPING) {
- float labda = labda_PdistVL2Dfl(data->mval, v1, v2);
+ float labda = labda_PdistVL2Dfl(data->mval_fl, screen_co_a, screen_co_b);
float vec[3];
vec[0] = eed->v1->co[0] + labda * (eed->v2->co[0] - eed->v1->co[0]);
vec[1] = eed->v1->co[1] + labda * (eed->v2->co[1] - eed->v1->co[1]);
vec[2] = eed->v1->co[2] + labda * (eed->v2->co[2] - eed->v1->co[2]);
- mul_m4_v3(data->vc.obedit->obmat, vec);
if (ED_view3d_clipping_test(data->vc.rv3d, vec, TRUE) == 0) {
data->dist = distance;
@@ -500,11 +494,11 @@ static void findnearestedge__doClosest(void *userData, BMEdge *eed, int x0, int
}
}
}
-BMEdge *EDBM_edge_find_nearest(ViewContext *vc, int *dist)
+BMEdge *EDBM_edge_find_nearest(ViewContext *vc, float *r_dist)
{
if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
- int distance;
+ float distance;
unsigned int index;
BMEdge *eed;
@@ -513,8 +507,8 @@ BMEdge *EDBM_edge_find_nearest(ViewContext *vc, int *dist)
index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_solidoffs, bm_wireoffs, &distance, 0, NULL, NULL);
eed = BM_edge_at_index(vc->em->bm, index - 1);
- if (eed && distance < *dist) {
- *dist = distance;
+ if (eed && distance < *r_dist) {
+ *r_dist = distance;
return eed;
}
else {
@@ -522,36 +516,37 @@ BMEdge *EDBM_edge_find_nearest(ViewContext *vc, int *dist)
}
}
else {
- struct { ViewContext vc; float mval[2]; int dist; BMEdge *closest; } data;
+ struct { ViewContext vc; float mval_fl[2]; float dist; BMEdge *closest; } data;
data.vc = *vc;
- data.mval[0] = vc->mval[0];
- data.mval[1] = vc->mval[1];
- data.dist = *dist;
+ data.mval_fl[0] = vc->mval[0];
+ data.mval_fl[1] = vc->mval[1];
+ data.dist = *r_dist;
data.closest = NULL;
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
- mesh_foreachScreenEdge(vc, findnearestedge__doClosest, &data, 2);
+ mesh_foreachScreenEdge(vc, findnearestedge__doClosest, &data, V3D_PROJ_TEST_CLIP_WIN);
- *dist = data.dist;
+ *r_dist = data.dist;
return data.closest;
}
}
-static void findnearestface__getDistance(void *userData, BMFace *efa, int x, int y, int UNUSED(index))
+static void findnearestface__getDistance(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
{
- struct { short mval[2]; int dist; BMFace *toFace; } *data = userData;
+ struct { float mval_fl[2]; float dist; BMFace *toFace; } *data = userData;
if (efa == data->toFace) {
- int temp = abs(data->mval[0] - x) + abs(data->mval[1] - y);
+ const float dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
- if (temp < data->dist)
- data->dist = temp;
+ if (dist_test < data->dist) {
+ data->dist = dist_test;
+ }
}
}
-static void findnearestface__doClosest(void *userData, BMFace *efa, int x, int y, int index)
+static void findnearestface__doClosest(void *userData, BMFace *efa, const float screen_co[2], int index)
{
- struct { short mval[2], pass; int dist, lastIndex, closestIndex; BMFace *closest; } *data = userData;
+ struct { float mval_fl[2], pass; float dist, lastIndex, closestIndex; BMFace *closest; } *data = userData;
if (data->pass == 0) {
if (index <= data->lastIndex)
@@ -563,17 +558,17 @@ static void findnearestface__doClosest(void *userData, BMFace *efa, int x, int y
}
if (data->dist > 3) {
- int temp = abs(data->mval[0] - x) + abs(data->mval[1] - y);
+ const float dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
- if (temp < data->dist) {
- data->dist = temp;
+ if (dist_test < data->dist) {
+ data->dist = dist_test;
data->closest = efa;
data->closestIndex = index;
}
}
}
-BMFace *EDBM_face_find_nearest(ViewContext *vc, int *dist)
+BMFace *EDBM_face_find_nearest(ViewContext *vc, float *r_dist)
{
if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
@@ -586,17 +581,17 @@ BMFace *EDBM_face_find_nearest(ViewContext *vc, int *dist)
efa = BM_face_at_index(vc->em->bm, index - 1);
if (efa) {
- struct { short mval[2]; int dist; BMFace *toFace; } data;
+ struct { float mval_fl[2]; float dist; BMFace *toFace; } data;
- data.mval[0] = vc->mval[0];
- data.mval[1] = vc->mval[1];
+ data.mval_fl[0] = vc->mval[0];
+ data.mval_fl[1] = vc->mval[1];
data.dist = 0x7FFF; /* largest short */
data.toFace = efa;
- mesh_foreachScreenFace(vc, findnearestface__getDistance, &data);
+ mesh_foreachScreenFace(vc, findnearestface__getDistance, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
- if (vc->em->selectmode == SCE_SELECT_FACE || data.dist < *dist) { /* only faces, no dist check */
- *dist = data.dist;
+ if ((vc->em->selectmode == SCE_SELECT_FACE) || (data.dist < *r_dist)) { /* only faces, no dist check */
+ *r_dist = data.dist;
return efa;
}
}
@@ -604,7 +599,7 @@ BMFace *EDBM_face_find_nearest(ViewContext *vc, int *dist)
return NULL;
}
else {
- struct { short mval[2], pass; int dist, lastIndex, closestIndex; BMFace *closest; } data;
+ struct { float mval_fl[2], pass; float dist, lastIndex, closestIndex; BMFace *closest; } data;
static int lastSelectedIndex = 0;
static BMFace *lastSelected = NULL;
@@ -614,23 +609,23 @@ BMFace *EDBM_face_find_nearest(ViewContext *vc, int *dist)
}
data.lastIndex = lastSelectedIndex;
- data.mval[0] = vc->mval[0];
- data.mval[1] = vc->mval[1];
- data.dist = *dist;
+ data.mval_fl[0] = vc->mval[0];
+ data.mval_fl[1] = vc->mval[1];
+ data.dist = *r_dist;
data.closest = NULL;
data.closestIndex = 0;
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
data.pass = 0;
- mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
+ mesh_foreachScreenFace(vc, findnearestface__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
- if (data.dist > 3) {
+ if (data.dist > 3.0f) {
data.pass = 1;
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
- mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
+ mesh_foreachScreenFace(vc, findnearestface__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
- *dist = data.dist;
+ *r_dist = data.dist;
lastSelected = data.closest;
lastSelectedIndex = data.closestIndex;
@@ -646,7 +641,7 @@ BMFace *EDBM_face_find_nearest(ViewContext *vc, int *dist)
static int unified_findnearest(ViewContext *vc, BMVert **r_eve, BMEdge **r_eed, BMFace **r_efa)
{
BMEditMesh *em = vc->em;
- int dist = 75;
+ float dist = 75.0f;
*r_eve = NULL;
*r_eed = NULL;
@@ -676,6 +671,13 @@ static int unified_findnearest(ViewContext *vc, BMVert **r_eve, BMEdge **r_eed,
}
/* **************** SIMILAR "group" SELECTS. FACE, EDGE AND VERTEX ************** */
+static EnumPropertyItem prop_similar_compare_types[] = {
+ {SIM_CMP_EQ, "EQUAL", 0, "Equal", ""},
+ {SIM_CMP_GT, "GREATER", 0, "Greater", ""},
+ {SIM_CMP_LT, "LESS", 0, "Less", ""},
+
+ {0, NULL, 0, NULL, NULL}
+};
static EnumPropertyItem prop_similar_types[] = {
{SIMVERT_NORMAL, "NORMAL", 0, "Normal", ""},
@@ -695,6 +697,7 @@ static EnumPropertyItem prop_similar_types[] = {
{SIMFACE_MATERIAL, "MATERIAL", 0, "Material", ""},
{SIMFACE_IMAGE, "IMAGE", 0, "Image", ""},
{SIMFACE_AREA, "AREA", 0, "Area", ""},
+ {SIMFACE_SIDES, "SIDES", 0, "Polygon Sides", ""},
{SIMFACE_PERIMETER, "PERIMETER", 0, "Perimeter", ""},
{SIMFACE_NORMAL, "NORMAL", 0, "Normal", ""},
{SIMFACE_COPLANAR, "COPLANAR", 0, "Co-planar", ""},
@@ -711,11 +714,14 @@ static int similar_face_select_exec(bContext *C, wmOperator *op)
BMOperator bmop;
/* get the type from RNA */
- int type = RNA_enum_get(op->ptr, "type");
- float thresh = RNA_float_get(op->ptr, "threshold");
+ const int type = RNA_enum_get(op->ptr, "type");
+ const float thresh = RNA_float_get(op->ptr, "threshold");
+ const int compare = RNA_enum_get(op->ptr, "compare");
/* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
- EDBM_op_init(em, &bmop, op, "similar_faces faces=%hf type=%i thresh=%f", BM_ELEM_SELECT, type, thresh);
+ EDBM_op_init(em, &bmop, op,
+ "similar_faces faces=%hf type=%i thresh=%f compare=%i",
+ BM_ELEM_SELECT, type, thresh, compare);
/* execute the operator */
BMO_op_exec(em->bm, &bmop);
@@ -749,11 +755,14 @@ static int similar_edge_select_exec(bContext *C, wmOperator *op)
BMOperator bmop;
/* get the type from RNA */
- int type = RNA_enum_get(op->ptr, "type");
- float thresh = RNA_float_get(op->ptr, "threshold");
+ const int type = RNA_enum_get(op->ptr, "type");
+ const float thresh = RNA_float_get(op->ptr, "threshold");
+ const int compare = RNA_enum_get(op->ptr, "compare");
/* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
- EDBM_op_init(em, &bmop, op, "similar_edges edges=%he type=%i thresh=%f", BM_ELEM_SELECT, type, thresh);
+ EDBM_op_init(em, &bmop, op,
+ "similar_edges edges=%he type=%i thresh=%f compare=%i",
+ BM_ELEM_SELECT, type, thresh, compare);
/* execute the operator */
BMO_op_exec(em->bm, &bmop);
@@ -790,11 +799,14 @@ static int similar_vert_select_exec(bContext *C, wmOperator *op)
BMEditMesh *em = BMEdit_FromObject(ob);
BMOperator bmop;
/* get the type from RNA */
- int type = RNA_enum_get(op->ptr, "type");
+ const int type = RNA_enum_get(op->ptr, "type");
float thresh = RNA_float_get(op->ptr, "threshold");
+ const int compare = RNA_enum_get(op->ptr, "compare");
/* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
- EDBM_op_init(em, &bmop, op, "similar_verts verts=%hv type=%i thresh=%f", BM_ELEM_SELECT, type, thresh);
+ EDBM_op_init(em, &bmop, op,
+ "similar_verts verts=%hv type=%i thresh=%f compare=%i",
+ BM_ELEM_SELECT, type, thresh, compare);
/* execute the operator */
BMO_op_exec(em->bm, &bmop);
@@ -823,7 +835,7 @@ static int edbm_select_similar_exec(bContext *C, wmOperator *op)
ToolSettings *ts = CTX_data_tool_settings(C);
PropertyRNA *prop = RNA_struct_find_property(op->ptr, "threshold");
- int type = RNA_enum_get(op->ptr, "type");
+ const int type = RNA_enum_get(op->ptr, "type");
if (!RNA_property_is_set(op->ptr, prop)) {
RNA_property_float_set(op->ptr, prop, ts->select_thresh);
@@ -834,7 +846,7 @@ static int edbm_select_similar_exec(bContext *C, wmOperator *op)
if (type < 100) return similar_vert_select_exec(C, op);
else if (type < 200) return similar_edge_select_exec(C, op);
- else return similar_face_select_exec(C, op);
+ else return similar_face_select_exec(C, op);
}
static EnumPropertyItem *select_similar_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
@@ -898,7 +910,9 @@ void MESH_OT_select_similar(wmOperatorType *ot)
prop = ot->prop = RNA_def_enum(ot->srna, "type", prop_similar_types, SIMVERT_NORMAL, "Type", "");
RNA_def_enum_funcs(prop, select_similar_type_itemf);
- RNA_def_float(ot->srna, "threshold", 0.0, 0.0, 1.0, "Threshold", "", 0.01, 1.0);
+ RNA_def_enum(ot->srna, "compare", prop_similar_compare_types, SIM_CMP_EQ, "Compare", "");
+
+ RNA_def_float(ot->srna, "threshold", 0.0, 0.0, 1.0, "Threshold", "", 0.0, 1.0);
}
/* ***************************************************** */
@@ -1005,7 +1019,7 @@ static void mouse_mesh_loop(bContext *C, int mval[2], short extend, short ring)
BMEditMesh *em;
BMEdge *eed;
int select = TRUE;
- int dist = 50;
+ float dist = 50.0f;
float mvalf[2];
em_setup_viewcontext(C, &vc);
@@ -1051,21 +1065,27 @@ static void mouse_mesh_loop(bContext *C, int mval[2], short extend, short ring)
/* sets as active, useful for other tools */
if (select) {
if (em->selectmode & SCE_SELECT_VERTEX) {
- /* Find nearest vert from mouse. */
+ /* Find nearest vert from mouse
+ * (initialize to large values incase only one vertex can be projected) */
float v1_co[2], v2_co[2];
+ float length_1 = FLT_MAX;
+ float length_2 = FLT_MAX;
/* We can't be sure this has already been set... */
ED_view3d_init_mats_rv3d(vc.obedit, vc.rv3d);
- project_float_noclip(vc.ar, eed->v1->co, v1_co);
- project_float_noclip(vc.ar, eed->v2->co, v2_co);
+
+ if (ED_view3d_project_float_object(vc.ar, eed->v1->co, v1_co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ length_1 = len_squared_v2v2(mvalf, v1_co);
+ }
+
+ if (ED_view3d_project_float_object(vc.ar, eed->v2->co, v2_co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ length_2 = len_squared_v2v2(mvalf, v2_co);
+ }
#if 0
printf("mouse to v1: %f\nmouse to v2: %f\n", len_squared_v2v2(mvalf, v1_co),
len_squared_v2v2(mvalf, v2_co));
#endif
- if (len_squared_v2v2(mvalf, v1_co) < len_squared_v2v2(mvalf, v2_co))
- BM_select_history_store(em->bm, eed->v1);
- else
- BM_select_history_store(em->bm, eed->v2);
+ BM_select_history_store(em->bm, (length_1 < length_2) ? eed->v1 : eed->v2);
}
else if (em->selectmode & SCE_SELECT_EDGE) {
BM_select_history_store(em->bm, eed);
@@ -1085,12 +1105,13 @@ static void mouse_mesh_loop(bContext *C, int mval[2], short extend, short ring)
float co[2], tdist;
BM_face_calc_center_mean(f, cent);
- project_float_noclip(vc.ar, cent, co);
- tdist = len_squared_v2v2(mvalf, co);
- if (tdist < best_dist) {
-/* printf("Best face: %p (%f)\n", f, tdist);*/
- best_dist = tdist;
- efa = f;
+ if (ED_view3d_project_float_object(vc.ar, cent, co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ tdist = len_squared_v2v2(mvalf, co);
+ if (tdist < best_dist) {
+/* printf("Best face: %p (%f)\n", f, tdist);*/
+ best_dist = tdist;
+ efa = f;
+ }
}
}
}
@@ -1324,7 +1345,7 @@ static int edgetag_shortest_path(Scene *scene, BMEditMesh *em, BMEdge *source, B
EDBM_index_arrays_init(em, 1, 1, 0);
targetnum = BM_elem_index_get(target);
- while (!BLI_heap_empty(heap)) {
+ while (!BLI_heap_is_empty(heap)) {
mednum = GET_INT_FROM_POINTER(BLI_heap_popmin(heap));
e = EDBM_edge_at_index(em, mednum);
@@ -1386,7 +1407,7 @@ static int mouse_mesh_shortest_path(bContext *C, int mval[2])
ViewContext vc;
BMEditMesh *em;
BMEdge *e;
- int dist = 50;
+ float dist = 75.0f;
em_setup_viewcontext(C, &vc);
vc.mval[0] = mval[0];
@@ -1435,7 +1456,7 @@ static int mouse_mesh_shortest_path(bContext *C, int mval[2])
case EDGE_MODE_TAG_SHARP:
me->drawflag |= ME_DRAWSHARP;
break;
- case EDGE_MODE_TAG_CREASE:
+ case EDGE_MODE_TAG_CREASE:
me->drawflag |= ME_DRAWCREASES;
break;
case EDGE_MODE_TAG_BEVEL:
@@ -1705,7 +1726,7 @@ void EDBM_selectmode_convert(BMEditMesh *em, const short selectmode_old, const s
BM_edge_select_set(em->bm, eed, TRUE);
}
}
- }
+ }
else if (selectmode_new == SCE_SELECT_FACE) {
BMIter liter;
BMLoop *l;
@@ -2163,11 +2184,19 @@ static void walker_deselect_nth(BMEditMesh *em, int nth, int offset, BMHeader *h
BMW_FLAG_NOP, /* don't use BMW_FLAG_TEST_HIDDEN here since we want to desel all */
BMW_NIL_LAY);
+ /* use tag to avoid touching the same verts twice */
+ BM_ITER_MESH (ele, &iter, bm, itertype) {
+ BM_elem_flag_disable(ele, BM_ELEM_TAG);
+ }
+
BLI_assert(walker.order == BMW_BREADTH_FIRST);
for (ele = BMW_begin(&walker, h_act); ele != NULL; ele = BMW_step(&walker)) {
- /* Deselect elements that aren't at "nth" depth from active */
- if ((offset + BMW_current_depth(&walker)) % nth) {
- BM_elem_select_set(bm, ele, FALSE);
+ if (!BM_elem_flag_test(ele, BM_ELEM_TAG)) {
+ /* Deselect elements that aren't at "nth" depth from active */
+ if ((offset + BMW_current_depth(&walker)) % nth) {
+ BM_elem_select_set(bm, ele, FALSE);
+ }
+ BM_elem_flag_enable(ele, BM_ELEM_TAG);
}
}
BMW_end(&walker);
@@ -2279,9 +2308,9 @@ static int edbm_select_nth_exec(bContext *C, wmOperator *op)
void MESH_OT_select_nth(wmOperatorType *ot)
{
/* identifiers */
- ot->name = "Select Nth";
+ ot->name = "Checker Deselect";
ot->idname = "MESH_OT_select_nth";
- ot->description = "Select every Nth element starting from a selected vertex, edge or face";
+ ot->description = "Deselect every Nth element starting from a selected vertex, edge or face";
/* api callbacks */
ot->exec = edbm_select_nth_exec;
@@ -2290,8 +2319,8 @@ void MESH_OT_select_nth(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- RNA_def_int(ot->srna, "nth", 2, 2, 100, "Nth Selection", "", 1, INT_MAX);
- RNA_def_int(ot->srna, "offset", 0, 0, 100, "Offset", "", 0, INT_MAX);
+ RNA_def_int(ot->srna, "nth", 2, 2, INT_MAX, "Nth Selection", "", 2, 100);
+ RNA_def_int(ot->srna, "offset", 0, 0, INT_MAX, "Offset", "", 0, 100);
}
void em_setup_viewcontext(bContext *C, ViewContext *vc)
@@ -2462,7 +2491,7 @@ static int edbm_select_non_manifold_exec(bContext *C, wmOperator *op)
*/
if (em->selectmode == SCE_SELECT_FACE) {
- BKE_report(op->reports, RPT_ERROR, "Doesn't work in face selection mode");
+ BKE_report(op->reports, RPT_ERROR, "Does not work in face selection mode");
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/mesh/editmesh_slide.c b/source/blender/editors/mesh/editmesh_slide.c
index 86ea5bc8651..d370b5a881e 100644
--- a/source/blender/editors/mesh/editmesh_slide.c
+++ b/source/blender/editors/mesh/editmesh_slide.c
@@ -34,6 +34,8 @@
#include "BLI_array.h"
#include "BLI_math.h"
+#include "BLF_translation.h"
+
#include "BKE_context.h"
#include "BKE_report.h"
#include "BKE_tessmesh.h"
@@ -113,11 +115,11 @@ static int vtx_slide_init(bContext *C, wmOperator *op)
/* Custom data */
VertexSlideOp *vso;
- const char *header_str = "Vertex Slide: Hover over an edge and left-click to select slide edge. "
- "Left-Shift: Midpoint Snap, Left-Alt: Snap, Left-Ctrl: Snap&Merge";
+ const char *header_str = TIP_("Vertex Slide: Hover over an edge and left-click to select slide edge. "
+ "Left-Shift: Midpoint Snap, Left-Alt: Snap, Left-Ctrl: Snap & Merge");
if (!obedit) {
- BKE_report(op->reports, RPT_ERROR, "Vertex Slide Error: Not object in context");
+ BKE_report(op->reports, RPT_ERROR, "Vertex slide error: no object in context");
return FALSE;
}
@@ -126,7 +128,7 @@ static int vtx_slide_init(bContext *C, wmOperator *op)
/* Is there a starting vertex ? */
if (ese == NULL || (ese->htype != BM_VERT && ese->htype != BM_EDGE)) {
- BKE_report(op->reports, RPT_ERROR_INVALID_INPUT, "Vertex Slide Error: Select a (single) vertex");
+ BKE_report(op->reports, RPT_ERROR_INVALID_INPUT, "Vertex slide error: select a (single) vertex");
return FALSE;
}
@@ -177,7 +179,7 @@ static int vtx_slide_init(bContext *C, wmOperator *op)
/* Init frame */
if (!vtx_slide_set_frame(vso)) {
- BKE_report(op->reports, RPT_ERROR_INVALID_INPUT, "Vertex Slide: Can't find starting vertex!");
+ BKE_report(op->reports, RPT_ERROR_INVALID_INPUT, "Vertex slide error: cannot find starting vertex!");
vtx_slide_exit(C, op);
return FALSE;
}
@@ -381,22 +383,23 @@ static BMEdge *vtx_slide_nrst_in_frame(VertexSlideOp *vso, const float mval[2])
BMEdge *edge = NULL;
float v1_proj[3], v2_proj[3];
- float dist = 0;
float min_dist = FLT_MAX;
for (i = 0; i < vso->disk_edges; i++) {
edge = vso->edge_frame[i];
mul_v3_m4v3(v1_proj, vso->obj->obmat, edge->v1->co);
- project_float_noclip(vso->active_region, v1_proj, v1_proj);
-
mul_v3_m4v3(v2_proj, vso->obj->obmat, edge->v2->co);
- project_float_noclip(vso->active_region, v2_proj, v2_proj);
- dist = dist_to_line_segment_v2(mval, v1_proj, v2_proj);
- if (dist < min_dist) {
- min_dist = dist;
- cl_edge = edge;
+ /* we could use ED_view3d_project_float_object here, but for now dont since we dont have the context */
+ if ((ED_view3d_project_float_global(vso->active_region, v1_proj, v1_proj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
+ (ED_view3d_project_float_global(vso->active_region, v2_proj, v2_proj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
+ {
+ const float dist = dist_to_line_segment_v2(mval, v1_proj, v2_proj);
+ if (dist < min_dist) {
+ min_dist = dist;
+ cl_edge = edge;
+ }
}
}
}
@@ -408,7 +411,8 @@ static void vtx_slide_find_edge(VertexSlideOp *vso, wmEvent *event)
/* Nearest edge */
BMEdge *nst_edge = NULL;
- const float mval_float[] = { (float)event->mval[0], (float)event->mval[1]};
+ const float mval_float[2] = {(float)event->mval[0],
+ (float)event->mval[1]};
/* Set mouse coords */
copy_v2_v2_int(vso->view_context->mval, event->mval);
@@ -448,17 +452,21 @@ static void vtx_slide_update(VertexSlideOp *vso, wmEvent *event)
/* Calculate interpolation value for preview */
float t_val;
- float mval_float[] = { (float)event->mval[0], (float)event->mval[1]};
+ float mval_float[2] = { (float)event->mval[0], (float)event->mval[1]};
float closest_2d[2];
other = BM_edge_other_vert(edge, vso->start_vtx);
/* Project points onto screen and do interpolation in 2D */
mul_v3_m4v3(start_vtx_proj, vso->obj->obmat, vso->start_vtx->co);
- project_float_noclip(vso->active_region, start_vtx_proj, start_vtx_proj);
-
mul_v3_m4v3(edge_other_proj, vso->obj->obmat, other->co);
- project_float_noclip(vso->active_region, edge_other_proj, edge_other_proj);
+
+ if ((ED_view3d_project_float_global(vso->active_region, edge_other_proj, edge_other_proj, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) ||
+ (ED_view3d_project_float_global(vso->active_region, start_vtx_proj, start_vtx_proj, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK))
+ {
+ /* not much we can do here */
+ return;
+ }
closest_to_line_v2(closest_2d, mval_float, start_vtx_proj, edge_other_proj);
@@ -470,7 +478,7 @@ static void vtx_slide_update(VertexSlideOp *vso, wmEvent *event)
if (edge_len <= 0.0f)
edge_len = VTX_SLIDE_SNAP_THRSH;
- edge_len = (len_v3v3(edge->v1->co, edge->v2->co) * VTX_SLIDE_SNAP_THRSH) / edge_len;
+ edge_len = (BM_edge_calc_length(edge) * VTX_SLIDE_SNAP_THRSH) / edge_len;
vso->snap_threshold = edge_len;
@@ -713,7 +721,7 @@ static int edbm_vertex_slide_exec_ex(bContext *C, wmOperator *op, const int do_u
/* Is there a starting vertex ? */
if ((ese == NULL) || (ese->htype != BM_VERT && ese->htype != BM_EDGE)) {
- BKE_report(op->reports, RPT_ERROR_INVALID_INPUT, "Vertex Slide Error: Select a (single) vertex");
+ BKE_report(op->reports, RPT_ERROR_INVALID_INPUT, "Vertex slide error: select a (single) vertex");
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/mesh/editmesh_tools.c b/source/blender/editors/mesh/editmesh_tools.c
index 546b28bfb25..f10faddc169 100644
--- a/source/blender/editors/mesh/editmesh_tools.c
+++ b/source/blender/editors/mesh/editmesh_tools.c
@@ -41,7 +41,9 @@
#include "RNA_define.h"
#include "RNA_access.h"
+#include "BLI_array.h"
#include "BLI_blenlib.h"
+#include "BLI_noise.h"
#include "BLI_math.h"
#include "BLI_rand.h"
@@ -49,6 +51,7 @@
#include "BKE_context.h"
#include "BKE_cdderivedmesh.h"
#include "BKE_depsgraph.h"
+#include "BKE_mesh.h"
#include "BKE_object.h"
#include "BKE_report.h"
#include "BKE_texture.h"
@@ -72,6 +75,8 @@
#include "mesh_intern.h"
+#define MVAL_PIXEL_MARGIN 5.0f
+
/* allow accumulated normals to form a new direction but don't
* accept direct opposite directions else they will cancel each other out */
static void add_normal_aligned(float nor[3], const float add[3])
@@ -153,19 +158,67 @@ void MESH_OT_subdivide(wmOperatorType *ot)
}
-void EMBM_project_snap_verts(bContext *C, ARegion *ar, Object *obedit, BMEditMesh *em)
+static int edbm_unsubdivide_exec(bContext *C, wmOperator *op)
{
+ Object *obedit = CTX_data_edit_object(C);
+ BMEditMesh *em = BMEdit_FromObject(obedit);
+ BMOperator bmop;
+
+ int iterations = RNA_int_get(op->ptr, "iterations");
+
+ EDBM_op_init(em, &bmop, op,
+ "unsubdivide verts=%hv iterations=%i", BM_ELEM_SELECT, iterations);
+
+ BMO_op_exec(em->bm, &bmop);
+
+ if (!EDBM_op_finish(em, &bmop, op, TRUE)) {
+ return 0;
+ }
+
+ if ((em->selectmode & SCE_SELECT_VERTEX) == 0) {
+ EDBM_selectmode_flush_ex(em, SCE_SELECT_VERTEX); /* need to flush vert->face first */
+ }
+ EDBM_selectmode_flush(em);
+
+ EDBM_update_generic(C, em, TRUE);
+
+ return OPERATOR_FINISHED;
+}
+
+void MESH_OT_unsubdivide(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Un-Subdivide";
+ ot->description = "UnSubdivide selected edges & faces";
+ ot->idname = "MESH_OT_unsubdivide";
+
+ /* api callbacks */
+ ot->exec = edbm_unsubdivide_exec;
+ ot->poll = ED_operator_editmesh;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* props */
+ RNA_def_int(ot->srna, "iterations", 2, 1, INT_MAX, "Iterations", "Number of times to unsubdivide", 1, 100);
+}
+
+void EMBM_project_snap_verts(bContext *C, ARegion *ar, BMEditMesh *em)
+{
+ Object *obedit = em->ob;
BMIter iter;
BMVert *eve;
+ ED_view3d_init_mats_rv3d(obedit, ar->regiondata);
+
BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
- float mval[2], vec[3], no_dummy[3];
+ float mval[2], co_proj[3], no_dummy[3];
int dist_dummy;
- mul_v3_m4v3(vec, obedit->obmat, eve->co);
- project_float_noclip(ar, vec, mval);
- if (snapObjectsContext(C, mval, &dist_dummy, vec, no_dummy, SNAP_NOT_OBEDIT)) {
- mul_v3_m4v3(eve->co, obedit->imat, vec);
+ if (ED_view3d_project_float_object(ar, eve->co, mval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ if (snapObjectsContext(C, mval, &dist_dummy, co_proj, no_dummy, SNAP_NOT_OBEDIT)) {
+ mul_v3_m4v3(eve->co, obedit->imat, co_proj);
+ }
}
}
}
@@ -202,7 +255,7 @@ static short edbm_extrude_discrete_faces(BMEditMesh *em, wmOperator *op, const c
return 0;
}
- return 's'; // s is shrink/fatten
+ return 's'; /* s is shrink/fatten */
}
/* extrudes individual edges */
@@ -222,7 +275,7 @@ static short edbm_extrude_edges_indiv(BMEditMesh *em, wmOperator *op, const char
return 0;
}
- return 'n'; // n is normal grab
+ return 'n'; /* n is normal grab */
}
/* extrudes individual vertices */
@@ -242,7 +295,7 @@ static short edbm_extrude_verts_indiv(BMEditMesh *em, wmOperator *op, const char
return 0;
}
- return 'g'; // g is grab
+ return 'g'; /* g is grab */
}
static short edbm_extrude_edge(Object *obedit, BMEditMesh *em, const char hflag, float nor[3])
@@ -426,8 +479,8 @@ void MESH_OT_extrude_repeat(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* props */
- RNA_def_float(ot->srna, "offset", 2.0f, 0.0f, 100.0f, "Offset", "", 0.0f, FLT_MAX);
- RNA_def_int(ot->srna, "steps", 10, 0, 180, "Steps", "", 0, INT_MAX);
+ RNA_def_float(ot->srna, "offset", 2.0f, 0.0f, FLT_MAX, "Offset", "", 0.0f, 100.0f);
+ RNA_def_int(ot->srna, "steps", 10, 0, INT_MAX, "Steps", "", 0, 180);
}
/* generic extern called extruder */
@@ -439,16 +492,17 @@ static int edbm_extrude_mesh(Scene *scene, Object *obedit, BMEditMesh *em, wmOpe
zero_v3(nor);
+ /* XXX If those popup menus were to be enabled again, please get rid of this "menu string" syntax! */
if (em->selectmode & SCE_SELECT_VERTEX) {
if (em->bm->totvertsel == 0) nr = 0;
else if (em->bm->totvertsel == 1) nr = 4;
else if (em->bm->totedgesel == 0) nr = 4;
else if (em->bm->totfacesel == 0)
- nr = 3; // pupmenu("Extrude %t|Only Edges%x3|Only Vertices%x4");
+ nr = 3; /* pupmenu("Extrude %t|Only Edges %x3|Only Vertices %x4"); */
else if (em->bm->totfacesel == 1)
- nr = 1; // pupmenu("Extrude %t|Region %x1|Only Edges%x3|Only Vertices%x4");
+ nr = 1; /* pupmenu("Extrude %t|Region %x1|Only Edges% x3|Only Vertices %x4"); */
else
- nr = 1; // pupmenu("Extrude %t|Region %x1||Individual Faces %x2|Only Edges%x3|Only Vertices%x4");
+ nr = 1; /* pupmenu("Extrude %t|Region %x1|Individual Faces %x2|Only Edges %x3|Only Vertices %x4"); */
}
else if (em->selectmode & SCE_SELECT_EDGE) {
if (em->bm->totedgesel == 0) nr = 0;
@@ -458,16 +512,16 @@ static int edbm_extrude_mesh(Scene *scene, Object *obedit, BMEditMesh *em, wmOpe
else if (em->totedgesel == 1) nr = 3;
else if (em->totfacesel == 0) nr = 3;
else if (em->totfacesel == 1)
- nr = 1; // pupmenu("Extrude %t|Region %x1|Only Edges%x3");
+ nr = 1; /* pupmenu("Extrude %t|Region %x1|Only Edges %x3"); */
else
- nr = 1; // pupmenu("Extrude %t|Region %x1||Individual Faces %x2|Only Edges%x3");
+ nr = 1; /* pupmenu("Extrude %t|Region %x1|Individual Faces %x2|Only Edges %x3"); */
#endif
}
else {
if (em->bm->totfacesel == 0) nr = 0;
else if (em->bm->totfacesel == 1) nr = 1;
else
- nr = 1; // pupmenu("Extrude %t|Region %x1||Individual Faces %x2");
+ nr = 1; /* pupmenu("Extrude %t|Region %x1|Individual Faces %x2"); */
}
if (nr < 1) return 'g';
@@ -730,7 +784,10 @@ static int edbm_dupli_extrude_cursor_invoke(bContext *C, wmOperator *op, wmEvent
short use_proj;
em_setup_viewcontext(C, &vc);
-
+
+ ED_view3d_init_mats_rv3d(vc.obedit, vc.rv3d);
+
+
use_proj = ((vc.scene->toolsettings->snap_flag & SCE_SNAP) &&
(vc.scene->toolsettings->snap_mode == SCE_SNAP_MODE_FACE));
@@ -758,27 +815,27 @@ static int edbm_dupli_extrude_cursor_invoke(bContext *C, wmOperator *op, wmEvent
done = FALSE;
BM_ITER_MESH (eed, &iter, vc.em->bm, BM_EDGES_OF_MESH) {
if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
- float co1[3], co2[3];
- mul_v3_m4v3(co1, vc.obedit->obmat, eed->v1->co);
- mul_v3_m4v3(co2, vc.obedit->obmat, eed->v2->co);
- project_float_noclip(vc.ar, co1, co1);
- project_float_noclip(vc.ar, co2, co2);
-
- /* 2D rotate by 90d while adding.
- * (x, y) = (y, -x)
- *
- * accumulate the screenspace normal in 2D,
- * with screenspace edge length weighting the result. */
- if (line_point_side_v2(co1, co2, mval_f) >= 0.0f) {
- nor[0] += (co1[1] - co2[1]);
- nor[1] += -(co1[0] - co2[0]);
- }
- else {
- nor[0] += (co2[1] - co1[1]);
- nor[1] += -(co2[0] - co1[0]);
+ float co1[2], co2[2];
+
+ if ((ED_view3d_project_float_object(vc.ar, eed->v1->co, co1, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
+ (ED_view3d_project_float_object(vc.ar, eed->v2->co, co2, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
+ {
+ /* 2D rotate by 90d while adding.
+ * (x, y) = (y, -x)
+ *
+ * accumulate the screenspace normal in 2D,
+ * with screenspace edge length weighting the result. */
+ if (line_point_side_v2(co1, co2, mval_f) >= 0.0f) {
+ nor[0] += (co1[1] - co2[1]);
+ nor[1] += -(co1[0] - co2[0]);
+ }
+ else {
+ nor[0] += (co2[1] - co1[1]);
+ nor[1] += -(co2[0] - co1[0]);
+ }
+ done = TRUE;
}
}
- done = TRUE;
}
if (done) {
@@ -835,7 +892,7 @@ static int edbm_dupli_extrude_cursor_invoke(bContext *C, wmOperator *op, wmEvent
/* also project the source, for retopo workflow */
if (use_proj)
- EMBM_project_snap_verts(C, vc.ar, vc.obedit, vc.em);
+ EMBM_project_snap_verts(C, vc.ar, vc.em);
}
edbm_extrude_edge(vc.obedit, vc.em, BM_ELEM_SELECT, nor);
@@ -868,7 +925,7 @@ static int edbm_dupli_extrude_cursor_invoke(bContext *C, wmOperator *op, wmEvent
}
if (use_proj)
- EMBM_project_snap_verts(C, vc.ar, vc.obedit, vc.em);
+ EMBM_project_snap_verts(C, vc.ar, vc.em);
/* This normally happens when pushing undo but modal operators
* like this one don't push undo data until after modal mode is
@@ -1208,10 +1265,13 @@ static int edbm_vert_connect(bContext *C, wmOperator *op)
if (!EDBM_op_finish(em, &bmop, op, TRUE)) {
return OPERATOR_CANCELLED;
}
-
- EDBM_update_generic(C, em, TRUE);
+ else {
+ EDBM_selectmode_flush(em); /* so newly created edges get the selection state from the vertex */
- return len ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
+ EDBM_update_generic(C, em, TRUE);
+
+ return len ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
+ }
}
void MESH_OT_vert_connect(wmOperatorType *ot)
@@ -1600,12 +1660,94 @@ void MESH_OT_vertices_smooth(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- RNA_def_int(ot->srna, "repeat", 1, 1, 100, "Number of times to smooth the mesh", "", 1, INT_MAX);
+ RNA_def_int(ot->srna, "repeat", 1, 1, 1000, "Number of times to smooth the mesh", "", 1, 100);
RNA_def_boolean(ot->srna, "xaxis", 1, "X-Axis", "Smooth along the X axis");
RNA_def_boolean(ot->srna, "yaxis", 1, "Y-Axis", "Smooth along the Y axis");
RNA_def_boolean(ot->srna, "zaxis", 1, "Z-Axis", "Smooth along the Z axis");
}
+static int edbm_do_smooth_laplacian_vertex_exec(bContext *C, wmOperator *op)
+{
+ Object *obedit = CTX_data_edit_object(C);
+ BMEditMesh *em = BMEdit_FromObject(obedit);
+ int usex = TRUE, usey = TRUE, usez = TRUE, volume_preservation = TRUE;
+ int i, repeat;
+ float lambda;
+ float lambda_border;
+ BMIter fiter;
+ BMFace *f;
+
+ /* Check if select faces are triangles */
+ BM_ITER_MESH (f, &fiter, em->bm, BM_FACES_OF_MESH) {
+ if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
+ if (f->len > 4) {
+ BKE_report(op->reports, RPT_WARNING, "Selected faces must be triangles or quads");
+ return OPERATOR_CANCELLED;
+ }
+ }
+ }
+
+ /* mirror before smooth */
+ if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
+ EDBM_verts_mirror_cache_begin(em, TRUE);
+ }
+
+ repeat = RNA_int_get(op->ptr, "repeat");
+ lambda = RNA_float_get(op->ptr, "lambda");
+ lambda_border = RNA_float_get(op->ptr, "lambda_border");
+ usex = RNA_boolean_get(op->ptr, "use_x");
+ usey = RNA_boolean_get(op->ptr, "use_y");
+ usez = RNA_boolean_get(op->ptr, "use_z");
+ volume_preservation = RNA_boolean_get(op->ptr, "volume_preservation");
+ if (!repeat)
+ repeat = 1;
+
+ for (i = 0; i < repeat; i++) {
+ if (!EDBM_op_callf(em, op,
+ "smooth_laplacian_vert verts=%hv lambda=%f lambda_border=%f use_x=%b use_y=%b use_z=%b volume_preservation=%b",
+ BM_ELEM_SELECT, lambda, lambda_border, usex, usey, usez, volume_preservation))
+ {
+ return OPERATOR_CANCELLED;
+ }
+ }
+
+ /* apply mirror */
+ if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
+ EDBM_verts_mirror_apply(em, BM_ELEM_SELECT, 0);
+ EDBM_verts_mirror_cache_end(em);
+ }
+
+ EDBM_update_generic(C, em, TRUE);
+
+ return OPERATOR_FINISHED;
+}
+
+void MESH_OT_vertices_smooth_laplacian(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Laplacian Smooth Vertex";
+ ot->description = "Laplacian smooth of selected vertices";
+ ot->idname = "MESH_OT_vertices_smooth_laplacian";
+
+ /* api callbacks */
+ ot->exec = edbm_do_smooth_laplacian_vertex_exec;
+ ot->poll = ED_operator_editmesh;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ RNA_def_int(ot->srna, "repeat", 1, 1, 200,
+ "Number of iterations to smooth the mesh", "", 1, 200);
+ RNA_def_float(ot->srna, "lambda", 0.00005f, 0.0000001f, 1000.0f,
+ "Lambda factor", "", 0.0000001f, 1000.0f);
+ RNA_def_float(ot->srna, "lambda_border", 0.00005f, 0.0000001f, 1000.0f,
+ "Lambda factor in border", "", 0.0000001f, 1000.0f);
+ RNA_def_boolean(ot->srna, "use_x", 1, "Smooth X Axis", "Smooth object along X axis");
+ RNA_def_boolean(ot->srna, "use_y", 1, "Smooth Y Axis", "Smooth object along Y axis");
+ RNA_def_boolean(ot->srna, "use_z", 1, "Smooth Z Axis", "Smooth object along Z axis");
+ RNA_def_boolean(ot->srna, "volume_preservation", 1, "Preserve Volume", "Apply volume preservation after smooth");
+}
+
/********************** Smooth/Solid Operators *************************/
static void mesh_set_smooth_faces(BMEditMesh *em, short smooth)
@@ -2073,7 +2215,7 @@ static int edbm_remove_doubles_exec(bContext *C, wmOperator *op)
}
count = totvert_orig - em->bm->totvert;
- BKE_reportf(op->reports, RPT_INFO, "Removed %d vert%s", count, (count == 1) ? "ex" : "ices");
+ BKE_reportf(op->reports, RPT_INFO, "Removed %d vertices", count);
EDBM_update_generic(C, em, TRUE);
@@ -2140,7 +2282,7 @@ static int edbm_select_vertex_path_exec(bContext *C, wmOperator *op)
}
/* if those are not found, because vertices where selected by e.g.
- border or circle select, find two selected vertices */
+ * border or circle select, find two selected vertices */
if (svert == NULL) {
BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
@@ -2150,7 +2292,7 @@ static int edbm_select_vertex_path_exec(bContext *C, wmOperator *op)
else if (evert == NULL) evert = eve;
else {
/* more than two vertices are selected,
- show warning message and cancel operator */
+ * show warning message and cancel operator */
svert = evert = NULL;
break;
}
@@ -2158,7 +2300,7 @@ static int edbm_select_vertex_path_exec(bContext *C, wmOperator *op)
}
if (svert == NULL || evert == NULL) {
- BKE_report(op->reports, RPT_WARNING, "Path Selection requires that two vertices be selected");
+ BKE_report(op->reports, RPT_WARNING, "Path selection requires two vertices to be selected");
return OPERATOR_CANCELLED;
}
@@ -2526,17 +2668,6 @@ void MESH_OT_solidify(wmOperatorType *ot)
RNA_def_property_ui_range(prop, -10, 10, 0.1, 4);
}
-#define TRAIL_POLYLINE 1 /* For future use, They don't do anything yet */
-#define TRAIL_FREEHAND 2
-#define TRAIL_MIXED 3 /* (1|2) */
-#define TRAIL_AUTO 4
-#define TRAIL_MIDPOINTS 8
-
-typedef struct CutCurve {
- float x;
- float y;
-} CutCurve;
-
/* ******************************************************************** */
/* Knife Subdivide Tool. Subdivides edges intersected by a mouse trail
* drawn by user.
@@ -2570,15 +2701,14 @@ static EnumPropertyItem knife_items[] = {
/* bm_edge_seg_isect() Determines if and where a mouse trail intersects an BMEdge */
-static float bm_edge_seg_isect(BMEdge *e, CutCurve *c, int len, char mode,
- struct GHash *gh, int *isected)
+static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2],
+ float (*mouse_path)[2], int len, char mode, int *isected)
{
#define MAXSLOPE 100000
float x11, y11, x12 = 0, y12 = 0, x2max, x2min, y2max;
float y2min, dist, lastdist = 0, xdiff2, xdiff1;
float m1, b1, m2, b2, x21, x22, y21, y22, xi;
float yi, x1min, x1max, y1max, y1min, perc = 0;
- float *scr;
float threshold = 0.0;
int i;
@@ -2586,13 +2716,11 @@ static float bm_edge_seg_isect(BMEdge *e, CutCurve *c, int len, char mode,
// XXX threshold = scene->toolsettings->select_thresh / 100;
/* Get screen coords of verts */
- scr = BLI_ghash_lookup(gh, e->v1);
- x21 = scr[0];
- y21 = scr[1];
+ x21 = sco_a[0];
+ y21 = sco_a[1];
- scr = BLI_ghash_lookup(gh, e->v2);
- x22 = scr[0];
- y22 = scr[1];
+ x22 = sco_b[0];
+ y22 = sco_b[1];
xdiff2 = (x22 - x21);
if (xdiff2) {
@@ -2614,11 +2742,11 @@ static float bm_edge_seg_isect(BMEdge *e, CutCurve *c, int len, char mode,
y11 = y12;
}
else {
- x11 = c[i].x;
- y11 = c[i].y;
+ x11 = mouse_path[i][0];
+ y11 = mouse_path[i][1];
}
- x12 = c[i].x;
- y12 = c[i].y;
+ x12 = mouse_path[i][0];
+ y12 = mouse_path[i][1];
/* test e->v1 */
if ((x11 == x21 && y11 == y21) || (x12 == x21 && y12 == y21)) {
@@ -2642,11 +2770,11 @@ static float bm_edge_seg_isect(BMEdge *e, CutCurve *c, int len, char mode,
y11 = y12;
}
else {
- x11 = c[i].x;
- y11 = c[i].y;
+ x11 = mouse_path[i][0];
+ y11 = mouse_path[i][1];
}
- x12 = c[i].x;
- y12 = c[i].y;
+ x12 = mouse_path[i][0];
+ y12 = mouse_path[i][1];
/* Perp. Distance from point to line */
if (m2 != MAXSLOPE) dist = (y12 - m2 * x12 - b2); /* /sqrt(m2 * m2 + 1); Only looking for */
@@ -2666,21 +2794,21 @@ static float bm_edge_seg_isect(BMEdge *e, CutCurve *c, int len, char mode,
m1 = MAXSLOPE;
b1 = x12;
}
- x2max = maxf(x21, x22) + 0.001f; /* prevent missed edges */
- x2min = minf(x21, x22) - 0.001f; /* due to round off error */
- y2max = maxf(y21, y22) + 0.001f;
- y2min = minf(y21, y22) - 0.001f;
+ x2max = max_ff(x21, x22) + 0.001f; /* prevent missed edges */
+ x2min = min_ff(x21, x22) - 0.001f; /* due to round off error */
+ y2max = max_ff(y21, y22) + 0.001f;
+ y2min = min_ff(y21, y22) - 0.001f;
/* Found an intersect, calc intersect point */
if (m1 == m2) { /* co-incident lines */
/* cut at 50% of overlap area */
- x1max = maxf(x11, x12);
- x1min = minf(x11, x12);
- xi = (minf(x2max, x1max) + maxf(x2min, x1min)) / 2.0f;
+ x1max = max_ff(x11, x12);
+ x1min = min_ff(x11, x12);
+ xi = (min_ff(x2max, x1max) + max_ff(x2min, x1min)) / 2.0f;
- y1max = maxf(y11, y12);
- y1min = minf(y11, y12);
- yi = (minf(y2max, y1max) + maxf(y2min, y1min)) / 2.0f;
+ y1max = max_ff(y11, y12);
+ y1min = min_ff(y11, y12);
+ yi = (min_ff(y2max, y1max) + max_ff(y2min, y1min)) / 2.0f;
}
else if (m2 == MAXSLOPE) {
xi = x22;
@@ -2720,13 +2848,13 @@ static float bm_edge_seg_isect(BMEdge *e, CutCurve *c, int len, char mode,
break;
}
- }
+ }
lastdist = dist;
}
return perc;
-}
+}
-#define MAX_CUTS 2048
+#define ELE_EDGE_CUT 1
static int edbm_knife_cut_exec(bContext *C, wmOperator *op)
{
@@ -2738,76 +2866,93 @@ static int edbm_knife_cut_exec(bContext *C, wmOperator *op)
BMIter iter;
BMEdge *be;
BMOperator bmop;
- CutCurve curve[MAX_CUTS];
- struct GHash *gh;
float isect = 0.0f;
- float *scr, co[4];
- int len = 0, isected;
+ int len = 0, isected, i;
short numcuts = 1, mode = RNA_int_get(op->ptr, "type");
+
+ /* allocd vars */
+ float (*screen_vert_coords)[2], (*sco)[2], (*mouse_path)[2];
/* edit-object needed for matrix, and ar->regiondata for projections to work */
if (ELEM3(NULL, obedit, ar, ar->regiondata))
return OPERATOR_CANCELLED;
if (bm->totvertsel < 2) {
- //error("No edges are selected to operate on");
+ BKE_report(op->reports, RPT_ERROR, "No edges are selected to operate on");
+ return OPERATOR_CANCELLED;
+ }
+
+ len = RNA_collection_length(op->ptr, "path");
+
+ if (len < 2) {
+ BKE_report(op->reports, RPT_ERROR, "Mouse path too short");
return OPERATOR_CANCELLED;
}
+ mouse_path = MEM_mallocN(len * sizeof(*mouse_path), __func__);
+
/* get the cut curve */
RNA_BEGIN(op->ptr, itemptr, "path")
{
- RNA_float_get_array(&itemptr, "loc", (float *)&curve[len]);
- len++;
- if (len >= MAX_CUTS) {
- break;
- }
+ RNA_float_get_array(&itemptr, "loc", (float *)&mouse_path[len]);
}
RNA_END;
-
- if (len < 2) {
- return OPERATOR_CANCELLED;
- }
+
+ /* for ED_view3d_project_float_object */
+ ED_view3d_init_mats_rv3d(obedit, ar->regiondata);
+
+ /* TODO, investigate using index lookup for screen_vert_coords() rather then a hash table */
/* the floating point coordinates of verts in screen space will be stored in a hash table according to the vertices pointer */
- gh = BLI_ghash_ptr_new("knife cut exec");
- for (bv = BM_iter_new(&iter, bm, BM_VERTS_OF_MESH, NULL); bv; bv = BM_iter_step(&iter)) {
- scr = MEM_mallocN(sizeof(float) * 2, "Vertex Screen Coordinates");
- copy_v3_v3(co, bv->co);
- co[3] = 1.0f;
- mul_m4_v4(obedit->obmat, co);
- project_float(ar, co, scr);
- BLI_ghash_insert(gh, bv, scr);
+ screen_vert_coords = sco = MEM_mallocN(bm->totvert * sizeof(float) * 2, __func__);
+
+ BM_ITER_MESH_INDEX (bv, &iter, bm, BM_VERTS_OF_MESH, i) {
+ if (ED_view3d_project_float_object(ar, bv->co, *sco, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
+ copy_v2_fl(*sco, FLT_MAX); /* set error value */
+ }
+ BM_elem_index_set(bv, i); /* set_ok */
+ sco++;
+
}
+ bm->elem_index_dirty &= ~BM_VERT; /* clear dirty flag */
if (!EDBM_op_init(em, &bmop, op, "subdivide_edges")) {
+ MEM_freeN(mouse_path);
+ MEM_freeN(screen_vert_coords);
return OPERATOR_CANCELLED;
}
/* store percentage of edge cut for KNIFE_EXACT here.*/
for (be = BM_iter_new(&iter, bm, BM_EDGES_OF_MESH, NULL); be; be = BM_iter_step(&iter)) {
+ int is_cut = FALSE;
if (BM_elem_flag_test(be, BM_ELEM_SELECT)) {
- isect = bm_edge_seg_isect(be, curve, len, mode, gh, &isected);
-
- if (isect != 0.0f) {
- if (mode != KNIFE_MULTICUT && mode != KNIFE_MIDPOINT) {
- BMO_slot_map_float_insert(bm, &bmop,
- "edgepercents",
- be, isect);
-
+ const float *sco_a = screen_vert_coords[BM_elem_index_get(be->v1)];
+ const float *sco_b = screen_vert_coords[BM_elem_index_get(be->v2)];
+
+ /* check for error value (vert cant be projected) */
+ if ((sco_a[0] != FLT_MAX) && (sco_b[0] != FLT_MAX)) {
+ isect = bm_edge_seg_isect(sco_a, sco_b, mouse_path, len, mode, &isected);
+
+ if (isect != 0.0f) {
+ if (mode != KNIFE_MULTICUT && mode != KNIFE_MIDPOINT) {
+ BMO_slot_map_float_insert(bm, &bmop,
+ "edgepercents",
+ be, isect);
+ }
}
- BMO_elem_flag_enable(bm, be, 1);
}
- else {
- BMO_elem_flag_disable(bm, be, 1);
- }
- }
- else {
- BMO_elem_flag_disable(bm, be, 1);
}
+
+ BMO_elem_flag_set(bm, be, ELE_EDGE_CUT, is_cut);
}
-
- BMO_slot_buffer_from_enabled_flag(bm, &bmop, "edges", BM_EDGE, 1);
+
+
+ /* free all allocs */
+ MEM_freeN(screen_vert_coords);
+ MEM_freeN(mouse_path);
+
+
+ BMO_slot_buffer_from_enabled_flag(bm, &bmop, "edges", BM_EDGE, ELE_EDGE_CUT);
if (mode == KNIFE_MIDPOINT) numcuts = 1;
BMO_slot_int_set(&bmop, "numcuts", numcuts);
@@ -2822,14 +2967,14 @@ static int edbm_knife_cut_exec(bContext *C, wmOperator *op)
if (!EDBM_op_finish(em, &bmop, op, TRUE)) {
return OPERATOR_CANCELLED;
}
-
- BLI_ghash_free(gh, NULL, (GHashValFreeFP)MEM_freeN);
EDBM_update_generic(C, em, TRUE);
return OPERATOR_FINISHED;
}
+#undef ELE_EDGE_CUT
+
void MESH_OT_knife_cut(wmOperatorType *ot)
{
PropertyRNA *prop;
@@ -2858,9 +3003,6 @@ void MESH_OT_knife_cut(wmOperatorType *ot)
static int mesh_separate_tagged(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old)
{
Base *base_new;
- BMIter iter;
- BMVert *v;
- BMEdge *e;
Object *obedit = base_old->object;
BMesh *bm_new;
@@ -2886,15 +3028,10 @@ static int mesh_separate_tagged(Main *bmain, Scene *scene, Base *base_old, BMesh
BMO_op_callf(bm_old, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
"delete geom=%hvef context=%i", BM_ELEM_TAG, DEL_FACES);
- /* deselect loose data - this used to get deleted */
- BM_ITER_MESH (e, &iter, bm_old, BM_EDGES_OF_MESH) {
- BM_edge_select_set(bm_old, e, FALSE);
- }
-
- /* clean up any loose verts */
- BM_ITER_MESH (v, &iter, bm_old, BM_VERTS_OF_MESH) {
- BM_vert_select_set(bm_old, v, FALSE);
- }
+ /* deselect loose data - this used to get deleted,
+ * we could de-select edges and verts only, but this turns out to be less complicated
+ * since de-selecting all skips selection flushing logic */
+ BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, FALSE);
BM_mesh_normals_update(bm_new, FALSE);
@@ -2908,7 +3045,10 @@ static int mesh_separate_tagged(Main *bmain, Scene *scene, Base *base_old, BMesh
static int mesh_separate_selected(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old)
{
- /* tag -> select */
+ /* we may have tags from previous operators */
+ BM_mesh_elem_hflag_disable_all(bm_old, BM_FACE | BM_EDGE | BM_VERT, BM_ELEM_TAG, FALSE);
+
+ /* sel -> tag */
BM_mesh_elem_hflag_enable_test(bm_old, BM_FACE | BM_EDGE | BM_VERT, BM_ELEM_TAG, TRUE, BM_ELEM_SELECT);
return mesh_separate_tagged(bmain, scene, base_old, bm_old);
@@ -3073,7 +3213,7 @@ static int edbm_separate_exec(bContext *C, wmOperator *op)
}
else {
if (type == 0) {
- BKE_report(op->reports, RPT_ERROR, "Selecton not supported in object mode");
+ BKE_report(op->reports, RPT_ERROR, "Selection not supported in object mode");
return OPERATOR_CANCELLED;
}
@@ -3354,7 +3494,8 @@ static int edbm_dissolve_limited_exec(bContext *C, wmOperator *op)
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BMEdit_FromObject(obedit);
BMesh *bm = em->bm;
- float angle_limit = RNA_float_get(op->ptr, "angle_limit");
+ const float angle_limit = RNA_float_get(op->ptr, "angle_limit");
+ const int use_dissolve_boundaries = RNA_boolean_get(op->ptr, "use_dissolve_boundaries");
char dissolve_flag;
@@ -3390,8 +3531,8 @@ static int edbm_dissolve_limited_exec(bContext *C, wmOperator *op)
}
if (!EDBM_op_callf(em, op,
- "dissolve_limit edges=%he verts=%hv angle_limit=%f",
- dissolve_flag, dissolve_flag, angle_limit))
+ "dissolve_limit edges=%he verts=%hv angle_limit=%f use_dissolve_boundaries=%b",
+ dissolve_flag, dissolve_flag, angle_limit, use_dissolve_boundaries))
{
return OPERATOR_CANCELLED;
}
@@ -3418,8 +3559,10 @@ void MESH_OT_dissolve_limited(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
prop = RNA_def_float_rotation(ot->srna, "angle_limit", 0, NULL, 0.0f, DEG2RADF(180.0f),
- "Max Angle", "Angle Limit in Degrees", 0.0f, DEG2RADF(180.0f));
+ "Max Angle", "Angle limit", 0.0f, DEG2RADF(180.0f));
RNA_def_property_float_default(prop, DEG2RADF(15.0f));
+ RNA_def_boolean(ot->srna, "use_dissolve_boundaries", 0, "All Boundaries",
+ "Dissolve all vertices inbetween face boundaries");
}
static int edbm_split_exec(bContext *C, wmOperator *op)
@@ -3537,7 +3680,7 @@ void MESH_OT_spin(wmOperatorType *ot)
RNA_def_float(ot->srna, "degrees", 90.0f, -FLT_MAX, FLT_MAX, "Degrees", "Degrees", -360.0f, 360.0f);
RNA_def_float_vector(ot->srna, "center", 3, NULL, -FLT_MAX, FLT_MAX, "Center", "Center in global view space", -FLT_MAX, FLT_MAX);
- RNA_def_float_vector(ot->srna, "axis", 3, NULL, -1.0f, 1.0f, "Axis", "Axis in global view space", -FLT_MAX, FLT_MAX);
+ RNA_def_float_vector(ot->srna, "axis", 3, NULL, -FLT_MAX, FLT_MAX, "Axis", "Axis in global view space", -1.0f, 1.0f);
}
@@ -3661,34 +3804,40 @@ void MESH_OT_screw(wmOperatorType *ot)
RNA_def_float_vector(ot->srna, "center", 3, NULL, -FLT_MAX, FLT_MAX,
"Center", "Center in global view space", -FLT_MAX, FLT_MAX);
- RNA_def_float_vector(ot->srna, "axis", 3, NULL, -1.0f, 1.0f,
- "Axis", "Axis in global view space", -FLT_MAX, FLT_MAX);
+ RNA_def_float_vector(ot->srna, "axis", 3, NULL, -FLT_MAX, FLT_MAX,
+ "Axis", "Axis in global view space", -1.0f, 1.0f);
}
-static int edbm_select_by_number_vertices_exec(bContext *C, wmOperator *op)
+static int edbm_select_face_by_sides_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BMEdit_FromObject(obedit);
BMFace *efa;
BMIter iter;
- int numverts = RNA_int_get(op->ptr, "number");
- int type = RNA_enum_get(op->ptr, "type");
+ const int numverts = RNA_int_get(op->ptr, "number");
+ const int type = RNA_enum_get(op->ptr, "type");
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
- int select = 0;
+ int select;
- if (type == 0 && efa->len < numverts) {
- select = 1;
- }
- else if (type == 1 && efa->len == numverts) {
- select = 1;
- }
- else if (type == 2 && efa->len > numverts) {
- select = 1;
- }
- else if (type == 3 && efa->len != numverts) {
- select = 1;
+ switch (type) {
+ case 0:
+ select = (efa->len < numverts);
+ break;
+ case 1:
+ select = (efa->len == numverts);
+ break;
+ case 2:
+ select = (efa->len > numverts);
+ break;
+ case 3:
+ select = (efa->len != numverts);
+ break;
+ default:
+ BLI_assert(0);
+ select = FALSE;
+ break;
}
if (select) {
@@ -3702,7 +3851,7 @@ static int edbm_select_by_number_vertices_exec(bContext *C, wmOperator *op)
return OPERATOR_FINISHED;
}
-void MESH_OT_select_by_number_vertices(wmOperatorType *ot)
+void MESH_OT_select_face_by_sides(wmOperatorType *ot)
{
static const EnumPropertyItem type_items[] = {
{0, "LESS", 0, "Less Than", ""},
@@ -3713,12 +3862,12 @@ void MESH_OT_select_by_number_vertices(wmOperatorType *ot)
};
/* identifiers */
- ot->name = "Select by Number of Vertices";
- ot->description = "Select vertices or faces by vertex count";
- ot->idname = "MESH_OT_select_by_number_vertices";
+ ot->name = "Select Faces by Sides";
+ ot->description = "Select vertices or faces by the number of polygon sides";
+ ot->idname = "MESH_OT_select_face_by_sides";
/* api callbacks */
- ot->exec = edbm_select_by_number_vertices_exec;
+ ot->exec = edbm_select_face_by_sides_exec;
ot->poll = ED_operator_editmesh;
/* flags */
@@ -3846,8 +3995,8 @@ static void sort_bmelem_flag(Scene *scene, Object *ob,
char *pblock[3] = {NULL, NULL, NULL}, *pb;
BMElemSort *sblock[3] = {NULL, NULL, NULL}, *sb;
int *map[3] = {NULL, NULL, NULL}, *mp;
- int totelem[3] = {0, 0, 0}, tot;
- int affected[3] = {0, 0, 0}, aff;
+ int totelem[3] = {0, 0, 0};
+ int affected[3] = {0, 0, 0};
int i, j;
if (!(types && flag && action))
@@ -4222,8 +4371,8 @@ static void sort_bmelem_flag(Scene *scene, Object *ob,
if (pb && sb && !map[j]) {
char *p_blk;
BMElemSort *s_blk;
- tot = totelem[j];
- aff = affected[j];
+ int tot = totelem[j];
+ int aff = affected[j];
qsort(sb, aff, sizeof(BMElemSort), bmelemsort_comp);
@@ -4272,7 +4421,7 @@ static int edbm_sort_elements_exec(bContext *C, wmOperator *op)
if (ELEM(action, SRT_VIEW_ZAXIS, SRT_VIEW_XAXIS)) {
if (rv3d == NULL) {
- BKE_report(op->reports, RPT_ERROR, "View not found, can't sort by view axis");
+ BKE_report(op->reports, RPT_ERROR, "View not found, cannot sort by view axis");
return OPERATOR_CANCELLED;
}
}
@@ -4460,6 +4609,7 @@ typedef struct {
int li;
int mcenter[2];
float initial_length;
+ float pixel_size; /* use when mouse input is interpreted as spatial distance */
int is_modal;
NumInput num_input;
float shift_factor; /* The current factor when shift is pressed. Negative when shift not active. */
@@ -4657,8 +4807,10 @@ static int edbm_bevel_exec(bContext *C, wmOperator *op)
static int edbm_bevel_invoke(bContext *C, wmOperator *op, wmEvent *event)
{
/* TODO make modal keymap (see fly mode) */
+ RegionView3D *rv3d = CTX_wm_region_view3d(C);
BevelData *opdata;
float mlen[2];
+ float center_3d[3];
if (!edbm_bevel_init(C, op, TRUE)) {
return OPERATOR_CANCELLED;
@@ -4667,7 +4819,7 @@ static int edbm_bevel_invoke(bContext *C, wmOperator *op, wmEvent *event)
opdata = op->customdata;
/* initialize mouse values */
- if (!calculateTransformCenter(C, V3D_CENTROID, NULL, opdata->mcenter)) {
+ if (!calculateTransformCenter(C, V3D_CENTROID, center_3d, opdata->mcenter)) {
/* in this case the tool will likely do nothing,
* ideally this will never happen and should be checked for above */
opdata->mcenter[0] = opdata->mcenter[1] = 0;
@@ -4675,6 +4827,7 @@ static int edbm_bevel_invoke(bContext *C, wmOperator *op, wmEvent *event)
mlen[0] = opdata->mcenter[0] - event->mval[0];
mlen[1] = opdata->mcenter[1] - event->mval[1];
opdata->initial_length = len_v2(mlen);
+ opdata->pixel_size = rv3d ? ED_view3d_pixel_size(rv3d, center_3d) : 1.0f;
edbm_bevel_update_header(op, C);
@@ -4688,6 +4841,44 @@ static int edbm_bevel_invoke(bContext *C, wmOperator *op, wmEvent *event)
return OPERATOR_RUNNING_MODAL;
}
+static float edbm_bevel_mval_factor(wmOperator *op, wmEvent *event)
+{
+ BevelData *opdata = op->customdata;
+ int use_dist = RNA_boolean_get(op->ptr, "use_dist");
+ float mdiff[2];
+ float factor;
+
+ mdiff[0] = opdata->mcenter[0] - event->mval[0];
+ mdiff[1] = opdata->mcenter[1] - event->mval[1];
+
+ if (use_dist) {
+ factor = ((len_v2(mdiff) - MVAL_PIXEL_MARGIN) - opdata->initial_length) * opdata->pixel_size;
+ }
+ else {
+ factor = (len_v2(mdiff) - MVAL_PIXEL_MARGIN) / opdata->initial_length;
+ factor = factor - 1.0f; /* a different kind of buffer where nothing happens */
+ }
+
+ /* Fake shift-transform... */
+ if (event->shift) {
+ if (opdata->shift_factor < 0.0f)
+ opdata->shift_factor = RNA_float_get(op->ptr, "percent");
+ factor = (factor - opdata->shift_factor) * 0.1f + opdata->shift_factor;
+ }
+ else if (opdata->shift_factor >= 0.0f)
+ opdata->shift_factor = -1.0f;
+
+ /* clamp differently based on distance/factor */
+ if (use_dist) {
+ if (factor < 0.0f) factor = 0.0f;
+ }
+ else {
+ CLAMP(factor, 0.0f, 1.0f);
+ }
+
+ return factor;
+}
+
static int edbm_bevel_modal(bContext *C, wmOperator *op, wmEvent *event)
{
BevelData *opdata = op->customdata;
@@ -4715,25 +4906,7 @@ static int edbm_bevel_modal(bContext *C, wmOperator *op, wmEvent *event)
case MOUSEMOVE:
if (!hasNumInput(&opdata->num_input)) {
- float factor;
- float mdiff[2];
-
- mdiff[0] = opdata->mcenter[0] - event->mval[0];
- mdiff[1] = opdata->mcenter[1] - event->mval[1];
-
- factor = -len_v2(mdiff) / opdata->initial_length + 1.0f;
-
- /* Fake shift-transform... */
- if (event->shift) {
- if (opdata->shift_factor < 0.0f)
- opdata->shift_factor = RNA_float_get(op->ptr, "percent");
- factor = (factor - opdata->shift_factor) * 0.1f + opdata->shift_factor;
- }
- else if (opdata->shift_factor >= 0.0f)
- opdata->shift_factor = -1.0f;
-
- CLAMP(factor, 0.0f, 1.0f);
-
+ const float factor = edbm_bevel_mval_factor(op, event);
RNA_float_set(op->ptr, "percent", factor);
edbm_bevel_calc(C, op);
@@ -4763,6 +4936,11 @@ static int edbm_bevel_modal(bContext *C, wmOperator *op, wmEvent *event)
int use_dist = RNA_boolean_get(op->ptr, "use_dist");
RNA_boolean_set(op->ptr, "use_dist", !use_dist);
+ {
+ const float factor = edbm_bevel_mval_factor(op, event);
+ RNA_float_set(op->ptr, "percent", factor);
+ }
+
edbm_bevel_calc(C, op);
edbm_bevel_update_header(op, C);
}
@@ -4787,8 +4965,9 @@ void MESH_OT_bevel(wmOperatorType *ot)
ot->poll = ED_operator_editmesh;
/* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_GRAB_POINTER | OPTYPE_BLOCKING;
+ /* take note, used as a factor _and_ a distance depending on 'use_dist' */
RNA_def_float(ot->srna, "percent", 0.0f, -FLT_MAX, FLT_MAX, "Percentage", "", 0.0f, 1.0f);
/* XXX, disabled for 2.63 release, needs to work much better without overlap before we can give to users. */
/* RNA_def_int(ot->srna, "recursion", 1, 1, 50, "Recursion Level", "Recursion Level", 1, 8); */
@@ -4853,8 +5032,9 @@ typedef struct {
float old_depth;
int mcenter[2];
int modify_depth;
- int is_modal;
float initial_length;
+ float pixel_size; /* use when mouse input is interpreted as spatial distance */
+ int is_modal;
int shift;
float shift_amount;
BMBackup backup;
@@ -5020,15 +5200,17 @@ static int edbm_inset_exec(bContext *C, wmOperator *op)
static int edbm_inset_invoke(bContext *C, wmOperator *op, wmEvent *event)
{
+ RegionView3D *rv3d = CTX_wm_region_view3d(C);
InsetData *opdata;
float mlen[2];
+ float center_3d[3];
edbm_inset_init(C, op, TRUE);
opdata = op->customdata;
/* initialize mouse values */
- if (!calculateTransformCenter(C, V3D_CENTROID, NULL, opdata->mcenter)) {
+ if (!calculateTransformCenter(C, V3D_CENTROID, center_3d, opdata->mcenter)) {
/* in this case the tool will likely do nothing,
* ideally this will never happen and should be checked for above */
opdata->mcenter[0] = opdata->mcenter[1] = 0;
@@ -5036,6 +5218,7 @@ static int edbm_inset_invoke(bContext *C, wmOperator *op, wmEvent *event)
mlen[0] = opdata->mcenter[0] - event->mval[0];
mlen[1] = opdata->mcenter[1] - event->mval[1];
opdata->initial_length = len_v2(mlen);
+ opdata->pixel_size = rv3d ? ED_view3d_pixel_size(rv3d, center_3d) : 1.0f;
edbm_inset_calc(C, op);
@@ -5055,7 +5238,7 @@ static int edbm_inset_modal(bContext *C, wmOperator *op, wmEvent *event)
if (handleNumInput(&opdata->num_input, event)) {
applyNumInput(&opdata->num_input, amounts);
- amounts[0] = maxf(amounts[0], 0.0f);
+ amounts[0] = max_ff(amounts[0], 0.0f);
RNA_float_set(op->ptr, "thickness", amounts[0]);
RNA_float_set(op->ptr, "depth", amounts[1]);
@@ -5085,9 +5268,9 @@ static int edbm_inset_modal(bContext *C, wmOperator *op, wmEvent *event)
mdiff[1] = opdata->mcenter[1] - event->mval[1];
if (opdata->modify_depth)
- amount = opdata->old_depth + len_v2(mdiff) / opdata->initial_length - 1.0f;
+ amount = opdata->old_depth + ((len_v2(mdiff) - opdata->initial_length) * opdata->pixel_size);
else
- amount = opdata->old_thickness - len_v2(mdiff) / opdata->initial_length + 1.0f;
+ amount = opdata->old_thickness - ((len_v2(mdiff) - opdata->initial_length) * opdata->pixel_size);
/* Fake shift-transform... */
if (opdata->shift)
@@ -5096,7 +5279,7 @@ static int edbm_inset_modal(bContext *C, wmOperator *op, wmEvent *event)
if (opdata->modify_depth)
RNA_float_set(op->ptr, "depth", amount);
else {
- amount = maxf(amount, 0.0f);
+ amount = max_ff(amount, 0.0f);
RNA_float_set(op->ptr, "thickness", amount);
}
@@ -5206,7 +5389,7 @@ void MESH_OT_inset(wmOperatorType *ot)
ot->poll = ED_operator_editmesh;
/* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_GRAB_POINTER | OPTYPE_BLOCKING;
/* properties */
RNA_def_boolean(ot->srna, "use_boundary", TRUE, "Boundary", "Inset face boundaries");
@@ -5294,6 +5477,7 @@ void MESH_OT_wireframe(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "use_replace", TRUE, "Replace", "Remove original faces");
}
+#ifdef WITH_BULLET
static int edbm_convex_hull_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -5387,3 +5571,55 @@ void MESH_OT_convex_hull(wmOperatorType *ot)
join_triangle_props(ot);
}
+#endif
+
+static int mesh_symmetrize_exec(bContext *C, wmOperator *op)
+{
+ Object *obedit = CTX_data_edit_object(C);
+ BMEditMesh *em = BMEdit_FromObject(obedit);
+ BMOperator bmop;
+
+ EDBM_op_init(em, &bmop, op, "symmetrize input=%hvef direction=%i",
+ BM_ELEM_SELECT, RNA_enum_get(op->ptr, "direction"));
+ BMO_op_exec(em->bm, &bmop);
+
+ if (!EDBM_op_finish(em, &bmop, op, TRUE)) {
+ return OPERATOR_CANCELLED;
+ }
+ else {
+ EDBM_update_generic(C, em, TRUE);
+ EDBM_selectmode_flush(em);
+ return OPERATOR_FINISHED;
+ }
+}
+
+void MESH_OT_symmetrize(struct wmOperatorType *ot)
+{
+ static EnumPropertyItem axis_direction_items[] = {
+ {BMO_SYMMETRIZE_NEGATIVE_X, "NEGATIVE_X", 0, "-X to +X", ""},
+ {BMO_SYMMETRIZE_POSITIVE_X, "POSITIVE_X", 0, "+X to -X", ""},
+
+ {BMO_SYMMETRIZE_NEGATIVE_Y, "NEGATIVE_Y", 0, "-Y to +Y", ""},
+ {BMO_SYMMETRIZE_POSITIVE_Y, "POSITIVE_Y", 0, "+Y to -Y", ""},
+
+ {BMO_SYMMETRIZE_NEGATIVE_Z, "NEGATIVE_Z", 0, "-Z to +Z", ""},
+ {BMO_SYMMETRIZE_POSITIVE_Z, "POSITIVE_Z", 0, "+Z to -Z", ""},
+ {0, NULL, 0, NULL, NULL},
+ };
+
+ /* identifiers */
+ ot->name = "Symmetrize";
+ ot->description = "Enforce symmetry (both form and topological) across an axis";
+ ot->idname = "MESH_OT_symmetrize";
+
+ /* api callbacks */
+ ot->exec = mesh_symmetrize_exec;
+ ot->poll = ED_operator_editmesh;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ ot->prop = RNA_def_enum(ot->srna, "direction", axis_direction_items,
+ BMO_SYMMETRIZE_NEGATIVE_X,
+ "Direction", "Which sides to copy from and to");
+}
diff --git a/source/blender/editors/mesh/editmesh_utils.c b/source/blender/editors/mesh/editmesh_utils.c
index 03e2f2691a8..ef3d8db4156 100644
--- a/source/blender/editors/mesh/editmesh_utils.c
+++ b/source/blender/editors/mesh/editmesh_utils.c
@@ -48,6 +48,8 @@
#include "BKE_report.h"
#include "BKE_tessmesh.h"
+#include "BKE_object.h" /* XXX. only for EDBM_mesh_ensure_valid_dm_hack() which will be removed */
+
#include "WM_api.h"
#include "WM_types.h"
@@ -102,7 +104,17 @@ void EDBM_redo_state_free(BMBackup *backup, BMEditMesh *em, int recalctess)
BMEdit_RecalcTessellation(em);
}
-
+/* hack to workaround multiple operators being called within the same event loop without an update
+ * see: [#31811] */
+void EDBM_mesh_ensure_valid_dm_hack(Scene *scene, BMEditMesh *em)
+{
+ if ((((ID *)em->ob->data)->flag & LIB_ID_RECALC) ||
+ (em->ob->recalc & OB_RECALC_DATA))
+ {
+ em->ob->recalc |= OB_RECALC_DATA; /* since we may not have done selection flushing */
+ BKE_object_handle_update(scene, em->ob);
+ }
+}
void EDBM_mesh_normals_update(BMEditMesh *em)
{
@@ -535,6 +547,16 @@ static void *getEditMesh(bContext *C)
typedef struct UndoMesh {
Mesh me;
int selectmode;
+
+ /** \note
+ * this isn't a prefect solution, if you edit keys and change shapes this works well (fixing [#32442]),
+ * but editing shape keys, going into object mode, removing or changing their order,
+ * then go back into editmode and undo will give issues - where the old index will be out of sync
+ * with the new object index.
+ *
+ * There are a few ways this could be made to work but for now its a known limitation with mixing
+ * object and editmode operations - Campbell */
+ int shapenr;
} UndoMesh;
/* undo simply makes copies of a bmesh */
@@ -546,13 +568,14 @@ static void *editbtMesh_to_undoMesh(void *emv, void *obdata)
UndoMesh *um = MEM_callocN(sizeof(UndoMesh), "undo Mesh");
/* make sure shape keys work */
- um->me.key = obme->key ? copy_key_nolib(obme->key) : NULL;
+ um->me.key = obme->key ? BKE_key_copy_nolib(obme->key) : NULL;
/* BM_mesh_validate(em->bm); */ /* for troubleshooting */
BM_mesh_bm_to_me(em->bm, &um->me, FALSE);
um->selectmode = em->selectmode;
+ um->shapenr = em->bm->shapenr;
return um;
}
@@ -564,7 +587,7 @@ static void undoMesh_to_editbtMesh(void *umv, void *em_v, void *UNUSED(obdata))
UndoMesh *um = umv;
BMesh *bm;
- ob->shapenr = em->bm->shapenr;
+ ob->shapenr = em->bm->shapenr = um->shapenr;
EDBM_mesh_free(em);
@@ -989,6 +1012,19 @@ void EDBM_uv_element_map_free(UvElementMap *element_map)
}
}
+UvElement *ED_uv_element_get(UvElementMap *map, BMFace *efa, BMLoop *l)
+{
+ UvElement *element;
+
+ element = map->vert[BM_elem_index_get(l->v)];
+
+ for (; element; element = element->next)
+ if (element->face == efa)
+ return element;
+
+ return NULL;
+}
+
/* last_sel, use em->act_face otherwise get the last selected face in the editselections
* at the moment, last_sel is mainly useful for making sure the space image dosnt flicker */
MTexPoly *EDBM_mtexpoly_active_get(BMEditMesh *em, BMFace **r_act_efa, int sloppy, int selected)
diff --git a/source/blender/editors/mesh/mesh_data.c b/source/blender/editors/mesh/mesh_data.c
index 09d89a961e4..e9906f852de 100644
--- a/source/blender/editors/mesh/mesh_data.c
+++ b/source/blender/editors/mesh/mesh_data.c
@@ -47,6 +47,8 @@
#include "BLI_array.h"
#include "BLI_math.h"
#include "BLI_edgehash.h"
+#include "BLI_linklist.h"
+#include "BLI_listbase.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
@@ -74,6 +76,64 @@
#include "mesh_intern.h"
+static CustomData *mesh_customdata_get_type(Mesh *me, const char htype, int *r_tot)
+{
+ CustomData *data;
+ BMesh *bm = (me->edit_btmesh) ? me->edit_btmesh->bm : NULL;
+ int tot;
+
+ /* this */
+ switch (htype) {
+ case BM_VERT:
+ if (bm) {
+ data = &bm->vdata;
+ tot = bm->totvert;
+ }
+ else {
+ data = &me->vdata;
+ tot = me->totvert;
+ }
+ break;
+ case BM_EDGE:
+ if (bm) {
+ data = &bm->edata;
+ tot = bm->totedge;
+ }
+ else {
+ data = &me->edata;
+ tot = me->totedge;
+ }
+ break;
+ case BM_LOOP:
+ if (bm) {
+ data = &bm->ldata;
+ tot = bm->totloop;
+ }
+ else {
+ data = &me->ldata;
+ tot = me->totloop;
+ }
+ break;
+ case BM_FACE:
+ if (bm) {
+ data = &bm->pdata;
+ tot = bm->totface;
+ }
+ else {
+ data = &me->pdata;
+ tot = me->totpoly;
+ }
+ break;
+ default:
+ BLI_assert(0);
+ tot = 0;
+ data = NULL;
+ }
+
+ *r_tot = tot;
+ return data;
+}
+
#define GET_CD_DATA(me, data) (me->edit_btmesh ? &me->edit_btmesh->bm->data : &me->data)
static void delete_customdata_layer(bContext *C, Object *ob, CustomDataLayer *layer)
{
@@ -85,24 +145,10 @@ static void delete_customdata_layer(bContext *C, Object *ob, CustomDataLayer *la
int i, actindex, rndindex, cloneindex, stencilindex, tot;
if (layer->type == CD_MLOOPCOL || layer->type == CD_MLOOPUV) {
- if (me->edit_btmesh) {
- data = &me->edit_btmesh->bm->ldata;
- tot = me->edit_btmesh->bm->totloop;
- }
- else {
- data = &me->ldata;
- tot = me->totloop;
- }
+ data = mesh_customdata_get_type(me, BM_LOOP, &tot);
}
else {
- if (me->edit_btmesh) {
- data = &me->edit_btmesh->bm->pdata;
- tot = me->edit_btmesh->bm->totface;
- }
- else {
- data = &me->pdata;
- tot = me->totpoly;
- }
+ data = mesh_customdata_get_type(me, BM_FACE, &tot);
}
index = CustomData_get_layer_index(data, type);
@@ -189,7 +235,8 @@ static void delete_customdata_layer(bContext *C, Object *ob, CustomDataLayer *la
}
}
-int ED_mesh_uv_loop_reset_ex(struct bContext *C, struct Mesh *me, const int layernum)
+/* without bContext, called in uvedit */
+int ED_mesh_uv_loop_reset_ex(struct Mesh *me, const int layernum)
{
BMEditMesh *em = me->edit_btmesh;
MLoopUV *luv;
@@ -292,7 +339,6 @@ int ED_mesh_uv_loop_reset_ex(struct bContext *C, struct Mesh *me, const int laye
BLI_array_free(polylengths);
DAG_id_tag_update(&me->id, 0);
- WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
return 1;
}
@@ -302,7 +348,11 @@ int ED_mesh_uv_loop_reset(struct bContext *C, struct Mesh *me)
/* could be ldata or pdata */
CustomData *pdata = GET_CD_DATA(me, pdata);
const int layernum = CustomData_get_active_layer_index(pdata, CD_MTEXPOLY);
- return ED_mesh_uv_loop_reset_ex(C, me, layernum);
+ int retval = ED_mesh_uv_loop_reset_ex(me, layernum);
+
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
+
+ return retval;
}
/* note: keep in sync with ED_mesh_color_add */
@@ -373,7 +423,7 @@ int ED_mesh_uv_texture_add(bContext *C, Mesh *me, const char *name, int active_s
/* don't overwrite our copied coords */
if (is_init == FALSE) {
- ED_mesh_uv_loop_reset_ex(C, me, layernum_dst);
+ ED_mesh_uv_loop_reset_ex(me, layernum_dst);
}
DAG_id_tag_update(&me->id, 0);
@@ -547,7 +597,7 @@ static int drop_named_image_invoke(bContext *C, wmOperator *op, wmEvent *event)
/* Check context */
if (base == NULL || base->object->type != OB_MESH) {
- BKE_report(op->reports, RPT_ERROR, "Not an Object or Mesh");
+ BKE_report(op->reports, RPT_ERROR, "Not an object or mesh");
return OPERATOR_CANCELLED;
}
@@ -564,7 +614,7 @@ static int drop_named_image_invoke(bContext *C, wmOperator *op, wmEvent *event)
}
if (!ima) {
- BKE_report(op->reports, RPT_ERROR, "Not an Image");
+ BKE_report(op->reports, RPT_ERROR, "Not an image");
return OPERATOR_CANCELLED;
}
@@ -701,71 +751,124 @@ void MESH_OT_vertex_color_remove(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-/*********************** sticky operators ************************/
+/* *** CustomData clear functions, we need an operator for each *** */
-static int mesh_sticky_add_exec(bContext *C, wmOperator *UNUSED(op))
+static int mesh_customdata_clear_exec__internal(bContext *C,
+ char htype, int type)
{
- Scene *scene = CTX_data_scene(C);
- View3D *v3d = CTX_wm_view3d(C);
- Object *ob = ED_object_context(C);
- Mesh *me = ob->data;
+ Object *obedit = ED_object_context(C);
+ Mesh *me = obedit->data;
- /* why is this commented out? */
-#if 0
- if (me->msticky)
+ int tot;
+ CustomData *data = mesh_customdata_get_type(me, htype, &tot);
+
+ BLI_assert(CustomData_layertype_is_singleton(type) == TRUE);
+
+ if (CustomData_has_layer(data, type)) {
+ if (me->edit_btmesh) {
+ BM_data_layer_free(me->edit_btmesh->bm, data, type);
+ }
+ else {
+ CustomData_free_layers(data, type, tot);
+ }
+
+ DAG_id_tag_update(&me->id, 0);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
+
+ return OPERATOR_FINISHED;
+ }
+ else {
return OPERATOR_CANCELLED;
-#endif
+ }
+}
- RE_make_sticky(scene, v3d);
+/* Clear Mask */
+static int mesh_customdata_clear_mask_poll(bContext *C)
+{
+ Object *ob = ED_object_context(C);
+ if (ob && ob->type == OB_MESH) {
+ Mesh *me = ob->data;
- DAG_id_tag_update(&me->id, 0);
- WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
+ /* special case - can't run this if we're in sculpt mode */
+ if (ob->mode & OB_MODE_SCULPT) {
+ return FALSE;
+ }
- return OPERATOR_FINISHED;
+ if (me->id.lib == NULL) {
+ CustomData *data = GET_CD_DATA(me, vdata);
+ if (CustomData_has_layer(data, CD_PAINT_MASK)) {
+ return TRUE;
+ }
+ data = GET_CD_DATA(me, ldata);
+ if (CustomData_has_layer(data, CD_GRID_PAINT_MASK)) {
+ return TRUE;
+ }
+ }
+ }
+ return FALSE;
+}
+static int mesh_customdata_clear_mask_exec(bContext *C, wmOperator *UNUSED(op))
+{
+ int ret_a = mesh_customdata_clear_exec__internal(C, BM_VERT, CD_PAINT_MASK);
+ int ret_b = mesh_customdata_clear_exec__internal(C, BM_LOOP, CD_GRID_PAINT_MASK);
+
+ if (ret_a == OPERATOR_FINISHED ||
+ ret_b == OPERATOR_FINISHED)
+ {
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
}
-void MESH_OT_sticky_add(wmOperatorType *ot)
+void MESH_OT_customdata_clear_mask(wmOperatorType *ot)
{
+
/* identifiers */
- ot->name = "Add Sticky";
- ot->description = "Add sticky UV texture layer";
- ot->idname = "MESH_OT_sticky_add";
-
+ ot->name = "Clear Sculpt-Mask Data";
+ ot->idname = "MESH_OT_customdata_clear_mask";
+ ot->description = "Clear vertex sculpt masking data from the mesh";
+
/* api callbacks */
- ot->poll = layers_poll;
- ot->exec = mesh_sticky_add_exec;
+ ot->exec = mesh_customdata_clear_mask_exec;
+ ot->poll = mesh_customdata_clear_mask_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-static int mesh_sticky_remove_exec(bContext *C, wmOperator *UNUSED(op))
+/* Clear Skin */
+static int mesh_customdata_clear_skin_poll(bContext *C)
{
Object *ob = ED_object_context(C);
- Mesh *me = ob->data;
-
- if (!me->msticky)
- return OPERATOR_CANCELLED;
-
- CustomData_free_layer_active(&me->vdata, CD_MSTICKY, me->totvert);
- me->msticky = NULL;
-
- DAG_id_tag_update(&me->id, 0);
- WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
- return OPERATOR_FINISHED;
+ if (ob && ob->type == OB_MESH) {
+ Mesh *me = ob->data;
+ if (me->id.lib == NULL) {
+ CustomData *data = GET_CD_DATA(me, vdata);
+ if (CustomData_has_layer(data, CD_MVERT_SKIN)) {
+ return TRUE;
+ }
+ }
+ }
+ return FALSE;
+}
+static int mesh_customdata_clear_skin_exec(bContext *C, wmOperator *UNUSED(op))
+{
+ return mesh_customdata_clear_exec__internal(C, BM_VERT, CD_MVERT_SKIN);
}
-void MESH_OT_sticky_remove(wmOperatorType *ot)
+void MESH_OT_customdata_clear_skin(wmOperatorType *ot)
{
/* identifiers */
- ot->name = "Remove Sticky";
- ot->description = "Remove sticky UV texture layer";
- ot->idname = "MESH_OT_sticky_remove";
-
+ ot->name = "Clear Skin Data";
+ ot->idname = "MESH_OT_customdata_clear_skin";
+ ot->description = "Clear vertex skin layer";
+
/* api callbacks */
- ot->poll = layers_poll;
- ot->exec = mesh_sticky_remove_exec;
+ ot->exec = mesh_customdata_clear_skin_exec;
+ ot->poll = mesh_customdata_clear_skin_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -803,7 +906,7 @@ void ED_mesh_update(Mesh *mesh, bContext *C, int calc_edges, int calc_tessface)
* so rather then add poly-index layer and calculate normals for it
* calculate normals only for the mvert's. - campbell */
#ifdef USE_BMESH_MPOLY_NORMALS
- polyindex = CustomData_get_layer(&mesh->fdata, CD_POLYINDEX);
+ polyindex = CustomData_get_layer(&mesh->fdata, CD_ORIGINDEX);
/* add a normals layer for tessellated faces, a tessface normal will
* contain the normal of the poly the face was tessellated from. */
face_nors = CustomData_add_layer(&mesh->fdata, CD_NORMAL, CD_CALLOC, NULL, mesh->totface);
@@ -848,6 +951,7 @@ static void mesh_add_verts(Mesh *mesh, int len)
/* scan the input list and insert the new vertices */
+ /* set default flags */
mvert = &mesh->mvert[mesh->totvert];
for (i = 0; i < len; i++, mvert++)
mvert->flag |= SELECT;
@@ -1025,7 +1129,7 @@ static void mesh_remove_faces(Mesh *mesh, int len)
void ED_mesh_geometry_add(Mesh *mesh, ReportList *reports, int verts, int edges, int faces)
{
if (mesh->edit_btmesh) {
- BKE_report(reports, RPT_ERROR, "Can't add geometry in edit mode");
+ BKE_report(reports, RPT_ERROR, "Cannot add geometry in edit mode");
return;
}
@@ -1041,12 +1145,12 @@ void ED_mesh_geometry_add(Mesh *mesh, ReportList *reports, int verts, int edges,
void ED_mesh_tessfaces_add(Mesh *mesh, ReportList *reports, int count)
{
if (mesh->edit_btmesh) {
- BKE_report(reports, RPT_ERROR, "Can't add tessfaces in edit mode");
+ BKE_report(reports, RPT_ERROR, "Cannot add tessfaces in edit mode");
return;
}
if (mesh->mpoly) {
- BKE_report(reports, RPT_ERROR, "Can't add tessfaces to a mesh that already has polygons");
+ BKE_report(reports, RPT_ERROR, "Cannot add tessfaces to a mesh that already has polygons");
return;
}
@@ -1056,7 +1160,7 @@ void ED_mesh_tessfaces_add(Mesh *mesh, ReportList *reports, int count)
void ED_mesh_edges_add(Mesh *mesh, ReportList *reports, int count)
{
if (mesh->edit_btmesh) {
- BKE_report(reports, RPT_ERROR, "Can't add edges in edit mode");
+ BKE_report(reports, RPT_ERROR, "Cannot add edges in edit mode");
return;
}
@@ -1066,7 +1170,7 @@ void ED_mesh_edges_add(Mesh *mesh, ReportList *reports, int count)
void ED_mesh_vertices_add(Mesh *mesh, ReportList *reports, int count)
{
if (mesh->edit_btmesh) {
- BKE_report(reports, RPT_ERROR, "Can't add vertices in edit mode");
+ BKE_report(reports, RPT_ERROR, "Cannot add vertices in edit mode");
return;
}
@@ -1076,11 +1180,11 @@ void ED_mesh_vertices_add(Mesh *mesh, ReportList *reports, int count)
void ED_mesh_faces_remove(Mesh *mesh, ReportList *reports, int count)
{
if (mesh->edit_btmesh) {
- BKE_report(reports, RPT_ERROR, "Can't remove faces in edit mode");
+ BKE_report(reports, RPT_ERROR, "Cannot remove faces in edit mode");
return;
}
else if (count > mesh->totface) {
- BKE_report(reports, RPT_ERROR, "Can't remove more faces than the mesh contains");
+ BKE_report(reports, RPT_ERROR, "Cannot remove more faces than the mesh contains");
return;
}
@@ -1090,11 +1194,11 @@ void ED_mesh_faces_remove(Mesh *mesh, ReportList *reports, int count)
void ED_mesh_edges_remove(Mesh *mesh, ReportList *reports, int count)
{
if (mesh->edit_btmesh) {
- BKE_report(reports, RPT_ERROR, "Can't remove edges in edit mode");
+ BKE_report(reports, RPT_ERROR, "Cannot remove edges in edit mode");
return;
}
else if (count > mesh->totedge) {
- BKE_report(reports, RPT_ERROR, "Can't remove more edges than the mesh contains");
+ BKE_report(reports, RPT_ERROR, "Cannot remove more edges than the mesh contains");
return;
}
@@ -1104,11 +1208,11 @@ void ED_mesh_edges_remove(Mesh *mesh, ReportList *reports, int count)
void ED_mesh_vertices_remove(Mesh *mesh, ReportList *reports, int count)
{
if (mesh->edit_btmesh) {
- BKE_report(reports, RPT_ERROR, "Can't remove vertices in edit mode");
+ BKE_report(reports, RPT_ERROR, "Cannot remove vertices in edit mode");
return;
}
else if (count > mesh->totvert) {
- BKE_report(reports, RPT_ERROR, "Can't remove more vertices than the mesh contains");
+ BKE_report(reports, RPT_ERROR, "Cannot remove more vertices than the mesh contains");
return;
}
@@ -1118,7 +1222,7 @@ void ED_mesh_vertices_remove(Mesh *mesh, ReportList *reports, int count)
void ED_mesh_loops_add(Mesh *mesh, ReportList *reports, int count)
{
if (mesh->edit_btmesh) {
- BKE_report(reports, RPT_ERROR, "Can't add loops in edit mode.");
+ BKE_report(reports, RPT_ERROR, "Cannot add loops in edit mode");
return;
}
@@ -1128,7 +1232,7 @@ void ED_mesh_loops_add(Mesh *mesh, ReportList *reports, int count)
void ED_mesh_polys_add(Mesh *mesh, ReportList *reports, int count)
{
if (mesh->edit_btmesh) {
- BKE_report(reports, RPT_ERROR, "Can't add polys in edit mode.");
+ BKE_report(reports, RPT_ERROR, "Cannot add polygons in edit mode");
return;
}
diff --git a/source/blender/editors/mesh/mesh_intern.h b/source/blender/editors/mesh/mesh_intern.h
index 41666740730..82b785e5785 100644
--- a/source/blender/editors/mesh/mesh_intern.h
+++ b/source/blender/editors/mesh/mesh_intern.h
@@ -121,7 +121,7 @@ void MESH_OT_select_linked(struct wmOperatorType *ot);
void MESH_OT_select_linked_pick(struct wmOperatorType *ot);
void MESH_OT_hide(struct wmOperatorType *ot);
void MESH_OT_reveal(struct wmOperatorType *ot);
-void MESH_OT_select_by_number_vertices(struct wmOperatorType *ot);
+void MESH_OT_select_face_by_sides(struct wmOperatorType *ot);
void MESH_OT_select_loose_verts(struct wmOperatorType *ot);
void MESH_OT_select_mirror(struct wmOperatorType *ot);
void MESH_OT_normals_make_consistent(struct wmOperatorType *ot);
@@ -134,6 +134,7 @@ void MESH_OT_loop_multi_select(struct wmOperatorType *ot);
void MESH_OT_mark_seam(struct wmOperatorType *ot);
void MESH_OT_mark_sharp(struct wmOperatorType *ot);
void MESH_OT_vertices_smooth(struct wmOperatorType *ot);
+void MESH_OT_vertices_smooth_laplacian(struct wmOperatorType *ot);
void MESH_OT_noise(struct wmOperatorType *ot);
void MESH_OT_flip_normals(struct wmOperatorType *ot);
void MESH_OT_solidify(struct wmOperatorType *ot);
@@ -144,6 +145,7 @@ extern struct EnumPropertyItem *corner_type_items;
void MESH_OT_merge(struct wmOperatorType *ot);
void MESH_OT_subdivide(struct wmOperatorType *ot);
+void MESH_OT_unsubdivide(struct wmOperatorType *ot);
void MESH_OT_remove_doubles(struct wmOperatorType *ot);
void MESH_OT_spin(struct wmOperatorType *ot);
void MESH_OT_screw(struct wmOperatorType *ot);
@@ -187,8 +189,10 @@ void MESH_OT_uv_texture_add(struct wmOperatorType *ot);
void MESH_OT_uv_texture_remove(struct wmOperatorType *ot);
void MESH_OT_vertex_color_add(struct wmOperatorType *ot);
void MESH_OT_vertex_color_remove(struct wmOperatorType *ot);
-void MESH_OT_sticky_add(struct wmOperatorType *ot);
-void MESH_OT_sticky_remove(struct wmOperatorType *ot);
+/* no create_mask yet */
+void MESH_OT_customdata_clear_mask(struct wmOperatorType *ot);
+void MESH_OT_customdata_clear_skin(struct wmOperatorType *ot);
+
void MESH_OT_drop_named_image(struct wmOperatorType *ot);
/* ************* bmesh_tools.c ***********/
@@ -212,6 +216,8 @@ void MESH_OT_vert_slide(struct wmOperatorType *ot);
void MESH_OT_convex_hull(struct wmOperatorType *ot);
+void MESH_OT_symmetrize(struct wmOperatorType *ot);
+
/* ******************* mesh_navmesh.c */
void MESH_OT_navmesh_make(struct wmOperatorType *ot);
void MESH_OT_navmesh_face_copy(struct wmOperatorType *ot);
@@ -219,5 +225,4 @@ void MESH_OT_navmesh_face_add(struct wmOperatorType *ot);
void MESH_OT_navmesh_reset(struct wmOperatorType *ot);
void MESH_OT_navmesh_clear(struct wmOperatorType *ot);
-#endif // __MESH_INTERN_H__
-
+#endif /* __MESH_INTERN_H__ */
diff --git a/source/blender/editors/mesh/mesh_navmesh.c b/source/blender/editors/mesh/mesh_navmesh.c
index 88b1f191e3a..f6f8eee0a69 100644
--- a/source/blender/editors/mesh/mesh_navmesh.c
+++ b/source/blender/editors/mesh/mesh_navmesh.c
@@ -209,7 +209,7 @@ static int buildNavMesh(const RecastData *recastParams, int nverts, float *verts
triflags = MEM_callocN(sizeof(unsigned char) * ntris, "buildNavMesh triflags");
/* Find triangles which are walkable based on their slope and rasterize them */
- recast_markWalkableTriangles(RAD2DEG(recastParams->agentmaxslope), verts, nverts, tris, ntris, triflags);
+ recast_markWalkableTriangles(RAD2DEGF(recastParams->agentmaxslope), verts, nverts, tris, ntris, triflags);
recast_rasterizeTriangles(verts, nverts, tris, triflags, ntris, solid);
MEM_freeN(triflags);
diff --git a/source/blender/editors/mesh/mesh_ops.c b/source/blender/editors/mesh/mesh_ops.c
index dfa1beb614f..d319fdcca26 100644
--- a/source/blender/editors/mesh/mesh_ops.c
+++ b/source/blender/editors/mesh/mesh_ops.c
@@ -68,12 +68,13 @@ void ED_operatortypes_mesh(void)
WM_operatortype_append(MESH_OT_select_random);
WM_operatortype_append(MESH_OT_hide);
WM_operatortype_append(MESH_OT_reveal);
- WM_operatortype_append(MESH_OT_select_by_number_vertices);
+ WM_operatortype_append(MESH_OT_select_face_by_sides);
WM_operatortype_append(MESH_OT_select_loose_verts);
WM_operatortype_append(MESH_OT_select_mirror);
WM_operatortype_append(MESH_OT_normals_make_consistent);
WM_operatortype_append(MESH_OT_merge);
WM_operatortype_append(MESH_OT_subdivide);
+ WM_operatortype_append(MESH_OT_unsubdivide);
WM_operatortype_append(MESH_OT_faces_select_linked_flat);
WM_operatortype_append(MESH_OT_edges_select_sharp);
WM_operatortype_append(MESH_OT_primitive_plane_add);
@@ -132,9 +133,9 @@ void ED_operatortypes_mesh(void)
WM_operatortype_append(MESH_OT_mark_seam);
WM_operatortype_append(MESH_OT_mark_sharp);
WM_operatortype_append(MESH_OT_vertices_smooth);
+ WM_operatortype_append(MESH_OT_vertices_smooth_laplacian);
WM_operatortype_append(MESH_OT_noise);
WM_operatortype_append(MESH_OT_flip_normals);
- //WM_operatortype_append(MESH_OT_knife_cut);
WM_operatortype_append(MESH_OT_rip);
WM_operatortype_append(MESH_OT_blend_from_shape);
WM_operatortype_append(MESH_OT_shape_propagate_to_all);
@@ -143,8 +144,8 @@ void ED_operatortypes_mesh(void)
WM_operatortype_append(MESH_OT_uv_texture_remove);
WM_operatortype_append(MESH_OT_vertex_color_add);
WM_operatortype_append(MESH_OT_vertex_color_remove);
- WM_operatortype_append(MESH_OT_sticky_add);
- WM_operatortype_append(MESH_OT_sticky_remove);
+ WM_operatortype_append(MESH_OT_customdata_clear_mask);
+ WM_operatortype_append(MESH_OT_customdata_clear_skin);
WM_operatortype_append(MESH_OT_drop_named_image);
WM_operatortype_append(MESH_OT_edgering_select);
@@ -165,7 +166,11 @@ void ED_operatortypes_mesh(void)
WM_operatortype_append(MESH_OT_wireframe);
WM_operatortype_append(MESH_OT_edge_split);
+#ifdef WITH_BULLET
WM_operatortype_append(MESH_OT_convex_hull);
+#endif
+
+ WM_operatortype_append(MESH_OT_symmetrize);
#ifdef WITH_GAMEENGINE
WM_operatortype_append(MESH_OT_navmesh_make);
@@ -210,7 +215,17 @@ void ED_operatormacros_mesh(void)
ot = WM_operatortype_append_macro("MESH_OT_rip_move", "Rip", "Rip polygons and move the result",
OPTYPE_UNDO | OPTYPE_REGISTER);
- WM_operatortype_macro_define(ot, "MESH_OT_rip");
+ otmacro = WM_operatortype_macro_define(ot, "MESH_OT_rip");
+ RNA_boolean_set(otmacro->ptr, "use_fill", FALSE);
+ otmacro = WM_operatortype_macro_define(ot, "TRANSFORM_OT_translate");
+ RNA_enum_set(otmacro->ptr, "proportional", 0);
+ RNA_boolean_set(otmacro->ptr, "mirror", FALSE);
+
+ /* annoying we can't pass 'use_fill' through the macro */
+ ot = WM_operatortype_append_macro("MESH_OT_rip_move_fill", "Rip Fill", "Rip-fill polygons and move the result",
+ OPTYPE_UNDO | OPTYPE_REGISTER);
+ otmacro = WM_operatortype_macro_define(ot, "MESH_OT_rip");
+ RNA_boolean_set(otmacro->ptr, "use_fill", TRUE);
otmacro = WM_operatortype_macro_define(ot, "TRANSFORM_OT_translate");
RNA_enum_set(otmacro->ptr, "proportional", 0);
RNA_boolean_set(otmacro->ptr, "mirror", FALSE);
@@ -325,6 +340,8 @@ void ED_keymap_mesh(wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "MESH_OT_tris_convert_to_quads", JKEY, KM_PRESS, KM_ALT, 0);
WM_keymap_add_item(keymap, "MESH_OT_rip_move", VKEY, KM_PRESS, 0, 0);
+ WM_keymap_add_item(keymap, "MESH_OT_rip_move_fill", VKEY, KM_PRESS, KM_ALT, 0);
+
WM_keymap_add_item(keymap, "MESH_OT_merge", MKEY, KM_PRESS, KM_ALT, 0);
WM_keymap_add_item(keymap, "TRANSFORM_OT_shrink_fatten", SKEY, KM_PRESS, KM_ALT, 0);
diff --git a/source/blender/editors/mesh/meshtools.c b/source/blender/editors/mesh/meshtools.c
index a7467ee4c79..c0b6327d740 100644
--- a/source/blender/editors/mesh/meshtools.c
+++ b/source/blender/editors/mesh/meshtools.c
@@ -104,7 +104,7 @@ int join_mesh_exec(bContext *C, wmOperator *op)
MLoop *mloop = NULL;
Key *key, *nkey = NULL;
KeyBlock *kb, *okb, *kbn;
- float imat[4][4], cmat[4][4], *fp1, *fp2, curpos;
+ float imat[4][4], cmat[4][4], *fp1, *fp2;
int a, b, totcol, totmat = 0, totedge = 0, totvert = 0, ok = 0;
int totloop = 0, totpoly = 0, vertofs, *matmap = NULL;
int i, j, index, haskey = 0, edgeofs, loopofs, polyofs;
@@ -113,7 +113,7 @@ int join_mesh_exec(bContext *C, wmOperator *op)
CustomData vdata, edata, fdata, ldata, pdata;
if (scene->obedit) {
- BKE_report(op->reports, RPT_WARNING, "Cant join while in editmode");
+ BKE_report(op->reports, RPT_WARNING, "Cannot join while in edit mode");
return OPERATOR_CANCELLED;
}
@@ -161,10 +161,13 @@ int join_mesh_exec(bContext *C, wmOperator *op)
}
if (totvert > MESH_MAX_VERTS) {
- BKE_reportf(op->reports, RPT_WARNING, "Joining results in %d vertices, limit is " STRINGIFY(MESH_MAX_VERTS), totvert);
- return OPERATOR_CANCELLED;
+ BKE_reportf(op->reports, RPT_WARNING, "Joining results in %d vertices, limit is %ld", totvert, MESH_MAX_VERTS);
+ return OPERATOR_CANCELLED;
}
+ /* remove tessface to ensure we don't old references to invalid faces */
+ BKE_mesh_tessface_clear(me);
+
/* new material indices and material array */
matar = MEM_callocN(sizeof(void *) * totmat, "join_mesh matar");
if (totmat) matmap = MEM_callocN(sizeof(int) * totmat, "join_mesh matmap");
@@ -196,7 +199,7 @@ int join_mesh_exec(bContext *C, wmOperator *op)
}
else if (haskey) {
/* add a new key-block and add to the mesh */
- key = me->key = add_key((ID *)me);
+ key = me->key = BKE_key_add((ID *)me);
key->type = KEY_RELATIVE;
}
@@ -243,29 +246,29 @@ int join_mesh_exec(bContext *C, wmOperator *op)
/* if this mesh has shapekeys, check if destination mesh already has matching entries too */
if (me->key && key) {
- for (kb = me->key->block.first; kb; kb = kb->next) {
+ /* for remapping KeyBlock.relative */
+ int *index_map = MEM_mallocN(sizeof(int) * me->key->totkey, __func__);
+ KeyBlock **kb_map = MEM_mallocN(sizeof(KeyBlock *) * me->key->totkey, __func__);
+
+ for (kb = me->key->block.first, i = 0; kb; kb = kb->next, i++) {
+ BLI_assert(i < me->key->totkey);
+
+ kbn = BKE_keyblock_find_name(key, kb->name);
/* if key doesn't exist in destination mesh, add it */
- if (key_get_named_keyblock(key, kb->name) == NULL) {
- /* copy this existing one over to the new shapekey block */
- kbn = MEM_dupallocN(kb);
- kbn->prev = kbn->next = NULL;
-
+ if (kbn) {
+ index_map[i] = BLI_findindex(&key->block, kbn);
+ }
+ else {
+ index_map[i] = key->totkey;
+
+ kbn = BKE_keyblock_add(key, kb->name);
+
+ BKE_keyblock_copy_settings(kbn, kb);
+
/* adjust settings to fit (allocate a new data-array) */
kbn->data = MEM_callocN(sizeof(float) * 3 * totvert, "joined_shapekey");
kbn->totelem = totvert;
- kbn->weights = NULL;
-
- okb = key->block.last;
- curpos = (okb) ? okb->pos : -0.1f;
- if (key->type == KEY_RELATIVE)
- kbn->pos = curpos + 0.1f;
- else
- kbn->pos = curpos;
-
- BLI_addtail(&key->block, kbn);
- key->totkey++;
- if (key->totkey == 1) key->refkey = kbn;
-
+
/* XXX 2.5 Animato */
#if 0
/* also, copy corresponding ipo-curve to ipo-block if applicable */
@@ -275,20 +278,33 @@ int join_mesh_exec(bContext *C, wmOperator *op)
}
#endif
}
+
+ kb_map[i] = kbn;
+ }
+
+ /* remap relative index values */
+ for (kb = me->key->block.first, i = 0; kb; kb = kb->next, i++) {
+ if (LIKELY(kb->relative < me->key->totkey)) { /* sanity check, should always be true */
+ kb_map[i]->relative = index_map[kb->relative];
+ }
}
+
+ MEM_freeN(index_map);
+ MEM_freeN(kb_map);
}
}
}
}
CTX_DATA_END;
-
+
+
/* setup new data for destination mesh */
- memset(&vdata, 0, sizeof(vdata));
- memset(&edata, 0, sizeof(edata));
- memset(&fdata, 0, sizeof(fdata));
- memset(&ldata, 0, sizeof(ldata));
- memset(&pdata, 0, sizeof(pdata));
-
+ CustomData_reset(&vdata);
+ CustomData_reset(&edata);
+ CustomData_reset(&fdata);
+ CustomData_reset(&ldata);
+ CustomData_reset(&pdata);
+
mvert = CustomData_add_layer(&vdata, CD_MVERT, CD_CALLOC, NULL, totvert);
medge = CustomData_add_layer(&edata, CD_MEDGE, CD_CALLOC, NULL, totedge);
mloop = CustomData_add_layer(&ldata, CD_MLOOP, CD_CALLOC, NULL, totloop);
@@ -356,7 +372,8 @@ int join_mesh_exec(bContext *C, wmOperator *op)
fp1 = ((float *)kb->data) + (vertofs * 3);
/* check if this mesh has such a shapekey */
- okb = key_get_named_keyblock(me->key, kb->name);
+ okb = me->key ? BKE_keyblock_find_name(me->key, kb->name) : NULL;
+
if (okb) {
/* copy this mesh's shapekey to the destination shapekey (need to transform first) */
fp2 = ((float *)(okb->data));
@@ -386,7 +403,7 @@ int join_mesh_exec(bContext *C, wmOperator *op)
fp1 = ((float *)kb->data) + (vertofs * 3);
/* check if this was one of the original shapekeys */
- okb = key_get_named_keyblock(nkey, kb->name);
+ okb = nkey ? BKE_keyblock_find_name(nkey, kb->name) : NULL;
if (okb) {
/* copy this mesh's shapekey to the destination shapekey */
fp2 = ((float *)(okb->data));
@@ -427,8 +444,8 @@ int join_mesh_exec(bContext *C, wmOperator *op)
if ((mmd = get_multires_modifier(scene, base->object, TRUE))) {
ED_object_iter_other(bmain, base->object, TRUE,
- ED_object_multires_update_totlevels_cb,
- &mmd->totlvl);
+ ED_object_multires_update_totlevels_cb,
+ &mmd->totlvl);
}
}
@@ -499,7 +516,8 @@ int join_mesh_exec(bContext *C, wmOperator *op)
me->ldata = ldata;
me->pdata = pdata;
- mesh_update_customdata_pointers(me, TRUE); /* BMESH_TODO, check if this arg can be failse, non urgent - campbell */
+ /* tessface data removed above, no need to update */
+ mesh_update_customdata_pointers(me, FALSE);
/* old material array */
for (a = 1; a <= ob->totcol; a++) {
@@ -548,6 +566,12 @@ int join_mesh_exec(bContext *C, wmOperator *op)
MEM_freeN(nkey);
}
+ /* ensure newly inserted keys are time sorted */
+ if (key && (key->type != KEY_RELATIVE)) {
+ BKE_key_sort(key);
+ }
+
+
DAG_scene_sort(bmain, scene); // removed objects, need to rebuild dag before editmode call
#if 0
@@ -607,12 +631,12 @@ int join_mesh_shapes_exec(bContext *C, wmOperator *op)
}
if (key == NULL) {
- key = me->key = add_key((ID *)me);
+ key = me->key = BKE_key_add((ID *)me);
key->type = KEY_RELATIVE;
/* first key added, so it was the basis. initialize it with the existing mesh */
- kb = add_keyblock(key, NULL);
- mesh_to_key(me, kb);
+ kb = BKE_keyblock_add(key, NULL);
+ BKE_key_convert_from_mesh(me, kb);
}
/* now ready to add new keys from selected meshes */
@@ -628,7 +652,7 @@ int join_mesh_shapes_exec(bContext *C, wmOperator *op)
if (!dm) continue;
- kb = add_keyblock(key, base->object->id.name + 2);
+ kb = BKE_keyblock_add(key, base->object->id.name + 2);
DM_to_meshkey(dm, me, kb);
@@ -709,9 +733,9 @@ static void mesh_octree_add_nodes(MocNode **basetable, const float co[3], const
float fx, fy, fz;
int vx, vy, vz;
- if (!finite(co[0]) ||
- !finite(co[1]) ||
- !finite(co[2]))
+ if ((finite(co[0]) == FALSE) ||
+ (finite(co[1]) == FALSE) ||
+ (finite(co[2]) == FALSE))
{
return;
}
@@ -823,7 +847,7 @@ intptr_t mesh_octree_table(Object *ob, BMEditMesh *em, const float co[3], char m
minmax_v3v3_v3(min, max, eve->co);
}
}
- else {
+ else {
MVert *mvert;
int a;
@@ -858,7 +882,7 @@ intptr_t mesh_octree_table(Object *ob, BMEditMesh *em, const float co[3], char m
mesh_octree_add_nodes(MeshOctree.table, eve->co, MeshOctree.offs, MeshOctree.div, (intptr_t)(eve));
}
}
- else {
+ else {
MVert *mvert;
int a;
@@ -940,9 +964,9 @@ static BMVert *editbmesh_get_x_mirror_vert_spatial(Object *ob, BMEditMesh *em, c
intptr_t poinval;
/* ignore nan verts */
- if (!finite(co[0]) ||
- !finite(co[1]) ||
- !finite(co[2]))
+ if ((finite(co[0]) == FALSE) ||
+ (finite(co[1]) == FALSE) ||
+ (finite(co[2]) == FALSE))
{
return NULL;
}
@@ -1172,7 +1196,7 @@ int ED_mesh_pick_face(bContext *C, Mesh *me, const int mval[2], unsigned int *in
/* sample rect to increase chances of selecting, so that when clicking
* on an edge in the backbuf, we can still select a face */
- int dummy_dist;
+ float dummy_dist;
*index = view3d_sample_backbuf_rect(&vc, mval, size, 1, me->totpoly + 1, &dummy_dist, 0, NULL, NULL);
}
else {
@@ -1217,11 +1241,12 @@ int ED_mesh_pick_face_vert(bContext *C, Mesh *me, Object *ob, const int mval[2],
const int v_idx = me->mloop[mp->loopstart + fidx].v;
dm->getVertCo(dm, v_idx, co);
mul_m4_v3(ob->obmat, co);
- project_float_noclip(ar, co, sco);
- len = len_squared_v2v2(mval_f, sco);
- if (len < len_best) {
- len_best = len;
- v_idx_best = v_idx;
+ if (ED_view3d_project_float_global(ar, co, sco, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ len = len_squared_v2v2(mval_f, sco);
+ if (len < len_best) {
+ len_best = len;
+ v_idx_best = v_idx;
+ }
}
} while (fidx--);
}
@@ -1256,7 +1281,7 @@ int ED_mesh_pick_vert(bContext *C, Mesh *me, const int mval[2], unsigned int *in
/* sample rect to increase chances of selecting, so that when clicking
* on an face in the backbuf, we can still select a vert */
- int dummy_dist;
+ float dummy_dist;
*index = view3d_sample_backbuf_rect(&vc, mval, size, 1, me->totvert + 1, &dummy_dist, 0, NULL, NULL);
}
else {
diff --git a/source/blender/editors/metaball/mball_edit.c b/source/blender/editors/metaball/mball_edit.c
index 50d5569c483..8633a7a9b38 100644
--- a/source/blender/editors/metaball/mball_edit.c
+++ b/source/blender/editors/metaball/mball_edit.c
@@ -98,9 +98,8 @@ void load_editMball(Object *UNUSED(obedit))
}
/* Add metaelem primitive to metaball object (which is in edit mode) */
-MetaElem *add_metaball_primitive(bContext *C, float mat[4][4], int type, int UNUSED(newname))
+MetaElem *add_metaball_primitive(bContext *UNUSED(C), Object *obedit, float mat[4][4], float dia, int type, int UNUSED(newname))
{
- Object *obedit = CTX_data_edit_object(C);
MetaBall *mball = (MetaBall *)obedit->data;
MetaElem *ml;
@@ -112,6 +111,7 @@ MetaElem *add_metaball_primitive(bContext *C, float mat[4][4], int type, int UNU
}
ml = BKE_mball_element_add(mball, type);
+ ml->rad *= dia;
copy_v3_v3(&ml->x, mat[3]);
ml->flag |= SELECT;
@@ -124,43 +124,38 @@ MetaElem *add_metaball_primitive(bContext *C, float mat[4][4], int type, int UNU
/* Select or deselect all MetaElements */
static int mball_select_all_exec(bContext *C, wmOperator *op)
{
- //Scene *scene= CTX_data_scene(C);
Object *obedit = CTX_data_edit_object(C);
MetaBall *mb = (MetaBall *)obedit->data;
MetaElem *ml;
int action = RNA_enum_get(op->ptr, "action");
- ml = mb->editelems->first;
- if (ml) {
- if (action == SEL_TOGGLE) {
- action = SEL_SELECT;
- while (ml) {
- if (ml->flag & SELECT) {
- action = SEL_DESELECT;
- break;
- }
- ml = ml->next;
- }
- }
+ if (mb->editelems->first == NULL)
+ return OPERATOR_CANCELLED;
- ml = mb->editelems->first;
- while (ml) {
- switch (action) {
- case SEL_SELECT:
- ml->flag |= SELECT;
- break;
- case SEL_DESELECT:
- ml->flag &= ~SELECT;
- break;
- case SEL_INVERT:
- ml->flag ^= SELECT;
- break;
+ if (action == SEL_TOGGLE) {
+ action = SEL_SELECT;
+ for (ml = mb->editelems->first; ml; ml = ml->next) {
+ if (ml->flag & SELECT) {
+ action = SEL_DESELECT;
+ break;
}
- ml = ml->next;
}
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, mb);
}
+ switch (action) {
+ case SEL_SELECT:
+ BKE_mball_select_all(mb);
+ break;
+ case SEL_DESELECT:
+ BKE_mball_deselect_all(mb);
+ break;
+ case SEL_INVERT:
+ BKE_mball_select_swap(mb);
+ break;
+ }
+
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, mb);
+
return OPERATOR_FINISHED;
}
@@ -422,7 +417,7 @@ int mouse_mball(bContext *C, const int mval[2], int extend, int deselect, int to
Object *obedit = CTX_data_edit_object(C);
ViewContext vc;
MetaBall *mb = (MetaBall *)obedit->data;
- MetaElem *ml, *act = NULL;
+ MetaElem *ml, *ml_act = NULL;
int a, hits;
unsigned int buffer[4 * MAXPICKBUF];
rcti rect;
@@ -452,14 +447,14 @@ int mouse_mball(bContext *C, const int mval[2], int extend, int deselect, int to
/* index converted for gl stuff */
if (ml->selcol1 == buffer[4 * a + 3]) {
ml->flag |= MB_SCALE_RAD;
- act = ml;
+ ml_act = ml;
}
if (ml->selcol2 == buffer[4 * a + 3]) {
ml->flag &= ~MB_SCALE_RAD;
- act = ml;
+ ml_act = ml;
}
}
- if (act) break;
+ if (ml_act) break;
ml = ml->next;
if (ml == NULL) ml = mb->editelems->first;
if (ml == startelem) break;
@@ -467,31 +462,28 @@ int mouse_mball(bContext *C, const int mval[2], int extend, int deselect, int to
/* When some metaelem was found, then it is necessary to select or
* deselect it. */
- if (act) {
+ if (ml_act) {
if (extend) {
- act->flag |= SELECT;
+ ml_act->flag |= SELECT;
}
else if (deselect) {
- act->flag &= ~SELECT;
+ ml_act->flag &= ~SELECT;
}
else if (toggle) {
- if (act->flag & SELECT)
- act->flag &= ~SELECT;
+ if (ml_act->flag & SELECT)
+ ml_act->flag &= ~SELECT;
else
- act->flag |= SELECT;
+ ml_act->flag |= SELECT;
}
else {
/* Deselect all existing metaelems */
- ml = mb->editelems->first;
- while (ml) {
- ml->flag &= ~SELECT;
- ml = ml->next;
- }
+ BKE_mball_deselect_all(mb);
+
/* Select only metaelem clicked on */
- act->flag |= SELECT;
+ ml_act->flag |= SELECT;
}
- mb->lastelem = act;
+ mb->lastelem = ml_act;
WM_event_add_notifier(C, NC_GEOM | ND_SELECT, mb);
diff --git a/source/blender/editors/object/object_add.c b/source/blender/editors/object/object_add.c
index d73bbbabf84..9fc4e0a906d 100644
--- a/source/blender/editors/object/object_add.c
+++ b/source/blender/editors/object/object_add.c
@@ -43,6 +43,7 @@
#include "DNA_meta_types.h"
#include "DNA_object_fluidsim.h"
#include "DNA_object_force.h"
+#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "DNA_speaker_types.h"
#include "DNA_vfont_types.h"
@@ -110,7 +111,7 @@
#include "object_intern.h"
/* this is an exact copy of the define in rna_lamp.c
- * kept here because of linking order.
+ * kept here because of linking order.
* Icons are only defined here */
EnumPropertyItem lamp_type_items[] = {
{LA_LOCAL, "POINT", ICON_LAMP_POINT, "Point", "Omnidirectional point light source"},
@@ -121,6 +122,24 @@ EnumPropertyItem lamp_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
+/* copy from rna_object_force.c */
+static EnumPropertyItem field_type_items[] = {
+ {PFIELD_FORCE, "FORCE", ICON_FORCE_FORCE, "Force", ""},
+ {PFIELD_WIND, "WIND", ICON_FORCE_WIND, "Wind", ""},
+ {PFIELD_VORTEX, "VORTEX", ICON_FORCE_VORTEX, "Vortex", ""},
+ {PFIELD_MAGNET, "MAGNET", ICON_FORCE_MAGNETIC, "Magnetic", ""},
+ {PFIELD_HARMONIC, "HARMONIC", ICON_FORCE_HARMONIC, "Harmonic", ""},
+ {PFIELD_CHARGE, "CHARGE", ICON_FORCE_CHARGE, "Charge", ""},
+ {PFIELD_LENNARDJ, "LENNARDJ", ICON_FORCE_LENNARDJONES, "Lennard-Jones", ""},
+ {PFIELD_TEXTURE, "TEXTURE", ICON_FORCE_TEXTURE, "Texture", ""},
+ {PFIELD_GUIDE, "GUIDE", ICON_FORCE_CURVE, "Curve Guide", ""},
+ {PFIELD_BOID, "BOID", ICON_FORCE_BOID, "Boid", ""},
+ {PFIELD_TURBULENCE, "TURBULENCE", ICON_FORCE_TURBULENCE, "Turbulence", ""},
+ {PFIELD_DRAG, "DRAG", ICON_FORCE_DRAG, "Drag", ""},
+ {PFIELD_SMOKEFLOW, "SMOKE", ICON_FORCE_SMOKEFLOW, "Smoke Flow", ""},
+ {0, NULL, 0, NULL, NULL}
+};
+
/************************** Exported *****************************/
void ED_object_location_from_view(bContext *C, float loc[3])
@@ -128,7 +147,7 @@ void ED_object_location_from_view(bContext *C, float loc[3])
View3D *v3d = CTX_wm_view3d(C);
Scene *scene = CTX_data_scene(C);
float *cursor;
-
+
cursor = give_cursor(scene, v3d);
copy_v3_v3(loc, cursor);
@@ -152,46 +171,56 @@ void ED_object_base_init_transform(bContext *C, Base *base, const float loc[3],
{
Object *ob = base->object;
Scene *scene = CTX_data_scene(C);
-
+
if (!scene) return;
-
+
if (loc)
copy_v3_v3(ob->loc, loc);
-
+
if (rot)
copy_v3_v3(ob->rot, rot);
-
+
BKE_object_where_is_calc(scene, ob);
}
-/* uses context to figure out transform for primitive */
-/* returns standard diameter */
+/* Uses context to figure out transform for primitive.
+ * Returns standard diameter. */
float ED_object_new_primitive_matrix(bContext *C, Object *obedit,
- const float loc[3], const float rot[3], float primmat[][4])
+ const float loc[3], const float rot[3], float primmat[][4],
+ int apply_diameter)
{
Scene *scene = CTX_data_scene(C);
View3D *v3d = CTX_wm_view3d(C);
float mat[3][3], rmat[3][3], cmat[3][3], imat[3][3];
-
+
unit_m4(primmat);
-
+
eul_to_mat3(rmat, rot);
invert_m3(rmat);
-
+
/* inverse transform for initial rotation and object */
copy_m3_m4(mat, obedit->obmat);
mul_m3_m3m3(cmat, rmat, mat);
invert_m3_m3(imat, cmat);
copy_m4_m3(primmat, imat);
-
+
/* center */
copy_v3_v3(primmat[3], loc);
sub_v3_v3v3(primmat[3], primmat[3], obedit->obmat[3]);
invert_m3_m3(imat, mat);
mul_m3_v3(imat, primmat[3]);
-
- if (v3d)
- return ED_view3d_grid_scale(scene, v3d, NULL);
+
+ if (v3d) {
+ float dia = ED_view3d_grid_scale(scene, v3d, NULL);
+
+ if (apply_diameter) {
+ primmat[0][0] *= dia;
+ primmat[1][1] *= dia;
+ primmat[2][2] *= dia;
+ }
+
+ return dia;
+ }
return 1.0f;
}
@@ -206,7 +235,7 @@ static void view_align_update(struct Main *UNUSED(main), struct Scene *UNUSED(sc
void ED_object_add_generic_props(wmOperatorType *ot, int do_editmode)
{
PropertyRNA *prop;
-
+
/* note: this property gets hidden for add-camera operator */
prop = RNA_def_boolean(ot->srna, "view_align", 0, "Align to View", "Align the new object to the view");
RNA_def_property_update_runtime(prop, view_align_update);
@@ -216,112 +245,112 @@ void ED_object_add_generic_props(wmOperatorType *ot, int do_editmode)
"Enter editmode when adding this object");
RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}
-
+
prop = RNA_def_float_vector_xyz(ot->srna, "location", 3, NULL, -FLT_MAX, FLT_MAX, "Location",
"Location for the newly added object", -FLT_MAX, FLT_MAX);
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
prop = RNA_def_float_rotation(ot->srna, "rotation", 3, NULL, -FLT_MAX, FLT_MAX, "Rotation",
"Rotation for the newly added object", (float)-M_PI * 2.0f, (float)M_PI * 2.0f);
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
-
+
prop = RNA_def_boolean_layer_member(ot->srna, "layers", 20, NULL, "Layer", "");
RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}
-static void object_add_generic_invoke_options(bContext *C, wmOperator *op)
+int ED_object_add_generic_get_opts(bContext *C, wmOperator *op, float loc[3], float rot[3],
+ int *enter_editmode, unsigned int *layer, int *is_view_aligned)
{
- if (RNA_struct_find_property(op->ptr, "enter_editmode")) /* optional */
- if (!RNA_struct_property_is_set(op->ptr, "enter_editmode"))
- RNA_boolean_set(op->ptr, "enter_editmode", U.flag & USER_ADD_EDITMODE);
-
- if (!RNA_struct_property_is_set(op->ptr, "location")) {
- float loc[3];
-
- ED_object_location_from_view(C, loc);
- RNA_float_set_array(op->ptr, "location", loc);
- }
-
- if (!RNA_struct_property_is_set(op->ptr, "layers")) {
- View3D *v3d = CTX_wm_view3d(C);
- Scene *scene = CTX_data_scene(C);
- int a, values[20], layer;
+ View3D *v3d = CTX_wm_view3d(C);
- if (v3d) {
- layer = (v3d->scenelock && !v3d->localvd) ? scene->layact : v3d->layact;
- }
+ /* Switch to Edit mode? */
+ if (RNA_struct_find_property(op->ptr, "enter_editmode")) { /* optional */
+ int _enter_editmode;
+ if (!enter_editmode)
+ enter_editmode = &_enter_editmode;
+
+ if (RNA_struct_property_is_set(op->ptr, "enter_editmode") && enter_editmode)
+ *enter_editmode = RNA_boolean_get(op->ptr, "enter_editmode");
else {
- layer = scene->layact;
+ *enter_editmode = U.flag & USER_ADD_EDITMODE;
+ RNA_boolean_set(op->ptr, "enter_editmode", *enter_editmode);
}
+ }
- for (a = 0; a < 20; a++) {
- values[a] = (layer & (1 << a));
+ /* Get layers! */
+ {
+ int a, layer_values[20];
+ unsigned int _layer;
+ if (!layer)
+ layer = &_layer;
+
+ if (RNA_struct_property_is_set(op->ptr, "layers")) {
+ RNA_boolean_get_array(op->ptr, "layers", layer_values);
+ *layer = 0;
+ for (a = 0; a < 20; a++) {
+ if (layer_values[a])
+ *layer |= (1 << a);
+ }
+ }
+ else {
+ Scene *scene = CTX_data_scene(C);
+ if (v3d)
+ *layer = (v3d->scenelock && !v3d->localvd) ? scene->layact : v3d->layact;
+ else
+ *layer = scene->layact;
+ for (a = 0; a < 20; a++) {
+ layer_values[a] = *layer & (1 << a);
+ }
+ RNA_boolean_set_array(op->ptr, "layers", layer_values);
}
- RNA_boolean_set_array(op->ptr, "layers", values);
+ /* in local view we additionally add local view layers,
+ * not part of operator properties */
+ if (v3d && v3d->localvd)
+ *layer |= v3d->lay;
}
-}
-
-int ED_object_add_generic_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
-{
- object_add_generic_invoke_options(C, op);
- return op->type->exec(C, op);
-}
-int ED_object_add_generic_get_opts(bContext *C, wmOperator *op, float loc[3], float rot[3],
- int *enter_editmode, unsigned int *layer, int *is_view_aligned)
-{
- View3D *v3d = CTX_wm_view3d(C);
- int a, layer_values[20];
- int view_align;
-
- *enter_editmode = FALSE;
- if (RNA_struct_find_property(op->ptr, "enter_editmode") && RNA_boolean_get(op->ptr, "enter_editmode")) {
- *enter_editmode = TRUE;
- }
+ /* Location! */
+ {
+ float _loc[3];
+ if (!loc)
+ loc = _loc;
- if (RNA_struct_property_is_set(op->ptr, "layers")) {
- RNA_boolean_get_array(op->ptr, "layers", layer_values);
- *layer = 0;
- for (a = 0; a < 20; a++) {
- if (layer_values[a])
- *layer |= (1 << a);
- else
- *layer &= ~(1 << a);
+ if (RNA_struct_property_is_set(op->ptr, "location")) {
+ RNA_float_get_array(op->ptr, "location", loc);
+ }
+ else {
+ ED_object_location_from_view(C, loc);
+ RNA_float_set_array(op->ptr, "location", loc);
}
- }
- else {
- /* not set, use the scenes layers */
- Scene *scene = CTX_data_scene(C);
- *layer = scene->layact;
}
- /* in local view we additionally add local view layers,
- * not part of operator properties */
- if (v3d && v3d->localvd)
- *layer |= v3d->lay;
+ /* Rotation! */
+ {
+ int _is_view_aligned;
+ float _rot[3];
+ if (!is_view_aligned)
+ is_view_aligned = &_is_view_aligned;
+ if (!rot)
+ rot = _rot;
+
+ if (RNA_struct_property_is_set(op->ptr, "rotation"))
+ *is_view_aligned = FALSE;
+ else if (RNA_struct_property_is_set(op->ptr, "view_align"))
+ *is_view_aligned = RNA_boolean_get(op->ptr, "view_align");
+ else {
+ *is_view_aligned = U.flag & USER_ADD_VIEWALIGNED;
+ RNA_boolean_set(op->ptr, "view_align", *is_view_aligned);
+ }
- if (RNA_struct_property_is_set(op->ptr, "rotation"))
- view_align = FALSE;
- else if (RNA_struct_property_is_set(op->ptr, "view_align"))
- view_align = RNA_boolean_get(op->ptr, "view_align");
- else {
- view_align = U.flag & USER_ADD_VIEWALIGNED;
- RNA_boolean_set(op->ptr, "view_align", view_align);
- }
-
- if (view_align) {
- ED_object_rotation_from_view(C, rot);
- RNA_float_set_array(op->ptr, "rotation", rot);
+ if (*is_view_aligned) {
+ ED_object_rotation_from_view(C, rot);
+ RNA_float_set_array(op->ptr, "rotation", rot);
+ }
+ else
+ RNA_float_get_array(op->ptr, "rotation", rot);
}
- else
- RNA_float_get_array(op->ptr, "rotation", rot);
-
- if (is_view_aligned)
- *is_view_aligned = view_align;
-
- RNA_float_get_array(op->ptr, "location", loc);
-
- if (*layer == 0) {
+
+ if (layer && *layer == 0) {
BKE_report(op->reports, RPT_ERROR, "Property 'layer' has no values set");
return 0;
}
@@ -329,19 +358,19 @@ int ED_object_add_generic_get_opts(bContext *C, wmOperator *op, float loc[3], fl
return 1;
}
-/* for object add primitive operators */
-/* do not call undo push in this function (users of this function have to) */
+/* For object add primitive operators.
+ * Do not call undo push in this function (users of this function have to). */
Object *ED_object_add_type(bContext *C, int type, const float loc[3], const float rot[3],
int enter_editmode, unsigned int layer)
{
Main *bmain = CTX_data_main(C);
Scene *scene = CTX_data_scene(C);
Object *ob;
-
+
/* for as long scene has editmode... */
if (CTX_data_edit_object(C))
ED_object_exit_editmode(C, EM_FREEDATA | EM_FREEUNDO | EM_WAITCURSOR | EM_DO_UNDO); /* freedata, and undo */
-
+
/* deselects all, sets scene->basact */
ob = BKE_object_add(scene, type);
BASACT->lay = ob->lay = layer;
@@ -371,12 +400,12 @@ static int object_add_exec(bContext *C, wmOperator *op)
int enter_editmode;
unsigned int layer;
float loc[3], rot[3];
-
+
if (!ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL))
return OPERATOR_CANCELLED;
ED_object_add_type(C, RNA_enum_get(op->ptr, "type"), loc, rot, enter_editmode, layer);
-
+
return OPERATOR_FINISHED;
}
@@ -386,89 +415,62 @@ void OBJECT_OT_add(wmOperatorType *ot)
ot->name = "Add Object";
ot->description = "Add an object to the scene";
ot->idname = "OBJECT_OT_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = object_add_exec;
-
ot->poll = ED_operator_objectmode;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
RNA_def_enum(ot->srna, "type", object_type_items, 0, "Type", "");
ED_object_add_generic_props(ot, TRUE);
}
/********************* Add Effector Operator ********************/
-/* copy from rna_object_force.c*/
-static EnumPropertyItem field_type_items[] = {
- {PFIELD_FORCE, "FORCE", ICON_FORCE_FORCE, "Force", ""},
- {PFIELD_WIND, "WIND", ICON_FORCE_WIND, "Wind", ""},
- {PFIELD_VORTEX, "VORTEX", ICON_FORCE_VORTEX, "Vortex", ""},
- {PFIELD_MAGNET, "MAGNET", ICON_FORCE_MAGNETIC, "Magnetic", ""},
- {PFIELD_HARMONIC, "HARMONIC", ICON_FORCE_HARMONIC, "Harmonic", ""},
- {PFIELD_CHARGE, "CHARGE", ICON_FORCE_CHARGE, "Charge", ""},
- {PFIELD_LENNARDJ, "LENNARDJ", ICON_FORCE_LENNARDJONES, "Lennard-Jones", ""},
- {PFIELD_TEXTURE, "TEXTURE", ICON_FORCE_TEXTURE, "Texture", ""},
- {PFIELD_GUIDE, "GUIDE", ICON_FORCE_CURVE, "Curve Guide", ""},
- {PFIELD_BOID, "BOID", ICON_FORCE_BOID, "Boid", ""},
- {PFIELD_TURBULENCE, "TURBULENCE", ICON_FORCE_TURBULENCE, "Turbulence", ""},
- {PFIELD_DRAG, "DRAG", ICON_FORCE_DRAG, "Drag", ""},
- {0, NULL, 0, NULL, NULL}};
-/* for effector add primitive operators */
-static Object *effector_add_type(bContext *C, wmOperator *op, int type)
+/* for object add operator */
+static int effector_add_exec(bContext *C, wmOperator *op)
{
Object *ob;
- int enter_editmode;
+ int type, enter_editmode;
unsigned int layer;
float loc[3], rot[3];
float mat[4][4];
-
- object_add_generic_invoke_options(C, op);
if (!ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL))
- return NULL;
+ return OPERATOR_CANCELLED;
+
+ type = RNA_enum_get(op->ptr, "type");
if (type == PFIELD_GUIDE) {
ob = ED_object_add_type(C, OB_CURVE, loc, rot, FALSE, layer);
- rename_id(&ob->id, "CurveGuide");
+ if (!ob)
+ return OPERATOR_CANCELLED;
+ rename_id(&ob->id, "CurveGuide");
((Curve *)ob->data)->flag |= CU_PATH | CU_3D;
ED_object_enter_editmode(C, 0);
- ED_object_new_primitive_matrix(C, ob, loc, rot, mat);
- BLI_addtail(object_editcurve_get(ob), add_nurbs_primitive(C, mat, CU_NURBS | CU_PRIM_PATH, 1));
-
+ ED_object_new_primitive_matrix(C, ob, loc, rot, mat, FALSE);
+ BLI_addtail(object_editcurve_get(ob), add_nurbs_primitive(C, ob, mat, CU_NURBS | CU_PRIM_PATH, 1));
if (!enter_editmode)
ED_object_exit_editmode(C, EM_FREEDATA);
}
else {
ob = ED_object_add_type(C, OB_EMPTY, loc, rot, FALSE, layer);
- rename_id(&ob->id, "Field");
+ if (!ob)
+ return OPERATOR_CANCELLED;
- switch (type) {
- case PFIELD_WIND:
- case PFIELD_VORTEX:
- ob->empty_drawtype = OB_SINGLE_ARROW;
- break;
- }
+ rename_id(&ob->id, "Field");
+ if (ELEM(type, PFIELD_WIND, PFIELD_VORTEX))
+ ob->empty_drawtype = OB_SINGLE_ARROW;
}
ob->pd = object_add_collision_fields(type);
DAG_scene_sort(CTX_data_main(C), CTX_data_scene(C));
- return ob;
-}
-
-/* for object add operator */
-static int effector_add_exec(bContext *C, wmOperator *op)
-{
- if (effector_add_type(C, op, RNA_enum_get(op->ptr, "type")) == NULL)
- return OPERATOR_CANCELLED;
-
return OPERATOR_FINISHED;
}
@@ -478,22 +480,20 @@ void OBJECT_OT_effector_add(wmOperatorType *ot)
ot->name = "Add Effector";
ot->description = "Add an empty object with a physics effector to the scene";
ot->idname = "OBJECT_OT_effector_add";
-
+
/* api callbacks */
- ot->invoke = WM_menu_invoke;
ot->exec = effector_add_exec;
-
ot->poll = ED_operator_objectmode;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
ot->prop = RNA_def_enum(ot->srna, "type", field_type_items, 0, "Type", "");
ED_object_add_generic_props(ot, TRUE);
}
-/* ***************** Add Camera *************** */
+/********************* Add Camera Operator ********************/
static int object_camera_add_exec(bContext *C, wmOperator *op)
{
@@ -503,17 +503,15 @@ static int object_camera_add_exec(bContext *C, wmOperator *op)
int enter_editmode;
unsigned int layer;
float loc[3], rot[3];
-
+
/* force view align for cameras */
RNA_boolean_set(op->ptr, "view_align", TRUE);
-
- object_add_generic_invoke_options(C, op);
if (!ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL))
return OPERATOR_CANCELLED;
ob = ED_object_add_type(C, OB_CAMERA, loc, rot, FALSE, layer);
-
+
if (v3d) {
if (v3d->camera == NULL)
v3d->camera = ob;
@@ -528,81 +526,61 @@ static int object_camera_add_exec(bContext *C, wmOperator *op)
void OBJECT_OT_camera_add(wmOperatorType *ot)
{
PropertyRNA *prop;
-
+
/* identifiers */
ot->name = "Add Camera";
ot->description = "Add a camera object to the scene";
ot->idname = "OBJECT_OT_camera_add";
-
+
/* api callbacks */
ot->exec = object_camera_add_exec;
ot->poll = ED_operator_objectmode;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
ED_object_add_generic_props(ot, TRUE);
-
+
/* hide this for cameras, default */
prop = RNA_struct_type_find_property(ot->srna, "view_align");
RNA_def_property_flag(prop, PROP_HIDDEN);
-
}
-/* ***************** add primitives *************** */
+/********************* Add Metaball Operator ********************/
+
static int object_metaball_add_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
- /*MetaElem *elem;*/ /*UNUSED*/
int newob = 0;
int enter_editmode;
unsigned int layer;
float loc[3], rot[3];
float mat[4][4];
-
- object_add_generic_invoke_options(C, op); /* XXX these props don't get set right when only exec() is called */
+ float dia;
if (!ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL))
return OPERATOR_CANCELLED;
-
+
if (obedit == NULL || obedit->type != OB_MBALL) {
obedit = ED_object_add_type(C, OB_MBALL, loc, rot, TRUE, layer);
newob = 1;
}
- else DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
-
- ED_object_new_primitive_matrix(C, obedit, loc, rot, mat);
-
- /* elem= (MetaElem *) */ add_metaball_primitive(C, mat, RNA_enum_get(op->ptr, "type"), newob);
+ else
+ DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
+
+ dia = ED_object_new_primitive_matrix(C, obedit, loc, rot, mat, FALSE);
+
+ add_metaball_primitive(C, obedit, mat, dia, RNA_enum_get(op->ptr, "type"), newob);
/* userdef */
if (newob && !enter_editmode) {
ED_object_exit_editmode(C, EM_FREEDATA);
}
-
- WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obedit);
-
- return OPERATOR_FINISHED;
-}
-
-static int object_metaball_add_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
-{
- Object *obedit = CTX_data_edit_object(C);
- uiPopupMenu *pup;
- uiLayout *layout;
-
- object_add_generic_invoke_options(C, op);
- pup = uiPupMenuBegin(C, op->type->name, ICON_NONE);
- layout = uiPupMenuLayout(pup);
- if (!obedit || obedit->type == OB_MBALL)
- uiItemsEnumO(layout, op->type->idname, "type");
- else
- uiItemsEnumO(layout, "OBJECT_OT_metaball_add", "type");
- uiPupMenuEnd(C, pup);
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obedit);
- return OPERATOR_CANCELLED;
+ return OPERATOR_FINISHED;
}
void OBJECT_OT_metaball_add(wmOperatorType *ot)
@@ -613,35 +591,37 @@ void OBJECT_OT_metaball_add(wmOperatorType *ot)
ot->idname = "OBJECT_OT_metaball_add";
/* api callbacks */
- ot->invoke = object_metaball_add_invoke;
+ ot->invoke = WM_menu_invoke;/* object_metaball_add_invoke; */
ot->exec = object_metaball_add_exec;
ot->poll = ED_operator_scene_editable;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
- RNA_def_enum(ot->srna, "type", metaelem_type_items, 0, "Primitive", "");
+
+ ot->prop = RNA_def_enum(ot->srna, "type", metaelem_type_items, 0, "Primitive", "");
+
ED_object_add_generic_props(ot, TRUE);
}
+/********************* Add Text Operator ********************/
+
static int object_add_text_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
int enter_editmode;
unsigned int layer;
float loc[3], rot[3];
-
- object_add_generic_invoke_options(C, op); /* XXX these props don't get set right when only exec() is called */
+
if (!ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL))
return OPERATOR_CANCELLED;
-
+
if (obedit && obedit->type == OB_FONT)
return OPERATOR_CANCELLED;
obedit = ED_object_add_type(C, OB_FONT, loc, rot, enter_editmode, layer);
-
+
WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obedit);
-
+
return OPERATOR_FINISHED;
}
@@ -651,17 +631,18 @@ void OBJECT_OT_text_add(wmOperatorType *ot)
ot->name = "Add Text";
ot->description = "Add a text object to the scene";
ot->idname = "OBJECT_OT_text_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = object_add_text_exec;
ot->poll = ED_operator_objectmode;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
ED_object_add_generic_props(ot, TRUE);
}
+/********************* Add Armature Operator ********************/
+
static int object_armature_add_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -672,7 +653,6 @@ static int object_armature_add_exec(bContext *C, wmOperator *op)
unsigned int layer;
float loc[3], rot[3];
- object_add_generic_invoke_options(C, op); /* XXX these props don't get set right when only exec() is called */
if (!ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL))
return OPERATOR_CANCELLED;
@@ -687,36 +667,76 @@ static int object_armature_add_exec(bContext *C, wmOperator *op)
BKE_report(op->reports, RPT_ERROR, "Cannot create editmode armature");
return OPERATOR_CANCELLED;
}
-
+
/* v3d and rv3d are allowed to be NULL */
add_primitive_bone(CTX_data_scene(C), v3d, rv3d);
/* userdef */
if (newob && !enter_editmode)
ED_object_exit_editmode(C, EM_FREEDATA);
-
+
WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obedit);
-
+
return OPERATOR_FINISHED;
}
void OBJECT_OT_armature_add(wmOperatorType *ot)
-{
+{
/* identifiers */
ot->name = "Add Armature";
ot->description = "Add an armature object to the scene";
ot->idname = "OBJECT_OT_armature_add";
-
+
/* api callbacks */
- ot->invoke = ED_object_add_generic_invoke;
ot->exec = object_armature_add_exec;
ot->poll = ED_operator_objectmode;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
ED_object_add_generic_props(ot, TRUE);
}
+/********************* Add Empty Operator ********************/
+
+static int object_empty_add_exec(bContext *C, wmOperator *op)
+{
+ Object *ob;
+ int type = RNA_enum_get(op->ptr, "type");
+ unsigned int layer;
+ float loc[3], rot[3];
+
+ if (!ED_object_add_generic_get_opts(C, op, loc, rot, NULL, &layer, NULL))
+ return OPERATOR_CANCELLED;
+
+ ob = ED_object_add_type(C, OB_EMPTY, loc, rot, FALSE, layer);
+ ob->empty_drawtype = type;
+
+ return OPERATOR_FINISHED;
+}
+
+void OBJECT_OT_empty_add(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Add Empty";
+ ot->description = "Add an empty object to the scene";
+ ot->idname = "OBJECT_OT_empty_add";
+
+ /* api callbacks */
+ ot->invoke = WM_menu_invoke;
+ ot->exec = object_empty_add_exec;
+ ot->poll = ED_operator_objectmode;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
+ ot->prop = RNA_def_enum(ot->srna, "type", object_empty_drawtype_items, 0, "Type", "");
+
+ ED_object_add_generic_props(ot, FALSE);
+}
+
+/********************* Add Lamp Operator ********************/
+
static const char *get_lamp_defname(int type)
{
switch (type) {
@@ -736,12 +756,10 @@ static int object_lamp_add_exec(bContext *C, wmOperator *op)
Object *ob;
Lamp *la;
int type = RNA_enum_get(op->ptr, "type");
- int enter_editmode;
unsigned int layer;
float loc[3], rot[3];
-
- object_add_generic_invoke_options(C, op);
- if (!ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL))
+
+ if (!ED_object_add_generic_get_opts(C, op, loc, rot, NULL, &layer, NULL))
return OPERATOR_CANCELLED;
ob = ED_object_add_type(C, OB_LAMP, loc, rot, FALSE, layer);
@@ -755,7 +773,7 @@ static int object_lamp_add_exec(bContext *C, wmOperator *op)
ED_node_shader_default(scene, &la->id);
la->use_nodes = TRUE;
}
-
+
return OPERATOR_FINISHED;
}
@@ -765,12 +783,12 @@ void OBJECT_OT_lamp_add(wmOperatorType *ot)
ot->name = "Add Lamp";
ot->description = "Add a lamp object to the scene";
ot->idname = "OBJECT_OT_lamp_add";
-
+
/* api callbacks */
ot->invoke = WM_menu_invoke;
ot->exec = object_lamp_add_exec;
ot->poll = ED_operator_objectmode;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -780,16 +798,16 @@ void OBJECT_OT_lamp_add(wmOperatorType *ot)
ED_object_add_generic_props(ot, FALSE);
}
+/********************* Add Group Instance Operator ********************/
+
static int group_instance_add_exec(bContext *C, wmOperator *op)
{
Group *group = BLI_findlink(&CTX_data_main(C)->group, RNA_enum_get(op->ptr, "group"));
- int enter_editmode;
unsigned int layer;
float loc[3], rot[3];
-
- object_add_generic_invoke_options(C, op);
- if (!ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL))
+
+ if (!ED_object_add_generic_get_opts(C, op, loc, rot, NULL, &layer, NULL))
return OPERATOR_CANCELLED;
if (group) {
@@ -812,20 +830,42 @@ static int group_instance_add_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
+/* only used as menu */
+void OBJECT_OT_group_instance_add(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Add Group Instance";
+ ot->description = "Add a dupligroup instance";
+ ot->idname = "OBJECT_OT_group_instance_add";
+
+ /* api callbacks */
+ ot->invoke = WM_enum_search_invoke;
+ ot->exec = group_instance_add_exec;
+ ot->poll = ED_operator_objectmode;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
+ ot->prop = RNA_def_enum(ot->srna, "group", DummyRNA_NULL_items, 0, "Group", "");
+ RNA_def_enum_funcs(ot->prop, RNA_group_itemf);
+ ED_object_add_generic_props(ot, FALSE);
+}
+
+/********************* Add Speaker Operator ********************/
+
static int object_speaker_add_exec(bContext *C, wmOperator *op)
{
Object *ob;
- int enter_editmode;
unsigned int layer;
float loc[3], rot[3];
Scene *scene = CTX_data_scene(C);
- object_add_generic_invoke_options(C, op);
- if (!ED_object_add_generic_get_opts(C, op, loc, rot, &enter_editmode, &layer, NULL))
+ if (!ED_object_add_generic_get_opts(C, op, loc, rot, NULL, &layer, NULL))
return OPERATOR_CANCELLED;
ob = ED_object_add_type(C, OB_SPEAKER, loc, rot, FALSE, layer);
-
+
/* to make it easier to start using this immediately in NLA, a default sound clip is created
* ready to be moved around to retime the sound and/or make new sound clips
*/
@@ -836,14 +876,14 @@ static int object_speaker_add_exec(bContext *C, wmOperator *op)
NlaStrip *strip = add_nla_soundstrip(CTX_data_scene(C), ob->data);
strip->start = CFRA;
strip->end += strip->start;
-
+
/* hook them up */
BKE_nlatrack_add_strip(nlt, strip);
-
+
/* auto-name the strip, and give the track an interesting name */
strcpy(nlt->name, "SoundTrack");
BKE_nlastrip_validate_name(adt, strip);
-
+
WM_event_add_notifier(C, NC_ANIMATION | ND_NLA | NA_EDITED, NULL);
}
@@ -867,32 +907,6 @@ void OBJECT_OT_speaker_add(wmOperatorType *ot)
ED_object_add_generic_props(ot, TRUE);
}
-/* only used as menu */
-void OBJECT_OT_group_instance_add(wmOperatorType *ot)
-{
- PropertyRNA *prop;
-
- /* identifiers */
- ot->name = "Add Group Instance";
- ot->description = "Add a dupligroup instance";
- ot->idname = "OBJECT_OT_group_instance_add";
-
- /* api callbacks */
- ot->invoke = WM_enum_search_invoke;
- ot->exec = group_instance_add_exec;
-
- ot->poll = ED_operator_objectmode;
-
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
- /* properties */
- prop = RNA_def_enum(ot->srna, "group", DummyRNA_NULL_items, 0, "Group", "");
- RNA_def_enum_funcs(prop, RNA_group_itemf);
- ot->prop = prop;
- ED_object_add_generic_props(ot, FALSE);
-}
-
/**************************** Delete Object *************************/
static void object_delete_check_glsl_update(Object *ob)
@@ -901,7 +915,7 @@ static void object_delete_check_glsl_update(Object *ob)
* are being tagged to be updated when object is removing from scene
*/
if (ob->type == OB_LAMP) {
- if (ob->gpulamp.first)
+ if (ob->gpulamp.first)
GPU_lamp_free(ob);
}
}
@@ -923,16 +937,12 @@ static int object_delete_exec(bContext *C, wmOperator *op)
Main *bmain = CTX_data_main(C);
Scene *scene = CTX_data_scene(C);
const short use_global = RNA_boolean_get(op->ptr, "use_global");
- /* int is_lamp = FALSE; */ /* UNUSED */
-
+
if (CTX_data_edit_object(C))
return OPERATOR_CANCELLED;
-
+
CTX_DATA_BEGIN (C, Base *, base, selected_bases)
{
-
- /* if (base->object->type==OB_LAMP) is_lamp = TRUE; */
-
/* deselect object -- it could be used in other scenes */
base->object->flag &= ~SELECT;
@@ -959,10 +969,10 @@ static int object_delete_exec(bContext *C, wmOperator *op)
DAG_scene_sort(bmain, scene);
DAG_ids_flush_update(bmain, 0);
-
+
WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, scene);
-
+
return OPERATOR_FINISHED;
}
@@ -972,12 +982,12 @@ void OBJECT_OT_delete(wmOperatorType *ot)
ot->name = "Delete";
ot->description = "Delete selected objects";
ot->idname = "OBJECT_OT_delete";
-
+
/* api callbacks */
ot->invoke = WM_operator_confirm;
ot->exec = object_delete_exec;
ot->poll = ED_operator_objectmode;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -993,29 +1003,29 @@ static void copy_object_set_idnew(bContext *C, int dupflag)
Material *ma, *mao;
ID *id;
int a;
-
+
/* XXX check object pointers */
CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
{
BKE_object_relink(ob);
}
CTX_DATA_END;
-
+
/* materials */
if (dupflag & USER_DUP_MAT) {
mao = bmain->mat.first;
while (mao) {
if (mao->id.newid) {
-
ma = (Material *)mao->id.newid;
-
+
if (dupflag & USER_DUP_TEX) {
for (a = 0; a < MAX_MTEX; a++) {
if (ma->mtex[a]) {
id = (ID *)ma->mtex[a]->tex;
if (id) {
ID_NEW_US(ma->mtex[a]->tex)
- else ma->mtex[a]->tex = BKE_texture_copy(ma->mtex[a]->tex);
+ else
+ ma->mtex[a]->tex = BKE_texture_copy(ma->mtex[a]->tex);
id->us--;
}
}
@@ -1025,7 +1035,8 @@ static void copy_object_set_idnew(bContext *C, int dupflag)
id = (ID *)ma->ipo;
if (id) {
ID_NEW_US(ma->ipo)
- else ma->ipo = copy_ipo(ma->ipo);
+ else
+ ma->ipo = copy_ipo(ma->ipo);
id->us--;
}
#endif // XXX old animation system
@@ -1033,7 +1044,7 @@ static void copy_object_set_idnew(bContext *C, int dupflag)
mao = mao->id.next;
}
}
-
+
#if 0 // XXX old animation system
/* lamps */
if (dupflag & USER_DUP_IPO) {
@@ -1044,14 +1055,15 @@ static void copy_object_set_idnew(bContext *C, int dupflag)
id = (ID *)lan->ipo;
if (id) {
ID_NEW_US(lan->ipo)
- else lan->ipo = copy_ipo(lan->ipo);
+ else
+ lan->ipo = copy_ipo(lan->ipo);
id->us--;
}
}
la = la->id.next;
}
}
-
+
/* ipos */
ipo = bmain->ipo.first;
while (ipo) {
@@ -1067,9 +1079,9 @@ static void copy_object_set_idnew(bContext *C, int dupflag)
ipo = ipo->id.next;
}
#endif // XXX old animation system
-
+
set_sca_new_poins();
-
+
clear_id_newpoins();
}
@@ -1082,17 +1094,17 @@ static void make_object_duplilist_real(bContext *C, Scene *scene, Base *base,
ListBase *lb;
DupliObject *dob;
GHash *dupli_gh = NULL, *parent_gh = NULL;
-
+
if (!(base->object->transflag & OB_DUPLI))
return;
-
- lb = object_duplilist(scene, base->object);
+
+ lb = object_duplilist(scene, base->object, FALSE);
if (use_hierarchy || use_base_parent) {
dupli_gh = BLI_ghash_ptr_new("make_object_duplilist_real dupli_gh");
parent_gh = BLI_ghash_pair_new("make_object_duplilist_real parent_gh");
}
-
+
for (dob = lb->first; dob; dob = dob->next) {
Base *basen;
Object *ob = BKE_object_copy(dob->ob);
@@ -1100,24 +1112,24 @@ static void make_object_duplilist_real(bContext *C, Scene *scene, Base *base,
* should be implemented better...
*/
if (ob->mat == NULL) ob->totcol = 0;
-
+
basen = MEM_dupallocN(base);
basen->flag &= ~(OB_FROMDUPLI | OB_FROMGROUP);
ob->flag = basen->flag;
basen->lay = base->lay;
BLI_addhead(&scene->base, basen); /* addhead: othwise eternal loop */
basen->object = ob;
-
+
/* make sure apply works */
- BKE_free_animdata(&ob->id);
+ BKE_free_animdata(&ob->id);
ob->adt = NULL;
-
+
ob->parent = NULL;
ob->constraints.first = ob->constraints.last = NULL;
ob->disp.first = ob->disp.last = NULL;
- ob->transflag &= ~OB_DUPLI;
+ ob->transflag &= ~OB_DUPLI;
ob->lay = base->lay;
-
+
copy_m4_m4(ob->obmat, dob->mat);
BKE_object_apply_mat4(ob, ob->obmat, FALSE, FALSE);
@@ -1126,7 +1138,7 @@ static void make_object_duplilist_real(bContext *C, Scene *scene, Base *base,
if (parent_gh)
BLI_ghash_insert(parent_gh, BLI_ghashutil_pairalloc(dob->ob, SET_INT_IN_POINTER(dob->index)), ob);
}
-
+
if (use_hierarchy) {
for (dob = lb->first; dob; dob = dob->next) {
/* original parents */
@@ -1186,8 +1198,6 @@ static void make_object_duplilist_real(bContext *C, Scene *scene, Base *base,
invert_m4_m4(ob_dst->parentinv, dob->mat);
BKE_object_apply_mat4(ob_dst, dob->mat, FALSE, TRUE);
DAG_id_tag_update(&ob_dst->id, OB_RECALC_OB);
-
-
}
}
@@ -1197,9 +1207,9 @@ static void make_object_duplilist_real(bContext *C, Scene *scene, Base *base,
BLI_ghash_free(parent_gh, BLI_ghashutil_pairfree, NULL);
copy_object_set_idnew(C, 0);
-
+
free_object_duplilist(lb);
-
+
base->object->transflag &= ~OB_DUPLI;
}
@@ -1210,9 +1220,9 @@ static int object_duplicates_make_real_exec(bContext *C, wmOperator *op)
const short use_base_parent = RNA_boolean_get(op->ptr, "use_base_parent");
const short use_hierarchy = RNA_boolean_get(op->ptr, "use_hierarchy");
-
+
clear_id_newpoins();
-
+
CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
{
make_object_duplilist_real(C, scene, base, use_base_parent, use_hierarchy);
@@ -1226,23 +1236,22 @@ static int object_duplicates_make_real_exec(bContext *C, wmOperator *op)
DAG_ids_flush_update(bmain, 0);
WM_event_add_notifier(C, NC_SCENE, scene);
WM_main_add_notifier(NC_OBJECT | ND_DRAW, NULL);
-
+
return OPERATOR_FINISHED;
}
void OBJECT_OT_duplicates_make_real(wmOperatorType *ot)
{
-
/* identifiers */
ot->name = "Make Duplicates Real";
ot->description = "Make dupli objects attached to this object real";
ot->idname = "OBJECT_OT_duplicates_make_real";
-
+
/* api callbacks */
ot->exec = object_duplicates_make_real_exec;
-
+
ot->poll = ED_operator_objectmode;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1398,7 +1407,7 @@ static int convert_exec(bContext *C, wmOperator *op)
* cases this doesnt give correct results (when MDEF is used for eg)
*/
dm = mesh_get_derived_final(scene, newob, CD_MASK_MESH);
- /* dm= mesh_create_derived_no_deform(ob1, NULL); this was called original (instead of get_derived). man o man why! (ton) */
+ // dm = mesh_create_derived_no_deform(ob1, NULL); /* this was called original (instead of get_derived). man o man why! (ton) */
DM_to_mesh(dm, newob->data, newob);
@@ -1564,7 +1573,7 @@ static int convert_exec(bContext *C, wmOperator *op)
/* delete original if needed */
if (basedel) {
if (!keep_original)
- ED_base_object_free_and_unlink(bmain, scene, basedel);
+ ED_base_object_free_and_unlink(bmain, scene, basedel);
basedel = NULL;
}
@@ -1616,12 +1625,12 @@ void OBJECT_OT_convert(wmOperatorType *ot)
ot->name = "Convert to";
ot->description = "Convert selected objects to another type";
ot->idname = "OBJECT_OT_convert";
-
+
/* api callbacks */
ot->invoke = WM_menu_invoke;
ot->exec = convert_exec;
ot->poll = convert_poll;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1655,12 +1664,12 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, Base *base
else {
obn = BKE_object_copy(ob);
obn->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
-
+
basen = MEM_mallocN(sizeof(Base), "duplibase");
*basen = *base;
BLI_addhead(&scene->base, basen); /* addhead: prevent eternal loop */
basen->object = obn;
-
+
if (basen->flag & OB_FROMGROUP) {
Group *group;
for (group = bmain->group.first; group; group = group->id.next) {
@@ -1668,20 +1677,21 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, Base *base
add_to_group(group, obn, scene, basen);
}
}
-
+
/* duplicates using userflags */
if (dupflag & USER_DUP_ACT) {
BKE_copy_animdata_id_action(&obn->id);
}
-
+
if (dupflag & USER_DUP_MAT) {
for (a = 0; a < obn->totcol; a++) {
id = (ID *)obn->mat[a];
if (id) {
ID_NEW_US(obn->mat[a])
- else obn->mat[a] = BKE_material_copy(obn->mat[a]);
+ else
+ obn->mat[a] = BKE_material_copy(obn->mat[a]);
id->us--;
-
+
if (dupflag & USER_DUP_ACT) {
BKE_copy_animdata_id_action(&obn->mat[a]->id);
}
@@ -1694,8 +1704,9 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, Base *base
id = (ID *) psys->part;
if (id) {
ID_NEW_US(psys->part)
- else psys->part = BKE_particlesettings_copy(psys->part);
-
+ else
+ psys->part = BKE_particlesettings_copy(psys->part);
+
if (dupflag & USER_DUP_ACT) {
BKE_copy_animdata_id_action(&psys->part->id);
}
@@ -1704,21 +1715,19 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, Base *base
}
}
}
-
+
id = obn->data;
didit = 0;
-
+
switch (obn->type) {
case OB_MESH:
if (dupflag & USER_DUP_MESH) {
ID_NEW_US2(obn->data)
else {
obn->data = BKE_mesh_copy(obn->data);
-
if (obn->fluidsimSettings) {
obn->fluidsimSettings->orgMesh = (Mesh *)obn->data;
}
-
didit = 1;
}
id->us--;
@@ -1774,11 +1783,10 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, Base *base
id->us--;
}
break;
-
case OB_ARMATURE:
obn->recalc |= OB_RECALC_DATA;
- if (obn->pose) obn->pose->flag |= POSE_RECALC;
-
+ if (obn->pose)
+ obn->pose->flag |= POSE_RECALC;
if (dupflag & USER_DUP_ARM) {
ID_NEW_US2(obn->data)
else {
@@ -1788,9 +1796,7 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, Base *base
}
id->us--;
}
-
break;
-
case OB_LATTICE:
if (dupflag != 0) {
ID_NEW_US2(obn->data)
@@ -1821,13 +1827,12 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, Base *base
id->us--;
}
break;
-
}
/* check if obdata is copied */
if (didit) {
- Key *key = ob_get_key(obn);
-
+ Key *key = BKE_key_from_object(obn);
+
if (dupflag & USER_DUP_ACT) {
bActuator *act;
@@ -1846,7 +1851,7 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, Base *base
}
}
}
-
+
if (dupflag & USER_DUP_MAT) {
matarar = give_matarar(obn);
if (matarar) {
@@ -1854,8 +1859,8 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, Base *base
id = (ID *)(*matarar)[a];
if (id) {
ID_NEW_US((*matarar)[a])
- else (*matarar)[a] = BKE_material_copy((*matarar)[a]);
-
+ else
+ (*matarar)[a] = BKE_material_copy((*matarar)[a]);
id->us--;
}
}
@@ -1906,14 +1911,14 @@ static int duplicate_exec(bContext *C, wmOperator *op)
Scene *scene = CTX_data_scene(C);
int linked = RNA_boolean_get(op->ptr, "linked");
int dupflag = (linked) ? 0 : U.dupflag;
-
+
clear_id_newpoins();
clear_sca_new_poins(); /* sensor/contr/act */
-
+
CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
{
Base *basen = object_add_duplicate_internal(bmain, scene, base, dupflag);
-
+
/* note that this is safe to do with this context iterator,
* the list is made in advance */
ED_base_object_select(base, BA_DESELECT);
@@ -1945,19 +1950,19 @@ static int duplicate_exec(bContext *C, wmOperator *op)
void OBJECT_OT_duplicate(wmOperatorType *ot)
{
PropertyRNA *prop;
-
+
/* identifiers */
ot->name = "Duplicate Objects";
ot->description = "Duplicate selected objects";
ot->idname = "OBJECT_OT_duplicate";
-
+
/* api callbacks */
ot->exec = duplicate_exec;
ot->poll = ED_operator_objectmode;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* to give to transform */
RNA_def_boolean(ot->srna, "linked", 0, "Linked", "Duplicate object but not object data, linking to the original data");
prop = RNA_def_enum(ot->srna, "mode", transform_mode_types, TFM_TRANSLATION, "Mode", "");
@@ -1966,7 +1971,6 @@ void OBJECT_OT_duplicate(wmOperatorType *ot)
/* **************** add named object, for dragdrop ************* */
-
static int add_named_exec(bContext *C, wmOperator *op)
{
Main *bmain = CTX_data_main(C);
@@ -2021,45 +2025,43 @@ void OBJECT_OT_add_named(wmOperatorType *ot)
ot->name = "Add Named Object";
ot->description = "Add named object";
ot->idname = "OBJECT_OT_add_named";
-
+
/* api callbacks */
ot->exec = add_named_exec;
ot->poll = ED_operator_objectmode;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
RNA_def_boolean(ot->srna, "linked", 0, "Linked", "Duplicate object but not object data, linking to the original data");
RNA_def_string(ot->srna, "name", "Cube", MAX_ID_NAME - 2, "Name", "Object name to add");
}
-
-
/**************************** Join *************************/
+
static int join_poll(bContext *C)
{
Object *ob = CTX_data_active_object(C);
-
+
if (!ob || ob->id.lib) return 0;
-
+
if (ELEM4(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_ARMATURE))
return ED_operator_screenactive(C);
else
return 0;
}
-
static int join_exec(bContext *C, wmOperator *op)
{
Scene *scene = CTX_data_scene(C);
Object *ob = CTX_data_active_object(C);
if (scene->obedit) {
- BKE_report(op->reports, RPT_ERROR, "This data does not support joining in editmode");
+ BKE_report(op->reports, RPT_ERROR, "This data does not support joining in edit mode");
return OPERATOR_CANCELLED;
}
else if (BKE_object_obdata_is_libdata(ob)) {
- BKE_report(op->reports, RPT_ERROR, "Can't edit external libdata");
+ BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
return OPERATOR_CANCELLED;
}
@@ -2069,7 +2071,7 @@ static int join_exec(bContext *C, wmOperator *op)
return join_curve_exec(C, op);
else if (ob->type == OB_ARMATURE)
return join_armature_exec(C, op);
-
+
return OPERATOR_CANCELLED;
}
@@ -2079,22 +2081,23 @@ void OBJECT_OT_join(wmOperatorType *ot)
ot->name = "Join";
ot->description = "Join selected objects into active object";
ot->idname = "OBJECT_OT_join";
-
+
/* api callbacks */
ot->exec = join_exec;
ot->poll = join_poll;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/**************************** Join as Shape Key*************************/
+
static int join_shapes_poll(bContext *C)
{
Object *ob = CTX_data_active_object(C);
-
+
if (!ob || ob->id.lib) return 0;
-
+
/* only meshes supported at the moment */
if (ob->type == OB_MESH)
return ED_operator_screenactive(C);
@@ -2106,19 +2109,19 @@ static int join_shapes_exec(bContext *C, wmOperator *op)
{
Scene *scene = CTX_data_scene(C);
Object *ob = CTX_data_active_object(C);
-
+
if (scene->obedit) {
- BKE_report(op->reports, RPT_ERROR, "This data does not support joining in editmode");
+ BKE_report(op->reports, RPT_ERROR, "This data does not support joining in edit mode");
return OPERATOR_CANCELLED;
}
else if (BKE_object_obdata_is_libdata(ob)) {
- BKE_report(op->reports, RPT_ERROR, "Can't edit external libdata");
+ BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
return OPERATOR_CANCELLED;
}
-
+
if (ob->type == OB_MESH)
return join_mesh_shapes_exec(C, op);
-
+
return OPERATOR_CANCELLED;
}
@@ -2128,11 +2131,11 @@ void OBJECT_OT_join_shapes(wmOperatorType *ot)
ot->name = "Join as Shapes";
ot->description = "Merge selected objects to shapes of active object";
ot->idname = "OBJECT_OT_join_shapes";
-
+
/* api callbacks */
ot->exec = join_shapes_exec;
ot->poll = join_shapes_poll;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
diff --git a/source/blender/editors/object/object_bake.c b/source/blender/editors/object/object_bake.c
index f03cb312e3e..ee3c66b6eac 100644
--- a/source/blender/editors/object/object_bake.c
+++ b/source/blender/editors/object/object_bake.c
@@ -150,11 +150,13 @@ typedef struct {
float height_min, height_max;
Image *ima;
DerivedMesh *ssdm;
- const int *origindex;
+ const int *orig_index_mf_to_mpoly;
+ const int *orig_index_mp_to_orig;
} MHeightBakeData;
typedef struct {
- const int *origindex;
+ const int *orig_index_mf_to_mpoly;
+ const int *orig_index_mp_to_orig;
} MNormalBakeData;
static void multiresbake_get_normal(const MResolvePixelData *data, float norm[], const int face_num, const int vert_index)
@@ -508,7 +510,9 @@ static void interp_bilinear_grid(CCGKey *key, CCGElem *grid, float crn_x, float
interp_bilinear_quad_data(data, u, v, res);
}
-static void get_ccgdm_data(DerivedMesh *lodm, DerivedMesh *hidm, const int *origindex, const int lvl, const int face_index, const float u, const float v, float co[3], float n[3])
+static void get_ccgdm_data(DerivedMesh *lodm, DerivedMesh *hidm,
+ const int *index_mf_to_mpoly, const int *index_mp_to_orig,
+ const int lvl, const int face_index, const float u, const float v, float co[3], float n[3])
{
MFace mface;
CCGElem **grid_data;
@@ -532,7 +536,7 @@ static void get_ccgdm_data(DerivedMesh *lodm, DerivedMesh *hidm, const int *orig
}
else {
int side = (1 << (lvl - 1)) + 1;
- int grid_index = origindex[face_index];
+ int grid_index = DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, face_index);
int loc_offs = face_index % (1 << (2 * lvl));
int cell_index = loc_offs % ((side - 1) * (side - 1));
int cell_side = (grid_size - 1) / (side - 1);
@@ -628,7 +632,8 @@ static void *init_heights_data(MultiresBakeRender *bkr, Image *ima)
}
}
- height_data->origindex = lodm->getTessFaceDataArray(lodm, CD_ORIGINDEX);
+ height_data->orig_index_mf_to_mpoly = lodm->getTessFaceDataArray(lodm, CD_ORIGINDEX);
+ height_data->orig_index_mp_to_orig = lodm->getPolyDataArray(lodm, CD_ORIGINDEX);
return (void *)height_data;
}
@@ -640,7 +645,8 @@ static void *init_normal_data(MultiresBakeRender *bkr, Image *UNUSED(ima))
normal_data = MEM_callocN(sizeof(MNormalBakeData), "MultiresBake normalData");
- normal_data->origindex = lodm->getTessFaceDataArray(lodm, CD_ORIGINDEX);
+ normal_data->orig_index_mf_to_mpoly = lodm->getTessFaceDataArray(lodm, CD_ORIGINDEX);
+ normal_data->orig_index_mp_to_orig = lodm->getPolyDataArray(lodm, CD_ORIGINDEX);
return (void *)normal_data;
}
@@ -735,10 +741,14 @@ static void apply_heights_callback(DerivedMesh *lores_dm, DerivedMesh *hires_dm,
CLAMP(uv[0], 0.0f, 1.0f);
CLAMP(uv[1], 0.0f, 1.0f);
- get_ccgdm_data(lores_dm, hires_dm, height_data->origindex, lvl, face_index, uv[0], uv[1], p1, 0);
+ get_ccgdm_data(lores_dm, hires_dm,
+ height_data->orig_index_mf_to_mpoly, height_data->orig_index_mf_to_mpoly,
+ lvl, face_index, uv[0], uv[1], p1, 0);
if (height_data->ssdm) {
- get_ccgdm_data(lores_dm, height_data->ssdm, height_data->origindex, 0, face_index, uv[0], uv[1], p0, n);
+ get_ccgdm_data(lores_dm, height_data->ssdm,
+ height_data->orig_index_mf_to_mpoly, height_data->orig_index_mf_to_mpoly,
+ 0, face_index, uv[0], uv[1], p0, n);
}
else {
lores_dm->getTessFace(lores_dm, face_index, &mface);
@@ -808,7 +818,9 @@ static void apply_tangmat_callback(DerivedMesh *lores_dm, DerivedMesh *hires_dm,
CLAMP(uv[0], 0.0f, 1.0f);
CLAMP(uv[1], 0.0f, 1.0f);
- get_ccgdm_data(lores_dm, hires_dm, normal_data->origindex, lvl, face_index, uv[0], uv[1], NULL, n);
+ get_ccgdm_data(lores_dm, hires_dm,
+ normal_data->orig_index_mf_to_mpoly, normal_data->orig_index_mp_to_orig,
+ lvl, face_index, uv[0], uv[1], NULL, n);
mul_v3_m3v3(vec, tangmat, n);
normalize_v3(vec);
@@ -900,7 +912,7 @@ static void finish_images(MultiresBakeRender *bkr)
RE_bake_ibuf_filter(ibuf, (char *)ibuf->userdata, bkr->bake_filter);
- ibuf->userflags |= IB_BITMAPDIRTY | IB_DISPLAY_BUFFER_INVALID;;
+ ibuf->userflags |= IB_BITMAPDIRTY | IB_DISPLAY_BUFFER_INVALID;
if (ibuf->rect_float)
ibuf->userflags |= IB_RECT_INVALID;
@@ -937,7 +949,7 @@ static int multiresbake_check(bContext *C, wmOperator *op)
ob = base->object;
if (ob->type != OB_MESH) {
- BKE_report(op->reports, RPT_ERROR, "Basking of multires data only works with active object which is a mesh");
+ BKE_report(op->reports, RPT_ERROR, "Baking of multires data only works with an active mesh object");
ok = 0;
break;
@@ -966,6 +978,12 @@ static int multiresbake_check(bContext *C, wmOperator *op)
break;
}
+ if (mmd->lvl == 0) {
+ BKE_report(op->reports, RPT_ERROR, "Multires data baking is not supported for preview subdivision level 0");
+
+ break;
+ }
+
if (!me->mtpoly) {
BKE_report(op->reports, RPT_ERROR, "Mesh should be unwrapped before multires data baking");
@@ -985,7 +1003,7 @@ static int multiresbake_check(bContext *C, wmOperator *op)
ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
if (!ibuf) {
- BKE_report(op->reports, RPT_ERROR, "Baking should happend to image with image buffer");
+ BKE_report(op->reports, RPT_ERROR, "Baking should happen to image with image buffer");
ok = 0;
}
@@ -1030,8 +1048,7 @@ static DerivedMesh *multiresbake_create_loresdm(Scene *scene, Object *ob, int *l
tmp_mmd.lvl = *lvl;
tmp_mmd.sculptlvl = *lvl;
- dm = multires_make_derived_from_derived(cddm, &tmp_mmd, ob,
- MULTIRES_USE_LOCAL_MMD);
+ dm = multires_make_derived_from_derived(cddm, &tmp_mmd, ob, 0);
cddm->release(cddm);
}
@@ -1051,8 +1068,7 @@ static DerivedMesh *multiresbake_create_hiresdm(Scene *scene, Object *ob, int *l
tmp_mmd.lvl = mmd->totlvl;
tmp_mmd.sculptlvl = mmd->totlvl;
- dm = multires_make_derived_from_derived(cddm, &tmp_mmd, ob,
- MULTIRES_USE_LOCAL_MMD);
+ dm = multires_make_derived_from_derived(cddm, &tmp_mmd, ob, 0);
cddm->release(cddm);
return dm;
@@ -1329,11 +1345,12 @@ static int test_bake_internal(bContext *C, ReportList *reports)
static void init_bake_internal(BakeRender *bkr, bContext *C)
{
Scene *scene = CTX_data_scene(C);
+ bScreen *sc = CTX_wm_screen(C);
/* get editmode results */
ED_object_exit_editmode(C, 0); /* 0 = does not exit editmode */
- bkr->sa = BKE_screen_find_big_area(CTX_wm_screen(C), SPACE_IMAGE, 10); /* can be NULL */
+ bkr->sa = sc ? BKE_screen_find_big_area(sc, SPACE_IMAGE, 10) : NULL; /* can be NULL */
bkr->main = CTX_data_main(C);
bkr->scene = scene;
bkr->actob = (scene->r.bake_flag & R_BAKE_TO_ACTIVE) ? OBACT : NULL;
@@ -1365,20 +1382,23 @@ static void finish_bake_internal(BakeRender *bkr)
if (bkr->prev_r_raytrace == 0)
bkr->scene->r.mode &= ~R_RAYTRACE;
-
/* force OpenGL reload and mipmap recalc */
for (ima = G.main->image.first; ima; ima = ima->id.next) {
ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
- if (bkr->result == BAKE_RESULT_OK) {
- if (ima->ok == IMA_OK_LOADED) {
- if (ibuf) {
- if (ibuf->userflags & IB_BITMAPDIRTY) {
- ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
- GPU_free_image(ima);
- imb_freemipmapImBuf(ibuf);
- }
+ /* some of the images could have been changed during bake,
+ * so recreate mipmaps regardless bake result status
+ */
+ if (ima->ok == IMA_OK_LOADED) {
+ if (ibuf) {
+ if (ibuf->userflags & IB_BITMAPDIRTY) {
+ GPU_free_image(ima);
+ imb_freemipmapImBuf(ibuf);
}
+
+ /* invalidate display buffers for changed images */
+ if (ibuf->userflags & IB_BITMAPDIRTY)
+ ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
}
}
diff --git a/source/blender/editors/object/object_constraint.c b/source/blender/editors/object/object_constraint.c
index 1ef7c12b409..f78e1203bc4 100644
--- a/source/blender/editors/object/object_constraint.c
+++ b/source/blender/editors/object/object_constraint.c
@@ -40,6 +40,7 @@
#include "BLI_dynstr.h"
#include "BLI_utildefines.h"
+#include "DNA_anim_types.h"
#include "DNA_constraint_types.h"
#include "DNA_curve_types.h"
#include "DNA_scene_types.h"
@@ -51,6 +52,7 @@
#include "BKE_constraint.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
+#include "BKE_fcurve.h"
#include "BKE_global.h"
#include "BKE_main.h"
#include "BKE_object.h"
@@ -71,6 +73,7 @@
#include "ED_object.h"
#include "ED_armature.h"
+#include "ED_keyframing.h"
#include "ED_screen.h"
#include "UI_interface.h"
@@ -491,9 +494,9 @@ static void test_constraints(Object *owner, bPoseChannel *pchan)
/* auto-set 'Path' setting on curve so this works */
cu->flag |= CU_PATH;
}
- }
+ }
}
- }
+ }
/* free any temporary targets */
if (cti->flush_constraint_targets)
@@ -590,7 +593,7 @@ static bConstraint *edit_constraint_property_get(wmOperator *op, Object *ob, int
if (owner == EDIT_CONSTRAINT_OWNER_OBJECT) {
list = &ob->constraints;
- }
+ }
else if (owner == EDIT_CONSTRAINT_OWNER_BONE) {
bPoseChannel *pchan = BKE_pose_channel_active(ob);
if (pchan)
@@ -655,12 +658,15 @@ void CONSTRAINT_OT_stretchto_reset(wmOperatorType *ot)
ot->idname = "CONSTRAINT_OT_stretchto_reset";
ot->description = "Reset original length of bone for Stretch To Constraint";
- ot->exec = stretchto_reset_exec;
+ /* callbacks */
ot->invoke = stretchto_reset_invoke;
+ ot->exec = stretchto_reset_exec;
ot->poll = edit_constraint_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
edit_constraint_properties(ot);
}
@@ -698,12 +704,15 @@ void CONSTRAINT_OT_limitdistance_reset(wmOperatorType *ot)
ot->idname = "CONSTRAINT_OT_limitdistance_reset";
ot->description = "Reset limiting distance for Limit Distance Constraint";
- ot->exec = limitdistance_reset_exec;
+ /* callbacks */
ot->invoke = limitdistance_reset_invoke;
+ ot->exec = limitdistance_reset_exec;
ot->poll = edit_constraint_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
edit_constraint_properties(ot);
}
@@ -798,7 +807,7 @@ static int childof_set_inverse_exec(bContext *C, wmOperator *op)
/* despite 3 layers of checks, we may still not be able to find a constraint */
if (data == NULL) {
printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
- BKE_report(op->reports, RPT_ERROR, "Couldn't find constraint data for Child-Of Set Inverse");
+ BKE_report(op->reports, RPT_ERROR, "Could not find constraint data for Child-Of Set Inverse");
return OPERATOR_CANCELLED;
}
@@ -824,12 +833,15 @@ void CONSTRAINT_OT_childof_set_inverse(wmOperatorType *ot)
ot->idname = "CONSTRAINT_OT_childof_set_inverse";
ot->description = "Set inverse correction for ChildOf constraint";
- ot->exec = childof_set_inverse_exec;
+ /* callbacks */
ot->invoke = childof_set_inverse_invoke;
+ ot->exec = childof_set_inverse_exec;
ot->poll = edit_constraint_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
edit_constraint_properties(ot);
}
@@ -841,7 +853,7 @@ static int childof_clear_inverse_exec(bContext *C, wmOperator *op)
bChildOfConstraint *data = (con) ? (bChildOfConstraint *)con->data : NULL;
if (data == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Childof constraint not found");
+ BKE_report(op->reports, RPT_ERROR, "Child Of constraint not found");
return OPERATOR_CANCELLED;
}
@@ -868,15 +880,142 @@ void CONSTRAINT_OT_childof_clear_inverse(wmOperatorType *ot)
ot->idname = "CONSTRAINT_OT_childof_clear_inverse";
ot->description = "Clear inverse correction for ChildOf constraint";
- ot->exec = childof_clear_inverse_exec;
+ /* callbacks */
ot->invoke = childof_clear_inverse_invoke;
+ ot->exec = childof_clear_inverse_exec;
ot->poll = edit_constraint_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
edit_constraint_properties(ot);
}
+/* --------------- Follow Path Constraint ------------------ */
+
+static int followpath_path_animate_exec(bContext *C, wmOperator *op)
+{
+ Object *ob = ED_object_active_context(C);
+ bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_FOLLOWPATH);
+ bFollowPathConstraint *data = (con) ? (bFollowPathConstraint *)con->data : NULL;
+
+ bAction *act = NULL;
+ FCurve *fcu = NULL;
+ int sfra = RNA_int_get(op->ptr, "frame_start");
+ int len = RNA_int_get(op->ptr, "length");
+ float standardRange = 1.0;
+
+ /* nearly impossible sanity check */
+ if (data == NULL) {
+ BKE_report(op->reports, RPT_ERROR, "Follow Path constraint not found");
+ return OPERATOR_CANCELLED;
+ }
+
+ /* add F-Curve as appropriate */
+ if (data->tar) {
+ Curve *cu = (Curve *)data->tar->data;
+
+ if ( ELEM(NULL, cu->adt, cu->adt->action) ||
+ (list_find_fcurve(&cu->adt->action->curves, "eval_time", 0) == NULL))
+ {
+ /* create F-Curve for path animation */
+ act = verify_adt_action(&cu->id, 1);
+ fcu = verify_fcurve(act, NULL, NULL, "eval_time", 0, 1);
+
+ /* standard vertical range - 1:1 = 100 frames */
+ standardRange = 100.0f;
+ }
+ else {
+ /* path anim exists already - abort for now as this may well be what was intended */
+ BKE_report(op->reports, RPT_WARNING, "Path is already animated");
+ return OPERATOR_CANCELLED;
+ }
+ }
+ else {
+ /* animate constraint's "fixed offset" */
+ PointerRNA ptr;
+ PropertyRNA *prop;
+ char *path;
+
+ /* get RNA pointer to constraint's "offset_factor" property - to build RNA path */
+ RNA_pointer_create(&ob->id, &RNA_FollowPathConstraint, con, &ptr);
+ prop = RNA_struct_find_property(&ptr, "offset_factor");
+
+ path = RNA_path_from_ID_to_property(&ptr, prop);
+
+ /* create F-Curve for constraint */
+ act = verify_adt_action(&ob->id, 1);
+ fcu = verify_fcurve(act, NULL, NULL, path, 0, 1);
+
+ /* standard vertical range - 0.0 to 1.0 */
+ standardRange = 1.0f;
+
+ /* enable "Use Fixed Position" so that animating this has effect */
+ data->followflag |= FOLLOWPATH_STATIC;
+
+ /* path needs to be freed */
+ if (path)
+ MEM_freeN(path);
+ }
+
+ /* setup dummy 'generator' modifier here to get 1-1 correspondence still working
+ * and define basic slope of this curve based on the properties
+ */
+ if (!fcu->bezt && !fcu->fpt && !fcu->modifiers.first) {
+ FModifier *fcm = add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR);
+ FMod_Generator *gen = fcm->data;
+
+ /* Assume that we have the following equation:
+ * y = Ax + B
+ * 1 0 <-- coefficients array indices
+ */
+ float A = standardRange / (float)(len);
+ float B = (float)(-sfra) * A;
+
+ gen->coefficients[1] = A;
+ gen->coefficients[0] = B;
+ }
+
+ /* updates... */
+ WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
+ return OPERATOR_FINISHED;
+}
+
+static int followpath_path_animate_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
+{
+ /* hook up invoke properties for figuring out which constraint we're dealing with */
+ if (edit_constraint_invoke_properties(C, op)) {
+ return followpath_path_animate_exec(C, op);
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+void CONSTRAINT_OT_followpath_path_animate(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Auto Animate Path";
+ ot->idname = "CONSTRAINT_OT_followpath_path_animate";
+ ot->description = "Add default animation for path used by constraint if it isn't animated already";
+
+ /* callbacks */
+ ot->invoke = followpath_path_animate_invoke;
+ ot->exec = followpath_path_animate_exec;
+ ot->poll = edit_constraint_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* props */
+ edit_constraint_properties(ot);
+ RNA_def_int(ot->srna, "frame_start", 1, MINAFRAME, MAXFRAME, "Start Frame",
+ "First frame of path animation", MINAFRAME, MAXFRAME);
+ RNA_def_int(ot->srna, "length", 100, 0, MAXFRAME, "Length",
+ "Number of frames that path animation should take", 0, MAXFRAME);
+}
+
/* ------------- Object Solver Constraint ------------------ */
static int objectsolver_set_inverse_exec(bContext *C, wmOperator *op)
@@ -889,7 +1028,7 @@ static int objectsolver_set_inverse_exec(bContext *C, wmOperator *op)
/* despite 3 layers of checks, we may still not be able to find a constraint */
if (data == NULL) {
printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
- BKE_report(op->reports, RPT_ERROR, "Couldn't find constraint data for Child-Of Set Inverse");
+ BKE_report(op->reports, RPT_ERROR, "Could not find constraint data for Child-Of Set Inverse");
return OPERATOR_CANCELLED;
}
@@ -914,13 +1053,16 @@ void CONSTRAINT_OT_objectsolver_set_inverse(wmOperatorType *ot)
ot->name = "Set Inverse";
ot->idname = "CONSTRAINT_OT_objectsolver_set_inverse";
ot->description = "Set inverse correction for ObjectSolver constraint";
-
- ot->exec = objectsolver_set_inverse_exec;
+
+ /* callbacks */
ot->invoke = objectsolver_set_inverse_invoke;
+ ot->exec = objectsolver_set_inverse_exec;
ot->poll = edit_constraint_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
edit_constraint_properties(ot);
}
@@ -931,7 +1073,7 @@ static int objectsolver_clear_inverse_exec(bContext *C, wmOperator *op)
bObjectSolverConstraint *data = (con) ? (bObjectSolverConstraint *)con->data : NULL;
if (data == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Childof constraint not found");
+ BKE_report(op->reports, RPT_ERROR, "Child Of constraint not found");
return OPERATOR_CANCELLED;
}
@@ -957,13 +1099,16 @@ void CONSTRAINT_OT_objectsolver_clear_inverse(wmOperatorType *ot)
ot->name = "Clear Inverse";
ot->idname = "CONSTRAINT_OT_objectsolver_clear_inverse";
ot->description = "Clear inverse correction for ObjectSolver constraint";
-
- ot->exec = objectsolver_clear_inverse_exec;
+
+ /* callbacks */
ot->invoke = objectsolver_clear_inverse_invoke;
+ ot->exec = objectsolver_clear_inverse_exec;
ot->poll = edit_constraint_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
edit_constraint_properties(ot);
}
@@ -983,13 +1128,14 @@ void ED_object_constraint_set_active(Object *ob, bConstraint *con)
void ED_object_constraint_update(Object *ob)
{
-
if (ob->pose) BKE_pose_update_constraint_flags(ob->pose);
object_test_constraints(ob);
- if (ob->type == OB_ARMATURE) DAG_id_tag_update(&ob->id, OB_RECALC_DATA | OB_RECALC_OB);
- else DAG_id_tag_update(&ob->id, OB_RECALC_OB);
+ if (ob->type == OB_ARMATURE)
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA | OB_RECALC_OB);
+ else
+ DAG_id_tag_update(&ob->id, OB_RECALC_OB);
}
void ED_object_constraint_dependency_update(Main *bmain, Scene *scene, Object *ob)
@@ -1006,6 +1152,7 @@ static int constraint_poll(bContext *C)
return (ptr.id.data && ptr.data);
}
+
static int constraint_delete_exec(bContext *C, wmOperator *UNUSED(op))
{
PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
@@ -1020,12 +1167,12 @@ static int constraint_delete_exec(bContext *C, wmOperator *UNUSED(op))
constraints_set_active(lb, NULL);
ED_object_constraint_update(ob); /* needed to set the flags on posebones correctly */
-
+
/* ITASC needs to be rebuilt once a constraint is removed [#26920] */
if (is_ik) {
BIK_clear_data(ob->pose);
}
-
+
/* notifiers */
WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
@@ -1052,6 +1199,7 @@ void CONSTRAINT_OT_delete(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+
static int constraint_move_down_exec(bContext *C, wmOperator *op)
{
Object *ob = ED_object_active_context(C);
@@ -1081,7 +1229,6 @@ static int constraint_move_down_invoke(bContext *C, wmOperator *op, wmEvent *UNU
return OPERATOR_CANCELLED;
}
-
void CONSTRAINT_OT_move_down(wmOperatorType *ot)
{
/* identifiers */
@@ -1090,12 +1237,14 @@ void CONSTRAINT_OT_move_down(wmOperatorType *ot)
ot->description = "Move constraint down in constraint stack";
/* callbacks */
- ot->exec = constraint_move_down_exec;
ot->invoke = constraint_move_down_invoke;
+ ot->exec = constraint_move_down_exec;
ot->poll = edit_constraint_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
edit_constraint_properties(ot);
}
@@ -1479,15 +1628,15 @@ static int constraint_add_exec(bContext *C, wmOperator *op, Object *ob, ListBase
return OPERATOR_CANCELLED;
}
if ((type == CONSTRAINT_TYPE_RIGIDBODYJOINT) && (list != &ob->constraints)) {
- BKE_report(op->reports, RPT_ERROR, "Rigid Body Joint Constraint can only be added to Objects");
+ BKE_report(op->reports, RPT_ERROR, "Rigid Body Joint constraint can only be added to objects");
return OPERATOR_CANCELLED;
}
if ((type == CONSTRAINT_TYPE_KINEMATIC) && ((!pchan) || (list != &pchan->constraints))) {
- BKE_report(op->reports, RPT_ERROR, "IK Constraint can only be added to Bones");
+ BKE_report(op->reports, RPT_ERROR, "IK constraint can only be added to bones");
return OPERATOR_CANCELLED;
}
if ((type == CONSTRAINT_TYPE_SPLINEIK) && ((!pchan) || (list != &pchan->constraints))) {
- BKE_report(op->reports, RPT_ERROR, "Spline IK Constraint can only be added to Bones");
+ BKE_report(op->reports, RPT_ERROR, "Spline IK constraint can only be added to bones");
return OPERATOR_CANCELLED;
}
@@ -1707,7 +1856,7 @@ static int pose_ik_add_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(evt))
/* must have active bone */
if (ELEM(NULL, ob, pchan)) {
- BKE_report(op->reports, RPT_ERROR, "Must have active bone to add IK Constraint to");
+ BKE_report(op->reports, RPT_ERROR, "Must have an active bone to add IK constraint to");
return OPERATOR_CANCELLED;
}
@@ -1716,7 +1865,7 @@ static int pose_ik_add_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(evt))
if (con->type == CONSTRAINT_TYPE_KINEMATIC) break;
}
if (con) {
- BKE_report(op->reports, RPT_ERROR, "Bone already has IK Constraint");
+ BKE_report(op->reports, RPT_ERROR, "Bone already has an IK constraint");
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/object/object_edit.c b/source/blender/editors/object/object_edit.c
index aa885320b37..c0c2195592b 100644
--- a/source/blender/editors/object/object_edit.c
+++ b/source/blender/editors/object/object_edit.c
@@ -201,7 +201,7 @@ static int object_hide_view_set_exec(bContext *C, wmOperator *op)
ED_base_object_activate(C, NULL);
}
}
- }
+ }
}
CTX_DATA_END;
@@ -649,11 +649,11 @@ static void copymenu_properties(Scene *scene, View3D *v3d, Object *ob)
for (base = FIRSTBASE; base; base = base->next) {
if ((base != BASACT) && (TESTBASELIB(v3d, base))) {
if (nr == 1) { /* replace */
- copy_properties(&base->object->prop, &ob->prop);
+ BKE_bproperty_copy_list(&base->object->prop, &ob->prop);
}
else {
for (prop = ob->prop.first; prop; prop = prop->next) {
- set_ob_property(base->object, prop);
+ BKE_bproperty_object_set(base->object, prop);
}
}
}
@@ -665,7 +665,7 @@ static void copymenu_properties(Scene *scene, View3D *v3d, Object *ob)
if (prop) {
for (base = FIRSTBASE; base; base = base->next) {
if ((base != BASACT) && (TESTBASELIB(v3d, base))) {
- set_ob_property(base->object, prop);
+ BKE_bproperty_object_set(base->object, prop);
}
}
}
@@ -684,7 +684,7 @@ static void copymenu_logicbricks(Scene *scene, View3D *v3d, Object *ob)
if (TESTBASELIB(v3d, base)) {
/* first: free all logic */
- free_sensors(&base->object->sensors);
+ free_sensors(&base->object->sensors);
unlink_controllers(&base->object->controllers);
free_controllers(&base->object->controllers);
unlink_actuators(&base->object->actuators);
@@ -885,7 +885,7 @@ static void copy_attr(Main *bmain, Scene *scene, View3D *v3d, short event)
id_us_plus((ID *)cu1->vfonti);
if (cu1->vfontbi) cu1->vfontbi->id.us--;
cu1->vfontbi = cu->vfontbi;
- id_us_plus((ID *)cu1->vfontbi);
+ id_us_plus((ID *)cu1->vfontbi);
BKE_vfont_to_curve(bmain, scene, base->object, 0); /* needed? */
@@ -957,7 +957,7 @@ static void copy_attr(Main *bmain, Scene *scene, View3D *v3d, short event)
base->object->softflag = ob->softflag;
if (base->object->soft) sbFree(base->object->soft);
- base->object->soft = copy_softbody(ob->soft);
+ base->object->soft = copy_softbody(ob->soft, FALSE);
if (!modifiers_findByType(base->object, eModifierType_Softbody)) {
BLI_addhead(&base->object->modifiers, modifier_new(eModifierType_Softbody));
@@ -988,7 +988,7 @@ static void copy_attr(Main *bmain, Scene *scene, View3D *v3d, short event)
cu1->flag |= CU_UV_ORCO;
else
cu1->flag &= ~CU_UV_ORCO;
- }
+ }
}
else if (event == 29) { /* protected bits */
base->object->protectflag = ob->protectflag;
@@ -1017,9 +1017,9 @@ static void UNUSED_FUNCTION(copy_attr_menu) (Main * bmain, Scene * scene, View3D
if (!(ob = OBACT)) return;
- if (scene->obedit) { // XXX get from context
-// if (ob->type == OB_MESH)
-// XXX mesh_copy_menu();
+ if (scene->obedit) { /* XXX get from context */
+/* if (ob->type == OB_MESH) */
+/* XXX mesh_copy_menu(); */
return;
}
@@ -1030,34 +1030,34 @@ static void UNUSED_FUNCTION(copy_attr_menu) (Main * bmain, Scene * scene, View3D
*/
strcpy(str,
- "Copy Attributes %t|Location%x1|Rotation%x2|Size%x3|Draw Options%x4|"
- "Time Offset%x5|Dupli%x6|Object Color%x31|%l|Mass%x7|Damping%x8|All Physical Attributes%x11|Properties%x9|"
- "Logic Bricks%x10|Protected Transform%x29|%l");
+ "Copy Attributes %t|Location %x1|Rotation %x2|Size %x3|Draw Options %x4|"
+ "Time Offset %x5|Dupli %x6|Object Color %x31|%l|Mass %x7|Damping %x8|All Physical Attributes %x11|Properties %x9|"
+ "Logic Bricks %x10|Protected Transform %x29|%l");
- strcat(str, "|Object Constraints%x22");
- strcat(str, "|NLA Strips%x26");
+ strcat(str, "|Object Constraints %x22");
+ strcat(str, "|NLA Strips %x26");
-// XXX if (OB_TYPE_SUPPORT_MATERIAL(ob->type)) {
-// strcat(str, "|Texture Space%x17");
-// }
+/* XXX if (OB_TYPE_SUPPORT_MATERIAL(ob->type)) { */
+/* strcat(str, "|Texture Space %x17"); */
+/* } */
- if (ob->type == OB_FONT) strcat(str, "|Font Settings%x18|Bevel Settings%x19");
- if (ob->type == OB_CURVE) strcat(str, "|Bevel Settings%x19|UV Orco%x28");
+ if (ob->type == OB_FONT) strcat(str, "|Font Settings %x18|Bevel Settings %x19");
+ if (ob->type == OB_CURVE) strcat(str, "|Bevel Settings %x19|UV Orco %x28");
if ((ob->type == OB_FONT) || (ob->type == OB_CURVE)) {
- strcat(str, "|Curve Resolution%x25");
+ strcat(str, "|Curve Resolution %x25");
}
if (ob->type == OB_MESH) {
- strcat(str, "|Subsurf Settings%x21|AutoSmooth%x27");
+ strcat(str, "|Subsurf Settings %x21|AutoSmooth %x27");
}
- if (ob->soft) strcat(str, "|Soft Body Settings%x23");
+ if (ob->soft) strcat(str, "|Soft Body Settings %x23");
- strcat(str, "|Pass Index%x30");
+ strcat(str, "|Pass Index %x30");
if (ob->type == OB_MESH || ob->type == OB_CURVE || ob->type == OB_LATTICE || ob->type == OB_SURF) {
- strcat(str, "|Modifiers ...%x24");
+ strcat(str, "|Modifiers ... %x24");
}
event = pupmenu(str);
@@ -1401,7 +1401,7 @@ static void UNUSED_FUNCTION(image_aspect) (Scene * scene, View3D * v3d)
else ob->size[1] = ob->size[0] * y / x;
done = TRUE;
- DAG_id_tag_update(&ob->id, OB_RECALC_OB);
+ DAG_id_tag_update(&ob->id, OB_RECALC_OB);
}
}
if (done) break;
@@ -1585,7 +1585,7 @@ static int game_property_new(bContext *C, wmOperator *op)
char name[MAX_NAME];
int type = RNA_enum_get(op->ptr, "type");
- prop = new_property(type);
+ prop = BKE_bproperty_new(type);
BLI_addtail(&ob->prop, prop);
RNA_string_get(op->ptr, "name", name);
@@ -1593,7 +1593,7 @@ static int game_property_new(bContext *C, wmOperator *op)
BLI_strncpy(prop->name, name, sizeof(prop->name));
}
- unique_property(NULL, prop, 0); // make_unique_prop_names(prop->name);
+ BKE_bproperty_unique(NULL, prop, 0); // make_unique_prop_names(prop->name);
WM_event_add_notifier(C, NC_LOGIC, NULL);
return OPERATOR_FINISHED;
@@ -1631,7 +1631,7 @@ static int game_property_remove(bContext *C, wmOperator *op)
if (prop) {
BLI_remlink(&ob->prop, prop);
- free_property(prop);
+ BKE_bproperty_free(prop);
WM_event_add_notifier(C, NC_LOGIC, NULL);
return OPERATOR_FINISHED;
@@ -1711,7 +1711,7 @@ static int game_property_copy_exec(bContext *C, wmOperator *op)
CTX_DATA_BEGIN(C, Object *, ob_iter, selected_editable_objects)
{
if (ob != ob_iter)
- set_ob_property(ob_iter, prop);
+ BKE_bproperty_object_set(ob_iter, prop);
} CTX_DATA_END;
}
}
@@ -1721,12 +1721,12 @@ static int game_property_copy_exec(bContext *C, wmOperator *op)
{
if (ob != ob_iter) {
if (type == COPY_PROPERTIES_REPLACE) {
- copy_properties(&ob_iter->prop, &ob->prop);
+ BKE_bproperty_copy_list(&ob_iter->prop, &ob->prop);
}
else {
/* merge - the default when calling with no argument */
for (prop = ob->prop.first; prop; prop = prop->next) {
- set_ob_property(ob_iter, prop);
+ BKE_bproperty_object_set(ob_iter, prop);
}
}
}
@@ -1763,7 +1763,7 @@ static int game_property_clear_exec(bContext *C, wmOperator *UNUSED(op))
{
CTX_DATA_BEGIN(C, Object *, ob_iter, selected_editable_objects)
{
- free_properties(&ob_iter->prop);
+ BKE_bproperty_free_list(&ob_iter->prop);
}
CTX_DATA_END;
@@ -1795,7 +1795,7 @@ static int logicbricks_copy_exec(bContext *C, wmOperator *UNUSED(op))
{
if (ob != ob_iter) {
/* first: free all logic */
- free_sensors(&ob_iter->sensors);
+ free_sensors(&ob_iter->sensors);
unlink_controllers(&ob_iter->controllers);
free_controllers(&ob_iter->controllers);
unlink_actuators(&ob_iter->actuators);
@@ -1864,7 +1864,7 @@ static int game_physics_copy_exec(bContext *C, wmOperator *UNUSED(op))
ob_iter->anisotropicFriction[0] = ob->anisotropicFriction[0];
ob_iter->anisotropicFriction[1] = ob->anisotropicFriction[1];
ob_iter->anisotropicFriction[2] = ob->anisotropicFriction[2];
- ob_iter->collision_boundtype = ob->collision_boundtype;
+ ob_iter->collision_boundtype = ob->collision_boundtype;
ob_iter->margin = ob->margin;
ob_iter->bsoft = copy_bulletsoftbody(ob->bsoft);
if (ob->restrictflag & OB_RESTRICT_RENDER)
diff --git a/source/blender/editors/object/object_group.c b/source/blender/editors/object/object_group.c
index cca37cf3a44..a3bf27a19d6 100644
--- a/source/blender/editors/object/object_group.c
+++ b/source/blender/editors/object/object_group.c
@@ -195,7 +195,7 @@ static int objects_remove_active_exec(bContext *C, wmOperator *op)
}
}
- if (!ok) BKE_report(op->reports, RPT_ERROR, "Active Object contains no groups");
+ if (!ok) BKE_report(op->reports, RPT_ERROR, "Active object contains no groups");
DAG_scene_sort(bmain, scene);
WM_event_add_notifier(C, NC_GROUP | NA_EDITED, NULL);
@@ -211,7 +211,7 @@ void GROUP_OT_objects_remove_active(wmOperatorType *ot)
ot->idname = "GROUP_OT_objects_remove_active";
/* api callbacks */
- ot->exec = objects_remove_active_exec;
+ ot->exec = objects_remove_active_exec;
ot->poll = ED_operator_objectmode;
/* flags */
@@ -333,7 +333,7 @@ void GROUP_OT_create(wmOperatorType *ot)
ot->idname = "GROUP_OT_create";
/* api callbacks */
- ot->exec = group_create_exec;
+ ot->exec = group_create_exec;
ot->poll = ED_operator_objectmode;
/* flags */
diff --git a/source/blender/editors/object/object_hook.c b/source/blender/editors/object/object_hook.c
index a6afe6b2d04..caeff1e82a7 100644
--- a/source/blender/editors/object/object_hook.c
+++ b/source/blender/editors/object/object_hook.c
@@ -442,7 +442,7 @@ static int add_hook_object(Main *bmain, Scene *scene, Object *obedit, Object *ob
ok = object_hook_index_array(scene, obedit, &tot, &indexar, name, cent);
if (!ok) {
- BKE_report(reports, RPT_ERROR, "Requires selected vertices or active Vertex Group");
+ BKE_report(reports, RPT_ERROR, "Requires selected vertices or active vertex group");
return FALSE;
}
@@ -515,12 +515,12 @@ static int object_add_hook_selob_exec(bContext *C, wmOperator *op)
CTX_DATA_END;
if (!obsel) {
- BKE_report(op->reports, RPT_ERROR, "Can't add hook with no other selected objects");
+ BKE_report(op->reports, RPT_ERROR, "Cannot add hook with no other selected objects");
return OPERATOR_CANCELLED;
}
if (use_bone && obsel->type != OB_ARMATURE) {
- BKE_report(op->reports, RPT_ERROR, "Can't add hook bone for a non armature object");
+ BKE_report(op->reports, RPT_ERROR, "Cannot add hook bone for a non armature object");
return OPERATOR_CANCELLED;
}
@@ -590,7 +590,7 @@ static int object_hook_remove_exec(bContext *C, wmOperator *op)
hmd = (HookModifierData *)BLI_findlink(&ob->modifiers, num);
if (!hmd) {
- BKE_report(op->reports, RPT_ERROR, "Couldn't find hook modifier");
+ BKE_report(op->reports, RPT_ERROR, "Could not find hook modifier");
return OPERATOR_CANCELLED;
}
@@ -667,13 +667,13 @@ static int object_hook_reset_exec(bContext *C, wmOperator *op)
if (ptr.data) { /* if modifier context is available, use that */
ob = ptr.id.data;
hmd = ptr.data;
- }
+ }
else { /* use the provided property */
ob = CTX_data_edit_object(C);
hmd = (HookModifierData *)BLI_findlink(&ob->modifiers, num);
}
if (!ob || !hmd) {
- BKE_report(op->reports, RPT_ERROR, "Couldn't find hook modifier");
+ BKE_report(op->reports, RPT_ERROR, "Could not find hook modifier");
return OPERATOR_CANCELLED;
}
@@ -735,13 +735,13 @@ static int object_hook_recenter_exec(bContext *C, wmOperator *op)
if (ptr.data) { /* if modifier context is available, use that */
ob = ptr.id.data;
hmd = ptr.data;
- }
+ }
else { /* use the provided property */
ob = CTX_data_edit_object(C);
hmd = (HookModifierData *)BLI_findlink(&ob->modifiers, num);
}
if (!ob || !hmd) {
- BKE_report(op->reports, RPT_ERROR, "Couldn't find hook modifier");
+ BKE_report(op->reports, RPT_ERROR, "Could not find hook modifier");
return OPERATOR_CANCELLED;
}
@@ -793,13 +793,13 @@ static int object_hook_assign_exec(bContext *C, wmOperator *op)
if (ptr.data) { /* if modifier context is available, use that */
ob = ptr.id.data;
hmd = ptr.data;
- }
+ }
else { /* use the provided property */
ob = CTX_data_edit_object(C);
hmd = (HookModifierData *)BLI_findlink(&ob->modifiers, num);
}
if (!ob || !hmd) {
- BKE_report(op->reports, RPT_ERROR, "Couldn't find hook modifier");
+ BKE_report(op->reports, RPT_ERROR, "Could not find hook modifier");
return OPERATOR_CANCELLED;
}
@@ -855,13 +855,13 @@ static int object_hook_select_exec(bContext *C, wmOperator *op)
if (ptr.data) { /* if modifier context is available, use that */
ob = ptr.id.data;
hmd = ptr.data;
- }
+ }
else { /* use the provided property */
ob = CTX_data_edit_object(C);
hmd = (HookModifierData *)BLI_findlink(&ob->modifiers, num);
}
if (!ob || !hmd) {
- BKE_report(op->reports, RPT_ERROR, "Couldn't find hook modifier");
+ BKE_report(op->reports, RPT_ERROR, "Could not find hook modifier");
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/object/object_intern.h b/source/blender/editors/object/object_intern.h
index b62ff676066..0be9c92897e 100644
--- a/source/blender/editors/object/object_intern.h
+++ b/source/blender/editors/object/object_intern.h
@@ -112,6 +112,7 @@ void OBJECT_OT_add_named(struct wmOperatorType *ot);
void OBJECT_OT_metaball_add(struct wmOperatorType *ot);
void OBJECT_OT_text_add(struct wmOperatorType *ot);
void OBJECT_OT_armature_add(struct wmOperatorType *ot);
+void OBJECT_OT_empty_add(struct wmOperatorType *ot);
void OBJECT_OT_lamp_add(struct wmOperatorType *ot);
void OBJECT_OT_effector_add(struct wmOperatorType *ot);
void OBJECT_OT_camera_add(struct wmOperatorType *ot);
@@ -137,6 +138,7 @@ void OBJECT_OT_hook_recenter(struct wmOperatorType *ot);
/* object_lattice.c */
void LATTICE_OT_select_all(struct wmOperatorType *ot);
void LATTICE_OT_make_regular(struct wmOperatorType *ot);
+void LATTICE_OT_flip(struct wmOperatorType *ot);
/* object_group.c */
void GROUP_OT_create(struct wmOperatorType *ot);
@@ -193,6 +195,7 @@ void CONSTRAINT_OT_childof_set_inverse(struct wmOperatorType *ot);
void CONSTRAINT_OT_childof_clear_inverse(struct wmOperatorType *ot);
void CONSTRAINT_OT_objectsolver_set_inverse(struct wmOperatorType *ot);
void CONSTRAINT_OT_objectsolver_clear_inverse(struct wmOperatorType *ot);
+void CONSTRAINT_OT_followpath_path_animate(struct wmOperatorType *ot);
/* object_vgroup.c */
void OBJECT_OT_vertex_group_add(struct wmOperatorType *ot);
@@ -202,6 +205,7 @@ void OBJECT_OT_vertex_group_remove_from(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_select(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_deselect(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_copy_to_linked(struct wmOperatorType *ot);
+void OBJECT_OT_vertex_group_transfer_weight(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_copy_to_selected(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_copy(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_normalize(struct wmOperatorType *ot);
@@ -212,6 +216,7 @@ void OBJECT_OT_vertex_group_fix(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_invert(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_blend(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_clean(struct wmOperatorType *ot);
+void OBJECT_OT_vertex_group_limit_total(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_mirror(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_set_active(struct wmOperatorType *ot);
void OBJECT_OT_vertex_group_sort(struct wmOperatorType *ot);
diff --git a/source/blender/editors/object/object_lattice.c b/source/blender/editors/object/object_lattice.c
index 89f9f5de311..4aa2e825954 100644
--- a/source/blender/editors/object/object_lattice.c
+++ b/source/blender/editors/object/object_lattice.c
@@ -46,6 +46,7 @@
#include "DNA_scene_types.h"
#include "RNA_access.h"
+#include "RNA_define.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
@@ -92,9 +93,9 @@ void make_editLatt(Object *obedit)
free_editLatt(obedit);
- actkey = ob_get_keyblock(obedit);
+ actkey = BKE_keyblock_from_object(obedit);
if (actkey)
- key_to_latt(actkey, lt);
+ BKE_key_convert_to_lattice(actkey, lt);
lt->editlatt = MEM_callocN(sizeof(EditLatt), "editlatt");
lt->editlatt->latt = MEM_dupallocN(lt);
@@ -167,7 +168,7 @@ void load_editLatt(Object *obedit)
}
}
-/************************** Operators *************************/
+/************************** Select All Operator *************************/
void ED_setflagsLatt(Object *obedit, int flag)
{
@@ -254,6 +255,8 @@ void LATTICE_OT_select_all(wmOperatorType *ot)
WM_operator_properties_select_all(ot);
}
+/************************** Make Regular Operator *************************/
+
static int make_regular_poll(bContext *C)
{
Object *ob;
@@ -300,18 +303,265 @@ void LATTICE_OT_make_regular(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+/************************** Flip Verts Operator *************************/
+
+/* flipping options */
+typedef enum eLattice_FlipAxes {
+ LATTICE_FLIP_U = 0,
+ LATTICE_FLIP_V = 1,
+ LATTICE_FLIP_W = 2
+} eLattice_FlipAxes;
+
+/* Helper macro for accessing item at index (u, v, w)
+ * < lt: (Lattice)
+ * < U: (int) u-axis coordinate of point
+ * < V: (int) v-axis coordinate of point
+ * < W: (int) w-axis coordinate of point
+ * < dimU: (int) number of points per row or number of columns (U-Axis)
+ * < dimV: (int) number of rows (V-Axis)
+ * > returns: (BPoint *) pointer to BPoint at this index
+ */
+#define LATTICE_PT(lt, U, V, W, dimU, dimV) \
+ ( (lt)->def + \
+ ((dimU) * (dimV)) * (W) + \
+ (dimU) * (V) + \
+ (U) \
+ )
+
+/* Flip midpoint value so that relative distances between midpoint and neighbour-pair is maintained
+ * ! Assumes that uvw <=> xyz (i.e. axis-aligned index-axes with coordinate-axes)
+ * - Helper for lattice_flip_exec()
+ */
+static void lattice_flip_point_value(Lattice *lt, int u, int v, int w, float mid, eLattice_FlipAxes axis)
+{
+ BPoint *bp;
+ float diff;
+
+ /* just the point in the middle (unpaired) */
+ bp = LATTICE_PT(lt, u, v, w, lt->pntsu, lt->pntsv);
+
+ /* flip over axis */
+ diff = mid - bp->vec[axis];
+ bp->vec[axis] = mid + diff;
+}
+
+/* Swap pairs of lattice points along a specified axis
+ * - Helper for lattice_flip_exec()
+ */
+static void lattice_swap_point_pairs(Lattice *lt, int u, int v, int w, float mid, eLattice_FlipAxes axis)
+{
+ BPoint *bpA, *bpB;
+
+ int numU = lt->pntsu;
+ int numV = lt->pntsv;
+ int numW = lt->pntsw;
+
+ int u0 = u, u1 = u;
+ int v0 = v, v1 = v;
+ int w0 = w, w1 = w;
+
+ /* get pair index by just overriding the relevant pair-value
+ * - "-1" else buffer overflow
+ */
+ switch (axis) {
+ case LATTICE_FLIP_U:
+ u1 = numU - u - 1;
+ break;
+ case LATTICE_FLIP_V:
+ v1 = numV - v - 1;
+ break;
+ case LATTICE_FLIP_W:
+ w1 = numW - w - 1;
+ break;
+ }
+
+ /* get points to operate on */
+ bpA = LATTICE_PT(lt, u0, v0, w0, numU, numV);
+ bpB = LATTICE_PT(lt, u1, v1, w1, numU, numV);
+
+ /* Swap all coordinates, so that flipped coordinates belong to
+ * the indices on the correct side of the lattice.
+ *
+ * Coords: (-2 4) |0| (3 4) --> (3 4) |0| (-2 4)
+ * Indices: (0,L) (1,R) --> (0,L) (1,R)
+ */
+ swap_v3_v3(bpA->vec, bpB->vec);
+
+ /* However, we need to mirror the coordinate values on the axis we're dealing with,
+ * otherwise we'd have effectively only rotated the points around. If we don't do this,
+ * we'd just be reimplementing the naive mirroring algorithm, which causes unwanted deforms
+ * such as flipped normals, etc.
+ *
+ * Coords: (3 4) |0| (-2 4) --\
+ * \-> (-3 4) |0| (2 4)
+ * Indices: (0,L) (1,R) --> (0,L) (1,R)
+ */
+ lattice_flip_point_value(lt, u0, v0, w0, mid, axis);
+ lattice_flip_point_value(lt, u1, v1, w1, mid, axis);
+}
+
+static int lattice_flip_exec(bContext *C, wmOperator *op)
+{
+ Object *obedit = CTX_data_edit_object(C);
+ Lattice *lt;
+
+ eLattice_FlipAxes axis = RNA_enum_get(op->ptr, "axis");
+ int numU, numV, numW;
+ int totP;
+
+ float mid = 0.0f;
+ short isOdd = 0;
+
+ /* get lattice - we need the "edit lattice" from the lattice... confusing... */
+ lt = (Lattice *)obedit->data;
+ lt = lt->editlatt->latt;
+
+ numU = lt->pntsu;
+ numV = lt->pntsv;
+ numW = lt->pntsw;
+ totP = numU * numV * numW;
+
+ /* First Pass: determine midpoint - used for flipping center verts if there are odd number of points on axis */
+ switch (axis) {
+ case LATTICE_FLIP_U:
+ isOdd = numU & 1;
+ break;
+ case LATTICE_FLIP_V:
+ isOdd = numV & 1;
+ break;
+ case LATTICE_FLIP_W:
+ isOdd = numW & 1;
+ break;
+
+ default:
+ printf("lattice_flip(): Unknown flipping axis (%d)\n", axis);
+ return OPERATOR_CANCELLED;
+ }
+
+ if (isOdd) {
+ BPoint *bp;
+ float avgInv = 1.0f / (float)totP;
+ int i;
+
+ /* midpoint calculation - assuming that u/v/w are axis-aligned */
+ for (i = 0, bp = lt->def; i < totP; i++, bp++) {
+ mid += bp->vec[axis] * avgInv;
+ }
+ }
+
+ /* Second Pass: swap pairs of vertices per axis, assuming they are all sorted */
+ switch (axis) {
+ case LATTICE_FLIP_U:
+ {
+ int u, v, w;
+
+ /* v/w strips - front to back, top to bottom */
+ for (w = 0; w < numW; w++) {
+ for (v = 0; v < numV; v++) {
+ /* swap coordinates of pairs of vertices on u */
+ for (u = 0; u < (numU / 2); u++) {
+ lattice_swap_point_pairs(lt, u, v, w, mid, axis);
+ }
+
+ /* flip u-coordinate of midpoint (i.e. unpaired point on u) */
+ if (isOdd) {
+ u = (numU / 2);
+ lattice_flip_point_value(lt, u, v, w, mid, axis);
+ }
+ }
+ }
+ }
+ break;
+ case LATTICE_FLIP_V:
+ {
+ int u, v, w;
+
+ /* u/w strips - front to back, left to right */
+ for (w = 0; w < numW; w++) {
+ for (u = 0; u < numU; u++) {
+ /* swap coordinates of pairs of vertices on v */
+ for (v = 0; v < (numV / 2); v++) {
+ lattice_swap_point_pairs(lt, u, v, w, mid, axis);
+ }
+
+ /* flip v-coordinate of midpoint (i.e. unpaired point on v) */
+ if (isOdd) {
+ v = (numV / 2);
+ lattice_flip_point_value(lt, u, v, w, mid, axis);
+ }
+ }
+ }
+ }
+ break;
+ case LATTICE_FLIP_W:
+ {
+ int u, v, w;
+
+ for (v = 0; v < numV; v++) {
+ for (u = 0; u < numU; u++) {
+ /* swap coordinates of pairs of vertices on w */
+ for (w = 0; w < (numW / 2); w++) {
+ lattice_swap_point_pairs(lt, u, v, w, mid, axis);
+ }
+
+ /* flip w-coordinate of midpoint (i.e. unpaired point on w) */
+ if (isOdd) {
+ w = (numW / 2);
+ lattice_flip_point_value(lt, u, v, w, mid, axis);
+ }
+ }
+ }
+ }
+ break;
+
+ default: /* shouldn't happen, but just in case */
+ break;
+ }
+
+ /* updates */
+ DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
+
+ return OPERATOR_FINISHED;
+}
+
+void LATTICE_OT_flip(wmOperatorType *ot)
+{
+ static EnumPropertyItem flip_items[] = {
+ {LATTICE_FLIP_U, "U", 0, "U (X) Axis", ""},
+ {LATTICE_FLIP_V, "V", 0, "V (Y) Axis", ""},
+ {LATTICE_FLIP_W, "W", 0, "W (Z) Axis", ""},
+ {0, NULL, 0, NULL, NULL}};
+
+ /* identifiers */
+ ot->name = "Flip (Distortion Free)";
+ ot->description = "Mirror all control points without inverting the lattice deform";
+ ot->idname = "LATTICE_OT_flip";
+
+ /* api callbacks */
+ ot->poll = ED_operator_editlattice;
+ ot->invoke = WM_menu_invoke;
+ ot->exec = lattice_flip_exec;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
+ ot->prop = RNA_def_enum(ot->srna, "axis", flip_items, LATTICE_FLIP_U, "Flip Axis", "Coordinates along this axis get flipped");
+}
+
/****************************** Mouse Selection *************************/
-static void findnearestLattvert__doClosest(void *userData, BPoint *bp, int x, int y)
+static void findnearestLattvert__doClosest(void *userData, BPoint *bp, const float screen_co[2])
{
- struct { BPoint *bp; short dist, select; int mval[2]; } *data = userData;
- float temp = abs(data->mval[0] - x) + abs(data->mval[1] - y);
+ struct { BPoint *bp; float dist; int select; float mval_fl[2]; } *data = userData;
+ float dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
- if ((bp->f1 & SELECT) == data->select)
- temp += 5;
+ if ((bp->f1 & SELECT) && data->select)
+ dist_test += 5.0f;
- if (temp < data->dist) {
- data->dist = temp;
+ if (dist_test < data->dist) {
+ data->dist = dist_test;
data->bp = bp;
}
@@ -319,18 +569,18 @@ static void findnearestLattvert__doClosest(void *userData, BPoint *bp, int x, in
static BPoint *findnearestLattvert(ViewContext *vc, const int mval[2], int sel)
{
- /* sel==1: selected gets a disadvantage */
+ /* (sel == 1): selected gets a disadvantage */
/* in nurb and bezt or bp the nearest is written */
/* return 0 1 2: handlepunt */
- struct { BPoint *bp; short dist, select; int mval[2]; } data = {NULL};
+ struct { BPoint *bp; float dist; int select; float mval_fl[2]; } data = {NULL};
data.dist = 100;
data.select = sel;
- data.mval[0] = mval[0];
- data.mval[1] = mval[1];
+ data.mval_fl[0] = mval[0];
+ data.mval_fl[1] = mval[1];
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
- lattice_foreachScreenVert(vc, findnearestLattvert__doClosest, &data);
+ lattice_foreachScreenVert(vc, findnearestLattvert__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
return data.bp;
}
@@ -341,7 +591,7 @@ int mouse_lattice(bContext *C, const int mval[2], int extend, int deselect, int
BPoint *bp = NULL;
view3d_set_viewcontext(C, &vc);
- bp = findnearestLattvert(&vc, mval, 1);
+ bp = findnearestLattvert(&vc, mval, TRUE);
if (bp) {
if (extend) {
diff --git a/source/blender/editors/object/object_modifier.c b/source/blender/editors/object/object_modifier.c
index 4858fdf1c35..3d2c4f95624 100644
--- a/source/blender/editors/object/object_modifier.c
+++ b/source/blender/editors/object/object_modifier.c
@@ -99,13 +99,13 @@ ModifierData *ED_object_modifier_add(ReportList *reports, Main *bmain, Scene *sc
/* only geometry objects should be able to get modifiers [#25291] */
if (!ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
- BKE_reportf(reports, RPT_WARNING, "Modifiers cannot be added to Object '%s'", ob->id.name + 2);
+ BKE_reportf(reports, RPT_WARNING, "Modifiers cannot be added to object '%s'", ob->id.name + 2);
return NULL;
}
if (mti->flags & eModifierTypeFlag_Single) {
if (modifiers_findByType(ob, type)) {
- BKE_report(reports, RPT_WARNING, "Only one modifier of this type allowed");
+ BKE_report(reports, RPT_WARNING, "Only one modifier of this type is allowed");
return NULL;
}
}
@@ -159,8 +159,10 @@ ModifierData *ED_object_modifier_add(ReportList *reports, Main *bmain, Scene *sc
/* set totlvl from existing MDISPS layer if object already had it */
multiresModifier_set_levels_from_disps((MultiresModifierData *)new_md, ob);
- /* ensure that grid paint mask layer is created */
- ED_sculpt_mask_layers_ensure(ob, (MultiresModifierData *)new_md);
+ if (ob->mode & OB_MODE_SCULPT) {
+ /* ensure that grid paint mask layer is created */
+ ED_sculpt_mask_layers_ensure(ob, (MultiresModifierData *)new_md);
+ }
}
else if (type == eModifierType_Skin) {
/* ensure skin-node customdata exists */
@@ -554,7 +556,7 @@ static int modifier_apply_shape(ReportList *reports, Scene *scene, Object *ob, M
KeyBlock *kb;
if (!modifier_sameTopology(md) || mti->type == eModifierTypeType_NonGeometrical) {
- BKE_report(reports, RPT_ERROR, "Only deforming modifiers can be applied to Shapes");
+ BKE_report(reports, RPT_ERROR, "Only deforming modifiers can be applied to shapes");
return 0;
}
@@ -565,15 +567,15 @@ static int modifier_apply_shape(ReportList *reports, Scene *scene, Object *ob, M
}
if (key == NULL) {
- key = me->key = add_key((ID *)me);
+ key = me->key = BKE_key_add((ID *)me);
key->type = KEY_RELATIVE;
/* if that was the first key block added, then it was the basis.
* Initialize it with the mesh, and add another for the modifier */
- kb = add_keyblock(key, NULL);
- mesh_to_key(me, kb);
+ kb = BKE_keyblock_add(key, NULL);
+ BKE_key_convert_from_mesh(me, kb);
}
- kb = add_keyblock(key, md->name);
+ kb = BKE_keyblock_add(key, md->name);
DM_to_meshkey(dm, me, kb);
dm->release(dm);
@@ -602,7 +604,7 @@ static int modifier_apply_obdata(ReportList *reports, Scene *scene, Object *ob,
MultiresModifierData *mmd = find_multires_modifier_before(scene, md);
if (me->key && mti->type != eModifierTypeType_NonGeometrical) {
- BKE_report(reports, RPT_ERROR, "Modifier cannot be applied to Mesh with Shape Keys");
+ BKE_report(reports, RPT_ERROR, "Modifier cannot be applied to a mesh with shape keys");
return 0;
}
@@ -679,7 +681,7 @@ int ED_object_modifier_apply(ReportList *reports, Scene *scene, Object *ob, Modi
int prev_mode;
if (scene->obedit) {
- BKE_report(reports, RPT_ERROR, "Modifiers cannot be applied in editmode");
+ BKE_report(reports, RPT_ERROR, "Modifiers cannot be applied in edit mode");
return 0;
}
else if (((ID *) ob->data)->us > 1) {
@@ -710,11 +712,6 @@ int ED_object_modifier_apply(ReportList *reports, Scene *scene, Object *ob, Modi
BLI_remlink(&ob->modifiers, md);
modifier_free(md);
- if (ob->type == OB_MESH) {
- /* ensure mesh paint mask layer remains after applying */
- ED_sculpt_mask_layers_ensure(ob, NULL);
- }
-
return 1;
}
@@ -1245,7 +1242,7 @@ static int multires_reshape_exec(bContext *C, wmOperator *op)
CTX_DATA_END;
if (!secondob) {
- BKE_report(op->reports, RPT_ERROR, "Second selected mesh object require to copy shape from");
+ BKE_report(op->reports, RPT_ERROR, "Second selected mesh object required to copy shape from");
return OPERATOR_CANCELLED;
}
@@ -1692,11 +1689,9 @@ static void skin_armature_bone_create(Object *skin_ob,
v = (e->v1 == parent_v ? e->v2 : e->v1);
- bone = MEM_callocN(sizeof(EditBone),
- "skin_armature_bone_create EditBone");
+ bone = ED_armature_edit_bone_add(arm, "Bone");
bone->parent = parent_bone;
- bone->layer = 1;
bone->flag |= BONE_CONNECTED;
copy_v3_v3(bone->head, mvert[parent_v].co);
@@ -1704,8 +1699,6 @@ static void skin_armature_bone_create(Object *skin_ob,
bone->rad_head = bone->rad_tail = 0.25;
BLI_snprintf(bone->name, sizeof(bone->name), "Bone.%.2d", endx);
- BLI_addtail(arm->edbo, bone);
-
/* add bDeformGroup */
if ((dg = ED_vgroup_add_name(skin_ob, bone->name))) {
ED_vgroup_vert_add(skin_ob, dg, parent_v, 1, WEIGHT_REPLACE);
@@ -1770,16 +1763,13 @@ static Object *modifier_skin_armature_create(struct Scene *scene,
* a fake root bone (have it going off in the Y direction
* (arbitrary) */
if (emap[v].count > 1) {
- bone = MEM_callocN(sizeof(EditBone), "EditBone");
+ bone = ED_armature_edit_bone_add(arm, "Bone");
copy_v3_v3(bone->head, me->mvert[v].co);
copy_v3_v3(bone->tail, me->mvert[v].co);
- bone->layer = 1;
bone->head[1] = 1.0f;
bone->rad_head = bone->rad_tail = 0.25;
-
- BLI_addtail(arm->edbo, bone);
}
if (emap[v].count >= 1) {
diff --git a/source/blender/editors/object/object_ops.c b/source/blender/editors/object/object_ops.c
index cec849efca7..d19277d20a2 100644
--- a/source/blender/editors/object/object_ops.c
+++ b/source/blender/editors/object/object_ops.c
@@ -113,6 +113,7 @@ void ED_operatortypes_object(void)
WM_operatortype_append(OBJECT_OT_delete);
WM_operatortype_append(OBJECT_OT_text_add);
WM_operatortype_append(OBJECT_OT_armature_add);
+ WM_operatortype_append(OBJECT_OT_empty_add);
WM_operatortype_append(OBJECT_OT_lamp_add);
WM_operatortype_append(OBJECT_OT_camera_add);
WM_operatortype_append(OBJECT_OT_speaker_add);
@@ -168,6 +169,7 @@ void ED_operatortypes_object(void)
WM_operatortype_append(CONSTRAINT_OT_childof_clear_inverse);
WM_operatortype_append(CONSTRAINT_OT_objectsolver_set_inverse);
WM_operatortype_append(CONSTRAINT_OT_objectsolver_clear_inverse);
+ WM_operatortype_append(CONSTRAINT_OT_followpath_path_animate);
WM_operatortype_append(OBJECT_OT_vertex_group_add);
WM_operatortype_append(OBJECT_OT_vertex_group_remove);
@@ -176,6 +178,7 @@ void ED_operatortypes_object(void)
WM_operatortype_append(OBJECT_OT_vertex_group_select);
WM_operatortype_append(OBJECT_OT_vertex_group_deselect);
WM_operatortype_append(OBJECT_OT_vertex_group_copy_to_linked);
+ WM_operatortype_append(OBJECT_OT_vertex_group_transfer_weight);
WM_operatortype_append(OBJECT_OT_vertex_group_copy_to_selected);
WM_operatortype_append(OBJECT_OT_vertex_group_copy);
WM_operatortype_append(OBJECT_OT_vertex_group_normalize);
@@ -186,6 +189,7 @@ void ED_operatortypes_object(void)
WM_operatortype_append(OBJECT_OT_vertex_group_levels);
WM_operatortype_append(OBJECT_OT_vertex_group_blend);
WM_operatortype_append(OBJECT_OT_vertex_group_clean);
+ WM_operatortype_append(OBJECT_OT_vertex_group_limit_total);
WM_operatortype_append(OBJECT_OT_vertex_group_mirror);
WM_operatortype_append(OBJECT_OT_vertex_group_set_active);
WM_operatortype_append(OBJECT_OT_vertex_group_sort);
@@ -207,6 +211,7 @@ void ED_operatortypes_object(void)
WM_operatortype_append(LATTICE_OT_select_all);
WM_operatortype_append(LATTICE_OT_make_regular);
+ WM_operatortype_append(LATTICE_OT_flip);
WM_operatortype_append(OBJECT_OT_group_add);
WM_operatortype_append(OBJECT_OT_group_link);
@@ -388,7 +393,7 @@ void ED_keymap_object(wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "OBJECT_OT_proxy_make", PKEY, KM_PRESS, KM_CTRL | KM_ALT, 0);
WM_keymap_add_item(keymap, "OBJECT_OT_make_local", LKEY, KM_PRESS, 0, 0);
- // XXX this should probably be in screen instead... here for testing purposes in the meantime... - Aligorith
+ /* XXX this should probably be in screen instead... here for testing purposes in the meantime... - Aligorith */
WM_keymap_verify_item(keymap, "ANIM_OT_keyframe_insert_menu", IKEY, KM_PRESS, 0, 0);
WM_keymap_verify_item(keymap, "ANIM_OT_keyframe_delete_v3d", IKEY, KM_PRESS, KM_ALT, 0);
WM_keymap_verify_item(keymap, "ANIM_OT_keying_set_active_set", IKEY, KM_PRESS, KM_CTRL | KM_SHIFT | KM_ALT, 0);
@@ -420,6 +425,8 @@ void ED_keymap_object(wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "OBJECT_OT_vertex_parent_set", PKEY, KM_PRESS, KM_CTRL, 0);
+ WM_keymap_add_item(keymap, "LATTICE_OT_flip", FKEY, KM_PRESS, KM_CTRL, 0);
+
/* menus */
WM_keymap_add_menu(keymap, "VIEW3D_MT_hook", HKEY, KM_PRESS, KM_CTRL, 0);
diff --git a/source/blender/editors/object/object_relations.c b/source/blender/editors/object/object_relations.c
index cafc7ce9300..58c6959d6f0 100644
--- a/source/blender/editors/object/object_relations.c
+++ b/source/blender/editors/object/object_relations.c
@@ -423,29 +423,92 @@ void OBJECT_OT_proxy_make(wmOperatorType *ot)
/********************** Clear Parent Operator ******************* */
+typedef enum eObClearParentTypes {
+ CLEAR_PARENT_ALL = 0,
+ CLEAR_PARENT_KEEP_TRANSFORM,
+ CLEAR_PARENT_INVERSE
+} eObClearParentTypes;
+
EnumPropertyItem prop_clear_parent_types[] = {
- {0, "CLEAR", 0, "Clear Parent", ""},
- {1, "CLEAR_KEEP_TRANSFORM", 0, "Clear and Keep Transformation", ""},
- {2, "CLEAR_INVERSE", 0, "Clear Parent Inverse", ""},
+ {CLEAR_PARENT_ALL, "CLEAR", 0, "Clear Parent", ""},
+ {CLEAR_PARENT_KEEP_TRANSFORM, "CLEAR_KEEP_TRANSFORM", 0, "Clear and Keep Transformation", ""},
+ {CLEAR_PARENT_INVERSE, "CLEAR_INVERSE", 0, "Clear Parent Inverse", ""},
{0, NULL, 0, NULL, NULL}
};
-void ED_object_parent_clear(Object *ob, int type)
+/* Helper for ED_object_parent_clear() - Remove deform-modifiers associated with parent */
+static void object_remove_parent_deform_modifiers(Object *ob, const Object *par)
{
+ if (ELEM3(par->type, OB_ARMATURE, OB_LATTICE, OB_CURVE)) {
+ ModifierData *md, *mdn;
+
+ /* assume that we only need to remove the first instance of matching deform modifier here */
+ for (md = ob->modifiers.first; md; md = mdn) {
+ short free = FALSE;
+
+ mdn = md->next;
+
+ /* need to match types (modifier + parent) and references */
+ if ((md->type == eModifierType_Armature) && (par->type == OB_ARMATURE)) {
+ ArmatureModifierData *amd = (ArmatureModifierData *)md;
+ if (amd->object == par) {
+ free = TRUE;
+ }
+ }
+ else if ((md->type == eModifierType_Lattice) && (par->type == OB_LATTICE)) {
+ LatticeModifierData *lmd = (LatticeModifierData *)md;
+ if (lmd->object == par) {
+ free = TRUE;
+ }
+ }
+ else if ((md->type == eModifierType_Curve) && (par->type == OB_CURVE)) {
+ CurveModifierData *cmd = (CurveModifierData *)md;
+ if (cmd->object == par) {
+ free = TRUE;
+ }
+ }
+
+ /* free modifier if match */
+ if (free) {
+ BLI_remlink(&ob->modifiers, md);
+ modifier_free(md);
+ }
+ }
+ }
+}
+void ED_object_parent_clear(Object *ob, int type)
+{
if (ob->parent == NULL)
return;
+
+ switch (type) {
+ case CLEAR_PARENT_ALL:
+ {
+ /* for deformers, remove corresponding modifiers to prevent a large number of modifiers building up */
+ object_remove_parent_deform_modifiers(ob, ob->parent);
+
+ /* clear parenting relationship completely */
+ ob->parent = NULL;
+ }
+ break;
- if (type == 0) {
- ob->parent = NULL;
- }
- else if (type == 1) {
- ob->parent = NULL;
- BKE_object_apply_mat4(ob, ob->obmat, TRUE, FALSE);
- }
- else if (type == 2)
- unit_m4(ob->parentinv);
+ case CLEAR_PARENT_KEEP_TRANSFORM:
+ {
+ /* remove parent, and apply the parented transform result as object's local transforms */
+ ob->parent = NULL;
+ BKE_object_apply_mat4(ob, ob->obmat, TRUE, FALSE);
+ }
+ break;
+ case CLEAR_PARENT_INVERSE:
+ {
+ /* object stays parented, but the parent inverse (i.e. offset from parent to retain binding state) is cleared */
+ unit_m4(ob->parentinv);
+ }
+ break;
+ }
+
ob->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
}
@@ -525,7 +588,7 @@ EnumPropertyItem prop_make_parent_types[] = {
};
int ED_object_parent_set(ReportList *reports, Main *bmain, Scene *scene, Object *ob, Object *par,
- int partype, int xmirror)
+ int partype, int xmirror, int keep_transform)
{
bPoseChannel *pchan = NULL;
int pararm = ELEM4(partype, PAR_ARMATURE, PAR_ARMATURE_NAME, PAR_ARMATURE_ENVELOPE, PAR_ARMATURE_AUTO);
@@ -559,13 +622,13 @@ int ED_object_parent_set(ReportList *reports, Main *bmain, Scene *scene, Object
/* fall back on regular parenting now (for follow only) */
if (partype == PAR_FOLLOW)
partype = PAR_OBJECT;
- }
+ }
}
else if (partype == PAR_BONE) {
pchan = BKE_pose_channel_active(par);
if (pchan == NULL) {
- BKE_report(reports, RPT_ERROR, "No active Bone");
+ BKE_report(reports, RPT_ERROR, "No active bone");
return 0;
}
}
@@ -577,10 +640,14 @@ int ED_object_parent_set(ReportList *reports, Main *bmain, Scene *scene, Object
}
else {
Object workob;
-
+
/* apply transformation of previous parenting */
- /* BKE_object_apply_mat4(ob, ob->obmat); */ /* removed because of bug [#23577] */
-
+ if (keep_transform) {
+ /* was removed because of bug [#23577],
+ * but this can be handy in some cases too [#32616], so make optional */
+ BKE_object_apply_mat4(ob, ob->obmat, FALSE, FALSE);
+ }
+
/* set the parent (except for follow-path constraint option) */
if (partype != PAR_PATH_CONST) {
ob->parent = par;
@@ -600,25 +667,40 @@ int ED_object_parent_set(ReportList *reports, Main *bmain, Scene *scene, Object
* NOTE: the old (2.4x) method was to set ob->partype = PARSKEL, creating the virtual modifiers
*/
ob->partype = PAROBJECT; /* note, dna define, not operator property */
- //ob->partype= PARSKEL; /* note, dna define, not operator property */
+ //ob->partype = PARSKEL; /* note, dna define, not operator property */
- /* BUT, to keep the deforms, we need a modifier, and then we need to set the object that it uses */
+ /* BUT, to keep the deforms, we need a modifier, and then we need to set the object that it uses
+ * - We need to ensure that the modifier we're adding doesn't already exist, so we check this by
+ * assuming that the parent is selected too...
+ */
// XXX currently this should only happen for meshes, curves, surfaces, and lattices - this stuff isn't available for metas yet
if (ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
ModifierData *md;
switch (partype) {
case PAR_CURVE: /* curve deform */
- md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Curve);
- ((CurveModifierData *)md)->object = par;
+ if ( modifiers_isDeformedByCurve(ob) != par) {
+ md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Curve);
+ if (md) {
+ ((CurveModifierData *)md)->object = par;
+ }
+ }
break;
case PAR_LATTICE: /* lattice deform */
- md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Lattice);
- ((LatticeModifierData *)md)->object = par;
+ if (modifiers_isDeformedByLattice(ob) != par) {
+ md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Lattice);
+ if (md) {
+ ((LatticeModifierData *)md)->object = par;
+ }
+ }
break;
default: /* armature deform */
- md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Armature);
- ((ArmatureModifierData *)md)->object = par;
+ if (modifiers_isDeformedByArmature(ob) != par) {
+ md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Armature);
+ if (md) {
+ ((ArmatureModifierData *)md)->object = par;
+ }
+ }
break;
}
}
@@ -682,11 +764,12 @@ static int parent_set_exec(bContext *C, wmOperator *op)
Object *par = ED_object_active_context(C);
int partype = RNA_enum_get(op->ptr, "type");
int xmirror = RNA_boolean_get(op->ptr, "xmirror");
+ int keep_transform = RNA_boolean_get(op->ptr, "keep_transform");
int ok = 1;
CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
{
- if (!ED_object_parent_set(op->reports, bmain, scene, ob, par, partype, xmirror)) {
+ if (!ED_object_parent_set(op->reports, bmain, scene, ob, par, partype, xmirror, keep_transform)) {
ok = 0;
break;
}
@@ -710,25 +793,36 @@ static int parent_set_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *UNUSE
Object *ob = ED_object_active_context(C);
uiPopupMenu *pup = uiPupMenuBegin(C, "Set Parent To", ICON_NONE);
uiLayout *layout = uiPupMenuLayout(pup);
-
- uiLayoutSetOperatorContext(layout, WM_OP_EXEC_DEFAULT);
- uiItemEnumO(layout, "OBJECT_OT_parent_set", NULL, 0, "type", PAR_OBJECT);
-
+
+ wmOperatorType *ot = WM_operatortype_find("OBJECT_OT_parent_set", TRUE);
+ PointerRNA opptr;
+
+#if 0
+ uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_OBJECT);
+#else
+ opptr = uiItemFullO_ptr(layout, ot, "Object", ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ RNA_enum_set(&opptr, "type", PAR_OBJECT);
+ RNA_boolean_set(&opptr, "keep_transform", FALSE);
+
+ opptr = uiItemFullO_ptr(layout, ot, "Object (Keep Transform)", ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ RNA_enum_set(&opptr, "type", PAR_OBJECT);
+ RNA_boolean_set(&opptr, "keep_transform", TRUE);
+#endif
/* ob becomes parent, make the associated menus */
if (ob->type == OB_ARMATURE) {
- uiItemEnumO(layout, "OBJECT_OT_parent_set", NULL, 0, "type", PAR_ARMATURE);
- uiItemEnumO(layout, "OBJECT_OT_parent_set", NULL, 0, "type", PAR_ARMATURE_NAME);
- uiItemEnumO(layout, "OBJECT_OT_parent_set", NULL, 0, "type", PAR_ARMATURE_ENVELOPE);
- uiItemEnumO(layout, "OBJECT_OT_parent_set", NULL, 0, "type", PAR_ARMATURE_AUTO);
- uiItemEnumO(layout, "OBJECT_OT_parent_set", NULL, 0, "type", PAR_BONE);
+ uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE);
+ uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_NAME);
+ uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_ENVELOPE);
+ uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_AUTO);
+ uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_BONE);
}
else if (ob->type == OB_CURVE) {
- uiItemEnumO(layout, "OBJECT_OT_parent_set", NULL, 0, "type", PAR_CURVE);
- uiItemEnumO(layout, "OBJECT_OT_parent_set", NULL, 0, "type", PAR_FOLLOW);
- uiItemEnumO(layout, "OBJECT_OT_parent_set", NULL, 0, "type", PAR_PATH_CONST);
+ uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_CURVE);
+ uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_FOLLOW);
+ uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_PATH_CONST);
}
else if (ob->type == OB_LATTICE) {
- uiItemEnumO(layout, "OBJECT_OT_parent_set", NULL, 0, "type", PAR_LATTICE);
+ uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_LATTICE);
}
uiPupMenuEnd(C, pup);
@@ -783,6 +877,9 @@ void OBJECT_OT_parent_set(wmOperatorType *ot)
RNA_def_enum(ot->srna, "type", prop_make_parent_types, 0, "Type", "");
RNA_def_boolean(ot->srna, "xmirror", FALSE, "X Mirror",
"Apply weights symmetrically along X axis, for Envelope/Automatic vertex groups creation");
+ RNA_def_boolean(ot->srna, "keep_transform", FALSE, "Keep Transform",
+ "Apply transformation before parenting");
+
}
/* ************ Make Parent Without Inverse Operator ******************* */
@@ -939,7 +1036,7 @@ static int object_track_clear_exec(bContext *C, wmOperator *op)
int type = RNA_enum_get(op->ptr, "type");
if (CTX_data_edit_object(C)) {
- BKE_report(op->reports, RPT_ERROR, "Operation cannot be performed in EditMode");
+ BKE_report(op->reports, RPT_ERROR, "Operation cannot be performed in edit mode");
return OPERATOR_CANCELLED;
}
CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
@@ -1163,7 +1260,7 @@ static int move_to_layer_exec(bContext *C, wmOperator *op)
base->object->lay = lay;
base->object->flag &= ~SELECT;
base->flag &= ~SELECT;
- /* if (base->object->type==OB_LAMP) is_lamp = TRUE; */
+ /* if (base->object->type == OB_LAMP) is_lamp = TRUE; */
}
CTX_DATA_END;
}
@@ -1176,7 +1273,7 @@ static int move_to_layer_exec(bContext *C, wmOperator *op)
local = base->lay & 0xFF000000;
base->lay = lay + local;
base->object->lay = lay;
- /* if (base->object->type==OB_LAMP) is_lamp = TRUE; */
+ /* if (base->object->type == OB_LAMP) is_lamp = TRUE; */
}
CTX_DATA_END;
}
@@ -1253,17 +1350,17 @@ static int make_links_scene_exec(bContext *C, wmOperator *op)
Scene *scene_to = BLI_findlink(&CTX_data_main(C)->scene, RNA_enum_get(op->ptr, "scene"));
if (scene_to == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Couldn't find scene");
+ BKE_report(op->reports, RPT_ERROR, "Could not find scene");
return OPERATOR_CANCELLED;
}
if (scene_to == CTX_data_scene(C)) {
- BKE_report(op->reports, RPT_ERROR, "Can't link objects into the same scene");
+ BKE_report(op->reports, RPT_ERROR, "Cannot link objects into the same scene");
return OPERATOR_CANCELLED;
}
if (scene_to->id.lib) {
- BKE_report(op->reports, RPT_ERROR, "Can't link objects into a linked scene");
+ BKE_report(op->reports, RPT_ERROR, "Cannot link objects into a linked scene");
return OPERATOR_CANCELLED;
}
@@ -1275,6 +1372,9 @@ static int make_links_scene_exec(bContext *C, wmOperator *op)
DAG_ids_flush_update(bmain, 0);
+ /* redraw the 3D view because the object center points are colored differently */
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, NULL);
+
/* one day multiple scenes will be visible, then we should have some update function for them */
return OPERATOR_FINISHED;
}
@@ -1610,7 +1710,7 @@ static void single_obdata_users(Main *bmain, Scene *scene, int flag)
break;
case OB_MESH:
ob->data = BKE_mesh_copy(ob->data);
- //me= ob->data;
+ //me = ob->data;
//if (me && me->key)
// ipo_idnew(me->key->ipo); /* drivers */
break;
diff --git a/source/blender/editors/object/object_select.c b/source/blender/editors/object/object_select.c
index 7eb8cc01db9..2aa737d204d 100644
--- a/source/blender/editors/object/object_select.c
+++ b/source/blender/editors/object/object_select.c
@@ -198,7 +198,7 @@ enum {
};
static EnumPropertyItem prop_select_linked_types[] = {
- //{OBJECT_SELECT_LINKED_IPO, "IPO", 0, "Object IPO", ""}, // XXX depreceated animation system stuff...
+ //{OBJECT_SELECT_LINKED_IPO, "IPO", 0, "Object IPO", ""}, // XXX deprecated animation system stuff...
{OBJECT_SELECT_LINKED_OBDATA, "OBDATA", 0, "Object Data", ""},
{OBJECT_SELECT_LINKED_MATERIAL, "MATERIAL", 0, "Material", ""},
{OBJECT_SELECT_LINKED_TEXTURE, "TEXTURE", 0, "Texture", ""},
@@ -425,7 +425,7 @@ static int object_select_linked_exec(bContext *C, wmOperator *op)
ob = OBACT;
if (ob == NULL) {
- BKE_report(op->reports, RPT_ERROR, "No Active Object");
+ BKE_report(op->reports, RPT_ERROR, "No active object");
return OPERATOR_CANCELLED;
}
@@ -608,11 +608,11 @@ static short select_grouped_group(bContext *C, Object *ob) /* Select objects in
for (i = 0; i < group_count; i++) {
group = ob_groups[i];
- uiItemStringO(layout, group->id.name + 2, 0, "OBJECT_OT_select_same_group", "group", group->id.name);
+ uiItemStringO(layout, group->id.name + 2, 0, "OBJECT_OT_select_same_group", "group", group->id.name + 2);
}
uiPupMenuEnd(C, pup);
- return changed; // The operator already handle this!
+ return changed; /* The operator already handle this! */
}
static short select_grouped_object_hooks(bContext *C, Object *ob)
@@ -723,7 +723,7 @@ static short objects_share_gameprop(Object *a, Object *b)
/*make a copy of all its properties*/
for (prop = a->prop.first; prop; prop = prop->next) {
- if (get_ob_property(b, prop->name) )
+ if (BKE_bproperty_object_get(b, prop->name) )
return 1;
}
return 0;
@@ -754,8 +754,8 @@ static short select_grouped_keyingset(bContext *C, Object *UNUSED(ob))
return 0;
/* select each object that Keying Set refers to */
- // TODO: perhaps to be more in line with the rest of these, we should only take objects
- // if the passed in object is included in this too
+ /* TODO: perhaps to be more in line with the rest of these, we should only take objects
+ * if the passed in object is included in this too */
CTX_DATA_BEGIN (C, Base *, base, selectable_bases)
{
/* only check for this object if it isn't selected already, to limit time wasted */
@@ -800,7 +800,7 @@ static int object_select_grouped_exec(bContext *C, wmOperator *op)
ob = OBACT;
if (ob == NULL) {
- BKE_report(op->reports, RPT_ERROR, "No Active Object");
+ BKE_report(op->reports, RPT_ERROR, "No active object");
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/object/object_shapekey.c b/source/blender/editors/object/object_shapekey.c
index 40b653a62fd..2b6d69ca694 100644
--- a/source/blender/editors/object/object_shapekey.c
+++ b/source/blender/editors/object/object_shapekey.c
@@ -78,7 +78,7 @@ static void ED_object_shape_key_add(bContext *C, Scene *scene, Object *ob, int f
{
KeyBlock *kb;
if ((kb = BKE_object_insert_shape_key(scene, ob, NULL, from_mix))) {
- Key *key = ob_get_key(ob);
+ Key *key = BKE_key_from_object(ob);
/* for absolute shape keys, new keys may not be added last */
ob->shapenr = BLI_findindex(&key->block, kb) + 1;
@@ -95,7 +95,7 @@ static int ED_object_shape_key_remove(bContext *C, Object *ob)
Key *key;
//IpoCurve *icu;
- key = ob_get_key(ob);
+ key = BKE_key_from_object(ob);
if (key == NULL)
return 0;
@@ -115,14 +115,14 @@ static int ED_object_shape_key_remove(bContext *C, Object *ob)
/* apply new basis key on original data */
switch (ob->type) {
case OB_MESH:
- key_to_mesh(key->refkey, ob->data);
+ BKE_key_convert_to_mesh(key->refkey, ob->data);
break;
case OB_CURVE:
case OB_SURF:
- key_to_curve(key->refkey, ob->data, BKE_curve_nurbs_get(ob->data));
+ BKE_key_convert_to_curve(key->refkey, ob->data, BKE_curve_nurbs_get(ob->data));
break;
case OB_LATTICE:
- key_to_latt(key->refkey, ob->data);
+ BKE_key_convert_to_lattice(key->refkey, ob->data);
break;
}
}
@@ -155,22 +155,22 @@ static int object_shape_key_mirror(bContext *C, Object *ob)
KeyBlock *kb;
Key *key;
- key = ob_get_key(ob);
+ key = BKE_key_from_object(ob);
if (key == NULL)
return 0;
kb = BLI_findlink(&key->block, ob->shapenr - 1);
if (kb) {
- int i1, i2;
- float *fp1, *fp2;
- float tvec[3];
char *tag_elem = MEM_callocN(sizeof(char) * kb->totelem, "shape_key_mirror");
if (ob->type == OB_MESH) {
Mesh *me = ob->data;
MVert *mv;
+ int i1, i2;
+ float *fp1, *fp2;
+ float tvec[3];
mesh_octree_table(ob, NULL, NULL, 's');
@@ -211,7 +211,7 @@ static int object_shape_key_mirror(bContext *C, Object *ob)
/* currently editmode isn't supported by mesh so
* ignore here for now too */
- /* if (lt->editlatt) lt= lt->editlatt->latt; */
+ /* if (lt->editlatt) lt = lt->editlatt->latt; */
for (w = 0; w < lt->pntsw; w++) {
for (v = 0; v < lt->pntsv; v++) {
@@ -323,8 +323,8 @@ void OBJECT_OT_shape_key_remove(wmOperatorType *ot)
static int shape_key_clear_exec(bContext *C, wmOperator *UNUSED(op))
{
Object *ob = ED_object_context(C);
- Key *key = ob_get_key(ob);
- KeyBlock *kb = ob_get_keyblock(ob);
+ Key *key = BKE_key_from_object(ob);
+ KeyBlock *kb = BKE_keyblock_from_object(ob);
if (!key || !kb)
return OPERATOR_CANCELLED;
@@ -357,8 +357,8 @@ void OBJECT_OT_shape_key_clear(wmOperatorType *ot)
static int shape_key_retime_exec(bContext *C, wmOperator *UNUSED(op))
{
Object *ob = ED_object_context(C);
- Key *key = ob_get_key(ob);
- KeyBlock *kb = ob_get_keyblock(ob);
+ Key *key = BKE_key_from_object(ob);
+ KeyBlock *kb = BKE_keyblock_from_object(ob);
float cfra = 0.0f;
if (!key || !kb)
@@ -419,7 +419,7 @@ static int shape_key_move_exec(bContext *C, wmOperator *op)
Object *ob = ED_object_context(C);
int type = RNA_enum_get(op->ptr, "type");
- Key *key = ob_get_key(ob);
+ Key *key = BKE_key_from_object(ob);
if (key) {
KeyBlock *kb, *kb_other;
diff --git a/source/blender/editors/object/object_transform.c b/source/blender/editors/object/object_transform.c
index 9129d651d4d..900bf57b509 100644
--- a/source/blender/editors/object/object_transform.c
+++ b/source/blender/editors/object/object_transform.c
@@ -171,7 +171,7 @@ static void object_clear_rot(Object *ob)
}
}
} // Duplicated in source/blender/editors/armature/editarmature.c
- else {
+ else {
if (ob->rotmode == ROT_MODE_QUAT) {
unit_qt(ob->quat);
unit_qt(ob->dquat);
@@ -217,7 +217,7 @@ static int object_clear_transform_generic_exec(bContext *C, wmOperator *op,
/* sanity checks */
if (ELEM(NULL, clear_func, default_ksName)) {
- BKE_report(op->reports, RPT_ERROR, "Programming error: missing clear transform func or Keying Set Name");
+ BKE_report(op->reports, RPT_ERROR, "Programming error: missing clear transform function or keying set name");
return OPERATOR_CANCELLED;
}
@@ -381,8 +381,8 @@ static int apply_objects_internal(bContext *C, ReportList *reports, int apply_lo
{
Main *bmain = CTX_data_main(C);
Scene *scene = CTX_data_scene(C);
- float rsmat[3][3], tmat[3][3], obmat[3][3], iobmat[3][3], mat[4][4], scale;
- int a, change = 1;
+ float rsmat[3][3], obmat[3][3], iobmat[3][3], mat[4][4], scale;
+ int change = 1;
/* first check if we can execute */
CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
@@ -390,19 +390,19 @@ static int apply_objects_internal(bContext *C, ReportList *reports, int apply_lo
if (ob->type == OB_MESH) {
if (ID_REAL_USERS(ob->data) > 1) {
- BKE_report(reports, RPT_ERROR, "Can't apply to a multi user mesh, doing nothing");
+ BKE_report(reports, RPT_ERROR, "Cannot apply to a multi user mesh, doing nothing");
change = 0;
}
}
else if (ob->type == OB_ARMATURE) {
if (ID_REAL_USERS(ob->data) > 1) {
- BKE_report(reports, RPT_ERROR, "Can't apply to a multi user armature, doing nothing");
+ BKE_report(reports, RPT_ERROR, "Cannot apply to a multi user armature, doing nothing");
change = 0;
}
}
else if (ob->type == OB_LATTICE) {
if (ID_REAL_USERS(ob->data) > 1) {
- BKE_report(reports, RPT_ERROR, "Can't apply to a multi user lattice, doing nothing");
+ BKE_report(reports, RPT_ERROR, "Cannot apply to a multi user lattice, doing nothing");
change = 0;
}
}
@@ -410,18 +410,19 @@ static int apply_objects_internal(bContext *C, ReportList *reports, int apply_lo
Curve *cu;
if (ID_REAL_USERS(ob->data) > 1) {
- BKE_report(reports, RPT_ERROR, "Can't apply to a multi user curve, doing nothing");
+ BKE_report(reports, RPT_ERROR, "Cannot apply to a multi user curve, doing nothing");
change = 0;
}
cu = ob->data;
if (!(cu->flag & CU_3D) && (apply_rot || apply_loc)) {
- BKE_report(reports, RPT_ERROR, "Neither rotation nor location could be applied to a 2d curve, doing nothing");
+ BKE_report(reports, RPT_ERROR,
+ "Neither rotation nor location could be applied to a 2D curve, doing nothing");
change = 0;
}
if (cu->key) {
- BKE_report(reports, RPT_ERROR, "Can't apply to a curve with vertex keys, doing nothing");
+ BKE_report(reports, RPT_ERROR, "Cannot apply to a curve with vertex keys, doing nothing");
change = 0;
}
}
@@ -464,6 +465,7 @@ static int apply_objects_internal(bContext *C, ReportList *reports, int apply_lo
copy_v3_v3(mat[3], ob->loc);
if (!(apply_scale && apply_rot)) {
+ float tmat[3][3];
/* correct for scale and rotation that is still applied */
BKE_object_to_mat3(ob, obmat);
invert_m3_m3(iobmat, obmat);
@@ -476,6 +478,7 @@ static int apply_objects_internal(bContext *C, ReportList *reports, int apply_lo
if (ob->type == OB_MESH) {
Mesh *me = ob->data;
MVert *mvert;
+ int a;
if (apply_scale)
multiresModifier_scale_disp(scene, ob);
@@ -518,6 +521,7 @@ static int apply_objects_internal(bContext *C, ReportList *reports, int apply_lo
Nurb *nu;
BPoint *bp;
BezTriple *bezt;
+ int a;
scale = mat3_to_scale(rsmat);
@@ -650,7 +654,8 @@ void OBJECT_OT_transform_apply(wmOperatorType *ot)
enum {
GEOMETRY_TO_ORIGIN = 0,
ORIGIN_TO_GEOMETRY,
- ORIGIN_TO_CURSOR
+ ORIGIN_TO_CURSOR,
+ ORIGIN_TO_CENTER_OF_MASS
};
static int object_origin_set_exec(bContext *C, wmOperator *op)
@@ -667,7 +672,7 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
int tot_change = 0, tot_lib_error = 0, tot_multiuser_arm_error = 0;
if (obedit && centermode != GEOMETRY_TO_ORIGIN) {
- BKE_report(op->reports, RPT_ERROR, "Operation cannot be performed in EditMode");
+ BKE_report(op->reports, RPT_ERROR, "Operation cannot be performed in edit mode");
return OPERATOR_CANCELLED;
}
else {
@@ -781,6 +786,7 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
Mesh *me = ob->data;
if (centermode == ORIGIN_TO_CURSOR) { /* done */ }
+ else if (centermode == ORIGIN_TO_CENTER_OF_MASS) { BKE_mesh_center_centroid(me, cent); }
else if (around == V3D_CENTROID) { BKE_mesh_center_median(me, cent); }
else { BKE_mesh_center_bounds(me, cent); }
@@ -848,7 +854,7 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
if (ID_REAL_USERS(arm) > 1) {
#if 0
- BKE_report(op->reports, RPT_ERROR, "Can't apply to a multi user armature");
+ BKE_report(op->reports, RPT_ERROR, "Cannot apply to a multi user armature");
return;
#endif
tot_multiuser_arm_error++;
@@ -861,7 +867,7 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
tot_change++;
arm->id.flag |= LIB_DOIT;
- /* do_inverse_offset= TRUE; */ /* docenter_armature() handles this */
+ /* do_inverse_offset = TRUE; */ /* docenter_armature() handles this */
BKE_object_where_is_calc(scene, ob);
BKE_pose_where_is(scene, ob); /* needed for bone parents */
@@ -896,10 +902,17 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
/* offset other selected objects */
if (do_inverse_offset && (centermode != GEOMETRY_TO_ORIGIN)) {
+ CollectionPointerLink *ctx_link_other;
+ float obmat[4][4];
+
/* was the object data modified
* note: the functions above must set 'cent' */
+
+ /* convert the offset to parent space */
+ BKE_object_to_mat4(ob, obmat);
copy_v3_v3(centn, cent);
- mul_mat3_m4_v3(ob->obmat, centn); /* ommit translation part */
+ mul_mat3_m4_v3(obmat, centn); /* omit translation part */
+
add_v3_v3(ob->loc, centn);
BKE_object_where_is_calc(scene, ob);
@@ -910,8 +923,16 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
ignore_parent_tx(bmain, scene, ob);
/* other users? */
- CTX_DATA_BEGIN (C, Object *, ob_other, selected_editable_objects)
+ //CTX_DATA_BEGIN (C, Object *, ob_other, selected_editable_objects)
+ //{
+
+ /* use existing context looper */
+ for (ctx_link_other = ctx_data_list.first;
+ ctx_link_other;
+ ctx_link_other = ctx_link_other->next)
{
+ Object *ob_other = ctx_link_other->ptr.data;
+
if ((ob_other->flag & OB_DONE) == 0 &&
((ob->data && (ob->data == ob_other->data)) ||
(ob->dup_group == ob_other->dup_group &&
@@ -931,7 +952,7 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
ignore_parent_tx(bmain, scene, ob_other);
}
}
- CTX_DATA_END;
+ //CTX_DATA_END;
}
}
}
@@ -948,9 +969,9 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
/* Warn if any errors occurred */
if (tot_lib_error + tot_multiuser_arm_error) {
- BKE_reportf(op->reports, RPT_WARNING, "%i Object(s) Not Centered, %i Changed:", tot_lib_error + tot_multiuser_arm_error, tot_change);
+ BKE_reportf(op->reports, RPT_WARNING, "%i object(s) not centered, %i changed:", tot_lib_error + tot_multiuser_arm_error, tot_change);
if (tot_lib_error)
- BKE_reportf(op->reports, RPT_WARNING, "|%i linked library objects", tot_lib_error);
+ BKE_reportf(op->reports, RPT_WARNING, "|%i linked library object(s)", tot_lib_error);
if (tot_multiuser_arm_error)
BKE_reportf(op->reports, RPT_WARNING, "|%i multiuser armature object(s)", tot_multiuser_arm_error);
}
@@ -962,8 +983,12 @@ void OBJECT_OT_origin_set(wmOperatorType *ot)
{
static EnumPropertyItem prop_set_center_types[] = {
{GEOMETRY_TO_ORIGIN, "GEOMETRY_ORIGIN", 0, "Geometry to Origin", "Move object geometry to object origin"},
- {ORIGIN_TO_GEOMETRY, "ORIGIN_GEOMETRY", 0, "Origin to Geometry", "Move object origin to center of object geometry"},
- {ORIGIN_TO_CURSOR, "ORIGIN_CURSOR", 0, "Origin to 3D Cursor", "Move object origin to position of the 3d cursor"},
+ {ORIGIN_TO_GEOMETRY, "ORIGIN_GEOMETRY", 0, "Origin to Geometry",
+ "Move object origin to center of object geometry"},
+ {ORIGIN_TO_CURSOR, "ORIGIN_CURSOR", 0, "Origin to 3D Cursor",
+ "Move object origin to position of the 3D cursor"},
+ {ORIGIN_TO_CENTER_OF_MASS, "ORIGIN_CENTER_OF_MASS", 0, "Origin to Center of Mass",
+ "Move object origin to the object center of mass (assuming uniform density)"},
{0, NULL, 0, NULL, NULL}
};
@@ -975,7 +1000,7 @@ void OBJECT_OT_origin_set(wmOperatorType *ot)
/* identifiers */
ot->name = "Set Origin";
- ot->description = "Set the object's origin, by either moving the data, or set to center of data, or use 3d cursor";
+ ot->description = "Set the object's origin, by either moving the data, or set to center of data, or use 3D cursor";
ot->idname = "OBJECT_OT_origin_set";
/* api callbacks */
@@ -990,4 +1015,3 @@ void OBJECT_OT_origin_set(wmOperatorType *ot)
ot->prop = RNA_def_enum(ot->srna, "type", prop_set_center_types, 0, "Type", "");
RNA_def_enum(ot->srna, "center", prop_set_bounds_types, V3D_CENTROID, "Center", "");
}
-
diff --git a/source/blender/editors/object/object_vgroup.c b/source/blender/editors/object/object_vgroup.c
index b31d2b8b076..05524af34f0 100644
--- a/source/blender/editors/object/object_vgroup.c
+++ b/source/blender/editors/object/object_vgroup.c
@@ -20,7 +20,7 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): none yet.
+ * Contributor(s): Ove M Henriksen.
*
* ***** END GPL LICENSE BLOCK *****
*/
@@ -29,7 +29,6 @@
* \ingroup edobj
*/
-
#include <string.h>
#include <stddef.h>
#include <math.h>
@@ -83,6 +82,19 @@ static void vgroup_delete_edit_mode(Object *ob, bDeformGroup *defgroup);
static void vgroup_delete_object_mode(Object *ob, bDeformGroup *dg);
static void vgroup_delete_all(Object *ob);
+static int vertex_group_use_vert_sel(Object *ob)
+{
+ if (ob->mode == OB_MODE_EDIT) {
+ return TRUE;
+ }
+ else if (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) {
+ return TRUE;
+ }
+ else {
+ return FALSE;
+ }
+}
+
static Lattice *vgroup_edit_lattice(Object *ob)
{
Lattice *lt = ob->data;
@@ -126,21 +138,12 @@ bDeformGroup *ED_vgroup_add(Object *ob)
void ED_vgroup_delete(Object *ob, bDeformGroup *defgroup)
{
- bDeformGroup *dg = (bDeformGroup *)ob->defbase.first;
-
- while (dg) {
- if (dg == defgroup)
- break;
- dg = dg->next;
- }
-
- if (dg == NULL)
- return;
+ BLI_assert(BLI_findindex(&ob->defbase, defgroup) != -1);
if (ED_vgroup_object_is_edit_mode(ob))
- vgroup_delete_edit_mode(ob, dg);
+ vgroup_delete_edit_mode(ob, defgroup);
else
- vgroup_delete_object_mode(ob, dg);
+ vgroup_delete_object_mode(ob, defgroup);
}
void ED_vgroup_clear(Object *ob)
@@ -377,6 +380,332 @@ int ED_vgroup_copy_array(Object *ob, Object *ob_from)
return 1;
}
+/***********************Start weight transfer (WT)*********************************/
+
+typedef enum WT_VertexGroupMode {
+ WT_REPLACE_ACTIVE_VERTEX_GROUP = 1,
+ WT_REPLACE_ALL_VERTEX_GROUPS = 2
+} WT_VertexGroupMode;
+
+typedef enum WT_Method {
+ WT_BY_INDEX = 1,
+ WT_BY_NEAREST_VERTEX = 2,
+ WT_BY_NEAREST_FACE = 3,
+ WT_BY_NEAREST_VERTEX_IN_FACE = 4
+} WT_Method;
+
+typedef enum WT_ReplaceMode {
+ WT_REPLACE_ALL_WEIGHTS = 1,
+ WT_REPLACE_EMPTY_WEIGHTS = 2
+} WT_ReplaceMode;
+
+static EnumPropertyItem WT_vertex_group_mode_item[] = {
+ {WT_REPLACE_ACTIVE_VERTEX_GROUP, "WT_REPLACE_ACTIVE_VERTEX_GROUP", 1, "Active", "Transfer active vertex group from selected to active mesh"},
+ {WT_REPLACE_ALL_VERTEX_GROUPS, "WT_REPLACE_ALL_VERTEX_GROUPS", 1, "All", "Transfer all vertex groups from selected to active mesh"},
+ {0, NULL, 0, NULL, NULL}
+};
+
+static EnumPropertyItem WT_method_item[] = {
+ {WT_BY_INDEX, "WT_BY_INDEX", 1, "Vertex index", "Copy for identical meshes"},
+ {WT_BY_NEAREST_VERTEX, "WT_BY_NEAREST_VERTEX", 1, "Nearest vertex", "Copy weight from closest vertex"},
+ {WT_BY_NEAREST_FACE, "WT_BY_NEAREST_FACE", 1, "Nearest face", "Barycentric interpolation from nearest face"},
+ {WT_BY_NEAREST_VERTEX_IN_FACE, "WT_BY_NEAREST_VERTEX_IN_FACE", 1, "Nearest vertex in face", "Copy weight from closest vertex in nearest face"},
+ {0, NULL, 0, NULL, NULL}
+};
+
+static EnumPropertyItem WT_replace_mode_item[] = {
+ {WT_REPLACE_ALL_WEIGHTS, "WT_REPLACE_ALL_WEIGHTS", 1, "All", "Overwrite all weights"},
+ {WT_REPLACE_EMPTY_WEIGHTS, "WT_REPLACE_EMPTY_WEIGHTS", 1, "Empty", "Add weights to vertices with no weight"},
+ {0, NULL, 0, NULL, NULL}
+};
+
+/*copy weight*/
+static void vgroup_transfer_weight(float *r_weight_dst, const float weight_src, const WT_ReplaceMode replace_mode)
+{
+ switch (replace_mode) {
+ case WT_REPLACE_ALL_WEIGHTS:
+ *r_weight_dst = weight_src;
+ break;
+
+ case WT_REPLACE_EMPTY_WEIGHTS:
+ if (*r_weight_dst == 0.0f) {
+ *r_weight_dst = weight_src;
+ }
+ break;
+
+ default:
+ BLI_assert(0);
+ break;
+ }
+}
+
+/* could be exposed externally */
+static int ed_vgroup_transfer_weight(Object *ob_dst, Object *ob_src, bDeformGroup *dg_src, Scene *scene,
+ WT_Method method, WT_ReplaceMode replace_mode, wmOperator *op)
+{
+ bDeformGroup *dg_dst;
+ Mesh *me_dst, *me_src;
+ DerivedMesh *dmesh_src;
+ BVHTreeFromMesh tree_mesh_vertices_src, tree_mesh_faces_src = {NULL};
+ MDeformVert **dv_array_src, **dv_array_dst, **dv_src, **dv_dst;
+ MVert *mv_dst, *mv_src;
+ MFace *mface_src, *mf;
+ BVHTreeNearest nearest;
+ MDeformWeight *dw_dst, *dw_src;
+ int dv_tot_src, dv_tot_dst, i, v_index, index_dst, index_src, index_nearest, index_nearest_vertex;
+ unsigned int f_index;
+ float weight, tmp_weight[4], tmp_co[3], normal[3], tmp_mat[4][4], dist_v1, dist_v2, dist_v3, dist_v4;
+ const int use_vert_sel = vertex_group_use_vert_sel(ob_dst);
+
+ /* create new and overwrite vertex group on destination without data */
+ if (!defgroup_find_name(ob_dst, dg_src->name)) {
+ ED_vgroup_delete(ob_dst, defgroup_find_name(ob_dst, dg_src->name));
+ ED_vgroup_add_name(ob_dst, dg_src->name);
+ }
+
+ /* get destination deformgroup */
+ dg_dst = defgroup_find_name(ob_dst, dg_src->name);
+
+ /* get meshes */
+ dmesh_src = mesh_get_derived_deform(scene, ob_src, CD_MASK_BAREMESH);
+ me_dst = ob_dst->data;
+ me_src = ob_src->data;
+
+ /* sanity check */
+ if (!me_src->dvert) {
+ BKE_report(op->reports, RPT_ERROR, "Transfer failed (source mesh does not have any vertex groups)");
+ return 0;
+ }
+
+ /* create data in memory when nothing there */
+ if (!me_dst->dvert) ED_vgroup_data_create(ob_dst->data);
+
+ /* get vertex group arrays */
+ ED_vgroup_give_parray(ob_src->data, &dv_array_src, &dv_tot_src, FALSE);
+ ED_vgroup_give_parray(ob_dst->data, &dv_array_dst, &dv_tot_dst, use_vert_sel);
+
+ /* get indexes of vertex groups */
+ index_src = BLI_findindex(&ob_src->defbase, dg_src);
+ index_dst = BLI_findindex(&ob_dst->defbase, dg_dst);
+
+ /* get vertices */
+ mv_dst = me_dst->mvert;
+ mv_src = dmesh_src->getVertArray(dmesh_src);
+
+ /* prepare transformation matrix */
+ invert_m4_m4(ob_src->imat, ob_src->obmat);
+ mult_m4_m4m4(tmp_mat, ob_src->imat, ob_dst->obmat);
+
+ /* clear weights */
+ if (replace_mode == WT_REPLACE_ALL_WEIGHTS) {
+ for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++) {
+
+ if (*dv_dst == NULL) continue;
+
+ dw_dst = defvert_find_index(*dv_dst, index_dst);
+ /* remove vertex from group */
+ if (dw_dst) defvert_remove_group(*dv_dst, dw_dst);
+ }
+ }
+
+ switch (method) {
+
+ case WT_BY_INDEX:
+ /* check if indices are matching, delete and return if not */
+ if (ob_dst == ob_src || dv_tot_dst == 0 || dv_tot_dst != dv_tot_src ||
+ dv_array_src == NULL || dv_array_dst == NULL)
+ {
+ ED_vgroup_delete(ob_dst, defgroup_find_name(ob_dst, dg_dst->name));
+ if (dv_array_src) MEM_freeN(dv_array_src);
+ if (dv_array_dst) MEM_freeN(dv_array_dst);
+ dmesh_src->release(dmesh_src);
+ BKE_report(op->reports, RPT_ERROR, "Transfer failed (indices are not matching)");
+ return 0;
+ }
+
+ /* loop through the vertices*/
+ for (i = 0, dv_src = dv_array_src, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++, dv_src++, mv_src++, mv_dst++) {
+
+ if (*dv_dst == NULL) {
+ continue;
+ }
+
+ /* copy weight */
+ dw_src = defvert_find_index(*dv_src, index_src);
+ if (dw_src && dw_src->weight) {
+ dw_dst = defvert_verify_index(*dv_dst, index_dst);
+ vgroup_transfer_weight(&dw_dst->weight, dw_src->weight, replace_mode);
+ }
+ }
+ break;
+
+ case WT_BY_NEAREST_VERTEX:
+ /* make node tree */
+ bvhtree_from_mesh_verts(&tree_mesh_vertices_src, dmesh_src, FLT_EPSILON, 2, 6);
+
+ /* loop trough vertices */
+ for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++, mv_dst++) {
+
+ if (*dv_dst == NULL) {
+ continue;
+ }
+
+ /* reset nearest */
+ nearest.dist = FLT_MAX;
+ /* with current binary tree its marginally faster to start searching at the top, as opposed to previous search. */
+ nearest.index = -1;
+
+ /* transform into target space */
+ mul_v3_m4v3(tmp_co, tmp_mat, mv_dst->co);
+
+ /* node tree accelerated search for closest vetex */
+ BLI_bvhtree_find_nearest(tree_mesh_vertices_src.tree, tmp_co,
+ &nearest, tree_mesh_vertices_src.nearest_callback, &tree_mesh_vertices_src);
+
+ /* copy weight that are not NULL including weight value 0. Existing target weights are overwritten prior to this in relevant cases. */
+ dw_src = defvert_find_index(dv_array_src[nearest.index], index_src);
+ if (dw_src && dw_src->weight) {
+ dw_dst = defvert_verify_index(*dv_dst, index_dst);
+ vgroup_transfer_weight(&dw_dst->weight, dw_src->weight, replace_mode);
+ }
+ }
+
+ /* free memory */
+ free_bvhtree_from_mesh(&tree_mesh_vertices_src);
+ break;
+
+ case WT_BY_NEAREST_FACE:
+ /* get faces */
+ DM_ensure_tessface(dmesh_src);
+ mface_src = dmesh_src->getTessFaceArray(dmesh_src);
+
+ /* make node tree */
+ bvhtree_from_mesh_faces(&tree_mesh_faces_src, dmesh_src, FLT_EPSILON, 2, 6);
+
+ /* loop through the vertices */
+ for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++, mv_dst++) {
+
+ if (*dv_dst == NULL) {
+ continue;
+ }
+
+ /* reset nearest */
+ nearest.dist = FLT_MAX;
+ /* with current binary tree its marginally faster to start searching at the top, as opposed to previous search. */
+ nearest.index = -1;
+
+ /* transform into target space */
+ mul_v3_m4v3(tmp_co, tmp_mat, mv_dst->co);
+
+ /* node tree accelerated search for closest face */
+ BLI_bvhtree_find_nearest(tree_mesh_faces_src.tree, tmp_co,
+ &nearest, tree_mesh_faces_src.nearest_callback, &tree_mesh_faces_src);
+ index_nearest = nearest.index;
+
+ /* project onto face */
+ mf = &mface_src[index_nearest];
+ normal_tri_v3(normal, mv_src[mf->v1].co, mv_src[mf->v2].co, mv_src[mf->v3].co);
+ project_v3_plane(tmp_co, normal, mv_src[mf->v1].co);
+
+ /* interpolate weights over face*/
+ f_index = mf->v4 ? 3 : 2;
+ if (f_index == 3) {
+ interp_weights_face_v3(tmp_weight, mv_src[mf->v1].co, mv_src[mf->v2].co, mv_src[mf->v3].co, mv_src[mf->v4].co, tmp_co);
+ }
+ else {
+ interp_weights_face_v3(tmp_weight, mv_src[mf->v1].co, mv_src[mf->v2].co, mv_src[mf->v3].co, NULL, tmp_co);
+ }
+
+ /* get weights from face*/
+ weight = 0;
+ do {
+ v_index = (&mf->v1)[f_index];
+ weight += tmp_weight[f_index] * defvert_find_weight(dv_array_src[v_index], index_src);
+ } while (f_index--);
+
+ /* copy weight that are not NULL including weight value 0. Existing target weights are overwritten prior to this in relevant cases. */
+ if (weight > 0) {
+ dw_dst = defvert_verify_index(*dv_dst, index_dst);
+ vgroup_transfer_weight(&dw_dst->weight, weight, replace_mode);
+ }
+ }
+
+ /* free memory */
+ free_bvhtree_from_mesh(&tree_mesh_faces_src);
+ break;
+
+ case WT_BY_NEAREST_VERTEX_IN_FACE:
+ /* get faces */
+ DM_ensure_tessface(dmesh_src);
+ mface_src = dmesh_src->getTessFaceArray(dmesh_src);
+
+ /* make node tree */
+ bvhtree_from_mesh_faces(&tree_mesh_faces_src, dmesh_src, FLT_EPSILON, 2, 6);
+
+ /* loop through the vertices */
+ for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++, mv_dst++) {
+
+ if (*dv_dst == NULL) {
+ continue;
+ }
+
+ /* reset nearest */
+ nearest.dist = FLT_MAX;
+ /* With current binary tree its marginally faster to start searching at the top, as opposed to previous search. */
+ nearest.index = -1;
+
+ /* transform into target space */
+ mul_v3_m4v3(tmp_co, tmp_mat, mv_dst->co);
+
+ /* node tree accelerated search for closest face */
+ BLI_bvhtree_find_nearest(tree_mesh_faces_src.tree, tmp_co,
+ &nearest, tree_mesh_faces_src.nearest_callback, &tree_mesh_faces_src);
+ index_nearest = nearest.index;
+
+ /* get distances */
+ mf = &mface_src[index_nearest];
+ dist_v1 = len_squared_v3v3(tmp_co, mv_src[mf->v1].co);
+ dist_v2 = len_squared_v3v3(tmp_co, mv_src[mf->v2].co);
+ dist_v3 = len_squared_v3v3(tmp_co, mv_src[mf->v3].co);
+
+ /* get closest vertex */
+ f_index = mf->v4 ? 3 : 2;
+ if (dist_v1 < dist_v2 && dist_v1 < dist_v3) index_nearest_vertex = mf->v1;
+ else if (dist_v2 < dist_v3) index_nearest_vertex = mf->v2;
+ else index_nearest_vertex = mf->v3;
+ if (f_index == 3) {
+ dist_v4 = len_squared_v3v3(tmp_co, mv_src[mf->v4].co);
+ if (dist_v4 < dist_v1 && dist_v4 < dist_v2 && dist_v4 < dist_v3) {
+ index_nearest_vertex = mf->v4;
+ }
+ }
+
+ /* copy weight that are not NULL including weight value 0. Existing target weights are overwritten prior to this in relevant cases. */
+ dw_src = defvert_find_index(dv_array_src[index_nearest_vertex], index_src);
+ if (dw_src && dw_src->weight) {
+ dw_dst = defvert_verify_index(*dv_dst, index_dst);
+ vgroup_transfer_weight(&dw_dst->weight, dw_src->weight, replace_mode);
+ }
+ }
+
+ /* free memory */
+ free_bvhtree_from_mesh(&tree_mesh_faces_src);
+ break;
+
+ default:
+ BLI_assert(0);
+ break;
+ }
+
+ /*free memory*/
+ if (dv_array_src) MEM_freeN(dv_array_src);
+ if (dv_array_dst) MEM_freeN(dv_array_dst);
+ dmesh_src->release(dmesh_src);
+
+ return 1;
+}
+
+/***********************End weight transfer (WT)***********************************/
/* for Mesh in Object mode */
/* allows editmode for Lattice */
@@ -580,7 +909,6 @@ void ED_vgroup_select_by_name(Object *ob, const char *name)
static void vgroup_select_verts(Object *ob, int select)
{
const int def_nr = ob->actdef - 1;
- MDeformVert *dv;
if (!BLI_findlink(&ob->defbase, def_nr)) {
return;
@@ -596,7 +924,7 @@ static void vgroup_select_verts(Object *ob, int select)
BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
- dv = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT);
+ MDeformVert *dv = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT);
if (defvert_find_index(dv, def_nr)) {
BM_vert_select_set(em->bm, eve, select);
}
@@ -604,7 +932,7 @@ static void vgroup_select_verts(Object *ob, int select)
}
/* this has to be called, because this function operates on vertices only */
- if (select) EDBM_select_flush(em); // vertices to edges/faces
+ if (select) EDBM_select_flush(em); /* vertices to edges/faces */
else EDBM_deselect_flush(em);
}
else {
@@ -633,6 +961,7 @@ static void vgroup_select_verts(Object *ob, int select)
Lattice *lt = vgroup_edit_lattice(ob);
if (lt->dvert) {
+ MDeformVert *dv;
BPoint *bp;
int a, tot;
@@ -704,7 +1033,7 @@ static void vgroup_normalize(Object *ob)
int i, dvert_tot = 0;
const int def_nr = ob->actdef - 1;
- const int use_vert_sel = (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) != 0;
+ const int use_vert_sel = vertex_group_use_vert_sel(ob);
if (!BLI_findlink(&ob->defbase, def_nr)) {
return;
@@ -724,7 +1053,7 @@ static void vgroup_normalize(Object *ob)
dw = defvert_find_index(dv, def_nr);
if (dw) {
- weight_max = MAX2(dw->weight, weight_max);
+ weight_max = max_ff(dw->weight, weight_max);
}
}
@@ -836,23 +1165,24 @@ static void getVerticalAndHorizontalChange(const float norm[3], float d, const f
const float start[3], float distToStart,
float *end, float (*changes)[2], float *dists, int index)
{
- // A=Q-((Q-P).N)N
- // D = (a*x0 + b*y0 +c*z0 +d)
+ /* A = Q - ((Q - P).N)N
+ * D = (a * x0 + b * y0 +c * z0 + d) */
float projA[3], projB[3];
closest_to_plane_v3(projA, coord, norm, start);
closest_to_plane_v3(projB, coord, norm, end);
- // (vertical and horizontal refer to the plane's y and xz respectively)
- // vertical distance
+ /* (vertical and horizontal refer to the plane's y and xz respectively)
+ * vertical distance */
dists[index] = dot_v3v3(norm, end) + d;
- // vertical change
+ /* vertical change */
changes[index][0] = dists[index] - distToStart;
//printf("vc %f %f\n", distance(end, projB, 3)-distance(start, projA, 3), changes[index][0]);
- // horizontal change
+ /* horizontal change */
changes[index][1] = len_v3v3(projA, projB);
}
-// I need the derived mesh to be forgotten so the positions are recalculated with weight changes (see dm_deform_recalc)
+/* I need the derived mesh to be forgotten so the positions are recalculated
+ * with weight changes (see dm_deform_recalc) */
static void dm_deform_clear(DerivedMesh *dm, Object *ob)
{
if (ob->derivedDeform && (ob->derivedDeform) == dm) {
@@ -973,7 +1303,7 @@ static void moveCloserToDistanceFromPlane(Scene *scene, Object *ob, Mesh *me, in
}
}
}
- // sort the changes by the vertical change
+ /* sort the changes by the vertical change */
for (k = 0; k < totweight; k++) {
float tf;
int ti;
@@ -985,7 +1315,7 @@ static void moveCloserToDistanceFromPlane(Scene *scene, Object *ob, Mesh *me, in
bestIndex = i;
}
}
- // switch with k
+ /* switch with k */
if (bestIndex != k) {
ti = upDown[k];
upDown[k] = upDown[bestIndex];
@@ -1109,7 +1439,7 @@ static void vgroup_levels(Object *ob, float offset, float gain)
int i, dvert_tot = 0;
const int def_nr = ob->actdef - 1;
- const int use_vert_sel = (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) != 0;
+ const int use_vert_sel = vertex_group_use_vert_sel(ob);
if (!BLI_findlink(&ob->defbase, def_nr)) {
return;
@@ -1143,7 +1473,7 @@ static void vgroup_normalize_all(Object *ob, int lock_active)
int i, dvert_tot = 0;
const int def_nr = ob->actdef - 1;
- const int use_vert_sel = (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) != 0;
+ const int use_vert_sel = vertex_group_use_vert_sel(ob);
if (lock_active && !BLI_findlink(&ob->defbase, def_nr)) {
return;
@@ -1221,7 +1551,7 @@ static void vgroup_invert(Object *ob, const short auto_assign, const short auto_
MDeformVert *dv, **dvert_array = NULL;
int i, dvert_tot = 0;
const int def_nr = ob->actdef - 1;
- const int use_vert_sel = (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) != 0;
+ const int use_vert_sel = vertex_group_use_vert_sel(ob);
if (!BLI_findlink(&ob->defbase, def_nr)) {
return;
@@ -1312,11 +1642,11 @@ static void vgroup_blend(Object *ob, const float fac)
/* i1 is always the selected one */
if (sel1) {
i1 = BM_elem_index_get(eed->v1);
- /* i2= BM_elem_index_get(eed->v2); */ /* UNUSED */
+ /* i2 = BM_elem_index_get(eed->v2); */ /* UNUSED */
eve = eed->v2;
}
else {
- /* i2= BM_elem_index_get(eed->v1); */ /* UNUSED */
+ /* i2 = BM_elem_index_get(eed->v1); */ /* UNUSED */
i1 = BM_elem_index_get(eed->v2);
eve = eed->v1;
}
@@ -1389,13 +1719,119 @@ static void vgroup_blend(Object *ob, const float fac)
}
}
+static int inv_cmp_mdef_vert_weights(const void *a1, const void *a2)
+{
+ /* qsort sorts in ascending order. We want descending order to save a memcopy
+ * so this compare function is inverted from the standard greater than comparison qsort needs.
+ * A normal compare function is called with two pointer arguments and should return an integer less than, equal to,
+ * or greater than zero corresponding to whether its first argument is considered less than, equal to,
+ * or greater than its second argument. This does the opposite. */
+ const struct MDeformWeight *dw1 = a1, *dw2 = a2;
+
+ if (dw1->weight < dw2->weight) return 1;
+ else if (dw1->weight > dw2->weight) return -1;
+ else if (&dw1 < &dw2) return 1; /* compare addresses so we have a stable sort algorithm */
+ else return -1;
+}
+
+/* Used for limiting the number of influencing bones per vertex when exporting
+ * skinned meshes. if all_deform_weights is True, limit all deform modifiers
+ * to max_weights regardless of type, otherwise, only limit the number of influencing bones per vertex*/
+static int vertex_group_limit_total(Object *ob,
+ const int max_weights,
+ const int all_deform_weights)
+{
+ MDeformVert *dv, **dvert_array = NULL;
+ int i, dvert_tot = 0;
+ const int use_vert_sel = vertex_group_use_vert_sel(ob);
+ int is_change = FALSE;
+
+ ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
+
+ if (dvert_array) {
+ int defbase_tot = BLI_countlist(&ob->defbase);
+ const char *vgroup_validmap = (all_deform_weights == FALSE) ?
+ BKE_objdef_validmap_get(ob, defbase_tot) :
+ NULL;
+ int num_to_drop = 0;
+
+ /* only the active group */
+ for (i = 0; i < dvert_tot; i++) {
+
+ /* in case its not selected */
+ if (!(dv = dvert_array[i])) {
+ continue;
+ }
+
+ if (all_deform_weights) {
+ /* keep only the largest weights, discarding the rest
+ * qsort will put array in descending order because of invCompare function */
+ num_to_drop = dv->totweight - max_weights;
+ if (num_to_drop > 0) {
+ qsort(dv->dw, dv->totweight, sizeof(MDeformWeight), inv_cmp_mdef_vert_weights);
+ dv->dw = MEM_reallocN(dv->dw, sizeof(MDeformWeight) * max_weights);
+ dv->totweight = max_weights;
+ is_change = TRUE;
+ }
+ }
+ else {
+ MDeformWeight *dw_temp;
+ int bone_count = 0, non_bone_count = 0;
+ int j;
+ /* only consider vgroups with bone modifiers attached (in vgroup_validmap) */
+
+ num_to_drop = dv->totweight - max_weights;
+
+ /* first check if we even need to test further */
+ if (num_to_drop > 0) {
+ /* re-pack dw array so that non-bone weights are first, bone-weighted verts at end
+ * sort the tail, then copy only the truncated array back to dv->dw */
+ dw_temp = MEM_mallocN(sizeof(MDeformWeight) * (dv->totweight), __func__);
+ bone_count = 0; non_bone_count = 0;
+ for (j = 0; j < dv->totweight; j++) {
+ BLI_assert(dv->dw[j].def_nr < defbase_tot);
+ if (!vgroup_validmap[(dv->dw[j]).def_nr]) {
+ dw_temp[non_bone_count] = dv->dw[j];
+ non_bone_count += 1;
+ }
+ else {
+ dw_temp[dv->totweight - 1 - bone_count] = dv->dw[j];
+ bone_count += 1;
+ }
+ }
+ BLI_assert(bone_count + non_bone_count == dv->totweight);
+ num_to_drop = bone_count - max_weights;
+ if (num_to_drop > 0) {
+ qsort(&dw_temp[non_bone_count], bone_count, sizeof(MDeformWeight), inv_cmp_mdef_vert_weights);
+ dv->totweight -= num_to_drop;
+ /* Do we want to clean/normalize here? */
+ MEM_freeN(dv->dw);
+ dv->dw = MEM_reallocN(dw_temp, sizeof(MDeformWeight) * dv->totweight);
+ is_change = TRUE;
+ }
+ else {
+ MEM_freeN(dw_temp);
+ }
+ }
+ }
+ }
+ MEM_freeN(dvert_array);
+
+ if (vgroup_validmap) {
+ MEM_freeN((void *)vgroup_validmap);
+ }
+ }
+
+ return is_change;
+}
+
static void vgroup_clean(Object *ob, const float epsilon, int keep_single)
{
MDeformWeight *dw;
MDeformVert *dv, **dvert_array = NULL;
int i, dvert_tot = 0;
const int def_nr = ob->actdef - 1;
- const int use_vert_sel = (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) != 0;
+ const int use_vert_sel = vertex_group_use_vert_sel(ob);
if (!BLI_findlink(&ob->defbase, def_nr)) {
return;
@@ -1431,7 +1867,7 @@ static void vgroup_clean_all(Object *ob, const float epsilon, const int keep_sin
{
MDeformVert **dvert_array = NULL;
int i, dvert_tot = 0;
- const int use_vert_sel = (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) != 0;
+ const int use_vert_sel = vertex_group_use_vert_sel(ob);
ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
@@ -2007,7 +2443,6 @@ static void vgroup_delete_all(Object *ob)
/* only in editmode */
static void vgroup_assign_verts(Object *ob, const float weight)
{
- MDeformVert *dv;
const int def_nr = ob->actdef - 1;
if (!BLI_findlink(&ob->defbase, def_nr))
@@ -2027,6 +2462,7 @@ static void vgroup_assign_verts(Object *ob, const float weight)
/* Go through the list of editverts and assign them */
BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
+ MDeformVert *dv;
MDeformWeight *dw;
dv = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT); /* can be NULL */
dw = defvert_verify_index(dv, def_nr);
@@ -2061,6 +2497,7 @@ static void vgroup_assign_verts(Object *ob, const float weight)
}
else if (ob->type == OB_LATTICE) {
Lattice *lt = vgroup_edit_lattice(ob);
+ MDeformVert *dv;
BPoint *bp;
int a, tot;
@@ -2665,6 +3102,47 @@ void OBJECT_OT_vertex_group_clean(wmOperatorType *ot)
"Keep verts assigned to at least one group when cleaning");
}
+static int vertex_group_limit_total_exec(bContext *C, wmOperator *op)
+{
+ Object *ob = ED_object_context(C);
+
+ const int limit = RNA_int_get(op->ptr, "limit");
+ const int all_deform_weights = RNA_boolean_get(op->ptr, "all_deform_weights");
+
+ if (vertex_group_limit_total(ob, limit, all_deform_weights)) {
+
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
+
+ return OPERATOR_FINISHED;
+ }
+ else {
+ BKE_report(op->reports, RPT_WARNING, "No vertex groups limited");
+
+ /* note, would normally return cancelled, except we want the redo
+ * UI to show up for users to change */
+ return OPERATOR_FINISHED;
+ }
+}
+
+void OBJECT_OT_vertex_group_limit_total(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Limit Number of Weights per Vertex";
+ ot->idname = "OBJECT_OT_vertex_group_limit_total";
+ ot->description = "Limit deform weights associated with a vertex to a specified number by removing lowest weights";
+
+ /* api callbacks */
+ ot->poll = vertex_group_poll;
+ ot->exec = vertex_group_limit_total_exec;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ RNA_def_int(ot->srna, "limit", 4, 1, 32, "Limit", "Maximum number of deform weights", 1, 32);
+ RNA_def_boolean(ot->srna, "all_deform_weights", FALSE, "All Deform Weights", "Cull all deform weights, not just bones");
+}
static int vertex_group_mirror_exec(bContext *C, wmOperator *op)
{
@@ -2762,14 +3240,13 @@ static int vertex_group_copy_to_selected_exec(bContext *C, wmOperator *op)
if ((change == 0 && fail == 0) || fail) {
BKE_reportf(op->reports, RPT_ERROR,
- "Copy to VGroups to Selected warning done %d, failed %d, object data must have matching indices",
+ "Copy VGroups to Selected warning, %d done, %d failed (object data must have matching indices)",
change, fail);
}
return OPERATOR_FINISHED;
}
-
void OBJECT_OT_vertex_group_copy_to_selected(wmOperatorType *ot)
{
/* identifiers */
@@ -2785,6 +3262,86 @@ void OBJECT_OT_vertex_group_copy_to_selected(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+static int vertex_group_transfer_weight_exec(bContext *C, wmOperator *op)
+{
+ Scene *scene = CTX_data_scene(C);
+ Object *ob_act = CTX_data_active_object(C);
+ bDeformGroup *dg_src;
+ int fail = 0;
+
+ WT_VertexGroupMode vertex_group_mode = RNA_enum_get(op->ptr, "WT_vertex_group_mode");
+ WT_Method method = RNA_enum_get(op->ptr, "WT_method");
+ WT_ReplaceMode replace_mode = RNA_enum_get(op->ptr, "WT_replace_mode");
+
+ /* Macro to loop through selected objects and perform operation depending on function, option and method */
+ CTX_DATA_BEGIN (C, Object *, ob_slc, selected_editable_objects)
+ {
+
+ if (ob_act != ob_slc && ob_slc->defbase.first) {
+ switch (vertex_group_mode) {
+
+ case WT_REPLACE_ACTIVE_VERTEX_GROUP:
+ if (!ed_vgroup_transfer_weight(ob_act, ob_slc,
+ BLI_findlink(&ob_slc->defbase, ob_slc->actdef - 1),
+ scene, method, replace_mode, op))
+ {
+ fail++;
+ }
+ break;
+
+ case WT_REPLACE_ALL_VERTEX_GROUPS:
+ for (dg_src = ob_slc->defbase.first; dg_src; dg_src = dg_src->next) {
+ if (!ed_vgroup_transfer_weight(ob_act, ob_slc,
+ dg_src, scene, method, replace_mode, op))
+ {
+ fail++;
+ }
+ }
+ break;
+
+ default:
+ BLI_assert(0);
+ break;
+ }
+ }
+ }
+
+ /* Event notifiers for correct display of data */
+ DAG_id_tag_update(&ob_slc->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob_slc);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob_slc->data);
+
+ CTX_DATA_END;
+
+ if (fail != 0) {
+ return OPERATOR_CANCELLED;
+ }
+ else {
+ return OPERATOR_FINISHED;
+ }
+}
+
+/* transfers weight from active to selected */
+void OBJECT_OT_vertex_group_transfer_weight(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Transfer Weights";
+ ot->idname = "OBJECT_OT_vertex_group_transfer_weight";
+ ot->description = "Transfer weight paint to active from selected mesh";
+
+ /* api callbacks */
+ ot->poll = vertex_group_poll;
+ ot->exec = vertex_group_transfer_weight_exec;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
+ ot->prop = RNA_def_enum(ot->srna, "WT_vertex_group_mode", WT_vertex_group_mode_item, 1, "Group", "");
+ ot->prop = RNA_def_enum(ot->srna, "WT_method", WT_method_item, 3, "Method", "");
+ ot->prop = RNA_def_enum(ot->srna, "WT_replace_mode", WT_replace_mode_item, 1, "Replace", "");
+}
+
static EnumPropertyItem vgroup_items[] = {
{0, NULL, 0, NULL, NULL}
};
@@ -2904,7 +3461,7 @@ static int vgroup_do_remap(Object *ob, char *name_array, wmOperator *op)
}
}
else {
- BKE_report(op->reports, RPT_ERROR, "Editmode lattice isn't supported yet");
+ BKE_report(op->reports, RPT_ERROR, "Editmode lattice is not supported yet");
MEM_freeN(sort_map_update);
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/physics/CMakeLists.txt b/source/blender/editors/physics/CMakeLists.txt
index 4d43c618568..da12a26e747 100644
--- a/source/blender/editors/physics/CMakeLists.txt
+++ b/source/blender/editors/physics/CMakeLists.txt
@@ -20,6 +20,7 @@
set(INC
../include
+ ../../blenfont
../../blenkernel
../../blenlib
../../blenloader
@@ -54,4 +55,8 @@ if(WITH_OPENMP)
add_definitions(-DPARALLEL=1)
endif()
+if(WITH_INTERNATIONAL)
+ add_definitions(-DWITH_INTERNATIONAL)
+endif()
+
blender_add_lib(bf_editor_physics "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/editors/physics/SConscript b/source/blender/editors/physics/SConscript
index 9fe6cff4349..fffe05d6a0d 100644
--- a/source/blender/editors/physics/SConscript
+++ b/source/blender/editors/physics/SConscript
@@ -3,12 +3,12 @@ Import ('env')
sources = env.Glob('*.c')
-incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
+incs = '../include ../../blenfont ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
incs += ' ../../windowmanager #/intern/guardedalloc #/extern/glew/include'
incs += ' ../../gpu ../../blenloader ../../bmesh'
incs += ' ../../makesrna ../../render/extern/include #/intern/elbeem/extern'
-defs = ''
+defs = []
if env['OURPLATFORM'] == 'linux':
cflags='-pthread'
@@ -17,9 +17,11 @@ if env['OURPLATFORM'] == 'linux':
if env['OURPLATFORM'] in ('win32-vc', 'win32-mingw', 'linuxcross', 'win64-vc', 'win64-mingw'):
incs += ' ' + env['BF_PTHREADS_INC']
-
if env['OURPLATFORM'] == 'darwin':
if env['WITH_BF_OPENMP']:
- defs += ' PARALLEL=1'
+ defs.append('PARALLEL=1')
+
+if env['WITH_BF_INTERNATIONAL']:
+ defs.append('WITH_INTERNATIONAL')
-env.BlenderLib ( 'bf_editors_physics', sources, Split(incs), Split(defs), libtype=['core'], priority=[45] )
+env.BlenderLib ( 'bf_editors_physics', sources, Split(incs), defs, libtype=['core'], priority=[45] )
diff --git a/source/blender/editors/physics/dynamicpaint_ops.c b/source/blender/editors/physics/dynamicpaint_ops.c
index 70fe87e5c01..c51b3ca4c43 100644
--- a/source/blender/editors/physics/dynamicpaint_ops.c
+++ b/source/blender/editors/physics/dynamicpaint_ops.c
@@ -26,6 +26,8 @@
#include "BLI_string.h"
#include "BLI_utildefines.h"
+#include "BLF_translation.h"
+
#include "DNA_dynamicpaint_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
@@ -73,9 +75,9 @@ static int surface_slot_add_exec(bContext *C, wmOperator *UNUSED(op))
/* set preview for this surface only and set active */
canvas->active_sur = 0;
- for (surface=surface->prev; surface; surface=surface->prev) {
- surface->flags &= ~MOD_DPAINT_PREVIEW;
- canvas->active_sur++;
+ for (surface = surface->prev; surface; surface = surface->prev) {
+ surface->flags &= ~MOD_DPAINT_PREVIEW;
+ canvas->active_sur++;
}
return OPERATOR_FINISHED;
@@ -94,26 +96,26 @@ void DPAINT_OT_surface_slot_add(wmOperatorType *ot)
ot->poll = ED_operator_object_active_editable;
/* flags */
- ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
static int surface_slot_remove_exec(bContext *C, wmOperator *UNUSED(op))
{
DynamicPaintModifierData *pmd = NULL;
- Object *cObject = ED_object_context(C);
+ Object *obj_ctx = ED_object_context(C);
DynamicPaintCanvasSettings *canvas;
DynamicPaintSurface *surface;
- int id=0;
+ int id = 0;
/* Make sure we're dealing with a canvas */
- pmd = (DynamicPaintModifierData *)modifiers_findByType(cObject, eModifierType_DynamicPaint);
+ pmd = (DynamicPaintModifierData *)modifiers_findByType(obj_ctx, eModifierType_DynamicPaint);
if (!pmd || !pmd->canvas) return OPERATOR_CANCELLED;
canvas = pmd->canvas;
surface = canvas->surfaces.first;
/* find active surface and remove it */
- for (; surface; surface=surface->next) {
+ for (; surface; surface = surface->next) {
if (id == canvas->active_sur) {
canvas->active_sur -= 1;
dynamicPaint_freeSurface(surface);
@@ -123,8 +125,8 @@ static int surface_slot_remove_exec(bContext *C, wmOperator *UNUSED(op))
}
dynamicPaint_resetPreview(canvas);
- DAG_id_tag_update(&cObject->id, OB_RECALC_DATA);
- WM_event_add_notifier(C, NC_OBJECT|ND_MODIFIER, cObject);
+ DAG_id_tag_update(&obj_ctx->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, obj_ctx);
return OPERATOR_FINISHED;
}
@@ -142,7 +144,7 @@ void DPAINT_OT_surface_slot_remove(wmOperatorType *ot)
ot->poll = ED_operator_object_active_editable;
/* flags */
- ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
static int type_toggle_exec(bContext *C, wmOperator *op)
@@ -151,7 +153,7 @@ static int type_toggle_exec(bContext *C, wmOperator *op)
Object *cObject = ED_object_context(C);
Scene *scene = CTX_data_scene(C);
DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)modifiers_findByType(cObject, eModifierType_DynamicPaint);
- int type= RNA_enum_get(op->ptr, "type");
+ int type = RNA_enum_get(op->ptr, "type");
if (!pmd) return OPERATOR_CANCELLED;
@@ -170,7 +172,7 @@ static int type_toggle_exec(bContext *C, wmOperator *op)
/* update dependency */
DAG_id_tag_update(&cObject->id, OB_RECALC_DATA);
- WM_event_add_notifier(C, NC_OBJECT|ND_MODIFIER, cObject);
+ WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, cObject);
DAG_scene_sort(CTX_data_main(C), scene);
return OPERATOR_FINISHED;
@@ -190,10 +192,10 @@ void DPAINT_OT_type_toggle(wmOperatorType *ot)
ot->poll = ED_operator_object_active_editable;
/* flags */
- ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
- prop= RNA_def_enum(ot->srna, "type", prop_dynamicpaint_type_items, MOD_DYNAMICPAINT_TYPE_CANVAS, "Type", "");
+ prop = RNA_def_enum(ot->srna, "type", prop_dynamicpaint_type_items, MOD_DYNAMICPAINT_TYPE_CANVAS, "Type", "");
ot->prop = prop;
}
@@ -203,7 +205,7 @@ static int output_toggle_exec(bContext *C, wmOperator *op)
Scene *scene = CTX_data_scene(C);
DynamicPaintSurface *surface;
DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)modifiers_findByType(ob, eModifierType_DynamicPaint);
- int output= RNA_enum_get(op->ptr, "output"); /* currently only 1/0 */
+ int output = RNA_enum_get(op->ptr, "output"); /* currently only 1/0 */
if (!pmd || !pmd->canvas) return OPERATOR_CANCELLED;
surface = get_activeSurface(pmd->canvas);
@@ -258,7 +260,7 @@ void DPAINT_OT_output_toggle(wmOperatorType *ot)
ot->poll = ED_operator_object_active_editable;
/* flags */
- ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
ot->prop = RNA_def_enum(ot->srna, "output", prop_output_toggle_types, 0, "Output Toggle", "");
@@ -274,13 +276,16 @@ void DPAINT_OT_output_toggle(wmOperatorType *ot)
static int dynamicPaint_bakeImageSequence(bContext *C, DynamicPaintSurface *surface, Object *cObject)
{
DynamicPaintCanvasSettings *canvas = surface->canvas;
- Scene *scene= CTX_data_scene(C);
+ Scene *scene = CTX_data_scene(C);
wmWindow *win = CTX_wm_window(C);
int frame = 1;
int frames;
frames = surface->end_frame - surface->start_frame + 1;
- if (frames <= 0) {BLI_strncpy(canvas->error, "No frames to bake.", sizeof(canvas->error)); return 0;}
+ if (frames <= 0) {
+ BLI_strncpy(canvas->error, N_("No frames to bake"), sizeof(canvas->error));
+ return 0;
+ }
/* Set frame to start point (also inits modifier data) */
frame = surface->start_frame;
@@ -291,7 +296,7 @@ static int dynamicPaint_bakeImageSequence(bContext *C, DynamicPaintSurface *surf
if (!dynamicPaint_createUVSurface(surface)) return 0;
/* Loop through selected frames */
- for (frame=surface->start_frame; frame<=surface->end_frame; frame++) {
+ for (frame = surface->start_frame; frame <= surface->end_frame; frame++) {
float progress = (frame - surface->start_frame) / (float)frames * 100;
surface->current_frame = frame;
@@ -346,7 +351,6 @@ static int dynamicPaint_initBake(struct bContext *C, struct wmOperator *op)
Object *ob = ED_object_context(C);
int status = 0;
double timer = PIL_check_seconds_timer();
- char result_str[80];
DynamicPaintSurface *surface;
/*
@@ -354,14 +358,14 @@ static int dynamicPaint_initBake(struct bContext *C, struct wmOperator *op)
*/
pmd = (DynamicPaintModifierData *)modifiers_findByType(ob, eModifierType_DynamicPaint);
if (!pmd) {
- BKE_report(op->reports, RPT_ERROR, "Bake Failed: No Dynamic Paint modifier found.");
+ BKE_report(op->reports, RPT_ERROR, "Bake failed: no Dynamic Paint modifier found");
return 0;
}
/* Make sure we're dealing with a canvas */
canvas = pmd->canvas;
if (!canvas) {
- BKE_report(op->reports, RPT_ERROR, "Bake Failed: Invalid Canvas.");
+ BKE_report(op->reports, RPT_ERROR, "Bake failed: invalid canvas");
return 0;
}
surface = get_activeSurface(canvas);
@@ -381,23 +385,20 @@ static int dynamicPaint_initBake(struct bContext *C, struct wmOperator *op)
/* Bake was successful:
* Report for ended bake and how long it took */
if (status) {
- /* Format time string */
+ /* Format time string */
char time_str[30];
double time = PIL_check_seconds_timer() - timer;
BLI_timestr(time, time_str);
/* Show bake info */
- BLI_snprintf(result_str, sizeof(result_str), "Bake Complete! (%s)", time_str);
- BKE_report(op->reports, RPT_INFO, result_str);
+ BKE_reportf(op->reports, RPT_INFO, "Bake complete! (%s)", time_str);
}
else {
- if (strlen(canvas->error)) { /* If an error occured */
- BLI_snprintf(result_str, sizeof(result_str), "Bake Failed: %s", canvas->error);
- BKE_report(op->reports, RPT_ERROR, result_str);
+ if (strlen(canvas->error)) { /* If an error occurred */
+ BKE_reportf(op->reports, RPT_ERROR, "Bake failed: %s", canvas->error);
}
- else { /* User canceled the bake */
- BLI_strncpy(result_str, "Baking Cancelled!", sizeof(result_str));
- BKE_report(op->reports, RPT_WARNING, result_str);
+ else { /* User canceled the bake */
+ BKE_report(op->reports, RPT_WARNING, "Baking canceled!");
}
}
diff --git a/source/blender/editors/physics/particle_boids.c b/source/blender/editors/physics/particle_boids.c
index aff66b272fe..dc309ec3c31 100644
--- a/source/blender/editors/physics/particle_boids.c
+++ b/source/blender/editors/physics/particle_boids.c
@@ -273,7 +273,7 @@ static int state_del_exec(bContext *C, wmOperator *UNUSED(op))
/* there must be at least one state */
if (!part->boids->states.first) {
state = boid_new_state(part->boids);
- BLI_addtail(&part->boids->states, state);
+ BLI_addtail(&part->boids->states, state);
}
else
state = part->boids->states.first;
diff --git a/source/blender/editors/physics/particle_edit.c b/source/blender/editors/physics/particle_edit.c
index b7ce32aa10a..f8ec51c7a7c 100644
--- a/source/blender/editors/physics/particle_edit.c
+++ b/source/blender/editors/physics/particle_edit.c
@@ -328,7 +328,7 @@ void PE_hide_keys_time(Scene *scene, PTCacheEdit *edit, float cfra)
static int pe_x_mirror(Object *ob)
{
if (ob->type == OB_MESH)
- return (((Mesh*)ob->data)->editflag & ME_EDIT_MIRROR_X);
+ return (((Mesh *)ob->data)->editflag & ME_EDIT_MIRROR_X);
return 0;
}
@@ -398,41 +398,41 @@ static void PE_set_view3d_data(bContext *C, PEData *data)
/*************************** selection utilities *******************************/
-static int key_test_depth(PEData *data, const float co[3])
+static int key_test_depth(PEData *data, const float co[3], const int screen_co[2])
{
View3D *v3d= data->vc.v3d;
double ux, uy, uz;
float depth;
- short wco[3], x, y;
/* nothing to do */
if ((v3d->drawtype<=OB_WIRE) || (v3d->flag & V3D_ZBUF_SELECT)==0)
return 1;
- project_short(data->vc.ar, co, wco);
-
- if (wco[0] == IS_CLIPPED)
+ /* used to calculate here but all callers have the screen_co already, so pass as arg */
+#if 0
+ if (ED_view3d_project_int_global(data->vc.ar, co, screen_co,
+ V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN) != V3D_PROJ_RET_OK)
+ {
return 0;
+ }
+#endif
gluProject(co[0], co[1], co[2], data->mats.modelview, data->mats.projection,
(GLint *)data->mats.viewport, &ux, &uy, &uz);
- x=wco[0];
- y=wco[1];
-
#if 0 /* works well but too slow on some systems [#23118] */
- x+= (short)data->vc.ar->winrct.xmin;
- y+= (short)data->vc.ar->winrct.ymin;
+ screen_co[0] += (short)data->vc.ar->winrct.xmin;
+ screen_co[1] += (short)data->vc.ar->winrct.ymin;
/* PE_set_view3d_data calls this. no need to call here */
/* view3d_validate_backbuf(&data->vc); */
- glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
+ glReadPixels(screen_co[0], screen_co[1], 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
#else /* faster to use depths, these are calculated in PE_set_view3d_data */
{
ViewDepths *vd = data->vc.rv3d->depths;
assert(vd && vd->depths);
/* we know its not clipped */
- depth= vd->depths[y * vd->w + x];
+ depth = vd->depths[screen_co[1] * vd->w + screen_co[0]];
}
#endif
@@ -445,21 +445,21 @@ static int key_test_depth(PEData *data, const float co[3])
static int key_inside_circle(PEData *data, float rad, const float co[3], float *distance)
{
float dx, dy, dist;
- int sco[2];
+ int screen_co[2];
- project_int(data->vc.ar, co, sco);
-
- if (sco[0] == IS_CLIPPED)
+ /* TODO, should this check V3D_PROJ_TEST_CLIP_BB too? */
+ if (ED_view3d_project_int_global(data->vc.ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) != V3D_PROJ_RET_OK) {
return 0;
-
- dx= data->mval[0] - sco[0];
- dy= data->mval[1] - sco[1];
+ }
+
+ dx= data->mval[0] - screen_co[0];
+ dy= data->mval[1] - screen_co[1];
dist= sqrt(dx*dx + dy*dy);
if (dist > rad)
return 0;
- if (key_test_depth(data, co)) {
+ if (key_test_depth(data, co, screen_co)) {
if (distance)
*distance=dist;
@@ -471,17 +471,16 @@ static int key_inside_circle(PEData *data, float rad, const float co[3], float *
static int key_inside_rect(PEData *data, const float co[3])
{
- int sco[2];
-
- project_int(data->vc.ar, co, sco);
+ int screen_co[2];
- if (sco[0] == IS_CLIPPED)
+ if (ED_view3d_project_int_global(data->vc.ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) != V3D_PROJ_RET_OK) {
return 0;
+ }
- if (sco[0] > data->rect->xmin && sco[0] < data->rect->xmax &&
- sco[1] > data->rect->ymin && sco[1] < data->rect->ymax)
+ if (screen_co[0] > data->rect->xmin && screen_co[0] < data->rect->xmax &&
+ screen_co[1] > data->rect->ymin && screen_co[1] < data->rect->ymax)
{
- return key_test_depth(data, co);
+ return key_test_depth(data, co, screen_co);
}
return 0;
@@ -604,7 +603,7 @@ static void foreach_mouse_hit_key(PEData *data, ForKeyMatFunc func, int selected
ParticleSystemModifierData *psmd = NULL;
ParticleEditSettings *pset= PE_settings(data->scene);
POINT_P; KEY_K;
- float mat[4][4]= MAT4_UNITY, imat[4][4]= MAT4_UNITY;
+ float mat[4][4] = MAT4_UNITY, imat[4][4] = MAT4_UNITY;
if (edit->psys)
psmd= psys_get_modifier(data->ob, edit->psys);
@@ -674,7 +673,7 @@ static void foreach_point(PEData *data, ForPointFunc func)
PTCacheEdit *edit = data->edit;
POINT_P;
- LOOP_POINTS {
+ LOOP_POINTS {
func(data, p);
}
}
@@ -745,15 +744,15 @@ static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys)
psys_mat_hair_to_orco(ob, psmd->dm, psys->part->from, pa, mat);
copy_v3_v3(co, key->co);
mul_m4_v3(mat, co);
- co[0]= -co[0];
+ co[0] = -co[0];
index= BLI_kdtree_find_nearest(tree, co, NULL, &nearest);
/* this needs a custom threshold still, duplicated for editmode mirror */
if (index != -1 && index != p && (nearest.dist <= 0.0002f))
- edit->mirror_cache[p]= index;
+ edit->mirror_cache[p] = index;
else
- edit->mirror_cache[p]= -1;
+ edit->mirror_cache[p] = -1;
}
/* make sure mirrors are in two directions */
@@ -761,7 +760,7 @@ static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys)
if (edit->mirror_cache[p]) {
index= edit->mirror_cache[p];
if (edit->mirror_cache[index] != p)
- edit->mirror_cache[p]= -1;
+ edit->mirror_cache[p] = -1;
}
}
@@ -830,7 +829,7 @@ static void PE_mirror_particle(Object *ob, DerivedMesh *dm, ParticleSystem *psys
for (k=0; k<pa->totkey; k++, hkey++, mhkey++, key++, mkey++) {
copy_v3_v3(mhkey->co, hkey->co);
mul_m4_v3(mat, mhkey->co);
- mhkey->co[0]= -mhkey->co[0];
+ mhkey->co[0] = -mhkey->co[0];
mul_m4_v3(immat, mhkey->co);
if (key->flag & PEK_TAG)
@@ -987,9 +986,9 @@ static void pe_iterate_lengths(Scene *scene, PTCacheEdit *edit)
PTCacheEditKey *key;
int j, k;
float tlen;
- float dv0[3]= {0.0f, 0.0f, 0.0f};
- float dv1[3]= {0.0f, 0.0f, 0.0f};
- float dv2[3]= {0.0f, 0.0f, 0.0f};
+ float dv0[3] = {0.0f, 0.0f, 0.0f};
+ float dv1[3] = {0.0f, 0.0f, 0.0f};
+ float dv2[3] = {0.0f, 0.0f, 0.0f};
if (edit==0 || (pset->flag & PE_KEEP_LENGTHS)==0)
return;
@@ -1004,12 +1003,12 @@ static void pe_iterate_lengths(Scene *scene, PTCacheEdit *edit)
if (pset->flag & PE_LOCK_FIRST) {
key= point->keys + 1;
k= 1;
- dv1[0]= dv1[1]= dv1[2]= 0.0;
+ dv1[0] = dv1[1] = dv1[2] = 0.0;
}
else {
key= point->keys;
k= 0;
- dv0[0]= dv0[1]= dv0[2]= 0.0;
+ dv0[0] = dv0[1] = dv0[2] = 0.0;
}
for (; k<point->totkey; k++, key++) {
@@ -1528,8 +1527,8 @@ static int select_linked_exec(bContext *C, wmOperator *op)
int location[2];
RNA_int_get_array(op->ptr, "location", location);
- mval[0]= location[0];
- mval[1]= location[1];
+ mval[0] = location[0];
+ mval[1] = location[1];
PE_set_view3d_data(C, &data);
data.mval= mval;
@@ -1634,7 +1633,7 @@ int PE_circle_select(bContext *C, int selecting, const int mval[2], float rad)
/************************ lasso select operator ************************/
-int PE_lasso_select(bContext *C, int mcords[][2], short moves, short extend, short select)
+int PE_lasso_select(bContext *C, const int mcords[][2], const short moves, short extend, short select)
{
Scene *scene= CTX_data_scene(C);
Object *ob= CTX_data_active_object(C);
@@ -1644,8 +1643,8 @@ int PE_lasso_select(bContext *C, int mcords[][2], short moves, short extend, sho
ParticleSystem *psys = edit->psys;
ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
POINT_P; KEY_K;
- float co[3], mat[4][4]= MAT4_UNITY;
- int vertco[2];
+ float co[3], mat[4][4] = MAT4_UNITY;
+ int screen_co[2];
PEData data;
@@ -1666,9 +1665,9 @@ int PE_lasso_select(bContext *C, int mcords[][2], short moves, short extend, sho
LOOP_KEYS {
copy_v3_v3(co, key->co);
mul_m4_v3(mat, co);
- project_int(ar, co, vertco);
- if (BLI_lasso_is_point_inside(mcords, moves, vertco[0], vertco[1], IS_CLIPPED) &&
- key_test_depth(&data, co))
+ if ((ED_view3d_project_int_global(ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) == V3D_PROJ_RET_OK) &&
+ BLI_lasso_is_point_inside(mcords, moves, screen_co[0], screen_co[1], IS_CLIPPED) &&
+ key_test_depth(&data, co, screen_co))
{
if (select && !(key->flag & PEK_SELECT)) {
key->flag |= PEK_SELECT;
@@ -1686,9 +1685,9 @@ int PE_lasso_select(bContext *C, int mcords[][2], short moves, short extend, sho
copy_v3_v3(co, key->co);
mul_m4_v3(mat, co);
- project_int(ar, co, vertco);
- if (BLI_lasso_is_point_inside(mcords, moves, vertco[0], vertco[1], IS_CLIPPED) &&
- key_test_depth(&data, co))
+ if ((ED_view3d_project_int_global(ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) == V3D_PROJ_RET_OK) &&
+ BLI_lasso_is_point_inside(mcords, moves, screen_co[0], screen_co[1], IS_CLIPPED) &&
+ key_test_depth(&data, co, screen_co))
{
if (select && !(key->flag & PEK_SELECT)) {
key->flag |= PEK_SELECT;
@@ -2415,7 +2414,7 @@ static int remove_doubles_exec(bContext *C, wmOperator *op)
if (totremoved == 0)
return OPERATOR_CANCELLED;
- BKE_reportf(op->reports, RPT_INFO, "Remove %d double particles", totremoved);
+ BKE_reportf(op->reports, RPT_INFO, "Removed %d double particles", totremoved);
DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob);
@@ -2536,7 +2535,7 @@ static void toggle_particle_cursor(bContext *C, int enable)
enum { DEL_PARTICLE, DEL_KEY };
-static EnumPropertyItem delete_type_items[]= {
+static EnumPropertyItem delete_type_items[] = {
{DEL_PARTICLE, "PARTICLE", 0, "Particle", ""},
{DEL_KEY, "KEY", 0, "Key", ""},
{0, NULL, 0, NULL, NULL}};
@@ -2602,7 +2601,7 @@ void PARTICLE_OT_delete(wmOperatorType *ot)
static void PE_mirror_x(Scene *scene, Object *ob, int tagged)
{
- Mesh *me= (Mesh*)(ob->data);
+ Mesh *me= (Mesh *)(ob->data);
ParticleSystemModifierData *psmd;
PTCacheEdit *edit= PE_get_current(scene, ob);
ParticleSystem *psys = edit->psys;
@@ -2692,10 +2691,10 @@ static void PE_mirror_x(Scene *scene, Object *ob, int tagged)
/* rotate weights according to vertex index rotation */
rotation= mirrorfaces[pa->num*2+1];
- newpa->fuv[0]= pa->fuv[2];
- newpa->fuv[1]= pa->fuv[1];
- newpa->fuv[2]= pa->fuv[0];
- newpa->fuv[3]= pa->fuv[3];
+ newpa->fuv[0] = pa->fuv[2];
+ newpa->fuv[1] = pa->fuv[1];
+ newpa->fuv[2] = pa->fuv[0];
+ newpa->fuv[3] = pa->fuv[3];
while (rotation-- > 0)
if (me->mface[pa->num].v4) {
SHIFT4(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2], newpa->fuv[3]);
@@ -2789,7 +2788,7 @@ static void brush_cut(PEData *data, int pa_index)
float rad2, cut_time= 1.0;
float x0, x1, v0, v1, o0, o1, xo0, xo1, d, dv;
int k, cut, keys= (int)pow(2.0, (double)pset->draw_step);
- int vertco[2];
+ int screen_co[2];
/* blunt scissors */
if (BLI_frand() > data->cutfac) return;
@@ -2798,13 +2797,15 @@ static void brush_cut(PEData *data, int pa_index)
if (edit->points[pa_index].flag & PEP_HIDE)
return;
+ if (ED_view3d_project_int_global(ar, key->co, screen_co, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK)
+ return;
+
rad2= data->rad * data->rad;
cut=0;
- project_int_noclip(ar, key->co, vertco);
- x0= (float)vertco[0];
- x1= (float)vertco[1];
+ x0 = (float)screen_co[0];
+ x1 = (float)screen_co[1];
o0= (float)data->mval[0];
o1= (float)data->mval[1];
@@ -2813,26 +2814,27 @@ static void brush_cut(PEData *data, int pa_index)
xo1= x1 - o1;
/* check if root is inside circle */
- if (xo0*xo0 + xo1*xo1 < rad2 && key_test_depth(data, key->co)) {
+ if (xo0*xo0 + xo1*xo1 < rad2 && key_test_depth(data, key->co, screen_co)) {
cut_time= -1.0f;
cut= 1;
}
else {
/* calculate path time closest to root that was inside the circle */
for (k=1, key++; k<=keys; k++, key++) {
- project_int_noclip(ar, key->co, vertco);
- if (key_test_depth(data, key->co) == 0) {
- x0= (float)vertco[0];
- x1= (float)vertco[1];
+ if ((ED_view3d_project_int_global(ar, key->co, screen_co, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) ||
+ key_test_depth(data, key->co, screen_co) == 0)
+ {
+ x0 = (float)screen_co[0];
+ x1 = (float)screen_co[1];
xo0= x0 - o0;
xo1= x1 - o1;
continue;
}
- v0= (float)vertco[0] - x0;
- v1= (float)vertco[1] - x1;
+ v0 = (float)screen_co[0] - x0;
+ v1 = (float)screen_co[1] - x1;
dv= v0*v0 + v1*v1;
@@ -2857,8 +2859,8 @@ static void brush_cut(PEData *data, int pa_index)
}
}
- x0= (float)vertco[0];
- x1= (float)vertco[1];
+ x0 = (float)screen_co[0];
+ x1 = (float)screen_co[1];
xo0= x0 - o0;
xo1= x1 - o1;
@@ -3086,9 +3088,9 @@ static void intersect_dm_quad_weights(const float v1[3], const float v2[3], cons
copy_v3_v3(vert[2], v3);
copy_v3_v3(vert[3], v4);
- co[0]= v1[0]*w[0] + v2[0]*w[1] + v3[0]*w[2] + v4[0]*w[3];
- co[1]= v1[1]*w[0] + v2[1]*w[1] + v3[1]*w[2] + v4[1]*w[3];
- co[2]= v1[2]*w[0] + v2[2]*w[1] + v3[2]*w[2] + v4[2]*w[3];
+ co[0] = v1[0]*w[0] + v2[0]*w[1] + v3[0]*w[2] + v4[0]*w[3];
+ co[1] = v1[1]*w[0] + v2[1]*w[1] + v3[1]*w[2] + v4[1]*w[3];
+ co[2] = v1[2]*w[0] + v2[2]*w[1] + v3[2]*w[2] + v4[2]*w[3];
interp_weights_poly_v3(w, vert, 4, co);
}
@@ -3196,10 +3198,10 @@ static int particle_intersect_dm(Scene *scene, Object *ob, DerivedMesh *dm,
if (isect_line_tri_v3(co1, co2, v1, v2, v3, &cur_d, cur_uv)) {
if (cur_d<*min_d) {
*min_d=cur_d;
- min_w[0]= 1.0f - cur_uv[0] - cur_uv[1];
- min_w[1]= cur_uv[0];
- min_w[2]= cur_uv[1];
- min_w[3]= 0.0f;
+ min_w[0] = 1.0f - cur_uv[0] - cur_uv[1];
+ min_w[1] = cur_uv[0];
+ min_w[2] = cur_uv[1];
+ min_w[3] = 0.0f;
if (mface->v4)
intersect_dm_quad_weights(v1, v2, v3, v4, min_w);
*min_face=i;
@@ -3210,10 +3212,10 @@ static int particle_intersect_dm(Scene *scene, Object *ob, DerivedMesh *dm,
if (isect_line_tri_v3(co1, co2, v1, v3, v4, &cur_d, cur_uv)) {
if (cur_d<*min_d) {
*min_d=cur_d;
- min_w[0]= 1.0f - cur_uv[0] - cur_uv[1];
- min_w[1]= 0.0f;
- min_w[2]= cur_uv[0];
- min_w[3]= cur_uv[1];
+ min_w[0] = 1.0f - cur_uv[0] - cur_uv[1];
+ min_w[1] = 0.0f;
+ min_w[2] = cur_uv[0];
+ min_w[3] = cur_uv[1];
intersect_dm_quad_weights(v1, v2, v3, v4, min_w);
*min_face=i;
intersect=1;
@@ -3272,8 +3274,8 @@ static int brush_add(PEData *data, short number)
}
}
- mco[0]= data->mval[0] + dmx;
- mco[1]= data->mval[1] + dmy;
+ mco[0] = data->mval[0] + dmx;
+ mco[1] = data->mval[1] + dmy;
ED_view3d_win_to_segment_clip(data->vc.ar, data->vc.v3d, mco, co1, co2);
mul_m4_v3(imat, co1);
@@ -3366,11 +3368,11 @@ static int brush_add(PEData *data, short number)
maxd= ptn[maxw-1].dist;
for (w=0; w<maxw; w++) {
- weight[w]= (float)pow(2.0, (double)(-6.0f * ptn[w].dist / maxd));
+ weight[w] = (float)pow(2.0, (double)(-6.0f * ptn[w].dist / maxd));
totw += weight[w];
}
for (;w<3; w++) {
- weight[w]= 0.0f;
+ weight[w] = 0.0f;
}
for (w=0; w<maxw; w++)
@@ -3379,7 +3381,7 @@ static int brush_add(PEData *data, short number)
ppa= psys->particles+ptn[0].index;
for (k=0; k<pset->totaddkey; k++) {
- thkey= (HairKey*)pa->hair + k;
+ thkey= (HairKey *)pa->hair + k;
thkey->time= pa->time + k * framestep;
key3[0].time= thkey->time/ 100.0f;
@@ -3504,15 +3506,15 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr)
flip= RNA_boolean_get(itemptr, "pen_flip");
if (bedit->first) {
- bedit->lastmouse[0]= mouse[0];
- bedit->lastmouse[1]= mouse[1];
+ bedit->lastmouse[0] = mouse[0];
+ bedit->lastmouse[1] = mouse[1];
}
dx= mouse[0] - bedit->lastmouse[0];
dy= mouse[1] - bedit->lastmouse[1];
- mval[0]= mouse[0];
- mval[1]= mouse[1];
+ mval[0] = mouse[0];
+ mval[1] = mouse[1];
/* disable locking temporatily for disconnected hair */
@@ -3527,7 +3529,7 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr)
view3d_operator_needs_opengl(C);
selected= (short)count_selected_keys(scene, edit);
- dmax = maxf(fabsf(dx), fabsf(dy));
+ dmax = max_ff(fabsf(dx), fabsf(dy));
tot_steps = dmax/(0.2f * brush->size) + 1;
dx /= (float)tot_steps;
@@ -3637,7 +3639,7 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr)
data.mval= mval;
data.rad= (float)brush->size;
- data.vec[0]= data.vec[1]= data.vec[2]= 0.0f;
+ data.vec[0] = data.vec[1] = data.vec[2] = 0.0f;
data.tot= 0;
data.smoothfac= brush->strength;
@@ -3691,8 +3693,8 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr)
WM_event_add_notifier(C, NC_OBJECT|ND_MODIFIER, ob);
}
- bedit->lastmouse[0]= mouse[0];
- bedit->lastmouse[1]= mouse[1];
+ bedit->lastmouse[0] = mouse[0];
+ bedit->lastmouse[1] = mouse[1];
bedit->first= 0;
}
@@ -3987,7 +3989,9 @@ void PE_undo_step(Scene *scene, int step)
}
else if (step==1) {
- if (edit->curundo==NULL || edit->curundo->prev==NULL);
+ if (edit->curundo==NULL || edit->curundo->prev==NULL) {
+ /* pass */
+ }
else {
if (G.debug & G_DEBUG) printf("undo %s\n", edit->curundo->name);
edit->curundo= edit->curundo->prev;
@@ -3997,7 +4001,9 @@ void PE_undo_step(Scene *scene, int step)
else {
/* curundo has to remain current situation! */
- if (edit->curundo==NULL || edit->curundo->next==NULL);
+ if (edit->curundo==NULL || edit->curundo->next==NULL) {
+ /* pass */
+ }
else {
get_PTCacheUndo(edit, edit->curundo->next);
edit->curundo= edit->curundo->next;
@@ -4103,7 +4109,7 @@ int PE_minmax(Scene *scene, float min[3], float max[3])
LOOP_SELECTED_KEYS {
copy_v3_v3(co, key->co);
mul_m4_v3(mat, co);
- DO_MINMAX(co, min, max);
+ DO_MINMAX(co, min, max);
ok= 1;
}
}
@@ -4139,7 +4145,7 @@ static void PE_create_particle_edit(Scene *scene, Object *ob, PointCache *cache,
return;
if (!edit) {
- totpoint = psys ? psys->totpart : (int)((PTCacheMem*)cache->mem_cache.first)->totpoint;
+ totpoint = psys ? psys->totpart : (int)((PTCacheMem *)cache->mem_cache.first)->totpoint;
edit= MEM_callocN(sizeof(PTCacheEdit), "PE_create_particle_edit");
edit->points=MEM_callocN(totpoint*sizeof(PTCacheEditPoint), "PTCacheEditPoints");
diff --git a/source/blender/editors/physics/particle_object.c b/source/blender/editors/physics/particle_object.c
index a17d84af128..221aad2161c 100644
--- a/source/blender/editors/physics/particle_object.c
+++ b/source/blender/editors/physics/particle_object.c
@@ -110,11 +110,14 @@ static int particle_system_remove_exec(bContext *C, wmOperator *UNUSED(op))
/* possible this isn't the active object
* object_remove_particle_system() clears the mode on the last psys
- * */
- if (mode_orig & OB_MODE_PARTICLE_EDIT)
- if ((ob->mode & OB_MODE_PARTICLE_EDIT)==0)
- if (scene->basact && scene->basact->object==ob)
+ */
+ if (mode_orig & OB_MODE_PARTICLE_EDIT) {
+ if ((ob->mode & OB_MODE_PARTICLE_EDIT) == 0) {
+ if (scene->basact && scene->basact->object == ob) {
WM_event_add_notifier(C, NC_SCENE|ND_MODE|NS_MODE_OBJECT, NULL);
+ }
+ }
+ }
WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob);
diff --git a/source/blender/editors/physics/physics_fluid.c b/source/blender/editors/physics/physics_fluid.c
index 099d868a0ad..218af8f0f33 100644
--- a/source/blender/editors/physics/physics_fluid.c
+++ b/source/blender/editors/physics/physics_fluid.c
@@ -196,10 +196,10 @@ static void fluidsimPrintChannel(FILE *file, float *channel, int paramsize, char
int i, j;
int channelSize = paramsize;
- if (entries==3) {
+ if (entries == 3) {
elbeemSimplifyChannelVec3(channel, &channelSize);
}
- else if (entries==1) {
+ else if (entries == 1) {
elbeemSimplifyChannelFloat(channel, &channelSize);
}
else {
@@ -211,10 +211,10 @@ static void fluidsimPrintChannel(FILE *file, float *channel, int paramsize, char
fprintf(file, " ");
for (j=0;j <= entries;j++) { // also print time value
fprintf(file, " %f ", channel[i*(entries + 1) + j]);
- if (j==entries-1) { fprintf(file, " "); }
- }
+ if (j == entries-1) { fprintf(file, " "); }
+ }
fprintf(file, "\n");
- }
+ }
fprintf(file, " ;\n");
}
@@ -242,7 +242,7 @@ static void init_time(FluidsimSettings *domainSettings, FluidAnimChannels *chann
channels->timeAtFrame[0] = channels->timeAtFrame[1] = domainSettings->animStart; // start at index 1
for (i=2; i <= channels->length; i++) {
- channels->timeAtFrame[i] = channels->timeAtFrame[i-1] + channels->aniFrameTime;
+ channels->timeAtFrame[i] = channels->timeAtFrame[i - 1] + (float)channels->aniFrameTime;
}
}
@@ -402,7 +402,7 @@ static void fluid_init_all_channels(bContext *C, Object *UNUSED(fsDomain), Fluid
}
/* now we loop over the frames and fill the allocated channels with data */
- for (i=0; i<channels->length; i++) {
+ for (i=0; i < channels->length; i++) {
FluidObject *fobj;
float viscosity, gravity[3];
float timeAtFrame, time;
@@ -426,7 +426,7 @@ static void fluid_init_all_channels(bContext *C, Object *UNUSED(fsDomain), Fluid
/* Domain time */
// TODO: have option for not running sim, time mangling, in which case second case comes in handy
if (channels->DomainTime) {
- time = get_fluid_rate(domainSettings) * channels->aniFrameTime;
+ time = get_fluid_rate(domainSettings) * (float)channels->aniFrameTime;
timeAtFrame = channels->timeAtFrame[i] + time;
channels->timeAtFrame[i+1] = timeAtFrame;
@@ -456,11 +456,11 @@ static void fluid_init_all_channels(bContext *C, Object *UNUSED(fsDomain), Fluid
/* get the rotation from ob->obmat rather than ob->rot to account for parent animations */
if (i) {
copy_v3_v3(old_rot, fobj->Rotation + 4*(i-1));
- mul_v3_fl(old_rot, -M_PI/180.f);
+ mul_v3_fl(old_rot, (float)-M_PI / 180.f);
}
mat4_to_compatible_eulO(rot_d, old_rot, 0, ob->obmat);
- mul_v3_fl(rot_d, -180.f/M_PI);
+ mul_v3_fl(rot_d, -180.0f / (float)M_PI);
set_channel(fobj->Translation, timeAtFrame, ob->loc, i, CHANNEL_VEC);
set_channel(fobj->Rotation, timeAtFrame, rot_d, i, CHANNEL_VEC);
@@ -527,7 +527,7 @@ static void export_fluid_objects(ListBase *fobjects, Scene *scene, int length)
if ( ELEM(fsmesh.type, OB_FLUIDSIM_FLUID, OB_FLUIDSIM_INFLOW)) {
fsmesh.channelInitialVel = fobj->InitialVelocity;
fsmesh.localInivelCoords = ((fluidmd->fss->typeFlags & OB_FSINFLOW_LOCALCOORD)?1:0);
- }
+ }
if (fluidmd->fss->typeFlags & OB_FSBND_NOSLIP)
fsmesh.obstacleType = FLUIDSIM_OBSTACLE_NOSLIP;
@@ -593,7 +593,7 @@ static int fluid_validate_scene(ReportList *reports, Scene *scene, Object *fsDom
for (base=scene->base.first; base; base= base->next) {
Object *ob = base->object;
- FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
+ FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
/* only find objects with fluid modifiers */
if (!fluidmdtmp || ob->type != OB_MESH) continue;
@@ -627,7 +627,7 @@ static int fluid_validate_scene(ReportList *reports, Scene *scene, Object *fsDom
return 0;
}
- if (channelObjCount>=255) {
+ if (channelObjCount >= 255) {
BKE_report(reports, RPT_ERROR, "Cannot bake with more then 256 objects");
return 0;
}
@@ -648,7 +648,7 @@ static int fluid_validate_scene(ReportList *reports, Scene *scene, Object *fsDom
static int fluid_init_filepaths(Object *fsDomain, char *targetDir, char *targetFile, char *debugStrBuffer)
{
FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(fsDomain, eModifierType_Fluidsim);
- FluidsimSettings *domainSettings= fluidmd->fss;
+ FluidsimSettings *domainSettings= fluidmd->fss;
FILE *fileCfg;
int dirExist = 0;
char newSurfdataPath[FILE_MAX]; /* modified output settings */
@@ -673,7 +673,7 @@ static int fluid_init_filepaths(Object *fsDomain, char *targetDir, char *targetF
// check selected directory
// simply try to open cfg file for writing to test validity of settings
fileCfg = BLI_fopen(targetFile, "w");
- if (fileCfg) {
+ if (fileCfg) {
dirExist = 1; fclose(fileCfg);
// remove cfg dummy from directory test
BLI_delete(targetFile, 0, 0);
@@ -695,21 +695,21 @@ static int fluid_init_filepaths(Object *fsDomain, char *targetDir, char *targetF
outStringsChanged=1;
}
- // check if modified output dir is ok
+ /* check if modified output dir is ok */
#if 0
if (outStringsChanged) {
char dispmsg[FILE_MAX+256];
int selection=0;
BLI_strncpy(dispmsg, "Output settings set to: '", sizeof(dispmsg));
strcat(dispmsg, newSurfdataPath);
- strcat(dispmsg, "'%t|Continue with changed settings%x1|Discard and abort%x0");
+ strcat(dispmsg, "'%t|Continue with changed settings %x1|Discard and abort %x0");
- // ask user if thats what he/she wants...
+ /* ask user if thats what he/she wants... */
selection = pupmenu(dispmsg);
- if (selection < 1) return 0; // 0 from menu, or -1 aborted
+ if (selection < 1) return 0; /* 0 from menu, or -1 aborted */
BLI_strncpy(targetDir, newSurfdataPath, sizeof(targetDir));
strncpy(domainSettings->surfdataPath, newSurfdataPath, FILE_MAXDIR);
- BLI_path_abs(targetDir, G.main->name); // fixed #frame-no
+ BLI_path_abs(targetDir, G.main->name); /* fixed #frame-no */
}
#endif
return outStringsChanged;
@@ -902,7 +902,7 @@ static int fluidsimBake(bContext *C, ReportList *reports, Object *fsDomain, shor
/* make sure it corresponds to startFrame setting (old: noFrames = scene->r.efra - scene->r.sfra +1) */;
noFrames = scene->r.efra - 0;
if (noFrames<=0) {
- BKE_report(reports, RPT_ERROR, "No frames to export - check your animation range settings");
+ BKE_report(reports, RPT_ERROR, "No frames to export (check your animation range settings)");
fluidbake_free_data(channels, fobjects, fsset, fb);
return 0;
}
@@ -944,8 +944,7 @@ static int fluidsimBake(bContext *C, ReportList *reports, Object *fsDomain, shor
if (domainSettings->resolutionxyz>128) {
gridlevels = 2;
}
- else
- if (domainSettings->resolutionxyz>64) {
+ else if (domainSettings->resolutionxyz > 64) {
gridlevels = 1;
}
else {
@@ -963,7 +962,7 @@ static int fluidsimBake(bContext *C, ReportList *reports, Object *fsDomain, shor
/* ******** prepare output file paths ******** */
outStringsChanged = fluid_init_filepaths(fsDomain, targetDir, targetFile, debugStrBuffer);
channels->length = scene->r.efra;
- channels->aniFrameTime = (domainSettings->animEnd - domainSettings->animStart)/(double)noFrames;
+ channels->aniFrameTime = (double)(domainSettings->animEnd - domainSettings->animStart) / (double)noFrames;
/* ******** initialize and allocate animation channels ******** */
fluid_init_all_channels(C, fsDomain, domainSettings, channels, fobjects);
@@ -1050,7 +1049,7 @@ static int fluidsimBake(bContext *C, ReportList *reports, Object *fsDomain, shor
fsset->generateVertexVectors = (domainSettings->domainNovecgen==0);
// init blender domain transform matrix
- { int j;
+ { int j;
for (i=0; i<4; i++) {
for (j=0; j<4; j++) {
fsset->surfaceTrafo[i*4+j] = invDomMat[j][i];
diff --git a/source/blender/editors/physics/physics_ops.c b/source/blender/editors/physics/physics_ops.c
index 89ddfe02208..fb99d296a54 100644
--- a/source/blender/editors/physics/physics_ops.c
+++ b/source/blender/editors/physics/physics_ops.c
@@ -61,7 +61,7 @@ static void operatortypes_particle(void)
WM_operatortype_append(PARTICLE_OT_rekey);
WM_operatortype_append(PARTICLE_OT_subdivide);
WM_operatortype_append(PARTICLE_OT_remove_doubles);
- WM_operatortype_append(PARTICLE_OT_weight_set);
+ WM_operatortype_append(PARTICLE_OT_weight_set);
WM_operatortype_append(PARTICLE_OT_delete);
WM_operatortype_append(PARTICLE_OT_mirror);
diff --git a/source/blender/editors/physics/physics_pointcache.c b/source/blender/editors/physics/physics_pointcache.c
index 218ae628d3f..bbce94b6215 100644
--- a/source/blender/editors/physics/physics_pointcache.c
+++ b/source/blender/editors/physics/physics_pointcache.c
@@ -325,9 +325,9 @@ static int ptcache_add_new_exec(bContext *C, wmOperator *UNUSED(op))
for (pid=pidlist.first; pid; pid=pid->next) {
if (pid->cache == cache) {
- PointCache *cache = BKE_ptcache_add(pid->ptcaches);
- cache->step = pid->default_step;
- *(pid->cache_ptr) = cache;
+ PointCache *cache_new = BKE_ptcache_add(pid->ptcaches);
+ cache_new->step = pid->default_step;
+ *(pid->cache_ptr) = cache_new;
break;
}
}
diff --git a/source/blender/editors/render/render_internal.c b/source/blender/editors/render/render_internal.c
index ebacac917e8..4b177629f72 100644
--- a/source/blender/editors/render/render_internal.c
+++ b/source/blender/editors/render/render_internal.c
@@ -80,11 +80,10 @@ void image_buffer_rect_update(Scene *scene, RenderResult *rr, ImBuf *ibuf, volat
float *rectf = NULL;
int ymin, ymax, xmin, xmax;
int rymin, rxmin;
- unsigned char *rectc;
/* if renrect argument, we only refresh scanlines */
if (renrect) {
- /* if ymax==recty, rendering of layer is ready, we should not draw, other things happen... */
+ /* if (ymax == recty), rendering of layer is ready, we should not draw, other things happen... */
if (rr->renlay == NULL || renrect->ymax >= rr->recty)
return;
@@ -124,8 +123,14 @@ void image_buffer_rect_update(Scene *scene, RenderResult *rr, ImBuf *ibuf, volat
if (rr->rectf)
rectf = rr->rectf;
else {
- if (rr->rect32)
+ if (rr->rect32) {
+ /* special case, currently only happens with sequencer rendering,
+ * which updates the whole frame, so we can only mark display buffer
+ * as invalid here (sergey)
+ */
+ ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
return;
+ }
else {
if (rr->renlay == NULL || rr->renlay->rectf == NULL) return;
rectf = rr->renlay->rectf;
@@ -137,11 +142,10 @@ void image_buffer_rect_update(Scene *scene, RenderResult *rr, ImBuf *ibuf, volat
imb_addrectImBuf(ibuf);
rectf += 4 * (rr->rectx * ymin + xmin);
- rectc = (unsigned char *)(ibuf->rect + ibuf->x * rymin + rxmin);
IMB_partial_display_buffer_update(ibuf, rectf, NULL, rr->rectx, rxmin, rymin,
&scene->view_settings, &scene->display_settings,
- rxmin, rymin, rxmin + xmax, rymin + ymax);
+ rxmin, rymin, rxmin + xmax, rymin + ymax, TRUE);
}
/* ****************************** render invoking ***************** */
@@ -198,7 +202,7 @@ static int screen_render_exec(bContext *C, wmOperator *op)
screen_render_scene_layer_set(op, mainp, &scene, &srl);
if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
- BKE_report(op->reports, RPT_ERROR, "Can't write a single file with an animation format selected");
+ BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
return OPERATOR_CANCELLED;
}
@@ -291,7 +295,11 @@ static void make_renderinfo_string(RenderStats *rs, Scene *scene, char *str)
if (rs->tothalo) spos += sprintf(spos, "Ha:%d ", rs->tothalo);
if (rs->totstrand) spos += sprintf(spos, "St:%d ", rs->totstrand);
if (rs->totlamp) spos += sprintf(spos, "La:%d ", rs->totlamp);
- spos += sprintf(spos, "Mem:%.2fM (%.2fM, peak %.2fM) ", megs_used_memory, mmap_used_memory, megs_peak_memory);
+
+ if (rs->mem_peak == 0.0f)
+ spos += sprintf(spos, "Mem:%.2fM (%.2fM, peak %.2fM) ", megs_used_memory, mmap_used_memory, megs_peak_memory);
+ else
+ spos += sprintf(spos, "Mem:%.2fM, Peak: %.2fM ", rs->mem_used, rs->mem_peak);
if (rs->curfield)
spos += sprintf(spos, "Field %d ", rs->curfield);
@@ -489,12 +497,12 @@ static int screen_render_invoke(bContext *C, wmOperator *op, wmEvent *event)
}
if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
- BKE_report(op->reports, RPT_ERROR, "Can't write a single file with an animation format selected");
+ BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
return OPERATOR_CANCELLED;
- }
+ }
- /* stop all running jobs, currently previews frustrate Render */
- WM_jobs_stop_all(CTX_wm_manager(C));
+ /* stop all running jobs, except screen one. currently previews frustrate Render */
+ WM_jobs_kill_all_except(CTX_wm_manager(C), CTX_wm_screen(C));
/* get main */
if (G.debug_value == 101) {
diff --git a/source/blender/editors/render/render_opengl.c b/source/blender/editors/render/render_opengl.c
index d9618e89b68..e4592a4f77e 100644
--- a/source/blender/editors/render/render_opengl.c
+++ b/source/blender/editors/render/render_opengl.c
@@ -171,11 +171,13 @@ static void screen_opengl_render_apply(OGLRender *oglrender)
}
}
else if (view_context) {
+ ED_view3d_draw_offscreen_init(scene, v3d);
+
GPU_offscreen_bind(oglrender->ofs); /* bind */
/* render 3d view */
if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
- /*int is_ortho= scene->r.mode & R_ORTHO;*/
+ /*int is_ortho = scene->r.mode & R_ORTHO;*/
camera = v3d->camera;
RE_GetCameraWindow(oglrender->re, camera, scene->r.cfra, winmat);
@@ -189,7 +191,7 @@ static void screen_opengl_render_apply(OGLRender *oglrender)
else perspective_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
}
- if ((scene->r.mode & R_OSA) == 0) {
+ if ((scene->r.mode & R_OSA) == 0) {
ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat, TRUE, FALSE);
GPU_offscreen_read_pixels(oglrender->ofs, GL_FLOAT, rr->rectf);
}
@@ -306,7 +308,7 @@ static int screen_opengl_render_init(bContext *C, wmOperator *op)
char err_out[256] = "unknown";
if (G.background) {
- BKE_report(op->reports, RPT_ERROR, "Can't use OpenGL render in background mode (no opengl context)");
+ BKE_report(op->reports, RPT_ERROR, "Cannot use OpenGL render in background mode (no opengl context)");
return 0;
}
@@ -327,12 +329,12 @@ static int screen_opengl_render_init(bContext *C, wmOperator *op)
}
if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
- BKE_report(op->reports, RPT_ERROR, "Can't write a single file with an animation format selected");
+ BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
return 0;
}
- /* stop all running jobs, currently previews frustrate Render */
- WM_jobs_stop_all(CTX_wm_manager(C));
+ /* stop all running jobs, except screen one. currently previews frustrate Render */
+ WM_jobs_kill_all_except(CTX_wm_manager(C), CTX_wm_screen(C));
/* create offscreen buffer */
sizex = (scene->r.size * scene->r.xsch) / 100;
@@ -342,7 +344,7 @@ static int screen_opengl_render_init(bContext *C, wmOperator *op)
ofs = GPU_offscreen_create(sizex, sizey, err_out);
if (!ofs) {
- BKE_reportf(op->reports, RPT_ERROR, "Failed to create OpenGL offscreen buffer, %s", err_out);
+ BKE_reportf(op->reports, RPT_ERROR, "Failed to create OpenGL off-screen buffer, %s", err_out);
return 0;
}
@@ -547,11 +549,11 @@ static int screen_opengl_render_anim_step(bContext *C, wmOperator *op)
if (ibuf) {
int needs_free = FALSE;
- if (is_movie || !BKE_imtype_supports_float(scene->r.im_format.imtype)) {
- ImBuf *colormanage_ibuf = IMB_dupImBuf(ibuf);
+ if (is_movie || !BKE_imtype_requires_linear_float(scene->r.im_format.imtype)) {
+ ImBuf *colormanage_ibuf;
- IMB_display_buffer_to_imbuf_rect(colormanage_ibuf, &scene->view_settings, &scene->display_settings);
- imb_freerectfloatImBuf(colormanage_ibuf);
+ colormanage_ibuf = IMB_colormanagement_imbuf_for_write(ibuf, TRUE, TRUE, &scene->view_settings,
+ &scene->display_settings, &scene->r.im_format);
// IMB_freeImBuf(ibuf); /* owned by the image */
ibuf = colormanage_ibuf;
@@ -716,7 +718,7 @@ static int screen_opengl_render_exec(bContext *C, wmOperator *op)
}
}
- // no redraw needed, we leave state as we entered it
+ /* no redraw needed, we leave state as we entered it */
// ED_update_for_newframe(C, 1);
WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, CTX_data_scene(C));
diff --git a/source/blender/editors/render/render_preview.c b/source/blender/editors/render/render_preview.c
index a829ef57b85..53cb5340940 100644
--- a/source/blender/editors/render/render_preview.c
+++ b/source/blender/editors/render/render_preview.c
@@ -266,14 +266,18 @@ static Scene *preview_prepare_scene(Scene *scene, ID *id, int id_type, ShaderPre
BKE_color_managed_view_settings_copy(&sce->view_settings, &scene->view_settings);
/* prevent overhead for small renders and icons (32) */
- if (id && sp->sizex < 40)
- sce->r.xparts = sce->r.yparts = 1;
- else
- sce->r.xparts = sce->r.yparts = 4;
+ if (id && sp->sizex < 40) {
+ sce->r.tilex = sce->r.tiley = 64;
+ }
+ else {
+ sce->r.tilex = sce->r.xsch / 4;
+ sce->r.tiley = sce->r.ysch / 4;
+ }
- /* exception: don't color manage texture previews or icons */
- if ((id && sp->pr_method == PR_ICON_RENDER) || id_type == ID_TE)
+ /* exception: don't apply render part of display transform for texture previews or icons */
+ if ((id && sp->pr_method == PR_ICON_RENDER) || id_type == ID_TE) {
BKE_scene_disable_color_management(sce);
+ }
if ((id && sp->pr_method == PR_ICON_RENDER) && id_type != ID_WO)
sce->r.alphamode = R_ALPHAPREMUL;
@@ -340,7 +344,7 @@ static Scene *preview_prepare_scene(Scene *scene, ID *id, int id_type, ShaderPre
if (sp->pr_method == PR_ICON_RENDER) {
if (mat->material_type == MA_TYPE_HALO) {
sce->lay = 1 << MA_FLAT;
- }
+ }
else {
sce->lay = 1 << MA_SPHERE_A;
}
@@ -367,7 +371,7 @@ static Scene *preview_prepare_scene(Scene *scene, ID *id, int id_type, ShaderPre
if (OB_TYPE_SUPPORT_MATERIAL(base->object->type)) {
/* don't use assign_material, it changed mat->id.us, which shows in the UI */
Material ***matar = give_matarar(base->object);
- int actcol = MAX2(base->object->actcol - 1, 0);
+ int actcol = max_ii(base->object->actcol - 1, 0);
if (matar && actcol < base->object->totcol)
(*matar)[actcol] = mat;
@@ -385,7 +389,7 @@ static Scene *preview_prepare_scene(Scene *scene, ID *id, int id_type, ShaderPre
tex = localize_texture(origtex);
sp->texcopy = tex;
BLI_addtail(&pr_main->tex, tex);
- }
+ }
sce->lay = 1 << MA_TEXTURE;
for (base = sce->base.first; base; base = base->next) {
@@ -485,8 +489,8 @@ static int ed_preview_draw_rect(ScrArea *sa, Scene *sce, ID *id, int split, int
char name[32];
int do_gamma_correct = FALSE, do_predivide = FALSE;
int offx = 0;
- int newx = BLI_RCT_SIZE_X(rect);
- int newy = BLI_RCT_SIZE_Y(rect);
+ int newx = BLI_rcti_size_x(rect);
+ int newy = BLI_rcti_size_y(rect);
if (id && GS(id->name) != ID_TE) {
/* exception: don't color manage texture previews - show the raw values */
@@ -517,8 +521,8 @@ static int ed_preview_draw_rect(ScrArea *sa, Scene *sce, ID *id, int split, int
if (ABS(rres.rectx - newx) < 2 && ABS(rres.recty - newy) < 2) {
- newrect->xmax = MAX2(newrect->xmax, rect->xmin + rres.rectx + offx);
- newrect->ymax = MAX2(newrect->ymax, rect->ymin + rres.recty);
+ newrect->xmax = max_ii(newrect->xmax, rect->xmin + rres.rectx + offx);
+ newrect->ymax = max_ii(newrect->ymax, rect->ymin + rres.recty);
if (rres.rectx && rres.recty) {
/* temporary conversion to byte for drawing */
@@ -540,7 +544,7 @@ static int ed_preview_draw_rect(ScrArea *sa, Scene *sce, ID *id, int split, int
* color managed as well?
*/
IMB_buffer_byte_from_float(rect_byte, rres.rectf,
- 4, dither, IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB, do_predivide,
+ 4, dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB, do_predivide,
rres.rectx, rres.recty, rres.rectx, rres.rectx);
}
@@ -569,8 +573,8 @@ void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, r
SpaceButs *sbuts = sa->spacedata.first;
rcti newrect;
int ok;
- int newx = BLI_RCT_SIZE_X(rect);
- int newy = BLI_RCT_SIZE_Y(rect);
+ int newx = BLI_rcti_size_x(rect);
+ int newy = BLI_rcti_size_y(rect);
newrect.xmin = rect->xmin;
newrect.xmax = rect->xmin;
@@ -596,7 +600,7 @@ void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, r
if (ok == 0) {
ED_preview_shader_job(C, sa, id, parent, slot, newx, newy, PR_BUTS_RENDER);
}
- }
+ }
}
/* **************************** new shader preview system ****************** */
@@ -648,7 +652,7 @@ static void shader_preview_updatejob(void *spv)
if (sp->lampcopy && la->nodetree && sp->lampcopy->nodetree)
ntreeLocalSync(sp->lampcopy->nodetree, la->nodetree);
}
- }
+ }
}
}
@@ -808,7 +812,7 @@ static void shader_preview_free(void *customdata)
/* get rid of copied world */
BLI_remlink(&pr_main->world, sp->worldcopy);
- BKE_world_free_ex(sp->worldcopy, FALSE);
+ BKE_world_free_ex(sp->worldcopy, TRUE); /* [#32865] - we need to unlink the texture copies, unlike for materials */
properties = IDP_GetProperties((ID *)sp->worldcopy, FALSE);
if (properties) {
@@ -860,7 +864,7 @@ static void icon_copy_rect(ImBuf *ibuf, unsigned int w, unsigned int h, unsigned
scaledx = (float)w;
scaledy = ( (float)ima->y / (float)ima->x) * (float)w;
}
- else {
+ else {
scaledx = ( (float)ima->x / (float)ima->y) * (float)h;
scaledy = (float)h;
}
diff --git a/source/blender/editors/render/render_shading.c b/source/blender/editors/render/render_shading.c
index 8bdd4e544e8..25a01d38dd5 100644
--- a/source/blender/editors/render/render_shading.c
+++ b/source/blender/editors/render/render_shading.c
@@ -747,7 +747,11 @@ void TEXTURE_OT_envmap_save(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER; /* no undo since this doesnt modify the env-map */
/* properties */
- prop = RNA_def_float_array(ot->srna, "layout", 12, default_envmap_layout, 0.0f, 0.0f, "File layout", "Flat array describing the X,Y position of each cube face in the output image, where 1 is the size of a face - order is [+Z -Z +Y -X -Y +X] (use -1 to skip a face)", 0.0f, 0.0f);
+ prop = RNA_def_float_array(ot->srna, "layout", 12, default_envmap_layout, 0.0f, 0.0f,
+ "File layout",
+ "Flat array describing the X,Y position of each cube face in the output image, "
+ "where 1 is the size of a face - order is [+Z -Z +Y -X -Y +X] "
+ "(use -1 to skip a face)", 0.0f, 0.0f);
RNA_def_property_flag(prop, PROP_HIDDEN);
WM_operator_properties_filesel(ot, FOLDERFILE | IMAGEFILE | MOVIEFILE, FILE_SPECIAL, FILE_SAVE,
diff --git a/source/blender/editors/render/render_update.c b/source/blender/editors/render/render_update.c
index 08ccf37265b..c5320fde0ff 100644
--- a/source/blender/editors/render/render_update.c
+++ b/source/blender/editors/render/render_update.c
@@ -74,12 +74,19 @@ void ED_render_scene_update(Main *bmain, Scene *scene, int updated)
bScreen *sc;
ScrArea *sa;
ARegion *ar;
+ static int recursive_check = FALSE;
/* don't do this render engine update if we're updating the scene from
* other threads doing e.g. rendering or baking jobs */
if (!BLI_thread_is_main())
return;
+ /* don't call this recursively for frame updates */
+ if (recursive_check)
+ return;
+
+ recursive_check = TRUE;
+
C = CTX_create();
CTX_data_main_set(C, bmain);
CTX_data_scene_set(C, scene);
@@ -114,6 +121,8 @@ void ED_render_scene_update(Main *bmain, Scene *scene, int updated)
}
CTX_free(C);
+
+ recursive_check = FALSE;
}
void ED_render_engine_area_exit(ScrArea *sa)
@@ -224,8 +233,12 @@ static void material_changed(Main *bmain, Material *ma)
/* find node materials using this */
for (parent = bmain->mat.first; parent; parent = parent->id.next) {
- if (parent->use_nodes && parent->nodetree && nodes_use_material(parent->nodetree, ma)) ;
- else continue;
+ if (parent->use_nodes && parent->nodetree && nodes_use_material(parent->nodetree, ma)) {
+ /* pass */
+ }
+ else {
+ continue;
+ }
BKE_icon_changed(BKE_icon_getid(&parent->id));
@@ -247,9 +260,15 @@ static void texture_changed(Main *bmain, Tex *tex)
/* find materials */
for (ma = bmain->mat.first; ma; ma = ma->id.next) {
- if (mtex_use_tex(ma->mtex, MAX_MTEX, tex)) ;
- else if (ma->use_nodes && ma->nodetree && nodes_use_tex(ma->nodetree, tex)) ;
- else continue;
+ if (mtex_use_tex(ma->mtex, MAX_MTEX, tex)) {
+ /* pass */
+ }
+ else if (ma->use_nodes && ma->nodetree && nodes_use_tex(ma->nodetree, tex)) {
+ /* pass */
+ }
+ else {
+ continue;
+ }
BKE_icon_changed(BKE_icon_getid(&ma->id));
@@ -259,18 +278,30 @@ static void texture_changed(Main *bmain, Tex *tex)
/* find lamps */
for (la = bmain->lamp.first; la; la = la->id.next) {
- if (mtex_use_tex(la->mtex, MAX_MTEX, tex)) ;
- else if (la->nodetree && nodes_use_tex(la->nodetree, tex)) ;
- else continue;
+ if (mtex_use_tex(la->mtex, MAX_MTEX, tex)) {
+ /* pass */
+ }
+ else if (la->nodetree && nodes_use_tex(la->nodetree, tex)) {
+ /* pass */
+ }
+ else {
+ continue;
+ }
BKE_icon_changed(BKE_icon_getid(&la->id));
}
/* find worlds */
for (wo = bmain->world.first; wo; wo = wo->id.next) {
- if (mtex_use_tex(wo->mtex, MAX_MTEX, tex)) ;
- else if (wo->nodetree && nodes_use_tex(wo->nodetree, tex)) ;
- else continue;
+ if (mtex_use_tex(wo->mtex, MAX_MTEX, tex)) {
+ /* pass */
+ }
+ else if (wo->nodetree && nodes_use_tex(wo->nodetree, tex)) {
+ /* pass */
+ }
+ else {
+ continue;
+ }
BKE_icon_changed(BKE_icon_getid(&wo->id));
}
diff --git a/source/blender/editors/render/render_view.c b/source/blender/editors/render/render_view.c
index 01c0169eb50..5ec7f4d05b6 100644
--- a/source/blender/editors/render/render_view.c
+++ b/source/blender/editors/render/render_view.c
@@ -220,7 +220,6 @@ void render_view_open(bContext *C, int mx, int my)
else {
/* Leave it alone so the image editor will just go back from
* full screen to the original tiled setup */
- ;
}
}
}
@@ -282,7 +281,7 @@ static int render_view_show_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent
if (wincur->screen->temp) {
wm_window_lower(wincur);
}
- else {
+ else {
wmWindow *win, *winshow;
ScrArea *sa = find_area_showing_r_result(C, &winshow);
diff --git a/source/blender/editors/screen/area.c b/source/blender/editors/screen/area.c
index 0bfe5d04e5e..f30e0abb4f3 100644
--- a/source/blender/editors/screen/area.c
+++ b/source/blender/editors/screen/area.c
@@ -104,8 +104,8 @@ static void region_draw_emboss(ARegion *ar, rcti *scirct)
void ED_region_pixelspace(ARegion *ar)
{
- int width = BLI_RCT_SIZE_X(&ar->winrct) + 1;
- int height = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
+ int width = BLI_rcti_size_x(&ar->winrct) + 1;
+ int height = BLI_rcti_size_y(&ar->winrct) + 1;
wmOrtho2(-GLA_PIXEL_OFS, (float)width - GLA_PIXEL_OFS, -GLA_PIXEL_OFS, (float)height - GLA_PIXEL_OFS);
glLoadIdentity();
@@ -390,7 +390,7 @@ void ED_area_overdraw(bContext *C)
az->do_draw = FALSE;
}
}
- }
+ }
glDisable(GL_BLEND);
}
@@ -407,8 +407,12 @@ void region_scissor_winrct(ARegion *ar, rcti *winrct)
ar = ar->prev;
if (BLI_rcti_isect(winrct, &ar->winrct, NULL)) {
- if (ar->flag & RGN_FLAG_HIDDEN) ;
- else if (ar->alignment & RGN_SPLIT_PREV) ;
+ if (ar->flag & RGN_FLAG_HIDDEN) {
+ /* pass */
+ }
+ else if (ar->alignment & RGN_SPLIT_PREV) {
+ /* pass */
+ }
else if (ar->alignment == RGN_OVERLAP_LEFT) {
winrct->xmin = ar->winrct.xmax + 1;
}
@@ -461,11 +465,11 @@ void ED_region_do_draw(bContext *C, ARegion *ar)
if (ar->drawrct.xmin == ar->drawrct.xmax)
ar->drawrct = winrct;
else {
- /* extra clip for safety */
- ar->drawrct.xmin = MAX2(winrct.xmin, ar->drawrct.xmin);
- ar->drawrct.ymin = MAX2(winrct.ymin, ar->drawrct.ymin);
- ar->drawrct.xmax = MIN2(winrct.xmax, ar->drawrct.xmax);
- ar->drawrct.ymax = MIN2(winrct.ymax, ar->drawrct.ymax);
+ /* extra clip for safety (intersect the rects, could use API func) */
+ ar->drawrct.xmin = max_ii(winrct.xmin, ar->drawrct.xmin);
+ ar->drawrct.ymin = max_ii(winrct.ymin, ar->drawrct.ymin);
+ ar->drawrct.xmax = min_ii(winrct.xmax, ar->drawrct.xmax);
+ ar->drawrct.ymax = min_ii(winrct.ymax, ar->drawrct.ymax);
}
/* note; this sets state, so we can use wmOrtho and friends */
@@ -529,10 +533,7 @@ void ED_region_tag_redraw_partial(ARegion *ar, rcti *rct)
}
else if (ar->drawrct.xmin != ar->drawrct.xmax) {
/* partial redraw already set, expand region */
- ar->drawrct.xmin = MIN2(ar->drawrct.xmin, rct->xmin);
- ar->drawrct.ymin = MIN2(ar->drawrct.ymin, rct->ymin);
- ar->drawrct.xmax = MAX2(ar->drawrct.xmax, rct->xmax);
- ar->drawrct.ymax = MAX2(ar->drawrct.ymax, rct->ymax);
+ BLI_rcti_union(&ar->drawrct, rct);
}
}
}
@@ -901,10 +902,10 @@ static void region_azone_add(ScrArea *sa, ARegion *ar, int alignment)
static int rct_fits(rcti *rect, char dir, int size)
{
if (dir == 'h') {
- return BLI_RCT_SIZE_X(rect) - size;
+ return BLI_rcti_size_x(rect) - size;
}
else { /* 'v' */
- return BLI_RCT_SIZE_Y(rect) - size;
+ return BLI_rcti_size_y(rect) - size;
}
}
@@ -935,20 +936,25 @@ static void region_rect_recursive(ScrArea *sa, ARegion *ar, rcti *remainder, int
/* prefsize, for header we stick to exception */
prefsizex = ar->sizex ? ar->sizex : ar->type->prefsizex;
- if (ar->regiontype == RGN_TYPE_HEADER)
+ if (ar->regiontype == RGN_TYPE_HEADER) {
prefsizey = ar->type->prefsizey;
+ }
else if (ar->regiontype == RGN_TYPE_UI && sa->spacetype == SPACE_FILE) {
prefsizey = UI_UNIT_Y * 2 + (UI_UNIT_Y / 2);
}
- else
+ else {
prefsizey = ar->sizey ? ar->sizey : ar->type->prefsizey;
-
- /* hidden is user flag */
- if (ar->flag & RGN_FLAG_HIDDEN) ;
- /* XXX floating area region, not handled yet here */
- else if (alignment == RGN_ALIGN_FLOAT) ;
- /* remainder is too small for any usage */
+ }
+
+
+ if (ar->flag & RGN_FLAG_HIDDEN) {
+ /* hidden is user flag */
+ }
+ else if (alignment == RGN_ALIGN_FLOAT) {
+ /* XXX floating area region, not handled yet here */
+ }
else if (rct_fits(remainder, 'v', 1) < 0 || rct_fits(remainder, 'h', 1) < 0) {
+ /* remainder is too small for any usage */
ar->flag |= RGN_FLAG_TOO_SMALL;
}
else if (alignment == RGN_ALIGN_NONE) {
@@ -1010,7 +1016,7 @@ static void region_rect_recursive(ScrArea *sa, ARegion *ar, rcti *remainder, int
if (alignment == RGN_ALIGN_HSPLIT) {
if (rct_fits(remainder, 'h', prefsizex) > 4) {
- ar->winrct.xmax = BLI_RCT_CENTER_X(remainder);
+ ar->winrct.xmax = BLI_rcti_cent_x(remainder);
remainder->xmin = ar->winrct.xmax + 1;
}
else {
@@ -1019,7 +1025,7 @@ static void region_rect_recursive(ScrArea *sa, ARegion *ar, rcti *remainder, int
}
else {
if (rct_fits(remainder, 'v', prefsizey) > 4) {
- ar->winrct.ymax = BLI_RCT_CENTER_Y(remainder);
+ ar->winrct.ymax = BLI_rcti_cent_y(remainder);
remainder->ymin = ar->winrct.ymax + 1;
}
else {
@@ -1051,20 +1057,20 @@ static void region_rect_recursive(ScrArea *sa, ARegion *ar, rcti *remainder, int
}
if (quad) {
if (quad == 1) { /* left bottom */
- ar->winrct.xmax = BLI_RCT_CENTER_X(remainder);
- ar->winrct.ymax = BLI_RCT_CENTER_Y(remainder);
+ ar->winrct.xmax = BLI_rcti_cent_x(remainder);
+ ar->winrct.ymax = BLI_rcti_cent_y(remainder);
}
else if (quad == 2) { /* left top */
- ar->winrct.xmax = BLI_RCT_CENTER_X(remainder);
- ar->winrct.ymin = BLI_RCT_CENTER_Y(remainder) + 1;
+ ar->winrct.xmax = BLI_rcti_cent_x(remainder);
+ ar->winrct.ymin = BLI_rcti_cent_y(remainder) + 1;
}
else if (quad == 3) { /* right bottom */
- ar->winrct.xmin = BLI_RCT_CENTER_X(remainder) + 1;
- ar->winrct.ymax = BLI_RCT_CENTER_Y(remainder);
+ ar->winrct.xmin = BLI_rcti_cent_x(remainder) + 1;
+ ar->winrct.ymax = BLI_rcti_cent_y(remainder);
}
else { /* right top */
- ar->winrct.xmin = BLI_RCT_CENTER_X(remainder) + 1;
- ar->winrct.ymin = BLI_RCT_CENTER_Y(remainder) + 1;
+ ar->winrct.xmin = BLI_rcti_cent_x(remainder) + 1;
+ ar->winrct.ymin = BLI_rcti_cent_y(remainder) + 1;
BLI_rcti_init(remainder, 0, 0, 0, 0);
}
@@ -1073,8 +1079,8 @@ static void region_rect_recursive(ScrArea *sa, ARegion *ar, rcti *remainder, int
}
/* for speedup */
- ar->winx = BLI_RCT_SIZE_X(&ar->winrct) + 1;
- ar->winy = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
+ ar->winx = BLI_rcti_size_x(&ar->winrct) + 1;
+ ar->winy = BLI_rcti_size_y(&ar->winrct) + 1;
/* set winrect for azones */
if (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL)) {
@@ -1096,8 +1102,8 @@ static void region_rect_recursive(ScrArea *sa, ARegion *ar, rcti *remainder, int
if (ar->alignment & RGN_SPLIT_PREV) {
if (ar->prev) {
remainder = remainder_prev;
- ar->prev->winx = BLI_RCT_SIZE_X(&ar->prev->winrct) + 1;
- ar->prev->winy = BLI_RCT_SIZE_Y(&ar->prev->winrct) + 1;
+ ar->prev->winx = BLI_rcti_size_x(&ar->prev->winrct) + 1;
+ ar->prev->winy = BLI_rcti_size_y(&ar->prev->winrct) + 1;
}
}
@@ -1133,8 +1139,8 @@ static void area_calc_totrct(ScrArea *sa, int sizex, int sizey)
else sa->totrct.ymax = sa->v2->vec.y;
/* for speedup */
- sa->winx = BLI_RCT_SIZE_X(&sa->totrct) + 1;
- sa->winy = BLI_RCT_SIZE_Y(&sa->totrct) + 1;
+ sa->winx = BLI_rcti_size_x(&sa->totrct) + 1;
+ sa->winy = BLI_rcti_size_y(&sa->totrct) + 1;
}
@@ -1251,25 +1257,21 @@ void ED_area_initialize(wmWindowManager *wm, wmWindow *win, ScrArea *sa)
}
else {
/* prevent uiblocks to run */
- uiFreeBlocks(NULL, &ar->uiblocks);
+ uiFreeBlocks(NULL, &ar->uiblocks);
}
-
- /* rechecks 2d matrix for header on dpi changing, do not do for other regions, it resets view && blocks view2d operator polls (ton) */
- if (ar->regiontype == RGN_TYPE_HEADER)
- ar->v2d.flag &= ~V2D_IS_INITIALISED;
}
}
/* externally called for floating regions like menus */
void ED_region_init(bContext *C, ARegion *ar)
{
-// ARegionType *at= ar->type;
+// ARegionType *at = ar->type;
/* refresh can be called before window opened */
region_subwindow(CTX_wm_window(C), ar);
- ar->winx = BLI_RCT_SIZE_X(&ar->winrct) + 1;
- ar->winy = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
+ ar->winx = BLI_rcti_size_x(&ar->winrct) + 1;
+ ar->winy = BLI_rcti_size_y(&ar->winrct) + 1;
/* UI convention */
wmOrtho2(-0.01f, ar->winx - 0.01f, -0.01f, ar->winy - 0.01f);
@@ -1405,7 +1407,7 @@ void ED_area_newspace(bContext *C, ScrArea *sa, int type)
/* put in front of list */
BLI_remlink(&sa->spacedata, sl);
BLI_addhead(&sa->spacedata, sl);
- }
+ }
else {
/* new space */
if (st) {
@@ -1448,7 +1450,8 @@ void ED_area_prevspace(bContext *C, ScrArea *sa)
ED_area_newspace(C, sa, sl->next->spacetype);
}
else {
- ED_area_newspace(C, sa, SPACE_INFO);
+ /* no change */
+ return;
}
ED_area_tag_redraw(sa);
@@ -1459,39 +1462,39 @@ void ED_area_prevspace(bContext *C, ScrArea *sa)
static const char *editortype_pup(void)
{
const char *types = N_(
- "Editor type:%t"
+ "Editor type: %t"
"|3D View %x1"
"|%l"
-
+
"|Timeline %x15"
"|Graph Editor %x2"
"|DopeSheet %x12"
"|NLA Editor %x13"
-
+
"|%l"
-
+
"|UV/Image Editor %x6"
-
+
"|Video Sequence Editor %x8"
"|Movie Clip Editor %x20"
"|Text Editor %x9"
"|Node Editor %x16"
"|Logic Editor %x17"
-
+
"|%l"
-
+
"|Properties %x4"
"|Outliner %x3"
"|User Preferences %x19"
- "|Info%x7"
+ "|Info %x7"
"|%l"
"|File Browser %x5"
-
+
"|%l"
-
+
"|Python Console %x18"
);
@@ -1517,7 +1520,7 @@ int ED_area_header_switchbutton(const bContext *C, uiBlock *block, int yco)
but = uiDefIconTextButC(block, ICONTEXTROW, 0, ICON_VIEW3D,
editortype_pup(), xco, yco, UI_UNIT_X + 10, UI_UNIT_Y,
&(sa->butspacetype), 1.0, SPACEICONMAX, 0, 0,
- TIP_("Displays current editor type. Click for menu of available types"));
+ TIP_("Display current editor type (click for a menu of available types)"));
uiButSetFunc(but, spacefunc, NULL, NULL);
uiButClearFlag(but, UI_BUT_UNDO); /* skip undo on screen buttons */
@@ -1574,7 +1577,7 @@ void ED_region_panels(const bContext *C, ARegion *ar, int vertical, const char *
newcontext = UI_view2d_tab_set(v2d, contextnr);
if (vertical) {
- w = BLI_RCT_SIZE_X(&v2d->cur);
+ w = BLI_rctf_size_x(&v2d->cur);
em = (ar->type->prefsizex) ? UI_UNIT_Y / 2 : UI_UNIT_Y;
}
else {
@@ -1661,11 +1664,9 @@ void ED_region_panels(const bContext *C, ARegion *ar, int vertical, const char *
v2d->scroll |= V2D_SCROLL_HORIZONTAL_HIDE;
v2d->scroll &= ~V2D_SCROLL_VERTICAL_HIDE;
- /* don't jump back when panels close or hide */
- if (!newcontext)
- y = MAX2(-y, -v2d->cur.ymin);
- else
- y = -y;
+ /* ensure tot is set correctly, to keep views on bottons, with sliders */
+ y = min_ii(y, v2d->cur.ymin);
+ y = -y;
}
else {
/* for now, allow scrolling in both directions (since layouts are optimized for vertical,
@@ -1679,7 +1680,7 @@ void ED_region_panels(const bContext *C, ARegion *ar, int vertical, const char *
/* don't jump back when panels close or hide */
if (!newcontext)
- x = MAX2(x, v2d->cur.xmax);
+ x = max_ii(x, v2d->cur.xmax);
y = -y;
}
@@ -1732,7 +1733,7 @@ void ED_region_header(const bContext *C, ARegion *ar)
int maxco, xco, yco;
int headery = ED_area_headersize();
- /* clear */
+ /* clear */
UI_ThemeClearColor((ED_screen_area_active(C)) ? TH_HEADER : TH_HEADERDESEL);
glClear(GL_COLOR_BUFFER_BIT);
@@ -1769,7 +1770,7 @@ void ED_region_header(const bContext *C, ARegion *ar)
}
/* always as last */
- UI_view2d_totRect_set(&ar->v2d, maxco + UI_UNIT_X + 80, BLI_RCT_SIZE_Y(&ar->v2d.tot));
+ UI_view2d_totRect_set(&ar->v2d, maxco + UI_UNIT_X + 80, headery);
/* restore view matrix? */
UI_view2d_view_restore(C);
@@ -1798,16 +1799,16 @@ void ED_region_info_draw(ARegion *ar, const char *text, int block, float alpha)
/* background box */
rect = ar->winrct;
rect.xmin = 0;
- rect.ymin = BLI_RCT_SIZE_Y(&ar->winrct) - header_height;
+ rect.ymin = BLI_rcti_size_y(&ar->winrct) - header_height;
if (block) {
- rect.xmax = BLI_RCT_SIZE_X(&ar->winrct);
+ rect.xmax = BLI_rcti_size_x(&ar->winrct);
}
else {
rect.xmax = rect.xmin + BLF_width(fontid, text) + 24;
}
- rect.ymax = BLI_RCT_SIZE_Y(&ar->winrct);
+ rect.ymax = BLI_rcti_size_y(&ar->winrct);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
diff --git a/source/blender/editors/screen/glutil.c b/source/blender/editors/screen/glutil.c
index c93f4156eeb..ce2d045dc80 100644
--- a/source/blender/editors/screen/glutil.c
+++ b/source/blender/editors/screen/glutil.c
@@ -600,8 +600,8 @@ void glaDrawPixelsSafe(float x, float y, int img_w, int img_h, int row_w, int fo
/* The maximum pixel amounts the image can be cropped
* at the lower left without exceeding the origin.
*/
- int off_x = floor(MAX2(ix, 0));
- int off_y = floor(MAX2(iy, 0));
+ int off_x = floor(max_ff(ix, 0.0f));
+ int off_y = floor(max_ff(iy, 0.0f));
/* The zoomed space coordinate of the raster position
* (starting at the lower left most unclipped pixel).
@@ -625,8 +625,8 @@ void glaDrawPixelsSafe(float x, float y, int img_w, int img_h, int row_w, int fo
* covers the entire screen).
*/
glGetFloatv(GL_SCISSOR_BOX, scissor);
- draw_w = mini(img_w - off_x, ceil((scissor[2] - rast_x) / xzoom));
- draw_h = mini(img_h - off_y, ceil((scissor[3] - rast_y) / yzoom));
+ draw_w = min_ii(img_w - off_x, ceil((scissor[2] - rast_x) / xzoom));
+ draw_h = min_ii(img_h - off_y, ceil((scissor[3] - rast_y) / yzoom));
if (draw_w > 0 && draw_h > 0) {
int old_row_length = glaGetOneInteger(GL_UNPACK_ROW_LENGTH);
@@ -669,8 +669,8 @@ void glaDrawPixelsSafe(float x, float y, int img_w, int img_h, int row_w, int fo
void glaDefine2DArea(rcti *screen_rect)
{
- const int sc_w = BLI_RCT_SIZE_X(screen_rect) + 1;
- const int sc_h = BLI_RCT_SIZE_Y(screen_rect) + 1;
+ const int sc_w = BLI_rcti_size_x(screen_rect) + 1;
+ const int sc_h = BLI_rcti_size_y(screen_rect) + 1;
glViewport(screen_rect->xmin, screen_rect->ymin, sc_w, sc_h);
glScissor(screen_rect->xmin, screen_rect->ymin, sc_w, sc_h);
@@ -714,10 +714,10 @@ void gla2DSetMap(gla2DDrawInfo *di, rctf *rect)
di->world_rect = *rect;
- sc_w = BLI_RCT_SIZE_X(&di->screen_rect);
- sc_h = BLI_RCT_SIZE_Y(&di->screen_rect);
- wo_w = BLI_RCT_SIZE_X(&di->world_rect);
- wo_h = BLI_RCT_SIZE_Y(&di->world_rect);
+ sc_w = BLI_rcti_size_x(&di->screen_rect);
+ sc_h = BLI_rcti_size_y(&di->screen_rect);
+ wo_w = BLI_rcti_size_x(&di->world_rect);
+ wo_h = BLI_rcti_size_y(&di->world_rect);
di->wo_to_sc[0] = sc_w / wo_w;
di->wo_to_sc[1] = sc_h / wo_h;
@@ -745,10 +745,10 @@ gla2DDrawInfo *glaBegin2DDraw(rcti *screen_rect, rctf *world_rect)
di->world_rect.ymax = di->screen_rect.ymax;
}
- sc_w = BLI_RCT_SIZE_X(&di->screen_rect);
- sc_h = BLI_RCT_SIZE_Y(&di->screen_rect);
- wo_w = BLI_RCT_SIZE_X(&di->world_rect);
- wo_h = BLI_RCT_SIZE_Y(&di->world_rect);
+ sc_w = BLI_rcti_size_x(&di->screen_rect);
+ sc_h = BLI_rcti_size_y(&di->screen_rect);
+ wo_w = BLI_rcti_size_x(&di->world_rect);
+ wo_h = BLI_rcti_size_y(&di->world_rect);
di->wo_to_sc[0] = sc_w / wo_w;
di->wo_to_sc[1] = sc_h / wo_h;
diff --git a/source/blender/editors/screen/screen_context.c b/source/blender/editors/screen/screen_context.c
index 352039c5a61..a516603cfd4 100644
--- a/source/blender/editors/screen/screen_context.c
+++ b/source/blender/editors/screen/screen_context.c
@@ -194,7 +194,7 @@ int ed_screen_context(const bContext *C, const char *member, bContextDataResult
CTX_data_list_add(result, &arm->id, &RNA_EditBone, flipbone);
}
}
- }
+ }
CTX_data_type_set(result, CTX_DATA_TYPE_COLLECTION);
return 1;
}
@@ -236,7 +236,7 @@ int ed_screen_context(const bContext *C, const char *member, bContextDataResult
CTX_data_list_add(result, &arm->id, &RNA_EditBone, flipbone);
}
}
- }
+ }
CTX_data_type_set(result, CTX_DATA_TYPE_COLLECTION);
return 1;
}
diff --git a/source/blender/editors/screen/screen_edit.c b/source/blender/editors/screen/screen_edit.c
index 11d32e11cd0..60aad14efcf 100644
--- a/source/blender/editors/screen/screen_edit.c
+++ b/source/blender/editors/screen/screen_edit.c
@@ -36,10 +36,12 @@
#include "DNA_scene_types.h"
#include "DNA_userdef_types.h"
+#include "BLI_math.h"
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
#include "BKE_context.h"
+#include "BKE_depsgraph.h"
#include "BKE_global.h"
#include "BKE_library.h"
#include "BKE_main.h"
@@ -270,7 +272,7 @@ ScrEdge *screen_find_active_scredge(bScreen *sc, int mx, int my)
if (abs(my - se->v1->vec.y) <= 2 && mx >= min && mx <= max)
return se;
- }
+ }
else {
short min, max;
min = MIN2(se->v1->vec.y, se->v2->vec.y);
@@ -630,10 +632,8 @@ static void screen_test_scale(bScreen *sc, int winsizex, int winsizey)
max[0] = max[1] = 0.0f;
for (sv = sc->vertbase.first; sv; sv = sv->next) {
- min[0] = MIN2(min[0], sv->vec.x);
- min[1] = MIN2(min[1], sv->vec.y);
- max[0] = MAX2(max[0], sv->vec.x);
- max[1] = MAX2(max[1], sv->vec.y);
+ const float fv[2] = {(float)sv->vec.x, (float)sv->vec.y};
+ minmax_v2v2_v2(min, max, fv);
}
/* always make 0.0 left under */
@@ -704,10 +704,6 @@ static void screen_test_scale(bScreen *sc, int winsizex, int winsizey)
/* *********************** DRAWING **************************************** */
-
-#define SCR_BACK 0.55
-#define SCR_ROUND 12
-
/* draw vertical shape visualizing future joining (left as well
* right direction of future joining) */
static void draw_horizontal_join_shape(ScrArea *sa, char dir)
@@ -878,7 +874,7 @@ static void scrarea_draw_shape_light(ScrArea *sa, char UNUSED(dir))
glBlendFunc(GL_DST_COLOR, GL_SRC_ALPHA);
glEnable(GL_BLEND);
/* value 181 was hardly computed: 181~105 */
- glColor4ub(255, 255, 255, 50);
+ glColor4ub(255, 255, 255, 50);
/* draw_join_shape(sa, dir); */
glRecti(sa->v1->vec.x, sa->v1->vec.y, sa->v3->vec.x, sa->v3->vec.y);
glDisable(GL_BLEND);
@@ -1069,7 +1065,7 @@ static void screen_refresh_headersizes(void)
for (st = lb->first; st; st = st->next) {
ARegionType *art = BKE_regiontype_from_id(st, RGN_TYPE_HEADER);
if (art) art->prefsizey = ED_area_headersize();
- }
+ }
}
/* make this screen usable */
@@ -1323,7 +1319,7 @@ int ED_screen_area_active(const bContext *C)
for (ar = sa->regionbase.first; ar; ar = ar->next)
if (ar->swinid == sc->subwinactive)
return 1;
- }
+ }
return 0;
}
@@ -1456,10 +1452,10 @@ void ED_screen_set_scene(bContext *C, bScreen *screen, Scene *scene)
if (scene != sc->scene) {
/* all areas endlocalview */
- // XXX ScrArea *sa= sc->areabase.first;
+ // XXX ScrArea *sa = sc->areabase.first;
// while (sa) {
// endlocalview(sa);
- // sa= sa->next;
+ // sa = sa->next;
// }
sc->scene = scene;
}
@@ -1506,6 +1502,7 @@ void ED_screen_set_scene(bContext *C, bScreen *screen, Scene *scene)
CTX_data_scene_set(C, scene);
BKE_scene_set_background(bmain, scene);
+ DAG_on_visible_update(bmain, FALSE);
ED_render_engine_changed(bmain);
ED_update_for_newframe(bmain, scene, 1);
@@ -1735,7 +1732,7 @@ void ED_refresh_viewport_fps(bContext *C)
fpsi->redrawtime = fpsi->lredrawtime;
fpsi->lredrawtime = animtimer->ltime;
}
- else {
+ else {
/* playback stopped or shouldn't be running */
if (scene->fps_info)
MEM_freeN(scene->fps_info);
diff --git a/source/blender/editors/screen/screen_ops.c b/source/blender/editors/screen/screen_ops.c
index 50a210e5d7c..6a9c24d2913 100644
--- a/source/blender/editors/screen/screen_ops.c
+++ b/source/blender/editors/screen/screen_ops.c
@@ -192,7 +192,7 @@ int ED_operator_region_view3d_active(bContext *C)
return TRUE;
CTX_wm_operator_poll_msg_set(C, "expected a view3d region");
- return FALSE;
+ return FALSE;
}
/* generic for any view2d which uses anim_ops */
@@ -256,7 +256,7 @@ int ED_operator_node_active(bContext *C)
return 0;
}
-// XXX rename
+/* XXX rename */
int ED_operator_graphedit_active(bContext *C)
{
return ed_spacetype_test(C, SPACE_IPO);
@@ -372,6 +372,21 @@ int ED_operator_posemode_exclusive(bContext *C)
return 0;
}
+/* allows for pinned pose objects to be used in the object buttons
+ * and the the non-active pose object to be used in the 3D view */
+int ED_operator_posemode_context(bContext *C)
+{
+ Object *obpose = ED_pose_object_from_context(C);
+
+ if (obpose && !(obpose->mode & OB_MODE_EDIT)) {
+ if (BKE_object_pose_context_check(obpose)) {
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
int ED_operator_posemode(bContext *C)
{
Object *obact = CTX_data_active_object(C);
@@ -565,7 +580,7 @@ static int actionzone_area_poll(bContext *C)
for (az = sa->actionzones.first; az; az = az->next)
if (BLI_rcti_isect_pt(&az->rect, x, y))
return 1;
- }
+ }
return 0;
}
@@ -613,6 +628,7 @@ static void actionzone_apply(bContext *C, wmOperator *op, int type)
event.type = EVT_ACTIONZONE_AREA;
else
event.type = EVT_ACTIONZONE_REGION;
+ event.val = 0;
event.customdata = op->customdata;
event.customdatafree = TRUE;
op->customdata = NULL;
@@ -686,7 +702,7 @@ static int actionzone_modal(bContext *C, wmOperator *op, wmEvent *event)
case ESCKEY:
actionzone_exit(op);
return OPERATOR_CANCELLED;
- case LEFTMOUSE:
+ case LEFTMOUSE:
actionzone_exit(op);
return OPERATOR_CANCELLED;
@@ -954,18 +970,18 @@ static void area_move_set_limits(bScreen *sc, int dir, int *bigger, int *smaller
/* if top or down edge selected, test height */
if (sa->v1->flag && sa->v4->flag)
- *bigger = MIN2(*bigger, y1);
+ *bigger = min_ii(*bigger, y1);
else if (sa->v2->flag && sa->v3->flag)
- *smaller = MIN2(*smaller, y1);
+ *smaller = min_ii(*smaller, y1);
}
else {
int x1 = sa->v4->vec.x - sa->v1->vec.x - AREAMINX;
/* if left or right edge selected, test width */
if (sa->v1->flag && sa->v2->flag)
- *bigger = MIN2(*bigger, x1);
+ *bigger = min_ii(*bigger, x1);
else if (sa->v3->flag && sa->v4->flag)
- *smaller = MIN2(*smaller, x1);
+ *smaller = min_ii(*smaller, x1);
}
}
}
@@ -1196,9 +1212,6 @@ static void SCREEN_OT_area_move(wmOperatorType *ot)
* call exit() or cancel() and remove handler
*/
-#define SPLIT_STARTED 1
-#define SPLIT_PROGRESS 2
-
typedef struct sAreaSplitData {
int x, y; /* last used mouse position */
@@ -1329,7 +1342,7 @@ static int area_split_apply(bContext *C, wmOperator *op)
WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
return 1;
- }
+ }
return 0;
}
@@ -1635,10 +1648,10 @@ static int area_max_regionsize(ScrArea *sa, ARegion *scalear, AZEdge edge)
int dist;
if (edge == AE_RIGHT_TO_TOPLEFT || edge == AE_LEFT_TO_TOPRIGHT) {
- dist = BLI_RCT_SIZE_X(&sa->totrct);
+ dist = BLI_rcti_size_x(&sa->totrct);
}
else { /* AE_BOTTOM_TO_TOPLEFT, AE_TOP_TO_BOTTOMRIGHT */
- dist = BLI_RCT_SIZE_Y(&sa->totrct);
+ dist = BLI_rcti_size_y(&sa->totrct);
}
/* subtractwidth of regions on opposite side
@@ -1679,7 +1692,7 @@ static int region_scale_invoke(bContext *C, wmOperator *op, wmEvent *event)
AZone *az;
if (event->type != EVT_ACTIONZONE_REGION) {
- BKE_report(op->reports, RPT_ERROR, "Can only scale region size from an action zone");
+ BKE_report(op->reports, RPT_ERROR, "Can only scale region size from an action zone");
return OPERATOR_CANCELLED;
}
@@ -1843,7 +1856,7 @@ static int region_scale_modal(bContext *C, wmOperator *op, wmEvent *event)
break;
case ESCKEY:
- ;
+ break;
}
return OPERATOR_RUNNING_MODAL;
@@ -2059,15 +2072,23 @@ static void SCREEN_OT_keyframe_jump(wmOperatorType *ot)
/* ************** switch screen operator ***************************** */
+static int screen_set_is_ok(bScreen *screen, bScreen *screen_prev)
+{
+ return ((screen->winid == 0) &&
+ (screen->full == 0) &&
+ (screen != screen_prev) &&
+ (screen->id.name[2] != '.' || !(U.uiflag & USER_HIDE_DOT)));
+}
/* function to be called outside UI context, or for redo */
static int screen_set_exec(bContext *C, wmOperator *op)
{
+ Main *bmain = CTX_data_main(C);
bScreen *screen = CTX_wm_screen(C);
bScreen *screen_prev = screen;
ScrArea *sa = CTX_wm_area(C);
- int tot = BLI_countlist(&CTX_data_main(C)->screen);
+ int tot = BLI_countlist(&bmain->screen);
int delta = RNA_int_get(op->ptr, "delta");
/* temp screens are for userpref or render display */
@@ -2077,17 +2098,19 @@ static int screen_set_exec(bContext *C, wmOperator *op)
if (delta == 1) {
while (tot--) {
screen = screen->id.next;
- if (screen == NULL) screen = CTX_data_main(C)->screen.first;
- if (screen->winid == 0 && screen->full == 0 && screen != screen_prev)
+ if (screen == NULL) screen = bmain->screen.first;
+ if (screen_set_is_ok(screen, screen_prev)) {
break;
+ }
}
}
else if (delta == -1) {
while (tot--) {
screen = screen->id.prev;
- if (screen == NULL) screen = CTX_data_main(C)->screen.last;
- if (screen->winid == 0 && screen->full == 0 && screen != screen_prev)
+ if (screen == NULL) screen = bmain->screen.last;
+ if (screen_set_is_ok(screen, screen_prev)) {
break;
+ }
}
}
else {
@@ -2347,14 +2370,14 @@ static int area_join_modal(bContext *C, wmOperator *op, wmEvent *event)
ScrArea *sa = screen_areahascursor(sc, event->x, event->y);
int dir;
- if (sa) {
+ if (sa) {
if (jd->sa1 != sa) {
dir = area_getorientation(jd->sa1, sa);
if (dir >= 0) {
if (jd->sa2) jd->sa2->flag &= ~AREA_FLAG_DRAWJOINTO;
jd->sa2 = sa;
jd->sa2->flag |= AREA_FLAG_DRAWJOINTO;
- }
+ }
else {
/* we are not bordering on the previously selected area
* we check if area has common border with the one marked for removal
@@ -2368,14 +2391,14 @@ static int area_join_modal(bContext *C, wmOperator *op, wmEvent *event)
jd->sa2 = sa;
if (jd->sa1) jd->sa1->flag |= AREA_FLAG_DRAWJOINFROM;
if (jd->sa2) jd->sa2->flag |= AREA_FLAG_DRAWJOINTO;
- }
+ }
else {
if (jd->sa2) jd->sa2->flag &= ~AREA_FLAG_DRAWJOINTO;
jd->sa2 = NULL;
}
}
WM_event_add_notifier(C, NC_WINDOW, NULL);
- }
+ }
else {
/* we are back in the area previously selected for keeping
* we swap the areas if possible to allow user to choose */
@@ -2390,7 +2413,7 @@ static int area_join_modal(bContext *C, wmOperator *op, wmEvent *event)
if (dir < 0) {
printf("oops, didn't expect that!\n");
}
- }
+ }
else {
dir = area_getorientation(jd->sa1, sa);
if (dir >= 0) {
@@ -2704,6 +2727,8 @@ static int region_quadview_exec(bContext *C, wmOperator *op)
/* lock views and set them */
if (sa->spacetype == SPACE_VIEW3D) {
+ View3D *v3d = sa->spacedata.first;
+
/* run ED_view3d_lock() so the correct 'rv3d->viewquat' is set,
* otherwise when restoring rv3d->localvd the 'viewquat' won't
* match the 'view', set on entering localview See: [#26315],
@@ -2731,7 +2756,15 @@ static int region_quadview_exec(bContext *C, wmOperator *op)
ar = ar->next;
rv3d = ar->regiondata;
- rv3d->view = RV3D_VIEW_CAMERA; rv3d->persp = RV3D_CAMOB;
+
+ /* check if we have a camera */
+ if (v3d->camera) {
+ rv3d->view = RV3D_VIEW_CAMERA; rv3d->persp = RV3D_CAMOB;
+ }
+ else {
+ rv3d->view = RV3D_VIEW_PERSPORTHO; rv3d->persp = RV3D_PERSP;
+ }
+
ED_view3d_lock(rv3d);
view3d_localview_update_rv3d(rv3d);
}
@@ -2815,7 +2848,7 @@ static int header_flip_exec(bContext *C, wmOperator *UNUSED(op))
/* don't do anything if no region */
if (ar == NULL)
return OPERATOR_CANCELLED;
- }
+ }
/* copied from SCREEN_OT_region_flip */
if (ar->alignment == RGN_ALIGN_TOP)
@@ -2849,36 +2882,78 @@ static void SCREEN_OT_header_flip(wmOperatorType *ot)
ot->flag = 0;
}
-/* ************** header tools operator ***************************** */
-static int header_toolbox_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *UNUSED(event))
+
+/* ************** show menus operator ***************************** */
+
+/* show/hide header text menus */
+static int header_toggle_menus_exec(bContext *C, wmOperator *UNUSED(op))
{
ScrArea *sa = CTX_wm_area(C);
- ARegion *ar = CTX_wm_region(C);
- uiPopupMenu *pup;
- uiLayout *layout;
-
- pup = uiPupMenuBegin(C, "Header", ICON_NONE);
- layout = uiPupMenuLayout(pup);
+
+ sa->flag = sa->flag ^ HEADER_NO_PULLDOWN;
+
+ ED_area_tag_redraw(CTX_wm_area(C));
+ WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
+
+ return OPERATOR_FINISHED;
+}
+
+
+static void SCREEN_OT_header_toggle_menus(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Show/Hide Header Menus";
+ ot->idname = "SCREEN_OT_header_toggle_menus";
+ ot->description = "Show or hide the header pulldown menus";
- // XXX SCREEN_OT_region_flip doesn't work - gets wrong context for active region, so added custom operator
+ /* api callbacks */
+ ot->exec = header_toggle_menus_exec;
+ ot->poll = ED_operator_areaactive;
+ ot->flag = 0;
+}
+
+
+/* ************** header tools operator ***************************** */
+void ED_screens_header_tools_menu_create(bContext *C, uiLayout *layout, void *UNUSED(arg))
+{
+ ScrArea *sa = CTX_wm_area(C);
+ ARegion *ar = CTX_wm_region(C);
+
+ /* XXX SCREEN_OT_region_flip doesn't work - gets wrong context for active region, so added custom operator. */
if (ar->alignment == RGN_ALIGN_TOP)
- uiItemO(layout, "Flip to Bottom", ICON_NONE, "SCREEN_OT_header_flip");
+ uiItemO(layout, IFACE_("Flip to Bottom"), ICON_NONE, "SCREEN_OT_header_flip");
else
- uiItemO(layout, "Flip to Top", ICON_NONE, "SCREEN_OT_header_flip");
-
+ uiItemO(layout, IFACE_("Flip to Top"), ICON_NONE, "SCREEN_OT_header_flip");
+
+ if (sa->flag & HEADER_NO_PULLDOWN)
+ uiItemO(layout, IFACE_("Show Menus"), ICON_NONE, "SCREEN_OT_header_toggle_menus");
+ else
+ uiItemO(layout, IFACE_("Hide Menus"), ICON_NONE, "SCREEN_OT_header_toggle_menus");
+
uiItemS(layout);
-
+
/* file browser should be fullscreen all the time, but other regions can be maximized/restored... */
if (sa->spacetype != SPACE_FILE) {
if (sa->full)
- uiItemO(layout, "Tile Area", ICON_NONE, "SCREEN_OT_screen_full_area");
+ uiItemO(layout, IFACE_("Tile Area"), ICON_NONE, "SCREEN_OT_screen_full_area");
else
- uiItemO(layout, "Maximize Area", ICON_NONE, "SCREEN_OT_screen_full_area");
+ uiItemO(layout, IFACE_("Maximize Area"), ICON_NONE, "SCREEN_OT_screen_full_area");
}
-
+}
+
+static int header_toolbox_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *UNUSED(event))
+{
+ uiPopupMenu *pup;
+ uiLayout *layout;
+
+ pup = uiPupMenuBegin(C, N_("Header"), ICON_NONE);
+ layout = uiPupMenuLayout(pup);
+
+ ED_screens_header_tools_menu_create(C, layout, NULL);
+
uiPupMenuEnd(C, pup);
-
+
return OPERATOR_CANCELLED;
}
@@ -3008,7 +3083,11 @@ static int screen_animation_step(bContext *C, wmOperator *UNUSED(op), wmEvent *e
}
else {
if (sync) {
- int step = floor((wt->duration - sad->last_duration) * FPS);
+ /* note: this is very simplistic,
+ * its has problem that it may skip too many frames.
+ * however at least this gives a less jittery playback */
+ const int step = max_ii(1, floor((wt->duration - sad->last_duration) * FPS));
+
/* skip frames */
if (sad->flag & ANIMPLAY_FLAG_REVERSE)
scene->r.cfra -= step;
@@ -3077,11 +3156,12 @@ static int screen_animation_step(bContext *C, wmOperator *UNUSED(op), wmEvent *e
for (sa = window->screen->areabase.first; sa; sa = sa->next) {
ARegion *ar;
for (ar = sa->regionbase.first; ar; ar = ar->next) {
- if (ar == sad->ar)
+ if (ar == sad->ar) {
ED_region_tag_redraw(ar);
- else
- if (match_region_with_redraws(sa->spacetype, ar->regiontype, sad->redraws))
+ }
+ else if (match_region_with_redraws(sa->spacetype, ar->regiontype, sad->redraws)) {
ED_region_tag_redraw(ar);
+ }
}
if (match_area_with_refresh(sa->spacetype, sad->refresh))
@@ -3098,7 +3178,7 @@ static int screen_animation_step(bContext *C, wmOperator *UNUSED(op), wmEvent *e
/* recalculate the timestep for the timer now that we've finished calculating this,
* since the frames-per-second value may have been changed
*/
- // TODO: this may make evaluation a bit slower if the value doesn't change... any way to avoid this?
+ /* TODO: this may make evaluation a bit slower if the value doesn't change... any way to avoid this? */
wt->timestep = (1.0 / FPS);
return OPERATOR_FINISHED;
@@ -3148,7 +3228,7 @@ int ED_screen_animation_play(bContext *C, int sync, int mode)
else {
int refresh = SPACE_TIME; /* these settings are currently only available from a menu in the TimeLine */
- if (mode == 1) // XXX only play audio forwards!?
+ if (mode == 1) /* XXX only play audio forwards!? */
sound_play_scene(scene);
ED_screen_animation_timer(C, screen->redraws_flag, refresh, sync, mode);
@@ -3400,7 +3480,7 @@ static int screen_delete_exec(bContext *C, wmOperator *UNUSED(op))
static void SCREEN_OT_delete(wmOperatorType *ot)
{
/* identifiers */
- ot->name = "Delete Screen"; //was scene
+ ot->name = "Delete Screen"; /* was scene */
ot->description = "Delete active screen";
ot->idname = "SCREEN_OT_delete";
@@ -3520,6 +3600,7 @@ void ED_operatortypes_screen(void)
WM_operatortype_append(SCREEN_OT_region_scale);
WM_operatortype_append(SCREEN_OT_region_flip);
WM_operatortype_append(SCREEN_OT_header_flip);
+ WM_operatortype_append(SCREEN_OT_header_toggle_menus);
WM_operatortype_append(SCREEN_OT_header_toolbox);
WM_operatortype_append(SCREEN_OT_screen_set);
WM_operatortype_append(SCREEN_OT_screen_full_area);
@@ -3547,7 +3628,7 @@ void ED_operatortypes_screen(void)
/* tools shared by more space types */
WM_operatortype_append(ED_OT_undo);
WM_operatortype_append(ED_OT_undo_push);
- WM_operatortype_append(ED_OT_redo);
+ WM_operatortype_append(ED_OT_redo);
WM_operatortype_append(ED_OT_undo_history);
}
@@ -3717,7 +3798,7 @@ void ED_keymap_screen(wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "SCREEN_OT_animation_cancel", MEDIASTOP, KM_PRESS, 0, 0);
/* Alternative keys for animation and sequencer playing */
-#if 0 // XXX: disabled for restoring later... bad implementation
+#if 0 /* XXX: disabled for restoring later... bad implementation */
keymap = WM_keymap_find(keyconf, "Frames", 0, 0);
kmi = WM_keymap_add_item(keymap, "SCREEN_OT_animation_play", RIGHTARROWKEY, KM_PRESS, KM_ALT, 0);
RNA_boolean_set(kmi->ptr, "cycle_speed", TRUE);
diff --git a/source/blender/editors/screen/screendump.c b/source/blender/editors/screen/screendump.c
index 5e54119118a..0ecac5fc497 100644
--- a/source/blender/editors/screen/screendump.c
+++ b/source/blender/editors/screen/screendump.c
@@ -149,8 +149,8 @@ static void screenshot_crop(ImBuf *ibuf, rcti crop)
{
unsigned int *to = ibuf->rect;
unsigned int *from = ibuf->rect + crop.ymin * ibuf->x + crop.xmin;
- int crop_x = BLI_RCT_SIZE_X(&crop);
- int crop_y = BLI_RCT_SIZE_Y(&crop);
+ int crop_x = BLI_rcti_size_x(&crop);
+ int crop_y = BLI_rcti_size_y(&crop);
int y;
if (crop_x > 0 && crop_y > 0) {
@@ -214,7 +214,7 @@ static int screenshot_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event)
WM_event_add_fileselect(C, op);
return OPERATOR_RUNNING_MODAL;
- }
+ }
return OPERATOR_CANCELLED;
}
@@ -245,7 +245,7 @@ static void screenshot_draw(bContext *UNUSED(C), wmOperator *op)
/* image template */
RNA_pointer_create(NULL, &RNA_ImageFormatSettings, &scd->im_format, &ptr);
- uiTemplateImageSettings(layout, &ptr, TRUE);
+ uiTemplateImageSettings(layout, &ptr, FALSE);
/* main draw call */
RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
@@ -365,7 +365,7 @@ static void screenshot_startjob(void *sjv, short *stop, short *do_update, float
if (ok == 0) {
printf("Write error: cannot save %s\n", name);
- BKE_reportf(&sj->reports, RPT_INFO, "Write error: cannot save %s\n", name);
+ BKE_reportf(&sj->reports, RPT_INFO, "Write error: cannot save %s", name);
break;
}
else {
@@ -374,7 +374,7 @@ static void screenshot_startjob(void *sjv, short *stop, short *do_update, float
}
/* imbuf knows which rects are not part of ibuf */
- IMB_freeImBuf(ibuf);
+ IMB_freeImBuf(ibuf);
}
MEM_freeN(sj->dumprect);
@@ -408,7 +408,7 @@ static int screencast_exec(bContext *C, wmOperator *op)
sj->y = 0;
sj->dumpsx = win->sizex;
sj->dumpsy = win->sizey;
- }
+ }
else {
ScrArea *curarea = CTX_wm_area(C);
sj->x = curarea->totrct.xmin;
diff --git a/source/blender/editors/sculpt_paint/CMakeLists.txt b/source/blender/editors/sculpt_paint/CMakeLists.txt
index 043b7ecb5cb..ae72dce1415 100644
--- a/source/blender/editors/sculpt_paint/CMakeLists.txt
+++ b/source/blender/editors/sculpt_paint/CMakeLists.txt
@@ -20,6 +20,7 @@
set(INC
../include
+ ../uvedit
../../blenkernel
../../blenlib
../../blenloader
@@ -28,7 +29,6 @@ set(INC
../../imbuf
../../makesdna
../../makesrna
- ../uvedit
../../render/extern/include
../../windowmanager
../../../../intern/guardedalloc
diff --git a/source/blender/editors/sculpt_paint/paint_cursor.c b/source/blender/editors/sculpt_paint/paint_cursor.c
index 8616d4e66eb..5e23a144408 100644
--- a/source/blender/editors/sculpt_paint/paint_cursor.c
+++ b/source/blender/editors/sculpt_paint/paint_cursor.c
@@ -322,11 +322,16 @@ static int project_brush_radius(ViewContext *vc,
add_v3_v3v3(offset, location, ortho);
/* project the center of the brush, and the tangent point to the view onto the screen */
- project_float(vc->ar, location, p1);
- project_float(vc->ar, offset, p2);
-
- /* the distance between these points is the size of the projected brush in pixels */
- return len_v2v2(p1, p2);
+ if ((ED_view3d_project_float_global(vc->ar, location, p1, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
+ (ED_view3d_project_float_global(vc->ar, offset, p2, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
+ {
+ /* the distance between these points is the size of the projected brush in pixels */
+ return len_v2v2(p1, p2);
+ }
+ else {
+ BLI_assert(0); /* assert because the code that sets up the vectors should disallow this */
+ return 0;
+ }
}
static int sculpt_get_brush_geometry(bContext *C, ViewContext *vc,
@@ -335,7 +340,6 @@ static int sculpt_get_brush_geometry(bContext *C, ViewContext *vc,
{
Scene *scene = CTX_data_scene(C);
Paint *paint = paint_get_active_from_context(C);
- Brush *brush = paint_brush(paint);
float window[2];
int hit;
@@ -345,6 +349,7 @@ static int sculpt_get_brush_geometry(bContext *C, ViewContext *vc,
if (vc->obact->sculpt && vc->obact->sculpt->pbvh &&
sculpt_stroke_get_location(C, location, window))
{
+ Brush *brush = paint_brush(paint);
*pixel_radius =
project_brush_radius(vc,
BKE_brush_unprojected_radius_get(scene, brush),
@@ -441,8 +446,8 @@ static void paint_draw_alpha_overlay(Sculpt *sd, Brush *brush,
else {
quad.xmin = 0;
quad.ymin = 0;
- quad.xmax = BLI_RCT_SIZE_X(&vc->ar->winrct);
- quad.ymax = BLI_RCT_SIZE_Y(&vc->ar->winrct);
+ quad.xmax = BLI_rcti_size_x(&vc->ar->winrct);
+ quad.ymax = BLI_rcti_size_y(&vc->ar->winrct);
}
/* set quad color */
diff --git a/source/blender/editors/sculpt_paint/paint_hide.c b/source/blender/editors/sculpt_paint/paint_hide.c
index e809267d076..bdd73cd6db3 100644
--- a/source/blender/editors/sculpt_paint/paint_hide.c
+++ b/source/blender/editors/sculpt_paint/paint_hide.c
@@ -197,7 +197,7 @@ static void partialvis_update_grids(Object *ob,
for (x = 0; x < key.grid_size; x++) {
CCGElem *elem = CCG_grid_elem(&key, grids[g], x, y);
const float *co = CCG_elem_co(&key, elem);
- float mask = *CCG_elem_mask(&key, elem);
+ float mask = key.has_mask ? *CCG_elem_mask(&key, elem) : 0.0f;
/* skip grid element if not in the effected area */
if (is_effected(area, planes, co, mask)) {
@@ -251,7 +251,7 @@ static void clip_planes_from_rect(bContext *C,
view3d_operator_needs_opengl(C);
view3d_set_viewcontext(C, &vc);
view3d_get_transformation(vc.ar, vc.rv3d, vc.obact, &mats);
- ED_view3d_calc_clipping(&bb, clip_planes, &mats, rect);
+ ED_view3d_clipping_calc(&bb, clip_planes, &mats, rect);
mul_m4_fl(clip_planes, -1.0f);
}
@@ -388,7 +388,7 @@ void PAINT_OT_hide_show(struct wmOperatorType *ot)
ot->modal = WM_border_select_modal;
ot->exec = hide_show_exec;
/* sculpt-only for now */
- ot->poll = sculpt_mode_poll;
+ ot->poll = sculpt_mode_poll_view3d;
ot->flag = OPTYPE_REGISTER;
diff --git a/source/blender/editors/sculpt_paint/paint_image.c b/source/blender/editors/sculpt_paint/paint_image.c
index 64430a263f0..e00a8776bea 100644
--- a/source/blender/editors/sculpt_paint/paint_image.c
+++ b/source/blender/editors/sculpt_paint/paint_image.c
@@ -113,26 +113,26 @@
#define IMAPAINT_CHAR_TO_FLOAT(c) ((c) / 255.0f)
#define IMAPAINT_FLOAT_RGB_TO_CHAR(c, f) { \
- (c)[0]= FTOCHAR((f)[0]); \
- (c)[1]= FTOCHAR((f)[1]); \
- (c)[2]= FTOCHAR((f)[2]); \
+ (c)[0] = FTOCHAR((f)[0]); \
+ (c)[1] = FTOCHAR((f)[1]); \
+ (c)[2] = FTOCHAR((f)[2]); \
} (void)0
#define IMAPAINT_FLOAT_RGBA_TO_CHAR(c, f) { \
- (c)[0]= FTOCHAR((f)[0]); \
- (c)[1]= FTOCHAR((f)[1]); \
- (c)[2]= FTOCHAR((f)[2]); \
- (c)[3]= FTOCHAR((f)[3]); \
+ (c)[0] = FTOCHAR((f)[0]); \
+ (c)[1] = FTOCHAR((f)[1]); \
+ (c)[2] = FTOCHAR((f)[2]); \
+ (c)[3] = FTOCHAR((f)[3]); \
} (void)0
#define IMAPAINT_CHAR_RGB_TO_FLOAT(f, c) { \
- (f)[0]= IMAPAINT_CHAR_TO_FLOAT((c)[0]); \
- (f)[1]= IMAPAINT_CHAR_TO_FLOAT((c)[1]); \
- (f)[2]= IMAPAINT_CHAR_TO_FLOAT((c)[2]); \
+ (f)[0] = IMAPAINT_CHAR_TO_FLOAT((c)[0]); \
+ (f)[1] = IMAPAINT_CHAR_TO_FLOAT((c)[1]); \
+ (f)[2] = IMAPAINT_CHAR_TO_FLOAT((c)[2]); \
} (void)0
#define IMAPAINT_CHAR_RGBA_TO_FLOAT(f, c) { \
- (f)[0]= IMAPAINT_CHAR_TO_FLOAT((c)[0]); \
- (f)[1]= IMAPAINT_CHAR_TO_FLOAT((c)[1]); \
- (f)[2]= IMAPAINT_CHAR_TO_FLOAT((c)[2]); \
- (f)[3]= IMAPAINT_CHAR_TO_FLOAT((c)[3]); \
+ (f)[0] = IMAPAINT_CHAR_TO_FLOAT((c)[0]); \
+ (f)[1] = IMAPAINT_CHAR_TO_FLOAT((c)[1]); \
+ (f)[2] = IMAPAINT_CHAR_TO_FLOAT((c)[2]); \
+ (f)[3] = IMAPAINT_CHAR_TO_FLOAT((c)[3]); \
} (void)0
#define IMAPAINT_FLOAT_RGB_COPY(a, b) copy_v3_v3(a, b)
@@ -173,7 +173,7 @@ typedef struct ImagePaintState {
} ImagePaintState;
typedef struct ImagePaintPartialRedraw {
- int x1, y1, x2, y2;
+ int x1, y1, x2, y2; /* XXX, could use 'rcti' */
int enabled;
} ImagePaintPartialRedraw;
@@ -240,8 +240,6 @@ typedef struct ImagePaintRegion {
/* vert flags */
#define PROJ_VERT_CULL 1
-#define PI_80_DEG ((M_PI_2 / 9) * 8)
-
/* This is mainly a convenience struct used so we can keep an array of images we use
* Thir imbufs, etc, in 1 array, When using threads this array is copied for each thread
* because 'partRedrawRect' and 'touch' values would not be thread safe */
@@ -785,7 +783,7 @@ static int project_paint_PickColor(const ProjPaintState *ps, float pt[2], float
else {
//xi = (int)((uv[0]*ibuf->x) + 0.5f);
//yi = (int)((uv[1]*ibuf->y) + 0.5f);
- //if (xi<0 || xi>=ibuf->x || yi<0 || yi>=ibuf->y) return 0;
+ //if (xi < 0 || xi >= ibuf->x || yi < 0 || yi >= ibuf->y) return 0;
/* wrap */
xi = ((int)(uv[0] * ibuf->x)) % ibuf->x;
@@ -905,7 +903,7 @@ static int project_bucket_point_occluded(const ProjPaintState *ps, LinkNode *buc
else
isect_ret = project_paint_occlude_ptv(pixelScreenCo, ps->screenCoords[mf->v1], ps->screenCoords[mf->v2], ps->screenCoords[mf->v3], w, ps->is_ortho);
- /* Note, if isect_ret==-1 then we don't want to test the other side of the quad */
+ /* Note, if (isect_ret == -1) then we don't want to test the other side of the quad */
if (isect_ret == 0 && mf->v4) {
if (do_clip)
isect_ret = project_paint_occlude_ptv_clip(ps, mf, pixelScreenCo, ps->screenCoords[mf->v1], ps->screenCoords[mf->v3], ps->screenCoords[mf->v4], 1);
@@ -944,7 +942,7 @@ static int line_isect_y(const float p1[2], const float p2[2], const float y_leve
if (y_diff < 0.000001f) {
*x_isect = (p1[0] + p2[0]) * 0.5f;
- return ISECT_TRUE;
+ return ISECT_TRUE;
}
if (p1[1] > y_level && p2[1] < y_level) {
@@ -977,7 +975,7 @@ static int line_isect_x(const float p1[2], const float p2[2], const float x_leve
if (x_diff < 0.000001f) { /* yuck, vertical line, we cant do much here */
*y_isect = (p1[0] + p2[0]) * 0.5f;
- return ISECT_TRUE;
+ return ISECT_TRUE;
}
if (p1[0] > x_level && p2[0] < x_level) {
@@ -1005,7 +1003,7 @@ static int cmp_uv(const float vec2a[2], const float vec2b[2])
float ya = (float)fmodf(vec2a[1], 1.0f);
float xb = (float)fmodf(vec2b[0], 1.0f);
- float yb = (float)fmodf(vec2b[1], 1.0f);
+ float yb = (float)fmodf(vec2b[1], 1.0f);
if (xa < 0.0f) xa += 1.0f;
if (ya < 0.0f) ya += 1.0f;
@@ -1862,7 +1860,7 @@ static int project_bucket_isect_circle(const float cent[2], const float radius_s
/* lower left out of radius test */
if (cent[1] < bucket_bounds->ymin) {
return (len_squared_v2v2_alt(cent, bucket_bounds->xmin, bucket_bounds->ymin) < radius_squared) ? 1 : 0;
- }
+ }
/* top left test */
else if (cent[1] > bucket_bounds->ymax) {
return (len_squared_v2v2_alt(cent, bucket_bounds->xmin, bucket_bounds->ymax) < radius_squared) ? 1 : 0;
@@ -1872,7 +1870,7 @@ static int project_bucket_isect_circle(const float cent[2], const float radius_s
/* lower right out of radius test */
if (cent[1] < bucket_bounds->ymin) {
return (len_squared_v2v2_alt(cent, bucket_bounds->xmax, bucket_bounds->ymin) < radius_squared) ? 1 : 0;
- }
+ }
/* top right test */
else if (cent[1] > bucket_bounds->ymax) {
return (len_squared_v2v2_alt(cent, bucket_bounds->xmax, bucket_bounds->ymax) < radius_squared) ? 1 : 0;
@@ -2113,7 +2111,7 @@ static void project_bucket_clip_face(
if ((inside_bucket_flag & ISECT_2) == 0) { copy_v2_v2(isectVCosSS[*tot], v1_clipSS); (*tot)++; }
if ((inside_bucket_flag & ISECT_3) == 0) { copy_v2_v2(isectVCosSS[*tot], v2_clipSS); (*tot)++; }
}
- }
+ }
if ((inside_bucket_flag & (ISECT_3 | ISECT_1)) != (ISECT_3 | ISECT_1)) {
if (line_clip_rect2f(bucket_bounds, v3coSS, v1coSS, v1_clipSS, v2_clipSS)) {
@@ -2322,7 +2320,7 @@ static int IsectPoly2Df_twoside(const float pt[2], float uv[][2], const int tot)
return 1;
}
-/* One of the most important function for projectiopn painting, since it selects the pixels to be added into each bucket.
+/* One of the most important function for projection painting, since it selects the pixels to be added into each bucket.
* initialize pixels from this face where it intersects with the bucket_index, optionally initialize pixels for removing seams */
static void project_paint_face_init(const ProjPaintState *ps, const int thread_index, const int bucket_index, const int face_index, const int image_index, rctf *bucket_bounds, const ImBuf *ibuf, const short clamp_u, const short clamp_v)
{
@@ -2396,7 +2394,7 @@ static void project_paint_face_init(const ProjPaintState *ps, const int thread_i
tf_uv_pxoffset[1][1] = tf->uv[1][1] - yhalfpx;
tf_uv_pxoffset[2][0] = tf->uv[2][0] - xhalfpx;
- tf_uv_pxoffset[2][1] = tf->uv[2][1] - yhalfpx;
+ tf_uv_pxoffset[2][1] = tf->uv[2][1] - yhalfpx;
if (mf->v4) {
vCo[3] = ps->dm_mvert[mf->v4].co;
@@ -2556,7 +2554,6 @@ static void project_paint_face_init(const ProjPaintState *ps, const int thread_i
float (*outset_uv)[2] = ps->faceSeamUVs[face_index];
float insetCos[4][3]; /* inset face coords. NOTE!!! ScreenSace for ortho, Worldspace in prespective view */
- float fac;
float *vCoSS[4]; /* vertex screenspace coords */
float bucket_clip_edges[2][2]; /* store the screenspace coords of the face, clipped by the bucket's screen aligned rectangle */
@@ -2638,6 +2635,7 @@ static void project_paint_face_init(const ProjPaintState *ps, const int thread_i
/* test we're inside uvspace bucket and triangle bounds */
if (isect_point_quad_v2(uv, seam_subsection[0], seam_subsection[1], seam_subsection[2], seam_subsection[3])) {
+ float fac;
/* We need to find the closest point along the face edge,
* getting the screen_px_from_*** wont work because our actual location
@@ -2672,9 +2670,9 @@ static void project_paint_face_init(const ProjPaintState *ps, const int thread_i
#if 1
/* get the UV on the line since we want to copy the pixels from there for bleeding */
float uv_close[2];
- float fac = closest_to_line_v2(uv_close, uv, tf_uv_pxoffset[fidx1], tf_uv_pxoffset[fidx2]);
- if (fac < 0.0f) copy_v2_v2(uv_close, tf_uv_pxoffset[fidx1]);
- else if (fac > 1.0f) copy_v2_v2(uv_close, tf_uv_pxoffset[fidx2]);
+ float uv_fac = closest_to_line_v2(uv_close, uv, tf_uv_pxoffset[fidx1], tf_uv_pxoffset[fidx2]);
+ if (uv_fac < 0.0f) copy_v2_v2(uv_close, tf_uv_pxoffset[fidx1]);
+ else if (uv_fac > 1.0f) copy_v2_v2(uv_close, tf_uv_pxoffset[fidx2]);
if (side) {
barycentric_weights_v2(tf_uv_pxoffset[0], tf_uv_pxoffset[2], tf_uv_pxoffset[3], uv_close, w);
@@ -2685,16 +2683,16 @@ static void project_paint_face_init(const ProjPaintState *ps, const int thread_i
#else /* this is buggy with quads, don't use for now */
/* Cheat, we know where we are along the edge so work out the weights from that */
- fac = fac1 + (fac * (fac2 - fac1));
+ uv_fac = fac1 + (uv_fac * (fac2 - fac1));
w[0] = w[1] = w[2] = 0.0;
if (side) {
- w[fidx1 ? fidx1 - 1 : 0] = 1.0f - fac;
- w[fidx2 ? fidx2 - 1 : 0] = fac;
+ w[fidx1 ? fidx1 - 1 : 0] = 1.0f - uv_fac;
+ w[fidx2 ? fidx2 - 1 : 0] = uv_fac;
}
else {
- w[fidx1] = 1.0f - fac;
- w[fidx2] = fac;
+ w[fidx1] = 1.0f - uv_fac;
+ w[fidx2] = uv_fac;
}
#endif
}
@@ -3138,7 +3136,7 @@ static void project_paint_begin(ProjPaintState *ps)
ps->is_ortho = params.is_ortho;
}
- /* same as view3d_get_object_project_mat */
+ /* same as #ED_view3d_ob_project_mat_get */
mult_m4_m4m4(vmat, viewmat, ps->ob->obmat);
mult_m4_m4m4(ps->projectMat, winmat, vmat);
}
@@ -3434,7 +3432,7 @@ static void project_paint_begin_clone(ProjPaintState *ps, int mouse[2])
mul_m4_v4(ps->projectMat, projCo);
ps->cloneOffset[0] = mouse[0] - ((float)(ps->winx / 2.0f) + (ps->winx / 2.0f) * projCo[0] / projCo[3]);
ps->cloneOffset[1] = mouse[1] - ((float)(ps->winy / 2.0f) + (ps->winy / 2.0f) * projCo[1] / projCo[3]);
- }
+ }
}
static void project_paint_end(ProjPaintState *ps)
@@ -3563,7 +3561,7 @@ static void project_paint_end(ProjPaintState *ps)
ps->dm->release(ps->dm);
}
-/* 1= an undo, -1 is a redo. */
+/* 1 = an undo, -1 is a redo. */
static void partial_redraw_array_init(ImagePaintPartialRedraw *pr)
{
int tot = PROJ_BOUNDBOX_SQUARED;
@@ -3585,11 +3583,11 @@ static int partial_redraw_array_merge(ImagePaintPartialRedraw *pr, ImagePaintPar
{
int touch = 0;
while (tot--) {
- pr->x1 = MIN2(pr->x1, pr_other->x1);
- pr->y1 = MIN2(pr->y1, pr_other->y1);
+ pr->x1 = min_ii(pr->x1, pr_other->x1);
+ pr->y1 = min_ii(pr->y1, pr_other->y1);
- pr->x2 = MAX2(pr->x2, pr_other->x2);
- pr->y2 = MAX2(pr->y2, pr_other->y2);
+ pr->x2 = max_ii(pr->x2, pr_other->x2);
+ pr->y2 = max_ii(pr->y2, pr_other->y2);
if (pr->x2 != -1)
touch = 1;
@@ -4034,11 +4032,11 @@ static void *do_projectpaint_thread(void *ph_v)
/* end copy */
last_partial_redraw_cell = last_projIma->partRedrawRect + projPixel->bb_cell_index;
- last_partial_redraw_cell->x1 = MIN2(last_partial_redraw_cell->x1, projPixel->x_px);
- last_partial_redraw_cell->y1 = MIN2(last_partial_redraw_cell->y1, projPixel->y_px);
+ last_partial_redraw_cell->x1 = min_ii(last_partial_redraw_cell->x1, (int)projPixel->x_px);
+ last_partial_redraw_cell->y1 = min_ii(last_partial_redraw_cell->y1, (int)projPixel->y_px);
- last_partial_redraw_cell->x2 = MAX2(last_partial_redraw_cell->x2, projPixel->x_px + 1);
- last_partial_redraw_cell->y2 = MAX2(last_partial_redraw_cell->y2, projPixel->y_px + 1);
+ last_partial_redraw_cell->x2 = max_ii(last_partial_redraw_cell->x2, (int)projPixel->x_px + 1);
+ last_partial_redraw_cell->y2 = max_ii(last_partial_redraw_cell->y2, (int)projPixel->y_px + 1);
switch (tool) {
@@ -4102,7 +4100,7 @@ static int project_paint_op(void *state, ImBuf *UNUSED(ibufb), const float lastp
{
/* First unpack args from the struct */
ProjPaintState *ps = (ProjPaintState *)state;
- int touch_any = 0;
+ int touch_any = 0;
ProjectHandle handles[BLENDER_MAX_THREADS];
ListBase threads;
@@ -4135,7 +4133,7 @@ static int project_paint_op(void *state, ImBuf *UNUSED(ibufb), const float lastp
/* image bounds */
for (i = 0; i < ps->image_tot; i++) {
handles[a].projImages[i].partRedrawRect = (ImagePaintPartialRedraw *)BLI_memarena_alloc(ps->arena_mt[a], sizeof(ImagePaintPartialRedraw) * PROJ_BOUNDBOX_SQUARED);
- memcpy(handles[a].projImages[i].partRedrawRect, ps->projImages[i].partRedrawRect, sizeof(ImagePaintPartialRedraw) * PROJ_BOUNDBOX_SQUARED);
+ memcpy(handles[a].projImages[i].partRedrawRect, ps->projImages[i].partRedrawRect, sizeof(ImagePaintPartialRedraw) * PROJ_BOUNDBOX_SQUARED);
}
if (ps->thread_tot > 1)
@@ -4224,10 +4222,10 @@ static void imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w,
imapaintpartial.enabled = 1;
}
else {
- imapaintpartial.x1 = MIN2(imapaintpartial.x1, x);
- imapaintpartial.y1 = MIN2(imapaintpartial.y1, y);
- imapaintpartial.x2 = MAX2(imapaintpartial.x2, x + w);
- imapaintpartial.y2 = MAX2(imapaintpartial.y2, y + h);
+ imapaintpartial.x1 = min_ii(imapaintpartial.x1, x);
+ imapaintpartial.y1 = min_ii(imapaintpartial.y1, y);
+ imapaintpartial.x2 = max_ii(imapaintpartial.x2, x + w);
+ imapaintpartial.y2 = max_ii(imapaintpartial.y2, y + h);
}
w = ((x + w - 1) >> IMAPAINT_TILE_BITS);
@@ -4251,7 +4249,7 @@ static void imapaint_image_update(Scene *scene, SpaceImage *sima, Image *image,
IMB_partial_display_buffer_update(ibuf, ibuf->rect_float, (unsigned char *) ibuf->rect, ibuf->x, 0, 0,
&scene->view_settings, &scene->display_settings,
imapaintpartial.x1, imapaintpartial.y1,
- imapaintpartial.x2, imapaintpartial.y2);
+ imapaintpartial.x2, imapaintpartial.y2, FALSE);
}
else {
ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
@@ -4265,7 +4263,7 @@ static void imapaint_image_update(Scene *scene, SpaceImage *sima, Image *image,
int w = imapaintpartial.x2 - imapaintpartial.x1;
int h = imapaintpartial.y2 - imapaintpartial.y1;
/* Testing with partial update in uv editor too */
- GPU_paint_update_image(image, imapaintpartial.x1, imapaintpartial.y1, w, h, 0); //!texpaint);
+ GPU_paint_update_image(image, imapaintpartial.x1, imapaintpartial.y1, w, h); //!texpaint);
}
}
@@ -4556,7 +4554,7 @@ static int imapaint_canvas_set(ImagePaintState *s, Image *ima)
else if (ima->packedfile && ima->rr) {
s->warnpackedfile = ima->id.name + 2;
return 0;
- }
+ }
else if (ibuf && ibuf->channels != 4) {
s->warnmultifile = ima->id.name + 2;
return 0;
@@ -4596,10 +4594,13 @@ static int imapaint_paint_sub_stroke(ImagePaintState *s, BrushPainter *painter,
{
ImBuf *ibuf = BKE_image_get_ibuf(image, s->sima ? &s->sima->iuser : NULL);
float pos[2];
+ int is_data;
if (!ibuf)
return 0;
+ is_data = ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA;
+
pos[0] = uv[0] * ibuf->x;
pos[1] = uv[1] * ibuf->y;
@@ -4608,7 +4609,7 @@ static int imapaint_paint_sub_stroke(ImagePaintState *s, BrushPainter *painter,
/* OCIO_TODO: float buffers are now always linear, so always use color correction
* this should probably be changed when texture painting color space is supported
*/
- if (BKE_brush_painter_paint(painter, imapaint_paint_op, pos, time, pressure, s, TRUE)) {
+ if (BKE_brush_painter_paint(painter, imapaint_paint_op, pos, time, pressure, s, is_data == FALSE)) {
if (update)
imapaint_image_update(s->scene, s->sima, image, ibuf, texpaint);
return 1;
@@ -5047,7 +5048,7 @@ static void paint_apply(bContext *C, wmOperator *op, PointerRNA *itemptr)
pop->prevmouse[1] = mouse[1];
}
- else {
+ else {
redraw = imapaint_paint_stroke(&pop->vc, &pop->s, pop->painter, pop->mode == PAINT_MODE_3D, pop->prevmouse, mouse, time, pressure);
pop->prevmouse[0] = mouse[0];
pop->prevmouse[1] = mouse[1];
@@ -5065,7 +5066,7 @@ static void paint_brush_exit_tex(Brush *brush)
MTex *mtex = &brush->mtex;
if (mtex->tex && mtex->tex->nodetree)
ntreeTexEndExecTree(mtex->tex->nodetree->execdata, 1);
- }
+ }
}
static void paint_exit(bContext *C, wmOperator *op)
@@ -5265,10 +5266,12 @@ static int get_imapaint_zoom(bContext *C, float *zoomx, float *zoomy)
if (!rv3d) {
SpaceImage *sima = CTX_wm_space_image(C);
ARegion *ar = CTX_wm_region(C);
-
- ED_space_image_get_zoom(sima, ar, zoomx, zoomy);
- return 1;
+ if (sima->mode == SI_MODE_PAINT) {
+ ED_space_image_get_zoom(sima, ar, zoomx, zoomy);
+
+ return 1;
+ }
}
*zoomx = *zoomy = 1;
@@ -5284,24 +5287,21 @@ static void brush_drawcursor(bContext *C, int x, int y, void *UNUSED(customdata)
#define PX_SIZE_FADE_MIN 4.0f
Scene *scene = CTX_data_scene(C);
- //Brush *brush= image_paint_brush(C);
+ //Brush *brush = image_paint_brush(C);
Paint *paint = paint_get_active_from_context(C);
Brush *brush = paint_brush(paint);
if (paint && brush && paint->flags & PAINT_SHOW_BRUSH) {
- ToolSettings *ts;
float zoomx, zoomy;
const float size = (float)BKE_brush_size_get(scene, brush);
short use_zoom;
float pixel_size;
float alpha = 0.5f;
- ts = scene->toolsettings;
- use_zoom = get_imapaint_zoom(C, &zoomx, &zoomy) &&
- !(ts->use_uv_sculpt && (scene->basact->object->mode == OB_MODE_EDIT));
+ use_zoom = get_imapaint_zoom(C, &zoomx, &zoomy);
if (use_zoom) {
- pixel_size = size * maxf(zoomx, zoomy);
+ pixel_size = size * max_ff(zoomx, zoomy);
}
else {
pixel_size = size;
@@ -5365,7 +5365,7 @@ void ED_space_image_paint_update(wmWindowManager *wm, ToolSettings *settings)
for (win = wm->windows.first; win; win = win->next)
for (sa = win->screen->areabase.first; sa; sa = sa->next)
if (sa->spacetype == SPACE_IMAGE)
- if (((SpaceImage*)sa->spacedata.first)->mode == SI_MODE_PAINT)
+ if (((SpaceImage *)sa->spacedata.first)->mode == SI_MODE_PAINT)
enabled = TRUE;
if (enabled) {
@@ -5653,7 +5653,7 @@ static int texture_paint_toggle_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
if (BKE_object_obdata_is_libdata(ob)) {
- BKE_report(op->reports, RPT_ERROR, "Can't edit external libdata");
+ BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
return OPERATOR_CANCELLED;
}
@@ -5889,7 +5889,7 @@ static int texture_paint_image_from_view_exec(bContext *C, wmOperator *op)
if (!ibuf) {
/* Mostly happens when OpenGL offscreen buffer was failed to create, */
/* but could be other reasons. Should be handled in the future. nazgul */
- BKE_reportf(op->reports, RPT_ERROR, "Failed to create OpenGL offscreen buffer: %s", err_out);
+ BKE_reportf(op->reports, RPT_ERROR, "Failed to create OpenGL off-screen buffer: %s", err_out);
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/sculpt_paint/paint_intern.h b/source/blender/editors/sculpt_paint/paint_intern.h
index 794e7755636..162e2fa15d6 100644
--- a/source/blender/editors/sculpt_paint/paint_intern.h
+++ b/source/blender/editors/sculpt_paint/paint_intern.h
@@ -51,7 +51,7 @@ struct wmOperator;
struct wmOperatorType;
/* paint_stroke.c */
-typedef int (*StrokeGetLocation)(struct bContext *C, float location[3], float mouse[2]);
+typedef int (*StrokeGetLocation)(struct bContext *C, float location[3], const float mouse[2]);
typedef int (*StrokeTestStart)(struct bContext *C, struct wmOperator *op, const float mouse[2]);
typedef void (*StrokeUpdateStep)(struct bContext *C, struct PaintStroke *stroke, struct PointerRNA *itemptr);
typedef void (*StrokeDone)(const struct bContext *C, struct PaintStroke *stroke);
diff --git a/source/blender/editors/sculpt_paint/paint_mask.c b/source/blender/editors/sculpt_paint/paint_mask.c
index e309bdb99cb..697d7c63d1f 100644
--- a/source/blender/editors/sculpt_paint/paint_mask.c
+++ b/source/blender/editors/sculpt_paint/paint_mask.c
@@ -54,6 +54,7 @@
#include "WM_types.h"
#include "ED_screen.h"
+#include "ED_sculpt.h"
#include "paint_intern.h"
#include "sculpt_intern.h" /* for undo push */
@@ -77,7 +78,9 @@ static void mask_flood_fill_set_elem(float *elem,
static int mask_flood_fill_exec(bContext *C, wmOperator *op)
{
ARegion *ar = CTX_wm_region(C);
+ struct Scene *scene = CTX_data_scene(C);
Object *ob = CTX_data_active_object(C);
+ struct MultiresModifierData *mmd = sculpt_multires_active(scene, ob);
PaintMaskFloodMode mode;
float value;
DerivedMesh *dm;
@@ -88,7 +91,9 @@ static int mask_flood_fill_exec(bContext *C, wmOperator *op)
mode = RNA_enum_get(op->ptr, "mode");
value = RNA_float_get(op->ptr, "value");
- dm = mesh_get_derived_final(CTX_data_scene(C), ob, CD_MASK_BAREMESH);
+ ED_sculpt_mask_layers_ensure(ob, mmd);
+
+ dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
pbvh = dm->getPBVH(ob, dm);
ob->sculpt->pbvh = pbvh;
diff --git a/source/blender/editors/sculpt_paint/paint_ops.c b/source/blender/editors/sculpt_paint/paint_ops.c
index 39a95300d5d..40dcb92f087 100644
--- a/source/blender/editors/sculpt_paint/paint_ops.c
+++ b/source/blender/editors/sculpt_paint/paint_ops.c
@@ -93,7 +93,7 @@ static int brush_scale_size_exec(bContext *C, wmOperator *op)
Scene *scene = CTX_data_scene(C);
Paint *paint = paint_get_active_from_context(C);
struct Brush *brush = paint_brush(paint);
- // Object *ob= CTX_data_active_object(C);
+ // Object *ob = CTX_data_active_object(C);
float scalar = RNA_float_get(op->ptr, "scalar");
if (brush) {
diff --git a/source/blender/editors/sculpt_paint/paint_stroke.c b/source/blender/editors/sculpt_paint/paint_stroke.c
index 7657f78596a..6396a0c2cbc 100644
--- a/source/blender/editors/sculpt_paint/paint_stroke.c
+++ b/source/blender/editors/sculpt_paint/paint_stroke.c
@@ -139,13 +139,13 @@ static float event_tablet_data(wmEvent *event, int *pen_flip)
}
/* Put the location of the next stroke dot into the stroke RNA and apply it to the mesh */
-static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, wmEvent *event, float mouse_in[2])
+static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, wmEvent *event, const float mouse_in[2])
{
Scene *scene = CTX_data_scene(C);
Paint *paint = paint_get_active_from_context(C);
Brush *brush = paint_brush(paint);
PaintStroke *stroke = op->customdata;
- float mouse[3];
+ float mouse_out[2];
PointerRNA itemptr;
float location[3];
float pressure;
@@ -159,24 +159,24 @@ static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, wmEvent *ev
if (stroke->vc.obact->sculpt) {
float delta[2];
- BKE_brush_jitter_pos(scene, brush, mouse_in, mouse);
+ BKE_brush_jitter_pos(scene, brush, mouse_in, mouse_out);
/* XXX: meh, this is round about because
* BKE_brush_jitter_pos isn't written in the best way to
* be reused here */
if (brush->flag & BRUSH_JITTER_PRESSURE) {
- sub_v2_v2v2(delta, mouse, mouse_in);
+ sub_v2_v2v2(delta, mouse_out, mouse_in);
mul_v2_fl(delta, pressure);
- add_v2_v2v2(mouse, mouse_in, delta);
+ add_v2_v2v2(mouse_out, mouse_in, delta);
}
}
else {
- copy_v2_v2(mouse, mouse_in);
+ copy_v2_v2(mouse_out, mouse_in);
}
/* TODO: can remove the if statement once all modes have this */
if (stroke->get_location)
- stroke->get_location(C, location, mouse);
+ stroke->get_location(C, location, mouse_out);
else
zero_v3(location);
@@ -184,12 +184,11 @@ static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, wmEvent *ev
RNA_collection_add(op->ptr, "stroke", &itemptr);
RNA_float_set_array(&itemptr, "location", location);
- RNA_float_set_array(&itemptr, "mouse", mouse);
+ RNA_float_set_array(&itemptr, "mouse", mouse_out);
RNA_boolean_set(&itemptr, "pen_flip", pen_flip);
RNA_float_set(&itemptr, "pressure", pressure);
- stroke->last_mouse_position[0] = mouse[0];
- stroke->last_mouse_position[1] = mouse[1];
+ copy_v2_v2(stroke->last_mouse_position, mouse_out);
stroke->update_step(C, stroke, &itemptr);
}
@@ -256,7 +255,7 @@ static int paint_space_stroke(bContext *C, wmOperator *op, wmEvent *event, const
if (pressure > FLT_EPSILON) {
/* brushes can have a minimum size of 1.0 but with pressure it can be smaller then a pixel
* causing very high step sizes, hanging blender [#32381] */
- const float size_clamp = maxf(1.0f, BKE_brush_size_get(scene, stroke->brush) * pressure);
+ const float size_clamp = max_ff(1.0f, BKE_brush_size_get(scene, stroke->brush) * pressure);
scale = (size_clamp * stroke->brush->spacing / 50.0f) / length;
if (scale > FLT_EPSILON) {
mul_v2_fl(vec, scale);
@@ -407,10 +406,10 @@ int paint_stroke_modal(bContext *C, wmOperator *op, wmEvent *event)
paint_stroke_add_sample(p, stroke, event->x, event->y);
paint_stroke_sample_average(stroke, &sample_average);
- // let NDOF motion pass through to the 3D view so we can paint and rotate simultaneously!
- // this isn't perfect... even when an extra MOUSEMOVE is spoofed, the stroke discards it
- // since the 2D deltas are zero -- code in this file needs to be updated to use the
- // post-NDOF_MOTION MOUSEMOVE
+ /* let NDOF motion pass through to the 3D view so we can paint and rotate simultaneously!
+ * this isn't perfect... even when an extra MOUSEMOVE is spoofed, the stroke discards it
+ * since the 2D deltas are zero -- code in this file needs to be updated to use the
+ * post-NDOF_MOTION MOUSEMOVE */
if (event->type == NDOF_MOTION)
return OPERATOR_PASS_THROUGH;
@@ -524,8 +523,10 @@ int paint_poll(bContext *C)
{
Paint *p = paint_get_active_from_context(C);
Object *ob = CTX_data_active_object(C);
+ ScrArea *sa = CTX_wm_area(C);
+ ARegion *ar = CTX_wm_region(C);
return p && ob && paint_brush(p) &&
- CTX_wm_area(C)->spacetype == SPACE_VIEW3D &&
- CTX_wm_region(C)->regiontype == RGN_TYPE_WINDOW;
+ (sa && sa->spacetype == SPACE_VIEW3D) &&
+ (ar && ar->regiontype == RGN_TYPE_WINDOW);
}
diff --git a/source/blender/editors/sculpt_paint/paint_undo.c b/source/blender/editors/sculpt_paint/paint_undo.c
index f5b9aa742c6..e406d4f5c3b 100644
--- a/source/blender/editors/sculpt_paint/paint_undo.c
+++ b/source/blender/editors/sculpt_paint/paint_undo.c
@@ -152,7 +152,9 @@ static int undo_stack_step(bContext *C, UndoStack *stack, int step, const char *
UndoElem *undo;
if (step == 1) {
- if (stack->current == NULL) ;
+ if (stack->current == NULL) {
+ /* pass */
+ }
else {
if (!name || strcmp(stack->current->name, name) == 0) {
if (G.debug & G_DEBUG_WM) {
@@ -165,7 +167,9 @@ static int undo_stack_step(bContext *C, UndoStack *stack, int step, const char *
}
}
else if (step == -1) {
- if ((stack->current != NULL && stack->current->next == NULL) || stack->elems.first == NULL) ;
+ if ((stack->current != NULL && stack->current->next == NULL) || stack->elems.first == NULL) {
+ /* pass */
+ }
else {
if (!name || strcmp(stack->current->name, name) == 0) {
undo = (stack->current && stack->current->next) ? stack->current->next : stack->elems.first;
@@ -254,7 +258,9 @@ int ED_undo_paint_valid(int type, const char *name)
else
return 0;
- if (stack->current == NULL) ;
+ if (stack->current == NULL) {
+ /* pass */
+ }
else {
if (name && strcmp(stack->current->name, name) == 0)
return 1;
diff --git a/source/blender/editors/sculpt_paint/paint_utils.c b/source/blender/editors/sculpt_paint/paint_utils.c
index df64e1c9d90..c5eff1a1f0e 100644
--- a/source/blender/editors/sculpt_paint/paint_utils.c
+++ b/source/blender/editors/sculpt_paint/paint_utils.c
@@ -98,7 +98,7 @@ int paint_convert_bb_to_rect(rcti *rect,
vec[1] = j ? bb_min[1] : bb_max[1];
vec[2] = k ? bb_min[2] : bb_max[2];
/* convert corner to screen space */
- ED_view3d_project_float_v2(ar, vec, proj, projection_mat);
+ ED_view3d_project_float_v2_m4(ar, vec, proj, projection_mat);
/* expand 2D rectangle */
/* we could project directly to int? */
@@ -137,7 +137,7 @@ void paint_calc_redraw_planes(float planes[4][4],
rect.ymin -= 2;
rect.ymax += 2;
- ED_view3d_calc_clipping(&bb, planes, &mats, &rect);
+ ED_view3d_clipping_calc(&bb, planes, &mats, &rect);
mul_m4_fl(planes, -1.0f);
}
@@ -201,7 +201,7 @@ static void imapaint_project(Object *ob, float model[][4], float proj[][4], cons
static void imapaint_tri_weights(Object *ob,
const float v1[3], const float v2[3], const float v3[3],
- const float co[3], float w[3])
+ const float co[2], float w[3])
{
float pv1[4], pv2[4], pv3[4], h[3], divw;
float model[4][4], proj[4][4], wmat[3][3], invwmat[3][3];
@@ -248,19 +248,25 @@ static void imapaint_tri_weights(Object *ob,
void imapaint_pick_uv(Scene *scene, Object *ob, unsigned int faceindex, const int xy[2], float uv[2])
{
DerivedMesh *dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
- const int *index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
MTFace *tface = dm->getTessFaceDataArray(dm, CD_MTFACE), *tf;
int numfaces = dm->getNumTessFaces(dm), a, findex;
float p[2], w[3], absw, minabsw;
MFace mf;
MVert mv[4];
+ /* double lookup */
+ const int *index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX);
+ if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) {
+ index_mf_to_mpoly = index_mp_to_orig = NULL;
+ }
+
minabsw = 1e10;
uv[0] = uv[1] = 0.0;
/* test all faces in the derivedmesh with the original index of the picked face */
for (a = 0; a < numfaces; a++) {
- findex = index ? index[a] : a;
+ findex = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, a) : a;
if (findex == faceindex) {
dm->getTessFace(dm, a, &mf);
diff --git a/source/blender/editors/sculpt_paint/paint_vertex.c b/source/blender/editors/sculpt_paint/paint_vertex.c
index fd5044afc44..56d46a22e10 100644
--- a/source/blender/editors/sculpt_paint/paint_vertex.c
+++ b/source/blender/editors/sculpt_paint/paint_vertex.c
@@ -79,6 +79,7 @@
#include "WM_api.h"
#include "WM_types.h"
+#include "GPU_buffers.h"
#include "ED_armature.h"
#include "ED_mesh.h"
@@ -106,18 +107,40 @@ static int vertex_paint_use_fast_update_check(Object *ob)
/* if the polygons from the mesh and the 'derivedFinal' match
* we can assume that no modifiers are applied and that its worth adding tessellated faces
* so 'vertex_paint_use_fast_update_check()' returns TRUE */
-static int vertex_paint_use_tessface_check(Object *ob)
+static int vertex_paint_use_tessface_check(Object *ob, Mesh *me)
{
DerivedMesh *dm = ob->derivedFinal;
- if (dm) {
- Mesh *me = BKE_mesh_from_object(ob);
- return (me->mpoly == CustomData_get_layer(&dm->faceData, CD_MPOLY));
+ if (me && dm) {
+ return (me->mpoly == CustomData_get_layer(&dm->polyData, CD_MPOLY));
}
return FALSE;
}
+static void update_tessface_data(Object *ob, Mesh *me)
+{
+ if (vertex_paint_use_tessface_check(ob, me)) {
+ /* assume if these exist, that they are up to date & valid */
+ if (!me->mcol || !me->mface) {
+ /* should always be true */
+ /* XXX Why this clearing? tessface_calc will reset it anyway! */
+/* if (me->mcol) {*/
+/* memset(me->mcol, 255, 4 * sizeof(MCol) * me->totface);*/
+/* }*/
+
+ /* create tessfaces because they will be used for drawing & fast updates */
+ BKE_mesh_tessface_calc(me); /* does own call to update pointers */
+ }
+ }
+ else {
+ if (me->totface) {
+ /* this wont be used, theres no need to keep it */
+ BKE_mesh_tessface_clear(me);
+ }
+ }
+
+}
/* polling - retrieve whether cursor should be set or operator should be done */
/* Returns true if vertex paint mode is active */
@@ -134,7 +157,7 @@ int vertex_paint_poll(bContext *C)
paint_brush(&CTX_data_tool_settings(C)->vpaint->paint))
{
ScrArea *sa = CTX_wm_area(C);
- if (sa->spacetype == SPACE_VIEW3D) {
+ if (sa && sa->spacetype == SPACE_VIEW3D) {
ARegion *ar = CTX_wm_region(C);
if (ar->regiontype == RGN_TYPE_WINDOW)
return 1;
@@ -326,29 +349,12 @@ static void make_vertexcol(Object *ob) /* single ob */
CustomData_add_layer(&me->fdata, CD_MCOL, CD_DEFAULT, NULL, me->totface);
}
if (!me->mloopcol) {
- CustomData_add_layer(&me->ldata, CD_MLOOPCOL, CD_DEFAULT, NULL, me->totloop);
+ CustomData_add_layer(&me->ldata, CD_MLOOPCOL, CD_DEFAULT, NULL, me->totloop);
}
mesh_update_customdata_pointers(me, TRUE);
}
- if (vertex_paint_use_tessface_check(ob)) {
- /* assume if these exist, that they are up to date & valid */
- if (!me->mcol || !me->mface) {
- /* should always be true */
- if (me->mcol) {
- memset(me->mcol, 255, 4 * sizeof(MCol) * me->totface);
- }
-
- /* create tessfaces because they will be used for drawing & fast updates */
- BKE_mesh_tessface_calc(me); /* does own call to update pointers */
- }
- }
- else {
- if (me->totface) {
- /* this wont be used, theres no need to keep it */
- BKE_mesh_tessface_clear(me);
- }
- }
+ update_tessface_data(ob, me);
//if (shade)
// shadeMeshMCol(scene, ob, me);
@@ -846,20 +852,22 @@ static int sample_backbuf_area(ViewContext *vc, int *indexar, int totface, int x
static float calc_vp_strength_dl(VPaint *vp, ViewContext *vc, const float vert_nor[3],
const float mval[2], const float brush_size_pressure)
{
- Brush *brush = paint_brush(&vp->paint);
- float dist_squared;
- float vertco[2], delta[2];
+ float vertco[2];
- project_float_noclip(vc->ar, vert_nor, vertco);
- sub_v2_v2v2(delta, mval, vertco);
- dist_squared = dot_v2v2(delta, delta); /* len squared */
- if (dist_squared > brush_size_pressure * brush_size_pressure) {
- return 0.0f;
- }
- else {
- const float dist = sqrtf(dist_squared);
- return BKE_brush_curve_strength_clamp(brush, dist, brush_size_pressure);
+ if (ED_view3d_project_float_global(vc->ar, vert_nor, vertco, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ float delta[2];
+ float dist_squared;
+
+ sub_v2_v2v2(delta, mval, vertco);
+ dist_squared = dot_v2v2(delta, delta); /* len squared */
+ if (dist_squared <= brush_size_pressure * brush_size_pressure) {
+ Brush *brush = paint_brush(&vp->paint);
+ const float dist = sqrtf(dist_squared);
+ return BKE_brush_curve_strength_clamp(brush, dist, brush_size_pressure);
+ }
}
+
+ return 0.0f;
}
static float calc_vp_alpha_dl(VPaint *vp, ViewContext *vc,
@@ -1524,7 +1532,7 @@ static void enforce_locks(MDeformVert *odv, MDeformVert *ndv,
if (total_changed > 1 && do_multipaint) {
float undo_change = get_mp_change(ndv, defbase_tot, defbase_sel, left_over);
multipaint_selection(ndv, defbase_tot, undo_change, defbase_sel);
- }
+ }
/* or designatedw is still -1 put weight back as evenly as possible */
else {
redistribute_change(ndv, defbase_tot, change_status, 2, -2, left_over, total_changed, do_auto_normalize);
@@ -1533,7 +1541,6 @@ static void enforce_locks(MDeformVert *odv, MDeformVert *ndv,
}
else {
/* reset the weights */
- unsigned int i;
MDeformWeight *dw_old = odv->dw;
MDeformWeight *dw_new = ndv->dw;
@@ -2047,7 +2054,6 @@ static int wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UNU
Object *ob = CTX_data_active_object(C);
struct WPaintData *wpd;
Mesh *me;
- bDeformGroup *dg;
float mat[4][4], imat[4][4];
@@ -2096,12 +2102,14 @@ static int wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UNU
return FALSE;
}
- /* check if we are attempting to paint onto a locked vertex group,
- * and other options disallow it from doing anything useful */
- dg = BLI_findlink(&ob->defbase, (ob->actdef - 1));
- if (dg->flag & DG_LOCK_WEIGHT) {
- BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
- return FALSE;
+ {
+ /* check if we are attempting to paint onto a locked vertex group,
+ * and other options disallow it from doing anything useful */
+ bDeformGroup *dg = BLI_findlink(&ob->defbase, (ob->actdef - 1));
+ if (dg->flag & DG_LOCK_WEIGHT) {
+ BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
+ return FALSE;
+ }
}
/* ALLOCATIONS! no return after this line */
@@ -2227,19 +2235,7 @@ static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, P
if (indexar[0]) totindex = 1;
else totindex = 0;
}
-
- if (wp->flag & VP_COLINDEX) {
- for (index = 0; index < totindex; index++) {
- if (indexar[index] && indexar[index] <= me->totpoly) {
- MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
-
- if (mpoly->mat_nr != ob->actcol - 1) {
- indexar[index] = 0;
- }
- }
- }
- }
-
+
if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
for (index = 0; index < totindex; index++) {
if (indexar[index] && indexar[index] <= me->totpoly) {
@@ -2382,7 +2378,8 @@ static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
{
-
+ int retval;
+
op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
wpaint_stroke_update_step,
wpaint_stroke_done, event->type);
@@ -2390,7 +2387,9 @@ static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
/* add modal handler */
WM_event_add_modal_handler(C, op);
- op->type->modal(C, op, event);
+ retval = op->type->modal(C, op, event);
+ OPERATOR_RETVAL_CHECK(retval);
+ BLI_assert(retval == OPERATOR_RUNNING_MODAL);
return OPERATOR_RUNNING_MODAL;
}
@@ -2571,7 +2570,7 @@ static void vpaint_build_poly_facemap(struct VPaintData *vd, Mesh *me)
vd->polyfacemap = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(ListBase) * me->totpoly);
- origIndex = CustomData_get_layer(&me->fdata, CD_POLYINDEX);
+ origIndex = CustomData_get_layer(&me->fdata, CD_ORIGINDEX);
mf = me->mface;
if (!origIndex)
@@ -2607,7 +2606,12 @@ static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const fl
make_vertexcol(ob);
if (me->mloopcol == NULL)
return OPERATOR_CANCELLED;
-
+
+ /* Update tessface data if needed
+ * Added here too because e.g. switching to/from edit mode would remove tessface data,
+ * yet "fast_update" could still be used! */
+ update_tessface_data(ob, me);
+
/* make mode data storage */
vpd = MEM_callocN(sizeof(struct VPaintData), "VPaintData");
paint_stroke_set_mode_data(stroke, vpd);
@@ -2623,9 +2627,11 @@ static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const fl
if (vertex_paint_use_fast_update_check(ob)) {
vpaint_build_poly_facemap(vpd, me);
vpd->use_fast_update = TRUE;
+/* printf("Fast update!\n");*/
}
else {
vpd->use_fast_update = FALSE;
+/* printf("No fast update!\n");*/
}
/* for filtering */
@@ -2639,53 +2645,6 @@ static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const fl
return 1;
}
-#if 0
-static void vpaint_paint_face(VPaint *vp, VPaintData *vpd, Object *ob,
- const unsigned int index, const float mval[2],
- const float brush_size_pressure, const float brush_alpha_pressure,
- int UNUSED(flip))
-{
- ViewContext *vc = &vpd->vc;
- Brush *brush = paint_brush(&vp->paint);
- Mesh *me = BKE_mesh_from_object(ob);
- MFace *mface = &me->mface[index];
- unsigned int *mcol = ((unsigned int *)me->mcol) + 4 * index;
- unsigned int *mcolorig = ((unsigned int *)vp->vpaint_prev) + 4 * index;
- float alpha;
- int i;
-
- int brush_alpha_pressure_i;
-
- if ((vp->flag & VP_COLINDEX && mface->mat_nr != ob->actcol - 1) ||
- ((me->editflag & ME_EDIT_PAINT_MASK) && !(mface->flag & ME_FACE_SEL)))
- return;
-
- if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
- unsigned int fcol1 = mcol_blend(mcol[0], mcol[1], 128);
- if (mface->v4) {
- unsigned int fcol2 = mcol_blend(mcol[2], mcol[3], 128);
- vpd->paintcol = mcol_blend(fcol1, fcol2, 128);
- }
- else {
- vpd->paintcol = mcol_blend(mcol[2], fcol1, 170);
- }
- }
-
- brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
-
- for (i = 0; i < (mface->v4 ? 4 : 3); ++i) {
- alpha = calc_vp_alpha_dl(vp, vc, vpd->vpimat, vpd->vertexcosnos + 6 * (&mface->v1)[i],
- mval, brush_size_pressure, brush_alpha_pressure);
- if (alpha) {
- const int alpha_i = (int)(alpha * 255.0f);
- mcol[i] = vpaint_blend(vp, mcol[i], mcolorig[i], vpd->paintcol, alpha_i, brush_alpha_pressure_i);
- }
- }
-}
-#endif
-
-/* BMESH version of vpaint_paint_face (commented above) */
-
static void vpaint_paint_poly(VPaint *vp, VPaintData *vpd, Object *ob,
const unsigned int index, const float mval[2],
const float brush_size_pressure, const float brush_alpha_pressure)
@@ -2744,33 +2703,29 @@ static void vpaint_paint_poly(VPaint *vp, VPaintData *vpd, Object *ob,
}
if (vpd->use_fast_update) {
-
-#ifdef CPYCOL
-# undef CPYCOL
-#endif
-#define CPYCOL(c, l) (c)->a = (l)->a, (c)->r = (l)->r, (c)->g = (l)->g, (c)->b = (l)->b
-
/* update vertex colors for tessellations incrementally,
* rather then regenerating the tessellation altogether */
for (e = vpd->polyfacemap[index].first; e; e = e->next) {
- mf = me->mface + e->facenr;
- mc = me->mcol + e->facenr * 4;
+ mf = &me->mface[e->facenr];
+ mc = &me->mcol[e->facenr * 4];
ml = me->mloop + mpoly->loopstart;
mlc = me->mloopcol + mpoly->loopstart;
for (j = 0; j < mpoly->totloop; j++, ml++, mlc++) {
- if (ml->v == mf->v1)
- CPYCOL(mc, mlc);
- else if (ml->v == mf->v2)
- CPYCOL(mc + 1, mlc);
- else if (ml->v == mf->v3)
- CPYCOL(mc + 2, mlc);
- else if (mf->v4 && ml->v == mf->v4)
- CPYCOL(mc + 3, mlc);
-
+ if (ml->v == mf->v1) {
+ MESH_MLOOPCOL_TO_MCOL(mlc, mc + 0);
+ }
+ else if (ml->v == mf->v2) {
+ MESH_MLOOPCOL_TO_MCOL(mlc, mc + 1);
+ }
+ else if (ml->v == mf->v3) {
+ MESH_MLOOPCOL_TO_MCOL(mlc, mc + 2);
+ }
+ else if (mf->v4 && ml->v == mf->v4) {
+ MESH_MLOOPCOL_TO_MCOL(mlc, mc + 3);
+ }
}
}
-#undef CPYCOL
}
}
@@ -2804,7 +2759,7 @@ static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, P
mval[0] -= vc->ar->winrct.xmin;
mval[1] -= vc->ar->winrct.ymin;
-
+
/* which faces are involved */
if (vp->flag & VP_AREA) {
totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
@@ -2814,19 +2769,6 @@ static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, P
if (indexar[0]) totindex = 1;
else totindex = 0;
}
-
-
- if (vp->flag & VP_COLINDEX) {
- for (index = 0; index < totindex; index++) {
- if (indexar[index] && indexar[index] <= me->totpoly) {
- MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
-
- if (mpoly->mat_nr != ob->actcol - 1) {
- indexar[index] = 0;
- }
- }
- }
- }
if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
for (index = 0; index < totindex; index++) {
@@ -2835,15 +2777,13 @@ static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, P
if ((mpoly->flag & ME_FACE_SEL) == 0)
indexar[index] = 0;
- }
+ }
}
}
swap_m4m4(vc->rv3d->persmat, mat);
-
for (index = 0; index < totindex; index++) {
-
if (indexar[index] && indexar[index] <= me->totpoly) {
vpaint_paint_poly(vp, vpd, ob, indexar[index] - 1, mval, brush_size_pressure, brush_alpha_pressure);
}
@@ -2864,6 +2804,10 @@ static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, P
* avoid this if we can! */
DAG_id_tag_update(ob->data, 0);
}
+ else if (!GPU_buffer_legacy(ob->derivedFinal)) {
+ /* If using new VBO drawing, mark mcol as dirty to force colors gpu buffer refresh! */
+ ob->derivedFinal->dirty |= DM_DIRTY_MCOL_UPDATE_DRAW;
+ }
}
static void vpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
@@ -2891,7 +2835,8 @@ static void vpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
{
-
+ int retval;
+
op->customdata = paint_stroke_new(C, NULL, vpaint_stroke_test_start,
vpaint_stroke_update_step,
vpaint_stroke_done, event->type);
@@ -2899,7 +2844,9 @@ static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
/* add modal handler */
WM_event_add_modal_handler(C, op);
- op->type->modal(C, op, event);
+ retval = op->type->modal(C, op, event);
+ OPERATOR_RETVAL_CHECK(retval);
+ BLI_assert(retval == OPERATOR_RUNNING_MODAL);
return OPERATOR_RUNNING_MODAL;
}
diff --git a/source/blender/editors/sculpt_paint/sculpt.c b/source/blender/editors/sculpt_paint/sculpt.c
index 210477e3e5a..38dbdcd8337 100644
--- a/source/blender/editors/sculpt_paint/sculpt.c
+++ b/source/blender/editors/sculpt_paint/sculpt.c
@@ -771,7 +771,7 @@ static float tex_strength(SculptSession *ss, Brush *br, float point[3],
if (ss->cache->radial_symmetry_pass)
mul_m4_v3(ss->cache->symm_rot_mat_inv, symm_point);
- ED_view3d_project_float_v2(ss->cache->vc->ar, symm_point, point_2d, ss->cache->projection_mat);
+ ED_view3d_project_float_v2_m4(ss->cache->vc->ar, symm_point, point_2d, ss->cache->projection_mat);
if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
/* keep coordinates relative to mouse */
@@ -1225,7 +1225,7 @@ static void do_mesh_smooth_brush(Sculpt *sd, SculptSession *ss, PBVHNode *node,
if (sculpt_brush_test(&test, vd.co)) {
const float fade = bstrength * tex_strength(ss, brush, vd.co, test.dist,
ss->cache->view_normal, vd.no, vd.fno,
- smooth_mask ? 0 : *vd.mask);
+ smooth_mask ? 0 : (vd.mask ? *vd.mask : 0.0f));
if (smooth_mask) {
float val = neighbor_average_mask(ss, vd.vert_indices[vd.i]) - *vd.mask;
val *= fade * bstrength;
@@ -1524,7 +1524,7 @@ static void do_draw_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
/* offset vertex */
float fade = tex_strength(ss, brush, vd.co, test.dist,
ss->cache->sculpt_normal_symm, vd.no,
- vd.fno, *vd.mask);
+ vd.fno, vd.mask ? *vd.mask : 0.0f);
mul_v3_v3fl(proxy[vd.i], offset, fade);
@@ -1580,7 +1580,7 @@ static void do_crease_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnod
/* offset vertex */
const float fade = tex_strength(ss, brush, vd.co, test.dist,
ss->cache->sculpt_normal_symm,
- vd.no, vd.fno, *vd.mask);
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f);
float val1[3];
float val2[3];
@@ -1623,7 +1623,7 @@ static void do_pinch_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode
if (sculpt_brush_test(&test, vd.co)) {
float fade = bstrength * tex_strength(ss, brush, vd.co, test.dist,
ss->cache->view_normal, vd.no,
- vd.fno, *vd.mask);
+ vd.fno, vd.mask ? *vd.mask : 0.0f);
float val[3];
sub_v3_v3v3(val, test.location, vd.co);
@@ -1677,7 +1677,8 @@ static void do_grab_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
{
if (sculpt_brush_test(&test, origco[vd.i])) {
const float fade = bstrength * tex_strength(ss, brush, origco[vd.i], test.dist,
- ss->cache->sculpt_normal_symm, origno[vd.i], NULL, *vd.mask);
+ ss->cache->sculpt_normal_symm, origno[vd.i],
+ NULL, vd.mask ? *vd.mask : 0.0f);
mul_v3_v3fl(proxy[vd.i], grab_delta, fade);
@@ -1718,7 +1719,7 @@ static void do_nudge_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode
if (sculpt_brush_test(&test, vd.co)) {
const float fade = bstrength * tex_strength(ss, brush, vd.co, test.dist,
ss->cache->sculpt_normal_symm,
- vd.no, vd.fno, *vd.mask);
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f);
mul_v3_v3fl(proxy[vd.i], cono, fade);
@@ -1767,7 +1768,7 @@ static void do_snake_hook_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int to
if (sculpt_brush_test(&test, vd.co)) {
const float fade = bstrength * tex_strength(ss, brush, vd.co, test.dist,
ss->cache->sculpt_normal_symm,
- vd.no, vd.fno, *vd.mask);
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f);
mul_v3_v3fl(proxy[vd.i], grab_delta, fade);
@@ -1815,7 +1816,7 @@ static void do_thumb_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode
if (sculpt_brush_test(&test, origco[vd.i])) {
const float fade = bstrength * tex_strength(ss, brush, origco[vd.i], test.dist,
ss->cache->sculpt_normal_symm,
- origno[vd.i], NULL, *vd.mask);
+ origno[vd.i], NULL, vd.mask ? *vd.mask : 0.0f);
mul_v3_v3fl(proxy[vd.i], cono, fade);
@@ -1868,7 +1869,7 @@ static void do_rotate_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnod
if (sculpt_brush_test(&test, origco[vd.i])) {
const float fade = bstrength * tex_strength(ss, brush, origco[vd.i], test.dist,
ss->cache->sculpt_normal_symm,
- origno[vd.i], NULL, *vd.mask);
+ origno[vd.i], NULL, vd.mask ? *vd.mask : 0.0f);
mul_v3_m4v3(proxy[vd.i], m, origco[vd.i]);
sub_v3_v3(proxy[vd.i], origco[vd.i]);
@@ -1921,7 +1922,7 @@ static void do_layer_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode
if (sculpt_brush_test(&test, origco[vd.i])) {
const float fade = bstrength * tex_strength(ss, brush, vd.co, test.dist,
ss->cache->sculpt_normal_symm,
- vd.no, vd.fno, *vd.mask);
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f);
float *disp = &layer_disp[vd.i];
float val[3];
@@ -1974,7 +1975,8 @@ static void do_inflate_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totno
{
if (sculpt_brush_test(&test, vd.co)) {
const float fade = bstrength * tex_strength(ss, brush, vd.co, test.dist,
- ss->cache->view_normal, vd.no, vd.fno, *vd.mask);
+ ss->cache->view_normal,
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f);
float val[3];
if (vd.fno) copy_v3_v3(val, vd.fno);
@@ -2315,7 +2317,7 @@ static void do_flatten_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totno
if (plane_trim(ss->cache, brush, val)) {
const float fade = bstrength * tex_strength(ss, brush, vd.co, sqrt(test.dist),
- an, vd.no, vd.fno, *vd.mask);
+ an, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f);
mul_v3_v3fl(proxy[vd.i], val, fade);
@@ -2389,7 +2391,7 @@ static void do_clay_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
if (plane_trim(ss->cache, brush, val)) {
const float fade = bstrength * tex_strength(ss, brush, vd.co,
sqrt(test.dist),
- an, vd.no, vd.fno, *vd.mask);
+ an, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f);
mul_v3_v3fl(proxy[vd.i], val, fade);
@@ -2491,7 +2493,7 @@ static void do_clay_strips_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int t
if (plane_trim(ss->cache, brush, val)) {
const float fade = bstrength * tex_strength(ss, brush, vd.co,
ss->cache->radius * test.dist,
- an, vd.no, vd.fno, *vd.mask);
+ an, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f);
mul_v3_v3fl(proxy[vd.i], val, fade);
@@ -2555,7 +2557,7 @@ static void do_fill_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
if (plane_trim(ss->cache, brush, val)) {
const float fade = bstrength * tex_strength(ss, brush, vd.co,
sqrt(test.dist),
- an, vd.no, vd.fno, *vd.mask);
+ an, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f);
mul_v3_v3fl(proxy[vd.i], val, fade);
@@ -2619,7 +2621,7 @@ static void do_scrape_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnod
if (plane_trim(ss->cache, brush, val)) {
const float fade = bstrength * tex_strength(ss, brush, vd.co,
sqrt(test.dist),
- an, vd.no, vd.fno, *vd.mask);
+ an, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f);
mul_v3_v3fl(proxy[vd.i], val, fade);
@@ -2649,7 +2651,7 @@ void sculpt_vertcos_to_key(Object *ob, KeyBlock *kb, float (*vertCos)[3])
}
if (is_basis) {
- ofs = key_to_vertcos(ob, kb);
+ ofs = BKE_key_convert_to_vertcos(ob, kb);
/* calculate key coord offsets (from previous location) */
for (a = 0; a < me->totvert; a++) {
@@ -2662,7 +2664,7 @@ void sculpt_vertcos_to_key(Object *ob, KeyBlock *kb, float (*vertCos)[3])
int apply_offset = ((currkey != kb) && (ob->shapenr - 1 == currkey->relative));
if (apply_offset)
- offset_to_key(ob, currkey, ofs);
+ BKE_key_convert_from_offset(ob, currkey, ofs);
currkey = currkey->next;
}
@@ -2683,7 +2685,7 @@ void sculpt_vertcos_to_key(Object *ob, KeyBlock *kb, float (*vertCos)[3])
}
/* apply new coords on active key block */
- vertcos_to_key(ob, kb, vertCos);
+ BKE_key_convert_from_vertcos(ob, kb, vertCos);
}
static void do_brush_action(Sculpt *sd, Object *ob, Brush *brush)
@@ -3062,7 +3064,11 @@ static void sculpt_update_tex(const Scene *scene, Sculpt *sd, SculptSession *ss)
}
}
-void sculpt_update_mesh_elements(Scene *scene, Sculpt *sd, Object *ob, int need_pmap)
+/**
+ * \param need_mask So the DerivedMesh thats returned has mask data
+ */
+void sculpt_update_mesh_elements(Scene *scene, Sculpt *sd, Object *ob,
+ int need_pmap, int need_mask)
{
DerivedMesh *dm;
SculptSession *ss = ob->sculpt;
@@ -3070,11 +3076,33 @@ void sculpt_update_mesh_elements(Scene *scene, Sculpt *sd, Object *ob, int need_
MultiresModifierData *mmd = sculpt_multires_active(scene, ob);
ss->modifiers_active = sculpt_modifiers_active(scene, sd, ob);
+ ss->show_diffuse_color = sd->flags & SCULPT_SHOW_DIFFUSE;
+
+ if (need_mask) {
+ if (mmd == NULL) {
+ if (!CustomData_has_layer(&me->vdata, CD_PAINT_MASK)) {
+ ED_sculpt_mask_layers_ensure(ob, NULL);
+ }
+ }
+ else {
+ if (!CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
+#if 1
+ ED_sculpt_mask_layers_ensure(ob, mmd);
+#else /* if we wanted to support adding mask data while multi-res painting, we would need to do this */
+ if ((ED_sculpt_mask_layers_ensure(ob, mmd) & ED_SCULPT_MASK_LAYER_CALC_LOOP)) {
+ /* remake the derived mesh */
+ ob->recalc |= OB_RECALC_DATA;
+ BKE_object_handle_update(scene, ob);
+ }
+#endif
+ }
+ }
+ }
/* BMESH ONLY --- at some point we should move sculpt code to use polygons only - but for now it needs tessfaces */
BKE_mesh_tessface_ensure(me);
- if (!mmd) ss->kb = ob_get_keyblock(ob);
+ if (!mmd) ss->kb = BKE_keyblock_from_object(ob);
else ss->kb = NULL;
/* needs to be called after we ensure tessface */
@@ -3103,13 +3131,15 @@ void sculpt_update_mesh_elements(Scene *scene, Sculpt *sd, Object *ob, int need_
ss->pbvh = dm->getPBVH(ob, dm);
ss->pmap = (need_pmap && dm->getPolyMap) ? dm->getPolyMap(ob, dm) : NULL;
+ pbvh_show_diffuse_color_set(ss->pbvh, ss->show_diffuse_color);
+
if (ss->modifiers_active) {
if (!ss->orig_cos) {
int a;
free_sculptsession_deformMats(ss);
- ss->orig_cos = (ss->kb) ? key_to_vertcos(ob, ss->kb) : mesh_getVertexCos(me, NULL);
+ ss->orig_cos = (ss->kb) ? BKE_key_convert_to_vertcos(ob, ss->kb) : mesh_getVertexCos(me, NULL);
crazyspace_build_sculpt(scene, ob, &ss->deform_imats, &ss->deform_cos);
BLI_pbvh_apply_vertCos(ss->pbvh, ss->deform_cos);
@@ -3123,7 +3153,7 @@ void sculpt_update_mesh_elements(Scene *scene, Sculpt *sd, Object *ob, int need_
/* if pbvh is deformed, key block is already applied to it */
if (ss->kb && !BLI_pbvh_isDeformed(ss->pbvh)) {
- float (*vertCos)[3] = key_to_vertcos(ob, ss->kb);
+ float (*vertCos)[3] = BKE_key_convert_to_vertcos(ob, ss->kb);
if (vertCos) {
/* apply shape keys coordinates to PBVH */
@@ -3139,6 +3169,11 @@ int sculpt_mode_poll(bContext *C)
return ob && ob->mode & OB_MODE_SCULPT;
}
+int sculpt_mode_poll_view3d(bContext *C)
+{
+ return (sculpt_mode_poll(C) && CTX_wm_region_view3d(C));
+}
+
int sculpt_poll(bContext *C)
{
return sculpt_mode_poll(C) && paint_poll(C);
@@ -3481,7 +3516,7 @@ static void sculpt_update_brush_delta(Sculpt *sd, Object *ob, Brush *brush)
if (tool == SCULPT_TOOL_GRAB)
copy_v3_v3(sd->anchored_location, cache->true_location);
else if (tool == SCULPT_TOOL_THUMB)
- copy_v3_v3(sd->anchored_location, cache->orig_grab_location);
+ copy_v3_v3(sd->anchored_location, cache->orig_grab_location);
if (ELEM(tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_THUMB)) {
/* location stays the same for finding vertices in brush radius */
@@ -3504,8 +3539,6 @@ static void sculpt_update_cache_variants(bContext *C, Sculpt *sd, Object *ob,
StrokeCache *cache = ss->cache;
Brush *brush = paint_brush(&sd->paint);
- int dx, dy;
-
/* RNA_float_get_array(ptr, "location", cache->traced_location); */
if (cache->first_time ||
@@ -3574,8 +3607,8 @@ static void sculpt_update_cache_variants(bContext *C, Sculpt *sd, Object *ob,
if (brush->flag & BRUSH_ANCHORED) {
int hit = 0;
- dx = cache->mouse[0] - cache->initial_mouse[0];
- dy = cache->mouse[1] - cache->initial_mouse[1];
+ const float dx = cache->mouse[0] - cache->initial_mouse[0];
+ const float dy = cache->mouse[1] - cache->initial_mouse[1];
sd->anchored_size = cache->pixel_radius = sqrt(dx * dx + dy * dy);
@@ -3585,8 +3618,8 @@ static void sculpt_update_cache_variants(bContext *C, Sculpt *sd, Object *ob,
float halfway[2];
float out[3];
- halfway[0] = (float)dx * 0.5f + cache->initial_mouse[0];
- halfway[1] = (float)dy * 0.5f + cache->initial_mouse[1];
+ halfway[0] = dx * 0.5f + cache->initial_mouse[0];
+ halfway[1] = dy * 0.5f + cache->initial_mouse[1];
if (sculpt_stroke_get_location(C, out, halfway)) {
copy_v3_v3(sd->anchored_location, out);
@@ -3633,8 +3666,8 @@ static void sculpt_update_cache_variants(bContext *C, Sculpt *sd, Object *ob,
sculpt_update_brush_delta(sd, ob, brush);
if (brush->sculpt_tool == SCULPT_TOOL_ROTATE) {
- dx = cache->mouse[0] - cache->initial_mouse[0];
- dy = cache->mouse[1] - cache->initial_mouse[1];
+ const float dx = cache->mouse[0] - cache->initial_mouse[0];
+ const float dy = cache->mouse[1] - cache->initial_mouse[1];
cache->vertex_rotation = -atan2f(dx, dy) * cache->bstrength;
@@ -3671,7 +3704,7 @@ static void sculpt_stroke_modifiers_check(const bContext *C, Object *ob)
Brush *brush = paint_brush(&sd->paint);
sculpt_update_mesh_elements(CTX_data_scene(C), sd, ob,
- sculpt_any_smooth_mode(brush, ss->cache, 0));
+ sculpt_any_smooth_mode(brush, ss->cache, 0), FALSE);
}
}
@@ -3706,7 +3739,7 @@ static void sculpt_raycast_cb(PBVHNode *node, void *data_v, float *tmin)
* (This allows us to ignore the GL depth buffer)
* Returns 0 if the ray doesn't hit the mesh, non-zero otherwise
*/
-int sculpt_stroke_get_location(bContext *C, float out[3], float mouse[2])
+int sculpt_stroke_get_location(bContext *C, float out[3], const float mouse[2])
{
ViewContext vc;
Object *ob;
@@ -3777,12 +3810,17 @@ static int sculpt_brush_stroke_init(bContext *C, wmOperator *op)
Brush *brush = paint_brush(&sd->paint);
int mode = RNA_enum_get(op->ptr, "mode");
int is_smooth = 0;
+ int need_mask = FALSE;
+
+ if (brush->sculpt_tool == SCULPT_TOOL_MASK) {
+ need_mask = TRUE;
+ }
view3d_operator_needs_opengl(C);
sculpt_brush_init_tex(scene, sd, ss);
is_smooth = sculpt_any_smooth_mode(brush, NULL, mode);
- sculpt_update_mesh_elements(scene, sd, ob, is_smooth);
+ sculpt_update_mesh_elements(scene, sd, ob, is_smooth, need_mask);
return 1;
}
@@ -3961,6 +3999,7 @@ static int sculpt_brush_stroke_invoke(bContext *C, wmOperator *op, wmEvent *even
{
struct PaintStroke *stroke;
int ignore_background_click;
+ int retval;
if (!sculpt_brush_stroke_init(C, op))
return OPERATOR_CANCELLED;
@@ -3984,7 +4023,9 @@ static int sculpt_brush_stroke_invoke(bContext *C, wmOperator *op, wmEvent *even
/* add modal handler */
WM_event_add_modal_handler(C, op);
- op->type->modal(C, op, event);
+ retval = op->type->modal(C, op, event);
+ OPERATOR_RETVAL_CHECK(retval);
+ BLI_assert(retval == OPERATOR_RUNNING_MODAL);
return OPERATOR_RUNNING_MODAL;
}
@@ -4098,13 +4139,14 @@ static void sculpt_init_session(Scene *scene, Object *ob)
{
ob->sculpt = MEM_callocN(sizeof(SculptSession), "sculpt session");
- sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, 0);
+ sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, 0, FALSE);
}
-void ED_sculpt_mask_layers_ensure(Object *ob, MultiresModifierData *mmd)
+int ED_sculpt_mask_layers_ensure(Object *ob, MultiresModifierData *mmd)
{
float *paint_mask;
Mesh *me = ob->data;
+ int ret = 0;
paint_mask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK);
@@ -4112,7 +4154,7 @@ void ED_sculpt_mask_layers_ensure(Object *ob, MultiresModifierData *mmd)
* isn't one already */
if (mmd && !CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
GridPaintMask *gmask;
- int level = MAX2(1, mmd->sculptlvl);
+ int level = max_ii(1, mmd->sculptlvl);
int gridsize = ccg_gridsize(level);
int gridarea = gridsize * gridsize;
int i, j;
@@ -4157,13 +4199,18 @@ void ED_sculpt_mask_layers_ensure(Object *ob, MultiresModifierData *mmd)
}
}
}
+
+ ret |= ED_SCULPT_MASK_LAYER_CALC_LOOP;
}
/* create vertex paint mask layer if there isn't one already */
if (!paint_mask) {
CustomData_add_layer(&me->vdata, CD_PAINT_MASK,
CD_CALLOC, NULL, me->totvert);
+ ret |= ED_SCULPT_MASK_LAYER_CALC_VERT;
}
+
+ return ret;
}
static int sculpt_toggle_mode(bContext *C, wmOperator *UNUSED(op))
@@ -4213,14 +4260,18 @@ static int sculpt_toggle_mode(bContext *C, wmOperator *UNUSED(op))
sculpt_init_session(scene, ob);
/* Mask layer is required */
- ED_sculpt_mask_layers_ensure(ob, mmd);
+ if (mmd) {
+ /* XXX, we could attempt to support adding mask data mid-sculpt mode (with multi-res)
+ * but this ends up being quite tricky (and slow) */
+ ED_sculpt_mask_layers_ensure(ob, mmd);
+ }
BKE_paint_init(&ts->sculpt->paint, PAINT_CURSOR_SCULPT);
paint_cursor_start(C, sculpt_poll);
}
- WM_event_add_notifier(C, NC_SCENE | ND_MODE, CTX_data_scene(C));
+ WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
return OPERATOR_FINISHED;
}
diff --git a/source/blender/editors/sculpt_paint/sculpt_intern.h b/source/blender/editors/sculpt_paint/sculpt_intern.h
index f4467dc22fc..acb906e4a91 100644
--- a/source/blender/editors/sculpt_paint/sculpt_intern.h
+++ b/source/blender/editors/sculpt_paint/sculpt_intern.h
@@ -56,14 +56,16 @@ struct MultiresModifierData *sculpt_multires_active(struct Scene *scene, struct
void sculpt(struct Sculpt *sd);
int sculpt_mode_poll(struct bContext *C);
+int sculpt_mode_poll_view3d(struct bContext *C);
int sculpt_poll(struct bContext *C);
-void sculpt_update_mesh_elements(struct Scene *scene, struct Sculpt *sd, struct Object *ob, int need_pmap);
+void sculpt_update_mesh_elements(struct Scene *scene, struct Sculpt *sd, struct Object *ob,
+ int need_pmap, int need_mask);
/* Deformed mesh sculpt */
void free_sculptsession_deformMats(struct SculptSession *ss);
/* Stroke */
-int sculpt_stroke_get_location(bContext *C, float out[3], float mouse[2]);
+int sculpt_stroke_get_location(bContext *C, float out[3], const float mouse[2]);
/* Undo */
diff --git a/source/blender/editors/sculpt_paint/sculpt_undo.c b/source/blender/editors/sculpt_paint/sculpt_undo.c
index c62dc687c73..1b3fd24ae22 100644
--- a/source/blender/editors/sculpt_paint/sculpt_undo.c
+++ b/source/blender/editors/sculpt_paint/sculpt_undo.c
@@ -99,7 +99,7 @@ static int sculpt_undo_restore_coords(bContext *C, DerivedMesh *dm, SculptUndoNo
Object *ob = CTX_data_active_object(C);
SculptSession *ss = ob->sculpt;
MVert *mvert;
- int *index, i, j;
+ int *index, i, j;
if (unode->maxvert) {
/* regular mesh restore */
@@ -107,13 +107,13 @@ static int sculpt_undo_restore_coords(bContext *C, DerivedMesh *dm, SculptUndoNo
if (ss->kb && strcmp(ss->kb->name, unode->shapeName)) {
/* shape key has been changed before calling undo operator */
- Key *key = ob_get_key(ob);
- KeyBlock *kb = key_get_named_keyblock(key, unode->shapeName);
+ Key *key = BKE_key_from_object(ob);
+ KeyBlock *kb = key ? BKE_keyblock_find_name(key, unode->shapeName) : NULL;
if (kb) {
ob->shapenr = BLI_findindex(&key->block, kb) + 1;
- sculpt_update_mesh_elements(scene, sd, ob, 0);
+ sculpt_update_mesh_elements(scene, sd, ob, 0, FALSE);
WM_event_add_notifier(C, NC_OBJECT | ND_DATA, ob);
}
else {
@@ -127,7 +127,7 @@ static int sculpt_undo_restore_coords(bContext *C, DerivedMesh *dm, SculptUndoNo
if (ss->kb) {
float (*vertCos)[3];
- vertCos = key_to_vertcos(ob, ss->kb);
+ vertCos = BKE_key_convert_to_vertcos(ob, ss->kb);
for (i = 0; i < unode->totvert; i++) {
if (ss->modifiers_active) sculpt_undo_restore_deformed(ss, unode, i, index[i], vertCos[index[i]]);
@@ -224,7 +224,7 @@ static int sculpt_undo_restore_mask(bContext *C, DerivedMesh *dm, SculptUndoNode
SculptSession *ss = ob->sculpt;
MVert *mvert;
float *vmask;
- int *index, i, j;
+ int *index, i, j;
if (unode->maxvert) {
/* regular mesh restore */
@@ -266,13 +266,28 @@ static void sculpt_undo_restore(bContext *C, ListBase *lb)
Scene *scene = CTX_data_scene(C);
Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
Object *ob = CTX_data_active_object(C);
- DerivedMesh *dm = mesh_get_derived_final(scene, ob, 0);
+ DerivedMesh *dm;
SculptSession *ss = ob->sculpt;
SculptUndoNode *unode;
MultiresModifierData *mmd;
int update = FALSE, rebuild = FALSE;
+ int need_mask = FALSE;
- sculpt_update_mesh_elements(scene, sd, ob, 0);
+ for (unode = lb->first; unode; unode = unode->next) {
+ if (strcmp(unode->idname, ob->id.name) == 0) {
+ if (unode->type == SCULPT_UNDO_MASK) {
+ /* is possible that we can't do the mask undo (below)
+ * because of the vertex count */
+ need_mask = TRUE;
+ break;
+ }
+ }
+ }
+
+ sculpt_update_mesh_elements(scene, sd, ob, 0, need_mask);
+
+ /* call _after_ sculpt_update_mesh_elements() which may update 'ob->derivedFinal' */
+ dm = mesh_get_derived_final(scene, ob, 0);
for (unode = lb->first; unode; unode = unode->next) {
if (!(strcmp(unode->idname, ob->id.name) == 0))
diff --git a/source/blender/editors/space_action/action_draw.c b/source/blender/editors/space_action/action_draw.c
index 878fd20b27e..9bd7d2a44ca 100644
--- a/source/blender/editors/space_action/action_draw.c
+++ b/source/blender/editors/space_action/action_draw.c
@@ -89,7 +89,7 @@ void draw_channel_names(bContext *C, bAnimContext *ac, ARegion *ar)
* start of list offset, and the second is as a correction for the scrollers.
*/
height = ((items * ACHANNEL_STEP) + (ACHANNEL_HEIGHT * 2));
- if (height > BLI_RCT_SIZE_Y(&v2d->mask)) {
+ if (height > BLI_rcti_size_y(&v2d->mask)) {
/* don't use totrect set, as the width stays the same
* (NOTE: this is ok here, the configuration is pretty straightforward)
*/
@@ -98,7 +98,7 @@ void draw_channel_names(bContext *C, bAnimContext *ac, ARegion *ar)
/* need to do a view-sync here, so that the keys area doesn't jump around (it must copy this) */
UI_view2d_sync(NULL, ac->sa, v2d, V2D_LOCK_COPY);
- /* loop through channels, and set up drawing depending on their type */
+ /* loop through channels, and set up drawing depending on their type */
{ /* first pass: just the standard GL-drawing for backdrop + text */
y = (float)ACHANNEL_FIRST;
@@ -189,7 +189,7 @@ void draw_channel_strips(bAnimContext *ac, SpaceAction *saction, ARegion *ar)
/* if in NLA there's a strip active, map the view */
if (ac->datatype == ANIMCONT_ACTION) {
- /* adt= ANIM_nla_mapping_get(ac, NULL); */ /* UNUSED */
+ /* adt = ANIM_nla_mapping_get(ac, NULL); */ /* UNUSED */
/* start and end of action itself */
calc_action_range(ac->data, &act_start, &act_end, 0);
@@ -307,7 +307,7 @@ void draw_channel_strips(bAnimContext *ac, SpaceAction *saction, ARegion *ar)
/* Increment the step */
y -= ACHANNEL_STEP;
- }
+ }
glDisable(GL_BLEND);
/* Draw keyframes
diff --git a/source/blender/editors/space_action/action_edit.c b/source/blender/editors/space_action/action_edit.c
index c95f1dba31d..ae78b71f2ad 100644
--- a/source/blender/editors/space_action/action_edit.c
+++ b/source/blender/editors/space_action/action_edit.c
@@ -132,7 +132,7 @@ void ACTION_OT_new(wmOperatorType *ot)
/* api callbacks */
ot->exec = act_new_exec;
- // NOTE: this is used in the NLA too...
+ /* NOTE: this is used in the NLA too... */
//ot->poll = ED_operator_action_active;
/* flags */
@@ -234,8 +234,8 @@ static void get_keyframe_extents(bAnimContext *ac, float *min, float *max, const
int filter;
/* get data to filter, from Action or Dopesheet */
- // XXX: what is sel doing here?!
- // Commented it, was breaking things (eg. the "auto preview range" tool).
+ /* XXX: what is sel doing here?!
+ * Commented it, was breaking things (eg. the "auto preview range" tool). */
filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_LIST_VISIBLE /*| ANIMFILTER_SEL *//*| ANIMFILTER_CURVESONLY*/ | ANIMFILTER_NODUPLIS);
ANIM_animdata_filter(ac, &anim_data, filter, ac->data, ac->datatype);
@@ -254,8 +254,9 @@ static void get_keyframe_extents(bAnimContext *ac, float *min, float *max, const
/* find gp-frame which is less than or equal to cframe */
for (gpf = gpl->frames.first; gpf; gpf = gpf->next) {
- *min = MIN2(*min, gpf->framenum);
- *max = MAX2(*max, gpf->framenum);
+ const float framenum = (float)gpf->framenum;
+ *min = min_ff(*min, framenum);
+ *max = max_ff(*max, framenum);
}
}
else if (ale->datatype == ALE_MASKLAY) {
@@ -267,8 +268,9 @@ static void get_keyframe_extents(bAnimContext *ac, float *min, float *max, const
masklay_shape;
masklay_shape = masklay_shape->next)
{
- *min = MIN2(*min, masklay_shape->frame);
- *max = MAX2(*max, masklay_shape->frame);
+ const float framenum = (float)masklay_shape->frame;
+ *min = min_ff(*min, framenum);
+ *max = max_ff(*max, framenum);
}
}
else {
@@ -284,8 +286,8 @@ static void get_keyframe_extents(bAnimContext *ac, float *min, float *max, const
}
/* try to set cur using these values, if they're more extreme than previously set values */
- *min = MIN2(*min, tmin);
- *max = MAX2(*max, tmax);
+ *min = min_ff(*min, tmin);
+ *max = max_ff(*max, tmax);
}
}
@@ -365,13 +367,13 @@ static int actkeys_viewall(bContext *C, const short onlySel)
/* set the horizontal range, with an extra offset so that the extreme keys will be in view */
get_keyframe_extents(&ac, &v2d->cur.xmin, &v2d->cur.xmax, onlySel);
- extra = 0.1f * BLI_RCT_SIZE_X(&v2d->cur);
+ extra = 0.1f * BLI_rctf_size_x(&v2d->cur);
v2d->cur.xmin -= extra;
v2d->cur.xmax += extra;
/* set vertical range */
v2d->cur.ymax = 0.0f;
- v2d->cur.ymin = (float)-BLI_RCT_SIZE_Y(&v2d->mask);
+ v2d->cur.ymin = (float)-BLI_rcti_size_y(&v2d->mask);
/* do View2D syncing */
UI_view2d_sync(CTX_wm_screen(C), CTX_wm_area(C), v2d, V2D_LOCK_COPY);
@@ -493,7 +495,7 @@ static int actkeys_copy_exec(bContext *C, wmOperator *op)
/* copy keyframes */
if (ELEM(ac.datatype, ANIMCONT_GPENCIL, ANIMCONT_MASK)) {
/* FIXME... */
- BKE_report(op->reports, RPT_ERROR, "Keyframe pasting is not available for Grease Pencil mode");
+ BKE_report(op->reports, RPT_ERROR, "Keyframe pasting is not available for grease pencil mode");
return OPERATOR_CANCELLED;
}
else if (ac.datatype == ANIMCONT_MASK) {
@@ -502,7 +504,7 @@ static int actkeys_copy_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
else {
- if (copy_action_keys(&ac)) {
+ if (copy_action_keys(&ac)) {
BKE_report(op->reports, RPT_ERROR, "No keyframes copied to keyframes copy/paste buffer");
return OPERATOR_CANCELLED;
}
@@ -542,8 +544,8 @@ static int actkeys_paste_exec(bContext *C, wmOperator *op)
/* paste keyframes */
if (ELEM(ac.datatype, ANIMCONT_GPENCIL, ANIMCONT_MASK)) {
- // FIXME...
- BKE_report(op->reports, RPT_ERROR, "Keyframe pasting is not available for Grease Pencil or Mask mode");
+ /* FIXME... */
+ BKE_report(op->reports, RPT_ERROR, "Keyframe pasting is not available for grease pencil or mask mode");
return OPERATOR_CANCELLED;
}
else {
@@ -588,7 +590,7 @@ void ACTION_OT_paste(wmOperatorType *ot)
static EnumPropertyItem prop_actkeys_insertkey_types[] = {
{1, "ALL", 0, "All Channels", ""},
{2, "SEL", 0, "Only Selected Channels", ""},
- {3, "GROUP", 0, "In Active Group", ""}, // xxx not in all cases
+ {3, "GROUP", 0, "In Active Group", ""}, /* XXX not in all cases */
{0, NULL, 0, NULL, NULL}
};
@@ -976,8 +978,8 @@ void ACTION_OT_sample(wmOperatorType *ot)
/* defines for set extrapolation-type for selected keyframes tool */
static EnumPropertyItem prop_actkeys_expo_types[] = {
- {FCURVE_EXTRAPOLATE_CONSTANT, "CONSTANT", 0, "Constant Extrapolation", ""},
- {FCURVE_EXTRAPOLATE_LINEAR, "LINEAR", 0, "Linear Extrapolation", ""},
+ {FCURVE_EXTRAPOLATE_CONSTANT, "CONSTANT", 0, "Constant Extrapolation", "Values on endpoint keyframes are held"},
+ {FCURVE_EXTRAPOLATE_LINEAR, "LINEAR", 0, "Linear Extrapolation", "Straight-line slope of end segments are extended past the endpoint keyframes"},
{MAKE_CYCLIC_EXPO, "MAKE_CYCLIC", 0, "Make Cyclic (F-Modifier)", "Add Cycles F-Modifier if one doesn't exist already"},
{CLEAR_CYCLIC_EXPO, "CLEAR_CYCLIC", 0, "Clear Cyclic (F-Modifier)", "Remove Cycles F-Modifier if not needed anymore"},
@@ -1010,7 +1012,7 @@ static void setexpo_action_keys(bAnimContext *ac, short mode)
if (mode == MAKE_CYCLIC_EXPO) {
/* only add if one doesn't exist */
if (list_has_suitable_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES, -1) == 0) {
- // TODO: add some more preset versions which set different extrapolation options?
+ /* TODO: add some more preset versions which set different extrapolation options? */
add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES);
}
}
@@ -1319,7 +1321,7 @@ static int actkeys_framejump_exec(bContext *C, wmOperator *UNUSED(op))
if (ANIM_animdata_get_context(C, &ac) == 0)
return OPERATOR_CANCELLED;
- /* init edit data */
+ /* init edit data */
/* loop over action data, averaging values */
filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_LIST_VISIBLE /*| ANIMFILTER_CURVESONLY */ | ANIMFILTER_NODUPLIS);
ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
@@ -1353,9 +1355,9 @@ static int actkeys_framejump_exec(bContext *C, wmOperator *UNUSED(op))
void ACTION_OT_frame_jump(wmOperatorType *ot)
{
/* identifiers */
- ot->name = "Jump to Frame";
+ ot->name = "Jump to Keyframes";
ot->idname = "ACTION_OT_frame_jump";
- ot->description = "Set the current frame to the average frame of the selected keyframes";
+ ot->description = "Set the current frame to the average frame value of selected keyframes";
/* api callbacks */
ot->exec = actkeys_framejump_exec;
@@ -1369,10 +1371,14 @@ void ACTION_OT_frame_jump(wmOperatorType *ot)
/* defines for snap keyframes tool */
static EnumPropertyItem prop_actkeys_snap_types[] = {
- {ACTKEYS_SNAP_CFRA, "CFRA", 0, "Current frame", ""},
- {ACTKEYS_SNAP_NEAREST_FRAME, "NEAREST_FRAME", 0, "Nearest Frame", ""}, // XXX as single entry?
- {ACTKEYS_SNAP_NEAREST_SECOND, "NEAREST_SECOND", 0, "Nearest Second", ""}, // XXX as single entry?
- {ACTKEYS_SNAP_NEAREST_MARKER, "NEAREST_MARKER", 0, "Nearest Marker", ""},
+ {ACTKEYS_SNAP_CFRA, "CFRA", 0, "Current frame",
+ "Snap selected keyframes to the current frame"},
+ {ACTKEYS_SNAP_NEAREST_FRAME, "NEAREST_FRAME", 0, "Nearest Frame",
+ "Snap selected keyframes to the nearest (whole) frame (use to fix accidental sub-frame offsets)"},
+ {ACTKEYS_SNAP_NEAREST_SECOND, "NEAREST_SECOND", 0, "Nearest Second",
+ "Snap selected keyframes to the nearest second"},
+ {ACTKEYS_SNAP_NEAREST_MARKER, "NEAREST_MARKER", 0, "Nearest Marker",
+ "Snap selected keyframes to the nearest marker"},
{0, NULL, 0, NULL, NULL}
};
@@ -1431,7 +1437,7 @@ static int actkeys_snap_exec(bContext *C, wmOperator *op)
if (ANIM_animdata_get_context(C, &ac) == 0)
return OPERATOR_CANCELLED;
- // XXX...
+ /* XXX... */
if (ELEM(ac.datatype, ANIMCONT_GPENCIL, ANIMCONT_MASK))
return OPERATOR_PASS_THROUGH;
@@ -1473,9 +1479,12 @@ void ACTION_OT_snap(wmOperatorType *ot)
/* defines for mirror keyframes tool */
static EnumPropertyItem prop_actkeys_mirror_types[] = {
- {ACTKEYS_MIRROR_CFRA, "CFRA", 0, "By Times over Current frame", ""},
- {ACTKEYS_MIRROR_XAXIS, "XAXIS", 0, "By Values over Value=0", ""},
- {ACTKEYS_MIRROR_MARKER, "MARKER", 0, "By Times over First Selected Marker", ""},
+ {ACTKEYS_MIRROR_CFRA, "CFRA", 0, "By Times over Current frame",
+ "Flip times of selected keyframes using the current frame as the mirror line"},
+ {ACTKEYS_MIRROR_XAXIS, "XAXIS", 0, "By Values over Value=0",
+ "Flip values of selected keyframes (i.e. negative values become positive, and vice versa)"},
+ {ACTKEYS_MIRROR_MARKER, "MARKER", 0, "By Times over First Selected Marker",
+ "Flip times of selected keyframes using the first selected marker as the reference point"},
{0, NULL, 0, NULL, NULL}
};
@@ -1495,14 +1504,10 @@ static void mirror_action_keys(bAnimContext *ac, short mode)
ked.scene = ac->scene;
/* for 'first selected marker' mode, need to find first selected marker first! */
- // XXX should this be made into a helper func in the API?
+ /* XXX should this be made into a helper func in the API? */
if (mode == ACTKEYS_MIRROR_MARKER) {
- TimeMarker *marker = NULL;
-
- /* find first selected marker */
- marker = ED_markers_get_first_selected(ac->markers);
+ TimeMarker *marker = ED_markers_get_first_selected(ac->markers);
- /* store marker's time (if available) */
if (marker)
ked.f1 = (float)marker->frame;
else
@@ -1545,7 +1550,7 @@ static int actkeys_mirror_exec(bContext *C, wmOperator *op)
if (ANIM_animdata_get_context(C, &ac) == 0)
return OPERATOR_CANCELLED;
- // XXX...
+ /* XXX... */
if (ELEM(ac.datatype, ANIMCONT_GPENCIL, ANIMCONT_MASK))
return OPERATOR_PASS_THROUGH;
diff --git a/source/blender/editors/space_action/action_intern.h b/source/blender/editors/space_action/action_intern.h
index c684ae1de51..10085d8a149 100644
--- a/source/blender/editors/space_action/action_intern.h
+++ b/source/blender/editors/space_action/action_intern.h
@@ -111,7 +111,7 @@ enum {
ACTKEYS_SNAP_CFRA = 1,
ACTKEYS_SNAP_NEAREST_FRAME,
ACTKEYS_SNAP_NEAREST_SECOND,
- ACTKEYS_SNAP_NEAREST_MARKER,
+ ACTKEYS_SNAP_NEAREST_MARKER,
} eActKeys_Snap_Mode;
/* defines for mirror keyframes
@@ -121,7 +121,7 @@ enum {
ACTKEYS_MIRROR_CFRA = 1,
ACTKEYS_MIRROR_YAXIS,
ACTKEYS_MIRROR_XAXIS,
- ACTKEYS_MIRROR_MARKER,
+ ACTKEYS_MIRROR_MARKER,
} eActKeys_Mirror_Mode;
/* ***************************************** */
diff --git a/source/blender/editors/space_action/action_ops.c b/source/blender/editors/space_action/action_ops.c
index e4a161e3e22..cca71bb1331 100644
--- a/source/blender/editors/space_action/action_ops.c
+++ b/source/blender/editors/space_action/action_ops.c
@@ -168,9 +168,8 @@ static void action_keymap_keyframes(wmKeyConfig *keyconf, wmKeyMap *keymap)
/* action_edit.c */
- /* snap - current frame to selected keys */
- // TODO: maybe since this is called jump, we're better to have it on <something>-J?
- WM_keymap_add_item(keymap, "ACTION_OT_frame_jump", SKEY, KM_PRESS, KM_CTRL | KM_SHIFT, 0);
+ /* jump to selected keyframes */
+ WM_keymap_add_item(keymap, "ACTION_OT_frame_jump", GKEY, KM_PRESS, KM_CTRL, 0);
/* menu + single-step transform */
WM_keymap_add_item(keymap, "ACTION_OT_snap", SKEY, KM_PRESS, KM_SHIFT, 0);
diff --git a/source/blender/editors/space_action/action_select.c b/source/blender/editors/space_action/action_select.c
index 9ab79d73e76..d0f76c21019 100644
--- a/source/blender/editors/space_action/action_select.c
+++ b/source/blender/editors/space_action/action_select.c
@@ -309,7 +309,7 @@ static int actkeys_borderselect_exec(bContext *C, wmOperator *op)
* - the frame-range select option is favored over the channel one (x over y), as frame-range one is often
* used for tweaking timing when "blocking", while channels is not that useful...
*/
- if (BLI_RCT_SIZE_X(&rect) >= BLI_RCT_SIZE_Y(&rect))
+ if (BLI_rcti_size_x(&rect) >= BLI_rcti_size_y(&rect))
mode = ACTKEYS_BORDERSEL_FRAMERANGE;
else
mode = ACTKEYS_BORDERSEL_CHANNELS;
@@ -763,7 +763,7 @@ static void actkeys_select_leftright(bAnimContext *ac, short leftright, short se
if (leftright == ACTKEYS_LRSEL_LEFT) {
ked.f1 = MINAFRAMEF;
ked.f2 = (float)(CFRA + 0.1f);
- }
+ }
else {
ked.f1 = (float)(CFRA - 0.1f);
ked.f2 = MAXFRAMEF;
@@ -785,7 +785,7 @@ static void actkeys_select_leftright(bAnimContext *ac, short leftright, short se
ANIM_fcurve_keyframes_loop(&ked, ale->key_data, ok_cb, select_cb, NULL);
ANIM_nla_mapping_apply_fcurve(adt, ale->key_data, 1, 1);
}
- else if (ale->type == ANIMTYPE_GPLAYER)
+ else if (ale->type == ANIMTYPE_GPLAYER)
ED_gplayer_frames_select_border(ale->data, ked.f1, ked.f2, select_mode);
else if (ale->type == ANIMTYPE_MASKLAYER)
ED_masklayer_frames_select_border(ale->data, ked.f1, ked.f2, select_mode);
@@ -869,7 +869,7 @@ static int actkeys_select_leftright_invoke(bContext *C, wmOperator *op, wmEvent
UI_view2d_region_to_view(v2d, event->mval[0], event->mval[1], &x, NULL);
if (x < CFRA)
RNA_enum_set(op->ptr, "mode", ACTKEYS_LRSEL_LEFT);
- else
+ else
RNA_enum_set(op->ptr, "mode", ACTKEYS_LRSEL_RIGHT);
}
@@ -912,9 +912,6 @@ void ACTION_OT_select_leftright(wmOperatorType *ot)
* selection mode between replacing the selection (without) and inverting the selection (with).
*/
-/* sensitivity factor for frame-selections */
-#define FRAME_CLICK_THRESH 0.1f
-
/* ------------------- */
/* option 1) select keyframe directly under mouse */
@@ -1084,7 +1081,7 @@ static void mouse_action_keys(bAnimContext *ac, const int mval[2], short select_
/* dopesheet summary covers everything */
summary_to_keylist(ac, &anim_keys, NULL);
}
- else if (ale->type == ANIMTYPE_GROUP) {
+ else if (ale->type == ANIMTYPE_GROUP) {
// TODO: why don't we just give groups key_data too?
bActionGroup *agrp = (bActionGroup *)ale->data;
agroup_to_keylist(adt, agrp, &anim_keys, NULL);
@@ -1147,7 +1144,7 @@ static void mouse_action_keys(bAnimContext *ac, const int mval[2], short select_
agrp->flag |= AGRP_SELECTED;
ANIM_set_active_channel(ac, ac->data, ac->datatype, filter, agrp, ANIMTYPE_GROUP);
- }
+ }
else if (ale->type == ANIMTYPE_FCURVE) {
FCurve *fcu = ale->data;
@@ -1213,7 +1210,7 @@ static int actkeys_clickselect_invoke(bContext *C, wmOperator *op, wmEvent *even
return OPERATOR_CANCELLED;
/* get useful pointers from animation context data */
- /* ar= ac.ar; */ /* UNUSED */
+ /* ar = ac.ar; */ /* UNUSED */
/* select mode is either replace (deselect all, then add) or add/extend */
if (RNA_boolean_get(op->ptr, "extend"))
diff --git a/source/blender/editors/space_action/space_action.c b/source/blender/editors/space_action/space_action.c
index 1f641829e7e..c5f3ccee101 100644
--- a/source/blender/editors/space_action/space_action.c
+++ b/source/blender/editors/space_action/space_action.c
@@ -129,7 +129,7 @@ static SpaceLink *action_new(const bContext *C)
/* not spacelink itself */
static void action_free(SpaceLink *UNUSED(sl))
{
-// SpaceAction *saction= (SpaceAction *) sl;
+// SpaceAction *saction = (SpaceAction *) sl;
}
@@ -357,8 +357,8 @@ static void action_listener(ScrArea *sa, wmNotifier *wmn)
/* context changes */
switch (wmn->category) {
- case NC_SCREEN:
- if (wmn->data == ND_GPENCIL) {
+ case NC_GPENCIL:
+ if (wmn->action == NA_EDITED) {
/* only handle this event in GPencil mode for performance considerations */
if (saction->mode == SACTCONT_GPENCIL)
ED_area_tag_redraw(sa);
@@ -377,7 +377,7 @@ static void action_listener(ScrArea *sa, wmNotifier *wmn)
ED_area_tag_refresh(sa);
break;
case NC_SCENE:
- switch (wmn->data) {
+ switch (wmn->data) {
case ND_OB_ACTIVE: /* selection changed, so force refresh to flush (needs flag set to do syncing) */
case ND_OB_SELECT:
saction->flag |= SACTION_TEMP_NEEDCHANSYNC;
@@ -409,6 +409,7 @@ static void action_listener(ScrArea *sa, wmNotifier *wmn)
switch (wmn->data) {
case ND_DATA:
ED_area_tag_refresh(sa);
+ ED_area_tag_redraw(sa);
break;
default: /* just redrawing the view will do */
ED_area_tag_redraw(sa);
@@ -432,7 +433,7 @@ static void action_listener(ScrArea *sa, wmNotifier *wmn)
saction->flag |= SACTION_TEMP_NEEDCHANSYNC;
ED_area_tag_refresh(sa);
break;
- }
+ }
break;
case NC_WINDOW:
if (saction->flag & SACTION_TEMP_NEEDCHANSYNC) {
diff --git a/source/blender/editors/space_api/spacetypes.c b/source/blender/editors/space_api/spacetypes.c
index 2cbcbcdbc9a..35344f2c5a4 100644
--- a/source/blender/editors/space_api/spacetypes.c
+++ b/source/blender/editors/space_api/spacetypes.c
@@ -193,7 +193,7 @@ void ED_spacetypes_keymap(wmKeyConfig *keyconf)
typedef struct RegionDrawCB {
struct RegionDrawCB *next, *prev;
- void (*draw)(const struct bContext *, struct ARegion *, void *);
+ void (*draw)(const struct bContext *, struct ARegion *, void *);
void *customdata;
int type;
@@ -239,7 +239,7 @@ void ED_region_draw_cb_draw(const bContext *C, ARegion *ar, int type)
for (rdc = ar->type->drawcalls.first; rdc; rdc = rdc->next) {
if (rdc->type == type)
rdc->draw(C, ar, rdc->customdata);
- }
+ }
}
diff --git a/source/blender/editors/space_buttons/buttons_context.c b/source/blender/editors/space_buttons/buttons_context.c
index c41d2521ee8..9c47c407bd9 100644
--- a/source/blender/editors/space_buttons/buttons_context.c
+++ b/source/blender/editors/space_buttons/buttons_context.c
@@ -236,7 +236,7 @@ static int buttons_context_path_material(ButsContextPath *path, int for_texture)
if (ma) {
RNA_id_pointer_create(&ma->id, &path->ptr[path->len]);
path->len++;
- }
+ }
return 1;
}
}
@@ -889,7 +889,7 @@ int buttons_context(const bContext *C, const char *member, bContextDataResult *r
else
CTX_data_pointer_set(result, NULL, &RNA_ParticleSystem, NULL);
return 1;
- }
+ }
else if (CTX_data_equals(member, "particle_settings")) {
/* only available when pinned */
PointerRNA *ptr = get_pointer_type(path, &RNA_ParticleSettings);
@@ -900,7 +900,7 @@ int buttons_context(const bContext *C, const char *member, bContextDataResult *r
}
else {
/* get settings from active particle system instead */
- PointerRNA *ptr = get_pointer_type(path, &RNA_ParticleSystem);
+ ptr = get_pointer_type(path, &RNA_ParticleSystem);
if (ptr && ptr->data) {
ParticleSettings *part = ((ParticleSystem *)ptr->data)->part;
diff --git a/source/blender/editors/space_buttons/buttons_header.c b/source/blender/editors/space_buttons/buttons_header.c
index 4bcd4a933ed..ebba7d92819 100644
--- a/source/blender/editors/space_buttons/buttons_header.c
+++ b/source/blender/editors/space_buttons/buttons_header.c
@@ -148,7 +148,7 @@ void buttons_header_buttons(const bContext *C, ARegion *ar)
uiBlockEndAlign(block);
/* always as last */
- UI_view2d_totRect_set(&ar->v2d, xco + (UI_UNIT_X / 2), BLI_RCT_SIZE_Y(&ar->v2d.tot));
+ UI_view2d_totRect_set(&ar->v2d, xco + (UI_UNIT_X / 2), BLI_rctf_size_y(&ar->v2d.tot));
uiEndBlock(C, block);
uiDrawBlock(C, block);
diff --git a/source/blender/editors/space_buttons/buttons_ops.c b/source/blender/editors/space_buttons/buttons_ops.c
index c8cf69e3e17..d40426a5bc9 100644
--- a/source/blender/editors/space_buttons/buttons_ops.c
+++ b/source/blender/editors/space_buttons/buttons_ops.c
@@ -162,7 +162,7 @@ static int file_browse_invoke(bContext *C, wmOperator *op, wmEvent *event)
char *str;
if (CTX_wm_space_file(C)) {
- BKE_report(op->reports, RPT_ERROR, "Can't activate a file selector, one already open");
+ BKE_report(op->reports, RPT_ERROR, "Cannot activate a file selector, one already open");
return OPERATOR_CANCELLED;
}
@@ -207,7 +207,7 @@ static int file_browse_invoke(bContext *C, wmOperator *op, wmEvent *event)
* user-prefs exception - campbell */
if (RNA_struct_find_property(op->ptr, "relative_path")) {
if (!RNA_struct_property_is_set(op->ptr, "relative_path")) {
- /* annoying exception!, if were dealign with the user prefs, default relative to be off */
+ /* annoying exception!, if were dealing with the user prefs, default relative to be off */
RNA_boolean_set(op->ptr, "relative_path", U.flag & USER_RELPATHS && (ptr.data != &U));
}
}
diff --git a/source/blender/editors/space_buttons/space_buttons.c b/source/blender/editors/space_buttons/space_buttons.c
index 33229496d0b..09ad7312123 100644
--- a/source/blender/editors/space_buttons/space_buttons.c
+++ b/source/blender/editors/space_buttons/space_buttons.c
@@ -323,7 +323,7 @@ static void buttons_area_listener(ScrArea *sa, wmNotifier *wmn)
/* currently works by redraws... if preview is set, it (re)starts job */
sbuts->preview = 1;
break;
- }
+ }
break;
case NC_WORLD:
buttons_area_redraw(sa, BCONTEXT_WORLD);
diff --git a/source/blender/editors/space_clip/CMakeLists.txt b/source/blender/editors/space_clip/CMakeLists.txt
index ecc4dea8b05..75e3d8d5685 100644
--- a/source/blender/editors/space_clip/CMakeLists.txt
+++ b/source/blender/editors/space_clip/CMakeLists.txt
@@ -33,10 +33,10 @@ set(INC
../../windowmanager
../../gpu
../../../../intern/guardedalloc
- ${GLEW_INCLUDE_PATH}
)
set(INC_SYS
+ ${GLEW_INCLUDE_PATH}
)
set(SRC
diff --git a/source/blender/editors/space_clip/clip_buttons.c b/source/blender/editors/space_clip/clip_buttons.c
index 0a1e1d75098..969b0e25928 100644
--- a/source/blender/editors/space_clip/clip_buttons.c
+++ b/source/blender/editors/space_clip/clip_buttons.c
@@ -174,7 +174,7 @@ void uiTemplateTrack(uiLayout *layout, PointerRNA *ptr, const char *propname)
scopes->track_preview_height =
(scopes->track_preview_height <= UI_UNIT_Y) ? UI_UNIT_Y : scopes->track_preview_height;
- uiDefBut(block, TRACKPREVIEW, 0, "", rect.xmin, rect.ymin, BLI_RCT_SIZE_X(&rect),
+ uiDefBut(block, TRACKPREVIEW, 0, "", rect.xmin, rect.ymin, BLI_rctf_size_x(&rect),
scopes->track_preview_height, scopes, 0, 0, 0, 0, "");
}
diff --git a/source/blender/editors/space_clip/clip_dopesheet_draw.c b/source/blender/editors/space_clip/clip_dopesheet_draw.c
index 5d890155e25..cc1b8d444bc 100644
--- a/source/blender/editors/space_clip/clip_dopesheet_draw.c
+++ b/source/blender/editors/space_clip/clip_dopesheet_draw.c
@@ -274,7 +274,7 @@ void clip_draw_dopesheet_channels(const bContext *C, ARegion *ar)
dopesheet = &tracking->dopesheet;
height = (dopesheet->tot_channel * CHANNEL_STEP) + (CHANNEL_HEIGHT * 2);
- if (height > BLI_RCT_SIZE_Y(&v2d->mask)) {
+ if (height > BLI_rcti_size_y(&v2d->mask)) {
/* don't use totrect set, as the width stays the same
* (NOTE: this is ok here, the configuration is pretty straightforward)
*/
diff --git a/source/blender/editors/space_clip/clip_draw.c b/source/blender/editors/space_clip/clip_draw.c
index d486caeacc2..a2e4da719e9 100644
--- a/source/blender/editors/space_clip/clip_draw.c
+++ b/source/blender/editors/space_clip/clip_draw.c
@@ -117,6 +117,7 @@ static void draw_movieclip_cache(SpaceClip *sc, ARegion *ar, MovieClip *clip, Sc
int *points, totseg, i, a;
float sfra = SFRA, efra = EFRA, framelen = ar->winx / (efra - sfra + 1);
MovieTracking *tracking = &clip->tracking;
+ MovieTrackingObject *act_object = BKE_tracking_object_get_active(tracking);
MovieTrackingTrack *act_track = BKE_tracking_track_get_active(&clip->tracking);
MovieTrackingReconstruction *reconstruction = BKE_tracking_get_active_reconstruction(tracking);
@@ -212,14 +213,14 @@ static void draw_movieclip_cache(SpaceClip *sc, ARegion *ar, MovieClip *clip, Sc
x = (sc->user.framenr - sfra) / (efra - sfra + 1) * ar->winx;
UI_ThemeColor(TH_CFRAME);
- glRecti(x, 0, x + framelen, 8);
+ glRecti(x, 0, x + ceilf(framelen), 8);
clip_draw_curfra_label(sc->user.framenr, x, 8.0f);
/* solver keyframes */
glColor4ub(175, 255, 0, 255);
- draw_keyframe(tracking->settings.keyframe1 + clip->start_frame - 1, CFRA, sfra, framelen, 2);
- draw_keyframe(tracking->settings.keyframe2 + clip->start_frame - 1, CFRA, sfra, framelen, 2);
+ draw_keyframe(act_object->keyframe1 + clip->start_frame - 1, CFRA, sfra, framelen, 2);
+ draw_keyframe(act_object->keyframe2 + clip->start_frame - 1, CFRA, sfra, framelen, 2);
/* movie clip animation */
if ((sc->mode == SC_MODE_MASKEDIT) && sc->mask_info.mask) {
@@ -715,7 +716,7 @@ static float get_shortest_pattern_side(MovieTrackingMarker *marker)
cur_len = len_v2v2(marker->pattern_corners[i], marker->pattern_corners[next]);
- len = minf(cur_len, len);
+ len = min_ff(cur_len, len);
}
return len;
@@ -787,11 +788,11 @@ static void draw_marker_slide_zones(SpaceClip *sc, MovieTrackingTrack *track, Mo
dy = 6.0f / height / sc->zoom;
side = get_shortest_pattern_side(marker);
- patdx = minf(dx * 2.0f / 3.0f, side / 6.0f);
- patdy = minf(dy * 2.0f / 3.0f, side * width / height / 6.0f);
+ patdx = min_ff(dx * 2.0f / 3.0f, side / 6.0f);
+ patdy = min_ff(dy * 2.0f / 3.0f, side * width / height / 6.0f);
- searchdx = minf(dx, (marker->search_max[0] - marker->search_min[0]) / 6.0f);
- searchdy = minf(dy, (marker->search_max[1] - marker->search_min[1]) / 6.0f);
+ searchdx = min_ff(dx, (marker->search_max[0] - marker->search_min[0]) / 6.0f);
+ searchdy = min_ff(dy, (marker->search_max[1] - marker->search_min[1]) / 6.0f);
px[0] = 1.0f / sc->zoom / width / sc->scale;
px[1] = 1.0f / sc->zoom / height / sc->scale;
@@ -957,12 +958,12 @@ static void draw_marker_texts(SpaceClip *sc, MovieTrackingTrack *track, MovieTra
static void view2d_to_region_float(View2D *v2d, float x, float y, float *regionx, float *regiony)
{
/* express given coordinates as proportional values */
- x = -v2d->cur.xmin / BLI_RCT_SIZE_X(&v2d->cur);
- y = -v2d->cur.ymin / BLI_RCT_SIZE_Y(&v2d->cur);
+ x = -v2d->cur.xmin / BLI_rctf_size_x(&v2d->cur);
+ y = -v2d->cur.ymin / BLI_rctf_size_y(&v2d->cur);
/* convert proportional distances to screen coordinates */
- *regionx = v2d->mask.xmin + x * BLI_RCT_SIZE_X(&v2d->mask);
- *regiony = v2d->mask.ymin + y * BLI_RCT_SIZE_Y(&v2d->mask);
+ *regionx = v2d->mask.xmin + x * BLI_rcti_size_x(&v2d->mask);
+ *regiony = v2d->mask.ymin + y * BLI_rcti_size_y(&v2d->mask);
}
static void draw_tracking_tracks(SpaceClip *sc, ARegion *ar, MovieClip *clip,
@@ -1126,7 +1127,7 @@ static void draw_tracking_tracks(SpaceClip *sc, ARegion *ar, MovieClip *clip,
if (MARKER_VISIBLE(sc, track, marker)) {
float npos[2];
- copy_v4_v4(vec, track->bundle_pos);
+ copy_v3_v3(vec, track->bundle_pos);
vec[3] = 1;
mul_v4_m4v4(pos, mat, vec);
diff --git a/source/blender/editors/space_clip/clip_editor.c b/source/blender/editors/space_clip/clip_editor.c
index f2a48f299cf..71589517c83 100644
--- a/source/blender/editors/space_clip/clip_editor.c
+++ b/source/blender/editors/space_clip/clip_editor.c
@@ -44,6 +44,7 @@
#include "BLI_utildefines.h"
#include "BLI_math.h"
+#include "BLI_string.h"
#include "BLI_rect.h"
#include "GPU_extensions.h"
@@ -149,8 +150,8 @@ void ED_space_clip_get_zoom(SpaceClip *sc, ARegion *ar, float *zoomx, float *zoo
ED_space_clip_get_size(sc, &width, &height);
- *zoomx = (float)(BLI_RCT_SIZE_X(&ar->winrct) + 1) / (float)(BLI_RCT_SIZE_X(&ar->v2d.cur) * width);
- *zoomy = (float)(BLI_RCT_SIZE_Y(&ar->winrct) + 1) / (float)(BLI_RCT_SIZE_Y(&ar->v2d.cur) * height);
+ *zoomx = (float)(BLI_rcti_size_x(&ar->winrct) + 1) / (BLI_rctf_size_x(&ar->v2d.cur) * width);
+ *zoomy = (float)(BLI_rcti_size_y(&ar->winrct) + 1) / (BLI_rctf_size_y(&ar->v2d.cur) * height);
}
void ED_space_clip_get_aspect(SpaceClip *sc, float *aspx, float *aspy)
@@ -368,7 +369,7 @@ int ED_clip_view_selection(const bContext *C, ARegion *ar, int fit)
ED_space_clip_get_size(sc, &frame_width, &frame_height);
- if (frame_width == 0 || frame_height == 0)
+ if ((frame_width == 0) || (frame_height == 0) || (sc->clip == NULL))
return FALSE;
if (!selected_boundbox(sc, min, max))
@@ -388,13 +389,13 @@ int ED_clip_view_selection(const bContext *C, ARegion *ar, int fit)
ED_space_clip_get_aspect(sc, &aspx, &aspy);
- width = BLI_RCT_SIZE_X(&ar->winrct) + 1;
- height = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
+ width = BLI_rcti_size_x(&ar->winrct) + 1;
+ height = BLI_rcti_size_y(&ar->winrct) + 1;
zoomx = (float)width / w / aspx;
zoomy = (float)height / h / aspy;
- newzoom = 1.0f / power_of_2(1.0f / minf(zoomx, zoomy));
+ newzoom = 1.0f / power_of_2(1.0f / min_ff(zoomx, zoomy));
if (fit || sc->zoom > newzoom)
sc->zoom = newzoom;
@@ -692,7 +693,7 @@ int ED_space_clip_load_movieclip_buffer(SpaceClip *sc, ImBuf *ibuf, const unsign
context->start_frame = clip->start_frame;
context->frame_offset = clip->frame_offset;
- strcpy(context->colorspace, clip->colorspace_settings.name);
+ BLI_strncpy(context->colorspace, clip->colorspace_settings.name, sizeof(context->colorspace));
}
else {
/* displaying exactly the same image which was loaded t oa texture,
diff --git a/source/blender/editors/space_clip/clip_graph_ops.c b/source/blender/editors/space_clip/clip_graph_ops.c
index f48d4e8d946..fa235bd2997 100644
--- a/source/blender/editors/space_clip/clip_graph_ops.c
+++ b/source/blender/editors/space_clip/clip_graph_ops.c
@@ -580,11 +580,11 @@ static int view_all_exec(bContext *C, wmOperator *UNUSED(op))
}
/* we need an extra "buffer" factor on either side so that the endpoints are visible */
- extra = 0.01f * BLI_RCT_SIZE_X(&v2d->cur);
+ extra = 0.01f * BLI_rctf_size_x(&v2d->cur);
v2d->cur.xmin -= extra;
v2d->cur.xmax += extra;
- extra = 0.01f * BLI_RCT_SIZE_Y(&v2d->cur);
+ extra = 0.01f * BLI_rctf_size_y(&v2d->cur);
v2d->cur.ymin -= extra;
v2d->cur.ymax += extra;
@@ -610,7 +610,7 @@ void CLIP_OT_graph_view_all(wmOperatorType *ot)
void ED_clip_graph_center_current_frame(Scene *scene, ARegion *ar)
{
View2D *v2d = &ar->v2d;
- float extra = BLI_RCT_SIZE_X(&v2d->cur) / 2.0f;
+ float extra = BLI_rctf_size_x(&v2d->cur) / 2.0f;
/* set extents of view to start/end frames */
v2d->cur.xmin = (float)CFRA - extra;
diff --git a/source/blender/editors/space_clip/clip_ops.c b/source/blender/editors/space_clip/clip_ops.c
index aa2cadbd2d3..9ec2ad82bef 100644
--- a/source/blender/editors/space_clip/clip_ops.c
+++ b/source/blender/editors/space_clip/clip_ops.c
@@ -41,6 +41,8 @@
#include "BLI_math.h"
#include "BLI_rect.h"
+#include "BLF_translation.h"
+
#include "BKE_context.h"
#include "BKE_global.h"
#include "BKE_report.h"
@@ -90,9 +92,9 @@ static void sclip_zoom_set(const bContext *C, float zoom, float location[2])
if ((width < 4) && (height < 4))
sc->zoom = oldzoom;
- else if (BLI_RCT_SIZE_X(&ar->winrct) <= sc->zoom)
+ else if (BLI_rcti_size_x(&ar->winrct) <= sc->zoom)
sc->zoom = oldzoom;
- else if (BLI_RCT_SIZE_Y(&ar->winrct) <= sc->zoom)
+ else if (BLI_rcti_size_y(&ar->winrct) <= sc->zoom)
sc->zoom = oldzoom;
}
@@ -180,7 +182,7 @@ static int open_exec(bContext *C, wmOperator *op)
BLI_join_dirfile(str, sizeof(str), dir_only, file_only);
}
else {
- BKE_reportf(op->reports, RPT_ERROR, "No files selected to be opened");
+ BKE_report(op->reports, RPT_ERROR, "No files selected to be opened");
return OPERATOR_CANCELLED;
}
@@ -195,8 +197,8 @@ static int open_exec(bContext *C, wmOperator *op)
if (op->customdata)
MEM_freeN(op->customdata);
- BKE_reportf(op->reports, RPT_ERROR, "Can't read: \"%s\", %s.", str,
- errno ? strerror(errno) : "Unsupported movie clip format");
+ BKE_reportf(op->reports, RPT_ERROR, "Cannot read '%s': %s", str,
+ errno ? strerror(errno) : TIP_("unsupported movie clip format"));
return OPERATOR_CANCELLED;
}
@@ -514,9 +516,14 @@ static int view_zoom_exec(bContext *C, wmOperator *op)
static int view_zoom_invoke(bContext *C, wmOperator *op, wmEvent *event)
{
if (event->type == MOUSEZOOM) {
- float factor;
+ float delta, factor;
+
+ delta = event->x - event->prevx + event->y - event->prevy;
+
+ if (U.uiflag & USER_ZOOM_INVERT)
+ delta *= -1;
- factor = 1.0f + (event->x - event->prevx + event->y - event->prevy) / 300.0f;
+ factor = 1.0f + delta / 300.0f;
RNA_float_set(op->ptr, "factor", factor);
sclip_zoom_set_factor_exec(C, event, factor);
@@ -533,11 +540,16 @@ static int view_zoom_invoke(bContext *C, wmOperator *op, wmEvent *event)
static int view_zoom_modal(bContext *C, wmOperator *op, wmEvent *event)
{
ViewZoomData *vpd = op->customdata;
- float factor;
+ float delta, factor;
switch (event->type) {
case MOUSEMOVE:
- factor = 1.0f + (vpd->x - event->x + vpd->y - event->y) / 300.0f;
+ delta = event->x - vpd->x + event->y - vpd->y;
+
+ if (U.uiflag & USER_ZOOM_INVERT)
+ delta *= -1;
+
+ factor = 1.0f + delta / 300.0f;
RNA_float_set(op->ptr, "factor", factor);
sclip_zoom_set(C, vpd->zoom * factor, vpd->location);
ED_region_tag_redraw(CTX_wm_region(C));
@@ -579,7 +591,7 @@ void CLIP_OT_view_zoom(wmOperatorType *ot)
ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_POINTER;
/* properties */
- RNA_def_float(ot->srna, "factor", 0.0f, 0.0f, FLT_MAX,
+ RNA_def_float(ot->srna, "factor", 0.0f, -FLT_MAX, FLT_MAX,
"Factor", "Zoom factor, values higher than 1.0 zoom in, lower values zoom out", -FLT_MAX, FLT_MAX);
}
@@ -700,7 +712,7 @@ void CLIP_OT_view_zoom_ratio(wmOperatorType *ot)
ot->poll = ED_space_clip_view_clip_poll;
/* properties */
- RNA_def_float(ot->srna, "ratio", 0.0f, 0.0f, FLT_MAX,
+ RNA_def_float(ot->srna, "ratio", 0.0f, -FLT_MAX, FLT_MAX,
"Ratio", "Zoom ratio, 1.0 is 1:1, higher is zoomed in, lower is zoomed out", -FLT_MAX, FLT_MAX);
}
@@ -726,8 +738,8 @@ static int view_all_exec(bContext *C, wmOperator *op)
h = h * aspy;
/* check if the image will fit in the image with zoom == 1 */
- width = BLI_RCT_SIZE_X(&ar->winrct) + 1;
- height = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
+ width = BLI_rcti_size_x(&ar->winrct) + 1;
+ height = BLI_rcti_size_y(&ar->winrct) + 1;
if (fit_view) {
const int margin = 5; /* margin from border */
@@ -735,7 +747,7 @@ static int view_all_exec(bContext *C, wmOperator *op)
zoomx = (float) width / (w + 2 * margin);
zoomy = (float) height / (h + 2 * margin);
- sclip_zoom_set(C, minf(zoomx, zoomy), NULL);
+ sclip_zoom_set(C, min_ff(zoomx, zoomy), NULL);
}
else {
if ((w >= width || h >= height) && (width > 0 && height > 0)) {
@@ -743,7 +755,7 @@ static int view_all_exec(bContext *C, wmOperator *op)
zoomy = (float) height / h;
/* find the zoom value that will fit the image in the image space */
- sclip_zoom_set(C, 1.0f / power_of_2(1.0f / minf(zoomx, zoomy)), NULL);
+ sclip_zoom_set(C, 1.0f / power_of_2(1.0f / min_ff(zoomx, zoomy)), NULL);
}
else
sclip_zoom_set(C, 1.0f, NULL);
diff --git a/source/blender/editors/space_clip/space_clip.c b/source/blender/editors/space_clip/space_clip.c
index 7f43c404095..ffe4762ad15 100644
--- a/source/blender/editors/space_clip/space_clip.c
+++ b/source/blender/editors/space_clip/space_clip.c
@@ -407,8 +407,6 @@ static void clip_listener(ScrArea *sa, wmNotifier *wmn)
case NC_SCREEN:
switch (wmn->data) {
case ND_ANIMPLAY:
- case ND_GPENCIL:
- clip_scopes_check_gpencil_change(sa);
ED_area_tag_redraw(sa);
break;
}
@@ -420,6 +418,12 @@ static void clip_listener(ScrArea *sa, wmNotifier *wmn)
ED_area_tag_redraw(sa);
}
break;
+ case NC_GPENCIL:
+ if (wmn->action == NA_EDITED) {
+ clip_scopes_check_gpencil_change(sa);
+ ED_area_tag_redraw(sa);
+ }
+ break;
}
}
@@ -1036,8 +1040,8 @@ static void movieclip_main_area_set_view2d(const bContext *C, ARegion *ar)
if (clip)
h *= clip->aspy / clip->aspx / clip->tracking.camera.pixel_aspect;
- winx = BLI_RCT_SIZE_X(&ar->winrct) + 1;
- winy = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
+ winx = BLI_rcti_size_x(&ar->winrct) + 1;
+ winy = BLI_rcti_size_y(&ar->winrct) + 1;
ar->v2d.tot.xmin = 0;
ar->v2d.tot.ymin = 0;
@@ -1159,8 +1163,8 @@ static void clip_main_area_listener(ARegion *ar, wmNotifier *wmn)
{
/* context changes */
switch (wmn->category) {
- case NC_SCREEN:
- if (wmn->data == ND_GPENCIL)
+ case NC_GPENCIL:
+ if (wmn->action == NA_EDITED)
ED_region_tag_redraw(ar);
break;
}
@@ -1373,8 +1377,8 @@ static void clip_props_area_listener(ARegion *ar, wmNotifier *wmn)
if (wmn->data == ND_SPACE_CLIP)
ED_region_tag_redraw(ar);
break;
- case NC_SCREEN:
- if (wmn->data == ND_GPENCIL)
+ case NC_GPENCIL:
+ if (wmn->action == NA_EDITED)
ED_region_tag_redraw(ar);
break;
}
@@ -1406,8 +1410,8 @@ static void clip_properties_area_listener(ARegion *ar, wmNotifier *wmn)
{
/* context changes */
switch (wmn->category) {
- case NC_SCREEN:
- if (wmn->data == ND_GPENCIL)
+ case NC_GPENCIL:
+ if (wmn->data == ND_DATA)
ED_region_tag_redraw(ar);
break;
case NC_BRUSH:
diff --git a/source/blender/editors/space_clip/tracking_ops.c b/source/blender/editors/space_clip/tracking_ops.c
index 97f7d7bf132..dd939d57cbe 100644
--- a/source/blender/editors/space_clip/tracking_ops.c
+++ b/source/blender/editors/space_clip/tracking_ops.c
@@ -154,7 +154,7 @@ void CLIP_OT_add_marker(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
- RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MIN, FLT_MAX,
+ RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
"Location", "Location of marker on frame", -1.0f, 1.0f);
}
@@ -372,8 +372,8 @@ static int mouse_on_slide_zone(SpaceClip *sc, MovieTrackingMarker *marker,
dx = size / width / sc->zoom;
dy = size / height / sc->zoom;
- dx = minf(dx, (max[0] - min[0]) / 6.0f);
- dy = minf(dy, (max[1] - min[1]) / 6.0f);
+ dx = min_ff(dx, (max[0] - min[0]) / 6.0f);
+ dy = min_ff(dy, (max[1] - min[1]) / 6.0f);
return IN_RANGE_INCL(co[0], slide_zone[0] - dx, slide_zone[0] + dx) &&
IN_RANGE_INCL(co[1], slide_zone[1] - dy, slide_zone[1] + dy);
@@ -424,14 +424,14 @@ static int get_mouse_pattern_corner(SpaceClip *sc, MovieTrackingMarker *marker,
cur_len = len_v2v2(marker->pattern_corners[i], marker->pattern_corners[next]);
- len = minf(cur_len, len);
+ len = min_ff(cur_len, len);
}
dx = 12.0f / width / sc->zoom;
dy = 12.0f / height / sc->zoom;
- dx = minf(dx, len * 2.0f / 3.0f);
- dy = minf(dy, len * width / height * 2.0f / 3.0f);
+ dx = min_ff(dx, len * 2.0f / 3.0f);
+ dy = min_ff(dy, len * width / height * 2.0f / 3.0f);
for (i = 0; i < 4; i++) {
float crn[2];
@@ -462,8 +462,8 @@ static int mouse_on_offset(SpaceClip *sc, MovieTrackingTrack *track, MovieTracki
dx = 12.0f / width / sc->zoom;
dy = 12.0f / height / sc->zoom;
- dx = minf(dx, (pat_max[0] - pat_min[0]) / 2.0f);
- dy = minf(dy, (pat_max[1] - pat_min[1]) / 2.0f);
+ dx = min_ff(dx, (pat_max[0] - pat_min[0]) / 2.0f);
+ dy = min_ff(dy, (pat_max[1] - pat_min[1]) / 2.0f);
return co[0] >= pos[0] - dx && co[0] <= pos[0] + dx && co[1] >= pos[1] - dy && co[1] <= pos[1] + dy;
}
@@ -855,8 +855,8 @@ static int slide_marker_modal(bContext *C, wmOperator *op, wmEvent *event)
vec[0] *= data->width;
vec[1] *= data->height;
- data->corners[a][0] = (vec[0] * cos(angle) - vec[1] * sin(angle)) / data->width;
- data->corners[a][1] = (vec[1] * cos(angle) + vec[0] * sin(angle)) / data->height;
+ data->corners[a][0] = (vec[0] * cosf(angle) - vec[1] * sinf(angle)) / data->width;
+ data->corners[a][1] = (vec[1] * cosf(angle) + vec[0] * sinf(angle)) / data->height;
}
BKE_tracking_marker_clamp(data->marker, CLAMP_PAT_DIM);
@@ -1018,7 +1018,7 @@ static void track_init_markers(SpaceClip *sc, MovieClip *clip, int *frames_limit
if (frames_limit == 0)
frames_limit = track->frames_limit;
else
- frames_limit = MIN2(frames_limit, track->frames_limit);
+ frames_limit = min_ii(frames_limit, (int)track->frames_limit);
}
}
}
@@ -1343,7 +1343,6 @@ static int solve_camera_initjob(bContext *C, SolveCameraJob *scj, wmOperator *op
MovieClip *clip = ED_space_clip_get_clip(sc);
Scene *scene = CTX_data_scene(C);
MovieTracking *tracking = &clip->tracking;
- MovieTrackingSettings *settings = &clip->tracking.settings;
MovieTrackingObject *object = BKE_tracking_object_get_active(tracking);
int width, height;
@@ -1359,7 +1358,7 @@ static int solve_camera_initjob(bContext *C, SolveCameraJob *scj, wmOperator *op
scj->user = sc->user;
scj->context = BKE_tracking_reconstruction_context_new(tracking, object,
- settings->keyframe1, settings->keyframe2, width, height);
+ object->keyframe1, object->keyframe2, width, height);
tracking->stats = MEM_callocN(sizeof(MovieTrackingStats), "solve camera stats");
@@ -1397,11 +1396,10 @@ static void solve_camera_freejob(void *scv)
}
solved = BKE_tracking_reconstruction_finish(scj->context, tracking);
-
if (!solved)
- BKE_report(scj->reports, RPT_WARNING, "Some data failed to reconstruct, see console for details");
+ BKE_report(scj->reports, RPT_WARNING, "Some data failed to reconstruct (see console for details)");
else
- BKE_reportf(scj->reports, RPT_INFO, "Average re-projection error %.3f", tracking->reconstruction.error);
+ BKE_reportf(scj->reports, RPT_INFO, "Average re-projection error: %.3f", tracking->reconstruction.error);
/* set currently solved clip as active for scene */
if (scene->clip)
@@ -1411,7 +1409,7 @@ static void solve_camera_freejob(void *scv)
id_us_plus(&clip->id);
/* set blender camera focal length so result would look fine there */
- if (scene->camera) {
+ if (scene->camera && GS(scene->camera->id.name) == ID_CA) {
Camera *camera = (Camera *)scene->camera->data;
int width, height;
@@ -2767,7 +2765,7 @@ static int join_tracks_exec(bContext *C, wmOperator *op)
next = track->next;
if (TRACK_VIEW_SELECTED(sc, track) && track != act_track) {
- BKE_tracking_tracks_join(act_track, track);
+ BKE_tracking_tracks_join(tracking, act_track, track);
if (tracking->stabilization.rot_track == track)
tracking->stabilization.rot_track = act_track;
@@ -2859,14 +2857,14 @@ static int set_solver_keyframe_exec(bContext *C, wmOperator *op)
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
- MovieTrackingSettings *settings = &tracking->settings;
+ MovieTrackingObject *object = BKE_tracking_object_get_active(tracking);
int keyframe = RNA_enum_get(op->ptr, "keyframe");
int framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, sc->user.framenr);
if (keyframe == 0)
- settings->keyframe1 = framenr;
+ object->keyframe1 = framenr;
else
- settings->keyframe2 = framenr;
+ object->keyframe2 = framenr;
WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
@@ -3373,7 +3371,7 @@ static int tracking_object_remove_exec(bContext *C, wmOperator *op)
object = BKE_tracking_object_get_active(tracking);
if (object->flag & TRACKING_OBJECT_CAMERA) {
- BKE_report(op->reports, RPT_WARNING, "Object used for camera tracking can't be deleted");
+ BKE_report(op->reports, RPT_WARNING, "Object used for camera tracking cannot be deleted");
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/space_clip/tracking_select.c b/source/blender/editors/space_clip/tracking_select.c
index 507e492497d..b8e162bfb17 100644
--- a/source/blender/editors/space_clip/tracking_select.c
+++ b/source/blender/editors/space_clip/tracking_select.c
@@ -107,7 +107,7 @@ static int mouse_on_crns(float co[2], float pos[2], float crns[4][2], float epsx
{
float dist = dist_to_crns(co, pos, crns);
- return dist < maxf(epsx, epsy);
+ return dist < max_ff(epsx, epsy);
}
static int track_mouse_area(const bContext *C, float co[2], MovieTrackingTrack *track)
@@ -128,8 +128,8 @@ static int track_mouse_area(const bContext *C, float co[2], MovieTrackingTrack *
epsy = MIN4(pat_min[1] - marker->search_min[1], marker->search_max[1] - pat_max[1],
fabsf(pat_min[1]), fabsf(pat_max[1])) / 2;
- epsx = maxf(epsx, 2.0f / width);
- epsy = maxf(epsy, 2.0f / height);
+ epsx = max_ff(epsx, 2.0f / width);
+ epsy = max_ff(epsy, 2.0f / height);
if (sc->flag & SC_SHOW_MARKER_SEARCH) {
if (mouse_on_rect(co, marker->pos, marker->search_min, marker->search_max, epsx, epsy))
@@ -291,7 +291,6 @@ static int select_invoke(bContext *C, wmOperator *op, wmEvent *event)
MovieTrackingTrack *track = tracking_marker_check_slide(C, event, NULL, NULL, NULL);
if (track) {
- SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
clip->tracking.act_track = track;
@@ -413,7 +412,7 @@ void CLIP_OT_select_border(wmOperatorType *ot)
/********************** lasso select operator *********************/
-static int do_lasso_select_marker(bContext *C, int mcords[][2], short moves, short select)
+static int do_lasso_select_marker(bContext *C, const int mcords[][2], const short moves, short select)
{
SpaceClip *sc = CTX_wm_space_clip(C);
ARegion *ar = CTX_wm_region(C);
@@ -469,7 +468,7 @@ static int do_lasso_select_marker(bContext *C, int mcords[][2], short moves, sho
static int clip_lasso_select_exec(bContext *C, wmOperator *op)
{
int mcords_tot;
- int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
+ const int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
if (mcords) {
short select;
@@ -477,7 +476,7 @@ static int clip_lasso_select_exec(bContext *C, wmOperator *op)
select = !RNA_boolean_get(op->ptr, "deselect");
do_lasso_select_marker(C, mcords, mcords_tot, select);
- MEM_freeN(mcords);
+ MEM_freeN((void *)mcords);
return OPERATOR_FINISHED;
}
diff --git a/source/blender/editors/space_console/console_draw.c b/source/blender/editors/space_console/console_draw.c
index 4c2f0ac73d4..f19835b7f85 100644
--- a/source/blender/editors/space_console/console_draw.c
+++ b/source/blender/editors/space_console/console_draw.c
@@ -84,7 +84,7 @@ typedef struct ConsoleDrawContext {
#if 0 /* used by textview, may use later */
int *xy; // [2]
int *sel; // [2]
- int *pos_pick; // bottom of view == 0, top of file == combine chars, end of line is lower then start.
+ int *pos_pick; /* bottom of view == 0, top of file == combine chars, end of line is lower then start. */
int *mval; // [2]
int draw;
#endif
@@ -94,12 +94,14 @@ void console_scrollback_prompt_begin(struct SpaceConsole *sc, ConsoleLine *cl_du
{
/* fake the edit line being in the scroll buffer */
ConsoleLine *cl = sc->history.last;
+ int prompt_len = strlen(sc->prompt);
+
cl_dummy->type = CONSOLE_LINE_INPUT;
- cl_dummy->len = cl_dummy->len_alloc = strlen(sc->prompt) + cl->len;
+ cl_dummy->len = prompt_len + cl->len;
cl_dummy->len_alloc = cl_dummy->len + 1;
cl_dummy->line = MEM_mallocN(cl_dummy->len_alloc, "cl_dummy");
- memcpy(cl_dummy->line, sc->prompt, (cl_dummy->len_alloc - cl->len));
- memcpy(cl_dummy->line + ((cl_dummy->len_alloc - cl->len)) - 1, cl->line, cl->len + 1);
+ memcpy(cl_dummy->line, sc->prompt, prompt_len);
+ memcpy(cl_dummy->line + prompt_len, cl->line, cl->len + 1);
BLI_addtail(&sc->scrollback, cl_dummy);
}
void console_scrollback_prompt_end(struct SpaceConsole *sc, ConsoleLine *cl_dummy)
@@ -158,12 +160,13 @@ static int console_textview_line_color(struct TextViewContext *tvc, unsigned cha
const ConsoleLine *cl = (ConsoleLine *)sc->history.last;
const int prompt_len = strlen(sc->prompt);
const int cursor_loc = cl->cursor + prompt_len;
+ const int line_len = cl->len + prompt_len;
int xy[2] = {CONSOLE_DRAW_MARGIN, CONSOLE_DRAW_MARGIN};
int pen[2];
xy[1] += tvc->lheight / 6;
/* account for wrapping */
- if (cl->len < tvc->console_width) {
+ if (line_len < tvc->console_width) {
/* simple case, no wrapping */
pen[0] = tvc->cwidth * cursor_loc;
pen[1] = -2;
@@ -171,7 +174,7 @@ static int console_textview_line_color(struct TextViewContext *tvc, unsigned cha
else {
/* wrap */
pen[0] = tvc->cwidth * (cursor_loc % tvc->console_width);
- pen[1] = -2 + (((cl->len / tvc->console_width) - (cursor_loc / tvc->console_width)) * tvc->lheight);
+ pen[1] = -2 + (((line_len / tvc->console_width) - (cursor_loc / tvc->console_width)) * tvc->lheight);
}
/* cursor */
diff --git a/source/blender/editors/space_console/console_ops.c b/source/blender/editors/space_console/console_ops.c
index 7efcbcceb3c..d3ae5373a18 100644
--- a/source/blender/editors/space_console/console_ops.c
+++ b/source/blender/editors/space_console/console_ops.c
@@ -39,6 +39,7 @@
#include "BLI_string.h"
#include "BLI_dynstr.h"
#include "BLI_utildefines.h"
+#include "BLI_math.h"
#include "BKE_context.h"
#include "BKE_text.h" /* only for character utility funcs */
@@ -449,7 +450,9 @@ static int console_indent_exec(bContext *C, wmOperator *UNUSED(op))
memmove(ci->line + len, ci->line, ci->len);
memset(ci->line, ' ', len);
ci->len += len;
+ BLI_assert(ci->len >= 0);
console_line_cursor_set(ci, ci->cursor + len);
+ console_select_offset(sc, len);
console_textview_update_rect(sc, ar);
ED_area_tag_redraw(CTX_wm_area(C));
@@ -495,9 +498,10 @@ static int console_unindent_exec(bContext *C, wmOperator *UNUSED(op))
memmove(ci->line, ci->line + len, (ci->len - len) + 1);
ci->len -= len;
- console_line_cursor_set(ci, ci->cursor - len);
+ BLI_assert(ci->len >= 0);
- //console_select_offset(sc, -4);
+ console_line_cursor_set(ci, ci->cursor - len);
+ console_select_offset(sc, -len);
console_textview_update_rect(sc, ar);
ED_area_tag_redraw(CTX_wm_area(C));
@@ -554,6 +558,7 @@ static int console_delete_exec(bContext *C, wmOperator *op)
if (stride) {
memmove(ci->line + ci->cursor, ci->line + ci->cursor + stride, (ci->len - ci->cursor) + 1);
ci->len -= stride;
+ BLI_assert(ci->len >= 0);
done = TRUE;
}
}
@@ -570,6 +575,7 @@ static int console_delete_exec(bContext *C, wmOperator *op)
ci->cursor -= stride; /* same as above */
memmove(ci->line + ci->cursor, ci->line + ci->cursor + stride, (ci->len - ci->cursor) + 1);
ci->len -= stride;
+ BLI_assert(ci->len >= 0);
done = TRUE;
}
}
@@ -580,7 +586,7 @@ static int console_delete_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
else {
- console_select_offset(sc, -1);
+ console_select_offset(sc, -stride);
}
console_textview_update_rect(sc, ar);
@@ -650,7 +656,7 @@ static int console_clear_exec(bContext *C, wmOperator *op)
short scrollback = RNA_boolean_get(op->ptr, "scrollback");
short history = RNA_boolean_get(op->ptr, "history");
- /*ConsoleLine *ci= */ console_history_verify(C);
+ /*ConsoleLine *ci = */ console_history_verify(C);
if (scrollback) { /* last item in mistory */
while (sc->scrollback.first)
@@ -803,7 +809,7 @@ void CONSOLE_OT_history_append(wmOperatorType *ot)
ot->poll = ED_operator_console_active;
/* properties */
- RNA_def_string(ot->srna, "text", "", 0, "Text", "Text to insert at the cursor position");
+ RNA_def_string(ot->srna, "text", "", 0, "Text", "Text to insert at the cursor position");
RNA_def_int(ot->srna, "current_character", 0, 0, INT_MAX, "Cursor", "The index of the cursor", 0, 10000);
RNA_def_boolean(ot->srna, "remove_duplicates", 0, "Remove Duplicates", "Remove duplicate items in the history");
}
@@ -904,8 +910,8 @@ static int console_copy_exec(bContext *C, wmOperator *UNUSED(op))
for (cl = sc->scrollback.first; cl; cl = cl->next) {
if (sel[0] <= cl->len && sel[1] >= 0) {
- int sta = MAX2(sel[0], 0);
- int end = MIN2(sel[1], cl->len);
+ int sta = max_ii(sel[0], 0);
+ int end = min_ii(sel[1], cl->len);
if (BLI_dynstr_get_len(buf_dyn))
BLI_dynstr_append(buf_dyn, "\n");
@@ -1050,7 +1056,7 @@ static void console_modal_select_apply(bContext *C, wmOperator *op, wmEvent *eve
static void console_cursor_set_exit(bContext *UNUSED(C), wmOperator *op)
{
-// SpaceConsole *sc= CTX_wm_space_console(C);
+// SpaceConsole *sc = CTX_wm_space_console(C);
SetConsoleCursor *scu = op->customdata;
#if 0
@@ -1067,7 +1073,7 @@ static void console_cursor_set_exit(bContext *UNUSED(C), wmOperator *op)
static int console_modal_select_invoke(bContext *C, wmOperator *op, wmEvent *event)
{
SpaceConsole *sc = CTX_wm_space_console(C);
-// ARegion *ar= CTX_wm_region(C);
+// ARegion *ar = CTX_wm_region(C);
SetConsoleCursor *scu;
op->customdata = MEM_callocN(sizeof(SetConsoleCursor), "SetConsoleCursor");
diff --git a/source/blender/editors/space_console/space_console.c b/source/blender/editors/space_console/space_console.c
index a4f7e30ed7b..75add570708 100644
--- a/source/blender/editors/space_console/space_console.c
+++ b/source/blender/editors/space_console/space_console.c
@@ -91,7 +91,7 @@ static SpaceLink *console_new(const bContext *UNUSED(C))
ar->v2d.minzoom = ar->v2d.maxzoom = 1.0f;
/* for now, aspect ratio should be maintained, and zoom is clamped within sane default limits */
- //ar->v2d.keepzoom= (V2D_KEEPASPECT|V2D_LIMITZOOM);
+ //ar->v2d.keepzoom = (V2D_KEEPASPECT|V2D_LIMITZOOM);
return (SpaceLink *)sconsole;
}
@@ -142,7 +142,7 @@ static void console_main_area_init(wmWindowManager *wm, ARegion *ar)
/* always keep the bottom part of the view aligned, less annoying */
if (prev_y_min != ar->v2d.cur.ymin) {
- const float cur_y_range = BLI_RCT_SIZE_Y(&ar->v2d.cur);
+ const float cur_y_range = BLI_rctf_size_y(&ar->v2d.cur);
ar->v2d.cur.ymin = prev_y_min;
ar->v2d.cur.ymax = prev_y_min + cur_y_range;
}
@@ -162,7 +162,7 @@ static void console_main_area_init(wmWindowManager *wm, ARegion *ar)
static int id_drop_poll(bContext *UNUSED(C), wmDrag *drag, wmEvent *UNUSED(event))
{
-// SpaceConsole *sc= CTX_wm_space_console(C);
+// SpaceConsole *sc = CTX_wm_space_console(C);
if (drag->type == WM_DRAG_ID)
return 1;
return 0;
@@ -184,7 +184,7 @@ static void id_drop_copy(wmDrag *drag, wmDropBox *drop)
static int path_drop_poll(bContext *UNUSED(C), wmDrag *drag, wmEvent *UNUSED(event))
{
-// SpaceConsole *sc= CTX_wm_space_console(C);
+ // SpaceConsole *sc = CTX_wm_space_console(C);
if (drag->type == WM_DRAG_PATH)
return 1;
return 0;
@@ -359,7 +359,7 @@ static void console_header_area_draw(const bContext *C, ARegion *ar)
static void console_main_area_listener(ARegion *ar, wmNotifier *wmn)
{
- // SpaceInfo *sinfo= sa->spacedata.first;
+ // SpaceInfo *sinfo = sa->spacedata.first;
/* context changes */
switch (wmn->category) {
diff --git a/source/blender/editors/space_file/file_draw.c b/source/blender/editors/space_file/file_draw.c
index 55e75992b89..fb438ae45fb 100644
--- a/source/blender/editors/space_file/file_draw.c
+++ b/source/blender/editors/space_file/file_draw.c
@@ -257,21 +257,23 @@ static int get_file_icon(struct direntry *file)
else if (file->flags & BLENDERFILE)
return ICON_FILE_BLEND;
else if (file->flags & BLENDERFILE_BACKUP)
- return ICON_FILE_BLEND;
+ return ICON_FILE_BACKUP;
else if (file->flags & IMAGEFILE)
return ICON_FILE_IMAGE;
else if (file->flags & MOVIEFILE)
return ICON_FILE_MOVIE;
else if (file->flags & PYSCRIPTFILE)
return ICON_FILE_SCRIPT;
- else if (file->flags & SOUNDFILE)
+ else if (file->flags & SOUNDFILE)
return ICON_FILE_SOUND;
- else if (file->flags & FTFONTFILE)
+ else if (file->flags & FTFONTFILE)
return ICON_FILE_FONT;
- else if (file->flags & BTXFILE)
+ else if (file->flags & BTXFILE)
return ICON_FILE_BLANK;
- else if (file->flags & COLLADAFILE)
+ else if (file->flags & COLLADAFILE)
return ICON_FILE_BLANK;
+ else if (file->flags & TEXTFILE)
+ return ICON_FILE_TEXT;
else
return ICON_FILE_BLANK;
}
@@ -280,7 +282,7 @@ static void file_draw_icon(uiBlock *block, char *path, int sx, int sy, int icon,
{
uiBut *but;
int x, y;
- /*float alpha=1.0f;*/
+ // float alpha = 1.0f;
x = sx;
y = sy - height;
@@ -494,7 +496,7 @@ void file_draw_list(const bContext *C, ARegion *ar)
sx += (int)(v2d->tot.xmin + 2.0f);
sy = (int)(v2d->tot.ymax - sy);
- file = filelist_file(files, i);
+ file = filelist_file(files, i);
UI_ThemeColor4(TH_TEXT);
@@ -544,7 +546,7 @@ void file_draw_list(const bContext *C, ARegion *ar)
if (params->display == FILE_SHORTDISPLAY) {
sx += (int)layout->column_widths[COLUMN_NAME] + 12;
if (!(file->type & S_IFDIR)) {
- file_draw_string(sx, sy, file->size, layout->column_widths[COLUMN_SIZE], layout->tile_h, align);
+ file_draw_string(sx, sy, file->size, layout->column_widths[COLUMN_SIZE], layout->tile_h, align);
sx += (int)layout->column_widths[COLUMN_SIZE] + 12;
}
}
diff --git a/source/blender/editors/space_file/file_intern.h b/source/blender/editors/space_file/file_intern.h
index a07a560328c..e5c6a839380 100644
--- a/source/blender/editors/space_file/file_intern.h
+++ b/source/blender/editors/space_file/file_intern.h
@@ -66,6 +66,7 @@ void FILE_OT_select_border(struct wmOperatorType *ot);
void FILE_OT_select_bookmark(struct wmOperatorType *ot);
void FILE_OT_bookmark_add(struct wmOperatorType *ot);
void FILE_OT_delete_bookmark(struct wmOperatorType *ot);
+void FILE_OT_reset_recent(wmOperatorType *ot);
void FILE_OT_hidedot(struct wmOperatorType *ot);
void FILE_OT_execute(struct wmOperatorType *ot);
void FILE_OT_cancel(struct wmOperatorType *ot);
diff --git a/source/blender/editors/space_file/file_ops.c b/source/blender/editors/space_file/file_ops.c
index 040f276940d..763b18788de 100644
--- a/source/blender/editors/space_file/file_ops.c
+++ b/source/blender/editors/space_file/file_ops.c
@@ -64,11 +64,6 @@
#include <stdio.h>
#include <ctype.h>
-/* for events */
-#define NOTACTIVEFILE 0
-#define ACTIVATE 1
-#define INACTIVATE 2
-
/* ---------- FILE SELECTION ------------ */
static FileSelection find_file_mouse_rect(SpaceFile *sfile, ARegion *ar, const rcti *rect)
{
@@ -312,7 +307,7 @@ void FILE_OT_select_border(wmOperatorType *ot)
ot->poll = ED_operator_file_active;
ot->cancel = WM_border_select_cancel;
- /* rna */
+ /* properties */
WM_operator_properties_gesture_border(ot, 1);
}
@@ -352,6 +347,8 @@ static int file_select_invoke(bContext *C, wmOperator *op, wmEvent *event)
void FILE_OT_select(wmOperatorType *ot)
{
+ PropertyRNA *prop;
+
/* identifiers */
ot->name = "Activate/Select File";
ot->description = "Activate/select file";
@@ -361,10 +358,13 @@ void FILE_OT_select(wmOperatorType *ot)
ot->invoke = file_select_invoke;
ot->poll = ED_operator_file_active;
- /* rna */
- RNA_def_boolean(ot->srna, "extend", FALSE, "Extend", "Extend selection instead of deselecting everything first");
- RNA_def_boolean(ot->srna, "fill", FALSE, "Fill", "Select everything beginning with the last selection");
- RNA_def_boolean(ot->srna, "open", TRUE, "Open", "Open a directory when selecting it");
+ /* properties */
+ prop = RNA_def_boolean(ot->srna, "extend", FALSE, "Extend", "Extend selection instead of deselecting everything first");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+ prop = RNA_def_boolean(ot->srna, "fill", FALSE, "Fill", "Select everything beginning with the last selection");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+ prop = RNA_def_boolean(ot->srna, "open", TRUE, "Open", "Open a directory when selecting it");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
static int file_select_all_exec(bContext *C, wmOperator *UNUSED(op))
@@ -409,9 +409,7 @@ void FILE_OT_select_all_toggle(wmOperatorType *ot)
ot->exec = file_select_all_exec;
ot->poll = ED_operator_file_active;
- /* rna */
-
-
+ /* properties */
}
/* ---------- BOOKMARKS ----------- */
@@ -437,6 +435,8 @@ static int bookmark_select_exec(bContext *C, wmOperator *op)
void FILE_OT_select_bookmark(wmOperatorType *ot)
{
+ PropertyRNA *prop;
+
/* identifiers */
ot->name = "Select Directory";
ot->description = "Select a bookmarked directory";
@@ -446,7 +446,9 @@ void FILE_OT_select_bookmark(wmOperatorType *ot)
ot->exec = bookmark_select_exec;
ot->poll = ED_operator_file_active;
- RNA_def_string(ot->srna, "dir", "", 256, "Dir", "");
+ /* properties */
+ prop = RNA_def_string(ot->srna, "dir", "", FILE_MAXDIR, "Dir", "");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
static int bookmark_add_exec(bContext *C, wmOperator *UNUSED(op))
@@ -459,7 +461,7 @@ static int bookmark_add_exec(bContext *C, wmOperator *UNUSED(op))
if (params->dir[0] != '\0') {
char name[FILE_MAX];
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, params->dir, 0, 1);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, params->dir, FS_INSERT_SAVE);
BLI_make_file_string("/", name, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_BOOKMARK_FILE);
fsmenu_write_file(fsmenu, name);
}
@@ -503,6 +505,8 @@ static int bookmark_delete_exec(bContext *C, wmOperator *op)
void FILE_OT_delete_bookmark(wmOperatorType *ot)
{
+ PropertyRNA *prop;
+
/* identifiers */
ot->name = "Delete Bookmark";
ot->description = "Delete selected bookmark";
@@ -512,14 +516,45 @@ void FILE_OT_delete_bookmark(wmOperatorType *ot)
ot->exec = bookmark_delete_exec;
ot->poll = ED_operator_file_active;
- RNA_def_int(ot->srna, "index", -1, -1, 20000, "Index", "", -1, 20000);
+ /* properties */
+ prop = RNA_def_int(ot->srna, "index", -1, -1, 20000, "Index", "", -1, 20000);
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+}
+
+static int reset_recent_exec(bContext *C, wmOperator *UNUSED(op))
+{
+ ScrArea *sa = CTX_wm_area(C);
+ char name[FILE_MAX];
+ struct FSMenu *fsmenu = fsmenu_get();
+
+ while (fsmenu_get_entry(fsmenu, FS_CATEGORY_RECENT, 0) != NULL) {
+ fsmenu_remove_entry(fsmenu, FS_CATEGORY_RECENT, 0);
+ }
+ BLI_make_file_string("/", name, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_BOOKMARK_FILE);
+ fsmenu_write_file(fsmenu, name);
+ ED_area_tag_redraw(sa);
+
+ return OPERATOR_FINISHED;
+}
+
+void FILE_OT_reset_recent(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Reset Recent";
+ ot->description = "Reset Recent files";
+ ot->idname = "FILE_OT_reset_recent";
+
+ /* api callbacks */
+ ot->exec = reset_recent_exec;
+ ot->poll = ED_operator_file_active;
+
}
int file_highlight_set(SpaceFile *sfile, ARegion *ar, int mx, int my)
{
View2D *v2d = &ar->v2d;
FileSelectParams *params;
- int numfiles, origfile;
+ int numfiles, origfile;
if (sfile == NULL || sfile->files == NULL) return 0;
@@ -770,8 +805,9 @@ int file_exec(bContext *C, wmOperator *exec_op)
file_sfile_to_operator(op, sfile, filepath);
- if (BLI_exists(sfile->params->dir))
- fsmenu_insert_entry(fsmenu_get(), FS_CATEGORY_RECENT, sfile->params->dir, 0, 1);
+ if (BLI_exists(sfile->params->dir)) {
+ fsmenu_insert_entry(fsmenu_get(), FS_CATEGORY_RECENT, sfile->params->dir, FS_INSERT_SAVE | FS_INSERT_FIRST);
+ }
BLI_make_file_string(G.main->name, filepath, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_BOOKMARK_FILE);
fsmenu_write_file(fsmenu_get(), filepath);
@@ -794,7 +830,8 @@ void FILE_OT_execute(struct wmOperatorType *ot)
/* api callbacks */
ot->exec = file_exec;
ot->poll = file_operator_poll;
-
+
+ /* properties */
prop = RNA_def_boolean(ot->srna, "need_active", 0, "Need Active",
"Only execute if there's an active selected file in the file list");
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
@@ -812,7 +849,7 @@ int file_parent_exec(bContext *C, wmOperator *UNUSED(unused))
file_change_dir(C, 0);
WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, NULL);
}
- }
+ }
return OPERATOR_FINISHED;
@@ -905,7 +942,7 @@ int file_next_exec(bContext *C, wmOperator *UNUSED(unused))
folderlist_pushdir(sfile->folders_prev, sfile->params->dir);
file_change_dir(C, 1);
- }
+ }
WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, NULL);
return OPERATOR_FINISHED;
@@ -1068,7 +1105,7 @@ int file_directory_new_exec(bContext *C, wmOperator *op)
if (generate_name) {
/* create a new, non-existing folder name */
if (!new_folder_path(sfile->params->dir, path, name)) {
- BKE_report(op->reports, RPT_ERROR, "Couldn't create new folder name");
+ BKE_report(op->reports, RPT_ERROR, "Could not create new folder name");
return OPERATOR_CANCELLED;
}
}
@@ -1077,9 +1114,9 @@ int file_directory_new_exec(bContext *C, wmOperator *op)
BLI_dir_create_recursive(path);
if (!BLI_exists(path)) {
- BKE_report(op->reports, RPT_ERROR, "Couldn't create new folder");
+ BKE_report(op->reports, RPT_ERROR, "Could not create new folder");
return OPERATOR_CANCELLED;
- }
+ }
/* now remember file to jump into editing */
BLI_strncpy(sfile->params->renamefile, name, FILE_MAXFILE);
@@ -1098,6 +1135,8 @@ int file_directory_new_exec(bContext *C, wmOperator *op)
void FILE_OT_directory_new(struct wmOperatorType *ot)
{
+ PropertyRNA *prop;
+
/* identifiers */
ot->name = "Create New Directory";
ot->description = "Create a new directory";
@@ -1108,7 +1147,8 @@ void FILE_OT_directory_new(struct wmOperatorType *ot)
ot->exec = file_directory_new_exec;
ot->poll = ED_operator_file_active; /* <- important, handler is on window level */
- RNA_def_string_dir_path(ot->srna, "directory", "", FILE_MAX, "Directory", "Name of new directory");
+ prop = RNA_def_string_dir_path(ot->srna, "directory", "", FILE_MAX, "Directory", "Name of new directory");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
@@ -1387,11 +1427,11 @@ static int file_rename_poll(bContext *C)
SpaceFile *sfile = CTX_wm_space_file(C);
if (sfile && sfile->params) {
- if (sfile->params->active_file < 0) {
+ if (sfile->params->active_file < 0) {
poll = 0;
}
else {
- char dir[FILE_MAX], group[FILE_MAX];
+ char dir[FILE_MAX], group[FILE_MAX];
if (filelist_islibrary(sfile->files, dir, group)) poll = 0;
}
}
@@ -1420,11 +1460,11 @@ static int file_delete_poll(bContext *C)
struct direntry *file;
if (sfile && sfile->params) {
- if (sfile->params->active_file < 0) {
+ if (sfile->params->active_file < 0) {
poll = 0;
}
else {
- char dir[FILE_MAX], group[FILE_MAX];
+ char dir[FILE_MAX], group[FILE_MAX];
if (filelist_islibrary(sfile->files, dir, group)) poll = 0;
file = filelist_file(sfile->files, sfile->params->active_file);
if (file && S_ISDIR(file->type)) poll = 0;
@@ -1445,7 +1485,7 @@ int file_delete_exec(bContext *C, wmOperator *UNUSED(op))
file = filelist_file(sfile->files, sfile->params->active_file);
BLI_make_file_string(G.main->name, str, sfile->params->dir, file->relname);
- BLI_delete(str, 0, 0);
+ BLI_delete(str, 0, 0);
ED_fileselect_clear(C, sfile);
WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, NULL);
diff --git a/source/blender/editors/space_file/file_panels.c b/source/blender/editors/space_file/file_panels.c
index 51bd660e126..a159c88221e 100644
--- a/source/blender/editors/space_file/file_panels.c
+++ b/source/blender/editors/space_file/file_panels.c
@@ -67,14 +67,14 @@ static void file_panel_cb(bContext *C, void *arg_entry, void *UNUSED(arg_v))
WM_operator_properties_free(&ptr);
}
-static void file_panel_category(const bContext *C, Panel *pa, FSMenuCategory category, short *nr, int icon, int allow_delete, int reverse)
+static void file_panel_category(const bContext *C, Panel *pa, FSMenuCategory category, short *nr, int icon, int allow_delete)
{
SpaceFile *sfile = CTX_wm_space_file(C);
uiBlock *block;
uiBut *but;
uiLayout *box, *col;
struct FSMenu *fsmenu = fsmenu_get();
- int i, i_iter, nentries = fsmenu_get_nentries(fsmenu, category);
+ int i, nentries = fsmenu_get_nentries(fsmenu, category);
/* reset each time */
*nr = -1;
@@ -89,13 +89,11 @@ static void file_panel_category(const bContext *C, Panel *pa, FSMenuCategory cat
box = uiLayoutBox(pa->layout);
col = uiLayoutColumn(box, TRUE);
- for (i_iter = 0; i_iter < nentries; ++i_iter) {
+ for (i = 0; i < nentries; ++i) {
char dir[FILE_MAX];
char temp[FILE_MAX];
uiLayout *layout = uiLayoutRow(col, FALSE);
char *entry;
-
- i = reverse ? nentries - (i_iter + 1) : i_iter;
entry = fsmenu_get_entry(fsmenu, category, i);
@@ -134,7 +132,17 @@ static void file_panel_system(const bContext *C, Panel *pa)
SpaceFile *sfile = CTX_wm_space_file(C);
if (sfile)
- file_panel_category(C, pa, FS_CATEGORY_SYSTEM, &sfile->systemnr, ICON_DISK_DRIVE, 0, 0);
+ file_panel_category(C, pa, FS_CATEGORY_SYSTEM, &sfile->systemnr, ICON_DISK_DRIVE, 0);
+}
+
+static void file_panel_system_bookmarks(const bContext *C, Panel *pa)
+{
+ SpaceFile *sfile = CTX_wm_space_file(C);
+
+ if (sfile && !(U.uiflag & USER_HIDE_SYSTEM_BOOKMARKS) ) {
+ file_panel_category(C, pa, FS_CATEGORY_SYSTEM_BOOKMARKS, &sfile->systemnr, ICON_BOOKMARKS, 0);
+ }
+
}
static void file_panel_bookmarks(const bContext *C, Panel *pa)
@@ -147,17 +155,22 @@ static void file_panel_bookmarks(const bContext *C, Panel *pa)
uiItemO(row, IFACE_("Add"), ICON_ZOOMIN, "file.bookmark_add");
uiItemL(row, NULL, ICON_NONE);
- file_panel_category(C, pa, FS_CATEGORY_BOOKMARKS, &sfile->bookmarknr, ICON_BOOKMARKS, 1, 0);
+ file_panel_category(C, pa, FS_CATEGORY_BOOKMARKS, &sfile->bookmarknr, ICON_BOOKMARKS, 1);
}
}
static void file_panel_recent(const bContext *C, Panel *pa)
{
SpaceFile *sfile = CTX_wm_space_file(C);
+ uiLayout *row;
if (sfile) {
if (!(U.uiflag & USER_HIDE_RECENT) ) {
- file_panel_category(C, pa, FS_CATEGORY_RECENT, &sfile->recentnr, ICON_FILE_FOLDER, 0, 1);
+ row = uiLayoutRow(pa->layout, FALSE);
+ uiItemO(row, IFACE_("Reset"), ICON_X, "file.reset_recent");
+ uiItemL(row, NULL, ICON_NONE);
+
+ file_panel_category(C, pa, FS_CATEGORY_RECENT, &sfile->recentnr, ICON_FILE_FOLDER, 0);
}
}
}
@@ -190,7 +203,7 @@ static void file_panel_operator(const bContext *C, Panel *pa)
{
SpaceFile *sfile = CTX_wm_space_file(C);
wmOperator *op = sfile->op;
- // int empty= 1, flag;
+ // int empty = 1, flag;
uiBlockSetFunc(uiLayoutGetBlock(pa->layout), file_draw_check_cb, NULL, NULL);
@@ -209,6 +222,12 @@ void file_panels_register(ARegionType *art)
pt->draw = file_panel_system;
BLI_addtail(&art->paneltypes, pt);
+ pt = MEM_callocN(sizeof(PanelType), "spacetype file system bookmarks");
+ strcpy(pt->idname, "FILE_PT_system_bookmarks");
+ strcpy(pt->label, N_("System Bookmarks"));
+ pt->draw = file_panel_system_bookmarks;
+ BLI_addtail(&art->paneltypes, pt);
+
pt = MEM_callocN(sizeof(PanelType), "spacetype file bookmarks");
strcpy(pt->idname, "FILE_PT_bookmarks");
strcpy(pt->label, N_("Bookmarks"));
diff --git a/source/blender/editors/space_file/filelist.c b/source/blender/editors/space_file/filelist.c
index d3b4df05aa9..8f94086013c 100644
--- a/source/blender/editors/space_file/filelist.c
+++ b/source/blender/editors/space_file/filelist.c
@@ -143,7 +143,8 @@ typedef struct FolderList {
#define SPECIAL_IMG_FONTFILE 8
#define SPECIAL_IMG_UNKNOWNFILE 9
#define SPECIAL_IMG_LOADING 10
-#define SPECIAL_IMG_MAX SPECIAL_IMG_LOADING + 1
+#define SPECIAL_IMG_BACKUP 11
+#define SPECIAL_IMG_MAX SPECIAL_IMG_BACKUP + 1
static ImBuf *gSpecialFileImages[SPECIAL_IMG_MAX];
@@ -300,7 +301,7 @@ static int is_hidden_file(const char *filename, short hide_dot)
if ( (len > 0) && (filename[len - 1] == '~') ) {
is_hidden = 1; /* ignore file~ */
}
- }
+ }
}
else {
if (((filename[0] == '.') && (filename[1] == 0) )) {
@@ -360,7 +361,7 @@ void filelist_filter(FileList *filelist)
struct direntry *file = &filelist->filelist[i];
if (filelist->filterf(file, filelist->dir, filelist->filter, filelist->hide_dot) ) {
num_filtered++;
- }
+ }
}
if (filelist->fidx) {
@@ -420,7 +421,7 @@ void filelist_free_icons(void)
}
}
-//-----------------FOLDERLIST (previous/next) --------------//
+/* -----------------FOLDERLIST (previous/next) -------------- */
ListBase *folderlist_new(void)
{
ListBase *p = MEM_callocN(sizeof(ListBase), "folderlist");
@@ -520,7 +521,7 @@ static void filelist_read_main(struct FileList *filelist);
static void filelist_read_library(struct FileList *filelist);
static void filelist_read_dir(struct FileList *filelist);
-//------------------FILELIST------------------------//
+/* ------------------FILELIST------------------------ */
FileList *filelist_new(short type)
{
FileList *p = MEM_callocN(sizeof(FileList), "filelist");
@@ -557,7 +558,7 @@ void filelist_free(struct FileList *filelist)
}
for (i = 0; i < filelist->numfiles; ++i) {
- if (filelist->filelist[i].image) {
+ if (filelist->filelist[i].image) {
IMB_freeImBuf(filelist->filelist[i].image);
}
filelist->filelist[i].image = NULL;
@@ -573,7 +574,7 @@ void filelist_free(struct FileList *filelist)
filelist->numfiles = 0;
free(filelist->filelist);
- filelist->filelist = NULL;
+ filelist->filelist = NULL;
filelist->filter = 0;
filelist->filter_glob[0] = '\0';
filelist->numfiltered = 0;
@@ -683,6 +684,9 @@ ImBuf *filelist_geticon(struct FileList *filelist, int index)
else if (file->flags & IMAGEFILE) {
ibuf = gSpecialFileImages[SPECIAL_IMG_LOADING];
}
+ else if (file->flags & BLENDERFILE_BACKUP) {
+ ibuf = gSpecialFileImages[SPECIAL_IMG_BACKUP];
+ }
return ibuf;
}
@@ -748,7 +752,9 @@ static int file_is_blend_backup(const char *str)
a = strlen(str);
b = 7;
- if (a == 0 || b >= a) ;
+ if (a == 0 || b >= a) {
+ /* pass */
+ }
else {
char *loc;
@@ -779,6 +785,7 @@ static int file_extension_type(const char *relname)
}
else if (BLI_testextensie(relname, ".txt") ||
BLI_testextensie(relname, ".glsl") ||
+ BLI_testextensie(relname, ".osl") ||
BLI_testextensie(relname, ".data"))
{
return TEXTFILE;
@@ -789,7 +796,7 @@ static int file_extension_type(const char *relname)
BLI_testextensie(relname, ".otf") ||
BLI_testextensie(relname, ".otc"))
{
- return FTFONTFILE;
+ return FTFONTFILE;
}
else if (BLI_testextensie(relname, ".btx")) {
return BTXFILE;
@@ -800,14 +807,14 @@ static int file_extension_type(const char *relname)
else if (BLI_testextensie_array(relname, imb_ext_image) ||
(G.have_quicktime && BLI_testextensie_array(relname, imb_ext_image_qt)))
{
- return IMAGEFILE;
+ return IMAGEFILE;
}
else if (BLI_testextensie_array(relname, imb_ext_movie)) {
- return MOVIEFILE;
+ return MOVIEFILE;
}
else if (BLI_testextensie_array(relname, imb_ext_audio)) {
return SOUNDFILE;
- }
+ }
return 0;
}
@@ -815,8 +822,10 @@ int ED_file_extension_icon(const char *relname)
{
int type = file_extension_type(relname);
- if (type == BLENDERFILE || type == BLENDERFILE_BACKUP)
+ if (type == BLENDERFILE)
return ICON_FILE_BLEND;
+ else if (type == BLENDERFILE_BACKUP)
+ return ICON_FILE_BACKUP;
else if (type == IMAGEFILE)
return ICON_FILE_IMAGE;
else if (type == MOVIEFILE)
@@ -831,6 +840,8 @@ int ED_file_extension_icon(const char *relname)
return ICON_FILE_BLANK;
else if (type == COLLADAFILE)
return ICON_FILE_BLANK;
+ else if (type == TEXTFILE)
+ return ICON_FILE_TEXT;
return ICON_FILE_BLANK;
}
@@ -932,7 +943,7 @@ void filelist_parent(struct FileList *filelist)
void filelist_select_file(struct FileList *filelist, int index, FileSelType select, unsigned int flag, FileCheckType check)
{
struct direntry *file = filelist_file(filelist, index);
- if (file != NULL) {
+ if (file != NULL) {
int check_ok = 0;
switch (check) {
case CHECK_DIRS:
@@ -967,7 +978,7 @@ void filelist_select(struct FileList *filelist, FileSelection *sel, FileSelType
/* select all valid files between first and last indicated */
if ( (sel->first >= 0) && (sel->first < filelist->numfiltered) && (sel->last >= 0) && (sel->last < filelist->numfiltered) ) {
int current_file;
- for (current_file = sel->first; current_file <= sel->last; current_file++) {
+ for (current_file = sel->first; current_file <= sel->last; current_file++) {
filelist_select_file(filelist, current_file, select, flag, check);
}
}
@@ -1034,7 +1045,7 @@ void filelist_from_library(struct FileList *filelist)
struct ImBuf *ima;
int ok, i, nprevs, nnames, idcode;
char filename[FILE_MAX];
- char dir[FILE_MAX], group[GROUP_MAX];
+ char dir[FILE_MAX], group[GROUP_MAX];
/* name test */
ok = filelist_islibrary(filelist, dir, group);
@@ -1223,21 +1234,22 @@ void filelist_from_main(struct FileList *filelist)
if (ok) {
if (!filelist->hide_dot || id->name[2] != '.') {
memset(files, 0, sizeof(struct direntry));
- if (id->lib == NULL)
+ if (id->lib == NULL) {
files->relname = BLI_strdup(id->name + 2);
+ }
else {
- files->relname = MEM_mallocN(FILE_MAX + 32, "filename for lib");
- sprintf(files->relname, "%s | %s", id->lib->name, id->name + 2);
+ files->relname = MEM_mallocN(FILE_MAX + (MAX_ID_NAME - 2), "filename for lib");
+ BLI_snprintf(files->relname, FILE_MAX + (MAX_ID_NAME - 2) + 3, "%s | %s", id->lib->name, id->name + 2);
}
files->type |= S_IFREG;
-#if 0 // XXXXX TODO show the selection status of the objects
+#if 0 /* XXXXX TODO show the selection status of the objects */
if (!filelist->has_func) { /* F4 DATA BROWSE */
if (idcode == ID_OB) {
if ( ((Object *)id)->flag & SELECT) files->selflag |= SELECTED_FILE;
}
else if (idcode == ID_SCE) {
if ( ((Scene *)id)->r.scemode & R_BG_RENDER) files->selflag |= SELECTED_FILE;
- }
+ }
}
#endif
files->nr = totbl + 1;
@@ -1246,10 +1258,10 @@ void filelist_from_main(struct FileList *filelist)
if (idcode == ID_MA || idcode == ID_TE || idcode == ID_LA || idcode == ID_WO || idcode == ID_IM) {
files->flags |= IMAGEFILE;
}
- if (id->lib && fake) BLI_snprintf(files->extra, sizeof(files->extra), "LF %d", id->us);
- else if (id->lib) BLI_snprintf(files->extra, sizeof(files->extra), "L %d", id->us);
- else if (fake) BLI_snprintf(files->extra, sizeof(files->extra), "F %d", id->us);
- else BLI_snprintf(files->extra, sizeof(files->extra), " %d", id->us);
+ if (id->lib && fake) BLI_snprintf(files->extra, sizeof(files->extra), "LF %d", id->us);
+ else if (id->lib) BLI_snprintf(files->extra, sizeof(files->extra), "L %d", id->us);
+ else if (fake) BLI_snprintf(files->extra, sizeof(files->extra), "F %d", id->us);
+ else BLI_snprintf(files->extra, sizeof(files->extra), " %d", id->us);
if (id->lib) {
if (totlib == 0) firstlib = files;
@@ -1298,7 +1310,7 @@ static void thumbnails_startjob(void *tjv, short *stop, short *do_update, float
if (limg->flags & IMAGEFILE) {
limg->img = IMB_thumb_manage(limg->path, THB_NORMAL, THB_SOURCE_IMAGE);
}
- else if (limg->flags & BLENDERFILE) {
+ else if (limg->flags & (BLENDERFILE | BLENDERFILE_BACKUP)) {
limg->img = IMB_thumb_manage(limg->path, THB_NORMAL, THB_SOURCE_BLEND);
}
else if (limg->flags & MOVIEFILE) {
@@ -1355,7 +1367,7 @@ void thumbnails_start(struct FileList *filelist, const struct bContext *C)
tj->filelist = filelist;
for (idx = 0; idx < filelist->numfiles; idx++) {
if (!filelist->filelist[idx].image) {
- if ( (filelist->filelist[idx].flags & (IMAGEFILE | MOVIEFILE | BLENDERFILE)) ) {
+ if ( (filelist->filelist[idx].flags & (IMAGEFILE | MOVIEFILE | BLENDERFILE | BLENDERFILE_BACKUP)) ) {
FileImage *limg = MEM_callocN(sizeof(struct FileImage), "loadimage");
BLI_strncpy(limg->path, filelist->filelist[idx].path, FILE_MAX);
limg->index = idx;
diff --git a/source/blender/editors/space_file/filesel.c b/source/blender/editors/space_file/filesel.c
index 09231efd367..49562958f82 100644
--- a/source/blender/editors/space_file/filesel.c
+++ b/source/blender/editors/space_file/filesel.c
@@ -94,6 +94,9 @@ FileSelectParams *ED_fileselect_get_params(struct SpaceFile *sfile)
return sfile->params;
}
+/**
+ * \note RNA_struct_property_is_set_ex is used here because we wan't
+ * the previously used settings to be used here rather then overriding them */
short ED_fileselect_set_params(SpaceFile *sfile)
{
FileSelectParams *params;
@@ -124,7 +127,7 @@ short ED_fileselect_set_params(SpaceFile *sfile)
else
params->type = FILE_SPECIAL;
- if (is_filepath && RNA_struct_property_is_set(op->ptr, "filepath")) {
+ if (is_filepath && RNA_struct_property_is_set_ex(op->ptr, "filepath", FALSE)) {
char name[FILE_MAX];
RNA_string_get(op->ptr, "filepath", name);
if (params->type == FILE_LOADLIB) {
@@ -136,12 +139,12 @@ short ED_fileselect_set_params(SpaceFile *sfile)
}
}
else {
- if (is_directory && RNA_struct_property_is_set(op->ptr, "directory")) {
+ if (is_directory && RNA_struct_property_is_set_ex(op->ptr, "directory", FALSE)) {
RNA_string_get(op->ptr, "directory", params->dir);
sfile->params->file[0] = '\0';
}
- if (is_filename && RNA_struct_property_is_set(op->ptr, "filename")) {
+ if (is_filename && RNA_struct_property_is_set_ex(op->ptr, "filename", FALSE)) {
RNA_string_get(op->ptr, "filename", params->file);
}
}
@@ -165,8 +168,6 @@ short ED_fileselect_set_params(SpaceFile *sfile)
params->filter |= RNA_boolean_get(op->ptr, "filter_image") ? IMAGEFILE : 0;
if (RNA_struct_find_property(op->ptr, "filter_movie"))
params->filter |= RNA_boolean_get(op->ptr, "filter_movie") ? MOVIEFILE : 0;
- if (RNA_struct_find_property(op->ptr, "filter_text"))
- params->filter |= RNA_boolean_get(op->ptr, "filter_text") ? TEXTFILE : 0;
if (RNA_struct_find_property(op->ptr, "filter_python"))
params->filter |= RNA_boolean_get(op->ptr, "filter_python") ? PYSCRIPTFILE : 0;
if (RNA_struct_find_property(op->ptr, "filter_font"))
@@ -228,7 +229,7 @@ short ED_fileselect_set_params(SpaceFile *sfile)
}
if (is_relative_path) {
- if (!RNA_struct_property_is_set(op->ptr, "relative_path")) {
+ if (!RNA_struct_property_is_set_ex(op->ptr, "relative_path", FALSE)) {
RNA_boolean_set(op->ptr, "relative_path", U.flag & USER_RELPATHS);
}
}
@@ -270,12 +271,12 @@ int ED_fileselect_layout_numfiles(FileLayout *layout, ARegion *ar)
int numfiles;
if (layout->flag & FILE_LAYOUT_HOR) {
- int width = (int)(BLI_RCT_SIZE_X(&ar->v2d.cur) - 2 * layout->tile_border_x);
+ int width = (int)(BLI_rctf_size_x(&ar->v2d.cur) - 2 * layout->tile_border_x);
numfiles = (int)((float)width / (float)layout->tile_w + 0.5f);
return numfiles * layout->rows;
}
else {
- int height = (int)(BLI_RCT_SIZE_Y(&ar->v2d.cur) - 2 * layout->tile_border_y);
+ int height = (int)(BLI_rctf_size_y(&ar->v2d.cur) - 2 * layout->tile_border_y);
numfiles = (int)((float)height / (float)layout->tile_h + 0.5f);
return numfiles * layout->columns;
}
@@ -307,7 +308,7 @@ FileSelection ED_fileselect_layout_offset_rect(FileLayout *layout, const rcti *r
CLAMP(rowmin, 0, layout->rows - 1);
CLAMP(colmax, 0, layout->columns - 1);
CLAMP(rowmax, 0, layout->rows - 1);
- }
+ }
if ((colmin > layout->columns - 1) || (rowmin > layout->rows - 1)) {
sel.first = -1;
@@ -503,7 +504,7 @@ void ED_fileselect_init_layout(struct SpaceFile *sfile, ARegion *ar)
layout->prv_border_y = 6;
layout->tile_w = layout->prv_w + 2 * layout->prv_border_x;
layout->tile_h = layout->prv_h + 2 * layout->prv_border_y + textheight;
- layout->width = (int)(BLI_RCT_SIZE_X(&v2d->cur) - 2 * layout->tile_border_x);
+ layout->width = (int)(BLI_rctf_size_x(&v2d->cur) - 2 * layout->tile_border_x);
layout->columns = layout->width / (layout->tile_w + 2 * layout->tile_border_x);
if (layout->columns > 0)
layout->rows = numfiles / layout->columns + 1; // XXX dirty, modulo is zero
@@ -522,7 +523,7 @@ void ED_fileselect_init_layout(struct SpaceFile *sfile, ARegion *ar)
layout->prv_border_x = 0;
layout->prv_border_y = 0;
layout->tile_h = textheight * 3 / 2;
- layout->height = (int)(BLI_RCT_SIZE_Y(&v2d->cur) - 2 * layout->tile_border_y);
+ layout->height = (int)(BLI_rctf_size_y(&v2d->cur) - 2 * layout->tile_border_y);
layout->rows = layout->height / (layout->tile_h + 2 * layout->tile_border_y);
column_widths(sfile->files, layout);
diff --git a/source/blender/editors/space_file/fsmenu.c b/source/blender/editors/space_file/fsmenu.c
index a127e2ca2bc..a5647c06b92 100644
--- a/source/blender/editors/space_file/fsmenu.c
+++ b/source/blender/editors/space_file/fsmenu.c
@@ -80,9 +80,9 @@ struct _FSMenuEntry {
typedef struct FSMenu {
FSMenuEntry *fsmenu_system;
+ FSMenuEntry *fsmenu_system_bookmarks;
FSMenuEntry *fsmenu_bookmarks;
FSMenuEntry *fsmenu_recent;
-
} FSMenu;
static FSMenu *g_fsmenu = NULL;
@@ -97,84 +97,100 @@ FSMenu *fsmenu_get(void)
static FSMenuEntry *fsmenu_get_category(struct FSMenu *fsmenu, FSMenuCategory category)
{
- FSMenuEntry *fsms = NULL;
+ FSMenuEntry *fsm_head = NULL;
switch (category) {
case FS_CATEGORY_SYSTEM:
- fsms = fsmenu->fsmenu_system;
+ fsm_head = fsmenu->fsmenu_system;
+ break;
+ case FS_CATEGORY_SYSTEM_BOOKMARKS:
+ fsm_head = fsmenu->fsmenu_system_bookmarks;
break;
case FS_CATEGORY_BOOKMARKS:
- fsms = fsmenu->fsmenu_bookmarks;
+ fsm_head = fsmenu->fsmenu_bookmarks;
break;
case FS_CATEGORY_RECENT:
- fsms = fsmenu->fsmenu_recent;
+ fsm_head = fsmenu->fsmenu_recent;
break;
}
- return fsms;
+ return fsm_head;
}
-static void fsmenu_set_category(struct FSMenu *fsmenu, FSMenuCategory category, FSMenuEntry *fsms)
+static void fsmenu_set_category(struct FSMenu *fsmenu, FSMenuCategory category, FSMenuEntry *fsm_head)
{
switch (category) {
case FS_CATEGORY_SYSTEM:
- fsmenu->fsmenu_system = fsms;
+ fsmenu->fsmenu_system = fsm_head;
+ break;
+ case FS_CATEGORY_SYSTEM_BOOKMARKS:
+ fsmenu->fsmenu_system_bookmarks = fsm_head;
break;
case FS_CATEGORY_BOOKMARKS:
- fsmenu->fsmenu_bookmarks = fsms;
+ fsmenu->fsmenu_bookmarks = fsm_head;
break;
case FS_CATEGORY_RECENT:
- fsmenu->fsmenu_recent = fsms;
+ fsmenu->fsmenu_recent = fsm_head;
break;
}
}
int fsmenu_get_nentries(struct FSMenu *fsmenu, FSMenuCategory category)
{
- FSMenuEntry *fsme;
+ FSMenuEntry *fsm_iter;
int count = 0;
- for (fsme = fsmenu_get_category(fsmenu, category); fsme; fsme = fsme->next)
+ for (fsm_iter = fsmenu_get_category(fsmenu, category); fsm_iter; fsm_iter = fsm_iter->next) {
count++;
+ }
return count;
}
char *fsmenu_get_entry(struct FSMenu *fsmenu, FSMenuCategory category, int idx)
{
- FSMenuEntry *fsme;
+ FSMenuEntry *fsm_iter;
- for (fsme = fsmenu_get_category(fsmenu, category); fsme && idx; fsme = fsme->next)
+ for (fsm_iter = fsmenu_get_category(fsmenu, category); fsm_iter && idx; fsm_iter = fsm_iter->next) {
idx--;
+ }
- return fsme ? fsme->path : NULL;
+ return fsm_iter ? fsm_iter->path : NULL;
}
short fsmenu_can_save(struct FSMenu *fsmenu, FSMenuCategory category, int idx)
{
- FSMenuEntry *fsme;
+ FSMenuEntry *fsm_iter;
- for (fsme = fsmenu_get_category(fsmenu, category); fsme && idx; fsme = fsme->next)
+ for (fsm_iter = fsmenu_get_category(fsmenu, category); fsm_iter && idx; fsm_iter = fsm_iter->next) {
idx--;
+ }
- return fsme ? fsme->save : 0;
+ return fsm_iter ? fsm_iter->save : 0;
}
-void fsmenu_insert_entry(struct FSMenu *fsmenu, FSMenuCategory category, const char *path, int sorted, short save)
+void fsmenu_insert_entry(struct FSMenu *fsmenu, FSMenuCategory category, const char *path, FSMenuInsert flag)
{
- FSMenuEntry *prev;
- FSMenuEntry *fsme;
- FSMenuEntry *fsms;
+ FSMenuEntry *fsm_prev;
+ FSMenuEntry *fsm_iter;
+ FSMenuEntry *fsm_head;
- fsms = fsmenu_get_category(fsmenu, category);
- prev = fsme = fsms;
+ fsm_head = fsmenu_get_category(fsmenu, category);
+ fsm_prev = fsm_head; /* this is odd and not really correct? */
- for (; fsme; prev = fsme, fsme = fsme->next) {
- if (fsme->path) {
- const int cmp_ret = BLI_path_cmp(path, fsme->path);
+ for (fsm_iter = fsm_head; fsm_iter; fsm_prev = fsm_iter, fsm_iter = fsm_iter->next) {
+ if (fsm_iter->path) {
+ const int cmp_ret = BLI_path_cmp(path, fsm_iter->path);
if (cmp_ret == 0) {
+ if (flag & FS_INSERT_FIRST) {
+ if (fsm_iter != fsm_head) {
+ fsm_prev->next = fsm_iter->next;
+ fsm_iter->next = fsm_head;
+ fsmenu_set_category(fsmenu, category, fsm_iter);
+ }
+ }
return;
}
- else if (sorted && cmp_ret < 0) {
+ else if ((flag & FS_INSERT_SORTED) && cmp_ret < 0) {
break;
}
}
@@ -182,78 +198,82 @@ void fsmenu_insert_entry(struct FSMenu *fsmenu, FSMenuCategory category, const c
/* if we're bookmarking this, file should come
* before the last separator, only automatically added
* current dir go after the last sep. */
- if (save) {
+ if (flag & FS_INSERT_SAVE) {
break;
}
}
}
- fsme = MEM_mallocN(sizeof(*fsme), "fsme");
- fsme->path = BLI_strdup(path);
- fsme->save = save;
+ fsm_iter = MEM_mallocN(sizeof(*fsm_iter), "fsme");
+ fsm_iter->path = BLI_strdup(path);
+ fsm_iter->save = (flag & FS_INSERT_SAVE) != 0;
- if (prev) {
- fsme->next = prev->next;
- prev->next = fsme;
+ if (fsm_prev) {
+ if (flag & FS_INSERT_FIRST) {
+ fsm_iter->next = fsm_head;
+ fsmenu_set_category(fsmenu, category, fsm_iter);
+ }
+ else {
+ fsm_iter->next = fsm_prev->next;
+ fsm_prev->next = fsm_iter;
+ }
}
else {
- fsme->next = fsms;
- fsmenu_set_category(fsmenu, category, fsme);
+ fsm_iter->next = fsm_head;
+ fsmenu_set_category(fsmenu, category, fsm_iter);
}
}
void fsmenu_remove_entry(struct FSMenu *fsmenu, FSMenuCategory category, int idx)
{
- FSMenuEntry *prev = NULL, *fsme = NULL;
- FSMenuEntry *fsms = fsmenu_get_category(fsmenu, category);
+ FSMenuEntry *fsm_prev = NULL;
+ FSMenuEntry *fsm_iter;
+ FSMenuEntry *fsm_head;
+
+ fsm_head = fsmenu_get_category(fsmenu, category);
- for (fsme = fsms; fsme && idx; prev = fsme, fsme = fsme->next)
+ for (fsm_iter = fsm_head; fsm_iter && idx; fsm_prev = fsm_iter, fsm_iter = fsm_iter->next)
idx--;
- if (fsme) {
+ if (fsm_iter) {
/* you should only be able to remove entries that were
* not added by default, like windows drives.
* also separators (where path == NULL) shouldn't be removed */
- if (fsme->save && fsme->path) {
+ if (fsm_iter->save && fsm_iter->path) {
/* remove fsme from list */
- if (prev) {
- prev->next = fsme->next;
+ if (fsm_prev) {
+ fsm_prev->next = fsm_iter->next;
}
else {
- fsms = fsme->next;
- fsmenu_set_category(fsmenu, category, fsms);
+ fsm_head = fsm_iter->next;
+ fsmenu_set_category(fsmenu, category, fsm_head);
}
/* free entry */
- MEM_freeN(fsme->path);
- MEM_freeN(fsme);
+ MEM_freeN(fsm_iter->path);
+ MEM_freeN(fsm_iter);
}
}
}
void fsmenu_write_file(struct FSMenu *fsmenu, const char *filename)
{
- FSMenuEntry *fsme = NULL;
- int nskip = 0;
+ FSMenuEntry *fsm_iter = NULL;
+ int nwritten = 0;
FILE *fp = BLI_fopen(filename, "w");
if (!fp) return;
fprintf(fp, "[Bookmarks]\n");
- for (fsme = fsmenu_get_category(fsmenu, FS_CATEGORY_BOOKMARKS); fsme; fsme = fsme->next) {
- if (fsme->path && fsme->save) {
- fprintf(fp, "%s\n", fsme->path);
+ for (fsm_iter = fsmenu_get_category(fsmenu, FS_CATEGORY_BOOKMARKS); fsm_iter; fsm_iter = fsm_iter->next) {
+ if (fsm_iter->path && fsm_iter->save) {
+ fprintf(fp, "%s\n", fsm_iter->path);
}
}
fprintf(fp, "[Recent]\n");
- nskip = fsmenu_get_nentries(fsmenu, FS_CATEGORY_RECENT) - FSMENU_RECENT_MAX;
- /* skip first entries if list too long */
- for (fsme = fsmenu_get_category(fsmenu, FS_CATEGORY_RECENT); fsme && (nskip > 0); fsme = fsme->next, --nskip) {
- /* pass */
- }
- for (; fsme; fsme = fsme->next) {
- if (fsme->path && fsme->save) {
- fprintf(fp, "%s\n", fsme->path);
+ for (fsm_iter = fsmenu_get_category(fsmenu, FS_CATEGORY_RECENT); fsm_iter && (nwritten < FSMENU_RECENT_MAX); fsm_iter = fsm_iter->next, ++nwritten) {
+ if (fsm_iter->path && fsm_iter->save) {
+ fprintf(fp, "%s\n", fsm_iter->path);
}
}
fclose(fp);
@@ -288,7 +308,7 @@ void fsmenu_read_bookmarks(struct FSMenu *fsmenu, const char *filename)
if (BLI_exists(line))
#endif
{
- fsmenu_insert_entry(fsmenu, category, line, 0, 1);
+ fsmenu_insert_entry(fsmenu, category, line, FS_INSERT_SAVE);
}
}
}
@@ -315,16 +335,16 @@ void fsmenu_read_system(struct FSMenu *fsmenu, int read_bookmarks)
tmps[2] = '\\';
tmps[3] = 0;
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, tmps, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, tmps, FS_INSERT_SORTED);
}
}
/* Adding Desktop and My Documents */
if (read_bookmarks) {
SHGetSpecialFolderPath(0, line, CSIDL_PERSONAL, 0);
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, line, FS_INSERT_SORTED);
SHGetSpecialFolderPath(0, line, CSIDL_DESKTOPDIRECTORY, 0);
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, line, FS_INSERT_SORTED);
}
}
#else
@@ -347,7 +367,7 @@ void fsmenu_read_system(struct FSMenu *fsmenu, int read_bookmarks)
FSRefMakePath(&dir, path, FILE_MAX);
if (strcmp((char *)path, "/home") && strcmp((char *)path, "/net")) {
/* /net and /home are meaningless on OSX, home folders are stored in /Users */
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, (char *)path, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, (char *)path, FS_INSERT_SORTED);
}
}
@@ -357,26 +377,26 @@ void fsmenu_read_system(struct FSMenu *fsmenu, int read_bookmarks)
home = getenv("HOME");
if (read_bookmarks && home) {
BLI_snprintf(line, 256, "%s/", home);
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, line, FS_INSERT_SORTED);
BLI_snprintf(line, 256, "%s/Desktop/", home);
if (BLI_exists(line)) {
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, line, FS_INSERT_SORTED);
}
BLI_snprintf(line, 256, "%s/Documents/", home);
if (BLI_exists(line)) {
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, line, FS_INSERT_SORTED);
}
BLI_snprintf(line, 256, "%s/Pictures/", home);
if (BLI_exists(line)) {
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, line, FS_INSERT_SORTED);
}
BLI_snprintf(line, 256, "%s/Music/", home);
if (BLI_exists(line)) {
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, line, FS_INSERT_SORTED);
}
BLI_snprintf(line, 256, "%s/Movies/", home);
if (BLI_exists(line)) {
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, line, FS_INSERT_SORTED);
}
}
#else
@@ -409,7 +429,7 @@ void fsmenu_read_system(struct FSMenu *fsmenu, int read_bookmarks)
if (!CFStringGetCString(pathString, line, 256, kCFStringEncodingASCII))
continue;
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, line, FS_INSERT_SORTED);
CFRelease(pathString);
CFRelease(cfURL);
@@ -436,7 +456,10 @@ void fsmenu_read_system(struct FSMenu *fsmenu, int read_bookmarks)
FSRefMakePath(&dir, path, FILE_MAX);
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, (char *)path, 1, 0);
+ if (strcmp((char *)path, "/home") && strcmp((char *)path, "/net")) {
+ /* /net and /home are meaningless on OSX, home folders are stored in /Users */
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, (char *)path, FS_INSERT_SORTED);
+ }
}
/* Finally get user favorite places */
@@ -459,7 +482,7 @@ void fsmenu_read_system(struct FSMenu *fsmenu, int read_bookmarks)
if (!CFStringGetCString(pathString, line, 256, kCFStringEncodingASCII))
continue;
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, line, FS_INSERT_SORTED);
CFRelease(pathString);
CFRelease(cfURL);
@@ -477,10 +500,10 @@ void fsmenu_read_system(struct FSMenu *fsmenu, int read_bookmarks)
if (read_bookmarks && home) {
BLI_snprintf(line, FILE_MAXDIR, "%s/", home);
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, line, FS_INSERT_SORTED);
BLI_snprintf(line, FILE_MAXDIR, "%s/Desktop/", home);
if (BLI_exists(line)) {
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_BOOKMARKS, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, line, FS_INSERT_SORTED);
}
}
@@ -505,10 +528,11 @@ void fsmenu_read_system(struct FSMenu *fsmenu, int read_bookmarks)
len = strlen(mnt->mnt_dir);
if (len && mnt->mnt_dir[len - 1] != '/') {
BLI_snprintf(line, FILE_MAXDIR, "%s/", mnt->mnt_dir);
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, line, 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, line, FS_INSERT_SORTED);
+ }
+ else {
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, mnt->mnt_dir, FS_INSERT_SORTED);
}
- else
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, mnt->mnt_dir, 1, 0);
found = 1;
}
@@ -520,7 +544,7 @@ void fsmenu_read_system(struct FSMenu *fsmenu, int read_bookmarks)
/* fallback */
if (!found)
- fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, "/", 1, 0);
+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_SYSTEM, "/", FS_INSERT_SORTED);
}
}
#endif
@@ -530,15 +554,17 @@ void fsmenu_read_system(struct FSMenu *fsmenu, int read_bookmarks)
static void fsmenu_free_category(struct FSMenu *fsmenu, FSMenuCategory category)
{
- FSMenuEntry *fsme = fsmenu_get_category(fsmenu, category);
+ FSMenuEntry *fsm_iter = fsmenu_get_category(fsmenu, category);
- while (fsme) {
- FSMenuEntry *n = fsme->next;
+ while (fsm_iter) {
+ FSMenuEntry *fsm_next = fsm_iter->next;
- if (fsme->path) MEM_freeN(fsme->path);
- MEM_freeN(fsme);
+ if (fsm_iter->path) {
+ MEM_freeN(fsm_iter->path);
+ }
+ MEM_freeN(fsm_iter);
- fsme = n;
+ fsm_iter = fsm_next;
}
}
@@ -547,13 +573,17 @@ void fsmenu_refresh_system_category(struct FSMenu *fsmenu)
fsmenu_free_category(fsmenu, FS_CATEGORY_SYSTEM);
fsmenu_set_category(fsmenu, FS_CATEGORY_SYSTEM, NULL);
+ fsmenu_free_category(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS);
+ fsmenu_set_category(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, NULL);
+
/* Add all entries to system category */
- fsmenu_read_system(fsmenu, FALSE);
+ fsmenu_read_system(fsmenu, TRUE);
}
void fsmenu_free(struct FSMenu *fsmenu)
{
fsmenu_free_category(fsmenu, FS_CATEGORY_SYSTEM);
+ fsmenu_free_category(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS);
fsmenu_free_category(fsmenu, FS_CATEGORY_BOOKMARKS);
fsmenu_free_category(fsmenu, FS_CATEGORY_RECENT);
MEM_freeN(fsmenu);
diff --git a/source/blender/editors/space_file/fsmenu.h b/source/blender/editors/space_file/fsmenu.h
index d7576d71933..1b69eb09fce 100644
--- a/source/blender/editors/space_file/fsmenu.h
+++ b/source/blender/editors/space_file/fsmenu.h
@@ -39,10 +39,17 @@
typedef enum FSMenuCategory {
FS_CATEGORY_SYSTEM,
+ FS_CATEGORY_SYSTEM_BOOKMARKS,
FS_CATEGORY_BOOKMARKS,
FS_CATEGORY_RECENT
} FSMenuCategory;
+typedef enum FSMenuInsert {
+ FS_INSERT_SORTED = (1 << 0),
+ FS_INSERT_SAVE = (1 << 1),
+ FS_INSERT_FIRST = (1 << 2) /* moves the item to the front of the list when its not already there */
+} FSMenuInsert;
+
struct FSMenu;
struct FSMenu *fsmenu_get(void);
@@ -59,7 +66,7 @@ char *fsmenu_get_entry(struct FSMenu *fsmenu, FSMenuCategory category, int index
* Duplicate entries are not added.
* \param sorted Should entry be inserted in sorted order?
*/
-void fsmenu_insert_entry(struct FSMenu *fsmenu, FSMenuCategory category, const char *path, int sorted, short save);
+void fsmenu_insert_entry(struct FSMenu *fsmenu, FSMenuCategory category, const char *path, const FSMenuInsert flag);
/** Return whether the entry was created by the user and can be saved and deleted */
short fsmenu_can_save(struct FSMenu *fsmenu, FSMenuCategory category, int index);
diff --git a/source/blender/editors/space_file/space_file.c b/source/blender/editors/space_file/space_file.c
index 4b568b43695..be037a0d5ba 100644
--- a/source/blender/editors/space_file/space_file.c
+++ b/source/blender/editors/space_file/space_file.c
@@ -198,7 +198,7 @@ static void file_refresh(const bContext *C, ScrArea *UNUSED(sa))
params->active_file = -1; // added this so it opens nicer (ton)
}
filelist_hidedot(sfile->files, params->flag & FILE_HIDE_DOT);
- filelist_setfilter(sfile->files, params->flag & FILE_FILTER ? params->filter : 0);
+ filelist_setfilter(sfile->files, params->flag & FILE_FILTER ? params->filter : 0);
filelist_setfilter_types(sfile->files, params->filter_glob);
if (filelist_empty(sfile->files)) {
@@ -252,7 +252,7 @@ static void file_refresh(const bContext *C, ScrArea *UNUSED(sa))
static void file_listener(ScrArea *sa, wmNotifier *wmn)
{
- /* SpaceFile *sfile = (SpaceFile*)sa->spacedata.first; */
+ /* SpaceFile *sfile = (SpaceFile *)sa->spacedata.first; */
/* context changes */
switch (wmn->category) {
@@ -386,6 +386,7 @@ static void file_operatortypes(void)
WM_operatortype_append(FILE_OT_bookmark_toggle);
WM_operatortype_append(FILE_OT_bookmark_add);
WM_operatortype_append(FILE_OT_delete_bookmark);
+ WM_operatortype_append(FILE_OT_reset_recent);
WM_operatortype_append(FILE_OT_hidedot);
WM_operatortype_append(FILE_OT_filenum);
WM_operatortype_append(FILE_OT_directory_new);
@@ -480,7 +481,7 @@ static void file_channel_area_init(wmWindowManager *wm, ARegion *ar)
ED_region_panels_init(wm, ar);
/* own keymaps */
- keymap = WM_keymap_find(wm->defaultconf, "File Browser", SPACE_FILE, 0);
+ keymap = WM_keymap_find(wm->defaultconf, "File Browser", SPACE_FILE, 0);
WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct);
}
@@ -504,7 +505,7 @@ static void file_header_area_init(wmWindowManager *wm, ARegion *ar)
ED_region_header_init(ar);
- keymap = WM_keymap_find(wm->defaultconf, "File Browser", SPACE_FILE, 0);
+ keymap = WM_keymap_find(wm->defaultconf, "File Browser", SPACE_FILE, 0);
WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct);
}
@@ -537,7 +538,7 @@ static void file_ui_area_draw(const bContext *C, ARegion *ar)
glClear(GL_COLOR_BUFFER_BIT);
/* scrolling here is just annoying, disable it */
- ar->v2d.cur.ymax = BLI_RCT_SIZE_Y(&ar->v2d.cur);
+ ar->v2d.cur.ymax = BLI_rctf_size_y(&ar->v2d.cur);
ar->v2d.cur.ymin = 0;
/* set view2d view matrix for scrolling (without scrollers) */
@@ -597,7 +598,7 @@ void ED_spacetype_file(void)
art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_VIEW2D | ED_KEYMAP_HEADER;
art->init = file_header_area_init;
art->draw = file_header_area_draw;
- // art->listener= file_header_area_listener;
+ // art->listener = file_header_area_listener;
BLI_addhead(&st->regiontypes, art);
/* regions: ui */
diff --git a/source/blender/editors/space_graph/graph_buttons.c b/source/blender/editors/space_graph/graph_buttons.c
index efe62eaf495..8bb57a32090 100644
--- a/source/blender/editors/space_graph/graph_buttons.c
+++ b/source/blender/editors/space_graph/graph_buttons.c
@@ -69,12 +69,6 @@
#include "graph_intern.h" // own include
-/* XXX */
-
-/* temporary definition for limits of float number buttons (FLT_MAX tends to infinity with old system) */
-#define UI_FLT_MAX 10000.0f
-
-
/* ******************* graph editor space & buttons ************** */
#define B_REDR 1
@@ -83,7 +77,7 @@
static void do_graph_region_buttons(bContext *UNUSED(C), void *UNUSED(arg), int event)
{
- //Scene *scene= CTX_data_scene(C);
+ //Scene *scene = CTX_data_scene(C);
switch (event) {
@@ -154,6 +148,7 @@ static void graph_panel_view(const bContext *C, Panel *pa)
row = uiLayoutSplit(sub, 0.7f, TRUE);
uiItemR(row, &sceneptr, "frame_current", 0, IFACE_("Cursor X"), ICON_NONE);
uiItemEnumO(row, "GRAPH_OT_snap", IFACE_("To Keys"), 0, "type", GRAPHKEYS_SNAP_CFRA);
+
row = uiLayoutSplit(sub, 0.7f, TRUE);
uiItemR(row, &spaceptr, "cursor_position_y", 0, IFACE_("Cursor Y"), ICON_NONE);
uiItemEnumO(row, "GRAPH_OT_snap", IFACE_("To Keys"), 0, "type", GRAPHKEYS_SNAP_VALUE);
@@ -304,7 +299,7 @@ static void graph_panel_key_properties(const bContext *C, Panel *pa)
if (RNA_path_resolve(&id_ptr, fcu->rna_path, &fcu_prop_ptr, &fcu_prop) && fcu_prop) {
/* determine the unit for this property */
unit = RNA_SUBTYPE_UNIT(RNA_property_subtype(fcu_prop));
- }
+ }
/* interpolation */
col = uiLayoutColumn(layout, FALSE);
@@ -314,44 +309,43 @@ static void graph_panel_key_properties(const bContext *C, Panel *pa)
* - we use the button-versions of the calls so that we can attach special update handlers
* and unit conversion magic that cannot be achieved using a purely RNA-approach
*/
- // XXX:
col = uiLayoutColumn(layout, TRUE);
/* keyframe itself */
{
uiItemL(col, IFACE_("Key:"), ICON_NONE);
-
+
but = uiDefButR(block, NUM, B_REDR, IFACE_("Frame"), 0, 0, UI_UNIT_X, UI_UNIT_Y,
&bezt_ptr, "co", 0, 0, 0, -1, -1, NULL);
uiButSetFunc(but, graphedit_activekey_update_cb, fcu, bezt);
-
+
but = uiDefButR(block, NUM, B_REDR, IFACE_("Value"), 0, 0, UI_UNIT_X, UI_UNIT_Y,
&bezt_ptr, "co", 1, 0, 0, -1, -1, NULL);
uiButSetFunc(but, graphedit_activekey_update_cb, fcu, bezt);
uiButSetUnitType(but, unit);
}
-
+
/* previous handle - only if previous was Bezier interpolation */
if ((prevbezt) && (prevbezt->ipo == BEZT_IPO_BEZ)) {
uiItemL(col, IFACE_("Left Handle:"), ICON_NONE);
-
+
but = uiDefButR(block, NUM, B_REDR, "X", 0, 0, UI_UNIT_X, UI_UNIT_Y,
&bezt_ptr, "handle_left", 0, 0, 0, -1, -1, NULL);
uiButSetFunc(but, graphedit_activekey_handles_cb, fcu, bezt);
-
+
but = uiDefButR(block, NUM, B_REDR, "Y", 0, 0, UI_UNIT_X, UI_UNIT_Y,
&bezt_ptr, "handle_left", 1, 0, 0, -1, -1, NULL);
uiButSetFunc(but, graphedit_activekey_handles_cb, fcu, bezt);
uiButSetUnitType(but, unit);
}
-
+
/* next handle - only if current is Bezier interpolation */
if (bezt->ipo == BEZT_IPO_BEZ) {
uiItemL(col, IFACE_("Right Handle:"), ICON_NONE);
-
+
but = uiDefButR(block, NUM, B_REDR, "X", 0, 0, UI_UNIT_X, UI_UNIT_Y,
&bezt_ptr, "handle_right", 0, 0, 0, -1, -1, NULL);
uiButSetFunc(but, graphedit_activekey_handles_cb, fcu, bezt);
-
+
but = uiDefButR(block, NUM, B_REDR, "Y", 0, 0, UI_UNIT_X, UI_UNIT_Y,
&bezt_ptr, "handle_right", 1, 0, 0, -1, -1, NULL);
uiButSetFunc(but, graphedit_activekey_handles_cb, fcu, bezt);
@@ -413,7 +407,7 @@ static void driver_remove_cb(bContext *C, void *ale_v, void *UNUSED(arg))
if (ELEM(NULL, id, fcu))
return;
- /* call API method to remove this driver */
+ /* call API method to remove this driver */
ANIM_remove_driver(reports, id, fcu->rna_path, fcu->array_index, 0);
}
@@ -443,7 +437,7 @@ static void driver_update_flags_cb(bContext *UNUSED(C), void *fcu_v, void *UNUSE
ChannelDriver *driver = fcu->driver;
/* clear invalid flags */
- fcu->flag &= ~FCURVE_DISABLED; // XXX?
+ fcu->flag &= ~FCURVE_DISABLED;
driver->flag &= ~DRIVER_FLAG_INVALID;
}
@@ -473,7 +467,6 @@ static void graph_panel_driverVar__singleProp(uiLayout *layout, ID *id, DriverVa
uiTemplateAnyID(row, &dtar_ptr, "id", "id_type", IFACE_("Prop:"));
/* Target Property */
- // TODO: make this less technical...
if (dtar->id) {
PointerRNA root_ptr;
@@ -636,12 +629,12 @@ static void graph_panel_drivers(const bContext *C, Panel *pa)
/* errors? */
if (driver->flag & DRIVER_FLAG_INVALID)
- uiItemL(col, IFACE_("ERROR: invalid Python expression"), ICON_ERROR);
+ uiItemL(col, IFACE_("ERROR: Invalid Python expression"), ICON_ERROR);
}
else {
/* errors? */
if (driver->flag & DRIVER_FLAG_INVALID)
- uiItemL(col, IFACE_("ERROR: invalid target channel(s)"), ICON_ERROR);
+ uiItemL(col, IFACE_("ERROR: Invalid target channel(s)"), ICON_ERROR);
}
col = uiLayoutColumn(pa->layout, TRUE);
@@ -712,15 +705,15 @@ static void graph_panel_drivers(const bContext *C, Panel *pa)
graph_panel_driverVar__transChan(box, ale->id, dvar);
break;
}
-
+
/* value of variable */
if (driver->flag & DRIVER_FLAG_SHOWDEBUG) {
char valBuf[32];
-
+
box = uiLayoutBox(col);
row = uiLayoutRow(box, TRUE);
uiItemL(row, IFACE_("Value:"), ICON_NONE);
-
+
BLI_snprintf(valBuf, sizeof(valBuf), "%.3f", dvar->curval);
uiItemL(row, valBuf, ICON_NONE);
}
@@ -730,8 +723,8 @@ static void graph_panel_drivers(const bContext *C, Panel *pa)
MEM_freeN(ale);
}
-/* ******************* f-modifiers ******************************** */
-/* all the drawing code is in editors/animation/fmodifier_ui.c */
+/* ******************* F-Modifiers ******************************** */
+/* All the drawing code is in editors/animation/fmodifier_ui.c */
#define B_FMODIFIER_REDRAW 20
@@ -763,7 +756,9 @@ static void graph_panel_modifiers(const bContext *C, Panel *pa)
row = uiLayoutRow(pa->layout, FALSE);
block = uiLayoutGetBlock(row);
- // XXX for now, this will be a operator button which calls a 'add modifier' operator
+ /* this is an operator button which calls a 'add modifier' operator...
+ * a menu might be nicer but would be tricky as we need some custom filtering
+ */
uiDefButO(block, BUT, "GRAPH_OT_fmodifier_add", WM_OP_INVOKE_REGION_WIN, IFACE_("Add Modifier"),
10, 0, 150, 20, TIP_("Adds a new F-Curve Modifier for the active F-Curve"));
diff --git a/source/blender/editors/space_graph/graph_draw.c b/source/blender/editors/space_graph/graph_draw.c
index e4bda15bc7d..f665b979559 100644
--- a/source/blender/editors/space_graph/graph_draw.c
+++ b/source/blender/editors/space_graph/graph_draw.c
@@ -83,12 +83,12 @@ static float fcurve_display_alpha(FCurve *fcu)
/* Envelope -------------- */
-// TODO: draw a shaded poly showing the region of influence too!!!
+/* TODO: draw a shaded poly showing the region of influence too!!! */
static void draw_fcurve_modifier_controls_envelope(FModifier *fcm, View2D *v2d)
{
FMod_Envelope *env = (FMod_Envelope *)fcm->data;
FCM_EnvelopeData *fed;
- const float fac = 0.05f * BLI_RCT_SIZE_X(&v2d->cur);
+ const float fac = 0.05f * BLI_rctf_size_x(&v2d->cur);
int i;
/* draw two black lines showing the standard reference levels */
@@ -101,13 +101,13 @@ static void draw_fcurve_modifier_controls_envelope(FModifier *fcm, View2D *v2d)
glVertex2f(v2d->cur.xmin, env->midval + env->max);
glVertex2f(v2d->cur.xmax, env->midval + env->max);
- glEnd(); // GL_LINES
+ glEnd(); /* GL_LINES */
setlinestyle(0);
/* set size of vertices (non-adjustable for now) */
glPointSize(2.0f);
- // for now, point color is fixed, and is white
+ /* for now, point color is fixed, and is white */
glColor3f(1.0f, 1.0f, 1.0f);
/* we use bgl points not standard gl points, to workaround vertex
@@ -123,7 +123,7 @@ static void draw_fcurve_modifier_controls_envelope(FModifier *fcm, View2D *v2d)
glVertex2f(fed->time, fed->max);
}
}
- bglEnd(); // GL_POINTS
+ bglEnd(); /* GL_POINTS */
glPointSize(1.0f);
}
@@ -137,7 +137,7 @@ static void draw_fcurve_modifier_controls_envelope(FModifier *fcm, View2D *v2d)
static void draw_fcurve_vertices_keyframes(FCurve *fcu, SpaceIpo *UNUSED(sipo), View2D *v2d, short edit, short sel)
{
BezTriple *bezt = fcu->bezt;
- const float fac = 0.05f * BLI_RCT_SIZE_X(&v2d->cur);
+ const float fac = 0.05f * BLI_rctf_size_x(&v2d->cur);
int i;
/* we use bgl points not standard gl points, to workaround vertex
@@ -160,13 +160,13 @@ static void draw_fcurve_vertices_keyframes(FCurve *fcu, SpaceIpo *UNUSED(sipo),
}
else {
/* no check for selection here, as curve is not editable... */
- // XXX perhaps we don't want to even draw points? maybe add an option for that later
+ /* XXX perhaps we don't want to even draw points? maybe add an option for that later */
bglVertex3fv(bezt->vec[1]);
}
}
}
- bglEnd(); // GL_POINTS
+ bglEnd(); /* GL_POINTS */
}
@@ -262,7 +262,7 @@ static void set_fcurve_vertex_color(FCurve *fcu, short sel)
/* Curve's points ARE BEING edited */
if (sel) UI_ThemeColorShadeAlpha(TH_VERTEX_SELECT, 0, alphaOffset);
else UI_ThemeColorShadeAlpha(TH_VERTEX, 0, alphaOffset);
- }
+ }
else {
/* Curve's points CANNOT BE edited */
if (sel) UI_ThemeColorShadeAlpha(TH_TEXT_HI, 0, alphaOffset);
@@ -318,7 +318,7 @@ static int draw_fcurve_handles_check(SpaceIpo *sipo, FCurve *fcu)
)
{
return 0;
- }
+ }
else {
return 1;
}
@@ -404,7 +404,7 @@ static void draw_fcurve_handles(SpaceIpo *sipo, FCurve *fcu)
}
}
- glEnd(); // GL_LINES
+ glEnd(); /* GL_LINES */
}
/* Samples ---------------- */
@@ -428,7 +428,7 @@ static void draw_fcurve_sample_control(float x, float y, float xscale, float ysc
glVertex2f(-0.7f, +0.7f);
glVertex2f(+0.7f, -0.7f);
- glEnd(); // GL_LINES
+ glEnd(); /* GL_LINES */
glEndList();
}
@@ -515,7 +515,7 @@ static void draw_fcurve_curve(bAnimContext *ac, ID *id, FCurve *fcu, View2D *v2d
* chosen here is just the coarsest value which still looks reasonable...
*/
/* grid->dx represents the number of 'frames' between gridlines, but we divide by U.v2d_min_gridsize to get pixels-steps */
- // TODO: perhaps we should have 1.0 frames as upper limit so that curves don't get too distorted?
+ /* TODO: perhaps we should have 1.0 frames as upper limit so that curves don't get too distorted? */
samplefreq = dx / U.v2d_min_gridsize;
if (samplefreq < 0.00001f) samplefreq = 0.00001f;
@@ -561,7 +561,7 @@ static void draw_fcurve_curve_samples(bAnimContext *ac, ID *id, FCurve *fcu, Vie
if ((fcu->extend == FCURVE_EXTRAPOLATE_CONSTANT) || (fcu->flag & FCURVE_INT_VALUES) || (fcu->totvert == 1)) {
/* just extend across the first keyframe's value */
v[1] = prevfpt->vec[1];
- }
+ }
else {
/* extrapolate linear dosnt use the handle, use the next points center instead */
fac = (prevfpt->vec[0] - fpt->vec[0]) / (prevfpt->vec[0] - v[0]);
@@ -599,7 +599,7 @@ static void draw_fcurve_curve_samples(bAnimContext *ac, ID *id, FCurve *fcu, Vie
if ((fcu->extend == FCURVE_EXTRAPOLATE_CONSTANT) || (fcu->flag & FCURVE_INT_VALUES) || (fcu->totvert == 1)) {
/* based on last keyframe's value */
v[1] = prevfpt->vec[1];
- }
+ }
else {
/* extrapolate linear dosnt use the handle, use the previous points center instead */
fpt = prevfpt - 1;
@@ -642,13 +642,13 @@ static void draw_fcurve_curve_bezts(bAnimContext *ac, ID *id, FCurve *fcu, View2
if ((fcu->extend == FCURVE_EXTRAPOLATE_CONSTANT) || (prevbezt->ipo == BEZT_IPO_CONST) || (fcu->totvert == 1)) {
/* just extend across the first keyframe's value */
v1[1] = prevbezt->vec[1][1];
- }
+ }
else if (prevbezt->ipo == BEZT_IPO_LIN) {
/* extrapolate linear dosnt use the handle, use the next points center instead */
fac = (prevbezt->vec[1][0] - bezt->vec[1][0]) / (prevbezt->vec[1][0] - v1[0]);
if (fac) fac = 1.0f / fac;
v1[1] = prevbezt->vec[1][1] - fac * (prevbezt->vec[1][1] - bezt->vec[1][1]);
- }
+ }
else {
/* based on angle of handle 1 (relative to keyframe) */
fac = (prevbezt->vec[0][0] - prevbezt->vec[1][0]) / (prevbezt->vec[1][0] - v1[0]);
@@ -667,7 +667,7 @@ static void draw_fcurve_curve_bezts(bAnimContext *ac, ID *id, FCurve *fcu, View2
}
/* draw curve between first and last keyframe (if there are enough to do so) */
- // TODO: optimize this to not have to calc stuff out of view too?
+ /* TODO: optimize this to not have to calc stuff out of view too? */
while (b--) {
if (prevbezt->ipo == BEZT_IPO_CONST) {
/* Constant-Interpolation: draw segment between previous keyframe and next, but holding same value */
@@ -691,7 +691,7 @@ static void draw_fcurve_curve_bezts(bAnimContext *ac, ID *id, FCurve *fcu, View2
*/
/* resol depends on distance between points (not just horizontal) OR is a fixed high res */
- // TODO: view scale should factor into this someday too...
+ /* TODO: view scale should factor into this someday too... */
if (fcu->driver)
resol = 32;
else
@@ -705,7 +705,7 @@ static void draw_fcurve_curve_bezts(bAnimContext *ac, ID *id, FCurve *fcu, View2
}
else {
/* clamp resolution to max of 32 */
- // NOTE: higher values will crash
+ /* NOTE: higher values will crash */
if (resol > 32) resol = 32;
v1[0] = prevbezt->vec[1][0];
@@ -748,14 +748,14 @@ static void draw_fcurve_curve_bezts(bAnimContext *ac, ID *id, FCurve *fcu, View2
if ((fcu->extend == FCURVE_EXTRAPOLATE_CONSTANT) || (fcu->flag & FCURVE_INT_VALUES) || (prevbezt->ipo == BEZT_IPO_CONST) || (fcu->totvert == 1)) {
/* based on last keyframe's value */
v1[1] = prevbezt->vec[1][1];
- }
+ }
else if (prevbezt->ipo == BEZT_IPO_LIN) {
/* extrapolate linear dosnt use the handle, use the previous points center instead */
bezt = prevbezt - 1;
fac = (prevbezt->vec[1][0] - bezt->vec[1][0]) / (prevbezt->vec[1][0] - v1[0]);
if (fac) fac = 1.0f / fac;
v1[1] = prevbezt->vec[1][1] - fac * (prevbezt->vec[1][1] - bezt->vec[1][1]);
- }
+ }
else {
/* based on angle of handle 1 (relative to keyframe) */
fac = (prevbezt->vec[2][0] - prevbezt->vec[1][0]) / (prevbezt->vec[1][0] - v1[0]);
@@ -852,7 +852,7 @@ void graph_draw_curves(bAnimContext *ac, SpaceIpo *sipo, ARegion *ar, View2DGrid
}
if (((fcu->grp) && (fcu->grp->flag & AGRP_MUTED)) || (fcu->flag & FCURVE_MUTED)) {
/* muted curves are drawn in a grayish hue */
- // XXX should we have some variations?
+ /* XXX should we have some variations? */
UI_ThemeColorShade(TH_HEADER, 50);
}
else {
@@ -971,7 +971,7 @@ void graph_draw_channel_names(bContext *C, bAnimContext *ac, ARegion *ar)
height = (float)((items * ACHANNEL_STEP) + (ACHANNEL_HEIGHT * 2));
UI_view2d_totRect_set(v2d, ar->winx, height);
- /* loop through channels, and set up drawing depending on their type */
+ /* loop through channels, and set up drawing depending on their type */
{ /* first pass: just the standard GL-drawing for backdrop + text */
y = (float)ACHANNEL_FIRST;
diff --git a/source/blender/editors/space_graph/graph_edit.c b/source/blender/editors/space_graph/graph_edit.c
index f01d64b46b8..453549ebf79 100644
--- a/source/blender/editors/space_graph/graph_edit.c
+++ b/source/blender/editors/space_graph/graph_edit.c
@@ -229,11 +229,11 @@ static int graphkeys_viewall(bContext *C, const short do_sel_only, const short i
&cur_new.ymin, &cur_new.ymax,
do_sel_only, include_handles);
- extra = 0.1f * BLI_RCT_SIZE_X(&cur_new);
+ extra = 0.1f * BLI_rctf_size_x(&cur_new);
cur_new.xmin -= extra;
cur_new.xmax += extra;
- extra = 0.1f * BLI_RCT_SIZE_Y(&cur_new);
+ extra = 0.1f * BLI_rctf_size_y(&cur_new);
cur_new.ymin -= extra;
cur_new.ymax += extra;
@@ -332,7 +332,7 @@ static void create_ghost_curves(bAnimContext *ac, int start, int end)
ChannelDriver *driver = fcu->driver;
FPoint *fpt;
float unitFac;
- int cfra;
+ int cfra;
/* disable driver so that it don't muck up the sampling process */
fcu->driver = NULL;
@@ -724,7 +724,7 @@ static int graphkeys_copy_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
/* copy keyframes */
- if (copy_graph_keys(&ac)) {
+ if (copy_graph_keys(&ac)) {
BKE_report(op->reports, RPT_ERROR, "No keyframes copied to keyframes copy/paste buffer");
return OPERATOR_CANCELLED;
}
@@ -1143,9 +1143,9 @@ static int graphkeys_sound_bake_exec(bContext *C, wmOperator *op)
RNA_float_get(op->ptr, "attack"),
RNA_float_get(op->ptr, "release"),
RNA_float_get(op->ptr, "threshold"),
- RNA_boolean_get(op->ptr, "accumulate"),
+ RNA_boolean_get(op->ptr, "use_accumulate"),
RNA_boolean_get(op->ptr, "use_additive"),
- RNA_boolean_get(op->ptr, "square"),
+ RNA_boolean_get(op->ptr, "use_square"),
RNA_float_get(op->ptr, "sthreshold"),
FPS, &sbi.length);
@@ -1225,15 +1225,27 @@ void GRAPH_OT_sound_bake(wmOperatorType *ot)
/* properties */
WM_operator_properties_filesel(ot, FOLDERFILE | SOUNDFILE | MOVIEFILE, FILE_SPECIAL, FILE_OPENFILE,
WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY);
- RNA_def_float(ot->srna, "low", 0.0f, 0.0, 100000.0, "Lowest frequency", "", 0.1, 1000.00);
- RNA_def_float(ot->srna, "high", 100000.0, 0.0, 100000.0, "Highest frequency", "", 0.1, 1000.00);
- RNA_def_float(ot->srna, "attack", 0.005, 0.0, 2.0, "Attack time", "", 0.01, 0.1);
- RNA_def_float(ot->srna, "release", 0.2, 0.0, 5.0, "Release time", "", 0.01, 0.2);
- RNA_def_float(ot->srna, "threshold", 0.0, 0.0, 1.0, "Threshold", "", 0.01, 0.1);
- RNA_def_boolean(ot->srna, "accumulate", 0, "Accumulate", "");
- RNA_def_boolean(ot->srna, "use_additive", 0, "Additive", "");
- RNA_def_boolean(ot->srna, "square", 0, "Square", "");
- RNA_def_float(ot->srna, "sthreshold", 0.1, 0.0, 1.0, "Square Threshold", "", 0.01, 0.1);
+ RNA_def_float(ot->srna, "low", 0.0f, 0.0, 100000.0, "Lowest frequency",
+ "Cutoff frequency of a high-pass filter that is applied to the audio data", 0.1, 1000.00);
+ RNA_def_float(ot->srna, "high", 100000.0, 0.0, 100000.0, "Highest frequency",
+ "Cutoff frequency of a low-pass filter that is applied to the audio data", 0.1, 1000.00);
+ RNA_def_float(ot->srna, "attack", 0.005, 0.0, 2.0, "Attack time",
+ "Value for the hull curve calculation that tells how fast the hull curve can rise "
+ "(the lower the value the steeper it can rise)", 0.01, 0.1);
+ RNA_def_float(ot->srna, "release", 0.2, 0.0, 5.0, "Release time",
+ "Value for the hull curve calculation that tells how fast the hull curve can fall "
+ "(the lower the value the steeper it can fall)", 0.01, 0.2);
+ RNA_def_float(ot->srna, "threshold", 0.0, 0.0, 1.0, "Threshold",
+ "Minimum amplitude value needed to influence the hull curve", 0.01, 0.1);
+ RNA_def_boolean(ot->srna, "use_accumulate", 0, "Accumulate",
+ "Only the positive differences of the hull curve amplitudes are summarized to produce the output");
+ RNA_def_boolean(ot->srna, "use_additive", 0, "Additive",
+ "The amplitudes of the hull curve are summarized (or, when Accumulate is enabled, "
+ "both positive and negative differences are accumulated)");
+ RNA_def_boolean(ot->srna, "use_square", 0, "Square",
+ "The output is a square curve (negative values always result in -1, and positive ones in 1)");
+ RNA_def_float(ot->srna, "sthreshold", 0.1, 0.0, 1.0, "Square Threshold",
+ "Square only: all values with an absolute amplitude lower than that result in 0", 0.01, 0.1);
}
/* ******************** Sample Keyframes Operator *********************** */
@@ -1309,8 +1321,8 @@ void GRAPH_OT_sample(wmOperatorType *ot)
/* defines for set extrapolation-type for selected keyframes tool */
static EnumPropertyItem prop_graphkeys_expo_types[] = {
- {FCURVE_EXTRAPOLATE_CONSTANT, "CONSTANT", 0, "Constant Extrapolation", ""},
- {FCURVE_EXTRAPOLATE_LINEAR, "LINEAR", 0, "Linear Extrapolation", ""},
+ {FCURVE_EXTRAPOLATE_CONSTANT, "CONSTANT", 0, "Constant Extrapolation", "Values on endpoint keyframes are held"},
+ {FCURVE_EXTRAPOLATE_LINEAR, "LINEAR", 0, "Linear Extrapolation", "Straight-line slope of end segments are extended past the endpoint keyframes"},
{MAKE_CYCLIC_EXPO, "MAKE_CYCLIC", 0, "Make Cyclic (F-Modifier)", "Add Cycles F-Modifier if one doesn't exist already"},
{CLEAR_CYCLIC_EXPO, "CLEAR_CYCLIC", 0, "Clear Cyclic (F-Modifier)", "Remove Cycles F-Modifier if not needed anymore"},
@@ -1614,7 +1626,7 @@ static int graphkeys_euler_filter_exec(bContext *C, wmOperator *op)
else if (ELEM3(fcu->array_index, 0, 1, 2) == 0) {
BKE_reportf(op->reports, RPT_WARNING,
"Euler Rotation F-Curve has invalid index (ID='%s', Path='%s', Index=%d)",
- (ale->id) ? ale->id->name : "<No ID>", fcu->rna_path, fcu->array_index);
+ (ale->id) ? ale->id->name : TIP_("<No ID>"), fcu->rna_path, fcu->array_index);
continue;
}
@@ -1711,13 +1723,16 @@ static int graphkeys_euler_filter_exec(bContext *C, wmOperator *op)
/* updates + finishing warnings */
if (failed == groups) {
BKE_report(op->reports, RPT_ERROR,
- "No Euler Rotations could be corrected, ensure each rotation has keys for all components, and that F-Curves for these are in consecutive XYZ order and selected");
+ "No Euler Rotations could be corrected, ensure each rotation has keys for all components, "
+ "and that F-Curves for these are in consecutive XYZ order and selected");
return OPERATOR_CANCELLED;
}
else {
if (failed) {
BKE_report(op->reports, RPT_ERROR,
- "Some Euler Rotations couldn't be corrected due to missing/unselected/out-of-order F-Curves, ensure each rotation has keys for all components, and that F-Curves for these are in consecutive XYZ order and selected");
+ "Some Euler Rotations could not be corrected due to missing/unselected/out-of-order F-Curves, "
+ "ensure each rotation has keys for all components, and that F-Curves for these are in "
+ "consecutive XYZ order and selected");
}
/* validate keyframes after editing */
@@ -1808,9 +1823,9 @@ static int graphkeys_framejump_exec(bContext *C, wmOperator *UNUSED(op))
void GRAPH_OT_frame_jump(wmOperatorType *ot)
{
/* identifiers */
- ot->name = "Jump to Frame";
+ ot->name = "Jump to Keyframes";
ot->idname = "GRAPH_OT_frame_jump";
- ot->description = "Set the current frame to the average frame of the selected keyframes";
+ ot->description = "Place the cursor on the midpoint of selected keyframes";
/* api callbacks */
ot->exec = graphkeys_framejump_exec;
@@ -1824,12 +1839,18 @@ void GRAPH_OT_frame_jump(wmOperatorType *ot)
/* defines for snap keyframes tool */
static EnumPropertyItem prop_graphkeys_snap_types[] = {
- {GRAPHKEYS_SNAP_CFRA, "CFRA", 0, "Current Frame", ""},
- {GRAPHKEYS_SNAP_VALUE, "VALUE", 0, "Cursor Value", ""},
- {GRAPHKEYS_SNAP_NEAREST_FRAME, "NEAREST_FRAME", 0, "Nearest Frame", ""}, // XXX as single entry?
- {GRAPHKEYS_SNAP_NEAREST_SECOND, "NEAREST_SECOND", 0, "Nearest Second", ""}, // XXX as single entry?
- {GRAPHKEYS_SNAP_NEAREST_MARKER, "NEAREST_MARKER", 0, "Nearest Marker", ""},
- {GRAPHKEYS_SNAP_HORIZONTAL, "HORIZONTAL", 0, "Flatten Handles", ""},
+ {GRAPHKEYS_SNAP_CFRA, "CFRA", 0, "Current Frame",
+ "Snap selected keyframes to the current frame"},
+ {GRAPHKEYS_SNAP_VALUE, "VALUE", 0, "Cursor Value",
+ "Set values of selected keyframes to the cursor value (Y/Horizontal component)"},
+ {GRAPHKEYS_SNAP_NEAREST_FRAME, "NEAREST_FRAME", 0, "Nearest Frame",
+ "Snap selected keyframes to the nearest (whole) frame (use to fix accidental sub-frame offsets)"},
+ {GRAPHKEYS_SNAP_NEAREST_SECOND, "NEAREST_SECOND", 0, "Nearest Second",
+ "Snap selected keyframes to the nearest second"},
+ {GRAPHKEYS_SNAP_NEAREST_MARKER, "NEAREST_MARKER", 0, "Nearest Marker",
+ "Snap selected keyframes to the nearest marker"},
+ {GRAPHKEYS_SNAP_HORIZONTAL, "HORIZONTAL", 0, "Flatten Handles",
+ "Flatten handles for a smoother transition"},
{0, NULL, 0, NULL, NULL}
};
@@ -1932,11 +1953,16 @@ void GRAPH_OT_snap(wmOperatorType *ot)
/* defines for mirror keyframes tool */
static EnumPropertyItem prop_graphkeys_mirror_types[] = {
- {GRAPHKEYS_MIRROR_CFRA, "CFRA", 0, "By Times over Current Frame", ""},
- {GRAPHKEYS_MIRROR_VALUE, "VALUE", 0, "By Values over Cursor Value", ""},
- {GRAPHKEYS_MIRROR_YAXIS, "YAXIS", 0, "By Times over Time=0", ""},
- {GRAPHKEYS_MIRROR_XAXIS, "XAXIS", 0, "By Values over Value=0", ""},
- {GRAPHKEYS_MIRROR_MARKER, "MARKER", 0, "By Times over First Selected Marker", ""},
+ {GRAPHKEYS_MIRROR_CFRA, "CFRA", 0, "By Times over Current Frame",
+ "Flip times of selected keyframes using the current frame as the mirror line"},
+ {GRAPHKEYS_MIRROR_VALUE, "VALUE", 0, "By Values over Cursor Value",
+ "Flip values of selected keyframes using the cursor value (Y/Horizontal component) as the mirror line"},
+ {GRAPHKEYS_MIRROR_YAXIS, "YAXIS", 0, "By Times over Time=0",
+ "Flip times of selected keyframes, effectively reversing the order they appear in"},
+ {GRAPHKEYS_MIRROR_XAXIS, "XAXIS", 0, "By Values over Value=0",
+ "Flip values of selected keyframes (i.e. negative values become positive, and vice versa)"},
+ {GRAPHKEYS_MIRROR_MARKER, "MARKER", 0, "By Times over First Selected Marker",
+ "Flip times of selected keyframes using the first selected marker as the reference point"},
{0, NULL, 0, NULL, NULL}
};
@@ -2170,7 +2196,7 @@ static int graph_fmodifier_add_exec(bContext *C, wmOperator *op)
if (fcm)
set_active_fmodifier(&fcu->modifiers, fcm);
else {
- BKE_report(op->reports, RPT_ERROR, "Modifier couldn't be added, see console for details");
+ BKE_report(op->reports, RPT_ERROR, "Modifier could not be added (see console for details)");
break;
}
}
diff --git a/source/blender/editors/space_graph/graph_intern.h b/source/blender/editors/space_graph/graph_intern.h
index eb657169970..b2dbf764c1d 100644
--- a/source/blender/editors/space_graph/graph_intern.h
+++ b/source/blender/editors/space_graph/graph_intern.h
@@ -123,7 +123,7 @@ enum {
GRAPHKEYS_SNAP_CFRA = 1,
GRAPHKEYS_SNAP_NEAREST_FRAME,
GRAPHKEYS_SNAP_NEAREST_SECOND,
- GRAPHKEYS_SNAP_NEAREST_MARKER,
+ GRAPHKEYS_SNAP_NEAREST_MARKER,
GRAPHKEYS_SNAP_HORIZONTAL,
GRAPHKEYS_SNAP_VALUE,
} eGraphKeys_Snap_Mode;
diff --git a/source/blender/editors/space_graph/graph_ops.c b/source/blender/editors/space_graph/graph_ops.c
index d54e3694f07..9b031c015a9 100644
--- a/source/blender/editors/space_graph/graph_ops.c
+++ b/source/blender/editors/space_graph/graph_ops.c
@@ -346,9 +346,8 @@ static void graphedit_keymap_keyframes(wmKeyConfig *keyconf, wmKeyMap *keymap)
/* graph_edit.c */
- /* snap - current frame to selected keys */
- // TODO: maybe since this is called jump, we're better to have it on <something>-J?
- WM_keymap_add_item(keymap, "GRAPH_OT_frame_jump", SKEY, KM_PRESS, KM_CTRL | KM_SHIFT, 0);
+ /* jump to selected keyframes */
+ WM_keymap_add_item(keymap, "GRAPH_OT_frame_jump", GKEY, KM_PRESS, KM_CTRL, 0);
/* menu + single-step transform */
WM_keymap_add_item(keymap, "GRAPH_OT_snap", SKEY, KM_PRESS, KM_SHIFT, 0);
@@ -372,7 +371,7 @@ static void graphedit_keymap_keyframes(wmKeyConfig *keyconf, wmKeyMap *keymap)
/* insertkey */
WM_keymap_add_item(keymap, "GRAPH_OT_keyframe_insert", IKEY, KM_PRESS, 0, 0);
- WM_keymap_add_item(keymap, "GRAPH_OT_click_insert", LEFTMOUSE, KM_CLICK, KM_CTRL, 0);
+ WM_keymap_add_item(keymap, "GRAPH_OT_click_insert", ACTIONMOUSE, KM_CLICK, KM_CTRL, 0);
/* copy/paste */
WM_keymap_add_item(keymap, "GRAPH_OT_copy", CKEY, KM_PRESS, KM_CTRL, 0);
diff --git a/source/blender/editors/space_graph/graph_select.c b/source/blender/editors/space_graph/graph_select.c
index 633f2b72cf6..978b3224850 100644
--- a/source/blender/editors/space_graph/graph_select.c
+++ b/source/blender/editors/space_graph/graph_select.c
@@ -325,7 +325,7 @@ static int graphkeys_borderselect_exec(bContext *C, wmOperator *op)
* - the frame-range select option is favored over the channel one (x over y), as frame-range one is often
* used for tweaking timing when "blocking", while channels is not that useful...
*/
- if ((BLI_RCT_SIZE_X(&rect)) >= (BLI_RCT_SIZE_Y(&rect)))
+ if ((BLI_rcti_size_x(&rect)) >= (BLI_rcti_size_y(&rect)))
mode = BEZT_OK_FRAMERANGE;
else
mode = BEZT_OK_VALUERANGE;
@@ -757,7 +757,7 @@ static void graphkeys_select_leftright(bAnimContext *ac, short leftright, short
if (leftright == GRAPHKEYS_LRSEL_LEFT) {
ked.f1 = MINAFRAMEF;
ked.f2 = (float)(CFRA + 0.1f);
- }
+ }
else {
ked.f1 = (float)(CFRA - 0.1f);
ked.f2 = MAXFRAMEF;
@@ -835,7 +835,7 @@ static int graphkeys_select_leftright_invoke(bContext *C, wmOperator *op, wmEven
UI_view2d_region_to_view(v2d, event->mval[0], event->mval[1], &x, NULL);
if (x < CFRA)
RNA_enum_set(op->ptr, "mode", GRAPHKEYS_LRSEL_LEFT);
- else
+ else
RNA_enum_set(op->ptr, "mode", GRAPHKEYS_LRSEL_RIGHT);
}
@@ -1113,7 +1113,7 @@ static void mouse_graph_keys(bAnimContext *ac, const int mval[2], short select_m
nvi = find_nearest_fcurve_vert(ac, mval);
/* check if anything to select */
- if (nvi == NULL)
+ if (nvi == NULL)
return;
/* deselect all other curves? */
@@ -1241,7 +1241,7 @@ static void graphkeys_mselect_column(bAnimContext *ac, const int mval[2], short
nvi = find_nearest_fcurve_vert(ac, mval);
/* check if anything to select */
- if (nvi == NULL)
+ if (nvi == NULL)
return;
/* get frame number on which elements should be selected */
diff --git a/source/blender/editors/space_graph/space_graph.c b/source/blender/editors/space_graph/space_graph.c
index a4611cf1453..f41169b6c39 100644
--- a/source/blender/editors/space_graph/space_graph.c
+++ b/source/blender/editors/space_graph/space_graph.c
@@ -441,7 +441,7 @@ static void graph_listener(ScrArea *sa, wmNotifier *wmn)
ED_area_tag_refresh(sa);
break;
case NC_SCENE:
- switch (wmn->data) {
+ switch (wmn->data) {
case ND_OB_ACTIVE: /* selection changed, so force refresh to flush (needs flag set to do syncing) */
case ND_OB_SELECT:
sipo->flag |= SIPO_TEMP_NEEDCHANSYNC;
@@ -461,7 +461,7 @@ static void graph_listener(ScrArea *sa, wmNotifier *wmn)
ED_area_tag_refresh(sa);
break;
case ND_TRANSFORM:
- break; /*do nothing*/
+ break; /*do nothing*/
default: /* just redrawing the view will do */
ED_area_tag_redraw(sa);
diff --git a/source/blender/editors/space_image/image_buttons.c b/source/blender/editors/space_image/image_buttons.c
index c372973b7b0..ae7a718ab5b 100644
--- a/source/blender/editors/space_image/image_buttons.c
+++ b/source/blender/editors/space_image/image_buttons.c
@@ -71,28 +71,6 @@
#include "image_intern.h"
-#define B_REDR 1
-#define B_IMAGECHANGED 2
-#define B_NOP 0
-#define B_TWINANIM 5
-#define B_SIMAGETILE 6
-#define B_IDNAME 10
-#define B_FACESEL_PAINT_TEST 11
-#define B_SIMA_RECORD 12
-#define B_SIMA_PLAY 13
-
-#define B_SIMANOTHING 16
-#define B_SIMABRUSHCHANGE 17
-#define B_SIMABRUSHBROWSE 18
-#define B_SIMABRUSHLOCAL 19
-#define B_SIMABRUSHDELETE 20
-#define B_KEEPDATA 21
-#define B_SIMABTEXBROWSE 22
-#define B_SIMABTEXDELETE 23
-#define B_VPCOLSLI 24
-#define B_SIMACLONEBROWSE 25
-#define B_SIMACLONEDELETE 26
-
/* proto */
static void image_info(Scene *scene, ImageUser *iuser, Image *ima, ImBuf *ibuf, char *str)
@@ -213,7 +191,7 @@ void image_preview_event(int event)
waitcursor(0);
WM_event_add_notifier(C, NC_IMAGE, ima_v);
- }
+ }
}
@@ -228,13 +206,13 @@ static void preview_cb(ScrArea *sa, struct uiBlock *block)
int mval[2];
if (G.scene->r.mode & R_BORDER) {
- winx *= BLI_RCT_SIZE_X(&G.scene->r.border);
- winy *= BLI_RCT_SIZE_Y(&G.scene->r.border);
+ winx *= BLI_rcti_size_x(&G.scene->r.border);
+ winy *= BLI_rctf_size_y(&G.scene->r.border);
}
/* while dragging we need to update the rects, otherwise it doesn't end with correct one */
- BLI_rctf_init(&dispf, 15.0f, BLI_RCT_SIZE_X(&block->rect) - 15.0f, 15.0f, (BLI_RCT_SIZE_Y(&block->rect)) - 15.0f);
+ BLI_rctf_init(&dispf, 15.0f, BLI_rcti_size_x(&block->rect) - 15.0f, 15.0f, (BLI_rctf_size_y(&block->rect)) - 15.0f);
ui_graphics_to_window_rct(sa->win, &dispf, disprect);
/* correction for gla draw */
@@ -744,8 +722,10 @@ void uiTemplateImage(uiLayout *layout, bContext *C, PointerRNA *ptr, const char
split = uiLayoutSplit(layout, 0.0f, FALSE);
col = uiLayoutColumn(split, TRUE);
+ uiLayoutSetEnabled(col, 0);
uiItemR(col, &imaptr, "generated_width", 0, "X", ICON_NONE);
uiItemR(col, &imaptr, "generated_height", 0, "Y", ICON_NONE);
+
uiItemR(col, &imaptr, "use_generated_float", 0, NULL, ICON_NONE);
uiItemR(split, &imaptr, "generated_type", UI_ITEM_R_EXPAND, NULL, ICON_NONE);
@@ -781,9 +761,10 @@ void uiTemplateImageSettings(uiLayout *layout, PointerRNA *imfptr, int color_man
uiItemR(sub, imfptr, "color_mode", UI_ITEM_R_EXPAND, IFACE_("Color"), ICON_NONE);
/* only display depth setting if multiple depths can be used */
- if ((ELEM6(depth_ok,
+ if ((ELEM7(depth_ok,
R_IMF_CHAN_DEPTH_1,
R_IMF_CHAN_DEPTH_8,
+ R_IMF_CHAN_DEPTH_10,
R_IMF_CHAN_DEPTH_12,
R_IMF_CHAN_DEPTH_16,
R_IMF_CHAN_DEPTH_24,
@@ -823,9 +804,13 @@ void uiTemplateImageSettings(uiLayout *layout, PointerRNA *imfptr, int color_man
uiItemR(col, imfptr, "use_jpeg2k_ycc", 0, NULL, ICON_NONE);
}
+ if (imf->imtype == R_IMF_IMTYPE_DPX) {
+ uiItemR(col, imfptr, "use_cineon_log", 0, NULL, ICON_NONE);
+ }
+
if (imf->imtype == R_IMF_IMTYPE_CINEON) {
#if 1
- uiItemL(col, IFACE_("Hard coded Non-Linear, Gamma: 1.0"), ICON_NONE);
+ uiItemL(col, IFACE_("Hard coded Non-Linear, Gamma:1.7"), ICON_NONE);
#else
uiItemR(col, imfptr, "use_cineon_log", 0, NULL, ICON_NONE);
uiItemR(col, imfptr, "cineon_black", 0, NULL, ICON_NONE);
@@ -836,7 +821,7 @@ void uiTemplateImageSettings(uiLayout *layout, PointerRNA *imfptr, int color_man
/* color management */
if (color_management &&
- (!BKE_imtype_supports_float(imf->imtype) ||
+ (!BKE_imtype_requires_linear_float(imf->imtype) ||
(show_preview && imf->flag & R_IMF_FLAG_PREVIEW_JPG)))
{
prop = RNA_struct_find_property(imfptr, "display_settings");
diff --git a/source/blender/editors/space_image/image_draw.c b/source/blender/editors/space_image/image_draw.c
index 638a2ac6681..9fc2b981547 100644
--- a/source/blender/editors/space_image/image_draw.c
+++ b/source/blender/editors/space_image/image_draw.c
@@ -78,8 +78,6 @@
#include "image_intern.h"
-#define HEADER_HEIGHT 18
-
static void draw_render_info(Scene *scene, Image *ima, ARegion *ar)
{
RenderResult *rr;
@@ -118,7 +116,7 @@ void ED_image_draw_info(Scene *scene, ARegion *ar, int color_manage, int use_def
/* noisy, high contrast make impossible to read if lower alpha is used. */
glColor4ub(0, 0, 0, 190);
- glRecti(0.0, 0.0, BLI_RCT_SIZE_X(&ar->winrct) + 1, 20);
+ glRecti(0.0, 0.0, BLI_rcti_size_x(&ar->winrct) + 1, 20);
glDisable(GL_BLEND);
BLF_size(blf_mono_font, 11, 72);
@@ -524,7 +522,7 @@ static void draw_image_buffer_tiled(SpaceImage *sima, ARegion *ar, Scene *scene,
dy = ibuf->y / ima->yrep;
sx = (sima->curtile % ima->xrep) * dx;
sy = (sima->curtile / ima->xrep) * dy;
- rect = get_part_from_buffer((unsigned int*)display_buffer, ibuf->x, sx, sy, sx + dx, sy + dy);
+ rect = get_part_from_buffer((unsigned int *)display_buffer, ibuf->x, sx, sy, sx + dx, sy + dy);
/* draw repeated */
for (sy = 0; sy + dy <= ibuf->y; sy += dy) {
@@ -580,7 +578,7 @@ void draw_image_grease_pencil(bContext *C, short onlyv2d)
}
else {
/* assume that UI_view2d_restore(C) has been called... */
- //SpaceImage *sima= (SpaceImage *)CTX_wm_space_data(C);
+ //SpaceImage *sima = (SpaceImage *)CTX_wm_space_data(C);
/* draw grease-pencil ('screen' strokes) */
draw_gpencil_view2d(C, 0);
@@ -793,7 +791,7 @@ void draw_image_main(const bContext *C, ARegion *ar)
xoffs = scene->r.disprect.xmin;
yoffs = scene->r.disprect.ymin;
glColor3ub(0, 0, 0);
- calc_image_view(sima, 'f');
+ calc_image_view(sima, 'f');
myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
glRectf(0.0f, 0.0f, 1.0f, 1.0f);
glLoadIdentity();
diff --git a/source/blender/editors/space_image/image_edit.c b/source/blender/editors/space_image/image_edit.c
index 79d01491df7..4ca2f8888f8 100644
--- a/source/blender/editors/space_image/image_edit.c
+++ b/source/blender/editors/space_image/image_edit.c
@@ -78,8 +78,8 @@ void ED_space_image_set(SpaceImage *sima, Scene *scene, Object *obedit, Image *i
if (sima->image)
BKE_image_signal(sima->image, &sima->iuser, IMA_SIGNAL_USER_NEW_IMAGE);
- if (sima->image && sima->image->id.us == 0)
- sima->image->id.us = 1;
+ if (sima->image && ID_REAL_USERS(sima->image) <= 0)
+ sima->image->id.us = max_ii(sima->image->id.us, 0) + 1;
if (obedit)
WM_main_add_notifier(NC_GEOM | ND_DATA, obedit->data);
@@ -97,8 +97,8 @@ void ED_space_image_set_mask(bContext *C, SpaceImage *sima, Mask *mask)
sima->mask_info.mask = mask;
/* weak, but same as image/space */
- if (sima->mask_info.mask && sima->mask_info.mask->id.us == 0)
- sima->mask_info.mask->id.us = 1;
+ if (sima->mask_info.mask && ID_REAL_USERS(sima->mask_info.mask) <= 0)
+ sima->mask_info.mask->id.us = max_ii(sima->mask_info.mask->id.us, 0) + 1;
if (C) {
WM_event_add_notifier(C, NC_MASK | NA_SELECTED, mask);
@@ -120,6 +120,8 @@ ImBuf *ED_space_image_acquire_buffer(SpaceImage *sima, void **lock_r)
if (ibuf && (ibuf->rect || ibuf->rect_float))
return ibuf;
}
+ else
+ *lock_r = NULL;
return NULL;
}
@@ -161,8 +163,8 @@ void ED_space_image_get_size(SpaceImage *sima, int *width, int *height)
*height = (scene->r.ysch * scene->r.size) / 100;
if ((scene->r.mode & R_BORDER) && (scene->r.mode & R_CROP)) {
- *width *= BLI_RCT_SIZE_X(&scene->r.border);
- *height *= BLI_RCT_SIZE_Y(&scene->r.border);
+ *width *= BLI_rctf_size_x(&scene->r.border);
+ *height *= BLI_rctf_size_y(&scene->r.border);
}
}
@@ -204,8 +206,8 @@ void ED_space_image_get_zoom(SpaceImage *sima, ARegion *ar, float *zoomx, float
ED_space_image_get_size(sima, &width, &height);
- *zoomx = (float)(BLI_RCT_SIZE_X(&ar->winrct) + 1) / (float)(BLI_RCT_SIZE_X(&ar->v2d.cur) * width);
- *zoomy = (float)(BLI_RCT_SIZE_Y(&ar->winrct) + 1) / (float)(BLI_RCT_SIZE_Y(&ar->v2d.cur) * height);
+ *zoomx = (float)(BLI_rcti_size_x(&ar->winrct) + 1) / (float)(BLI_rctf_size_x(&ar->v2d.cur) * width);
+ *zoomy = (float)(BLI_rcti_size_y(&ar->winrct) + 1) / (float)(BLI_rctf_size_y(&ar->v2d.cur) * height);
}
void ED_space_image_get_uv_aspect(SpaceImage *sima, float *aspx, float *aspy)
diff --git a/source/blender/editors/space_image/image_ops.c b/source/blender/editors/space_image/image_ops.c
index 16804c5a1c6..ce3c6e1fd26 100644
--- a/source/blender/editors/space_image/image_ops.c
+++ b/source/blender/editors/space_image/image_ops.c
@@ -39,6 +39,8 @@
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
+#include "BLF_translation.h"
+
#include "DNA_object_types.h"
#include "DNA_node_types.h"
#include "DNA_packedFile_types.h"
@@ -99,9 +101,9 @@ static void sima_zoom_set(SpaceImage *sima, ARegion *ar, float zoom, float locat
if ((width < 4) && (height < 4))
sima->zoom = oldzoom;
- else if (BLI_RCT_SIZE_X(&ar->winrct) <= sima->zoom)
+ else if (BLI_rcti_size_x(&ar->winrct) <= sima->zoom)
sima->zoom = oldzoom;
- else if (BLI_RCT_SIZE_Y(&ar->winrct) <= sima->zoom)
+ else if (BLI_rcti_size_y(&ar->winrct) <= sima->zoom)
sima->zoom = oldzoom;
}
@@ -183,7 +185,7 @@ static int space_image_poll(bContext *C)
int space_image_main_area_poll(bContext *C)
{
SpaceImage *sima = CTX_wm_space_image(C);
- // XXX ARegion *ar= CTX_wm_region(C);
+ // XXX ARegion *ar = CTX_wm_region(C);
if (sima)
return 1; // XXX (ar && ar->type->regionid == RGN_TYPE_WINDOW);
@@ -430,11 +432,16 @@ static int image_view_zoom_invoke(bContext *C, wmOperator *op, wmEvent *event)
if (event->type == MOUSEZOOM) {
SpaceImage *sima = CTX_wm_space_image(C);
ARegion *ar = CTX_wm_region(C);
- float factor, location[2];
+ float delta, factor, location[2];
UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &location[0], &location[1]);
- factor = 1.0f + (event->x - event->prevx + event->y - event->prevy) / 300.0f;
+ delta = event->x - event->prevx + event->y - event->prevy;
+
+ if (U.uiflag & USER_ZOOM_INVERT)
+ delta *= -1;
+
+ factor = 1.0f + delta / 300.0f;
RNA_float_set(op->ptr, "factor", factor);
sima_zoom_set(sima, ar, sima->zoom * factor, location);
ED_region_tag_redraw(CTX_wm_region(C));
@@ -452,11 +459,16 @@ static int image_view_zoom_modal(bContext *C, wmOperator *op, wmEvent *event)
SpaceImage *sima = CTX_wm_space_image(C);
ARegion *ar = CTX_wm_region(C);
ViewZoomData *vpd = op->customdata;
- float factor;
+ float delta, factor;
switch (event->type) {
case MOUSEMOVE:
- factor = 1.0f + (vpd->x - event->x + vpd->y - event->y) / 300.0f;
+ delta = event->x - vpd->x + event->y - vpd->y;
+
+ if (U.uiflag & USER_ZOOM_INVERT)
+ delta *= -1;
+
+ factor = 1.0f + delta / 300.0f;
RNA_float_set(op->ptr, "factor", factor);
sima_zoom_set(sima, ar, vpd->zoom * factor, vpd->location);
ED_region_tag_redraw(CTX_wm_region(C));
@@ -496,7 +508,7 @@ void IMAGE_OT_view_zoom(wmOperatorType *ot)
ot->flag = OPTYPE_BLOCKING;
/* properties */
- RNA_def_float(ot->srna, "factor", 0.0f, 0.0f, FLT_MAX,
+ RNA_def_float(ot->srna, "factor", 0.0f, -FLT_MAX, FLT_MAX,
"Factor", "Zoom factor, values higher than 1.0 zoom in, lower values zoom out", -FLT_MAX, FLT_MAX);
}
@@ -541,7 +553,7 @@ static int image_view_ndof_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *
sima->xof += pan_x;
sima->yof += pan_y;
- ED_region_tag_redraw(ar);
+ ED_region_tag_redraw(ar);
return OPERATOR_FINISHED;
}
@@ -582,14 +594,14 @@ static int image_view_all_exec(bContext *C, wmOperator *UNUSED(op))
h = height * aspy;
/* check if the image will fit in the image with (zoom == 1) */
- width = BLI_RCT_SIZE_X(&ar->winrct) + 1;
- height = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
+ width = BLI_rcti_size_x(&ar->winrct) + 1;
+ height = BLI_rcti_size_y(&ar->winrct) + 1;
if ((w >= width || h >= height) && (width > 0 && height > 0)) {
/* find the zoom value that will fit the image in the image space */
zoomx = width / w;
zoomy = height / h;
- sima_zoom_set(sima, ar, 1.0f / power_of_2(1.0f / minf(zoomx, zoomy)), NULL);
+ sima_zoom_set(sima, ar, 1.0f / power_of_2(1.0f / min_ff(zoomx, zoomy)), NULL);
}
else
sima_zoom_set(sima, ar, 1.0f, NULL);
@@ -606,7 +618,7 @@ void IMAGE_OT_view_all(wmOperatorType *ot)
/* identifiers */
ot->name = "View All";
ot->idname = "IMAGE_OT_view_all";
- ot->description = "View the whole picture";
+ ot->description = "View the entire image";
/* api callbacks */
ot->exec = image_view_all_exec;
@@ -793,14 +805,14 @@ void IMAGE_OT_view_zoom_ratio(wmOperatorType *ot)
/* identifiers */
ot->name = "View Zoom Ratio";
ot->idname = "IMAGE_OT_view_zoom_ratio";
- ot->description = "Set zoom ration of the view";
+ ot->description = "Set zoom ratio of the view";
/* api callbacks */
ot->exec = image_view_zoom_ratio_exec;
ot->poll = space_image_main_area_poll;
/* properties */
- RNA_def_float(ot->srna, "ratio", 0.0f, 0.0f, FLT_MAX,
+ RNA_def_float(ot->srna, "ratio", 0.0f, -FLT_MAX, FLT_MAX,
"Ratio", "Zoom ratio, 1.0 is 1:1, higher is zoomed in, lower is zoomed out", -FLT_MAX, FLT_MAX);
}
@@ -848,7 +860,8 @@ static int image_open_exec(bContext *C, wmOperator *op)
if (!ima) {
if (op->customdata) MEM_freeN(op->customdata);
- BKE_reportf(op->reports, RPT_ERROR, "Can't read: \"%s\", %s", str, errno ? strerror(errno) : "Unsupported image format");
+ BKE_reportf(op->reports, RPT_ERROR, "Cannot read '%s': %s",
+ str, errno ? strerror(errno) : TIP_("unsupported image format"));
return OPERATOR_CANCELLED;
}
@@ -1137,7 +1150,7 @@ static int save_image_options_init(SaveImageOptions *simopts, SpaceImage *sima,
else {
simopts->im_format.imtype = BKE_ftype_to_imtype(ibuf->ftype);
}
- //simopts->subimtype= scene->r.subimtype; /* XXX - this is lame, we need to make these available too! */
+ //simopts->subimtype = scene->r.subimtype; /* XXX - this is lame, we need to make these available too! */
simopts->im_format.quality = ibuf->ftype & 0xff;
BLI_strncpy(simopts->filepath, ibuf->name, sizeof(simopts->filepath));
@@ -1205,39 +1218,6 @@ static void save_image_options_to_op(SaveImageOptions *simopts, wmOperator *op)
RNA_string_set(op->ptr, "filepath", simopts->filepath);
}
-static ImBuf *save_image_colormanaged_imbuf_acquire(ImBuf *ibuf, SaveImageOptions *simopts, int save_as_render, void **cache_handle)
-{
- ImageFormatData *imf = &simopts->im_format;
- ImBuf *colormanaged_ibuf;
- int do_colormanagement;
-
- *cache_handle = NULL;
- do_colormanagement = save_as_render && !BKE_imtype_supports_float(imf->imtype);
-
- if (do_colormanagement) {
- unsigned char *display_buffer;
-
- display_buffer = IMB_display_buffer_acquire(ibuf, &imf->view_settings, &imf->display_settings, cache_handle);
-
- if (*cache_handle) {
- colormanaged_ibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, 0);
- colormanaged_ibuf->rect = (unsigned int *) display_buffer;
- }
- else {
- /* no cache handle means color management didn't run transformation
- * or performed transformation to image's byte buffer which doesn't
- * require allocating new image buffer
- */
- colormanaged_ibuf = ibuf;
- }
- }
- else {
- colormanaged_ibuf = ibuf;
- }
-
- return colormanaged_ibuf;
-}
-
/* assumes name is FILE_MAX */
/* ima->name and ibuf->name should end up the same */
static void save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveImageOptions *simopts, int do_newpath)
@@ -1247,12 +1227,12 @@ static void save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveI
ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
if (ibuf) {
- void *cache_handle;
ImBuf *colormanaged_ibuf;
const char *relbase = ID_BLEND_PATH(CTX_data_main(C), &ima->id);
const short relative = (RNA_struct_find_property(op->ptr, "relative_path") && RNA_boolean_get(op->ptr, "relative_path"));
const short save_copy = (RNA_struct_find_property(op->ptr, "copy") && RNA_boolean_get(op->ptr, "copy"));
const short save_as_render = (RNA_struct_find_property(op->ptr, "save_as_render") && RNA_boolean_get(op->ptr, "save_as_render"));
+ ImageFormatData *imf = &simopts->im_format;
short ok = FALSE;
/* old global to ensure a 2nd save goes to same dir */
@@ -1277,7 +1257,7 @@ static void save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveI
}
}
- colormanaged_ibuf = save_image_colormanaged_imbuf_acquire(ibuf, simopts, save_as_render, &cache_handle);
+ colormanaged_ibuf = IMB_colormanagement_imbuf_for_write(ibuf, save_as_render, TRUE, &imf->view_settings, &imf->display_settings, imf);
if (simopts->im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
Scene *scene = CTX_data_scene(C);
@@ -1292,8 +1272,7 @@ static void save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveI
BKE_image_release_renderresult(scene, ima);
}
else {
- if (BKE_imbuf_write_as(colormanaged_ibuf, simopts->filepath, &simopts->im_format, save_copy))
- {
+ if (BKE_imbuf_write_as(colormanaged_ibuf, simopts->filepath, &simopts->im_format, save_copy)) {
ok = TRUE;
}
}
@@ -1337,7 +1316,7 @@ static void save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveI
}
}
else {
- BKE_reportf(op->reports, RPT_ERROR, "Couldn't write image: %s", simopts->filepath);
+ BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s", simopts->filepath);
}
@@ -1345,12 +1324,8 @@ static void save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveI
WM_cursor_wait(0);
- if (cache_handle) {
- colormanaged_ibuf->rect = NULL;
+ if (colormanaged_ibuf != ibuf)
IMB_freeImBuf(colormanaged_ibuf);
-
- IMB_display_buffer_release(cache_handle);
- }
}
ED_space_image_release_buffer(sima, lock);
@@ -1414,7 +1389,7 @@ static int image_save_as_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(eve
RNA_boolean_set(op->ptr, "copy", TRUE);
}
- if (ima->source == IMA_SRC_VIEWER)
+ if (ima->source == IMA_SRC_VIEWER || (ima->flag & IMA_VIEW_AS_RENDER))
RNA_boolean_set(op->ptr, "save_as_render", TRUE);
else
RNA_boolean_set(op->ptr, "save_as_render", FALSE);
@@ -1461,6 +1436,24 @@ static void image_save_as_draw(bContext *UNUSED(C), wmOperator *op)
uiDefAutoButsRNA(layout, &ptr, image_save_as_draw_check_prop, '\0');
}
+static int image_save_as_poll(bContext *C)
+{
+ if (space_image_buffer_exists_poll(C)) {
+ if (G.is_rendering) {
+ /* no need to NULL check here */
+ SpaceImage *sima = CTX_wm_space_image(C);
+ Image *ima = ED_space_image(sima);
+
+ if (ima->source == IMA_SRC_VIEWER) {
+ CTX_wm_operator_poll_msg_set(C, "can't save image while rendering");
+ return FALSE;
+ }
+ }
+ return TRUE;
+ }
+ return FALSE;
+}
+
void IMAGE_OT_save_as(wmOperatorType *ot)
{
// PropertyRNA *prop;
@@ -1476,7 +1469,7 @@ void IMAGE_OT_save_as(wmOperatorType *ot)
ot->invoke = image_save_as_invoke;
ot->cancel = image_save_as_cancel;
ot->ui = image_save_as_draw;
- ot->poll = space_image_buffer_exists_poll;
+ ot->poll = image_save_as_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1505,7 +1498,7 @@ static int image_save_exec(bContext *C, wmOperator *op)
save_image_doit(C, sima, op, &simopts, FALSE);
}
else {
- BKE_reportf(op->reports, RPT_ERROR, "Can not save image, path '%s' is not writable", simopts.filepath);
+ BKE_reportf(op->reports, RPT_ERROR, "Cannot save image, path '%s' is not writable", simopts.filepath);
return OPERATOR_CANCELLED;
}
@@ -1546,7 +1539,7 @@ static int image_save_sequence_exec(bContext *C, wmOperator *op)
}
if (sima->image->type == IMA_TYPE_MULTILAYER) {
- BKE_report(op->reports, RPT_ERROR, "Can't save multilayer sequences");
+ BKE_report(op->reports, RPT_ERROR, "Cannot save multilayer sequences");
return OPERATOR_CANCELLED;
}
@@ -1568,7 +1561,7 @@ static int image_save_sequence_exec(bContext *C, wmOperator *op)
BLI_strncpy(di, ibuf->name, FILE_MAX);
BLI_splitdirstring(di, fi);
- BKE_reportf(op->reports, RPT_INFO, "%d Image(s) will be saved in %s", tot, di);
+ BKE_reportf(op->reports, RPT_INFO, "%d image(s) will be saved in %s", tot, di);
for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next) {
if (ibuf->userflags & IB_BITMAPDIRTY) {
@@ -1582,7 +1575,7 @@ static int image_save_sequence_exec(bContext *C, wmOperator *op)
break;
}
- BKE_reportf(op->reports, RPT_INFO, "Saved: %s\n", ibuf->name);
+ BKE_reportf(op->reports, RPT_INFO, "Saved %s", ibuf->name);
ibuf->userflags &= ~IB_BITMAPDIRTY;
}
}
@@ -1692,16 +1685,24 @@ static int image_new_exec(bContext *C, wmOperator *op)
RNA_property_pointer_set(&ptr, prop, idptr);
RNA_property_update(C, &ptr, prop);
}
- else if (sima)
+ else if (sima) {
ED_space_image_set(sima, scene, obedit, ima);
+ }
+ else {
+ Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
+ if (tex && tex->type == TEX_IMAGE) {
+ tex->ima = ima;
+ ED_area_tag_redraw(CTX_wm_area(C));
+ }
+ }
- // XXX other users?
BKE_image_signal(ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_USER_NEW_IMAGE);
return OPERATOR_FINISHED;
}
/* XXX, Ton is not a fan of OK buttons but using this function to avoid undo/redo bug while in mesh-editmode, - campbell */
+/* XXX Note: the WM_operator_props_dialog_popup() doesn't work for uiIDContextProperty(), image is not being that way */
static int image_new_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
{
return WM_operator_props_dialog_popup(C, op, 300, 100);
@@ -1854,7 +1855,7 @@ static int image_pack_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
- BKE_report(op->reports, RPT_ERROR, "Can't pack edited image from disk, only as internal PNG");
+ BKE_report(op->reports, RPT_ERROR, "Cannot pack edited image from disk, only as internal PNG");
return OPERATOR_CANCELLED;
}
@@ -2372,8 +2373,8 @@ static int image_record_composite_apply(bContext *C, wmOperator *op)
WM_cursor_time(CTX_wm_window(C), scene->r.cfra);
- // XXX scene->nodetree->test_break= blender_test_break;
- // XXX scene->nodetree->test_break= NULL;
+ // XXX scene->nodetree->test_break = blender_test_break;
+ // XXX scene->nodetree->test_break = NULL;
BKE_image_all_free_anim_ibufs(scene->r.cfra);
ntreeCompositTagAnimated(scene->nodetree);
@@ -2439,8 +2440,7 @@ static int image_record_composite_exec(bContext *C, wmOperator *op)
if (!image_record_composite_init(C, op))
return OPERATOR_CANCELLED;
- while (image_record_composite_apply(C, op))
- ;
+ while (image_record_composite_apply(C, op)) {}
image_record_composite_exit(C, op);
diff --git a/source/blender/editors/space_image/space_image.c b/source/blender/editors/space_image/space_image.c
index 5b288bd6149..4131cbfdd0d 100644
--- a/source/blender/editors/space_image/space_image.c
+++ b/source/blender/editors/space_image/space_image.c
@@ -408,16 +408,15 @@ static void image_refresh(const bContext *C, ScrArea *sa)
MTexPoly *tf;
if (em && EDBM_mtexpoly_check(em)) {
- sima->image = NULL;
-
tf = EDBM_mtexpoly_active_get(em, NULL, sloppy, selected);
if (tf) {
/* don't need to check for pin here, see above */
sima->image = tf->tpage;
- if (sima->flag & SI_EDITTILE) ;
- else sima->curtile = tf->tile;
+ if ((sima->flag & SI_EDITTILE) == 0) {
+ sima->curtile = tf->tile;
+ }
}
}
}
@@ -438,6 +437,10 @@ static void image_listener(ScrArea *sa, wmNotifier *wmn)
ED_area_tag_redraw(sa);
break;
case ND_MODE:
+ if (wmn->subtype == NS_EDITMODE_MESH)
+ ED_area_tag_refresh(sa);
+ ED_area_tag_redraw(sa);
+ break;
case ND_RENDER_RESULT:
case ND_RENDER_OPTIONS:
case ND_COMPO_RESULT:
@@ -454,7 +457,7 @@ static void image_listener(ScrArea *sa, wmNotifier *wmn)
ED_area_tag_redraw(sa);
}
break;
- case NC_SPACE:
+ case NC_SPACE:
if (wmn->data == ND_SPACE_IMAGE) {
image_scopes_tag_refresh(sa);
ED_area_tag_redraw(sa);
@@ -547,7 +550,7 @@ static void image_main_area_set_view2d(SpaceImage *sima, ARegion *ar)
int width, height, winx, winy;
#if 0
- if (image_preview_active(curarea, &width, &height)) ;
+ if (image_preview_active(curarea, &width, &height)) {}
else
#endif
ED_space_image_get_size(sima, &width, &height);
@@ -558,8 +561,8 @@ static void image_main_area_set_view2d(SpaceImage *sima, ARegion *ar)
if (ima)
h *= ima->aspy / ima->aspx;
- winx = BLI_RCT_SIZE_X(&ar->winrct) + 1;
- winy = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
+ winx = BLI_rcti_size_x(&ar->winrct) + 1;
+ winy = BLI_rcti_size_y(&ar->winrct) + 1;
ar->v2d.tot.xmin = 0;
ar->v2d.tot.ymin = 0;
@@ -706,8 +709,8 @@ static void image_main_area_listener(ARegion *ar, wmNotifier *wmn)
{
/* context changes */
switch (wmn->category) {
- case NC_SCREEN:
- if (wmn->data == ND_GPENCIL)
+ case NC_GPENCIL:
+ if (wmn->action == NA_EDITED)
ED_region_tag_redraw(ar);
break;
}
@@ -735,8 +738,8 @@ static void image_buttons_area_listener(ARegion *ar, wmNotifier *wmn)
{
/* context changes */
switch (wmn->category) {
- case NC_SCREEN:
- if (wmn->data == ND_GPENCIL)
+ case NC_GPENCIL:
+ if (wmn->data == ND_DATA)
ED_region_tag_redraw(ar);
break;
case NC_BRUSH:
diff --git a/source/blender/editors/space_info/info_draw.c b/source/blender/editors/space_info/info_draw.c
index 35e19bcce38..5830c4574df 100644
--- a/source/blender/editors/space_info/info_draw.c
+++ b/source/blender/editors/space_info/info_draw.c
@@ -136,7 +136,7 @@ static int report_textview_skip__internal(TextViewContext *tvc)
static int report_textview_begin(TextViewContext *tvc)
{
- // SpaceConsole *sc= (SpaceConsole *)tvc->arg1;
+ // SpaceConsole *sc = (SpaceConsole *)tvc->arg1;
ReportList *reports = (ReportList *)tvc->arg2;
tvc->lheight = 14; //sc->lheight;
diff --git a/source/blender/editors/space_info/info_ops.c b/source/blender/editors/space_info/info_ops.c
index 805ff1794c9..131908bc9db 100644
--- a/source/blender/editors/space_info/info_ops.c
+++ b/source/blender/editors/space_info/info_ops.c
@@ -124,7 +124,7 @@ static const EnumPropertyItem unpack_all_method_items[] = {
{PF_WRITE_LOCAL, "WRITE_LOCAL", 0, "Write files to current directory (overwrite existing files)", ""},
{PF_USE_ORIGINAL, "USE_ORIGINAL", 0, "Use files in original location (create when necessary)", ""},
{PF_WRITE_ORIGINAL, "WRITE_ORIGINAL", 0, "Write files to original location (overwrite existing files)", ""},
- {PF_KEEP, "KEEP", 0, "Disable AutoPack, keep all packed files", ""},
+ {PF_KEEP, "KEEP", 0, "Disable Auto-pack, keep all packed files", ""},
/* {PF_ASK, "ASK", 0, "Ask for each file", ""}, */
{0, NULL, 0, NULL, NULL}};
@@ -150,7 +150,7 @@ static int unpack_all_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event)
count = countPackedFiles(bmain);
if (!count) {
- BKE_report(op->reports, RPT_WARNING, "No packed files. Autopack disabled");
+ BKE_report(op->reports, RPT_WARNING, "No packed files (auto-pack disabled)");
G.fileflags &= ~G_AUTOPACK;
return OPERATOR_CANCELLED;
}
@@ -196,7 +196,7 @@ static int make_paths_relative_exec(bContext *C, wmOperator *op)
Main *bmain = CTX_data_main(C);
if (!G.relbase_valid) {
- BKE_report(op->reports, RPT_WARNING, "Can't set relative paths with an unsaved blend file");
+ BKE_report(op->reports, RPT_WARNING, "Cannot set relative paths with an unsaved blend file");
return OPERATOR_CANCELLED;
}
@@ -229,7 +229,7 @@ static int make_paths_absolute_exec(bContext *C, wmOperator *op)
Main *bmain = CTX_data_main(C);
if (!G.relbase_valid) {
- BKE_report(op->reports, RPT_WARNING, "Can't set absolute paths with an unsaved blend file");
+ BKE_report(op->reports, RPT_WARNING, "Cannot set absolute paths with an unsaved blend file");
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/space_info/info_report.c b/source/blender/editors/space_info/info_report.c
index 2324f735a33..049a50f89fc 100644
--- a/source/blender/editors/space_info/info_report.c
+++ b/source/blender/editors/space_info/info_report.c
@@ -68,9 +68,9 @@ int info_report_mask(SpaceInfo *UNUSED(sinfo))
// TODO, get this working again!
static int report_replay_exec(bContext *C, wmOperator *UNUSED(op))
{
-// SpaceInfo *sc= CTX_wm_space_info(C);
-// ReportList *reports= CTX_wm_reports(C);
-// int report_mask= info_report_mask(sc);
+// SpaceInfo *sc = CTX_wm_space_info(C);
+// ReportList *reports = CTX_wm_reports(C);
+// int report_mask = info_report_mask(sc);
// Report *report;
#if 0
@@ -223,7 +223,7 @@ static int borderselect_exec(bContext *C, wmOperator *op)
int extend = RNA_boolean_get(op->ptr, "extend");
Report *report_min, *report_max, *report;
- //View2D *v2d= UI_view2d_fromcontext(C);
+ //View2D *v2d = UI_view2d_fromcontext(C);
rcti rect;
diff --git a/source/blender/editors/space_info/info_stats.c b/source/blender/editors/space_info/info_stats.c
index 4ffa99319c4..5e5e0c87feb 100644
--- a/source/blender/editors/space_info/info_stats.c
+++ b/source/blender/editors/space_info/info_stats.c
@@ -368,7 +368,7 @@ static void stats_string(Scene *scene)
s += sprintf(s, "%s | ", versionstr);
if (scene->obedit) {
- if (ob_get_keyblock(scene->obedit))
+ if (BKE_keyblock_from_object(scene->obedit))
s += sprintf(s, "(Key) ");
if (scene->obedit->type == OB_MESH) {
diff --git a/source/blender/editors/space_info/space_info.c b/source/blender/editors/space_info/space_info.c
index 7cb89b6bc6b..f108881091a 100644
--- a/source/blender/editors/space_info/space_info.c
+++ b/source/blender/editors/space_info/space_info.c
@@ -93,7 +93,7 @@ static SpaceLink *info_new(const bContext *UNUSED(C))
ar->v2d.minzoom = ar->v2d.maxzoom = 1.0f;
/* for now, aspect ratio should be maintained, and zoom is clamped within sane default limits */
- //ar->v2d.keepzoom= (V2D_KEEPASPECT|V2D_LIMITZOOM);
+ //ar->v2d.keepzoom = (V2D_KEEPASPECT|V2D_LIMITZOOM);
return (SpaceLink *)sinfo;
}
@@ -101,7 +101,7 @@ static SpaceLink *info_new(const bContext *UNUSED(C))
/* not spacelink itself */
static void info_free(SpaceLink *UNUSED(sl))
{
-// SpaceInfo *sinfo= (SpaceInfo*) sl;
+// SpaceInfo *sinfo = (SpaceInfo *) sl;
}
@@ -228,7 +228,7 @@ static void info_header_area_draw(const bContext *C, ARegion *ar)
static void info_main_area_listener(ARegion *ar, wmNotifier *wmn)
{
- // SpaceInfo *sinfo= sa->spacedata.first;
+ // SpaceInfo *sinfo = sa->spacedata.first;
/* context changes */
switch (wmn->category) {
@@ -249,7 +249,7 @@ static void info_header_listener(ARegion *ar, wmNotifier *wmn)
if (ELEM(wmn->data, ND_SCREENCAST, ND_ANIMPLAY))
ED_region_tag_redraw(ar);
break;
- case NC_WM:
+ case NC_WM:
if (wmn->data == ND_JOB)
ED_region_tag_redraw(ar);
break;
@@ -257,7 +257,7 @@ static void info_header_listener(ARegion *ar, wmNotifier *wmn)
if (wmn->data == ND_RENDER_RESULT)
ED_region_tag_redraw(ar);
break;
- case NC_SPACE:
+ case NC_SPACE:
if (wmn->data == ND_SPACE_INFO)
ED_region_tag_redraw(ar);
break;
diff --git a/source/blender/editors/space_info/textview.c b/source/blender/editors/space_info/textview.c
index 4ba196276da..f454b1dbe7d 100644
--- a/source/blender/editors/space_info/textview.c
+++ b/source/blender/editors/space_info/textview.c
@@ -36,8 +36,6 @@
#include "BLI_math.h"
#include "BLI_utildefines.h"
-
-
#include "BIF_gl.h"
#include "BIF_glutil.h"
@@ -66,8 +64,8 @@ typedef struct ConsoleDrawContext {
static void console_draw_sel(int sel[2], int xy[2], int str_len_draw, int cwidth, int lheight)
{
if (sel[0] <= str_len_draw && sel[1] >= 0) {
- int sta = MAX2(sel[0], 0);
- int end = MIN2(sel[1], str_len_draw);
+ int sta = max_ii(sel[0], 0);
+ int end = min_ii(sel[1], str_len_draw);
glEnable(GL_POLYGON_STIPPLE);
glPolygonStipple(stipple_halftone);
@@ -128,7 +126,7 @@ static int console_draw_string(ConsoleDrawContext *cdc, const char *str, int str
return 1;
}
- if (str_len > cdc->console_width) { /* wrap? */
+ if (tot_lines > 1) { /* wrap? */
const int initial_offset = ((tot_lines - 1) * cdc->console_width);
const char *line_stride = str + initial_offset; /* advance to the last line and draw it first */
diff --git a/source/blender/editors/space_logic/CMakeLists.txt b/source/blender/editors/space_logic/CMakeLists.txt
index 8859d1d8bfd..13e6f9484e8 100644
--- a/source/blender/editors/space_logic/CMakeLists.txt
+++ b/source/blender/editors/space_logic/CMakeLists.txt
@@ -48,4 +48,8 @@ if(WITH_GAMEENGINE)
add_definitions(-DWITH_GAMEENGINE)
endif()
+if(WITH_INTERNATIONAL)
+ add_definitions(-DWITH_INTERNATIONAL)
+endif()
+
blender_add_lib(bf_editor_space_logic "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/editors/space_logic/SConscript b/source/blender/editors/space_logic/SConscript
index 6beb3ecb48f..e63d88ea5de 100644
--- a/source/blender/editors/space_logic/SConscript
+++ b/source/blender/editors/space_logic/SConscript
@@ -3,7 +3,7 @@ Import ('env')
sources = env.Glob('*.c')
-incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
+incs = '../include ../../blenfont ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
incs += ' ../../windowmanager #/intern/guardedalloc #/extern/glew/include'
incs += ' ../../makesrna ../interface ../../blenloader'
@@ -12,4 +12,7 @@ defs = []
if env['WITH_BF_GAMEENGINE']:
defs.append('WITH_GAMEENGINE')
+if env['WITH_BF_INTERNATIONAL']:
+ defs.append('WITH_INTERNATIONAL')
+
env.BlenderLib ( 'bf_editors_space_game', sources, Split(incs), defs, libtype=['core'], priority=[120] )
diff --git a/source/blender/editors/space_logic/logic_buttons.c b/source/blender/editors/space_logic/logic_buttons.c
index abffb955405..e898a1baf74 100644
--- a/source/blender/editors/space_logic/logic_buttons.c
+++ b/source/blender/editors/space_logic/logic_buttons.c
@@ -52,8 +52,8 @@
static int logic_properties(bContext *C, wmOperator *UNUSED(op))
{
- ScrArea *sa= CTX_wm_area(C);
- ARegion *ar= logic_has_buttons_region(sa);
+ ScrArea *sa = CTX_wm_area(C);
+ ARegion *ar = logic_has_buttons_region(sa);
if (ar)
ED_region_toggle_hidden(C, ar);
@@ -84,10 +84,10 @@ static int cut_links_intersect(uiLinkLine *line, float mcoords[][2], int tot)
int i, b;
rcti rectlink;
- rectlink.xmin = (int)BLI_RCT_CENTER_X(&line->from->rect);
- rectlink.ymin = (int)BLI_RCT_CENTER_Y(&line->from->rect);
- rectlink.xmax = (int)BLI_RCT_CENTER_X(&line->to->rect);
- rectlink.ymax = (int)BLI_RCT_CENTER_Y(&line->to->rect);
+ rectlink.xmin = (int)BLI_rctf_cent_x(&line->from->rect);
+ rectlink.ymin = (int)BLI_rctf_cent_y(&line->from->rect);
+ rectlink.xmax = (int)BLI_rctf_cent_x(&line->to->rect);
+ rectlink.ymax = (int)BLI_rctf_cent_y(&line->to->rect);
if (ui_link_bezier_points(&rectlink, coord_array, LINK_RESOL)) {
for (i=0; i<tot-1; i++)
@@ -100,9 +100,9 @@ static int cut_links_intersect(uiLinkLine *line, float mcoords[][2], int tot)
static int cut_links_exec(bContext *C, wmOperator *op)
{
- ARegion *ar= CTX_wm_region(C);
+ ARegion *ar = CTX_wm_region(C);
float mcoords[256][2];
- int i= 0;
+ int i = 0;
RNA_BEGIN (op->ptr, itemptr, "path")
{
@@ -113,7 +113,7 @@ static int cut_links_exec(bContext *C, wmOperator *op)
(int)loc[0], (int)loc[1],
&mcoords[i][0], &mcoords[i][1]);
i++;
- if (i>= 256) break;
+ if (i >= 256) break;
}
RNA_END;
@@ -121,23 +121,23 @@ static int cut_links_exec(bContext *C, wmOperator *op)
uiBlock *block;
uiLinkLine *line, *nline;
uiBut *but;
- for (block= ar->uiblocks.first; block; block= block->next) {
- but= block->buttons.first;
+ for (block = ar->uiblocks.first; block; block = block->next) {
+ but = block->buttons.first;
while (but) {
if (but->type==LINK && but->link) {
- for (line= but->link->lines.first; line; line= nline) {
- nline= line->next;
+ for (line = but->link->lines.first; line; line = nline) {
+ nline = line->next;
if (cut_links_intersect(line, mcoords, i)) {
ui_delete_linkline(line, but);
}
}
}
- but= but->next;
+ but = but->next;
}
}
return OPERATOR_FINISHED;
- }
+ }
return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
}
@@ -159,7 +159,7 @@ void LOGIC_OT_links_cut(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
- prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
+ prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
/* internal */
RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
diff --git a/source/blender/editors/space_logic/logic_ops.c b/source/blender/editors/space_logic/logic_ops.c
index f2013e405e2..74be7c46d26 100644
--- a/source/blender/editors/space_logic/logic_ops.c
+++ b/source/blender/editors/space_logic/logic_ops.c
@@ -138,7 +138,7 @@ static bSensor *edit_sensor_property_get(bContext *C, wmOperator *op, Object **o
*ob = edit_object_property_get(C, op);
if (!*ob) return NULL;
- sens = BLI_findstring(&((*ob)->sensors), sensor_name, offsetof(bSensor, name));
+ sens = BLI_findstring(&((*ob)->sensors), sensor_name, offsetof(bSensor, name));
return sens;
}
@@ -177,7 +177,7 @@ static bController *edit_controller_property_get(bContext *C, wmOperator *op, Ob
*ob = edit_object_property_get(C, op);
if (!*ob) return NULL;
- cont = BLI_findstring(&((*ob)->controllers), controller_name, offsetof(bController, name));
+ cont = BLI_findstring(&((*ob)->controllers), controller_name, offsetof(bController, name));
return cont;
}
@@ -216,7 +216,7 @@ static bActuator *edit_actuator_property_get(bContext *C, wmOperator *op, Object
*ob = edit_object_property_get(C, op);
if (!*ob) return NULL;
- act = BLI_findstring(&((*ob)->actuators), actuator_name, offsetof(bActuator, name));
+ act = BLI_findstring(&((*ob)->actuators), actuator_name, offsetof(bActuator, name));
return act;
}
diff --git a/source/blender/editors/space_logic/logic_window.c b/source/blender/editors/space_logic/logic_window.c
index 6ffac1dcd34..5a8a7cef119 100644
--- a/source/blender/editors/space_logic/logic_window.c
+++ b/source/blender/editors/space_logic/logic_window.c
@@ -56,6 +56,7 @@
#include "BKE_library.h"
#include "BKE_main.h"
#include "BKE_sca.h"
+#include "BKE_screen.h"
#include "ED_util.h"
@@ -63,7 +64,10 @@
#include "BIF_gl.h"
+#include "BLF_translation.h"
+
#include "UI_interface.h"
+#include "UI_view2d.h"
#include "RNA_access.h"
@@ -72,10 +76,7 @@
#include "logic_intern.h"
-
-#define MAX_RENDER_PASS 100
#define B_REDR 1
-#define B_IDNAME 2
#define B_ADD_SENS 2703
#define B_CHANGE_SENS 2704
@@ -91,7 +92,6 @@
#define B_SOUNDACT_BROWSE 2712
-#define B_SETSECTOR 2713
#define B_SETPROP 2714
#define B_SETACTOR 2715
#define B_SETMAINACTOR 2716
@@ -106,8 +106,8 @@ static int vergname(const void *v1, const void *v2)
{
char **x1, **x2;
- x1= (char **)v1;
- x2= (char **)v2;
+ x1 = (char **)v1;
+ x2 = (char **)v2;
return BLI_natstrcmp(*x1, *x2);
}
@@ -138,7 +138,7 @@ void make_unique_prop_names(bContext *C, char *str)
propcount+= BLI_countlist(&ob->sensors);
propcount+= BLI_countlist(&ob->controllers);
propcount+= BLI_countlist(&ob->actuators);
- }
+ }
if (propcount==0) {
if (idar) MEM_freeN(idar);
return;
@@ -153,22 +153,22 @@ void make_unique_prop_names(bContext *C, char *str)
ob= (Object *)idar[a];
prop= ob->prop.first;
while (prop) {
- names[nr++]= prop->name;
+ names[nr++] = prop->name;
prop= prop->next;
}
sens= ob->sensors.first;
while (sens) {
- names[nr++]= sens->name;
+ names[nr++] = sens->name;
sens= sens->next;
}
cont= ob->controllers.first;
while (cont) {
- names[nr++]= cont->name;
+ names[nr++] = cont->name;
cont= cont->next;
}
act= ob->actuators.first;
while (act) {
- names[nr++]= act->name;
+ names[nr++] = act->name;
act= act->next;
}
}
@@ -187,178 +187,6 @@ void make_unique_prop_names(bContext *C, char *str)
MEM_freeN(names);
}
-static void make_unique_prop_names_cb(bContext *C, void *strv, void *UNUSED(redraw_view3d_flagv))
-{
- char *str= strv;
-// int redraw_view3d_flag= GET_INT_FROM_POINTER(redraw_view3d_flagv);
-
- make_unique_prop_names(C, str);
-}
-
-
-static void old_sca_move_sensor(bContext *C, void *datav, void *move_up)
-{
- /* deprecated, no longer using it (moved to sca.c) */
- Scene *scene= CTX_data_scene(C);
- bSensor *sens_to_delete= datav;
- int val;
- Base *base;
- bSensor *sens, *tmp;
-
- // val= pupmenu("Move up%x1|Move down %x2");
- val = move_up ? 1:2;
-
- if (val>0) {
- /* now find out which object has this ... */
- base= FIRSTBASE;
- while (base) {
-
- sens= base->object->sensors.first;
- while (sens) {
- if (sens == sens_to_delete) break;
- sens= sens->next;
- }
-
- if (sens) {
- if ( val==1 && sens->prev) {
- for (tmp=sens->prev; tmp; tmp=tmp->prev) {
- if (tmp->flag & SENS_VISIBLE)
- break;
- }
- if (tmp) {
- BLI_remlink(&base->object->sensors, sens);
- BLI_insertlinkbefore(&base->object->sensors, tmp, sens);
- }
- }
- else if ( val==2 && sens->next) {
- for (tmp=sens->next; tmp; tmp=tmp->next) {
- if (tmp->flag & SENS_VISIBLE)
- break;
- }
- if (tmp) {
- BLI_remlink(&base->object->sensors, sens);
- BLI_insertlink(&base->object->sensors, tmp, sens);
- }
- }
- ED_undo_push(C, "Move sensor");
- break;
- }
-
- base= base->next;
- }
- }
-}
-
-static void old_sca_move_controller(bContext *C, void *datav, void *move_up)
-{
- /* deprecated, no longer using it (moved to sca.c) */
- Scene *scene= CTX_data_scene(C);
- bController *controller_to_del= datav;
- int val;
- Base *base;
- bController *cont, *tmp;
-
- //val= pupmenu("Move up%x1|Move down %x2");
- val = move_up ? 1:2;
-
- if (val>0) {
- /* now find out which object has this ... */
- base= FIRSTBASE;
- while (base) {
-
- cont= base->object->controllers.first;
- while (cont) {
- if (cont == controller_to_del) break;
- cont= cont->next;
- }
-
- if (cont) {
- if ( val==1 && cont->prev) {
- /* locate the controller that has the same state mask but is earlier in the list */
- tmp = cont->prev;
- while (tmp) {
- if (tmp->state_mask & cont->state_mask)
- break;
- tmp = tmp->prev;
- }
- if (tmp) {
- BLI_remlink(&base->object->controllers, cont);
- BLI_insertlinkbefore(&base->object->controllers, tmp, cont);
- }
- }
- else if ( val==2 && cont->next) {
- tmp = cont->next;
- while (tmp) {
- if (tmp->state_mask & cont->state_mask)
- break;
- tmp = tmp->next;
- }
- BLI_remlink(&base->object->controllers, cont);
- BLI_insertlink(&base->object->controllers, tmp, cont);
- }
- ED_undo_push(C, "Move controller");
- break;
- }
-
- base= base->next;
- }
- }
-}
-
-static void old_sca_move_actuator(bContext *C, void *datav, void *move_up)
-{
- /* deprecated, no longer using it (moved to sca.c) */
- Scene *scene= CTX_data_scene(C);
- bActuator *actuator_to_move= datav;
- int val;
- Base *base;
- bActuator *act, *tmp;
-
- //val= pupmenu("Move up%x1|Move down %x2");
- val = move_up ? 1:2;
-
- if (val>0) {
- /* now find out which object has this ... */
- base= FIRSTBASE;
- while (base) {
-
- act= base->object->actuators.first;
- while (act) {
- if (act == actuator_to_move) break;
- act= act->next;
- }
-
- if (act) {
- if ( val==1 && act->prev) {
- /* locate the first visible actuators before this one */
- for (tmp = act->prev; tmp; tmp=tmp->prev) {
- if (tmp->flag & ACT_VISIBLE)
- break;
- }
- if (tmp) {
- BLI_remlink(&base->object->actuators, act);
- BLI_insertlinkbefore(&base->object->actuators, tmp, act);
- }
- }
- else if ( val==2 && act->next) {
- for (tmp=act->next; tmp; tmp=tmp->next) {
- if (tmp->flag & ACT_VISIBLE)
- break;
- }
- if (tmp) {
- BLI_remlink(&base->object->actuators, act);
- BLI_insertlink(&base->object->actuators, tmp, act);
- }
- }
- ED_undo_push(C, "Move actuator");
- break;
- }
-
- base= base->next;
- }
- }
-}
-
static void do_logic_buts(bContext *C, void *UNUSED(arg), int event)
{
Main *bmain= CTX_data_main(C);
@@ -631,14 +459,6 @@ static const char *sensor_name(int type)
return "unknown";
}
-static const char *sensor_pup(void)
-{
- /* the number needs to match defines in DNA_sensor_types.h */
- return "Sensors %t|Always %x0|Delay %x13|Keyboard %x3|Mouse %x5|"
- "Touch %x1|Collision %x6|Near %x2|Radar %x7|"
- "Property %x4|Random %x8|Ray %x9|Message %x10|Joystick %x11|Actuator %x12|Armature %x14";
-}
-
static const char *controller_name(int type)
{
switch (type) {
@@ -662,11 +482,6 @@ static const char *controller_name(int type)
return "unknown";
}
-static const char *controller_pup(void)
-{
- return "Controllers %t|AND %x0|OR %x1|XOR %x6|NAND %x4|NOR %x5|XNOR %x7|Expression %x2|Python %x3";
-}
-
static const char *actuator_name(int type)
{
switch (type) {
@@ -713,41 +528,11 @@ static const char *actuator_name(int type)
case ACT_ARMATURE:
return "Armature";
case ACT_STEERING:
- return "Steering";
+ return "Steering";
}
return "unknown";
}
-
-
-
-static const char *actuator_pup(Object *owner)
-{
- switch (owner->type) {
- case OB_ARMATURE:
- return ("Actuators %t|Action %x15|Armature %x23|Motion %x0|Constraint %x9|Ipo %x1"
- "|Camera %x3|Sound %x5|Property %x6|Edit Object %x10"
- "|Scene %x11|Random %x13|Message %x14|Game %x17"
- "|Visibility %x18|2D Filter %x19|Parent %x20|State %x22");
- break;
-
- case OB_MESH:
- return ("Actuators %t|Shape Action %x21|Motion %x0|Constraint %x9|Ipo %x1"
- "|Camera %x3|Sound %x5|Property %x6|Edit Object %x10"
- "|Scene %x11|Random %x13|Message %x14|Game %x17"
- "|Visibility %x18|2D Filter %x19|Parent %x20|State %x22");
- break;
-
- default:
- return ("Actuators %t|Motion %x0|Constraint %x9|Ipo %x1"
- "|Camera %x3|Sound %x5|Property %x6|Edit Object %x10"
- "|Scene %x11|Random %x13|Message %x14|Game %x17"
- "|Visibility %x18|2D Filter %x19|Parent %x20|State %x22");
- }
-}
-
-
-
static void set_sca_ob(Object *ob)
{
bController *cont;
@@ -897,7 +682,7 @@ static ID **get_selected_and_linked_obs(bContext *C, short *count, short scavisf
ob= ob->id.next;
}
}
- }
+ }
/* now we count */
ob= bmain->object.first;
@@ -906,8 +691,8 @@ static ID **get_selected_and_linked_obs(bContext *C, short *count, short scavisf
ob= ob->id.next;
}
- if (*count==0) return NULL;
- if (*count>24) *count= 24; /* temporal */
+ if (*count == 0) return NULL;
+ if (*count > 24) *count = 24; /* temporal */
idar= MEM_callocN((*count)*sizeof(void *), "idar");
@@ -916,16 +701,16 @@ static ID **get_selected_and_linked_obs(bContext *C, short *count, short scavisf
/* make the active object always the first one of the list */
if (obact) {
- idar[0]= (ID *)obact;
+ idar[0] = (ID *)obact;
nr++;
}
while (ob) {
if ((ob->scavisflag) && (ob != obact)) {
- idar[nr]= (ID *)ob;
+ idar[nr] = (ID *)ob;
nr++;
}
- if (nr>=24) break;
+ if (nr >= 24) break;
ob= ob->id.next;
}
@@ -935,151 +720,6 @@ static ID **get_selected_and_linked_obs(bContext *C, short *count, short scavisf
return idar;
}
-
-static int get_col_sensor(int type)
-{
- /* XXX themecolors not here */
-
- switch (type) {
- case SENS_ALWAYS: return TH_PANEL;
- case SENS_DELAY: return TH_PANEL;
- case SENS_TOUCH: return TH_PANEL;
- case SENS_COLLISION: return TH_PANEL;
- case SENS_NEAR: return TH_PANEL;
- case SENS_KEYBOARD: return TH_PANEL;
- case SENS_PROPERTY: return TH_PANEL;
- case SENS_ARMATURE: return TH_PANEL;
- case SENS_ACTUATOR: return TH_PANEL;
- case SENS_MOUSE: return TH_PANEL;
- case SENS_RADAR: return TH_PANEL;
- case SENS_RANDOM: return TH_PANEL;
- case SENS_RAY: return TH_PANEL;
- case SENS_MESSAGE: return TH_PANEL;
- case SENS_JOYSTICK: return TH_PANEL;
- default: return TH_PANEL;
- }
-}
-static void set_col_sensor(int type, int medium)
-{
- int col= get_col_sensor(type);
- UI_ThemeColorShade(col, medium?30:0);
-}
-
-
-static void verify_logicbutton_func(bContext *UNUSED(C), void *data1, void *data2)
-{
- bSensor *sens= (bSensor*)data1;
-
- if (sens->level && sens->tap) {
- if (data2 == &(sens->level))
- sens->tap= 0;
- else
- sens->level= 0;
- }
-}
-
-static void test_scriptpoin_but(struct bContext *C, const char *name, ID **idpp)
-{
- *idpp= BLI_findstring(&CTX_data_main(C)->text, name, offsetof(ID, name) + 2);
-}
-
-static void test_actionpoin_but(struct bContext *C, const char *name, ID **idpp)
-{
- *idpp= BLI_findstring(&CTX_data_main(C)->action, name, offsetof(ID, name) + 2);
- if (*idpp)
- id_us_plus(*idpp);
-}
-
-
-static void test_obpoin_but(struct bContext *C, const char *name, ID **idpp)
-{
- *idpp= BLI_findstring(&CTX_data_main(C)->object, name, offsetof(ID, name) + 2);
- if (*idpp)
- id_lib_extern(*idpp); /* checks lib data, sets correct flag for saving then */
-}
-
-static void test_meshpoin_but(struct bContext *C, const char *name, ID **idpp)
-{
- *idpp= BLI_findstring(&CTX_data_main(C)->mesh, name, offsetof(ID, name) + 2);
- if (*idpp)
- id_us_plus(*idpp);
-}
-
-static void test_matpoin_but(struct bContext *C, const char *name, ID **idpp)
-{
- *idpp= BLI_findstring(&CTX_data_main(C)->mat, name, offsetof(ID, name) + 2);
- if (*idpp)
- id_us_plus(*idpp);
-}
-
-static void test_scenepoin_but(struct bContext *C, const char *name, ID **idpp)
-{
- *idpp= BLI_findstring(&CTX_data_main(C)->scene, name, offsetof(ID, name) + 2);
- if (*idpp)
- id_us_plus(*idpp);
-}
-
-static void test_keyboard_event(struct bContext *UNUSED(C), void *arg_ks, void *UNUSED(arg))
-{
- bKeyboardSensor *ks= (bKeyboardSensor*)arg_ks;
-
- if (!ISKEYBOARD(ks->key))
- ks->key= 0;
- if (!ISKEYBOARD(ks->qual))
- ks->qual= 0;
- if (!ISKEYBOARD(ks->qual2))
- ks->qual2= 0;
-}
-
-/**
- * Draws a toggle for pulse mode, a frequency field and a toggle to invert
- * the value of this sensor. Operates on the shared data block of sensors.
- */
-static void draw_default_sensor_header(bSensor *sens,
- uiBlock *block,
- short x,
- short y,
- short w)
-{
- uiBut *but;
-
- /* Pulsing and frequency */
- uiBlockBeginAlign(block);
- uiDefIconButBitS(block, TOG, SENS_PULSE_REPEAT, 1, ICON_DOTSUP,
- (short)(x + 10 + 0.0 * (w - 20)), (short)(y - 21), (short)(0.1 * (w - 20)), 19,
- &sens->pulse, 0.0, 0.0, 0, 0,
- "Activate TRUE level triggering (pulse mode)");
-
- uiDefIconButBitS(block, TOG, SENS_NEG_PULSE_MODE, 1, ICON_DOTSDOWN,
- (short)(x + 10 + 0.1 * (w-20)), (short)(y - 21), (short)(0.1 * (w-20)), 19,
- &sens->pulse, 0.0, 0.0, 0, 0,
- "Activate FALSE level triggering (pulse mode)");
- uiDefButS(block, NUM, 1, "f:",
- (short)(x + 10 + 0.2 * (w-20)), (short)(y - 21), (short)(0.275 * (w-20)), 19,
- &sens->freq, 0.0, 10000.0, 0, 0,
- "Delay between repeated pulses (in logic tics, 0 = no delay)");
- uiBlockEndAlign(block);
-
- /* value or shift? */
- uiBlockBeginAlign(block);
- but = uiDefButS(block, TOG, 1, "Level",
- (short)(x + 10 + 0.5 * (w-20)), (short)(y - 21), (short)(0.20 * (w-20)), 19,
- &sens->level, 0.0, 0.0, 0, 0,
- "Level detector, trigger controllers of new states (only applicable upon logic state transition)");
- uiButSetFunc(but, verify_logicbutton_func, sens, &(sens->level));
- but = uiDefButS(block, TOG, 1, "Tap",
- (short)(x + 10 + 0.702 * (w-20)), (short)(y - 21), (short)(0.12 * (w-20)), 19,
- &sens->tap, 0.0, 0.0, 0, 0,
- "Trigger controllers only for an instant, even while the sensor remains true");
- uiButSetFunc(but, verify_logicbutton_func, sens, &(sens->tap));
- uiBlockEndAlign(block);
-
- uiDefButS(block, TOG, 1, "Inv",
- (short)(x + 10 + 0.85 * (w-20)), (short)(y - 21), (short)(0.15 * (w-20)), 19,
- &sens->invert, 0.0, 0.0, 0, 0,
- "Invert the level (output) of this sensor");
-}
-
static void get_armature_bone_constraint(Object *ob, const char *posechannel, const char *constraint_name, bConstraint **constraint)
{
/* check that bone exist in the active object */
@@ -1094,1848 +734,6 @@ static void get_armature_bone_constraint(Object *ob, const char *posechannel, co
}
/* didn't find any */
}
-static void check_armature_bone_constraint(Object *ob, char *posechannel, char *constraint)
-{
- /* check that bone exist in the active object */
- if (ob->type == OB_ARMATURE && ob->pose) {
- bPoseChannel *pchan;
- bPose *pose = ob->pose;
- for (pchan=pose->chanbase.first; pchan; pchan=pchan->next) {
- if (!strcmp(pchan->name, posechannel)) {
- /* found it, now look for constraint channel */
- bConstraint *con;
- for (con=pchan->constraints.first; con; con=con->next) {
- if (!strcmp(con->name, constraint)) {
- /* found it, all ok */
- return;
- }
- }
- /* didn't find constraint, make empty */
- constraint[0] = 0;
- return;
- }
- }
- }
- /* didn't find any */
- posechannel[0] = 0;
- constraint[0] = 0;
-}
-
-static void check_armature_sensor(bContext *C, void *arg1_but, void *arg2_sens)
-{
- bArmatureSensor *sens = arg2_sens;
- uiBut *but = arg1_but;
- Object *ob= CTX_data_active_object(C);
-
- /* check that bone exist in the active object */
- but->retval = B_REDR;
- check_armature_bone_constraint(ob, sens->posechannel, sens->constraint);
-}
-
-static short draw_sensorbuttons(Object *ob, bSensor *sens, uiBlock *block, short xco, short yco, short width)
-{
- bNearSensor *ns = NULL;
- bTouchSensor *ts = NULL;
- bKeyboardSensor *ks = NULL;
- bPropertySensor *ps = NULL;
- bArmatureSensor *arm = NULL;
- bMouseSensor *ms = NULL;
- bCollisionSensor *cs = NULL;
- bRadarSensor *rs = NULL;
- bRandomSensor *randomSensor = NULL;
- bRaySensor *raySens = NULL;
- bMessageSensor *mes = NULL;
- bJoystickSensor *joy = NULL;
- bActuatorSensor *as = NULL;
- bDelaySensor *ds = NULL;
- uiBut *but;
- short ysize;
- const char *str;
-
- /* yco is at the top of the rect, draw downwards */
-
- set_col_sensor(sens->type, 0);
-
- switch (sens->type) {
- case SENS_ALWAYS:
- {
- ysize= 24;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- draw_default_sensor_header(sens, block, xco, yco, width);
-
- yco-= ysize;
-
- break;
- }
- case SENS_TOUCH:
- {
- ysize= 48;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- draw_default_sensor_header(sens, block, xco, yco, width);
-
- ts= sens->data;
-
- // uiDefBut(block, TEX, 1, "Property:", xco, yco-22, width, 19, &ts->name, 0, MAX_NAME, 0, 0, "Only look for Objects with this property");
- uiDefIDPoinBut(block, test_matpoin_but, ID_MA, 1, "MA:", (short)(xco + 10), (short)(yco-44), (short)(width - 20), 19, &ts->ma, "Only look for floors with this Material");
- // uiDefButF(block, NUM, 1, "Margin:", xco+width/2, yco-44, width/2, 19, &ts->dist, 0.0, 10.0, 100, 0, "Extra margin (distance) for larger sensitivity");
- yco-= ysize;
- break;
- }
- case SENS_COLLISION:
- {
- ysize= 48;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- draw_default_sensor_header(sens, block, xco, yco, width);
- cs= sens->data;
-
- /* The collision sensor will become a generic collision (i.e. it */
- /* absorb the old touch sensor). */
-
- uiDefButBitS(block, TOG, SENS_COLLISION_PULSE, B_REDR, "Pulse", (short)(xco + 10), (short)(yco - 44),
- (short)(0.20 * (width-20)), 19, &cs->mode, 0.0, 0.0, 0, 0,
- "Changes to the set of colliding objects generated pulses");
-
- uiDefButBitS(block, TOG, SENS_COLLISION_MATERIAL, B_REDR, "M/P", (short)(xco + 10 + (0.20 * (width-20))), (short)(yco - 44),
- (short)(0.20 * (width-20)), 19, &cs->mode, 0.0, 0.0, 0, 0,
- "Toggle collision on material or property");
-
- if (cs->mode & SENS_COLLISION_MATERIAL) {
- uiDefBut(block, TEX, 1, "Material:", (short)(xco + 10 + 0.40 * (width-20)),
- (short)(yco-44), (short)(0.6*(width-20)), 19, &cs->materialName, 0, MAX_NAME, 0, 0,
- "Only look for Objects with this material");
- }
- else {
- uiDefBut(block, TEX, 1, "Property:", (short)(xco + 10 + 0.40 * (width-20)), (short)(yco-44),
- (short)(0.6*(width-20)), 19, &cs->name, 0, MAX_NAME, 0, 0,
- "Only look for Objects with this property");
- }
-
- /* uiDefButS(block, NUM, 1, "Damp:", xco+10+width-90, yco-24, 70, 19, &cs->damp, 0, 250, 0, 0, "For 'damp' time don't detect another collision"); */
-
- yco-= ysize;
- break;
- }
- case SENS_NEAR:
- {
- ysize= 72;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- draw_default_sensor_header(sens, block, xco, yco, width);
- ns= sens->data;
-
- uiDefBut(block, TEX, 1, "Property:", (short)(10+xco), (short)(yco-44), (short)(width-20), 19,
- &ns->name, 0, MAX_NAME, 0, 0, "Only look for Objects with this property");
- uiDefButF(block, NUM, 1, "Dist", (short)(10+xco), (short)(yco-68), (short)((width-22)/2), 19,
- &ns->dist, 0.0, 1000.0, 1000, 0, "Trigger distance");
- uiDefButF(block, NUM, 1, "Reset", (short)(10+xco+(width-22)/2), (short)(yco-68), (short)((width-22)/2), 19,
- &ns->resetdist, 0.0, 1000.0, 1000, 0, "Reset distance");
- yco-= ysize;
- break;
- }
- case SENS_RADAR:
- {
- ysize= 72;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- draw_default_sensor_header(sens, block, xco, yco, width);
-
- rs= sens->data;
-
- uiDefBut(block, TEX, 1, "Prop:",
- (short)(10+xco), (short)(yco-44), (short)(0.7 * (width-20)), 19,
- &rs->name, 0, MAX_NAME, 0, 0,
- "Only look for Objects with this property");
-
- str = "Type %t|+X axis %x0|+Y axis %x1|+Z axis %x2|-X axis %x3|-Y axis %x4|-Z axis %x5";
- uiDefButS(block, MENU, B_REDR, str,
- (short)(10+xco+0.7 * (width-20)), (short)(yco-44), (short)(0.3 * (width-22)), 19,
- &rs->axis, 2.0, 31, 0, 0,
- "Specify along which axis the radar cone is cast");
-
- uiDefButF(block, NUM, 1, "Ang:",
- (short)(10+xco), (short)(yco-68), (short)((width-20)/2), 19,
- &rs->angle, 0.0, 179.9, 10, 0,
- "Opening angle of the radar cone");
- uiDefButF(block, NUM, 1, "Dist:",
- (short)(xco+10 + (width-20)/2), (short)(yco-68), (short)((width-20)/2), 19,
- &rs->range, 0.01, 10000.0, 100, 0,
- "Depth of the radar cone");
- yco-= ysize;
- break;
- }
- case SENS_KEYBOARD:
- {
- ks= sens->data;
-
- /* 5 lines: 120 height */
- ysize= (ks->type&1) ? 96:120;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- /* header line */
- draw_default_sensor_header(sens, block, xco, yco, width);
-
- /* part of line 1 */
- uiDefBut(block, LABEL, 0, "Key", xco, yco-44, 40, 19, NULL, 0, 0, 0, 0, "");
- uiDefButBitS(block, TOG, 1, B_REDR, "All keys", xco+40+(width/2), yco-44, (width/2)-50, 19,
- &ks->type, 0, 0, 0, 0, "");
-
-
- if ((ks->type&1)==0) { /* is All Keys option off? */
- /* line 2: hotkey and allkeys toggle */
- but = uiDefKeyevtButS(block, 0, "", xco+40, yco-44, (width)/2, 19, &ks->key, "Key code");
- uiButSetFunc(but, test_keyboard_event, ks, NULL);
-
- /* line 3: two key modifyers (qual1, qual2) */
- uiDefBut(block, LABEL, 0, "Hold", xco, yco-68, 40, 19, NULL, 0, 0, 0, 0, "");
- but = uiDefKeyevtButS(block, 0, "", xco+40, yco-68, (width-50)/2, 19, &ks->qual, "Modifier key code");
- uiButSetFunc(but, test_keyboard_event, ks, NULL);
- but = uiDefKeyevtButS(block, 0, "", xco+40+(width-50)/2, yco-68, (width-50)/2, 19, &ks->qual2, "Second Modifier key code");
- uiButSetFunc(but, test_keyboard_event, ks, NULL);
- }
-
- /* line 4: toggle property for string logging mode */
- uiDefBut(block, TEX, 1, "LogToggle: ",
- xco+10, yco-((ks->type&1) ? 68:92), (width-20), 19,
- ks->toggleName, 0, MAX_NAME, 0, 0,
- "Property that indicates whether to log "
- "keystrokes as a string");
-
- /* line 5: target property for string logging mode */
- uiDefBut(block, TEX, 1, "Target: ",
- xco+10, yco-((ks->type&1) ? 92:116), (width-20), 19,
- ks->targetName, 0, MAX_NAME, 0, 0,
- "Property that receives the keystrokes in case "
- "a string is logged");
-
- yco-= ysize;
- break;
- }
- case SENS_PROPERTY:
- {
- ysize= 96;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize,
- (float)xco+width, (float)yco, 1);
-
- draw_default_sensor_header(sens, block, xco, yco, width);
- ps= sens->data;
-
- str= "Type %t|Equal %x0|Not Equal %x1|Interval %x2|Changed %x3";
- /* str= "Type %t|Equal %x0|Not Equal %x1"; */
- uiDefButI(block, MENU, B_REDR, str, xco+30, yco-44, width-60, 19,
- &ps->type, 0, 31, 0, 0, "Type");
-
- if (ps->type != SENS_PROP_EXPRESSION) {
- uiDefBut(block, TEX, 1, "Prop: ", xco+30, yco-68, width-60, 19,
- ps->name, 0, MAX_NAME, 0, 0, "Property name");
- }
-
- if (ps->type == SENS_PROP_INTERVAL) {
- uiDefBut(block, TEX, 1, "Min: ", xco, yco-92, width/2, 19,
- ps->value, 0, MAX_NAME, 0, 0, "check for min value");
- uiDefBut(block, TEX, 1, "Max: ", xco+width/2, yco-92, width/2, 19,
- ps->maxvalue, 0, MAX_NAME, 0, 0, "check for max value");
- }
- else if (ps->type == SENS_PROP_CHANGED) {
- /* pass */
- }
- else {
- uiDefBut(block, TEX, 1, "Value: ", xco+30, yco-92, width-60, 19,
- ps->value, 0, MAX_NAME, 0, 0, "check for value");
- }
-
- yco-= ysize;
- break;
- }
- case SENS_ARMATURE:
- {
- ysize= 70;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize,
- (float)xco+width, (float)yco, 1);
-
- draw_default_sensor_header(sens, block, xco, yco, width);
- arm= sens->data;
-
- if (ob->type == OB_ARMATURE) {
- uiBlockBeginAlign(block);
- but = uiDefBut(block, TEX, 1, "Bone: ",
- (xco+10), (yco-44), (width-20)/2, 19,
- arm->posechannel, 0, MAX_NAME, 0, 0,
- "Bone on which you want to check a constraint");
- uiButSetFunc(but, check_armature_sensor, but, arm);
- but = uiDefBut(block, TEX, 1, "Cons: ",
- (xco+10)+(width-20)/2, (yco-44), (width-20)/2, 19,
- arm->constraint, 0, MAX_NAME, 0, 0,
- "Name of the constraint you want to control");
- uiButSetFunc(but, check_armature_sensor, but, arm);
- uiBlockEndAlign(block);
-
- str= "Type %t|State changed %x0|Lin error below %x1|Lin error above %x2|Rot error below %x3|Rot error above %x4";
-
- uiDefButI(block, MENU, B_REDR, str, xco+10, yco-66, 0.4*(width-20), 19,
- &arm->type, 0, 31, 0, 0, "Type");
-
- if (arm->type != SENS_ARM_STATE_CHANGED) {
- uiDefButF(block, NUM, 1, "Value: ", xco+10+0.4*(width-20), yco-66, 0.6*(width-20), 19,
- &arm->value, -10000.0, 10000.0, 100, 0, "Test the error against this value");
- }
- }
- yco-= ysize;
- break;
- }
- case SENS_ACTUATOR:
- {
- ysize= 48;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize,
- (float)xco+width, (float)yco, 1);
-
- draw_default_sensor_header(sens, block, xco, yco, width);
- as= sens->data;
-
- uiDefBut(block, TEX, 1, "Act: ", xco+30, yco-44, width-60, 19,
- as->name, 0, MAX_NAME, 0, 0, "Actuator name, actuator active state modifications will be detected");
- yco-= ysize;
- break;
- }
- case SENS_DELAY:
- {
- ysize= 48;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize,
- (float)xco+width, (float)yco, 1);
-
- draw_default_sensor_header(sens, block, xco, yco, width);
- ds = sens->data;
-
- uiDefButS(block, NUM, 0, "Delay", (short)(10+xco), (short)(yco-44), (short)((width-22)*0.4+10), 19,
- &ds->delay, 0.0, 5000.0, 0, 0, "Delay in number of logic tics before the positive trigger (default 60 per second)");
- uiDefButS(block, NUM, 0, "Dur", (short)(10+xco+(width-22)*0.4+10), (short)(yco-44), (short)((width-22)*0.4-10), 19,
- &ds->duration, 0.0, 5000.0, 0, 0, "If >0, delay in number of logic tics before the negative trigger following the positive trigger");
- uiDefButBitS(block, TOG, SENS_DELAY_REPEAT, 0, "REP", (short)(xco + 10 + (width-22)*0.8), (short)(yco - 44),
- (short)(0.20 * (width-22)), 19, &ds->flag, 0.0, 0.0, 0, 0,
- "Toggle repeat option. If selected, the sensor restarts after Delay+Dur logic tics");
- yco-= ysize;
- break;
- }
- case SENS_MOUSE:
- {
- ms= sens->data;
- /* Two lines: 48 pixels high. */
- ysize = 48;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- /* line 1: header */
- draw_default_sensor_header(sens, block, xco, yco, width);
-
- /* Line 2: type selection. The number are a bit mangled to get
- * proper compatibility with older .blend files. */
-
- /* Any sensor type default is 0 but the ms enum starts in 1.
- * Therefore the mouse sensor is initialized to 1 in sca.c */
- str= "Type %t|Left button %x1|Middle button %x2|"
- "Right button %x4|Wheel Up %x5|Wheel Down %x6|Movement %x8|Mouse over %x16|Mouse over any%x32";
- uiDefButS(block, MENU, B_REDR, str, xco+10, yco-44, (width*0.8f)-20, 19,
- &ms->type, 0, 31, 0, 0,
- "Specify the type of event this mouse sensor should trigger on");
-
- if (ms->type==32) {
- uiDefButBitS(block, TOG, SENS_MOUSE_FOCUS_PULSE, B_REDR, "Pulse", (short)(xco + 10) + (width*0.8f)-20, (short)(yco - 44),
- (short)(0.20 * (width-20)), 19, &ms->flag, 0.0, 0.0, 0, 0,
- "Moving the mouse over a different object generates a pulse");
- }
-
- yco-= ysize;
- break;
- }
- case SENS_RANDOM:
- {
- ysize = 48;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- draw_default_sensor_header(sens, block, xco, yco, width);
- randomSensor = sens->data;
- /* some files were wrongly written, avoid crash now */
- if (randomSensor) {
- uiDefButI(block, NUM, 1, "Seed: ", xco+10, yco-44, (width-20), 19,
- &randomSensor->seed, 0, 1000, 0, 0,
- "Initial seed of the generator. (Choose 0 for not random)");
- }
- yco-= ysize;
- break;
- }
- case SENS_RAY:
- {
- ysize = 72;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- draw_default_sensor_header(sens, block, xco, yco, width);
- raySens = sens->data;
-
- /* 1. property or material */
- uiDefButBitS(block, TOG, SENS_COLLISION_MATERIAL, B_REDR, "M/P",
- xco + 10, yco - 44, 0.20 * (width-20), 19,
- &raySens->mode, 0.0, 0.0, 0, 0,
- "Toggle collision on material or property");
-
- if (raySens->mode & SENS_COLLISION_MATERIAL) {
- uiDefBut(block, TEX, 1, "Material:", xco + 10 + 0.20 * (width-20), yco-44, 0.8*(width-20), 19,
- &raySens->matname, 0, MAX_NAME, 0, 0,
- "Only look for Objects with this material");
- }
- else {
- uiDefBut(block, TEX, 1, "Property:", xco + 10 + 0.20 * (width-20), yco-44, 0.8*(width-20), 19,
- &raySens->propname, 0, MAX_NAME, 0, 0,
- "Only look for Objects with this property");
- }
-
- /* X-Ray option */
- uiDefButBitS(block, TOG, SENS_RAY_XRAY, 1, "X",
- xco + 10, yco - 68, 0.10 * (width-20), 19,
- &raySens->mode, 0.0, 0.0, 0, 0,
- "Toggle X-Ray option (see through objects that don't have the property)");
- /* 2. sensing range */
- uiDefButF(block, NUM, 1, "Range", xco+10 + 0.10 * (width-20), yco-68, 0.5 * (width-20), 19,
- &raySens->range, 0.01, 10000.0, 100, 0,
- "Sense objects no farther than this distance");
-
- /* 3. axis choice */
- str = "Type %t|+ X axis %x1|+ Y axis %x0|+ Z axis %x2|- X axis %x3|- Y axis %x4|- Z axis %x5";
- uiDefButI(block, MENU, B_REDR, str, xco+10 + 0.6 * (width-20), yco-68, 0.4 * (width-20), 19,
- &raySens->axisflag, 2.0, 31, 0, 0,
- "Specify along which axis the ray is cast");
-
- yco-= ysize;
- break;
- }
- case SENS_MESSAGE:
- {
- mes = sens->data;
- ysize = 2 * 24; /* total number of lines * 24 pixels/line */
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize,
- (float)xco+width, (float)yco, 1);
-
- /* line 1: header line */
- draw_default_sensor_header(sens, block, xco, yco, width);
-
- /* line 2: Subject filter */
- uiDefBut(block, TEX, 1, "Subject: ",
- (xco+10), (yco-44), (width-20), 19,
- mes->subject, 0, MAX_NAME, 0, 0,
- "Optional subject filter: only accept messages with this subject"
- ", or empty for all");
-
- yco -= ysize;
- break;
- }
- case SENS_JOYSTICK:
- {
-
- ysize = 72;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- /* line 1: header */
- draw_default_sensor_header(sens, block, xco, yco, width);
-
- joy= sens->data;
-
- uiDefButC(block, NUM, 1, "Index:", xco+10, yco-44, 0.33 * (width-20), 19,
- &joy->joyindex, 0, SENS_JOY_MAXINDEX-1, 100, 0,
- "Specify which joystick to use");
-
- str= "Type %t|Button %x0|Axis %x1|Single Axis %x3|Hat%x2";
- uiDefButC(block, MENU, B_REDR, str, xco+87, yco-44, 0.26 * (width-20), 19,
- &joy->type, 0, 31, 0, 0,
- "The type of event this joystick sensor is triggered on");
-
- if (joy->type != SENS_JOY_AXIS_SINGLE) {
- if (joy->flag & SENS_JOY_ANY_EVENT) {
- switch (joy->type) {
- case SENS_JOY_AXIS:
- str = "All Axis Events";
- break;
- case SENS_JOY_BUTTON:
- str = "All Button Events";
- break;
- default:
- str = "All Hat Events";
- break;
- }
- }
- else {
- str = "All";
- }
-
- uiDefButBitS(block, TOG, SENS_JOY_ANY_EVENT, B_REDR, str,
- xco+10 + 0.475 * (width-20), yco-68, ((joy->flag & SENS_JOY_ANY_EVENT) ? 0.525 : 0.12) * (width-20), 19,
- &joy->flag, 0, 0, 0, 0,
- "Triggered by all events on this joysticks current type (axis/button/hat)");
- }
- if (joy->type == SENS_JOY_BUTTON) {
- if ((joy->flag & SENS_JOY_ANY_EVENT)==0) {
- uiDefButI(block, NUM, 1, "Number:", xco+10 + 0.6 * (width-20), yco-68, 0.4 * (width-20), 19,
- &joy->button, 0, 18, 100, 0,
- "Specify which button to use");
- }
- }
- else if (joy->type == SENS_JOY_AXIS) {
- uiDefButS(block, NUM, 1, "Number:", xco+10, yco-68, 0.46 * (width-20), 19,
- &joy->axis, 1, 8.0, 100, 0,
- "Specify which axis pair to use, 1 is useually the main direction input");
-
- uiDefButI(block, NUM, 1, "Threshold:", xco+10 + 0.6 * (width-20), yco-44, 0.4 * (width-20), 19,
- &joy->precision, 0, 32768.0, 100, 0,
- "Specify the precision of the axis");
-
- if ((joy->flag & SENS_JOY_ANY_EVENT)==0) {
- str = "Type %t|Up Axis %x1 |Down Axis %x3|Left Axis %x2|Right Axis %x0";
- uiDefButI(block, MENU, B_REDR, str, xco+10 + 0.6 * (width-20), yco-68, 0.4 * (width-20), 19,
- &joy->axisf, 2.0, 31, 0, 0,
- "The direction of the axis, use 'All Events' to receive events on any direction");
- }
- }
- else if (joy->type == SENS_JOY_HAT) {
- uiDefButI(block, NUM, 1, "Number:", xco+10, yco-68, 0.46 * (width-20), 19,
- &joy->hat, 1, 4.0, 100, 0,
- "Specify which hat to use");
-
- if ((joy->flag & SENS_JOY_ANY_EVENT)==0) {
- str = "Direction%t|Up%x1|Down%x4|Left%x8|Right%x2|%l|Up/Right%x3|Down/Left%x12|Up/Left%x9|Down/Right%x6";
- uiDefButI(block, MENU, 0, str, xco+10 + 0.6 * (width-20), yco-68, 0.4 * (width-20), 19,
- &joy->hatf, 2.0, 31, 0, 0,
- "The direction of the hat, use 'All Events' to receive events on any direction");
- }
- }
- else { /* (joy->type == SENS_JOY_AXIS_SINGLE)*/
- uiDefButS(block, NUM, 1, "Number:", xco+10, yco-68, 0.46 * (width-20), 19,
- &joy->axis_single, 1, 16.0, 100, 0,
- "Specify a single axis (verticle/horizontal/other) to detect");
-
- uiDefButI(block, NUM, 1, "Threshold:", xco+10 + 0.6 * (width-20), yco-44, 0.4 * (width-20), 19,
- &joy->precision, 0, 32768.0, 100, 0,
- "Specify the precision of the axis");
- }
- yco-= ysize;
- break;
- }
- }
-
- return yco-4;
-}
-
-
-
-static short draw_controllerbuttons(bController *cont, uiBlock *block, short xco, short yco, short width)
-{
- bExpressionCont *ec;
- bPythonCont *pc;
- short ysize;
-
- switch (cont->type) {
- case CONT_EXPRESSION:
- ysize= 28;
-
- UI_ThemeColor(TH_PANEL);
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- /* uiDefBut(block, LABEL, 1, "Not yet...", xco, yco-24, 80, 19, NULL, 0, 0, 0, 0, ""); */
- ec= cont->data;
- /* uiDefBut(block, BUT, 1, "Variables", xco, yco-24, 80, 19, NULL, 0, 0, 0, 0, "Available variables for expression"); */
- uiDefBut(block, TEX, 1, "Exp:", xco + 10, yco-21, width-20, 19,
- ec->str, 0, sizeof(ec->str), 0, 0,
- "Expression");
-
- yco-= ysize;
- break;
- case CONT_PYTHON:
- ysize= 28;
-
- if (cont->data==NULL) init_controller(cont);
- pc= cont->data;
-
- UI_ThemeColor(TH_PANEL);
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
-
- uiBlockBeginAlign(block);
- uiDefButI(block, MENU, B_REDR, "Execution Method%t|Script%x0|Module%x1", xco+4, yco-23, 66, 19, &pc->mode, 0, 0, 0, 0, "Python script type (textblock or module - faster)");
- if (pc->mode==0)
- uiDefIDPoinBut(block, test_scriptpoin_but, ID_TXT, 1, "", xco+70, yco-23, width-74, 19, &pc->text, "Blender textblock to run as a script");
- else {
- uiDefBut(block, TEX, 1, "", xco+70, yco-23, (width-70)-25, 19, pc->module, 0, sizeof(pc->module), 0, 0, "Module name and function to run e.g. \"someModule.main\". Internal texts and external python files can be used");
- uiDefButBitI(block, TOG, CONT_PY_DEBUG, B_REDR, "D", (xco+width)-25, yco-23, 19, 19, &pc->flag, 0, 0, 0, 0, "Continuously reload the module from disk for editing external modules without restarting");
- }
- uiBlockEndAlign(block);
-
- yco-= ysize;
- break;
-
- default:
- ysize= 4;
-
- UI_ThemeColor(TH_PANEL);
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- yco-= ysize;
- }
-
- return yco;
-}
-
-static int get_col_actuator(int type)
-{
- switch (type) {
- case ACT_ACTION: return TH_PANEL;
- case ACT_SHAPEACTION: return TH_PANEL;
- case ACT_OBJECT: return TH_PANEL;
- case ACT_IPO: return TH_PANEL;
- case ACT_PROPERTY: return TH_PANEL;
- case ACT_SOUND: return TH_PANEL;
- case ACT_CAMERA: return TH_PANEL;
- case ACT_EDIT_OBJECT: return TH_PANEL;
- case ACT_GROUP: return TH_PANEL;
- case ACT_RANDOM: return TH_PANEL;
- case ACT_SCENE: return TH_PANEL;
- case ACT_MESSAGE: return TH_PANEL;
- case ACT_GAME: return TH_PANEL;
- case ACT_VISIBILITY: return TH_PANEL;
- case ACT_CONSTRAINT: return TH_PANEL;
- case ACT_STATE: return TH_PANEL;
- case ACT_ARMATURE: return TH_PANEL;
- case ACT_STEERING: return TH_PANEL;
- default: return TH_PANEL;
- }
-}
-static void set_col_actuator(int item, int medium)
-{
- int col= get_col_actuator(item);
- UI_ThemeColorShade(col, medium?30:10);
-
-}
-
-static void change_object_actuator(bContext *UNUSED(C), void *act, void *UNUSED(arg))
-{
- bObjectActuator *oa = act;
-
- if (oa->type != oa->otype) {
- switch (oa->type) {
- case ACT_OBJECT_NORMAL:
- memset(oa, 0, sizeof(bObjectActuator));
- oa->flag = ACT_FORCE_LOCAL|ACT_TORQUE_LOCAL|ACT_DLOC_LOCAL|ACT_DROT_LOCAL;
- oa->type = ACT_OBJECT_NORMAL;
- break;
-
- case ACT_OBJECT_SERVO:
- memset(oa, 0, sizeof(bObjectActuator));
- oa->flag = ACT_LIN_VEL_LOCAL;
- oa->type = ACT_OBJECT_SERVO;
- oa->forcerot[0] = 30.0f;
- oa->forcerot[1] = 0.5f;
- oa->forcerot[2] = 0.0f;
- break;
- }
- }
-}
-
-static void change_ipo_actuator(bContext *UNUSED(C), void *arg1_but, void *arg2_ia)
-{
- bIpoActuator *ia = arg2_ia;
- uiBut *but = arg1_but;
-
- if (but->retval & ACT_IPOFORCE)
- ia->flag &= ~ACT_IPOADD;
- else if (but->retval & ACT_IPOADD)
- ia->flag &= ~ACT_IPOFORCE;
- but->retval = B_REDR;
-}
-
-static void update_object_actuator_PID(bContext *UNUSED(C), void *act, void *UNUSED(arg))
-{
- bObjectActuator *oa = act;
- oa->forcerot[0] = 60.0f*oa->forcerot[1];
-}
-
-static char *get_state_name(Object *ob, short bit)
-{
- bController *cont;
- unsigned int mask;
-
- mask = (1<<bit);
- cont = ob->controllers.first;
- while (cont) {
- if (cont->state_mask & mask) {
- return cont->name;
- }
- cont = cont->next;
- }
- return (char*)"";
-}
-
-static void check_state_mask(bContext *C, void *arg1_but, void *arg2_mask)
-{
- wmWindow *win= CTX_wm_window(C);
- int shift= win->eventstate->shift;
- unsigned int *cont_mask = arg2_mask;
- uiBut *but = arg1_but;
-
- if (*cont_mask == 0 || !(shift))
- *cont_mask = (1<<but->retval);
- but->retval = B_REDR;
-}
-
-static void check_armature_actuator(bContext *C, void *arg1_but, void *arg2_act)
-{
- bArmatureActuator *act = arg2_act;
- uiBut *but = arg1_but;
- Object *ob= CTX_data_active_object(C);
-
- /* check that bone exist in the active object */
- but->retval = B_REDR;
- check_armature_bone_constraint(ob, act->posechannel, act->constraint);
-}
-
-
-static short draw_actuatorbuttons(Main *bmain, Object *ob, bActuator *act, uiBlock *block, short xco, short yco, short width)
-{
- bSoundActuator *sa = NULL;
- bObjectActuator *oa = NULL;
- bIpoActuator *ia = NULL;
- bPropertyActuator *pa = NULL;
- bCameraActuator *ca = NULL;
- bEditObjectActuator *eoa = NULL;
- bConstraintActuator *coa = NULL;
- bSceneActuator *sca = NULL;
- bGroupActuator *ga = NULL;
- bRandomActuator *randAct = NULL;
- bMessageActuator *ma = NULL;
- bActionActuator *aa = NULL;
- bGameActuator *gma = NULL;
- bVisibilityActuator *visAct = NULL;
- bTwoDFilterActuator *tdfa = NULL;
- bParentActuator *parAct = NULL;
- bStateActuator *staAct = NULL;
- bArmatureActuator *armAct = NULL;
-
- float *fp;
- short ysize = 0, wval;
- const char *str;
- int myline, stbit;
- uiBut *but;
-
-
- /* yco is at the top of the rect, draw downwards */
- set_col_actuator(act->type, 0);
-
- switch (act->type) {
- case ACT_OBJECT:
- {
- oa = act->data;
- wval = (width-100)/3;
- if (oa->type == ACT_OBJECT_NORMAL) {
- if (ob->gameflag & OB_DYNAMIC) {
- ysize= 175;
- }
- else {
- ysize= 72;
- }
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiBlockBeginAlign(block);
- uiDefBut(block, LABEL, 0, "Loc", xco, yco-45, 45, 19, NULL, 0, 0, 0, 0, "Sets the location");
- uiDefButF(block, NUM, 0, "", xco+45, yco-45, wval, 19, oa->dloc, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+wval, yco-45, wval, 19, oa->dloc+1, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+2*wval, yco-45, wval, 19, oa->dloc+2, -10000.0, 10000.0, 10, 0, "");
- uiBlockEndAlign(block);
-
- uiDefBut(block, LABEL, 0, "Rot", xco, yco-64, 45, 19, NULL, 0, 0, 0, 0, "Sets the rotation");
- uiBlockBeginAlign(block);
- uiDefButF(block, NUM, 0, "", xco+45, yco-64, wval, 19, oa->drot, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+wval, yco-64, wval, 19, oa->drot+1, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+2*wval, yco-64, wval, 19, oa->drot+2, -10000.0, 10000.0, 10, 0, "");
- uiBlockEndAlign(block);
-
- uiDefButBitS(block, TOG, ACT_DLOC_LOCAL, 0, "L", xco+45+3*wval, yco-45, 15, 19, &oa->flag, 0.0, 0.0, 0, 0, "Local transformation");
- uiDefButBitS(block, TOG, ACT_DROT_LOCAL, 0, "L", xco+45+3*wval, yco-64, 15, 19, &oa->flag, 0.0, 0.0, 0, 0, "Local transformation");
-
- if (ob->gameflag & OB_DYNAMIC) {
- uiDefBut(block, LABEL, 0, "Force", xco, yco-87, 55, 19, NULL, 0, 0, 0, 0, "Sets the force");
- uiBlockBeginAlign(block);
- uiDefButF(block, NUM, 0, "", xco+45, yco-87, wval, 19, oa->forceloc, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+wval, yco-87, wval, 19, oa->forceloc+1, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+2*wval, yco-87, wval, 19, oa->forceloc+2, -10000.0, 10000.0, 10, 0, "");
- uiBlockEndAlign(block);
-
- uiDefBut(block, LABEL, 0, "Torque", xco, yco-106, 55, 19, NULL, 0, 0, 0, 0, "Sets the torque");
- uiBlockBeginAlign(block);
- uiDefButF(block, NUM, 0, "", xco+45, yco-106, wval, 19, oa->forcerot, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+wval, yco-106, wval, 19, oa->forcerot+1, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+2*wval, yco-106, wval, 19, oa->forcerot+2, -10000.0, 10000.0, 10, 0, "");
- uiBlockEndAlign(block);
- }
-
- if (ob->gameflag & OB_DYNAMIC) {
- uiDefBut(block, LABEL, 0, "LinV", xco, yco-129, 45, 19, NULL, 0, 0, 0, 0, "Sets the linear velocity");
- uiBlockBeginAlign(block);
- uiDefButF(block, NUM, 0, "", xco+45, yco-129, wval, 19, oa->linearvelocity, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+wval, yco-129, wval, 19, oa->linearvelocity+1, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+2*wval, yco-129, wval, 19, oa->linearvelocity+2, -10000.0, 10000.0, 10, 0, "");
- uiBlockEndAlign(block);
-
- uiDefBut(block, LABEL, 0, "AngV", xco, yco-148, 45, 19, NULL, 0, 0, 0, 0, "Sets the angular velocity");
- uiBlockBeginAlign(block);
- uiDefButF(block, NUM, 0, "", xco+45, yco-148, wval, 19, oa->angularvelocity, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+wval, yco-148, wval, 19, oa->angularvelocity+1, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+2*wval, yco-148, wval, 19, oa->angularvelocity+2, -10000.0, 10000.0, 10, 0, "");
- uiBlockEndAlign(block);
-
- uiDefBut(block, LABEL, 0, "Damp", xco, yco-171, 45, 19, NULL, 0, 0, 0, 0, "Number of frames to reach the target velocity");
- uiDefButS(block, NUM, 0, "", xco+45, yco-171, wval, 19, &oa->damping, 0.0, 1000.0, 100, 0, "");
-
- uiDefButBitS(block, TOG, ACT_FORCE_LOCAL, 0, "L", xco+45+3*wval, yco-87, 15, 19, &oa->flag, 0.0, 0.0, 0, 0, "Local transformation");
- uiDefButBitS(block, TOG, ACT_TORQUE_LOCAL, 0, "L", xco+45+3*wval, yco-106, 15, 19, &oa->flag, 0.0, 0.0, 0, 0, "Local transformation");
- uiDefButBitS(block, TOG, ACT_LIN_VEL_LOCAL, 0, "L", xco+45+3*wval, yco-129, 15, 19, &oa->flag, 0.0, 0.0, 0, 0, "Local transformation");
- uiDefButBitS(block, TOG, ACT_ANG_VEL_LOCAL, 0, "L", xco+45+3*wval, yco-148, 15, 19, &oa->flag, 0.0, 0.0, 0, 0, "Local transformation");
-
- uiDefButBitS(block, TOG, ACT_ADD_LIN_VEL, 0, "use_additive", xco+45+3*wval+15, yco-129, 35, 19, &oa->flag, 0.0, 0.0, 0, 0, "Toggles between ADD and SET linV");
- }
- }
- else if (oa->type == ACT_OBJECT_SERVO) {
- ysize= 195;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefBut(block, LABEL, 0, "Ref", xco, yco-45, 45, 19, NULL, 0, 0, 0, 0, "");
- uiDefIDPoinBut(block, test_obpoin_but, ID_OB, 1, "OB:", xco+45, yco-45, wval*3, 19, &(oa->reference), "Reference object for velocity calculation, leave empty for world reference");
- uiDefBut(block, LABEL, 0, "linV", xco, yco-68, 45, 19, NULL, 0, 0, 0, 0, "Sets the target relative linear velocity, it will be achieved by automatic application of force. Null velocity is a valid target");
- uiBlockBeginAlign(block);
- uiDefButF(block, NUM, 0, "", xco+45, yco-68, wval, 19, oa->linearvelocity, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+wval, yco-68, wval, 19, oa->linearvelocity+1, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+2*wval, yco-68, wval, 19, oa->linearvelocity+2, -10000.0, 10000.0, 10, 0, "");
- uiBlockEndAlign(block);
- uiDefButBitS(block, TOG, ACT_LIN_VEL_LOCAL, 0, "L", xco+45+3*wval, yco-68, 15, 19, &oa->flag, 0.0, 0.0, 0, 0, "Velocity is defined in local coordinates");
-
- uiDefBut(block, LABEL, 0, "Limit", xco, yco-91, 45, 19, NULL, 0, 0, 0, 0, "Select if the force needs to be limited along certain axis (local or global depending on LinV Local flag)");
- uiBlockBeginAlign(block);
- uiDefButBitS(block, TOG, ACT_SERVO_LIMIT_X, B_REDR, "X", xco+45, yco-91, wval, 19, &oa->flag, 0.0, 0.0, 0, 0, "Set limit to force along the X axis");
- uiDefButBitS(block, TOG, ACT_SERVO_LIMIT_Y, B_REDR, "Y", xco+45+wval, yco-91, wval, 19, &oa->flag, 0.0, 0.0, 0, 0, "Set limit to force along the Y axis");
- uiDefButBitS(block, TOG, ACT_SERVO_LIMIT_Z, B_REDR, "Z", xco+45+2*wval, yco-91, wval, 19, &oa->flag, 0.0, 0.0, 0, 0, "Set limit to force along the Z axis");
- uiBlockEndAlign(block);
- uiDefBut(block, LABEL, 0, "Max", xco, yco-110, 45, 19, NULL, 0, 0, 0, 0, "Set the upper limit for force");
- uiDefBut(block, LABEL, 0, "Min", xco, yco-129, 45, 19, NULL, 0, 0, 0, 0, "Set the lower limit for force");
- if (oa->flag & ACT_SERVO_LIMIT_X) {
- uiDefButF(block, NUM, 0, "", xco+45, yco-110, wval, 19, oa->dloc, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45, yco-129, wval, 19, oa->drot, -10000.0, 10000.0, 10, 0, "");
- }
- if (oa->flag & ACT_SERVO_LIMIT_Y) {
- uiDefButF(block, NUM, 0, "", xco+45+wval, yco-110, wval, 19, oa->dloc+1, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+wval, yco-129, wval, 19, oa->drot+1, -10000.0, 10000.0, 10, 0, "");
- }
- if (oa->flag & ACT_SERVO_LIMIT_Z) {
- uiDefButF(block, NUM, 0, "", xco+45+2*wval, yco-110, wval, 19, oa->dloc+2, -10000.0, 10000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+45+2*wval, yco-129, wval, 19, oa->drot+2, -10000.0, 10000.0, 10, 0, "");
- }
- uiDefBut(block, LABEL, 0, "Servo", xco, yco-152, 45, 19, NULL, 0, 0, 0, 0, "Coefficients of the PID servo controller");
- uiDefButF(block, NUMSLI, B_REDR, "P: ", xco+45, yco-152, wval*3, 19, oa->forcerot, 0.00, 200.0, 100, 0, "Proportional coefficient, typical value is 60x Integral coefficient");
- uiDefBut(block, LABEL, 0, "Slow", xco, yco-171, 45, 19, NULL, 0, 0, 0, 0, "Low value of I coefficient correspond to slow response");
- but = uiDefButF(block, NUMSLI, B_REDR, " I : ", xco+45, yco-171, wval*3, 19, oa->forcerot+1, 0.0, 3.0, 1, 0, "Integral coefficient, low value (0.01) for slow response, high value (0.5) for fast response");
- uiButSetFunc(but, update_object_actuator_PID, oa, NULL);
- uiDefBut(block, LABEL, 0, "Fast", xco+45+3*wval, yco-171, 45, 19, NULL, 0, 0, 0, 0, "High value of I coefficient correspond to fast response");
- uiDefButF(block, NUMSLI, B_REDR, "D: ", xco+45, yco-190, wval*3, 19, oa->forcerot+2, -100.0, 100.0, 100, 0, "Derivate coefficient, not required, high values can cause instability");
- }
- str= "Motion Type %t|Simple motion %x0|Servo Control %x1";
- but = uiDefButS(block, MENU, B_REDR, str, xco+40, yco-23, (width-80), 19, &oa->type, 0.0, 0.0, 0, 0, "");
- oa->otype = oa->type;
- uiButSetFunc(but, change_object_actuator, oa, NULL);
- yco-= ysize;
- break;
- }
- case ACT_ACTION:
- case ACT_SHAPEACTION:
- {
- /* DrawAct */
-#ifdef __NLA_ACTION_BY_MOTION_ACTUATOR
- ysize = 112;
-#else
- ysize= 92;
-#endif
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- aa = act->data;
- wval = (width-60)/3;
-
- // str= "Action types %t|Play %x0|Ping Pong %x1|Flipper %x2|Loop Stop %x3|Loop End %x4|Property %x6";
-#ifdef __NLA_ACTION_BY_MOTION_ACTUATOR
- str= "Action types %t|Play %x0|Flipper %x2|Loop Stop %x3|Loop End %x4|Property %x6|Displacement %x7";
-#else
- str= "Action types %t|Play %x0|Flipper %x2|Loop Stop %x3|Loop End %x4|Property %x6";
-#endif
- uiDefButS(block, MENU, B_REDR, str, xco+10, yco-24, width/3, 19, &aa->type, 0.0, 0.0, 0.0, 0.0, "Action playback type");
- uiDefIDPoinBut(block, test_actionpoin_but, ID_AC, 1, "AC: ", xco+10+ (width/3), yco-24, ((width/3)*2) - (20 + 60), 19, &aa->act, "Action name");
-
- uiDefButBitS(block, TOGN, 1, 0, "Continue", xco+((width/3)*2)+20, yco-24, 60, 19,
- &aa->end_reset, 0.0, 0.0, 0, 0, "Restore last frame when switching on/off, otherwise play from the start each time");
-
-
- if (aa->type == ACT_ACTION_FROM_PROP) {
- uiDefBut(block, TEX, 0, "Prop: ", xco+10, yco-44, width-20, 19, aa->name, 0.0, MAX_NAME, 0, 0, "Use this property to define the Action position");
- }
- else {
- uiDefButF(block, NUM, 0, "Sta: ", xco+10, yco-44, (width-20)/2, 19, &aa->sta, 1.0, MAXFRAMEF, 0, 0, "Start frame");
- uiDefButF(block, NUM, 0, "End: ", xco+10+(width-20)/2, yco-44, (width-20)/2, 19, &aa->end, 1.0, MAXFRAMEF, 0, 0, "End frame");
- }
-
- uiDefButS(block, NUM, 0, "Blendin: ", xco+10, yco-64, (width-20)/2, 19, &aa->blendin, 0.0, 32767, 0.0, 0.0, "Number of frames of motion blending");
- uiDefButS(block, NUM, 0, "Priority: ", xco+10+(width-20)/2, yco-64, (width-20)/2, 19, &aa->priority, 0.0, 100.0, 0.0, 0.0, "Execution priority - lower numbers will override actions with higher numbers, With 2 or more actions at once, the overriding channels must be lower in the stack");
-
- uiDefBut(block, TEX, 0, "FrameProp: ", xco+10, yco-84, width-20, 19, aa->frameProp, 0.0, MAX_NAME, 0, 0, "Assign the action's current frame number to this property");
-
-
-#ifdef __NLA_ACTION_BY_MOTION_ACTUATOR
- if (aa->type == ACT_ACTION_MOTION) {
- uiDefButF(block, NUM, 0, "Cycle: ", xco+30, yco-84, (width-60)/2, 19, &aa->stridelength, 0.0, 2500.0, 0, 0, "Distance covered by a single cycle of the action");
- }
-#endif
-
-
-
- yco-=ysize;
- break;
- }
- case ACT_IPO:
- {
- ia= act->data;
-
- ysize= 72;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- str = "Ipo types %t|Play %x0|Ping Pong %x1|Flipper %x2|Loop Stop %x3|Loop End %x4|Property %x6";
-
- uiDefButS(block, MENU, B_REDR, str, xco+10, yco-24, (width-20)/2, 19, &ia->type, 0, 0, 0, 0, "");
-
- but = uiDefButBitS(block, TOG, ACT_IPOFORCE, ACT_IPOFORCE,
- "Force", xco+10+(width-20)/2, yco-24, (width-20)/4-10, 19,
- &ia->flag, 0, 0, 0, 0,
- "Apply Ipo as a global or local force depending on the local option (dynamic objects only)");
- uiButSetFunc(but, change_ipo_actuator, but, ia);
-
- but = uiDefButBitS(block, TOG, ACT_IPOADD, ACT_IPOADD,
- "Add", xco+3*(width-20)/4, yco-24, (width-20)/4-10, 19,
- &ia->flag, 0, 0, 0, 0,
- "Ipo is added to the current loc/rot/scale in global or local coordinate according to Local flag");
- uiButSetFunc(but, change_ipo_actuator, but, ia);
-
- /* Only show the do-force-local toggle if force is requested */
- if (ia->flag & (ACT_IPOFORCE|ACT_IPOADD)) {
- uiDefButBitS(block, TOG, ACT_IPOLOCAL, 0,
- "L", xco+width-30, yco-24, 20, 19,
- &ia->flag, 0, 0, 0, 0,
- "Let the ipo acts in local coordinates, used in Force and Add mode");
- }
-
- if (ia->type==ACT_IPO_FROM_PROP) {
- uiDefBut(block, TEX, 0,
- "Prop: ", xco+10, yco-44, width-80, 19,
- ia->name, 0.0, MAX_NAME, 0, 0,
- "Use this property to define the Ipo position");
- }
- else {
- uiDefButF(block, NUM, 0,
- "Sta", xco+10, yco-44, (width-80)/2, 19,
- &ia->sta, 1.0, MAXFRAMEF, 0, 0,
- "Start frame");
- uiDefButF(block, NUM, 0,
- "End", xco+10+(width-80)/2, yco-44, (width-80)/2, 19,
- &ia->end, 1.0, MAXFRAMEF, 0, 0,
- "End frame");
- }
- uiDefButBitS(block, TOG, ACT_IPOCHILD, B_REDR,
- "Child", xco+10+(width-80), yco-44, 60, 19,
- &ia->flag, 0, 0, 0, 0,
- "Update IPO on all children Objects as well");
- uiDefBut(block, TEX, 0,
- "FrameProp: ", xco+10, yco-64, width-20, 19,
- ia->frameProp, 0.0, MAX_NAME, 0, 0,
- "Assign the action's current frame number to this property");
-
- yco-= ysize;
- break;
- }
- case ACT_PROPERTY:
- {
- ysize= 68;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- pa= act->data;
-
- str= "Type%t|Assign%x0|Add %x1|Copy %x2|Toggle (bool/int/float/timer)%x3";
- uiDefButI(block, MENU, B_REDR, str, xco+30, yco-24, width-60, 19, &pa->type, 0, 31, 0, 0, "Type");
-
- uiDefBut(block, TEX, 1, "Prop: ", xco+30, yco-44, width-60, 19, pa->name, 0, MAX_NAME, 0, 0, "Property name");
-
-
- if (pa->type==ACT_PROP_TOGGLE) {
- /* no ui */
- ysize -= 22;
- }
- else if (pa->type==ACT_PROP_COPY) {
- uiDefIDPoinBut(block, test_obpoin_but, ID_OB, 1, "OB:", xco+10, yco-64, (width-20)/2, 19, &(pa->ob), "Copy from this Object");
- uiDefBut(block, TEX, 1, "Prop: ", xco+10+(width-20)/2, yco-64, (width-20)/2, 19, pa->value, 0, MAX_NAME, 0, 0, "Copy this property");
- }
- else {
- uiDefBut(block, TEX, 1, "Value: ", xco+30, yco-64, width-60, 19, pa->value, 0, MAX_NAME, 0, 0, "change with this value, use \"\" around strings");
- }
- yco-= ysize;
-
- break;
- }
- case ACT_SOUND:
- {
- sa = act->data;
- sa->sndnr = 0;
-
- if (sa->flag & ACT_SND_3D_SOUND)
- ysize = 180;
- else
- ysize = 92;
-
- wval = (width-20)/2;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- if (bmain->sound.first) {
- IDnames_to_pupstring(&str, "Sound files", NULL, &(bmain->sound), (ID *)sa->sound, &(sa->sndnr));
- /* reset this value, it is for handling the event */
- sa->sndnr = 0;
- uiDefButS(block, MENU, B_SOUNDACT_BROWSE, str, xco+10, yco-22, 20, 19, &(sa->sndnr), 0, 0, 0, 0, "");
- uiDefButO(block, BUT, "sound.open", 0, "Load Sound", xco+wval+10, yco-22, wval, 19,
- "Load a sound file (remember to set caching on for small sounds that are played often)");
-
- if (sa->sound) {
- char dummy_str[] = "Sound mode %t|Play Stop %x0|Play End %x1|Loop Stop %x2|"
- "Loop End %x3|Loop Ping Pong Stop %x5|Loop Ping Pong %x4";
- uiDefBut(block, TEX, B_IDNAME, "SO:", xco+30, yco-22, wval-20, 19,
- ((ID *)sa->sound)->name+2, 0.0, MAX_ID_NAME-2, 0, 0, "");
- uiDefButS(block, MENU, 1, dummy_str, xco+10, yco-44, width-20, 19,
- &sa->type, 0.0, 0.0, 0, 0, "");
- uiDefButF(block, NUM, 0, "Volume:", xco+10, yco-66, wval, 19, &sa->volume,
- 0.0, 1.0, 0, 0, "Sets the volume of this sound");
- uiDefButF(block, NUM, 0, "Pitch:", xco+wval+10, yco-66, wval, 19, &sa->pitch, -12.0,
- 12.0, 0, 0, "Sets the pitch of this sound");
- uiDefButS(block, TOG | UI_BUT_POIN_BIT, 0, "3D Sound", xco+10, yco-88, width-20, 19,
- &sa->flag, 0.0, 1.0, 0.0, 0.0, "Plays the sound positioned in 3D space");
- if (sa->flag & ACT_SND_3D_SOUND) {
- uiDefButF(block, NUM, 0, "Minimum Gain: ", xco+10, yco-110, wval, 19,
- &sa->sound3D.min_gain, 0.0, 1.0, 0.0, 0.0,
- "The minimum gain of the sound, no matter how far it is away");
- uiDefButF(block, NUM, 0, "Maximum Gain: ", xco+10, yco-132, wval, 19,
- &sa->sound3D.max_gain, 0.0, 1.0, 0.0, 0.0,
- "The maximum gain of the sound, no matter how near it is");
- uiDefButF(block, NUM, 0, "Reference Distance: ", xco+10, yco-154, wval, 19,
- &sa->sound3D.reference_distance, 0.0, FLT_MAX, 0.0, 0.0,
- "The reference distance is the distance where the sound has a gain of 1.0");
- uiDefButF(block, NUM, 0, "Maximum Distance: ", xco+10, yco-176, wval, 19,
- &sa->sound3D.max_distance, 0.0, FLT_MAX, 0.0, 0.0,
- "The maximum distance at which you can hear the sound");
- uiDefButF(block, NUM, 0, "Rolloff: ", xco+wval+10, yco-110, wval, 19,
- &sa->sound3D.rolloff_factor, 0.0, 5.0, 0.0, 0.0,
- "The rolloff factor defines the influence factor on volume depending on distance");
- uiDefButF(block, NUM, 0, "Cone Outer Gain: ", xco+wval+10, yco-132, wval, 19,
- &sa->sound3D.cone_outer_gain, 0.0, 1.0, 0.0, 0.0,
- "The gain outside the outer cone. The gain in the outer cone will be "
- "interpolated between this value and the normal gain in the inner cone");
- uiDefButF(block, NUM, 0, "Cone Outer Angle: ", xco+wval+10, yco-154, wval,
- 19, &sa->sound3D.cone_outer_angle, 0.0, 360.0, 0.0, 0.0,
- "The angle of the outer cone");
- uiDefButF(block, NUM, 0, "Cone Inner Angle: ", xco+wval+10, yco-176, wval,
- 19, &sa->sound3D.cone_inner_angle, 0.0, 360.0, 0.0, 0.0,
- "The angle of the inner cone");
- }
- }
- MEM_freeN((void *)str);
- }
- else {
- uiDefButO(block, BUT, "sound.open", 0, "Load Sound", xco+10, yco-22, width-20, 19, "Load a sound file");
- }
-
- yco-= ysize;
-
- break;
- }
- case ACT_CAMERA:
-
- ysize= 48;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- ca= act->data;
-
- uiDefIDPoinBut(block, test_obpoin_but, ID_OB, 1, "OB:", xco+10, yco-24, (width-20)/2, 19, &(ca->ob), "Look at this Object");
- uiDefButF(block, NUM, 0, "Height:", xco+10+(width-20)/2, yco-24, (width-20)/2, 19, &ca->height, 0.0, 20.0, 0, 0, "");
-
- uiDefButF(block, NUM, 0, "Min:", xco+10, yco-44, (width-60)/2, 19, &ca->min, 0.0, 20.0, 0, 0, "");
-
- if (ca->axis==0) ca->axis= 'x';
- uiDefButS(block, ROW, 0, "X", xco+10+(width-60)/2, yco-44, 20, 19, &ca->axis, 4.0, (float)'x', 0, 0, "Camera tries to get behind the X axis");
- uiDefButS(block, ROW, 0, "Y", xco+30+(width-60)/2, yco-44, 20, 19, &ca->axis, 4.0, (float)'y', 0, 0, "Camera tries to get behind the Y axis");
-
- uiDefButF(block, NUM, 0, "Max:", xco+20+(width)/2, yco-44, (width-60)/2, 19, &ca->max, 0.0, 20.0, 0, 0, "");
-
- yco-= ysize;
-
- break;
-
- case ACT_EDIT_OBJECT:
-
- eoa= act->data;
-
- if (eoa->type==ACT_EDOB_ADD_OBJECT) {
- ysize = 92;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefIDPoinBut(block, test_obpoin_but, ID_OB, 1, "OB:", xco+10, yco-44, (width-20)/2, 19, &(eoa->ob), "Add this Object and all its children (cant be on an visible layer)");
- uiDefButI(block, NUM, 0, "Time:", xco+10+(width-20)/2, yco-44, (width-20)/2, 19, &eoa->time, 0.0, 2000.0, 0, 0, "Duration the new Object lives");
-
- wval= (width-60)/3;
- uiDefBut(block, LABEL, 0, "linV", xco, yco-68, 45, 19,
- NULL, 0, 0, 0, 0,
- "Velocity upon creation");
- uiDefButF(block, NUM, 0, "", xco+45, yco-68, wval, 19,
- eoa->linVelocity, -100.0, 100.0, 10, 0,
- "Velocity upon creation, x component");
- uiDefButF(block, NUM, 0, "", xco+45+wval, yco-68, wval, 19,
- eoa->linVelocity+1, -100.0, 100.0, 10, 0,
- "Velocity upon creation, y component");
- uiDefButF(block, NUM, 0, "", xco+45+2*wval, yco-68, wval, 19,
- eoa->linVelocity+2, -100.0, 100.0, 10, 0,
- "Velocity upon creation, z component");
- uiDefButBitS(block, TOG, ACT_EDOB_LOCAL_LINV, 0, "L", xco+45+3*wval, yco-68, 15, 19,
- &eoa->localflag, 0.0, 0.0, 0, 0,
- "Apply the transformation locally");
-
-
- uiDefBut(block, LABEL, 0, "AngV", xco, yco-90, 45, 19,
- NULL, 0, 0, 0, 0,
- "Angular velocity upon creation");
- uiDefButF(block, NUM, 0, "", xco+45, yco-90, wval, 19,
- eoa->angVelocity, -10000.0, 10000.0, 10, 0,
- "Angular velocity upon creation, x component");
- uiDefButF(block, NUM, 0, "", xco+45+wval, yco-90, wval, 19,
- eoa->angVelocity+1, -10000.0, 10000.0, 10, 0,
- "Angular velocity upon creation, y component");
- uiDefButF(block, NUM, 0, "", xco+45+2*wval, yco-90, wval, 19,
- eoa->angVelocity+2, -10000.0, 10000.0, 10, 0,
- "Angular velocity upon creation, z component");
- uiDefButBitS(block, TOG, ACT_EDOB_LOCAL_ANGV, 0, "L", xco+45+3*wval, yco-90, 15, 19,
- &eoa->localflag, 0.0, 0.0, 0, 0,
- "Apply the rotation locally");
-
-
- }
- else if (eoa->type==ACT_EDOB_END_OBJECT) {
- ysize= 28;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
- }
- else if (eoa->type==ACT_EDOB_REPLACE_MESH) {
- ysize= 48;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefIDPoinBut(block, test_meshpoin_but, ID_ME, 1, "ME:", xco+40, yco-44, (width-80)/2, 19, &(eoa->me), "replace the existing, when left blank 'Phys' will remake the existing physics mesh");
-
- uiDefButBitS(block, TOGN, ACT_EDOB_REPLACE_MESH_NOGFX, 0, "Gfx", xco+40 + (width-80)/2, yco-44, (width-80)/4, 19, &eoa->flag, 0, 0, 0, 0, "Replace the display mesh");
- uiDefButBitS(block, TOG, ACT_EDOB_REPLACE_MESH_PHYS, 0, "Phys", xco+40 + (width-80)/2 +(width-80)/4, yco-44, (width-80)/4, 19, &eoa->flag, 0, 0, 0, 0, "Replace the physics mesh (triangle bounds only. compound shapes not supported)");
- }
- else if (eoa->type==ACT_EDOB_TRACK_TO) {
- ysize= 48;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefIDPoinBut(block, test_obpoin_but, ID_OB, 1, "OB:", xco+10, yco-44, (width-20)/2, 19, &(eoa->ob), "Track to this Object");
- uiDefButI(block, NUM, 0, "Time:", xco+10+(width-20)/2, yco-44, (width-20)/2-40, 19, &eoa->time, 0.0, 2000.0, 0, 0, "Duration the tracking takes");
- uiDefButS(block, TOG, 0, "3D", xco+width-50, yco-44, 40, 19, &eoa->flag, 0.0, 0.0, 0, 0, "Enable 3D tracking");
- }
- else if (eoa->type==ACT_EDOB_DYNAMICS) {
- ysize= 69;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- str= "Dynamic Operation %t|Restore Dynamics %x0|Suspend Dynamics %x1|Enable Rigid Body %x2|Disable Rigid Body %x3|Set Mass %x4";
- uiDefButS(block, MENU, B_REDR, str, xco+40, yco-44, (width-80), 19, &(eoa->dyn_operation), 0.0, 0.0, 0, 0, "");
- if (eoa->dyn_operation==4) {
- uiDefButF(block, NUM, 0, "", xco+40, yco-63, width-80, 19,
- &eoa->mass, 0.0, 10000.0, 10, 0,
- "Mass for object");
- }
- }
- str= "Edit Object %t|Add Object %x0|End Object %x1|Replace Mesh %x2|Track to %x3|Dynamics %x4";
- uiDefButS(block, MENU, B_REDR, str, xco+40, yco-24, (width-80), 19, &eoa->type, 0.0, 0.0, 0, 0, "");
-
- yco-= ysize;
-
- break;
-
- case ACT_CONSTRAINT:
- coa= act->data;
-
- if (coa->type == ACT_CONST_TYPE_LOC) {
- ysize= 69;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- /* str= "Limit %t|None %x0|Loc X %x1|Loc Y %x2|Loc Z %x4|Rot X %x8|Rot Y %x16|Rot Z %x32"; */
- /* coa->flag &= ~(63); */
- str= "Limit %t|None %x0|Loc X %x1|Loc Y %x2|Loc Z %x4";
- coa->flag &= 7;
- coa->time = 0;
- uiDefButS(block, MENU, 1, str, xco+10, yco-65, 70, 19, &coa->flag, 0.0, 0.0, 0, 0, "");
-
- uiDefButS(block, NUM, 0, "damp", xco+10, yco-45, 70, 19, &coa->damp, 0.0, 100.0, 0, 0, "Damping factor: time constant (in frame) of low pass filter");
- uiDefBut(block, LABEL, 0, "Min", xco+80, yco-45, (width-90)/2, 19, NULL, 0.0, 0.0, 0, 0, "");
- uiDefBut(block, LABEL, 0, "Max", xco+80+(width-90)/2, yco-45, (width-90)/2, 19, NULL, 0.0, 0.0, 0, 0, "");
-
- if (coa->flag & ACT_CONST_LOCX) fp= coa->minloc;
- else if (coa->flag & ACT_CONST_LOCY) fp= coa->minloc+1;
- else if (coa->flag & ACT_CONST_LOCZ) fp= coa->minloc+2;
- else if (coa->flag & ACT_CONST_ROTX) fp= coa->minrot;
- else if (coa->flag & ACT_CONST_ROTY) fp= coa->minrot+1;
- else fp= coa->minrot+2;
-
- uiDefButF(block, NUM, 0, "", xco+80, yco-65, (width-90)/2, 19, fp, -2000.0, 2000.0, 10, 0, "");
- uiDefButF(block, NUM, 0, "", xco+80+(width-90)/2, yco-65, (width-90)/2, 19, fp+3, -2000.0, 2000.0, 10, 0, "");
- }
- else if (coa->type == ACT_CONST_TYPE_DIST) {
- ysize= 106;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- str= "Direction %t|None %x0|X axis %x1|Y axis %x2|Z axis %x4|-X axis %x8|-Y axis %x16|-Z axis %x32";
- uiDefButS(block, MENU, B_REDR, str, xco+10, yco-65, 70, 19, &coa->mode, 0.0, 0.0, 0, 0, "Set the direction of the ray");
-
- uiDefButS(block, NUM, 0, "damp", xco+10, yco-45, 70, 19, &coa->damp, 0.0, 100.0, 0, 0, "Damping factor: time constant (in frame) of low pass filter");
- uiDefBut(block, LABEL, 0, "Range", xco+80, yco-45, (width-115)/2, 19, NULL, 0.0, 0.0, 0, 0, "Set the maximum length of ray");
- uiDefButBitS(block, TOG, ACT_CONST_DISTANCE, B_REDR, "Dist", xco+80+(width-115)/2, yco-45, (width-115)/2, 19, &coa->flag, 0.0, 0.0, 0, 0, "Force distance of object to point of impact of ray");
- uiDefButBitS(block, TOG, ACT_CONST_LOCAL, 0, "L", xco+80+(width-115), yco-45, 25, 19,
- &coa->flag, 0.0, 0.0, 0, 0, "Set ray along object's axis or global axis");
-
- if (coa->mode & (ACT_CONST_DIRPX|ACT_CONST_DIRNX)) fp= coa->minloc;
- else if (coa->mode & (ACT_CONST_DIRPY|ACT_CONST_DIRNY)) fp= coa->minloc+1;
- else fp= coa->minloc+2;
-
- uiDefButF(block, NUM, 0, "", xco+80, yco-65, (width-115)/2, 19, fp+3, 0.0, 2000.0, 10, 0, "Maximum length of ray");
- if (coa->flag & ACT_CONST_DISTANCE)
- uiDefButF(block, NUM, 0, "", xco+80+(width-115)/2, yco-65, (width-115)/2, 19, fp, -2000.0, 2000.0, 10, 0, "Keep this distance to target");
- uiDefButBitS(block, TOG, ACT_CONST_NORMAL, 0, "N", xco+80+(width-115), yco-65, 25, 19,
- &coa->flag, 0.0, 0.0, 0, 0, "Set object axis along (local axis) or parallel (global axis) to the normal at hit position");
- uiDefButBitS(block, TOG, ACT_CONST_MATERIAL, B_REDR, "M/P", xco+10, yco-84, 40, 19,
- &coa->flag, 0.0, 0.0, 0, 0, "Detect material instead of property");
- if (coa->flag & ACT_CONST_MATERIAL) {
- uiDefBut(block, TEX, 1, "Material:", xco + 50, yco-84, (width-60), 19,
- coa->matprop, 0, MAX_NAME, 0, 0,
- "Ray detects only Objects with this material");
- }
- else {
- uiDefBut(block, TEX, 1, "Property:", xco + 50, yco-84, (width-60), 19,
- coa->matprop, 0, MAX_NAME, 0, 0,
- "Ray detect only Objects with this property");
- }
- uiDefButBitS(block, TOG, ACT_CONST_PERMANENT, 0, "PER", xco+10, yco-103, 40, 19,
- &coa->flag, 0.0, 0.0, 0, 0, "Persistent actuator: stays active even if ray does not reach target");
- uiDefButS(block, NUM, 0, "time", xco+50, yco-103, (width-60)/2, 19, &(coa->time), 0.0, 1000.0, 0, 0, "Maximum activation time in frame, 0 for unlimited");
- uiDefButS(block, NUM, 0, "rotDamp", xco+50+(width-60)/2, yco-103, (width-60)/2, 19, &(coa->rotdamp), 0.0, 100.0, 0, 0, "Use a different damping for orientation");
- }
- else if (coa->type == ACT_CONST_TYPE_ORI) {
- ysize= 87;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- str= "Direction %t|None %x0|X axis %x1|Y axis %x2|Z axis %x4";
- uiDefButS(block, MENU, B_REDR, str, xco+10, yco-65, 70, 19, &coa->mode, 0.0, 0.0, 0, 0, "Select the axis to be aligned along the reference direction");
-
- uiDefButS(block, NUM, 0, "damp", xco+10, yco-45, 70, 19, &coa->damp, 0.0, 100.0, 0, 0, "Damping factor: time constant (in frame) of low pass filter");
- uiDefBut(block, LABEL, 0, "X", xco+80, yco-45, (width-115)/3, 19, NULL, 0.0, 0.0, 0, 0, "");
- uiDefBut(block, LABEL, 0, "Y", xco+80+(width-115)/3, yco-45, (width-115)/3, 19, NULL, 0.0, 0.0, 0, 0, "");
- uiDefBut(block, LABEL, 0, "Z", xco+80+2*(width-115)/3, yco-45, (width-115)/3, 19, NULL, 0.0, 0.0, 0, 0, "");
-
- uiDefButF(block, NUM, 0, "", xco+80, yco-65, (width-115)/3, 19, &coa->maxrot[0], -2000.0, 2000.0, 10, 0, "X component of reference direction");
- uiDefButF(block, NUM, 0, "", xco+80+(width-115)/3, yco-65, (width-115)/3, 19, &coa->maxrot[1], -2000.0, 2000.0, 10, 0, "Y component of reference direction");
- uiDefButF(block, NUM, 0, "", xco+80+2*(width-115)/3, yco-65, (width-115)/3, 19, &coa->maxrot[2], -2000.0, 2000.0, 10, 0, "Z component of reference direction");
-
- uiDefButS(block, NUM, 0, "time", xco+10, yco-84, 70, 19, &(coa->time), 0.0, 1000.0, 0, 0, "Maximum activation time in frame, 0 for unlimited");
- uiDefButF(block, NUM, 0, "min", xco+80, yco-84, (width-115)/2, 19, &(coa->minloc[0]), 0.0, 180.0, 10, 1, "Minimum angle (in degree) to maintain with target direction. No correction is done if angle with target direction is between min and max");
- uiDefButF(block, NUM, 0, "max", xco+80+(width-115)/2, yco-84, (width-115)/2, 19, &(coa->maxloc[0]), 0.0, 180.0, 10, 1, "Maximum angle (in degree) allowed with target direction. No correction is done if angle with target direction is between min and max");
- }
- else if (coa->type == ACT_CONST_TYPE_FH) {
- ysize= 106;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- str= "Direction %t|None %x0|X axis %x1|Y axis %x2|Z axis %x4|-X axis %x8|-Y axis %x16|-Z axis %x32";
- uiDefButS(block, MENU, B_REDR, str, xco+10, yco-65, 70, 19, &coa->mode, 0.0, 0.0, 0, 0, "Set the direction of the ray (in world coordinate)");
-
- if (coa->mode & (ACT_CONST_DIRPX|ACT_CONST_DIRNX)) fp= coa->minloc;
- else if (coa->mode & (ACT_CONST_DIRPY|ACT_CONST_DIRNY)) fp= coa->minloc+1;
- else fp= coa->minloc+2;
-
- uiDefButF(block, NUM, 0, "damp", xco+10, yco-45, (width-70)/2, 19, &coa->maxrot[0], 0.0, 1.0, 1, 0, "Damping factor of the Fh spring force");
- uiDefButF(block, NUM, 0, "dist", xco+10+(width-70)/2, yco-45, (width-70)/2, 19, fp, 0.010, 2000.0, 10, 0, "Height of the Fh area");
- uiDefButBitS(block, TOG, ACT_CONST_DOROTFH, 0, "Rot Fh", xco+10+(width-70), yco-45, 50, 19, &coa->flag, 0.0, 0.0, 0, 0, "Keep object axis parallel to normal");
-
- uiDefButF(block, NUMSLI, 0, "Fh ", xco+80, yco-65, (width-115), 19, fp+3, 0.0, 1.0, 0, 0, "Spring force within the Fh area");
- uiDefButBitS(block, TOG, ACT_CONST_NORMAL, 0, "N", xco+80+(width-115), yco-65, 25, 19,
- &coa->flag, 0.0, 0.0, 0, 0, "Add a horizontal spring force on slopes");
- uiDefButBitS(block, TOG, ACT_CONST_MATERIAL, B_REDR, "M/P", xco+10, yco-84, 40, 19,
- &coa->flag, 0.0, 0.0, 0, 0, "Detect material instead of property");
- if (coa->flag & ACT_CONST_MATERIAL) {
- uiDefBut(block, TEX, 1, "Material:", xco + 50, yco-84, (width-60), 19,
- coa->matprop, 0, MAX_NAME, 0, 0,
- "Ray detects only Objects with this material");
- }
- else {
- uiDefBut(block, TEX, 1, "Property:", xco + 50, yco-84, (width-60), 19,
- coa->matprop, 0, MAX_NAME, 0, 0,
- "Ray detect only Objects with this property");
- }
- uiDefButBitS(block, TOG, ACT_CONST_PERMANENT, 0, "PER", xco+10, yco-103, 40, 19,
- &coa->flag, 0.0, 0.0, 0, 0, "Persistent actuator: stays active even if ray does not reach target");
- uiDefButS(block, NUM, 0, "time", xco+50, yco-103, 90, 19, &(coa->time), 0.0, 1000.0, 0, 0, "Maximum activation time in frame, 0 for unlimited");
- uiDefButF(block, NUM, 0, "rotDamp", xco+140, yco-103, (width-150), 19, &coa->maxrot[1], 0.0, 1.0, 1, 0, "Use a different damping for rotation");
- }
- str= "Constraint Type %t|Location %x0|Distance %x1|Orientation %x2|Force field %x3";
- but = uiDefButS(block, MENU, B_REDR, str, xco+40, yco-23, (width-80), 19, &coa->type, 0.0, 0.0, 0, 0, "");
- yco-= ysize;
- break;
-
- case ACT_SCENE:
- sca= act->data;
-
- if (sca->type==ACT_SCENE_RESTART) {
- ysize= 28;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
- }
- else if (sca->type==ACT_SCENE_CAMERA) {
-
- ysize= 48;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefIDPoinBut(block, test_obpoin_but, ID_OB, 1, "OB:", xco+40, yco-44, (width-80), 19, &(sca->camera), "Set this Camera. Leave empty to refer to self object");
- }
- else if (sca->type==ACT_SCENE_SET) {
-
- ysize= 48;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefIDPoinBut(block, test_scenepoin_but, ID_SCE, 1, "SCE:", xco+40, yco-44, (width-80), 19, &(sca->scene), "Set this Scene");
- }
- else if (sca->type==ACT_SCENE_ADD_FRONT) {
-
- ysize= 48;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefIDPoinBut(block, test_scenepoin_but, ID_SCE, 1, "SCE:", xco+40, yco-44, (width-80), 19, &(sca->scene), "Add an Overlay Scene");
- }
- else if (sca->type==ACT_SCENE_ADD_BACK) {
-
- ysize= 48;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefIDPoinBut(block, test_scenepoin_but, ID_SCE, 1, "SCE:", xco+40, yco-44, (width-80), 19, &(sca->scene), "Add a Background Scene");
- }
- else if (sca->type==ACT_SCENE_REMOVE) {
-
- ysize= 48;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefIDPoinBut(block, test_scenepoin_but, ID_SCE, 1, "SCE:", xco+40, yco-44, (width-80), 19, &(sca->scene), "Remove a Scene");
- }
- else if (sca->type==ACT_SCENE_SUSPEND) {
-
- ysize= 48;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefIDPoinBut(block, test_scenepoin_but, ID_SCE, 1, "SCE:", xco+40, yco-44, (width-80), 19, &(sca->scene), "Pause a Scene");
- }
- else if (sca->type==ACT_SCENE_RESUME) {
-
- ysize= 48;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefIDPoinBut(block, test_scenepoin_but, ID_SCE, 1, "SCE:", xco+40, yco-44, (width-80), 19, &(sca->scene), "Unpause a Scene");
- }
-
- str= "Scene %t|Restart %x0|Set Scene %x1|Set Camera %x2|Add OverlayScene %x3|Add BackgroundScene %x4|Remove Scene %x5|Suspend Scene %x6|Resume Scene %x7";
- uiDefButS(block, MENU, B_REDR, str, xco+40, yco-24, (width-80), 19, &sca->type, 0.0, 0.0, 0, 0, "");
-
- yco-= ysize;
- break;
- case ACT_GAME:
- {
- gma = act->data;
- if (gma->type == ACT_GAME_LOAD) {
- //ysize = 68;
- ysize = 48;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
- uiDefBut(block, TEX, 1, "File: ", xco+10, yco-44, width-20, 19, &(gma->filename), 0, sizeof(gma->filename), 0, 0, "Load this blend file, use the \"//\" prefix for a path relative to the current blend file");
- // uiDefBut(block, TEX, 1, "Anim: ", xco+10, yco-64, width-20, 19, &(gma->loadaniname), 0, sizeof(gma->loadaniname), 0, 0, "Use this loadinganimation");
- }
-#if 0
- else if (gma->type == ACT_GAME_START) {
- ysize = 68;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- uiDefBut(block, TEX, 1, "File: ", xco+10, yco-44, width-20, 19, &(gma->filename), 0, sizeof(gma->filename), 0, 0, "Load this file");
- uiDefBut(block, TEX, 1, "Anim: ", xco+10, yco-64, width-20, 19, &(gma->loadaniname), 0, sizeof(gma->loadaniname), 0, 0, "Use this loadinganimation");
- }
-#endif
- else if (ELEM4(gma->type, ACT_GAME_RESTART, ACT_GAME_QUIT, ACT_GAME_SAVECFG, ACT_GAME_LOADCFG)) {
- ysize = 28;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
- }
-
- //str = "Scene %t|Load game%x0|Start loaded game%x1|Restart this game%x2|Quit this game %x3";
- str = "Scene %t|Start new game%x0|Restart this game%x2|Quit this game %x3|Save bge.logic.globalDict %x4|Load bge.logic.globalDict %x5";
- uiDefButS(block, MENU, B_REDR, str, xco+40, yco-24, (width-80), 19, &gma->type, 0.0, 0.0, 0, 0, "");
-
- yco -= ysize;
- break;
- }
- case ACT_GROUP:
- ga= act->data;
-
- ysize= 52;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- str= "GroupKey types %t|Set Key %x6|Play %x0|Ping Pong %x1|Flipper %x2|Loop Stop %x3|Loop End %x4|Property %x5";
-
- uiDefButS(block, MENU, 1, str, xco+20, yco-24, width-40, 19, &ga->type, 0, 0, 0, 0, "");
- if (ga->type==ACT_GROUP_SET) {
- uiDefBut(block, TEX, 0, "Key: ", xco+20, yco-44, (width-10)/2, 19, ga->name, 0.0, MAX_NAME, 0, 0, "This name defines groupkey to be set");
- uiDefButI(block, NUM, 0, "Frame:", xco+20+(width-10)/2, yco-44, (width-70)/2, 19, &ga->sta, 0.0, 2500.0, 0, 0, "Set this frame");
- }
- else if (ga->type==ACT_GROUP_FROM_PROP) {
- uiDefBut(block, TEX, 0, "Prop: ", xco+20, yco-44, width-40, 19, ga->name, 0.0, MAX_NAME, 0, 0, "Use this property to define the Group position");
- }
- else {
- uiDefButI(block, NUM, 0, "State", xco+20, yco-44, (width-40)/2, 19, &ga->sta, 0.0, 2500.0, 0, 0, "Start frame");
- uiDefButI(block, NUM, 0, "End", xco+20+(width-40)/2, yco-44, (width-40)/2, 19, &ga->end, 0.0, 2500.0, 0, 0, "End frame");
- }
- yco-= ysize;
- break;
-
- case ACT_VISIBILITY:
- ysize = 24;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco,
- (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- visAct = act->data;
-
- uiBlockBeginAlign(block);
- uiDefButBitI(block, TOGN, ACT_VISIBILITY_INVISIBLE, B_REDR,
- "Visible",
- xco + 10, yco - 20, (width - 20)/3, 19, &visAct->flag,
- 0.0, 0.0, 0, 0,
- "Set the objects visible. Initialized from the objects render restriction toggle (access in the outliner)");
- uiDefButBitI(block, TOG, ACT_VISIBILITY_OCCLUSION, B_REDR,
- "Occlusion",
- xco + 10 + ((width - 20)/3), yco - 20, (width - 20)/3, 19, &visAct->flag,
- 0.0, 0.0, 0, 0,
- "Set the object to occlude objects behind it. Initialized from the object type in physics button");
- uiBlockEndAlign(block);
-
- uiDefButBitI(block, TOG, ACT_VISIBILITY_RECURSIVE, 0,
- "Children",
- xco + 10 + (((width - 20)/3)*2)+10, yco - 20, ((width - 20)/3)-10, 19, &visAct->flag,
- 0.0, 0.0, 0, 0,
- "Sets all the children of this object to the same visibility/occlusion recursively");
-
- yco-= ysize;
-
- break;
-
- case ACT_STATE:
- ysize = 34;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco,
- (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- staAct = act->data;
-
- str= "Operation %t|Cpy %x0|Add %x1|Sub %x2|Inv %x3";
-
- uiDefButI(block, MENU, B_REDR, str,
- xco + 10, yco - 24, 65, 19, &staAct->type,
- 0.0, 0.0, 0, 0,
- "Select the bit operation on object state mask");
-
- for (wval=0; wval<15; wval+=5) {
- uiBlockBeginAlign(block);
- for (stbit=0; stbit<5; stbit++) {
- but = uiDefButBitI(block, TOG, 1<<(stbit+wval), stbit+wval, "", (short)(xco+85+12*stbit+13*wval), yco-17, 12, 12, (int *)&(staAct->mask), 0, 0, 0, 0, get_state_name(ob, (short)(stbit+wval)));
- uiButSetFunc(but, check_state_mask, but, &(staAct->mask));
- }
- for (stbit=0; stbit<5; stbit++) {
- but = uiDefButBitI(block, TOG, 1<<(stbit+wval+15), stbit+wval+15, "", (short)(xco+85+12*stbit+13*wval), yco-29, 12, 12, (int *)&(staAct->mask), 0, 0, 0, 0, get_state_name(ob, (short)(stbit+wval+15)));
- uiButSetFunc(but, check_state_mask, but, &(staAct->mask));
- }
- }
- uiBlockEndAlign(block);
-
- yco-= ysize;
-
- break;
-
- case ACT_RANDOM:
- ysize = 69;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco,
- (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- randAct = act->data;
-
- /* 1. seed */
- uiDefButI(block, NUM, 1, "Seed: ", (xco+10), yco-24, 0.4 *(width-20), 19,
- &randAct->seed, 0, 1000, 0, 0,
- "Initial seed of the random generator. Use Python for more freedom. "
- " (Choose 0 for not random)");
-
- /* 2. distribution type */
- /* One pick per distribution. These numbers MUST match the #defines */
- /* in game.h !!! */
- str= "Distribution %t|Bool Constant %x0|Bool Uniform %x1"
- "|Bool Bernoulli %x2|Int Constant %x3|Int Uniform %x4"
- "|Int Poisson %x5|Float Constant %x6|Float Uniform %x7"
- "|Float Normal %x8|Float Neg. Exp. %x9";
- uiDefButI(block, MENU, B_REDR, str, (xco+10) + 0.4 * (width-20), yco-24, 0.6 * (width-20), 19,
- &randAct->distribution, 0.0, 0.0, 0, 0,
- "Choose the type of distribution");
-
- /* 3. property */
- uiDefBut(block, TEX, 1, "Property:", (xco+10), yco-44, (width-20), 19,
- &randAct->propname, 0, MAX_NAME, 0, 0,
- "Assign the random value to this property");
-
- /*4. and 5. arguments for the distribution*/
- switch (randAct->distribution) {
- case ACT_RANDOM_BOOL_CONST:
- uiDefButBitI(block, TOG, 1, 1, "Always true", (xco+10), yco-64, (width-20), 19,
- &randAct->int_arg_1, 2.0, 1, 0, 0,
- "Always false or always true");
- break;
- case ACT_RANDOM_BOOL_UNIFORM:
- uiDefBut(block, LABEL, 0, " Do a 50-50 pick", (xco+10), yco-64, (width-20), 19,
- NULL, 0, 0, 0, 0,
- "Choose between true and false, 50% chance each");
- break;
- case ACT_RANDOM_BOOL_BERNOUILLI:
- uiDefButF(block, NUM, 1, "Chance", (xco+10), yco-64, (width-20), 19,
- &randAct->float_arg_1, 0.0, 1.0, 0, 0,
- "Pick a number between 0 and 1. Success if you stay "
- "below this value");
- break;
- case ACT_RANDOM_INT_CONST:
- uiDefButI(block, NUM, 1, "Value: ", (xco+10), yco-64, (width-20), 19,
- &randAct->int_arg_1, -1000, 1000, 0, 0,
- "Always return this number");
- break;
- case ACT_RANDOM_INT_UNIFORM:
- uiDefButI(block, NUM, 1, "Min: ", (xco+10), yco-64, (width-20)/2, 19,
- &randAct->int_arg_1, -1000, 1000, 0, 0,
- "Choose a number from a range. "
- "Lower boundary of the range");
- uiDefButI(block, NUM, 1, "Max: ", (xco+10) + (width-20)/2, yco-64, (width-20)/2, 19,
- &randAct->int_arg_2, -1000, 1000, 0, 0,
- "Choose a number from a range. "
- "Upper boundary of the range");
- break;
- case ACT_RANDOM_INT_POISSON:
- uiDefButF(block, NUM, 1, "Mean: ", (xco+10), yco-64, (width-20), 19,
- &randAct->float_arg_1, 0.01, 100.0, 0, 0,
- "Expected mean value of the distribution");
- break;
- case ACT_RANDOM_FLOAT_CONST:
- uiDefButF(block, NUM, 1, "Value: ", (xco+10), yco-64, (width-20), 19,
- &randAct->float_arg_1, 0.0, 1.0, 0, 0,
- "Always return this number");
- break;
- case ACT_RANDOM_FLOAT_UNIFORM:
- uiDefButF(block, NUM, 1, "Min: ", (xco+10), yco-64, (width-20)/2, 19,
- &randAct->float_arg_1, -10000.0, 10000.0, 0, 0,
- "Choose a number from a range"
- "Lower boundary of the range");
- uiDefButF(block, NUM, 1, "Max: ", (xco+10) + (width-20)/2, yco-64, (width-20)/2, 19,
- &randAct->float_arg_2, -10000.0, 10000.0, 0, 0,
- "Choose a number from a range"
- "Upper boundary of the range");
- break;
- case ACT_RANDOM_FLOAT_NORMAL:
- uiDefButF(block, NUM, 1, "Mean: ", (xco+10), yco-64, (width-20)/2, 19,
- &randAct->float_arg_1, -10000.0, 10000.0, 0, 0,
- "A normal distribution. Mean of the distribution");
- uiDefButF(block, NUM, 1, "SD: ", (xco+10) + (width-20)/2, yco-64, (width-20)/2, 19,
- &randAct->float_arg_2, 0.0, 10000.0, 0, 0,
- "A normal distribution. Standard deviation of the "
- "distribution");
- break;
- case ACT_RANDOM_FLOAT_NEGATIVE_EXPONENTIAL:
- uiDefButF(block, NUM, 1, "Half-life time: ", (xco+10), yco-64, (width-20), 19,
- &randAct->float_arg_1, 0.001, 10000.0, 0, 0,
- "Negative exponential dropoff");
- break;
- default:
- ; /* don't know what this distro is... can be useful for testing */
- /* though :) */
- }
-
- yco-= ysize;
- break;
- case ACT_MESSAGE:
- ma = act->data;
-
- ysize = 4 + (3 * 24); /* footer + number of lines * 24 pixels/line */
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize,
- (float)xco+width, (float)yco, 1);
-
- myline=1;
-
- /* line 1: To */
- uiDefBut(block, TEX, 1, "To: ",
- (xco+10), (yco-(myline++*24)), (width-20), 19,
- &ma->toPropName, 0, MAX_NAME, 0, 0,
- "Optional send message to objects with this name only, or empty to broadcast");
-
- /* line 2: Message Subject */
- uiDefBut(block, TEX, 1, "Subject: ",
- (xco+10), (yco-(myline++*24)), (width-20), 19,
- &ma->subject, 0, MAX_NAME, 0, 0,
- "Optional message subject. This is what can be filtered on");
-
- /* line 3: Text/Property */
- uiDefButBitS(block, TOG, 1, B_REDR, "T/P",
- (xco+10), (yco-(myline*24)), (0.20 * (width-20)), 19,
- &ma->bodyType, 0.0, 0.0, 0, 0,
- "Toggle message type: either Text or a PropertyName");
-
- if (ma->bodyType == ACT_MESG_MESG) {
- /* line 3: Message Body */
- uiDefBut(block, TEX, 1, "Body: ",
- (xco+10+(0.20*(width-20))), (yco-(myline++*24)), (0.8*(width-20)), 19,
- &ma->body, 0, MAX_NAME, 0, 0,
- "Optional message body Text");
- }
- else {
- /* line 3: Property body (set by property) */
- uiDefBut(block, TEX, 1, "Propname: ",
- (xco+10+(0.20*(width-20))), (yco-(myline++*24)), (0.8*(width-20)), 19,
- &ma->body, 0, MAX_NAME, 0, 0,
- "The message body will be set by the Property Value");
- }
-
- yco -= ysize;
- break;
- case ACT_2DFILTER:
- tdfa = act->data;
-
- ysize = 50;
- if (tdfa->type == ACT_2DFILTER_CUSTOMFILTER) {
- ysize +=20;
- }
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- switch (tdfa->type) {
- case ACT_2DFILTER_MOTIONBLUR:
- if (!tdfa->flag) {
- uiDefButS(block, TOG, B_REDR, "D", xco+30, yco-44, 19, 19, &tdfa->flag, 0.0, 0.0, 0.0, 0.0, "Disable Motion Blur");
- uiDefButF(block, NUM, B_REDR, "Value:", xco+52, yco-44, width-82, 19, &tdfa->float_arg, 0.0, 1.0, 0.0, 0.0, "Set motion blur value");
- }
- else {
- uiDefButS(block, TOG, B_REDR, "Disabled", xco+30, yco-44, width-60, 19, &tdfa->flag, 0.0, 0.0, 0.0, 0.0, "Enable Motion Blur");
- }
- break;
- case ACT_2DFILTER_BLUR:
- case ACT_2DFILTER_SHARPEN:
- case ACT_2DFILTER_DILATION:
- case ACT_2DFILTER_EROSION:
- case ACT_2DFILTER_LAPLACIAN:
- case ACT_2DFILTER_SOBEL:
- case ACT_2DFILTER_PREWITT:
- case ACT_2DFILTER_GRAYSCALE:
- case ACT_2DFILTER_SEPIA:
- case ACT_2DFILTER_INVERT:
- case ACT_2DFILTER_NOFILTER:
- case ACT_2DFILTER_DISABLED:
- case ACT_2DFILTER_ENABLED:
- uiDefButI(block, NUM, B_REDR, "Pass Number:", xco+30, yco-44, width-60, 19, &tdfa->int_arg, 0.0, MAX_RENDER_PASS-1, 0.0, 0.0, "Set filter order");
- break;
- case ACT_2DFILTER_CUSTOMFILTER:
- uiDefButI(block, NUM, B_REDR, "Pass Number:", xco+30, yco-44, width-60, 19, &tdfa->int_arg, 0.0, MAX_RENDER_PASS-1, 0.0, 0.0, "Set filter order");
- uiDefIDPoinBut(block, test_scriptpoin_but, ID_SCRIPT, 1, "Script: ", xco+30, yco-64, width-60, 19, &tdfa->text, "");
- break;
- }
-
- str= "2D Filter %t|Motion Blur %x1|Blur %x2|Sharpen %x3|Dilation %x4|Erosion %x5|"
- "Laplacian %x6|Sobel %x7|Prewitt %x8|Gray Scale %x9|Sepia %x10|Invert %x11|Custom Filter %x12|"
- "Enable Filter %x-2|Disable Filter %x-1|Remove Filter %x0|";
- uiDefButS(block, MENU, B_REDR, str, xco+30, yco-24, width-60, 19, &tdfa->type, 0.0, 0.0, 0.0, 0.0, "2D filter type");
-
- yco -= ysize;
- break;
- case ACT_PARENT:
- parAct = act->data;
-
- if (parAct->type==ACT_PARENT_SET) {
-
- ysize= 48;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
- uiDefIDPoinBut(block, test_obpoin_but, ID_OB, 1, "OB:", xco+95, yco-24, (width-100), 19, &(parAct->ob), "Set this object as parent");
- uiBlockBeginAlign(block);
- uiDefButBitS(block, TOGN, ACT_PARENT_COMPOUND, B_REDR,
- "Compound",
- xco + 5, yco - 44, (width - 10)/2, 19, &parAct->flag,
- 0.0, 0.0, 0, 0,
- "Add this object shape to the parent shape (only if the parent shape is already compound)");
- uiDefButBitS(block, TOGN, ACT_PARENT_GHOST, B_REDR,
- "Ghost",
- xco + 5 + ((width - 10)/2), yco - 44, (width - 10)/2, 19, &parAct->flag,
- 0.0, 0.0, 0, 0,
- "Make this object ghost while parented (only if not compound)");
- uiBlockEndAlign(block);
- }
- else if (parAct->type==ACT_PARENT_REMOVE) {
-
- ysize= 28;
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
- }
-
- str= "Parent %t|Set Parent %x0|Remove Parent %x1";
- uiDefButI(block, MENU, B_REDR, str, xco+5, yco-24, parAct->type==1?(width-80):90, 19, &parAct->type, 0.0, 0.0, 0, 0, "");
-
- yco-= ysize;
- break;
- case ACT_ARMATURE:
- armAct = act->data;
-
- if (ob->type == OB_ARMATURE) {
- str= "Constraint %t|Run armature %x0|Enable %x1|Disable %x2|Set target %x3|Set weight %x4";
- uiDefButI(block, MENU, B_REDR, str, xco+5, yco-24, (width-10)*0.35, 19, &armAct->type, 0.0, 0.0, 0, 0, "");
-
- switch (armAct->type) {
- case ACT_ARM_RUN:
- ysize = 28;
- break;
- default:
- uiBlockBeginAlign(block);
- but = uiDefBut(block, TEX, 1, "Bone: ",
- (xco+5), (yco-44), (width-10)/2, 19,
- armAct->posechannel, 0, MAX_NAME, 0, 0,
- "Bone on which the constraint is defined");
- uiButSetFunc(but, check_armature_actuator, but, armAct);
- but = uiDefBut(block, TEX, 1, "Cons: ",
- (xco+5)+(width-10)/2, (yco-44), (width-10)/2, 19,
- armAct->constraint, 0, MAX_NAME, 0, 0,
- "Name of the constraint you want to control");
- uiButSetFunc(but, check_armature_actuator, but, armAct);
- uiBlockEndAlign(block);
- ysize = 48;
- switch (armAct->type) {
- case ACT_ARM_SETTARGET:
- uiDefIDPoinBut(block, test_obpoin_but, ID_OB, 1, "Target: ", xco+5, yco-64, (width-10), 19, &(armAct->target), "Set this object as the target of the constraint");
- uiDefIDPoinBut(block, test_obpoin_but, ID_OB, 1, "Secondary Target: ", xco+5, yco-84, (width-10), 19, &(armAct->subtarget), "Set this object as the secondary target of the constraint (only IK polar target at the moment)");
- ysize += 40;
- break;
- case ACT_ARM_SETWEIGHT:
- uiDefButF(block, NUM, B_REDR, "Weight:", xco+5+(width-10)*0.35, yco-24, (width-10)*0.65, 19, &armAct->weight, 0.0, 1.0, 0.0, 0.0, "Set weight of this constraint");
- break;
- }
- }
- }
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
- yco-= ysize;
- break;
-
- default:
- ysize= 4;
-
- glRects(xco, yco-ysize, xco+width, yco);
- uiEmboss((float)xco, (float)yco-ysize, (float)xco+width, (float)yco, 1);
-
- yco-= ysize;
- break;
- }
-
- uiBlockSetEmboss(block, UI_EMBOSS);
-
- return yco-4;
-}
static void do_sensor_menu(bContext *C, void *UNUSED(arg), int event)
{
@@ -2974,11 +772,11 @@ static uiBlock *sensor_menu(bContext *C, ARegion *ar, void *UNUSED(arg))
block= uiBeginBlock(C, ar, __func__, UI_EMBOSSP);
uiBlockSetButmFunc(block, do_sensor_menu, NULL);
- uiDefBut(block, BUTM, 1, "Show Objects", 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 0, "");
- uiDefBut(block, BUTM, 1, "Hide Objects", 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 1, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Show Objects"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 0, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Hide Objects"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 1, "");
uiDefBut(block, SEPR, 0, "", 0, (short)(yco-=6), 160, 6, NULL, 0.0, 0.0, 0, 0, "");
- uiDefBut(block, BUTM, 1, "Show Sensors", 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 2, "");
- uiDefBut(block, BUTM, 1, "Hide Sensors", 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 3, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Show Sensors"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 2, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Hide Sensors"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 3, "");
uiBlockSetDirection(block, UI_TOP);
uiEndBlock(C, block);
@@ -3023,11 +821,11 @@ static uiBlock *controller_menu(bContext *C, ARegion *ar, void *UNUSED(arg))
block= uiBeginBlock(C, ar, __func__, UI_EMBOSSP);
uiBlockSetButmFunc(block, do_controller_menu, NULL);
- uiDefBut(block, BUTM, 1, "Show Objects", 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 0, "");
- uiDefBut(block, BUTM, 1, "Hide Objects", 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 1, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Show Objects"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 0, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Hide Objects"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 1, "");
uiDefBut(block, SEPR, 0, "", 0, (short)(yco-=6), 160, 6, NULL, 0.0, 0.0, 0, 0, "");
- uiDefBut(block, BUTM, 1, "Show Controllers", 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 2, 2, "");
- uiDefBut(block, BUTM, 1, "Hide Controllers", 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 3, 3, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Show Controllers"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 2, 2, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Hide Controllers"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 3, 3, "");
uiBlockSetDirection(block, UI_TOP);
uiEndBlock(C, block);
@@ -3072,11 +870,11 @@ static uiBlock *actuator_menu(bContext *C, ARegion *ar, void *UNUSED(arg))
block= uiBeginBlock(C, ar, __func__, UI_EMBOSSP);
uiBlockSetButmFunc(block, do_actuator_menu, NULL);
- uiDefBut(block, BUTM, 1, "Show Objects", 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 0, "");
- uiDefBut(block, BUTM, 1, "Hide Objects", 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 1, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Show Objects"), 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 0, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Hide Objects"), 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 1, "");
uiDefBut(block, SEPR, 0, "", 0, (short)(xco-=6), 160, 6, NULL, 0.0, 0.0, 0, 0, "");
- uiDefBut(block, BUTM, 1, "Show Actuators", 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 2, "");
- uiDefBut(block, BUTM, 1, "Hide Actuators", 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 3, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Show Actuators"), 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 2, "");
+ uiDefBut(block, BUTM, 1, IFACE_("Hide Actuators"), 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 3, "");
uiBlockSetDirection(block, UI_TOP);
uiEndBlock(C, block);
@@ -3084,8 +882,6 @@ static uiBlock *actuator_menu(bContext *C, ARegion *ar, void *UNUSED(arg))
return block;
}
-
-
static void check_controller_state_mask(bContext *UNUSED(C), void *arg1_but, void *arg2_mask)
{
unsigned int *cont_mask = arg2_mask;
@@ -3096,17 +892,6 @@ static void check_controller_state_mask(bContext *UNUSED(C), void *arg1_but, voi
but->retval = B_REDR;
}
-static int first_bit(unsigned int mask)
-{
- int bit;
-
- for (bit=0; bit<32; bit++) {
- if (mask & (1<<bit))
- return bit;
- }
- return -1;
-}
-
static uiBlock *controller_state_mask_menu(bContext *C, ARegion *ar, void *arg_cont)
{
uiBlock *block;
@@ -3120,7 +905,7 @@ static uiBlock *controller_state_mask_menu(bContext *C, ARegion *ar, void *arg_c
/* use this for a fake extra empy space around the buttons */
uiDefBut(block, LABEL, 0, "", -5, -5, 200, 34, NULL, 0, 0, 0, 0, "");
- for (offset=0; offset<15; offset+=5) {
+ for (offset=0; offset<15; offset += 5) {
uiBlockBeginAlign(block);
for (stbit=0; stbit<5; stbit++) {
but = uiDefButBitI(block, TOG, (1<<(stbit+offset)), (stbit+offset), "", (short)(xco+12*stbit+13*offset), yco, 12, 12, (int *)&(cont->state_mask), 0, 0, 0, 0, "");
@@ -3139,44 +924,6 @@ static uiBlock *controller_state_mask_menu(bContext *C, ARegion *ar, void *arg_c
return block;
}
-static void do_object_state_menu(bContext *UNUSED(C), void *arg, int event)
-{
- Object *ob = arg;
-
- switch (event) {
- case 0:
- ob->state = 0x3FFFFFFF;
- break;
- case 1:
- ob->state = ob->init_state;
- if (!ob->state)
- ob->state = 1;
- break;
- case 2:
- ob->init_state = ob->state;
- break;
- }
-}
-
-static uiBlock *object_state_mask_menu(bContext *C, ARegion *ar, void *arg_obj)
-{
- uiBlock *block;
- short xco = 0;
-
- block= uiBeginBlock(C, ar, __func__, UI_EMBOSSP);
- uiBlockSetButmFunc(block, do_object_state_menu, arg_obj);
-
- uiDefBut(block, BUTM, 1, "Set all bits", 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 0, "");
- uiDefBut(block, BUTM, 1, "Recall init state", 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 1, "");
- uiDefBut(block, SEPR, 0, "", 0, (short)(xco-=6), 160, 6, NULL, 0.0, 0.0, 0, 0, "");
- uiDefBut(block, BUTM, 1, "Store init state", 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 2, "");
-
- uiBlockSetDirection(block, UI_TOP);
- uiEndBlock(C, block);
-
- return block;
-}
-
static int is_sensor_linked(uiBlock *block, bSensor *sens)
{
bController *cont;
@@ -3238,13 +985,13 @@ static void draw_sensor_internal_header(uiLayout *layout, PointerRNA *ptr)
sub = uiLayoutRow(row, FALSE);
uiLayoutSetActive(sub, (RNA_boolean_get(ptr, "use_pulse_true_level") ||
RNA_boolean_get(ptr, "use_pulse_false_level")));
- uiItemR(sub, ptr, "frequency", 0, "Freq", ICON_NONE);
+ uiItemR(sub, ptr, "frequency", 0, IFACE_("Freq"), ICON_NONE);
row = uiLayoutRow(split, TRUE);
uiItemR(row, ptr, "use_level", UI_ITEM_R_TOGGLE, NULL, ICON_NONE);
uiItemR(row, ptr, "use_tap", UI_ITEM_R_TOGGLE, NULL, ICON_NONE);
- uiItemR(split, ptr, "invert", UI_ITEM_R_TOGGLE, "Invert", ICON_NONE);
+ uiItemR(split, ptr, "invert", UI_ITEM_R_TOGGLE, IFACE_("Invert"), ICON_NONE);
}
/* sensors in alphabetical order */
@@ -3267,7 +1014,7 @@ static void draw_sensor_armature(uiLayout *layout, PointerRNA *ptr)
uiLayout *row;
if (ob->type != OB_ARMATURE) {
- uiItemL(layout, "Sensor only available for armatures", ICON_NONE);
+ uiItemL(layout, IFACE_("Sensor only available for armatures"), ICON_NONE);
return;
}
@@ -3369,7 +1116,7 @@ static void draw_sensor_keyboard(uiLayout *layout, PointerRNA *ptr)
uiLayout *row, *col;
row = uiLayoutRow(layout, FALSE);
- uiItemL(row, "Key:", ICON_NONE);
+ uiItemL(row, IFACE_("Key:"), ICON_NONE);
col = uiLayoutColumn(row, FALSE);
uiLayoutSetActive(col, RNA_boolean_get(ptr, "use_all_keys") == FALSE);
uiItemR(col, ptr, "key", UI_ITEM_R_EVENT, "", ICON_NONE);
@@ -3379,11 +1126,11 @@ static void draw_sensor_keyboard(uiLayout *layout, PointerRNA *ptr)
col = uiLayoutColumn(layout, FALSE);
uiLayoutSetActive(col, RNA_boolean_get(ptr, "use_all_keys") == FALSE);
row = uiLayoutRow(col, FALSE);
- uiItemL(row, "First Modifier:", ICON_NONE);
+ uiItemL(row, IFACE_("First Modifier:"), ICON_NONE);
uiItemR(row, ptr, "modifier_key_1", UI_ITEM_R_EVENT, "", ICON_NONE);
row = uiLayoutRow(col, FALSE);
- uiItemL(row, "Second Modifier:", ICON_NONE);
+ uiItemL(row, IFACE_("Second Modifier:"), ICON_NONE);
uiItemR(row, ptr, "modifier_key_2", UI_ITEM_R_EVENT, "", ICON_NONE);
RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr);
@@ -3569,7 +1316,7 @@ static void draw_controller_header(uiLayout *layout, PointerRNA *ptr, int xco, i
uiItemR(row, ptr, "type", 0, "", ICON_NONE);
uiItemR(row, ptr, "name", 0, "", ICON_NONE);
/* XXX provisory for Blender 2.50Beta */
- uiDefBlockBut(uiLayoutGetBlock(layout), controller_state_mask_menu, cont, state, (short)(xco+width-44), yco, 22+22, UI_UNIT_Y, "Set controller state index (from 1 to 30)");
+ uiDefBlockBut(uiLayoutGetBlock(layout), controller_state_mask_menu, cont, state, (short)(xco+width-44), yco, 22+22, UI_UNIT_Y, IFACE_("Set controller state index (from 1 to 30)"));
}
else {
uiItemL(row, controller_name(cont->type), ICON_NONE);
@@ -3737,7 +1484,7 @@ static void draw_actuator_armature(uiLayout *layout, PointerRNA *ptr)
PropertyRNA *bones_prop = NULL;
if (ob->type != OB_ARMATURE) {
- uiItemL(layout, "Actuator only available for armatures", ICON_NONE);
+ uiItemL(layout, IFACE_("Actuator only available for armatures"), ICON_NONE);
return;
}
@@ -3843,7 +1590,7 @@ static void draw_actuator_constraint(uiLayout *layout, PointerRNA *ptr, bContext
row = uiLayoutRow(layout, FALSE);
col = uiLayoutColumn(row, TRUE);
- uiItemL(col, "Range:", ICON_NONE);
+ uiItemL(col, IFACE_("Range:"), ICON_NONE);
uiItemR(col, ptr, "range", 0, "", ICON_NONE);
col = uiLayoutColumn(row, TRUE);
@@ -3941,7 +1688,7 @@ static void draw_actuator_edit_object(uiLayout *layout, PointerRNA *ptr)
break;
case ACT_EDOB_REPLACE_MESH:
if (ob->type != OB_MESH) {
- uiItemL(layout, "Mode only available for mesh objects", ICON_NONE);
+ uiItemL(layout, IFACE_("Mode only available for mesh objects"), ICON_NONE);
break;
}
split = uiLayoutSplit(layout, 0.6, FALSE);
@@ -3959,7 +1706,7 @@ static void draw_actuator_edit_object(uiLayout *layout, PointerRNA *ptr)
break;
case ACT_EDOB_DYNAMICS:
if (ob->type != OB_MESH) {
- uiItemL(layout, "Mode only available for mesh objects", ICON_NONE);
+ uiItemL(layout, IFACE_("Mode only available for mesh objects"), ICON_NONE);
break;
}
uiItemR(layout, ptr, "dynamic_operation", 0, NULL, ICON_NONE);
@@ -4029,7 +1776,7 @@ static void draw_actuator_motion(uiLayout *layout, PointerRNA *ptr)
uiLayout *split, *row, *col, *sub;
int physics_type;
- ob = (Object *)ptr->id.data;
+ ob = (Object *)ptr->id.data;
RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr);
physics_type = RNA_enum_get(&settings_ptr, "physics_type");
@@ -4047,8 +1794,8 @@ static void draw_actuator_motion(uiLayout *layout, PointerRNA *ptr)
uiItemR(row, ptr, "offset_rotation", 0, NULL, ICON_NONE);
uiItemR(split, ptr, "use_local_rotation", UI_ITEM_R_TOGGLE, NULL, ICON_NONE);
- if (ELEM3(physics_type, OB_BODY_TYPE_DYNAMIC, OB_BODY_TYPE_RIGID, OB_BODY_TYPE_SOFT)) {
- uiItemL(layout, "Dynamic Object Settings:", ICON_NONE);
+ if (ELEM3(physics_type, OB_BODY_TYPE_DYNAMIC, OB_BODY_TYPE_RIGID, OB_BODY_TYPE_SOFT)) {
+ uiItemL(layout, IFACE_("Dynamic Object Settings:"), ICON_NONE);
split = uiLayoutSplit(layout, 0.9, FALSE);
row = uiLayoutRow(split, FALSE);
uiItemR(row, ptr, "force", 0, NULL, ICON_NONE);
@@ -4198,7 +1945,7 @@ static void draw_actuator_random(uiLayout *layout, PointerRNA *ptr)
break;
case ACT_RANDOM_BOOL_UNIFORM:
- uiItemL(row, "Choose between true and false, 50% chance each", ICON_NONE);
+ uiItemL(row, IFACE_("Choose between true and false, 50% chance each"), ICON_NONE);
break;
case ACT_RANDOM_BOOL_BERNOUILLI:
@@ -4261,7 +2008,7 @@ static void draw_actuator_shape_action(uiLayout *layout, PointerRNA *ptr)
uiLayout *row;
if (ob->type != OB_MESH) {
- uiItemL(layout, "Actuator only available for mesh objects", ICON_NONE);
+ uiItemL(layout, IFACE_("Actuator only available for mesh objects"), ICON_NONE);
return;
}
@@ -4299,7 +2046,7 @@ static void draw_actuator_sound(uiLayout *layout, PointerRNA *ptr, bContext *C)
uiTemplateID(layout, C, ptr, "sound", NULL, "SOUND_OT_open", NULL);
if (!RNA_pointer_get(ptr, "sound").data) {
- uiItemL(layout, "Select a sound from the list or load a new one", ICON_NONE);
+ uiItemL(layout, IFACE_("Select a sound from the list or load a new one"), ICON_NONE);
return;
}
uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE);
@@ -4458,21 +2205,18 @@ static void draw_brick_actuator(uiLayout *layout, PointerRNA *ptr, bContext *C)
}
}
-static void logic_buttons_new(bContext *C, ARegion *ar)
+void logic_buttons(bContext *C, ARegion *ar)
{
SpaceLogic *slogic= CTX_wm_space_logic(C);
Object *ob= CTX_data_active_object(C);
- Object *act_ob= ob;
ID **idar;
-
- PointerRNA logic_ptr, settings_ptr;
-
+ PointerRNA logic_ptr, settings_ptr, object_ptr;
uiLayout *layout, *row, *box;
uiBlock *block;
uiBut *but;
char uiblockstr[32];
short a, count;
- int xco, yco, width;
+ int xco, yco, width, height;
if (ob==NULL) return;
@@ -4526,15 +2270,15 @@ static void logic_buttons_new(bContext *C, ARegion *ar)
/* ****************** Controllers ****************** */
- xco= 420; yco= 170; width= 300;
+ xco= 420; yco= -10; width= 300;
layout= uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, xco, yco, width, 20, UI_GetStyle());
row = uiLayoutRow(layout, TRUE);
- uiDefBlockBut(block, controller_menu, NULL, "Controllers", xco-10, yco, 300, UI_UNIT_Y, ""); /* replace this with uiLayout stuff later */
+ uiDefBlockBut(block, controller_menu, NULL, IFACE_("Controllers"), xco-10, yco, 300, UI_UNIT_Y, ""); /* replace this with uiLayout stuff later */
- uiItemR(row, &logic_ptr, "show_controllers_selected_objects", 0, "Sel", ICON_NONE);
- uiItemR(row, &logic_ptr, "show_controllers_active_object", 0, "Act", ICON_NONE);
- uiItemR(row, &logic_ptr, "show_controllers_linked_controller", 0, "Link", ICON_NONE);
+ uiItemR(row, &logic_ptr, "show_controllers_selected_objects", 0, IFACE_("Sel"), ICON_NONE);
+ uiItemR(row, &logic_ptr, "show_controllers_active_object", 0, IFACE_("Act"), ICON_NONE);
+ uiItemR(row, &logic_ptr, "show_controllers_linked_controller", 0, IFACE_("Link"), ICON_NONE);
for (a=0; a<count; a++) {
bController *cont;
@@ -4557,9 +2301,11 @@ static void logic_buttons_new(bContext *C, ARegion *ar)
uiItemR(split, &settings_ptr, "show_state_panel", UI_ITEM_R_NO_BG, "", ICON_DISCLOSURE_TRI_RIGHT);
row = uiLayoutRow(split, TRUE);
- uiDefButBitS(block, TOG, OB_SHOWCONT, B_REDR, ob->id.name+2, (short)(xco-10), yco, (short)(width-30), UI_UNIT_Y, &ob->scaflag, 0, 31, 0, 0, "Object name, click to show/hide controllers");
- if (ob == act_ob)
- uiItemMenuEnumO(row, "LOGIC_OT_controller_add", "type", "Add Controller", ICON_NONE);
+ uiDefButBitS(block, TOG, OB_SHOWCONT, B_REDR, ob->id.name+2, (short)(xco-10), yco, (short)(width-30), UI_UNIT_Y, &ob->scaflag, 0, 31, 0, 0, TIP_("Object name, click to show/hide controllers"));
+
+ RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr);
+ uiLayoutSetContextPointer(row, "object", &object_ptr);
+ uiItemMenuEnumO(row, "LOGIC_OT_controller_add", "type", IFACE_("Add Controller"), ICON_NONE);
if (RNA_boolean_get(&settings_ptr, "show_state_panel")) {
@@ -4567,16 +2313,16 @@ static void logic_buttons_new(bContext *C, ARegion *ar)
split = uiLayoutSplit(box, 0.2f, FALSE);
col = uiLayoutColumn(split, FALSE);
- uiItemL(col, "Visible", ICON_NONE);
- uiItemL(col, "Initial", ICON_NONE);
+ uiItemL(col, IFACE_("Visible"), ICON_NONE);
+ uiItemL(col, IFACE_("Initial"), ICON_NONE);
subsplit = uiLayoutSplit(split, 0.85f, FALSE);
col = uiLayoutColumn(subsplit, FALSE);
row = uiLayoutRow(col, FALSE);
uiLayoutSetActive(row, RNA_boolean_get(&settings_ptr, "use_all_states") == FALSE);
- uiTemplateLayers(row, &settings_ptr, "states_visible", &settings_ptr, "used_states", 0);
+ uiTemplateGameStates(row, &settings_ptr, "states_visible", &settings_ptr, "used_states", 0);
row = uiLayoutRow(col, FALSE);
- uiTemplateLayers(row, &settings_ptr, "states_initial", &settings_ptr, "used_states", 0);
+ uiTemplateGameStates(row, &settings_ptr, "states_initial", &settings_ptr, "used_states", 0);
col = uiLayoutColumn(subsplit, FALSE);
uiItemR(col, &settings_ptr, "use_all_states", UI_ITEM_R_TOGGLE, NULL, ICON_NONE);
@@ -4627,20 +2373,20 @@ static void logic_buttons_new(bContext *C, ARegion *ar)
}
}
uiBlockLayoutResolve(block, NULL, &yco); /* stores final height in yco */
-
+ height = yco;
/* ****************** Sensors ****************** */
- xco= 10; yco= 170; width= 340;
+ xco= 10; yco= -10; width= 340;
layout= uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, xco, yco, width, 20, UI_GetStyle());
row = uiLayoutRow(layout, TRUE);
- uiDefBlockBut(block, sensor_menu, NULL, "Sensors", xco-10, yco, 300, UI_UNIT_Y, ""); /* replace this with uiLayout stuff later */
+ uiDefBlockBut(block, sensor_menu, NULL, IFACE_("Sensors"), xco-10, yco, 300, UI_UNIT_Y, ""); /* replace this with uiLayout stuff later */
- uiItemR(row, &logic_ptr, "show_sensors_selected_objects", 0, "Sel", ICON_NONE);
- uiItemR(row, &logic_ptr, "show_sensors_active_object", 0, "Act", ICON_NONE);
- uiItemR(row, &logic_ptr, "show_sensors_linked_controller", 0, "Link", ICON_NONE);
- uiItemR(row, &logic_ptr, "show_sensors_active_states", 0, "State", ICON_NONE);
+ uiItemR(row, &logic_ptr, "show_sensors_selected_objects", 0, IFACE_("Sel"), ICON_NONE);
+ uiItemR(row, &logic_ptr, "show_sensors_active_object", 0, IFACE_("Act"), ICON_NONE);
+ uiItemR(row, &logic_ptr, "show_sensors_linked_controller", 0, IFACE_("Link"), ICON_NONE);
+ uiItemR(row, &logic_ptr, "show_sensors_active_states", 0, IFACE_("State"), ICON_NONE);
for (a=0; a<count; a++) {
bSensor *sens;
@@ -4652,9 +2398,11 @@ static void logic_buttons_new(bContext *C, ARegion *ar)
if ((ob->scavisflag & OB_VIS_SENS) == 0) continue;
row = uiLayoutRow(layout, TRUE);
- uiDefButBitS(block, TOG, OB_SHOWSENS, B_REDR, ob->id.name+2, (short)(xco-10), yco, (short)(width-30), UI_UNIT_Y, &ob->scaflag, 0, 31, 0, 0, "Object name, click to show/hide sensors");
- if (ob == act_ob)
- uiItemMenuEnumO(row, "LOGIC_OT_sensor_add", "type", "Add Sensor", ICON_NONE);
+ uiDefButBitS(block, TOG, OB_SHOWSENS, B_REDR, ob->id.name+2, (short)(xco-10), yco, (short)(width-30), UI_UNIT_Y, &ob->scaflag, 0, 31, 0, 0, TIP_("Object name, click to show/hide sensors"));
+
+ RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr);
+ uiLayoutSetContextPointer(row, "object", &object_ptr);
+ uiItemMenuEnumO(row, "LOGIC_OT_sensor_add", "type", IFACE_("Add Sensor"), ICON_NONE);
if ((ob->scaflag & OB_SHOWSENS) == 0) continue;
@@ -4694,19 +2442,20 @@ static void logic_buttons_new(bContext *C, ARegion *ar)
}
}
uiBlockLayoutResolve(block, NULL, &yco); /* stores final height in yco */
+ height = MIN2(height, yco);
/* ****************** Actuators ****************** */
- xco= 800; yco= 170; width= 340;
+ xco= 800; yco= -10; width= 340;
layout= uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, xco, yco, width, 20, UI_GetStyle());
row = uiLayoutRow(layout, TRUE);
- uiDefBlockBut(block, actuator_menu, NULL, "Actuators", xco-10, yco, 300, UI_UNIT_Y, ""); /* replace this with uiLayout stuff later */
+ uiDefBlockBut(block, actuator_menu, NULL, IFACE_("Actuators"), xco-10, yco, 300, UI_UNIT_Y, ""); /* replace this with uiLayout stuff later */
- uiItemR(row, &logic_ptr, "show_actuators_selected_objects", 0, "Sel", ICON_NONE);
- uiItemR(row, &logic_ptr, "show_actuators_active_object", 0, "Act", ICON_NONE);
- uiItemR(row, &logic_ptr, "show_actuators_linked_controller", 0, "Link", ICON_NONE);
- uiItemR(row, &logic_ptr, "show_actuators_active_states", 0, "State", ICON_NONE);
+ uiItemR(row, &logic_ptr, "show_actuators_selected_objects", 0, IFACE_("Sel"), ICON_NONE);
+ uiItemR(row, &logic_ptr, "show_actuators_active_object", 0, IFACE_("Act"), ICON_NONE);
+ uiItemR(row, &logic_ptr, "show_actuators_linked_controller", 0, IFACE_("Link"), ICON_NONE);
+ uiItemR(row, &logic_ptr, "show_actuators_active_states", 0, IFACE_("State"), ICON_NONE);
for (a=0; a<count; a++) {
bActuator *act;
@@ -4720,9 +2469,11 @@ static void logic_buttons_new(bContext *C, ARegion *ar)
}
row = uiLayoutRow(layout, TRUE);
- uiDefButBitS(block, TOG, OB_SHOWACT, B_REDR, ob->id.name+2, (short)(xco-10), yco, (short)(width-30), UI_UNIT_Y, &ob->scaflag, 0, 31, 0, 0, "Object name, click to show/hide actuators");
- if (ob == act_ob)
- uiItemMenuEnumO(row, "LOGIC_OT_actuator_add", "type", "Add Actuator", ICON_NONE);
+ uiDefButBitS(block, TOG, OB_SHOWACT, B_REDR, ob->id.name+2, (short)(xco-10), yco, (short)(width-30), UI_UNIT_Y, &ob->scaflag, 0, 31, 0, 0, TIP_("Object name, click to show/hide actuators"));
+
+ RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr);
+ uiLayoutSetContextPointer(row, "object", &object_ptr);
+ uiItemMenuEnumO(row, "LOGIC_OT_actuator_add", "type", IFACE_("Add Actuator"), ICON_NONE);
if ((ob->scaflag & OB_SHOWACT) == 0) continue;
@@ -4763,387 +2514,21 @@ static void logic_buttons_new(bContext *C, ARegion *ar)
}
}
uiBlockLayoutResolve(block, NULL, &yco); /* stores final height in yco */
-
-
- uiComposeLinks(block);
-
- uiEndBlock(C, block);
- uiDrawBlock(C, block);
-
- if (idar) MEM_freeN(idar);
-}
-
-void logic_buttons(bContext *C, ARegion *ar)
-{
- Main *bmain= CTX_data_main(C);
- SpaceLogic *slogic= CTX_wm_space_logic(C);
- Object *ob= CTX_data_active_object(C);
- ID **idar;
- bSensor *sens;
- bController *cont;
- bActuator *act;
- uiBlock *block;
- uiBut *but;
- PointerRNA logic_ptr;
- int a, iact, stbit, offset;
- int xco, yco, width, ycoo;
- short count;
- char numstr[32];
- /* pin is a bool used for actuator and sensor drawing with states
- * pin so changing states dosnt hide the logic brick */
- char pin;
-
- if (G.debug_value == 0) {
- logic_buttons_new(C, ar);
- return;
- }
-
- if (ob==NULL) return;
-// uiSetButLock(BKE_object_is_libdata(ob), ERROR_LIBDATA_MESSAGE);
-
- BLI_snprintf(numstr, sizeof(numstr), "buttonswin %p", (void *)ar);
- block= uiBeginBlock(C, ar, numstr, UI_EMBOSS);
- uiBlockSetHandleFunc(block, do_logic_buts, NULL);
-
- RNA_pointer_create(NULL, &RNA_SpaceLogicEditor, slogic, &logic_ptr);
-
- idar= get_selected_and_linked_obs(C, &count, slogic->scaflag);
-
- /* clean ACT_LINKED and ACT_VISIBLE of all potentially visible actuators so that
- * we can determine which is actually linked/visible */
- for (a=0; a<count; a++) {
- ob= (Object *)idar[a];
- act= ob->actuators.first;
- while (act) {
- act->flag &= ~(ACT_LINKED|ACT_VISIBLE);
- act = act->next;
- }
- /* same for sensors */
- sens= ob->sensors.first;
- while (sens) {
- sens->flag &= ~(SENS_VISIBLE);
- sens = sens->next;
- }
- }
-
- /* start with the controller because we need to know which one is visible */
- /* ******************************* */
- xco= 400; yco= 170; width= 300;
+ height = MIN2(height, yco);
- uiDefBlockBut(block, controller_menu, NULL, "Controllers", xco-10, yco+35, 100, UI_UNIT_Y, "");
-
- uiBlockBeginAlign(block);
- uiDefButBitS(block, TOG, BUTS_CONT_SEL, B_REDR, "Sel", xco+110, yco+35, (width-100)/3, UI_UNIT_Y, &slogic->scaflag, 0, 0, 0, 0, "Show all selected Objects");
- uiDefButBitS(block, TOG, BUTS_CONT_ACT, B_REDR, "Act", xco+110+(width-100)/3, yco+35, (width-100)/3, UI_UNIT_Y, &slogic->scaflag, 0, 0, 0, 0, "Show active Object");
- uiDefButBitS(block, TOG, BUTS_CONT_LINK, B_REDR, "Link", xco+110+2*(width-100)/3, yco+35, (width-100)/3, UI_UNIT_Y, &slogic->scaflag, 0, 0, 0, 0, "Show linked Objects to Sensor/Actuator");
- uiBlockEndAlign(block);
+ UI_view2d_totRect_set(&ar->v2d, 1150, height);
- for (a=0; a<count; a++) {
- unsigned int controller_state_mask = 0; /* store a bitmask for states that are used */
-
- ob= (Object *)idar[a];
-// uiClearButLock();
-// uiSetButLock(BKE_object_is_libdata(ob), ERROR_LIBDATA_MESSAGE);
- if ((ob->scavisflag & OB_VIS_CONT) == 0) {
- continue;
- }
-
- /* presume it is only objects for now */
- uiBlockBeginAlign(block);
-// if (ob->controllers.first) uiSetCurFont(block, UI_HELVB);
- uiDefButBitS(block, TOG, OB_SHOWCONT, B_REDR, ob->id.name+2, (short)(xco-10), yco, (short)(width-30), UI_UNIT_Y, &ob->scaflag, 0, 0, 0, 0, "Active Object name");
-// if (ob->controllers.first) uiSetCurFont(block, UI_HELV);
- uiDefButBitS(block, TOG, OB_ADDCONT, B_ADD_CONT, "Add", (short)(xco+width-40), yco, 50, UI_UNIT_Y, &ob->scaflag, 0, 0, 0, 0, "Add a new Controller");
- uiBlockEndAlign(block);
- yco-=20;
-
- /* mark all actuators linked to these controllers */
- /* note that some of these actuators could be from objects that are not in the display list.
- * It's ok because those actuators will not be displayed here */
- cont= ob->controllers.first;
- while (cont) {
- for (iact=0; iact<cont->totlinks; iact++) {
- act = cont->links[iact];
- if (act)
- act->flag |= ACT_LINKED;
- }
- controller_state_mask |= cont->state_mask;
- cont = cont->next;
- }
-
- if (ob->scaflag & OB_SHOWCONT) {
-
- /* first show the state */
- uiDefBlockBut(block, object_state_mask_menu, ob, "State", (short)(xco-10), (short)(yco-10), 36, UI_UNIT_Y, "Object state menu: store and retrieve initial state");
-
- if (!ob->state)
- ob->state = 1;
- for (offset=0; offset<15; offset+=5) {
- uiBlockBeginAlign(block);
- for (stbit=0; stbit<5; stbit++) {
- but = uiDefButBitI(block, controller_state_mask&(1<<(stbit+offset)) ? BUT_TOGDUAL:TOG, 1<<(stbit+offset), stbit+offset, "", (short)(xco+31+12*stbit+13*offset), yco, 12, 12, (int *)&(ob->state), 0, 0, 0, 0, get_state_name(ob, (short)(stbit+offset)));
- uiButSetFunc(but, check_state_mask, but, &(ob->state));
- }
- for (stbit=0; stbit<5; stbit++) {
- but = uiDefButBitI(block, controller_state_mask&(1<<(stbit+offset+15)) ? BUT_TOGDUAL:TOG, 1<<(stbit+offset+15), stbit+offset+15, "", (short)(xco+31+12*stbit+13*offset), yco-12, 12, 12, (int *)&(ob->state), 0, 0, 0, 0, get_state_name(ob, (short)(stbit+offset+15)));
- uiButSetFunc(but, check_state_mask, but, &(ob->state));
- }
- }
- uiBlockBeginAlign(block);
- uiDefButBitS(block, TOG, OB_ALLSTATE, B_SET_STATE_BIT, "All", (short)(xco+226), yco-10, 22, UI_UNIT_Y, &ob->scaflag, 0, 0, 0, 0, "Set all state bits");
- uiDefButBitS(block, TOG, OB_INITSTBIT, B_INIT_STATE_BIT, "Ini", (short)(xco+248), yco-10, 22, UI_UNIT_Y, &ob->scaflag, 0, 0, 0, 0, "Set the initial state");
- uiDefButBitS(block, TOG, OB_DEBUGSTATE, 0, "D", (short)(xco+270), yco-10, 15, UI_UNIT_Y, &ob->scaflag, 0, 0, 0, 0, "Print state debug info");
- uiBlockEndAlign(block);
-
- yco-=35;
-
- /* display only the controllers that match the current state */
- offset = 0;
- for (stbit=0; stbit<32; stbit++) {
- if (!(ob->state & (1<<stbit)))
- continue;
- /* add a separation between controllers of different states */
- if (offset) {
- offset = 0;
- yco -= 6;
- }
- cont= ob->controllers.first;
- while (cont) {
- if (cont->state_mask & (1<<stbit)) {
- /* this controller is visible, mark all its actuator */
- for (iact=0; iact<cont->totlinks; iact++) {
- act = cont->links[iact];
- if (act)
- act->flag |= ACT_VISIBLE;
- }
- uiDefIconButBitS(block, TOG, CONT_DEL, B_DEL_CONT, ICON_X, xco, yco, 22, UI_UNIT_Y, &cont->flag, 0, 0, 0, 0, "Delete Controller");
- uiDefIconButBitS(block, ICONTOG, CONT_SHOW, B_REDR, ICON_RIGHTARROW, (short)(xco+width-22), yco, 22, UI_UNIT_Y, &cont->flag, 0, 0, 0, 0, "Controller settings");
- uiDefIconButBitS(block, TOG, CONT_PRIO, B_REDR, ICON_BOOKMARKS, (short)(xco+width-66), yco, 22, UI_UNIT_Y, &cont->flag, 0, 0, 0, 0, "Mark controller for execution before all non-marked controllers (good for startup scripts)");
-
- sprintf(numstr, "%d", first_bit(cont->state_mask)+1);
- uiDefBlockBut(block, controller_state_mask_menu, cont, numstr, (short)(xco+width-44), yco, 22, UI_UNIT_Y, "Set controller state index (from 1 to 30)");
-
- if (cont->flag & CONT_SHOW) {
- cont->otype= cont->type;
- uiDefButS(block, MENU, B_CHANGE_CONT, controller_pup(), (short)(xco+22), yco, 70, UI_UNIT_Y, &cont->type, 0, 0, 0, 0, "Controller type");
- but = uiDefBut(block, TEX, 1, "", (short)(xco+92), yco, (short)(width-158), UI_UNIT_Y, cont->name, 0, MAX_NAME, 0, 0, "Controller name");
- uiButSetFunc(but, make_unique_prop_names_cb, cont->name, (void*) 0);
-
- ycoo= yco;
- yco= draw_controllerbuttons(cont, block, xco, yco, width);
- if (yco-6 < ycoo) ycoo= (yco+ycoo-20)/2;
- }
- else {
- cpack(0x999999);
- glRecti(xco+22, yco, xco+width-22, yco+19);
- but = uiDefBut(block, LABEL, 0, controller_name(cont->type), (short)(xco+22), yco, 70, UI_UNIT_Y, cont, 0, 0, 0, 0, "Controller type");
- //uiButSetFunc(but, old_sca_move_controller, cont, NULL);
- but = uiDefBut(block, LABEL, 0, cont->name, (short)(xco+92), yco, (short)(width-158), UI_UNIT_Y, cont, 0, 0, 0, 0, "Controller name");
- //uiButSetFunc(but, old_sca_move_controller, cont, NULL);
-
- uiBlockBeginAlign(block);
- but = uiDefIconBut(block, BUT, B_REDR, ICON_TRIA_UP, (short)(xco+width-(110+5)), yco, 22, UI_UNIT_Y, NULL, 0, 0, 0, 0, "Move this logic brick up");
- uiButSetFunc(but, old_sca_move_controller, cont, (void *)TRUE);
- but = uiDefIconBut(block, BUT, B_REDR, ICON_TRIA_DOWN, (short)(xco+width-(88+5)), yco, 22, UI_UNIT_Y, NULL, 0, 0, 0, 0, "Move this logic brick down");
- uiButSetFunc(but, old_sca_move_controller, cont, (void *)FALSE);
- uiBlockEndAlign(block);
-
- ycoo= yco;
- }
-
- but = uiDefIconBut(block, LINK, 0, ICON_LINK, (short)(xco+width), ycoo, UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
- uiSetButLink(but, NULL, (void ***)&(cont->links), &cont->totlinks, LINK_CONTROLLER, LINK_ACTUATOR);
-
- uiDefIconBut(block, INLINK, 0, ICON_INLINK, (short)(xco-19), ycoo, UI_UNIT_X, UI_UNIT_Y, cont, LINK_CONTROLLER, 0, 0, 0, "");
- /* offset is >0 if at least one controller was displayed */
- offset++;
- yco-=20;
- }
- cont= cont->next;
- }
-
- }
- yco-= 6;
- }
- }
-
- /* ******************************* */
- xco= 10; yco= 170; width= 300;
-
- uiDefBlockBut(block, sensor_menu, NULL, "Sensors", xco-10, yco+35, 70, UI_UNIT_Y, "");
-
- uiBlockBeginAlign(block);
- uiDefButBitS(block, TOG, BUTS_SENS_SEL, B_REDR, "Sel", xco+80, yco+35, (width-70)/4, UI_UNIT_Y, &slogic->scaflag, 0, 0, 0, 0, "Show all selected Objects");
- uiDefButBitS(block, TOG, BUTS_SENS_ACT, B_REDR, "Act", xco+80+(width-70)/4, yco+35, (width-70)/4, UI_UNIT_Y, &slogic->scaflag, 0, 0, 0, 0, "Show active Object");
- uiDefButBitS(block, TOG, BUTS_SENS_LINK, B_REDR, "Link", xco+80+2*(width-70)/4, yco+35, (width-70)/4, UI_UNIT_Y, &slogic->scaflag, 0, 0, 0, 0, "Show linked Objects to Controller");
- uiDefButBitS(block, TOG, BUTS_SENS_STATE, B_REDR, "State", xco+80+3*(width-70)/4, yco+35, (width-70)/4, UI_UNIT_Y, &slogic->scaflag, 0, 0, 0, 0, "Show only sensors connected to active states");
- uiBlockEndAlign(block);
-
- for (a=0; a<count; a++) {
- ob= (Object *)idar[a];
-// uiClearButLock();
-// uiSetButLock(BKE_object_is_libdata(ob), ERROR_LIBDATA_MESSAGE);
-
- if ((ob->scavisflag & OB_VIS_SENS) == 0) {
- continue;
- }
-
- /* presume it is only objects for now */
- uiBlockBeginAlign(block);
-// if (ob->sensors.first) uiSetCurFont(block, UI_HELVB);
- uiDefButBitS(block, TOG, OB_SHOWSENS, B_REDR, ob->id.name+2, (short)(xco-10), yco, (short)(width-30), UI_UNIT_Y, &ob->scaflag, 0, 31, 0, 0, "Object name, click to show/hide sensors");
-// if (ob->sensors.first) uiSetCurFont(block, UI_HELV);
- uiDefButBitS(block, TOG, OB_ADDSENS, B_ADD_SENS, "Add", (short)(xco+width-40), yco, 50, UI_UNIT_Y, &ob->scaflag, 0, 0, 0, 0, "Add a new Sensor");
- uiBlockEndAlign(block);
- yco-=20;
-
- if (ob->scaflag & OB_SHOWSENS) {
-
- sens= ob->sensors.first;
- while (sens) {
- if (!(slogic->scaflag & BUTS_SENS_STATE) ||
- (sens->totlinks == 0) || /* always display sensor without links so that is can be edited */
- (sens->flag & SENS_PIN && slogic->scaflag & BUTS_SENS_STATE) || /* states can hide some sensors, pinned sensors ignore the visible state */
- (is_sensor_linked(block, sens))
- ) {
- /* should we draw the pin? - for now always draw when there is a state */
- pin = (slogic->scaflag & BUTS_SENS_STATE && (sens->flag & SENS_SHOW || sens->flag & SENS_PIN)) ? 1 : 0;
-
- sens->flag |= SENS_VISIBLE;
- uiDefIconButBitS(block, TOG, SENS_DEL, B_DEL_SENS, ICON_X, xco, yco, 22, UI_UNIT_Y, &sens->flag, 0, 0, 0, 0, "Delete Sensor");
- if (pin)
- uiDefIconButBitS(block, ICONTOG, SENS_PIN, B_REDR, ICON_PINNED, (short)(xco+width-44), yco, 22, UI_UNIT_Y, &sens->flag, 0, 0, 0, 0, "Display when not linked to a visible states controller");
-
- uiDefIconButBitS(block, ICONTOG, SENS_SHOW, B_REDR, ICON_RIGHTARROW, (short)(xco+width-22), yco, 22, UI_UNIT_Y, &sens->flag, 0, 0, 0, 0, "Sensor settings");
-
- ycoo= yco;
- if (sens->flag & SENS_SHOW) {
- uiDefButS(block, MENU, B_CHANGE_SENS, sensor_pup(), (short)(xco+22), yco, 80, UI_UNIT_Y, &sens->type, 0, 0, 0, 0, "Sensor type");
- but = uiDefBut(block, TEX, 1, "", (short)(xco+102), yco, (short)(width-(pin?146:124)), UI_UNIT_Y, sens->name, 0, MAX_NAME, 0, 0, "Sensor name");
- uiButSetFunc(but, make_unique_prop_names_cb, sens->name, (void*) 0);
-
- sens->otype= sens->type;
- yco= draw_sensorbuttons(ob, sens, block, xco, yco, width);
- if (yco-6 < ycoo) ycoo= (yco+ycoo-20)/2;
- }
- else {
- set_col_sensor(sens->type, 1);
- glRecti(xco + 22, yco, xco + width - 22, yco + 19);
- but = uiDefBut(block, LABEL, 0, sensor_name(sens->type), (short)(xco+22), yco, 80, UI_UNIT_Y, sens, 0, 0, 0, 0, "");
- //uiButSetFunc(but, old_sca_move_sensor, sens, NULL);
- but = uiDefBut(block, LABEL, 0, sens->name, (short)(xco+102), yco, (short)(width-(pin?146:124)), UI_UNIT_Y, sens, 0, MAX_NAME, 0, 0, "");
- //uiButSetFunc(but, old_sca_move_sensor, sens, NULL);
-
- uiBlockBeginAlign(block);
- but = uiDefIconBut(block, BUT, B_REDR, ICON_TRIA_UP, (short)(xco+width-(66+5)), yco, 22, UI_UNIT_Y, NULL, 0, 0, 0, 0, "Move this logic brick up");
- uiButSetFunc(but, old_sca_move_sensor, sens, (void *)TRUE);
- but = uiDefIconBut(block, BUT, B_REDR, ICON_TRIA_DOWN, (short)(xco+width-(44+5)), yco, 22, UI_UNIT_Y, NULL, 0, 0, 0, 0, "Move this logic brick down");
- uiButSetFunc(but, old_sca_move_sensor, sens, (void *)FALSE);
- uiBlockEndAlign(block);
- }
-
- but = uiDefIconBut(block, LINK, 0, ICON_LINK, (short)(xco+width), ycoo, UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
- uiSetButLink(but, NULL, (void ***)&(sens->links), &sens->totlinks, LINK_SENSOR, LINK_CONTROLLER);
-
- yco-=20;
- }
- sens= sens->next;
- }
- yco-= 6;
- }
- }
- /* ******************************* */
- xco= 800; yco= 170; width= 300;
- uiDefBlockBut(block, actuator_menu, NULL, "Actuators", xco-10, yco+35, 90, UI_UNIT_Y, "");
-
- uiBlockBeginAlign(block);
- uiDefButBitS(block, TOG, BUTS_ACT_SEL, B_REDR, "Sel", xco+110, yco+35, (width-100)/4, UI_UNIT_Y, &slogic->scaflag, 0, 0, 0, 0, "Show all selected Objects");
- uiDefButBitS(block, TOG, BUTS_ACT_ACT, B_REDR, "Act", xco+110+(width-100)/4, yco+35, (width-100)/4, UI_UNIT_Y, &slogic->scaflag, 0, 0, 0, 0, "Show active Object");
- uiDefButBitS(block, TOG, BUTS_ACT_LINK, B_REDR, "Link", xco+110+2*(width-100)/4, yco+35, (width-100)/4, UI_UNIT_Y, &slogic->scaflag, 0, 0, 0, 0, "Show linked Objects to Controller");
- uiDefButBitS(block, TOG, BUTS_ACT_STATE, B_REDR, "State", xco+110+3*(width-100)/4, yco+35, (width-100)/4, UI_UNIT_Y, &slogic->scaflag, 0, 0, 0, 0, "Show only actuators connected to active states");
- uiBlockEndAlign(block);
- for (a=0; a<count; a++) {
- ob= (Object *)idar[a];
-// uiClearButLock();
-// uiSetButLock(BKE_object_is_libdata(ob), ERROR_LIBDATA_MESSAGE);
- if ((ob->scavisflag & OB_VIS_ACT) == 0) {
- continue;
- }
-
- /* presume it is only objects for now */
- uiBlockBeginAlign(block);
-// if (ob->actuators.first) uiSetCurFont(block, UI_HELVB);
- uiDefButBitS(block, TOG, OB_SHOWACT, B_REDR, ob->id.name+2, (short)(xco-10), yco, (short)(width-30), UI_UNIT_Y, &ob->scaflag, 0, 31, 0, 0, "Object name, click to show/hide actuators");
-// if (ob->actuators.first) uiSetCurFont(block, UI_HELV);
- uiDefButBitS(block, TOG, OB_ADDACT, B_ADD_ACT, "Add", (short)(xco+width-40), yco, 50, UI_UNIT_Y, &ob->scaflag, 0, 0, 0, 0, "Add a new Actuator");
- uiBlockEndAlign(block);
- yco-=20;
-
- if (ob->scaflag & OB_SHOWACT) {
-
- act= ob->actuators.first;
- while (act) {
- if (!(slogic->scaflag & BUTS_ACT_STATE) ||
- !(act->flag & ACT_LINKED) || /* always display actuators without links so that is can be edited */
- (act->flag & ACT_VISIBLE) || /* this actuator has visible connection, display it */
- (act->flag & ACT_PIN && slogic->scaflag & BUTS_ACT_STATE))
- {
- pin = (slogic->scaflag & BUTS_ACT_STATE && (act->flag & SENS_SHOW || act->flag & SENS_PIN)) ? 1 : 0;
-
- act->flag |= ACT_VISIBLE; /* mark the actuator as visible to help implementing the up/down action */
- uiDefIconButBitS(block, TOG, ACT_DEL, B_DEL_ACT, ICON_X, xco, yco, 22, UI_UNIT_Y, &act->flag, 0, 0, 0, 0, "Delete Actuator");
- if (pin)
- uiDefIconButBitS(block, ICONTOG, ACT_PIN, B_REDR, ICON_PINNED, (short)(xco+width-44), yco, 22, UI_UNIT_Y, &act->flag, 0, 0, 0, 0, "Display when not linked to a visible states controller");
- uiDefIconButBitS(block, ICONTOG, ACT_SHOW, B_REDR, ICON_RIGHTARROW, (short)(xco+width-22), yco, 22, UI_UNIT_Y, &act->flag, 0, 0, 0, 0, "Display the actuator");
-
- if (act->flag & ACT_SHOW) {
- act->otype= act->type;
- uiDefButS(block, MENU, B_CHANGE_ACT, actuator_pup(ob), (short)(xco+22), yco, 90, UI_UNIT_Y, &act->type, 0, 0, 0, 0, "Actuator type");
- but = uiDefBut(block, TEX, 1, "", (short)(xco+112), yco, (short)(width-(pin?156:134)), UI_UNIT_Y, act->name, 0, MAX_NAME, 0, 0, "Actuator name");
- uiButSetFunc(but, make_unique_prop_names_cb, act->name, (void*) 0);
-
- ycoo= yco;
- yco= draw_actuatorbuttons(bmain, ob, act, block, xco, yco, width);
- if (yco-6 < ycoo) ycoo= (yco+ycoo-20)/2;
- }
- else {
- set_col_actuator(act->type, 1);
- glRecti((short)(xco+22), yco, (short)(xco+width-22), (short)(yco+19));
- /* but= */ uiDefBut(block, LABEL, 0, actuator_name(act->type), (short)(xco+22), yco, 90, UI_UNIT_Y, act, 0, 0, 0, 0, "Actuator type");
- // uiButSetFunc(but, old_sca_move_actuator, act, NULL);
- /* but= */ uiDefBut(block, LABEL, 0, act->name, (short)(xco+112), yco, (short)(width-(pin?156:134)), UI_UNIT_Y, act, 0, 0, 0, 0, "Actuator name");
- // uiButSetFunc(but, old_sca_move_actuator, act, NULL);
-
- uiBlockBeginAlign(block);
- but = uiDefIconBut(block, BUT, B_REDR, ICON_TRIA_UP, (short)(xco+width-(66+5)), yco, 22, UI_UNIT_Y, NULL, 0, 0, 0, 0, "Move this logic brick up");
- uiButSetFunc(but, old_sca_move_actuator, act, (void *)TRUE);
- but = uiDefIconBut(block, BUT, B_REDR, ICON_TRIA_DOWN, (short)(xco+width-(44+5)), yco, 22, UI_UNIT_Y, NULL, 0, 0, 0, 0, "Move this logic brick down");
- uiButSetFunc(but, old_sca_move_actuator, act, (void *)FALSE);
- uiBlockEndAlign(block);
-
- ycoo= yco;
- }
-
- uiDefIconBut(block, INLINK, 0, ICON_INLINK, (short)(xco - 19), ycoo, UI_UNIT_X, UI_UNIT_Y, act, LINK_ACTUATOR, 0, 0, 0, "");
-
- yco-=20;
- }
- act= act->next;
- }
- yco-= 6;
- }
- }
+ /* set the view */
+ UI_view2d_view_ortho(&ar->v2d);
uiComposeLinks(block);
uiEndBlock(C, block);
uiDrawBlock(C, block);
-
+
+ /* restore view matrix */
+ UI_view2d_view_restore(C);
+
if (idar) MEM_freeN(idar);
}
-
-
-
-
-
diff --git a/source/blender/editors/space_logic/space_logic.c b/source/blender/editors/space_logic/space_logic.c
index 1a50f72153a..4cd53215697 100644
--- a/source/blender/editors/space_logic/space_logic.c
+++ b/source/blender/editors/space_logic/space_logic.c
@@ -62,20 +62,20 @@ ARegion *logic_has_buttons_region(ScrArea *sa)
{
ARegion *ar, *arnew;
- ar= BKE_area_find_region_type(sa, RGN_TYPE_UI);
+ ar = BKE_area_find_region_type(sa, RGN_TYPE_UI);
if (ar) return ar;
/* add subdiv level; after header */
- ar= BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
+ ar = BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
/* is error! */
- if (ar==NULL) return NULL;
+ if (ar == NULL) return NULL;
arnew= MEM_callocN(sizeof(ARegion), "buttons for image");
BLI_insertlinkafter(&sa->regionbase, ar, arnew);
- arnew->regiontype= RGN_TYPE_UI;
- arnew->alignment= RGN_ALIGN_LEFT;
+ arnew->regiontype = RGN_TYPE_UI;
+ arnew->alignment = RGN_ALIGN_LEFT;
arnew->flag = RGN_FLAG_HIDDEN;
@@ -84,8 +84,9 @@ ARegion *logic_has_buttons_region(ScrArea *sa)
/* ******************** default callbacks for image space ***************** */
-static SpaceLink *logic_new(const bContext *UNUSED(C))
+static SpaceLink *logic_new(const bContext *C)
{
+ ScrArea *sa= CTX_wm_area(C);
ARegion *ar;
SpaceLogic *slogic;
@@ -93,10 +94,10 @@ static SpaceLink *logic_new(const bContext *UNUSED(C))
slogic->spacetype= SPACE_LOGIC;
/* default options */
- slogic->scaflag = (BUTS_SENS_SEL|BUTS_SENS_ACT|BUTS_SENS_LINK) |
- (BUTS_CONT_SEL|BUTS_CONT_ACT|BUTS_CONT_LINK) |
- (BUTS_ACT_SEL|BUTS_ACT_ACT|BUTS_ACT_LINK) |
- (BUTS_SENS_STATE|BUTS_ACT_STATE);
+ slogic->scaflag = ((BUTS_SENS_SEL|BUTS_SENS_ACT|BUTS_SENS_LINK) |
+ (BUTS_CONT_SEL|BUTS_CONT_ACT|BUTS_CONT_LINK) |
+ (BUTS_ACT_SEL|BUTS_ACT_ACT|BUTS_ACT_LINK) |
+ (BUTS_SENS_STATE|BUTS_ACT_STATE));
/* header */
@@ -120,28 +121,26 @@ static SpaceLink *logic_new(const bContext *UNUSED(C))
ar->regiontype= RGN_TYPE_WINDOW;
ar->v2d.tot.xmin = 0.0f;
- ar->v2d.tot.ymin = 0.0f;
- ar->v2d.tot.xmax = 1280;
- ar->v2d.tot.ymax = 240.0f;
+ ar->v2d.tot.ymax = 0.0f;
+ ar->v2d.tot.xmax = 1150.0f;
+ ar->v2d.tot.ymin = ( 1150.0f/(float)sa->winx ) * (float)-sa->winy;
- ar->v2d.cur.xmin = 0.0f;
- ar->v2d.cur.ymin = 0.0f;
- ar->v2d.cur.xmax = 1280.0f;
- ar->v2d.cur.ymax = 240.0f;
+ ar->v2d.cur = ar->v2d.tot;
- ar->v2d.min[0]= 1.0f;
- ar->v2d.min[1]= 1.0f;
+ ar->v2d.min[0] = 1.0f;
+ ar->v2d.min[1] = 1.0f;
- ar->v2d.max[0]= 32000.0f;
- ar->v2d.max[1]= 32000.0f;
+ ar->v2d.max[0] = 32000.0f;
+ ar->v2d.max[1] = 32000.0f;
- ar->v2d.minzoom= 0.5f;
- ar->v2d.maxzoom= 1.21f;
-
- ar->v2d.scroll= (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM);
- ar->v2d.keepzoom= V2D_LIMITZOOM|V2D_KEEPASPECT;
- ar->v2d.keeptot= 0;
+ ar->v2d.minzoom = 0.5f;
+ ar->v2d.maxzoom = 1.5f;
+ ar->v2d.scroll = (V2D_SCROLL_RIGHT | V2D_SCROLL_BOTTOM);
+ ar->v2d.keepzoom = V2D_KEEPZOOM | V2D_LIMITZOOM | V2D_KEEPASPECT;
+ ar->v2d.keeptot = V2D_KEEPTOT_BOUNDS;
+ ar->v2d.align = V2D_ALIGN_NO_POS_Y | V2D_ALIGN_NO_NEG_X;
+ ar->v2d.keepofs = V2D_KEEPOFS_Y;
return (SpaceLink *)slogic;
}
@@ -183,6 +182,9 @@ static void logic_keymap(struct wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "LOGIC_OT_properties", NKEY, KM_PRESS, 0, 0);
WM_keymap_add_item(keymap, "LOGIC_OT_links_cut", LEFTMOUSE, KM_PRESS, KM_CTRL, 0);
WM_keymap_add_menu(keymap, "LOGIC_MT_logicbricks_add", AKEY, KM_PRESS, KM_SHIFT, 0);
+
+ WM_keymap_add_item(keymap, "VIEW2D_OT_reset", HOMEKEY, KM_PRESS, 0, 0);
+
}
static void logic_refresh(const bContext *UNUSED(C), ScrArea *UNUSED(sa))
@@ -234,7 +236,7 @@ static void logic_main_area_init(wmWindowManager *wm, ARegion *ar)
wmKeyMap *keymap;
UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy);
-
+
/* own keymaps */
keymap = WM_keymap_find(wm->defaultconf, "Logic Editor", SPACE_LOGIC, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
@@ -259,7 +261,7 @@ static void logic_main_area_draw(const bContext *C, ARegion *ar)
UI_view2d_view_restore(C);
/* scrollers */
- scrollers= UI_view2d_scrollers_calc(C, v2d, 10, V2D_GRID_CLAMP, V2D_ARG_DUMMY, V2D_ARG_DUMMY);
+ scrollers= UI_view2d_scrollers_calc(C, v2d, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY);
UI_view2d_scrollers_draw(C, v2d, scrollers);
UI_view2d_scrollers_free(scrollers);
diff --git a/source/blender/editors/space_nla/nla_buttons.c b/source/blender/editors/space_nla/nla_buttons.c
index 804d44ba720..d75946c4317 100644
--- a/source/blender/editors/space_nla/nla_buttons.c
+++ b/source/blender/editors/space_nla/nla_buttons.c
@@ -67,14 +67,11 @@
/* ******************* nla editor space & buttons ************** */
-#define B_NOP 1
-#define B_REDR 2
-
/* -------------- */
static void do_nla_region_buttons(bContext *C, void *UNUSED(arg), int event)
{
- //Scene *scene= CTX_data_scene(C);
+ //Scene *scene = CTX_data_scene(C);
switch (event) {
@@ -159,7 +156,7 @@ static int nla_panel_context(const bContext *C, PointerRNA *adt_ptr, PointerRNA
found = -1;
}
}
- }
+ }
break;
}
@@ -245,7 +242,7 @@ static void nla_panel_animdata(const bContext *C, Panel *pa)
if (!nla_panel_context(C, &adt_ptr, NULL, NULL))
return;
- /* adt= adt_ptr.data; */
+ /* adt = adt_ptr.data; */
block = uiLayoutGetBlock(layout);
uiBlockSetHandleFunc(block, do_nla_region_buttons, NULL);
@@ -408,7 +405,7 @@ static void nla_panel_evaluation(const bContext *C, Panel *pa)
uiItemR(col, &strip_ptr, "use_animated_influence", 0, NULL, ICON_NONE);
sub = uiLayoutColumn(col, TRUE);
- uiLayoutSetEnabled(sub, RNA_boolean_get(&strip_ptr, "use_animated_influence"));
+ uiLayoutSetEnabled(sub, RNA_boolean_get(&strip_ptr, "use_animated_influence"));
uiItemR(sub, &strip_ptr, "influence", 0, NULL, ICON_NONE);
col = uiLayoutColumn(layout, TRUE);
diff --git a/source/blender/editors/space_nla/nla_channels.c b/source/blender/editors/space_nla/nla_channels.c
index b3a869ed57d..95e75d0e4fc 100644
--- a/source/blender/editors/space_nla/nla_channels.c
+++ b/source/blender/editors/space_nla/nla_channels.c
@@ -199,7 +199,7 @@ static int mouse_nla_channels(bAnimContext *ac, float x, int channel_index, shor
}
notifierFlags |= (ND_ANIMCHAN | NA_SELECTED);
- }
+ }
break;
case ANIMTYPE_NLATRACK:
diff --git a/source/blender/editors/space_nla/nla_draw.c b/source/blender/editors/space_nla/nla_draw.c
index 92f014fd804..fd999bf2476 100644
--- a/source/blender/editors/space_nla/nla_draw.c
+++ b/source/blender/editors/space_nla/nla_draw.c
@@ -163,7 +163,7 @@ static void nla_strip_get_color_inside(AnimData *adt, NlaStrip *strip, float col
/* normal, unselected strip - use (hardly noticeable) blue tinge */
UI_GetThemeColor3fv(TH_NLA_TRANSITION, color);
}
- }
+ }
else if (strip->type == NLASTRIP_TYPE_META) {
/* Meta Clip */
// TODO: should temporary metas get different colors too?
@@ -528,7 +528,7 @@ void draw_nla_main_data(bAnimContext *ac, SpaceNla *snla, ARegion *ar)
*/
v2d->tot.ymin = (float)(-height);
- /* loop through channels, and set up drawing depending on their type */
+ /* loop through channels, and set up drawing depending on their type */
y = (float)(-NLACHANNEL_HEIGHT(snla));
for (ale = anim_data.first; ale; ale = ale->next) {
@@ -628,7 +628,7 @@ static void draw_nla_channel_list_gl(bAnimContext *ac, ListBase *anim_data, View
bAnimListElem *ale;
float x = 0.0f;
- /* loop through channels, and set up drawing depending on their type */
+ /* loop through channels, and set up drawing depending on their type */
for (ale = anim_data->first; ale; ale = ale->next) {
const float yminc = (float)(y - NLACHANNEL_HEIGHT_HALF(snla));
const float ymaxc = (float)(y + NLACHANNEL_HEIGHT_HALF(snla));
@@ -709,7 +709,7 @@ static void draw_nla_channel_list_gl(bAnimContext *ac, ListBase *anim_data, View
// draw backdrops only...
ANIM_channel_draw(ac, ale, yminc, ymaxc);
break;
- }
+ }
/* if special types, draw manually for now... */
if (do_draw) {
@@ -737,7 +737,7 @@ static void draw_nla_channel_list_gl(bAnimContext *ac, ListBase *anim_data, View
/* even more */
offset = 21;
indent = 1;
- }
+ }
break;
default:
@@ -775,7 +775,7 @@ static void draw_nla_channel_list_gl(bAnimContext *ac, ListBase *anim_data, View
glColor3fv(color);
}
else {
- float alpha = (adt && (adt->flag & ADT_NLA_SOLO_TRACK)) ? 0.3 : 1.0f;
+ float alpha = (adt && (adt->flag & ADT_NLA_SOLO_TRACK)) ? 0.3f : 1.0f;
glColor4f(color[0], color[1], color[2], alpha);
}
@@ -849,8 +849,6 @@ static void draw_nla_channel_list_gl(bAnimContext *ac, ListBase *anim_data, View
/* draw NLA-action line 'status-icons' - only when there's an action */
if ((ale->type == ANIMTYPE_NLAACTION) && (ale->data)) {
- AnimData *adt = ale->adt;
-
offset += 16;
/* now draw some indicator icons */
@@ -938,7 +936,7 @@ void draw_nla_channel_list(bContext *C, bAnimContext *ac, ARegion *ar)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
- /* loop through channels, and set up drawing depending on their type */
+ /* loop through channels, and set up drawing depending on their type */
for (ale = anim_data.first; ale; ale = ale->next) {
const float yminc = (float)(y - NLACHANNEL_HEIGHT_HALF(snla));
const float ymaxc = (float)(y + NLACHANNEL_HEIGHT_HALF(snla));
diff --git a/source/blender/editors/space_nla/nla_edit.c b/source/blender/editors/space_nla/nla_edit.c
index 2861d17b350..3740c3fae5e 100644
--- a/source/blender/editors/space_nla/nla_edit.c
+++ b/source/blender/editors/space_nla/nla_edit.c
@@ -121,9 +121,9 @@ static int nlaedit_enable_tweakmode_exec(bContext *C, wmOperator *op)
/* if no blocks, popup error? */
if (anim_data.first == NULL) {
- BKE_report(op->reports, RPT_ERROR, "No AnimData blocks to enter tweakmode for");
+ BKE_report(op->reports, RPT_ERROR, "No AnimData blocks to enter tweak mode for");
return OPERATOR_CANCELLED;
- }
+ }
/* for each AnimData block with NLA-data, try setting it in tweak-mode */
for (ale = anim_data.first; ale; ale = ale->next) {
@@ -147,7 +147,7 @@ static int nlaedit_enable_tweakmode_exec(bContext *C, wmOperator *op)
WM_event_add_notifier(C, NC_ANIMATION | ND_NLA_ACTCHANGE, NULL);
}
else {
- BKE_report(op->reports, RPT_ERROR, "No active strip(s) to enter tweakmode on");
+ BKE_report(op->reports, RPT_ERROR, "No active strip(s) to enter tweak mode on");
return OPERATOR_CANCELLED;
}
@@ -190,9 +190,9 @@ static int nlaedit_disable_tweakmode_exec(bContext *C, wmOperator *op)
/* if no blocks, popup error? */
if (anim_data.first == NULL) {
- BKE_report(op->reports, RPT_ERROR, "No AnimData blocks to enter tweakmode for");
+ BKE_report(op->reports, RPT_ERROR, "No AnimData blocks to enter tweak mode for");
return OPERATOR_CANCELLED;
- }
+ }
/* for each AnimData block with NLA-data, try exitting tweak-mode */
for (ale = anim_data.first; ale; ale = ale->next) {
@@ -266,8 +266,8 @@ static void get_nlastrip_extents(bAnimContext *ac, float *min, float *max, const
/* only consider selected strips? */
if ((onlySel == 0) || (strip->flag & NLASTRIP_FLAG_SELECT)) {
/* extend range if appropriate */
- *min = minf(*min, strip->start);
- *max = maxf(*max, strip->end);
+ *min = min_ff(*min, strip->start);
+ *max = max_ff(*max, strip->end);
}
}
}
@@ -304,13 +304,13 @@ static int nlaedit_viewall(bContext *C, const short onlySel)
/* set the horizontal range, with an extra offset so that the extreme keys will be in view */
get_nlastrip_extents(&ac, &v2d->cur.xmin, &v2d->cur.xmax, onlySel);
- extra = 0.1f * BLI_RCT_SIZE_X(&v2d->cur);
+ extra = 0.1f * BLI_rctf_size_x(&v2d->cur);
v2d->cur.xmin -= extra;
v2d->cur.xmax += extra;
/* set vertical range */
v2d->cur.ymax = 0.0f;
- v2d->cur.ymin = (float)-BLI_RCT_SIZE_Y(&v2d->mask);
+ v2d->cur.ymin = (float)-BLI_rcti_size_y(&v2d->mask);
/* do View2D syncing */
UI_view2d_sync(CTX_wm_screen(C), CTX_wm_area(C), v2d, V2D_LOCK_COPY);
@@ -398,14 +398,16 @@ static int nlaedit_add_actionclip_exec(bContext *C, wmOperator *op)
act = BLI_findlink(&CTX_data_main(C)->action, RNA_enum_get(op->ptr, "action"));
if (act == NULL) {
- BKE_report(op->reports, RPT_ERROR, "No valid Action to add");
+ BKE_report(op->reports, RPT_ERROR, "No valid action to add");
//printf("Add strip - actname = '%s'\n", actname);
return OPERATOR_CANCELLED;
}
else if (act->idroot == 0) {
/* hopefully in this case (i.e. library of userless actions), the user knows what they're doing... */
BKE_reportf(op->reports, RPT_WARNING,
- "Action '%s' does not specify what datablocks it can be used on. Try setting the 'ID Root Type' setting from the Datablocks Editor for this Action to avoid future problems",
+ "Action '%s' does not specify what datablocks it can be used on "
+ "(try setting the 'ID Root Type' setting from the Datablocks Editor "
+ "for this action to avoid future problems)",
act->id.name + 2);
}
@@ -431,7 +433,7 @@ static int nlaedit_add_actionclip_exec(bContext *C, wmOperator *op)
*/
if ((act->idroot) && (act->idroot != GS(ale->id->name))) {
BKE_reportf(op->reports, RPT_ERROR,
- "Couldn't add action '%s' as it cannot be used relative to ID-blocks of type '%s'",
+ "Could not add action '%s' as it cannot be used relative to ID-blocks of type '%s'",
act->id.name + 2, ale->id->name);
continue;
}
@@ -1170,7 +1172,8 @@ static int nlaedit_bake_exec(bContext *C, wmOperator *UNUSED(op))
return OPERATOR_FINISHED;
}
-static void NLA_OT_bake(wmOperatorType *ot)
+/* why isn't this used? */
+static void UNUSED_FUNCTION(NLA_OT_bake)(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Bake Strips";
@@ -1361,7 +1364,7 @@ static int nlaedit_swap_exec(bContext *C, wmOperator *op)
"Cannot swap selected strips as they will not be able to fit in their new places");
}
else {
- BKE_reportf(op->reports, RPT_WARNING,
+ BKE_reportf(op->reports, RPT_WARNING,
"Cannot swap '%s' and '%s' as one or both will not be able to fit in their new places",
sa->name, sb->name);
}
@@ -2020,7 +2023,7 @@ static int nla_fmodifier_add_exec(bContext *C, wmOperator *op)
set_active_fmodifier(&strip->modifiers, fcm);
else {
BKE_reportf(op->reports, RPT_ERROR,
- "Modifier couldn't be added to (%s : %s) (see console for details)",
+ "Modifier could not be added to (%s : %s) (see console for details)",
nlt->name, strip->name);
}
}
diff --git a/source/blender/editors/space_nla/nla_ops.c b/source/blender/editors/space_nla/nla_ops.c
index 3a74d0b4c9c..54ade829c0d 100644
--- a/source/blender/editors/space_nla/nla_ops.c
+++ b/source/blender/editors/space_nla/nla_ops.c
@@ -256,7 +256,7 @@ static void nla_keymap_main(wmKeyConfig *keyconf, wmKeyMap *keymap)
WM_keymap_add_item(keymap, "NLA_OT_meta_remove", GKEY, KM_PRESS, KM_ALT, 0);
/* duplicate */
- WM_keymap_add_item(keymap, "NLA_OT_duplicate", DKEY, KM_PRESS, KM_SHIFT, 0);
+ WM_keymap_add_item(keymap, "NLA_OT_duplicate", DKEY, KM_PRESS, KM_SHIFT, 0);
/* delete */
WM_keymap_add_item(keymap, "NLA_OT_delete", XKEY, KM_PRESS, 0, 0);
diff --git a/source/blender/editors/space_nla/nla_select.c b/source/blender/editors/space_nla/nla_select.c
index 222c2414fcb..97553b7aa56 100644
--- a/source/blender/editors/space_nla/nla_select.c
+++ b/source/blender/editors/space_nla/nla_select.c
@@ -309,7 +309,7 @@ static int nlaedit_borderselect_exec(bContext *C, wmOperator *op)
* - the frame-range select option is favored over the channel one (x over y), as frame-range one is often
* used for tweaking timing when "blocking", while channels is not that useful...
*/
- if (BLI_RCT_SIZE_X(&rect) >= BLI_RCT_SIZE_Y(&rect))
+ if (BLI_rcti_size_x(&rect) >= BLI_rcti_size_y(&rect))
mode = NLA_BORDERSEL_FRAMERANGE;
else
mode = NLA_BORDERSEL_CHANNELS;
@@ -390,7 +390,7 @@ static void nlaedit_select_leftright(bContext *C, bAnimContext *ac, short leftri
if (leftright == NLAEDIT_LRSEL_LEFT) {
xmin = MINAFRAMEF;
xmax = (float)(CFRA + 0.1f);
- }
+ }
else {
xmin = (float)(CFRA - 0.1f);
xmax = MAXFRAMEF;
@@ -471,7 +471,7 @@ static int nlaedit_select_leftright_invoke(bContext *C, wmOperator *op, wmEvent
UI_view2d_region_to_view(v2d, event->mval[0], event->mval[1], &x, NULL);
if (x < CFRA)
RNA_int_set(op->ptr, "mode", NLAEDIT_LRSEL_LEFT);
- else
+ else
RNA_int_set(op->ptr, "mode", NLAEDIT_LRSEL_RIGHT);
}
@@ -582,7 +582,7 @@ static void mouse_nla_strips(bContext *C, bAnimContext *ac, const int mval[2], s
ANIM_deselect_anim_channels(ac, ac->data, ac->datatype, 0, ACHANNEL_SETFLAG_CLEAR);
/* Highlight NLA-Track */
- if (ale->type == ANIMTYPE_NLATRACK) {
+ if (ale->type == ANIMTYPE_NLATRACK) {
NlaTrack *nlt = (NlaTrack *)ale->data;
nlt->flag |= NLATRACK_SELECTED;
diff --git a/source/blender/editors/space_node/drawnode.c b/source/blender/editors/space_node/drawnode.c
index 1f266c98020..0938562857b 100644
--- a/source/blender/editors/space_node/drawnode.c
+++ b/source/blender/editors/space_node/drawnode.c
@@ -69,9 +69,6 @@
#include "node_intern.h" /* own include */
-/* XXX interface.h */
-extern void ui_dropshadow(rctf *rct, float radius, float aspect, float alpha, int select);
-
/* ****************** SOCKET BUTTON DRAW FUNCTIONS ***************** */
static void node_sync_cb(bContext *UNUSED(C), void *snode_v, void *node_v)
@@ -200,25 +197,22 @@ static void node_draw_output_default(const bContext *C, uiBlock *block,
const char *name, int UNUSED(x), int UNUSED(y), int UNUSED(width))
{
SpaceNode *snode = CTX_wm_space_node(C);
- float slen;
- int ofs = 0;
const char *ui_name = IFACE_(name);
- int len = strlen(ui_name);
+ float slen;
+
UI_ThemeColor(TH_TEXT);
slen = (UI_GetStringWidth(ui_name) + NODE_MARGIN_X) * snode->aspect_sqrt;
- while (slen > node->width && ofs < len) {
- ofs++;
- slen = (UI_GetStringWidth(ui_name + ofs) + NODE_MARGIN_X) * snode->aspect_sqrt;
+ while (slen > node->width && *ui_name) {
+ ui_name = BLI_str_find_next_char_utf8(ui_name, NULL);
+ slen = (UI_GetStringWidth(ui_name) + NODE_MARGIN_X) * snode->aspect_sqrt;
}
-
- if (ofs < len) {
- uiDefBut(block, LABEL, 0, ui_name + ofs,
- (int)(sock->locx - slen), (int)(sock->locy - 9.0f),
- (short)(node->width - NODE_DY), (short)NODE_DY,
- NULL, 0, 0, 0, 0, "");
+
+ if (*ui_name) {
+ uiDefBut(block, LABEL, 0, ui_name,
+ (int)(sock->locx - slen), (int)(sock->locy - 9.0f),
+ (short)slen, (short)NODE_DY,
+ NULL, 0, 0, 0, 0, "");
}
-
- (void)snode;
}
/* ****************** BASE DRAW FUNCTIONS FOR NEW OPERATOR NODES ***************** */
@@ -387,7 +381,7 @@ static void node_buts_normal(uiLayout *layout, bContext *UNUSED(C), PointerRNA *
bt = uiDefButF(block, BUT_NORMAL, B_NODE_EXEC, "",
(int)butr->xmin, (int)butr->xmin,
- (short)BLI_RCT_SIZE_X(butr), (short)BLI_RCT_SIZE_X(butr),
+ (short)BLI_rctf_size_x(butr), (short)BLI_rctf_size_x(butr),
nor, 0.0f, 1.0f, 0, 0, "");
uiButSetFunc(bt, node_normal_cb, ntree, node);
}
@@ -523,7 +517,7 @@ static void node_update_group(const bContext *C, bNodeTree *ntree, bNode *gnode)
rect->ymax += NODE_DY;
/* input sockets */
- dy = BLI_RCT_CENTER_Y(rect) + (NODE_DY * (BLI_countlist(&gnode->inputs) - 1));
+ dy = BLI_rctf_cent_y(rect) + (NODE_DY * (BLI_countlist(&gnode->inputs) - 1));
gsock = ngroup->inputs.first;
sock = gnode->inputs.first;
while (gsock || sock) {
@@ -571,7 +565,7 @@ static void node_update_group(const bContext *C, bNodeTree *ntree, bNode *gnode)
}
/* output sockets */
- dy = BLI_RCT_CENTER_Y(rect) + (NODE_DY * (BLI_countlist(&gnode->outputs) - 1));
+ dy = BLI_rctf_cent_y(rect) + (NODE_DY * (BLI_countlist(&gnode->outputs) - 1));
gsock = ngroup->outputs.first;
sock = gnode->outputs.first;
while (gsock || sock) {
@@ -646,13 +640,13 @@ static void update_group_output_cb(bContext *UNUSED(C), void *UNUSED(snode_v), v
}
static void draw_group_socket_name(SpaceNode *snode, bNode *gnode, bNodeSocket *sock,
- int in_out, float xoffset, float yoffset)
+ int in_out, float xoffset, float yoffset, short width, short height)
{
if (sock->flag & SOCK_DYNAMIC) {
bNodeTree *ngroup = (bNodeTree *)gnode->id;
uiBut *but;
but = uiDefBut(gnode->block, TEX, 0, "",
- sock->locx + xoffset, sock->locy + 1 + yoffset, 72, NODE_DY,
+ sock->locx + xoffset, sock->locy + 1 + yoffset, width, height,
sock->name, 0, sizeof(sock->name), 0, 0, "");
if (in_out == SOCK_IN)
uiButSetFunc(but, update_group_input_cb, snode, ngroup);
@@ -662,7 +656,7 @@ static void draw_group_socket_name(SpaceNode *snode, bNode *gnode, bNodeSocket *
else {
const char *ui_name = IFACE_(sock->name);
uiDefBut(gnode->block, LABEL, 0, ui_name,
- sock->locx + xoffset, sock->locy + 1 + yoffset, 72, NODE_DY,
+ sock->locx + xoffset, sock->locy + 1 + yoffset, width, height,
NULL, 0, 0, 0, 0, "");
}
}
@@ -670,23 +664,26 @@ static void draw_group_socket_name(SpaceNode *snode, bNode *gnode, bNodeSocket *
static void draw_group_socket(const bContext *C, SpaceNode *snode, bNodeTree *ntree, bNode *gnode,
bNodeSocket *sock, bNodeSocket *gsock, int index, int in_out)
{
+ const float dpi_fac = U.dpi / 72.0f;
bNodeTree *ngroup = (bNodeTree *)gnode->id;
bNodeSocketType *stype = ntreeGetSocketType(gsock ? gsock->type : sock->type);
uiBut *bt;
float offset;
int draw_value;
- float node_group_frame = U.dpi * NODE_GROUP_FRAME / 72;
- float socket_size = NODE_SOCKSIZE * U.dpi / 72;
- float arrowbutw = 0.8f * UI_UNIT_X;
+ const float node_group_frame = NODE_GROUP_FRAME * dpi_fac;
+ const float socket_size = NODE_SOCKSIZE * dpi_fac;
+ const float arrowbutw = 0.8f * UI_UNIT_X;
+ const short co_text_w = 72 * dpi_fac;
+ const float co_margin = 6.0f * dpi_fac;
/* layout stuff for buttons on group left frame */
- float colw = 0.6f * node_group_frame;
- float col1 = 6 - node_group_frame;
- float col2 = col1 + colw + 6;
- float col3 = -arrowbutw - 6;
+ const float colw = 0.6f * node_group_frame;
+ const float col1 = co_margin - node_group_frame;
+ const float col2 = col1 + colw + co_margin;
+ const float col3 = -arrowbutw - co_margin;
/* layout stuff for buttons on group right frame */
- float cor1 = 6;
- float cor2 = cor1 + arrowbutw + 6;
- float cor3 = cor2 + arrowbutw + 6;
+ const float cor1 = co_margin;
+ const float cor2 = cor1 + arrowbutw;
+ const float cor3 = cor2 + arrowbutw + co_margin;
/* node and group socket circles */
if (sock)
@@ -716,13 +713,13 @@ static void draw_group_socket(const bContext *C, SpaceNode *snode, bNodeTree *nt
if (draw_value) {
/* both name and value buttons */
if (gsock) {
- draw_group_socket_name(snode, gnode, gsock, in_out, offset, 0);
+ draw_group_socket_name(snode, gnode, gsock, in_out, offset, 0, co_text_w, NODE_DY);
if (stype->buttonfunc)
stype->buttonfunc(C, gnode->block, ngroup, NULL, gsock, "",
gsock->locx + offset, gsock->locy - NODE_DY, colw);
}
else {
- draw_group_socket_name(snode, gnode, sock, in_out, offset, 0);
+ draw_group_socket_name(snode, gnode, sock, in_out, offset, 0, co_text_w, NODE_DY);
if (stype->buttonfunc)
stype->buttonfunc(C, gnode->block, ngroup, NULL, sock, "",
sock->locx + offset, sock->locy - NODE_DY, colw);
@@ -731,9 +728,9 @@ static void draw_group_socket(const bContext *C, SpaceNode *snode, bNodeTree *nt
else {
/* only name, no value button */
if (gsock)
- draw_group_socket_name(snode, gnode, gsock, in_out, offset, -NODE_DYS);
+ draw_group_socket_name(snode, gnode, gsock, in_out, offset, -NODE_DYS, co_text_w, NODE_DY);
else
- draw_group_socket_name(snode, gnode, sock, in_out, offset, -NODE_DYS);
+ draw_group_socket_name(snode, gnode, sock, in_out, offset, -NODE_DYS, co_text_w, NODE_DY);
}
if (gsock && (gsock->flag & SOCK_DYNAMIC)) {
@@ -837,7 +834,7 @@ static void node_draw_group(const bContext *C, ARegion *ar, SpaceNode *snode, bN
layout = uiBlockLayout(gnode->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL,
(int)(rect.xmin + NODE_MARGIN_X), (int)(rect.ymax + (group_header - (2.5f * dpi_fac))),
- mini((int)(BLI_RCT_SIZE_X(&rect) - 18.0f), node_group_frame + 20), group_header, UI_GetStyle());
+ min_ii((int)(BLI_rctf_size_x(&rect) - 18.0f), node_group_frame + 20), group_header, UI_GetStyle());
RNA_pointer_create(&ntree->id, &RNA_Node, gnode, &ptr);
uiTemplateIDBrowse(layout, (bContext *)C, &ptr, "node_tree", NULL, NULL, NULL);
uiBlockLayoutResolve(gnode->block, NULL, NULL);
@@ -898,11 +895,6 @@ static void node_uifunc_group(uiLayout *layout, bContext *C, PointerRNA *ptr)
uiTemplateIDBrowse(layout, C, ptr, "node_tree", NULL, NULL, NULL);
}
-static void node_common_buts_whileloop(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
-{
- uiItemR(layout, ptr, "max_iterations", 0, NULL, ICON_NONE);
-}
-
/* XXX Does a bounding box update by iterating over all children.
* Not ideal to do this in every draw call, but doing as transform callback doesn't work,
* since the child node totr rects are not updated properly at that point.
@@ -979,7 +971,7 @@ static void node_draw_frame_label(bNode *node, const float aspect)
ascender = BLF_ascender(fontid);
/* 'x' doesn't need aspect correction */
- x = BLI_RCT_CENTER_X(rct) - (0.5f * width);
+ x = BLI_rctf_cent_x(rct) - (0.5f * width);
y = rct->ymax - (((NODE_DY / 4) / aspect) + (ascender * aspect));
BLF_position(fontid, x, y, 0);
@@ -1182,16 +1174,6 @@ static void node_common_set_butfunc(bNodeType *ntype)
ntype->drawfunc = node_draw_group;
ntype->drawupdatefunc = node_update_group;
break;
- case NODE_FORLOOP:
-// ntype->uifunc= node_common_buts_group;
- ntype->drawfunc = node_draw_group;
- ntype->drawupdatefunc = node_update_group;
- break;
- case NODE_WHILELOOP:
- ntype->uifunc = node_common_buts_whileloop;
- ntype->drawfunc = node_draw_group;
- ntype->drawupdatefunc = node_update_group;
- break;
case NODE_FRAME:
ntype->drawfunc = node_draw_frame;
ntype->drawupdatefunc = node_update_frame;
@@ -1392,16 +1374,49 @@ static void node_shader_buts_tex_voronoi(uiLayout *layout, bContext *UNUSED(C),
uiItemR(layout, ptr, "coloring", 0, "", ICON_NONE);
}
+static void node_shader_buts_tex_coord(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
+{
+ uiItemR(layout, ptr, "from_dupli", 0, NULL, 0);
+}
+
static void node_shader_buts_glossy(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
{
uiItemR(layout, ptr, "distribution", 0, "", ICON_NONE);
}
+static void node_shader_buts_script(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
+{
+ uiLayout *row;
+
+ row = uiLayoutRow(layout, FALSE);
+ uiItemR(row, ptr, "mode", UI_ITEM_R_EXPAND, NULL, ICON_NONE);
+
+ row = uiLayoutRow(layout, TRUE);
+
+ if (RNA_enum_get(ptr, "mode") == NODE_SCRIPT_INTERNAL)
+ uiItemR(row, ptr, "script", 0, "", ICON_NONE);
+ else
+ uiItemR(row, ptr, "filepath", 0, "", ICON_NONE);
+
+ uiItemO(row, "", ICON_FILE_REFRESH, "node.shader_script_update");
+}
+
+static void node_shader_buts_script_details(uiLayout *layout, bContext *C, PointerRNA *ptr)
+{
+ uiItemS(layout);
+
+ node_shader_buts_script(layout, C, ptr);
+
+ /* not implemented yet
+ if(RNA_enum_get(ptr, "mode") == NODE_SCRIPT_EXTERNAL)
+ uiItemR(layout, ptr, "use_auto_update", 0, NULL, ICON_NONE);*/
+}
+
/* only once called */
static void node_shader_set_butfunc(bNodeType *ntype)
{
switch (ntype->type) {
- /* case NODE_GROUP: note, typeinfo for group is generated... see "XXX ugly hack" */
+ /* case NODE_GROUP: note, typeinfo for group is generated... see "XXX ugly hack" */
case SH_NODE_MATERIAL:
case SH_NODE_MATERIAL_EXT:
@@ -1473,10 +1488,17 @@ static void node_shader_set_butfunc(bNodeType *ntype)
case SH_NODE_TEX_VORONOI:
ntype->uifunc = node_shader_buts_tex_voronoi;
break;
+ case SH_NODE_TEX_COORD:
+ ntype->uifunc = node_shader_buts_tex_coord;
+ break;
case SH_NODE_BSDF_GLOSSY:
case SH_NODE_BSDF_GLASS:
ntype->uifunc = node_shader_buts_glossy;
break;
+ case SH_NODE_SCRIPT:
+ ntype->uifunc = node_shader_buts_script;
+ ntype->uifuncbut = node_shader_buts_script_details;
+ break;
}
}
@@ -1497,6 +1519,21 @@ static void node_composit_buts_image(uiLayout *layout, bContext *C, PointerRNA *
node_buts_image_user(layout, C, ptr, &imaptr, &iuserptr);
}
+static void node_composit_buts_image_details(uiLayout *layout, bContext *C, PointerRNA *ptr)
+{
+ bNode *node = ptr->data;
+ PointerRNA imaptr;
+
+ node_composit_buts_image(layout, C, ptr);
+
+ if (!node->id)
+ return;
+
+ imaptr = RNA_pointer_get(ptr, "image");
+
+ uiTemplateColorspaceSettings(layout, &imaptr, "colorspace_settings");
+}
+
static void node_composit_buts_renderlayers(uiLayout *layout, bContext *C, PointerRNA *ptr)
{
bNode *node = ptr->data;
@@ -2019,43 +2056,45 @@ static void node_composit_buts_file_output_details(uiLayout *layout, bContext *C
{
PointerRNA imfptr = RNA_pointer_get(ptr, "format");
PointerRNA active_input_ptr, op_ptr;
- uiLayout *row;
+ uiLayout *row, *col;
int active_index;
int multilayer = (RNA_enum_get(&imfptr, "file_format") == R_IMF_IMTYPE_MULTILAYER);
node_composit_buts_file_output(layout, C, ptr);
- uiTemplateImageSettings(layout, &imfptr, TRUE);
+ uiTemplateImageSettings(layout, &imfptr, FALSE);
uiItemS(layout);
uiItemO(layout, IFACE_("Add Input"), ICON_ZOOMIN, "NODE_OT_output_file_add_socket");
+ row = uiLayoutRow(layout, FALSE);
+ col = uiLayoutColumn(row, TRUE);
+
active_index = RNA_int_get(ptr, "active_input_index");
/* using different collection properties if multilayer format is enabled */
if (multilayer) {
- uiTemplateList(layout, C, ptr, "layer_slots", ptr, "active_input_index", NULL, 0, 0, 0);
+ uiTemplateList(col, C, ptr, "layer_slots", ptr, "active_input_index", NULL, 0, 0, 0);
RNA_property_collection_lookup_int(ptr, RNA_struct_find_property(ptr, "layer_slots"),
active_index, &active_input_ptr);
}
else {
- uiTemplateList(layout, C, ptr, "file_slots", ptr, "active_input_index", NULL, 0, 0, 0);
+ uiTemplateList(col, C, ptr, "file_slots", ptr, "active_input_index", NULL, 0, 0, 0);
RNA_property_collection_lookup_int(ptr, RNA_struct_find_property(ptr, "file_slots"),
active_index, &active_input_ptr);
}
/* XXX collection lookup does not return the ID part of the pointer, setting this manually here */
active_input_ptr.id.data = ptr->id.data;
- row = uiLayoutRow(layout, TRUE);
- op_ptr = uiItemFullO(row, "NODE_OT_output_file_move_active_socket", "",
+ col = uiLayoutColumn(row, TRUE);
+ op_ptr = uiItemFullO(col, "NODE_OT_output_file_move_active_socket", "",
ICON_TRIA_UP, NULL, WM_OP_INVOKE_DEFAULT, UI_ITEM_O_RETURN_PROPS);
RNA_enum_set(&op_ptr, "direction", 1);
- op_ptr = uiItemFullO(row, "NODE_OT_output_file_move_active_socket", "",
+ op_ptr = uiItemFullO(col, "NODE_OT_output_file_move_active_socket", "",
ICON_TRIA_DOWN, NULL, WM_OP_INVOKE_DEFAULT, UI_ITEM_O_RETURN_PROPS);
RNA_enum_set(&op_ptr, "direction", 2);
if (active_input_ptr.data) {
if (multilayer) {
- uiLayout *row, *col;
col = uiLayoutColumn(layout, TRUE);
uiItemL(col, IFACE_("Layer:"), ICON_NONE);
@@ -2065,7 +2104,6 @@ static void node_composit_buts_file_output_details(uiLayout *layout, bContext *C
ICON_X, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_R_ICON_ONLY);
}
else {
- uiLayout *row, *col;
col = uiLayoutColumn(layout, TRUE);
uiItemL(col, IFACE_("File Path:"), ICON_NONE);
@@ -2083,7 +2121,7 @@ static void node_composit_buts_file_output_details(uiLayout *layout, bContext *C
col = uiLayoutColumn(layout, FALSE);
uiLayoutSetActive(col, RNA_boolean_get(&active_input_ptr, "use_node_format") == FALSE);
- uiTemplateImageSettings(col, &imfptr, TRUE);
+ uiTemplateImageSettings(col, &imfptr, FALSE);
}
}
}
@@ -2224,6 +2262,21 @@ static void node_composit_buts_movieclip(uiLayout *layout, bContext *C, PointerR
uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL);
}
+static void node_composit_buts_movieclip_details(uiLayout *layout, bContext *C, PointerRNA *ptr)
+{
+ bNode *node = ptr->data;
+ PointerRNA clipptr;
+
+ uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL);
+
+ if (!node->id)
+ return;
+
+ clipptr = RNA_pointer_get(ptr, "clip");
+
+ uiTemplateColorspaceSettings(layout, &clipptr, "colorspace_settings");
+}
+
static void node_composit_buts_stabilize2d(uiLayout *layout, bContext *C, PointerRNA *ptr)
{
bNode *node = ptr->data;
@@ -2559,7 +2612,7 @@ static void node_composit_buts_keyingscreen(uiLayout *layout, bContext *C, Point
static void node_composit_buts_keying(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
{
- /* bNode *node= ptr->data; */ /* UNUSED */
+ /* bNode *node = ptr->data; */ /* UNUSED */
uiItemR(layout, ptr, "blur_pre", 0, NULL, ICON_NONE);
uiItemR(layout, ptr, "screen_balance", 0, NULL, ICON_NONE);
@@ -2609,7 +2662,7 @@ static void node_composit_buts_trackpos(uiLayout *layout, bContext *C, PointerRN
uiItemR(layout, ptr, "position", 0, NULL, ICON_NONE);
if (node->custom1 == 2) {
- uiItemR(layout, ptr, "relative_frame", 0, NULL, ICON_NONE);
+ uiItemR(layout, ptr, "frame_relative", 0, NULL, ICON_NONE);
}
}
}
@@ -2618,10 +2671,11 @@ static void node_composit_buts_trackpos(uiLayout *layout, bContext *C, PointerRN
static void node_composit_set_butfunc(bNodeType *ntype)
{
switch (ntype->type) {
- /* case NODE_GROUP: note, typeinfo for group is generated... see "XXX ugly hack" */
+ /* case NODE_GROUP: note, typeinfo for group is generated... see "XXX ugly hack" */
case CMP_NODE_IMAGE:
ntype->uifunc = node_composit_buts_image;
+ ntype->uifuncbut = node_composit_buts_image_details;
break;
case CMP_NODE_R_LAYERS:
ntype->uifunc = node_composit_buts_renderlayers;
@@ -2776,6 +2830,7 @@ static void node_composit_set_butfunc(bNodeType *ntype)
break;
case CMP_NODE_MOVIECLIP:
ntype->uifunc = node_composit_buts_movieclip;
+ ntype->uifuncbut = node_composit_buts_movieclip_details;
break;
case CMP_NODE_STABILIZE2D:
ntype->uifunc = node_composit_buts_stabilize2d;
@@ -3060,7 +3115,6 @@ void draw_nodespace_back_pix(const bContext *C, ARegion *ar, SpaceNode *snode)
void *lock;
ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, &lock);
if (ibuf) {
- SpaceNode *snode = CTX_wm_space_node(C);
float x, y;
unsigned char *display_buffer;
void *cache_handle;
@@ -3103,7 +3157,7 @@ void draw_nodespace_back_pix(const bContext *C, ARegion *ar, SpaceNode *snode)
/* swap bytes, so alpha is most significant one, then just draw it as luminance int */
glaDrawPixelsSafe(x, y, ibuf->x, ibuf->y, ibuf->x, GL_LUMINANCE, GL_UNSIGNED_INT,
- ((unsigned char *)ibuf->rect) + ofs);
+ display_buffer + ofs);
glPixelZoom(1.0f, 1.0f);
}
@@ -3189,7 +3243,7 @@ static void draw_nodespace_back_tex(ScrArea *sa, SpaceNode *snode)
float zoomx, zoomy;
zoomx = (float)sa->winx / ibuf->x;
zoomy = (float)sa->winy / ibuf->y;
- zoom = minf(zoomx, zoomy);
+ zoom = min_ff(zoomx, zoomy);
}
x = (sa->winx - zoom * ibuf->x) / 2 + snode->xof;
@@ -3520,7 +3574,7 @@ void node_draw_link(View2D *v2d, SpaceNode *snode, bNodeLink *link)
}
do_shaded = TRUE;
do_triple = TRUE;
- }
+ }
else {
th_col1 = TH_REDALERT;
}
diff --git a/source/blender/editors/space_node/node_add.c b/source/blender/editors/space_node/node_add.c
index 99d49fa1e8f..04d2947ce89 100644
--- a/source/blender/editors/space_node/node_add.c
+++ b/source/blender/editors/space_node/node_add.c
@@ -31,10 +31,15 @@
#include <errno.h>
+#include "MEM_guardedalloc.h"
+
#include "DNA_node_types.h"
+#include "BLI_listbase.h"
#include "BLI_math.h"
+#include "BLF_translation.h"
+
#include "BKE_context.h"
#include "BKE_image.h"
#include "BKE_library.h"
@@ -131,14 +136,105 @@ static int add_reroute_intersect_check(bNodeLink *link, float mcoords[][2], int
return 0;
}
+typedef struct bNodeSocketLink {
+ struct bNodeSocketLink *next, *prev;
+
+ struct bNodeSocket *sock;
+ struct bNodeLink *link;
+ float point[2];
+} bNodeSocketLink;
+
+static bNodeSocketLink *add_reroute_insert_socket_link(ListBase *lb, bNodeSocket *sock, bNodeLink *link, float point[2])
+{
+ bNodeSocketLink *socklink, *prev;
+
+ socklink = MEM_callocN(sizeof(bNodeSocketLink), "socket link");
+ socklink->sock = sock;
+ socklink->link = link;
+ copy_v2_v2(socklink->point, point);
+
+ for (prev = lb->last; prev; prev = prev->prev) {
+ if (prev->sock == sock)
+ break;
+ }
+ BLI_insertlinkafter(lb, prev, socklink);
+ return socklink;
+}
+
+static bNodeSocketLink *add_reroute_do_socket_section(bContext *C, bNodeSocketLink *socklink, int in_out)
+{
+ SpaceNode *snode = CTX_wm_space_node(C);
+ bNodeTree *ntree = snode->edittree;
+ bNode *reroute_node = NULL;
+ bNodeSocket *cursock = socklink->sock;
+ float insert_point[2];
+ int num_links;
+
+ zero_v2(insert_point);
+ num_links = 0;
+
+ while (socklink && socklink->sock == cursock) {
+ if (!(socklink->link->flag & NODE_LINK_TEST)) {
+ socklink->link->flag |= NODE_LINK_TEST;
+
+ /* create the reroute node for this cursock */
+ if (!reroute_node) {
+ bNodeTemplate ntemp;
+ ntemp.type = NODE_REROUTE;
+ reroute_node = nodeAddNode(ntree, &ntemp);
+
+ /* add a single link to/from the reroute node to replace multiple links */
+ if (in_out == SOCK_OUT) {
+ nodeAddLink(ntree, socklink->link->fromnode, socklink->link->fromsock, reroute_node, reroute_node->inputs.first);
+ }
+ else {
+ nodeAddLink(ntree, reroute_node, reroute_node->outputs.first, socklink->link->tonode, socklink->link->tosock);
+ }
+ }
+
+ /* insert the reroute node into the link */
+ if (in_out == SOCK_OUT) {
+ socklink->link->fromnode = reroute_node;
+ socklink->link->fromsock = reroute_node->outputs.first;
+ }
+ else {
+ socklink->link->tonode = reroute_node;
+ socklink->link->tosock = reroute_node->inputs.first;
+ }
+
+ add_v2_v2(insert_point, socklink->point);
+ ++num_links;
+ }
+ socklink = socklink->next;
+ }
+
+ if (num_links > 0) {
+ bNode *gnode = node_tree_get_editgroup(snode->nodetree);
+
+ /* average cut point from shared links */
+ mul_v2_fl(insert_point, 1.0f / num_links);
+
+ if (gnode) {
+ nodeFromView(gnode, insert_point[0], insert_point[1], &reroute_node->locx, &reroute_node->locy);
+ }
+ else {
+ reroute_node->locx = insert_point[0];
+ reroute_node->locy = insert_point[1];
+ }
+ }
+
+ return socklink;
+}
+
static int add_reroute_exec(bContext *C, wmOperator *op)
{
SpaceNode *snode = CTX_wm_space_node(C);
ARegion *ar = CTX_wm_region(C);
- bNode *gnode = node_tree_get_editgroup(snode->nodetree);
+ bNodeTree *ntree = snode->edittree;
float mcoords[256][2];
int i = 0;
-
+
+ /* Get the cut path */
RNA_BEGIN(op->ptr, itemptr, "path")
{
float loc[2];
@@ -152,46 +248,52 @@ static int add_reroute_exec(bContext *C, wmOperator *op)
RNA_END;
if (i > 1) {
+ ListBase output_links, input_links;
bNodeLink *link;
- float insertPoint[2];
-
- for (link = snode->edittree->links.first; link; link = link->next) {
- if (add_reroute_intersect_check(link, mcoords, i, insertPoint)) {
- bNodeTemplate ntemp;
- bNode *rerouteNode;
-
- /* always first */
- ED_preview_kill_jobs(C);
-
- node_deselect_all(snode);
-
- ntemp.type = NODE_REROUTE;
- rerouteNode = nodeAddNode(snode->edittree, &ntemp);
- if (gnode) {
- nodeFromView(gnode, insertPoint[0], insertPoint[1], &rerouteNode->locx, &rerouteNode->locy);
- }
- else {
- rerouteNode->locx = insertPoint[0];
- rerouteNode->locy = insertPoint[1];
- }
-
- nodeAddLink(snode->edittree, link->fromnode, link->fromsock, rerouteNode, rerouteNode->inputs.first);
- link->fromnode = rerouteNode;
- link->fromsock = rerouteNode->outputs.first;
-
- /* always last */
- ntreeUpdateTree(snode->edittree);
- snode_notify(C, snode);
- snode_dag_update(C, snode);
-
- return OPERATOR_FINISHED; // add one reroute at the time.
+ bNodeSocketLink *socklink;
+ float insert_point[2];
+
+ /* always first */
+ ED_preview_kill_jobs(C);
+
+ node_deselect_all(snode);
+
+ /* Find cut links and sort them by sockets */
+ output_links.first = output_links.last = NULL;
+ input_links.first = input_links.last = NULL;
+ for (link = ntree->links.first; link; link = link->next) {
+ if (add_reroute_intersect_check(link, mcoords, i, insert_point)) {
+ add_reroute_insert_socket_link(&output_links, link->fromsock, link, insert_point);
+ add_reroute_insert_socket_link(&input_links, link->tosock, link, insert_point);
+
+ /* Clear flag */
+ link->flag &= ~NODE_LINK_TEST;
}
}
-
- return OPERATOR_CANCELLED;
-
+
+ /* Create reroute nodes for intersected links.
+ * Only one reroute if links share the same input/output socket.
+ */
+ socklink = output_links.first;
+ while (socklink) {
+ socklink = add_reroute_do_socket_section(C, socklink, SOCK_OUT);
+ }
+ socklink = input_links.first;
+ while (socklink) {
+ socklink = add_reroute_do_socket_section(C, socklink, SOCK_IN);
+ }
+
+ BLI_freelistN(&output_links);
+ BLI_freelistN(&input_links);
+
+ /* always last */
+ ntreeUpdateTree(ntree);
+ snode_notify(C, snode);
+ snode_dag_update(C, snode);
+
+ return OPERATOR_FINISHED;
}
-
+
return OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH;
}
@@ -240,7 +342,8 @@ static int node_add_file_exec(bContext *C, wmOperator *op)
ima = BKE_image_load_exists(path);
if (!ima) {
- BKE_reportf(op->reports, RPT_ERROR, "Can't read image: \"%s\", %s", path, errno ? strerror(errno) : "Unsupported format");
+ BKE_reportf(op->reports, RPT_ERROR, "Cannot read image '%s': %s",
+ path, errno ? strerror(errno) : TIP_("unsupported format"));
return OPERATOR_CANCELLED;
}
}
@@ -250,7 +353,7 @@ static int node_add_file_exec(bContext *C, wmOperator *op)
ima = (Image *)BKE_libblock_find_name(ID_IM, name);
if (!ima) {
- BKE_reportf(op->reports, RPT_ERROR, "Image named \"%s\", not found", name);
+ BKE_reportf(op->reports, RPT_ERROR, "Image '%s' not found", name);
return OPERATOR_CANCELLED;
}
}
diff --git a/source/blender/editors/space_node/node_draw.c b/source/blender/editors/space_node/node_draw.c
index 7d35f566140..1d3b21fe2d6 100644
--- a/source/blender/editors/space_node/node_draw.c
+++ b/source/blender/editors/space_node/node_draw.c
@@ -62,10 +62,8 @@
#include "node_intern.h" /* own include */
#include "COM_compositor.h"
-/* width of socket columns in group display */
-#define NODE_GROUP_FRAME 120
/* XXX interface.h */
-extern void ui_dropshadow(rctf *rct, float radius, float aspect, float alpha, int select);
+extern void ui_dropshadow(const rctf *rct, float radius, float aspect, float alpha, int select);
/* XXX update functions for node editor are a mess, needs a clear concept */
void ED_node_tree_update(SpaceNode *snode, Scene *scene)
@@ -103,7 +101,7 @@ void ED_node_changed_update(ID *id, bNode *node)
nodeUpdateID(nodetree, node->id);
WM_main_add_notifier(NC_SCENE | ND_NODES, id);
- }
+ }
else if (treetype == NTREE_TEXTURE) {
DAG_id_tag_update(id, 0);
WM_main_add_notifier(NC_TEXTURE | ND_NODES, id);
@@ -343,7 +341,7 @@ static void node_update_basis(const bContext *C, bNodeTree *ntree, bNode *node)
if (node->prvr.ymax < node->prvr.ymin) SWAP(float, node->prvr.ymax, node->prvr.ymin);
}
else {
- float oldh = BLI_RCT_SIZE_Y(&node->prvr);
+ float oldh = BLI_rctf_size_y(&node->prvr);
if (oldh == 0.0f)
oldh = 0.6f * node->width - NODE_DY;
dy -= NODE_DYS / 2;
@@ -393,7 +391,7 @@ static void node_update_basis(const bContext *C, bNodeTree *ntree, bNode *node)
node->totr.xmin = locx;
node->totr.xmax = locx + node->width;
node->totr.ymax = locy;
- node->totr.ymin = minf(dy, locy - 2 * NODE_DY);
+ node->totr.ymin = min_ff(dy, locy - 2 * NODE_DY);
/* Set the block bounds to clip mouse events from underlying nodes.
* Add a margin for sockets on each side.
@@ -508,25 +506,16 @@ int node_get_colorid(bNode *node)
/* note: in node_edit.c is similar code, for untangle node */
static void node_draw_mute_line(View2D *v2d, SpaceNode *snode, bNode *node)
{
- ListBase links;
bNodeLink *link;
- if (node->typeinfo->internal_connect == NULL)
- return;
-
- /* Get default muting links. */
- links = node->typeinfo->internal_connect(snode->edittree, node);
-
glEnable(GL_BLEND);
glEnable(GL_LINE_SMOOTH);
- for (link = links.first; link; link = link->next)
+ for (link = node->internal_links.first; link; link = link->next)
node_draw_link_bezier(v2d, snode, link, TH_REDALERT, 0, TH_WIRE, 0, TH_WIRE);
glDisable(GL_BLEND);
glDisable(GL_LINE_SMOOTH);
-
- BLI_freelistN(&links);
}
/* this might have some more generic use */
@@ -584,9 +573,9 @@ void node_socket_circle_draw(bNodeTree *UNUSED(ntree), bNodeSocket *sock, float
/* not a callback */
static void node_draw_preview(bNodePreview *preview, rctf *prv)
{
- float xscale = BLI_RCT_SIZE_X(prv) / ((float)preview->xsize);
- float yscale = BLI_RCT_SIZE_Y(prv) / ((float)preview->ysize);
- float tile = BLI_RCT_SIZE_X(prv) / 10.0f;
+ float xscale = BLI_rctf_size_x(prv) / ((float)preview->xsize);
+ float yscale = BLI_rctf_size_y(prv) / ((float)preview->ysize);
+ float tile = BLI_rctf_size_x(prv) / 10.0f;
float x, y;
/* draw checkerboard backdrop to show alpha */
@@ -670,7 +659,7 @@ static void node_draw_basis(const bContext *C, ARegion *ar, SpaceNode *snode, bN
bNodeSocket *sock;
rctf *rct = &node->totr;
float iconofs;
- /* float socket_size= NODE_SOCKSIZE*U.dpi/72; */ /* UNUSED */
+ /* float socket_size = NODE_SOCKSIZE*U.dpi/72; */ /* UNUSED */
float iconbutw = 0.8f * UI_UNIT_X;
int color_id = node_get_colorid(node);
char showname[128]; /* 128 used below */
@@ -852,8 +841,8 @@ static void node_draw_hidden(const bContext *C, ARegion *ar, SpaceNode *snode, b
{
bNodeSocket *sock;
rctf *rct = &node->totr;
- float dx, centy = BLI_RCT_CENTER_Y(rct);
- float hiddenrad = BLI_RCT_SIZE_Y(rct) / 2.0f;
+ float dx, centy = BLI_rctf_cent_y(rct);
+ float hiddenrad = BLI_rctf_size_y(rct) / 2.0f;
float socket_size = NODE_SOCKSIZE * U.dpi / 72;
int color_id = node_get_colorid(node);
char showname[128]; /* 128 is used below */
@@ -917,7 +906,7 @@ static void node_draw_hidden(const bContext *C, ARegion *ar, SpaceNode *snode, b
/* disable lines */
if (node->flag & NODE_MUTED)
- node_draw_mute_line(&ar->v2d, snode, node);
+ node_draw_mute_line(&ar->v2d, snode, node);
if (node->flag & SELECT)
UI_ThemeColor(TH_SELECT);
@@ -932,9 +921,9 @@ static void node_draw_hidden(const bContext *C, ARegion *ar, SpaceNode *snode, b
uiDefBut(node->block, LABEL, 0, showname,
(int)(rct->xmin + (NODE_MARGIN_X / snode->aspect_sqrt)), (int)(centy - 10),
- (short)(BLI_RCT_SIZE_X(rct) - 18.0f - 12.0f), (short)NODE_DY,
+ (short)(BLI_rctf_size_x(rct) - 18.0f - 12.0f), (short)NODE_DY,
NULL, 0, 0, 0, 0, "");
- }
+ }
/* scale widget thing */
UI_ThemeColorShade(color_id, -10);
@@ -1108,9 +1097,9 @@ void drawnodespace(const bContext *C, ARegion *ar, View2D *v2d)
glEnable(GL_MAP1_VERTEX_3);
/* aspect+font, set each time */
- snode->aspect = BLI_RCT_SIZE_X(&v2d->cur) / (float)ar->winx;
+ snode->aspect = BLI_rctf_size_x(&v2d->cur) / (float)ar->winx;
snode->aspect_sqrt = sqrtf(snode->aspect);
- // XXX snode->curfont= uiSetCurFont_ext(snode->aspect);
+ // XXX snode->curfont = uiSetCurFont_ext(snode->aspect);
/* grid */
UI_view2d_multi_grid_draw(v2d, 25.0f, 5, 2);
@@ -1140,7 +1129,7 @@ void drawnodespace(const bContext *C, ARegion *ar, View2D *v2d)
#ifdef WITH_COMPOSITOR
if (snode->nodetree->type == NTREE_COMPOSIT) {
COM_startReadHighlights();
- }
+ }
#endif
node_draw_nodetree(C, ar, snode, snode->nodetree);
diff --git a/source/blender/editors/space_node/node_edit.c b/source/blender/editors/space_node/node_edit.c
index cc386da2e93..6bf0e9f73e3 100644
--- a/source/blender/editors/space_node/node_edit.c
+++ b/source/blender/editors/space_node/node_edit.c
@@ -35,6 +35,7 @@
#include "DNA_material_types.h"
#include "DNA_node_types.h"
#include "DNA_object_types.h"
+#include "DNA_text_types.h"
#include "DNA_world_types.h"
#include "BLI_math.h"
@@ -54,6 +55,7 @@
#include "BKE_scene.h"
#include "BKE_texture.h"
+#include "RE_engine.h"
#include "RE_pipeline.h"
@@ -1622,7 +1624,7 @@ static int node_mute_exec(bContext *C, wmOperator *UNUSED(op))
for (node = snode->edittree->nodes.first; node; node = node->next) {
/* Only allow muting of nodes having a mute func! */
- if ((node->flag & SELECT) && node->typeinfo->internal_connect) {
+ if ((node->flag & SELECT) && node->typeinfo->update_internal_links) {
node->flag ^= NODE_MUTED;
snode_update(snode, node);
}
@@ -1935,7 +1937,7 @@ static int node_clipboard_copy_exec(bContext *C, wmOperator *UNUSED(op))
bNodeTree *ntree = snode->edittree;
bNode *gnode = node_tree_get_editgroup(snode->nodetree);
float gnode_x = 0.0f, gnode_y = 0.0f;
- bNode *node, *new_node;
+ bNode *node;
bNodeLink *link, *newlink;
ED_preview_kill_jobs(C);
@@ -1950,6 +1952,7 @@ static int node_clipboard_copy_exec(bContext *C, wmOperator *UNUSED(op))
for (node = ntree->nodes.first; node; node = node->next) {
if (node->flag & SELECT) {
+ bNode *new_node;
new_node = nodeCopyNode(NULL, node);
BKE_node_clipboard_add_node(new_node);
}
@@ -1971,7 +1974,7 @@ static int node_clipboard_copy_exec(bContext *C, wmOperator *UNUSED(op))
}
/* transform to basic view space. child node location is relative to parent */
- if (!new_node->parent) {
+ if (!new_node->parent) {
new_node->locx += gnode_x;
new_node->locy += gnode_y;
}
@@ -2067,8 +2070,8 @@ static int node_clipboard_paste_exec(bContext *C, wmOperator *op)
/* calculate "barycenter" for placing on mouse cursor */
zero_v2(center);
for (node = clipboard_nodes_lb->first, num_nodes = 0; node; node = node->next, num_nodes++) {
- center[0] += BLI_RCT_CENTER_X(&node->totr);
- center[1] += BLI_RCT_CENTER_Y(&node->totr);
+ center[0] += BLI_rctf_cent_x(&node->totr);
+ center[1] += BLI_rctf_cent_y(&node->totr);
}
mul_v2_fl(center, 1.0 / num_nodes);
@@ -2136,3 +2139,120 @@ void NODE_OT_clipboard_paste(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+
+/* ********************** Shader Script Update ******************/
+
+typedef struct ScriptUpdateData {
+ RenderEngine *engine;
+ RenderEngineType *type;
+
+ Text *text;
+ int found;
+} ScriptUpdateData;
+
+static int node_shader_script_update_poll(bContext *C)
+{
+ Scene *scene = CTX_data_scene(C);
+ RenderEngineType *type = RE_engines_find(scene->r.engine);
+ bNode *node;
+ Text *text;
+
+ /* test if we have a render engine that supports shaders scripts */
+ if (!(type && type->update_script_node))
+ return 0;
+
+ /* see if we have a shader script node in context */
+ node = CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript).data;
+ if (node && node->type == SH_NODE_SCRIPT) {
+ NodeShaderScript *nss = node->storage;
+
+ if (node->id || nss->filepath[0]) {
+ return 1;
+ }
+ }
+
+ /* see if we have a text datablock in context */
+ text = CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;
+ if (text)
+ return 1;
+
+ /* we don't check if text datablock is actually in use, too slow for poll */
+
+ return 0;
+}
+
+static void node_shader_script_update_text(void *data_, ID *UNUSED(id), bNodeTree *ntree)
+{
+ ScriptUpdateData *data = (ScriptUpdateData *)data_;
+ bNode *node;
+
+ /* update each script that is using this text datablock */
+ for (node = ntree->nodes.first; node; node = node->next) {
+ if (node->type == NODE_GROUP) {
+ node_shader_script_update_text(data_, NULL, (bNodeTree *)node->id);
+ }
+ else if (node->type == SH_NODE_SCRIPT && node->id == &data->text->id) {
+ data->type->update_script_node(data->engine, ntree, node);
+ data->found = TRUE;
+ }
+ }
+}
+
+static int node_shader_script_update_exec(bContext *C, wmOperator *op)
+{
+ Main *bmain = CTX_data_main(C);
+ Scene *scene = CTX_data_scene(C);
+ ScriptUpdateData data;
+ PointerRNA nodeptr = CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript);
+
+ /* setup render engine */
+ data.type = RE_engines_find(scene->r.engine);
+ data.engine = RE_engine_create(data.type);
+ data.engine->reports = op->reports;
+ data.text = NULL;
+ data.found = FALSE;
+
+ if (nodeptr.data) {
+ /* update single node */
+ bNodeTree *ntree = nodeptr.id.data;
+ bNode *node = nodeptr.data;
+
+ data.type->update_script_node(data.engine, ntree, node);
+
+ data.found = TRUE;
+ }
+ else {
+ /* update all nodes using text datablock */
+ data.text = CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;
+
+ if (data.text) {
+ bNodeTreeType *ntreetype = ntreeGetType(NTREE_SHADER);
+
+ if (ntreetype && ntreetype->foreach_nodetree)
+ ntreetype->foreach_nodetree(bmain, &data, node_shader_script_update_text);
+
+ if (!data.found)
+ BKE_report(op->reports, RPT_INFO, "Text not used by any node, no update done.");
+ }
+ }
+
+ RE_engine_free(data.engine);
+
+ return (data.found)? OPERATOR_FINISHED: OPERATOR_CANCELLED;
+}
+
+void NODE_OT_shader_script_update(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Script Node Update";
+ ot->description = "Update shader script node with new sockets and options from the script";
+ ot->idname = "NODE_OT_shader_script_update";
+
+ /* api callbacks */
+ ot->exec = node_shader_script_update_exec;
+ ot->poll = node_shader_script_update_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+}
+
diff --git a/source/blender/editors/space_node/node_group.c b/source/blender/editors/space_node/node_group.c
index b76cc05af5c..5f8b5db7766 100644
--- a/source/blender/editors/space_node/node_group.c
+++ b/source/blender/editors/space_node/node_group.c
@@ -583,7 +583,7 @@ static int node_group_ungroup_exec(bContext *C, wmOperator *op)
ntreeUpdateTree(snode->nodetree);
}
else {
- BKE_report(op->reports, RPT_WARNING, "Can't ungroup");
+ BKE_report(op->reports, RPT_WARNING, "Cannot ungroup");
return OPERATOR_CANCELLED;
}
@@ -755,13 +755,13 @@ static int node_group_separate_exec(bContext *C, wmOperator *op)
switch (type) {
case NODE_GS_COPY:
if (!node_group_separate_selected(snode->nodetree, gnode, 1)) {
- BKE_report(op->reports, RPT_WARNING, "Can't separate nodes");
+ BKE_report(op->reports, RPT_WARNING, "Cannot separate nodes");
return OPERATOR_CANCELLED;
}
break;
case NODE_GS_MOVE:
if (!node_group_separate_selected(snode->nodetree, gnode, 0)) {
- BKE_report(op->reports, RPT_WARNING, "Can't separate nodes");
+ BKE_report(op->reports, RPT_WARNING, "Cannot separate nodes");
return OPERATOR_CANCELLED;
}
break;
@@ -875,7 +875,7 @@ static int node_group_make_insert_selected(bNodeTree *ntree, bNode *gnode)
bNodeTree *ngroup = (bNodeTree *)gnode->id;
bNodeLink *link, *linkn;
bNode *node, *nextn;
- bNodeSocket *gsock;
+ bNodeSocket *gsock, *sock;
ListBase anim_basepaths = {NULL, NULL};
float min[2], max[2];
@@ -982,8 +982,42 @@ static int node_group_make_insert_selected(bNodeTree *ntree, bNode *gnode)
}
}
+ /* auto-add interface for "solo" nodes */
+ node = ((bNodeTree *)gnode->id)->nodes.first;
+ if (node && !node->next) {
+ for (sock = node->inputs.first; sock; sock = sock->next) {
+ int skip = FALSE;
+
+ for (link = ((bNodeTree *)gnode->id)->links.first; link; link = link->next)
+ if (link->tosock == sock)
+ skip = TRUE;
+
+ if (skip == TRUE)
+ continue;
+
+ gsock = node_group_expose_socket(ngroup, sock, SOCK_IN);
+ node_group_add_extern_socket(ntree, &gnode->inputs, SOCK_IN, gsock);
+ nodeAddLink(ngroup, NULL, gsock, node, sock);
+ }
+
+ for (sock = node->outputs.first; sock; sock = sock->next) {
+ int skip = FALSE;
+
+ for (link = ((bNodeTree *)gnode->id)->links.first; link; link = link->next)
+ if (link->fromsock == sock)
+ skip = TRUE;
+
+ if (skip == TRUE)
+ continue;
+
+ gsock = node_group_expose_socket(ngroup, sock, SOCK_OUT);
+ node_group_add_extern_socket(ntree, &gnode->outputs, SOCK_OUT, gsock);
+ nodeAddLink(ngroup, NULL, gsock, node, sock);
+ }
+ }
+
/* update of the group tree */
- ngroup->update |= NTREE_UPDATE;
+ ngroup->update |= NTREE_UPDATE | NTREE_UPDATE_LINKS;
/* update of the tree containing the group instance node */
ntree->update |= NTREE_UPDATE_NODES | NTREE_UPDATE_LINKS;
@@ -1036,7 +1070,7 @@ static int node_group_make_exec(bContext *C, wmOperator *op)
int type = RNA_enum_get(op->ptr, "type");
if (snode->edittree != snode->nodetree) {
- BKE_report(op->reports, RPT_WARNING, "Can not add a new Group in a Group");
+ BKE_report(op->reports, RPT_WARNING, "Cannot add a new group in a group");
return OPERATOR_CANCELLED;
}
@@ -1049,7 +1083,7 @@ static int node_group_make_exec(bContext *C, wmOperator *op)
}
if (gnode) {
- BKE_report(op->reports, RPT_WARNING, "Can not add RenderLayer in a Group");
+ BKE_report(op->reports, RPT_WARNING, "Cannot add a Render Layers node in a group");
return OPERATOR_CANCELLED;
}
}
@@ -1062,21 +1096,21 @@ static int node_group_make_exec(bContext *C, wmOperator *op)
gnode = node_group_make_from_selected(snode->nodetree);
}
else {
- BKE_report(op->reports, RPT_WARNING, "Can not make Group");
+ BKE_report(op->reports, RPT_WARNING, "Cannot make group");
return OPERATOR_CANCELLED;
}
break;
case NODE_GM_INSERT:
gnode = nodeGetActive(snode->nodetree);
if (!gnode || gnode->type != NODE_GROUP) {
- BKE_report(op->reports, RPT_WARNING, "No active Group node");
+ BKE_report(op->reports, RPT_WARNING, "No active group node");
return OPERATOR_CANCELLED;
}
if (node_group_make_test(snode->nodetree, gnode)) {
node_group_make_insert_selected(snode->nodetree, gnode);
}
else {
- BKE_report(op->reports, RPT_WARNING, "Can not insert into Group");
+ BKE_report(op->reports, RPT_WARNING, "Cannot insert into group");
return OPERATOR_CANCELLED;
}
break;
diff --git a/source/blender/editors/space_node/node_header.c b/source/blender/editors/space_node/node_header.c
index 5ab698cd415..e82917feb21 100644
--- a/source/blender/editors/space_node/node_header.c
+++ b/source/blender/editors/space_node/node_header.c
@@ -138,12 +138,6 @@ static void do_node_add_group(bContext *C, void *UNUSED(arg), int event)
case NODE_GROUP:
ntemp.ngroup = ntreeAddTree("Group", snode->treetype, ntemp.type);
break;
- case NODE_FORLOOP:
- ntemp.ngroup = ntreeAddTree("For Loop", snode->treetype, ntemp.type);
- break;
- case NODE_WHILELOOP:
- ntemp.ngroup = ntreeAddTree("While Loop", snode->treetype, ntemp.type);
- break;
default:
ntemp.ngroup = NULL;
}
@@ -199,15 +193,11 @@ static void node_add_menu(bContext *C, uiLayout *layout, void *arg_nodeclass)
/* XXX hack: negative numbers used for empty group types */
if (node_tree_has_type(ntree->type, NODE_GROUP))
uiItemV(layout, IFACE_("New Group"), 0, -NODE_GROUP);
- if (node_tree_has_type(ntree->type, NODE_FORLOOP))
- uiItemV(layout, IFACE_("New For Loop"), 0, -NODE_FORLOOP);
- if (node_tree_has_type(ntree->type, NODE_WHILELOOP))
- uiItemV(layout, IFACE_("New While Loop"), 0, -NODE_WHILELOOP);
uiItemS(layout);
for (ngroup = bmain->nodetree.first, event = 0; ngroup; ngroup = ngroup->id.next, ++event) {
/* only use group trees */
- if (ngroup->type == ntree->type && ELEM3(ngroup->nodetype, NODE_GROUP, NODE_FORLOOP, NODE_WHILELOOP)) {
+ if (ngroup->type == ntree->type && ngroup->nodetype == NODE_GROUP) {
uiItemV(layout, ngroup->id.name + 2, 0, event);
}
}
diff --git a/source/blender/editors/space_node/node_intern.h b/source/blender/editors/space_node/node_intern.h
index 36ebddc8d22..45509e02226 100644
--- a/source/blender/editors/space_node/node_intern.h
+++ b/source/blender/editors/space_node/node_intern.h
@@ -206,6 +206,8 @@ void NODE_OT_output_file_move_active_socket(struct wmOperatorType *ot);
void NODE_OT_clipboard_copy(struct wmOperatorType *ot);
void NODE_OT_clipboard_paste(struct wmOperatorType *ot);
+void NODE_OT_shader_script_update(struct wmOperatorType *ot);
+
extern const char *node_context_dir[];
// XXXXXX
diff --git a/source/blender/editors/space_node/node_ops.c b/source/blender/editors/space_node/node_ops.c
index a5032fb6465..64e5f67a348 100644
--- a/source/blender/editors/space_node/node_ops.c
+++ b/source/blender/editors/space_node/node_ops.c
@@ -117,6 +117,8 @@ void node_operatortypes(void)
WM_operatortype_append(NODE_OT_clipboard_copy);
WM_operatortype_append(NODE_OT_clipboard_paste);
+
+ WM_operatortype_append(NODE_OT_shader_script_update);
}
void ED_operatormacros_node(void)
@@ -167,7 +169,7 @@ void ED_operatormacros_node(void)
ot = WM_operatortype_append_macro("NODE_OT_move_detach_links_release", "Detach", "Move a node to detach links",
OPTYPE_UNDO | OPTYPE_REGISTER);
WM_operatortype_macro_define(ot, "NODE_OT_links_detach");
- mot = WM_operatortype_macro_define(ot, "NODE_OT_translate_attach");
+ WM_operatortype_macro_define(ot, "NODE_OT_translate_attach");
}
/* helper function for repetitive select operator keymap */
diff --git a/source/blender/editors/space_node/node_relationships.c b/source/blender/editors/space_node/node_relationships.c
index fec7366ee73..7fa48c48ad6 100644
--- a/source/blender/editors/space_node/node_relationships.c
+++ b/source/blender/editors/space_node/node_relationships.c
@@ -136,7 +136,7 @@ static bNodeSocket *best_socket_input(bNodeTree *ntree, bNode *node, int num, in
int a = 0;
for (sock = node->inputs.first; sock; sock = sock->next) {
- maxtype = MAX2(sock->type, maxtype);
+ maxtype = max_ii(sock->type, maxtype);
}
/* find sockets of higher 'types' first (i.e. image) */
@@ -1368,7 +1368,7 @@ static bNodeSocket *socket_best_match(ListBase *sockets)
/* find type range */
for (sock = sockets->first; sock; sock = sock->next)
- maxtype = MAX2(sock->type, maxtype);
+ maxtype = max_ii(sock->type, maxtype);
/* try all types, starting from 'highest' (i.e. colors, vectors, values) */
for (type = maxtype; type >= 0; --type) {
diff --git a/source/blender/editors/space_node/node_select.c b/source/blender/editors/space_node/node_select.c
index a56d76a3ef7..a3efa15c54a 100644
--- a/source/blender/editors/space_node/node_select.c
+++ b/source/blender/editors/space_node/node_select.c
@@ -539,7 +539,7 @@ void NODE_OT_select_border(wmOperatorType *ot)
/* ****** Lasso Select ****** */
-static int do_lasso_select_node(bContext *C, int mcords[][2], short moves, short select)
+static int do_lasso_select_node(bContext *C, const int mcords[][2], short moves, short select)
{
SpaceNode *snode = CTX_wm_space_node(C);
bNode *node;
@@ -555,8 +555,8 @@ static int do_lasso_select_node(bContext *C, int mcords[][2], short moves, short
/* do actual selection */
for (node = snode->edittree->nodes.first; node; node = node->next) {
int screen_co[2];
- const float cent[2] = {BLI_RCT_CENTER_X(&node->totr),
- BLI_RCT_CENTER_Y(&node->totr)};
+ const float cent[2] = {BLI_rctf_cent_x(&node->totr),
+ BLI_rctf_cent_y(&node->totr)};
/* marker in screen coords */
UI_view2d_view_to_region(&ar->v2d,
@@ -585,7 +585,7 @@ static int do_lasso_select_node(bContext *C, int mcords[][2], short moves, short
static int node_lasso_select_exec(bContext *C, wmOperator *op)
{
int mcords_tot;
- int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
+ const int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
if (mcords) {
short select;
@@ -593,7 +593,7 @@ static int node_lasso_select_exec(bContext *C, wmOperator *op)
select = !RNA_boolean_get(op->ptr, "deselect");
do_lasso_select_node(C, mcords, mcords_tot, select);
- MEM_freeN(mcords);
+ MEM_freeN((void *)mcords);
return OPERATOR_FINISHED;
}
diff --git a/source/blender/editors/space_node/node_templates.c b/source/blender/editors/space_node/node_templates.c
index 7881014ed54..23f4e948794 100644
--- a/source/blender/editors/space_node/node_templates.c
+++ b/source/blender/editors/space_node/node_templates.c
@@ -122,6 +122,7 @@ static void node_socket_disconnect(Main *bmain, bNodeTree *ntree, bNode *node_to
return;
nodeRemLink(ntree, sock_to->link);
+ sock_to->flag |= SOCK_COLLAPSED;
nodeUpdate(ntree, node_to);
ntreeUpdateTree(ntree);
@@ -136,6 +137,7 @@ static void node_socket_remove(Main *bmain, bNodeTree *ntree, bNode *node_to, bN
return;
node_remove_linked(ntree, sock_to->link->fromnode);
+ sock_to->flag |= SOCK_COLLAPSED;
nodeUpdate(ntree, node_to);
ntreeUpdateTree(ntree);
@@ -147,7 +149,7 @@ static void node_socket_remove(Main *bmain, bNodeTree *ntree, bNode *node_to, bN
static void node_socket_add_replace(Main *bmain, bNodeTree *ntree, bNode *node_to, bNodeSocket *sock_to, bNodeTemplate *ntemp, int sock_num)
{
bNode *node_from;
- bNodeSocket *sock_from;
+ bNodeSocket *sock_from_tmp;
bNode *node_prev = NULL;
/* unlink existing node */
@@ -183,8 +185,9 @@ static void node_socket_add_replace(Main *bmain, bNodeTree *ntree, bNode *node_t
nodeSetActive(ntree, node_from);
/* add link */
- sock_from = BLI_findlink(&node_from->outputs, sock_num);
- nodeAddLink(ntree, node_from, sock_from, node_to, sock_to);
+ sock_from_tmp = BLI_findlink(&node_from->outputs, sock_num);
+ nodeAddLink(ntree, node_from, sock_from_tmp, node_to, sock_to);
+ sock_to->flag &= ~SOCK_COLLAPSED;
/* copy input sockets from previous node */
if (node_prev && node_from != node_prev) {
@@ -230,7 +233,7 @@ static void node_socket_add_replace(Main *bmain, bNodeTree *ntree, bNode *node_t
/****************************** Node Link Menu *******************************/
-#define UI_NODE_LINK_ADD 0
+// #define UI_NODE_LINK_ADD 0
#define UI_NODE_LINK_DISCONNECT -1
#define UI_NODE_LINK_REMOVE -2
@@ -289,8 +292,7 @@ static void ui_node_sock_name(bNodeSocket *sock, char name[UI_MAX_NAME_STR])
BLI_strncpy(node_name, node->typeinfo->name, UI_MAX_NAME_STR);
if (node->inputs.first == NULL &&
- node->outputs.first != node->outputs.last &&
- !(node->typeinfo->flag & NODE_OPTIONS))
+ node->outputs.first != node->outputs.last)
{
BLI_snprintf(name, UI_MAX_NAME_STR, "%s | %s", IFACE_(node_name), IFACE_(sock->link->fromsock->name));
}
@@ -613,7 +615,7 @@ static void ui_node_draw_input(uiLayout *layout, bContext *C, bNodeTree *ntree,
/* input linked to a node */
uiTemplateNodeLink(split, ntree, node, input);
- if (!(input->flag & SOCK_COLLAPSED)) {
+ if (depth == 0 || !(input->flag & SOCK_COLLAPSED)) {
if (depth == 0)
uiItemS(layout);
diff --git a/source/blender/editors/space_node/node_view.c b/source/blender/editors/space_node/node_view.c
index 8e38247348f..ccf5c4b540f 100644
--- a/source/blender/editors/space_node/node_view.c
+++ b/source/blender/editors/space_node/node_view.c
@@ -72,8 +72,8 @@ static int space_node_view_flag(bContext *C, SpaceNode *snode, ARegion *ar, cons
int tot = 0;
int has_frame = FALSE;
- oldwidth = BLI_RCT_SIZE_X(&ar->v2d.cur);
- oldheight = BLI_RCT_SIZE_Y(&ar->v2d.cur);
+ oldwidth = BLI_rctf_size_x(&ar->v2d.cur);
+ oldheight = BLI_rctf_size_y(&ar->v2d.cur);
BLI_rctf_init_minmax(&cur_new);
@@ -91,8 +91,8 @@ static int space_node_view_flag(bContext *C, SpaceNode *snode, ARegion *ar, cons
}
if (tot) {
- width = BLI_RCT_SIZE_X(&cur_new);
- height = BLI_RCT_SIZE_Y(&cur_new);
+ width = BLI_rctf_size_x(&cur_new);
+ height = BLI_rctf_size_y(&cur_new);
/* for single non-frame nodes, don't zoom in, just pan view,
* but do allow zooming out, this allows for big nodes to be zoomed out */
@@ -358,6 +358,13 @@ int ED_space_node_color_sample(SpaceNode *snode, ARegion *ar, int mval[2], float
float fx, fy, bufx, bufy;
int ret = FALSE;
+ if (snode->treetype != NTREE_COMPOSIT || (snode->flag & SNODE_BACKDRAW) == 0) {
+ /* use viewer image for color sampling only if we're in compositor tree
+ * with backdrop enabled
+ */
+ return FALSE;
+ }
+
ima = BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
ibuf = BKE_image_acquire_ibuf(ima, NULL, &lock);
if (!ibuf) {
diff --git a/source/blender/editors/space_node/space_node.c b/source/blender/editors/space_node/space_node.c
index 0601d7c105f..4d2512cdc93 100644
--- a/source/blender/editors/space_node/space_node.c
+++ b/source/blender/editors/space_node/space_node.c
@@ -111,7 +111,6 @@ static SpaceLink *node_new(const bContext *UNUSED(C))
BLI_addtail(&snode->regionbase, ar);
ar->regiontype = RGN_TYPE_UI;
ar->alignment = RGN_ALIGN_RIGHT;
- ar->flag = RGN_FLAG_HIDDEN;
/* main area */
ar = MEM_callocN(sizeof(ARegion), "main area for node");
@@ -254,6 +253,15 @@ static void node_area_listener(ScrArea *sa, wmNotifier *wmn)
}
}
break;
+
+ case NC_MOVIECLIP:
+ if (wmn->action == NA_EDITED) {
+ if (type == NTREE_COMPOSIT) {
+ if (nodeUpdateID(snode->nodetree, wmn->reference))
+ ED_area_tag_refresh(sa);
+ }
+ }
+ break;
}
}
@@ -440,9 +448,6 @@ static void node_region_listener(ARegion *ar, wmNotifier *wmn)
break;
case NC_SCREEN:
switch (wmn->data) {
- case ND_GPENCIL:
- ED_region_tag_redraw(ar);
- break;
case ND_SCREENCAST:
case ND_ANIMPLAY:
ED_region_tag_redraw(ar);
@@ -463,6 +468,10 @@ static void node_region_listener(ARegion *ar, wmNotifier *wmn)
if (wmn->action == NA_RENAME)
ED_region_tag_redraw(ar);
break;
+ case NC_GPENCIL:
+ if (wmn->action == NA_EDITED)
+ ED_region_tag_redraw(ar);
+ break;
}
}
diff --git a/source/blender/editors/space_outliner/outliner_draw.c b/source/blender/editors/space_outliner/outliner_draw.c
index 21e06f00d8e..c4afe32e85f 100644
--- a/source/blender/editors/space_outliner/outliner_draw.c
+++ b/source/blender/editors/space_outliner/outliner_draw.c
@@ -36,6 +36,7 @@
#include "DNA_scene_types.h"
#include "DNA_sequence_types.h"
+#include "BLI_math.h"
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
@@ -92,7 +93,7 @@ static void outliner_width(SpaceOops *soops, ListBase *lb, int *w)
{
TreeElement *te = lb->first;
while (te) {
-// TreeStoreElem *tselem= TREESTORE(te);
+// TreeStoreElem *tselem = TREESTORE(te);
// XXX fixme... te->xend is not set yet
if (!TSELEM_OPEN(tselem, soops)) {
@@ -238,9 +239,9 @@ static int group_select_flag(Group *gr)
void restrictbutton_gr_restrict_flag(void *poin, void *poin2, int flag)
{
- Scene *scene = (Scene *)poin;
+ Scene *scene = (Scene *)poin;
GroupObject *gob;
- Group *gr = (Group *)poin2;
+ Group *gr = (Group *)poin2;
if (group_restrict_flag(gr, flag)) {
for (gob = gr->gobject.first; gob; gob = gob->next) {
@@ -256,10 +257,12 @@ void restrictbutton_gr_restrict_flag(void *poin, void *poin2, int flag)
/* not in editmode */
if (scene->obedit != gob->ob) {
gob->ob->restrictflag |= flag;
-
- if (flag == OB_RESTRICT_VIEW)
- if ((gob->ob->flag & SELECT) == 0)
- ED_base_object_select(BKE_scene_base_find(scene, gob->ob), BA_SELECT);
+
+ if (ELEM(flag, OB_RESTRICT_SELECT, OB_RESTRICT_VIEW)) {
+ if ((gob->ob->flag & SELECT)) {
+ ED_base_object_select(BKE_scene_base_find(scene, gob->ob), BA_DESELECT);
+ }
+ }
}
}
}
@@ -307,7 +310,7 @@ static void namebutton_cb(bContext *C, void *tsep, char *oldname)
WM_event_add_notifier(C, NC_SCENE, NULL); break;
default:
WM_event_add_notifier(C, NC_ID | NA_RENAME, NULL); break;
- }
+ }
/* Check the library target exists */
if (te->idcode == ID_LI) {
Library *lib = (Library *)tselem->id;
@@ -625,7 +628,7 @@ static uiBlock *operator_search_menu(bContext *C, ARegion *ar, void *arg_kmi)
search[0] = 0;
block = uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
- uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_REDRAW | UI_BLOCK_RET_1);
+ uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_REDRAW | UI_BLOCK_SEARCH_MENU);
/* fake button, it holds space for search items */
uiDefBut(block, LABEL, 0, "", 10, 15, 150, uiSearchBoxhHeight(), NULL, 0, 0, 0, 0, NULL);
@@ -634,7 +637,7 @@ static uiBlock *operator_search_menu(bContext *C, ARegion *ar, void *arg_kmi)
uiButSetSearchFunc(but, operator_search_cb, arg_kmi, operator_call_cb, ot);
uiBoundsBlock(block, 6);
- uiBlockSetDirection(block, UI_DOWN);
+ uiBlockSetDirection(block, UI_DOWN);
uiEndBlock(C, block);
event = *(win->eventstate); /* XXX huh huh? make api call */
@@ -781,7 +784,9 @@ static void outliner_draw_keymapbuts(uiBlock *block, ARegion *ar, SpaceOops *soo
wmKeyMapItem *kmi = te->directdata;
/* modal map? */
- if (kmi->propvalue) ;
+ if (kmi->propvalue) {
+ /* pass */
+ }
else {
uiDefBlockBut(block, operator_search_menu, kmi, "", xstart, (int)te->ys + 1, butw1, UI_UNIT_Y - 1, "Assign new Operator");
}
@@ -996,6 +1001,7 @@ static void tselem_draw_icon(uiBlock *block, int xmax, float x, float y, TreeSto
case eModifierType_Bevel:
UI_icon_draw(x, y, ICON_MOD_BEVEL); break;
case eModifierType_Smooth:
+ case eModifierType_LaplacianSmooth:
UI_icon_draw(x, y, ICON_MOD_SMOOTH); break;
case eModifierType_SimpleDeform:
UI_icon_draw(x, y, ICON_MOD_SIMPLEDEFORM); break;
@@ -1247,7 +1253,7 @@ static void outliner_set_coord_tree_element(SpaceOops *soops, TreeElement *te, i
for (ten = te->subtree.first; ten; ten = ten->next) {
outliner_set_coord_tree_element(soops, ten, startx + UI_UNIT_X, starty);
- }
+ }
}
@@ -1392,7 +1398,7 @@ static void outliner_draw_tree_element(bContext *C, uiBlock *block, Scene *scene
UI_icon_draw((float)startx + offsx, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_DIRECT);
glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
offsx += UI_UNIT_X;
- }
+ }
glDisable(GL_BLEND);
/* name */
@@ -1407,11 +1413,15 @@ static void outliner_draw_tree_element(bContext *C, uiBlock *block, Scene *scene
/* closed item, we draw the icons, not when it's a scene, or master-server list though */
if (!TSELEM_OPEN(tselem, soops)) {
if (te->subtree.first) {
- if (tselem->type == 0 && te->idcode == ID_SCE) ;
- else if (tselem->type != TSE_R_LAYER) { /* this tree element always has same amount of branches, so don't draw */
+ if (tselem->type == 0 && te->idcode == ID_SCE) {
+ /* pass */
+ }
+ else if (tselem->type != TSE_R_LAYER) {
+ /* this tree element always has same amount of branches, so don't draw */
+
int tempx = startx + offsx;
- // divider
+ /* divider */
UI_ThemeColorShade(TH_BACK, -40);
glRecti(tempx - 10, *starty + 4, tempx - 8, *starty + UI_UNIT_Y - 4);
@@ -1425,7 +1435,7 @@ static void outliner_draw_tree_element(bContext *C, uiBlock *block, Scene *scene
}
}
}
- }
+ }
/* store coord and continue, we need coordinates for elements outside view too */
te->xs = (float)startx;
te->ys = (float)*starty;
@@ -1436,7 +1446,7 @@ static void outliner_draw_tree_element(bContext *C, uiBlock *block, Scene *scene
for (ten = te->subtree.first; ten; ten = ten->next)
outliner_draw_tree_element(C, block, scene, ar, soops, ten, startx + UI_UNIT_X, starty);
- }
+ }
else {
for (ten = te->subtree.first; ten; ten = ten->next)
outliner_set_coord_tree_element(soops, te, startx, starty);
@@ -1523,7 +1533,7 @@ static void outliner_draw_tree(bContext *C, uiBlock *block, Scene *scene, ARegio
{
TreeElement *te;
int starty, startx;
- float col[4];
+ float col[3];
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // only once
@@ -1640,7 +1650,7 @@ void draw_outliner(const bContext *C)
/* get actual width of column 1 */
outliner_rna_width(soops, &soops->tree, &sizex_rna, 0);
- sizex_rna = MAX2(OL_RNA_COLX, sizex_rna + OL_RNA_COL_SPACEX);
+ sizex_rna = max_ii(OL_RNA_COLX, sizex_rna + OL_RNA_COL_SPACEX);
/* get width of data (for setting 'tot' rect, this is column 1 + column 2 + a bit extra) */
if (soops->outlinevis == SO_KEYMAP)
@@ -1693,7 +1703,7 @@ void draw_outliner(const bContext *C)
}
/* draw edit buttons if nessecery */
- outliner_buttons(C, block, ar, soops, &soops->tree);
+ outliner_buttons(C, block, ar, soops, &soops->tree);
uiEndBlock(C, block);
uiDrawBlock(C, block);
diff --git a/source/blender/editors/space_outliner/outliner_edit.c b/source/blender/editors/space_outliner/outliner_edit.c
index 0874ddcb279..23766d6a6fe 100644
--- a/source/blender/editors/space_outliner/outliner_edit.c
+++ b/source/blender/editors/space_outliner/outliner_edit.c
@@ -81,7 +81,7 @@ static int outliner_open_back(SpaceOops *soops, TreeElement *te)
for (te = te->parent; te; te = te->parent) {
tselem = TREESTORE(te);
- if (tselem->flag & TSE_CLOSED) {
+ if (tselem->flag & TSE_CLOSED) {
tselem->flag &= ~TSE_CLOSED;
retval = 1;
}
@@ -197,10 +197,10 @@ static void do_item_rename(ARegion *ar, TreeElement *te, TreeStoreElem *tselem,
}
else if (tselem->id->lib) {
// XXX error_libdata();
- }
+ }
else if (te->idcode == ID_LI && te->parent) {
BKE_report(reports, RPT_WARNING, "Cannot edit the path of an indirectly linked library");
- }
+ }
else {
tselem->flag |= TSE_TEXTBUT;
ED_region_tag_redraw(ar);
@@ -368,12 +368,14 @@ void group_toggle_visibility_cb(bContext *UNUSED(C), Scene *scene, TreeElement *
static int outliner_toggle_visibility_exec(bContext *C, wmOperator *UNUSED(op))
{
+ Main *bmain = CTX_data_main(C);
SpaceOops *soops = CTX_wm_space_outliner(C);
Scene *scene = CTX_data_scene(C);
ARegion *ar = CTX_wm_region(C);
outliner_do_object_operation(C, scene, soops, &soops->tree, object_toggle_visibility_cb);
+ DAG_id_type_tag(bmain, ID_OB);
WM_event_add_notifier(C, NC_SCENE | ND_OB_VISIBLE, scene);
ED_region_tag_redraw(ar);
@@ -464,11 +466,13 @@ void group_toggle_renderability_cb(bContext *UNUSED(C), Scene *scene, TreeElemen
static int outliner_toggle_renderability_exec(bContext *C, wmOperator *UNUSED(op))
{
+ Main *bmain = CTX_data_main(C);
SpaceOops *soops = CTX_wm_space_outliner(C);
Scene *scene = CTX_data_scene(C);
outliner_do_object_operation(C, scene, soops, &soops->tree, object_toggle_renderability_cb);
+ DAG_id_type_tag(bmain, ID_OB);
WM_event_add_notifier(C, NC_SCENE | ND_OB_RENDER, scene);
return OPERATOR_FINISHED;
@@ -579,11 +583,11 @@ static int outliner_show_active_exec(bContext *C, wmOperator *UNUSED(op))
te = outliner_find_id(so, &so->tree, (ID *)OBACT);
if (te) {
/* make te->ys center of view */
- ytop = (int)(te->ys + BLI_RCT_SIZE_Y(&v2d->mask) / 2);
+ ytop = (int)(te->ys + BLI_rcti_size_y(&v2d->mask) / 2);
if (ytop > 0) ytop = 0;
v2d->cur.ymax = (float)ytop;
- v2d->cur.ymin = (float)(ytop - BLI_RCT_SIZE_Y(&v2d->mask));
+ v2d->cur.ymin = (float)(ytop - BLI_rcti_size_y(&v2d->mask));
/* make te->xs ==> te->xend center of view */
xdelta = (int)(te->xs - v2d->cur.xmin);
@@ -615,7 +619,7 @@ void OUTLINER_OT_show_active(wmOperatorType *ot)
static int outliner_scroll_page_exec(bContext *C, wmOperator *op)
{
ARegion *ar = CTX_wm_region(C);
- int dy = BLI_RCT_SIZE_Y(&ar->v2d.mask);
+ int dy = BLI_rcti_size_y(&ar->v2d.mask);
int up = 0;
if (RNA_boolean_get(op->ptr, "up"))
@@ -726,7 +730,7 @@ static void outliner_find_panel(Scene *UNUSED(scene), ARegion *ar, SpaceOops *so
/* determine which type of search to do */
if (again && last_find) {
- /* no popup panel - previous + user wanted to search for next after previous */
+ /* no popup panel - previous + user wanted to search for next after previous */
BLI_strncpy(name, soops->search_string, sizeof(name));
flags = soops->search_flags;
@@ -742,7 +746,7 @@ static void outliner_find_panel(Scene *UNUSED(scene), ARegion *ar, SpaceOops *so
/* pop up panel - no previous, or user didn't want search after previous */
name[0] = '\0';
// XXX if (sbutton(name, 0, sizeof(name)-1, "Find: ") && name[0]) {
-// te= outliner_find_name(soops, &soops->tree, name, flags, NULL, &prevFound);
+// te = outliner_find_name(soops, &soops->tree, name, flags, NULL, &prevFound);
// }
// else return; /* XXX RETURN! XXX */
}
@@ -760,10 +764,10 @@ static void outliner_find_panel(Scene *UNUSED(scene), ARegion *ar, SpaceOops *so
tselem->flag |= TSE_SELECTED;
/* make te->ys center of view */
- ytop = (int)(te->ys + BLI_RCT_SIZE_Y(&ar->v2d.mask) / 2);
+ ytop = (int)(te->ys + BLI_rctf_size_y(&ar->v2d.mask) / 2);
if (ytop > 0) ytop = 0;
ar->v2d.cur.ymax = (float)ytop;
- ar->v2d.cur.ymin = (float)(ytop - BLI_RCT_SIZE_Y(&ar->v2d.mask));
+ ar->v2d.cur.ymin = (float)(ytop - BLI_rctf_size_y(&ar->v2d.mask));
/* make te->xs ==> te->xend center of view */
xdelta = (int)(te->xs - ar->v2d.cur.xmin);
@@ -782,7 +786,7 @@ static void outliner_find_panel(Scene *UNUSED(scene), ARegion *ar, SpaceOops *so
}
else {
/* no tree-element found */
- BKE_report(reports, RPT_WARNING, "Not found: %s", name);
+ BKE_reportf(reports, RPT_WARNING, "Not found: %s", name);
}
}
#endif
@@ -994,7 +998,7 @@ static void tree_element_to_path(SpaceOops *soops, TreeElement *te, TreeStoreEle
char buf[128], *name;
temnext = (TreeElement *)(ld->next->data);
- /* tsenext= TREESTORE(temnext); */ /* UNUSED */
+ /* tsenext = TREESTORE(temnext); */ /* UNUSED */
nextptr = &temnext->rnaptr;
name = RNA_struct_name_get_alloc(nextptr, buf, sizeof(buf), NULL);
@@ -1340,7 +1344,7 @@ static int outliner_keyingset_additems_exec(bContext *C, wmOperator *op)
/* check for invalid states */
if (ks == NULL) {
- BKE_report(op->reports, RPT_ERROR, "Operation requires an Active Keying Set");
+ BKE_report(op->reports, RPT_ERROR, "Operation requires an active keying set");
return OPERATOR_CANCELLED;
}
if (soutliner == NULL)
@@ -1423,7 +1427,7 @@ static int parent_drop_exec(bContext *C, wmOperator *op)
RNA_string_get(op->ptr, "child", childname);
ob = (Object *)BKE_libblock_find_name(ID_OB, childname);
- ED_object_parent_set(op->reports, bmain, scene, ob, par, partype, FALSE);
+ ED_object_parent_set(op->reports, bmain, scene, ob, par, partype, FALSE, FALSE);
DAG_scene_sort(bmain, scene);
DAG_ids_flush_update(bmain, 0);
@@ -1514,7 +1518,7 @@ static int parent_drop_invoke(bContext *C, wmOperator *op, wmEvent *event)
}
if ((par->type != OB_ARMATURE) && (par->type != OB_CURVE) && (par->type != OB_LATTICE)) {
- if (ED_object_parent_set(op->reports, bmain, scene, ob, par, partype, FALSE)) {
+ if (ED_object_parent_set(op->reports, bmain, scene, ob, par, partype, FALSE, FALSE)) {
DAG_scene_sort(bmain, scene);
DAG_ids_flush_update(bmain, 0);
WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
@@ -1854,7 +1858,7 @@ static int material_drop_invoke(bContext *C, wmOperator *op, wmEvent *event)
assign_material(ob, ma, ob->totcol + 1, BKE_MAT_ASSIGN_USERPREF);
DAG_ids_flush_update(bmain, 0);
- WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
WM_event_add_notifier(C, NC_MATERIAL | ND_SHADING, ma);
return OPERATOR_FINISHED;
diff --git a/source/blender/editors/space_outliner/outliner_select.c b/source/blender/editors/space_outliner/outliner_select.c
index 823de61d044..4668dfa1386 100644
--- a/source/blender/editors/space_outliner/outliner_select.c
+++ b/source/blender/editors/space_outliner/outliner_select.c
@@ -236,7 +236,7 @@ static int tree_element_active_texture(bContext *C, Scene *scene, SpaceOops *soo
if (ob == NULL) return 0; // no active object
- /*tselem= TREESTORE(te);*/ /*UNUSED*/
+ /*tselem = TREESTORE(te);*/ /*UNUSED*/
/* find buttons area (note, this is undefined really still, needs recode in blender) */
/* XXX removed finding sbuts */
@@ -250,8 +250,8 @@ static int tree_element_active_texture(bContext *C, Scene *scene, SpaceOops *soo
if (set) {
if (sbuts) {
- // XXX sbuts->tabo= TAB_SHADING_TEX; // hack from header_buttonswin.c
- // XXX sbuts->texfrom= 1;
+ // XXX sbuts->tabo = TAB_SHADING_TEX; // hack from header_buttonswin.c
+ // XXX sbuts->texfrom = 1;
}
// XXX extern_set_butspace(F6KEY, 0); // force shading buttons texture
wrld->texact = te->index;
@@ -264,8 +264,8 @@ static int tree_element_active_texture(bContext *C, Scene *scene, SpaceOops *soo
Lamp *la = (Lamp *)tselemp->id;
if (set) {
if (sbuts) {
- // XXX sbuts->tabo= TAB_SHADING_TEX; // hack from header_buttonswin.c
- // XXX sbuts->texfrom= 2;
+ // XXX sbuts->tabo = TAB_SHADING_TEX; // hack from header_buttonswin.c
+ // XXX sbuts->texfrom = 2;
}
// XXX extern_set_butspace(F6KEY, 0); // force shading buttons texture
la->texact = te->index;
@@ -280,8 +280,8 @@ static int tree_element_active_texture(bContext *C, Scene *scene, SpaceOops *soo
Material *ma = (Material *)tselemp->id;
if (set) {
if (sbuts) {
- //sbuts->tabo= TAB_SHADING_TEX; // hack from header_buttonswin.c
- // XXX sbuts->texfrom= 0;
+ //sbuts->tabo = TAB_SHADING_TEX; // hack from header_buttonswin.c
+ // XXX sbuts->texfrom = 0;
}
// XXX extern_set_butspace(F6KEY, 0); // force shading buttons texture
ma->texact = (char)te->index;
diff --git a/source/blender/editors/space_outliner/outliner_tools.c b/source/blender/editors/space_outliner/outliner_tools.c
index bf76fdda61e..3b83279e09d 100644
--- a/source/blender/editors/space_outliner/outliner_tools.c
+++ b/source/blender/editors/space_outliner/outliner_tools.c
@@ -158,11 +158,16 @@ static void unlink_material_cb(bContext *UNUSED(C), Scene *UNUSED(scene), TreeEl
totcol = mb->totcol;
matar = mb->mat;
}
+ else {
+ BLI_assert(0);
+ }
- for (a = 0; a < totcol; a++) {
- if (a == te->index && matar[a]) {
- matar[a]->id.us--;
- matar[a] = NULL;
+ if (LIKELY(matar != NULL)) {
+ for (a = 0; a < totcol; a++) {
+ if (a == te->index && matar[a]) {
+ matar[a]->id.us--;
+ matar[a] = NULL;
+ }
}
}
}
@@ -811,7 +816,7 @@ static int outliner_id_operation_exec(bContext *C, wmOperator *op)
ED_undo_push(C, "Unlink world");
break;
default:
- BKE_report(op->reports, RPT_WARNING, "Not Yet");
+ BKE_report(op->reports, RPT_WARNING, "Not yet implemented");
break;
}
}
@@ -844,7 +849,7 @@ static int outliner_id_operation_exec(bContext *C, wmOperator *op)
break;
default:
- BKE_report(op->reports, RPT_WARNING, "Not Yet");
+ BKE_report(op->reports, RPT_WARNING, "Not yet implemented");
break;
}
}
@@ -974,15 +979,15 @@ static int outliner_action_set_exec(bContext *C, wmOperator *op)
act = BLI_findlink(&CTX_data_main(C)->action, RNA_enum_get(op->ptr, "action"));
if (act == NULL) {
- BKE_report(op->reports, RPT_ERROR, "No valid Action to add");
+ BKE_report(op->reports, RPT_ERROR, "No valid action to add");
return OPERATOR_CANCELLED;
}
else if (act->idroot == 0) {
/* hopefully in this case (i.e. library of userless actions), the user knows what they're doing... */
BKE_reportf(op->reports, RPT_WARNING,
- "Action '%s' does not specify what datablocks it can be used on. "
- "Try setting the 'ID Root Type' setting from the Datablocks Editor "
- "for this Action to avoid future problems",
+ "Action '%s' does not specify what datablocks it can be used on "
+ "(try setting the 'ID Root Type' setting from the Datablocks Editor "
+ "for this action to avoid future problems)",
act->id.name + 2);
}
@@ -1160,37 +1165,50 @@ static int outliner_data_operation_exec(bContext *C, wmOperator *op)
event = RNA_enum_get(op->ptr, "type");
set_operation_types(soops, &soops->tree, &scenelevel, &objectlevel, &idlevel, &datalevel);
- if (datalevel == TSE_POSE_CHANNEL) {
- if (event > 0) {
+ if (event <= 0)
+ return OPERATOR_CANCELLED;
+
+ switch (datalevel) {
+ case TSE_POSE_CHANNEL:
+ {
outliner_do_data_operation(soops, datalevel, event, &soops->tree, pchan_cb, NULL);
WM_event_add_notifier(C, NC_OBJECT | ND_POSE, NULL);
ED_undo_push(C, "PoseChannel operation");
}
- }
- else if (datalevel == TSE_BONE) {
- if (event > 0) {
+ break;
+
+ case TSE_BONE:
+ {
outliner_do_data_operation(soops, datalevel, event, &soops->tree, bone_cb, NULL);
WM_event_add_notifier(C, NC_OBJECT | ND_POSE, NULL);
ED_undo_push(C, "Bone operation");
}
- }
- else if (datalevel == TSE_EBONE) {
- if (event > 0) {
+ break;
+
+ case TSE_EBONE:
+ {
outliner_do_data_operation(soops, datalevel, event, &soops->tree, ebone_cb, NULL);
WM_event_add_notifier(C, NC_OBJECT | ND_POSE, NULL);
ED_undo_push(C, "EditBone operation");
}
- }
- else if (datalevel == TSE_SEQUENCE) {
- if (event > 0) {
+ break;
+
+ case TSE_SEQUENCE:
+ {
Scene *scene = CTX_data_scene(C);
outliner_do_data_operation(soops, datalevel, event, &soops->tree, sequence_cb, scene);
}
- }
- else if (datalevel == TSE_RNA_STRUCT) {
- if (event == 5) {
- outliner_do_data_operation(soops, datalevel, event, &soops->tree, data_select_linked_cb, C);
- }
+ break;
+
+ case TSE_RNA_STRUCT:
+ if (event == 5) {
+ outliner_do_data_operation(soops, datalevel, event, &soops->tree, data_select_linked_cb, C);
+ }
+ break;
+
+ default:
+ BKE_report(op->reports, RPT_WARNING, "Not yet implemented");
+ break;
}
return OPERATOR_FINISHED;
@@ -1262,12 +1280,15 @@ static int do_outliner_operation_event(bContext *C, Scene *scene, ARegion *ar, S
else {
if (datalevel == TSE_ANIM_DATA)
WM_operator_name_call(C, "OUTLINER_OT_animdata_operation", WM_OP_INVOKE_REGION_WIN, NULL);
- else if (datalevel == TSE_DRIVER_BASE)
- /* do nothing... no special ops needed yet */;
- else if (ELEM3(datalevel, TSE_R_LAYER_BASE, TSE_R_LAYER, TSE_R_PASS))
- /*WM_operator_name_call(C, "OUTLINER_OT_renderdata_operation", WM_OP_INVOKE_REGION_WIN, NULL)*/;
- else
+ else if (datalevel == TSE_DRIVER_BASE) {
+ /* do nothing... no special ops needed yet */
+ }
+ else if (ELEM3(datalevel, TSE_R_LAYER_BASE, TSE_R_LAYER, TSE_R_PASS)) {
+ /*WM_operator_name_call(C, "OUTLINER_OT_renderdata_operation", WM_OP_INVOKE_REGION_WIN, NULL)*/
+ }
+ else {
WM_operator_name_call(C, "OUTLINER_OT_data_operation", WM_OP_INVOKE_REGION_WIN, NULL);
+ }
}
}
@@ -1289,11 +1310,13 @@ static int outliner_operation(bContext *C, wmOperator *UNUSED(op), wmEvent *even
SpaceOops *soops = CTX_wm_space_outliner(C);
TreeElement *te;
float fmval[2];
-
+
UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], fmval, fmval + 1);
for (te = soops->tree.first; te; te = te->next) {
- if (do_outliner_operation_event(C, scene, ar, soops, te, event, fmval)) break;
+ if (do_outliner_operation_event(C, scene, ar, soops, te, event, fmval)) {
+ break;
+ }
}
return OPERATOR_FINISHED;
diff --git a/source/blender/editors/space_outliner/outliner_tree.c b/source/blender/editors/space_outliner/outliner_tree.c
index 3e1ce1fea6e..af890a81ad6 100644
--- a/source/blender/editors/space_outliner/outliner_tree.c
+++ b/source/blender/editors/space_outliner/outliner_tree.c
@@ -553,16 +553,16 @@ static void outliner_add_object_contents(SpaceOops *soops, TreeElement *te, Tree
if (md->type == eModifierType_Lattice) {
outliner_add_element(soops, &te->subtree, ((LatticeModifierData *) md)->object, te, TSE_LINKED_OB, 0);
- }
+ }
else if (md->type == eModifierType_Curve) {
outliner_add_element(soops, &te->subtree, ((CurveModifierData *) md)->object, te, TSE_LINKED_OB, 0);
- }
+ }
else if (md->type == eModifierType_Armature) {
outliner_add_element(soops, &te->subtree, ((ArmatureModifierData *) md)->object, te, TSE_LINKED_OB, 0);
- }
+ }
else if (md->type == eModifierType_Hook) {
outliner_add_element(soops, &te->subtree, ((HookModifierData *) md)->object, te, TSE_LINKED_OB, 0);
- }
+ }
else if (md->type == eModifierType_ParticleSystem) {
TreeElement *ten;
ParticleSystem *psys = ((ParticleSystemModifierData *) md)->psys;
@@ -590,7 +590,7 @@ static void outliner_add_object_contents(SpaceOops *soops, TreeElement *te, Tree
/* duplicated group */
if (ob->dup_group)
- outliner_add_element(soops, &te->subtree, ob->dup_group, te, 0, 0);
+ outliner_add_element(soops, &te->subtree, ob->dup_group, te, 0, 0);
}
// can be inlined if necessary
@@ -731,7 +731,7 @@ static void outliner_add_id_contents(SpaceOops *soops, TreeElement *te, TreeStor
case ID_AC:
{
// XXX do we want to be exposing the F-Curves here?
- //bAction *act= (bAction *)id;
+ //bAction *act = (bAction *)id;
}
break;
case ID_AR:
@@ -769,7 +769,9 @@ static void outliner_add_id_contents(SpaceOops *soops, TreeElement *te, TreeStor
else {
/* do not extend Armature when we have posemode */
tselem = TREESTORE(te->parent);
- if (GS(tselem->id->name) == ID_OB && ((Object *)tselem->id)->mode & OB_MODE_POSE) ;
+ if (GS(tselem->id->name) == ID_OB && ((Object *)tselem->id)->mode & OB_MODE_POSE) {
+ /* pass */
+ }
else {
Bone *curBone;
for (curBone = arm->bonebase.first; curBone; curBone = curBone->next) {
@@ -811,9 +813,15 @@ static TreeElement *outliner_add_element(SpaceOops *soops, ListBase *lb, void *i
te->parent = parent;
te->index = index; // for data arays
- if (ELEM3(type, TSE_SEQUENCE, TSE_SEQ_STRIP, TSE_SEQUENCE_DUP)) ;
- else if (ELEM3(type, TSE_RNA_STRUCT, TSE_RNA_PROPERTY, TSE_RNA_ARRAY_ELEM)) ;
- else if (type == TSE_ANIM_DATA) ;
+ if (ELEM3(type, TSE_SEQUENCE, TSE_SEQ_STRIP, TSE_SEQUENCE_DUP)) {
+ /* pass */
+ }
+ else if (ELEM3(type, TSE_RNA_STRUCT, TSE_RNA_PROPERTY, TSE_RNA_ARRAY_ELEM)) {
+ /* pass */
+ }
+ else if (type == TSE_ANIM_DATA) {
+ /* pass */
+ }
else {
te->name = id->name + 2; // default, can be overridden by Library or non-ID data
te->idcode = GS(id->name);
@@ -1055,8 +1063,12 @@ static TreeElement *outliner_add_element(SpaceOops *soops, ListBase *lb, void *i
if (key[0]) {
wmOperatorType *ot = NULL;
- if (kmi->propvalue) ;
- else ot = WM_operatortype_find(kmi->idname, 0);
+ if (kmi->propvalue) {
+ /* pass */
+ }
+ else {
+ ot = WM_operatortype_find(kmi->idname, 0);
+ }
if (ot || kmi->propvalue) {
TreeElement *ten = outliner_add_element(soops, &te->subtree, kmi, te, TSE_KEYMAP_ITEM, a);
@@ -1136,7 +1148,7 @@ static void outliner_add_seq_dup(SpaceOops *soops, Sequence *seq, TreeElement *t
}
if (!strcmp(p->strip->stripdata->name, seq->strip->stripdata->name))
- /* ch= */ /* UNUSED */ outliner_add_element(soops, &te->subtree, (void *)p, te, TSE_SEQUENCE, index);
+ /* ch = */ /* UNUSED */ outliner_add_element(soops, &te->subtree, (void *)p, te, TSE_SEQUENCE, index);
p = p->next;
}
}
@@ -1519,7 +1531,7 @@ void outliner_build_tree(Main *mainvar, Scene *scene, SpaceOops *soops)
while (seq) {
op = need_add_seq_dup(seq);
if (op == 1) {
- /* ten= */ outliner_add_element(soops, &soops->tree, (void *)seq, NULL, TSE_SEQUENCE, 0);
+ /* ten = */ outliner_add_element(soops, &soops->tree, (void *)seq, NULL, TSE_SEQUENCE, 0);
}
else if (op == 0) {
ten = outliner_add_element(soops, &soops->tree, (void *)seq, NULL, TSE_SEQUENCE_DUP, 0);
@@ -1557,7 +1569,7 @@ void outliner_build_tree(Main *mainvar, Scene *scene, SpaceOops *soops)
wmKeyMap *km;
for (km = wm->defaultconf->keymaps.first; km; km = km->next) {
- /* ten= */ outliner_add_element(soops, &soops->tree, (void *)km, NULL, TSE_KEYMAP, 0);
+ /* ten = */ outliner_add_element(soops, &soops->tree, (void *)km, NULL, TSE_KEYMAP, 0);
}
}
else {
diff --git a/source/blender/editors/space_sequencer/CMakeLists.txt b/source/blender/editors/space_sequencer/CMakeLists.txt
index c1f7fc942e4..f108d9f1aaa 100644
--- a/source/blender/editors/space_sequencer/CMakeLists.txt
+++ b/source/blender/editors/space_sequencer/CMakeLists.txt
@@ -57,4 +57,8 @@ if(WITH_AUDASPACE)
add_definitions(-DWITH_AUDASPACE)
endif()
+if(WITH_INTERNATIONAL)
+ add_definitions(-DWITH_INTERNATIONAL)
+endif()
+
blender_add_lib(bf_editor_space_sequencer "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/editors/space_sequencer/SConscript b/source/blender/editors/space_sequencer/SConscript
index ec06eacae9c..0b429ae750b 100644
--- a/source/blender/editors/space_sequencer/SConscript
+++ b/source/blender/editors/space_sequencer/SConscript
@@ -8,7 +8,12 @@ incs += ' ../../windowmanager #/intern/guardedalloc #/extern/glew/include'
incs += ' ../../makesrna ../../blenloader ../../blenfont'
incs += ' #/intern/audaspace/intern'
+defs = []
+
if env['OURPLATFORM'] in ('win32-vc', 'win32-mingw', 'linuxcross', 'win64-vc', 'win64-mingw'):
incs += ' ' + env['BF_PTHREADS_INC']
-env.BlenderLib ( 'bf_editors_space_sequencer', sources, Split(incs), [], libtype=['core'], priority=[100] )
+if env['WITH_BF_INTERNATIONAL']:
+ defs.append('WITH_INTERNATIONAL')
+
+env.BlenderLib ( 'bf_editors_space_sequencer', sources, Split(incs), defs, libtype=['core'], priority=[100] )
diff --git a/source/blender/editors/space_sequencer/sequencer_add.c b/source/blender/editors/space_sequencer/sequencer_add.c
index 7b7170d99e0..fd46f69da83 100644
--- a/source/blender/editors/space_sequencer/sequencer_add.c
+++ b/source/blender/editors/space_sequencer/sequencer_add.c
@@ -242,7 +242,7 @@ static int sequencer_add_scene_strip_exec(bContext *C, wmOperator *op)
strip->us = 1;
BLI_strncpy(seq->name + 2, sce_seq->id.name + 2, sizeof(seq->name) - 2);
- BKE_seqence_base_unique_name_recursive(&ed->seqbase, seq);
+ BKE_sequence_base_unique_name_recursive(&ed->seqbase, seq);
seq->scene_sound = sound_scene_add_scene_sound(scene, seq, start_frame, start_frame + seq->len, 0);
@@ -325,7 +325,7 @@ static int sequencer_add_movieclip_strip_exec(bContext *C, wmOperator *op)
clip = BLI_findlink(&CTX_data_main(C)->movieclip, RNA_enum_get(op->ptr, "clip"));
if (clip == NULL) {
- BKE_report(op->reports, RPT_ERROR, "MovieClip not found");
+ BKE_report(op->reports, RPT_ERROR, "Movie clip not found");
return OPERATOR_CANCELLED;
}
@@ -343,7 +343,7 @@ static int sequencer_add_movieclip_strip_exec(bContext *C, wmOperator *op)
strip->us = 1;
BLI_strncpy(seq->name + 2, clip->id.name + 2, sizeof(seq->name) - 2);
- BKE_seqence_base_unique_name_recursive(&ed->seqbase, seq);
+ BKE_sequence_base_unique_name_recursive(&ed->seqbase, seq);
BKE_sequence_calc_disp(scene, seq);
BKE_sequencer_sort(scene);
@@ -439,7 +439,7 @@ static int sequencer_add_mask_strip_exec(bContext *C, wmOperator *op)
strip->us = 1;
BLI_strncpy(seq->name + 2, mask->id.name + 2, sizeof(seq->name) - 2);
- BKE_seqence_base_unique_name_recursive(&ed->seqbase, seq);
+ BKE_sequence_base_unique_name_recursive(&ed->seqbase, seq);
BKE_sequence_calc_disp(scene, seq);
BKE_sequencer_sort(scene);
@@ -553,7 +553,7 @@ static int sequencer_add_generic_strip_exec(bContext *C, wmOperator *op, SeqLoad
}
if (seq_load.tot_success == 0) {
- BKE_reportf(op->reports, RPT_ERROR, "File \"%s\" could not be loaded", seq_load.path);
+ BKE_reportf(op->reports, RPT_ERROR, "File '%s' could not be loaded", seq_load.path);
return OPERATOR_CANCELLED;
}
@@ -820,7 +820,7 @@ static int sequencer_add_effect_strip_exec(bContext *C, wmOperator *op)
seq->type = type;
BLI_strncpy(seq->name + 2, BKE_sequence_give_name(seq), sizeof(seq->name) - 2);
- BKE_seqence_base_unique_name_recursive(&ed->seqbase, seq);
+ BKE_sequence_base_unique_name_recursive(&ed->seqbase, seq);
sh = BKE_sequence_get_effect(seq);
diff --git a/source/blender/editors/space_sequencer/sequencer_draw.c b/source/blender/editors/space_sequencer/sequencer_draw.c
index 7363bf2fbd8..29babd355ad 100644
--- a/source/blender/editors/space_sequencer/sequencer_draw.c
+++ b/source/blender/editors/space_sequencer/sequencer_draw.c
@@ -355,7 +355,7 @@ static void draw_seq_handle(View2D *v2d, Sequence *seq, const float handsize_cla
y2 = seq->machine + SEQ_STRIP_OFSTOP;
/* set up co-ordinates/dimensions for either left or right handle */
- if (direction == SEQ_LEFTHANDLE) {
+ if (direction == SEQ_LEFTHANDLE) {
rx1 = x1;
rx2 = x1 + handsize_clamped * 0.75f;
@@ -415,7 +415,7 @@ static void draw_seq_handle(View2D *v2d, Sequence *seq, const float handsize_cla
y1 = y2 + 0.05f;
}
UI_view2d_text_cache_add(v2d, x1, y1, numstr, col);
- }
+ }
}
static void draw_seq_extensions(Scene *scene, ARegion *ar, Sequence *seq)
@@ -432,7 +432,7 @@ static void draw_seq_extensions(Scene *scene, ARegion *ar, Sequence *seq)
y1 = seq->machine + SEQ_STRIP_OFSBOTTOM;
y2 = seq->machine + SEQ_STRIP_OFSTOP;
- pixely = BLI_RCT_SIZE_Y(&v2d->cur) / BLI_RCT_SIZE_Y(&v2d->mask);
+ pixely = BLI_rctf_size_y(&v2d->cur) / BLI_rcti_size_y(&v2d->mask);
if (pixely <= 0) return; /* can happen when the view is split/resized */
@@ -725,7 +725,7 @@ static void draw_seq_strip(Scene *scene, ARegion *ar, Sequence *seq, int outline
/* draw sound wave */
if (seq->type == SEQ_TYPE_SOUND_RAM) {
- drawseqwave(scene, seq, x1, y1, x2, y2, BLI_RCT_SIZE_X(&ar->v2d.cur) / ar->winx);
+ drawseqwave(scene, seq, x1, y1, x2, y2, BLI_rctf_size_x(&ar->v2d.cur) / ar->winx);
}
/* draw lock */
@@ -747,7 +747,7 @@ static void draw_seq_strip(Scene *scene, ARegion *ar, Sequence *seq, int outline
glDisable(GL_BLEND);
}
- if (!BKE_seqence_is_valid_check(seq)) {
+ if (!BKE_sequence_is_valid_check(seq)) {
glEnable(GL_POLYGON_STIPPLE);
/* panic! */
@@ -810,7 +810,7 @@ static void UNUSED_FUNCTION(set_special_seq_update) (int val)
/* if mouse over a sequence && LEFTMOUSE */
if (val) {
-// XXX special_seq_update= find_nearest_seq(&x);
+// XXX special_seq_update = find_nearest_seq(&x);
}
else special_seq_update = NULL;
}
@@ -885,7 +885,10 @@ static ImBuf *sequencer_make_scope(Scene *scene, ImBuf *ibuf, ImBuf *(*make_scop
ImBuf *display_ibuf = IMB_dupImBuf(ibuf);
ImBuf *scope;
- IMB_colormanagement_imbuf_make_display_space(display_ibuf, &scene->view_settings, &scene->display_settings);
+ if (display_ibuf->rect_float) {
+ IMB_colormanagement_imbuf_make_display_space(display_ibuf, &scene->view_settings,
+ &scene->display_settings);
+ }
scope = make_scope_cb(display_ibuf);
@@ -967,7 +970,10 @@ void draw_image_seq(const bContext *C, Scene *scene, ARegion *ar, SpaceSeq *sseq
if (!scopes->zebra_ibuf) {
ImBuf *display_ibuf = IMB_dupImBuf(ibuf);
- IMB_colormanagement_imbuf_make_display_space(display_ibuf, &scene->view_settings, &scene->display_settings);
+ if (display_ibuf->rect_float) {
+ IMB_colormanagement_imbuf_make_display_space(display_ibuf, &scene->view_settings,
+ &scene->display_settings);
+ }
scopes->zebra_ibuf = make_zebra_view_from_ibuf(display_ibuf, sseq->zebra);
IMB_freeImBuf(display_ibuf);
}
@@ -1032,10 +1038,10 @@ void draw_image_seq(const bContext *C, Scene *scene, ARegion *ar, SpaceSeq *sseq
if (draw_overlay) {
if (sseq->overlay_type == SEQ_DRAW_OVERLAY_RECT) {
rctf tot_clip;
- tot_clip.xmin = v2d->tot.xmin + (ABS(BLI_RCT_SIZE_X(&v2d->tot)) * scene->ed->over_border.xmin);
- tot_clip.ymin = v2d->tot.ymin + (ABS(BLI_RCT_SIZE_Y(&v2d->tot)) * scene->ed->over_border.ymin);
- tot_clip.xmax = v2d->tot.xmin + (ABS(BLI_RCT_SIZE_X(&v2d->tot)) * scene->ed->over_border.xmax);
- tot_clip.ymax = v2d->tot.ymin + (ABS(BLI_RCT_SIZE_Y(&v2d->tot)) * scene->ed->over_border.ymax);
+ tot_clip.xmin = v2d->tot.xmin + (fabsf(BLI_rctf_size_x(&v2d->tot)) * scene->ed->over_border.xmin);
+ tot_clip.ymin = v2d->tot.ymin + (fabsf(BLI_rctf_size_y(&v2d->tot)) * scene->ed->over_border.ymin);
+ tot_clip.xmax = v2d->tot.xmin + (fabsf(BLI_rctf_size_x(&v2d->tot)) * scene->ed->over_border.xmax);
+ tot_clip.ymax = v2d->tot.ymin + (fabsf(BLI_rctf_size_y(&v2d->tot)) * scene->ed->over_border.ymax);
glTexCoord2f(scene->ed->over_border.xmin, scene->ed->over_border.ymin); glVertex2f(tot_clip.xmin, tot_clip.ymin);
glTexCoord2f(scene->ed->over_border.xmin, scene->ed->over_border.ymax); glVertex2f(tot_clip.xmin, tot_clip.ymax);
@@ -1183,7 +1189,7 @@ static void draw_seq_backdrop(View2D *v2d)
glRectf(v2d->cur.xmin, -1.0, v2d->cur.xmax, 1.0);
/* Alternating horizontal stripes */
- i = maxi(1, ((int)v2d->cur.ymin) - 1);
+ i = max_ii(1, ((int)v2d->cur.ymin) - 1);
glBegin(GL_QUADS);
while (i < v2d->cur.ymax) {
@@ -1202,7 +1208,7 @@ static void draw_seq_backdrop(View2D *v2d)
glEnd();
/* Darker lines separating the horizontal bands */
- i = maxi(1, ((int)v2d->cur.ymin) - 1);
+ i = max_ii(1, ((int)v2d->cur.ymin) - 1);
UI_ThemeColor(TH_GRID);
glBegin(GL_LINES);
@@ -1222,7 +1228,7 @@ static void draw_seq_strips(const bContext *C, Editing *ed, ARegion *ar)
View2D *v2d = &ar->v2d;
Sequence *last_seq = BKE_sequencer_active_get(scene);
int sel = 0, j;
- float pixelx = BLI_RCT_SIZE_X(&v2d->cur) / BLI_RCT_SIZE_X(&v2d->mask);
+ float pixelx = BLI_rctf_size_x(&v2d->cur) / BLI_rcti_size_x(&v2d->mask);
/* loop through twice, first unselected, then selected */
for (j = 0; j < 2; j++) {
@@ -1234,8 +1240,8 @@ static void draw_seq_strips(const bContext *C, Editing *ed, ARegion *ar)
/* boundbox and selection tests for NOT drawing the strip... */
if ((seq->flag & SELECT) != sel) continue;
else if (seq == last_seq) continue;
- else if (MIN2(seq->startdisp, seq->start) > v2d->cur.xmax) continue;
- else if (MAX2(seq->enddisp, seq->start + seq->len) < v2d->cur.xmin) continue;
+ else if (min_ii(seq->startdisp, seq->start) > v2d->cur.xmax) continue;
+ else if (max_ii(seq->enddisp, seq->start + seq->len) < v2d->cur.xmin) continue;
else if (seq->machine + 1.0f < v2d->cur.ymin) continue;
else if (seq->machine > v2d->cur.ymax) continue;
diff --git a/source/blender/editors/space_sequencer/sequencer_edit.c b/source/blender/editors/space_sequencer/sequencer_edit.c
index f47eb339878..7270516aa51 100644
--- a/source/blender/editors/space_sequencer/sequencer_edit.c
+++ b/source/blender/editors/space_sequencer/sequencer_edit.c
@@ -46,6 +46,8 @@
#include "BLI_utildefines.h"
#include "BLI_threads.h"
+#include "BLF_translation.h"
+
#include "DNA_scene_types.h"
#include "DNA_userdef_types.h"
@@ -372,7 +374,7 @@ Sequence *find_nearest_seq(Scene *scene, View2D *v2d, int *hand, const int mval[
if (ed == NULL) return NULL;
- pixelx = BLI_RCT_SIZE_X(&v2d->cur) / BLI_RCT_SIZE_X(&v2d->mask);
+ pixelx = BLI_rctf_size_x(&v2d->cur) / BLI_rcti_size_x(&v2d->mask);
UI_view2d_region_to_view(v2d, mval[0], mval[1], &x, &y);
@@ -507,7 +509,7 @@ int seq_effect_find_selected(Scene *scene, Sequence *activeseq, int type, Sequen
for (seq = ed->seqbasep->first; seq; seq = seq->next) {
if (seq->flag & SELECT) {
if (seq->type == SEQ_TYPE_SOUND_RAM && BKE_sequence_effect_get_num_inputs(type) != 0) {
- *error_str = "Can't apply effects to audio sequence strips";
+ *error_str = N_("Cannot apply effects to audio sequence strips");
return 0;
}
if ((seq != activeseq) && (seq != seq2)) {
@@ -515,7 +517,7 @@ int seq_effect_find_selected(Scene *scene, Sequence *activeseq, int type, Sequen
else if (seq1 == NULL) seq1 = seq;
else if (seq3 == NULL) seq3 = seq;
else {
- *error_str = "Can't apply effect to more than 3 sequence strips";
+ *error_str = N_("Cannot apply effect to more than 3 sequence strips");
return 0;
}
}
@@ -537,21 +539,21 @@ int seq_effect_find_selected(Scene *scene, Sequence *activeseq, int type, Sequen
return 1; /* succsess */
case 1:
if (seq2 == NULL) {
- *error_str = "Need at least one selected sequence strip";
+ *error_str = N_("At least one selected sequence strip is needed");
return 0;
}
if (seq1 == NULL) seq1 = seq2;
if (seq3 == NULL) seq3 = seq2;
case 2:
if (seq1 == NULL || seq2 == NULL) {
- *error_str = "Need 2 selected sequence strips";
+ *error_str = N_("2 selected sequence strips are needed");
return 0;
}
if (seq3 == NULL) seq3 = seq2;
}
if (seq1 == NULL && seq2 == NULL && seq3 == NULL) {
- *error_str = "TODO: in what cases does this happen?";
+ *error_str = N_("TODO: in what cases does this happen?");
return 0;
}
@@ -579,7 +581,9 @@ static Sequence *del_seq_find_replace_recurs(Scene *scene, Sequence *seq)
seq2 = del_seq_find_replace_recurs(scene, seq->seq2);
seq3 = del_seq_find_replace_recurs(scene, seq->seq3);
- if (seq1 == seq->seq1 && seq2 == seq->seq2 && seq3 == seq->seq3) ;
+ if (seq1 == seq->seq1 && seq2 == seq->seq2 && seq3 == seq->seq3) {
+ /* pass */
+ }
else if (seq1 || seq2 || seq3) {
seq->seq1 = (seq1) ? seq1 : (seq2) ? seq2 : seq3;
seq->seq2 = (seq2) ? seq2 : (seq1) ? seq1 : seq3;
@@ -678,7 +682,7 @@ static Sequence *cut_seq_hard(Scene *scene, Sequence *seq, int cutframe)
seqn = BKE_sequence_dupli_recursive(scene, NULL, seq, SEQ_DUPE_UNIQUE_NAME | SEQ_DUPE_ANIM);
}
- if (seqn) {
+ if (seqn) {
seqn->flag |= SELECT;
/* Second Strip! */
@@ -699,7 +703,7 @@ static Sequence *cut_seq_hard(Scene *scene, Sequence *seq, int cutframe)
seqn->anim_startofs += cutframe - ts.start;
seqn->anim_endofs = ts.anim_endofs;
seqn->endstill = ts.endstill;
- }
+ }
/* strips with extended stillframes after */
else if (((seqn->start + seqn->len) < cutframe) && (seqn->endstill)) {
@@ -771,7 +775,7 @@ static Sequence *cut_seq_soft(Scene *scene, Sequence *seq, int cutframe)
seqn = BKE_sequence_dupli_recursive(scene, NULL, seq, SEQ_DUPE_UNIQUE_NAME | SEQ_DUPE_ANIM);
}
- if (seqn) {
+ if (seqn) {
seqn->flag |= SELECT;
/* Second Strip! */
@@ -789,7 +793,7 @@ static Sequence *cut_seq_soft(Scene *scene, Sequence *seq, int cutframe)
seqn->startofs = cutframe - ts.start;
seqn->endofs = ts.endofs;
seqn->endstill = ts.endstill;
- }
+ }
/* strips with extended stillframes after */
else if (((seqn->start + seqn->len) < cutframe) && (seqn->endstill)) {
@@ -1054,7 +1058,7 @@ static int sequencer_snap_exec(bContext *C, wmOperator *op)
{
if ((seq->flag & (SEQ_LEFTSEL + SEQ_RIGHTSEL)) == 0) {
/* simple but no anim update */
- /* seq->start= snap_frame-seq->startofs+seq->startstill; */
+ /* seq->start = snap_frame-seq->startofs+seq->startstill; */
BKE_sequence_translate(scene, seq, (snap_frame - seq->startofs + seq->startstill) - seq->start);
}
@@ -1143,13 +1147,13 @@ static int sequencer_mute_exec(bContext *C, wmOperator *op)
if (selected) { /* mute unselected */
if (seq->flag & SELECT) {
seq->flag |= SEQ_MUTE;
- BKE_sequence_invalidate_deendent(scene, seq);
+ BKE_sequence_invalidate_dependent(scene, seq);
}
}
else {
if ((seq->flag & SELECT) == 0) {
seq->flag |= SEQ_MUTE;
- BKE_sequence_invalidate_deendent(scene, seq);
+ BKE_sequence_invalidate_dependent(scene, seq);
}
}
}
@@ -1194,13 +1198,13 @@ static int sequencer_unmute_exec(bContext *C, wmOperator *op)
if (selected) { /* unmute unselected */
if (seq->flag & SELECT) {
seq->flag &= ~SEQ_MUTE;
- BKE_sequence_invalidate_deendent(scene, seq);
+ BKE_sequence_invalidate_dependent(scene, seq);
}
}
else {
if ((seq->flag & SELECT) == 0) {
seq->flag &= ~SEQ_MUTE;
- BKE_sequence_invalidate_deendent(scene, seq);
+ BKE_sequence_invalidate_dependent(scene, seq);
}
}
}
@@ -1382,7 +1386,7 @@ static int sequencer_reassign_inputs_exec(bContext *C, wmOperator *op)
seq_is_predecessor(seq2, last_seq) ||
seq_is_predecessor(seq3, last_seq))
{
- BKE_report(op->reports, RPT_ERROR, "Can't reassign inputs: no cycles allowed");
+ BKE_report(op->reports, RPT_ERROR, "Cannot reassign inputs: no cycles allowed");
return OPERATOR_CANCELLED;
}
@@ -1572,8 +1576,8 @@ static int apply_unique_name_cb(Sequence *seq, void *arg_pt)
Scene *scene = (Scene *)arg_pt;
char name[sizeof(seq->name) - 2];
- strcpy(name, seq->name + 2);
- BKE_seqence_base_unique_name_recursive(&scene->ed->seqbase, seq);
+ BLI_strncpy_utf8(name, seq->name + 2, sizeof(name));
+ BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seq);
BKE_sequencer_dupe_animdata(scene, name, seq->name + 2);
return 1;
@@ -1851,7 +1855,7 @@ void SEQUENCER_OT_images_separate(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- RNA_def_int(ot->srna, "length", 1, 1, 1000, "Length", "Length of each frame", 1, INT_MAX);
+ RNA_def_int(ot->srna, "length", 1, 1, INT_MAX, "Length", "Length of each frame", 1, 1000);
}
@@ -1950,7 +1954,7 @@ static int sequencer_meta_make_exec(bContext *C, wmOperator *op)
while (seq) {
next = seq->next;
if (seq != seqm && (seq->flag & SELECT)) {
- channel_max = MAX2(seq->machine, channel_max);
+ channel_max = max_ii(seq->machine, channel_max);
BLI_remlink(ed->seqbasep, seq);
BLI_addtail(&seqm->seqbase, seq);
}
@@ -1968,7 +1972,7 @@ static int sequencer_meta_make_exec(bContext *C, wmOperator *op)
BKE_sequencer_update_muting(ed);
- BKE_seqence_base_unique_name_recursive(&scene->ed->seqbase, seqm);
+ BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seqm);
WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER, scene);
@@ -2127,7 +2131,7 @@ static int sequencer_view_all_preview_exec(bContext *C, wmOperator *UNUSED(op))
zoomY = ((float)height) / ((float)imgheight);
sseq->zoom = (zoomX < zoomY) ? zoomX : zoomY;
- sseq->zoom = 1.0f / power_of_2(1 / minf(zoomX, zoomY));
+ sseq->zoom = 1.0f / power_of_2(1 / min_ff(zoomX, zoomY));
}
else {
sseq->zoom = 1.0f;
@@ -2164,8 +2168,8 @@ static int sequencer_view_zoom_ratio_exec(bContext *C, wmOperator *op)
float winx = (int)(rd->size * rd->xsch) / 100;
float winy = (int)(rd->size * rd->ysch) / 100;
- float facx = BLI_RCT_SIZE_X(&v2d->mask) / winx;
- float facy = BLI_RCT_SIZE_Y(&v2d->mask) / winy;
+ float facx = BLI_rcti_size_x(&v2d->mask) / winx;
+ float facy = BLI_rcti_size_y(&v2d->mask) / winy;
BLI_rctf_resize(&v2d->cur, (int)(winx * facx * ratio) + 1, (int)(winy * facy * ratio) + 1);
@@ -2186,7 +2190,7 @@ void SEQUENCER_OT_view_zoom_ratio(wmOperatorType *ot)
ot->poll = ED_operator_sequencer_active;
/* properties */
- RNA_def_float(ot->srna, "ratio", 1.0f, 0.0f, FLT_MAX,
+ RNA_def_float(ot->srna, "ratio", 1.0f, -FLT_MAX, FLT_MAX,
"Ratio", "Zoom ratio, 1.0 is 1:1, higher is zoomed in, lower is zoomed out", -FLT_MAX, FLT_MAX);
}
@@ -2253,11 +2257,11 @@ static int sequencer_view_selected_exec(bContext *C, wmOperator *UNUSED(op))
for (seq = ed->seqbasep->first; seq; seq = seq->next) {
if (seq->flag & SELECT) {
- xmin = MIN2(xmin, seq->startdisp);
- xmax = MAX2(xmax, seq->enddisp);
+ xmin = min_ii(xmin, seq->startdisp);
+ xmax = max_ii(xmax, seq->enddisp);
- ymin = MIN2(ymin, seq->machine);
- ymax = MAX2(ymax, seq->machine);
+ ymin = min_ii(ymin, seq->machine);
+ ymax = max_ii(ymax, seq->machine);
}
}
@@ -2268,7 +2272,7 @@ static int sequencer_view_selected_exec(bContext *C, wmOperator *UNUSED(op))
ymax += ymargin;
ymin -= ymargin;
- orig_height = BLI_RCT_SIZE_Y(&cur_new);
+ orig_height = BLI_rctf_size_y(&cur_new);
cur_new.xmin = xmin;
cur_new.xmax = xmax;
@@ -2277,8 +2281,8 @@ static int sequencer_view_selected_exec(bContext *C, wmOperator *UNUSED(op))
cur_new.ymax = ymax;
/* only zoom out vertically */
- if (orig_height > BLI_RCT_SIZE_Y(&cur_new)) {
- ymid = BLI_RCT_CENTER_Y(&cur_new);
+ if (orig_height > BLI_rctf_size_y(&cur_new)) {
+ ymid = BLI_rctf_cent_y(&cur_new);
cur_new.ymin = ymid - (orig_height / 2);
cur_new.ymax = ymid + (orig_height / 2);
@@ -2618,7 +2622,6 @@ static int sequencer_copy_exec(bContext *C, wmOperator *op)
{
Scene *scene = CTX_data_scene(C);
Editing *ed = BKE_sequencer_editing_get(scene, FALSE);
- Sequence *seq;
ListBase nseqbase = {NULL, NULL};
@@ -2654,8 +2657,11 @@ static int sequencer_copy_exec(bContext *C, wmOperator *op)
seqbase_clipboard_frame = scene->r.cfra;
/* Need to remove anything that references the current scene */
- for (seq = seqbase_clipboard.first; seq; seq = seq->next) {
- seq_copy_del_sound(scene, seq);
+ {
+ Sequence *seq;
+ for (seq = seqbase_clipboard.first; seq; seq = seq->next) {
+ seq_copy_del_sound(scene, seq);
+ }
}
return OPERATOR_FINISHED;
@@ -2738,7 +2744,7 @@ static int sequencer_swap_data_exec(bContext *C, wmOperator *op)
const char *error_msg;
if (BKE_sequencer_active_get_pair(scene, &seq_act, &seq_other) == 0) {
- BKE_report(op->reports, RPT_ERROR, "Must select 2 strips");
+ BKE_report(op->reports, RPT_ERROR, "Please select two strips");
return OPERATOR_CANCELLED;
}
@@ -2800,11 +2806,11 @@ static int view_ghost_border_exec(bContext *C, wmOperator *op)
if (ed == NULL)
return OPERATOR_CANCELLED;
- rect.xmin /= (float)(ABS(BLI_RCT_SIZE_X(&v2d->tot)));
- rect.ymin /= (float)(ABS(BLI_RCT_SIZE_Y(&v2d->tot)));
+ rect.xmin /= fabsf(BLI_rctf_size_x(&v2d->tot));
+ rect.ymin /= fabsf(BLI_rctf_size_y(&v2d->tot));
- rect.xmax /= (float)(ABS(BLI_RCT_SIZE_X(&v2d->tot)));
- rect.ymax /= (float)(ABS(BLI_RCT_SIZE_Y(&v2d->tot)));
+ rect.xmax /= fabsf(BLI_rctf_size_x(&v2d->tot));
+ rect.ymax /= fabsf(BLI_rctf_size_y(&v2d->tot));
rect.xmin += 0.5f;
rect.xmax += 0.5f;
@@ -2901,7 +2907,7 @@ static int sequencer_change_effect_input_exec(bContext *C, wmOperator *op)
}
if (*seq_1 == NULL || *seq_2 == NULL) {
- BKE_report(op->reports, RPT_ERROR, "One of the effect inputs is unset, can't swap");
+ BKE_report(op->reports, RPT_ERROR, "One of the effect inputs is unset, cannot swap");
return OPERATOR_CANCELLED;
}
else {
@@ -3038,7 +3044,7 @@ static int sequencer_change_path_exec(bContext *C, wmOperator *op)
seq->anim_startofs = seq->anim_endofs = 0;
/* correct start/end frames so we don't move
- * important not to set seq->len= len; allow the function to handle it */
+ * important not to set seq->len = len; allow the function to handle it */
BKE_sequence_reload_new_file(scene, seq, TRUE);
BKE_sequence_calc(scene, seq);
diff --git a/source/blender/editors/space_sequencer/sequencer_ops.c b/source/blender/editors/space_sequencer/sequencer_ops.c
index dc5cf98f515..70b288a59e6 100644
--- a/source/blender/editors/space_sequencer/sequencer_ops.c
+++ b/source/blender/editors/space_sequencer/sequencer_ops.c
@@ -78,6 +78,9 @@ void sequencer_operatortypes(void)
WM_operatortype_append(SEQUENCER_OT_swap_data);
WM_operatortype_append(SEQUENCER_OT_rendersize);
+ WM_operatortype_append(SEQUENCER_OT_copy);
+ WM_operatortype_append(SEQUENCER_OT_paste);
+
WM_operatortype_append(SEQUENCER_OT_view_all);
WM_operatortype_append(SEQUENCER_OT_view_selected);
WM_operatortype_append(SEQUENCER_OT_view_all_preview);
@@ -110,10 +113,9 @@ void sequencer_operatortypes(void)
WM_operatortype_append(SEQUENCER_OT_sound_strip_add);
WM_operatortype_append(SEQUENCER_OT_image_strip_add);
WM_operatortype_append(SEQUENCER_OT_effect_strip_add);
- WM_operatortype_append(SEQUENCER_OT_properties);
- WM_operatortype_append(SEQUENCER_OT_copy);
- WM_operatortype_append(SEQUENCER_OT_paste);
+ /* sequencer_buttons.c */
+ WM_operatortype_append(SEQUENCER_OT_properties);
/* sequencer_modifiers.c */
WM_operatortype_append(SEQUENCER_OT_strip_modifier_add);
@@ -132,7 +134,9 @@ void sequencer_keymap(wmKeyConfig *keyconf)
/* Common items ------------------------------------------------------------------ */
keymap = WM_keymap_find(keyconf, "SequencerCommon", SPACE_SEQ, 0);
-
+
+ WM_keymap_add_item(keymap, "SEQUENCER_OT_properties", NKEY, KM_PRESS, 0, 0);
+
kmi = WM_keymap_add_item(keymap, "WM_OT_context_toggle", OKEY, KM_PRESS, KM_SHIFT, 0);
RNA_string_set(kmi->ptr, "data_path", "scene.sequence_editor.show_overlay");
@@ -141,9 +145,7 @@ void sequencer_keymap(wmKeyConfig *keyconf)
/* Strips Region --------------------------------------------------------------- */
keymap = WM_keymap_find(keyconf, "Sequencer", SPACE_SEQ, 0);
-
- WM_keymap_add_item(keymap, "SEQUENCER_OT_properties", NKEY, KM_PRESS, 0, 0);
-
+
kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_select_all", AKEY, KM_PRESS, 0, 0);
RNA_enum_set(kmi->ptr, "action", SEL_TOGGLE);
kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_select_all", IKEY, KM_PRESS, KM_CTRL, 0);
@@ -153,12 +155,12 @@ void sequencer_keymap(wmKeyConfig *keyconf)
RNA_enum_set(kmi->ptr, "type", SEQ_CUT_SOFT);
kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_cut", KKEY, KM_PRESS, KM_SHIFT, 0);
RNA_enum_set(kmi->ptr, "type", SEQ_CUT_HARD);
-
+
kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_mute", HKEY, KM_PRESS, 0, 0);
RNA_boolean_set(kmi->ptr, "unselected", FALSE);
kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_mute", HKEY, KM_PRESS, KM_SHIFT, 0);
RNA_boolean_set(kmi->ptr, "unselected", TRUE);
-
+
kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_unmute", HKEY, KM_PRESS, KM_ALT, 0);
RNA_boolean_set(kmi->ptr, "unselected", FALSE);
kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_unmute", HKEY, KM_PRESS, KM_ALT | KM_SHIFT, 0);
@@ -179,7 +181,7 @@ void sequencer_keymap(wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "SEQUENCER_OT_delete", XKEY, KM_PRESS, 0, 0);
WM_keymap_add_item(keymap, "SEQUENCER_OT_delete", DELKEY, KM_PRESS, 0, 0);
-
+
WM_keymap_add_item(keymap, "SEQUENCER_OT_copy", CKEY, KM_PRESS, KM_CTRL, 0);
WM_keymap_add_item(keymap, "SEQUENCER_OT_paste", VKEY, KM_PRESS, KM_CTRL, 0);
@@ -210,7 +212,7 @@ void sequencer_keymap(wmKeyConfig *keyconf)
RNA_enum_set(WM_keymap_add_item(keymap, "SEQUENCER_OT_swap", LEFTARROWKEY, KM_PRESS, KM_ALT, 0)->ptr, "side", SEQ_SIDE_LEFT);
RNA_enum_set(WM_keymap_add_item(keymap, "SEQUENCER_OT_swap", RIGHTARROWKEY, KM_PRESS, KM_ALT, 0)->ptr, "side", SEQ_SIDE_RIGHT);
-
+
WM_keymap_add_item(keymap, "SEQUENCER_OT_snap", SKEY, KM_PRESS, KM_SHIFT, 0);
WM_keymap_add_item(keymap, "SEQUENCER_OT_swap_inputs", SKEY, KM_PRESS, KM_ALT, 0);
@@ -245,7 +247,7 @@ void sequencer_keymap(wmKeyConfig *keyconf)
RNA_boolean_set(kmi->ptr, "linked_left", TRUE);
kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_select", SELECTMOUSE, KM_PRESS, KM_ALT, 0);
RNA_boolean_set(kmi->ptr, "linked_right", TRUE);
-
+
kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_select", SELECTMOUSE, KM_PRESS, KM_CTRL | KM_ALT, 0);
RNA_boolean_set(kmi->ptr, "linked_left", TRUE);
RNA_boolean_set(kmi->ptr, "linked_right", TRUE);
@@ -293,14 +295,14 @@ void sequencer_keymap(wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "SEQUENCER_OT_select_more", PADPLUSKEY, KM_PRESS, KM_CTRL, 0);
WM_keymap_add_item(keymap, "SEQUENCER_OT_select_less", PADMINUS, KM_PRESS, KM_CTRL, 0);
-
+
kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_select_linked_pick", LKEY, KM_PRESS, 0, 0);
RNA_boolean_set(kmi->ptr, "extend", FALSE);
kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_select_linked_pick", LKEY, KM_PRESS, KM_SHIFT, 0);
RNA_boolean_set(kmi->ptr, "extend", TRUE);
-
+
WM_keymap_add_item(keymap, "SEQUENCER_OT_select_linked", LKEY, KM_PRESS, KM_CTRL, 0);
-
+
WM_keymap_add_item(keymap, "SEQUENCER_OT_select_border", BKEY, KM_PRESS, 0, 0);
WM_keymap_add_item(keymap, "SEQUENCER_OT_select_grouped", GKEY, KM_PRESS, KM_SHIFT, 0);
@@ -308,33 +310,32 @@ void sequencer_keymap(wmKeyConfig *keyconf)
WM_keymap_add_menu(keymap, "SEQUENCER_MT_add", AKEY, KM_PRESS, KM_SHIFT, 0);
WM_keymap_add_menu(keymap, "SEQUENCER_MT_change", CKEY, KM_PRESS, 0, 0);
-
+
kmi = WM_keymap_add_item(keymap, "WM_OT_context_set_int", OKEY, KM_PRESS, 0, 0);
RNA_string_set(kmi->ptr, "data_path", "scene.sequence_editor.overlay_frame");
RNA_int_set(kmi->ptr, "value", 0);
transform_keymap_for_space(keyconf, keymap, SPACE_SEQ);
-
+
/* special markers hotkeys for anim editors: see note in definition of this function */
ED_marker_keymap_animedit_conflictfree(keymap);
-
-
+
+
/* Preview Region ----------------------------------------------------------- */
keymap = WM_keymap_find(keyconf, "SequencerPreview", SPACE_SEQ, 0);
WM_keymap_add_item(keymap, "SEQUENCER_OT_view_all_preview", HOMEKEY, KM_PRESS, 0, 0);
- WM_keymap_add_item(keymap, "SEQUENCER_OT_properties", NKEY, KM_PRESS, 0, 0);
WM_keymap_add_item(keymap, "SEQUENCER_OT_view_ghost_border", OKEY, KM_PRESS, 0, 0);
/* would prefer to use numpad keys for job */
RNA_float_set(WM_keymap_add_item(keymap, "SEQUENCER_OT_view_zoom_ratio", PAD1, KM_PRESS, 0, 0)->ptr, "ratio", 1.0f);
-
+
/* Setting zoom levels is not that useful, except for back to zoom level 1, removing keymap because of conflicts for now */
#if 0
RNA_float_set(WM_keymap_add_item(keymap, "SEQUENCER_OT_view_zoom_ratio", PAD8, KM_PRESS, KM_SHIFT, 0)->ptr, "ratio", 8.0f);
RNA_float_set(WM_keymap_add_item(keymap, "SEQUENCER_OT_view_zoom_ratio", PAD4, KM_PRESS, KM_SHIFT, 0)->ptr, "ratio", 4.0f);
RNA_float_set(WM_keymap_add_item(keymap, "SEQUENCER_OT_view_zoom_ratio", PAD2, KM_PRESS, KM_SHIFT, 0)->ptr, "ratio", 2.0f);
-
+
RNA_float_set(WM_keymap_add_item(keymap, "SEQUENCER_OT_view_zoom_ratio", PAD2, KM_PRESS, 0, 0)->ptr, "ratio", 0.5f);
RNA_float_set(WM_keymap_add_item(keymap, "SEQUENCER_OT_view_zoom_ratio", PAD4, KM_PRESS, 0, 0)->ptr, "ratio", 0.25f);
RNA_float_set(WM_keymap_add_item(keymap, "SEQUENCER_OT_view_zoom_ratio", PAD8, KM_PRESS, 0, 0)->ptr, "ratio", 0.125f);
diff --git a/source/blender/editors/space_sequencer/sequencer_scopes.c b/source/blender/editors/space_sequencer/sequencer_scopes.c
index d09d6a29c10..6ed34a79510 100644
--- a/source/blender/editors/space_sequencer/sequencer_scopes.c
+++ b/source/blender/editors/space_sequencer/sequencer_scopes.c
@@ -449,6 +449,8 @@ static void draw_histogram_bar(ImBuf *ibuf, int x, float val, int col)
}
}
+#define HIS_STEPS 512
+
static ImBuf *make_histogram_view_from_ibuf_byte(ImBuf *ibuf)
{
ImBuf *rval = IMB_allocImBuf(515, 128, 32, IB_rect);
@@ -456,13 +458,13 @@ static ImBuf *make_histogram_view_from_ibuf_byte(ImBuf *ibuf)
unsigned int n;
unsigned char *src = (unsigned char *) ibuf->rect;
- unsigned int bins[3][256];
+ unsigned int bins[3][HIS_STEPS];
memset(bins, 0, sizeof(bins));
#pragma omp parallel for shared(bins, src, ibuf) private(x, y) if (ibuf->y >= 256)
for (y = 0; y < ibuf->y; y++) {
- unsigned int cur_bins[3][512];
+ unsigned int cur_bins[3][HIS_STEPS];
memset(cur_bins, 0, sizeof(cur_bins));
@@ -477,7 +479,7 @@ static ImBuf *make_histogram_view_from_ibuf_byte(ImBuf *ibuf)
#pragma omp critical
{
int i;
- for (i = 0; i < 512; i++) {
+ for (i = 0; i < HIS_STEPS; i++) {
bins[0][i] += cur_bins[0][i];
bins[1][i] += cur_bins[1][i];
bins[2][i] += cur_bins[2][i];
@@ -487,7 +489,7 @@ static ImBuf *make_histogram_view_from_ibuf_byte(ImBuf *ibuf)
n = 0;
for (c = 0; c < 3; c++) {
- for (x = 0; x < 256; x++) {
+ for (x = 0; x < HIS_STEPS; x++) {
if (bins[c][x] > n) {
n = bins[c][x];
}
@@ -495,7 +497,7 @@ static ImBuf *make_histogram_view_from_ibuf_byte(ImBuf *ibuf)
}
for (c = 0; c < 3; c++) {
- for (x = 0; x < 256; x++) {
+ for (x = 0; x < HIS_STEPS; x++) {
draw_histogram_bar(rval, x * 2 + 1, ((float) bins[c][x]) / n, c);
draw_histogram_bar(rval, x * 2 + 2, ((float) bins[c][x]) / n, c);
}
@@ -524,13 +526,13 @@ static ImBuf *make_histogram_view_from_ibuf_float(ImBuf *ibuf)
int n, c, x, y;
float *src = ibuf->rect_float;
- unsigned int bins[3][512];
+ unsigned int bins[3][HIS_STEPS];
memset(bins, 0, sizeof(bins));
#pragma omp parallel for shared(bins, src, ibuf) private(x, y) if (ibuf->y >= 256)
for (y = 0; y < ibuf->y; y++) {
- unsigned int cur_bins[3][512];
+ unsigned int cur_bins[3][HIS_STEPS];
memset(cur_bins, 0, sizeof(cur_bins));
@@ -545,7 +547,7 @@ static ImBuf *make_histogram_view_from_ibuf_float(ImBuf *ibuf)
#pragma omp critical
{
int i;
- for (i = 0; i < 512; i++) {
+ for (i = 0; i < HIS_STEPS; i++) {
bins[0][i] += cur_bins[0][i];
bins[1][i] += cur_bins[1][i];
bins[2][i] += cur_bins[2][i];
@@ -558,14 +560,14 @@ static ImBuf *make_histogram_view_from_ibuf_float(ImBuf *ibuf)
n = 0;
for (c = 0; c < 3; c++) {
- for (x = 0; x < 512; x++) {
+ for (x = 0; x < HIS_STEPS; x++) {
if (bins[c][x] > n) {
n = bins[c][x];
}
}
}
for (c = 0; c < 3; c++) {
- for (x = 0; x < 512; x++) {
+ for (x = 0; x < HIS_STEPS; x++) {
draw_histogram_bar(rval, x + 1, (float) bins[c][x] / n, c);
}
}
@@ -575,6 +577,8 @@ static ImBuf *make_histogram_view_from_ibuf_float(ImBuf *ibuf)
return rval;
}
+#undef HIS_STEPS
+
ImBuf *make_histogram_view_from_ibuf(ImBuf *ibuf)
{
if (ibuf->rect_float) {
diff --git a/source/blender/editors/space_sequencer/sequencer_select.c b/source/blender/editors/space_sequencer/sequencer_select.c
index 3d57f2f88ed..192f45ac918 100644
--- a/source/blender/editors/space_sequencer/sequencer_select.c
+++ b/source/blender/editors/space_sequencer/sequencer_select.c
@@ -353,7 +353,7 @@ static int sequencer_select_invoke(bContext *C, wmOperator *op, wmEvent *event)
}
else {
/* deselect_markers(0, 0); */ /* XXX, in 2.4x, seq selection used to deselect all, need to re-thnik this for 2.5 */
- marker->flag |= SELECT;
+ marker->flag |= SELECT;
}
}
@@ -399,7 +399,7 @@ static int sequencer_select_invoke(bContext *C, wmOperator *op, wmEvent *event)
}
}
else {
- // seq= find_nearest_seq(scene, v2d, &hand, mval);
+ // seq = find_nearest_seq(scene, v2d, &hand, mval);
act_orig = ed->act_seq;
@@ -414,8 +414,7 @@ static int sequencer_select_invoke(bContext *C, wmOperator *op, wmEvent *event)
BLI_strncpy(ed->act_imagedir, seq->strip->dir, FILE_MAXDIR);
}
}
- else
- if (seq->type == SEQ_TYPE_SOUND_RAM) {
+ else if (seq->type == SEQ_TYPE_SOUND_RAM) {
if (seq->strip) {
BLI_strncpy(ed->act_sounddir, seq->strip->dir, FILE_MAXDIR);
}
@@ -1109,7 +1108,7 @@ static short select_grouped_effect_link(Editing *ed, Sequence *actseq)
actseq->tmp = SET_INT_IN_POINTER(TRUE);
- for (BKE_seqence_iterator_begin(ed, &iter, TRUE); iter.valid; BKE_seqence_iterator_next(&iter)) {
+ for (BKE_sequence_iterator_begin(ed, &iter, TRUE); iter.valid; BKE_sequence_iterator_next(&iter)) {
seq = iter.seq;
/* Ignore all seqs already selected! */
@@ -1137,8 +1136,8 @@ static short select_grouped_effect_link(Editing *ed, Sequence *actseq)
changed = TRUE;
/* Unfortunately, we must restart checks from the beginning. */
- BKE_seqence_iterator_end(&iter);
- BKE_seqence_iterator_begin(ed, &iter, TRUE);
+ BKE_sequence_iterator_end(&iter);
+ BKE_sequence_iterator_begin(ed, &iter, TRUE);
}
/* Video strips bellow active one, or any strip for audio (order do no matters here!). */
@@ -1147,7 +1146,7 @@ static short select_grouped_effect_link(Editing *ed, Sequence *actseq)
changed = TRUE;
}
}
- BKE_seqence_iterator_end(&iter);
+ BKE_sequence_iterator_end(&iter);
return changed;
}
@@ -1167,7 +1166,7 @@ static int sequencer_select_grouped_exec(bContext *C, wmOperator *op)
extend = RNA_boolean_get(op->ptr, "extend");
if (actseq == NULL) {
- BKE_report(op->reports, RPT_ERROR, "No Active Sequence!");
+ BKE_report(op->reports, RPT_ERROR, "No active sequence!");
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/space_sequencer/sequencer_view.c b/source/blender/editors/space_sequencer/sequencer_view.c
index 3c3489115a4..92b17393114 100644
--- a/source/blender/editors/space_sequencer/sequencer_view.c
+++ b/source/blender/editors/space_sequencer/sequencer_view.c
@@ -25,7 +25,7 @@
*/
-/** \file blender/editors/space_sequencer/sequencer_modifier.c
+/** \file blender/editors/space_sequencer/sequencer_view.c
* \ingroup spseq
*/
diff --git a/source/blender/editors/space_sequencer/space_sequencer.c b/source/blender/editors/space_sequencer/space_sequencer.c
index 8ac50a57b10..e8d47016608 100644
--- a/source/blender/editors/space_sequencer/space_sequencer.c
+++ b/source/blender/editors/space_sequencer/space_sequencer.c
@@ -196,7 +196,7 @@ static SpaceLink *sequencer_new(const bContext *C)
/* not spacelink itself */
static void sequencer_free(SpaceLink *sl)
{
- SpaceSeq *sseq= (SpaceSeq *) sl;
+ SpaceSeq *sseq = (SpaceSeq *) sl;
SequencerScopes *scopes = &sseq->scopes;
// XXX if (sseq->gpd) BKE_gpencil_free(sseq->gpd);
@@ -311,7 +311,7 @@ static SpaceLink *sequencer_duplicate(SpaceLink *sl)
SpaceSeq *sseqn = MEM_dupallocN(sl);
/* clear or remove stuff from old */
-// XXX sseq->gpd= gpencil_data_duplicate(sseq->gpd);
+// XXX sseq->gpd = gpencil_data_duplicate(sseq->gpd);
return (SpaceLink *)sseqn;
}
@@ -363,7 +363,7 @@ static void sequencer_main_area_init(wmWindowManager *wm, ARegion *ar)
static void sequencer_main_area_draw(const bContext *C, ARegion *ar)
{
-// ScrArea *sa= CTX_wm_area(C);
+// ScrArea *sa = CTX_wm_area(C);
/* NLE - strip editing timeline interface */
draw_timeline_seq(C, ar);
@@ -556,8 +556,8 @@ static void sequencer_preview_area_listener(ARegion *ar, wmNotifier *wmn)
{
/* context changes */
switch (wmn->category) {
- case NC_SCREEN:
- if (wmn->data == ND_GPENCIL) {
+ case NC_GPENCIL:
+ if (wmn->action == NA_EDITED) {
ED_region_tag_redraw(ar);
}
break;
@@ -610,8 +610,8 @@ static void sequencer_buttons_area_listener(ARegion *ar, wmNotifier *wmn)
{
/* context changes */
switch (wmn->category) {
- case NC_SCREEN:
- if (wmn->data == ND_GPENCIL) {
+ case NC_GPENCIL:
+ if (wmn->data == ND_DATA) {
ED_region_tag_redraw(ar);
}
break;
diff --git a/source/blender/editors/space_text/CMakeLists.txt b/source/blender/editors/space_text/CMakeLists.txt
index ead7de92c5c..9cc407f0604 100644
--- a/source/blender/editors/space_text/CMakeLists.txt
+++ b/source/blender/editors/space_text/CMakeLists.txt
@@ -54,4 +54,8 @@ if(WITH_PYTHON)
add_definitions(-DWITH_PYTHON)
endif()
+if(WITH_INTERNATIONAL)
+ add_definitions(-DWITH_INTERNATIONAL)
+endif()
+
blender_add_lib(bf_editor_text "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/editors/space_text/SConscript b/source/blender/editors/space_text/SConscript
index 6ad6427f1d3..373564520c8 100644
--- a/source/blender/editors/space_text/SConscript
+++ b/source/blender/editors/space_text/SConscript
@@ -10,4 +10,7 @@ incs += ' ../../python ../../makesrna ../../blenfont ../../blenloader'
if env['WITH_BF_PYTHON']:
defs.append('WITH_PYTHON')
+if env['WITH_BF_INTERNATIONAL']:
+ defs.append('WITH_INTERNATIONAL')
+
env.BlenderLib ( 'bf_editors_space_text', sources, Split(incs), defs, libtype=['core'], priority=[95] )
diff --git a/source/blender/editors/space_text/space_text.c b/source/blender/editors/space_text/space_text.c
index 501e1cad67e..3f70b2cb66e 100644
--- a/source/blender/editors/space_text/space_text.c
+++ b/source/blender/editors/space_text/space_text.c
@@ -431,7 +431,7 @@ static void text_main_area_draw(const bContext *C, ARegion *ar)
{
/* draw entirely, view changes should be handled here */
SpaceText *st = CTX_wm_space_text(C);
- //View2D *v2d= &ar->v2d;
+ //View2D *v2d = &ar->v2d;
/* clear and setup matrix */
UI_ThemeClearColor(TH_BACK);
diff --git a/source/blender/editors/space_text/text_draw.c b/source/blender/editors/space_text/text_draw.c
index 97eb5b41db7..94f64563fd8 100644
--- a/source/blender/editors/space_text/text_draw.c
+++ b/source/blender/editors/space_text/text_draw.c
@@ -1139,7 +1139,7 @@ static void calc_text_rcts(SpaceText *st, ARegion *ar, rcti *scroll, rcti *back)
barheight = (ltexth > 0) ? (st->viewlines * pix_available) / ltexth : 0;
pix_bardiff = 0;
if (barheight < 20) {
- pix_bardiff = 20 - barheight; /* take into account the now non-linear sizing of the bar */
+ pix_bardiff = 20 - barheight; /* take into account the now non-linear sizing of the bar */
barheight = 20;
}
barstart = (ltexth > 0) ? ((pix_available - pix_bardiff) * st->top) / ltexth : 0;
@@ -1166,9 +1166,9 @@ static void calc_text_rcts(SpaceText *st, ARegion *ar, rcti *scroll, rcti *back)
/* the scrollbar is non-linear sized */
if (pix_bardiff > 0) {
/* the start of the highlight is in the current viewport */
- if (ltexth && st->viewlines && lhlstart >= st->top && lhlstart <= st->top + st->viewlines) {
+ if (ltexth && st->viewlines && lhlstart >= st->top && lhlstart <= st->top + st->viewlines) {
/* speed the progresion of the start of the highlight through the scrollbar */
- hlstart = ( ( (pix_available - pix_bardiff) * lhlstart) / ltexth) + (pix_bardiff * (lhlstart - st->top) / st->viewlines);
+ hlstart = ( ( (pix_available - pix_bardiff) * lhlstart) / ltexth) + (pix_bardiff * (lhlstart - st->top) / st->viewlines);
}
else if (lhlstart > st->top + st->viewlines && hlstart < barstart + barheight && hlstart > barstart) {
/* push hl start down */
@@ -1179,35 +1179,35 @@ static void calc_text_rcts(SpaceText *st, ARegion *ar, rcti *scroll, rcti *back)
hlstart = barstart;
}
- if (hlend <= hlstart) {
+ if (hlend <= hlstart) {
hlend = hlstart + 2;
}
/* the end of the highlight is in the current viewport */
- if (ltexth && st->viewlines && lhlend >= st->top && lhlend <= st->top + st->viewlines) {
+ if (ltexth && st->viewlines && lhlend >= st->top && lhlend <= st->top + st->viewlines) {
/* speed the progresion of the end of the highlight through the scrollbar */
hlend = (((pix_available - pix_bardiff) * lhlend) / ltexth) + (pix_bardiff * (lhlend - st->top) / st->viewlines);
}
else if (lhlend < st->top && hlend >= barstart - 2 && hlend < barstart + barheight) {
/* push hl end up */
hlend = barstart;
- }
+ }
else if (lhlend > st->top + st->viewlines && lhlstart < st->top + st->viewlines && hlend < barstart + barheight) {
/* fill out end */
hlend = barstart + barheight;
}
- if (hlend <= hlstart) {
+ if (hlend <= hlstart) {
hlstart = hlend - 2;
- }
- }
+ }
+ }
}
else {
hlstart = 0;
hlend = 0;
}
- if (hlend - hlstart < 2) {
+ if (hlend - hlstart < 2) {
hlend = hlstart + 2;
}
@@ -1232,7 +1232,7 @@ static void draw_textscroll(SpaceText *st, rcti *scroll, rcti *back)
uiWidgetScrollDraw(&wcol, scroll, &st->txtbar, (st->flags & ST_SCROLL_SELECT) ? UI_SCROLL_PRESSED : 0);
uiSetRoundBox(UI_CNR_ALL);
- rad = 0.4f * mini(BLI_RCT_SIZE_X(&st->txtscroll), BLI_RCT_SIZE_Y(&st->txtscroll));
+ rad = 0.4f * min_ii(BLI_rcti_size_x(&st->txtscroll), BLI_rcti_size_y(&st->txtscroll));
UI_GetThemeColor3ubv(TH_HILITE, col);
col[3] = 48;
glColor4ubv(col);
@@ -1355,7 +1355,7 @@ static void draw_documentation(SpaceText *st, ARegion *ar)
x += SUGG_LIST_WIDTH * st->cwidth + 50;
}
- /* top= */ /* UNUSED */ y = ar->winy - st->lheight * l - 2;
+ /* top = */ /* UNUSED */ y = ar->winy - st->lheight * l - 2;
boxw = DOC_WIDTH * st->cwidth + 20;
boxh = (DOC_HEIGHT + 1) * st->lheight;
@@ -1702,7 +1702,7 @@ static void draw_brackets(SpaceText *st, ARegion *ar)
if (!endl || endc == -1)
return;
- UI_ThemeColor(TH_HILITE);
+ UI_ThemeColor(TH_HILITE);
x = st->showlinenrs ? TXT_OFFSET + TEXTXLOC : TXT_OFFSET;
y = ar->winy - st->lheight;
@@ -1741,6 +1741,7 @@ void draw_text_main(SpaceText *st, ARegion *ar)
char linenr[12];
int i, x, y, winx, linecount = 0, lineno = 0;
int wraplinecount = 0, wrap_skip = 0;
+ int margin_column_x;
if (st->lheight) st->viewlines = (int)ar->winy / st->lheight;
else st->viewlines = 0;
@@ -1788,7 +1789,7 @@ void draw_text_main(SpaceText *st, ARegion *ar)
text_font_begin(st);
st->cwidth = BLF_fixed_width(mono);
- st->cwidth = MAX2(st->cwidth, 1);
+ st->cwidth = MAX2(st->cwidth, (char)1);
/* draw line numbers background */
if (st->showlinenrs) {
@@ -1845,10 +1846,14 @@ void draw_text_main(SpaceText *st, ARegion *ar)
if (st->flags & ST_SHOW_MARGIN) {
UI_ThemeColor(TH_HILITE);
- glBegin(GL_LINES);
- glVertex2i(x + st->cwidth * st->margin_column, 0);
- glVertex2i(x + st->cwidth * st->margin_column, ar->winy - 2);
- glEnd();
+ margin_column_x = x + st->cwidth * (st->margin_column - st->left);
+
+ if (margin_column_x >= x) {
+ glBegin(GL_LINES);
+ glVertex2i(margin_column_x, 0);
+ glVertex2i(margin_column_x, ar->winy - 2);
+ glEnd();
+ }
}
/* draw other stuff */
@@ -1868,7 +1873,7 @@ void text_update_character_width(SpaceText *st)
{
text_font_begin(st);
st->cwidth = BLF_fixed_width(mono);
- st->cwidth = MAX2(st->cwidth, 1);
+ st->cwidth = MAX2(st->cwidth, (char)1);
text_font_end(st);
}
diff --git a/source/blender/editors/space_text/text_header.c b/source/blender/editors/space_text/text_header.c
index b0cd6aeaab4..7dc3ec1ac60 100644
--- a/source/blender/editors/space_text/text_header.c
+++ b/source/blender/editors/space_text/text_header.c
@@ -59,17 +59,12 @@
#include "WM_types.h"
-
-
-
#ifdef WITH_PYTHON
// XXX #include "BPY_menus.h"
#endif
#include "text_intern.h"
-#define HEADER_PATH_MAX 260
-
/* ************************ header area region *********************** */
/************************** properties ******************************/
diff --git a/source/blender/editors/space_text/text_ops.c b/source/blender/editors/space_text/text_ops.c
index 5af44f93d06..2d902c4586a 100644
--- a/source/blender/editors/space_text/text_ops.c
+++ b/source/blender/editors/space_text/text_ops.c
@@ -44,6 +44,8 @@
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
+#include "BLF_translation.h"
+
#include "PIL_time.h"
#include "BKE_context.h"
@@ -93,7 +95,7 @@ static int text_edit_poll(bContext *C)
return 0;
if (text->id.lib) {
- // BKE_report(op->reports, RPT_ERROR, "Can't edit external libdata");
+ // BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
return 0;
}
@@ -109,7 +111,7 @@ static int text_space_edit_poll(bContext *C)
return 0;
if (text->id.lib) {
- // BKE_report(op->reports, RPT_ERROR, "Can't edit external libdata");
+ // BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
return 0;
}
@@ -129,7 +131,7 @@ static int text_region_edit_poll(bContext *C)
return 0;
if (text->id.lib) {
- // BKE_report(op->reports, RPT_ERROR, "Can't edit external libdata");
+ // BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
return 0;
}
@@ -463,7 +465,8 @@ static void txt_write_file(Text *text, ReportList *reports)
fp = BLI_fopen(filepath, "w");
if (fp == NULL) {
- BKE_reportf(reports, RPT_ERROR, "Unable to save \"%s\": %s", filepath, errno ? strerror(errno) : "Unknown error writing file");
+ BKE_reportf(reports, RPT_ERROR, "Unable to save '%s': %s",
+ filepath, errno ? strerror(errno) : TIP_("unknown error writing file"));
return;
}
@@ -482,7 +485,8 @@ static void txt_write_file(Text *text, ReportList *reports)
}
else {
text->mtime = 0;
- BKE_reportf(reports, RPT_WARNING, "Unable to stat \"%s\": %s", filepath, errno ? strerror(errno) : "Unknown error starrng file");
+ BKE_reportf(reports, RPT_WARNING, "Unable to stat '%s': %s",
+ filepath, errno ? strerror(errno) : TIP_("unknown error stating file"));
}
if (text->flags & TXT_ISDIRTY)
@@ -602,9 +606,12 @@ static int text_run_script(bContext *C, ReportList *reports)
/* Don't report error messages while live editing */
if (!is_live) {
- if (text->curl != curl_prev || curc_prev != text->curc) {
- text_update_cursor_moved(C);
- WM_event_add_notifier(C, NC_TEXT | NA_EDITED, text);
+ /* text may have freed its self */
+ if (CTX_data_edit_text(C) == text) {
+ if (text->curl != curl_prev || curc_prev != text->curc) {
+ text_update_cursor_moved(C);
+ WM_event_add_notifier(C, NC_TEXT | NA_EDITED, text);
+ }
}
BKE_report(reports, RPT_ERROR, "Python script fail, look in the console for now...");
@@ -967,21 +974,17 @@ static int text_unindent_exec(bContext *C, wmOperator *UNUSED(op))
{
Text *text = CTX_data_edit_text(C);
- if (txt_has_sel(text)) {
- text_drawcache_tag_update(CTX_wm_space_text(C), 0);
+ text_drawcache_tag_update(CTX_wm_space_text(C), 0);
- txt_order_cursors(text);
- txt_unindent(text);
+ txt_order_cursors(text);
+ txt_unindent(text);
- text_update_edited(text);
-
- text_update_cursor_moved(C);
- WM_event_add_notifier(C, NC_TEXT | NA_EDITED, text);
+ text_update_edited(text);
- return OPERATOR_FINISHED;
- }
+ text_update_cursor_moved(C);
+ WM_event_add_notifier(C, NC_TEXT | NA_EDITED, text);
- return OPERATOR_CANCELLED;
+ return OPERATOR_FINISHED;
}
void TEXT_OT_unindent(wmOperatorType *ot)
@@ -1945,7 +1948,7 @@ static int text_move_cursor(bContext *C, int type, int select)
txt_move_left(text, select);
break;
- case NEXT_CHAR:
+ case NEXT_CHAR:
txt_move_right(text, select);
break;
@@ -2409,8 +2412,8 @@ static int text_scroll_bar_invoke(bContext *C, wmOperator *op, wmEvent *event)
/* jump scroll, works in v2d but needs to be added here too :S */
if (event->type == MIDDLEMOUSE) {
- tsc->old[0] = ar->winrct.xmin + BLI_RCT_CENTER_X(&st->txtbar);
- tsc->old[1] = ar->winrct.ymin + BLI_RCT_CENTER_Y(&st->txtbar);
+ tsc->old[0] = ar->winrct.xmin + BLI_rcti_cent_x(&st->txtbar);
+ tsc->old[1] = ar->winrct.ymin + BLI_rcti_cent_y(&st->txtbar);
tsc->delta[0] = 0;
tsc->delta[1] = 0;
@@ -2666,7 +2669,7 @@ static void text_cursor_set_apply(bContext *C, wmOperator *op, wmEvent *event)
text_update_cursor_moved(C);
WM_event_add_notifier(C, NC_TEXT | ND_CURSOR, st->text);
- }
+ }
else if (!st->wordwrap && (event->mval[0] < 0 || event->mval[0] > ar->winx)) {
if (event->mval[0] > ar->winx) st->left++;
else if (event->mval[0] < 0 && st->left > 0) st->left--;
@@ -2676,7 +2679,7 @@ static void text_cursor_set_apply(bContext *C, wmOperator *op, wmEvent *event)
text_update_cursor_moved(C);
WM_event_add_notifier(C, NC_TEXT | ND_CURSOR, st->text);
// XXX PIL_sleep_ms(10);
- }
+ }
else {
text_cursor_set_to_pos(st, ar, event->mval[0], event->mval[1], 1);
@@ -2685,7 +2688,7 @@ static void text_cursor_set_apply(bContext *C, wmOperator *op, wmEvent *event)
ssel->old[0] = event->mval[0];
ssel->old[1] = event->mval[1];
- }
+ }
}
static void text_cursor_set_exit(bContext *C, wmOperator *op)
@@ -3349,7 +3352,7 @@ void TEXT_OT_to_3d_object(wmOperatorType *ot)
/* identifiers */
ot->name = "To 3D Object";
ot->idname = "TEXT_OT_to_3d_object";
- ot->description = "Create 3d text object from active text data block";
+ ot->description = "Create 3D text object from active text data block";
/* api callbacks */
ot->exec = text_to_3d_object_exec;
diff --git a/source/blender/editors/space_text/text_python.c b/source/blender/editors/space_text/text_python.c
index f980e19e9c8..966afe22e42 100644
--- a/source/blender/editors/space_text/text_python.c
+++ b/source/blender/editors/space_text/text_python.c
@@ -180,13 +180,9 @@ static void confirm_suggestion(Text *text, int skipleft)
}
// XXX
-#define L_MOUSE 0
-#define M_MOUSE 0
-#define R_MOUSE 0
#define LR_SHIFTKEY 0
#define LR_ALTKEY 0
#define LR_CTRLKEY 0
-#define LR_OSKEY 0
// XXX
static int doc_scroll = 0;
diff --git a/source/blender/editors/space_time/space_time.c b/source/blender/editors/space_time/space_time.c
index a9315313d26..13c1938d77c 100644
--- a/source/blender/editors/space_time/space_time.c
+++ b/source/blender/editors/space_time/space_time.c
@@ -401,6 +401,7 @@ static void time_listener(ScrArea *sa, wmNotifier *wmn)
case ND_POINTCACHE:
case ND_MODIFIER:
case ND_PARTICLE:
+ case ND_KEYS:
ED_area_tag_refresh(sa);
ED_area_tag_redraw(sa);
break;
diff --git a/source/blender/editors/space_time/time_ops.c b/source/blender/editors/space_time/time_ops.c
index 733fd27135b..9067fb6933f 100644
--- a/source/blender/editors/space_time/time_ops.c
+++ b/source/blender/editors/space_time/time_ops.c
@@ -151,7 +151,7 @@ static int time_view_all_exec(bContext *C, wmOperator *UNUSED(op))
v2d->cur.xmax = (float)PEFRA;
/* we need an extra "buffer" factor on either side so that the endpoints are visible */
- extra = 0.01f * BLI_RCT_SIZE_X(&v2d->cur);
+ extra = 0.01f * BLI_rctf_size_x(&v2d->cur);
v2d->cur.xmin -= extra;
v2d->cur.xmax += extra;
diff --git a/source/blender/editors/space_userpref/space_userpref.c b/source/blender/editors/space_userpref/space_userpref.c
index 5376b82f24c..1ea3876f5cc 100644
--- a/source/blender/editors/space_userpref/space_userpref.c
+++ b/source/blender/editors/space_userpref/space_userpref.c
@@ -80,7 +80,7 @@ static SpaceLink *userpref_new(const bContext *UNUSED(C))
/* not spacelink itself */
static void userpref_free(SpaceLink *UNUSED(sl))
{
-// SpaceUserPref *spref= (SpaceUserPref*) sl;
+// SpaceUserPref *spref = (SpaceUserPref *)sl;
}
diff --git a/source/blender/editors/space_view3d/CMakeLists.txt b/source/blender/editors/space_view3d/CMakeLists.txt
index 1bba237ed5c..35dd88c3209 100644
--- a/source/blender/editors/space_view3d/CMakeLists.txt
+++ b/source/blender/editors/space_view3d/CMakeLists.txt
@@ -51,7 +51,9 @@ set(SRC
view3d_edit.c
view3d_fly.c
view3d_header.c
+ view3d_iterators.c
view3d_ops.c
+ view3d_project.c
view3d_select.c
view3d_snap.c
view3d_toolbar.c
diff --git a/source/blender/editors/space_view3d/drawanimviz.c b/source/blender/editors/space_view3d/drawanimviz.c
index 5f312ff7fca..0649edc1ac4 100644
--- a/source/blender/editors/space_view3d/drawanimviz.c
+++ b/source/blender/editors/space_view3d/drawanimviz.c
@@ -84,7 +84,7 @@ void draw_motion_paths_init(View3D *v3d, ARegion *ar)
void draw_motion_path_instance(Scene *scene,
Object *ob, bPoseChannel *pchan, bAnimVizSettings *avs, bMotionPath *mpath)
{
- //RegionView3D *rv3d= ar->regiondata;
+ //RegionView3D *rv3d = ar->regiondata;
bMotionPathVert *mpv, *mpv_start;
int i, stepsize = avs->path_step;
int sfra, efra, sind, len;
@@ -107,11 +107,6 @@ void draw_motion_path_instance(Scene *scene,
* - abort if whole range is past ends of path
* - otherwise clamp endpoints to extents of path
*/
- if ((sfra > mpath->end_frame) || (efra < mpath->start_frame)) {
- /* whole path is out of bounds */
- return;
- }
-
if (sfra < mpath->start_frame) {
/* start clamp */
sfra = mpath->start_frame;
@@ -121,9 +116,14 @@ void draw_motion_path_instance(Scene *scene,
efra = mpath->end_frame;
}
+ if ((sfra > mpath->end_frame) || (efra < mpath->start_frame)) {
+ /* whole path is out of bounds */
+ return;
+ }
+
len = efra - sfra;
- if (len <= 0) {
+ if ((len <= 0) || (mpath->points == NULL)) {
return;
}
@@ -148,11 +148,11 @@ void draw_motion_path_instance(Scene *scene,
if ((sfra + i) < CFRA) {
/* black - before cfra */
if (sel) {
- // intensity= 0.5f;
+ // intensity = 0.5f;
intensity = SET_INTENSITY(sfra, i, CFRA, 0.25f, 0.75f);
}
else {
- //intensity= 0.8f;
+ //intensity = 0.8f;
intensity = SET_INTENSITY(sfra, i, CFRA, 0.68f, 0.92f);
}
UI_ThemeColorBlend(TH_WIRE, TH_BACK, intensity);
@@ -178,9 +178,9 @@ void draw_motion_path_instance(Scene *scene,
intensity = 0.99f;
}
UI_ThemeColorBlendShade(TH_CFRAME, TH_BACK, intensity, 10);
- }
+ }
- /* draw a vertex with this color */
+ /* draw a vertex with this color */
glVertex3fv(mpv->co);
}
@@ -230,7 +230,7 @@ void draw_motion_path_instance(Scene *scene,
unsigned char col[4];
UI_GetThemeColor3ubv(TH_TEXT_HI, col);
col[3] = 255;
-
+
for (i = 0, mpv = mpv_start; i < len; i += stepsize, mpv += stepsize) {
char numstr[32];
float co[3];
diff --git a/source/blender/editors/space_view3d/drawarmature.c b/source/blender/editors/space_view3d/drawarmature.c
index ecce12b8cba..beafee335d4 100644
--- a/source/blender/editors/space_view3d/drawarmature.c
+++ b/source/blender/editors/space_view3d/drawarmature.c
@@ -100,7 +100,7 @@ static void set_pchan_colorset(Object *ob, bPoseChannel *pchan)
}
/* only try to set custom color if enabled for armature */
- if (arm->flag & ARM_COL_CUSTOM) {
+ if (arm->flag & ARM_COL_CUSTOM) {
/* currently, a bone can only use a custom color set if it's group (if it has one),
* has been set to use one
*/
@@ -647,7 +647,7 @@ static void draw_sphere_bone_dist(float smat[][4], float imat[][4], bPoseChannel
/* this routine doesn't call get_matrix_editbone() that calculates it */
ebone->length = len_v3v3(ebone->head, ebone->tail);
- /*length= ebone->length;*/ /*UNUSED*/
+ /*length = ebone->length;*/ /*UNUSED*/
tail = ebone->rad_tail;
dist = ebone->dist;
if (ebone->parent && (ebone->flag & BONE_CONNECTED))
@@ -658,7 +658,7 @@ static void draw_sphere_bone_dist(float smat[][4], float imat[][4], bPoseChannel
tailvec = ebone->tail;
}
else {
- /*length= pchan->bone->length;*/ /*UNUSED*/
+ /*length = pchan->bone->length;*/ /*UNUSED*/
tail = pchan->bone->rad_tail;
dist = pchan->bone->dist;
if (pchan->parent && (pchan->bone->flag & BONE_CONNECTED))
@@ -767,7 +767,7 @@ static void draw_sphere_bone_wire(float smat[][4], float imat[][4],
/* this routine doesn't call get_matrix_editbone() that calculates it */
ebone->length = len_v3v3(ebone->head, ebone->tail);
- /*length= ebone->length;*/ /*UNUSED*/
+ /*length = ebone->length;*/ /*UNUSED*/
tail = ebone->rad_tail;
if (ebone->parent && (boneflag & BONE_CONNECTED))
head = ebone->parent->rad_tail;
@@ -777,7 +777,7 @@ static void draw_sphere_bone_wire(float smat[][4], float imat[][4],
tailvec = ebone->tail;
}
else {
- /*length= pchan->bone->length;*/ /*UNUSED*/
+ /*length = pchan->bone->length;*/ /*UNUSED*/
tail = pchan->bone->rad_tail;
if ((pchan->parent) && (boneflag & BONE_CONNECTED))
head = pchan->parent->bone->rad_tail;
@@ -969,7 +969,7 @@ static void draw_sphere_bone(const short dt, int armflag, int boneflag, short co
glTranslatef(0.0f, 0.0f, head);
gluSphere(qobj, fac1 * head + (1.0f - fac1) * tail, 16, 10);
}
- else {
+ else {
/* 1 sphere in center */
glTranslatef(0.0f, 0.0f, (head + length - tail) / 2.0f);
gluSphere(qobj, fac1 * head + (1.0f - fac1) * tail, 16, 10);
@@ -1040,7 +1040,7 @@ static void draw_line_bone(int armflag, int boneflag, short constflag, unsigned
glEnd();
/* tip */
- if (G.f & G_PICKSEL) {
+ if (G.f & G_PICKSEL) {
/* no bitmap in selection mode, crashes 3d cards... */
glLoadName(id | BONESEL_TIP);
glBegin(GL_POINTS);
@@ -1189,7 +1189,7 @@ static void draw_b_bone(const short dt, int armflag, int boneflag, short constfl
glDisable(GL_COLOR_MATERIAL);
glDisable(GL_LIGHTING);
}
- else {
+ else {
/* wire */
if (armflag & ARM_POSEMODE) {
if (constflag) {
@@ -1205,9 +1205,9 @@ static void draw_b_bone(const short dt, int armflag, int boneflag, short constfl
/* restore colors */
set_pchan_glColor(PCHAN_COLOR_NORMAL, boneflag, constflag);
}
- }
+ }
- draw_b_bone_boxes(OB_WIRE, pchan, xwidth, length, zwidth);
+ draw_b_bone_boxes(OB_WIRE, pchan, xwidth, length, zwidth);
}
}
@@ -1333,7 +1333,7 @@ static void draw_bone(const short dt, int armflag, int boneflag, short constflag
else if (armflag & ARM_POSEMODE) {
if (constflag) {
/* draw constraint colors */
- if (set_pchan_glColor(PCHAN_COLOR_CONSTS, boneflag, constflag)) {
+ if (set_pchan_glColor(PCHAN_COLOR_CONSTS, boneflag, constflag)) {
glEnable(GL_BLEND);
draw_bone_solid_octahedral();
@@ -1344,10 +1344,10 @@ static void draw_bone(const short dt, int armflag, int boneflag, short constflag
/* restore colors */
set_pchan_glColor(PCHAN_COLOR_NORMAL, boneflag, constflag);
}
- }
+ }
draw_bone_octahedral();
}
- else {
+ else {
/* solid */
if (armflag & ARM_POSEMODE)
set_pchan_glColor(PCHAN_COLOR_SOLID, boneflag, constflag);
@@ -1741,7 +1741,7 @@ static void draw_pose_bones(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
if (use_custom && pchan->custom_tx) {
glMultMatrixf(pchan->custom_tx->pose_mat);
- }
+ }
else {
glMultMatrixf(pchan->pose_mat);
}
@@ -1803,7 +1803,7 @@ static void draw_pose_bones(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
*/
if (ELEM(arm->drawtype, ARM_LINE, ARM_WIRE) == 0 && (draw_wire == 0)) {
/* object tag, for bordersel optim */
- glLoadName(index & 0xFFFF);
+ glLoadName(index & 0xFFFF);
index = -1;
}
}
@@ -1830,7 +1830,7 @@ static void draw_pose_bones(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
if (pchan->custom_tx) {
glMultMatrixf(pchan->custom_tx->pose_mat);
- }
+ }
else {
glMultMatrixf(pchan->pose_mat);
}
@@ -1869,7 +1869,7 @@ static void draw_pose_bones(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
/* stick or wire bones have not been drawn yet so don't clear object selection in this case */
if (ELEM(arm->drawtype, ARM_LINE, ARM_WIRE) == 0 && draw_wire) {
/* object tag, for bordersel optim */
- glLoadName(index & 0xFFFF);
+ glLoadName(index & 0xFFFF);
index = -1;
}
}
@@ -1938,7 +1938,7 @@ static void draw_pose_bones(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
glLoadName(index & 0xFFFF);
pchan_draw_IK_root_lines(pchan, !(do_dashed & 2));
}
- }
+ }
}
}
@@ -1992,7 +1992,7 @@ static void draw_pose_bones(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
/* restore things */
if (!ELEM(arm->drawtype, ARM_WIRE, ARM_LINE) && (dt > OB_WIRE) && (arm->flag & ARM_POSEMODE))
bglPolygonOffset(rv3d->dist, 0.0);
- }
+ }
/* restore */
glDisable(GL_CULL_FACE);
@@ -2045,7 +2045,7 @@ static void draw_pose_bones(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
if (arm->flag & ARM_DRAWNAMES) {
mid_v3_v3v3(vec, pchan->pose_head, pchan->pose_tail);
view3d_cached_text_draw_add(vec, pchan->name, 10, 0, col);
- }
+ }
/* Draw additional axes on the bone tail */
if ((arm->flag & ARM_DRAWAXES) && (arm->flag & ARM_POSEMODE)) {
@@ -2075,7 +2075,7 @@ static void get_matrix_editbone(EditBone *eBone, float bmat[][4])
float mat[3][3];
/* Compose the parent transforms (i.e. their translations) */
- sub_v3_v3v3(delta, eBone->tail, eBone->head);
+ sub_v3_v3v3(delta, eBone->tail, eBone->head);
eBone->length = (float)sqrt(delta[0] * delta[0] + delta[1] * delta[1] + delta[2] * delta[2]);
@@ -2226,9 +2226,16 @@ static void draw_ebones(View3D *v3d, ARegion *ar, Object *ob, const short dt)
}
/* restore */
- if (index != -1) glLoadName(-1);
- if (ELEM(arm->drawtype, ARM_LINE, ARM_WIRE)) ;
- else if (dt > OB_WIRE) bglPolygonOffset(rv3d->dist, 0.0f);
+ if (index != -1) {
+ glLoadName(-1);
+ }
+
+ if (ELEM(arm->drawtype, ARM_LINE, ARM_WIRE)) {
+ /* pass */
+ }
+ else if (dt > OB_WIRE) {
+ bglPolygonOffset(rv3d->dist, 0.0f);
+ }
/* finally names and axes */
if (arm->flag & (ARM_DRAWNAMES | ARM_DRAWAXES)) {
@@ -2251,7 +2258,7 @@ static void draw_ebones(View3D *v3d, ARegion *ar, Object *ob, const short dt)
mid_v3_v3v3(vec, eBone->head, eBone->tail);
glRasterPos3fv(vec);
view3d_cached_text_draw_add(vec, eBone->name, 10, 0, col);
- }
+ }
/* Draw additional axes */
if (arm->flag & ARM_DRAWAXES) {
glPushMatrix();
@@ -2636,7 +2643,7 @@ int draw_armature(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
}
draw_pose_paths(scene, v3d, ar, ob);
}
- }
+ }
}
draw_pose_bones(scene, v3d, ar, base, dt, ob_wire_col, (dflag & DRAW_CONSTCOLOR), is_outline);
arm->flag &= ~ARM_POSEMODE;
diff --git a/source/blender/editors/space_view3d/drawmesh.c b/source/blender/editors/space_view3d/drawmesh.c
index ca4f00be2d5..cb5556396dd 100644
--- a/source/blender/editors/space_view3d/drawmesh.c
+++ b/source/blender/editors/space_view3d/drawmesh.c
@@ -373,13 +373,7 @@ static void draw_textured_begin(Scene *scene, View3D *v3d, RegionView3D *rv3d, O
Gtexdraw.ob = ob;
Gtexdraw.is_tex = is_tex;
- /* OCIO_TODO: for now assume OpenGL is always doing color management and working in sRGB space
- * supporting for real display conversion could be nice here, but it's a bit challenging
- * since all the shaders should be aware of such a transform
- * perhaps this flag could be completely removed before release in separated commit and
- * be re-implemented if real display transform would be needed
- */
- Gtexdraw.color_profile = TRUE;
+ Gtexdraw.color_profile = BKE_scene_check_color_management_enabled(scene);
memcpy(Gtexdraw.obcol, obcol, sizeof(obcol));
set_draw_settings_cached(1, NULL, NULL, Gtexdraw);
@@ -388,7 +382,7 @@ static void draw_textured_begin(Scene *scene, View3D *v3d, RegionView3D *rv3d, O
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
}
- else {
+ else {
glDisable(GL_CULL_FACE);
}
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, (me->flag & ME_TWOSIDED) ? GL_TRUE : GL_FALSE);
@@ -412,7 +406,7 @@ static void draw_textured_end(void)
* - zr
*/
glPushMatrix();
- glLoadIdentity();
+ glLoadIdentity();
GPU_default_lights();
glPopMatrix();
}
@@ -539,8 +533,7 @@ static void update_tface_color_layer(DerivedMesh *dm)
}
else {
float col[3];
- Material *ma = give_current_material(Gtexdraw.ob, mface[i].mat_nr + 1);
-
+
if (ma) {
if (Gtexdraw.color_profile) linearrgb_to_srgb_v3_v3(col, &ma->r);
else copy_v3_v3(col, &ma->r);
@@ -638,12 +631,12 @@ static void draw_mesh_text(Scene *scene, Object *ob, int glsl)
MLoopCol *mloopcol = me->mloopcol; /* why does mcol exist? */
MLoopCol *lcol;
- bProperty *prop = get_ob_property(ob, "Text");
+ bProperty *prop = BKE_bproperty_object_get(ob, "Text");
GPUVertexAttribs gattribs;
int a, totpoly = me->totpoly;
/* fake values to pass to GPU_render_text() */
- MCol tmp_mcol[4] = {{0}};
+ MCol tmp_mcol[4] = {{0}};
MCol *tmp_mcol_pt = mloopcol ? tmp_mcol : NULL;
MTFace tmp_tf = {{{0}}};
@@ -710,11 +703,11 @@ static void draw_mesh_text(Scene *scene, Object *ob, int glsl)
/* COLOR */
if (mloopcol) {
- unsigned int totloop_clamp = MIN2(4, mp->totloop);
+ unsigned int totloop_clamp = min_ii(4, mp->totloop);
unsigned int j;
lcol = &mloopcol[mp->loopstart];
- for (j = 0; j <= totloop_clamp; j++, lcol++) {
+ for (j = 0; j < totloop_clamp; j++, lcol++) {
MESH_MLOOPCOL_TO_MCOL(lcol, &tmp_mcol[j]);
}
}
@@ -732,7 +725,7 @@ static void draw_mesh_text(Scene *scene, Object *ob, int glsl)
/* The BM_FONT handling is in the gpu module, shared with the
* game engine, was duplicated previously */
- set_property_valstr(prop, string);
+ BKE_bproperty_set_valstr(prop, string);
characters = strlen(string);
if (!BKE_image_get_ibuf(mtpoly->tpage, NULL))
@@ -832,7 +825,7 @@ static void draw_mesh_textured_old(Scene *scene, View3D *v3d, RegionView3D *rv3d
}
/* draw game engine text hack */
- if (get_ob_property(ob, "Text"))
+ if (BKE_bproperty_object_get(ob, "Text"))
draw_mesh_text(scene, ob, 0);
draw_textured_end();
diff --git a/source/blender/editors/space_view3d/drawobject.c b/source/blender/editors/space_view3d/drawobject.c
index a51ec15bd86..f100f003ff5 100644
--- a/source/blender/editors/space_view3d/drawobject.c
+++ b/source/blender/editors/space_view3d/drawobject.c
@@ -27,10 +27,6 @@
* \ingroup spview3d
*/
-
-#include <string.h>
-#include <math.h>
-
#include "MEM_guardedalloc.h"
#include "DNA_camera_types.h"
@@ -40,21 +36,14 @@
#include "DNA_lattice_types.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
#include "DNA_meta_types.h"
#include "DNA_scene_types.h"
#include "DNA_smoke_types.h"
-#include "DNA_speaker_types.h"
#include "DNA_world_types.h"
-#include "DNA_armature_types.h"
#include "DNA_object_types.h"
-#include "BLI_utildefines.h"
#include "BLI_blenlib.h"
#include "BLI_math.h"
-#include "BLI_edgehash.h"
-#include "BLI_rand.h"
-#include "BLI_utildefines.h"
#include "BKE_anim.h" /* for the where_on_path function */
#include "BKE_armature.h"
@@ -79,13 +68,10 @@
#include "BKE_pointcache.h"
#include "BKE_scene.h"
#include "BKE_unit.h"
-#include "BKE_movieclip.h"
#include "BKE_tracking.h"
#include "BKE_tessmesh.h"
-#include "smoke_API.h"
-
#include "IMB_imbuf.h"
#include "IMB_imbuf_types.h"
@@ -100,15 +86,13 @@
#include "ED_screen.h"
#include "ED_sculpt.h"
#include "ED_types.h"
-#include "ED_curve.h" /* for curve_editnurbs */
#include "UI_resources.h"
#include "WM_api.h"
-#include "wm_subwindow.h"
#include "BLF_api.h"
-#include "view3d_intern.h" /* own include */
+#include "view3d_intern.h" /* bad level include */
typedef enum eWireDrawMode {
OBDRAW_WIRE_OFF = 0,
@@ -116,28 +100,6 @@ typedef enum eWireDrawMode {
OBDRAW_WIRE_ON_DEPTH = 2
} eWireDrawMode;
-/* user data structures for derived mesh callbacks */
-typedef struct foreachScreenVert_userData {
- void (*func)(void *userData, BMVert *eve, int x, int y, int index);
- void *userData;
- ViewContext vc;
- eV3DClipTest clipVerts;
-} foreachScreenVert_userData;
-
-typedef struct foreachScreenEdge_userData {
- void (*func)(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int index);
- void *userData;
- ViewContext vc;
- rcti win_rect; /* copy of: vc.ar->winx/winy, use for faster tests, minx/y will always be 0 */
- eV3DClipTest clipVerts;
-} foreachScreenEdge_userData;
-
-typedef struct foreachScreenFace_userData {
- void (*func)(void *userData, BMFace *efa, int x, int y, int index);
- void *userData;
- ViewContext vc;
-} foreachScreenFace_userData;
-
typedef struct drawDMVerts_userData {
BMEditMesh *em; /* BMESH BRANCH ONLY */
@@ -170,7 +132,8 @@ typedef struct drawDMFacesSel_userData {
BMEditMesh *em; /* BMESH BRANCH ONLY */
BMFace *efa_act;
- int *orig_index;
+ int *orig_index_mf_to_mpoly;
+ int *orig_index_mp_to_orig;
} drawDMFacesSel_userData;
typedef struct drawDMNormal_userData {
@@ -239,107 +202,6 @@ static int check_ob_drawface_dot(Scene *sce, View3D *vd, char dt)
return 1;
}
-/* ************* only use while object drawing **************
- * or after running ED_view3d_init_mats_rv3d
- * */
-static void view3d_project_short_clip(ARegion *ar, const float vec[3], short adr[2], int is_local)
-{
- RegionView3D *rv3d = ar->regiondata;
- float fx, fy, vec4[4];
-
- adr[0] = IS_CLIPPED;
-
- /* clipplanes in eye space */
- if (rv3d->rflag & RV3D_CLIPPING) {
- if (ED_view3d_clipping_test(rv3d, vec, is_local))
- return;
- }
-
- copy_v3_v3(vec4, vec);
- vec4[3] = 1.0;
-
- mul_m4_v4(rv3d->persmatob, vec4);
-
- /* clipplanes in window space */
- if (vec4[3] > (float)BL_NEAR_CLIP) { /* is the NEAR clipping cutoff for picking */
- fx = (ar->winx / 2) * (1 + vec4[0] / vec4[3]);
-
- if (fx > 0 && fx < ar->winx) {
-
- fy = (ar->winy / 2) * (1 + vec4[1] / vec4[3]);
-
- if (fy > 0.0f && fy < (float)ar->winy) {
- adr[0] = (short)floorf(fx);
- adr[1] = (short)floorf(fy);
- }
- }
- }
-}
-
-/* BMESH NOTE: this function is unused in bmesh only */
-
-/* only use while object drawing */
-static void UNUSED_FUNCTION(view3d_project_short_noclip) (ARegion * ar, const float vec[3], short adr[2])
-{
- RegionView3D *rv3d = ar->regiondata;
- float fx, fy, vec4[4];
-
- adr[0] = IS_CLIPPED;
-
- copy_v3_v3(vec4, vec);
- vec4[3] = 1.0;
-
- mul_m4_v4(rv3d->persmatob, vec4);
-
- if (vec4[3] > (float)BL_NEAR_CLIP) { /* is the NEAR clipping cutoff for picking */
- fx = (ar->winx / 2) * (1 + vec4[0] / vec4[3]);
-
- if (fx > -32700 && fx < 32700) {
-
- fy = (ar->winy / 2) * (1 + vec4[1] / vec4[3]);
-
- if (fy > -32700.0f && fy < 32700.0f) {
- adr[0] = (short)floorf(fx);
- adr[1] = (short)floorf(fy);
- }
- }
- }
-}
-
-/* same as view3d_project_short_clip but use persmat instead of persmatob for projection */
-static void view3d_project_short_clip_persmat(ARegion *ar, const float vec[3], short adr[2], int is_local)
-{
- RegionView3D *rv3d = ar->regiondata;
- float fx, fy, vec4[4];
-
- adr[0] = IS_CLIPPED;
-
- /* clipplanes in eye space */
- if (rv3d->rflag & RV3D_CLIPPING) {
- if (ED_view3d_clipping_test(rv3d, vec, is_local))
- return;
- }
-
- copy_v3_v3(vec4, vec);
- vec4[3] = 1.0;
-
- mul_m4_v4(rv3d->persmat, vec4);
-
- /* clipplanes in window space */
- if (vec4[3] > (float)BL_NEAR_CLIP) { /* is the NEAR clipping cutoff for picking */
- fx = (ar->winx / 2) * (1 + vec4[0] / vec4[3]);
-
- if (fx > 0 && fx < ar->winx) {
-
- fy = (ar->winy / 2) * (1 + vec4[1] / vec4[3]);
-
- if (fy > 0.0f && fy < (float)ar->winy) {
- adr[0] = (short)floorf(fx);
- adr[1] = (short)floorf(fy);
- }
- }
- }
-}
/* ************************ */
/* check for glsl drawing */
@@ -372,12 +234,13 @@ static int check_alpha_pass(Base *base)
}
/***/
-static unsigned int colortab[24] =
-{0x0, 0xFF88FF, 0xFFBBFF,
- 0x403000, 0xFFFF88, 0xFFFFBB,
- 0x104040, 0x66CCCC, 0x77CCCC,
- 0x104010, 0x55BB55, 0x66FF66,
- 0xFFFFFF};
+static unsigned int colortab[24] = {
+ 0x0, 0xFF88FF, 0xFFBBFF,
+ 0x403000, 0xFFFF88, 0xFFFFBB,
+ 0x104040, 0x66CCCC, 0x77CCCC,
+ 0x104010, 0x55BB55, 0x66FF66,
+ 0xFFFFFF
+};
static float cube[8][3] = {
@@ -717,7 +580,7 @@ static void draw_empty_image(Object *ob, const short dflag, const unsigned char
glTranslatef(0.0f, 0.0f, 0.0f);
/* Calculate Image scale */
- scale = (ob->empty_drawsize / (float)MAX2(ima_x * sca_x, ima_y * sca_y));
+ scale = (ob->empty_drawsize / max_ff((float)ima_x * sca_x, (float)ima_y * sca_y));
/* Set the object scale */
glScalef(scale * sca_x, scale * sca_y, 1.0f);
@@ -883,13 +746,17 @@ void view3d_cached_text_draw_end(View3D *v3d, ARegion *ar, int depth_write, floa
if (mat && !(vos->flag & V3D_CACHE_TEXT_WORLDSPACE))
mul_m4_v3(mat, vos->vec);
- if (vos->flag & V3D_CACHE_TEXT_GLOBALSPACE)
- view3d_project_short_clip_persmat(ar, vos->vec, vos->sco, (vos->flag & V3D_CACHE_TEXT_LOCALCLIP) != 0);
- else
- view3d_project_short_clip(ar, vos->vec, vos->sco, (vos->flag & V3D_CACHE_TEXT_LOCALCLIP) != 0);
-
- if (vos->sco[0] != IS_CLIPPED)
+ if (ED_view3d_project_short_ex(ar,
+ (vos->flag & V3D_CACHE_TEXT_GLOBALSPACE) ? rv3d->persmat : rv3d->persmatob,
+ (vos->flag & V3D_CACHE_TEXT_LOCALCLIP) != 0,
+ vos->vec, vos->sco,
+ V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN) == V3D_PROJ_RET_OK)
+ {
tot++;
+ }
+ else {
+ vos->sco[0] = IS_CLIPPED;
+ }
}
if (tot) {
@@ -954,7 +821,9 @@ void view3d_cached_text_draw_end(View3D *v3d, ARegion *ar, int depth_write, floa
if (depth_write) {
if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
}
- else glDepthMask(1);
+ else {
+ glDepthMask(1);
+ }
glMatrixMode(GL_PROJECTION);
glPopMatrix();
@@ -996,7 +865,7 @@ static void drawcube(void)
glEnd();
}
-/* draws a cube on given the scaling of the cube, assuming that
+/* draws a cube on given the scaling of the cube, assuming that
* all required matrices have been set (used for drawing empties)
*/
static void drawcube_size(float size)
@@ -1380,8 +1249,10 @@ static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
glVertex3fv(tvec);
glEnd();
}
- else circ(0.0, 0.0, fabsf(z));
-
+ else {
+ circ(0.0, 0.0, fabsf(z));
+ }
+
/* draw the circle/square representing spotbl */
if (la->type == LA_SPOT) {
float spotblcirc = fabs(z) * (1 - pow(la->spotblend, 2));
@@ -1525,7 +1396,7 @@ static void draw_limit_line(float sta, float end, unsigned int col)
glVertex3f(0.0, 0.0, -end);
glEnd();
glPointSize(1.0);
-}
+}
/* yafray: draw camera focus point (cross, similar to aqsis code in tuhopuu) */
@@ -1966,27 +1837,6 @@ static void lattice_draw_verts(Lattice *lt, DispList *dl, short sel)
bglEnd();
}
-void lattice_foreachScreenVert(ViewContext *vc, void (*func)(void *userData, BPoint *bp, int x, int y), void *userData)
-{
- Object *obedit = vc->obedit;
- Lattice *lt = obedit->data;
- BPoint *bp = lt->editlatt->latt->def;
- DispList *dl = BKE_displist_find(&obedit->disp, DL_VERTS);
- float *co = dl ? dl->verts : NULL;
- int i, N = lt->editlatt->latt->pntsu * lt->editlatt->latt->pntsv * lt->editlatt->latt->pntsw;
- short s[2] = {IS_CLIPPED, 0};
-
- ED_view3d_clipping_local(vc->rv3d, obedit->obmat); /* for local clipping lookups */
-
- for (i = 0; i < N; i++, bp++, co += 3) {
- if (bp->hide == 0) {
- view3d_project_short_clip(vc->ar, dl ? co : bp->vec, s, TRUE);
- if (s[0] != IS_CLIPPED)
- func(userData, bp, s[0], s[1]);
- }
- }
-}
-
static void drawlattice__point(Lattice *lt, DispList *dl, int u, int v, int w, int use_wcol)
{
int index = ((w * lt->pntsv + v) * lt->pntsu) + u;
@@ -2073,56 +1923,6 @@ static void drawlattice(Scene *scene, View3D *v3d, Object *ob)
/* ***************** ******************** */
-/* Note! - foreach funcs should be called while drawing or directly after
- * if not, ED_view3d_init_mats_rv3d() can be used for selection tools
- * but would not give correct results with dupli's for eg. which don't
- * use the object matrix in the usual way */
-static void mesh_foreachScreenVert__mapFunc(void *userData, int index, const float co[3],
- const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
-{
- foreachScreenVert_userData *data = userData;
- BMVert *eve = EDBM_vert_at_index(data->vc.em, index);
-
- if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
- short s[2] = {IS_CLIPPED, 0};
-
- if (data->clipVerts != V3D_CLIP_TEST_OFF) {
- view3d_project_short_clip(data->vc.ar, co, s, TRUE);
- }
- else {
- float co2[2];
- mul_v3_m4v3(co2, data->vc.obedit->obmat, co);
- project_short_noclip(data->vc.ar, co2, s);
- }
-
- if (s[0] != IS_CLIPPED)
- data->func(data->userData, eve, s[0], s[1], index);
- }
-}
-
-void mesh_foreachScreenVert(
- ViewContext *vc,
- void (*func)(void *userData, BMVert *eve, int x, int y, int index),
- void *userData, eV3DClipTest clipVerts)
-{
- foreachScreenVert_userData data;
- DerivedMesh *dm = editbmesh_get_derived_cage(vc->scene, vc->obedit, vc->em, CD_MASK_BAREMESH);
-
- data.vc = *vc;
- data.func = func;
- data.userData = userData;
- data.clipVerts = clipVerts;
-
- if (clipVerts != V3D_CLIP_TEST_OFF)
- ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
-
- EDBM_index_arrays_init(vc->em, 1, 0, 0);
- dm->foreachMappedVert(dm, mesh_foreachScreenVert__mapFunc, &data);
- EDBM_index_arrays_free(vc->em);
-
- dm->release(dm);
-}
-
/* draw callback */
static void drawSelectedVertices__mapFunc(void *userData, int index, const float co[3],
const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
@@ -2151,166 +1951,9 @@ static void drawSelectedVertices(DerivedMesh *dm, Mesh *me)
glEnd();
}
-static void mesh_foreachScreenEdge__mapFunc(void *userData, int index, const float v0co[3], const float v1co[3])
-{
- foreachScreenEdge_userData *data = userData;
- BMEdge *eed = EDBM_edge_at_index(data->vc.em, index);
-
- if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
- short s[2][2];
-
- if (data->clipVerts == V3D_CLIP_TEST_RV3D_CLIPPING) {
- view3d_project_short_clip(data->vc.ar, v0co, s[0], TRUE);
- view3d_project_short_clip(data->vc.ar, v1co, s[1], TRUE);
- }
- else {
- float v1_co[3], v2_co[3];
-
- mul_v3_m4v3(v1_co, data->vc.obedit->obmat, v0co);
- mul_v3_m4v3(v2_co, data->vc.obedit->obmat, v1co);
-
- project_short_noclip(data->vc.ar, v1_co, s[0]);
- project_short_noclip(data->vc.ar, v2_co, s[1]);
-
- if (data->clipVerts == V3D_CLIP_TEST_REGION) {
- /* make an int copy */
- int s_int[2][2] = {{s[0][0], s[0][1]},
- {s[1][0], s[1][1]}};
- if (!BLI_rcti_isect_segment(&data->win_rect, s_int[0], s_int[1])) {
- return;
- }
- }
- }
-
- data->func(data->userData, eed, s[0][0], s[0][1], s[1][0], s[1][1], index);
- }
-}
-
-void mesh_foreachScreenEdge(
- ViewContext *vc,
- void (*func)(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int index),
- void *userData, eV3DClipTest clipVerts)
-{
- foreachScreenEdge_userData data;
- DerivedMesh *dm = editbmesh_get_derived_cage(vc->scene, vc->obedit, vc->em, CD_MASK_BAREMESH);
-
- data.vc = *vc;
-
- data.win_rect.xmin = 0;
- data.win_rect.ymin = 0;
- data.win_rect.xmax = vc->ar->winx;
- data.win_rect.ymax = vc->ar->winy;
-
- data.func = func;
- data.userData = userData;
- data.clipVerts = clipVerts;
-
- if (clipVerts != V3D_CLIP_TEST_OFF)
- ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
-
- EDBM_index_arrays_init(vc->em, 0, 1, 0);
- dm->foreachMappedEdge(dm, mesh_foreachScreenEdge__mapFunc, &data);
- EDBM_index_arrays_free(vc->em);
-
- dm->release(dm);
-}
-
-static void mesh_foreachScreenFace__mapFunc(void *userData, int index, const float cent[3], const float UNUSED(no[3]))
-{
- foreachScreenFace_userData *data = userData;
- BMFace *efa = EDBM_face_at_index(data->vc.em, index);
-
- if (efa && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
- float cent2[3];
- short s[2];
-
- mul_v3_m4v3(cent2, data->vc.obedit->obmat, cent);
- project_short(data->vc.ar, cent2, s);
-
- if (s[0] != IS_CLIPPED) {
- data->func(data->userData, efa, s[0], s[1], index);
- }
- }
-}
-
-void mesh_foreachScreenFace(
- ViewContext *vc,
- void (*func)(void *userData, BMFace *efa, int x, int y, int index),
- void *userData)
-{
- foreachScreenFace_userData data;
- DerivedMesh *dm = editbmesh_get_derived_cage(vc->scene, vc->obedit, vc->em, CD_MASK_BAREMESH);
-
- data.vc = *vc;
- data.func = func;
- data.userData = userData;
-
- //if (clipVerts)
- ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
-
- EDBM_index_arrays_init(vc->em, 0, 0, 1);
- dm->foreachMappedFaceCenter(dm, mesh_foreachScreenFace__mapFunc, &data);
- EDBM_index_arrays_free(vc->em);
-
- dm->release(dm);
-}
-
-void nurbs_foreachScreenVert(
- ViewContext *vc,
- void (*func)(void *userData, Nurb *nu, BPoint *bp, BezTriple *bezt, int beztindex, int x, int y),
- void *userData)
-{
- Curve *cu = vc->obedit->data;
- short s[2] = {IS_CLIPPED, 0};
- Nurb *nu;
- int i;
- ListBase *nurbs = BKE_curve_editNurbs_get(cu);
-
- ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
-
- for (nu = nurbs->first; nu; nu = nu->next) {
- if (nu->type == CU_BEZIER) {
- for (i = 0; i < nu->pntsu; i++) {
- BezTriple *bezt = &nu->bezt[i];
-
- if (bezt->hide == 0) {
-
- if (cu->drawflag & CU_HIDE_HANDLES) {
- view3d_project_short_clip(vc->ar, bezt->vec[1], s, TRUE);
- if (s[0] != IS_CLIPPED)
- func(userData, nu, NULL, bezt, 1, s[0], s[1]);
- }
- else {
- view3d_project_short_clip(vc->ar, bezt->vec[0], s, TRUE);
- if (s[0] != IS_CLIPPED)
- func(userData, nu, NULL, bezt, 0, s[0], s[1]);
- view3d_project_short_clip(vc->ar, bezt->vec[1], s, TRUE);
- if (s[0] != IS_CLIPPED)
- func(userData, nu, NULL, bezt, 1, s[0], s[1]);
- view3d_project_short_clip(vc->ar, bezt->vec[2], s, TRUE);
- if (s[0] != IS_CLIPPED)
- func(userData, nu, NULL, bezt, 2, s[0], s[1]);
- }
- }
- }
- }
- else {
- for (i = 0; i < nu->pntsu * nu->pntsv; i++) {
- BPoint *bp = &nu->bp[i];
-
- if (bp->hide == 0) {
- view3d_project_short_clip(vc->ar, bp->vec, s, TRUE);
- if (s[0] != IS_CLIPPED)
- func(userData, nu, bp, NULL, -1, s[0], s[1]);
- }
- }
- }
- }
-}
-
/* ************** DRAW MESH ****************** */
-/* First section is all the "simple" draw routines,
+/* First section is all the "simple" draw routines,
* ones that just pass some sort of primitive to GL,
* with perhaps various options to control lighting,
* color, etc.
@@ -2545,7 +2188,7 @@ static DMDrawOption draw_dm_edges_sel__setDrawOptions(void *userData, int index)
return DM_DRAW_OPTION_SKIP;
}
}
-static void draw_dm_edges_sel(BMEditMesh *em, DerivedMesh *dm, unsigned char *baseCol,
+static void draw_dm_edges_sel(BMEditMesh *em, DerivedMesh *dm, unsigned char *baseCol,
unsigned char *selCol, unsigned char *actCol, BMEdge *eed_act)
{
drawDMEdgesSel_userData data;
@@ -2567,7 +2210,7 @@ static DMDrawOption draw_dm_edges__setDrawOptions(void *userData, int index)
return DM_DRAW_OPTION_NORMAL;
}
-static void draw_dm_edges(BMEditMesh *em, DerivedMesh *dm)
+static void draw_dm_edges(BMEditMesh *em, DerivedMesh *dm)
{
dm->drawMappedEdges(dm, draw_dm_edges__setDrawOptions, em);
}
@@ -2669,11 +2312,11 @@ static int draw_dm_faces_sel__compareDrawOptions(void *userData, int index, int
unsigned char *col, *next_col;
- if (!data->orig_index)
+ if (!data->orig_index_mf_to_mpoly)
return 0;
- efa = EDBM_face_at_index(data->em, data->orig_index[index]);
- next_efa = EDBM_face_at_index(data->em, data->orig_index[next_index]);
+ efa = EDBM_face_at_index(data->em, DM_origindex_mface_mpoly(data->orig_index_mf_to_mpoly, data->orig_index_mp_to_orig, index));
+ next_efa = EDBM_face_at_index(data->em, DM_origindex_mface_mpoly(data->orig_index_mf_to_mpoly, data->orig_index_mp_to_orig, next_index));
if (efa == next_efa)
return 1;
@@ -2691,7 +2334,7 @@ static int draw_dm_faces_sel__compareDrawOptions(void *userData, int index, int
}
/* also draws the active face */
-static void draw_dm_faces_sel(BMEditMesh *em, DerivedMesh *dm, unsigned char *baseCol,
+static void draw_dm_faces_sel(BMEditMesh *em, DerivedMesh *dm, unsigned char *baseCol,
unsigned char *selCol, unsigned char *actCol, BMFace *efa_act)
{
drawDMFacesSel_userData data;
@@ -2701,7 +2344,12 @@ static void draw_dm_faces_sel(BMEditMesh *em, DerivedMesh *dm, unsigned char *ba
data.cols[1] = selCol;
data.cols[2] = actCol;
data.efa_act = efa_act;
- data.orig_index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
+ /* double lookup */
+ data.orig_index_mf_to_mpoly = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
+ data.orig_index_mp_to_orig = DM_get_poly_data_layer(dm, CD_ORIGINDEX);
+ if ((data.orig_index_mf_to_mpoly && data.orig_index_mp_to_orig) == FALSE) {
+ data.orig_index_mf_to_mpoly = data.orig_index_mp_to_orig = NULL;
+ }
dm->drawMappedFaces(dm, draw_dm_faces_sel__setDrawOptions, GPU_enable_material, draw_dm_faces_sel__compareDrawOptions, &data, 0);
}
@@ -2788,9 +2436,9 @@ static void draw_dm_bweights(BMEditMesh *em, Scene *scene, DerivedMesh *dm)
/* EditMesh drawing routines*/
-static void draw_em_fancy_verts(Scene *scene, View3D *v3d, Object *obedit,
+static void draw_em_fancy_verts(Scene *scene, View3D *v3d, Object *obedit,
BMEditMesh *em, DerivedMesh *cageDM, BMVert *eve_act,
- RegionView3D *rv3d)
+ RegionView3D *rv3d)
{
ToolSettings *ts = scene->toolsettings;
int sel;
@@ -2910,7 +2558,7 @@ static void draw_em_fancy_edges(BMEditMesh *em, Scene *scene, View3D *v3d,
glEnable(GL_DEPTH_TEST);
}
}
-}
+}
static void draw_em_measure_stats(View3D *v3d, Object *ob, BMEditMesh *em, UnitSettings *unit)
{
@@ -3175,7 +2823,7 @@ static void draw_em_fancy(Scene *scene, View3D *v3d, RegionView3D *rv3d,
if (ese->type == BM_FACE) {
efa_act = (BMFace *)ese->data;
}
- else
+ else
#endif
if (ese->htype == BM_EDGE) {
eed_act = (BMEdge *)ese->ele;
@@ -3344,13 +2992,12 @@ static void draw_em_fancy(Scene *scene, View3D *v3d, RegionView3D *rv3d,
static void draw_mesh_object_outline(View3D *v3d, Object *ob, DerivedMesh *dm)
{
-
if ((v3d->transp == FALSE) && /* not when we draw the transparent pass */
(ob->mode & OB_MODE_ALL_PAINT) == FALSE) /* not when painting (its distracting) - campbell */
{
glLineWidth(UI_GetThemeValuef(TH_OUTLINE_WIDTH) * 2.0f);
glDepthMask(0);
-
+
/* if transparent, we cannot draw the edges for solid select... edges have no material info.
* drawFacesSolid() doesn't draw the transparent faces */
if (ob->dtx & OB_DRAWTRANSP) {
@@ -3432,7 +3079,7 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
glFrontFace((ob->transflag & OB_NEG_SCALE) ? GL_CW : GL_CCW);
dm->drawFacesGLSL(dm, GPU_enable_material);
-// if (get_ob_property(ob, "Text"))
+// if (BKE_bproperty_object_get(ob, "Text"))
// XXX draw_mesh_text(ob, 1);
GPU_disable_material();
@@ -3620,7 +3267,7 @@ static int draw_mesh_object(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
}
if (obedit && ob != obedit && ob->data == obedit->data) {
- if (ob_get_key(ob) || ob_get_key(obedit)) {}
+ if (BKE_key_from_object(ob) || BKE_key_from_object(obedit)) {}
else if (ob->modifiers.first || obedit->modifiers.first) {}
else drawlinked = 1;
}
@@ -3672,7 +3319,7 @@ static int draw_mesh_object(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
}
}
- if ((dflag & DRAW_PICKING) == 0 && (base->flag & OB_FROMDUPLI) == 0) {
+ if ((dflag & DRAW_PICKING) == 0 && (base->flag & OB_FROMDUPLI) == 0 && (v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
/* GPU_begin_object_materials checked if this is needed */
if (do_alpha_after) {
if (ob->dtx & OB_DRAWXRAY) {
@@ -3795,7 +3442,7 @@ static int drawDispListwire(ListBase *dlbase)
return 0;
}
-static void drawDispListsolid(ListBase *lb, Object *ob,
+static void drawDispListsolid(ListBase *lb, Object *ob, const short dflag,
const unsigned char ob_wire_col[4], int use_glsl)
{
DispList *dl;
@@ -3826,7 +3473,9 @@ static void drawDispListsolid(ListBase *lb, Object *ob,
int nr;
glDisable(GL_LIGHTING);
- glColor3ubv(ob_wire_col);
+
+ if ((dflag & DRAW_CONSTCOLOR) == 0)
+ glColor3ubv(ob_wire_col);
// glVertexPointer(3, GL_FLOAT, 0, dl->verts);
// glDrawArrays(GL_LINE_STRIP, 0, dl->nr);
@@ -3953,7 +3602,7 @@ static int drawCurveDerivedMesh(Scene *scene, View3D *v3d, RegionView3D *rv3d, B
/* returns 1 when nothing was drawn */
static int drawDispList(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
- const short dt, const unsigned char ob_wire_col[4])
+ const short dt, const short dflag, const unsigned char ob_wire_col[4])
{
Object *ob = base->object;
ListBase *lb = NULL;
@@ -4001,12 +3650,12 @@ static int drawDispList(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *bas
else {
if (draw_glsl_material(scene, ob, v3d, dt)) {
GPU_begin_object_materials(v3d, rv3d, scene, ob, 1, NULL);
- drawDispListsolid(lb, ob, ob_wire_col, TRUE);
+ drawDispListsolid(lb, ob, dflag, ob_wire_col, TRUE);
GPU_end_object_materials();
}
else {
GPU_begin_object_materials(v3d, rv3d, scene, ob, 0, NULL);
- drawDispListsolid(lb, ob, ob_wire_col, FALSE);
+ drawDispListsolid(lb, ob, dflag, ob_wire_col, FALSE);
GPU_end_object_materials();
}
if (cu->editnurb && cu->bevobj == NULL && cu->taperobj == NULL && cu->ext1 == 0.0f && cu->ext2 == 0.0f) {
@@ -4038,12 +3687,12 @@ static int drawDispList(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *bas
if (draw_glsl_material(scene, ob, v3d, dt)) {
GPU_begin_object_materials(v3d, rv3d, scene, ob, 1, NULL);
- drawDispListsolid(lb, ob, ob_wire_col, TRUE);
+ drawDispListsolid(lb, ob, dflag, ob_wire_col, TRUE);
GPU_end_object_materials();
}
else {
GPU_begin_object_materials(v3d, rv3d, scene, ob, 0, NULL);
- drawDispListsolid(lb, ob, ob_wire_col, FALSE);
+ drawDispListsolid(lb, ob, dflag, ob_wire_col, FALSE);
GPU_end_object_materials();
}
}
@@ -4062,12 +3711,12 @@ static int drawDispList(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *bas
if (draw_glsl_material(scene, ob, v3d, dt)) {
GPU_begin_object_materials(v3d, rv3d, scene, ob, 1, NULL);
- drawDispListsolid(lb, ob, ob_wire_col, TRUE);
+ drawDispListsolid(lb, ob, dflag, ob_wire_col, TRUE);
GPU_end_object_materials();
}
else {
GPU_begin_object_materials(v3d, rv3d, scene, ob, 0, NULL);
- drawDispListsolid(lb, ob, ob_wire_col, FALSE);
+ drawDispListsolid(lb, ob, dflag, ob_wire_col, FALSE);
GPU_end_object_materials();
}
}
@@ -4785,7 +4434,7 @@ static void draw_new_particle_system(Scene *scene, View3D *v3d, RegionView3D *rv
if (cdata2)
MEM_freeN(cdata2);
- /* cd2= */ /* UNUSED */ cdata2 = NULL;
+ /* cd2 = */ /* UNUSED */ cdata2 = NULL;
glLineWidth(1.0f);
@@ -5580,7 +5229,7 @@ static void draw_editnurb(Object *ob, Nurb *nurb, int sel)
}
static void drawnurb(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base, Nurb *nurb,
- const short dt, const unsigned char ob_wire_col[4])
+ const short dt, const short dflag, const unsigned char ob_wire_col[4])
{
ToolSettings *ts = scene->toolsettings;
Object *ob = base->object;
@@ -5595,7 +5244,7 @@ static void drawnurb(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
UI_GetThemeColor3ubv(TH_WIRE, wire_col);
glColor3ubv(wire_col);
- drawDispList(scene, v3d, rv3d, base, dt, ob_wire_col);
+ drawDispList(scene, v3d, rv3d, base, dt, dflag, ob_wire_col);
if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
@@ -5841,7 +5490,7 @@ static void drawspiral(const float cent[3], float rad, float tmat[][4], int star
glEnd();
}
-/* draws a circle on x-z plane given the scaling of the circle, assuming that
+/* draws a circle on x-z plane given the scaling of the circle, assuming that
* all required matrices have been set (used for drawing empties)
*/
static void drawcircle_size(float size)
@@ -5851,7 +5500,7 @@ static void drawcircle_size(float size)
glBegin(GL_LINE_LOOP);
- /* coordinates are: cos(degrees*11.25)=x, sin(degrees*11.25)=y, 0.0f=z */
+ /* coordinates are: cos(degrees * 11.25) = x, sin(degrees*11.25) = y, 0.0f = z */
for (degrees = 0; degrees < CIRCLE_RESOL; degrees++) {
x = cosval[degrees];
y = sinval[degrees];
@@ -5920,17 +5569,17 @@ static int drawmball(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
if (mb->editelems) {
if ((G.f & G_PICKSEL) == 0) {
- unsigned char wire_col[3];
- UI_GetThemeColor3ubv(TH_WIRE, wire_col);
+ unsigned char wire_col[4];
+ UI_GetThemeColor4ubv(TH_WIRE, wire_col);
glColor3ubv(wire_col);
- drawDispList(scene, v3d, rv3d, base, dt, wire_col);
+ drawDispList(scene, v3d, rv3d, base, dt, dflag, wire_col);
}
ml = mb->editelems->first;
}
else {
if ((base->flag & OB_FROMDUPLI) == 0) {
- drawDispList(scene, v3d, rv3d, base, dt, ob_wire_col);
+ drawDispList(scene, v3d, rv3d, base, dt, dflag, ob_wire_col);
}
ml = mb->elems.first;
}
@@ -6579,7 +6228,7 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
return;
/* xray delay? */
- if ((dflag & DRAW_PICKING) == 0 && (base->flag & OB_FROMDUPLI) == 0) {
+ if ((dflag & DRAW_PICKING) == 0 && (base->flag & OB_FROMDUPLI) == 0 && (v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
/* don't do xray in particle mode, need the z-buffer */
if (!(ob->mode & OB_MODE_PARTICLE_EDIT)) {
/* xray and transp are set when it is drawing the 2nd/3rd pass */
@@ -6614,7 +6263,7 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
/* which wire color */
if ((dflag & DRAW_CONSTCOLOR) == 0) {
- project_short(ar, ob->obmat[3], &base->sx);
+ ED_view3d_project_base(ar, base);
draw_object_wire_color(scene, base, _ob_wire_col, warning_recursive);
ob_wire_col = _ob_wire_col;
@@ -6698,11 +6347,11 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
if (cu->flag & CU_FAST) {
cpack(0xFFFFFF);
set_inverted_drawing(1);
- drawDispList(scene, v3d, rv3d, base, OB_WIRE, ob_wire_col);
+ drawDispList(scene, v3d, rv3d, base, OB_WIRE, dflag, ob_wire_col);
set_inverted_drawing(0);
}
else {
- drawDispList(scene, v3d, rv3d, base, dt, ob_wire_col);
+ drawDispList(scene, v3d, rv3d, base, dt, dflag, ob_wire_col);
}
if (cu->linewidth != 0.0f) {
@@ -6777,7 +6426,7 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
}
}
else if (ED_view3d_boundbox_clip(rv3d, ob->obmat, ob->bb ? ob->bb : cu->bb)) {
- empty_object = drawDispList(scene, v3d, rv3d, base, dt, ob_wire_col);
+ empty_object = drawDispList(scene, v3d, rv3d, base, dt, dflag, ob_wire_col);
}
break;
@@ -6787,7 +6436,7 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
if (cu->editnurb) {
ListBase *nurbs = BKE_curve_editNurbs_get(cu);
- drawnurb(scene, v3d, rv3d, base, nurbs->first, dt, ob_wire_col);
+ drawnurb(scene, v3d, rv3d, base, nurbs->first, dt, dflag, ob_wire_col);
}
else if (dt == OB_BOUNDBOX) {
if (((v3d->flag2 & V3D_RENDER_OVERRIDE) && (v3d->drawtype >= OB_WIRE)) == 0) {
@@ -6795,7 +6444,7 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
}
}
else if (ED_view3d_boundbox_clip(rv3d, ob->obmat, ob->bb ? ob->bb : cu->bb)) {
- empty_object = drawDispList(scene, v3d, rv3d, base, dt, ob_wire_col);
+ empty_object = drawDispList(scene, v3d, rv3d, base, dt, dflag, ob_wire_col);
//XXX old animsys if (cu->path)
// curve_draw_speed(scene, ob);
@@ -6898,7 +6547,6 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
/* code for new particle system */
if ((warning_recursive == 0) &&
(ob->particlesystem.first) &&
- (dflag & DRAW_PICKING) == 0 &&
(ob != scene->obedit)
)
{
@@ -6986,72 +6634,76 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
}
/* only draw domains */
- if (smd->domain && smd->domain->fluid) {
- if (CFRA < smd->domain->point_cache[0]->startframe) {
- /* don't show smoke before simulation starts, this could be made an option in the future */
- }
- else if (!smd->domain->wt || !(smd->domain->viewsettings & MOD_SMOKE_VIEW_SHOWBIG)) {
-// #if 0
- smd->domain->tex = NULL;
- GPU_create_smoke(smd, 0);
- draw_volume(ar, smd->domain->tex,
- smd->domain->p0, smd->domain->p1,
- smd->domain->res, smd->domain->dx,
- smd->domain->tex_shadow);
- GPU_free_smoke(smd);
-// #endif
-#if 0
- int x, y, z;
- float *density = smoke_get_density(smd->domain->fluid);
+ if (smd->domain) {
+ SmokeDomainSettings *sds = smd->domain;
+ float p0[3], p1[3], viewnormal[3];
+ BoundBox bb;
- glLoadMatrixf(rv3d->viewmat);
- // glMultMatrixf(ob->obmat);
+ glLoadMatrixf(rv3d->viewmat);
+ glMultMatrixf(ob->obmat);
- if (col || (ob->flag & SELECT)) cpack(0xFFFFFF);
- glDepthMask(GL_FALSE);
- glEnable(GL_BLEND);
-
+ /* draw adaptive domain bounds */
+ if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
+ /* draw domain max bounds */
+ VECSUBFAC(p0, sds->p0, sds->cell_size, sds->adapt_res);
+ VECADDFAC(p1, sds->p1, sds->cell_size, sds->adapt_res);
+ BKE_boundbox_init_from_minmax(&bb, p0, p1);
+ draw_box(bb.vec);
- // glPointSize(3.0);
- bglBegin(GL_POINTS);
+ /* draw base resolution bounds */
+#if 0
+ BKE_boundbox_init_from_minmax(&bb, sds->p0, sds->p1);
+ draw_box(bb.vec);
+#endif
+ }
- for (x = 0; x < smd->domain->res[0]; x++) {
- for (y = 0; y < smd->domain->res[1]; y++) {
- for (z = 0; z < smd->domain->res[2]; z++) {
- float tmp[3];
- int index = smoke_get_index(x, smd->domain->res[0], y, smd->domain->res[1], z);
-
- if (density[index] > FLT_EPSILON) {
- float color[3];
- copy_v3_v3(tmp, smd->domain->p0);
- tmp[0] += smd->domain->dx * x + smd->domain->dx * 0.5;
- tmp[1] += smd->domain->dx * y + smd->domain->dx * 0.5;
- tmp[2] += smd->domain->dx * z + smd->domain->dx * 0.5;
- color[0] = color[1] = color[2] = density[index];
- glColor3fv(color);
- bglVertex3fv(tmp);
- }
- }
- }
+ /* don't show smoke before simulation starts, this could be made an option in the future */
+ if (smd->domain->fluid && CFRA >= smd->domain->point_cache[0]->startframe) {
+
+ // get view vector
+ copy_v3_v3(viewnormal, rv3d->viewinv[2]);
+ mul_mat3_m4_v3(ob->imat, viewnormal);
+ normalize_v3(viewnormal);
+
+ /* set dynamic boundaries to draw the volume */
+ p0[0] = sds->p0[0] + sds->cell_size[0] * sds->res_min[0] + sds->obj_shift_f[0];
+ p0[1] = sds->p0[1] + sds->cell_size[1] * sds->res_min[1] + sds->obj_shift_f[1];
+ p0[2] = sds->p0[2] + sds->cell_size[2] * sds->res_min[2] + sds->obj_shift_f[2];
+ p1[0] = sds->p0[0] + sds->cell_size[0] * sds->res_max[0] + sds->obj_shift_f[0];
+ p1[1] = sds->p0[1] + sds->cell_size[1] * sds->res_max[1] + sds->obj_shift_f[1];
+ p1[2] = sds->p0[2] + sds->cell_size[2] * sds->res_max[2] + sds->obj_shift_f[2];
+
+ /* scale cube to global space to equalize volume slicing on all axises
+ * (its scaled back before drawing) */
+ mul_v3_v3(p0, ob->size);
+ mul_v3_v3(p1, ob->size);
+
+ if (!sds->wt || !(sds->viewsettings & MOD_SMOKE_VIEW_SHOWBIG)) {
+ smd->domain->tex = NULL;
+ GPU_create_smoke(smd, 0);
+ draw_smoke_volume(sds, ob, sds->tex,
+ p0, p1,
+ sds->res, sds->dx, sds->scale * sds->maxres,
+ viewnormal, sds->tex_shadow, sds->tex_flame);
+ GPU_free_smoke(smd);
+ }
+ else if (sds->wt && (sds->viewsettings & MOD_SMOKE_VIEW_SHOWBIG)) {
+ sds->tex = NULL;
+ GPU_create_smoke(smd, 1);
+ draw_smoke_volume(sds, ob, sds->tex,
+ p0, p1,
+ sds->res_wt, sds->dx, sds->scale * sds->maxres,
+ viewnormal, sds->tex_shadow, sds->tex_flame);
+ GPU_free_smoke(smd);
}
- bglEnd();
- glPointSize(1.0);
-
- glMultMatrixf(ob->obmat);
- glDisable(GL_BLEND);
- glDepthMask(GL_TRUE);
- if (col) cpack(col);
+ /* smoke debug render */
+#ifdef SMOKE_DEBUG_VELOCITY
+ draw_smoke_velocity(smd->domain, ob);
+#endif
+#ifdef SMOKE_DEBUG_HEAT
+ draw_smoke_heat(smd->domain, ob);
#endif
- }
- else if (smd->domain->wt && (smd->domain->viewsettings & MOD_SMOKE_VIEW_SHOWBIG)) {
- smd->domain->tex = NULL;
- GPU_create_smoke(smd, 1);
- draw_volume(ar, smd->domain->tex,
- smd->domain->p0, smd->domain->p1,
- smd->domain->res_wt, smd->domain->dx_wt,
- smd->domain->tex_shadow);
- GPU_free_smoke(smd);
}
}
}
@@ -7140,7 +6792,7 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
}
/* object centers, need to be drawn in viewmat space for speed, but OK for picking select */
- if (!is_obact || !(ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT))) {
+ if (!is_obact || !(ob->mode & OB_MODE_ALL_PAINT)) {
int do_draw_center = -1; /* defines below are zero or positive... */
if (v3d->flag2 & V3D_RENDER_OVERRIDE) {
@@ -7313,7 +6965,7 @@ static void bbs_mesh_verts(BMEditMesh *em, DerivedMesh *dm, int offset)
dm->foreachMappedVert(dm, bbs_mesh_verts__mapFunc, ptrs);
bglEnd();
glPointSize(1.0);
-}
+}
static DMDrawOption bbs_mesh_wire__setDrawOptions(void *userData, int index)
{
@@ -7333,7 +6985,7 @@ static void bbs_mesh_wire(BMEditMesh *em, DerivedMesh *dm, int offset)
{
void *ptrs[2] = {(void *)(intptr_t) offset, em};
dm->drawMappedEdges(dm, bbs_mesh_wire__setDrawOptions, ptrs);
-}
+}
static DMDrawOption bbs_mesh_solid__setSolidDrawOptions(void *userData, int index)
{
@@ -7512,7 +7164,7 @@ void draw_object_backbufsel(Scene *scene, View3D *v3d, RegionView3D *rv3d, Objec
/* assumes all matrices/etc set OK */
/* helper function for drawing object instances - meshes */
-static void draw_object_mesh_instance(Scene *scene, View3D *v3d, RegionView3D *rv3d,
+static void draw_object_mesh_instance(Scene *scene, View3D *v3d, RegionView3D *rv3d,
Object *ob, const short dt, int outline)
{
Mesh *me = ob->data;
diff --git a/source/blender/editors/space_view3d/drawvolume.c b/source/blender/editors/space_view3d/drawvolume.c
index 2c2d4039225..ebb48960b80 100644
--- a/source/blender/editors/space_view3d/drawvolume.c
+++ b/source/blender/editors/space_view3d/drawvolume.c
@@ -36,6 +36,7 @@
#include "DNA_scene_types.h"
#include "DNA_screen_types.h"
+#include "DNA_smoke_types.h"
#include "DNA_view3d_types.h"
#include "BLI_utildefines.h"
@@ -132,7 +133,7 @@ static int intersect_edges(float *points, float a, float b, float c, float d, fl
int i;
float t;
int numpoints = 0;
-
+
for (i = 0; i < 12; i++) {
t = -(a * edges[i][0][0] + b * edges[i][0][1] + c * edges[i][0][2] + d) /
(a * edges[i][1][0] + b * edges[i][1][1] + c * edges[i][1][2]);
@@ -156,12 +157,12 @@ static int convex(const float p0[3], const float up[3], const float a[3], const
return dot_v3v3(up, tmp) >= 0;
}
-void draw_volume(ARegion *ar, GPUTexture *tex, float min[3], float max[3], int res[3], float dx, GPUTexture *tex_shadow)
+void draw_smoke_volume(SmokeDomainSettings *sds, Object *ob,
+ GPUTexture *tex, float min[3], float max[3],
+ int res[3], float dx, float UNUSED(base_scale), float viewnormal[3],
+ GPUTexture *tex_shadow, GPUTexture *tex_flame)
{
- RegionView3D *rv3d = ar->regiondata;
-
- float viewnormal[3];
- int i, j, n, good_index;
+ int i, j, k, n, good_index;
float d /*, d0 */ /* UNUSED */, dd, ds;
float *points = NULL;
int numpoints = 0;
@@ -193,25 +194,76 @@ void draw_volume(ARegion *ar, GPUTexture *tex, float min[3], float max[3], int r
{{-1.0f, 1.0f, -1.0f}, {2.0f, 0.0f, 0.0f}}
};
+ unsigned char *spec_data;
+ float *spec_pixels;
+ GPUTexture *tex_spec;
+
/* Fragment program to calculate the view3d of smoke */
- /* using 2 textures, density and shadow */
- const char *text = "!!ARBfp1.0\n"
- "PARAM dx = program.local[0];\n"
- "PARAM darkness = program.local[1];\n"
- "PARAM f = {1.442695041, 1.442695041, 1.442695041, 0.01};\n"
- "TEMP temp, shadow, value;\n"
- "TEX temp, fragment.texcoord[0], texture[0], 3D;\n"
- "TEX shadow, fragment.texcoord[0], texture[1], 3D;\n"
- "MUL value, temp, darkness;\n"
- "MUL value, value, dx;\n"
- "MUL value, value, f;\n"
- "EX2 temp, -value.r;\n"
- "SUB temp.a, 1.0, temp.r;\n"
- "MUL temp.r, temp.r, shadow.r;\n"
- "MUL temp.g, temp.g, shadow.r;\n"
- "MUL temp.b, temp.b, shadow.r;\n"
- "MOV result.color, temp;\n"
- "END\n";
+ /* using 4 textures, density, shadow, flame and flame spectrum */
+ const char *shader_basic =
+ "!!ARBfp1.0\n"
+ "PARAM dx = program.local[0];\n"
+ "PARAM darkness = program.local[1];\n"
+ "PARAM render = program.local[2];\n"
+ "PARAM f = {1.442695041, 1.442695041, 1.442695041, 0.01};\n"
+ "TEMP temp, shadow, flame, spec, value;\n"
+ "TEX temp, fragment.texcoord[0], texture[0], 3D;\n"
+ "TEX shadow, fragment.texcoord[0], texture[1], 3D;\n"
+ "TEX flame, fragment.texcoord[0], texture[2], 3D;\n"
+ "TEX spec, flame.r, texture[3], 1D;\n"
+ /* calculate shading factor from density */
+ "MUL value.r, temp.a, darkness.a;\n"
+ "MUL value.r, value.r, dx.r;\n"
+ "MUL value.r, value.r, f.r;\n"
+ "EX2 temp, -value.r;\n"
+ /* alpha */
+ "SUB temp.a, 1.0, temp.r;\n"
+ /* shade colors */
+ "MUL temp.r, temp.r, shadow.r;\n"
+ "MUL temp.g, temp.g, shadow.r;\n"
+ "MUL temp.b, temp.b, shadow.r;\n"
+ "MUL temp.r, temp.r, darkness.r;\n"
+ "MUL temp.g, temp.g, darkness.g;\n"
+ "MUL temp.b, temp.b, darkness.b;\n"
+ /* for now this just replace smoke shading if rendering fire */
+ "CMP result.color, render.r, temp, spec;\n"
+ "END\n";
+
+ /* color shader */
+ const char *shader_color =
+ "!!ARBfp1.0\n"
+ "PARAM dx = program.local[0];\n"
+ "PARAM darkness = program.local[1];\n"
+ "PARAM render = program.local[2];\n"
+ "PARAM f = {1.442695041, 1.442695041, 1.442695041, 1.442695041};\n"
+ "TEMP temp, shadow, flame, spec, value;\n"
+ "TEX temp, fragment.texcoord[0], texture[0], 3D;\n"
+ "TEX shadow, fragment.texcoord[0], texture[1], 3D;\n"
+ "TEX flame, fragment.texcoord[0], texture[2], 3D;\n"
+ "TEX spec, flame.r, texture[3], 1D;\n"
+ /* unpremultiply volume texture */
+ "RCP value.r, temp.a;\n"
+ "MUL temp.r, temp.r, value.r;\n"
+ "MUL temp.g, temp.g, value.r;\n"
+ "MUL temp.b, temp.b, value.r;\n"
+ /* calculate shading factor from density */
+ "MUL value.r, temp.a, darkness.a;\n"
+ "MUL value.r, value.r, dx.r;\n"
+ "MUL value.r, value.r, f.r;\n"
+ "EX2 value.r, -value.r;\n"
+ /* alpha */
+ "SUB temp.a, 1.0, value.r;\n"
+ /* shade colors */
+ "MUL temp.r, temp.r, shadow.r;\n"
+ "MUL temp.g, temp.g, shadow.r;\n"
+ "MUL temp.b, temp.b, shadow.r;\n"
+ "MUL temp.r, temp.r, value.r;\n"
+ "MUL temp.g, temp.g, value.r;\n"
+ "MUL temp.b, temp.b, value.r;\n"
+ /* for now this just replace smoke shading if rendering fire */
+ "CMP result.color, render.r, temp, spec;\n"
+ "END\n";
+
GLuint prog;
@@ -223,6 +275,33 @@ void draw_volume(ARegion *ar, GPUTexture *tex, float min[3], float max[3], int r
}
tstart();
+ /* generate flame spectrum texture */
+ #define SPEC_WIDTH 256
+ #define FIRE_THRESH 7
+ #define MAX_FIRE_ALPHA 0.06f
+ #define FULL_ON_FIRE 100
+ spec_data = malloc(SPEC_WIDTH * 4 * sizeof(unsigned char));
+ flame_get_spectrum(spec_data, SPEC_WIDTH, 1500, 3000);
+ spec_pixels = malloc(SPEC_WIDTH * 4 * 16 * 16 * sizeof(float));
+ for (i = 0; i < 16; i++) {
+ for (j = 0; j < 16; j++) {
+ for (k = 0; k < SPEC_WIDTH; k++) {
+ int index = (j * SPEC_WIDTH * 16 + i * SPEC_WIDTH + k) * 4;
+ if (k >= FIRE_THRESH) {
+ spec_pixels[index] = ((float)spec_data[k * 4]) / 255.0f;
+ spec_pixels[index + 1] = ((float)spec_data[k * 4 + 1]) / 255.0f;
+ spec_pixels[index + 2] = ((float)spec_data[k * 4 + 2]) / 255.0f;
+ spec_pixels[index + 3] = MAX_FIRE_ALPHA * (
+ (k > FULL_ON_FIRE) ? 1.0f : (k - FIRE_THRESH) / ((float)FULL_ON_FIRE - FIRE_THRESH));
+ }
+ else {
+ spec_pixels[index] = spec_pixels[index + 1] = spec_pixels[index + 2] = spec_pixels[index + 3] = 0.0f;
+ }
+ }
+ }
+ }
+
+ tex_spec = GPU_texture_create_1D(SPEC_WIDTH, spec_pixels, NULL);
sub_v3_v3v3(size, max, min);
@@ -296,32 +375,17 @@ void draw_volume(ARegion *ar, GPUTexture *tex, float min[3], float max[3], int r
glGetBooleanv(GL_BLEND, (GLboolean *)&gl_blend);
glGetBooleanv(GL_DEPTH_TEST, (GLboolean *)&gl_depth);
- glLoadMatrixf(rv3d->viewmat);
- // glMultMatrixf(ob->obmat);
-
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-
-#if 0
- printf("Viewinv:\n");
- printf("%f, %f, %f\n", rv3d->viewinv[0][0], rv3d->viewinv[0][1], rv3d->viewinv[0][2]);
- printf("%f, %f, %f\n", rv3d->viewinv[1][0], rv3d->viewinv[1][1], rv3d->viewinv[1][2]);
- printf("%f, %f, %f\n", rv3d->viewinv[2][0], rv3d->viewinv[2][1], rv3d->viewinv[2][2]);
-#endif
-
- /* get view vector */
- copy_v3_v3(viewnormal, rv3d->viewinv[2]);
- normalize_v3(viewnormal);
/* find cube vertex that is closest to the viewer */
for (i = 0; i < 8; i++) {
float x, y, z;
- x = cv[i][0] - viewnormal[0]*size[0]*0.5f;
- y = cv[i][1] - viewnormal[1]*size[1]*0.5f;
- z = cv[i][2] - viewnormal[2]*size[2]*0.5f;
+ x = cv[i][0] - viewnormal[0] * size[0] * 0.5f;
+ y = cv[i][1] - viewnormal[1] * size[1] * 0.5f;
+ z = cv[i][2] - viewnormal[2] * size[2] * 0.5f;
if ((x >= min[0]) && (x <= max[0]) &&
(y >= min[1]) && (y <= max[1]) &&
@@ -344,12 +408,19 @@ void draw_volume(ARegion *ar, GPUTexture *tex, float min[3], float max[3], int r
glGenProgramsARB(1, &prog);
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prog);
- glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen(text), text);
+ /* set shader */
+ if (sds->active_fields & SM_ACTIVE_COLORS)
+ glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen(shader_color), shader_color);
+ else
+ glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen(shader_basic), shader_basic);
/* cell spacing */
glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 0, dx, dx, dx, 1.0);
/* custom parameter for smoke style (higher = thicker) */
- glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 1, 7.0, 7.0, 7.0, 1.0);
+ if (sds->active_fields & SM_ACTIVE_COLORS)
+ glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 1, 1.0, 1.0, 1.0, 10.0);
+ else
+ glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 1, sds->active_color[0], sds->active_color[1], sds->active_color[2], 10.0);
}
else
printf("Your gfx card does not support 3D View smoke drawing.\n");
@@ -360,6 +431,11 @@ void draw_volume(ARegion *ar, GPUTexture *tex, float min[3], float max[3], int r
else
printf("No volume shadow\n");
+ if (tex_flame) {
+ GPU_texture_bind(tex_flame, 2);
+ GPU_texture_bind(tex_spec, 3);
+ }
+
if (!GPU_non_power_of_two_support()) {
cor[0] = (float)res[0] / (float)power_of_2_max_i(res[0]);
cor[1] = (float)res[1] / (float)power_of_2_max_i(res[1]);
@@ -373,7 +449,7 @@ void draw_volume(ARegion *ar, GPUTexture *tex, float min[3], float max[3], int r
/* d0 = (viewnormal[0]*cv[i][0] + viewnormal[1]*cv[i][1] + viewnormal[2]*cv[i][2]); */ /* UNUSED */
ds = (ABS(viewnormal[0]) * size[0] + ABS(viewnormal[1]) * size[1] + ABS(viewnormal[2]) * size[2]);
- dd = ds / 96.f;
+ dd = MAX3(sds->global_size[0], sds->global_size[1], sds->global_size[2]) / 128.f;
n = 0;
good_index = i;
@@ -416,14 +492,29 @@ void draw_volume(ARegion *ar, GPUTexture *tex, float min[3], float max[3], int r
}
}
- // printf("numpoints: %d\n", numpoints);
+ /* render fire slice */
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
+ glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 2, 1.0, 0.0, 0.0, 0.0);
+ glBegin(GL_POLYGON);
+ glColor3f(1.0, 1.0, 1.0);
+ for (i = 0; i < numpoints; i++) {
+ glTexCoord3d((points[i * 3 + 0] - min[0]) * cor[0] / size[0],
+ (points[i * 3 + 1] - min[1]) * cor[1] / size[1],
+ (points[i * 3 + 2] - min[2]) * cor[2] / size[2]);
+ glVertex3f(points[i * 3 + 0] / ob->size[0], points[i * 3 + 1] / ob->size[1], points[i * 3 + 2] / ob->size[2]);
+ }
+ glEnd();
+
+ /* render smoke slice */
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 2, -1.0, 0.0, 0.0, 0.0);
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
for (i = 0; i < numpoints; i++) {
glTexCoord3d((points[i * 3 + 0] - min[0]) * cor[0] / size[0],
(points[i * 3 + 1] - min[1]) * cor[1] / size[1],
(points[i * 3 + 2] - min[2]) * cor[2] / size[2]);
- glVertex3f(points[i * 3 + 0], points[i * 3 + 1], points[i * 3 + 2]);
+ glVertex3f(points[i * 3 + 0] / ob->size[0], points[i * 3 + 1] / ob->size[1], points[i * 3 + 2] / ob->size[2]);
}
glEnd();
}
@@ -436,6 +527,14 @@ void draw_volume(ARegion *ar, GPUTexture *tex, float min[3], float max[3], int r
if (tex_shadow)
GPU_texture_unbind(tex_shadow);
GPU_texture_unbind(tex);
+ if (tex_flame) {
+ GPU_texture_unbind(tex_flame);
+ GPU_texture_unbind(tex_spec);
+ }
+ GPU_texture_free(tex_spec);
+
+ free(spec_data);
+ free(spec_pixels);
if (GLEW_ARB_fragment_program) {
glDisable(GL_FRAGMENT_PROGRAM_ARB);
@@ -451,6 +550,109 @@ void draw_volume(ARegion *ar, GPUTexture *tex, float min[3], float max[3], int r
if (gl_depth) {
glEnable(GL_DEPTH_TEST);
- glDepthMask(GL_TRUE);
+ glDepthMask(GL_TRUE);
}
}
+
+#ifdef SMOKE_DEBUG_VELOCITY
+void draw_smoke_velocity(SmokeDomainSettings *domain, Object *ob)
+{
+ float x, y, z;
+ float x0, y0, z0;
+ int *base_res = domain->base_res;
+ int *res = domain->res;
+ int *res_min = domain->res_min;
+ int *res_max = domain->res_max;
+ float *vel_x = smoke_get_velocity_x(domain->fluid);
+ float *vel_y = smoke_get_velocity_y(domain->fluid);
+ float *vel_z = smoke_get_velocity_z(domain->fluid);
+
+ float min[3];
+ float *cell_size = domain->cell_size;
+ float step_size = ((float)MAX3(base_res[0], base_res[1], base_res[2])) / 16.f;
+ float vf = domain->scale / 16.f * 2.f; /* velocity factor */
+
+ glLineWidth(1.0f);
+
+ /* set first position so that it doesn't jump when domain moves */
+ x0 = res_min[0] + fmod(-(float)domain->shift[0] + res_min[0], step_size);
+ y0 = res_min[1] + fmod(-(float)domain->shift[1] + res_min[1], step_size);
+ z0 = res_min[2] + fmod(-(float)domain->shift[2] + res_min[2], step_size);
+ if (x0 < res_min[0]) x0 += step_size;
+ if (y0 < res_min[1]) y0 += step_size;
+ if (z0 < res_min[2]) z0 += step_size;
+ add_v3_v3v3(min, domain->p0, domain->obj_shift_f);
+
+ for (x = floor(x0); x < res_max[0]; x += step_size)
+ for (y = floor(y0); y < res_max[1]; y += step_size)
+ for (z = floor(z0); z < res_max[2]; z += step_size) {
+ int index = (floor(x) - res_min[0]) + (floor(y) - res_min[1]) * res[0] + (floor(z) - res_min[2]) * res[0] * res[1];
+
+ float pos[3] = {min[0] + ((float)x + 0.5f) * cell_size[0], min[1] + ((float)y + 0.5f) * cell_size[1], min[2] + ((float)z + 0.5f) * cell_size[2]};
+ float vel = sqrtf(vel_x[index] * vel_x[index] + vel_y[index] * vel_y[index] + vel_z[index] * vel_z[index]);
+
+ /* draw heat as scaled "arrows" */
+ if (vel >= 0.01f) {
+ float col_g = 1.0f - vel;
+ CLAMP(col_g, 0.0f, 1.0f);
+ glColor3f(1.0f, col_g, 0.0f);
+ glPointSize(10.0f * vel);
+
+ glBegin(GL_LINES);
+ glVertex3f(pos[0], pos[1], pos[2]);
+ glVertex3f(pos[0] + vel_x[index] * vf, pos[1] + vel_y[index] * vf, pos[2] + vel_z[index] * vf);
+ glEnd();
+ glBegin(GL_POINTS);
+ glVertex3f(pos[0] + vel_x[index] * vf, pos[1] + vel_y[index] * vf, pos[2] + vel_z[index] * vf);
+ glEnd();
+ }
+ }
+}
+#endif
+
+#ifdef SMOKE_DEBUG_HEAT
+void draw_smoke_heat(SmokeDomainSettings *domain, Object *ob)
+{
+ float x, y, z;
+ float x0, y0, z0;
+ int *base_res = domain->base_res;
+ int *res = domain->res;
+ int *res_min = domain->res_min;
+ int *res_max = domain->res_max;
+ float *heat = smoke_get_heat(domain->fluid);
+
+ float min[3];
+ float *cell_size = domain->cell_size;
+ float step_size = ((float)MAX3(base_res[0], base_res[1], base_res[2])) / 16.f;
+ float vf = domain->scale / 16.f * 2.f; /* velocity factor */
+
+ /* set first position so that it doesn't jump when domain moves */
+ x0 = res_min[0] + fmod(-(float)domain->shift[0] + res_min[0], step_size);
+ y0 = res_min[1] + fmod(-(float)domain->shift[1] + res_min[1], step_size);
+ z0 = res_min[2] + fmod(-(float)domain->shift[2] + res_min[2], step_size);
+ if (x0 < res_min[0]) x0 += step_size;
+ if (y0 < res_min[1]) y0 += step_size;
+ if (z0 < res_min[2]) z0 += step_size;
+ add_v3_v3v3(min, domain->p0, domain->obj_shift_f);
+
+ for (x = floor(x0); x < res_max[0]; x += step_size)
+ for (y = floor(y0); y < res_max[1]; y += step_size)
+ for (z = floor(z0); z < res_max[2]; z += step_size) {
+ int index = (floor(x) - res_min[0]) + (floor(y) - res_min[1]) * res[0] + (floor(z) - res_min[2]) * res[0] * res[1];
+
+ float pos[3] = {min[0] + ((float)x + 0.5f) * cell_size[0], min[1] + ((float)y + 0.5f) * cell_size[1], min[2] + ((float)z + 0.5f) * cell_size[2]};
+
+ /* draw heat as different sized points */
+ if (heat[index] >= 0.01f) {
+ float col_gb = 1.0f - heat[index];
+ CLAMP(col_gb, 0.0f, 1.0f);
+ glColor3f(1.0f, col_gb, col_gb);
+ glPointSize(24.0f * heat[index]);
+
+ glBegin(GL_POINTS);
+ glVertex3f(pos[0], pos[1], pos[2]);
+ glEnd();
+ }
+ }
+}
+#endif
diff --git a/source/blender/editors/space_view3d/space_view3d.c b/source/blender/editors/space_view3d/space_view3d.c
index 1e371cb074d..6818c78bbd6 100644
--- a/source/blender/editors/space_view3d/space_view3d.c
+++ b/source/blender/editors/space_view3d/space_view3d.c
@@ -185,7 +185,7 @@ int ED_view3d_context_user_region(bContext *C, View3D **v3d_r, ARegion **ar_r)
ar_unlock_user = ar;
break;
}
- }
+ }
}
}
@@ -719,7 +719,7 @@ static void view3d_main_area_listener(ARegion *ar, wmNotifier *wmn)
case NC_BRUSH:
if (wmn->action == NA_EDITED)
ED_region_tag_redraw_overlay(ar);
- break;
+ break;
case NC_MATERIAL:
switch (wmn->data) {
case ND_SHADING_DRAW:
@@ -748,12 +748,12 @@ static void view3d_main_area_listener(ARegion *ar, wmNotifier *wmn)
break;
}
break;
- case NC_IMAGE:
+ case NC_IMAGE:
/* this could be more fine grained checks if we had
* more context than just the region */
ED_region_tag_redraw(ar);
break;
- case NC_TEXTURE:
+ case NC_TEXTURE:
/* same as above */
ED_region_tag_redraw(ar);
break;
@@ -776,7 +776,6 @@ static void view3d_main_area_listener(ARegion *ar, wmNotifier *wmn)
break;
case NC_SCREEN:
switch (wmn->data) {
- case ND_GPENCIL:
case ND_ANIMPLAY:
case ND_SKETCH:
ED_region_tag_redraw(ar);
@@ -793,6 +792,10 @@ static void view3d_main_area_listener(ARegion *ar, wmNotifier *wmn)
}
break;
+ case NC_GPENCIL:
+ if (wmn->action == NA_EDITED)
+ ED_region_tag_redraw(ar);
+ break;
}
}
@@ -879,7 +882,7 @@ static void view3d_buttons_area_listener(ARegion *ar, wmNotifier *wmn)
case ND_KEYFRAME:
if (wmn->action == NA_EDITED)
ED_region_tag_redraw(ar);
- break;
+ break;
}
break;
case NC_SCENE:
@@ -941,8 +944,8 @@ static void view3d_buttons_area_listener(ARegion *ar, wmNotifier *wmn)
if (wmn->action == NA_RENAME)
ED_region_tag_redraw(ar);
break;
- case NC_SCREEN:
- if (wmn->data == ND_GPENCIL)
+ case NC_GPENCIL:
+ if (wmn->data == ND_DATA)
ED_region_tag_redraw(ar);
break;
}
diff --git a/source/blender/editors/space_view3d/view3d_buttons.c b/source/blender/editors/space_view3d/view3d_buttons.c
index c819637fd04..bf14d915412 100644
--- a/source/blender/editors/space_view3d/view3d_buttons.c
+++ b/source/blender/editors/space_view3d/view3d_buttons.c
@@ -83,17 +83,18 @@
/* ******************* view3d space & buttons ************** */
-#define B_NOP 1
#define B_REDR 2
#define B_OBJECTPANELMEDIAN 1008
+#define NBR_TRANSFORM_PROPERTIES 7
+
/* temporary struct for storing transform properties */
typedef struct {
float ob_eul[4]; /* used for quat too... */
float ob_scale[3]; /* need temp space due to linked values */
float ob_dims[3];
short link_scale;
- float ve_median[9];
+ float ve_median[NBR_TRANSFORM_PROPERTIES];
int curdef;
float *defweightp;
} TransformProperties;
@@ -132,17 +133,38 @@ static float compute_scale_factor(const float ve_median, const float median)
/* is used for both read and write... */
static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float lim)
{
+/* Get rid of those ugly magic numbers, even in a single func they become confusing! */
+/* Location, common to all. */
+/* XXX Those two *must* remain contiguous (used as array)! */
+#define LOC_X 0
+#define LOC_Y 1
+#define LOC_Z 2
+/* Meshes... */
+#define M_CREASE 3
+#define M_WEIGHT 4
+/* XXX Those two *must* remain contiguous (used as array)! */
+#define M_SKIN_X 5
+#define M_SKIN_Y 6
+/* Curves... */
+#define C_BWEIGHT 3
+#define C_WEIGHT 4
+#define C_RADIUS 5
+#define C_TILT 6
+/*Lattice... */
+#define L_WEIGHT 4
+
uiBlock *block = (layout) ? uiLayoutAbsoluteBlock(layout) : NULL;
MDeformVert *dvert = NULL;
TransformProperties *tfp;
- float median[9], ve_median[9];
- int tot, totw, totweight, totedge, totradius, totskinradius;
+ float median[NBR_TRANSFORM_PROPERTIES], ve_median[NBR_TRANSFORM_PROPERTIES];
+ int tot, totedgedata, totcurvedata, totlattdata, totskinradius, totcurvebweight;
+ int meshdata = FALSE;
char defstr[320];
- PointerRNA radius_ptr;
+ PointerRNA data_ptr;
- median[0] = median[1] = median[2] = median[3] = median[4] = median[5] = median[6] = median[7] = median[8] = 0.0;
- tot = totw = totweight = totedge = totradius = totskinradius = 0;
- defstr[0] = 0;
+ fill_vn_fl(median, NBR_TRANSFORM_PROPERTIES, 0.0f);
+ tot = totedgedata = totcurvedata = totlattdata = totskinradius = totcurvebweight = 0;
+ defstr[0] = '\0';
/* make sure we got storage */
if (v3d->properties_storage == NULL)
@@ -163,11 +185,11 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
evedef = eve;
tot++;
- add_v3_v3(median, eve->co);
+ add_v3_v3(&median[LOC_X], eve->co);
vs = (MVertSkin *)CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_MVERT_SKIN);
if (vs) {
- add_v2_v2(median + 7, vs->radius); /* Third val not used currently. */
+ add_v2_v2(&median[M_SKIN_X], vs->radius); /* Third val not used currently. */
totskinradius++;
}
}
@@ -177,12 +199,12 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
float *f;
- totedge++;
+ totedgedata++;
f = (float *)CustomData_bmesh_get(&bm->edata, eed->head.data, CD_CREASE);
- median[3] += f ? *f : 0.0f;
+ median[M_CREASE] += f ? *f : 0.0f;
f = (float *)CustomData_bmesh_get(&bm->edata, eed->head.data, CD_BWEIGHT);
- median[6] += f ? *f : 0.0f;
+ median[M_WEIGHT] += f ? *f : 0.0f;
}
}
@@ -212,6 +234,8 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
tfp->defweightp = &dvert->dw[0].weight;
}
}
+
+ meshdata = totedgedata || totskinradius;
}
else if (ob->type == OB_CURVE || ob->type == OB_SURF) {
Curve *cu = ob->data;
@@ -230,22 +254,24 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
a = nu->pntsu;
while (a--) {
if (bezt->f2 & SELECT) {
- add_v3_v3(median, bezt->vec[1]);
+ add_v3_v3(&median[LOC_X], bezt->vec[1]);
tot++;
- median[4] += bezt->weight;
- totweight++;
- median[5] += bezt->radius;
- totradius++;
- selp = bezt;
- seltype = &RNA_BezierSplinePoint;
+ median[C_WEIGHT] += bezt->weight;
+ median[C_RADIUS] += bezt->radius;
+ median[C_TILT] += bezt->alfa;
+ if (!totcurvedata) { /* I.e. first time... */
+ selp = bezt;
+ seltype = &RNA_BezierSplinePoint;
+ }
+ totcurvedata++;
}
else {
if (bezt->f1 & SELECT) {
- add_v3_v3(median, bezt->vec[0]);
+ add_v3_v3(&median[LOC_X], bezt->vec[0]);
tot++;
}
if (bezt->f3 & SELECT) {
- add_v3_v3(median, bezt->vec[2]);
+ add_v3_v3(&median[LOC_X], bezt->vec[2]);
tot++;
}
}
@@ -257,16 +283,18 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
a = nu->pntsu * nu->pntsv;
while (a--) {
if (bp->f1 & SELECT) {
- add_v3_v3(median, bp->vec);
- median[3] += bp->vec[3];
- totw++;
+ add_v3_v3(&median[LOC_X], bp->vec);
+ median[C_BWEIGHT] += bp->vec[3];
+ totcurvebweight++;
tot++;
- median[4] += bp->weight;
- totweight++;
- median[5] += bp->radius;
- totradius++;
- selp = bp;
- seltype = &RNA_SplinePoint;
+ median[C_WEIGHT] += bp->weight;
+ median[C_RADIUS] += bp->radius;
+ median[C_TILT] += bp->alfa;
+ if (!totcurvedata) { /* I.e. first time... */
+ selp = bp;
+ seltype = &RNA_SplinePoint;
+ }
+ totcurvedata++;
}
bp++;
}
@@ -274,84 +302,102 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
nu = nu->next;
}
- if (totradius == 1)
- RNA_pointer_create(&cu->id, seltype, selp, &radius_ptr);
+ if (totcurvedata == 1)
+ RNA_pointer_create(&cu->id, seltype, selp, &data_ptr);
}
else if (ob->type == OB_LATTICE) {
Lattice *lt = ob->data;
BPoint *bp;
int a;
+ StructRNA *seltype = NULL;
+ void *selp = NULL;
a = lt->editlatt->latt->pntsu * lt->editlatt->latt->pntsv * lt->editlatt->latt->pntsw;
bp = lt->editlatt->latt->def;
while (a--) {
if (bp->f1 & SELECT) {
- add_v3_v3(median, bp->vec);
+ add_v3_v3(&median[LOC_X], bp->vec);
tot++;
- median[4] += bp->weight;
- totweight++;
+ median[L_WEIGHT] += bp->weight;
+ if (!totlattdata) { /* I.e. first time... */
+ selp = bp;
+ seltype = &RNA_LatticePoint;
+ }
+ totlattdata++;
}
bp++;
}
+
+ if (totlattdata == 1)
+ RNA_pointer_create(&lt->id, seltype, selp, &data_ptr);
}
if (tot == 0) {
uiDefBut(block, LABEL, 0, IFACE_("Nothing selected"), 0, 130, 200, 20, NULL, 0, 0, 0, 0, "");
return;
}
- median[0] /= (float)tot;
- median[1] /= (float)tot;
- median[2] /= (float)tot;
- if (totedge) {
- median[3] /= (float)totedge;
- median[6] /= (float)totedge;
- }
- else if (totw)
- median[3] /= (float)totw;
- if (totweight)
- median[4] /= (float)totweight;
- if (totradius)
- median[5] /= (float)totradius;
- if (totskinradius) {
- median[7] /= (float)totskinradius;
- median[8] /= (float)totskinradius;
- }
+ /* Location, X/Y/Z */
+ mul_v3_fl(&median[LOC_X], 1.0f / (float)tot);
if (v3d->flag & V3D_GLOBAL_STATS)
- mul_m4_v3(ob->obmat, median);
+ mul_m4_v3(ob->obmat, &median[LOC_X]);
+
+ if (meshdata) {
+ if (totedgedata) {
+ median[M_CREASE] /= (float)totedgedata;
+ median[M_WEIGHT] /= (float)totedgedata;
+ }
+ if (totskinradius) {
+ median[M_SKIN_X] /= (float)totskinradius;
+ median[M_SKIN_Y] /= (float)totskinradius;
+ }
+ }
+ else if (totcurvedata) {
+ median[C_WEIGHT] /= (float)totcurvedata;
+ median[C_RADIUS] /= (float)totcurvedata;
+ median[C_TILT] /= (float)totcurvedata;
+ if (totcurvebweight)
+ median[C_BWEIGHT] /= (float)totcurvebweight;
+ }
+ else if (totlattdata)
+ median[L_WEIGHT] /= (float)totlattdata;
if (block) { /* buttons */
uiBut *but;
int yi = 200;
const int buth = 20 * UI_DPI_ICON_FAC;
const int but_margin = 2;
+ const char *c;
memcpy(tfp->ve_median, median, sizeof(tfp->ve_median));
uiBlockBeginAlign(block);
if (tot == 1) {
- uiDefBut(block, LABEL, 0, IFACE_("Vertex:"), 0, yi -= buth, 200, buth, NULL, 0, 0, 0, 0, "");
- }
- else {
- uiDefBut(block, LABEL, 0, IFACE_("Median:"), 0, yi -= buth, 200, buth, NULL, 0, 0, 0, 0, "");
+ if (totcurvedata) /* Curve */
+ c = IFACE_("Control Point:");
+ else /* Mesh or lattice */
+ c = IFACE_("Vertex:");
}
+ else
+ c = IFACE_("Median:");
+ uiDefBut(block, LABEL, 0, c, 0, yi -= buth, 200, buth, NULL, 0, 0, 0, 0, "");
uiBlockBeginAlign(block);
/* Should be no need to translate these. */
but = uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "X:", 0, yi -= buth, 200, buth,
- &(tfp->ve_median[0]), -lim, lim, 10, RNA_TRANSLATION_PREC_DEFAULT, "");
+ &(tfp->ve_median[LOC_X]), -lim, lim, 10, RNA_TRANSLATION_PREC_DEFAULT, "");
uiButSetUnitType(but, PROP_UNIT_LENGTH);
but = uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Y:", 0, yi -= buth, 200, buth,
- &(tfp->ve_median[1]), -lim, lim, 10, RNA_TRANSLATION_PREC_DEFAULT, "");
+ &(tfp->ve_median[LOC_Y]), -lim, lim, 10, RNA_TRANSLATION_PREC_DEFAULT, "");
uiButSetUnitType(but, PROP_UNIT_LENGTH);
but = uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Z:", 0, yi -= buth, 200, buth,
- &(tfp->ve_median[2]), -lim, lim, 10, RNA_TRANSLATION_PREC_DEFAULT, "");
+ &(tfp->ve_median[LOC_Z]), -lim, lim, 10, RNA_TRANSLATION_PREC_DEFAULT, "");
uiButSetUnitType(but, PROP_UNIT_LENGTH);
- if (totw == tot) {
+ if (totcurvebweight == tot) {
uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "W:", 0, yi -= buth, 200, buth,
- &(tfp->ve_median[3]), 0.01, 100.0, 1, 3, "");
+ &(tfp->ve_median[C_BWEIGHT]), 0.01, 100.0, 1, 3, "");
}
uiBlockBeginAlign(block);
@@ -363,60 +409,60 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
&v3d->flag, 0, 0, 0, 0, "Displays local values");
uiBlockEndAlign(block);
- if (totweight == 1) {
- uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Weight:"),
- 0, yi -= buth + but_margin, 200, buth,
- &(tfp->ve_median[4]), 0.0, 1.0, 1, 3, TIP_("Weight used for SoftBody Goal"));
+ /* Meshes... */
+ if (meshdata) {
+ if (totedgedata) {
+ uiDefButF(block, NUM, B_OBJECTPANELMEDIAN,
+ totedgedata == 1 ? IFACE_("Crease:") : IFACE_("Mean Crease:"),
+ 0, yi -= buth + but_margin, 200, buth,
+ &(tfp->ve_median[M_CREASE]), 0.0, 1.0, 1, 3, TIP_("Weight used by SubSurf modifier"));
+ uiDefButF(block, NUM, B_OBJECTPANELMEDIAN,
+ totedgedata == 1 ? IFACE_("Bevel Weight:") : IFACE_("Mean Bevel Weight:"),
+ 0, yi -= buth + but_margin, 200, buth,
+ &(tfp->ve_median[M_WEIGHT]), 0.0, 1.0, 1, 3, TIP_("Weight used by Bevel modifier"));
+ }
+ if (totskinradius) {
+ uiDefButF(block, NUM, B_OBJECTPANELMEDIAN,
+ totskinradius == 1 ? IFACE_("Radius X:") : IFACE_("Mean Radius X:"),
+ 0, yi -= buth + but_margin, 200, buth,
+ &(tfp->ve_median[M_SKIN_X]), 0.0, 100.0, 1, 3, TIP_("X radius used by Skin modifier"));
+ uiDefButF(block, NUM, B_OBJECTPANELMEDIAN,
+ totskinradius == 1 ? IFACE_("Radius Y:") : IFACE_("Mean Radius Y:"),
+ 0, yi -= buth + but_margin, 200, buth,
+ &(tfp->ve_median[M_SKIN_Y]), 0.0, 100.0, 1, 3, TIP_("Y radius used by Skin modifier"));
+ }
}
- else if (totweight > 1) {
- uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Mean Weight:"),
- 0, yi -= buth, 200, buth,
- &(tfp->ve_median[4]), 0.0, 1.0, 1, 3, TIP_("Weight used for SoftBody Goal"));
+ /* Curve... */
+ else if (totcurvedata == 1) {
+ uiDefButR(block, NUM, 0, "Weight", 0, yi -= buth + but_margin, 200, buth,
+ &data_ptr, "weight_softbody", 0, 0.0, 1.0, 1, 3, NULL);
+ uiDefButR(block, NUM, 0, "Radius", 0, yi -= buth + but_margin, 200, buth,
+ &data_ptr, "radius", 0, 0.0, 100.0, 1, 3, NULL);
+ uiDefButR(block, NUM, 0, "Tilt", 0, yi -= buth + but_margin, 200, buth,
+ &data_ptr, "tilt", 0, -M_PI * 2.0, M_PI * 2.0, 1, 3, NULL);
}
-
- if (totradius == 1) {
- uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Radius:"),
+ else if (totcurvedata > 1) {
+ uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Mean Weight:"),
0, yi -= buth + but_margin, 200, buth,
- &(tfp->ve_median[5]), 0.0, 100.0, 1, 3, TIP_("Radius of curve control points"));
- }
- else if (totradius > 1) {
+ &(tfp->ve_median[C_WEIGHT]), 0.0, 1.0, 1, 3, TIP_("Weight used for SoftBody Goal"));
uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Mean Radius:"),
0, yi -= buth + but_margin, 200, buth,
- &(tfp->ve_median[5]), 0.0, 100.0, 1, 3, TIP_("Radius of curve control points"));
+ &(tfp->ve_median[C_RADIUS]), 0.0, 100.0, 1, 3, TIP_("Radius of curve control points"));
+ but = uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Mean Tilt:"),
+ 0, yi -= buth + but_margin, 200, buth,
+ &(tfp->ve_median[C_TILT]), -M_PI * 2.0, M_PI * 2.0, 1, 3,
+ TIP_("Tilt of curve control points"));
+ uiButSetUnitType(but, PROP_UNIT_ROTATION);
}
-
- if (totskinradius == 1) {
- uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Radius X:"),
- 0, yi -= buth + but_margin, 200, buth,
- &(tfp->ve_median[7]), 0.0, 100.0, 1, 3, TIP_("X radius used by Skin modifier"));
- uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Radius Y:"),
- 0, yi -= buth + but_margin, 200, buth,
- &(tfp->ve_median[8]), 0.0, 100.0, 1, 3, TIP_("Y radius used by Skin modifier"));
+ /* Lattice... */
+ else if (totlattdata == 1) {
+ uiDefButR(block, NUM, 0, "Weight", 0, yi -= buth + but_margin, 200, buth,
+ &data_ptr, "weight_softbody", 0, 0.0, 1.0, 1, 3, NULL);
}
- else if (totskinradius > 1) {
- uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Mean Radius X:"),
- 0, yi -= buth + but_margin, 200, buth,
- &(tfp->ve_median[7]), 0.0, 100.0, 1, 3, TIP_("Median X radius used by Skin modifier"));
- uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Mean Radius Y:"),
- 0, yi -= buth + but_margin, 200, buth,
- &(tfp->ve_median[8]), 0.0, 100.0, 1, 3, TIP_("Median Y radius used by Skin modifier"));
- }
-
- if (totedge == 1) {
- uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Crease:"),
- 0, yi -= buth + but_margin, 200, buth,
- &(tfp->ve_median[3]), 0.0, 1.0, 1, 3, TIP_("Weight used by SubSurf modifier"));
- uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Bevel Weight:"),
- 0, yi -= buth + but_margin, 200, buth,
- &(tfp->ve_median[6]), 0.0, 1.0, 1, 3, TIP_("Weight used by Bevel modifier"));
- }
- else if (totedge > 1) {
- uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Mean Crease:"),
- 0, yi -= buth + but_margin, 200, buth,
- &(tfp->ve_median[3]), 0.0, 1.0, 1, 3, TIP_("Weight used by SubSurf modifier"));
- uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Mean Bevel Weight:"),
+ else if (totlattdata > 1) {
+ uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, IFACE_("Mean Weight:"),
0, yi -= buth + but_margin, 200, buth,
- &(tfp->ve_median[6]), 0.0, 1.0, 1, 3, TIP_("Weight used by Bevel modifier"));
+ &(tfp->ve_median[L_WEIGHT]), 0.0, 1.0, 1, 3, TIP_("Weight used for SoftBody Goal"));
}
uiBlockEndAlign(block);
@@ -424,42 +470,40 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
}
else { /* apply */
+ int i;
+
memcpy(ve_median, tfp->ve_median, sizeof(tfp->ve_median));
if (v3d->flag & V3D_GLOBAL_STATS) {
invert_m4_m4(ob->imat, ob->obmat);
- mul_m4_v3(ob->imat, median);
- mul_m4_v3(ob->imat, ve_median);
+ mul_m4_v3(ob->imat, &median[LOC_X]);
+ mul_m4_v3(ob->imat, &ve_median[LOC_X]);
}
- sub_v3_v3v3(median, ve_median, median);
- median[3] = ve_median[3] - median[3];
- median[4] = ve_median[4] - median[4];
- median[5] = ve_median[5] - median[5];
- median[6] = ve_median[6] - median[6];
- median[7] = ve_median[7] - median[7];
- median[8] = ve_median[8] - median[8];
+ i = NBR_TRANSFORM_PROPERTIES;
+ while (i--)
+ median[i] = ve_median[i] - median[i];
if (ob->type == OB_MESH) {
Mesh *me = ob->data;
BMEditMesh *em = me->edit_btmesh;
BMesh *bm = em->bm;
- BMVert *eve;
BMIter iter;
- if (len_v3(median) > 0.000001f) {
+ if (len_v3(&median[LOC_X]) > 0.000001f) {
+ BMVert *eve;
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
- add_v3_v3(eve->co, median);
+ add_v3_v3(eve->co, &median[LOC_X]);
}
}
EDBM_mesh_normals_update(em);
}
- if (median[3] != 0.0f) {
+ if (median[M_CREASE] != 0.0f) {
BMEdge *eed;
- const float sca = compute_scale_factor(ve_median[3], median[3]);
+ const float sca = compute_scale_factor(ve_median[M_CREASE], median[M_CREASE]);
if (ELEM(sca, 0.0f, 1.0f)) {
BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
@@ -495,9 +539,9 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
}
}
- if (median[6] != 0.0f) {
+ if (median[M_WEIGHT] != 0.0f) {
BMEdge *eed;
- const float sca = compute_scale_factor(ve_median[6], median[6]);
+ const float sca = compute_scale_factor(ve_median[M_WEIGHT], median[M_WEIGHT]);
if (ELEM(sca, 0.0f, 1.0f)) {
BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
@@ -533,11 +577,11 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
}
}
- if (median[7] != 0.0f) {
+ if (median[M_SKIN_X] != 0.0f) {
BMVert *eve;
/* That one is not clamped to [0.0, 1.0]. */
- float sca = ve_median[7];
- if (ve_median[7] - median[7] == 0.0f) {
+ float sca = ve_median[M_SKIN_X];
+ if (ve_median[M_SKIN_X] - median[M_SKIN_X] == 0.0f) {
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
MVertSkin *vs = (MVertSkin *)CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_MVERT_SKIN);
@@ -547,7 +591,7 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
}
}
else {
- sca /= (ve_median[7] - median[7]);
+ sca /= (ve_median[M_SKIN_X] - median[M_SKIN_X]);
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
MVertSkin *vs = (MVertSkin *)CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_MVERT_SKIN);
@@ -557,11 +601,11 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
}
}
}
- if (median[8] != 0.0f) {
+ if (median[M_SKIN_Y] != 0.0f) {
BMVert *eve;
/* That one is not clamped to [0.0, 1.0]. */
- float sca = ve_median[8];
- if (ve_median[8] - median[8] == 0.0f) {
+ float sca = ve_median[M_SKIN_Y];
+ if (ve_median[M_SKIN_Y] - median[M_SKIN_Y] == 0.0f) {
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
MVertSkin *vs = (MVertSkin *)CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_MVERT_SKIN);
@@ -571,7 +615,7 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
}
}
else {
- sca /= (ve_median[8] - median[8]);
+ sca /= (ve_median[M_SKIN_Y] - median[M_SKIN_Y]);
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
MVertSkin *vs = (MVertSkin *)CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_MVERT_SKIN);
@@ -590,7 +634,7 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
BezTriple *bezt;
int a;
ListBase *nurbs = BKE_curve_editNurbs_get(cu);
- const float scale_w = compute_scale_factor(ve_median[4], median[4]);
+ const float scale_w = compute_scale_factor(ve_median[C_WEIGHT], median[C_WEIGHT]);
nu = nurbs->first;
while (nu) {
@@ -599,11 +643,11 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
a = nu->pntsu;
while (a--) {
if (bezt->f2 & SELECT) {
- add_v3_v3(bezt->vec[0], median);
- add_v3_v3(bezt->vec[1], median);
- add_v3_v3(bezt->vec[2], median);
+ add_v3_v3(bezt->vec[0], &median[LOC_X]);
+ add_v3_v3(bezt->vec[1], &median[LOC_X]);
+ add_v3_v3(bezt->vec[2], &median[LOC_X]);
- if (median[4] != 0.0f) {
+ if (median[C_WEIGHT] != 0.0f) {
if (ELEM(scale_w, 0.0f, 1.0f)) {
bezt->weight = scale_w;
}
@@ -614,14 +658,15 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
}
}
- bezt->radius += median[5];
+ bezt->radius += median[C_RADIUS];
+ bezt->alfa += median[C_TILT];
}
else {
if (bezt->f1 & SELECT) {
- add_v3_v3(bezt->vec[0], median);
+ add_v3_v3(bezt->vec[0], &median[LOC_X]);
}
if (bezt->f3 & SELECT) {
- add_v3_v3(bezt->vec[2], median);
+ add_v3_v3(bezt->vec[2], &median[LOC_X]);
}
}
bezt++;
@@ -632,10 +677,10 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
a = nu->pntsu * nu->pntsv;
while (a--) {
if (bp->f1 & SELECT) {
- add_v3_v3(bp->vec, median);
- bp->vec[3] += median[3];
+ add_v3_v3(bp->vec, &median[LOC_X]);
+ bp->vec[3] += median[C_BWEIGHT];
- if (median[4] != 0.0f) {
+ if (median[C_WEIGHT] != 0.0f) {
if (ELEM(scale_w, 0.0f, 1.0f)) {
bp->weight = scale_w;
}
@@ -646,7 +691,8 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
}
}
- bp->radius += median[5];
+ bp->radius += median[C_RADIUS];
+ bp->alfa += median[C_TILT];
}
bp++;
}
@@ -661,15 +707,15 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
Lattice *lt = ob->data;
BPoint *bp;
int a;
- const float scale_w = compute_scale_factor(ve_median[4], median[4]);
+ const float scale_w = compute_scale_factor(ve_median[L_WEIGHT], median[L_WEIGHT]);
a = lt->editlatt->latt->pntsu * lt->editlatt->latt->pntsv * lt->editlatt->latt->pntsw;
bp = lt->editlatt->latt->def;
while (a--) {
if (bp->f1 & SELECT) {
- add_v3_v3(bp->vec, median);
+ add_v3_v3(bp->vec, &median[LOC_X]);
- if (median[4] != 0.0f) {
+ if (median[L_WEIGHT] != 0.0f) {
if (ELEM(scale_w, 0.0f, 1.0f)) {
bp->weight = scale_w;
}
@@ -686,7 +732,28 @@ static void v3d_editvertex_buts(uiLayout *layout, View3D *v3d, Object *ob, float
/* ED_undo_push(C, "Transform properties"); */
}
+
+/* Clean up! */
+/* Location, common to all. */
+#undef LOC_X
+#undef LOC_Y
+#undef LOC_Z
+/* Meshes (and lattice)... */
+#undef M_CREASE
+#undef M_WEIGHT
+#undef M_SKIN_X
+#undef M_SKIN_Y
+/* Curves... */
+#undef C_BWEIGHT
+#undef C_WEIGHT
+#undef C_RADIUS
+#undef C_TILT
+/* Lattice... */
+#undef L_WEIGHT
}
+#undef NBR_TRANSFORM_PROPERTIES
+
+
#define B_VGRP_PNL_COPY 1
#define B_VGRP_PNL_NORMALIZE 2
#define B_VGRP_PNL_EDIT_SINGLE 8 /* or greater */
@@ -1156,13 +1223,12 @@ static void view3d_panel_object(const bContext *C, Panel *pa)
if (ob == NULL)
return;
- lim = 10000.0f * MAX2(1.0f, v3d->grid);
+ lim = 10000.0f * max_ff(1.0f, v3d->grid);
block = uiLayoutGetBlock(pa->layout);
uiBlockSetHandleFunc(block, do_view3d_region_buttons, NULL);
col = uiLayoutColumn(pa->layout, FALSE);
- /* row = uiLayoutRow(col, FALSE); */ /* UNUSED */
RNA_id_pointer_create(&ob->id, &obptr);
if (ob == obedit) {
diff --git a/source/blender/editors/space_view3d/view3d_draw.c b/source/blender/editors/space_view3d/view3d_draw.c
index 5fbf1971349..4d4fad47698 100644
--- a/source/blender/editors/space_view3d/view3d_draw.c
+++ b/source/blender/editors/space_view3d/view3d_draw.c
@@ -243,7 +243,7 @@ static void drawgrid_draw(ARegion *ar, double wx, double wy, double x, double y,
verts[1][1] = (double)ar->winy;
/* iter over 'X' */
- verts[0][0] = verts[1][0] = x - dx *floor(x / dx);
+ verts[0][0] = verts[1][0] = x - dx * floor(x / dx);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_DOUBLE, 0, verts);
@@ -257,7 +257,7 @@ static void drawgrid_draw(ARegion *ar, double wx, double wy, double x, double y,
verts[1][0] = (double)ar->winx;
/* iter over 'Y' */
- verts[0][1] = verts[1][1] = y - dx *floor(y / dx);
+ verts[0][1] = verts[1][1] = y - dx * floor(y / dx);
while (verts[0][1] < ar->winy) {
glDrawArrays(GL_LINES, 0, 2);
verts[0][1] = verts[1][1] = verts[0][1] + dx;
@@ -355,7 +355,9 @@ static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **
if (dx < GRID_MIN_PX_D) {
rv3d->gridview *= sublines;
dx *= sublines;
- if (dx < GRID_MIN_PX_D) ;
+ if (dx < GRID_MIN_PX_D) {
+ /* pass */
+ }
else {
UI_ThemeColor(TH_GRID);
drawgrid_draw(ar, wx, wy, x, y, dx);
@@ -521,7 +523,7 @@ static void drawfloor(Scene *scene, View3D *v3d, const char **grid_unit)
GPU_print_error("sdsd");
}
- /* draw the Z axis line */
+ /* draw the Z axis line */
/* check for the 'show Z axis' preference */
if (v3d->gridflag & (V3D_SHOW_X | V3D_SHOW_Y | V3D_SHOW_Z)) {
int axis;
@@ -553,32 +555,23 @@ static void drawfloor(Scene *scene, View3D *v3d, const char **grid_unit)
static void drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
{
- int mx, my, co[2];
- int flag;
-
+ int co[2];
+
/* we don't want the clipping for cursor */
- flag = v3d->flag;
- v3d->flag = 0;
- project_int(ar, give_cursor(scene, v3d), co);
- v3d->flag = flag;
-
- mx = co[0];
- my = co[1];
-
- if (mx != IS_CLIPPED) {
+ if (ED_view3d_project_int_global(ar, give_cursor(scene, v3d), co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
setlinestyle(0);
cpack(0xFF);
- circ((float)mx, (float)my, 10.0);
+ circ((float)co[0], (float)co[1], 10.0);
setlinestyle(4);
cpack(0xFFFFFF);
- circ((float)mx, (float)my, 10.0);
+ circ((float)co[0], (float)co[1], 10.0);
setlinestyle(0);
cpack(0x0);
- sdrawline(mx - 20, my, mx - 5, my);
- sdrawline(mx + 5, my, mx + 20, my);
- sdrawline(mx, my - 20, mx, my - 5);
- sdrawline(mx, my + 5, mx, my + 20);
+ sdrawline(co[0] - 20, co[1], co[0] - 5, co[1]);
+ sdrawline(co[0] + 5, co[1], co[0] + 20, co[1]);
+ sdrawline(co[0], co[1] - 20, co[0], co[1] - 5);
+ sdrawline(co[0], co[1] + 5, co[0], co[1] + 20);
}
}
@@ -730,7 +723,7 @@ static void draw_rotation_guide(RegionView3D *rv3d)
glColor4fv(color);
glBegin(GL_LINE_LOOP);
for (i = 0, angle = 0.f; i < ROT_AXIS_DETAIL; ++i, angle += step) {
- float p[3] = {s *cosf(angle), s * sinf(angle), 0.0f};
+ float p[3] = {s * cosf(angle), s * sinf(angle), 0.0f};
if (!upright) {
mul_qt_v3(q, p);
@@ -901,7 +894,7 @@ static void draw_selected_name(Scene *scene, Object *ob)
/* try to display active shapekey too */
shapes[0] = '\0';
- key = ob_get_key(ob);
+ key = BKE_key_from_object(ob);
if (key) {
kb = BLI_findlink(&key->block, ob->shapenr - 1);
if (kb) {
@@ -973,10 +966,10 @@ static void view3d_camera_border(Scene *scene, ARegion *ar, View3D *v3d, RegionV
rect_camera = params.viewplane;
/* get camera border within viewport */
- viewborder_r->xmin = ((rect_camera.xmin - rect_view.xmin) / BLI_RCT_SIZE_X(&rect_view)) * ar->winx;
- viewborder_r->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_RCT_SIZE_X(&rect_view)) * ar->winx;
- viewborder_r->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_RCT_SIZE_Y(&rect_view)) * ar->winy;
- viewborder_r->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_RCT_SIZE_Y(&rect_view)) * ar->winy;
+ viewborder_r->xmin = ((rect_camera.xmin - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
+ viewborder_r->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
+ viewborder_r->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
+ viewborder_r->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
}
void ED_view3d_calc_camera_border_size(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D *rv3d, float size_r[2])
@@ -984,8 +977,8 @@ void ED_view3d_calc_camera_border_size(Scene *scene, ARegion *ar, View3D *v3d, R
rctf viewborder;
view3d_camera_border(scene, ar, v3d, rv3d, &viewborder, TRUE, TRUE);
- size_r[0] = BLI_RCT_SIZE_X(&viewborder);
- size_r[1] = BLI_RCT_SIZE_Y(&viewborder);
+ size_r[0] = BLI_rctf_size_x(&viewborder);
+ size_r[1] = BLI_rctf_size_y(&viewborder);
}
void ED_view3d_calc_camera_border(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D *rv3d,
@@ -1067,7 +1060,7 @@ static void drawviewborder_triangle(float x1, float x2, float y1, float y2, cons
static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
{
- float fac, a;
+ float hmargin, vmargin;
float x1, x2, y1, y2;
float x1i, x2i, y1i, y2i;
float x3, y3, x4, y4;
@@ -1122,7 +1115,7 @@ static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
}
/* edge */
- glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
setlinestyle(0);
@@ -1221,20 +1214,15 @@ static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
}
if (ca->flag & CAM_SHOWTITLESAFE) {
- fac = 0.1;
-
- a = fac * (x2 - x1);
- x1 += a;
- x2 -= a;
-
- a = fac * (y2 - y1);
- y1 += a;
- y2 -= a;
-
UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
- uiSetRoundBox(UI_CNR_ALL);
- uiDrawBox(GL_LINE_LOOP, x1, y1, x2, y2, 12.0);
+ hmargin = 0.1f * (x2 - x1);
+ vmargin = 0.05f * (y2 - y1);
+ uiDrawBox(GL_LINE_LOOP, x1 + hmargin, y1+vmargin, x2 - hmargin, y2 - vmargin, 2.0f);
+
+ hmargin = 0.035f * (x2 - x1);
+ vmargin = 0.035f * (y2 - y1);
+ uiDrawBox(GL_LINE_LOOP, x1 + hmargin, y1+vmargin, x2 - hmargin, y2 - vmargin, 2.0f);
}
if (ca && (ca->flag & CAM_SHOWSENSOR)) {
/* determine sensor fit, and get sensor x/y, for auto fit we
@@ -1341,7 +1329,7 @@ static void backdrawview3d(Scene *scene, ARegion *ar, View3D *v3d)
glDisable(GL_MULTISAMPLE_ARB);
region_scissor_winrct(ar, &winrct);
- glScissor(winrct.xmin, winrct.ymin, BLI_RCT_SIZE_X(&winrct), BLI_RCT_SIZE_Y(&winrct));
+ glScissor(winrct.xmin, winrct.ymin, BLI_rcti_size_x(&winrct), BLI_rcti_size_y(&winrct));
glClearColor(0.0, 0.0, 0.0, 0.0);
if (v3d->zbuf) {
@@ -1436,7 +1424,7 @@ ImBuf *view3d_read_backbuf(ViewContext *vc, short xmin, short ymin, short xmax,
(ymaxc - yminc + 1),
GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
- glReadBuffer(GL_BACK);
+ glReadBuffer(GL_BACK);
if (ENDIAN_ORDER == B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
@@ -1469,7 +1457,7 @@ ImBuf *view3d_read_backbuf(ViewContext *vc, short xmin, short ymin, short xmax,
/* smart function to sample a rect spiralling outside, nice for backbuf selection */
unsigned int view3d_sample_backbuf_rect(ViewContext *vc, const int mval[2], int size,
- unsigned int min, unsigned int max, int *dist, short strict,
+ unsigned int min, unsigned int max, float *r_dist, short strict,
void *handle, unsigned int (*indextest)(void *handle, unsigned int index))
{
struct ImBuf *buf;
@@ -1478,7 +1466,7 @@ unsigned int view3d_sample_backbuf_rect(ViewContext *vc, const int mval[2], int
int a, b, rc, nr, amount, dirvec[4][2];
int distance = 0;
unsigned int index = 0;
- short indexok = 0;
+ short indexok = 0;
amount = (size - 1) / 2;
@@ -1507,13 +1495,13 @@ unsigned int view3d_sample_backbuf_rect(ViewContext *vc, const int mval[2], int
if (strict) {
indexok = indextest(handle, *tbuf - min + 1);
if (indexok) {
- *dist = (short) sqrt( (float)distance);
+ *r_dist = sqrtf((float)distance);
index = *tbuf - min + 1;
goto exit;
}
}
else {
- *dist = (short) sqrt( (float)distance); /* XXX, this distance is wrong - */
+ *r_dist = sqrtf((float)distance); /* XXX, this distance is wrong - */
index = *tbuf - min + 1; /* messy yah, but indices start at 1 */
goto exit;
}
@@ -1543,11 +1531,6 @@ static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
{
RegionView3D *rv3d = ar->regiondata;
BGpic *bgpic;
- Image *ima;
- MovieClip *clip;
- ImBuf *ibuf = NULL, *freeibuf;
- float vec[4], fac, asp, zoomx, zoomy;
- float x1, y1, x2, y2, cx, cy;
int fg_flag = do_foreground ? V3D_BGPIC_FOREGROUND : 0;
for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
@@ -1560,6 +1543,13 @@ static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
(rv3d->persp == RV3D_CAMOB && bgpic->view == (1 << RV3D_VIEW_CAMERA)))
{
float image_aspect[2];
+ float fac, asp, zoomx, zoomy;
+ float x1, y1, x2, y2;
+
+ ImBuf *ibuf = NULL, *freeibuf;
+
+ Image *ima;
+ MovieClip *clip;
/* disable individual images */
if ((bgpic->flag & V3D_BGPIC_DISABLED))
@@ -1645,7 +1635,7 @@ static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
/* apply offset last - camera offset is different to offset in blender units */
/* so this has some sane way of working - this matches camera's shift _exactly_ */
{
- const float max_dim = maxf(x2 - x1, y2 - y1);
+ const float max_dim = max_ff(x2 - x1, y2 - y1);
const float xof_scale = bgpic->xof * max_dim;
const float yof_scale = bgpic->yof * max_dim;
@@ -1687,26 +1677,25 @@ static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
}
}
else {
+ float tvec[3];
float sco[2];
const float mval_f[2] = {1.0f, 0.0f};
/* calc window coord */
initgrabz(rv3d, 0.0, 0.0, 0.0);
- ED_view3d_win_to_delta(ar, mval_f, vec);
- fac = maxf(fabsf(vec[0]), maxf(fabsf(vec[1]), fabsf(vec[2]))); /* largest abs axis */
+ ED_view3d_win_to_delta(ar, mval_f, tvec);
+ fac = max_ff(fabsf(tvec[0]), max_ff(fabsf(tvec[1]), fabsf(tvec[2]))); /* largest abs axis */
fac = 1.0f / fac;
- asp = ( (float)ibuf->y) / (float)ibuf->x;
+ asp = (float)ibuf->y / (float)ibuf->x;
- zero_v3(vec);
- ED_view3d_project_float_v2(ar, vec, sco, rv3d->persmat);
- cx = sco[0];
- cy = sco[1];
+ zero_v3(tvec);
+ ED_view3d_project_float_v2_m4(ar, tvec, sco, rv3d->persmat);
- x1 = cx + fac * (bgpic->xof - bgpic->size);
- y1 = cy + asp * fac * (bgpic->yof - bgpic->size);
- x2 = cx + fac * (bgpic->xof + bgpic->size);
- y2 = cy + asp * fac * (bgpic->yof + bgpic->size);
+ x1 = sco[0] + fac * (bgpic->xof - bgpic->size);
+ y1 = sco[1] + asp * fac * (bgpic->yof - bgpic->size);
+ x2 = sco[0] + fac * (bgpic->xof + bgpic->size);
+ y2 = sco[1] + asp * fac * (bgpic->yof + bgpic->size);
}
/* complete clip? */
@@ -1723,7 +1712,7 @@ static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
/* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
if (zoomx < 1.0f || zoomy < 1.0f) {
- float tzoom = minf(zoomx, zoomy);
+ float tzoom = min_ff(zoomx, zoomy);
int mip = 0;
if ((ibuf->userflags & IB_MIPMAP_INVALID) != 0) {
@@ -1772,8 +1761,9 @@ static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
glDepthMask(1);
if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
- if (freeibuf)
+ if (freeibuf) {
IMB_freeImBuf(freeibuf);
+ }
}
}
}
@@ -1925,7 +1915,7 @@ static void draw_dupli_objects_color(Scene *scene, ARegion *ar, View3D *v3d, Bas
if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
tbase.flag = OB_FROMDUPLI | base->flag;
- lb = object_duplilist(scene, base->object);
+ lb = object_duplilist(scene, base->object, FALSE);
// BLI_sortlist(lb, dupli_ob_sort); /* might be nice to have if we have a dupli list with mixed objects. */
dob = dupli_step(lb->first);
@@ -2029,7 +2019,7 @@ static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *bas
void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
{
- int x, y, w, h;
+ int x, y, w, h;
rcti r;
/* clamp rect by area */
@@ -2045,8 +2035,8 @@ void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
x = rect->xmin;
y = rect->ymin;
- w = BLI_RCT_SIZE_X(rect);
- h = BLI_RCT_SIZE_Y(rect);
+ w = BLI_rcti_size_x(rect);
+ h = BLI_rcti_size_y(rect);
if (w <= 0 || h <= 0) {
if (d->depths)
@@ -2127,7 +2117,7 @@ float view3d_depth_near(ViewDepths *d)
int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
/* far is both the starting 'far' value
- * and the closest value found. */
+ * and the closest value found. */
while (i--) {
depth = *depths++;
if ((depth < far) && (depth > near)) {
@@ -2143,7 +2133,7 @@ void draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
short zbuf = v3d->zbuf;
RegionView3D *rv3d = ar->regiondata;
- setwinmatrixview3d(ar, v3d, NULL); /* 0= no pick rect */
+ setwinmatrixview3d(ar, v3d, NULL);
setviewmatrixview3d(scene, v3d, rv3d); /* note: calls BKE_object_where_is_calc for camera... */
mult_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
@@ -2178,7 +2168,7 @@ void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (*func)(void *))
U.glalphaclip = 0.5; /* not that nice but means we wont zoom into billboards */
U.obcenter_dia = 0;
- setwinmatrixview3d(ar, v3d, NULL); /* 0= no pick rect */
+ setwinmatrixview3d(ar, v3d, NULL);
setviewmatrixview3d(scene, v3d, rv3d); /* note: calls BKE_object_where_is_calc for camera... */
mult_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
@@ -2338,7 +2328,7 @@ static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
if (ob->transflag & OB_DUPLI) {
DupliObject *dob;
- ListBase *lb = object_duplilist(scene, ob);
+ ListBase *lb = object_duplilist(scene, ob, FALSE);
for (dob = lb->first; dob; dob = dob->next)
if (dob->ob->type == OB_LAMP)
@@ -2376,6 +2366,7 @@ static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
mult_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
invert_m4_m4(rv3d.persinv, rv3d.viewinv);
+ /* no need to call ED_view3d_draw_offscreen_init since shadow buffers were already updated */
ED_view3d_draw_offscreen(scene, v3d, &ar, winsize, winsize, viewmat, winmat, FALSE, FALSE);
GPU_lamp_shadow_buffer_unbind(shadow->lamp);
@@ -2465,7 +2456,7 @@ void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float view
if (winmat)
copy_m4_m4(rv3d->winmat, winmat);
else
- setwinmatrixview3d(ar, v3d, NULL); /* NULL= no pickrect */
+ setwinmatrixview3d(ar, v3d, NULL);
/* setup view matrix */
if (viewmat)
@@ -2483,7 +2474,7 @@ void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float view
/* note: '1.0f / len_v3(v1)' replaced 'len_v3(rv3d->viewmat[0])'
* because of float point precision problems at large values [#23908] */
float v1[3], v2[3];
- float len1, len2;
+ float len_px, len_sc;
v1[0] = rv3d->persmat[0][0];
v1[1] = rv3d->persmat[1][0];
@@ -2493,10 +2484,10 @@ void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float view
v2[1] = rv3d->persmat[1][1];
v2[2] = rv3d->persmat[2][1];
- len1 = 1.0f / len_v3(v1);
- len2 = 1.0f / len_v3(v2);
+ len_px = 2.0f / sqrtf(min_ff(len_squared_v3(v1), len_squared_v3(v2)));
+ len_sc = (float)MAX2(ar->winx, ar->winy);
- rv3d->pixsize = (2.0f * MAX2(len1, len2)) / (float)MAX2(ar->winx, ar->winy);
+ rv3d->pixsize = len_px / len_sc;
}
}
@@ -2513,6 +2504,16 @@ static void view3d_main_area_setup_view(Scene *scene, View3D *v3d, ARegion *ar,
glLoadMatrixf(rv3d->viewmat);
}
+void ED_view3d_draw_offscreen_init(Scene *scene, View3D *v3d)
+{
+ /* shadow buffers, before we setup matrices */
+ if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
+ gpu_update_lamps_shadows(scene, v3d);
+}
+
+/* ED_view3d_draw_offscreen_init should be called before this to initialize
+ * stuff like shadow buffers
+ */
void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar,
int winx, int winy, float viewmat[][4], float winmat[][4],
int do_bgpic, int colormanage_background)
@@ -2546,10 +2547,6 @@ void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar,
/* free images which can have changed on frame-change
* warning! can be slow so only free animated images - campbell */
GPU_free_images_anim();
-
- /* shadow buffers, before we setup matrices */
- if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
- gpu_update_lamps_shadows(scene, v3d);
/* set background color, fallback on the view background color
* (if active clip is set but frame is failed to load fallback to horizon color as background) */
@@ -2557,7 +2554,7 @@ void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar,
/* NOTE: currently OpenGL is supposed to always work in sRGB space and do not
* apply any tonemaps since it's really tricky to support for all features (GLSL, textures, etc)
* but due to compatibility issues background is being affected display transform, so we can
- * emulate behavior of disabled colro management
+ * emulate behavior of disabled color management
* but this function is also used for sequencer's scene strips which shouldn't be affected by
* tonemaps now and should be purely sRGB, that's why we've got this colormanage_background
* we can drop this flag in cost of some compatibility loss -- background wouldn't be
@@ -2692,6 +2689,8 @@ ImBuf *ED_view3d_draw_offscreen_imbuf(Scene *scene, View3D *v3d, ARegion *ar,
if (ofs == NULL)
return NULL;
+ ED_view3d_draw_offscreen_init(scene, v3d);
+
GPU_offscreen_bind(ofs);
/* render 3d view */
@@ -2820,7 +2819,7 @@ static void draw_viewport_fps(Scene *scene, ARegion *ar)
if (fps + 0.5f < (float)(FPS)) {
UI_ThemeColor(TH_REDALERT);
BLI_snprintf(printable, sizeof(printable), "fps: %.2f", fps);
- }
+ }
else {
UI_ThemeColor(TH_TEXT_HI);
BLI_snprintf(printable, sizeof(printable), "fps: %i", (int)(fps + 0.5f));
@@ -2858,8 +2857,8 @@ static int view3d_main_area_draw_engine(const bContext *C, ARegion *ar, int draw
engine = RE_engine_create(type);
- engine->tile_x = ceil(ar->winx/(float)scene->r.xparts);
- engine->tile_y = ceil(ar->winy/(float)scene->r.yparts);
+ engine->tile_x = scene->r.tilex;
+ engine->tile_y = scene->r.tiley;
type->view_update(engine, C);
@@ -2877,12 +2876,20 @@ static int view3d_main_area_draw_engine(const bContext *C, ARegion *ar, int draw
rctf viewborder;
rcti cliprct;
- ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, FALSE);
+ if (rv3d->persp == RV3D_CAMOB) {
+ ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, FALSE);
- cliprct.xmin = viewborder.xmin + scene->r.border.xmin * BLI_RCT_SIZE_X(&viewborder);
- cliprct.ymin = viewborder.ymin + scene->r.border.ymin * BLI_RCT_SIZE_Y(&viewborder);
- cliprct.xmax = viewborder.xmin + scene->r.border.xmax * BLI_RCT_SIZE_X(&viewborder);
- cliprct.ymax = viewborder.ymin + scene->r.border.ymax * BLI_RCT_SIZE_Y(&viewborder);
+ cliprct.xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
+ cliprct.ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
+ cliprct.xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
+ cliprct.ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
+ }
+ else {
+ cliprct.xmin = v3d->render_border.xmin * ar->winx;
+ cliprct.xmax = v3d->render_border.xmax * ar->winx;
+ cliprct.ymin = v3d->render_border.ymin * ar->winy;
+ cliprct.ymax = v3d->render_border.ymax * ar->winy;
+ }
cliprct.xmin += ar->winrct.xmin;
cliprct.xmax += ar->winrct.xmin;
@@ -2896,7 +2903,7 @@ static int view3d_main_area_draw_engine(const bContext *C, ARegion *ar, int draw
if (cliprct.xmax > cliprct.xmin && cliprct.ymax > cliprct.ymin) {
glGetIntegerv(GL_SCISSOR_BOX, scissor);
- glScissor(cliprct.xmin, cliprct.ymin, BLI_RCT_SIZE_X(&cliprct), BLI_RCT_SIZE_Y(&cliprct));
+ glScissor(cliprct.xmin, cliprct.ymin, BLI_rcti_size_x(&cliprct), BLI_rcti_size_y(&cliprct));
}
else
return 0;
@@ -3126,50 +3133,64 @@ static void view3d_main_area_draw_info(const bContext *C, ARegion *ar, const cha
View3D *v3d = CTX_wm_view3d(C);
RegionView3D *rv3d = CTX_wm_region_view3d(C);
- Object *ob;
-
- if (rv3d->persp == RV3D_CAMOB)
+ if (rv3d->persp == RV3D_CAMOB) {
drawviewborder(scene, ar, v3d);
+ }
+ else if (v3d->flag2 & V3D_RENDER_BORDER) {
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ setlinestyle(3);
+ cpack(0x4040FF);
+
+ glRectf(v3d->render_border.xmin * ar->winx, v3d->render_border.ymin * ar->winy,
+ v3d->render_border.xmax * ar->winx, v3d->render_border.ymax * ar->winy);
+
+ setlinestyle(0);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ }
if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
+ Object *ob;
+
/* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
// if (v3d->flag2 & V3D_DISPGP)
draw_gpencil_view3d(scene, v3d, ar, 0);
drawcursor(scene, ar, v3d);
+
+ if (U.uiflag & USER_SHOW_ROTVIEWICON)
+ draw_view_axis(rv3d);
+ else
+ draw_view_icon(rv3d);
+
+ ob = OBACT;
+ if (U.uiflag & USER_DRAWVIEWINFO)
+ draw_selected_name(scene, ob);
}
-
- if (U.uiflag & USER_SHOW_ROTVIEWICON)
- draw_view_axis(rv3d);
- else
- draw_view_icon(rv3d);
-
- ob = OBACT;
- if (U.uiflag & USER_DRAWVIEWINFO)
- draw_selected_name(scene, ob);
if (rv3d->render_engine) {
view3d_main_area_draw_engine_info(rv3d, ar);
return;
}
- if ((U.uiflag & USER_SHOW_FPS) && ED_screen_animation_playing(wm)) {
- draw_viewport_fps(scene, ar);
- }
- else if (U.uiflag & USER_SHOW_VIEWPORTNAME) {
- draw_viewport_name(ar, v3d);
- }
+ if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
+ if ((U.uiflag & USER_SHOW_FPS) && ED_screen_animation_playing(wm)) {
+ draw_viewport_fps(scene, ar);
+ }
+ else if (U.uiflag & USER_SHOW_VIEWPORTNAME) {
+ draw_viewport_name(ar, v3d);
+ }
- if (grid_unit) { /* draw below the viewport name */
- char numstr[32] = "";
+ if (grid_unit) { /* draw below the viewport name */
+ char numstr[32] = "";
- UI_ThemeColor(TH_TEXT_HI);
- if (v3d->grid != 1.0f) {
- BLI_snprintf(numstr, sizeof(numstr), "%s x %.4g", grid_unit, v3d->grid);
- }
+ UI_ThemeColor(TH_TEXT_HI);
+ if (v3d->grid != 1.0f) {
+ BLI_snprintf(numstr, sizeof(numstr), "%s x %.4g", grid_unit, v3d->grid);
+ }
- BLF_draw_default_ascii(22, ar->winy - (USER_SHOW_VIEWPORTNAME ? 40 : 20), 0.0f,
- numstr[0] ? numstr : grid_unit, sizeof(numstr));
+ BLF_draw_default_ascii(22, ar->winy - (USER_SHOW_VIEWPORTNAME ? 40 : 20), 0.0f,
+ numstr[0] ? numstr : grid_unit, sizeof(numstr));
+ }
}
}
@@ -3179,18 +3200,12 @@ void view3d_main_area_draw(const bContext *C, ARegion *ar)
View3D *v3d = CTX_wm_view3d(C);
RegionView3D *rv3d = CTX_wm_region_view3d(C);
const char *grid_unit = NULL;
- int draw_border = (rv3d->persp == RV3D_CAMOB && (scene->r.mode & R_BORDER));
+ int draw_border = FALSE;
- /* --- until we get a clue and make viewport threadsafe (temp mango change for stability) */
- if (G.is_rendering) {
- ED_region_pixelspace(ar);
- glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
- UI_ThemeClearColor(TH_BACK);
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- BLF_draw_default(10,10,0, "do do da da.. da da.. da da.. can't touch this! it's render time", 512);
- return;
- }
- /* --- end temp mango change */
+ if (rv3d->persp == RV3D_CAMOB)
+ draw_border = scene->r.mode & R_BORDER;
+ else
+ draw_border = v3d->flag2 & V3D_RENDER_BORDER;
/* draw viewport using opengl */
if (v3d->drawtype != OB_RENDER || !view3d_main_area_do_render_draw(C) || draw_border) {
diff --git a/source/blender/editors/space_view3d/view3d_edit.c b/source/blender/editors/space_view3d/view3d_edit.c
index 7accdb0c0e4..36d7341f2f2 100644
--- a/source/blender/editors/space_view3d/view3d_edit.c
+++ b/source/blender/editors/space_view3d/view3d_edit.c
@@ -96,6 +96,7 @@ int ED_view3d_camera_lock_check(View3D *v3d, RegionView3D *rv3d)
void ED_view3d_camera_lock_init(View3D *v3d, RegionView3D *rv3d)
{
if (ED_view3d_camera_lock_check(v3d, rv3d)) {
+ rv3d->dist = ED_view3d_offset_distance(v3d->camera->obmat, rv3d->ofs);
ED_view3d_from_object(v3d->camera, rv3d->ofs, rv3d->viewquat, &rv3d->dist, NULL);
}
}
@@ -375,17 +376,17 @@ typedef struct ViewOpsData {
#define TRACKBALLSIZE (1.1)
-static void calctrackballvec(rcti *rect, int mx, int my, float vec[3])
+static void calctrackballvec(const rcti *rect, int mx, int my, float vec[3])
{
float x, y, radius, d, z, t;
radius = TRACKBALLSIZE;
/* normalize x and y */
- x = BLI_RCT_CENTER_X(rect) - mx;
- x /= (float)(BLI_RCT_SIZE_X(rect) / 4);
- y = BLI_RCT_CENTER_Y(rect) - my;
- y /= (float)(BLI_RCT_SIZE_Y(rect) / 2);
+ x = BLI_rcti_cent_x(rect) - mx;
+ x /= (float)(BLI_rcti_size_x(rect) / 4);
+ y = BLI_rcti_cent_y(rect) - my;
+ y /= (float)(BLI_rcti_size_y(rect) / 2);
d = sqrt(x * x + y * y);
if (d < radius * (float)M_SQRT1_2) { /* Inside sphere */
@@ -894,6 +895,7 @@ static int viewrotate_invoke(bContext *C, wmOperator *op, wmEvent *event)
/* changed since 2.4x, use the camera view */
if (vod->v3d->camera) {
+ rv3d->dist = ED_view3d_offset_distance(vod->v3d->camera->obmat, rv3d->ofs);
ED_view3d_from_object(vod->v3d->camera, rv3d->ofs, rv3d->viewquat, &rv3d->dist, NULL);
}
@@ -921,7 +923,7 @@ static int viewrotate_invoke(bContext *C, wmOperator *op, wmEvent *event)
return OPERATOR_FINISHED;
}
- else {
+ else {
/* add temp handler */
WM_event_add_modal_handler(C, op);
@@ -929,18 +931,6 @@ static int viewrotate_invoke(bContext *C, wmOperator *op, wmEvent *event)
}
}
-static int view3d_camera_active_poll(bContext *C)
-{
- if (ED_operator_view3d_active(C)) {
- RegionView3D *rv3d = CTX_wm_region_view3d(C);
- if (rv3d && rv3d->persp == RV3D_CAMOB) {
- return 1;
- }
- }
-
- return 0;
-}
-
/* test for unlocked camera view in quad view */
static int view3d_camera_user_poll(bContext *C)
{
@@ -966,7 +956,6 @@ static int viewrotate_cancel(bContext *C, wmOperator *op)
void VIEW3D_OT_rotate(wmOperatorType *ot)
{
-
/* identifiers */
ot->name = "Rotate view";
ot->description = "Rotate the view";
@@ -1235,8 +1224,8 @@ void VIEW3D_OT_ndof_pan(struct wmOperatorType *ot)
/*
-* this is basically just the pan only code + the rotate only code crammed into one function that does both
-*/
+ * this is basically just the pan only code + the rotate only code crammed into one function that does both
+ */
static int ndof_all_invoke(bContext *C, wmOperator *op, wmEvent *event)
{
if (event->type != NDOF_MOTION)
@@ -1367,7 +1356,7 @@ static int ndof_all_invoke(bContext *C, wmOperator *op, wmEvent *event)
ED_view3d_camera_lock_sync(v3d, rv3d);
ED_region_tag_redraw(CTX_wm_region(C));
- viewops_data_free(C, op);
+ viewops_data_free(C, op);
return OPERATOR_FINISHED;
}
}
@@ -1514,7 +1503,7 @@ static int viewmove_invoke(bContext *C, wmOperator *op, wmEvent *event)
viewmove_apply(vod, event->prevx, event->prevy);
ED_view3d_depth_tag_update(vod->rv3d);
- viewops_data_free(C, op);
+ viewops_data_free(C, op);
return OPERATOR_FINISHED;
}
@@ -1637,7 +1626,7 @@ static void viewzoom_apply(ViewOpsData *vod, int x, int y, const short viewzoom,
if (use_cam_zoom) {
float delta;
delta = (x - vod->origx + y - vod->origy) / 10.0f;
- vod->rv3d->camzoom = vod->camzoom0 - delta;
+ vod->rv3d->camzoom = vod->camzoom0 + (zoom_invert ? -delta : delta);
CLAMP(vod->rv3d->camzoom, RV3D_CAMZOOM_MIN, RV3D_CAMZOOM_MAX);
}
@@ -1666,8 +1655,8 @@ static void viewzoom_apply(ViewOpsData *vod, int x, int y, const short viewzoom,
int ctr[2], len1, len2;
/* method which zooms based on how far you move the mouse */
- ctr[0] = BLI_RCT_CENTER_X(&vod->ar->winrct);
- ctr[1] = BLI_RCT_CENTER_Y(&vod->ar->winrct);
+ ctr[0] = BLI_rcti_cent_x(&vod->ar->winrct);
+ ctr[1] = BLI_rcti_cent_y(&vod->ar->winrct);
len1 = (int)sqrt((ctr[0] - x) * (ctr[0] - x) + (ctr[1] - y) * (ctr[1] - y)) + 5;
len2 = (int)sqrt((ctr[0] - vod->origx) * (ctr[0] - vod->origx) + (ctr[1] - vod->origy) * (ctr[1] - vod->origy)) + 5;
@@ -1692,11 +1681,11 @@ static void viewzoom_apply(ViewOpsData *vod, int x, int y, const short viewzoom,
if (use_cam_zoom) {
/* zfac is ignored in this case, see below */
#if 0
- zfac = vod->camzoom0 * (2.0f * ((len2 / len1) - 1.0f) + 1.0f) / vod->rv3d->camzoom;
+ zfac = vod->camzoom0 * (2.0f * ((len1 / len2) - 1.0f) + 1.0f) / vod->rv3d->camzoom;
#endif
}
else {
- zfac = vod->dist0 * (2.0f * ((len2 / len1) - 1.0f) + 1.0f) / vod->rv3d->dist;
+ zfac = vod->dist0 * (2.0f * ((len1 / len2) - 1.0f) + 1.0f) / vod->rv3d->dist;
}
}
@@ -1889,12 +1878,12 @@ static int viewzoom_invoke(bContext *C, wmOperator *op, wmEvent *event)
if (U.uiflag & USER_ZOOM_HORIZ) {
vod->origx = vod->oldx = event->x;
- viewzoom_apply(vod, event->prevx, event->prevy, USER_ZOOM_DOLLY, FALSE);
+ viewzoom_apply(vod, event->prevx, event->prevy, USER_ZOOM_DOLLY, (U.uiflag & USER_ZOOM_INVERT) == 0);
}
else {
/* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
vod->origy = vod->oldy = vod->origy + event->x - event->prevx;
- viewzoom_apply(vod, event->prevx, event->prevy, USER_ZOOM_DOLLY, FALSE);
+ viewzoom_apply(vod, event->prevx, event->prevy, USER_ZOOM_DOLLY, (U.uiflag & USER_ZOOM_INVERT) == 0);
}
ED_view3d_depth_tag_update(vod->rv3d);
@@ -1972,7 +1961,7 @@ static void viewdolly_apply(ViewOpsData *vod, int x, int y, const short zoom_inv
if (zoom_invert)
SWAP(float, len1, len2);
- zfac = 1.0f + ((len2 - len1) * 0.01f * vod->rv3d->dist);
+ zfac = 1.0f + ((len1 - len2) * 0.01f * vod->rv3d->dist);
}
if (zfac != 1.0f)
@@ -2052,7 +2041,7 @@ static int viewdolly_exec(bContext *C, wmOperator *op)
normalize_v3(mousevec);
}
- /* v3d= sa->spacedata.first; */ /* UNUSED */
+ /* v3d = sa->spacedata.first; */ /* UNUSED */
rv3d = ar->regiondata;
/* overwrite the mouse vector with the view direction (zoom into the center) */
@@ -2108,13 +2097,13 @@ static int viewdolly_invoke(bContext *C, wmOperator *op, wmEvent *event)
if (U.uiflag & USER_ZOOM_HORIZ) {
vod->origx = vod->oldx = event->x;
- viewdolly_apply(vod, event->prevx, event->prevy, FALSE);
+ viewdolly_apply(vod, event->prevx, event->prevy, (U.uiflag & USER_ZOOM_INVERT) == 0);
}
else {
/* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
vod->origy = vod->oldy = vod->origy + event->x - event->prevx;
- viewdolly_apply(vod, event->prevx, event->prevy, FALSE);
+ viewdolly_apply(vod, event->prevx, event->prevy, (U.uiflag & USER_ZOOM_INVERT) == 0);
}
ED_view3d_depth_tag_update(vod->rv3d);
@@ -2179,21 +2168,98 @@ void VIEW3D_OT_dolly(wmOperatorType *ot)
RNA_def_int(ot->srna, "my", 0, 0, INT_MAX, "Zoom Position Y", "", 0, INT_MAX);
}
+static void view3d_from_minmax(bContext *C, View3D *v3d, ARegion *ar,
+ const float min[3], const float max[3],
+ int ok_dist)
+{
+ RegionView3D *rv3d = ar->regiondata;
+ float afm[3];
+ float size;
+
+ /* SMOOTHVIEW */
+ float new_ofs[3];
+ float new_dist;
+
+ sub_v3_v3v3(afm, max, min);
+ size = MAX3(afm[0], afm[1], afm[2]);
+
+ if (ok_dist) {
+ /* fix up zoom distance if needed */
+
+ if (rv3d->is_persp) {
+ if (size <= v3d->near * 1.5f) {
+ /* do not zoom closer than the near clipping plane */
+ size = v3d->near * 1.5f;
+ }
+ }
+ else { /* ortho */
+ if (size < 0.0001f) {
+ /* bounding box was a single point so do not zoom */
+ ok_dist = 0;
+ }
+ else {
+ /* adjust zoom so it looks nicer */
+ size *= 0.7f;
+ }
+ }
+ }
+
+ mid_v3_v3v3(new_ofs, min, max);
+ negate_v3(new_ofs);
+ new_dist = size;
+
+ /* correction for window aspect ratio */
+ if (ar->winy > 2 && ar->winx > 2) {
+ size = (float)ar->winx / (float)ar->winy;
+ if (size < 1.0f) size = 1.0f / size;
+ new_dist *= size;
+ }
+
+ if (rv3d->persp == RV3D_CAMOB && !ED_view3d_camera_lock_check(v3d, rv3d)) {
+ rv3d->persp = RV3D_PERSP;
+ view3d_smooth_view(C, v3d, ar, v3d->camera, NULL, new_ofs, NULL, ok_dist ? &new_dist : NULL, NULL);
+ }
+ else {
+ view3d_smooth_view(C, v3d, ar, NULL, NULL, new_ofs, NULL, ok_dist ? &new_dist : NULL, NULL);
+ }
+
+ /* smooth view does viewlock RV3D_BOXVIEW copy */
+}
+
+/* same as view3d_from_minmax but for all regions (except cameras) */
+static void view3d_from_minmax_multi(bContext *C, View3D *v3d,
+ const float min[3], const float max[3],
+ const int ok_dist)
+{
+ ScrArea *sa = CTX_wm_area(C);
+ ARegion *ar;
+ for (ar = sa->regionbase.first; ar; ar = ar->next) {
+ if (ar->regiontype == RGN_TYPE_WINDOW) {
+ RegionView3D *rv3d = ar->regiondata;
+ /* when using all regions, don't jump out of camera view,
+ * but _do_ allow locked cameras to be moved */
+ if ((rv3d->persp != RV3D_CAMOB) || ED_view3d_camera_lock_check(v3d, rv3d)) {
+ view3d_from_minmax(C, v3d, ar, min, max, ok_dist);
+ }
+ }
+ }
+}
static int view3d_all_exec(bContext *C, wmOperator *op) /* was view3d_home() in 2.4x */
{
ARegion *ar = CTX_wm_region(C);
View3D *v3d = CTX_wm_view3d(C);
- RegionView3D *rv3d = CTX_wm_region_view3d(C);
Scene *scene = CTX_data_scene(C);
Base *base;
float *curs;
- const short skip_camera = ED_view3d_camera_lock_check(v3d, rv3d);
-
+ const short use_all_regions = RNA_boolean_get(op->ptr, "use_all_regions");
+ const short skip_camera = (ED_view3d_camera_lock_check(v3d, ar->regiondata) ||
+ /* any one of the regions may be locked */
+ (use_all_regions && v3d->flag2 & V3D_LOCK_CAMERA));
int center = RNA_boolean_get(op->ptr, "center");
- float size, min[3], max[3], afm[3];
+ float min[3], max[3];
int ok = 1, onedone = FALSE;
if (center) {
@@ -2230,37 +2296,16 @@ static int view3d_all_exec(bContext *C, wmOperator *op) /* was view3d_home() in
return OPERATOR_FINISHED;
}
- sub_v3_v3v3(afm, max, min);
- size = 0.7f * MAX3(afm[0], afm[1], afm[2]);
- if (size == 0.0f) ok = 0;
-
- if (ok) {
- float new_dist;
- float new_ofs[3];
-
- new_dist = size;
- new_ofs[0] = -(min[0] + max[0]) / 2.0f;
- new_ofs[1] = -(min[1] + max[1]) / 2.0f;
- new_ofs[2] = -(min[2] + max[2]) / 2.0f;
-
- /* correction for window aspect ratio */
- if (ar->winy > 2 && ar->winx > 2) {
- size = (float)ar->winx / (float)ar->winy;
- if (size < 1.0f) size = 1.0f / size;
- new_dist *= size;
- }
-
- if ((rv3d->persp == RV3D_CAMOB) && !ED_view3d_camera_lock_check(v3d, rv3d)) {
- rv3d->persp = RV3D_PERSP;
- view3d_smooth_view(C, v3d, ar, v3d->camera, NULL, new_ofs, NULL, &new_dist, NULL);
- }
- else {
- view3d_smooth_view(C, v3d, ar, NULL, NULL, new_ofs, NULL, &new_dist, NULL);
- }
+ if (ok == 0) {
+ return OPERATOR_FINISHED;
}
-// XXX BIF_view3d_previewrender_signal(curarea, PR_DBASE|PR_DISPRECT);
- WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
+ if (use_all_regions) {
+ view3d_from_minmax_multi(C, v3d, min, max, TRUE);
+ }
+ else {
+ view3d_from_minmax(C, v3d, ar, min, max, TRUE);
+ }
return OPERATOR_FINISHED;
}
@@ -2268,6 +2313,8 @@ static int view3d_all_exec(bContext *C, wmOperator *op) /* was view3d_home() in
void VIEW3D_OT_view_all(wmOperatorType *ot)
{
+ PropertyRNA *prop;
+
/* identifiers */
ot->name = "View All";
ot->description = "View all objects in scene";
@@ -2280,25 +2327,25 @@ void VIEW3D_OT_view_all(wmOperatorType *ot)
/* flags */
ot->flag = 0;
+ prop = RNA_def_boolean(ot->srna, "use_all_regions", 0, "All Regions", "View selected for all regions");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
RNA_def_boolean(ot->srna, "center", 0, "Center", "");
}
/* like a localview without local!, was centerview() in 2.4x */
-static int viewselected_exec(bContext *C, wmOperator *UNUSED(op))
+static int viewselected_exec(bContext *C, wmOperator *op)
{
ARegion *ar = CTX_wm_region(C);
View3D *v3d = CTX_wm_view3d(C);
- RegionView3D *rv3d = CTX_wm_region_view3d(C);
Scene *scene = CTX_data_scene(C);
Object *ob = OBACT;
Object *obedit = CTX_data_edit_object(C);
- float size, min[3], max[3], afm[3];
+ float min[3], max[3];
int ok = 0, ok_dist = 1;
- const short skip_camera = ED_view3d_camera_lock_check(v3d, rv3d);
-
- /* SMOOTHVIEW */
- float new_ofs[3];
- float new_dist;
+ const short use_all_regions = RNA_boolean_get(op->ptr, "use_all_regions");
+ const short skip_camera = (ED_view3d_camera_lock_check(v3d, ar->regiondata) ||
+ /* any one of the regions may be locked */
+ (use_all_regions && v3d->flag2 & V3D_LOCK_CAMERA));
INIT_MINMAX(min, max);
@@ -2369,54 +2416,17 @@ static int viewselected_exec(bContext *C, wmOperator *UNUSED(op))
}
}
- if (ok == 0) return OPERATOR_FINISHED;
-
- sub_v3_v3v3(afm, max, min);
- size = MAX3(afm[0], afm[1], afm[2]);
-
- if (ok_dist) {
- /* fix up zoom distance if needed */
-
- if (rv3d->is_persp) {
- if (size <= v3d->near * 1.5f) {
- /* do not zoom closer than the near clipping plane */
- size = v3d->near * 1.5f;
- }
- }
- else { /* ortho */
- if (size < 0.0001f) {
- /* bounding box was a single point so do not zoom */
- ok_dist = 0;
- }
- else {
- /* adjust zoom so it looks nicer */
- size *= 0.7f;
- }
- }
- }
-
- add_v3_v3v3(new_ofs, min, max);
- mul_v3_fl(new_ofs, -0.5f);
-
- new_dist = size;
-
- /* correction for window aspect ratio */
- if (ar->winy > 2 && ar->winx > 2) {
- size = (float)ar->winx / (float)ar->winy;
- if (size < 1.0f) size = 1.0f / size;
- new_dist *= size;
+ if (ok == 0) {
+ return OPERATOR_FINISHED;
}
- if (rv3d->persp == RV3D_CAMOB && !ED_view3d_camera_lock_check(v3d, rv3d)) {
- rv3d->persp = RV3D_PERSP;
- view3d_smooth_view(C, v3d, ar, v3d->camera, NULL, new_ofs, NULL, ok_dist ? &new_dist : NULL, NULL);
+ if (use_all_regions) {
+ view3d_from_minmax_multi(C, v3d, min, max, ok_dist);
}
else {
- view3d_smooth_view(C, v3d, ar, NULL, NULL, new_ofs, NULL, ok_dist ? &new_dist : NULL, NULL);
+ view3d_from_minmax(C, v3d, ar, min, max, ok_dist);
}
- /* smooth view does viewlock RV3D_BOXVIEW copy */
-
// XXX BIF_view3d_previewrender_signal(curarea, PR_DBASE|PR_DISPRECT);
return OPERATOR_FINISHED;
@@ -2424,6 +2434,7 @@ static int viewselected_exec(bContext *C, wmOperator *UNUSED(op))
void VIEW3D_OT_view_selected(wmOperatorType *ot)
{
+ PropertyRNA *prop;
/* identifiers */
ot->name = "View Selected";
@@ -2436,6 +2447,10 @@ void VIEW3D_OT_view_selected(wmOperatorType *ot)
/* flags */
ot->flag = 0;
+
+ /* rna later */
+ prop = RNA_def_boolean(ot->srna, "use_all_regions", 0, "All Regions", "View selected for all regions");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
static int view_lock_clear_exec(bContext *C, wmOperator *UNUSED(op))
@@ -2578,7 +2593,7 @@ static int view3d_center_camera_exec(bContext *C, wmOperator *UNUSED(op)) /* was
xfac = (float)ar->winx / (float)(size[0] + 4);
yfac = (float)ar->winy / (float)(size[1] + 4);
- rv3d->camzoom = BKE_screen_view3d_zoom_from_fac(minf(xfac, yfac));
+ rv3d->camzoom = BKE_screen_view3d_zoom_from_fac(min_ff(xfac, yfac));
CLAMP(rv3d->camzoom, RV3D_CAMZOOM_MIN, RV3D_CAMZOOM_MAX);
WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
@@ -2608,42 +2623,71 @@ static int render_border_exec(bContext *C, wmOperator *op)
View3D *v3d = CTX_wm_view3d(C);
ARegion *ar = CTX_wm_region(C);
RegionView3D *rv3d = ED_view3d_context_rv3d(C);
+
Scene *scene = CTX_data_scene(C);
rcti rect;
- rctf vb;
+ rctf vb, border;
+
+ int camera_only = RNA_boolean_get(op->ptr, "camera_only");
+
+ if (camera_only && rv3d->persp != RV3D_CAMOB)
+ return OPERATOR_PASS_THROUGH;
/* get border select values using rna */
WM_operator_properties_border_to_rcti(op, &rect);
/* calculate range */
- ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, FALSE);
- scene->r.border.xmin = ((float)rect.xmin - vb.xmin) / BLI_RCT_SIZE_X(&vb);
- scene->r.border.ymin = ((float)rect.ymin - vb.ymin) / BLI_RCT_SIZE_Y(&vb);
- scene->r.border.xmax = ((float)rect.xmax - vb.xmin) / BLI_RCT_SIZE_X(&vb);
- scene->r.border.ymax = ((float)rect.ymax - vb.ymin) / BLI_RCT_SIZE_Y(&vb);
+ if (rv3d->persp == RV3D_CAMOB) {
+ ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, FALSE);
+ }
+ else {
+ vb.xmin = 0;
+ vb.ymin = 0;
+ vb.xmax = ar->winx;
+ vb.ymax = ar->winy;
+ }
+
+ border.xmin = ((float)rect.xmin - vb.xmin) / BLI_rctf_size_x(&vb);
+ border.ymin = ((float)rect.ymin - vb.ymin) / BLI_rctf_size_y(&vb);
+ border.xmax = ((float)rect.xmax - vb.xmin) / BLI_rctf_size_x(&vb);
+ border.ymax = ((float)rect.ymax - vb.ymin) / BLI_rctf_size_y(&vb);
/* actually set border */
- CLAMP(scene->r.border.xmin, 0.0f, 1.0f);
- CLAMP(scene->r.border.ymin, 0.0f, 1.0f);
- CLAMP(scene->r.border.xmax, 0.0f, 1.0f);
- CLAMP(scene->r.border.ymax, 0.0f, 1.0f);
+ CLAMP(border.xmin, 0.0f, 1.0f);
+ CLAMP(border.ymin, 0.0f, 1.0f);
+ CLAMP(border.xmax, 0.0f, 1.0f);
+ CLAMP(border.ymax, 0.0f, 1.0f);
+
+ if (rv3d->persp == RV3D_CAMOB) {
+ scene->r.border = border;
+
+ WM_event_add_notifier(C, NC_SCENE | ND_RENDER_OPTIONS, NULL);
+ }
+ else {
+ v3d->render_border = border;
+
+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+ }
/* drawing a border surrounding the entire camera view switches off border rendering
* or the border covers no pixels */
- if ((scene->r.border.xmin <= 0.0f && scene->r.border.xmax >= 1.0f &&
- scene->r.border.ymin <= 0.0f && scene->r.border.ymax >= 1.0f) ||
- (scene->r.border.xmin == scene->r.border.xmax ||
- scene->r.border.ymin == scene->r.border.ymax))
+ if ((border.xmin <= 0.0f && border.xmax >= 1.0f &&
+ border.ymin <= 0.0f && border.ymax >= 1.0f) ||
+ (border.xmin == border.xmax || border.ymin == border.ymax))
{
- scene->r.mode &= ~R_BORDER;
+ if (rv3d->persp == RV3D_CAMOB)
+ scene->r.mode &= ~R_BORDER;
+ else
+ v3d->flag2 &= ~V3D_RENDER_BORDER;
}
else {
- scene->r.mode |= R_BORDER;
+ if (rv3d->persp == RV3D_CAMOB)
+ scene->r.mode |= R_BORDER;
+ else
+ v3d->flag2 |= V3D_RENDER_BORDER;
}
-
- WM_event_add_notifier(C, NC_SCENE | ND_RENDER_OPTIONS, NULL);
return OPERATOR_FINISHED;
@@ -2653,7 +2697,7 @@ void VIEW3D_OT_render_border(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Set Render Border";
- ot->description = "Set the boundaries of the border render and enables border render";
+ ot->description = "Set the boundaries of the border render and enable border render";
ot->idname = "VIEW3D_OT_render_border";
/* api callbacks */
@@ -2662,7 +2706,7 @@ void VIEW3D_OT_render_border(wmOperatorType *ot)
ot->modal = WM_border_select_modal;
ot->cancel = WM_border_select_cancel;
- ot->poll = view3d_camera_active_poll;
+ ot->poll = ED_operator_view3d_active;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -2670,7 +2714,56 @@ void VIEW3D_OT_render_border(wmOperatorType *ot)
/* rna */
WM_operator_properties_border(ot);
+ RNA_def_boolean(ot->srna, "camera_only", 0, "Camera Only", "Set render border for camera view and final render only");
}
+
+/* ********************* Clear render border operator ****************** */
+
+static int clear_render_border_exec(bContext *C, wmOperator *UNUSED(op))
+{
+ View3D *v3d = CTX_wm_view3d(C);
+ RegionView3D *rv3d = ED_view3d_context_rv3d(C);
+
+ Scene *scene = CTX_data_scene(C);
+ rctf *border = NULL;
+
+ if (rv3d->persp == RV3D_CAMOB) {
+ scene->r.mode &= ~R_BORDER;
+ border = &scene->r.border;
+
+ WM_event_add_notifier(C, NC_SCENE | ND_RENDER_OPTIONS, NULL);
+ }
+ else {
+ v3d->flag2 &= ~V3D_RENDER_BORDER;
+ border = &v3d->render_border;
+
+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+ }
+
+ border->xmin = 0.0f;
+ border->ymin = 0.0f;
+ border->xmax = 1.0f;
+ border->ymax = 1.0f;
+
+ return OPERATOR_FINISHED;
+
+}
+
+void VIEW3D_OT_clear_render_border(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Clear Render Border";
+ ot->description = "Clear the boundaries of the border render and disable border render";
+ ot->idname = "VIEW3D_OT_clear_render_border";
+
+ /* api callbacks */
+ ot->exec = clear_render_border_exec;
+ ot->poll = ED_operator_view3d_active;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+}
+
/* ********************* Border Zoom operator ****************** */
static int view3d_zoom_border_exec(bContext *C, wmOperator *op)
@@ -2729,7 +2822,7 @@ static int view3d_zoom_border_exec(bContext *C, wmOperator *op)
/* no depths to use, we cant do anything! */
if (depth_close == FLT_MAX) {
- BKE_report(op->reports, RPT_ERROR, "Depth Too Large");
+ BKE_report(op->reports, RPT_ERROR, "Depth too large");
return OPERATOR_CANCELLED;
}
/* convert border to 3d coordinates */
@@ -2786,9 +2879,9 @@ static int view3d_zoom_border_exec(bContext *C, wmOperator *op)
}
/* work out the ratios, so that everything selected fits when we zoom */
- xscale = (BLI_RCT_SIZE_X(&rect) / vb[0]);
- yscale = (BLI_RCT_SIZE_Y(&rect) / vb[1]);
- new_dist *= maxf(xscale, yscale);
+ xscale = (BLI_rcti_size_x(&rect) / vb[0]);
+ yscale = (BLI_rcti_size_y(&rect) / vb[1]);
+ new_dist *= max_ff(xscale, yscale);
/* zoom in as required, or as far as we can go */
dist_range_min = 0.001f * v3d->grid;
@@ -2901,7 +2994,7 @@ static EnumPropertyItem prop_view_items[] = {
{RV3D_VIEW_RIGHT, "RIGHT", 0, "Right", "View From the Right"},
{RV3D_VIEW_TOP, "TOP", 0, "Top", "View From the Top"},
{RV3D_VIEW_BOTTOM, "BOTTOM", 0, "Bottom", "View From the Bottom"},
- {RV3D_VIEW_CAMERA, "CAMERA", 0, "Camera", "View From the active camera"},
+ {RV3D_VIEW_CAMERA, "CAMERA", 0, "Camera", "View From the Active Camera"},
{0, NULL, 0, NULL, NULL}
};
@@ -3125,7 +3218,7 @@ void VIEW3D_OT_viewnumpad(wmOperatorType *ot)
/* identifiers */
ot->name = "View numpad";
- ot->description = "Set the view";
+ ot->description = "Use a preset viewpoint";
ot->idname = "VIEW3D_OT_viewnumpad";
/* api callbacks */
@@ -3135,8 +3228,8 @@ void VIEW3D_OT_viewnumpad(wmOperatorType *ot)
/* flags */
ot->flag = 0;
- prop = RNA_def_enum(ot->srna, "type", prop_view_items, 0, "View", "The Type of view");
- RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+ ot->prop = RNA_def_enum(ot->srna, "type", prop_view_items, 0, "View", "Preset viewpoint to use");
+ RNA_def_property_flag(ot->prop, PROP_SKIP_SAVE);
prop = RNA_def_boolean(ot->srna, "align_active", 0, "Align Active", "Align to the active object's axis");
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
@@ -3213,7 +3306,9 @@ void VIEW3D_OT_view_orbit(wmOperatorType *ot)
/* flags */
ot->flag = 0;
- RNA_def_enum(ot->srna, "type", prop_view_orbit_items, 0, "Orbit", "Direction of View Orbit");
+
+ /* properties */
+ ot->prop = RNA_def_enum(ot->srna, "type", prop_view_orbit_items, 0, "Orbit", "Direction of View Orbit");
}
static EnumPropertyItem prop_view_pan_items[] = {
@@ -3262,7 +3357,9 @@ void VIEW3D_OT_view_pan(wmOperatorType *ot)
/* flags */
ot->flag = 0;
- RNA_def_enum(ot->srna, "type", prop_view_pan_items, 0, "Pan", "Direction of View Pan");
+
+ /* Properties */
+ ot->prop = RNA_def_enum(ot->srna, "type", prop_view_pan_items, 0, "Pan", "Direction of View Pan");
}
static int viewpersportho_exec(bContext *C, wmOperator *UNUSED(op))
@@ -3290,7 +3387,7 @@ void VIEW3D_OT_view_persportho(wmOperatorType *ot)
{
/* identifiers */
ot->name = "View Persp/Ortho";
- ot->description = "Switch the current view from perspective/orthographic";
+ ot->description = "Switch the current view from perspective/orthographic projection";
ot->idname = "VIEW3D_OT_view_persportho";
/* api callbacks */
@@ -3406,7 +3503,8 @@ void VIEW3D_OT_background_image_remove(wmOperatorType *ot)
/* flags */
ot->flag = 0;
-
+
+ /* properties */
RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "Background image index to remove", 0, INT_MAX);
}
@@ -3465,7 +3563,7 @@ static int view3d_clipping_exec(bContext *C, wmOperator *op)
view3d_set_viewcontext(C, &vc);
view3d_get_transformation(vc.ar, vc.rv3d, NULL, &mats); /* NULL because we don't want it in object space */
- ED_view3d_calc_clipping(rv3d->clipbb, rv3d->clip, &mats, &rect);
+ ED_view3d_clipping_calc(rv3d->clipbb, rv3d->clip, &mats, &rect);
return OPERATOR_FINISHED;
}
@@ -3514,57 +3612,49 @@ void VIEW3D_OT_clip_border(wmOperatorType *ot)
/* ***************** 3d cursor cursor op ******************* */
/* mx my in region coords */
-static int set_3dcursor_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
+static int view3d_cursor3d_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
{
Scene *scene = CTX_data_scene(C);
ARegion *ar = CTX_wm_region(C);
View3D *v3d = CTX_wm_view3d(C);
RegionView3D *rv3d = CTX_wm_region_view3d(C);
- float dx, dy, fz, *fp = NULL, dvec[3], oldcurs[3];
- int mval[2];
-// short ctrl= 0; // XXX
+ float *fp = NULL;
+ float mval_fl[2];
int flip;
fp = give_cursor(scene, v3d);
-// if (obedit && ctrl) lr_click= 1;
- copy_v3_v3(oldcurs, fp);
-
- project_int_noclip(ar, fp, mval);
flip = initgrabz(rv3d, fp[0], fp[1], fp[2]);
- /* reset the depth based on the view offset */
+ /* reset the depth based on the view offset (we _know_ the offset is infront of us) */
if (flip) {
negate_v3_v3(fp, rv3d->ofs);
-
- /* re initialize */
- project_int_noclip(ar, fp, mval);
- flip = initgrabz(rv3d, fp[0], fp[1], fp[2]);
- (void)flip;
+ /* re initialize, no need to check flip again */
+ /* flip = */ initgrabz(rv3d, fp[0], fp[1], fp[2]);
}
- if (mval[0] != IS_CLIPPED) {
- short depth_used = 0;
+ if (ED_view3d_project_float_global(ar, fp, mval_fl, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ short depth_used = FALSE;
if (U.uiflag & USER_ZBUF_CURSOR) { /* maybe this should be accessed some other way */
view3d_operator_needs_opengl(C);
if (ED_view3d_autodist(scene, ar, v3d, event->mval, fp))
- depth_used = 1;
+ depth_used = TRUE;
}
- if (depth_used == 0) {
- float mval_f[2];
- VECSUB2D(mval_f, mval, event->mval);
- ED_view3d_win_to_delta(ar, mval_f, dvec);
+ if (depth_used == FALSE) {
+ float dvec[3];
+ VECSUB2D(mval_fl, mval_fl, event->mval);
+ ED_view3d_win_to_delta(ar, mval_fl, dvec);
sub_v3_v3(fp, dvec);
}
}
else {
-
- dx = ((float)(event->mval[0] - (ar->winx / 2))) * rv3d->zfac / (ar->winx / 2);
- dy = ((float)(event->mval[1] - (ar->winy / 2))) * rv3d->zfac / (ar->winy / 2);
-
- fz = rv3d->persmat[0][3] * fp[0] + rv3d->persmat[1][3] * fp[1] + rv3d->persmat[2][3] * fp[2] + rv3d->persmat[3][3];
- fz = fz / rv3d->zfac;
+ const float dx = ((float)(event->mval[0] - (ar->winx / 2))) * rv3d->zfac / (ar->winx / 2);
+ const float dy = ((float)(event->mval[1] - (ar->winy / 2))) * rv3d->zfac / (ar->winy / 2);
+ const float fz = (rv3d->persmat[0][3] * fp[0] +
+ rv3d->persmat[1][3] * fp[1] +
+ rv3d->persmat[2][3] * fp[2] +
+ rv3d->persmat[3][3]) / rv3d->zfac;
fp[0] = (rv3d->persinv[0][0] * dx + rv3d->persinv[1][0] * dy + rv3d->persinv[2][0] * fz) - rv3d->ofs[0];
fp[1] = (rv3d->persinv[0][1] * dx + rv3d->persinv[1][1] * dy + rv3d->persinv[2][1] * fz) - rv3d->ofs[1];
@@ -3588,7 +3678,7 @@ void VIEW3D_OT_cursor3d(wmOperatorType *ot)
ot->idname = "VIEW3D_OT_cursor3d";
/* api callbacks */
- ot->invoke = set_3dcursor_invoke;
+ ot->invoke = view3d_cursor3d_invoke;
ot->poll = ED_operator_view3d_active;
@@ -3836,11 +3926,25 @@ int ED_view3d_autodist_depth_seg(ARegion *ar, const int mval_sta[2], const int m
return (*depth == FLT_MAX) ? 0 : 1;
}
+float ED_view3d_offset_distance(float mat[4][4], float ofs[3]) {
+ float pos[4] = {0.0f, 0.0f, 0.0f, 1.0f};
+ float dir[4] = {0.0f, 0.0f, 1.0f, 0.0f};
+
+ mul_m4_v4(mat, pos);
+ add_v3_v3(pos, ofs);
+ mul_m4_v4(mat, dir);
+ normalize_v3(dir);
+
+ return dot_v3v3(pos, dir);
+}
+
/**
- * Gets the view transformation from a camera
- * currently dosnt take camzoom into account
+ * Set the view transformation from a 4x4 matrix.
*
- * The dist is not modified for this function, if NULL its assumed zero
+ * \param mat The view 4x4 transformation matrix to assign.
+ * \param ofs The view offset, normally from RegionView3D.ofs.
+ * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
+ * \param dist The view distance from ofs, normally from RegionView3D.dist.
*/
void ED_view3d_from_m4(float mat[][4], float ofs[3], float quat[4], float *dist)
{
@@ -3871,6 +3975,14 @@ void ED_view3d_from_m4(float mat[][4], float ofs[3], float quat[4], float *dist)
}
}
+/**
+ * Calculate the view transformation matrix from RegionView3D input.
+ * The resulting matrix is equivalent to RegionView3D.viewinv
+ * \param mat The view 4x4 transformation matrix to calculate.
+ * \param ofs The view offset, normally from RegionView3D.ofs.
+ * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
+ * \param dist The view distance from ofs, normally from RegionView3D.dist.
+ */
void ED_view3d_to_m4(float mat[][4], const float ofs[3], const float quat[4], const float dist)
{
float iviewquat[4] = {-quat[0], quat[1], quat[2], quat[3]};
@@ -3881,8 +3993,14 @@ void ED_view3d_to_m4(float mat[][4], const float ofs[3], const float quat[4], co
sub_v3_v3v3(mat[3], dvec, ofs);
}
-
-/* object -> view */
+/**
+ * Set the RegionView3D members from an objects transformation and optionally lens.
+ * \param ob The object to set the view to.
+ * \param ofs The view offset to be set, normally from RegionView3D.ofs.
+ * \param quat The view rotation to be set, quaternion normally from RegionView3D.viewquat.
+ * \param dist The view distance from ofs to be set, normally from RegionView3D.dist.
+ * \param lens The view lens angle set for cameras and lamps, normally from View3D.lens.
+ */
void ED_view3d_from_object(Object *ob, float ofs[3], float quat[4], float *dist, float *lens)
{
ED_view3d_from_m4(ob->obmat, ofs, quat, dist);
@@ -3896,7 +4014,13 @@ void ED_view3d_from_object(Object *ob, float ofs[3], float quat[4], float *dist,
}
}
-/* view -> object */
+/**
+ * Set the object transformation from RegionView3D members.
+ * \param ob The object which has the transformation assigned.
+ * \param ofs The view offset, normally from RegionView3D.ofs.
+ * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
+ * \param dist The view distance from ofs, normally from RegionView3D.dist.
+ */
void ED_view3d_to_object(Object *ob, const float ofs[3], const float quat[4], const float dist)
{
float mat[4][4];
diff --git a/source/blender/editors/space_view3d/view3d_fly.c b/source/blender/editors/space_view3d/view3d_fly.c
index 855771b17a2..5aee90f0860 100644
--- a/source/blender/editors/space_view3d/view3d_fly.c
+++ b/source/blender/editors/space_view3d/view3d_fly.c
@@ -27,7 +27,7 @@
/* defines VIEW3D_OT_fly modal operator */
//#define NDOF_FLY_DEBUG
-//#define NDOF_FLY_DRAW_TOOMUCH // is this needed for ndof? - commented so redraw doesnt thrash - campbell
+//#define NDOF_FLY_DRAW_TOOMUCH /* is this needed for ndof? - commented so redraw doesnt thrash - campbell */
#include "DNA_anim_types.h"
#include "DNA_scene_types.h"
#include "DNA_object_types.h"
@@ -284,6 +284,11 @@ static int initFlyInfo(bContext *C, FlyInfo *fly, wmOperator *op, wmEvent *event
puts("\n-- fly begin --");
#endif
+ /* sanity check: for rare but possible case (if lib-linking the camera fails) */
+ if ((fly->rv3d->persp == RV3D_CAMOB) && (fly->v3d->camera == NULL)) {
+ fly->rv3d->persp = RV3D_PERSP;
+ }
+
if (fly->rv3d->persp == RV3D_CAMOB && fly->v3d->camera->id.lib) {
BKE_report(op->reports, RPT_ERROR, "Cannot fly a camera from an external library");
return FALSE;
@@ -346,7 +351,6 @@ static int initFlyInfo(bContext *C, FlyInfo *fly, wmOperator *op, wmEvent *event
/* check for flying ortho camera - which we cant support well
* we _could_ also check for an ortho camera but this is easier */
if ((fly->rv3d->persp == RV3D_CAMOB) &&
- (fly->v3d->camera != NULL) &&
(fly->rv3d->is_persp == FALSE))
{
((Camera *)fly->v3d->camera->data)->type = CAM_PERSP;
@@ -422,7 +426,6 @@ static int flyEnd(bContext *C, FlyInfo *fly)
ED_region_draw_cb_exit(fly->ar->type, fly->draw_handle_pixel);
rv3d->dist = fly->dist_backup;
-
if (fly->state == FLY_CANCEL) {
/* Revert to original view? */
if (fly->persp_backup == RV3D_CAMOB) { /* a camera view */
@@ -437,12 +440,16 @@ static int flyEnd(bContext *C, FlyInfo *fly)
else {
/* Non Camera we need to reset the view back to the original location bacause the user canceled*/
copy_qt_qt(rv3d->viewquat, fly->rot_backup);
- copy_v3_v3(rv3d->ofs, fly->ofs_backup);
rv3d->persp = fly->persp_backup;
}
+ /* always, is set to zero otherwise */
+ copy_v3_v3(rv3d->ofs, fly->ofs_backup);
}
else if (fly->persp_backup == RV3D_CAMOB) { /* camera */
DAG_id_tag_update(fly->root_parent ? &fly->root_parent->id : &v3d->camera->id, OB_RECALC_OB);
+
+ /* always, is set to zero otherwise */
+ copy_v3_v3(rv3d->ofs, fly->ofs_backup);
}
else { /* not camera */
@@ -549,7 +556,7 @@ static void flyEvent(FlyInfo *fly, wmEvent *event)
time_wheel = (float)(time_currwheel - fly->time_lastwheel);
fly->time_lastwheel = time_currwheel;
/* Mouse wheel delays range from (0.5 == slow) to (0.01 == fast) */
- time_wheel = 1.0f + (10.0f - (20.0f * minf(time_wheel, 0.5f))); /* 0-0.5 -> 0-5.0 */
+ time_wheel = 1.0f + (10.0f - (20.0f * min_ff(time_wheel, 0.5f))); /* 0-0.5 -> 0-5.0 */
if (fly->speed < 0.0f) {
fly->speed = 0.0f;
@@ -567,7 +574,7 @@ static void flyEvent(FlyInfo *fly, wmEvent *event)
time_currwheel = PIL_check_seconds_timer();
time_wheel = (float)(time_currwheel - fly->time_lastwheel);
fly->time_lastwheel = time_currwheel;
- time_wheel = 1.0f + (10.0f - (20.0f * minf(time_wheel, 0.5f))); /* 0-0.5 -> 0-5.0 */
+ time_wheel = 1.0f + (10.0f - (20.0f * min_ff(time_wheel, 0.5f))); /* 0-0.5 -> 0-5.0 */
if (fly->speed > 0.0f) {
fly->speed = 0;
@@ -791,8 +798,8 @@ static int flyApply(bContext *C, FlyInfo *fly)
ymargin = ar->winy / 20.0f;
// UNUSED
- // cent_orig[0]= ar->winrct.xmin + ar->winx/2;
- // cent_orig[1]= ar->winrct.ymin + ar->winy/2;
+ // cent_orig[0] = ar->winrct.xmin + ar->winx / 2;
+ // cent_orig[1] = ar->winrct.ymin + ar->winy / 2;
{
@@ -843,7 +850,7 @@ static int flyApply(bContext *C, FlyInfo *fly)
#endif
time_current = PIL_check_seconds_timer();
time_redraw = (float)(time_current - fly->time_lastdraw);
- time_redraw_clamped = minf(0.05f, time_redraw); /* clamp redraw time to avoid jitter in roll correction */
+ time_redraw_clamped = min_ff(0.05f, time_redraw); /* clamp redraw time to avoid jitter in roll correction */
fly->time_lastdraw = time_current;
/* Scale the time to use shift to scale the speed down- just like
diff --git a/source/blender/editors/space_view3d/view3d_header.c b/source/blender/editors/space_view3d/view3d_header.c
index fd43333acfe..d8fcc7e12e7 100644
--- a/source/blender/editors/space_view3d/view3d_header.c
+++ b/source/blender/editors/space_view3d/view3d_header.c
@@ -84,25 +84,10 @@
* This can be cleaned when I make some new 'mode' icons.
*/
-/* view3d handler codes */
-#define VIEW3D_HANDLER_BACKGROUND 1
-#define VIEW3D_HANDLER_PROPERTIES 2
-#define VIEW3D_HANDLER_OBJECT 3
-#define VIEW3D_HANDLER_PREVIEW 4
-#define VIEW3D_HANDLER_MULTIRES 5
-#define VIEW3D_HANDLER_TRANSFORM 6
-#define VIEW3D_HANDLER_GREASEPENCIL 7
-#define VIEW3D_HANDLER_BONESKETCH 8
-
/* end XXX ************* */
static void do_view3d_header_buttons(bContext *C, void *arg, int event);
-#define B_SCENELOCK 101
-#define B_FULL 102
-#define B_HOME 103
-#define B_VIEWBUT 104
-#define B_PERSP 105
#define B_MODESELECT 108
#define B_SEL_VERT 110
#define B_SEL_EDGE 111
@@ -110,10 +95,7 @@ static void do_view3d_header_buttons(bContext *C, void *arg, int event);
#define B_MAN_TRANS 116
#define B_MAN_ROT 117
#define B_MAN_SCALE 118
-#define B_NDOF 119
#define B_MAN_MODE 120
-#define B_REDR 122
-#define B_NOP 123
/* XXX quickly ported across */
static void handle_view3d_lock(bContext *C)
@@ -185,7 +167,7 @@ static int view3d_layers_exec(bContext *C, wmOperator *op)
}
else {
v3d->lay |= (1 << 20) - 1;
- }
+ }
}
else {
int bit;
@@ -346,10 +328,6 @@ static void do_view3d_header_buttons(bContext *C, void *UNUSED(arg), int event)
/* watch it: if sa->win does not exist, check that when calling direct drawing routines */
switch (event) {
- case B_REDR:
- ED_area_tag_redraw(sa);
- break;
-
case B_MODESELECT:
WM_operator_properties_create(&props_ptr, "OBJECT_OT_mode_set");
RNA_enum_set(&props_ptr, "mode", v3d->modeselect);
@@ -416,9 +394,6 @@ static void do_view3d_header_buttons(bContext *C, void *UNUSED(arg), int event)
}
ED_area_tag_redraw(sa);
break;
- case B_NDOF:
- ED_area_tag_redraw(sa);
- break;
case B_MAN_MODE:
ED_area_tag_redraw(sa);
break;
@@ -477,7 +452,7 @@ void uiTemplateHeader3D(uiLayout *layout, struct bContext *C)
const float dpi_fac = UI_DPI_FAC;
int is_paint = 0;
- RNA_pointer_create(&screen->id, &RNA_SpaceView3D, v3d, &v3dptr);
+ RNA_pointer_create(&screen->id, &RNA_SpaceView3D, v3d, &v3dptr);
RNA_pointer_create(&scene->id, &RNA_ToolSettings, ts, &toolsptr);
RNA_pointer_create(&scene->id, &RNA_Scene, scene, &sceneptr);
diff --git a/source/blender/editors/space_view3d/view3d_intern.h b/source/blender/editors/space_view3d/view3d_intern.h
index 5bfabf4fc4a..5beeda9f220 100644
--- a/source/blender/editors/space_view3d/view3d_intern.h
+++ b/source/blender/editors/space_view3d/view3d_intern.h
@@ -40,6 +40,7 @@ struct ARegionType;
struct BoundBox;
struct DerivedMesh;
struct Object;
+struct SmokeDomainSettings;
struct ViewContext;
struct bAnimVizSettings;
struct bContext;
@@ -50,8 +51,6 @@ struct wmNDOFMotionData;
struct wmOperatorType;
struct wmWindowManager;
-#define BL_NEAR_CLIP 0.001
-
/* drawing flags: */
enum {
DRAW_PICKING = (1 << 0),
@@ -97,6 +96,7 @@ void VIEW3D_OT_cursor3d(struct wmOperatorType *ot);
void VIEW3D_OT_manipulator(struct wmOperatorType *ot);
void VIEW3D_OT_enable_manipulator(struct wmOperatorType *ot);
void VIEW3D_OT_render_border(struct wmOperatorType *ot);
+void VIEW3D_OT_clear_render_border(struct wmOperatorType *ot);
void VIEW3D_OT_zoom_border(struct wmOperatorType *ot);
void view3d_boxview_copy(ScrArea *sa, ARegion *ar);
@@ -177,7 +177,7 @@ int ED_view3d_boundbox_clip(RegionView3D * rv3d, float obmat[][4], struct BoundB
void view3d_smooth_view(struct bContext *C, struct View3D *v3d, struct ARegion *ar, struct Object *, struct Object *,
float *ofs, float *quat, float *dist, float *lens);
-void setwinmatrixview3d(ARegion *ar, View3D *v3d, rctf *rect); /* rect: for picking */
+void setwinmatrixview3d(ARegion *ar, View3D *v3d, rctf *rect);
void setviewmatrixview3d(Scene *scene, View3D *v3d, RegionView3D *rv3d);
void fly_modal_keymap(struct wmKeyConfig *keyconf);
@@ -212,7 +212,20 @@ ARegion *view3d_has_tools_region(ScrArea *sa);
extern const char *view3d_context_dir[]; /* doc access */
/* draw_volume.c */
-void draw_volume(struct ARegion *ar, struct GPUTexture *tex, float min[3], float max[3], int res[3], float dx, struct GPUTexture *tex_shadow);
+void draw_smoke_volume(struct SmokeDomainSettings *sds, struct Object *ob,
+ struct GPUTexture *tex, float min[3], float max[3],
+ int res[3], float dx, float base_scale, float viewnormal[3],
+ struct GPUTexture *tex_shadow, struct GPUTexture *tex_flame);
+
+//#define SMOKE_DEBUG_VELOCITY
+//#define SMOKE_DEBUG_HEAT
+
+#ifdef SMOKE_DEBUG_VELOCITY
+void draw_smoke_velocity(struct SmokeDomainSettings *domain, struct Object *ob);
+#endif
+#ifdef SMOKE_DEBUG_HEAT
+void draw_smoke_heat(struct SmokeDomainSettings *domain, struct Object *ob);
+#endif
/* workaround for trivial but noticeable camera bug caused by imprecision
* between view border calculation in 2D/3D space, workaround for bug [#28037].
diff --git a/source/blender/editors/space_view3d/view3d_iterators.c b/source/blender/editors/space_view3d/view3d_iterators.c
new file mode 100644
index 00000000000..b928e060ca0
--- /dev/null
+++ b/source/blender/editors/space_view3d/view3d_iterators.c
@@ -0,0 +1,416 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Blender Foundation, full recode and added functions
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/object/view3d_iterators.c
+ * \ingroup spview3d
+ */
+
+#include "DNA_curve_types.h"
+#include "DNA_lattice_types.h"
+#include "DNA_meta_types.h"
+#include "DNA_armature_types.h"
+#include "DNA_object_types.h"
+
+#include "BLI_utildefines.h"
+#include "BLI_listbase.h"
+#include "BLI_rect.h"
+
+#include "BKE_armature.h"
+#include "BKE_curve.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_displist.h"
+
+#include "bmesh.h"
+
+#include "ED_mesh.h"
+#include "ED_screen.h"
+#include "ED_armature.h"
+#include "ED_object.h"
+#include "ED_view3d.h"
+
+
+typedef struct foreachScreenVert_userData {
+ void (*func)(void *userData, BMVert *eve, const float screen_co_b[2], int index);
+ void *userData;
+ ViewContext vc;
+ eV3DProjTest clip_flag;
+} foreachScreenVert_userData;
+
+/* user data structures for derived mesh callbacks */
+typedef struct foreachScreenEdge_userData {
+ void (*func)(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index);
+ void *userData;
+ ViewContext vc;
+ rctf win_rect; /* copy of: vc.ar->winx/winy, use for faster tests, minx/y will always be 0 */
+ eV3DProjTest clip_flag;
+} foreachScreenEdge_userData;
+
+typedef struct foreachScreenFace_userData {
+ void (*func)(void *userData, BMFace *efa, const float screen_co_b[2], int index);
+ void *userData;
+ ViewContext vc;
+ eV3DProjTest clip_flag;
+} foreachScreenFace_userData;
+
+
+/* Note! - foreach funcs should be called while drawing or directly after
+ * if not, ED_view3d_init_mats_rv3d() can be used for selection tools
+ * but would not give correct results with dupli's for eg. which don't
+ * use the object matrix in the usual way */
+
+/* ------------------------------------------------------------------------ */
+
+static void mesh_foreachScreenVert__mapFunc(void *userData, int index, const float co[3],
+ const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
+{
+ foreachScreenVert_userData *data = userData;
+ BMVert *eve = EDBM_vert_at_index(data->vc.em, index);
+
+ if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
+ float screen_co[2];
+
+ if (ED_view3d_project_float_object(data->vc.ar, co, screen_co, data->clip_flag) != V3D_PROJ_RET_OK) {
+ return;
+ }
+
+ data->func(data->userData, eve, screen_co, index);
+ }
+}
+
+void mesh_foreachScreenVert(
+ ViewContext *vc,
+ void (*func)(void *userData, BMVert *eve, const float screen_co[2], int index),
+ void *userData, eV3DProjTest clip_flag)
+{
+ foreachScreenVert_userData data;
+ DerivedMesh *dm = editbmesh_get_derived_cage(vc->scene, vc->obedit, vc->em, CD_MASK_BAREMESH);
+
+ data.vc = *vc;
+ data.func = func;
+ data.userData = userData;
+ data.clip_flag = clip_flag;
+
+ if (clip_flag & V3D_PROJ_TEST_CLIP_BB) {
+ ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
+ }
+
+ EDBM_index_arrays_init(vc->em, 1, 0, 0);
+ dm->foreachMappedVert(dm, mesh_foreachScreenVert__mapFunc, &data);
+ EDBM_index_arrays_free(vc->em);
+
+ dm->release(dm);
+}
+
+/* ------------------------------------------------------------------------ */
+
+static void mesh_foreachScreenEdge__mapFunc(void *userData, int index, const float v0co[3], const float v1co[3])
+{
+ foreachScreenEdge_userData *data = userData;
+ BMEdge *eed = EDBM_edge_at_index(data->vc.em, index);
+
+ if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
+ float screen_co_a[2];
+ float screen_co_b[2];
+ eV3DProjTest clip_flag_nowin = data->clip_flag &= ~V3D_PROJ_TEST_CLIP_WIN;
+
+ if (ED_view3d_project_float_object(data->vc.ar, v0co, screen_co_a, clip_flag_nowin) != V3D_PROJ_RET_OK) {
+ return;
+ }
+ if (ED_view3d_project_float_object(data->vc.ar, v1co, screen_co_b, clip_flag_nowin) != V3D_PROJ_RET_OK) {
+ return;
+ }
+
+ if (data->clip_flag & V3D_PROJ_TEST_CLIP_WIN) {
+ if (!BLI_rctf_isect_segment(&data->win_rect, screen_co_a, screen_co_b)) {
+ return;
+ }
+ }
+
+ data->func(data->userData, eed, screen_co_a, screen_co_b, index);
+ }
+}
+
+void mesh_foreachScreenEdge(
+ ViewContext *vc,
+ void (*func)(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index),
+ void *userData, eV3DProjTest clip_flag)
+{
+ foreachScreenEdge_userData data;
+ DerivedMesh *dm = editbmesh_get_derived_cage(vc->scene, vc->obedit, vc->em, CD_MASK_BAREMESH);
+
+ data.vc = *vc;
+
+ data.win_rect.xmin = 0;
+ data.win_rect.ymin = 0;
+ data.win_rect.xmax = vc->ar->winx;
+ data.win_rect.ymax = vc->ar->winy;
+
+ data.func = func;
+ data.userData = userData;
+ data.clip_flag = clip_flag;
+
+ if (clip_flag & V3D_PROJ_TEST_CLIP_BB) {
+ ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
+ }
+
+ EDBM_index_arrays_init(vc->em, 0, 1, 0);
+ dm->foreachMappedEdge(dm, mesh_foreachScreenEdge__mapFunc, &data);
+ EDBM_index_arrays_free(vc->em);
+
+ dm->release(dm);
+}
+
+/* ------------------------------------------------------------------------ */
+
+static void mesh_foreachScreenFace__mapFunc(void *userData, int index, const float cent[3], const float UNUSED(no[3]))
+{
+ foreachScreenFace_userData *data = userData;
+ BMFace *efa = EDBM_face_at_index(data->vc.em, index);
+
+ if (efa && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
+ float screen_co[2];
+ if (ED_view3d_project_float_object(data->vc.ar, cent, screen_co, data->clip_flag) == V3D_PROJ_RET_OK) {
+ data->func(data->userData, efa, screen_co, index);
+ }
+ }
+}
+
+void mesh_foreachScreenFace(
+ ViewContext *vc,
+ void (*func)(void *userData, BMFace *efa, const float screen_co_b[2], int index),
+ void *userData, const eV3DProjTest clip_flag)
+{
+ foreachScreenFace_userData data;
+ DerivedMesh *dm = editbmesh_get_derived_cage(vc->scene, vc->obedit, vc->em, CD_MASK_BAREMESH);
+
+ data.vc = *vc;
+ data.func = func;
+ data.userData = userData;
+ data.clip_flag = clip_flag;
+
+ ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
+
+ EDBM_index_arrays_init(vc->em, 0, 0, 1);
+ dm->foreachMappedFaceCenter(dm, mesh_foreachScreenFace__mapFunc, &data);
+ EDBM_index_arrays_free(vc->em);
+
+ dm->release(dm);
+}
+
+/* ------------------------------------------------------------------------ */
+
+void nurbs_foreachScreenVert(
+ ViewContext *vc,
+ void (*func)(void *userData, Nurb *nu, BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co_b[2]),
+ void *userData, const eV3DProjTest clip_flag)
+{
+ Curve *cu = vc->obedit->data;
+ Nurb *nu;
+ int i;
+ ListBase *nurbs = BKE_curve_editNurbs_get(cu);
+
+ if (clip_flag & V3D_PROJ_TEST_CLIP_BB) {
+ ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
+ }
+
+ for (nu = nurbs->first; nu; nu = nu->next) {
+ if (nu->type == CU_BEZIER) {
+ for (i = 0; i < nu->pntsu; i++) {
+ BezTriple *bezt = &nu->bezt[i];
+
+ if (bezt->hide == 0) {
+ float screen_co[2];
+
+ if (cu->drawflag & CU_HIDE_HANDLES) {
+ if (ED_view3d_project_float_object(vc->ar, bezt->vec[1], screen_co,
+ V3D_PROJ_RET_CLIP_BB | V3D_PROJ_RET_CLIP_WIN) == V3D_PROJ_RET_OK)
+ {
+ func(userData, nu, NULL, bezt, 1, screen_co);
+ }
+ }
+ else {
+ if (ED_view3d_project_float_object(vc->ar, bezt->vec[0], screen_co,
+ V3D_PROJ_RET_CLIP_BB | V3D_PROJ_RET_CLIP_WIN) == V3D_PROJ_RET_OK)
+ {
+ func(userData, nu, NULL, bezt, 0, screen_co);
+ }
+ if (ED_view3d_project_float_object(vc->ar, bezt->vec[1], screen_co,
+ V3D_PROJ_RET_CLIP_BB | V3D_PROJ_RET_CLIP_WIN) == V3D_PROJ_RET_OK)
+ {
+ func(userData, nu, NULL, bezt, 1, screen_co);
+ }
+ if (ED_view3d_project_float_object(vc->ar, bezt->vec[2], screen_co,
+ V3D_PROJ_RET_CLIP_BB | V3D_PROJ_RET_CLIP_WIN) == V3D_PROJ_RET_OK)
+ {
+ func(userData, nu, NULL, bezt, 2, screen_co);
+ }
+ }
+ }
+ }
+ }
+ else {
+ for (i = 0; i < nu->pntsu * nu->pntsv; i++) {
+ BPoint *bp = &nu->bp[i];
+
+ if (bp->hide == 0) {
+ float screen_co[2];
+ if (ED_view3d_project_float_object(vc->ar, bp->vec, screen_co,
+ V3D_PROJ_RET_CLIP_BB | V3D_PROJ_RET_CLIP_WIN) == V3D_PROJ_RET_OK)
+ {
+ func(userData, nu, bp, NULL, -1, screen_co);
+ }
+ }
+ }
+ }
+ }
+}
+
+/* ------------------------------------------------------------------------ */
+
+/* ED_view3d_init_mats_rv3d must be called first */
+void mball_foreachScreenElem(
+ struct ViewContext *vc,
+ void (*func)(void *userData, struct MetaElem *ml, const float screen_co_b[2]),
+ void *userData, const eV3DProjTest clip_flag)
+{
+ MetaBall *mb = (MetaBall *)vc->obedit->data;
+ MetaElem *ml;
+
+ for (ml = mb->editelems->first; ml; ml = ml->next) {
+ float screen_co[2];
+ if (ED_view3d_project_float_object(vc->ar, &ml->x, screen_co, clip_flag) == V3D_PROJ_RET_OK) {
+ func(userData, ml, screen_co);
+ }
+ }
+}
+
+/* ------------------------------------------------------------------------ */
+
+void lattice_foreachScreenVert(
+ ViewContext *vc,
+ void (*func)(void *userData, BPoint *bp, const float screen_co[2]),
+ void *userData, const eV3DProjTest clip_flag)
+{
+ Object *obedit = vc->obedit;
+ Lattice *lt = obedit->data;
+ BPoint *bp = lt->editlatt->latt->def;
+ DispList *dl = BKE_displist_find(&obedit->disp, DL_VERTS);
+ float *co = dl ? dl->verts : NULL;
+ int i, N = lt->editlatt->latt->pntsu * lt->editlatt->latt->pntsv * lt->editlatt->latt->pntsw;
+
+ if (clip_flag & V3D_PROJ_TEST_CLIP_BB) {
+ ED_view3d_clipping_local(vc->rv3d, obedit->obmat); /* for local clipping lookups */
+ }
+
+ for (i = 0; i < N; i++, bp++, co += 3) {
+ if (bp->hide == 0) {
+ float screen_co[2];
+ if (ED_view3d_project_float_object(vc->ar, dl ? co : bp->vec, screen_co, clip_flag) == V3D_PROJ_RET_OK) {
+ func(userData, bp, screen_co);
+ }
+ }
+ }
+}
+
+/* ------------------------------------------------------------------------ */
+
+/* ED_view3d_init_mats_rv3d must be called first */
+void armature_foreachScreenBone(
+ struct ViewContext *vc,
+ void (*func)(void *userData, struct EditBone *ebone, const float screen_co_a[2], const float screen_co_b[2]),
+ void *userData, const eV3DProjTest clip_flag)
+{
+ bArmature *arm = vc->obedit->data;
+ EditBone *ebone;
+
+ for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
+ if (EBONE_VISIBLE(arm, ebone)) {
+ float screen_co_a[2], screen_co_b[2];
+ int points_proj_tot = 0;
+
+ /* project head location to screenspace */
+ if (ED_view3d_project_float_object(vc->ar, ebone->head, screen_co_a, clip_flag) == V3D_PROJ_RET_OK) {
+ points_proj_tot++;
+ }
+ else {
+ screen_co_a[0] = IS_CLIPPED; /* weak */
+ /* screen_co_a[1]: intentionally dont set this so we get errors on misuse */
+ }
+
+ /* project tail location to screenspace */
+ if (ED_view3d_project_float_object(vc->ar, ebone->tail, screen_co_b, clip_flag) == V3D_PROJ_RET_OK) {
+ points_proj_tot++;
+ }
+ else {
+ screen_co_b[0] = IS_CLIPPED; /* weak */
+ /* screen_co_b[1]: intentionally dont set this so we get errors on misuse */
+ }
+
+ if (points_proj_tot) { /* at least one point's projection worked */
+ func(userData, ebone, screen_co_a, screen_co_b);
+ }
+ }
+ }
+}
+
+/* ------------------------------------------------------------------------ */
+
+/* ED_view3d_init_mats_rv3d must be called first */
+/* almost _exact_ copy of #armature_foreachScreenBone */
+void pose_foreachScreenBone(
+ struct ViewContext *vc,
+ void (*func)(void *userData, struct bPoseChannel *pchan, const float screen_co_a[2], const float screen_co_b[2]),
+ void *userData, const eV3DProjTest clip_flag)
+{
+ bArmature *arm = vc->obact->data;
+ bPose *pose = vc->obact->pose;
+ bPoseChannel *pchan;
+
+ for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
+ if (PBONE_VISIBLE(arm, pchan->bone)) {
+ float screen_co_a[2], screen_co_b[2];
+ int points_proj_tot = 0;
+
+ /* project head location to screenspace */
+ if (ED_view3d_project_float_object(vc->ar, pchan->pose_head, screen_co_a, clip_flag) == V3D_PROJ_RET_OK) {
+ points_proj_tot++;
+ }
+ else {
+ screen_co_a[0] = IS_CLIPPED; /* weak */
+ /* screen_co_a[1]: intentionally dont set this so we get errors on misuse */
+ }
+
+ /* project tail location to screenspace */
+ if (ED_view3d_project_float_object(vc->ar, pchan->pose_tail, screen_co_b, clip_flag) == V3D_PROJ_RET_OK) {
+ points_proj_tot++;
+ }
+ else {
+ screen_co_b[0] = IS_CLIPPED; /* weak */
+ /* screen_co_b[1]: intentionally dont set this so we get errors on misuse */
+ }
+
+ if (points_proj_tot) { /* at least one point's projection worked */
+ func(userData, pchan, screen_co_a, screen_co_b);
+ }
+ }
+ }
+}
diff --git a/source/blender/editors/space_view3d/view3d_ops.c b/source/blender/editors/space_view3d/view3d_ops.c
index 14c02c2357e..73f1563417c 100644
--- a/source/blender/editors/space_view3d/view3d_ops.c
+++ b/source/blender/editors/space_view3d/view3d_ops.c
@@ -83,6 +83,7 @@ void view3d_operatortypes(void)
WM_operatortype_append(VIEW3D_OT_select_circle);
WM_operatortype_append(VIEW3D_OT_smoothview);
WM_operatortype_append(VIEW3D_OT_render_border);
+ WM_operatortype_append(VIEW3D_OT_clear_render_border);
WM_operatortype_append(VIEW3D_OT_zoom_border);
WM_operatortype_append(VIEW3D_OT_manipulator);
WM_operatortype_append(VIEW3D_OT_enable_manipulator);
@@ -136,8 +137,10 @@ void view3d_keymap(wmKeyConfig *keyconf)
WM_keymap_verify_item(keymap, "VIEW3D_OT_move", MIDDLEMOUSE, KM_PRESS, KM_SHIFT, 0);
WM_keymap_verify_item(keymap, "VIEW3D_OT_zoom", MIDDLEMOUSE, KM_PRESS, KM_CTRL, 0);
WM_keymap_verify_item(keymap, "VIEW3D_OT_dolly", MIDDLEMOUSE, KM_PRESS, KM_CTRL | KM_SHIFT, 0);
- WM_keymap_verify_item(keymap, "VIEW3D_OT_view_selected", PADPERIOD, KM_PRESS, 0, 0);
- WM_keymap_verify_item(keymap, "VIEW3D_OT_view_center_cursor", PADPERIOD, KM_PRESS, KM_CTRL, 0);
+ kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_view_selected", PADPERIOD, KM_PRESS, KM_CTRL, 0);
+ RNA_boolean_set(kmi->ptr, "use_all_regions", TRUE);
+ kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_view_selected", PADPERIOD, KM_PRESS, 0, 0);
+ RNA_boolean_set(kmi->ptr, "use_all_regions", FALSE);
WM_keymap_verify_item(keymap, "VIEW3D_OT_view_lock_to_active", PADPERIOD, KM_PRESS, KM_SHIFT, 0);
WM_keymap_verify_item(keymap, "VIEW3D_OT_view_lock_clear", PADPERIOD, KM_PRESS, KM_ALT, 0);
@@ -169,6 +172,9 @@ void view3d_keymap(wmKeyConfig *keyconf)
kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_view_all", HOMEKEY, KM_PRESS, 0, 0);
RNA_boolean_set(kmi->ptr, "center", FALSE); /* only without camera view */
+ kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_view_all", HOMEKEY, KM_PRESS, KM_CTRL, 0);
+ RNA_boolean_set(kmi->ptr, "use_all_regions", TRUE);
+ RNA_boolean_set(kmi->ptr, "center", FALSE); /* only without camera view */
kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_view_all", CKEY, KM_PRESS, KM_SHIFT, 0);
RNA_boolean_set(kmi->ptr, "center", TRUE);
@@ -340,7 +346,13 @@ void view3d_keymap(wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "VIEW3D_OT_clip_border", BKEY, KM_PRESS, KM_ALT, 0);
WM_keymap_add_item(keymap, "VIEW3D_OT_zoom_border", BKEY, KM_PRESS, KM_SHIFT, 0);
- WM_keymap_add_item(keymap, "VIEW3D_OT_render_border", BKEY, KM_PRESS, KM_SHIFT, 0);
+
+ kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_render_border", BKEY, KM_PRESS, KM_SHIFT, 0);
+ RNA_boolean_set(kmi->ptr, "camera_only", TRUE);
+ kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_render_border", BKEY, KM_PRESS, KM_CTRL, 0);
+ RNA_boolean_set(kmi->ptr, "camera_only", FALSE);
+
+ WM_keymap_add_item(keymap, "VIEW3D_OT_clear_render_border", BKEY, KM_PRESS, KM_CTRL | KM_ALT, 0);
WM_keymap_add_item(keymap, "VIEW3D_OT_camera_to_view", PAD0, KM_PRESS, KM_ALT | KM_CTRL, 0);
WM_keymap_add_item(keymap, "VIEW3D_OT_object_as_camera", PAD0, KM_PRESS, KM_CTRL, 0);
diff --git a/source/blender/editors/space_view3d/view3d_project.c b/source/blender/editors/space_view3d/view3d_project.c
new file mode 100644
index 00000000000..6ba05abae9a
--- /dev/null
+++ b/source/blender/editors/space_view3d/view3d_project.c
@@ -0,0 +1,493 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ *
+ * Contributor(s): Blender Foundation
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/space_view3d/view3d_project.c
+ * \ingroup spview3d
+ */
+
+#include "DNA_object_types.h"
+#include "DNA_screen_types.h"
+#include "DNA_scene_types.h"
+#include "DNA_view3d_types.h"
+
+#include "BLO_sys_types.h" /* int64_t */
+
+#include "BIF_gl.h" /* bglMats */
+#include "BIF_glutil.h" /* bglMats */
+
+#include "BLI_math_vector.h"
+
+#include "ED_view3d.h" /* own include */
+
+#define BL_NEAR_CLIP 0.001
+
+/* Non Clipping Projection Functions
+ * ********************************* */
+
+/**
+ * \note use #ED_view3d_ob_project_mat_get to get the projection matrix
+ */
+void ED_view3d_project_float_v2_m4(const ARegion *ar, const float co[3], float r_co[2], float mat[4][4])
+{
+ float vec4[4];
+
+ copy_v3_v3(vec4, co);
+ vec4[3] = 1.0;
+ /* r_co[0] = IS_CLIPPED; */ /* always overwritten */
+
+ mul_m4_v4(mat, vec4);
+
+ if (vec4[3] > FLT_EPSILON) {
+ r_co[0] = (float)(ar->winx / 2.0f) + (ar->winx / 2.0f) * vec4[0] / vec4[3];
+ r_co[1] = (float)(ar->winy / 2.0f) + (ar->winy / 2.0f) * vec4[1] / vec4[3];
+ }
+ else {
+ zero_v2(r_co);
+ }
+}
+
+/**
+ * \note use #ED_view3d_ob_project_mat_get to get projecting mat
+ */
+void ED_view3d_project_float_v3_m4(ARegion *ar, const float vec[3], float r_co[3], float mat[4][4])
+{
+ float vec4[4];
+
+ copy_v3_v3(vec4, vec);
+ vec4[3] = 1.0;
+ /* r_co[0] = IS_CLIPPED; */ /* always overwritten */
+
+ mul_m4_v4(mat, vec4);
+
+ if (vec4[3] > FLT_EPSILON) {
+ r_co[0] = (float)(ar->winx / 2.0f) + (ar->winx / 2.0f) * vec4[0] / vec4[3];
+ r_co[1] = (float)(ar->winy / 2.0f) + (ar->winy / 2.0f) * vec4[1] / vec4[3];
+ r_co[2] = vec4[2] / vec4[3];
+ }
+ else {
+ zero_v3(r_co);
+ }
+}
+
+
+/* Clipping Projection Functions
+ * ***************************** */
+
+eV3DProjStatus ED_view3d_project_base(struct ARegion *ar, struct Base *base)
+{
+ eV3DProjStatus ret = ED_view3d_project_short_global(ar, base->object->obmat[3], &base->sx, V3D_PROJ_TEST_CLIP_DEFAULT);
+
+ if (ret != V3D_PROJ_RET_OK) {
+ base->sx = IS_CLIPPED;
+ base->sy = 0;
+ }
+
+ return ret;
+}
+
+/* perspmat is typically...
+ * - 'rv3d->perspmat', is_local == FALSE
+ * - 'rv3d->perspmatob', is_local == TRUE
+ */
+static eV3DProjStatus ed_view3d_project__internal(ARegion *ar,
+ float perspmat[4][4], const int is_local, /* normally hidden */
+ const float co[3], float r_co[2], const eV3DProjTest flag)
+{
+ float fx, fy, vec4[4];
+
+ /* check for bad flags */
+ BLI_assert((flag & V3D_PROJ_TEST_ALL) == flag);
+
+ if (flag & V3D_PROJ_TEST_CLIP_BB) {
+ RegionView3D *rv3d = ar->regiondata;
+ if (rv3d->rflag & RV3D_CLIPPING) {
+ if (ED_view3d_clipping_test(rv3d, co, is_local)) {
+ return V3D_PROJ_RET_CLIP_BB;
+ }
+ }
+ }
+
+ copy_v3_v3(vec4, co);
+ vec4[3] = 1.0;
+ mul_m4_v4(perspmat, vec4);
+
+ if (vec4[3] > (float)BL_NEAR_CLIP) {
+ fx = ((float)ar->winx / 2.0f) * (1.0f + vec4[0] / vec4[3]);
+ if (((flag & V3D_PROJ_TEST_CLIP_WIN) == 0) || (fx > 0 && fx < ar->winx)) {
+ fy = ((float)ar->winy / 2.0f) * (1.0f + vec4[1] / vec4[3]);
+ if (((flag & V3D_PROJ_TEST_CLIP_WIN) == 0) || (fy > 0.0f && fy < (float)ar->winy)) {
+ r_co[0] = (short)floor(fx);
+ r_co[1] = (short)floor(fy);
+ }
+ else {
+ return V3D_PROJ_RET_CLIP_WIN;
+ }
+ }
+ else {
+ return V3D_PROJ_RET_CLIP_WIN;
+ }
+ }
+ else {
+ return V3D_PROJ_RET_CLIP_NEAR;
+ }
+
+ return V3D_PROJ_RET_OK;
+}
+
+eV3DProjStatus ED_view3d_project_short_ex(ARegion *ar, float perspmat[4][4], const int is_local,
+ const float co[3], short r_co[2], const eV3DProjTest flag)
+{
+ float tvec[2];
+ eV3DProjStatus ret = ed_view3d_project__internal(ar, perspmat, is_local, co, tvec, flag);
+ if (ret == V3D_PROJ_RET_OK) {
+ if ((tvec[0] > -32700.0f && tvec[0] < 32700.0f) &&
+ (tvec[1] > -32700.0f && tvec[1] < 32700.0f))
+ {
+ r_co[0] = (short)floor(tvec[0]);
+ r_co[1] = (short)floor(tvec[1]);
+ }
+ else {
+ ret = V3D_PROJ_RET_OVERFLOW;
+ }
+ }
+ return ret;
+}
+
+eV3DProjStatus ED_view3d_project_int_ex(ARegion *ar, float perspmat[4][4], const int is_local,
+ const float co[3], int r_co[2], const eV3DProjTest flag)
+{
+ float tvec[2];
+ eV3DProjStatus ret = ed_view3d_project__internal(ar, perspmat, is_local, co, tvec, flag);
+ if (ret == V3D_PROJ_RET_OK) {
+ if ((tvec[0] > -2140000000.0f && tvec[0] < 2140000000.0f) &&
+ (tvec[1] > -2140000000.0f && tvec[1] < 2140000000.0f))
+ {
+ r_co[0] = (int)floor(tvec[0]);
+ r_co[1] = (int)floor(tvec[1]);
+ }
+ else {
+ ret = V3D_PROJ_RET_OVERFLOW;
+ }
+ }
+ return ret;
+}
+
+eV3DProjStatus ED_view3d_project_float_ex(ARegion *ar, float perspmat[4][4], const int is_local,
+ const float co[3], float r_co[2], const eV3DProjTest flag)
+{
+ float tvec[2];
+ eV3DProjStatus ret = ed_view3d_project__internal(ar, perspmat, is_local, co, tvec, flag);
+ if (ret == V3D_PROJ_RET_OK) {
+ if (finite(tvec[0]) &&
+ finite(tvec[1]))
+ {
+ copy_v2_v2(r_co, tvec);
+ }
+ else {
+ ret = V3D_PROJ_RET_OVERFLOW;
+ }
+ }
+ return ret;
+}
+
+/* --- short --- */
+eV3DProjStatus ED_view3d_project_short_global(ARegion *ar, const float co[3], short r_co[2], const eV3DProjTest flag)
+{
+ RegionView3D *rv3d = ar->regiondata;
+ return ED_view3d_project_short_ex(ar, rv3d->persmat, FALSE, co, r_co, flag);
+}
+/* object space, use ED_view3d_init_mats_rv3d before calling */
+eV3DProjStatus ED_view3d_project_short_object(ARegion *ar, const float co[3], short r_co[2], const eV3DProjTest flag)
+{
+ RegionView3D *rv3d = ar->regiondata;
+ return ED_view3d_project_short_ex(ar, rv3d->persmatob, TRUE, co, r_co, flag);
+}
+
+/* --- int --- */
+eV3DProjStatus ED_view3d_project_int_global(ARegion *ar, const float co[3], int r_co[2], const eV3DProjTest flag)
+{
+ RegionView3D *rv3d = ar->regiondata;
+ return ED_view3d_project_int_ex(ar, rv3d->persmat, FALSE, co, r_co, flag);
+}
+/* object space, use ED_view3d_init_mats_rv3d before calling */
+eV3DProjStatus ED_view3d_project_int_object(ARegion *ar, const float co[3], int r_co[2], const eV3DProjTest flag)
+{
+ RegionView3D *rv3d = ar->regiondata;
+ return ED_view3d_project_int_ex(ar, rv3d->persmatob, TRUE, co, r_co, flag);
+}
+
+/* --- float --- */
+eV3DProjStatus ED_view3d_project_float_global(ARegion *ar, const float co[3], float r_co[2], const eV3DProjTest flag)
+{
+ RegionView3D *rv3d = ar->regiondata;
+ return ED_view3d_project_float_ex(ar, rv3d->persmat, FALSE, co, r_co, flag);
+}
+/* object space, use ED_view3d_init_mats_rv3d before calling */
+eV3DProjStatus ED_view3d_project_float_object(ARegion *ar, const float co[3], float r_co[2], const eV3DProjTest flag)
+{
+ RegionView3D *rv3d = ar->regiondata;
+ return ED_view3d_project_float_ex(ar, rv3d->persmatob, TRUE, co, r_co, flag);
+}
+
+
+
+/* More Generic Window/Ray/Vector projection functions
+ * *************************************************** */
+
+/* odd function, need to document better */
+int initgrabz(RegionView3D *rv3d, float x, float y, float z)
+{
+ int flip = FALSE;
+ if (rv3d == NULL) return flip;
+ rv3d->zfac = rv3d->persmat[0][3] * x + rv3d->persmat[1][3] * y + rv3d->persmat[2][3] * z + rv3d->persmat[3][3];
+ if (rv3d->zfac < 0.0f)
+ flip = TRUE;
+ /* if x,y,z is exactly the viewport offset, zfac is 0 and we don't want that
+ * (accounting for near zero values)
+ */
+ if (rv3d->zfac < 1.e-6f && rv3d->zfac > -1.e-6f) rv3d->zfac = 1.0f;
+
+ /* Negative zfac means x, y, z was behind the camera (in perspective).
+ * This gives flipped directions, so revert back to ok default case.
+ */
+ /* NOTE: I've changed this to flip zfac to be positive again for now so that GPencil draws ok
+ * Aligorith, 2009Aug31 */
+ //if (rv3d->zfac < 0.0f) rv3d->zfac = 1.0f;
+ if (rv3d->zfac < 0.0f) rv3d->zfac = -rv3d->zfac;
+
+ return flip;
+}
+
+/**
+ * Calculate a 3d viewpoint and direction vector from 2d window coordinates.
+ * This ray_start is located at the viewpoint, ray_normal is the direction towards mval.
+ * ray_start is clipped by the view near limit so points in front of it are always in view.
+ * In orthographic view the resulting ray_normal will match the view vector.
+ * \param ar The region (used for the window width and height).
+ * \param v3d The 3d viewport (used for near clipping value).
+ * \param mval The area relative 2d location (such as event->mval, converted into float[2]).
+ * \param ray_start The world-space starting point of the segment.
+ * \param ray_normal The normalized world-space direction of towards mval.
+ */
+void ED_view3d_win_to_ray(ARegion *ar, View3D *v3d, const float mval[2], float ray_start[3], float ray_normal[3])
+{
+ float ray_end[3];
+
+ ED_view3d_win_to_segment_clip(ar, v3d, mval, ray_start, ray_end);
+ sub_v3_v3v3(ray_normal, ray_end, ray_start);
+ normalize_v3(ray_normal);
+}
+
+/**
+ * Calculate a normalized 3d direction vector from the viewpoint towards a global location.
+ * In orthographic view the resulting vector will match the view vector.
+ * \param rv3d The region (used for the window width and height).
+ * \param coord The world-space location.
+ * \param vec The resulting normalized vector.
+ */
+void ED_view3d_global_to_vector(RegionView3D *rv3d, const float coord[3], float vec[3])
+{
+ if (rv3d->is_persp) {
+ float p1[4], p2[4];
+
+ copy_v3_v3(p1, coord);
+ p1[3] = 1.0f;
+ copy_v3_v3(p2, p1);
+ p2[3] = 1.0f;
+ mul_m4_v4(rv3d->viewmat, p2);
+
+ mul_v3_fl(p2, 2.0f);
+
+ mul_m4_v4(rv3d->viewinv, p2);
+
+ sub_v3_v3v3(vec, p1, p2);
+ }
+ else {
+ copy_v3_v3(vec, rv3d->viewinv[2]);
+ }
+ normalize_v3(vec);
+}
+
+/**
+ * Calculate a 3d location from 2d window coordinates.
+ * \param ar The region (used for the window width and height).
+ * \param depth_pt The reference location used to calculate the Z depth.
+ * \param mval The area relative location (such as event->mval converted to floats).
+ * \param out The resulting world-space location.
+ */
+void ED_view3d_win_to_3d(ARegion *ar, const float depth_pt[3], const float mval[2], float out[3])
+{
+ RegionView3D *rv3d = ar->regiondata;
+
+ float line_sta[3];
+ float line_end[3];
+
+ if (rv3d->is_persp) {
+ float mousevec[3];
+ copy_v3_v3(line_sta, rv3d->viewinv[3]);
+ ED_view3d_win_to_vector(ar, mval, mousevec);
+ add_v3_v3v3(line_end, line_sta, mousevec);
+
+ if (isect_line_plane_v3(out, line_sta, line_end, depth_pt, rv3d->viewinv[2], TRUE) == 0) {
+ /* highly unlikely to ever happen, mouse vec paralelle with view plane */
+ zero_v3(out);
+ }
+ }
+ else {
+ const float dx = (2.0f * mval[0] / (float)ar->winx) - 1.0f;
+ const float dy = (2.0f * mval[1] / (float)ar->winy) - 1.0f;
+ line_sta[0] = (rv3d->persinv[0][0] * dx) + (rv3d->persinv[1][0] * dy) + rv3d->viewinv[3][0];
+ line_sta[1] = (rv3d->persinv[0][1] * dx) + (rv3d->persinv[1][1] * dy) + rv3d->viewinv[3][1];
+ line_sta[2] = (rv3d->persinv[0][2] * dx) + (rv3d->persinv[1][2] * dy) + rv3d->viewinv[3][2];
+
+ add_v3_v3v3(line_end, line_sta, rv3d->viewinv[2]);
+ closest_to_line_v3(out, depth_pt, line_sta, line_end);
+ }
+}
+
+/**
+ * Calculate a 3d difference vector from 2d window offset.
+ * note that initgrabz() must be called first to determine
+ * the depth used to calculate the delta.
+ * \param ar The region (used for the window width and height).
+ * \param mval The area relative 2d difference (such as event->mval[0] - other_x).
+ * \param out The resulting world-space delta.
+ */
+void ED_view3d_win_to_delta(ARegion *ar, const float mval[2], float out[3])
+{
+ RegionView3D *rv3d = ar->regiondata;
+ float dx, dy;
+
+ dx = 2.0f * mval[0] * rv3d->zfac / ar->winx;
+ dy = 2.0f * mval[1] * rv3d->zfac / ar->winy;
+
+ out[0] = (rv3d->persinv[0][0] * dx + rv3d->persinv[1][0] * dy);
+ out[1] = (rv3d->persinv[0][1] * dx + rv3d->persinv[1][1] * dy);
+ out[2] = (rv3d->persinv[0][2] * dx + rv3d->persinv[1][2] * dy);
+}
+
+/**
+ * Calculate a 3d direction vector from 2d window coordinates.
+ * This direction vector starts and the view in the direction of the 2d window coordinates.
+ * In orthographic view all window coordinates yield the same vector.
+ *
+ * \note doesn't rely on initgrabz
+ * for perspective view, get the vector direction to
+ * the mouse cursor as a normalized vector.
+ *
+ * \param ar The region (used for the window width and height).
+ * \param mval The area relative 2d location (such as event->mval converted to floats).
+ * \param out The resulting normalized world-space direction vector.
+ */
+void ED_view3d_win_to_vector(ARegion *ar, const float mval[2], float out[3])
+{
+ RegionView3D *rv3d = ar->regiondata;
+
+ if (rv3d->is_persp) {
+ out[0] = 2.0f * (mval[0] / ar->winx) - 1.0f;
+ out[1] = 2.0f * (mval[1] / ar->winy) - 1.0f;
+ out[2] = -0.5f;
+ mul_project_m4_v3(rv3d->persinv, out);
+ sub_v3_v3(out, rv3d->viewinv[3]);
+ }
+ else {
+ copy_v3_v3(out, rv3d->viewinv[2]);
+ }
+ normalize_v3(out);
+}
+
+/**
+ * Calculate a 3d segment from 2d window coordinates.
+ * This ray_start is located at the viewpoint, ray_end is a far point.
+ * ray_start and ray_end are clipped by the view near and far limits
+ * so points along this line are always in view.
+ * In orthographic view all resulting segments will be parallel.
+ * \param ar The region (used for the window width and height).
+ * \param v3d The 3d viewport (used for near and far clipping range).
+ * \param mval The area relative 2d location (such as event->mval, converted into float[2]).
+ * \param ray_start The world-space starting point of the segment.
+ * \param ray_end The world-space end point of the segment.
+ */
+void ED_view3d_win_to_segment_clip(ARegion *ar, View3D *v3d, const float mval[2], float ray_start[3], float ray_end[3])
+{
+ RegionView3D *rv3d = ar->regiondata;
+
+ if (rv3d->is_persp) {
+ float vec[3];
+ ED_view3d_win_to_vector(ar, mval, vec);
+
+ copy_v3_v3(ray_start, rv3d->viewinv[3]);
+ madd_v3_v3v3fl(ray_start, rv3d->viewinv[3], vec, v3d->near);
+ madd_v3_v3v3fl(ray_end, rv3d->viewinv[3], vec, v3d->far);
+ }
+ else {
+ float vec[4];
+ vec[0] = 2.0f * mval[0] / ar->winx - 1;
+ vec[1] = 2.0f * mval[1] / ar->winy - 1;
+ vec[2] = 0.0f;
+ vec[3] = 1.0f;
+
+ mul_m4_v4(rv3d->persinv, vec);
+
+ madd_v3_v3v3fl(ray_start, vec, rv3d->viewinv[2], 1000.0f);
+ madd_v3_v3v3fl(ray_end, vec, rv3d->viewinv[2], -1000.0f);
+ }
+
+ /* clipping */
+ if (rv3d->rflag & RV3D_CLIPPING) {
+ int a;
+ for (a = 0; a < 4; a++) {
+ clip_line_plane(ray_start, ray_end, rv3d->clip[a]);
+ }
+ }
+}
+
+
+/* Utility functions for projection
+ * ******************************** */
+
+void ED_view3d_ob_project_mat_get(RegionView3D *rv3d, Object *ob, float pmat[4][4])
+{
+ float vmat[4][4];
+
+ mult_m4_m4m4(vmat, rv3d->viewmat, ob->obmat);
+ mult_m4_m4m4(pmat, rv3d->winmat, vmat);
+}
+
+/**
+ * Uses window coordinates (x,y) and depth component z to find a point in
+ * modelspace */
+void ED_view3d_unproject(bglMats *mats, float out[3], const float x, const float y, const float z)
+{
+ double ux, uy, uz;
+
+ gluUnProject(x, y, z, mats->modelview, mats->projection,
+ (GLint *)mats->viewport, &ux, &uy, &uz);
+
+ out[0] = ux;
+ out[1] = uy;
+ out[2] = uz;
+}
diff --git a/source/blender/editors/space_view3d/view3d_select.c b/source/blender/editors/space_view3d/view3d_select.c
index 166a62562fd..43626b058d6 100644
--- a/source/blender/editors/space_view3d/view3d_select.c
+++ b/source/blender/editors/space_view3d/view3d_select.c
@@ -61,13 +61,14 @@
#include "IMB_imbuf.h"
#include "BKE_global.h"
-#include "BKE_context.h"
-#include "BKE_paint.h"
#include "BKE_armature.h"
+#include "BKE_context.h"
#include "BKE_depsgraph.h"
-#include "BKE_tessmesh.h"
+#include "BKE_mball.h"
#include "BKE_movieclip.h"
#include "BKE_object.h"
+#include "BKE_paint.h"
+#include "BKE_tessmesh.h"
#include "BKE_tracking.h"
@@ -110,15 +111,16 @@ int view3d_get_view_aligned_coordinate(ViewContext *vc, float fp[3], const int m
{
float dvec[3];
int mval_cpy[2];
+ eV3DProjStatus ret;
mval_cpy[0] = mval[0];
mval_cpy[1] = mval[1];
- project_int_noclip(vc->ar, fp, mval_cpy);
+ ret = ED_view3d_project_int_global(vc->ar, fp, mval_cpy, V3D_PROJ_TEST_NOP);
initgrabz(vc->rv3d, fp[0], fp[1], fp[2]);
- if (mval_cpy[0] != IS_CLIPPED) {
+ if (ret == V3D_PROJ_RET_OK) {
const float mval_f[2] = {(float)(mval_cpy[0] - mval[0]),
(float)(mval_cpy[1] - mval[1])};
ED_view3d_win_to_delta(vc->ar, mval_f, dvec);
@@ -163,7 +165,7 @@ void view3d_get_transformation(const ARegion *ar, RegionView3D *rv3d, Object *ob
mats->viewport[0] = ar->winrct.xmin;
mats->viewport[1] = ar->winrct.ymin;
mats->viewport[2] = ar->winx;
- mats->viewport[3] = ar->winy;
+ mats->viewport[3] = ar->winy;
}
/* ********************** view3d_select: selection manipulations ********************* */
@@ -255,10 +257,39 @@ static void edbm_backbuf_check_and_select_tfaces(Mesh *me, int select)
typedef struct LassoSelectUserData {
ViewContext *vc;
- rcti *rect;
- int (*mcords)[2], moves, select, pass, done;
+ const rcti *rect;
+ const rctf *rect_fl;
+ rctf _rect_fl;
+ const int (*mcords)[2];
+ int moves;
+ int select;
+
+ /* runtime */
+ int pass;
+ int is_done;
+ int is_change;
} LassoSelectUserData;
+static void view3d_userdata_lassoselect_init(LassoSelectUserData *r_data,
+ ViewContext *vc, const rcti *rect, const int (*mcords)[2],
+ const int moves, const int select)
+{
+ r_data->vc = vc;
+
+ r_data->rect = rect;
+ r_data->rect_fl = &r_data->_rect_fl;
+ BLI_rctf_rcti_copy(&r_data->_rect_fl, rect);
+
+ r_data->mcords = mcords;
+ r_data->moves = moves;
+ r_data->select = select;
+
+ /* runtime */
+ r_data->pass = 0;
+ r_data->is_done = FALSE;
+ r_data->is_change = FALSE;
+}
+
static int view3d_selectable_data(bContext *C)
{
Object *ob = CTX_data_active_object(C);
@@ -289,29 +320,29 @@ static int view3d_selectable_data(bContext *C)
/* helper also for borderselect */
-static int edge_fully_inside_rect(rcti *rect, short x1, short y1, short x2, short y2)
+static int edge_fully_inside_rect(const rctf *rect, const float v1[2], const float v2[2])
{
- return BLI_rcti_isect_pt(rect, x1, y1) && BLI_rcti_isect_pt(rect, x2, y2);
+ return BLI_rctf_isect_pt_v(rect, v1) && BLI_rctf_isect_pt_v(rect, v2);
}
-static int edge_inside_rect(rcti *rect, short x1, short y1, short x2, short y2)
+static int edge_inside_rect(const rctf *rect, const float v1[2], const float v2[2])
{
int d1, d2, d3, d4;
/* check points in rect */
- if (edge_fully_inside_rect(rect, x1, y1, x2, y2)) return 1;
+ if (edge_fully_inside_rect(rect, v1, v2)) return 1;
/* check points completely out rect */
- if (x1 < rect->xmin && x2 < rect->xmin) return 0;
- if (x1 > rect->xmax && x2 > rect->xmax) return 0;
- if (y1 < rect->ymin && y2 < rect->ymin) return 0;
- if (y1 > rect->ymax && y2 > rect->ymax) return 0;
+ if (v1[0] < rect->xmin && v2[0] < rect->xmin) return 0;
+ if (v1[0] > rect->xmax && v2[0] > rect->xmax) return 0;
+ if (v1[1] < rect->ymin && v2[1] < rect->ymin) return 0;
+ if (v1[1] > rect->ymax && v2[1] > rect->ymax) return 0;
/* simple check lines intersecting. */
- d1 = (y1 - y2) * (x1 - rect->xmin) + (x2 - x1) * (y1 - rect->ymin);
- d2 = (y1 - y2) * (x1 - rect->xmin) + (x2 - x1) * (y1 - rect->ymax);
- d3 = (y1 - y2) * (x1 - rect->xmax) + (x2 - x1) * (y1 - rect->ymax);
- d4 = (y1 - y2) * (x1 - rect->xmax) + (x2 - x1) * (y1 - rect->ymin);
+ d1 = (v1[1] - v2[1]) * (v1[0] - rect->xmin) + (v2[0] - v1[0]) * (v1[1] - rect->ymin);
+ d2 = (v1[1] - v2[1]) * (v1[0] - rect->xmin) + (v2[0] - v1[0]) * (v1[1] - rect->ymax);
+ d3 = (v1[1] - v2[1]) * (v1[0] - rect->xmax) + (v2[0] - v1[0]) * (v1[1] - rect->ymax);
+ d4 = (v1[1] - v2[1]) * (v1[0] - rect->xmax) + (v2[0] - v1[0]) * (v1[1] - rect->ymin);
if (d1 < 0 && d2 < 0 && d3 < 0 && d4 < 0) return 0;
if (d1 > 0 && d2 > 0 && d3 > 0 && d4 > 0) return 0;
@@ -319,40 +350,79 @@ static int edge_inside_rect(rcti *rect, short x1, short y1, short x2, short y2)
return 1;
}
+static void do_lasso_select_pose__doSelectBone(void *userData, struct bPoseChannel *pchan, const float screen_co_a[2], const float screen_co_b[2])
+{
+ LassoSelectUserData *data = userData;
+ bArmature *arm = data->vc->obact->data;
-#define MOVES_GESTURE 50
-#define MOVES_LASSO 500
+ if (PBONE_SELECTABLE(arm, pchan->bone)) {
+ int is_point_done = FALSE;
+ int points_proj_tot = 0;
+ const int x0 = screen_co_a[0];
+ const int y0 = screen_co_a[1];
+ const int x1 = screen_co_b[0];
+ const int y1 = screen_co_b[1];
-/* warning; lasso select with backbuffer-check draws in backbuf with persp(PERSP_WIN)
- * and returns with persp(PERSP_VIEW). After lasso select backbuf is not OK
- */
-static void do_lasso_select_pose(ViewContext *vc, Object *ob, int mcords[][2], short moves, short select)
-{
- bPoseChannel *pchan;
- float vec[3];
- int sco1[2], sco2[2];
- bArmature *arm = ob->data;
-
- if ((ob->type != OB_ARMATURE) || (ob->pose == NULL)) return;
+ /* project head location to screenspace */
+ if (x0 != IS_CLIPPED) {
+ points_proj_tot++;
+ if (BLI_rcti_isect_pt(data->rect, x0, y0) &&
+ BLI_lasso_is_point_inside(data->mcords, data->moves, x0, y0, INT_MAX))
+ {
+ is_point_done = TRUE;
+ }
+ }
- for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
- if (PBONE_VISIBLE(arm, pchan->bone) && (pchan->bone->flag & BONE_UNSELECTABLE) == 0) {
- mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
- project_int(vc->ar, vec, sco1);
- mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
- project_int(vc->ar, vec, sco2);
-
- if (BLI_lasso_is_edge_inside(mcords, moves, sco1[0], sco1[1], sco2[0], sco2[1], IS_CLIPPED)) {
- if (select) pchan->bone->flag |= BONE_SELECTED;
- else pchan->bone->flag &= ~BONE_SELECTED;
+ /* project tail location to screenspace */
+ if (x1 != IS_CLIPPED) {
+ points_proj_tot++;
+ if (BLI_rcti_isect_pt(data->rect, x1, y1) &&
+ BLI_lasso_is_point_inside(data->mcords, data->moves, x1, y1, INT_MAX))
+ {
+ is_point_done = TRUE;
}
}
+
+ /* if one of points selected, we skip the bone itself */
+ if ((is_point_done == TRUE) ||
+ ((is_point_done == FALSE) && (points_proj_tot == 2) &&
+ BLI_lasso_is_edge_inside(data->mcords, data->moves, x0, y0, x1, y1, INT_MAX)))
+ {
+ if (data->select) pchan->bone->flag |= BONE_SELECTED;
+ else pchan->bone->flag &= ~BONE_SELECTED;
+ data->is_change = TRUE;
+ }
+ data->is_change |= is_point_done;
}
+}
+static void do_lasso_select_pose(ViewContext *vc, Object *ob, const int mcords[][2], short moves, short select)
+{
+ ViewContext vc_tmp;
+ LassoSelectUserData data;
+ rcti rect;
- if (arm->flag & ARM_HAS_VIZ_DEPS) {
- /* mask modifier ('armature' mode), etc. */
- DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ if ((ob->type != OB_ARMATURE) || (ob->pose == NULL)) {
+ return;
+ }
+
+ vc_tmp = *vc;
+ vc_tmp.obact = ob;
+
+ BLI_lasso_boundbox(&rect, mcords, moves);
+
+ view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
+
+ ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d);
+
+ pose_foreachScreenBone(&vc_tmp, do_lasso_select_pose__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
+
+ if (data.is_change) {
+ bArmature *arm = ob->data;
+ if (arm->flag & ARM_HAS_VIZ_DEPS) {
+ /* mask modifier ('armature' mode), etc. */
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ }
}
}
@@ -367,7 +437,7 @@ static void object_deselect_all_visible(Scene *scene, View3D *v3d)
}
}
-static void do_lasso_select_objects(ViewContext *vc, int mcords[][2], short moves, short extend, short select)
+static void do_lasso_select_objects(ViewContext *vc, const int mcords[][2], const short moves, short extend, short select)
{
Base *base;
@@ -376,7 +446,7 @@ static void do_lasso_select_objects(ViewContext *vc, int mcords[][2], short move
for (base = vc->scene->base.first; base; base = base->next) {
if (BASE_SELECTABLE(vc->v3d, base)) { /* use this to avoid un-needed lasso lookups */
- project_short(vc->ar, base->object->obmat[3], &base->sx);
+ ED_view3d_project_base(vc->ar, base);
if (BLI_lasso_is_point_inside(mcords, moves, base->sx, base->sy, IS_CLIPPED)) {
if (select) ED_base_object_select(base, BA_SELECT);
@@ -390,28 +460,33 @@ static void do_lasso_select_objects(ViewContext *vc, int mcords[][2], short move
}
}
-static void do_lasso_select_mesh__doSelectVert(void *userData, BMVert *eve, int x, int y, int UNUSED(index))
+static void do_lasso_select_mesh__doSelectVert(void *userData, BMVert *eve, const float screen_co[2], int UNUSED(index))
{
LassoSelectUserData *data = userData;
- if (BLI_rcti_isect_pt(data->rect, x, y) &&
- BLI_lasso_is_point_inside(data->mcords, data->moves, x, y, IS_CLIPPED))
+ if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
+ BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED))
{
BM_vert_select_set(data->vc->em->bm, eve, data->select);
}
}
-static void do_lasso_select_mesh__doSelectEdge(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int index)
+static void do_lasso_select_mesh__doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index)
{
LassoSelectUserData *data = userData;
if (EDBM_backbuf_check(bm_solidoffs + index)) {
+ const int x0 = screen_co_a[0];
+ const int y0 = screen_co_a[1];
+ const int x1 = screen_co_b[0];
+ const int y1 = screen_co_b[1];
+
if (data->pass == 0) {
- if (edge_fully_inside_rect(data->rect, x0, y0, x1, y1) &&
+ if (edge_fully_inside_rect(data->rect_fl, screen_co_a, screen_co_b) &&
BLI_lasso_is_point_inside(data->mcords, data->moves, x0, y0, IS_CLIPPED) &&
BLI_lasso_is_point_inside(data->mcords, data->moves, x1, y1, IS_CLIPPED))
{
BM_edge_select_set(data->vc->em->bm, eed, data->select);
- data->done = TRUE;
+ data->is_done = TRUE;
}
}
else {
@@ -421,36 +496,30 @@ static void do_lasso_select_mesh__doSelectEdge(void *userData, BMEdge *eed, int
}
}
}
-static void do_lasso_select_mesh__doSelectFace(void *userData, BMFace *efa, int x, int y, int UNUSED(index))
+static void do_lasso_select_mesh__doSelectFace(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
{
LassoSelectUserData *data = userData;
- if (BLI_rcti_isect_pt(data->rect, x, y) &&
- BLI_lasso_is_point_inside(data->mcords, data->moves, x, y, IS_CLIPPED))
+ if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
+ BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED))
{
BM_face_select_set(data->vc->em->bm, efa, data->select);
}
}
-static void do_lasso_select_mesh(ViewContext *vc, int mcords[][2], short moves, short extend, short select)
+static void do_lasso_select_mesh(ViewContext *vc, const int mcords[][2], short moves, short extend, short select)
{
LassoSelectUserData data;
ToolSettings *ts = vc->scene->toolsettings;
rcti rect;
int bbsel;
- BLI_lasso_boundbox(&rect, mcords, moves);
-
/* set editmesh */
vc->em = BMEdit_FromObject(vc->obedit);
- data.vc = vc;
- data.rect = &rect;
- data.mcords = mcords;
- data.moves = moves;
- data.select = select;
- data.done = FALSE;
- data.pass = 0;
+ BLI_lasso_boundbox(&rect, mcords, moves);
+
+ view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
if (extend == 0 && select)
EDBM_flag_disable_all(vc->em, BM_ELEM_SELECT);
@@ -466,17 +535,17 @@ static void do_lasso_select_mesh(ViewContext *vc, int mcords[][2], short moves,
edbm_backbuf_check_and_select_verts(vc->em, select);
}
else {
- mesh_foreachScreenVert(vc, do_lasso_select_mesh__doSelectVert, &data, V3D_CLIP_TEST_RV3D_CLIPPING);
+ mesh_foreachScreenVert(vc, do_lasso_select_mesh__doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
}
if (ts->selectmode & SCE_SELECT_EDGE) {
/* Does both bbsel and non-bbsel versions (need screen cos for both) */
data.pass = 0;
- mesh_foreachScreenEdge(vc, do_lasso_select_mesh__doSelectEdge, &data, V3D_CLIP_TEST_OFF);
+ mesh_foreachScreenEdge(vc, do_lasso_select_mesh__doSelectEdge, &data, V3D_PROJ_TEST_NOP);
- if (data.done == 0) {
+ if (data.is_done == 0) {
data.pass = 1;
- mesh_foreachScreenEdge(vc, do_lasso_select_mesh__doSelectEdge, &data, V3D_CLIP_TEST_OFF);
+ mesh_foreachScreenEdge(vc, do_lasso_select_mesh__doSelectEdge, &data, V3D_PROJ_TEST_NOP);
}
}
@@ -485,7 +554,7 @@ static void do_lasso_select_mesh(ViewContext *vc, int mcords[][2], short moves,
edbm_backbuf_check_and_select_faces(vc->em, select);
}
else {
- mesh_foreachScreenFace(vc, do_lasso_select_mesh__doSelectFace, &data);
+ mesh_foreachScreenFace(vc, do_lasso_select_mesh__doSelectFace, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
}
@@ -493,16 +562,16 @@ static void do_lasso_select_mesh(ViewContext *vc, int mcords[][2], short moves,
EDBM_selectmode_flush(vc->em);
}
-static void do_lasso_select_curve__doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, int x, int y)
+static void do_lasso_select_curve__doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
{
LassoSelectUserData *data = userData;
Object *obedit = data->vc->obedit;
Curve *cu = (Curve *)obedit->data;
- if (BLI_lasso_is_point_inside(data->mcords, data->moves, x, y, IS_CLIPPED)) {
+ if (BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED)) {
if (bp) {
bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
- if (bp == cu->lastsel && !(bp->f1 & 1)) cu->lastsel = NULL;
+ if (bp == cu->lastsel && !(bp->f1 & SELECT)) cu->lastsel = NULL;
}
else {
if (cu->drawflag & CU_HIDE_HANDLES) {
@@ -521,129 +590,155 @@ static void do_lasso_select_curve__doSelect(void *userData, Nurb *UNUSED(nu), BP
}
}
- if (bezt == cu->lastsel && !(bezt->f2 & 1)) cu->lastsel = NULL;
+ if (bezt == cu->lastsel && !(bezt->f2 & SELECT)) cu->lastsel = NULL;
}
}
}
-static void do_lasso_select_curve(ViewContext *vc, int mcords[][2], short moves, short extend, short select)
+static void do_lasso_select_curve(ViewContext *vc, const int mcords[][2], short moves, short extend, short select)
{
LassoSelectUserData data;
+ rcti rect;
+
+ BLI_lasso_boundbox(&rect, mcords, moves);
- /* set vc->editnurb */
- data.vc = vc;
- data.mcords = mcords;
- data.moves = moves;
- data.select = select;
+ view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
if (extend == 0 && select)
CU_deselect_all(vc->obedit);
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
- nurbs_foreachScreenVert(vc, do_lasso_select_curve__doSelect, &data);
+ nurbs_foreachScreenVert(vc, do_lasso_select_curve__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
-static void do_lasso_select_lattice__doSelect(void *userData, BPoint *bp, int x, int y)
+static void do_lasso_select_lattice__doSelect(void *userData, BPoint *bp, const float screen_co[2])
{
LassoSelectUserData *data = userData;
- if (BLI_lasso_is_point_inside(data->mcords, data->moves, x, y, IS_CLIPPED)) {
+ if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
+ BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED)) {
bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
}
}
-static void do_lasso_select_lattice(ViewContext *vc, int mcords[][2], short moves, short extend, short select)
+static void do_lasso_select_lattice(ViewContext *vc, const int mcords[][2], short moves, short extend, short select)
{
LassoSelectUserData data;
+ rcti rect;
+
+ BLI_lasso_boundbox(&rect, mcords, moves);
- /* set editdata in vc */
- data.mcords = mcords;
- data.moves = moves;
- data.select = select;
+ view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
if (extend == 0 && select)
ED_setflagsLatt(vc->obedit, 0);
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
- lattice_foreachScreenVert(vc, do_lasso_select_lattice__doSelect, &data);
+ lattice_foreachScreenVert(vc, do_lasso_select_lattice__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
-static void do_lasso_select_armature(ViewContext *vc, int mcords[][2], short moves, short extend, short select)
+static void do_lasso_select_armature__doSelectBone(void *userData, struct EditBone *ebone, const float screen_co_a[2], const float screen_co_b[2])
{
- bArmature *arm = vc->obedit->data;
- EditBone *ebone;
- float vec[3];
- short sco1[2], sco2[2], didpoint;
- int change = FALSE;
+ LassoSelectUserData *data = userData;
+ bArmature *arm = data->vc->obedit->data;
- if (extend == 0 && select)
- ED_armature_deselect_all_visible(vc->obedit);
+ if (EBONE_SELECTABLE(arm, ebone)) {
+ int is_point_done = FALSE;
+ int points_proj_tot = 0;
- /* set editdata in vc */
-
- for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
- if (EBONE_VISIBLE(arm, ebone) && (ebone->flag & BONE_UNSELECTABLE) == 0) {
- mul_v3_m4v3(vec, vc->obedit->obmat, ebone->head);
- project_short(vc->ar, vec, sco1);
- mul_v3_m4v3(vec, vc->obedit->obmat, ebone->tail);
- project_short(vc->ar, vec, sco2);
-
- didpoint = 0;
- if (BLI_lasso_is_point_inside(mcords, moves, sco1[0], sco1[1], IS_CLIPPED)) {
- if (select) ebone->flag |= BONE_ROOTSEL;
- else ebone->flag &= ~BONE_ROOTSEL;
- didpoint = 1;
- change = TRUE;
- }
- if (BLI_lasso_is_point_inside(mcords, moves, sco2[0], sco2[1], IS_CLIPPED)) {
- if (select) ebone->flag |= BONE_TIPSEL;
- else ebone->flag &= ~BONE_TIPSEL;
- didpoint = 1;
- change = TRUE;
+ const int x0 = screen_co_a[0];
+ const int y0 = screen_co_a[1];
+ const int x1 = screen_co_b[0];
+ const int y1 = screen_co_b[1];
+
+ /* project head location to screenspace */
+ if (x0 != IS_CLIPPED) {
+ points_proj_tot++;
+ if (BLI_rcti_isect_pt(data->rect, x0, y0) &&
+ BLI_lasso_is_point_inside(data->mcords, data->moves, x0, y0, INT_MAX))
+ {
+ is_point_done = TRUE;
+ if (data->select) ebone->flag |= BONE_ROOTSEL;
+ else ebone->flag &= ~BONE_ROOTSEL;
}
- /* if one of points selected, we skip the bone itself */
- if (didpoint == 0 &&
- BLI_lasso_is_edge_inside(mcords, moves, sco1[0], sco1[1], sco2[0], sco2[1], IS_CLIPPED))
+ }
+
+ /* project tail location to screenspace */
+ if (x1 != IS_CLIPPED) {
+ points_proj_tot++;
+ if (BLI_rcti_isect_pt(data->rect, x1, y1) &&
+ BLI_lasso_is_point_inside(data->mcords, data->moves, x1, y1, INT_MAX))
{
- if (select) ebone->flag |= BONE_TIPSEL | BONE_ROOTSEL | BONE_SELECTED;
- else ebone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
- change = TRUE;
+ is_point_done = TRUE;
+ if (data->select) ebone->flag |= BONE_TIPSEL;
+ else ebone->flag &= ~BONE_TIPSEL;
}
}
+
+ /* if one of points selected, we skip the bone itself */
+ if ((is_point_done == FALSE) && (points_proj_tot == 2) &&
+ BLI_lasso_is_edge_inside(data->mcords, data->moves, x0, y0, x1, y1, INT_MAX))
+ {
+ if (data->select) ebone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
+ else ebone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
+ data->is_change = TRUE;
+ }
+
+ data->is_change |= is_point_done;
}
-
- if (change) {
+}
+
+static void do_lasso_select_armature(ViewContext *vc, const int mcords[][2], short moves, short extend, short select)
+{
+ LassoSelectUserData data;
+ rcti rect;
+
+ BLI_lasso_boundbox(&rect, mcords, moves);
+
+ view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
+
+ ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
+
+ if (extend == 0 && select)
+ ED_armature_deselect_all_visible(vc->obedit);
+
+ armature_foreachScreenBone(vc, do_lasso_select_armature__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
+
+ if (data.is_change) {
+ bArmature *arm = vc->obedit->data;
ED_armature_sync_selection(arm->edbo);
ED_armature_validate_active(arm);
WM_main_add_notifier(NC_OBJECT | ND_BONE_SELECT, vc->obedit);
}
}
+static void do_lasso_select_mball__doSelectElem(void *userData, struct MetaElem *ml, const float screen_co[2])
+{
+ LassoSelectUserData *data = userData;
-
-
-static void do_lasso_select_meta(ViewContext *vc, int mcords[][2], short moves, short extend, short select)
+ if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
+ BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], INT_MAX)) {
+ if (data->select) ml->flag |= SELECT;
+ else ml->flag &= ~SELECT;
+ data->is_change = TRUE;
+ }
+}
+static void do_lasso_select_meta(ViewContext *vc, const int mcords[][2], short moves, short extend, short select)
{
+ LassoSelectUserData data;
+ rcti rect;
+
MetaBall *mb = (MetaBall *)vc->obedit->data;
- MetaElem *ml;
- float vec[3];
- short sco[2];
- if (extend == 0 && select) {
- for (ml = mb->editelems->first; ml; ml = ml->next) {
- ml->flag &= ~SELECT;
- }
- }
+ if (extend == 0 && select)
+ BKE_mball_deselect_all(mb);
- for (ml = mb->editelems->first; ml; ml = ml->next) {
-
- mul_v3_m4v3(vec, vc->obedit->obmat, &ml->x);
- project_short(vc->ar, vec, sco);
+ BLI_lasso_boundbox(&rect, mcords, moves);
- if (BLI_lasso_is_point_inside(mcords, moves, sco[0], sco[1], IS_CLIPPED)) {
- if (select) ml->flag |= SELECT;
- else ml->flag &= ~SELECT;
- }
- }
+ view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
+
+ ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
+
+ mball_foreachScreenElem(vc, do_lasso_select_mball__doSelectElem, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
static int do_paintvert_box_select(ViewContext *vc, rcti *rect, int select, int extend)
@@ -654,8 +749,8 @@ static int do_paintvert_box_select(ViewContext *vc, rcti *rect, int select, int
unsigned int *rt;
int a, index;
char *selar;
- int sx = BLI_RCT_SIZE_X(rect) + 1;
- int sy = BLI_RCT_SIZE_Y(rect) + 1;
+ int sx = BLI_rcti_size_x(rect) + 1;
+ int sy = BLI_rcti_size_y(rect) + 1;
me = vc->obact->data;
@@ -705,7 +800,7 @@ static int do_paintvert_box_select(ViewContext *vc, rcti *rect, int select, int
return OPERATOR_FINISHED;
}
-static void do_lasso_select_paintvert(ViewContext *vc, int mcords[][2], short moves, short extend, short select)
+static void do_lasso_select_paintvert(ViewContext *vc, const int mcords[][2], short moves, short extend, short select)
{
Object *ob = vc->obact;
Mesh *me = ob ? ob->data : NULL;
@@ -727,7 +822,7 @@ static void do_lasso_select_paintvert(ViewContext *vc, int mcords[][2], short mo
paintvert_flush_flags(ob);
}
-static void do_lasso_select_paintface(ViewContext *vc, int mcords[][2], short moves, short extend, short select)
+static void do_lasso_select_paintface(ViewContext *vc, const int mcords[][2], short moves, short extend, short select)
{
Object *ob = vc->obact;
Mesh *me = ob ? ob->data : NULL;
@@ -782,7 +877,9 @@ static void do_lasso_select_node(int mcords[][2], short moves, short select)
}
#endif
-static void view3d_lasso_select(bContext *C, ViewContext *vc, int mcords[][2], short moves, short extend, short select)
+static void view3d_lasso_select(bContext *C, ViewContext *vc,
+ const int mcords[][2], short moves,
+ short extend, short select)
{
Object *ob = CTX_data_active_object(C);
@@ -791,9 +888,10 @@ static void view3d_lasso_select(bContext *C, ViewContext *vc, int mcords[][2], s
do_lasso_select_paintface(vc, mcords, moves, extend, select);
else if (paint_vertsel_test(ob))
do_lasso_select_paintvert(vc, mcords, moves, extend, select);
- else if (ob && ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT))
- ;
- else if (ob && ob->mode & OB_MODE_PARTICLE_EDIT)
+ else if (ob && (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT))) {
+ /* pass */
+ }
+ else if (ob && (ob->mode & OB_MODE_PARTICLE_EDIT))
PE_lasso_select(C, mcords, moves, extend, select);
else {
do_lasso_select_objects(vc, mcords, moves, extend, select);
@@ -833,7 +931,7 @@ static int view3d_lasso_select_exec(bContext *C, wmOperator *op)
{
ViewContext vc;
int mcords_tot;
- int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
+ const int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
if (mcords) {
short extend, select;
@@ -846,7 +944,7 @@ static int view3d_lasso_select_exec(bContext *C, wmOperator *op)
select = !RNA_boolean_get(op->ptr, "deselect");
view3d_lasso_select(C, &vc, mcords, mcords_tot, extend, select);
- MEM_freeN(mcords);
+ MEM_freeN((void *)mcords);
return OPERATOR_FINISHED;
}
@@ -1064,8 +1162,7 @@ static Base *object_mouse_select_menu(bContext *C, ViewContext *vc, unsigned int
}
else {
int temp, dist = 15;
-
- project_short(vc->ar, base->object->obmat[3], &base->sx);
+ ED_view3d_project_base(vc->ar, base);
temp = abs(base->sx - mval[0]) + abs(base->sy - mval[1]);
if (temp < dist)
@@ -1323,9 +1420,12 @@ static int mouse_select(bContext *C, const int mval[2], short extend, short dese
View3D *v3d = CTX_wm_view3d(C);
Scene *scene = CTX_data_scene(C);
Base *base, *startbase = NULL, *basact = NULL, *oldbasact = NULL;
- int temp, a, dist = 100;
+ int a;
+ float dist = 100.0f;
int retval = 0;
short hits;
+ const float mval_fl[2] = {(float)mval[0], (float)mval[1]};
+
/* setup view context for argument to callbacks */
view3d_set_viewcontext(C, &vc);
@@ -1346,14 +1446,16 @@ static int mouse_select(bContext *C, const int mval[2], short extend, short dese
base = startbase;
while (base) {
if (BASE_SELECTABLE(v3d, base)) {
- project_short(ar, base->object->obmat[3], &base->sx);
-
- temp = abs(base->sx - mval[0]) + abs(base->sy - mval[1]);
- if (base == BASACT) temp += 10;
- if (temp < dist) {
-
- dist = temp;
- basact = base;
+ float screen_co[2];
+ if (ED_view3d_project_float_global(ar, base->object->obmat[3], screen_co,
+ V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN) == V3D_PROJ_RET_OK)
+ {
+ float dist_temp = len_manhattan_v2v2(mval_fl, screen_co);
+ if (base == BASACT) dist_temp += 10.0f;
+ if (dist_temp < dist) {
+ dist = dist_temp;
+ basact = base;
+ }
}
}
base = base->next;
@@ -1400,7 +1502,7 @@ static int mouse_select(bContext *C, const int mval[2], short extend, short dese
}
/* index of bundle is 1<<16-based. if there's no "bone" index
- * in hight word, this buffer value belongs to camera,. not to bundle */
+ * in height word, this buffer value belongs to camera,. not to bundle */
if (buffer[4 * i + 3] & 0xFFFF0000) {
MovieClip *clip = BKE_object_movieclip_get(scene, basact->object, 0);
MovieTracking *tracking = &clip->tracking;
@@ -1443,7 +1545,8 @@ static int mouse_select(bContext *C, const int mval[2], short extend, short dese
}
}
}
- else if (ED_do_pose_selectbuffer(scene, basact, buffer, hits, extend, deselect, toggle) ) { /* then bone is found */
+ else if (ED_do_pose_selectbuffer(scene, basact, buffer, hits, extend, deselect, toggle) ) {
+ /* then bone is found */
/* we make the armature selected:
* not-selected active object in posemode won't work well for tools */
@@ -1518,27 +1621,48 @@ static int mouse_select(bContext *C, const int mval[2], short extend, short dese
typedef struct BoxSelectUserData {
ViewContext *vc;
- rcti *rect;
- int select, pass, done;
+ const rcti *rect;
+ const rctf *rect_fl;
+ rctf _rect_fl;
+ int select;
+
+ /* runtime */
+ int pass;
+ int is_done;
+ int is_change;
} BoxSelectUserData;
-int edge_inside_circle(int centx, int centy, int rad, int x1, int y1, int x2, int y2)
+static void view3d_userdata_boxselect_init(BoxSelectUserData *r_data,
+ ViewContext *vc, const rcti *rect, const int select)
{
- int radsq = rad * rad;
+ r_data->vc = vc;
+
+ r_data->rect = rect;
+ r_data->rect_fl = &r_data->_rect_fl;
+ BLI_rctf_rcti_copy(&r_data->_rect_fl, rect);
+
+ r_data->select = select;
+
+ /* runtime */
+ r_data->pass = 0;
+ r_data->is_done = FALSE;
+ r_data->is_change = FALSE;
+}
+
+int edge_inside_circle(const float cent[2], float radius, const float screen_co_a[2], const float screen_co_b[2])
+{
+ int radius_squared = radius * radius;
/* check points in circle itself */
- if ((x1 - centx) * (x1 - centx) + (y1 - centy) * (y1 - centy) <= radsq) {
+ if (len_squared_v2v2(cent, screen_co_a) <= radius_squared) {
return TRUE;
}
- else if ((x2 - centx) * (x2 - centx) + (y2 - centy) * (y2 - centy) <= radsq) {
+ if (len_squared_v2v2(cent, screen_co_b) <= radius_squared) {
return TRUE;
}
else {
- const float cent[2] = {centx, centy};
- const float v1[2] = {x1, y1};
- const float v2[2] = {x2, y2};
/* pointdistline */
- if (dist_squared_to_line_segment_v2(cent, v1, v2) < (float)radsq) {
+ if (dist_squared_to_line_segment_v2(cent, screen_co_a, screen_co_b) < (float)radius_squared) {
return TRUE;
}
}
@@ -1546,16 +1670,16 @@ int edge_inside_circle(int centx, int centy, int rad, int x1, int y1, int x2, in
return FALSE;
}
-static void do_nurbs_box_select__doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, int x, int y)
+static void do_nurbs_box_select__doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
{
BoxSelectUserData *data = userData;
Object *obedit = data->vc->obedit;
Curve *cu = (Curve *)obedit->data;
- if (BLI_rcti_isect_pt(data->rect, x, y)) {
+ if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
if (bp) {
bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
- if (bp == cu->lastsel && !(bp->f1 & 1)) cu->lastsel = NULL;
+ if (bp == cu->lastsel && !(bp->f1 & SELECT)) cu->lastsel = NULL;
}
else {
if (cu->drawflag & CU_HIDE_HANDLES) {
@@ -1574,7 +1698,7 @@ static void do_nurbs_box_select__doSelect(void *userData, Nurb *UNUSED(nu), BPoi
}
}
- if (bezt == cu->lastsel && !(bezt->f2 & 1)) cu->lastsel = NULL;
+ if (bezt == cu->lastsel && !(bezt->f2 & SELECT)) cu->lastsel = NULL;
}
}
}
@@ -1582,24 +1706,22 @@ static int do_nurbs_box_select(ViewContext *vc, rcti *rect, int select, int exte
{
BoxSelectUserData data;
- data.vc = vc;
- data.rect = rect;
- data.select = select;
+ view3d_userdata_boxselect_init(&data, vc, rect, select);
if (extend == 0 && select)
CU_deselect_all(vc->obedit);
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
- nurbs_foreachScreenVert(vc, do_nurbs_box_select__doSelect, &data);
+ nurbs_foreachScreenVert(vc, do_nurbs_box_select__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
return OPERATOR_FINISHED;
}
-static void do_lattice_box_select__doSelect(void *userData, BPoint *bp, int x, int y)
+static void do_lattice_box_select__doSelect(void *userData, BPoint *bp, const float screen_co[2])
{
BoxSelectUserData *data = userData;
- if (BLI_rcti_isect_pt(data->rect, x, y)) {
+ if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
}
}
@@ -1607,50 +1729,48 @@ static int do_lattice_box_select(ViewContext *vc, rcti *rect, int select, int ex
{
BoxSelectUserData data;
- data.vc = vc;
- data.rect = rect;
- data.select = select;
+ view3d_userdata_boxselect_init(&data, vc, rect, select);
if (extend == 0 && select)
ED_setflagsLatt(vc->obedit, 0);
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
- lattice_foreachScreenVert(vc, do_lattice_box_select__doSelect, &data);
+ lattice_foreachScreenVert(vc, do_lattice_box_select__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
return OPERATOR_FINISHED;
}
-static void do_mesh_box_select__doSelectVert(void *userData, BMVert *eve, int x, int y, int UNUSED(index))
+static void do_mesh_box_select__doSelectVert(void *userData, BMVert *eve, const float screen_co[2], int UNUSED(index))
{
BoxSelectUserData *data = userData;
- if (BLI_rcti_isect_pt(data->rect, x, y)) {
+ if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
BM_vert_select_set(data->vc->em->bm, eve, data->select);
}
}
-static void do_mesh_box_select__doSelectEdge(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int index)
+static void do_mesh_box_select__doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index)
{
BoxSelectUserData *data = userData;
if (EDBM_backbuf_check(bm_solidoffs + index)) {
if (data->pass == 0) {
- if (edge_fully_inside_rect(data->rect, x0, y0, x1, y1)) {
+ if (edge_fully_inside_rect(data->rect_fl, screen_co_a, screen_co_b)) {
BM_edge_select_set(data->vc->em->bm, eed, data->select);
- data->done = TRUE;
+ data->is_done = TRUE;
}
}
else {
- if (edge_inside_rect(data->rect, x0, y0, x1, y1)) {
+ if (edge_inside_rect(data->rect_fl, screen_co_a, screen_co_b)) {
BM_edge_select_set(data->vc->em->bm, eed, data->select);
}
}
}
}
-static void do_mesh_box_select__doSelectFace(void *userData, BMFace *efa, int x, int y, int UNUSED(index))
+static void do_mesh_box_select__doSelectFace(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
{
BoxSelectUserData *data = userData;
- if (BLI_rcti_isect_pt(data->rect, x, y)) {
+ if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
BM_face_select_set(data->vc->em->bm, efa, data->select);
}
}
@@ -1660,11 +1780,7 @@ static int do_mesh_box_select(ViewContext *vc, rcti *rect, int select, int exten
ToolSettings *ts = vc->scene->toolsettings;
int bbsel;
- data.vc = vc;
- data.rect = rect;
- data.select = select;
- data.pass = 0;
- data.done = FALSE;
+ view3d_userdata_boxselect_init(&data, vc, rect, select);
if (extend == 0 && select)
EDBM_flag_disable_all(vc->em, BM_ELEM_SELECT);
@@ -1680,18 +1796,18 @@ static int do_mesh_box_select(ViewContext *vc, rcti *rect, int select, int exten
edbm_backbuf_check_and_select_verts(vc->em, select);
}
else {
- mesh_foreachScreenVert(vc, do_mesh_box_select__doSelectVert, &data, V3D_CLIP_TEST_RV3D_CLIPPING);
+ mesh_foreachScreenVert(vc, do_mesh_box_select__doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
}
if (ts->selectmode & SCE_SELECT_EDGE) {
/* Does both bbsel and non-bbsel versions (need screen cos for both) */
data.pass = 0;
- mesh_foreachScreenEdge(vc, do_mesh_box_select__doSelectEdge, &data, V3D_CLIP_TEST_OFF);
+ mesh_foreachScreenEdge(vc, do_mesh_box_select__doSelectEdge, &data, V3D_PROJ_TEST_NOP);
- if (data.done == 0) {
+ if (data.is_done == 0) {
data.pass = 1;
- mesh_foreachScreenEdge(vc, do_mesh_box_select__doSelectEdge, &data, V3D_CLIP_TEST_OFF);
+ mesh_foreachScreenEdge(vc, do_mesh_box_select__doSelectEdge, &data, V3D_PROJ_TEST_NOP);
}
}
@@ -1700,7 +1816,7 @@ static int do_mesh_box_select(ViewContext *vc, rcti *rect, int select, int exten
edbm_backbuf_check_and_select_faces(vc->em, select);
}
else {
- mesh_foreachScreenFace(vc, do_mesh_box_select__doSelectFace, &data);
+ mesh_foreachScreenFace(vc, do_mesh_box_select__doSelectFace, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
}
@@ -1722,11 +1838,8 @@ static int do_meta_box_select(ViewContext *vc, rcti *rect, int select, int exten
hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, rect);
- if (extend == 0 && select) {
- for (ml = mb->editelems->first; ml; ml = ml->next) {
- ml->flag &= ~SELECT;
- }
- }
+ if (extend == 0 && select)
+ BKE_mball_deselect_all(mb);
for (ml = mb->editelems->first; ml; ml = ml->next) {
for (a = 0; a < hits; a++) {
@@ -1902,12 +2015,10 @@ static int do_object_pose_box_select(bContext *C, ViewContext *vc, rcti *rect, i
}
if (bone_selected) {
- Object *ob = base->object;
-
- if (ob && (ob->type == OB_ARMATURE)) {
- bArmature *arm = ob->data;
+ if (base->object && (base->object->type == OB_ARMATURE)) {
+ bArmature *arm = base->object->data;
- WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
+ WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, base->object);
if (arm && (arm->flag & ARM_HAS_VIZ_DEPS)) {
/* mask modifier ('armature' mode), etc. */
@@ -2145,35 +2256,52 @@ void VIEW3D_OT_select(wmOperatorType *ot)
typedef struct CircleSelectUserData {
ViewContext *vc;
short select;
- int mval[2];
+ int mval[2];
+ float mval_fl[2];
float radius;
+ float radius_squared;
+
+ /* runtime */
+ int is_change;
} CircleSelectUserData;
-static void mesh_circle_doSelectVert(void *userData, BMVert *eve, int x, int y, int UNUSED(index))
+static void view3d_userdata_circleselect_init(CircleSelectUserData *r_data,
+ ViewContext *vc, const int select, const int mval[2], const float rad)
+{
+ r_data->vc = vc;
+ r_data->select = select;
+ copy_v2_v2_int(r_data->mval, mval);
+ r_data->mval_fl[0] = mval[0];
+ r_data->mval_fl[1] = mval[1];
+
+ r_data->radius = rad;
+ r_data->radius_squared = rad * rad;
+
+ /* runtime */
+ r_data->is_change = FALSE;
+}
+
+static void mesh_circle_doSelectVert(void *userData, BMVert *eve, const float screen_co[2], int UNUSED(index))
{
CircleSelectUserData *data = userData;
- int mx = x - data->mval[0], my = y - data->mval[1];
- float r = sqrt(mx * mx + my * my);
- if (r <= data->radius) {
+ if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
BM_vert_select_set(data->vc->em->bm, eve, data->select);
}
}
-static void mesh_circle_doSelectEdge(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int UNUSED(index))
+static void mesh_circle_doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int UNUSED(index))
{
CircleSelectUserData *data = userData;
- if (edge_inside_circle(data->mval[0], data->mval[1], (int)data->radius, x0, y0, x1, y1)) {
+ if (edge_inside_circle(data->mval_fl, (int)data->radius, screen_co_a, screen_co_b)) {
BM_edge_select_set(data->vc->em->bm, eed, data->select);
}
}
-static void mesh_circle_doSelectFace(void *userData, BMFace *efa, int x, int y, int UNUSED(index))
+static void mesh_circle_doSelectFace(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
{
CircleSelectUserData *data = userData;
- int mx = x - data->mval[0], my = y - data->mval[1];
- float r = sqrt(mx * mx + my * my);
-
- if (r <= data->radius) {
+
+ if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
BM_face_select_set(data->vc->em->bm, efa, data->select);
}
}
@@ -2189,18 +2317,14 @@ static void mesh_circle_select(ViewContext *vc, int select, const int mval[2], f
vc->em = BMEdit_FromObject(vc->obedit);
- data.vc = vc;
- data.select = select;
- data.mval[0] = mval[0];
- data.mval[1] = mval[1];
- data.radius = rad;
+ view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
if (ts->selectmode & SCE_SELECT_VERTEX) {
if (bbsel) {
edbm_backbuf_check_and_select_verts(vc->em, select == LEFTMOUSE);
}
else {
- mesh_foreachScreenVert(vc, mesh_circle_doSelectVert, &data, V3D_CLIP_TEST_RV3D_CLIPPING);
+ mesh_foreachScreenVert(vc, mesh_circle_doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
}
@@ -2209,7 +2333,7 @@ static void mesh_circle_select(ViewContext *vc, int select, const int mval[2], f
edbm_backbuf_check_and_select_edges(vc->em, select == LEFTMOUSE);
}
else {
- mesh_foreachScreenEdge(vc, mesh_circle_doSelectEdge, &data, V3D_CLIP_TEST_OFF);
+ mesh_foreachScreenEdge(vc, mesh_circle_doSelectEdge, &data, V3D_PROJ_TEST_NOP);
}
}
@@ -2218,7 +2342,7 @@ static void mesh_circle_select(ViewContext *vc, int select, const int mval[2], f
edbm_backbuf_check_and_select_faces(vc->em, select == LEFTMOUSE);
}
else {
- mesh_foreachScreenFace(vc, mesh_circle_doSelectFace, &data);
+ mesh_foreachScreenFace(vc, mesh_circle_doSelectFace, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
}
@@ -2235,7 +2359,7 @@ static void paint_facesel_circle_select(ViewContext *vc, int select, const int m
if (me) {
bm_vertoffs = me->totpoly + 1; /* max index array */
- /* bbsel= */ /* UNUSED */ EDBM_backbuf_circle_init(vc, mval[0], mval[1], (short)(rad + 1.0f));
+ /* bbsel = */ /* UNUSED */ EDBM_backbuf_circle_init(vc, mval[0], mval[1], (short)(rad + 1.0f));
edbm_backbuf_check_and_select_tfaces(me, select == LEFTMOUSE);
EDBM_backbuf_free();
paintface_flush_flags(ob);
@@ -2252,7 +2376,7 @@ static void paint_vertsel_circle_select(ViewContext *vc, int select, const int m
if (me) {
bm_vertoffs = me->totvert + 1; /* max index array */
- /* bbsel= */ /* UNUSED */ EDBM_backbuf_circle_init(vc, mval[0], mval[1], (short)(rad + 1.0f));
+ /* bbsel = */ /* UNUSED */ EDBM_backbuf_circle_init(vc, mval[0], mval[1], (short)(rad + 1.0f));
edbm_backbuf_check_and_select_verts_obmode(me, select == LEFTMOUSE);
EDBM_backbuf_free();
@@ -2261,19 +2385,17 @@ static void paint_vertsel_circle_select(ViewContext *vc, int select, const int m
}
-static void nurbscurve_circle_doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, int x, int y)
+static void nurbscurve_circle_doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
{
CircleSelectUserData *data = userData;
- int mx = x - data->mval[0], my = y - data->mval[1];
- float r = sqrt(mx * mx + my * my);
Object *obedit = data->vc->obedit;
Curve *cu = (Curve *)obedit->data;
- if (r <= data->radius) {
+ if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
if (bp) {
bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
- if (bp == cu->lastsel && !(bp->f1 & 1)) cu->lastsel = NULL;
+ if (bp == cu->lastsel && !(bp->f1 & SELECT)) cu->lastsel = NULL;
}
else {
if (cu->drawflag & CU_HIDE_HANDLES) {
@@ -2292,7 +2414,7 @@ static void nurbscurve_circle_doSelect(void *userData, Nurb *UNUSED(nu), BPoint
}
}
- if (bezt == cu->lastsel && !(bezt->f2 & 1)) cu->lastsel = NULL;
+ if (bezt == cu->lastsel && !(bezt->f2 & SELECT)) cu->lastsel = NULL;
}
}
}
@@ -2300,26 +2422,18 @@ static void nurbscurve_circle_select(ViewContext *vc, int select, const int mval
{
CircleSelectUserData data;
- /* set vc-> edit data */
-
- data.select = select;
- data.mval[0] = mval[0];
- data.mval[1] = mval[1];
- data.radius = rad;
- data.vc = vc;
+ view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
- nurbs_foreachScreenVert(vc, nurbscurve_circle_doSelect, &data);
+ nurbs_foreachScreenVert(vc, nurbscurve_circle_doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
-static void latticecurve_circle_doSelect(void *userData, BPoint *bp, int x, int y)
+static void latticecurve_circle_doSelect(void *userData, BPoint *bp, const float screen_co[2])
{
CircleSelectUserData *data = userData;
- int mx = x - data->mval[0], my = y - data->mval[1];
- float r = sqrt(mx * mx + my * my);
- if (r <= data->radius) {
+ if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
}
}
@@ -2327,26 +2441,19 @@ static void lattice_circle_select(ViewContext *vc, int select, const int mval[2]
{
CircleSelectUserData data;
- /* set vc-> edit data */
-
- data.select = select;
- data.mval[0] = mval[0];
- data.mval[1] = mval[1];
- data.radius = rad;
+ view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
- lattice_foreachScreenVert(vc, latticecurve_circle_doSelect, &data);
+ lattice_foreachScreenVert(vc, latticecurve_circle_doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
/* NOTE: pose-bone case is copied from editbone case... */
-static short pchan_circle_doSelectJoint(void *userData, bPoseChannel *pchan, int x, int y)
+static short pchan_circle_doSelectJoint(void *userData, bPoseChannel *pchan, const float screen_co[2])
{
CircleSelectUserData *data = userData;
- int mx = x - data->mval[0], my = y - data->mval[1];
- float r = sqrt(mx * mx + my * my);
-
- if (r <= data->radius) {
+
+ if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
if (data->select)
pchan->bone->flag |= BONE_SELECTED;
else
@@ -2355,63 +2462,76 @@ static short pchan_circle_doSelectJoint(void *userData, bPoseChannel *pchan, int
}
return 0;
}
+static void do_circle_select_pose__doSelectBone(void *userData, struct bPoseChannel *pchan, const float screen_co_a[2], const float screen_co_b[2])
+{
+ CircleSelectUserData *data = userData;
+ bArmature *arm = data->vc->obact->data;
+
+ if (PBONE_SELECTABLE(arm, pchan->bone)) {
+ int is_point_done = FALSE;
+ int points_proj_tot = 0;
+
+ /* project head location to screenspace */
+ if (screen_co_a[0] != IS_CLIPPED) {
+ points_proj_tot++;
+ if (pchan_circle_doSelectJoint(data, pchan, screen_co_a)) {
+ is_point_done = TRUE;
+ }
+ }
+
+ /* project tail location to screenspace */
+ if (screen_co_b[0] != IS_CLIPPED) {
+ points_proj_tot++;
+ if (pchan_circle_doSelectJoint(data, pchan, screen_co_a)) {
+ is_point_done = TRUE;
+ }
+ }
+
+ /* check if the head and/or tail is in the circle
+ * - the call to check also does the selection already
+ */
+
+ /* only if the endpoints didn't get selected, deal with the middle of the bone too
+ * It works nicer to only do this if the head or tail are not in the circle,
+ * otherwise there is no way to circle select joints alone */
+ if ((is_point_done == FALSE) && (points_proj_tot == 2) &&
+ edge_inside_circle(data->mval_fl, data->radius, screen_co_a, screen_co_b))
+ {
+ if (data->select) pchan->bone->flag |= BONE_SELECTED;
+ else pchan->bone->flag &= ~BONE_SELECTED;
+ data->is_change = TRUE;
+ }
+
+ data->is_change |= is_point_done;
+ }
+}
static void pose_circle_select(ViewContext *vc, int select, const int mval[2], float rad)
{
CircleSelectUserData data;
- bArmature *arm = vc->obact->data;
- bPose *pose = vc->obact->pose;
- bPoseChannel *pchan;
- int change = FALSE;
- /* set vc->edit data */
- data.select = select;
- data.mval[0] = mval[0];
- data.mval[1] = mval[1];
- data.radius = rad;
+ view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d); /* for foreach's screen/vert projection */
- /* check each PoseChannel... */
- /* TODO: could be optimized at some point */
- for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
- short sco1[2], sco2[2], didpoint = 0;
- float vec[3];
-
- /* skip invisible bones */
- if (PBONE_VISIBLE(arm, pchan->bone) == 0)
- continue;
-
- /* project head location to screenspace */
- mul_v3_m4v3(vec, vc->obact->obmat, pchan->pose_head);
- project_short(vc->ar, vec, sco1);
-
- /* project tail location to screenspace */
- mul_v3_m4v3(vec, vc->obact->obmat, pchan->pose_tail);
- project_short(vc->ar, vec, sco2);
-
- /* check if the head and/or tail is in the circle
- * - the call to check also does the selection already
- */
- if (pchan_circle_doSelectJoint(&data, pchan, sco1[0], sco1[1]))
- didpoint = 1;
- if (pchan_circle_doSelectJoint(&data, pchan, sco2[0], sco2[1]))
- didpoint = 1;
-
- change |= didpoint;
- }
+ pose_foreachScreenBone(vc, do_circle_select_pose__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
+
+ if (data.is_change) {
+ bArmature *arm = vc->obact->data;
- if (change) {
WM_main_add_notifier(NC_OBJECT | ND_BONE_SELECT, vc->obact);
+
+ if (arm->flag & ARM_HAS_VIZ_DEPS) {
+ /* mask modifier ('armature' mode), etc. */
+ DAG_id_tag_update(&vc->obact->id, OB_RECALC_DATA);
+ }
}
}
-static short armature_circle_doSelectJoint(void *userData, EditBone *ebone, int x, int y, short head)
+static short armature_circle_doSelectJoint(void *userData, EditBone *ebone, const float screen_co[2], short head)
{
CircleSelectUserData *data = userData;
- int mx = x - data->mval[0], my = y - data->mval[1];
- float r = sqrt(mx * mx + my * my);
-
- if (r <= data->radius) {
+
+ if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
if (head) {
if (data->select)
ebone->flag |= BONE_ROOTSEL;
@@ -2428,63 +2548,88 @@ static short armature_circle_doSelectJoint(void *userData, EditBone *ebone, int
}
return 0;
}
-static void armature_circle_select(ViewContext *vc, int select, const int mval[2], float rad)
+static void do_circle_select_armature__doSelectBone(void *userData, struct EditBone *ebone, const float screen_co_a[2], const float screen_co_b[2])
{
- CircleSelectUserData data;
- bArmature *arm = vc->obedit->data;
- EditBone *ebone;
- int change = FALSE;
-
- /* set vc->edit data */
- data.select = select;
- data.mval[0] = mval[0];
- data.mval[1] = mval[1];
- data.radius = rad;
+ CircleSelectUserData *data = userData;
+ bArmature *arm = data->vc->obedit->data;
+
+ if (EBONE_SELECTABLE(arm, ebone)) {
+ int is_point_done = FALSE;
+ int points_proj_tot = 0;
- ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
-
- /* check each EditBone... */
- /* TODO: could be optimized at some point */
- for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
- short sco1[2], sco2[2], didpoint = 0;
- float vec[3];
-
/* project head location to screenspace */
- mul_v3_m4v3(vec, vc->obedit->obmat, ebone->head);
- project_short(vc->ar, vec, sco1);
-
+ if (screen_co_a[0] != IS_CLIPPED) {
+ points_proj_tot++;
+ if (armature_circle_doSelectJoint(data, ebone, screen_co_a, TRUE)) {
+ is_point_done = TRUE;
+ }
+ }
+
/* project tail location to screenspace */
- mul_v3_m4v3(vec, vc->obedit->obmat, ebone->tail);
- project_short(vc->ar, vec, sco2);
-
- /* check if the head and/or tail is in the circle
- * - the call to check also does the selection already
+ if (screen_co_b[0] != IS_CLIPPED) {
+ points_proj_tot++;
+ if (armature_circle_doSelectJoint(data, ebone, screen_co_b, FALSE)) {
+ is_point_done = TRUE;
+ }
+ }
+
+ /* check if the head and/or tail is in the circle
+ * - the call to check also does the selection already
*/
- if (armature_circle_doSelectJoint(&data, ebone, sco1[0], sco1[1], 1))
- didpoint = 1;
- if (armature_circle_doSelectJoint(&data, ebone, sco2[0], sco2[1], 0))
- didpoint = 1;
-
- /* only if the endpoints didn't get selected, deal with the middle of the bone too */
- /* XXX should we just do this always? */
- if ((didpoint == 0) && edge_inside_circle(mval[0], mval[1], rad, sco1[0], sco1[1], sco2[0], sco2[1])) {
- if (select)
- ebone->flag |= BONE_TIPSEL | BONE_ROOTSEL | BONE_SELECTED;
- else
- ebone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
- change = TRUE;
+
+ /* only if the endpoints didn't get selected, deal with the middle of the bone too
+ * It works nicer to only do this if the head or tail are not in the circle,
+ * otherwise there is no way to circle select joints alone */
+ if ((is_point_done == FALSE) && (points_proj_tot == 2) &&
+ edge_inside_circle(data->mval_fl, data->radius, screen_co_a, screen_co_b))
+ {
+ if (data->select) ebone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
+ else ebone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
+ data->is_change = TRUE;
}
-
- change |= didpoint;
+
+ data->is_change |= is_point_done;
}
+}
+static void armature_circle_select(ViewContext *vc, int select, const int mval[2], float rad)
+{
+ CircleSelectUserData data;
+ bArmature *arm = vc->obedit->data;
+
+ view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
+
+ ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
+
+ armature_foreachScreenBone(vc, do_circle_select_armature__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
- if (change) {
+ if (data.is_change) {
ED_armature_sync_selection(arm->edbo);
ED_armature_validate_active(arm);
WM_main_add_notifier(NC_OBJECT | ND_BONE_SELECT, vc->obedit);
}
}
+static void do_circle_select_mball__doSelectElem(void *userData, struct MetaElem *ml, const float screen_co[2])
+{
+ CircleSelectUserData *data = userData;
+
+ if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
+ if (data->select) ml->flag |= SELECT;
+ else ml->flag &= ~SELECT;
+ data->is_change = TRUE;
+ }
+}
+static void mball_circle_select(ViewContext *vc, int select, const int mval[2], float rad)
+{
+ CircleSelectUserData data;
+
+ view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
+
+ ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
+
+ mball_foreachScreenElem(vc, do_circle_select_mball__doSelectElem, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
+}
+
/** Callbacks for circle selection in Editmode */
static void obedit_circle_select(ViewContext *vc, short select, const int mval[2], float rad)
@@ -2503,24 +2648,51 @@ static void obedit_circle_select(ViewContext *vc, short select, const int mval[2
case OB_ARMATURE:
armature_circle_select(vc, select, mval, rad);
break;
+ case OB_MBALL:
+ mball_circle_select(vc, select, mval, rad);
+ break;
default:
return;
}
}
+static int object_circle_select(ViewContext *vc, int select, const int mval[2], float rad)
+{
+ Scene *scene = vc->scene;
+ const float radius_squared = rad * rad;
+ const float mval_fl[2] = {mval[0], mval[1]};
+ int is_change = FALSE;
+ int select_flag = select ? SELECT : 0;
+
+ Base *base;
+ select = select ? BA_SELECT : BA_DESELECT;
+ for (base = FIRSTBASE; base; base = base->next) {
+ if (BASE_SELECTABLE(vc->v3d, base) && ((base->flag & SELECT) != select_flag)) {
+ float screen_co[2];
+ if (ED_view3d_project_float_global(vc->ar, base->object->obmat[3], screen_co,
+ V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN) == V3D_PROJ_RET_OK)
+ {
+ if (len_squared_v2v2(mval_fl, screen_co) <= radius_squared) {
+ ED_base_object_select(base, select);
+ is_change = TRUE;
+ }
+ }
+ }
+ }
+
+ return is_change;
+}
+
/* not a real operator, only for circle test */
static int view3d_circle_select_exec(bContext *C, wmOperator *op)
{
- ScrArea *sa = CTX_wm_area(C);
- ARegion *ar = CTX_wm_region(C);
Scene *scene = CTX_data_scene(C);
Object *obact = CTX_data_active_object(C);
- View3D *v3d = sa->spacedata.first;
- int x = RNA_int_get(op->ptr, "x");
- int y = RNA_int_get(op->ptr, "y");
int radius = RNA_int_get(op->ptr, "radius");
int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
int select;
+ const int mval[2] = {RNA_int_get(op->ptr, "x"),
+ RNA_int_get(op->ptr, "y")};
select = (gesture_mode == GESTURE_MODAL_SELECT);
@@ -2528,13 +2700,10 @@ static int view3d_circle_select_exec(bContext *C, wmOperator *op)
(obact && (obact->mode & (OB_MODE_PARTICLE_EDIT | OB_MODE_POSE))) )
{
ViewContext vc;
- int mval[2];
view3d_operator_needs_opengl(C);
view3d_set_viewcontext(C, &vc);
- mval[0] = x;
- mval[1] = y;
if (CTX_data_edit_object(C)) {
obedit_circle_select(&vc, select, mval, (float)radius);
@@ -2557,21 +2726,12 @@ static int view3d_circle_select_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
else {
- Base *base;
- select = select ? BA_SELECT : BA_DESELECT;
- for (base = FIRSTBASE; base; base = base->next) {
- if (BASE_SELECTABLE(v3d, base)) {
- project_short(ar, base->object->obmat[3], &base->sx);
- if (base->sx != IS_CLIPPED) {
- int dx = base->sx - x;
- int dy = base->sy - y;
- if (dx * dx + dy * dy < radius * radius)
- ED_base_object_select(base, select);
- }
- }
+ ViewContext vc;
+ view3d_set_viewcontext(C, &vc);
+
+ if (object_circle_select(&vc, select, mval, (float)radius)) {
+ WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
}
-
- WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, CTX_data_scene(C));
}
return OPERATOR_FINISHED;
diff --git a/source/blender/editors/space_view3d/view3d_snap.c b/source/blender/editors/space_view3d/view3d_snap.c
index 4ca9bd95485..7f1bbb22f24 100644
--- a/source/blender/editors/space_view3d/view3d_snap.c
+++ b/source/blender/editors/space_view3d/view3d_snap.c
@@ -82,10 +82,9 @@ extern float originmat[3][3]; /* XXX object.c */
typedef struct TransVert {
float *loc;
- float oldloc[3], maploc[3], fac;
+ float oldloc[3], maploc[3];
float *val, oldval;
int flag;
- float *nor;
} TransVert;
/* SELECT == (1 << 0) */
@@ -193,6 +192,20 @@ static void special_transvert_update(Object *obedit)
}
}
+/* currently only used for bmesh index values */
+enum {
+ TM_INDEX_ON = 1, /* tag to make trans verts */
+ TM_INDEX_OFF = 0, /* don't make verts */
+ TM_INDEX_SKIP = -1 /* dont make verts (when the index values point to trans-verts) */
+};
+
+/* copied from editobject.c, needs to be replaced with new transform code still */
+/* mode flags: */
+enum {
+ TM_ALL_JOINTS = 1, /* all joints (for bones only) */
+ TM_SKIP_HANDLES = 2 /* skip handles when control point is selected (for curves only) */
+};
+
static void set_mapped_co(void *vuserdata, int index, const float co[3],
const float UNUSED(no[3]), const short UNUSED(no_s[3]))
{
@@ -201,16 +214,25 @@ static void set_mapped_co(void *vuserdata, int index, const float co[3],
TransVert *tv = userdata[1];
BMVert *eve = EDBM_vert_at_index(em, index);
- if (BM_elem_index_get(eve) != -1 && !(tv[BM_elem_index_get(eve)].flag & TX_VERT_USE_MAPLOC)) {
- copy_v3_v3(tv[BM_elem_index_get(eve)].maploc, co);
- tv[BM_elem_index_get(eve)].flag |= TX_VERT_USE_MAPLOC;
+ if (BM_elem_index_get(eve) != TM_INDEX_SKIP) {
+ tv = &tv[BM_elem_index_get(eve)];
+
+ /* be clever, get the closest vertex to the original,
+ * behaves most logically when the mirror modifier is used for eg [#33051]*/
+ if ((tv->flag & TX_VERT_USE_MAPLOC) == 0) {
+ /* first time */
+ copy_v3_v3(tv->maploc, co);
+ tv->flag |= TX_VERT_USE_MAPLOC;
+ }
+ else {
+ /* find best location to use */
+ if (len_squared_v3v3(eve->co, co) < len_squared_v3v3(eve->co, tv->maploc)) {
+ copy_v3_v3(tv->maploc, co);
+ }
+ }
}
}
-/* copied from editobject.c, needs to be replaced with new transform code still */
-/* mode flags: */
-#define TM_ALL_JOINTS 1 /* all joints (for bones only) */
-#define TM_SKIP_HANDLES 2 /* skip handles when control point is selected (for curves only) */
static void make_trans_verts(Object *obedit, float min[3], float max[3], int mode)
{
Nurb *nu;
@@ -233,7 +255,7 @@ static void make_trans_verts(Object *obedit, float min[3], float max[3], int mod
BMesh *bm = em->bm;
BMIter iter;
void *userdata[2] = {em, NULL};
- /*int proptrans= 0; */ /*UNUSED*/
+ /*int proptrans = 0; */ /*UNUSED*/
/* abuses vertex index all over, set, just set dirty here,
* perhaps this could use its own array instead? - campbell */
@@ -243,35 +265,37 @@ static void make_trans_verts(Object *obedit, float min[3], float max[3], int mod
if (em->selectmode & SCE_SELECT_VERTEX) {
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN) && BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
- BM_elem_index_set(eve, 1); /* set_dirty! */
+ BM_elem_index_set(eve, TM_INDEX_ON); /* set_dirty! */
tottrans++;
}
- else BM_elem_index_set(eve, 0); /* set_dirty! */
+ else {
+ BM_elem_index_set(eve, TM_INDEX_OFF); /* set_dirty! */
+ }
}
}
else if (em->selectmode & SCE_SELECT_EDGE) {
BMEdge *eed;
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
- BM_elem_index_set(eve, 0); /* set_dirty! */
+ BM_elem_index_set(eve, TM_INDEX_OFF); /* set_dirty! */
}
BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
- BM_elem_index_set(eed->v1, 1); /* set_dirty! */
- BM_elem_index_set(eed->v2, 1); /* set_dirty! */
+ BM_elem_index_set(eed->v1, TM_INDEX_ON); /* set_dirty! */
+ BM_elem_index_set(eed->v2, TM_INDEX_ON); /* set_dirty! */
}
}
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
- if (BM_elem_index_get(eve)) tottrans++;
+ if (BM_elem_index_get(eve) == TM_INDEX_ON) tottrans++;
}
}
else {
BMFace *efa;
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
- BM_elem_index_set(eve, 0); /* set_dirty! */
+ BM_elem_index_set(eve, TM_INDEX_OFF); /* set_dirty! */
}
BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
@@ -280,13 +304,13 @@ static void make_trans_verts(Object *obedit, float min[3], float max[3], int mod
BMLoop *l;
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
- BM_elem_index_set(l->v, 1); /* set_dirty! */
+ BM_elem_index_set(l->v, TM_INDEX_ON); /* set_dirty! */
}
}
}
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
- if (BM_elem_index_get(eve)) tottrans++;
+ if (BM_elem_index_get(eve) == TM_INDEX_ON) tottrans++;
}
}
/* for any of the 3 loops above which all dirty the indices */
@@ -299,17 +323,15 @@ static void make_trans_verts(Object *obedit, float min[3], float max[3], int mod
a = 0;
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_index_get(eve)) {
- BM_elem_index_set(eve, a); /* set_dirty! */
+ BM_elem_index_set(eve, a); /* set_dirty! */
copy_v3_v3(tv->oldloc, eve->co);
tv->loc = eve->co;
- if (eve->no[0] != 0.0f || eve->no[1] != 0.0f || eve->no[2] != 0.0f)
- tv->nor = eve->no; /* note this is a hackish signal (ton) */
- tv->flag = BM_elem_index_get(eve) & SELECT;
+ tv->flag = (BM_elem_index_get(eve) == TM_INDEX_ON) ? SELECT : 0;
tv++;
a++;
}
else {
- BM_elem_index_set(eve, -1); /* set_dirty! */
+ BM_elem_index_set(eve, TM_INDEX_SKIP); /* set_dirty! */
}
}
/* set dirty already, above */
@@ -345,17 +367,15 @@ static void make_trans_verts(Object *obedit, float min[3], float max[3], int mod
if (rootok) {
copy_v3_v3(tv->oldloc, ebo->head);
tv->loc = ebo->head;
- tv->nor = NULL;
- tv->flag = 1;
+ tv->flag = SELECT;
tv++;
tottrans++;
- }
+ }
if ((mode & TM_ALL_JOINTS) && (tipsel)) {
copy_v3_v3(tv->oldloc, ebo->tail);
tv->loc = ebo->tail;
- tv->nor = NULL;
- tv->flag = 1;
+ tv->flag = SELECT;
tv++;
tottrans++;
}
@@ -363,8 +383,7 @@ static void make_trans_verts(Object *obedit, float min[3], float max[3], int mod
else if (tipsel) {
copy_v3_v3(tv->oldloc, ebo->tail);
tv->loc = ebo->tail;
- tv->nor = NULL;
- tv->flag = 1;
+ tv->flag = SELECT;
tv++;
tottrans++;
}
@@ -456,7 +475,7 @@ static void make_trans_verts(Object *obedit, float min[3], float max[3], int mod
copy_v3_v3(tv->oldloc, tv->loc);
tv->val = &(ml->rad);
tv->oldval = ml->rad;
- tv->flag = 1;
+ tv->flag = SELECT;
tv++;
tottrans++;
}
@@ -607,9 +626,9 @@ static int snap_sel_to_grid(bContext *C, wmOperator *UNUSED(op))
else {
ob->recalc |= OB_RECALC_OB;
- vec[0] = -ob->obmat[3][0] + gridf *floorf(0.5f + ob->obmat[3][0] / gridf);
- vec[1] = -ob->obmat[3][1] + gridf *floorf(0.5f + ob->obmat[3][1] / gridf);
- vec[2] = -ob->obmat[3][2] + gridf *floorf(0.5f + ob->obmat[3][2] / gridf);
+ vec[0] = -ob->obmat[3][0] + gridf * floorf(0.5f + ob->obmat[3][0] / gridf);
+ vec[1] = -ob->obmat[3][1] + gridf * floorf(0.5f + ob->obmat[3][1] / gridf);
+ vec[2] = -ob->obmat[3][2] + gridf * floorf(0.5f + ob->obmat[3][2] / gridf);
if (ob->parent) {
BKE_object_where_is_calc(scene, ob);
diff --git a/source/blender/editors/space_view3d/view3d_toolbar.c b/source/blender/editors/space_view3d/view3d_toolbar.c
index b40e880591a..d36b0085acb 100644
--- a/source/blender/editors/space_view3d/view3d_toolbar.c
+++ b/source/blender/editors/space_view3d/view3d_toolbar.c
@@ -173,7 +173,7 @@ static uiBlock *tool_search_menu(bContext *C, ARegion *ar, void *arg_listbase)
search[0] = 0;
block = uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
- uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_REDRAW | UI_BLOCK_RET_1);
+ uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_REDRAW | UI_BLOCK_SEARCH_MENU);
/* fake button, it holds space for search items */
uiDefBut(block, LABEL, 0, "", 10, 15, 150, uiSearchBoxhHeight(), NULL, 0, 0, 0, 0, NULL);
@@ -182,7 +182,7 @@ static uiBlock *tool_search_menu(bContext *C, ARegion *ar, void *arg_listbase)
uiButSetSearchFunc(but, operator_search_cb, arg_listbase, operator_call_cb, NULL);
uiBoundsBlock(block, 6);
- uiBlockSetDirection(block, UI_DOWN);
+ uiBlockSetDirection(block, UI_DOWN);
uiEndBlock(C, block);
event = *(win->eventstate); /* XXX huh huh? make api call */
diff --git a/source/blender/editors/space_view3d/view3d_view.c b/source/blender/editors/space_view3d/view3d_view.c
index c25bb80bfde..c16f04f01f3 100644
--- a/source/blender/editors/space_view3d/view3d_view.c
+++ b/source/blender/editors/space_view3d/view3d_view.c
@@ -125,7 +125,7 @@ struct SmoothView3DStore {
/* will start timer if appropriate */
/* the arguments are the desired situation */
void view3d_smooth_view(bContext *C, View3D *v3d, ARegion *ar, Object *oldcamera, Object *camera,
- float *ofs, float *quat, float *dist, float *lens)
+ float *ofs, float *quat, float *dist, float *lens)
{
wmWindowManager *wm = CTX_wm_manager(C);
wmWindow *win = CTX_wm_window(C);
@@ -140,7 +140,7 @@ void view3d_smooth_view(bContext *C, View3D *v3d, ARegion *ar, Object *oldcamera
copy_qt_qt(sms.new_quat, rv3d->viewquat);
sms.new_dist = rv3d->dist;
sms.new_lens = v3d->lens;
- sms.to_camera = 0;
+ sms.to_camera = FALSE;
/* note on camera locking, this is a little confusing but works ok.
* we may be changing the view 'as if' there is no active camera, but in fact
@@ -161,23 +161,24 @@ void view3d_smooth_view(bContext *C, View3D *v3d, ARegion *ar, Object *oldcamera
if (lens) sms.new_lens = *lens;
if (camera) {
+ sms.new_dist = ED_view3d_offset_distance(camera->obmat, ofs);
ED_view3d_from_object(camera, sms.new_ofs, sms.new_quat, &sms.new_dist, &sms.new_lens);
- sms.to_camera = 1; /* restore view3d values in end */
+ sms.to_camera = TRUE; /* restore view3d values in end */
}
if (C && U.smooth_viewtx) {
- int changed = 0; /* zero means no difference */
+ int changed = FALSE; /* zero means no difference */
if (oldcamera != camera)
- changed = 1;
+ changed = TRUE;
else if (sms.new_dist != rv3d->dist)
- changed = 1;
+ changed = TRUE;
else if (sms.new_lens != v3d->lens)
- changed = 1;
+ changed = TRUE;
else if (!equals_v3v3(sms.new_ofs, rv3d->ofs))
- changed = 1;
+ changed = TRUE;
else if (!equals_v4v4(sms.new_quat, rv3d->viewquat))
- changed = 1;
+ changed = TRUE;
/* The new view is different from the old one
* so animate the view */
@@ -185,7 +186,7 @@ void view3d_smooth_view(bContext *C, View3D *v3d, ARegion *ar, Object *oldcamera
/* original values */
if (oldcamera) {
- sms.orig_dist = rv3d->dist; /* below function does weird stuff with it... */
+ sms.orig_dist = ED_view3d_offset_distance(oldcamera->obmat, rv3d->ofs);
ED_view3d_from_object(oldcamera, sms.orig_ofs, sms.orig_quat, &sms.orig_dist, &sms.orig_lens);
}
else {
@@ -241,13 +242,15 @@ void view3d_smooth_view(bContext *C, View3D *v3d, ARegion *ar, Object *oldcamera
/* if we get here nothing happens */
if (ok == FALSE) {
- if (sms.to_camera == 0) {
+ if (sms.to_camera == FALSE) {
copy_v3_v3(rv3d->ofs, sms.new_ofs);
copy_qt_qt(rv3d->viewquat, sms.new_quat);
rv3d->dist = sms.new_dist;
v3d->lens = sms.new_lens;
}
+ ED_view3d_camera_lock_sync(v3d, rv3d);
+
if (rv3d->viewlock & RV3D_BOXVIEW)
view3d_boxview_copy(sa, ar);
@@ -520,7 +523,7 @@ void VIEW3D_OT_object_as_camera(wmOperatorType *ot)
/* ********************************** */
-void ED_view3d_calc_clipping(BoundBox *bb, float planes[4][4], bglMats *mats, const rcti *rect)
+void ED_view3d_clipping_calc(BoundBox *bb, float planes[4][4], bglMats *mats, const rcti *rect)
{
float modelview[4][4];
double xs, ys, p[3];
@@ -569,264 +572,27 @@ void ED_view3d_calc_clipping(BoundBox *bb, float planes[4][4], bglMats *mats, co
}
}
-/* create intersection coordinates in view Z direction at mouse coordinates */
-void ED_view3d_win_to_segment_clip(ARegion *ar, View3D *v3d, const float mval[2], float ray_start[3], float ray_end[3])
-{
- RegionView3D *rv3d = ar->regiondata;
-
- if (rv3d->is_persp) {
- float vec[3];
- ED_view3d_win_to_vector(ar, mval, vec);
-
- copy_v3_v3(ray_start, rv3d->viewinv[3]);
- madd_v3_v3v3fl(ray_start, rv3d->viewinv[3], vec, v3d->near);
- madd_v3_v3v3fl(ray_end, rv3d->viewinv[3], vec, v3d->far);
- }
- else {
- float vec[4];
- vec[0] = 2.0f * mval[0] / ar->winx - 1;
- vec[1] = 2.0f * mval[1] / ar->winy - 1;
- vec[2] = 0.0f;
- vec[3] = 1.0f;
-
- mul_m4_v4(rv3d->persinv, vec);
-
- madd_v3_v3v3fl(ray_start, vec, rv3d->viewinv[2], 1000.0f);
- madd_v3_v3v3fl(ray_end, vec, rv3d->viewinv[2], -1000.0f);
- }
-
- /* clipping */
- if (rv3d->rflag & RV3D_CLIPPING) {
- int a;
- for (a = 0; a < 4; a++) {
- clip_line_plane(ray_start, ray_end, rv3d->clip[a]);
- }
- }
-}
-
-/* create intersection ray in view Z direction at mouse coordinates */
-void ED_view3d_win_to_ray(ARegion *ar, View3D *v3d, const float mval[2], float ray_start[3], float ray_normal[3])
-{
- float ray_end[3];
-
- ED_view3d_win_to_segment_clip(ar, v3d, mval, ray_start, ray_end);
- sub_v3_v3v3(ray_normal, ray_end, ray_start);
- normalize_v3(ray_normal);
-}
-
-void ED_view3d_global_to_vector(RegionView3D *rv3d, const float coord[3], float vec[3])
-{
- if (rv3d->is_persp) {
- float p1[4], p2[4];
-
- copy_v3_v3(p1, coord);
- p1[3] = 1.0f;
- copy_v3_v3(p2, p1);
- p2[3] = 1.0f;
- mul_m4_v4(rv3d->viewmat, p2);
-
- mul_v3_fl(p2, 2.0f);
-
- mul_m4_v4(rv3d->viewinv, p2);
-
- sub_v3_v3v3(vec, p1, p2);
- }
- else {
- copy_v3_v3(vec, rv3d->viewinv[2]);
- }
- normalize_v3(vec);
-}
-
-int initgrabz(RegionView3D *rv3d, float x, float y, float z)
-{
- int flip = FALSE;
- if (rv3d == NULL) return flip;
- rv3d->zfac = rv3d->persmat[0][3] * x + rv3d->persmat[1][3] * y + rv3d->persmat[2][3] * z + rv3d->persmat[3][3];
- if (rv3d->zfac < 0.0f)
- flip = TRUE;
- /* if x,y,z is exactly the viewport offset, zfac is 0 and we don't want that
- * (accounting for near zero values)
- */
- if (rv3d->zfac < 1.e-6f && rv3d->zfac > -1.e-6f) rv3d->zfac = 1.0f;
-
- /* Negative zfac means x, y, z was behind the camera (in perspective).
- * This gives flipped directions, so revert back to ok default case.
- */
- /* NOTE: I've changed this to flip zfac to be positive again for now so that GPencil draws ok
- * Aligorith, 2009Aug31 */
- //if (rv3d->zfac < 0.0f) rv3d->zfac = 1.0f;
- if (rv3d->zfac < 0.0f) rv3d->zfac = -rv3d->zfac;
-
- return flip;
-}
-
-void ED_view3d_win_to_3d(ARegion *ar, const float depth_pt[3], const float mval[2], float out[3])
-{
- RegionView3D *rv3d = ar->regiondata;
-
- float line_sta[3];
- float line_end[3];
-
- if (rv3d->is_persp) {
- float mousevec[3];
- copy_v3_v3(line_sta, rv3d->viewinv[3]);
- ED_view3d_win_to_vector(ar, mval, mousevec);
- add_v3_v3v3(line_end, line_sta, mousevec);
-
- if (isect_line_plane_v3(out, line_sta, line_end, depth_pt, rv3d->viewinv[2], TRUE) == 0) {
- /* highly unlikely to ever happen, mouse vec paralelle with view plane */
- zero_v3(out);
- }
- }
- else {
- const float dx = (2.0f * mval[0] / (float)ar->winx) - 1.0f;
- const float dy = (2.0f * mval[1] / (float)ar->winy) - 1.0f;
- line_sta[0] = (rv3d->persinv[0][0] * dx) + (rv3d->persinv[1][0] * dy) + rv3d->viewinv[3][0];
- line_sta[1] = (rv3d->persinv[0][1] * dx) + (rv3d->persinv[1][1] * dy) + rv3d->viewinv[3][1];
- line_sta[2] = (rv3d->persinv[0][2] * dx) + (rv3d->persinv[1][2] * dy) + rv3d->viewinv[3][2];
-
- add_v3_v3v3(line_end, line_sta, rv3d->viewinv[2]);
- closest_to_line_v3(out, depth_pt, line_sta, line_end);
- }
-}
-
-/* always call initgrabz */
-/* only to detect delta motion */
-void ED_view3d_win_to_delta(ARegion *ar, const float mval[2], float out[3])
-{
- RegionView3D *rv3d = ar->regiondata;
- float dx, dy;
-
- dx = 2.0f * mval[0] * rv3d->zfac / ar->winx;
- dy = 2.0f * mval[1] * rv3d->zfac / ar->winy;
-
- out[0] = (rv3d->persinv[0][0] * dx + rv3d->persinv[1][0] * dy);
- out[1] = (rv3d->persinv[0][1] * dx + rv3d->persinv[1][1] * dy);
- out[2] = (rv3d->persinv[0][2] * dx + rv3d->persinv[1][2] * dy);
-}
-
-/* doesn't rely on initgrabz */
-/* for perspective view, get the vector direction to
- * the mouse cursor as a normalized vector */
-void ED_view3d_win_to_vector(ARegion *ar, const float mval[2], float out[3])
-{
- RegionView3D *rv3d = ar->regiondata;
-
- if (rv3d->is_persp) {
- out[0] = 2.0f * (mval[0] / ar->winx) - 1.0f;
- out[1] = 2.0f * (mval[1] / ar->winy) - 1.0f;
- out[2] = -0.5f;
- mul_project_m4_v3(rv3d->persinv, out);
- sub_v3_v3(out, rv3d->viewinv[3]);
- }
- else {
- copy_v3_v3(out, rv3d->viewinv[2]);
- }
- normalize_v3(out);
-}
-
-float ED_view3d_depth_read_cached(ViewContext *vc, int x, int y)
-{
- ViewDepths *vd = vc->rv3d->depths;
-
- x -= vc->ar->winrct.xmin;
- y -= vc->ar->winrct.ymin;
-
- if (vd && vd->depths && x > 0 && y > 0 && x < vd->w && y < vd->h)
- return vd->depths[y * vd->w + x];
- else
- return 1;
-}
-
-void ED_view3d_depth_tag_update(RegionView3D *rv3d)
-{
- if (rv3d->depths)
- rv3d->depths->damaged = 1;
-}
-
-void ED_view3d_ob_project_mat_get(RegionView3D *rv3d, Object *ob, float pmat[4][4])
-{
- float vmat[4][4];
-
- mult_m4_m4m4(vmat, rv3d->viewmat, ob->obmat);
- mult_m4_m4m4(pmat, rv3d->winmat, vmat);
-}
-
-/* Uses window coordinates (x,y) and depth component z to find a point in
- * modelspace */
-void view3d_unproject(bglMats *mats, float out[3], const short x, const short y, const float z)
-{
- double ux, uy, uz;
-
- gluUnProject(x, y, z, mats->modelview, mats->projection,
- (GLint *)mats->viewport, &ux, &uy, &uz);
-
- out[0] = ux;
- out[1] = uy;
- out[2] = uz;
-}
-
-/* use view3d_get_object_project_mat to get projecting mat */
-void ED_view3d_project_float_v2(const ARegion *ar, const float vec[3], float adr[2], float mat[4][4])
-{
- float vec4[4];
-
- copy_v3_v3(vec4, vec);
- vec4[3] = 1.0;
- /* adr[0]= IS_CLIPPED; */ /* always overwritten */
-
- mul_m4_v4(mat, vec4);
-
- if (vec4[3] > FLT_EPSILON) {
- adr[0] = (float)(ar->winx / 2.0f) + (ar->winx / 2.0f) * vec4[0] / vec4[3];
- adr[1] = (float)(ar->winy / 2.0f) + (ar->winy / 2.0f) * vec4[1] / vec4[3];
- }
- else {
- adr[0] = adr[1] = 0.0f;
- }
-}
-
-/* use view3d_get_object_project_mat to get projecting mat */
-void ED_view3d_project_float_v3(ARegion *ar, const float vec[3], float adr[3], float mat[4][4])
-{
- float vec4[4];
-
- copy_v3_v3(vec4, vec);
- vec4[3] = 1.0;
- /* adr[0]= IS_CLIPPED; */ /* always overwritten */
-
- mul_m4_v4(mat, vec4);
-
- if (vec4[3] > FLT_EPSILON) {
- adr[0] = (float)(ar->winx / 2.0f) + (ar->winx / 2.0f) * vec4[0] / vec4[3];
- adr[1] = (float)(ar->winy / 2.0f) + (ar->winy / 2.0f) * vec4[1] / vec4[3];
- adr[2] = vec4[2] / vec4[3];
- }
- else {
- zero_v3(adr);
- }
-}
int ED_view3d_boundbox_clip(RegionView3D *rv3d, float obmat[][4], BoundBox *bb)
{
/* return 1: draw */
-
+
float mat[4][4];
float vec[4], min, max;
int a, flag = -1, fl;
-
+
if (bb == NULL) return 1;
if (bb->flag & OB_BB_DISABLED) return 1;
-
+
mult_m4_m4m4(mat, rv3d->persmat, obmat);
-
+
for (a = 0; a < 8; a++) {
copy_v3_v3(vec, bb->vec[a]);
vec[3] = 1.0;
mul_m4_v4(mat, vec);
max = vec[3];
min = -vec[3];
-
+
fl = 0;
if (vec[0] < min) fl += 1;
if (vec[0] > max) fl += 2;
@@ -834,161 +600,31 @@ int ED_view3d_boundbox_clip(RegionView3D *rv3d, float obmat[][4], BoundBox *bb)
if (vec[1] > max) fl += 8;
if (vec[2] < min) fl += 16;
if (vec[2] > max) fl += 32;
-
+
flag &= fl;
if (flag == 0) return 1;
}
-
- return 0;
-}
-void project_short(ARegion *ar, const float vec[3], short adr[2]) /* clips */
-{
- RegionView3D *rv3d = ar->regiondata;
- float fx, fy, vec4[4];
-
- adr[0] = IS_CLIPPED;
-
- if (rv3d->rflag & RV3D_CLIPPING) {
- if (ED_view3d_clipping_test(rv3d, vec, FALSE)) {
- return;
- }
- }
-
- copy_v3_v3(vec4, vec);
- vec4[3] = 1.0;
- mul_m4_v4(rv3d->persmat, vec4);
-
- if (vec4[3] > (float)BL_NEAR_CLIP) { /* 0.001 is the NEAR clipping cutoff for picking */
- fx = (ar->winx / 2) * (1 + vec4[0] / vec4[3]);
-
- if (fx > 0 && fx < ar->winx) {
-
- fy = (ar->winy / 2) * (1 + vec4[1] / vec4[3]);
-
- if (fy > 0.0f && fy < (float)ar->winy) {
- adr[0] = (short)floor(fx);
- adr[1] = (short)floor(fy);
- }
- }
- }
-}
-
-void project_int(ARegion *ar, const float vec[3], int adr[2])
-{
- RegionView3D *rv3d = ar->regiondata;
- float fx, fy, vec4[4];
-
- copy_v3_v3(vec4, vec);
- vec4[3] = 1.0;
- adr[0] = (int)2140000000.0f;
-
- mul_m4_v4(rv3d->persmat, vec4);
-
- if (vec4[3] > (float)BL_NEAR_CLIP) { /* 0.001 is the NEAR clipping cutoff for picking */
- fx = (ar->winx / 2) * (1 + vec4[0] / vec4[3]);
-
- if (fx > -2140000000.0f && fx < 2140000000.0f) {
- fy = (ar->winy / 2) * (1 + vec4[1] / vec4[3]);
-
- if (fy > -2140000000.0f && fy < 2140000000.0f) {
- adr[0] = (int)floor(fx);
- adr[1] = (int)floor(fy);
- }
- }
- }
-}
-
-void project_int_noclip(ARegion *ar, const float vec[3], int adr[2])
-{
- RegionView3D *rv3d = ar->regiondata;
- float fx, fy, vec4[4];
-
- copy_v3_v3(vec4, vec);
- vec4[3] = 1.0;
-
- mul_m4_v4(rv3d->persmat, vec4);
-
- if (fabs(vec4[3]) > BL_NEAR_CLIP) {
- fx = (ar->winx / 2) * (1 + vec4[0] / vec4[3]);
- fy = (ar->winy / 2) * (1 + vec4[1] / vec4[3]);
-
- adr[0] = (int)floor(fx);
- adr[1] = (int)floor(fy);
- }
- else {
- adr[0] = ar->winx / 2;
- adr[1] = ar->winy / 2;
- }
+ return 0;
}
-void project_short_noclip(ARegion *ar, const float vec[3], short adr[2])
+float ED_view3d_depth_read_cached(ViewContext *vc, int x, int y)
{
- RegionView3D *rv3d = ar->regiondata;
- float fx, fy, vec4[4];
-
- copy_v3_v3(vec4, vec);
- vec4[3] = 1.0;
- adr[0] = IS_CLIPPED;
-
- mul_m4_v4(rv3d->persmat, vec4);
-
- if (vec4[3] > (float)BL_NEAR_CLIP) { /* 0.001 is the NEAR clipping cutoff for picking */
- fx = (ar->winx / 2) * (1 + vec4[0] / vec4[3]);
+ ViewDepths *vd = vc->rv3d->depths;
- if (fx > -32700 && fx < 32700) {
-
- fy = (ar->winy / 2) * (1 + vec4[1] / vec4[3]);
-
- if (fy > -32700.0f && fy < 32700.0f) {
- adr[0] = (short)floor(fx);
- adr[1] = (short)floor(fy);
- }
- }
- }
-}
-
-void apply_project_float(float persmat[4][4], int winx, int winy, const float vec[3], float adr[2])
-{
- float vec4[4];
-
- copy_v3_v3(vec4, vec);
- vec4[3] = 1.0;
- adr[0] = IS_CLIPPED;
-
- mul_m4_v4(persmat, vec4);
-
- if (vec4[3] > (float)BL_NEAR_CLIP) {
- adr[0] = (float)(winx / 2.0f) + (winx / 2.0f) * vec4[0] / vec4[3];
- adr[1] = (float)(winy / 2.0f) + (winy / 2.0f) * vec4[1] / vec4[3];
- }
-}
-
-void project_float(ARegion *ar, const float vec[3], float adr[2])
-{
- RegionView3D *rv3d = ar->regiondata;
+ x -= vc->ar->winrct.xmin;
+ y -= vc->ar->winrct.ymin;
- apply_project_float(rv3d->persmat, ar->winx, ar->winy, vec, adr);
+ if (vd && vd->depths && x > 0 && y > 0 && x < vd->w && y < vd->h)
+ return vd->depths[y * vd->w + x];
+ else
+ return 1;
}
-void project_float_noclip(ARegion *ar, const float vec[3], float adr[2])
+void ED_view3d_depth_tag_update(RegionView3D *rv3d)
{
- RegionView3D *rv3d = ar->regiondata;
- float vec4[4];
-
- copy_v3_v3(vec4, vec);
- vec4[3] = 1.0;
-
- mul_m4_v4(rv3d->persmat, vec4);
-
- if (fabs(vec4[3]) > BL_NEAR_CLIP) {
- adr[0] = (float)(ar->winx / 2.0f) + (ar->winx / 2.0f) * vec4[0] / vec4[3];
- adr[1] = (float)(ar->winy / 2.0f) + (ar->winy / 2.0f) * vec4[1] / vec4[3];
- }
- else {
- adr[0] = ar->winx / 2.0f;
- adr[1] = ar->winy / 2.0f;
- }
+ if (rv3d->depths)
+ rv3d->depths->damaged = 1;
}
/* copies logic of get_view3d_viewplane(), keep in sync */
@@ -1022,7 +658,10 @@ int ED_view3d_viewplane_get(View3D *v3d, RegionView3D *rv3d, int winx, int winy,
return params.is_ortho;
}
-void setwinmatrixview3d(ARegion *ar, View3D *v3d, rctf *rect) /* rect: for picking */
+/*!
+ * \param rect for picking, NULL not to use.
+ */
+void setwinmatrixview3d(ARegion *ar, View3D *v3d, rctf *rect)
{
RegionView3D *rv3d = ar->regiondata;
rctf viewplane;
@@ -1055,7 +694,7 @@ void setwinmatrixview3d(ARegion *ar, View3D *v3d, rctf *rect) /* rect: for
if (orth) wmOrtho(rect->xmin, rect->xmax, rect->ymin, rect->ymax, -clipend, clipend);
else wmFrustum(rect->xmin, rect->xmax, rect->ymin, rect->ymax, clipsta, clipend);
-
+
}
else {
if (orth) wmOrtho(x1, x2, y1, y2, clipsta, clipend);
@@ -1151,7 +790,7 @@ void setviewmatrixview3d(Scene *scene, View3D *v3d, RegionView3D *rv3d)
{
if (rv3d->persp == RV3D_CAMOB) { /* obs/camera */
if (v3d->camera) {
- BKE_object_where_is_calc(scene, v3d->camera);
+ BKE_object_where_is_calc(scene, v3d->camera);
obmat_to_viewmat(v3d, rv3d, v3d->camera, 0);
}
else {
@@ -1256,14 +895,14 @@ short view3d_opengl_select(ViewContext *vc, unsigned int *buffer, unsigned int b
glLoadName(code);
draw_object(scene, ar, v3d, base, DRAW_PICKING | DRAW_CONSTCOLOR);
- /* we draw group-duplicators for selection too */
- if ((base->object->transflag & OB_DUPLI) && base->object->dup_group) {
+ /* we draw duplicators for selection too */
+ if ((base->object->transflag & OB_DUPLI)) {
ListBase *lb;
DupliObject *dob;
Base tbase;
tbase.flag = OB_FROMDUPLI;
- lb = object_duplilist(scene, base->object);
+ lb = object_duplilist(scene, base->object, FALSE);
for (dob = lb->first; dob; dob = dob->next) {
tbase.object = dob->ob;
@@ -1284,7 +923,7 @@ short view3d_opengl_select(ViewContext *vc, unsigned int *buffer, unsigned int b
free_object_duplilist(lb);
}
code++;
- }
+ }
}
}
v3d->xray = FALSE; /* restore */
@@ -1402,7 +1041,7 @@ static int view3d_localview_init(Main *bmain, Scene *scene, ScrArea *sa, ReportL
locallay = free_localbit(bmain);
if (locallay == 0) {
- BKE_reportf(reports, RPT_ERROR, "No more than 8 localviews");
+ BKE_report(reports, RPT_ERROR, "No more than 8 local views");
ok = FALSE;
}
else {
@@ -1557,7 +1196,7 @@ static int view3d_localview_exit(Main *bmain, Scene *scene, ScrArea *sa)
DAG_on_visible_update(bmain, FALSE);
return TRUE;
- }
+ }
else {
return FALSE;
}
@@ -1591,7 +1230,6 @@ static int localview_exec(bContext *C, wmOperator *op)
void VIEW3D_OT_localview(wmOperatorType *ot)
{
-
/* identifiers */
ot->name = "Local View";
ot->description = "Toggle display of selected object(s) separately and centered in view";
@@ -1631,12 +1269,12 @@ static void RestoreState(bContext *C, wmWindow *win)
GPU_paint_set_mipmap(0);
//XXX curarea->win_swap = 0;
- //XXX curarea->head_swap=0;
+ //XXX curarea->head_swap = 0;
//XXX allqueue(REDRAWVIEW3D, 1);
//XXX allqueue(REDRAWBUTSALL, 0);
//XXX reset_slowparents();
//XXX waitcursor(0);
- //XXX G.qual= 0;
+ //XXX G.qual = 0;
if (win) /* check because closing win can set to NULL */
win->queue = queue_back;
@@ -1761,7 +1399,7 @@ static int game_engine_exec(bContext *C, wmOperator *op)
WM_redraw_windows(C);
rv3d = CTX_wm_region_view3d(C);
- /* sa= CTX_wm_area(C); */ /* UNUSED */
+ /* sa = CTX_wm_area(C); */ /* UNUSED */
ar = CTX_wm_region(C);
view3d_operator_needs_opengl(C);
diff --git a/source/blender/editors/transform/transform.c b/source/blender/editors/transform/transform.c
index a3fb4e851e2..245241763fd 100644
--- a/source/blender/editors/transform/transform.c
+++ b/source/blender/editors/transform/transform.c
@@ -57,6 +57,8 @@
#include "BIF_gl.h"
#include "BIF_glutil.h"
+#include "BLF_api.h"
+
#include "BKE_nla.h"
#include "BKE_bmesh.h"
#include "BKE_context.h"
@@ -89,12 +91,11 @@
#include "BLI_smallhash.h"
#include "BLI_array.h"
+#include "UI_interface_icons.h"
#include "UI_resources.h"
#include "transform.h"
-#include <stdio.h>
-
static void drawTransformApply(const struct bContext *C, ARegion *ar, void *arg);
static int doEdgeSlide(TransInfo *t, float perc);
@@ -126,11 +127,11 @@ static void convertViewVec2D(View2D *v2d, float r_vec[3], int dx, int dy)
{
float divx, divy;
- divx = BLI_RCT_SIZE_X(&v2d->mask);
- divy = BLI_RCT_SIZE_Y(&v2d->mask);
+ divx = BLI_rcti_size_x(&v2d->mask);
+ divy = BLI_rcti_size_y(&v2d->mask);
- r_vec[0] = BLI_RCT_SIZE_X(&v2d->cur) * dx / divx;
- r_vec[1] = BLI_RCT_SIZE_Y(&v2d->cur) * dy / divy;
+ r_vec[0] = BLI_rctf_size_x(&v2d->cur) * dx / divx;
+ r_vec[1] = BLI_rctf_size_y(&v2d->cur) * dy / divy;
r_vec[2] = 0.0f;
}
@@ -139,11 +140,11 @@ static void convertViewVec2D_mask(View2D *v2d, float r_vec[3], int dx, int dy)
float divx, divy;
float mulx, muly;
- divx = BLI_RCT_SIZE_X(&v2d->mask);
- divy = BLI_RCT_SIZE_Y(&v2d->mask);
+ divx = BLI_rcti_size_x(&v2d->mask);
+ divy = BLI_rcti_size_y(&v2d->mask);
- mulx = BLI_RCT_SIZE_X(&v2d->cur);
- muly = BLI_RCT_SIZE_Y(&v2d->cur);
+ mulx = BLI_rctf_size_x(&v2d->cur);
+ muly = BLI_rctf_size_y(&v2d->cur);
/* difference with convertViewVec2D */
/* clamp w/h, mask only */
@@ -225,8 +226,12 @@ void convertViewVec(TransInfo *t, float r_vec[3], int dx, int dy)
void projectIntView(TransInfo *t, const float vec[3], int adr[2])
{
if (t->spacetype == SPACE_VIEW3D) {
- if (t->ar->regiontype == RGN_TYPE_WINDOW)
- project_int_noclip(t->ar, vec, adr);
+ if (t->ar->regiontype == RGN_TYPE_WINDOW) {
+ if (ED_view3d_project_int_global(t->ar, vec, adr, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
+ adr[0] = (int)2140000000.0f; /* this is what was done in 2.64, perhaps we can be smarter? */
+ adr[1] = (int)2140000000.0f;
+ }
+ }
}
else if (t->spacetype == SPACE_IMAGE) {
SpaceImage *sima = t->sa->spacedata.first;
@@ -272,7 +277,7 @@ void projectIntView(TransInfo *t, const float vec[3], int adr[2])
//vec[0] = vec[0]/((t->scene->r.frs_sec / t->scene->r.frs_sec_base));
/* same as below */
UI_view2d_to_region_no_clip((View2D *)t->view, vec[0], vec[1], out, out + 1);
- }
+ }
else
#endif
{
@@ -332,6 +337,9 @@ void projectIntView(TransInfo *t, const float vec[3], int adr[2])
UI_view2d_to_region_no_clip(t->view, v[0], v[1], adr, adr + 1);
}
+ else {
+ BLI_assert(0);
+ }
}
else if (t->spacetype == SPACE_NODE) {
UI_view2d_to_region_no_clip((View2D *)t->view, vec[0], vec[1], adr, adr + 1);
@@ -344,7 +352,11 @@ void projectFloatView(TransInfo *t, const float vec[3], float adr[2])
case SPACE_VIEW3D:
{
if (t->ar->regiontype == RGN_TYPE_WINDOW) {
- project_float_noclip(t->ar, vec, adr);
+ if (ED_view3d_project_float_global(t->ar, vec, adr, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
+ /* XXX, 2.64 and prior did this, weak! */
+ adr[0] = t->ar->winx / 2.0f;
+ adr[1] = t->ar->winy / 2.0f;
+ }
return;
}
break;
@@ -457,11 +469,11 @@ static void viewRedrawForce(const bContext *C, TransInfo *t)
}
else if (t->spacetype == SPACE_ACTION) {
- //SpaceAction *saction= (SpaceAction *)t->sa->spacedata.first;
+ //SpaceAction *saction = (SpaceAction *)t->sa->spacedata.first;
WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, NULL);
}
else if (t->spacetype == SPACE_IPO) {
- //SpaceIpo *sipo= (SpaceIpo *)t->sa->spacedata.first;
+ //SpaceIpo *sipo = (SpaceIpo *)t->sa->spacedata.first;
WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, NULL);
}
else if (t->spacetype == SPACE_NLA) {
@@ -816,7 +828,7 @@ int transformEvent(TransInfo *t, wmEvent *event)
float mati[3][3] = MAT3_UNITY;
char cmode = constraintModeToChar(t);
int handled = 1;
-
+
t->redraw |= handleMouseInput(t, &t->mouse, event);
if (event->type == MOUSEMOVE) {
@@ -1011,7 +1023,7 @@ int transformEvent(TransInfo *t, wmEvent *event)
if (t->flag & T_PROP_EDIT) {
t->prop_size *= 1.1f;
if (t->spacetype == SPACE_VIEW3D && t->persp != RV3D_ORTHO)
- t->prop_size = minf(t->prop_size, ((View3D *)t->view)->far);
+ t->prop_size = min_ff(t->prop_size, ((View3D *)t->view)->far);
calculatePropRatio(t);
}
t->redraw |= TREDRAW_HARD;
@@ -1181,7 +1193,7 @@ int transformEvent(TransInfo *t, wmEvent *event)
if (event->alt && t->flag & T_PROP_EDIT) {
t->prop_size *= 1.1f;
if (t->spacetype == SPACE_VIEW3D && t->persp != RV3D_ORTHO)
- t->prop_size = minf(t->prop_size, ((View3D *)t->view)->far);
+ t->prop_size = min_ff(t->prop_size, ((View3D *)t->view)->far);
calculatePropRatio(t);
}
t->redraw = 1;
@@ -1209,6 +1221,12 @@ int transformEvent(TransInfo *t, wmEvent *event)
else view_editmove(event->type);
t->redraw = 1;
break;
+ case LEFTALTKEY:
+ case RIGHTALTKEY:
+ if (t->spacetype == SPACE_SEQ)
+ t->flag |= T_ALT_TRANSFORM;
+
+ break;
default:
handled = 0;
break;
@@ -1242,6 +1260,12 @@ int transformEvent(TransInfo *t, wmEvent *event)
//// if (t->options & CTX_TWEAK)
// t->state = TRANS_CONFIRM;
// break;
+ case LEFTALTKEY:
+ case RIGHTALTKEY:
+ if (t->spacetype == SPACE_SEQ)
+ t->flag &= ~T_ALT_TRANSFORM;
+
+ break;
default:
handled = 0;
break;
@@ -1255,15 +1279,19 @@ int transformEvent(TransInfo *t, wmEvent *event)
}
}
}
+ else
+ handled = 0;
// Per transform event, if present
if (t->handleEvent)
t->redraw |= t->handleEvent(t, event);
- if (handled || t->redraw)
+ if (handled || t->redraw) {
return 0;
- else
+ }
+ else {
return OPERATOR_PASS_THROUGH;
+ }
}
int calculateTransformCenter(bContext *C, int centerMode, float cent3d[3], int cent2d[2])
@@ -1473,8 +1501,8 @@ static void drawHelpline(bContext *UNUSED(C), int x, int y, void *customdata)
float dx = t->mval[0] - cent[0], dy = t->mval[1] - cent[1];
float angle = atan2f(dy, dx);
float dist = sqrtf(dx * dx + dy * dy);
- float delta_angle = minf(15.0f / dist, (float)M_PI / 4.0f);
- float spacing_angle = minf(5.0f / dist, (float)M_PI / 12.0f);
+ float delta_angle = min_ff(15.0f / dist, (float)M_PI / 4.0f);
+ float spacing_angle = min_ff(5.0f / dist, (float)M_PI / 12.0f);
UI_ThemeColor(TH_WIRE);
setlinestyle(3);
@@ -1546,14 +1574,55 @@ static void drawTransformView(const struct bContext *C, ARegion *UNUSED(ar), voi
drawNonPropEdge(C, t);
}
-#if 0
-static void drawTransformPixel(const struct bContext *UNUSED(C), ARegion *UNUSED(ar), void *UNUSED(arg))
+/* just draw a little warning message in the top-right corner of the viewport to warn that autokeying is enabled */
+static void drawAutoKeyWarning(TransInfo *UNUSED(t), ARegion *ar)
{
-// TransInfo *t = arg;
-//
-// drawHelpline(C, t->mval[0], t->mval[1], t);
+ const char printable[] = "Auto Keying On";
+ float printable_size[2];
+ int xco, yco;
+
+ BLF_width_and_height_default(printable, &printable_size[0], &printable_size[1]);
+
+ xco = ar->winx - (int)printable_size[0] - 10;
+ yco = ar->winy - (int)printable_size[1] - 10;
+
+ /* warning text (to clarify meaning of overlays)
+ * - original color was red to match the icon, but that clashes badly with a less nasty border
+ */
+ UI_ThemeColorShade(TH_TEXT_HI, -50);
+ BLF_draw_default_ascii(xco, ar->winy - 17, 0.0f, printable, sizeof(printable));
+
+ /* autokey recording icon... */
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glEnable(GL_BLEND);
+
+ xco -= (ICON_DEFAULT_WIDTH + 2);
+ UI_icon_draw(xco, yco, ICON_REC);
+
+ glDisable(GL_BLEND);
+}
+
+static void drawTransformPixel(const struct bContext *UNUSED(C), ARegion *ar, void *arg)
+{
+ TransInfo *t = arg;
+ Scene *scene = t->scene;
+ Object *ob = OBACT;
+
+ /* draw autokeyframing hint in the corner
+ * - only draw if enabled (advanced users may be distracted/annoyed),
+ * for objects that will be autokeyframed (no point ohterwise),
+ * AND only for the active region (as showing all is too overwhelming)
+ */
+ if ((U.autokey_flag & AUTOKEY_FLAG_NOWARNING) == 0) {
+ if (ar == t->ar) {
+ if (t->flag & (T_OBJECT | T_POSE)) {
+ if (ob && autokeyframe_cfra_can_key(scene, &ob->id)) {
+ drawAutoKeyWarning(t, ar);
+ }
+ }
+ }
+ }
}
-#endif
void saveTransform(bContext *C, TransInfo *t, wmOperator *op)
{
@@ -1723,7 +1792,7 @@ int initTransform(bContext *C, TransInfo *t, wmOperator *op, wmEvent *event, int
t->draw_handle_apply = ED_region_draw_cb_activate(t->ar->type, drawTransformApply, t, REGION_DRAW_PRE_VIEW);
t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
- //t->draw_handle_pixel = ED_region_draw_cb_activate(t->ar->type, drawTransformPixel, t, REGION_DRAW_POST_PIXEL);
+ t->draw_handle_pixel = ED_region_draw_cb_activate(t->ar->type, drawTransformPixel, t, REGION_DRAW_POST_PIXEL);
t->draw_handle_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), helpline_poll, drawHelpline, t);
}
else if (t->spacetype == SPACE_IMAGE) {
@@ -2195,7 +2264,6 @@ static void constraintTransLim(TransInfo *t, TransData *td)
for (con = td->con; con; con = con->next) {
bConstraintTypeInfo *cti = NULL;
ListBase targets = {NULL, NULL};
- float tmat[4][4];
/* only consider constraint if enabled */
if (con->flag & CONSTRAINT_DISABLE) continue;
@@ -2221,8 +2289,7 @@ static void constraintTransLim(TransInfo *t, TransData *td)
/* do space conversions */
if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
/* just multiply by td->mtx (this should be ok) */
- copy_m4_m4(tmat, cob.matrix);
- mul_m4_m3m4(cob.matrix, td->mtx, tmat);
+ mul_m4_m3m4(cob.matrix, td->mtx, cob.matrix);
}
else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
/* skip... incompatable spacetype */
@@ -2237,9 +2304,8 @@ static void constraintTransLim(TransInfo *t, TransData *td)
/* convert spaces again */
if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
- /* just multiply by td->mtx (this should be ok) */
- copy_m4_m4(tmat, cob.matrix);
- mul_m4_m3m4(cob.matrix, td->smtx, tmat);
+ /* just multiply by td->smtx (this should be ok) */
+ mul_m4_m3m4(cob.matrix, td->smtx, cob.matrix);
}
/* free targets list */
@@ -2287,18 +2353,17 @@ static void constraintRotLim(TransInfo *UNUSED(t), TransData *td)
bConstraintOb cob;
bConstraint *con;
int do_limit = FALSE;
-
+
/* Evaluate valid constraints */
for (con = td->con; con; con = con->next) {
/* only consider constraint if enabled */
if (con->flag & CONSTRAINT_DISABLE) continue;
if (con->enforce == 0.0f) continue;
-
+
/* we're only interested in Limit-Rotation constraints */
if (con->type == CONSTRAINT_TYPE_ROTLIMIT) {
bRotLimitConstraint *data = con->data;
- float tmat[4][4];
-
+
/* only use it if it's tagged for this purpose */
if ((data->flag2 & LIMIT_TRANSFORM) == 0)
continue;
@@ -2312,12 +2377,11 @@ static void constraintRotLim(TransInfo *UNUSED(t), TransData *td)
constraintob_from_transdata(&cob, td);
do_limit = TRUE;
}
-
+
/* do space conversions */
if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
/* just multiply by td->mtx (this should be ok) */
- copy_m4_m4(tmat, cob.matrix);
- mul_m4_m3m4(cob.matrix, td->mtx, tmat);
+ mul_m4_m3m4(cob.matrix, td->mtx, cob.matrix);
}
/* do constraint */
@@ -2325,9 +2389,8 @@ static void constraintRotLim(TransInfo *UNUSED(t), TransData *td)
/* convert spaces again */
if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
- /* just multiply by td->mtx (this should be ok) */
- copy_m4_m4(tmat, cob.matrix);
- mul_m4_m3m4(cob.matrix, td->smtx, tmat);
+ /* just multiply by td->smtx (this should be ok) */
+ mul_m4_m3m4(cob.matrix, td->smtx, cob.matrix);
}
}
}
@@ -2382,7 +2445,6 @@ static void constraintSizeLim(TransInfo *t, TransData *td)
/* we're only interested in Limit-Scale constraints */
if (con->type == CONSTRAINT_TYPE_SIZELIMIT) {
bSizeLimitConstraint *data = con->data;
- float tmat[4][4];
/* only use it if it's tagged for this purpose */
if ((data->flag2 & LIMIT_TRANSFORM) == 0)
@@ -2391,11 +2453,10 @@ static void constraintSizeLim(TransInfo *t, TransData *td)
/* do space conversions */
if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
/* just multiply by td->mtx (this should be ok) */
- copy_m4_m4(tmat, cob.matrix);
- mul_m4_m3m4(cob.matrix, td->mtx, tmat);
+ mul_m4_m3m4(cob.matrix, td->mtx, cob.matrix);
}
else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
- /* skip... incompatable spacetype */
+ /* skip... incompatible spacetype */
continue;
}
@@ -2404,13 +2465,12 @@ static void constraintSizeLim(TransInfo *t, TransData *td)
/* convert spaces again */
if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
- /* just multiply by td->mtx (this should be ok) */
- copy_m4_m4(tmat, cob.matrix);
- mul_m4_m3m4(cob.matrix, td->smtx, tmat);
+ /* just multiply by td->smtx (this should be ok) */
+ mul_m4_m3m4(cob.matrix, td->smtx, cob.matrix);
}
}
}
-
+
/* copy results from cob->matrix */
if ((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)) {
/* scale val and reset size */
@@ -2420,7 +2480,7 @@ static void constraintSizeLim(TransInfo *t, TransData *td)
/* Reset val if SINGLESIZE but using a constraint */
if (td->flag & TD_SINGLESIZE)
return;
-
+
mat4_to_size(td->ext->size, cob.matrix);
}
}
@@ -2852,11 +2912,11 @@ static void ElementResize(TransInfo *t, TransData *td, float mat[3][3])
if (t->flag & (T_OBJECT | T_TEXTURE | T_POSE)) {
float obsizemat[3][3];
- // Reorient the size mat to fit the oriented object.
+ /* Reorient the size mat to fit the oriented object. */
mul_m3_m3m3(obsizemat, tmat, td->axismtx);
- //print_m3("obsizemat", obsizemat);
+ /* print_m3("obsizemat", obsizemat); */
TransMat3ToSize(obsizemat, td->axismtx, fsize);
- //print_v3("fsize", fsize);
+ /* print_v3("fsize", fsize); */
}
else {
mat3_to_size(fsize, tmat);
@@ -2864,7 +2924,7 @@ static void ElementResize(TransInfo *t, TransData *td, float mat[3][3])
protectedSizeBits(td->protectflag, fsize);
- if ((t->flag & T_V3D_ALIGN) == 0) { // align mode doesn't resize objects itself
+ if ((t->flag & T_V3D_ALIGN) == 0) { /* align mode doesn't resize objects itself */
if ((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)) {
/* scale val and reset size */
*td->val = td->ival * (1 + (fsize[0] - 1) * td->factor);
@@ -3339,7 +3399,7 @@ static void ElementRotation(TransInfo *t, TransData *td, float mat[3][3], short
/* this function works on end result */
protectedAxisAngleBits(td->protectflag, td->ext->rotAxis, td->ext->rotAngle, td->ext->irotAxis, td->ext->irotAngle);
}
- else {
+ else {
float eulmat[3][3];
mul_m3_m3m3(totmat, mat, td->ext->r_mtx);
@@ -3915,7 +3975,7 @@ int ShrinkFatten(TransInfo *t, const int UNUSED(mval[2]))
sprintf(str, "Shrink/Fatten: %.4f %s", distance, t->proptext);
}
- t->values[0] = distance;
+ t->values[0] = -distance;
for (i = 0; i < t->total; i++, td++) {
if (td->flag & TD_NOACTION)
@@ -3979,12 +4039,15 @@ int Tilt(TransInfo *t, const int UNUSED(mval[2]))
outputNumInput(&(t->num), c);
- sprintf(str, "Tilt: %s %s", &c[0], t->proptext);
+ sprintf(str, "Tilt: %s° %s", &c[0], t->proptext);
final = DEG2RADF(final);
+
+ /* XXX For some reason, this seems needed for this op, else RNA prop is not updated... :/ */
+ t->values[0] = final;
}
else {
- sprintf(str, "Tilt: %.2f %s", RAD2DEGF(final), t->proptext);
+ sprintf(str, "Tilt: %.2f° %s", RAD2DEGF(final), t->proptext);
}
for (i = 0; i < t->total; i++, td++) {
@@ -4100,9 +4163,9 @@ void initMaskShrinkFatten(TransInfo *t)
int MaskShrinkFatten(TransInfo *t, const int UNUSED(mval[2]))
{
- TransData *td = t->data;
+ TransData *td;
float ratio;
- int i;
+ int i, initial_feather = FALSE;
char str[50];
ratio = t->values[0];
@@ -4116,13 +4179,30 @@ int MaskShrinkFatten(TransInfo *t, const int UNUSED(mval[2]))
char c[NUM_STR_REP_LEN];
outputNumInput(&(t->num), c);
- sprintf(str, "Shrink/Fatten: %s", c);
+ sprintf(str, "Feather Shrink/Fatten: %s", c);
}
else {
- sprintf(str, "Shrink/Fatten: %3f", ratio);
+ sprintf(str, "Feather Shrink/Fatten: %3f", ratio);
}
- for (i = 0; i < t->total; i++, td++) {
+ /* detect if no points have feather yet */
+ if (ratio > 1.0f) {
+ initial_feather = TRUE;
+
+ for (td = t->data, i = 0; i < t->total; i++, td++) {
+ if (td->flag & TD_NOACTION)
+ break;
+
+ if (td->flag & TD_SKIP)
+ continue;
+
+ if (td->ival >= 0.001f)
+ initial_feather = FALSE;
+ }
+ }
+
+ /* apply shrink/fatten */
+ for (td = t->data, i = 0; i < t->total; i++, td++) {
if (td->flag & TD_NOACTION)
break;
@@ -4130,7 +4210,11 @@ int MaskShrinkFatten(TransInfo *t, const int UNUSED(mval[2]))
continue;
if (td->val) {
- *td->val = td->ival * ratio;
+ if (initial_feather)
+ *td->val = td->ival + (ratio - 1.0f) * 0.01f;
+ else
+ *td->val = td->ival * ratio;
+
/* apply PET */
*td->val = (*td->val * td->factor) + ((1.0f - td->factor) * td->ival);
if (*td->val <= 0.0f) *td->val = 0.001f;
@@ -4721,8 +4805,7 @@ static BMLoop *get_next_loop(BMVert *v, BMLoop *l,
cross_v3_v3v3(a, f2, l->f->no);
mul_v3_fl(a, -1.0f);
- add_v3_v3(a, f3);
- mul_v3_fl(a, 0.5f);
+ mid_v3_v3v3(a, a, f3);
}
copy_v3_v3(vec, a);
@@ -4743,7 +4826,7 @@ static BMLoop *get_next_loop(BMVert *v, BMLoop *l,
}
l = l->radial_next;
- } while (l != firstl);
+ } while (l != firstl);
if (i)
mul_v3_fl(a, 1.0f / (float)i);
@@ -4774,12 +4857,12 @@ static void calcNonProportionalEdgeSlide(TransInfo *t, SlideData *sld, const flo
sv->edge_len = len_v3v3(dw_p, up_p);
mul_v3_m4v3(v_proj, t->obedit->obmat, sv->v->co);
- project_float_noclip(t->ar, v_proj, v_proj);
-
- dist = len_squared_v2v2(mval, v_proj);
- if (dist < min_dist) {
- min_dist = dist;
- sld->curr_sv_index = i;
+ if (ED_view3d_project_float_global(t->ar, v_proj, v_proj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ dist = len_squared_v2v2(mval, v_proj);
+ if (dist < min_dist) {
+ min_dist = dist;
+ sld->curr_sv_index = i;
+ }
}
}
}
@@ -4792,10 +4875,9 @@ static int createSlideVerts(TransInfo *t)
{
BMEditMesh *em = BMEdit_FromObject(t->obedit);
BMesh *bm = em->bm;
- BMIter iter, iter2;
+ BMIter iter;
BMEdge *e, *e1;
BMVert *v, *v2, *first;
- BMLoop *l, *l1, *l2;
TransDataSlideVert *sv_array;
BMBVHTree *btree = BMBVH_NewBVH(em, BMBVH_RESPECT_HIDDEN, NULL, NULL);
SmallHash table;
@@ -4835,6 +4917,7 @@ static int createSlideVerts(TransInfo *t)
/*ensure valid selection*/
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
+ BMIter iter2;
numsel = 0;
BM_ITER_ELEM (e, &iter2, v, BM_EDGES_OF_VERT) {
if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
@@ -4887,6 +4970,8 @@ static int createSlideVerts(TransInfo *t)
j = 0;
while (1) {
+ BMLoop *l, *l1, *l2;
+
v = NULL;
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(v, BM_ELEM_TAG))
@@ -5020,7 +5105,7 @@ static int createSlideVerts(TransInfo *t)
if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
BMIter iter2;
BMEdge *e2;
- float vec1[3], mval[2] = {t->mval[0], t->mval[1]}, d;
+ float vec1[3], d;
/* search cross edges for visible edge to the mouse cursor,
* then use the shared vertex to calculate screen vector*/
@@ -5040,19 +5125,19 @@ static int createSlideVerts(TransInfo *t)
j = GET_INT_FROM_POINTER(BLI_smallhash_lookup(&table, (uintptr_t)v));
if (sv_array[j].down) {
- ED_view3d_project_float_v3(ar, sv_array[j].down->co, vec1, projectMat);
+ ED_view3d_project_float_v3_m4(ar, sv_array[j].down->co, vec1, projectMat);
}
else {
add_v3_v3v3(vec1, v->co, sv_array[j].downvec);
- ED_view3d_project_float_v3(ar, vec1, vec1, projectMat);
+ ED_view3d_project_float_v3_m4(ar, vec1, vec1, projectMat);
}
if (sv_array[j].up) {
- ED_view3d_project_float_v3(ar, sv_array[j].up->co, vec2, projectMat);
+ ED_view3d_project_float_v3_m4(ar, sv_array[j].up->co, vec2, projectMat);
}
else {
add_v3_v3v3(vec2, v->co, sv_array[j].upvec);
- ED_view3d_project_float_v3(ar, vec2, vec2, projectMat);
+ ED_view3d_project_float_v3_m4(ar, vec2, vec2, projectMat);
}
/* global direction */
@@ -5443,7 +5528,7 @@ void drawNonPropEdge(const struct bContext *C, TransInfo *t)
float v1[3], v2[3];
float interp_v;
TransDataSlideVert *curr_sv = &sld->sv[sld->curr_sv_index];
- const float ctrl_size = UI_GetThemeValuef(TH_FACEDOT_SIZE) + 1.5;
+ const float ctrl_size = UI_GetThemeValuef(TH_FACEDOT_SIZE) + 1.5f;
const float guide_size = ctrl_size - 0.5f;
const float line_size = UI_GetThemeValuef(TH_OUTLINE_WIDTH) + 0.5f;
const int alpha_shade = -30;
@@ -5514,42 +5599,42 @@ static int doEdgeSlide(TransInfo *t, float perc)
int i;
sld->perc = perc;
-
sv = svlist;
- for (i = 0; i < sld->totsv; i++, sv++) {
- if (sld->is_proportional == FALSE) {
- TransDataSlideVert *curr_sv = &sld->sv[sld->curr_sv_index];
- float cur_sel = curr_sv->edge_len;
- float cur_sv = sv->edge_len;
- float extd = 0.0f;
- float recip_cur_sv = 0.0f;
-
- if (cur_sel == 0.0f) cur_sel = 1.0f;
- if (cur_sv == 0.0f) cur_sv = 1.0f;
- recip_cur_sv = 1.0f / cur_sv;
-
- if (!sld->flipped_vtx) {
- extd = (cur_sv - cur_sel) * recip_cur_sv;
+ if (sld->is_proportional == TRUE) {
+ for (i = 0; i < sld->totsv; i++, sv++) {
+ if (perc > 0.0f) {
+ copy_v3_v3(vec, sv->upvec);
+ mul_v3_fl(vec, perc);
+ add_v3_v3v3(sv->v->co, sv->origvert.co, vec);
}
else {
- extd = (cur_sel - cur_sv) * recip_cur_sv;
+ copy_v3_v3(vec, sv->downvec);
+ mul_v3_fl(vec, -perc);
+ add_v3_v3v3(sv->v->co, sv->origvert.co, vec);
}
-
- extd += (sld->perc * cur_sel) * recip_cur_sv;
- CLAMP(extd, -1.0f, 1.0f);
- perc = extd;
}
+ }
+ else {
+ /**
+ * Implementation note, non proportional mode ignores the starting positions and uses only the
+ * up/down verts, this could be changed/improved so the distance is still met but the verts are moved along
+ * their original path (which may not be straight), however how it works now is OK and matches 2.4x - Campbell
+ */
+ TransDataSlideVert *curr_sv = &sld->sv[sld->curr_sv_index];
+ const float curr_length_perc = len_v3v3(curr_sv->up->co, curr_sv->down->co) *
+ (((sld->flipped_vtx ? perc : -perc) + 1.0f) / 2.0f);
- if (perc > 0.0f) {
- copy_v3_v3(vec, sv->upvec);
- mul_v3_fl(vec, perc);
- add_v3_v3v3(sv->v->co, sv->origvert.co, vec);
- }
- else {
- copy_v3_v3(vec, sv->downvec);
- mul_v3_fl(vec, -perc);
- add_v3_v3v3(sv->v->co, sv->origvert.co, vec);
+ for (i = 0; i < sld->totsv; i++, sv++) {
+ const float sv_length = len_v3v3(sv->up->co, sv->down->co);
+ const float fac = min_ff(sv_length, curr_length_perc) / sv_length;
+
+ if (sld->flipped_vtx) {
+ interp_v3_v3v3(sv->v->co, sv->down->co, sv->up->co, fac);
+ }
+ else {
+ interp_v3_v3v3(sv->v->co, sv->up->co, sv->down->co, fac);
+ }
}
}
@@ -6038,7 +6123,7 @@ static short getAnimEdit_DrawTime(TransInfo *t)
SpaceIpo *sipo = (SpaceIpo *)t->sa->spacedata.first;
drawtime = (sipo->flag & SIPO_DRAWTIME) ? 1 : 0;
- }
+ }
else {
drawtime = 0;
}
@@ -6519,5 +6604,5 @@ int TimeScale(TransInfo *t, const int UNUSED(mval[2]))
void BIF_TransformSetUndo(const char *UNUSED(str))
{
// TRANSFORM_FIX_ME
- //Trans.undostr= str;
+ //Trans.undostr = str;
}
diff --git a/source/blender/editors/transform/transform.h b/source/blender/editors/transform/transform.h
index e645cb2fed6..1f9775821d1 100644
--- a/source/blender/editors/transform/transform.h
+++ b/source/blender/editors/transform/transform.h
@@ -322,7 +322,7 @@ typedef struct TransInfo {
float auto_values[4];
float axis[3];
float axis_orig[3]; /* TransCon can change 'axis', store the original value here */
-
+
void *view;
struct bContext *context; /* Only valid (non null) during an operator called function. */
struct ScrArea *sa;
diff --git a/source/blender/editors/transform/transform_constraints.c b/source/blender/editors/transform/transform_constraints.c
index 0aa46a36afe..311cb5ee94d 100644
--- a/source/blender/editors/transform/transform_constraints.c
+++ b/source/blender/editors/transform/transform_constraints.c
@@ -782,7 +782,7 @@ void startConstraint(TransInfo *t)
{
t->con.mode |= CON_APPLY;
*t->con.text = ' ';
- t->num.idx_max = MIN2(getConstraintSpaceDimension(t) - 1, t->idx_max);
+ t->num.idx_max = min_ii(getConstraintSpaceDimension(t) - 1, t->idx_max);
}
void stopConstraint(TransInfo *t)
diff --git a/source/blender/editors/transform/transform_conversions.c b/source/blender/editors/transform/transform_conversions.c
index 181f9fe6036..f6b888d4881 100644
--- a/source/blender/editors/transform/transform_conversions.c
+++ b/source/blender/editors/transform/transform_conversions.c
@@ -76,6 +76,7 @@
#include "BKE_gpencil.h"
#include "BKE_key.h"
#include "BKE_main.h"
+#include "BKE_mesh.h"
#include "BKE_modifier.h"
#include "BKE_movieclip.h"
#include "BKE_nla.h"
@@ -124,62 +125,46 @@ static short constraints_list_needinv(TransInfo *t, ListBase *list);
/* ************************** Functions *************************** */
-static void qsort_trans_data(TransInfo *t, TransData *head, TransData *tail, TransData *temp)
+static int trans_data_compare_dist(const void *A, const void *B)
{
- TransData *ihead = head;
- TransData *itail = tail;
- *temp = *head;
+ const TransData *td_A = (const TransData*)A;
+ const TransData *td_B = (const TransData*)B;
- while (head < tail) {
- if (t->flag & T_PROP_CONNECTED) {
- while ((tail->dist >= temp->dist) && (head < tail))
- tail--;
- }
- else {
- while ((tail->rdist >= temp->rdist) && (head < tail))
- tail--;
- }
-
- if (head != tail) {
- *head = *tail;
- head++;
- }
-
- if (t->flag & T_PROP_CONNECTED) {
- while ((head->dist <= temp->dist) && (head < tail))
- head++;
- }
- else {
- while ((head->rdist <= temp->rdist) && (head < tail))
- head++;
- }
+ if (td_A->dist < td_B->dist)
+ return -1;
+ else if (td_A->dist > td_B->dist)
+ return 1;
+
+ return 0;
+}
- if (head != tail) {
- *tail = *head;
- tail--;
- }
- }
+static int trans_data_compare_rdist(const void *A, const void *B)
+{
+ const TransData *td_A = (const TransData*)A;
+ const TransData *td_B = (const TransData*)B;
- *head = *temp;
- if (ihead < head) {
- qsort_trans_data(t, ihead, head - 1, temp);
- }
- if (itail > head) {
- qsort_trans_data(t, head + 1, itail, temp);
- }
+ if (td_A->rdist < td_B->rdist)
+ return -1;
+ else if (td_A->rdist > td_B->rdist)
+ return 1;
+
+ return 0;
}
void sort_trans_data_dist(TransInfo *t)
{
- TransData temp;
TransData *start = t->data;
- int i = 1;
+ int i;
- while (i < t->total && start->flag & TD_SELECTED) {
+ for (i = 0; i < t->total && start->flag & TD_SELECTED; i++)
start++;
- i++;
+
+ if (i < t->total) {
+ if (t->flag & T_PROP_CONNECTED)
+ qsort(start, t->total - i, sizeof(TransData), trans_data_compare_dist);
+ else
+ qsort(start, t->total - i, sizeof(TransData), trans_data_compare_rdist);
}
- qsort_trans_data(t, start, t->data + t->total - 1, &temp);
}
static void sort_trans_data(TransInfo *t)
@@ -332,13 +317,9 @@ static void createTransEdge(TransInfo *t)
invert_m3_m3(smtx, mtx);
BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
- if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && (BM_elem_flag_test(eed, BM_ELEM_SELECT) || propmode)) {
- float *bweight = CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_BWEIGHT);
- float *crease = CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_CREASE);
-
+ if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && (BM_elem_flag_test(eed, BM_ELEM_SELECT) || propmode)) {
/* need to set center for center calculations */
- add_v3_v3v3(td->center, eed->v1->co, eed->v2->co);
- mul_v3_fl(td->center, 0.5f);
+ mid_v3_v3v3(td->center, eed->v1->co, eed->v2->co);
td->loc = NULL;
if (BM_elem_flag_test(eed, BM_ELEM_SELECT))
@@ -346,16 +327,18 @@ static void createTransEdge(TransInfo *t)
else
td->flag = 0;
-
copy_m3_m3(td->smtx, smtx);
copy_m3_m3(td->mtx, mtx);
td->ext = NULL;
if (t->mode == TFM_BWEIGHT) {
+ float *bweight = CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_BWEIGHT);
td->val = bweight;
td->ival = bweight ? *bweight : 1.0f;
}
else {
+ float *crease = CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_CREASE);
+ BLI_assert(t->mode == TFM_CREASE);
td->val = crease;
td->ival = crease ? *crease : 0.0f;
}
@@ -419,7 +402,7 @@ static short apply_targetless_ik(Object *ob)
float rmat[4][4] /*, tmat[4][4], imat[4][4]*/;
/* pose_mat(b) = pose_mat(b-1) * offs_bone * channel * constraint * IK */
- /* we put in channel the entire result of rmat= (channel * constraint * IK) */
+ /* we put in channel the entire result of rmat = (channel * constraint * IK) */
/* pose_mat(b) = pose_mat(b-1) * offs_bone * rmat */
/* rmat = pose_mat(b) * inv(pose_mat(b-1) * offs_bone ) */
@@ -850,7 +833,7 @@ static short pose_grab_with_ik_add(bPoseChannel *pchan)
con = add_pose_constraint(NULL, pchan, "TempConstraint", CONSTRAINT_TYPE_KINEMATIC);
pchan->constflag |= (PCHAN_HAS_IK | PCHAN_HAS_TARGET); /* for draw, but also for detecting while pose solving */
data = con->data;
- if (targetless) {
+ if (targetless) {
/* if exists, use values from last targetless (but disabled) IK-constraint as base */
*data = *targetless;
}
@@ -973,7 +956,7 @@ static void createTransPose(TransInfo *t, Object *ob)
if (arm->flag & ARM_RESTPOS) {
if (ELEM(t->mode, TFM_DUMMY, TFM_BONESIZE) == 0) {
// XXX use transform operator reports
- // BKE_report(op->reports, RPT_ERROR, "Can't select linked when sync selection is enabled");
+ // BKE_report(op->reports, RPT_ERROR, "Cannot select linked when sync selection is enabled");
return;
}
}
@@ -1334,10 +1317,9 @@ static TransDataCurveHandleFlags *initTransDataCurveHandles(TransData *td, struc
return hdata;
}
-static void createTransCurveVerts(bContext *C, TransInfo *t)
+static void createTransCurveVerts(TransInfo *t)
{
- Object *obedit = CTX_data_edit_object(C);
- Curve *cu = obedit->data;
+ Curve *cu = t->obedit->data;
TransData *td = NULL;
Nurb *nu;
BezTriple *bezt;
@@ -1490,6 +1472,8 @@ static void createTransCurveVerts(bContext *C, TransInfo *t)
count++;
tail++;
}
+
+ (void)hdata; /* quiet warning */
}
else if (propmode && head != tail) {
calc_distanceCurveVerts(head, tail - 1);
@@ -1773,9 +1757,6 @@ void flushTransParticles(TransInfo *t)
/* ********************* mesh ****************** */
-/* proportional distance based on connectivity */
-#define THRESHOLDFACTOR (1.0f - 0.0001f)
-
/* I did this wrong, it should be a breadth-first search
* but instead it's a depth-first search, fudged
* to report shortest distances. I have no idea how fast
@@ -1832,7 +1813,7 @@ static void editmesh_set_connectivity_distance(BMEditMesh *em, float mtx[][3], f
d2 = d + len_v3(vec);
if (dists[BM_elem_index_get(v3)] != FLT_MAX)
- dists[BM_elem_index_get(v3)] = minf(d2, dists[BM_elem_index_get(v3)]);
+ dists[BM_elem_index_get(v3)] = min_ff(d2, dists[BM_elem_index_get(v3)]);
else
dists[BM_elem_index_get(v3)] = d2;
@@ -1938,9 +1919,9 @@ static void VertsToTransData(TransInfo *t, TransData *td, TransDataExtension *tx
}
}
-static void createTransEditVerts(bContext *C, TransInfo *t)
+static void createTransEditVerts(TransInfo *t)
{
- ToolSettings *ts = CTX_data_tool_settings(C);
+ ToolSettings *ts = t->scene->toolsettings;
TransData *tob = NULL;
TransDataExtension *tx = NULL;
BMEditMesh *em = BMEdit_FromObject(t->obedit);
@@ -2361,6 +2342,7 @@ static void createTransUVs(bContext *C, TransInfo *t)
SpaceImage *sima = CTX_wm_space_image(C);
Image *ima = CTX_data_edit_image(C);
Scene *scene = t->scene;
+ ToolSettings *ts = CTX_data_tool_settings(C);
TransData *td = NULL;
TransData2D *td2d = NULL;
MTexPoly *tf;
@@ -2369,12 +2351,26 @@ static void createTransUVs(bContext *C, TransInfo *t)
BMFace *efa;
BMLoop *l;
BMIter iter, liter;
- int count = 0, countsel = 0;
+ UvElementMap *elementmap;
+ char *island_enabled;
+ int count = 0, countsel = 0, count_rejected = 0;
int propmode = t->flag & T_PROP_EDIT;
+ int propconnected = t->flag & T_PROP_CONNECTED;
if (!ED_space_image_show_uvedit(sima, t->obedit)) return;
/* count */
+ if (propconnected) {
+ /* create element map with island information */
+ if (ts->uv_flag & UV_SYNC_SELECTION) {
+ elementmap = EDBM_uv_element_map_create (em, FALSE, TRUE);
+ }
+ else {
+ elementmap = EDBM_uv_element_map_create (em, TRUE, TRUE);
+ }
+ island_enabled = MEM_callocN(sizeof(*island_enabled) * elementmap->totalIslands, "TransIslandData(UV Editing)");
+ }
+
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
@@ -2382,14 +2378,22 @@ static void createTransUVs(bContext *C, TransInfo *t)
BM_elem_flag_disable(efa, BM_ELEM_TAG);
continue;
}
-
+
BM_elem_flag_enable(efa, BM_ELEM_TAG);
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
- if (uvedit_uv_select_test(em, scene, l))
+ if (uvedit_uv_select_test(em, scene, l)) {
countsel++;
- if (propmode)
+ if (propconnected) {
+ UvElement *element = ED_uv_element_get(elementmap, efa, l);
+ island_enabled[element->island] = TRUE;
+ }
+
+ }
+
+ if (propmode) {
count++;
+ }
}
}
@@ -2415,12 +2419,26 @@ static void createTransUVs(bContext *C, TransInfo *t)
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
if (!propmode && !uvedit_uv_select_test(em, scene, l))
continue;
+
+ if (propconnected) {
+ UvElement *element = ED_uv_element_get(elementmap, efa, l);
+ if (!island_enabled[element->island]) {
+ count_rejected++;
+ continue;
+ }
+ }
luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
UVsToTransData(sima, td++, td2d++, luv->uv, uvedit_uv_select_test(em, scene, l));
}
}
+ if (propconnected) {
+ t->total -= count_rejected;
+ EDBM_uv_element_map_free(elementmap);
+ MEM_freeN(island_enabled);
+ }
+
if (sima->flag & SI_LIVE_UNWRAP)
ED_uvedit_live_unwrap_begin(t->scene, t->obedit);
}
@@ -2512,8 +2530,8 @@ void clipUVData(TransInfo *t)
if ((td->flag & TD_SKIP) || (!td->loc))
continue;
- td->loc[0] = minf(maxf(0.0f, td->loc[0]), aspx);
- td->loc[1] = minf(maxf(0.0f, td->loc[1]), aspy);
+ td->loc[0] = min_ff(max_ff(0.0f, td->loc[0]), aspx);
+ td->loc[1] = min_ff(max_ff(0.0f, td->loc[1]), aspy);
}
}
@@ -3295,15 +3313,19 @@ static void createTransActionData(bContext *C, TransInfo *t)
if (ELEM(ac.datatype, ANIMCONT_GPENCIL, ANIMCONT_MASK)) {
if (t->mode == TFM_TIME_SLIDE) {
t->customData = MEM_callocN((sizeof(float) * 2) + (sizeof(tGPFtransdata) * count), "TimeSlide + tGPFtransdata");
+ t->flag |= T_FREE_CUSTOMDATA;
tfd = (tGPFtransdata *)((float *)(t->customData) + 2);
}
else {
t->customData = MEM_callocN(sizeof(tGPFtransdata) * count, "tGPFtransdata");
+ t->flag |= T_FREE_CUSTOMDATA;
tfd = (tGPFtransdata *)(t->customData);
}
}
- else if (t->mode == TFM_TIME_SLIDE)
+ else if (t->mode == TFM_TIME_SLIDE) {
t->customData = MEM_callocN(sizeof(float) * 2, "TimeSlide Min/Max");
+ t->flag |= T_FREE_CUSTOMDATA;
+ }
/* loop 2: build transdata array */
for (ale = anim_data.first; ale; ale = ale->next) {
@@ -3414,14 +3436,14 @@ static void bezt_to_transdata(TransData *td, TransData2D *td2d, AnimData *adt, B
if (td->flag & TD_MOVEHANDLE1) {
td2d->h1 = bezt->vec[0];
copy_v2_v2(td2d->ih1, td2d->h1);
- }
- else
+ }
+ else
td2d->h1 = NULL;
if (td->flag & TD_MOVEHANDLE2) {
td2d->h2 = bezt->vec[2];
copy_v2_v2(td2d->ih2, td2d->h2);
- }
+ }
else
td2d->h2 = NULL;
@@ -3525,7 +3547,7 @@ static void createTransGraphEditData(bContext *C, TransInfo *t)
if (sel1) count++;
if (sel3) count++;
}
- }
+ }
else if (sipo->around == V3D_LOCAL) {
/* for local-pivot we only need to count the number of selected handles only, so that centerpoints don't
* don't get moved wrong
@@ -3620,18 +3642,18 @@ static void createTransGraphEditData(bContext *C, TransInfo *t)
if (sel1) {
hdata = initTransDataCurveHandles(td, bezt);
bezt_to_transdata(td++, td2d++, adt, bezt, 0, 1, 1, intvals, mtx, smtx);
- }
+ }
else {
- /* h1= 0; */ /* UNUSED */
+ /* h1 = 0; */ /* UNUSED */
}
if (sel3) {
if (hdata == NULL)
hdata = initTransDataCurveHandles(td, bezt);
bezt_to_transdata(td++, td2d++, adt, bezt, 2, 1, 1, intvals, mtx, smtx);
- }
+ }
else {
- /* h2= 0; */ /* UNUSED */
+ /* h2 = 0; */ /* UNUSED */
}
}
@@ -3984,13 +4006,13 @@ static void SeqTransInfo(TransInfo *t, Sequence *seq, int *recursive, int *count
*flag = (seq->flag | SELECT) & ~(SEQ_LEFTSEL | SEQ_RIGHTSEL);
if (t->frame_side == 'R') {
- if (right <= cfra) *count = *flag = 0; /* ignore */
- else if (left > cfra) ; /* keep the selection */
+ if (right <= cfra) { *count = *flag = 0; } /* ignore */
+ else if (left > cfra) { } /* keep the selection */
else *flag |= SEQ_RIGHTSEL;
}
else {
- if (left >= cfra) *count = *flag = 0; /* ignore */
- else if (right < cfra) ; /* keep the selection */
+ if (left >= cfra) { *count = *flag = 0; } /* ignore */
+ else if (right < cfra) { } /* keep the selection */
else *flag |= SEQ_LEFTSEL;
}
}
@@ -4253,15 +4275,14 @@ static void freeSeqData(TransInfo *t)
}
}
-#if 1 /* (mango hack! - for Ian) this is truely bad - should _never_ be in a release :| */
- if (CTX_wm_window(t->context)->eventstate->alt) {
+ if (t->flag & T_ALT_TRANSFORM) {
int minframe = MAXFRAME;
td = t->data;
seq_prev = NULL;
for (a = 0; a < t->total; a++, td++) {
seq = ((TransDataSeq *)td->extra)->seq;
if ((seq != seq_prev)) {
- minframe = mini(minframe, seq->startdisp);
+ minframe = min_ii(minframe, seq->startdisp);
}
}
@@ -4291,9 +4312,6 @@ static void freeSeqData(TransInfo *t)
else {
BKE_sequence_base_shuffle_time(seqbasep, t->scene);
}
-#else
- BKE_sequence_base_shuffle_time(seqbasep, t->scene);
-#endif
if (has_effect) {
/* update effects strips based on strips just moved in time */
@@ -4467,6 +4485,7 @@ static short constraints_list_needinv(TransInfo *t, ListBase *list)
if (con->type == CONSTRAINT_TYPE_FOLLOWPATH) return 1;
if (con->type == CONSTRAINT_TYPE_CLAMPTO) return 1;
if (con->type == CONSTRAINT_TYPE_OBJECTSOLVER) return 1;
+ if (con->type == CONSTRAINT_TYPE_FOLLOWTRACK) return 1;
/* constraints that require this only under special conditions */
if (con->type == CONSTRAINT_TYPE_ROTLIKE) {
@@ -4543,7 +4562,7 @@ static void ObjectToTransData(TransInfo *t, TransData *td, Object *ob)
td->ext->irotAngle = ob->rotAngle;
copy_v3_v3(td->ext->irotAxis, ob->rotAxis);
- // td->ext->drotAngle= ob->drotAngle; // XXX, not implemented
+ // td->ext->drotAngle = ob->drotAngle; // XXX, not implemented
// copy_v3_v3(td->ext->drotAxis, ob->drotAxis); // XXX, not implemented
}
else {
@@ -4601,7 +4620,7 @@ static void set_trans_object_base_flags(TransInfo *t)
/*
* if Base selected and has parent selected:
- * base->flag= BA_WAS_SEL
+ * base->flag = BA_WAS_SEL
*/
Base *base;
@@ -5170,7 +5189,7 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
/* Depending on the lock status, draw necessary views */
// fixme... some of this stuff is not good
if (ob) {
- if (ob->pose || ob_get_key(ob))
+ if (ob->pose || BKE_key_from_object(ob))
DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
else
DAG_id_tag_update(&ob->id, OB_RECALC_OB);
@@ -5554,8 +5573,8 @@ static void createTransObject(bContext *C, TransInfo *t)
static void NodeToTransData(TransData *td, TransData2D *td2d, bNode *node)
{
/* hold original location */
- float locxy[2] = {BLI_RCT_CENTER_X(&node->totr),
- BLI_RCT_CENTER_Y(&node->totr)};
+ float locxy[2] = {BLI_rctf_cent_x(&node->totr),
+ BLI_rctf_cent_y(&node->totr)};
copy_v2_v2(td2d->loc, locxy);
td2d->loc[2] = 0.0f;
@@ -5722,10 +5741,9 @@ static void markerToTransDataInit(TransData *td, TransData2D *td2d, TransDataTra
unit_m3(td->smtx);
}
-static void trackToTransData(SpaceClip *sc, TransData *td, TransData2D *td2d,
+static void trackToTransData(const int framenr, TransData *td, TransData2D *td2d,
TransDataTracking *tdt, MovieTrackingTrack *track, float aspx, float aspy)
{
- int framenr = ED_space_clip_get_clip_frame_number(sc);
MovieTrackingMarker *marker = BKE_tracking_marker_ensure(track, framenr);
tdt->flag = marker->flag;
@@ -5766,6 +5784,7 @@ static void transDataTrackingFree(TransInfo *t)
MEM_freeN(tdt->smarkers);
MEM_freeN(tdt);
+ t->customData = NULL;
}
}
@@ -5777,7 +5796,6 @@ static void createTransTrackingTracksData(bContext *C, TransInfo *t)
MovieClip *clip = ED_space_clip_get_clip(sc);
ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
MovieTrackingTrack *track;
- MovieTrackingMarker *marker;
TransDataTracking *tdt;
int framenr = ED_space_clip_get_clip_frame_number(sc);
float aspx, aspy;
@@ -5788,8 +5806,6 @@ static void createTransTrackingTracksData(bContext *C, TransInfo *t)
track = tracksbase->first;
while (track) {
if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
- marker = BKE_tracking_marker_get(track, framenr);
-
t->total++; /* offset */
if (track->flag & SELECT)
@@ -5820,9 +5836,7 @@ static void createTransTrackingTracksData(bContext *C, TransInfo *t)
track = tracksbase->first;
while (track) {
if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
- marker = BKE_tracking_marker_get(track, framenr);
-
- trackToTransData(sc, td, td2d, tdt, track, aspx, aspy);
+ trackToTransData(framenr, td, td2d, tdt, track, aspx, aspy);
/* offset */
td++;
@@ -5845,12 +5859,6 @@ static void createTransTrackingTracksData(bContext *C, TransInfo *t)
td += 2;
td2d += 2;
tdt += 2;
-
- if (marker->flag & MARKER_DISABLED) {
- td += 3;
- td2d += 3;
- tdt += 3;
- };
}
}
@@ -6435,10 +6443,10 @@ void createTransData(bContext *C, TransInfo *t)
else if (t->obedit) {
t->ext = NULL;
if (t->obedit->type == OB_MESH) {
- createTransEditVerts(C, t);
+ createTransEditVerts(t);
}
else if (ELEM(t->obedit->type, OB_CURVE, OB_SURF)) {
- createTransCurveVerts(C, t);
+ createTransCurveVerts(t);
}
else if (t->obedit->type == OB_LATTICE) {
createTransLatticeVerts(t);
diff --git a/source/blender/editors/transform/transform_generics.c b/source/blender/editors/transform/transform_generics.c
index 325dbe639b4..615bb786071 100644
--- a/source/blender/editors/transform/transform_generics.c
+++ b/source/blender/editors/transform/transform_generics.c
@@ -705,7 +705,7 @@ static void recalcData_view3d(TransInfo *t)
BKE_nurb_handles_calc(nu); /* Cant do testhandlesNurb here, it messes up the h1 and h2 flags */
nu = nu->next;
}
- }
+ }
else {
/* Normal updating */
while (nu) {
@@ -895,16 +895,20 @@ static void recalcData_view3d(TransInfo *t)
/* helper for recalcData() - for sequencer transforms */
static void recalcData_sequencer(TransInfo *t)
{
- Editing *ed = BKE_sequencer_editing_get(t->scene, FALSE);
- Sequence *seq;
+ TransData *td;
+ int a;
+ Sequence *seq_prev = NULL;
- SEQ_BEGIN(ed, seq)
- {
- if (seq->flag & SELECT) {
- BKE_sequence_invalidate_deendent(t->scene, seq);
+ for (a = 0, td = t->data; a < t->total; a++, td++) {
+ TransDataSeq *tdsq = (TransDataSeq *) td->extra;
+ Sequence *seq = tdsq->seq;
+
+ if (seq != seq_prev) {
+ BKE_sequence_invalidate_dependent(t->scene, seq);
}
+
+ seq_prev = seq;
}
- SEQ_END
BKE_sequencer_preprocessed_cache_cleanup();
@@ -998,9 +1002,9 @@ int initTransInfo(bContext *C, TransInfo *t, wmOperator *op, wmEvent *event)
/* moving: is shown in drawobject() (transform color) */
// TRANSFORM_FIX_ME
-// if (obedit || (t->flag & T_POSE) ) G.moving= G_TRANSFORM_EDIT;
-// else if (G.f & G_PARTICLEEDIT) G.moving= G_TRANSFORM_PARTICLE;
-// else G.moving= G_TRANSFORM_OBJ;
+// if (obedit || (t->flag & T_POSE) ) G.moving = G_TRANSFORM_EDIT;
+// else if (G.f & G_PARTICLEEDIT) G.moving = G_TRANSFORM_PARTICLE;
+// else G.moving = G_TRANSFORM_OBJ;
t->scene = sce;
t->sa = sa;
@@ -1248,7 +1252,7 @@ int initTransInfo(bContext *C, TransInfo *t, wmOperator *op, wmEvent *event)
/* TRANSFORM_FIX_ME rna restrictions */
if (t->prop_size <= 0.00001f) {
- printf("Proportional size (%f) under 0.00001, reseting to 1!\n", t->prop_size);
+ printf("Proportional size (%f) under 0.00001, resetting to 1!\n", t->prop_size);
t->prop_size = 1.0f;
}
@@ -1293,19 +1297,26 @@ void postTrans(bContext *C, TransInfo *t)
if (t->customFree) {
/* Can take over freeing t->data and data2d etc... */
t->customFree(t);
+ BLI_assert(t->customData == NULL);
}
else if ((t->customData != NULL) && (t->flag & T_FREE_CUSTOMDATA)) {
MEM_freeN(t->customData);
+ t->customData = NULL;
}
/* postTrans can be called when nothing is selected, so data is NULL already */
if (t->data) {
- int a;
/* free data malloced per trans-data */
- for (a = 0, td = t->data; a < t->total; a++, td++) {
- if (td->flag & TD_BEZTRIPLE)
- MEM_freeN(td->hdata);
+ if ((t->obedit && ELEM(t->obedit->type, OB_CURVE, OB_SURF)) ||
+ (t->spacetype == SPACE_IPO))
+ {
+ int a;
+ for (a = 0, td = t->data; a < t->total; a++, td++) {
+ if (td->flag & TD_BEZTRIPLE) {
+ MEM_freeN(td->hdata);
+ }
+ }
}
MEM_freeN(t->data);
}
@@ -1557,9 +1568,8 @@ void calculateCenterBound(TransInfo *t)
copy_v3_v3(min, t->data[i].center);
}
}
- add_v3_v3v3(t->center, min, max);
- mul_v3_fl(t->center, 0.5);
-
+ mid_v3_v3v3(t->center, min, max);
+
calculateCenter2D(t);
}
@@ -1701,8 +1711,9 @@ void calculatePropRatio(TransInfo *t)
/*
* The elements are sorted according to their dist member in the array,
* that means we can stop when it finds one element outside of the propsize.
+ * do not set 'td->flag |= TD_NOACTION', the prop circle is being changed.
*/
- td->flag |= TD_NOACTION;
+
td->factor = 0.0f;
restoreElement(td);
}
diff --git a/source/blender/editors/transform/transform_manipulator.c b/source/blender/editors/transform/transform_manipulator.c
index 74a2292d74c..0780b8f90b5 100644
--- a/source/blender/editors/transform/transform_manipulator.c
+++ b/source/blender/editors/transform/transform_manipulator.c
@@ -441,7 +441,7 @@ int calc_manipulator_stats(const bContext *C)
}
else if (obedit->type == OB_MBALL) {
MetaBall *mb = (MetaBall *)obedit->data;
- MetaElem *ml /* , *ml_sel=NULL */ /* UNUSED */;
+ MetaElem *ml /* , *ml_sel = NULL */ /* UNUSED */;
ml = mb->editelems->first;
while (ml) {
@@ -498,7 +498,7 @@ int calc_manipulator_stats(const bContext *C)
}
}
else if (ob && (ob->mode & OB_MODE_ALL_PAINT)) {
- ;
+ /* pass */
}
else if (ob && ob->mode & OB_MODE_PARTICLE_EDIT) {
PTCacheEdit *edit = PE_get_current(scene, ob);
diff --git a/source/blender/editors/transform/transform_ops.c b/source/blender/editors/transform/transform_ops.c
index 81a4c082dcc..916cf540589 100644
--- a/source/blender/editors/transform/transform_ops.c
+++ b/source/blender/editors/transform/transform_ops.c
@@ -284,7 +284,7 @@ static int create_orientation_exec(bContext *C, wmOperator *op)
RNA_string_get(op->ptr, "name", name);
if (use && !CTX_wm_view3d(C)) {
- BKE_report(op->reports, RPT_ERROR, "Create Orientation \"use\" parameter only valid in a 3dView context");
+ BKE_report(op->reports, RPT_ERROR, "Create Orientation's 'use' parameter only valid in a 3DView context");
return OPERATOR_CANCELLED;
}
@@ -605,8 +605,10 @@ static void TRANSFORM_OT_trackball(struct wmOperatorType *ot)
static void TRANSFORM_OT_rotate(struct wmOperatorType *ot)
{
+ PropertyRNA *prop;
+
/* identifiers */
- ot->name = "Rotate";
+ ot->name = "Rotate";
ot->description = "Rotate selected items";
ot->idname = OP_ROTATION;
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
@@ -618,19 +620,22 @@ static void TRANSFORM_OT_rotate(struct wmOperatorType *ot)
ot->cancel = transform_cancel;
ot->poll = ED_operator_screenactive;
- RNA_def_float_rotation(ot->srna, "value", 1, NULL, -FLT_MAX, FLT_MAX, "Angle", "", -M_PI * 2, M_PI * 2);
+ prop = RNA_def_float(ot->srna, "value", 0.0f, -FLT_MAX, FLT_MAX, "Angle", "", -M_PI * 2, M_PI * 2);
+ RNA_def_property_subtype(prop, PROP_ANGLE);
Transform_Properties(ot, P_AXIS | P_CONSTRAINT | P_PROPORTIONAL | P_MIRROR | P_GEO_SNAP);
}
static void TRANSFORM_OT_tilt(struct wmOperatorType *ot)
{
+ PropertyRNA *prop;
+
/* identifiers */
- ot->name = "Tilt";
+ ot->name = "Tilt";
/* optionals -
* "Tilt selected vertices"
- * "Specify an extra axis rotation for selected vertices of 3d curve" */
- ot->description = "Tilt selected control vertices of 3d curve";
+ * "Specify an extra axis rotation for selected vertices of 3D curve" */
+ ot->description = "Tilt selected control vertices of 3D curve";
ot->idname = OP_TILT;
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
@@ -641,9 +646,10 @@ static void TRANSFORM_OT_tilt(struct wmOperatorType *ot)
ot->cancel = transform_cancel;
ot->poll = ED_operator_editcurve_3d;
- RNA_def_float_rotation(ot->srna, "value", 1, NULL, -FLT_MAX, FLT_MAX, "Angle", "", -M_PI * 2, M_PI * 2);
+ prop = RNA_def_float(ot->srna, "value", 0.0, -FLT_MAX, FLT_MAX, "Angle", "", -M_PI * 2, M_PI * 2);
+ RNA_def_property_subtype(prop, PROP_ANGLE);
- Transform_Properties(ot, P_CONSTRAINT | P_PROPORTIONAL | P_MIRROR | P_SNAP);
+ Transform_Properties(ot, P_PROPORTIONAL | P_MIRROR | P_SNAP);
}
static void TRANSFORM_OT_warp(struct wmOperatorType *ot)
diff --git a/source/blender/editors/transform/transform_orientations.c b/source/blender/editors/transform/transform_orientations.c
index a155ff7786a..70e4d4cd027 100644
--- a/source/blender/editors/transform/transform_orientations.c
+++ b/source/blender/editors/transform/transform_orientations.c
@@ -142,7 +142,7 @@ TransformOrientation *createObjectSpace(bContext *C, ReportList *UNUSED(reports)
strncpy(name, ob->id.name + 2, MAX_ID_NAME - 2);
}
- return addMatrixSpace(C, mat, name, overwrite);
+ return addMatrixSpace(C, mat, name, overwrite);
}
TransformOrientation *createBoneSpace(bContext *C, ReportList *reports, char *name, int overwrite)
@@ -402,7 +402,7 @@ EnumPropertyItem *BIF_enumTransformOrientation(bContext *C)
const char *BIF_menustringTransformOrientation(const bContext *C, const char *title)
{
- const char *menu = IFACE_("%t|Global%x0|Local%x1|Gimbal%x4|Normal%x2|View%x3");
+ const char *menu = IFACE_("%t|Global %x0|Local %x1|Gimbal %x4|Normal %x2|View %x3");
ListBase *transform_spaces = &CTX_data_scene(C)->transform_spaces;
TransformOrientation *ts;
int i = V3D_MANIP_CUSTOM;
@@ -411,14 +411,14 @@ const char *BIF_menustringTransformOrientation(const bContext *C, const char *ti
title = IFACE_(title);
- str_menu = MEM_callocN(strlen(menu) + strlen(title) + 1 + elem_size * BIF_countTransformOrientation(C), TIP_("UserTransSpace from matrix"));
+ str_menu = MEM_callocN(strlen(menu) + strlen(title) + 1 + elem_size * BIF_countTransformOrientation(C), "UserTransSpace from matrix");
p = str_menu;
p += sprintf(str_menu, "%s", title);
p += sprintf(p, "%s", menu);
for (ts = transform_spaces->first; ts; ts = ts->next) {
- p += sprintf(p, "|%s%%x%d", ts->name, i++);
+ p += sprintf(p, "|%s %%x%d", ts->name, i++);
}
return str_menu;
@@ -631,7 +631,6 @@ int getTransformOrientation(const bContext *C, float normal[3], float plane[3],
/* if there's an edge available, use that for the tangent */
if (em->bm->totedgesel >= 1) {
BMEdge *eed = NULL;
- BMIter iter;
BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
@@ -746,14 +745,14 @@ int getTransformOrientation(const bContext *C, float normal[3], float plane[3],
MetaBall *mb = obedit->data;
if (mb->lastelem) {
- float mat[4][4];
+ float qmat[3][3];
/* Rotation of MetaElem is stored in quat */
- quat_to_mat4(mat, mb->lastelem->quat);
+ quat_to_mat3(qmat, mb->lastelem->quat);
- copy_v3_v3(normal, mat[2]);
+ copy_v3_v3(normal, qmat[2]);
- negate_v3_v3(plane, mat[1]);
+ negate_v3_v3(plane, qmat[1]);
result = ORIENTATION_FACE;
}
diff --git a/source/blender/editors/transform/transform_snap.c b/source/blender/editors/transform/transform_snap.c
index b88ae68e00b..a6fb7e7ed00 100644
--- a/source/blender/editors/transform/transform_snap.c
+++ b/source/blender/editors/transform/transform_snap.c
@@ -78,7 +78,7 @@
#include "transform.h"
-#define USE_BVH_FACE_SNAP
+#define TRANSFORM_DIST_MAX_PX 1000
/********************* PROTOTYPES ***********************/
@@ -296,7 +296,7 @@ void applyProject(TransInfo *t)
for (i = 0; i < t->total; i++, td++) {
float iloc[3], loc[3], no[3];
float mval[2];
- int dist = 1000;
+ int dist = TRANSFORM_DIST_MAX_PX;
if (td->flag & TD_NOACTION)
break;
@@ -315,18 +315,18 @@ void applyProject(TransInfo *t)
copy_v3_v3(iloc, td->ob->obmat[3]);
}
- project_float(t->ar, iloc, mval);
-
- if (snapObjectsTransform(t, mval, &dist, loc, no, t->tsnap.modeSelect)) {
-// if (t->flag & (T_EDIT|T_POSE)) {
-// mul_m4_v3(imat, loc);
-// }
-//
- sub_v3_v3v3(tvec, loc, iloc);
-
- mul_m3_v3(td->smtx, tvec);
-
- add_v3_v3(td->loc, tvec);
+ if (ED_view3d_project_float_global(t->ar, iloc, mval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ if (snapObjectsTransform(t, mval, &dist, loc, no, t->tsnap.modeSelect)) {
+// if (t->flag & (T_EDIT|T_POSE)) {
+// mul_m4_v3(imat, loc);
+// }
+
+ sub_v3_v3v3(tvec, loc, iloc);
+
+ mul_m3_v3(td->smtx, tvec);
+
+ add_v3_v3(td->loc, tvec);
+ }
}
//XXX constraintTransLim(t, td);
@@ -601,7 +601,9 @@ int updateSelectedSnapPoint(TransInfo *t)
int dx, dy;
int dist;
- project_int(t->ar, p->co, screen_loc);
+ if (ED_view3d_project_int_global(t->ar, p->co, screen_loc, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
+ continue;
+ }
dx = t->mval[0] - screen_loc[0];
dy = t->mval[1] - screen_loc[1];
@@ -719,14 +721,14 @@ static float RotationBetween(TransInfo *t, float p1[3], float p2[3])
{
float angle, start[3], end[3], center[3];
- copy_v3_v3(center, t->center);
+ copy_v3_v3(center, t->center);
if (t->flag & (T_EDIT | T_POSE)) {
Object *ob = t->obedit ? t->obedit : t->poseobj;
mul_m4_v3(ob->obmat, center);
}
sub_v3_v3v3(start, p1, center);
- sub_v3_v3v3(end, p2, center);
+ sub_v3_v3v3(end, p2, center);
// Angle around a constraint axis (error prone, will need debug)
if (t->con.applyRot != NULL && (t->con.mode & CON_APPLY)) {
@@ -775,7 +777,7 @@ static float ResizeBetween(TransInfo *t, float p1[3], float p2[3])
{
float d1[3], d2[3], center[3], len_d1;
- copy_v3_v3(center, t->center);
+ copy_v3_v3(center, t->center);
if (t->flag & (T_EDIT | T_POSE)) {
Object *ob = t->obedit ? t->obedit : t->poseobj;
mul_m4_v3(ob->obmat, center);
@@ -842,7 +844,7 @@ static void CalcSnapGeometry(TransInfo *t, float *UNUSED(vec))
p2 = NULL;
p1->flag = 1;
- /* if peeling objects, take the first and last from each object */
+ /* if peeling objects, take the first and last from each object */
if (t->settings->snap_flag & SCE_SNAP_PEEL_OBJECT) {
DepthPeel *peel;
for (peel = p1->next; peel; peel = peel->next) {
@@ -960,8 +962,8 @@ static void TargetSnapOffset(TransInfo *t, TransData *td)
if (t->spacetype == SPACE_NODE && td != NULL) {
bNode *node = td->extra;
char border = t->tsnap.snapNodeBorder;
- float width = BLI_RCT_SIZE_X(&node->totr);
- float height = BLI_RCT_SIZE_Y(&node->totr);
+ float width = BLI_rctf_size_x(&node->totr);
+ float height = BLI_rctf_size_y(&node->totr);
if (border & NODE_LEFT)
t->tsnap.snapTarget[0] -= 0.5f * width;
@@ -978,7 +980,7 @@ static void TargetSnapCenter(TransInfo *t)
{
/* Only need to calculate once */
if ((t->tsnap.status & TARGET_INIT) == 0) {
- copy_v3_v3(t->tsnap.snapTarget, t->center);
+ copy_v3_v3(t->tsnap.snapTarget, t->center);
if (t->flag & (T_EDIT | T_POSE)) {
Object *ob = t->obedit ? t->obedit : t->poseobj;
@@ -987,7 +989,7 @@ static void TargetSnapCenter(TransInfo *t)
TargetSnapOffset(t, NULL);
- t->tsnap.status |= TARGET_INIT;
+ t->tsnap.status |= TARGET_INIT;
}
}
@@ -1023,7 +1025,7 @@ static void TargetSnapActive(TransInfo *t)
t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
t->tsnap.targetSnap = TargetSnapMedian;
TargetSnapMedian(t);
- }
+ }
}
}
@@ -1051,7 +1053,7 @@ static void TargetSnapMedian(TransInfo *t)
TargetSnapOffset(t, NULL);
- t->tsnap.status |= TARGET_INIT;
+ t->tsnap.status |= TARGET_INIT;
}
}
@@ -1132,58 +1134,6 @@ static void TargetSnapClosest(TransInfo *t)
t->tsnap.status |= TARGET_INIT;
}
}
-/*================================================================*/
-#ifndef USE_BVH_FACE_SNAP
-static int snapFace(ARegion *ar, float v1co[3], float v2co[3], float v3co[3], float *v4co, float mval[2], float ray_start[3], float ray_start_local[3], float ray_normal_local[3], float obmat[][4], float timat[][3], float loc[3], float no[3], int *dist, float *depth)
-{
- float lambda;
- int result;
- int retval = 0;
-
- result = isect_ray_tri_threshold_v3(ray_start_local, ray_normal_local, v1co, v2co, v3co, &lambda, NULL, 0.001);
-
- if (result) {
- float location[3], normal[3];
- float intersect[3];
- float new_depth;
- int screen_loc[2];
- int new_dist;
-
- copy_v3_v3(intersect, ray_normal_local);
- mul_v3_fl(intersect, lambda);
- add_v3_v3(intersect, ray_start_local);
-
- copy_v3_v3(location, intersect);
-
- if (v4co)
- normal_quad_v3(normal, v1co, v2co, v3co, v4co);
- else
- normal_tri_v3(normal, v1co, v2co, v3co);
-
- mul_m4_v3(obmat, location);
-
- new_depth = len_v3v3(location, ray_start);
-
- project_int(ar, location, screen_loc);
- new_dist = abs(screen_loc[0] - (int)mval[0]) + abs(screen_loc[1] - (int)mval[1]);
-
- if (new_dist <= *dist && new_depth < *depth) {
- *depth = new_depth;
- retval = 1;
-
- copy_v3_v3(loc, location);
- copy_v3_v3(no, normal);
-
- mul_m3_v3(timat, no);
- normalize_v3(no);
-
- *dist = new_dist;
- }
- }
-
- return retval;
-}
-#endif
static int snapEdge(ARegion *ar, float v1co[3], short v1no[3], float v2co[3], short v2no[3], float obmat[][4], float timat[][3],
const float ray_start[3], const float ray_start_local[3], const float ray_normal_local[3], const float mval[2],
@@ -1230,10 +1180,14 @@ static int snapEdge(ARegion *ar, float v1co[3], short v1no[3], float v2co[3], sh
mul_m4_v3(obmat, location);
- new_depth = len_v3v3(location, ray_start);
+ new_depth = len_v3v3(location, ray_start);
- project_int(ar, location, screen_loc);
- new_dist = abs(screen_loc[0] - (int)mval[0]) + abs(screen_loc[1] - (int)mval[1]);
+ if (ED_view3d_project_int_global(ar, location, screen_loc, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ new_dist = abs(screen_loc[0] - (int)mval[0]) + abs(screen_loc[1] - (int)mval[1]);
+ }
+ else {
+ new_dist = TRANSFORM_DIST_MAX_PX;
+ }
/* 10% threshold if edge is closer but a bit further
* this takes care of series of connected edges a bit slanted w.r.t the viewport
@@ -1251,17 +1205,17 @@ static int snapEdge(ARegion *ar, float v1co[3], short v1no[3], float v2co[3], sh
mul = dot_v3v3(vec, edge_loc) / dot_v3v3(edge_loc, edge_loc);
if (r_no) {
- normal_short_to_float_v3(n1, v1no);
+ normal_short_to_float_v3(n1, v1no);
normal_short_to_float_v3(n2, v2no);
interp_v3_v3v3(r_no, n2, n1, mul);
mul_m3_v3(timat, r_no);
normalize_v3(r_no);
- }
+ }
copy_v3_v3(r_loc, location);
*r_dist = new_dist;
- }
+ }
}
}
@@ -1289,8 +1243,13 @@ static int snapVertex(ARegion *ar, float vco[3], short vno[3], float obmat[][4],
new_depth = len_v3v3(location, ray_start);
- project_int(ar, location, screen_loc);
- new_dist = abs(screen_loc[0] - (int)mval[0]) + abs(screen_loc[1] - (int)mval[1]);
+ if (ED_view3d_project_int_global(ar, location, screen_loc, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
+ new_dist = abs(screen_loc[0] - (int)mval[0]) + abs(screen_loc[1] - (int)mval[1]);
+ }
+ else {
+ new_dist = TRANSFORM_DIST_MAX_PX;
+ }
+
if (new_dist <= *r_dist && new_depth < *r_depth) {
*r_depth = new_depth;
@@ -1305,7 +1264,7 @@ static int snapVertex(ARegion *ar, float vco[3], short vno[3], float obmat[][4],
}
*r_dist = new_dist;
- }
+ }
}
return retval;
@@ -1412,8 +1371,7 @@ static int snapDerivedMesh(short snap_mode, ARegion *ar, Object *ob, DerivedMesh
switch (snap_mode) {
case SCE_SNAP_MODE_FACE:
- {
-#ifdef USE_BVH_FACE_SNAP // Added for durian
+ {
BVHTreeRayHit hit;
BVHTreeFromMesh treeData;
@@ -1443,80 +1401,6 @@ static int snapDerivedMesh(short snap_mode, ARegion *ar, Object *ob, DerivedMesh
}
}
break;
-
-#else
- MVert *verts = dm->getVertArray(dm);
- MFace *faces = dm->getTessFaceArray(dm);
- int *index_array = NULL;
- int index = 0;
- int i;
-
- if (em != NULL) {
- index_array = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
- EDBM_index_arrays_init(em, 0, 0, 1);
- }
-
- for (i = 0; i < totface; i++) {
- BMFace *efa = NULL;
- MFace *f = faces + i;
-
- test = 1; /* reset for every face */
-
- if (em != NULL) {
- if (index_array) {
- index = index_array[i];
- }
- else {
- index = i;
- }
-
- if (index == ORIGINDEX_NONE) {
- test = 0;
- }
- else {
- efa = EDBM_face_at_index(em, index);
-
- if (efa && BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
- test = 0;
- }
- else if (efa) {
- BMIter iter;
- BMLoop *l;
-
- l = BM_iter_new(&iter, em->bm, BM_LOOPS_OF_FACE, efa);
- for (; l; l = BM_iter_step(&iter)) {
- if (BM_elem_flag_test(l->v, BM_ELEM_SELECT)) {
- test = 0;
- break;
- }
- }
- }
- }
- }
-
-
- if (test) {
- int result;
- float *v4co = NULL;
-
- if (f->v4) {
- v4co = verts[f->v4].co;
- }
-
- result = snapFace(ar, verts[f->v1].co, verts[f->v2].co, verts[f->v3].co, v4co, mval, ray_start, ray_start_local, ray_normal_local, obmat, timat, loc, no, dist, depth);
- retval |= result;
-
- if (f->v4 && result == 0) {
- retval |= snapFace(ar, verts[f->v3].co, verts[f->v4].co, verts[f->v1].co, verts[f->v2].co, mval, ray_start, ray_start_local, ray_normal_local, obmat, timat, loc, no, dist, depth);
- }
- }
- }
-
- if (em != NULL) {
- EDBM_index_arrays_free(em);
- }
-#endif
- break;
}
case SCE_SNAP_MODE_VERTEX:
{
@@ -1697,7 +1581,7 @@ static int snapObjects(Scene *scene, View3D *v3d, ARegion *ar, Object *obedit, c
if (ob->transflag & OB_DUPLI) {
DupliObject *dupli_ob;
- ListBase *lb = object_duplilist(scene, ob);
+ ListBase *lb = object_duplilist(scene, ob, FALSE);
for (dupli_ob = lb->first; dupli_ob; dupli_ob = dupli_ob->next) {
Object *dob = dupli_ob->ob;
@@ -1845,7 +1729,7 @@ static int peelDerivedMesh(Object *ob, DerivedMesh *dm, float obmat[][4],
mul_m4_v3(obmat, location);
- new_depth = len_v3v3(location, ray_start);
+ new_depth = len_v3v3(location, ray_start);
mul_m3_v3(timat, normal);
normalize_v3(normal);
@@ -1880,7 +1764,7 @@ static int peelDerivedMesh(Object *ob, DerivedMesh *dm, float obmat[][4],
normalize_v3(normal);
addDepthPeel(depth_peels, new_depth, location, normal, ob);
- }
+ }
}
}
}
@@ -1903,7 +1787,7 @@ static int peelObjects(Scene *scene, View3D *v3d, ARegion *ar, Object *obedit, L
if (ob->transflag & OB_DUPLI) {
DupliObject *dupli_ob;
- ListBase *lb = object_duplilist(scene, ob);
+ ListBase *lb = object_duplilist(scene, ob, FALSE);
for (dupli_ob = lb->first; dupli_ob; dupli_ob = dupli_ob->next) {
Object *dob = dupli_ob->ob;
diff --git a/source/blender/editors/util/crazyspace.c b/source/blender/editors/util/crazyspace.c
index b0edc702e48..e953aa2f0ed 100644
--- a/source/blender/editors/util/crazyspace.c
+++ b/source/blender/editors/util/crazyspace.c
@@ -409,7 +409,7 @@ void crazyspace_build_sculpt(Scene *scene, Object *ob, float (**deformmats)[3][3
MEM_freeN(quats);
}
- if (!*deformmats) {
+ if (*deformmats == NULL) {
int a, numVerts;
Mesh *me = (Mesh *)ob->data;
diff --git a/source/blender/editors/util/editmode_undo.c b/source/blender/editors/util/editmode_undo.c
index 9a3b0476205..c8c26ed771d 100644
--- a/source/blender/editors/util/editmode_undo.c
+++ b/source/blender/editors/util/editmode_undo.c
@@ -104,7 +104,7 @@ static UndoElem *curundo = NULL;
static void undo_restore(UndoElem *undo, void *editdata, void *obdata)
{
if (undo) {
- undo->to_editmode(undo->undodata, editdata, obdata);
+ undo->to_editmode(undo->undodata, editdata, obdata);
}
}
@@ -233,7 +233,7 @@ static void undo_clean_stack(bContext *C)
if (curundo == NULL) curundo = undobase.last;
}
-/* 1= an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation */
+/* 1 = an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation */
void undo_editmode_step(bContext *C, int step)
{
Object *obedit = CTX_data_edit_object(C);
diff --git a/source/blender/editors/util/numinput.c b/source/blender/editors/util/numinput.c
index 281b682465d..b73f5fa0869 100644
--- a/source/blender/editors/util/numinput.c
+++ b/source/blender/editors/util/numinput.c
@@ -279,7 +279,9 @@ char handleNumInput(NumInput *n, wmEvent *event)
if (!n->ctrl[idx])
n->ctrl[idx] = 1;
- if (fabsf(n->val[idx]) > 9999999.0f) ;
+ if (fabsf(n->val[idx]) > 9999999.0f) {
+ /* pass */
+ }
else if (n->ctrl[idx] == 1) {
n->val[idx] *= 10;
n->val[idx] += Val;
diff --git a/source/blender/editors/util/undo.c b/source/blender/editors/util/undo.c
index 5eafc3e65a9..1753a564a3c 100644
--- a/source/blender/editors/util/undo.c
+++ b/source/blender/editors/util/undo.c
@@ -505,7 +505,7 @@ static int undo_history_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(even
MEM_freeN(item);
uiPupMenuEnd(C, pup);
- }
+ }
}
return OPERATOR_CANCELLED;
diff --git a/source/blender/editors/uvedit/uvedit_draw.c b/source/blender/editors/uvedit/uvedit_draw.c
index d6794912043..9c2c300c530 100644
--- a/source/blender/editors/uvedit/uvedit_draw.c
+++ b/source/blender/editors/uvedit/uvedit_draw.c
@@ -453,8 +453,6 @@ static void draw_uvs(SpaceImage *sima, Scene *scene, Object *obedit)
int drawfaces, interpedges;
Image *ima = sima->image;
- StitchPreviewer *stitch_preview = uv_get_stitch_previewer();
-
activetf = EDBM_mtexpoly_active_get(em, &efa_act, FALSE, FALSE); /* will be set to NULL if hidden */
activef = BM_active_face_get(bm, FALSE, FALSE);
ts = scene->toolsettings;
@@ -536,7 +534,7 @@ static void draw_uvs(SpaceImage *sima, Scene *scene, Object *obedit)
BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
tf = CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_MTEXPOLY);
- if (uvedit_face_visible_test(scene, ima, efa, tf)) {
+ if (uvedit_face_visible_test(scene, ima, efa, tf)) {
BM_elem_flag_enable(efa, BM_ELEM_TAG);
}
else {
@@ -820,52 +818,7 @@ static void draw_uvs(SpaceImage *sima, Scene *scene, Object *obedit)
bglVertex2fv(luv->uv);
}
}
- bglEnd();
- }
-
- /* finally draw stitch preview */
- if (stitch_preview) {
- int i, index = 0;
- glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
- glEnableClientState(GL_VERTEX_ARRAY);
-
- glEnable(GL_BLEND);
-
- UI_ThemeColor4(TH_STITCH_PREVIEW_ACTIVE);
- glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
- glVertexPointer(2, GL_FLOAT, 0, stitch_preview->static_tris);
- glDrawArrays(GL_TRIANGLES, 0, stitch_preview->num_static_tris * 3);
-
- glVertexPointer(2, GL_FLOAT, 0, stitch_preview->preview_polys);
- for (i = 0; i < stitch_preview->num_polys; i++) {
- glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
- UI_ThemeColor4(TH_STITCH_PREVIEW_FACE);
- glDrawArrays(GL_POLYGON, index, stitch_preview->uvs_per_polygon[i]);
- glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
- UI_ThemeColor4(TH_STITCH_PREVIEW_EDGE);
- glDrawArrays(GL_POLYGON, index, stitch_preview->uvs_per_polygon[i]);
-
- index += stitch_preview->uvs_per_polygon[i];
- }
- glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
-#if 0
- UI_ThemeColor4(TH_STITCH_PREVIEW_VERT);
- glDrawArrays(GL_TRIANGLES, 0, stitch_preview->num_tris * 3);
-#endif
- glDisable(GL_BLEND);
-
- /* draw vert preview */
- glPointSize(pointsize * 2.0f);
- UI_ThemeColor4(TH_STITCH_PREVIEW_STITCHABLE);
- glVertexPointer(2, GL_FLOAT, 0, stitch_preview->preview_stitchable);
- glDrawArrays(GL_POINTS, 0, stitch_preview->num_stitchable);
-
- UI_ThemeColor4(TH_STITCH_PREVIEW_UNSTITCHABLE);
- glVertexPointer(2, GL_FLOAT, 0, stitch_preview->preview_unstitchable);
- glDrawArrays(GL_POINTS, 0, stitch_preview->num_unstitchable);
-
- glPopClientAttrib();
- glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ bglEnd();
}
glPointSize(1.0);
diff --git a/source/blender/editors/uvedit/uvedit_intern.h b/source/blender/editors/uvedit/uvedit_intern.h
index f0ff79ae25e..b42875f20c2 100644
--- a/source/blender/editors/uvedit/uvedit_intern.h
+++ b/source/blender/editors/uvedit/uvedit_intern.h
@@ -72,33 +72,8 @@ void uv_find_nearest_edge(struct Scene *scene, struct Image *ima, struct BMEditM
/* utility tool functions */
-struct UvElement *ED_uv_element_get(struct UvElementMap *map, struct BMFace *efa, struct BMLoop *l);
void uvedit_live_unwrap_update(struct SpaceImage *sima, struct Scene *scene, struct Object *obedit);
-/* smart stitch */
-
-/* object that stores display data for previewing before accepting stitching */
-typedef struct StitchPreviewer {
- /* here we'll store the preview triangle indices of the mesh */
- float *preview_polys;
- /* uvs per polygon. */
- unsigned int *uvs_per_polygon;
- /*number of preview polygons */
- unsigned int num_polys;
- /* preview data. These will be either the previewed vertices or edges depending on stitch mode settings */
- float *preview_stitchable;
- float *preview_unstitchable;
- /* here we'll store the number of elements to be drawn */
- unsigned int num_stitchable;
- unsigned int num_unstitchable;
- unsigned int preview_uvs;
- /* ...and here we'll store the triangles*/
- float *static_tris;
- unsigned int num_static_tris;
-} StitchPreviewer;
-
-StitchPreviewer *uv_get_stitch_previewer(void);
-
/* operators */
void UV_OT_average_islands_scale(struct wmOperatorType *ot);
diff --git a/source/blender/editors/uvedit/uvedit_ops.c b/source/blender/editors/uvedit/uvedit_ops.c
index 06da1c8bfea..e860d486ea3 100644
--- a/source/blender/editors/uvedit/uvedit_ops.c
+++ b/source/blender/editors/uvedit/uvedit_ops.c
@@ -170,7 +170,6 @@ void ED_object_assign_active_image(Main *bmain, Object *ob, int mat_nr, Image *i
void ED_uvedit_assign_image(Main *bmain, Scene *scene, Object *obedit, Image *ima, Image *previma)
{
BMEditMesh *em;
- BMFace *efa;
BMIter iter;
MTexPoly *tf;
int update = 0;
@@ -198,6 +197,8 @@ void ED_uvedit_assign_image(Main *bmain, Scene *scene, Object *obedit, Image *im
ED_object_assign_active_image(bmain, obedit, efa->mat_nr + 1, ima);
}
else {
+ BMFace *efa;
+
/* old shading system, assign image to selected faces */
#ifdef USE_SWITCH_ASPECT
float prev_aspect[2], fprev_aspect;
@@ -214,6 +215,8 @@ void ED_uvedit_assign_image(Main *bmain, Scene *scene, Object *obedit, Image *im
if (!CustomData_has_layer(&em->bm->pdata, CD_MTEXPOLY)) {
BM_data_layer_add(em->bm, &em->bm->pdata, CD_MTEXPOLY);
BM_data_layer_add(em->bm, &em->bm->ldata, CD_MLOOPUV);
+ /* make UVs all nice 0-1 */
+ ED_mesh_uv_loop_reset_ex(obedit->data, CustomData_get_active_layer_index(&em->bm->pdata, CD_MTEXPOLY));
update = 1;
}
@@ -759,31 +762,32 @@ static int nearest_uv_between(BMEditMesh *em, BMFace *efa, int UNUSED(nverts), i
BMLoop *l;
MLoopUV *luv;
BMIter iter;
- float m[3], v1[3], v2[3], c1, c2, *uv1 = NULL, /* *uv2, */ /* UNUSED */ *uv3 = NULL;
+ float m[2], v1[2], v2[2], c1, c2, *uv1 = NULL, /* *uv2, */ /* UNUSED */ *uv3 = NULL;
int id1, id2, i;
id1 = (id + efa->len - 1) % efa->len;
id2 = (id + efa->len + 1) % efa->len;
- m[0] = co[0] - uv[0];
- m[1] = co[1] - uv[1];
+ sub_v2_v2v2(m, co, uv);
i = 0;
BM_ITER_ELEM (l, &iter, efa, BM_LOOPS_OF_FACE) {
luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
- if (i == id1)
+ if (i == id1) {
uv1 = luv->uv;
- else if (i == id)
- ; /* uv2 = luv->uv; */ /* UNUSED */
- else if (i == id2)
+ }
+ else if (i == id) {
+ /* uv2 = luv->uv; */ /* UNUSED */
+ }
+ else if (i == id2) {
uv3 = luv->uv;
-
+ }
i++;
}
- sub_v3_v3v3(v1, uv1, uv);
- sub_v3_v3v3(v2, uv3, uv);
+ sub_v2_v2v2(v1, uv1, uv);
+ sub_v2_v2v2(v2, uv3, uv);
/* m and v2 on same side of v-v1? */
c1 = v1[0] * m[1] - v1[1] * m[0];
@@ -893,19 +897,6 @@ int ED_uvedit_nearest_uv(Scene *scene, Object *obedit, Image *ima, const float c
return found;
}
-UvElement *ED_uv_element_get(UvElementMap *map, BMFace *efa, BMLoop *l)
-{
- UvElement *element;
-
- element = map->vert[BM_elem_index_get(l->v)];
-
- for (; element; element = element->next)
- if (element->face == efa)
- return element;
-
- return NULL;
-}
-
/*********************** loop select ***********************/
static void select_edgeloop_uv_vertex_loop_flag(UvMapVert *first)
@@ -1311,9 +1302,7 @@ static void weld_align_uv(bContext *C, int tool)
Object *obedit;
Image *ima;
BMEditMesh *em;
- BMIter iter, liter;
MTexPoly *tf;
- MLoopUV *luv;
float cent[2], min[2], max[2];
scene = CTX_data_scene(C);
@@ -1325,6 +1314,7 @@ static void weld_align_uv(bContext *C, int tool)
INIT_MINMAX2(min, max);
if (tool == 'a') {
+ BMIter iter, liter;
BMFace *efa;
BMLoop *l;
@@ -1336,7 +1326,7 @@ static void weld_align_uv(bContext *C, int tool)
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
if (uvedit_uv_select_test(em, scene, l)) {
- luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
+ MLoopUV *luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
DO_MINMAX2(luv->uv, min, max);
}
}
@@ -1348,6 +1338,7 @@ static void weld_align_uv(bContext *C, int tool)
uvedit_center(scene, ima, obedit, cent, 0);
if (tool == 'x' || tool == 'w') {
+ BMIter iter, liter;
BMFace *efa;
BMLoop *l;
@@ -1358,7 +1349,7 @@ static void weld_align_uv(bContext *C, int tool)
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
if (uvedit_uv_select_test(em, scene, l)) {
- luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
+ MLoopUV *luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
luv->uv[0] = cent[0];
}
@@ -1367,6 +1358,7 @@ static void weld_align_uv(bContext *C, int tool)
}
if (tool == 'y' || tool == 'w') {
+ BMIter iter, liter;
BMFace *efa;
BMLoop *l;
@@ -1377,7 +1369,7 @@ static void weld_align_uv(bContext *C, int tool)
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
if (uvedit_uv_select_test(em, scene, l)) {
- luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
+ MLoopUV *luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
luv->uv[1] = cent[1];
}
@@ -1744,7 +1736,7 @@ static int mouse_select(bContext *C, const float co[2], int extend, int loop)
* the selection rather than de-selecting the closest. */
uvedit_pixel_to_float(sima, limit, 0.05f);
- uvedit_pixel_to_float(sima, penalty, 5.0f / sima->zoom);
+ uvedit_pixel_to_float(sima, penalty, 5.0f / (sima ? sima->zoom : 1.0f));
/* retrieve operation mode */
if (ts->uv_flag & UV_SYNC_SELECTION) {
@@ -1950,7 +1942,7 @@ static int mouse_select(bContext *C, const float co[2], int extend, int loop)
}
flush = 1;
- }
+ }
}
}
else {
@@ -2132,7 +2124,7 @@ static int select_linked_internal(bContext *C, wmOperator *op, wmEvent *event, i
NearestHit hit, *hit_p = NULL;
if (ts->uv_flag & UV_SYNC_SELECTION) {
- BKE_report(op->reports, RPT_ERROR, "Can't select linked when sync selection is enabled");
+ BKE_report(op->reports, RPT_ERROR, "Cannot select linked when sync selection is enabled");
return OPERATOR_CANCELLED;
}
@@ -2239,7 +2231,7 @@ static int select_split_exec(bContext *C, wmOperator *op)
short change = FALSE;
if (ts->uv_flag & UV_SYNC_SELECTION) {
- BKE_report(op->reports, RPT_ERROR, "Can't split selection when sync selection is enabled");
+ BKE_report(op->reports, RPT_ERROR, "Cannot split selection when sync selection is enabled");
return OPERATOR_CANCELLED;
}
@@ -2280,6 +2272,7 @@ static int select_split_exec(bContext *C, wmOperator *op)
}
if (change) {
+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_IMAGE, NULL);
return OPERATOR_FINISHED;
}
else {
@@ -2317,7 +2310,7 @@ static int unlink_selection_exec(bContext *C, wmOperator *op)
MLoopUV *luv;
if (ts->uv_flag & UV_SYNC_SELECTION) {
- BKE_report(op->reports, RPT_ERROR, "Can't unlink selection when sync selection is enabled");
+ BKE_report(op->reports, RPT_ERROR, "Cannot unlink selection when sync selection is enabled");
return OPERATOR_CANCELLED;
}
@@ -2488,13 +2481,16 @@ static void uv_faces_do_sticky(SpaceImage *sima, Scene *scene, Object *obedit, s
break;
if (efa_index != vlist_iter->f) {
+ BMLoop *l_other;
efa_vlist = EDBM_face_at_index(em, vlist_iter->f);
/* tf_vlist = CustomData_bmesh_get(&em->bm->pdata, efa_vlist->head.data, CD_MTEXPOLY); */ /* UNUSED */
+ l_other = BM_iter_at_index(em->bm, BM_LOOPS_OF_FACE, efa_vlist, vlist_iter->tfindex);
+
if (select)
- uvedit_uv_select_enable(em, scene, BM_iter_at_index(em->bm, BM_LOOPS_OF_FACE, efa_vlist, vlist_iter->tfindex), FALSE);
+ uvedit_uv_select_enable(em, scene, l_other, FALSE);
else
- uvedit_uv_select_disable(em, scene, BM_iter_at_index(em->bm, BM_LOOPS_OF_FACE, efa_vlist, vlist_iter->tfindex));
+ uvedit_uv_select_disable(em, scene, l_other);
}
vlist_iter = vlist_iter->next;
}
@@ -2745,7 +2741,7 @@ static void UV_OT_circle_select(wmOperatorType *ot)
/* ******************** lasso select operator **************** */
-static int do_lasso_select_mesh_uv(bContext *C, int mcords[][2], short moves, short select)
+static int do_lasso_select_mesh_uv(bContext *C, const int mcords[][2], short moves, short select)
{
Image *ima = CTX_data_edit_image(C);
ARegion *ar = CTX_wm_region(C);
@@ -2819,7 +2815,7 @@ static int do_lasso_select_mesh_uv(bContext *C, int mcords[][2], short moves, sh
static int uv_lasso_select_exec(bContext *C, wmOperator *op)
{
int mcords_tot;
- int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
+ const int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
if (mcords) {
short select;
@@ -2828,7 +2824,7 @@ static int uv_lasso_select_exec(bContext *C, wmOperator *op)
select = !RNA_boolean_get(op->ptr, "deselect");
change = do_lasso_select_mesh_uv(C, mcords, mcords_tot, select);
- MEM_freeN(mcords);
+ MEM_freeN((void *)mcords);
return change ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/uvedit/uvedit_parametrizer.c b/source/blender/editors/uvedit/uvedit_parametrizer.c
index f017394356e..5b6125b558b 100644
--- a/source/blender/editors/uvedit/uvedit_parametrizer.c
+++ b/source/blender/editors/uvedit/uvedit_parametrizer.c
@@ -1566,7 +1566,7 @@ static void p_vert_harmonic_insert(PVert *v)
e = v->edge;
do {
- npoints++;
+ npoints++;
e = p_wheel_edge_next(e);
} while (e && (e != v->edge));
@@ -3306,7 +3306,7 @@ static void p_chart_stretch_minimize(PChart *chart, RNG *rng)
trusted_radius /= 2 * nedges;
- random_angle = rng_getFloat(rng) * 2.0f * (float)M_PI;
+ random_angle = BLI_rng_get_float(rng) * 2.0f * (float)M_PI;
dir[0] = trusted_radius * cosf(random_angle);
dir[1] = trusted_radius * sinf(random_angle);
@@ -3988,7 +3988,7 @@ static void p_smooth(PChart *chart)
diff[1] = p[1] - oldp[1];
length = sqrt(diff[0] * diff[0] + diff[1] * diff[1]);
- d = MAX2(d, length);
+ d = max_ff(d, length);
moved += length;
}
}
@@ -4285,7 +4285,7 @@ void param_stretch_begin(ParamHandle *handle)
param_assert(phandle->state == PHANDLE_STATE_CONSTRUCTED);
phandle->state = PHANDLE_STATE_STRETCH;
- phandle->rng = rng_new(31415926);
+ phandle->rng = BLI_rng_new(31415926);
phandle->blend = 0.0f;
for (i = 0; i < phandle->ncharts; i++) {
@@ -4332,7 +4332,7 @@ void param_stretch_end(ParamHandle *handle)
param_assert(phandle->state == PHANDLE_STATE_STRETCH);
phandle->state = PHANDLE_STATE_CONSTRUCTED;
- rng_free(phandle->rng);
+ BLI_rng_free(phandle->rng);
phandle->rng = NULL;
}
@@ -4400,7 +4400,7 @@ void param_pack(ParamHandle *handle, float margin)
if (margin > 0.0f)
area += sqrt(box->w * box->h);
- }
+ }
if (margin > 0.0f) {
/* multiply the margin by the area to give predictable results not dependent on UV scale,
diff --git a/source/blender/editors/uvedit/uvedit_smart_stitch.c b/source/blender/editors/uvedit/uvedit_smart_stitch.c
index 4e0e7944e84..b1945c37048 100644
--- a/source/blender/editors/uvedit/uvedit_smart_stitch.c
+++ b/source/blender/editors/uvedit/uvedit_smart_stitch.c
@@ -46,6 +46,8 @@
#include "BLI_math_vector.h"
#include "BLI_string.h"
+#include "BIF_gl.h"
+
#include "BKE_context.h"
#include "BKE_customdata.h"
#include "BKE_depsgraph.h"
@@ -55,6 +57,7 @@
#include "ED_mesh.h"
#include "ED_uvedit.h"
#include "ED_screen.h"
+#include "ED_space_api.h"
#include "RNA_access.h"
#include "RNA_define.h"
@@ -63,11 +66,32 @@
#include "WM_types.h"
#include "UI_view2d.h"
+#include "UI_resources.h"
#include "uvedit_intern.h"
/* ********************** smart stitch operator *********************** */
+/* object that stores display data for previewing before accepting stitching */
+typedef struct StitchPreviewer {
+ /* here we'll store the preview triangle indices of the mesh */
+ float *preview_polys;
+ /* uvs per polygon. */
+ unsigned int *uvs_per_polygon;
+ /*number of preview polygons */
+ unsigned int num_polys;
+ /* preview data. These will be either the previewed vertices or edges depending on stitch mode settings */
+ float *preview_stitchable;
+ float *preview_unstitchable;
+ /* here we'll store the number of elements to be drawn */
+ unsigned int num_stitchable;
+ unsigned int num_unstitchable;
+ unsigned int preview_uvs;
+ /* ...and here we'll store the triangles*/
+ float *static_tris;
+ unsigned int num_static_tris;
+} StitchPreviewer;
+
struct IslandStitchData;
@@ -143,6 +167,8 @@ typedef struct StitchState {
int static_island;
/* store number of primitives per face so that we can allocate the active island buffer later */
unsigned int *tris_per_island;
+
+ void *draw_handle;
} StitchState;
typedef struct PreviewPosition {
@@ -216,7 +242,7 @@ static void stitch_preview_delete(void)
/* "getter method" */
-StitchPreviewer *uv_get_stitch_previewer(void)
+static StitchPreviewer *uv_get_stitch_previewer(void)
{
return _stitch_preview;
}
@@ -406,8 +432,8 @@ static void stitch_island_calculate_edge_rotation(UvEdge *edge, StitchState *sta
edgesin = uv1[0] * uv2[1] - uv2[0] * uv1[1];
rotation = (edgesin > 0.0f) ?
- +acosf(maxf(-1.0f, minf(1.0f, edgecos))) :
- -acosf(maxf(-1.0f, minf(1.0f, edgecos)));
+ +acosf(max_ff(-1.0f, min_ff(1.0f, edgecos))) :
+ -acosf(max_ff(-1.0f, min_ff(1.0f, edgecos)));
island_stitch_data[element1->island].num_rot_elements++;
island_stitch_data[element1->island].rotation += rotation;
@@ -981,6 +1007,55 @@ static void stitch_calculate_edge_normal(BMEditMesh *em, UvEdge *edge, float *no
normalize_v2(normal);
}
+static void stitch_draw(const bContext *UNUSED(C), ARegion *UNUSED(ar), void *UNUSED(arg))
+{
+ int i, index = 0;
+ float pointsize = UI_GetThemeValuef(TH_VERTEX_SIZE);
+ StitchPreviewer *stitch_preview = uv_get_stitch_previewer();
+
+ glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
+ glEnableClientState(GL_VERTEX_ARRAY);
+
+ glEnable(GL_BLEND);
+
+ UI_ThemeColor4(TH_STITCH_PREVIEW_ACTIVE);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ glVertexPointer(2, GL_FLOAT, 0, stitch_preview->static_tris);
+ glDrawArrays(GL_TRIANGLES, 0, stitch_preview->num_static_tris * 3);
+
+ glVertexPointer(2, GL_FLOAT, 0, stitch_preview->preview_polys);
+ for (i = 0; i < stitch_preview->num_polys; i++) {
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ UI_ThemeColor4(TH_STITCH_PREVIEW_FACE);
+ glDrawArrays(GL_POLYGON, index, stitch_preview->uvs_per_polygon[i]);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ UI_ThemeColor4(TH_STITCH_PREVIEW_EDGE);
+ glDrawArrays(GL_POLYGON, index, stitch_preview->uvs_per_polygon[i]);
+
+ index += stitch_preview->uvs_per_polygon[i];
+ }
+ glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
+#if 0
+ UI_ThemeColor4(TH_STITCH_PREVIEW_VERT);
+ glDrawArrays(GL_TRIANGLES, 0, stitch_preview->num_tris * 3);
+#endif
+ glDisable(GL_BLEND);
+
+ /* draw vert preview */
+ glPointSize(pointsize * 2.0f);
+ UI_ThemeColor4(TH_STITCH_PREVIEW_STITCHABLE);
+ glVertexPointer(2, GL_FLOAT, 0, stitch_preview->preview_stitchable);
+ glDrawArrays(GL_POINTS, 0, stitch_preview->num_stitchable);
+
+ UI_ThemeColor4(TH_STITCH_PREVIEW_UNSTITCHABLE);
+ glVertexPointer(2, GL_FLOAT, 0, stitch_preview->preview_unstitchable);
+ glDrawArrays(GL_POINTS, 0, stitch_preview->num_unstitchable);
+
+ glPopClientAttrib();
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+
+}
+
static int stitch_init(bContext *C, wmOperator *op)
{
/* for fast edge lookup... */
@@ -1016,6 +1091,7 @@ static int stitch_init(bContext *C, wmOperator *op)
state->static_island = RNA_int_get(op->ptr, "static_island");
state->midpoints = RNA_boolean_get(op->ptr, "midpoint_snap");
state->clear_seams = RNA_boolean_get(op->ptr, "clear_seams");
+ state->draw_handle = ED_region_draw_cb_activate(CTX_wm_region(C)->type, stitch_draw, NULL, REGION_DRAW_POST_VIEW);
/* in uv synch selection, all uv's are visible */
if (ts->uv_flag & UV_SYNC_SELECTION) {
state->element_map = EDBM_uv_element_map_create(state->em, 0, 1);
@@ -1282,6 +1358,8 @@ static void stitch_exit(bContext *C, wmOperator *op, int finished)
if (sa)
ED_area_headerprint(sa, NULL);
+ ED_region_draw_cb_exit(CTX_wm_region(C)->type, stitch_state->draw_handle);
+
DAG_id_tag_update(obedit->data, 0);
WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
diff --git a/source/blender/editors/uvedit/uvedit_unwrap_ops.c b/source/blender/editors/uvedit/uvedit_unwrap_ops.c
index c95b2e85248..f615902eedf 100644
--- a/source/blender/editors/uvedit/uvedit_unwrap_ops.c
+++ b/source/blender/editors/uvedit/uvedit_unwrap_ops.c
@@ -60,6 +60,7 @@
#include "BKE_main.h"
#include "BKE_mesh.h"
#include "BKE_report.h"
+#include "BKE_scene.h"
#include "BKE_tessmesh.h"
#include "BLI_math.h"
@@ -177,7 +178,33 @@ static int uvedit_have_selection(Scene *scene, BMEditMesh *em, short implicit)
return 0;
}
-static ParamHandle *construct_param_handle(Scene *scene, BMEditMesh *em,
+static void ED_uvedit_get_aspect(Scene *scene, Object *ob, BMEditMesh *em, float *aspx, float *aspy)
+{
+ int sloppy = TRUE;
+ int selected = FALSE;
+ BMFace *efa;
+ Image *ima;
+
+ efa = BM_active_face_get(em->bm, sloppy, selected);
+
+ if (efa) {
+ if (BKE_scene_use_new_shading_nodes(scene)) {
+ ED_object_get_active_image(ob, efa->mat_nr + 1, &ima, NULL, NULL);
+ }
+ else {
+ MTexPoly *tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
+ ima = tf->tpage;
+ }
+
+ ED_image_get_uv_aspect(ima, NULL, aspx, aspy);
+ }
+ else {
+ *aspx = 1.0f;
+ *aspy = 1.0f;
+ }
+}
+
+static ParamHandle *construct_param_handle(Scene *scene, Object *ob, BMEditMesh *em,
short implicit, short fill, short sel,
short correct_aspect)
{
@@ -187,27 +214,16 @@ static ParamHandle *construct_param_handle(Scene *scene, BMEditMesh *em,
BMLoop *l;
BMEdge *eed;
BMIter iter, liter;
- MTexPoly *tf;
handle = param_construct_begin();
if (correct_aspect) {
- int sloppy = TRUE;
- int selected = FALSE;
-
- efa = BM_active_face_get(em->bm, sloppy, selected);
+ float aspx, aspy;
- if (efa) {
- float aspx, aspy;
- tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
+ ED_uvedit_get_aspect(scene, ob, em, &aspx, &aspy);
- ED_image_get_uv_aspect(tf->tpage, NULL, &aspx, &aspy);
-
- if (aspx != aspy)
- param_aspect_ratio(handle, aspx, aspy);
- else
- param_aspect_ratio(handle, 1.0, 1.0);
- }
+ if (aspx != aspy)
+ param_aspect_ratio(handle, aspx, aspy);
}
/* we need the vert indices */
@@ -223,7 +239,7 @@ static ParamHandle *construct_param_handle(Scene *scene, BMEditMesh *em,
BMLoop *ls[3];
float *co[4];
float *uv[4];
- int i, lsel;
+ int lsel;
if ((BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) || (sel && BM_elem_flag_test(efa, BM_ELEM_SELECT) == 0))
continue;
@@ -242,9 +258,10 @@ static ParamHandle *construct_param_handle(Scene *scene, BMEditMesh *em,
key = (ParamKey)efa;
- tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
+ // tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY); // UNUSED
if (efa->len == 3 || efa->len == 4) {
+ int i;
/* for quads let parametrize split, it can make better decisions
* about which split is best for unwrapping than scanfill */
i = 0;
@@ -291,6 +308,7 @@ static ParamHandle *construct_param_handle(Scene *scene, BMEditMesh *em,
BLI_scanfill_calc_ex(&sf_ctx, TRUE, efa->no);
for (sf_tri = sf_ctx.fillfacebase.first; sf_tri; sf_tri = sf_tri->next) {
+ int i;
ls[0] = sf_tri->v1->tmp.p;
ls[1] = sf_tri->v2->tmp.p;
ls[2] = sf_tri->v3->tmp.p;
@@ -353,13 +371,12 @@ static void texface_from_original_index(BMFace *efa, int index, float **uv, Para
/* unwrap handle initialization for subsurf aware-unwrapper. The many modifications required to make the original function(see above)
* work justified the existence of a new function. */
-static ParamHandle *construct_param_handle_subsurfed(Scene *scene, BMEditMesh *em, short fill, short sel, short correct_aspect)
+static ParamHandle *construct_param_handle_subsurfed(Scene *scene, Object *ob, BMEditMesh *em, short fill, short sel, short correct_aspect)
{
ParamHandle *handle;
/* index pointers */
MFace *face;
MEdge *edge;
- BMFace *editFace;
int i;
/* modifier initialization data, will control what type of subdivision will happen*/
@@ -367,7 +384,7 @@ static ParamHandle *construct_param_handle_subsurfed(Scene *scene, BMEditMesh *e
/* Used to hold subsurfed Mesh */
DerivedMesh *derivedMesh, *initialDerived;
/* holds original indices for subsurfed mesh */
- int *origVertIndices, *origFaceIndices, *origEdgeIndices;
+ int *origVertIndices, *origEdgeIndices, *origFaceIndices, *origPolyIndices;
/* Holds vertices of subsurfed mesh */
MVert *subsurfedVerts;
MEdge *subsurfedEdges;
@@ -383,30 +400,19 @@ static ParamHandle *construct_param_handle_subsurfed(Scene *scene, BMEditMesh *e
handle = param_construct_begin();
if (correct_aspect) {
- int sloppy = TRUE;
- int selected = FALSE;
-
- editFace = BM_active_face_get(em->bm, sloppy, selected);
-
- if (editFace) {
- MTexPoly *tf;
- float aspx, aspy;
- tf = CustomData_bmesh_get(&em->bm->pdata, editFace->head.data, CD_MTEXPOLY);
+ float aspx, aspy;
- ED_image_get_uv_aspect(tf->tpage, NULL, &aspx, &aspy);
+ ED_uvedit_get_aspect(scene, ob, em, &aspx, &aspy);
- if (aspx != aspy)
- param_aspect_ratio(handle, aspx, aspy);
- else
- param_aspect_ratio(handle, 1.0, 1.0);
- }
+ if (aspx != aspy)
+ param_aspect_ratio(handle, aspx, aspy);
}
/* number of subdivisions to perform */
smd.levels = scene->toolsettings->uv_subsurf_level;
smd.subdivType = ME_CC_SUBSURF;
- initialDerived = CDDM_from_BMEditMesh(em, NULL, 0, 0);
+ initialDerived = CDDM_from_editbmesh(em, FALSE, FALSE);
derivedMesh = subsurf_make_derived_from_derived(initialDerived, &smd,
NULL, SUBSURF_IN_EDIT_MODE);
@@ -420,6 +426,7 @@ static ParamHandle *construct_param_handle_subsurfed(Scene *scene, BMEditMesh *e
origVertIndices = derivedMesh->getVertDataArray(derivedMesh, CD_ORIGINDEX);
origEdgeIndices = derivedMesh->getEdgeDataArray(derivedMesh, CD_ORIGINDEX);
origFaceIndices = derivedMesh->getTessFaceDataArray(derivedMesh, CD_ORIGINDEX);
+ origPolyIndices = derivedMesh->getPolyDataArray(derivedMesh, CD_ORIGINDEX);
numOfEdges = derivedMesh->getNumEdges(derivedMesh);
numOfFaces = derivedMesh->getNumTessFaces(derivedMesh);
@@ -431,7 +438,7 @@ static ParamHandle *construct_param_handle_subsurfed(Scene *scene, BMEditMesh *e
/* map subsurfed faces to original editFaces */
for (i = 0; i < numOfFaces; i++)
- faceMap[i] = EDBM_face_at_index(em, origFaceIndices[i]);
+ faceMap[i] = EDBM_face_at_index(em, DM_origindex_mface_mpoly(origFaceIndices, origPolyIndices, i));
edgeMap = MEM_mallocN(numOfEdges * sizeof(BMEdge *), "unwrap_edit_edge_map");
@@ -538,7 +545,7 @@ static int minimize_stretch_init(bContext *C, wmOperator *op)
ms->blend = RNA_float_get(op->ptr, "blend");
ms->iterations = RNA_int_get(op->ptr, "iterations");
ms->i = 0;
- ms->handle = construct_param_handle(scene, em, implicit, fill_holes, 1, 1);
+ ms->handle = construct_param_handle(scene, obedit, em, implicit, fill_holes, 1, 1);
ms->lasttime = PIL_check_seconds_timer();
param_stretch_begin(ms->handle);
@@ -727,14 +734,12 @@ static int pack_islands_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
- if (RNA_struct_property_is_set(op->ptr, "margin")) {
+ if (RNA_struct_property_is_set(op->ptr, "margin"))
scene->toolsettings->uvcalc_margin = RNA_float_get(op->ptr, "margin");
- }
- else {
+ else
RNA_float_set(op->ptr, "margin", scene->toolsettings->uvcalc_margin);
- }
- handle = construct_param_handle(scene, em, implicit, 0, 1, 1);
+ handle = construct_param_handle(scene, obedit, em, implicit, 0, 1, 1);
param_pack(handle, scene->toolsettings->uvcalc_margin);
param_flush(handle);
param_delete(handle);
@@ -759,7 +764,7 @@ void UV_OT_pack_islands(wmOperatorType *ot)
ot->poll = ED_operator_uvedit;
/* properties */
- RNA_def_float_factor(ot->srna, "margin", 0.0f, 0.0f, 1.0f, "Margin", "Space between islands", 0.0f, 1.0f);
+ RNA_def_float_factor(ot->srna, "margin", 0.001f, 0.0f, 1.0f, "Margin", "Space between islands", 0.0f, 1.0f);
}
/* ******************** Average Islands Scale operator **************** */
@@ -776,7 +781,7 @@ static int average_islands_scale_exec(bContext *C, wmOperator *UNUSED(op))
return OPERATOR_CANCELLED;
}
- handle = construct_param_handle(scene, em, implicit, 0, 1, 1);
+ handle = construct_param_handle(scene, obedit, em, implicit, 0, 1, 1);
param_average(handle);
param_flush(handle);
param_delete(handle);
@@ -817,9 +822,9 @@ void ED_uvedit_live_unwrap_begin(Scene *scene, Object *obedit)
}
if (use_subsurf)
- liveHandle = construct_param_handle_subsurfed(scene, em, fillholes, 0, 1);
+ liveHandle = construct_param_handle_subsurfed(scene, obedit, em, fillholes, 0, 1);
else
- liveHandle = construct_param_handle(scene, em, 0, fillholes, 0, 1);
+ liveHandle = construct_param_handle(scene, obedit, em, 0, fillholes, 0, 1);
param_lscm_begin(liveHandle, PARAM_TRUE, abf);
}
@@ -1007,22 +1012,15 @@ static void uv_transform_properties(wmOperatorType *ot, int radius)
"Radius of the sphere or cylinder", 0.0001f, 100.0f);
}
-static void correct_uv_aspect(BMEditMesh *em)
+static void correct_uv_aspect(Scene *scene, Object *ob, BMEditMesh *em)
{
- int sloppy = TRUE;
- int selected = FALSE;
- BMFace *efa = BM_active_face_get(em->bm, sloppy, selected);
BMLoop *l;
BMIter iter, liter;
MLoopUV *luv;
- float scale, aspx = 1.0f, aspy = 1.0f;
+ BMFace *efa;
+ float scale, aspx, aspy;
- if (efa) {
- MTexPoly *tf;
-
- tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
- ED_image_get_uv_aspect(tf->tpage, NULL, &aspx, &aspy);
- }
+ ED_uvedit_get_aspect(scene, ob, em, &aspx, &aspy);
if (aspx == aspy)
return;
@@ -1067,7 +1065,7 @@ static void uv_map_clip_correct_properties(wmOperatorType *ot)
"Scale UV coordinates to bounds after unwrapping");
}
-static void uv_map_clip_correct(BMEditMesh *em, wmOperator *op)
+static void uv_map_clip_correct(Scene *scene, Object *ob, BMEditMesh *em, wmOperator *op)
{
BMFace *efa;
BMLoop *l;
@@ -1080,7 +1078,7 @@ static void uv_map_clip_correct(BMEditMesh *em, wmOperator *op)
/* correct for image aspect ratio */
if (correct_aspect)
- correct_uv_aspect(em);
+ correct_uv_aspect(scene, ob, em);
if (scale_to_bounds) {
INIT_MINMAX2(min, max);
@@ -1144,9 +1142,9 @@ void ED_unwrap_lscm(Scene *scene, Object *obedit, const short sel)
const short use_subsurf = scene->toolsettings->uvcalc_flag & UVCALC_USESUBSURF;
if (use_subsurf)
- handle = construct_param_handle_subsurfed(scene, em, fill_holes, sel, correct_aspect);
+ handle = construct_param_handle_subsurfed(scene, obedit, em, fill_holes, sel, correct_aspect);
else
- handle = construct_param_handle(scene, em, 0, fill_holes, sel, correct_aspect);
+ handle = construct_param_handle(scene, obedit, em, 0, fill_holes, sel, correct_aspect);
param_lscm_begin(handle, PARAM_FALSE, scene->toolsettings->unwrapper == 0);
param_lscm_solve(handle);
@@ -1170,7 +1168,7 @@ static int unwrap_exec(bContext *C, wmOperator *op)
int correct_aspect = RNA_boolean_get(op->ptr, "correct_aspect");
int use_subsurf = RNA_boolean_get(op->ptr, "use_subsurf_data");
int subsurf_level = RNA_int_get(op->ptr, "uv_subsurf_level");
- float obsize[3], unitsize[3] = {1.0f, 1.0f, 1.0f};
+ float obsize[3];
short implicit = 0;
if (!uvedit_have_selection(scene, em, implicit)) {
@@ -1183,8 +1181,9 @@ static int unwrap_exec(bContext *C, wmOperator *op)
}
mat4_to_size(obsize, obedit->obmat);
- if (!compare_v3v3(obsize, unitsize, 1e-4f))
- BKE_report(op->reports, RPT_INFO, "Object scale is not 1.0. Unwrap will operate on a non-scaled version of the mesh.");
+ if (!(fabsf(obsize[0] - obsize[1]) < 1e-4f && fabsf(obsize[1] - obsize[2]) < 1e-4f))
+ BKE_report(op->reports, RPT_INFO,
+ "Object has non-uniform scale, unwrap will operate on a non-scaled version of the mesh");
/* remember last method for live unwrap */
if (RNA_struct_property_is_set(op->ptr, "method"))
@@ -1192,6 +1191,12 @@ static int unwrap_exec(bContext *C, wmOperator *op)
else
RNA_enum_set(op->ptr, "method", scene->toolsettings->unwrapper);
+ /* remember packing marging */
+ if (RNA_struct_property_is_set(op->ptr, "margin"))
+ scene->toolsettings->uvcalc_margin = RNA_float_get(op->ptr, "margin");
+ else
+ RNA_float_set(op->ptr, "margin", scene->toolsettings->uvcalc_margin);
+
scene->toolsettings->uv_subsurf_level = subsurf_level;
if (fill_holes) scene->toolsettings->uvcalc_flag |= UVCALC_FILLHOLES;
@@ -1239,8 +1244,9 @@ void UV_OT_unwrap(wmOperatorType *ot)
"Map UVs taking image aspect ratio into account");
RNA_def_boolean(ot->srna, "use_subsurf_data", 0, "Use Subsurf Data",
"Map UVs taking vertex position after subsurf into account");
- RNA_def_int(ot->srna, "uv_subsurf_level", 1, 1, 6, "SubSurf Target",
+ RNA_def_int(ot->srna, "uv_subsurf_level", 1, 1, 6, "Subsurf Target",
"Number of times to subdivide before calculating UVs", 1, 6);
+ RNA_def_float_factor(ot->srna, "margin", 0.001f, 0.0f, 1.0f, "Margin", "Space between islands", 0.0f, 1.0f);
}
/**************** Project From View operator **************/
@@ -1313,7 +1319,7 @@ static int uv_from_view_exec(bContext *C, wmOperator *op)
}
}
- uv_map_clip_correct(em, op);
+ uv_map_clip_correct(scene, obedit, em, op);
DAG_id_tag_update(obedit->data, 0);
WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
@@ -1428,8 +1434,8 @@ static void uv_map_mirror(BMEditMesh *em, BMFace *efa, MTexPoly *UNUSED(tf))
if (i != mi) {
dx = uvs[mi][0] - uvs[i][0];
if (dx > 0.5f) uvs[i][0] += 1.0f;
- }
- }
+ }
+ }
BLI_array_fixedstack_free(uvs);
}
@@ -1467,7 +1473,7 @@ static int sphere_project_exec(bContext *C, wmOperator *op)
uv_map_mirror(em, efa, tf);
}
- uv_map_clip_correct(em, op);
+ uv_map_clip_correct(scene, obedit, em, op);
DAG_id_tag_update(obedit->data, 0);
WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
@@ -1542,7 +1548,7 @@ static int cylinder_project_exec(bContext *C, wmOperator *op)
uv_map_mirror(em, efa, tf);
}
- uv_map_clip_correct(em, op);
+ uv_map_clip_correct(scene, obedit, em, op);
DAG_id_tag_update(obedit->data, 0);
WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
@@ -1622,7 +1628,7 @@ static int cube_project_exec(bContext *C, wmOperator *op)
}
}
- uv_map_clip_correct(em, op);
+ uv_map_clip_correct(scene, obedit, em, op);
DAG_id_tag_update(obedit->data, 0);
WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
diff --git a/source/blender/gpu/GPU_buffers.h b/source/blender/gpu/GPU_buffers.h
index 1729ac06f5a..36fbd818f11 100644
--- a/source/blender/gpu/GPU_buffers.h
+++ b/source/blender/gpu/GPU_buffers.h
@@ -123,37 +123,36 @@ void GPU_global_buffer_pool_free(void);
GPUBuffer *GPU_buffer_alloc(int size);
void GPU_buffer_free(GPUBuffer *buffer);
-GPUDrawObject *GPU_drawobject_new(struct DerivedMesh *dm );
-void GPU_drawobject_free(struct DerivedMesh *dm );
+GPUDrawObject *GPU_drawobject_new(struct DerivedMesh *dm);
+void GPU_drawobject_free(struct DerivedMesh *dm);
/* called before drawing */
-void GPU_vertex_setup(struct DerivedMesh *dm );
-void GPU_normal_setup(struct DerivedMesh *dm );
-void GPU_uv_setup(struct DerivedMesh *dm );
-void GPU_color_setup(struct DerivedMesh *dm );
-void GPU_edge_setup(struct DerivedMesh *dm ); /* does not mix with other data */
-void GPU_uvedge_setup(struct DerivedMesh *dm );
-int GPU_attrib_element_size( GPUAttrib data[], int numdata );
-void GPU_interleaved_attrib_setup( GPUBuffer *buffer, GPUAttrib data[], int numdata );
+void GPU_vertex_setup(struct DerivedMesh *dm);
+void GPU_normal_setup(struct DerivedMesh *dm);
+void GPU_uv_setup(struct DerivedMesh *dm);
+/* colType is the cddata MCol type to use! */
+void GPU_color_setup(struct DerivedMesh *dm, int colType);
+void GPU_edge_setup(struct DerivedMesh *dm); /* does not mix with other data */
+void GPU_uvedge_setup(struct DerivedMesh *dm);
+int GPU_attrib_element_size(GPUAttrib data[], int numdata);
+void GPU_interleaved_attrib_setup(GPUBuffer *buffer, GPUAttrib data[], int numdata);
/* can't lock more than one buffer at once */
-void *GPU_buffer_lock( GPUBuffer *buffer );
-void *GPU_buffer_lock_stream( GPUBuffer *buffer );
-void GPU_buffer_unlock( GPUBuffer *buffer );
+void *GPU_buffer_lock(GPUBuffer *buffer);
+void *GPU_buffer_lock_stream(GPUBuffer *buffer);
+void GPU_buffer_unlock(GPUBuffer *buffer);
-/* upload three unsigned chars, representing RGB colors, for each vertex. Resets dm->drawObject->colType to -1 */
-void GPU_color3_upload(struct DerivedMesh *dm, unsigned char *data );
/* switch color rendering on=1/off=0 */
-void GPU_color_switch( int mode );
+void GPU_color_switch(int mode);
/* used for drawing edges */
-void GPU_buffer_draw_elements( GPUBuffer *elements, unsigned int mode, int start, int count );
+void GPU_buffer_draw_elements(GPUBuffer *elements, unsigned int mode, int start, int count);
/* called after drawing */
void GPU_buffer_unbind(void);
/* used to check whether to use the old (without buffers) code */
-int GPU_buffer_legacy(struct DerivedMesh *dm );
+int GPU_buffer_legacy(struct DerivedMesh *dm);
/* Buffers for non-DerivedMesh drawing */
typedef struct GPU_Buffers GPU_Buffers;
@@ -162,18 +161,22 @@ GPU_Buffers *GPU_build_mesh_buffers(int (*face_vert_indices)[4],
struct MFace *mface, struct MVert *mvert,
int *face_indices, int totface);
-void GPU_update_mesh_buffers(GPU_Buffers *buffers, struct MVert *mvert,
- int *vert_indices, int totvert, const float *vmask);
+void GPU_update_mesh_buffers(GPU_Buffers *buffers, MVert *mvert,
+ int *vert_indices, int totvert, const float *vmask,
+ int (*face_vert_indices)[4], int show_diffuse_color);
GPU_Buffers *GPU_build_grid_buffers(int *grid_indices, int totgrid,
unsigned int **grid_hidden, int gridsize);
void GPU_update_grid_buffers(GPU_Buffers *buffers, struct CCGElem **grids,
const struct DMFlagMat *grid_flag_mats,
- int *grid_indices, int totgrid, const struct CCGKey *key);
+ int *grid_indices, int totgrid, const struct CCGKey *key,
+ int show_diffuse_color);
void GPU_draw_buffers(GPU_Buffers *buffers, DMSetMaterial setMaterial);
+int GPU_buffers_diffuse_changed(GPU_Buffers *buffers, int show_diffuse_color);
+
void GPU_free_buffers(GPU_Buffers *buffers);
#endif
diff --git a/source/blender/gpu/GPU_draw.h b/source/blender/gpu/GPU_draw.h
index 467adbe10b8..b26c25558c3 100644
--- a/source/blender/gpu/GPU_draw.h
+++ b/source/blender/gpu/GPU_draw.h
@@ -75,6 +75,8 @@ void GPU_end_object_materials(void);
int GPU_enable_material(int nr, void *attribs);
void GPU_disable_material(void);
+void GPU_material_diffuse_get(int nr, float diff[4]);
+
void GPU_set_material_alpha_blend(int alphablend);
int GPU_get_material_alpha_blend(void);
@@ -119,10 +121,10 @@ void GPU_set_gpu_mipmapping(int gpu_mipmap);
/* Image updates and free
* - these deal with images bound as opengl textures */
-void GPU_paint_update_image(struct Image *ima, int x, int y, int w, int h, int mipmap);
+void GPU_paint_update_image(struct Image *ima, int x, int y, int w, int h);
void GPU_update_images_framechange(void);
int GPU_update_image_time(struct Image *ima, double time);
-int GPU_verify_image(struct Image *ima, struct ImageUser *iuser, int tftile, int compare, int mipmap, int ncd);
+int GPU_verify_image(struct Image *ima, struct ImageUser *iuser, int tftile, int compare, int mipmap, int isdata);
void GPU_create_gl_tex(unsigned int *bind, unsigned int *pix, float *frect, int rectw, int recth, int mipmap, int use_hight_bit_depth, struct Image *ima);
void GPU_create_gl_tex_compressed(unsigned int *bind, unsigned int *pix, int x, int y, int mipmap, struct Image *ima, struct ImBuf *ibuf);
int GPU_upload_dxt_texture(struct ImBuf *ibuf);
diff --git a/source/blender/gpu/GPU_extensions.h b/source/blender/gpu/GPU_extensions.h
index 198d002ff0d..7eaa4084e61 100644
--- a/source/blender/gpu/GPU_extensions.h
+++ b/source/blender/gpu/GPU_extensions.h
@@ -107,11 +107,11 @@ int GPU_type_matches(GPUDeviceType device, GPUOSType os, GPUDriverType driver);
GPUTexture *GPU_texture_create_1D(int w, float *pixels, char err_out[256]);
GPUTexture *GPU_texture_create_2D(int w, int h, float *pixels, char err_out[256]);
-GPUTexture *GPU_texture_create_3D(int w, int h, int depth, float *fpixels);
+GPUTexture *GPU_texture_create_3D(int w, int h, int depth, int channels, float *fpixels);
GPUTexture *GPU_texture_create_depth(int w, int h, char err_out[256]);
GPUTexture *GPU_texture_create_vsm_shadow_map(int size, char err_out[256]);
GPUTexture *GPU_texture_from_blender(struct Image *ima,
- struct ImageUser *iuser, int ncd, double time, int mipmap);
+ struct ImageUser *iuser, int isdata, double time, int mipmap);
void GPU_texture_free(GPUTexture *tex);
void GPU_texture_ref(GPUTexture *tex);
diff --git a/source/blender/gpu/GPU_material.h b/source/blender/gpu/GPU_material.h
index baa557c3484..97e8b756d08 100644
--- a/source/blender/gpu/GPU_material.h
+++ b/source/blender/gpu/GPU_material.h
@@ -107,7 +107,7 @@ typedef struct GPUNodeStack {
GPUNodeLink *GPU_attribute(int type, const char *name);
GPUNodeLink *GPU_uniform(float *num);
GPUNodeLink *GPU_dynamic_uniform(float *num, int dynamictype, void *data);
-GPUNodeLink *GPU_image(struct Image *ima, struct ImageUser *iuser, int ncd);
+GPUNodeLink *GPU_image(struct Image *ima, struct ImageUser *iuser, int isdata);
GPUNodeLink *GPU_texture(int size, float *pixels);
GPUNodeLink *GPU_dynamic_texture(struct GPUTexture *tex, int dynamictype, void *data);
GPUNodeLink *GPU_socket(GPUNodeStack *sock);
diff --git a/source/blender/gpu/intern/gpu_buffers.c b/source/blender/gpu/intern/gpu_buffers.c
index c44a181841e..6e475ace09d 100644
--- a/source/blender/gpu/intern/gpu_buffers.c
+++ b/source/blender/gpu/intern/gpu_buffers.c
@@ -54,6 +54,7 @@
#include "DNA_userdef_types.h"
#include "GPU_buffers.h"
+#include "GPU_draw.h"
typedef enum {
GPU_BUFFER_VERTEX_STATE = 1,
@@ -707,34 +708,6 @@ static void GPU_buffer_copy_uv(DerivedMesh *dm, float *varray, int *index, int *
}
}
-
-static void GPU_buffer_copy_color3(DerivedMesh *dm, float *varray_, int *index, int *mat_orig_to_new, void *user)
-{
- int i, totface;
- char *varray = (char *)varray_;
- char *mcol = (char *)user;
- MFace *f = dm->getTessFaceArray(dm);
-
- totface = dm->getNumTessFaces(dm);
- for (i = 0; i < totface; i++, f++) {
- int start = index[mat_orig_to_new[f->mat_nr]];
-
- /* v1 v2 v3 */
- copy_v3_v3_char(&varray[start], &mcol[i * 12]);
- copy_v3_v3_char(&varray[start + 3], &mcol[i * 12 + 3]);
- copy_v3_v3_char(&varray[start + 6], &mcol[i * 12 + 6]);
- index[mat_orig_to_new[f->mat_nr]] += 9;
-
- if (f->v4) {
- /* v3 v4 v1 */
- copy_v3_v3_char(&varray[start + 9], &mcol[i * 12 + 6]);
- copy_v3_v3_char(&varray[start + 12], &mcol[i * 12 + 9]);
- copy_v3_v3_char(&varray[start + 15], &mcol[i * 12]);
- index[mat_orig_to_new[f->mat_nr]] += 9;
- }
- }
-}
-
static void copy_mcol_uc3(unsigned char *v, unsigned char *col)
{
v[0] = col[3];
@@ -819,28 +792,6 @@ static void GPU_buffer_copy_uvedge(DerivedMesh *dm, float *varray, int *UNUSED(i
}
}
-/* get the DerivedMesh's MCols; choose (in decreasing order of
- * preference) from CD_ID_MCOL, CD_PREVIEW_MCOL, or CD_MCOL */
-static MCol *gpu_buffer_color_type(DerivedMesh *dm)
-{
- MCol *c;
- int type;
-
- type = CD_ID_MCOL;
- c = DM_get_tessface_data_layer(dm, type);
- if (!c) {
- type = CD_PREVIEW_MCOL;
- c = DM_get_tessface_data_layer(dm, type);
- if (!c) {
- type = CD_MCOL;
- c = DM_get_tessface_data_layer(dm, type);
- }
- }
-
- dm->drawObject->colType = type;
- return c;
-}
-
typedef enum {
GPU_BUFFER_VERTEX = 0,
GPU_BUFFER_NORMAL,
@@ -923,7 +874,7 @@ static GPUBuffer *gpu_buffer_setup_type(DerivedMesh *dm, GPUBufferType type)
/* special handling for MCol and UV buffers */
if (type == GPU_BUFFER_COLOR) {
- if (!(user_data = gpu_buffer_color_type(dm)))
+ if (!(user_data = DM_get_tessface_data_layer(dm, dm->drawObject->colType)))
return NULL;
}
else if (type == GPU_BUFFER_UV) {
@@ -943,7 +894,7 @@ static GPUBuffer *gpu_buffer_setup_type(DerivedMesh *dm, GPUBufferType type)
static GPUBuffer *gpu_buffer_setup_common(DerivedMesh *dm, GPUBufferType type)
{
GPUBuffer **buf;
-
+
if (!dm->drawObject)
dm->drawObject = GPU_drawobject_new(dm);
@@ -1005,8 +956,28 @@ void GPU_uv_setup(DerivedMesh *dm)
GLStates |= GPU_BUFFER_TEXCOORD_STATE;
}
-void GPU_color_setup(DerivedMesh *dm)
+void GPU_color_setup(DerivedMesh *dm, int colType)
{
+ if (!dm->drawObject) {
+ /* XXX Not really nice, but we need a valid gpu draw object to set the colType...
+ * Else we would have to add a new param to gpu_buffer_setup_common. */
+ dm->drawObject = GPU_drawobject_new(dm);
+ dm->dirty &= ~DM_DIRTY_MCOL_UPDATE_DRAW;
+ dm->drawObject->colType = colType;
+ }
+ /* In paint mode, dm may stay the same during stroke, however we still want to update colors!
+ * Also check in case we changed color type (i.e. which MCol cdlayer we use). */
+ else if ((dm->dirty & DM_DIRTY_MCOL_UPDATE_DRAW) || (colType != dm->drawObject->colType)) {
+ GPUBuffer **buf = gpu_drawobject_buffer_from_type(dm->drawObject, GPU_BUFFER_COLOR);
+ /* XXX Freeing this buffer is a bit stupid, as geometry has not changed, size should remain the same.
+ * Not sure though it would be worth defining a sort of gpu_buffer_update func - nor whether
+ * it is even possible ! */
+ GPU_buffer_free(*buf);
+ *buf = NULL;
+ dm->dirty &= ~DM_DIRTY_MCOL_UPDATE_DRAW;
+ dm->drawObject->colType = colType;
+ }
+
if (!gpu_buffer_setup_common(dm, GPU_BUFFER_COLOR))
return;
@@ -1167,20 +1138,6 @@ void GPU_buffer_unbind(void)
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
}
-/* confusion: code in cdderivedmesh calls both GPU_color_setup and
- * GPU_color3_upload; both of these set the `colors' buffer, so seems
- * like it will just needlessly overwrite? --nicholas */
-void GPU_color3_upload(DerivedMesh *dm, unsigned char *data)
-{
- if (dm->drawObject == 0)
- dm->drawObject = GPU_drawobject_new(dm);
- GPU_buffer_free(dm->drawObject->colors);
-
- dm->drawObject->colors = gpu_buffer_setup(dm, dm->drawObject, 3,
- sizeof(char) * 3 * dm->drawObject->tot_triangle_point,
- GL_ARRAY_BUFFER_ARB, data, GPU_buffer_copy_color3);
-}
-
void GPU_color_switch(int mode)
{
if (mode) {
@@ -1269,6 +1226,14 @@ void GPU_buffer_draw_elements(GPUBuffer *elements, unsigned int mode, int start,
/* XXX: the rest of the code in this file is used for optimized PBVH
* drawing and doesn't interact at all with the buffer code above */
+/* Return false if VBO is either unavailable or disabled by the user,
+ * true otherwise */
+static int gpu_vbo_enabled(void)
+{
+ return (GLEW_ARB_vertex_buffer_object &&
+ !(U.gameflags & USER_DISABLE_VBO));
+}
+
/* Convenience struct for building the VBO. */
typedef struct {
float co[3];
@@ -1304,6 +1269,13 @@ struct GPU_Buffers {
int has_hidden;
unsigned int tot_tri, tot_quad;
+
+ /* The PBVH ensures that either all faces in the node are
+ smooth-shaded or all faces are flat-shaded */
+ int smooth;
+
+ int show_diffuse_color;
+ float diffuse_color[4];
};
typedef enum {
VBO_ENABLED,
@@ -1327,24 +1299,24 @@ static void gpu_colors_disable(VBO_State vbo_state)
static float gpu_color_from_mask(float mask)
{
- return (1.0f - mask) * 0.5f + 0.25f;
+ return 1.0f - mask * 0.75f;
}
-static void gpu_color_from_mask_copy(float mask, unsigned char out[3])
+static void gpu_color_from_mask_copy(float mask, const float diffuse_color[4], unsigned char out[3])
{
- unsigned char color;
-
- color = gpu_color_from_mask(mask) * 255.0f;
+ float mask_color;
- out[0] = color;
- out[1] = color;
- out[2] = color;
+ mask_color = gpu_color_from_mask(mask) * 255.0f;
+
+ out[0] = diffuse_color[0] * mask_color;
+ out[1] = diffuse_color[1] * mask_color;
+ out[2] = diffuse_color[2] * mask_color;
}
-static void gpu_color_from_mask_set(float mask)
+static void gpu_color_from_mask_set(float mask, float diffuse_color[4])
{
float color = gpu_color_from_mask(mask);
- glColor3f(color, color, color);
+ glColor3f(diffuse_color[0] * color, diffuse_color[1] * color, diffuse_color[2] * color);
}
static float gpu_color_from_mask_quad(const CCGKey *key,
@@ -1360,52 +1332,149 @@ static float gpu_color_from_mask_quad(const CCGKey *key,
static void gpu_color_from_mask_quad_copy(const CCGKey *key,
CCGElem *a, CCGElem *b,
CCGElem *c, CCGElem *d,
+ const float *diffuse_color,
unsigned char out[3])
{
- unsigned char color =
+ float mask_color =
gpu_color_from_mask((*CCG_elem_mask(key, a) +
*CCG_elem_mask(key, b) +
*CCG_elem_mask(key, c) +
*CCG_elem_mask(key, d)) * 0.25f) * 255.0f;
- out[0] = color;
- out[1] = color;
- out[2] = color;
+ out[0] = diffuse_color[0] * mask_color;
+ out[1] = diffuse_color[1] * mask_color;
+ out[2] = diffuse_color[2] * mask_color;
}
static void gpu_color_from_mask_quad_set(const CCGKey *key,
CCGElem *a, CCGElem *b,
- CCGElem *c, CCGElem *d)
+ CCGElem *c, CCGElem *d,
+ float diffuse_color[4])
{
float color = gpu_color_from_mask_quad(key, a, b, c, d);
- glColor3f(color, color, color);
+ glColor3f(diffuse_color[0] * color, diffuse_color[1] * color, diffuse_color[2] * color);
}
void GPU_update_mesh_buffers(GPU_Buffers *buffers, MVert *mvert,
- int *vert_indices, int totvert, const float *vmask)
+ int *vert_indices, int totvert, const float *vmask,
+ int (*face_vert_indices)[4], int show_diffuse_color)
{
VertexBufferFormat *vert_data;
- int i;
+ int i, j, k;
buffers->vmask = vmask;
+ buffers->show_diffuse_color = show_diffuse_color;
if (buffers->vert_buf) {
+ int totelem = (buffers->smooth ? totvert : (buffers->tot_tri * 3));
+ float diffuse_color[4] = {0.8f, 0.8f, 0.8f, 1.0f};
+
+ if (buffers->show_diffuse_color) {
+ MFace *f = buffers->mface + buffers->face_indices[0];
+
+ GPU_material_diffuse_get(f->mat_nr + 1, diffuse_color);
+ }
+
+ copy_v4_v4(buffers->diffuse_color, diffuse_color);
+
/* Build VBO */
glBindBufferARB(GL_ARRAY_BUFFER_ARB, buffers->vert_buf);
glBufferDataARB(GL_ARRAY_BUFFER_ARB,
- sizeof(VertexBufferFormat) * totvert,
- NULL, GL_STATIC_DRAW_ARB);
+ sizeof(VertexBufferFormat) * totelem,
+ NULL, GL_STATIC_DRAW_ARB);
+
vert_data = glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB);
if (vert_data) {
- for (i = 0; i < totvert; ++i) {
- MVert *v = mvert + vert_indices[i];
- VertexBufferFormat *out = vert_data + i;
-
- copy_v3_v3(out->co, v->co);
- memcpy(out->no, v->no, sizeof(short) * 3);
- gpu_color_from_mask_copy(vmask[vert_indices[i]],
- out->color);
+ /* Vertex data is shared if smooth-shaded, but seperate
+ copies are made for flat shading because normals
+ shouldn't be shared. */
+ if (buffers->smooth) {
+ for (i = 0; i < totvert; ++i) {
+ MVert *v = mvert + vert_indices[i];
+ VertexBufferFormat *out = vert_data + i;
+
+ copy_v3_v3(out->co, v->co);
+ memcpy(out->no, v->no, sizeof(short) * 3);
+ }
+
+#define UPDATE_VERTEX(face, vertex, index, diffuse_color) \
+ { \
+ VertexBufferFormat *out = vert_data + face_vert_indices[face][index]; \
+ if (vmask) \
+ gpu_color_from_mask_copy(vmask[vertex], diffuse_color, out->color); \
+ else \
+ rgb_float_to_uchar(out->color, diffuse_color); \
+ } (void)0
+
+ for (i = 0; i < buffers->totface; i++) {
+ MFace *f = buffers->mface + buffers->face_indices[i];
+
+ UPDATE_VERTEX(i, f->v1, 0, diffuse_color);
+ UPDATE_VERTEX(i, f->v2, 1, diffuse_color);
+ UPDATE_VERTEX(i, f->v3, 2, diffuse_color);
+ if (f->v4)
+ UPDATE_VERTEX(i, f->v4, 3, diffuse_color);
+ }
+#undef UPDATE_VERTEX
+ }
+ else {
+ for (i = 0; i < buffers->totface; ++i) {
+ const MFace *f = &buffers->mface[buffers->face_indices[i]];
+ const unsigned int *fv = &f->v1;
+ const int vi[2][3] = {{0, 1, 2}, {3, 0, 2}};
+ float fno[3];
+ short no[3];
+
+ float fmask;
+
+ if (paint_is_face_hidden(f, mvert))
+ continue;
+
+ /* Face normal and mask */
+ if (f->v4) {
+ normal_quad_v3(fno,
+ mvert[fv[0]].co,
+ mvert[fv[1]].co,
+ mvert[fv[2]].co,
+ mvert[fv[3]].co);
+ if (vmask) {
+ fmask = (vmask[fv[0]] +
+ vmask[fv[1]] +
+ vmask[fv[2]] +
+ vmask[fv[3]]) * 0.25f;
+ }
+ }
+ else {
+ normal_tri_v3(fno,
+ mvert[fv[0]].co,
+ mvert[fv[1]].co,
+ mvert[fv[2]].co);
+ if (vmask) {
+ fmask = (vmask[fv[0]] +
+ vmask[fv[1]] +
+ vmask[fv[2]]) / 3.0f;
+ }
+ }
+ normal_float_to_short_v3(no, fno);
+
+ for (j = 0; j < (f->v4 ? 2 : 1); j++) {
+ for (k = 0; k < 3; k++) {
+ const MVert *v = &mvert[fv[vi[j][k]]];
+ VertexBufferFormat *out = vert_data;
+
+ copy_v3_v3(out->co, v->co);
+ memcpy(out->no, no, sizeof(short) * 3);
+
+ if (vmask)
+ gpu_color_from_mask_copy(fmask, diffuse_color, out->color);
+ else
+ rgb_float_to_uchar(out->color, diffuse_color);
+
+ vert_data++;
+ }
+ }
+ }
}
glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
@@ -1432,6 +1501,9 @@ GPU_Buffers *GPU_build_mesh_buffers(int (*face_vert_indices)[4],
buffers = MEM_callocN(sizeof(GPU_Buffers), "GPU_Buffers");
buffers->index_type = GL_UNSIGNED_SHORT;
+ buffers->smooth = mface[face_indices[0]].flag & ME_SMOOTH;
+
+ buffers->show_diffuse_color = FALSE;
/* Count the number of visible triangles */
for (i = 0, tottri = 0; i < totface; ++i) {
@@ -1439,8 +1511,11 @@ GPU_Buffers *GPU_build_mesh_buffers(int (*face_vert_indices)[4],
if (!paint_is_face_hidden(f, mvert))
tottri += f->v4 ? 2 : 1;
}
-
- if (GLEW_ARB_vertex_buffer_object && !(U.gameflags & USER_DISABLE_VBO))
+
+ /* An element index buffer is used for smooth shading, but flat
+ shading requires separate vertex normals so an index buffer is
+ can't be used there. */
+ if (gpu_vbo_enabled() && buffers->smooth)
glGenBuffersARB(1, &buffers->index_buf);
if (buffers->index_buf) {
@@ -1484,7 +1559,7 @@ GPU_Buffers *GPU_build_mesh_buffers(int (*face_vert_indices)[4],
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
}
- if (buffers->index_buf)
+ if (gpu_vbo_enabled() && (buffers->index_buf || !buffers->smooth))
glGenBuffersARB(1, &buffers->vert_buf);
buffers->tot_tri = tottri;
@@ -1498,15 +1573,27 @@ GPU_Buffers *GPU_build_mesh_buffers(int (*face_vert_indices)[4],
void GPU_update_grid_buffers(GPU_Buffers *buffers, CCGElem **grids,
const DMFlagMat *grid_flag_mats, int *grid_indices,
- int totgrid, const CCGKey *key)
+ int totgrid, const CCGKey *key, int show_diffuse_color)
{
VertexBufferFormat *vert_data;
int i, j, k, x, y;
+ buffers->show_diffuse_color = show_diffuse_color;
+
/* Build VBO */
if (buffers->vert_buf) {
int totvert = key->grid_area * totgrid;
int smooth = grid_flag_mats[grid_indices[0]].flag & ME_SMOOTH;
+ const int has_mask = key->has_mask;
+ float diffuse_color[4] = {0.8f, 0.8f, 0.8f, 1.0f};
+
+ if (buffers->show_diffuse_color) {
+ const DMFlagMat *flags = &grid_flag_mats[grid_indices[0]];
+
+ GPU_material_diffuse_get(flags->mat_nr + 1, diffuse_color);
+ }
+
+ copy_v4_v4(buffers->diffuse_color, diffuse_color);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, buffers->vert_buf);
glBufferDataARB(GL_ARRAY_BUFFER_ARB,
@@ -1524,11 +1611,12 @@ void GPU_update_grid_buffers(GPU_Buffers *buffers, CCGElem **grids,
copy_v3_v3(vd->co, CCG_elem_co(key, elem));
if (smooth) {
- normal_float_to_short_v3(vd->no,
- CCG_elem_no(key, elem));
+ normal_float_to_short_v3(vd->no, CCG_elem_no(key, elem));
- gpu_color_from_mask_copy(*CCG_elem_mask(key, elem),
- vd->color);
+ if (has_mask) {
+ gpu_color_from_mask_copy(*CCG_elem_mask(key, elem),
+ diffuse_color, vd->color);
+ }
}
vd++;
}
@@ -1556,12 +1644,16 @@ void GPU_update_grid_buffers(GPU_Buffers *buffers, CCGElem **grids,
vd = vert_data + (j + 1) * key->grid_size + (k + 1);
normal_float_to_short_v3(vd->no, fno);
- gpu_color_from_mask_quad_copy(key,
- elems[0],
- elems[1],
- elems[2],
- elems[3],
- vd->color);
+
+ if (has_mask) {
+ gpu_color_from_mask_quad_copy(key,
+ elems[0],
+ elems[1],
+ elems[2],
+ elems[3],
+ diffuse_color,
+ vd->color);
+ }
}
}
}
@@ -1583,6 +1675,8 @@ void GPU_update_grid_buffers(GPU_Buffers *buffers, CCGElem **grids,
buffers->grid_flag_mats = grid_flag_mats;
buffers->gridkey = *key;
+ buffers->smooth = grid_flag_mats[grid_indices[0]].flag & ME_SMOOTH;
+
//printf("node updated %p\n", buffers);
}
@@ -1677,7 +1771,7 @@ static GLuint gpu_get_grid_buffer(int gridsize, GLenum *index_type, unsigned *to
/* VBO is disabled; delete the previous buffer (if it exists) and
* return an invalid handle */
- if (!GLEW_ARB_vertex_buffer_object || (U.gameflags & USER_DISABLE_VBO)) {
+ if (!gpu_vbo_enabled()) {
if (buffer)
glDeleteBuffersARB(1, &buffer);
return 0;
@@ -1726,6 +1820,8 @@ GPU_Buffers *GPU_build_grid_buffers(int *grid_indices, int totgrid,
buffers->grid_hidden = grid_hidden;
buffers->totgrid = totgrid;
+ buffers->show_diffuse_color = FALSE;
+
/* Count the number of quads */
totquad = gpu_count_grid_quads(grid_hidden, grid_indices, totgrid, gridsize);
@@ -1765,12 +1861,20 @@ GPU_Buffers *GPU_build_grid_buffers(int *grid_indices, int totgrid,
#undef FILL_QUAD_BUFFER
-static void gpu_draw_buffers_legacy_mesh(GPU_Buffers *buffers, int smooth)
+static void gpu_draw_buffers_legacy_mesh(GPU_Buffers *buffers)
{
const MVert *mvert = buffers->mvert;
int i, j;
+ const int has_mask = (buffers->vmask != NULL);
+ const MFace *face = &buffers->mface[buffers->face_indices[0]];
+ float diffuse_color[4] = {0.8f, 0.8f, 0.8f, 1.0f};
- gpu_colors_enable(VBO_DISABLED);
+ if (buffers->show_diffuse_color)
+ GPU_material_diffuse_get(face->mat_nr + 1, diffuse_color);
+
+ if (has_mask) {
+ gpu_colors_enable(VBO_DISABLED);
+ }
for (i = 0; i < buffers->totface; ++i) {
MFace *f = buffers->mface + buffers->face_indices[i];
@@ -1782,15 +1886,17 @@ static void gpu_draw_buffers_legacy_mesh(GPU_Buffers *buffers, int smooth)
glBegin((f->v4) ? GL_QUADS : GL_TRIANGLES);
- if (smooth) {
+ if (buffers->smooth) {
for (j = 0; j < S; j++) {
- gpu_color_from_mask_set(buffers->vmask[fv[j]]);
+ if (has_mask) {
+ gpu_color_from_mask_set(buffers->vmask[fv[j]], diffuse_color);
+ }
glNormal3sv(mvert[fv[j]].no);
glVertex3fv(mvert[fv[j]].co);
}
}
else {
- float fmask, fno[3];
+ float fno[3];
/* calculate face normal */
if (f->v4) {
@@ -1801,15 +1907,19 @@ static void gpu_draw_buffers_legacy_mesh(GPU_Buffers *buffers, int smooth)
normal_tri_v3(fno, mvert[fv[0]].co, mvert[fv[1]].co, mvert[fv[2]].co);
glNormal3fv(fno);
- /* calculate face mask color */
- fmask = (buffers->vmask[fv[0]] +
- buffers->vmask[fv[1]] +
- buffers->vmask[fv[2]]);
- if (f->v4)
- fmask = (fmask + buffers->vmask[fv[3]]) * 0.25;
- else
- fmask /= 3.0f;
- gpu_color_from_mask_set(fmask);
+ if (has_mask) {
+ float fmask;
+
+ /* calculate face mask color */
+ fmask = (buffers->vmask[fv[0]] +
+ buffers->vmask[fv[1]] +
+ buffers->vmask[fv[2]]);
+ if (f->v4)
+ fmask = (fmask + buffers->vmask[fv[3]]) * 0.25f;
+ else
+ fmask /= 3.0f;
+ gpu_color_from_mask_set(fmask, diffuse_color);
+ }
for (j = 0; j < S; j++)
glVertex3fv(mvert[fv[j]].co);
@@ -1818,15 +1928,25 @@ static void gpu_draw_buffers_legacy_mesh(GPU_Buffers *buffers, int smooth)
glEnd();
}
- gpu_colors_disable(VBO_DISABLED);
+ if (has_mask) {
+ gpu_colors_disable(VBO_DISABLED);
+ }
}
-static void gpu_draw_buffers_legacy_grids(GPU_Buffers *buffers, int smooth)
+static void gpu_draw_buffers_legacy_grids(GPU_Buffers *buffers)
{
const CCGKey *key = &buffers->gridkey;
int i, j, x, y, gridsize = buffers->gridkey.grid_size;
+ const int has_mask = key->has_mask;
+ const DMFlagMat *flags = &buffers->grid_flag_mats[buffers->grid_indices[0]];
+ float diffuse_color[4] = {0.8f, 0.8f, 0.8f, 1.0f};
+
+ if (buffers->show_diffuse_color)
+ GPU_material_diffuse_get(flags->mat_nr + 1, diffuse_color);
- gpu_colors_enable(VBO_DISABLED);
+ if (has_mask) {
+ gpu_colors_enable(VBO_DISABLED);
+ }
for (i = 0; i < buffers->totgrid; ++i) {
int g = buffers->grid_indices[i];
@@ -1851,9 +1971,11 @@ static void gpu_draw_buffers_legacy_grids(GPU_Buffers *buffers, int smooth)
if (paint_is_grid_face_hidden(gh, gridsize, x, y))
continue;
- if (smooth) {
+ if (buffers->smooth) {
for (j = 0; j < 4; j++) {
- gpu_color_from_mask_set(*CCG_elem_mask(key, e[j]));
+ if (has_mask) {
+ gpu_color_from_mask_set(*CCG_elem_mask(key, e[j]), diffuse_color);
+ }
glNormal3fv(CCG_elem_no(key, e[j]));
glVertex3fv(CCG_elem_co(key, e[j]));
}
@@ -1866,7 +1988,10 @@ static void gpu_draw_buffers_legacy_grids(GPU_Buffers *buffers, int smooth)
CCG_elem_co(key, e[2]),
CCG_elem_co(key, e[3]));
glNormal3fv(fno);
- gpu_color_from_mask_quad_set(key, e[0], e[1], e[2], e[3]);
+
+ if (has_mask) {
+ gpu_color_from_mask_quad_set(key, e[0], e[1], e[2], e[3], diffuse_color);
+ }
for (j = 0; j < 4; j++)
glVertex3fv(CCG_elem_co(key, e[j]));
@@ -1876,17 +2001,21 @@ static void gpu_draw_buffers_legacy_grids(GPU_Buffers *buffers, int smooth)
glEnd();
}
- else if (smooth) {
+ else if (buffers->smooth) {
for (y = 0; y < gridsize - 1; y++) {
glBegin(GL_QUAD_STRIP);
for (x = 0; x < gridsize; x++) {
CCGElem *a = CCG_grid_elem(key, grid, x, y);
CCGElem *b = CCG_grid_elem(key, grid, x, y + 1);
- gpu_color_from_mask_set(*CCG_elem_mask(key, a));
+ if (has_mask) {
+ gpu_color_from_mask_set(*CCG_elem_mask(key, a), diffuse_color);
+ }
glNormal3fv(CCG_elem_no(key, a));
glVertex3fv(CCG_elem_co(key, a));
- gpu_color_from_mask_set(*CCG_elem_mask(key, b));
+ if (has_mask) {
+ gpu_color_from_mask_set(*CCG_elem_mask(key, b), diffuse_color);
+ }
glNormal3fv(CCG_elem_no(key, b));
glVertex3fv(CCG_elem_co(key, b));
}
@@ -1912,7 +2041,9 @@ static void gpu_draw_buffers_legacy_grids(GPU_Buffers *buffers, int smooth)
CCG_elem_co(key, c));
glNormal3fv(fno);
- gpu_color_from_mask_quad_set(key, a, b, c, d);
+ if (has_mask) {
+ gpu_color_from_mask_quad_set(key, a, b, c, d, diffuse_color);
+ }
}
glVertex3fv(CCG_elem_co(key, a));
@@ -1923,37 +2054,35 @@ static void gpu_draw_buffers_legacy_grids(GPU_Buffers *buffers, int smooth)
}
}
- gpu_colors_disable(VBO_DISABLED);
+ if (has_mask) {
+ gpu_colors_disable(VBO_DISABLED);
+ }
}
void GPU_draw_buffers(GPU_Buffers *buffers, DMSetMaterial setMaterial)
{
- int smooth = 0;
-
if (buffers->totface) {
const MFace *f = &buffers->mface[buffers->face_indices[0]];
if (!setMaterial(f->mat_nr + 1, NULL))
return;
-
- smooth = f->flag & ME_SMOOTH;
- glShadeModel(smooth ? GL_SMOOTH : GL_FLAT);
}
else if (buffers->totgrid) {
const DMFlagMat *f = &buffers->grid_flag_mats[buffers->grid_indices[0]];
if (!setMaterial(f->mat_nr + 1, NULL))
return;
-
- smooth = f->flag & ME_SMOOTH;
- glShadeModel(smooth ? GL_SMOOTH : GL_FLAT);
}
- if (buffers->vert_buf && buffers->index_buf) {
+ glShadeModel((buffers->smooth || buffers->totface) ? GL_SMOOTH : GL_FLAT);
+
+ if (buffers->vert_buf) {
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
gpu_colors_enable(VBO_ENABLED);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, buffers->vert_buf);
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, buffers->index_buf);
+
+ if (buffers->index_buf)
+ glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, buffers->index_buf);
if (buffers->tot_quad) {
char *offset = 0;
@@ -1972,6 +2101,8 @@ void GPU_draw_buffers(GPU_Buffers *buffers, DMSetMaterial setMaterial)
}
}
else {
+ int totelem = buffers->tot_tri * 3;
+
glVertexPointer(3, GL_FLOAT, sizeof(VertexBufferFormat),
(void *)offsetof(VertexBufferFormat, co));
glNormalPointer(GL_SHORT, sizeof(VertexBufferFormat),
@@ -1979,11 +2110,15 @@ void GPU_draw_buffers(GPU_Buffers *buffers, DMSetMaterial setMaterial)
glColorPointer(3, GL_UNSIGNED_BYTE, sizeof(VertexBufferFormat),
(void *)offsetof(VertexBufferFormat, color));
- glDrawElements(GL_TRIANGLES, buffers->tot_tri * 3, buffers->index_type, 0);
+ if (buffers->index_buf)
+ glDrawElements(GL_TRIANGLES, totelem, buffers->index_type, 0);
+ else
+ glDrawArrays(GL_TRIANGLES, 0, totelem);
}
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
+ if (buffers->index_buf)
+ glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
@@ -1991,13 +2126,39 @@ void GPU_draw_buffers(GPU_Buffers *buffers, DMSetMaterial setMaterial)
}
/* fallbacks if we are out of memory or VBO is disabled */
else if (buffers->totface) {
- gpu_draw_buffers_legacy_mesh(buffers, smooth);
+ gpu_draw_buffers_legacy_mesh(buffers);
}
else if (buffers->totgrid) {
- gpu_draw_buffers_legacy_grids(buffers, smooth);
+ gpu_draw_buffers_legacy_grids(buffers);
}
}
+int GPU_buffers_diffuse_changed(GPU_Buffers *buffers, int show_diffuse_color)
+{
+ float diffuse_color[4];
+
+ if (buffers->show_diffuse_color != show_diffuse_color)
+ return TRUE;
+
+ if (buffers->show_diffuse_color == FALSE)
+ return FALSE;
+
+ if (buffers->mface) {
+ MFace *f = buffers->mface + buffers->face_indices[0];
+
+ GPU_material_diffuse_get(f->mat_nr + 1, diffuse_color);
+ }
+ else {
+ const DMFlagMat *flags = &buffers->grid_flag_mats[buffers->grid_indices[0]];
+
+ GPU_material_diffuse_get(flags->mat_nr + 1, diffuse_color);
+ }
+
+ return diffuse_color[0] != buffers->diffuse_color[0] ||
+ diffuse_color[1] != buffers->diffuse_color[1] ||
+ diffuse_color[2] != buffers->diffuse_color[2];
+}
+
void GPU_free_buffers(GPU_Buffers *buffers)
{
if (buffers) {
diff --git a/source/blender/gpu/intern/gpu_codegen.c b/source/blender/gpu/intern/gpu_codegen.c
index 25990e8fc6e..b4490e656f3 100644
--- a/source/blender/gpu/intern/gpu_codegen.c
+++ b/source/blender/gpu/intern/gpu_codegen.c
@@ -761,7 +761,7 @@ void GPU_pass_bind(GPUPass *pass, double time, int mipmap)
/* now bind the textures */
for (input=inputs->first; input; input=input->next) {
if (input->ima)
- input->tex = GPU_texture_from_blender(input->ima, input->iuser, input->imagencd, time, mipmap);
+ input->tex = GPU_texture_from_blender(input->ima, input->iuser, input->image_isdata, time, mipmap);
if (input->tex && input->bindtex) {
GPU_texture_bind(input->tex, input->texid);
@@ -917,7 +917,7 @@ static void gpu_node_input_link(GPUNode *node, GPUNodeLink *link, int type)
input->ima = link->ptr1;
input->iuser = link->ptr2;
- input->imagencd = link->imagencd;
+ input->image_isdata = link->image_isdata;
input->textarget = GL_TEXTURE_2D;
input->textype = GPU_TEX2D;
MEM_freeN(link);
@@ -1046,17 +1046,20 @@ static void gpu_nodes_get_vertex_attributes(ListBase *nodes, GPUVertexAttribs *a
}
}
- if (a == attribs->totlayer && a < GPU_MAX_ATTRIB) {
- input->attribid = attribs->totlayer++;
- input->attribfirst = 1;
+ if (a < GPU_MAX_ATTRIB) {
+ if (a == attribs->totlayer) {
+ input->attribid = attribs->totlayer++;
+ input->attribfirst = 1;
- attribs->layer[a].type = input->attribtype;
- attribs->layer[a].attribid = input->attribid;
- BLI_strncpy(attribs->layer[a].name, input->attribname,
- sizeof(attribs->layer[a].name));
+ attribs->layer[a].type = input->attribtype;
+ attribs->layer[a].attribid = input->attribid;
+ BLI_strncpy(attribs->layer[a].name, input->attribname,
+ sizeof(attribs->layer[a].name));
+ }
+ else {
+ input->attribid = attribs->layer[a].attribid;
+ }
}
- else
- input->attribid = attribs->layer[a].attribid;
}
}
}
@@ -1110,14 +1113,14 @@ GPUNodeLink *GPU_dynamic_uniform(float *num, int dynamictype, void *data)
return link;
}
-GPUNodeLink *GPU_image(Image *ima, ImageUser *iuser, int ncd)
+GPUNodeLink *GPU_image(Image *ima, ImageUser *iuser, int isdata)
{
GPUNodeLink *link = GPU_node_link_create(0);
link->image= 1;
link->ptr1= ima;
link->ptr2= iuser;
- link->imagencd= ncd;
+ link->image_isdata= isdata;
return link;
}
diff --git a/source/blender/gpu/intern/gpu_codegen.h b/source/blender/gpu/intern/gpu_codegen.h
index 3010937a2f3..f61f34908c5 100644
--- a/source/blender/gpu/intern/gpu_codegen.h
+++ b/source/blender/gpu/intern/gpu_codegen.h
@@ -91,7 +91,7 @@ struct GPUNodeLink {
const char *attribname;
int image;
- int imagencd;
+ int image_isdata;
int texture;
int texturesize;
@@ -99,7 +99,7 @@ struct GPUNodeLink {
void *ptr1, *ptr2;
int dynamic;
- int dynamictype;
+ int dynamictype;
int type;
int users;
@@ -138,7 +138,7 @@ typedef struct GPUInput {
struct Image *ima; /* image */
struct ImageUser *iuser;/* image user */
- int imagencd; /* image does not contain color data */
+ int image_isdata; /* image does not contain color data */
float *dynamicvec; /* vector data in case it is dynamic */
int dynamictype; /* origin of the dynamic uniform (GPUDynamicType) */
void *dynamicdata; /* data source of the dynamic uniform */
diff --git a/source/blender/gpu/intern/gpu_draw.c b/source/blender/gpu/intern/gpu_draw.c
index 9b027f7906d..7bd72430969 100644
--- a/source/blender/gpu/intern/gpu_draw.c
+++ b/source/blender/gpu/intern/gpu_draw.c
@@ -422,7 +422,7 @@ static void gpu_verify_reflection(Image *ima)
}
}
-int GPU_verify_image(Image *ima, ImageUser *iuser, int tftile, int compare, int mipmap, int ncd)
+int GPU_verify_image(Image *ima, ImageUser *iuser, int tftile, int compare, int mipmap, int is_data)
{
ImBuf *ibuf = NULL;
unsigned int *bind = NULL;
@@ -492,7 +492,7 @@ int GPU_verify_image(Image *ima, ImageUser *iuser, int tftile, int compare, int
}
/* TODO unneeded when float images are correctly treated as linear always */
- if (!ncd)
+ if (!is_data)
do_color_management = TRUE;
if (ibuf->rect==NULL)
@@ -611,12 +611,21 @@ int GPU_verify_image(Image *ima, ImageUser *iuser, int tftile, int compare, int
rect= tilerect;
}
}
+
#ifdef WITH_DDS
if (ibuf->ftype & DDS)
GPU_create_gl_tex_compressed(bind, rect, rectw, recth, mipmap, ima, ibuf);
else
#endif
GPU_create_gl_tex(bind, rect, frect, rectw, recth, mipmap, use_high_bit_depth, ima);
+
+ /* mark as non-color data texture */
+ if (*bind) {
+ if (is_data)
+ ima->tpageflag |= IMA_GLBIND_IS_DATA;
+ else
+ ima->tpageflag &= ~IMA_GLBIND_IS_DATA;
+ }
/* clean up */
if (tilerect)
@@ -709,7 +718,7 @@ void GPU_create_gl_tex(unsigned int *bind, unsigned int *pix, float * frect, int
*/
int GPU_upload_dxt_texture(ImBuf *ibuf)
{
-#if WITH_DDS
+#ifdef WITH_DDS
GLint format = 0;
int blocksize, height, width, i, size, offset = 0;
@@ -730,12 +739,17 @@ int GPU_upload_dxt_texture(ImBuf *ibuf)
return FALSE;
}
+ if (!is_power_of_2_i(width) || !is_power_of_2_i(height)) {
+ printf("Unable to load non-power-of-two DXT image resolution, falling back to uncompressed\n");
+ return FALSE;
+ }
+
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
- blocksize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16;
+ blocksize = (ibuf->dds_data.fourcc == FOURCC_DXT1) ? 8 : 16;
for (i=0; i<ibuf->dds_data.nummipmaps && (width||height); ++i) {
if (width == 0)
width = 1;
@@ -878,13 +892,13 @@ void GPU_paint_set_mipmap(int mipmap)
}
}
-void GPU_paint_update_image(Image *ima, int x, int y, int w, int h, int mipmap)
+void GPU_paint_update_image(Image *ima, int x, int y, int w, int h)
{
ImBuf *ibuf;
ibuf = BKE_image_get_ibuf(ima, NULL);
- if (ima->repbind || (GPU_get_mipmap() && mipmap) || !ima->bindcode || !ibuf ||
+ if (ima->repbind || (GPU_get_mipmap() && !GTS.gpu_mipmap) || !ima->bindcode || !ibuf ||
(!is_power_of_2_i(ibuf->x) || !is_power_of_2_i(ibuf->y)) ||
(w == 0) || (h == 0))
{
@@ -903,7 +917,8 @@ void GPU_paint_update_image(Image *ima, int x, int y, int w, int h, int mipmap)
/* if color correction is needed, we must update the part that needs updating. */
if (ibuf->rect_float) {
float *buffer = MEM_mallocN(w*h*sizeof(float)*4, "temp_texpaint_float_buf");
- IMB_partial_rect_from_float(ibuf, buffer, x, y, w, h);
+ int is_data = (ima->tpageflag & IMA_GLBIND_IS_DATA);
+ IMB_partial_rect_from_float(ibuf, buffer, x, y, w, h, is_data);
glBindTexture(GL_TEXTURE_2D, ima->bindcode);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA,
@@ -911,8 +926,14 @@ void GPU_paint_update_image(Image *ima, int x, int y, int w, int h, int mipmap)
MEM_freeN(buffer);
- if (ima->tpageflag & IMA_MIPMAP_COMPLETE)
+ /* we have already accounted for the case where GTS.gpu_mipmap is false
+ * so we will be using GPU mipmap generation here */
+ if (GPU_get_mipmap()) {
+ glGenerateMipmapEXT(GL_TEXTURE_2D);
+ }
+ else {
ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
+ }
return;
}
@@ -923,19 +944,20 @@ void GPU_paint_update_image(Image *ima, int x, int y, int w, int h, int mipmap)
glPixelStorei(GL_UNPACK_SKIP_PIXELS, x);
glPixelStorei(GL_UNPACK_SKIP_ROWS, y);
- if (ibuf->rect_float)
- glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA,
- GL_FLOAT, ibuf->rect_float);
- else
- glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA,
- GL_UNSIGNED_BYTE, ibuf->rect);
+ glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA,
+ GL_UNSIGNED_BYTE, ibuf->rect);
glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, skip_pixels);
glPixelStorei(GL_UNPACK_SKIP_ROWS, skip_rows);
- if (ima->tpageflag & IMA_MIPMAP_COMPLETE)
+ /* see comment above as to why we are using gpu mipmap generation here */
+ if (GPU_get_mipmap()) {
+ glGenerateMipmapEXT(GL_TEXTURE_2D);
+ }
+ else {
ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
+ }
}
}
@@ -1008,21 +1030,53 @@ void GPU_free_smoke(SmokeModifierData *smd)
if (smd->domain->tex_shadow)
GPU_texture_free(smd->domain->tex_shadow);
smd->domain->tex_shadow = NULL;
+
+ if (smd->domain->tex_flame)
+ GPU_texture_free(smd->domain->tex_flame);
+ smd->domain->tex_flame = NULL;
}
}
void GPU_create_smoke(SmokeModifierData *smd, int highres)
{
#ifdef WITH_SMOKE
- if (smd->type & MOD_SMOKE_TYPE_DOMAIN && !smd->domain->tex && !highres)
- smd->domain->tex = GPU_texture_create_3D(smd->domain->res[0], smd->domain->res[1], smd->domain->res[2], smoke_get_density(smd->domain->fluid));
- else if (smd->type & MOD_SMOKE_TYPE_DOMAIN && !smd->domain->tex && highres)
- smd->domain->tex = GPU_texture_create_3D(smd->domain->res_wt[0], smd->domain->res_wt[1], smd->domain->res_wt[2], smoke_turbulence_get_density(smd->domain->wt));
+ if (smd->type & MOD_SMOKE_TYPE_DOMAIN) {
+ SmokeDomainSettings *sds = smd->domain;
+ if (!sds->tex && !highres) {
+ /* rgba texture for color + density */
+ if (smoke_has_colors(sds->fluid)) {
+ float *data = MEM_callocN(sizeof(float)*sds->total_cells*4, "smokeColorTexture");
+ smoke_get_rgba(sds->fluid, data, 0);
+ sds->tex = GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 4, data);
+ MEM_freeN(data);
+ }
+ /* density only */
+ else {
+ sds->tex = GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 1, smoke_get_density(sds->fluid));
+ }
+ sds->tex_flame = (smoke_has_fuel(sds->fluid)) ? GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 1, smoke_get_flame(sds->fluid)) : NULL;
+ }
+ else if (!sds->tex && highres) {
+ /* rgba texture for color + density */
+ if (smoke_turbulence_has_colors(sds->wt)) {
+ float *data = MEM_callocN(sizeof(float)*smoke_turbulence_get_cells(sds->wt)*4, "smokeColorTexture");
+ smoke_turbulence_get_rgba(sds->wt, data, 0);
+ sds->tex = GPU_texture_create_3D(sds->res_wt[0], sds->res_wt[1], sds->res_wt[2], 4, data);
+ MEM_freeN(data);
+ }
+ /* density only */
+ else {
+ sds->tex = GPU_texture_create_3D(sds->res_wt[0], sds->res_wt[1], sds->res_wt[2], 1, smoke_turbulence_get_density(sds->wt));
+ }
+ sds->tex_flame = (smoke_turbulence_has_fuel(sds->wt)) ? GPU_texture_create_3D(sds->res_wt[0], sds->res_wt[1], sds->res_wt[2], 1, smoke_turbulence_get_flame(sds->wt)) : NULL;
+ }
- smd->domain->tex_shadow = GPU_texture_create_3D(smd->domain->res[0], smd->domain->res[1], smd->domain->res[2], smd->domain->shadow);
+ sds->tex_shadow = GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 1, sds->shadow);
+ }
#else // WITH_SMOKE
(void)highres;
smd->domain->tex= NULL;
+ smd->domain->tex_flame= NULL;
smd->domain->tex_shadow= NULL;
#endif // WITH_SMOKE
}
@@ -1087,7 +1141,7 @@ void GPU_free_image(Image *ima)
ima->repbind= NULL;
}
- ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
+ ima->tpageflag &= ~(IMA_MIPMAP_COMPLETE|IMA_GLBIND_IS_DATA);
}
void GPU_free_images(void)
@@ -1173,7 +1227,7 @@ static void gpu_material_to_fixed(GPUMaterialFixed *smat, const Material *bmat,
if (gamma) {
linearrgb_to_srgb_v3_v3(smat->diff, smat->diff);
linearrgb_to_srgb_v3_v3(smat->spec, smat->spec);
- }
+ }
}
}
@@ -1198,10 +1252,7 @@ void GPU_begin_object_materials(View3D *v3d, RegionView3D *rv3d, Scene *scene, O
GPUBlendMode alphablend;
int a;
- /* OCIO_TODO: assume color management is always enabled. could be nice to support real display transform here,
- * but that's not so important and could be done later
- */
- int gamma = TRUE;
+ int gamma = BKE_scene_check_color_management_enabled(scene);
int new_shading_nodes = BKE_scene_use_new_shading_nodes(scene);
@@ -1429,6 +1480,21 @@ void GPU_disable_material(void)
GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
}
+void GPU_material_diffuse_get(int nr, float diff[4])
+{
+ /* prevent index to use un-initialized array items */
+ if (nr >= GMS.totmat)
+ nr = 0;
+
+ /* no GPU_begin_object_materials, use default material */
+ if (!GMS.matbuf) {
+ mul_v3_v3fl(diff, &defmaterial.r, defmaterial.ref + defmaterial.emit);
+ }
+ else {
+ copy_v4_v4(diff, GMS.matbuf[nr].diff);
+ }
+}
+
void GPU_end_object_materials(void)
{
GPU_disable_material();
@@ -1587,7 +1653,7 @@ int GPU_scene_object_lights(Scene *scene, Object *ob, int lay, float viewmat[][4
glLightfv(GL_LIGHT0+count, GL_SPECULAR, energy);
glEnable(GL_LIGHT0+count);
- glPopMatrix();
+ glPopMatrix();
count++;
if (count==8)
diff --git a/source/blender/gpu/intern/gpu_extensions.c b/source/blender/gpu/intern/gpu_extensions.c
index c5f427fbcab..cef664437b7 100644
--- a/source/blender/gpu/intern/gpu_extensions.c
+++ b/source/blender/gpu/intern/gpu_extensions.c
@@ -442,7 +442,7 @@ static GPUTexture *GPU_texture_create_nD(int w, int h, int n, float *fpixels, in
}
-GPUTexture *GPU_texture_create_3D(int w, int h, int depth, float *fpixels)
+GPUTexture *GPU_texture_create_3D(int w, int h, int depth, int channels, float *fpixels)
{
GPUTexture *tex;
GLenum type, format, internalformat;
@@ -480,9 +480,15 @@ GPUTexture *GPU_texture_create_3D(int w, int h, int depth, float *fpixels)
GPU_print_error("3D glBindTexture");
- type = GL_FLOAT; // GL_UNSIGNED_BYTE
- format = GL_RED;
- internalformat = GL_INTENSITY;
+ type = GL_FLOAT;
+ if (channels == 4) {
+ format = GL_RGBA;
+ internalformat = GL_RGBA;
+ }
+ else {
+ format = GL_RED;
+ internalformat = GL_INTENSITY;
+ }
//if (fpixels)
// pixels = GPU_texture_convert_pixels(w*h*depth, fpixels);
@@ -522,7 +528,7 @@ GPUTexture *GPU_texture_create_3D(int w, int h, int depth, float *fpixels)
return tex;
}
-GPUTexture *GPU_texture_from_blender(Image *ima, ImageUser *iuser, int ncd, double time, int mipmap)
+GPUTexture *GPU_texture_from_blender(Image *ima, ImageUser *iuser, int isdata, double time, int mipmap)
{
GPUTexture *tex;
GLint w, h, border, lastbindcode, bindcode;
@@ -530,7 +536,7 @@ GPUTexture *GPU_texture_from_blender(Image *ima, ImageUser *iuser, int ncd, doub
glGetIntegerv(GL_TEXTURE_BINDING_2D, &lastbindcode);
GPU_update_image_time(ima, time);
- bindcode = GPU_verify_image(ima, iuser, 0, 0, mipmap, ncd);
+ bindcode = GPU_verify_image(ima, iuser, 0, 0, mipmap, isdata);
if (ima->gputexture) {
ima->gputexture->bindcode = bindcode;
@@ -1289,7 +1295,7 @@ GPUShader *GPU_shader_get_builtin_shader(GPUBuiltinShader shader)
return retval;
}
-void GPU_shader_free_builtin_shaders()
+void GPU_shader_free_builtin_shaders(void)
{
if (GG.shaders.vsm_store) {
MEM_freeN(GG.shaders.vsm_store);
diff --git a/source/blender/gpu/intern/gpu_material.c b/source/blender/gpu/intern/gpu_material.c
index dd92b561235..ef73764753c 100644
--- a/source/blender/gpu/intern/gpu_material.c
+++ b/source/blender/gpu/intern/gpu_material.c
@@ -389,10 +389,8 @@ void gpu_material_add_node(GPUMaterial *material, GPUNode *node)
int GPU_material_do_color_management(GPUMaterial *mat)
{
- /* OCIO_TODO: for now assume scene always does color management. probably could be
- * improved in the future to support real display transform
- * also probably we'll need to get rid ofgame engine's color management flag
- */
+ if (!BKE_scene_check_color_management_enabled(mat->scene))
+ return FALSE;
return !((mat->scene->gm.flag & GAME_GLSL_NO_COLOR_MANAGEMENT));
}
@@ -782,7 +780,9 @@ static void shade_one_light(GPUShadeInput *shi, GPUShadeResult *shr, GPULamp *la
}
}
- if (mat->scene->gm.flag & GAME_GLSL_NO_SHADERS);
+ if (mat->scene->gm.flag & GAME_GLSL_NO_SHADERS) {
+ /* pass */
+ }
else if (!(lamp->mode & LA_NO_SPEC) && !(lamp->mode & LA_ONLYSHADOW) &&
(GPU_link_changed(shi->spec) || ma->spec != 0.0f))
{
@@ -843,7 +843,7 @@ static void material_lights(GPUShadeInput *shi, GPUShadeResult *shr)
if (ob->transflag & OB_DUPLI) {
DupliObject *dob;
- ListBase *lb = object_duplilist(shi->gpumat->scene, ob);
+ ListBase *lb = object_duplilist(shi->gpumat->scene, ob, FALSE);
for (dob=lb->first; dob; dob=dob->next) {
Object *ob_iter = dob->ob;
@@ -1129,7 +1129,7 @@ static void do_material_tex(GPUShadeInput *shi)
newnor = tnor;
}
- norfac = minf(fabsf(mtex->norfac), 1.0f);
+ norfac = min_ff(fabsf(mtex->norfac), 1.0f);
if (norfac == 1.0f && !GPU_link_changed(stencil)) {
shi->vn = newnor;
@@ -1589,8 +1589,8 @@ void GPU_lamp_update_distance(GPULamp *lamp, float distance, float att1, float a
void GPU_lamp_update_spot(GPULamp *lamp, float spotsize, float spotblend)
{
- lamp->spotsi= cos(M_PI*spotsize/360.0);
- lamp->spotbl= (1.0f - lamp->spotsi)*spotblend;
+ lamp->spotsi= cosf((float)M_PI * spotsize / 360.0f);
+ lamp->spotbl= (1.0f - lamp->spotsi) * spotblend;
}
static void gpu_lamp_from_blender(Scene *scene, Object *ob, Object *par, Lamp *la, GPULamp *lamp)
@@ -1881,7 +1881,7 @@ GPUShaderExport *GPU_shader_export(struct Scene *scene, struct Material *ma)
GPUBuiltin gputype;
GPUDynamicType dynamictype;
GPUDataType datatype;
- } builtins[] = {
+ } builtins[] = {
{ GPU_VIEW_MATRIX, GPU_DYNAMIC_OBJECT_VIEWMAT, GPU_DATA_16F },
{ GPU_INVERSE_VIEW_MATRIX, GPU_DYNAMIC_OBJECT_VIEWIMAT, GPU_DATA_16F },
{ GPU_OBJECT_MATRIX, GPU_DYNAMIC_OBJECT_MAT, GPU_DATA_16F },
diff --git a/source/blender/gpu/shaders/gpu_shader_material.glsl b/source/blender/gpu/shaders/gpu_shader_material.glsl
index 81c3cab97d4..b930058864c 100644
--- a/source/blender/gpu/shaders/gpu_shader_material.glsl
+++ b/source/blender/gpu/shaders/gpu_shader_material.glsl
@@ -1894,7 +1894,7 @@ void test_shadowbuf_vsm(vec3 rco, sampler2D shadowmap, mat4 shadowpersmat, float
}
else {
result = 1.0;
- }
+ }
}
}
@@ -1992,7 +1992,7 @@ void node_bsdf_diffuse(vec4 color, float roughness, vec3 N, out vec4 result)
result = vec4(L*color.rgb, 1.0);
}
-void node_bsdf_glossy(vec4 color, float roughness, vec3 N, vec3 I, out vec4 result)
+void node_bsdf_glossy(vec4 color, float roughness, vec3 N, out vec4 result)
{
/* ambient light */
vec3 L = vec3(0.2);
@@ -2013,12 +2013,12 @@ void node_bsdf_glossy(vec4 color, float roughness, vec3 N, vec3 I, out vec4 resu
result = vec4(L*color.rgb, 1.0);
}
-void node_bsdf_anisotropic(vec4 color, float roughnessU, float roughnessV, vec3 N, vec3 I, out vec4 result)
+void node_bsdf_anisotropic(vec4 color, float roughness, float anisotropy, float rotation, vec3 N, vec3 T, out vec4 result)
{
node_bsdf_diffuse(color, 0.0, N, result);
}
-void node_bsdf_glass(vec4 color, float roughness, float ior, vec3 N, vec3 I, out vec4 result)
+void node_bsdf_glass(vec4 color, float roughness, float ior, vec3 N, out vec4 result)
{
node_bsdf_diffuse(color, 0.0, N, result);
}
@@ -2195,7 +2195,8 @@ void node_light_path(
out float is_glossy_ray,
out float is_singular_ray,
out float is_reflection_ray,
- out float is_transmission_ray)
+ out float is_transmission_ray,
+ out float ray_length)
{
is_camera_ray = 1.0;
is_shadow_ray = 0.0;
@@ -2204,6 +2205,7 @@ void node_light_path(
is_singular_ray = 0.0;
is_reflection_ray = 0.0;
is_transmission_ray = 0.0;
+ ray_length = 1.0;
}
void node_light_falloff(float strength, float tsmooth, out float quadratic, out float linear, out float constant)
@@ -2221,6 +2223,10 @@ void node_object_info(out vec3 location, out float object_index, out float mater
random = 0.0;
}
+void node_bump(float strength, float height, vec3 N, out vec3 result)
+{
+ result = N;
+}
/* output */
diff --git a/source/blender/ikplugin/BIK_api.h b/source/blender/ikplugin/BIK_api.h
index e1d5f50edfb..95b1dafd129 100644
--- a/source/blender/ikplugin/BIK_api.h
+++ b/source/blender/ikplugin/BIK_api.h
@@ -58,7 +58,7 @@ struct BIK_ParamValue {
float f[8];
int i[8];
char s[32];
- } value;
+ } value;
};
typedef struct BIK_ParamValue BIK_ParamValue;
@@ -92,5 +92,4 @@ void BIK_test_constraint(struct Object *ob, struct bConstraint *cons);
}
#endif
-#endif // __BIK_API_H__
-
+#endif /* __BIK_API_H__ */
diff --git a/source/blender/ikplugin/CMakeLists.txt b/source/blender/ikplugin/CMakeLists.txt
index 903267c5618..0a0e0e664b4 100644
--- a/source/blender/ikplugin/CMakeLists.txt
+++ b/source/blender/ikplugin/CMakeLists.txt
@@ -56,9 +56,11 @@ endif()
if(WITH_IK_ITASC)
add_definitions(-DWITH_IK_ITASC)
list(APPEND INC
- ../../../extern/Eigen3
../../../intern/itasc
)
+ list(APPEND INC_SYS
+ ../../../extern/Eigen3
+ )
list(APPEND SRC
intern/itasc_plugin.cpp
intern/itasc_plugin.h
diff --git a/source/blender/ikplugin/intern/ikplugin_api.h b/source/blender/ikplugin/intern/ikplugin_api.h
index 77c962269dc..53d9da8e614 100644
--- a/source/blender/ikplugin/intern/ikplugin_api.h
+++ b/source/blender/ikplugin/intern/ikplugin_api.h
@@ -60,5 +60,4 @@ typedef struct IKPlugin IKPlugin;
}
#endif
-#endif // __IKPLUGIN_API_H__
-
+#endif /* __IKPLUGIN_API_H__ */
diff --git a/source/blender/ikplugin/intern/iksolver_plugin.h b/source/blender/ikplugin/intern/iksolver_plugin.h
index dd00c5f4add..c2ae4f937e7 100644
--- a/source/blender/ikplugin/intern/iksolver_plugin.h
+++ b/source/blender/ikplugin/intern/iksolver_plugin.h
@@ -47,5 +47,4 @@ void iksolver_execute_tree(struct Scene *scene, struct Object *ob, struct bPose
}
#endif
-#endif // __IKSOLVER_PLUGIN_H__
-
+#endif /* __IKSOLVER_PLUGIN_H__ */
diff --git a/source/blender/ikplugin/intern/itasc_plugin.cpp b/source/blender/ikplugin/intern/itasc_plugin.cpp
index c5722995d32..5cf762af3e8 100644
--- a/source/blender/ikplugin/intern/itasc_plugin.cpp
+++ b/source/blender/ikplugin/intern/itasc_plugin.cpp
@@ -393,7 +393,7 @@ static bool constraint_valid(bConstraint *con)
return true;
}
-int initialize_scene(Object *ob, bPoseChannel *pchan_tip)
+static int initialize_scene(Object *ob, bPoseChannel *pchan_tip)
{
bConstraint *con;
int treecount;
@@ -1172,10 +1172,8 @@ static IK_Scene *convert_tree(Scene *blscene, Object *ob, bPoseChannel *pchan)
switch (ikchan->jointType & ~IK_TRANSY) {
case 0:
// fixed bone
- if (!(ikchan->jointType & IK_TRANSY)) {
- joint += ":F";
- ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, tip);
- }
+ joint += ":F";
+ ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, tip);
break;
case IK_XDOF:
// RX only, get the X rotation
@@ -1255,7 +1253,7 @@ static IK_Scene *convert_tree(Scene *blscene, Object *ob, bPoseChannel *pchan)
ret = arm->addSegment(joint, parent, KDL::Joint::TransY, rot[ikchan->ndof - 1]);
const float ikstretch = pchan->ikstretch * pchan->ikstretch;
/* why invert twice here? */
- weight[1] = (1.0 - minf(1.0 - ikstretch, 1.0f - 0.001f));
+ weight[1] = (1.0 - min_ff(1.0 - ikstretch, 1.0f - 0.001f));
weights.push_back(weight[1]);
}
if (!ret)
diff --git a/source/blender/ikplugin/intern/itasc_plugin.h b/source/blender/ikplugin/intern/itasc_plugin.h
index 0d5fde0bec0..0500125b4c7 100644
--- a/source/blender/ikplugin/intern/itasc_plugin.h
+++ b/source/blender/ikplugin/intern/itasc_plugin.h
@@ -52,5 +52,4 @@ void itasc_test_constraint(struct Object *ob, struct bConstraint *cons);
}
#endif
-#endif // __ITASC_PLUGIN_H__
-
+#endif /* __ITASC_PLUGIN_H__ */
diff --git a/source/blender/imbuf/CMakeLists.txt b/source/blender/imbuf/CMakeLists.txt
index 8849265679a..29ed8c95fc6 100644
--- a/source/blender/imbuf/CMakeLists.txt
+++ b/source/blender/imbuf/CMakeLists.txt
@@ -25,7 +25,6 @@
set(INC
.
- ../avi
../blenkernel
../blenlib
../blenloader
@@ -76,30 +75,12 @@ set(SRC
IMB_thumbs.h
intern/IMB_allocimbuf.h
intern/IMB_anim.h
+ intern/IMB_colormanagement_intern.h
intern/IMB_filetype.h
intern/IMB_filter.h
intern/IMB_indexer.h
intern/IMB_metadata.h
- intern/cineon/cin_debug_stuff.h
- intern/cineon/cineonfile.h
- intern/cineon/cineonlib.h
- intern/cineon/dpxfile.h
- intern/cineon/dpxlib.h
- intern/cineon/logImageCore.h
- intern/cineon/logImageLib.h
- intern/cineon/logmemfile.h
- intern/dds/BlockDXT.h
- intern/dds/Color.h
- intern/dds/ColorBlock.h
- intern/dds/Common.h
- intern/dds/DirectDrawSurface.h
- intern/dds/Image.h
- intern/dds/PixelFormat.h
- intern/dds/Stream.h
- intern/dds/dds_api.h
intern/imbuf.h
- intern/openexr/openexr_api.h
- intern/openexr/openexr_multi.h
# orphan include
../../../intern/ffmpeg/ffmpeg_compat.h
@@ -142,6 +123,13 @@ if(WITH_IMAGE_REDCODE)
add_definitions(-DWITH_REDCODE)
endif()
+if(WITH_CODEC_AVI)
+ list(APPEND INC
+ ../avi
+ )
+ add_definitions(-DWITH_AVI)
+endif()
+
if(WITH_CODEC_QUICKTIME)
list(APPEND INC
../quicktime
diff --git a/source/blender/imbuf/IMB_colormanagement.h b/source/blender/imbuf/IMB_colormanagement.h
index d09007985b0..0653956e113 100644
--- a/source/blender/imbuf/IMB_colormanagement.h
+++ b/source/blender/imbuf/IMB_colormanagement.h
@@ -45,15 +45,11 @@ struct rcti;
struct PartialBufferUpdateContext;
struct wmWindow;
struct Scene;
+struct ImageFormatData;
struct ColorSpace;
struct ColorManagedDisplay;
-/* ** Initialization / De-initialization ** */
-
-void IMB_colormanagement_init(void);
-void IMB_colormanagement_exit(void);
-
/* ** Generic functions ** */
void IMB_colormanagement_check_file_config(struct Main *bmain);
@@ -62,6 +58,9 @@ void IMB_colormanagement_validate_settings(struct ColorManagedDisplaySettings *d
struct ColorManagedViewSettings *view_settings);
const char *IMB_colormanagement_role_colorspace_name_get(int role);
+void IMB_colormanagement_check_is_data(struct ImBuf *ibuf, const char *name);
+void IMB_colormanagement_assign_float_colorspace(struct ImBuf *ibuf, const char *name);
+void IMB_colormanagement_assign_rect_colorspace(struct ImBuf *ibuf, const char *name);
/* ** Color space transformation functions ** */
void IMB_colormanagement_transform(float *buffer, int width, int height, int channels,
@@ -84,20 +83,20 @@ void IMB_colormanagement_pixel_to_display_space_v4(float result[4], const float
void IMB_colormanagement_pixel_to_display_space_v3(float result[3], const float pixel[3], const struct ColorManagedViewSettings *view_settings,
const struct ColorManagedDisplaySettings *display_settings);
-void IMB_colormanagement_imbuf_assign_float_space(struct ImBuf *ibuf, struct ColorManagedColorspaceSettings *colorspace_settings);
-
void IMB_colormanagement_imbuf_make_display_space(struct ImBuf *ibuf, const struct ColorManagedViewSettings *view_settings,
const struct ColorManagedDisplaySettings *display_settings);
+struct ImBuf *IMB_colormanagement_imbuf_for_write(struct ImBuf *ibuf, int save_as_render, int allocate_result,
+ const struct ColorManagedViewSettings *view_settings,
+ const struct ColorManagedDisplaySettings *display_settings,
+ struct ImageFormatData *image_format_data);
+
/* ** Public display buffers interfaces ** */
unsigned char *IMB_display_buffer_acquire(struct ImBuf *ibuf, const struct ColorManagedViewSettings *view_settings,
const struct ColorManagedDisplaySettings *display_settings, void **cache_handle);
unsigned char *IMB_display_buffer_acquire_ctx(const struct bContext *C, struct ImBuf *ibuf, void **cache_handle);
-void IMB_display_buffer_to_imbuf_rect(struct ImBuf *ibuf, const struct ColorManagedViewSettings *view_settings,
- const struct ColorManagedDisplaySettings *display_settings);
-
void IMB_display_buffer_transform_apply(unsigned char *display_buffer, float *linear_buffer, int width, int height,
int channels, const struct ColorManagedViewSettings *view_settings,
const struct ColorManagedDisplaySettings *display_settings, int predivide);
@@ -109,6 +108,7 @@ int IMB_colormanagement_display_get_named_index(const char *name);
const char *IMB_colormanagement_display_get_indexed_name(int index);
const char *IMB_colormanagement_display_get_default_name(void);
struct ColorManagedDisplay *IMB_colormanagement_display_get_named(const char *name);
+const char *IMB_colormanagement_display_get_none_name(void);
/* ** View funcrions ** */
int IMB_colormanagement_view_get_named_index(const char *name);
@@ -130,7 +130,8 @@ void IMB_colormanagement_colorspace_items_add(struct EnumPropertyItem **items, i
void IMB_partial_display_buffer_update(struct ImBuf *ibuf, const float *linear_buffer, const unsigned char *buffer_byte,
int stride, int offset_x, int offset_y, const struct ColorManagedViewSettings *view_settings,
const struct ColorManagedDisplaySettings *display_settings,
- int xmin, int ymin, int xmax, int ymax);
+ int xmin, int ymin, int xmax, int ymax,
+ int update_orig_byte_buffer);
/* ** Pixel processor functions ** */
struct ColormanageProcessor *IMB_colormanagement_display_processor_new(const struct ColorManagedViewSettings *view_settings,
diff --git a/source/blender/imbuf/IMB_imbuf.h b/source/blender/imbuf/IMB_imbuf.h
index 1503b9f6f67..d0ac71a7131 100644
--- a/source/blender/imbuf/IMB_imbuf.h
+++ b/source/blender/imbuf/IMB_imbuf.h
@@ -103,7 +103,7 @@ struct ImBuf *IMB_ibImageFromMemory(unsigned char *mem, size_t size, int flags,
*
* \attention Defined in readimage.c
*/
-struct ImBuf *IMB_testiffname(const char *filepath, int flags, char colorspace[IM_MAX_SPACE]);
+struct ImBuf *IMB_testiffname(const char *filepath, int flags);
/**
*
@@ -371,7 +371,7 @@ void IMB_interlace(struct ImBuf *ibuf);
void IMB_rect_from_float(struct ImBuf *ibuf);
/* Create char buffer for part of the image, color corrected if necessary,
* Changed part will be stored in buffer. This is expected to be used for texture painting updates */
-void IMB_partial_rect_from_float(struct ImBuf *ibuf, float *buffer, int x, int y, int w, int h);
+void IMB_partial_rect_from_float(struct ImBuf *ibuf, float *buffer, int x, int y, int w, int h, int is_data);
void IMB_float_from_rect(struct ImBuf *ibuf);
void IMB_float_from_rect_simple(struct ImBuf *ibuf); /* no profile conversion */
/* note, check that the conversion exists, only some are supported */
@@ -410,10 +410,10 @@ void bicubic_interpolation(struct ImBuf *in, struct ImBuf *out, float u, float v
void neareast_interpolation(struct ImBuf *in, struct ImBuf *out, float u, float v, int xout, int yout);
void bilinear_interpolation(struct ImBuf *in, struct ImBuf *out, float u, float v, int xout, int yout);
-void bicubic_interpolation_color(struct ImBuf *in, unsigned char *col, float *col_float, float u, float v);
-void neareast_interpolation_color(struct ImBuf *in, unsigned char *col, float *col_float, float u, float v);
-void bilinear_interpolation_color(struct ImBuf *in, unsigned char *col, float *col_float, float u, float v);
-void bilinear_interpolation_color_wrap(struct ImBuf *in, unsigned char *col, float *col_float, float u, float v);
+void bicubic_interpolation_color(struct ImBuf *in, unsigned char col[4], float col_float[4], float u, float v);
+void neareast_interpolation_color(struct ImBuf *in, unsigned char col[4], float col_float[4], float u, float v);
+void bilinear_interpolation_color(struct ImBuf *in, unsigned char col[4], float col_float[4], float u, float v);
+void bilinear_interpolation_color_wrap(struct ImBuf *in, unsigned char col[4], float col_float[4], float u, float v);
/**
*
diff --git a/source/blender/imbuf/IMB_imbuf_types.h b/source/blender/imbuf/IMB_imbuf_types.h
index 93e213dc486..28e62d496b2 100644
--- a/source/blender/imbuf/IMB_imbuf_types.h
+++ b/source/blender/imbuf/IMB_imbuf_types.h
@@ -93,7 +93,7 @@ typedef struct ImBuf {
/* tiled pixel storage */
int tilex, tiley;
int xtiles, ytiles;
- unsigned int **tiles;
+ unsigned int **tiles;
/* zbuffer */
int *zbuf; /* z buffer data, original zbuffer */
@@ -131,6 +131,7 @@ typedef struct ImBuf {
struct ColorSpace *float_colorspace; /* color space of float buffer, used by sequencer only */
unsigned int *display_buffer_flags; /* array of per-display display buffers dirty flags */
struct ColormanageCache *colormanage_cache; /* cache used by color management */
+ int colormanage_flag;
/* information for compressed textures */
struct DDSData dds_data;
@@ -199,6 +200,10 @@ typedef struct ImBuf {
#ifdef WITH_CINEON
#define CINEON (1 << 21)
#define DPX (1 << 20)
+#define CINEON_LOG (1 << 8)
+#define CINEON_16BIT (1 << 7)
+#define CINEON_12BIT (1 << 6)
+#define CINEON_10BIT (1 << 5)
#endif
#ifdef WITH_DDS
@@ -241,7 +246,7 @@ typedef struct ImBuf {
((unsigned long)(unsigned char)(ch1) << 8) | \
((unsigned long)(unsigned char)(ch2) << 16) | \
((unsigned long)(unsigned char)(ch3) << 24))
-#endif //MAKEFOURCC
+#endif /* MAKEFOURCC */
/*
* FOURCC codes for DX compressed-texture pixel formats
@@ -254,10 +259,14 @@ typedef struct ImBuf {
#define FOURCC_DXT4 (MAKEFOURCC('D','X','T','4'))
#define FOURCC_DXT5 (MAKEFOURCC('D','X','T','5'))
-#endif // DDS
+#endif /* DDS */
extern const char *imb_ext_image[];
extern const char *imb_ext_image_qt[];
extern const char *imb_ext_movie[];
extern const char *imb_ext_audio[];
+enum {
+ IMB_COLORMANAGE_IS_DATA = (1 << 0)
+};
+
#endif
diff --git a/source/blender/imbuf/intern/IMB_anim.h b/source/blender/imbuf/intern/IMB_anim.h
index d5cc4929aed..ed349e8f7eb 100644
--- a/source/blender/imbuf/intern/IMB_anim.h
+++ b/source/blender/imbuf/intern/IMB_anim.h
@@ -62,7 +62,9 @@
#include "imbuf.h"
-#include "AVI_avi.h"
+#ifdef WITH_AVI
+# include "AVI_avi.h"
+#endif
#ifdef WITH_QUICKTIME
# if defined(_WIN32) || defined(__APPLE__)
diff --git a/source/blender/imbuf/intern/IMB_colormanagement_intern.h b/source/blender/imbuf/intern/IMB_colormanagement_intern.h
index 0c002b78848..ba9e20ac411 100644
--- a/source/blender/imbuf/intern/IMB_colormanagement_intern.h
+++ b/source/blender/imbuf/intern/IMB_colormanagement_intern.h
@@ -35,7 +35,7 @@
#define BCM_CONFIG_FILE "config.ocio"
-struct ConstProcessorRcPtr;
+struct OCIO_ConstProcessorRcPtr;
struct ImBuf;
typedef struct ColorSpace {
@@ -44,10 +44,11 @@ typedef struct ColorSpace {
char name[64];
char description[64];
- struct ConstProcessorRcPtr *to_scene_linear;
- struct ConstProcessorRcPtr *from_scene_linear;
+ struct OCIO_ConstProcessorRcPtr *to_scene_linear;
+ struct OCIO_ConstProcessorRcPtr *from_scene_linear;
int is_invertible;
+ int is_data;
} ColorSpace;
typedef struct ColorManagedDisplay {
@@ -56,8 +57,8 @@ typedef struct ColorManagedDisplay {
char name[64];
ListBase views;
- struct ConstProcessorRcPtr *to_scene_linear;
- struct ConstProcessorRcPtr *from_scene_linear;
+ struct OCIO_ConstProcessorRcPtr *to_scene_linear;
+ struct OCIO_ConstProcessorRcPtr *from_scene_linear;
} ColorManagedDisplay;
typedef struct ColorManagedView {
@@ -66,8 +67,14 @@ typedef struct ColorManagedView {
char name[64];
} ColorManagedView;
+/* ** Initialization / De-initialization ** */
+
+void colormanagement_init(void);
+void colormanagement_exit(void);
+
void colormanage_cache_free(struct ImBuf *ibuf);
+const char *colormanage_display_get_default_name(void);
struct ColorManagedDisplay *colormanage_display_get_default(void);
struct ColorManagedDisplay *colormanage_display_add(const char *name);
struct ColorManagedDisplay *colormanage_display_get_named(const char *name);
@@ -79,7 +86,7 @@ struct ColorManagedView *colormanage_view_add(const char *name);
struct ColorManagedView *colormanage_view_get_indexed(int index);
struct ColorManagedView *colormanage_view_get_named(const char *name);
-struct ColorSpace *colormanage_colorspace_add(const char *name, const char *description, int is_invertible);
+struct ColorSpace *colormanage_colorspace_add(const char *name, const char *description, int is_invertible, int is_data);
struct ColorSpace *colormanage_colorspace_get_named(const char *name);
struct ColorSpace *colormanage_colorspace_get_roled(int role);
struct ColorSpace *colormanage_colorspace_get_indexed(int index);
diff --git a/source/blender/imbuf/intern/IMB_filetype.h b/source/blender/imbuf/intern/IMB_filetype.h
index 56a03121409..68ad4808c80 100644
--- a/source/blender/imbuf/intern/IMB_filetype.h
+++ b/source/blender/imbuf/intern/IMB_filetype.h
@@ -97,13 +97,13 @@ struct ImBuf *imb_cocoaLoadImage(unsigned char *mem, size_t size, int flags, cha
short imb_cocoaSaveImage(struct ImBuf *ibuf, const char *name, int flags);
/* cineon */
-int imb_savecineon(struct ImBuf *buf, const char *name, int flags);
-struct ImBuf *imb_loadcineon(unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE]);
+int imb_save_cineon(struct ImBuf *buf, const char *name, int flags);
+struct ImBuf *imb_load_cineon(unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE]);
int imb_is_cineon(unsigned char *buf);
/* dpx */
int imb_save_dpx(struct ImBuf *buf, const char *name, int flags);
-struct ImBuf *imb_loaddpx(unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE]);
+struct ImBuf *imb_load_dpx(unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE]);
int imb_is_dpx(unsigned char *buf);
/* hdr */
diff --git a/source/blender/imbuf/intern/IMB_indexer.h b/source/blender/imbuf/intern/IMB_indexer.h
index 18816924a9b..9c95531e90d 100644
--- a/source/blender/imbuf/intern/IMB_indexer.h
+++ b/source/blender/imbuf/intern/IMB_indexer.h
@@ -72,7 +72,7 @@ typedef struct anim_index_builder {
char name[FILE_MAX];
char temp_name[FILE_MAX];
- void * private_data;
+ void *private_data;
void (*delete_priv_data)(struct anim_index_builder * idx);
void (*proc_frame)(struct anim_index_builder * idx,
diff --git a/source/blender/imbuf/intern/allocimbuf.c b/source/blender/imbuf/intern/allocimbuf.c
index 69048274104..1b3a6d4a4cd 100644
--- a/source/blender/imbuf/intern/allocimbuf.c
+++ b/source/blender/imbuf/intern/allocimbuf.c
@@ -357,7 +357,7 @@ ImBuf *IMB_allocImBuf(unsigned int x, unsigned int y, uchar planes, unsigned int
ibuf->planes = planes;
ibuf->ftype = TGA;
ibuf->channels = 4; /* float option, is set to other values when buffers get assigned */
- ibuf->ppm[0] = ibuf->ppm[1] = IMB_DPI_DEFAULT / 0.0254; /* IMB_DPI_DEFAULT -> pixels-per-meter */
+ ibuf->ppm[0] = ibuf->ppm[1] = IMB_DPI_DEFAULT / 0.0254f; /* IMB_DPI_DEFAULT -> pixels-per-meter */
if (flags & IB_rect) {
if (imb_addrectImBuf(ibuf) == FALSE) {
diff --git a/source/blender/imbuf/intern/anim_movie.c b/source/blender/imbuf/intern/anim_movie.c
index 394f5169046..5b64416c309 100644
--- a/source/blender/imbuf/intern/anim_movie.c
+++ b/source/blender/imbuf/intern/anim_movie.c
@@ -78,7 +78,9 @@
#include "imbuf.h"
-#include "AVI_avi.h"
+#ifdef WITH_AVI
+# include "AVI_avi.h"
+#endif
#ifdef WITH_QUICKTIME
#if defined(_WIN32) || defined(__APPLE__)
@@ -185,6 +187,7 @@ static void an_stringenc(char *string, const char *head, const char *tail, unsig
BLI_stringenc(string, head, tail, numlen, pic);
}
+#ifdef WITH_AVI
static void free_anim_avi(struct anim *anim)
{
#if defined(_WIN32) && !defined(FREE_WINDOWS)
@@ -219,6 +222,7 @@ static void free_anim_avi(struct anim *anim)
anim->duration = 0;
}
+#endif /* WITH_AVI */
#ifdef WITH_FFMPEG
static void free_anim_ffmpeg(struct anim *anim);
@@ -235,7 +239,10 @@ void IMB_free_anim(struct anim *anim)
}
free_anim_movie(anim);
+
+#ifdef WITH_AVI
free_anim_avi(anim);
+#endif
#ifdef WITH_QUICKTIME
free_anim_quicktime(anim);
@@ -287,7 +294,7 @@ struct anim *IMB_open_anim(const char *name, int ib_flags, int streamindex, char
return(anim);
}
-
+#ifdef WITH_AVI
static int startavi(struct anim *anim)
{
@@ -397,7 +404,9 @@ static int startavi(struct anim *anim)
return 0;
}
+#endif /* WITH_AVI */
+#ifdef WITH_AVI
static ImBuf *avi_fetchibuf(struct anim *anim, int position)
{
ImBuf *ibuf = NULL;
@@ -447,6 +456,7 @@ static ImBuf *avi_fetchibuf(struct anim *anim, int position)
return ibuf;
}
+#endif /* WITH_AVI */
#ifdef WITH_FFMPEG
@@ -1206,7 +1216,11 @@ static ImBuf *anim_getnew(struct anim *anim)
if (anim == NULL) return(NULL);
free_anim_movie(anim);
+
+#ifdef WITH_AVI
free_anim_avi(anim);
+#endif
+
#ifdef WITH_QUICKTIME
free_anim_quicktime(anim);
#endif
@@ -1219,7 +1233,7 @@ static ImBuf *anim_getnew(struct anim *anim)
if (anim->curtype != 0) return (NULL);
- anim->curtype = imb_get_anim_type(anim->name);
+ anim->curtype = imb_get_anim_type(anim->name);
switch (anim->curtype) {
case ANIM_SEQUENCE:
@@ -1233,6 +1247,7 @@ static ImBuf *anim_getnew(struct anim *anim)
if (startmovie(anim)) return (NULL);
ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0); /* fake */
break;
+#ifdef WITH_AVI
case ANIM_AVI:
if (startavi(anim)) {
printf("couldnt start avi\n");
@@ -1240,6 +1255,7 @@ static ImBuf *anim_getnew(struct anim *anim)
}
ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0);
break;
+#endif
#ifdef WITH_QUICKTIME
case ANIM_QTIME:
if (startquicktime(anim)) return (0);
@@ -1331,11 +1347,13 @@ struct ImBuf *IMB_anim_absolute(struct anim *anim, int position,
IMB_convert_rgba_to_abgr(ibuf);
}
break;
+#ifdef WITH_AVI
case ANIM_AVI:
ibuf = avi_fetchibuf(anim, position);
if (ibuf)
anim->curposition = position;
break;
+#endif
#ifdef WITH_QUICKTIME
case ANIM_QTIME:
ibuf = qtime_fetchibuf(anim, position);
diff --git a/source/blender/imbuf/intern/bmp.c b/source/blender/imbuf/intern/bmp.c
index df12f0b703e..32733668052 100644
--- a/source/blender/imbuf/intern/bmp.c
+++ b/source/blender/imbuf/intern/bmp.c
@@ -184,7 +184,7 @@ struct ImBuf *imb_bmp_decode(unsigned char *mem, size_t size, int flags, char co
rect += 4; bmp += 3;
}
/* for 24-bit images, rows are padded to multiples of 4 */
- bmp += x % 4;
+ bmp += x % 4;
}
}
else if (depth == 32) {
diff --git a/source/blender/imbuf/intern/cineon/CMakeLists.txt b/source/blender/imbuf/intern/cineon/CMakeLists.txt
index fdf4f5409a5..b94cfd22058 100644
--- a/source/blender/imbuf/intern/cineon/CMakeLists.txt
+++ b/source/blender/imbuf/intern/cineon/CMakeLists.txt
@@ -39,12 +39,24 @@ set(INC_SYS
)
set(SRC
+ cin_debug_stuff.h
+ cineonfile.h
+ cineonlib.h
+ dpxfile.h
+ dpxlib.h
+ logImageCore.h
+ logImageLib.h
+ logmemfile.h
+
cineon_dpx.c
cineonlib.c
dpxlib.c
logImageCore.c
- logImageLib.c
logmemfile.c
)
+if(WITH_IMAGE_CINEON)
+ add_definitions(-DWITH_CINEON)
+endif()
+
blender_add_lib(bf_imbuf_cineon "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/imbuf/intern/cineon/SConscript b/source/blender/imbuf/intern/cineon/SConscript
index e1afb5ebd2d..a07334632d7 100644
--- a/source/blender/imbuf/intern/cineon/SConscript
+++ b/source/blender/imbuf/intern/cineon/SConscript
@@ -15,4 +15,7 @@ incs = ['.',
defs = []
+if env['WITH_BF_CINEON']:
+ defs.append('WITH_CINEON')
+
env.BlenderLib ('bf_imbuf_cineon', source_files, incs, defs, libtype=['core','player'], priority = [220,175])
diff --git a/source/blender/imbuf/intern/cineon/cin_debug_stuff.h b/source/blender/imbuf/intern/cineon/cin_debug_stuff.h
index a97499fb1ae..e69de29bb2d 100644
--- a/source/blender/imbuf/intern/cineon/cin_debug_stuff.h
+++ b/source/blender/imbuf/intern/cineon/cin_debug_stuff.h
@@ -1,4 +0,0 @@
-/** \file blender/imbuf/intern/cineon/cin_debug_stuff.h
- * \ingroup imbcineon
- */
-#define d_printf printf
diff --git a/source/blender/imbuf/intern/cineon/cineon_dpx.c b/source/blender/imbuf/intern/cineon/cineon_dpx.c
index 7705af13b1e..d20c6dec9d3 100644
--- a/source/blender/imbuf/intern/cineon/cineon_dpx.c
+++ b/source/blender/imbuf/intern/cineon/cineon_dpx.c
@@ -4,11 +4,11 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -20,25 +20,24 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): none yet.
+ * Contributor(s): Julien Enche.
*
* ***** END GPL LICENSE BLOCK *****
* cineon.c
- * contributors: joeedh
+ * contributors: joeedh, Julien Enche
* I hearby donate this code and all rights to the Blender Foundation.
+ * $Id$
*/
/** \file blender/imbuf/intern/cineon/cineon_dpx.c
* \ingroup imbcineon
*/
-
-#include <stdio.h>
-#include <string.h> /*for memcpy*/
-#include "logImageLib.h"
-#include "cineonlib.h"
-#include "dpxlib.h"
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+#include "logImageCore.h"
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -51,167 +50,142 @@
#include "MEM_guardedalloc.h"
-#if 0
-static void cineon_conversion_parameters(LogImageByteConversionParameters *params)
-{
-// params->blackPoint = scene?scene->r.cineonblack:95;
-// params->whitePoint = scene?scene->r.cineonwhite:685;
-// params->gamma = scene?scene->r.cineongamma:1.7f;
-// params->doLogarithm = scene?scene->r.subimtype & R_CINEON_LOG:0;
-
- params->blackPoint = 95;
- params->whitePoint = 685;
- params->gamma = 1.0f;
- params->doLogarithm = 0;
-}
-#endif
-
-static ImBuf *imb_load_dpx_cineon(unsigned char *mem, int use_cineon, int size, int flags, char colorspace[IM_MAX_SPACE])
+static struct ImBuf *imb_load_dpx_cineon(unsigned char *mem, size_t size, int use_cineon, int flags,
+ char colorspace[IM_MAX_SPACE])
{
ImBuf *ibuf;
LogImageFile *image;
- int x, y;
- unsigned short *row, *upix;
int width, height, depth;
- float *frow;
colorspace_set_default_role(colorspace, IM_MAX_SPACE, COLOR_ROLE_DEFAULT_FLOAT);
- logImageSetVerbose((G.debug & G_DEBUG) ? 1:0);
-
- image = logImageOpenFromMem(mem, size, use_cineon);
-
- if (!image) {
- printf("no image!\n");
- return NULL;
+ logImageSetVerbose((G.f & G_DEBUG) ? 1 : 0);
+
+ image = logImageOpenFromMemory(mem, size);
+
+ if (image == 0) {
+ printf("DPX/Cineon: error opening image.\n");
+ return 0;
}
-
+
logImageGetSize(image, &width, &height, &depth);
-
- if (depth != 3) { /*need to do grayscale loading eventually.*/
+
+ if (width == 0 || height == 0) {
logImageClose(image);
- return NULL;
+ return 0;
}
-
- if (width == 0 && height == 0) {
+
+ ibuf = IMB_allocImBuf(width, height, 32, IB_rectfloat | flags);
+ if (ibuf == 0) {
logImageClose(image);
- return NULL;
+ return 0;
}
-
- ibuf = IMB_allocImBuf(width, height, 32, IB_rectfloat | flags);
- row = MEM_mallocN(sizeof(unsigned short)*width*depth, "row in cineon_dpx.c");
- frow = ibuf->rect_float+width*height*4;
-
- for (y = 0; y < height; y++) {
- logImageGetRowBytes(image, row, y); /* checks image->params.doLogarithm and convert */
- upix = row;
- frow -= width*4;
-
- for (x=0; x<width; x++) {
- *(frow++) = ((float)*(upix++)) / 65535.0f;
- *(frow++) = ((float)*(upix++)) / 65535.0f;
- *(frow++) = ((float)*(upix++)) / 65535.0f;
- *(frow++) = 1.0f;
- }
- frow -= width*4;
+ if (logImageGetDataRGBA(image, ibuf->rect_float, 1) != 0) {
+ /* Conversion not possible (probably because the format is unsupported) */
+ logImageClose(image);
+ MEM_freeN(ibuf);
+ return 0;
}
- MEM_freeN(row);
logImageClose(image);
-
- if (flags & IB_rect) {
+ ibuf->ftype = use_cineon ? CINEON : DPX;
+ IMB_flipy(ibuf);
+
+ if (flags & IB_rect)
IMB_rect_from_float(ibuf);
- }
+
return ibuf;
}
static int imb_save_dpx_cineon(ImBuf *ibuf, const char *filename, int use_cineon, int flags)
{
- LogImageByteConversionParameters conversion;
- const int width= ibuf->x;
- const int height= ibuf->y;
- const int depth= 3;
- LogImageFile* logImage;
- unsigned short* line, *pixel;
- int i, j;
- float *fline;
+ LogImageFile *logImage;
float *fbuf;
- int is_alloc= 0;
+ float *fbuf_ptr;
+ unsigned char *rect_ptr;
+ int x, y, depth, bitspersample, rvalue;
+
+ if (flags & IB_mem) {
+ printf("DPX/Cineon: saving in memory is not supported.\n");
+ return 0;
+ }
- (void)flags; /* unused */
+ logImageSetVerbose((G.f & G_DEBUG) ? 1 : 0);
- // cineon_conversion_parameters(&conversion);
- logImageGetByteConversionDefaults(&conversion);
+ depth = (ibuf->planes + 7) >> 3;
+ if (depth > 4 || depth < 3) {
+ printf("DPX/Cineon: unsupported depth: %d for file: '%s'\n", depth, filename);
+ return 0;
+ }
- /*
- * Get the drawable for the current image...
- */
+ if (ibuf->ftype & CINEON_10BIT)
+ bitspersample = 10;
+ else if (ibuf->ftype & CINEON_12BIT)
+ bitspersample = 12;
+ else if (ibuf->ftype & CINEON_16BIT)
+ bitspersample = 16;
+ else
+ bitspersample = 8;
- fbuf= IMB_float_profile_ensure(ibuf, conversion.doLogarithm ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE, &is_alloc);
+ logImage = logImageCreate(filename, use_cineon, ibuf->x, ibuf->y, bitspersample, (depth == 4),
+ (ibuf->ftype & CINEON_LOG), -1, -1, -1, "Blender");
- if (fbuf == NULL) { /* in the unlikely event that converting to a float buffer fails */
+ if (logImage == 0) {
+ printf("DPX/Cineon: error creating file.\n");
return 0;
}
-
- logImageSetVerbose((G.debug & G_DEBUG) ? 1:0);
- logImage = logImageCreate(filename, use_cineon, width, height, depth);
- if (!logImage) return 0;
-
- if (logImageSetByteConversion(logImage, &conversion)==0) {
- printf("error setting args\n");
+ if (ibuf->rect_float != 0 && bitspersample != 8) {
+ /* don't use the float buffer to save 8 bpp picture to prevent color banding
+ (there's no dithering algorithm behing the logImageSetDataRGBA function) */
+ IMB_flipy(ibuf);
+ rvalue = (logImageSetDataRGBA(logImage, ibuf->rect_float, 1) == 0);
+ IMB_flipy(ibuf);
}
-
- line = MEM_mallocN(sizeof(unsigned short)*depth*width, "line");
-
- /*note that image is flipped when sent to logImageSetRowBytes (see last passed parameter).*/
- for (j = 0; j < height; ++j) {
- fline = &fbuf[width*j*4];
- for (i=0; i<width; i++) {
- float *fpix, fpix2[3];
- /*we have to convert to cinepaint's 16-bit-per-channel here*/
- pixel = &line[i*depth];
- fpix = &fline[i*4];
- memcpy(fpix2, fpix, sizeof(float)*3);
-
- if (fpix2[0]>=1.0f) fpix2[0] = 1.0f; else if (fpix2[0]<0.0f) fpix2[0]= 0.0f;
- if (fpix2[1]>=1.0f) fpix2[1] = 1.0f; else if (fpix2[1]<0.0f) fpix2[1]= 0.0f;
- if (fpix2[2]>=1.0f) fpix2[2] = 1.0f; else if (fpix2[2]<0.0f) fpix2[2]= 0.0f;
-
- pixel[0] = (unsigned short)(fpix2[0] * 65535.0f); /*float-float math is faster*/
- pixel[1] = (unsigned short)(fpix2[1] * 65535.0f);
- pixel[2] = (unsigned short)(fpix2[2] * 65535.0f);
+ else {
+ if (ibuf->rect == 0)
+ IMB_rect_from_float(ibuf);
+
+ fbuf = (float *)MEM_mallocN(ibuf->x * ibuf->y * 4 * sizeof(float), "fbuf in imb_save_dpx_cineon");
+ if (fbuf == 0) {
+ printf("DPX/Cineon: error allocating memory.\n");
+ logImageClose(logImage);
+ return 0;
}
- logImageSetRowBytes(logImage, (const unsigned short*)line, height-1-j);
- }
- logImageClose(logImage);
-
- MEM_freeN(line);
-
- if (is_alloc) {
+ for (y = 0; y < ibuf->y; y++) {
+ for (x = 0; x < ibuf->x; x++) {
+ fbuf_ptr = fbuf + 4 * ((ibuf->y - y - 1) * ibuf->x + x);
+ rect_ptr = (unsigned char *)ibuf->rect + 4 * (y * ibuf->x + x);
+ fbuf_ptr[0] = (float)rect_ptr[0] / 255.0f;
+ fbuf_ptr[1] = (float)rect_ptr[1] / 255.0f;
+ fbuf_ptr[2] = (float)rect_ptr[2] / 255.0f;
+ fbuf_ptr[3] = (depth == 4) ? ((float)rect_ptr[3] / 255.0f) : 1.0f;
+ }
+ }
+ rvalue = (logImageSetDataRGBA(logImage, fbuf, 0) == 0);
MEM_freeN(fbuf);
}
-
- return 1;
+
+ logImageClose(logImage);
+ return rvalue;
}
-int imb_savecineon(struct ImBuf *buf, const char *myfile, int flags)
+int imb_save_cineon(struct ImBuf *buf, const char *myfile, int flags)
{
return imb_save_dpx_cineon(buf, myfile, 1, flags);
}
-
int imb_is_cineon(unsigned char *buf)
{
- return cineonIsMemFileCineon(buf);
+ return logImageIsCineon(buf);
}
-ImBuf *imb_loadcineon(unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE])
+ImBuf *imb_load_cineon(unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE])
{
if (imb_is_cineon(mem))
- return imb_load_dpx_cineon(mem, 1, size, flags, colorspace);
- return NULL;
+ return imb_load_dpx_cineon(mem, size, 1, flags, colorspace);
+ return 0;
}
int imb_save_dpx(struct ImBuf *buf, const char *myfile, int flags)
@@ -221,12 +195,12 @@ int imb_save_dpx(struct ImBuf *buf, const char *myfile, int flags)
int imb_is_dpx(unsigned char *buf)
{
- return dpxIsMemFileCineon(buf);
+ return logImageIsDpx(buf);
}
-ImBuf *imb_loaddpx(unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE])
+ImBuf *imb_load_dpx(unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE])
{
if (imb_is_dpx(mem))
- return imb_load_dpx_cineon(mem, 0, size, flags, colorspace);
- return NULL;
+ return imb_load_dpx_cineon(mem, size, 0, flags, colorspace);
+ return 0;
}
diff --git a/source/blender/imbuf/intern/cineon/cineonfile.h b/source/blender/imbuf/intern/cineon/cineonfile.h
index e681153aa6e..e69de29bb2d 100644
--- a/source/blender/imbuf/intern/cineon/cineonfile.h
+++ b/source/blender/imbuf/intern/cineon/cineonfile.h
@@ -1,134 +0,0 @@
-/*
- * Cineon image file format library definitions.
- * Cineon file format structures.
- *
- * This header file contains private details.
- * User code should generally use cineonlib.h only.
- *
- * Copyright 1999,2000,2001 David Hodson <hodsond@acm.org>
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef __CINEONFILE_H__
-#define __CINEONFILE_H__
-
-/** \file blender/imbuf/intern/cineon/cineonfile.h
- * \ingroup imbcineon
- */
-
-#include "logImageCore.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct {
- U32 magic_num; /* magic number */
- U32 image_offset; /* offset to image data in bytes */
- U32 gen_hdr_size; /* generic header length in bytes */
- U32 ind_hdr_size; /* industry header length in bytes */
- U32 user_data_size; /* user-defined data length in bytes */
- U32 file_size; /* file size in bytes */
- ASCII vers[8]; /* which header format version is being used (v4.5) */
- ASCII file_name[100]; /* image file name */
- ASCII create_date[12]; /* file creation date */
- ASCII create_time[12]; /* file creation time */
- ASCII Reserved[36]; /* reserved field TBD (need to pad) */
-} CineonFileInformation;
-
-typedef struct {
- U8 designator1;
- U8 designator2;
- U8 bits_per_pixel;
- U8 filler;
- U32 pixels_per_line;
- U32 lines_per_image;
- U32 ref_low_data; /* reference low data code value */
- R32 ref_low_quantity; /* reference low quantity represented */
- U32 ref_high_data; /* reference high data code value */
- R32 ref_high_quantity;/* reference high quantity represented */
-} CineonChannelInformation;
-
-typedef struct {
- U8 orientation; /* image orientation */
- U8 channels_per_image;
- U16 filler;
- CineonChannelInformation channel[8];
- R32 white_point_x;
- R32 white_point_y;
- R32 red_primary_x;
- R32 red_primary_y;
- R32 green_primary_x;
- R32 green_primary_y;
- R32 blue_primary_x;
- R32 blue_primary_y;
- ASCII label[200];
- ASCII reserved[28];
-} CineonImageInformation;
-
-typedef struct {
- U8 interleave;
- U8 packing;
- U8 signage;
- U8 sense;
- U32 line_padding;
- U32 channel_padding;
- ASCII reserved[20];
-} CineonFormatInformation;
-
-typedef struct {
- S32 x_offset;
- S32 y_offset;
- ASCII file_name[100];
- ASCII create_date[12]; /* file creation date */
- ASCII create_time[12]; /* file creation time */
- ASCII input_device[64];
- ASCII model_number[32];
- ASCII serial_number[32];
- R32 x_input_samples_per_mm;
- R32 y_input_samples_per_mm;
- R32 input_device_gamma;
- ASCII reserved[40];
-} CineonOriginationInformation;
-
-typedef struct {
- CineonFileInformation fileInfo;
- CineonImageInformation imageInfo;
- CineonFormatInformation formatInfo;
- CineonOriginationInformation originInfo;
-} CineonGenericHeader;
-
-typedef struct {
- U8 filmCode;
- U8 filmType;
- U8 perfOffset;
- U8 filler;
- U32 keycodePrefix;
- U32 keycodeCount;
- ASCII format[32];
- U32 framePosition; /* in sequence */
- R32 frameRate; /* frames per second */
- ASCII attribute[32];
- ASCII slate[200];
- ASCII reserved[740];
-} CineonMPISpecificInformation;
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __CINEONFILE_H__ */
diff --git a/source/blender/imbuf/intern/cineon/cineonlib.c b/source/blender/imbuf/intern/cineon/cineonlib.c
index a9001303679..9926d8c8562 100644
--- a/source/blender/imbuf/intern/cineon/cineonlib.c
+++ b/source/blender/imbuf/intern/cineon/cineonlib.c
@@ -1,21 +1,23 @@
/*
- * Cineon image file format library routines.
+ * Cineon image file format library routines.
*
- * Copyright 1999,2000,2001 David Hodson <hodsond@acm.org>
+ * Copyright 1999,2000,2001 David Hodson <hodsond@acm.org>
*
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Julien Enche.
*
*/
@@ -23,800 +25,355 @@
* \ingroup imbcineon
*/
+
#include "cineonlib.h"
-#include "cineonfile.h"
+#include "logmemfile.h"
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
-#include <time.h> /* strftime() */
+#include <time.h>
#include <sys/types.h>
-#ifdef WIN32
-#include <winsock.h>
-#else
-#include <netinet/in.h> /* htonl() */
-#endif
-#include <string.h> /* memset */
+#include <string.h>
-#include "BLI_utildefines.h"
#include "BLI_fileops.h"
+#include "BLI_math_base.h"
+#include "BLI_utildefines.h"
-#include "cin_debug_stuff.h"
-#include "logmemfile.h"
-
-static void
-fillCineonFileInfo(CineonFile* cineon, CineonFileInformation* fileInfo, const char* filename) {
-
- time_t fileClock;
- struct tm* fileTime;
-
- fileInfo->magic_num = htonl(CINEON_FILE_MAGIC);
- fileInfo->image_offset = htonl(cineon->imageOffset);
- fileInfo->gen_hdr_size = htonl(
- sizeof(CineonFileInformation) +
- sizeof(CineonImageInformation) +
- sizeof(CineonFormatInformation) +
- sizeof(CineonOriginationInformation));
- fileInfo->ind_hdr_size = 0;
- fileInfo->user_data_size = 0;
- fileInfo->file_size = htonl(cineon->imageOffset + cineon->height * cineon->lineBufferLength);
- strcpy(fileInfo->vers, "V4.5");
- strncpy(fileInfo->file_name, filename, 99);
- fileInfo->file_name[99] = 0;
-
- fileClock = time(0);
- fileTime = localtime(&fileClock);
- strftime(fileInfo->create_date, 12, "%Y:%m:%d", fileTime);
- /* Question: is %Z in strftime guaranteed to return 3 chars? */
- strftime(fileInfo->create_time, 12, "%H:%M:%S%Z", fileTime);
- fileInfo->create_time[11] = 0;
-}
-
-static void
-dumpCineonFileInfo(CineonFileInformation* fileInfo) {
- d_printf("\n--File Information--\n");
- d_printf("Magic: %8.8lX\n", (uintptr_t)ntohl(fileInfo->magic_num));
- d_printf("Image Offset %ld\n", (intptr_t)ntohl(fileInfo->image_offset));
- d_printf("Generic Header size %ld\n", (intptr_t)ntohl(fileInfo->gen_hdr_size));
- d_printf("Industry Header size %ld\n", (intptr_t)ntohl(fileInfo->ind_hdr_size));
- d_printf("User Data size %ld\n", (intptr_t)ntohl(fileInfo->user_data_size));
- d_printf("File size %ld\n", (intptr_t)ntohl(fileInfo->file_size));
- d_printf("Version \"%s\"\n", fileInfo->vers);
- d_printf("File name \"%s\"\n", fileInfo->file_name);
- d_printf("Creation date \"%s\"\n", fileInfo->create_date);
- d_printf("Creation time \"%s\"\n", fileInfo->create_time);
-}
-
-static void
-fillCineonChannelInfo(CineonFile* cineon, CineonChannelInformation* chan, int des) {
-
- chan->designator1 = 0;
- chan->designator2 = des;
- chan->bits_per_pixel = 10;
- chan->pixels_per_line = htonl(cineon->width);
- chan->lines_per_image = htonl(cineon->height);
- chan->ref_low_data = htonl(0);
- chan->ref_low_quantity = htonf(0.0);
- chan->ref_high_data = htonl(1023);
- chan->ref_high_quantity = htonf(2.046);
-}
-
-static void
-dumpCineonChannelInfo(CineonChannelInformation* chan) {
- d_printf(" Metric selector: %d", chan->designator1);
- switch (chan->designator1) {
- case 0: d_printf(" (Universal)\n"); break;
- default: d_printf(" (Vendor specific)\n"); break;
- }
- d_printf(" Metric: %d,", chan->designator2);
- switch (chan->designator2) {
- case 0: d_printf(" B&W (printing density?)\n"); break;
- case 1: d_printf(" Red printing density\n"); break;
- case 2: d_printf(" Green printing density\n"); break;
- case 3: d_printf(" Blue printing density\n"); break;
- case 4: d_printf(" Red CCIR XA/11\n"); break;
- case 5: d_printf(" Green CCIR XA/11\n"); break;
- case 6: d_printf(" Blue CCIR XA/11\n"); break;
- default: d_printf(" (unknown)\n"); break;
- }
- d_printf(" Bits per pixel %d\n", chan->bits_per_pixel);
- d_printf(" Pixels per line %ld\n", (intptr_t)ntohl(chan->pixels_per_line));
- d_printf(" Lines per image %ld\n", (intptr_t)ntohl(chan->lines_per_image));
- d_printf(" Ref low data %ld\n", (intptr_t)ntohl(chan->ref_low_data));
- d_printf(" Ref low quantity %f\n", ntohf(chan->ref_low_quantity));
- d_printf(" Ref high data %ld\n", (intptr_t)ntohl(chan->ref_high_data));
- d_printf(" Ref high quantity %f\n", ntohf(chan->ref_high_quantity));
-}
-
-static void
-fillCineonImageInfo(CineonFile* cineon, CineonImageInformation* imageInfo) {
-
- imageInfo->orientation = 0;
- imageInfo->channels_per_image = cineon->depth;
-
- if (cineon->depth == 1) {
- fillCineonChannelInfo(cineon, &imageInfo->channel[0], 0);
-
- }
- else if (cineon->depth == 3) {
- fillCineonChannelInfo(cineon, &imageInfo->channel[0], 1);
- fillCineonChannelInfo(cineon, &imageInfo->channel[1], 2);
- fillCineonChannelInfo(cineon, &imageInfo->channel[2], 3);
- }
-
- imageInfo->white_point_x = htonf(undefined());
- imageInfo->white_point_y = htonf(undefined());
- imageInfo->red_primary_x = htonf(undefined());
- imageInfo->red_primary_y = htonf(undefined());
- imageInfo->green_primary_x = htonf(undefined());
- imageInfo->green_primary_y = htonf(undefined());
- imageInfo->blue_primary_x = htonf(undefined());
- imageInfo->blue_primary_y = htonf(undefined());
-
- strcpy(imageInfo->label, "David's Cineon writer.");
-
-}
-
-static void
-dumpCineonImageInfo(CineonImageInformation* imageInfo) {
-
- int i;
- d_printf("\n--Image Information--\n");
- d_printf("Image orientation %d,", imageInfo->orientation);
- switch (imageInfo->orientation) {
- case 0: d_printf(" LRTB\n"); break;
- case 1: d_printf(" LRBT\n"); break;
- case 2: d_printf(" RLTB\n"); break;
- case 3: d_printf(" RLBT\n"); break;
- case 4: d_printf(" TBLR\n"); break;
- case 5: d_printf(" TBRL\n"); break;
- case 6: d_printf(" BTLR\n"); break;
- case 7: d_printf(" BTRL\n"); break;
- default: d_printf(" (unknown)\n"); break;
- }
- d_printf("Channels %d\n", imageInfo->channels_per_image);
- for (i = 0; i < imageInfo->channels_per_image; ++i) {
- d_printf(" --Channel %d--\n", i);
- dumpCineonChannelInfo(&imageInfo->channel[i]);
- }
-
- d_printf("White point x %f\n", ntohf(imageInfo->white_point_x));
- d_printf("White point y %f\n", ntohf(imageInfo->white_point_y));
- d_printf("Red primary x %f\n", ntohf(imageInfo->red_primary_x));
- d_printf("Red primary y %f\n", ntohf(imageInfo->red_primary_y));
- d_printf("Green primary x %f\n", ntohf(imageInfo->green_primary_x));
- d_printf("Green primary y %f\n", ntohf(imageInfo->green_primary_y));
- d_printf("Blue primary x %f\n", ntohf(imageInfo->blue_primary_x));
- d_printf("Blue primary y %f\n", ntohf(imageInfo->blue_primary_y));
- d_printf("Label \"%s\"\n", imageInfo->label);
-}
-
-static void
-fillCineonFormatInfo(CineonFile* cineon, CineonFormatInformation* formatInfo) {
-
- (void)cineon; /* unused */
-
- formatInfo->interleave = 0;
- formatInfo->packing = 5;
- formatInfo->signage = 0;
- formatInfo->sense = 0;
- formatInfo->line_padding = htonl(0);
- formatInfo->channel_padding = htonl(0);
-}
-
-static void
-dumpCineonFormatInfo(CineonFormatInformation* formatInfo) {
- d_printf("\n--Format Information--\n");
- d_printf("Interleave %d,", formatInfo->interleave);
- switch (formatInfo->interleave) {
- case 0: d_printf(" pixel interleave\n"); break;
- case 1: d_printf(" line interleave\n"); break;
- case 2: d_printf(" channel interleave\n"); break;
- default: d_printf(" (unknown)\n"); break;
- }
- d_printf("Packing %d,", formatInfo->packing);
- if (formatInfo->packing & 0x80) {
- d_printf(" multi pixel,");
- }
- else {
- d_printf(" single pixel,");
- }
- switch (formatInfo->packing & 0x7F) {
- case 0: d_printf(" tight\n"); break;
- case 1: d_printf(" byte packed left\n"); break;
- case 2: d_printf(" byte packed right\n"); break;
- case 3: d_printf(" word packed left\n"); break;
- case 4: d_printf(" word packed right\n"); break;
- case 5: d_printf(" long packed left\n"); break;
- case 6: d_printf(" long packed right\n"); break;
- default: d_printf(" (unknown)\n"); break;
- }
- d_printf("Sign %d,", formatInfo->signage);
- if (formatInfo->signage) {
- d_printf(" signed\n");
- }
- else {
- d_printf(" unsigned\n");
- }
- d_printf("Sense %d,", formatInfo->signage);
- if (formatInfo->signage) {
- d_printf(" negative\n");
- }
- else {
- d_printf(" positive\n");
- }
- d_printf("End of line padding %ld\n", (intptr_t)ntohl(formatInfo->line_padding));
- d_printf("End of channel padding %ld\n", (intptr_t)ntohl(formatInfo->channel_padding));
-}
-
-static void
-fillCineonOriginationInfo(CineonFile* cineon,
- CineonOriginationInformation* originInfo, CineonFileInformation* fileInfo) {
-
- (void)cineon; /* unused */
-
- originInfo->x_offset = htonl(0);
- originInfo->y_offset = htonl(0);
- strcpy(originInfo->file_name, fileInfo->file_name);
- strcpy(originInfo->create_date, fileInfo->create_date);
- strcpy(originInfo->create_time, fileInfo->create_time);
- strncpy(originInfo->input_device, "David's Cineon writer", 64);
- strncpy(originInfo->model_number, "Software", 32);
- strncpy(originInfo->serial_number, "001", 32);
- originInfo->x_input_samples_per_mm = htonf(undefined());
- originInfo->y_input_samples_per_mm = htonf(undefined());
- /* this should probably be undefined, too */
- originInfo->input_device_gamma = htonf(1.0);
-}
-
-static void
-dumpCineonOriginationInfo(CineonOriginationInformation* originInfo) {
- d_printf("\n--Origination Information--\n");
- d_printf("X offset %ld\n", (intptr_t)ntohl(originInfo->x_offset));
- d_printf("Y offset %ld\n", (intptr_t)ntohl(originInfo->y_offset));
- d_printf("File name \"%s\"\n", originInfo->file_name);
- d_printf("Creation date \"%s\"\n", originInfo->create_date);
- d_printf("Creation time \"%s\"\n", originInfo->create_time);
- d_printf("Input device \"%s\"\n", originInfo->input_device);
- d_printf("Model number \"%s\"\n", originInfo->model_number);
- d_printf("Serial number \"%s\"\n", originInfo->serial_number);
- d_printf("Samples per mm in x %f\n", ntohf(originInfo->x_input_samples_per_mm));
- d_printf("Samples per mm in y %f\n", ntohf(originInfo->y_input_samples_per_mm));
- d_printf("Input device gamma %f\n", ntohf(originInfo->input_device_gamma));
-}
-
-static int
-initCineonGenericHeader(CineonFile* cineon, CineonGenericHeader* header, const char* imagename) {
-
- fillCineonFileInfo(cineon, &header->fileInfo, imagename);
- fillCineonImageInfo(cineon, &header->imageInfo);
- fillCineonFormatInfo(cineon, &header->formatInfo);
- fillCineonOriginationInfo(cineon, &header->originInfo, &header->fileInfo);
+#include "logImageLib.h"
- return 0;
-}
+#include "MEM_guardedalloc.h"
-static void
-UNUSED_FUNCTION(dumpCineonGenericHeader)(CineonGenericHeader* header) {
- dumpCineonFileInfo(&header->fileInfo);
- dumpCineonImageInfo(&header->imageInfo);
- dumpCineonFormatInfo(&header->formatInfo);
- dumpCineonOriginationInfo(&header->originInfo);
-}
+/*
+ * For debug purpose
+ */
static int verbose = 0;
-void
-cineonSetVerbose(int verbosity) {
- verbose = verbosity;
-}
-
-static void
-verboseMe(CineonFile* cineon) {
-
- d_printf("size %d x %d x %d\n", cineon->width, cineon->height, cineon->depth);
- d_printf("ImageStart %d, lineBufferLength %d, implied length %d\n",
- cineon->imageOffset, cineon->lineBufferLength * 4,
- cineon->imageOffset + cineon->lineBufferLength * 4 * cineon->height);
-}
-
-int
-cineonGetRowBytes(CineonFile* cineon, unsigned short* row, int y) {
-
- int longsRead;
- int pixelIndex;
- int longIndex;
- int numPixels = cineon->width * cineon->depth;
-
-
- /* only seek if not reading consecutive lines */
- if (y != cineon->fileYPos) {
- int lineOffset = cineon->imageOffset + y * cineon->lineBufferLength * 4;
- if (verbose) d_printf("Seek in getRowBytes\n");
- if (logimage_fseek(cineon, lineOffset, SEEK_SET) != 0) {
- if (verbose) d_printf("Couldn't seek to line %d at %d\n", y, lineOffset);
- return 1;
- }
- cineon->fileYPos = y;
- }
-
- longsRead = logimage_fread(cineon->lineBuffer, 4, cineon->lineBufferLength, cineon);
- if (longsRead != cineon->lineBufferLength) {
- if (verbose) {
- d_printf("Couldn't read line %d length %d\n", y, cineon->lineBufferLength * 4);
- perror("cineonGetRowBytes");
- }
-
- return 1;
- }
- /* remember where we left the car, honey */
- ++cineon->fileYPos;
-
- /* convert longwords to pixels */
- pixelIndex = 0;
- for (longIndex = 0; longIndex < cineon->lineBufferLength; ++longIndex) {
- unsigned int t = ntohl(cineon->lineBuffer[longIndex]);
- t = t >> 2;
- cineon->pixelBuffer[pixelIndex+2] = (unsigned short) t & 0x3ff;
- t = t >> 10;
- cineon->pixelBuffer[pixelIndex+1] = (unsigned short) t & 0x3ff;
- t = t >> 10;
- cineon->pixelBuffer[pixelIndex] = (unsigned short) t & 0x3ff;
- pixelIndex += 3;
- }
-
- /* extract required pixels */
- for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- if (cineon->params.doLogarithm)
- row[pixelIndex] = cineon->lut10_16[cineon->pixelBuffer[pixelIndex]];
- else
- row[pixelIndex] = cineon->pixelBuffer[pixelIndex] << 6;
- }
-
- return 0;
+void cineonSetVerbose(int verbosity) {
+ verbose = verbosity;
}
-int
-cineonSetRowBytes(CineonFile* cineon, const unsigned short* row, int y) {
-
- int pixelIndex;
- int numPixels = cineon->width * cineon->depth;
- int longIndex;
- int longsWritten;
-
- /* put new pixels into pixelBuffer */
- for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- if (cineon->params.doLogarithm)
- cineon->pixelBuffer[pixelIndex] = cineon->lut16_16[row[pixelIndex]];
- else
- cineon->pixelBuffer[pixelIndex] = row[pixelIndex] >> 6;
- }
-
- /* pack into longwords */
- pixelIndex = 0;
- for (longIndex = 0; longIndex < cineon->lineBufferLength; ++longIndex) {
- unsigned int t =
- (cineon->pixelBuffer[pixelIndex] << 22) |
- (cineon->pixelBuffer[pixelIndex+1] << 12) |
- (cineon->pixelBuffer[pixelIndex+2] << 2);
- cineon->lineBuffer[longIndex] = htonl(t);
- pixelIndex += 3;
- }
-
- /* only seek if not reading consecutive lines */
- if (y != cineon->fileYPos) {
- int lineOffset = cineon->imageOffset + y * cineon->lineBufferLength * 4;
- if (verbose) d_printf("Seek in setRowBytes\n");
- if (logimage_fseek(cineon, lineOffset, SEEK_SET) != 0) {
- if (verbose) d_printf("Couldn't seek to line %d at %d\n", y, lineOffset);
- return 1;
- }
- cineon->fileYPos = y;
- }
-
- longsWritten = fwrite(cineon->lineBuffer, 4, cineon->lineBufferLength, cineon->file);
- if (longsWritten != cineon->lineBufferLength) {
- if (verbose) d_printf("Couldn't write line %d length %d\n", y, cineon->lineBufferLength * 4);
- return 1;
- }
-
- ++cineon->fileYPos;
+static void fillCineonMainHeader(LogImageFile *cineon, CineonMainHeader *header,
+ const char *filename, const char *creator)
+{
+ time_t fileClock;
+ struct tm *fileTime;
+ int i;
- return 0;
+ memset(header, 0, sizeof(CineonMainHeader));
+
+ /* --- File header --- */
+ header->fileHeader.magic_num = swap_uint(CINEON_FILE_MAGIC, cineon->isMSB);
+ header->fileHeader.offset = swap_uint(cineon->element[0].dataOffset, cineon->isMSB);
+ header->fileHeader.gen_hdr_size = swap_uint(sizeof(CineonFileHeader) + sizeof(CineonImageHeader) +
+ sizeof(CineonOriginationHeader), cineon->isMSB);
+ header->fileHeader.ind_hdr_size = 0;
+ header->fileHeader.user_data_size = 0;
+ header->fileHeader.file_size = swap_uint(cineon->element[0].dataOffset + cineon->height * getRowLength(cineon->width, cineon->element[0]), cineon->isMSB);
+ strcpy(header->fileHeader.version, "v4.5");
+ strncpy(header->fileHeader.file_name, filename, 99);
+ header->fileHeader.file_name[99] = 0;
+ fileClock = time(0);
+ fileTime = localtime(&fileClock);
+ strftime(header->fileHeader.creation_date, 12, "%Y:%m:%d", fileTime);
+ strftime(header->fileHeader.creation_time, 12, "%H:%M:%S%Z", fileTime);
+ header->fileHeader.creation_time[11] = 0;
+
+ /* --- Image header --- */
+ header->imageHeader.orientation = 0;
+ header->imageHeader.elements_per_image = cineon->depth;
+
+ for (i = 0; i < 3; i++) {
+ header->imageHeader.element[i].descriptor1 = 0;
+ header->imageHeader.element[i].descriptor2 = i;
+ header->imageHeader.element[i].bits_per_sample = cineon->element[0].bitsPerSample;
+ header->imageHeader.element[i].pixels_per_line = swap_uint(cineon->width, cineon->isMSB);
+ header->imageHeader.element[i].lines_per_image = swap_uint(cineon->height, cineon->isMSB);
+ header->imageHeader.element[i].ref_low_data = swap_uint(cineon->element[0].refLowData, cineon->isMSB);
+ header->imageHeader.element[i].ref_low_quantity = swap_float(cineon->element[0].refLowQuantity, cineon->isMSB);
+ header->imageHeader.element[i].ref_high_data = swap_uint(cineon->element[0].refHighData, cineon->isMSB);
+ header->imageHeader.element[i].ref_high_quantity = swap_float(cineon->element[0].refHighQuantity, cineon->isMSB);
+ }
+
+ header->imageHeader.white_point_x = swap_float(0.0f, cineon->isMSB);
+ header->imageHeader.white_point_y = swap_float(0.0f, cineon->isMSB);
+ header->imageHeader.red_primary_x = swap_float(0.0f, cineon->isMSB);
+ header->imageHeader.red_primary_y = swap_float(0.0f, cineon->isMSB);
+ header->imageHeader.green_primary_x = swap_float(0.0f, cineon->isMSB);
+ header->imageHeader.green_primary_y = swap_float(0.0f, cineon->isMSB);
+ header->imageHeader.blue_primary_x = swap_float(0.0f, cineon->isMSB);
+ header->imageHeader.blue_primary_y = swap_float(0.0f, cineon->isMSB);
+ strncpy(header->imageHeader.label, creator, 199);
+ header->imageHeader.label[199] = 0;
+ header->imageHeader.interleave = 0;
+ header->imageHeader.data_sign = 0;
+ header->imageHeader.sense = 0;
+ header->imageHeader.line_padding = swap_uint(0, cineon->isMSB);
+ header->imageHeader.element_padding = swap_uint(0, cineon->isMSB);
+
+ switch (cineon->element[0].packing) {
+ case 0:
+ header->imageHeader.packing = 0;
+ break;
+
+ case 1:
+ header->imageHeader.packing = 5;
+ break;
+
+ case 2:
+ header->imageHeader.packing = 6;
+ break;
+ }
+
+ /* --- Origination header --- */
+ /* we leave it blank */
+
+ /* --- Film header --- */
+ /* we leave it blank */
}
-int
-cineonGetRow(CineonFile* cineon, unsigned short* row, int y) {
-
- int longsRead;
- int pixelIndex;
- int longIndex;
-/* int numPixels = cineon->width * cineon->depth;
-*/
- /* only seek if not reading consecutive lines */
- if (y != cineon->fileYPos) {
- int lineOffset = cineon->imageOffset + y * cineon->lineBufferLength * 4;
- if (verbose) d_printf("Seek in getRow\n");
- if (logimage_fseek(cineon, lineOffset, SEEK_SET) != 0) {
- if (verbose) d_printf("Couldn't seek to line %d at %d\n", y, lineOffset);
- return 1;
- }
- cineon->fileYPos = y;
- }
-
- longsRead = logimage_fread(cineon->lineBuffer, 4, cineon->lineBufferLength, cineon);
- if (longsRead != cineon->lineBufferLength) {
- if (verbose) d_printf("Couldn't read line %d length %d\n", y, cineon->lineBufferLength * 4);
- return 1;
- }
+LogImageFile *cineonOpen(const unsigned char *byteStuff, int fromMemory, size_t bufferSize)
+{
+ CineonMainHeader header;
+ LogImageFile *cineon = (LogImageFile *)MEM_mallocN(sizeof(LogImageFile), __func__);
+ char *filename = (char *)byteStuff;
+ int i;
+ unsigned int dataOffset;
- /* remember where we left the car, honey */
- ++cineon->fileYPos;
-
- /* convert longwords to pixels */
- pixelIndex = 0;
- for (longIndex = 0; longIndex < cineon->lineBufferLength; ++longIndex) {
- unsigned int t = ntohl(cineon->lineBuffer[longIndex]);
- t = t >> 2;
- row[pixelIndex+2] = (unsigned short) t & 0x3ff;
- t = t >> 10;
- row[pixelIndex+1] = (unsigned short) t & 0x3ff;
- t = t >> 10;
- row[pixelIndex] = (unsigned short) t & 0x3ff;
- pixelIndex += 3;
+ if (cineon == 0) {
+ if (verbose) printf("Cineon: Failed to malloc cineon file structure.\n");
+ return 0;
}
- return 0;
-}
+ /* zero the header */
+ memset(&header, 0, sizeof(CineonMainHeader));
-int
-cineonSetRow(CineonFile* cineon, const unsigned short* row, int y) {
-
- int pixelIndex;
-/* int numPixels = cineon->width * cineon->depth;
-*/ int longIndex;
- int longsWritten;
-
- /* pack into longwords */
- pixelIndex = 0;
- for (longIndex = 0; longIndex < cineon->lineBufferLength; ++longIndex) {
- unsigned int t =
- (row[pixelIndex] << 22) |
- (row[pixelIndex+1] << 12) |
- (row[pixelIndex+2] << 2);
- cineon->lineBuffer[longIndex] = htonl(t);
- pixelIndex += 3;
- }
+ /* for close routine */
+ cineon->file = 0;
- /* only seek if not reading consecutive lines */
- if (y != cineon->fileYPos) {
- int lineOffset = cineon->imageOffset + y * cineon->lineBufferLength * 4;
- if (verbose) d_printf("Seek in setRowBytes\n");
- if (logimage_fseek(cineon, lineOffset, SEEK_SET) != 0) {
- if (verbose) d_printf("Couldn't seek to line %d at %d\n", y, lineOffset);
- return 1;
+ if (fromMemory == 0) {
+ /* byteStuff is then the filename */
+ cineon->file = BLI_fopen(filename, "rb");
+ if (cineon->file == 0) {
+ if (verbose) printf("Cineon: Failed to open file \"%s\".\n", filename);
+ logImageClose(cineon);
+ return 0;
}
- cineon->fileYPos = y;
+ /* not used in this case */
+ cineon->memBuffer = 0;
+ cineon->memCursor = 0;
+ cineon->memBufferSize = 0;
}
-
- longsWritten = fwrite(cineon->lineBuffer, 4, cineon->lineBufferLength, cineon->file);
- if (longsWritten != cineon->lineBufferLength) {
- if (verbose) d_printf("Couldn't write line %d length %d\n", y, cineon->lineBufferLength * 4);
- return 1;
+ else {
+ cineon->memBuffer = (unsigned char *)byteStuff;
+ cineon->memCursor = (unsigned char *)byteStuff;
+ cineon->memBufferSize = bufferSize;
}
- ++cineon->fileYPos;
-
- return 0;
-}
-
-CineonFile*
-cineonOpen(const char* filename) {
-
- CineonGenericHeader header;
-
- CineonFile* cineon = (CineonFile* )malloc(sizeof(CineonFile));
- if (cineon == 0) {
- if (verbose) d_printf("Failed to malloc cineon file structure.\n");
+ if (logimage_fread(&header, sizeof(header), 1, cineon) == 0) {
+ if (verbose) printf("Cineon: Not enough data for header in \"%s\".\n", byteStuff);
+ logImageClose(cineon);
return 0;
}
- /* for close routine */
- cineon->file = 0;
- cineon->lineBuffer = 0;
- cineon->pixelBuffer = 0;
- cineon->membuffer = 0;
- cineon->memcursor = 0;
- cineon->membuffersize = 0;
-
- cineon->file = BLI_fopen(filename, "rb");
- if (cineon->file == 0) {
- if (verbose) d_printf("Failed to open file \"%s\".\n", filename);
- cineonClose(cineon);
- return 0;
+ /* endianness determination */
+ if (header.fileHeader.magic_num == swap_uint(CINEON_FILE_MAGIC, 1)) {
+ cineon->isMSB = 1;
+ if (verbose) printf("Cineon: File is MSB.\n");
}
- cineon->reading = 1;
-
- if (logimage_fread(&header, sizeof(CineonGenericHeader), 1, cineon) == 0) {
- if (verbose) d_printf("Not enough data for header in \"%s\".\n", filename);
- cineonClose(cineon);
- return 0;
+ else if (header.fileHeader.magic_num == CINEON_FILE_MAGIC) {
+ cineon->isMSB = 0;
+ if (verbose) printf("Cineon: File is LSB.\n");
}
-
- /* let's assume cineon files are always network order */
- if (header.fileInfo.magic_num != ntohl(CINEON_FILE_MAGIC)) {
- if (verbose) d_printf("Bad magic number %8.8lX in \"%s\".\n",
- (uintptr_t)ntohl(header.fileInfo.magic_num), filename);
- cineonClose(cineon);
+ else {
+ if (verbose) printf("Cineon: Bad magic number %lu in \"%s\".\n",
+ (uintptr_t)header.fileHeader.magic_num, byteStuff);
+ logImageClose(cineon);
return 0;
}
- if (header.formatInfo.packing != 5) {
- if (verbose) d_printf("Can't understand packing %d\n", header.formatInfo.packing);
- cineonClose(cineon);
- return 0;
- }
+ cineon->width = swap_uint(header.imageHeader.element[0].pixels_per_line, cineon->isMSB);
+ cineon->height = swap_uint(header.imageHeader.element[0].lines_per_image, cineon->isMSB);
+ cineon->depth = header.imageHeader.elements_per_image;
+ cineon->srcFormat = format_Cineon;
- cineon->width = ntohl(header.imageInfo.channel[0].pixels_per_line);
- cineon->height = ntohl(header.imageInfo.channel[0].lines_per_image);
- cineon->depth = header.imageInfo.channels_per_image;
- /* cineon->bitsPerPixel = 10; */
- cineon->bitsPerPixel = header.imageInfo.channel[0].bits_per_pixel;
- cineon->imageOffset = ntohl(header.fileInfo.image_offset);
-
- cineon->lineBufferLength = pixelsToLongs(cineon->width * cineon->depth);
- cineon->lineBuffer = malloc(cineon->lineBufferLength * 4);
- if (cineon->lineBuffer == 0) {
- if (verbose) d_printf("Couldn't malloc line buffer of size %d\n", cineon->lineBufferLength * 4);
- cineonClose(cineon);
+ if (header.imageHeader.interleave == 0)
+ cineon->numElements = 1;
+ else if (header.imageHeader.interleave == 2)
+ cineon->numElements = header.imageHeader.elements_per_image;
+ else {
+ if (verbose) printf("Cineon: Data interleave not supported: %d\n", header.imageHeader.interleave);
return 0;
}
- cineon->pixelBuffer = malloc(cineon->lineBufferLength * 3 * sizeof(unsigned short));
- if (cineon->pixelBuffer == 0) {
- if (verbose) d_printf("Couldn't malloc pixel buffer of size %d\n",
- (cineon->width * cineon->depth) * (int)sizeof(unsigned short));
- cineonClose(cineon);
- return 0;
+ if (cineon->depth == 1) {
+ /* Grayscale image */
+ cineon->element[0].descriptor = descriptor_Luminance;
+ cineon->element[0].transfer = transfer_Linear;
+ cineon->element[0].depth = 1;
}
- cineon->pixelBufferUsed = 0;
-
- if (logimage_fseek(cineon, cineon->imageOffset, SEEK_SET) != 0) {
- if (verbose) d_printf("Couldn't seek to image data at %d\n", cineon->imageOffset);
- cineonClose(cineon);
- return 0;
+ else if (cineon->depth == 3) {
+ /* RGB image */
+ if (cineon->numElements == 1) {
+ cineon->element[0].descriptor = descriptor_RGB;
+ cineon->element[0].transfer = transfer_PrintingDensity;
+ cineon->element[0].depth = 3;
+ }
+ else if (cineon->numElements == 3) {
+ cineon->element[0].descriptor = descriptor_Red;
+ cineon->element[0].transfer = transfer_PrintingDensity;
+ cineon->element[0].depth = 1;
+ cineon->element[1].descriptor = descriptor_Green;
+ cineon->element[1].transfer = transfer_PrintingDensity;
+ cineon->element[1].depth = 1;
+ cineon->element[2].descriptor = descriptor_Blue;
+ cineon->element[2].transfer = transfer_PrintingDensity;
+ cineon->element[2].depth = 1;
+ }
}
- cineon->fileYPos = 0;
-
- logImageGetByteConversionDefaults(&cineon->params);
- setupLut(cineon);
-
- cineon->getRow = &cineonGetRowBytes;
- cineon->setRow = 0;
- cineon->close = &cineonClose;
-
- if (verbose) {
- verboseMe(cineon);
+ else {
+ if (verbose) printf("Cineon: Cineon image depth unsupported: %d\n", cineon->depth);
+ return 0;
}
- return cineon;
-}
+ dataOffset = swap_uint(header.fileHeader.offset, cineon->isMSB);
-int cineonIsMemFileCineon(unsigned char *mem)
-{
- unsigned int num;
- memcpy(&num, mem, sizeof(unsigned int));
-
- if (num != ntohl(CINEON_FILE_MAGIC)) {
- return 0;
- }
- else return 1;
-}
+ for (i = 0; i < cineon->numElements; i++) {
+ cineon->element[i].bitsPerSample = header.imageHeader.element[i].bits_per_sample;
+ cineon->element[i].maxValue = powf(2, cineon->element[i].bitsPerSample) - 1.0f;
+ cineon->element[i].refLowData = swap_uint(header.imageHeader.element[i].ref_low_data, cineon->isMSB);
+ cineon->element[i].refLowQuantity = swap_float(header.imageHeader.element[i].ref_low_quantity, cineon->isMSB);
+ cineon->element[i].refHighData = swap_uint(header.imageHeader.element[i].ref_high_data, cineon->isMSB);
+ cineon->element[i].refHighQuantity = swap_float(header.imageHeader.element[i].ref_high_quantity, cineon->isMSB);
-CineonFile*
-cineonOpenFromMem(unsigned char *mem, unsigned int size) {
+ switch (header.imageHeader.packing) {
+ case 0:
+ cineon->element[i].packing = 0;
+ break;
- CineonGenericHeader header;
-
- CineonFile* cineon = (CineonFile* )malloc(sizeof(CineonFile));
- if (cineon == 0) {
- if (verbose) d_printf("Failed to malloc cineon file structure.\n");
- return 0;
- }
+ case 5:
+ cineon->element[i].packing = 1;
+ break;
- /* for close routine */
- cineon->file = 0;
- cineon->lineBuffer = 0;
- cineon->pixelBuffer = 0;
- cineon->membuffer = mem;
- cineon->membuffersize = size;
- cineon->memcursor = mem;
-
- cineon->file = 0;
- cineon->reading = 1;
- verbose = 0;
- if (size < sizeof(CineonGenericHeader)) {
- if (verbose) d_printf("Not enough data for header!\n");
- cineonClose(cineon);
- return 0;
- }
+ case 6:
+ cineon->element[i].packing = 2;
+ break;
- logimage_fread(&header, sizeof(CineonGenericHeader), 1, cineon);
+ default:
+ /* Not supported */
+ if (verbose) printf("Cineon: packing unsupported: %d\n", header.imageHeader.packing);
+ return 0;
+ }
- /* let's assume cineon files are always network order */
- if (header.fileInfo.magic_num != ntohl(CINEON_FILE_MAGIC)) {
- if (verbose) d_printf("Bad magic number %8.8lX in\n", (uintptr_t)ntohl(header.fileInfo.magic_num));
+ if (cineon->element[i].refLowData == CINEON_UNDEFINED_U32 || isnan(cineon->element[i].refLowData))
+ cineon->element[i].refLowData = 0;
- cineonClose(cineon);
- return 0;
- }
+ if (cineon->element[i].refHighData == CINEON_UNDEFINED_U32 || isnan(cineon->element[i].refHighData))
+ cineon->element[i].refHighData = (unsigned int)cineon->element[i].maxValue;
- if (header.formatInfo.packing != 5) {
- if (verbose) d_printf("Can't understand packing %d\n", header.formatInfo.packing);
- cineonClose(cineon);
- return 0;
- }
+ if (cineon->element[i].refLowQuantity == CINEON_UNDEFINED_R32 || isnan(cineon->element[i].refLowQuantity))
+ cineon->element[i].refLowQuantity = 0.0f;
- cineon->width = ntohl(header.imageInfo.channel[0].pixels_per_line);
- cineon->height = ntohl(header.imageInfo.channel[0].lines_per_image);
- cineon->depth = header.imageInfo.channels_per_image;
- /* cineon->bitsPerPixel = 10; */
- cineon->bitsPerPixel = header.imageInfo.channel[0].bits_per_pixel;
- cineon->imageOffset = ntohl(header.fileInfo.image_offset);
-
- cineon->lineBufferLength = pixelsToLongs(cineon->width * cineon->depth);
- cineon->lineBuffer = malloc(cineon->lineBufferLength * 4);
- if (cineon->lineBuffer == 0) {
- if (verbose) d_printf("Couldn't malloc line buffer of size %d\n", cineon->lineBufferLength * 4);
- cineonClose(cineon);
- return 0;
- }
+ if (cineon->element[i].refHighQuantity == CINEON_UNDEFINED_R32 || isnan(cineon->element[i].refHighQuantity)) {
+ if (cineon->element[i].transfer == transfer_PrintingDensity)
+ cineon->element[i].refHighQuantity = 2.048f;
+ else
+ cineon->element[i].refHighQuantity = cineon->element[i].maxValue;
+ }
- cineon->pixelBuffer = malloc(cineon->lineBufferLength * 3 * sizeof(unsigned short));
- if (cineon->pixelBuffer == 0) {
- if (verbose) d_printf("Couldn't malloc pixel buffer of size %d\n",
- (cineon->width * cineon->depth) * (int)sizeof(unsigned short));
- cineonClose(cineon);
- return 0;
- }
- cineon->pixelBufferUsed = 0;
-
- if (logimage_fseek(cineon, cineon->imageOffset, SEEK_SET) != 0) {
- if (verbose) d_printf("Couldn't seek to image data at %d\n", cineon->imageOffset);
- cineonClose(cineon);
- return 0;
+ cineon->element[i].dataOffset = dataOffset;
+ dataOffset += cineon->height * getRowLength(cineon->width, cineon->element[i]);
}
-
- cineon->fileYPos = 0;
-
- logImageGetByteConversionDefaults(&cineon->params);
- setupLut(cineon);
- cineon->getRow = &cineonGetRowBytes;
- cineon->setRow = 0;
- cineon->close = &cineonClose;
+ cineon->referenceBlack = 95.0f / 1023.0f * cineon->element[0].maxValue;
+ cineon->referenceWhite = 685.0f / 1023.0f * cineon->element[0].maxValue;
+ cineon->gamma = 1.7f;
if (verbose) {
- verboseMe(cineon);
- }
+ printf("size %d x %d x %d elements\n", cineon->width, cineon->height, cineon->numElements);
+ for (i = 0; i < cineon->numElements; i++) {
+ printf(" Element %d:\n", i);
+ printf(" Bits per sample: %d\n", cineon->element[i].bitsPerSample);
+ printf(" Depth: %d\n", cineon->element[i].depth);
+ printf(" Transfer characteristics: %d\n", cineon->element[i].transfer);
+ printf(" Packing: %d\n", cineon->element[i].packing);
+ printf(" Descriptor: %d\n", cineon->element[i].descriptor);
+ printf(" Data offset: %u\n", cineon->element[i].dataOffset);
+ printf(" Reference low data: %u\n", cineon->element[i].refLowData);
+ printf(" Reference low quantity: %f\n", cineon->element[i].refLowQuantity);
+ printf(" Reference high data: %u\n", cineon->element[i].refHighData);
+ printf(" Reference high quantity: %f\n", cineon->element[i].refHighQuantity);
+ printf("\n");
+ }
+ printf("Gamma: %f\n", cineon->gamma);
+ printf("Reference black: %f\n", cineon->referenceBlack);
+ printf("Reference white: %f\n", cineon->referenceWhite);
+ printf("----------------------------\n");
+ }
return cineon;
}
+LogImageFile *cineonCreate(const char *filename, int width, int height, int bitsPerSample, const char *creator)
+{
+ CineonMainHeader header;
+ const char *shortFilename = 0;
+ /* unsigned char pad[6044]; */
-int
-cineonGetSize(const CineonFile* cineon, int* width, int* height, int* depth) {
- *width = cineon->width;
- *height = cineon->height;
- *depth = cineon->depth;
- return 0;
-}
-
-CineonFile*
-cineonCreate(const char* filename, int width, int height, int depth) {
-
- /* Note: always write files in network order */
- /* By the spec, it shouldn't matter, but ... */
-
- CineonGenericHeader header;
- const char* shortFilename = 0;
-
- CineonFile* cineon = (CineonFile*)malloc(sizeof(CineonFile));
+ LogImageFile *cineon = (LogImageFile *)MEM_mallocN(sizeof(LogImageFile), __func__);
if (cineon == 0) {
- if (verbose) d_printf("Failed to malloc cineon file structure.\n");
+ if (verbose) printf("cineon: Failed to malloc cineon file structure.\n");
return 0;
}
- memset(&header, 0, sizeof(header));
-
- /* for close routine */
- cineon->file = 0;
- cineon->lineBuffer = 0;
- cineon->pixelBuffer = 0;
-
- cineon->file = BLI_fopen(filename, "wb");
- if (cineon->file == 0) {
- if (verbose) d_printf("Couldn't open file %s\n", filename);
- cineonClose(cineon);
+ /* Only 10 bits Cineon are supported */
+ if (bitsPerSample != 10) {
+ if (verbose) printf("cineon: Only 10 bits Cineon are supported.\n");
+ logImageClose(cineon);
return 0;
}
- cineon->reading = 0;
cineon->width = width;
cineon->height = height;
- cineon->depth = depth;
- cineon->bitsPerPixel = 10;
- cineon->imageOffset = sizeof(CineonGenericHeader);
-
- cineon->lineBufferLength = pixelsToLongs(cineon->width * cineon->depth);
- cineon->lineBuffer = malloc(cineon->lineBufferLength * 4);
- if (cineon->lineBuffer == 0) {
- if (verbose) d_printf("Couldn't malloc line buffer of size %d\n", cineon->lineBufferLength * 4);
- cineonClose(cineon);
- return 0;
- }
+ cineon->element[0].bitsPerSample = 10;
+ cineon->element[0].dataOffset = sizeof(CineonMainHeader);
+ cineon->element[0].maxValue = 1023;
+ cineon->isMSB = 1;
+ cineon->numElements = 1;
+ cineon->element[0].packing = 1;
+ cineon->depth = 3;
+ cineon->element[0].depth = 3;
+ cineon->element[0].descriptor = descriptor_RGB;
+ cineon->element[0].transfer = transfer_PrintingDensity;
+ cineon->element[0].refHighQuantity = 2.048f;
+ cineon->element[0].refLowQuantity = 0;
+ cineon->element[0].refLowData = 0;
+ cineon->element[0].refHighData = cineon->element[0].maxValue;
+ cineon->referenceWhite = 685.0f;
+ cineon->referenceBlack = 95.0f;
+ cineon->gamma = 1.7f;
- cineon->pixelBuffer = malloc(cineon->lineBufferLength * 3 * sizeof(unsigned short));
- if (cineon->pixelBuffer == 0) {
- if (verbose) d_printf("Couldn't malloc pixel buffer of size %d\n",
- (cineon->width * cineon->depth) * (int)sizeof(unsigned short));
- cineonClose(cineon);
- return 0;
- }
- cineon->pixelBufferUsed = 0;
-
- /* find trailing part of filename */
shortFilename = strrchr(filename, '/');
- if (shortFilename == 0) {
+ if (shortFilename == 0)
shortFilename = filename;
- }
- else {
- ++shortFilename;
- }
+ else
+ shortFilename++;
- if (initCineonGenericHeader(cineon, &header, shortFilename) != 0) {
- cineonClose(cineon);
+ cineon->file = BLI_fopen(filename, "wb");
+ if (cineon->file == 0) {
+ if (verbose) printf("cineon: Couldn't open file %s\n", filename);
+ logImageClose(cineon);
return 0;
}
+ fillCineonMainHeader(cineon, &header, shortFilename, creator);
+
if (fwrite(&header, sizeof(header), 1, cineon->file) == 0) {
- if (verbose) d_printf("Couldn't write image header\n");
- cineonClose(cineon);
+ if (verbose) printf("cineon: Couldn't write image header\n");
+ logImageClose(cineon);
return 0;
}
- cineon->fileYPos = 0;
-
- logImageGetByteConversionDefaults(&cineon->params);
- setupLut(cineon);
-
- cineon->getRow = 0;
- cineon->setRow = &cineonSetRowBytes;
- cineon->close = &cineonClose;
return cineon;
}
-
-void
-cineonClose(CineonFile* cineon) {
-
- if (cineon == 0) {
- return;
- }
-
- if (cineon->file) {
- fclose(cineon->file);
- cineon->file = 0;
- }
-
- if (cineon->lineBuffer) {
- free(cineon->lineBuffer);
- cineon->lineBuffer = 0;
- }
-
- if (cineon->pixelBuffer) {
- free(cineon->pixelBuffer);
- cineon->pixelBuffer = 0;
- }
-
- free(cineon);
-}
diff --git a/source/blender/imbuf/intern/cineon/cineonlib.h b/source/blender/imbuf/intern/cineon/cineonlib.h
index ef992c527b0..9333743a1bf 100644
--- a/source/blender/imbuf/intern/cineon/cineonlib.h
+++ b/source/blender/imbuf/intern/cineon/cineonlib.h
@@ -1,68 +1,142 @@
/*
- * Cineon image file format library definitions.
- * Also handles DPX files (almost)
+ * Cineon image file format library definitions.
+ * Also handles DPX files (almost)
*
- * Copyright 1999,2000,2001 David Hodson <hodsond@acm.org>
+ * Copyright 1999,2000,2001 David Hodson <hodsond@acm.org>
*
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Julien Enche.
*
*/
-#ifndef __CINEONLIB_H__
-#define __CINEONLIB_H__
-
/** \file blender/imbuf/intern/cineon/cineonlib.h
* \ingroup imbcineon
*/
-#include "logImageCore.h"
+
+#ifndef __CINEON_LIB_H__
+#define __CINEON_LIB_H__
#ifdef __cplusplus
extern "C" {
#endif
-/*
- * Cineon image structure. You don't care what this is.
- */
+#include "logImageCore.h"
-typedef struct _Log_Image_File_t_ CineonFile;
+#define CINEON_FILE_MAGIC 0x802A5FD7
+#define CINEON_UNDEFINED_U8 0xFF
+#define CINEON_UNDEFINED_U16 0xFFFF
+#define CINEON_UNDEFINED_U32 0xFFFFFFFF
+#define CINEON_UNDEFINED_R32 0x7F800000
+#define CINEON_UNDEFINED_CHAR 0
-/* int functions return 0 for OK */
+typedef struct {
+ unsigned int magic_num;
+ unsigned int offset;
+ unsigned int gen_hdr_size;
+ unsigned int ind_hdr_size;
+ unsigned int user_data_size;
+ unsigned int file_size;
+ char version[8];
+ char file_name[100];
+ char creation_date[12];
+ char creation_time[12];
+ char reserved[36];
+} CineonFileHeader;
-void cineonSetVerbose(int);
+typedef struct {
+ unsigned char descriptor1;
+ unsigned char descriptor2;
+ unsigned char bits_per_sample;
+ unsigned char filler;
+ unsigned int pixels_per_line;
+ unsigned int lines_per_image;
+ unsigned int ref_low_data;
+ float ref_low_quantity;
+ unsigned int ref_high_data;
+ float ref_high_quantity;
+} CineonElementHeader;
-CineonFile* cineonOpenFromMem(unsigned char *mem, unsigned int size);
+typedef struct {
+ unsigned char orientation;
+ unsigned char elements_per_image;
+ unsigned short filler;
+ CineonElementHeader element[8];
+ float white_point_x;
+ float white_point_y;
+ float red_primary_x;
+ float red_primary_y;
+ float green_primary_x;
+ float green_primary_y;
+ float blue_primary_x;
+ float blue_primary_y;
+ char label[200];
+ char reserved[28];
+ unsigned char interleave;
+ unsigned char packing;
+ unsigned char data_sign;
+ unsigned char sense;
+ unsigned int line_padding;
+ unsigned int element_padding;
+ char reserved2[20];
+} CineonImageHeader;
-CineonFile* cineonOpen(const char* filename);
-int cineonGetSize(const CineonFile* cineon, int* xsize, int* ysize, int* channels);
-CineonFile* cineonCreate(const char* filename, int xsize, int ysize, int channels);
-int cineonIsMemFileCineon(unsigned char *mem);
+typedef struct {
+ int x_offset;
+ int y_offset;
+ char file_name[100];
+ char creation_date[12];
+ char creation_time[12];
+ char input_device[64];
+ char model_number[32];
+ char input_serial_number[32];
+ float x_input_samples_per_mm;
+ float y_input_samples_per_mm;
+ float input_device_gamma;
+ char reserved[40];
+} CineonOriginationHeader;
-/* get/set scanline of converted bytes */
-int cineonGetRowBytes(CineonFile* cineon, unsigned short* row, int y);
-int cineonSetRowBytes(CineonFile* cineon, const unsigned short* row, int y);
+typedef struct {
+ unsigned char film_code;
+ unsigned char film_type;
+ unsigned char edge_code_perforation_offset;
+ unsigned char filler;
+ unsigned int prefix;
+ unsigned int count;
+ char format[32];
+ unsigned int frame_position;
+ float frame_rate;
+ char attribute[32];
+ char slate[200];
+ char reserved[740];
+} CineonFilmHeader;
-/* get/set scanline of unconverted shorts */
-int cineonGetRow(CineonFile* cineon, unsigned short* row, int y);
-int cineonSetRow(CineonFile* cineon, const unsigned short* row, int y);
+typedef struct {
+ CineonFileHeader fileHeader;
+ CineonImageHeader imageHeader;
+ CineonOriginationHeader originationHeader;
+ CineonFilmHeader filmHeader;
+} CineonMainHeader;
-/* closes file and deletes data */
-void cineonClose(CineonFile* cineon);
+void cineonSetVerbose(int);
+LogImageFile *cineonOpen(const unsigned char *byteStuff, int fromMemory, size_t bufferSize);
+LogImageFile *cineonCreate(const char *filename, int width, int height, int bitsPerSample, const char *creator);
#ifdef __cplusplus
}
#endif
-#endif /* __CINEONLIB_H__ */
+#endif /* __CINEON_LIB_H__ */
diff --git a/source/blender/imbuf/intern/cineon/dpxfile.h b/source/blender/imbuf/intern/cineon/dpxfile.h
index e1d95268a80..e69de29bb2d 100644
--- a/source/blender/imbuf/intern/cineon/dpxfile.h
+++ b/source/blender/imbuf/intern/cineon/dpxfile.h
@@ -1,128 +0,0 @@
-/*
- * Cineon image file format library definitions.
- * Dpx file format structures.
- *
- * This header file contains private details.
- * User code should generally use cineonlib.h only.
- *
- * Copyright 1999,2000,2001 David Hodson <hodsond@acm.org>
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef __DPXFILE_H__
-#define __DPXFILE_H__
-
-/** \file blender/imbuf/intern/cineon/dpxfile.h
- * \ingroup imbcineon
- */
-
-#include "logImageCore.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct {
- U32 magic_num; /* magic number */
- U32 offset; /* offset to image data in bytes */
- ASCII vers[8]; /* which header format version is being used (v1.0) */
- U32 file_size; /* file size in bytes */
- U32 ditto_key; /* I bet some people use this */
- U32 gen_hdr_size; /* generic header length in bytes */
- U32 ind_hdr_size; /* industry header length in bytes */
- U32 user_data_size; /* user-defined data length in bytes */
- ASCII file_name[100]; /* image file name */
- ASCII create_date[24]; /* file creation date, yyyy:mm:dd:hh:mm:ss:LTZ */
- ASCII creator[100];
- ASCII project[200];
- ASCII copyright[200];
- U32 key; /* encryption key, FFFFFFF = unencrypted */
- ASCII Reserved[104]; /* reserved field TBD (need to pad) */
-} DpxFileInformation;
-
-typedef struct {
- U32 signage;
- U32 ref_low_data; /* reference low data code value */
- R32 ref_low_quantity; /* reference low quantity represented */
- U32 ref_high_data; /* reference high data code value */
- R32 ref_high_quantity;/* reference high quantity represented */
- U8 designator1;
- U8 transfer_characteristics;
- U8 colorimetry;
- U8 bits_per_pixel;
- U16 packing;
- U16 encoding;
- U32 data_offset;
- U32 line_padding;
- U32 channel_padding;
- ASCII description[32];
-} DpxChannelInformation;
-
-typedef struct {
- U16 orientation;
- U16 channels_per_image;
- U32 pixels_per_line;
- U32 lines_per_image;
- DpxChannelInformation channel[8];
- ASCII reserved[52];
-} DpxImageInformation;
-
-typedef struct {
- U32 x_offset;
- U32 y_offset;
- R32 x_centre;
- R32 y_centre;
- U32 x_original_size;
- U32 y_original_size;
- ASCII file_name[100];
- ASCII creation_time[24];
- ASCII input_device[32];
- ASCII input_serial_number[32];
- U16 border_validity[4];
- U32 pixel_aspect_ratio[2]; /* h:v */
- ASCII reserved[28];
-} DpxOriginationInformation;
-
-typedef struct {
- ASCII film_manufacturer_id[2];
- ASCII film_type[2];
- ASCII edge_code_perforation_offset[2];
- ASCII edge_code_prefix[6];
- ASCII edge_code_count[4];
- ASCII film_format[32];
- U32 frame_position;
- U32 sequence_length;
- U32 held_count;
- R32 frame_rate;
- R32 shutter_angle;
- ASCII frame_identification[32];
- ASCII slate_info[100];
- ASCII reserved[56];
-} DpxMPIInformation;
-
-typedef struct {
- DpxFileInformation fileInfo;
- DpxImageInformation imageInfo;
- DpxOriginationInformation originInfo;
- DpxMPIInformation filmHeader;
-} DpxMainHeader;
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __DPXFILE_H__ */
diff --git a/source/blender/imbuf/intern/cineon/dpxlib.c b/source/blender/imbuf/intern/cineon/dpxlib.c
index c1138225e93..aedce52a7bf 100644
--- a/source/blender/imbuf/intern/cineon/dpxlib.c
+++ b/source/blender/imbuf/intern/cineon/dpxlib.c
@@ -1,21 +1,23 @@
/*
- * Dpx image file format library routines.
+ * Dpx image file format library routines.
*
- * Copyright 1999 - 2002 David Hodson <hodsond@acm.org>
+ * Copyright 1999 - 2002 David Hodson <hodsond@acm.org>
*
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Julien Enche.
*
*/
@@ -23,689 +25,445 @@
* \ingroup imbcineon
*/
-#include "dpxfile.h"
+
#include "dpxlib.h"
+#include "logmemfile.h"
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
-#include <time.h> /* strftime() */
+#include <time.h>
#include <sys/types.h>
-#ifdef WIN32
-#include <winsock.h>
-#else
-#include <netinet/in.h> /* htonl() */
-#endif
-#include <string.h> /* memset */
-#include "cin_debug_stuff.h"
-#include "logmemfile.h"
-#include "BLI_fileops.h"
-
-static void
-fillDpxChannelInfo(DpxFile* dpx, DpxChannelInformation* chan, int des) {
-
- (void)dpx; /* unused */
-
- chan->signage = 0;
- chan->ref_low_data = htonl(0);
- chan->ref_low_quantity = htonf(0.0);
- chan->ref_high_data = htonl(1023);
- chan->ref_high_quantity = htonf(2.046);
- chan->designator1 = des;
- chan->transfer_characteristics = 0;
- chan->colorimetry = 0;
- chan->bits_per_pixel = 10;
- chan->packing = htons(1);
- chan->encoding = 0;
- chan->data_offset = 0;
- chan->line_padding = htonl(0);
- chan->channel_padding = htonl(0);
- chan->description[0] = 0;
-}
-
-static void
-dumpDpxChannelInfo(DpxChannelInformation* chan) {
- d_printf(" Signage %ld", (intptr_t)ntohl(chan->signage));
- d_printf(" Ref low data %ld\n", (intptr_t)ntohl(chan->ref_low_data));
- d_printf(" Ref low quantity %f\n", ntohf(chan->ref_low_quantity));
- d_printf(" Ref high data %ld\n", (intptr_t)ntohl(chan->ref_high_data));
- d_printf(" Ref high quantity %f\n", ntohf(chan->ref_high_quantity));
- d_printf(" Designator1: %d,", chan->designator1);
- d_printf(" Bits per pixel %d\n", chan->bits_per_pixel);
- d_printf(" Packing: %d,", ntohs(chan->packing));
- d_printf(" Data Offset: %ld,", (intptr_t)ntohl(chan->data_offset));
-}
-
-static void
-fillDpxFileInfo(
- DpxFile* dpx, DpxFileInformation* fileInfo, const char* filename) {
-
- time_t fileClock;
- struct tm* fileTime;
-
- /* Note: always write files in network order */
- /* By the spec, it shouldn't matter, but ... */
-
- fileInfo->magic_num = htonl(DPX_FILE_MAGIC);
- fileInfo->offset = htonl(dpx->imageOffset);
- strcpy(fileInfo->vers, "v1.0");
- fileInfo->file_size = htonl(dpx->imageOffset +
- pixelsToLongs(dpx->height * dpx->width * dpx->depth) * 4);
- fileInfo->ditto_key = 0;
- fileInfo->gen_hdr_size = htonl(
- sizeof(DpxFileInformation) +
- sizeof(DpxImageInformation) +
- sizeof(DpxOriginationInformation));
- fileInfo->ind_hdr_size = htonl(sizeof(DpxMPIInformation));
- fileInfo->user_data_size = 0;
- strncpy(fileInfo->file_name, filename, 99);
- fileInfo->file_name[99] = 0;
+#include <string.h>
- fileClock = time(0);
- fileTime = localtime(&fileClock);
- strftime(fileInfo->create_date, 24, "%Y:%m:%d:%H:%M:%S%Z", fileTime);
- /* Question: is %Z in strftime guaranteed to return 3 chars? */
- fileInfo->create_date[23] = 0;
-
- strcpy(fileInfo->creator, "David's DPX writer");
- fileInfo->project[0] = 0;
- fileInfo->copyright[0] = 0;
- fileInfo->key = 0xFFFFFFFF; /* same in any byte order */
-}
+#include "BLI_fileops.h"
+#include "BLI_math_base.h"
+#include "BLI_utildefines.h"
-static void
-dumpDpxFileInfo(DpxFileInformation* fileInfo) {
- d_printf("\n--File Information--\n");
- d_printf("Magic: %8.8lX\n", (unsigned long)ntohl(fileInfo->magic_num));
- d_printf("Image Offset %ld\n", (intptr_t)ntohl(fileInfo->offset));
- d_printf("Version \"%s\"\n", fileInfo->vers);
- d_printf("File size %ld\n", (intptr_t)ntohl(fileInfo->file_size));
- d_printf("Ditto key %ld\n", (intptr_t)ntohl(fileInfo->ditto_key));
- d_printf("Generic Header size %ld\n", (intptr_t)ntohl(fileInfo->gen_hdr_size));
- d_printf("Industry Header size %ld\n", (intptr_t)ntohl(fileInfo->ind_hdr_size));
- d_printf("User Data size %ld\n", (intptr_t)ntohl(fileInfo->user_data_size));
- d_printf("File name \"%s\"\n", fileInfo->file_name);
- d_printf("Creation date \"%s\"\n", fileInfo->create_date);
- d_printf("Creator \"%s\"\n", fileInfo->creator);
- d_printf("Project \"%s\"\n", fileInfo->project);
- d_printf("Copyright \"%s\"\n", fileInfo->copyright);
- d_printf("Key %ld\n", (intptr_t)ntohl(fileInfo->key));
-}
+#include "MEM_guardedalloc.h"
-static void
-fillDpxImageInfo(
- DpxFile* dpx, DpxImageInformation* imageInfo) {
- imageInfo->orientation = 0;
- imageInfo->channels_per_image = htons(1);
- imageInfo->pixels_per_line = htonl(dpx->width);
- imageInfo->lines_per_image = htonl(dpx->height);
+/*
+ * For debug purpose
+ */
- if (dpx->depth == 1) {
- fillDpxChannelInfo(dpx, &imageInfo->channel[0], 0);
+static int verbose = 0;
- }
- else if (dpx->depth == 3) {
- fillDpxChannelInfo(dpx, &imageInfo->channel[0], 50);
- }
+void dpxSetVerbose(int verbosity) {
+ verbose = verbosity;
}
-static void
-dumpDpxImageInfo(DpxImageInformation* imageInfo) {
- int n;
- int i;
- d_printf("\n--Image Information--\n");
- d_printf("Image orientation %d,", ntohs(imageInfo->orientation));
- n = ntohs(imageInfo->channels_per_image);
- d_printf("Channels %d\n", n);
- d_printf("Pixels per line %ld\n", (intptr_t)ntohl(imageInfo->pixels_per_line));
- d_printf("Lines per image %ld\n", (intptr_t)ntohl(imageInfo->lines_per_image));
- for (i = 0; i < n; ++i) {
- d_printf(" --Channel %d--\n", i);
- dumpDpxChannelInfo(&imageInfo->channel[i]);
- }
-}
+/*
+ * Headers
+ */
-static void
-fillDpxOriginationInfo(
- DpxFile* dpx, DpxOriginationInformation* originInfo, DpxFileInformation* fileInfo)
+static void fillDpxMainHeader(LogImageFile *dpx, DpxMainHeader *header, const char *filename, const char *creator)
{
- /* unused */
- (void)dpx;
- (void)originInfo;
- (void)fileInfo;
-}
-
-static void
-dumpDpxOriginationInfo(DpxOriginationInformation* originInfo) {
- d_printf("\n--Origination Information--\n");
- d_printf("X offset %ld\n", (intptr_t)ntohl(originInfo->x_offset));
- d_printf("Y offset %ld\n", (intptr_t)ntohl(originInfo->y_offset));
- d_printf("X centre %f\n", ntohf(originInfo->x_centre));
- d_printf("Y centre %f\n", ntohf(originInfo->y_centre));
- d_printf("Original X %ld\n", (intptr_t)ntohl(originInfo->x_original_size));
- d_printf("Original Y %ld\n", (intptr_t)ntohl(originInfo->y_original_size));
- d_printf("File name \"%s\"\n", originInfo->file_name);
- d_printf("Creation time \"%s\"\n", originInfo->creation_time);
- d_printf("Input device \"%s\"\n", originInfo->input_device);
- d_printf("Serial number \"%s\"\n", originInfo->input_serial_number);
-}
+ time_t fileClock;
+ struct tm *fileTime;
-static void
-initDpxMainHeader(DpxFile* dpx, DpxMainHeader* header, const char* shortFilename) {
memset(header, 0, sizeof(DpxMainHeader));
- fillDpxFileInfo(dpx, &header->fileInfo, shortFilename);
- fillDpxImageInfo(dpx, &header->imageInfo);
- fillDpxOriginationInfo(dpx, &header->originInfo, &header->fileInfo);
-#if 0
- fillDpxMPIInfo(dpx, &header->filmHeader);
-#endif
-}
-
-static void
-dumpDpxMainHeader(DpxMainHeader* header) {
- dumpDpxFileInfo(&header->fileInfo);
- dumpDpxImageInfo(&header->imageInfo);
- dumpDpxOriginationInfo(&header->originInfo);
-#if 0
- dumpDpxMPIInformation(&header->filmHeader);
-#endif
-}
-
-static int verbose = 0;
-void
-dpxSetVerbose(int verbosity) {
- verbose = verbosity;
-}
-
-static void
-verboseMe(DpxFile* dpx) {
-
- d_printf("size %d x %d x %d\n", dpx->width, dpx->height, dpx->depth);
- d_printf("ImageStart %d, lineBufferLength %d, implied length %d\n",
- dpx->imageOffset, dpx->lineBufferLength * 4,
- dpx->imageOffset + pixelsToLongs(dpx->width * dpx->depth * dpx->height) * 4);
-}
-
-int
-dpxGetRowBytes(DpxFile* dpx, unsigned short* row, int y) {
-
- /* Note: this code is bizarre because DPX files can wrap */
- /* packed longwords across line boundaries!!!! */
-
- size_t readLongs;
- unsigned int longIndex;
- int numPixels = dpx->width * dpx->depth;
- int pixelIndex;
-
- /* only seek if not reading consecutive lines */
- /* this is not quite right yet, need to account for leftovers */
- if (y != dpx->fileYPos) {
- int lineOffset = pixelsToLongs(y * dpx->width * dpx->depth) * 4;
- if (verbose) d_printf("Seek in getRowBytes\n");
- if (logimage_fseek(dpx, dpx->imageOffset + lineOffset, SEEK_SET) != 0) {
- if (verbose) d_printf("Couldn't seek to line %d at %d\n", y, dpx->imageOffset + lineOffset);
- return 1;
- }
- dpx->fileYPos = y;
- }
-
- /* read enough longwords */
- readLongs = pixelsToLongs(numPixels - dpx->pixelBufferUsed);
- if (logimage_fread(dpx->lineBuffer, 4, readLongs, dpx) != readLongs) {
- if (verbose) d_printf("Couldn't read line %d length %d\n", y, (int)readLongs * 4);
- return 1;
- }
- ++dpx->fileYPos;
-
- /* convert longwords to pixels */
- pixelIndex = dpx->pixelBufferUsed;
-
- /* this is just strange */
- if (dpx->depth == 1) {
- for (longIndex = 0; longIndex < readLongs; ++longIndex) {
- unsigned int t = ntohl(dpx->lineBuffer[longIndex]);
- dpx->pixelBuffer[pixelIndex] = t & 0x3ff;
- t = t >> 10;
- dpx->pixelBuffer[pixelIndex+1] = t & 0x3ff;
- t = t >> 10;
- dpx->pixelBuffer[pixelIndex+2] = t & 0x3ff;
- pixelIndex += 3;
- }
- }
- else /* if (dpx->depth == 3) */ {
- for (longIndex = 0; longIndex < readLongs; ++longIndex) {
- unsigned int t = ntohl(dpx->lineBuffer[longIndex]);
- t = t >> 2;
- dpx->pixelBuffer[pixelIndex+2] = t & 0x3ff;
- t = t >> 10;
- dpx->pixelBuffer[pixelIndex+1] = t & 0x3ff;
- t = t >> 10;
- dpx->pixelBuffer[pixelIndex] = t & 0x3ff;
- pixelIndex += 3;
- }
- }
- dpx->pixelBufferUsed = pixelIndex;
-
- /* extract required pixels */
- for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- if (dpx->params.doLogarithm)
- row[pixelIndex] = dpx->lut10_16[dpx->pixelBuffer[pixelIndex]];
- else
- row[pixelIndex] = dpx->pixelBuffer[pixelIndex] << 6;
- }
-
- /* save remaining pixels */
- while (pixelIndex < dpx->pixelBufferUsed) {
- dpx->pixelBuffer[pixelIndex - numPixels] = dpx->pixelBuffer[pixelIndex];
- ++pixelIndex;
- }
- dpx->pixelBufferUsed -= numPixels;
- /* done! */
- return 0;
-}
-
-int
-dpxSetRowBytes(DpxFile* dpx, const unsigned short* row, int y) {
-
- /* Note: this code is bizarre because DPX files can wrap */
- /* packed longwords across line boundaries!!!! */
-
- size_t writeLongs;
- int longIndex;
- int numPixels = dpx->width * dpx->depth;
- int pixelIndex;
- int pixelIndex2;
-
- /* only seek if not reading consecutive lines */
- /* this is not quite right yet */
- if (y != dpx->fileYPos) {
- int lineOffset = pixelsToLongs(y * dpx->width * dpx->depth) * 4;
- if (verbose) d_printf("Seek in getRowBytes\n");
- if (logimage_fseek(dpx, dpx->imageOffset + lineOffset, SEEK_SET) != 0) {
- if (verbose) d_printf("Couldn't seek to line %d at %d\n", y, dpx->imageOffset + lineOffset);
- return 1;
- }
- dpx->fileYPos = y;
- }
-
- /* put new pixels into pixelBuffer */
- for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- if (dpx->params.doLogarithm)
- dpx->pixelBuffer[dpx->pixelBufferUsed + pixelIndex] = dpx->lut16_16[row[pixelIndex]];
- else
- dpx->pixelBuffer[dpx->pixelBufferUsed + pixelIndex] = row[pixelIndex] >> 6;
- }
- dpx->pixelBufferUsed += numPixels;
-
- /* pack into longwords */
- writeLongs = dpx->pixelBufferUsed / 3;
- /* process whole line at image end */
- if (dpx->fileYPos == (dpx->height - 1)) {
- writeLongs = pixelsToLongs(dpx->pixelBufferUsed);
- }
- pixelIndex = 0;
- if (dpx->depth == 1) {
- for (longIndex = 0; longIndex < writeLongs; ++longIndex) {
- unsigned int t = dpx->pixelBuffer[pixelIndex] |
- (dpx->pixelBuffer[pixelIndex+1] << 10) |
- (dpx->pixelBuffer[pixelIndex+2] << 20);
- dpx->lineBuffer[longIndex] = htonl(t);
- pixelIndex += 3;
- }
- }
- else {
- for (longIndex = 0; longIndex < writeLongs; ++longIndex) {
- unsigned int t = dpx->pixelBuffer[pixelIndex+2] << 2 |
- (dpx->pixelBuffer[pixelIndex+1] << 12) |
- (dpx->pixelBuffer[pixelIndex] << 22);
- dpx->lineBuffer[longIndex] = htonl(t);
- pixelIndex += 3;
- }
- }
-
- /* write them */
- if (fwrite(dpx->lineBuffer, 4, writeLongs, dpx->file) != writeLongs) {
- if (verbose) d_printf("Couldn't write line %d length %d\n", y, (int)writeLongs * 4);
- return 1;
- }
- ++dpx->fileYPos;
-
- /* save remaining pixels */
- pixelIndex2 = 0;
- while (pixelIndex < dpx->pixelBufferUsed) {
- dpx->pixelBuffer[pixelIndex2] = dpx->pixelBuffer[pixelIndex];
- ++pixelIndex;
- ++pixelIndex2;
- }
- dpx->pixelBufferUsed = pixelIndex2;
-
- return 0;
+ /* --- File header --- */
+ header->fileHeader.magic_num = swap_uint(DPX_FILE_MAGIC, dpx->isMSB);
+ header->fileHeader.offset = swap_uint(dpx->element[0].dataOffset, dpx->isMSB);
+ strcpy(header->fileHeader.version, "v2.0");
+ header->fileHeader.file_size = swap_uint(dpx->element[0].dataOffset + dpx->height * getRowLength(dpx->width, dpx->element[0]), dpx->isMSB);
+ header->fileHeader.ditto_key = 0;
+ header->fileHeader.gen_hdr_size = swap_uint(sizeof(DpxFileHeader) + sizeof(DpxImageHeader) + sizeof(DpxOrientationHeader), dpx->isMSB);
+ header->fileHeader.ind_hdr_size = swap_uint(sizeof(DpxFilmHeader) + sizeof(DpxTelevisionHeader), dpx->isMSB);
+ header->fileHeader.user_data_size = DPX_UNDEFINED_U32;
+ strncpy(header->fileHeader.file_name, filename, 99);
+ header->fileHeader.file_name[99] = 0;
+ fileClock = time(0);
+ fileTime = localtime(&fileClock);
+ strftime(header->fileHeader.creation_date, 24, "%Y:%m:%d:%H:%M:%S%Z", fileTime);
+ header->fileHeader.creation_date[23] = 0;
+ strncpy(header->fileHeader.creator, creator, 99);
+ header->fileHeader.creator[99] = 0;
+ header->fileHeader.project[0] = 0;
+ header->fileHeader.copyright[0] = 0;
+ header->fileHeader.key = 0xFFFFFFFF;
+
+ /* --- Image header --- */
+ header->imageHeader.orientation = 0;
+ header->imageHeader.elements_per_image = swap_ushort(1, dpx->isMSB);
+ header->imageHeader.pixels_per_line = swap_uint(dpx->width, dpx->isMSB);
+ header->imageHeader.lines_per_element = swap_uint(dpx->height, dpx->isMSB);
+
+ /* Fills element */
+ header->imageHeader.element[0].data_sign = 0;
+ header->imageHeader.element[0].ref_low_data = swap_uint(dpx->element[0].refLowData, dpx->isMSB);
+ header->imageHeader.element[0].ref_low_quantity = swap_float(dpx->element[0].refLowQuantity, dpx->isMSB);
+ header->imageHeader.element[0].ref_high_data = swap_uint(dpx->element[0].refHighData, dpx->isMSB);
+ header->imageHeader.element[0].ref_high_quantity = swap_float(dpx->element[0].refHighQuantity, dpx->isMSB);
+ header->imageHeader.element[0].descriptor = dpx->element[0].descriptor;
+ header->imageHeader.element[0].transfer = dpx->element[0].transfer;
+ header->imageHeader.element[0].colorimetric = 0;
+ header->imageHeader.element[0].bits_per_sample = dpx->element[0].bitsPerSample;
+ header->imageHeader.element[0].packing = swap_ushort(dpx->element[0].packing, dpx->isMSB);
+ header->imageHeader.element[0].encoding = 0;
+ header->imageHeader.element[0].data_offset = swap_uint(dpx->element[0].dataOffset, dpx->isMSB);
+ header->imageHeader.element[0].line_padding = 0;
+ header->imageHeader.element[0].element_padding = 0;
+ header->imageHeader.element[0].description[0] = 0;
+
+ /* --- Orientation header --- */
+ /* we leave it blank */
+
+ /* --- Television header --- */
+ header->televisionHeader.time_code = DPX_UNDEFINED_U32;
+ header->televisionHeader.user_bits = DPX_UNDEFINED_U32;
+ header->televisionHeader.interlace = DPX_UNDEFINED_U8;
+ header->televisionHeader.field_number = DPX_UNDEFINED_U8;
+ header->televisionHeader.video_signal = DPX_UNDEFINED_U8;
+ header->televisionHeader.padding = DPX_UNDEFINED_U8;
+ header->televisionHeader.horizontal_sample_rate = DPX_UNDEFINED_R32;
+ header->televisionHeader.vertical_sample_rate = DPX_UNDEFINED_R32;
+ header->televisionHeader.frame_rate = DPX_UNDEFINED_R32;
+ header->televisionHeader.time_offset = DPX_UNDEFINED_R32;
+ header->televisionHeader.gamma = swap_float(dpx->gamma, dpx->isMSB);
+ header->televisionHeader.black_level = swap_float(dpx->referenceBlack, dpx->isMSB);
+ header->televisionHeader.black_gain = DPX_UNDEFINED_R32;
+ header->televisionHeader.breakpoint = DPX_UNDEFINED_R32;
+ header->televisionHeader.white_level = swap_float(dpx->referenceWhite, dpx->isMSB);
+ header->televisionHeader.integration_times = DPX_UNDEFINED_R32;
}
-#define LFMEMFILE 0
-#define LFREALFILE 1
-
-static DpxFile*
-intern_dpxOpen(int mode, const char* bytestuff, int bufsize) {
-
+LogImageFile *dpxOpen(const unsigned char *byteStuff, int fromMemory, size_t bufferSize)
+{
DpxMainHeader header;
- const char *filename = bytestuff;
- DpxFile* dpx = (DpxFile*)malloc(sizeof(DpxFile));
-
+ LogImageFile *dpx = (LogImageFile *)MEM_mallocN(sizeof(LogImageFile), __func__);
+ char *filename = (char *)byteStuff;
+ int i;
+
if (dpx == 0) {
- if (verbose) d_printf("Failed to malloc dpx file structure.\n");
+ if (verbose) printf("DPX: Failed to malloc dpx file structure.\n");
return 0;
}
+ /* zero the header */
+ memset(&header, 0, sizeof(DpxMainHeader));
+
/* for close routine */
dpx->file = 0;
- dpx->lineBuffer = 0;
- dpx->pixelBuffer = 0;
- if (mode == LFREALFILE) {
- filename = bytestuff;
+ if (fromMemory == 0) {
+ /* byteStuff is then the filename */
dpx->file = BLI_fopen(filename, "rb");
- if (dpx->file == 0) {
- if (verbose) d_printf("Failed to open file \"%s\".\n", filename);
- dpxClose(dpx);
+ if (dpx->file == 0) {
+ if (verbose) printf("DPX: Failed to open file \"%s\".\n", filename);
+ logImageClose(dpx);
return 0;
}
- dpx->membuffer = 0;
- dpx->memcursor = 0;
- dpx->membuffersize = 0;
+ /* not used in this case */
+ dpx->memBuffer = 0;
+ dpx->memCursor = 0;
+ dpx->memBufferSize = 0;
}
- else if (mode == LFMEMFILE) {
- dpx->membuffer = (unsigned char *)bytestuff;
- dpx->memcursor = (unsigned char *)bytestuff;
- dpx->membuffersize = bufsize;
+ else {
+ dpx->memBuffer = (unsigned char *)byteStuff;
+ dpx->memCursor = (unsigned char *)byteStuff;
+ dpx->memBufferSize = bufferSize;
}
-
- dpx->reading = 1;
if (logimage_fread(&header, sizeof(header), 1, dpx) == 0) {
- if (verbose) d_printf("Not enough data for header in \"%s\".\n", filename);
- dpxClose(dpx);
+ if (verbose) printf("DPX: Not enough data for header in \"%s\".\n", byteStuff);
+ logImageClose(dpx);
return 0;
}
- /* let's assume dpx files are always network order */
- if (header.fileInfo.magic_num != ntohl(DPX_FILE_MAGIC)) {
- if (verbose) d_printf("Bad magic number %8.8lX in \"%s\".\n",
- (uintptr_t)ntohl(header.fileInfo.magic_num), filename);
- dpxClose(dpx);
- return 0;
+ /* endianness determination */
+ if (header.fileHeader.magic_num == swap_uint(DPX_FILE_MAGIC, 1)) {
+ dpx->isMSB = 1;
+ if (verbose) printf("DPX: File is MSB.\n");
}
-
- if (ntohs(header.imageInfo.channel[0].packing) != 1) {
- if (verbose) d_printf("Unknown packing %d\n", header.imageInfo.channel[0].packing);
- dpxClose(dpx);
+ else if (header.fileHeader.magic_num == DPX_FILE_MAGIC) {
+ dpx->isMSB = 0;
+ if (verbose) printf("DPX: File is LSB.\n");
+ }
+ else {
+ if (verbose) printf("DPX: Bad magic number %lu in \"%s\".\n",
+ (uintptr_t)header.fileHeader.magic_num, byteStuff);
+ logImageClose(dpx);
return 0;
}
+ dpx->srcFormat = format_DPX;
+ dpx->numElements = swap_ushort(header.imageHeader.elements_per_image, dpx->isMSB);
+ dpx->width = swap_uint(header.imageHeader.pixels_per_line, dpx->isMSB);
+ dpx->height = swap_uint(header.imageHeader.lines_per_element, dpx->isMSB);
+ dpx->depth = 0;
+
+ for (i = 0; i < dpx->numElements; i++) {
+ dpx->element[i].descriptor = header.imageHeader.element[i].descriptor;
+
+ switch (dpx->element[i].descriptor) {
+ case descriptor_Red:
+ case descriptor_Green:
+ case descriptor_Blue:
+ case descriptor_Alpha:
+ case descriptor_Luminance:
+ case descriptor_Chrominance:
+ dpx->depth++;
+ dpx->element[i].depth = 1;
+ break;
+
+ case descriptor_CbYCrY:
+ dpx->depth += 2;
+ dpx->element[i].depth = 2;
+ break;
+
+ case descriptor_RGB:
+ case descriptor_CbYCr:
+ case descriptor_CbYACrYA:
+ dpx->depth += 3;
+ dpx->element[i].depth = 3;
+ break;
+
+ case descriptor_RGBA:
+ case descriptor_ABGR:
+ case descriptor_CbYCrA:
+ dpx->depth += 4;
+ dpx->element[i].depth = 4;
+ break;
+
+ case descriptor_Depth:
+ case descriptor_Composite:
+ /* unsupported */
+ break;
+ }
- dpx->width = ntohl(header.imageInfo.pixels_per_line);
- dpx->height = ntohl(header.imageInfo.lines_per_image);
- dpx->depth = ntohs(header.imageInfo.channels_per_image);
- /* Another DPX vs Cineon wierdness */
- if (dpx->depth == 1) {
- switch (header.imageInfo.channel[0].designator1) {
- case 50: dpx->depth = 3; break;
- case 51: dpx->depth = 4; break;
- case 52: dpx->depth = 4; break;
- default: break;
+ if (dpx->depth == 0 || dpx->depth > 4) {
+ if (verbose) printf("DPX: Unsupported image depth: %d\n", dpx->depth);
+ logImageClose(dpx);
+ return 0;
}
- }
- /* dpx->bitsPerPixel = 10; */
- dpx->bitsPerPixel = header.imageInfo.channel[0].bits_per_pixel;
- if (dpx->bitsPerPixel != 10) {
- if (verbose) d_printf("Don't support depth: %d\n", dpx->bitsPerPixel);
- dpxClose(dpx);
- return 0;
- }
- dpx->imageOffset = ntohl(header.fileInfo.offset);
- dpx->lineBufferLength = pixelsToLongs(dpx->width * dpx->depth);
- dpx->lineBuffer = malloc(dpx->lineBufferLength * 4);
- if (dpx->lineBuffer == 0) {
- if (verbose) d_printf("Couldn't malloc line buffer of size %d\n", dpx->lineBufferLength * 4);
- dpxClose(dpx);
- return 0;
- }
+ dpx->element[i].bitsPerSample = header.imageHeader.element[i].bits_per_sample;
+ dpx->element[i].maxValue = powf(2, dpx->element[i].bitsPerSample) - 1.0f;
+ dpx->element[i].packing = swap_ushort(header.imageHeader.element[i].packing, dpx->isMSB);
- /* could have 2 pixels left over */
- dpx->pixelBuffer = malloc((dpx->lineBufferLength * 3 + 2) * sizeof(unsigned short));
- if (dpx->pixelBuffer == 0) {
- if (verbose) d_printf("Couldn't malloc pixel buffer of size %d\n",
- (dpx->width * dpx->depth + 2 + 2) * (int)sizeof(unsigned short));
- dpxClose(dpx);
- return 0;
- }
- dpx->pixelBufferUsed = 0;
+ /* Sometimes, the offset is not set correctly in the header */
+ dpx->element[i].dataOffset = swap_uint(header.imageHeader.element[i].data_offset, dpx->isMSB);
+ if (dpx->element[i].dataOffset == 0 && dpx->numElements == 1)
+ dpx->element[i].dataOffset = swap_uint(header.fileHeader.offset, dpx->isMSB);
- if (logimage_fseek(dpx, dpx->imageOffset, SEEK_SET) != 0) {
- if (verbose) d_printf("Couldn't seek to image data start at %d\n", dpx->imageOffset);
- dpxClose(dpx);
- return 0;
- }
- dpx->fileYPos = 0;
-
- logImageGetByteConversionDefaults(&dpx->params);
- /* The SMPTE define this code:
- * 0 - User-defined
- * 1 - Printing density
- * 2 - Linear
- * 3 - Logarithmic
- * 4 - Unspecified video
- * 5 - SMPTE 240M
- * 6 - CCIR 709-1
- * 7 - CCIR 601-2 system B or G
- * 8 - CCIR 601-2 system M
- * 9 - NTSC composite video
- * 10 - PAL composite video
- * 11 - Z linear
- * 12 - homogeneous
- *
- * Note that transfer_characteristics is U8, don't need
- * check the byte order.
- */
-
- switch (header.imageInfo.channel[0].transfer_characteristics) {
- case 1:
- case 2: /* linear */
- dpx->params.doLogarithm= 0;
- break;
-
- case 3:
- dpx->params.doLogarithm= 1;
- break;
-
- /* TODO - Unsupported, but for now just load them,
- * colors may look wrong, but can solve color conversion later
- */
- case 4:
- case 5:
- case 6:
- case 7:
- case 8:
- case 9:
- case 10:
- case 11:
- case 12:
- if (verbose) d_printf("Un-supported Transfer Characteristics: %d using linear color conversion\n", header.imageInfo.channel[0].transfer_characteristics);
- dpx->params.doLogarithm= 0;
- break;
- default:
- if (verbose) d_printf("Un-supported Transfer Characteristics: %d\n", header.imageInfo.channel[0].transfer_characteristics);
- dpxClose(dpx);
+ if (dpx->element[i].dataOffset == 0) {
+ if (verbose) printf("DPX: Image header is corrupted.\n");
+ logImageClose(dpx);
return 0;
- break;
- }
- setupLut(dpx);
-
- dpx->getRow = &dpxGetRowBytes;
- dpx->setRow = 0;
- dpx->close = &dpxClose;
+ }
- if (verbose) {
- verboseMe(dpx);
+ dpx->element[i].transfer = header.imageHeader.element[i].transfer;
+
+ /* if undefined, assign default */
+ dpx->element[i].refLowData = swap_uint(header.imageHeader.element[i].ref_low_data, dpx->isMSB);
+ dpx->element[i].refLowQuantity = swap_float(header.imageHeader.element[i].ref_low_quantity, dpx->isMSB);
+ dpx->element[i].refHighData = swap_uint(header.imageHeader.element[i].ref_high_data, dpx->isMSB);
+ dpx->element[i].refHighQuantity = swap_float(header.imageHeader.element[i].ref_high_quantity, dpx->isMSB);
+
+ switch (dpx->element[i].descriptor) {
+ case descriptor_Red:
+ case descriptor_Green:
+ case descriptor_Blue:
+ case descriptor_Alpha:
+ case descriptor_RGB:
+ case descriptor_RGBA:
+ case descriptor_ABGR:
+ if (dpx->element[i].refLowData == DPX_UNDEFINED_U32 || isnan(dpx->element[i].refLowData))
+ dpx->element[i].refLowData = 0;
+
+ if (dpx->element[i].refHighData == DPX_UNDEFINED_U32 || isnan(dpx->element[i].refHighData))
+ dpx->element[i].refHighData = (unsigned int)dpx->element[i].maxValue;
+
+ if (dpx->element[i].refLowQuantity == DPX_UNDEFINED_R32 || isnan(dpx->element[i].refLowQuantity))
+ dpx->element[i].refLowQuantity = 0.0f;
+
+ if (dpx->element[i].refHighQuantity == DPX_UNDEFINED_R32 || isnan(dpx->element[i].refHighQuantity)) {
+ if (dpx->element[i].transfer == transfer_PrintingDensity || dpx->element[i].transfer == transfer_Logarithmic)
+ dpx->element[i].refHighQuantity = 2.048f;
+ else
+ dpx->element[i].refHighQuantity = dpx->element[i].maxValue;
+ }
+
+ break;
+
+ case descriptor_Luminance:
+ case descriptor_Chrominance:
+ case descriptor_CbYCrY:
+ case descriptor_CbYCr:
+ case descriptor_CbYACrYA:
+ case descriptor_CbYCrA:
+ if (dpx->element[i].refLowData == DPX_UNDEFINED_U32 || isnan(dpx->element[i].refLowData))
+ dpx->element[i].refLowData = 16.0f / 255.0f * dpx->element[i].maxValue;
+
+ if (dpx->element[i].refHighData == DPX_UNDEFINED_U32 || isnan(dpx->element[i].refHighData))
+ dpx->element[i].refHighData = 235.0f / 255.0f * dpx->element[i].maxValue;
+
+ if (dpx->element[i].refLowQuantity == DPX_UNDEFINED_R32 || isnan(dpx->element[i].refLowQuantity))
+ dpx->element[i].refLowQuantity = 0.0f;
+
+ if (dpx->element[i].refHighQuantity == DPX_UNDEFINED_R32 || isnan(dpx->element[i].refHighQuantity))
+ dpx->element[i].refHighQuantity = 0.7f;
+
+ break;
+
+ default:
+ break;
+ }
}
- return dpx;
-}
-
-DpxFile*
-dpxOpen(const char *filename) {
- return intern_dpxOpen(LFREALFILE, filename, 0);
-}
+ dpx->referenceBlack = swap_float(header.televisionHeader.black_level, dpx->isMSB);
+ dpx->referenceWhite = swap_float(header.televisionHeader.white_level, dpx->isMSB);
+ dpx->gamma = swap_float(header.televisionHeader.gamma, dpx->isMSB);
-DpxFile*
-dpxOpenFromMem(unsigned char *buffer, unsigned int size) {
- return intern_dpxOpen(LFMEMFILE, (const char *) buffer, size);
-}
+ if ((dpx->referenceBlack == DPX_UNDEFINED_R32 || isnan(dpx->referenceBlack)) ||
+ (dpx->referenceWhite == DPX_UNDEFINED_R32 || dpx->referenceWhite <= dpx->referenceBlack || isnan(dpx->referenceWhite)) ||
+ (dpx->gamma == DPX_UNDEFINED_R32 || dpx->gamma <= 0 || isnan(dpx->gamma)))
+ {
-int
-dpxIsMemFileCineon(void *buffer) {
- int magicnum = 0;
- magicnum = *((int*)buffer);
- if (magicnum == ntohl(DPX_FILE_MAGIC)) return 1;
- else return 0;
-}
+ dpx->referenceBlack = 95.0f / 1023.0f * dpx->element[0].maxValue;
+ dpx->referenceWhite = 685.0f / 1023.0f * dpx->element[0].maxValue;
+ dpx->gamma = 1.7f;
+ }
-DpxFile*
-dpxCreate(const char* filename, int width, int height, int depth) {
+ if (verbose) {
+ printf("size %d x %d x %d elements\n", dpx->width, dpx->height, dpx->numElements);
+ for (i = 0; i < dpx->numElements; i++) {
+ printf(" Element %d:\n", i);
+ printf(" Bits per sample: %d\n", dpx->element[i].bitsPerSample);
+ printf(" Depth: %d\n", dpx->element[i].depth);
+ printf(" Transfer characteristics: %d\n", dpx->element[i].transfer);
+ printf(" Packing: %d\n", dpx->element[i].packing);
+ printf(" Descriptor: %d\n", dpx->element[i].descriptor);
+ printf(" Data offset: %u\n", dpx->element[i].dataOffset);
+ printf(" Reference low data: %u\n", dpx->element[i].refLowData);
+ printf(" Reference low quantity: %f\n", dpx->element[i].refLowQuantity);
+ printf(" Reference high data: %u\n", dpx->element[i].refHighData);
+ printf(" Reference high quantity: %f\n", dpx->element[i].refHighQuantity);
+ printf("\n");
+ }
- /* Note: always write files in network order */
- /* By the spec, it shouldn't matter, but ... */
+ printf("Gamma: %f\n", dpx->gamma);
+ printf("Reference black: %f\n", dpx->referenceBlack);
+ printf("Reference white: %f\n", dpx->referenceWhite);
+ printf("----------------------------\n");
+ }
+ return dpx;
+}
+LogImageFile *dpxCreate(const char *filename, int width, int height, int bitsPerSample, int hasAlpha,
+ int isLogarithmic, int referenceWhite, int referenceBlack, float gamma,
+ const char *creator)
+{
DpxMainHeader header;
- const char* shortFilename = 0;
+ const char *shortFilename = 0;
+ unsigned char pad[6044];
- DpxFile* dpx = (DpxFile*)malloc(sizeof(DpxFile));
+ LogImageFile *dpx = (LogImageFile *)MEM_mallocN(sizeof(LogImageFile), __func__);
if (dpx == 0) {
- if (verbose) d_printf("Failed to malloc dpx file structure.\n");
- return 0;
- }
-
- memset(&header, 0, sizeof(header));
-
- /* for close routine */
- dpx->file = 0;
- dpx->lineBuffer = 0;
- dpx->pixelBuffer = 0;
-
- dpx->file = BLI_fopen(filename, "wb");
- if (dpx->file == 0) {
- if (verbose) d_printf("Couldn't open file %s\n", filename);
- dpxClose(dpx);
+ if (verbose) printf("DPX: Failed to malloc dpx file structure.\n");
return 0;
}
- dpx->reading = 0;
dpx->width = width;
dpx->height = height;
- dpx->depth = depth;
- dpx->bitsPerPixel = 10;
- dpx->imageOffset = sizeof(DpxMainHeader);
-
- dpx->lineBufferLength = pixelsToLongs(dpx->width * dpx->depth);
- dpx->lineBuffer = malloc(dpx->lineBufferLength * 4);
- if (dpx->lineBuffer == 0) {
- if (verbose) d_printf("Couldn't malloc line buffer of size %d\n", dpx->lineBufferLength * 4);
- dpxClose(dpx);
- return 0;
- }
+ dpx->element[0].bitsPerSample = bitsPerSample;
+ dpx->element[0].dataOffset = 8092;
+ dpx->element[0].maxValue = powf(2, dpx->element[0].bitsPerSample) - 1.0f;
+ dpx->isMSB = 1;
+ dpx->numElements = 1;
- dpx->pixelBuffer = malloc((dpx->lineBufferLength * 3 + 2) * sizeof(unsigned short));
- if (dpx->pixelBuffer == 0) {
- if (verbose) d_printf("Couldn't malloc pixel buffer of size %d\n",
- (dpx->width * dpx->depth + 2 + 2) * (int)sizeof(unsigned short));
- dpxClose(dpx);
- return 0;
+ switch (bitsPerSample) {
+ case 8:
+ case 16:
+ dpx->element[0].packing = 0;
+ break;
+
+ case 10:
+ case 12:
+ /* Packed Type A padding is the most common 10/12 bits format */
+ dpx->element[0].packing = 1;
+ break;
+
+ default:
+ if (verbose) printf("DPX: bitsPerSample not supported: %d\n", bitsPerSample);
+ logImageClose(dpx);
+ return 0;
}
- dpx->pixelBufferUsed = 0;
- /* find trailing part of filename */
- shortFilename = strrchr(filename, '/');
- if (shortFilename == 0) {
- shortFilename = filename;
+ if (hasAlpha == 0) {
+ dpx->depth = 3;
+ dpx->element[0].depth = 3;
+ dpx->element[0].descriptor = descriptor_RGB;
}
else {
- ++shortFilename;
+ dpx->depth = 4;
+ dpx->element[0].depth = 4;
+ dpx->element[0].descriptor = descriptor_RGBA;
}
- initDpxMainHeader(dpx, &header, shortFilename);
- logImageGetByteConversionDefaults(&dpx->params);
- /* Need set the file type before write the header!
- * 2 - Linear
- * 3 - Logarithmic
- *
- * Note that transfer characteristics is U8, don't need
- * check the byte order.
- */
- if (dpx->params.doLogarithm == 0)
- header.imageInfo.channel[0].transfer_characteristics= 2;
- else
- header.imageInfo.channel[0].transfer_characteristics= 3;
- if (fwrite(&header, sizeof(header), 1, dpx->file) == 0) {
- if (verbose) d_printf("Couldn't write image header\n");
- dpxClose(dpx);
- return 0;
+ if (isLogarithmic == 0) {
+ dpx->element[0].transfer = transfer_Linear;
+ dpx->element[0].refHighQuantity = dpx->element[0].maxValue;
}
- dpx->fileYPos = 0;
- setupLut(dpx);
+ else {
+ dpx->element[0].transfer = transfer_PrintingDensity;
+ dpx->element[0].refHighQuantity = 2.048f;
- dpx->getRow = 0;
- dpx->setRow = &dpxSetRowBytes;
- dpx->close = &dpxClose;
+ }
- return dpx;
-}
+ dpx->element[0].refLowQuantity = 0;
+ dpx->element[0].refLowData = 0;
+ dpx->element[0].refHighData = dpx->element[0].maxValue;
-void
-dpxClose(DpxFile* dpx) {
+ if (referenceWhite > 0)
+ dpx->referenceWhite = referenceWhite;
+ else
+ dpx->referenceWhite = 685.0f / 1023.0f * dpx->element[0].maxValue;
- if (dpx == 0) {
- return;
- }
+ if (referenceBlack > 0)
+ dpx->referenceBlack = referenceBlack;
+ else
+ dpx->referenceBlack = 95.0f / 1023.0f * dpx->element[0].maxValue;
- if (dpx->file) {
- fclose(dpx->file);
- dpx->file = 0;
- }
+ if (gamma > 0.0f)
+ dpx->gamma = gamma;
+ else
+ dpx->gamma = 1.7f;
- if (dpx->lineBuffer) {
- free(dpx->lineBuffer);
- dpx->lineBuffer = 0;
- }
- if (dpx->pixelBuffer) {
- free(dpx->pixelBuffer);
- dpx->pixelBuffer = 0;
- }
+ shortFilename = strrchr(filename, '/');
+ if (shortFilename == 0)
+ shortFilename = filename;
+ else
+ shortFilename++;
- free(dpx);
-}
+ dpx->file = BLI_fopen(filename, "wb");
-void
-dpxDump(const char* filename) {
+ if (dpx->file == 0) {
+ if (verbose) printf("DPX: Couldn't open file %s\n", filename);
+ logImageClose(dpx);
+ return 0;
+ }
- DpxMainHeader header;
- FILE* file;
+ fillDpxMainHeader(dpx, &header, shortFilename, creator);
- file = BLI_fopen(filename, "rb");
- if (file == 0) {
- d_printf("Failed to open file \"%s\".\n", filename);
- return;
+ if (fwrite(&header, sizeof(header), 1, dpx->file) == 0) {
+ if (verbose) printf("DPX: Couldn't write image header\n");
+ logImageClose(dpx);
+ return 0;
}
- if (fread(&header, sizeof(header), 1, file) == 0) {
- d_printf("Not enough data for header in \"%s\".\n", filename);
- fclose(file);
- return;
+ /* Header should be rounded to next 8k block
+ 6044 = 8092 - sizeof(DpxMainHeader) */
+ memset(&pad, 0, 6044);
+ if (fwrite(&pad, 6044, 1, dpx->file) == 0) {
+ if (verbose) printf("DPX: Couldn't write image header\n");
+ logImageClose(dpx);
+ return 0;
}
- fclose(file);
- dumpDpxMainHeader(&header);
+ return dpx;
}
diff --git a/source/blender/imbuf/intern/cineon/dpxlib.h b/source/blender/imbuf/intern/cineon/dpxlib.h
index eb3937f2bf7..e910aaa61e1 100644
--- a/source/blender/imbuf/intern/cineon/dpxlib.h
+++ b/source/blender/imbuf/intern/cineon/dpxlib.h
@@ -1,60 +1,160 @@
/*
- * DPX image file format library definitions.
+ * DPX image file format library definitions.
*
- * Copyright 1999 - 2002 David Hodson <hodsond@acm.org>
+ * Copyright 1999 - 2002 David Hodson <hodsond@acm.org>
*
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Julien Enche.
*
*/
-#ifndef __DPXLIB_H__
-#define __DPXLIB_H__
-
/** \file blender/imbuf/intern/cineon/dpxlib.h
* \ingroup imbcineon
*/
+
+#ifndef __DPX_LIB_H__
+#define __DPX_LIB_H__
+
#ifdef __cplusplus
extern "C" {
#endif
#include "logImageCore.h"
-typedef struct _Log_Image_File_t_ DpxFile;
+#define DPX_FILE_MAGIC 0x53445058
+#define DPX_UNDEFINED_U8 0xFF
+#define DPX_UNDEFINED_U16 0xFFFF
+#define DPX_UNDEFINED_U32 0xFFFFFFFF
+#define DPX_UNDEFINED_R32 0xFFFFFFFF
+#define DPX_UNDEFINED_CHAR 0
-/* int functions return 0 for OK */
+typedef struct {
+ unsigned int magic_num;
+ unsigned int offset;
+ char version[8];
+ unsigned int file_size;
+ unsigned int ditto_key;
+ unsigned int gen_hdr_size;
+ unsigned int ind_hdr_size;
+ unsigned int user_data_size;
+ char file_name[100];
+ char creation_date[24];
+ char creator[100];
+ char project[200];
+ char copyright[200];
+ unsigned int key;
+ char reserved[104];
+} DpxFileHeader;
-void dpxSetVerbose(int);
+typedef struct {
+ unsigned int data_sign;
+ unsigned int ref_low_data;
+ float ref_low_quantity;
+ unsigned int ref_high_data;
+ float ref_high_quantity;
+ unsigned char descriptor;
+ unsigned char transfer;
+ unsigned char colorimetric;
+ unsigned char bits_per_sample;
+ unsigned short packing;
+ unsigned short encoding;
+ unsigned int data_offset;
+ unsigned int line_padding;
+ unsigned int element_padding;
+ char description[32];
+} DpxElementHeader;
-DpxFile* dpxOpen(const char* filename);
-DpxFile* dpxCreate(const char* filename, int xsize, int ysize, int channels);
-DpxFile* dpxOpenFromMem(unsigned char *buffer, unsigned int size);
-int dpxIsMemFileCineon(void *buffer);
+typedef struct {
+ unsigned short orientation;
+ unsigned short elements_per_image;
+ unsigned int pixels_per_line;
+ unsigned int lines_per_element;
+ DpxElementHeader element[8];
+ char reserved[52];
+} DpxImageHeader;
-/* get/set scanline of converted bytes */
-int dpxGetRowBytes(DpxFile* dpx, unsigned short* row, int y);
-int dpxSetRowBytes(DpxFile* dpx, const unsigned short* row, int y);
+typedef struct {
+ unsigned int x_offset;
+ unsigned int y_offset;
+ float x_center;
+ float y_center;
+ unsigned int x_original_size;
+ unsigned int y_original_size;
+ char file_name[100];
+ char creation_time[24];
+ char input_device[32];
+ char input_serial_number[32];
+ unsigned short border_validity[4];
+ unsigned int pixel_aspect_ratio[2];
+ char reserved[28];
+} DpxOrientationHeader;
-/* closes file and deletes data */
-void dpxClose(DpxFile* dpx);
+typedef struct {
+ char film_manufacturer_id[2];
+ char film_type[2];
+ char edge_code_perforation_offset[2];
+ char edge_code_prefix[6];
+ char edge_code_count[4];
+ char film_format[32];
+ unsigned int frame_position;
+ unsigned int sequence_length;
+ unsigned int held_count;
+ float frame_rate;
+ float shutter_angle;
+ char frame_identification[32];
+ char slate_info[100];
+ char reserved[56];
+} DpxFilmHeader;
-/* dumps file to stdout */
-void dpxDump(const char* filename);
+typedef struct {
+ unsigned int time_code;
+ unsigned int user_bits;
+ unsigned char interlace;
+ unsigned char field_number;
+ unsigned char video_signal;
+ unsigned char padding;
+ float horizontal_sample_rate;
+ float vertical_sample_rate;
+ float frame_rate;
+ float time_offset;
+ float gamma;
+ float black_level;
+ float black_gain;
+ float breakpoint;
+ float white_level;
+ float integration_times;
+ unsigned char reserved[76];
+} DpxTelevisionHeader;
+
+
+typedef struct {
+ DpxFileHeader fileHeader;
+ DpxImageHeader imageHeader;
+ DpxOrientationHeader orientationHeader;
+ DpxFilmHeader filmHeader;
+ DpxTelevisionHeader televisionHeader;
+} DpxMainHeader;
+
+void dpxSetVerbose(int verbosity);
+LogImageFile *dpxOpen(const unsigned char *byteStuff, int fromMemory, size_t bufferSize);
+LogImageFile *dpxCreate(const char *filename, int width, int height, int bitsPerSample, int hasAlpha, int isLogarithmic, int referenceWhite, int referenceBlack, float gamma, const char *creator);
#ifdef __cplusplus
}
#endif
-#endif /* __DPXLIB_H__ */
+#endif
diff --git a/source/blender/imbuf/intern/cineon/logImageCore.c b/source/blender/imbuf/intern/cineon/logImageCore.c
index f772cc7d477..3911e5c2ef3 100644
--- a/source/blender/imbuf/intern/cineon/logImageCore.c
+++ b/source/blender/imbuf/intern/cineon/logImageCore.c
@@ -1,21 +1,23 @@
/*
- * Cineon image file format library routines.
+ * Cineon image file format library routines.
*
- * Copyright 1999,2000,2001 David Hodson <hodsond@acm.org>
+ * Copyright 1999,2000,2001 David Hodson <hodsond@acm.org>
*
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Julien Enche.
*
*/
@@ -23,223 +25,1407 @@
* \ingroup imbcineon
*/
+
+#include "logmemfile.h"
#include "logImageCore.h"
+#include "dpxlib.h"
+#include "cineonlib.h"
-#include <time.h> /* strftime() */
+#include <stdlib.h>
+#include <string.h>
#include <math.h>
-/* Makes rint consistent in Windows and Linux: */
-#define rint(x) floor(x+0.5)
-#ifdef WIN32
-#include <winsock.h>
-#else
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <sys/param.h>
-#endif
+#include "BLI_fileops.h"
+#include "BLI_utildefines.h"
+
+#include "MEM_guardedalloc.h"
+
+/*
+ * Declaration of static functions
+ */
+
+static int logImageSetData8(LogImageFile *logImage, LogImageElement logElement, float *data);
+static int logImageSetData10(LogImageFile *logImage, LogImageElement logElement, float *data);
+static int logImageSetData12(LogImageFile *logImage, LogImageElement logElement, float *data);
+static int logImageSetData16(LogImageFile *logImage, LogImageElement logElement, float *data);
+static int logImageElementGetData(LogImageFile *dpx, LogImageElement logElement, float *data);
+static int logImageElementGetData1(LogImageFile *dpx, LogImageElement logElement, float *data);
+static int logImageElementGetData8(LogImageFile *dpx, LogImageElement logElement, float *data);
+static int logImageElementGetData10(LogImageFile *dpx, LogImageElement logElement, float *data);
+static int logImageElementGetData10Packed(LogImageFile *dpx, LogImageElement logElement, float *data);
+static int logImageElementGetData12(LogImageFile *dpx, LogImageElement logElement, float *data);
+static int logImageElementGetData12Packed(LogImageFile *dpx, LogImageElement logElement, float *data);
+static int logImageElementGetData16(LogImageFile *dpx, LogImageElement logElement, float *data);
+static int convertLogElementToRGBA(float *src, float *dst, LogImageFile *logImage, LogImageElement logElement, int dstIsLinearRGB);
+static int convertRGBAToLogElement(float *src, float *dst, LogImageFile *logImage, LogImageElement logElement, int srcIsLinearRGB);
+
+
+/*
+ * For debug purpose
+ */
+
+static int verbose = 0;
+
+void logImageSetVerbose(int verbosity)
+{
+ verbose = verbosity;
+ cineonSetVerbose(verbosity);
+ dpxSetVerbose(verbosity);
+}
+
+
+/*
+ * IO stuff
+ */
+
+int logImageIsDpx(const void *buffer)
+{
+ unsigned int magicNum = *(unsigned int *)buffer;
+ return (magicNum == DPX_FILE_MAGIC || magicNum == swap_uint(DPX_FILE_MAGIC, 1));
+}
-#if defined(__hpux)
-/* These are macros in hpux */
-#ifdef htonl
-#undef htonl
-#undef htons
-#undef ntohl
-#undef ntohs
-#endif
-unsigned int htonl(h) unsigned int h; { return(h); }
-unsigned short htons(h) unsigned short h; { return(h); }
-unsigned int ntohl(n) unsigned int n; { return(n); }
-unsigned short ntohs(n) unsigned short n; { return(n); }
-#endif
-
-
-/* obscure LogImage conversion */
-/* from 10 bit int to 0.0 - 1.0 */
-/* magic numbers left intact */
-static double
-convertTo(int inp, int white, float gamma) {
- /* return pow(pow(10.0, ((inp - white) * 0.002 / 0.6)), gamma); */
- return pow(10.0, (inp - white) * gamma * 0.002 / 0.6);
+int logImageIsCineon(const void *buffer)
+{
+ unsigned int magicNum = *(unsigned int *)buffer;
+ return (magicNum == CINEON_FILE_MAGIC || magicNum == swap_uint(CINEON_FILE_MAGIC, 1));
}
-static double
-convertFrom(double inp, int white, float gamma) {
- return white + log10(inp) / (gamma * 0.002 / 0.6);
+LogImageFile *logImageOpenFromFile(const char *filename, int cineon)
+{
+ unsigned int magicNum;
+ FILE *f = BLI_fopen(filename, "rb");
+
+ (void)cineon;
+
+ if (f == 0)
+ return 0;
+
+ if (fread(&magicNum, sizeof(unsigned int), 1, f) != 1) {
+ fclose(f);
+ return 0;
+ }
+
+ fclose(f);
+
+ if (logImageIsDpx(&magicNum))
+ return dpxOpen((const unsigned char *)filename, 0, 0);
+ else if (logImageIsCineon(&magicNum))
+ return cineonOpen((const unsigned char *)filename, 0, 0);
+
+ return 0;
}
-/* set up the 10 bit to 8 bit and 8 bit to 10 bit tables */
-void
-setupLut(LogImageFile *logImage) {
+LogImageFile *logImageOpenFromMemory(const unsigned char *buffer, unsigned int size)
+{
+ if (logImageIsDpx(buffer))
+ return dpxOpen(buffer, 1, size);
+ else if (logImageIsCineon(buffer))
+ return cineonOpen(buffer, 1, size);
- int i;
- double f_black;
- double scale;
+ return 0;
+}
+
+LogImageFile *logImageCreate(const char *filename, int cineon, int width, int height, int bitsPerSample,
+ int isLogarithmic, int hasAlpha, int referenceWhite, int referenceBlack,
+ float gamma, const char *creator)
+{
+ /* referenceWhite, referenceBlack and gamma values are only supported for DPX file */
+ if (cineon)
+ return cineonCreate(filename, width, height, bitsPerSample, creator);
+ else
+ return dpxCreate(filename, width, height, bitsPerSample, isLogarithmic, hasAlpha,
+ referenceWhite, referenceBlack, gamma, creator);
- f_black = convertTo(logImage->params.blackPoint, logImage->params.whitePoint, logImage->params.gamma);
- scale = 255.0 / (1.0 - f_black);
+ return 0;
+}
- for (i = 0; i <= logImage->params.blackPoint; ++i) {
- logImage->lut10[i] = 0;
+void logImageClose(LogImageFile *logImage)
+{
+ if (logImage != 0) {
+ if (logImage->file) {
+ fclose(logImage->file);
+ logImage->file = 0;
+ }
+ MEM_freeN(logImage);
}
- for (; i < logImage->params.whitePoint; ++i) {
- double f_i;
- f_i = convertTo(i, logImage->params.whitePoint, logImage->params.gamma);
- logImage->lut10[i] = (int)rint(scale * (f_i - f_black));
+}
+
+void logImageGetSize(LogImageFile *logImage, int *width, int *height, int *depth)
+{
+ *width = logImage->width;
+ *height = logImage->height;
+ *depth = logImage->depth;
+}
+
+
+/*
+ * Helper
+ */
+
+unsigned int getRowLength(int width, LogImageElement logElement)
+{
+ /* return the row length in bytes according to width and packing method */
+ switch (logElement.bitsPerSample) {
+ case 1:
+ return ((width * logElement.depth - 1) / 32 + 1) * 4;
+
+ case 8:
+ return ((width * logElement.depth - 1) / 4 + 1) * 4;
+
+ case 10:
+ if (logElement.packing == 0)
+ return ((width * logElement.depth * 10 - 1) / 32 + 1) * 4;
+ else if (logElement.packing == 1 || logElement.packing == 2)
+ return ((width * logElement.depth - 1) / 3 + 1) * 4;
+
+ case 12:
+ if (logElement.packing == 0)
+ return ((width * logElement.depth * 12 - 1) / 32 + 1) * 4;
+ else if (logElement.packing == 1 || logElement.packing == 2)
+ return width * logElement.depth * 2;
+
+ case 16:
+ return width * logElement.depth * 2;
+
+ default:
+ return 0;
}
- for (; i < 1024; ++i) {
- logImage->lut10[i] = 255;
+}
+
+
+/*
+ * Data writing
+ */
+
+int logImageSetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB)
+{
+ float *elementData;
+ int returnValue;
+
+ elementData = (float *)MEM_mallocN(logImage->width * logImage->height * logImage->depth * sizeof(float), __func__);
+ if (elementData == 0)
+ return 1;
+
+ if (convertRGBAToLogElement(data, elementData, logImage, logImage->element[0], dataIsLinearRGB) != 0) {
+ MEM_freeN(elementData);
+ return 1;
}
- for (i = 0; i < 256; ++i) {
- double f_i = f_black + (i / 255.0) * (1.0 - f_black);
- logImage->lut8[i] = convertFrom(f_i, logImage->params.whitePoint, logImage->params.gamma);
- }
-}
-
-/* set up the 10 bit to 16 bit and 16 bit to 10 bit tables */
-void
-setupLut16(LogImageFile *logImage) {
+ switch (logImage->element[0].bitsPerSample) {
+ case 8:
+ returnValue = logImageSetData8(logImage, logImage->element[0], elementData);
+ break;
+
+ case 10:
+ returnValue = logImageSetData10(logImage, logImage->element[0], elementData);
+ break;
- int i;
- double f_black;
- double scale;
+ case 12:
+ returnValue = logImageSetData12(logImage, logImage->element[0], elementData);
+ break;
- f_black = convertTo(logImage->params.blackPoint, logImage->params.whitePoint, logImage->params.gamma);
- scale = 65535.0 / (1.0 - f_black);
-
- for (i = 0; i <= logImage->params.blackPoint; ++i) {
- logImage->lut10_16[i] = 0;
- }
- for (; i < logImage->params.whitePoint; ++i) {
- double f_i;
- f_i = convertTo(i, logImage->params.whitePoint, logImage->params.gamma);
- logImage->lut10_16[i] = (int)rint(scale * (f_i - f_black));
- }
- for (; i < 1024; ++i) {
- logImage->lut10_16[i] = 65535;
- }
-
- for (i = 0; i < 65536; ++i) {
- double f_i = f_black + (i / 65535.0) * (1.0 - f_black);
- logImage->lut16_16[i] = convertFrom(f_i, logImage->params.whitePoint, logImage->params.gamma);
- }
-}
-
-/* how many longwords to hold this many pixels? */
-int
-pixelsToLongs(int numPixels) {
- return (numPixels + 2) / 3;
-}
-
-/* byte reversed float */
+ case 16:
+ returnValue = logImageSetData16(logImage, logImage->element[0], elementData);
+ break;
-typedef union {
- U32 i;
- R32 f;
-} Hack;
+ default:
+ returnValue = 1;
+ break;
+ }
-R32
-htonf(R32 f) {
- Hack hack;
- hack.f = f;
- hack.i = htonl(hack.i);
- return hack.f;
+ MEM_freeN(elementData);
+ return returnValue;
}
-R32
-ntohf(R32 f) {
- Hack hack;
- hack.f = f;
- hack.i = ntohl(hack.i);
- return hack.f;
+static int logImageSetData8(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ unsigned int rowLength = getRowLength(logImage->width, logElement);
+ unsigned char *row;
+ int x, y;
+
+ row = (unsigned char *)MEM_mallocN(rowLength, __func__);
+ if (row == 0) {
+ if (verbose) printf("DPX/Cineon: Cannot allocate row.\n");
+ return 1;
+ }
+ memset(row, 0, rowLength);
+
+ for (y = 0; y < logImage->height; y++) {
+ for (x = 0; x < logImage->width * logImage->depth; x++)
+ row[x] = (unsigned char)float_uint(data[y * logImage->width * logImage->depth + x], 255);
+
+ if (logimage_fwrite(row, rowLength, 1, logImage) == 0) {
+ if (verbose) printf("DPX/Cineon: Error while writing file.\n");
+ MEM_freeN(row);
+ return 1;
+ }
+ }
+ MEM_freeN(row);
+ return 0;
}
-#define UNDEF_FLOAT 0x7F800000
+static int logImageSetData10(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ unsigned int rowLength = getRowLength(logImage->width, logElement);
+ unsigned int pixel, index;
+ unsigned int *row;
+ int x, y, offset;
-R32
-undefined(void) {
- Hack hack;
- hack.i = UNDEF_FLOAT;
- return hack.f;
+ row = (unsigned int *)MEM_mallocN(rowLength, __func__);
+ if (row == 0) {
+ if (verbose) printf("DPX/Cineon: Cannot allocate row.\n");
+ return 1;
+ }
+
+ for (y = 0; y < logImage->height; y++) {
+ offset = 22;
+ index = 0;
+ pixel = 0;
+
+ for (x = 0; x < logImage->width * logImage->depth; x++) {
+ pixel |= (unsigned int)float_uint(data[y * logImage->width * logImage->depth + x], 1023) << offset;
+ offset -= 10;
+ if (offset < 0) {
+ row[index] = swap_uint(pixel, logImage->isMSB);
+ index++;
+ pixel = 0;
+ offset = 22;
+ }
+ }
+ if (pixel != 0)
+ row[index] = swap_uint(pixel, logImage->isMSB);
+
+ if (logimage_fwrite(row, rowLength, 1, logImage) == 0) {
+ if (verbose) printf("DPX/Cineon: Error while writing file.\n"); {
+ MEM_freeN(row);
+ return 1;
+ }
+ }
+ }
+ MEM_freeN(row);
+ return 0;
}
-/* reverse an endian-swapped U16 */
-U16
-reverseU16(U16 value) {
+static int logImageSetData12(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ unsigned int rowLength = getRowLength(logImage->width, logElement);
+ unsigned short *row;
+ int x, y;
- union {
- U16 whole;
- char part[2];
- } buff;
- char temp;
- buff.whole = value;
- temp = buff.part[0];
- buff.part[0] = buff.part[1];
- buff.part[1] = temp;
- return buff.whole;
+ row = (unsigned short *)MEM_mallocN(rowLength, __func__);
+ if (row == 0) {
+ if (verbose) printf("DPX/Cineon: Cannot allocate row.\n");
+ return 1;
+ }
+
+ for (y = 0; y < logImage->height; y++) {
+ for (x = 0; x < logImage->width * logImage->depth; x++)
+ row[x] = swap_ushort(((unsigned short)float_uint(data[y * logImage->width * logImage->depth + x], 4095)) << 4, logImage->isMSB);
+
+ if (logimage_fwrite(row, rowLength, 1, logImage) == 0) {
+ if (verbose) printf("DPX/Cineon: Error while writing file.\n");
+ MEM_freeN(row);
+ return 1;
+ }
+ }
+ MEM_freeN(row);
+ return 0;
}
-/* reverse an endian-swapped U32 */
-U32
-reverseU32(U32 value) {
+static int logImageSetData16(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ unsigned int rowLength = getRowLength(logImage->width, logElement);
+ unsigned short *row;
+ int x, y;
- union {
- U32 whole;
- char part[4];
- } buff;
- char temp;
- buff.whole = value;
- temp = buff.part[0];
- buff.part[0] = buff.part[3];
- buff.part[3] = temp;
- temp = buff.part[1];
- buff.part[1] = buff.part[2];
- buff.part[2] = temp;
- return buff.whole;
+ row = (unsigned short *)MEM_mallocN(rowLength, __func__);
+ if (row == 0) {
+ if (verbose) printf("DPX/Cineon: Cannot allocate row.\n");
+ return 1;
+ }
+
+ for (y = 0; y < logImage->height; y++) {
+ for (x = 0; x < logImage->width * logImage->depth; x++)
+ row[x] = swap_ushort((unsigned short)float_uint(data[y * logImage->width * logImage->depth + x], 65535), logImage->isMSB);
+
+ if (logimage_fwrite(row, rowLength, 1, logImage) == 0) {
+ if (verbose) printf("DPX/Cineon: Error while writing file.\n");
+ MEM_freeN(row);
+ return 1;
+ }
+ }
+ MEM_freeN(row);
+ return 0;
}
-/* reverse an endian-swapped R32 */
-R32
-reverseR32(R32 value) {
- union {
- R32 whole;
- char part[4];
- } buff;
- char temp;
- buff.whole = value;
- temp = buff.part[0];
- buff.part[0] = buff.part[3];
- buff.part[3] = temp;
- temp = buff.part[1];
- buff.part[1] = buff.part[2];
- buff.part[2] = temp;
- return buff.whole;
+/*
+ * Data reading
+ */
+
+int logImageGetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB)
+{
+ /* Fills data with 32 bits float RGBA values */
+ int i, j, returnValue, sortedElementData[8], hasAlpha;
+ float *elementData[8];
+ float *elementData_ptr[8];
+ float *mergedData;
+ unsigned int sampleIndex;
+ LogImageElement mergedElement;
+
+ /* Determine the depth of the picture and if there's a separate alpha element.
+ If the element is supported, load it into an unsigned ints array. */
+ memset(&elementData, 0, 8 * sizeof(float *));
+ hasAlpha = 0;
+
+ for (i = 0; i < logImage->numElements; i++) {
+ /* descriptor_Depth and descriptor_Composite are not supported */
+ if (logImage->element[i].descriptor != descriptor_Depth && logImage->element[i].descriptor != descriptor_Composite) {
+ /* Allocate memory */
+ elementData[i] = (float *)MEM_mallocN(logImage->width * logImage->height * logImage->element[i].depth * sizeof(float), __func__);
+ if (elementData[i] == 0) {
+ if (verbose) printf("DPX/Cineon: Cannot allocate memory for elementData[%d]\n.", i);
+ for (j = 0; j < i; j++)
+ if (elementData[j] != 0)
+ MEM_freeN(elementData[j]);
+ return 1;
+ }
+ elementData_ptr[i] = elementData[i];
+
+ /* Load data */
+ if (logImageElementGetData(logImage, logImage->element[i], elementData[i]) != 0) {
+ if (verbose) printf("DPX/Cineon: Cannot read elementData[%d]\n.", i);
+ for (j = 0; j < i; j++)
+ if (elementData[j] != 0)
+ MEM_freeN(elementData[j]);
+ return 1;
+ }
+ }
+
+ if (logImage->element[i].descriptor == descriptor_Alpha)
+ hasAlpha = 1;
+ }
+
+ /* only one element, easy case, no need to do anything */
+ if (logImage->numElements == 1) {
+ returnValue = convertLogElementToRGBA(elementData[0], data, logImage, logImage->element[0], dataIsLinearRGB);
+ MEM_freeN(elementData[0]);
+ }
+ else {
+ /* The goal here is to merge every elements into only one
+ * to recreate a classic 16 bits RGB, RGBA or YCbCr element.
+ * Unsupported elements are skipped (depth, composite) */
+
+ memcpy(&mergedElement, &logImage->element[0], sizeof(LogImageElement));
+ mergedElement.descriptor = -1;
+ mergedElement.depth = logImage->depth;
+ memset(&sortedElementData, -1, 8 * sizeof(int));
+
+ /* Try to know how to assemble the elements */
+ for (i = 0; i < logImage->numElements; i++) {
+ switch (logImage->element[i].descriptor) {
+ case descriptor_Red:
+ case descriptor_RGB:
+ if (hasAlpha == 0)
+ mergedElement.descriptor = descriptor_RGB;
+ else
+ mergedElement.descriptor = descriptor_RGBA;
+
+ sortedElementData[0] = i;
+ break;
+
+ case descriptor_Green:
+ if (hasAlpha == 0)
+ mergedElement.descriptor = descriptor_RGB;
+ else
+ mergedElement.descriptor = descriptor_RGBA;
+
+ sortedElementData[1] = i;
+ break;
+
+ case descriptor_Blue:
+ if (hasAlpha == 0)
+ mergedElement.descriptor = descriptor_RGB;
+ else
+ mergedElement.descriptor = descriptor_RGBA;
+
+ sortedElementData[2] = i;
+ break;
+
+ case descriptor_Alpha:
+ /* Alpha component is always the last one */
+ sortedElementData[mergedElement.depth - 1] = i;
+ break;
+
+ case descriptor_Luminance:
+ if (mergedElement.descriptor == -1)
+ if (hasAlpha == 0)
+ mergedElement.descriptor = descriptor_Luminance;
+ else
+ mergedElement.descriptor = descriptor_YA;
+ else if (mergedElement.descriptor == descriptor_Chrominance) {
+ if (mergedElement.depth == 2)
+ mergedElement.descriptor = descriptor_CbYCrY;
+ else if (mergedElement.depth == 3)
+ if (hasAlpha == 0)
+ mergedElement.descriptor = descriptor_CbYCr;
+ else
+ mergedElement.descriptor = descriptor_CbYACrYA;
+ else if (mergedElement.depth == 4)
+ mergedElement.descriptor = descriptor_CbYCrA;
+ }
+
+ /* Y component always in 1 except if it's alone or with alpha */
+ if (mergedElement.depth == 1 || (mergedElement.depth == 2 && hasAlpha == 1))
+ sortedElementData[0] = i;
+ else
+ sortedElementData[1] = i;
+ break;
+
+ case descriptor_Chrominance:
+ if (mergedElement.descriptor == -1)
+ mergedElement.descriptor = descriptor_Chrominance;
+ else if (mergedElement.descriptor == descriptor_Luminance) {
+ if (mergedElement.depth == 2)
+ mergedElement.descriptor = descriptor_CbYCrY;
+ else if (mergedElement.depth == 3)
+ if (hasAlpha == 0)
+ mergedElement.descriptor = descriptor_CbYCr;
+ else
+ mergedElement.descriptor = descriptor_CbYACrYA;
+ else if (mergedElement.depth == 4)
+ mergedElement.descriptor = descriptor_CbYCrA;
+ }
+
+ /* Cb and Cr always in 0 or 2 */
+ if (sortedElementData[0] == -1)
+ sortedElementData[0] = i;
+ else
+ sortedElementData[2] = i;
+ break;
+
+ case descriptor_CbYCr:
+ if (hasAlpha == 0)
+ mergedElement.descriptor = descriptor_CbYCr;
+ else
+ mergedElement.descriptor = descriptor_CbYCrA;
+
+ sortedElementData[0] = i;
+ break;
+
+ case descriptor_RGBA:
+ case descriptor_ABGR:
+ case descriptor_CbYACrYA:
+ case descriptor_CbYCrY:
+ case descriptor_CbYCrA:
+ /* I don't think these ones can be seen in a planar image */
+ mergedElement.descriptor = logImage->element[i].descriptor;
+ sortedElementData[0] = i;
+ break;
+
+ case descriptor_Depth:
+ case descriptor_Composite:
+ /* Not supported */
+ break;
+ }
+ }
+
+ mergedData = (float *)MEM_mallocN(logImage->width * logImage->height * mergedElement.depth * sizeof(float), __func__);
+ if (mergedData == 0) {
+ if (verbose) printf("DPX/Cineon: Cannot allocate mergedData.\n");
+ for (i = 0; i < logImage->numElements; i++)
+ if (elementData[i] != 0)
+ MEM_freeN(elementData[i]);
+ return 1;
+ }
+
+ sampleIndex = 0;
+ while (sampleIndex < logImage->width * logImage->height * mergedElement.depth) {
+ for (i = 0; i < logImage->numElements; i++)
+ for (j = 0; j < logImage->element[sortedElementData[i]].depth; j++)
+ mergedData[sampleIndex++] = *(elementData_ptr[sortedElementData[i]]++);
+ }
+
+ /* Done with elements data, clean-up */
+ for (i = 0; i < logImage->numElements; i++)
+ if (elementData[i] != 0)
+ MEM_freeN(elementData[i]);
+
+ returnValue = convertLogElementToRGBA(mergedData, data, logImage, mergedElement, dataIsLinearRGB);
+ MEM_freeN(mergedData);
+ }
+ return returnValue;
}
-#if 0
-/* bytes per line for images packed 3 10 bit pixels to 32 bits, 32 bit aligned */
-int
-bytesPerLine_10_4(int numPixels) {
- return ((numPixels + 2) / 3) * 4;
+static int logImageElementGetData(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ switch (logElement.bitsPerSample) {
+ case 1:
+ return logImageElementGetData1(logImage, logElement, data);
+
+ case 8:
+ return logImageElementGetData8(logImage, logElement, data);
+
+ case 10:
+ if (logElement.packing == 0)
+ return logImageElementGetData10Packed(logImage, logElement, data);
+ else if (logElement.packing == 1 || logElement.packing == 2)
+ return logImageElementGetData10(logImage, logElement, data);
+
+ case 12:
+ if (logElement.packing == 0)
+ return logImageElementGetData12Packed(logImage, logElement, data);
+ else if (logElement.packing == 1 || logElement.packing == 2)
+ return logImageElementGetData12(logImage, logElement, data);
+
+ case 16:
+ return logImageElementGetData16(logImage, logElement, data);
+
+ default:
+ /* format not supported */
+ return 1;
+ }
}
-void
-seekLine_noPadding(LogImageFile* logImage, int lineNumber) {
- int fileOffset = bytesPerLine_10_4(lineNumber * logImage->width * logImage->depth);
- int filePos = logImage->imageOffset + fileOffset;
- if (fseek(logImage->file, filePos, SEEK_SET) != 0) {
- /* complain? */
- }
-}
-
-void
-seekLine_padding(LogImageFile* logImage, int lineNumber) {
- int fileOffset = lineNumber * bytesPerLine_10_4(logImage->width * logImage->depth);
- int filePos = logImage->imageOffset + fileOffset;
- if (fseek(logImage->file, filePos, SEEK_SET) != 0) {
- /* complain? */
- }
-}
-#endif
+static int logImageElementGetData1(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ unsigned int pixel;
+ int x, y, offset;
+
+ /* seek at the right place */
+ if (logimage_fseek(logImage, logElement.dataOffset, SEEK_SET) != 0) {
+ if (verbose) printf("DPX/Cineon: Couldn't seek at %d\n", logElement.dataOffset);
+ return 1;
+ }
+
+ /* read 1 bit data padded to 32 bits */
+ for (y = 0; y < logImage->height; y++) {
+ for (x = 0; x < logImage->width * logElement.depth; x += 32) {
+ if (logimage_read_uint(&pixel, logImage) != 0) {
+ if (verbose) printf("DPX/Cineon: EOF reached\n");
+ return 1;
+ }
+ pixel = swap_uint(pixel, logImage->isMSB);
+ for (offset = 0; offset < 32 && x + offset < logImage->width; offset++)
+ data[y * logImage->width * logElement.depth + x + offset] = (float)((pixel >> offset) & 0x01);
+ }
+ }
+ return 0;
+}
+
+static int logImageElementGetData8(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ unsigned int rowLength = getRowLength(logImage->width, logElement);
+ unsigned char pixel;
+ int x, y;
+
+ /* extract required pixels */
+ for (y = 0; y < logImage->height; y++) {
+ /* 8 bits are 32-bits padded so we need to seek at each row */
+ if (logimage_fseek(logImage, logElement.dataOffset + y * rowLength, SEEK_SET) != 0) {
+ if (verbose) printf("DPX/Cineon: Couldn't seek at %d\n", logElement.dataOffset + y * rowLength);
+ return 1;
+ }
+
+ for (x = 0; x < logImage->width * logElement.depth; x++) {
+ if (logimage_read_uchar(&pixel, logImage) != 0) {
+ if (verbose) printf("DPX/Cineon: EOF reached\n");
+ return 1;
+ }
+ data[y * logImage->width * logElement.depth + x] = (float)pixel / 255.0f;
+ }
+ }
+ return 0;
+}
+
+static int logImageElementGetData10(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ unsigned int pixel;
+ int x, y, offset;
+
+ /* seek to data */
+ if (logimage_fseek(logImage, logElement.dataOffset, SEEK_SET) != 0) {
+ if (verbose) printf("DPX/Cineon: Couldn't seek at %d\n", logElement.dataOffset);
+ return 1;
+ }
+
+ if (logImage->depth == 1 && logImage->srcFormat == format_DPX) {
+ for (y = 0; y < logImage->height; y++) {
+ offset = 32;
+ for (x = 0; x < logImage->width * logElement.depth; x++) {
+ /* we need to read the next long */
+ if (offset >= 30) {
+ if (logElement.packing == 1)
+ offset = 2;
+ else if (logElement.packing == 2)
+ offset = 0;
+
+ if (logimage_read_uint(&pixel, logImage) != 0) {
+ if (verbose) printf("DPX/Cineon: EOF reached\n");
+ return 1;
+ }
+ pixel = swap_uint(pixel, logImage->isMSB);
+ }
+ data[y * logImage->width * logElement.depth + x] = (float)((pixel >> offset) & 0x3ff) / 1023.0f;
+ offset += 10;
+ }
+ }
+ }
+ else {
+ for (y = 0; y < logImage->height; y++) {
+ offset = -1;
+ for (x = 0; x < logImage->width * logElement.depth; x++) {
+ /* we need to read the next long */
+ if (offset < 0) {
+ if (logElement.packing == 1)
+ offset = 22;
+ else if (logElement.packing == 2)
+ offset = 20;
+
+ if (logimage_read_uint(&pixel, logImage) != 0) {
+ if (verbose) printf("DPX/Cineon: EOF reached\n");
+ return 1;
+ }
+ pixel = swap_uint(pixel, logImage->isMSB);
+ }
+ data[y * logImage->width * logElement.depth + x] = (float)((pixel >> offset) & 0x3ff) / 1023.0f;
+ offset -= 10;
+ }
+ }
+ }
+
+ return 0;
+}
+
+static int logImageElementGetData10Packed(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ unsigned int rowLength = getRowLength(logImage->width, logElement);
+ unsigned int pixel, oldPixel;
+ int offset, offset2, x, y;
+
+ /* converting bytes to pixels */
+ for (y = 0; y < logImage->height; y++) {
+ /* seek to data */
+ if (logimage_fseek(logImage, y * rowLength + logElement.dataOffset, SEEK_SET) != 0) {
+ if (verbose) printf("DPX/Cineon: Couldn't seek at %u\n", y * rowLength + logElement.dataOffset);
+ return 1;
+ }
+
+ oldPixel = 0;
+ offset = 0;
+ offset2 = 0;
+
+ for (x = 0; x < logImage->width * logElement.depth; x++) {
+ if (offset2 != 0) {
+ offset = 10 - offset2;
+ offset2 = 0;
+ oldPixel = 0;
+ }
+ else if (offset == 32) {
+ offset = 0;
+ }
+ else if (offset + 10 > 32) {
+ /* next pixel is on two different longs */
+ oldPixel = (pixel >> offset);
+ offset2 = 32 - offset;
+ offset = 0;
+ }
+
+ if (offset == 0) {
+ /* we need to read the next long */
+ if (logimage_read_uint(&pixel, logImage) != 0) {
+ if (verbose) printf("DPX/Cineon: EOF reached\n");
+ return 1;
+ }
+ pixel = swap_uint(pixel, logImage->isMSB);
+ }
+ data[y * logImage->width * logElement.depth + x] = (float)((((pixel << offset2) >> offset) & 0x3ff) | oldPixel) / 1023.0f;
+ offset += 10;
+ }
+ }
+ return 0;
+}
+
+static int logImageElementGetData12(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ unsigned int sampleIndex;
+ unsigned int numSamples = logImage->width * logImage->height * logElement.depth;
+ unsigned short pixel;
+
+ /* seek to data */
+ if (logimage_fseek(logImage, logElement.dataOffset, SEEK_SET) != 0) {
+ if (verbose) printf("DPX/Cineon: Couldn't seek at %d\n", logElement.dataOffset);
+ return 1;
+ }
+
+ /* convert bytes to pixels */
+ sampleIndex = 0;
+
+ for (sampleIndex = 0; sampleIndex < numSamples; sampleIndex++) {
+ if (logimage_read_ushort(&pixel, logImage) != 0) {
+ if (verbose) printf("DPX/Cineon: EOF reached\n");
+ return 1;
+ }
+ pixel = swap_ushort(pixel, logImage->isMSB);
+
+ if (logElement.packing == 1) /* padded to the right */
+ data[sampleIndex] = (float)(pixel >> 4) / 4095.0f;
+ else if (logElement.packing == 2) /* padded to the left */
+ data[sampleIndex] = (float)pixel / 4095.0f;
+ }
+ return 0;
+}
+
+static int logImageElementGetData12Packed(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ unsigned int rowLength = getRowLength(logImage->width, logElement);
+ unsigned int pixel, oldPixel;
+ int offset, offset2, x, y;
+
+ /* converting bytes to pixels */
+ for (y = 0; y < logImage->height; y++) {
+ /* seek to data */
+ if (logimage_fseek(logImage, y * rowLength + logElement.dataOffset, SEEK_SET) != 0) {
+ if (verbose) printf("DPX/Cineon: Couldn't seek at %u\n", y * rowLength + logElement.dataOffset);
+ return 1;
+ }
+
+ oldPixel = 0;
+ offset = 0;
+ offset2 = 0;
+
+ for (x = 0; x < logImage->width * logElement.depth; x++) {
+ if (offset2 != 0) {
+ offset = 12 - offset2;
+ offset2 = 0;
+ oldPixel = 0;
+ }
+ else if (offset == 32) {
+ offset = 0;
+ }
+ else if (offset + 12 > 32) {
+ /* next pixel is on two different longs */
+ oldPixel = (pixel >> offset);
+ offset2 = 32 - offset;
+ offset = 0;
+ }
+
+ if (offset == 0) {
+ /* we need to read the next long */
+ if (logimage_read_uint(&pixel, logImage) != 0) {
+ if (verbose) printf("DPX/Cineon: EOF reached\n");
+ return 1;
+ }
+ pixel = swap_uint(pixel, logImage->isMSB);
+ }
+ data[y * logImage->width * logElement.depth + x] = (float)((((pixel << offset2) >> offset) & 0xfff) | oldPixel) / 4095.0f;
+ offset += 12;
+ }
+ }
+ return 0;
+}
+
+static int logImageElementGetData16(LogImageFile *logImage, LogImageElement logElement, float *data)
+{
+ unsigned int numSamples = logImage->width * logImage->height * logElement.depth;
+ unsigned int sampleIndex;
+ unsigned short pixel;
+
+ /* seek to data */
+ if (logimage_fseek(logImage, logElement.dataOffset, SEEK_SET) != 0) {
+ if (verbose) printf("DPX/Cineon: Couldn't seek at %d\n", logElement.dataOffset);
+ return 1;
+ }
+
+ for (sampleIndex = 0; sampleIndex < numSamples; sampleIndex++) {
+ if (logimage_read_ushort(&pixel, logImage) != 0) {
+ if (verbose) printf("DPX/Cineon: EOF reached\n");
+ return 1;
+ }
+ pixel = swap_ushort(pixel, logImage->isMSB);
+ data[sampleIndex] = (float)pixel / 65535.0f;
+ }
+
+ return 0;
+}
+
+
+/*
+ * Color conversion
+ */
+
+static int getYUVtoRGBMatrix(float *matrix, LogImageElement logElement)
+{
+ float scaleY, scaleCbCr;
+ float refHighData = (float)logElement.refHighData / logElement.maxValue;
+ float refLowData = (float)logElement.refLowData / logElement.maxValue;
+
+ scaleY = 1.0f / (refHighData - refLowData);
+ scaleCbCr = scaleY * ((940.0f - 64.0f) / (960.0f - 64.0f));
+
+ switch (logElement.transfer) {
+ case 2: /* linear */
+ matrix[0] = 1.0f * scaleY;
+ matrix[1] = 1.0f * scaleCbCr;
+ matrix[2] = 1.0f * scaleCbCr;
+ matrix[3] = 1.0f * scaleY;
+ matrix[4] = 1.0f * scaleCbCr;
+ matrix[5] = 1.0f * scaleCbCr;
+ matrix[6] = 1.0f * scaleY;
+ matrix[7] = 1.0f * scaleCbCr;
+ matrix[8] = 1.0f * scaleCbCr;
+ return 0;
+
+ case 5: /* SMPTE 240M */
+ matrix[0] = 1.0000f * scaleY;
+ matrix[1] = 0.0000f * scaleCbCr;
+ matrix[2] = 1.5756f * scaleCbCr;
+ matrix[3] = 1.0000f * scaleY;
+ matrix[4] = -0.2253f * scaleCbCr;
+ matrix[5] = -0.5000f * scaleCbCr;
+ matrix[6] = 1.0000f * scaleY;
+ matrix[7] = 1.8270f * scaleCbCr;
+ matrix[8] = 0.0000f * scaleCbCr;
+ return 0;
+
+ case 6: /* CCIR 709-1 */
+ matrix[0] = 1.000000f * scaleY;
+ matrix[1] = 0.000000f * scaleCbCr;
+ matrix[2] = 1.574800f * scaleCbCr;
+ matrix[3] = 1.000000f * scaleY;
+ matrix[4] = -0.187324f * scaleCbCr;
+ matrix[5] = -0.468124f * scaleCbCr;
+ matrix[6] = 1.000000f * scaleY;
+ matrix[7] = 1.855600f * scaleCbCr;
+ matrix[8] = 0.000000f * scaleCbCr;
+ return 0;
+
+ case 7: /* CCIR 601 */
+ case 8: /* I'm not sure 7 and 8 should share the same matrix */
+ matrix[0] = 1.000000f * scaleY;
+ matrix[1] = 0.000000f * scaleCbCr;
+ matrix[2] = 1.402000f * scaleCbCr;
+ matrix[3] = 1.000000f * scaleY;
+ matrix[4] = -0.344136f * scaleCbCr;
+ matrix[5] = -0.714136f * scaleCbCr;
+ matrix[6] = 1.000000f * scaleY;
+ matrix[7] = 1.772000f * scaleCbCr;
+ matrix[8] = 0.000000f * scaleCbCr;
+ return 0;
+
+ default:
+ return 1;
+ }
+}
+
+static void getLinToLogLut(float *lut, LogImageFile *logImage, LogImageElement logElement)
+{
+ float gain, negativeFilmGamma, offset, step;
+ unsigned int i;
+
+ negativeFilmGamma = 0.6;
+ step = logElement.refHighQuantity / logElement.maxValue;
+ gain = logElement.maxValue / (1.0f - powf(10, (logImage->referenceBlack - logImage->referenceWhite) * step / negativeFilmGamma * logImage->gamma / 1.7f));
+ offset = gain - logElement.maxValue;
+
+ for (i = 0; i < (int)(logElement.maxValue + 1); i++)
+ lut[i] = (logImage->referenceWhite + log10f(powf((i + offset) / gain, 1.7f / logImage->gamma)) / (step / negativeFilmGamma)) / logElement.maxValue;
+}
+
+static void getLogToLinLut(float *lut, LogImageFile *logImage, LogImageElement logElement)
+{
+ float breakPoint, gain, kneeGain, kneeOffset, negativeFilmGamma, offset, step, softClip;
+ /* float filmGamma; unused */
+ unsigned int i;
+
+ /* Building the Log -> Lin LUT */
+ step = logElement.refHighQuantity / logElement.maxValue;
+ negativeFilmGamma = 0.6;
+
+ /* these are default values */
+ /* filmGamma = 2.2f; unused */
+ softClip = 0;
+
+ breakPoint = logImage->referenceWhite - softClip;
+ gain = logElement.maxValue / (1.0f - powf(10, (logImage->referenceBlack - logImage->referenceWhite) * step / negativeFilmGamma * logImage->gamma / 1.7f));
+ offset = gain - logElement.maxValue;
+ kneeOffset = powf(10, (breakPoint - logImage->referenceWhite) * step / negativeFilmGamma * logImage->gamma / 1.7f) * gain - offset;
+ kneeGain = (logElement.maxValue - kneeOffset) / powf(5 * softClip, softClip / 100);
+
+ for (i = 0; i < (int)(logElement.maxValue + 1); i++) {
+ if (i < logImage->referenceBlack)
+ lut[i] = 0.0f;
+ else if (i > breakPoint)
+ lut[i] = (powf(i - breakPoint, softClip / 100) * kneeGain + kneeOffset) / logElement.maxValue;
+ else
+ lut[i] = (powf(10, ((float)i - logImage->referenceWhite) * step / negativeFilmGamma * logImage->gamma / 1.7f) * gain - offset) / logElement.maxValue;
+ }
+}
+
+static void getLinToSrgbLut(float *lut, LogImageElement logElement)
+{
+ unsigned int i;
+ float col;
+
+ for (i = 0; i < (int)(logElement.maxValue + 1); i++) {
+ col = (float)i / logElement.maxValue;
+ if (col < 0.0031308f)
+ lut[i] = (col < 0.0f) ? 0.0f : col * 12.92f;
+ else
+ lut[i] = 1.055f * powf(col, 1.0f / 2.4f) - 0.055f;
+ }
+}
+
+static void getSrgbToLinLut(float *lut, LogImageElement logElement)
+{
+ unsigned int i;
+ float col;
+
+ for (i = 0; i < (int)(logElement.maxValue + 1); i++) {
+ col = (float)i / logElement.maxValue;
+ if (col < 0.04045f)
+ lut[i] = (col < 0.0f) ? 0.0f : col * (1.0f / 12.92f);
+ else
+ lut[i] = powf((col + 0.055f) * (1.0f / 1.055f), 2.4f);
+ }
+}
+
+static int convertRGBA_RGB(float *src, float *dst, LogImageFile *logImage,
+ LogImageElement logElement, int elementIsSource)
+{
+ unsigned int i;
+ float lut[65536];
+ float *src_ptr = src;
+ float *dst_ptr = dst;
+
+ switch (logElement.transfer) {
+ case transfer_UserDefined:
+ case transfer_Linear:
+ case transfer_Logarithmic:
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ *(dst_ptr++) = *(src_ptr++);
+ *(dst_ptr++) = *(src_ptr++);
+ *(dst_ptr++) = *(src_ptr++);
+ src_ptr++;
+ }
+ return 0;
+
+ case transfer_PrintingDensity:
+ if (elementIsSource == 1)
+ getLogToLinLut((float *)&lut, logImage, logElement);
+ else
+ getLinToLogLut((float *)&lut, logImage, logElement);
+
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ src_ptr++;
+ }
+ return 0;
+
+ default:
+ return 1;
+ }
+}
+
+static int convertRGB_RGBA(float *src, float *dst, LogImageFile *logImage,
+ LogImageElement logElement, int elementIsSource)
+{
+ unsigned int i;
+ float lut[65536];
+ float *src_ptr = src;
+ float *dst_ptr = dst;
+
+ switch (logElement.transfer) {
+ case transfer_UserDefined:
+ case transfer_Linear:
+ case transfer_Logarithmic:
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ *(dst_ptr++) = *(src_ptr++);
+ *(dst_ptr++) = *(src_ptr++);
+ *(dst_ptr++) = *(src_ptr++);
+ *(dst_ptr++) = 1.0f;
+ }
+ return 0;
+
+ case transfer_PrintingDensity:
+ if (elementIsSource == 1)
+ getLogToLinLut((float *)&lut, logImage, logElement);
+ else
+ getLinToLogLut((float *)&lut, logImage, logElement);
+
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(dst_ptr++) = 1.0f;
+ }
+ return 0;
+
+ default:
+ return 1;
+ }
+}
+
+static int convertRGBA_RGBA(float *src, float *dst, LogImageFile *logImage,
+ LogImageElement logElement, int elementIsSource)
+{
+ unsigned int i;
+ float lut[65536];
+ float *src_ptr = src;
+ float *dst_ptr = dst;
+
+ switch (logElement.transfer) {
+ case transfer_UserDefined:
+ case transfer_Linear:
+ case transfer_Logarithmic:
+ memcpy(dst, src, 4 * logImage->width * logImage->height * sizeof(float));
+ return 0;
+
+ case transfer_PrintingDensity:
+ if (elementIsSource == 1)
+ getLogToLinLut((float *)&lut, logImage, logElement);
+ else
+ getLinToLogLut((float *)&lut, logImage, logElement);
+
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(dst_ptr++) = *(src_ptr++);
+ }
+ return 0;
+
+ default:
+ return 1;
+ }
+}
+
+static int convertABGR_RGBA(float *src, float *dst, LogImageFile *logImage,
+ LogImageElement logElement, int elementIsSource)
+{
+ unsigned int i;
+ float lut[65536];
+ float *src_ptr = src;
+ float *dst_ptr = dst;
+
+ switch (logElement.transfer) {
+ case transfer_UserDefined:
+ case transfer_Linear:
+ case transfer_Logarithmic:
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ src_ptr += 4;
+ *(dst_ptr++) = *(src_ptr--);
+ *(dst_ptr++) = *(src_ptr--);
+ *(dst_ptr++) = *(src_ptr--);
+ *(dst_ptr++) = *(src_ptr--);
+ src_ptr += 4;
+ }
+ return 0;
+
+ case transfer_PrintingDensity:
+ if (elementIsSource == 1)
+ getLogToLinLut((float *)&lut, logImage, logElement);
+ else
+ getLinToLogLut((float *)&lut, logImage, logElement);
+
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ src_ptr += 4;
+ *(dst_ptr++) = lut[float_uint(*(src_ptr--), logElement.maxValue)];
+ *(dst_ptr++) = lut[float_uint(*(src_ptr--), logElement.maxValue)];
+ *(dst_ptr++) = lut[float_uint(*(src_ptr--), logElement.maxValue)];
+ *(dst_ptr++) = *(src_ptr--);
+ src_ptr += 4;
+ }
+ return 0;
+
+ default:
+ return 1;
+ }
+}
+
+static int convertCbYCr_RGBA(float *src, float *dst, LogImageFile *logImage, LogImageElement logElement)
+{
+ unsigned int i;
+ float conversionMatrix[9], refLowData, y, cb, cr;
+ float *src_ptr = src;
+ float *dst_ptr = dst;
+
+ if (getYUVtoRGBMatrix((float *)&conversionMatrix, logElement) != 0)
+ return 1;
+
+ refLowData = (float)logElement.refLowData / logElement.maxValue;
+
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ cb = *(src_ptr++) - 0.5f;
+ y = *(src_ptr++) - refLowData;
+ cr = *(src_ptr++) - 0.5f;
+
+ *(dst_ptr++) = clamp_float(y * conversionMatrix[0] + cb * conversionMatrix[1] + cr * conversionMatrix[2], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y * conversionMatrix[3] + cb * conversionMatrix[4] + cr * conversionMatrix[5], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y * conversionMatrix[6] + cb * conversionMatrix[7] + cr * conversionMatrix[8], 0.0f, 1.0f);
+ *(dst_ptr++) = 1.0f;
+ }
+ return 0;
+}
+
+static int convertCbYCrA_RGBA(float *src, float *dst, LogImageFile *logImage, LogImageElement logElement)
+{
+ unsigned int i;
+ float conversionMatrix[9], refLowData, y, cb, cr, a;
+ float *src_ptr = src;
+ float *dst_ptr = dst;
+
+ if (getYUVtoRGBMatrix((float *)&conversionMatrix, logElement) != 0)
+ return 1;
+
+ refLowData = (float)logElement.refLowData / logElement.maxValue;
+
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ cb = *(src_ptr++) - 0.5f;
+ y = *(src_ptr++) - refLowData;
+ cr = *(src_ptr++) - 0.5f;
+ a = *(src_ptr++);
+
+ *(dst_ptr++) = clamp_float(y * conversionMatrix[0] + cb * conversionMatrix[1] + cr * conversionMatrix[2], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y * conversionMatrix[3] + cb * conversionMatrix[4] + cr * conversionMatrix[5], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y * conversionMatrix[6] + cb * conversionMatrix[7] + cr * conversionMatrix[8], 0.0f, 1.0f);
+ *(dst_ptr++) = a;
+ }
+ return 0;
+}
+
+static int convertCbYCrY_RGBA(float *src, float *dst, LogImageFile *logImage, LogImageElement logElement)
+{
+ unsigned int i;
+ float conversionMatrix[9], refLowData, y1, y2, cb, cr;
+ float *src_ptr = src;
+ float *dst_ptr = dst;
+
+ if (getYUVtoRGBMatrix((float *)&conversionMatrix, logElement) != 0)
+ return 1;
+
+ refLowData = (float)logElement.refLowData / logElement.maxValue;
+
+ for (i = 0; i < logImage->width * logImage->height / 2; i++) {
+ cb = *(src_ptr++) - 0.5f;
+ y1 = *(src_ptr++) - refLowData;
+ cr = *(src_ptr++) - 0.5f;
+ y2 = *(src_ptr++) - refLowData;
+
+ *(dst_ptr++) = clamp_float(y1 * conversionMatrix[0] + cb * conversionMatrix[1] + cr * conversionMatrix[2], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y1 * conversionMatrix[3] + cb * conversionMatrix[4] + cr * conversionMatrix[5], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y1 * conversionMatrix[6] + cb * conversionMatrix[7] + cr * conversionMatrix[8], 0.0f, 1.0f);
+ *(dst_ptr++) = 1.0f;
+ *(dst_ptr++) = clamp_float(y2 * conversionMatrix[0] + cb * conversionMatrix[1] + cr * conversionMatrix[2], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y2 * conversionMatrix[3] + cb * conversionMatrix[4] + cr * conversionMatrix[5], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y2 * conversionMatrix[6] + cb * conversionMatrix[7] + cr * conversionMatrix[8], 0.0f, 1.0f);
+ *(dst_ptr++) = 1.0f;
+ }
+ return 0;
+}
+
+static int convertCbYACrYA_RGBA(float *src, float *dst, LogImageFile *logImage, LogImageElement logElement)
+{
+ unsigned int i;
+ float conversionMatrix[9], refLowData, y1, y2, cb, cr, a1, a2;
+ float *src_ptr = src;
+ float *dst_ptr = dst;
+
+ if (getYUVtoRGBMatrix((float *)&conversionMatrix, logElement) != 0)
+ return 1;
+
+ refLowData = (float)logElement.refLowData / logElement.maxValue;
+
+ for (i = 0; i < logImage->width * logImage->height / 2; i++) {
+ cb = *(src_ptr++) - 0.5f;
+ y1 = *(src_ptr++) - refLowData;
+ a1 = *(src_ptr++);
+ cr = *(src_ptr++) - 0.5f;
+ y2 = *(src_ptr++) - refLowData;
+ a2 = *(src_ptr++);
+
+ *(dst_ptr++) = clamp_float(y1 * conversionMatrix[0] + cb * conversionMatrix[1] + cr * conversionMatrix[2], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y1 * conversionMatrix[3] + cb * conversionMatrix[4] + cr * conversionMatrix[5], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y1 * conversionMatrix[6] + cb * conversionMatrix[7] + cr * conversionMatrix[8], 0.0f, 1.0f);
+ *(dst_ptr++) = a1;
+ *(dst_ptr++) = clamp_float(y2 * conversionMatrix[0] + cb * conversionMatrix[1] + cr * conversionMatrix[2], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y2 * conversionMatrix[3] + cb * conversionMatrix[4] + cr * conversionMatrix[5], 0.0f, 1.0f);
+ *(dst_ptr++) = clamp_float(y2 * conversionMatrix[6] + cb * conversionMatrix[7] + cr * conversionMatrix[8], 0.0f, 1.0f);
+ *(dst_ptr++) = a2;
+ }
+ return 0;
+}
+
+static int convertLuminance_RGBA(float *src, float *dst, LogImageFile *logImage, LogImageElement logElement)
+{
+ unsigned int i;
+ float conversionMatrix[9], value, refLowData;
+ float *src_ptr = src;
+ float *dst_ptr = dst;
+
+ if (getYUVtoRGBMatrix((float *)&conversionMatrix, logElement) != 0)
+ return 1;
+
+ refLowData = (float)logElement.refLowData / logElement.maxValue;
+
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ value = clamp_float((*(src_ptr++) - refLowData) * conversionMatrix[0], 0.0f, 1.0f);
+ *(dst_ptr++) = value;
+ *(dst_ptr++) = value;
+ *(dst_ptr++) = value;
+ *(dst_ptr++) = 1.0f;
+ }
+ return 0;
+}
+
+static int convertYA_RGBA(float *src, float *dst, LogImageFile *logImage, LogImageElement logElement)
+{
+ unsigned int i;
+ float conversionMatrix[9], value, refLowData;
+ float *src_ptr = src;
+ float *dst_ptr = dst;
+
+ if (getYUVtoRGBMatrix((float *)&conversionMatrix, logElement) != 0)
+ return 1;
+
+ refLowData = (float)logElement.refLowData / logElement.maxValue;
+
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ value = clamp_float((*(src_ptr++) - refLowData) * conversionMatrix[0], 0.0f, 1.0f);
+ *(dst_ptr++) = value;
+ *(dst_ptr++) = value;
+ *(dst_ptr++) = value;
+ *(dst_ptr++) = *(src_ptr++);
+ }
+ return 0;
+}
+
+static int convertLogElementToRGBA(float *src, float *dst, LogImageFile *logImage,
+ LogImageElement logElement, int dstIsLinearRGB)
+{
+ int rvalue;
+ unsigned int i;
+ float *src_ptr;
+ float *dst_ptr;
+ float lut[65536];
+
+ /* Convert data in src to linear RGBA in dst */
+ switch (logElement.descriptor) {
+ case descriptor_RGB:
+ rvalue = convertRGB_RGBA(src, dst, logImage, logElement, 1);
+ break;
+
+ case descriptor_RGBA:
+ rvalue = convertRGBA_RGBA(src, dst, logImage, logElement, 1);
+ break;
+
+ case descriptor_ABGR:
+ rvalue = convertABGR_RGBA(src, dst, logImage, logElement, 1);
+ break;
+
+ case descriptor_Luminance:
+ rvalue = convertLuminance_RGBA(src, dst, logImage, logElement);
+ break;
+
+ case descriptor_CbYCr:
+ rvalue = convertCbYCr_RGBA(src, dst, logImage, logElement);
+ break;
+
+ case descriptor_CbYCrY:
+ rvalue = convertCbYCrY_RGBA(src, dst, logImage, logElement);
+ break;
+
+ case descriptor_CbYACrYA:
+ rvalue = convertCbYACrYA_RGBA(src, dst, logImage, logElement);
+ break;
+
+ case descriptor_CbYCrA:
+ rvalue = convertCbYCrA_RGBA(src, dst, logImage, logElement);
+ break;
+
+ case descriptor_YA: /* this descriptor is for internal use only */
+ rvalue = convertYA_RGBA(src, dst, logImage, logElement);
+ break;
+
+ default:
+ return 1;
+ }
+
+ if (rvalue == 1)
+ return 1;
+ else if (dstIsLinearRGB) {
+ /* convert data from sRGB to Linear RGB via lut */
+ getSrgbToLinLut((float *)&lut, logElement);
+ src_ptr = dst; // no error here
+ dst_ptr = dst;
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(dst_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ dst_ptr++; src_ptr++;
+ }
+ }
+ return 0;
+}
+
+static int convertRGBAToLogElement(float *src, float *dst, LogImageFile *logImage,
+ LogImageElement logElement, int srcIsLinearRGB)
+{
+ unsigned int i;
+ int rvalue;
+ float *srgbSrc;
+ float *srgbSrc_ptr;
+ float *src_ptr = src;
+ float lut[65536];
+
+ if (srcIsLinearRGB != 0) {
+ /* we need to convert src to sRGB */
+ srgbSrc = (float *)MEM_mallocN(4 * logImage->width * logImage->height * sizeof(float), __func__);
+ if (srgbSrc == 0)
+ return 1;
+
+ memcpy(srgbSrc, src, 4 * logImage->width * logImage->height * sizeof(float));
+ srgbSrc_ptr = srgbSrc;
+
+ /* convert data from Linear RGB to sRGB via lut */
+ getLinToSrgbLut((float *)&lut, logElement);
+ for (i = 0; i < logImage->width * logImage->height; i++) {
+ *(srgbSrc_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(srgbSrc_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ *(srgbSrc_ptr++) = lut[float_uint(*(src_ptr++), logElement.maxValue)];
+ srgbSrc_ptr++; src_ptr++;
+ }
+ }
+ else
+ srgbSrc = src;
+
+ /* Convert linear RGBA data in src to format described by logElement in dst */
+ switch (logElement.descriptor) {
+ case descriptor_RGB:
+ rvalue = convertRGBA_RGB(srgbSrc, dst, logImage, logElement, 0);
+ break;
+
+ case descriptor_RGBA:
+ rvalue = convertRGBA_RGBA(srgbSrc, dst, logImage, logElement, 0);
+ break;
+
+ /* these ones are not supported for the moment */
+ case descriptor_ABGR:
+ case descriptor_Luminance:
+ case descriptor_CbYCr:
+ case descriptor_CbYCrY:
+ case descriptor_CbYACrYA:
+ case descriptor_CbYCrA:
+ case descriptor_YA: /* this descriptor is for internal use only */
+ default:
+ rvalue = 1;
+ }
+
+ if (srcIsLinearRGB != 0) {
+ MEM_freeN(srgbSrc);
+ }
+
+ return rvalue;
+}
diff --git a/source/blender/imbuf/intern/cineon/logImageCore.h b/source/blender/imbuf/intern/cineon/logImageCore.h
index 7d88c10c2d6..7c75f8b730b 100644
--- a/source/blender/imbuf/intern/cineon/logImageCore.h
+++ b/source/blender/imbuf/intern/cineon/logImageCore.h
@@ -1,123 +1,283 @@
/*
- * Cineon image file format library definitions.
- * Cineon and DPX common structures.
+ * Cineon image file format library definitions.
+ * Cineon and DPX common structures.
*
- * This header file contains private details.
- * User code should generally use cineonlib.h and dpxlib.h only.
- * Hmm. I thought the two formats would have more in common!
+ * This header file contains private details.
+ * User code should generally use cineonlib.h and dpxlib.h only.
+ * Hmm. I thought the two formats would have more in common!
*
- * Copyright 1999,2000,2001 David Hodson <hodsond@acm.org>
+ * Copyright 1999,2000,2001 David Hodson <hodsond@acm.org>
*
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Julien Enche.
*
*/
-#ifndef __LOGIMAGECORE_H__
-#define __LOGIMAGECORE_H__
-
/** \file blender/imbuf/intern/cineon/logImageCore.h
* \ingroup imbcineon
*/
+#ifndef __LOG_IMAGE_CORE_H__
+#define __LOG_IMAGE_CORE_H__
+
#include <stdio.h>
-#include "logImageLib.h"
+
+#include "BLO_sys_types.h"
+#include "BLI_utildefines.h"
#ifdef __cplusplus
extern "C" {
#endif
-#include "BLO_sys_types.h" // for intptr_t support
+/*
+ * Image structure
+ */
-#ifdef _MSC_VER
-#undef ntohl
-#undef htonl
-#endif
+/* There are some differences between DPX and Cineon so we need to know from what type of file the datas come from */
+enum format {
+ format_DPX,
+ format_Cineon
+};
-typedef int (GetRowFn)(LogImageFile* logImage, unsigned short* row, int lineNum);
-typedef int (SetRowFn)(LogImageFile* logImage, const unsigned short* row, int lineNum);
-typedef void (CloseFn)(LogImageFile* logImage);
+typedef struct LogImageElement
+{
+ int depth;
+ int bitsPerSample;
+ int dataOffset;
+ int packing;
+ int transfer;
+ int descriptor;
+ unsigned int refLowData;
+ unsigned int refHighData;
+ float refLowQuantity;
+ float refHighQuantity;
+ float maxValue; /* = 2^bitsPerSample - 1 (used internally, doesn't come from the file header) */
+} LogImageElement;
-struct _Log_Image_File_t_
+typedef struct LogImageFile
{
/* specified in header */
int width;
int height;
+ int numElements;
int depth;
- int bitsPerPixel;
- int imageOffset;
+ LogImageElement element[8];
- /* file buffer, measured in longwords (4 byte) */
- int lineBufferLength;
- unsigned int* lineBuffer;
-
- /* pixel buffer, holds 10 bit pixel values */
- unsigned short* pixelBuffer;
- int pixelBufferUsed;
+ /* used for log <-> lin conversion */
+ float referenceBlack;
+ float referenceWhite;
+ float gamma;
/* io stuff */
- FILE* file;
- int reading;
- int fileYPos;
+ FILE *file;
+ unsigned char *memBuffer;
+ uintptr_t memBufferSize;
+ unsigned char *memCursor;
- /* byte conversion stuff */
- LogImageByteConversionParameters params;
-#if 0
- float gamma;
- int blackPoint;
- int whitePoint;
-#endif
- unsigned char lut10[1024];
- unsigned short lut8[256];
-
- unsigned short lut10_16[1024];
- unsigned short lut16_16[65536];
-
- /* pixel access functions */
- GetRowFn* getRow;
- SetRowFn* setRow;
- CloseFn* close;
-
- unsigned char *membuffer;
- uintptr_t membuffersize;
- unsigned char *memcursor;
+ /* is the file LSB or MSB ? */
+ int isMSB;
+
+ /* DPX or Cineon ? */
+ int srcFormat;
+} LogImageFile;
+
+
+/* The SMPTE defines this code:
+ * 0 - User-defined
+ * 1 - Printing density
+ * 2 - Linear
+ * 3 - Logarithmic
+ * 4 - Unspecified video
+ * 5 - SMPTE 240M
+ * 6 - CCIR 709-1
+ * 7 - CCIR 601-2 system B or G
+ * 8 - CCIR 601-2 system M
+ * 9 - NTSC composite video
+ * 10 - PAL composite video
+ * 11 - Z linear
+ * 12 - homogeneous
+ *
+ * Note that transfer_characteristics is U8, don't need
+ * check the byte order.
+ */
+
+enum transfer {
+ transfer_UserDefined,
+ transfer_PrintingDensity,
+ transfer_Linear,
+ transfer_Logarithmic,
+ transfer_Unspecified,
+ transfer_Smpte240M,
+ transfer_Ccir7091,
+ transfer_Ccir6012BG,
+ transfer_Ccir6012M,
+ transfer_NTSC,
+ transfer_PAL,
+ transfer_ZLinear,
+ transfer_Homogeneous
+};
+
+/* The SMPTE defines this code:
+ * 0 - User-defined
+ * 1 - Red
+ * 2 - Green
+ * 3 - Blue
+ * 4 - Alpha
+ * 6 - Luminance
+ * 7 - Chrominance
+ * 8 - Depth
+ * 9 - Composite video
+ * 50 - RGB
+ * 51 - RGBA
+ * 52 - ABGR
+ * 100 - CbYCrY
+ * 101 - CbYACrYA
+ * 102 - CbYCr
+ * 103 - CbYCrA
+ * 150 - User-defined 2-component element
+ * 151 - User-defined 3-component element
+ * 152 - User-defined 4-component element
+ * 153 - User-defined 5-component element
+ * 154 - User-defined 6-component element
+ * 155 - User-defined 7-component element
+ * 156 - User-defined 8-component element
+ */
+
+enum descriptor {
+ descriptor_UserDefined,
+ descriptor_Red,
+ descriptor_Green,
+ descriptor_Blue,
+ descriptor_Alpha,
+ descriptor_Luminance = 6, /* don't ask me why there's no 5 */
+ descriptor_Chrominance,
+ descriptor_Depth,
+ descriptor_Composite,
+ descriptor_RGB = 50,
+ descriptor_RGBA,
+ descriptor_ABGR,
+ descriptor_CbYCrY = 100,
+ descriptor_CbYACrYA,
+ descriptor_CbYCr,
+ descriptor_CbYCrA,
+ descriptor_UserDefined2Elt = 150,
+ descriptor_UserDefined3Elt,
+ descriptor_UserDefined4Elt,
+ descriptor_UserDefined5Elt,
+ descriptor_UserDefined6Elt,
+ descriptor_UserDefined7Elt,
+ descriptor_UserDefined8Elt,
+ /* following descriptors are for internal use only */
+ descriptor_YA
};
-void setupLut(LogImageFile*);
-void setupLut16(LogImageFile*);
+/* int functions return 0 for OK */
-int pixelsToLongs(int numPixels);
+void logImageSetVerbose(int verbosity);
+int logImageIsDpx(const void *buffer);
+int logImageIsCineon(const void *buffer);
+LogImageFile *logImageOpenFromMemory(const unsigned char *buffer, unsigned int size);
+LogImageFile *logImageOpenFromFile(const char *filename, int cineon);
+void logImageGetSize(LogImageFile *logImage, int *width, int *height, int *depth);
+LogImageFile *logImageCreate(const char *filename, int cineon, int width, int height, int bitsPerSample,
+ int isLogarithmic, int hasAlpha, int referenceWhite, int referenceBlack,
+ float gamma, const char *creator);
+void logImageClose(LogImageFile *logImage);
-/* typedefs used in original docs */
-/* note size assumptions! */
+/* Data handling */
+unsigned int getRowLength(int width, LogImageElement logElement);
+int logImageSetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB);
+int logImageGetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB);
-typedef unsigned int U32;
-typedef unsigned short U16;
-typedef unsigned char U8;
-typedef signed int S32;
-typedef float R32;
-typedef char ASCII;
+/*
+ * Inline routines
+ */
+
+/* Endianness swapping */
+
+BLI_INLINE unsigned short swap_ushort(unsigned short x, int swap)
+{
+ if (swap != 0)
+ return (x >> 8) | (x << 8);
+ else
+ return x;
+}
+
+BLI_INLINE unsigned int swap_uint(unsigned int x, int swap)
+{
+ if (swap != 0)
+ return (x >> 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x << 24);
+ else
+ return x;
+}
+
+BLI_INLINE float swap_float(float x, int swap)
+{
+ if (swap != 0) {
+ union {
+ float f;
+ unsigned char b[4];
+ } dat1, dat2;
+
+ dat1.f = x;
+ dat2.b[0] = dat1.b[3];
+ dat2.b[1] = dat1.b[2];
+ dat2.b[2] = dat1.b[1];
+ dat2.b[3] = dat1.b[0];
+ return dat2.f;
+ }
+ else
+ return x;
+}
+
+/* Other */
+
+BLI_INLINE unsigned int clamp_uint(unsigned int x, unsigned int low, unsigned int high)
+{
+ if (x > high)
+ return high;
+ else if (x < low)
+ return low;
+ else
+ return x;
+}
+
+BLI_INLINE float clamp_float(float x, float low, float high)
+{
+ if (x > high)
+ return high;
+ else if (x < low)
+ return low;
+ else
+ return x;
+}
+
+BLI_INLINE unsigned int float_uint(float value, unsigned int max)
+{
+ if (value < 0.0f)
+ return 0;
+ else if (value > (1.0f - 0.5f / (float)max))
+ return max;
+ else
+ return (unsigned int)(((float)max * value) + 0.5f);
+}
-R32 htonf(R32 f);
-R32 ntohf(R32 f);
-R32 undefined(void);
-U16 reverseU16(U16 value);
-U32 reverseU32(U32 value);
-R32 reverseR32(R32 value);
#ifdef __cplusplus
}
#endif
-#endif /* __LOGIMAGECORE_H__ */
+#endif /* __LOG_IMAGE_CORE_H__ */
diff --git a/source/blender/imbuf/intern/cineon/logImageLib.c b/source/blender/imbuf/intern/cineon/logImageLib.c
deleted file mode 100644
index ccc6045e6e5..00000000000
--- a/source/blender/imbuf/intern/cineon/logImageLib.c
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Cineon and DPX image file format library routines.
- *
- * Copyright 1999 - 2002 David Hodson <hodsond@acm.org>
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-/** \file blender/imbuf/intern/cineon/logImageLib.c
- * \ingroup imbcineon
- */
-
-#include "cineonlib.h"
-#include "dpxlib.h"
-
-#include <stdio.h>
-#include <math.h>
-#include <stdlib.h>
-#include <time.h> /* strftime() */
-#include <sys/types.h>
-#ifdef WIN32
-#include <winsock.h>
-#else
-#include <netinet/in.h> /* htonl() */
-#endif
-#include <string.h> /* memset */
-#include "BLI_fileops.h"
-
-#define MIN_GAMMA 0.01
-#define MAX_GAMMA 99.9
-#define DEFAULT_GAMMA 1.0
-#define DEFAULT_BLACK_POINT 95
-#define DEFAULT_WHITE_POINT 685
-
-void
-logImageSetVerbose(int verbosity)
-{
- cineonSetVerbose(verbosity);
- dpxSetVerbose(verbosity);
-}
-
-LogImageFile*
-logImageOpen(const char* filename, int cineon)
-{
- if (cineon) {
- return cineonOpen(filename);
- }
- else {
- return dpxOpen(filename);
- }
- return 0;
-}
-
-LogImageFile*
-logImageOpenFromMem(unsigned char *buffer, unsigned int size, int cineon)
-{
- if (cineon) {
- return cineonOpenFromMem(buffer, size);
- }
- else {
- return dpxOpenFromMem(buffer, size);
- }
- return 0;
-}
-
-LogImageFile*
-logImageCreate(const char* filename, int cineon, int width, int height, int depth)
-{
- if (cineon) {
- return cineonCreate(filename, width, height, depth);
- }
- else {
- return dpxCreate(filename, width, height, depth);
- }
- return 0;
-}
-
-int
-logImageGetSize(const LogImageFile* logImage, int* width, int* height, int* depth)
-{
- *width = logImage->width;
- *height = logImage->height;
- *depth = logImage->depth;
- return 0;
-}
-
-int
-logImageGetByteConversionDefaults(LogImageByteConversionParameters* params)
-{
- params->gamma = DEFAULT_GAMMA;
- params->blackPoint = DEFAULT_BLACK_POINT;
- params->whitePoint = DEFAULT_WHITE_POINT;
- params->doLogarithm = 0;
- return 0;
-}
-
-int
-logImageGetByteConversion(const LogImageFile* logImage, LogImageByteConversionParameters* params)
-{
- params->gamma = logImage->params.gamma;
- params->blackPoint = logImage->params.blackPoint;
- params->whitePoint = logImage->params.whitePoint;
- params->doLogarithm = 0;
- return 0;
-}
-
-int
-logImageSetByteConversion(LogImageFile* logImage, const LogImageByteConversionParameters* params)
-{
- if ((params->gamma >= MIN_GAMMA) &&
- (params->gamma <= MAX_GAMMA) &&
- (params->blackPoint >= 0) &&
- (params->blackPoint < params->whitePoint) &&
- (params->whitePoint <= 1023))
- {
- logImage->params.gamma = params->gamma;
- logImage->params.blackPoint = params->blackPoint;
- logImage->params.whitePoint = params->whitePoint;
- logImage->params.doLogarithm = params->doLogarithm;
- setupLut16(logImage);
- return 0;
- }
- return 1;
-}
-
-int
-logImageGetRowBytes(LogImageFile* logImage, unsigned short* row, int y)
-{
- return logImage->getRow(logImage, row, y);
-}
-
-int
-logImageSetRowBytes(LogImageFile* logImage, const unsigned short* row, int y)
-{
- return logImage->setRow(logImage, row, y);
-}
-
-void
-logImageClose(LogImageFile* logImage)
-{
- logImage->close(logImage);
-}
-
-void
-logImageDump(const char* filename)
-{
-
- U32 magic;
-
- FILE* foo = BLI_fopen(filename, "rb");
- if (foo == 0) {
- return;
- }
-
- if (fread(&magic, sizeof(magic), 1, foo) == 0) {
- fclose(foo);
- return;
- }
-
- fclose(foo);
-
- if (magic == ntohl(CINEON_FILE_MAGIC)) {
-#if 0
- cineonDump(filename);
-#endif
- }
- else if (magic == ntohl(DPX_FILE_MAGIC)) {
- dpxDump(filename);
- }
-}
diff --git a/source/blender/imbuf/intern/cineon/logImageLib.h b/source/blender/imbuf/intern/cineon/logImageLib.h
index 1c24358e4ef..e69de29bb2d 100644
--- a/source/blender/imbuf/intern/cineon/logImageLib.h
+++ b/source/blender/imbuf/intern/cineon/logImageLib.h
@@ -1,87 +0,0 @@
-/*
- * Common library definitions for Cineon and DPX image files.
- *
- * Copyright 1999,2000,2001 David Hodson <hodsond@acm.org>
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef __LOGIMAGELIB_H__
-#define __LOGIMAGELIB_H__
-
-/** \file blender/imbuf/intern/cineon/logImageLib.h
- * \ingroup imbcineon
- */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Image structure. You don't care what this is.
- */
-
-typedef struct _Log_Image_File_t_ LogImageFile;
-
-/*
- * Magic numbers for normal and byte-swapped Cineon and Dpx files
- */
-
-#define CINEON_FILE_MAGIC 0x802A5FD7
-#define DPX_FILE_MAGIC 0x53445058
-
-/*
- * Image 8 bit <-> 10 bit conversion parameters.
- */
-
-typedef struct {
- float gamma;
- int blackPoint;
- int whitePoint;
- int doLogarithm;
-} LogImageByteConversionParameters;
-
-/* int functions return 0 for OK */
-
-void logImageSetVerbose(int);
-
-LogImageFile* logImageOpenFromMem(unsigned char *buffer, unsigned int size, int cineon);
-LogImageFile* logImageOpen(const char* filename, int cineon);
-int logImageGetSize(const LogImageFile* logImage, int* xsize, int* ysize, int* channels);
-LogImageFile* logImageCreate(const char* filename, int cineon, int xsize, int ysize, int channels);
-
-/* byte conversion routines for mapping logImage (usually) 10 bit values to 8 bit */
-/* see Kodak docs for details... */
-
-int logImageGetByteConversionDefaults(LogImageByteConversionParameters* params);
-int logImageGetByteConversion(const LogImageFile* logImage, LogImageByteConversionParameters* params);
-int logImageSetByteConversion(LogImageFile* logImage, const LogImageByteConversionParameters* params);
-
-/* get/set scanline of converted bytes */
-int logImageGetRowBytes(LogImageFile* logImage, unsigned short* row, int y);
-int logImageSetRowBytes(LogImageFile* logImage, const unsigned short* row, int y);
-
-/* closes file and deletes data */
-void logImageClose(LogImageFile* logImage);
-
-/* read file and dump header info */
-void logImageDump(const char* filename);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __LOGIMAGELIB_H__ */
diff --git a/source/blender/imbuf/intern/cineon/logmemfile.c b/source/blender/imbuf/intern/cineon/logmemfile.c
index a9938582f2a..3914f6dc633 100644
--- a/source/blender/imbuf/intern/cineon/logmemfile.c
+++ b/source/blender/imbuf/intern/cineon/logmemfile.c
@@ -1,21 +1,23 @@
/*
- * Cineon image file format library routines.
+ * Cineon image file format library routines.
*
- * Copyright 2006 Joseph Eagar (joeedh@gmail.com)
+ * Copyright 2006 Joseph Eagar (joeedh@gmail.com)
*
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Julien Enche.
*
*/
@@ -23,64 +25,102 @@
* \ingroup imbcineon
*/
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "logImageCore.h"
+#include "logmemfile.h"
-#include "logmemfile.h" /* own include */
-
-int logimage_fseek(void* logfile, intptr_t offsett, int origin)
-{
- struct _Log_Image_File_t_ *file = (struct _Log_Image_File_t_*) logfile;
- intptr_t offset = offsett;
-
- if (file->file) fseek(file->file, offset, origin);
- else { /*we're seeking in memory*/
- if (origin==SEEK_SET) {
- if (offset > file->membuffersize) return 1;
- file->memcursor = file->membuffer + offset;
+int logimage_fseek(LogImageFile *logFile, intptr_t offset, int origin)
+{
+ if (logFile->file)
+ fseek(logFile->file, offset, origin);
+ else { /* we're seeking in memory */
+ if (origin == SEEK_SET) {
+ if (offset > logFile->memBufferSize)
+ return 1;
+ logFile->memCursor = logFile->memBuffer + offset;
}
- else if (origin==SEEK_END) {
- if (offset > file->membuffersize) return 1;
- file->memcursor = (file->membuffer + file->membuffersize) - offset;
+ else if (origin == SEEK_END) {
+ if (offset > logFile->memBufferSize)
+ return 1;
+ logFile->memCursor = (logFile->memBuffer + logFile->memBufferSize) - offset;
}
- else if (origin==SEEK_CUR) {
- uintptr_t pos = (uintptr_t)file->membuffer - (uintptr_t)file->memcursor;
- if (pos + offset > file->membuffersize) return 1;
- if (pos < 0) return 1;
- file->memcursor += offset;
+ else if (origin == SEEK_CUR) {
+ uintptr_t pos = (uintptr_t)logFile->memCursor - (uintptr_t)logFile->memBuffer;
+ if (pos + offset > logFile->memBufferSize || pos < 0)
+ return 1;
+
+ logFile->memCursor += offset;
}
}
return 0;
}
-int logimage_fwrite(void *buffer, unsigned int size, unsigned int count, void *logfile)
+int logimage_fwrite(void *buffer, size_t size, unsigned int count, LogImageFile *logFile)
{
- struct _Log_Image_File_t_ *file = (struct _Log_Image_File_t_*) logfile;
- if (file->file) return fwrite(buffer, size, count, file->file);
- else { /*we're writing to memory*/
- /*do nothing as this isn't supported yet*/
+ if (logFile->file)
+ return fwrite(buffer, size, count, logFile->file);
+ else { /* we're writing to memory */
+ /* do nothing as this isn't supported yet */
return count;
}
}
-int logimage_fread(void *buffer, unsigned int size, unsigned int count, void *logfile)
+int logimage_fread(void *buffer, size_t size, unsigned int count, LogImageFile *logFile)
{
- struct _Log_Image_File_t_ *file = (struct _Log_Image_File_t_*) logfile;
- if (file->file) return fread(buffer, size, count, file->file);
- else { /*we're reading from memory*/
- int i;
- /* we convert ot uchar just on the off chance some platform can't handle
- * pointer arithmetic with type (void*). */
- unsigned char *buf = (unsigned char *) buffer;
-
- for (i=0; i<count; i++) {
- memcpy(buf, file->memcursor, size);
- file->memcursor += size;
- buf += size;
+ if (logFile->file) {
+ return fread(buffer, size, count, logFile->file);
+ }
+ else { /* we're reading from memory */
+ unsigned char *buf = (unsigned char *)buffer;
+ uintptr_t pos = (uintptr_t)logFile->memCursor - (uintptr_t)logFile->memBuffer;
+ size_t total_size = size * count;
+ if (pos + total_size > logFile->memBufferSize) {
+ /* how many elements can we read without overflow ? */
+ count = (logFile->memBufferSize - pos) / size;
+ /* recompute the size */
+ total_size = size * count;
}
+
+ if (total_size != 0)
+ memcpy(buf, logFile->memCursor, total_size);
+
return count;
}
}
+
+int logimage_read_uchar(unsigned char *x, LogImageFile *logFile)
+{
+ uintptr_t pos = (uintptr_t)logFile->memCursor - (uintptr_t)logFile->memBuffer;
+ if (pos + sizeof(unsigned char) > logFile->memBufferSize)
+ return 1;
+
+ *x = *(unsigned char *)logFile->memCursor;
+ logFile->memCursor += sizeof(unsigned char);
+ return 0;
+}
+
+int logimage_read_ushort(unsigned short *x, LogImageFile *logFile)
+{
+ uintptr_t pos = (uintptr_t)logFile->memCursor - (uintptr_t)logFile->memBuffer;
+ if (pos + sizeof(unsigned short) > logFile->memBufferSize)
+ return 1;
+
+ *x = *(unsigned short *)logFile->memCursor;
+ logFile->memCursor += sizeof(unsigned short);
+ return 0;
+}
+
+int logimage_read_uint(unsigned int *x, LogImageFile *logFile)
+{
+ uintptr_t pos = (uintptr_t)logFile->memCursor - (uintptr_t)logFile->memBuffer;
+ if (pos + sizeof(unsigned int) > logFile->memBufferSize)
+ return 1;
+
+ *x = *(unsigned int *)logFile->memCursor;
+ logFile->memCursor += sizeof(unsigned int);
+ return 0;
+}
diff --git a/source/blender/imbuf/intern/cineon/logmemfile.h b/source/blender/imbuf/intern/cineon/logmemfile.h
index df3589a70d3..068a53e641b 100644
--- a/source/blender/imbuf/intern/cineon/logmemfile.h
+++ b/source/blender/imbuf/intern/cineon/logmemfile.h
@@ -1,33 +1,43 @@
/*
- * Cineon image file format library routines.
+ * Cineon image file format library routines.
*
- * Copyright 2006 Joseph Eagar (joeedh@gmail.com)
+ * Copyright 2006 Joseph Eagar (joeedh@gmail.com)
*
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the Free
- * Software Foundation; either version 2 of the License, or (at your option)
- * any later version.
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * for more details.
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Julien Enche.
*
*/
-
-#ifndef __LOGMEMFILE_H__
-#define __LOGMEMFILE_H__
/** \file blender/imbuf/intern/cineon/logmemfile.h
* \ingroup imbcineon
*/
-int logimage_fseek(void* logfile, intptr_t offsett, int origin);
-int logimage_fwrite(void *buffer, unsigned int size, unsigned int count, void *logfile);
-int logimage_fread(void *buffer, unsigned int size, unsigned int count, void *logfile);
-#endif /* __LOGMEMFILE_H__ */
+#ifndef __LOGMEMFILE_H__
+#define __LOGMEMFILE_H__
+
+#include "logImageCore.h"
+
+#include <stdlib.h>
+
+int logimage_fseek(LogImageFile *logFile, intptr_t offset, int origin);
+int logimage_fwrite(void *buffer, size_t size, unsigned int count, LogImageFile *logFile);
+int logimage_fread(void *buffer, size_t size, unsigned int count, LogImageFile *logFile);
+int logimage_read_uchar(unsigned char *x, LogImageFile *logFile);
+int logimage_read_ushort(unsigned short *x, LogImageFile *logFile);
+int logimage_read_uint(unsigned int *x, LogImageFile *logFile);
+
+#endif /* __LOGMEMFILE_H__ */
diff --git a/source/blender/imbuf/intern/colormanagement.c b/source/blender/imbuf/intern/colormanagement.c
index 6db45f0308a..6581987aed7 100644
--- a/source/blender/imbuf/intern/colormanagement.c
+++ b/source/blender/imbuf/intern/colormanagement.c
@@ -51,6 +51,7 @@
#include "MEM_guardedalloc.h"
#include "BLI_blenlib.h"
+#include "BLI_fileops.h"
#include "BLI_math.h"
#include "BLI_math_color.h"
#include "BLI_path_util.h"
@@ -59,6 +60,7 @@
#include "BKE_colortools.h"
#include "BKE_context.h"
+#include "BKE_image.h"
#include "BKE_utildefines.h"
#include "BKE_main.h"
@@ -68,7 +70,8 @@
/*********************** Global declarations *************************/
-#define MAX_COLORSPACE_NAME 64
+#define MAX_COLORSPACE_NAME 64
+#define DISPLAY_BUFFER_CHANNELS 4
/* ** list of all supported color spaces, displays and views */
static char global_role_scene_linear[MAX_COLORSPACE_NAME];
@@ -86,9 +89,17 @@ static int global_tot_colorspace = 0;
static int global_tot_display = 0;
static int global_tot_view = 0;
+/* lock used by pre-cached processors getters, so processor wouldn't
+ * be created several times
+ * LOCK_COLORMANAGE can not be used since this mutex could be needed to
+ * be locked before pre-cached processor are creating
+ */
+static pthread_mutex_t processor_lock = BLI_MUTEX_INITIALIZER;
+
typedef struct ColormanageProcessor {
- ConstProcessorRcPtr *processor;
+ OCIO_ConstProcessorRcPtr *processor;
CurveMapping *curve_mapping;
+ int is_data_result;
} ColormanageProcessor;
/*********************** Color managed cache *************************/
@@ -329,8 +340,7 @@ static unsigned char *colormanage_cache_get(ImBuf *ibuf, const ColormanageCacheV
ColormnaageCacheData *cache_data;
BLI_assert(cache_ibuf->x == ibuf->x &&
- cache_ibuf->y == ibuf->y &&
- cache_ibuf->channels == ibuf->channels);
+ cache_ibuf->y == ibuf->y);
/* only buffers with different color space conversions are being stored
* in cache separately. buffer which were used only different exposure/gamma
@@ -411,12 +421,15 @@ static void colormanage_cache_handle_release(void *cache_handle)
/*********************** Initialization / De-initialization *************************/
-static void colormanage_role_color_space_name_get(ConstConfigRcPtr *config, char *colorspace_name, const char *role)
+static void colormanage_role_color_space_name_get(OCIO_ConstConfigRcPtr *config, char *colorspace_name, const char *role, const char *backup_role)
{
- ConstColorSpaceRcPtr *ociocs;
+ OCIO_ConstColorSpaceRcPtr *ociocs;
ociocs = OCIO_configGetColorSpace(config, role);
+ if (!ociocs && backup_role)
+ ociocs = OCIO_configGetColorSpace(config, backup_role);
+
if (ociocs) {
const char *name = OCIO_colorSpaceGetName(ociocs);
@@ -429,33 +442,34 @@ static void colormanage_role_color_space_name_get(ConstConfigRcPtr *config, char
}
}
-static void colormanage_load_config(ConstConfigRcPtr *config)
+static void colormanage_load_config(OCIO_ConstConfigRcPtr *config)
{
int tot_colorspace, tot_display, tot_display_view, index, viewindex, viewindex2;
const char *name;
/* get roles */
- colormanage_role_color_space_name_get(config, global_role_scene_linear, OCIO_ROLE_SCENE_LINEAR);
- colormanage_role_color_space_name_get(config, global_role_color_picking, OCIO_ROLE_COLOR_PICKING);
- colormanage_role_color_space_name_get(config, global_role_texture_painting, OCIO_ROLE_TEXTURE_PAINT);
- colormanage_role_color_space_name_get(config, global_role_default_sequencer, OCIO_ROLE_DEFAULT_SEQUENCER);
- colormanage_role_color_space_name_get(config, global_role_default_byte, OCIO_ROLE_DEFAULT_BYTE);
- colormanage_role_color_space_name_get(config, global_role_default_float, OCIO_ROLE_DEFAULT_FLOAT);
+ colormanage_role_color_space_name_get(config, global_role_scene_linear, OCIO_ROLE_SCENE_LINEAR, NULL);
+ colormanage_role_color_space_name_get(config, global_role_color_picking, OCIO_ROLE_COLOR_PICKING, NULL);
+ colormanage_role_color_space_name_get(config, global_role_texture_painting, OCIO_ROLE_TEXTURE_PAINT, NULL);
+ colormanage_role_color_space_name_get(config, global_role_default_sequencer, OCIO_ROLE_DEFAULT_SEQUENCER, OCIO_ROLE_SCENE_LINEAR);
+ colormanage_role_color_space_name_get(config, global_role_default_byte, OCIO_ROLE_DEFAULT_BYTE, OCIO_ROLE_TEXTURE_PAINT);
+ colormanage_role_color_space_name_get(config, global_role_default_float, OCIO_ROLE_DEFAULT_FLOAT, OCIO_ROLE_SCENE_LINEAR);
/* load colorspaces */
tot_colorspace = OCIO_configGetNumColorSpaces(config);
for (index = 0 ; index < tot_colorspace; index++) {
- ConstColorSpaceRcPtr *ocio_colorspace;
+ OCIO_ConstColorSpaceRcPtr *ocio_colorspace;
const char *description;
- int is_invertible;
+ int is_invertible, is_data;
name = OCIO_configGetColorSpaceNameByIndex(config, index);
ocio_colorspace = OCIO_configGetColorSpace(config, name);
description = OCIO_colorSpaceGetDescription(ocio_colorspace);
is_invertible = OCIO_colorSpaceIsInvertible(ocio_colorspace);
+ is_data = OCIO_colorSpaceIsData(ocio_colorspace);
- colormanage_colorspace_add(name, description, is_invertible);
+ colormanage_colorspace_add(name, description, is_invertible, is_data);
OCIO_colorSpaceRelease(ocio_colorspace);
}
@@ -509,10 +523,10 @@ static void colormanage_free_config(void)
/* free precomputer processors */
if (colorspace->to_scene_linear)
- OCIO_processorRelease((ConstProcessorRcPtr *) colorspace->to_scene_linear);
+ OCIO_processorRelease((OCIO_ConstProcessorRcPtr *) colorspace->to_scene_linear);
if (colorspace->from_scene_linear)
- OCIO_processorRelease((ConstProcessorRcPtr *) colorspace->from_scene_linear);
+ OCIO_processorRelease((OCIO_ConstProcessorRcPtr *) colorspace->from_scene_linear);
/* free color space itself */
MEM_freeN(colorspace);
@@ -527,10 +541,10 @@ static void colormanage_free_config(void)
/* free precomputer processors */
if (display->to_scene_linear)
- OCIO_processorRelease((ConstProcessorRcPtr *) display->to_scene_linear);
+ OCIO_processorRelease((OCIO_ConstProcessorRcPtr *) display->to_scene_linear);
if (display->from_scene_linear)
- OCIO_processorRelease((ConstProcessorRcPtr *) display->from_scene_linear);
+ OCIO_processorRelease((OCIO_ConstProcessorRcPtr *) display->from_scene_linear);
/* free list of views */
BLI_freelistN(&display->views);
@@ -541,14 +555,18 @@ static void colormanage_free_config(void)
/* free views */
BLI_freelistN(&global_views);
+
+ OCIO_exit();
}
-void IMB_colormanagement_init(void)
+void colormanagement_init(void)
{
const char *ocio_env;
const char *configdir;
char configfile[FILE_MAX];
- ConstConfigRcPtr *config = NULL;
+ OCIO_ConstConfigRcPtr *config = NULL;
+
+ OCIO_init();
ocio_env = getenv("OCIO");
@@ -558,13 +576,29 @@ void IMB_colormanagement_init(void)
if (config == NULL) {
configdir = BLI_get_folder(BLENDER_DATAFILES, "colormanagement");
- if (configdir) {
+ if (configdir) {
BLI_join_dirfile(configfile, sizeof(configfile), configdir, BCM_CONFIG_FILE);
+#ifdef WIN32
+ {
+ /* quite a hack to support loading configuration from path with non-acii symbols */
+
+ char short_name[256];
+ BLI_get_short_name(short_name, configfile);
+ config = OCIO_configCreateFromFile(short_name);
+ }
+#else
config = OCIO_configCreateFromFile(configfile);
+#endif
}
}
+ if (config == NULL) {
+ printf("Color management: using fallback mode for management\n");
+
+ config = OCIO_configCreateFallback();
+ }
+
if (config) {
OCIO_setCurrentConfig(config);
@@ -576,7 +610,7 @@ void IMB_colormanagement_init(void)
BLI_init_srgb_conversion();
}
-void IMB_colormanagement_exit(void)
+void colormanagement_exit(void)
{
colormanage_free_config();
}
@@ -624,18 +658,39 @@ static void display_transform_get_from_ctx(const bContext *C, ColorManagedViewSe
}
}
-static ConstProcessorRcPtr *create_display_buffer_processor(const char *view_transform, const char *display,
- float exposure, float gamma)
+static const char *display_transform_get_colorspace_name(const ColorManagedViewSettings *view_settings,
+ const ColorManagedDisplaySettings *display_settings)
{
- ConstConfigRcPtr *config = OCIO_getCurrentConfig();
- DisplayTransformRcPtr *dt;
- ConstProcessorRcPtr *processor;
+ OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
- if (!config) {
- /* there's no valid OCIO configuration, can't create processor */
+ const char *display = display_settings->display_device;
+ const char *view = view_settings->view_transform;
+ const char *colorspace_name;
- return NULL;
- }
+ colorspace_name = OCIO_configGetDisplayColorSpaceName(config, display, view);
+
+ OCIO_configRelease(config);
+
+ return colorspace_name;
+}
+
+static ColorSpace *display_transform_get_colorspace(const ColorManagedViewSettings *view_settings,
+ const ColorManagedDisplaySettings *display_settings)
+{
+ const char *colorspace_name = display_transform_get_colorspace_name(view_settings, display_settings);
+
+ if (colorspace_name)
+ return colormanage_colorspace_get_named(colorspace_name);
+
+ return NULL;
+}
+
+static OCIO_ConstProcessorRcPtr *create_display_buffer_processor(const char *view_transform, const char *display,
+ float exposure, float gamma)
+{
+ OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
+ OCIO_DisplayTransformRcPtr *dt;
+ OCIO_ConstProcessorRcPtr *processor;
dt = OCIO_createDisplayTransform();
@@ -646,7 +701,7 @@ static ConstProcessorRcPtr *create_display_buffer_processor(const char *view_tra
/* fstop exposure control */
if (exposure != 0.0f) {
- MatrixTransformRcPtr *mt;
+ OCIO_MatrixTransformRcPtr *mt;
float gain = powf(2.0f, exposure);
const float scale4f[] = {gain, gain, gain, gain};
float m44[16], offset4[4];
@@ -654,25 +709,25 @@ static ConstProcessorRcPtr *create_display_buffer_processor(const char *view_tra
OCIO_matrixTransformScale(m44, offset4, scale4f);
mt = OCIO_createMatrixTransform();
OCIO_matrixTransformSetValue(mt, m44, offset4);
- OCIO_displayTransformSetLinearCC(dt, (ConstTransformRcPtr *) mt);
+ OCIO_displayTransformSetLinearCC(dt, (OCIO_ConstTransformRcPtr *) mt);
OCIO_matrixTransformRelease(mt);
}
/* post-display gamma transform */
if (gamma != 1.0f) {
- ExponentTransformRcPtr *et;
+ OCIO_ExponentTransformRcPtr *et;
float exponent = 1.0f / MAX2(FLT_EPSILON, gamma);
const float exponent4f[] = {exponent, exponent, exponent, exponent};
et = OCIO_createExponentTransform();
OCIO_exponentTransformSetValue(et, exponent4f);
- OCIO_displayTransformSetDisplayCC(dt, (ConstTransformRcPtr *) et);
+ OCIO_displayTransformSetDisplayCC(dt, (OCIO_ConstTransformRcPtr *) et);
OCIO_exponentTransformRelease(et);
}
- processor = OCIO_configGetProcessor(config, (ConstTransformRcPtr *) dt);
+ processor = OCIO_configGetProcessor(config, (OCIO_ConstTransformRcPtr *) dt);
OCIO_displayTransformRelease(dt);
OCIO_configRelease(config);
@@ -680,17 +735,11 @@ static ConstProcessorRcPtr *create_display_buffer_processor(const char *view_tra
return processor;
}
-static ConstProcessorRcPtr *create_colorspace_transform_processor(const char *from_colorspace,
+static OCIO_ConstProcessorRcPtr *create_colorspace_transform_processor(const char *from_colorspace,
const char *to_colorspace)
{
- ConstConfigRcPtr *config = OCIO_getCurrentConfig();
- ConstProcessorRcPtr *processor;
-
- if (!config) {
- /* there's no valid OCIO configuration, can't create processor */
-
- return NULL;
- }
+ OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
+ OCIO_ConstProcessorRcPtr *processor;
processor = OCIO_configGetProcessorWithNames(config, from_colorspace, to_colorspace);
@@ -699,49 +748,49 @@ static ConstProcessorRcPtr *create_colorspace_transform_processor(const char *fr
return processor;
}
-static ConstProcessorRcPtr *colorspace_to_scene_linear_processor(ColorSpace *colorspace)
+static OCIO_ConstProcessorRcPtr *colorspace_to_scene_linear_processor(ColorSpace *colorspace)
{
if (colorspace->to_scene_linear == NULL) {
- BLI_lock_thread(LOCK_COLORMANAGE);
+ BLI_mutex_lock(&processor_lock);
if (colorspace->to_scene_linear == NULL) {
- ConstProcessorRcPtr *to_scene_linear;
+ OCIO_ConstProcessorRcPtr *to_scene_linear;
to_scene_linear = create_colorspace_transform_processor(colorspace->name, global_role_scene_linear);
- colorspace->to_scene_linear = (struct ConstProcessorRcPtr *) to_scene_linear;
+ colorspace->to_scene_linear = (struct OCIO_ConstProcessorRcPtr *) to_scene_linear;
}
- BLI_unlock_thread(LOCK_COLORMANAGE);
+ BLI_mutex_unlock(&processor_lock);
}
- return (ConstProcessorRcPtr *) colorspace->to_scene_linear;
+ return (OCIO_ConstProcessorRcPtr *) colorspace->to_scene_linear;
}
-static ConstProcessorRcPtr *colorspace_from_scene_linear_processor(ColorSpace *colorspace)
+static OCIO_ConstProcessorRcPtr *colorspace_from_scene_linear_processor(ColorSpace *colorspace)
{
if (colorspace->from_scene_linear == NULL) {
- BLI_lock_thread(LOCK_COLORMANAGE);
+ BLI_mutex_lock(&processor_lock);
if (colorspace->from_scene_linear == NULL) {
- ConstProcessorRcPtr *from_scene_linear;
+ OCIO_ConstProcessorRcPtr *from_scene_linear;
from_scene_linear = create_colorspace_transform_processor(global_role_scene_linear, colorspace->name);
- colorspace->from_scene_linear = (struct ConstProcessorRcPtr *) from_scene_linear;
+ colorspace->from_scene_linear = (struct OCIO_ConstProcessorRcPtr *) from_scene_linear;
}
- BLI_unlock_thread(LOCK_COLORMANAGE);
+ BLI_mutex_unlock(&processor_lock);
}
- return (ConstProcessorRcPtr *) colorspace->from_scene_linear;
+ return (OCIO_ConstProcessorRcPtr *) colorspace->from_scene_linear;
}
-static ConstProcessorRcPtr *display_from_scene_linear_processor(ColorManagedDisplay *display)
+static OCIO_ConstProcessorRcPtr *display_from_scene_linear_processor(ColorManagedDisplay *display)
{
if (display->from_scene_linear == NULL) {
- BLI_lock_thread(LOCK_COLORMANAGE);
+ BLI_mutex_lock(&processor_lock);
if (display->from_scene_linear == NULL) {
const char *view_name = colormanage_view_get_default_name(display);
- ConstConfigRcPtr *config = OCIO_getCurrentConfig();
- ConstProcessorRcPtr *processor = NULL;
+ OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
+ OCIO_ConstProcessorRcPtr *processor = NULL;
if (view_name && config) {
const char *view_colorspace = OCIO_configGetDisplayColorSpaceName(config, display->name, view_name);
@@ -750,24 +799,24 @@ static ConstProcessorRcPtr *display_from_scene_linear_processor(ColorManagedDisp
OCIO_configRelease(config);
}
- display->from_scene_linear = (struct ConstProcessorRcPtr *) processor;
+ display->from_scene_linear = (struct OCIO_ConstProcessorRcPtr *) processor;
}
- BLI_unlock_thread(LOCK_COLORMANAGE);
+ BLI_mutex_unlock(&processor_lock);
}
- return (ConstProcessorRcPtr *) display->from_scene_linear;
+ return (OCIO_ConstProcessorRcPtr *) display->from_scene_linear;
}
-static ConstProcessorRcPtr *display_to_scene_linear_processor(ColorManagedDisplay *display)
+static OCIO_ConstProcessorRcPtr *display_to_scene_linear_processor(ColorManagedDisplay *display)
{
if (display->to_scene_linear == NULL) {
- BLI_lock_thread(LOCK_COLORMANAGE);
+ BLI_mutex_lock(&processor_lock);
if (display->to_scene_linear == NULL) {
const char *view_name = colormanage_view_get_default_name(display);
- ConstConfigRcPtr *config = OCIO_getCurrentConfig();
- ConstProcessorRcPtr *processor = NULL;
+ OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
+ OCIO_ConstProcessorRcPtr *processor = NULL;
if (view_name && config) {
const char *view_colorspace = OCIO_configGetDisplayColorSpaceName(config, display->name, view_name);
@@ -776,23 +825,25 @@ static ConstProcessorRcPtr *display_to_scene_linear_processor(ColorManagedDispla
OCIO_configRelease(config);
}
- display->to_scene_linear = (struct ConstProcessorRcPtr *) processor;
+ display->to_scene_linear = (struct OCIO_ConstProcessorRcPtr *) processor;
}
- BLI_unlock_thread(LOCK_COLORMANAGE);
+ BLI_mutex_unlock(&processor_lock);
}
- return (ConstProcessorRcPtr *) display->to_scene_linear;
+ return (OCIO_ConstProcessorRcPtr *) display->to_scene_linear;
}
static void init_default_view_settings(const ColorManagedDisplaySettings *display_settings,
ColorManagedViewSettings *view_settings)
{
ColorManagedDisplay *display;
- ColorManagedView *default_view;
+ ColorManagedView *default_view = NULL;
display = colormanage_display_get_named(display_settings->display_device);
- default_view = colormanage_view_get_default(display);
+
+ if (display)
+ default_view = colormanage_view_get_default(display);
if (default_view)
BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
@@ -837,6 +888,13 @@ void colormanage_imbuf_set_default_spaces(ImBuf *ibuf)
void colormanage_imbuf_make_linear(ImBuf *ibuf, const char *from_colorspace)
{
+ ColorSpace *colorspace = colormanage_colorspace_get_named(from_colorspace);
+
+ if (colorspace->is_data) {
+ ibuf->colormanage_flag |= IMB_COLORMANAGE_IS_DATA;
+ return;
+ }
+
if (ibuf->rect_float) {
const char *to_colorspace = global_role_scene_linear;
int predivide = ibuf->flags & IB_cm_predivide;
@@ -874,11 +932,13 @@ static void colormanage_check_view_settings(ColorManagedDisplaySettings *display
ColorManagedViewSettings *view_settings, const char *what)
{
ColorManagedDisplay *display;
- ColorManagedView *default_view;
+ ColorManagedView *default_view = NULL;
if (view_settings->view_transform[0] == '\0') {
display = colormanage_display_get_named(display_settings->display_device);
- default_view = colormanage_view_get_default(display);
+
+ if (display)
+ default_view = colormanage_view_get_default(display);
if (default_view)
BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
@@ -888,7 +948,9 @@ static void colormanage_check_view_settings(ColorManagedDisplaySettings *display
if (!view) {
display = colormanage_display_get_named(display_settings->display_device);
- default_view = colormanage_view_get_default(display);
+
+ if (display)
+ default_view = colormanage_view_get_default(display);
if (default_view) {
printf("Color management: %s view \"%s\" not found, setting default \"%s\".\n",
@@ -970,10 +1032,11 @@ void IMB_colormanagement_validate_settings(ColorManagedDisplaySettings *display_
ColorManagedViewSettings *view_settings)
{
ColorManagedDisplay *display;
- ColorManagedView *default_view;
+ ColorManagedView *default_view = NULL;
LinkData *view_link;
display = colormanage_display_get_named(display_settings->display_device);
+
default_view = colormanage_view_get_default(display);
for (view_link = display->views.first; view_link; view_link = view_link->next) {
@@ -983,7 +1046,7 @@ void IMB_colormanagement_validate_settings(ColorManagedDisplaySettings *display_
break;
}
- if (view_link == NULL)
+ if (view_link == NULL && default_view)
BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
}
@@ -1016,6 +1079,40 @@ const char *IMB_colormanagement_role_colorspace_name_get(int role)
return NULL;
}
+void IMB_colormanagement_check_is_data(ImBuf *ibuf, const char *name)
+{
+ ColorSpace *colorspace = colormanage_colorspace_get_named(name);
+
+ if (colorspace->is_data)
+ ibuf->colormanage_flag |= IMB_COLORMANAGE_IS_DATA;
+ else
+ ibuf->colormanage_flag &= ~IMB_COLORMANAGE_IS_DATA;
+}
+
+void IMB_colormanagement_assign_float_colorspace(ImBuf *ibuf, const char *name)
+{
+ ColorSpace *colorspace = colormanage_colorspace_get_named(name);
+
+ ibuf->float_colorspace = colorspace;
+
+ if (colorspace->is_data)
+ ibuf->colormanage_flag |= IMB_COLORMANAGE_IS_DATA;
+ else
+ ibuf->colormanage_flag &= ~IMB_COLORMANAGE_IS_DATA;
+}
+
+void IMB_colormanagement_assign_rect_colorspace(ImBuf *ibuf, const char *name)
+{
+ ColorSpace *colorspace = colormanage_colorspace_get_named(name);
+
+ ibuf->rect_colorspace = colorspace;
+
+ if (colorspace->is_data)
+ ibuf->colormanage_flag |= IMB_COLORMANAGE_IS_DATA;
+ else
+ ibuf->colormanage_flag &= ~IMB_COLORMANAGE_IS_DATA;
+}
+
/*********************** Threaded display buffer transform routines *************************/
typedef struct DisplayBufferThread {
@@ -1034,6 +1131,7 @@ typedef struct DisplayBufferThread {
int channels;
float dither;
int predivide;
+ int is_data;
const char *byte_colorspace;
const char *float_colorspace;
@@ -1063,8 +1161,10 @@ static void display_buffer_init_handle(void *handle_v, int start_line, int tot_l
int predivide = ibuf->flags & IB_cm_predivide;
int channels = ibuf->channels;
float dither = ibuf->dither;
+ int is_data = ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA;
int offset = channels * start_line * ibuf->x;
+ int display_buffer_byte_offset = DISPLAY_BUFFER_CHANNELS * start_line * ibuf->x;
memset(handle, 0, sizeof(DisplayBufferThread));
@@ -1080,7 +1180,7 @@ static void display_buffer_init_handle(void *handle_v, int start_line, int tot_l
handle->display_buffer = init_data->display_buffer + offset;
if (init_data->display_buffer_byte)
- handle->display_buffer_byte = init_data->display_buffer_byte + offset;
+ handle->display_buffer_byte = init_data->display_buffer_byte + display_buffer_byte_offset;
handle->width = ibuf->x;
@@ -1090,6 +1190,7 @@ static void display_buffer_init_handle(void *handle_v, int start_line, int tot_l
handle->channels = channels;
handle->dither = dither;
handle->predivide = predivide;
+ handle->is_data = is_data;
handle->byte_colorspace = init_data->byte_colorspace;
handle->float_colorspace = init_data->float_colorspace;
@@ -1106,6 +1207,8 @@ static void *display_buffer_apply_get_linear_buffer(DisplayBufferThread *handle)
int buffer_size = channels * width * height;
int predivide = handle->predivide;
+ int is_data = handle->is_data;
+ int is_data_display = handle->cm_processor->is_data_result;
linear_buffer = MEM_callocN(buffer_size * sizeof(float), "color conversion linear buffer");
@@ -1122,14 +1225,16 @@ static void *display_buffer_apply_get_linear_buffer(DisplayBufferThread *handle)
/* first convert byte buffer to float, keep in image space */
for (i = 0, fp = linear_buffer, cp = byte_buffer;
i < channels * width * height;
- i++, fp++, cp++)
+ i++, fp++, cp++)
{
*fp = (float)(*cp) / 255.0f;
}
- /* convert float buffer to scene linear space */
- IMB_colormanagement_transform(linear_buffer, width, height, channels,
- from_colorspace, to_colorspace, predivide);
+ if (!is_data && !is_data_display) {
+ /* convert float buffer to scene linear space */
+ IMB_colormanagement_transform(linear_buffer, width, height, channels,
+ from_colorspace, to_colorspace, predivide);
+ }
}
else if (handle->float_colorspace) {
/* currently float is non-linear only in sequencer, which is working
@@ -1166,7 +1271,6 @@ static void *do_display_buffer_apply_thread(void *handle_v)
{
DisplayBufferThread *handle = (DisplayBufferThread *) handle_v;
ColormanageProcessor *cm_processor = handle->cm_processor;
- float *buffer = handle->buffer;
float *display_buffer = handle->display_buffer;
unsigned char *display_buffer_byte = handle->display_buffer_byte;
int channels = handle->channels;
@@ -1174,25 +1278,45 @@ static void *do_display_buffer_apply_thread(void *handle_v)
int height = handle->tot_line;
float dither = handle->dither;
int predivide = handle->predivide;
+ int is_data = handle->is_data;
- float *linear_buffer = display_buffer_apply_get_linear_buffer(handle);
-
- /* apply processor */
- IMB_colormanagement_processor_apply(cm_processor, linear_buffer, width, height, channels, predivide);
+ if (cm_processor == NULL) {
+ if (display_buffer_byte) {
+ IMB_buffer_byte_from_byte(display_buffer_byte, handle->byte_buffer, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
+ FALSE, width, height, width, width);
+ }
- /* copy result to output buffers */
- if (display_buffer_byte) {
- /* do conversion */
- IMB_buffer_byte_from_float(display_buffer_byte, linear_buffer,
- channels, dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
- predivide, width, height, width, width);
+ if (display_buffer) {
+ IMB_buffer_float_from_byte(display_buffer, handle->byte_buffer, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
+ FALSE, width, height, width, width);
+ }
}
+ else {
+ float *linear_buffer = display_buffer_apply_get_linear_buffer(handle);
- if (display_buffer)
- memcpy(display_buffer, linear_buffer, width * height * channels * sizeof(float));
+ if (is_data) {
+ /* special case for data buffers - no color space conversions,
+ * only generate byte buffers
+ */
+ }
+ else {
+ /* apply processor */
+ IMB_colormanagement_processor_apply(cm_processor, linear_buffer, width, height, channels, predivide);
+ }
+
+ /* copy result to output buffers */
+ if (display_buffer_byte) {
+ /* do conversion */
+ IMB_buffer_byte_from_float(display_buffer_byte, linear_buffer,
+ channels, dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
+ predivide, width, height, width, width);
+ }
+
+ if (display_buffer)
+ memcpy(display_buffer, linear_buffer, width * height * channels * sizeof(float));
- if (linear_buffer != buffer)
MEM_freeN(linear_buffer);
+ }
return NULL;
}
@@ -1235,14 +1359,35 @@ static void colormanage_display_buffer_process_ex(ImBuf *ibuf, float *display_bu
const ColorManagedViewSettings *view_settings,
const ColorManagedDisplaySettings *display_settings)
{
- ColormanageProcessor *cm_processor;
+ ColormanageProcessor *cm_processor = NULL;
+ int skip_transform = FALSE;
- cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
+ /* if we're going to transform byte buffer, check whether transformation would
+ * happen to the same color space as byte buffer itself is
+ * this would save byte -> float -> byte conversions making display buffer
+ * computation noticeable faster
+ */
+ if (ibuf->rect_float == NULL && ibuf->rect_colorspace) {
+ if ((view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) == 0 &&
+ view_settings->exposure == 0.0f &&
+ view_settings->gamma == 1.0f)
+ {
+ const char *from_colorspace = ibuf->rect_colorspace->name;
+ const char *to_colorspace = display_transform_get_colorspace_name(view_settings, display_settings);
+
+ if (to_colorspace && !strcmp(from_colorspace, to_colorspace))
+ skip_transform = TRUE;
+ }
+ }
+
+ if (skip_transform == FALSE)
+ cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
display_buffer_apply_threaded(ibuf, ibuf->rect_float, (unsigned char *) ibuf->rect,
display_buffer, display_buffer_byte, cm_processor);
- IMB_colormanagement_processor_free(cm_processor);
+ if (cm_processor)
+ IMB_colormanagement_processor_free(cm_processor);
}
static void colormanage_display_buffer_process(ImBuf *ibuf, unsigned char *display_buffer,
@@ -1401,13 +1546,11 @@ void IMB_colormanagement_transform_v4(float pixel[4], const char *from_colorspac
*/
void IMB_colormanagement_colorspace_to_scene_linear_v3(float pixel[3], ColorSpace *colorspace)
{
- ConstProcessorRcPtr *processor;
+ OCIO_ConstProcessorRcPtr *processor;
if (!colorspace) {
- /* OCIO_TODO: make sure it never happens */
-
+ /* should never happen */
printf("%s: perform conversion from unknown color space\n", __func__);
-
return;
}
@@ -1420,13 +1563,11 @@ void IMB_colormanagement_colorspace_to_scene_linear_v3(float pixel[3], ColorSpac
/* same as above, but converts colors in opposite direction */
void IMB_colormanagement_scene_linear_to_colorspace_v3(float pixel[3], ColorSpace *colorspace)
{
- ConstProcessorRcPtr *processor;
+ OCIO_ConstProcessorRcPtr *processor;
if (!colorspace) {
- /* OCIO_TODO: make sure it never happens */
-
+ /* should never happen */
printf("%s: perform conversion from unknown color space\n", __func__);
-
return;
}
@@ -1438,22 +1579,20 @@ void IMB_colormanagement_scene_linear_to_colorspace_v3(float pixel[3], ColorSpac
void IMB_colormanagement_colorspace_to_scene_linear(float *buffer, int width, int height, int channels, struct ColorSpace *colorspace, int predivide)
{
- ConstProcessorRcPtr *processor;
+ OCIO_ConstProcessorRcPtr *processor;
if (!colorspace) {
- /* OCIO_TODO: make sure it never happens */
-
+ /* should never happen */
printf("%s: perform conversion from unknown color space\n", __func__);
-
return;
}
processor = colorspace_to_scene_linear_processor(colorspace);
if (processor) {
- PackedImageDesc *img;
+ OCIO_PackedImageDesc *img;
- img = OCIO_createPackedImageDesc(buffer, width, height, channels, sizeof(float),
+ img = OCIO_createOCIO_PackedImageDesc(buffer, width, height, channels, sizeof(float),
channels * sizeof(float), channels * sizeof(float) * width);
if (predivide)
@@ -1461,7 +1600,7 @@ void IMB_colormanagement_colorspace_to_scene_linear(float *buffer, int width, in
else
OCIO_processorApply(processor, img);
- OCIO_packedImageDescRelease(img);
+ OCIO_OCIO_PackedImageDescRelease(img);
}
}
@@ -1471,7 +1610,7 @@ void IMB_colormanagement_colorspace_to_scene_linear(float *buffer, int width, in
*/
void IMB_colormanagement_scene_linear_to_display_v3(float pixel[3], ColorManagedDisplay *display)
{
- ConstProcessorRcPtr *processor;
+ OCIO_ConstProcessorRcPtr *processor;
processor = display_from_scene_linear_processor(display);
@@ -1482,7 +1621,7 @@ void IMB_colormanagement_scene_linear_to_display_v3(float pixel[3], ColorManaged
/* same as above, but converts color in opposite direction */
void IMB_colormanagement_display_to_scene_linear_v3(float pixel[3], ColorManagedDisplay *display)
{
- ConstProcessorRcPtr *processor;
+ OCIO_ConstProcessorRcPtr *processor;
processor = display_to_scene_linear_processor(display);
@@ -1516,25 +1655,104 @@ void IMB_colormanagement_pixel_to_display_space_v3(float result[3], const float
IMB_colormanagement_processor_free(cm_processor);
}
-void IMB_colormanagement_imbuf_assign_float_space(ImBuf *ibuf, ColorManagedColorspaceSettings *colorspace_settings)
-{
- ibuf->float_colorspace = colormanage_colorspace_get_named(colorspace_settings->name);
-}
-
-void IMB_colormanagement_imbuf_make_display_space(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
- const ColorManagedDisplaySettings *display_settings)
+static void colormanagement_imbuf_make_display_space(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
+ const ColorManagedDisplaySettings *display_settings, int make_byte)
{
- /* OCIO_TODO: byte buffer management is not supported here yet */
- if (!ibuf->rect_float)
- return;
+ if (!ibuf->rect && make_byte)
+ imb_addrectImBuf(ibuf);
if (global_tot_display == 0 || global_tot_view == 0) {
IMB_buffer_float_from_float(ibuf->rect_float, ibuf->rect_float, ibuf->channels, IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB,
ibuf->flags & IB_cm_predivide, ibuf->x, ibuf->y, ibuf->x, ibuf->x);
}
else {
- colormanage_display_buffer_process_ex(ibuf, ibuf->rect_float, NULL, view_settings, display_settings);
+ colormanage_display_buffer_process_ex(ibuf, ibuf->rect_float, (unsigned char *)ibuf->rect,
+ view_settings, display_settings);
+ }
+}
+
+void IMB_colormanagement_imbuf_make_display_space(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
+ const ColorManagedDisplaySettings *display_settings)
+{
+ colormanagement_imbuf_make_display_space(ibuf, view_settings, display_settings, FALSE);
+}
+
+/* prepare image buffer to be saved on disk, applying color management if needed
+ * color management would be applied if image is saving as render result and if
+ * file format is not expecting float buffer to be in linear space (currently
+ * JPEG2000 and TIFF are such formats -- they're storing image as float but
+ * file itself stores applied color space).
+ *
+ * Both byte and float buffers would contain applied color space, and result's
+ * float_colorspace would be set to display color space. This should be checked
+ * in image format write callback and if float_colorspace is not NULL, no color
+ * space transformation should be applied on this buffer.
+ */
+ImBuf *IMB_colormanagement_imbuf_for_write(ImBuf *ibuf, int save_as_render, int allocate_result, const ColorManagedViewSettings *view_settings,
+ const ColorManagedDisplaySettings *display_settings, ImageFormatData *image_format_data)
+{
+ ImBuf *colormanaged_ibuf = ibuf;
+ int do_colormanagement;
+ int is_movie = BKE_imtype_is_movie(image_format_data->imtype);
+ int requires_linear_float = BKE_imtype_requires_linear_float(image_format_data->imtype);
+
+ do_colormanagement = save_as_render && (is_movie || !requires_linear_float);
+
+ if (do_colormanagement) {
+ int make_byte = FALSE;
+ ImFileType *type;
+
+ if (allocate_result) {
+ colormanaged_ibuf = IMB_dupImBuf(ibuf);
+ }
+ else {
+ /* render pipeline is constructing image buffer itself, but it's re-using byte and float buffers from render result
+ * make copy of this buffers here sine this buffers would be transformed to other color space here
+ */
+
+ if (ibuf->rect && (ibuf->mall & IB_rect) == 0) {
+ ibuf->rect = MEM_dupallocN(ibuf->rect);
+ ibuf->mall |= IB_rect;
+ }
+
+ if (ibuf->rect_float && (ibuf->mall & IB_rectfloat) == 0) {
+ ibuf->rect_float = MEM_dupallocN(ibuf->rect_float);
+ ibuf->mall |= IB_rectfloat;
+ }
+ }
+
+ /* for proper check whether byte buffer is required by a format or not
+ * should be pretty safe since this image buffer is supposed to be used for
+ * saving only and ftype would be overwritten a bit later by BKE_imbuf_write
+ */
+ colormanaged_ibuf->ftype = BKE_imtype_to_ftype(image_format_data->imtype);
+
+ /* if file format isn't able to handle float buffer itself,
+ * we need to allocate byte buffer and store color managed
+ * image there
+ */
+ for (type = IMB_FILE_TYPES; type->is_a; type++) {
+ if (type->save && type->ftype(type, colormanaged_ibuf)) {
+ if ((type->flag & IM_FTYPE_FLOAT) == 0)
+ make_byte = TRUE;
+
+ break;
+ }
+ }
+
+ /* perform color space conversions */
+ colormanagement_imbuf_make_display_space(colormanaged_ibuf, view_settings, display_settings, make_byte);
+
+ if (colormanaged_ibuf->rect_float) {
+ /* float buffer isn't linear anymore,
+ * image format write callback should check for this flag and assume
+ * no space conversion should happen if ibuf->float_colorspace != NULL
+ */
+ colormanaged_ibuf->float_colorspace = display_transform_get_colorspace(view_settings, display_settings);
+ }
}
+
+ return colormanaged_ibuf;
}
static void imbuf_verify_float(ImBuf *ibuf)
@@ -1606,7 +1824,7 @@ unsigned char *IMB_display_buffer_acquire(ImBuf *ibuf, const ColorManagedViewSet
if (global_tot_display)
ibuf->display_buffer_flags = MEM_callocN(sizeof(unsigned int) * global_tot_display, "imbuf display_buffer_flags");
}
- else if (ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) {
+ else if (ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) {
/* all display buffers were marked as invalid from other areas,
* now propagate this flag to internal color management routines
*/
@@ -1622,7 +1840,7 @@ unsigned char *IMB_display_buffer_acquire(ImBuf *ibuf, const ColorManagedViewSet
return display_buffer;
}
- buffer_size = ibuf->channels * ibuf->x * ibuf->y * sizeof(float);
+ buffer_size = DISPLAY_BUFFER_CHANNELS * ibuf->x * ibuf->y * sizeof(char);
display_buffer = MEM_callocN(buffer_size, "imbuf display buffer");
colormanage_display_buffer_process(ibuf, display_buffer, applied_view_settings, display_settings);
@@ -1646,28 +1864,12 @@ unsigned char *IMB_display_buffer_acquire_ctx(const bContext *C, ImBuf *ibuf, vo
return IMB_display_buffer_acquire(ibuf, view_settings, display_settings, cache_handle);
}
-/* covert float buffer to display space and store it in image buffer's byte array */
-void IMB_display_buffer_to_imbuf_rect(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
- const ColorManagedDisplaySettings *display_settings)
-{
- if (global_tot_display == 0 || global_tot_view == 0) {
- imbuf_verify_float(ibuf);
- }
- else {
- if (!ibuf->rect) {
- imb_addrectImBuf(ibuf);
- }
-
- colormanage_display_buffer_process(ibuf, (unsigned char *) ibuf->rect, view_settings, display_settings);
- }
-}
-
void IMB_display_buffer_transform_apply(unsigned char *display_buffer, float *linear_buffer, int width, int height,
int channels, const ColorManagedViewSettings *view_settings,
const ColorManagedDisplaySettings *display_settings, int predivide)
{
if (global_tot_display == 0 || global_tot_view == 0) {
- IMB_buffer_byte_from_float(display_buffer, linear_buffer, 4, 0.0f, IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB, FALSE,
+ IMB_buffer_byte_from_float(display_buffer, linear_buffer, channels, 0.0f, IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB, FALSE,
width, height, width, width);
}
else {
@@ -1701,25 +1903,26 @@ void IMB_display_buffer_release(void *cache_handle)
/*********************** Display functions *************************/
-ColorManagedDisplay *colormanage_display_get_default(void)
+const char *colormanage_display_get_default_name(void)
{
- ConstConfigRcPtr *config = OCIO_getCurrentConfig();
- const char *display;
+ OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
+ const char *display_name;
- if (!config) {
- /* no valid OCIO configuration, can't get default display */
+ display_name = OCIO_configGetDefaultDisplay(config);
- return NULL;
- }
+ OCIO_configRelease(config);
- display = OCIO_configGetDefaultDisplay(config);
+ return display_name;
+}
- OCIO_configRelease(config);
+ColorManagedDisplay *colormanage_display_get_default(void)
+{
+ const char *display_name = colormanage_display_get_default_name();
- if (display[0] == '\0')
+ if (display_name[0] == '\0')
return NULL;
- return colormanage_display_get_named(display);
+ return colormanage_display_get_named(display_name);
}
ColorManagedDisplay *colormanage_display_add(const char *name)
@@ -1801,19 +2004,21 @@ ColorManagedDisplay *IMB_colormanagement_display_get_named(const char *name)
return colormanage_display_get_named(name);
}
+const char *IMB_colormanagement_display_get_none_name(void)
+{
+ if (colormanage_display_get_named("None") != NULL)
+ return "None";
+
+ return colormanage_display_get_default_name();
+}
+
/*********************** View functions *************************/
const char *colormanage_view_get_default_name(const ColorManagedDisplay *display)
{
- ConstConfigRcPtr *config = OCIO_getCurrentConfig();
+ OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
const char *name;
- if (!config) {
- /* no valid OCIO configuration, can't get default view */
-
- return NULL;
- }
-
name = OCIO_configGetDefaultView(config, display->name);
OCIO_configRelease(config);
@@ -1890,11 +2095,13 @@ const char *IMB_colormanagement_view_get_indexed_name(int index)
const char *IMB_colormanagement_view_get_default_name(const char *display_name)
{
ColorManagedDisplay *display = colormanage_display_get_named(display_name);
- ColorManagedView *view = colormanage_view_get_default(display);
+ ColorManagedView *view = NULL;
+
+ if (display)
+ view = colormanage_view_get_default(display);
- if (view) {
+ if (view)
return view->name;
- }
return NULL;
}
@@ -1921,7 +2128,7 @@ static void colormanage_description_strip(char *description)
}
}
-ColorSpace *colormanage_colorspace_add(const char *name, const char *description, int is_invertible)
+ColorSpace *colormanage_colorspace_add(const char *name, const char *description, int is_invertible, int is_data)
{
ColorSpace *colorspace, *prev_space;
int counter = 1;
@@ -1937,6 +2144,7 @@ ColorSpace *colormanage_colorspace_add(const char *name, const char *description
}
colorspace->is_invertible = is_invertible;
+ colorspace->is_data = is_data;
for (prev_space = global_colorspaces.first; prev_space; prev_space = prev_space->next) {
if (BLI_strcasecmp(prev_space->name, colorspace->name) > 0)
@@ -2124,6 +2332,7 @@ static void partial_buffer_update_rect(ImBuf *ibuf, unsigned char *display_buffe
float *display_buffer_float = NULL;
int width = xmax - xmin;
int height = ymax - ymin;
+ int is_data = ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA;
if (dither != 0.0f) {
display_buffer_float = MEM_callocN(channels * width * height * sizeof(float), "display buffer for dither");
@@ -2140,14 +2349,15 @@ static void partial_buffer_update_rect(ImBuf *ibuf, unsigned char *display_buffe
}
else if (byte_buffer) {
rgba_uchar_to_float(pixel, byte_buffer + linear_index);
-
IMB_colormanagement_colorspace_to_scene_linear_v3(pixel, rect_colorspace);
}
- if (predivide)
- IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
- else
- IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
+ if (!is_data) {
+ if (predivide)
+ IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
+ else
+ IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
+ }
if (display_buffer_float) {
int index = ((y - ymin) * width + (x - xmin)) * channels;
@@ -2173,9 +2383,9 @@ static void partial_buffer_update_rect(ImBuf *ibuf, unsigned char *display_buffe
void IMB_partial_display_buffer_update(ImBuf *ibuf, const float *linear_buffer, const unsigned char *byte_buffer,
int stride, int offset_x, int offset_y, const ColorManagedViewSettings *view_settings,
const ColorManagedDisplaySettings *display_settings,
- int xmin, int ymin, int xmax, int ymax)
+ int xmin, int ymin, int xmax, int ymax, int update_orig_byte_buffer)
{
- if (ibuf->rect && ibuf->rect_float) {
+ if ((ibuf->rect && ibuf->rect_float) || update_orig_byte_buffer) {
/* update byte buffer created by legacy color management */
unsigned char *rect = (unsigned char *) ibuf->rect;
@@ -2240,28 +2450,29 @@ ColormanageProcessor *IMB_colormanagement_display_processor_new(const ColorManag
const ColorManagedDisplaySettings *display_settings)
{
ColormanageProcessor *cm_processor;
+ ColorManagedViewSettings default_view_settings;
+ const ColorManagedViewSettings *applied_view_settings;
+ ColorSpace *display_space;
cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
- {
- ColorManagedViewSettings default_view_settings;
- const ColorManagedViewSettings *applied_view_settings;
+ if (view_settings) {
+ applied_view_settings = view_settings;
+ }
+ else {
+ init_default_view_settings(display_settings, &default_view_settings);
+ applied_view_settings = &default_view_settings;
+ }
- if (view_settings) {
- applied_view_settings = view_settings;
- }
- else {
- init_default_view_settings(display_settings, &default_view_settings);
- applied_view_settings = &default_view_settings;
- }
+ display_space = display_transform_get_colorspace(applied_view_settings, display_settings);
+ cm_processor->is_data_result = display_space->is_data;
- cm_processor->processor = create_display_buffer_processor(applied_view_settings->view_transform, display_settings->display_device,
- applied_view_settings->exposure, applied_view_settings->gamma);
+ cm_processor->processor = create_display_buffer_processor(applied_view_settings->view_transform, display_settings->display_device,
+ applied_view_settings->exposure, applied_view_settings->gamma);
- if (applied_view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) {
- cm_processor->curve_mapping = curvemapping_copy(applied_view_settings->curve_mapping);
- curvemapping_premultiply(cm_processor->curve_mapping, FALSE);
- }
+ if (applied_view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) {
+ cm_processor->curve_mapping = curvemapping_copy(applied_view_settings->curve_mapping);
+ curvemapping_premultiply(cm_processor->curve_mapping, FALSE);
}
return cm_processor;
@@ -2270,9 +2481,13 @@ ColormanageProcessor *IMB_colormanagement_display_processor_new(const ColorManag
ColormanageProcessor *IMB_colormanagement_colorspace_processor_new(const char *from_colorspace, const char *to_colorspace)
{
ColormanageProcessor *cm_processor;
+ ColorSpace *color_space;
cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
+ color_space = colormanage_colorspace_get_named(to_colorspace);
+ cm_processor->is_data_result = color_space->is_data;
+
cm_processor->processor = create_colorspace_transform_processor(from_colorspace, to_colorspace);
return cm_processor;
@@ -2283,7 +2498,8 @@ void IMB_colormanagement_processor_apply_v4(ColormanageProcessor *cm_processor,
if (cm_processor->curve_mapping)
curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
- OCIO_processorApplyRGBA(cm_processor->processor, pixel);
+ if (cm_processor->processor)
+ OCIO_processorApplyRGBA(cm_processor->processor, pixel);
}
void IMB_colormanagement_processor_apply_v3(ColormanageProcessor *cm_processor, float pixel[3])
@@ -2291,7 +2507,8 @@ void IMB_colormanagement_processor_apply_v3(ColormanageProcessor *cm_processor,
if (cm_processor->curve_mapping)
curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
- OCIO_processorApplyRGB(cm_processor->processor, pixel);
+ if (cm_processor->processor)
+ OCIO_processorApplyRGB(cm_processor->processor, pixel);
}
void IMB_colormanagement_processor_apply(ColormanageProcessor *cm_processor, float *buffer, int width, int height,
@@ -2310,11 +2527,11 @@ void IMB_colormanagement_processor_apply(ColormanageProcessor *cm_processor, flo
}
}
- {
- PackedImageDesc *img;
+ if (cm_processor->processor && channels >= 3) {
+ OCIO_PackedImageDesc *img;
/* apply OCIO processor */
- img = OCIO_createPackedImageDesc(buffer, width, height, channels, sizeof(float),
+ img = OCIO_createOCIO_PackedImageDesc(buffer, width, height, channels, sizeof(float),
channels * sizeof(float), channels * sizeof(float) * width);
if (predivide)
@@ -2322,7 +2539,7 @@ void IMB_colormanagement_processor_apply(ColormanageProcessor *cm_processor, flo
else
OCIO_processorApply(cm_processor->processor, img);
- OCIO_packedImageDescRelease(img);
+ OCIO_OCIO_PackedImageDescRelease(img);
}
}
@@ -2330,8 +2547,8 @@ void IMB_colormanagement_processor_free(ColormanageProcessor *cm_processor)
{
if (cm_processor->curve_mapping)
curvemapping_free(cm_processor->curve_mapping);
-
- OCIO_processorRelease(cm_processor->processor);
+ if (cm_processor->processor)
+ OCIO_processorRelease(cm_processor->processor);
MEM_freeN(cm_processor);
}
diff --git a/source/blender/imbuf/intern/dds/BlockDXT.cpp b/source/blender/imbuf/intern/dds/BlockDXT.cpp
index f5e9e536e41..db2ca5969ec 100644
--- a/source/blender/imbuf/intern/dds/BlockDXT.cpp
+++ b/source/blender/imbuf/intern/dds/BlockDXT.cpp
@@ -232,7 +232,7 @@ void BlockDXT1::decodeBlock(ColorBlock * block) const
uint idx = (row[j] >> (2 * i)) & 3;
block->color(i, j) = color_array[idx];
}
- }
+ }
}
void BlockDXT1::decodeBlockNV5x(ColorBlock * block) const
@@ -592,7 +592,7 @@ void BlockCTX1::decodeBlock(ColorBlock * block) const
uint idx = (row[j] >> (2 * i)) & 3;
block->color(i, j) = color_array[idx];
}
- }
+ }
}
void BlockCTX1::setIndices(int * idx)
diff --git a/source/blender/imbuf/intern/dds/BlockDXT.h b/source/blender/imbuf/intern/dds/BlockDXT.h
index c6712f4f058..9b90b744b67 100644
--- a/source/blender/imbuf/intern/dds/BlockDXT.h
+++ b/source/blender/imbuf/intern/dds/BlockDXT.h
@@ -271,4 +271,4 @@ void mem_read(Stream & mem, BlockATI1 & block);
void mem_read(Stream & mem, BlockATI2 & block);
void mem_read(Stream & mem, BlockCTX1 & block);
-#endif // __BLOCKDXT_H__
+#endif /* __BLOCKDXT_H__ */
diff --git a/source/blender/imbuf/intern/dds/CMakeLists.txt b/source/blender/imbuf/intern/dds/CMakeLists.txt
index e514b7ab6f9..57603725ce1 100644
--- a/source/blender/imbuf/intern/dds/CMakeLists.txt
+++ b/source/blender/imbuf/intern/dds/CMakeLists.txt
@@ -39,9 +39,21 @@ set(INC_SYS
)
set(SRC
+ BlockDXT.h
+ Color.h
+ ColorBlock.h
+ Common.h
+ DirectDrawSurface.h
+ FlipDXT.h
+ Image.h
+ PixelFormat.h
+ Stream.h
+ dds_api.h
+
BlockDXT.cpp
ColorBlock.cpp
DirectDrawSurface.cpp
+ FlipDXT.cpp
Image.cpp
Stream.cpp
dds_api.cpp
@@ -51,4 +63,4 @@ if(WITH_IMAGE_DDS)
add_definitions(-DWITH_DDS)
endif()
-blender_add_lib(bf_imbuf_dds "${SRC}" "${INC}" "${INC_SYS}")
+blender_add_lib(bf_imbuf_dds "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/imbuf/intern/dds/Color.h b/source/blender/imbuf/intern/dds/Color.h
index 17de0a596c6..6676057d710 100644
--- a/source/blender/imbuf/intern/dds/Color.h
+++ b/source/blender/imbuf/intern/dds/Color.h
@@ -96,4 +96,4 @@ public:
};
};
-#endif // __COLOR_H__
+#endif /* __COLOR_H__ */
diff --git a/source/blender/imbuf/intern/dds/ColorBlock.cpp b/source/blender/imbuf/intern/dds/ColorBlock.cpp
index 0b9f5c163fb..dbd87bf1426 100644
--- a/source/blender/imbuf/intern/dds/ColorBlock.cpp
+++ b/source/blender/imbuf/intern/dds/ColorBlock.cpp
@@ -393,7 +393,7 @@ void ColorBlock::computeRange(Vector3::Arg axis, Color32 * start, Color32 * end)
int mini, maxi;
mini = maxi = 0;
- float min, max;
+ float min, max;
min = max = dot(Vector3(m_color[0].r, m_color[0].g, m_color[0].b), axis);
for (uint i = 1; i < 16; i++)
diff --git a/source/blender/imbuf/intern/dds/ColorBlock.h b/source/blender/imbuf/intern/dds/ColorBlock.h
index 2bf362f2780..f0864f06e6f 100644
--- a/source/blender/imbuf/intern/dds/ColorBlock.h
+++ b/source/blender/imbuf/intern/dds/ColorBlock.h
@@ -104,4 +104,4 @@ inline Color32 & ColorBlock::color(uint x, uint y)
return m_color[y * 4 + x];
}
-#endif // __COLORBLOCK_H__
+#endif /* __COLORBLOCK_H__ */
diff --git a/source/blender/imbuf/intern/dds/Common.h b/source/blender/imbuf/intern/dds/Common.h
index 4e3e3e024f7..ab929b82264 100644
--- a/source/blender/imbuf/intern/dds/Common.h
+++ b/source/blender/imbuf/intern/dds/Common.h
@@ -42,9 +42,9 @@ template<typename T>
inline void
swap(T & a, T & b)
{
- T tmp = a;
- a = b;
- b = tmp;
+ T tmp = a;
+ a = b;
+ b = tmp;
}
typedef unsigned char uint8;
diff --git a/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp b/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
index 82f355e1bb2..ccf72f9af86 100644
--- a/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
+++ b/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
@@ -280,19 +280,19 @@ static const uint DDPF_SRGB = 0x40000000U;
DXGI_FORMAT_B8G8R8A8_UNORM = 87,
DXGI_FORMAT_B8G8R8X8_UNORM = 88,
- DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89,
- DXGI_FORMAT_B8G8R8A8_TYPELESS = 90,
- DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91,
- DXGI_FORMAT_B8G8R8X8_TYPELESS = 92,
- DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93,
-
- DXGI_FORMAT_BC6H_TYPELESS = 94,
- DXGI_FORMAT_BC6H_UF16 = 95,
- DXGI_FORMAT_BC6H_SF16 = 96,
-
- DXGI_FORMAT_BC7_TYPELESS = 97,
- DXGI_FORMAT_BC7_UNORM = 98,
- DXGI_FORMAT_BC7_UNORM_SRGB = 99,
+ DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89,
+ DXGI_FORMAT_B8G8R8A8_TYPELESS = 90,
+ DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91,
+ DXGI_FORMAT_B8G8R8X8_TYPELESS = 92,
+ DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93,
+
+ DXGI_FORMAT_BC6H_TYPELESS = 94,
+ DXGI_FORMAT_BC6H_UF16 = 95,
+ DXGI_FORMAT_BC6H_SF16 = 96,
+
+ DXGI_FORMAT_BC7_TYPELESS = 97,
+ DXGI_FORMAT_BC7_UNORM = 98,
+ DXGI_FORMAT_BC7_UNORM_SRGB = 99,
};
enum D3D10_RESOURCE_DIMENSION
@@ -305,7 +305,7 @@ static const uint DDPF_SRGB = 0x40000000U;
};
- const char * getDxgiFormatString(DXGI_FORMAT dxgiFormat)
+ static const char * getDxgiFormatString(DXGI_FORMAT dxgiFormat)
{
#define CASE(format) case DXGI_FORMAT_##format: return #format
switch (dxgiFormat)
@@ -429,7 +429,7 @@ static const uint DDPF_SRGB = 0x40000000U;
#undef CASE
}
- const char * getD3d10ResourceDimensionString(D3D10_RESOURCE_DIMENSION resourceDimension)
+ static const char * getD3d10ResourceDimensionString(D3D10_RESOURCE_DIMENSION resourceDimension)
{
switch (resourceDimension)
{
@@ -496,60 +496,60 @@ void mem_read(Stream & mem, DDSHeader & header)
namespace
{
- struct FormatDescriptor
- {
- uint format;
- uint bitcount;
- uint rmask;
- uint gmask;
- uint bmask;
- uint amask;
- };
-
- static const FormatDescriptor s_d3dFormats[] =
- {
- { D3DFMT_R8G8B8, 24, 0xFF0000, 0xFF00, 0xFF, 0 },
- { D3DFMT_A8R8G8B8, 32, 0xFF0000, 0xFF00, 0xFF, 0xFF000000 }, // DXGI_FORMAT_B8G8R8A8_UNORM
- { D3DFMT_X8R8G8B8, 32, 0xFF0000, 0xFF00, 0xFF, 0 }, // DXGI_FORMAT_B8G8R8X8_UNORM
- { D3DFMT_R5G6B5, 16, 0xF800, 0x7E0, 0x1F, 0 }, // DXGI_FORMAT_B5G6R5_UNORM
- { D3DFMT_X1R5G5B5, 16, 0x7C00, 0x3E0, 0x1F, 0 },
- { D3DFMT_A1R5G5B5, 16, 0x7C00, 0x3E0, 0x1F, 0x8000 }, // DXGI_FORMAT_B5G5R5A1_UNORM
- { D3DFMT_A4R4G4B4, 16, 0xF00, 0xF0, 0xF, 0xF000 },
- { D3DFMT_R3G3B2, 8, 0xE0, 0x1C, 0x3, 0 },
- { D3DFMT_A8, 8, 0, 0, 0, 8 }, // DXGI_FORMAT_A8_UNORM
- { D3DFMT_A8R3G3B2, 16, 0xE0, 0x1C, 0x3, 0xFF00 },
- { D3DFMT_X4R4G4B4, 16, 0xF00, 0xF0, 0xF, 0 },
- { D3DFMT_A2B10G10R10, 32, 0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000 }, // DXGI_FORMAT_R10G10B10A2
- { D3DFMT_A8B8G8R8, 32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000 }, // DXGI_FORMAT_R8G8B8A8_UNORM
- { D3DFMT_X8B8G8R8, 32, 0xFF, 0xFF00, 0xFF0000, 0 },
- { D3DFMT_G16R16, 32, 0xFFFF, 0xFFFF0000, 0, 0 }, // DXGI_FORMAT_R16G16_UNORM
- { D3DFMT_A2R10G10B10, 32, 0x3FF00000, 0xFFC00, 0x3FF, 0xC0000000 },
- { D3DFMT_A2B10G10R10, 32, 0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000 },
-
- { D3DFMT_L8, 8, 8, 0, 0, 0 }, // DXGI_FORMAT_R8_UNORM
- { D3DFMT_L16, 16, 16, 0, 0, 0 }, // DXGI_FORMAT_R16_UNORM
- };
-
- static const uint s_d3dFormatCount = sizeof(s_d3dFormats) / sizeof(s_d3dFormats[0]);
+struct FormatDescriptor
+{
+ uint format;
+ uint bitcount;
+ uint rmask;
+ uint gmask;
+ uint bmask;
+ uint amask;
+};
+
+static const FormatDescriptor s_d3dFormats[] =
+{
+ { D3DFMT_R8G8B8, 24, 0xFF0000, 0xFF00, 0xFF, 0 },
+ { D3DFMT_A8R8G8B8, 32, 0xFF0000, 0xFF00, 0xFF, 0xFF000000 }, /* DXGI_FORMAT_B8G8R8A8_UNORM */
+ { D3DFMT_X8R8G8B8, 32, 0xFF0000, 0xFF00, 0xFF, 0 }, /* DXGI_FORMAT_B8G8R8X8_UNORM */
+ { D3DFMT_R5G6B5, 16, 0xF800, 0x7E0, 0x1F, 0 }, /* DXGI_FORMAT_B5G6R5_UNORM */
+ { D3DFMT_X1R5G5B5, 16, 0x7C00, 0x3E0, 0x1F, 0 },
+ { D3DFMT_A1R5G5B5, 16, 0x7C00, 0x3E0, 0x1F, 0x8000 }, /* DXGI_FORMAT_B5G5R5A1_UNORM */
+ { D3DFMT_A4R4G4B4, 16, 0xF00, 0xF0, 0xF, 0xF000 },
+ { D3DFMT_R3G3B2, 8, 0xE0, 0x1C, 0x3, 0 },
+ { D3DFMT_A8, 8, 0, 0, 0, 8 }, /* DXGI_FORMAT_A8_UNORM */
+ { D3DFMT_A8R3G3B2, 16, 0xE0, 0x1C, 0x3, 0xFF00 },
+ { D3DFMT_X4R4G4B4, 16, 0xF00, 0xF0, 0xF, 0 },
+ { D3DFMT_A2B10G10R10, 32, 0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000 }, /* DXGI_FORMAT_R10G10B10A2 */
+ { D3DFMT_A8B8G8R8, 32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000 }, /* DXGI_FORMAT_R8G8B8A8_UNORM */
+ { D3DFMT_X8B8G8R8, 32, 0xFF, 0xFF00, 0xFF0000, 0 },
+ { D3DFMT_G16R16, 32, 0xFFFF, 0xFFFF0000, 0, 0 }, /* DXGI_FORMAT_R16G16_UNORM */
+ { D3DFMT_A2R10G10B10, 32, 0x3FF00000, 0xFFC00, 0x3FF, 0xC0000000 },
+ { D3DFMT_A2B10G10R10, 32, 0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000 },
+
+ { D3DFMT_L8, 8, 8, 0, 0, 0 }, /* DXGI_FORMAT_R8_UNORM */
+ { D3DFMT_L16, 16, 16, 0, 0, 0 }, /* DXGI_FORMAT_R16_UNORM */
+};
+
+static const uint s_d3dFormatCount = sizeof(s_d3dFormats) / sizeof(s_d3dFormats[0]);
} // namespace
-uint findD3D9Format(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask)
+static uint findD3D9Format(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask)
{
- for (int i = 0; i < s_d3dFormatCount; i++)
- {
- if (s_d3dFormats[i].bitcount == bitcount &&
- s_d3dFormats[i].rmask == rmask &&
- s_d3dFormats[i].gmask == gmask &&
- s_d3dFormats[i].bmask == bmask &&
- s_d3dFormats[i].amask == amask)
- {
- return s_d3dFormats[i].format;
- }
- }
+ for (int i = 0; i < s_d3dFormatCount; i++)
+ {
+ if (s_d3dFormats[i].bitcount == bitcount &&
+ s_d3dFormats[i].rmask == rmask &&
+ s_d3dFormats[i].gmask == gmask &&
+ s_d3dFormats[i].bmask == bmask &&
+ s_d3dFormats[i].amask == amask)
+ {
+ return s_d3dFormats[i].format;
+ }
+ }
- return 0;
- }
+ return 0;
+}
@@ -566,7 +566,7 @@ DDSHeader::DDSHeader()
for (uint i = 0; i < 11; i++) this->reserved[i] = 0;
// Store version information on the reserved header attributes.
- this->reserved[9] = FOURCC_NVTT;
+ this->reserved[9] = FOURCC_NVTT;
this->reserved[10] = (2 << 16) | (1 << 8) | (0); // major.minor.revision
this->pf.size = 32;
@@ -613,7 +613,7 @@ void DDSHeader::setMipmapCount(uint count)
if (count == 0 || count == 1)
{
this->flags &= ~DDSD_MIPMAPCOUNT;
- this->mipmapcount = 1;
+ this->mipmapcount = 1;
if (this->caps.caps2 == 0) {
this->caps.caps1 = DDSCAPS_TEXTURE;
@@ -715,14 +715,14 @@ void DDSHeader::setPixelFormat(uint bitcount, uint rmask, uint gmask, uint bmask
if (rmask != 0 || gmask != 0 || bmask != 0)
{
- if (gmask == 0 && bmask == 0)
- {
- this->pf.flags = DDPF_LUMINANCE;
- }
- else
- {
- this->pf.flags = DDPF_RGB;
- }
+ if (gmask == 0 && bmask == 0)
+ {
+ this->pf.flags = DDPF_LUMINANCE;
+ }
+ else
+ {
+ this->pf.flags = DDPF_RGB;
+ }
if (amask != 0) {
this->pf.flags |= DDPF_ALPHAPIXELS;
@@ -737,17 +737,17 @@ void DDSHeader::setPixelFormat(uint bitcount, uint rmask, uint gmask, uint bmask
{
// Compute bit count from the masks.
uint total = rmask | gmask | bmask | amask;
- while(total != 0) {
+ while (total != 0) {
bitcount++;
total >>= 1;
}
}
- // D3DX functions do not like this:
+ // D3DX functions do not like this:
this->pf.fourcc = 0; //findD3D9Format(bitcount, rmask, gmask, bmask, amask);
- /*if (this->pf.fourcc) {
- this->pf.flags |= DDPF_FOURCC;
- }*/
+ /*if (this->pf.fourcc) {
+ this->pf.flags |= DDPF_FOURCC;
+ }*/
if (!(bitcount > 0 && bitcount <= 32)) {
printf("DDS: bad bit count, pixel format not set\n");
@@ -775,8 +775,8 @@ void DDSHeader::setNormalFlag(bool b)
void DDSHeader::setSrgbFlag(bool b)
{
- if (b) this->pf.flags |= DDPF_SRGB;
- else this->pf.flags &= ~DDPF_SRGB;
+ if (b) this->pf.flags |= DDPF_SRGB;
+ else this->pf.flags &= ~DDPF_SRGB;
}
void DDSHeader::setHasAlphaFlag(bool b)
@@ -787,8 +787,8 @@ void DDSHeader::setHasAlphaFlag(bool b)
void DDSHeader::setUserVersion(int version)
{
- this->reserved[7] = FOURCC_UVER;
- this->reserved[8] = version;
+ this->reserved[7] = FOURCC_UVER;
+ this->reserved[8] = version;
}
/*
@@ -836,45 +836,45 @@ bool DDSHeader::hasDX10Header() const
uint DDSHeader::signature() const
{
- return this->reserved[9];
+ return this->reserved[9];
}
uint DDSHeader::toolVersion() const
{
- return this->reserved[10];
+ return this->reserved[10];
}
uint DDSHeader::userVersion() const
{
- if (this->reserved[7] == FOURCC_UVER) {
- return this->reserved[8];
- }
- return 0;
+ if (this->reserved[7] == FOURCC_UVER) {
+ return this->reserved[8];
+ }
+ return 0;
}
bool DDSHeader::isNormalMap() const
{
- return (pf.flags & DDPF_NORMAL) != 0;
+ return (pf.flags & DDPF_NORMAL) != 0;
}
bool DDSHeader::isSrgb() const
{
- return (pf.flags & DDPF_SRGB) != 0;
+ return (pf.flags & DDPF_SRGB) != 0;
}
bool DDSHeader::hasAlpha() const
{
- return (pf.flags & DDPF_ALPHAPIXELS) != 0;
+ return (pf.flags & DDPF_ALPHAPIXELS) != 0;
}
uint DDSHeader::d3d9Format() const
{
- if (pf.flags & DDPF_FOURCC) {
- return pf.fourcc;
- }
- else {
- return findD3D9Format(pf.bitcount, pf.rmask, pf.gmask, pf.bmask, pf.amask);
- }
+ if (pf.flags & DDPF_FOURCC) {
+ return pf.fourcc;
+ }
+ else {
+ return findD3D9Format(pf.bitcount, pf.rmask, pf.gmask, pf.bmask, pf.amask);
+ }
}
DirectDrawSurface::DirectDrawSurface(unsigned char *mem, uint size) : stream(mem, size), header()
@@ -949,9 +949,9 @@ bool DirectDrawSurface::isSupported() const
return false;
}
}
- else if ((header.pf.flags & DDPF_RGB) || (header.pf.flags & DDPF_LUMINANCE))
- {
- // All RGB and luminance formats are supported now.
+ else if ((header.pf.flags & DDPF_RGB) || (header.pf.flags & DDPF_LUMINANCE))
+ {
+ // All RGB and luminance formats are supported now.
}
else
{
@@ -1001,7 +1001,7 @@ bool DirectDrawSurface::hasAlpha() const
}
else
{
- // @@ Here we could check the ALPHA_PIXELS flag, but nobody sets it. (except us?)
+ // @@ Here we could check the ALPHA_PIXELS flag, but nobody sets it. (except us?)
return true;
}
}
@@ -1089,7 +1089,7 @@ void DirectDrawSurface::setHasAlphaFlag(bool b)
void DirectDrawSurface::setUserVersion(int version)
{
- header.setUserVersion(version);
+ header.setUserVersion(version);
}
void DirectDrawSurface::mipmap(Image * img, uint face, uint mipmap)
@@ -1268,15 +1268,15 @@ void DirectDrawSurface::readBlock(ColorBlock * rgba)
block.decodeBlock(rgba);
}
else if (fourcc == FOURCC_DXT2 ||
- header.pf.fourcc == FOURCC_DXT3)
+ header.pf.fourcc == FOURCC_DXT3)
{
BlockDXT3 block;
mem_read(stream, block);
block.decodeBlock(rgba);
}
else if (fourcc == FOURCC_DXT4 ||
- header.pf.fourcc == FOURCC_DXT5 ||
- header.pf.fourcc == FOURCC_RXGB)
+ header.pf.fourcc == FOURCC_DXT5 ||
+ header.pf.fourcc == FOURCC_RXGB)
{
BlockDXT5 block;
mem_read(stream, block);
@@ -1393,8 +1393,8 @@ uint DirectDrawSurface::mipmapSize(uint mipmap) const
}
else if (header.pf.flags & DDPF_RGB || (header.pf.flags & DDPF_LUMINANCE))
{
- uint pitch = computePitch(w, header.pf.bitcount, 8); // Asuming 8 bit alignment, which is the same D3DX expects.
-
+ uint pitch = computePitch(w, header.pf.bitcount, 8); // Asuming 8 bit alignment, which is the same D3DX expects.
+
return pitch * h * d;
}
else {
@@ -1461,7 +1461,7 @@ void DirectDrawSurface::printInfo() const
printf("Pixel Format:\n");
printf("\tFlags: 0x%.8X\n", header.pf.flags);
if (header.pf.flags & DDPF_RGB) printf("\t\tDDPF_RGB\n");
- if (header.pf.flags & DDPF_LUMINANCE) printf("\t\tDDPF_LUMINANCE\n");
+ if (header.pf.flags & DDPF_LUMINANCE) printf("\t\tDDPF_LUMINANCE\n");
if (header.pf.flags & DDPF_FOURCC) printf("\t\tDDPF_FOURCC\n");
if (header.pf.flags & DDPF_ALPHAPIXELS) printf("\t\tDDPF_ALPHAPIXELS\n");
if (header.pf.flags & DDPF_ALPHA) printf("\t\tDDPF_ALPHA\n");
@@ -1472,24 +1472,24 @@ void DirectDrawSurface::printInfo() const
if (header.pf.flags & DDPF_ALPHAPREMULT) printf("\t\tDDPF_ALPHAPREMULT\n");
if (header.pf.flags & DDPF_NORMAL) printf("\t\tDDPF_NORMAL\n");
- if (header.pf.fourcc != 0) {
- // Display fourcc code even when DDPF_FOURCC flag not set.
- printf("\tFourCC: '%c%c%c%c' (0x%.8X)\n",
- ((header.pf.fourcc >> 0) & 0xFF),
- ((header.pf.fourcc >> 8) & 0xFF),
- ((header.pf.fourcc >> 16) & 0xFF),
- ((header.pf.fourcc >> 24) & 0xFF),
- header.pf.fourcc);
- }
-
- if ((header.pf.flags & DDPF_FOURCC) && (header.pf.bitcount != 0))
+ if (header.pf.fourcc != 0) {
+ // Display fourcc code even when DDPF_FOURCC flag not set.
+ printf("\tFourCC: '%c%c%c%c' (0x%.8X)\n",
+ ((header.pf.fourcc >> 0) & 0xFF),
+ ((header.pf.fourcc >> 8) & 0xFF),
+ ((header.pf.fourcc >> 16) & 0xFF),
+ ((header.pf.fourcc >> 24) & 0xFF),
+ header.pf.fourcc);
+ }
+
+ if ((header.pf.flags & DDPF_FOURCC) && (header.pf.bitcount != 0))
{
- printf("\tSwizzle: '%c%c%c%c' (0x%.8X)\n",
- (header.pf.bitcount >> 0) & 0xFF,
- (header.pf.bitcount >> 8) & 0xFF,
- (header.pf.bitcount >> 16) & 0xFF,
- (header.pf.bitcount >> 24) & 0xFF,
- header.pf.bitcount);
+ printf("\tSwizzle: '%c%c%c%c' (0x%.8X)\n",
+ (header.pf.bitcount >> 0) & 0xFF,
+ (header.pf.bitcount >> 8) & 0xFF,
+ (header.pf.bitcount >> 16) & 0xFF,
+ (header.pf.bitcount >> 24) & 0xFF,
+ header.pf.bitcount);
}
else
{
@@ -1535,7 +1535,7 @@ void DirectDrawSurface::printInfo() const
printf("\tArray size: %u\n", header.header10.arraySize);
}
- if (header.reserved[9] == FOURCC_NVTT)
+ if (header.reserved[9] == FOURCC_NVTT)
{
int major = (header.reserved[10] >> 16) & 0xFF;
int minor = (header.reserved[10] >> 8) & 0xFF;
@@ -1545,9 +1545,9 @@ void DirectDrawSurface::printInfo() const
printf("\tNVIDIA Texture Tools %d.%d.%d\n", major, minor, revision);
}
- if (header.reserved[7] == FOURCC_UVER)
- {
- printf("User Version: %u\n", header.reserved[8]);
- }
+ if (header.reserved[7] == FOURCC_UVER)
+ {
+ printf("User Version: %u\n", header.reserved[8]);
+ }
}
diff --git a/source/blender/imbuf/intern/dds/DirectDrawSurface.h b/source/blender/imbuf/intern/dds/DirectDrawSurface.h
index a851533b1f3..72a524daba2 100644
--- a/source/blender/imbuf/intern/dds/DirectDrawSurface.h
+++ b/source/blender/imbuf/intern/dds/DirectDrawSurface.h
@@ -169,7 +169,7 @@ public:
void setNormalFlag(bool b);
void setHasAlphaFlag(bool b);
- void setUserVersion(int version);
+ void setUserVersion(int version);
void mipmap(Image * img, uint f, uint m);
void* readData(uint &size);
@@ -200,4 +200,4 @@ void mem_read(Stream & mem, DDSCaps & caps);
void mem_read(Stream & mem, DDSHeader & header);
void mem_read(Stream & mem, DDSHeader10 & header);
-#endif // __DIRECTDRAWSURFACE_H__
+#endif /* __DIRECTDRAWSURFACE_H__ */
diff --git a/source/blender/imbuf/intern/dds/FlipDXT.cpp b/source/blender/imbuf/intern/dds/FlipDXT.cpp
new file mode 100644
index 00000000000..ee7a0ebb2f7
--- /dev/null
+++ b/source/blender/imbuf/intern/dds/FlipDXT.cpp
@@ -0,0 +1,255 @@
+/*
+ * Copyright 2009, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * 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.
+ */
+
+// This file comes from the chromium project, adapted to Blender to add DDS
+// flipping to OpenGL convention for Blender
+
+#include "IMB_imbuf_types.h"
+
+#include <string.h>
+
+#include <Common.h>
+#include <Stream.h>
+#include <ColorBlock.h>
+#include <BlockDXT.h>
+#include <FlipDXT.h>
+
+// A function that flips a DXTC block.
+typedef void (*FlipBlockFunction)(uint8_t *block);
+
+// Flips a full DXT1 block in the y direction.
+static void FlipDXT1BlockFull(uint8_t *block)
+{
+ // A DXT1 block layout is:
+ // [0-1] color0.
+ // [2-3] color1.
+ // [4-7] color bitmap, 2 bits per pixel.
+ // So each of the 4-7 bytes represents one line, flipping a block is just
+ // flipping those bytes.
+ uint8_t tmp = block[4];
+ block[4] = block[7];
+ block[7] = tmp;
+ tmp = block[5];
+ block[5] = block[6];
+ block[6] = tmp;
+}
+
+// Flips the first 2 lines of a DXT1 block in the y direction.
+static void FlipDXT1BlockHalf(uint8_t *block)
+{
+ // See layout above.
+ uint8_t tmp = block[4];
+ block[4] = block[5];
+ block[5] = tmp;
+}
+
+// Flips a full DXT3 block in the y direction.
+static void FlipDXT3BlockFull(uint8_t *block)
+{
+ // A DXT3 block layout is:
+ // [0-7] alpha bitmap, 4 bits per pixel.
+ // [8-15] a DXT1 block.
+
+ // We can flip the alpha bits at the byte level (2 bytes per line).
+ uint8_t tmp = block[0];
+
+ block[0] = block[6];
+ block[6] = tmp;
+ tmp = block[1];
+ block[1] = block[7];
+ block[7] = tmp;
+ tmp = block[2];
+ block[2] = block[4];
+ block[4] = tmp;
+ tmp = block[3];
+ block[3] = block[5];
+ block[5] = tmp;
+
+ // And flip the DXT1 block using the above function.
+ FlipDXT1BlockFull(block + 8);
+}
+
+// Flips the first 2 lines of a DXT3 block in the y direction.
+static void FlipDXT3BlockHalf(uint8_t *block)
+{
+ // See layout above.
+ uint8_t tmp = block[0];
+
+ block[0] = block[2];
+ block[2] = tmp;
+ tmp = block[1];
+ block[1] = block[3];
+ block[3] = tmp;
+ FlipDXT1BlockHalf(block + 8);
+}
+
+// Flips a full DXT5 block in the y direction.
+static void FlipDXT5BlockFull(uint8_t *block)
+{
+ // A DXT5 block layout is:
+ // [0] alpha0.
+ // [1] alpha1.
+ // [2-7] alpha bitmap, 3 bits per pixel.
+ // [8-15] a DXT1 block.
+
+ // The alpha bitmap doesn't easily map lines to bytes, so we have to
+ // interpret it correctly. Extracted from
+ // http://www.opengl.org/registry/specs/EXT/texture_compression_s3tc.txt :
+ //
+ // The 6 "bits" bytes of the block are decoded into one 48-bit integer:
+ //
+ // bits = bits_0 + 256 * (bits_1 + 256 * (bits_2 + 256 * (bits_3 +
+ // 256 * (bits_4 + 256 * bits_5))))
+ //
+ // bits is a 48-bit unsigned integer, from which a three-bit control code
+ // is extracted for a texel at location (x,y) in the block using:
+ //
+ // code(x,y) = bits[3*(4*y+x)+1..3*(4*y+x)+0]
+ //
+ // where bit 47 is the most significant and bit 0 is the least
+ // significant bit.
+ unsigned int line_0_1 = block[2] + 256 * (block[3] + 256 * block[4]);
+ unsigned int line_2_3 = block[5] + 256 * (block[6] + 256 * block[7]);
+ // swap lines 0 and 1 in line_0_1.
+ unsigned int line_1_0 = ((line_0_1 & 0x000fff) << 12) |
+ ((line_0_1 & 0xfff000) >> 12);
+ // swap lines 2 and 3 in line_2_3.
+ unsigned int line_3_2 = ((line_2_3 & 0x000fff) << 12) |
+ ((line_2_3 & 0xfff000) >> 12);
+
+ block[2] = line_3_2 & 0xff;
+ block[3] = (line_3_2 & 0xff00) >> 8;
+ block[4] = (line_3_2 & 0xff0000) >> 8;
+ block[5] = line_1_0 & 0xff;
+ block[6] = (line_1_0 & 0xff00) >> 8;
+ block[7] = (line_1_0 & 0xff0000) >> 8;
+
+ // And flip the DXT1 block using the above function.
+ FlipDXT1BlockFull(block + 8);
+}
+
+// Flips the first 2 lines of a DXT5 block in the y direction.
+static void FlipDXT5BlockHalf(uint8_t *block)
+{
+ // See layout above.
+ unsigned int line_0_1 = block[2] + 256 * (block[3] + 256 * block[4]);
+ unsigned int line_1_0 = ((line_0_1 & 0x000fff) << 12) |
+ ((line_0_1 & 0xfff000) >> 12);
+ block[2] = line_1_0 & 0xff;
+ block[3] = (line_1_0 & 0xff00) >> 8;
+ block[4] = (line_1_0 & 0xff0000) >> 8;
+ FlipDXT1BlockHalf(block + 8);
+}
+
+// Flips a DXTC image, by flipping and swapping DXTC blocks as appropriate.
+int FlipDXTCImage(unsigned int width, unsigned int height, unsigned int levels, int fourcc, uint8_t *data)
+{
+ // must have valid dimensions
+ if (width == 0 || height == 0)
+ return 0;
+ // height must be a power-of-two
+ if ((height & (height - 1)) != 0)
+ return 0;
+
+ FlipBlockFunction full_block_function;
+ FlipBlockFunction half_block_function;
+ unsigned int block_bytes = 0;
+
+ switch (fourcc) {
+ case FOURCC_DXT1:
+ full_block_function = FlipDXT1BlockFull;
+ half_block_function = FlipDXT1BlockHalf;
+ block_bytes = 8;
+ break;
+ case FOURCC_DXT3:
+ full_block_function = FlipDXT3BlockFull;
+ half_block_function = FlipDXT3BlockHalf;
+ block_bytes = 16;
+ break;
+ case FOURCC_DXT5:
+ full_block_function = FlipDXT5BlockFull;
+ half_block_function = FlipDXT5BlockHalf;
+ block_bytes = 16;
+ break;
+ default:
+ return 0;
+ }
+
+ unsigned int mip_width = width;
+ unsigned int mip_height = height;
+
+ for (unsigned int i = 0; i < levels; ++i) {
+ unsigned int blocks_per_row = (mip_width + 3) / 4;
+ unsigned int blocks_per_col = (mip_height + 3) / 4;
+ unsigned int blocks = blocks_per_row * blocks_per_col;
+
+ if (mip_height == 1) {
+ // no flip to do, and we're done.
+ break;
+ }
+ else if (mip_height == 2) {
+ // flip the first 2 lines in each block.
+ for (unsigned int i = 0; i < blocks_per_row; ++i) {
+ half_block_function(data + i * block_bytes);
+ }
+ }
+ else {
+ // flip each block.
+ for (unsigned int i = 0; i < blocks; ++i)
+ full_block_function(data + i * block_bytes);
+
+ // swap each block line in the first half of the image with the
+ // corresponding one in the second half.
+ // note that this is a no-op if mip_height is 4.
+ unsigned int row_bytes = block_bytes * blocks_per_row;
+ uint8_t *temp_line = new uint8_t[row_bytes];
+
+ for (unsigned int y = 0; y < blocks_per_col / 2; ++y) {
+ uint8_t *line1 = data + y * row_bytes;
+ uint8_t *line2 = data + (blocks_per_col - y - 1) * row_bytes;
+
+ memcpy(temp_line, line1, row_bytes);
+ memcpy(line1, line2, row_bytes);
+ memcpy(line2, temp_line, row_bytes);
+ }
+
+ delete temp_line;
+ }
+
+ // mip levels are contiguous.
+ data += block_bytes * blocks;
+ mip_width = max(1U, mip_width >> 1);
+ mip_height = max(1U, mip_height >> 1);
+ }
+
+ return 1;
+}
+
diff --git a/source/blender/imbuf/intern/dds/FlipDXT.h b/source/blender/imbuf/intern/dds/FlipDXT.h
new file mode 100644
index 00000000000..8d0ae8139a1
--- /dev/null
+++ b/source/blender/imbuf/intern/dds/FlipDXT.h
@@ -0,0 +1,32 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributors: Amorilia (amorilia@users.sourceforge.net)
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __FLIPDXT_H__
+#define __FLIPDXT_H__
+
+#include "MEM_sys_types.h"
+
+/* flip compressed DXT image vertically to fit OpenGL convention */
+int FlipDXTCImage(unsigned int width, unsigned int height, unsigned int levels, int fourcc, uint8_t *data);
+
+#endif
+
diff --git a/source/blender/imbuf/intern/dds/Image.h b/source/blender/imbuf/intern/dds/Image.h
index 5dcf3011c76..81074fba6b7 100644
--- a/source/blender/imbuf/intern/dds/Image.h
+++ b/source/blender/imbuf/intern/dds/Image.h
@@ -101,4 +101,4 @@ inline Color32 & Image::pixel(uint x, uint y)
return pixel(y * width() + x);
}
-#endif // __IMAGE_H__
+#endif /* __IMAGE_H__ */
diff --git a/source/blender/imbuf/intern/dds/PixelFormat.h b/source/blender/imbuf/intern/dds/PixelFormat.h
index 308ea810f03..2bb1864e49d 100644
--- a/source/blender/imbuf/intern/dds/PixelFormat.h
+++ b/source/blender/imbuf/intern/dds/PixelFormat.h
@@ -101,38 +101,38 @@
}
}
- inline float quantizeCeil(float f, int inbits, int outbits)
- {
- //uint i = f * (float(1 << inbits) - 1);
- //i = convert(i, inbits, outbits);
- //float result = float(i) / (float(1 << outbits) - 1);
- //nvCheck(result >= f);
- float result;
- int offset = 0;
- do {
- uint i = offset + uint(f * (float(1 << inbits) - 1));
- i = convert(i, inbits, outbits);
- result = float(i) / (float(1 << outbits) - 1);
- offset++;
- } while (result < f);
-
- return result;
- }
-
- /*
- inline float quantizeRound(float f, int bits)
- {
- float scale = float(1 << bits);
- return fround(f * scale) / scale;
- }
-
- inline float quantizeFloor(float f, int bits)
- {
- float scale = float(1 << bits);
- return floor(f * scale) / scale;
- }
- */
+ inline float quantizeCeil(float f, int inbits, int outbits)
+ {
+ //uint i = f * (float(1 << inbits) - 1);
+ //i = convert(i, inbits, outbits);
+ //float result = float(i) / (float(1 << outbits) - 1);
+ //nvCheck(result >= f);
+ float result;
+ int offset = 0;
+ do {
+ uint i = offset + uint(f * (float(1 << inbits) - 1));
+ i = convert(i, inbits, outbits);
+ result = float(i) / (float(1 << outbits) - 1);
+ offset++;
+ } while (result < f);
+
+ return result;
+ }
+
+#if 0
+ inline float quantizeRound(float f, int bits)
+ {
+ float scale = float(1 << bits);
+ return fround(f * scale) / scale;
+ }
+
+ inline float quantizeFloor(float f, int bits)
+ {
+ float scale = float(1 << bits);
+ return floor(f * scale) / scale;
+ }
+#endif
} // PixelFormat namespace
-#endif // _DDS_IMAGE_PIXELFORMAT_H
+#endif /* __PIXELFORMAT_H__ */
diff --git a/source/blender/imbuf/intern/dds/SConscript b/source/blender/imbuf/intern/dds/SConscript
index 4245f5001b9..d5a613f5981 100644
--- a/source/blender/imbuf/intern/dds/SConscript
+++ b/source/blender/imbuf/intern/dds/SConscript
@@ -1,7 +1,7 @@
#!/usr/bin/python
Import ('env')
-source_files = ['dds_api.cpp', 'DirectDrawSurface.cpp', 'Stream.cpp', 'BlockDXT.cpp', 'ColorBlock.cpp', 'Image.cpp']
+source_files = ['dds_api.cpp', 'DirectDrawSurface.cpp', 'Stream.cpp', 'BlockDXT.cpp', 'ColorBlock.cpp', 'Image.cpp', 'FlipDXT.cpp']
incs = ['.',
'../../',
diff --git a/source/blender/imbuf/intern/dds/Stream.h b/source/blender/imbuf/intern/dds/Stream.h
index 9f513ca8aba..7fed4ca89e7 100644
--- a/source/blender/imbuf/intern/dds/Stream.h
+++ b/source/blender/imbuf/intern/dds/Stream.h
@@ -45,5 +45,4 @@ unsigned int mem_read(Stream & mem, unsigned short & i);
unsigned int mem_read(Stream & mem, unsigned char & i);
unsigned int mem_read(Stream & mem, unsigned char *i, unsigned int cnt);
-#endif // __STREAM_H__
-
+#endif /* __STREAM_H__ */
diff --git a/source/blender/imbuf/intern/dds/dds_api.cpp b/source/blender/imbuf/intern/dds/dds_api.cpp
index 7aacbf20bae..5459cffe590 100644
--- a/source/blender/imbuf/intern/dds/dds_api.cpp
+++ b/source/blender/imbuf/intern/dds/dds_api.cpp
@@ -29,6 +29,7 @@
#include <dds_api.h>
#include <Stream.h>
#include <DirectDrawSurface.h>
+#include <FlipDXT.h>
#include <stdio.h> // printf
#include <fstream>
@@ -162,13 +163,18 @@ struct ImBuf *imb_load_dds(unsigned char *mem, size_t size, int flags, char colo
rect[i] = col;
}
- if (ibuf->dds_data.fourcc != FOURCC_DDS)
+ if (ibuf->dds_data.fourcc != FOURCC_DDS) {
ibuf->dds_data.data = (unsigned char*)dds.readData(ibuf->dds_data.size);
+
+ /* flip compressed texture */
+ FlipDXTCImage(dds.width(), dds.height(), dds.mipmapCount(), dds.fourCC(), ibuf->dds_data.data);
+ }
else {
ibuf->dds_data.data = NULL;
ibuf->dds_data.size = 0;
}
+ /* flip uncompressed texture */
IMB_flipy(ibuf);
}
diff --git a/source/blender/imbuf/intern/divers.c b/source/blender/imbuf/intern/divers.c
index 9ce5d0e30da..55c1b02e90b 100644
--- a/source/blender/imbuf/intern/divers.c
+++ b/source/blender/imbuf/intern/divers.c
@@ -43,6 +43,8 @@
#include "IMB_colormanagement.h"
#include "IMB_colormanagement_intern.h"
+#include "BLI_threads.h"
+
#include "MEM_guardedalloc.h"
/**************************** Interlace/Deinterlace **************************/
@@ -60,7 +62,7 @@ void IMB_de_interlace(ImBuf *ibuf)
tbuf1 = IMB_allocImBuf(ibuf->x, ibuf->y / 2, 32, IB_rect);
tbuf2 = IMB_allocImBuf(ibuf->x, ibuf->y / 2, 32, IB_rect);
- ibuf->x *= 2;
+ ibuf->x *= 2;
IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
@@ -559,7 +561,7 @@ void IMB_rect_from_float(ImBuf *ibuf)
}
/* converts from linear float to sRGB byte for part of the texture, buffer will hold the changed part */
-void IMB_partial_rect_from_float(ImBuf *ibuf, float *buffer, int x, int y, int w, int h)
+void IMB_partial_rect_from_float(ImBuf *ibuf, float *buffer, int x, int y, int w, int h, int is_data)
{
float *rect_float;
uchar *rect_byte;
@@ -578,14 +580,27 @@ void IMB_partial_rect_from_float(ImBuf *ibuf, float *buffer, int x, int y, int w
rect_float = ibuf->rect_float + (x + y * ibuf->x) * ibuf->channels;
rect_byte = (uchar *)ibuf->rect + (x + y * ibuf->x) * 4;
- IMB_buffer_float_from_float(buffer, rect_float,
- ibuf->channels, IB_PROFILE_SRGB, profile_from, predivide,
- w, h, w, ibuf->x);
+ if (is_data) {
+ /* exception for non-color data, just copy float */
+ IMB_buffer_float_from_float(buffer, rect_float,
+ ibuf->channels, IB_PROFILE_LINEAR_RGB, IB_PROFILE_LINEAR_RGB, 0,
+ w, h, w, ibuf->x);
- /* XXX: need to convert to image buffer's rect space */
- IMB_buffer_byte_from_float(rect_byte, buffer,
- 4, ibuf->dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB, 0,
- w, h, ibuf->x, w);
+ /* and do color space conversion to byte */
+ IMB_buffer_byte_from_float(rect_byte, rect_float,
+ 4, ibuf->dither, IB_PROFILE_SRGB, profile_from, predivide,
+ w, h, ibuf->x, w);
+ }
+ else {
+ IMB_buffer_float_from_float(buffer, rect_float,
+ ibuf->channels, IB_PROFILE_SRGB, profile_from, predivide,
+ w, h, w, ibuf->x);
+
+ /* XXX: need to convert to image buffer's rect space */
+ IMB_buffer_byte_from_float(rect_byte, buffer,
+ 4, ibuf->dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB, 0,
+ w, h, ibuf->x, w);
+ }
/* ensure user flag is reset */
ibuf->userflags &= ~IB_RECT_INVALID;
@@ -599,9 +614,18 @@ void IMB_float_from_rect(ImBuf *ibuf)
if (ibuf->rect == NULL)
return;
+ /* lock the color management thread
+ * need this because allocated but not filled float buffer will confuse
+ * display transform which lead to black areas across the frame
+ */
+ BLI_lock_thread(LOCK_COLORMANAGE);
+
if (ibuf->rect_float == NULL) {
- if (imb_addrectfloatImBuf(ibuf) == 0)
+ if (imb_addrectfloatImBuf(ibuf) == 0) {
+ BLI_unlock_thread(LOCK_COLORMANAGE);
+
return;
+ }
}
/* first, create float buffer in non-linear space */
@@ -611,6 +635,8 @@ void IMB_float_from_rect(ImBuf *ibuf)
/* then make float be in linear space */
IMB_colormanagement_colorspace_to_scene_linear(ibuf->rect_float, ibuf->x, ibuf->y, ibuf->channels,
ibuf->rect_colorspace, predivide);
+
+ BLI_unlock_thread(LOCK_COLORMANAGE);
}
/* no profile conversion */
@@ -697,7 +723,7 @@ void IMB_buffer_float_clamp(float *buf, int width, int height)
{
int i, total = width * height * 4;
for (i = 0; i < total; i++) {
- buf[i] = minf(1.0, buf[i]);
+ buf[i] = min_ff(1.0, buf[i]);
}
}
diff --git a/source/blender/imbuf/intern/filetype.c b/source/blender/imbuf/intern/filetype.c
index ed4db50035d..5c2dc0c7df9 100644
--- a/source/blender/imbuf/intern/filetype.c
+++ b/source/blender/imbuf/intern/filetype.c
@@ -74,8 +74,8 @@ ImFileType IMB_FILE_TYPES[] = {
{NULL, NULL, imb_is_a_targa, imb_ftype_default, imb_loadtarga, imb_savetarga, NULL, 0, TGA, COLOR_ROLE_DEFAULT_BYTE},
{NULL, NULL, imb_is_a_iris, imb_ftype_iris, imb_loadiris, imb_saveiris, NULL, 0, IMAGIC, COLOR_ROLE_DEFAULT_BYTE},
#ifdef WITH_CINEON
- {NULL, NULL, imb_is_dpx, imb_ftype_default, imb_loaddpx, imb_save_dpx, NULL, IM_FTYPE_FLOAT, DPX, COLOR_ROLE_DEFAULT_FLOAT},
- {NULL, NULL, imb_is_cineon, imb_ftype_default, imb_loadcineon, imb_savecineon, NULL, IM_FTYPE_FLOAT, CINEON, COLOR_ROLE_DEFAULT_FLOAT},
+ {NULL, NULL, imb_is_dpx, imb_ftype_default, imb_load_dpx, imb_save_dpx, NULL, IM_FTYPE_FLOAT, DPX, COLOR_ROLE_DEFAULT_FLOAT},
+ {NULL, NULL, imb_is_cineon, imb_ftype_default, imb_load_cineon, imb_save_cineon, NULL, IM_FTYPE_FLOAT, CINEON, COLOR_ROLE_DEFAULT_FLOAT},
#endif
#ifdef WITH_TIFF
{imb_inittiff, NULL, imb_is_a_tiff, imb_ftype_default, imb_loadtiff, imb_savetiff, imb_loadtiletiff, 0, TIF, COLOR_ROLE_DEFAULT_BYTE},
diff --git a/source/blender/imbuf/intern/imageprocess.c b/source/blender/imbuf/intern/imageprocess.c
index 3fd06a7c34d..57fbce710a1 100644
--- a/source/blender/imbuf/intern/imageprocess.c
+++ b/source/blender/imbuf/intern/imageprocess.c
@@ -125,15 +125,16 @@ static float P(float k)
}
#endif
-void bicubic_interpolation_color(struct ImBuf *in, unsigned char *outI, float *outF, float u, float v)
+void bicubic_interpolation_color(struct ImBuf *in, unsigned char outI[4], float outF[4], float u, float v)
{
int i, j, n, m, x1, y1;
unsigned char *dataI;
float a, b, w, wx, wy[4], outR, outG, outB, outA, *dataF;
/* sample area entirely outside image? */
- if (ceil(u) < 0 || floor(u) > in->x - 1 || ceil(v) < 0 || floor(v) > in->y - 1)
+ if (ceil(u) < 0 || floor(u) > in->x - 1 || ceil(v) < 0 || floor(v) > in->y - 1) {
return;
+ }
/* ImBuf in must have a valid rect or rect_float, assume this is already checked */
@@ -226,11 +227,12 @@ void bicubic_interpolation_color(struct ImBuf *in, unsigned char *outI, float *o
void bicubic_interpolation(ImBuf *in, ImBuf *out, float u, float v, int xout, int yout)
{
-
unsigned char *outI = NULL;
float *outF = NULL;
- if (in == NULL || (in->rect == NULL && in->rect_float == NULL)) return;
+ if (in == NULL || (in->rect == NULL && in->rect_float == NULL)) {
+ return;
+ }
pixel_from_buffer(out, &outI, &outF, xout, yout); /* gcc warns these could be uninitialized, but its ok */
@@ -239,7 +241,7 @@ void bicubic_interpolation(ImBuf *in, ImBuf *out, float u, float v, int xout, in
/* function assumes out to be zero'ed, only does RGBA */
/* BILINEAR INTERPOLATION */
-void bilinear_interpolation_color(struct ImBuf *in, unsigned char *outI, float *outF, float u, float v)
+void bilinear_interpolation_color(struct ImBuf *in, unsigned char outI[4], float outF[4], float u, float v)
{
float *row1, *row2, *row3, *row4, a, b;
unsigned char *row1I, *row2I, *row3I, *row4I;
@@ -257,7 +259,9 @@ void bilinear_interpolation_color(struct ImBuf *in, unsigned char *outI, float *
y2 = (int)ceil(v);
/* sample area entirely outside image? */
- if (x2 < 0 || x1 > in->x - 1 || y2 < 0 || y1 > in->y - 1) return;
+ if (x2 < 0 || x1 > in->x - 1 || y2 < 0 || y1 > in->y - 1) {
+ return;
+ }
if (outF) {
/* sample including outside of edges of image */
@@ -315,7 +319,7 @@ void bilinear_interpolation_color(struct ImBuf *in, unsigned char *outI, float *
/* Note about wrapping, the u/v still needs to be within the image bounds,
* just the interpolation is wrapped.
* This the same as bilinear_interpolation_color except it wraps rather than using empty and emptyI */
-void bilinear_interpolation_color_wrap(struct ImBuf *in, unsigned char *outI, float *outF, float u, float v)
+void bilinear_interpolation_color_wrap(struct ImBuf *in, unsigned char outI[4], float outF[4], float u, float v)
{
float *row1, *row2, *row3, *row4, a, b;
unsigned char *row1I, *row2I, *row3I, *row4I;
@@ -331,7 +335,9 @@ void bilinear_interpolation_color_wrap(struct ImBuf *in, unsigned char *outI, fl
y2 = (int)ceil(v);
/* sample area entirely outside image? */
- if (x2 < 0 || x1 > in->x - 1 || y2 < 0 || y1 > in->y - 1) return;
+ if (x2 < 0 || x1 > in->x - 1 || y2 < 0 || y1 > in->y - 1) {
+ return;
+ }
/* wrap interpolation pixels - main difference from bilinear_interpolation_color */
if (x1 < 0) x1 = in->x + x1;
@@ -378,11 +384,12 @@ void bilinear_interpolation_color_wrap(struct ImBuf *in, unsigned char *outI, fl
void bilinear_interpolation(ImBuf *in, ImBuf *out, float u, float v, int xout, int yout)
{
-
unsigned char *outI = NULL;
float *outF = NULL;
- if (in == NULL || (in->rect == NULL && in->rect_float == NULL)) return;
+ if (in == NULL || (in->rect == NULL && in->rect_float == NULL)) {
+ return;
+ }
pixel_from_buffer(out, &outI, &outF, xout, yout); /* gcc warns these could be uninitialized, but its ok */
@@ -391,7 +398,7 @@ void bilinear_interpolation(ImBuf *in, ImBuf *out, float u, float v, int xout, i
/* function assumes out to be zero'ed, only does RGBA */
/* NEAREST INTERPOLATION */
-void neareast_interpolation_color(struct ImBuf *in, unsigned char *outI, float *outF, float u, float v)
+void neareast_interpolation_color(struct ImBuf *in, unsigned char outI[4], float outF[4], float u, float v)
{
float *dataF;
unsigned char *dataI;
@@ -403,7 +410,9 @@ void neareast_interpolation_color(struct ImBuf *in, unsigned char *outI, float *
y1 = (int)(v);
/* sample area entirely outside image? */
- if (x1 < 0 || x1 > in->x - 1 || y1 < 0 || y1 > in->y - 1) return;
+ if (x1 < 0 || x1 > in->x - 1 || y1 < 0 || y1 > in->y - 1) {
+ return;
+ }
/* sample including outside of edges of image */
if (x1 < 0 || y1 < 0) {
@@ -435,16 +444,17 @@ void neareast_interpolation_color(struct ImBuf *in, unsigned char *outI, float *
outF[2] = dataF[2];
outF[3] = dataF[3];
}
- }
+ }
}
void neareast_interpolation(ImBuf *in, ImBuf *out, float x, float y, int xout, int yout)
{
-
unsigned char *outI = NULL;
float *outF = NULL;
- if (in == NULL || (in->rect == NULL && in->rect_float == NULL)) return;
+ if (in == NULL || (in->rect == NULL && in->rect_float == NULL)) {
+ return;
+ }
pixel_from_buffer(out, &outI, &outF, xout, yout); /* gcc warns these could be uninitialized, but its ok */
diff --git a/source/blender/imbuf/intern/indexer.c b/source/blender/imbuf/intern/indexer.c
index 97316c48621..5dda33dfd62 100644
--- a/source/blender/imbuf/intern/indexer.c
+++ b/source/blender/imbuf/intern/indexer.c
@@ -36,18 +36,19 @@
#include "IMB_indexer.h"
#include "IMB_anim.h"
-#include "AVI_avi.h"
#include "imbuf.h"
#include "MEM_guardedalloc.h"
#include "DNA_userdef_types.h"
#include "BKE_global.h"
-#ifdef WITH_FFMPEG
-
-#include "ffmpeg_compat.h"
+#ifdef WITH_AVI
+# include "AVI_avi.h"
+#endif
-#endif //WITH_FFMPEG
+#ifdef WITH_FFMPEG
+# include "ffmpeg_compat.h"
+#endif
static char magic[] = "BlenMIdx";
@@ -869,9 +870,9 @@ static void index_rebuild_ffmpeg_proc_decoded_frame(
context->start_pts_set = TRUE;
}
- context->frameno = floor((pts - context->start_pts)
- * context->pts_time_base
- * context->frame_rate + 0.5f);
+ context->frameno = floor((pts - context->start_pts) *
+ context->pts_time_base *
+ context->frame_rate + 0.5f);
/* decoding starts *always* on I-Frames,
* so: P-Frames won't work, even if all the
@@ -955,9 +956,9 @@ static int index_rebuild_ffmpeg(FFmpegIndexBuilderContext *context,
}
/* process pictures still stuck in decoder engine after EOF
- according to ffmpeg docs using 0-size packets.
-
- At least, if we haven't already stopped... */
+ * according to ffmpeg docs using 0-size packets.
+ *
+ * At least, if we haven't already stopped... */
if (!*stop) {
int frame_finished;
@@ -989,6 +990,7 @@ static int index_rebuild_ffmpeg(FFmpegIndexBuilderContext *context,
* - internal AVI (fallback) rebuilder
* ---------------------------------------------------------------------- */
+#ifdef WITH_AVI
typedef struct FallbackIndexBuilderContext {
int anim_type;
@@ -1149,6 +1151,8 @@ static void index_rebuild_fallback(FallbackIndexBuilderContext *context,
}
}
+#endif /* WITH_AVI */
+
/* ----------------------------------------------------------------------
* - public API
* ---------------------------------------------------------------------- */
@@ -1164,15 +1168,19 @@ IndexBuildContext *IMB_anim_index_rebuild_context(struct anim *anim, IMB_Timecod
context = index_ffmpeg_create_context(anim, tcs_in_use, proxy_sizes_in_use, quality);
break;
#endif
+#ifdef WITH_AVI
default:
context = index_fallback_create_context(anim, tcs_in_use, proxy_sizes_in_use, quality);
break;
+#endif
}
if (context)
context->anim_type = anim->curtype;
return context;
+
+ (void)tcs_in_use, (void)proxy_sizes_in_use, (void)quality;
}
void IMB_anim_index_rebuild(struct IndexBuildContext *context,
@@ -1184,10 +1192,14 @@ void IMB_anim_index_rebuild(struct IndexBuildContext *context,
index_rebuild_ffmpeg((FFmpegIndexBuilderContext *)context, stop, do_update, progress);
break;
#endif
+#ifdef WITH_AVI
default:
index_rebuild_fallback((FallbackIndexBuilderContext *)context, stop, do_update, progress);
break;
+#endif
}
+
+ (void)stop, (void)do_update, (void)progress;
}
void IMB_anim_index_rebuild_finish(IndexBuildContext *context, short stop)
@@ -1198,10 +1210,15 @@ void IMB_anim_index_rebuild_finish(IndexBuildContext *context, short stop)
index_rebuild_ffmpeg_finish((FFmpegIndexBuilderContext *)context, stop);
break;
#endif
+#ifdef WITH_AVI
default:
index_rebuild_fallback_finish((FallbackIndexBuilderContext *)context, stop);
break;
+#endif
}
+
+ (void)stop;
+ (void)proxy_sizes; /* static defined at top of the file */
}
diff --git a/source/blender/imbuf/intern/iris.c b/source/blender/imbuf/intern/iris.c
index 3fd25fff92f..dec5f6fb39e 100644
--- a/source/blender/imbuf/intern/iris.c
+++ b/source/blender/imbuf/intern/iris.c
@@ -83,21 +83,21 @@ typedef struct {
#define OFFSET_R 0 /* this is byte order dependent */
#define OFFSET_G 1
#define OFFSET_B 2
-#define OFFSET_A 3
+// #define OFFSET_A 3
#define CHANOFFSET(z) (3 - (z)) /* this is byte order dependent */
-#define TYPEMASK 0xff00
+// #define TYPEMASK 0xff00
#define BPPMASK 0x00ff
-#define ITYPE_VERBATIM 0x0000
+// #define ITYPE_VERBATIM 0x0000 // UNUSED
#define ITYPE_RLE 0x0100
#define ISRLE(type) (((type) & 0xff00) == ITYPE_RLE)
-#define ISVERBATIM(type) (((type) & 0xff00) == ITYPE_VERBATIM)
+// #define ISVERBATIM(type) (((type) & 0xff00) == ITYPE_VERBATIM)
#define BPP(type) ((type) & BPPMASK)
#define RLE(bpp) (ITYPE_RLE | (bpp))
-#define VERBATIM(bpp) (ITYPE_VERBATIM | (bpp))
-#define IBUFSIZE(pixels) ((pixels + (pixels >> 6)) << 2)
-#define RLE_NOP 0x00
+// #define VERBATIM(bpp) (ITYPE_VERBATIM | (bpp)) // UNUSED
+// #define IBUFSIZE(pixels) ((pixels + (pixels >> 6)) << 2) // UNUSED
+// #define RLE_NOP 0x00
/* funcs */
static void readheader(FILE *inf, IMAGE *image);
@@ -408,7 +408,7 @@ struct ImBuf *imb_loadiris(unsigned char *mem, size_t size, int flags, char colo
}
MEM_freeN(starttab);
- MEM_freeN(lengthtab);
+ MEM_freeN(lengthtab);
}
else {
@@ -613,7 +613,7 @@ static void expandrow2(float *optr, unsigned char *iptr, int z)
optr += 4;
}
}
- }
+ }
}
static void expandrow(unsigned char *optr, unsigned char *iptr, int z)
diff --git a/source/blender/imbuf/intern/jp2.c b/source/blender/imbuf/intern/jp2.c
index dd559c55402..692ba3c49ea 100644
--- a/source/blender/imbuf/intern/jp2.c
+++ b/source/blender/imbuf/intern/jp2.c
@@ -436,7 +436,7 @@ static void cinema_parameters(opj_cparameters_t *parameters)
parameters->image_offset_y0 = 0;
/*Codeblock size = 32 * 32*/
- parameters->cblockw_init = 32;
+ parameters->cblockw_init = 32;
parameters->cblockh_init = 32;
parameters->csty |= 0x01;
@@ -544,6 +544,10 @@ static void cinema_setup_encoder(opj_cparameters_t *parameters, opj_image_t *ima
parameters->cp_disto_alloc = 1;
}
+static float channel_colormanage_noop(float value)
+{
+ return value;
+}
static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
{
@@ -560,9 +564,20 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */
opj_image_t *image = NULL;
+ float (*chanel_colormanage_cb)(float);
+
img_fol_t img_fol; /* only needed for cinema presets */
memset(&img_fol, 0, sizeof(img_fol_t));
+ if (ibuf->float_colorspace) {
+ /* float buffer was managed already, no need in color space conversion */
+ chanel_colormanage_cb = channel_colormanage_noop;
+ }
+ else {
+ /* standard linear-to-srgb conversion if float buffer wasn't managed */
+ chanel_colormanage_cb = linearrgb_to_srgb;
+ }
+
if (ibuf->ftype & JP2_CINE) {
if (ibuf->x == 4096 || ibuf->y == 2160)
@@ -587,7 +602,7 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
prec = 12;
numcomps = 3;
}
- else {
+ else {
/* Get settings from the imbuf */
color_space = (ibuf->ftype & JP2_YCC) ? CLRSPC_SYCC : CLRSPC_SRGB;
@@ -649,9 +664,9 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
if (numcomps == 4) {
PIXEL_LOOPER_BEGIN(rect_float)
{
- r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[0]));
- g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[1]));
- b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[2]));
+ r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[0]));
+ g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[1]));
+ b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[2]));
a[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[3]);
}
PIXEL_LOOPER_END;
@@ -659,9 +674,9 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
else {
PIXEL_LOOPER_BEGIN(rect_float)
{
- r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[0]));
- g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[1]));
- b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[2]));
+ r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[0]));
+ g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[1]));
+ b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[2]));
}
PIXEL_LOOPER_END;
}
@@ -671,9 +686,9 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
if (numcomps == 4) {
PIXEL_LOOPER_BEGIN(rect_float)
{
- r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[0]));
- g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[1]));
- b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[2]));
+ r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[0]));
+ g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[1]));
+ b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[2]));
a[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[3]);
}
PIXEL_LOOPER_END;
@@ -681,9 +696,9 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
else {
PIXEL_LOOPER_BEGIN(rect_float)
{
- r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[0]));
- g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[1]));
- b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[2]));
+ r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[0]));
+ g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[1]));
+ b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[2]));
}
PIXEL_LOOPER_END;
}
@@ -693,9 +708,9 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
if (numcomps == 4) {
PIXEL_LOOPER_BEGIN(rect_float)
{
- r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[0]));
- g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[1]));
- b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[2]));
+ r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[0]));
+ g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[1]));
+ b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[2]));
a[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[3]);
}
PIXEL_LOOPER_END;
@@ -703,9 +718,9 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
else {
PIXEL_LOOPER_BEGIN(rect_float)
{
- r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[0]));
- g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[1]));
- b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[2]));
+ r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[0]));
+ g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[1]));
+ b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[2]));
}
PIXEL_LOOPER_END;
}
diff --git a/source/blender/imbuf/intern/jpeg.c b/source/blender/imbuf/intern/jpeg.c
index 691db96989d..61275a8937c 100644
--- a/source/blender/imbuf/intern/jpeg.c
+++ b/source/blender/imbuf/intern/jpeg.c
@@ -51,9 +51,9 @@
#include "IMB_colormanagement.h"
#include "IMB_colormanagement_intern.h"
-#define IS_jpg(x) (x->ftype & JPG)
+// #define IS_jpg(x) (x->ftype & JPG) // UNUSED
#define IS_stdjpg(x) ((x->ftype & JPG_MSK) == JPG_STD)
-#define IS_vidjpg(x) ((x->ftype & JPG_MSK) == JPG_VID)
+// #define IS_vidjpg(x) ((x->ftype & JPG_MSK) == JPG_VID) // UNUSED
#define IS_jstjpg(x) ((x->ftype & JPG_MSK) == JPG_JST)
#define IS_maxjpg(x) ((x->ftype & JPG_MSK) == JPG_MAX)
diff --git a/source/blender/imbuf/intern/module.c b/source/blender/imbuf/intern/module.c
index 55a29333620..9141dad6f9c 100644
--- a/source/blender/imbuf/intern/module.c
+++ b/source/blender/imbuf/intern/module.c
@@ -28,16 +28,19 @@
#include <stddef.h>
#include "IMB_imbuf.h"
#include "IMB_filetype.h"
+#include "IMB_colormanagement_intern.h"
void IMB_init(void)
{
imb_filetypes_init();
imb_tile_cache_init();
+ colormanagement_init();
}
void IMB_exit(void)
{
imb_tile_cache_exit();
imb_filetypes_exit();
+ colormanagement_exit();
}
diff --git a/source/blender/imbuf/intern/moviecache.c b/source/blender/imbuf/intern/moviecache.c
index 78a989ad48f..d5aa635f548 100644
--- a/source/blender/imbuf/intern/moviecache.c
+++ b/source/blender/imbuf/intern/moviecache.c
@@ -386,7 +386,7 @@ ImBuf *IMB_moviecache_get(MovieCache *cache, void *userkey)
void IMB_moviecache_free(MovieCache *cache)
{
- PRINT("%s: create '%s' free\n", __func__, cache->name);
+ PRINT("%s: cache '%s' free\n", __func__, cache->name);
BLI_ghash_free(cache->hash, moviecache_keyfree, moviecache_valfree);
diff --git a/source/blender/imbuf/intern/openexr/CMakeLists.txt b/source/blender/imbuf/intern/openexr/CMakeLists.txt
index a5afc1abdc6..d5cb8e8a3b6 100644
--- a/source/blender/imbuf/intern/openexr/CMakeLists.txt
+++ b/source/blender/imbuf/intern/openexr/CMakeLists.txt
@@ -39,6 +39,9 @@ set(INC_SYS
)
set(SRC
+ openexr_api.h
+ openexr_multi.h
+
openexr_api.cpp
)
@@ -49,4 +52,4 @@ if(WITH_IMAGE_OPENEXR)
add_definitions(-DWITH_OPENEXR)
endif()
-blender_add_lib(bf_imbuf_openexr "${SRC}" "${INC}" "${INC_SYS}")
+blender_add_lib(bf_imbuf_openexr "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/imbuf/intern/openexr/openexr_api.cpp b/source/blender/imbuf/intern/openexr/openexr_api.cpp
index 13078921d1c..60c6e184070 100644
--- a/source/blender/imbuf/intern/openexr/openexr_api.cpp
+++ b/source/blender/imbuf/intern/openexr/openexr_api.cpp
@@ -238,19 +238,19 @@ public:
Iex::throwErrnoExc();
}
- virtual void write(const char c[], int n)
+ virtual void write(const char c[], int n)
{
errno = 0;
ofs.write(c, n);
check_error();
}
- virtual Int64 tellp()
+ virtual Int64 tellp()
{
return std::streamoff(ofs.tellp());
}
- virtual void seekp(Int64 pos)
+ virtual void seekp(Int64 pos)
{
ofs.seekp(pos);
check_error();
@@ -372,10 +372,10 @@ static int imb_save_openexr_half(struct ImBuf *ibuf, const char *name, int flags
for (int j = ibuf->x; j > 0; j--) {
to->r = from[0];
- to->g = from[1];
- to->b = from[2];
+ to->g = (channels >= 2) ? from[1] : from[0];
+ to->b = (channels >= 3) ? from[2] : from[0];
to->a = (channels >= 4) ? from[3] : 1.0f;
- to++; from += 4;
+ to++; from += channels;
}
}
}
@@ -383,7 +383,7 @@ static int imb_save_openexr_half(struct ImBuf *ibuf, const char *name, int flags
unsigned char *from;
for (int i = ibuf->y - 1; i >= 0; i--) {
- from = (unsigned char *)ibuf->rect + channels * i * width;
+ from = (unsigned char *)ibuf->rect + 4 * i * width;
for (int j = ibuf->x; j > 0; j--) {
to->r = srgb_to_linearrgb((float)from[0] / 255.0f);
@@ -448,8 +448,8 @@ static int imb_save_openexr_float(struct ImBuf *ibuf, const char *name, int flag
/* last scanline, stride negative */
rect[0] = ibuf->rect_float + channels * (height - 1) * width;
- rect[1] = rect[0] + 1;
- rect[2] = rect[0] + 2;
+ rect[1] = (channels >= 2) ? rect[0] + 1 : rect[0];
+ rect[2] = (channels >= 3) ? rect[0] + 2 : rect[0];
rect[3] = (channels >= 4) ? rect[0] + 3 : rect[0]; /* red as alpha, is this needed since alpha isn't written? */
frameBuffer.insert("R", Slice(Imf::FLOAT, (char *)rect[0], xstride, ystride));
diff --git a/source/blender/imbuf/intern/png.c b/source/blender/imbuf/intern/png.c
index 6310d8e105f..dcfebb95b87 100644
--- a/source/blender/imbuf/intern/png.c
+++ b/source/blender/imbuf/intern/png.c
@@ -558,7 +558,8 @@ ImBuf *imb_loadpng(unsigned char *mem, size_t size, int flags, char colorspace[I
MEM_freeN(pixels);
if (pixels16)
MEM_freeN(pixels16);
- MEM_freeN(row_pointers);
+ if (row_pointers)
+ MEM_freeN(row_pointers);
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
return(ibuf);
diff --git a/source/blender/imbuf/intern/radiance_hdr.c b/source/blender/imbuf/intern/radiance_hdr.c
index 5add372cd4e..72cec0e3749 100644
--- a/source/blender/imbuf/intern/radiance_hdr.c
+++ b/source/blender/imbuf/intern/radiance_hdr.c
@@ -154,7 +154,7 @@ static void FLOAT2RGBE(fCOLOR fcol, RGBE rgbe)
if (d <= 1e-32f)
rgbe[RED] = rgbe[GRN] = rgbe[BLU] = rgbe[EXP] = 0;
else {
- d = frexp(d, &e) * 256.f / d;
+ d = (float)frexp(d, &e) * 256.0f / d;
rgbe[RED] = (unsigned char)(fcol[RED] * d);
rgbe[GRN] = (unsigned char)(fcol[GRN] * d);
rgbe[BLU] = (unsigned char)(fcol[BLU] * d);
@@ -168,9 +168,9 @@ int imb_is_a_hdr(unsigned char *buf)
{
/* For recognition, Blender only loads first 32 bytes, so use #?RADIANCE id instead */
/* update: actually, the 'RADIANCE' part is just an optional program name, the magic word is really only the '#?' part */
- //if (strstr((char*)buf, "#?RADIANCE")) return 1;
+ //if (strstr((char *)buf, "#?RADIANCE")) return 1;
if (strstr((char *)buf, "#?")) return 1;
- // if (strstr((char*)buf, "32-bit_rle_rgbe")) return 1;
+ // if (strstr((char *)buf, "32-bit_rle_rgbe")) return 1;
return 0;
}
diff --git a/source/blender/imbuf/intern/readimage.c b/source/blender/imbuf/intern/readimage.c
index a1fa05d1098..5669a4cc45d 100644
--- a/source/blender/imbuf/intern/readimage.c
+++ b/source/blender/imbuf/intern/readimage.c
@@ -100,7 +100,8 @@ ImBuf *IMB_ibImageFromMemory(unsigned char *mem, size_t size, int flags, char co
}
}
- fprintf(stderr, "%s: unknown fileformat (%s)\n", __func__, descr);
+ if ((flags & IB_test) == 0)
+ fprintf(stderr, "%s: unknown fileformat (%s)\n", __func__, descr);
return NULL;
}
@@ -170,11 +171,12 @@ ImBuf *IMB_loadiffname(const char *filepath, int flags, char colorspace[IM_MAX_S
return ibuf;
}
-ImBuf *IMB_testiffname(const char *filepath, int flags, char colorspace[IM_MAX_SPACE])
+ImBuf *IMB_testiffname(const char *filepath, int flags)
{
ImBuf *ibuf;
int file;
char filepath_tx[IB_FILENAME_SIZE];
+ char colorspace[IM_MAX_SPACE];
imb_cache_filename(filepath_tx, filepath, flags);
diff --git a/source/blender/imbuf/intern/rectop.c b/source/blender/imbuf/intern/rectop.c
index a11f16d5669..8e072361583 100644
--- a/source/blender/imbuf/intern/rectop.c
+++ b/source/blender/imbuf/intern/rectop.c
@@ -447,7 +447,7 @@ void IMB_rectblend(struct ImBuf *dbuf, struct ImBuf *sbuf, int destx,
drectf += destskip * 4;
srectf += srcskip * 4;
- }
+ }
}
}
}
@@ -482,13 +482,13 @@ void IMB_rectfill(struct ImBuf *drect, const float col[4])
*rrectf++ = col[2];
*rrectf++ = col[3];
}
- }
+ }
}
void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height,
- const float col[4], struct ColorManagedDisplay *display,
- int x1, int y1, int x2, int y2)
+ const float col[4], struct ColorManagedDisplay *display,
+ int x1, int y1, int x2, int y2)
{
int i, j;
float a; /* alpha */
diff --git a/source/blender/imbuf/intern/scaling.c b/source/blender/imbuf/intern/scaling.c
index 389c3c42b6d..527f334d6a4 100644
--- a/source/blender/imbuf/intern/scaling.c
+++ b/source/blender/imbuf/intern/scaling.c
@@ -1051,7 +1051,7 @@ static ImBuf *scaledowny(struct ImBuf *ibuf, int newy)
sample -= 1.0f;
}
- }
+ }
if (do_rect) {
// printf("%ld %ld\n", (uchar *)rect - ((uchar *)ibuf->rect), rect_size);
diff --git a/source/blender/imbuf/intern/targa.c b/source/blender/imbuf/intern/targa.c
index 253680e4bea..eaad77f1ff9 100644
--- a/source/blender/imbuf/intern/targa.c
+++ b/source/blender/imbuf/intern/targa.c
@@ -55,9 +55,9 @@
/***/
typedef struct TARGA {
- unsigned char numid;
+ unsigned char numid;
unsigned char maptyp;
- unsigned char imgtyp;
+ unsigned char imgtyp;
short maporig;
short mapsize;
unsigned char mapbits;
diff --git a/source/blender/imbuf/intern/thumbs.c b/source/blender/imbuf/intern/thumbs.c
index ff7218d649c..a3ce332b609 100644
--- a/source/blender/imbuf/intern/thumbs.c
+++ b/source/blender/imbuf/intern/thumbs.c
@@ -175,7 +175,7 @@ static void to_hex_char(char *hexbytes, const unsigned char *bytes, int len)
static int uri_from_filename(const char *path, char *uri)
{
- char orig_uri[URI_MAX];
+ char orig_uri[URI_MAX];
const char *dirstart = path;
#ifdef WIN32
@@ -265,7 +265,7 @@ ImBuf *IMB_thumb_create(const char *path, ThumbSize size, ThumbSource source, Im
char thumb[40];
short tsize = 128;
short ex, ey;
- float scaledx, scaledy;
+ float scaledx, scaledy;
struct stat info;
switch (size) {
@@ -334,7 +334,7 @@ ImBuf *IMB_thumb_create(const char *path, ThumbSize size, ThumbSource source, Im
}
else {
IMB_freeImBuf(img);
- img = IMB_anim_previewframe(anim);
+ img = IMB_anim_previewframe(anim);
}
IMB_free_anim(anim);
}
@@ -401,7 +401,7 @@ ImBuf *IMB_thumb_read(const char *path, ThumbSize size)
if (!uri_from_filename(path, uri)) {
return NULL;
}
- if (thumbpath_from_uri(uri, thumb, sizeof(thumb), size)) {
+ if (thumbpath_from_uri(uri, thumb, sizeof(thumb), size)) {
img = IMB_loadiffname(thumb, IB_rect | IB_metadata, NULL);
}
@@ -438,7 +438,7 @@ ImBuf *IMB_thumb_manage(const char *path, ThumbSize size, ThumbSource source)
if (stat(path, &st)) {
return NULL;
- }
+ }
if (!uri_from_filename(path, uri)) {
return NULL;
}
diff --git a/source/blender/imbuf/intern/thumbs_blend.c b/source/blender/imbuf/intern/thumbs_blend.c
index cfc49d8cef5..73ced4095f9 100644
--- a/source/blender/imbuf/intern/thumbs_blend.c
+++ b/source/blender/imbuf/intern/thumbs_blend.c
@@ -166,7 +166,7 @@ void IMB_overlayblend_thumb(unsigned int *thumb, int width, int height, float as
margin_t = height - margin_b;
}
- {
+ {
int x, y;
int stride_x = (margin_r - margin_l) - 2;
diff --git a/source/blender/imbuf/intern/tiff.c b/source/blender/imbuf/intern/tiff.c
index 932a4941a0a..83830f260e1 100644
--- a/source/blender/imbuf/intern/tiff.c
+++ b/source/blender/imbuf/intern/tiff.c
@@ -114,7 +114,7 @@ static int imb_tiff_DummyMapProc(thandle_t fd, tdata_t *pbase, toff_t *psize)
* Reads data from an in-memory TIFF file.
*
* \param handle: Handle of the TIFF file (pointer to ImbTIFFMemFile).
- * \param data: Buffer to contain data (treat as void*).
+ * \param data: Buffer to contain data (treat as (void *)).
* \param n: Number of bytes to read.
*
* \return: Number of bytes actually read.
@@ -790,7 +790,14 @@ int imb_savetiff(ImBuf *ibuf, const char *name, int flags)
/* convert from float source */
float rgb[4];
- linearrgb_to_srgb_v3_v3(rgb, &fromf[from_i]);
+ if (ibuf->float_colorspace) {
+ /* float buffer was managed already, no need in color space conversion */
+ copy_v3_v3(rgb, &fromf[from_i]);
+ }
+ else {
+ /* standard linear-to-srgb conversion if float buffer wasn't managed */
+ linearrgb_to_srgb_v3_v3(rgb, &fromf[from_i]);
+ }
rgb[3] = fromf[from_i + 3];
diff --git a/source/blender/imbuf/intern/util.c b/source/blender/imbuf/intern/util.c
index 833671e3f2f..fe138a71a4a 100644
--- a/source/blender/imbuf/intern/util.c
+++ b/source/blender/imbuf/intern/util.c
@@ -211,7 +211,12 @@ int IMB_ispic(const char *filename)
static int isavi(const char *name)
{
+#ifdef WITH_AVI
return AVI_is_avi(name);
+#else
+ (void)name;
+ return FALSE;
+#endif
}
#ifdef WITH_QUICKTIME
@@ -223,6 +228,10 @@ static int isqtime(const char *name)
#ifdef WITH_FFMPEG
+/* BLI_vsnprintf in ffmpeg_log_callback() causes invalid warning */
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wmissing-format-attribute"
+
static char ffmpeg_last_error[1024];
static void ffmpeg_log_callback(void *ptr, int level, const char *format, va_list arg)
@@ -240,6 +249,8 @@ static void ffmpeg_log_callback(void *ptr, int level, const char *format, va_lis
}
}
+#pragma GCC diagnostic pop
+
void IMB_ffmpeg_init(void)
{
av_register_all();
@@ -405,7 +416,7 @@ int IMB_isanim(const char *filename)
type = imb_get_anim_type(filename);
}
else {
- return(FALSE);
+ return(FALSE);
}
}
else { /* no quicktime */
diff --git a/source/blender/makesdna/DNA_action_types.h b/source/blender/makesdna/DNA_action_types.h
index ffe25a7b1ec..d8d1ad78451 100644
--- a/source/blender/makesdna/DNA_action_types.h
+++ b/source/blender/makesdna/DNA_action_types.h
@@ -563,6 +563,7 @@ typedef enum eDopeSheet_FilterFlag {
/* general filtering 3 */
ADS_FILTER_INCL_HIDDEN = (1 << 26), /* include 'hidden' channels too (i.e. those from hidden Objects/Bones) */
ADS_FILTER_BY_FCU_NAME = (1 << 27), /* for F-Curves, filter by the displayed name (i.e. to isolate all Location curves only) */
+ ADS_FILTER_ONLY_ERRORS = (1 << 28), /* show only F-Curves which are disabled/have errors - for debugging drivers */
/* combination filters (some only used at runtime) */
ADS_FILTER_NOOBDATA = (ADS_FILTER_NOCAM | ADS_FILTER_NOMAT | ADS_FILTER_NOLAM | ADS_FILTER_NOCUR | ADS_FILTER_NOPART | ADS_FILTER_NOARM | ADS_FILTER_NOSPK)
@@ -604,11 +605,11 @@ typedef enum eSAction_Flag {
/* draw time in seconds instead of time in frames */
SACTION_DRAWTIME = (1 << 2),
/* don't filter action channels according to visibility */
- //SACTION_NOHIDE = (1<<3), // XXX depreceated... old animation system
+ //SACTION_NOHIDE = (1<<3), // XXX deprecated... old animation system
/* don't kill overlapping keyframes after transform */
SACTION_NOTRANSKEYCULL = (1 << 4),
/* don't include keyframes that are out of view */
- //SACTION_HORIZOPTIMISEON = (1<<5), // XXX depreceated... old irrelevant trick
+ //SACTION_HORIZOPTIMISEON = (1<<5), // XXX deprecated... old irrelevant trick
/* show pose-markers (local to action) in Action Editor mode */
SACTION_POSEMARKERS_SHOW = (1 << 6),
/* don't draw action channels using group colors (where applicable) */
@@ -653,7 +654,7 @@ typedef enum eAnimEdit_AutoSnap {
/* ************************************************ */
/* Legacy Data */
-/* WARNING: Action Channels are now depreceated... they were part of the old animation system!
+/* WARNING: Action Channels are now deprecated... they were part of the old animation system!
* (ONLY USED FOR DO_VERSIONS...)
*
* Action Channels belong to Actions. They are linked with an IPO block, and can also own
diff --git a/source/blender/makesdna/DNA_actuator_types.h b/source/blender/makesdna/DNA_actuator_types.h
index 4a5ad69cb91..b445d59db2c 100644
--- a/source/blender/makesdna/DNA_actuator_types.h
+++ b/source/blender/makesdna/DNA_actuator_types.h
@@ -46,21 +46,21 @@ typedef struct bAddObjectActuator {
struct Object *ob;
} bAddObjectActuator;
-typedef struct bActionActuator {
- struct bAction *act; /* Pointer to action */
- short type, flag; /* Playback type */ // not in use
- float sta, end; /* Start & End frames */
- char name[64]; /* For property-driven playback, MAX_NAME */
- char frameProp[64]; /* Set this property to the actions current frame, MAX_NAME */
- short blendin; /* Number of frames of blending */
- short priority; /* Execution priority */
- short layer; /* Animation layer */
- short end_reset; /* Ending the actuator (negative pulse) wont reset the the action to its starting frame */
- short strideaxis; /* Displacement axis */
- short pad;
- float stridelength; /* Displacement incurred by cycle */ // not in use
- float layer_weight; /* How much of the previous layer to use for blending. (<0 = disable, 0 = add mode) */
-} bActionActuator;
+typedef struct bActionActuator {
+ struct bAction *act; /* Pointer to action */
+ short type, flag; /* Playback type */ // not in use
+ float sta, end; /* Start & End frames */
+ char name[64]; /* For property-driven playback, MAX_NAME */
+ char frameProp[64]; /* Set this property to the actions current frame, MAX_NAME */
+ short blendin; /* Number of frames of blending */
+ short priority; /* Execution priority */
+ short layer; /* Animation layer */
+ short end_reset; /* Ending the actuator (negative pulse) wont reset the the action to its starting frame */
+ short strideaxis; /* Displacement axis */
+ short pad;
+ float stridelength; /* Displacement incurred by cycle */ // not in use
+ float layer_weight; /* How much of the previous layer to use for blending. (<0 = disable, 0 = add mode) */
+} bActionActuator;
typedef struct Sound3D {
float min_gain;
@@ -261,7 +261,7 @@ typedef struct bActuator {
/**
* For ipo's and props: to find out which object the actuator
* belongs to */
- struct Object *ob;
+ struct Object *ob;
} bActuator;
diff --git a/source/blender/makesdna/DNA_anim_types.h b/source/blender/makesdna/DNA_anim_types.h
index 7cf0d588710..1ac6e6db94b 100644
--- a/source/blender/makesdna/DNA_anim_types.h
+++ b/source/blender/makesdna/DNA_anim_types.h
@@ -246,13 +246,13 @@ typedef enum eFMod_Noise_Modifications {
/* stepped modifier data */
typedef struct FMod_Stepped {
- float step_size; /* Number of frames each interpolated value should be held */
- float offset; /* Reference frame number that stepping starts from */
-
- float start_frame; /* start frame of the frame range that modifier works in */
- float end_frame; /* end frame of the frame range that modifier works in */
-
- int flag; /* various settings */
+ float step_size; /* Number of frames each interpolated value should be held */
+ float offset; /* Reference frame number that stepping starts from */
+
+ float start_frame; /* start frame of the frame range that modifier works in */
+ float end_frame; /* end frame of the frame range that modifier works in */
+
+ int flag; /* various settings */
} FMod_Stepped;
/* stepped modifier range flags */
@@ -325,14 +325,14 @@ typedef enum eDriverTarget_TransformChannels {
*/
typedef struct DriverVar {
struct DriverVar *next, *prev;
-
- char name[64]; /* name of the variable to use in py-expression (must be valid python identifier) */
-
- DriverTarget targets[8]; /* MAX_DRIVER_TARGETS, target slots */
- short num_targets; /* number of targets actually used by this variable */
-
- short type; /* type of driver target (eDriverTarget_Types) */
- float curval; /* result of previous evaluation */
+
+ char name[64]; /* name of the variable to use in py-expression (must be valid python identifier) */
+
+ DriverTarget targets[8]; /* MAX_DRIVER_TARGETS, target slots */
+ short num_targets; /* number of targets actually used by this variable */
+
+ short type; /* type of driver target (eDriverTarget_Types) */
+ float curval; /* result of previous evaluation */
} DriverVar;
/* Driver Variable Types */
@@ -556,36 +556,36 @@ typedef struct AnimMapper {
*/
typedef struct NlaStrip {
struct NlaStrip *next, *prev;
-
- ListBase strips; /* 'Child' strips (used for 'meta' strips) */
- bAction *act; /* Action that is referenced by this strip (strip is 'user' of the action) */
- AnimMapper *remap; /* Remapping info this strip (for tweaking correspondence of action with context) */
-
- ListBase fcurves; /* F-Curves for controlling this strip's influence and timing */ // TODO: move out?
- ListBase modifiers; /* F-Curve modifiers to be applied to the entire strip's referenced F-Curves */
-
- char name[64]; /* User-Visible Identifier for Strip */
-
- float influence; /* Influence of strip */
- float strip_time; /* Current 'time' within action being used (automatically evaluated, but can be overridden) */
-
- float start, end; /* extents of the strip */
- float actstart, actend; /* range of the action to use */
-
- float repeat; /* The number of times to repeat the action range (only when no F-Curves) */
- float scale; /* The amount the action range is scaled by (only when no F-Curves) */
-
- float blendin, blendout; /* strip blending length (only used when there are no F-Curves) */
- short blendmode; /* strip blending mode (layer-based mixing) */
-
- short extendmode; /* strip extrapolation mode (time-based mixing) */
+
+ ListBase strips; /* 'Child' strips (used for 'meta' strips) */
+ bAction *act; /* Action that is referenced by this strip (strip is 'user' of the action) */
+ AnimMapper *remap; /* Remapping info this strip (for tweaking correspondence of action with context) */
+
+ ListBase fcurves; /* F-Curves for controlling this strip's influence and timing */ // TODO: move out?
+ ListBase modifiers; /* F-Curve modifiers to be applied to the entire strip's referenced F-Curves */
+
+ char name[64]; /* User-Visible Identifier for Strip */
+
+ float influence; /* Influence of strip */
+ float strip_time; /* Current 'time' within action being used (automatically evaluated, but can be overridden) */
+
+ float start, end; /* extents of the strip */
+ float actstart, actend; /* range of the action to use */
+
+ float repeat; /* The number of times to repeat the action range (only when no F-Curves) */
+ float scale; /* The amount the action range is scaled by (only when no F-Curves) */
+
+ float blendin, blendout; /* strip blending length (only used when there are no F-Curves) */
+ short blendmode; /* strip blending mode (layer-based mixing) */
+
+ short extendmode; /* strip extrapolation mode (time-based mixing) */
short pad1;
-
- short type; /* type of NLA strip */
-
- void *speaker_handle; /* handle for speaker objects */
-
- int flag; /* settings */
+
+ short type; /* type of NLA strip */
+
+ void *speaker_handle; /* handle for speaker objects */
+
+ int flag; /* settings */
int pad2;
} NlaStrip;
@@ -600,48 +600,48 @@ typedef enum eNlaStrip_Blend_Mode {
/* NLA Strip Extrpolation Mode */
typedef enum eNlaStrip_Extrapolate_Mode {
/* extend before first frame if no previous strips in track, and always hold+extend last frame */
- NLASTRIP_EXTEND_HOLD = 0,
+ NLASTRIP_EXTEND_HOLD = 0,
/* only hold+extend last frame */
- NLASTRIP_EXTEND_HOLD_FORWARD,
+ NLASTRIP_EXTEND_HOLD_FORWARD = 1,
/* don't contribute at all */
- NLASTRIP_EXTEND_NOTHING
+ NLASTRIP_EXTEND_NOTHING = 2
} eNlaStrip_Extrapolate_Mode;
/* NLA Strip Settings */
typedef enum eNlaStrip_Flag {
/* UI selection flags */
/* NLA strip is the active one in the track (also indicates if strip is being tweaked) */
- NLASTRIP_FLAG_ACTIVE = (1<<0),
+ NLASTRIP_FLAG_ACTIVE = (1<<0),
/* NLA strip is selected for editing */
- NLASTRIP_FLAG_SELECT = (1<<1),
-// NLASTRIP_FLAG_SELECT_L = (1<<2), // left handle selected
-// NLASTRIP_FLAG_SELECT_R = (1<<3), // right handle selected
+ NLASTRIP_FLAG_SELECT = (1<<1),
+// NLASTRIP_FLAG_SELECT_L = (1<<2), // left handle selected
+// NLASTRIP_FLAG_SELECT_R = (1<<3), // right handle selected
/* NLA strip uses the same action that the action being tweaked uses (not set for the twaking one though) */
- NLASTRIP_FLAG_TWEAKUSER = (1<<4),
-
+ NLASTRIP_FLAG_TWEAKUSER = (1<<4),
+
/* controls driven by local F-Curves */
/* strip influence is controlled by local F-Curve */
- NLASTRIP_FLAG_USR_INFLUENCE = (1<<5),
- NLASTRIP_FLAG_USR_TIME = (1<<6),
+ NLASTRIP_FLAG_USR_INFLUENCE = (1<<5),
+ NLASTRIP_FLAG_USR_TIME = (1<<6),
NLASTRIP_FLAG_USR_TIME_CYCLIC = (1<<7),
-
+
/* NLA strip length is synced to the length of the referenced action */
- NLASTRIP_FLAG_SYNC_LENGTH = (1<<9),
-
+ NLASTRIP_FLAG_SYNC_LENGTH = (1<<9),
+
/* playback flags (may be overridden by F-Curves) */
/* NLA strip blendin/out values are set automatically based on overlaps */
- NLASTRIP_FLAG_AUTO_BLENDS = (1<<10),
+ NLASTRIP_FLAG_AUTO_BLENDS = (1<<10),
/* NLA strip is played back in reverse order */
- NLASTRIP_FLAG_REVERSE = (1<<11),
+ NLASTRIP_FLAG_REVERSE = (1<<11),
/* NLA strip is muted (i.e. doesn't contribute in any way) */
- NLASTRIP_FLAG_MUTED = (1<<12),
+ NLASTRIP_FLAG_MUTED = (1<<12),
/* NLA Strip is played back in 'ping-pong' style */
- NLASTRIP_FLAG_MIRROR = (1<<13),
-
+ NLASTRIP_FLAG_MIRROR = (1<<13),
+
/* temporary editing flags */
/* NLA-Strip is really just a temporary meta used to facilitate easier transform code */
- NLASTRIP_FLAG_TEMP_META = (1<<30),
- NLASTRIP_FLAG_EDIT_TOUCHED = (1<<31)
+ NLASTRIP_FLAG_TEMP_META = (1<<30),
+ NLASTRIP_FLAG_EDIT_TOUCHED = (1<<31)
} eNlaStrip_Flag;
/* NLA Strip Type */
@@ -651,7 +651,7 @@ typedef enum eNlaStrip_Type {
/* 'transition' - blends between the adjacent strips */
NLASTRIP_TYPE_TRANSITION,
/* 'meta' - a strip which acts as a container for a few others */
- NLASTRIP_TYPE_META,
+ NLASTRIP_TYPE_META,
/* 'emit sound' - a strip which is used for timing when speaker emits sounds */
NLASTRIP_TYPE_SOUND
@@ -827,71 +827,71 @@ typedef struct AnimOverride {
* This datablock should be placed immediately after the ID block where it is used, so that
* the code which retrieves this data can do so in an easier manner. See blenkernel/intern/anim_sys.c for details.
*/
-typedef struct AnimData {
+typedef struct AnimData {
/* active action - acts as the 'tweaking track' for the NLA */
- bAction *action;
- /* temp-storage for the 'real' active action (i.e. the one used before the tweaking-action
- * took over to be edited in the Animation Editors)
+ bAction *action;
+ /* temp-storage for the 'real' active action (i.e. the one used before the tweaking-action
+ * took over to be edited in the Animation Editors)
*/
- bAction *tmpact;
- /* remapping-info for active action - should only be used if needed
- * (for 'foreign' actions that aren't working correctly)
+ bAction *tmpact;
+ /* remapping-info for active action - should only be used if needed
+ * (for 'foreign' actions that aren't working correctly)
*/
- AnimMapper *remap;
-
+ AnimMapper *remap;
+
/* nla-tracks */
- ListBase nla_tracks;
+ ListBase nla_tracks;
/* active NLA-strip (only set/used during tweaking, so no need to worry about dangling pointers) */
- NlaStrip *actstrip;
-
- /* 'drivers' for this ID-block's settings - FCurves, but are completely
- * separate from those for animation data
+ NlaStrip *actstrip;
+
+ /* 'drivers' for this ID-block's settings - FCurves, but are completely
+ * separate from those for animation data
*/
- ListBase drivers; /* standard user-created Drivers/Expressions (used as part of a rig) */
- ListBase overrides; /* temp storage (AnimOverride) of values for settings that are animated (but the value hasn't been keyframed) */
-
+ ListBase drivers; /* standard user-created Drivers/Expressions (used as part of a rig) */
+ ListBase overrides; /* temp storage (AnimOverride) of values for settings that are animated (but the value hasn't been keyframed) */
+
/* settings for animation evaluation */
- int flag; /* user-defined settings */
- int recalc; /* depsgraph recalculation flags */
-
+ int flag; /* user-defined settings */
+ int recalc; /* depsgraph recalculation flags */
+
/* settings for active action evaluation (based on NLA strip settings) */
- short act_blendmode; /* accumulation mode for active action */
- short act_extendmode; /* extrapolation mode for active action */
- float act_influence; /* influence for active action */
+ short act_blendmode; /* accumulation mode for active action */
+ short act_extendmode; /* extrapolation mode for active action */
+ float act_influence; /* influence for active action */
} AnimData;
/* Animation Data settings (mostly for NLA) */
typedef enum eAnimData_Flag {
/* only evaluate a single track in the NLA */
- ADT_NLA_SOLO_TRACK = (1<<0),
+ ADT_NLA_SOLO_TRACK = (1<<0),
/* don't use NLA */
- ADT_NLA_EVAL_OFF = (1<<1),
+ ADT_NLA_EVAL_OFF = (1<<1),
/* NLA is being 'tweaked' (i.e. in EditMode) */
- ADT_NLA_EDIT_ON = (1<<2),
+ ADT_NLA_EDIT_ON = (1<<2),
/* active Action for 'tweaking' does not have mapping applied for editing */
- ADT_NLA_EDIT_NOMAP = (1<<3),
+ ADT_NLA_EDIT_NOMAP = (1<<3),
/* NLA-Strip F-Curves are expanded in UI */
- ADT_NLA_SKEYS_COLLAPSED = (1<<4),
-
+ ADT_NLA_SKEYS_COLLAPSED = (1<<4),
+
/* drivers expanded in UI */
- ADT_DRIVERS_COLLAPSED = (1<<10),
+ ADT_DRIVERS_COLLAPSED = (1<<10),
/* don't execute drivers */
- ADT_DRIVERS_DISABLED = (1<<11),
-
+ ADT_DRIVERS_DISABLED = (1<<11),
+
/* AnimData block is selected in UI */
- ADT_UI_SELECTED = (1<<14),
+ ADT_UI_SELECTED = (1<<14),
/* AnimData block is active in UI */
- ADT_UI_ACTIVE = (1<<15),
-
+ ADT_UI_ACTIVE = (1<<15),
+
/* F-Curves from this AnimData block are not visible in the Graph Editor */
- ADT_CURVES_NOT_VISIBLE = (1<<16)
+ ADT_CURVES_NOT_VISIBLE = (1<<16)
} eAnimData_Flag;
/* Animation Data recalculation settings (to be set by depsgraph) */
typedef enum eAnimData_Recalc {
- ADT_RECALC_DRIVERS = (1<<0),
- ADT_RECALC_ANIM = (1<<1),
- ADT_RECALC_ALL = (ADT_RECALC_DRIVERS | ADT_RECALC_ANIM)
+ ADT_RECALC_DRIVERS = (1 << 0),
+ ADT_RECALC_ANIM = (1 << 1),
+ ADT_RECALC_ALL = (ADT_RECALC_DRIVERS | ADT_RECALC_ANIM)
} eAnimData_Recalc;
/* Base Struct for Anim ------------------------------------- */
diff --git a/source/blender/makesdna/DNA_armature_types.h b/source/blender/makesdna/DNA_armature_types.h
index 0afe3773c94..fd68a6d9a27 100644
--- a/source/blender/makesdna/DNA_armature_types.h
+++ b/source/blender/makesdna/DNA_armature_types.h
@@ -45,91 +45,91 @@ struct AnimData;
*/
typedef struct Bone {
- struct Bone *next, *prev; /* Next/prev elements within this list */
- IDProperty *prop; /* User-Defined Properties on this Bone */
- struct Bone *parent; /* Parent (ik parent if appropriate flag is set */
- ListBase childbase; /* Children */
- char name[64]; /* Name of the bone - must be unique within the armature, MAXBONENAME */
-
- float roll; /* roll is input for editmode, length calculated */
- float head[3];
- float tail[3]; /* head/tail and roll in Bone Space */
- float bone_mat[3][3]; /* rotation derived from head/tail/roll */
-
- int flag;
-
- float arm_head[3];
- float arm_tail[3]; /* head/tail in Armature Space (rest pos) */
- float arm_mat[4][4]; /* matrix: (bonemat(b)+head(b))*arm_mat(b-1), rest pos*/
- float arm_roll; /* roll in Armature Space (rest pos) */
-
- float dist, weight; /* dist, weight: for non-deformgroup deforms */
- float xwidth, length, zwidth; /* width: for block bones. keep in this order, transform! */
- float ease1, ease2; /* length of bezier handles */
- float rad_head, rad_tail; /* radius for head/tail sphere, defining deform as well, parent->rad_tip overrides rad_head*/
-
- float size[3]; /* patch for upward compat, UNUSED! */
- int layer; /* layers that bone appears on */
- short segments; /* for B-bones */
- short pad[1];
+ struct Bone *next, *prev; /* Next/prev elements within this list */
+ IDProperty *prop; /* User-Defined Properties on this Bone */
+ struct Bone *parent; /* Parent (ik parent if appropriate flag is set */
+ ListBase childbase; /* Children */
+ char name[64]; /* Name of the bone - must be unique within the armature, MAXBONENAME */
+
+ float roll; /* roll is input for editmode, length calculated */
+ float head[3];
+ float tail[3]; /* head/tail and roll in Bone Space */
+ float bone_mat[3][3]; /* rotation derived from head/tail/roll */
+
+ int flag;
+
+ float arm_head[3];
+ float arm_tail[3]; /* head/tail in Armature Space (rest pos) */
+ float arm_mat[4][4]; /* matrix: (bonemat(b)+head(b))*arm_mat(b-1), rest pos*/
+ float arm_roll; /* roll in Armature Space (rest pos) */
+
+ float dist, weight; /* dist, weight: for non-deformgroup deforms */
+ float xwidth, length, zwidth; /* width: for block bones. keep in this order, transform! */
+ float ease1, ease2; /* length of bezier handles */
+ float rad_head, rad_tail; /* radius for head/tail sphere, defining deform as well, parent->rad_tip overrides rad_head */
+
+ float size[3]; /* patch for upward compat, UNUSED! */
+ int layer; /* layers that bone appears on */
+ short segments; /* for B-bones */
+ short pad[1];
} Bone;
typedef struct bArmature {
- ID id;
+ ID id;
struct AnimData *adt;
-
- ListBase bonebase;
- ListBase chainbase;
- ListBase *edbo; /* editbone listbase, we use pointer so we can check state */
-
+
+ ListBase bonebase;
+ ListBase chainbase;
+ ListBase *edbo; /* editbone listbase, we use pointer so we can check state */
+
/* active bones should work like active object where possible
* - active and selection are unrelated
- * - active & hidden is not allowed
+ * - active & hidden is not allowed
* - from the user perspective active == last selected
* - active should be ignored when not visible (hidden layer) */
- Bone *act_bone; /* active bone (when not in editmode) */
- void *act_edbone; /* active editbone (in editmode) */
-
- void *sketch; /* sketch struct for etch-a-ton */
-
- int flag;
- int drawtype;
- int gevertdeformer; /* how vertex deformation is handled in the ge */
- int pad;
- short deformflag;
- short pathflag;
-
- unsigned int layer_used; /* for UI, to show which layers are there */
- unsigned int layer, layer_protected; /* for buttons to work, both variables in this order together */
-
-// XXX depreceated... old animaton system (armature only viz) ---
- short ghostep, ghostsize; /* number of frames to ghosts to show, and step between them */
- short ghosttype, pathsize; /* ghost drawing options and number of frames between points of path */
- int ghostsf, ghostef; /* start and end frames of ghost-drawing range */
- int pathsf, pathef; /* start and end frames of path-calculation range for all bones */
- int pathbc, pathac; /* number of frames before/after current frame of path-calculation for all bones */
-// XXX end of depreceated code ----------------------------------
+ Bone *act_bone; /* active bone (when not in editmode) */
+ void *act_edbone; /* active editbone (in editmode) */
+
+ void *sketch; /* sketch struct for etch-a-ton */
+
+ int flag;
+ int drawtype;
+ int gevertdeformer; /* how vertex deformation is handled in the ge */
+ int pad;
+ short deformflag;
+ short pathflag;
+
+ unsigned int layer_used; /* for UI, to show which layers are there */
+ unsigned int layer, layer_protected; /* for buttons to work, both variables in this order together */
+
+// XXX deprecated... old animaton system (armature only viz) ---
+ short ghostep, ghostsize; /* number of frames to ghosts to show, and step between them */
+ short ghosttype, pathsize; /* ghost drawing options and number of frames between points of path */
+ int ghostsf, ghostef; /* start and end frames of ghost-drawing range */
+ int pathsf, pathef; /* start and end frames of path-calculation range for all bones */
+ int pathbc, pathac; /* number of frames before/after current frame of path-calculation for all bones */
+// XXX end of deprecated code ----------------------------------
} bArmature;
/* armature->flag */
/* don't use bit 7, was saved in files to disable stuff */
typedef enum eArmature_Flag {
- ARM_RESTPOS = (1<<0),
- ARM_DRAWXRAY = (1<<1), /* XRAY is here only for backwards converting */
- ARM_DRAWAXES = (1<<2),
- ARM_DRAWNAMES = (1<<3),
- ARM_POSEMODE = (1<<4),
- ARM_EDITMODE = (1<<5),
- ARM_DELAYDEFORM = (1<<6),
- ARM_DONT_USE = (1<<7),
- ARM_MIRROR_EDIT = (1<<8),
- ARM_AUTO_IK = (1<<9),
- ARM_NO_CUSTOM = (1<<10), /* made option negative, for backwards compat */
- ARM_COL_CUSTOM = (1<<11), /* draw custom colors */
- ARM_GHOST_ONLYSEL = (1<<12), /* when ghosting, only show selected bones (this should belong to ghostflag instead) */ /* XXX depreceated */
- ARM_DS_EXPAND = (1<<13), /* dopesheet channel is expanded */
- ARM_HAS_VIZ_DEPS = (1<<14), /* other objects are used for visualizing various states (hack for efficient updates) */
+ ARM_RESTPOS = (1<<0),
+ ARM_DRAWXRAY = (1<<1), /* XRAY is here only for backwards converting */
+ ARM_DRAWAXES = (1<<2),
+ ARM_DRAWNAMES = (1<<3),
+ ARM_POSEMODE = (1<<4),
+ ARM_EDITMODE = (1<<5),
+ ARM_DELAYDEFORM = (1<<6),
+ ARM_DONT_USE = (1<<7),
+ ARM_MIRROR_EDIT = (1<<8),
+ ARM_AUTO_IK = (1<<9),
+ ARM_NO_CUSTOM = (1<<10), /* made option negative, for backwards compat */
+ ARM_COL_CUSTOM = (1<<11), /* draw custom colors */
+ ARM_GHOST_ONLYSEL = (1<<12), /* when ghosting, only show selected bones (this should belong to ghostflag instead) */ /* XXX deprecated */
+ ARM_DS_EXPAND = (1<<13), /* dopesheet channel is expanded */
+ ARM_HAS_VIZ_DEPS = (1<<14), /* other objects are used for visualizing various states (hack for efficient updates) */
} eArmature_Flag;
/* armature->drawtype */
@@ -157,7 +157,7 @@ typedef enum eArmature_DeformFlag {
} eArmature_DeformFlag;
/* armature->pathflag */
-// XXX depreceated... old animation system (armature only viz)
+// XXX deprecated... old animation system (armature only viz)
typedef enum eArmature_PathFlag {
ARM_PATH_FNUMS = (1<<0),
ARM_PATH_KFRAS = (1<<1),
@@ -167,7 +167,7 @@ typedef enum eArmature_PathFlag {
} eArmature_PathFlag;
/* armature->ghosttype */
-// XXX depreceated... old animation system (armature only viz)
+// XXX deprecated... old animation system (armature only viz)
typedef enum eArmature_GhostType {
ARM_GHOST_CUR = 0,
ARM_GHOST_RANGE = 1,
@@ -176,29 +176,29 @@ typedef enum eArmature_GhostType {
/* bone->flag */
typedef enum eBone_Flag {
- BONE_SELECTED = (1<<0),
- BONE_ROOTSEL = (1<<1),
- BONE_TIPSEL = (1<<2),
- BONE_TRANSFORM = (1<<3), /* Used instead of BONE_SELECTED during transform */
- BONE_CONNECTED = (1<<4), /* when bone has a parent, connect head of bone to parent's tail*/
- /* 32 used to be quatrot, was always set in files, do not reuse unless you clear it always */
- BONE_HIDDEN_P = (1<<6), /* hidden Bones when drawing PoseChannels */
- BONE_DONE = (1<<7), /* For detecting cyclic dependencies */
- BONE_DRAW_ACTIVE = (1<<8), /* active is on mouse clicks only - deprecated, ONLY USE FOR DRAWING */
- BONE_HINGE = (1<<9), /* No parent rotation or scale */
- BONE_HIDDEN_A = (1<<10), /* hidden Bones when drawing Armature Editmode */
- BONE_MULT_VG_ENV = (1<<11), /* multiplies vgroup with envelope */
- BONE_NO_DEFORM = (1<<12), /* bone doesn't deform geometry */
- BONE_UNKEYED = (1<<13), /* set to prevent destruction of its unkeyframed pose (after transform) */
- BONE_HINGE_CHILD_TRANSFORM = (1<<14), /* set to prevent hinge child bones from influencing the transform center */
- BONE_NO_SCALE = (1<<15), /* No parent scale */
- BONE_HIDDEN_PG = (1<<16), /* hidden bone when drawing PoseChannels (for ghost drawing) */
- BONE_DRAWWIRE = (1<<17), /* bone should be drawn as OB_WIRE, regardless of draw-types of view+armature */
- BONE_NO_CYCLICOFFSET = (1<<18), /* when no parent, bone will not get cyclic offset */
- BONE_EDITMODE_LOCKED = (1<<19), /* bone transforms are locked in EditMode */
- BONE_TRANSFORM_CHILD = (1<<20), /* Indicates that a parent is also being transformed */
- BONE_UNSELECTABLE = (1<<21), /* bone cannot be selected */
- BONE_NO_LOCAL_LOCATION = (1<<22) /* bone location is in armature space */
+ BONE_SELECTED = (1 << 0),
+ BONE_ROOTSEL = (1 << 1),
+ BONE_TIPSEL = (1 << 2),
+ BONE_TRANSFORM = (1 << 3), /* Used instead of BONE_SELECTED during transform */
+ BONE_CONNECTED = (1 << 4), /* when bone has a parent, connect head of bone to parent's tail*/
+ /* 32 used to be quatrot, was always set in files, do not reuse unless you clear it always */
+ BONE_HIDDEN_P = (1 << 6), /* hidden Bones when drawing PoseChannels */
+ BONE_DONE = (1 << 7), /* For detecting cyclic dependencies */
+ BONE_DRAW_ACTIVE = (1 << 8), /* active is on mouse clicks only - deprecated, ONLY USE FOR DRAWING */
+ BONE_HINGE = (1 << 9), /* No parent rotation or scale */
+ BONE_HIDDEN_A = (1 << 10), /* hidden Bones when drawing Armature Editmode */
+ BONE_MULT_VG_ENV = (1 << 11), /* multiplies vgroup with envelope */
+ BONE_NO_DEFORM = (1 << 12), /* bone doesn't deform geometry */
+ BONE_UNKEYED = (1 << 13), /* set to prevent destruction of its unkeyframed pose (after transform) */
+ BONE_HINGE_CHILD_TRANSFORM = (1 << 14), /* set to prevent hinge child bones from influencing the transform center */
+ BONE_NO_SCALE = (1 << 15), /* No parent scale */
+ BONE_HIDDEN_PG = (1 << 16), /* hidden bone when drawing PoseChannels (for ghost drawing) */
+ BONE_DRAWWIRE = (1 << 17), /* bone should be drawn as OB_WIRE, regardless of draw-types of view+armature */
+ BONE_NO_CYCLICOFFSET = (1 << 18), /* when no parent, bone will not get cyclic offset */
+ BONE_EDITMODE_LOCKED = (1 << 19), /* bone transforms are locked in EditMode */
+ BONE_TRANSFORM_CHILD = (1 << 20), /* Indicates that a parent is also being transformed */
+ BONE_UNSELECTABLE = (1 << 21), /* bone cannot be selected */
+ BONE_NO_LOCAL_LOCATION = (1 << 22) /* bone location is in armature space */
} eBone_Flag;
#define MAXBONENAME 64
diff --git a/source/blender/makesdna/DNA_boid_types.h b/source/blender/makesdna/DNA_boid_types.h
index ce5fc4b0c3c..f1930ffd643 100644
--- a/source/blender/makesdna/DNA_boid_types.h
+++ b/source/blender/makesdna/DNA_boid_types.h
@@ -36,18 +36,18 @@
typedef enum BoidRuleType {
eBoidRuleType_None = 0,
- eBoidRuleType_Goal = 1, /* go to goal assigned object or loudest assigned signal source */
- eBoidRuleType_Avoid = 2, /* get away from assigned object or loudest assigned signal source */
- eBoidRuleType_AvoidCollision = 3, /* manoeuver to avoid collisions with other boids and deflector object in near future */
- eBoidRuleType_Separate = 4, /* keep from going through other boids */
- eBoidRuleType_Flock = 5, /* move to center of neighbors and match their velocity */
- eBoidRuleType_FollowLeader = 6, /* follow a boid or assigned object */
- eBoidRuleType_AverageSpeed = 7, /* maintain speed, flight level or wander*/
- eBoidRuleType_Fight = 8, /* go to closest enemy and attack when in range */
- //eBoidRuleType_Protect = 9, /* go to enemy closest to target and attack when in range */
- //eBoidRuleType_Hide = 10, /* find a deflector move to it's other side from closest enemy */
- //eBoidRuleType_FollowPath = 11, /* move along a assigned curve or closest curve in a group */
- //eBoidRuleType_FollowWall = 12, /* move next to a deflector object's in direction of it's tangent */
+ eBoidRuleType_Goal = 1, /* go to goal assigned object or loudest assigned signal source */
+ eBoidRuleType_Avoid = 2, /* get away from assigned object or loudest assigned signal source */
+ eBoidRuleType_AvoidCollision = 3, /* manoeuver to avoid collisions with other boids and deflector object in near future */
+ eBoidRuleType_Separate = 4, /* keep from going through other boids */
+ eBoidRuleType_Flock = 5, /* move to center of neighbors and match their velocity */
+ eBoidRuleType_FollowLeader = 6, /* follow a boid or assigned object */
+ eBoidRuleType_AverageSpeed = 7, /* maintain speed, flight level or wander*/
+ eBoidRuleType_Fight = 8, /* go to closest enemy and attack when in range */
+ //eBoidRuleType_Protect = 9, /* go to enemy closest to target and attack when in range */
+ //eBoidRuleType_Hide = 10, /* find a deflector move to it's other side from closest enemy */
+ //eBoidRuleType_FollowPath = 11, /* move along a assigned curve or closest curve in a group */
+ //eBoidRuleType_FollowWall = 12, /* move next to a deflector object's in direction of it's tangent */
NUM_BOID_RULE_TYPES
} BoidRuleType;
@@ -67,7 +67,7 @@ typedef struct BoidRuleGoalAvoid {
BoidRule rule;
struct Object *ob;
int options;
- float fear_factor;
+ float fear_factor;
/* signals */
int signal_id, channels;
diff --git a/source/blender/makesdna/DNA_camera_types.h b/source/blender/makesdna/DNA_camera_types.h
index 73cebfb3d9f..1ece25c9f70 100644
--- a/source/blender/makesdna/DNA_camera_types.h
+++ b/source/blender/makesdna/DNA_camera_types.h
@@ -99,7 +99,7 @@ typedef struct Camera {
#define CAM_SHOWSENSOR 256
/* yafray: dof sampling switch */
-/* #define CAM_YF_NO_QMC 512 */ /* depreceated */
+/* #define CAM_YF_NO_QMC 512 */ /* deprecated */
/* Sensor fit */
#define CAMERA_SENSOR_FIT_AUTO 0
diff --git a/source/blender/makesdna/DNA_cloth_types.h b/source/blender/makesdna/DNA_cloth_types.h
index 4928a88b33e..df1cba6a44d 100644
--- a/source/blender/makesdna/DNA_cloth_types.h
+++ b/source/blender/makesdna/DNA_cloth_types.h
@@ -45,7 +45,7 @@
*/
typedef struct ClothSimSettings {
- struct LinkNode *cache; /* UNUSED atm */
+ struct LinkNode *cache; /* UNUSED atm */
float mingoal; /* see SB */
float Cdis; /* Mechanical damping of springs. */
float Cvi; /* Viscous/fluid damping. */
diff --git a/source/blender/makesdna/DNA_constraint_types.h b/source/blender/makesdna/DNA_constraint_types.h
index ad3284d430d..f1b7a7c3cc3 100644
--- a/source/blender/makesdna/DNA_constraint_types.h
+++ b/source/blender/makesdna/DNA_constraint_types.h
@@ -42,7 +42,7 @@ struct Text;
struct Ipo;
/* channels reside in Object or Action (ListBase) constraintChannels */
-// XXX depreceated... old AnimSys
+// XXX deprecated... old AnimSys
typedef struct bConstraintChannel {
struct bConstraintChannel *next, *prev;
struct Ipo *ipo;
@@ -170,7 +170,7 @@ typedef struct bSplineIKConstraint {
short numpoints; /* number of points to bound in points array */
short chainlen; /* number of bones ('n') that are in the chain */
- /* settings */
+ /* settings */
short flag; /* general settings for constraint */
short xzScaleMode; /* method used for determining the x & z scaling of the bones */
} bSplineIKConstraint;
@@ -182,7 +182,7 @@ typedef struct bSplineIKConstraint {
typedef struct bTrackToConstraint {
struct Object *tar;
int reserved1; /* I'll be using reserved1 and reserved2 as Track and Up flags,
- * not sure if that's what they were intented for anyway.
+ * not sure if that's what they were intended for anyway.
* Not sure either if it would create backward incompatibility if I were to rename them.
* - theeth*/
int reserved2;
@@ -340,7 +340,7 @@ typedef struct bTransformConstraint {
float from_max[3]; /* to map on to to_min/max range. */
float to_min[3]; /* range of motion on owner caused by target */
- float to_max[3];
+ float to_max[3];
} bTransformConstraint;
/* Pivot Constraint */
@@ -486,7 +486,7 @@ typedef enum eBConstraint_Flags {
CONSTRAINT_EXPAND = (1<<0),
/* pre-check for illegal object name or bone name */
CONSTRAINT_DISABLE = (1<<2),
- /* to indicate which Ipo should be shown, maybe for 3d access later too */
+ /* to indicate which Ipo should be shown, maybe for 3d access later too */
CONSTRAINT_ACTIVE = (1<<4),
/* to indicate that the owner's space should only be changed into ownspace, but not out of it */
CONSTRAINT_SPACEONCE = (1<<6),
@@ -515,7 +515,7 @@ typedef enum eBConstraint_SpaceTypes {
} eBConstraint_SpaceTypes;
/* bConstraintChannel.flag */
-// XXX depreceated... old AnimSys
+// XXX deprecated... old AnimSys
typedef enum eConstraintChannel_Flags {
CONSTRAINT_CHANNEL_SELECT = (1<<0),
CONSTRAINT_CHANNEL_PROTECTED = (1<<1)
@@ -539,7 +539,7 @@ typedef enum eCopyLocation_Flags {
LOCLIKE_X = (1<<0),
LOCLIKE_Y = (1<<1),
LOCLIKE_Z = (1<<2),
- /* LOCLIKE_TIP is a depreceated option... use headtail=1.0f instead */
+ /* LOCLIKE_TIP is a deprecated option... use headtail=1.0f instead */
LOCLIKE_TIP = (1<<3),
LOCLIKE_X_INVERT = (1<<4),
LOCLIKE_Y_INVERT = (1<<5),
@@ -664,7 +664,7 @@ typedef enum eSplineIK_Flags {
/* bones in the chain should not scale to fit the curve */
CONSTRAINT_SPLINEIK_SCALE_LIMITED = (1<<2),
/* evenly distribute the bones along the path regardless of length */
- CONSTRAINT_SPLINEIK_EVENSPLITS = (1<<3),
+ CONSTRAINT_SPLINEIK_EVENSPLITS = (1<<3),
/* don't adjust the x and z scaling of the bones by the curve radius */
CONSTRAINT_SPLINEIK_NO_CURVERAD = (1<<4)
} eSplineIK_Flags;
@@ -751,7 +751,7 @@ typedef enum eChildOf_Flags {
/* Restrictions for Pivot Constraint axis to consider for enabling constraint */
typedef enum ePivotConstraint_Axis {
/* do not consider this activity-clamping */
- PIVOTCON_AXIS_NONE = -1,
+ PIVOTCON_AXIS_NONE = -1,
/* consider -ve x-axis rotations */
PIVOTCON_AXIS_X_NEG = 0,
diff --git a/source/blender/makesdna/DNA_curve_types.h b/source/blender/makesdna/DNA_curve_types.h
index 284694f2b48..3cf84648ea6 100644
--- a/source/blender/makesdna/DNA_curve_types.h
+++ b/source/blender/makesdna/DNA_curve_types.h
@@ -74,7 +74,7 @@ typedef struct Path {
typedef struct BevList {
struct BevList *next, *prev;
int nr, dupe_nr;
- short poly, hole;
+ int poly, hole;
} BevList;
/* These two Lines with # tell makesdna this struct can be excluded. */
@@ -234,11 +234,11 @@ typedef struct Curve {
float ctime; /* current evaltime - for use by Objects parented to curves */
int totbox, actbox;
- struct TextBox *tb;
+ struct TextBox *tb;
- int selstart, selend;
+ int selstart, selend;
- struct CharInfo *strinfo;
+ struct CharInfo *strinfo;
struct CharInfo curinfo;
float bevfac1, bevfac2;
diff --git a/source/blender/makesdna/DNA_customdata_types.h b/source/blender/makesdna/DNA_customdata_types.h
index 377af042922..6f7bb5a723e 100644
--- a/source/blender/makesdna/DNA_customdata_types.h
+++ b/source/blender/makesdna/DNA_customdata_types.h
@@ -36,8 +36,6 @@
extern "C" {
#endif
-#include "DNA_defs.h" /* USE_BMESH_FORWARD_COMPAT */
-
/** descriptor and storage for a custom data layer */
typedef struct CustomDataLayer {
int type; /* type of data in layer */
@@ -74,7 +72,7 @@ typedef struct CustomData {
/* CustomData.type */
#define CD_MVERT 0
-#define CD_MSTICKY 1
+#define CD_MSTICKY 1 /* DEPRECATED */
#define CD_MDEFORMVERT 2
#define CD_MEDGE 3
#define CD_MFACE 4
@@ -82,7 +80,7 @@ typedef struct CustomData {
#define CD_MCOL 6
#define CD_ORIGINDEX 7
#define CD_NORMAL 8
-#define CD_POLYINDEX 9
+//#define CD_POLYINDEX 9
#define CD_PROP_FLT 10
#define CD_PROP_INT 11
#define CD_PROP_STR 12
@@ -118,7 +116,7 @@ typedef struct CustomData {
/* Bits for CustomDataMask */
#define CD_MASK_MVERT (1 << CD_MVERT)
-#define CD_MASK_MSTICKY (1 << CD_MSTICKY)
+#define CD_MASK_MSTICKY (1 << CD_MSTICKY) /* DEPRECATED */
#define CD_MASK_MDEFORMVERT (1 << CD_MDEFORMVERT)
#define CD_MASK_MEDGE (1 << CD_MEDGE)
#define CD_MASK_MFACE (1 << CD_MFACE)
@@ -126,7 +124,7 @@ typedef struct CustomData {
#define CD_MASK_MCOL (1 << CD_MCOL)
#define CD_MASK_ORIGINDEX (1 << CD_ORIGINDEX)
#define CD_MASK_NORMAL (1 << CD_NORMAL)
-#define CD_MASK_POLYINDEX (1 << CD_POLYINDEX)
+// #define CD_MASK_POLYINDEX (1 << CD_POLYINDEX)
#define CD_MASK_PROP_FLT (1 << CD_PROP_FLT)
#define CD_MASK_PROP_INT (1 << CD_PROP_INT)
#define CD_MASK_PROP_STR (1 << CD_PROP_STR)
diff --git a/source/blender/makesdna/DNA_defs.h b/source/blender/makesdna/DNA_defs.h
index 762e027f934..774fbcf081a 100644
--- a/source/blender/makesdna/DNA_defs.h
+++ b/source/blender/makesdna/DNA_defs.h
@@ -45,9 +45,6 @@
/* hrmf, we need a better include then this */
#include "../blenloader/BLO_sys_types.h" /* needed for int64_t only! */
-/* Must not be defined for BMesh, as this guards code for pre-BMesh code to load BMesh .blend files */
-/* #define USE_BMESH_FORWARD_COMPAT */
-
/* non-id name variables should use this length */
#define MAX_NAME 64
diff --git a/source/blender/makesdna/DNA_dynamicpaint_types.h b/source/blender/makesdna/DNA_dynamicpaint_types.h
index ca1b1bf1725..1f2a589dc27 100644
--- a/source/blender/makesdna/DNA_dynamicpaint_types.h
+++ b/source/blender/makesdna/DNA_dynamicpaint_types.h
@@ -136,7 +136,7 @@ typedef struct DynamicPaintSurface {
/* canvas flags */
#if 0 /* This should not be needed, having a valid WEIGHT_MCOL layer should be enough.
- * And if not, should be a general flag. But seems unecessary for now... */
+ * And if not, should be a general flag. But seems unnecessary for now... */
#define MOD_DPAINT_PREVIEW_READY (1<<0) /* if viewport preview is ready */
#endif
#define MOD_DPAINT_BAKING (1<<1) /* surface is already baking, so it wont get updated (loop) */
diff --git a/source/blender/makesdna/DNA_genfile.h b/source/blender/makesdna/DNA_genfile.h
index 20f7bb44e92..2d1549ff487 100644
--- a/source/blender/makesdna/DNA_genfile.h
+++ b/source/blender/makesdna/DNA_genfile.h
@@ -35,8 +35,8 @@
struct SDNA;
-extern unsigned char DNAstr[]; /* DNA.c */
-extern int DNAlen;
+extern const unsigned char DNAstr[]; /* DNA.c */
+extern const int DNAlen;
typedef enum eSDNA_Type {
SDNA_TYPE_CHAR = 0,
@@ -56,7 +56,7 @@ typedef enum eSDNA_Type {
/* define so switch statements don't complain */
#define SDNA_TYPE_VOID 9
-struct SDNA *DNA_sdna_from_data(void *data, int datalen, int do_endian_swap);
+struct SDNA *DNA_sdna_from_data(const void *data, const int datalen, int do_endian_swap);
void DNA_sdna_free(struct SDNA *sdna);
int DNA_struct_find_nr(struct SDNA *sdna, const char *str);
diff --git a/source/blender/makesdna/DNA_gpencil_types.h b/source/blender/makesdna/DNA_gpencil_types.h
index 3de5372d848..100968e7257 100644
--- a/source/blender/makesdna/DNA_gpencil_types.h
+++ b/source/blender/makesdna/DNA_gpencil_types.h
@@ -39,7 +39,7 @@
* This assumes that the bottom-left corner is (0,0)
*/
typedef struct bGPDspoint {
- float x, y, z; /* co-ordinates of point (usually 2d, but can be 3d as well) */
+ float x, y, z; /* co-ordinates of point (usually 2d, but can be 3d as well) */
float pressure; /* pressure of input device (from 0 to 1) at this point */
} bGPDspoint;
@@ -53,7 +53,7 @@ typedef struct bGPDstroke {
bGPDspoint *points; /* array of data-points for stroke */
int totpoints; /* number of data-points in array */
- short thickness; /* thickness of stroke (currently not used) */
+ short thickness; /* thickness of stroke (currently not used) */
short flag; /* various settings about this stroke */
} bGPDstroke;
@@ -94,7 +94,7 @@ typedef struct bGPDlayer {
ListBase frames; /* list of annotations to display for frames (bGPDframe list) */
bGPDframe *actframe; /* active frame (should be the frame that is currently being displayed) */
- int flag; /* settings for layer */
+ int flag; /* settings for layer */
short thickness; /* current thickness to apply to strokes */
short gstep; /* max number of frames between active and ghost to show (0=only those on either side) */
@@ -141,16 +141,16 @@ typedef struct bGPdata {
} bGPdata;
/* bGPdata->flag */
-// XXX many of these flags should be depreceated for more general ideas in 2.5
+// XXX many of these flags should be deprecated for more general ideas in 2.5
/* don't allow painting to occur at all */
- // XXX is depreceated - not well understood
+ // XXX is deprecated - not well understood
#define GP_DATA_LMBPLOCK (1<<0)
/* show debugging info in viewport (i.e. status print) */
#define GP_DATA_DISPINFO (1<<1)
/* in Action Editor, show as expanded channel */
#define GP_DATA_EXPAND (1<<2)
/* is the block overriding all clicks? */
- // XXX is depreceated - nasty old concept
+ // XXX is deprecated - nasty old concept
#define GP_DATA_EDITPAINT (1<<3)
/* new strokes are added in viewport space */
#define GP_DATA_VIEWALIGN (1<<4)
diff --git a/source/blender/makesdna/DNA_image_types.h b/source/blender/makesdna/DNA_image_types.h
index 38058dbb699..fe3550327f7 100644
--- a/source/blender/makesdna/DNA_image_types.h
+++ b/source/blender/makesdna/DNA_image_types.h
@@ -137,6 +137,7 @@ typedef struct Image {
#define IMA_CLAMP_U 16
#define IMA_CLAMP_V 32
#define IMA_TPAGE_REFRESH 64
+#define IMA_GLBIND_IS_DATA 128 /* opengl image texture bound as non-color data */
/* ima->type and ima->source moved to BKE_image.h, for API */
diff --git a/source/blender/makesdna/DNA_ipo_types.h b/source/blender/makesdna/DNA_ipo_types.h
index 6bf8dbbe73a..3e641fba1ac 100644
--- a/source/blender/makesdna/DNA_ipo_types.h
+++ b/source/blender/makesdna/DNA_ipo_types.h
@@ -28,7 +28,7 @@
/** \file DNA_ipo_types.h
* \ingroup DNA
* \deprecated
- * The contents of this file are now officially depreceated. They were used for the 'old' animation system,
+ * The contents of this file are now officially deprecated. They were used for the 'old' animation system,
* which has (as of 2.50) been replaced with a completely new system by Joshua Leung (aligorith). All defines,
* etc. are only still maintained to provide backwards compatibility for old files.
*/
@@ -93,7 +93,7 @@ typedef struct Ipo {
rctf cur; /* Rect defining extents of keyframes? */
short blocktype, showkey; /* blocktype: self-explanatory; showkey: either 0 or 1 (show vertical yellow lines for editing) */
- short muteipo, pad; /* muteipo: either 0 or 1 (whether ipo block is muted) */
+ short muteipo, pad; /* muteipo: either 0 or 1 (whether ipo block is muted) */
} Ipo;
/* ----------- adrcodes (for matching ipo-curves to data) ------------- */
diff --git a/source/blender/makesdna/DNA_key_types.h b/source/blender/makesdna/DNA_key_types.h
index 8494e663fbe..6e5861043c1 100644
--- a/source/blender/makesdna/DNA_key_types.h
+++ b/source/blender/makesdna/DNA_key_types.h
@@ -105,7 +105,7 @@ typedef struct Key {
/* Key->type: KeyBlocks are interpreted as... */
enum {
- /* Sequencial positions over time (using KeyBlock->pos and Key->ctime) */
+ /* Sequential positions over time (using KeyBlock->pos and Key->ctime) */
KEY_NORMAL = 0,
/* States to blend between (default) */
diff --git a/source/blender/makesdna/DNA_lamp_types.h b/source/blender/makesdna/DNA_lamp_types.h
index 4884db14c57..f36e65085c9 100644
--- a/source/blender/makesdna/DNA_lamp_types.h
+++ b/source/blender/makesdna/DNA_lamp_types.h
@@ -109,7 +109,7 @@ typedef struct Lamp {
struct PreviewImage *preview;
/* nodes */
- struct bNodeTree *nodetree;
+ struct bNodeTree *nodetree;
} Lamp;
/* **************** LAMP ********************* */
diff --git a/source/blender/makesdna/DNA_mask_types.h b/source/blender/makesdna/DNA_mask_types.h
index bf388d8c018..5b25d1a072c 100644
--- a/source/blender/makesdna/DNA_mask_types.h
+++ b/source/blender/makesdna/DNA_mask_types.h
@@ -211,4 +211,4 @@ enum {
MASK_ANIMF_EXPAND = (1 << 4)
};
-#endif // __DNA_MASK_TYPES_H__
+#endif /* __DNA_MASK_TYPES_H__ */
diff --git a/source/blender/makesdna/DNA_material_types.h b/source/blender/makesdna/DNA_material_types.h
index 940c5c5f30b..9a8d3bf981c 100644
--- a/source/blender/makesdna/DNA_material_types.h
+++ b/source/blender/makesdna/DNA_material_types.h
@@ -86,7 +86,7 @@ typedef struct Material {
ID id;
struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */
- short material_type, flag;
+ short material_type, flag;
/* note, keep this below synced with render_types.h */
float r, g, b;
float specr, specg, specb;
@@ -130,8 +130,11 @@ typedef struct Material {
/* for buttons and render*/
char rgbsel, texact, pr_type, use_nodes;
- short pr_back, pr_lamp, pr_texture, ml_flag; /* ml_flag is for disable base material */
+ short pr_lamp, pr_texture, ml_flag; /* ml_flag is for disable base material */
+ /* mapping */
+ char mapflag, pad;
+
/* shaders */
short diff_shader, spec_shader;
float roughness, refrac;
@@ -140,6 +143,8 @@ typedef struct Material {
float param[4]; /* size, smooth, size, smooth, for toonshader, 0 (fac) and 1 (fresnel) also for fresnel shader */
float rms;
float darkness;
+
+ /* runtime - OR'd from 'mtex' */
short texco, mapto;
/* ramp colors */
@@ -151,7 +156,7 @@ typedef struct Material {
float rampfac_col, rampfac_spec;
struct MTex *mtex[18]; /* MAX_MTEX */
- struct bNodeTree *nodetree;
+ struct bNodeTree *nodetree;
struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */
struct Group *group; /* light group */
struct PreviewImage *preview;
@@ -271,6 +276,9 @@ typedef struct Material {
#define MA_MODE_MASK 0x6fffffff /* all valid mode bits */
+/* mapflag */
+#define MA_MAPFLAG_UVPROJECT (1 << 0)
+
/* ray mirror fadeout */
#define MA_RAYMIR_FADETOSKY 0
#define MA_RAYMIR_FADETOMAT 1
@@ -284,6 +292,7 @@ typedef struct Material {
#define MA_CUBIC 1
#define MA_OBCOLOR 2
#define MA_APPROX_OCCLUSION 4
+#define MA_GROUP_LOCAL 8
/* diff_shader */
#define MA_DIFF_LAMBERT 0
@@ -337,7 +346,7 @@ typedef struct Material {
#define TEXCO_OBJECT 32
#define TEXCO_LAVECTOR 64
#define TEXCO_VIEW 128
-#define TEXCO_STICKY 256
+#define TEXCO_STICKY_ 256 // DEPRECATED
#define TEXCO_OSA 512
#define TEXCO_WINDOW 1024
#define NEED_UV 2048
diff --git a/source/blender/makesdna/DNA_mesh_types.h b/source/blender/makesdna/DNA_mesh_types.h
index e584cfd76ac..dd0845dbf1e 100644
--- a/source/blender/makesdna/DNA_mesh_types.h
+++ b/source/blender/makesdna/DNA_mesh_types.h
@@ -37,8 +37,6 @@
#include "DNA_ID.h"
#include "DNA_customdata_types.h"
-#include "DNA_defs.h" /* USE_BMESH_FORWARD_COMPAT */
-
struct AnimData;
struct DerivedMesh;
struct Ipo;
@@ -89,8 +87,7 @@ typedef struct Mesh {
/* array of colors for the tessellated faces, must be number of tessellated
* faces * 4 in length */
- struct MCol *mcol;
- struct MSticky *msticky;
+ struct MCol *mcol;
struct Mesh *texcomesh;
/* When the object is available, the preferred access method is: BMEdit_FromObject(ob) */
diff --git a/source/blender/makesdna/DNA_meshdata_types.h b/source/blender/makesdna/DNA_meshdata_types.h
index 54e1e762f8b..0c193e9be21 100644
--- a/source/blender/makesdna/DNA_meshdata_types.h
+++ b/source/blender/makesdna/DNA_meshdata_types.h
@@ -72,7 +72,7 @@ typedef struct MVert {
* at the moment alpha is abused for vertex painting
* and not used for transparency, note that red and blue are swapped */
typedef struct MCol {
- char a, r, g, b;
+ char a, r, g, b;
} MCol;
/* new face structure, replaces MFace, which is now
@@ -146,13 +146,9 @@ typedef struct MLoopCol {
mcol__tmp->a = mloopcol__tmp->a; \
} (void)0
-typedef struct MSticky {
- float co[2];
-} MSticky;
-
typedef struct MSelect {
int index;
- int type; /* EDITVERT/EDITEDGE/EDITFACE */
+ int type; /* ME_VSEL/ME_ESEL/ME_FSEL */
} MSelect;
/*tessellation uv face data*/
diff --git a/source/blender/makesdna/DNA_meta_types.h b/source/blender/makesdna/DNA_meta_types.h
index 2912650c77c..5b37ff523cb 100644
--- a/source/blender/makesdna/DNA_meta_types.h
+++ b/source/blender/makesdna/DNA_meta_types.h
@@ -93,7 +93,7 @@ typedef struct MetaBall {
/* used in editmode */
/*ListBase edit_elems;*/
- MetaElem *lastelem;
+ MetaElem *lastelem;
} MetaBall;
/* **************** METABALL ********************* */
diff --git a/source/blender/makesdna/DNA_modifier_types.h b/source/blender/makesdna/DNA_modifier_types.h
index 4172db90c05..c9e929ce41b 100644
--- a/source/blender/makesdna/DNA_modifier_types.h
+++ b/source/blender/makesdna/DNA_modifier_types.h
@@ -28,9 +28,6 @@
#include "DNA_defs.h"
#include "DNA_listBase.h"
-
-#define MODSTACK_DEBUG 1
-
/* WARNING ALERT! TYPEDEF VALUES ARE WRITTEN IN FILES! SO DO NOT CHANGE!
* (ONLY ADD NEW ITEMS AT THE END) */
@@ -78,6 +75,7 @@ typedef enum ModifierType {
eModifierType_DynamicPaint = 40,
eModifierType_Remesh = 41,
eModifierType_Skin = 42,
+ eModifierType_LaplacianSmooth = 43,
NUM_MODIFIER_TYPES
} ModifierType;
@@ -351,7 +349,7 @@ typedef struct UVProjectModifierData {
int flags;
int num_projectors;
float aspectx, aspecty;
- float scalex, scaley;
+ float scalex, scaley;
char uvlayer_name[64]; /* MAX_CUSTOMDATA_LAYER_NAME */
int uvlayer_tmp, pad;
} UVProjectModifierData;
@@ -364,10 +362,30 @@ typedef struct UVProjectModifierData {
typedef struct DecimateModifierData {
ModifierData modifier;
- float percent;
- int faceCount;
+ float percent; /* (mode == MOD_DECIM_MODE_COLLAPSE) */
+ short iter; /* (mode == MOD_DECIM_MODE_UNSUBDIV) */
+ short pad;
+ float angle; /* (mode == MOD_DECIM_MODE_DISSOLVE) */
+
+ char defgrp_name[64]; /* MAX_VGROUP_NAME */
+ short flag, mode;
+
+ /* runtime only */
+ int face_count, pad2;
} DecimateModifierData;
+enum {
+ MOD_DECIM_FLAG_INVERT_VGROUP = (1 << 0),
+ MOD_DECIM_FLAG_TRIANGULATE = (1 << 1), /* for collapse only. dont convert tri pairs back to quads */
+ MOD_DECIM_FLAG_ALL_BOUNDARY_VERTS = (1 << 2) /* for dissolve only. collapse all verts between 2 faces */
+};
+
+enum {
+ MOD_DECIM_MODE_COLLAPSE,
+ MOD_DECIM_MODE_UNSUBDIV,
+ MOD_DECIM_MODE_DISSOLVE /* called planar in the UI */
+};
+
/* Smooth modifier flags */
#define MOD_SMOOTH_X (1<<1)
#define MOD_SMOOTH_Y (1<<2)
@@ -686,7 +704,7 @@ typedef struct SimpleDeformModifierData {
struct Object *origin; /* object to control the origin of modifier space coordinates */
char vgroup_name[64]; /* optional vertexgroup name, MAX_VGROUP_NAME */
float factor; /* factors to control simple deforms */
- float limit[2]; /* lower and upper limit */
+ float limit[2]; /* lower and upper limit */
char mode; /* deform function */
char axis; /* lock axis (for taper and strech) */
@@ -705,6 +723,8 @@ typedef struct SimpleDeformModifierData {
/* indicates whether simple deform should use the local
* coordinates or global coordinates of origin */
+/* XXX, this should have never been an option, all other modifiers work relatively
+ * (so moving both objects makes no change!) - Campbell */
#define MOD_SIMPLEDEFORM_ORIGIN_LOCAL (1<<0)
#define MOD_UVPROJECT_MAX 10
@@ -1093,4 +1113,17 @@ enum {
MOD_SKIN_SMOOTH_SHADING = 1
};
+/* Smooth modifier flags */
+#define MOD_LAPLACIANSMOOTH_X (1<<1)
+#define MOD_LAPLACIANSMOOTH_Y (1<<2)
+#define MOD_LAPLACIANSMOOTH_Z (1<<3)
+#define MOD_LAPLACIANSMOOTH_VOLUME_PRESERVATION (1<<4)
+
+typedef struct LaplacianSmoothModifierData {
+ ModifierData modifier;
+ float lambda, lambda_border, pad1;
+ char defgrp_name[64]; /* MAX_VGROUP_NAME */
+ short flag, repeat;
+} LaplacianSmoothModifierData;
+
#endif
diff --git a/source/blender/makesdna/DNA_movieclip_types.h b/source/blender/makesdna/DNA_movieclip_types.h
index cda51779528..499f1c50155 100644
--- a/source/blender/makesdna/DNA_movieclip_types.h
+++ b/source/blender/makesdna/DNA_movieclip_types.h
@@ -118,38 +118,50 @@ typedef struct MovieClipScopes {
} MovieClipScopes;
/* MovieClipProxy->build_size_flag */
-#define MCLIP_PROXY_SIZE_25 (1 << 0)
-#define MCLIP_PROXY_SIZE_50 (1 << 1)
-#define MCLIP_PROXY_SIZE_75 (1 << 2)
-#define MCLIP_PROXY_SIZE_100 (1 << 3)
-#define MCLIP_PROXY_UNDISTORTED_SIZE_25 (1 << 4)
-#define MCLIP_PROXY_UNDISTORTED_SIZE_50 (1 << 5)
-#define MCLIP_PROXY_UNDISTORTED_SIZE_75 (1 << 6)
-#define MCLIP_PROXY_UNDISTORTED_SIZE_100 (1 << 7)
+enum {
+ MCLIP_PROXY_SIZE_25 = (1 << 0),
+ MCLIP_PROXY_SIZE_50 = (1 << 1),
+ MCLIP_PROXY_SIZE_75 = (1 << 2),
+ MCLIP_PROXY_SIZE_100 = (1 << 3),
+ MCLIP_PROXY_UNDISTORTED_SIZE_25 = (1 << 4),
+ MCLIP_PROXY_UNDISTORTED_SIZE_50 = (1 << 5),
+ MCLIP_PROXY_UNDISTORTED_SIZE_75 = (1 << 6),
+ MCLIP_PROXY_UNDISTORTED_SIZE_100 = (1 << 7)
+};
/* MovieClip->source */
-#define MCLIP_SRC_SEQUENCE 1
-#define MCLIP_SRC_MOVIE 2
+enum {
+ MCLIP_SRC_SEQUENCE = 1,
+ MCLIP_SRC_MOVIE = 2
+};
/* MovieClip->selection types */
-#define MCLIP_SEL_NONE 0
-#define MCLIP_SEL_TRACK 1
+enum {
+ MCLIP_SEL_NONE = 0,
+ MCLIP_SEL_TRACK = 1
+};
/* MovieClip->flag */
-#define MCLIP_USE_PROXY (1 << 0)
-#define MCLIP_USE_PROXY_CUSTOM_DIR (1 << 1)
-/*#define MCLIP_CUSTOM_START_FRAME (1<<2)*/ /* UNUSED */
+enum {
+ MCLIP_USE_PROXY = (1 << 0),
+ MCLIP_USE_PROXY_CUSTOM_DIR = (1 << 1),
+ /* MCLIP_CUSTOM_START_FRAME = (1<<2), */ /* UNUSED */
-#define MCLIP_TIMECODE_FLAGS (MCLIP_USE_PROXY | MCLIP_USE_PROXY_CUSTOM_DIR)
+ MCLIP_TIMECODE_FLAGS = (MCLIP_USE_PROXY | MCLIP_USE_PROXY_CUSTOM_DIR)
+};
/* MovieClip->render_size */
-#define MCLIP_PROXY_RENDER_SIZE_FULL 0
-#define MCLIP_PROXY_RENDER_SIZE_25 1
-#define MCLIP_PROXY_RENDER_SIZE_50 2
-#define MCLIP_PROXY_RENDER_SIZE_75 3
-#define MCLIP_PROXY_RENDER_SIZE_100 4
+enum {
+ MCLIP_PROXY_RENDER_SIZE_FULL = 0,
+ MCLIP_PROXY_RENDER_SIZE_25 = 1,
+ MCLIP_PROXY_RENDER_SIZE_50 = 2,
+ MCLIP_PROXY_RENDER_SIZE_75 = 3,
+ MCLIP_PROXY_RENDER_SIZE_100 = 4
+};
/* MovieClip->render_flag */
-#define MCLIP_PROXY_RENDER_UNDISTORT 1
+enum {
+ MCLIP_PROXY_RENDER_UNDISTORT = 1
+};
#endif
diff --git a/source/blender/makesdna/DNA_nla_types.h b/source/blender/makesdna/DNA_nla_types.h
index 43b52ed65eb..5837f891ae0 100644
--- a/source/blender/makesdna/DNA_nla_types.h
+++ b/source/blender/makesdna/DNA_nla_types.h
@@ -50,7 +50,7 @@ typedef struct bActionModifier {
/* path deform modifier */
short no_rot_axis;
- struct Object *ob;
+ struct Object *ob;
} bActionModifier;
/* NLA-Modifier Types */
diff --git a/source/blender/makesdna/DNA_node_types.h b/source/blender/makesdna/DNA_node_types.h
index 3f1f4933585..c73ba87754f 100644
--- a/source/blender/makesdna/DNA_node_types.h
+++ b/source/blender/makesdna/DNA_node_types.h
@@ -167,6 +167,7 @@ typedef struct bNode {
struct ID *id; /* optional link to libdata */
void *storage; /* custom data, must be struct, for storage in file */
struct bNode *original; /* the original node in the tree (for localized tree) */
+ ListBase internal_links; /* list of cached internal links (input to output), for muted nodes and operators */
float locx, locy; /* root offset for drawing (parent space) */
float width, height; /* node custom width and height */
@@ -240,6 +241,7 @@ typedef struct bNodeLink {
/* link->flag */
#define NODE_LINKFLAG_HILITE 1 /* link has been successfully validated */
#define NODE_LINK_VALID 2
+#define NODE_LINK_TEST 4 /* free test flag, undefined */
/* tree->edit_quality/tree->render_quality */
#define NTREE_QUALITY_HIGH 0
@@ -702,6 +704,26 @@ typedef struct NodeTrackPosData {
char track_name[64];
} NodeTrackPosData;
+typedef struct NodeShaderScript {
+ int mode;
+ int flag;
+
+ char filepath[1024]; /* 1024 = FILE_MAX */
+
+ char bytecode_hash[64];
+ char *bytecode;
+
+ IDProperty *prop;
+} NodeShaderScript;
+
+/* script node mode */
+#define NODE_SCRIPT_INTERNAL 0
+#define NODE_SCRIPT_EXTERNAL 1
+
+/* script node flag */
+#define NODE_SCRIPT_AUTO_UPDATE 1
+
+
/* frame node flags */
#define NODE_FRAME_SHRINK 1 /* keep the bounding box minimal */
#define NODE_FRAME_RESIZEABLE 2 /* test flag, if frame can be resized by user */
diff --git a/source/blender/makesdna/DNA_object_force.h b/source/blender/makesdna/DNA_object_force.h
index 1dd2aa6c59b..5cc56d861a3 100644
--- a/source/blender/makesdna/DNA_object_force.h
+++ b/source/blender/makesdna/DNA_object_force.h
@@ -54,6 +54,7 @@ typedef enum PFieldType {
PFIELD_BOID = 10, /* Defines predator / goal for boids */
PFIELD_TURBULENCE = 11, /* Force defined by BLI_gTurbulence */
PFIELD_DRAG = 12, /* Linear & quadratic drag */
+ PFIELD_SMOKEFLOW = 13, /* Force based on smoke simulation air flow */
NUM_PFIELD_TYPES
} PFieldType;
@@ -110,14 +111,17 @@ typedef struct PartDeflect {
struct RNG *rng; /* random noise generator for e.g. wind */
float f_noise; /* noise of force */
int seed; /* noise random seed */
+
+ struct Object *f_source; /* force source object */
} PartDeflect;
typedef struct EffectorWeights {
struct Group *group; /* only use effectors from this group of objects */
- float weight[13]; /* effector type specific weights */
+ float weight[14]; /* effector type specific weights */
float global_gravity;
short flag, rt[3];
+ int pad;
} EffectorWeights;
/* EffectorWeights->flag */
@@ -276,7 +280,7 @@ typedef struct SoftBody {
float nodemass; /* softbody mass of *vertex* */
char namedVG_Mass[64]; /* MAX_VGROUP_NAME */
/* along with it introduce mass painting
- * starting to fix old bug .. nastyness that VG are indexes
+ * starting to fix old bug .. nastiness that VG are indexes
* rather find them by name tag to find it -> jow20090613 */
float grav; /* softbody amount of gravitaion to apply */
float mediafrict; /* friction to env */
@@ -291,7 +295,7 @@ typedef struct SoftBody {
float defgoal; /* default goal for vertices without vgroup */
short vertgroup; /* index starting at 1 */
char namedVG_Softgoal[64]; /* MAX_VGROUP_NAME */
- /* starting to fix old bug .. nastyness that VG are indexes
+ /* starting to fix old bug .. nastiness that VG are indexes
* rather find them by name tag to find it -> jow20090613 */
short fuzzyness; /* */
@@ -301,7 +305,7 @@ typedef struct SoftBody {
float infrict; /* softbody inner springs friction */
char namedVG_Spring_K[64]; /* MAX_VGROUP_NAME */
/* along with it introduce Spring_K painting
- * starting to fix old bug .. nastyness that VG are indexes
+ * starting to fix old bug .. nastiness that VG are indexes
* rather find them by name tag to find it -> jow20090613 */
/* baking */
@@ -365,6 +369,7 @@ typedef struct SoftBody {
#define PFIELD_DO_LOCATION (1<<14)
#define PFIELD_DO_ROTATION (1<<15)
#define PFIELD_GUIDE_PATH_WEIGHT (1<<16) /* apply curve weights */
+#define PFIELD_SMOKE_DENSITY (1<<17) /* multiply smoke force by density */
/* pd->falloff */
#define PFIELD_FALL_SPHERE 0
@@ -395,7 +400,7 @@ typedef struct SoftBody {
//#define PTCACHE_BAKE_EDIT 16
//#define PTCACHE_BAKE_EDIT_ACTIVE 32
#define PTCACHE_DISK_CACHE 64
-#define PTCACHE_QUICK_CACHE 128
+//#define PTCACHE_QUICK_CACHE 128 /* removed since 2.64 - [#30974], could be added back in a more useful way */
#define PTCACHE_FRAMES_SKIPPED 256
#define PTCACHE_EXTERNAL 512
#define PTCACHE_READ_INFO 1024
diff --git a/source/blender/makesdna/DNA_object_types.h b/source/blender/makesdna/DNA_object_types.h
index af44db3896a..29f6499986c 100644
--- a/source/blender/makesdna/DNA_object_types.h
+++ b/source/blender/makesdna/DNA_object_types.h
@@ -117,7 +117,7 @@ typedef struct Object {
struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */
/* struct Path *path; */
struct BoundBox *bb;
- struct bAction *action DNA_DEPRECATED; // XXX depreceated... old animation system
+ struct bAction *action DNA_DEPRECATED; // XXX deprecated... old animation system
struct bAction *poselib;
struct bPose *pose; /* pose data, armature objects only */
void *data; /* pointer to objects data - an 'ID' or NULL */
@@ -127,8 +127,8 @@ typedef struct Object {
bAnimVizSettings avs; /* settings for visualization of object-transform animation */
bMotionPath *mpath; /* motion path cache for this object */
- ListBase constraintChannels DNA_DEPRECATED; // XXX depreceated... old animation system
- ListBase effect DNA_DEPRECATED; // XXX depreceated... keep for readfile
+ ListBase constraintChannels DNA_DEPRECATED; // XXX deprecated... old animation system
+ ListBase effect DNA_DEPRECATED; // XXX deprecated... keep for readfile
ListBase disp; /* list of DispList, used by lattice, metaballs curve & surfaces */
ListBase defbase; /* list of bDeformGroup (vertex groups) names and flag only */
ListBase modifiers; /* list of ModifierData structures */
@@ -175,7 +175,7 @@ typedef struct Object {
short transflag, protectflag; /* transformation settings and transform locks */
short trackflag, upflag;
short nlaflag; /* used for DopeSheet filtering settings (expanded/collapsed) */
- short ipoflag; // xxx depreceated... old animation system
+ short ipoflag; // xxx deprecated... old animation system
short scaflag; /* ui state for game logic */
char scavisflag; /* more display settings for game logic */
char pad5;
@@ -209,7 +209,9 @@ typedef struct Object {
float step_height;
float jump_speed;
float fall_speed;
- char pad1[4];
+
+ /** Collision mask settings */
+ unsigned short col_group, col_mask;
short rotmode; /* rotation mode - uses defines set out in DNA_action_types.h for PoseChannel rotations... */
@@ -244,8 +246,8 @@ typedef struct Object {
float anisotropicFriction[3];
ListBase constraints; /* object constraints */
- ListBase nlastrips DNA_DEPRECATED; // XXX depreceated... old animation system
- ListBase hooks DNA_DEPRECATED; // XXX depreceated... old animation system
+ ListBase nlastrips DNA_DEPRECATED; // XXX deprecated... old animation system
+ ListBase hooks DNA_DEPRECATED; // XXX deprecated... old animation system
ListBase particlesystem; /* particle systems */
struct PartDeflect *pd; /* particle deflector/attractor/collision data */
@@ -378,6 +380,7 @@ typedef struct DupliObject {
#define OB_DUPLIPARTS 2048
#define OB_RENDER_DUPLI 4096
#define OB_NO_CONSTRAINTS 8192 /* runtime constraints disable */
+#define OB_NO_PSYS_UPDATE 16384 /* hack to work around particle issue */
/* (short) ipoflag */
/* XXX: many old flags for features removed due to incompatibility
@@ -478,6 +481,9 @@ typedef struct DupliObject {
/* controller state */
#define OB_MAX_STATES 30
+/* collision masks */
+#define OB_MAX_COL_MASKS 8
+
/* ob->gameflag */
#define OB_DYNAMIC 1
#define OB_CHILD 2
diff --git a/source/blender/makesdna/DNA_packedFile_types.h b/source/blender/makesdna/DNA_packedFile_types.h
index f01e89d18c9..ef0a0f642d6 100644
--- a/source/blender/makesdna/DNA_packedFile_types.h
+++ b/source/blender/makesdna/DNA_packedFile_types.h
@@ -35,9 +35,9 @@
#define __DNA_PACKEDFILE_TYPES_H__
typedef struct PackedFile {
- int size;
- int seek;
- void * data;
+ int size;
+ int seek;
+ void *data;
} PackedFile;
enum PF_FileStatus
@@ -45,7 +45,7 @@ enum PF_FileStatus
PF_EQUAL = 0,
PF_DIFFERS = 1,
PF_NOFILE = 2,
-
+
PF_WRITE_ORIGINAL = 3,
PF_WRITE_LOCAL = 4,
PF_USE_LOCAL = 5,
@@ -53,7 +53,7 @@ enum PF_FileStatus
PF_KEEP = 7,
PF_REMOVE = 8,
PF_NOOP = 9,
-
+
PF_ASK = 10
};
diff --git a/source/blender/makesdna/DNA_scene_types.h b/source/blender/makesdna/DNA_scene_types.h
index e3a8863714a..1479d5268ed 100644
--- a/source/blender/makesdna/DNA_scene_types.h
+++ b/source/blender/makesdna/DNA_scene_types.h
@@ -318,10 +318,11 @@ typedef struct ImageFormatData {
/* return values from BKE_imtype_valid_depths, note this is depts per channel */
#define R_IMF_CHAN_DEPTH_1 (1<<0) /* 1bits (unused) */
#define R_IMF_CHAN_DEPTH_8 (1<<1) /* 8bits (default) */
-#define R_IMF_CHAN_DEPTH_12 (1<<2) /* 12bits (uncommon, jp2 supports) */
-#define R_IMF_CHAN_DEPTH_16 (1<<3) /* 16bits (tiff, halff float exr) */
-#define R_IMF_CHAN_DEPTH_24 (1<<4) /* 24bits (unused) */
-#define R_IMF_CHAN_DEPTH_32 (1<<5) /* 32bits (full float exr) */
+#define R_IMF_CHAN_DEPTH_10 (1<<2) /* 10bits (uncommon, Cineon/DPX support) */
+#define R_IMF_CHAN_DEPTH_12 (1<<3) /* 12bits (uncommon, jp2/DPX support) */
+#define R_IMF_CHAN_DEPTH_16 (1<<4) /* 16bits (tiff, halff float exr) */
+#define R_IMF_CHAN_DEPTH_24 (1<<5) /* 24bits (unused) */
+#define R_IMF_CHAN_DEPTH_32 (1<<6) /* 32bits (full float exr) */
/* ImageFormatData.planes */
#define R_IMF_PLANES_RGB 24
@@ -395,11 +396,16 @@ typedef struct RenderData {
/**
* The number of part to use in the x direction
*/
- short xparts;
+ short xparts DNA_DEPRECATED;
/**
* The number of part to use in the y direction
*/
- short yparts;
+ short yparts DNA_DEPRECATED;
+
+ /**
+ * render tile dimensions
+ */
+ short tilex, tiley;
short planes DNA_DEPRECATED, imtype DNA_DEPRECATED, subimtype DNA_DEPRECATED, quality DNA_DEPRECATED; /*deprecated!*/
@@ -447,6 +453,8 @@ typedef struct RenderData {
short frs_sec, edgeint;
+ int pad;
+
/* safety, border and display rect */
rctf safety, border;
@@ -475,7 +483,7 @@ typedef struct RenderData {
int color_mgt_flag;
/** post-production settings. deprecated, but here for upwards compat (initialized to 1) */
- float postgamma, posthue, postsat;
+ float postgamma, posthue, postsat;
/* Dither noise intensity */
float dither_intensity;
@@ -829,14 +837,15 @@ typedef struct VPaint {
void *paintcursor; /* wm handle */
} VPaint;
-/* VPaint flag */
-#define VP_COLINDEX 1
-#define VP_AREA 2 /* vertex paint only */
-
-#define VP_NORMALS 8
-#define VP_SPRAY 16
-// #define VP_MIRROR_X 32 // deprecated in 2.5x use (me->editflag & ME_EDIT_MIRROR_X)
-#define VP_ONLYVGROUP 128 /* weight paint only */
+/* VPaint.flag */
+enum {
+ // VP_COLINDEX = (1 << 0), /* only paint onto active material*/ /* deprecated since before 2.49 */
+ VP_AREA = (1 << 1),
+ VP_NORMALS = (1 << 3),
+ VP_SPRAY = (1 << 4),
+ // VP_MIRROR_X = (1 << 5), /* deprecated in 2.5x use (me->editflag & ME_EDIT_MIRROR_X) */
+ VP_ONLYVGROUP = (1 << 7) /* weight paint only */
+};
/* *************************************************************** */
/* Transform Orientations */
@@ -1045,7 +1054,7 @@ typedef struct UnitSettings {
/* Display/Editing unit options for each scene */
float scale_length; /* maybe have other unit conversions? */
char system; /* imperial, metric etc */
- char system_rotation; /* not implemented as a propper unit system yet */
+ char system_rotation; /* not implemented as a proper unit system yet */
short flag;
} UnitSettings;
@@ -1085,7 +1094,7 @@ typedef struct Scene {
short use_nodes;
- struct bNodeTree *nodetree;
+ struct bNodeTree *nodetree;
struct Editing *ed; /* sequence editor data is allocated here */
@@ -1186,7 +1195,7 @@ typedef struct Scene {
/* seq_flag */
#define R_SEQ_GL_PREV 1
-#define R_SEQ_GL_REND 2
+// #define R_SEQ_GL_REND 2 // UNUSED, opengl render has its own operator now.
/* displaymode */
@@ -1300,6 +1309,7 @@ typedef struct Scene {
/* sequencer seq_prev_type seq_rend_type */
+
/* **************** SCENE ********************* */
/* for general use */
@@ -1352,8 +1362,8 @@ typedef struct Scene {
#define SFRA (scene->r.sfra)
#define EFRA (scene->r.efra)
#define PRVRANGEON (scene->r.flag & SCER_PRV_RANGE)
-#define PSFRA ((PRVRANGEON)? (scene->r.psfra): (scene->r.sfra))
-#define PEFRA ((PRVRANGEON)? (scene->r.pefra): (scene->r.efra))
+#define PSFRA ((PRVRANGEON) ? (scene->r.psfra) : (scene->r.sfra))
+#define PEFRA ((PRVRANGEON) ? (scene->r.pefra) : (scene->r.efra))
#define FRA2TIME(a) ((((double) scene->r.frs_sec_base) * (double)(a)) / (double)scene->r.frs_sec)
#define TIME2FRA(a) ((((double) scene->r.frs_sec) * (double)(a)) / (double)scene->r.frs_sec_base)
#define FPS (((double) scene->r.frs_sec) / (double)scene->r.frs_sec_base)
@@ -1451,6 +1461,7 @@ typedef enum SculptFlags {
SCULPT_SYMMETRY_FEATHER = (1<<6),
SCULPT_USE_OPENMP = (1<<7),
SCULPT_ONLY_DEFORM = (1<<8),
+ SCULPT_SHOW_DIFFUSE = (1<<9),
} SculptFlags;
/* ImagePaintSettings.flag */
diff --git a/source/blender/makesdna/DNA_sdna_types.h b/source/blender/makesdna/DNA_sdna_types.h
index 8b2e7645823..28204ebeb88 100644
--- a/source/blender/makesdna/DNA_sdna_types.h
+++ b/source/blender/makesdna/DNA_sdna_types.h
@@ -48,7 +48,7 @@ typedef struct SDNA {
short *typelens; /* type lengths */
int nr_structs; /* number of struct types */
- short **structs; /* sp = structs[a] is the address of a struct definintion
+ short **structs; /* sp = structs[a] is the address of a struct definition
* sp[0] is struct type number, sp[1] amount of members
*
* (sp[2], sp[3]), (sp[4], sp[5]), .. are the member
diff --git a/source/blender/makesdna/DNA_smoke_types.h b/source/blender/makesdna/DNA_smoke_types.h
index cceb7333478..76ba3fcf7f8 100644
--- a/source/blender/makesdna/DNA_smoke_types.h
+++ b/source/blender/makesdna/DNA_smoke_types.h
@@ -39,6 +39,7 @@
#define MOD_SMOKE_HIGH_SMOOTH (1<<5) /* smoothens high res emission*/
#define MOD_SMOKE_FILE_LOAD (1<<6) /* flag for file load */
+#define MOD_SMOKE_ADAPTIVE_DOMAIN (1<<7)
/* noise */
#define MOD_SMOKE_NOISEWAVE (1<<0)
@@ -61,6 +62,12 @@
#define SM_COLL_RIGID 1
#define SM_COLL_ANIMATED 2
+/* smoke data fileds (active_fields) */
+#define SM_ACTIVE_HEAT (1<<0)
+#define SM_ACTIVE_FIRE (1<<1)
+#define SM_ACTIVE_COLORS (1<<2)
+#define SM_ACTIVE_COLOR_SET (1<<3)
+
typedef struct SmokeDomainSettings {
struct SmokeModifierData *smd; /* for fast RNA access */
struct FLUID_3D *fluid;
@@ -71,17 +78,37 @@ typedef struct SmokeDomainSettings {
struct GPUTexture *tex;
struct GPUTexture *tex_wt;
struct GPUTexture *tex_shadow;
+ struct GPUTexture *tex_flame;
float *shadow;
- float p0[3]; /* start point of BB */
- float p1[3]; /* end point of BB */
- float dx; /* edge length of one cell */
- float omega; /* smoke color - from 0 to 1 */
- float temp; /* fluid temperature */
- float tempAmb; /* ambient temperature */
+
+ /* simulation data */
+ float p0[3]; /* start point of BB in local space (includes sub-cell shift for adaptive domain)*/
+ float p1[3]; /* end point of BB in local space */
+ float dp0[3]; /* difference from object center to grid start point */
+ float cell_size[3]; /* size of simulation cell in local space */
+ float global_size[3]; /* global size of domain axises */
+ float prev_loc[3];
+ int shift[3]; /* current domain shift in simulation cells */
+ float shift_f[3]; /* exact domain shift */
+ float obj_shift_f[3]; /* how much object has shifted since previous smoke frame (used to "lock" domain while drawing) */
+ float imat[4][4]; /* domain object imat */
+ float obmat[4][4]; /* domain obmat */
+
+ int base_res[3]; /* initial "non-adapted" resolution */
+ int res_min[3]; /* cell min */
+ int res_max[3]; /* cell max */
+ int res[3]; /* data resolution (res_max-res_min) */
+ int total_cells;
+ float dx; /* 1.0f / res */
+ float scale; /* largest domain size */
+
+ /* user settings */
+ int adapt_margin;
+ int adapt_res;
+ float adapt_threshold;
+
float alpha;
float beta;
- float scale; /* largest domain size */
- int res[3]; /* domain resolution */
int amplify; /* wavelet amplification */
int maxres; /* longest axis on the BB gets this resolution assigned */
int flags; /* show up-res or low res, etc */
@@ -92,7 +119,6 @@ typedef struct SmokeDomainSettings {
float strength;
int res_wt[3];
float dx_wt;
- int v3dnum;
int cache_comp;
int cache_high_comp;
@@ -103,31 +129,67 @@ typedef struct SmokeDomainSettings {
int border_collisions; /* How domain border collisions are handled */
float time_scale;
float vorticity;
- int pad2;
+ int active_fields;
+ float active_color[3]; /* monitor color situation of simulation */
+ int pad;
+
+ /* flame parameters */
+ float burning_rate, flame_smoke, flame_vorticity;
+ float flame_ignition, flame_max_temp;
+ float flame_smoke_color[3];
} SmokeDomainSettings;
/* inflow / outflow */
/* type */
-#define MOD_SMOKE_FLOW_TYPE_OUTFLOW (1<<1)
+#define MOD_SMOKE_FLOW_TYPE_SMOKE 0
+#define MOD_SMOKE_FLOW_TYPE_FIRE 1
+#define MOD_SMOKE_FLOW_TYPE_OUTFLOW 2
+#define MOD_SMOKE_FLOW_TYPE_SMOKEFIRE 3
+
+/* flow source */
+#define MOD_SMOKE_FLOW_SOURCE_PARTICLES 0
+#define MOD_SMOKE_FLOW_SOURCE_MESH 1
+
+/* flow texture type */
+#define MOD_SMOKE_FLOW_TEXTURE_MAP_AUTO 0
+#define MOD_SMOKE_FLOW_TEXTURE_MAP_UV 1
/* flags */
#define MOD_SMOKE_FLOW_ABSOLUTE (1<<1) /*old style emission*/
#define MOD_SMOKE_FLOW_INITVELOCITY (1<<2) /* passes particles speed to the smoke */
+#define MOD_SMOKE_FLOW_TEXTUREEMIT (1<<3) /* use texture to control emission speed */
typedef struct SmokeFlowSettings {
struct SmokeModifierData *smd; /* for fast RNA access */
+ struct DerivedMesh *dm;
struct ParticleSystem *psys;
+ struct Tex *noise_texture;
+
+ /* initial velocity */
+ float *verts_old; /* previous vertex positions in domain space */
+ int numverts;
+ float vel_multi; // Multiplier for inherited velocity
+ float vel_normal;
+ float vel_random;
+ /* emission */
float density;
+ float color[3];
+ float fuel_amount;
float temp; /* delta temperature (temp - ambient temp) */
- float velocity[2]; /* UNUSED, velocity taken from particles */
- float vel_multi; // Multiplier for particle velocity
- float vgrp_heat_scale[2]; /* min and max scaling for vgroup_heat */
- short vgroup_flow; /* where inflow/outflow happens - red=1=action */
+ float volume_density; /* density emitted within mesh volume */
+ float surface_distance; /* maximum emission distance from mesh surface */
+ /* texture control */
+ float texture_size;
+ float texture_offset;
+ int pad;
+ char uvlayer_name[64]; /* MAX_CUSTOMDATA_LAYER_NAME */
short vgroup_density;
- short vgroup_heat;
- short type; /* inflow =0 or outflow = 1 */
+
+ short type; /* smoke, flames, both, outflow */
+ short source;
+ short texture_type;
int flags; /* absolute emission etc*/
} SmokeFlowSettings;
@@ -139,20 +201,11 @@ typedef struct SmokeFlowSettings {
/* collision objects (filled with smoke) */
typedef struct SmokeCollSettings {
struct SmokeModifierData *smd; /* for fast RNA access */
- struct BVHTree *bvhtree; /* bounding volume hierarchy for this cloth object */
- float *points;
- float *points_old;
- float *vel; // UNUSED
- int *tridivs;
- float mat[4][4];
- float mat_old[4][4];
- int numpoints;
- int numverts; // check if mesh changed
- int numtris;
- float dx; /* global domain cell length taken from (scale / resolution) */
+ struct DerivedMesh *dm;
+ float *verts_old;
+ int numverts;
short type; // static = 0, rigid = 1, dynamic = 2
short pad;
- int pad2;
} SmokeCollSettings;
#endif
diff --git a/source/blender/makesdna/DNA_space_types.h b/source/blender/makesdna/DNA_space_types.h
index 6cc4541f19e..be6464778e5 100644
--- a/source/blender/makesdna/DNA_space_types.h
+++ b/source/blender/makesdna/DNA_space_types.h
@@ -264,8 +264,8 @@ typedef enum eSpaceOutliner_Mode {
SO_SAME_TYPE = 5,
SO_GROUPS = 6,
SO_LIBRARIES = 7,
- SO_VERSE_SESSION = 8,
- SO_VERSE_MS = 9,
+ /* SO_VERSE_SESSION = 8, */ /* deprecated! */
+ /* SO_VERSE_MS = 9, */ /* deprecated!*/
SO_SEQUENCE = 10,
SO_DATABLOCKS = 11,
SO_USERDEF = 12,
@@ -376,7 +376,7 @@ typedef struct SpaceNla {
/* nla->flag */
typedef enum eSpaceNla_Flag {
- /* flags (1<<0), (1<<1), and (1<<3) are depreceated flags from old verisons */
+ /* flags (1<<0), (1<<1), and (1<<3) are deprecated flags from old verisons */
/* draw timing in seconds instead of frames */
SNLA_DRAWTIME = (1 << 2),
@@ -618,7 +618,7 @@ enum FileSortTypeE {
#define FILE_MAXFILE 256
#define FILE_MAX 1024
-#define FILE_MAX_LIBEXTRA (FILE_MAX + 32)
+#define FILE_MAX_LIBEXTRA (FILE_MAX + MAX_ID_NAME)
/* filesel types */
#define FILE_UNIX 8
@@ -792,10 +792,10 @@ typedef struct SpaceText {
float blockscale DNA_DEPRECATED;
short blockhandler[8] DNA_DEPRECATED;
- struct Text *text;
+ struct Text *text;
int top, viewlines;
- short flags, menunr;
+ short flags, menunr;
short lheight; /* user preference */
char cwidth, linenrs_tot; /* runtime computed, character width and the number of chars to use when showing line numbers */
diff --git a/source/blender/makesdna/DNA_texture_types.h b/source/blender/makesdna/DNA_texture_types.h
index 9fdd9216549..dd63e6aad59 100644
--- a/source/blender/makesdna/DNA_texture_types.h
+++ b/source/blender/makesdna/DNA_texture_types.h
@@ -161,7 +161,7 @@ typedef struct PointDensity {
float speed_scale, falloff_speed_scale, pdpad2;
struct ColorBand *coba; /* for time -> color */
- struct CurveMapping *falloff_curve; /* falloff density curve */
+ struct CurveMapping *falloff_curve; /* falloff density curve */
} PointDensity;
typedef struct VoxelData {
@@ -171,9 +171,12 @@ typedef struct VoxelData {
short flag;
short extend;
short smoked_type;
+ short data_type;
+ short pad;
+ int _pad;
struct Object *object; /* for rendering smoke sims */
- float int_multiplier;
+ float int_multiplier;
int still_frame;
char source_path[1024]; /* 1024 = FILE_MAX */
@@ -470,6 +473,7 @@ typedef struct ColorMapping {
#define MTEX_BUMP_TEXTURESPACE 2048
/* #define MTEX_BUMP_FLIPPED 4096 */ /* UNUSED */
#define MTEX_BICUBIC_BUMP 8192
+#define MTEX_MAPTO_BOUNDS 16384
/* blendtype */
#define MTEX_BLEND 0
@@ -577,6 +581,11 @@ typedef struct ColorMapping {
#define TEX_VD_SMOKEDENSITY 0
#define TEX_VD_SMOKEHEAT 1
#define TEX_VD_SMOKEVEL 2
+#define TEX_VD_SMOKEFLAME 3
+
+/* data_type */
+#define TEX_VD_INTENSITY 0
+#define TEX_VD_RGBA_PREMUL 1
/******************** Ocean *****************************/
/* output */
diff --git a/source/blender/makesdna/DNA_tracking_types.h b/source/blender/makesdna/DNA_tracking_types.h
index 1ab64ed1cc1..9c80d30bca4 100644
--- a/source/blender/makesdna/DNA_tracking_types.h
+++ b/source/blender/makesdna/DNA_tracking_types.h
@@ -162,7 +162,13 @@ typedef struct MovieTrackingSettings {
short speed; /* speed of tracking */
/* ** reconstruction settings ** */
- int keyframe1, keyframe2; /* two keyframes for reconstrution initialization */
+ int keyframe1 DNA_DEPRECATED,
+ keyframe2 DNA_DEPRECATED; /* two keyframes for reconstrution initialization
+ * were moved to per-tracking object settings
+ */
+
+ float reconstruction_success_threshold;
+ int reconstruction_flag;
/* which camera intrinsics to refine. uses on the REFINE_* flags */
short refine_camera_intrinsics, pad2;
@@ -220,6 +226,9 @@ typedef struct MovieTrackingObject {
ListBase tracks; /* list of tracks use to tracking this object */
MovieTrackingReconstruction reconstruction; /* reconstruction data for this object */
+
+ /* reconstruction options */
+ int keyframe1, keyframe2; /* two keyframes for reconstrution initialization */
} MovieTrackingObject;
typedef struct MovieTrackingStats {
@@ -275,92 +284,129 @@ enum {
};
/* MovieTrackingMarker->flag */
-#define MARKER_DISABLED (1 << 0)
-#define MARKER_TRACKED (1 << 1)
-#define MARKER_GRAPH_SEL_X (1 << 2)
-#define MARKER_GRAPH_SEL_Y (1 << 3)
-#define MARKER_GRAPH_SEL (MARKER_GRAPH_SEL_X | MARKER_GRAPH_SEL_Y)
+enum {
+ MARKER_DISABLED = (1 << 0),
+ MARKER_TRACKED = (1 << 1),
+ MARKER_GRAPH_SEL_X = (1 << 2),
+ MARKER_GRAPH_SEL_Y = (1 << 3),
+ MARKER_GRAPH_SEL = (MARKER_GRAPH_SEL_X | MARKER_GRAPH_SEL_Y)
+};
/* MovieTrackingTrack->flag */
-#define TRACK_HAS_BUNDLE (1 << 1)
-#define TRACK_DISABLE_RED (1 << 2)
-#define TRACK_DISABLE_GREEN (1 << 3)
-#define TRACK_DISABLE_BLUE (1 << 4)
-#define TRACK_HIDDEN (1 << 5)
-#define TRACK_LOCKED (1 << 6)
-#define TRACK_CUSTOMCOLOR (1 << 7)
-#define TRACK_USE_2D_STAB (1 << 8)
-#define TRACK_PREVIEW_GRAYSCALE (1 << 9)
-#define TRACK_DOPE_SEL (1 << 10)
-#define TRACK_PREVIEW_ALPHA (1 << 11)
+enum {
+ TRACK_HAS_BUNDLE = (1 << 1),
+ TRACK_DISABLE_RED = (1 << 2),
+ TRACK_DISABLE_GREEN = (1 << 3),
+ TRACK_DISABLE_BLUE = (1 << 4),
+ TRACK_HIDDEN = (1 << 5),
+ TRACK_LOCKED = (1 << 6),
+ TRACK_CUSTOMCOLOR = (1 << 7),
+ TRACK_USE_2D_STAB = (1 << 8),
+ TRACK_PREVIEW_GRAYSCALE = (1 << 9),
+ TRACK_DOPE_SEL = (1 << 10),
+ TRACK_PREVIEW_ALPHA = (1 << 11)
+};
/* MovieTrackingTrack->motion_model */
-#define TRACK_MOTION_MODEL_TRANSLATION 0
-#define TRACK_MOTION_MODEL_TRANSLATION_ROTATION 1
-#define TRACK_MOTION_MODEL_TRANSLATION_SCALE 2
-#define TRACK_MOTION_MODEL_TRANSLATION_ROTATION_SCALE 3
-#define TRACK_MOTION_MODEL_AFFINE 4
-#define TRACK_MOTION_MODEL_HOMOGRAPHY 5
+enum {
+ TRACK_MOTION_MODEL_TRANSLATION = 0,
+ TRACK_MOTION_MODEL_TRANSLATION_ROTATION = 1,
+ TRACK_MOTION_MODEL_TRANSLATION_SCALE = 2,
+ TRACK_MOTION_MODEL_TRANSLATION_ROTATION_SCALE = 3,
+ TRACK_MOTION_MODEL_AFFINE = 4,
+ TRACK_MOTION_MODEL_HOMOGRAPHY = 5
+};
/* MovieTrackingTrack->algorithm_flag */
-#define TRACK_ALGORITHM_FLAG_USE_BRUTE (1 << 0)
-#define TRACK_ALGORITHM_FLAG_USE_NORMALIZATION (1 << 2)
-#define TRACK_ALGORITHM_FLAG_USE_MASK (1 << 3)
+enum {
+ TRACK_ALGORITHM_FLAG_USE_BRUTE = (1 << 0),
+ TRACK_ALGORITHM_FLAG_USE_NORMALIZATION = (1 << 2),
+ TRACK_ALGORITHM_FLAG_USE_MASK = (1 << 3)
+};
/* MovieTrackingTrack->adjframes */
-#define TRACK_MATCH_KEYFRAME 0
-#define TRACK_MATCH_PREVFRAME 1
+enum {
+ TRACK_MATCH_KEYFRAME = 0,
+ TRACK_MATCH_PREVFRAME = 1
+};
/* MovieTrackingSettings->flag */
-#define TRACKING_SETTINGS_SHOW_DEFAULT_EXPANDED (1 << 0)
+enum {
+ TRACKING_SETTINGS_SHOW_DEFAULT_EXPANDED = (1 << 0)
+};
/* MovieTrackingSettings->motion_flag */
-#define TRACKING_MOTION_TRIPOD (1 << 0)
+enum {
+ TRACKING_MOTION_TRIPOD = (1 << 0),
-#define TRACKING_MOTION_MODAL (TRACKING_MOTION_TRIPOD)
+ TRACKING_MOTION_MODAL = (TRACKING_MOTION_TRIPOD)
+};
/* MovieTrackingSettings->speed */
-#define TRACKING_SPEED_FASTEST 0
-#define TRACKING_SPEED_REALTIME 1
-#define TRACKING_SPEED_HALF 2
-#define TRACKING_SPEED_QUARTER 4
-#define TRACKING_SPEED_DOUBLE 5
+enum {
+ TRACKING_SPEED_FASTEST = 0,
+ TRACKING_SPEED_REALTIME = 1,
+ TRACKING_SPEED_HALF = 2,
+ TRACKING_SPEED_QUARTER = 4,
+ TRACKING_SPEED_DOUBLE = 5
+};
+
+/* MovieTrackingObject->reconstruction_flag */
+enum {
+ TRACKING_USE_FALLBACK_RECONSTRUCTION = (1 << 0)
+};
/* MovieTrackingSettings->refine_camera_intrinsics */
-#define REFINE_FOCAL_LENGTH (1 << 0)
-#define REFINE_PRINCIPAL_POINT (1 << 1)
-#define REFINE_RADIAL_DISTORTION_K1 (1 << 2)
-#define REFINE_RADIAL_DISTORTION_K2 (1 << 4)
+enum {
+ REFINE_FOCAL_LENGTH = (1 << 0),
+ REFINE_PRINCIPAL_POINT = (1 << 1),
+ REFINE_RADIAL_DISTORTION_K1 = (1 << 2),
+ REFINE_RADIAL_DISTORTION_K2 = (1 << 4)
+};
/* MovieTrackingStrabilization->flag */
-#define TRACKING_2D_STABILIZATION (1 << 0)
-#define TRACKING_AUTOSCALE (1 << 1)
-#define TRACKING_STABILIZE_ROTATION (1 << 2)
+enum {
+ TRACKING_2D_STABILIZATION = (1 << 0),
+ TRACKING_AUTOSCALE = (1 << 1),
+ TRACKING_STABILIZE_ROTATION = (1 << 2)
+};
/* MovieTrackingStrabilization->filter */
-#define TRACKING_FILTER_NEAREAST 0
-#define TRACKING_FILTER_BILINEAR 1
-#define TRACKING_FILTER_BICUBIC 2
+enum {
+ TRACKING_FILTER_NEAREAST = 0,
+ TRACKING_FILTER_BILINEAR = 1,
+ TRACKING_FILTER_BICUBIC = 2
+};
/* MovieTrackingReconstruction->flag */
-#define TRACKING_RECONSTRUCTED (1 << 0)
+enum {
+ TRACKING_RECONSTRUCTED = (1 << 0)
+};
/* MovieTrackingObject->flag */
-#define TRACKING_OBJECT_CAMERA (1 << 0)
+enum {
+ TRACKING_OBJECT_CAMERA = (1 << 0)
+};
-#define TRACKING_CLEAN_SELECT 0
-#define TRACKING_CLEAN_DELETE_TRACK 1
-#define TRACKING_CLEAN_DELETE_SEGMENT 2
+enum {
+ TRACKING_CLEAN_SELECT = 0,
+ TRACKING_CLEAN_DELETE_TRACK = 1,
+ TRACKING_CLEAN_DELETE_SEGMENT = 2
+};
/* MovieTrackingDopesheet->sort_method */
-#define TRACKING_DOPE_SORT_NAME 0
-#define TRACKING_DOPE_SORT_LONGEST 1
-#define TRACKING_DOPE_SORT_TOTAL 2
-#define TRACKING_DOPE_SORT_AVERAGE_ERROR 3
+enum {
+ TRACKING_DOPE_SORT_NAME = 0,
+ TRACKING_DOPE_SORT_LONGEST = 1,
+ TRACKING_DOPE_SORT_TOTAL = 2,
+ TRACKING_DOPE_SORT_AVERAGE_ERROR = 3
+};
/* MovieTrackingDopesheet->flag */
-#define TRACKING_DOPE_SORT_INVERSE (1 << 0)
-#define TRACKING_DOPE_SELECTED_ONLY (1 << 1)
-#define TRACKING_DOPE_SHOW_HIDDEN (1 << 2)
+enum {
+ TRACKING_DOPE_SORT_INVERSE = (1 << 0),
+ TRACKING_DOPE_SELECTED_ONLY = (1 << 1),
+ TRACKING_DOPE_SHOW_HIDDEN = (1 << 2)
+};
#endif
diff --git a/source/blender/makesdna/DNA_userdef_types.h b/source/blender/makesdna/DNA_userdef_types.h
index 218027209a8..2256968da56 100644
--- a/source/blender/makesdna/DNA_userdef_types.h
+++ b/source/blender/makesdna/DNA_userdef_types.h
@@ -49,11 +49,14 @@ struct ColorBand;
#define MAX_STYLE_NAME 64
/* default uifont_id offered by Blender */
-#define UIFONT_DEFAULT 0
-/*#define UIFONT_BITMAP 1*/ /*UNUSED*/
-/* free slots */
-#define UIFONT_CUSTOM1 2
-#define UIFONT_CUSTOM2 3
+typedef enum eUIFont_ID {
+ UIFONT_DEFAULT = 0,
+/* UIFONT_BITMAP = 1 */ /* UNUSED */
+
+ /* free slots */
+ UIFONT_CUSTOM1 = 2,
+ UIFONT_CUSTOM2 = 3
+} eUIFont_ID;
/* default fonts to load/initalize */
/* first font is the default (index 0), others optional */
@@ -64,7 +67,6 @@ typedef struct uiFont {
short uifont_id; /* own id */
short r_to_l; /* fonts that read from left to right */
short pad;
-
} uiFont;
/* this state defines appearance of text */
@@ -79,13 +81,14 @@ typedef struct uiFontStyle {
short align; /* text align hint */
float shadowalpha; /* total alpha */
float shadowcolor; /* 1 value, typically white or black anyway */
-
} uiFontStyle;
/* uiFontStyle->align */
-#define UI_STYLE_TEXT_LEFT 0
-#define UI_STYLE_TEXT_CENTER 1
-#define UI_STYLE_TEXT_RIGHT 2
+typedef enum eFontStyle_Align {
+ UI_STYLE_TEXT_LEFT = 0,
+ UI_STYLE_TEXT_CENTER = 1,
+ UI_STYLE_TEXT_RIGHT = 2
+} eFontStyle_Align;
/* this is fed to the layout engine and widget code */
@@ -145,7 +148,6 @@ typedef struct uiPanelColors {
} uiPanelColors;
typedef struct ThemeUI {
-
/* Interface Elements (buttons, menus, icons) */
uiWidgetColors wcol_regular, wcol_tool, wcol_text;
uiWidgetColors wcol_radio, wcol_option, wcol_toggle;
@@ -182,7 +184,7 @@ typedef struct ThemeSpace {
/* button/tool regions */
char button[4];
char button_title[4];
- char button_text[4];
+ char button_text[4];
char button_text_hi[4];
/* listview regions */
@@ -193,8 +195,8 @@ typedef struct ThemeSpace {
/* float panel */
char panel[4];
- char panel_title[4];
- char panel_text[4];
+ char panel_title[4];
+ char panel_text[4];
char panel_text_hi[4];
char shade1[4];
@@ -209,8 +211,8 @@ typedef struct ThemeSpace {
char vertex[4], vertex_select[4];
char edge[4], edge_select[4];
char edge_seam[4], edge_sharp[4], edge_facesel[4], edge_crease[4];
- char face[4], face_select[4]; // solid faces
- char face_dot[4]; // selected color
+ char face[4], face_select[4]; /* solid faces */
+ char face_dot[4]; /* selected color */
char extra_edge_len[4], extra_face_angle[4], extra_face_area[4], pad3[4];
char normal[4];
char vertex_normal[4];
@@ -224,7 +226,7 @@ typedef struct ThemeSpace {
char handle_free[4], handle_auto[4], handle_vect[4], handle_align[4], handle_auto_clamped[4];
char handle_sel_free[4], handle_sel_auto[4], handle_sel_vect[4], handle_sel_align[4], handle_sel_auto_clamped[4];
- char ds_channel[4], ds_subchannel[4]; // dopesheet
+ char ds_channel[4], ds_subchannel[4]; /* dopesheet */
char console_output[4], console_input[4], console_info[4], console_error[4];
char console_cursor[4];
@@ -232,10 +234,10 @@ typedef struct ThemeSpace {
char vertex_size, outline_width, facedot_size;
char noodle_curving;
- char syntaxl[4], syntaxn[4], syntaxb[4]; // syntax for textwindow and nodes
+ char syntaxl[4], syntaxn[4], syntaxb[4]; /* syntax for textwindow and nodes */
char syntaxv[4], syntaxc[4];
- char movie[4], movieclip[4], mask[4], image[4], scene[4], audio[4]; // for sequence editor
+ char movie[4], movieclip[4], mask[4], image[4], scene[4], audio[4]; /* for sequence editor */
char effect[4], hpad0[4], transition[4], meta[4];
char editmesh_active[4];
@@ -287,8 +289,10 @@ typedef struct ThemeWireColor {
} ThemeWireColor;
/* flags for ThemeWireColor */
-#define TH_WIRECOLOR_CONSTCOLS (1<<0)
-#define TH_WIRECOLOR_TEXTCOLS (1<<1)
+typedef enum eWireColor_Flags {
+ TH_WIRECOLOR_CONSTCOLS = (1 << 0),
+ TH_WIRECOLOR_TEXTCOLS = (1 << 1),
+} eWireColor_Flags;
/* A theme */
typedef struct bTheme {
@@ -298,7 +302,7 @@ typedef struct bTheme {
ThemeUI tui;
/* Individual Spacetypes */
- ThemeSpace tbuts;
+ ThemeSpace tbuts;
ThemeSpace tv3d;
ThemeSpace tfile;
ThemeSpace tipo;
@@ -312,7 +316,7 @@ typedef struct bTheme {
ThemeSpace ttime;
ThemeSpace tnode;
ThemeSpace tlogic;
- ThemeSpace tuserpref;
+ ThemeSpace tuserpref;
ThemeSpace tconsole;
ThemeSpace tclip;
@@ -321,7 +325,6 @@ typedef struct bTheme {
/*ThemeWireColor tobj[20];*/
int active_theme_area, pad;
-
} bTheme;
/* for the moment only the name. may want to store options with this later */
@@ -345,8 +348,8 @@ typedef struct UserDef {
char pythondir[768];
char sounddir[768];
char i18ndir[768];
- char image_editor[1024]; /* 1024 = FILE_MAX */
- char anim_player[1024]; /* 1024 = FILE_MAX */
+ char image_editor[1024]; /* 1024 = FILE_MAX */
+ char anim_player[1024]; /* 1024 = FILE_MAX */
int anim_player_preset;
short v2d_min_gridsize; /* minimum spacing between gridlines in View2D grids */
@@ -393,7 +396,7 @@ typedef struct UserDef {
int memcachelimit;
int prefetchframes;
short frameserverport;
- short pad_rot_angle; /*control the rotation step of the view when PAD2, PAD4, PAD6&PAD8 is use*/
+ short pad_rot_angle; /* control the rotation step of the view when PAD2, PAD4, PAD6&PAD8 is use */
short obcenter_dia;
short rvisize; /* rotating view icon size */
short rvibright; /* rotating view icon brightness */
@@ -422,7 +425,7 @@ typedef struct UserDef {
short autokey_mode; /* autokeying mode */
short autokey_flag; /* flags for autokeying */
- short text_render, pad9; /*options for text rendering*/
+ short text_render, pad9; /* options for text rendering */
struct ColorBand coba_weight; /* from texture.h */
@@ -445,217 +448,259 @@ extern UserDef U; /* from blenkernel blender.c */
/* ***************** USERDEF ****************** */
/* userpref/section */
-#define USER_SECTION_INTERFACE 0
-#define USER_SECTION_EDIT 1
-#define USER_SECTION_FILE 2
-#define USER_SECTION_SYSTEM 3
-#define USER_SECTION_THEME 4
-#define USER_SECTION_INPUT 5
-#define USER_SECTION_ADDONS 6
+typedef enum eUserPref_Section {
+ USER_SECTION_INTERFACE = 0,
+ USER_SECTION_EDIT = 1,
+ USER_SECTION_FILE = 2,
+ USER_SECTION_SYSTEM = 3,
+ USER_SECTION_THEME = 4,
+ USER_SECTION_INPUT = 5,
+ USER_SECTION_ADDONS = 6,
+} eUserPref_Section;
/* flag */
-#define USER_AUTOSAVE (1 << 0)
-/*#define USER_AUTOGRABGRID (1 << 1) deprecated */
-/*#define USER_AUTOROTGRID (1 << 2) deprecated */
-/*#define USER_AUTOSIZEGRID (1 << 3) deprecated */
-#define USER_SCENEGLOBAL (1 << 4)
-#define USER_TRACKBALL (1 << 5)
-/*#define USER_DUPLILINK (1 << 6) deprecated */
-/*#define USER_FSCOLLUM (1 << 7) deprecated */
-#define USER_MAT_ON_OB (1 << 8)
-/*#define USER_NO_CAPSLOCK (1 << 9)*/ /* not used anywhere */
-/*#define USER_VIEWMOVE (1 << 10)*/ /* not used anywhere */
-#define USER_TOOLTIPS (1 << 11)
-#define USER_TWOBUTTONMOUSE (1 << 12)
-#define USER_NONUMPAD (1 << 13)
-#define USER_LMOUSESELECT (1 << 14)
-#define USER_FILECOMPRESS (1 << 15)
-#define USER_SAVE_PREVIEWS (1 << 16)
-#define USER_CUSTOM_RANGE (1 << 17)
-#define USER_ADD_EDITMODE (1 << 18)
-#define USER_ADD_VIEWALIGNED (1 << 19)
-#define USER_RELPATHS (1 << 20)
-#define USER_RELEASECONFIRM (1 << 21)
-#define USER_SCRIPT_AUTOEXEC_DISABLE (1 << 22)
-#define USER_FILENOUI (1 << 23)
-#define USER_NONEGFRAMES (1 << 24)
-#define USER_TXT_TABSTOSPACES_DISABLE (1 << 25)
-#define USER_TOOLTIPS_PYTHON (1 << 26)
-
+typedef enum eUserPref_Flag {
+ USER_AUTOSAVE = (1 << 0),
+/* USER_AUTOGRABGRID = (1 << 1), deprecated */
+/* USER_AUTOROTGRID = (1 << 2), deprecated */
+/* USER_AUTOSIZEGRID = (1 << 3), deprecated */
+ USER_SCENEGLOBAL = (1 << 4),
+ USER_TRACKBALL = (1 << 5),
+/* USER_DUPLILINK = (1 << 6), deprecated */
+/* USER_FSCOLLUM = (1 << 7), deprecated */
+ USER_MAT_ON_OB = (1 << 8),
+/* USER_NO_CAPSLOCK = (1 << 9), */ /* not used anywhere */
+/* USER_VIEWMOVE = (1 << 10), */ /* not used anywhere */
+ USER_TOOLTIPS = (1 << 11),
+ USER_TWOBUTTONMOUSE = (1 << 12),
+ USER_NONUMPAD = (1 << 13),
+ USER_LMOUSESELECT = (1 << 14),
+ USER_FILECOMPRESS = (1 << 15),
+ USER_SAVE_PREVIEWS = (1 << 16),
+ USER_CUSTOM_RANGE = (1 << 17),
+ USER_ADD_EDITMODE = (1 << 18),
+ USER_ADD_VIEWALIGNED = (1 << 19),
+ USER_RELPATHS = (1 << 20),
+ USER_RELEASECONFIRM = (1 << 21),
+ USER_SCRIPT_AUTOEXEC_DISABLE = (1 << 22),
+ USER_FILENOUI = (1 << 23),
+ USER_NONEGFRAMES = (1 << 24),
+ USER_TXT_TABSTOSPACES_DISABLE = (1 << 25),
+ USER_TOOLTIPS_PYTHON = (1 << 26),
+} eUserPref_Flag;
+
/* helper macro for checking frame clamping */
#define FRAMENUMBER_MIN_CLAMP(cfra) { \
if ((U.flag & USER_NONEGFRAMES) && (cfra < 0)) \
cfra = 0; \
} (void)0
-/* viewzom */
-#define USER_ZOOM_CONT 0
-#define USER_ZOOM_SCALE 1
-#define USER_ZOOM_DOLLY 2
+/* viewzoom */
+typedef enum eViewZoom_Style {
+ USER_ZOOM_CONT = 0,
+ USER_ZOOM_SCALE = 1,
+ USER_ZOOM_DOLLY = 2
+} eViewZoom_Style;
/* uiflag */
-// old flag for #define USER_KEYINSERTACT (1 << 0)
-// old flag for #define USER_KEYINSERTOBJ (1 << 1)
-#define USER_WHEELZOOMDIR (1 << 2)
-#define USER_FILTERFILEEXTS (1 << 3)
-#define USER_DRAWVIEWINFO (1 << 4)
-#define USER_PLAINMENUS (1 << 5) // old EVTTOCONSOLE print ghost events, here for tuhopuu compat. --phase
- // old flag for hide pulldown was here
-/*#define USER_FLIPFULLSCREEN (1 << 7)*/ /* deprecated */
-#define USER_ALLWINCODECS (1 << 8)
-#define USER_MENUOPENAUTO (1 << 9)
-#define USER_ZBUF_CURSOR (1 << 10)
-#define USER_AUTOPERSP (1 << 11)
-#define USER_LOCKAROUND (1 << 12)
-#define USER_GLOBALUNDO (1 << 13)
-#define USER_ORBIT_SELECTION (1 << 14)
-#define USER_ZBUF_ORBIT (1 << 15)
-#define USER_HIDE_DOT (1 << 16)
-#define USER_SHOW_ROTVIEWICON (1 << 17)
-#define USER_SHOW_VIEWPORTNAME (1 << 18)
-#define USER_CAM_LOCK_NO_PARENT (1 << 19)
-#define USER_ZOOM_TO_MOUSEPOS (1 << 20)
-#define USER_SHOW_FPS (1 << 21)
-#define USER_MMB_PASTE (1 << 22)
-#define USER_MENUFIXEDORDER (1 << 23)
-#define USER_CONTINUOUS_MOUSE (1 << 24)
-#define USER_ZOOM_INVERT (1 << 25)
-#define USER_ZOOM_HORIZ (1 << 26) /* for CONTINUE and DOLLY zoom */
-#define USER_SPLASH_DISABLE (1 << 27)
-#define USER_HIDE_RECENT (1 << 28)
-#define USER_SHOW_THUMBNAILS (1 << 29)
-#define USER_QUIT_PROMPT (1 << 30)
+typedef enum eUserpref_UI_Flag {
+ /* flags 0 and 1 were old flags (for autokeying) that aren't used anymore */
+ USER_WHEELZOOMDIR = (1 << 2),
+ USER_FILTERFILEEXTS = (1 << 3),
+ USER_DRAWVIEWINFO = (1 << 4),
+ USER_PLAINMENUS = (1 << 5),
+ /* flags 6 and 7 were old flags that are no-longer used */
+ USER_ALLWINCODECS = (1 << 8),
+ USER_MENUOPENAUTO = (1 << 9),
+ USER_ZBUF_CURSOR = (1 << 10),
+ USER_AUTOPERSP = (1 << 11),
+ USER_LOCKAROUND = (1 << 12),
+ USER_GLOBALUNDO = (1 << 13),
+ USER_ORBIT_SELECTION = (1 << 14),
+ USER_ZBUF_ORBIT = (1 << 15),
+ USER_HIDE_DOT = (1 << 16),
+ USER_SHOW_ROTVIEWICON = (1 << 17),
+ USER_SHOW_VIEWPORTNAME = (1 << 18),
+ USER_CAM_LOCK_NO_PARENT = (1 << 19),
+ USER_ZOOM_TO_MOUSEPOS = (1 << 20),
+ USER_SHOW_FPS = (1 << 21),
+ USER_MMB_PASTE = (1 << 22),
+ USER_MENUFIXEDORDER = (1 << 23),
+ USER_CONTINUOUS_MOUSE = (1 << 24),
+ USER_ZOOM_INVERT = (1 << 25),
+ USER_ZOOM_HORIZ = (1 << 26), /* for CONTINUE and DOLLY zoom */
+ USER_SPLASH_DISABLE = (1 << 27),
+ USER_HIDE_RECENT = (1 << 28),
+ USER_SHOW_THUMBNAILS = (1 << 29),
+ USER_QUIT_PROMPT = (1 << 30),
+ USER_HIDE_SYSTEM_BOOKMARKS = (1 << 31)
+} eUserpref_UI_Flag;
/* Auto-Keying mode */
+typedef enum eAutokey_Mode {
/* AUTOKEY_ON is a bitflag */
-#define AUTOKEY_ON 1
+ AUTOKEY_ON = 1,
+
/* AUTOKEY_ON + 2**n... (i.e. AUTOKEY_MODE_NORMAL = AUTOKEY_ON + 2) to preserve setting, even when autokey turned off */
-#define AUTOKEY_MODE_NORMAL 3
-#define AUTOKEY_MODE_EDITKEYS 5
+ AUTOKEY_MODE_NORMAL = 3,
+ AUTOKEY_MODE_EDITKEYS = 5
+} eAutokey_Mode;
/* Auto-Keying flag
* U.autokey_flag (not strictly used when autokeying only - is also used when keyframing these days)
* note: AUTOKEY_FLAG_* is used with a macro, search for lines like IS_AUTOKEY_FLAG(INSERTAVAIL)
*/
-#define AUTOKEY_FLAG_INSERTAVAIL (1<<0)
-#define AUTOKEY_FLAG_INSERTNEEDED (1<<1)
-#define AUTOKEY_FLAG_AUTOMATKEY (1<<2)
-#define AUTOKEY_FLAG_XYZ2RGB (1<<3)
-
-/* toolsettings->autokey_flag */
-#define AUTOKEY_FLAG_ONLYKEYINGSET (1<<6)
-#define ANIMRECORD_FLAG_WITHNLA (1<<10)
+typedef enum eAutokey_Flag {
+ AUTOKEY_FLAG_INSERTAVAIL = (1 << 0),
+ AUTOKEY_FLAG_INSERTNEEDED = (1 << 1),
+ AUTOKEY_FLAG_AUTOMATKEY = (1 << 2),
+ AUTOKEY_FLAG_XYZ2RGB = (1 << 3),
+
+ /* toolsettings->autokey_flag */
+ AUTOKEY_FLAG_ONLYKEYINGSET = (1 << 6),
+ AUTOKEY_FLAG_NOWARNING = (1 << 7),
+ ANIMRECORD_FLAG_WITHNLA = (1 << 10),
+} eAutokey_Flag;
/* transopts */
-#define USER_TR_TOOLTIPS (1 << 0)
-#define USER_TR_IFACE (1 << 1)
-/*#define USER_TR_MENUS (1 << 2) deprecated*/
-/*#define USER_TR_FILESELECT (1 << 3) deprecated*/
-/*#define USER_TR_TEXTEDIT (1 << 4) deprecated*/
-#define USER_DOTRANSLATE (1 << 5)
-#define USER_USETEXTUREFONT (1 << 6)
-/*#define CONVERT_TO_UTF8 (1 << 7) deprecated*/
+typedef enum eUserpref_Translation_Flags {
+ USER_TR_TOOLTIPS = (1 << 0),
+ USER_TR_IFACE = (1 << 1),
+/* USER_TR_MENUS = (1 << 2) deprecated */
+/* USER_TR_FILESELECT = (1 << 3) deprecated */
+/* USER_TR_TEXTEDIT = (1 << 4) deprecated */
+ USER_DOTRANSLATE = (1 << 5),
+ USER_USETEXTUREFONT = (1 << 6),
+/* CONVERT_TO_UTF8 = (1 << 7) deprecated */
+} eUserpref_Translation_Flags;
/* dupflag */
-#define USER_DUP_MESH (1 << 0)
-#define USER_DUP_CURVE (1 << 1)
-#define USER_DUP_SURF (1 << 2)
-#define USER_DUP_FONT (1 << 3)
-#define USER_DUP_MBALL (1 << 4)
-#define USER_DUP_LAMP (1 << 5)
-#define USER_DUP_IPO (1 << 6)
-#define USER_DUP_MAT (1 << 7)
-#define USER_DUP_TEX (1 << 8)
-#define USER_DUP_ARM (1 << 9)
-#define USER_DUP_ACT (1 << 10)
-#define USER_DUP_PSYS (1 << 11)
+typedef enum eDupli_ID_Flags {
+ USER_DUP_MESH = (1 << 0),
+ USER_DUP_CURVE = (1 << 1),
+ USER_DUP_SURF = (1 << 2),
+ USER_DUP_FONT = (1 << 3),
+ USER_DUP_MBALL = (1 << 4),
+ USER_DUP_LAMP = (1 << 5),
+ USER_DUP_IPO = (1 << 6),
+ USER_DUP_MAT = (1 << 7),
+ USER_DUP_TEX = (1 << 8),
+ USER_DUP_ARM = (1 << 9),
+ USER_DUP_ACT = (1 << 10),
+ USER_DUP_PSYS = (1 << 11)
+} eDupli_ID_Flags;
/* gameflags */
-// #define USER_DEPRECATED_FLAG 1
-// #define USER_DISABLE_SOUND 2 deprecated, don't use without checking for
-// backwards compatibilty in do_versions!
-#define USER_DISABLE_MIPMAP 4
-#define USER_DISABLE_VBO 8
-#define USER_DISABLE_AA 16
+typedef enum eOpenGL_RenderingOptions {
+ /* USER_DEPRECATED_FLAG = (1 << 0), */
+ /* USER_DISABLE_SOUND = (1 << 1), */ /* deprecated, don't use without checking for */
+ /* backwards compatibilty in do_versions! */
+ USER_DISABLE_MIPMAP = (1 << 2),
+ USER_DISABLE_VBO = (1 << 3),
+ USER_DISABLE_AA = (1 << 4),
+} eOpenGL_RenderingOptions;
/* wm draw method */
-#define USER_DRAW_TRIPLE 0
-#define USER_DRAW_OVERLAP 1
-#define USER_DRAW_FULL 2
-#define USER_DRAW_AUTOMATIC 3
-#define USER_DRAW_OVERLAP_FLIP 4
-
-/* text draw options*/
-#define USER_TEXT_DISABLE_AA (1 << 0)
+typedef enum eWM_DrawMethod {
+ USER_DRAW_TRIPLE = 0,
+ USER_DRAW_OVERLAP = 1,
+ USER_DRAW_FULL = 2,
+ USER_DRAW_AUTOMATIC = 3,
+ USER_DRAW_OVERLAP_FLIP = 4,
+} eWM_DrawMethod;
+
+/* text draw options */
+typedef enum eText_Draw_Options {
+ USER_TEXT_DISABLE_AA = (1 << 0),
+} eText_Draw_Options;
/* tw_flag (transform widget) */
/* gp_settings (Grease Pencil Settings) */
-#define GP_PAINT_DOSMOOTH (1<<0)
-#define GP_PAINT_DOSIMPLIFY (1<<1)
+typedef enum eGP_UserdefSettings {
+ GP_PAINT_DOSMOOTH = (1 << 0),
+ GP_PAINT_DOSIMPLIFY = (1 << 1),
+} eGP_UserdefSettings;
/* color picker types */
-#define USER_CP_CIRCLE 0
-#define USER_CP_SQUARE_SV 1
-#define USER_CP_SQUARE_HS 2
-#define USER_CP_SQUARE_HV 3
+typedef enum eColorPicker_Types {
+ USER_CP_CIRCLE = 0,
+ USER_CP_SQUARE_SV = 1,
+ USER_CP_SQUARE_HS = 2,
+ USER_CP_SQUARE_HV = 3,
+} eColorPicker_Types;
/* timecode display styles */
+typedef enum eTimecodeStyles {
/* as little info as is necessary to show relevant info
* with '+' to denote the frames
* i.e. HH:MM:SS+FF, MM:SS+FF, SS+FF, or MM:SS
*/
-#define USER_TIMECODE_MINIMAL 0
+ USER_TIMECODE_MINIMAL = 0,
+
/* reduced SMPTE - (HH:)MM:SS:FF */
-#define USER_TIMECODE_SMPTE_MSF 1
+ USER_TIMECODE_SMPTE_MSF = 1,
+
/* full SMPTE - HH:MM:SS:FF */
-#define USER_TIMECODE_SMPTE_FULL 2
+ USER_TIMECODE_SMPTE_FULL = 2,
+
/* milliseconds for sub-frames - HH:MM:SS.sss */
-#define USER_TIMECODE_MILLISECONDS 3
+ USER_TIMECODE_MILLISECONDS = 3,
+
/* seconds only */
-#define USER_TIMECODE_SECONDS_ONLY 4
+ USER_TIMECODE_SECONDS_ONLY = 4,
+} eTimecodeStyles;
/* theme drawtypes */
-#define TH_MINIMAL 0
-#define TH_ROUNDSHADED 1
-#define TH_ROUNDED 2
-#define TH_OLDSKOOL 3
-#define TH_SHADED 4
+/* XXX: These are probably only for the old UI engine? */
+typedef enum eTheme_DrawTypes {
+ TH_MINIMAL = 0,
+ TH_ROUNDSHADED = 1,
+ TH_ROUNDED = 2,
+ TH_OLDSKOOL = 3,
+ TH_SHADED = 4
+} eTheme_DrawTypes;
/* ndof_flag (3D mouse options) */
-#define NDOF_SHOW_GUIDE (1 << 0)
-#define NDOF_FLY_HELICOPTER (1 << 1)
-#define NDOF_LOCK_HORIZON (1 << 2)
-/* the following might not need to be saved between sessions,
- * but they do need to live somewhere accessible... */
-#define NDOF_SHOULD_PAN (1 << 3)
-#define NDOF_SHOULD_ZOOM (1 << 4)
-#define NDOF_SHOULD_ROTATE (1 << 5)
-/* orbit navigation modes
- * only two options, so it's sort of a hybrid bool/enum
- * if ((U.ndof_flag & NDOF_ORBIT_MODE) == NDOF_OM_OBJECT)... */
-
-// #define NDOF_ORBIT_MODE (1 << 6)
-// #define NDOF_OM_TARGETCAMERA 0
-// #define NDOF_OM_OBJECT NDOF_ORBIT_MODE
-
-/* actually... users probably don't care about what the mode
- * is called, just that it feels right */
-/* zoom is up/down if this flag is set (otherwise forward/backward) */
-#define NDOF_ZOOM_UPDOWN (1 << 7)
-#define NDOF_ZOOM_INVERT (1 << 8)
-#define NDOF_ROTATE_INVERT_AXIS (1 << 9)
-#define NDOF_TILT_INVERT_AXIS (1 << 10)
-#define NDOF_ROLL_INVERT_AXIS (1 << 11)
-#define NDOF_PANX_INVERT_AXIS (1 << 12)
-#define NDOF_PANY_INVERT_AXIS (1 << 13)
-#define NDOF_PANZ_INVERT_AXIS (1 << 14)
-#define NDOF_TURNTABLE (1 << 15)
+typedef enum eNdof_Flag {
+ NDOF_SHOW_GUIDE = (1 << 0),
+ NDOF_FLY_HELICOPTER = (1 << 1),
+ NDOF_LOCK_HORIZON = (1 << 2),
+
+ /* the following might not need to be saved between sessions,
+ * but they do need to live somewhere accessible... */
+ NDOF_SHOULD_PAN = (1 << 3),
+ NDOF_SHOULD_ZOOM = (1 << 4),
+ NDOF_SHOULD_ROTATE = (1 << 5),
+
+ /* orbit navigation modes
+ * only two options, so it's sort of a hybrid bool/enum
+ * if ((U.ndof_flag & NDOF_ORBIT_MODE) == NDOF_OM_OBJECT)... */
+
+ // NDOF_ORBIT_MODE = (1 << 6),
+ // #define NDOF_OM_TARGETCAMERA 0
+ // #define NDOF_OM_OBJECT NDOF_ORBIT_MODE
+
+ /* actually... users probably don't care about what the mode
+ * is called, just that it feels right */
+ /* zoom is up/down if this flag is set (otherwise forward/backward) */
+ NDOF_ZOOM_UPDOWN = (1 << 7),
+ NDOF_ZOOM_INVERT = (1 << 8),
+ NDOF_ROTATE_INVERT_AXIS = (1 << 9),
+ NDOF_TILT_INVERT_AXIS = (1 << 10),
+ NDOF_ROLL_INVERT_AXIS = (1 << 11),
+ NDOF_PANX_INVERT_AXIS = (1 << 12),
+ NDOF_PANY_INVERT_AXIS = (1 << 13),
+ NDOF_PANZ_INVERT_AXIS = (1 << 14),
+ NDOF_TURNTABLE = (1 << 15),
+} eNdof_Flag;
/* compute_device_type */
-#define USER_COMPUTE_DEVICE_NONE 0
-#define USER_COMPUTE_DEVICE_OPENCL 1
-#define USER_COMPUTE_DEVICE_CUDA 2
+typedef enum eCompute_Device_Type {
+ USER_COMPUTE_DEVICE_NONE = 0,
+ USER_COMPUTE_DEVICE_OPENCL = 1,
+ USER_COMPUTE_DEVICE_CUDA = 2,
+} eCompute_Device_Type;
#ifdef __cplusplus
}
diff --git a/source/blender/makesdna/DNA_view2d_types.h b/source/blender/makesdna/DNA_view2d_types.h
index a3f4b362672..084496871bf 100644
--- a/source/blender/makesdna/DNA_view2d_types.h
+++ b/source/blender/makesdna/DNA_view2d_types.h
@@ -128,7 +128,7 @@ typedef struct View2D {
#define V2D_SCROLL_HORIZONTAL (V2D_SCROLL_TOP|V2D_SCROLL_BOTTOM|V2D_SCROLL_BOTTOM_O)
/* scale markings - vertical */
#define V2D_SCROLL_SCALE_VERTICAL (1<<5)
- /* scale markings - horizontal */
+ /* scale markings - horizontal */
#define V2D_SCROLL_SCALE_HORIZONTAL (1<<6)
/* induce hiding of scrollbars - set by region drawing in response to size of region */
#define V2D_SCROLL_VERTICAL_HIDE (1<<7)
diff --git a/source/blender/makesdna/DNA_view3d_types.h b/source/blender/makesdna/DNA_view3d_types.h
index 9da10381af0..c83b0bc366f 100644
--- a/source/blender/makesdna/DNA_view3d_types.h
+++ b/source/blender/makesdna/DNA_view3d_types.h
@@ -169,6 +169,7 @@ typedef struct View3D {
short view DNA_DEPRECATED;
struct Object *camera, *ob_centre;
+ rctf render_border;
struct ListBase bgpicbase;
struct BGpic *bgpic DNA_DEPRECATED; /* deprecated, use bgpicbase, only kept for do_versions(...) */
@@ -267,6 +268,7 @@ typedef struct View3D {
#define V3D_SHOW_CAMERAPATH 256
#define V3D_SHOW_BUNDLENAME 512
#define V3D_BACKFACE_CULLING 1024
+#define V3D_RENDER_BORDER 2048
/* View3D->around */
#define V3D_CENTER 0
diff --git a/source/blender/makesdna/DNA_windowmanager_types.h b/source/blender/makesdna/DNA_windowmanager_types.h
index 780ca0b5878..2294abc0735 100644
--- a/source/blender/makesdna/DNA_windowmanager_types.h
+++ b/source/blender/makesdna/DNA_windowmanager_types.h
@@ -334,7 +334,7 @@ typedef struct wmOperator {
#define OPERATOR_FLAGS_ALL ((1<<5)-1)
/* sanity checks for debug mode only */
-#define OPERATOR_RETVAL_CHECK(ret) BLI_assert(ret != 0 && (ret & OPERATOR_FLAGS_ALL) == ret)
+#define OPERATOR_RETVAL_CHECK(ret) (void)ret, BLI_assert(ret != 0 && (ret & OPERATOR_FLAGS_ALL) == ret)
/* wmOperator flag */
#define OP_GRAB_POINTER 1
diff --git a/source/blender/makesdna/DNA_world_types.h b/source/blender/makesdna/DNA_world_types.h
index b3c10406d4c..8a14564f8a4 100644
--- a/source/blender/makesdna/DNA_world_types.h
+++ b/source/blender/makesdna/DNA_world_types.h
@@ -61,14 +61,14 @@ typedef struct World {
float ambr, ambg, ambb;
float pad2;
- unsigned int fastcol;
+ unsigned int fastcol;
/**
* Exposure= mult factor. unused now, but maybe back later. Kept in to be upward compat.
* New is exp/range control. linfac & logfac are constants... don't belong in
* file, but allocating 8 bytes for temp mem isn't useful either.
*/
- float exposure, exp, range;
+ float exposure, exp, range;
float linfac, logfac;
/**
@@ -129,7 +129,7 @@ typedef struct World {
struct PreviewImage *preview;
/* nodes */
- struct bNodeTree *nodetree;
+ struct bNodeTree *nodetree;
} World;
diff --git a/source/blender/makesdna/intern/dna_genfile.c b/source/blender/makesdna/intern/dna_genfile.c
index f5cf7e3ea3b..10c3b0bbee4 100644
--- a/source/blender/makesdna/intern/dna_genfile.c
+++ b/source/blender/makesdna/intern/dna_genfile.c
@@ -62,7 +62,7 @@ typedef long long __int64;
* - if you want a struct not to be in DNA file: add two hash marks above it (#<enter>#<enter>)
*
* Structure DNA data is added to each blender file and to each executable, this to detect
- * in .blend files new veriables in structs, changed array sizes, etc. It's also used for
+ * in .blend files new variables in structs, changed array sizes, etc. It's also used for
* converting endian and pointer size (32-64 bits)
* As an extra, Python uses a call to detect run-time the contents of a blender struct.
*
@@ -506,7 +506,7 @@ static void init_structDNA(SDNA *sdna, int do_endian_swap)
}
}
-SDNA *DNA_sdna_from_data(void *data, int datalen, int do_endian_swap)
+SDNA *DNA_sdna_from_data(const void *data, const int datalen, int do_endian_swap)
{
SDNA *sdna = MEM_mallocN(sizeof(*sdna), "sdna");
diff --git a/source/blender/makesdna/intern/makesdna.c b/source/blender/makesdna/intern/makesdna.c
index fec3aa22e92..bef5e5cc161 100644
--- a/source/blender/makesdna/intern/makesdna.c
+++ b/source/blender/makesdna/intern/makesdna.c
@@ -87,14 +87,14 @@ static const char *includefiles[] = {
"DNA_mesh_types.h",
"DNA_meshdata_types.h",
"DNA_modifier_types.h",
- "DNA_lattice_types.h",
+ "DNA_lattice_types.h",
"DNA_object_types.h",
"DNA_object_force.h",
"DNA_object_fluidsim.h",
"DNA_world_types.h",
"DNA_scene_types.h",
"DNA_view3d_types.h",
- "DNA_view2d_types.h",
+ "DNA_view2d_types.h",
"DNA_space_types.h",
"DNA_userdef_types.h",
"DNA_screen_types.h",
@@ -485,11 +485,15 @@ static int preprocess_include(char *maindata, int len)
}
/* do not copy when: */
- if (comment) ;
- else if (cp[0] == ' ' && cp[1] == ' ') ;
- else if (cp[-1] == '*' && cp[0] == ' ') ; /* pointers with a space */
-
- /* skip special keywords */
+ if (comment) {
+ /* pass */
+ }
+ else if (cp[0] == ' ' && cp[1] == ' ') {
+ /* pass */
+ }
+ else if (cp[-1] == '*' && cp[0] == ' ') {
+ /* pointers with a space */
+ } /* skip special keywords */
else if (strncmp("DNA_DEPRECATED", cp, 14) == 0) {
/* single values are skipped already, so decrement 1 less */
a -= 13;
@@ -1028,7 +1032,9 @@ static int make_structDNA(char *baseDirectory, FILE *file)
if (debugSDNA > -1) printf("Writing file ... ");
- if (nr_names == 0 || nr_structs == 0) ;
+ if (nr_names == 0 || nr_structs == 0) {
+ /* pass */
+ }
else {
strcpy(str, "SDNA");
dna_write(file, str, 4);
@@ -1088,7 +1094,9 @@ static int make_structDNA(char *baseDirectory, FILE *file)
int a;
fp = fopen("padding.c", "w");
- if (fp == NULL) ;
+ if (fp == NULL) {
+ /* pass */
+ }
else {
/* add all include files defined in the global array */
@@ -1166,7 +1174,7 @@ int main(int argc, char **argv)
strcpy(baseDirectory, BASE_HEADER);
}
- fprintf(file, "unsigned char DNAstr[]= {\n");
+ fprintf(file, "const unsigned char DNAstr[] = {\n");
if (make_structDNA(baseDirectory, file)) {
/* error */
fclose(file);
@@ -1175,7 +1183,7 @@ int main(int argc, char **argv)
}
else {
fprintf(file, "};\n");
- fprintf(file, "int DNAlen = sizeof(DNAstr);\n");
+ fprintf(file, "const int DNAlen = sizeof(DNAstr);\n");
fclose(file);
}
@@ -1186,7 +1194,19 @@ int main(int argc, char **argv)
return(return_status);
}
+/* handy but fails on struct bounds which makesdna doesnt care about
+ * with quite the same strictness as GCC does */
+#if 0
/* include files for automatic dependencies */
+
+/* extra safety check that we are aligned,
+ * warnings here are easier to fix the makesdna's */
+#ifdef __GNUC__
+# pragma GCC diagnostic error "-Wpadded"
+#endif
+
+#endif /* if 0 */
+
#include "DNA_listBase.h"
#include "DNA_vec_types.h"
#include "DNA_ID.h"
diff --git a/source/blender/makesrna/RNA_access.h b/source/blender/makesrna/RNA_access.h
index 8e387dd4eba..5f667db4425 100644
--- a/source/blender/makesrna/RNA_access.h
+++ b/source/blender/makesrna/RNA_access.h
@@ -286,6 +286,7 @@ extern StructRNA RNA_KinematicConstraint;
extern StructRNA RNA_Lamp;
extern StructRNA RNA_LampSkySettings;
extern StructRNA RNA_LampTextureSlot;
+extern StructRNA RNA_LaplacianSmoothModifier;
extern StructRNA RNA_Lattice;
extern StructRNA RNA_LatticeModifier;
extern StructRNA RNA_LatticePoint;
@@ -456,6 +457,7 @@ extern StructRNA RNA_ShaderNodeMath;
extern StructRNA RNA_ShaderNodeMixRGB;
extern StructRNA RNA_ShaderNodeNormal;
extern StructRNA RNA_ShaderNodeOutput;
+extern StructRNA RNA_ShaderNodeScript;
extern StructRNA RNA_ShaderNodeRGB;
extern StructRNA RNA_ShaderNodeRGBCurve;
extern StructRNA RNA_ShaderNodeRGBToBW;
@@ -960,7 +962,9 @@ void RNA_collection_clear(PointerRNA *ptr, const char *name);
}
/* check if the idproperty exists, for operators */
+int RNA_property_is_set_ex(PointerRNA *ptr, PropertyRNA *prop, int use_ghost);
int RNA_property_is_set(PointerRNA *ptr, PropertyRNA *prop);
+int RNA_struct_property_is_set_ex(PointerRNA *ptr, const char *identifier, int use_ghost);
int RNA_struct_property_is_set(PointerRNA *ptr, const char *identifier);
int RNA_property_is_idprop(PropertyRNA *prop);
@@ -1029,6 +1033,13 @@ short RNA_type_to_ID_code(StructRNA *type);
StructRNA *ID_code_to_RNA_type(short idcode);
+#define RNA_POINTER_INVALIDATE(ptr) { \
+ /* this is checked for validity */ \
+ (ptr)->type = \
+ /* should not be needed but prevent bad pointer access, just in case */ \
+ (ptr)->id.data = NULL; \
+} (void)0
+
/* macro which inserts the function name */
#if defined __GNUC__ || defined __sun
# define RNA_warning(format, args ...) _RNA_warning("%s: " format "\n", __func__, ##args)
diff --git a/source/blender/makesrna/RNA_enum_types.h b/source/blender/makesrna/RNA_enum_types.h
index b651d4d5e5c..0f9a00de7b6 100644
--- a/source/blender/makesrna/RNA_enum_types.h
+++ b/source/blender/makesrna/RNA_enum_types.h
@@ -38,6 +38,7 @@ extern EnumPropertyItem DummyRNA_NULL_items[];
extern EnumPropertyItem DummyRNA_DEFAULT_items[];
extern EnumPropertyItem object_mode_items[];
+extern EnumPropertyItem object_empty_drawtype_items[];
extern EnumPropertyItem metaelem_type_items[];
extern EnumPropertyItem proportional_falloff_items[];
diff --git a/source/blender/makesrna/RNA_types.h b/source/blender/makesrna/RNA_types.h
index 511999dfa37..87504dc6eb7 100644
--- a/source/blender/makesrna/RNA_types.h
+++ b/source/blender/makesrna/RNA_types.h
@@ -113,6 +113,7 @@ typedef enum PropertySubType {
PROP_BYTESTRING = 4, /* a string which should be represented as bytes
* in python, still NULL terminated though. */
PROP_TRANSLATE = 5, /* a string which should be translated */
+ PROP_PASSWORD = 6, /* a string which should not be displayed in UI */
/* numbers */
PROP_UNSIGNED = 13,
@@ -312,6 +313,7 @@ typedef enum FunctionFlag {
FUNC_USE_CONTEXT = 4,
FUNC_USE_REPORTS = 8,
FUNC_USE_SELF_ID = 2048,
+ FUNC_ALLOW_WRITE = 4096,
/* registering */
FUNC_REGISTER = 16,
diff --git a/source/blender/makesrna/intern/makesrna.c b/source/blender/makesrna/intern/makesrna.c
index ef3c7f42e96..7c4ce3d18d7 100644
--- a/source/blender/makesrna/intern/makesrna.c
+++ b/source/blender/makesrna/intern/makesrna.c
@@ -61,7 +61,6 @@
/* Replace if different */
#define TMP_EXT ".tmp"
-
/* copied from BLI_file_older */
#include <sys/stat.h>
static int file_older(const char *file1, const char *file2)
@@ -76,6 +75,22 @@ static int file_older(const char *file1, const char *file2)
}
static const char *makesrna_path = NULL;
+/* forward declarations */
+static void rna_generate_static_parameter_prototypes(FILE *f, StructRNA *srna, FunctionDefRNA *dfunc,
+ const char *name_override, int close_prototype);
+
+/* helpers */
+#define WRITE_COMMA { \
+ if (!first) \
+ fprintf(f, ", "); \
+ first = 0; \
+ } (void)0
+
+#define WRITE_PARAM(param) { \
+ WRITE_COMMA; \
+ fprintf(f, param); \
+ }
+
static int replace_if_different(char *tmpfile, const char *dep_files[])
{
/* return 0; *//* use for testing had edited rna */
@@ -212,6 +227,8 @@ static const char *rna_safe_id(const char *id)
return "default_value";
else if (strcmp(id, "operator") == 0)
return "operator_value";
+ else if (strcmp(id, "new") == 0)
+ return "create";
return id;
}
@@ -322,13 +339,26 @@ static void rna_print_id_get(FILE *f, PropertyDefRNA *UNUSED(dp))
fprintf(f, " ID *id= ptr->id.data;\n");
}
+static void rna_construct_function_name(char *buffer, int size, const char *structname, const char *propname, const char *type)
+{
+ snprintf(buffer, size, "%s_%s_%s", structname, propname, type);
+}
+
+static void rna_construct_wrapper_function_name(char *buffer, int size, const char *structname, const char *propname, const char *type)
+{
+ if (type == NULL || type[0] == '\0')
+ snprintf(buffer, size, "%s_%s", structname, propname);
+ else
+ snprintf(buffer, size, "%s_%s_%s", structname, propname, type);
+}
+
static char *rna_alloc_function_name(const char *structname, const char *propname, const char *type)
{
AllocDefRNA *alloc;
char buffer[2048];
char *result;
- snprintf(buffer, sizeof(buffer), "%s_%s_%s", structname, propname, type);
+ rna_construct_function_name(buffer, sizeof(buffer), structname, propname, type);
result = MEM_callocN(sizeof(char) * strlen(buffer) + 1, "rna_alloc_function_name");
strcpy(result, buffer);
@@ -627,17 +657,17 @@ static char *rna_def_property_get_func(FILE *f, StructRNA *srna, PropertyRNA *pr
"get_length");
fprintf(f, " int i, arraylen[RNA_MAX_ARRAY_DIMENSION];\n");
fprintf(f, " int len= %s(ptr, arraylen);\n\n", lenfunc);
- fprintf(f, " for (i=0; i<len; i++) {\n");
+ fprintf(f, " for (i=0; i < len; i++) {\n");
MEM_freeN(lenfunc);
}
else {
fprintf(f, " int i;\n\n");
- fprintf(f, " for (i=0; i<%u; i++) {\n", prop->totarraylength);
+ fprintf(f, " for (i=0; i < %u; i++) {\n", prop->totarraylength);
}
if (dp->dnaarraylength == 1) {
if (prop->type == PROP_BOOLEAN && dp->booleanbit) {
- fprintf(f, " values[i] = %s((data->%s & (%d<<i)) != 0);\n",
+ fprintf(f, " values[i] = %s((data->%s & (%d << i)) != 0);\n",
(dp->booleannegative) ? "!" : "", dp->dnaname, dp->booleanbit);
}
else {
@@ -653,7 +683,7 @@ static char *rna_def_property_get_func(FILE *f, StructRNA *srna, PropertyRNA *pr
fprintf(f, ") != 0);\n");
}
else if (rna_color_quantize(prop, dp)) {
- fprintf(f, " values[i] = (%s)(data->%s[i]*(1.0f/255.0f));\n",
+ fprintf(f, " values[i] = (%s)(data->%s[i]*(1.0f / 255.0f));\n",
rna_type_type(prop), dp->dnaname);
}
else if (dp->dnatype) {
@@ -878,20 +908,20 @@ static char *rna_def_property_set_func(FILE *f, StructRNA *srna, PropertyRNA *pr
fprintf(f, " int i, arraylen[RNA_MAX_ARRAY_DIMENSION];\n");
fprintf(f, " int len= %s(ptr, arraylen);\n\n", lenfunc);
rna_clamp_value_range(f, prop);
- fprintf(f, " for (i=0; i<len; i++) {\n");
+ fprintf(f, " for (i=0; i < len; i++) {\n");
MEM_freeN(lenfunc);
}
else {
fprintf(f, " int i;\n\n");
rna_clamp_value_range(f, prop);
- fprintf(f, " for (i=0; i<%u; i++) {\n", prop->totarraylength);
+ fprintf(f, " for (i=0; i < %u; i++) {\n", prop->totarraylength);
}
if (dp->dnaarraylength == 1) {
if (prop->type == PROP_BOOLEAN && dp->booleanbit) {
fprintf(f, " if (%svalues[i]) data->%s |= (%d<<i);\n",
(dp->booleannegative) ? "!" : "", dp->dnaname, dp->booleanbit);
- fprintf(f, " else data->%s &= ~(%d<<i);\n", dp->dnaname, dp->booleanbit);
+ fprintf(f, " else data->%s &= ~(%d << i);\n", dp->dnaname, dp->booleanbit);
}
else {
fprintf(f, " (&data->%s)[i] = %s", dp->dnaname, (dp->booleannegative) ? "!" : "");
@@ -1015,9 +1045,9 @@ static char *rna_def_property_length_func(FILE *f, StructRNA *srna, PropertyRNA
else {
rna_print_data_get(f, dp);
if (dp->dnalengthname)
- fprintf(f, " return (data->%s == NULL)? 0: data->%s;\n", dp->dnaname, dp->dnalengthname);
+ fprintf(f, " return (data->%s == NULL) ? 0 : data->%s;\n", dp->dnaname, dp->dnalengthname);
else
- fprintf(f, " return (data->%s == NULL)? 0: %d;\n", dp->dnaname, dp->dnalengthfixed);
+ fprintf(f, " return (data->%s == NULL) ? 0 : %d;\n", dp->dnaname, dp->dnalengthfixed);
}
fprintf(f, "}\n\n");
}
@@ -1091,7 +1121,7 @@ static char *rna_def_property_lookup_int_func(FILE *f, StructRNA *srna, Property
const char *manualfunc, const char *nextfunc)
{
/* note on indices, this is for external functions and ignores skipped values.
- * so the the index can only be checked against the length when there is no 'skip' funcion. */
+ * so the the index can only be checked against the length when there is no 'skip' function. */
char *func;
if (prop->flag & PROP_IDPROPERTY && manualfunc == NULL)
@@ -1102,8 +1132,8 @@ static char *rna_def_property_lookup_int_func(FILE *f, StructRNA *srna, Property
return NULL;
/* only supported in case of standard next functions */
- if (strcmp(nextfunc, "rna_iterator_array_next") == 0) ;
- else if (strcmp(nextfunc, "rna_iterator_listbase_next") == 0) ;
+ if (strcmp(nextfunc, "rna_iterator_array_next") == 0) {}
+ else if (strcmp(nextfunc, "rna_iterator_listbase_next") == 0) {}
else return NULL;
}
@@ -1372,9 +1402,12 @@ static void rna_def_property_funcs(FILE *f, StructRNA *srna, PropertyDefRNA *dp)
CollectionPropertyRNA *cprop = (CollectionPropertyRNA *)prop;
const char *nextfunc = (const char *)cprop->next;
- if (dp->dnatype && strcmp(dp->dnatype, "ListBase") == 0) ;
- else if (dp->dnalengthname || dp->dnalengthfixed)
+ if (dp->dnatype && strcmp(dp->dnatype, "ListBase") == 0) {
+ /* pass */
+ }
+ else if (dp->dnalengthname || dp->dnalengthfixed) {
cprop->length = (void *)rna_def_property_length_func(f, srna, prop, dp, (const char *)cprop->length);
+ }
/* test if we can allow raw array access, if it is using our standard
* array get/next function, we can be sure it is an actual array */
@@ -1437,15 +1470,15 @@ static void rna_def_property_funcs_header(FILE *f, StructRNA *srna, PropertyDefR
{
if (!prop->arraydimension) {
fprintf(f, "int %sget(PointerRNA *ptr);\n", func);
- /*fprintf(f, "void %sset(PointerRNA *ptr, int value);\n", func); */
+ fprintf(f, "void %sset(PointerRNA *ptr, int value);\n", func);
}
else if (prop->arraydimension && prop->totarraylength) {
fprintf(f, "void %sget(PointerRNA *ptr, int values[%u]);\n", func, prop->totarraylength);
- /*fprintf(f, "void %sset(PointerRNA *ptr, const int values[%d]);\n", func, prop->arraylength); */
+ fprintf(f, "void %sset(PointerRNA *ptr, const int values[%d]);\n", func, prop->totarraylength);
}
else {
fprintf(f, "void %sget(PointerRNA *ptr, int values[]);\n", func);
- /*fprintf(f, "void %sset(PointerRNA *ptr, const int values[]);\n", func); */
+ fprintf(f, "void %sset(PointerRNA *ptr, const int values[]);\n", func);
}
break;
}
@@ -1453,15 +1486,15 @@ static void rna_def_property_funcs_header(FILE *f, StructRNA *srna, PropertyDefR
{
if (!prop->arraydimension) {
fprintf(f, "float %sget(PointerRNA *ptr);\n", func);
- /*fprintf(f, "void %sset(PointerRNA *ptr, float value);\n", func); */
+ fprintf(f, "void %sset(PointerRNA *ptr, float value);\n", func);
}
else if (prop->arraydimension && prop->totarraylength) {
fprintf(f, "void %sget(PointerRNA *ptr, float values[%u]);\n", func, prop->totarraylength);
- /*fprintf(f, "void %sset(PointerRNA *ptr, const float values[%d]);\n", func, prop->arraylength); */
+ fprintf(f, "void %sset(PointerRNA *ptr, const float values[%d]);\n", func, prop->totarraylength);
}
else {
fprintf(f, "void %sget(PointerRNA *ptr, float values[]);\n", func);
- /*fprintf(f, "void %sset(PointerRNA *ptr, const float values[]);\n", func); */
+ fprintf(f, "void %sset(PointerRNA *ptr, const float values[]);", func);
}
break;
}
@@ -1482,7 +1515,7 @@ static void rna_def_property_funcs_header(FILE *f, StructRNA *srna, PropertyDefR
}
fprintf(f, "int %sget(PointerRNA *ptr);\n", func);
- /*fprintf(f, "void %sset(PointerRNA *ptr, int value);\n", func); */
+ fprintf(f, "void %sset(PointerRNA *ptr, int value);\n", func);
break;
}
@@ -1496,7 +1529,7 @@ static void rna_def_property_funcs_header(FILE *f, StructRNA *srna, PropertyDefR
fprintf(f, "void %sget(PointerRNA *ptr, char *value);\n", func);
fprintf(f, "int %slength(PointerRNA *ptr);\n", func);
- /*fprintf(f, "void %sset(PointerRNA *ptr, const char *value);\n", func); */
+ fprintf(f, "void %sset(PointerRNA *ptr, const char *value);\n", func);
break;
}
@@ -1508,19 +1541,38 @@ static void rna_def_property_funcs_header(FILE *f, StructRNA *srna, PropertyDefR
}
case PROP_COLLECTION:
{
+ CollectionPropertyRNA *cprop = (CollectionPropertyRNA *)prop;
fprintf(f, "void %sbegin(CollectionPropertyIterator *iter, PointerRNA *ptr);\n", func);
fprintf(f, "void %snext(CollectionPropertyIterator *iter);\n", func);
fprintf(f, "void %send(CollectionPropertyIterator *iter);\n", func);
- /*fprintf(f, "int %slength(PointerRNA *ptr);\n", func); */
- /*fprintf(f, "void %slookup_int(PointerRNA *ptr, int key, StructRNA **type);\n", func); */
- /*fprintf(f, "void %slookup_string(PointerRNA *ptr, const char *key, StructRNA **type);\n", func); */
+ if (cprop->length)
+ fprintf(f, "int %slength(PointerRNA *ptr);\n", func);
+ if (cprop->lookupint)
+ fprintf(f, "int %slookup_int(PointerRNA *ptr, int key, PointerRNA *r_ptr);\n", func);
+ if (cprop->lookupstring)
+ fprintf(f, "int %slookup_string(PointerRNA *ptr, const char *key, PointerRNA *r_ptr);\n", func);
break;
}
}
+ if (prop->getlength) {
+ char funcname[2048];
+ rna_construct_wrapper_function_name(funcname, sizeof(funcname), srna->identifier, prop->identifier, "get_length");
+ fprintf(f, "int %s(PointerRNA *ptr, int *arraylen);\n", funcname);
+ }
+
fprintf(f, "\n");
}
+static void rna_def_function_funcs_header(FILE *f, StructRNA *srna, FunctionDefRNA *dfunc)
+{
+ FunctionRNA *func = dfunc->func;
+ char funcname[2048];
+
+ rna_construct_wrapper_function_name(funcname, sizeof(funcname), srna->identifier, func->identifier, NULL);
+ rna_generate_static_parameter_prototypes(f, srna, dfunc, funcname, 1);
+}
+
static void rna_def_property_funcs_header_cpp(FILE *f, StructRNA *srna, PropertyDefRNA *dp)
{
PropertyRNA *prop;
@@ -1540,26 +1592,50 @@ static void rna_def_property_funcs_header_cpp(FILE *f, StructRNA *srna, Property
switch (prop->type) {
case PROP_BOOLEAN:
{
- if (!prop->arraydimension)
- fprintf(f, "\tinline bool %s(void);", rna_safe_id(prop->identifier));
- else if (prop->totarraylength)
- fprintf(f, "\tinline Array<int, %u> %s(void);", prop->totarraylength, rna_safe_id(prop->identifier));
+ if (!prop->arraydimension) {
+ fprintf(f, "\tinline bool %s(void);\n", rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline void %s(int value);", rna_safe_id(prop->identifier));
+ }
+ else if (prop->totarraylength) {
+ fprintf(f, "\tinline Array<int, %u> %s(void);\n", prop->totarraylength, rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline void %s(int values[%u]);", rna_safe_id(prop->identifier), prop->totarraylength);
+ }
+ else if (prop->getlength) {
+ fprintf(f, "\tinline DynamicArray<int> %s(void);\n", rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline void %s(int values[]);", rna_safe_id(prop->identifier));
+ }
break;
}
case PROP_INT:
{
- if (!prop->arraydimension)
- fprintf(f, "\tinline int %s(void);", rna_safe_id(prop->identifier));
- else if (prop->totarraylength)
- fprintf(f, "\tinline Array<int, %u> %s(void);", prop->totarraylength, rna_safe_id(prop->identifier));
+ if (!prop->arraydimension) {
+ fprintf(f, "\tinline int %s(void);\n", rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline void %s(int value);", rna_safe_id(prop->identifier));
+ }
+ else if (prop->totarraylength) {
+ fprintf(f, "\tinline Array<int, %u> %s(void);\n", prop->totarraylength, rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline void %s(int values[%u]);", rna_safe_id(prop->identifier), prop->totarraylength);
+ }
+ else if (prop->getlength) {
+ fprintf(f, "\tinline DynamicArray<int> %s(void);\n", rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline void %s(int values[]);", rna_safe_id(prop->identifier));
+ }
break;
}
case PROP_FLOAT:
{
- if (!prop->arraydimension)
- fprintf(f, "\tinline float %s(void);", rna_safe_id(prop->identifier));
- else if (prop->totarraylength)
- fprintf(f, "\tinline Array<float, %u> %s(void);", prop->totarraylength, rna_safe_id(prop->identifier));
+ if (!prop->arraydimension) {
+ fprintf(f, "\tinline float %s(void);\n", rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline void %s(float value);", rna_safe_id(prop->identifier));
+ }
+ else if (prop->totarraylength) {
+ fprintf(f, "\tinline Array<float, %u> %s(void);\n", prop->totarraylength, rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline void %s(float values[%u]);", rna_safe_id(prop->identifier), prop->totarraylength);
+ }
+ else if (prop->getlength) {
+ fprintf(f, "\tinline DynamicArray<float> %s(void);\n", rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline void %s(float values[]);", rna_safe_id(prop->identifier));
+ }
break;
}
case PROP_ENUM:
@@ -1578,12 +1654,14 @@ static void rna_def_property_funcs_header_cpp(FILE *f, StructRNA *srna, Property
fprintf(f, "\t};\n");
}
- fprintf(f, "\tinline %s_enum %s(void);", rna_safe_id(prop->identifier), rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline %s_enum %s(void);\n", rna_safe_id(prop->identifier), rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline void %s(%s_enum value);", rna_safe_id(prop->identifier), rna_safe_id(prop->identifier));
break;
}
case PROP_STRING:
{
fprintf(f, "\tinline std::string %s(void);", rna_safe_id(prop->identifier));
+ fprintf(f, "\tinline void %s(const std::string& value);", rna_safe_id(prop->identifier));
break;
}
case PROP_POINTER:
@@ -1599,13 +1677,19 @@ static void rna_def_property_funcs_header_cpp(FILE *f, StructRNA *srna, Property
case PROP_COLLECTION:
{
CollectionPropertyRNA *cprop = (CollectionPropertyRNA *)dp->prop;
+ const char *collection_funcs = "DefaultCollectionFunctions";
+
+ if (!(dp->prop->flag & (PROP_IDPROPERTY | PROP_BUILTIN)) && cprop->property.srna)
+ collection_funcs = (char*)cprop->property.srna;
if (cprop->item_type)
- fprintf(f, "\tCOLLECTION_PROPERTY(%s, %s, %s)", (const char *)cprop->item_type, srna->identifier,
- rna_safe_id(prop->identifier));
+ fprintf(f, "\tCOLLECTION_PROPERTY(%s, %s, %s, %s, %s, %s, %s)", collection_funcs, (const char *)cprop->item_type, srna->identifier,
+ rna_safe_id(prop->identifier), (cprop->length ? "TRUE" : "FALSE"),
+ (cprop->lookupint ? "TRUE" : "FALSE"), (cprop->lookupstring ? "TRUE" : "FALSE"));
else
- fprintf(f, "\tCOLLECTION_PROPERTY(%s, %s, %s)", "UnknownType", srna->identifier,
- rna_safe_id(prop->identifier));
+ fprintf(f, "\tCOLLECTION_PROPERTY(%s, %s, %s, %s, %s, %s, %s)", collection_funcs, "UnknownType", srna->identifier,
+ rna_safe_id(prop->identifier), (cprop->length ? "TRUE" : "FALSE"),
+ (cprop->lookupint ? "TRUE" : "FALSE"), (cprop->lookupstring ? "TRUE" : "FALSE"));
break;
}
}
@@ -1613,6 +1697,96 @@ static void rna_def_property_funcs_header_cpp(FILE *f, StructRNA *srna, Property
fprintf(f, "\n");
}
+static const char *rna_parameter_type_cpp_name(PropertyRNA *prop)
+{
+ if (prop->type == PROP_POINTER) {
+ /* for cpp api we need to use RNA structures names for pointers */
+ PointerPropertyRNA *pprop = (PointerPropertyRNA *) prop;
+
+ return (const char *) pprop->type;
+ }
+ else {
+ return rna_parameter_type_name(prop);
+ }
+}
+
+static void rna_def_struct_function_prototype_cpp(FILE *f, StructRNA *srna, FunctionDefRNA *dfunc,
+ const char *namespace, int close_prototype)
+{
+ PropertyDefRNA *dp;
+ FunctionRNA *func = dfunc->func;
+
+ int first = 1;
+ const char *retval_type = "void";
+
+ if (func->c_ret) {
+ dp = rna_find_parameter_def(func->c_ret);
+ retval_type = rna_parameter_type_cpp_name(dp->prop);
+ }
+
+ if (namespace && namespace[0])
+ fprintf(f, "\tinline %s %s::%s(", retval_type, namespace, rna_safe_id(func->identifier));
+ else
+ fprintf(f, "\tinline %s %s(", retval_type, rna_safe_id(func->identifier));
+
+ if (func->flag & FUNC_USE_MAIN)
+ WRITE_PARAM("void *main");
+
+ if (func->flag & FUNC_USE_CONTEXT)
+ WRITE_PARAM("Context C");
+
+ for (dp = dfunc->cont.properties.first; dp; dp = dp->next) {
+ int type, flag, pout;
+ const char *ptrstr;
+
+ if (dp->prop == func->c_ret)
+ continue;
+
+ type = dp->prop->type;
+ flag = dp->prop->flag;
+ pout = (flag & PROP_OUTPUT);
+
+ if (type == PROP_POINTER)
+ ptrstr = "";
+ else if ((type == PROP_POINTER) && (flag & PROP_RNAPTR) && !(flag & PROP_THICK_WRAP))
+ ptrstr = "*";
+ else if (type == PROP_POINTER || dp->prop->arraydimension)
+ ptrstr = "*";
+ else if (type == PROP_STRING && (flag & PROP_THICK_WRAP))
+ ptrstr = "";
+ else
+ ptrstr = pout ? "*" : "";
+
+ WRITE_COMMA;
+
+ if (flag & PROP_DYNAMIC)
+ fprintf(f, "int %s%s_len, ", (flag & PROP_OUTPUT) ? "*" : "", dp->prop->identifier);
+
+ if (!(flag & PROP_DYNAMIC) && dp->prop->arraydimension)
+ fprintf(f, "%s %s[%u]", rna_parameter_type_cpp_name(dp->prop),
+ rna_safe_id(dp->prop->identifier), dp->prop->totarraylength);
+ else
+ fprintf(f, "%s %s%s", rna_parameter_type_cpp_name(dp->prop),
+ ptrstr, rna_safe_id(dp->prop->identifier));
+ }
+
+ fprintf(f, ")");
+ if (close_prototype)
+ fprintf(f, ";\n");
+}
+
+static void rna_def_struct_function_header_cpp(FILE *f, StructRNA *srna, FunctionDefRNA *dfunc)
+{
+ FunctionRNA *func = dfunc->func;
+
+ if (!dfunc->call)
+ return;
+
+ fprintf(f, "\n\t/* %s */\n", func->description);
+
+ rna_def_struct_function_prototype_cpp(f, srna, dfunc, NULL, 1);
+}
+
static void rna_def_property_funcs_impl_cpp(FILE *f, StructRNA *srna, PropertyDefRNA *dp)
{
PropertyRNA *prop;
@@ -1630,6 +1804,9 @@ static void rna_def_property_funcs_impl_cpp(FILE *f, StructRNA *srna, PropertyDe
else if (prop->totarraylength)
fprintf(f, "\tBOOLEAN_ARRAY_PROPERTY(%s, %u, %s)", srna->identifier, prop->totarraylength,
rna_safe_id(prop->identifier));
+ else if (prop->getlength)
+ fprintf(f, "\tBOOLEAN_DYNAMIC_ARRAY_PROPERTY(%s, %s)", srna->identifier,
+ rna_safe_id(prop->identifier));
break;
}
case PROP_INT:
@@ -1639,6 +1816,9 @@ static void rna_def_property_funcs_impl_cpp(FILE *f, StructRNA *srna, PropertyDe
else if (prop->totarraylength)
fprintf(f, "\tINT_ARRAY_PROPERTY(%s, %u, %s)", srna->identifier, prop->totarraylength,
rna_safe_id(prop->identifier));
+ else if (prop->getlength)
+ fprintf(f, "\tINT_DYNAMIC_ARRAY_PROPERTY(%s, %s)", srna->identifier,
+ rna_safe_id(prop->identifier));
break;
}
case PROP_FLOAT:
@@ -1648,6 +1828,9 @@ static void rna_def_property_funcs_impl_cpp(FILE *f, StructRNA *srna, PropertyDe
else if (prop->totarraylength)
fprintf(f, "\tFLOAT_ARRAY_PROPERTY(%s, %u, %s)", srna->identifier, prop->totarraylength,
rna_safe_id(prop->identifier));
+ else if (prop->getlength)
+ fprintf(f, "\tFLOAT_DYNAMIC_ARRAY_PROPERTY(%s, %s)", srna->identifier,
+ rna_safe_id(prop->identifier));
break;
}
case PROP_ENUM:
@@ -1680,10 +1863,13 @@ static void rna_def_property_funcs_impl_cpp(FILE *f, StructRNA *srna, PropertyDe
CollectionPropertyRNA *cprop = (CollectionPropertyRNA *)dp->prop;
if (cprop->type)
- fprintf(f, "\tCOLLECTION_PROPERTY(%s, %s, %s)", (const char *)cprop->type, srna->identifier,
- prop->identifier);
+ fprintf(f, "\tCOLLECTION_PROPERTY(%s, %s, %s, %s, %s, %s)", (const char *)cprop->type, srna->identifier,
+ prop->identifier, (cprop->length ? "TRUE" : "FALSE"),
+ (cprop->lookupint ? "TRUE" : "FALSE"), (cprop->lookupstring ? "TRUE" : "FALSE"));
else
- fprintf(f, "\tCOLLECTION_PROPERTY(%s, %s, %s)", "UnknownType", srna->identifier, prop->identifier);
+ fprintf(f, "\tCOLLECTION_PROPERTY(%s, %s, %s, %s, %s, %s)", "UnknownType", srna->identifier,
+ prop->identifier, (cprop->length ? "TRUE" : "FALSE"),
+ (cprop->lookupint ? "TRUE" : "FALSE"), (cprop->lookupstring ? "TRUE" : "FALSE"));
#endif
break;
}
@@ -1692,6 +1878,181 @@ static void rna_def_property_funcs_impl_cpp(FILE *f, StructRNA *srna, PropertyDe
fprintf(f, "\n");
}
+static void rna_def_struct_function_call_impl_cpp(FILE *f, StructRNA *srna, FunctionDefRNA *dfunc)
+{
+ PropertyDefRNA *dp;
+ StructDefRNA *dsrna;
+ FunctionRNA *func = dfunc->func;
+ char funcname[2048];
+
+ int first = 1;
+
+ rna_construct_wrapper_function_name(funcname, sizeof(funcname), srna->identifier, func->identifier, NULL);
+
+ fprintf(f, "%s(", funcname);
+
+ dsrna = rna_find_struct_def(srna);
+
+ if (func->flag & FUNC_USE_SELF_ID)
+ WRITE_PARAM("(::ID *) ptr.id.data");
+
+ if ((func->flag & FUNC_NO_SELF) == 0) {
+ WRITE_COMMA;
+ if (dsrna->dnaname) fprintf(f, "(::%s *) this->ptr.data", dsrna->dnaname);
+ else fprintf(f, "(::%s *) this->ptr.data", srna->identifier);
+ }
+
+ if (func->flag & FUNC_USE_MAIN)
+ WRITE_PARAM("(::Main *) main");
+
+ if (func->flag & FUNC_USE_CONTEXT)
+ WRITE_PARAM("(::bContext *) C.ptr.data");
+
+ if (func->flag & FUNC_USE_REPORTS)
+ WRITE_PARAM("NULL");
+
+ dp = dfunc->cont.properties.first;
+ for (; dp; dp = dp->next) {
+ if (dp->prop == func->c_ret)
+ continue;
+
+ WRITE_COMMA;
+
+ if (dp->prop->flag & PROP_DYNAMIC)
+ fprintf(f, "%s_len, ", dp->prop->identifier);
+
+ if (dp->prop->type == PROP_POINTER)
+ if ((dp->prop->flag & PROP_RNAPTR) && !(dp->prop->flag & PROP_THICK_WRAP))
+ fprintf(f, "(::%s *) &%s.ptr", rna_parameter_type_name(dp->prop), rna_safe_id(dp->prop->identifier));
+ else
+ fprintf(f, "(::%s *) %s.ptr.data", rna_parameter_type_name(dp->prop), rna_safe_id(dp->prop->identifier));
+ else
+ fprintf(f, "%s", rna_safe_id(dp->prop->identifier));
+ }
+
+ fprintf(f, ");\n");
+}
+
+static void rna_def_struct_function_impl_cpp(FILE *f, StructRNA *srna, FunctionDefRNA *dfunc)
+{
+ PropertyDefRNA *dp;
+ PointerPropertyRNA *pprop;
+
+ FunctionRNA *func = dfunc->func;
+
+ if (!dfunc->call)
+ return;
+
+ rna_def_struct_function_prototype_cpp(f, srna, dfunc, srna->identifier, 0);
+
+ fprintf(f, " {\n");
+
+ if (func->c_ret) {
+ dp = rna_find_parameter_def(func->c_ret);
+
+ if (dp->prop->type == PROP_POINTER) {
+ pprop = (PointerPropertyRNA *) dp->prop;
+
+ fprintf(f, "\t\tPointerRNA result;\n");
+
+ if ((dp->prop->flag & PROP_RNAPTR) == 0) {
+ StructRNA *ret_srna = rna_find_struct((const char *) pprop->type);
+ fprintf(f, "\t\t::%s *retdata = ", rna_parameter_type_name(dp->prop));
+ rna_def_struct_function_call_impl_cpp(f, srna, dfunc);
+ if (ret_srna->flag & STRUCT_ID)
+ fprintf(f, "\t\tRNA_id_pointer_create((::ID *) retdata, &result);\n");
+ else
+ fprintf(f, "\t\tRNA_pointer_create((::ID *) ptr.id.data, &RNA_%s, retdata, &result);\n", (const char *) pprop->type);
+ }
+ else {
+ fprintf(f, "\t\tresult = ");
+ rna_def_struct_function_call_impl_cpp(f, srna, dfunc);
+ }
+
+ fprintf(f, "\t\treturn %s(result);\n", (const char *) pprop->type);
+ }
+ else {
+ fprintf(f, "\t\treturn ");
+ rna_def_struct_function_call_impl_cpp(f, srna, dfunc);
+ }
+ }
+ else {
+ fprintf(f, "\t\t");
+ rna_def_struct_function_call_impl_cpp(f, srna, dfunc);
+ }
+
+ fprintf(f, "\t}\n\n");
+}
+
+static void rna_def_property_wrapper_funcs(FILE *f, StructDefRNA *dsrna, PropertyDefRNA *dp)
+{
+ if (dp->prop->getlength) {
+ char funcname[2048];
+ rna_construct_wrapper_function_name(funcname, sizeof(funcname), dsrna->srna->identifier, dp->prop->identifier, "get_length");
+ fprintf(f, "int %s(PointerRNA *ptr, int *arraylen)\n", funcname);
+ fprintf(f, "{\n");
+ fprintf(f, "\treturn %s(ptr, arraylen);\n", rna_function_string(dp->prop->getlength));
+ fprintf(f, "}\n\n");
+ }
+}
+
+static void rna_def_function_wrapper_funcs(FILE *f, StructDefRNA *dsrna, FunctionDefRNA *dfunc)
+{
+ StructRNA *srna = dsrna->srna;
+ FunctionRNA *func = dfunc->func;
+ PropertyDefRNA *dparm;
+
+ int first;
+ char funcname[2048];
+
+ if (!dfunc->call)
+ return;
+
+ rna_construct_wrapper_function_name(funcname, sizeof(funcname), srna->identifier, func->identifier, NULL);
+
+ rna_generate_static_parameter_prototypes(f, srna, dfunc, funcname, 0);
+
+ fprintf(f, "\n{\n");
+
+ if (func->c_ret)
+ fprintf(f, "\treturn %s(", dfunc->call);
+ else
+ fprintf(f, "\t%s(", dfunc->call);
+
+ first = 1;
+
+ if (func->flag & FUNC_USE_SELF_ID)
+ WRITE_PARAM("_selfid");
+
+ if ((func->flag & FUNC_NO_SELF) == 0)
+ WRITE_PARAM("_self");
+
+ if (func->flag & FUNC_USE_MAIN)
+ WRITE_PARAM("bmain");
+
+ if (func->flag & FUNC_USE_CONTEXT)
+ WRITE_PARAM("C");
+
+ if (func->flag & FUNC_USE_REPORTS)
+ WRITE_PARAM("reports");
+
+ dparm = dfunc->cont.properties.first;
+ for (; dparm; dparm = dparm->next) {
+ if (dparm->prop == func->c_ret)
+ continue;
+
+ WRITE_COMMA;
+
+ if (dparm->prop->flag & PROP_DYNAMIC)
+ fprintf(f, "%s_len, %s", dparm->prop->identifier, dparm->prop->identifier);
+ else
+ fprintf(f, "%s", rna_safe_id(dparm->prop->identifier));
+ }
+
+ fprintf(f, ");\n");
+ fprintf(f, "}\n\n");
+}
+
static void rna_def_function_funcs(FILE *f, StructDefRNA *dsrna, FunctionDefRNA *dfunc)
{
StructRNA *srna;
@@ -1741,6 +2102,8 @@ static void rna_def_function_funcs(FILE *f, StructDefRNA *dsrna, FunctionDefRNA
/* fixed size arrays and RNA pointers are pre-allocated on the ParameterList stack, pass a pointer to it */
else if (type == PROP_POINTER || dparm->prop->arraydimension)
ptrstr = "*";
+ else if ((type == PROP_POINTER) && (flag & PROP_RNAPTR) && !(flag & PROP_THICK_WRAP))
+ ptrstr = "*";
/* PROP_THICK_WRAP strings are pre-allocated on the ParameterList stack,
* but type name for string props is already char*, so leave empty */
else if (type == PROP_STRING && (flag & PROP_THICK_WRAP))
@@ -1792,6 +2155,10 @@ static void rna_def_function_funcs(FILE *f, StructDefRNA *dsrna, FunctionDefRNA
ptrstr = "**";
valstr = "*";
}
+ else if ((type == PROP_POINTER) && !(flag & PROP_THICK_WRAP)) {
+ ptrstr = "**";
+ valstr = "*";
+ }
else if (type == PROP_POINTER || dparm->prop->arraydimension) {
ptrstr = "*";
valstr = "";
@@ -1991,6 +2358,7 @@ static const char *rna_property_subtypename(PropertySubType type)
case PROP_COORDS: return "PROP_COORDS";
case PROP_LAYER: return "PROP_LAYER";
case PROP_LAYER_MEMBER: return "PROP_LAYER_MEMBER";
+ case PROP_PASSWORD: return "PROP_PASSWORD";
default: {
/* in case we don't have a type preset that includes the subtype */
if (RNA_SUBTYPE_UNIT(type)) {
@@ -2107,7 +2475,7 @@ static void rna_generate_function_prototypes(BlenderRNA *brna, StructRNA *srna,
fprintf(f, "\n");
}
-static void rna_generate_static_parameter_prototypes(BlenderRNA *UNUSED(brna), StructRNA *srna, FunctionDefRNA *dfunc, FILE *f)
+static void rna_generate_static_parameter_prototypes(FILE *f, StructRNA *srna, FunctionDefRNA *dfunc, const char *name_override, int close_prototype)
{
FunctionRNA *func;
PropertyDefRNA *dparm;
@@ -2138,7 +2506,10 @@ static void rna_generate_static_parameter_prototypes(BlenderRNA *UNUSED(brna), S
fprintf(f, "void ");
/* function name */
- fprintf(f, "%s(", dfunc->call);
+ if (name_override == NULL || name_override[0] == '\0')
+ fprintf(f, "%s(", dfunc->call);
+ else
+ fprintf(f, "%s(", name_override);
first = 1;
@@ -2147,7 +2518,7 @@ static void rna_generate_static_parameter_prototypes(BlenderRNA *UNUSED(brna), S
fprintf(f, "struct ID *_selfid");
first = 0;
}
-
+
if ((func->flag & FUNC_NO_SELF) == 0) {
if (!first) fprintf(f, ", ");
if (dsrna->dnaname) fprintf(f, "struct %s *_self", dsrna->dnaname);
@@ -2200,17 +2571,19 @@ static void rna_generate_static_parameter_prototypes(BlenderRNA *UNUSED(brna), S
if (!(flag & PROP_DYNAMIC) && dparm->prop->arraydimension)
fprintf(f, "%s%s %s[%u]", rna_type_struct(dparm->prop), rna_parameter_type_name(dparm->prop),
- dparm->prop->identifier, dparm->prop->totarraylength);
+ rna_safe_id(dparm->prop->identifier), dparm->prop->totarraylength);
else
fprintf(f, "%s%s %s%s", rna_type_struct(dparm->prop), rna_parameter_type_name(dparm->prop),
- ptrstr, dparm->prop->identifier);
+ ptrstr, rna_safe_id(dparm->prop->identifier));
}
- fprintf(f, ");\n");
+ fprintf(f, ")");
+ if (close_prototype)
+ fprintf(f, ";\n");
}
-static void rna_generate_static_function_prototypes(BlenderRNA *brna, StructRNA *srna, FILE *f)
+static void rna_generate_static_function_prototypes(BlenderRNA *UNUSED(brna), StructRNA *srna, FILE *f)
{
FunctionRNA *func;
FunctionDefRNA *dfunc;
@@ -2225,7 +2598,50 @@ static void rna_generate_static_function_prototypes(BlenderRNA *brna, StructRNA
first = 0;
}
- rna_generate_static_parameter_prototypes(brna, srna, dfunc, f);
+ rna_generate_static_parameter_prototypes(f, srna, dfunc, NULL, 1);
+ }
+ }
+
+ fprintf(f, "\n");
+}
+
+static void rna_generate_struct_prototypes(FILE *f)
+{
+ StructDefRNA *ds;
+ PropertyDefRNA *dp;
+ FunctionDefRNA *dfunc;
+ const char *structures[2048];
+ int all_structures = 0;
+
+ /* structures definitions */
+ for (ds = DefRNA.structs.first; ds; ds = ds->cont.next) {
+ for (dfunc = ds->functions.first; dfunc; dfunc = dfunc->cont.next) {
+ if (dfunc->call) {
+ for (dp = dfunc->cont.properties.first; dp; dp = dp->next) {
+ if (dp->prop->type == PROP_POINTER) {
+ int a, found = 0;
+ const char *struct_name = rna_parameter_type_name(dp->prop);
+
+ for (a = 0; a < all_structures; a++) {
+ if (strcmp(struct_name, structures[a]) == 0) {
+ found = 1;
+ break;
+ }
+ }
+
+ if (found == 0) {
+ fprintf(f, "struct %s;\n", struct_name);
+
+ if (all_structures >= sizeof(structures) / sizeof(structures[0])) {
+ printf("Array size to store all structures names is too small\n");
+ exit(1);
+ }
+
+ structures[all_structures++] = struct_name;
+ }
+ }
+ }
+ }
}
}
@@ -2791,8 +3207,13 @@ static void rna_generate(BlenderRNA *brna, FILE *f, const char *filename, const
for (ds = DefRNA.structs.first; ds; ds = ds->cont.next) {
if (!filename || ds->filename == filename) {
- for (dfunc = ds->functions.first; dfunc; dfunc = dfunc->cont.next)
+ for (dp = ds->cont.properties.first; dp; dp = dp->next)
+ rna_def_property_wrapper_funcs(f, ds, dp);
+
+ for (dfunc = ds->functions.first; dfunc; dfunc = dfunc->cont.next) {
+ rna_def_function_wrapper_funcs(f, ds, dfunc);
rna_def_function_funcs(f, ds, dfunc);
+ }
rna_generate_static_function_prototypes(brna, ds->srna, f);
}
@@ -2816,6 +3237,7 @@ static void rna_generate_header(BlenderRNA *UNUSED(brna), FILE *f)
StructDefRNA *ds;
PropertyDefRNA *dp;
StructRNA *srna;
+ FunctionDefRNA *dfunc;
fprintf(f, "\n#ifndef __RNA_BLENDER_H__\n");
fprintf(f, "#define __RNA_BLENDER_H__\n\n");
@@ -2853,6 +3275,9 @@ static void rna_generate_header(BlenderRNA *UNUSED(brna), FILE *f)
for (dp = ds->cont.properties.first; dp; dp = dp->next)
rna_def_property_funcs_header(f, ds->srna, dp);
+
+ for (dfunc = ds->functions.first; dfunc; dfunc = dfunc->cont.next)
+ rna_def_function_funcs_header(f, ds->srna, dfunc);
}
fprintf(f, "#ifdef __cplusplus\n}\n#endif\n\n");
@@ -2868,43 +3293,141 @@ static const char *cpp_classes = ""
"namespace BL {\n"
"\n"
"#define BOOLEAN_PROPERTY(sname, identifier) \\\n"
-" inline bool sname::identifier(void) { return sname##_##identifier##_get(&ptr)? true: false; }\n"
+" inline bool sname::identifier(void) { return sname##_##identifier##_get(&ptr)? true: false; } \\\n"
+" inline void sname::identifier(int value) { sname##_##identifier##_set(&ptr, value); }\n"
"\n"
"#define BOOLEAN_ARRAY_PROPERTY(sname, size, identifier) \\\n"
" inline Array<int,size> sname::identifier(void) \\\n"
-" { Array<int, size> ar; sname##_##identifier##_get(&ptr, ar.data); return ar; }\n"
+" { Array<int, size> ar; sname##_##identifier##_get(&ptr, ar.data); return ar; } \\\n"
+" inline void sname::identifier(int values[size]) \\\n"
+" { sname##_##identifier##_set(&ptr, values); } \\\n"
+"\n"
+"#define BOOLEAN_DYNAMIC_ARRAY_PROPERTY(sname, identifier) \\\n"
+" inline DynamicArray<int> sname::identifier(void) { \\\n"
+" int arraylen[3]; \\\n"
+" int len = sname##_##identifier##_get_length(&ptr, arraylen); \\\n"
+" DynamicArray<int> ar(len); \\\n"
+" sname##_##identifier##_get(&ptr, ar.data); \\\n"
+" return ar; } \\\n"
+" inline void sname::identifier(int values[]) \\\n"
+" { sname##_##identifier##_set(&ptr, values); } \\\n"
"\n"
"#define INT_PROPERTY(sname, identifier) \\\n"
-" inline int sname::identifier(void) { return sname##_##identifier##_get(&ptr); }\n"
+" inline int sname::identifier(void) { return sname##_##identifier##_get(&ptr); } \\\n"
+" inline void sname::identifier(int value) { sname##_##identifier##_set(&ptr, value); }\n"
"\n"
"#define INT_ARRAY_PROPERTY(sname, size, identifier) \\\n"
" inline Array<int,size> sname::identifier(void) \\\n"
-" { Array<int, size> ar; sname##_##identifier##_get(&ptr, ar.data); return ar; }\n"
+" { Array<int, size> ar; sname##_##identifier##_get(&ptr, ar.data); return ar; } \\\n"
+" inline void sname::identifier(int values[size]) \\\n"
+" { sname##_##identifier##_set(&ptr, values); } \\\n"
+"\n"
+"#define INT_DYNAMIC_ARRAY_PROPERTY(sname, identifier) \\\n"
+" inline DynamicArray<int> sname::identifier(void) { \\\n"
+" int arraylen[3]; \\\n"
+" int len = sname##_##identifier##_get_length(&ptr, arraylen); \\\n"
+" DynamicArray<int> ar(len); \\\n"
+" sname##_##identifier##_get(&ptr, ar.data); \\\n"
+" return ar; } \\\n"
+" inline void sname::identifier(int values[]) \\\n"
+" { sname##_##identifier##_set(&ptr, values); } \\\n"
"\n"
"#define FLOAT_PROPERTY(sname, identifier) \\\n"
-" inline float sname::identifier(void) { return sname##_##identifier##_get(&ptr); }\n"
+" inline float sname::identifier(void) { return sname##_##identifier##_get(&ptr); } \\\n"
+" inline void sname::identifier(float value) { sname##_##identifier##_set(&ptr, value); }\n"
"\n"
"#define FLOAT_ARRAY_PROPERTY(sname, size, identifier) \\\n"
" inline Array<float,size> sname::identifier(void) \\\n"
-" { Array<float, size> ar; sname##_##identifier##_get(&ptr, ar.data); return ar; }\n"
+" { Array<float, size> ar; sname##_##identifier##_get(&ptr, ar.data); return ar; } \\\n"
+" inline void sname::identifier(float values[size]) \\\n"
+" { sname##_##identifier##_set(&ptr, values); } \\\n"
+"\n"
+"#define FLOAT_DYNAMIC_ARRAY_PROPERTY(sname, identifier) \\\n"
+" inline DynamicArray<float> sname::identifier(void) { \\\n"
+" int arraylen[3]; \\\n"
+" int len = sname##_##identifier##_get_length(&ptr, arraylen); \\\n"
+" DynamicArray<float> ar(len); \\\n"
+" sname##_##identifier##_get(&ptr, ar.data); \\\n"
+" return ar; } \\\n"
+" inline void sname::identifier(float values[]) \\\n"
+" { sname##_##identifier##_set(&ptr, values); } \\\n"
"\n"
"#define ENUM_PROPERTY(type, sname, identifier) \\\n"
-" inline sname::type sname::identifier(void) { return (type)sname##_##identifier##_get(&ptr); }\n"
+" inline sname::type sname::identifier(void) { return (type)sname##_##identifier##_get(&ptr); } \\\n"
+" inline void sname::identifier(sname::type value) { sname##_##identifier##_set(&ptr, value); }\n"
"\n"
"#define STRING_PROPERTY(sname, identifier) \\\n"
" inline std::string sname::identifier(void) { \\\n"
" int len= sname##_##identifier##_length(&ptr); \\\n"
" std::string str; str.resize(len); \\\n"
" sname##_##identifier##_get(&ptr, &str[0]); return str; } \\\n"
+" inline void sname::identifier(const std::string& value) { \\\n"
+" sname##_##identifier##_set(&ptr, value.c_str()); } \\\n"
"\n"
"#define POINTER_PROPERTY(type, sname, identifier) \\\n"
" inline type sname::identifier(void) { return type(sname##_##identifier##_get(&ptr)); }\n"
"\n"
-"#define COLLECTION_PROPERTY(type, sname, identifier) \\\n"
+"#define COLLECTION_PROPERTY_LENGTH_FALSE(sname, identifier) \\\n"
+" inline static int sname##_##identifier##_length_wrap(PointerRNA *ptr) \\\n"
+" { \\\n"
+" CollectionPropertyIterator iter; \\\n"
+" int length = 0; \\\n"
+" sname##_##identifier##_begin(&iter, ptr); \\\n"
+" while (iter.valid) { \\\n"
+" sname##_##identifier##_next(&iter); \\\n"
+" ++length; \\\n"
+" } \\\n"
+" sname##_##identifier##_end(&iter); \\\n"
+" return length; \\\n"
+" } \n"
+"#define COLLECTION_PROPERTY_LENGTH_TRUE(sname, identifier) \\\n"
+" inline static int sname##_##identifier##_length_wrap(PointerRNA *ptr) \\\n"
+" { return sname##_##identifier##_length(ptr); } \n"
+"\n"
+"#define COLLECTION_PROPERTY_LOOKUP_INT_FALSE(sname, identifier) \\\n"
+" inline static int sname##_##identifier##_lookup_int_wrap(PointerRNA *ptr, int key, PointerRNA *r_ptr) \\\n"
+" { \\\n"
+" CollectionPropertyIterator iter; \\\n"
+" int i = 0, found = 0; \\\n"
+" sname##_##identifier##_begin(&iter, ptr); \\\n"
+" while (iter.valid) { \\\n"
+" if (i == key) { \\\n"
+" *r_ptr = iter.ptr; \\\n"
+" found = 1; \\\n"
+" break; \\\n"
+" } \\\n"
+" sname##_##identifier##_next(&iter); \\\n"
+" ++i; \\\n"
+" } \\\n"
+" sname##_##identifier##_end(&iter); \\\n"
+" if (!found) \\\n"
+" memset(r_ptr, 0, sizeof(*r_ptr)); \\\n"
+" return found; \\\n"
+" } \n"
+"#define COLLECTION_PROPERTY_LOOKUP_INT_TRUE(sname, identifier) \\\n"
+" inline static int sname##_##identifier##_lookup_int_wrap(PointerRNA *ptr, int key, PointerRNA *r_ptr) \\\n"
+" { return sname##_##identifier##_lookup_int(ptr, key, r_ptr); } \n"
+"\n"
+"#define COLLECTION_PROPERTY_LOOKUP_STRING_FALSE(sname, identifier) \\\n"
+" inline static int sname##_##identifier##_lookup_string_wrap(PointerRNA *ptr, const char *key, PointerRNA *r_ptr) \\\n"
+" { \\\n"
+" memset(r_ptr, 0, sizeof(*r_ptr)); \\\n"
+" return 0; \\\n"
+" } \n"
+"#define COLLECTION_PROPERTY_LOOKUP_STRING_TRUE(sname, identifier) \\\n"
+" inline static int sname##_##identifier##_lookup_string_wrap(PointerRNA *ptr, const char *key, PointerRNA *r_ptr) \\\n"
+" { return sname##_##identifier##_lookup_string(ptr, key, r_ptr); } \n"
+"\n"
+"#define COLLECTION_PROPERTY(collection_funcs, type, sname, identifier, has_length, has_lookup_int, has_lookup_string) \\\n"
" typedef CollectionIterator<type, sname##_##identifier##_begin, \\\n"
" sname##_##identifier##_next, sname##_##identifier##_end> identifier##_iterator; \\\n"
+" COLLECTION_PROPERTY_LENGTH_##has_length(sname, identifier) \\\n"
+" COLLECTION_PROPERTY_LOOKUP_INT_##has_lookup_int(sname, identifier) \\\n"
+" COLLECTION_PROPERTY_LOOKUP_STRING_##has_lookup_string(sname, identifier) \\\n"
" Collection<sname, type, sname##_##identifier##_begin, \\\n"
-" sname##_##identifier##_next, sname##_##identifier##_end> identifier;\n"
+" sname##_##identifier##_next, sname##_##identifier##_end, \\\n"
+" sname##_##identifier##_length_wrap, \\\n"
+" sname##_##identifier##_lookup_int_wrap, sname##_##identifier##_lookup_string_wrap, collection_funcs> identifier;\n"
"\n"
"class Pointer {\n"
"public:\n"
@@ -2923,7 +3446,7 @@ static const char *cpp_classes = ""
"public:\n"
" T data[Tsize];\n"
"\n"
-" Array() {}\n"
+" Array() {}\n"
" Array(const Array<T, Tsize>& other) { memcpy(data, other.data, sizeof(T) * Tsize); }\n"
" const Array<T, Tsize>& operator=(const Array<T, Tsize>& other) { memcpy(data, other.data, sizeof(T) * Tsize); "
"return *this; }\n"
@@ -2931,9 +3454,36 @@ static const char *cpp_classes = ""
" operator T*() { return data; }\n"
"};\n"
"\n"
+"template<typename T>\n"
+"class DynamicArray {\n"
+"public:\n"
+" T *data;\n"
+" int length;\n"
+"\n"
+" DynamicArray() : data(NULL), length(0) {}\n"
+" DynamicArray(int new_length) : data(NULL), length(new_length) { data = (float*)malloc(sizeof(T) * new_length); }\n"
+" DynamicArray(const DynamicArray<T>& other) { copy_from(other); }\n"
+" const DynamicArray<T>& operator=(const DynamicArray<T>& other) { copy_from(other); return *this; }\n"
+"\n"
+" ~DynamicArray() { if (data) free(data); }\n"
+"\n"
+" operator T*() { return data; }\n"
+"\n"
+"protected:\n"
+" void copy_from(const DynamicArray<T>& other) {\n"
+" if (data) free(data);\n"
+" data = (float*)malloc(sizeof(T) * other.length);\n"
+" memcpy(data, other.data, sizeof(T) * other.length);\n"
+" length = other.length;\n"
+" }\n"
+"};\n"
+"\n"
"typedef void (*TBeginFunc)(CollectionPropertyIterator *iter, PointerRNA *ptr);\n"
"typedef void (*TNextFunc)(CollectionPropertyIterator *iter);\n"
"typedef void (*TEndFunc)(CollectionPropertyIterator *iter);\n"
+"typedef int (*TLengthFunc)(PointerRNA *ptr);\n"
+"typedef int (*TLookupIntFunc)(PointerRNA *ptr, int key, PointerRNA *r_ptr);\n"
+"typedef int (*TLookupStringFunc)(PointerRNA *ptr, const char *key, PointerRNA *r_ptr);\n"
"\n"
"template<typename T, TBeginFunc Tbegin, TNextFunc Tnext, TEndFunc Tend>\n"
"class CollectionIterator {\n"
@@ -2964,26 +3514,97 @@ static const char *cpp_classes = ""
" bool init;\n"
"};\n"
"\n"
-"template<typename Tp, typename T, TBeginFunc Tbegin, TNextFunc Tnext, TEndFunc Tend>\n"
-"class Collection {\n"
+"template<typename Tp, typename T, TBeginFunc Tbegin, TNextFunc Tnext, TEndFunc Tend,\n"
+" TLengthFunc Tlength, TLookupIntFunc Tlookup_int, TLookupStringFunc Tlookup_string,\n"
+" typename Tcollection_funcs>\n"
+"class Collection : public Tcollection_funcs {\n"
"public:\n"
-" Collection(const PointerRNA &p) : ptr(p) {}\n"
+" Collection(const PointerRNA &p) : Tcollection_funcs(p), ptr(p) {}\n"
"\n"
" void begin(CollectionIterator<T, Tbegin, Tnext, Tend>& iter)\n"
" { iter.begin(ptr); }\n"
" CollectionIterator<T, Tbegin, Tnext, Tend> end()\n"
" { return CollectionIterator<T, Tbegin, Tnext, Tend>(); } /* test */ \n"
+""
+" int length()\n"
+" { return Tlength(&ptr); }\n"
+" T operator[](int key)\n"
+" { PointerRNA r_ptr; Tlookup_int(&ptr, key, &r_ptr); return T(r_ptr); }\n"
+" T operator[](const std::string &key)\n"
+" { PointerRNA r_ptr; Tlookup_string(&ptr, key.c_str(), &r_ptr); return T(r_ptr); }\n"
"\n"
"private:\n"
" PointerRNA ptr;\n"
"};\n"
+"\n"
+"class DefaultCollectionFunctions {\n"
+"public:\n"
+" DefaultCollectionFunctions(const PointerRNA &p) {}\n"
+"};\n"
+"\n"
"\n";
+static int rna_is_collection_prop(PropertyRNA *prop)
+{
+ if (!(prop->flag & (PROP_IDPROPERTY | PROP_BUILTIN)))
+ if (prop->type == PROP_COLLECTION)
+ return 1;
+
+ return 0;
+}
+
+static int rna_is_collection_functions_struct(const char **collection_structs, const char *struct_name)
+{
+ int a = 0, found = 0;
+
+ while (collection_structs[a]) {
+ if (!strcmp(collection_structs[a], struct_name)) {
+ found = 1;
+ break;
+ }
+ a++;
+ }
+
+ return found;
+}
+
+static void rna_generate_header_class_cpp(StructDefRNA *ds, FILE *f)
+{
+ StructRNA *srna = ds->srna;
+ PropertyDefRNA *dp;
+ FunctionDefRNA *dfunc;
+
+ fprintf(f, "/**************** %s ****************/\n\n", srna->name);
+
+ fprintf(f, "class %s : public %s {\n", srna->identifier, (srna->base) ? srna->base->identifier : "Pointer");
+ fprintf(f, "public:\n");
+ fprintf(f, "\t%s(const PointerRNA &ptr_arg) :\n\t\t%s(ptr_arg)", srna->identifier,
+ (srna->base) ? srna->base->identifier : "Pointer");
+ for (dp = ds->cont.properties.first; dp; dp = dp->next)
+ if (rna_is_collection_prop(dp->prop))
+ fprintf(f, ",\n\t\t%s(ptr_arg)", dp->prop->identifier);
+ fprintf(f, "\n\t\t{}\n\n");
+
+ for (dp = ds->cont.properties.first; dp; dp = dp->next)
+ rna_def_property_funcs_header_cpp(f, ds->srna, dp);
+
+ fprintf(f, "\n");
+ for (dfunc = ds->functions.first; dfunc; dfunc = dfunc->cont.next)
+ rna_def_struct_function_header_cpp(f, srna, dfunc);
+
+ fprintf(f, "};\n\n");
+}
+
static void rna_generate_header_cpp(BlenderRNA *UNUSED(brna), FILE *f)
{
StructDefRNA *ds;
PropertyDefRNA *dp;
StructRNA *srna;
+ FunctionDefRNA *dfunc;
+ const char *first_collection_func_struct = NULL;
+ const char *collection_func_structs[256] = {NULL};
+ int all_collection_func_structs = 0;
+ int max_collection_func_structs = sizeof(collection_func_structs) / sizeof(collection_func_structs[0]) - 1;
fprintf(f, "\n#ifndef __RNA_BLENDER_CPP_H__\n");
fprintf(f, "#define __RNA_BLENDER_CPP_H__\n\n");
@@ -3000,38 +3621,86 @@ static void rna_generate_header_cpp(BlenderRNA *UNUSED(brna), FILE *f)
fprintf(f, "/**************** Declarations ****************/\n\n");
- for (ds = DefRNA.structs.first; ds; ds = ds->cont.next)
+ for (ds = DefRNA.structs.first; ds; ds = ds->cont.next) {
fprintf(f, "class %s;\n", ds->srna->identifier);
+ }
fprintf(f, "\n");
+ /* first get list of all structures used as collection functions, so they'll be declared first */
+ for (ds = DefRNA.structs.first; ds; ds = ds->cont.next) {
+ for (dp = ds->cont.properties.first; dp; dp = dp->next) {
+ if (rna_is_collection_prop(dp->prop)) {
+ PropertyRNA *prop = dp->prop;
+
+ if (prop->srna) {
+ /* store name of structure which first uses custom functions for collections */
+ if (first_collection_func_struct == NULL)
+ first_collection_func_struct = ds->srna->identifier;
+
+ if (!rna_is_collection_functions_struct(collection_func_structs, (char*)prop->srna)) {
+ if (all_collection_func_structs >= max_collection_func_structs) {
+ printf("Array size to store all collection structures names is too small\n");
+ exit(1);
+ }
+
+ collection_func_structs[all_collection_func_structs++] = (char*)prop->srna;
+ }
+ }
+ }
+ }
+ }
+
+ /* declare all structures in such order:
+ * - first N structures which doesn't use custom functions for collections
+ * - all structures used for custom functions in collections
+ * - all the rest structures
+ * such an order prevents usage of non-declared classes
+ */
for (ds = DefRNA.structs.first; ds; ds = ds->cont.next) {
srna = ds->srna;
- fprintf(f, "/**************** %s ****************/\n\n", srna->name);
+ if (!strcmp(srna->identifier, first_collection_func_struct)) {
+ StructDefRNA *ds2;
+ StructRNA *srna2;
- fprintf(f, "class %s : public %s {\n", srna->identifier, (srna->base) ? srna->base->identifier : "Pointer");
- fprintf(f, "public:\n");
- fprintf(f, "\t%s(const PointerRNA &ptr_arg) :\n\t\t%s(ptr_arg)", srna->identifier,
- (srna->base) ? srna->base->identifier : "Pointer");
- for (dp = ds->cont.properties.first; dp; dp = dp->next)
- if (!(dp->prop->flag & (PROP_IDPROPERTY | PROP_BUILTIN)))
- if (dp->prop->type == PROP_COLLECTION)
- fprintf(f, ",\n\t\t%s(ptr_arg)", dp->prop->identifier);
- fprintf(f, "\n\t\t{}\n\n");
+ for (ds2 = DefRNA.structs.first; ds2; ds2 = ds2->cont.next) {
+ srna2 = ds2->srna;
- for (dp = ds->cont.properties.first; dp; dp = dp->next)
- rna_def_property_funcs_header_cpp(f, ds->srna, dp);
- fprintf(f, "};\n\n");
+ if (rna_is_collection_functions_struct(collection_func_structs, srna2->identifier)) {
+ rna_generate_header_class_cpp(ds2, f);
+ }
+ }
+ }
+
+ if (!rna_is_collection_functions_struct(collection_func_structs, srna->identifier))
+ rna_generate_header_class_cpp(ds, f);
}
+ fprintf(f, "} /* namespace BL */\n");
+ fprintf(f, "\n");
fprintf(f, "/**************** Implementation ****************/\n");
+ fprintf(f, "\n");
+
+ fprintf(f, "/* Structure prototypes */\n\n");
+ fprintf(f, "extern \"C\" {\n");
+ rna_generate_struct_prototypes(f);
+ fprintf(f, "}\n\n");
+
+ fprintf(f, "namespace BL {\n");
for (ds = DefRNA.structs.first; ds; ds = ds->cont.next) {
+ srna = ds->srna;
+
for (dp = ds->cont.properties.first; dp; dp = dp->next)
rna_def_property_funcs_impl_cpp(f, ds->srna, dp);
fprintf(f, "\n");
+
+ for (dfunc = ds->functions.first; dfunc; dfunc = dfunc->cont.next)
+ rna_def_struct_function_impl_cpp(f, srna, dfunc);
+
+ fprintf(f, "\n");
}
fprintf(f, "}\n\n#endif /* __RNA_BLENDER_CPP_H__ */\n\n");
@@ -3068,34 +3737,8 @@ static int rna_preprocess(const char *outfile)
rna_auto_types();
-
- /* create RNA_blender_cpp.h */
- strcpy(deffile, outfile);
- strcat(deffile, "RNA_blender_cpp.h" TMP_EXT);
-
status = (DefRNA.error != 0);
- if (status) {
- make_bad_file(deffile, __LINE__);
- }
- else {
- file = fopen(deffile, "w");
-
- if (!file) {
- fprintf(stderr, "Unable to open file: %s\n", deffile);
- status = 1;
- }
- else {
- rna_generate_header_cpp(brna, file);
- fclose(file);
- status = (DefRNA.error != 0);
- }
- }
-
- replace_if_different(deffile, NULL);
-
- rna_sort(brna);
-
/* create rna_gen_*.c files */
for (i = 0; PROCESS_ITEMS[i].filename; i++) {
strcpy(deffile, outfile);
@@ -3128,6 +3771,31 @@ static int rna_preprocess(const char *outfile)
replace_if_different(deffile, deps);
}
+ /* create RNA_blender_cpp.h */
+ strcpy(deffile, outfile);
+ strcat(deffile, "RNA_blender_cpp.h" TMP_EXT);
+
+ if (status) {
+ make_bad_file(deffile, __LINE__);
+ }
+ else {
+ file = fopen(deffile, "w");
+
+ if (!file) {
+ fprintf(stderr, "Unable to open file: %s\n", deffile);
+ status = 1;
+ }
+ else {
+ rna_generate_header_cpp(brna, file);
+ fclose(file);
+ status = (DefRNA.error != 0);
+ }
+ }
+
+ replace_if_different(deffile, NULL);
+
+ rna_sort(brna);
+
/* create RNA_blender.h */
strcpy(deffile, outfile);
strcat(deffile, "RNA_blender.h" TMP_EXT);
diff --git a/source/blender/makesrna/intern/rna_ID.c b/source/blender/makesrna/intern/rna_ID.c
index 897e784c8e4..11ce7345e41 100644
--- a/source/blender/makesrna/intern/rna_ID.c
+++ b/source/blender/makesrna/intern/rna_ID.c
@@ -243,8 +243,8 @@ StructRNA *rna_PropertyGroup_register(Main *UNUSED(bmain), ReportList *reports,
* owns the string pointer which it could potentially free while blender
* is running. */
if (BLI_strnlen(identifier, MAX_IDPROP_NAME) == MAX_IDPROP_NAME) {
- BKE_reportf(reports, RPT_ERROR, "registering id property class: '%s' is too long, maximum length is "
- STRINGIFY(MAX_IDPROP_NAME), identifier);
+ BKE_reportf(reports, RPT_ERROR, "Registering id property class: '%s' is too long, maximum length is %d",
+ identifier, MAX_IDPROP_NAME);
return NULL;
}
@@ -256,7 +256,7 @@ StructRNA *rna_PropertyGroup_refine(PointerRNA *ptr)
return ptr->type;
}
-ID *rna_ID_copy(ID *id)
+static ID *rna_ID_copy(ID *id)
{
ID *newid;
@@ -287,7 +287,7 @@ static void rna_ID_update_tag(ID *id, ReportList *reports, int flag)
switch (GS(id->name)) {
case ID_OB:
if (flag & ~(OB_RECALC_ALL)) {
- BKE_report(reports, RPT_ERROR, "'refresh' incompatible with Object ID type");
+ BKE_report(reports, RPT_ERROR, "'Refresh' incompatible with Object ID type");
return;
}
break;
@@ -295,7 +295,7 @@ static void rna_ID_update_tag(ID *id, ReportList *reports, int flag)
#if 0
case ID_PA:
if (flag & ~(OB_RECALC_ALL | PSYS_RECALC)) {
- BKE_report(reports, RPT_ERROR, "'refresh' incompatible with ParticleSettings ID type");
+ BKE_report(reports, RPT_ERROR, "'Refresh' incompatible with ParticleSettings ID type");
return;
}
break;
@@ -309,7 +309,7 @@ static void rna_ID_update_tag(ID *id, ReportList *reports, int flag)
DAG_id_tag_update(id, flag);
}
-void rna_ID_user_clear(ID *id)
+static void rna_ID_user_clear(ID *id)
{
id->us = 0; /* don't save */
id->flag &= ~LIB_FAKEUSER;
@@ -341,7 +341,7 @@ int rna_IDMaterials_assign_int(PointerRNA *ptr, int key, const PointerRNA *assig
}
}
-void rna_IDMaterials_append_id(ID *id, Material *ma)
+static void rna_IDMaterials_append_id(ID *id, Material *ma)
{
material_append_id(id, ma);
@@ -349,7 +349,7 @@ void rna_IDMaterials_append_id(ID *id, Material *ma)
WM_main_add_notifier(NC_OBJECT | ND_OB_SHADING, id);
}
-Material *rna_IDMaterials_pop_id(ID *id, int index_i, int remove_material_slot)
+static Material *rna_IDMaterials_pop_id(ID *id, int index_i, int remove_material_slot)
{
Material *ma = material_pop_id(id, index_i, remove_material_slot);
@@ -360,7 +360,7 @@ Material *rna_IDMaterials_pop_id(ID *id, int index_i, int remove_material_slot)
return ma;
}
-void rna_Library_filepath_set(PointerRNA *ptr, const char *value)
+static void rna_Library_filepath_set(PointerRNA *ptr, const char *value)
{
Library *lib = (Library *)ptr->data;
BKE_library_filepath_set(lib, value);
diff --git a/source/blender/makesrna/intern/rna_access.c b/source/blender/makesrna/intern/rna_access.c
index 4c1c377cb9f..1fe46342819 100644
--- a/source/blender/makesrna/intern/rna_access.c
+++ b/source/blender/makesrna/intern/rna_access.c
@@ -233,7 +233,7 @@ static void rna_idproperty_touch(IDProperty *idprop)
}
/* return a UI local ID prop definition for this prop */
-IDProperty *rna_idproperty_ui(PropertyRNA *prop)
+static IDProperty *rna_idproperty_ui(PropertyRNA *prop)
{
IDProperty *idprop;
@@ -618,7 +618,7 @@ PropertyRNA *RNA_struct_find_property(PointerRNA *ptr, const char *identifier)
}
/* Find the property which uses the given nested struct */
-PropertyRNA *RNA_struct_find_nested(PointerRNA *ptr, StructRNA *srna)
+static PropertyRNA *RNA_struct_find_nested(PointerRNA *ptr, StructRNA *srna)
{
PropertyRNA *prop = NULL;
@@ -996,7 +996,7 @@ void RNA_property_float_range(PointerRNA *ptr, PropertyRNA *prop, float *hardmin
IDProperty *item;
item = IDP_GetPropertyTypeFromGroup(idp_ui, "min", IDP_DOUBLE);
- *hardmin = item ? (float)IDP_Double(item) : FLT_MIN;
+ *hardmin = item ? (float)IDP_Double(item) : -FLT_MAX;
item = IDP_GetPropertyTypeFromGroup(idp_ui, "max", IDP_DOUBLE);
*hardmax = item ? (float)IDP_Double(item) : FLT_MAX;
@@ -3169,7 +3169,7 @@ static int rna_raw_access(ReportList *reports, PointerRNA *ptr, PropertyRNA *pro
itemtype = RNA_property_type(iprop);
}
else {
- BKE_reportf(reports, RPT_ERROR, "Property named %s not found", propname);
+ BKE_reportf(reports, RPT_ERROR, "Property named '%s' not found", propname);
err = 1;
break;
}
@@ -3606,7 +3606,7 @@ static char *rna_path_token(const char **path, char *fixedbuf, int fixedlen, int
/* copy string, taking into account escaped ] */
if (bracket) {
for (p = *path, i = 0, j = 0; i < len; i++, p++) {
- if (*p == '\\' && *(p + 1) == quote) ;
+ if (*p == '\\' && *(p + 1) == quote) {}
else buf[j++] = *p;
}
@@ -3647,7 +3647,8 @@ int RNA_path_resolve(PointerRNA *ptr, const char *path, PointerRNA *r_ptr, Prope
int RNA_path_resolve_full(PointerRNA *ptr, const char *path, PointerRNA *r_ptr, PropertyRNA **r_prop, int *index)
{
PropertyRNA *prop;
- PointerRNA curptr, nextptr;
+ PointerRNA curptr;
+ PointerRNA nextptr; /* keep uninitialized, helps expose bugs in collection accessor functions */
char fixedbuf[256], *token;
int type, intkey;
@@ -3713,7 +3714,12 @@ int RNA_path_resolve_full(PointerRNA *ptr, const char *path, PointerRNA *r_ptr,
/* check for "" to see if it is a string */
if (rna_token_strip_quotes(token)) {
- RNA_property_collection_lookup_string(&curptr, prop, token + 1, &nextptr);
+ if (RNA_property_collection_lookup_string(&curptr, prop, token + 1, &nextptr)) {
+ /* pass */
+ }
+ else {
+ nextptr.data = NULL;
+ }
}
else {
/* otherwise do int lookup */
@@ -3721,7 +3727,12 @@ int RNA_path_resolve_full(PointerRNA *ptr, const char *path, PointerRNA *r_ptr,
if (intkey == 0 && (token[0] != '0' || token[1] != '\0')) {
return 0; /* we can be sure the fixedbuf was used in this case */
}
- RNA_property_collection_lookup_int(&curptr, prop, intkey, &nextptr);
+ if (RNA_property_collection_lookup_int(&curptr, prop, intkey, &nextptr)) {
+ /* pass */
+ }
+ else {
+ nextptr.data = NULL;
+ }
}
if (token != fixedbuf) {
@@ -3730,13 +3741,14 @@ int RNA_path_resolve_full(PointerRNA *ptr, const char *path, PointerRNA *r_ptr,
}
else {
PointerRNA c_ptr;
-
- /* ensure we quit on invalid values */
- nextptr.data = NULL;
if (RNA_property_collection_type_get(&curptr, prop, &c_ptr)) {
nextptr = c_ptr;
}
+ else {
+ /* ensure we quit on invalid values */
+ nextptr.data = NULL;
+ }
}
if (nextptr.data) {
@@ -4512,6 +4524,17 @@ int RNA_collection_length(PointerRNA *ptr, const char *name)
}
}
+int RNA_property_is_set_ex(PointerRNA *ptr, PropertyRNA *prop, int use_ghost)
+{
+ if (prop->flag & PROP_IDPROPERTY) {
+ IDProperty *idprop = rna_idproperty_find(ptr, prop->identifier);
+ return ((idprop != NULL) && (use_ghost == FALSE || !(idprop->flag & IDP_FLAG_GHOST)));
+ }
+ else {
+ return 1;
+ }
+}
+
int RNA_property_is_set(PointerRNA *ptr, PropertyRNA *prop)
{
if (prop->flag & PROP_IDPROPERTY) {
@@ -4523,6 +4546,20 @@ int RNA_property_is_set(PointerRNA *ptr, PropertyRNA *prop)
}
}
+int RNA_struct_property_is_set_ex(PointerRNA *ptr, const char *identifier, int use_ghost)
+{
+ PropertyRNA *prop = RNA_struct_find_property(ptr, identifier);
+
+ if (prop) {
+ return RNA_property_is_set_ex(ptr, prop, use_ghost);
+ }
+ else {
+ /* python raises an error */
+ /* printf("%s: %s.%s not found.\n", __func__, ptr->type->identifier, name); */
+ return 0;
+ }
+}
+
int RNA_struct_property_is_set(PointerRNA *ptr, const char *identifier)
{
PropertyRNA *prop = RNA_struct_find_property(ptr, identifier);
@@ -5219,7 +5256,7 @@ static int rna_function_format_array_length(const char *format, int ofs, int fle
lenbuf[idx] = format[ofs];
if (ofs < flen && format[ofs + 1] == ']') {
- /* XXX put better error reporting for ofs>=flen or idx over lenbuf capacity */
+ /* XXX put better error reporting for (ofs >= flen) or idx over lenbuf capacity */
lenbuf[idx] = '\0';
return atoi(lenbuf);
}
diff --git a/source/blender/makesrna/intern/rna_action.c b/source/blender/makesrna/intern/rna_action.c
index 00a257ab4f9..ba1aca2baba 100644
--- a/source/blender/makesrna/intern/rna_action.c
+++ b/source/blender/makesrna/intern/rna_action.c
@@ -27,6 +27,7 @@
#include <stdlib.h>
+#include "RNA_access.h"
#include "RNA_define.h"
#include "RNA_enum_types.h"
@@ -68,29 +69,30 @@ static bActionGroup *rna_Action_groups_new(bAction *act, const char name[])
return action_groups_add_new(act, name);
}
-static void rna_Action_groups_remove(bAction *act, ReportList *reports, bActionGroup *agrp)
+static void rna_Action_groups_remove(bAction *act, ReportList *reports, PointerRNA *agrp_ptr)
{
+ bActionGroup *agrp = agrp_ptr->data;
FCurve *fcu, *fcn;
/* try to remove the F-Curve from the action */
- if (!BLI_remlink_safe(&act->groups, agrp)) {
- BKE_reportf(reports, RPT_ERROR, "ActionGroup '%s' not found in action '%s'", agrp->name, act->id.name + 2);
+ if (BLI_remlink_safe(&act->groups, agrp) == FALSE) {
+ BKE_reportf(reports, RPT_ERROR, "Action group '%s' not found in action '%s'", agrp->name, act->id.name + 2);
return;
}
/* move every one one of the group's F-Curves out into the Action again */
for (fcu = agrp->channels.first; (fcu) && (fcu->grp == agrp); fcu = fcn) {
fcn = fcu->next;
-
+
/* remove from group */
action_groups_remove_channel(act, fcu);
-
+
/* tack onto the end */
BLI_addtail(&act->curves, fcu);
}
-
- /* XXX, invalidates PyObject */
+
MEM_freeN(agrp);
+ RNA_POINTER_INVALIDATE(agrp_ptr);
}
static FCurve *rna_Action_fcurve_new(bAction *act, ReportList *reports, const char *data_path,
@@ -112,17 +114,19 @@ static FCurve *rna_Action_fcurve_new(bAction *act, ReportList *reports, const ch
return verify_fcurve(act, group, NULL, data_path, index, 1);
}
-static void rna_Action_fcurve_remove(bAction *act, ReportList *reports, FCurve *fcu)
+static void rna_Action_fcurve_remove(bAction *act, ReportList *reports, PointerRNA *fcu_ptr)
{
+ FCurve *fcu = fcu_ptr->data;
if (fcu->grp) {
if (BLI_findindex(&act->groups, fcu->grp) == -1) {
- BKE_reportf(reports, RPT_ERROR, "F-Curve's ActionGroup '%s' not found in action '%s'",
+ BKE_reportf(reports, RPT_ERROR, "F-Curve's action group '%s' not found in action '%s'",
fcu->grp->name, act->id.name + 2);
return;
}
action_groups_remove_channel(act, fcu);
free_fcurve(fcu);
+ RNA_POINTER_INVALIDATE(fcu_ptr);
}
else {
if (BLI_findindex(&act->curves, fcu) == -1) {
@@ -132,6 +136,7 @@ static void rna_Action_fcurve_remove(bAction *act, ReportList *reports, FCurve *
BLI_remlink(&act->curves, fcu);
free_fcurve(fcu);
+ RNA_POINTER_INVALIDATE(fcu_ptr);
}
}
@@ -145,15 +150,16 @@ static TimeMarker *rna_Action_pose_markers_new(bAction *act, const char name[])
return marker;
}
-static void rna_Action_pose_markers_remove(bAction *act, ReportList *reports, TimeMarker *marker)
+static void rna_Action_pose_markers_remove(bAction *act, ReportList *reports, PointerRNA *marker_ptr)
{
- if (!BLI_remlink_safe(&act->markers, marker)) {
- BKE_reportf(reports, RPT_ERROR, "TimelineMarker '%s' not found in Action '%s'", marker->name, act->id.name + 2);
+ TimeMarker *marker = marker_ptr->data;
+ if (BLI_remlink_safe(&act->markers, marker) == FALSE) {
+ BKE_reportf(reports, RPT_ERROR, "Timeline marker '%s' not found in action '%s'", marker->name, act->id.name + 2);
return;
}
- /* XXX, invalidates PyObject */
MEM_freeN(marker);
+ RNA_POINTER_INVALIDATE(marker_ptr);
}
static PointerRNA rna_Action_active_pose_marker_get(PointerRNA *ptr)
@@ -256,15 +262,14 @@ static void rna_def_dopesheet(BlenderRNA *brna)
srna = RNA_def_struct(brna, "DopeSheet", NULL);
RNA_def_struct_sdna(srna, "bDopeSheet");
- RNA_def_struct_ui_text(srna, "DopeSheet", "Settings for filtering the channels shown in Animation Editors");
+ RNA_def_struct_ui_text(srna, "DopeSheet", "Settings for filtering the channels shown in animation editors");
/* Source of DopeSheet data */
/* XXX: make this obsolete? */
prop = RNA_def_property(srna, "source", PROP_POINTER, PROP_NONE);
RNA_def_property_struct_type(prop, "ID");
RNA_def_property_ui_text(prop, "Source",
- "ID-Block representing source data, currently ID_SCE (for Dopesheet), "
- "and ID_SC (for Grease Pencil)");
+ "ID-Block representing source data, usually ID_SCE (i.e. Scene)");
/* Show datablock filters */
prop = RNA_def_property(srna, "show_datablock_filters", PROP_BOOLEAN, PROP_NONE);
@@ -283,22 +288,29 @@ static void rna_def_dopesheet(BlenderRNA *brna)
prop = RNA_def_property(srna, "show_hidden", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "filterflag", ADS_FILTER_INCL_HIDDEN);
- RNA_def_property_ui_text(prop, "Display Hidden", "Include channels from objects/bone that aren't visible");
+ RNA_def_property_ui_text(prop, "Display Hidden", "Include channels from objects/bone that are not visible");
RNA_def_property_ui_icon(prop, ICON_GHOST_ENABLED, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
+ /* Debug Filtering Settings */
+ prop = RNA_def_property(srna, "show_only_errors", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "filterflag", ADS_FILTER_ONLY_ERRORS);
+ RNA_def_property_ui_text(prop, "Show Errors", "Only include F-Curves and drivers that are disabled or have errors");
+ RNA_def_property_ui_icon(prop, ICON_HELP, 0); /* XXX: this doesn't quite fit */
+ RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
+
/* Object Group Filtering Settings */
prop = RNA_def_property(srna, "show_only_group_objects", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "filterflag", ADS_FILTER_ONLYOBGROUP);
RNA_def_property_ui_text(prop, "Only Objects in Group",
- "Only include channels from Objects in the specified Group");
+ "Only include channels from objects in the specified group");
RNA_def_property_ui_icon(prop, ICON_GROUP, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "filter_group", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "filter_grp");
RNA_def_property_flag(prop, PROP_EDITABLE);
- RNA_def_property_ui_text(prop, "Filtering Group", "Group that included Object should be a member of");
+ RNA_def_property_ui_text(prop, "Filtering Group", "Group that included object should be a member of");
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
/* FCurve Display Name Search Settings */
@@ -318,21 +330,21 @@ static void rna_def_dopesheet(BlenderRNA *brna)
prop = RNA_def_property(srna, "show_missing_nla", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NLA_NOACT);
RNA_def_property_ui_text(prop, "Include Missing NLA",
- "Include Animation Data blocks with no NLA data (NLA Editor only)");
+ "Include animation data blocks with no NLA data (NLA editor only)");
RNA_def_property_ui_icon(prop, ICON_ACTION, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
/* Summary Settings (DopeSheet editors only) */
prop = RNA_def_property(srna, "show_summary", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "filterflag", ADS_FILTER_SUMMARY);
- RNA_def_property_ui_text(prop, "Display Summary", "Display an additional 'summary' line (DopeSheet Editors only)");
+ RNA_def_property_ui_text(prop, "Display Summary", "Display an additional 'summary' line (DopeSheet editors only)");
RNA_def_property_ui_icon(prop, ICON_BORDERMOVE, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_expanded_summary", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", ADS_FLAG_SUMMARY_COLLAPSED);
RNA_def_property_ui_text(prop, "Collapse Summary",
- "Collapse summary when shown, so all other channels get hidden (DopeSheet Editors Only)");
+ "Collapse summary when shown, so all other channels get hidden (DopeSheet editors only)");
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
@@ -340,97 +352,97 @@ static void rna_def_dopesheet(BlenderRNA *brna)
prop = RNA_def_property(srna, "show_transforms", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOOBJ);
RNA_def_property_ui_text(prop, "Display Transforms",
- "Include visualization of Object-level Animation data (mostly Transforms)");
+ "Include visualization of object-level animation data (mostly transforms)");
RNA_def_property_ui_icon(prop, ICON_MANIPUL, 0); /* XXX? */
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_shapekeys", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOSHAPEKEYS);
- RNA_def_property_ui_text(prop, "Display Shapekeys", "Include visualization of ShapeKey related Animation data");
+ RNA_def_property_ui_text(prop, "Display Shapekeys", "Include visualization of shape key related animation data");
RNA_def_property_ui_icon(prop, ICON_SHAPEKEY_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_meshes", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOMESH);
- RNA_def_property_ui_text(prop, "Display Meshes", "Include visualization of Mesh related Animation data");
+ RNA_def_property_ui_text(prop, "Display Meshes", "Include visualization of mesh related animation data");
RNA_def_property_ui_icon(prop, ICON_MESH_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_lattices", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOLAT);
- RNA_def_property_ui_text(prop, "Display Lattices", "Include visualization of Lattice related Animation data");
+ RNA_def_property_ui_text(prop, "Display Lattices", "Include visualization of lattice related animation data");
RNA_def_property_ui_icon(prop, ICON_LATTICE_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_cameras", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOCAM);
- RNA_def_property_ui_text(prop, "Display Camera", "Include visualization of Camera related Animation data");
+ RNA_def_property_ui_text(prop, "Display Camera", "Include visualization of camera related animation data");
RNA_def_property_ui_icon(prop, ICON_CAMERA_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_materials", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOMAT);
- RNA_def_property_ui_text(prop, "Display Material", "Include visualization of Material related Animation data");
+ RNA_def_property_ui_text(prop, "Display Material", "Include visualization of material related animation data");
RNA_def_property_ui_icon(prop, ICON_MATERIAL_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_lamps", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOLAM);
- RNA_def_property_ui_text(prop, "Display Lamp", "Include visualization of Lamp related Animation data");
+ RNA_def_property_ui_text(prop, "Display Lamp", "Include visualization of lamp related animation data");
RNA_def_property_ui_icon(prop, ICON_LAMP_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_textures", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOTEX);
- RNA_def_property_ui_text(prop, "Display Texture", "Include visualization of Texture related Animation data");
+ RNA_def_property_ui_text(prop, "Display Texture", "Include visualization of texture related animation data");
RNA_def_property_ui_icon(prop, ICON_TEXTURE_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_curves", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOCUR);
- RNA_def_property_ui_text(prop, "Display Curve", "Include visualization of Curve related Animation data");
+ RNA_def_property_ui_text(prop, "Display Curve", "Include visualization of curve related animation data");
RNA_def_property_ui_icon(prop, ICON_CURVE_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_worlds", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOWOR);
- RNA_def_property_ui_text(prop, "Display World", "Include visualization of World related Animation data");
+ RNA_def_property_ui_text(prop, "Display World", "Include visualization of world related animation data");
RNA_def_property_ui_icon(prop, ICON_WORLD_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_scenes", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOSCE);
- RNA_def_property_ui_text(prop, "Display Scene", "Include visualization of Scene related Animation data");
+ RNA_def_property_ui_text(prop, "Display Scene", "Include visualization of scene related animation data");
RNA_def_property_ui_icon(prop, ICON_SCENE_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_particles", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOPART);
- RNA_def_property_ui_text(prop, "Display Particle", "Include visualization of Particle related Animation data");
+ RNA_def_property_ui_text(prop, "Display Particle", "Include visualization of particle related animation data");
RNA_def_property_ui_icon(prop, ICON_PARTICLE_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_metaballs", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOMBA);
- RNA_def_property_ui_text(prop, "Display Metaball", "Include visualization of Metaball related Animation data");
+ RNA_def_property_ui_text(prop, "Display Metaball", "Include visualization of metaball related animation data");
RNA_def_property_ui_icon(prop, ICON_META_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_armatures", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOARM);
- RNA_def_property_ui_text(prop, "Display Armature", "Include visualization of Armature related Animation data");
+ RNA_def_property_ui_text(prop, "Display Armature", "Include visualization of armature related animation data");
RNA_def_property_ui_icon(prop, ICON_ARMATURE_DATA, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_nodes", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NONTREE);
- RNA_def_property_ui_text(prop, "Display Node", "Include visualization of Node related Animation data");
+ RNA_def_property_ui_text(prop, "Display Node", "Include visualization of node related animation data");
RNA_def_property_ui_icon(prop, ICON_NODETREE, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_speakers", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "filterflag", ADS_FILTER_NOSPK);
- RNA_def_property_ui_text(prop, "Display Speaker", "Include visualization of Speaker related Animation data");
+ RNA_def_property_ui_text(prop, "Display Speaker", "Include visualization of speaker related animation data");
RNA_def_property_ui_icon(prop, ICON_SPEAKER, 0);
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
}
@@ -467,17 +479,17 @@ static void rna_def_action_group(BlenderRNA *brna)
prop = RNA_def_property(srna, "select", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", AGRP_SELECTED);
- RNA_def_property_ui_text(prop, "Select", "Action Group is selected");
+ RNA_def_property_ui_text(prop, "Select", "Action group is selected");
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_SELECTED, NULL);
prop = RNA_def_property(srna, "lock", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", AGRP_PROTECTED);
- RNA_def_property_ui_text(prop, "Lock", "Action Group is locked");
+ RNA_def_property_ui_text(prop, "Lock", "Action group is locked");
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
prop = RNA_def_property(srna, "show_expanded", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", AGRP_EXPANDED);
- RNA_def_property_ui_text(prop, "Expanded", "Action Group is expanded");
+ RNA_def_property_ui_text(prop, "Expanded", "Action group is expanded");
RNA_def_property_update(prop, NC_ANIMATION | ND_ANIMCHAN | NA_EDITED, NULL);
/* color set */
@@ -510,7 +522,8 @@ static void rna_def_action_groups(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove action group");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "action_group", "ActionGroup", "", "Action group to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
static void rna_def_action_fcurves(BlenderRNA *brna, PropertyRNA *cprop)
@@ -541,7 +554,8 @@ static void rna_def_action_fcurves(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove action group");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "fcurve", "FCurve", "", "F-Curve to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
static void rna_def_action_pose_markers(BlenderRNA *brna, PropertyRNA *cprop)
@@ -569,14 +583,15 @@ static void rna_def_action_pose_markers(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove a timeline marker");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "marker", "TimelineMarker", "", "Timeline marker to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
prop = RNA_def_property(srna, "active", PROP_POINTER, PROP_NONE);
RNA_def_property_struct_type(prop, "TimelineMarker");
RNA_def_property_flag(prop, PROP_EDITABLE);
RNA_def_property_pointer_funcs(prop, "rna_Action_active_pose_marker_get",
"rna_Action_active_pose_marker_set", NULL, NULL);
- RNA_def_property_ui_text(prop, "Active Pose Marker", "Active pose marker for this Action");
+ RNA_def_property_ui_text(prop, "Active Pose Marker", "Active pose marker for this action");
prop = RNA_def_property(srna, "active_index", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "active_marker");
@@ -599,7 +614,7 @@ static void rna_def_action(BlenderRNA *brna)
prop = RNA_def_property(srna, "fcurves", PROP_COLLECTION, PROP_NONE);
RNA_def_property_collection_sdna(prop, NULL, "curves", NULL);
RNA_def_property_struct_type(prop, "FCurve");
- RNA_def_property_ui_text(prop, "F-Curves", "The individual F-Curves that make up the Action");
+ RNA_def_property_ui_text(prop, "F-Curves", "The individual F-Curves that make up the action");
rna_def_action_fcurves(brna, prop);
prop = RNA_def_property(srna, "groups", PROP_COLLECTION, PROP_NONE);
@@ -611,7 +626,7 @@ static void rna_def_action(BlenderRNA *brna)
prop = RNA_def_property(srna, "pose_markers", PROP_COLLECTION, PROP_NONE);
RNA_def_property_collection_sdna(prop, NULL, "markers", NULL);
RNA_def_property_struct_type(prop, "TimelineMarker");
- RNA_def_property_ui_text(prop, "Pose Markers", "Markers specific to this Action, for labeling poses");
+ RNA_def_property_ui_text(prop, "Pose Markers", "Markers specific to this action, for labeling poses");
rna_def_action_pose_markers(brna, prop);
/* properties */
@@ -626,8 +641,8 @@ static void rna_def_action(BlenderRNA *brna)
RNA_def_property_enum_sdna(prop, NULL, "idroot");
RNA_def_property_enum_items(prop, id_type_items);
RNA_def_property_ui_text(prop, "ID Root Type",
- "Type of ID-block that action can be used on - "
- "DO NOT CHANGE UNLESS YOU KNOW WHAT YOU'RE DOING");
+ "Type of ID block that action can be used on - "
+ "DO NOT CHANGE UNLESS YOU KNOW WHAT YOU ARE DOING");
/* API calls */
RNA_api_action(srna);
diff --git a/source/blender/makesrna/intern/rna_action_api.c b/source/blender/makesrna/intern/rna_action_api.c
index 7e95aaab31b..fe429d8698b 100644
--- a/source/blender/makesrna/intern/rna_action_api.c
+++ b/source/blender/makesrna/intern/rna_action_api.c
@@ -34,10 +34,14 @@
#include <string.h>
#include <time.h>
+#include "BLI_utildefines.h"
+
#include "RNA_define.h"
#include "DNA_action_types.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include "BKE_action.h"
@@ -47,7 +51,7 @@
#else
-void RNA_api_action(StructRNA *srna)
+void RNA_api_action(StructRNA *UNUSED(srna))
{
}
diff --git a/source/blender/makesrna/intern/rna_actuator.c b/source/blender/makesrna/intern/rna_actuator.c
index bb714043002..b1fdfccd0be 100644
--- a/source/blender/makesrna/intern/rna_actuator.c
+++ b/source/blender/makesrna/intern/rna_actuator.c
@@ -29,6 +29,7 @@
#include "RNA_define.h"
#include "RNA_access.h"
+#include "RNA_enum_types.h"
#include "rna_internal.h"
#include "DNA_constraint_types.h"
@@ -40,6 +41,8 @@
#include "BLI_utildefines.h"
+#include "BLF_translation.h"
+
/* Always keep in alphabetical order */
EnumPropertyItem actuator_type_items[] = {
{ACT_ACTION, "ACTION", 0, "Action", ""},
@@ -110,7 +113,7 @@ static StructRNA *rna_Actuator_refine(struct PointerRNA *ptr)
}
}
-void rna_Actuator_name_set(PointerRNA *ptr, const char *value)
+static void rna_Actuator_name_set(PointerRNA *ptr, const char *value)
{
bActuator *act = (bActuator *)ptr->data;
@@ -530,7 +533,7 @@ static void rna_Actuator_action_action_set(PointerRNA *ptr, PointerRNA value)
#else
-void rna_def_actuator(BlenderRNA *brna)
+static void rna_def_actuator(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
@@ -970,11 +973,13 @@ static void rna_def_sound_actuator(BlenderRNA *brna)
RNA_def_property_ui_range(prop, 0.0, 1.0, 1, 2);
RNA_def_property_range(prop, 0.0, 2.0);
RNA_def_property_ui_text(prop, "Volume", "Initial volume of the sound");
+ RNA_def_property_translation_context(prop, BLF_I18NCONTEXT_AUDIO);
RNA_def_property_update(prop, NC_LOGIC, NULL);
prop = RNA_def_property(srna, "pitch", PROP_FLOAT, PROP_NONE);
RNA_def_property_ui_range(prop, -12.0, 12.0, 1, 2);
RNA_def_property_ui_text(prop, "Pitch", "Pitch of the sound");
+ RNA_def_property_translation_context(prop, BLF_I18NCONTEXT_AUDIO);
RNA_def_property_update(prop, NC_LOGIC, NULL);
/* floats - 3D Parameters */
diff --git a/source/blender/makesrna/intern/rna_actuator_api.c b/source/blender/makesrna/intern/rna_actuator_api.c
index 68b2c4f8b52..4a34961964d 100644
--- a/source/blender/makesrna/intern/rna_actuator_api.c
+++ b/source/blender/makesrna/intern/rna_actuator_api.c
@@ -35,6 +35,8 @@
#include "WM_types.h"
#include "RNA_define.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include "BKE_sca.h"
diff --git a/source/blender/makesrna/intern/rna_animation.c b/source/blender/makesrna/intern/rna_animation.c
index 69f785c32de..ce884fa4ecc 100644
--- a/source/blender/makesrna/intern/rna_animation.c
+++ b/source/blender/makesrna/intern/rna_animation.c
@@ -369,27 +369,30 @@ static KS_Path *rna_KeyingSet_paths_add(KeyingSet *keyingset, ReportList *report
keyingset->active_path = BLI_countlist(&keyingset->paths);
}
else {
- BKE_report(reports, RPT_ERROR, "Keying Set Path could not be added");
+ BKE_report(reports, RPT_ERROR, "Keying set path could not be added");
}
/* return added path */
return ksp;
}
-static void rna_KeyingSet_paths_remove(KeyingSet *keyingset, ReportList *reports, KS_Path *ksp)
+static void rna_KeyingSet_paths_remove(KeyingSet *keyingset, ReportList *reports, PointerRNA *ksp_ptr)
{
+ KS_Path *ksp = ksp_ptr->data;
+
/* if data is valid, call the API function for this */
- if (keyingset && ksp) {
- /* remove the active path from the KeyingSet */
- BKE_keyingset_free_path(keyingset, ksp);
-
- /* the active path number will most likely have changed */
- /* TODO: we should get more fancy and actually check if it was removed, but this will do for now */
- keyingset->active_path = 0;
- }
- else {
- BKE_report(reports, RPT_ERROR, "Keying Set Path could not be removed");
+ if ((keyingset && ksp) == FALSE) {
+ BKE_report(reports, RPT_ERROR, "Keying set path could not be removed");
+ return;
}
+
+ /* remove the active path from the KeyingSet */
+ BKE_keyingset_free_path(keyingset, ksp);
+ RNA_POINTER_INVALIDATE(ksp_ptr);
+
+ /* the active path number will most likely have changed */
+ /* TODO: we should get more fancy and actually check if it was removed, but this will do for now */
+ keyingset->active_path = 0;
}
static void rna_KeyingSet_paths_clear(KeyingSet *keyingset, ReportList *reports)
@@ -408,7 +411,7 @@ static void rna_KeyingSet_paths_clear(KeyingSet *keyingset, ReportList *reports)
keyingset->active_path = 0;
}
else {
- BKE_report(reports, RPT_ERROR, "Keying Set Paths could not be removed");
+ BKE_report(reports, RPT_ERROR, "Keying set paths could not be removed");
}
}
@@ -422,9 +425,17 @@ static NlaTrack *rna_NlaTrack_new(AnimData *adt, bContext *C, NlaTrack *track)
return new_track;
}
-static void rna_NlaTrack_remove(AnimData *adt, bContext *C, NlaTrack *track)
+static void rna_NlaTrack_remove(AnimData *adt, bContext *C, ReportList *reports, PointerRNA *track_ptr)
{
+ NlaTrack *track = track_ptr->data;
+
+ if (BLI_findindex(&adt->nla_tracks, track) == -1) {
+ BKE_reportf(reports, RPT_ERROR, "NlaTrack '%s' can't be removed", track->name);
+ return;
+ }
+
free_nlatrack(&adt->nla_tracks, track);
+ RNA_POINTER_INVALIDATE(track_ptr);
WM_event_add_notifier(C, NC_ANIMATION | ND_NLA | NA_REMOVED, NULL);
}
@@ -448,7 +459,7 @@ static FCurve *rna_Driver_from_existing(AnimData *adt, bContext *C, FCurve *src_
{
/* verify that we've got a driver to duplicate */
if (ELEM(NULL, src_driver, src_driver->driver)) {
- BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "No valid driver data to create copy of");
+ BKE_report(CTX_wm_reports(C), RPT_ERROR, "No valid driver data to create copy of");
return NULL;
}
else {
@@ -678,7 +689,8 @@ static void rna_def_keyingset_paths(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
/* path to remove */
parm = RNA_def_pointer(func, "path", "KeyingSetPath", "Path", "");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
/* Remove All Paths */
@@ -783,10 +795,11 @@ static void rna_api_animdata_nla_tracks(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_return(func, parm);
func = RNA_def_function(srna, "remove", "rna_NlaTrack_remove");
- RNA_def_function_flag(func, FUNC_USE_CONTEXT);
+ RNA_def_function_flag(func, FUNC_USE_REPORTS | FUNC_USE_CONTEXT);
RNA_def_function_ui_description(func, "Remove a NLA Track");
parm = RNA_def_pointer(func, "track", "NlaTrack", "", "NLA Track to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
prop = RNA_def_property(srna, "active", PROP_POINTER, PROP_NONE);
RNA_def_property_struct_type(prop, "NlaTrack");
@@ -829,7 +842,7 @@ void rna_def_animdata_common(StructRNA *srna)
RNA_def_property_ui_text(prop, "Animation Data", "Animation data for this datablock");
}
-void rna_def_animdata(BlenderRNA *brna)
+static void rna_def_animdata(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
diff --git a/source/blender/makesrna/intern/rna_animation_api.c b/source/blender/makesrna/intern/rna_animation_api.c
index 32472c8d415..492659fdc2e 100644
--- a/source/blender/makesrna/intern/rna_animation_api.c
+++ b/source/blender/makesrna/intern/rna_animation_api.c
@@ -39,6 +39,7 @@
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
+#include "rna_internal.h" /* own include */
#ifdef RNA_RUNTIME
@@ -55,11 +56,11 @@ static void rna_KeyingSet_context_refresh(KeyingSet *ks, bContext *C, ReportList
if (success != 0) {
switch (success) {
case MODIFYKEY_INVALID_CONTEXT:
- BKE_report(reports, RPT_ERROR, "Invalid context for Keying Set");
+ BKE_report(reports, RPT_ERROR, "Invalid context for keying set");
break;
case MODIFYKEY_MISSING_TYPEINFO:
- BKE_report(reports, RPT_ERROR, "Incomplete built-in Keying Set. Appears to be missing type info");
+ BKE_report(reports, RPT_ERROR, "Incomplete built-in keying set, appears to be missing type info");
break;
}
}
diff --git a/source/blender/makesrna/intern/rna_armature.c b/source/blender/makesrna/intern/rna_armature.c
index be70405d165..4c566d71981 100644
--- a/source/blender/makesrna/intern/rna_armature.c
+++ b/source/blender/makesrna/intern/rna_armature.c
@@ -29,6 +29,7 @@
#include "BLI_math.h"
+#include "RNA_access.h"
#include "RNA_define.h"
#include "rna_internal.h"
@@ -100,28 +101,30 @@ static void rna_Armature_act_edit_bone_set(PointerRNA *ptr, PointerRNA value)
}
}
-EditBone *rna_Armature_edit_bone_new(bArmature *arm, ReportList *reports, const char *name)
+static EditBone *rna_Armature_edit_bone_new(bArmature *arm, ReportList *reports, const char *name)
{
if (arm->edbo == NULL) {
- BKE_reportf(reports, RPT_ERROR, "Armature '%s' not in editmode, cant add an editbone", arm->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Armature '%s' not in edit mode, cannot add an editbone", arm->id.name + 2);
return NULL;
}
return ED_armature_edit_bone_add(arm, name);
}
-void rna_Armature_edit_bone_remove(bArmature *arm, ReportList *reports, EditBone *ebone)
+static void rna_Armature_edit_bone_remove(bArmature *arm, ReportList *reports, PointerRNA *ebone_ptr)
{
+ EditBone *ebone = ebone_ptr->data;
if (arm->edbo == NULL) {
- BKE_reportf(reports, RPT_ERROR, "Armature '%s' not in editmode, cant remove an editbone", arm->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Armature '%s' not in edit mode, cannot remove an editbone", arm->id.name + 2);
return;
}
if (BLI_findindex(arm->edbo, ebone) == -1) {
- BKE_reportf(reports, RPT_ERROR, "Armature '%s' doesn't contain bone '%s'", arm->id.name + 2, ebone->name);
+ BKE_reportf(reports, RPT_ERROR, "Armature '%s' does not contain bone '%s'", arm->id.name + 2, ebone->name);
return;
}
ED_armature_edit_bone_remove(arm, ebone);
+ RNA_POINTER_INVALIDATE(ebone_ptr);
}
static void rna_Armature_update_layers(Main *bmain, Scene *UNUSED(scene), PointerRNA *ptr)
@@ -271,7 +274,7 @@ static void rna_Armature_layer_set(PointerRNA *ptr, const int *values)
}
}
-/* XXX depreceated.... old armature only animviz */
+/* XXX deprecated.... old armature only animviz */
static void rna_Armature_ghost_start_frame_set(PointerRNA *ptr, int value)
{
bArmature *data = (bArmature *)ptr->data;
@@ -293,7 +296,7 @@ static void rna_Armature_ghost_end_frame_set(PointerRNA *ptr, int value)
data->ghostsf = MAX2(data->ghostef, 1);
}
}
-/* XXX depreceated... old armature only animviz */
+/* XXX deprecated... old armature only animviz */
static void rna_EditBone_name_set(PointerRNA *ptr, const char *value)
{
@@ -564,7 +567,7 @@ static void rna_def_bone_common(StructRNA *srna, int editbone)
if (editbone) RNA_def_property_update(prop, 0, "rna_Armature_editbone_transform_update");
else RNA_def_property_update(prop, 0, "rna_Armature_update_data");
RNA_def_property_float_sdna(prop, NULL, "rad_head");
- /* XXX range is 0 to lim, where lim= 10000.0f*MAX2(1.0, view3d->grid); */
+ /* XXX range is 0 to lim, where lim = 10000.0f * MAX2(1.0, view3d->grid); */
/*RNA_def_property_range(prop, 0, 1000); */
RNA_def_property_ui_range(prop, 0.01, 100, 0.1, 3);
RNA_def_property_ui_text(prop, "Envelope Head Radius", "Radius of head of bone (for Envelope deform only)");
@@ -573,7 +576,7 @@ static void rna_def_bone_common(StructRNA *srna, int editbone)
if (editbone) RNA_def_property_update(prop, 0, "rna_Armature_editbone_transform_update");
else RNA_def_property_update(prop, 0, "rna_Armature_update_data");
RNA_def_property_float_sdna(prop, NULL, "rad_tail");
- /* XXX range is 0 to lim, where lim= 10000.0f*MAX2(1.0, view3d->grid); */
+ /* XXX range is 0 to lim, where lim = 10000.0f * MAX2(1.0, view3d->grid); */
/*RNA_def_property_range(prop, 0, 1000); */
RNA_def_property_ui_range(prop, 0.01, 100, 0.1, 3);
RNA_def_property_ui_text(prop, "Envelope Tail Radius", "Radius of tail of bone (for Envelope deform only)");
@@ -865,7 +868,8 @@ static void rna_def_armature_edit_bones(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove an existing bone from the armature");
/* target to remove*/
parm = RNA_def_pointer(func, "bone", "EditBone", "", "EditBone to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
static void rna_def_armature(BlenderRNA *brna)
@@ -945,14 +949,14 @@ static void rna_def_armature(BlenderRNA *brna)
RNA_def_property_update(prop, 0, "rna_Armature_redraw_data");
RNA_def_property_flag(prop, PROP_LIB_EXCEPTION);
-/* XXX depreceated ....... old animviz for armatures only */
+/* XXX deprecated ....... old animviz for armatures only */
prop = RNA_def_property(srna, "ghost_type", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "ghosttype");
RNA_def_property_enum_items(prop, prop_ghost_type_items);
RNA_def_property_ui_text(prop, "Ghost Type", "Method of Onion-skinning for active Action");
RNA_def_property_update(prop, 0, "rna_Armature_redraw_data");
RNA_def_property_flag(prop, PROP_LIB_EXCEPTION);
-/* XXX depreceated ....... old animviz for armatures only */
+/* XXX deprecated ....... old animviz for armatures only */
/* Boolean values */
/* layer */
@@ -1013,16 +1017,16 @@ static void rna_def_armature(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Draw Bone Group Colors", "Draw bone group colors");
RNA_def_property_update(prop, 0, "rna_Armature_redraw_data");
-/* XXX depreceated ....... old animviz for armatures only */
+/* XXX deprecated ....... old animviz for armatures only */
prop = RNA_def_property(srna, "show_only_ghost_selected", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", ARM_GHOST_ONLYSEL);
RNA_def_property_ui_text(prop, "Draw Ghosts on Selected Bones Only", "");
RNA_def_property_update(prop, 0, "rna_Armature_redraw_data");
RNA_def_property_flag(prop, PROP_LIB_EXCEPTION);
-/* XXX depreceated ....... old animviz for armatures only */
+/* XXX deprecated ....... old animviz for armatures only */
/* Number fields */
-/* XXX depreceated ....... old animviz for armatures only */
+/* XXX deprecated ....... old animviz for armatures only */
/* ghost/onionskining settings */
prop = RNA_def_property(srna, "ghost_step", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "ghostep");
@@ -1058,7 +1062,7 @@ static void rna_def_armature(BlenderRNA *brna)
"(not for 'Around Current Frame' Onion-skinning method)");
RNA_def_property_update(prop, 0, "rna_Armature_redraw_data");
RNA_def_property_flag(prop, PROP_LIB_EXCEPTION);
-/* XXX depreceated ....... old animviz for armatures only */
+/* XXX deprecated ....... old animviz for armatures only */
}
void RNA_def_armature(BlenderRNA *brna)
diff --git a/source/blender/makesrna/intern/rna_armature_api.c b/source/blender/makesrna/intern/rna_armature_api.c
index 29dc23b7bef..96c5350e5b7 100644
--- a/source/blender/makesrna/intern/rna_armature_api.c
+++ b/source/blender/makesrna/intern/rna_armature_api.c
@@ -36,18 +36,20 @@
#include "RNA_define.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include <stddef.h>
#include "BKE_armature.h"
-void rna_EditBone_align_roll(EditBone *ebo, float no[3])
+static void rna_EditBone_align_roll(EditBone *ebo, float no[3])
{
ebo->roll = ED_rollBoneToVector(ebo, no, FALSE);
}
-float rna_Bone_do_envelope(Bone *bone, float *vec)
+static float rna_Bone_do_envelope(Bone *bone, float *vec)
{
float scale = (bone->flag & BONE_MULT_VG_ENV) == BONE_MULT_VG_ENV ? bone->weight : 1.0f;
return distfactor_to_bone(vec, bone->arm_head, bone->arm_tail, bone->rad_head * scale,
diff --git a/source/blender/makesrna/intern/rna_boid.c b/source/blender/makesrna/intern/rna_boid.c
index 2a6ea2994fa..8e45da50e9b 100644
--- a/source/blender/makesrna/intern/rna_boid.c
+++ b/source/blender/makesrna/intern/rna_boid.c
@@ -436,7 +436,7 @@ static void rna_def_boidrule(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "On Land", "Use rule when boid is on land");
RNA_def_property_update(prop, 0, "rna_Boids_reset");
- /*prop= RNA_def_property(srna, "show_expanded", PROP_BOOLEAN, PROP_NONE); */
+ /*prop = RNA_def_property(srna, "show_expanded", PROP_BOOLEAN, PROP_NONE); */
/*RNA_def_property_boolean_sdna(prop, NULL, "mode", eModifierMode_Expanded); */
/*RNA_def_property_ui_text(prop, "Expanded", "Set modifier expanded in the user interface"); */
diff --git a/source/blender/makesrna/intern/rna_camera.c b/source/blender/makesrna/intern/rna_camera.c
index ad926d6a08e..b72bba0422a 100644
--- a/source/blender/makesrna/intern/rna_camera.c
+++ b/source/blender/makesrna/intern/rna_camera.c
@@ -258,7 +258,7 @@ void RNA_def_camera(BlenderRNA *brna)
prop = RNA_def_property(srna, "show_title_safe", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", CAM_SHOWTITLESAFE);
- RNA_def_property_ui_text(prop, "Show Title Safe", "Show indicators for the title safe zone in Camera view");
+ RNA_def_property_ui_text(prop, "Show Safe Areas", "Show TV title safe and action safe zones in Camera view");
RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, NULL);
prop = RNA_def_property(srna, "show_name", PROP_BOOLEAN, PROP_NONE);
diff --git a/source/blender/makesrna/intern/rna_camera_api.c b/source/blender/makesrna/intern/rna_camera_api.c
index 75941fa224f..bf916806e40 100644
--- a/source/blender/makesrna/intern/rna_camera_api.c
+++ b/source/blender/makesrna/intern/rna_camera_api.c
@@ -31,6 +31,8 @@
#include "RNA_define.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include "DNA_scene_types.h"
@@ -39,8 +41,8 @@
#include "BKE_context.h"
#include "BKE_object.h"
-void rna_camera_view_frame(struct Camera *camera, struct Scene *scene,
- float vec1_r[3], float vec2_r[3], float vec3_r[3], float vec4_r[3])
+static void rna_camera_view_frame(struct Camera *camera, struct Scene *scene,
+ float vec1_r[3], float vec2_r[3], float vec3_r[3], float vec4_r[3])
{
float vec[4][3];
diff --git a/source/blender/makesrna/intern/rna_cloth.c b/source/blender/makesrna/intern/rna_cloth.c
index 5f1ce4f2773..b9e86e116a2 100644
--- a/source/blender/makesrna/intern/rna_cloth.c
+++ b/source/blender/makesrna/intern/rna_cloth.c
@@ -419,41 +419,41 @@ static void rna_def_cloth_sim_settings(BlenderRNA *brna)
/* unused still */
#if 0
- prop= RNA_def_property(srna, "shear_stiffness", PROP_FLOAT, PROP_NONE);
+ prop = RNA_def_property(srna, "shear_stiffness", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "shear");
RNA_def_property_range(prop, 0.0f, 1000.0f);
RNA_def_property_ui_text(prop, "Shear Stiffness", "Shear spring stiffness");
#endif
/* unused still */
#if 0
- prop= RNA_def_property(srna, "shear_stiffness_max", PROP_FLOAT, PROP_NONE);
+ prop = RNA_def_property(srna, "shear_stiffness_max", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "max_shear");
RNA_def_property_range(prop, 0.0f, upperLimitf);
RNA_def_property_ui_text(prop, "Shear Stiffness Maximum", "Maximum shear scaling value");
#endif
/* unused still */
#if 0
- prop= RNA_def_property(srna, "effector_force_scale", PROP_FLOAT, PROP_NONE);
+ prop = RNA_def_property(srna, "effector_force_scale", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "eff_force_scale");
RNA_def_property_range(prop, 0.0f, 100.0f);
RNA_def_property_ui_text(prop, "Effector Force Scale", "");
#endif
/* unused still */
#if 0
- prop= RNA_def_property(srna, "effector_wind_scale", PROP_FLOAT, PROP_NONE);
+ prop = RNA_def_property(srna, "effector_wind_scale", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "eff_wind_scale");
RNA_def_property_range(prop, 0.0f, 100.0f);
RNA_def_property_ui_text(prop, "Effector Wind Scale", "");
#endif
/* unused still */
#if 0
- prop= RNA_def_property(srna, "tearing", PROP_BOOLEAN, PROP_NONE);
+ prop = RNA_def_property(srna, "tearing", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flags", CLOTH_SIMSETTINGS_FLAG_TEARING);
RNA_def_property_ui_text(prop, "Tearing", "");
#endif
/* unused still */
#if 0
- prop= RNA_def_property(srna, "max_spring_extensions", PROP_INT, PROP_NONE);
+ prop = RNA_def_property(srna, "max_spring_extensions", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "maxspringlen");
RNA_def_property_range(prop, 1.0, 1000.0);
RNA_def_property_ui_text(prop, "Maximum Spring Extension", "Maximum extension before spring gets cut");
diff --git a/source/blender/makesrna/intern/rna_color.c b/source/blender/makesrna/intern/rna_color.c
index 0edcad59577..c93d2ef15cf 100644
--- a/source/blender/makesrna/intern/rna_color.c
+++ b/source/blender/makesrna/intern/rna_color.c
@@ -314,7 +314,7 @@ static void rna_ColorRamp_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *
}
}
-void rna_ColorRamp_eval(struct ColorBand *coba, float position, float color[4])
+static void rna_ColorRamp_eval(struct ColorBand *coba, float position, float color[4])
{
do_colorband(coba, position, color);
}
@@ -329,12 +329,27 @@ static CBData *rna_ColorRampElement_new(struct ColorBand *coba, ReportList *repo
return element;
}
-static void rna_ColorRampElement_remove(struct ColorBand *coba, ReportList *reports, CBData *element)
+static void rna_ColorRampElement_remove(struct ColorBand *coba, ReportList *reports, PointerRNA *element_ptr)
{
+ CBData *element = element_ptr->data;
int index = (int)(element - coba->data);
- if (colorband_element_remove(coba, index) == 0)
+ if (colorband_element_remove(coba, index) == FALSE) {
BKE_report(reports, RPT_ERROR, "Element not found in element collection or last element");
+ return;
+ }
+
+ RNA_POINTER_INVALIDATE(element_ptr);
+}
+
+void rna_CurveMap_remove_point(CurveMap *cuma, ReportList *reports, PointerRNA *point_ptr)
+{
+ CurveMapPoint *point = point_ptr->data;
+ if (curvemap_remove_point(cuma, point) == FALSE) {
+ BKE_report(reports, RPT_ERROR, "Unable to remove curve point");
+ return;
+ }
+ RNA_POINTER_INVALIDATE(point_ptr);
}
static void rna_Scopes_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
@@ -377,6 +392,9 @@ static void rna_ColorManagedDisplaySettings_display_device_update(Main *UNUSED(b
{
ID *id = ptr->id.data;
+ if (!id)
+ return;
+
if (GS(id->name) == ID_SCE) {
Scene *scene = (Scene *) id;
@@ -471,14 +489,20 @@ static void rna_ColorManagedColorspaceSettings_reload_update(Main *UNUSED(bmain)
if (GS(id->name) == ID_IM) {
Image *ima = (Image *) id;
- BKE_image_signal(ima, NULL, IMA_SIGNAL_RELOAD);
+ DAG_id_tag_update(&ima->id, 0);
+
+ BKE_image_signal(ima, NULL, IMA_SIGNAL_COLORMANAGE);
+
WM_main_add_notifier(NC_IMAGE | ND_DISPLAY, &ima->id);
+ WM_main_add_notifier(NC_IMAGE | NA_EDITED, &ima->id);
}
else if (GS(id->name) == ID_MC) {
MovieClip *clip = (MovieClip *) id;
BKE_movieclip_reload(clip);
+
WM_main_add_notifier(NC_MOVIECLIP | ND_DISPLAY, &clip->id);
+ WM_main_add_notifier(NC_MOVIECLIP | NA_EDITED, &clip->id);
}
}
@@ -486,13 +510,16 @@ static void rna_ColorManagement_update(Main *UNUSED(bmain), Scene *UNUSED(scene)
{
ID *id = ptr->id.data;
+ if (!id)
+ return;
+
if (GS(id->name) == ID_SCE) {
WM_main_add_notifier(NC_SCENE | ND_SEQUENCER, NULL);
}
}
/* this function only exists because #curvemap_evaluateF uses a 'const' qualifier */
-float rna_CurveMap_evaluateF(struct CurveMap *cuma, float value)
+static float rna_CurveMap_evaluateF(struct CurveMap *cuma, float value)
{
return curvemap_evaluateF(cuma, value);
}
@@ -547,10 +574,12 @@ static void rna_def_curvemap_points_api(BlenderRNA *brna, PropertyRNA *cprop)
parm = RNA_def_pointer(func, "point", "CurveMapPoint", "", "New point");
RNA_def_function_return(func, parm);
- func = RNA_def_function(srna, "remove", "curvemap_remove_point");
+ func = RNA_def_function(srna, "remove", "rna_CurveMap_remove_point");
+ RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Delete point from CurveMap");
parm = RNA_def_pointer(func, "point", "CurveMapPoint", "", "PointElement to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
static void rna_def_curvemap(BlenderRNA *brna)
@@ -699,7 +728,8 @@ static void rna_def_color_ramp_element_api(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Delete element from ColorRamp");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "element", "ColorRampElement", "", "Element to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
static void rna_def_color_ramp(BlenderRNA *brna)
@@ -860,7 +890,7 @@ static void rna_def_colormanage(BlenderRNA *brna)
srna = RNA_def_struct(brna, "ColorManagedDisplaySettings", NULL);
RNA_def_struct_ui_text(srna, "ColorManagedDisplaySettings", "Color management specific to display device");
- prop= RNA_def_property(srna, "display_device", PROP_ENUM, PROP_NONE);
+ prop = RNA_def_property(srna, "display_device", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_items(prop, display_device_items);
RNA_def_property_enum_funcs(prop, "rna_ColorManagedDisplaySettings_display_device_get",
"rna_ColorManagedDisplaySettings_display_device_set",
@@ -872,7 +902,7 @@ static void rna_def_colormanage(BlenderRNA *brna)
srna = RNA_def_struct(brna, "ColorManagedViewSettings", NULL);
RNA_def_struct_ui_text(srna, "ColorManagedViewSettings", "Color management settings used for displaying images on the display");
- prop= RNA_def_property(srna, "view_transform", PROP_ENUM, PROP_NONE);
+ prop = RNA_def_property(srna, "view_transform", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_items(prop, view_transform_items);
RNA_def_property_enum_funcs(prop, "rna_ColorManagedViewSettings_view_transform_get",
"rna_ColorManagedViewSettings_view_transform_set",
@@ -909,7 +939,7 @@ static void rna_def_colormanage(BlenderRNA *brna)
srna = RNA_def_struct(brna, "ColorManagedColorspaceSettings", NULL);
RNA_def_struct_ui_text(srna, "ColorManagedColorspaceSettings", "Input color space settings");
- prop= RNA_def_property(srna, "name", PROP_ENUM, PROP_NONE);
+ prop = RNA_def_property(srna, "name", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_items(prop, color_space_items);
RNA_def_property_enum_funcs(prop, "rna_ColorManagedColorspaceSettings_colorspace_get",
"rna_ColorManagedColorspaceSettings_colorspace_set",
diff --git a/source/blender/makesrna/intern/rna_constraint.c b/source/blender/makesrna/intern/rna_constraint.c
index 770bdb68e38..7b6b629ca82 100644
--- a/source/blender/makesrna/intern/rna_constraint.c
+++ b/source/blender/makesrna/intern/rna_constraint.c
@@ -703,11 +703,6 @@ static void rna_def_constraint_kinematic(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Lock Z Rot", "Constraint rotation along Z axis");
RNA_def_property_update(prop, NC_OBJECT | ND_POSE, "rna_Constraint_dependency_update");
- prop = RNA_def_property(srna, "use_target", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", CONSTRAINT_IK_AUTO);
- RNA_def_property_ui_text(prop, "Target", "Disable for targetless IK");
- RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_dependency_update");
-
prop = RNA_def_property(srna, "use_stretch", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", CONSTRAINT_IK_STRETCH);
RNA_def_property_ui_text(prop, "Stretch", "Enable IK Stretching");
@@ -1243,7 +1238,7 @@ static void rna_def_constraint_follow_path(BlenderRNA *brna)
prop = RNA_def_property(srna, "offset_factor", PROP_FLOAT, PROP_FACTOR);
RNA_def_property_float_sdna(prop, NULL, "offset_fac");
RNA_def_property_range(prop, 0.0f, 1.0f);
- RNA_def_property_ui_text(prop, "Offset Factor", "Percentage value defining target position along length of bone");
+ RNA_def_property_ui_text(prop, "Offset Factor", "Percentage value defining target position along length of curve");
RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update");
prop = RNA_def_property(srna, "forward_axis", PROP_ENUM, PROP_NONE);
@@ -2422,7 +2417,7 @@ void RNA_def_constraint(BlenderRNA *brna)
RNA_def_property_float_sdna(prop, NULL, "rot_error");
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_ui_text(prop, "Rot error",
- "Amount of residual error in radiant for constraints that work on orientation");
+ "Amount of residual error in radians for constraints that work on orientation");
/* pointers */
rna_def_constrainttarget(brna);
diff --git a/source/blender/makesrna/intern/rna_controller.c b/source/blender/makesrna/intern/rna_controller.c
index 44c8a2b412b..c59e376da82 100644
--- a/source/blender/makesrna/intern/rna_controller.c
+++ b/source/blender/makesrna/intern/rna_controller.c
@@ -77,7 +77,7 @@ static StructRNA *rna_Controller_refine(struct PointerRNA *ptr)
}
}
-void rna_Constroller_name_set(PointerRNA *ptr, const char *value)
+static void rna_Constroller_name_set(PointerRNA *ptr, const char *value)
{
bController *cont = (bController *)ptr->data;
@@ -240,7 +240,7 @@ void RNA_def_controller(BlenderRNA *brna)
/* State */
/* array of OB_MAX_STATES */
- /*prop= RNA_def_property(srna, "states", PROP_BOOLEAN, PROP_LAYER_MEMBER); */
+ /*prop = RNA_def_property(srna, "states", PROP_BOOLEAN, PROP_LAYER_MEMBER); */
/*RNA_def_property_array(prop, OB_MAX_STATES); */
/*RNA_def_property_clear_flag(prop, PROP_EDITABLE); */
/*RNA_def_property_ui_text(prop, "", "Set Controller state index (1 to 30)"); */
diff --git a/source/blender/makesrna/intern/rna_controller_api.c b/source/blender/makesrna/intern/rna_controller_api.c
index 6fe90e1721b..639d6a330a5 100644
--- a/source/blender/makesrna/intern/rna_controller_api.c
+++ b/source/blender/makesrna/intern/rna_controller_api.c
@@ -35,6 +35,8 @@
#include "WM_types.h"
#include "RNA_define.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include "BKE_sca.h"
diff --git a/source/blender/makesrna/intern/rna_curve.c b/source/blender/makesrna/intern/rna_curve.c
index b2a2bab0f4b..35699c6ef3f 100644
--- a/source/blender/makesrna/intern/rna_curve.c
+++ b/source/blender/makesrna/intern/rna_curve.c
@@ -26,6 +26,7 @@
#include <stdlib.h>
+#include "RNA_access.h"
#include "RNA_define.h"
#include "rna_internal.h"
@@ -62,9 +63,9 @@ EnumPropertyItem keyframe_handle_type_items[] = {
};
EnumPropertyItem beztriple_interpolation_mode_items[] = {
- {BEZT_IPO_CONST, "CONSTANT", 0, "Constant", ""},
- {BEZT_IPO_LIN, "LINEAR", 0, "Linear", ""},
- {BEZT_IPO_BEZ, "BEZIER", 0, "Bezier", ""},
+ {BEZT_IPO_CONST, "CONSTANT", 0, "Constant", "No interpolation, value of A gets held until B is encountered"},
+ {BEZT_IPO_LIN, "LINEAR", 0, "Linear", "Straight-line interpolation between A and B (i.e. no ease in/out)"},
+ {BEZT_IPO_BEZ, "BEZIER", 0, "Bezier", "Smooth interpolation between A and B, with some control over curve shape"},
{0, NULL, 0, NULL, NULL}
};
@@ -432,20 +433,20 @@ static void rna_Curve_offset_set(PointerRNA *ptr, float value)
}
/* name functions that ignore the first two ID characters */
-void rna_Curve_body_get(PointerRNA *ptr, char *value)
+static void rna_Curve_body_get(PointerRNA *ptr, char *value)
{
Curve *cu = (Curve *)ptr->id.data;
BLI_strncpy(value, cu->str, cu->len + 1);
}
-int rna_Curve_body_length(PointerRNA *ptr)
+static int rna_Curve_body_length(PointerRNA *ptr)
{
Curve *cu = (Curve *)ptr->id.data;
return cu->len;
}
/* TODO - check UTF & python play nice */
-void rna_Curve_body_set(PointerRNA *ptr, const char *value)
+static void rna_Curve_body_set(PointerRNA *ptr, const char *value)
{
int len = strlen(value);
Curve *cu = (Curve *)ptr->id.data;
@@ -511,7 +512,7 @@ static void rna_Nurb_update_knot_v(Main *bmain, Scene *scene, PointerRNA *ptr)
static void rna_Curve_spline_points_add(ID *id, Nurb *nu, ReportList *reports, int number)
{
if (nu->type == CU_BEZIER) {
- BKE_report(reports, RPT_ERROR, "Bezier spline can't have points added");
+ BKE_report(reports, RPT_ERROR, "Bezier spline cannot have points added");
}
else if (number == 0) {
/* do nothing */
@@ -573,20 +574,18 @@ static Nurb *rna_Curve_spline_new(Curve *cu, int type)
return nu;
}
-static void rna_Curve_spline_remove(Curve *cu, ReportList *reports, Nurb *nu)
+static void rna_Curve_spline_remove(Curve *cu, ReportList *reports, PointerRNA *nu_ptr)
{
- int found = 0;
+ Nurb *nu = nu_ptr->data;
ListBase *nurbs = BKE_curve_nurbs_get(cu);
- found = BLI_remlink_safe(nurbs, nu);
-
- if (!found) {
- BKE_reportf(reports, RPT_ERROR, "Curve \"%s\" does not contain spline given", cu->id.name + 2);
+ if (BLI_remlink_safe(nurbs, nu) == FALSE) {
+ BKE_reportf(reports, RPT_ERROR, "Curve '%s' does not contain spline given", cu->id.name + 2);
return;
}
BKE_nurb_free(nu);
- /* invalidate pointer!, no can do */
+ RNA_POINTER_INVALIDATE(nu_ptr);
DAG_id_tag_update(&cu->id, OB_RECALC_DATA);
WM_main_add_notifier(NC_GEOM | ND_DATA, NULL);
@@ -721,7 +720,7 @@ static void rna_def_bpoint(BlenderRNA *brna)
RNA_def_property_update(prop, 0, "rna_Curve_update_data");
/* Number values */
- prop = RNA_def_property(srna, "tilt", PROP_FLOAT, PROP_NONE);
+ prop = RNA_def_property(srna, "tilt", PROP_FLOAT, PROP_ANGLE);
RNA_def_property_float_sdna(prop, NULL, "alfa");
/*RNA_def_property_range(prop, -FLT_MAX, FLT_MAX);*/
RNA_def_property_ui_text(prop, "Tilt", "Tilt in 3D View");
@@ -808,13 +807,14 @@ static void rna_def_beztriple(BlenderRNA *brna)
RNA_def_property_update(prop, 0, "rna_Curve_update_points");
/* Number values */
- prop = RNA_def_property(srna, "tilt", PROP_FLOAT, PROP_NONE);
+ prop = RNA_def_property(srna, "tilt", PROP_FLOAT, PROP_ANGLE);
RNA_def_property_float_sdna(prop, NULL, "alfa");
/*RNA_def_property_range(prop, -FLT_MAX, FLT_MAX);*/
RNA_def_property_ui_text(prop, "Tilt", "Tilt in 3D View");
RNA_def_property_update(prop, 0, "rna_Curve_update_data");
- prop = RNA_def_property(srna, "weight", PROP_FLOAT, PROP_NONE);
+ prop = RNA_def_property(srna, "weight_softbody", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "weight");
RNA_def_property_range(prop, 0.01f, 100.0f);
RNA_def_property_ui_text(prop, "Weight", "Softbody goal weight");
RNA_def_property_update(prop, 0, "rna_Curve_update_data");
@@ -1108,7 +1108,7 @@ static void rna_def_charinfo(BlenderRNA *brna)
/* probably there is no reason to expose this */
#if 0
- prop= RNA_def_property(srna, "wrap", PROP_BOOLEAN, PROP_NONE);
+ prop = RNA_def_property(srna, "wrap", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", CU_CHINFO_WRAP);
RNA_def_property_ui_text(prop, "Wrap", "");
RNA_def_property_update(prop, 0, "rna_Curve_update_data"); */
@@ -1163,14 +1163,15 @@ static void rna_def_curve_spline_points(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "add", "rna_Curve_spline_points_add");
RNA_def_function_ui_description(func, "Add a number of points to this spline");
RNA_def_function_flag(func, FUNC_USE_SELF_ID | FUNC_USE_REPORTS);
- RNA_def_int(func, "count", 1, 1, INT_MAX, "Number", "Number of points to add to the spline", 1, INT_MAX);
+ RNA_def_int(func, "count", 1, 0, INT_MAX, "Number", "Number of points to add to the spline", 0, INT_MAX);
#if 0
- func= RNA_def_function(srna, "remove", "rna_Curve_spline_remove");
+ func = RNA_def_function(srna, "remove", "rna_Curve_spline_remove");
RNA_def_function_ui_description(func, "Remove a spline from a curve");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
- parm= RNA_def_pointer(func, "spline", "Spline", "", "The spline to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ parm = RNA_def_pointer(func, "spline", "Spline", "", "The spline to remove");
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
#endif
}
@@ -1190,14 +1191,15 @@ static void rna_def_curve_spline_bezpoints(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "add", "rna_Curve_spline_bezpoints_add");
RNA_def_function_ui_description(func, "Add a number of points to this spline");
RNA_def_function_flag(func, FUNC_USE_SELF_ID | FUNC_USE_REPORTS);
- RNA_def_int(func, "count", 1, INT_MIN, INT_MAX, "Number", "Number of points to add to the spline", 0, INT_MAX);
+ RNA_def_int(func, "count", 1, 0, INT_MAX, "Number", "Number of points to add to the spline", 0, INT_MAX);
#if 0
func = RNA_def_function(srna, "remove", "rna_Curve_spline_remove");
RNA_def_function_ui_description(func, "Remove a spline from a curve");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "spline", "Spline", "", "The spline to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
#endif
}
@@ -1226,7 +1228,8 @@ static void rna_def_curve_splines(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove a spline from a curve");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "spline", "Spline", "", "The spline to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "clear", "rna_Curve_spline_clear");
RNA_def_function_ui_description(func, "Remove all spline from a curve");
diff --git a/source/blender/makesrna/intern/rna_define.c b/source/blender/makesrna/intern/rna_define.c
index 45092d09ce1..bb1ecea6a24 100644
--- a/source/blender/makesrna/intern/rna_define.c
+++ b/source/blender/makesrna/intern/rna_define.c
@@ -42,10 +42,23 @@
#include "BLI_listbase.h"
#include "BLI_ghash.h"
+#include "BLF_translation.h"
+
#include "RNA_define.h"
#include "rna_internal.h"
+
+#ifdef DEBUG
+# define ASSERT_SOFT_HARD_LIMITS \
+ if (softmin < hardmin || softmax > hardmax) { \
+ fprintf(stderr, "Error with soft/hard limits: %s.%s\n", CONTAINER_RNA_ID(cont), identifier); \
+ BLI_assert(!"invalid soft/hard limits"); \
+ } (void)0
+#else
+# define ASSERT_SOFT_HARD_LIMITS (void)0
+#endif
+
/* Global used during defining */
BlenderDefRNA DefRNA = {NULL, {NULL, NULL}, {NULL, NULL}, NULL, 0, 0, 0, 1};
@@ -887,7 +900,7 @@ void RNA_def_struct_translation_context(StructRNA *srna, const char *context)
PropertyRNA *RNA_def_property(StructOrFunctionRNA *cont_, const char *identifier, int type, int subtype)
{
- /*StructRNA *srna= DefRNA.laststruct;*/ /* invalid for python defined props */
+ /*StructRNA *srna = DefRNA.laststruct;*/ /* invalid for python defined props */
ContainerRNA *cont = cont_;
ContainerDefRNA *dcont;
PropertyDefRNA *dprop = NULL;
@@ -968,8 +981,10 @@ PropertyRNA *RNA_def_property(StructOrFunctionRNA *cont_, const char *identifier
sprop->defaultvalue = "";
break;
}
- case PROP_ENUM:
case PROP_POINTER:
+ prop->flag |= PROP_THICK_WRAP; /* needed for default behavior when PROP_RNAPTR is set */
+ break;
+ case PROP_ENUM:
case PROP_COLLECTION:
break;
default:
@@ -2248,12 +2263,15 @@ PropertyRNA *RNA_def_boolean_vector(StructOrFunctionRNA *cont_, const char *iden
return prop;
}
-PropertyRNA *RNA_def_int(StructOrFunctionRNA *cont_, const char *identifier, int default_value, int hardmin,
- int hardmax, const char *ui_name, const char *ui_description, int softmin, int softmax)
+PropertyRNA *RNA_def_int(StructOrFunctionRNA *cont_, const char *identifier, int default_value,
+ int hardmin, int hardmax, const char *ui_name, const char *ui_description,
+ int softmin, int softmax)
{
ContainerRNA *cont = cont_;
PropertyRNA *prop;
+ ASSERT_SOFT_HARD_LIMITS;
+
prop = RNA_def_property(cont, identifier, PROP_INT, PROP_NONE);
RNA_def_property_int_default(prop, default_value);
if (hardmin != hardmax) RNA_def_property_range(prop, hardmin, hardmax);
@@ -2270,6 +2288,8 @@ PropertyRNA *RNA_def_int_vector(StructOrFunctionRNA *cont_, const char *identifi
ContainerRNA *cont = cont_;
PropertyRNA *prop;
+ ASSERT_SOFT_HARD_LIMITS;
+
prop = RNA_def_property(cont, identifier, PROP_INT, PROP_XYZ); /* XXX */
if (len != 0) RNA_def_property_array(prop, len);
if (default_value) RNA_def_property_int_array_default(prop, default_value);
@@ -2287,6 +2307,8 @@ PropertyRNA *RNA_def_int_array(StructOrFunctionRNA *cont_, const char *identifie
ContainerRNA *cont = cont_;
PropertyRNA *prop;
+ ASSERT_SOFT_HARD_LIMITS;
+
prop = RNA_def_property(cont, identifier, PROP_INT, PROP_NONE);
if (len != 0) RNA_def_property_array(prop, len);
if (default_value) RNA_def_property_int_array_default(prop, default_value);
@@ -2426,6 +2448,8 @@ PropertyRNA *RNA_def_float(StructOrFunctionRNA *cont_, const char *identifier, f
ContainerRNA *cont = cont_;
PropertyRNA *prop;
+ ASSERT_SOFT_HARD_LIMITS;
+
prop = RNA_def_property(cont, identifier, PROP_FLOAT, PROP_NONE);
RNA_def_property_float_default(prop, default_value);
if (hardmin != hardmax) RNA_def_property_range(prop, hardmin, hardmax);
@@ -2442,6 +2466,8 @@ PropertyRNA *RNA_def_float_vector(StructOrFunctionRNA *cont_, const char *identi
ContainerRNA *cont = cont_;
PropertyRNA *prop;
+ ASSERT_SOFT_HARD_LIMITS;
+
prop = RNA_def_property(cont, identifier, PROP_FLOAT, PROP_XYZ);
if (len != 0) RNA_def_property_array(prop, len);
if (default_value) RNA_def_property_float_array_default(prop, default_value);
@@ -2472,6 +2498,8 @@ PropertyRNA *RNA_def_float_color(StructOrFunctionRNA *cont_, const char *identif
ContainerRNA *cont = cont_;
PropertyRNA *prop;
+ ASSERT_SOFT_HARD_LIMITS;
+
prop = RNA_def_property(cont, identifier, PROP_FLOAT, PROP_COLOR);
if (len != 0) RNA_def_property_array(prop, len);
if (default_value) RNA_def_property_float_array_default(prop, default_value);
@@ -2489,10 +2517,9 @@ PropertyRNA *RNA_def_float_matrix(StructOrFunctionRNA *cont_, const char *identi
{
ContainerRNA *cont = cont_;
PropertyRNA *prop;
- int length[2];
+ const int length[2] = {rows, columns};
- length[0] = rows;
- length[1] = columns;
+ ASSERT_SOFT_HARD_LIMITS;
prop = RNA_def_property(cont, identifier, PROP_FLOAT, PROP_MATRIX);
RNA_def_property_multi_array(prop, 2, length);
@@ -2510,7 +2537,9 @@ PropertyRNA *RNA_def_float_rotation(StructOrFunctionRNA *cont_, const char *iden
{
ContainerRNA *cont = cont_;
PropertyRNA *prop;
-
+
+ ASSERT_SOFT_HARD_LIMITS;
+
prop = RNA_def_property(cont, identifier, PROP_FLOAT, (len != 0) ? PROP_EULER : PROP_ANGLE);
if (len != 0) {
RNA_def_property_array(prop, len);
@@ -2534,6 +2563,8 @@ PropertyRNA *RNA_def_float_array(StructOrFunctionRNA *cont_, const char *identif
ContainerRNA *cont = cont_;
PropertyRNA *prop;
+ ASSERT_SOFT_HARD_LIMITS;
+
prop = RNA_def_property(cont, identifier, PROP_FLOAT, PROP_NONE);
if (len != 0) RNA_def_property_array(prop, len);
if (default_value) RNA_def_property_float_array_default(prop, default_value);
@@ -2551,6 +2582,8 @@ PropertyRNA *RNA_def_float_percentage(StructOrFunctionRNA *cont_, const char *id
ContainerRNA *cont = cont_;
PropertyRNA *prop;
+ ASSERT_SOFT_HARD_LIMITS;
+
prop = RNA_def_property(cont, identifier, PROP_FLOAT, PROP_PERCENTAGE);
RNA_def_property_float_default(prop, default_value);
if (hardmin != hardmax) RNA_def_property_range(prop, hardmin, hardmax);
@@ -2567,6 +2600,8 @@ PropertyRNA *RNA_def_float_factor(StructOrFunctionRNA *cont_, const char *identi
ContainerRNA *cont = cont_;
PropertyRNA *prop;
+ ASSERT_SOFT_HARD_LIMITS;
+
prop = RNA_def_property(cont, identifier, PROP_FLOAT, PROP_FACTOR);
RNA_def_property_float_default(prop, default_value);
if (hardmin != hardmax) RNA_def_property_range(prop, hardmin, hardmax);
@@ -2777,14 +2812,26 @@ int rna_parameter_size(PropertyRNA *parm)
{
#ifdef RNA_RUNTIME
if (parm->flag & PROP_RNAPTR)
- return sizeof(PointerRNA);
+ if (parm->flag & PROP_THICK_WRAP) {
+ return sizeof(PointerRNA);
+ }
+ else {
+ return sizeof(PointerRNA *);
+ }
else
return sizeof(void *);
#else
- if (parm->flag & PROP_RNAPTR)
- return sizeof(PointerRNA);
- else
+ if (parm->flag & PROP_RNAPTR) {
+ if (parm->flag & PROP_THICK_WRAP) {
+ return sizeof(PointerRNA);
+ }
+ else {
+ return sizeof(PointerRNA *);
+ }
+ }
+ else {
return sizeof(void *);
+ }
#endif
}
case PROP_COLLECTION:
diff --git a/source/blender/makesrna/intern/rna_fcurve.c b/source/blender/makesrna/intern/rna_fcurve.c
index a0d64723a5c..4250acf5848 100644
--- a/source/blender/makesrna/intern/rna_fcurve.c
+++ b/source/blender/makesrna/intern/rna_fcurve.c
@@ -403,20 +403,22 @@ static void rna_FCurve_group_set(PointerRNA *ptr, PointerRNA value)
}
}
-DriverVar *rna_Driver_new_variable(ChannelDriver *driver)
+static DriverVar *rna_Driver_new_variable(ChannelDriver *driver)
{
/* call the API function for this */
return driver_add_new_variable(driver);
}
-void rna_Driver_remove_variable(ChannelDriver *driver, ReportList *reports, DriverVar *dvar)
+static void rna_Driver_remove_variable(ChannelDriver *driver, ReportList *reports, PointerRNA *dvar_ptr)
{
+ DriverVar *dvar = dvar_ptr->data;
if (BLI_findindex(&driver->variables, dvar) == -1) {
BKE_report(reports, RPT_ERROR, "Variable does not exist in this driver");
return;
}
driver_free_variable(driver, dvar);
+ RNA_POINTER_INVALIDATE(dvar_ptr);
}
@@ -438,13 +440,16 @@ static FModifier *rna_FCurve_modifiers_new(FCurve *fcu, int type)
return add_fmodifier(&fcu->modifiers, type);
}
-static void rna_FCurve_modifiers_remove(FCurve *fcu, ReportList *reports, FModifier *fcm)
+static void rna_FCurve_modifiers_remove(FCurve *fcu, ReportList *reports, PointerRNA *fcm_ptr)
{
+ FModifier *fcm = fcm_ptr->data;
if (BLI_findindex(&fcu->modifiers, fcm) == -1) {
BKE_reportf(reports, RPT_ERROR, "F-Curve modifier '%s' not found in F-Curve", fcm->name);
return;
}
+
remove_fmodifier(&fcu->modifiers, fcm);
+ RNA_POINTER_INVALIDATE(fcm_ptr);
}
static void rna_FModifier_active_set(PointerRNA *ptr, int UNUSED(value))
@@ -610,8 +615,9 @@ static void rna_FKeyframe_points_add(FCurve *fcu, int tot)
}
}
-static void rna_FKeyframe_points_remove(FCurve *fcu, ReportList *reports, BezTriple *bezt, int do_fast)
+static void rna_FKeyframe_points_remove(FCurve *fcu, ReportList *reports, PointerRNA *bezt_ptr, int do_fast)
{
+ BezTriple *bezt = bezt_ptr->data;
int index = (int)(bezt - fcu->bezt);
if (index < 0 || index >= fcu->totvert) {
BKE_report(reports, RPT_ERROR, "Keyframe not in F-Curve");
@@ -619,6 +625,7 @@ static void rna_FKeyframe_points_remove(FCurve *fcu, ReportList *reports, BezTri
}
delete_fcurve_key(fcu, index, !do_fast);
+ RNA_POINTER_INVALIDATE(bezt_ptr);
}
static void rna_fcurve_range(FCurve *fcu, float range[2])
@@ -1263,7 +1270,8 @@ static void rna_def_channeldriver_variables(BlenderRNA *brna, PropertyRNA *cprop
RNA_def_function_flag(func, FUNC_USE_REPORTS);
/* target to remove */
parm = RNA_def_pointer(func, "variable", "DriverVariable", "", "Variable to remove from the driver");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
static void rna_def_channeldriver(BlenderRNA *brna)
@@ -1458,7 +1466,8 @@ static void rna_def_fcurve_modifiers(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove a modifier from this F-Curve");
/* modifier to remove */
parm = RNA_def_pointer(func, "modifier", "FModifier", "", "Removed modifier");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
/* fcurve.keyframe_points */
@@ -1497,13 +1506,14 @@ static void rna_def_fcurve_keyframe_points(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "add", "rna_FKeyframe_points_add");
RNA_def_function_ui_description(func, "Add a keyframe point to a F-Curve");
- RNA_def_int(func, "count", 1, 1, INT_MAX, "Number", "Number of points to add to the spline", 1, INT_MAX);
+ RNA_def_int(func, "count", 1, 0, INT_MAX, "Number", "Number of points to add to the spline", 0, INT_MAX);
func = RNA_def_function(srna, "remove", "rna_FKeyframe_points_remove");
RNA_def_function_ui_description(func, "Remove keyframe from an F-Curve");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "keyframe", "Keyframe", "", "Keyframe to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
/* optional */
RNA_def_boolean(func, "fast", 0, "Fast", "Fast keyframe removal to avoid recalculating the curve each time");
}
diff --git a/source/blender/makesrna/intern/rna_fcurve_api.c b/source/blender/makesrna/intern/rna_fcurve_api.c
index 1f8b827f320..ab96f6f384d 100644
--- a/source/blender/makesrna/intern/rna_fcurve_api.c
+++ b/source/blender/makesrna/intern/rna_fcurve_api.c
@@ -34,10 +34,14 @@
#include <string.h>
#include <time.h>
+#include "BLI_utildefines.h"
+
#include "RNA_define.h"
#include "DNA_anim_types.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include <stddef.h>
@@ -47,7 +51,7 @@
#else
-void RNA_api_drivers(StructRNA *srna)
+void RNA_api_drivers(StructRNA *UNUSED(srna))
{
/* FunctionRNA *func; */
/* PropertyRNA *parm; */
diff --git a/source/blender/makesrna/intern/rna_fluidsim.c b/source/blender/makesrna/intern/rna_fluidsim.c
index daa661175a1..84ff53ee68f 100644
--- a/source/blender/makesrna/intern/rna_fluidsim.c
+++ b/source/blender/makesrna/intern/rna_fluidsim.c
@@ -699,7 +699,7 @@ void RNA_def_fluidsim(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Type", "Type of participation in the fluid simulation");
RNA_def_property_update(prop, 0, "rna_FluidSettings_update_type");
- /*prop= RNA_def_property(srna, "ipo", PROP_POINTER, PROP_NONE); */
+ /*prop = RNA_def_property(srna, "ipo", PROP_POINTER, PROP_NONE); */
/*RNA_def_property_ui_text(prop, "IPO Curves", "IPO curves used by fluid simulation settings"); */
/* types */
diff --git a/source/blender/makesrna/intern/rna_gpencil.c b/source/blender/makesrna/intern/rna_gpencil.c
index eb12a02aa99..b3c1f4dd505 100644
--- a/source/blender/makesrna/intern/rna_gpencil.c
+++ b/source/blender/makesrna/intern/rna_gpencil.c
@@ -27,6 +27,7 @@
#include <stdlib.h>
+#include "RNA_access.h"
#include "RNA_define.h"
#include "rna_internal.h"
@@ -40,6 +41,15 @@
#ifdef RNA_RUNTIME
+#include "WM_api.h"
+
+#include "BKE_gpencil.h"
+
+static void rna_GPencil_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr))
+{
+ WM_main_add_notifier(NC_GPENCIL | NA_EDITED, NULL);
+}
+
static int rna_GPencilLayer_active_frame_editable(PointerRNA *ptr)
{
bGPDlayer *gpl = (bGPDlayer *)ptr->data;
@@ -53,6 +63,7 @@ static int rna_GPencilLayer_active_frame_editable(PointerRNA *ptr)
static PointerRNA rna_GPencil_active_layer_get(PointerRNA *ptr)
{
+
bGPdata *gpd = ptr->id.data;
if (GS(gpd->id.name) == ID_GD) { /* why would this ever be not GD */
@@ -90,7 +101,7 @@ static void rna_GPencil_active_layer_set(PointerRNA *ptr, PointerRNA value)
}
}
-void rna_GPencilLayer_info_set(PointerRNA *ptr, const char *value)
+static void rna_GPencilLayer_info_set(PointerRNA *ptr, const char *value)
{
bGPdata *gpd = ptr->id.data;
bGPDlayer *gpl = ptr->data;
@@ -101,6 +112,160 @@ void rna_GPencilLayer_info_set(PointerRNA *ptr, const char *value)
BLI_uniquename(&gpd->layers, gpl, "GP_Layer", '.', offsetof(bGPDlayer, info), sizeof(gpl->info));
}
+static void rna_GPencil_stroke_point_add(bGPDstroke *stroke, int count)
+{
+ if (count > 0) {
+ if (stroke->points == NULL)
+ stroke->points = MEM_callocN(sizeof(bGPDspoint) * count, "gp_stroke_points");
+ else
+ stroke->points = MEM_reallocN(stroke->points, sizeof(bGPDspoint) * (stroke->totpoints + count));
+
+ stroke->totpoints += count;
+ }
+}
+
+static void rna_GPencil_stroke_point_pop(bGPDstroke *stroke, ReportList *reports, int index)
+{
+ bGPDspoint *pt_tmp = stroke->points;
+
+ /* python style negative indexing */
+ if (index < 0) {
+ index += stroke->totpoints;
+ }
+
+ if (stroke->totpoints <= index || index < 0) {
+ BKE_report(reports, RPT_ERROR, "GPencilStrokePoints.pop: index out of range");
+ return;
+ }
+
+ stroke->totpoints--;
+
+ stroke->points = MEM_callocN(sizeof(bGPDspoint) * stroke->totpoints, "gp_stroke_points");
+
+ if (index > 0)
+ memcpy(stroke->points, pt_tmp, sizeof(bGPDspoint) * index);
+
+ if (index < stroke->totpoints)
+ memcpy(&stroke->points[index], &pt_tmp[index + 1], sizeof(bGPDspoint) * (stroke->totpoints - index));
+
+ /* free temp buffer */
+ MEM_freeN(pt_tmp);
+
+ WM_main_add_notifier(NC_GPENCIL | NA_EDITED, NULL);
+}
+
+static bGPDstroke *rna_GPencil_stroke_new(bGPDframe *frame)
+{
+ bGPDstroke *stroke = MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
+
+ BLI_addtail(&frame->strokes, stroke);
+
+ return stroke;
+}
+
+static void rna_GPencil_stroke_remove(bGPDframe *frame, ReportList *reports, PointerRNA *stroke_ptr)
+{
+ bGPDstroke *stroke = stroke_ptr->data;
+ if (BLI_findindex(&frame->strokes, stroke) == -1) {
+ BKE_report(reports, RPT_ERROR, "Stroke not found in grease pencil frame");
+ return;
+ }
+
+ BLI_freelinkN(&frame->strokes, stroke);
+ RNA_POINTER_INVALIDATE(stroke_ptr);
+
+ WM_main_add_notifier(NC_GPENCIL | NA_EDITED, NULL);
+}
+
+static bGPDframe *rna_GPencil_frame_new(bGPDlayer *layer, ReportList *reports, int frame_number)
+{
+ bGPDframe *frame;
+
+ if (BKE_gpencil_layer_find_frame(layer, frame_number)) {
+ BKE_reportf(reports, RPT_ERROR, "Frame already exists on this frame number %d", frame_number);
+ return NULL;
+ }
+
+ frame = gpencil_frame_addnew(layer, frame_number);
+
+ WM_main_add_notifier(NC_GPENCIL | NA_EDITED, NULL);
+
+ return frame;
+}
+
+static void rna_GPencil_frame_remove(bGPDlayer *layer, ReportList *reports, PointerRNA *frame_ptr)
+{
+ bGPDframe *frame = frame_ptr->data;
+ if (BLI_findindex(&layer->frames, frame) == -1) {
+ BKE_report(reports, RPT_ERROR, "Frame not found in grease pencil layer");
+ return;
+ }
+
+ gpencil_layer_delframe(layer, frame);
+ RNA_POINTER_INVALIDATE(frame_ptr);
+
+ WM_main_add_notifier(NC_GPENCIL | NA_EDITED, NULL);
+}
+
+static bGPDframe *rna_GPencil_frame_copy(bGPDlayer *layer, bGPDframe *src)
+{
+ bGPDframe *frame = gpencil_frame_duplicate(src);
+
+ while (BKE_gpencil_layer_find_frame(layer, frame->framenum)) {
+ frame->framenum++;
+ }
+
+ BLI_addtail(&layer->frames, frame);
+
+ WM_main_add_notifier(NC_GPENCIL | NA_EDITED, NULL);
+
+ return frame;
+}
+
+static bGPDlayer *rna_GPencil_layer_new(bGPdata *gpd, const char *name, int setactive)
+{
+ bGPDlayer *gl = gpencil_layer_addnew(gpd, name, setactive);
+
+ WM_main_add_notifier(NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
+
+ return gl;
+}
+
+static void rna_GPencil_layer_remove(bGPdata *gpd, ReportList *reports, PointerRNA *layer_ptr)
+{
+ bGPDlayer *layer = layer_ptr->data;
+ if (BLI_findindex(&gpd->layers, layer) == -1) {
+ BKE_report(reports, RPT_ERROR, "Layer not found in grease pencil data");
+ return;
+ }
+
+ gpencil_layer_delete(gpd, layer);
+ RNA_POINTER_INVALIDATE(layer_ptr);
+
+ WM_main_add_notifier(NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
+}
+
+static void rna_GPencil_frame_clear(bGPDframe *frame)
+{
+ free_gpencil_strokes(frame);
+
+ WM_main_add_notifier(NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
+}
+
+static void rna_GPencil_layer_clear(bGPDlayer *layer)
+{
+ free_gpencil_frames(layer);
+
+ WM_main_add_notifier(NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
+}
+
+static void rna_GPencil_clear(bGPdata *gpd)
+{
+ free_gpencil_layers(&gpd->layers);
+
+ WM_main_add_notifier(NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
+}
+
#else
static void rna_def_gpencil_stroke_point(BlenderRNA *brna)
@@ -116,19 +281,49 @@ static void rna_def_gpencil_stroke_point(BlenderRNA *brna)
RNA_def_property_float_sdna(prop, NULL, "x");
RNA_def_property_array(prop, 3);
RNA_def_property_ui_text(prop, "Coordinates", "");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, "rna_GPencil_update");
prop = RNA_def_property(srna, "pressure", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "pressure");
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_ui_text(prop, "Pressure", "Pressure of tablet at point when drawing it");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, "rna_GPencil_update");
+}
+
+static void rna_def_gpencil_stroke_points_api(BlenderRNA *brna, PropertyRNA *cprop)
+{
+ StructRNA *srna;
+
+ FunctionRNA *func;
+ /* PropertyRNA *parm; */
+
+ RNA_def_property_srna(cprop, "GPencilStrokePoints");
+ srna = RNA_def_struct(brna, "GPencilStrokePoints", NULL);
+ RNA_def_struct_sdna(srna, "bGPDstroke");
+ RNA_def_struct_ui_text(srna, "Grease Pencil Stroke Points", "Collection of grease pencil stroke points");
+
+ func = RNA_def_function(srna, "add", "rna_GPencil_stroke_point_add");
+ RNA_def_function_ui_description(func, "Add a new grease pencil stroke point");
+ RNA_def_int(func, "count", 1, 0, INT_MAX, "Number", "Number of points to add to the stroke", 0, INT_MAX);
+
+ func = RNA_def_function(srna, "pop", "rna_GPencil_stroke_point_pop");
+ RNA_def_function_ui_description(func, "Remove a grease pencil stroke point");
+ RNA_def_function_flag(func, FUNC_USE_REPORTS);
+ RNA_def_int(func, "index", -1, INT_MIN, INT_MAX, "Index", "point index", INT_MIN, INT_MAX);
}
static void rna_def_gpencil_stroke(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
+
+ static EnumPropertyItem stroke_draw_mode_items[] = {
+ {0, "SCREEN", 0, "Screen", "Stroke is in screen-space"},
+ {GP_STROKE_3DSPACE, "3DSPACE", 0, "3D Space", "Stroke is in 3D-space"},
+ {GP_STROKE_2DSPACE, "2DSPACE", 0, "2D Space", "Stroke is in 2D-space"},
+ {GP_STROKE_2DIMAGE, "2DIMAGE", 0, "2D Image", "Stroke is in 2D-space (but with special 'image' scaling)"},
+ {0, NULL, 0, NULL, NULL}
+ };
srna = RNA_def_struct(brna, "GPencilStroke", NULL);
RNA_def_struct_sdna(srna, "bGPDstroke");
@@ -139,15 +334,46 @@ static void rna_def_gpencil_stroke(BlenderRNA *brna)
RNA_def_property_collection_sdna(prop, NULL, "points", "totpoints");
RNA_def_property_struct_type(prop, "GPencilStrokePoint");
RNA_def_property_ui_text(prop, "Stroke Points", "Stroke data points");
-
- /* Flags - Readonly type-info really... */
- /* TODO... */
+ rna_def_gpencil_stroke_points_api(brna, prop);
+
+ prop = RNA_def_property(srna, "draw_mode", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_bitflag_sdna(prop, NULL, "flag");
+ RNA_def_property_enum_items(prop, stroke_draw_mode_items);
+ RNA_def_property_ui_text(prop, "Draw Mode", "");
+ RNA_def_property_update(prop, 0, "rna_GPencil_update");
+}
+
+static void rna_def_gpencil_strokes_api(BlenderRNA *brna, PropertyRNA *cprop)
+{
+ StructRNA *srna;
+
+ FunctionRNA *func;
+ PropertyRNA *parm;
+
+ RNA_def_property_srna(cprop, "GPencilStrokes");
+ srna = RNA_def_struct(brna, "GPencilStrokes", NULL);
+ RNA_def_struct_sdna(srna, "bGPDframe");
+ RNA_def_struct_ui_text(srna, "Grease Pencil Frames", "Collection of grease pencil frames");
+
+ func = RNA_def_function(srna, "new", "rna_GPencil_stroke_new");
+ RNA_def_function_ui_description(func, "Add a new grease pencil frame");
+ parm = RNA_def_pointer(func, "stroke", "GPencilStroke", "", "The newly created stroke");
+ RNA_def_function_return(func, parm);
+
+ func = RNA_def_function(srna, "remove", "rna_GPencil_stroke_remove");
+ RNA_def_function_ui_description(func, "Remove a grease pencil frame");
+ RNA_def_function_flag(func, FUNC_USE_REPORTS);
+ parm = RNA_def_pointer(func, "stroke", "GPencilStroke", "Stroke", "The stroke to remove");
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
static void rna_def_gpencil_frame(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
+
+ FunctionRNA *func;
srna = RNA_def_struct(brna, "GPencilFrame", NULL);
RNA_def_struct_sdna(srna, "bGPDframe");
@@ -158,7 +384,8 @@ static void rna_def_gpencil_frame(BlenderRNA *brna)
RNA_def_property_collection_sdna(prop, NULL, "strokes", NULL);
RNA_def_property_struct_type(prop, "GPencilStroke");
RNA_def_property_ui_text(prop, "Strokes", "Freehand curves defining the sketch on this frame");
-
+ rna_def_gpencil_strokes_api(brna, prop);
+
/* Frame Number */
prop = RNA_def_property(srna, "frame_number", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "framenum");
@@ -173,12 +400,52 @@ static void rna_def_gpencil_frame(BlenderRNA *brna)
prop = RNA_def_property(srna, "select", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", GP_FRAME_SELECT);
RNA_def_property_ui_text(prop, "Select", "Frame is selected for editing in the DopeSheet");
+
+ func = RNA_def_function(srna, "clear", "rna_GPencil_frame_clear");
+ RNA_def_function_ui_description(func, "Remove all the grease pencil frame data");
+}
+
+static void rna_def_gpencil_frames_api(BlenderRNA *brna, PropertyRNA *cprop)
+{
+ StructRNA *srna;
+
+ FunctionRNA *func;
+ PropertyRNA *parm;
+
+ RNA_def_property_srna(cprop, "GPencilFrames");
+ srna = RNA_def_struct(brna, "GPencilFrames", NULL);
+ RNA_def_struct_sdna(srna, "bGPDlayer");
+ RNA_def_struct_ui_text(srna, "Grease Pencil Frames", "Collection of grease pencil frames");
+
+ func = RNA_def_function(srna, "new", "rna_GPencil_frame_new");
+ RNA_def_function_ui_description(func, "Add a new grease pencil frame");
+ RNA_def_function_flag(func, FUNC_USE_REPORTS);
+ parm = RNA_def_int(func, "frame_number", 1, MINFRAME, MAXFRAME, "Frame Number", "The frame on which this sketch appears", MINFRAME, MAXFRAME);
+ RNA_def_property_flag(parm, PROP_REQUIRED);
+ parm = RNA_def_pointer(func, "frame", "GPencilFrame", "", "The newly created frame");
+ RNA_def_function_return(func, parm);
+
+ func = RNA_def_function(srna, "remove", "rna_GPencil_frame_remove");
+ RNA_def_function_ui_description(func, "Remove a grease pencil frame");
+ RNA_def_function_flag(func, FUNC_USE_REPORTS);
+ parm = RNA_def_pointer(func, "frame", "GPencilFrame", "Frame", "The frame to remove");
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
+
+ func = RNA_def_function(srna, "copy", "rna_GPencil_frame_copy");
+ RNA_def_function_ui_description(func, "Copy a grease pencil frame");
+ parm = RNA_def_pointer(func, "source", "GPencilFrame", "Source", "The source frame");
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ parm = RNA_def_pointer(func, "copy", "GPencilFrame", "", "The newly copied frame");
+ RNA_def_function_return(func, parm);
}
static void rna_def_gpencil_layer(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
+
+ FunctionRNA *func;
srna = RNA_def_struct(brna, "GPencilLayer", NULL);
RNA_def_struct_sdna(srna, "bGPDlayer");
@@ -189,44 +456,47 @@ static void rna_def_gpencil_layer(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Info", "Layer name");
RNA_def_property_string_funcs(prop, NULL, NULL, "rna_GPencilLayer_info_set");
RNA_def_struct_name_property(srna, prop);
-
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, NULL);
+
/* Frames */
prop = RNA_def_property(srna, "frames", PROP_COLLECTION, PROP_NONE);
RNA_def_property_collection_sdna(prop, NULL, "frames", NULL);
RNA_def_property_struct_type(prop, "GPencilFrame");
RNA_def_property_ui_text(prop, "Frames", "Sketches for this layer on different frames");
-
+ rna_def_gpencil_frames_api(brna, prop);
+
/* Active Frame */
prop = RNA_def_property(srna, "active_frame", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "actframe");
RNA_def_property_ui_text(prop, "Active Frame", "Frame currently being displayed for this layer");
RNA_def_property_editable_func(prop, "rna_GPencilLayer_active_frame_editable");
-
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, NULL);
+
/* Drawing Color */
prop = RNA_def_property(srna, "color", PROP_FLOAT, PROP_COLOR_GAMMA);
RNA_def_property_array(prop, 3);
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_ui_text(prop, "Color", "Color for all strokes in this layer");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, "rna_GPencil_update");
prop = RNA_def_property(srna, "alpha", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "color[3]");
RNA_def_property_range(prop, 0.3, 1.0f);
RNA_def_property_ui_text(prop, "Opacity", "Layer Opacity");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, "rna_GPencil_update");
/* Line Thickness */
prop = RNA_def_property(srna, "line_width", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "thickness");
RNA_def_property_range(prop, 1, 10);
RNA_def_property_ui_text(prop, "Thickness", "Thickness of strokes (in pixels)");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, "rna_GPencil_update");
/* Onion-Skinning */
prop = RNA_def_property(srna, "use_onion_skinning", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", GP_LAYER_ONIONSKIN);
RNA_def_property_ui_text(prop, "Onion Skinning", "Ghost frames on either side of frame");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, "rna_GPencil_update");
prop = RNA_def_property(srna, "ghost_range_max", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "gstep");
@@ -234,23 +504,23 @@ static void rna_def_gpencil_layer(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Max Ghost Range",
"Maximum number of frames on either side of the active frame to show "
"(0 = show the 'first' available sketch on either side)");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, "rna_GPencil_update");
/* Flags */
prop = RNA_def_property(srna, "hide", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", GP_LAYER_HIDE);
RNA_def_property_ui_text(prop, "Hide", "Set layer Visibility");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, "rna_GPencil_update");
prop = RNA_def_property(srna, "lock", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", GP_LAYER_LOCKED);
RNA_def_property_ui_text(prop, "Locked", "Protect layer from further editing and/or frame changes");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, NULL);
prop = RNA_def_property(srna, "lock_frame", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", GP_LAYER_FRAMELOCK);
RNA_def_property_ui_text(prop, "Frame Locked", "Lock current frame displayed by layer");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, NULL);
/* expose as layers.active */
#if 0
@@ -258,54 +528,57 @@ static void rna_def_gpencil_layer(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "flag", GP_LAYER_ACTIVE);
RNA_def_property_boolean_funcs(prop, NULL, "rna_GPencilLayer_active_set");
RNA_def_property_ui_text(prop, "Active", "Set active layer for editing");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, NULL);
#endif
prop = RNA_def_property(srna, "select", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", GP_LAYER_SELECT);
RNA_def_property_ui_text(prop, "Select", "Layer is selected for editing in the DopeSheet");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, NULL);
/* XXX keep this option? */
prop = RNA_def_property(srna, "show_points", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", GP_LAYER_DRAWDEBUG);
RNA_def_property_ui_text(prop, "Show Points", "Draw the points which make up the strokes (for debugging purposes)");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update_runtime(prop, "rna_GPencil_update");
/* X-Ray */
prop = RNA_def_property(srna, "show_x_ray", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GP_LAYER_NO_XRAY);
RNA_def_property_ui_text(prop, "X Ray", "Make the layer draw in front of objects");
- RNA_def_property_update(prop, NC_SCREEN | ND_GPENCIL, NULL);
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, "rna_GPencil_update");
+
+ func = RNA_def_function(srna, "clear", "rna_GPencil_layer_clear");
+ RNA_def_function_ui_description(func, "Remove all the grease pencil layer data");
}
-static void rna_def_gpencil_layers(BlenderRNA *brna, PropertyRNA *cprop)
+static void rna_def_gpencil_layers_api(BlenderRNA *brna, PropertyRNA *cprop)
{
StructRNA *srna;
PropertyRNA *prop;
-/* FunctionRNA *func; */
-/* PropertyRNA *parm; */
+ FunctionRNA *func;
+ PropertyRNA *parm;
RNA_def_property_srna(cprop, "GreasePencilLayers");
srna = RNA_def_struct(brna, "GreasePencilLayers", NULL);
RNA_def_struct_sdna(srna, "bGPdata");
RNA_def_struct_ui_text(srna, "Grease Pencil Layers", "Collection of grease pencil layers");
-#if 0
func = RNA_def_function(srna, "new", "rna_GPencil_layer_new");
- RNA_def_function_ui_description(func, "Add a new spline to the curve");
- parm = RNA_def_enum(func, "type", curve_type_items, CU_POLY, "", "type for the new spline");
+ RNA_def_function_ui_description(func, "Add a new grease pencil layer");
+ parm = RNA_def_string(func, "name", "GPencilLayer", MAX_NAME, "Name", "Name of the layer");
RNA_def_property_flag(parm, PROP_REQUIRED);
- parm = RNA_def_pointer(func, "spline", "Spline", "", "The newly created spline");
+ RNA_def_boolean(func, "set_active", 0, "Set Active", "Set the newly created layer to the active layer");
+ parm = RNA_def_pointer(func, "layer", "GPencilLayer", "", "The newly created layer");
RNA_def_function_return(func, parm);
func = RNA_def_function(srna, "remove", "rna_GPencil_layer_remove");
- RNA_def_function_ui_description(func, "Remove a spline from a curve");
+ RNA_def_function_ui_description(func, "Remove a grease pencil layer");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
- parm = RNA_def_pointer(func, "spline", "Spline", "", "The spline to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
-#endif
+ parm = RNA_def_pointer(func, "layer", "GPencilLayer", "", "The layer to remove");
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
prop = RNA_def_property(srna, "active", PROP_POINTER, PROP_NONE);
RNA_def_property_struct_type(prop, "GreasePencil");
@@ -318,7 +591,8 @@ static void rna_def_gpencil_data(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
+ FunctionRNA *func;
+
static EnumPropertyItem draw_mode_items[] = {
{GP_DATA_VIEWALIGN, "CURSOR", 0, "Cursor", "Draw stroke at the 3D cursor"},
{0, "VIEW", 0, "View", "Stick stroke to the view "}, /* weird, GP_DATA_VIEWALIGN is inverted */
@@ -337,19 +611,22 @@ static void rna_def_gpencil_data(BlenderRNA *brna)
RNA_def_property_collection_sdna(prop, NULL, "layers", NULL);
RNA_def_property_struct_type(prop, "GPencilLayer");
RNA_def_property_ui_text(prop, "Layers", "");
- rna_def_gpencil_layers(brna, prop);
+ rna_def_gpencil_layers_api(brna, prop);
/* Flags */
prop = RNA_def_property(srna, "draw_mode", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_bitflag_sdna(prop, NULL, "flag");
RNA_def_property_enum_items(prop, draw_mode_items);
RNA_def_property_ui_text(prop, "Draw Mode", "");
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, NULL);
prop = RNA_def_property(srna, "use_stroke_endpoints", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", GP_DATA_DEPTH_STROKE_ENDPOINTS);
RNA_def_property_ui_text(prop, "Only Endpoints", "Only use the first and last parts of the stroke for snapping");
+ RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, NULL);
-
+ func = RNA_def_function(srna, "clear", "rna_GPencil_clear");
+ RNA_def_function_ui_description(func, "Remove all the grease pencil data");
}
/* --- */
diff --git a/source/blender/makesrna/intern/rna_group.c b/source/blender/makesrna/intern/rna_group.c
index 586b71aa2da..4baf46fd0b5 100644
--- a/source/blender/makesrna/intern/rna_group.c
+++ b/source/blender/makesrna/intern/rna_group.c
@@ -54,7 +54,7 @@ static PointerRNA rna_Group_objects_get(CollectionPropertyIterator *iter)
static void rna_Group_objects_link(Group *group, bContext *C, ReportList *reports, Object *object)
{
if (!add_to_group(group, object, CTX_data_scene(C), NULL)) {
- BKE_reportf(reports, RPT_ERROR, "Object \"%s\" already in group \"%s\"", object->id.name + 2, group->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Object '%s' already in group '%s'", object->id.name + 2, group->id.name + 2);
return;
}
@@ -64,7 +64,7 @@ static void rna_Group_objects_link(Group *group, bContext *C, ReportList *report
static void rna_Group_objects_unlink(Group *group, bContext *C, ReportList *reports, Object *object)
{
if (!rem_from_group(group, object, CTX_data_scene(C), NULL)) {
- BKE_reportf(reports, RPT_ERROR, "Object \"%s\" not in group \"%s\"", object->id.name + 2, group->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Object '%s' not in group '%s'", object->id.name + 2, group->id.name + 2);
return;
}
diff --git a/source/blender/makesrna/intern/rna_image.c b/source/blender/makesrna/intern/rna_image.c
index 495d60df49c..f8af2427827 100644
--- a/source/blender/makesrna/intern/rna_image.c
+++ b/source/blender/makesrna/intern/rna_image.c
@@ -147,10 +147,10 @@ static void rna_ImageUser_update(Main *UNUSED(bmain), Scene *scene, PointerRNA *
}
-char *rna_ImageUser_path(PointerRNA *ptr)
+static char *rna_ImageUser_path(PointerRNA *ptr)
{
if (ptr->id.data) {
- /* ImageUser *iuser= ptr->data; */
+ /* ImageUser *iuser = ptr->data; */
switch (GS(((ID *)ptr->id.data)->name)) {
case ID_TE:
@@ -366,7 +366,7 @@ static void rna_Image_pixels_set(PointerRNA *ptr, const float *values)
((unsigned char *)ibuf->rect)[i] = FTOCHAR(values[i]);
}
- ibuf->userflags |= IB_BITMAPDIRTY;
+ ibuf->userflags |= IB_BITMAPDIRTY | IB_DISPLAY_BUFFER_INVALID;
}
BKE_image_release_ibuf(ima, lock);
@@ -388,24 +388,27 @@ static void rna_def_imageuser(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "flag", IMA_ANIM_ALWAYS);
RNA_def_property_ui_text(prop, "Auto Refresh", "Always refresh image on frame changes");
RNA_def_property_update(prop, 0, "rna_ImageUser_update");
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
/* animation */
prop = RNA_def_property(srna, "use_cyclic", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "cycl", 0);
RNA_def_property_ui_text(prop, "Cyclic", "Cycle the images in the movie");
RNA_def_property_update(prop, 0, "rna_ImageUser_update");
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
prop = RNA_def_property(srna, "frame_duration", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "frames");
RNA_def_property_range(prop, 0, MAXFRAMEF);
RNA_def_property_ui_text(prop, "Frames", "Number of images of a movie to use");
RNA_def_property_update(prop, 0, "rna_ImageUser_update");
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
prop = RNA_def_property(srna, "frame_offset", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "offset");
- RNA_def_property_range(prop, MINAFRAMEF, MAXFRAMEF);
RNA_def_property_ui_text(prop, "Offset", "Offset the number of the frame to use in the animation");
RNA_def_property_update(prop, 0, "rna_ImageUser_update");
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
prop = RNA_def_property(srna, "frame_start", PROP_INT, PROP_TIME);
RNA_def_property_int_sdna(prop, NULL, "sfra");
@@ -413,12 +416,14 @@ static void rna_def_imageuser(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Start Frame",
"Global starting frame of the movie/sequence, assuming first picture has a #1");
RNA_def_property_update(prop, 0, "rna_ImageUser_update");
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
prop = RNA_def_property(srna, "fields_per_frame", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "fie_ima");
RNA_def_property_range(prop, 1, 200);
RNA_def_property_ui_text(prop, "Fields per Frame", "Number of fields per rendered frame (2 fields is 1 image)");
RNA_def_property_update(prop, 0, "rna_ImageUser_update");
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
prop = RNA_def_property(srna, "multilayer_layer", PROP_INT, PROP_UNSIGNED);
RNA_def_property_int_sdna(prop, NULL, "layer");
@@ -500,7 +505,8 @@ static void rna_def_image(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "flag", IMA_FIELDS);
RNA_def_property_ui_text(prop, "Fields", "Use fields of the image");
RNA_def_property_update(prop, NC_IMAGE | ND_DISPLAY, "rna_Image_fields_update");
-
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
+
prop = RNA_def_property(srna, "use_premultiply", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", IMA_DO_PREMUL);
RNA_def_property_ui_text(prop, "Premultiply", "Convert RGB from key alpha to premultiplied alpha");
@@ -529,23 +535,27 @@ static void rna_def_image(BlenderRNA *brna)
RNA_def_property_enum_items(prop, image_generated_type_items);
RNA_def_property_ui_text(prop, "Generated Type", "Generated image type");
RNA_def_property_update(prop, NC_IMAGE | ND_DISPLAY, "rna_Image_generated_update");
-
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
+
prop = RNA_def_property(srna, "generated_width", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "gen_x");
RNA_def_property_range(prop, 1, 16384);
RNA_def_property_ui_text(prop, "Generated Width", "Generated image width");
RNA_def_property_update(prop, NC_IMAGE | ND_DISPLAY, "rna_Image_generated_update");
-
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
+
prop = RNA_def_property(srna, "generated_height", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "gen_y");
RNA_def_property_range(prop, 1, 16384);
RNA_def_property_ui_text(prop, "Generated Height", "Generated image height");
RNA_def_property_update(prop, NC_IMAGE | ND_DISPLAY, "rna_Image_generated_update");
-
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
+
prop = RNA_def_property(srna, "use_generated_float", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "gen_flag", IMA_GEN_FLOAT);
RNA_def_property_ui_text(prop, "Float Buffer", "Generate floating point buffer");
RNA_def_property_update(prop, NC_IMAGE | ND_DISPLAY, "rna_Image_generated_update");
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
/* realtime properties */
prop = RNA_def_property(srna, "mapping", PROP_ENUM, PROP_NONE);
@@ -660,7 +670,7 @@ static void rna_def_image(BlenderRNA *brna)
prop = RNA_def_property(srna, "colorspace_settings", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "colorspace_settings");
RNA_def_property_struct_type(prop, "ColorManagedColorspaceSettings");
- RNA_def_property_ui_text(prop, "Colorspace Settings", "Input color space settings");
+ RNA_def_property_ui_text(prop, "Color Space Settings", "Input color space settings");
RNA_api_image(srna);
}
diff --git a/source/blender/makesrna/intern/rna_image_api.c b/source/blender/makesrna/intern/rna_image_api.c
index c66c0085763..cb5c515ce1f 100644
--- a/source/blender/makesrna/intern/rna_image_api.c
+++ b/source/blender/makesrna/intern/rna_image_api.c
@@ -41,6 +41,8 @@
#include "BIF_gl.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include "BKE_image.h"
@@ -78,26 +80,29 @@ static void rna_Image_save_render(Image *image, bContext *C, ReportList *reports
ibuf = BKE_image_acquire_ibuf(image, &iuser, &lock);
if (ibuf == NULL) {
- BKE_reportf(reports, RPT_ERROR, "Couldn't acquire buffer from image");
+ BKE_report(reports, RPT_ERROR, "Could not acquire buffer from image");
}
else {
- ImBuf *write_ibuf = IMB_dupImBuf(ibuf);
+ ImBuf *write_ibuf;
- IMB_display_buffer_to_imbuf_rect(write_ibuf, &scene->view_settings, &scene->display_settings);
+ write_ibuf = IMB_colormanagement_imbuf_for_write(ibuf, TRUE, TRUE, &scene->view_settings,
+ &scene->display_settings, &scene->r.im_format);
write_ibuf->planes = scene->r.im_format.planes;
write_ibuf->dither = scene->r.dither_intensity;
if (!BKE_imbuf_write(write_ibuf, path, &scene->r.im_format)) {
- BKE_reportf(reports, RPT_ERROR, "Couldn't write image: %s", path);
+ BKE_reportf(reports, RPT_ERROR, "Could not write image '%s'", path);
}
- IMB_freeImBuf(write_ibuf);
+
+ if (write_ibuf != ibuf)
+ IMB_freeImBuf(write_ibuf);
}
BKE_image_release_ibuf(image, lock);
}
else {
- BKE_reportf(reports, RPT_ERROR, "Scene not in context, couldn't get save parameters");
+ BKE_report(reports, RPT_ERROR, "Scene not in context, could not get save parameters");
}
}
@@ -111,7 +116,7 @@ static void rna_Image_save(Image *image, ReportList *reports)
if (image->packedfile) {
if (writePackedFile(reports, image->name, image->packedfile, 0) != RET_OK) {
- BKE_reportf(reports, RPT_ERROR, "Image \"%s\" could saved packed file to \"%s\"", image->id.name + 2, image->name);
+ BKE_reportf(reports, RPT_ERROR, "Image '%s' could not save packed file to '%s'", image->id.name + 2, image->name);
}
}
else if (IMB_saveiff(ibuf, filename, ibuf->flags)) {
@@ -125,11 +130,11 @@ static void rna_Image_save(Image *image, ReportList *reports)
ibuf->userflags &= ~IB_BITMAPDIRTY;
}
else {
- BKE_reportf(reports, RPT_ERROR, "Image \"%s\" could not be saved to \"%s\"", image->id.name + 2, image->name);
+ BKE_reportf(reports, RPT_ERROR, "Image '%s' could not be saved to '%s'", image->id.name + 2, image->name);
}
}
else {
- BKE_reportf(reports, RPT_ERROR, "Image \"%s\" does not have any image data", image->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Image '%s' does not have any image data", image->id.name + 2);
}
}
@@ -138,7 +143,7 @@ static void rna_Image_pack(Image *image, ReportList *reports, int as_png)
ImBuf *ibuf = BKE_image_get_ibuf(image, NULL);
if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
- BKE_reportf(reports, RPT_ERROR, "Can't pack edited image from disk, only as internal PNG");
+ BKE_report(reports, RPT_ERROR, "Cannot pack edited image from disk, only as internal PNG");
}
else {
if (as_png) {
@@ -175,17 +180,20 @@ static void rna_Image_update(Image *image, ReportList *reports)
ImBuf *ibuf = BKE_image_get_ibuf(image, NULL);
if (ibuf == NULL) {
- BKE_reportf(reports, RPT_ERROR, "Image \"%s\" does not have any image data", image->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Image '%s' does not have any image data", image->id.name + 2);
return;
}
- IMB_rect_from_float(ibuf);
+ if (ibuf->rect)
+ IMB_rect_from_float(ibuf);
+
+ ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
}
static void rna_Image_scale(Image *image, ReportList *reports, int width, int height)
{
if (!BKE_image_scale(image, width, height)) {
- BKE_reportf(reports, RPT_ERROR, "Image \"%s\" does not have any image data", image->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Image '%s' does not have any image data", image->id.name + 2);
}
}
@@ -201,7 +209,7 @@ static int rna_Image_gl_load(Image *image, ReportList *reports, int filter, int
ibuf = BKE_image_get_ibuf(image, NULL);
if (ibuf == NULL || ibuf->rect == NULL) {
- BKE_reportf(reports, RPT_ERROR, "Image \"%s\" does not have any image data", image->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Image '%s' does not have any image data", image->id.name + 2);
return (int)GL_INVALID_OPERATION;
}
@@ -292,9 +300,9 @@ void RNA_api_image(StructRNA *srna)
func = RNA_def_function(srna, "scale", "rna_Image_scale");
RNA_def_function_ui_description(func, "Scale the image in pixels");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
- parm = RNA_def_int(func, "width", 0, 1, 10000, "", "Width", 1, 10000);
+ parm = RNA_def_int(func, "width", 1, 1, 10000, "", "Width", 1, 10000);
RNA_def_property_flag(parm, PROP_REQUIRED);
- parm = RNA_def_int(func, "height", 0, 1, 10000, "", "Height", 1, 10000);
+ parm = RNA_def_int(func, "height", 1, 1, 10000, "", "Height", 1, 10000);
RNA_def_property_flag(parm, PROP_REQUIRED);
func = RNA_def_function(srna, "gl_touch", "rna_Image_gl_touch");
diff --git a/source/blender/makesrna/intern/rna_internal.h b/source/blender/makesrna/intern/rna_internal.h
index e8e40d307fb..6520f22fbf5 100644
--- a/source/blender/makesrna/intern/rna_internal.h
+++ b/source/blender/makesrna/intern/rna_internal.h
@@ -34,8 +34,14 @@
#define RNA_MAGIC ((int)~0)
+struct ColorBand;
struct ID;
struct IDProperty;
+struct Main;
+struct Mesh;
+struct Object;
+struct RenderEngine;
+struct ReportList;
struct SDNA;
struct Sequence;
@@ -259,6 +265,7 @@ void RNA_api_material(StructRNA *srna);
void RNA_api_mesh(struct StructRNA *srna);
void RNA_api_object(struct StructRNA *srna);
void RNA_api_object_base(struct StructRNA *srna);
+void RNA_api_pose(struct StructRNA *srna);
void RNA_api_pose_channel(struct StructRNA *srna);
void RNA_api_scene(struct StructRNA *srna);
void RNA_api_scene_render(struct StructRNA *srna);
@@ -352,7 +359,7 @@ typedef struct ArrayIterator {
void *free_ptr; /* will be freed if set */
int itemsize;
- /* array length with no skip functins applied, take care not to compare against index from animsys
+ /* array length with no skip functions applied, take care not to compare against index from animsys
* or python indices */
int length;
@@ -398,6 +405,11 @@ void rna_mtex_texture_slots_clear(struct ID *self, struct bContext *C, struct Re
int rna_IDMaterials_assign_int(struct PointerRNA *ptr, int key, const struct PointerRNA *assign_ptr);
+
+/* Internal functions that cycles uses so we need to declare (tsk tsk) */
+void rna_RenderLayer_rect_set(PointerRNA *ptr, const float *values);
+void rna_RenderPass_rect_set(PointerRNA *ptr, const float *values);
+
#endif /* __RNA_INTERNAL_H__ */
diff --git a/source/blender/makesrna/intern/rna_key.c b/source/blender/makesrna/intern/rna_key.c
index 5334c10c4c6..33bbaeec282 100644
--- a/source/blender/makesrna/intern/rna_key.c
+++ b/source/blender/makesrna/intern/rna_key.c
@@ -61,12 +61,12 @@ static Key *rna_ShapeKey_find_key(ID *id)
case ID_KE: return (Key *)id;
case ID_LT: return ((Lattice *)id)->key;
case ID_ME: return ((Mesh *)id)->key;
- case ID_OB: return ob_get_key((Object *)id);
+ case ID_OB: return BKE_key_from_object((Object *)id);
default: return NULL;
}
}
-void rna_ShapeKey_name_set(PointerRNA *ptr, const char *value)
+static void rna_ShapeKey_name_set(PointerRNA *ptr, const char *value)
{
KeyBlock *kb = ptr->data;
char oldname[sizeof(kb->name)];
@@ -360,7 +360,7 @@ static void rna_Key_update_data(Main *bmain, Scene *UNUSED(scene), PointerRNA *p
Object *ob;
for (ob = bmain->object.first; ob; ob = ob->id.next) {
- if (ob_get_key(ob) == key) {
+ if (BKE_key_from_object(ob) == key) {
DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
WM_main_add_notifier(NC_OBJECT | ND_MODIFIER, ob);
}
diff --git a/source/blender/makesrna/intern/rna_lattice.c b/source/blender/makesrna/intern/rna_lattice.c
index d4082cf3d9f..e4a29d9c674 100644
--- a/source/blender/makesrna/intern/rna_lattice.c
+++ b/source/blender/makesrna/intern/rna_lattice.c
@@ -240,6 +240,12 @@ static void rna_def_latticepoint(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Deformed Location", "");
RNA_def_property_update(prop, 0, "rna_Lattice_update_data");
+ prop = RNA_def_property(srna, "weight_softbody", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "weight");
+ RNA_def_property_range(prop, 0.01f, 100.0f);
+ RNA_def_property_ui_text(prop, "Weight", "Softbody goal weight");
+ RNA_def_property_update(prop, 0, "rna_Lattice_update_data");
+
prop = RNA_def_property(srna, "groups", PROP_COLLECTION, PROP_NONE);
RNA_def_property_collection_funcs(prop, "rna_LatticePoint_groups_begin", "rna_iterator_array_next",
"rna_iterator_array_end", "rna_iterator_array_get",
@@ -320,7 +326,7 @@ static void rna_def_lattice(BlenderRNA *brna)
RNA_def_property_collection_funcs(prop, "rna_Lattice_points_begin", "rna_iterator_array_next",
"rna_iterator_array_end", "rna_iterator_array_get", NULL, NULL, NULL, NULL);
RNA_def_property_ui_text(prop, "Points", "Points of the lattice");
-
+
/* pointers */
rna_def_animdata_common(srna);
}
diff --git a/source/blender/makesrna/intern/rna_main.c b/source/blender/makesrna/intern/rna_main.c
index 74b3c431183..04b8d2fa3df 100644
--- a/source/blender/makesrna/intern/rna_main.c
+++ b/source/blender/makesrna/intern/rna_main.c
@@ -51,7 +51,7 @@ static int rna_Main_is_dirty_get(PointerRNA *ptr)
/* XXX, not totally nice to do it this way, should store in main ? */
Main *bmain = (Main *)ptr->data;
wmWindowManager *wm;
- for (wm = bmain->wm.first; wm; wm = wm->id.next) {
+ if ((wm = bmain->wm.first)) {
return !wm->file_saved;
}
diff --git a/source/blender/makesrna/intern/rna_main_api.c b/source/blender/makesrna/intern/rna_main_api.c
index 307982e4bb1..cf9415a75e7 100644
--- a/source/blender/makesrna/intern/rna_main_api.c
+++ b/source/blender/makesrna/intern/rna_main_api.c
@@ -71,6 +71,7 @@
#include "BKE_speaker.h"
#include "BKE_movieclip.h"
#include "BKE_mask.h"
+#include "BKE_gpencil.h"
#include "DNA_armature_types.h"
#include "DNA_camera_types.h"
@@ -92,51 +93,58 @@
#include "DNA_node_types.h"
#include "DNA_movieclip_types.h"
#include "DNA_mask_types.h"
+#include "DNA_gpencil_types.h"
#include "ED_screen.h"
-Camera *rna_Main_cameras_new(Main *UNUSED(bmain), const char *name)
+#include "BLF_translation.h"
+
+static Camera *rna_Main_cameras_new(Main *UNUSED(bmain), const char *name)
{
ID *id = BKE_camera_add(name);
id_us_min(id);
return (Camera *)id;
}
-void rna_Main_cameras_remove(Main *bmain, ReportList *reports, struct Camera *camera)
+static void rna_Main_cameras_remove(Main *bmain, ReportList *reports, PointerRNA *camera_ptr)
{
- if (ID_REAL_USERS(camera) <= 0)
+ Camera *camera = camera_ptr->data;
+ if (ID_REAL_USERS(camera) <= 0) {
BKE_libblock_free(&bmain->camera, camera);
- else
- BKE_reportf(reports, RPT_ERROR, "Camera \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(camera_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Camera '%s' must have zero users to be removed, found %d",
camera->id.name + 2, ID_REAL_USERS(camera));
-
- /* XXX python now has invalid pointer? */
+ }
}
-Scene *rna_Main_scenes_new(Main *UNUSED(bmain), const char *name)
+static Scene *rna_Main_scenes_new(Main *UNUSED(bmain), const char *name)
{
return BKE_scene_add(name);
}
-void rna_Main_scenes_remove(Main *bmain, bContext *C, ReportList *reports, struct Scene *scene)
+static void rna_Main_scenes_remove(Main *bmain, bContext *C, ReportList *reports, PointerRNA *scene_ptr)
{
/* don't call BKE_libblock_free(...) directly */
- Scene *newscene;
+ Scene *scene = scene_ptr->data;
+ Scene *scene_new;
+
+ if ((scene_new = scene->id.prev) ||
+ (scene_new = scene->id.next))
+ {
+ bScreen *sc = CTX_wm_screen(C);
+ if (sc->scene == scene) {
+ ED_screen_set_scene(C, sc, scene_new);
+ }
- if (scene->id.prev)
- newscene = scene->id.prev;
- else if (scene->id.next)
- newscene = scene->id.next;
+ BKE_scene_unlink(bmain, scene, scene_new);
+ RNA_POINTER_INVALIDATE(scene_ptr);
+ }
else {
- BKE_reportf(reports, RPT_ERROR, "Scene \"%s\" is the last, cant ve removed", scene->id.name + 2);
- return;
+ BKE_reportf(reports, RPT_ERROR, "Scene '%s' is the last, cannot be removed", scene->id.name + 2);
}
-
- if (CTX_wm_screen(C)->scene == scene)
- ED_screen_set_scene(C, CTX_wm_screen(C), newscene);
-
- BKE_scene_unlink(bmain, scene, newscene);
}
-Object *rna_Main_objects_new(Main *UNUSED(bmain), ReportList *reports, const char *name, ID *data)
+static Object *rna_Main_objects_new(Main *UNUSED(bmain), ReportList *reports, const char *name, ID *data)
{
Object *ob;
int type = OB_EMPTY;
@@ -147,7 +155,7 @@ Object *rna_Main_objects_new(Main *UNUSED(bmain), ReportList *reports, const cha
type = OB_MESH;
break;
case ID_CU:
- type = BKE_curve_type_get((struct Curve *)data);
+ type = BKE_curve_type_get((Curve *)data);
break;
case ID_MB:
type = OB_MBALL;
@@ -173,7 +181,7 @@ Object *rna_Main_objects_new(Main *UNUSED(bmain), ReportList *reports, const cha
if (RNA_enum_id_from_value(id_type_items, GS(data->name), &idname) == 0)
idname = "UNKNOWN";
- BKE_reportf(reports, RPT_ERROR, "ID type '%s' is not valid for a object", idname);
+ BKE_reportf(reports, RPT_ERROR, "ID type '%s' is not valid for an object", idname);
return NULL;
}
}
@@ -190,165 +198,190 @@ Object *rna_Main_objects_new(Main *UNUSED(bmain), ReportList *reports, const cha
return ob;
}
-void rna_Main_objects_remove(Main *bmain, ReportList *reports, struct Object *object)
+static void rna_Main_objects_remove(Main *bmain, ReportList *reports, PointerRNA *object_ptr)
{
+ Object *object = object_ptr->data;
if (ID_REAL_USERS(object) <= 0) {
BKE_object_unlink(object); /* needed or ID pointers to this are not cleared */
BKE_libblock_free(&bmain->object, object);
+ RNA_POINTER_INVALIDATE(object_ptr);
}
else {
- BKE_reportf(reports, RPT_ERROR, "Object \"%s\" must have zero users to be removed, found %d",
+ BKE_reportf(reports, RPT_ERROR, "Object '%s' must have zero users to be removed, found %d",
object->id.name + 2, ID_REAL_USERS(object));
}
}
-Material *rna_Main_materials_new(Main *UNUSED(bmain), const char *name)
+static Material *rna_Main_materials_new(Main *UNUSED(bmain), const char *name)
{
ID *id = (ID *)BKE_material_add(name);
id_us_min(id);
return (Material *)id;
}
-void rna_Main_materials_remove(Main *bmain, ReportList *reports, struct Material *material)
+static void rna_Main_materials_remove(Main *bmain, ReportList *reports, PointerRNA *material_ptr)
{
- if (ID_REAL_USERS(material) <= 0)
+ Material *material = material_ptr->data;
+ if (ID_REAL_USERS(material) <= 0) {
BKE_libblock_free(&bmain->mat, material);
- else
- BKE_reportf(reports, RPT_ERROR, "Material \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(material_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Material '%s' must have zero users to be removed, found %d",
material->id.name + 2, ID_REAL_USERS(material));
-
- /* XXX python now has invalid pointer? */
+ }
}
-bNodeTree *rna_Main_nodetree_new(Main *UNUSED(bmain), const char *name, int type)
+static bNodeTree *rna_Main_nodetree_new(Main *UNUSED(bmain), const char *name, int type)
{
bNodeTree *tree = ntreeAddTree(name, type, NODE_GROUP);
id_us_min(&tree->id);
return tree;
}
-void rna_Main_nodetree_remove(Main *bmain, ReportList *reports, struct bNodeTree *tree)
+static void rna_Main_nodetree_remove(Main *bmain, ReportList *reports, PointerRNA *tree_ptr)
{
- if (ID_REAL_USERS(tree) <= 0)
+ bNodeTree *tree = tree_ptr->data;
+ if (ID_REAL_USERS(tree) <= 0) {
BKE_libblock_free(&bmain->nodetree, tree);
- else
- BKE_reportf(reports, RPT_ERROR, "Node Tree \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(tree_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Node tree '%s' must have zero users to be removed, found %d",
tree->id.name + 2, ID_REAL_USERS(tree));
-
- /* XXX python now has invalid pointer? */
+ }
}
-Mesh *rna_Main_meshes_new(Main *UNUSED(bmain), const char *name)
+static Mesh *rna_Main_meshes_new(Main *UNUSED(bmain), const char *name)
{
Mesh *me = BKE_mesh_add(name);
id_us_min(&me->id);
return me;
}
-void rna_Main_meshes_remove(Main *bmain, ReportList *reports, Mesh *mesh)
+static void rna_Main_meshes_remove(Main *bmain, ReportList *reports, PointerRNA *mesh_ptr)
{
- if (ID_REAL_USERS(mesh) <= 0)
+ Mesh *mesh = mesh_ptr->data;
+ if (ID_REAL_USERS(mesh) <= 0) {
BKE_libblock_free(&bmain->mesh, mesh);
- else
- BKE_reportf(reports, RPT_ERROR, "Mesh \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(mesh_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Mesh '%s' must have zero users to be removed, found %d",
mesh->id.name + 2, ID_REAL_USERS(mesh));
-
- /* XXX python now has invalid pointer? */
+ }
}
-Lamp *rna_Main_lamps_new(Main *UNUSED(bmain), const char *name, int type)
+static Lamp *rna_Main_lamps_new(Main *UNUSED(bmain), const char *name, int type)
{
Lamp *lamp = BKE_lamp_add(name);
lamp->type = type;
id_us_min(&lamp->id);
return lamp;
}
-void rna_Main_lamps_remove(Main *bmain, ReportList *reports, Lamp *lamp)
+static void rna_Main_lamps_remove(Main *bmain, ReportList *reports, PointerRNA *lamp_ptr)
{
- if (ID_REAL_USERS(lamp) <= 0)
+ Lamp *lamp = lamp_ptr->data;
+ if (ID_REAL_USERS(lamp) <= 0) {
BKE_libblock_free(&bmain->lamp, lamp);
- else
- BKE_reportf(reports, RPT_ERROR, "Lamp \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(lamp_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Lamp '%s' must have zero users to be removed, found %d",
lamp->id.name + 2, ID_REAL_USERS(lamp));
-
- /* XXX python now has invalid pointer? */
+ }
}
-Image *rna_Main_images_new(Main *UNUSED(bmain), const char *name, int width, int height, int alpha, int float_buffer)
+static Image *rna_Main_images_new(Main *UNUSED(bmain), const char *name, int width, int height, int alpha, int float_buffer)
{
float color[4] = {0.0, 0.0, 0.0, 1.0};
Image *image = BKE_image_add_generated(width, height, name, alpha ? 32 : 24, float_buffer, 0, color);
id_us_min(&image->id);
return image;
}
-Image *rna_Main_images_load(Main *UNUSED(bmain), ReportList *reports, const char *filepath)
+static Image *rna_Main_images_load(Main *UNUSED(bmain), ReportList *reports, const char *filepath)
{
Image *ima;
errno = 0;
ima = BKE_image_load(filepath);
- if (!ima)
- BKE_reportf(reports, RPT_ERROR, "Can't read: \"%s\", %s", filepath,
- errno ? strerror(errno) : "Unsupported image format");
+ if (!ima) {
+ BKE_reportf(reports, RPT_ERROR, "Cannot read '%s': %s", filepath,
+ errno ? strerror(errno) : TIP_("unsupported image format"));
+ }
return ima;
}
-void rna_Main_images_remove(Main *bmain, ReportList *reports, Image *image)
+static void rna_Main_images_remove(Main *bmain, ReportList *reports, PointerRNA *image_ptr)
{
- if (ID_REAL_USERS(image) <= 0)
+ Image *image = image_ptr->data;
+ if (ID_REAL_USERS(image) <= 0) {
BKE_libblock_free(&bmain->image, image);
- else
- BKE_reportf(reports, RPT_ERROR, "Image \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(image_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Image '%s' must have zero users to be removed, found %d",
image->id.name + 2, ID_REAL_USERS(image));
-
- /* XXX python now has invalid pointer? */
+ }
}
-Lattice *rna_Main_lattices_new(Main *UNUSED(bmain), const char *name)
+static Lattice *rna_Main_lattices_new(Main *UNUSED(bmain), const char *name)
{
Lattice *lt = BKE_lattice_add(name);
id_us_min(&lt->id);
return lt;
}
-void rna_Main_lattices_remove(Main *bmain, ReportList *reports, struct Lattice *lt)
+static void rna_Main_lattices_remove(Main *bmain, ReportList *reports, PointerRNA *lt_ptr)
{
- if (ID_REAL_USERS(lt) <= 0)
+ Lattice *lt = lt_ptr->data;
+ if (ID_REAL_USERS(lt) <= 0) {
BKE_libblock_free(&bmain->latt, lt);
- else
- BKE_reportf(reports, RPT_ERROR, "Lattice \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(lt_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Lattice '%s' must have zero users to be removed, found %d",
lt->id.name + 2, ID_REAL_USERS(lt));
+ }
}
-Curve *rna_Main_curves_new(Main *UNUSED(bmain), const char *name, int type)
+static Curve *rna_Main_curves_new(Main *UNUSED(bmain), const char *name, int type)
{
Curve *cu = BKE_curve_add(name, type);
id_us_min(&cu->id);
return cu;
}
-void rna_Main_curves_remove(Main *bmain, ReportList *reports, struct Curve *cu)
+static void rna_Main_curves_remove(Main *bmain, ReportList *reports, PointerRNA *cu_ptr)
{
- if (ID_REAL_USERS(cu) <= 0)
+ Curve *cu = cu_ptr->data;
+ if (ID_REAL_USERS(cu) <= 0) {
BKE_libblock_free(&bmain->curve, cu);
- else
- BKE_reportf(reports, RPT_ERROR, "Curve \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(cu_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Curve '%s' must have zero users to be removed, found %d",
cu->id.name + 2, ID_REAL_USERS(cu));
+ }
}
-MetaBall *rna_Main_metaballs_new(Main *UNUSED(bmain), const char *name)
+static MetaBall *rna_Main_metaballs_new(Main *UNUSED(bmain), const char *name)
{
MetaBall *mb = BKE_mball_add(name);
id_us_min(&mb->id);
return mb;
}
-void rna_Main_metaballs_remove(Main *bmain, ReportList *reports, struct MetaBall *mb)
+static void rna_Main_metaballs_remove(Main *bmain, ReportList *reports, PointerRNA *mb_ptr)
{
- if (ID_REAL_USERS(mb) <= 0)
+ MetaBall *mb = mb_ptr->data;
+ if (ID_REAL_USERS(mb) <= 0) {
BKE_libblock_free(&bmain->mball, mb);
- else
- BKE_reportf(reports, RPT_ERROR, "Metaball \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(mb_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Metaball '%s' must have zero users to be removed, found %d",
mb->id.name + 2, ID_REAL_USERS(mb));
+ }
}
-VFont *rna_Main_fonts_load(Main *bmain, ReportList *reports, const char *filepath)
+static VFont *rna_Main_fonts_load(Main *bmain, ReportList *reports, const char *filepath)
{
VFont *font;
@@ -356,109 +389,127 @@ VFont *rna_Main_fonts_load(Main *bmain, ReportList *reports, const char *filepat
font = BKE_vfont_load(bmain, filepath);
if (!font)
- BKE_reportf(reports, RPT_ERROR, "Can't read: \"%s\", %s", filepath,
- errno ? strerror(errno) : "Unsupported font format");
+ BKE_reportf(reports, RPT_ERROR, "Cannot read '%s': %s", filepath,
+ errno ? strerror(errno) : TIP_("unsupported font format"));
return font;
}
-void rna_Main_fonts_remove(Main *bmain, ReportList *reports, VFont *vfont)
+static void rna_Main_fonts_remove(Main *bmain, ReportList *reports, PointerRNA *vfont_ptr)
{
- if (ID_REAL_USERS(vfont) <= 0)
+ VFont *vfont = vfont_ptr->data;
+ if (ID_REAL_USERS(vfont) <= 0) {
BKE_libblock_free(&bmain->vfont, vfont);
- else
- BKE_reportf(reports, RPT_ERROR, "Font \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(vfont_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Font '%s' must have zero users to be removed, found %d",
vfont->id.name + 2, ID_REAL_USERS(vfont));
-
- /* XXX python now has invalid pointer? */
+ }
}
-Tex *rna_Main_textures_new(Main *UNUSED(bmain), const char *name, int type)
+static Tex *rna_Main_textures_new(Main *UNUSED(bmain), const char *name, int type)
{
Tex *tex = add_texture(name);
tex_set_type(tex, type);
id_us_min(&tex->id);
return tex;
}
-void rna_Main_textures_remove(Main *bmain, ReportList *reports, struct Tex *tex)
+static void rna_Main_textures_remove(Main *bmain, ReportList *reports, PointerRNA *tex_ptr)
{
- if (ID_REAL_USERS(tex) <= 0)
+ Tex *tex = tex_ptr->data;
+ if (ID_REAL_USERS(tex) <= 0) {
BKE_libblock_free(&bmain->tex, tex);
- else
- BKE_reportf(reports, RPT_ERROR, "Texture \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(tex_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Texture '%s' must have zero users to be removed, found %d",
tex->id.name + 2, ID_REAL_USERS(tex));
+ }
}
-Brush *rna_Main_brushes_new(Main *UNUSED(bmain), const char *name)
+static Brush *rna_Main_brushes_new(Main *UNUSED(bmain), const char *name)
{
Brush *brush = BKE_brush_add(name);
id_us_min(&brush->id);
return brush;
}
-void rna_Main_brushes_remove(Main *bmain, ReportList *reports, struct Brush *brush)
+static void rna_Main_brushes_remove(Main *bmain, ReportList *reports, PointerRNA *brush_ptr)
{
- if (ID_REAL_USERS(brush) <= 0)
+ Brush *brush = brush_ptr->data;
+ if (ID_REAL_USERS(brush) <= 0) {
BKE_libblock_free(&bmain->brush, brush);
- else
- BKE_reportf(reports, RPT_ERROR, "Brush \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(brush_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Brush '%s' must have zero users to be removed, found %d",
brush->id.name + 2, ID_REAL_USERS(brush));
+ }
}
-World *rna_Main_worlds_new(Main *UNUSED(bmain), const char *name)
+static World *rna_Main_worlds_new(Main *UNUSED(bmain), const char *name)
{
World *world = add_world(name);
id_us_min(&world->id);
return world;
}
-void rna_Main_worlds_remove(Main *bmain, ReportList *reports, struct World *world)
+static void rna_Main_worlds_remove(Main *bmain, ReportList *reports, PointerRNA *world_ptr)
{
- if (ID_REAL_USERS(world) <= 0)
+ Group *world = world_ptr->data;
+ if (ID_REAL_USERS(world) <= 0) {
BKE_libblock_free(&bmain->world, world);
- else
- BKE_reportf(reports, RPT_ERROR, "World \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(world_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "World '%s' must have zero users to be removed, found %d",
world->id.name + 2, ID_REAL_USERS(world));
+ }
}
-Group *rna_Main_groups_new(Main *UNUSED(bmain), const char *name)
+static Group *rna_Main_groups_new(Main *UNUSED(bmain), const char *name)
{
return add_group(name);
}
-void rna_Main_groups_remove(Main *bmain, Group *group)
+static void rna_Main_groups_remove(Main *bmain, PointerRNA *group_ptr)
{
+ Group *group = group_ptr->data;
BKE_group_unlink(group);
BKE_libblock_free(&bmain->group, group);
- /* XXX python now has invalid pointer? */
+ RNA_POINTER_INVALIDATE(group_ptr);
}
-Speaker *rna_Main_speakers_new(Main *UNUSED(bmain), const char *name)
+static Speaker *rna_Main_speakers_new(Main *UNUSED(bmain), const char *name)
{
Speaker *speaker = BKE_speaker_add(name);
id_us_min(&speaker->id);
return speaker;
}
-void rna_Main_speakers_remove(Main *bmain, ReportList *reports, Speaker *speaker)
+static void rna_Main_speakers_remove(Main *bmain, ReportList *reports, PointerRNA *speaker_ptr)
{
- if (ID_REAL_USERS(speaker) <= 0)
+ Speaker *speaker = speaker_ptr->data;
+ if (ID_REAL_USERS(speaker) <= 0) {
BKE_libblock_free(&bmain->speaker, speaker);
- else
- BKE_reportf(reports, RPT_ERROR, "Speaker \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(speaker_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Speaker '%s' must have zero users to be removed, found %d",
speaker->id.name + 2, ID_REAL_USERS(speaker));
-
- /* XXX python now has invalid pointer? */
+ }
}
-Text *rna_Main_texts_new(Main *UNUSED(bmain), const char *name)
+static Text *rna_Main_texts_new(Main *UNUSED(bmain), const char *name)
{
return BKE_text_add(name);
}
-void rna_Main_texts_remove(Main *bmain, Text *text)
+static void rna_Main_texts_remove(Main *bmain, PointerRNA *text_ptr)
{
+ Text *text = text_ptr->data;
BKE_text_unlink(bmain, text);
BKE_libblock_free(&bmain->text, text);
- /* XXX python now has invalid pointer? */
+ RNA_POINTER_INVALIDATE(text_ptr);
}
-Text *rna_Main_texts_load(Main *bmain, ReportList *reports, const char *filepath)
+static Text *rna_Main_texts_load(Main *bmain, ReportList *reports, const char *filepath)
{
Text *txt;
@@ -466,65 +517,71 @@ Text *rna_Main_texts_load(Main *bmain, ReportList *reports, const char *filepath
txt = BKE_text_load(filepath, bmain->name);
if (!txt)
- BKE_reportf(reports, RPT_ERROR, "Can't read: \"%s\", %s", filepath,
- errno ? strerror(errno) : "Unable to load text");
+ BKE_reportf(reports, RPT_ERROR, "Cannot read '%s': %s", filepath,
+ errno ? strerror(errno) : TIP_("unable to load text"));
return txt;
}
-bArmature *rna_Main_armatures_new(Main *UNUSED(bmain), const char *name)
+static bArmature *rna_Main_armatures_new(Main *UNUSED(bmain), const char *name)
{
bArmature *arm = BKE_armature_add(name);
id_us_min(&arm->id);
return arm;
}
-void rna_Main_armatures_remove(Main *bmain, ReportList *reports, bArmature *arm)
+static void rna_Main_armatures_remove(Main *bmain, ReportList *reports, PointerRNA *arm_ptr)
{
- if (ID_REAL_USERS(arm) <= 0)
+ bArmature *arm = arm_ptr->data;
+ if (ID_REAL_USERS(arm) <= 0) {
BKE_libblock_free(&bmain->armature, arm);
- else
- BKE_reportf(reports, RPT_ERROR, "Armature \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(arm_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Armature '%s' must have zero users to be removed, found %d",
arm->id.name + 2, ID_REAL_USERS(arm));
-
- /* XXX python now has invalid pointer? */
+ }
}
-bAction *rna_Main_actions_new(Main *UNUSED(bmain), const char *name)
+static bAction *rna_Main_actions_new(Main *UNUSED(bmain), const char *name)
{
bAction *act = add_empty_action(name);
id_us_min(&act->id);
act->id.flag &= ~LIB_FAKEUSER;
return act;
}
-void rna_Main_actions_remove(Main *bmain, ReportList *reports, bAction *act)
+static void rna_Main_actions_remove(Main *bmain, ReportList *reports, PointerRNA *act_ptr)
{
- if (ID_REAL_USERS(act) <= 0)
+ bAction *act = act_ptr->data;
+ if (ID_REAL_USERS(act) <= 0) {
BKE_libblock_free(&bmain->action, act);
- else
- BKE_reportf(reports, RPT_ERROR, "Action \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(act_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Action '%s' must have zero users to be removed, found %d",
act->id.name + 2, ID_REAL_USERS(act));
-
- /* XXX python now has invalid pointer? */
+ }
}
-ParticleSettings *rna_Main_particles_new(Main *bmain, const char *name)
+static ParticleSettings *rna_Main_particles_new(Main *bmain, const char *name)
{
ParticleSettings *part = psys_new_settings(name, bmain);
id_us_min(&part->id);
return part;
}
-void rna_Main_particles_remove(Main *bmain, ReportList *reports, ParticleSettings *part)
+static void rna_Main_particles_remove(Main *bmain, ReportList *reports, PointerRNA *part_ptr)
{
- if (ID_REAL_USERS(part) <= 0)
+ ParticleSettings *part = part_ptr->data;
+ if (ID_REAL_USERS(part) <= 0) {
BKE_libblock_free(&bmain->particle, part);
- else
- BKE_reportf(reports, RPT_ERROR, "Particle Settings \"%s\" must have zero users to be removed, found %d",
+ RNA_POINTER_INVALIDATE(part_ptr);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Particle settings '%s' must have zero users to be removed, found %d",
part->id.name + 2, ID_REAL_USERS(part));
-
- /* XXX python now has invalid pointer? */
+ }
}
-MovieClip *rna_Main_movieclip_load(Main *UNUSED(bmain), ReportList *reports, const char *filepath)
+static MovieClip *rna_Main_movieclip_load(Main *UNUSED(bmain), ReportList *reports, const char *filepath)
{
MovieClip *clip;
@@ -532,20 +589,21 @@ MovieClip *rna_Main_movieclip_load(Main *UNUSED(bmain), ReportList *reports, con
clip = BKE_movieclip_file_add(filepath);
if (!clip)
- BKE_reportf(reports, RPT_ERROR, "Can't read: \"%s\", %s.", filepath,
- errno ? strerror(errno) : "Unable to load movie clip");
+ BKE_reportf(reports, RPT_ERROR, "Cannot read '%s': %s", filepath,
+ errno ? strerror(errno) : TIP_("unable to load movie clip"));
return clip;
}
-void rna_Main_movieclips_remove(Main *bmain, MovieClip *clip)
+static void rna_Main_movieclips_remove(Main *bmain, PointerRNA *clip_ptr)
{
+ MovieClip *clip = clip_ptr->data;
BKE_movieclip_unlink(bmain, clip);
BKE_libblock_free(&bmain->movieclip, clip);
- /* XXX python now has invalid pointer? */
+ RNA_POINTER_INVALIDATE(clip_ptr);
}
-Mask *rna_Main_mask_new(Main *UNUSED(bmain), const char *name)
+static Mask *rna_Main_mask_new(Main *UNUSED(bmain), const char *name)
{
Mask *mask;
@@ -554,44 +612,58 @@ Mask *rna_Main_mask_new(Main *UNUSED(bmain), const char *name)
return mask;
}
-void rna_Main_masks_remove(Main *bmain, Mask *mask)
+static void rna_Main_masks_remove(Main *bmain, PointerRNA *mask_ptr)
{
+ Mask *mask = mask_ptr->data;
BKE_mask_free(bmain, mask);
BKE_libblock_free(&bmain->mask, mask);
- /* XXX python now has invalid pointer? */
+ RNA_POINTER_INVALIDATE(mask_ptr);
+}
+
+static void rna_Main_grease_pencil_remove(Main *bmain, ReportList *reports, PointerRNA *gpd_ptr)
+{
+ bGPdata *gpd = gpd_ptr->data;
+ if (ID_REAL_USERS(gpd) <= 0) {
+ BKE_gpencil_free(gpd);
+ BKE_libblock_free(&bmain->gpencil, gpd);
+ RNA_POINTER_INVALIDATE(gpd_ptr);
+ }
+ else
+ BKE_reportf(reports, RPT_ERROR, "Grease pencil '%s' must have zero users to be removed, found %d",
+ gpd->id.name + 2, ID_REAL_USERS(gpd));
}
/* tag functions, all the same */
-void rna_Main_cameras_tag(Main *bmain, int value) { tag_main_lb(&bmain->camera, value); }
-void rna_Main_scenes_tag(Main *bmain, int value) { tag_main_lb(&bmain->scene, value); }
-void rna_Main_objects_tag(Main *bmain, int value) { tag_main_lb(&bmain->object, value); }
-void rna_Main_materials_tag(Main *bmain, int value) { tag_main_lb(&bmain->mat, value); }
-void rna_Main_node_groups_tag(Main *bmain, int value) { tag_main_lb(&bmain->nodetree, value); }
-void rna_Main_meshes_tag(Main *bmain, int value) { tag_main_lb(&bmain->mesh, value); }
-void rna_Main_lamps_tag(Main *bmain, int value) { tag_main_lb(&bmain->lamp, value); }
-void rna_Main_libraries_tag(Main *bmain, int value) { tag_main_lb(&bmain->library, value); }
-void rna_Main_screens_tag(Main *bmain, int value) { tag_main_lb(&bmain->screen, value); }
-void rna_Main_window_managers_tag(Main *bmain, int value) { tag_main_lb(&bmain->wm, value); }
-void rna_Main_images_tag(Main *bmain, int value) { tag_main_lb(&bmain->image, value); }
-void rna_Main_lattices_tag(Main *bmain, int value) { tag_main_lb(&bmain->latt, value); }
-void rna_Main_curves_tag(Main *bmain, int value) { tag_main_lb(&bmain->curve, value); }
-void rna_Main_metaballs_tag(Main *bmain, int value) { tag_main_lb(&bmain->mball, value); }
-void rna_Main_fonts_tag(Main *bmain, int value) { tag_main_lb(&bmain->vfont, value); }
-void rna_Main_textures_tag(Main *bmain, int value) { tag_main_lb(&bmain->tex, value); }
-void rna_Main_brushes_tag(Main *bmain, int value) { tag_main_lb(&bmain->brush, value); }
-void rna_Main_worlds_tag(Main *bmain, int value) { tag_main_lb(&bmain->world, value); }
-void rna_Main_groups_tag(Main *bmain, int value) { tag_main_lb(&bmain->group, value); }
-void rna_Main_shape_keys_tag(Main *bmain, int value) { tag_main_lb(&bmain->key, value); }
-void rna_Main_scripts_tag(Main *bmain, int value) { tag_main_lb(&bmain->script, value); }
-void rna_Main_texts_tag(Main *bmain, int value) { tag_main_lb(&bmain->text, value); }
-void rna_Main_speakers_tag(Main *bmain, int value) { tag_main_lb(&bmain->speaker, value); }
-void rna_Main_sounds_tag(Main *bmain, int value) { tag_main_lb(&bmain->sound, value); }
-void rna_Main_armatures_tag(Main *bmain, int value) { tag_main_lb(&bmain->armature, value); }
-void rna_Main_actions_tag(Main *bmain, int value) { tag_main_lb(&bmain->action, value); }
-void rna_Main_particles_tag(Main *bmain, int value) { tag_main_lb(&bmain->particle, value); }
-void rna_Main_gpencil_tag(Main *bmain, int value) { tag_main_lb(&bmain->gpencil, value); }
-void rna_Main_movieclips_tag(Main *bmain, int value) { tag_main_lb(&bmain->movieclip, value); }
-void rna_Main_masks_tag(Main *bmain, int value) { tag_main_lb(&bmain->mask, value); }
+static void rna_Main_cameras_tag(Main *bmain, int value) { tag_main_lb(&bmain->camera, value); }
+static void rna_Main_scenes_tag(Main *bmain, int value) { tag_main_lb(&bmain->scene, value); }
+static void rna_Main_objects_tag(Main *bmain, int value) { tag_main_lb(&bmain->object, value); }
+static void rna_Main_materials_tag(Main *bmain, int value) { tag_main_lb(&bmain->mat, value); }
+static void rna_Main_node_groups_tag(Main *bmain, int value) { tag_main_lb(&bmain->nodetree, value); }
+static void rna_Main_meshes_tag(Main *bmain, int value) { tag_main_lb(&bmain->mesh, value); }
+static void rna_Main_lamps_tag(Main *bmain, int value) { tag_main_lb(&bmain->lamp, value); }
+static void rna_Main_libraries_tag(Main *bmain, int value) { tag_main_lb(&bmain->library, value); }
+static void rna_Main_screens_tag(Main *bmain, int value) { tag_main_lb(&bmain->screen, value); }
+static void rna_Main_window_managers_tag(Main *bmain, int value) { tag_main_lb(&bmain->wm, value); }
+static void rna_Main_images_tag(Main *bmain, int value) { tag_main_lb(&bmain->image, value); }
+static void rna_Main_lattices_tag(Main *bmain, int value) { tag_main_lb(&bmain->latt, value); }
+static void rna_Main_curves_tag(Main *bmain, int value) { tag_main_lb(&bmain->curve, value); }
+static void rna_Main_metaballs_tag(Main *bmain, int value) { tag_main_lb(&bmain->mball, value); }
+static void rna_Main_fonts_tag(Main *bmain, int value) { tag_main_lb(&bmain->vfont, value); }
+static void rna_Main_textures_tag(Main *bmain, int value) { tag_main_lb(&bmain->tex, value); }
+static void rna_Main_brushes_tag(Main *bmain, int value) { tag_main_lb(&bmain->brush, value); }
+static void rna_Main_worlds_tag(Main *bmain, int value) { tag_main_lb(&bmain->world, value); }
+static void rna_Main_groups_tag(Main *bmain, int value) { tag_main_lb(&bmain->group, value); }
+// static void rna_Main_shape_keys_tag(Main *bmain, int value) { tag_main_lb(&bmain->key, value); }
+// static void rna_Main_scripts_tag(Main *bmain, int value) { tag_main_lb(&bmain->script, value); }
+static void rna_Main_texts_tag(Main *bmain, int value) { tag_main_lb(&bmain->text, value); }
+static void rna_Main_speakers_tag(Main *bmain, int value) { tag_main_lb(&bmain->speaker, value); }
+static void rna_Main_sounds_tag(Main *bmain, int value) { tag_main_lb(&bmain->sound, value); }
+static void rna_Main_armatures_tag(Main *bmain, int value) { tag_main_lb(&bmain->armature, value); }
+static void rna_Main_actions_tag(Main *bmain, int value) { tag_main_lb(&bmain->action, value); }
+static void rna_Main_particles_tag(Main *bmain, int value) { tag_main_lb(&bmain->particle, value); }
+static void rna_Main_gpencil_tag(Main *bmain, int value) { tag_main_lb(&bmain->gpencil, value); }
+static void rna_Main_movieclips_tag(Main *bmain, int value) { tag_main_lb(&bmain->movieclip, value); }
+static void rna_Main_masks_tag(Main *bmain, int value) { tag_main_lb(&bmain->mask, value); }
static int rna_Main_cameras_is_updated_get(PointerRNA *ptr) { return DAG_id_type_tagged(ptr->data, ID_CA); }
static int rna_Main_scenes_is_updated_get(PointerRNA *ptr) { return DAG_id_type_tagged(ptr->data, ID_SCE); }
@@ -635,6 +707,8 @@ void RNA_api_main(StructRNA *srna)
RNA_def_property_flag(parm, PROP_REQUIRED);
parm = RNA_def_pointer(func, "image", "Image", "", "New image");
RNA_def_function_return(func, parm);
+#else
+ (void)srna;
#endif
}
@@ -662,7 +736,8 @@ void RNA_def_main_cameras(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a camera from the current blendfile");
parm = RNA_def_pointer(func, "camera", "Camera", "", "Camera to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_cameras_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -697,7 +772,8 @@ void RNA_def_main_scenes(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_CONTEXT | FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a scene from the current blendfile");
parm = RNA_def_pointer(func, "scene", "Scene", "", "Scene to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_scenes_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -736,7 +812,8 @@ void RNA_def_main_objects(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove a object from the current blendfile");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "object", "Object", "", "Object to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_objects_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -771,7 +848,8 @@ void RNA_def_main_materials(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a material from the current blendfile");
parm = RNA_def_pointer(func, "material", "Material", "", "Material to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_materials_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -814,7 +892,8 @@ void RNA_def_main_node_groups(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a node tree from the current blendfile");
parm = RNA_def_pointer(func, "tree", "NodeTree", "", "Node tree to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_node_groups_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -848,7 +927,8 @@ void RNA_def_main_meshes(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a mesh from the current blendfile");
parm = RNA_def_pointer(func, "mesh", "Mesh", "", "Mesh to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_meshes_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -884,7 +964,8 @@ void RNA_def_main_lamps(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a lamp from the current blendfile");
parm = RNA_def_pointer(func, "lamp", "Lamp", "", "Lamp to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_lamps_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -973,9 +1054,9 @@ void RNA_def_main_images(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Add a new image to the main database");
parm = RNA_def_string(func, "name", "Image", 0, "", "New name for the datablock");
RNA_def_property_flag(parm, PROP_REQUIRED);
- parm = RNA_def_int(func, "width", 1024, 1, INT_MAX, "", "Width of the image", 0, INT_MAX);
+ parm = RNA_def_int(func, "width", 1024, 1, INT_MAX, "", "Width of the image", 1, INT_MAX);
RNA_def_property_flag(parm, PROP_REQUIRED);
- parm = RNA_def_int(func, "height", 1024, 1, INT_MAX, "", "Height of the image", 0, INT_MAX);
+ parm = RNA_def_int(func, "height", 1024, 1, INT_MAX, "", "Height of the image", 1, INT_MAX);
RNA_def_property_flag(parm, PROP_REQUIRED);
RNA_def_boolean(func, "alpha", 0, "Alpha", "Use alpha channel");
RNA_def_boolean(func, "float_buffer", 0, "Float Buffer", "Create an image with floating point color");
@@ -996,7 +1077,8 @@ void RNA_def_main_images(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove an image from the current blendfile");
parm = RNA_def_pointer(func, "image", "Image", "", "Image to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_images_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1031,7 +1113,8 @@ void RNA_def_main_lattices(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a lattice from the current blendfile");
parm = RNA_def_pointer(func, "lattice", "Lattice", "", "Lattice to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_lattices_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1067,7 +1150,8 @@ void RNA_def_main_curves(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a curve from the current blendfile");
parm = RNA_def_pointer(func, "curve", "Curve", "", "Curve to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_curves_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1101,7 +1185,8 @@ void RNA_def_main_metaballs(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a metaball from the current blendfile");
parm = RNA_def_pointer(func, "metaball", "MetaBall", "", "Metaball to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_metaballs_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1136,7 +1221,8 @@ void RNA_def_main_fonts(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a font from the current blendfile");
parm = RNA_def_pointer(func, "vfont", "VectorFont", "", "Font to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_fonts_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1172,7 +1258,8 @@ void RNA_def_main_textures(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a texture from the current blendfile");
parm = RNA_def_pointer(func, "texture", "Texture", "", "Texture to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_textures_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1206,7 +1293,8 @@ void RNA_def_main_brushes(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a brush from the current blendfile");
parm = RNA_def_pointer(func, "brush", "Brush", "", "Brush to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_brushes_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1241,7 +1329,8 @@ void RNA_def_main_worlds(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a world from the current blendfile");
parm = RNA_def_pointer(func, "world", "World", "", "World to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_worlds_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1275,7 +1364,8 @@ void RNA_def_main_groups(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "remove", "rna_Main_groups_remove");
RNA_def_function_ui_description(func, "Remove a group from the current blendfile");
parm = RNA_def_pointer(func, "group", "Group", "", "Group to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_groups_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1310,7 +1400,8 @@ void RNA_def_main_speakers(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a speaker from the current blendfile");
parm = RNA_def_pointer(func, "speaker", "Speaker", "", "Speaker to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_speakers_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1344,7 +1435,8 @@ void RNA_def_main_texts(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "remove", "rna_Main_texts_remove");
RNA_def_function_ui_description(func, "Remove a text from the current blendfile");
parm = RNA_def_pointer(func, "text", "Text", "", "Text to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
/* load func */
func = RNA_def_function(srna, "load", "rna_Main_texts_load");
@@ -1412,7 +1504,8 @@ void RNA_def_main_armatures(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a armature from the current blendfile");
parm = RNA_def_pointer(func, "armature", "Armature", "", "Armature to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_armatures_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1446,7 +1539,8 @@ void RNA_def_main_actions(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a action from the current blendfile");
parm = RNA_def_pointer(func, "action", "Action", "", "Action to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_actions_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1480,7 +1574,8 @@ void RNA_def_main_particles(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a particle settings instance from the current blendfile");
parm = RNA_def_pointer(func, "particle", "ParticleSettings", "", "Particle Settings to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "tag", "rna_Main_particles_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1507,6 +1602,21 @@ void RNA_def_main_gpencil(BlenderRNA *brna, PropertyRNA *cprop)
parm = RNA_def_boolean(func, "value", 0, "Value", "");
RNA_def_property_flag(parm, PROP_REQUIRED);
+ func = RNA_def_function(srna, "new", "gpencil_data_addnew");
+ RNA_def_function_flag(func, FUNC_NO_SELF);
+ parm = RNA_def_string(func, "name", "GreasePencil", 0, "", "New name for the datablock");
+ RNA_def_property_flag(parm, PROP_REQUIRED);
+ /* return type */
+ parm = RNA_def_pointer(func, "grease_pencil", "GreasePencil", "", "New grease pencil datablock");
+ RNA_def_function_return(func, parm);
+
+ func = RNA_def_function(srna, "remove", "rna_Main_grease_pencil_remove");
+ RNA_def_function_flag(func, FUNC_USE_REPORTS);
+ RNA_def_function_ui_description(func, "Remove a grease pencil instance from the current blendfile");
+ parm = RNA_def_pointer(func, "grease_pencil", "GreasePencil", "", "Grease Pencil to remove");
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
+
prop = RNA_def_property(srna, "is_updated", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_boolean_funcs(prop, "rna_Main_gpencil_is_updated_get", NULL);
@@ -1530,7 +1640,8 @@ void RNA_def_main_movieclips(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "remove", "rna_Main_movieclips_remove");
RNA_def_function_ui_description(func, "Remove a movie clip from the current blendfile.");
parm = RNA_def_pointer(func, "clip", "MovieClip", "", "Movie clip to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
/* load func */
func = RNA_def_function(srna, "load", "rna_Main_movieclip_load");
@@ -1561,7 +1672,7 @@ void RNA_def_main_masks(BlenderRNA *brna, PropertyRNA *cprop)
/* new func */
func = RNA_def_function(srna, "new", "rna_Main_mask_new");
RNA_def_function_ui_description(func, "Add a new mask with a given name to the main database");
- parm = RNA_def_string_file_path(func, "name", "", MAX_ID_NAME - 2, "Mask", "Name of new mask datablock");
+ RNA_def_string_file_path(func, "name", "", MAX_ID_NAME - 2, "Mask", "Name of new mask datablock");
/* return type */
parm = RNA_def_pointer(func, "mask", "Mask", "", "New mask datablock");
RNA_def_function_return(func, parm);
@@ -1570,7 +1681,8 @@ void RNA_def_main_masks(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "remove", "rna_Main_masks_remove");
RNA_def_function_ui_description(func, "Remove a masks from the current blendfile.");
parm = RNA_def_pointer(func, "mask", "Mask", "", "Mask to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
#endif
diff --git a/source/blender/makesrna/intern/rna_mask.c b/source/blender/makesrna/intern/rna_mask.c
index 719baed8edb..56caa254a59 100644
--- a/source/blender/makesrna/intern/rna_mask.c
+++ b/source/blender/makesrna/intern/rna_mask.c
@@ -193,7 +193,7 @@ static void rna_MaskLayer_splines_begin(CollectionPropertyIterator *iter, Pointe
rna_iterator_listbase_begin(iter, &masklay->splines, NULL);
}
-void rna_MaskLayer_name_set(PointerRNA *ptr, const char *value)
+static void rna_MaskLayer_name_set(PointerRNA *ptr, const char *value)
{
Mask *mask = (Mask *)ptr->id.data;
MaskLayer *masklay = (MaskLayer *)ptr->data;
@@ -315,14 +315,16 @@ static MaskLayer *rna_Mask_layers_new(Mask *mask, const char *name)
return masklay;
}
-void rna_Mask_layers_remove(Mask *mask, ReportList *reports, MaskLayer *masklay)
+static void rna_Mask_layers_remove(Mask *mask, ReportList *reports, PointerRNA *masklay_ptr)
{
+ MaskLayer *masklay = masklay_ptr->data;
if (BLI_findindex(&mask->masklayers, masklay) == -1) {
- BKE_reportf(reports, RPT_ERROR, "MaskLayer '%s' not found in mask '%s'", masklay->name, mask->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Mask layer '%s' not found in mask '%s'", masklay->name, mask->id.name + 2);
return;
}
BKE_mask_layer_remove(mask, masklay);
+ RNA_POINTER_INVALIDATE(masklay_ptr);
WM_main_add_notifier(NC_MASK | NA_EDITED, mask);
}
@@ -705,7 +707,9 @@ static void rna_def_masklayers(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "remove", "rna_Mask_layers_remove");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove layer from this mask");
- RNA_def_pointer(func, "layer", "MaskLayer", "", "Shape to be removed");
+ parm = RNA_def_pointer(func, "layer", "MaskLayer", "", "Shape to be removed");
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
/* clear all layers */
func = RNA_def_function(srna, "clear", "rna_Mask_layers_clear");
diff --git a/source/blender/makesrna/intern/rna_material.c b/source/blender/makesrna/intern/rna_material.c
index 4523858d639..9232ae098ea 100644
--- a/source/blender/makesrna/intern/rna_material.c
+++ b/source/blender/makesrna/intern/rna_material.c
@@ -45,7 +45,6 @@ static EnumPropertyItem prop_texture_coordinates_items[] = {
{TEXCO_ORCO, "ORCO", 0, "Generated", "Use the original undeformed coordinates of the object"},
{TEXCO_STRAND, "STRAND", 0, "Strand / Particle",
"Use normalized strand texture coordinate (1D) or particle age (X) and trail position (Y)"},
- {TEXCO_STICKY, "STICKY", 0, "Sticky", "Use mesh's sticky coordinates for the texture coordinates"},
{TEXCO_WINDOW, "WINDOW", 0, "Window", "Use screen coordinates as texture coordinates"},
{TEXCO_NORM, "NORMAL", 0, "Normal", "Use normal vector as texture coordinates"},
{TEXCO_REFL, "REFLECTION", 0, "Reflection", "Use reflection vector as texture coordinates"},
@@ -82,12 +81,14 @@ EnumPropertyItem ramp_blend_items[] = {
#include "MEM_guardedalloc.h"
#include "DNA_node_types.h"
+#include "DNA_object_types.h"
#include "BKE_depsgraph.h"
#include "BKE_main.h"
#include "BKE_material.h"
#include "BKE_texture.h"
#include "BKE_node.h"
+#include "BKE_paint.h"
#include "ED_node.h"
@@ -106,7 +107,18 @@ static void rna_Material_update(Main *UNUSED(bmain), Scene *scene, PointerRNA *p
}
}
-static void rna_Material_draw_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
+static void rna_Material_update_previews(Main *bmain, Scene *scene, PointerRNA *ptr)
+{
+ Material *ma = ptr->id.data;
+
+ if (ma->nodetree)
+ ntreeClearPreview(ma->nodetree);
+
+ rna_Material_update(bmain, scene, ptr);
+}
+
+
+static void rna_Material_draw_update(Main *UNUSED(bmain), Scene *scene, PointerRNA *ptr)
{
Material *ma = ptr->id.data;
@@ -303,7 +315,6 @@ static EnumPropertyItem *rna_Material_texture_coordinates_itemf(bContext *UNUSED
else if (ELEM3(ma->material_type, MA_TYPE_SURFACE, MA_TYPE_HALO, MA_TYPE_WIRE)) {
RNA_enum_items_add_value(&item, &totitem, prop_texture_coordinates_items, TEXCO_UV);
RNA_enum_items_add_value(&item, &totitem, prop_texture_coordinates_items, TEXCO_STRAND);
- RNA_enum_items_add_value(&item, &totitem, prop_texture_coordinates_items, TEXCO_STICKY);
RNA_enum_items_add_value(&item, &totitem, prop_texture_coordinates_items, TEXCO_WINDOW);
RNA_enum_items_add_value(&item, &totitem, prop_texture_coordinates_items, TEXCO_NORM);
RNA_enum_items_add_value(&item, &totitem, prop_texture_coordinates_items, TEXCO_REFL);
@@ -321,7 +332,7 @@ MTex *rna_mtex_texture_slots_add(ID *self_id, struct bContext *C, ReportList *re
{
MTex *mtex = add_mtex_id(self_id, -1);
if (mtex == NULL) {
- BKE_reportf(reports, RPT_ERROR, "maximum number of textures added %d", MAX_MTEX);
+ BKE_reportf(reports, RPT_ERROR, "Maximum number of textures added %d", MAX_MTEX);
return NULL;
}
@@ -336,7 +347,7 @@ MTex *rna_mtex_texture_slots_create(ID *self_id, struct bContext *C, ReportList
MTex *mtex;
if (index < 0 || index >= MAX_MTEX) {
- BKE_reportf(reports, RPT_ERROR, "index %d is invalid", index);
+ BKE_reportf(reports, RPT_ERROR, "Index %d is invalid", index);
return NULL;
}
@@ -356,12 +367,12 @@ void rna_mtex_texture_slots_clear(ID *self_id, struct bContext *C, ReportList *r
give_active_mtex(self_id, &mtex_ar, &act);
if (mtex_ar == NULL) {
- BKE_report(reports, RPT_ERROR, "mtex not found for this type");
+ BKE_report(reports, RPT_ERROR, "Mtex not found for this type");
return;
}
if (index < 0 || index >= MAX_MTEX) {
- BKE_reportf(reports, RPT_ERROR, "index %d is invalid", index);
+ BKE_reportf(reports, RPT_ERROR, "Index %d is invalid", index);
return;
}
@@ -470,6 +481,12 @@ static void rna_def_material_mtex(BlenderRNA *brna)
"from their parent");
RNA_def_property_update(prop, 0, "rna_Material_update");
+ prop = RNA_def_property(srna, "use_map_to_bounds", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "texflag", MTEX_MAPTO_BOUNDS);
+ RNA_def_property_ui_text(prop, "Map to Bounds",
+ "Map coordinates in object bounds");
+ RNA_def_property_update(prop, 0, "rna_Material_update");
+
prop = RNA_def_property(srna, "use_from_original", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "texflag", MTEX_OB_DUPLI_ORIG);
RNA_def_property_ui_text(prop, "From Original",
@@ -1751,7 +1768,7 @@ void RNA_def_material(BlenderRNA *brna)
RNA_def_property_enum_sdna(prop, NULL, "pr_type");
RNA_def_property_enum_items(prop, preview_type_items);
RNA_def_property_ui_text(prop, "Preview render type", "Type of preview render");
- RNA_def_property_update(prop, 0, "rna_Material_update");
+ RNA_def_property_update(prop, 0, "rna_Material_update_previews");
prop = RNA_def_property(srna, "ambient", PROP_FLOAT, PROP_FACTOR);
RNA_def_property_float_sdna(prop, NULL, "amb");
@@ -1819,7 +1836,12 @@ void RNA_def_material(BlenderRNA *brna)
"Material uses the light group exclusively - these lamps are excluded "
"from other scene lighting");
RNA_def_property_update(prop, 0, "rna_Material_update");
-
+
+ prop = RNA_def_property(srna, "use_light_group_local", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "shade_flag", MA_GROUP_LOCAL);
+ RNA_def_property_ui_text(prop, "Light Group Local", "When linked in, material uses local light group with the same name");
+ RNA_def_property_update(prop, 0, "rna_Material_update");
+
prop = RNA_def_property(srna, "use_raytrace", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "mode", MA_TRACEBLE);
RNA_def_property_ui_text(prop, "Traceable",
@@ -1939,6 +1961,12 @@ void RNA_def_material(BlenderRNA *brna)
"- for anisotropic shading effects");
RNA_def_property_update(prop, 0, "rna_Material_update");
+ prop = RNA_def_property(srna, "use_uv_project", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "mapflag", MA_MAPFLAG_UVPROJECT);
+ RNA_def_property_ui_text(prop, "UV Project",
+ "Use to ensure UV interpolation is correct for camera projections (use with UV project modifier)");
+ RNA_def_property_update(prop, 0, "rna_Material_update");
+
/* nested structs */
prop = RNA_def_property(srna, "raytrace_mirror", PROP_POINTER, PROP_NONE);
RNA_def_property_flag(prop, PROP_NEVER_NULL);
diff --git a/source/blender/makesrna/intern/rna_material_api.c b/source/blender/makesrna/intern/rna_material_api.c
index 538a4c99df4..c7441f92c33 100644
--- a/source/blender/makesrna/intern/rna_material_api.c
+++ b/source/blender/makesrna/intern/rna_material_api.c
@@ -31,15 +31,19 @@
#include <stdlib.h>
#include <stdio.h>
+#include "BLI_utildefines.h"
+
#include "RNA_define.h"
#include "DNA_material_types.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#else
-void RNA_api_material(StructRNA *srna)
+void RNA_api_material(StructRNA *UNUSED(srna))
{
/* FunctionRNA *func; */
/* PropertyRNA *parm; */
diff --git a/source/blender/makesrna/intern/rna_mesh.c b/source/blender/makesrna/intern/rna_mesh.c
index fe5f8e574a0..f0b84332d07 100644
--- a/source/blender/makesrna/intern/rna_mesh.c
+++ b/source/blender/makesrna/intern/rna_mesh.c
@@ -149,7 +149,7 @@ void rna_Mesh_update_draw(Main *bmain, Scene *scene, PointerRNA *ptr)
}
-void rna_Mesh_update_vertmask(Main *bmain, Scene *scene, PointerRNA *ptr)
+static void rna_Mesh_update_vertmask(Main *bmain, Scene *scene, PointerRNA *ptr)
{
Mesh *me = ptr->data;
if ((me->editflag & ME_EDIT_VERT_SEL) && (me->editflag & ME_EDIT_PAINT_MASK)) {
@@ -158,7 +158,7 @@ void rna_Mesh_update_vertmask(Main *bmain, Scene *scene, PointerRNA *ptr)
rna_Mesh_update_draw(bmain, scene, ptr);
}
-void rna_Mesh_update_facemask(Main *bmain, Scene *scene, PointerRNA *ptr)
+static void rna_Mesh_update_facemask(Main *bmain, Scene *scene, PointerRNA *ptr)
{
Mesh *me = ptr->data;
if ((me->editflag & ME_EDIT_VERT_SEL) && (me->editflag & ME_EDIT_PAINT_MASK)) {
@@ -224,7 +224,7 @@ static void rna_MeshPolygon_normal_get(PointerRNA *ptr, float *values)
MPoly *mp = (MPoly *)ptr->data;
/* BMESH_TODO: might be faster to look for a CD_NORMALS layer and use that */
- mesh_calc_poly_normal(mp, me->mloop + mp->loopstart, me->mvert, values);
+ BKE_mesh_calc_poly_normal(mp, me->mloop + mp->loopstart, me->mvert, values);
}
static float rna_MeshPolygon_area_get(PointerRNA *ptr)
@@ -1204,11 +1204,6 @@ static char *rna_MeshColor_path(PointerRNA *ptr)
return rna_LoopCustomData_data_path(ptr, "vertex_colors", CD_MLOOPCOL);
}
-static char *rna_MeshSticky_path(PointerRNA *ptr)
-{
- return BLI_sprintfN("sticky[%d]", (int)((MSticky *)ptr->data - rna_mesh(ptr)->msticky));
-}
-
static char *rna_MeshIntPropertyLayer_path(PointerRNA *ptr)
{
return BLI_sprintfN("int_layers[\"%s\"]", ((CustomDataLayer *)ptr->data)->name);
@@ -1280,12 +1275,12 @@ static PointerRNA rna_Mesh_tessface_vertex_color_new(struct Mesh *me, struct bCo
int index;
if (me->edit_btmesh) {
- BKE_report(reports, RPT_ERROR, "Can't add tessface colors's in editmode");
+ BKE_report(reports, RPT_ERROR, "Cannot add tessface colors in edit mode");
return PointerRNA_NULL;
}
if (me->mpoly) {
- BKE_report(reports, RPT_ERROR, "Can't add tessface colors's when MPoly's exist");
+ BKE_report(reports, RPT_ERROR, "Cannot add tessface colors when MPoly's exist");
return PointerRNA_NULL;
}
@@ -1373,12 +1368,12 @@ static PointerRNA rna_Mesh_tessface_uv_texture_new(struct Mesh *me, struct bCont
int index;
if (me->edit_btmesh) {
- BKE_report(reports, RPT_ERROR, "Can't add tessface uv's in editmode");
+ BKE_report(reports, RPT_ERROR, "Cannot add tessface uv's in edit mode");
return PointerRNA_NULL;
}
if (me->mpoly) {
- BKE_report(reports, RPT_ERROR, "Can't add tessface uv's when MPoly's exist");
+ BKE_report(reports, RPT_ERROR, "Cannot add tessface uv's when MPoly's exist");
return PointerRNA_NULL;
}
@@ -1957,21 +1952,6 @@ static void rna_def_mtexpoly(BlenderRNA *brna)
#endif
}
-static void rna_def_msticky(BlenderRNA *brna)
-{
- StructRNA *srna;
- PropertyRNA *prop;
-
- srna = RNA_def_struct(brna, "MeshSticky", NULL);
- RNA_def_struct_sdna(srna, "MSticky");
- RNA_def_struct_ui_text(srna, "Mesh Vertex Sticky Texture Coordinate", "Sticky texture coordinate");
- RNA_def_struct_path_func(srna, "rna_MeshSticky_path");
-
- prop = RNA_def_property(srna, "co", PROP_FLOAT, PROP_XYZ);
- RNA_def_property_ui_text(prop, "Location", "Sticky texture coordinate location");
- RNA_def_property_update(prop, 0, "rna_Mesh_update_data");
-}
-
static void rna_def_mcol(BlenderRNA *brna)
{
StructRNA *srna;
@@ -2414,7 +2394,8 @@ static void rna_def_loop_colors(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove a vertex color layer");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "layer", "Layer", "", "The layer to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
#endif
prop = RNA_def_property(srna, "active", PROP_POINTER, PROP_UNSIGNED);
@@ -2591,7 +2572,8 @@ static void rna_def_uv_textures(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove a vertex color layer");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "layer", "Layer", "", "The layer to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
#endif
prop = RNA_def_property(srna, "active", PROP_POINTER, PROP_UNSIGNED);
@@ -2609,7 +2591,7 @@ static void rna_def_uv_textures(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_property_update(prop, 0, "rna_Mesh_update_data");
}
-static void rna_def_skin_vertices(BlenderRNA *brna, PropertyRNA *cprop)
+static void rna_def_skin_vertices(BlenderRNA *brna, PropertyRNA *UNUSED(cprop))
{
StructRNA *srna;
PropertyRNA *prop;
@@ -2696,11 +2678,6 @@ static void rna_def_mesh(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Polygons", "Polygons of the mesh");
rna_def_mesh_polygons(brna, prop);
- prop = RNA_def_property(srna, "sticky", PROP_COLLECTION, PROP_NONE);
- RNA_def_property_collection_sdna(prop, NULL, "msticky", "totvert");
- RNA_def_property_struct_type(prop, "MeshSticky");
- RNA_def_property_ui_text(prop, "Sticky", "Sticky texture coordinates");
-
/* TODO, should this be allowed to be its self? */
prop = RNA_def_property(srna, "texture_mesh", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "texcomesh");
@@ -3036,7 +3013,6 @@ void RNA_def_mesh(BlenderRNA *brna)
rna_def_mloopuv(brna);
rna_def_mtface(brna);
rna_def_mtexpoly(brna);
- rna_def_msticky(brna);
rna_def_mcol(brna);
rna_def_mloopcol(brna);
rna_def_mproperties(brna);
diff --git a/source/blender/makesrna/intern/rna_mesh_api.c b/source/blender/makesrna/intern/rna_mesh_api.c
index fe18e6254d0..1e75569c841 100644
--- a/source/blender/makesrna/intern/rna_mesh_api.c
+++ b/source/blender/makesrna/intern/rna_mesh_api.c
@@ -41,8 +41,10 @@
#include "BKE_mesh.h"
#include "ED_mesh.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
-const char *rna_Mesh_unit_test_compare(struct Mesh *mesh, bContext *C, struct Mesh *mesh2)
+static const char *rna_Mesh_unit_test_compare(struct Mesh *mesh, bContext *C, struct Mesh *mesh2)
{
const char *ret = BKE_mesh_cmp(mesh, mesh2, FLT_EPSILON * 60);
@@ -76,7 +78,7 @@ void RNA_api_mesh(StructRNA *srna)
RNA_def_function_flag(func, FUNC_USE_CONTEXT);
func = RNA_def_function(srna, "unit_test_compare", "rna_Mesh_unit_test_compare");
- parm = RNA_def_pointer(func, "mesh", "Mesh", "", "Mesh to compare to");
+ RNA_def_pointer(func, "mesh", "Mesh", "", "Mesh to compare to");
RNA_def_function_flag(func, FUNC_USE_CONTEXT);
/* return value */
parm = RNA_def_string(func, "result", "nothing", 64, "Return value", "String description of result of comparison");
diff --git a/source/blender/makesrna/intern/rna_meta.c b/source/blender/makesrna/intern/rna_meta.c
index c8b52b45604..08eefc082bf 100644
--- a/source/blender/makesrna/intern/rna_meta.c
+++ b/source/blender/makesrna/intern/rna_meta.c
@@ -27,6 +27,7 @@
#include <stdlib.h>
+#include "RNA_access.h"
#include "RNA_define.h"
#include "RNA_enum_types.h"
@@ -126,19 +127,17 @@ static MetaElem *rna_MetaBall_elements_new(MetaBall *mb, int type)
return ml;
}
-static void rna_MetaBall_elements_remove(MetaBall *mb, ReportList *reports, MetaElem *ml)
+static void rna_MetaBall_elements_remove(MetaBall *mb, ReportList *reports, PointerRNA *ml_ptr)
{
- int found = 0;
+ MetaElem *ml = ml_ptr->data;
- found = BLI_remlink_safe(&mb->elems, ml);
-
- if (!found) {
- BKE_reportf(reports, RPT_ERROR, "Metaball \"%s\" does not contain spline given", mb->id.name + 2);
+ if (BLI_remlink_safe(&mb->elems, ml) == FALSE) {
+ BKE_reportf(reports, RPT_ERROR, "Metaball '%s' does not contain spline given", mb->id.name + 2);
return;
}
MEM_freeN(ml);
- /* invalidate pointer!, no can do */
+ RNA_POINTER_INVALIDATE(ml_ptr);
/* cheating way for importers to avoid slow updates */
if (mb->id.us > 0) {
@@ -254,7 +253,8 @@ static void rna_def_metaball_elements(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove an element from the metaball");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "element", "MetaElement", "", "The element to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "clear", "rna_MetaBall_elements_clear");
RNA_def_function_ui_description(func, "Remove all elements from the metaball");
diff --git a/source/blender/makesrna/intern/rna_modifier.c b/source/blender/makesrna/intern/rna_modifier.c
index 084cda87507..8eca7162d39 100644
--- a/source/blender/makesrna/intern/rna_modifier.c
+++ b/source/blender/makesrna/intern/rna_modifier.c
@@ -84,6 +84,7 @@ EnumPropertyItem modifier_type_items[] = {
{eModifierType_Curve, "CURVE", ICON_MOD_CURVE, "Curve", ""},
{eModifierType_Displace, "DISPLACE", ICON_MOD_DISPLACE, "Displace", ""},
{eModifierType_Hook, "HOOK", ICON_HOOK, "Hook", ""},
+ {eModifierType_LaplacianSmooth, "LAPLACIANSMOOTH", ICON_MOD_SMOOTH, "Laplacian Smooth", ""},
{eModifierType_Lattice, "LATTICE", ICON_MOD_LATTICE, "Lattice", ""},
{eModifierType_MeshDeform, "MESH_DEFORM", ICON_MOD_MESHDEFORM, "Mesh Deform", ""},
{eModifierType_Shrinkwrap, "SHRINKWRAP", ICON_MOD_SHRINKWRAP, "Shrinkwrap", ""},
@@ -210,12 +211,14 @@ static StructRNA *rna_Modifier_refine(struct PointerRNA *ptr)
return &RNA_RemeshModifier;
case eModifierType_Skin:
return &RNA_SkinModifier;
+ case eModifierType_LaplacianSmooth:
+ return &RNA_LaplacianSmoothModifier;
default:
return &RNA_Modifier;
}
}
-void rna_Modifier_name_set(PointerRNA *ptr, const char *value)
+static void rna_Modifier_name_set(PointerRNA *ptr, const char *value)
{
ModifierData *md = ptr->data;
char oldname[sizeof(md->name)];
@@ -257,9 +260,6 @@ static void rna_Smoke_set_type(Main *bmain, Scene *scene, PointerRNA *ptr)
{
SmokeModifierData *smd = (SmokeModifierData *)ptr->data;
Object *ob = (Object *)ptr->id.data;
- ParticleSystemModifierData *psmd = NULL;
- ParticleSystem *psys = NULL;
- ParticleSettings *part = NULL;
/* nothing changed */
if ((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain)
@@ -273,28 +273,6 @@ static void rna_Smoke_set_type(Main *bmain, Scene *scene, PointerRNA *ptr)
ob->dt = OB_WIRE;
break;
case MOD_SMOKE_TYPE_FLOW:
- for (psys = ob->particlesystem.first; psys; psys = psys->next)
- if (psys->part->type == PART_EMITTER)
- break;
- if (ob->type == OB_MESH && !psys) {
- /* add particle system */
- psmd = (ParticleSystemModifierData *)object_add_particle_system(scene, ob, NULL);
- if (psmd) {
- psys = psmd->psys;
- part = psys->part;
- part->lifetime = 1.0f;
- part->sta = 1.0f;
- part->end = 250.0f;
- part->ren_as = PART_DRAW_NOT;
- part->flag |= PART_UNBORN;
- part->draw_as = PART_DRAW_DOT;
- BLI_strncpy(psys->name, "SmokeParticles", sizeof(psys->name));
- psys->recalc |= (PSYS_RECALC_RESET | PSYS_RECALC_PHYS);
- DAG_id_tag_update(ptr->id.data, OB_RECALC_DATA);
- }
- }
- if (smd->flow)
- smd->flow->psys = psys;
case MOD_SMOKE_TYPE_COLL:
case 0:
default:
@@ -384,6 +362,12 @@ static void rna_SmoothModifier_vgroup_set(PointerRNA *ptr, const char *value)
rna_object_vgroup_name_set(ptr, value, lmd->defgrp_name, sizeof(lmd->defgrp_name));
}
+static void rna_LaplacianSmoothModifier_vgroup_set(PointerRNA *ptr, const char *value)
+{
+ LaplacianSmoothModifierData *lmd = (LaplacianSmoothModifierData *)ptr->data;
+ rna_object_vgroup_name_set(ptr, value, lmd->defgrp_name, sizeof(lmd->defgrp_name));
+}
+
static void rna_WaveModifier_vgroup_set(PointerRNA *ptr, const char *value)
{
WaveModifierData *lmd = (WaveModifierData *)ptr->data;
@@ -402,6 +386,12 @@ static void rna_SolidifyModifier_vgroup_set(PointerRNA *ptr, const char *value)
rna_object_vgroup_name_set(ptr, value, smd->defgrp_name, sizeof(smd->defgrp_name));
}
+static void rna_DecimateModifier_vgroup_set(PointerRNA *ptr, const char *value)
+{
+ DecimateModifierData *dmd = (DecimateModifierData *)ptr->data;
+ rna_object_vgroup_name_set(ptr, value, dmd->defgrp_name, sizeof(dmd->defgrp_name));
+}
+
static void rna_WeightVGModifier_vgroup_set(PointerRNA *ptr, const char *value)
{
ModifierData *md = (ModifierData *)ptr->data;
@@ -1129,6 +1119,13 @@ static void rna_def_modifier_mirror(BlenderRNA *brna)
static void rna_def_modifier_decimate(BlenderRNA *brna)
{
+ static EnumPropertyItem modifier_decim_mode_items[] = {
+ {MOD_DECIM_MODE_COLLAPSE, "COLLAPSE", 0, "Collapse", "Use edge collapsing"},
+ {MOD_DECIM_MODE_UNSUBDIV, "UNSUBDIV", 0, "Un-Subdivide", "Use un-subdivide face reduction"},
+ {MOD_DECIM_MODE_DISSOLVE, "DISSOLVE", 0, "Planar", "Dissolve geometry to form planar polygons"},
+ {0, NULL, 0, NULL, NULL}
+ };
+
StructRNA *srna;
PropertyRNA *prop;
@@ -1137,15 +1134,65 @@ static void rna_def_modifier_decimate(BlenderRNA *brna)
RNA_def_struct_sdna(srna, "DecimateModifierData");
RNA_def_struct_ui_icon(srna, ICON_MOD_DECIM);
+ prop = RNA_def_property(srna, "decimate_type", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "mode");
+ RNA_def_property_enum_items(prop, modifier_decim_mode_items);
+ RNA_def_property_ui_text(prop, "Mode", "");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ /* (mode == MOD_DECIM_MODE_COLLAPSE) */
prop = RNA_def_property(srna, "ratio", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "percent");
RNA_def_property_range(prop, 0, 1);
- RNA_def_property_ui_range(prop, 0, 1, 1, 2);
- RNA_def_property_ui_text(prop, "Ratio", "Ratio of triangles to reduce to");
+ RNA_def_property_ui_range(prop, 0, 1, 1, 4);
+ RNA_def_property_ui_text(prop, "Ratio", "Ratio of triangles to reduce to (collapse only)");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
+ /* (mode == MOD_DECIM_MODE_UNSUBDIV) */
+ prop = RNA_def_property(srna, "iterations", PROP_INT, PROP_UNSIGNED);
+ RNA_def_property_int_sdna(prop, NULL, "iter");
+ RNA_def_property_range(prop, 0, SHRT_MAX);
+ RNA_def_property_ui_range(prop, 0, 100, 1, 0);
+ RNA_def_property_ui_text(prop, "Iterations", "Number of times reduce the geometry (unsubdivide only)");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ /* (mode == MOD_DECIM_MODE_DISSOLVE) */
+ prop = RNA_def_property(srna, "angle_limit", PROP_FLOAT, PROP_ANGLE);
+ RNA_def_property_float_sdna(prop, NULL, "angle");
+ RNA_def_property_range(prop, 0, DEG2RAD(180));
+ RNA_def_property_ui_range(prop, 0, DEG2RAD(180), 100, 2);
+ RNA_def_property_ui_text(prop, "Angle Limit", "Only dissolve angles below this (planar only)");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ /* (mode == MOD_DECIM_MODE_COLLAPSE) */
+ prop = RNA_def_property(srna, "vertex_group", PROP_STRING, PROP_NONE);
+ RNA_def_property_string_sdna(prop, NULL, "defgrp_name");
+ RNA_def_property_ui_text(prop, "Vertex Group", "Vertex group name (collapse only)");
+ RNA_def_property_string_funcs(prop, NULL, NULL, "rna_DecimateModifier_vgroup_set");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "invert_vertex_group", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_DECIM_FLAG_INVERT_VGROUP);
+ RNA_def_property_ui_text(prop, "Invert", "Invert vertex group influence (collapse only)");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "use_collapse_triangulate", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_DECIM_FLAG_TRIANGULATE);
+ RNA_def_property_ui_text(prop, "Triangulate", "Keep triangulated faces resulting from decimation (collapse only)");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+ /* end collapse-only option */
+
+ /* (mode == MOD_DECIM_MODE_DISSOLVE) */
+ prop = RNA_def_property(srna, "use_dissolve_boundaries", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_DECIM_FLAG_ALL_BOUNDARY_VERTS);
+ RNA_def_property_ui_text(prop, "All Boundaries", "Dissolve all vertices inbetween face boundaries (planar only)");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+ /* end dissolve-only option */
+
+
+
+ /* all modes use this */
prop = RNA_def_property(srna, "face_count", PROP_INT, PROP_NONE);
- RNA_def_property_int_sdna(prop, NULL, "faceCount");
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_ui_text(prop, "Face Count", "The current number of faces in the decimated mesh");
}
@@ -1742,6 +1789,64 @@ static void rna_def_modifier_smooth(BlenderRNA *brna)
RNA_def_property_update(prop, 0, "rna_Modifier_update");
}
+static void rna_def_modifier_laplaciansmooth(BlenderRNA *brna)
+{
+ StructRNA *srna;
+ PropertyRNA *prop;
+
+ srna = RNA_def_struct(brna, "LaplacianSmoothModifier", "Modifier");
+ RNA_def_struct_ui_text(srna, "Laplacian Smooth Modifier", "Smoothing effect modifier");
+ RNA_def_struct_sdna(srna, "LaplacianSmoothModifierData");
+ RNA_def_struct_ui_icon(srna, ICON_MOD_SMOOTH);
+
+ prop = RNA_def_property(srna, "use_x", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_LAPLACIANSMOOTH_X);
+ RNA_def_property_ui_text(prop, "X", "Smooth object along X axis");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "use_y", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_LAPLACIANSMOOTH_Y);
+ RNA_def_property_ui_text(prop, "Y", "Smooth object along Y axis");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "use_z", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_LAPLACIANSMOOTH_Z);
+ RNA_def_property_ui_text(prop, "Z", "Smooth object along Z axis");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "use_volume_preserve", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_LAPLACIANSMOOTH_VOLUME_PRESERVATION);
+ RNA_def_property_ui_text(prop, "Preserve Volume", "Apply volume preservation after smooth");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "lambda_factor", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "lambda");
+ RNA_def_property_range(prop, -FLT_MAX, FLT_MAX);
+ RNA_def_property_ui_range(prop, 0.0000001, 1000.0, 0.0000001, 8);
+ RNA_def_property_ui_text(prop, "Lambda Factor", "Smooth factor effect");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "lambda_border", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "lambda_border");
+ RNA_def_property_range(prop, -FLT_MAX, FLT_MAX);
+ RNA_def_property_ui_range(prop, 0.0000001, 1000.0, 0.0000001, 8);
+ RNA_def_property_ui_text(prop, "Lambda Border", "Lambda factor in border");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "iterations", PROP_INT, PROP_NONE);
+ RNA_def_property_int_sdna(prop, NULL, "repeat");
+ RNA_def_property_ui_range(prop, 0, 200, 1, 0);
+ RNA_def_property_ui_text(prop, "Repeat", "");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "vertex_group", PROP_STRING, PROP_NONE);
+ RNA_def_property_string_sdna(prop, NULL, "defgrp_name");
+ RNA_def_property_ui_text(prop, "Vertex Group",
+ "Name of Vertex Group which determines influence of modifier per point");
+ RNA_def_property_string_funcs(prop, NULL, NULL, "rna_LaplacianSmoothModifier_vgroup_set");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+}
+
static void rna_def_modifier_cast(BlenderRNA *brna)
{
StructRNA *srna;
@@ -2658,7 +2763,7 @@ static void rna_def_modifier_screw(BlenderRNA *brna)
#endif
}
-static void rna_def_modifier_weightvg_mask(BlenderRNA *brna, StructRNA *srna)
+static void rna_def_modifier_weightvg_mask(BlenderRNA *UNUSED(brna), StructRNA *srna)
{
static EnumPropertyItem weightvg_mask_tex_map_items[] = {
{MOD_DISP_MAP_LOCAL, "LOCAL", 0, "Local", "Use local generated coordinates"},
@@ -3007,7 +3112,7 @@ static void rna_def_modifier_remesh(BlenderRNA *brna)
prop = RNA_def_property(srna, "octree_depth", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "depth");
- RNA_def_property_range(prop, 1, 10);
+ RNA_def_property_range(prop, 1, 12);
RNA_def_property_ui_text(prop, "Octree Depth", "Resolution of the octree; higher values give finer details");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
@@ -3356,6 +3461,7 @@ void RNA_def_modifier(BlenderRNA *brna)
rna_def_modifier_ocean(brna);
rna_def_modifier_remesh(brna);
rna_def_modifier_skin(brna);
+ rna_def_modifier_laplaciansmooth(brna);
}
#endif
diff --git a/source/blender/makesrna/intern/rna_movieclip.c b/source/blender/makesrna/intern/rna_movieclip.c
index 8d1105fd620..99effc990a8 100644
--- a/source/blender/makesrna/intern/rna_movieclip.c
+++ b/source/blender/makesrna/intern/rna_movieclip.c
@@ -187,8 +187,7 @@ static void rna_def_moviecliUser(BlenderRNA *brna)
RNA_def_struct_ui_text(srna, "Movie Clip User",
"Parameters defining how a MovieClip datablock is used by another datablock");
- prop = RNA_def_property(srna, "current_frame", PROP_INT, PROP_TIME);
- RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ prop = RNA_def_property(srna, "frame_current", PROP_INT, PROP_TIME);
RNA_def_property_int_sdna(prop, NULL, "framenr");
RNA_def_property_range(prop, MINAFRAME, MAXFRAME);
RNA_def_property_ui_text(prop, "Current Frame", "Current frame number in movie or image sequence");
@@ -300,11 +299,17 @@ static void rna_def_movieclip(BlenderRNA *brna)
"(affects only how footage is loading, does not change data associated with a clip)");
RNA_def_property_update(prop, NC_MOVIECLIP | ND_DISPLAY, "rna_MovieClip_reload_update");
+ /* length */
+ prop = RNA_def_property(srna, "frame_duration", PROP_INT, PROP_NONE);
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ RNA_def_property_int_sdna(prop, NULL, "len");
+ RNA_def_property_ui_text(prop, "Duration", "Detected duration of movie clip in frames");
+
/* color management */
prop = RNA_def_property(srna, "colorspace_settings", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "colorspace_settings");
RNA_def_property_struct_type(prop, "ColorManagedColorspaceSettings");
- RNA_def_property_ui_text(prop, "Colorspace Settings", "Input color space settings");
+ RNA_def_property_ui_text(prop, "Color Space Settings", "Input color space settings");
}
void RNA_def_movieclip(BlenderRNA *brna)
diff --git a/source/blender/makesrna/intern/rna_nla.c b/source/blender/makesrna/intern/rna_nla.c
index 16753961852..574f06e9107 100644
--- a/source/blender/makesrna/intern/rna_nla.c
+++ b/source/blender/makesrna/intern/rna_nla.c
@@ -27,6 +27,7 @@
#include <stdlib.h>
+#include "RNA_access.h"
#include "RNA_define.h"
#include "rna_internal.h"
@@ -302,7 +303,7 @@ static NlaStrip *rna_NlaStrip_new(NlaTrack *track, bContext *C, ReportList *repo
NlaStrip *strip = add_nlastrip(action);
if (strip == NULL) {
- BKE_reportf(reports, RPT_ERROR, "Unable to create new strip");
+ BKE_report(reports, RPT_ERROR, "Unable to create new strip");
return NULL;
}
@@ -310,8 +311,8 @@ static NlaStrip *rna_NlaStrip_new(NlaTrack *track, bContext *C, ReportList *repo
strip->start = start;
if (BKE_nlastrips_add_strip(&track->strips, strip) == 0) {
- BKE_reportf(reports, RPT_ERROR,
- "Unable to add strip. Track doesn't have any space to accommodate this new strip");
+ BKE_report(reports, RPT_ERROR,
+ "Unable to add strip (the track does not have any space to accommodate this new strip)");
free_nlastrip(NULL, strip);
return NULL;
}
@@ -345,22 +346,24 @@ static NlaStrip *rna_NlaStrip_new(NlaTrack *track, bContext *C, ReportList *repo
return strip;
}
-static void rna_NlaStrip_remove(NlaTrack *track, bContext *C, ReportList *reports, NlaStrip *strip)
+static void rna_NlaStrip_remove(NlaTrack *track, bContext *C, ReportList *reports, PointerRNA *strip_ptr)
{
+ NlaStrip *strip = strip_ptr->data;
if (BLI_findindex(&track->strips, strip) == -1) {
- BKE_reportf(reports, RPT_ERROR, "NLA's Strip '%s' not found in track '%s'", strip->name, track->name);
+ BKE_reportf(reports, RPT_ERROR, "NLA strip '%s' not found in track '%s'", strip->name, track->name);
return;
}
- else {
- free_nlastrip(&track->strips, strip);
- WM_event_add_notifier(C, NC_ANIMATION | ND_NLA | NA_REMOVED, NULL);
- }
+
+ free_nlastrip(&track->strips, strip);
+ RNA_POINTER_INVALIDATE(strip_ptr);
+
+ WM_event_add_notifier(C, NC_ANIMATION | ND_NLA | NA_REMOVED, NULL);
}
/* Set the 'solo' setting for the given NLA-track, making sure that it is the only one
* that has this status in its AnimData block.
*/
-void rna_NlaTrack_solo_set(PointerRNA *ptr, int value)
+static void rna_NlaTrack_solo_set(PointerRNA *ptr, int value)
{
NlaTrack *data = (NlaTrack *)ptr->data;
AnimData *adt = BKE_animdata_from_id(ptr->id.data);
@@ -520,7 +523,7 @@ static void rna_def_nlastrip(BlenderRNA *brna)
prop = RNA_def_property(srna, "repeat", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "repeat");
RNA_def_property_float_funcs(prop, NULL, "rna_NlaStrip_repeat_set", NULL);
- /* these limits have currently be chosen arbitarily, but could be extended
+ /* these limits have currently be chosen arbitrarily, but could be extended
* (minimum should still be > 0 though) if needed... */
RNA_def_property_range(prop, 0.1f, 1000.0f);
RNA_def_property_ui_text(prop, "Repeat", "Number of times to repeat the action range");
@@ -639,7 +642,8 @@ static void rna_api_nlatrack_strips(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_CONTEXT | FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a NLA Strip");
parm = RNA_def_pointer(func, "strip", "NlaStrip", "", "NLA Strip to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
static void rna_def_nlatrack(BlenderRNA *brna)
diff --git a/source/blender/makesrna/intern/rna_nodetree.c b/source/blender/makesrna/intern/rna_nodetree.c
index 55dda3fc315..ece5c82f747 100644
--- a/source/blender/makesrna/intern/rna_nodetree.c
+++ b/source/blender/makesrna/intern/rna_nodetree.c
@@ -35,12 +35,16 @@
#include "rna_internal_types.h"
#include "BLI_listbase.h"
+#include "BLI_math.h"
+#include "BLI_string.h"
+#include "BLI_utildefines.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
#include "DNA_node_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
+#include "DNA_text_types.h"
#include "DNA_texture_types.h"
#include "BKE_animsys.h"
@@ -48,9 +52,9 @@
#include "BKE_node.h"
#include "BKE_image.h"
#include "BKE_texture.h"
+#include "BKE_idprop.h"
-#include "BLI_math.h"
-#include "BLI_utildefines.h"
+#include "IMB_imbuf.h"
#include "WM_types.h"
@@ -71,12 +75,12 @@ EnumPropertyItem node_quality_items[] = {
};
EnumPropertyItem node_chunksize_items[] = {
- {NTREE_CHUNCKSIZE_32, "32", 0, "32x32", "Chunksize of 32x32"},
- {NTREE_CHUNCKSIZE_64, "64", 0, "64x64", "Chunksize of 64x64"},
- {NTREE_CHUNCKSIZE_128, "128", 0, "128x128", "Chunksize of 128x128"},
- {NTREE_CHUNCKSIZE_256, "256", 0, "256x256", "Chunksize of 256x256"},
- {NTREE_CHUNCKSIZE_512, "512", 0, "512x512", "Chunksize of 512x512"},
- {NTREE_CHUNCKSIZE_1024, "1024", 0, "1024x1024", "Chunksize of 1024x1024"},
+ {NTREE_CHUNCKSIZE_32, "32", 0, "32x32", "Chunksize of 32x32"},
+ {NTREE_CHUNCKSIZE_64, "64", 0, "64x64", "Chunksize of 64x64"},
+ {NTREE_CHUNCKSIZE_128, "128", 0, "128x128", "Chunksize of 128x128"},
+ {NTREE_CHUNCKSIZE_256, "256", 0, "256x256", "Chunksize of 256x256"},
+ {NTREE_CHUNCKSIZE_512, "512", 0, "512x512", "Chunksize of 512x512"},
+ {NTREE_CHUNCKSIZE_1024, "1024", 0, "1024x1024", "Chunksize of 1024x1024"},
{0, NULL, 0, NULL, NULL}
};
@@ -206,6 +210,8 @@ EnumPropertyItem prop_wave_items[] = {
#include "BLI_linklist.h"
+#include "BKE_global.h"
+
#include "ED_node.h"
#include "RE_pipeline.h"
@@ -226,10 +232,6 @@ static StructRNA *rna_Node_refine(struct PointerRNA *ptr)
case NODE_GROUP:
return &RNA_NodeGroup;
- case NODE_FORLOOP:
- return &RNA_NodeForLoop;
- case NODE_WHILELOOP:
- return &RNA_NodeWhileLoop;
case NODE_FRAME:
return &RNA_NodeFrame;
case NODE_REROUTE:
@@ -689,7 +691,7 @@ static bNode *rna_NodeTree_node_new(bNodeTree *ntree, bContext *C, ReportList *r
bNodeTemplate ntemp;
if (type == NODE_GROUP && group == NULL) {
- BKE_reportf(reports, RPT_ERROR, "node type \'GROUP\' missing group argument");
+ BKE_report(reports, RPT_ERROR, "Node type 'GROUP' missing group argument");
return NULL;
}
@@ -700,7 +702,7 @@ static bNode *rna_NodeTree_node_new(bNodeTree *ntree, bContext *C, ReportList *r
node = nodeAddNode(ntree, &ntemp);
if (node == NULL) {
- BKE_reportf(reports, RPT_ERROR, "Unable to create node");
+ BKE_report(reports, RPT_ERROR, "Unable to create node");
}
else {
ntreeUpdateTree(ntree); /* update group node socket links*/
@@ -753,20 +755,20 @@ static bNode *rna_NodeTree_node_texture_new(bNodeTree *ntree, bContext *C, Repor
return node;
}
-static void rna_NodeTree_node_remove(bNodeTree *ntree, ReportList *reports, bNode *node)
+static void rna_NodeTree_node_remove(bNodeTree *ntree, ReportList *reports, PointerRNA *node_ptr)
{
+ bNode *node = node_ptr->data;
if (BLI_findindex(&ntree->nodes, node) == -1) {
- BKE_reportf(reports, RPT_ERROR, "Unable to locate node '%s' in nodetree", node->name);
+ BKE_reportf(reports, RPT_ERROR, "Unable to locate node '%s' in node tree", node->name);
+ return;
}
- else {
- if (node->id)
- id_us_min(node->id);
- nodeFreeNode(ntree, node);
- ntreeUpdateTree(ntree); /* update group node socket links*/
+ id_us_min(node->id);
+ nodeFreeNode(ntree, node);
+ RNA_POINTER_INVALIDATE(node_ptr);
- WM_main_add_notifier(NC_NODE | NA_EDITED, ntree);
- }
+ ntreeUpdateTree(ntree); /* update group node socket links */
+ WM_main_add_notifier(NC_NODE | NA_EDITED, ntree);
}
static void rna_NodeTree_node_clear(bNodeTree *ntree)
@@ -800,7 +802,7 @@ static bNodeLink *rna_NodeTree_link_new(bNodeTree *ntree, ReportList *reports,
nodeFindNode(ntree, tosock, &tonode, NULL, &to_in_out);
if (&from_in_out == &to_in_out) {
- BKE_reportf(reports, RPT_ERROR, "Same input/output direction of sockets");
+ BKE_report(reports, RPT_ERROR, "Same input/output direction of sockets");
return NULL;
}
@@ -824,17 +826,19 @@ static bNodeLink *rna_NodeTree_link_new(bNodeTree *ntree, ReportList *reports,
return ret;
}
-static void rna_NodeTree_link_remove(bNodeTree *ntree, ReportList *reports, bNodeLink *link)
+static void rna_NodeTree_link_remove(bNodeTree *ntree, ReportList *reports, PointerRNA *link_ptr)
{
+ bNodeLink *link = link_ptr->data;
if (BLI_findindex(&ntree->links, link) == -1) {
- BKE_reportf(reports, RPT_ERROR, "Unable to locate link in nodetree");
+ BKE_report(reports, RPT_ERROR, "Unable to locate link in node tree");
+ return;
}
- else {
- nodeRemLink(ntree, link);
- ntreeUpdateTree(ntree);
- WM_main_add_notifier(NC_NODE | NA_EDITED, ntree);
- }
+ nodeRemLink(ntree, link);
+ RNA_POINTER_INVALIDATE(link_ptr);
+
+ ntreeUpdateTree(ntree);
+ WM_main_add_notifier(NC_NODE | NA_EDITED, ntree);
}
static void rna_NodeTree_link_clear(bNodeTree *ntree)
@@ -882,9 +886,9 @@ static bNodeSocket *rna_NodeTree_input_expose(bNodeTree *ntree, ReportList *repo
int index, in_out;
if (!nodeFindNode(ntree, sock, &node, &index, &in_out))
- BKE_reportf(reports, RPT_ERROR, "Unable to locate socket in nodetree");
+ BKE_report(reports, RPT_ERROR, "Unable to locate socket in node tree");
else if (in_out != SOCK_IN)
- BKE_reportf(reports, RPT_ERROR, "Socket is not an input");
+ BKE_report(reports, RPT_ERROR, "Socket is not an input");
else {
/* XXX should check if tree is a group here! no good way to do this currently. */
gsock = node_group_add_socket(ntree, sock->name, sock->type, SOCK_IN);
@@ -906,9 +910,9 @@ static bNodeSocket *rna_NodeTree_output_expose(bNodeTree *ntree, ReportList *rep
int index, in_out;
if (!nodeFindNode(ntree, sock, &node, &index, &in_out))
- BKE_reportf(reports, RPT_ERROR, "Unable to locate socket in nodetree");
+ BKE_report(reports, RPT_ERROR, "Unable to locate socket in node tree");
else if (in_out != SOCK_OUT)
- BKE_reportf(reports, RPT_ERROR, "Socket is not an output");
+ BKE_report(reports, RPT_ERROR, "Socket is not an output");
else {
/* XXX should check if tree is a group here! no good way to do this currently. */
gsock = node_group_add_socket(ntree, sock->name, sock->type, SOCK_OUT);
@@ -997,6 +1001,129 @@ static void rna_NodeOutputFileSlotLayer_name_set(PointerRNA *ptr, const char *va
}
}
+static bNodeSocket *rna_ShaderNodeScript_find_socket(bNode *node, const char *name, int is_output)
+{
+ bNodeSocket *sock;
+
+ if (is_output) {
+ for (sock = node->outputs.first; sock; sock = sock->next) {
+ if (strcmp(sock->name, name) == 0) {
+ return sock;
+ }
+ }
+ }
+ else {
+ for (sock = node->inputs.first; sock; sock = sock->next) {
+ if (strcmp(sock->name, name) == 0) {
+ return sock;
+ }
+ }
+ }
+
+ return NULL;
+}
+
+static void rna_ShaderNodeScript_remove_socket(ID *id, bNode *node, bNodeSocket *sock)
+{
+ bNodeTree *ntree = (bNodeTree *)id;
+
+ nodeRemoveSocket(ntree, node, sock);
+
+ ED_node_generic_update(G.main, ntree, node);
+}
+
+static bNodeSocket *rna_ShaderNodeScript_add_socket(ID *id, bNode *node, const char *name, int type, int is_output)
+{
+ bNodeTree *ntree = (bNodeTree *)id;
+ bNodeSocket *sock;
+
+ /* replace existing socket with the same name, to keep it unique */
+ sock = rna_ShaderNodeScript_find_socket(node, name, is_output);
+ if (sock)
+ nodeRemoveSocket(ntree, node, sock);
+ sock = nodeAddSocket(ntree, node, (is_output ? SOCK_OUT : SOCK_IN), name, type);
+
+ ED_node_generic_update(G.main, ntree, node);
+
+ return sock;
+}
+
+static void rna_ShaderNodeScript_mode_set(PointerRNA *ptr, int value)
+{
+ bNode *node = (bNode *)ptr->data;
+ NodeShaderScript *nss = node->storage;
+
+ if (nss->mode != value) {
+ nss->mode = value;
+ nss->filepath[0] = '\0';
+ nss->flag &= ~NODE_SCRIPT_AUTO_UPDATE;
+
+ /* replace text datablock by filepath */
+ if (node->id) {
+ Text *text = (Text*)node->id;
+
+ if (value == NODE_SCRIPT_EXTERNAL && text->name) {
+ BLI_strncpy(nss->filepath, text->name, sizeof(nss->filepath));
+ BLI_path_rel(nss->filepath, G.main->name);
+ }
+
+ id_us_min(node->id);
+ node->id = NULL;
+ }
+
+ /* remove any bytecode */
+ if (nss->bytecode) {
+ MEM_freeN(nss->bytecode);
+ nss->bytecode = NULL;
+ }
+
+ nss->bytecode_hash[0] = '\0';
+ }
+}
+
+static void rna_ShaderNodeScript_bytecode_get(PointerRNA *ptr, char *value)
+{
+ bNode *node = (bNode *)ptr->data;
+ NodeShaderScript *nss = node->storage;
+
+ strcpy(value, (nss->bytecode)? nss->bytecode: "");
+}
+
+static int rna_ShaderNodeScript_bytecode_length(PointerRNA *ptr)
+{
+ bNode *node = (bNode *)ptr->data;
+ NodeShaderScript *nss = node->storage;
+
+ return (nss->bytecode) ? strlen(nss->bytecode) : 0;
+}
+
+static void rna_ShaderNodeScript_bytecode_set(PointerRNA *ptr, const char *value)
+{
+ bNode *node = (bNode *)ptr->data;
+ NodeShaderScript *nss = node->storage;
+
+ if (nss->bytecode)
+ MEM_freeN(nss->bytecode);
+
+ if (value && value[0])
+ nss->bytecode = BLI_strdup(value);
+ else
+ nss->bytecode = NULL;
+}
+
+static IDProperty *rna_ShaderNodeScript_idprops(PointerRNA *ptr, int create)
+{
+ bNode *node = (bNode *)ptr->data;
+ NodeShaderScript *nss = node->storage;
+
+ if (create && !nss->prop) {
+ IDPropertyTemplate val = {0};
+ nss->prop = IDP_New(IDP_GROUP, &val, "RNA_ShaderNodeScript ID properties");
+ }
+
+ return nss->prop;
+}
+
#else
static EnumPropertyItem prop_image_layer_items[] = {
@@ -1037,12 +1164,17 @@ static EnumPropertyItem node_glossy_items[] = {
{0, NULL, 0, NULL, NULL}
};
+static EnumPropertyItem node_script_mode_items[] = {
+ {NODE_SCRIPT_INTERNAL, "INTERNAL", 0, "Internal", "Use internal text datablock"},
+ {NODE_SCRIPT_EXTERNAL, "EXTERNAL", 0, "External", "Use external .osl or oso file"},
+ {0, NULL, 0, NULL, NULL}
+};
+
#define MaxNodes 50000
enum
{
Category_GroupNode,
- Category_LoopNode,
Category_LayoutNode,
Category_ShaderNode,
Category_CompositorNode,
@@ -1086,8 +1218,6 @@ static void init(void)
#include "rna_nodetree_types.h"
reg_node(NODE_GROUP, Category_GroupNode, "GROUP", "NodeGroup", "SpecialNode", "Group", "");
- reg_node(NODE_FORLOOP, Category_LoopNode, "FORLOOP", "NodeForLoop", "SpecialNode", "ForLoop", "");
- reg_node(NODE_WHILELOOP, Category_LoopNode, "WHILELOOP", "NodeWhileLoop", "SpecialNode", "WhileLoop", "");
reg_node(NODE_FRAME, Category_LayoutNode, "FRAME", "NodeFrame", "SpecialNode", "Frame", "");
reg_node(NODE_REROUTE, Category_LayoutNode, "REROUTE", "NodeReroute", "SpecialNode", "Reroute", "");
}
@@ -1166,36 +1296,6 @@ static void def_group(StructRNA *srna)
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_NodeGroup_update");
}
-static void def_forloop(StructRNA *srna)
-{
- PropertyRNA *prop;
-
- prop = RNA_def_property(srna, "node_tree", PROP_POINTER, PROP_NONE);
- RNA_def_property_pointer_sdna(prop, NULL, "id");
- RNA_def_property_struct_type(prop, "NodeTree");
- RNA_def_property_flag(prop, PROP_EDITABLE);
- RNA_def_property_ui_text(prop, "Node Tree", "");
- RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_NodeGroup_update");
-}
-
-static void def_whileloop(StructRNA *srna)
-{
- PropertyRNA *prop;
-
- prop = RNA_def_property(srna, "node_tree", PROP_POINTER, PROP_NONE);
- RNA_def_property_pointer_sdna(prop, NULL, "id");
- RNA_def_property_struct_type(prop, "NodeTree");
- RNA_def_property_flag(prop, PROP_EDITABLE);
- RNA_def_property_ui_text(prop, "Node Tree", "");
- RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_NodeGroup_update");
-
- prop = RNA_def_property(srna, "max_iterations", PROP_INT, PROP_NONE);
- RNA_def_property_int_sdna(prop, NULL, "custom1");
- RNA_def_property_range(prop, 0.0f, SHRT_MAX);
- RNA_def_property_ui_text(prop, "Max. Iterations", "Limit for number of iterations");
- RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_NodeGroup_update");
-}
-
static void def_frame(StructRNA *srna)
{
PropertyRNA *prop;
@@ -1462,7 +1562,8 @@ static void def_sh_tex_sky(StructRNA *srna)
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
prop = RNA_def_property(srna, "turbidity", PROP_FLOAT, PROP_NONE);
- RNA_def_property_ui_text(prop, "Turbidity", "");
+ RNA_def_property_range(prop, 1.0f, 30.0f);
+ RNA_def_property_ui_text(prop, "Turbidity", "Atmospheric turbidity");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
}
@@ -1720,6 +1821,16 @@ static void def_sh_tex_wave(StructRNA *srna)
RNA_def_property_update(prop, 0, "rna_Node_update");
}
+static void def_sh_tex_coord(StructRNA *srna)
+{
+ PropertyRNA *prop;
+
+ prop = RNA_def_property(srna, "from_dupli", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "custom1", 1);
+ RNA_def_property_ui_text(prop, "From Dupli", "Use the parent of the dupli object if possible");
+ RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
+}
+
static void def_glossy(StructRNA *srna)
{
PropertyRNA *prop;
@@ -1731,6 +1842,76 @@ static void def_glossy(StructRNA *srna)
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
}
+static void def_sh_script(StructRNA *srna)
+{
+ FunctionRNA *func;
+ PropertyRNA *prop, *parm;
+
+ prop = RNA_def_property(srna, "script", PROP_POINTER, PROP_NONE);
+ RNA_def_property_pointer_sdna(prop, NULL, "id");
+ RNA_def_property_struct_type(prop, "Text");
+ RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_REFCOUNT);
+ RNA_def_property_ui_text(prop, "Script", "Internal shader script to define the shader");
+ RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
+
+ RNA_def_struct_sdna_from(srna, "NodeShaderScript", "storage");
+ RNA_def_struct_idprops_func(srna, "rna_ShaderNodeScript_idprops");
+
+ prop = RNA_def_property(srna, "filepath", PROP_STRING, PROP_FILEPATH);
+ RNA_def_property_ui_text(prop, "File Path", "Shader script path");
+ RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
+
+ prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_funcs(prop, NULL, "rna_ShaderNodeScript_mode_set", NULL);
+ RNA_def_property_enum_items(prop, node_script_mode_items);
+ RNA_def_property_ui_text(prop, "Script Source", "");
+ RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
+
+ prop = RNA_def_property(srna, "use_auto_update", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", NODE_SCRIPT_AUTO_UPDATE);
+ RNA_def_property_ui_text(prop, "Auto Update", "Automatically updates the shader when the .osl file changes - external scripts only");
+
+ prop = RNA_def_property(srna, "bytecode", PROP_STRING, PROP_NONE);
+ RNA_def_property_string_funcs(prop, "rna_ShaderNodeScript_bytecode_get",
+ "rna_ShaderNodeScript_bytecode_length", "rna_ShaderNodeScript_bytecode_set");
+ RNA_def_property_ui_text(prop, "Bytecode", "Compile bytecode for shader script node");
+ RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
+
+ prop = RNA_def_property(srna, "bytecode_hash", PROP_STRING, PROP_NONE);
+ RNA_def_property_ui_text(prop, "Bytecode Hash", "Hash of compile bytecode, for quick equality checking");
+ RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
+
+ /* needs to be reset to avoid bad pointer type in API functions below */
+ RNA_def_struct_sdna_from(srna, "bNode", NULL);
+
+ /* API functions */
+
+ func = RNA_def_function(srna, "find_socket", "rna_ShaderNodeScript_find_socket");
+ RNA_def_function_ui_description(func, "Find a socket by name");
+ parm = RNA_def_string(func, "name", "", 0, "Socket name", "");
+ RNA_def_property_flag(parm, PROP_REQUIRED);
+ /*parm =*/ RNA_def_boolean(func, "is_output", FALSE, "Output", "Whether the socket is an output");
+ parm = RNA_def_pointer(func, "result", "NodeSocket", "", "");
+ RNA_def_function_return(func, parm);
+
+ func = RNA_def_function(srna, "add_socket", "rna_ShaderNodeScript_add_socket");
+ RNA_def_function_ui_description(func, "Add a socket socket");
+ RNA_def_function_flag(func, FUNC_USE_SELF_ID);
+ parm = RNA_def_string(func, "name", "", 0, "Name", "");
+ RNA_def_property_flag(parm, PROP_REQUIRED);
+ parm = RNA_def_enum(func, "type", node_socket_type_items, SOCK_FLOAT, "Type", "");
+ RNA_def_property_flag(parm, PROP_REQUIRED);
+ /*parm =*/ RNA_def_boolean(func, "is_output", FALSE, "Output", "Whether the socket is an output");
+ parm = RNA_def_pointer(func, "result", "NodeSocket", "", "");
+ RNA_def_function_return(func, parm);
+
+ func = RNA_def_function(srna, "remove_socket", "rna_ShaderNodeScript_remove_socket");
+ RNA_def_function_ui_description(func, "Remove a socket socket");
+ RNA_def_function_flag(func, FUNC_USE_SELF_ID);
+ parm = RNA_def_pointer(func, "sock", "NodeSocket", "Socket", "");
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+}
+
/* -- Compositor Nodes ------------------------------------------------------ */
static void def_cmp_alpha_over(StructRNA *srna)
@@ -1803,7 +1984,7 @@ static void def_cmp_blur(StructRNA *srna)
/* duplicated in def_cmp_bokehblur */
prop = RNA_def_property(srna, "use_variable_size", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "custom1", CMP_NODEFLAG_BLUR_VARIABLE_SIZE);
- RNA_def_property_ui_text(prop, "Variable Size", "Support variable blue per-pixel when using an image for size input");
+ RNA_def_property_ui_text(prop, "Variable Size", "Support variable blur per-pixel when using an image for size input");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
RNA_def_struct_sdna_from(srna, "NodeBlurData", "storage");
@@ -2195,14 +2376,14 @@ static void def_cmp_inpaint(StructRNA *srna)
{
PropertyRNA *prop;
-/*
+#if 0
prop = RNA_def_property(srna, "type", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "custom1");
RNA_def_property_enum_items(prop, type_items);
RNA_def_property_ui_text(prop, "Type", "Type of inpaint algorithm");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
-*/
+#endif
prop = RNA_def_property(srna, "distance", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "custom2");
@@ -3839,7 +4020,7 @@ static void def_cmp_trackpos(StructRNA *srna)
RNA_def_property_ui_text(prop, "Position", "Which marker position to use for output");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
- prop = RNA_def_property(srna, "relative_frame", PROP_INT, PROP_NONE);
+ prop = RNA_def_property(srna, "frame_relative", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "custom2");
RNA_def_property_ui_text(prop, "Frame", "Frame to be used for relative position");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
@@ -3984,8 +4165,6 @@ static void rna_def_special_node(BlenderRNA *brna)
static EnumPropertyItem specific_node_type_items[] = {
{NODE_GROUP, "GROUP", ICON_NODE, "Group", ""},
- {NODE_FORLOOP, "FORLOOP", ICON_NODE, "For Loop", ""},
- {NODE_WHILELOOP, "WHILELOOP", ICON_NODE, "While Loop", ""},
{NODE_FRAME, "FRAME", ICON_NODE, "Frame", ""},
{NODE_REROUTE, "REROUTE", ICON_NODE, "Reroute", ""},
{0, NULL, 0, NULL, NULL}
@@ -4029,14 +4208,15 @@ static void rna_def_nodetree_link_api(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "remove a node link from the node tree");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "link", "NodeLink", "", "The node link to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "clear", "rna_NodeTree_link_clear");
RNA_def_function_ui_description(func, "remove all node links from the node tree");
}
/* shared between all note tree types*/
-static void rna_def_nodetree_active_api(StructRNA *srna, PropertyRNA *cprop)
+static void rna_def_nodetree_active_api(StructRNA *srna, PropertyRNA *UNUSED(cprop))
{
PropertyRNA *prop;
@@ -4073,7 +4253,8 @@ static void rna_def_composite_nodetree_api(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove a node from this node tree");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "node", "Node", "", "The node to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "clear", "rna_NodeTree_node_clear");
RNA_def_function_ui_description(func, "Remove all nodes from this node tree");
@@ -4106,7 +4287,8 @@ static void rna_def_shader_nodetree_api(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove a node from this node tree");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "node", "Node", "", "The node to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "clear", "rna_NodeTree_node_clear");
RNA_def_function_ui_description(func, "Remove all nodes from this node tree");
@@ -4139,7 +4321,8 @@ static void rna_def_texture_nodetree_api(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove a node from this node tree");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "node", "Node", "", "The node to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "clear", "rna_NodeTree_node_clear");
RNA_def_function_ui_description(func, "Remove all nodes from this node tree");
@@ -4315,7 +4498,7 @@ static void rna_def_node(BlenderRNA *brna)
prop = RNA_def_property(srna, "label", PROP_STRING, PROP_NONE);
RNA_def_property_string_sdna(prop, NULL, "label");
RNA_def_property_ui_text(prop, "Label", "Optional custom node label");
- RNA_def_property_update(prop, NC_NODE, "rna_Node_update");
+ RNA_def_property_update(prop, NC_NODE | ND_DISPLAY, NULL);
prop = RNA_def_property(srna, "inputs", PROP_COLLECTION, PROP_NONE);
RNA_def_property_collection_sdna(prop, NULL, "inputs", NULL);
@@ -4608,8 +4791,6 @@ void RNA_def_nodetree(BlenderRNA *brna)
#include "rna_nodetree_types.h"
define_specific_node(brna, NODE_GROUP, def_group);
- define_specific_node(brna, NODE_FORLOOP, def_forloop);
- define_specific_node(brna, NODE_WHILELOOP, def_whileloop);
define_specific_node(brna, NODE_FRAME, def_frame);
define_specific_node(brna, NODE_REROUTE, 0);
diff --git a/source/blender/makesrna/intern/rna_nodetree_types.h b/source/blender/makesrna/intern/rna_nodetree_types.h
index 0baa4cc0838..c45c9b71442 100644
--- a/source/blender/makesrna/intern/rna_nodetree_types.h
+++ b/source/blender/makesrna/intern/rna_nodetree_types.h
@@ -67,6 +67,7 @@ DefNode( ShaderNode, SH_NODE_ADD_SHADER, 0, "AD
DefNode( ShaderNode, SH_NODE_ATTRIBUTE, def_sh_attribute, "ATTRIBUTE", Attribute, "Attribute", "" )
DefNode( ShaderNode, SH_NODE_BACKGROUND, 0, "BACKGROUND", Background, "Background", "" )
DefNode( ShaderNode, SH_NODE_HOLDOUT, 0, "HOLDOUT", Holdout, "Holdout", "" )
+DefNode( ShaderNode, SH_NODE_BSDF_ANISOTROPIC, 0, "BSDF_ANISOTROPIC", BsdfAnisotropic, "Anisotropic Bsdf", "" )
DefNode( ShaderNode, SH_NODE_BSDF_DIFFUSE, 0, "BSDF_DIFFUSE", BsdfDiffuse, "Diffuse Bsdf", "" )
DefNode( ShaderNode, SH_NODE_BSDF_GLOSSY, def_glossy, "BSDF_GLOSSY", BsdfGlossy, "Glossy Bsdf", "" )
DefNode( ShaderNode, SH_NODE_BSDF_GLASS, def_glossy, "BSDF_GLASS", BsdfGlass, "Glass Bsdf", "" )
@@ -81,6 +82,8 @@ DefNode( ShaderNode, SH_NODE_LIGHT_PATH, 0, "LI
DefNode( ShaderNode, SH_NODE_LIGHT_FALLOFF, 0, "LIGHT_FALLOFF", LightFalloff, "Light Falloff", "" )
DefNode( ShaderNode, SH_NODE_OBJECT_INFO, 0, "OBJECT_INFO", ObjectInfo, "Object Info", "" )
DefNode( ShaderNode, SH_NODE_PARTICLE_INFO, 0, "PARTICLE_INFO", ParticleInfo, "Particle Info", "" )
+DefNode( ShaderNode, SH_NODE_BUMP, 0, "BUMP", BumpNode, "Bump", "" )
+DefNode( ShaderNode, SH_NODE_SCRIPT, def_sh_script, "SCRIPT", Script, "Script", "" )
DefNode( ShaderNode, SH_NODE_TEX_IMAGE, def_sh_tex_image, "TEX_IMAGE", TexImage, "Image Texture", "" )
DefNode( ShaderNode, SH_NODE_TEX_ENVIRONMENT, def_sh_tex_environment, "TEX_ENVIRONMENT", TexEnvironment, "Environment Texture","" )
DefNode( ShaderNode, SH_NODE_TEX_SKY, def_sh_tex_sky, "TEX_SKY", TexSky, "Sky Texture", "" )
@@ -91,8 +94,8 @@ DefNode( ShaderNode, SH_NODE_TEX_WAVE, def_sh_tex_wave, "TE
DefNode( ShaderNode, SH_NODE_TEX_MUSGRAVE, def_sh_tex_musgrave, "TEX_MUSGRAVE", TexMusgrave, "Musgrave Texture", "" )
DefNode( ShaderNode, SH_NODE_TEX_VORONOI, def_sh_tex_voronoi, "TEX_VORONOI", TexVoronoi, "Voronoi Texture", "" )
DefNode( ShaderNode, SH_NODE_TEX_CHECKER, def_sh_tex_checker, "TEX_CHECKER", TexChecker, "Checker Texture", "" )
-DefNode( ShaderNode, SH_NODE_TEX_BRICK, def_sh_tex_brick, "TEX_BRICK", TexBrick, "Brick Texture", "" )
-DefNode( ShaderNode, SH_NODE_TEX_COORD, 0, "TEX_COORD", TexCoord, "Texture Coordinate","" )
+DefNode( ShaderNode, SH_NODE_TEX_BRICK, def_sh_tex_brick, "TEX_BRICK", TexBrick, "Brick Texture", "" )
+DefNode( ShaderNode, SH_NODE_TEX_COORD, def_sh_tex_coord, "TEX_COORD", TexCoord, "Texture Coordinate","" )
DefNode( CompositorNode, CMP_NODE_VIEWER, def_cmp_viewer, "VIEWER", Viewer, "Viewer", "" )
DefNode( CompositorNode, CMP_NODE_RGB, 0, "RGB", RGB, "RGB", "" )
diff --git a/source/blender/makesrna/intern/rna_object.c b/source/blender/makesrna/intern/rna_object.c
index e69d313b23b..10f361ef1bd 100644
--- a/source/blender/makesrna/intern/rna_object.c
+++ b/source/blender/makesrna/intern/rna_object.c
@@ -69,6 +69,19 @@ EnumPropertyItem object_mode_items[] = {
{0, NULL, 0, NULL, NULL}
};
+EnumPropertyItem object_empty_drawtype_items[] = {
+ {OB_PLAINAXES, "PLAIN_AXES", 0, "Plain Axes", ""},
+ {OB_ARROWS, "ARROWS", 0, "Arrows", ""},
+ {OB_SINGLE_ARROW, "SINGLE_ARROW", 0, "Single Arrow", ""},
+ {OB_CIRCLE, "CIRCLE", 0, "Circle", ""},
+ {OB_CUBE, "CUBE", 0, "Cube", ""},
+ {OB_EMPTY_SPHERE, "SPHERE", 0, "Sphere", ""},
+ {OB_EMPTY_CONE, "CONE", 0, "Cone", ""},
+ {OB_EMPTY_IMAGE, "IMAGE", 0, "Image", ""},
+ {0, NULL, 0, NULL, NULL}
+};
+
+
static EnumPropertyItem parent_type_items[] = {
{PAROBJECT, "OBJECT", 0, "Object", "The object is parented to an object"},
{PARCURVE, "CURVE", 0, "Curve", "The object is parented to a curve"},
@@ -80,7 +93,7 @@ static EnumPropertyItem parent_type_items[] = {
{PARBONE, "BONE", 0, "Bone", "The object is parented to a bone"},
{0, NULL, 0, NULL, NULL}
};
-
+
static EnumPropertyItem collision_bounds_items[] = {
{OB_BOUND_BOX, "BOX", 0, "Box", ""},
{OB_BOUND_SPHERE, "SPHERE", 0, "Sphere", ""},
@@ -231,7 +244,7 @@ void rna_Object_internal_update_data(Main *UNUSED(bmain), Scene *UNUSED(scene),
WM_main_add_notifier(NC_OBJECT | ND_DRAW, ptr->id.data);
}
-void rna_Object_active_shape_update(Main *bmain, Scene *scene, PointerRNA *ptr)
+static void rna_Object_active_shape_update(Main *bmain, Scene *scene, PointerRNA *ptr)
{
Object *ob = ptr->id.data;
@@ -493,10 +506,10 @@ static void rna_Object_dup_group_set(PointerRNA *ptr, PointerRNA value)
ob->dup_group = grp;
else
BKE_report(NULL, RPT_ERROR,
- "Cannot set dupli-group as object belongs in group being instanced thus causing a cycle");
+ "Cannot set dupli-group as object belongs in group being instanced, thus causing a cycle");
}
-void rna_VertexGroup_name_set(PointerRNA *ptr, const char *value)
+static void rna_VertexGroup_name_set(PointerRNA *ptr, const char *value)
{
Object *ob = (Object *)ptr->id.data;
bDeformGroup *dg = (bDeformGroup *)ptr->data;
@@ -838,11 +851,11 @@ static void rna_MaterialSlot_link_set(PointerRNA *ptr, int value)
if (value) {
ob->matbits[index] = 1;
- /* ob->colbits |= (1<<index); */ /* DEPRECATED */
+ /* ob->colbits |= (1 << index); */ /* DEPRECATED */
}
else {
ob->matbits[index] = 0;
- /* ob->colbits &= ~(1<<index); */ /* DEPRECATED */
+ /* ob->colbits &= ~(1 << index); */ /* DEPRECATED */
}
}
@@ -1023,8 +1036,8 @@ static unsigned int rna_Object_layer_validate__internal(const int *values, unsig
return 0;
for (i = 0; i < 20; i++) {
- if (values[i]) lay |= (1 << i);
- else lay &= ~(1 << i);
+ if (values[i]) lay |= (1 << i);
+ else lay &= ~(1 << i);
}
return lay;
@@ -1059,8 +1072,9 @@ static void rna_GameObjectSettings_state_get(PointerRNA *ptr, int *values)
int all_states = (ob->scaflag & OB_ALLSTATE ? 1 : 0);
memset(values, 0, sizeof(int) * OB_MAX_STATES);
- for (i = 0; i < OB_MAX_STATES; i++)
+ for (i = 0; i < OB_MAX_STATES; i++) {
values[i] = (ob->state & (1 << i)) | all_states;
+ }
}
static void rna_GameObjectSettings_state_set(PointerRNA *ptr, const int *values)
@@ -1098,10 +1112,69 @@ static void rna_GameObjectSettings_used_state_get(PointerRNA *ptr, int *values)
}
}
+static void rna_GameObjectSettings_col_group_get(PointerRNA *ptr, int *values)
+{
+ Object *ob = (Object*)ptr->data;
+ int i;
+
+ for (i = 0; i < OB_MAX_COL_MASKS; i++) {
+ values[i] = (ob->col_group & (1 << i));
+ }
+}
+
+static void rna_GameObjectSettings_col_group_set(PointerRNA *ptr, const int *values)
+{
+ Object *ob = (Object*)ptr->data;
+ int i, tot = 0;
+
+ /* ensure we always have some group selected */
+ for (i = 0; i < OB_MAX_COL_MASKS; i++)
+ if (values[i])
+ tot++;
+
+ if (tot == 0)
+ return;
+
+ for (i = 0; i < OB_MAX_COL_MASKS; i++) {
+ if (values[i]) ob->col_group |= (1 << i);
+ else ob->col_group &= ~(1 << i);
+ }
+}
+
+static void rna_GameObjectSettings_col_mask_get(PointerRNA *ptr, int *values)
+{
+ Object *ob = (Object*)ptr->data;
+ int i;
+
+ for (i = 0; i < OB_MAX_COL_MASKS; i++) {
+ values[i] = (ob->col_mask & (1 << i));
+ }
+}
+
+static void rna_GameObjectSettings_col_mask_set(PointerRNA *ptr, const int *values)
+{
+ Object *ob = (Object*)ptr->data;
+ int i, tot = 0;
+
+ /* ensure we always have some mask selected */
+ for (i = 0; i < OB_MAX_COL_MASKS; i++)
+ if (values[i])
+ tot++;
+
+ if (tot == 0)
+ return;
+
+ for (i = 0; i < OB_MAX_COL_MASKS; i++) {
+ if (values[i]) ob->col_mask |= (1 << i);
+ else ob->col_mask &= ~(1 << i);
+ }
+}
+
+
static void rna_Object_active_shape_key_index_range(PointerRNA *ptr, int *min, int *max, int *softmin, int *softmax)
{
Object *ob = (Object *)ptr->id.data;
- Key *key = ob_get_key(ob);
+ Key *key = BKE_key_from_object(ob);
*min = 0;
if (key) {
@@ -1130,7 +1203,7 @@ static void rna_Object_active_shape_key_index_set(PointerRNA *ptr, int value)
static PointerRNA rna_Object_active_shape_key_get(PointerRNA *ptr)
{
Object *ob = (Object *)ptr->id.data;
- Key *key = ob_get_key(ob);
+ Key *key = BKE_key_from_object(ob);
KeyBlock *kb;
PointerRNA keyptr;
@@ -1186,14 +1259,17 @@ static bConstraint *rna_Object_constraints_new(Object *object, int type)
return add_ob_constraint(object, NULL, type);
}
-static void rna_Object_constraints_remove(Object *object, ReportList *reports, bConstraint *con)
+static void rna_Object_constraints_remove(Object *object, ReportList *reports, PointerRNA *con_ptr)
{
+ bConstraint *con = con_ptr->data;
if (BLI_findindex(&object->constraints, con) == -1) {
BKE_reportf(reports, RPT_ERROR, "Constraint '%s' not found in object '%s'", con->name, object->id.name + 2);
return;
}
remove_constraint(&object->constraints, con);
+ RNA_POINTER_INVALIDATE(con_ptr);
+
ED_object_constraint_update(object);
ED_object_constraint_set_active(object, NULL);
WM_main_add_notifier(NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, object);
@@ -1215,9 +1291,15 @@ static ModifierData *rna_Object_modifier_new(Object *object, bContext *C, Report
return ED_object_modifier_add(reports, CTX_data_main(C), CTX_data_scene(C), object, name, type);
}
-static void rna_Object_modifier_remove(Object *object, bContext *C, ReportList *reports, ModifierData *md)
+static void rna_Object_modifier_remove(Object *object, bContext *C, ReportList *reports, PointerRNA *md_ptr)
{
- ED_object_modifier_remove(reports, CTX_data_main(C), CTX_data_scene(C), object, md);
+ ModifierData *md = md_ptr->data;
+ if (ED_object_modifier_remove(reports, CTX_data_main(C), CTX_data_scene(C), object, md) == FALSE) {
+ /* error is already set */
+ return;
+ }
+
+ RNA_POINTER_INVALIDATE(md_ptr);
WM_main_add_notifier(NC_OBJECT | ND_MODIFIER | NA_REMOVED, object);
}
@@ -1251,9 +1333,16 @@ static bDeformGroup *rna_Object_vgroup_new(Object *ob, const char *name)
return defgroup;
}
-static void rna_Object_vgroup_remove(Object *ob, bDeformGroup *defgroup)
+static void rna_Object_vgroup_remove(Object *ob, ReportList *reports, PointerRNA *defgroup_ptr)
{
+ bDeformGroup *defgroup = defgroup_ptr->data;
+ if (BLI_findindex(&ob->defbase, defgroup) == -1) {
+ BKE_reportf(reports, RPT_ERROR, "DeformGroup '%s' not in object '%s'", defgroup->name, ob->id.name + 2);
+ return;
+ }
+
ED_vgroup_delete(ob, defgroup);
+ RNA_POINTER_INVALIDATE(defgroup_ptr);
WM_main_add_notifier(NC_OBJECT | ND_DRAW, ob);
}
@@ -1271,7 +1360,7 @@ static void rna_VertexGroup_vertex_add(ID *id, bDeformGroup *def, ReportList *re
Object *ob = (Object *)id;
if (ED_vgroup_object_is_edit_mode(ob)) {
- BKE_reportf(reports, RPT_ERROR, "VertexGroup.add(): Can't be called while object is in edit mode");
+ BKE_report(reports, RPT_ERROR, "VertexGroup.add(): cannot be called while object is in edit mode");
return;
}
@@ -1286,7 +1375,7 @@ static void rna_VertexGroup_vertex_remove(ID *id, bDeformGroup *dg, ReportList *
Object *ob = (Object *)id;
if (ED_vgroup_object_is_edit_mode(ob)) {
- BKE_reportf(reports, RPT_ERROR, "VertexGroup.remove(): Can't be called while object is in edit mode");
+ BKE_report(reports, RPT_ERROR, "VertexGroup.remove(): cannot be called while object is in edit mode");
return;
}
@@ -1301,7 +1390,7 @@ static float rna_VertexGroup_weight(ID *id, bDeformGroup *dg, ReportList *report
float weight = ED_vgroup_vert_weight((Object *)id, dg, index);
if (weight < 0) {
- BKE_reportf(reports, RPT_ERROR, "Vertex not in group");
+ BKE_report(reports, RPT_ERROR, "Vertex not in group");
}
return weight;
}
@@ -1565,6 +1654,17 @@ static void rna_def_object_game_settings(BlenderRNA *brna)
RNA_def_property_range(prop, 0.0, 1000.0);
RNA_def_property_ui_text(prop, "Fall Speed Max", "Maximum speed at which the character will fall");
+ prop = RNA_def_property(srna, "collision_group", PROP_BOOLEAN, PROP_LAYER_MEMBER);
+ RNA_def_property_boolean_sdna(prop, NULL, "col_group", 1);
+ RNA_def_property_array(prop, OB_MAX_COL_MASKS);
+ RNA_def_property_ui_text(prop, "Collision Group", "The collision group of the object");
+ RNA_def_property_boolean_funcs(prop, "rna_GameObjectSettings_col_group_get", "rna_GameObjectSettings_col_group_set");
+
+ prop = RNA_def_property(srna, "collision_mask", PROP_BOOLEAN, PROP_LAYER_MEMBER);
+ RNA_def_property_boolean_sdna(prop, NULL, "col_mask", 1);
+ RNA_def_property_array(prop, OB_MAX_COL_MASKS);
+ RNA_def_property_ui_text(prop, "Collision Mask", "The groups this object can collide with");
+ RNA_def_property_boolean_funcs(prop, "rna_GameObjectSettings_col_mask_get", "rna_GameObjectSettings_col_mask_set");
/* lock position */
prop = RNA_def_property(srna, "lock_location_x", PROP_BOOLEAN, PROP_NONE);
@@ -1732,7 +1832,8 @@ static void rna_def_object_constraints(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_flag(func, FUNC_USE_REPORTS);
/* constraint to remove */
parm = RNA_def_pointer(func, "constraint", "Constraint", "", "Removed constraint");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "clear", "rna_Object_constraints_clear");
RNA_def_function_ui_description(func, "Remove all constraint from this object");
@@ -1783,7 +1884,8 @@ static void rna_def_object_modifiers(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove an existing modifier from the object");
/* modifier to remove */
parm = RNA_def_pointer(func, "modifier", "Modifier", "", "Modifier to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
/* clear all modifiers */
func = RNA_def_function(srna, "clear", "rna_Object_modifier_clear");
@@ -1861,9 +1963,11 @@ static void rna_def_object_vertex_groups(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_return(func, parm);
func = RNA_def_function(srna, "remove", "rna_Object_vgroup_remove");
+ RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Delete vertex group from object");
parm = RNA_def_pointer(func, "group", "VertexGroup", "", "Vertex group to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "clear", "rna_Object_vgroup_clear");
RNA_def_function_ui_description(func, "Delete all vertex groups from object");
@@ -1874,18 +1978,6 @@ static void rna_def_object(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
- static EnumPropertyItem empty_drawtype_items[] = {
- {OB_PLAINAXES, "PLAIN_AXES", 0, "Plain Axes", ""},
- {OB_ARROWS, "ARROWS", 0, "Arrows", ""},
- {OB_SINGLE_ARROW, "SINGLE_ARROW", 0, "Single Arrow", ""},
- {OB_CIRCLE, "CIRCLE", 0, "Circle", ""},
- {OB_CUBE, "CUBE", 0, "Cube", ""},
- {OB_EMPTY_SPHERE, "SPHERE", 0, "Sphere", ""},
- {OB_EMPTY_CONE, "CONE", 0, "Cone", ""},
- {OB_EMPTY_IMAGE, "IMAGE", 0, "Image", ""},
- {0, NULL, 0, NULL, NULL}
- };
static EnumPropertyItem track_items[] = {
{OB_POSX, "POS_X", 0, "+X", ""},
@@ -2267,7 +2359,7 @@ static void rna_def_object(BlenderRNA *brna)
/* empty */
prop = RNA_def_property(srna, "empty_draw_type", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "empty_drawtype");
- RNA_def_property_enum_items(prop, empty_drawtype_items);
+ RNA_def_property_enum_items(prop, object_empty_drawtype_items);
RNA_def_property_ui_text(prop, "Empty Display Type", "Viewport display style for empties");
RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, NULL);
@@ -2572,7 +2664,16 @@ static void rna_def_dupli_object(BlenderRNA *brna)
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE | PROP_EDITABLE);
RNA_def_property_ui_text(prop, "Particle Index", "Index in the lowest-level particle dupli list");
- /* TODO: DupliObject has more properties that can be wrapped */
+ prop = RNA_def_property(srna, "orco", PROP_FLOAT, PROP_TRANSLATION);
+ RNA_def_property_float_sdna(prop, NULL, "orco");
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE | PROP_EDITABLE);
+ RNA_def_property_ui_text(prop, "Generated Coordinates", "Generated coordinates in parent object space");
+
+ prop = RNA_def_property(srna, "uv", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "uv");
+ RNA_def_property_array(prop, 2);
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE | PROP_EDITABLE);
+ RNA_def_property_ui_text(prop, "UV Coordinates", "UV coordinates in parent object space");
}
static void rna_def_object_base(BlenderRNA *brna)
diff --git a/source/blender/makesrna/intern/rna_object_api.c b/source/blender/makesrna/intern/rna_object_api.c
index 5bf1cc281ad..87fc3be28a2 100644
--- a/source/blender/makesrna/intern/rna_object_api.c
+++ b/source/blender/makesrna/intern/rna_object_api.c
@@ -39,6 +39,8 @@
#include "DNA_object_types.h"
#include "DNA_modifier_types.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include "BLI_math.h"
@@ -72,7 +74,7 @@
/* copied from Mesh_getFromObject and adapted to RNA interface */
/* settings: 0 - preview, 1 - render */
-Mesh *rna_Object_to_mesh(Object *ob, ReportList *reports, Scene *sce, int apply_modifiers, int settings)
+static Mesh *rna_Object_to_mesh(Object *ob, ReportList *reports, Scene *sce, int apply_modifiers, int settings)
{
Mesh *tmpmesh;
Curve *tmpcu = NULL, *copycu;
@@ -94,7 +96,7 @@ Mesh *rna_Object_to_mesh(Object *ob, ReportList *reports, Scene *sce, int apply_
float (*orco)[3] = NULL;
/* copies object and modifiers (but not the data) */
- tmpobj = BKE_object_copy(ob);
+ tmpobj = BKE_object_copy_with_caches(ob);
tmpcu = (Curve *)tmpobj->data;
tmpcu->id.us--;
@@ -156,7 +158,7 @@ Mesh *rna_Object_to_mesh(Object *ob, ReportList *reports, Scene *sce, int apply_
/* BKE_mesh_from_nurbs changes the type to a mesh, check it worked */
if (tmpobj->type != OB_MESH) {
BKE_libblock_free_us(&(G.main->object), tmpobj);
- BKE_report(reports, RPT_ERROR, "cant convert curve to mesh. Does the curve have any segments?");
+ BKE_report(reports, RPT_ERROR, "Cannot convert curve to mesh (does the curve have any segments?)");
return NULL;
}
@@ -175,6 +177,8 @@ Mesh *rna_Object_to_mesh(Object *ob, ReportList *reports, Scene *sce, int apply_
return NULL; /* only do basis metaball */
tmpmesh = BKE_mesh_add("Mesh");
+ /* BKE_mesh_add gives us a user count we don't need */
+ tmpmesh->id.us--;
if (render) {
ListBase disp = {NULL, NULL};
@@ -184,6 +188,7 @@ Mesh *rna_Object_to_mesh(Object *ob, ReportList *reports, Scene *sce, int apply_
}
else
BKE_mesh_from_metaball(&ob->disp, tmpmesh);
+
break;
}
@@ -212,6 +217,9 @@ Mesh *rna_Object_to_mesh(Object *ob, ReportList *reports, Scene *sce, int apply_
dm->release(dm);
}
+ /* BKE_mesh_add/copy gives us a user count we don't need */
+ tmpmesh->id.us--;
+
break;
default:
BKE_report(reports, RPT_ERROR, "Object does not have geometry data");
@@ -281,9 +289,6 @@ Mesh *rna_Object_to_mesh(Object *ob, ReportList *reports, Scene *sce, int apply_
/* cycles and exporters rely on this still */
BKE_mesh_tessface_ensure(tmpmesh);
- /* we don't assign it to anything */
- tmpmesh->id.us--;
-
/* make sure materials get updated in objects */
test_object_materials(&tmpmesh->id);
@@ -316,7 +321,7 @@ static void dupli_render_particle_set(Scene *scene, Object *ob, int level, int e
}
}
- if (level == 0 && enable) {
+ if (enable) {
/* this is to make sure we get render level duplis in groups:
* the derivedmesh must be created before init_render_mesh,
* since object_duplilist does dupliparticles before that */
@@ -335,8 +340,10 @@ static void dupli_render_particle_set(Scene *scene, Object *ob, int level, int e
dupli_render_particle_set(scene, go->ob, level + 1, enable);
}
/* When no longer needed, duplilist should be freed with Object.free_duplilist */
-void rna_Object_create_duplilist(Object *ob, ReportList *reports, Scene *sce)
+static void rna_Object_create_duplilist(Object *ob, ReportList *reports, Scene *sce, int settings)
{
+ int for_render = settings == eModifierMode_Render;
+
if (!(ob->transflag & OB_DUPLI)) {
BKE_report(reports, RPT_ERROR, "Object does not have duplis");
return;
@@ -344,20 +351,20 @@ void rna_Object_create_duplilist(Object *ob, ReportList *reports, Scene *sce)
/* free duplilist if a user forgets to */
if (ob->duplilist) {
- BKE_reportf(reports, RPT_WARNING, "Object.dupli_list has not been freed");
+ BKE_report(reports, RPT_WARNING, "Object.dupli_list has not been freed");
free_object_duplilist(ob->duplilist);
ob->duplilist = NULL;
}
if (G.is_rendering)
dupli_render_particle_set(sce, ob, 0, 1);
- ob->duplilist = object_duplilist(sce, ob);
+ ob->duplilist = object_duplilist(sce, ob, for_render);
if (G.is_rendering)
dupli_render_particle_set(sce, ob, 0, 0);
/* ob->duplilist should now be freed with Object.free_duplilist */
}
-void rna_Object_free_duplilist(Object *ob)
+static void rna_Object_free_duplilist(Object *ob)
{
if (ob->duplilist) {
free_object_duplilist(ob->duplilist);
@@ -380,12 +387,12 @@ static PointerRNA rna_Object_shape_key_add(Object *ob, bContext *C, ReportList *
return keyptr;
}
else {
- BKE_reportf(reports, RPT_ERROR, "Object \"%s\"does not support shapes", ob->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Object '%s' does not support shapes", ob->id.name + 2);
return PointerRNA_NULL;
}
}
-int rna_Object_is_visible(Object *ob, Scene *sce)
+static int rna_Object_is_visible(Object *ob, Scene *sce)
{
return !(ob->restrictflag & OB_RESTRICT_VIEW) && (ob->lay & sce->lay);
}
@@ -395,14 +402,14 @@ static void rna_Mesh_assign_verts_to_group(Object *ob, bDeformGroup *group, int
float weight, int assignmode)
{
if (ob->type != OB_MESH) {
- BKE_report(reports, RPT_ERROR, "Object should be of MESH type");
+ BKE_report(reports, RPT_ERROR, "Object should be of mesh type");
return;
}
Mesh *me = (Mesh *)ob->data;
int group_index = BLI_findlink(&ob->defbase, group);
if (group_index == -1) {
- BKE_report(reports, RPT_ERROR, "No deform groups assigned to mesh");
+ BKE_report(reports, RPT_ERROR, "No vertex groups assigned to mesh");
return;
}
@@ -428,13 +435,13 @@ static void rna_Mesh_assign_verts_to_group(Object *ob, bDeformGroup *group, int
#endif
/* BMESH_TODO, return polygon index, not tessface */
-void rna_Object_ray_cast(Object *ob, ReportList *reports, float ray_start[3], float ray_end[3],
- float r_location[3], float r_normal[3], int *index)
+static void rna_Object_ray_cast(Object *ob, ReportList *reports, float ray_start[3], float ray_end[3],
+ float r_location[3], float r_normal[3], int *index)
{
BVHTreeFromMesh treeData = {NULL};
if (ob->derivedFinal == NULL) {
- BKE_reportf(reports, RPT_ERROR, "object \"%s\" has no mesh data to be used for ray casting", ob->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Object '%s' has no mesh data to be used for ray casting", ob->id.name + 2);
return;
}
@@ -442,7 +449,7 @@ void rna_Object_ray_cast(Object *ob, ReportList *reports, float ray_start[3], fl
bvhtree_from_mesh_faces(&treeData, ob->derivedFinal, 0.0f, 4, 6);
if (treeData.tree == NULL) {
- BKE_reportf(reports, RPT_ERROR, "object \"%s\" could not create internal data for ray casting", ob->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Object '%s' could not create internal data for ray casting", ob->id.name + 2);
return;
}
else {
@@ -470,13 +477,13 @@ void rna_Object_ray_cast(Object *ob, ReportList *reports, float ray_start[3], fl
*index = -1;
}
-void rna_Object_closest_point_on_mesh(Object *ob, ReportList *reports, float point_co[3], float max_dist,
- float n_location[3], float n_normal[3], int *index)
+static void rna_Object_closest_point_on_mesh(Object *ob, ReportList *reports, float point_co[3], float max_dist,
+ float n_location[3], float n_normal[3], int *index)
{
BVHTreeFromMesh treeData = {NULL};
if (ob->derivedFinal == NULL) {
- BKE_reportf(reports, RPT_ERROR, "object \"%s\" has no mesh data to be used for finding nearest point",
+ BKE_reportf(reports, RPT_ERROR, "Object '%s' has no mesh data to be used for finding nearest point",
ob->id.name + 2);
return;
}
@@ -485,7 +492,7 @@ void rna_Object_closest_point_on_mesh(Object *ob, ReportList *reports, float poi
bvhtree_from_mesh_faces(&treeData, ob->derivedFinal, 0.0f, 4, 6);
if (treeData.tree == NULL) {
- BKE_reportf(reports, RPT_ERROR, "object \"%s\" could not create internal data for finding nearest point",
+ BKE_reportf(reports, RPT_ERROR, "Object '%s' could not create internal data for finding nearest point",
ob->id.name + 2);
return;
}
@@ -510,17 +517,17 @@ void rna_Object_closest_point_on_mesh(Object *ob, ReportList *reports, float poi
/* ObjectBase */
-void rna_ObjectBase_layers_from_view(Base *base, View3D *v3d)
+static void rna_ObjectBase_layers_from_view(Base *base, View3D *v3d)
{
base->lay = base->object->lay = v3d->lay;
}
-int rna_Object_is_modified(Object *ob, Scene *scene, int settings)
+static int rna_Object_is_modified(Object *ob, Scene *scene, int settings)
{
return BKE_object_is_modified(scene, ob) & settings;
}
-int rna_Object_is_deform_modified(Object *ob, Scene *scene, int settings)
+static int rna_Object_is_deform_modified(Object *ob, Scene *scene, int settings)
{
return BKE_object_is_deform_modified(scene, ob) & settings;
}
@@ -606,6 +613,7 @@ void RNA_api_object(StructRNA *srna)
"objects real matrix and layers");
parm = RNA_def_pointer(func, "scene", "Scene", "", "Scene within which to evaluate duplis");
RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_enum(func, "settings", mesh_type_items, 0, "", "Generate texture coordinates for rendering");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
func = RNA_def_function(srna, "dupli_list_clear", "rna_Object_free_duplilist");
diff --git a/source/blender/makesrna/intern/rna_object_force.c b/source/blender/makesrna/intern/rna_object_force.c
index 1c896133408..f47b864d25a 100644
--- a/source/blender/makesrna/intern/rna_object_force.c
+++ b/source/blender/makesrna/intern/rna_object_force.c
@@ -820,10 +820,13 @@ static void rna_def_pointcache(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "File Path", "Cache file path");
RNA_def_property_update(prop, NC_OBJECT, "rna_Cache_idname_change");
+ /* removed, see PTCACHE_QUICK_CACHE */
+#if 0
prop = RNA_def_property(srna, "use_quick_cache", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", PTCACHE_QUICK_CACHE);
RNA_def_property_ui_text(prop, "Quick Cache", "Update simulation with cache steps");
RNA_def_property_update(prop, NC_OBJECT, "rna_Cache_change");
+#endif
prop = RNA_def_property(srna, "info", PROP_STRING, PROP_NONE);
RNA_def_property_string_sdna(prop, NULL, "info");
@@ -1056,6 +1059,13 @@ static void rna_def_effector_weight(BlenderRNA *brna)
RNA_def_property_ui_range(prop, 0.0f, 1.0f, 0.1, 3);
RNA_def_property_ui_text(prop, "Drag", "Drag effector weight");
RNA_def_property_update(prop, 0, "rna_EffectorWeight_update");
+
+ prop = RNA_def_property(srna, "smokeflow", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "weight[13]");
+ RNA_def_property_range(prop, -200.0f, 200.0f);
+ RNA_def_property_ui_range(prop, 0.0f, 1.0f, 0.1, 3);
+ RNA_def_property_ui_text(prop, "Smoke Flow", "Smoke Flow effector weight");
+ RNA_def_property_update(prop, 0, "rna_EffectorWeight_update");
}
static void rna_def_field(BlenderRNA *brna)
@@ -1082,6 +1092,7 @@ static void rna_def_field(BlenderRNA *brna)
{PFIELD_BOID, "BOID", ICON_FORCE_BOID, "Boid", ""},
{PFIELD_TURBULENCE, "TURBULENCE", ICON_FORCE_TURBULENCE, "Turbulence", "Create turbulence with a noise field"},
{PFIELD_DRAG, "DRAG", ICON_FORCE_DRAG, "Drag", "Create a force that dampens motion"},
+ {PFIELD_SMOKEFLOW, "SMOKE_FLOW", ICON_FORCE_SMOKEFLOW, "Smoke Flow", "Create a force based on smoke simulation air flow"},
{0, NULL, 0, NULL, NULL}
};
@@ -1307,7 +1318,7 @@ static void rna_def_field(BlenderRNA *brna)
prop = RNA_def_property(srna, "use_2d_force", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", PFIELD_TEX_2D);
- RNA_def_property_ui_text(prop, "2D", "Apply force only in 2d");
+ RNA_def_property_ui_text(prop, "2D", "Apply force only in 2D");
RNA_def_property_update(prop, 0, "rna_FieldSettings_update");
prop = RNA_def_property(srna, "use_root_coords", PROP_BOOLEAN, PROP_NONE);
@@ -1334,6 +1345,11 @@ static void rna_def_field(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "flag", PFIELD_MULTIPLE_SPRINGS);
RNA_def_property_ui_text(prop, "Multiple Springs", "Every point is effected by multiple springs");
RNA_def_property_update(prop, 0, "rna_FieldSettings_update");
+
+ prop = RNA_def_property(srna, "use_smoke_density", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", PFIELD_SMOKE_DENSITY);
+ RNA_def_property_ui_text(prop, "Apply Density", "Adjust force strength based on smoke density");
+ RNA_def_property_update(prop, 0, "rna_FieldSettings_update");
/* Pointer */
@@ -1342,6 +1358,12 @@ static void rna_def_field(BlenderRNA *brna)
RNA_def_property_flag(prop, PROP_EDITABLE);
RNA_def_property_ui_text(prop, "Texture", "Texture to use as force");
RNA_def_property_update(prop, 0, "rna_FieldSettings_update");
+
+ prop = RNA_def_property(srna, "source_object", PROP_POINTER, PROP_NONE);
+ RNA_def_property_pointer_sdna(prop, NULL, "f_source");
+ RNA_def_property_ui_text(prop, "Domain Object", "Select domain object of the smoke simulation");
+ RNA_def_property_flag(prop, PROP_EDITABLE);
+ RNA_def_property_update(prop, 0, "rna_FieldSettings_update");
/********** Curve Guide Field Settings **********/
diff --git a/source/blender/makesrna/intern/rna_particle.c b/source/blender/makesrna/intern/rna_particle.c
index fc3dfafe133..9ba2a062791 100644
--- a/source/blender/makesrna/intern/rna_particle.c
+++ b/source/blender/makesrna/intern/rna_particle.c
@@ -502,7 +502,7 @@ static int rna_PartSettings_is_fluid_get(PointerRNA *ptr)
return part->type == PART_FLUID;
}
-void rna_ParticleSystem_name_set(PointerRNA *ptr, const char *value)
+static void rna_ParticleSystem_name_set(PointerRNA *ptr, const char *value)
{
Object *ob = ptr->id.data;
ParticleSystem *part = (ParticleSystem *)ptr->data;
@@ -823,12 +823,12 @@ static void psys_vg_name_set__internal(PointerRNA *ptr, const char *value, int i
psys->vgroup[index] = 0;
}
else {
- int vgroup_num = defgroup_name_index(ob, value);
+ int defgrp_index = defgroup_name_index(ob, value);
- if (vgroup_num == -1)
+ if (defgrp_index == -1)
return;
- psys->vgroup[index] = vgroup_num + 1;
+ psys->vgroup[index] = defgrp_index + 1;
}
}
diff --git a/source/blender/makesrna/intern/rna_pose.c b/source/blender/makesrna/intern/rna_pose.c
index 739f302fcbe..c29537378dd 100644
--- a/source/blender/makesrna/intern/rna_pose.c
+++ b/source/blender/makesrna/intern/rna_pose.c
@@ -148,7 +148,7 @@ void rna_ActionGroup_colorset_set(PointerRNA *ptr, int value)
}
}
-void rna_BoneGroup_name_set(PointerRNA *ptr, const char *value)
+static void rna_BoneGroup_name_set(PointerRNA *ptr, const char *value)
{
Object *ob = ptr->id.data;
bActionGroup *agrp = ptr->data;
@@ -257,7 +257,7 @@ static int rna_PoseChannel_has_ik_get(PointerRNA *ptr)
return ED_pose_channel_in_IK_chain(ob, pchan);
}
-StructRNA *rna_IKParam_refine(PointerRNA *ptr)
+static StructRNA *rna_IKParam_refine(PointerRNA *ptr)
{
bIKParam *param = (bIKParam *)ptr->data;
@@ -269,7 +269,7 @@ StructRNA *rna_IKParam_refine(PointerRNA *ptr)
}
}
-PointerRNA rna_Pose_ikparam_get(struct PointerRNA *ptr)
+static PointerRNA rna_Pose_ikparam_get(struct PointerRNA *ptr)
{
bPose *pose = (bPose *)ptr->data;
return rna_pointer_inherit_refine(ptr, &RNA_IKParam, pose->ikparam);
@@ -497,24 +497,28 @@ static bConstraint *rna_PoseChannel_constraints_new(bPoseChannel *pchan, int typ
return add_pose_constraint(NULL, pchan, NULL, type);
}
-static void rna_PoseChannel_constraints_remove(ID *id, bPoseChannel *pchan, ReportList *reports, bConstraint *con)
+static void rna_PoseChannel_constraints_remove(ID *id, bPoseChannel *pchan, ReportList *reports, PointerRNA *con_ptr)
{
+ bConstraint *con = con_ptr->data;
+ const short is_ik = ELEM(con->type, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_SPLINEIK);
+ Object *ob = (Object *)id;
+
if (BLI_findindex(&pchan->constraints, con) == -1) {
BKE_reportf(reports, RPT_ERROR, "Constraint '%s' not found in pose bone '%s'", con->name, pchan->name);
return;
}
- else {
- Object *ob = (Object *)id;
- const short is_ik = ELEM(con->type, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_SPLINEIK);
- remove_constraint(&pchan->constraints, con);
- ED_object_constraint_update(ob);
- constraints_set_active(&pchan->constraints, NULL);
- WM_main_add_notifier(NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, id);
+ remove_constraint(&pchan->constraints, con);
+ RNA_POINTER_INVALIDATE(con_ptr);
- if (is_ik) {
- BIK_clear_data(ob->pose);
- }
+ ED_object_constraint_update(ob);
+
+ constraints_set_active(&pchan->constraints, NULL); /* XXX, is this really needed? - Campbell */
+
+ WM_main_add_notifier(NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, id);
+
+ if (is_ik) {
+ BIK_clear_data(ob->pose);
}
}
@@ -593,7 +597,7 @@ static int rna_PoseChannel_rotation_4d_editable(PointerRNA *ptr, int index)
}
/* not essential, but much faster then the default lookup function */
-int rna_PoseBones_lookup_string(PointerRNA *ptr, const char *key, PointerRNA *r_ptr)
+static int rna_PoseBones_lookup_string(PointerRNA *ptr, const char *key, PointerRNA *r_ptr)
{
bPose *pose = (bPose *)ptr->data;
bPoseChannel *pchan = BKE_pose_channel_find_name(pose, key);
@@ -727,7 +731,8 @@ static void rna_def_pose_channel_constraints(BlenderRNA *brna, PropertyRNA *cpro
RNA_def_function_flag(func, FUNC_USE_REPORTS | FUNC_USE_SELF_ID); /* ID needed for refresh */
/* constraint to remove */
parm = RNA_def_pointer(func, "constraint", "Constraint", "", "Removed constraint");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
static void rna_def_pose_channel(BlenderRNA *brna)
@@ -788,8 +793,6 @@ static void rna_def_pose_channel(BlenderRNA *brna)
RNA_def_property_editable_array_func(prop, "rna_PoseChannel_location_editable");
RNA_def_property_ui_text(prop, "Location", "");
RNA_def_property_ui_range(prop, -FLT_MAX, FLT_MAX, 1, RNA_TRANSLATION_PREC_DEFAULT);
- /* XXX... disabled, since proxy-locked layers are currently used for ensuring proxy-syncing too */
- RNA_def_property_editable_func(prop, "rna_PoseChannel_proxy_editable");
RNA_def_property_update(prop, NC_OBJECT | ND_POSE, "rna_Pose_update");
prop = RNA_def_property(srna, "scale", PROP_FLOAT, PROP_XYZ);
@@ -797,8 +800,6 @@ static void rna_def_pose_channel(BlenderRNA *brna)
RNA_def_property_editable_array_func(prop, "rna_PoseChannel_scale_editable");
RNA_def_property_float_array_default(prop, default_scale);
RNA_def_property_ui_text(prop, "Scale", "");
- /* XXX... disabled, since proxy-locked layers are currently used for ensuring proxy-syncing too */
- RNA_def_property_editable_func(prop, "rna_PoseChannel_proxy_editable");
RNA_def_property_update(prop, NC_OBJECT | ND_POSE, "rna_Pose_update");
prop = RNA_def_property(srna, "rotation_quaternion", PROP_FLOAT, PROP_QUATERNION);
@@ -806,8 +807,6 @@ static void rna_def_pose_channel(BlenderRNA *brna)
RNA_def_property_editable_array_func(prop, "rna_PoseChannel_rotation_4d_editable");
RNA_def_property_float_array_default(prop, default_quat);
RNA_def_property_ui_text(prop, "Quaternion Rotation", "Rotation in Quaternions");
- /* XXX... disabled, since proxy-locked layers are currently used for ensuring proxy-syncing too */
- RNA_def_property_editable_func(prop, "rna_PoseChannel_proxy_editable");
RNA_def_property_update(prop, NC_OBJECT | ND_POSE, "rna_Pose_update");
/* XXX: for axis-angle, it would have been nice to have 2 separate fields for UI purposes, but
@@ -820,15 +819,11 @@ static void rna_def_pose_channel(BlenderRNA *brna)
RNA_def_property_editable_array_func(prop, "rna_PoseChannel_rotation_4d_editable");
RNA_def_property_float_array_default(prop, default_axisAngle);
RNA_def_property_ui_text(prop, "Axis-Angle Rotation", "Angle of Rotation for Axis-Angle rotation representation");
- /* XXX... disabled, since proxy-locked layers are currently used for ensuring proxy-syncing too */
- RNA_def_property_editable_func(prop, "rna_PoseChannel_proxy_editable");
RNA_def_property_update(prop, NC_OBJECT | ND_POSE, "rna_Pose_update");
prop = RNA_def_property(srna, "rotation_euler", PROP_FLOAT, PROP_EULER);
RNA_def_property_float_sdna(prop, NULL, "eul");
RNA_def_property_editable_array_func(prop, "rna_PoseChannel_rotation_euler_editable");
- /* XXX... disabled, since proxy-locked layers are currently used for ensuring proxy-syncing too */
- RNA_def_property_editable_func(prop, "rna_PoseChannel_proxy_editable");
RNA_def_property_ui_text(prop, "Euler Rotation", "Rotation in Eulers");
RNA_def_property_update(prop, NC_OBJECT | ND_POSE, "rna_Pose_update");
@@ -1310,7 +1305,7 @@ static void rna_def_pose(BlenderRNA *brna)
/* animviz */
rna_def_animviz_common(srna);
- /* RNA_api_pose(srna); */
+ RNA_api_pose(srna);
}
void RNA_def_pose(BlenderRNA *brna)
diff --git a/source/blender/makesrna/intern/rna_pose_api.c b/source/blender/makesrna/intern/rna_pose_api.c
index ed4690ac6a7..29d7c616d25 100644
--- a/source/blender/makesrna/intern/rna_pose_api.c
+++ b/source/blender/makesrna/intern/rna_pose_api.c
@@ -34,12 +34,16 @@
#include <string.h>
#include <time.h>
+#include "BLI_utildefines.h"
+
#include "RNA_define.h"
#include "DNA_object_types.h"
/* #include "BLO_sys_types.h" */
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
/* #include "DNA_anim_types.h" */
@@ -57,7 +61,7 @@ static float rna_PoseBone_do_envelope(bPoseChannel *chan, float *vec)
}
#else
-void RNA_api_pose(StructRNA *srna)
+void RNA_api_pose(StructRNA *UNUSED(srna))
{
/* FunctionRNA *func; */
/* PropertyRNA *parm; */
diff --git a/source/blender/makesrna/intern/rna_property.c b/source/blender/makesrna/intern/rna_property.c
index bf9f924489b..fc3697633a4 100644
--- a/source/blender/makesrna/intern/rna_property.c
+++ b/source/blender/makesrna/intern/rna_property.c
@@ -89,7 +89,7 @@ static void rna_GameProperty_type_set(PointerRNA *ptr, int value)
if (prop->type != value) {
prop->type = value;
- init_property(prop);
+ BKE_bproperty_init(prop);
}
}
@@ -97,7 +97,7 @@ static void rna_GameProperty_name_set(PointerRNA *ptr, const char *value)
{
bProperty *prop = (bProperty *)(ptr->data);
BLI_strncpy_utf8(prop->name, value, sizeof(prop->name));
- unique_property(NULL, prop, 1);
+ BKE_bproperty_unique(NULL, prop, 1);
}
diff --git a/source/blender/makesrna/intern/rna_render.c b/source/blender/makesrna/intern/rna_render.c
index d2e4e8edbfb..46b22cd0963 100644
--- a/source/blender/makesrna/intern/rna_render.c
+++ b/source/blender/makesrna/intern/rna_render.c
@@ -50,12 +50,12 @@
/* RenderEngine Callbacks */
-void engine_tag_redraw(RenderEngine *engine)
+static void engine_tag_redraw(RenderEngine *engine)
{
engine->flag |= RE_ENGINE_DO_DRAW;
}
-void engine_tag_update(RenderEngine *engine)
+static void engine_tag_update(RenderEngine *engine)
{
engine->flag |= RE_ENGINE_DO_UPDATE;
}
@@ -129,6 +129,24 @@ static void engine_view_draw(RenderEngine *engine, const struct bContext *contex
RNA_parameter_list_free(&list);
}
+static void engine_update_script_node(RenderEngine *engine, struct bNodeTree *ntree, struct bNode *node)
+{
+ extern FunctionRNA rna_RenderEngine_update_script_node_func;
+ PointerRNA ptr, nodeptr;
+ ParameterList list;
+ FunctionRNA *func;
+
+ RNA_pointer_create(NULL, engine->type->ext.srna, engine, &ptr);
+ RNA_pointer_create((ID*)ntree, &RNA_Node, node, &nodeptr);
+ func = &rna_RenderEngine_update_script_node_func;
+
+ RNA_parameter_list_create(&list, &ptr, func);
+ RNA_parameter_set_lookup(&list, "node", &nodeptr);
+ engine->type->ext.call(NULL, &ptr, func, &list);
+
+ RNA_parameter_list_free(&list);
+}
+
/* RenderEngine registration */
static void rna_RenderEngine_unregister(Main *UNUSED(bmain), StructRNA *type)
@@ -149,7 +167,7 @@ static StructRNA *rna_RenderEngine_register(Main *bmain, ReportList *reports, vo
RenderEngineType *et, dummyet = {NULL};
RenderEngine dummyengine = {NULL};
PointerRNA dummyptr;
- int have_function[4];
+ int have_function[5];
/* setup dummy engine & engine type to store static properties in */
dummyengine.type = &dummyet;
@@ -160,7 +178,7 @@ static StructRNA *rna_RenderEngine_register(Main *bmain, ReportList *reports, vo
return NULL;
if (strlen(identifier) >= sizeof(dummyet.idname)) {
- BKE_reportf(reports, RPT_ERROR, "registering render engine class: '%s' is too long, maximum length is %d",
+ BKE_reportf(reports, RPT_ERROR, "Registering render engine class: '%s' is too long, maximum length is %d",
identifier, (int)sizeof(dummyet.idname));
return NULL;
}
@@ -188,6 +206,7 @@ static StructRNA *rna_RenderEngine_register(Main *bmain, ReportList *reports, vo
et->render = (have_function[1]) ? engine_render : NULL;
et->view_update = (have_function[2]) ? engine_view_update : NULL;
et->view_draw = (have_function[3]) ? engine_view_draw : NULL;
+ et->update_script_node = (have_function[4]) ? engine_update_script_node : NULL;
BLI_addtail(&R_engines, et);
@@ -300,6 +319,13 @@ static void rna_def_render_engine(BlenderRNA *brna)
RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL);
RNA_def_pointer(func, "context", "Context", "", "");
+ /* shader script callbacks */
+ func = RNA_def_function(srna, "update_script_node", NULL);
+ RNA_def_function_ui_description(func, "Compile shader script node");
+ RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL | FUNC_ALLOW_WRITE);
+ prop = RNA_def_pointer(func, "node", "Node", "", "");
+ RNA_def_property_flag(prop, PROP_RNAPTR);
+
/* tag for redraw */
RNA_def_function(srna, "tag_redraw", "engine_tag_redraw");
RNA_def_function_ui_description(func, "Request redraw for viewport rendering");
@@ -328,8 +354,7 @@ static void rna_def_render_engine(BlenderRNA *brna)
func = RNA_def_function(srna, "end_result", "RE_engine_end_result");
prop = RNA_def_pointer(func, "result", "RenderResult", "Result", "");
RNA_def_property_flag(prop, PROP_REQUIRED);
- prop = RNA_def_boolean(func, "cancel", 0, "Cancel", "Don't merge back results");
- RNA_def_property_flag(prop, PROP_REQUIRED);
+ RNA_def_boolean(func, "cancel", 0, "Cancel", "Don't merge back results");
func = RNA_def_function(srna, "test_break", "RE_engine_test_break");
prop = RNA_def_boolean(func, "do_break", 0, "Break", "");
@@ -345,6 +370,11 @@ static void rna_def_render_engine(BlenderRNA *brna)
prop = RNA_def_float(func, "progress", 0, 0.0f, 1.0f, "", "Percentage of render that's done", 0.0f, 1.0f);
RNA_def_property_flag(prop, PROP_REQUIRED);
+ func = RNA_def_function(srna, "update_memory_stats", "RE_engine_update_memory_stats");
+ RNA_def_float(func, "memory_used", 0, 0.0f, FLT_MAX, "", "Current memory usage in megabytes", 0.0f, FLT_MAX);
+ RNA_def_float(func, "memory_peak", 0, 0.0f, FLT_MAX, "", "Peak memory usage in megabytes", 0.0f, FLT_MAX);
+ RNA_def_property_flag(prop, PROP_REQUIRED);
+
func = RNA_def_function(srna, "report", "RE_engine_report");
prop = RNA_def_enum_flag(func, "type", wm_report_items, 0, "Type", "");
RNA_def_property_flag(prop, PROP_REQUIRED);
diff --git a/source/blender/makesrna/intern/rna_rna.c b/source/blender/makesrna/intern/rna_rna.c
index db309ed8f1f..7355e464fc3 100644
--- a/source/blender/makesrna/intern/rna_rna.c
+++ b/source/blender/makesrna/intern/rna_rna.c
@@ -829,7 +829,7 @@ static void rna_EnumProperty_items_begin(CollectionPropertyIterator *iter, Point
int totitem, free = 0;
rna_idproperty_check(&prop, ptr);
- /* eprop= (EnumPropertyRNA *)prop; */
+ /* eprop = (EnumPropertyRNA *)prop; */
RNA_property_enum_items(NULL, ptr, prop, &item, &totitem, &free);
rna_iterator_array_begin(iter, (void *)item, sizeof(EnumPropertyItem), totitem, free, rna_enum_check_separator);
diff --git a/source/blender/makesrna/intern/rna_scene.c b/source/blender/makesrna/intern/rna_scene.c
index 0227d9c1554..69bb1cc98ff 100644
--- a/source/blender/makesrna/intern/rna_scene.c
+++ b/source/blender/makesrna/intern/rna_scene.c
@@ -159,12 +159,13 @@ EnumPropertyItem snap_node_element_items[] = {
#define R_IMF_ENUM_TAGA_RAW {R_IMF_IMTYPE_RAWTGA, "TARGA_RAW", ICON_FILE_IMAGE, "Targa Raw", \
"Output image in uncompressed Targa format"},
-
+#if 0 /* UNUSED (so far) */
#ifdef WITH_DDS
# define R_IMF_ENUM_DDS {R_IMF_IMTYPE_DDS, "DDS", ICON_FILE_IMAGE, "DDS", "Output image in DDS format"},
#else
# define R_IMF_ENUM_DDS
#endif
+#endif
#ifdef WITH_OPENJPEG
# define R_IMF_ENUM_JPEG2K {R_IMF_IMTYPE_JP2, "JPEG2000", ICON_FILE_IMAGE, "JPEG 2000", \
@@ -275,6 +276,7 @@ EnumPropertyItem image_color_mode_items[] = {
EnumPropertyItem image_color_depth_items[] = {
/* 1 (monochrome) not used */
{R_IMF_CHAN_DEPTH_8, "8", 0, "8", "8 bit color channels"},
+ {R_IMF_CHAN_DEPTH_10, "10", 0, "10", "10 bit color channels"},
{R_IMF_CHAN_DEPTH_12, "12", 0, "12", "12 bit color channels"},
{R_IMF_CHAN_DEPTH_16, "16", 0, "16", "16 bit color channels"},
/* 24 not used */
@@ -356,7 +358,7 @@ static Base *rna_Scene_object_link(Scene *scene, bContext *C, ReportList *report
Base *base;
if (BKE_scene_base_find(scene, ob)) {
- BKE_reportf(reports, RPT_ERROR, "Object \"%s\" is already in scene \"%s\"", ob->id.name + 2, scene->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Object '%s' is already in scene '%s'", ob->id.name + 2, scene->id.name + 2);
return NULL;
}
@@ -388,7 +390,7 @@ static void rna_Scene_object_unlink(Scene *scene, ReportList *reports, Object *o
return;
}
if (base == scene->basact && ob->mode != OB_MODE_OBJECT) {
- BKE_reportf(reports, RPT_ERROR, "Object '%s' must be in 'Object Mode' to unlink", ob->id.name + 2);
+ BKE_reportf(reports, RPT_ERROR, "Object '%s' must be in object mode to unlink", ob->id.name + 2);
return;
}
if (scene->basact == base) {
@@ -498,7 +500,7 @@ static void rna_Scene_framelen_update(Main *UNUSED(bmain), Scene *scene, Pointer
}
-static void rna_Scene_current_frame_set(PointerRNA *ptr, int value)
+static void rna_Scene_frame_current_set(PointerRNA *ptr, int value)
{
Scene *data = (Scene *)ptr->data;
@@ -713,6 +715,7 @@ static void rna_ImageFormatSettings_file_format_set(PointerRNA *ptr, int value)
R_IMF_CHAN_DEPTH_24,
R_IMF_CHAN_DEPTH_16,
R_IMF_CHAN_DEPTH_12,
+ R_IMF_CHAN_DEPTH_10,
R_IMF_CHAN_DEPTH_8,
R_IMF_CHAN_DEPTH_1,
0};
@@ -810,9 +813,10 @@ static EnumPropertyItem *rna_ImageFormatSettings_color_depth_itemf(bContext *C,
const int is_float = ELEM3(imf->imtype, R_IMF_IMTYPE_RADHDR, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER);
EnumPropertyItem *item_8bit = &image_color_depth_items[0];
- EnumPropertyItem *item_12bit = &image_color_depth_items[1];
- EnumPropertyItem *item_16bit = &image_color_depth_items[2];
- EnumPropertyItem *item_32bit = &image_color_depth_items[3];
+ EnumPropertyItem *item_10bit = &image_color_depth_items[1];
+ EnumPropertyItem *item_12bit = &image_color_depth_items[2];
+ EnumPropertyItem *item_16bit = &image_color_depth_items[3];
+ EnumPropertyItem *item_32bit = &image_color_depth_items[4];
int totitem = 0;
EnumPropertyItem *item = NULL;
@@ -822,6 +826,10 @@ static EnumPropertyItem *rna_ImageFormatSettings_color_depth_itemf(bContext *C,
RNA_enum_item_add(&item, &totitem, item_8bit);
}
+ if (depth_ok & R_IMF_CHAN_DEPTH_10) {
+ RNA_enum_item_add(&item, &totitem, item_10bit);
+ }
+
if (depth_ok & R_IMF_CHAN_DEPTH_12) {
RNA_enum_item_add(&item, &totitem, item_12bit);
}
@@ -1025,17 +1033,20 @@ static SceneRenderLayer *rna_RenderLayer_new(ID *id, RenderData *UNUSED(rd), con
}
static void rna_RenderLayer_remove(ID *id, RenderData *UNUSED(rd), Main *bmain, ReportList *reports,
- SceneRenderLayer *srl)
+ PointerRNA *srl_ptr)
{
+ SceneRenderLayer *srl = srl_ptr->data;
Scene *scene = (Scene *)id;
if (!BKE_scene_remove_render_layer(bmain, scene, srl)) {
- BKE_reportf(reports, RPT_ERROR, "RenderLayer '%s' could not be removed from scene '%s'",
+ BKE_reportf(reports, RPT_ERROR, "Render layer '%s' could not be removed from scene '%s'",
srl->name, scene->id.name + 2);
+ return;
}
- else {
- WM_main_add_notifier(NC_SCENE | ND_RENDER_OPTIONS, NULL);
- }
+
+ RNA_POINTER_INVALIDATE(srl_ptr);
+
+ WM_main_add_notifier(NC_SCENE | ND_RENDER_OPTIONS, NULL);
}
static void rna_RenderSettings_engine_set(PointerRNA *ptr, int value)
@@ -1208,9 +1219,12 @@ static void object_simplify_update(Object *ob)
ModifierData *md;
ParticleSystem *psys;
- for (md = ob->modifiers.first; md; md = md->next)
- if (ELEM3(md->type, eModifierType_Subsurf, eModifierType_Multires, eModifierType_ParticleSystem))
- ob->recalc |= OB_RECALC_DATA | PSYS_RECALC_CHILD;
+ for (md = ob->modifiers.first; md; md = md->next) {
+ if (ELEM3(md->type, eModifierType_Subsurf, eModifierType_Multires, eModifierType_ParticleSystem)) {
+ ob->recalc |= PSYS_RECALC_CHILD;
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ }
+ }
for (psys = ob->particlesystem.first; psys; psys = psys->next)
psys->recalc |= PSYS_RECALC_CHILD;
@@ -1322,15 +1336,16 @@ static TimeMarker *rna_TimeLine_add(Scene *scene, const char name[])
return marker;
}
-static void rna_TimeLine_remove(Scene *scene, ReportList *reports, TimeMarker *marker)
+static void rna_TimeLine_remove(Scene *scene, ReportList *reports, PointerRNA *marker_ptr)
{
- if (!BLI_remlink_safe(&scene->markers, marker)) {
- BKE_reportf(reports, RPT_ERROR, "TimelineMarker '%s' not found in scene '%s'", marker->name, scene->id.name + 2);
+ TimeMarker *marker = marker_ptr->data;
+ if (BLI_remlink_safe(&scene->markers, marker) == FALSE) {
+ BKE_reportf(reports, RPT_ERROR, "Timeline marker '%s' not found in scene '%s'", marker->name, scene->id.name + 2);
return;
}
- /* XXX, invalidates PyObject */
MEM_freeN(marker);
+ RNA_POINTER_INVALIDATE(marker_ptr);
WM_main_add_notifier(NC_SCENE | ND_MARKERS, NULL);
WM_main_add_notifier(NC_ANIMATION | ND_MARKERS, NULL);
@@ -1356,7 +1371,7 @@ static KeyingSet *rna_Scene_keying_set_new(Scene *sce, ReportList *reports, cons
return ks;
}
else {
- BKE_report(reports, RPT_ERROR, "Keying Set could not be added");
+ BKE_report(reports, RPT_ERROR, "Keying set could not be added");
return NULL;
}
}
@@ -1403,6 +1418,12 @@ static void rna_SceneCamera_update(Main *UNUSED(bmain), Scene *UNUSED(scene), Po
DAG_id_tag_update(&camera->id, 0);
}
+static void rna_SceneSequencer_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr))
+{
+ BKE_sequencer_cache_cleanup();
+ BKE_sequencer_preprocessed_cache_cleanup();
+}
+
#else
static void rna_def_transform_orientation(BlenderRNA *brna)
@@ -2795,7 +2816,8 @@ static void rna_def_render_layers(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove a render layer");
RNA_def_function_flag(func, FUNC_USE_MAIN | FUNC_USE_REPORTS | FUNC_USE_SELF_ID);
parm = RNA_def_pointer(func, "layer", "SceneRenderLayer", "", "Timeline marker to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
/* use for render output and image save operator,
@@ -2887,7 +2909,6 @@ static void rna_def_scene_image_format_data(BlenderRNA *brna)
#endif
-
#ifdef WITH_OPENJPEG
/* Jpeg 2000 */
prop = RNA_def_property(srna, "use_jpeg2k_ycc", PROP_BOOLEAN, PROP_NONE);
@@ -2909,7 +2930,7 @@ static void rna_def_scene_image_format_data(BlenderRNA *brna)
/* Cineon and DPX */
prop = RNA_def_property(srna, "use_cineon_log", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "cineon_flag", R_CINEON_LOG);
+ RNA_def_property_boolean_sdna(prop, NULL, "cineon_flag", R_IMF_CINEON_FLAG_LOG);
RNA_def_property_ui_text(prop, "Log", "Convert to logarithmic color space");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
@@ -3105,6 +3126,7 @@ static void rna_def_scene_ffmpeg_settings(BlenderRNA *brna)
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_ui_text(prop, "Volume", "Audio volume");
+ RNA_def_property_translation_context(prop, "Audio");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
#endif
@@ -3373,16 +3395,16 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Resolution %", "Percentage scale for render resolution");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
- prop = RNA_def_property(srna, "parts_x", PROP_INT, PROP_NONE);
- RNA_def_property_int_sdna(prop, NULL, "xparts");
- RNA_def_property_range(prop, 1, 512);
- RNA_def_property_ui_text(prop, "Parts X", "Number of horizontal tiles to use while rendering");
+ prop = RNA_def_property(srna, "tile_x", PROP_INT, PROP_NONE);
+ RNA_def_property_int_sdna(prop, NULL, "tilex");
+ RNA_def_property_range(prop, 8, 10000);
+ RNA_def_property_ui_text(prop, "Tile X", "Horizontal tile size to use while rendering");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
- prop = RNA_def_property(srna, "parts_y", PROP_INT, PROP_NONE);
- RNA_def_property_int_sdna(prop, NULL, "yparts");
- RNA_def_property_range(prop, 1, 512);
- RNA_def_property_ui_text(prop, "Parts Y", "Number of vertical tiles to use while rendering");
+ prop = RNA_def_property(srna, "tile_y", PROP_INT, PROP_NONE);
+ RNA_def_property_int_sdna(prop, NULL, "tiley");
+ RNA_def_property_range(prop, 8, 10000);
+ RNA_def_property_ui_text(prop, "Tile Y", "Vertical tile size to use while rendering");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
prop = RNA_def_property(srna, "pixel_aspect_x", PROP_FLOAT, PROP_NONE);
@@ -3598,14 +3620,14 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "mode", R_MBLUR);
RNA_def_property_ui_text(prop, "Motion Blur", "Use multi-sampled 3D scene motion blur");
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
+ RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, "rna_Scene_glsl_update");
prop = RNA_def_property(srna, "motion_blur_samples", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "mblur_samples");
RNA_def_property_range(prop, 1, 32);
RNA_def_property_ui_text(prop, "Motion Samples", "Number of scene samples to take with motion blur");
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
+ RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, "rna_Scene_glsl_update");
prop = RNA_def_property(srna, "motion_blur_shutter", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "blurfac");
@@ -3613,7 +3635,7 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
RNA_def_property_ui_range(prop, 0.01, 2.0f, 1, 0);
RNA_def_property_ui_text(prop, "Shutter", "Time taken in frames between shutter open and close");
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
+ RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, "rna_Scene_glsl_update");
/* border */
prop = RNA_def_property(srna, "use_border", PROP_BOOLEAN, PROP_NONE);
@@ -3928,15 +3950,17 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "seq_flag", R_SEQ_GL_PREV);
RNA_def_property_ui_text(prop, "Sequencer OpenGL", "");
+#if 0 /* see R_SEQ_GL_REND comment */
prop = RNA_def_property(srna, "use_sequencer_gl_render", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "seq_flag", R_SEQ_GL_REND);
RNA_def_property_ui_text(prop, "Sequencer OpenGL", "");
-
+#endif
prop = RNA_def_property(srna, "sequencer_gl_preview", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "seq_prev_type");
RNA_def_property_enum_items(prop, viewport_shade_items);
RNA_def_property_ui_text(prop, "Sequencer Preview Shading", "Method to draw in the sequencer view");
+ RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SceneSequencer_update");
prop = RNA_def_property(srna, "sequencer_gl_render", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "seq_rend_type");
@@ -3962,6 +3986,7 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
RNA_def_property_enum_items(prop, engine_items);
RNA_def_property_enum_funcs(prop, "rna_RenderSettings_engine_get", "rna_RenderSettings_engine_set",
"rna_RenderSettings_engine_itemf");
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
RNA_def_property_ui_text(prop, "Engine", "Engine to use for rendering");
RNA_def_property_update(prop, NC_WINDOW, "rna_RenderSettings_engine_update");
@@ -4103,7 +4128,8 @@ static void rna_def_timeline_markers(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove a timeline marker");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "marker", "TimelineMarker", "", "Timeline marker to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "clear", "rna_TimeLine_clear");
RNA_def_function_ui_description(func, "Remove all timeline markers");
@@ -4299,7 +4325,7 @@ void RNA_def_scene(BlenderRNA *brna)
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
RNA_def_property_int_sdna(prop, NULL, "r.cfra");
RNA_def_property_range(prop, MINAFRAME, MAXFRAME);
- RNA_def_property_int_funcs(prop, NULL, "rna_Scene_current_frame_set", NULL);
+ RNA_def_property_int_funcs(prop, NULL, "rna_Scene_frame_current_set", NULL);
RNA_def_property_ui_text(prop, "Current Frame",
"Current Frame, to update animation data from python frame_set() instead");
RNA_def_property_update(prop, NC_SCENE | ND_FRAME, "rna_Scene_frame_update");
@@ -4515,6 +4541,7 @@ void RNA_def_scene(BlenderRNA *brna)
RNA_def_property_float_sdna(prop, NULL, "audio.volume");
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_ui_text(prop, "Volume", "Audio volume");
+ RNA_def_property_translation_context(prop, BLF_I18NCONTEXT_AUDIO);
RNA_def_property_update(prop, NC_SCENE, NULL);
RNA_def_property_float_funcs(prop, NULL, "rna_Scene_volume_set", NULL);
@@ -4566,7 +4593,7 @@ void RNA_def_scene(BlenderRNA *brna)
prop = RNA_def_property(srna, "sequencer_colorspace_settings", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "sequencer_colorspace_settings");
RNA_def_property_struct_type(prop, "ColorManagedColorspaceSettings");
- RNA_def_property_ui_text(prop, "Sequencer Colorspace Settings", "Settings of color space sequencer is working in");
+ RNA_def_property_ui_text(prop, "Sequencer Color Space Settings", "Settings of color space sequencer is working in");
/* Nestled Data */
rna_def_tool_settings(brna);
diff --git a/source/blender/makesrna/intern/rna_scene_api.c b/source/blender/makesrna/intern/rna_scene_api.c
index 69b61b47d8a..63253153699 100644
--- a/source/blender/makesrna/intern/rna_scene_api.c
+++ b/source/blender/makesrna/intern/rna_scene_api.c
@@ -40,6 +40,8 @@
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include "BKE_animsys.h"
@@ -51,7 +53,7 @@
-void rna_Scene_frame_set(Scene *scene, int frame, float subframe)
+static void rna_Scene_frame_set(Scene *scene, int frame, float subframe)
{
scene->r.cfra = frame;
scene->r.subframe = subframe;
@@ -87,29 +89,29 @@ static void rna_SceneRender_get_frame_path(RenderData *rd, int frame, char *name
#include "../../collada/collada.h"
static void rna_Scene_collada_export(
- Scene *scene,
- const char *filepath,
- int apply_modifiers,
- int export_mesh_type,
-
- int selected,
- int include_children,
- int include_armatures,
- int deform_bones_only,
-
- int active_uv_only,
- int include_uv_textures,
- int include_material_textures,
- int use_texture_copies,
-
- int use_object_instantiation,
- int sort_by_name,
- int second_life)
+ Scene *scene,
+ const char *filepath,
+ int apply_modifiers,
+ int export_mesh_type,
+
+ int selected,
+ int include_children,
+ int include_armatures,
+ int deform_bones_only,
+
+ int active_uv_only,
+ int include_uv_textures,
+ int include_material_textures,
+ int use_texture_copies,
+
+ int use_object_instantiation,
+ int sort_by_name,
+ int second_life)
{
- collada_export(scene, filepath, apply_modifiers, export_mesh_type, selected,
+ collada_export(scene, filepath, apply_modifiers, export_mesh_type, selected,
include_children, include_armatures, deform_bones_only,
- active_uv_only, include_uv_textures, include_material_textures,
- use_texture_copies, use_object_instantiation, sort_by_name, second_life);
+ active_uv_only, include_uv_textures, include_material_textures,
+ use_texture_copies, use_object_instantiation, sort_by_name, second_life);
}
#endif
diff --git a/source/blender/makesrna/intern/rna_screen.c b/source/blender/makesrna/intern/rna_screen.c
index a6d4e473df4..32e388598f5 100644
--- a/source/blender/makesrna/intern/rna_screen.c
+++ b/source/blender/makesrna/intern/rna_screen.c
@@ -140,12 +140,12 @@ static void rna_Area_type_update(bContext *C, PointerRNA *ptr)
}
}
-void rna_View2D_region_to_view(struct View2D *v2d, int x, int y, float result[2])
+static void rna_View2D_region_to_view(struct View2D *v2d, int x, int y, float result[2])
{
UI_view2d_region_to_view(v2d, x, y, &result[0], &result[1]);
}
-void rna_View2D_view_to_region(struct View2D *v2d, float x, float y, int clip, int result[2])
+static void rna_View2D_view_to_region(struct View2D *v2d, float x, float y, int clip, int result[2])
{
if (clip)
UI_view2d_view_to_region(v2d, x, y, &result[0], &result[1]);
diff --git a/source/blender/makesrna/intern/rna_sculpt_paint.c b/source/blender/makesrna/intern/rna_sculpt_paint.c
index 58d676555c1..84e76fae896 100644
--- a/source/blender/makesrna/intern/rna_sculpt_paint.c
+++ b/source/blender/makesrna/intern/rna_sculpt_paint.c
@@ -60,6 +60,8 @@ static EnumPropertyItem particle_edit_hair_brush_items[] = {
#include "BKE_particle.h"
#include "BKE_depsgraph.h"
+#include "BLI_pbvh.h"
+
#include "ED_particle.h"
static EnumPropertyItem particle_edit_disconnected_hair_brush_items[] = {
@@ -206,6 +208,21 @@ static void rna_Sculpt_update(Main *UNUSED(bmain), Scene *scene, PointerRNA *UNU
}
}
+static void rna_Sculpt_ShowDiffuseColor_update(Main *UNUSED(bmain), Scene *scene, PointerRNA *UNUSED(ptr))
+{
+ Object *ob = (scene->basact) ? scene->basact->object : NULL;
+
+ if (ob) {
+ Sculpt *sd = scene->toolsettings->sculpt;
+ ob->sculpt->show_diffuse_color = sd->flags & SCULPT_SHOW_DIFFUSE;
+
+ if (ob->sculpt->pbvh)
+ pbvh_show_diffuse_color_set(ob->sculpt->pbvh, ob->sculpt->show_diffuse_color);
+
+ WM_main_add_notifier(NC_OBJECT | ND_DRAW, ob);
+ }
+}
+
#else
static void rna_def_paint(BlenderRNA *brna)
@@ -297,6 +314,12 @@ static void rna_def_sculpt(BlenderRNA *brna)
"Use only deformation modifiers (temporary disable all "
"constructive modifiers except multi-resolution)");
RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, "rna_Sculpt_update");
+
+ prop = RNA_def_property(srna, "show_diffuse_color", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flags", SCULPT_SHOW_DIFFUSE);
+ RNA_def_property_ui_text(prop, "Show Diffuse Color",
+ "Show diffuse color of object and overlay sculpt mask on top of it");
+ RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, "rna_Sculpt_ShowDiffuseColor_update");
}
diff --git a/source/blender/makesrna/intern/rna_sensor.c b/source/blender/makesrna/intern/rna_sensor.c
index 314082dfd02..6097fa2ae96 100644
--- a/source/blender/makesrna/intern/rna_sensor.c
+++ b/source/blender/makesrna/intern/rna_sensor.c
@@ -104,7 +104,7 @@ static StructRNA *rna_Sensor_refine(struct PointerRNA *ptr)
}
}
-void rna_Sensor_name_set(PointerRNA *ptr, const char *value)
+static void rna_Sensor_name_set(PointerRNA *ptr, const char *value)
{
bSensor *sens = (bSensor *)ptr->data;
diff --git a/source/blender/makesrna/intern/rna_sensor_api.c b/source/blender/makesrna/intern/rna_sensor_api.c
index fd0c6f622ff..d920cbef4a2 100644
--- a/source/blender/makesrna/intern/rna_sensor_api.c
+++ b/source/blender/makesrna/intern/rna_sensor_api.c
@@ -35,6 +35,8 @@
#include "WM_types.h"
#include "RNA_define.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include "BKE_sca.h"
diff --git a/source/blender/makesrna/intern/rna_sequencer.c b/source/blender/makesrna/intern/rna_sequencer.c
index b27148e964d..054d0cc82c6 100644
--- a/source/blender/makesrna/intern/rna_sequencer.c
+++ b/source/blender/makesrna/intern/rna_sequencer.c
@@ -50,6 +50,8 @@
#include "WM_types.h"
#include "BLI_math.h"
+#include "BLF_translation.h"
+
typedef struct EffectInfo {
const char *struct_name;
const char *ui_name;
@@ -405,7 +407,7 @@ static void rna_Sequence_name_set(PointerRNA *ptr, const char *value)
BLI_strncpy_utf8(seq->name + 2, value, sizeof(seq->name) - 2);
/* make sure the name is unique */
- BKE_seqence_base_unique_name_recursive(&scene->ed->seqbase, seq);
+ BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seq);
/* fix all the animation data which may link to this */
@@ -699,12 +701,6 @@ static int colbalance_seq_cmp_cb(Sequence *seq, void *arg_pt)
{
SequenceSearchData *data = arg_pt;
- if (seq->strip && seq->strip->color_balance == data->data) {
- data->seq = seq;
- data->smd = NULL;
- return -1; /* done so bail out */
- }
-
if (seq->modifiers.first) {
SequenceModifierData *smd = seq->modifiers.first;
@@ -970,18 +966,20 @@ static SequenceModifierData *rna_Sequence_modifier_new(Sequence *seq, bContext *
}
}
-static void rna_Sequence_modifier_remove(Sequence *seq, bContext *C, ReportList *reports, SequenceModifierData *smd)
+static void rna_Sequence_modifier_remove(Sequence *seq, bContext *C, ReportList *reports, PointerRNA *smd_ptr)
{
+ SequenceModifierData *smd = smd_ptr->data;
Scene *scene = CTX_data_scene(C);
- if (BKE_sequence_modifier_remove(seq, smd)) {
- BKE_sequence_invalidate_cache_for_modifier(scene, seq);
-
- WM_main_add_notifier(NC_SCENE | ND_SEQUENCER, NULL);
- }
- else {
+ if (BKE_sequence_modifier_remove(seq, smd) == FALSE) {
BKE_report(reports, RPT_ERROR, "Modifier was not found in the stack");
+ return;
}
+
+ RNA_POINTER_INVALIDATE(smd_ptr);
+ BKE_sequence_invalidate_cache_for_modifier(scene, seq);
+
+ WM_main_add_notifier(NC_SCENE | ND_SEQUENCER, NULL);
}
static void rna_Sequence_modifier_clear(Sequence *seq, bContext *C)
@@ -1271,7 +1269,8 @@ static void rna_def_sequence_modifiers(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove an existing modifier from the sequence");
/* modifier to remove */
parm = RNA_def_pointer(func, "modifier", "SequenceModifier", "", "Modifier to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
/* clear all modifiers */
func = RNA_def_function(srna, "clear", "rna_Sequence_modifier_clear");
@@ -1679,14 +1678,14 @@ static void rna_def_effect_inputs(StructRNA *srna, int count)
RNA_def_property_ui_text(prop, "Input 2", "Second input for the effect strip");
}
- /*
+#if 0
if (count == 3) { // not used by any effects (perhaps one day plugins?)
prop = RNA_def_property(srna, "input_3", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "seq3");
RNA_def_property_flag(prop, PROP_EDITABLE | PROP_NEVER_NULL);
RNA_def_property_ui_text(prop, "Input 3", "Third input for the effect strip");
}
- */
+#endif
}
static void rna_def_image(BlenderRNA *brna)
@@ -1864,6 +1863,7 @@ static void rna_def_sound(BlenderRNA *brna)
RNA_def_property_float_sdna(prop, NULL, "volume");
RNA_def_property_range(prop, 0.0f, 100.0f);
RNA_def_property_ui_text(prop, "Volume", "Playback volume of the sound");
+ RNA_def_property_translation_context(prop, BLF_I18NCONTEXT_AUDIO);
RNA_def_property_float_funcs(prop, NULL, "rna_Sequence_volume_set", NULL);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
@@ -1871,6 +1871,7 @@ static void rna_def_sound(BlenderRNA *brna)
RNA_def_property_float_sdna(prop, NULL, "pitch");
RNA_def_property_range(prop, 0.1f, 10.0f);
RNA_def_property_ui_text(prop, "Pitch", "Playback pitch of the sound");
+ RNA_def_property_translation_context(prop, BLF_I18NCONTEXT_AUDIO);
RNA_def_property_float_funcs(prop, NULL, "rna_Sequence_pitch_set", NULL);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
diff --git a/source/blender/makesrna/intern/rna_sequencer_api.c b/source/blender/makesrna/intern/rna_sequencer_api.c
index ab1dfbf22b0..8ddb9d0a7e7 100644
--- a/source/blender/makesrna/intern/rna_sequencer_api.c
+++ b/source/blender/makesrna/intern/rna_sequencer_api.c
@@ -37,8 +37,6 @@
#include "DNA_scene_types.h"
#include "DNA_sequence_types.h"
-extern EnumPropertyItem blend_mode_items[];
-
#ifdef RNA_RUNTIME
//#include "DNA_anim_types.h"
@@ -83,7 +81,7 @@ static Sequence *alloc_generic_sequence(Editing *ed, const char *name, int start
seq->type = type;
BLI_strncpy(seq->name + 2, name, sizeof(seq->name) - 2);
- BKE_seqence_base_unique_name_recursive(&ed->seqbase, seq);
+ BKE_sequence_base_unique_name_recursive(&ed->seqbase, seq);
seq->strip = strip = MEM_callocN(sizeof(Strip), "strip");
seq->strip->us = 1;
@@ -236,9 +234,10 @@ static Sequence *rna_Sequences_new_sound(ID *id, Editing *ed, Main *bmain, Repor
}
#else /* WITH_AUDASPACE */
static Sequence *rna_Sequences_new_sound(ID *UNUSED(id), Editing *UNUSED(ed), Main *UNUSED(bmain), ReportList *reports,
- const char *UNUSED(name), const char *UNUSED(file), int UNUSED(channel), int UNUSED(start_frame))
+ const char *UNUSED(name), const char *UNUSED(file), int UNUSED(channel),
+ int UNUSED(start_frame))
{
- BKE_report(reports, RPT_ERROR, "Blender compiled without Audaspace support.");
+ BKE_report(reports, RPT_ERROR, "Blender compiled without Audaspace support");
return NULL;
}
#endif /* WITH_AUDASPACE */
@@ -251,39 +250,37 @@ static Sequence *rna_Sequences_new_effect(ID *id, Editing *ed, ReportList *repor
Scene *scene = (Scene *)id;
Sequence *seq;
struct SeqEffectHandle sh;
+ int num_inputs = BKE_sequence_effect_get_num_inputs(type);
- switch (BKE_sequence_effect_get_num_inputs(type)) {
+ switch (num_inputs) {
case 0:
if (end_frame <= start_frame) {
- BKE_report(reports, RPT_ERROR,
- "Sequences.new_effect: End frame not set");
+ BKE_report(reports, RPT_ERROR, "Sequences.new_effect: end frame not set");
return NULL;
}
break;
case 1:
if (seq1 == NULL) {
- BKE_report(reports, RPT_ERROR,
- "Sequences.new_effect: Effect takes 1 input sequence");
+ BKE_report(reports, RPT_ERROR, "Sequences.new_effect: effect takes 1 input sequence");
return NULL;
}
break;
case 2:
if (seq1 == NULL || seq2 == NULL) {
- BKE_report(reports, RPT_ERROR,
- "Sequences.new_effect: Effect takes 2 input sequences");
+ BKE_report(reports, RPT_ERROR, "Sequences.new_effect: effect takes 2 input sequences");
return NULL;
}
break;
case 3:
if (seq1 == NULL || seq2 == NULL || seq3 == NULL) {
- BKE_report(reports, RPT_ERROR,
- "Sequences.new_effect: Effect takes 3 input sequences");
+ BKE_report(reports, RPT_ERROR, "Sequences.new_effect: effect takes 3 input sequences");
return NULL;
}
break;
default:
- BKE_report(reports, RPT_ERROR,
- "Sequences.new_effect: BKE_sequence_effect_get_num_inputs() > 3 (should never happen)");
+ BKE_reportf(reports, RPT_ERROR,
+ "Sequences.new_effect: effect expects more than 3 inputs (%d, should never happen!)",
+ num_inputs);
return NULL;
}
@@ -311,12 +308,18 @@ static Sequence *rna_Sequences_new_effect(ID *id, Editing *ed, ReportList *repor
return seq;
}
-static void rna_Sequences_remove(ID *id, Editing *ed, Sequence *seq)
+static void rna_Sequences_remove(ID *id, Editing *ed, ReportList *reports, PointerRNA *seq_ptr)
{
+ Sequence *seq = seq_ptr->data;
Scene *scene = (Scene *)id;
- BLI_remlink(&ed->seqbase, seq);
+ if (BLI_remlink_safe(&ed->seqbase, seq) == FALSE) {
+ BKE_reportf(reports, RPT_ERROR, "Sequence '%s' not in scene '%s'", seq->name + 2, scene->id.name + 2);
+ return;
+ }
+
BKE_sequence_free(scene, seq);
+ RNA_POINTER_INVALIDATE(seq_ptr);
WM_main_add_notifier(NC_SCENE | ND_SEQUENCER, scene);
}
@@ -344,7 +347,7 @@ static void rna_SequenceElements_pop(ID *id, Sequence *seq, ReportList *reports,
StripElem *new_seq, *se;
if (seq->len == 1) {
- BKE_report(reports, RPT_ERROR, "SequenceElements.pop: can not pop the last element");
+ BKE_report(reports, RPT_ERROR, "SequenceElements.pop: cannot pop the last element");
return;
}
@@ -458,7 +461,7 @@ void RNA_api_sequences(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "new_clip", "rna_Sequences_new_clip");
RNA_def_function_flag(func, FUNC_USE_SELF_ID);
RNA_def_function_ui_description(func, "Add a new movie clip sequence");
- parm = RNA_def_string(func, "name", "Name", 0, "", "New name for the sequence");
+ parm = RNA_def_string(func, "name", "Name", 0, "", "Name for the new sequence");
RNA_def_property_flag(parm, PROP_REQUIRED);
parm = RNA_def_pointer(func, "clip", "MovieClip", "", "Movie clip to add");
RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
@@ -474,8 +477,8 @@ void RNA_api_sequences(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "new_mask", "rna_Sequences_new_mask");
RNA_def_function_flag(func, FUNC_USE_SELF_ID);
- RNA_def_function_ui_description(func, "Add a new movie clip sequence");
- parm = RNA_def_string(func, "name", "Name", 0, "", "New name for the sequence");
+ RNA_def_function_ui_description(func, "Add a new mask sequence");
+ parm = RNA_def_string(func, "name", "Name", 0, "", "Name for the new sequence");
RNA_def_property_flag(parm, PROP_REQUIRED);
parm = RNA_def_pointer(func, "mask", "Mask", "", "Mask to add");
RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
@@ -492,7 +495,7 @@ void RNA_api_sequences(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "new_scene", "rna_Sequences_new_scene");
RNA_def_function_flag(func, FUNC_USE_SELF_ID);
RNA_def_function_ui_description(func, "Add a new scene sequence");
- parm = RNA_def_string(func, "name", "Name", 0, "", "New name for the sequence");
+ parm = RNA_def_string(func, "name", "Name", 0, "", "Name for the new sequence");
RNA_def_property_flag(parm, PROP_REQUIRED);
parm = RNA_def_pointer(func, "scene", "Scene", "", "Scene to add");
RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
@@ -509,7 +512,7 @@ void RNA_api_sequences(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "new_image", "rna_Sequences_new_image");
RNA_def_function_flag(func, FUNC_USE_REPORTS | FUNC_USE_SELF_ID);
RNA_def_function_ui_description(func, "Add a new image sequence");
- parm = RNA_def_string(func, "name", "Name", 0, "", "New name for the sequence");
+ parm = RNA_def_string(func, "name", "Name", 0, "", "Name for the new sequence");
RNA_def_property_flag(parm, PROP_REQUIRED);
parm = RNA_def_string(func, "filepath", "File", 0, "", "Filepath to image");
RNA_def_property_flag(parm, PROP_REQUIRED);
@@ -526,7 +529,7 @@ void RNA_api_sequences(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "new_movie", "rna_Sequences_new_movie");
RNA_def_function_flag(func, FUNC_USE_REPORTS | FUNC_USE_SELF_ID);
RNA_def_function_ui_description(func, "Add a new movie sequence");
- parm = RNA_def_string(func, "name", "Name", 0, "", "New name for the sequence");
+ parm = RNA_def_string(func, "name", "Name", 0, "", "Name for the new sequence");
RNA_def_property_flag(parm, PROP_REQUIRED);
parm = RNA_def_string(func, "filepath", "File", 0, "", "Filepath to movie");
RNA_def_property_flag(parm, PROP_REQUIRED);
@@ -542,8 +545,8 @@ void RNA_api_sequences(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "new_sound", "rna_Sequences_new_sound");
RNA_def_function_flag(func, FUNC_USE_REPORTS | FUNC_USE_SELF_ID | FUNC_USE_MAIN);
- RNA_def_function_ui_description(func, "Add a new movie clip sequence");
- parm = RNA_def_string(func, "name", "Name", 0, "", "New name for the sequence");
+ RNA_def_function_ui_description(func, "Add a new sound sequence");
+ parm = RNA_def_string(func, "name", "Name", 0, "", "Name for the new sequence");
RNA_def_property_flag(parm, PROP_REQUIRED);
parm = RNA_def_string(func, "filepath", "File", 0, "", "Filepath to movie");
RNA_def_property_flag(parm, PROP_REQUIRED);
@@ -560,7 +563,7 @@ void RNA_api_sequences(BlenderRNA *brna, PropertyRNA *cprop)
func = RNA_def_function(srna, "new_effect", "rna_Sequences_new_effect");
RNA_def_function_flag(func, FUNC_USE_REPORTS | FUNC_USE_SELF_ID);
RNA_def_function_ui_description(func, "Add a new effect sequence");
- parm = RNA_def_string(func, "name", "Name", 0, "", "New name for the sequence");
+ parm = RNA_def_string(func, "name", "Name", 0, "", "Name for the new sequence");
RNA_def_property_flag(parm, PROP_REQUIRED);
parm = RNA_def_enum(func, "type", seq_effect_items, 0, "Type",
"type for the new sequence");
@@ -571,21 +574,22 @@ void RNA_api_sequences(BlenderRNA *brna, PropertyRNA *cprop)
parm = RNA_def_int(func, "start_frame", 0, -MAXFRAME, MAXFRAME, "",
"The start frame for the new sequence", -MAXFRAME, MAXFRAME);
RNA_def_property_flag(parm, PROP_REQUIRED);
- parm = RNA_def_int(func, "end_frame", 0, -MAXFRAME, MAXFRAME, "",
- "The end frame for the new sequence", -MAXFRAME, MAXFRAME);
- parm = RNA_def_pointer(func, "seq1", "Sequence", "", "Sequence 1 for effect");
- parm = RNA_def_pointer(func, "seq2", "Sequence", "", "Sequence 2 for effect");
- parm = RNA_def_pointer(func, "seq3", "Sequence", "", "Sequence 3 for effect");
+ RNA_def_int(func, "end_frame", 0, -MAXFRAME, MAXFRAME, "",
+ "The end frame for the new sequence", -MAXFRAME, MAXFRAME);
+ RNA_def_pointer(func, "seq1", "Sequence", "", "Sequence 1 for effect");
+ RNA_def_pointer(func, "seq2", "Sequence", "", "Sequence 2 for effect");
+ RNA_def_pointer(func, "seq3", "Sequence", "", "Sequence 3 for effect");
/* return type */
parm = RNA_def_pointer(func, "sequence", "Sequence", "", "New Sequence");
RNA_def_function_return(func, parm);
func = RNA_def_function(srna, "remove", "rna_Sequences_remove");
- RNA_def_function_flag(func, FUNC_USE_SELF_ID);
+ RNA_def_function_flag(func, FUNC_USE_SELF_ID | FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove a Sequence");
parm = RNA_def_pointer(func, "sequence", "Sequence", "", "Sequence to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
diff --git a/source/blender/makesrna/intern/rna_smoke.c b/source/blender/makesrna/intern/rna_smoke.c
index e8818248609..bdcda79583e 100644
--- a/source/blender/makesrna/intern/rna_smoke.c
+++ b/source/blender/makesrna/intern/rna_smoke.c
@@ -65,14 +65,20 @@ static void rna_Smoke_dependency_update(Main *bmain, Scene *scene, PointerRNA *p
DAG_scene_sort(bmain, scene);
}
+static void rna_Smoke_resetCache(Main *bmain, Scene *scene, PointerRNA *ptr)
+{
+ SmokeDomainSettings *settings = (SmokeDomainSettings *)ptr->data;
+ if (settings->smd && settings->smd->domain)
+ settings->point_cache[0]->flag |= PTCACHE_OUTDATED;
+ DAG_id_tag_update(ptr->id.data, OB_RECALC_DATA);
+}
+
static void rna_Smoke_reset(Main *bmain, Scene *scene, PointerRNA *ptr)
{
SmokeDomainSettings *settings = (SmokeDomainSettings *)ptr->data;
smokeModifier_reset(settings->smd);
-
- if (settings->smd && settings->smd->domain)
- settings->point_cache[0]->flag |= PTCACHE_OUTDATED;
+ rna_Smoke_resetCache(bmain, scene, ptr);
rna_Smoke_update(bmain, scene, ptr);
}
@@ -142,6 +148,30 @@ static void rna_SmokeModifier_density_get(PointerRNA *ptr, float *values)
memcpy(values, density, size * sizeof(float));
}
+static void rna_SmokeFlow_density_vgroup_get(PointerRNA *ptr, char *value)
+{
+ SmokeFlowSettings *flow = (SmokeFlowSettings *)ptr->data;
+ rna_object_vgroup_name_index_get(ptr, value, flow->vgroup_density);
+}
+
+static int rna_SmokeFlow_density_vgroup_length(PointerRNA *ptr)
+{
+ SmokeFlowSettings *flow = (SmokeFlowSettings *)ptr->data;
+ return rna_object_vgroup_name_index_length(ptr, flow->vgroup_density);
+}
+
+static void rna_SmokeFlow_density_vgroup_set(PointerRNA *ptr, const char *value)
+{
+ SmokeFlowSettings *flow = (SmokeFlowSettings *)ptr->data;
+ rna_object_vgroup_name_index_set(ptr, value, &flow->vgroup_density);
+}
+
+static void rna_SmokeFlow_uvlayer_set(PointerRNA *ptr, const char *value)
+{
+ SmokeFlowSettings *flow = (SmokeFlowSettings *)ptr->data;
+ rna_object_uvlayer_name_set(ptr, value, flow->uvlayer_name, sizeof(flow->uvlayer_name));
+}
+
#else
static void rna_def_smoke_domain_settings(BlenderRNA *brna)
@@ -217,7 +247,7 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
RNA_def_property_ui_range(prop, -5.0, 5.0, 0.02, 5);
RNA_def_property_ui_text(prop, "Density",
"How much density affects smoke motion (higher value results in faster rising smoke)");
- RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
prop = RNA_def_property(srna, "beta", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "beta");
@@ -225,7 +255,7 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
RNA_def_property_ui_range(prop, -5.0, 5.0, 0.02, 5);
RNA_def_property_ui_text(prop, "Heat",
"How much heat affects smoke motion (higher value results in faster rising smoke)");
- RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
prop = RNA_def_property(srna, "collision_group", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "coll_group");
@@ -253,24 +283,24 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
RNA_def_property_range(prop, 0.0, 10.0);
RNA_def_property_ui_range(prop, 0.0, 10.0, 1, 2);
RNA_def_property_ui_text(prop, "Strength", "Strength of noise");
- RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
prop = RNA_def_property(srna, "dissolve_speed", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "diss_speed");
RNA_def_property_range(prop, 1.0, 10000.0);
RNA_def_property_ui_range(prop, 1.0, 10000.0, 1, 0);
RNA_def_property_ui_text(prop, "Dissolve Speed", "Dissolve Speed");
- RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
prop = RNA_def_property(srna, "use_dissolve_smoke", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flags", MOD_SMOKE_DISSOLVE);
RNA_def_property_ui_text(prop, "Dissolve Smoke", "Enable smoke to disappear over time");
- RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
prop = RNA_def_property(srna, "use_dissolve_smoke_log", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flags", MOD_SMOKE_DISSOLVE_LOG);
RNA_def_property_ui_text(prop, "Logarithmic dissolve", "Using 1/x ");
- RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
prop = RNA_def_property(srna, "point_cache", PROP_POINTER, PROP_NONE);
RNA_def_property_flag(prop, PROP_NEVER_NULL);
@@ -297,21 +327,21 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
prop = RNA_def_property(srna, "smooth_emitter", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flags", MOD_SMOKE_HIGH_SMOOTH);
RNA_def_property_ui_text(prop, "Smooth Emitter", "Smooth emitted smoke to avoid blockiness");
- RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
prop = RNA_def_property(srna, "time_scale", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "time_scale");
RNA_def_property_range(prop, 0.2, 1.5);
RNA_def_property_ui_range(prop, 0.2, 1.5, 0.02, 5);
RNA_def_property_ui_text(prop, "Time Scale", "Adjust simulation speed");
- RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
prop = RNA_def_property(srna, "vorticity", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "vorticity");
RNA_def_property_range(prop, 0.01, 4.0);
RNA_def_property_ui_range(prop, 0.01, 4.0, 0.02, 5);
RNA_def_property_ui_text(prop, "Vorticity", "Amount of turbulence/rotation in fluid");
- RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
prop = RNA_def_property(srna, "density", PROP_FLOAT, PROP_NONE);
RNA_def_property_array(prop, 32);
@@ -321,25 +351,81 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
RNA_def_property_float_funcs(prop, "rna_SmokeModifier_density_get", NULL, NULL);
RNA_def_property_ui_text(prop, "Density", "Smoke density");
- prop = RNA_def_property(srna, "cell_size", PROP_FLOAT, PROP_NONE);
- RNA_def_property_float_sdna(prop, NULL, "dx");
+ prop = RNA_def_property(srna, "cell_size", PROP_FLOAT, PROP_XYZ); /* can change each frame when using adaptive domain */
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
- RNA_def_property_ui_text(prop, "dx", "Cell Size");
+ RNA_def_property_ui_text(prop, "cell_size", "Cell Size");
- prop = RNA_def_property(srna, "start_point", PROP_FLOAT, PROP_XYZ);
+ prop = RNA_def_property(srna, "start_point", PROP_FLOAT, PROP_XYZ); /* can change each frame when using adaptive domain */
RNA_def_property_float_sdna(prop, NULL, "p0");
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_ui_text(prop, "p0", "Start point");
- prop = RNA_def_property(srna, "scale", PROP_FLOAT, PROP_NONE);
- RNA_def_property_float_sdna(prop, NULL, "scale");
- RNA_def_property_clear_flag(prop, PROP_EDITABLE);
- RNA_def_property_ui_text(prop, "scale", "Domain scale factor");
-
- prop = RNA_def_property(srna, "domain_resolution", PROP_INT, PROP_XYZ);
+ prop = RNA_def_property(srna, "domain_resolution", PROP_INT, PROP_XYZ); /* can change each frame when using adaptive domain */
RNA_def_property_int_sdna(prop, NULL, "res");
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_ui_text(prop, "res", "Smoke Grid Resolution");
+
+ prop = RNA_def_property(srna, "burning_rate", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 0.01, 4.0);
+ RNA_def_property_ui_range(prop, 0.01, 2.0, 1.0, 5);
+ RNA_def_property_ui_text(prop, "Speed", "Speed of the burning reaction (use larger values for smaller flame)");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
+
+ prop = RNA_def_property(srna, "flame_smoke", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 0.0, 8.0);
+ RNA_def_property_ui_range(prop, 0.0, 4.0, 1.0, 5);
+ RNA_def_property_ui_text(prop, "Smoke", "Amount of smoke created by burning fuel");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
+
+ prop = RNA_def_property(srna, "flame_vorticity", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 0.0, 2.0);
+ RNA_def_property_ui_range(prop, 0.0, 1.0, 1.0, 5);
+ RNA_def_property_ui_text(prop, "Vorticity", "Additional vorticity for the flames");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
+
+ prop = RNA_def_property(srna, "flame_ignition", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 0.5, 5.0);
+ RNA_def_property_ui_range(prop, 0.5, 2.5, 1.0, 5);
+ RNA_def_property_ui_text(prop, "Ignition", "Minimum temperature of flames");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
+
+ prop = RNA_def_property(srna, "flame_max_temp", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 1.0, 10.0);
+ RNA_def_property_ui_range(prop, 1.0, 5.0, 1.0, 5);
+ RNA_def_property_ui_text(prop, "Maximum", "Maximum temperature of flames");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
+
+ prop = RNA_def_property(srna, "flame_smoke_color", PROP_FLOAT, PROP_COLOR_GAMMA);
+ RNA_def_property_array(prop, 3);
+ RNA_def_property_ui_text(prop, "Smoke Color", "Color of smoke emitted from burning fuel");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
+
+ prop = RNA_def_property(srna, "use_adaptive_domain", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flags", MOD_SMOKE_ADAPTIVE_DOMAIN);
+ RNA_def_property_ui_text(prop, "Adaptive Domain", "Adapt simulation resolution and size to fluid");
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "additional_res", PROP_INT, PROP_NONE);
+ RNA_def_property_int_sdna(prop, NULL, "adapt_res");
+ RNA_def_property_range(prop, 0, 512);
+ RNA_def_property_ui_range(prop, 0, 512, 2, 0);
+ RNA_def_property_ui_text(prop, "Additional", "Maximum number of additional cells");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
+
+ prop = RNA_def_property(srna, "adapt_margin", PROP_INT, PROP_NONE);
+ RNA_def_property_int_sdna(prop, NULL, "adapt_margin");
+ RNA_def_property_range(prop, 2, 24);
+ RNA_def_property_ui_range(prop, 2, 24, 2, 0);
+ RNA_def_property_ui_text(prop, "Margin", "Margin added around fluid to minimize boundary interference");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
+
+ prop = RNA_def_property(srna, "adapt_threshold", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 0.01, 0.5);
+ RNA_def_property_ui_range(prop, 0.01, 0.5, 1.0, 5);
+ RNA_def_property_ui_text(prop, "Threshold",
+ "Maximum amount of fluid cell can contain before it is considered empty");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_resetCache");
}
static void rna_def_smoke_flow_settings(BlenderRNA *brna)
@@ -347,6 +433,26 @@ static void rna_def_smoke_flow_settings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
+ static EnumPropertyItem smoke_flow_types[] = {
+ {MOD_SMOKE_FLOW_TYPE_OUTFLOW, "OUTFLOW", 0, "Outflow", "Delete smoke from simulation"},
+ {MOD_SMOKE_FLOW_TYPE_SMOKE, "SMOKE", 0, "Smoke", "Add smoke"},
+ {MOD_SMOKE_FLOW_TYPE_SMOKEFIRE, "BOTH", 0, "Fire + Smoke", "Add fire and smoke"},
+ {MOD_SMOKE_FLOW_TYPE_FIRE, "FIRE", 0, "Fire", "Add fire"},
+ {0, NULL, 0, NULL, NULL}
+ };
+
+ static EnumPropertyItem smoke_flow_sources[] = {
+ {MOD_SMOKE_FLOW_SOURCE_PARTICLES, "PARTICLES", ICON_PARTICLES, "Particle System", "Emit smoke from particles"},
+ {MOD_SMOKE_FLOW_SOURCE_MESH, "MESH", ICON_META_CUBE, "Mesh", "Emit smoke from mesh surface or volume"},
+ {0, NULL, 0, NULL, NULL}
+ };
+
+ static EnumPropertyItem smoke_flow_texture_types[] = {
+ {MOD_SMOKE_FLOW_TEXTURE_MAP_AUTO, "AUTO", 0, "Generated", "Generated coordinates centered to flow object"},
+ {MOD_SMOKE_FLOW_TEXTURE_MAP_UV, "UV", 0, "UV", "Use UV layer for texture coordinates"},
+ {0, NULL, 0, NULL, NULL}
+ };
+
srna = RNA_def_struct(brna, "SmokeFlowSettings", NULL);
RNA_def_struct_ui_text(srna, "Flow Settings", "Smoke flow settings");
RNA_def_struct_sdna(srna, "SmokeFlowSettings");
@@ -354,11 +460,23 @@ static void rna_def_smoke_flow_settings(BlenderRNA *brna)
prop = RNA_def_property(srna, "density", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "density");
- RNA_def_property_range(prop, 0.001, 1);
- RNA_def_property_ui_range(prop, 0.001, 1.0, 1.0, 4);
+ RNA_def_property_range(prop, 0.0, 1);
+ RNA_def_property_ui_range(prop, 0.0, 1.0, 1.0, 4);
RNA_def_property_ui_text(prop, "Density", "");
RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+ prop = RNA_def_property(srna, "smoke_color", PROP_FLOAT, PROP_COLOR_GAMMA);
+ RNA_def_property_float_sdna(prop, NULL, "color");
+ RNA_def_property_array(prop, 3);
+ RNA_def_property_ui_text(prop, "Smoke Color", "Color of smoke");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "fuel_amount", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 0.0, 10);
+ RNA_def_property_ui_range(prop, 0.0, 5.0, 1.0, 4);
+ RNA_def_property_ui_text(prop, "Flame Rate", "");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
prop = RNA_def_property(srna, "temperature", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "temp");
RNA_def_property_range(prop, -10, 10);
@@ -373,9 +491,16 @@ static void rna_def_smoke_flow_settings(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Particle Systems", "Particle systems emitted from the object");
RNA_def_property_update(prop, 0, "rna_Smoke_reset_dependancy");
- prop = RNA_def_property(srna, "use_outflow", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "type", MOD_SMOKE_FLOW_TYPE_OUTFLOW);
- RNA_def_property_ui_text(prop, "Outflow", "Delete smoke from simulation");
+ prop = RNA_def_property(srna, "smoke_flow_type", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "type");
+ RNA_def_property_enum_items(prop, smoke_flow_types);
+ RNA_def_property_ui_text(prop, "Flow Type", "Change how flow affects the simulation");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "smoke_flow_source", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "source");
+ RNA_def_property_enum_items(prop, smoke_flow_sources);
+ RNA_def_property_ui_text(prop, "Source", "Change how smoke is emitted");
RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
prop = RNA_def_property(srna, "use_absolute", PROP_BOOLEAN, PROP_NONE);
@@ -385,14 +510,82 @@ static void rna_def_smoke_flow_settings(BlenderRNA *brna)
prop = RNA_def_property(srna, "initial_velocity", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flags", MOD_SMOKE_FLOW_INITVELOCITY);
- RNA_def_property_ui_text(prop, "Initial Velocity", "Smoke inherits its velocity from the emitter particle");
+ RNA_def_property_ui_text(prop, "Initial Velocity", "Smoke has some initial velocity when it is emitted");
RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
prop = RNA_def_property(srna, "velocity_factor", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "vel_multi");
RNA_def_property_range(prop, -2.0, 2.0);
RNA_def_property_ui_range(prop, -2.0, 2.0, 0.05, 5);
- RNA_def_property_ui_text(prop, "Multiplier", "Multiplier to adjust velocity passed to smoke");
+ RNA_def_property_ui_text(prop, "Source", "Multiplier of source velocity passed to smoke");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "velocity_normal", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "vel_normal");
+ RNA_def_property_range(prop, -2.0, 2.0);
+ RNA_def_property_ui_range(prop, -2.0, 2.0, 0.05, 5);
+ RNA_def_property_ui_text(prop, "Normal", "Amount of normal directional velocity");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "velocity_random", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "vel_random");
+ RNA_def_property_range(prop, 0.0, 2.0);
+ RNA_def_property_ui_range(prop, 0.0, 2.0, 0.05, 5);
+ RNA_def_property_ui_text(prop, "Random", "Amount of random velocity");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "volume_density", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 0.0, 1.0);
+ RNA_def_property_ui_range(prop, 0.0, 1.0, 0.05, 5);
+ RNA_def_property_ui_text(prop, "Volume", "Factor for smoke emitted from inside the mesh volume");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "surface_distance", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 0.5, 10.0);
+ RNA_def_property_ui_range(prop, 0.5, 5.0, 0.05, 5);
+ RNA_def_property_ui_text(prop, "Surface", "Maximum distance from mesh surface to emit smoke");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "density_vertex_group", PROP_STRING, PROP_NONE);
+ RNA_def_property_string_funcs(prop, "rna_SmokeFlow_density_vgroup_get",
+ "rna_SmokeFlow_density_vgroup_length",
+ "rna_SmokeFlow_density_vgroup_set");
+ RNA_def_property_ui_text(prop, "Vertex Group",
+ "Name of vertex group which determines surface emission rate");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "use_texture", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flags", MOD_SMOKE_FLOW_TEXTUREEMIT);
+ RNA_def_property_ui_text(prop, "Use Texture", "Use a texture to control emission strength");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "texture_map_type", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "texture_type");
+ RNA_def_property_enum_items(prop, smoke_flow_texture_types);
+ RNA_def_property_ui_text(prop, "Mapping", "Texture mapping type");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "uv_layer", PROP_STRING, PROP_NONE);
+ RNA_def_property_string_sdna(prop, NULL, "uvlayer_name");
+ RNA_def_property_ui_text(prop, "UV Map", "UV map name");
+ RNA_def_property_string_funcs(prop, NULL, NULL, "rna_SmokeFlow_uvlayer_set");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "noise_texture", PROP_POINTER, PROP_NONE);
+ RNA_def_property_flag(prop, PROP_EDITABLE);
+ RNA_def_property_ui_text(prop, "Texture", "Texture that controls emission strength");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "texture_size", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 0.01, 10.0);
+ RNA_def_property_ui_range(prop, 0.1, 5.0, 0.05, 5);
+ RNA_def_property_ui_text(prop, "Size", "Size of texture mapping");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
+
+ prop = RNA_def_property(srna, "texture_offset", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 0.0, 200.0);
+ RNA_def_property_ui_range(prop, 0.0, 100.0, 0.05, 5);
+ RNA_def_property_ui_text(prop, "Offset", "Z-offset of texture mapping");
RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, "rna_Smoke_reset");
}
diff --git a/source/blender/makesrna/intern/rna_space.c b/source/blender/makesrna/intern/rna_space.c
index 246f9fef98a..962a92223eb 100644
--- a/source/blender/makesrna/intern/rna_space.c
+++ b/source/blender/makesrna/intern/rna_space.c
@@ -336,6 +336,15 @@ static void rna_View3D_CursorLocation_set(PointerRNA *ptr, const float *values)
copy_v3_v3(cursor, values);
}
+static float rna_View3D_GridScaleUnit_get(PointerRNA *ptr)
+{
+ View3D *v3d = (View3D *)(ptr->data);
+ bScreen *sc = (bScreen *)ptr->id.data;
+ Scene *scene = (Scene *)sc->scene;
+
+ return ED_view3d_grid_scale(scene, v3d, NULL);
+}
+
static void rna_SpaceView3D_layer_set(PointerRNA *ptr, const int *values)
{
View3D *v3d = (View3D *)(ptr->data);
@@ -478,7 +487,7 @@ static void rna_RegionView3D_view_matrix_set(PointerRNA *ptr, const float *value
}
/* api call */
-void rna_RegionView3D_update(ID *id, RegionView3D *rv3d)
+static void rna_RegionView3D_update(ID *id, RegionView3D *rv3d)
{
bScreen *sc = (bScreen *)id;
@@ -849,7 +858,7 @@ static void rna_SpaceDopeSheetEditor_action_update(Main *UNUSED(bmain), Scene *s
adt = BKE_id_add_animdata(&obact->id); /* this only adds if non-existant */
}
else if (saction->mode == SACTCONT_SHAPEKEY) {
- Key *key = ob_get_key(obact);
+ Key *key = BKE_key_from_object(obact);
if (key)
adt = BKE_id_add_animdata(&key->id); /* this only adds if non-existant */
}
@@ -876,7 +885,7 @@ static void rna_SpaceDopeSheetEditor_mode_update(Main *UNUSED(bmain), Scene *sce
/* special exceptions for ShapeKey Editor mode */
if (saction->mode == SACTCONT_SHAPEKEY) {
- Key *key = ob_get_key(obact);
+ Key *key = BKE_key_from_object(obact);
/* 1) update the action stored for the editor */
if (key)
@@ -949,15 +958,17 @@ static BGpic *rna_BackgroundImage_new(View3D *v3d)
return bgpic;
}
-static void rna_BackgroundImage_remove(View3D *v3d, ReportList *reports, BGpic *bgpic)
+static void rna_BackgroundImage_remove(View3D *v3d, ReportList *reports, PointerRNA *bgpic_ptr)
{
+ BGpic *bgpic = bgpic_ptr->data;
if (BLI_findindex(&v3d->bgpicbase, bgpic) == -1) {
- BKE_report(reports, RPT_ERROR, "BackgroundImage can't be removed");
- }
- else {
- ED_view3D_background_image_remove(v3d, bgpic);
- WM_main_add_notifier(NC_SPACE | ND_SPACE_VIEW3D, v3d);
+ BKE_report(reports, RPT_ERROR, "Background image cannot be removed");
}
+
+ ED_view3D_background_image_remove(v3d, bgpic);
+ RNA_POINTER_INVALIDATE(bgpic_ptr);
+
+ WM_main_add_notifier(NC_SPACE | ND_SPACE_VIEW3D, v3d);
}
static void rna_BackgroundImage_clear(View3D *v3d)
@@ -1102,7 +1113,7 @@ static void rna_def_space(BlenderRNA *brna)
}
/* for all spaces that use a mask */
-void rna_def_space_mask_info(StructRNA *srna, int noteflag, const char *mask_set_func)
+static void rna_def_space_mask_info(StructRNA *srna, int noteflag, const char *mask_set_func)
{
PropertyRNA *prop;
@@ -1324,7 +1335,7 @@ static void rna_def_background_image(BlenderRNA *brna)
srna = RNA_def_struct(brna, "BackgroundImage", NULL);
RNA_def_struct_sdna(srna, "BGpic");
- RNA_def_struct_ui_text(srna, "Background Image", "Image and settings for display in the 3d View background");
+ RNA_def_struct_ui_text(srna, "Background Image", "Image and settings for display in the 3D View background");
prop = RNA_def_property(srna, "source", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "source");
@@ -1442,7 +1453,8 @@ static void rna_def_backgroundImages(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_ui_description(func, "Remove background image");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "image", "BackgroundImage", "", "Image displayed as viewport background");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "clear", "rna_BackgroundImage_clear");
RNA_def_function_ui_description(func, "Remove all background images");
@@ -1494,7 +1506,39 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Camera",
"Active camera used in this view (when unlocked from the scene's active camera)");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
+ /* render border */
+ prop = RNA_def_property(srna, "use_render_border", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag2", V3D_RENDER_BORDER);
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
+ RNA_def_property_ui_text(prop, "Render Border",
+ "Use a user-defined border region within the frame size for rendered viewport");
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+
+ prop = RNA_def_property(srna, "render_border_min_x", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "render_border.xmin");
+ RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_ui_text(prop, "Border Minimum X", "Minimum X value to for the render border");
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+
+ prop = RNA_def_property(srna, "render_border_min_y", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "render_border.ymin");
+ RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_ui_text(prop, "Border Minimum Y", "Minimum Y value for the render border");
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+
+ prop = RNA_def_property(srna, "render_border_max_x", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "render_border.xmax");
+ RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_ui_text(prop, "Border Maximum X", "Maximum X value for the render border");
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+
+ prop = RNA_def_property(srna, "render_border_max_y", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "render_border.ymax");
+ RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_ui_text(prop, "Border Maximum Y", "Maximum Y value for the render border");
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+
prop = RNA_def_property(srna, "lock_object", PROP_POINTER, PROP_NONE);
RNA_def_property_flag(prop, PROP_EDITABLE);
RNA_def_property_pointer_sdna(prop, NULL, "ob_centre");
@@ -1533,7 +1577,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
prop = RNA_def_property(srna, "lens", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "lens");
- RNA_def_property_ui_text(prop, "Lens", "Lens angle (mm) in perspective view");
+ RNA_def_property_ui_text(prop, "Lens", "Viewport lens angle (mm)");
RNA_def_property_range(prop, 1.0f, 250.0f);
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
@@ -1571,7 +1615,12 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_range(prop, 1, 1024);
RNA_def_property_int_default(prop, 10);
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
+ prop = RNA_def_property(srna, "grid_scale_unit", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ RNA_def_property_float_funcs(prop, "rna_View3D_GridScaleUnit_get", NULL, NULL);
+ RNA_def_property_ui_text(prop, "Grid Scale Unit", "Grid cell size scaled by scene unit system settings");
+
prop = RNA_def_property(srna, "show_floor", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "gridflag", V3D_SHOW_FLOOR);
RNA_def_property_ui_text(prop, "Display Grid Floor", "Show the ground plane grid in perspective view");
@@ -2780,6 +2829,12 @@ static void rna_def_fileselect_params(BlenderRNA *brna)
RNA_def_property_ui_icon(prop, ICON_FILE_BLEND, 0);
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_FILE_PARAMS, NULL);
+ prop = RNA_def_property(srna, "use_filter_backup", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "filter", BLENDERFILE_BACKUP);
+ RNA_def_property_ui_text(prop, "Filter BlenderBackup files", "Show .blend1, .blend2, etc. files");
+ RNA_def_property_ui_icon(prop, ICON_FILE_BACKUP, 0);
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_FILE_PARAMS, NULL);
+
prop = RNA_def_property(srna, "use_filter_movie", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "filter", MOVIEFILE);
RNA_def_property_ui_text(prop, "Filter Movies", "Show movie files");
diff --git a/source/blender/makesrna/intern/rna_speaker.c b/source/blender/makesrna/intern/rna_speaker.c
index 1e3c8df9273..a160aaf94e2 100644
--- a/source/blender/makesrna/intern/rna_speaker.c
+++ b/source/blender/makesrna/intern/rna_speaker.c
@@ -35,6 +35,8 @@
#include "DNA_speaker_types.h"
#include "DNA_sound_types.h"
+#include "BLF_translation.h"
+
#ifdef RNA_RUNTIME
#include "MEM_guardedalloc.h"
@@ -45,7 +47,6 @@
#include "WM_api.h"
#include "WM_types.h"
-
#else
static void rna_def_speaker(BlenderRNA *brna)
@@ -151,6 +152,7 @@ static void rna_def_speaker(BlenderRNA *brna)
RNA_def_property_float_sdna(prop, NULL, "volume");
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_ui_text(prop, "Volume", "How loud the sound is");
+ RNA_def_property_translation_context(prop, BLF_I18NCONTEXT_AUDIO);
/* RNA_def_property_float_funcs(prop, NULL, "rna_Speaker_volume_set", NULL); */
/* RNA_def_property_update(prop, 0, "rna_Speaker_update"); */
@@ -158,6 +160,7 @@ static void rna_def_speaker(BlenderRNA *brna)
RNA_def_property_float_sdna(prop, NULL, "pitch");
RNA_def_property_range(prop, 0.1f, 10.0f);
RNA_def_property_ui_text(prop, "Pitch", "Playback pitch of the sound");
+ RNA_def_property_translation_context(prop, BLF_I18NCONTEXT_AUDIO);
/* RNA_def_property_float_funcs(prop, NULL, "rna_Speaker_pitch_set", NULL); */
/* RNA_def_property_update(prop, 0, "rna_Speaker_update"); */
diff --git a/source/blender/makesrna/intern/rna_text_api.c b/source/blender/makesrna/intern/rna_text_api.c
index 0366012e260..5f67f367195 100644
--- a/source/blender/makesrna/intern/rna_text_api.c
+++ b/source/blender/makesrna/intern/rna_text_api.c
@@ -30,6 +30,8 @@
#include "RNA_define.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include "WM_api.h"
diff --git a/source/blender/makesrna/intern/rna_texture.c b/source/blender/makesrna/intern/rna_texture.c
index 483e3ab7f8a..e77c5d13a6b 100644
--- a/source/blender/makesrna/intern/rna_texture.c
+++ b/source/blender/makesrna/intern/rna_texture.c
@@ -71,7 +71,7 @@ EnumPropertyItem texture_type_items[] = {
{TEX_POINTDENSITY, "POINT_DENSITY", ICON_TEXTURE, "Point Density", ""},
{TEX_STUCCI, "STUCCI", ICON_TEXTURE, "Stucci", "Procedural - create a fractal noise texture"},
{TEX_VORONOI, "VORONOI", ICON_TEXTURE, "Voronoi", "Procedural - create cell-like patterns based on Worley noise"},
- {TEX_VOXELDATA, "VOXEL_DATA", ICON_TEXTURE, "Voxel Data", "Create a 3d texture based on volumetric data"},
+ {TEX_VOXELDATA, "VOXEL_DATA", ICON_TEXTURE, "Voxel Data", "Create a 3D texture based on volumetric data"},
{TEX_WOOD, "WOOD", ICON_TEXTURE, "Wood", "Procedural - wave generated bands or rings, with optional noise"},
{TEX_OCEAN, "OCEAN", ICON_TEXTURE, "Ocean", "Use a texture generated by an Ocean modifier"},
{0, NULL, 0, NULL, NULL}
@@ -1733,6 +1733,7 @@ static void rna_def_texture_pointdensity(BlenderRNA *brna)
prop = RNA_def_property(srna, "turbulence_strength", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "noise_fac");
RNA_def_property_range(prop, 0.01, FLT_MAX);
+ RNA_def_property_ui_text(prop, "Turbulence Strength", "Strength of the added turbulent noise");
RNA_def_property_update(prop, 0, "rna_Texture_update");
prop = RNA_def_property(srna, "turbulence_depth", PROP_INT, PROP_NONE);
@@ -1799,7 +1800,8 @@ static void rna_def_texture_voxeldata(BlenderRNA *brna)
};
static EnumPropertyItem smoked_type_items[] = {
- {TEX_VD_SMOKEDENSITY, "SMOKEDENSITY", 0, "Density", "Use smoke density as texture data"},
+ {TEX_VD_SMOKEDENSITY, "SMOKEDENSITY", 0, "Smoke", "Use smoke density and color as texture data"},
+ {TEX_VD_SMOKEFLAME, "SMOKEFLAME", 0, "Flame", "Use flame temperature as texture data"},
{TEX_VD_SMOKEHEAT, "SMOKEHEAT", 0, "Heat", "Use smoke heat as texture data. Values from -2.0 to 2.0 are used"},
{TEX_VD_SMOKEVEL, "SMOKEVEL", 0, "Velocity", "Use smoke velocity as texture data"},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/makesrna/intern/rna_texture_api.c b/source/blender/makesrna/intern/rna_texture_api.c
index e62b3ecd804..5be9d3a0dec 100644
--- a/source/blender/makesrna/intern/rna_texture_api.c
+++ b/source/blender/makesrna/intern/rna_texture_api.c
@@ -32,6 +32,8 @@
#include "RNA_define.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include "IMB_imbuf.h"
@@ -42,8 +44,8 @@
#include "RE_pipeline.h"
#include "RE_shader_ext.h"
-void save_envmap(struct EnvMap *env, bContext *C, ReportList *reports, const char *filepath,
- struct Scene *scene, float layout[12])
+static void save_envmap(struct EnvMap *env, bContext *C, ReportList *reports, const char *filepath,
+ struct Scene *scene, float layout[12])
{
if (scene == NULL) {
scene = CTX_data_scene(C);
@@ -52,7 +54,7 @@ void save_envmap(struct EnvMap *env, bContext *C, ReportList *reports, const cha
RE_WriteEnvmapResult(reports, scene, env, filepath, scene->r.im_format.imtype, layout);
}
-void clear_envmap(struct EnvMap *env, bContext *C)
+static void clear_envmap(struct EnvMap *env, bContext *C)
{
Main *bmain = CTX_data_main(C);
Tex *tex;
@@ -66,7 +68,7 @@ void clear_envmap(struct EnvMap *env, bContext *C)
}
}
-void texture_evaluate(struct Tex *tex, float value[3], float color_r[4])
+static void texture_evaluate(struct Tex *tex, float value[3], float color_r[4])
{
TexResult texres = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0, NULL};
multitex_ext(tex, value, NULL, NULL, 1, &texres);
@@ -118,10 +120,10 @@ void RNA_api_environment_map(StructRNA *srna)
RNA_def_pointer(func, "scene", "Scene", "", "Overrides the scene from which image parameters are taken");
- RNA_def_float_array(func, "layout", 12, default_layout, 0.0f, 0.0f, "File layout",
+ RNA_def_float_array(func, "layout", 12, default_layout, 0.0f, 1000.0f, "File layout",
"Flat array describing the X,Y position of each cube face in the "
"output image, where 1 is the size of a face - order is [+Z -Z +Y -X -Y +X] "
- "(use -1 to skip a face)", 0.0f, 0.0f);
+ "(use -1 to skip a face)", 0.0f, 1000.0f);
}
#endif
diff --git a/source/blender/makesrna/intern/rna_tracking.c b/source/blender/makesrna/intern/rna_tracking.c
index 172a79970b5..51b50f78e66 100644
--- a/source/blender/makesrna/intern/rna_tracking.c
+++ b/source/blender/makesrna/intern/rna_tracking.c
@@ -35,6 +35,7 @@
#include "BKE_movieclip.h"
#include "BKE_tracking.h"
+#include "RNA_access.h"
#include "RNA_define.h"
#include "rna_internal.h"
@@ -144,7 +145,7 @@ static void rna_tracking_active_track_set(PointerRNA *ptr, PointerRNA value)
clip->tracking.act_track = NULL;
}
-void rna_trackingTrack_name_set(PointerRNA *ptr, const char *value)
+static void rna_trackingTrack_name_set(PointerRNA *ptr, const char *value)
{
MovieClip *clip = (MovieClip *)ptr->id.data;
MovieTracking *tracking = &clip->tracking;
@@ -325,7 +326,7 @@ static void rna_tracking_active_object_set(PointerRNA *ptr, PointerRNA value)
else clip->tracking.objectnr = 0;
}
-void rna_trackingObject_name_set(PointerRNA *ptr, const char *value)
+static void rna_trackingObject_name_set(PointerRNA *ptr, const char *value)
{
MovieClip *clip = (MovieClip *)ptr->id.data;
MovieTrackingObject *object = (MovieTrackingObject *)ptr->data;
@@ -447,9 +448,15 @@ static MovieTrackingObject *rna_trackingObject_new(MovieTracking *tracking, cons
return object;
}
-void rna_trackingObject_remove(MovieTracking *tracking, MovieTrackingObject *object)
+static void rna_trackingObject_remove(MovieTracking *tracking, ReportList *reports, PointerRNA *object_ptr)
{
- BKE_tracking_object_delete(tracking, object);
+ MovieTrackingObject *object = object_ptr->data;
+ if (BKE_tracking_object_delete(tracking, object) == FALSE) {
+ BKE_reportf(reports, RPT_ERROR, "MovieTracking '%s' can't be removed", object->name);
+ return;
+ }
+
+ RNA_POINTER_INVALIDATE(object_ptr);
WM_main_add_notifier(NC_MOVIECLIP | NA_EDITED, NULL);
}
@@ -477,7 +484,7 @@ static MovieTrackingMarker *rna_trackingMarkers_insert_frame(MovieTrackingTrack
return new_marker;
}
-void rna_trackingMarkers_delete_frame(MovieTrackingTrack *track, int framenr)
+static void rna_trackingMarkers_delete_frame(MovieTrackingTrack *track, int framenr)
{
if (track->markersnr == 1)
return;
@@ -567,17 +574,18 @@ static void rna_def_trackingSettings(BlenderRNA *brna)
"Limit speed of tracking to make visual feedback easier "
"(this does not affect the tracking quality)");
- /* keyframe_a */
- prop = RNA_def_property(srna, "keyframe_a", PROP_INT, PROP_NONE);
+ /* reconstruction success_threshold */
+ prop = RNA_def_property(srna, "reconstruction_success_threshold", PROP_FLOAT, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
- RNA_def_property_int_sdna(prop, NULL, "keyframe1");
- RNA_def_property_ui_text(prop, "Keyframe A", "First keyframe used for reconstruction initialization");
+ RNA_def_property_float_default(prop, 0.001f);
+ RNA_def_property_range(prop, 0, FLT_MAX);
+ RNA_def_property_ui_text(prop, "Success Threshold", "Threshold value of reconstruction error which is still considered successful");
- /* keyframe_b */
- prop = RNA_def_property(srna, "keyframe_b", PROP_INT, PROP_NONE);
+ /* use fallback reconstruction */
+ prop = RNA_def_property(srna, "use_fallback_reconstruction", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
- RNA_def_property_int_sdna(prop, NULL, "keyframe2");
- RNA_def_property_ui_text(prop, "Keyframe B", "Second keyframe used for reconstruction initialization");
+ RNA_def_property_boolean_sdna(prop, NULL, "reconstruction_flag", TRACKING_USE_FALLBACK_RECONSTRUCTION);
+ RNA_def_property_ui_text(prop, "Use Fallback", "Use fallback reconstruction algorithm in cases main reconstruction algorithm failed. Could give better solution with bad tracks");
/* intrinsics refinement during bundle adjustment */
prop = RNA_def_property(srna, "refine_intrinsics", PROP_ENUM, PROP_NONE);
@@ -909,8 +917,8 @@ static void rna_def_trackingMarkers(BlenderRNA *brna, PropertyRNA *cprop)
parm = RNA_def_int(func, "frame", 1, MINFRAME, MAXFRAME, "Frame",
"Frame number to find marker for", MINFRAME, MAXFRAME);
RNA_def_property_flag(parm, PROP_REQUIRED);
- parm = RNA_def_boolean(func, "exact", TRUE, "Exact",
- "Get marker at exact frame number rather than get estimated marker");
+ RNA_def_boolean(func, "exact", TRUE, "Exact",
+ "Get marker at exact frame number rather than get estimated marker");
parm = RNA_def_pointer(func, "marker", "MovieTrackingMarker", "", "Marker for specified frame");
RNA_def_function_return(func, parm);
@@ -1393,6 +1401,18 @@ static void rna_def_trackingObject(BlenderRNA *brna)
RNA_def_property_float_default(prop, 1.0f);
RNA_def_property_ui_text(prop, "Scale", "Scale of object solution in camera space");
RNA_def_property_update(prop, NC_MOVIECLIP | NA_EDITED, "rna_trackingObject_flushUpdate");
+
+ /* keyframe_a */
+ prop = RNA_def_property(srna, "keyframe_a", PROP_INT, PROP_NONE);
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
+ RNA_def_property_int_sdna(prop, NULL, "keyframe1");
+ RNA_def_property_ui_text(prop, "Keyframe A", "First keyframe used for reconstruction initialization");
+
+ /* keyframe_b */
+ prop = RNA_def_property(srna, "keyframe_b", PROP_INT, PROP_NONE);
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
+ RNA_def_property_int_sdna(prop, NULL, "keyframe2");
+ RNA_def_property_ui_text(prop, "Keyframe B", "Second keyframe used for reconstruction initialization");
}
static void rna_def_trackingObjects(BlenderRNA *brna, PropertyRNA *cprop)
@@ -1416,8 +1436,11 @@ static void rna_def_trackingObjects(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_return(func, parm);
func = RNA_def_function(srna, "remove", "rna_trackingObject_remove");
+ RNA_def_function_flag(func, FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove tracking object from this movie clip");
- RNA_def_pointer(func, "object", "MovieTrackingObject", "", "Motion tracking object to be removed");
+ parm = RNA_def_pointer(func, "object", "MovieTrackingObject", "", "Motion tracking object to be removed");
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
/* active object */
prop = RNA_def_property(srna, "active", PROP_POINTER, PROP_NONE);
diff --git a/source/blender/makesrna/intern/rna_ui.c b/source/blender/makesrna/intern/rna_ui.c
index 70d94bfc7ed..a0a9f6183af 100644
--- a/source/blender/makesrna/intern/rna_ui.c
+++ b/source/blender/makesrna/intern/rna_ui.c
@@ -85,7 +85,7 @@ static ARegionType *region_type_find(ReportList *reports, int space_type, int re
/* region type not found? abort */
if (art == NULL) {
- BKE_report(reports, RPT_ERROR, "Region not found in spacetype");
+ BKE_report(reports, RPT_ERROR, "Region not found in space type");
return NULL;
}
@@ -192,7 +192,7 @@ static StructRNA *rna_Panel_register(Main *bmain, ReportList *reports, void *dat
return NULL;
if (strlen(identifier) >= sizeof(dummypt.idname)) {
- BKE_reportf(reports, RPT_ERROR, "registering panel class: '%s' is too long, maximum length is %d",
+ BKE_reportf(reports, RPT_ERROR, "Registering panel class: '%s' is too long, maximum length is %d",
identifier, (int)sizeof(dummypt.idname));
return NULL;
}
@@ -309,7 +309,7 @@ static StructRNA *rna_Header_register(Main *bmain, ReportList *reports, void *da
return NULL;
if (strlen(identifier) >= sizeof(dummyht.idname)) {
- BKE_reportf(reports, RPT_ERROR, "registering header class: '%s' is too long, maximum length is %d",
+ BKE_reportf(reports, RPT_ERROR, "Registering header class: '%s' is too long, maximum length is %d",
identifier, (int)sizeof(dummyht.idname));
return NULL;
}
@@ -438,7 +438,7 @@ static StructRNA *rna_Menu_register(Main *bmain, ReportList *reports, void *data
return NULL;
if (strlen(identifier) >= sizeof(dummymt.idname)) {
- BKE_reportf(reports, RPT_ERROR, "registering menu class: '%s' is too long, maximum length is %d",
+ BKE_reportf(reports, RPT_ERROR, "Registering menu class: '%s' is too long, maximum length is %d",
identifier, (int)sizeof(dummymt.idname));
return NULL;
}
diff --git a/source/blender/makesrna/intern/rna_ui_api.c b/source/blender/makesrna/intern/rna_ui_api.c
index ea38b60b25f..2a8f1b90d4e 100644
--- a/source/blender/makesrna/intern/rna_ui_api.c
+++ b/source/blender/makesrna/intern/rna_ui_api.c
@@ -36,6 +36,8 @@
#include "UI_resources.h"
+#include "rna_internal.h"
+
#ifdef RNA_RUNTIME
static void rna_uiItemR(uiLayout *layout, PointerRNA *ptr, const char *propname, const char *name, int icon,
@@ -234,41 +236,41 @@ void RNA_api_ui_layout(StructRNA *srna)
/* useful in C but not in python */
#if 0
- func= RNA_def_function(srna, "operator_enum_single", "uiItemEnumO_string");
+ func = RNA_def_function(srna, "operator_enum_single", "uiItemEnumO_string");
api_ui_item_op_common(func);
- parm= RNA_def_string(func, "property", "", 0, "", "Identifier of property in operator");
+ parm = RNA_def_string(func, "property", "", 0, "", "Identifier of property in operator");
RNA_def_property_flag(parm, PROP_REQUIRED);
- parm= RNA_def_string(func, "value", "", 0, "", "Enum property value");
+ parm = RNA_def_string(func, "value", "", 0, "", "Enum property value");
RNA_def_property_flag(parm, PROP_REQUIRED);
- func= RNA_def_function(srna, "operator_boolean", "uiItemBooleanO");
+ func = RNA_def_function(srna, "operator_boolean", "uiItemBooleanO");
api_ui_item_op_common(func);
- parm= RNA_def_string(func, "property", "", 0, "", "Identifier of property in operator");
+ parm = RNA_def_string(func, "property", "", 0, "", "Identifier of property in operator");
RNA_def_property_flag(parm, PROP_REQUIRED);
- parm= RNA_def_boolean(func, "value", 0, "", "Value of the property to call the operator with");
+ parm = RNA_def_boolean(func, "value", 0, "", "Value of the property to call the operator with");
RNA_def_property_flag(parm, PROP_REQUIRED); */
- func= RNA_def_function(srna, "operator_int", "uiItemIntO");
+ func = RNA_def_function(srna, "operator_int", "uiItemIntO");
api_ui_item_op_common(func);
- parm= RNA_def_string(func, "property", "", 0, "", "Identifier of property in operator");
+ parm = RNA_def_string(func, "property", "", 0, "", "Identifier of property in operator");
RNA_def_property_flag(parm, PROP_REQUIRED);
- parm= RNA_def_int(func, "value", 0, INT_MIN, INT_MAX, "",
+ parm = RNA_def_int(func, "value", 0, INT_MIN, INT_MAX, "",
"Value of the property to call the operator with", INT_MIN, INT_MAX);
RNA_def_property_flag(parm, PROP_REQUIRED); */
- func= RNA_def_function(srna, "operator_float", "uiItemFloatO");
+ func = RNA_def_function(srna, "operator_float", "uiItemFloatO");
api_ui_item_op_common(func);
- parm= RNA_def_string(func, "property", "", 0, "", "Identifier of property in operator");
+ parm = RNA_def_string(func, "property", "", 0, "", "Identifier of property in operator");
RNA_def_property_flag(parm, PROP_REQUIRED);
- parm= RNA_def_float(func, "value", 0, -FLT_MAX, FLT_MAX, "",
+ parm = RNA_def_float(func, "value", 0, -FLT_MAX, FLT_MAX, "",
"Value of the property to call the operator with", -FLT_MAX, FLT_MAX);
RNA_def_property_flag(parm, PROP_REQUIRED); */
- func= RNA_def_function(srna, "operator_string", "uiItemStringO");
+ func = RNA_def_function(srna, "operator_string", "uiItemStringO");
api_ui_item_op_common(func);
- parm= RNA_def_string(func, "property", "", 0, "", "Identifier of property in operator");
+ parm = RNA_def_string(func, "property", "", 0, "", "Identifier of property in operator");
RNA_def_property_flag(parm, PROP_REQUIRED);
- parm= RNA_def_string(func, "value", "", 0, "", "Value of the property to call the operator with");
+ parm = RNA_def_string(func, "value", "", 0, "", "Value of the property to call the operator with");
RNA_def_property_flag(parm, PROP_REQUIRED);
#endif
@@ -437,7 +439,8 @@ void RNA_api_ui_layout(StructRNA *srna)
RNA_def_boolean(func, "compact", 0, "", "Use more compact layout");
func = RNA_def_function(srna, "template_list", "uiTemplateList");
- RNA_def_function_ui_description(func, "Item. A list widget to display data. e.g. vertexgroups");
+ RNA_def_function_ui_description(func, "Item. A list widget to display data, e.g. vertexgroups "
+ "(WARNING: only one per panel allowed!).");
RNA_def_function_flag(func, FUNC_USE_CONTEXT);
parm = RNA_def_pointer(func, "data", "AnyType", "", "Data from which to take property");
RNA_def_property_flag(parm, PROP_REQUIRED | PROP_RNAPTR);
diff --git a/source/blender/makesrna/intern/rna_userdef.c b/source/blender/makesrna/intern/rna_userdef.c
index 666fa4d7b81..415d5308d85 100644
--- a/source/blender/makesrna/intern/rna_userdef.c
+++ b/source/blender/makesrna/intern/rna_userdef.c
@@ -24,9 +24,9 @@
* \ingroup RNA
*/
-
#include <stdlib.h>
+#include "RNA_access.h"
#include "RNA_define.h"
#include "RNA_enum_types.h"
@@ -265,7 +265,7 @@ static void rna_UserDef_audio_update(Main *bmain, Scene *UNUSED(scene), PointerR
static void rna_Userdef_memcache_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr))
{
- MEM_CacheLimiter_set_maximum(U.memcachelimit * 1024 * 1024);
+ MEM_CacheLimiter_set_maximum(((size_t) U.memcachelimit) * 1024 * 1024);
}
static void rna_UserDef_weight_color_update(Main *bmain, Scene *scene, PointerRNA *ptr)
@@ -311,9 +311,16 @@ static bAddon *rna_userdef_addon_new(void)
return bext;
}
-static void rna_userdef_addon_remove(bAddon *bext)
+static void rna_userdef_addon_remove(ReportList *reports, PointerRNA *bext_ptr)
{
+ bAddon *bext = bext_ptr->data;
+ if (BLI_findindex(&U.addons, bext) == -1) {
+ BKE_report(reports, RPT_ERROR, "Addon is no longer valid");
+ return;
+ }
+
BLI_freelinkN(&U.addons, bext);
+ RNA_POINTER_INVALIDATE(bext_ptr);
}
static void rna_userdef_temp_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr))
@@ -410,6 +417,15 @@ static EnumPropertyItem *rna_userdef_compute_device_itemf(bContext *UNUSED(C), P
}
#endif
+#ifdef WITH_INTERNATIONAL
+static EnumPropertyItem *rna_lang_enum_properties_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
+ PropertyRNA *UNUSED(prop), int *free)
+{
+ *free = 0; /* These items are handled by BLF code! */
+ return BLF_RNA_lang_enum_properties();
+}
+#endif
+
#else
static void rna_def_userdef_theme_ui_font_style(BlenderRNA *brna)
@@ -481,7 +497,7 @@ static void rna_def_userdef_theme_ui_style(BlenderRNA *brna)
/* (not used yet) */
#if 0
- prop= RNA_def_property(srna, "panelzoom", PROP_FLOAT, PROP_NONE);
+ prop = RNA_def_property(srna, "panelzoom", PROP_FLOAT, PROP_NONE);
RNA_def_property_range(prop, 0.5, 2.0);
RNA_def_property_ui_text(prop, "Panel Zoom", "Default zoom level for panel areas");
#endif
@@ -2510,7 +2526,7 @@ static void rna_def_userdef_view(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Sub Level Menu Open Delay",
"Time delay in 1/10 seconds before automatically opening sub level menus");
- prop = RNA_def_property(srna, "quit_dialog", PROP_BOOLEAN, PROP_NONE);
+ prop = RNA_def_property(srna, "use_quit_dialog", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_QUIT_PROMPT);
RNA_def_property_ui_text(prop, "Prompt Quit",
"Asks for confirmation when quitting through the window close button");
@@ -2745,6 +2761,11 @@ static void rna_def_userdef_edit(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "autokey_flag", AUTOKEY_FLAG_INSERTAVAIL);
RNA_def_property_ui_text(prop, "Auto Keyframe Insert Available",
"Automatic keyframe insertion in available F-Curves");
+
+ prop = RNA_def_property(srna, "use_auto_keying_warning", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_negative_sdna(prop, NULL, "autokey_flag", AUTOKEY_FLAG_NOWARNING);
+ RNA_def_property_ui_text(prop, "Show Auto Keying Warning",
+ "Show warning indicators when transforming objects and bones if auto keying is enabled");
/* keyframing settings */
prop = RNA_def_property(srna, "use_keyframe_insert_needed", PROP_BOOLEAN, PROP_NONE);
@@ -2778,7 +2799,7 @@ static void rna_def_userdef_edit(BlenderRNA *brna)
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", USER_NONEGFRAMES);
RNA_def_property_ui_text(prop, "Allow Negative Frames",
"Current frame number can be manually set to a negative value");
-
+
/* fcurve opacity */
prop = RNA_def_property(srna, "fcurve_unselected_alpha", PROP_FLOAT, PROP_FACTOR);
RNA_def_property_float_sdna(prop, NULL, "fcu_inactive_alpha");
@@ -2978,14 +2999,16 @@ static void rna_def_userdef_system(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
+#if 0
/* hardcoded here, could become dynamic somehow */
/* locale according to http://www.roseindia.net/tutorials/I18N/locales-list.shtml */
/* if you edit here, please also edit the source/blender/blenfont/intern/blf_lang.c 's locales */
/* Note: As this list is in alphabetical order, and not defined order,
- * here is the highest define currently in use: 33 (Hebrew). */
+ * here is the highest define currently in use: 35 (Esperanto). */
static EnumPropertyItem language_items[] = {
- { 0, "", 0, N_("Nearly done"), ""},
+ { 0, "", 0, N_("Nearly Done"), ""},
{ 0, "DEFAULT", 0, "Default (Default)", ""},
+ /* using the utf8 flipped form of Arabic (العربية) */
{21, "ARABIC", 0, "Arabic (ﺔﻴﺑﺮﻌﻟﺍ)", "ar_EG"},
{32, "BRAZILIANPORTUGUESE", 0, "Brazilian Portuguese (Português do Brasil)", "pt_BR"},
{ 1, "ENGLISH", 0, "English (English)", "en_US"},
@@ -2998,32 +3021,40 @@ static void rna_def_userdef_system(BlenderRNA *brna)
{ 9, "SPANISH", 0, "Spanish (Español)", "es"},
{14, "TRADITIONAL_CHINESE", 0, "Traditional Chinese (繁體中文)", "zh_TW"},
{18, "UKRAINIAN", 0, "Ukrainian (Український)", "uk_UA"},
- { 0, "", 0, N_("In progress"), ""},
- /* using the utf8 flipped form of Arabic (العربية) */
- {22, "BULGARIAN", 0, "Bulgarian (Български)", "bg_BG"},
- {10, "CATALAN", 0, "Catalan (Català)", "ca_AD"},
+ { 0, "", 0, N_("In Progress"), ""},
+/* {22, "BULGARIAN", 0, "Bulgarian (Български)", "bg_BG"},*/ /* XXX Not active nor enough translated. */
+/* {10, "CATALAN", 0, "Catalan (Català)", "ca_AD"},*/ /* XXX Not active nor enough translated. */
{16, "CROATIAN", 0, "Croatian (Hrvatski)", "hr_HR"},
{11, "CZECH", 0, "Czech (Český)", "cs_CZ"},
{ 3, "DUTCH", 0, "Dutch (Nederlandse taal)", "nl_NL"},
- { 6, "FINNISH", 0, "Finnish (Suomi)", "fi_FI"},
+ {35, "ESPERANTO", 0, "Esperanto (Esperanto)", "eo"},
+ {34, "ESTONIAN", 0, "Estonian (Eestlane)", "et_EE"},
+/* { 6, "FINNISH", 0, "Finnish (Suomi)", "fi_FI"},*/ /* XXX Not active nor enough translated. */
{ 5, "GERMAN", 0, "German (Deutsch)", "de_DE"},
- {23, "GREEK", 0, "Greek (Ελληνικά)", "el_GR"},
- {33, "HEBREW", 0, "Hebrew (עִבְרִית)", "he_IL"},
- {31, "HUNGARIAN", 0, "Hungarian (magyar)", "hu_HU"},
+/* {23, "GREEK", 0, "Greek (Ελληνικά)", "el_GR"},*/ /* XXX Not active nor enough translated. */
+ /* using the utf8 flipped form of Hebrew (עִבְרִית)) */
+ {33, "HEBREW", 0, "Hebrew (תירִבְעִ)", "he_IL"},
+ {31, "HUNGARIAN", 0, "Hungarian (Magyar)", "hu_HU"},
{27, "INDONESIAN", 0, "Indonesian (Bahasa indonesia)", "id_ID"},
{29, "KYRGYZ", 0, "Kyrgyz (Кыргыз тили)", "ky_KG"},
-/* {24, "KOREAN", 0, "Korean (한국 언어)", "ko_KR"}, */ /* XXX No po's yet. */
- {25, "NEPALI", 0, "Nepali (नेपाली)", "ne_NP"},
+/* {24, "KOREAN", 0, "Korean (한국 언어)", "ko_KR"}, */ /* XXX Not active nor enough translated. */
+/* {25, "NEPALI", 0, "Nepali (नेपाली)", "ne_NP"},*/ /* XXX Not active nor enough translated. */
/* using the utf8 flipped form of Persian (فارسی) */
{26, "PERSIAN", 0, "Persian (ﯽﺳﺭﺎﻓ)", "fa_IR"},
- {19, "POLISH", 0, "Polish (Polski)", "pl_PL"},
-/* {20, "ROMANIAN", 0, "Romanian (Român)", "ro_RO"}, */ /* XXX No po's yet. */
+/* {19, "POLISH", 0, "Polish (Polski)", "pl_PL"},*/ /* XXX Not active nor enough translated. */
+/* {20, "ROMANIAN", 0, "Romanian (Român)", "ro_RO"}, */ /* XXX Not active nor enough translated. */
{17, "SERBIAN", 0, "Serbian (Српски)", "sr_RS"},
- {28, "SERBIAN_LATIN", 0, "Serbian latin (Srpski latinica)", "sr_RS@latin"},
+ {28, "SERBIAN_LATIN", 0, "Serbian Latin (Srpski latinica)", "sr_RS@latin"},
{ 7, "SWEDISH", 0, "Swedish (Svenska)", "sv_SE"},
{30, "TURKISH", 0, "Turkish (Türkçe)", "tr_TR"},
{ 0, NULL, 0, NULL, NULL}
};
+#else
+ static EnumPropertyItem language_items[] = {
+ { 0, "DEFAULT", 0, "Default (Default)", ""},
+ { 0, NULL, 0, NULL, NULL}
+ };
+#endif
#ifdef WITH_CYCLES
static EnumPropertyItem compute_device_items[] = {
@@ -3066,6 +3097,9 @@ static void rna_def_userdef_system(BlenderRNA *brna)
prop = RNA_def_property(srna, "language", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_items(prop, language_items);
+#ifdef WITH_INTERNATIONAL
+ RNA_def_property_enum_funcs(prop, NULL, NULL, "rna_lang_enum_properties_itemf");
+#endif
RNA_def_property_ui_text(prop, "Language", "Language used for translation");
RNA_def_property_update(prop, NC_WINDOW, "rna_userdef_language_update");
@@ -3292,6 +3326,12 @@ static void rna_def_userdef_input(BlenderRNA *brna)
{USER_TRACKBALL, "TRACKBALL", 0, "Trackball", "Use trackball style rotation in the viewport"},
{0, NULL, 0, NULL, NULL}
};
+
+ static EnumPropertyItem ndof_view_rotation_items[] = {
+ {NDOF_TURNTABLE, "TURNTABLE", 0, "Turntable", "Use turntable style rotation in the viewport"},
+ {0, "TRACKBALL", 0, "Trackball", "Use trackball style rotation in the viewport"},
+ {0, NULL, 0, NULL, NULL}
+ };
static EnumPropertyItem view_zoom_styles[] = {
{USER_ZOOM_CONT, "CONTINUE", 0, "Continue", "Old style zoom, continues while moving mouse up or down"},
@@ -3383,9 +3423,10 @@ static void rna_def_userdef_input(BlenderRNA *brna)
/* TODO: update description when fly-mode visuals are in place ("projected position in fly mode")*/
/* 3D view */
- prop = RNA_def_property(srna, "ndof_turntable", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_TURNTABLE);
- RNA_def_property_ui_text(prop, "Turntable", "Turntable for ndof rotation");
+ prop = RNA_def_property(srna, "ndof_view_rotate_method", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_bitflag_sdna(prop, NULL, "flag");
+ RNA_def_property_enum_items(prop, ndof_view_rotation_items);
+ RNA_def_property_ui_text(prop, "NDOF View Rotation", "Rotation style in the viewport");
/* 3D view: roll */
prop = RNA_def_property(srna, "ndof_roll_invert_axis", PROP_BOOLEAN, PROP_NONE);
@@ -3496,6 +3537,10 @@ static void rna_def_userdef_filepaths(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_HIDE_RECENT);
RNA_def_property_ui_text(prop, "Hide Recent Locations", "Hide recent locations in the file selector");
+ prop = RNA_def_property(srna, "hide_system_bookmarks", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_HIDE_SYSTEM_BOOKMARKS);
+ RNA_def_property_ui_text(prop, "Hide System Bookmarks", "Hide system bookmarks in the file selector");
+
prop = RNA_def_property(srna, "show_thumbnails", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_SHOW_THUMBNAILS);
RNA_def_property_ui_text(prop, "Show Thumbnails", "Open in thumbnail view for images and movies");
@@ -3592,7 +3637,7 @@ static void rna_def_userdef_filepaths(BlenderRNA *brna)
"Enables automatic saving of preview images in the .blend file");
}
-void rna_def_userdef_addon_collection(BlenderRNA *brna, PropertyRNA *cprop)
+static void rna_def_userdef_addon_collection(BlenderRNA *brna, PropertyRNA *cprop)
{
StructRNA *srna;
FunctionRNA *func;
@@ -3611,10 +3656,11 @@ void rna_def_userdef_addon_collection(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_function_return(func, parm);
func = RNA_def_function(srna, "remove", "rna_userdef_addon_remove");
- RNA_def_function_flag(func, FUNC_NO_SELF);
+ RNA_def_function_flag(func, FUNC_NO_SELF | FUNC_USE_REPORTS);
RNA_def_function_ui_description(func, "Remove addon");
parm = RNA_def_pointer(func, "addon", "Addon", "", "Addon to remove");
- RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
void RNA_def_userdef(BlenderRNA *brna)
diff --git a/source/blender/makesrna/intern/rna_wm.c b/source/blender/makesrna/intern/rna_wm.c
index 61c75e306cb..e5f44644f7a 100644
--- a/source/blender/makesrna/intern/rna_wm.c
+++ b/source/blender/makesrna/intern/rna_wm.c
@@ -122,6 +122,7 @@ EnumPropertyItem event_timer_type_items[] = {
};
EnumPropertyItem event_ndof_type_items[] = {
+ {NDOF_MOTION, "NDOF_MOTION", 0, "Motion", ""},
/* buttons on all 3dconnexion devices */
{NDOF_BUTTON_MENU, "NDOF_BUTTON_MENU", 0, "Menu", ""},
{NDOF_BUTTON_FIT, "NDOF_BUTTON_FIT", 0, "Fit", ""},
@@ -622,13 +623,34 @@ static void rna_wmKeyMapItem_map_type_set(PointerRNA *ptr, int value)
kmi->val = KM_NOTHING;
break;
case KMI_TYPE_NDOF:
- kmi->type = NDOF_BUTTON_MENU;
- kmi->val = KM_PRESS;
+ kmi->type = NDOF_MOTION;
+ kmi->val = KM_NOTHING;
break;
}
}
}
+/* assumes value to be an enum from event_type_items */
+/* function makes sure keymodifiers are only valid keys, ESC keeps it unaltered */
+static void rna_wmKeyMapItem_keymodifier_set(PointerRNA *ptr, int value)
+{
+ wmKeyMapItem *kmi = ptr->data;
+
+ /* XXX, this should really be managed in an _itemf function,
+ * giving a list of valid enums, then silently changing them when they are set is not
+ * a good precedent, don't do this unless you have a good reason! */
+ if (value == ESCKEY) {
+ /* pass */
+ }
+ else if (value >= AKEY) {
+ kmi->keymodifier = value;
+ }
+ else {
+ kmi->keymodifier = 0;
+ }
+}
+
+
static EnumPropertyItem *rna_KeyMapItem_type_itemf(bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop),
int *UNUSED(free))
{
@@ -765,14 +787,14 @@ static void rna_wmKeyMapItem_name_get(PointerRNA *ptr, char *value)
{
wmKeyMapItem *kmi = ptr->data;
wmOperatorType *ot = WM_operatortype_find(kmi->idname, 1);
- strcpy(value, ot ? ot->name : kmi->idname);
+ strcpy(value, ot ? RNA_struct_ui_name(ot->srna) : kmi->idname);
}
static int rna_wmKeyMapItem_name_length(PointerRNA *ptr)
{
wmKeyMapItem *kmi = ptr->data;
wmOperatorType *ot = WM_operatortype_find(kmi->idname, 1);
- return strlen(ot ? ot->name : kmi->idname);
+ return strlen(ot ? RNA_struct_ui_name(ot->srna) : kmi->idname);
}
static int rna_KeyMapItem_userdefined_get(PointerRNA *ptr)
@@ -1062,7 +1084,7 @@ static StructRNA *rna_Operator_register(Main *bmain, ReportList *reports, void *
}
else {
BKE_reportf(reports, RPT_ERROR,
- "registering operator class: '%s', invalid bl_idname '%s', at position %d",
+ "Registering operator class: '%s', invalid bl_idname '%s', at position %d",
identifier, _operator_idname, i);
return NULL;
}
@@ -1071,7 +1093,7 @@ static StructRNA *rna_Operator_register(Main *bmain, ReportList *reports, void *
}
if (i > ((int)sizeof(dummyop.idname)) - 3) {
- BKE_reportf(reports, RPT_ERROR, "registering operator class: '%s', invalid bl_idname '%s', "
+ BKE_reportf(reports, RPT_ERROR, "Registering operator class: '%s', invalid bl_idname '%s', "
"is too long, maximum length is %d", identifier, _operator_idname,
(int)sizeof(dummyop.idname) - 3);
return NULL;
@@ -1079,7 +1101,7 @@ static StructRNA *rna_Operator_register(Main *bmain, ReportList *reports, void *
if (dot != 1) {
BKE_reportf(reports, RPT_ERROR,
- "registering operator class: '%s', invalid bl_idname '%s', must contain 1 '.' character",
+ "Registering operator class: '%s', invalid bl_idname '%s', must contain 1 '.' character",
identifier, _operator_idname);
return NULL;
}
@@ -1136,7 +1158,7 @@ static StructRNA *rna_Operator_register(Main *bmain, ReportList *reports, void *
return dummyot.ext.srna;
}
-void **rna_Operator_instance(PointerRNA *ptr)
+static void **rna_Operator_instance(PointerRNA *ptr)
{
wmOperator *op = ptr->data;
return &op->py_instance;
@@ -1180,7 +1202,7 @@ static StructRNA *rna_MacroOperator_register(Main *bmain, ReportList *reports, v
}
if (strlen(identifier) >= sizeof(dummyop.idname)) {
- BKE_reportf(reports, RPT_ERROR, "registering operator class: '%s' is too long, maximum length is %d",
+ BKE_reportf(reports, RPT_ERROR, "Registering operator class: '%s' is too long, maximum length is %d",
identifier, (int)sizeof(dummyop.idname));
return NULL;
}
@@ -1230,24 +1252,30 @@ static void rna_Operator_bl_idname_set(PointerRNA *ptr, const char *value)
{
wmOperator *data = (wmOperator *)(ptr->data);
char *str = (char *)data->type->idname;
- if (!str[0]) BLI_strncpy(str, value, RNA_DYN_DESCR_MAX); /* utf8 already ensured */
- else assert(!"setting the bl_idname on a non-builtin operator");
+ if (!str[0])
+ BLI_strncpy(str, value, OP_MAX_TYPENAME); /* utf8 already ensured */
+ else
+ assert(!"setting the bl_idname on a non-builtin operator");
}
static void rna_Operator_bl_label_set(PointerRNA *ptr, const char *value)
{
wmOperator *data = (wmOperator *)(ptr->data);
char *str = (char *)data->type->name;
- if (!str[0]) BLI_strncpy(str, value, RNA_DYN_DESCR_MAX); /* utf8 already ensured */
- else assert(!"setting the bl_label on a non-builtin operator");
+ if (!str[0])
+ BLI_strncpy(str, value, OP_MAX_TYPENAME); /* utf8 already ensured */
+ else
+ assert(!"setting the bl_label on a non-builtin operator");
}
static void rna_Operator_bl_description_set(PointerRNA *ptr, const char *value)
{
wmOperator *data = (wmOperator *)(ptr->data);
char *str = (char *)data->type->description;
- if (!str[0]) BLI_strncpy(str, value, RNA_DYN_DESCR_MAX); /* utf8 already ensured */
- else assert(!"setting the bl_description on a non-builtin operator");
+ if (!str[0])
+ BLI_strncpy(str, value, RNA_DYN_DESCR_MAX); /* utf8 already ensured */
+ else
+ assert(!"setting the bl_description on a non-builtin operator");
}
static void rna_KeyMapItem_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
@@ -1404,7 +1432,7 @@ static void rna_def_operator_type_macro(BlenderRNA *brna)
RNA_def_struct_ui_text(srna, "Operator Macro", "Storage of a sub operator in a macro after it has been added");
RNA_def_struct_sdna(srna, "wmOperatorTypeMacro");
-/* prop= RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); */
+/* prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); */
/* RNA_def_property_clear_flag(prop, PROP_EDITABLE); */
/* RNA_def_property_string_sdna(prop, NULL, "idname"); */
/* RNA_def_property_ui_text(prop, "Name", "Name of the sub operator"); */
@@ -1793,7 +1821,7 @@ static void rna_def_keyconfig(BlenderRNA *brna)
* fallback on the operator ID */
prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
- RNA_def_property_ui_text(prop, "Name", "Name of operator to call on input event");
+ RNA_def_property_ui_text(prop, "Name", "Name of operator (translated) to call on input event");
RNA_def_property_string_funcs(prop, "rna_wmKeyMapItem_name_get", "rna_wmKeyMapItem_name_length", NULL);
prop = RNA_def_property(srna, "properties", PROP_POINTER, PROP_NONE);
@@ -1865,6 +1893,7 @@ static void rna_def_keyconfig(BlenderRNA *brna)
prop = RNA_def_property(srna, "key_modifier", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "keymodifier");
RNA_def_property_enum_items(prop, event_type_items);
+ RNA_def_property_enum_funcs(prop, NULL, "rna_wmKeyMapItem_keymodifier_set", NULL);
RNA_def_property_ui_text(prop, "Key Modifier", "Regular key pressed as a modifier");
RNA_def_property_update(prop, 0, "rna_KeyMapItem_update");
diff --git a/source/blender/makesrna/intern/rna_wm_api.c b/source/blender/makesrna/intern/rna_wm_api.c
index ae4d5dc493e..116e07073cd 100644
--- a/source/blender/makesrna/intern/rna_wm_api.c
+++ b/source/blender/makesrna/intern/rna_wm_api.c
@@ -32,6 +32,8 @@
#include <stdlib.h>
#include <stdio.h>
+#include "BLI_utildefines.h"
+
#include "RNA_define.h"
#include "RNA_enum_types.h"
@@ -39,6 +41,8 @@
#include "DNA_space_types.h"
#include "DNA_windowmanager_types.h"
+#include "rna_internal.h" /* own include */
+
#ifdef RNA_RUNTIME
#include "BKE_context.h"
@@ -72,12 +76,12 @@ static int rna_event_modal_handler_add(struct bContext *C, struct wmOperator *op
}
/* XXX, need a way for python to know event types, 0x0110 is hard coded */
-wmTimer *rna_event_timer_add(struct wmWindowManager *wm, float time_step, wmWindow *win)
+static wmTimer *rna_event_timer_add(struct wmWindowManager *wm, float time_step, wmWindow *win)
{
return WM_event_add_timer(wm, win, 0x0110, time_step);
}
-void rna_event_timer_remove(struct wmWindowManager *wm, wmTimer *timer)
+static void rna_event_timer_remove(struct wmWindowManager *wm, wmTimer *timer)
{
WM_event_remove_timer(wm, timer->win, timer);
}
@@ -149,6 +153,18 @@ static wmKeyMapItem *rna_KeyMap_item_new_modal(wmKeyMap *km, ReportList *reports
return WM_modalkeymap_add_item(km, type, value, modifier, keymodifier, propvalue);
}
+static void rna_KeyMap_item_remove(wmKeyMap *km, ReportList *reports, PointerRNA *kmi_ptr)
+{
+ wmKeyMapItem *kmi = kmi_ptr->data;
+
+ if (WM_keymap_remove_item(km, kmi) == FALSE) {
+ BKE_reportf(reports, RPT_ERROR, "KeyMapItem '%s' can't be removed from '%s'", kmi->idname, km->idname);
+ return;
+ }
+
+ RNA_POINTER_INVALIDATE(kmi_ptr);
+}
+
static wmKeyMap *rna_keymap_new(wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid, int modal)
{
if (modal == 0) {
@@ -174,6 +190,18 @@ static wmKeyMap *rna_keymap_find_modal(wmKeyConfig *UNUSED(keyconf), const char
return ot->modalkeymap;
}
+static void rna_KeyConfig_remove(wmWindowManager *wm, ReportList *reports, PointerRNA *keyconf_ptr)
+{
+ wmKeyConfig *keyconf = keyconf_ptr->data;
+
+ if (WM_keyconfig_remove(wm, keyconf) == FALSE) {
+ BKE_reportf(reports, RPT_ERROR, "KeyConfig '%s' can't be removed", keyconf->idname);
+ return;
+ }
+
+ RNA_POINTER_INVALIDATE(keyconf_ptr);
+}
+
#else
#define WM_GEN_INVOKE_EVENT (1 << 0)
@@ -288,7 +316,7 @@ void RNA_api_operator(StructRNA *srna)
/* exec */
func = RNA_def_function(srna, "execute", NULL);
RNA_def_function_ui_description(func, "Execute the operator");
- RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL);
+ RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL | FUNC_ALLOW_WRITE);
parm = RNA_def_pointer(func, "context", "Context", "", "");
RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
@@ -299,7 +327,7 @@ void RNA_api_operator(StructRNA *srna)
/* check */
func = RNA_def_function(srna, "check", NULL);
RNA_def_function_ui_description(func, "Check the operator settings, return True to signal a change to redraw");
- RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL);
+ RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL | FUNC_ALLOW_WRITE);
parm = RNA_def_pointer(func, "context", "Context", "", "");
RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
@@ -309,7 +337,7 @@ void RNA_api_operator(StructRNA *srna)
/* invoke */
func = RNA_def_function(srna, "invoke", NULL);
RNA_def_function_ui_description(func, "Invoke the operator");
- RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL);
+ RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL | FUNC_ALLOW_WRITE);
parm = RNA_def_pointer(func, "context", "Context", "", "");
RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
parm = RNA_def_pointer(func, "event", "Event", "", "");
@@ -321,7 +349,7 @@ void RNA_api_operator(StructRNA *srna)
func = RNA_def_function(srna, "modal", NULL); /* same as invoke */
RNA_def_function_ui_description(func, "Modal operator function");
- RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL);
+ RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL | FUNC_ALLOW_WRITE);
parm = RNA_def_pointer(func, "context", "Context", "", "");
RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
parm = RNA_def_pointer(func, "event", "Event", "", "");
@@ -341,7 +369,7 @@ void RNA_api_operator(StructRNA *srna)
/* cancel */
func = RNA_def_function(srna, "cancel", NULL);
RNA_def_function_ui_description(func, "Called when the operator is canceled");
- RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL);
+ RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL | FUNC_ALLOW_WRITE);
parm = RNA_def_pointer(func, "context", "Context", "", "");
RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
@@ -381,7 +409,7 @@ void RNA_api_macro(StructRNA *srna)
RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL);
}
-void RNA_api_keyconfig(StructRNA *srna)
+void RNA_api_keyconfig(StructRNA *UNUSED(srna))
{
/* FunctionRNA *func; */
/* PropertyRNA *parm; */
@@ -460,9 +488,11 @@ void RNA_api_keymapitems(StructRNA *srna)
parm = RNA_def_pointer(func, "item", "KeyMapItem", "Item", "Added key map item");
RNA_def_function_return(func, parm);
- func = RNA_def_function(srna, "remove", "WM_keymap_remove_item");
+ func = RNA_def_function(srna, "remove", "rna_KeyMap_item_remove");
+ RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "item", "KeyMapItem", "Item", "");
- RNA_def_property_flag(parm, PROP_REQUIRED);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
func = RNA_def_function(srna, "from_id", "WM_keymap_item_find_id");
parm = RNA_def_property(func, "id", PROP_INT, PROP_NONE);
@@ -512,10 +542,11 @@ void RNA_api_keyconfigs(StructRNA *srna)
parm = RNA_def_pointer(func, "keyconfig", "KeyConfig", "Key Configuration", "Added key configuration");
RNA_def_function_return(func, parm);
- func = RNA_def_function(srna, "remove", "WM_keyconfig_remove"); /* remove_keyconfig */
+ func = RNA_def_function(srna, "remove", "rna_KeyConfig_remove"); /* remove_keyconfig */
+ RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "keyconfig", "KeyConfig", "Key Configuration", "Removed key configuration");
- RNA_def_property_flag(parm, PROP_REQUIRED);
+ RNA_def_property_flag(parm, PROP_REQUIRED | PROP_NEVER_NULL | PROP_RNAPTR);
+ RNA_def_property_clear_flag(parm, PROP_THICK_WRAP);
}
#endif
-
diff --git a/source/blender/makesrna/rna_cleanup/rna_cleaner.py b/source/blender/makesrna/rna_cleanup/rna_cleaner.py
index e3359fbae59..0231e57fcfd 100755
--- a/source/blender/makesrna/rna_cleanup/rna_cleaner.py
+++ b/source/blender/makesrna/rna_cleanup/rna_cleaner.py
@@ -130,11 +130,11 @@ def get_props_from_txt(input_filename):
line = line[1:]
# class
- [bclass, tail] = [x.strip() for x in line.split('.', 1)]
+ bclass, tail = [x.strip() for x in line.split('.', 1)]
# comment
if '*' in bclass:
- [comment, bclass] = [x.strip() for x in bclass.split('*', 1)]
+ comment, bclass = [x.strip() for x in bclass.split('*', 1)]
else:
comment= ''
@@ -144,18 +144,18 @@ def get_props_from_txt(input_filename):
continue
# from
- [bfrom, tail] = [x.strip() for x in tail.split('->', 1)]
+ bfrom, tail = [x.strip() for x in tail.split('->', 1)]
# to
- [bto, tail] = [x.strip() for x in tail.split(':', 1)]
+ bto, tail = [x.strip() for x in tail.split(':', 1)]
# type, description
try:
- [btype, description] = tail.split(None, 1)
+ btype, description = tail.split(None, 1)
# make life easy and strip quotes
description = description.replace("'", "").replace('"', "").replace("\\", "").strip()
except ValueError:
- [btype, description] = [tail,'NO DESCRIPTION']
+ btype, description = [tail,'NO DESCRIPTION']
# keyword-check
kwcheck = check_prefix(bto, btype)
diff --git a/source/blender/modifiers/CMakeLists.txt b/source/blender/modifiers/CMakeLists.txt
index 83e7ea81ca5..3a7066ff41a 100644
--- a/source/blender/modifiers/CMakeLists.txt
+++ b/source/blender/modifiers/CMakeLists.txt
@@ -38,6 +38,7 @@ set(INC
../render/extern/include
../../../intern/elbeem/extern
../../../intern/guardedalloc
+ ../../../intern/opennl/extern
)
set(INC_SYS
@@ -64,6 +65,7 @@ set(SRC
intern/MOD_fluidsim_util.c
intern/MOD_hook.c
intern/MOD_lattice.c
+ intern/MOD_laplaciansmooth.c
intern/MOD_mask.c
intern/MOD_meshdeform.c
intern/MOD_mirror.c
@@ -117,13 +119,6 @@ if(WITH_MOD_REMESH)
)
endif()
-if(WITH_MOD_DECIMATE)
- add_definitions(-DWITH_MOD_DECIMATE)
- list(APPEND INC
- ../../../intern/decimation/extern
- )
-endif()
-
if(WITH_MOD_FLUID)
add_definitions(-DWITH_MOD_FLUID)
endif()
diff --git a/source/blender/modifiers/MOD_modifiertypes.h b/source/blender/modifiers/MOD_modifiertypes.h
index bf411c3b2fc..a4817ff775d 100644
--- a/source/blender/modifiers/MOD_modifiertypes.h
+++ b/source/blender/modifiers/MOD_modifiertypes.h
@@ -75,8 +75,9 @@ extern ModifierTypeInfo modifierType_WeightVGProximity;
extern ModifierTypeInfo modifierType_DynamicPaint;
extern ModifierTypeInfo modifierType_Remesh;
extern ModifierTypeInfo modifierType_Skin;
+extern ModifierTypeInfo modifierType_LaplacianSmooth;
/* MOD_util.c */
void modifier_type_init(ModifierTypeInfo *types[]);
-#endif //__MOD_MODIFIERTYPES_H__
+#endif /* __MOD_MODIFIERTYPES_H__ */
diff --git a/source/blender/modifiers/SConscript b/source/blender/modifiers/SConscript
index 2b506cce2cf..62fd9ba2de1 100644
--- a/source/blender/modifiers/SConscript
+++ b/source/blender/modifiers/SConscript
@@ -4,7 +4,7 @@ Import ('env')
sources = env.Glob('intern/*.c')
incs = '. ./intern'
-incs += ' #/intern/guardedalloc #/intern/decimation/extern #/intern/bsp/extern #/intern/elbeem/extern #/extern/glew/include'
+incs += ' #/intern/guardedalloc #/intern/bsp/extern #/intern/elbeem/extern #/extern/glew/include #/intern/opennl/extern'
incs += ' ../render/extern/include ../blenloader ../bmesh'
incs += ' ../include ../blenlib ../blenfont ../makesdna ../makesrna ../blenkernel ../blenkernel/intern'
incs += ' ../gpu'
@@ -20,9 +20,6 @@ if env['WITH_BF_REMESH']:
incs += ' #/intern/dualcon'
defs.append('WITH_MOD_REMESH')
-if env ['WITH_BF_DECIMATE']:
- defs.append('WITH_MOD_DECIMATE')
-
if env['WITH_BF_FLUID']:
defs.append('WITH_MOD_FLUID')
diff --git a/source/blender/modifiers/intern/MOD_armature.c b/source/blender/modifiers/intern/MOD_armature.c
index e6d86de45b4..7219038b087 100644
--- a/source/blender/modifiers/intern/MOD_armature.c
+++ b/source/blender/modifiers/intern/MOD_armature.c
@@ -135,13 +135,13 @@ static void deformVerts(ModifierData *md, Object *ob,
}
static void deformVertsEM(
- ModifierData *md, Object *ob, struct BMEditMesh *editData,
+ ModifierData *md, Object *ob, struct BMEditMesh *em,
DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
ArmatureModifierData *amd = (ArmatureModifierData *) md;
DerivedMesh *dm = derivedData;
- if (!derivedData) dm = CDDM_from_BMEditMesh(editData, ob->data, FALSE, FALSE);
+ if (!derivedData) dm = CDDM_from_editbmesh(em, FALSE, FALSE);
modifier_vgroup_cache(md, vertexCos); /* if next modifier needs original vertices */
@@ -158,14 +158,14 @@ static void deformVertsEM(
}
static void deformMatricesEM(
- ModifierData *md, Object *ob, struct BMEditMesh *editData,
+ ModifierData *md, Object *ob, struct BMEditMesh *em,
DerivedMesh *derivedData, float (*vertexCos)[3],
float (*defMats)[3][3], int numVerts)
{
ArmatureModifierData *amd = (ArmatureModifierData *) md;
DerivedMesh *dm = derivedData;
- if (!derivedData) dm = CDDM_from_BMEditMesh(editData, ob->data, FALSE, FALSE);
+ if (!derivedData) dm = CDDM_from_editbmesh(em, FALSE, FALSE);
armature_deform_verts(amd->object, ob, dm, vertexCos, defMats, numVerts,
amd->deformflag, NULL, amd->defgrp_name);
diff --git a/source/blender/modifiers/intern/MOD_array.c b/source/blender/modifiers/intern/MOD_array.c
index 26682e30841..b9dd37ac50c 100644
--- a/source/blender/modifiers/intern/MOD_array.c
+++ b/source/blender/modifiers/intern/MOD_array.c
@@ -53,7 +53,8 @@
#include "BKE_mesh.h"
#include "BKE_modifier.h"
#include "BKE_object.h"
-#include "BKE_tessmesh.h"
+
+#include "bmesh.h"
#include "depsgraph_private.h"
@@ -310,10 +311,11 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
int UNUSED(initFlags))
{
DerivedMesh *result;
- BMEditMesh *em = DM_to_editbmesh(dm, NULL, FALSE);
+ BMesh *bm = DM_to_bmesh(dm);
BMOperator first_dupe_op, dupe_op, old_dupe_op, weld_op;
BMVert **first_geom = NULL;
- int i, j, indexLen;
+ int i, j;
+ int index_len = -1; /* initialize to an invalid value */
/* offset matrix */
float offset[4][4];
float final_offset[4][4];
@@ -406,14 +408,14 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
* cleaner way to do this. One possibility: a "mirror" BMOp would
* certainly help by compressing it all into one top-level BMOp that
* executes a lot of second-level BMOps. */
- BMO_push(em->bm, NULL);
- bmesh_edit_begin(em->bm, 0);
+ BMO_push(bm, NULL);
+ bmesh_edit_begin(bm, 0);
if (amd->flags & MOD_ARR_MERGE)
- BMO_op_init(em->bm, &weld_op, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
+ BMO_op_init(bm, &weld_op, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
"weld_verts");
- BMO_op_initf(em->bm, &dupe_op, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
+ BMO_op_initf(bm, &dupe_op, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
"duplicate geom=%avef");
first_dupe_op = dupe_op;
@@ -424,11 +426,11 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
BMOIter oiter;
if (j != 0) {
- BMO_op_initf(em->bm, &dupe_op,
+ BMO_op_initf(bm, &dupe_op,
(BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
"duplicate geom=%s", &old_dupe_op, "newout");
}
- BMO_op_exec(em->bm, &dupe_op);
+ BMO_op_exec(bm, &dupe_op);
geom_slot = BMO_slot_get(&dupe_op, "geom");
newout_slot = BMO_slot_get(&dupe_op, "newout");
@@ -443,20 +445,23 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
}
/* apply transformation matrix */
- BMO_ITER (v, &oiter, em->bm, &dupe_op, "newout", BM_VERT) {
+ BMO_ITER (v, &oiter, bm, &dupe_op, "newout", BM_VERT) {
mul_m4_v3(offset, v->co);
}
if (amd->flags & MOD_ARR_MERGE) {
/*calculate merge mapping*/
if (j == 0) {
- indexMap = find_doubles_index_map(em->bm, &dupe_op,
- amd, &indexLen);
+ indexMap = find_doubles_index_map(bm, &dupe_op,
+ amd, &index_len);
}
#define _E(s, i) ((BMVert **)(s)->data.buf)[i]
- for (i = 0; i < indexLen; i++) {
+ /* ensure this is set */
+ BLI_assert(index_len != -1);
+
+ for (i = 0; i < index_len; i++) {
if (!indexMap[i]) continue;
/* merge v (from 'newout') into v2 (from old 'geom') */
@@ -465,11 +470,11 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
/* check in case the target vertex (v2) is already marked
* for merging */
- while ((v3 = BMO_slot_map_ptr_get(em->bm, &weld_op, "targetmap", v2))) {
+ while ((v3 = BMO_slot_map_ptr_get(bm, &weld_op, "targetmap", v2))) {
v2 = v3;
}
- BMO_slot_map_ptr_insert(em->bm, &weld_op, "targetmap", v, v2);
+ BMO_slot_map_ptr_insert(bm, &weld_op, "targetmap", v, v2);
}
#undef _E
@@ -481,7 +486,7 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
first_dupe_op = dupe_op;
if (j >= 2)
- BMO_op_finish(em->bm, &old_dupe_op);
+ BMO_op_finish(bm, &old_dupe_op);
old_dupe_op = dupe_op;
}
@@ -494,45 +499,44 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
* loop) the offset between first and last is different from
* dupe X to dupe X+1. */
- merge_first_last(em->bm, amd, &first_dupe_op, &dupe_op, &weld_op);
+ merge_first_last(bm, amd, &first_dupe_op, &dupe_op, &weld_op);
}
/* start capping */
if (start_cap || end_cap) {
- BM_mesh_elem_hflag_enable_all(em->bm, BM_VERT, BM_ELEM_TAG, FALSE);
+ BM_mesh_elem_hflag_enable_all(bm, BM_VERT, BM_ELEM_TAG, FALSE);
if (start_cap) {
float startoffset[4][4];
invert_m4_m4(startoffset, offset);
- bm_merge_dm_transform(em->bm, start_cap, startoffset, amd,
+ bm_merge_dm_transform(bm, start_cap, startoffset, amd,
&first_dupe_op, "geom", &weld_op);
}
if (end_cap) {
float endoffset[4][4];
mult_m4_m4m4(endoffset, offset, final_offset);
- bm_merge_dm_transform(em->bm, end_cap, endoffset, amd,
+ bm_merge_dm_transform(bm, end_cap, endoffset, amd,
&dupe_op, count == 1 ? "geom" : "newout", &weld_op);
}
}
/* done capping */
/* free remaining dupe operators */
- BMO_op_finish(em->bm, &first_dupe_op);
+ BMO_op_finish(bm, &first_dupe_op);
if (count > 2)
- BMO_op_finish(em->bm, &dupe_op);
+ BMO_op_finish(bm, &dupe_op);
/* run merge operator */
if (amd->flags & MOD_ARR_MERGE) {
- BMO_op_exec(em->bm, &weld_op);
- BMO_op_finish(em->bm, &weld_op);
+ BMO_op_exec(bm, &weld_op);
+ BMO_op_finish(bm, &weld_op);
}
/* Bump the stack level back down to match the adjustment up above */
- BMO_pop(em->bm);
+ BMO_pop(bm);
- BLI_assert(em->looptris == NULL);
- result = CDDM_from_BMEditMesh(em, NULL, FALSE, FALSE);
+ result = CDDM_from_bmesh(bm, FALSE);
if ((amd->offset_type & MOD_ARR_OFF_OBJ) && (amd->offset_ob)) {
/* Update normals in case offset object has rotation. */
@@ -543,8 +547,8 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
CDDM_calc_normals(result);
}
- BMEdit_Free(em);
- MEM_freeN(em);
+ BM_mesh_free(bm);
+
if (indexMap)
MEM_freeN(indexMap);
if (first_geom)
diff --git a/source/blender/modifiers/intern/MOD_bevel.c b/source/blender/modifiers/intern/MOD_bevel.c
index cdb200ff180..3e3bcb73491 100644
--- a/source/blender/modifiers/intern/MOD_bevel.c
+++ b/source/blender/modifiers/intern/MOD_bevel.c
@@ -38,11 +38,11 @@
#include "BKE_cdderivedmesh.h"
#include "BKE_modifier.h"
-#include "BKE_tessmesh.h"
#include "BKE_mesh.h"
-
#include "BKE_bmesh.h" /* only for defines */
+#include "bmesh.h"
+
#include "DNA_object_types.h"
#include "MEM_guardedalloc.h"
@@ -88,10 +88,12 @@ static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
return dataMask;
}
-#define EDGE_MARK 1
+// #define USE_BM_BEVEL_OP_AS_MOD
#ifdef USE_BM_BEVEL_OP_AS_MOD
+#define EDGE_MARK 1
+
/* BMESH_TODO
*
* this bevel calls the operator which is missing many of the options
@@ -111,14 +113,12 @@ static DerivedMesh *applyModifier(ModifierData *md, struct Object *UNUSED(ob),
{
DerivedMesh *result;
BMesh *bm;
- BMEditMesh *em;
BMIter iter;
BMEdge *e;
BevelModifierData *bmd = (BevelModifierData *) md;
- float threshold = cos((bmd->bevel_angle + 0.00001) * M_PI / 180.0);
+ float threshold = cos((bmd->bevel_angle + 0.00001f) * M_PI / 180.0f);
- em = DM_to_editbmesh(dm, NULL, FALSE);
- bm = em->bm;
+ bm = DM_to_bmesh(dm);
BM_mesh_normals_update(bm, FALSE);
BMO_push(bm, NULL);
@@ -148,10 +148,8 @@ static DerivedMesh *applyModifier(ModifierData *md, struct Object *UNUSED(ob),
EDGE_MARK, bmd->value, (bmd->flags & BME_BEVEL_EVEN) != 0, (bmd->flags & BME_BEVEL_DIST) != 0);
BMO_pop(bm);
- BLI_assert(em->looptris == NULL);
- result = CDDM_from_BMEditMesh(em, NULL, TRUE, FALSE);
- BMEdit_Free(em);
- MEM_freeN(em);
+ result = CDDM_from_bmesh(bm, TRUE);
+ BM_mesh_free(bm);
return result;
}
@@ -164,7 +162,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *UNUSED(ob),
ModifierApplyFlag UNUSED(flag))
{
DerivedMesh *result;
- BMEditMesh *em;
+ BMesh *bm;
/*bDeformGroup *def;*/
int /*i,*/ options, defgrp_index = -1;
@@ -175,18 +173,16 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *UNUSED(ob),
#if 0
if ((options & BME_BEVEL_VWEIGHT) && bmd->defgrp_name[0]) {
defgrp_index = defgroup_name_index(ob, bmd->defgrp_name);
- if (defgrp_index < 0) {
+ if (defgrp_index == -1) {
options &= ~BME_BEVEL_VWEIGHT;
}
}
#endif
- em = DM_to_editbmesh(derivedData, NULL, FALSE);
- BME_bevel(em, bmd->value, bmd->res, options, defgrp_index, DEG2RADF(bmd->bevel_angle), NULL, FALSE);
- BLI_assert(em->looptris == NULL);
- result = CDDM_from_BMEditMesh(em, NULL, TRUE, FALSE);
- BMEdit_Free(em);
- MEM_freeN(em);
+ bm = DM_to_bmesh(derivedData);
+ BME_bevel(bm, bmd->value, bmd->res, options, defgrp_index, DEG2RADF(bmd->bevel_angle), NULL);
+ result = CDDM_from_bmesh(bm, TRUE);
+ BM_mesh_free(bm);
/* until we allow for dirty normal flag, always calc,
* note: calculating on the CDDM is faster then the BMesh equivalent */
@@ -206,29 +202,29 @@ static DerivedMesh *applyModifierEM(ModifierData *md, Object *ob,
ModifierTypeInfo modifierType_Bevel = {
- /* name */ "Bevel",
- /* structName */ "BevelModifierData",
- /* structSize */ sizeof(BevelModifierData),
- /* type */ eModifierTypeType_Constructive,
- /* flags */ eModifierTypeFlag_AcceptsMesh |
- eModifierTypeFlag_SupportsEditmode |
- eModifierTypeFlag_EnableInEditmode,
-
- /* copyData */ copyData,
- /* deformVerts */ NULL,
- /* deformMatrices */ NULL,
- /* deformVertsEM */ NULL,
- /* deformMatricesEM */ NULL,
- /* applyModifier */ applyModifier,
- /* applyModifierEM */ applyModifierEM,
- /* initData */ initData,
- /* requiredDataMask */ requiredDataMask,
- /* freeData */ NULL,
- /* isDisabled */ NULL,
- /* updateDepgraph */ NULL,
- /* dependsOnTime */ NULL,
- /* dependsOnNormals */ NULL,
+ /* name */ "Bevel",
+ /* structName */ "BevelModifierData",
+ /* structSize */ sizeof(BevelModifierData),
+ /* type */ eModifierTypeType_Constructive,
+ /* flags */ eModifierTypeFlag_AcceptsMesh |
+ eModifierTypeFlag_SupportsEditmode |
+ eModifierTypeFlag_EnableInEditmode,
+
+ /* copyData */ copyData,
+ /* deformVerts */ NULL,
+ /* deformMatrices */ NULL,
+ /* deformVertsEM */ NULL,
+ /* deformMatricesEM */ NULL,
+ /* applyModifier */ applyModifier,
+ /* applyModifierEM */ applyModifierEM,
+ /* initData */ initData,
+ /* requiredDataMask */ requiredDataMask,
+ /* freeData */ NULL,
+ /* isDisabled */ NULL,
+ /* updateDepgraph */ NULL,
+ /* dependsOnTime */ NULL,
+ /* dependsOnNormals */ NULL,
/* foreachObjectLink */ NULL,
- /* foreachIDLink */ NULL,
- /* foreachTexLink */ NULL,
+ /* foreachIDLink */ NULL,
+ /* foreachTexLink */ NULL,
};
diff --git a/source/blender/modifiers/intern/MOD_boolean.c b/source/blender/modifiers/intern/MOD_boolean.c
index 5c78a8efe23..0a48003fc81 100644
--- a/source/blender/modifiers/intern/MOD_boolean.c
+++ b/source/blender/modifiers/intern/MOD_boolean.c
@@ -167,7 +167,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
if (result)
return result;
else
- modifier_setError(md, "%s", TIP_("Can't execute boolean operation."));
+ modifier_setError(md, "Cannot execute boolean operation");
}
return derivedData;
@@ -192,28 +192,28 @@ static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(
ModifierTypeInfo modifierType_Boolean = {
- /* name */ "Boolean",
- /* structName */ "BooleanModifierData",
- /* structSize */ sizeof(BooleanModifierData),
- /* type */ eModifierTypeType_Nonconstructive,
- /* flags */ eModifierTypeFlag_AcceptsMesh |
- eModifierTypeFlag_UsesPointCache,
-
- /* copyData */ copyData,
- /* deformVerts */ NULL,
- /* deformMatrices */ NULL,
- /* deformVertsEM */ NULL,
- /* deformMatricesEM */ NULL,
- /* applyModifier */ applyModifier,
- /* applyModifierEM */ NULL,
- /* initData */ NULL,
- /* requiredDataMask */ requiredDataMask,
- /* freeData */ NULL,
- /* isDisabled */ isDisabled,
- /* updateDepgraph */ updateDepgraph,
- /* dependsOnTime */ NULL,
- /* dependsOnNormals */ NULL,
+ /* name */ "Boolean",
+ /* structName */ "BooleanModifierData",
+ /* structSize */ sizeof(BooleanModifierData),
+ /* type */ eModifierTypeType_Nonconstructive,
+ /* flags */ eModifierTypeFlag_AcceptsMesh |
+ eModifierTypeFlag_UsesPointCache,
+
+ /* copyData */ copyData,
+ /* deformVerts */ NULL,
+ /* deformMatrices */ NULL,
+ /* deformVertsEM */ NULL,
+ /* deformMatricesEM */ NULL,
+ /* applyModifier */ applyModifier,
+ /* applyModifierEM */ NULL,
+ /* initData */ NULL,
+ /* requiredDataMask */ requiredDataMask,
+ /* freeData */ NULL,
+ /* isDisabled */ isDisabled,
+ /* updateDepgraph */ updateDepgraph,
+ /* dependsOnTime */ NULL,
+ /* dependsOnNormals */ NULL,
/* foreachObjectLink */ foreachObjectLink,
- /* foreachIDLink */ NULL,
- /* foreachTexLink */ NULL,
+ /* foreachIDLink */ NULL,
+ /* foreachTexLink */ NULL,
};
diff --git a/source/blender/modifiers/intern/MOD_boolean_util.c b/source/blender/modifiers/intern/MOD_boolean_util.c
index bded11ddfa7..2ff93532d14 100644
--- a/source/blender/modifiers/intern/MOD_boolean_util.c
+++ b/source/blender/modifiers/intern/MOD_boolean_util.c
@@ -361,9 +361,9 @@ static DerivedMesh *ConvertCSGDescriptorsToDerivedMesh(
/* create a new DerivedMesh */
result = CDDM_new(vertex_it->num_elements, 0, face_it->num_elements, 0, 0);
- CustomData_merge(&dm1->faceData, &result->faceData, CD_MASK_DERIVEDMESH & ~(CD_MASK_NORMAL | CD_MASK_POLYINDEX | CD_MASK_ORIGINDEX),
+ CustomData_merge(&dm1->faceData, &result->faceData, CD_MASK_DERIVEDMESH & ~(CD_MASK_NORMAL | CD_MASK_ORIGINDEX),
CD_DEFAULT, face_it->num_elements);
- CustomData_merge(&dm2->faceData, &result->faceData, CD_MASK_DERIVEDMESH & ~(CD_MASK_NORMAL | CD_MASK_POLYINDEX | CD_MASK_ORIGINDEX),
+ CustomData_merge(&dm2->faceData, &result->faceData, CD_MASK_DERIVEDMESH & ~(CD_MASK_NORMAL | CD_MASK_ORIGINDEX),
CD_DEFAULT, face_it->num_elements);
/* step through the vertex iterators: */
diff --git a/source/blender/modifiers/intern/MOD_boolean_util.h b/source/blender/modifiers/intern/MOD_boolean_util.h
index b996dc6d6ba..209db60f0c9 100644
--- a/source/blender/modifiers/intern/MOD_boolean_util.h
+++ b/source/blender/modifiers/intern/MOD_boolean_util.h
@@ -51,4 +51,4 @@ int NewBooleanMesh(struct Scene *scene, struct Base *base, struct Base *base_sel
struct DerivedMesh *NewBooleanDerivedMesh(struct DerivedMesh *dm, struct Object *ob,
struct DerivedMesh *dm_select, struct Object *ob_select, int int_op_type);
-#endif // MOD_BOOLEAN_UTILS
+#endif /* MOD_BOOLEAN_UTILS */
diff --git a/source/blender/modifiers/intern/MOD_build.c b/source/blender/modifiers/intern/MOD_build.c
index 121b0ee89e3..2105a6efd21 100644
--- a/source/blender/modifiers/intern/MOD_build.c
+++ b/source/blender/modifiers/intern/MOD_build.c
@@ -293,27 +293,27 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *UNUSED(ob),
ModifierTypeInfo modifierType_Build = {
- /* name */ "Build",
- /* structName */ "BuildModifierData",
- /* structSize */ sizeof(BuildModifierData),
- /* type */ eModifierTypeType_Nonconstructive,
- /* flags */ eModifierTypeFlag_AcceptsMesh |
- eModifierTypeFlag_AcceptsCVs,
- /* copyData */ copyData,
- /* deformVerts */ NULL,
- /* deformMatrices */ NULL,
- /* deformVertsEM */ NULL,
- /* deformMatricesEM */ NULL,
- /* applyModifier */ applyModifier,
- /* applyModifierEM */ NULL,
- /* initData */ initData,
- /* requiredDataMask */ NULL,
- /* freeData */ NULL,
- /* isDisabled */ NULL,
- /* updateDepgraph */ NULL,
- /* dependsOnTime */ dependsOnTime,
- /* dependsOnNormals */ NULL,
+ /* name */ "Build",
+ /* structName */ "BuildModifierData",
+ /* structSize */ sizeof(BuildModifierData),
+ /* type */ eModifierTypeType_Nonconstructive,
+ /* flags */ eModifierTypeFlag_AcceptsMesh |
+ eModifierTypeFlag_AcceptsCVs,
+ /* copyData */ copyData,
+ /* deformVerts */ NULL,
+ /* deformMatrices */ NULL,
+ /* deformVertsEM */ NULL,
+ /* deformMatricesEM */ NULL,
+ /* applyModifier */ applyModifier,
+ /* applyModifierEM */ NULL,
+ /* initData */ initData,
+ /* requiredDataMask */ NULL,
+ /* freeData */ NULL,
+ /* isDisabled */ NULL,
+ /* updateDepgraph */ NULL,
+ /* dependsOnTime */ dependsOnTime,
+ /* dependsOnNormals */ NULL,
/* foreachObjectLink */ NULL,
- /* foreachIDLink */ NULL,
- /* foreachTexLink */ NULL,
+ /* foreachIDLink */ NULL,
+ /* foreachTexLink */ NULL,
};
diff --git a/source/blender/modifiers/intern/MOD_cloth.c b/source/blender/modifiers/intern/MOD_cloth.c
index dc6fef9b617..54f3efcc84c 100644
--- a/source/blender/modifiers/intern/MOD_cloth.c
+++ b/source/blender/modifiers/intern/MOD_cloth.c
@@ -155,7 +155,7 @@ static void copyData(ModifierData *md, ModifierData *target)
if (clmd->sim_parms->effector_weights)
tclmd->sim_parms->effector_weights = MEM_dupallocN(clmd->sim_parms->effector_weights);
tclmd->coll_parms = MEM_dupallocN(clmd->coll_parms);
- tclmd->point_cache = BKE_ptcache_copy_list(&tclmd->ptcaches, &clmd->ptcaches);
+ tclmd->point_cache = BKE_ptcache_copy_list(&tclmd->ptcaches, &clmd->ptcaches, FALSE);
tclmd->clothObject = NULL;
}
@@ -180,7 +180,7 @@ static void freeData(ModifierData *md)
MEM_freeN(clmd->sim_parms);
}
if (clmd->coll_parms)
- MEM_freeN(clmd->coll_parms);
+ MEM_freeN(clmd->coll_parms);
BKE_ptcache_free_list(&clmd->ptcaches);
clmd->point_cache = NULL;
diff --git a/source/blender/modifiers/intern/MOD_curve.c b/source/blender/modifiers/intern/MOD_curve.c
index 0ce4d74aebb..3ef6b9bfcb8 100644
--- a/source/blender/modifiers/intern/MOD_curve.c
+++ b/source/blender/modifiers/intern/MOD_curve.c
@@ -125,12 +125,12 @@ static void deformVerts(ModifierData *md, Object *ob,
}
static void deformVertsEM(
- ModifierData *md, Object *ob, struct BMEditMesh *editData,
+ ModifierData *md, Object *ob, struct BMEditMesh *em,
DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
- if (!derivedData) dm = CDDM_from_BMEditMesh(editData, ob->data, FALSE, FALSE);
+ if (!derivedData) dm = CDDM_from_editbmesh(em, FALSE, FALSE);
deformVerts(md, ob, dm, vertexCos, numVerts, 0);
diff --git a/source/blender/modifiers/intern/MOD_decimate.c b/source/blender/modifiers/intern/MOD_decimate.c
index cb6681bfa68..dc29e59d549 100644
--- a/source/blender/modifiers/intern/MOD_decimate.c
+++ b/source/blender/modifiers/intern/MOD_decimate.c
@@ -32,10 +32,10 @@
* \ingroup modifiers
*/
-
-#include "DNA_meshdata_types.h"
+#include "DNA_object_types.h"
#include "BLI_math.h"
+#include "BLI_string.h"
#include "BLI_utildefines.h"
#include "BLF_translation.h"
@@ -44,12 +44,16 @@
#include "BKE_mesh.h"
#include "BKE_modifier.h"
+#include "BKE_deform.h"
#include "BKE_particle.h"
#include "BKE_cdderivedmesh.h"
+#include "bmesh.h"
+
+// #define USE_TIMEIT
-#ifdef WITH_MOD_DECIMATE
-#include "LOD_decimation.h"
+#ifdef USE_TIMEIT
+# include "PIL_time.h"
#endif
#include "MOD_util.h"
@@ -59,6 +63,7 @@ static void initData(ModifierData *md)
DecimateModifierData *dmd = (DecimateModifierData *) md;
dmd->percent = 1.0;
+ dmd->angle = DEG2RADF(15.0f);
}
static void copyData(ModifierData *md, ModifierData *target)
@@ -67,146 +72,136 @@ static void copyData(ModifierData *md, ModifierData *target)
DecimateModifierData *tdmd = (DecimateModifierData *) target;
tdmd->percent = dmd->percent;
+ tdmd->iter = dmd->iter;
+ tdmd->angle = dmd->angle;
+ BLI_strncpy(tdmd->defgrp_name, dmd->defgrp_name, sizeof(tdmd->defgrp_name));
+ tdmd->flag = dmd->flag;
+ tdmd->mode = dmd->mode;
}
-#ifdef WITH_MOD_DECIMATE
-static DerivedMesh *applyModifier(ModifierData *md, Object *UNUSED(ob),
+static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
+{
+ DecimateModifierData *dmd = (DecimateModifierData *) md;
+ CustomDataMask dataMask = 0;
+
+ /* ask for vertexgroups if we need them */
+ if (dmd->defgrp_name[0]) dataMask |= CD_MASK_MDEFORMVERT;
+
+ return dataMask;
+}
+
+static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
DerivedMesh *derivedData,
ModifierApplyFlag UNUSED(flag))
{
DecimateModifierData *dmd = (DecimateModifierData *) md;
DerivedMesh *dm = derivedData, *result = NULL;
- MVert *mvert;
- MFace *mface;
- LOD_Decimation_Info lod;
- int totvert, totface;
- int a, numTris;
-
- DM_ensure_tessface(dm); /* BMESH - UNTIL MODIFIER IS UPDATED FOR MPoly */
-
- mvert = dm->getVertArray(dm);
- mface = dm->getTessFaceArray(dm);
- totvert = dm->getNumVerts(dm);
- totface = dm->getNumTessFaces(dm);
-
- numTris = 0;
- for (a = 0; a < totface; a++) {
- MFace *mf = &mface[a];
- numTris++;
- if (mf->v4) numTris++;
- }
+ BMesh *bm;
- if (numTris < 3) {
- modifier_setError(md, "%s", TIP_("Modifier requires more than 3 input faces (triangles)."));
- dm = CDDM_copy(dm);
- return dm;
- }
+ float *vweights = NULL;
- lod.vertex_buffer = MEM_mallocN(3 * sizeof(float) * totvert, "vertices");
- lod.vertex_normal_buffer = MEM_mallocN(3 * sizeof(float) * totvert, "normals");
- lod.triangle_index_buffer = MEM_mallocN(3 * sizeof(int) * numTris, "trias");
- lod.vertex_num = totvert;
- lod.face_num = numTris;
+#ifdef USE_TIMEIT
+ TIMEIT_START(decim);
+#endif
- for (a = 0; a < totvert; a++) {
- MVert *mv = &mvert[a];
- float *vbCo = &lod.vertex_buffer[a * 3];
- float *vbNo = &lod.vertex_normal_buffer[a * 3];
+ /* set up front so we dont show invalid info in the UI */
+ dmd->face_count = dm->getNumPolys(dm);
- copy_v3_v3(vbCo, mv->co);
- normal_short_to_float_v3(vbNo, mv->no);
+ switch (dmd->mode) {
+ case MOD_DECIM_MODE_COLLAPSE:
+ if (dmd->percent == 1.0f) {
+ return dm;
+ }
+ break;
+ case MOD_DECIM_MODE_UNSUBDIV:
+ if (dmd->iter == 0) {
+ return dm;
+ }
+ break;
+ case MOD_DECIM_MODE_DISSOLVE:
+ if (dmd->angle == 0.0f) {
+ return dm;
+ }
+ break;
}
- numTris = 0;
- for (a = 0; a < totface; a++) {
- MFace *mf = &mface[a];
- int *tri = &lod.triangle_index_buffer[3 * numTris++];
- tri[0] = mf->v1;
- tri[1] = mf->v2;
- tri[2] = mf->v3;
-
- if (mf->v4) {
- tri = &lod.triangle_index_buffer[3 * numTris++];
- tri[0] = mf->v1;
- tri[1] = mf->v3;
- tri[2] = mf->v4;
- }
+ if (dmd->face_count <= 3) {
+ modifier_setError(md, "Modifier requires more than 3 input faces");
+ return dm;
}
- dmd->faceCount = 0;
- if (LOD_LoadMesh(&lod) ) {
- if (LOD_PreprocessMesh(&lod) ) {
- /* we assume the decim_faces tells how much to reduce */
+ if (dmd->mode == MOD_DECIM_MODE_COLLAPSE) {
+ if (dmd->defgrp_name[0]) {
+ MDeformVert *dvert;
+ int defgrp_index;
- while (lod.face_num > numTris * dmd->percent) {
- if (LOD_CollapseEdge(&lod) == 0) break;
- }
+ modifier_get_vgroup(ob, dm, dmd->defgrp_name, &dvert, &defgrp_index);
- if (lod.vertex_num > 2) {
- result = CDDM_new(lod.vertex_num, 0, lod.face_num, 0, 0);
- dmd->faceCount = lod.face_num;
- }
- else
- result = CDDM_new(lod.vertex_num, 0, 0, 0, 0);
-
- mvert = CDDM_get_verts(result);
- for (a = 0; a < lod.vertex_num; a++) {
- MVert *mv = &mvert[a];
- float *vbCo = &lod.vertex_buffer[a * 3];
-
- copy_v3_v3(mv->co, vbCo);
- }
+ if (dvert) {
+ const unsigned int vert_tot = dm->getNumVerts(dm);
+ unsigned int i;
+
+ vweights = MEM_mallocN(vert_tot * sizeof(float), __func__);
- if (lod.vertex_num > 2) {
- mface = CDDM_get_tessfaces(result);
- for (a = 0; a < lod.face_num; a++) {
- MFace *mf = &mface[a];
- int *tri = &lod.triangle_index_buffer[a * 3];
- mf->v1 = tri[0];
- mf->v2 = tri[1];
- mf->v3 = tri[2];
- test_index_face(mf, NULL, 0, 3);
+ if (dmd->flag & MOD_DECIM_FLAG_INVERT_VGROUP) {
+ for (i = 0; i < vert_tot; i++) {
+ vweights[i] = 1.0f - defvert_find_weight(&dvert[i], defgrp_index);
+ }
+ }
+ else {
+ for (i = 0; i < vert_tot; i++) {
+ vweights[i] = defvert_find_weight(&dvert[i], defgrp_index);
+ }
}
}
+ }
+ }
+
+ bm = DM_to_bmesh(dm);
- CDDM_calc_edges_tessface(result);
+ switch (dmd->mode) {
+ case MOD_DECIM_MODE_COLLAPSE:
+ {
+ const int do_triangulate = (dmd->flag & MOD_DECIM_FLAG_TRIANGULATE) != 0;
+ BM_mesh_decimate_collapse(bm, dmd->percent, vweights, do_triangulate);
+ break;
+ }
+ case MOD_DECIM_MODE_UNSUBDIV:
+ {
+ BM_mesh_decimate_unsubdivide(bm, dmd->iter);
+ break;
+ }
+ case MOD_DECIM_MODE_DISSOLVE:
+ {
+ const int do_dissolve_boundaries = (dmd->flag & MOD_DECIM_FLAG_ALL_BOUNDARY_VERTS) != 0;
+ BM_mesh_decimate_dissolve(bm, dmd->angle, do_dissolve_boundaries);
+ break;
}
- else
- modifier_setError(md, "%s", TIP_("Out of memory."));
+ }
- LOD_FreeDecimationData(&lod);
+ if (vweights) {
+ MEM_freeN(vweights);
}
- else
- modifier_setError(md, "%s", TIP_("Non-manifold mesh as input."));
- MEM_freeN(lod.vertex_buffer);
- MEM_freeN(lod.vertex_normal_buffer);
- MEM_freeN(lod.triangle_index_buffer);
+ /* update for display only */
+ dmd->face_count = bm->totface;
+ result = CDDM_from_bmesh(bm, FALSE);
+ BM_mesh_free(bm);
- if (result) {
- CDDM_tessfaces_to_faces(result); /*builds ngon faces from tess (mface) faces*/
+#ifdef USE_TIMEIT
+ TIMEIT_END(decim);
+#endif
- return result;
- }
- else {
- return dm;
- }
-}
-#else // WITH_MOD_DECIMATE
-static DerivedMesh *applyModifier(ModifierData *UNUSED(md), Object *UNUSED(ob),
- DerivedMesh *derivedData,
- ModifierApplyFlag UNUSED(flag))
-{
- return derivedData;
+ return result;
}
-#endif // WITH_MOD_DECIMATE
ModifierTypeInfo modifierType_Decimate = {
/* name */ "Decimate",
/* structName */ "DecimateModifierData",
/* structSize */ sizeof(DecimateModifierData),
/* type */ eModifierTypeType_Nonconstructive,
- /* flags */ eModifierTypeFlag_AcceptsMesh,
+ /* flags */ eModifierTypeFlag_AcceptsMesh |
+ eModifierTypeFlag_AcceptsCVs,
/* copyData */ copyData,
/* deformVerts */ NULL,
/* deformMatrices */ NULL,
@@ -215,7 +210,7 @@ ModifierTypeInfo modifierType_Decimate = {
/* applyModifier */ applyModifier,
/* applyModifierEM */ NULL,
/* initData */ initData,
- /* requiredDataMask */ NULL,
+ /* requiredDataMask */ requiredDataMask,
/* freeData */ NULL,
/* isDisabled */ NULL,
/* updateDepgraph */ NULL,
diff --git a/source/blender/modifiers/intern/MOD_dynamicpaint.c b/source/blender/modifiers/intern/MOD_dynamicpaint.c
index 7d7bfade9b7..80866a7c435 100644
--- a/source/blender/modifiers/intern/MOD_dynamicpaint.c
+++ b/source/blender/modifiers/intern/MOD_dynamicpaint.c
@@ -170,10 +170,10 @@ ModifierTypeInfo modifierType_DynamicPaint = {
/* structSize */ sizeof(DynamicPaintModifierData),
/* type */ eModifierTypeType_Constructive,
/* flags */ eModifierTypeFlag_AcceptsMesh |
-/* eModifierTypeFlag_SupportsMapping |*/
- eModifierTypeFlag_UsesPointCache |
- eModifierTypeFlag_Single |
- eModifierTypeFlag_UsesPreview,
+/* eModifierTypeFlag_SupportsMapping |*/
+ eModifierTypeFlag_UsesPointCache |
+ eModifierTypeFlag_Single |
+ eModifierTypeFlag_UsesPreview,
/* copyData */ copyData,
/* deformVerts */ NULL,
diff --git a/source/blender/modifiers/intern/MOD_edgesplit.c b/source/blender/modifiers/intern/MOD_edgesplit.c
index b1c3459bf51..21717d07fef 100644
--- a/source/blender/modifiers/intern/MOD_edgesplit.c
+++ b/source/blender/modifiers/intern/MOD_edgesplit.c
@@ -43,9 +43,10 @@
#include "BKE_cdderivedmesh.h"
#include "BKE_modifier.h"
-#include "BKE_tessmesh.h"
#include "BKE_mesh.h"
+#include "bmesh.h"
+
#include "DNA_object_types.h"
/* EdgeSplit */
@@ -61,15 +62,12 @@ static DerivedMesh *doEdgeSplit(DerivedMesh *dm, EdgeSplitModifierData *emd, Obj
{
DerivedMesh *result;
BMesh *bm;
- BMEditMesh *em;
BMIter iter;
BMEdge *e;
float threshold = cosf((emd->split_angle + 0.00001f) * (float)M_PI / 180.0f);
- em = DM_to_editbmesh(dm, NULL, FALSE);
- bm = em->bm;
+ bm = DM_to_bmesh(dm);
- BM_mesh_normals_update(bm, FALSE);
BMO_push(bm, NULL);
if (emd->flags & MOD_EDGESPLIT_FROMANGLE) {
@@ -110,10 +108,8 @@ static DerivedMesh *doEdgeSplit(DerivedMesh *dm, EdgeSplitModifierData *emd, Obj
/* BM_mesh_validate(bm); */ /* for troubleshooting */
- BLI_assert(em->looptris == NULL);
- result = CDDM_from_BMEditMesh(em, NULL, TRUE, FALSE);
- BMEdit_Free(em);
- MEM_freeN(em);
+ result = CDDM_from_bmesh(bm, TRUE);
+ BM_mesh_free(bm);
return result;
}
diff --git a/source/blender/modifiers/intern/MOD_explode.c b/source/blender/modifiers/intern/MOD_explode.c
index b9593353288..92ad6faa3ce 100644
--- a/source/blender/modifiers/intern/MOD_explode.c
+++ b/source/blender/modifiers/intern/MOD_explode.c
@@ -206,11 +206,11 @@ static MFace *get_dface(DerivedMesh *dm, DerivedMesh *split, int cur, int i, MFa
}
#define SET_VERTS(a, b, c, d) { \
- v[0] = mf->v##a; uv[0] = a - 1; \
- v[1] = mf->v##b; uv[1] = b - 1; \
- v[2] = mf->v##c; uv[2] = c - 1; \
- v[3] = mf->v##d; uv[3] = d - 1; \
- } (void)0
+ v[0] = mf->v##a; uv[0] = a - 1; \
+ v[1] = mf->v##b; uv[1] = b - 1; \
+ v[2] = mf->v##c; uv[2] = c - 1; \
+ v[3] = mf->v##d; uv[3] = d - 1; \
+ } (void)0
#define GET_ES(v1, v2) edgecut_get(eh, v1, v2)
#define INT_UV(uvf, c0, c1) interp_v2_v2v2(uvf, mf->uv[c0], mf->uv[c1], 0.5f)
@@ -669,8 +669,7 @@ static DerivedMesh *cutEdges(ExplodeModifierData *emd, DerivedMesh *dm)
mv = CDDM_get_vert(splitdm, ed_v1);
- add_v3_v3(dupve->co, mv->co);
- mul_v3_fl(dupve->co, 0.5f);
+ mid_v3_v3v3(dupve->co, dupve->co, mv->co);
}
BLI_edgehashIterator_free(ehi);
@@ -813,7 +812,7 @@ static DerivedMesh *explodeMesh(ExplodeModifierData *emd,
sim.psys = psmd->psys;
sim.psmd = psmd;
- /* timestep= psys_get_timestep(&sim); */
+ /* timestep = psys_get_timestep(&sim); */
cfra = BKE_scene_frame_get(scene);
@@ -861,7 +860,7 @@ static DerivedMesh *explodeMesh(ExplodeModifierData *emd,
/* the final duplicated vertices */
explode = CDDM_from_template(dm, totdup, 0, totface - delface, 0, 0);
mtface = CustomData_get_layer_named(&explode->faceData, CD_MTFACE, emd->uvname);
- /*dupvert= CDDM_get_verts(explode);*/
+ /*dupvert = CDDM_get_verts(explode);*/
/* getting back to object space */
invert_m4_m4(imat, ob->obmat);
@@ -1039,26 +1038,26 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
ModifierTypeInfo modifierType_Explode = {
- /* name */ "Explode",
- /* structName */ "ExplodeModifierData",
- /* structSize */ sizeof(ExplodeModifierData),
- /* type */ eModifierTypeType_Constructive,
- /* flags */ eModifierTypeFlag_AcceptsMesh,
- /* copyData */ copyData,
- /* deformVerts */ NULL,
- /* deformMatrices */ NULL,
- /* deformVertsEM */ NULL,
- /* deformMatricesEM */ NULL,
- /* applyModifier */ applyModifier,
- /* applyModifierEM */ NULL,
- /* initData */ initData,
- /* requiredDataMask */ requiredDataMask,
- /* freeData */ freeData,
- /* isDisabled */ NULL,
- /* updateDepgraph */ NULL,
- /* dependsOnTime */ dependsOnTime,
- /* dependsOnNormals */ NULL,
+ /* name */ "Explode",
+ /* structName */ "ExplodeModifierData",
+ /* structSize */ sizeof(ExplodeModifierData),
+ /* type */ eModifierTypeType_Constructive,
+ /* flags */ eModifierTypeFlag_AcceptsMesh,
+ /* copyData */ copyData,
+ /* deformVerts */ NULL,
+ /* deformMatrices */ NULL,
+ /* deformVertsEM */ NULL,
+ /* deformMatricesEM */ NULL,
+ /* applyModifier */ applyModifier,
+ /* applyModifierEM */ NULL,
+ /* initData */ initData,
+ /* requiredDataMask */ requiredDataMask,
+ /* freeData */ freeData,
+ /* isDisabled */ NULL,
+ /* updateDepgraph */ NULL,
+ /* dependsOnTime */ dependsOnTime,
+ /* dependsOnNormals */ NULL,
/* foreachObjectLink */ NULL,
- /* foreachIDLink */ NULL,
- /* foreachTexLink */ NULL,
+ /* foreachIDLink */ NULL,
+ /* foreachTexLink */ NULL,
};
diff --git a/source/blender/modifiers/intern/MOD_fluidsim_util.c b/source/blender/modifiers/intern/MOD_fluidsim_util.c
index 9acac6d00cd..47523286229 100644
--- a/source/blender/modifiers/intern/MOD_fluidsim_util.c
+++ b/source/blender/modifiers/intern/MOD_fluidsim_util.c
@@ -529,7 +529,7 @@ DerivedMesh *fluidsimModifier_do(FluidsimModifierData *fluidmd, Scene *scene,
fss = fluidmd->fss;
/* timescale not supported yet
- * clmd->sim_parms->timescale= timescale; */
+ * clmd->sim_parms->timescale = timescale; */
/* support reversing of baked fluid frames here */
if ((fss->flag & OB_FLUIDSIM_REVERSE) && (fss->lastgoodframe >= 0)) {
diff --git a/source/blender/modifiers/intern/MOD_laplaciansmooth.c b/source/blender/modifiers/intern/MOD_laplaciansmooth.c
new file mode 100644
index 00000000000..6f6589d4d14
--- /dev/null
+++ b/source/blender/modifiers/intern/MOD_laplaciansmooth.c
@@ -0,0 +1,703 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2005 by the Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Alexander Pinzon
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ *
+ */
+
+/** \file blender/modifiers/intern/MOD_laplaciansmooth.c
+ * \ingroup modifiers
+ */
+
+
+#include "DNA_meshdata_types.h"
+#include "DNA_object_types.h"
+
+#include "BLI_math.h"
+#include "BLI_utildefines.h"
+#include "BLI_string.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "BKE_cdderivedmesh.h"
+#include "BKE_deform.h"
+#include "BKE_displist.h"
+#include "BKE_mesh.h"
+#include "BKE_modifier.h"
+#include "BKE_object.h"
+#include "BKE_particle.h"
+#include "BKE_tessmesh.h"
+
+#include "MOD_modifiertypes.h"
+#include "MOD_util.h"
+
+#include "ONL_opennl.h"
+
+#define MOD_LAPLACIANSMOOTH_MAX_EDGE_PERCENTAGE 1.8f
+#define MOD_LAPLACIANSMOOTH_MIN_EDGE_PERCENTAGE 0.02f
+
+struct BLaplacianSystem {
+ float *eweights; /* Length weights per Edge */
+ float (*fweights)[3]; /* Cotangent weights per face */
+ float *ring_areas; /* Total area per ring*/
+ float *vlengths; /* Total sum of lengths(edges) per vertice*/
+ float *vweights; /* Total sum of weights per vertice*/
+ int numEdges; /* Number of edges*/
+ int numFaces; /* Number of faces*/
+ int numVerts; /* Number of verts*/
+ short *numNeFa; /* Number of neighboors faces around vertice*/
+ short *numNeEd; /* Number of neighboors Edges around vertice*/
+ short *zerola; /* Is zero area or length*/
+
+ /* Pointers to data*/
+ float (*vertexCos)[3];
+ MFace *mfaces;
+ MEdge *medges;
+ NLContext *context;
+
+ /*Data*/
+ float min_area;
+ float vert_centroid[3];
+};
+typedef struct BLaplacianSystem LaplacianSystem;
+
+static CustomDataMask required_data_mask(Object *UNUSED(ob), ModifierData *md);
+static int is_disabled(ModifierData *md, int UNUSED(useRenderParams));
+static float compute_volume(float (*vertexCos)[3], MFace *mfaces, int numFaces);
+static float cotan_weight(float *v1, float *v2, float *v3);
+static LaplacianSystem *init_laplacian_system(int a_numEdges, int a_numFaces, int a_numVerts);
+static void copy_data(ModifierData *md, ModifierData *target);
+static void delete_laplacian_system(LaplacianSystem *sys);
+static void delete_void_pointer(void *data);
+static void fill_laplacian_matrix(LaplacianSystem *sys);
+static void init_data(ModifierData *md);
+static void init_laplacian_matrix(LaplacianSystem *sys);
+static void memset_laplacian_system(LaplacianSystem *sys, int val);
+static void volume_preservation(LaplacianSystem *sys, float vini, float vend, short flag);
+static void validate_solution(LaplacianSystem *sys, short flag);
+
+static void delete_void_pointer(void *data)
+{
+ if (data) {
+ MEM_freeN(data);
+ data = NULL;
+ }
+}
+
+static void delete_laplacian_system(LaplacianSystem *sys)
+{
+ delete_void_pointer(sys->eweights);
+ delete_void_pointer(sys->fweights);
+ delete_void_pointer(sys->numNeEd);
+ delete_void_pointer(sys->numNeFa);
+ delete_void_pointer(sys->ring_areas);
+ delete_void_pointer(sys->vlengths);
+ delete_void_pointer(sys->vweights);
+ delete_void_pointer(sys->zerola);
+ if (sys->context) {
+ nlDeleteContext(sys->context);
+ }
+ sys->vertexCos = NULL;
+ sys->mfaces = NULL;
+ sys->medges = NULL;
+ MEM_freeN(sys);
+}
+
+static void memset_laplacian_system(LaplacianSystem *sys, int val)
+{
+ memset(sys->eweights, val, sizeof(float) * sys->numEdges);
+ memset(sys->fweights, val, sizeof(float) * sys->numFaces * 3);
+ memset(sys->numNeEd, val, sizeof(short) * sys->numVerts);
+ memset(sys->numNeFa, val, sizeof(short) * sys->numVerts);
+ memset(sys->ring_areas, val, sizeof(float) * sys->numVerts);
+ memset(sys->vlengths, val, sizeof(float) * sys->numVerts);
+ memset(sys->vweights, val, sizeof(float) * sys->numVerts);
+ memset(sys->zerola, val, sizeof(short) * sys->numVerts);
+}
+
+static LaplacianSystem *init_laplacian_system(int a_numEdges, int a_numFaces, int a_numVerts)
+{
+ LaplacianSystem *sys;
+ sys = MEM_callocN(sizeof(LaplacianSystem), "ModLaplSmoothSystem");
+ sys->numEdges = a_numEdges;
+ sys->numFaces = a_numFaces;
+ sys->numVerts = a_numVerts;
+
+ sys->eweights = MEM_callocN(sizeof(float) * sys->numEdges, "ModLaplSmoothEWeight");
+ if (!sys->eweights) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->fweights = MEM_callocN(sizeof(float) * 3 * sys->numFaces, "ModLaplSmoothFWeight");
+ if (!sys->fweights) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->numNeEd = MEM_callocN(sizeof(short) * sys->numVerts, "ModLaplSmoothNumNeEd");
+ if (!sys->numNeEd) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->numNeFa = MEM_callocN(sizeof(short) * sys->numVerts, "ModLaplSmoothNumNeFa");
+ if (!sys->numNeFa) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->ring_areas = MEM_callocN(sizeof(float) * sys->numVerts, "ModLaplSmoothRingAreas");
+ if (!sys->ring_areas) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->vlengths = MEM_callocN(sizeof(float) * sys->numVerts, "ModLaplSmoothVlengths");
+ if (!sys->vlengths) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->vweights = MEM_callocN(sizeof(float) * sys->numVerts, "ModLaplSmoothVweights");
+ if (!sys->vweights) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ sys->zerola = MEM_callocN(sizeof(short) * sys->numVerts, "ModLaplSmoothZeloa");
+ if (!sys->zerola) {
+ delete_laplacian_system(sys);
+ return NULL;
+ }
+
+ return sys;
+}
+
+static void init_data(ModifierData *md)
+{
+ LaplacianSmoothModifierData *smd = (LaplacianSmoothModifierData *) md;
+ smd->lambda = 0.00001f;
+ smd->lambda_border = 0.00005f;
+ smd->repeat = 1;
+ smd->flag = MOD_LAPLACIANSMOOTH_X | MOD_LAPLACIANSMOOTH_Y | MOD_LAPLACIANSMOOTH_Z | MOD_LAPLACIANSMOOTH_VOLUME_PRESERVATION;
+ smd->defgrp_name[0] = '\0';
+}
+
+static void copy_data(ModifierData *md, ModifierData *target)
+{
+ LaplacianSmoothModifierData *smd = (LaplacianSmoothModifierData *) md;
+ LaplacianSmoothModifierData *tsmd = (LaplacianSmoothModifierData *) target;
+
+ tsmd->lambda = smd->lambda;
+ tsmd->lambda_border = smd->lambda_border;
+ tsmd->repeat = smd->repeat;
+ tsmd->flag = smd->flag;
+ BLI_strncpy(tsmd->defgrp_name, smd->defgrp_name, sizeof(tsmd->defgrp_name));
+}
+
+static int is_disabled(ModifierData *md, int UNUSED(useRenderParams))
+{
+ LaplacianSmoothModifierData *smd = (LaplacianSmoothModifierData *) md;
+ short flag;
+
+ flag = smd->flag & (MOD_LAPLACIANSMOOTH_X | MOD_LAPLACIANSMOOTH_Y | MOD_LAPLACIANSMOOTH_Z);
+
+ /* disable if modifier is off for X, Y and Z or if factor is 0 */
+ if (flag == 0) return 1;
+
+ return 0;
+}
+
+static CustomDataMask required_data_mask(Object *UNUSED(ob), ModifierData *md)
+{
+ LaplacianSmoothModifierData *smd = (LaplacianSmoothModifierData *)md;
+ CustomDataMask dataMask = 0;
+
+ /* ask for vertexgroups if we need them */
+ if (smd->defgrp_name[0]) dataMask |= CD_MASK_MDEFORMVERT;
+
+ return dataMask;
+}
+
+static float cotan_weight(float *v1, float *v2, float *v3)
+{
+ float a[3], b[3], c[3], clen;
+
+ sub_v3_v3v3(a, v2, v1);
+ sub_v3_v3v3(b, v3, v1);
+ cross_v3_v3v3(c, a, b);
+
+ clen = len_v3(c);
+
+ if (clen == 0.0f)
+ return 0.0f;
+
+ return dot_v3v3(a, b) / clen;
+}
+
+static float compute_volume(float (*vertexCos)[3], MFace *mfaces, int numFaces)
+{
+ float vol = 0.0f;
+ float x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4;
+ int i;
+ float *vf[4];
+ for (i = 0; i < numFaces; i++) {
+ vf[0] = vertexCos[mfaces[i].v1];
+ vf[1] = vertexCos[mfaces[i].v2];
+ vf[2] = vertexCos[mfaces[i].v3];
+
+ x1 = vf[0][0];
+ y1 = vf[0][1];
+ z1 = vf[0][2];
+
+ x2 = vf[1][0];
+ y2 = vf[1][1];
+ z2 = vf[1][2];
+
+ x3 = vf[2][0];
+ y3 = vf[2][1];
+ z3 = vf[2][2];
+
+
+ vol += (1.0f / 6.0f) * (x2 * y3 * z1 + x3 * y1 * z2 - x1 * y3 * z2 - x2 * y1 * z3 + x1 * y2 * z3 - x3 * y2 * z1);
+ if ((&mfaces[i])->v4) {
+ vf[3] = vertexCos[mfaces[i].v4];
+ x4 = vf[3][0];
+ y4 = vf[3][1];
+ z4 = vf[3][2];
+ vol += (1.0f / 6.0f) * (x1 * y3 * z4 - x1 * y4 * z3 - x3 * y1 * z4 + x3 * z1 * y4 + y1 * x4 * z3 - x4 * y3 * z1);
+ }
+ }
+ return fabsf(vol);
+}
+
+static void volume_preservation(LaplacianSystem *sys, float vini, float vend, short flag)
+{
+ float beta;
+ int i;
+
+ if (vend != 0.0f) {
+ beta = pow(vini / vend, 1.0f / 3.0f);
+ for (i = 0; i < sys->numVerts; i++) {
+ if (flag & MOD_LAPLACIANSMOOTH_X) {
+ sys->vertexCos[i][0] = (sys->vertexCos[i][0] - sys->vert_centroid[0]) * beta + sys->vert_centroid[0];
+ }
+ if (flag & MOD_LAPLACIANSMOOTH_Y) {
+ sys->vertexCos[i][1] = (sys->vertexCos[i][1] - sys->vert_centroid[1]) * beta + sys->vert_centroid[1];
+ }
+ if (flag & MOD_LAPLACIANSMOOTH_Z) {
+ sys->vertexCos[i][2] = (sys->vertexCos[i][2] - sys->vert_centroid[2]) * beta + sys->vert_centroid[2];
+ }
+
+ }
+ }
+}
+
+static void init_laplacian_matrix(LaplacianSystem *sys)
+{
+ float *v1, *v2, *v3, *v4;
+ float w1, w2, w3, w4;
+ float areaf;
+ int i, j;
+ unsigned int idv1, idv2, idv3, idv4, idv[4];
+ int has_4_vert;
+ for (i = 0; i < sys->numEdges; i++) {
+ idv1 = sys->medges[i].v1;
+ idv2 = sys->medges[i].v2;
+
+ v1 = sys->vertexCos[idv1];
+ v2 = sys->vertexCos[idv2];
+
+ sys->numNeEd[idv1] = sys->numNeEd[idv1] + 1;
+ sys->numNeEd[idv2] = sys->numNeEd[idv2] + 1;
+ w1 = len_v3v3(v1, v2);
+ if (w1 < sys->min_area) {
+ sys->zerola[idv1] = 1;
+ sys->zerola[idv2] = 1;
+ }
+ else {
+ w1 = 1.0f / w1;
+ }
+
+ sys->eweights[i] = w1;
+ }
+ for (i = 0; i < sys->numFaces; i++) {
+ has_4_vert = ((&sys->mfaces[i])->v4) ? 1 : 0;
+
+ idv1 = sys->mfaces[i].v1;
+ idv2 = sys->mfaces[i].v2;
+ idv3 = sys->mfaces[i].v3;
+ idv4 = has_4_vert ? sys->mfaces[i].v4 : 0;
+
+ sys->numNeFa[idv1] += 1;
+ sys->numNeFa[idv2] += 1;
+ sys->numNeFa[idv3] += 1;
+ if (has_4_vert) sys->numNeFa[idv4] += 1;
+
+ v1 = sys->vertexCos[idv1];
+ v2 = sys->vertexCos[idv2];
+ v3 = sys->vertexCos[idv3];
+ v4 = has_4_vert ? sys->vertexCos[idv4] : 0;
+
+ if (has_4_vert) {
+ areaf = area_quad_v3(v1, v2, v3, sys->vertexCos[sys->mfaces[i].v4]);
+ }
+ else {
+ areaf = area_tri_v3(v1, v2, v3);
+ }
+ if (fabsf(areaf) < sys->min_area) {
+ sys->zerola[idv1] = 1;
+ sys->zerola[idv2] = 1;
+ sys->zerola[idv3] = 1;
+ if (has_4_vert) sys->zerola[idv4] = 1;
+ }
+
+ sys->ring_areas[idv1] += areaf;
+ sys->ring_areas[idv2] += areaf;
+ sys->ring_areas[idv3] += areaf;
+ if (has_4_vert) sys->ring_areas[idv4] += areaf;
+
+ if (has_4_vert) {
+
+ idv[0] = idv1;
+ idv[1] = idv2;
+ idv[2] = idv3;
+ idv[3] = idv4;
+
+ for (j = 0; j < 4; j++) {
+ idv1 = idv[j];
+ idv2 = idv[(j + 1) % 4];
+ idv3 = idv[(j + 2) % 4];
+ idv4 = idv[(j + 3) % 4];
+
+ v1 = sys->vertexCos[idv1];
+ v2 = sys->vertexCos[idv2];
+ v3 = sys->vertexCos[idv3];
+ v4 = sys->vertexCos[idv4];
+
+ w2 = cotan_weight(v4, v1, v2) + cotan_weight(v3, v1, v2);
+ w3 = cotan_weight(v2, v3, v1) + cotan_weight(v4, v1, v3);
+ w4 = cotan_weight(v2, v4, v1) + cotan_weight(v3, v4, v1);
+
+ sys->vweights[idv1] += (w2 + w3 + w4) / 4.0f;
+ }
+ }
+ else {
+ w1 = cotan_weight(v1, v2, v3);
+ w2 = cotan_weight(v2, v3, v1);
+ w3 = cotan_weight(v3, v1, v2);
+
+ sys->fweights[i][0] = sys->fweights[i][0] + w1;
+ sys->fweights[i][1] = sys->fweights[i][1] + w2;
+ sys->fweights[i][2] = sys->fweights[i][2] + w3;
+
+ sys->vweights[idv1] = sys->vweights[idv1] + w2 + w3;
+ sys->vweights[idv2] = sys->vweights[idv2] + w1 + w3;
+ sys->vweights[idv3] = sys->vweights[idv3] + w1 + w2;
+ }
+ }
+ for (i = 0; i < sys->numEdges; i++) {
+ idv1 = sys->medges[i].v1;
+ idv2 = sys->medges[i].v2;
+ /* if is boundary, apply scale-dependent umbrella operator only with neighboors in boundary */
+ if (sys->numNeEd[idv1] != sys->numNeFa[idv1] && sys->numNeEd[idv2] != sys->numNeFa[idv2]) {
+ sys->vlengths[idv1] += sys->eweights[i];
+ sys->vlengths[idv2] += sys->eweights[i];
+ }
+ }
+
+}
+
+static void fill_laplacian_matrix(LaplacianSystem *sys)
+{
+ float *v1, *v2, *v3, *v4;
+ float w2, w3, w4;
+ int i, j;
+ int has_4_vert;
+ unsigned int idv1, idv2, idv3, idv4, idv[4];
+
+ for (i = 0; i < sys->numFaces; i++) {
+ idv1 = sys->mfaces[i].v1;
+ idv2 = sys->mfaces[i].v2;
+ idv3 = sys->mfaces[i].v3;
+ has_4_vert = ((&sys->mfaces[i])->v4) ? 1 : 0;
+
+ if (has_4_vert) {
+ idv[0] = sys->mfaces[i].v1;
+ idv[1] = sys->mfaces[i].v2;
+ idv[2] = sys->mfaces[i].v3;
+ idv[3] = sys->mfaces[i].v4;
+ for (j = 0; j < 4; j++) {
+ idv1 = idv[j];
+ idv2 = idv[(j + 1) % 4];
+ idv3 = idv[(j + 2) % 4];
+ idv4 = idv[(j + 3) % 4];
+
+ v1 = sys->vertexCos[idv1];
+ v2 = sys->vertexCos[idv2];
+ v3 = sys->vertexCos[idv3];
+ v4 = sys->vertexCos[idv4];
+
+ w2 = cotan_weight(v4, v1, v2) + cotan_weight(v3, v1, v2);
+ w3 = cotan_weight(v2, v3, v1) + cotan_weight(v4, v1, v3);
+ w4 = cotan_weight(v2, v4, v1) + cotan_weight(v3, v4, v1);
+
+ w2 = w2 / 4.0f;
+ w3 = w3 / 4.0f;
+ w4 = w4 / 4.0f;
+
+ if (sys->numNeEd[idv1] == sys->numNeFa[idv1] && sys->zerola[idv1] == 0) {
+ nlMatrixAdd(idv1, idv2, w2 * sys->vweights[idv1]);
+ nlMatrixAdd(idv1, idv3, w3 * sys->vweights[idv1]);
+ nlMatrixAdd(idv1, idv4, w4 * sys->vweights[idv1]);
+ }
+ }
+ }
+ else {
+ /* Is ring if number of faces == number of edges around vertice*/
+ if (sys->numNeEd[idv1] == sys->numNeFa[idv1] && sys->zerola[idv1] == 0) {
+ nlMatrixAdd(idv1, idv2, sys->fweights[i][2] * sys->vweights[idv1]);
+ nlMatrixAdd(idv1, idv3, sys->fweights[i][1] * sys->vweights[idv1]);
+ }
+ if (sys->numNeEd[idv2] == sys->numNeFa[idv2] && sys->zerola[idv2] == 0) {
+ nlMatrixAdd(idv2, idv1, sys->fweights[i][2] * sys->vweights[idv2]);
+ nlMatrixAdd(idv2, idv3, sys->fweights[i][0] * sys->vweights[idv2]);
+ }
+ if (sys->numNeEd[idv3] == sys->numNeFa[idv3] && sys->zerola[idv3] == 0) {
+ nlMatrixAdd(idv3, idv1, sys->fweights[i][1] * sys->vweights[idv3]);
+ nlMatrixAdd(idv3, idv2, sys->fweights[i][0] * sys->vweights[idv3]);
+ }
+ }
+ }
+
+ for (i = 0; i < sys->numEdges; i++) {
+ idv1 = sys->medges[i].v1;
+ idv2 = sys->medges[i].v2;
+ /* Is boundary */
+ if (sys->numNeEd[idv1] != sys->numNeFa[idv1] &&
+ sys->numNeEd[idv2] != sys->numNeFa[idv2] &&
+ sys->zerola[idv1] == 0 &&
+ sys->zerola[idv2] == 0)
+ {
+ nlMatrixAdd(idv1, idv2, sys->eweights[i] * sys->vlengths[idv1]);
+ nlMatrixAdd(idv2, idv1, sys->eweights[i] * sys->vlengths[idv2]);
+ }
+ }
+}
+
+static void validate_solution(LaplacianSystem *sys, short flag)
+{
+ int i, idv1, idv2;
+ float leni, lene;
+ float vini, vend;
+ float *vi1, *vi2, ve1[3], ve2[3];
+ if (flag & MOD_LAPLACIANSMOOTH_VOLUME_PRESERVATION) {
+ vini = compute_volume(sys->vertexCos, sys->mfaces, sys->numFaces);
+ }
+ for (i = 0; i < sys->numEdges; i++) {
+ idv1 = sys->medges[i].v1;
+ idv2 = sys->medges[i].v2;
+ vi1 = sys->vertexCos[idv1];
+ vi2 = sys->vertexCos[idv2];
+ ve1[0] = nlGetVariable(0, idv1);
+ ve1[1] = nlGetVariable(1, idv1);
+ ve1[2] = nlGetVariable(2, idv1);
+ ve2[0] = nlGetVariable(0, idv2);
+ ve2[1] = nlGetVariable(1, idv2);
+ ve2[2] = nlGetVariable(2, idv2);
+ leni = len_v3v3(vi1, vi2);
+ lene = len_v3v3(ve1, ve2);
+ if (lene > leni * MOD_LAPLACIANSMOOTH_MAX_EDGE_PERCENTAGE || lene < leni * MOD_LAPLACIANSMOOTH_MIN_EDGE_PERCENTAGE) {
+ sys->zerola[idv1] = 1;
+ sys->zerola[idv2] = 1;
+ }
+ }
+ for (i = 0; i < sys->numVerts; i++) {
+ if (sys->zerola[i] == 0) {
+ if (flag & MOD_LAPLACIANSMOOTH_X) {
+ sys->vertexCos[i][0] = nlGetVariable(0, i);
+ }
+ if (flag & MOD_LAPLACIANSMOOTH_Y) {
+ sys->vertexCos[i][1] = nlGetVariable(1, i);
+ }
+ if (flag & MOD_LAPLACIANSMOOTH_Z) {
+ sys->vertexCos[i][2] = nlGetVariable(2, i);
+ }
+ }
+ }
+ if (flag & MOD_LAPLACIANSMOOTH_VOLUME_PRESERVATION) {
+ vend = compute_volume(sys->vertexCos, sys->mfaces, sys->numFaces);
+ volume_preservation(sys, vini, vend, flag);
+ }
+}
+
+static void laplaciansmoothModifier_do(
+ LaplacianSmoothModifierData *smd, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
+{
+ LaplacianSystem *sys;
+ MDeformVert *dvert = NULL;
+ MDeformVert *dv = NULL;
+ float w, wpaint;
+ int i, iter;
+ int defgrp_index;
+
+ DM_ensure_tessface(dm);
+
+ sys = init_laplacian_system(dm->getNumEdges(dm), dm->getNumTessFaces(dm), numVerts);
+ if (!sys) {
+ return;
+ }
+
+ sys->mfaces = dm->getTessFaceArray(dm);
+ sys->medges = dm->getEdgeArray(dm);
+ sys->vertexCos = vertexCos;
+ sys->min_area = 0.00001f;
+ modifier_get_vgroup(ob, dm, smd->defgrp_name, &dvert, &defgrp_index);
+
+ sys->vert_centroid[0] = 0.0f;
+ sys->vert_centroid[1] = 0.0f;
+ sys->vert_centroid[2] = 0.0f;
+ for (iter = 0; iter < smd->repeat; iter++) {
+ memset_laplacian_system(sys, 0);
+ nlNewContext();
+ sys->context = nlGetCurrent();
+ nlSolverParameteri(NL_NB_VARIABLES, numVerts);
+ nlSolverParameteri(NL_LEAST_SQUARES, NL_TRUE);
+ nlSolverParameteri(NL_NB_ROWS, numVerts);
+ nlSolverParameteri(NL_NB_RIGHT_HAND_SIDES, 3);
+
+ init_laplacian_matrix(sys);
+
+ nlBegin(NL_SYSTEM);
+ for (i = 0; i < numVerts; i++) {
+ nlSetVariable(0, i, vertexCos[i][0]);
+ nlSetVariable(1, i, vertexCos[i][1]);
+ nlSetVariable(2, i, vertexCos[i][2]);
+ if (iter == 0) {
+ add_v3_v3(sys->vert_centroid, vertexCos[i]);
+ }
+ }
+ if (iter == 0 && numVerts > 0) {
+ mul_v3_fl(sys->vert_centroid, 1.0f / (float)numVerts);
+ }
+
+ nlBegin(NL_MATRIX);
+ dv = dvert;
+ for (i = 0; i < numVerts; i++) {
+ nlRightHandSideAdd(0, i, vertexCos[i][0]);
+ nlRightHandSideAdd(1, i, vertexCos[i][1]);
+ nlRightHandSideAdd(2, i, vertexCos[i][2]);
+ if (dv) {
+ wpaint = defvert_find_weight(dv, defgrp_index);
+ dv++;
+ }
+ else {
+ wpaint = 1.0f;
+ }
+
+ if (sys->zerola[i] == 0) {
+ w = sys->vweights[i] * sys->ring_areas[i];
+ sys->vweights[i] = (w == 0.0f) ? 0.0f : -smd->lambda * wpaint / (4.0f * w);
+ w = sys->vlengths[i];
+ sys->vlengths[i] = (w == 0.0f) ? 0.0f : -smd->lambda_border * wpaint * 2.0f / w;
+
+ if (sys->numNeEd[i] == sys->numNeFa[i]) {
+ nlMatrixAdd(i, i, 1.0f + smd->lambda * wpaint / (4.0f * sys->ring_areas[i]));
+ }
+ else {
+ nlMatrixAdd(i, i, 1.0f + smd->lambda_border * wpaint * 2.0f);
+ }
+ }
+ else {
+ nlMatrixAdd(i, i, 1.0f);
+ }
+ }
+
+ fill_laplacian_matrix(sys);
+
+ nlEnd(NL_MATRIX);
+ nlEnd(NL_SYSTEM);
+
+ if (nlSolveAdvanced(NULL, NL_TRUE)) {
+ validate_solution(sys, smd->flag);
+ }
+ nlDeleteContext(sys->context);
+ sys->context = NULL;
+ }
+ delete_laplacian_system(sys);
+
+}
+
+static void deformVerts(ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts, ModifierApplyFlag UNUSED(flag))
+{
+ DerivedMesh *dm = get_dm(ob, NULL, derivedData, NULL, 0);
+
+ laplaciansmoothModifier_do((LaplacianSmoothModifierData *)md, ob, dm,
+ vertexCos, numVerts);
+
+ if (dm != derivedData)
+ dm->release(dm);
+}
+
+static void deformVertsEM(
+ ModifierData *md, Object *ob, struct BMEditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+{
+ DerivedMesh *dm = get_dm(ob, editData, derivedData, NULL, 0);
+
+ laplaciansmoothModifier_do((LaplacianSmoothModifierData *)md, ob, dm,
+ vertexCos, numVerts);
+
+ if (dm != derivedData)
+ dm->release(dm);
+}
+
+
+ModifierTypeInfo modifierType_LaplacianSmooth = {
+ /* name */ "Laplacian Smooth",
+ /* structName */ "LaplacianSmoothModifierData",
+ /* structSize */ sizeof(LaplacianSmoothModifierData),
+ /* type */ eModifierTypeType_OnlyDeform,
+ /* flags */ eModifierTypeFlag_AcceptsMesh |
+ eModifierTypeFlag_SupportsEditmode,
+
+ /* copy_data */ copy_data,
+ /* deformVerts */ deformVerts,
+ /* deformMatrices */ NULL,
+ /* deformVertsEM */ deformVertsEM,
+ /* deformMatricesEM */ NULL,
+ /* applyModifier */ NULL,
+ /* applyModifierEM */ NULL,
+ /* initData */ init_data,
+ /* requiredDataMask */ required_data_mask,
+ /* freeData */ NULL,
+ /* isDisabled */ is_disabled,
+ /* updateDepgraph */ NULL,
+ /* dependsOnTime */ NULL,
+ /* dependsOnNormals */ NULL,
+ /* foreachObjectLink */ NULL,
+ /* foreachIDLink */ NULL,
+ /* foreachTexLink */ NULL,
+};
diff --git a/source/blender/modifiers/intern/MOD_lattice.c b/source/blender/modifiers/intern/MOD_lattice.c
index d64ccf750b2..a5c52c6c76a 100644
--- a/source/blender/modifiers/intern/MOD_lattice.c
+++ b/source/blender/modifiers/intern/MOD_lattice.c
@@ -122,12 +122,12 @@ static void deformVerts(ModifierData *md, Object *ob,
}
static void deformVertsEM(
- ModifierData *md, Object *ob, struct BMEditMesh *editData,
+ ModifierData *md, Object *ob, struct BMEditMesh *em,
DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
- if (!derivedData) dm = CDDM_from_BMEditMesh(editData, ob->data, FALSE, FALSE);
+ if (!derivedData) dm = CDDM_from_editbmesh(em, FALSE, FALSE);
deformVerts(md, ob, dm, vertexCos, numVerts, 0);
diff --git a/source/blender/modifiers/intern/MOD_mask.c b/source/blender/modifiers/intern/MOD_mask.c
index ab7263a1b53..23ce8cdeb21 100644
--- a/source/blender/modifiers/intern/MOD_mask.c
+++ b/source/blender/modifiers/intern/MOD_mask.c
@@ -179,7 +179,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
}
/* verthash gives mapping from original vertex indices to the new indices (including selected matches only)
- * key=oldindex, value=newindex
+ * key = oldindex, value = newindex
*/
vertHash = BLI_ghash_int_new("mask vert gh");
@@ -226,11 +226,11 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
int defgrp_index = defgroup_name_index(ob, mmd->vgroup);
/* get dverts */
- if (defgrp_index >= 0)
+ if (defgrp_index != -1)
dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
/* if no vgroup (i.e. dverts) found, return the initial mesh */
- if ((defgrp_index < 0) || (dvert == NULL))
+ if ((defgrp_index == -1) || (dvert == NULL))
return dm;
/* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
diff --git a/source/blender/modifiers/intern/MOD_meshdeform.c b/source/blender/modifiers/intern/MOD_meshdeform.c
index f0bdf1bb737..f4d9b7270e6 100644
--- a/source/blender/modifiers/intern/MOD_meshdeform.c
+++ b/source/blender/modifiers/intern/MOD_meshdeform.c
@@ -218,7 +218,7 @@ static void meshdeformModifier_do(
}
if (!cagedm) {
- modifier_setError(md, "%s", TIP_("Can't get mesh from cage object."));
+ modifier_setError(md, "Cannot get mesh from cage object");
return;
}
@@ -246,17 +246,17 @@ static void meshdeformModifier_do(
totcagevert = cagedm->getNumVerts(cagedm);
if (mmd->totvert != totvert) {
- modifier_setError(md, TIP_("Verts changed from %d to %d."), mmd->totvert, totvert);
+ modifier_setError(md, "Verts changed from %d to %d", mmd->totvert, totvert);
cagedm->release(cagedm);
return;
}
else if (mmd->totcagevert != totcagevert) {
- modifier_setError(md, TIP_("Cage verts changed from %d to %d."), mmd->totcagevert, totcagevert);
+ modifier_setError(md, "Cage verts changed from %d to %d", mmd->totcagevert, totcagevert);
cagedm->release(cagedm);
return;
}
else if (mmd->bindcagecos == NULL) {
- modifier_setError(md, "%s", TIP_("Bind data missing."));
+ modifier_setError(md, "Bind data missing");
cagedm->release(cagedm);
return;
}
@@ -431,28 +431,28 @@ void modifier_mdef_compact_influences(ModifierData *md)
}
ModifierTypeInfo modifierType_MeshDeform = {
- /* name */ "MeshDeform",
- /* structName */ "MeshDeformModifierData",
- /* structSize */ sizeof(MeshDeformModifierData),
- /* type */ eModifierTypeType_OnlyDeform,
- /* flags */ eModifierTypeFlag_AcceptsCVs |
- eModifierTypeFlag_SupportsEditmode,
-
- /* copyData */ copyData,
- /* deformVerts */ deformVerts,
- /* deformMatrices */ NULL,
- /* deformVertsEM */ deformVertsEM,
- /* deformMatricesEM */ NULL,
- /* applyModifier */ NULL,
- /* applyModifierEM */ NULL,
- /* initData */ initData,
- /* requiredDataMask */ requiredDataMask,
- /* freeData */ freeData,
- /* isDisabled */ isDisabled,
- /* updateDepgraph */ updateDepgraph,
- /* dependsOnTime */ NULL,
- /* dependsOnNormals */ NULL,
+ /* name */ "MeshDeform",
+ /* structName */ "MeshDeformModifierData",
+ /* structSize */ sizeof(MeshDeformModifierData),
+ /* type */ eModifierTypeType_OnlyDeform,
+ /* flags */ eModifierTypeFlag_AcceptsCVs |
+ eModifierTypeFlag_SupportsEditmode,
+
+ /* copyData */ copyData,
+ /* deformVerts */ deformVerts,
+ /* deformMatrices */ NULL,
+ /* deformVertsEM */ deformVertsEM,
+ /* deformMatricesEM */ NULL,
+ /* applyModifier */ NULL,
+ /* applyModifierEM */ NULL,
+ /* initData */ initData,
+ /* requiredDataMask */ requiredDataMask,
+ /* freeData */ freeData,
+ /* isDisabled */ isDisabled,
+ /* updateDepgraph */ updateDepgraph,
+ /* dependsOnTime */ NULL,
+ /* dependsOnNormals */ NULL,
/* foreachObjectLink */ foreachObjectLink,
- /* foreachIDLink */ NULL,
- /* foreachTexLink */ NULL,
+ /* foreachIDLink */ NULL,
+ /* foreachTexLink */ NULL,
};
diff --git a/source/blender/modifiers/intern/MOD_mirror.c b/source/blender/modifiers/intern/MOD_mirror.c
index febc4190fdf..83c678db7b3 100644
--- a/source/blender/modifiers/intern/MOD_mirror.c
+++ b/source/blender/modifiers/intern/MOD_mirror.c
@@ -43,7 +43,8 @@
#include "BKE_mesh.h"
#include "BKE_modifier.h"
#include "BKE_deform.h"
-#include "BKE_tessmesh.h"
+
+#include "bmesh.h"
#include "MEM_guardedalloc.h"
#include "depsgraph_private.h"
diff --git a/source/blender/modifiers/intern/MOD_multires.c b/source/blender/modifiers/intern/MOD_multires.c
index afc85a8144e..4292246d8cc 100644
--- a/source/blender/modifiers/intern/MOD_multires.c
+++ b/source/blender/modifiers/intern/MOD_multires.c
@@ -80,6 +80,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *dm,
Mesh *me = (Mesh *)ob->data;
const int useRenderParams = flag & MOD_APPLY_RENDER;
MultiresFlags flags = 0;
+ int has_mask = CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK);
if (mmd->totlvl) {
if (!CustomData_get_layer(&me->ldata, CD_MDISPS)) {
@@ -88,7 +89,9 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *dm,
}
}
- flags = MULTIRES_ALLOC_PAINT_MASK;
+ if (has_mask)
+ flags |= MULTIRES_ALLOC_PAINT_MASK;
+
if (useRenderParams)
flags |= MULTIRES_USE_RENDER_PARAMS;
diff --git a/source/blender/modifiers/intern/MOD_ocean.c b/source/blender/modifiers/intern/MOD_ocean.c
index 3bf8b9ffacc..564fa696c2a 100644
--- a/source/blender/modifiers/intern/MOD_ocean.c
+++ b/source/blender/modifiers/intern/MOD_ocean.c
@@ -33,17 +33,17 @@
#include "DNA_modifier_types.h"
#include "DNA_scene_types.h"
-#include "BKE_cdderivedmesh.h"
-#include "BKE_global.h"
-#include "BKE_modifier.h"
-#include "BKE_ocean.h"
-
#include "BLI_blenlib.h"
#include "BLI_math.h"
#include "BLI_math_inline.h"
#include "BLI_utildefines.h"
#include "BLI_string.h"
+#include "BKE_cdderivedmesh.h"
+#include "BKE_global.h"
+#include "BKE_modifier.h"
+#include "BKE_ocean.h"
+
#include "MOD_util.h"
#ifdef WITH_OCEANSIM
@@ -241,13 +241,13 @@ static void dm_get_bounds(DerivedMesh *dm, float *sx, float *sy, float *ox, floa
copy_v3_v3(max, mvert->co);
for (v = 1; v < totvert; v++, mvert++) {
- min[0] = minf(min[0], mvert->co[0]);
- min[1] = minf(min[1], mvert->co[1]);
- min[2] = minf(min[2], mvert->co[2]);
+ min[0] = min_ff(min[0], mvert->co[0]);
+ min[1] = min_ff(min[1], mvert->co[1]);
+ min[2] = min_ff(min[2], mvert->co[2]);
- max[0] = maxf(max[0], mvert->co[0]);
- max[1] = maxf(max[1], mvert->co[1]);
- max[2] = maxf(max[2], mvert->co[2]);
+ max[0] = max_ff(max[0], mvert->co[0]);
+ max[1] = max_ff(max[1], mvert->co[1]);
+ max[2] = max_ff(max[2], mvert->co[2]);
}
sub_v3_v3v3(delta, max, min);
diff --git a/source/blender/modifiers/intern/MOD_particleinstance.c b/source/blender/modifiers/intern/MOD_particleinstance.c
index e64e80efde3..4984682455a 100644
--- a/source/blender/modifiers/intern/MOD_particleinstance.c
+++ b/source/blender/modifiers/intern/MOD_particleinstance.c
@@ -81,6 +81,44 @@ static int dependsOnTime(ModifierData *UNUSED(md))
{
return 0;
}
+
+static int isDisabled(ModifierData *md, int useRenderParams)
+{
+ ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *)md;
+ ParticleSystem *psys;
+ ModifierData *ob_md;
+
+ if (!pimd->ob)
+ return TRUE;
+
+ psys = BLI_findlink(&pimd->ob->particlesystem, pimd->psys - 1);
+ if (psys == NULL)
+ return TRUE;
+
+ /* If the psys modifier is disabled we cannot use its data.
+ * First look up the psys modifier from the object, then check if it is enabled.
+ */
+ for (ob_md = pimd->ob->modifiers.first; ob_md; ob_md = ob_md->next) {
+ if (ob_md->type == eModifierType_ParticleSystem) {
+ ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)ob_md;
+ if (psmd->psys == psys) {
+ int required_mode;
+
+ if (useRenderParams) required_mode = eModifierMode_Render;
+ else required_mode = eModifierMode_Realtime;
+
+ if (!modifier_isEnabled(md->scene, ob_md, required_mode))
+ return TRUE;
+
+ break;
+ }
+ }
+ }
+
+ return FALSE;
+}
+
+
static void updateDepgraph(ModifierData *md, DagForest *forest,
struct Scene *UNUSED(scene),
Object *UNUSED(ob),
@@ -363,32 +401,31 @@ static DerivedMesh *applyModifierEM(ModifierData *md, Object *ob,
return applyModifier(md, ob, derivedData, MOD_APPLY_USECACHE);
}
-
ModifierTypeInfo modifierType_ParticleInstance = {
- /* name */ "ParticleInstance",
- /* structName */ "ParticleInstanceModifierData",
- /* structSize */ sizeof(ParticleInstanceModifierData),
- /* type */ eModifierTypeType_Constructive,
- /* flags */ eModifierTypeFlag_AcceptsMesh |
- eModifierTypeFlag_SupportsMapping |
- eModifierTypeFlag_SupportsEditmode |
- eModifierTypeFlag_EnableInEditmode,
-
- /* copyData */ copyData,
- /* deformVerts */ NULL,
- /* deformMatrices */ NULL,
- /* deformVertsEM */ NULL,
- /* deformMatricesEM */ NULL,
- /* applyModifier */ applyModifier,
- /* applyModifierEM */ applyModifierEM,
- /* initData */ initData,
- /* requiredDataMask */ NULL,
- /* freeData */ NULL,
- /* isDisabled */ NULL,
- /* updateDepgraph */ updateDepgraph,
- /* dependsOnTime */ dependsOnTime,
- /* dependsOnNormals */ NULL,
+ /* name */ "ParticleInstance",
+ /* structName */ "ParticleInstanceModifierData",
+ /* structSize */ sizeof(ParticleInstanceModifierData),
+ /* type */ eModifierTypeType_Constructive,
+ /* flags */ eModifierTypeFlag_AcceptsMesh |
+ eModifierTypeFlag_SupportsMapping |
+ eModifierTypeFlag_SupportsEditmode |
+ eModifierTypeFlag_EnableInEditmode,
+
+ /* copyData */ copyData,
+ /* deformVerts */ NULL,
+ /* deformMatrices */ NULL,
+ /* deformVertsEM */ NULL,
+ /* deformMatricesEM */ NULL,
+ /* applyModifier */ applyModifier,
+ /* applyModifierEM */ applyModifierEM,
+ /* initData */ initData,
+ /* requiredDataMask */ NULL,
+ /* freeData */ NULL,
+ /* isDisabled */ isDisabled,
+ /* updateDepgraph */ updateDepgraph,
+ /* dependsOnTime */ dependsOnTime,
+ /* dependsOnNormals */ NULL,
/* foreachObjectLink */ foreachObjectLink,
- /* foreachIDLink */ NULL,
- /* foreachTexLink */ NULL,
+ /* foreachIDLink */ NULL,
+ /* foreachTexLink */ NULL,
};
diff --git a/source/blender/modifiers/intern/MOD_particlesystem.c b/source/blender/modifiers/intern/MOD_particlesystem.c
index 254c02b7672..cd2ef5957cd 100644
--- a/source/blender/modifiers/intern/MOD_particlesystem.c
+++ b/source/blender/modifiers/intern/MOD_particlesystem.c
@@ -44,6 +44,7 @@
#include "BKE_material.h"
#include "BKE_modifier.h"
#include "BKE_particle.h"
+#include "BKE_scene.h"
#include "MOD_util.h"
@@ -130,6 +131,7 @@ static void deformVerts(ModifierData *md, Object *ob,
ParticleSystemModifierData *psmd = (ParticleSystemModifierData *) md;
ParticleSystem *psys = NULL;
int needsFree = 0;
+ /* float cfra = BKE_scene_frame_get(md->scene); */ /* UNUSED */
if (ob->particlesystem.first)
psys = psmd->psys;
@@ -188,9 +190,11 @@ static void deformVerts(ModifierData *md, Object *ob,
psmd->totdmface = psmd->dm->getNumTessFaces(psmd->dm);
}
- psmd->flag &= ~eParticleSystemFlag_psys_updated;
- particle_system_update(md->scene, ob, psys);
- psmd->flag |= eParticleSystemFlag_psys_updated;
+ if (!(ob->transflag & OB_NO_PSYS_UPDATE)) {
+ psmd->flag &= ~eParticleSystemFlag_psys_updated;
+ particle_system_update(md->scene, ob, psys);
+ psmd->flag |= eParticleSystemFlag_psys_updated;
+ }
}
/* disabled particles in editmode for now, until support for proper derivedmesh
diff --git a/source/blender/modifiers/intern/MOD_remesh.c b/source/blender/modifiers/intern/MOD_remesh.c
index 2b55471be3d..746cad10a01 100644
--- a/source/blender/modifiers/intern/MOD_remesh.c
+++ b/source/blender/modifiers/intern/MOD_remesh.c
@@ -223,7 +223,7 @@ ModifierTypeInfo modifierType_Remesh = {
/* structSize */ sizeof(RemeshModifierData),
/* type */ eModifierTypeType_Nonconstructive,
/* flags */ eModifierTypeFlag_AcceptsMesh |
- eModifierTypeFlag_AcceptsCVs |
+ eModifierTypeFlag_AcceptsCVs |
eModifierTypeFlag_SupportsEditmode,
/* copyData */ copyData,
/* deformVerts */ NULL,
diff --git a/source/blender/modifiers/intern/MOD_screw.c b/source/blender/modifiers/intern/MOD_screw.c
index 4fd2c658380..93b5e36e5a4 100644
--- a/source/blender/modifiers/intern/MOD_screw.c
+++ b/source/blender/modifiers/intern/MOD_screw.c
@@ -215,7 +215,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
if (totlen != 0.0f) {
float zero[3] = {0.0f, 0.0f, 0.0f};
- float cp[3];
+ float cp[3];
screw_ofs = closest_to_line_v3(cp, mtx_tx[3], zero, axis_vec);
}
else {
@@ -363,7 +363,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
*/
vert_connect = MEM_mallocN(sizeof(ScrewVertConnect) * totvert, "ScrewVertConnect");
- //vert_connect= (ScrewVertConnect *) &medge_new[totvert]; /* skip the first slice of verts */
+ //vert_connect = (ScrewVertConnect *) &medge_new[totvert]; /* skip the first slice of verts */
vc = vert_connect;
/* Copy Vert Locations */
@@ -393,7 +393,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
mul_m4_v3(mtx_tx, vc->co);
/* length in 2d, don't sqrt because this is only for comparison */
- vc->dist = vc->co[other_axis_1] * vc->co[other_axis_1] +
+ vc->dist = vc->co[other_axis_1] * vc->co[other_axis_1] +
vc->co[other_axis_2] * vc->co[other_axis_2];
/* printf("location %f %f %f -- %f\n", vc->co[0], vc->co[1], vc->co[2], vc->dist);*/
@@ -410,7 +410,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
vc->v[0] = vc->v[1] = -1;
/* length in 2d, don't sqrt because this is only for comparison */
- vc->dist = vc->co[other_axis_1] * vc->co[other_axis_1] +
+ vc->dist = vc->co[other_axis_1] * vc->co[other_axis_1] +
vc->co[other_axis_2] * vc->co[other_axis_2];
/* printf("location %f %f %f -- %f\n", vc->co[0], vc->co[1], vc->co[2], vc->dist);*/
@@ -430,7 +430,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
vc->e[1] = med_new;
}
else {
- vc->v[0] = vc->v[1] = -2; /* erro value - don't use, 3 edges on vert */
+ vc->v[0] = vc->v[1] = -2; /* error value - don't use, 3 edges on vert */
}
vc = &vert_connect[med_new->v2];
@@ -445,7 +445,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
vc->e[1] = med_new;
}
else {
- vc->v[0] = vc->v[1] = -2; /* erro value - don't use, 3 edges on vert */
+ vc->v[0] = vc->v[1] = -2; /* error value - don't use, 3 edges on vert */
}
}
@@ -475,7 +475,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
/*printf("\t\tVERT: %i\n", lt_iter.v);*/
if (lt_iter.v_poin->flag) {
/*printf("\t\t\tBreaking Found end\n");*/
- //endpoints[0]= endpoints[1]= -1;
+ //endpoints[0] = endpoints[1] = -1;
ed_loop_closed = 1; /* circle */
break;
}
@@ -490,7 +490,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
screwvert_iter_step(&lt_iter);
if (!lt_iter.v_poin) {
/*printf("\t\t\tFound End Also Num %i\n", j);*/
- /*endpoints[j]= lt_iter.v_other;*/ /* other is still valid */
+ /*endpoints[j] = lt_iter.v_other;*/ /* other is still valid */
break;
}
}
@@ -732,7 +732,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
copy_v3_v3(mv_new->co, mv_new_base->co);
/* only need to set these if using non cleared memory */
- /*mv_new->mat_nr= mv_new->flag= 0;*/
+ /*mv_new->mat_nr = mv_new->flag = 0;*/
if (ltmd->ob_axis) {
sub_v3_v3(mv_new->co, mtx_tx[3]);
@@ -831,7 +831,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
}
/* close the loop*/
- if (close) {
+ if (close) {
if (do_flip) {
ml_new[3].v = i1;
ml_new[2].v = i2;
diff --git a/source/blender/modifiers/intern/MOD_shapekey.c b/source/blender/modifiers/intern/MOD_shapekey.c
index 3353382fa3d..7fe8dc69790 100644
--- a/source/blender/modifiers/intern/MOD_shapekey.c
+++ b/source/blender/modifiers/intern/MOD_shapekey.c
@@ -54,7 +54,7 @@ static void deformVerts(ModifierData *md, Object *ob,
int numVerts,
ModifierApplyFlag UNUSED(flag))
{
- KeyBlock *kb = ob_get_keyblock(ob);
+ KeyBlock *kb = BKE_keyblock_from_object(ob);
float (*deformedVerts)[3];
if (kb && kb->totelem == numVerts) {
@@ -69,8 +69,8 @@ static void deformVerts(ModifierData *md, Object *ob,
static void deformMatrices(ModifierData *md, Object *ob, DerivedMesh *derivedData,
float (*vertexCos)[3], float (*defMats)[3][3], int numVerts)
{
- Key *key = ob_get_key(ob);
- KeyBlock *kb = ob_get_keyblock(ob);
+ Key *key = BKE_key_from_object(ob);
+ KeyBlock *kb = BKE_keyblock_from_object(ob);
float scale[3][3];
(void)vertexCos; /* unused */
@@ -94,7 +94,7 @@ static void deformVertsEM(ModifierData *md, Object *ob,
float (*vertexCos)[3],
int numVerts)
{
- Key *key = ob_get_key(ob);
+ Key *key = BKE_key_from_object(ob);
if (key && key->type == KEY_RELATIVE)
deformVerts(md, ob, derivedData, vertexCos, numVerts, 0);
@@ -107,8 +107,8 @@ static void deformMatricesEM(ModifierData *UNUSED(md), Object *ob,
float (*defMats)[3][3],
int numVerts)
{
- Key *key = ob_get_key(ob);
- KeyBlock *kb = ob_get_keyblock(ob);
+ Key *key = BKE_key_from_object(ob);
+ KeyBlock *kb = BKE_keyblock_from_object(ob);
float scale[3][3];
(void)vertexCos; /* unused */
@@ -122,6 +122,7 @@ static void deformMatricesEM(ModifierData *UNUSED(md), Object *ob,
}
}
+
ModifierTypeInfo modifierType_ShapeKey = {
/* name */ "ShapeKey",
/* structName */ "ShapeKeyModifierData",
diff --git a/source/blender/modifiers/intern/MOD_shrinkwrap.c b/source/blender/modifiers/intern/MOD_shrinkwrap.c
index 45cd33efea8..d3a03614d7c 100644
--- a/source/blender/modifiers/intern/MOD_shrinkwrap.c
+++ b/source/blender/modifiers/intern/MOD_shrinkwrap.c
@@ -163,30 +163,30 @@ static void updateDepgraph(ModifierData *md, DagForest *forest,
ModifierTypeInfo modifierType_Shrinkwrap = {
- /* name */ "Shrinkwrap",
- /* structName */ "ShrinkwrapModifierData",
- /* structSize */ sizeof(ShrinkwrapModifierData),
- /* type */ eModifierTypeType_OnlyDeform,
- /* flags */ eModifierTypeFlag_AcceptsMesh |
- eModifierTypeFlag_AcceptsCVs |
- eModifierTypeFlag_SupportsEditmode |
- eModifierTypeFlag_EnableInEditmode,
-
- /* copyData */ copyData,
- /* deformVerts */ deformVerts,
- /* deformMatrices */ NULL,
- /* deformVertsEM */ deformVertsEM,
- /* deformMatricesEM */ NULL,
- /* applyModifier */ NULL,
- /* applyModifierEM */ NULL,
- /* initData */ initData,
- /* requiredDataMask */ requiredDataMask,
- /* freeData */ NULL,
- /* isDisabled */ isDisabled,
- /* updateDepgraph */ updateDepgraph,
- /* dependsOnTime */ NULL,
- /* dependsOnNormals */ NULL,
+ /* name */ "Shrinkwrap",
+ /* structName */ "ShrinkwrapModifierData",
+ /* structSize */ sizeof(ShrinkwrapModifierData),
+ /* type */ eModifierTypeType_OnlyDeform,
+ /* flags */ eModifierTypeFlag_AcceptsMesh |
+ eModifierTypeFlag_AcceptsCVs |
+ eModifierTypeFlag_SupportsEditmode |
+ eModifierTypeFlag_EnableInEditmode,
+
+ /* copyData */ copyData,
+ /* deformVerts */ deformVerts,
+ /* deformMatrices */ NULL,
+ /* deformVertsEM */ deformVertsEM,
+ /* deformMatricesEM */ NULL,
+ /* applyModifier */ NULL,
+ /* applyModifierEM */ NULL,
+ /* initData */ initData,
+ /* requiredDataMask */ requiredDataMask,
+ /* freeData */ NULL,
+ /* isDisabled */ isDisabled,
+ /* updateDepgraph */ updateDepgraph,
+ /* dependsOnTime */ NULL,
+ /* dependsOnNormals */ NULL,
/* foreachObjectLink */ foreachObjectLink,
- /* foreachIDLink */ NULL,
- /* foreachTexLink */ NULL,
+ /* foreachIDLink */ NULL,
+ /* foreachTexLink */ NULL,
};
diff --git a/source/blender/modifiers/intern/MOD_simpledeform.c b/source/blender/modifiers/intern/MOD_simpledeform.c
index bf5f6cd095e..5267c0d9ccb 100644
--- a/source/blender/modifiers/intern/MOD_simpledeform.c
+++ b/source/blender/modifiers/intern/MOD_simpledeform.c
@@ -72,7 +72,7 @@ static void simpleDeform_taper(const float factor, const float dcut[3], float r_
r_co[1] = y + y * scale;
r_co[2] = z;
- if (dcut) {
+ {
r_co[0] += dcut[0];
r_co[1] += dcut[1];
r_co[2] += dcut[2];
@@ -90,7 +90,7 @@ static void simpleDeform_stretch(const float factor, const float dcut[3], float
r_co[1] = y * scale;
r_co[2] = z * (1.0f + factor);
- if (dcut) {
+ {
r_co[0] += dcut[0];
r_co[1] += dcut[1];
r_co[2] += dcut[2];
@@ -110,7 +110,7 @@ static void simpleDeform_twist(const float factor, const float *dcut, float r_co
r_co[1] = x * sint + y * cost;
r_co[2] = z;
- if (dcut) {
+ {
r_co[0] += dcut[0];
r_co[1] += dcut[1];
r_co[2] += dcut[2];
@@ -132,7 +132,7 @@ static void simpleDeform_bend(const float factor, const float dcut[3], float r_c
r_co[2] = z;
}
- if (dcut) {
+ {
r_co[0] += cost * dcut[0];
r_co[1] += sint * dcut[0];
r_co[2] += dcut[2];
@@ -161,9 +161,9 @@ static void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object
if (smd->limit[0] < 0.0f) smd->limit[0] = 0.0f;
if (smd->limit[0] > 1.0f) smd->limit[0] = 1.0f;
- smd->limit[0] = minf(smd->limit[0], smd->limit[1]); /* Upper limit >= than lower limit */
+ smd->limit[0] = min_ff(smd->limit[0], smd->limit[1]); /* Upper limit >= than lower limit */
- //Calculate matrixs do convert between coordinate spaces
+ /* Calculate matrixs do convert between coordinate spaces */
if (smd->origin) {
transf = &tmp_transf;
@@ -176,10 +176,11 @@ static void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object
}
}
- //Setup vars
- limit_axis = (smd->mode == MOD_SIMPLEDEFORM_MODE_BEND) ? 0 : 2; //Bend limits on X.. all other modes limit on Z
+ /* Setup vars,
+ * Bend limits on X.. all other modes limit on Z */
+ limit_axis = (smd->mode == MOD_SIMPLEDEFORM_MODE_BEND) ? 0 : 2;
- //Update limits if needed
+ /* Update limits if needed */
{
float lower = FLT_MAX;
float upper = -FLT_MAX;
@@ -190,8 +191,8 @@ static void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object
if (transf) space_transform_apply(transf, tmp);
- lower = minf(lower, tmp[limit_axis]);
- upper = maxf(upper, tmp[limit_axis]);
+ lower = min_ff(lower, tmp[limit_axis]);
+ upper = max_ff(upper, tmp[limit_axis]);
}
@@ -199,7 +200,7 @@ static void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object
smd_limit[1] = lower + (upper - lower) * smd->limit[1];
smd_limit[0] = lower + (upper - lower) * smd->limit[0];
- smd_factor = smd->factor / MAX2(FLT_EPSILON, smd_limit[1] - smd_limit[0]);
+ smd_factor = smd->factor / max_ff(FLT_EPSILON, smd_limit[1] - smd_limit[0]);
}
modifier_get_vgroup(ob, dm, smd->vgroup_name, &dvert, &vgroup);
@@ -235,7 +236,9 @@ static void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object
simpleDeform_callback(smd_factor, dcut, co); /* apply deform */
interp_v3_v3v3(vertexCos[i], vertexCos[i], co, weight); /* Use vertex weight has coef of linear interpolation */
- if (transf) space_transform_invert(transf, vertexCos[i]);
+ if (transf) {
+ space_transform_invert(transf, vertexCos[i]);
+ }
}
}
}
@@ -249,6 +252,7 @@ static void initData(ModifierData *md)
SimpleDeformModifierData *smd = (SimpleDeformModifierData *) md;
smd->mode = MOD_SIMPLEDEFORM_MODE_TWIST;
+ smd->originOpts = MOD_SIMPLEDEFORM_ORIGIN_LOCAL;
smd->axis = 0;
smd->origin = NULL;
@@ -349,9 +353,9 @@ ModifierTypeInfo modifierType_SimpleDeform = {
/* type */ eModifierTypeType_OnlyDeform,
/* flags */ eModifierTypeFlag_AcceptsMesh |
- eModifierTypeFlag_AcceptsCVs |
- eModifierTypeFlag_SupportsEditmode |
- eModifierTypeFlag_EnableInEditmode,
+ eModifierTypeFlag_AcceptsCVs |
+ eModifierTypeFlag_SupportsEditmode |
+ eModifierTypeFlag_EnableInEditmode,
/* copyData */ copyData,
/* deformVerts */ deformVerts,
diff --git a/source/blender/modifiers/intern/MOD_skin.c b/source/blender/modifiers/intern/MOD_skin.c
index 222f13185ea..8a4d70da6e8 100644
--- a/source/blender/modifiers/intern/MOD_skin.c
+++ b/source/blender/modifiers/intern/MOD_skin.c
@@ -77,7 +77,8 @@
#include "BKE_DerivedMesh.h"
#include "BKE_mesh.h"
#include "BKE_modifier.h"
-#include "BKE_tessmesh.h"
+
+#include "bmesh.h"
#include "MOD_util.h"
@@ -143,6 +144,7 @@ static int is_quad_symmetric(BMVert *quad[4],
const SkinModifierData *smd)
{
const float threshold = 0.0001f;
+ const float threshold_squared = threshold * threshold;
int axis;
for (axis = 0; axis < 3; axis++) {
@@ -152,16 +154,16 @@ static int is_quad_symmetric(BMVert *quad[4],
copy_v3_v3(a, quad[0]->co);
a[axis] = -a[axis];
- if (len_v3v3(a, quad[1]->co) < threshold) {
+ if (len_squared_v3v3(a, quad[1]->co) < threshold_squared) {
copy_v3_v3(a, quad[2]->co);
a[axis] = -a[axis];
- if (len_v3v3(a, quad[3]->co) < threshold)
+ if (len_squared_v3v3(a, quad[3]->co) < threshold_squared)
return 1;
}
- else if (len_v3v3(a, quad[3]->co) < threshold) {
+ else if (len_squared_v3v3(a, quad[3]->co) < threshold_squared) {
copy_v3_v3(a, quad[2]->co);
a[axis] = -a[axis];
- if (len_v3v3(a, quad[1]->co) < threshold)
+ if (len_squared_v3v3(a, quad[1]->co) < threshold_squared)
return 1;
}
}
@@ -178,13 +180,13 @@ static int quad_crosses_symmetry_plane(BMVert *quad[4],
for (axis = 0; axis < 3; axis++) {
if (smd->symmetry_axes & (1 << axis)) {
- int i, left = 0, right = 0;
+ int i, left = FALSE, right = FALSE;
for (i = 0; i < 4; i++) {
- if (quad[i]->co[axis] < 0)
- left = 1;
- else if (quad[i]->co[axis] > 0)
- right = 1;
+ if (quad[i]->co[axis] < 0.0f)
+ left = TRUE;
+ else if (quad[i]->co[axis] > 0.0f)
+ right = TRUE;
if (left && right)
return TRUE;
@@ -355,7 +357,7 @@ static void merge_frame_corners(Frame **frames, int totframe)
BLI_assert(frames[i] != frames[k]);
side_b = frame_len(frames[k]);
- thresh = minf(side_a, side_b) / 2.0f;
+ thresh = min_ff(side_a, side_b) / 2.0f;
/* Compare with each corner of all other frames... */
for (l = 0; l < 4; l++) {
@@ -695,11 +697,11 @@ static void build_emats_stack(BLI_Stack *stack, int *visited_e, EMat *emat,
}
static EMat *build_edge_mats(const MVertSkin *vs,
- const MVert *mvert,
- int totvert,
+ const MVert *mvert,
+ int totvert,
const MEdge *medge,
- const MeshElemMap *emap,
- int totedge)
+ const MeshElemMap *emap,
+ int totedge)
{
BLI_Stack *stack;
EMat *emat;
@@ -1422,7 +1424,7 @@ static void hull_merge_triangles(SkinOutput *so, const SkinModifierData *smd)
}
}
- while (!BLI_heap_empty(heap)) {
+ while (!BLI_heap_is_empty(heap)) {
BMFace *adj[2];
e = BLI_heap_popmin(heap);
@@ -1544,23 +1546,23 @@ static void skin_output_end_nodes(SkinOutput *so, SkinNode *skin_nodes,
if (sn->flag & CAP_START) {
if (sn->flag & ROOT) {
add_poly(so,
- sn->frames[0].verts[0],
- sn->frames[0].verts[1],
- sn->frames[0].verts[2],
- sn->frames[0].verts[3]);
+ sn->frames[0].verts[0],
+ sn->frames[0].verts[1],
+ sn->frames[0].verts[2],
+ sn->frames[0].verts[3]);
}
else {
add_poly(so,
- sn->frames[0].verts[3],
- sn->frames[0].verts[2],
- sn->frames[0].verts[1],
- sn->frames[0].verts[0]);
+ sn->frames[0].verts[3],
+ sn->frames[0].verts[2],
+ sn->frames[0].verts[1],
+ sn->frames[0].verts[0]);
}
}
if (sn->flag & CAP_END) {
add_poly(so,
sn->frames[1].verts[0],
- sn->frames[1].verts[1],
+ sn->frames[1].verts[1],
sn->frames[1].verts[2],
sn->frames[1].verts[3]);
}
@@ -1770,7 +1772,6 @@ static void skin_set_orig_indices(DerivedMesh *dm)
static DerivedMesh *base_skin(DerivedMesh *origdm,
SkinModifierData *smd)
{
- BMEditMesh fake_em;
DerivedMesh *result;
MVertSkin *nodes;
BMesh *bm;
@@ -1807,8 +1808,7 @@ static DerivedMesh *base_skin(DerivedMesh *origdm,
if (!bm)
return NULL;
- fake_em.bm = bm;
- result = CDDM_from_BMEditMesh(&fake_em, NULL, FALSE, FALSE);
+ result = CDDM_from_bmesh(bm, FALSE);
BM_mesh_free(bm);
CDDM_calc_edges(result);
@@ -1861,7 +1861,7 @@ static void copyData(ModifierData *md, ModifierData *target)
static DerivedMesh *applyModifierEM(ModifierData *md,
Object *UNUSED(ob),
- BMEditMesh *UNUSED(em),
+ struct BMEditMesh *UNUSED(em),
DerivedMesh *dm)
{
DerivedMesh *result;
diff --git a/source/blender/modifiers/intern/MOD_smoke.c b/source/blender/modifiers/intern/MOD_smoke.c
index b9b3b89e06d..4b2ce47b8d9 100644
--- a/source/blender/modifiers/intern/MOD_smoke.c
+++ b/source/blender/modifiers/intern/MOD_smoke.c
@@ -81,19 +81,31 @@ static void freeData(ModifierData *md)
smokeModifier_free(smd);
}
-static void deformVerts(ModifierData *md, Object *ob,
- DerivedMesh *derivedData,
- float (*vertexCos)[3],
- int UNUSED(numVerts),
- ModifierApplyFlag UNUSED(flag))
+static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
{
- SmokeModifierData *smd = (SmokeModifierData *) md;
- DerivedMesh *dm = get_cddm(ob, NULL, derivedData, vertexCos);
+ SmokeModifierData *smd = (SmokeModifierData *)md;
+ CustomDataMask dataMask = 0;
+
+ if (smd && (smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow) {
+ if (smd->flow->source == MOD_SMOKE_FLOW_SOURCE_MESH) {
+ /* vertex groups */
+ if (smd->flow->vgroup_density)
+ dataMask |= CD_MASK_MDEFORMVERT;
+ /* uv layer */
+ if (smd->flow->texture_type == MOD_SMOKE_FLOW_TEXTURE_MAP_UV)
+ dataMask |= CD_MASK_MTFACE;
+ }
+ }
+ return dataMask;
+}
- smokeModifier_do(smd, md->scene, ob, dm);
+static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
+ DerivedMesh *dm,
+ ModifierApplyFlag UNUSED(flag))
+{
+ SmokeModifierData *smd = (SmokeModifierData *) md;
- if (dm != derivedData)
- dm->release(dm);
+ return smokeModifier_do(smd, md->scene, ob, dm);
}
static int dependsOnTime(ModifierData *UNUSED(md))
@@ -102,11 +114,11 @@ static int dependsOnTime(ModifierData *UNUSED(md))
}
static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Scene *scene,
- Object *UNUSED(ob),
+ struct Scene *scene, struct Object *ob,
DagNode *obNode)
{
SmokeModifierData *smd = (SmokeModifierData *) md;
+ Base *base;
if (smd && (smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain) {
if (smd->domain->fluid_group || smd->domain->coll_group) {
@@ -139,8 +151,7 @@ static void updateDepgraph(ModifierData *md, DagForest *forest,
}
}
else {
- Base *base = scene->base.first;
-
+ base = scene->base.first;
for (; base; base = base->next) {
SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(base->object, eModifierType_Smoke);
@@ -150,6 +161,14 @@ static void updateDepgraph(ModifierData *md, DagForest *forest,
}
}
}
+ /* add relation to all "smoke flow" force fields */
+ base = scene->base.first;
+ for (; base; base = base->next) {
+ if (base->object->pd && base->object->pd->forcefield == PFIELD_SMOKEFLOW && base->object->pd->f_source == ob) {
+ DagNode *node2 = dag_get_node(forest, base->object);
+ dag_add_relation(forest, obNode, node2, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Field Source Object");
+ }
+ }
}
}
@@ -167,26 +186,30 @@ static void foreachIDLink(ModifierData *md, Object *ob,
walk(userData, ob, (ID **)&smd->domain->effector_weights->group);
}
}
+
+ if (smd->type == MOD_SMOKE_TYPE_FLOW && smd->flow) {
+ walk(userData, ob, (ID **)&smd->flow->noise_texture);
+ }
}
ModifierTypeInfo modifierType_Smoke = {
/* name */ "Smoke",
/* structName */ "SmokeModifierData",
/* structSize */ sizeof(SmokeModifierData),
- /* type */ eModifierTypeType_OnlyDeform,
+ /* type */ eModifierTypeType_Constructive,
/* flags */ eModifierTypeFlag_AcceptsMesh |
eModifierTypeFlag_UsesPointCache |
eModifierTypeFlag_Single,
/* copyData */ copyData,
- /* deformVerts */ deformVerts,
+ /* deformVerts */ NULL,
/* deformMatrices */ NULL,
/* deformVertsEM */ NULL,
/* deformMatricesEM */ NULL,
- /* applyModifier */ NULL,
+ /* applyModifier */ applyModifier,
/* applyModifierEM */ NULL,
/* initData */ initData,
- /* requiredDataMask */ NULL,
+ /* requiredDataMask */ requiredDataMask,
/* freeData */ freeData,
/* isDisabled */ NULL,
/* updateDepgraph */ updateDepgraph,
diff --git a/source/blender/modifiers/intern/MOD_smooth.c b/source/blender/modifiers/intern/MOD_smooth.c
index 545e2135344..1d35d8f55bf 100644
--- a/source/blender/modifiers/intern/MOD_smooth.c
+++ b/source/blender/modifiers/intern/MOD_smooth.c
@@ -250,7 +250,7 @@ ModifierTypeInfo modifierType_Smooth = {
/* structSize */ sizeof(SmoothModifierData),
/* type */ eModifierTypeType_OnlyDeform,
/* flags */ eModifierTypeFlag_AcceptsMesh |
- eModifierTypeFlag_AcceptsCVs |
+ eModifierTypeFlag_AcceptsCVs |
eModifierTypeFlag_SupportsEditmode,
/* copyData */ copyData,
diff --git a/source/blender/modifiers/intern/MOD_solidify.c b/source/blender/modifiers/intern/MOD_solidify.c
index fc74b446762..cc77d73a736 100644
--- a/source/blender/modifiers/intern/MOD_solidify.c
+++ b/source/blender/modifiers/intern/MOD_solidify.c
@@ -107,7 +107,7 @@ static void dm_calc_normal(DerivedMesh *dm, float (*temp_nors)[3])
f_no = face_nors[i];
if (calc_face_nors)
- mesh_calc_poly_normal(mp, mloop + mp->loopstart, mvert, f_no);
+ BKE_mesh_calc_poly_normal(mp, mloop + mp->loopstart, mvert, f_no);
ml = mloop + mp->loopstart;
@@ -223,7 +223,6 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
const int numEdges = dm->getNumEdges(dm);
const int numFaces = dm->getNumPolys(dm);
int numLoops = 0, newLoops = 0, newFaces = 0, newEdges = 0;
- int j;
/* only use material offsets if we have 2 or more materials */
const short mat_nr_max = ob->totcol > 1 ? ob->totcol - 1 : 0;
@@ -292,9 +291,11 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
}
for (i = 0, mp = orig_mpoly; i < numFaces; i++, mp++) {
- MLoop *ml = orig_mloop + mp->loopstart;
unsigned int ml_v1;
unsigned int ml_v2;
+ int j;
+
+ ml = orig_mloop + mp->loopstart;
for (j = 0, ml_v1 = ml->v, ml_v2 = ml[mp->totloop - 1].v;
j < mp->totloop;
@@ -376,6 +377,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
for (i = 0; i < dm->numPolyData; i++, mp++) {
MLoop *ml2;
int e;
+ int j;
ml2 = mloop + mp->loopstart + dm->numLoopData;
for (j = 0; j < mp->totloop; j++) {
@@ -483,7 +485,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
/* --- not related to angle calc --- */
if (face_nors_calc)
- mesh_calc_poly_normal(mp, ml, mvert, face_nors[i]);
+ BKE_mesh_calc_poly_normal(mp, ml, mvert, face_nors[i]);
/* --- end non-angle-calc section --- */
sub_v3_v3v3(nor_prev, mvert[ml[i_this - 1].v].co, mvert[ml[i_this].v].co);
@@ -591,6 +593,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
int *origindex_edge;
int *orig_ed;
+ int j;
/* add faces & edges */
origindex_edge = result->getEdgeDataArray(result, CD_ORIGINDEX);
@@ -635,15 +638,15 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
/* notice we use 'mp->totloop' which is later overwritten,
* we could lookup the original face but theres no point since this is a copy
* and will have the same value, just take care when changing order of assignment */
- k1 = mpoly[fidx].loopstart + ((edge_order[eidx] + 1) % mp->totloop);
+ k1 = mpoly[fidx].loopstart + (((edge_order[eidx] - 1) + mp->totloop) % mp->totloop); /* prev loop */
k2 = mpoly[fidx].loopstart + (edge_order[eidx]);
mp->totloop = 4;
- CustomData_copy_data(&dm->loopData, &result->loopData, k1, numLoops * 2 + j + 0, 1);
- CustomData_copy_data(&dm->loopData, &result->loopData, k2, numLoops * 2 + j + 1, 1);
- CustomData_copy_data(&dm->loopData, &result->loopData, k2, numLoops * 2 + j + 2, 1);
- CustomData_copy_data(&dm->loopData, &result->loopData, k1, numLoops * 2 + j + 3, 1);
+ CustomData_copy_data(&dm->loopData, &result->loopData, k2, numLoops * 2 + j + 0, 1);
+ CustomData_copy_data(&dm->loopData, &result->loopData, k1, numLoops * 2 + j + 1, 1);
+ CustomData_copy_data(&dm->loopData, &result->loopData, k1, numLoops * 2 + j + 2, 1);
+ CustomData_copy_data(&dm->loopData, &result->loopData, k2, numLoops * 2 + j + 3, 1);
if (flip == FALSE) {
ml[j].v = ed->v1;
@@ -715,13 +718,13 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
for (i = 0; i < newEdges; i++, ed++) {
float nor_cpy[3];
short *nor_short;
- int j;
+ int k;
/* note, only the first vertex (lower half of the index) is calculated */
normalize_v3_v3(nor_cpy, edge_vert_nos[ed->v1]);
- for (j = 0; j < 2; j++) { /* loop over both verts of the edge */
- nor_short = mvert[*(&ed->v1 + j)].no;
+ for (k = 0; k < 2; k++) { /* loop over both verts of the edge */
+ nor_short = mvert[*(&ed->v1 + k)].no;
normal_short_to_float_v3(nor, nor_short);
add_v3_v3(nor, nor_cpy);
normalize_v3(nor);
diff --git a/source/blender/modifiers/intern/MOD_util.c b/source/blender/modifiers/intern/MOD_util.c
index 1dbbe14e643..3b769a30994 100644
--- a/source/blender/modifiers/intern/MOD_util.c
+++ b/source/blender/modifiers/intern/MOD_util.c
@@ -199,7 +199,7 @@ DerivedMesh *get_dm(Object *ob, struct BMEditMesh *em, DerivedMesh *dm, float (*
return dm;
if (ob->type == OB_MESH) {
- if (em) dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE);
+ if (em) dm = CDDM_from_editbmesh(em, FALSE, FALSE);
else dm = CDDM_from_mesh((struct Mesh *)(ob->data), ob);
if (vertexCos) {
@@ -222,7 +222,7 @@ void modifier_get_vgroup(Object *ob, DerivedMesh *dm, const char *name, MDeformV
*defgrp_index = defgroup_name_index(ob, name);
*dvert = NULL;
- if (*defgrp_index >= 0) {
+ if (*defgrp_index != -1) {
if (ob->type == OB_LATTICE)
*dvert = BKE_lattice_deform_verts_get(ob);
else if (dm)
@@ -277,5 +277,6 @@ void modifier_type_init(ModifierTypeInfo *types[])
INIT_TYPE(DynamicPaint);
INIT_TYPE(Remesh);
INIT_TYPE(Skin);
+ INIT_TYPE(LaplacianSmooth);
#undef INIT_TYPE
}
diff --git a/source/blender/modifiers/intern/MOD_util.h b/source/blender/modifiers/intern/MOD_util.h
index eadf7af553b..6f05c9a957a 100644
--- a/source/blender/modifiers/intern/MOD_util.h
+++ b/source/blender/modifiers/intern/MOD_util.h
@@ -42,10 +42,14 @@ struct TexResult;
void modifier_init_texture(struct Scene *scene, struct Tex *texture);
void get_texture_value(struct Tex *texture, float *tex_co, struct TexResult *texres);
-void get_texture_coords(struct MappingInfoModifierData *dmd, struct Object *ob, struct DerivedMesh *dm, float (*co)[3], float (*texco)[3], int numVerts);
+void get_texture_coords(struct MappingInfoModifierData *dmd, struct Object *ob, struct DerivedMesh *dm,
+ float (*co)[3], float (*texco)[3], int numVerts);
void modifier_vgroup_cache(struct ModifierData *md, float (*vertexCos)[3]);
-struct DerivedMesh *get_cddm(struct Object *ob, struct BMEditMesh *em, struct DerivedMesh *dm, float (*vertexCos)[3]);
-struct DerivedMesh *get_dm(struct Object *ob, struct BMEditMesh *em, struct DerivedMesh *dm, float (*vertexCos)[3], int orco);
-void modifier_get_vgroup(struct Object *ob, struct DerivedMesh *dm, const char *name, struct MDeformVert **dvert, int *defgrp_index);
+struct DerivedMesh *get_cddm(struct Object *ob, struct BMEditMesh *em, struct DerivedMesh *dm,
+ float (*vertexCos)[3]);
+struct DerivedMesh *get_dm(struct Object *ob, struct BMEditMesh *em, struct DerivedMesh *dm,
+ float (*vertexCos)[3], int orco);
+void modifier_get_vgroup(struct Object *ob, struct DerivedMesh *dm,
+ const char *name, struct MDeformVert **dvert, int *defgrp_index);
#endif /* __MOD_UTIL_H__ */
diff --git a/source/blender/modifiers/intern/MOD_uvproject.c b/source/blender/modifiers/intern/MOD_uvproject.c
index eb5a74f0dcc..88951919272 100644
--- a/source/blender/modifiers/intern/MOD_uvproject.c
+++ b/source/blender/modifiers/intern/MOD_uvproject.c
@@ -157,7 +157,6 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
int override_image = ((umd->flags & MOD_UVPROJECT_OVERRIDEIMAGE) != 0);
Projector projectors[MOD_UVPROJECT_MAXPROJECTORS];
int num_projectors = 0;
- float aspect;
char uvname[MAX_CUSTOMDATA_LAYER_NAME];
float aspx = umd->aspectx ? umd->aspectx : 1.0f;
float aspy = umd->aspecty ? umd->aspecty : 1.0f;
@@ -165,8 +164,6 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
float scay = umd->scaley ? umd->scaley : 1.0f;
int free_uci = 0;
- aspect = aspx / aspy;
-
for (i = 0; i < umd->num_projectors; ++i)
if (umd->projectors[i])
projectors[num_projectors++].ob = umd->projectors[i];
@@ -199,39 +196,23 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
free_uci = 1;
}
else {
- float sensor = BKE_camera_sensor_size(cam->sensor_fit, cam->sensor_x, cam->sensor_y);
- int sensor_fit = BKE_camera_sensor_fit(cam->sensor_fit, aspx, aspy);
- float scale = (cam->type == CAM_PERSP) ? cam->clipsta * sensor / cam->lens : cam->ortho_scale;
- float xmax, xmin, ymax, ymin;
-
- if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
- xmax = 0.5f * scale;
- ymax = xmax / aspect;
- }
- else {
- ymax = 0.5f * scale;
- xmax = ymax * aspect;
- }
+ CameraParams params;
- xmin = -xmax;
- ymin = -ymax;
+ /* setup parameters */
+ BKE_camera_params_init(&params);
+ BKE_camera_params_from_object(&params, projectors[i].ob);
- /* scale the matrix */
- xmin *= scax;
- xmax *= scax;
- ymin *= scay;
- ymax *= scay;
+ /* compute matrix, viewplane, .. */
+ BKE_camera_params_compute_viewplane(&params, 1, 1, aspx, aspy);
- if (cam->type == CAM_PERSP) {
- float perspmat[4][4];
- perspective_m4(perspmat, xmin, xmax, ymin, ymax, cam->clipsta, cam->clipend);
- mult_m4_m4m4(tmpmat, perspmat, projectors[i].projmat);
- }
- else { /* if (cam->type == CAM_ORTHO) */
- float orthomat[4][4];
- orthographic_m4(orthomat, xmin, xmax, ymin, ymax, cam->clipsta, cam->clipend);
- mult_m4_m4m4(tmpmat, orthomat, projectors[i].projmat);
- }
+ /* scale the view-plane */
+ params.viewplane.xmin *= scax;
+ params.viewplane.xmax *= scax;
+ params.viewplane.ymin *= scay;
+ params.viewplane.ymax *= scay;
+
+ BKE_camera_params_compute_matrix(&params);
+ mult_m4_m4m4(tmpmat, params.winmat, projectors[i].projmat);
}
}
else {
@@ -241,22 +222,7 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
unit_m4(offsetmat);
mul_mat3_m4_fl(offsetmat, 0.5);
offsetmat[3][0] = offsetmat[3][1] = offsetmat[3][2] = 0.5;
-
- if (cam) {
- if (aspx == aspy) {
- offsetmat[3][0] -= cam->shiftx;
- offsetmat[3][1] -= cam->shifty;
- }
- else if (aspx < aspy) {
- offsetmat[3][0] -= (cam->shiftx * aspy / aspx);
- offsetmat[3][1] -= cam->shifty;
- }
- else {
- offsetmat[3][0] -= cam->shiftx;
- offsetmat[3][1] -= (cam->shifty * aspx / aspy);
- }
- }
-
+
mult_m4_m4m4(projectors[i].projmat, offsetmat, tmpmat);
/* calculate worldspace projector normal (for best projector test) */
diff --git a/source/blender/modifiers/intern/MOD_warp.c b/source/blender/modifiers/intern/MOD_warp.c
index 95f6ef60665..c2a62231529 100644
--- a/source/blender/modifiers/intern/MOD_warp.c
+++ b/source/blender/modifiers/intern/MOD_warp.c
@@ -238,7 +238,7 @@ static void warpModifier_do(WarpModifierData *wmd, Object *ob,
(fac = (wmd->falloff_radius - fac) / wmd->falloff_radius)))
{
/* skip if no vert group found */
- if (dvert && defgrp_index >= 0) {
+ if (dvert && defgrp_index != -1) {
dv = &dvert[i];
if (dv) {
@@ -337,7 +337,7 @@ static void deformVerts(ModifierData *md, Object *ob, DerivedMesh *derivedData,
}
}
-static void deformVertsEM(ModifierData *md, Object *ob, struct BMEditMesh *editData,
+static void deformVertsEM(ModifierData *md, Object *ob, struct BMEditMesh *em,
DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
@@ -345,7 +345,7 @@ static void deformVertsEM(ModifierData *md, Object *ob, struct BMEditMesh *editD
if (use_dm) {
if (!derivedData)
- dm = CDDM_from_BMEditMesh(editData, ob->data, FALSE, FALSE);
+ dm = CDDM_from_editbmesh(em, FALSE, FALSE);
}
deformVerts(md, ob, dm, vertexCos, numVerts, 0);
@@ -357,27 +357,27 @@ static void deformVertsEM(ModifierData *md, Object *ob, struct BMEditMesh *editD
ModifierTypeInfo modifierType_Warp = {
- /* name */ "Warp",
- /* structName */ "WarpModifierData",
- /* structSize */ sizeof(WarpModifierData),
- /* type */ eModifierTypeType_OnlyDeform,
- /* flags */ eModifierTypeFlag_AcceptsCVs |
- eModifierTypeFlag_SupportsEditmode,
- /* copyData */ copyData,
- /* deformVerts */ deformVerts,
- /* deformMatrices */ NULL,
- /* deformVertsEM */ deformVertsEM,
- /* deformMatricesEM */ NULL,
- /* applyModifier */ 0,
- /* applyModifierEM */ 0,
- /* initData */ initData,
- /* requiredDataMask */ requiredDataMask,
- /* freeData */ freeData,
- /* isDisabled */ isDisabled,
- /* updateDepgraph */ updateDepgraph,
- /* dependsOnTime */ dependsOnTime,
- /* dependsOnNormals */ NULL,
+ /* name */ "Warp",
+ /* structName */ "WarpModifierData",
+ /* structSize */ sizeof(WarpModifierData),
+ /* type */ eModifierTypeType_OnlyDeform,
+ /* flags */ eModifierTypeFlag_AcceptsCVs |
+ eModifierTypeFlag_SupportsEditmode,
+ /* copyData */ copyData,
+ /* deformVerts */ deformVerts,
+ /* deformMatrices */ NULL,
+ /* deformVertsEM */ deformVertsEM,
+ /* deformMatricesEM */ NULL,
+ /* applyModifier */ 0,
+ /* applyModifierEM */ 0,
+ /* initData */ initData,
+ /* requiredDataMask */ requiredDataMask,
+ /* freeData */ freeData,
+ /* isDisabled */ isDisabled,
+ /* updateDepgraph */ updateDepgraph,
+ /* dependsOnTime */ dependsOnTime,
+ /* dependsOnNormals */ NULL,
/* foreachObjectLink */ foreachObjectLink,
- /* foreachIDLink */ foreachIDLink,
- /* foreachTexLink */ foreachTexLink,
+ /* foreachIDLink */ foreachIDLink,
+ /* foreachTexLink */ foreachTexLink,
};
diff --git a/source/blender/modifiers/intern/MOD_wave.c b/source/blender/modifiers/intern/MOD_wave.c
index 440d2c157fe..b713f56a4c2 100644
--- a/source/blender/modifiers/intern/MOD_wave.c
+++ b/source/blender/modifiers/intern/MOD_wave.c
@@ -186,7 +186,7 @@ static void waveModifier_do(WaveModifierData *md,
const float falloff = wmd->falloff;
float falloff_fac = 1.0f; /* when falloff == 0.0f this stays at 1.0f */
- if (wmd->flag & MOD_WAVE_NORM && ob->type == OB_MESH)
+ if ((wmd->flag & MOD_WAVE_NORM) && (ob->type == OB_MESH))
mvert = dm->getVertArray(dm);
if (wmd->objectcenter) {
diff --git a/source/blender/modifiers/intern/MOD_weightvgedit.c b/source/blender/modifiers/intern/MOD_weightvgedit.c
index ce6295e30cf..779ac6b5ecf 100644
--- a/source/blender/modifiers/intern/MOD_weightvgedit.c
+++ b/source/blender/modifiers/intern/MOD_weightvgedit.c
@@ -185,7 +185,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
float *org_w; /* Array original weights. */
float *new_w; /* Array new weights. */
int numVerts;
- int defgrp_idx;
+ int defgrp_index;
int i;
/* Flags. */
int do_add = (wmd->edit_flags & MOD_WVG_EDIT_ADD2VG) != 0;
@@ -205,8 +205,8 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
return dm;
/* Get vgroup idx from its name. */
- defgrp_idx = defgroup_name_index(ob, wmd->defgrp_name);
- if (defgrp_idx < 0)
+ defgrp_index = defgroup_name_index(ob, wmd->defgrp_name);
+ if (defgrp_index == -1)
return dm;
dvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MDEFORMVERT, numVerts);
@@ -228,7 +228,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
new_w = MEM_mallocN(sizeof(float) * numVerts, "WeightVGEdit Modifier, new_w");
dw = MEM_mallocN(sizeof(MDeformWeight *) * numVerts, "WeightVGEdit Modifier, dw");
for (i = 0; i < numVerts; i++) {
- dw[i] = defvert_find_index(&dvert[i], defgrp_idx);
+ dw[i] = defvert_find_index(&dvert[i], defgrp_index);
if (dw[i]) {
org_w[i] = new_w[i] = dw[i]->weight;
}
@@ -249,7 +249,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
wmd->mask_tex_map_obj, wmd->mask_tex_uvlayer_name);
/* Update/add/remove from vgroup. */
- weightvg_update_vg(dvert, defgrp_idx, dw, numVerts, NULL, org_w, do_add, wmd->add_threshold,
+ weightvg_update_vg(dvert, defgrp_index, dw, numVerts, NULL, org_w, do_add, wmd->add_threshold,
do_rem, wmd->rem_threshold);
/* If weight preview enabled... */
diff --git a/source/blender/modifiers/intern/MOD_weightvgmix.c b/source/blender/modifiers/intern/MOD_weightvgmix.c
index 2961082b448..5883b176317 100644
--- a/source/blender/modifiers/intern/MOD_weightvgmix.c
+++ b/source/blender/modifiers/intern/MOD_weightvgmix.c
@@ -225,7 +225,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
MDeformVert *dvert = NULL;
MDeformWeight **dw1, **tdw1, **dw2, **tdw2;
int numVerts;
- int defgrp_idx, defgrp_idx2 = -1;
+ int defgrp_index, defgrp_index_other = -1;
float *org_w;
float *new_w;
int *tidx, *indices = NULL;
@@ -246,13 +246,13 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
return dm;
/* Get vgroup idx from its name. */
- defgrp_idx = defgroup_name_index(ob, wmd->defgrp_name_a);
- if (defgrp_idx < 0)
+ defgrp_index = defgroup_name_index(ob, wmd->defgrp_name_a);
+ if (defgrp_index == -1)
return dm;
/* Get seconf vgroup idx from its name, if given. */
if (wmd->defgrp_name_b[0] != (char)0) {
- defgrp_idx2 = defgroup_name_index(ob, wmd->defgrp_name_b);
- if (defgrp_idx2 < 0)
+ defgrp_index_other = defgroup_name_index(ob, wmd->defgrp_name_b);
+ if (defgrp_index_other == -1)
return dm;
}
@@ -277,10 +277,10 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
case MOD_WVG_SET_A:
/* All vertices in first vgroup. */
for (i = 0; i < numVerts; i++) {
- MDeformWeight *dw = defvert_find_index(&dvert[i], defgrp_idx);
+ MDeformWeight *dw = defvert_find_index(&dvert[i], defgrp_index);
if (dw) {
tdw1[numIdx] = dw;
- tdw2[numIdx] = defvert_find_index(&dvert[i], defgrp_idx2);
+ tdw2[numIdx] = defvert_find_index(&dvert[i], defgrp_index_other);
tidx[numIdx++] = i;
}
}
@@ -288,9 +288,9 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
case MOD_WVG_SET_B:
/* All vertices in second vgroup. */
for (i = 0; i < numVerts; i++) {
- MDeformWeight *dw = defvert_find_index(&dvert[i], defgrp_idx2);
+ MDeformWeight *dw = defvert_find_index(&dvert[i], defgrp_index_other);
if (dw) {
- tdw1[numIdx] = defvert_find_index(&dvert[i], defgrp_idx);
+ tdw1[numIdx] = defvert_find_index(&dvert[i], defgrp_index);
tdw2[numIdx] = dw;
tidx[numIdx++] = i;
}
@@ -299,8 +299,8 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
case MOD_WVG_SET_OR:
/* All vertices in one vgroup or the other. */
for (i = 0; i < numVerts; i++) {
- MDeformWeight *adw = defvert_find_index(&dvert[i], defgrp_idx);
- MDeformWeight *bdw = defvert_find_index(&dvert[i], defgrp_idx2);
+ MDeformWeight *adw = defvert_find_index(&dvert[i], defgrp_index);
+ MDeformWeight *bdw = defvert_find_index(&dvert[i], defgrp_index_other);
if (adw || bdw) {
tdw1[numIdx] = adw;
tdw2[numIdx] = bdw;
@@ -311,8 +311,8 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
case MOD_WVG_SET_AND:
/* All vertices in both vgroups. */
for (i = 0; i < numVerts; i++) {
- MDeformWeight *adw = defvert_find_index(&dvert[i], defgrp_idx);
- MDeformWeight *bdw = defvert_find_index(&dvert[i], defgrp_idx2);
+ MDeformWeight *adw = defvert_find_index(&dvert[i], defgrp_index);
+ MDeformWeight *bdw = defvert_find_index(&dvert[i], defgrp_index_other);
if (adw && bdw) {
tdw1[numIdx] = adw;
tdw2[numIdx] = bdw;
@@ -324,8 +324,8 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
default:
/* Use all vertices. */
for (i = 0; i < numVerts; i++) {
- tdw1[i] = defvert_find_index(&dvert[i], defgrp_idx);
- tdw2[i] = defvert_find_index(&dvert[i], defgrp_idx2);
+ tdw1[i] = defvert_find_index(&dvert[i], defgrp_index);
+ tdw2[i] = defvert_find_index(&dvert[i], defgrp_index_other);
}
numIdx = -1;
break;
@@ -377,7 +377,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
/* Update (add to) vgroup.
* XXX Depending on the MOD_WVG_SET_xxx option chosen, we might have to add vertices to vgroup.
*/
- weightvg_update_vg(dvert, defgrp_idx, dw1, numIdx, indices, org_w, TRUE, -FLT_MAX, FALSE, 0.0f);
+ weightvg_update_vg(dvert, defgrp_index, dw1, numIdx, indices, org_w, TRUE, -FLT_MAX, FALSE, 0.0f);
/* If weight preview enabled... */
#if 0 /* XXX Currently done in mod stack :/ */
diff --git a/source/blender/modifiers/intern/MOD_weightvgproximity.c b/source/blender/modifiers/intern/MOD_weightvgproximity.c
index 25a2a61d8e3..e936e571a5b 100644
--- a/source/blender/modifiers/intern/MOD_weightvgproximity.c
+++ b/source/blender/modifiers/intern/MOD_weightvgproximity.c
@@ -347,7 +347,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
int numVerts;
float (*v_cos)[3] = NULL; /* The vertices coordinates. */
Object *obr = NULL; /* Our target object. */
- int defgrp_idx;
+ int defgrp_index;
float *tw = NULL;
float *org_w = NULL;
float *new_w = NULL;
@@ -378,8 +378,8 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
return dm;
/* Get vgroup idx from its name. */
- defgrp_idx = defgroup_name_index(ob, wmd->defgrp_name);
- if (defgrp_idx < 0)
+ defgrp_index = defgroup_name_index(ob, wmd->defgrp_name);
+ if (defgrp_index == -1)
return dm;
dvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MDEFORMVERT, numVerts);
@@ -394,7 +394,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
tw = MEM_mallocN(sizeof(float) * numVerts, "WeightVGProximity Modifier, tw");
tdw = MEM_mallocN(sizeof(MDeformWeight *) * numVerts, "WeightVGProximity Modifier, tdw");
for (i = 0; i < numVerts; i++) {
- MDeformWeight *_dw = defvert_find_index(&dvert[i], defgrp_idx);
+ MDeformWeight *_dw = defvert_find_index(&dvert[i], defgrp_index);
if (_dw) {
tidx[numIdx] = i;
tw[numIdx] = _dw->weight;
@@ -460,7 +460,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
else if (obr->type == OB_MESH) {
Mesh *me = (Mesh *)obr->data;
if (me->edit_btmesh)
- target_dm = CDDM_from_BMEditMesh(me->edit_btmesh, me, FALSE, FALSE);
+ target_dm = CDDM_from_editbmesh(me->edit_btmesh, FALSE, FALSE);
else
target_dm = CDDM_from_mesh(me, obr);
}
@@ -480,9 +480,9 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
for (i = 0; i < numIdx; i++) {
new_w[i] = dists_v ? dists_v[i] : FLT_MAX;
if (dists_e)
- new_w[i] = minf(dists_e[i], new_w[i]);
+ new_w[i] = min_ff(dists_e[i], new_w[i]);
if (dists_f)
- new_w[i] = minf(dists_f[i], new_w[i]);
+ new_w[i] = min_ff(dists_f[i], new_w[i]);
}
if (free_target_dm) target_dm->release(target_dm);
if (dists_v) MEM_freeN(dists_v);
@@ -509,7 +509,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
wmd->mask_tex_map_obj, wmd->mask_tex_uvlayer_name);
/* Update vgroup. Note we never add nor remove vertices from vgroup here. */
- weightvg_update_vg(dvert, defgrp_idx, dw, numIdx, indices, org_w, FALSE, 0.0f, FALSE, 0.0f);
+ weightvg_update_vg(dvert, defgrp_index, dw, numIdx, indices, org_w, FALSE, 0.0f, FALSE, 0.0f);
/* If weight preview enabled... */
#if 0 /* XXX Currently done in mod stack :/ */
diff --git a/source/blender/nodes/CMakeLists.txt b/source/blender/nodes/CMakeLists.txt
index 08e0e7b0f93..323a534c989 100644
--- a/source/blender/nodes/CMakeLists.txt
+++ b/source/blender/nodes/CMakeLists.txt
@@ -23,8 +23,12 @@
#
# ***** END GPL LICENSE BLOCK *****
-set(INC
+set(INC
.
+ composite
+ intern
+ shader
+ texture
../blenfont
../blenkernel
../blenlib
@@ -39,10 +43,6 @@ set(INC
set(INC_SYS
${GLEW_INCLUDE_PATH}
- intern
- composite
- shader
- texture
)
set(SRC
@@ -119,7 +119,8 @@ set(SRC
composite/nodes/node_composite_ellipsemask.c
composite/nodes/node_composite_switch.c
composite/nodes/node_composite_colorcorrection.c
-
+ composite/nodes/node_composite_pixelate.c
+
composite/node_composite_tree.c
composite/node_composite_util.c
@@ -146,13 +147,14 @@ set(SRC
shader/nodes/node_shader_vectMath.c
shader/nodes/node_shader_attribute.c
shader/nodes/node_shader_background.c
- # shader/nodes/node_shader_bsdf_anisotropic.c # XXX, why not included?
+ shader/nodes/node_shader_bsdf_anisotropic.c
shader/nodes/node_shader_bsdf_diffuse.c
shader/nodes/node_shader_bsdf_glossy.c
shader/nodes/node_shader_bsdf_glass.c
shader/nodes/node_shader_bsdf_translucent.c
shader/nodes/node_shader_bsdf_transparent.c
shader/nodes/node_shader_bsdf_velvet.c
+ shader/nodes/node_shader_bump.c
shader/nodes/node_shader_emission.c
shader/nodes/node_shader_fresnel.c
shader/nodes/node_shader_layer_weight.c
@@ -163,6 +165,7 @@ set(SRC
shader/nodes/node_shader_light_path.c
shader/nodes/node_shader_light_falloff.c
shader/nodes/node_shader_object_info.c
+ shader/nodes/node_shader_script.c
shader/nodes/node_shader_particle_info.c
shader/nodes/node_shader_mix_shader.c
shader/nodes/node_shader_add_shader.c
diff --git a/source/blender/nodes/NOD_composite.h b/source/blender/nodes/NOD_composite.h
index bcef230e1d0..ee67ac88085 100644
--- a/source/blender/nodes/NOD_composite.h
+++ b/source/blender/nodes/NOD_composite.h
@@ -96,7 +96,7 @@ void register_node_type_cmp_combhsva(struct bNodeTreeType *ttype);
void register_node_type_cmp_sepyuva(struct bNodeTreeType *ttype);
void register_node_type_cmp_combyuva(struct bNodeTreeType *ttype);
void register_node_type_cmp_sepycca(struct bNodeTreeType *ttype);
-void register_node_type_cmp_combycca(struct bNodeTreeType *ttype);
+void register_node_type_cmp_combycca(struct bNodeTreeType *ttype);
void register_node_type_cmp_premulkey(struct bNodeTreeType *ttype);
void register_node_type_cmp_diff_matte(struct bNodeTreeType *ttype);
@@ -105,7 +105,7 @@ void register_node_type_cmp_chroma_matte(struct bNodeTreeType *ttype);
void register_node_type_cmp_color_matte(struct bNodeTreeType *ttype);
void register_node_type_cmp_channel_matte(struct bNodeTreeType *ttype);
void register_node_type_cmp_color_spill(struct bNodeTreeType *ttype);
-void register_node_type_cmp_luma_matte(struct bNodeTreeType *ttype);
+void register_node_type_cmp_luma_matte(struct bNodeTreeType *ttype);
void register_node_type_cmp_doubleedgemask(struct bNodeTreeType *ttype);
void register_node_type_cmp_keyingscreen(struct bNodeTreeType *ttype);
void register_node_type_cmp_keying(struct bNodeTreeType *ttype);
@@ -133,7 +133,7 @@ void register_node_type_cmp_ellipsemask(struct bNodeTreeType *ttype);
void register_node_type_cmp_bokehimage(struct bNodeTreeType *ttype);
void register_node_type_cmp_bokehblur(struct bNodeTreeType *ttype);
void register_node_type_cmp_switch(struct bNodeTreeType *ttype);
-
+void register_node_type_cmp_pixelate(struct bNodeTreeType *ttype);
void register_node_type_cmp_trackpos(struct bNodeTreeType *ttype);
#endif
diff --git a/source/blender/nodes/NOD_shader.h b/source/blender/nodes/NOD_shader.h
index 49428c06e5f..66ab15ce29f 100644
--- a/source/blender/nodes/NOD_shader.h
+++ b/source/blender/nodes/NOD_shader.h
@@ -80,6 +80,7 @@ void register_node_type_sh_fresnel(struct bNodeTreeType *ttype);
void register_node_type_sh_layer_weight(struct bNodeTreeType *ttype);
void register_node_type_sh_tex_coord(struct bNodeTreeType *ttype);
void register_node_type_sh_particle_info(struct bNodeTreeType *ttype);
+void register_node_type_sh_script(struct bNodeTreeType *ttype);
void register_node_type_sh_background(struct bNodeTreeType *ttype);
void register_node_type_sh_bsdf_diffuse(struct bNodeTreeType *ttype);
@@ -88,6 +89,7 @@ void register_node_type_sh_bsdf_glass(struct bNodeTreeType *ttype);
void register_node_type_sh_bsdf_translucent(struct bNodeTreeType *ttype);
void register_node_type_sh_bsdf_transparent(struct bNodeTreeType *ttype);
void register_node_type_sh_bsdf_velvet(struct bNodeTreeType *ttype);
+void register_node_type_sh_bsdf_anisotropic(struct bNodeTreeType *ttype);
void register_node_type_sh_emission(struct bNodeTreeType *ttype);
void register_node_type_sh_holdout(struct bNodeTreeType *ttype);
void register_node_type_sh_volume_transparent(struct bNodeTreeType *ttype);
@@ -109,6 +111,7 @@ void register_node_type_sh_tex_wave(struct bNodeTreeType *ttype);
void register_node_type_sh_tex_musgrave(struct bNodeTreeType *ttype);
void register_node_type_sh_tex_noise(struct bNodeTreeType *ttype);
void register_node_type_sh_tex_checker(struct bNodeTreeType *ttype);
+void register_node_type_sh_bump(struct bNodeTreeType *ttype);
#endif
diff --git a/source/blender/nodes/composite/node_composite_tree.c b/source/blender/nodes/composite/node_composite_tree.c
index c9960df1345..9a7e587ff56 100644
--- a/source/blender/nodes/composite/node_composite_tree.c
+++ b/source/blender/nodes/composite/node_composite_tree.c
@@ -226,7 +226,7 @@ static void local_merge(bNodeTree *localtree, bNodeTree *ntree)
}
else if (lnode->type==CMP_NODE_MOVIEDISTORTION) {
/* special case for distortion node: distortion context is allocating in exec function
- * and to achive much better performance on further calls this context should be
+ * and to achieve much better performance on further calls this context should be
* copied back to original node */
if (lnode->storage) {
if (lnode->new_node->storage)
@@ -273,7 +273,7 @@ bNodeTreeType ntreeType_Composite = {
/* update */ update,
/* update_node */ update_node,
/* validate_link */ NULL,
- /* internal_connect */ node_internal_connect_default
+ /* update_internal_links */ node_update_internal_links_default
};
@@ -301,7 +301,7 @@ struct bNodeTreeExec *ntreeCompositBeginExecTree(bNodeTree *ntree, int use_tree_
for (node= exec->nodetree->nodes.first; node; node= node->next) {
/* initialize needed for groups */
- node->exec= 0;
+ node->exec= 0;
for (sock= node->outputs.first; sock; sock= sock->next) {
bNodeStack *ns= node_get_socket_stack(exec->stack, sock);
@@ -515,9 +515,9 @@ static int setExecutableNodes(bNodeTreeExec *exec, ThreadData *thd)
static void freeExecutableNode(bNodeTreeExec *exec)
{
/* node outputs can be freed when:
- - not a render result or image node
- - when node outputs go to nodes all being set NODE_FINISHED
- */
+ * - not a render result or image node
+ * - when node outputs go to nodes all being set NODE_FINISHED
+ */
bNodeTree *ntree = exec->nodetree;
bNodeExec *nodeexec;
bNode *node;
diff --git a/source/blender/nodes/composite/node_composite_util.c b/source/blender/nodes/composite/node_composite_util.c
index fe4eebc9492..57eb99021f6 100644
--- a/source/blender/nodes/composite/node_composite_util.c
+++ b/source/blender/nodes/composite/node_composite_util.c
@@ -72,7 +72,7 @@ CompBuf *dupalloc_compbuf(CompBuf *cbuf)
dupbuf->xof= cbuf->xof;
dupbuf->yof= cbuf->yof;
- }
+ }
return dupbuf;
}
@@ -94,7 +94,7 @@ CompBuf *pass_on_compbuf(CompBuf *cbuf)
break;
lastbuf->next= dupbuf;
dupbuf->prev= lastbuf;
- }
+ }
return dupbuf;
}
@@ -146,7 +146,7 @@ CompBuf *get_cropped_compbuf(rcti *drect, float *rectf, int rectx, int recty, in
if (disprect.xmin>= disprect.xmax) return NULL;
if (disprect.ymin>= disprect.ymax) return NULL;
- cbuf= alloc_compbuf(BLI_RCT_SIZE_X(&disprect), BLI_RCT_SIZE_Y(&disprect), type, 1);
+ cbuf= alloc_compbuf(BLI_rcti_size_x(&disprect), BLI_rcti_size_y(&disprect), type, 1);
outfp= cbuf->rect;
rectf += type*(disprect.ymin*rectx + disprect.xmin);
dx= type*cbuf->x;
@@ -213,53 +213,53 @@ void typecheck_compbuf_color(float *out, float *in, int outtype, int intype)
}
else if (outtype==CB_VEC2) {
if (intype==CB_VAL) {
- out[0]= in[0];
- out[1]= in[0];
+ out[0] = in[0];
+ out[1] = in[0];
}
else if (intype==CB_VEC3) {
- out[0]= in[0];
- out[1]= in[1];
+ out[0] = in[0];
+ out[1] = in[1];
}
else if (intype==CB_RGBA) {
- out[0]= in[0];
- out[1]= in[1];
+ out[0] = in[0];
+ out[1] = in[1];
}
}
else if (outtype==CB_VEC3) {
if (intype==CB_VAL) {
- out[0]= in[0];
- out[1]= in[0];
- out[2]= in[0];
+ out[0] = in[0];
+ out[1] = in[0];
+ out[2] = in[0];
}
else if (intype==CB_VEC2) {
- out[0]= in[0];
- out[1]= in[1];
- out[2]= 0.0f;
+ out[0] = in[0];
+ out[1] = in[1];
+ out[2] = 0.0f;
}
else if (intype==CB_RGBA) {
- out[0]= in[0];
- out[1]= in[1];
- out[2]= in[2];
+ out[0] = in[0];
+ out[1] = in[1];
+ out[2] = in[2];
}
}
else if (outtype==CB_RGBA) {
if (intype==CB_VAL) {
- out[0]= in[0];
- out[1]= in[0];
- out[2]= in[0];
- out[3]= 1.0f;
+ out[0] = in[0];
+ out[1] = in[0];
+ out[2] = in[0];
+ out[3] = 1.0f;
}
else if (intype==CB_VEC2) {
- out[0]= in[0];
- out[1]= in[1];
- out[2]= 0.0f;
- out[3]= 1.0f;
+ out[0] = in[0];
+ out[1] = in[1];
+ out[2] = 0.0f;
+ out[3] = 1.0f;
}
else if (intype==CB_VEC3) {
- out[0]= in[0];
- out[1]= in[1];
- out[2]= in[2];
- out[3]= 1.0f;
+ out[0] = in[0];
+ out[1] = in[1];
+ out[2] = in[2];
+ out[3] = 1.0f;
}
}
}
@@ -307,69 +307,69 @@ CompBuf *typecheck_compbuf(CompBuf *inbuf, int type)
else if (type==CB_VEC2) {
if (inbuf->type==CB_VAL) {
for (; x>0; x--, outrf+= 2, inrf+= 1) {
- outrf[0]= inrf[0];
- outrf[1]= inrf[0];
+ outrf[0] = inrf[0];
+ outrf[1] = inrf[0];
}
}
else if (inbuf->type==CB_VEC3) {
for (; x>0; x--, outrf+= 2, inrf+= 3) {
- outrf[0]= inrf[0];
- outrf[1]= inrf[1];
+ outrf[0] = inrf[0];
+ outrf[1] = inrf[1];
}
}
else if (inbuf->type==CB_RGBA) {
for (; x>0; x--, outrf+= 2, inrf+= 4) {
- outrf[0]= inrf[0];
- outrf[1]= inrf[1];
+ outrf[0] = inrf[0];
+ outrf[1] = inrf[1];
}
}
}
else if (type==CB_VEC3) {
if (inbuf->type==CB_VAL) {
for (; x>0; x--, outrf+= 3, inrf+= 1) {
- outrf[0]= inrf[0];
- outrf[1]= inrf[0];
- outrf[2]= inrf[0];
+ outrf[0] = inrf[0];
+ outrf[1] = inrf[0];
+ outrf[2] = inrf[0];
}
}
else if (inbuf->type==CB_VEC2) {
for (; x>0; x--, outrf+= 3, inrf+= 2) {
- outrf[0]= inrf[0];
- outrf[1]= inrf[1];
- outrf[2]= 0.0f;
+ outrf[0] = inrf[0];
+ outrf[1] = inrf[1];
+ outrf[2] = 0.0f;
}
}
else if (inbuf->type==CB_RGBA) {
for (; x>0; x--, outrf+= 3, inrf+= 4) {
- outrf[0]= inrf[0];
- outrf[1]= inrf[1];
- outrf[2]= inrf[2];
+ outrf[0] = inrf[0];
+ outrf[1] = inrf[1];
+ outrf[2] = inrf[2];
}
}
}
else if (type==CB_RGBA) {
if (inbuf->type==CB_VAL) {
for (; x>0; x--, outrf+= 4, inrf+= 1) {
- outrf[0]= inrf[0];
- outrf[1]= inrf[0];
- outrf[2]= inrf[0];
- outrf[3]= 1.0f;
+ outrf[0] = inrf[0];
+ outrf[1] = inrf[0];
+ outrf[2] = inrf[0];
+ outrf[3] = 1.0f;
}
}
else if (inbuf->type==CB_VEC2) {
for (; x>0; x--, outrf+= 4, inrf+= 2) {
- outrf[0]= inrf[0];
- outrf[1]= inrf[1];
- outrf[2]= 0.0f;
- outrf[3]= 1.0f;
+ outrf[0] = inrf[0];
+ outrf[1] = inrf[1];
+ outrf[2] = 0.0f;
+ outrf[3] = 1.0f;
}
}
else if (inbuf->type==CB_VEC3) {
for (; x>0; x--, outrf+= 4, inrf+= 3) {
- outrf[0]= inrf[0];
- outrf[1]= inrf[1];
- outrf[2]= inrf[2];
- outrf[3]= 1.0f;
+ outrf[0] = inrf[0];
+ outrf[1] = inrf[1];
+ outrf[2] = inrf[2];
+ outrf[3] = 1.0f;
}
}
}
@@ -387,7 +387,7 @@ float *compbuf_get_pixel(CompBuf *cbuf, float *defcol, float *use, int x, int y,
return use;
}
else {
- static float col[4]= {0.0f, 0.0f, 0.0f, 0.0f};
+ static float col[4] = {0.0f, 0.0f, 0.0f, 0.0f};
/* map coords */
x-= cbuf->xof;
@@ -707,18 +707,18 @@ void do_copy_rgba(bNode *UNUSED(node), float *out, float *in)
void do_copy_rgb(bNode *UNUSED(node), float *out, float *in)
{
copy_v3_v3(out, in);
- out[3]= 1.0f;
+ out[3] = 1.0f;
}
void do_copy_value(bNode *UNUSED(node), float *out, float *in)
{
- out[0]= in[0];
+ out[0] = in[0];
}
void do_copy_a_rgba(bNode *UNUSED(node), float *out, float *in, float *fac)
{
copy_v3_v3(out, in);
- out[3]= *fac;
+ out[3] = *fac;
}
/* only accepts RGBA buffers */
@@ -732,16 +732,16 @@ void gamma_correct_compbuf(CompBuf *img, int inversed)
drect= img->rect;
if (inversed) {
for (x=img->x*img->y; x>0; x--, drect+=4) {
- if (drect[0]>0.0f) drect[0]= sqrt(drect[0]); else drect[0]= 0.0f;
- if (drect[1]>0.0f) drect[1]= sqrt(drect[1]); else drect[1]= 0.0f;
- if (drect[2]>0.0f) drect[2]= sqrt(drect[2]); else drect[2]= 0.0f;
+ if (drect[0]>0.0f) drect[0] = sqrt(drect[0]); else drect[0] = 0.0f;
+ if (drect[1]>0.0f) drect[1] = sqrt(drect[1]); else drect[1] = 0.0f;
+ if (drect[2]>0.0f) drect[2] = sqrt(drect[2]); else drect[2] = 0.0f;
}
}
else {
for (x=img->x*img->y; x>0; x--, drect+=4) {
- if (drect[0]>0.0f) drect[0]*= drect[0]; else drect[0]= 0.0f;
- if (drect[1]>0.0f) drect[1]*= drect[1]; else drect[1]= 0.0f;
- if (drect[2]>0.0f) drect[2]*= drect[2]; else drect[2]= 0.0f;
+ if (drect[0]>0.0f) drect[0]*= drect[0]; else drect[0] = 0.0f;
+ if (drect[1]>0.0f) drect[1]*= drect[1]; else drect[1] = 0.0f;
+ if (drect[2]>0.0f) drect[2]*= drect[2]; else drect[2] = 0.0f;
}
}
}
@@ -757,9 +757,9 @@ void premul_compbuf(CompBuf *img, int inversed)
if (inversed) {
for (x=img->x*img->y; x>0; x--, drect+=4) {
if (fabsf(drect[3]) < 1e-5f) {
- drect[0]= 0.0f;
- drect[1]= 0.0f;
- drect[2]= 0.0f;
+ drect[0] = 0.0f;
+ drect[1] = 0.0f;
+ drect[2] = 0.0f;
}
else {
drect[0] /= drect[3];
@@ -1121,7 +1121,7 @@ void convolve(CompBuf* dst, CompBuf* in1, CompBuf* in2)
/*
*
- * Utility functions qd_* should probably be intergrated better with other functions here.
+ * Utility functions qd_* should probably be integrated better with other functions here.
*
*/
// sets fcol to pixelcolor at (x, y)
diff --git a/source/blender/nodes/composite/nodes/node_composite_alphaOver.c b/source/blender/nodes/composite/nodes/node_composite_alphaOver.c
index 86eb0aa2c83..72c2204d8c5 100644
--- a/source/blender/nodes/composite/nodes/node_composite_alphaOver.c
+++ b/source/blender/nodes/composite/nodes/node_composite_alphaOver.c
@@ -32,13 +32,13 @@
#include "node_composite_util.h"
/* **************** ALPHAOVER ******************** */
-static bNodeSocketTemplate cmp_node_alphaover_in[]= {
+static bNodeSocketTemplate cmp_node_alphaover_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_alphaover_out[]= {
+static bNodeSocketTemplate cmp_node_alphaover_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -48,7 +48,7 @@ static bNodeSocketTemplate cmp_node_alphaover_out[]= {
static void do_alphaover_premul(bNode *UNUSED(node), float *out, float *src, float *over, float *fac)
{
- /* Zero alpha values should still permit an add of RGB data */
+ /* Zero alpha values should still permit an add of RGB data */
if (over[3]<0.0f) {
copy_v4_v4(out, src);
}
@@ -58,11 +58,11 @@ static void do_alphaover_premul(bNode *UNUSED(node), float *out, float *src, flo
else {
float mul= 1.0f - fac[0]*over[3];
- out[0]= (mul*src[0]) + fac[0]*over[0];
- out[1]= (mul*src[1]) + fac[0]*over[1];
- out[2]= (mul*src[2]) + fac[0]*over[2];
- out[3]= (mul*src[3]) + fac[0]*over[3];
- }
+ out[0] = (mul*src[0]) + fac[0]*over[0];
+ out[1] = (mul*src[1]) + fac[0]*over[1];
+ out[2] = (mul*src[2]) + fac[0]*over[2];
+ out[3] = (mul*src[3]) + fac[0]*over[3];
+ }
}
/* result will be still premul, but the over part is premulled */
@@ -79,10 +79,10 @@ static void do_alphaover_key(bNode *UNUSED(node), float *out, float *src, float
float premul= fac[0]*over[3];
float mul= 1.0f - premul;
- out[0]= (mul*src[0]) + premul*over[0];
- out[1]= (mul*src[1]) + premul*over[1];
- out[2]= (mul*src[2]) + premul*over[2];
- out[3]= (mul*src[3]) + fac[0]*over[3];
+ out[0] = (mul*src[0]) + premul*over[0];
+ out[1] = (mul*src[1]) + premul*over[1];
+ out[2] = (mul*src[2]) + premul*over[2];
+ out[3] = (mul*src[3]) + fac[0]*over[3];
}
}
@@ -102,10 +102,10 @@ static void do_alphaover_mixed(bNode *node, float *out, float *src, float *over,
float premul= fac[0]*addfac;
float mul= 1.0f - fac[0]*over[3];
- out[0]= (mul*src[0]) + premul*over[0];
- out[1]= (mul*src[1]) + premul*over[1];
- out[2]= (mul*src[2]) + premul*over[2];
- out[3]= (mul*src[3]) + fac[0]*over[3];
+ out[0] = (mul*src[0]) + premul*over[0];
+ out[1] = (mul*src[1]) + premul*over[1];
+ out[2] = (mul*src[2]) + premul*over[2];
+ out[3] = (mul*src[3]) + fac[0]*over[3];
}
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_bilateralblur.c b/source/blender/nodes/composite/nodes/node_composite_bilateralblur.c
index e05ef1ea5a5..7674ace42a3 100644
--- a/source/blender/nodes/composite/nodes/node_composite_bilateralblur.c
+++ b/source/blender/nodes/composite/nodes/node_composite_bilateralblur.c
@@ -33,14 +33,14 @@
/* **************** BILATERALBLUR ******************** */
static bNodeSocketTemplate cmp_node_bilateralblur_in[] = {
- { SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
- { SOCK_RGBA, 1, N_("Determinator"), 1.0f, 1.0f, 1.0f, 1.0f},
- { -1, 0, "" }
+ { SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
+ { SOCK_RGBA, 1, N_("Determinator"), 1.0f, 1.0f, 1.0f, 1.0f},
+ { -1, 0, "" }
};
static bNodeSocketTemplate cmp_node_bilateralblur_out[] = {
- { SOCK_RGBA, 0, N_("Image")},
- { -1, 0, "" }
+ { SOCK_RGBA, 0, N_("Image")},
+ { -1, 0, "" }
};
#ifdef WITH_COMPOSITOR_LEGACY
diff --git a/source/blender/nodes/composite/nodes/node_composite_bokehimage.c b/source/blender/nodes/composite/nodes/node_composite_bokehimage.c
index c5697679f90..8324b77b2d1 100644
--- a/source/blender/nodes/composite/nodes/node_composite_bokehimage.c
+++ b/source/blender/nodes/composite/nodes/node_composite_bokehimage.c
@@ -37,7 +37,7 @@
/* **************** Bokeh image Tools ******************** */
-static bNodeSocketTemplate cmp_node_bokehimage_out[]= {
+static bNodeSocketTemplate cmp_node_bokehimage_out[] = {
{ SOCK_RGBA, 0, N_("Image"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_boxmask.c b/source/blender/nodes/composite/nodes/node_composite_boxmask.c
index 1ba522c0e5f..d3c6b2ccef0 100644
--- a/source/blender/nodes/composite/nodes/node_composite_boxmask.c
+++ b/source/blender/nodes/composite/nodes/node_composite_boxmask.c
@@ -1,6 +1,4 @@
/*
- * $Id: CMP_math.c 36271 2011-04-21 13:11:51Z campbellbarton $
- *
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
@@ -35,15 +33,15 @@
#include "../node_composite_util.h"
/* **************** SCALAR MATH ******************** */
-static bNodeSocketTemplate cmp_node_boxmask_in[]= {
+static bNodeSocketTemplate cmp_node_boxmask_in[] = {
{ SOCK_FLOAT, 1, N_("Mask"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Value"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
- { -1, 0, "" }
+ { -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_boxmask_out[]= {
+static bNodeSocketTemplate cmp_node_boxmask_out[] = {
{ SOCK_FLOAT, 0, N_("Mask"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
- { -1, 0, "" }
+ { -1, 0, "" }
};
static void node_composit_init_boxmask(bNodeTree *UNUSED(ntree), bNode *node, bNodeTemplate *UNUSED(ntemp))
diff --git a/source/blender/nodes/composite/nodes/node_composite_brightness.c b/source/blender/nodes/composite/nodes/node_composite_brightness.c
index 2b8a394d6f2..ecf572f59c7 100644
--- a/source/blender/nodes/composite/nodes/node_composite_brightness.c
+++ b/source/blender/nodes/composite/nodes/node_composite_brightness.c
@@ -36,13 +36,13 @@
/* **************** Brigh and contrsast ******************** */
-static bNodeSocketTemplate cmp_node_brightcontrast_in[]= {
+static bNodeSocketTemplate cmp_node_brightcontrast_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Bright"), 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("Contrast"), 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_brightcontrast_out[]= {
+static bNodeSocketTemplate cmp_node_brightcontrast_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -72,7 +72,7 @@ static void do_brightnesscontrast(bNode *UNUSED(node), float *out, float *in, fl
b = a * (brightness + delta);
}
- for (c=0; c<3; c++) {
+ for (c=0; c<3; c++) {
i = in[c];
v = a*i + b;
out[c] = v;
diff --git a/source/blender/nodes/composite/nodes/node_composite_channelMatte.c b/source/blender/nodes/composite/nodes/node_composite_channelMatte.c
index 06b77de463b..40dbbbb8dca 100644
--- a/source/blender/nodes/composite/nodes/node_composite_channelMatte.c
+++ b/source/blender/nodes/composite/nodes/node_composite_channelMatte.c
@@ -34,12 +34,12 @@
/* ******************* Channel Matte Node ********************************* */
-static bNodeSocketTemplate cmp_node_channel_matte_in[]={
+static bNodeSocketTemplate cmp_node_channel_matte_in[] ={
{SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{-1, 0, ""}
};
-static bNodeSocketTemplate cmp_node_channel_matte_out[]={
+static bNodeSocketTemplate cmp_node_channel_matte_out[] ={
{SOCK_RGBA, 0, N_("Image")},
{SOCK_FLOAT, 0, N_("Matte")},
{-1, 0, ""}
@@ -71,7 +71,7 @@ static void do_normalized_ycca_to_rgba2(bNode *UNUSED(node), float *out, float *
static void do_channel_matte(bNode *node, float *out, float *in)
{
NodeChroma *c=(NodeChroma *)node->storage;
- float alpha=0.0;
+ float alpha=0.0;
switch (c->algorithm) {
case 0: { /* Alpha=key_channel-limit channel */
diff --git a/source/blender/nodes/composite/nodes/node_composite_chromaMatte.c b/source/blender/nodes/composite/nodes/node_composite_chromaMatte.c
index 55ee1b090bb..f343f806d57 100644
--- a/source/blender/nodes/composite/nodes/node_composite_chromaMatte.c
+++ b/source/blender/nodes/composite/nodes/node_composite_chromaMatte.c
@@ -33,13 +33,13 @@
#include "node_composite_util.h"
/* ******************* Chroma Key ********************************************************** */
-static bNodeSocketTemplate cmp_node_chroma_in[]={
+static bNodeSocketTemplate cmp_node_chroma_in[] = {
{SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{SOCK_RGBA, 1, N_("Key Color"), 1.0f, 1.0f, 1.0f, 1.0f},
{-1, 0, ""}
};
-static bNodeSocketTemplate cmp_node_chroma_out[]={
+static bNodeSocketTemplate cmp_node_chroma_out[] = {
{SOCK_RGBA, 0, N_("Image")},
{SOCK_FLOAT, 0, N_("Matte")},
{-1, 0, ""}
diff --git a/source/blender/nodes/composite/nodes/node_composite_colorMatte.c b/source/blender/nodes/composite/nodes/node_composite_colorMatte.c
index 37fb29811ba..07a6647d976 100644
--- a/source/blender/nodes/composite/nodes/node_composite_colorMatte.c
+++ b/source/blender/nodes/composite/nodes/node_composite_colorMatte.c
@@ -33,13 +33,13 @@
#include "node_composite_util.h"
/* ******************* Color Key ********************************************************** */
-static bNodeSocketTemplate cmp_node_color_in[]={
+static bNodeSocketTemplate cmp_node_color_in[] = {
{SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{SOCK_RGBA, 1, N_("Key Color"), 1.0f, 1.0f, 1.0f, 1.0f},
{-1, 0, ""}
};
-static bNodeSocketTemplate cmp_node_color_out[]={
+static bNodeSocketTemplate cmp_node_color_out[] = {
{SOCK_RGBA, 0, N_("Image")},
{SOCK_FLOAT, 0, N_("Matte")},
{-1, 0, ""}
diff --git a/source/blender/nodes/composite/nodes/node_composite_colorSpill.c b/source/blender/nodes/composite/nodes/node_composite_colorSpill.c
index c4120ab22c6..e8965d50b47 100644
--- a/source/blender/nodes/composite/nodes/node_composite_colorSpill.c
+++ b/source/blender/nodes/composite/nodes/node_composite_colorSpill.c
@@ -36,13 +36,13 @@
#define AVG(a, b) ((a + b) / 2)
/* ******************* Color Spill Supression ********************************* */
-static bNodeSocketTemplate cmp_node_color_spill_in[]={
+static bNodeSocketTemplate cmp_node_color_spill_in[] = {
{SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
{-1, 0, ""}
};
-static bNodeSocketTemplate cmp_node_color_spill_out[]={
+static bNodeSocketTemplate cmp_node_color_spill_out[] = {
{SOCK_RGBA, 0, N_("Image")},
{-1, 0, ""}
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_colorbalance.c b/source/blender/nodes/composite/nodes/node_composite_colorbalance.c
index 0868c9467e5..e9d26ebebbc 100644
--- a/source/blender/nodes/composite/nodes/node_composite_colorbalance.c
+++ b/source/blender/nodes/composite/nodes/node_composite_colorbalance.c
@@ -35,13 +35,13 @@
/* ******************* Color Balance ********************************* */
-static bNodeSocketTemplate cmp_node_colorbalance_in[]={
+static bNodeSocketTemplate cmp_node_colorbalance_in[] = {
{SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
{SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{-1, 0, ""}
};
-static bNodeSocketTemplate cmp_node_colorbalance_out[]={
+static bNodeSocketTemplate cmp_node_colorbalance_out[] = {
{SOCK_RGBA, 0, N_("Image")},
{-1, 0, ""}
};
@@ -71,8 +71,8 @@ DO_INLINE float colorbalance_cdl(float in, float offset, float power, float slop
/* note: lift_lgg is just 2-lift, gamma_inv is 1.0/gamma */
DO_INLINE float colorbalance_lgg(float in, float lift_lgg, float gamma_inv, float gain)
{
- /* 1:1 match with the sequencer with linear/srgb conversions, the conversion isn'tisn't pretty
- * but best keep it this way, sice testing for durian shows a similar calculation
+ /* 1:1 match with the sequencer with linear/srgb conversions, the conversion isn't pretty
+ * but best keep it this way, since testing for durian shows a similar calculation
* without lin/srgb conversions gives bad results (over-saturated shadows) with colors
* slightly below 1.0. some correction can be done but it ends up looking bad for shadows or lighter tones - campbell */
float x= (((linearrgb_to_srgb(in) - 1.0f) * lift_lgg) + 1.0f) * gain;
diff --git a/source/blender/nodes/composite/nodes/node_composite_colorcorrection.c b/source/blender/nodes/composite/nodes/node_composite_colorcorrection.c
index ce43b2f0f2b..526f8472992 100644
--- a/source/blender/nodes/composite/nodes/node_composite_colorcorrection.c
+++ b/source/blender/nodes/composite/nodes/node_composite_colorcorrection.c
@@ -36,13 +36,13 @@
/* ******************* Color Balance ********************************* */
-static bNodeSocketTemplate cmp_node_colorcorrection_in[]={
+static bNodeSocketTemplate cmp_node_colorcorrection_in[] = {
{ SOCK_RGBA,1,N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Mask"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
{ -1,0,""}
};
-static bNodeSocketTemplate cmp_node_colorcorrection_out[]={
+static bNodeSocketTemplate cmp_node_colorcorrection_out[] = {
{ SOCK_RGBA,0,N_("Image")},
{ -1,0,""}
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_common.c b/source/blender/nodes/composite/nodes/node_composite_common.c
index 2596248d696..10b81cdaaa0 100644
--- a/source/blender/nodes/composite/nodes/node_composite_common.c
+++ b/source/blender/nodes/composite/nodes/node_composite_common.c
@@ -231,153 +231,3 @@ void register_node_type_cmp_group(bNodeTreeType *ttype)
nodeRegisterType(ttype, &ntype);
}
-
-#ifdef WITH_COMPOSITOR_LEGACY
-
-/**** FOR LOOP ****/
-
-#if 0 /* XXX loop nodes don't work nicely with current trees */
-/* Move the results from the previous iteration back to the input sockets. */
-static void loop_iteration_reset(bNodeTree *ngroup, bNodeStack *gstack)
-{
- bNodeSocket *gin, *gout;
- bNodeStack *nsin, *nsout;
-
- gin = ngroup->inputs.first;
- gout = ngroup->outputs.first;
-
- while (gin && gout) {
- /* skip static (non-looping) sockets */
- while (gin && !(gin->flag & SOCK_DYNAMIC))
- gin=gin->next;
- while (gout && !(gout->flag & SOCK_DYNAMIC))
- gout=gout->next;
-
- if (gin && gout) {
- nsin = node_get_socket_stack(gstack, gin);
- nsout = node_get_socket_stack(gstack, gout);
-
- move_stack(nsin, nsout);
-
- gin=gin->next;
- gout=gout->next;
- }
- }
-}
-
-static void forloop_execute(void *data, int thread, struct bNode *node, void *nodedata, struct bNodeStack **in, struct bNodeStack **out)
-{
- bNodeTreeExec *exec= (bNodeTreeExec *)nodedata;
- int totiterations= (int)in[0]->vec[0];
- bNodeSocket *sock;
- bNodeStack *ns;
- int iteration;
-
- /* XXX same behavior as trunk: all nodes inside group are executed.
- * it's stupid, but just makes it work. compo redesign will do this better.
- */
- {
- bNode *inode;
- for (inode=exec->nodetree->nodes.first; inode; inode=inode->next)
- inode->need_exec = 1;
- }
-
- /* "Iteration" socket */
- sock = exec->nodetree->inputs.first;
- ns = node_get_socket_stack(exec->stack, sock);
-
- group_copy_inputs(node, in, exec->stack);
- for (iteration=0; iteration < totiterations; ++iteration) {
- /* first input contains current iteration counter */
- ns->vec[0] = (float)iteration;
-
- if (iteration > 0)
- loop_iteration_reset(exec->nodetree, exec->stack);
- ntreeExecNodes(exec, data, thread);
- group_free_internal(exec);
- }
- group_move_outputs(node, out, exec->stack);
-}
-
-void register_node_type_cmp_forloop(bNodeTreeType *ttype)
-{
- static bNodeType ntype;
-
- node_type_base(ttype, &ntype, NODE_FORLOOP, "For", NODE_CLASS_GROUP, NODE_OPTIONS);
- node_type_socket_templates(&ntype, NULL, NULL);
- node_type_size(&ntype, 120, 60, 200);
- node_type_label(&ntype, node_group_label);
- node_type_init(&ntype, node_forloop_init);
- node_type_valid(&ntype, node_group_valid);
- node_type_template(&ntype, node_forloop_template);
- node_type_update(&ntype, NULL, node_group_verify);
- node_type_tree(&ntype, node_forloop_init_tree, node_loop_update_tree);
- node_type_group_edit(&ntype, node_group_edit_get, node_group_edit_set, node_group_edit_clear);
- node_type_exec_new(&ntype, group_initexec, group_freeexec, forloop_execute);
-
- nodeRegisterType(ttype, &ntype);
-}
-#endif
-
-
-/**** WHILE LOOP ****/
-
-#if 0 /* XXX loop nodes don't work nicely with current trees */
-static void whileloop_execute(void *data, int thread, struct bNode *node, void *nodedata, struct bNodeStack **in, struct bNodeStack **out)
-{
- bNodeTreeExec *exec= (bNodeTreeExec *)nodedata;
- int condition= (in[0]->vec[0] > 0.0f);
- bNodeSocket *sock;
- bNodeStack *ns;
- int iteration;
-
- /* XXX same behavior as trunk: all nodes inside group are executed.
- * it's stupid, but just makes it work. compo redesign will do this better.
- */
- {
- bNode *inode;
- for (inode=exec->nodetree->nodes.first; inode; inode=inode->next)
- inode->need_exec = 1;
- }
-
- /* "Condition" socket */
- sock = exec->nodetree->outputs.first;
- ns = node_get_socket_stack(exec->stack, sock);
-
- iteration = 0;
- group_copy_inputs(node, in, exec->stack);
- while (condition && iteration < node->custom1) {
- if (iteration > 0)
- loop_iteration_reset(exec->nodetree, exec->stack);
- ntreeExecNodes(exec, data, thread);
- group_free_internal(exec);
-
-// PRINT_BUFFERS(exec);
-
- condition = (ns->vec[0] > 0.0f);
- ++iteration;
- }
- group_move_outputs(node, out, exec->stack);
-}
-
-void register_node_type_cmp_whileloop(bNodeTreeType *ttype)
-{
- static bNodeType ntype;
-
- node_type_base(ttype, &ntype, NODE_WHILELOOP, "While", NODE_CLASS_GROUP, NODE_OPTIONS);
- node_type_socket_templates(&ntype, NULL, NULL);
- node_type_size(&ntype, 120, 60, 200);
- node_type_label(&ntype, node_group_label);
- node_type_init(&ntype, node_whileloop_init);
- node_type_valid(&ntype, node_group_valid);
- node_type_template(&ntype, node_whileloop_template);
- node_type_update(&ntype, NULL, node_group_verify);
- node_type_tree(&ntype, node_whileloop_init_tree, node_loop_update_tree);
- node_type_group_edit(&ntype, node_group_edit_get, node_group_edit_set, node_group_edit_clear);
- node_type_exec_new(&ntype, group_initexec, group_freeexec, whileloop_execute);
-
- nodeRegisterType(ttype, &ntype);
-}
-#endif
-
-#endif /* WITH_COMPOSITOR_LEGACY */
diff --git a/source/blender/nodes/composite/nodes/node_composite_composite.c b/source/blender/nodes/composite/nodes/node_composite_composite.c
index dadc863873d..cb932b6a8de 100644
--- a/source/blender/nodes/composite/nodes/node_composite_composite.c
+++ b/source/blender/nodes/composite/nodes/node_composite_composite.c
@@ -32,7 +32,7 @@
#include "node_composite_util.h"
/* **************** COMPOSITE ******************** */
-static bNodeSocketTemplate cmp_node_composite_in[]= {
+static bNodeSocketTemplate cmp_node_composite_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Alpha"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_FLOAT, 1, N_("Z"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
@@ -110,7 +110,7 @@ void register_node_type_cmp_composite(bNodeTreeType *ttype)
#endif
/* Do not allow muting for this node. */
- node_type_internal_connect(&ntype, NULL);
+ node_type_internal_links(&ntype, NULL);
nodeRegisterType(ttype, &ntype);
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_crop.c b/source/blender/nodes/composite/nodes/node_composite_crop.c
index 9b1483d95cf..ad51fae1998 100644
--- a/source/blender/nodes/composite/nodes/node_composite_crop.c
+++ b/source/blender/nodes/composite/nodes/node_composite_crop.c
@@ -34,11 +34,11 @@
/* **************** Crop ******************** */
-static bNodeSocketTemplate cmp_node_crop_in[]= {
+static bNodeSocketTemplate cmp_node_crop_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_crop_out[]= {
+static bNodeSocketTemplate cmp_node_crop_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -82,7 +82,7 @@ static void node_composit_exec_crop(void *UNUSED(data), bNode *node, bNodeStack
outputrect.ymin=MIN2(ntxy->y1, ntxy->y2);
if (node->custom1) {
- /* this option crops the image size too */
+ /* this option crops the image size too */
stackbuf= get_cropped_compbuf(&outputrect, cbuf->rect, cbuf->x, cbuf->y, cbuf->type);
}
else {
diff --git a/source/blender/nodes/composite/nodes/node_composite_curves.c b/source/blender/nodes/composite/nodes/node_composite_curves.c
index 1948709ec84..a1999ec8887 100644
--- a/source/blender/nodes/composite/nodes/node_composite_curves.c
+++ b/source/blender/nodes/composite/nodes/node_composite_curves.c
@@ -36,7 +36,7 @@
/* **************** CURVE Time ******************** */
/* custom1 = sfra, custom2 = efra */
-static bNodeSocketTemplate cmp_node_time_out[]= {
+static bNodeSocketTemplate cmp_node_time_out[] = {
{ SOCK_FLOAT, 0, N_("Fac")},
{ -1, 0, "" }
};
@@ -55,7 +55,7 @@ static void node_composit_exec_curves_time(void *data, bNode *node, bNodeStack *
curvemapping_initialize(node->storage);
fac = curvemapping_evaluateF(node->storage, 0, fac);
- out[0]->vec[0]= CLAMPIS(fac, 0.0f, 1.0f);
+ out[0]->vec[0] = CLAMPIS(fac, 0.0f, 1.0f);
}
#endif /* WITH_COMPOSITOR_LEGACY */
@@ -86,12 +86,12 @@ void register_node_type_cmp_curve_time(bNodeTreeType *ttype)
/* **************** CURVE VEC ******************** */
-static bNodeSocketTemplate cmp_node_curve_vec_in[]= {
+static bNodeSocketTemplate cmp_node_curve_vec_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_curve_vec_out[]= {
+static bNodeSocketTemplate cmp_node_curve_vec_out[] = {
{ SOCK_VECTOR, 0, N_("Vector")},
{ -1, 0, "" }
};
@@ -132,7 +132,7 @@ void register_node_type_cmp_curve_vec(bNodeTreeType *ttype)
/* **************** CURVE RGB ******************** */
-static bNodeSocketTemplate cmp_node_curve_rgb_in[]= {
+static bNodeSocketTemplate cmp_node_curve_rgb_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_FACTOR},
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_RGBA, 1, N_("Black Level"), 0.0f, 0.0f, 0.0f, 1.0f},
@@ -140,7 +140,7 @@ static bNodeSocketTemplate cmp_node_curve_rgb_in[]= {
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_curve_rgb_out[]= {
+static bNodeSocketTemplate cmp_node_curve_rgb_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -151,7 +151,7 @@ static void do_curves(bNode *node, float *out, float *in)
{
curvemapping_initialize(node->storage);
curvemapping_evaluate_premulRGBF(node->storage, out, in);
- out[3]= in[3];
+ out[3] = in[3];
}
static void do_curves_fac(bNode *node, float *out, float *in, float *fac)
@@ -166,11 +166,11 @@ static void do_curves_fac(bNode *node, float *out, float *in, float *fac)
else {
float col[4], mfac= 1.0f-*fac;
curvemapping_evaluate_premulRGBF(node->storage, col, in);
- out[0]= mfac*in[0] + *fac*col[0];
- out[1]= mfac*in[1] + *fac*col[1];
- out[2]= mfac*in[2] + *fac*col[2];
+ out[0] = mfac*in[0] + *fac*col[0];
+ out[1] = mfac*in[1] + *fac*col[1];
+ out[2] = mfac*in[2] + *fac*col[2];
}
- out[3]= in[3];
+ out[3] = in[3];
}
static void node_composit_exec_curve_rgb(void *UNUSED(data), bNode *node, bNodeStack **in, bNodeStack **out)
diff --git a/source/blender/nodes/composite/nodes/node_composite_defocus.c b/source/blender/nodes/composite/nodes/node_composite_defocus.c
index 1a9852264bf..27ce0f7c4a7 100644
--- a/source/blender/nodes/composite/nodes/node_composite_defocus.c
+++ b/source/blender/nodes/composite/nodes/node_composite_defocus.c
@@ -34,12 +34,12 @@
#include <limits.h>
/* ************ qdn: Defocus node ****************** */
-static bNodeSocketTemplate cmp_node_defocus_in[]= {
+static bNodeSocketTemplate cmp_node_defocus_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Z"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_defocus_out[]= {
+static bNodeSocketTemplate cmp_node_defocus_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -338,7 +338,7 @@ static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf,
// fast blur...
// bug #6656 part 1, probably when previous node_composite.c was split into separate files, it was not properly updated
// to include recent cvs commits (well, at least not defocus node), so this part was missing...
- wt = minf(nqd->maxblur, aperture * 128.0f);
+ wt = min_ff(nqd->maxblur, aperture * 128.0f);
IIR_gauss_single(crad, wt);
IIR_gauss_single(wts, wt);
@@ -589,8 +589,8 @@ static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf,
// n-agonal
int ov, nv;
float mind, maxd, lwt;
- ys = maxi((int)floor(bkh_b[2] * ct_crad + y), 0);
- ye = mini((int)ceil(bkh_b[3] * ct_crad + y), new->y - 1);
+ ys = max_ii((int)floor(bkh_b[2] * ct_crad + y), 0);
+ ye = min_ii((int)ceil(bkh_b[3] * ct_crad + y), new->y - 1);
for (sy=ys; sy<=ye; sy++) {
float fxs = 1e10f, fxe = -1e10f;
float yf = (sy - y)/ct_crad;
@@ -861,7 +861,7 @@ static void node_composit_exec_defocus(void *UNUSED(data), bNode *node, bNodeSta
if (node->exec & NODE_BREAK) {
free_compbuf(new);
new= NULL;
- }
+ }
out[0]->data = new;
if (zbuf_use && (zbuf_use != zbuf)) free_compbuf(zbuf_use);
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_despeckle.c b/source/blender/nodes/composite/nodes/node_composite_despeckle.c
index 21b703dc9a8..9d47e4bc276 100644
--- a/source/blender/nodes/composite/nodes/node_composite_despeckle.c
+++ b/source/blender/nodes/composite/nodes/node_composite_despeckle.c
@@ -32,12 +32,12 @@
#include "node_composite_util.h"
/* **************** FILTER ******************** */
-static bNodeSocketTemplate cmp_node_despeckle_in[]= {
+static bNodeSocketTemplate cmp_node_despeckle_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_despeckle_out[]= {
+static bNodeSocketTemplate cmp_node_despeckle_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_diffMatte.c b/source/blender/nodes/composite/nodes/node_composite_diffMatte.c
index ed43baef420..014b72d3c60 100644
--- a/source/blender/nodes/composite/nodes/node_composite_diffMatte.c
+++ b/source/blender/nodes/composite/nodes/node_composite_diffMatte.c
@@ -33,13 +33,13 @@
#include "node_composite_util.h"
/* ******************* channel Difference Matte ********************************* */
-static bNodeSocketTemplate cmp_node_diff_matte_in[]={
+static bNodeSocketTemplate cmp_node_diff_matte_in[] = {
{SOCK_RGBA, 1, N_("Image 1"), 1.0f, 1.0f, 1.0f, 1.0f},
{SOCK_RGBA, 1, N_("Image 2"), 1.0f, 1.0f, 1.0f, 1.0f},
{-1, 0, ""}
};
-static bNodeSocketTemplate cmp_node_diff_matte_out[]={
+static bNodeSocketTemplate cmp_node_diff_matte_out[] = {
{SOCK_RGBA, 0, N_("Image")},
{SOCK_FLOAT, 0, N_("Matte")},
{-1, 0, ""}
@@ -76,7 +76,7 @@ static void do_diff_matte(bNode *node, float *outColor, float *inColor1, float *
}
/*only change if more transparent than either image */
- maxInputAlpha=maxf(inColor1[3], inColor2[3]);
+ maxInputAlpha=max_ff(inColor1[3], inColor2[3]);
if (alpha < maxInputAlpha) {
/*clamp*/
if (alpha < 0.0f) alpha = 0.0f;
diff --git a/source/blender/nodes/composite/nodes/node_composite_dilate.c b/source/blender/nodes/composite/nodes/node_composite_dilate.c
index f53c64b990a..9787c9f7145 100644
--- a/source/blender/nodes/composite/nodes/node_composite_dilate.c
+++ b/source/blender/nodes/composite/nodes/node_composite_dilate.c
@@ -54,28 +54,28 @@ static void morpho_dilate(CompBuf *cbuf)
for (y = 0; y < cbuf->y; y++) {
for (x = 0; x < cbuf->x - 1; x++) {
p = rectf + cbuf->x * y + x;
- *p = maxf(*p, *(p + 1));
+ *p = max_ff(*p, *(p + 1));
}
}
for (y = 0; y < cbuf->y; y++) {
for (x = cbuf->x - 1; x >= 1; x--) {
p = rectf + cbuf->x * y + x;
- *p = maxf(*p, *(p - 1));
+ *p = max_ff(*p, *(p - 1));
}
}
for (x = 0; x < cbuf->x; x++) {
for (y = 0; y < cbuf->y - 1; y++) {
p = rectf + cbuf->x * y + x;
- *p = maxf(*p, *(p + cbuf->x));
+ *p = max_ff(*p, *(p + cbuf->x));
}
}
for (x = 0; x < cbuf->x; x++) {
for (y = cbuf->y - 1; y >= 1; y--) {
p = rectf + cbuf->x * y + x;
- *p = maxf(*p, *(p - cbuf->x));
+ *p = max_ff(*p, *(p - cbuf->x));
}
}
}
@@ -88,28 +88,28 @@ static void morpho_erode(CompBuf *cbuf)
for (y = 0; y < cbuf->y; y++) {
for (x = 0; x < cbuf->x - 1; x++) {
p = rectf + cbuf->x * y + x;
- *p = minf(*p, *(p + 1));
+ *p = min_ff(*p, *(p + 1));
}
}
for (y = 0; y < cbuf->y; y++) {
for (x = cbuf->x - 1; x >= 1; x--) {
p = rectf + cbuf->x * y + x;
- *p = minf(*p, *(p - 1));
+ *p = min_ff(*p, *(p - 1));
}
}
for (x = 0; x < cbuf->x; x++) {
for (y = 0; y < cbuf->y - 1; y++) {
p = rectf + cbuf->x * y + x;
- *p = minf(*p, *(p + cbuf->x));
+ *p = min_ff(*p, *(p + cbuf->x));
}
}
for (x = 0; x < cbuf->x; x++) {
for (y = cbuf->y - 1; y >= 1; y--) {
p = rectf + cbuf->x * y + x;
- *p = minf(*p, *(p - cbuf->x));
+ *p = min_ff(*p, *(p - cbuf->x));
}
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_directionalblur.c b/source/blender/nodes/composite/nodes/node_composite_directionalblur.c
index 2878d303632..a343315264d 100644
--- a/source/blender/nodes/composite/nodes/node_composite_directionalblur.c
+++ b/source/blender/nodes/composite/nodes/node_composite_directionalblur.c
@@ -65,7 +65,7 @@ static CompBuf *dblur(bNode *node, CompBuf *img, int iterations, int wrap,
center_y_pix = center_y * img->y;
tx = itsc * D * cosf(a);
- ty = -itsc *D *sinf(a);
+ ty = -itsc * D * sinf(a);
sc = itsc * zoom;
rot = itsc * spin;
diff --git a/source/blender/nodes/composite/nodes/node_composite_displace.c b/source/blender/nodes/composite/nodes/node_composite_displace.c
index 51ccc2a4d39..c07ad0a0c97 100644
--- a/source/blender/nodes/composite/nodes/node_composite_displace.c
+++ b/source/blender/nodes/composite/nodes/node_composite_displace.c
@@ -35,14 +35,14 @@
/* **************** Displace ******************** */
-static bNodeSocketTemplate cmp_node_displace_in[]= {
+static bNodeSocketTemplate cmp_node_displace_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_VECTOR, 1, N_("Vector"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_TRANSLATION},
{ SOCK_FLOAT, 1, N_("X Scale"), 0.0f, 0.0f, 0.0f, 0.0f, -1000.0f, 1000.0f, PROP_FACTOR},
{ SOCK_FLOAT, 1, N_("Y Scale"), 0.0f, 0.0f, 0.0f, 0.0f, -1000.0f, 1000.0f, PROP_FACTOR},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_displace_out[]= {
+static bNodeSocketTemplate cmp_node_displace_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -113,8 +113,8 @@ static void do_displace(bNode *node, CompBuf *stackbuf, CompBuf *cbuf, CompBuf *
dxt = p_dx - d_dx;
dyt = p_dy - d_dy;
- dxt = signf(dxt)*maxf(fabsf(dxt), DISPLACE_EPSILON)/(float)stackbuf->x;
- dyt = signf(dyt)*maxf(fabsf(dyt), DISPLACE_EPSILON)/(float)stackbuf->y;
+ dxt = signf(dxt)*max_ff(fabsf(dxt), DISPLACE_EPSILON)/(float)stackbuf->x;
+ dyt = signf(dyt)*max_ff(fabsf(dyt), DISPLACE_EPSILON)/(float)stackbuf->y;
ibuf_sample(ibuf, u, v, dxt, dyt, col);
qd_setPixel(stackbuf, x, y, col);
diff --git a/source/blender/nodes/composite/nodes/node_composite_distanceMatte.c b/source/blender/nodes/composite/nodes/node_composite_distanceMatte.c
index 7a101ff43b5..7e605865cd2 100644
--- a/source/blender/nodes/composite/nodes/node_composite_distanceMatte.c
+++ b/source/blender/nodes/composite/nodes/node_composite_distanceMatte.c
@@ -33,13 +33,13 @@
#include "node_composite_util.h"
/* ******************* channel Distance Matte ********************************* */
-static bNodeSocketTemplate cmp_node_distance_matte_in[]={
+static bNodeSocketTemplate cmp_node_distance_matte_in[] = {
{SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{SOCK_RGBA, 1, N_("Key Color"), 1.0f, 1.0f, 1.0f, 1.0f},
{-1, 0, ""}
};
-static bNodeSocketTemplate cmp_node_distance_matte_out[]={
+static bNodeSocketTemplate cmp_node_distance_matte_out[] = {
{SOCK_RGBA, 0, N_("Image")},
{SOCK_FLOAT, 0, N_("Matte")},
{-1, 0, ""}
@@ -159,9 +159,9 @@ static void node_composit_exec_distance_matte(void *data, bNode *node, bNodeStac
workbuf=dupalloc_compbuf(inbuf);
/*use the input color*/
- c->key[0]= in[1]->vec[0];
- c->key[1]= in[1]->vec[1];
- c->key[2]= in[1]->vec[2];
+ c->key[0] = in[1]->vec[0];
+ c->key[1] = in[1]->vec[1];
+ c->key[2] = in[1]->vec[2];
/* work in RGB color space */
if (c->channel == 1) {
diff --git a/source/blender/nodes/composite/nodes/node_composite_doubleEdgeMask.c b/source/blender/nodes/composite/nodes/node_composite_doubleEdgeMask.c
index 63a54efea74..3c1e3ee443e 100644
--- a/source/blender/nodes/composite/nodes/node_composite_doubleEdgeMask.c
+++ b/source/blender/nodes/composite/nodes/node_composite_doubleEdgeMask.c
@@ -32,12 +32,12 @@
/* **************** Double Edge Mask ******************** */
-static bNodeSocketTemplate cmp_node_doubleedgemask_in[]= {
+static bNodeSocketTemplate cmp_node_doubleedgemask_in[] = {
{ SOCK_FLOAT, 1, "Inner Mask", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f, PROP_NONE}, // inner mask socket definition
{ SOCK_FLOAT, 1, "Outer Mask", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f, PROP_NONE}, // outer mask socket definition
{ -1, 0, "" } // input socket array terminator
};
-static bNodeSocketTemplate cmp_node_doubleedgemask_out[]= {
+static bNodeSocketTemplate cmp_node_doubleedgemask_out[] = {
{ SOCK_FLOAT, 0, "Mask"}, // output socket definition
{ -1, 0, "" } // output socket array terminator
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_ellipsemask.c b/source/blender/nodes/composite/nodes/node_composite_ellipsemask.c
index a97322a17c0..761b0b13f11 100644
--- a/source/blender/nodes/composite/nodes/node_composite_ellipsemask.c
+++ b/source/blender/nodes/composite/nodes/node_composite_ellipsemask.c
@@ -1,6 +1,4 @@
/*
- * $Id: CMP_math.c 36271 2011-04-21 13:11:51Z campbellbarton $
- *
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
@@ -35,15 +33,15 @@
#include "../node_composite_util.h"
/* **************** SCALAR MATH ******************** */
-static bNodeSocketTemplate cmp_node_ellipsemask_in[]= {
+static bNodeSocketTemplate cmp_node_ellipsemask_in[] = {
{ SOCK_FLOAT, 1, N_("Mask"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Value"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
- { -1, 0, "" }
+ { -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_ellipsemask_out[]= {
+static bNodeSocketTemplate cmp_node_ellipsemask_out[] = {
{ SOCK_FLOAT, 0, N_("Mask"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
- { -1, 0, "" }
+ { -1, 0, "" }
};
static void node_composit_init_ellipsemask(bNodeTree *UNUSED(ntree), bNode *node, bNodeTemplate *UNUSED(ntemp))
diff --git a/source/blender/nodes/composite/nodes/node_composite_filter.c b/source/blender/nodes/composite/nodes/node_composite_filter.c
index 0b12c03682b..a27116ab077 100644
--- a/source/blender/nodes/composite/nodes/node_composite_filter.c
+++ b/source/blender/nodes/composite/nodes/node_composite_filter.c
@@ -33,12 +33,12 @@
#include "node_composite_util.h"
/* **************** FILTER ******************** */
-static bNodeSocketTemplate cmp_node_filter_in[]= {
+static bNodeSocketTemplate cmp_node_filter_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_filter_out[]= {
+static bNodeSocketTemplate cmp_node_filter_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -73,10 +73,10 @@ static void do_filter_edge(CompBuf *out, CompBuf *in, float *filter, float fac)
for (c=0; c<3; c++) {
f1= filter[0]*row1[0] + filter[1]*row1[4] + filter[2]*row1[8] + filter[3]*row2[0] + filter[4]*row2[4] + filter[5]*row2[8] + filter[6]*row3[0] + filter[7]*row3[4] + filter[8]*row3[8];
f2= filter[0]*row1[0] + filter[3]*row1[4] + filter[6]*row1[8] + filter[1]*row2[0] + filter[4]*row2[4] + filter[7]*row2[8] + filter[2]*row3[0] + filter[5]*row3[4] + filter[8]*row3[8];
- fp[0]= mfac*row2[4] + fac*sqrt(f1*f1 + f2*f2);
+ fp[0] = mfac*row2[4] + fac*sqrt(f1*f1 + f2*f2);
fp++; row1++; row2++; row3++;
}
- fp[0]= row2[4];
+ fp[0] = row2[4];
/* no alpha... will clear it completely */
fp++; row1++; row2++; row3++;
}
@@ -87,7 +87,7 @@ static void do_filter_edge(CompBuf *out, CompBuf *in, float *filter, float fac)
for (x=2; x<rowlen; x++) {
f1= filter[0]*row1[0] + filter[1]*row1[1] + filter[2]*row1[2] + filter[3]*row2[0] + filter[4]*row2[1] + filter[5]*row2[2] + filter[6]*row3[0] + filter[7]*row3[1] + filter[8]*row3[2];
f2= filter[0]*row1[0] + filter[3]*row1[1] + filter[6]*row1[2] + filter[1]*row2[0] + filter[4]*row2[1] + filter[7]*row2[2] + filter[2]*row3[0] + filter[5]*row3[1] + filter[8]*row3[2];
- fp[0]= mfac*row2[1] + fac*sqrt(f1*f1 + f2*f2);
+ fp[0] = mfac*row2[1] + fac*sqrt(f1*f1 + f2*f2);
fp++; row1++; row2++; row3++;
}
}
@@ -116,28 +116,28 @@ static void do_filter3(CompBuf *out, CompBuf *in, float *filter, float fac)
fp= out->rect + pixlen*(y)*rowlen;
if (pixlen==1) {
- fp[0]= row2[0];
+ fp[0] = row2[0];
fp+= 1;
for (x=2; x<rowlen; x++) {
- fp[0]= mfac*row2[1] + fac*(filter[0]*row1[0] + filter[1]*row1[1] + filter[2]*row1[2] + filter[3]*row2[0] + filter[4]*row2[1] + filter[5]*row2[2] + filter[6]*row3[0] + filter[7]*row3[1] + filter[8]*row3[2]);
+ fp[0] = mfac*row2[1] + fac*(filter[0]*row1[0] + filter[1]*row1[1] + filter[2]*row1[2] + filter[3]*row2[0] + filter[4]*row2[1] + filter[5]*row2[2] + filter[6]*row3[0] + filter[7]*row3[1] + filter[8]*row3[2]);
fp++; row1++; row2++; row3++;
}
- fp[0]= row2[1];
+ fp[0] = row2[1];
}
else if (pixlen==2) {
- fp[0]= row2[0];
- fp[1]= row2[1];
+ fp[0] = row2[0];
+ fp[1] = row2[1];
fp+= 2;
for (x=2; x<rowlen; x++) {
for (c=0; c<2; c++) {
- fp[0]= mfac*row2[2] + fac*(filter[0]*row1[0] + filter[1]*row1[2] + filter[2]*row1[4] + filter[3]*row2[0] + filter[4]*row2[2] + filter[5]*row2[4] + filter[6]*row3[0] + filter[7]*row3[2] + filter[8]*row3[4]);
+ fp[0] = mfac*row2[2] + fac*(filter[0]*row1[0] + filter[1]*row1[2] + filter[2]*row1[4] + filter[3]*row2[0] + filter[4]*row2[2] + filter[5]*row2[4] + filter[6]*row3[0] + filter[7]*row3[2] + filter[8]*row3[4]);
fp++; row1++; row2++; row3++;
}
}
- fp[0]= row2[2];
- fp[1]= row2[3];
+ fp[0] = row2[2];
+ fp[1] = row2[3];
}
else if (pixlen==3) {
copy_v3_v3(fp, row2);
@@ -145,7 +145,7 @@ static void do_filter3(CompBuf *out, CompBuf *in, float *filter, float fac)
for (x=2; x<rowlen; x++) {
for (c=0; c<3; c++) {
- fp[0]= mfac*row2[3] + fac*(filter[0]*row1[0] + filter[1]*row1[3] + filter[2]*row1[6] + filter[3]*row2[0] + filter[4]*row2[3] + filter[5]*row2[6] + filter[6]*row3[0] + filter[7]*row3[3] + filter[8]*row3[6]);
+ fp[0] = mfac*row2[3] + fac*(filter[0]*row1[0] + filter[1]*row1[3] + filter[2]*row1[6] + filter[3]*row2[0] + filter[4]*row2[3] + filter[5]*row2[6] + filter[6]*row3[0] + filter[7]*row3[3] + filter[8]*row3[6]);
fp++; row1++; row2++; row3++;
}
}
@@ -157,7 +157,7 @@ static void do_filter3(CompBuf *out, CompBuf *in, float *filter, float fac)
for (x=2; x<rowlen; x++) {
for (c=0; c<4; c++) {
- fp[0]= mfac*row2[4] + fac*(filter[0]*row1[0] + filter[1]*row1[4] + filter[2]*row1[8] + filter[3]*row2[0] + filter[4]*row2[4] + filter[5]*row2[8] + filter[6]*row3[0] + filter[7]*row3[4] + filter[8]*row3[8]);
+ fp[0] = mfac*row2[4] + fac*(filter[0]*row1[0] + filter[1]*row1[4] + filter[2]*row1[8] + filter[3]*row2[0] + filter[4]*row2[4] + filter[5]*row2[8] + filter[6]*row3[0] + filter[7]*row3[4] + filter[8]*row3[8]);
fp++; row1++; row2++; row3++;
}
}
@@ -169,13 +169,13 @@ static void do_filter3(CompBuf *out, CompBuf *in, float *filter, float fac)
static void node_composit_exec_filter(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
- static float soft[9]= {1/16.0f, 2/16.0f, 1/16.0f, 2/16.0f, 4/16.0f, 2/16.0f, 1/16.0f, 2/16.0f, 1/16.0f};
- float sharp[9]= {-1, -1, -1, -1, 9, -1, -1, -1, -1};
- float laplace[9]= {-1/8.0f, -1/8.0f, -1/8.0f, -1/8.0f, 1.0f, -1/8.0f, -1/8.0f, -1/8.0f, -1/8.0f};
- float sobel[9]= {1, 2, 1, 0, 0, 0, -1, -2, -1};
- float prewitt[9]= {1, 1, 1, 0, 0, 0, -1, -1, -1};
- float kirsch[9]= {5, 5, 5, -3, -3, -3, -2, -2, -2};
- float shadow[9]= {1, 2, 1, 0, 1, 0, -1, -2, -1};
+ static float soft[9] = {1/16.0f, 2/16.0f, 1/16.0f, 2/16.0f, 4/16.0f, 2/16.0f, 1/16.0f, 2/16.0f, 1/16.0f};
+ float sharp[9] = {-1, -1, -1, -1, 9, -1, -1, -1, -1};
+ float laplace[9] = {-1/8.0f, -1/8.0f, -1/8.0f, -1/8.0f, 1.0f, -1/8.0f, -1/8.0f, -1/8.0f, -1/8.0f};
+ float sobel[9] = {1, 2, 1, 0, 0, 0, -1, -2, -1};
+ float prewitt[9] = {1, 1, 1, 0, 0, 0, -1, -1, -1};
+ float kirsch[9] = {5, 5, 5, -3, -3, -3, -2, -2, -2};
+ float shadow[9] = {1, 2, 1, 0, 1, 0, -1, -2, -1};
if (out[0]->hasoutput==0) return;
diff --git a/source/blender/nodes/composite/nodes/node_composite_flip.c b/source/blender/nodes/composite/nodes/node_composite_flip.c
index 147e7591af7..4aa98d173e7 100644
--- a/source/blender/nodes/composite/nodes/node_composite_flip.c
+++ b/source/blender/nodes/composite/nodes/node_composite_flip.c
@@ -33,12 +33,12 @@
#include "node_composite_util.h"
/* **************** Flip ******************** */
-static bNodeSocketTemplate cmp_node_flip_in[]= {
+static bNodeSocketTemplate cmp_node_flip_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_flip_out[]= {
+static bNodeSocketTemplate cmp_node_flip_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -75,7 +75,7 @@ static void node_composit_exec_flip(void *UNUSED(data), bNode *node, bNodeStack
outfp += (src_width-1)*src_pix;
for (x=0; x<src_width; x++) {
for (i=0; i<src_pix; i++) {
- outfp[i]= srcfp[i];
+ outfp[i] = srcfp[i];
}
outfp -= src_pix;
srcfp += src_pix;
diff --git a/source/blender/nodes/composite/nodes/node_composite_gamma.c b/source/blender/nodes/composite/nodes/node_composite_gamma.c
index 87155478035..b8c99894301 100644
--- a/source/blender/nodes/composite/nodes/node_composite_gamma.c
+++ b/source/blender/nodes/composite/nodes/node_composite_gamma.c
@@ -35,12 +35,12 @@
/* **************** Gamma Tools ******************** */
-static bNodeSocketTemplate cmp_node_gamma_in[]= {
+static bNodeSocketTemplate cmp_node_gamma_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Gamma"), 1.0f, 0.0f, 0.0f, 0.0f, 0.001f, 10.0f, PROP_UNSIGNED},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_gamma_out[]= {
+static bNodeSocketTemplate cmp_node_gamma_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_glare.c b/source/blender/nodes/composite/nodes/node_composite_glare.c
index 7d6c0cb1a29..950d8a56f58 100644
--- a/source/blender/nodes/composite/nodes/node_composite_glare.c
+++ b/source/blender/nodes/composite/nodes/node_composite_glare.c
@@ -32,11 +32,11 @@
#include "node_composite_util.h"
-static bNodeSocketTemplate cmp_node_glare_in[]= {
+static bNodeSocketTemplate cmp_node_glare_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_glare_out[]= {
+static bNodeSocketTemplate cmp_node_glare_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_hueSatVal.c b/source/blender/nodes/composite/nodes/node_composite_hueSatVal.c
index c8784ceedb7..d52e3d01a32 100644
--- a/source/blender/nodes/composite/nodes/node_composite_hueSatVal.c
+++ b/source/blender/nodes/composite/nodes/node_composite_hueSatVal.c
@@ -34,12 +34,12 @@
/* **************** Hue Saturation ******************** */
-static bNodeSocketTemplate cmp_node_hue_sat_in[]= {
+static bNodeSocketTemplate cmp_node_hue_sat_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_hue_sat_out[]= {
+static bNodeSocketTemplate cmp_node_hue_sat_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -60,10 +60,10 @@ static void do_hue_sat_fac(bNode *node, float *out, float *in, float *fac)
hsv[2]*= nhs->val;
hsv_to_rgb(hsv[0], hsv[1], hsv[2], col, col+1, col+2);
- out[0]= mfac*in[0] + *fac*col[0];
- out[1]= mfac*in[1] + *fac*col[1];
- out[2]= mfac*in[2] + *fac*col[2];
- out[3]= in[3];
+ out[0] = mfac*in[0] + *fac*col[0];
+ out[1] = mfac*in[1] + *fac*col[1];
+ out[2] = mfac*in[2] + *fac*col[2];
+ out[3] = in[3];
}
else {
copy_v4_v4(out, in);
@@ -89,7 +89,7 @@ static void node_composit_exec_hue_sat(void *UNUSED(data), bNode *node, bNodeSta
out[0]->data= stackbuf;
- /* get rid of intermediary cbuf if it's extra */
+ /* get rid of intermediary cbuf if it's extra */
if (stackbuf!=cbuf)
free_compbuf(cbuf);
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_huecorrect.c b/source/blender/nodes/composite/nodes/node_composite_huecorrect.c
index 42077cd5c06..f751dbea8d2 100644
--- a/source/blender/nodes/composite/nodes/node_composite_huecorrect.c
+++ b/source/blender/nodes/composite/nodes/node_composite_huecorrect.c
@@ -32,13 +32,13 @@
#include "node_composite_util.h"
-static bNodeSocketTemplate cmp_node_huecorrect_in[]= {
+static bNodeSocketTemplate cmp_node_huecorrect_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_huecorrect_out[]= {
+static bNodeSocketTemplate cmp_node_huecorrect_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -71,7 +71,7 @@ static void do_huecorrect(bNode *node, float *out, float *in)
/* convert back to rgb */
hsv_to_rgb(hsv[0], hsv[1], hsv[2], out, out+1, out+2);
- out[3]= in[3];
+ out[3] = in[3];
}
static void do_huecorrect_fac(bNode *node, float *out, float *in, float *fac)
@@ -101,10 +101,10 @@ static void do_huecorrect_fac(bNode *node, float *out, float *in, float *fac)
/* convert back to rgb */
hsv_to_rgb(hsv[0], hsv[1], hsv[2], rgb, rgb+1, rgb+2);
- out[0]= mfac*in[0] + *fac*rgb[0];
- out[1]= mfac*in[1] + *fac*rgb[1];
- out[2]= mfac*in[2] + *fac*rgb[2];
- out[3]= in[3];
+ out[0] = mfac*in[0] + *fac*rgb[0];
+ out[1] = mfac*in[1] + *fac*rgb[1];
+ out[2] = mfac*in[2] + *fac*rgb[2];
+ out[3] = in[3];
}
static void node_composit_exec_huecorrect(void *UNUSED(data), bNode *node, bNodeStack **in, bNodeStack **out)
diff --git a/source/blender/nodes/composite/nodes/node_composite_idMask.c b/source/blender/nodes/composite/nodes/node_composite_idMask.c
index 31a3a765ebe..ef0c5021192 100644
--- a/source/blender/nodes/composite/nodes/node_composite_idMask.c
+++ b/source/blender/nodes/composite/nodes/node_composite_idMask.c
@@ -35,11 +35,11 @@
/* **************** ID Mask ******************** */
-static bNodeSocketTemplate cmp_node_idmask_in[]= {
+static bNodeSocketTemplate cmp_node_idmask_in[] = {
{ SOCK_FLOAT, 1, N_("ID value"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_idmask_out[]= {
+static bNodeSocketTemplate cmp_node_idmask_out[] = {
{ SOCK_FLOAT, 0, N_("Alpha")},
{ -1, 0, "" }
};
@@ -56,14 +56,14 @@ static void do_idmask(CompBuf *stackbuf, CompBuf *cbuf, float idnr)
rect= cbuf->rect;
for (x= cbuf->x*cbuf->y - 1; x>=0; x--)
if (rect[x]==idnr)
- abuf[x]= 255;
+ abuf[x] = 255;
antialias_tagbuf(cbuf->x, cbuf->y, abuf);
rect= stackbuf->rect;
for (x= cbuf->x*cbuf->y - 1; x>=0; x--)
if (abuf[x]>1)
- rect[x]= (1.0f/255.0f)*(float)abuf[x];
+ rect[x] = (1.0f/255.0f)*(float)abuf[x];
MEM_freeN(abuf);
}
@@ -78,7 +78,7 @@ static void do_idmask_fsa(CompBuf *stackbuf, CompBuf *cbuf, float idnr)
rs= stackbuf->rect;
for (x= cbuf->x*cbuf->y - 1; x>=0; x--)
if (rect[x]==idnr)
- rs[x]= 1.0f;
+ rs[x] = 1.0f;
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_image.c b/source/blender/nodes/composite/nodes/node_composite_image.c
index 9f3874560ac..150382c1f8f 100644
--- a/source/blender/nodes/composite/nodes/node_composite_image.c
+++ b/source/blender/nodes/composite/nodes/node_composite_image.c
@@ -34,7 +34,7 @@
/* **************** IMAGE (and RenderResult, multilayer image) ******************** */
-static bNodeSocketTemplate cmp_node_rlayers_out[]= {
+static bNodeSocketTemplate cmp_node_rlayers_out[] = {
{ SOCK_RGBA, 0, N_("Image"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Alpha"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Z"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
@@ -505,7 +505,7 @@ static void node_composit_exec_image(void *data, bNode *node, bNodeStack **UNUSE
generate_preview(data, node, stackbuf);
}
}
- }
+ }
}
#endif /* WITH_COMPOSITOR_LEGACY */
diff --git a/source/blender/nodes/composite/nodes/node_composite_invert.c b/source/blender/nodes/composite/nodes/node_composite_invert.c
index b0e656b173b..2db6e42f603 100644
--- a/source/blender/nodes/composite/nodes/node_composite_invert.c
+++ b/source/blender/nodes/composite/nodes/node_composite_invert.c
@@ -32,15 +32,15 @@
#include "node_composite_util.h"
/* **************** INVERT ******************** */
-static bNodeSocketTemplate cmp_node_invert_in[]= {
- { SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
- { SOCK_RGBA, 1, N_("Color"), 1.0f, 1.0f, 1.0f, 1.0f},
- { -1, 0, "" }
+static bNodeSocketTemplate cmp_node_invert_in[] = {
+ { SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_RGBA, 1, N_("Color"), 1.0f, 1.0f, 1.0f, 1.0f},
+ { -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_invert_out[]= {
- { SOCK_RGBA, 0, N_("Color")},
- { -1, 0, "" }
+static bNodeSocketTemplate cmp_node_invert_out[] = {
+ { SOCK_RGBA, 0, N_("Color")},
+ { -1, 0, "" }
};
#ifdef WITH_COMPOSITOR_LEGACY
diff --git a/source/blender/nodes/composite/nodes/node_composite_lensdist.c b/source/blender/nodes/composite/nodes/node_composite_lensdist.c
index a4983cce8b8..c3f64f0eacb 100644
--- a/source/blender/nodes/composite/nodes/node_composite_lensdist.c
+++ b/source/blender/nodes/composite/nodes/node_composite_lensdist.c
@@ -32,13 +32,13 @@
#include "node_composite_util.h"
-static bNodeSocketTemplate cmp_node_lensdist_in[]= {
+static bNodeSocketTemplate cmp_node_lensdist_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Distort"), 0.f, 0.f, 0.f, 0.f, -0.999f, 1.f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("Dispersion"), 0.f, 0.f, 0.f, 0.f, 0.f, 1.f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_lensdist_out[]= {
+static bNodeSocketTemplate cmp_node_lensdist_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -74,7 +74,7 @@ static void lensDistort(CompBuf *dst, CompBuf *src, float kr, float kg, float kb
qd_getPixelLerpChan(tsrc, (u*dst->x - kr) - 0.5f, v*dst->y - 0.5f, 2, colp[x]+2);
/* set alpha */
- colp[x][3]= 1.0f;
+ colp[x][3] = 1.0f;
}
}
free_compbuf(tsrc);
@@ -159,7 +159,7 @@ static void lensDistort(CompBuf *dst, CompBuf *src, float kr, float kg, float kb
if (db) colp[x][2] = 2.f*tc[2] / (float)db;
/* set alpha */
- colp[x][3]= 1.0f;
+ colp[x][3] = 1.0f;
}
}
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_levels.c b/source/blender/nodes/composite/nodes/node_composite_levels.c
index 601516c5bb0..57d94d6cb4d 100644
--- a/source/blender/nodes/composite/nodes/node_composite_levels.c
+++ b/source/blender/nodes/composite/nodes/node_composite_levels.c
@@ -34,12 +34,12 @@
/* **************** LEVELS ******************** */
-static bNodeSocketTemplate cmp_node_view_levels_in[]= {
+static bNodeSocketTemplate cmp_node_view_levels_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_view_levels_out[]={
+static bNodeSocketTemplate cmp_node_view_levels_out[] = {
{SOCK_FLOAT, 0, N_("Mean")},
{SOCK_FLOAT, 0, N_("Std Dev")},
{-1, 0, ""}
@@ -101,7 +101,7 @@ static void fill_bins(bNode *node, CompBuf* in, int* bins)
bins[ivalue]+=1;
} /*end if alpha */
}
- }
+ }
}
static float brightness_mean(bNode *node, CompBuf* in)
@@ -275,8 +275,8 @@ static void node_composit_exec_view_levels(void *data, bNode *node, bNodeStack *
if (in[0]->hasinput==0) return;
if (in[0]->data==NULL) return;
- histogram=alloc_compbuf(256, 256, CB_RGBA, 1);
- cbuf=typecheck_compbuf(in[0]->data, CB_RGBA);
+ histogram=alloc_compbuf(256, 256, CB_RGBA, 1);
+ cbuf=typecheck_compbuf(in[0]->data, CB_RGBA);
/*initalize bins*/
for (x=0; x<256; x++) {
@@ -300,9 +300,9 @@ static void node_composit_exec_view_levels(void *data, bNode *node, bNodeStack *
#endif
if (out[0]->hasoutput)
- out[0]->vec[0]= mean;
+ out[0]->vec[0] = mean;
if (out[1]->hasoutput)
- out[1]->vec[0]= std_dev;
+ out[1]->vec[0] = std_dev;
generate_preview(data, node, histogram);
diff --git a/source/blender/nodes/composite/nodes/node_composite_lummaMatte.c b/source/blender/nodes/composite/nodes/node_composite_lummaMatte.c
index 61cd4493f39..ed232933139 100644
--- a/source/blender/nodes/composite/nodes/node_composite_lummaMatte.c
+++ b/source/blender/nodes/composite/nodes/node_composite_lummaMatte.c
@@ -34,12 +34,12 @@
/* ******************* Luma Matte Node ********************************* */
-static bNodeSocketTemplate cmp_node_luma_matte_in[]={
+static bNodeSocketTemplate cmp_node_luma_matte_in[] = {
{SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{-1, 0, ""}
};
-static bNodeSocketTemplate cmp_node_luma_matte_out[]={
+static bNodeSocketTemplate cmp_node_luma_matte_out[] = {
{SOCK_RGBA, 0, N_("Image")},
{SOCK_FLOAT, 0, N_("Matte")},
{-1, 0, ""}
diff --git a/source/blender/nodes/composite/nodes/node_composite_mapUV.c b/source/blender/nodes/composite/nodes/node_composite_mapUV.c
index 04d2eaff4f4..40092a84367 100644
--- a/source/blender/nodes/composite/nodes/node_composite_mapUV.c
+++ b/source/blender/nodes/composite/nodes/node_composite_mapUV.c
@@ -34,12 +34,12 @@
/* **************** Map UV ******************** */
-static bNodeSocketTemplate cmp_node_mapuv_in[]= {
+static bNodeSocketTemplate cmp_node_mapuv_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_VECTOR, 1, N_("UV"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_mapuv_out[]= {
+static bNodeSocketTemplate cmp_node_mapuv_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -135,7 +135,7 @@ static void do_mapuv(CompBuf *stackbuf, CompBuf *cbuf, CompBuf *uvbuf, float thr
}
}
- IMB_freeImBuf(ibuf);
+ IMB_freeImBuf(ibuf);
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_mapValue.c b/source/blender/nodes/composite/nodes/node_composite_mapValue.c
index be69c11b35f..677d5bd5013 100644
--- a/source/blender/nodes/composite/nodes/node_composite_mapValue.c
+++ b/source/blender/nodes/composite/nodes/node_composite_mapValue.c
@@ -33,11 +33,11 @@
#include "node_composite_util.h"
/* **************** MAP VALUE ******************** */
-static bNodeSocketTemplate cmp_node_map_value_in[]= {
+static bNodeSocketTemplate cmp_node_map_value_in[] = {
{ SOCK_FLOAT, 1, N_("Value"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_map_value_out[]= {
+static bNodeSocketTemplate cmp_node_map_value_out[] = {
{ SOCK_FLOAT, 0, N_("Value")},
{ -1, 0, "" }
};
@@ -48,13 +48,13 @@ static void do_map_value(bNode *node, float *out, float *src)
{
TexMapping *texmap= node->storage;
- out[0]= (src[0] + texmap->loc[0])*texmap->size[0];
+ out[0] = (src[0] + texmap->loc[0])*texmap->size[0];
if (texmap->flag & TEXMAP_CLIP_MIN)
if (out[0]<texmap->min[0])
- out[0]= texmap->min[0];
+ out[0] = texmap->min[0];
if (texmap->flag & TEXMAP_CLIP_MAX)
if (out[0]>texmap->max[0])
- out[0]= texmap->max[0];
+ out[0] = texmap->max[0];
}
static void node_composit_exec_map_value(void *UNUSED(data), bNode *node, bNodeStack **in, bNodeStack **out)
diff --git a/source/blender/nodes/composite/nodes/node_composite_math.c b/source/blender/nodes/composite/nodes/node_composite_math.c
index 1bddfe0852a..c99e12a95b9 100644
--- a/source/blender/nodes/composite/nodes/node_composite_math.c
+++ b/source/blender/nodes/composite/nodes/node_composite_math.c
@@ -33,15 +33,15 @@
#include "node_composite_util.h"
/* **************** SCALAR MATH ******************** */
-static bNodeSocketTemplate cmp_node_math_in[]= {
- { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
- { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
- { -1, 0, "" }
+static bNodeSocketTemplate cmp_node_math_in[] = {
+ { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
+ { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
+ { -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_math_out[]= {
- { SOCK_FLOAT, 0, N_("Value")},
- { -1, 0, "" }
+static bNodeSocketTemplate cmp_node_math_out[] = {
+ { SOCK_FLOAT, 0, N_("Value")},
+ { -1, 0, "" }
};
#ifdef WITH_COMPOSITOR_LEGACY
@@ -50,63 +50,63 @@ static void do_math(bNode *node, float *out, float *in, float *in2)
{
switch (node->custom1) {
case 0: /* Add */
- out[0]= in[0] + in2[0];
+ out[0] = in[0] + in2[0];
break;
case 1: /* Subtract */
- out[0]= in[0] - in2[0];
+ out[0] = in[0] - in2[0];
break;
case 2: /* Multiply */
- out[0]= in[0] * in2[0];
+ out[0] = in[0] * in2[0];
break;
case 3: /* Divide */
{
if (in2[0]==0) /* We don't want to divide by zero. */
- out[0]= 0.0;
+ out[0] = 0.0;
else
- out[0]= in[0] / in2[0];
+ out[0] = in[0] / in2[0];
}
break;
case 4: /* Sine */
- out[0]= sin(in[0]);
+ out[0] = sin(in[0]);
break;
case 5: /* Cosine */
- out[0]= cos(in[0]);
+ out[0] = cos(in[0]);
break;
case 6: /* Tangent */
- out[0]= tan(in[0]);
+ out[0] = tan(in[0]);
break;
case 7: /* Arc-Sine */
{
/* Can't do the impossible... */
if (in[0] <= 1 && in[0] >= -1 )
- out[0]= asin(in[0]);
+ out[0] = asin(in[0]);
else
- out[0]= 0.0;
+ out[0] = 0.0;
}
break;
case 8: /* Arc-Cosine */
{
/* Can't do the impossible... */
if ( in[0] <= 1 && in[0] >= -1 )
- out[0]= acos(in[0]);
+ out[0] = acos(in[0]);
else
- out[0]= 0.0;
+ out[0] = 0.0;
}
break;
case 9: /* Arc-Tangent */
- out[0]= atan(in[0]);
+ out[0] = atan(in[0]);
break;
case 10: /* Power */
{
/* Only raise negative numbers by full integers */
if ( in[0] >= 0 ) {
- out[0]= pow(in[0], in2[0]);
+ out[0] = pow(in[0], in2[0]);
}
else {
float y_mod_1 = fmod(in2[0], 1);
/* if input value is not nearly an integer, fall back to zero, nicer than straight rounding */
if (y_mod_1 > 0.999f || y_mod_1 < 0.001f) {
- out[0]= powf(in[0], floorf(in2[0] + 0.5f));
+ out[0] = powf(in[0], floorf(in2[0] + 0.5f));
}
else {
out[0] = 0.0f;
@@ -118,50 +118,50 @@ static void do_math(bNode *node, float *out, float *in, float *in2)
{
/* Don't want any imaginary numbers... */
if ( in[0] > 0 && in2[0] > 0 )
- out[0]= log(in[0]) / log(in2[0]);
+ out[0] = log(in[0]) / log(in2[0]);
else
- out[0]= 0.0;
+ out[0] = 0.0;
}
break;
case 12: /* Minimum */
{
if ( in[0] < in2[0] )
- out[0]= in[0];
+ out[0] = in[0];
else
- out[0]= in2[0];
+ out[0] = in2[0];
}
break;
case 13: /* Maximum */
{
if ( in[0] > in2[0] )
- out[0]= in[0];
+ out[0] = in[0];
else
- out[0]= in2[0];
+ out[0] = in2[0];
}
break;
case 14: /* Round */
{
/* round by the second value */
if ( in2[0] != 0.0f )
- out[0]= floorf(in[0] / in2[0] + 0.5f) * in2[0];
+ out[0] = floorf(in[0] / in2[0] + 0.5f) * in2[0];
else
- out[0]= floorf(in[0] + 0.5f);
+ out[0] = floorf(in[0] + 0.5f);
}
break;
case 15: /* Less Than */
{
if ( in[0] < in2[0] )
- out[0]= 1.0f;
+ out[0] = 1.0f;
else
- out[0]= 0.0f;
+ out[0] = 0.0f;
}
break;
case 16: /* Greater Than */
{
if ( in[0] > in2[0] )
- out[0]= 1.0f;
+ out[0] = 1.0f;
else
- out[0]= 0.0f;
+ out[0] = 0.0f;
}
break;
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_mixrgb.c b/source/blender/nodes/composite/nodes/node_composite_mixrgb.c
index e2c9a5abcb1..5d3ee480612 100644
--- a/source/blender/nodes/composite/nodes/node_composite_mixrgb.c
+++ b/source/blender/nodes/composite/nodes/node_composite_mixrgb.c
@@ -32,13 +32,13 @@
#include "node_composite_util.h"
/* **************** MIX RGB ******************** */
-static bNodeSocketTemplate cmp_node_mix_rgb_in[]= {
+static bNodeSocketTemplate cmp_node_mix_rgb_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.0f, PROP_FACTOR},
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_mix_rgb_out[]= {
+static bNodeSocketTemplate cmp_node_mix_rgb_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -55,7 +55,7 @@ static void do_mix_rgb(bNode *node, float *out, float *in1, float *in2, float *f
else
ramp_blend(node->custom1, col, fac[0], in2);
copy_v3_v3(out, col);
- out[3]= in1[3];
+ out[3] = in1[3];
}
static void node_composit_exec_mix_rgb(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
diff --git a/source/blender/nodes/composite/nodes/node_composite_normal.c b/source/blender/nodes/composite/nodes/node_composite_normal.c
index 6f1e86e2760..93fd7ca1c1b 100644
--- a/source/blender/nodes/composite/nodes/node_composite_normal.c
+++ b/source/blender/nodes/composite/nodes/node_composite_normal.c
@@ -34,12 +34,12 @@
/* **************** NORMAL ******************** */
-static bNodeSocketTemplate cmp_node_normal_in[]= {
+static bNodeSocketTemplate cmp_node_normal_in[] = {
{ SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_DIRECTION},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_normal_out[]= {
+static bNodeSocketTemplate cmp_node_normal_out[] = {
{ SOCK_VECTOR, 0, N_("Normal")},
{ SOCK_FLOAT, 0, N_("Dot")},
{ -1, 0, "" }
@@ -53,7 +53,7 @@ static void do_normal(bNode *node, float *out, float *in)
float *nor= ((bNodeSocketValueVector*)sock->default_value)->value;
/* render normals point inside... the widget points outside */
- out[0]= -dot_v3v3(nor, in);
+ out[0] = -dot_v3v3(nor, in);
}
/* generates normal, does dot product */
@@ -68,7 +68,7 @@ static void node_composit_exec_normal(void *UNUSED(data), bNode *node, bNodeStac
if (in[0]->data==NULL) {
copy_v3_v3(out[0]->vec, nor);
/* render normals point inside... the widget points outside */
- out[1]->vec[0]= -dot_v3v3(out[0]->vec, in[0]->vec);
+ out[1]->vec[0] = -dot_v3v3(out[0]->vec, in[0]->vec);
}
else if (out[1]->hasoutput) {
/* make output size of input image */
diff --git a/source/blender/nodes/composite/nodes/node_composite_normalize.c b/source/blender/nodes/composite/nodes/node_composite_normalize.c
index 1d2312d8280..19b543dce5d 100644
--- a/source/blender/nodes/composite/nodes/node_composite_normalize.c
+++ b/source/blender/nodes/composite/nodes/node_composite_normalize.c
@@ -34,11 +34,11 @@
/* **************** NORMALIZE single channel, useful for Z buffer ******************** */
-static bNodeSocketTemplate cmp_node_normalize_in[]= {
+static bNodeSocketTemplate cmp_node_normalize_in[] = {
{ SOCK_FLOAT, 1, N_("Value"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_normalize_out[]= {
+static bNodeSocketTemplate cmp_node_normalize_out[] = {
{ SOCK_FLOAT, 0, N_("Value")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_pixelate.c b/source/blender/nodes/composite/nodes/node_composite_pixelate.c
new file mode 100644
index 00000000000..5eac4867a23
--- /dev/null
+++ b/source/blender/nodes/composite/nodes/node_composite_pixelate.c
@@ -0,0 +1,57 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2006 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Jeroen Bakker
+ * Monique Dewanchand
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/nodes/composite/nodes/node_composite_pixelate.c
+ * \ingroup cmpnodes
+ */
+
+
+#include "node_composite_util.h"
+
+
+/* **************** Pixelate ******************** */
+
+static bNodeSocketTemplate cmp_node_pixelate_in[] = {
+ { SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { -1, 0, "" }
+};
+static bNodeSocketTemplate cmp_node_pixelate_out[] = {
+ { SOCK_RGBA, 0, N_("Color")},
+ { -1, 0, "" }
+};
+
+void register_node_type_cmp_pixelate(bNodeTreeType *ttype)
+{
+ static bNodeType ntype;
+
+ node_type_base(ttype, &ntype, CMP_NODE_PIXELATE, "Pixelate", NODE_CLASS_OP_FILTER, NODE_OPTIONS);
+ node_type_socket_templates(&ntype, cmp_node_pixelate_in, cmp_node_pixelate_out);
+ node_type_size(&ntype, 130, 100, 130);
+
+ nodeRegisterType(ttype, &ntype);
+}
diff --git a/source/blender/nodes/composite/nodes/node_composite_premulkey.c b/source/blender/nodes/composite/nodes/node_composite_premulkey.c
index d791983b069..7f7b7692b02 100644
--- a/source/blender/nodes/composite/nodes/node_composite_premulkey.c
+++ b/source/blender/nodes/composite/nodes/node_composite_premulkey.c
@@ -35,11 +35,11 @@
/* **************** Premul and Key Alpha Convert ******************** */
-static bNodeSocketTemplate cmp_node_premulkey_in[]= {
+static bNodeSocketTemplate cmp_node_premulkey_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_premulkey_out[]= {
+static bNodeSocketTemplate cmp_node_premulkey_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_rgb.c b/source/blender/nodes/composite/nodes/node_composite_rgb.c
index 65c1dcdb7bb..54fba650783 100644
--- a/source/blender/nodes/composite/nodes/node_composite_rgb.c
+++ b/source/blender/nodes/composite/nodes/node_composite_rgb.c
@@ -34,7 +34,7 @@
/* **************** RGB ******************** */
-static bNodeSocketTemplate cmp_node_rgb_out[]= {
+static bNodeSocketTemplate cmp_node_rgb_out[] = {
{ SOCK_RGBA, 0, N_("RGBA"), 0.5f, 0.5f, 0.5f, 1.0f},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_rotate.c b/source/blender/nodes/composite/nodes/node_composite_rotate.c
index 8968fd5fb3a..9a76764b97e 100644
--- a/source/blender/nodes/composite/nodes/node_composite_rotate.c
+++ b/source/blender/nodes/composite/nodes/node_composite_rotate.c
@@ -34,12 +34,12 @@
/* **************** Rotate ******************** */
-static bNodeSocketTemplate cmp_node_rotate_in[]= {
+static bNodeSocketTemplate cmp_node_rotate_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Degr"), 0.0f, 0.0f, 0.0f, 0.0f, -10000.0f, 10000.0f, PROP_ANGLE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_rotate_out[]= {
+static bNodeSocketTemplate cmp_node_rotate_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_sepcombHSVA.c b/source/blender/nodes/composite/nodes/node_composite_sepcombHSVA.c
index ebc18cd19eb..f1a75493718 100644
--- a/source/blender/nodes/composite/nodes/node_composite_sepcombHSVA.c
+++ b/source/blender/nodes/composite/nodes/node_composite_sepcombHSVA.c
@@ -34,11 +34,11 @@
/* **************** SEPARATE HSVA ******************** */
-static bNodeSocketTemplate cmp_node_sephsva_in[]= {
+static bNodeSocketTemplate cmp_node_sephsva_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_sephsva_out[]= {
+static bNodeSocketTemplate cmp_node_sephsva_out[] = {
{ SOCK_FLOAT, 0, N_("H")},
{ SOCK_FLOAT, 0, N_("S")},
{ SOCK_FLOAT, 0, N_("V")},
@@ -54,10 +54,10 @@ static void do_sephsva(bNode *UNUSED(node), float *out, float *in)
rgb_to_hsv(in[0], in[1], in[2], &h, &s, &v);
- out[0]= h;
- out[1]= s;
- out[2]= v;
- out[3]= in[3];
+ out[0] = h;
+ out[1] = s;
+ out[2] = v;
+ out[3] = in[3];
}
static void node_composit_exec_sephsva(void *UNUSED(data), bNode *node, bNodeStack **in, bNodeStack **out)
@@ -97,7 +97,7 @@ static void node_composit_exec_sephsva(void *UNUSED(data), bNode *node, bNodeSta
/*not used anymore */
if (cbuf2!=cbuf)
free_compbuf(cbuf2);
- free_compbuf(cbuf);
+ free_compbuf(cbuf);
}
}
@@ -126,7 +126,7 @@ static bNodeSocketTemplate cmp_node_combhsva_in[] = {
{ SOCK_FLOAT, 1, N_("A"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_combhsva_out[]= {
+static bNodeSocketTemplate cmp_node_combhsva_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_sepcombRGBA.c b/source/blender/nodes/composite/nodes/node_composite_sepcombRGBA.c
index 0c989ed3fc6..83b2c731020 100644
--- a/source/blender/nodes/composite/nodes/node_composite_sepcombRGBA.c
+++ b/source/blender/nodes/composite/nodes/node_composite_sepcombRGBA.c
@@ -33,11 +33,11 @@
#include "node_composite_util.h"
/* **************** SEPARATE RGBA ******************** */
-static bNodeSocketTemplate cmp_node_seprgba_in[]= {
+static bNodeSocketTemplate cmp_node_seprgba_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_seprgba_out[]= {
+static bNodeSocketTemplate cmp_node_seprgba_out[] = {
{ SOCK_FLOAT, 0, N_("R")},
{ SOCK_FLOAT, 0, N_("G")},
{ SOCK_FLOAT, 0, N_("B")},
@@ -98,14 +98,14 @@ void register_node_type_cmp_seprgba(bNodeTreeType *ttype)
/* **************** COMBINE RGBA ******************** */
-static bNodeSocketTemplate cmp_node_combrgba_in[]= {
+static bNodeSocketTemplate cmp_node_combrgba_in[] = {
{ SOCK_FLOAT, 1, N_("R"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("G"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("B"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("A"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_combrgba_out[]= {
+static bNodeSocketTemplate cmp_node_combrgba_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -150,7 +150,7 @@ static void node_composit_exec_combrgba(void *UNUSED(data), bNode *node, bNodeSt
do_combrgba, CB_VAL, CB_VAL, CB_VAL, CB_VAL);
out[0]->data= stackbuf;
- }
+ }
}
#endif /* WITH_COMPOSITOR_LEGACY */
diff --git a/source/blender/nodes/composite/nodes/node_composite_sepcombYCCA.c b/source/blender/nodes/composite/nodes/node_composite_sepcombYCCA.c
index ccae7cfe57f..982d674708c 100644
--- a/source/blender/nodes/composite/nodes/node_composite_sepcombYCCA.c
+++ b/source/blender/nodes/composite/nodes/node_composite_sepcombYCCA.c
@@ -34,11 +34,11 @@
/* **************** SEPARATE YCCA ******************** */
-static bNodeSocketTemplate cmp_node_sepycca_in[]= {
+static bNodeSocketTemplate cmp_node_sepycca_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_sepycca_out[]= {
+static bNodeSocketTemplate cmp_node_sepycca_out[] = {
{ SOCK_FLOAT, 0, N_("Y")},
{ SOCK_FLOAT, 0, N_("Cb")},
{ SOCK_FLOAT, 0, N_("Cr")},
@@ -55,10 +55,10 @@ static void do_sepycca_601(bNode *UNUSED(node), float *out, float *in)
rgb_to_ycc(in[0], in[1], in[2], &y, &cb, &cr, BLI_YCC_ITU_BT601);
/*divided by 255 to normalize for viewing in */
- out[0]= y/255.0f;
- out[1]= cb/255.0f;
- out[2]= cr/255.0f;
- out[3]= in[3];
+ out[0] = y/255.0f;
+ out[1] = cb/255.0f;
+ out[2] = cr/255.0f;
+ out[3] = in[3];
}
static void do_sepycca_709(bNode *UNUSED(node), float *out, float *in)
@@ -68,10 +68,10 @@ static void do_sepycca_709(bNode *UNUSED(node), float *out, float *in)
rgb_to_ycc(in[0], in[1], in[2], &y, &cb, &cr, BLI_YCC_ITU_BT709);
/*divided by 255 to normalize for viewing in */
- out[0]= y/255.0f;
- out[1]= cb/255.0f;
- out[2]= cr/255.0f;
- out[3]= in[3];
+ out[0] = y/255.0f;
+ out[1] = cb/255.0f;
+ out[2] = cr/255.0f;
+ out[3] = in[3];
}
static void do_sepycca_jfif(bNode *UNUSED(node), float *out, float *in)
@@ -81,10 +81,10 @@ static void do_sepycca_jfif(bNode *UNUSED(node), float *out, float *in)
rgb_to_ycc(in[0], in[1], in[2], &y, &cb, &cr, BLI_YCC_JFIF_0_255);
/*divided by 255 to normalize for viewing in */
- out[0]= y/255.0f;
- out[1]= cb/255.0f;
- out[2]= cr/255.0f;
- out[3]= in[3];
+ out[0] = y/255.0f;
+ out[1] = cb/255.0f;
+ out[2] = cr/255.0f;
+ out[3] = in[3];
}
static void node_composit_exec_sepycca(void *UNUSED(data), bNode *node, bNodeStack **in, bNodeStack **out)
@@ -167,14 +167,14 @@ void register_node_type_cmp_sepycca(bNodeTreeType *ttype)
/* **************** COMBINE YCCA ******************** */
-static bNodeSocketTemplate cmp_node_combycca_in[]= {
+static bNodeSocketTemplate cmp_node_combycca_in[] = {
{ SOCK_FLOAT, 1, N_("Y"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("Cb"), 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("Cr"), 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("A"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_combycca_out[]= {
+static bNodeSocketTemplate cmp_node_combycca_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
@@ -296,7 +296,7 @@ static void node_composit_exec_combycca(void *UNUSED(data), bNode *node, bNodeSt
}
out[0]->data= stackbuf;
- }
+ }
}
#endif /* WITH_COMPOSITOR_LEGACY */
diff --git a/source/blender/nodes/composite/nodes/node_composite_sepcombYUVA.c b/source/blender/nodes/composite/nodes/node_composite_sepcombYUVA.c
index 9b8c805b0f0..0a9575971b4 100644
--- a/source/blender/nodes/composite/nodes/node_composite_sepcombYUVA.c
+++ b/source/blender/nodes/composite/nodes/node_composite_sepcombYUVA.c
@@ -34,11 +34,11 @@
/* **************** SEPARATE YUVA ******************** */
-static bNodeSocketTemplate cmp_node_sepyuva_in[]= {
+static bNodeSocketTemplate cmp_node_sepyuva_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_sepyuva_out[]= {
+static bNodeSocketTemplate cmp_node_sepyuva_out[] = {
{ SOCK_FLOAT, 0, N_("Y")},
{ SOCK_FLOAT, 0, N_("U")},
{ SOCK_FLOAT, 0, N_("V")},
@@ -54,10 +54,10 @@ static void do_sepyuva(bNode *UNUSED(node), float *out, float *in)
rgb_to_yuv(in[0], in[1], in[2], &y, &u, &v);
- out[0]= y;
- out[1]= u;
- out[2]= v;
- out[3]= in[3];
+ out[0] = y;
+ out[1] = u;
+ out[2] = v;
+ out[3] = in[3];
}
static void node_composit_exec_sepyuva(void *UNUSED(data), bNode *node, bNodeStack **in, bNodeStack **out)
@@ -121,14 +121,14 @@ void register_node_type_cmp_sepyuva(bNodeTreeType *ttype)
/* **************** COMBINE YUVA ******************** */
-static bNodeSocketTemplate cmp_node_combyuva_in[]= {
+static bNodeSocketTemplate cmp_node_combyuva_in[] = {
{ SOCK_FLOAT, 1, N_("Y"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("U"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("V"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("A"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_combyuva_out[]= {
+static bNodeSocketTemplate cmp_node_combyuva_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_setalpha.c b/source/blender/nodes/composite/nodes/node_composite_setalpha.c
index 503815b74a0..59c104869fe 100644
--- a/source/blender/nodes/composite/nodes/node_composite_setalpha.c
+++ b/source/blender/nodes/composite/nodes/node_composite_setalpha.c
@@ -33,12 +33,12 @@
#include "node_composite_util.h"
/* **************** SET ALPHA ******************** */
-static bNodeSocketTemplate cmp_node_setalpha_in[]= {
+static bNodeSocketTemplate cmp_node_setalpha_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Alpha"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_setalpha_out[]= {
+static bNodeSocketTemplate cmp_node_setalpha_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_splitViewer.c b/source/blender/nodes/composite/nodes/node_composite_splitViewer.c
index f6811f526f7..73cf039c6df 100644
--- a/source/blender/nodes/composite/nodes/node_composite_splitViewer.c
+++ b/source/blender/nodes/composite/nodes/node_composite_splitViewer.c
@@ -33,7 +33,7 @@
#include "node_composite_util.h"
/* **************** SPLIT VIEWER ******************** */
-static bNodeSocketTemplate cmp_node_splitviewer_in[]= {
+static bNodeSocketTemplate cmp_node_splitviewer_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_RGBA, 1, N_("Image"), 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
@@ -167,7 +167,7 @@ void register_node_type_cmp_splitviewer(bNodeTreeType *ttype)
#endif
/* Do not allow muting for this node. */
- node_type_internal_connect(&ntype, NULL);
+ node_type_internal_links(&ntype, NULL);
nodeRegisterType(ttype, &ntype);
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_stabilize2d.c b/source/blender/nodes/composite/nodes/node_composite_stabilize2d.c
index fdf0b38e844..1787e075a14 100644
--- a/source/blender/nodes/composite/nodes/node_composite_stabilize2d.c
+++ b/source/blender/nodes/composite/nodes/node_composite_stabilize2d.c
@@ -35,12 +35,12 @@
/* **************** Translate ******************** */
-static bNodeSocketTemplate cmp_node_stabilize2d_in[]= {
+static bNodeSocketTemplate cmp_node_stabilize2d_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_stabilize2d_out[]= {
+static bNodeSocketTemplate cmp_node_stabilize2d_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_switch.c b/source/blender/nodes/composite/nodes/node_composite_switch.c
index 258fac18c11..7f9127c969f 100644
--- a/source/blender/nodes/composite/nodes/node_composite_switch.c
+++ b/source/blender/nodes/composite/nodes/node_composite_switch.c
@@ -34,13 +34,13 @@
#include "../node_composite_util.h"
/* **************** MIX RGB ******************** */
-static bNodeSocketTemplate cmp_node_switch_in[]= {
+static bNodeSocketTemplate cmp_node_switch_in[] = {
{ SOCK_RGBA, 1, N_("Off"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_RGBA, 1, N_("On"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_switch_out[]= {
+static bNodeSocketTemplate cmp_node_switch_out[] = {
{ SOCK_RGBA, 0, N_("Image"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_texture.c b/source/blender/nodes/composite/nodes/node_composite_texture.c
index 3fedccd7d12..b6518c48638 100644
--- a/source/blender/nodes/composite/nodes/node_composite_texture.c
+++ b/source/blender/nodes/composite/nodes/node_composite_texture.c
@@ -33,12 +33,12 @@
#include "node_composite_util.h"
/* **************** TEXTURE ******************** */
-static bNodeSocketTemplate cmp_node_texture_in[]= {
+static bNodeSocketTemplate cmp_node_texture_in[] = {
{ SOCK_VECTOR, 1, N_("Offset"), 0.0f, 0.0f, 0.0f, 0.0f, -2.0f, 2.0f, PROP_TRANSLATION},
{ SOCK_VECTOR, 1, N_("Scale"), 1.0f, 1.0f, 1.0f, 1.0f, -10.0f, 10.0f, PROP_XYZ},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_texture_out[]= {
+static bNodeSocketTemplate cmp_node_texture_out[] = {
{ SOCK_FLOAT, 0, N_("Value")},
{ SOCK_RGBA, 0, N_("Color")},
{ -1, 0, "" }
@@ -51,28 +51,28 @@ static void texture_procedural(CompBuf *cbuf, float *out, float xco, float yco)
{
bNode *node= cbuf->node;
TexResult texres= {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0, NULL};
- float vec[3], *size, nor[3]={0.0f, 0.0f, 0.0f}, col[4];
+ float vec[3], *size, nor[3] = {0.0f, 0.0f, 0.0f}, col[4];
int retval, type= cbuf->procedural_type;
size= cbuf->procedural_size;
- vec[0]= size[0]*(xco + cbuf->procedural_offset[0]);
- vec[1]= size[1]*(yco + cbuf->procedural_offset[1]);
- vec[2]= size[2]*cbuf->procedural_offset[2];
+ vec[0] = size[0]*(xco + cbuf->procedural_offset[0]);
+ vec[1] = size[1]*(yco + cbuf->procedural_offset[1]);
+ vec[2] = size[2]*cbuf->procedural_offset[2];
retval= multitex_ext((Tex *)node->id, vec, NULL, NULL, 0, &texres);
if (type==CB_VAL) {
if (texres.talpha)
- col[0]= texres.ta;
+ col[0] = texres.ta;
else
- col[0]= texres.tin;
+ col[0] = texres.tin;
}
else if (type==CB_RGBA) {
if (texres.talpha)
- col[3]= texres.ta;
+ col[3] = texres.ta;
else
- col[3]= texres.tin;
+ col[3] = texres.tin;
if ((retval & TEX_RGB)) {
copy_v3_v3(col, &texres.tr);
@@ -81,7 +81,7 @@ static void texture_procedural(CompBuf *cbuf, float *out, float xco, float yco)
copy_v3_fl(col, col[3]);
}
}
- else {
+ else {
copy_v3_v3(col, nor);
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_tonemap.c b/source/blender/nodes/composite/nodes/node_composite_tonemap.c
index 5e4efe2f3b1..00b1a5514dc 100644
--- a/source/blender/nodes/composite/nodes/node_composite_tonemap.c
+++ b/source/blender/nodes/composite/nodes/node_composite_tonemap.c
@@ -32,11 +32,11 @@
#include "node_composite_util.h"
-static bNodeSocketTemplate cmp_node_tonemap_in[]= {
+static bNodeSocketTemplate cmp_node_tonemap_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_tonemap_out[]= {
+static bNodeSocketTemplate cmp_node_tonemap_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_translate.c b/source/blender/nodes/composite/nodes/node_composite_translate.c
index 649902ff908..1c2963a2f08 100644
--- a/source/blender/nodes/composite/nodes/node_composite_translate.c
+++ b/source/blender/nodes/composite/nodes/node_composite_translate.c
@@ -35,13 +35,13 @@
/* **************** Translate ******************** */
-static bNodeSocketTemplate cmp_node_translate_in[]= {
+static bNodeSocketTemplate cmp_node_translate_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("X"), 0.0f, 0.0f, 0.0f, 0.0f, -10000.0f, 10000.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("Y"), 0.0f, 0.0f, 0.0f, 0.0f, -10000.0f, 10000.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_translate_out[]= {
+static bNodeSocketTemplate cmp_node_translate_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_valToRgb.c b/source/blender/nodes/composite/nodes/node_composite_valToRgb.c
index 87a776c7bea..5c111998b18 100644
--- a/source/blender/nodes/composite/nodes/node_composite_valToRgb.c
+++ b/source/blender/nodes/composite/nodes/node_composite_valToRgb.c
@@ -34,11 +34,11 @@
/* **************** VALTORGB ******************** */
-static bNodeSocketTemplate cmp_node_valtorgb_in[]= {
+static bNodeSocketTemplate cmp_node_valtorgb_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_valtorgb_out[]= {
+static bNodeSocketTemplate cmp_node_valtorgb_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ SOCK_FLOAT, 0, N_("Alpha")},
{ -1, 0, "" }
@@ -106,11 +106,11 @@ void register_node_type_cmp_valtorgb(bNodeTreeType *ttype)
/* **************** RGBTOBW ******************** */
-static bNodeSocketTemplate cmp_node_rgbtobw_in[]= {
+static bNodeSocketTemplate cmp_node_rgbtobw_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_rgbtobw_out[]= {
+static bNodeSocketTemplate cmp_node_rgbtobw_out[] = {
{ SOCK_FLOAT, 0, N_("Val"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_value.c b/source/blender/nodes/composite/nodes/node_composite_value.c
index 63ab4fcb58f..2c65fe6be19 100644
--- a/source/blender/nodes/composite/nodes/node_composite_value.c
+++ b/source/blender/nodes/composite/nodes/node_composite_value.c
@@ -33,7 +33,7 @@
#include "node_composite_util.h"
/* **************** VALUE ******************** */
-static bNodeSocketTemplate cmp_node_value_out[]= {
+static bNodeSocketTemplate cmp_node_value_out[] = {
/* XXX value nodes use the output sockets for buttons, so we need explicit limits here! */
{ SOCK_FLOAT, 0, N_("Value"), 0.0f, 0.0f, 0.0f, 0.0f, -FLT_MAX, FLT_MAX},
{ -1, 0, "" }
@@ -56,7 +56,7 @@ static void node_composit_exec_value(void *UNUSED(data), bNode *node, bNodeStack
bNodeSocket *sock= node->outputs.first;
float val= ((bNodeSocketValueFloat*)sock->default_value)->value;
- out[0]->vec[0]= val;
+ out[0]->vec[0] = val;
}
#endif /* WITH_COMPOSITOR_LEGACY */
diff --git a/source/blender/nodes/composite/nodes/node_composite_viewer.c b/source/blender/nodes/composite/nodes/node_composite_viewer.c
index 6321b1def4d..938f75cf3f5 100644
--- a/source/blender/nodes/composite/nodes/node_composite_viewer.c
+++ b/source/blender/nodes/composite/nodes/node_composite_viewer.c
@@ -149,7 +149,7 @@ void register_node_type_cmp_viewer(bNodeTreeType *ttype)
node_type_exec(&ntype, node_composit_exec_viewer);
#endif
- node_type_internal_connect(&ntype, NULL);
+ node_type_internal_links(&ntype, NULL);
nodeRegisterType(ttype, &ntype);
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_zcombine.c b/source/blender/nodes/composite/nodes/node_composite_zcombine.c
index 3decbe8d230..8e639aaa357 100644
--- a/source/blender/nodes/composite/nodes/node_composite_zcombine.c
+++ b/source/blender/nodes/composite/nodes/node_composite_zcombine.c
@@ -35,14 +35,14 @@
/* **************** Z COMBINE ******************** */
/* lazy coder note: node->custom2 is abused to send signal */
-static bNodeSocketTemplate cmp_node_zcombine_in[]= {
+static bNodeSocketTemplate cmp_node_zcombine_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Z"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 10000.0f, PROP_NONE},
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Z"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 10000.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate cmp_node_zcombine_out[]= {
+static bNodeSocketTemplate cmp_node_zcombine_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ SOCK_FLOAT, 0, N_("Z")},
{ -1, 0, "" }
@@ -60,10 +60,10 @@ static void do_zcombine(bNode *node, float *out, float *src1, float *z1, float *
// use alpha in combine operation
alpha= src1[3];
malpha= 1.0f - alpha;
- out[0]= malpha*src2[0] + alpha*src1[0];
- out[1]= malpha*src2[1] + alpha*src1[1];
- out[2]= malpha*src2[2] + alpha*src1[2];
- out[3]= malpha*src2[3] + alpha*src1[3];
+ out[0] = malpha*src2[0] + alpha*src1[0];
+ out[1] = malpha*src2[1] + alpha*src1[1];
+ out[2] = malpha*src2[2] + alpha*src1[2];
+ out[3] = malpha*src2[3] + alpha*src1[3];
}
else {
// do combination based solely on z value
@@ -75,10 +75,10 @@ static void do_zcombine(bNode *node, float *out, float *src1, float *z1, float *
// use alpha in combine operation
alpha= src2[3];
malpha= 1.0f - alpha;
- out[0]= malpha*src1[0] + alpha*src2[0];
- out[1]= malpha*src1[1] + alpha*src2[1];
- out[2]= malpha*src1[2] + alpha*src2[2];
- out[3]= malpha*src1[3] + alpha*src2[3];
+ out[0] = malpha*src1[0] + alpha*src2[0];
+ out[1] = malpha*src1[1] + alpha*src2[1];
+ out[2] = malpha*src1[2] + alpha*src2[2];
+ out[3] = malpha*src1[3] + alpha*src2[3];
}
else {
// do combination based solely on z value
@@ -111,20 +111,20 @@ static void do_zcombine_add(bNode *node, float *out, float *col1, float *col2, f
malpha= 1.0f - alpha;
- out[0]= malpha*col1[0] + alpha*col2[0];
- out[1]= malpha*col1[1] + alpha*col2[1];
- out[2]= malpha*col1[2] + alpha*col2[2];
- out[3]= malpha*col1[3] + alpha*col2[3];
+ out[0] = malpha*col1[0] + alpha*col2[0];
+ out[1] = malpha*col1[1] + alpha*col2[1];
+ out[2] = malpha*col1[2] + alpha*col2[2];
+ out[3] = malpha*col1[3] + alpha*col2[3];
}
else {
alpha= col1[3];
malpha= 1.0f - alpha;
- out[0]= malpha*col2[0] + alpha*col1[0];
- out[1]= malpha*col2[1] + alpha*col1[1];
- out[2]= malpha*col2[2] + alpha*col1[2];
- out[3]= malpha*col2[3] + alpha*col1[3];
+ out[0] = malpha*col2[0] + alpha*col1[0];
+ out[1] = malpha*col2[1] + alpha*col1[1];
+ out[2] = malpha*col2[2] + alpha*col1[2];
+ out[3] = malpha*col2[3] + alpha*col1[3];
}
}
else {
@@ -132,10 +132,10 @@ static void do_zcombine_add(bNode *node, float *out, float *col1, float *col2, f
alpha = *acol;
malpha= 1.0f - alpha;
- out[0]= malpha*col1[0] + alpha*col2[0];
- out[1]= malpha*col1[1] + alpha*col2[1];
- out[2]= malpha*col1[2] + alpha*col2[2];
- out[3]= malpha*col1[3] + alpha*col2[3];
+ out[0] = malpha*col1[0] + alpha*col2[0];
+ out[1] = malpha*col1[1] + alpha*col2[1];
+ out[2] = malpha*col1[2] + alpha*col2[2];
+ out[3] = malpha*col1[3] + alpha*col2[3];
}
}
@@ -202,8 +202,8 @@ static void node_composit_exec_zcombine(void *data, bNode *node, bNodeStack **in
aabuf= MEM_mallocN(cbuf->x*cbuf->y, "aa buf");
fp= mbuf->rect;
for (x= cbuf->x*cbuf->y-1; x>=0; x--)
- if (fp[x]==0.0f) aabuf[x]= 0;
- else aabuf[x]= 255;
+ if (fp[x]==0.0f) aabuf[x] = 0;
+ else aabuf[x] = 255;
antialias_tagbuf(cbuf->x, cbuf->y, aabuf);
@@ -211,7 +211,7 @@ static void node_composit_exec_zcombine(void *data, bNode *node, bNodeStack **in
fp= mbuf->rect;
for (x= cbuf->x*cbuf->y-1; x>=0; x--)
if (aabuf[x]>1)
- fp[x]= (1.0f/255.0f)*(float)aabuf[x];
+ fp[x] = (1.0f/255.0f)*(float)aabuf[x];
composit3_pixel_processor(node, stackbuf, in[0]->data, in[0]->vec, in[2]->data, in[2]->vec, mbuf, NULL,
do_zcombine_add, CB_RGBA, CB_RGBA, CB_VAL);
diff --git a/source/blender/nodes/intern/node_common.c b/source/blender/nodes/intern/node_common.c
index 59a4d6818c8..86ef8a14c12 100644
--- a/source/blender/nodes/intern/node_common.c
+++ b/source/blender/nodes/intern/node_common.c
@@ -92,7 +92,7 @@ bNodeSocket *node_group_add_extern_socket(bNodeTree *UNUSED(ntree), ListBase *lb
sock->new_sock = NULL;
/* group sockets are dynamically added */
- sock->flag |= SOCK_DYNAMIC;
+ sock->flag |= SOCK_DYNAMIC|SOCK_COLLAPSED;
sock->own_index = gsock->own_index;
sock->groupsock = gsock;
@@ -115,7 +115,7 @@ bNodeSocket *node_group_add_socket(bNodeTree *ngroup, const char *name, int type
BLI_strncpy(gsock->name, name, sizeof(gsock->name));
gsock->type = type;
/* group sockets are dynamically added */
- gsock->flag |= SOCK_DYNAMIC;
+ gsock->flag |= SOCK_DYNAMIC|SOCK_COLLAPSED;
gsock->next = gsock->prev = NULL;
gsock->new_sock = NULL;
@@ -223,13 +223,13 @@ bNodeTemplate node_group_template(bNode *node)
{
bNodeTemplate ntemp;
ntemp.type = NODE_GROUP;
- ntemp.ngroup = (bNodeTree*)node->id;
+ ntemp.ngroup = (bNodeTree *)node->id;
return ntemp;
}
void node_group_init(bNodeTree *ntree, bNode *node, bNodeTemplate *ntemp)
{
- node->id = (ID*)ntemp->ngroup;
+ node->id = (ID *)ntemp->ngroup;
/* NB: group socket input/output roles are inverted internally!
* Group "inputs" work as outputs in links and vice versa.
@@ -354,168 +354,6 @@ static void UNUSED_FUNCTION(node_group_link)(bNodeTree *ntree, bNodeSocket *sock
node_group_expose_socket(ntree, sock, in_out);
}
-/**** For Loop ****/
-
-/* Essentially a group node with slightly different behavior.
- * The internal tree is executed several times, with each output being re-used
- * as an input in the next iteration. For this purpose, input and output socket
- * lists are kept identical!
- */
-
-bNodeTemplate node_forloop_template(bNode *node)
-{
- bNodeTemplate ntemp;
- ntemp.type = NODE_FORLOOP;
- ntemp.ngroup = (bNodeTree*)node->id;
- return ntemp;
-}
-
-void node_forloop_init(bNodeTree *ntree, bNode *node, bNodeTemplate *ntemp)
-{
- bNodeSocket *sock;
-
- node->id = (ID*)ntemp->ngroup;
-
- sock = nodeAddSocket(ntree, node, SOCK_IN, "Iterations", SOCK_FLOAT);
- node_socket_set_default_value_float(sock->default_value, PROP_UNSIGNED, 1, 0, 10000);
-
- /* NB: group socket input/output roles are inverted internally!
- * Group "inputs" work as outputs in links and vice versa.
- */
- if (ntemp->ngroup) {
- bNodeSocket *gsock;
- for (gsock=ntemp->ngroup->inputs.first; gsock; gsock=gsock->next)
- node_group_add_extern_socket(ntree, &node->inputs, SOCK_IN, gsock);
- for (gsock=ntemp->ngroup->outputs.first; gsock; gsock=gsock->next)
- node_group_add_extern_socket(ntree, &node->outputs, SOCK_OUT, gsock);
- }
-}
-
-void node_forloop_init_tree(bNodeTree *ntree)
-{
- bNodeSocket *sock;
- sock = node_group_add_socket(ntree, "Iteration", SOCK_FLOAT, SOCK_IN);
- sock->flag |= SOCK_INTERNAL;
-}
-
-static void loop_sync(bNodeTree *ntree, int sync_in_out)
-{
- bNodeSocket *sock, *sync, *nsync, *mirror;
- ListBase *sync_lb;
-
- if (sync_in_out==SOCK_IN) {
- sock = ntree->outputs.first;
-
- sync = ntree->inputs.first;
- sync_lb = &ntree->inputs;
- }
- else {
- sock = ntree->inputs.first;
-
- sync = ntree->outputs.first;
- sync_lb = &ntree->outputs;
- }
-
- /* NB: the sock->storage pointer is used here directly to store the own_index int
- * out the mirrored socket counterpart!
- */
-
- while (sock) {
- /* skip static and internal sockets on the sync side (preserves socket order!) */
- while (sync && ((sync->flag & SOCK_INTERNAL) || !(sync->flag & SOCK_DYNAMIC)))
- sync = sync->next;
-
- if (sync && !(sync->flag & SOCK_INTERNAL) && (sync->flag & SOCK_DYNAMIC)) {
- if (sock->storage==NULL) {
- /* if mirror index is 0, the sockets is newly added and a new mirror must be created. */
- mirror = node_group_expose_socket(ntree, sock, sync_in_out);
- /* store the mirror index */
- sock->storage = SET_INT_IN_POINTER(mirror->own_index);
- mirror->storage = SET_INT_IN_POINTER(sock->own_index);
- /* move mirror to the right place */
- BLI_remlink(sync_lb, mirror);
- if (sync)
- BLI_insertlinkbefore(sync_lb, sync, mirror);
- else
- BLI_addtail(sync_lb, mirror);
- }
- else {
- /* look up the mirror socket */
- for (mirror=sync; mirror; mirror=mirror->next)
- if (mirror->own_index == GET_INT_FROM_POINTER(sock->storage))
- break;
- /* make sure the name is the same (only for identification by user, no deeper meaning) */
- BLI_strncpy(mirror->name, sock->name, sizeof(mirror->name));
- /* fix the socket order if necessary */
- if (mirror != sync) {
- BLI_remlink(sync_lb, mirror);
- BLI_insertlinkbefore(sync_lb, sync, mirror);
- }
- else
- sync = sync->next;
- }
- }
-
- sock = sock->next;
- }
-
- /* remaining sockets in sync_lb are leftovers from deleted sockets, remove them */
- while (sync) {
- nsync = sync->next;
- if (!(sync->flag & SOCK_INTERNAL) && (sync->flag & SOCK_DYNAMIC))
- node_group_remove_socket(ntree, sync, sync_in_out);
- sync = nsync;
- }
-}
-
-void node_loop_update_tree(bNodeTree *ngroup)
-{
- /* make sure inputs & outputs are identical */
- if (ngroup->update & NTREE_UPDATE_GROUP_IN)
- loop_sync(ngroup, SOCK_OUT);
- if (ngroup->update & NTREE_UPDATE_GROUP_OUT)
- loop_sync(ngroup, SOCK_IN);
-}
-
-void node_whileloop_init(bNodeTree *ntree, bNode *node, bNodeTemplate *ntemp)
-{
- bNodeSocket *sock;
-
- node->id = (ID*)ntemp->ngroup;
-
- sock = nodeAddSocket(ntree, node, SOCK_IN, "Condition", SOCK_FLOAT);
- node_socket_set_default_value_float(sock->default_value, PROP_NONE, 1, 0, 1);
-
- /* max iterations */
- node->custom1 = 10000;
-
- /* NB: group socket input/output roles are inverted internally!
- * Group "inputs" work as outputs in links and vice versa.
- */
- if (ntemp->ngroup) {
- bNodeSocket *gsock;
- for (gsock=ntemp->ngroup->inputs.first; gsock; gsock=gsock->next)
- node_group_add_extern_socket(ntree, &node->inputs, SOCK_IN, gsock);
- for (gsock=ntemp->ngroup->outputs.first; gsock; gsock=gsock->next)
- node_group_add_extern_socket(ntree, &node->outputs, SOCK_OUT, gsock);
- }
-}
-
-void node_whileloop_init_tree(bNodeTree *ntree)
-{
- bNodeSocket *sock;
- sock = node_group_add_socket(ntree, "Condition", SOCK_FLOAT, SOCK_OUT);
- sock->flag |= SOCK_INTERNAL;
-}
-
-bNodeTemplate node_whileloop_template(bNode *node)
-{
- bNodeTemplate ntemp;
- ntemp.type = NODE_WHILELOOP;
- ntemp.ngroup = (bNodeTree*)node->id;
- return ntemp;
-}
-
/**** FRAME ****/
static void node_frame_init(bNodeTree *UNUSED(ntree), bNode *node, bNodeTemplate *UNUSED(ntemp))
@@ -547,16 +385,13 @@ void register_node_type_frame(bNodeTreeType *ttype)
/* **************** REROUTE ******************** */
/* simple, only a single input and output here */
-static ListBase node_reroute_internal_connect(bNodeTree *ntree, bNode *node)
+static void node_reroute_update_internal_links(bNodeTree *ntree, bNode *node)
{
bNodeLink *link;
- ListBase ret;
-
- ret.first = ret.last = NULL;
/* Security check! */
if (!ntree)
- return ret;
+ return;
link = MEM_callocN(sizeof(bNodeLink), "internal node link");
link->fromnode = node;
@@ -565,9 +400,7 @@ static ListBase node_reroute_internal_connect(bNodeTree *ntree, bNode *node)
link->tosock = node->outputs.first;
/* internal link is always valid */
link->flag |= NODE_LINK_VALID;
- BLI_addtail(&ret, link);
-
- return ret;
+ BLI_addtail(&node->internal_links, link);
}
static void node_reroute_init(bNodeTree *ntree, bNode *node, bNodeTemplate *UNUSED(ntemp))
@@ -586,7 +419,7 @@ void register_node_type_reroute(bNodeTreeType *ttype)
node_type_base(ttype, ntype, NODE_REROUTE, "Reroute", NODE_CLASS_LAYOUT, 0);
node_type_init(ntype, node_reroute_init);
- node_type_internal_connect(ntype, node_reroute_internal_connect);
+ node_type_internal_links(ntype, node_reroute_update_internal_links);
ntype->needs_free = 1;
nodeRegisterType(ttype, ntype);
@@ -650,3 +483,15 @@ void ntree_update_reroute_nodes(bNodeTree *ntree)
if (node->type == NODE_REROUTE && !node->done)
node_reroute_inherit_type_recursive(ntree, node);
}
+
+void BKE_node_tree_unlink_id_cb(void *calldata, struct ID *UNUSED(owner_id), struct bNodeTree *ntree)
+{
+ ID *id = (ID *)calldata;
+ bNode *node;
+
+ for (node = ntree->nodes.first; node; node = node->next) {
+ if (node->id == id) {
+ node->id = NULL;
+ }
+ }
+}
diff --git a/source/blender/nodes/intern/node_common.h b/source/blender/nodes/intern/node_common.h
index 00f72469b0f..9e04a9e05f8 100644
--- a/source/blender/nodes/intern/node_common.h
+++ b/source/blender/nodes/intern/node_common.h
@@ -38,18 +38,8 @@
struct bNodeTree;
void node_group_init(struct bNodeTree *ntree, struct bNode *node, struct bNodeTemplate *ntemp);
-void node_forloop_init(struct bNodeTree *ntree, struct bNode *node, struct bNodeTemplate *ntemp);
-void node_whileloop_init(struct bNodeTree *ntree, struct bNode *node, struct bNodeTemplate *ntemp);
-
-void node_forloop_init_tree(struct bNodeTree *ntree);
-void node_whileloop_init_tree(struct bNodeTree *ntree);
-
const char *node_group_label(struct bNode *node);
-
struct bNodeTemplate node_group_template(struct bNode *node);
-struct bNodeTemplate node_forloop_template(struct bNode *node);
-struct bNodeTemplate node_whileloop_template(struct bNode *node);
-
int node_group_valid(struct bNodeTree *ntree, struct bNodeTemplate *ntemp);
void node_group_verify(struct bNodeTree *ntree, struct bNode *node, struct ID *id);
@@ -57,8 +47,6 @@ struct bNodeTree *node_group_edit_get(struct bNode *node);
struct bNodeTree *node_group_edit_set(struct bNode *node, int edit);
void node_group_edit_clear(bNode *node);
-void node_loop_update_tree(struct bNodeTree *ngroup);
-
void ntree_update_reroute_nodes(struct bNodeTree *ntree);
#endif
diff --git a/source/blender/nodes/intern/node_exec.c b/source/blender/nodes/intern/node_exec.c
index d01ef2e2d52..3cc7ebf9337 100644
--- a/source/blender/nodes/intern/node_exec.c
+++ b/source/blender/nodes/intern/node_exec.c
@@ -69,7 +69,7 @@ void node_get_stack(bNode *node, bNodeStack *stack, bNodeStack **in, bNodeStack
}
}
-void node_init_input_index(bNodeSocket *sock, int *index)
+static void node_init_input_index(bNodeSocket *sock, int *index)
{
if (sock->link && sock->link->fromsock) {
sock->stack_index = sock->link->fromsock->stack_index;
@@ -79,16 +79,31 @@ void node_init_input_index(bNodeSocket *sock, int *index)
}
}
-void node_init_output_index(bNodeSocket *sock, int *index)
+static void node_init_output_index(bNodeSocket *sock, int *index, ListBase *internal_links)
{
- sock->stack_index = (*index)++;
+ if (internal_links) {
+ bNodeLink *link;
+ /* copy the stack index from internally connected input to skip the node */
+ for (link = internal_links->first; link; link = link->next) {
+ if (link->tosock == sock) {
+ sock->stack_index = link->fromsock->stack_index;
+ break;
+ }
+ }
+ /* if not internally connected, assign a new stack index anyway to avoid bad stack access */
+ if (!link)
+ sock->stack_index = (*index)++;
+ }
+ else {
+ sock->stack_index = (*index)++;
+ }
}
/* basic preparation of socket stacks */
static struct bNodeStack *setup_stack(bNodeStack *stack, bNodeSocket *sock)
{
bNodeStack *ns = node_get_socket_stack(stack, sock);
- float null_value[4]= {0.0f, 0.0f, 0.0f, 0.0f};
+ float null_value[4] = {0.0f, 0.0f, 0.0f, 0.0f};
/* don't mess with remote socket stacks, these are initialized by other nodes! */
if (sock->link)
@@ -133,7 +148,7 @@ bNodeTreeExec *ntree_exec_begin(bNodeTree *ntree)
bNodeExec *nodeexec;
bNodeSocket *sock, *gsock;
bNodeStack *ns;
- int index= 0;
+ int index;
bNode **nodelist;
int totnodes, n;
@@ -148,10 +163,11 @@ bNodeTreeExec *ntree_exec_begin(bNodeTree *ntree)
/* backpointer to node tree */
exec->nodetree = ntree;
+ /* set stack indices */
+ index = 0;
/* group inputs essentially work as outputs */
for (gsock=ntree->inputs.first; gsock; gsock = gsock->next)
- node_init_output_index(gsock, &index);
- /* set stack indexes */
+ node_init_output_index(gsock, &index, NULL);
for (n=0; n < totnodes; ++n) {
node = nodelist[n];
@@ -160,8 +176,15 @@ bNodeTreeExec *ntree_exec_begin(bNodeTree *ntree)
/* init node socket stack indexes */
for (sock=node->inputs.first; sock; sock=sock->next)
node_init_input_index(sock, &index);
- for (sock=node->outputs.first; sock; sock=sock->next)
- node_init_output_index(sock, &index);
+
+ if (node->flag & NODE_MUTED || node->type == NODE_REROUTE) {
+ for (sock=node->outputs.first; sock; sock=sock->next)
+ node_init_output_index(sock, &index, &node->internal_links);
+ }
+ else {
+ for (sock=node->outputs.first; sock; sock=sock->next)
+ node_init_output_index(sock, &index, NULL);
+ }
}
/* group outputs essentially work as inputs */
for (gsock=ntree->outputs.first; gsock; gsock = gsock->next)
diff --git a/source/blender/nodes/intern/node_exec.h b/source/blender/nodes/intern/node_exec.h
index 1003206e96a..e985795de71 100644
--- a/source/blender/nodes/intern/node_exec.h
+++ b/source/blender/nodes/intern/node_exec.h
@@ -73,8 +73,6 @@ typedef struct bNodeThreadStack {
struct bNodeStack *node_get_socket_stack(struct bNodeStack *stack, struct bNodeSocket *sock);
void node_get_stack(struct bNode *node, struct bNodeStack *stack, struct bNodeStack **in, struct bNodeStack **out);
-void node_init_input_index(struct bNodeSocket *sock, int *index);
-void node_init_output_index(struct bNodeSocket *sock, int *index);
struct bNodeTreeExec *ntree_exec_begin(struct bNodeTree *ntree);
void ntree_exec_end(struct bNodeTreeExec *exec);
diff --git a/source/blender/nodes/intern/node_socket.c b/source/blender/nodes/intern/node_socket.c
index 8b393dd740a..8e49484d1eb 100644
--- a/source/blender/nodes/intern/node_socket.c
+++ b/source/blender/nodes/intern/node_socket.c
@@ -490,39 +490,39 @@ static bNodeSocket *verify_socket_template(bNodeTree *ntree, bNode *node, int in
break;
}
if (sock) {
- sock->type= stemp->type; /* in future, read this from tydefs! */
- if (stemp->limit==0) sock->limit= 0xFFF;
- else sock->limit= stemp->limit;
+ sock->type = stemp->type; /* in future, read this from tydefs! */
+ if (stemp->limit == 0) sock->limit= 0xFFF;
+ else sock->limit = stemp->limit;
sock->flag |= stemp->flag;
/* Copy the property range and subtype parameters in case the template changed.
* NOT copying the actual value here, only button behavior changes!
*/
switch (sock->type) {
- case SOCK_FLOAT:
+ case SOCK_FLOAT:
{
bNodeSocketValueFloat *dval= sock->default_value;
dval->min = stemp->min;
dval->max = stemp->max;
dval->subtype = stemp->subtype;
+ break;
}
- break;
- case SOCK_INT:
+ case SOCK_INT:
{
bNodeSocketValueInt *dval= sock->default_value;
dval->min = stemp->min;
dval->max = stemp->max;
dval->subtype = stemp->subtype;
+ break;
}
- break;
- case SOCK_VECTOR:
+ case SOCK_VECTOR:
{
bNodeSocketValueVector *dval= sock->default_value;
dval->min = stemp->min;
dval->max = stemp->max;
dval->subtype = stemp->subtype;
+ break;
}
- break;
}
BLI_remlink(socklist, sock);
@@ -600,7 +600,9 @@ void node_verify_socket_templates(bNodeTree *ntree, bNode *node)
* This also prevents group node sockets from being removed, without the need to explicitly
* check the node type here.
*/
- if (ntype && ((ntype->inputs && ntype->inputs[0].type>=0) || (ntype->outputs && ntype->outputs[0].type>=0))) {
+ if (ntype && ((ntype->inputs && ntype->inputs[0].type >= 0) ||
+ (ntype->outputs && ntype->outputs[0].type >= 0)))
+ {
verify_socket_template_list(ntree, node, SOCK_IN, &node->inputs, ntype->inputs);
verify_socket_template_list(ntree, node, SOCK_OUT, &node->outputs, ntype->outputs);
}
diff --git a/source/blender/nodes/intern/node_util.c b/source/blender/nodes/intern/node_util.c
index 27258c45fe5..09e6ddd18a5 100644
--- a/source/blender/nodes/intern/node_util.c
+++ b/source/blender/nodes/intern/node_util.c
@@ -65,12 +65,12 @@ void node_free_standard_storage(bNode *node)
void node_copy_curves(bNode *orig_node, bNode *new_node)
{
- new_node->storage= curvemapping_copy(orig_node->storage);
+ new_node->storage = curvemapping_copy(orig_node->storage);
}
void node_copy_standard_storage(bNode *orig_node, bNode *new_node)
{
- new_node->storage= MEM_dupallocN(orig_node->storage);
+ new_node->storage = MEM_dupallocN(orig_node->storage);
}
void *node_initexec_curves(bNode *node)
@@ -109,18 +109,15 @@ const char *node_filter_label(bNode *node)
return IFACE_(name);
}
-ListBase node_internal_connect_default(bNodeTree *ntree, bNode *node)
+void node_update_internal_links_default(bNodeTree *ntree, bNode *node)
{
- ListBase ret;
bNodeSocket *fromsock_first=NULL, *tosock_first=NULL; /* used for fallback link if no other reconnections are found */
int datatype;
int num_links_in = 0, num_links_out = 0, num_reconnect = 0;
- ret.first = ret.last = NULL;
-
/* Security check! */
if (!ntree)
- return ret;
+ return;
for (datatype=0; datatype < NUM_SOCKET_TYPES; ++datatype) {
bNodeSocket *fromsock, *tosock;
@@ -170,7 +167,7 @@ ListBase node_internal_connect_default(bNodeTree *ntree, bNode *node)
ilink->tosock = tosock;
/* internal link is always valid */
ilink->flag |= NODE_LINK_VALID;
- BLI_addtail(&ret, ilink);
+ BLI_addtail(&node->internal_links, ilink);
++num_reconnect;
}
@@ -188,8 +185,6 @@ ListBase node_internal_connect_default(bNodeTree *ntree, bNode *node)
ilink->tosock = tosock_first;
/* internal link is always valid */
ilink->flag |= NODE_LINK_VALID;
- BLI_addtail(&ret, ilink);
+ BLI_addtail(&node->internal_links, ilink);
}
-
- return ret;
}
diff --git a/source/blender/nodes/intern/node_util.h b/source/blender/nodes/intern/node_util.h
index 95104df5fed..3134baa283c 100644
--- a/source/blender/nodes/intern/node_util.h
+++ b/source/blender/nodes/intern/node_util.h
@@ -62,7 +62,7 @@ const char *node_math_label(struct bNode *node);
const char *node_vect_math_label(struct bNode *node);
const char *node_filter_label(struct bNode *node);
-ListBase node_internal_connect_default(struct bNodeTree *ntree, struct bNode *node);
+void node_update_internal_links_default(struct bNodeTree *ntree, struct bNode *node);
#endif
diff --git a/source/blender/nodes/shader/node_shader_tree.c b/source/blender/nodes/shader/node_shader_tree.c
index ad907c317f8..b7dc83d7d79 100644
--- a/source/blender/nodes/shader/node_shader_tree.c
+++ b/source/blender/nodes/shader/node_shader_tree.c
@@ -87,10 +87,11 @@ static void foreach_nodeclass(Scene *scene, void *calldata, bNodeClassCallback f
func(calldata, NODE_CLASS_SHADER, N_("Shader"));
func(calldata, NODE_CLASS_TEXTURE, N_("Texture"));
}
-
+
func(calldata, NODE_CLASS_OP_COLOR, N_("Color"));
func(calldata, NODE_CLASS_OP_VECTOR, N_("Vector"));
func(calldata, NODE_CLASS_CONVERTOR, N_("Convertor"));
+ func(calldata, NODE_CLASS_SCRIPT, N_("Script"));
func(calldata, NODE_CLASS_GROUP, N_("Group"));
func(calldata, NODE_CLASS_LAYOUT, N_("Layout"));
}
@@ -153,7 +154,7 @@ bNodeTreeType ntreeType_Shader = {
/* update */ update,
/* update_node */ NULL,
/* validate_link */ NULL,
- /* internal_connect */ node_internal_connect_default
+ /* update_internal_links */ node_update_internal_links_default
};
/* GPU material from shader nodes */
diff --git a/source/blender/nodes/shader/node_shader_util.c b/source/blender/nodes/shader/node_shader_util.c
index 56704b981be..6130fe72af3 100644
--- a/source/blender/nodes/shader/node_shader_util.c
+++ b/source/blender/nodes/shader/node_shader_util.c
@@ -50,9 +50,9 @@ void nodestack_get_vec(float *in, short type_in, bNodeStack *ns)
}
else if (type_in==SOCK_VECTOR) {
if (ns->sockettype==SOCK_FLOAT) {
- in[0]= from[0];
- in[1]= from[0];
- in[2]= from[0];
+ in[0] = from[0];
+ in[1] = from[0];
+ in[2] = from[0];
}
else {
copy_v3_v3(in, from);
@@ -63,14 +63,14 @@ void nodestack_get_vec(float *in, short type_in, bNodeStack *ns)
copy_v4_v4(in, from);
}
else if (ns->sockettype==SOCK_FLOAT) {
- in[0]= from[0];
- in[1]= from[0];
- in[2]= from[0];
- in[3]= 1.0f;
+ in[0] = from[0];
+ in[1] = from[0];
+ in[2] = from[0];
+ in[3] = 1.0f;
}
else {
copy_v3_v3(in, from);
- in[3]= 1.0f;
+ in[3] = 1.0f;
}
}
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_add_shader.c b/source/blender/nodes/shader/nodes/node_shader_add_shader.c
index ee8513a4119..ec868b2cc38 100644
--- a/source/blender/nodes/shader/nodes/node_shader_add_shader.c
+++ b/source/blender/nodes/shader/nodes/node_shader_add_shader.c
@@ -29,13 +29,13 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_add_shader_in[]= {
+static bNodeSocketTemplate sh_node_add_shader_in[] = {
{ SOCK_SHADER, 1, N_("Shader")},
{ SOCK_SHADER, 1, N_("Shader")},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_add_shader_out[]= {
+static bNodeSocketTemplate sh_node_add_shader_out[] = {
{ SOCK_SHADER, 0, N_("Shader")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_attribute.c b/source/blender/nodes/shader/nodes/node_shader_attribute.c
index 9c65323337e..9b2ed2f14f0 100644
--- a/source/blender/nodes/shader/nodes/node_shader_attribute.c
+++ b/source/blender/nodes/shader/nodes/node_shader_attribute.c
@@ -29,7 +29,7 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_attribute_out[]= {
+static bNodeSocketTemplate sh_node_attribute_out[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ SOCK_VECTOR, 0, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Fac"), 0.0f, 0.0f, 0.0f, 0.0f, -FLT_MAX, FLT_MAX},
diff --git a/source/blender/nodes/shader/nodes/node_shader_background.c b/source/blender/nodes/shader/nodes/node_shader_background.c
index 7d13c359a2b..d82c513540c 100644
--- a/source/blender/nodes/shader/nodes/node_shader_background.c
+++ b/source/blender/nodes/shader/nodes/node_shader_background.c
@@ -29,13 +29,13 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_background_in[]= {
+static bNodeSocketTemplate sh_node_background_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Strength"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000000.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_background_out[]= {
+static bNodeSocketTemplate sh_node_background_out[] = {
{ SOCK_SHADER, 0, N_("Background")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_brightness.c b/source/blender/nodes/shader/nodes/node_shader_brightness.c
index 2735553cdad..9c23a29cae9 100644
--- a/source/blender/nodes/shader/nodes/node_shader_brightness.c
+++ b/source/blender/nodes/shader/nodes/node_shader_brightness.c
@@ -31,14 +31,14 @@
/* **************** Brigh and contrsast ******************** */
-static bNodeSocketTemplate sh_node_brightcontrast_in[]= {
+static bNodeSocketTemplate sh_node_brightcontrast_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Bright"), 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("Contrast"), 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_brightcontrast_out[]= {
+static bNodeSocketTemplate sh_node_brightcontrast_out[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_bsdf_anisotropic.c b/source/blender/nodes/shader/nodes/node_shader_bsdf_anisotropic.c
index 9157728b546..71780e9316e 100644
--- a/source/blender/nodes/shader/nodes/node_shader_bsdf_anisotropic.c
+++ b/source/blender/nodes/shader/nodes/node_shader_bsdf_anisotropic.c
@@ -29,21 +29,27 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_bsdf_anisotropic_in[]= {
+static bNodeSocketTemplate sh_node_bsdf_anisotropic_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
- { SOCK_FLOAT, 1, N_("Roughness U"), 0.2f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_FLOAT, 1, N_("Roughness V"), 0.2f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 1, N_("Roughness"), 0.2f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 1, N_("Anisotropy"), 0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f},
+ { SOCK_FLOAT, 1, N_("Rotation"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
+ { SOCK_VECTOR, 1, N_("Tangent"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_bsdf_anisotropic_out[]= {
+static bNodeSocketTemplate sh_node_bsdf_anisotropic_out[] = {
{ SOCK_SHADER, 0, N_("BSDF")},
{ -1, 0, "" }
};
static int node_shader_gpu_bsdf_anisotropic(GPUMaterial *mat, bNode *UNUSED(node), GPUNodeStack *in, GPUNodeStack *out)
{
- return GPU_stack_link(mat, "node_bsdf_anisotropic", in, out, GPU_builtin(GPU_VIEW_NORMAL), GPU_builtin(GPU_VIEW_POSITION));
+ if (!in[3].link)
+ in[3].link = GPU_builtin(GPU_VIEW_NORMAL);
+
+ return GPU_stack_link(mat, "node_bsdf_anisotropic", in, out);
}
/* node type definition */
@@ -51,7 +57,7 @@ void register_node_type_sh_bsdf_anisotropic(bNodeTreeType *ttype)
{
static bNodeType ntype;
- node_type_base(ttype, &ntype, SH_NODE_BSDF_ANISOTROPIC, "Glossy Anisotropic BSDF", NODE_CLASS_SHADER, 0);
+ node_type_base(ttype, &ntype, SH_NODE_BSDF_ANISOTROPIC, "Anisotropic BSDF", NODE_CLASS_SHADER, 0);
node_type_compatibility(&ntype, NODE_NEW_SHADING);
node_type_socket_templates(&ntype, sh_node_bsdf_anisotropic_in, sh_node_bsdf_anisotropic_out);
node_type_size(&ntype, 150, 60, 200);
diff --git a/source/blender/nodes/shader/nodes/node_shader_bsdf_diffuse.c b/source/blender/nodes/shader/nodes/node_shader_bsdf_diffuse.c
index d2e2db3e78a..ad9f197afb8 100644
--- a/source/blender/nodes/shader/nodes/node_shader_bsdf_diffuse.c
+++ b/source/blender/nodes/shader/nodes/node_shader_bsdf_diffuse.c
@@ -29,20 +29,24 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_bsdf_diffuse_in[]= {
+static bNodeSocketTemplate sh_node_bsdf_diffuse_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Roughness"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_bsdf_diffuse_out[]= {
+static bNodeSocketTemplate sh_node_bsdf_diffuse_out[] = {
{ SOCK_SHADER, 0, N_("BSDF")},
{ -1, 0, "" }
};
static int node_shader_gpu_bsdf_diffuse(GPUMaterial *mat, bNode *UNUSED(node), GPUNodeStack *in, GPUNodeStack *out)
{
- return GPU_stack_link(mat, "node_bsdf_diffuse", in, out, GPU_builtin(GPU_VIEW_NORMAL));
+ if (!in[2].link)
+ in[2].link = GPU_builtin(GPU_VIEW_NORMAL);
+
+ return GPU_stack_link(mat, "node_bsdf_diffuse", in, out);
}
/* node type definition */
diff --git a/source/blender/nodes/shader/nodes/node_shader_bsdf_glass.c b/source/blender/nodes/shader/nodes/node_shader_bsdf_glass.c
index 8ff0ad57742..9e188092570 100644
--- a/source/blender/nodes/shader/nodes/node_shader_bsdf_glass.c
+++ b/source/blender/nodes/shader/nodes/node_shader_bsdf_glass.c
@@ -29,21 +29,25 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_bsdf_glass_in[]= {
+static bNodeSocketTemplate sh_node_bsdf_glass_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Roughness"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("IOR"), 1.45f, 0.0f, 0.0f, 0.0f, 1.0f, 1000.0f},
+ { SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_bsdf_glass_out[]= {
+static bNodeSocketTemplate sh_node_bsdf_glass_out[] = {
{ SOCK_SHADER, 0, N_("BSDF")},
{ -1, 0, "" }
};
static int node_shader_gpu_bsdf_glass(GPUMaterial *mat, bNode *UNUSED(node), GPUNodeStack *in, GPUNodeStack *out)
{
- return GPU_stack_link(mat, "node_bsdf_glass", in, out, GPU_builtin(GPU_VIEW_NORMAL), GPU_builtin(GPU_VIEW_POSITION));
+ if (!in[3].link)
+ in[3].link = GPU_builtin(GPU_VIEW_NORMAL);
+
+ return GPU_stack_link(mat, "node_bsdf_glass", in, out);
}
/* node type definition */
diff --git a/source/blender/nodes/shader/nodes/node_shader_bsdf_glossy.c b/source/blender/nodes/shader/nodes/node_shader_bsdf_glossy.c
index d28b3454f02..5e32930b707 100644
--- a/source/blender/nodes/shader/nodes/node_shader_bsdf_glossy.c
+++ b/source/blender/nodes/shader/nodes/node_shader_bsdf_glossy.c
@@ -29,21 +29,24 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_bsdf_glossy_in[]= {
+static bNodeSocketTemplate sh_node_bsdf_glossy_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Roughness"), 0.2f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_bsdf_glossy_out[]= {
+static bNodeSocketTemplate sh_node_bsdf_glossy_out[] = {
{ SOCK_SHADER, 0, N_("BSDF")},
{ -1, 0, "" }
};
static int node_shader_gpu_bsdf_glossy(GPUMaterial *mat, bNode *UNUSED(node), GPUNodeStack *in, GPUNodeStack *out)
{
- /* todo: is incoming vector normalized? */
- return GPU_stack_link(mat, "node_bsdf_glossy", in, out, GPU_builtin(GPU_VIEW_NORMAL), GPU_builtin(GPU_VIEW_POSITION));
+ if (!in[2].link)
+ in[2].link = GPU_builtin(GPU_VIEW_NORMAL);
+
+ return GPU_stack_link(mat, "node_bsdf_glossy", in, out);
}
/* node type definition */
diff --git a/source/blender/nodes/shader/nodes/node_shader_bsdf_translucent.c b/source/blender/nodes/shader/nodes/node_shader_bsdf_translucent.c
index a3ba3ac7ff3..3c7084886b7 100644
--- a/source/blender/nodes/shader/nodes/node_shader_bsdf_translucent.c
+++ b/source/blender/nodes/shader/nodes/node_shader_bsdf_translucent.c
@@ -29,19 +29,23 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_bsdf_translucent_in[]= {
+static bNodeSocketTemplate sh_node_bsdf_translucent_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
+ { SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_bsdf_translucent_out[]= {
+static bNodeSocketTemplate sh_node_bsdf_translucent_out[] = {
{ SOCK_SHADER, 0, N_("BSDF")},
{ -1, 0, "" }
};
static int node_shader_gpu_bsdf_translucent(GPUMaterial *mat, bNode *UNUSED(node), GPUNodeStack *in, GPUNodeStack *out)
{
- return GPU_stack_link(mat, "node_bsdf_translucent", in, out, GPU_builtin(GPU_VIEW_NORMAL));
+ if (!in[1].link)
+ in[1].link = GPU_builtin(GPU_VIEW_NORMAL);
+
+ return GPU_stack_link(mat, "node_bsdf_translucent", in, out);
}
/* node type definition */
diff --git a/source/blender/nodes/shader/nodes/node_shader_bsdf_transparent.c b/source/blender/nodes/shader/nodes/node_shader_bsdf_transparent.c
index 8c945abdd0d..7fb452ad78d 100644
--- a/source/blender/nodes/shader/nodes/node_shader_bsdf_transparent.c
+++ b/source/blender/nodes/shader/nodes/node_shader_bsdf_transparent.c
@@ -29,12 +29,12 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_bsdf_transparent_in[]= {
+static bNodeSocketTemplate sh_node_bsdf_transparent_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_bsdf_transparent_out[]= {
+static bNodeSocketTemplate sh_node_bsdf_transparent_out[] = {
{ SOCK_SHADER, 0, N_("BSDF")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_bsdf_velvet.c b/source/blender/nodes/shader/nodes/node_shader_bsdf_velvet.c
index 04a1c1b32df..a4d25d42d4e 100644
--- a/source/blender/nodes/shader/nodes/node_shader_bsdf_velvet.c
+++ b/source/blender/nodes/shader/nodes/node_shader_bsdf_velvet.c
@@ -29,20 +29,24 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_bsdf_velvet_in[]= {
+static bNodeSocketTemplate sh_node_bsdf_velvet_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Sigma"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_bsdf_velvet_out[]= {
+static bNodeSocketTemplate sh_node_bsdf_velvet_out[] = {
{ SOCK_SHADER, 0, N_("BSDF")},
{ -1, 0, "" }
};
static int node_shader_gpu_bsdf_velvet(GPUMaterial *mat, bNode *UNUSED(node), GPUNodeStack *in, GPUNodeStack *out)
{
- return GPU_stack_link(mat, "node_bsdf_velvet", in, out, GPU_builtin(GPU_VIEW_NORMAL));
+ if (!in[2].link)
+ in[2].link = GPU_builtin(GPU_VIEW_NORMAL);
+
+ return GPU_stack_link(mat, "node_bsdf_velvet", in, out);
}
/* node type definition */
diff --git a/source/blender/nodes/shader/nodes/node_shader_bump.c b/source/blender/nodes/shader/nodes/node_shader_bump.c
new file mode 100644
index 00000000000..24ed825c36e
--- /dev/null
+++ b/source/blender/nodes/shader/nodes/node_shader_bump.c
@@ -0,0 +1,68 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/nodes/shader/nodes/node_shader_bump.c
+ * \ingroup shdnodes
+ */
+
+
+
+#include "node_shader_util.h"
+
+
+/* **************** BUMP ******************** */
+static bNodeSocketTemplate sh_node_bump_in[] = {
+ { SOCK_FLOAT, 1, "Strength", 0.1f, 0.0f, 0.0f, 0.0f, -1000.0f, 1000.0f},
+ { SOCK_FLOAT, 1, "Height", 1.0f, 1.0f, 1.0f, 1.0f, -1000.0f, 1000.0f, PROP_NONE, SOCK_HIDE_VALUE},
+ { -1, 0, "" }
+};
+
+static bNodeSocketTemplate sh_node_bump_out[] = {
+ { SOCK_VECTOR, 0, "Normal"},
+ { -1, 0, "" }
+};
+
+static int gpu_shader_bump(GPUMaterial *mat, bNode *UNUSED(node), GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "node_bump", in, out, GPU_builtin(GPU_VIEW_NORMAL));
+}
+
+/* node type definition */
+void register_node_type_sh_bump(bNodeTreeType *ttype)
+{
+ static bNodeType ntype;
+
+ node_type_base(ttype, &ntype, SH_NODE_BUMP, "Bump", NODE_CLASS_OP_VECTOR, NODE_OPTIONS);
+ node_type_compatibility(&ntype, NODE_NEW_SHADING);
+ node_type_socket_templates(&ntype, sh_node_bump_in, sh_node_bump_out);
+ node_type_size(&ntype, 150, 60, 200);
+ node_type_storage(&ntype, "BumpNode", node_free_standard_storage, node_copy_standard_storage);
+ node_type_exec(&ntype, NULL);
+ node_type_gpu(&ntype, gpu_shader_bump);
+
+ nodeRegisterType(ttype, &ntype);
+}
diff --git a/source/blender/nodes/shader/nodes/node_shader_camera.c b/source/blender/nodes/shader/nodes/node_shader_camera.c
index 17cec8196e8..fd36a94516e 100644
--- a/source/blender/nodes/shader/nodes/node_shader_camera.c
+++ b/source/blender/nodes/shader/nodes/node_shader_camera.c
@@ -33,7 +33,7 @@
#include "node_shader_util.h"
/* **************** CAMERA INFO ******************** */
-static bNodeSocketTemplate sh_node_camera_out[]= {
+static bNodeSocketTemplate sh_node_camera_out[] = {
{ SOCK_VECTOR, 0, N_("View Vector")},
{ SOCK_FLOAT, 0, N_("View Z Depth")},
{ SOCK_FLOAT, 0, N_("View Distance")},
@@ -47,8 +47,8 @@ static void node_shader_exec_camera(void *data, bNode *UNUSED(node), bNodeStack
ShadeInput *shi= ((ShaderCallData *)data)->shi; /* Data we need for shading. */
copy_v3_v3(out[0]->vec, shi->co); /* get view vector */
- out[1]->vec[0]= fabs(shi->co[2]); /* get view z-depth */
- out[2]->vec[0]= normalize_v3(out[0]->vec); /* get view distance */
+ out[1]->vec[0] = fabs(shi->co[2]); /* get view z-depth */
+ out[2]->vec[0] = normalize_v3(out[0]->vec); /* get view distance */
}
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_common.c b/source/blender/nodes/shader/nodes/node_shader_common.c
index df369482a2e..688d77d8350 100644
--- a/source/blender/nodes/shader/nodes/node_shader_common.c
+++ b/source/blender/nodes/shader/nodes/node_shader_common.c
@@ -204,128 +204,3 @@ void register_node_type_sh_group(bNodeTreeType *ttype)
nodeRegisterType(ttype, &ntype);
}
-
-
-/**** FOR LOOP ****/
-
-#if 0 /* XXX loop nodes don't work nicely with current trees */
-static void forloop_execute(void *data, int thread, struct bNode *node, void *nodedata, struct bNodeStack **in, struct bNodeStack **out)
-{
- bNodeTreeExec *exec= (bNodeTreeExec*)nodedata;
- bNodeThreadStack *nts;
- int iterations= (int)in[0]->vec[0];
- bNodeSocket *sock;
- bNodeStack *ns;
- int iteration;
-
- /* XXX same behavior as trunk: all nodes inside group are executed.
- * it's stupid, but just makes it work. compo redesign will do this better.
- */
- {
- bNode *inode;
- for (inode=exec->nodetree->nodes.first; inode; inode=inode->next)
- inode->need_exec = 1;
- }
-
- nts = ntreeGetThreadStack(exec, thread);
-
- /* "Iteration" socket */
- sock = exec->nodetree->inputs.first;
- ns = node_get_socket_stack(nts->stack, sock);
-
-// group_copy_inputs(node, in, nts->stack);
- for (iteration=0; iteration < iterations; ++iteration) {
- /* first input contains current iteration counter */
- ns->vec[0] = (float)iteration;
- ns->vec[1]=ns->vec[2]=ns->vec[3] = 0.0f;
-
-// if (iteration > 0)
-// loop_init_iteration(exec->nodetree, nts->stack);
-// ntreeExecThreadNodes(exec, nts, data, thread);
- }
-// loop_copy_outputs(node, in, out, exec->stack);
-
- ntreeReleaseThreadStack(nts);
-}
-
-void register_node_type_sh_forloop(bNodeTreeType *ttype)
-{
- static bNodeType ntype;
-
- node_type_base(ttype, &ntype, NODE_FORLOOP, "For", NODE_CLASS_GROUP, NODE_OPTIONS);
- node_type_socket_templates(&ntype, NULL, NULL);
- node_type_size(&ntype, 120, 60, 200);
- node_type_label(&ntype, node_group_label);
- node_type_init(&ntype, node_forloop_init);
- node_type_valid(&ntype, node_group_valid);
- node_type_template(&ntype, node_forloop_template);
- node_type_update(&ntype, NULL, node_group_verify);
- node_type_tree(&ntype, node_forloop_init_tree, node_loop_update_tree);
- node_type_group_edit(&ntype, node_group_edit_get, node_group_edit_set, node_group_edit_clear);
- node_type_exec_new(&ntype, group_initexec, group_freeexec, forloop_execute);
-
- nodeRegisterType(ttype, &ntype);
-}
-#endif
-
-/**** WHILE LOOP ****/
-
-#if 0 /* XXX loop nodes don't work nicely with current trees */
-static void whileloop_execute(void *data, int thread, struct bNode *node, void *nodedata, struct bNodeStack **in, struct bNodeStack **out)
-{
- bNodeTreeExec *exec= (bNodeTreeExec*)nodedata;
- bNodeThreadStack *nts;
- int condition= (in[0]->vec[0] > 0.0f);
- bNodeSocket *sock;
- bNodeStack *ns;
- int iteration;
-
- /* XXX same behavior as trunk: all nodes inside group are executed.
- * it's stupid, but just makes it work. compo redesign will do this better.
- */
- {
- bNode *inode;
- for (inode=exec->nodetree->nodes.first; inode; inode=inode->next)
- inode->need_exec = 1;
- }
-
- nts = ntreeGetThreadStack(exec, thread);
-
- /* "Condition" socket */
- sock = exec->nodetree->outputs.first;
- ns = node_get_socket_stack(nts->stack, sock);
-
- iteration = 0;
-// group_copy_inputs(node, in, nts->stack);
- while (condition && iteration < node->custom1) {
-// if (iteration > 0)
-// loop_init_iteration(exec->nodetree, nts->stack);
-// ntreeExecThreadNodes(exec, nts, data, thread);
-
- condition = (ns->vec[0] > 0.0f);
- ++iteration;
- }
-// loop_copy_outputs(node, in, out, exec->stack);
-
- ntreeReleaseThreadStack(nts);
-}
-
-void register_node_type_sh_whileloop(bNodeTreeType *ttype)
-{
- static bNodeType ntype;
-
- node_type_base(ttype, &ntype, NODE_WHILELOOP, "While", NODE_CLASS_GROUP, NODE_OPTIONS);
- node_type_socket_templates(&ntype, NULL, NULL);
- node_type_size(&ntype, 120, 60, 200);
- node_type_label(&ntype, node_group_label);
- node_type_init(&ntype, node_whileloop_init);
- node_type_valid(&ntype, node_group_valid);
- node_type_template(&ntype, node_whileloop_template);
- node_type_update(&ntype, NULL, node_group_verify);
- node_type_tree(&ntype, node_whileloop_init_tree, node_loop_update_tree);
- node_type_group_edit(&ntype, node_group_edit_get, node_group_edit_set, node_group_edit_clear);
- node_type_exec_new(&ntype, group_initexec, group_freeexec, whileloop_execute);
-
- nodeRegisterType(ttype, &ntype);
-}
-#endif
diff --git a/source/blender/nodes/shader/nodes/node_shader_curves.c b/source/blender/nodes/shader/nodes/node_shader_curves.c
index 83cb1d33628..9fa654c9740 100644
--- a/source/blender/nodes/shader/nodes/node_shader_curves.c
+++ b/source/blender/nodes/shader/nodes/node_shader_curves.c
@@ -34,13 +34,13 @@
/* **************** CURVE VEC ******************** */
-static bNodeSocketTemplate sh_node_curve_vec_in[]= {
+static bNodeSocketTemplate sh_node_curve_vec_in[] = {
{ SOCK_FLOAT, 0, N_("Fac"), 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_curve_vec_out[]= {
+static bNodeSocketTemplate sh_node_curve_vec_out[] = {
{ SOCK_VECTOR, 0, N_("Vector")},
{ -1, 0, "" }
};
@@ -88,13 +88,13 @@ void register_node_type_sh_curve_vec(bNodeTreeType *ttype)
/* **************** CURVE RGB ******************** */
-static bNodeSocketTemplate sh_node_curve_rgb_in[]= {
+static bNodeSocketTemplate sh_node_curve_rgb_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_FACTOR},
{ SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_curve_rgb_out[]= {
+static bNodeSocketTemplate sh_node_curve_rgb_out[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_emission.c b/source/blender/nodes/shader/nodes/node_shader_emission.c
index 4854d887592..0c4cb7ed51c 100644
--- a/source/blender/nodes/shader/nodes/node_shader_emission.c
+++ b/source/blender/nodes/shader/nodes/node_shader_emission.c
@@ -29,13 +29,13 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_emission_in[]= {
+static bNodeSocketTemplate sh_node_emission_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Strength"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000000.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_emission_out[]= {
+static bNodeSocketTemplate sh_node_emission_out[] = {
{ SOCK_SHADER, 0, N_("Emission")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_fresnel.c b/source/blender/nodes/shader/nodes/node_shader_fresnel.c
index 610a2149011..80913e6b07a 100644
--- a/source/blender/nodes/shader/nodes/node_shader_fresnel.c
+++ b/source/blender/nodes/shader/nodes/node_shader_fresnel.c
@@ -28,12 +28,12 @@
#include "../node_shader_util.h"
/* **************** Fresnel ******************** */
-static bNodeSocketTemplate sh_node_fresnel_in[]= {
+static bNodeSocketTemplate sh_node_fresnel_in[] = {
{ SOCK_FLOAT, 1, N_("IOR"), 1.45f, 0.0f, 0.0f, 0.0f, 1.0f, 1000.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_fresnel_out[]= {
+static bNodeSocketTemplate sh_node_fresnel_out[] = {
{ SOCK_FLOAT, 0, N_("Fac"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_gamma.c b/source/blender/nodes/shader/nodes/node_shader_gamma.c
index 526868f73d3..c49554c44be 100644
--- a/source/blender/nodes/shader/nodes/node_shader_gamma.c
+++ b/source/blender/nodes/shader/nodes/node_shader_gamma.c
@@ -30,13 +30,13 @@
/* **************** Gamma Tools ******************** */
-static bNodeSocketTemplate sh_node_gamma_in[]= {
+static bNodeSocketTemplate sh_node_gamma_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Gamma"), 1.0f, 0.0f, 0.0f, 0.0f, 0.001f, 10.0f, PROP_UNSIGNED},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_gamma_out[]= {
+static bNodeSocketTemplate sh_node_gamma_out[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_geom.c b/source/blender/nodes/shader/nodes/node_shader_geom.c
index f23158ab5d4..eb3d462d616 100644
--- a/source/blender/nodes/shader/nodes/node_shader_geom.c
+++ b/source/blender/nodes/shader/nodes/node_shader_geom.c
@@ -37,7 +37,7 @@
/* **************** GEOMETRY ******************** */
/* output socket type definition */
-static bNodeSocketTemplate sh_node_geom_out[]= {
+static bNodeSocketTemplate sh_node_geom_out[] = {
{ SOCK_VECTOR, 0, N_("Global")},
{ SOCK_VECTOR, 0, N_("Local")},
{ SOCK_VECTOR, 0, N_("View")},
@@ -92,12 +92,12 @@ static void node_shader_exec_geom(void *data, bNode *node, bNodeStack **UNUSED(i
}
copy_v3_v3(out[GEOM_OUT_VCOL]->vec, scol->col);
- out[GEOM_OUT_VCOL]->vec[3]= scol->col[3];
- out[GEOM_OUT_VCOL_ALPHA]->vec[0]= scol->col[3];
+ out[GEOM_OUT_VCOL]->vec[3] = scol->col[3];
+ out[GEOM_OUT_VCOL_ALPHA]->vec[0] = scol->col[3];
}
else {
memcpy(out[GEOM_OUT_VCOL]->vec, defaultvcol, sizeof(defaultvcol));
- out[GEOM_OUT_VCOL_ALPHA]->vec[0]= 1.0f;
+ out[GEOM_OUT_VCOL_ALPHA]->vec[0] = 1.0f;
}
if (shi->osatex) {
@@ -116,7 +116,7 @@ static void node_shader_exec_geom(void *data, bNode *node, bNodeStack **UNUSED(i
}
/* front/back, normal flipping was stored */
- out[GEOM_OUT_FRONTBACK]->vec[0]= (shi->flippednor)? 0.0f: 1.0f;
+ out[GEOM_OUT_FRONTBACK]->vec[0] = (shi->flippednor)? 0.0f: 1.0f;
}
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_geometry.c b/source/blender/nodes/shader/nodes/node_shader_geometry.c
index 2ebd93218d6..acef885d2d4 100644
--- a/source/blender/nodes/shader/nodes/node_shader_geometry.c
+++ b/source/blender/nodes/shader/nodes/node_shader_geometry.c
@@ -29,7 +29,7 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_geometry_out[]= {
+static bNodeSocketTemplate sh_node_geometry_out[] = {
{ SOCK_VECTOR, 0, N_("Position"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_VECTOR, 0, N_("Normal"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_VECTOR, 0, N_("Tangent"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
diff --git a/source/blender/nodes/shader/nodes/node_shader_holdout.c b/source/blender/nodes/shader/nodes/node_shader_holdout.c
index dbd4ed8ab67..18ad4994c9b 100644
--- a/source/blender/nodes/shader/nodes/node_shader_holdout.c
+++ b/source/blender/nodes/shader/nodes/node_shader_holdout.c
@@ -29,11 +29,11 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_holdout_in[]= {
+static bNodeSocketTemplate sh_node_holdout_in[] = {
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_holdout_out[]= {
+static bNodeSocketTemplate sh_node_holdout_out[] = {
{ SOCK_SHADER, 0, N_("Holdout")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_hueSatVal.c b/source/blender/nodes/shader/nodes/node_shader_hueSatVal.c
index b07650e33c0..b635ad1edd9 100644
--- a/source/blender/nodes/shader/nodes/node_shader_hueSatVal.c
+++ b/source/blender/nodes/shader/nodes/node_shader_hueSatVal.c
@@ -34,7 +34,7 @@
/* **************** Hue Saturation ******************** */
-static bNodeSocketTemplate sh_node_hue_sat_in[]= {
+static bNodeSocketTemplate sh_node_hue_sat_in[] = {
{ SOCK_FLOAT, 1, N_("Hue"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE},
{ SOCK_FLOAT, 1, N_("Saturation"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, PROP_FACTOR},
{ SOCK_FLOAT, 1, N_("Value"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, PROP_FACTOR},
@@ -42,7 +42,7 @@ static bNodeSocketTemplate sh_node_hue_sat_in[]= {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_hue_sat_out[]= {
+static bNodeSocketTemplate sh_node_hue_sat_out[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ -1, 0, "" }
};
@@ -60,9 +60,9 @@ static void do_hue_sat_fac(bNode *UNUSED(node), float *out, float *hue, float *s
hsv[2]*= *val;
hsv_to_rgb(hsv[0], hsv[1], hsv[2], col, col+1, col+2);
- out[0]= mfac*in[0] + *fac*col[0];
- out[1]= mfac*in[1] + *fac*col[1];
- out[2]= mfac*in[2] + *fac*col[2];
+ out[0] = mfac*in[0] + *fac*col[0];
+ out[1] = mfac*in[1] + *fac*col[1];
+ out[2] = mfac*in[2] + *fac*col[2];
}
else {
copy_v4_v4(out, in);
diff --git a/source/blender/nodes/shader/nodes/node_shader_invert.c b/source/blender/nodes/shader/nodes/node_shader_invert.c
index ef592a7e2ec..2ea858f4e34 100644
--- a/source/blender/nodes/shader/nodes/node_shader_invert.c
+++ b/source/blender/nodes/shader/nodes/node_shader_invert.c
@@ -35,15 +35,15 @@
/* **************** INVERT ******************** */
-static bNodeSocketTemplate sh_node_invert_in[]= {
- { SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
- { SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
- { -1, 0, "" }
+static bNodeSocketTemplate sh_node_invert_in[] = {
+ { SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_invert_out[]= {
- { SOCK_RGBA, 0, N_("Color")},
- { -1, 0, "" }
+static bNodeSocketTemplate sh_node_invert_out[] = {
+ { SOCK_RGBA, 0, N_("Color")},
+ { -1, 0, "" }
};
static void node_shader_exec_invert(void *UNUSED(data), bNode *UNUSED(node), bNodeStack **in,
diff --git a/source/blender/nodes/shader/nodes/node_shader_layer_weight.c b/source/blender/nodes/shader/nodes/node_shader_layer_weight.c
index 6eacea10b5b..3058483ebef 100644
--- a/source/blender/nodes/shader/nodes/node_shader_layer_weight.c
+++ b/source/blender/nodes/shader/nodes/node_shader_layer_weight.c
@@ -29,12 +29,12 @@
/* **************** Layer Weight ******************** */
-static bNodeSocketTemplate sh_node_layer_weight_in[]= {
+static bNodeSocketTemplate sh_node_layer_weight_in[] = {
{ SOCK_FLOAT, 1, N_("Blend"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_layer_weight_out[]= {
+static bNodeSocketTemplate sh_node_layer_weight_out[] = {
{ SOCK_FLOAT, 0, N_("Fresnel"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Facing"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
diff --git a/source/blender/nodes/shader/nodes/node_shader_light_falloff.c b/source/blender/nodes/shader/nodes/node_shader_light_falloff.c
index aab5fa8060d..2dec244ae3a 100644
--- a/source/blender/nodes/shader/nodes/node_shader_light_falloff.c
+++ b/source/blender/nodes/shader/nodes/node_shader_light_falloff.c
@@ -29,7 +29,7 @@
/* **************** INPUT ********************* */
-static bNodeSocketTemplate sh_node_light_falloff_in[]= {
+static bNodeSocketTemplate sh_node_light_falloff_in[] = {
{ SOCK_FLOAT, 0, N_("Strength"), 100.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000000.0f},
{ SOCK_FLOAT, 0, N_("Smooth"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
{ -1, 0, "" }
@@ -37,7 +37,7 @@ static bNodeSocketTemplate sh_node_light_falloff_in[]= {
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_light_falloff_out[]= {
+static bNodeSocketTemplate sh_node_light_falloff_out[] = {
{ SOCK_FLOAT, 0, N_("Quadratic"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Linear"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Constant"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
diff --git a/source/blender/nodes/shader/nodes/node_shader_light_path.c b/source/blender/nodes/shader/nodes/node_shader_light_path.c
index 264b1390688..b4a3d4e01e1 100644
--- a/source/blender/nodes/shader/nodes/node_shader_light_path.c
+++ b/source/blender/nodes/shader/nodes/node_shader_light_path.c
@@ -29,7 +29,7 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_light_path_out[]= {
+static bNodeSocketTemplate sh_node_light_path_out[] = {
{ SOCK_FLOAT, 0, N_("Is Camera Ray"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Is Shadow Ray"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Is Diffuse Ray"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
diff --git a/source/blender/nodes/shader/nodes/node_shader_mapping.c b/source/blender/nodes/shader/nodes/node_shader_mapping.c
index 4508f66543e..cedd3a4910c 100644
--- a/source/blender/nodes/shader/nodes/node_shader_mapping.c
+++ b/source/blender/nodes/shader/nodes/node_shader_mapping.c
@@ -33,12 +33,12 @@
#include "node_shader_util.h"
/* **************** MAPPING ******************** */
-static bNodeSocketTemplate sh_node_mapping_in[]= {
+static bNodeSocketTemplate sh_node_mapping_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_mapping_out[]= {
+static bNodeSocketTemplate sh_node_mapping_out[] = {
{ SOCK_VECTOR, 0, N_("Vector")},
{ -1, 0, "" }
};
@@ -55,14 +55,14 @@ static void node_shader_exec_mapping(void *UNUSED(data), bNode *node, bNodeStack
mul_m4_v3(texmap->mat, vec);
if (texmap->flag & TEXMAP_CLIP_MIN) {
- if (vec[0]<texmap->min[0]) vec[0]= texmap->min[0];
- if (vec[1]<texmap->min[1]) vec[1]= texmap->min[1];
- if (vec[2]<texmap->min[2]) vec[2]= texmap->min[2];
+ if (vec[0]<texmap->min[0]) vec[0] = texmap->min[0];
+ if (vec[1]<texmap->min[1]) vec[1] = texmap->min[1];
+ if (vec[2]<texmap->min[2]) vec[2] = texmap->min[2];
}
if (texmap->flag & TEXMAP_CLIP_MAX) {
- if (vec[0]>texmap->max[0]) vec[0]= texmap->max[0];
- if (vec[1]>texmap->max[1]) vec[1]= texmap->max[1];
- if (vec[2]>texmap->max[2]) vec[2]= texmap->max[2];
+ if (vec[0]>texmap->max[0]) vec[0] = texmap->max[0];
+ if (vec[1]>texmap->max[1]) vec[1] = texmap->max[1];
+ if (vec[2]>texmap->max[2]) vec[2] = texmap->max[2];
}
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_material.c b/source/blender/nodes/shader/nodes/node_shader_material.c
index 57865e072e7..bccf6d349cf 100644
--- a/source/blender/nodes/shader/nodes/node_shader_material.c
+++ b/source/blender/nodes/shader/nodes/node_shader_material.c
@@ -34,7 +34,7 @@
/* **************** MATERIAL ******************** */
-static bNodeSocketTemplate sh_node_material_in[]= {
+static bNodeSocketTemplate sh_node_material_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_RGBA, 1, N_("Spec"), 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Refl"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
@@ -42,7 +42,7 @@ static bNodeSocketTemplate sh_node_material_in[]= {
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_material_out[]= {
+static bNodeSocketTemplate sh_node_material_out[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ SOCK_FLOAT, 0, N_("Alpha")},
{ SOCK_VECTOR, 0, N_("Normal")},
@@ -51,7 +51,7 @@ static bNodeSocketTemplate sh_node_material_out[]= {
/* **************** EXTENDED MATERIAL ******************** */
-static bNodeSocketTemplate sh_node_material_ext_in[]= {
+static bNodeSocketTemplate sh_node_material_ext_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_RGBA, 1, N_("Spec"), 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Refl"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_FACTOR},
@@ -66,7 +66,7 @@ static bNodeSocketTemplate sh_node_material_ext_in[]= {
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_material_ext_out[]= {
+static bNodeSocketTemplate sh_node_material_ext_out[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ SOCK_FLOAT, 0, N_("Alpha")},
{ SOCK_VECTOR, 0, N_("Normal")},
@@ -84,7 +84,7 @@ static void node_shader_exec_material(void *data, bNode *node, bNodeStack **in,
ShaderCallData *shcd= data;
float col[4];
bNodeSocket *sock;
- char hasinput[NUM_MAT_IN]= {'\0'};
+ char hasinput[NUM_MAT_IN] = {'\0'};
int i;
/* note: cannot use the in[]->hasinput flags directly, as these are not necessarily
@@ -139,7 +139,7 @@ static void node_shader_exec_material(void *data, bNode *node, bNodeStack **in,
if (hasinput[MAT_IN_ALPHA])
nodestack_get_vec(&shi->alpha, SOCK_FLOAT, in[MAT_IN_ALPHA]);
if (hasinput[MAT_IN_TRANSLUCENCY])
- nodestack_get_vec(&shi->translucency, SOCK_FLOAT, in[MAT_IN_TRANSLUCENCY]);
+ nodestack_get_vec(&shi->translucency, SOCK_FLOAT, in[MAT_IN_TRANSLUCENCY]);
}
shi->nodes= 1; /* temp hack to prevent trashadow recursion */
@@ -157,20 +157,20 @@ static void node_shader_exec_material(void *data, bNode *node, bNodeStack **in,
copy_v3_v3(col, shrnode.spec);
}
else
- col[0]= col[1]= col[2]= 0.0f;
+ col[0] = col[1] = col[2] = 0.0f;
- col[3]= shrnode.alpha;
+ col[3] = shrnode.alpha;
if (shi->do_preview)
nodeAddToPreview(node, col, shi->xs, shi->ys, shi->do_manage);
copy_v3_v3(out[MAT_OUT_COLOR]->vec, col);
- out[MAT_OUT_ALPHA]->vec[0]= shrnode.alpha;
+ out[MAT_OUT_ALPHA]->vec[0] = shrnode.alpha;
if (node->custom1 & SH_NODE_MAT_NEG) {
- shi->vn[0]= -shi->vn[0];
- shi->vn[1]= -shi->vn[1];
- shi->vn[2]= -shi->vn[2];
+ shi->vn[0] = -shi->vn[0];
+ shi->vn[1] = -shi->vn[1];
+ shi->vn[2] = -shi->vn[2];
}
copy_v3_v3(out[MAT_OUT_NORMAL]->vec, shi->vn);
@@ -222,7 +222,7 @@ static int gpu_shader_material(GPUMaterial *mat, bNode *node, GPUNodeStack *in,
GPUShadeInput shi;
GPUShadeResult shr;
bNodeSocket *sock;
- char hasinput[NUM_MAT_IN]= {'\0'};
+ char hasinput[NUM_MAT_IN] = {'\0'};
int i;
/* note: cannot use the in[]->hasinput flags directly, as these are not necessarily
diff --git a/source/blender/nodes/shader/nodes/node_shader_math.c b/source/blender/nodes/shader/nodes/node_shader_math.c
index c112ae1d448..a70134b2325 100644
--- a/source/blender/nodes/shader/nodes/node_shader_math.c
+++ b/source/blender/nodes/shader/nodes/node_shader_math.c
@@ -34,61 +34,61 @@
/* **************** SCALAR MATH ******************** */
-static bNodeSocketTemplate sh_node_math_in[]= {
- { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
- { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
- { -1, 0, "" }
+static bNodeSocketTemplate sh_node_math_in[] = {
+ { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
+ { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
+ { -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_math_out[]= {
- { SOCK_FLOAT, 0, N_("Value")},
- { -1, 0, "" }
+static bNodeSocketTemplate sh_node_math_out[] = {
+ { SOCK_FLOAT, 0, N_("Value")},
+ { -1, 0, "" }
};
static void node_shader_exec_math(void *UNUSED(data), bNode *node, bNodeStack **in,
bNodeStack **out)
{
- switch (node->custom1) {
+ switch (node->custom1) {
case 0: /* Add */
- out[0]->vec[0]= in[0]->vec[0] + in[1]->vec[0];
+ out[0]->vec[0] = in[0]->vec[0] + in[1]->vec[0];
break;
case 1: /* Subtract */
- out[0]->vec[0]= in[0]->vec[0] - in[1]->vec[0];
+ out[0]->vec[0] = in[0]->vec[0] - in[1]->vec[0];
break;
case 2: /* Multiply */
- out[0]->vec[0]= in[0]->vec[0] * in[1]->vec[0];
+ out[0]->vec[0] = in[0]->vec[0] * in[1]->vec[0];
break;
case 3: /* Divide */
{
if (in[1]->vec[0]==0) /* We don't want to divide by zero. */
- out[0]->vec[0]= 0.0;
+ out[0]->vec[0] = 0.0;
else
- out[0]->vec[0]= in[0]->vec[0] / in[1]->vec[0];
+ out[0]->vec[0] = in[0]->vec[0] / in[1]->vec[0];
}
break;
case 4: /* Sine */
{
if (in[0]->hasinput || !in[1]->hasinput) /* This one only takes one input, so we've got to choose. */
- out[0]->vec[0]= sin(in[0]->vec[0]);
+ out[0]->vec[0] = sin(in[0]->vec[0]);
else
- out[0]->vec[0]= sin(in[1]->vec[0]);
+ out[0]->vec[0] = sin(in[1]->vec[0]);
}
break;
case 5: /* Cosine */
{
- if (in[0]->hasinput || !in[1]->hasinput) /* This one only takes one input, so we've got to choose. */
- out[0]->vec[0]= cos(in[0]->vec[0]);
+ if (in[0]->hasinput || !in[1]->hasinput) /* This one only takes one input, so we've got to choose. */
+ out[0]->vec[0] = cos(in[0]->vec[0]);
else
- out[0]->vec[0]= cos(in[1]->vec[0]);
+ out[0]->vec[0] = cos(in[1]->vec[0]);
}
break;
case 6: /* Tangent */
{
- if (in[0]->hasinput || !in[1]->hasinput) /* This one only takes one input, so we've got to choose. */
- out[0]->vec[0]= tan(in[0]->vec[0]);
+ if (in[0]->hasinput || !in[1]->hasinput) /* This one only takes one input, so we've got to choose. */
+ out[0]->vec[0] = tan(in[0]->vec[0]);
else
- out[0]->vec[0]= tan(in[1]->vec[0]);
+ out[0]->vec[0] = tan(in[1]->vec[0]);
}
break;
case 7: /* Arc-Sine */
@@ -96,16 +96,16 @@ bNodeStack **out)
if (in[0]->hasinput || !in[1]->hasinput) { /* This one only takes one input, so we've got to choose. */
/* Can't do the impossible... */
if ( in[0]->vec[0] <= 1 && in[0]->vec[0] >= -1 )
- out[0]->vec[0]= asin(in[0]->vec[0]);
+ out[0]->vec[0] = asin(in[0]->vec[0]);
else
- out[0]->vec[0]= 0.0;
+ out[0]->vec[0] = 0.0;
}
else {
/* Can't do the impossible... */
if ( in[1]->vec[0] <= 1 && in[1]->vec[0] >= -1 )
- out[0]->vec[0]= asin(in[1]->vec[0]);
+ out[0]->vec[0] = asin(in[1]->vec[0]);
else
- out[0]->vec[0]= 0.0;
+ out[0]->vec[0] = 0.0;
}
}
break;
@@ -114,86 +114,86 @@ bNodeStack **out)
if (in[0]->hasinput || !in[1]->hasinput) { /* This one only takes one input, so we've got to choose. */
/* Can't do the impossible... */
if ( in[0]->vec[0] <= 1 && in[0]->vec[0] >= -1 )
- out[0]->vec[0]= acos(in[0]->vec[0]);
+ out[0]->vec[0] = acos(in[0]->vec[0]);
else
- out[0]->vec[0]= 0.0;
+ out[0]->vec[0] = 0.0;
}
else {
/* Can't do the impossible... */
if ( in[1]->vec[0] <= 1 && in[1]->vec[0] >= -1 )
- out[0]->vec[0]= acos(in[1]->vec[0]);
+ out[0]->vec[0] = acos(in[1]->vec[0]);
else
- out[0]->vec[0]= 0.0;
+ out[0]->vec[0] = 0.0;
}
}
break;
case 9: /* Arc-Tangent */
{
if (in[0]->hasinput || !in[1]->hasinput) /* This one only takes one input, so we've got to choose. */
- out[0]->vec[0]= atan(in[0]->vec[0]);
+ out[0]->vec[0] = atan(in[0]->vec[0]);
else
- out[0]->vec[0]= atan(in[1]->vec[0]);
+ out[0]->vec[0] = atan(in[1]->vec[0]);
}
break;
case 10: /* Power */
{
/* Don't want any imaginary numbers... */
if ( in[0]->vec[0] >= 0 )
- out[0]->vec[0]= pow(in[0]->vec[0], in[1]->vec[0]);
+ out[0]->vec[0] = pow(in[0]->vec[0], in[1]->vec[0]);
else
- out[0]->vec[0]= 0.0;
+ out[0]->vec[0] = 0.0;
}
break;
case 11: /* Logarithm */
{
/* Don't want any imaginary numbers... */
if ( in[0]->vec[0] > 0 && in[1]->vec[0] > 0 )
- out[0]->vec[0]= log(in[0]->vec[0]) / log(in[1]->vec[0]);
+ out[0]->vec[0] = log(in[0]->vec[0]) / log(in[1]->vec[0]);
else
- out[0]->vec[0]= 0.0;
+ out[0]->vec[0] = 0.0;
}
break;
case 12: /* Minimum */
{
if ( in[0]->vec[0] < in[1]->vec[0] )
- out[0]->vec[0]= in[0]->vec[0];
+ out[0]->vec[0] = in[0]->vec[0];
else
- out[0]->vec[0]= in[1]->vec[0];
+ out[0]->vec[0] = in[1]->vec[0];
}
break;
case 13: /* Maximum */
{
if ( in[0]->vec[0] > in[1]->vec[0] )
- out[0]->vec[0]= in[0]->vec[0];
+ out[0]->vec[0] = in[0]->vec[0];
else
- out[0]->vec[0]= in[1]->vec[0];
+ out[0]->vec[0] = in[1]->vec[0];
}
break;
case 14: /* Round */
{
if (in[0]->hasinput || !in[1]->hasinput) /* This one only takes one input, so we've got to choose. */
- out[0]->vec[0]= (in[0]->vec[0]<0)?(int)(in[0]->vec[0] - 0.5f):(int)(in[0]->vec[0] + 0.5f);
+ out[0]->vec[0] = (in[0]->vec[0]<0)?(int)(in[0]->vec[0] - 0.5f):(int)(in[0]->vec[0] + 0.5f);
else
- out[0]->vec[0]= (in[1]->vec[0]<0)?(int)(in[1]->vec[0] - 0.5f):(int)(in[1]->vec[0] + 0.5f);
+ out[0]->vec[0] = (in[1]->vec[0]<0)?(int)(in[1]->vec[0] - 0.5f):(int)(in[1]->vec[0] + 0.5f);
}
break;
case 15: /* Less Than */
{
if ( in[0]->vec[0] < in[1]->vec[0] )
- out[0]->vec[0]= 1.0f;
+ out[0]->vec[0] = 1.0f;
else
- out[0]->vec[0]= 0.0f;
+ out[0]->vec[0] = 0.0f;
}
break;
case 16: /* Greater Than */
{
if ( in[0]->vec[0] > in[1]->vec[0] )
- out[0]->vec[0]= 1.0f;
+ out[0]->vec[0] = 1.0f;
else
- out[0]->vec[0]= 0.0f;
+ out[0]->vec[0] = 0.0f;
}
break;
- }
+ }
}
static int gpu_shader_math(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
diff --git a/source/blender/nodes/shader/nodes/node_shader_mixRgb.c b/source/blender/nodes/shader/nodes/node_shader_mixRgb.c
index 53c1387ca1a..18dcc8f7fef 100644
--- a/source/blender/nodes/shader/nodes/node_shader_mixRgb.c
+++ b/source/blender/nodes/shader/nodes/node_shader_mixRgb.c
@@ -33,13 +33,13 @@
#include "node_shader_util.h"
/* **************** MIX RGB ******************** */
-static bNodeSocketTemplate sh_node_mix_rgb_in[]= {
+static bNodeSocketTemplate sh_node_mix_rgb_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_RGBA, 1, N_("Color1"), 0.5f, 0.5f, 0.5f, 1.0f},
{ SOCK_RGBA, 1, N_("Color2"), 0.5f, 0.5f, 0.5f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_mix_rgb_out[]= {
+static bNodeSocketTemplate sh_node_mix_rgb_out[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_mix_shader.c b/source/blender/nodes/shader/nodes/node_shader_mix_shader.c
index 80ee1a8499d..039e63a4dea 100644
--- a/source/blender/nodes/shader/nodes/node_shader_mix_shader.c
+++ b/source/blender/nodes/shader/nodes/node_shader_mix_shader.c
@@ -29,14 +29,14 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_mix_shader_in[]= {
+static bNodeSocketTemplate sh_node_mix_shader_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_SHADER, 1, N_("Shader")},
{ SOCK_SHADER, 1, N_("Shader")},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_mix_shader_out[]= {
+static bNodeSocketTemplate sh_node_mix_shader_out[] = {
{ SOCK_SHADER, 0, N_("Shader")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_normal.c b/source/blender/nodes/shader/nodes/node_shader_normal.c
index bb0a85417d9..98a56c85279 100644
--- a/source/blender/nodes/shader/nodes/node_shader_normal.c
+++ b/source/blender/nodes/shader/nodes/node_shader_normal.c
@@ -33,12 +33,12 @@
#include "node_shader_util.h"
/* **************** NORMAL ******************** */
-static bNodeSocketTemplate sh_node_normal_in[]= {
+static bNodeSocketTemplate sh_node_normal_in[] = {
{ SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_normal_out[]= {
+static bNodeSocketTemplate sh_node_normal_out[] = {
{ SOCK_VECTOR, 0, N_("Normal")},
{ SOCK_FLOAT, 0, N_("Dot")},
{ -1, 0, "" }
@@ -68,7 +68,7 @@ static void node_shader_exec_normal(void *UNUSED(data), bNode *node, bNodeStack
copy_v3_v3(out[0]->vec, ((bNodeSocketValueVector*)sock->default_value)->value);
/* render normals point inside... the widget points outside */
- out[1]->vec[0]= -dot_v3v3(out[0]->vec, vec);
+ out[1]->vec[0] = -dot_v3v3(out[0]->vec, vec);
}
static int gpu_shader_normal(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
diff --git a/source/blender/nodes/shader/nodes/node_shader_object_info.c b/source/blender/nodes/shader/nodes/node_shader_object_info.c
index 1cafa01ecec..ef283004d46 100644
--- a/source/blender/nodes/shader/nodes/node_shader_object_info.c
+++ b/source/blender/nodes/shader/nodes/node_shader_object_info.c
@@ -29,7 +29,7 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_object_info_out[]= {
+static bNodeSocketTemplate sh_node_object_info_out[] = {
{ SOCK_VECTOR, 0, N_("Location"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Object Index"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Material Index"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
diff --git a/source/blender/nodes/shader/nodes/node_shader_output.c b/source/blender/nodes/shader/nodes/node_shader_output.c
index 4434054abae..6f7f900aecd 100644
--- a/source/blender/nodes/shader/nodes/node_shader_output.c
+++ b/source/blender/nodes/shader/nodes/node_shader_output.c
@@ -33,7 +33,7 @@
#include "node_shader_util.h"
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_output_in[]= {
+static bNodeSocketTemplate sh_node_output_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Alpha"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ -1, 0, "" }
@@ -62,7 +62,7 @@ static void node_shader_exec_output(void *data, bNode *node, bNodeStack **in, bN
// copy_v3_v3(shr->nor, in[3]->vec);
}
- }
+ }
}
static int gpu_shader_output(GPUMaterial *mat, bNode *UNUSED(node), GPUNodeStack *in, GPUNodeStack *out)
@@ -92,7 +92,7 @@ void register_node_type_sh_output(bNodeTreeType *ttype)
node_type_gpu(&ntype, gpu_shader_output);
/* Do not allow muting output node. */
- node_type_internal_connect(&ntype, NULL);
+ node_type_internal_links(&ntype, NULL);
nodeRegisterType(ttype, &ntype);
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_output_lamp.c b/source/blender/nodes/shader/nodes/node_shader_output_lamp.c
index eb7208302fe..ce406a8f5a1 100644
--- a/source/blender/nodes/shader/nodes/node_shader_output_lamp.c
+++ b/source/blender/nodes/shader/nodes/node_shader_output_lamp.c
@@ -29,7 +29,7 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_output_lamp_in[]= {
+static bNodeSocketTemplate sh_node_output_lamp_in[] = {
{ SOCK_SHADER, 1, N_("Surface"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
@@ -49,7 +49,7 @@ void register_node_type_sh_output_lamp(bNodeTreeType *ttype)
node_type_gpu(&ntype, NULL);
/* Do not allow muting output node. */
- node_type_internal_connect(&ntype, NULL);
+ node_type_internal_links(&ntype, NULL);
nodeRegisterType(ttype, &ntype);
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_output_material.c b/source/blender/nodes/shader/nodes/node_shader_output_material.c
index e81744c44bd..f185e13010b 100644
--- a/source/blender/nodes/shader/nodes/node_shader_output_material.c
+++ b/source/blender/nodes/shader/nodes/node_shader_output_material.c
@@ -29,7 +29,7 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_output_material_in[]= {
+static bNodeSocketTemplate sh_node_output_material_in[] = {
{ SOCK_SHADER, 1, N_("Surface")},
{ SOCK_SHADER, 1, N_("Volume")},
{ SOCK_FLOAT, 1, N_("Displacement"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
@@ -62,7 +62,7 @@ void register_node_type_sh_output_material(bNodeTreeType *ttype)
node_type_gpu(&ntype, node_shader_gpu_output_material);
/* Do not allow muting output node. */
- node_type_internal_connect(&ntype, NULL);
+ node_type_internal_links(&ntype, NULL);
nodeRegisterType(ttype, &ntype);
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_output_world.c b/source/blender/nodes/shader/nodes/node_shader_output_world.c
index 3a931c2af53..953197ab2cd 100644
--- a/source/blender/nodes/shader/nodes/node_shader_output_world.c
+++ b/source/blender/nodes/shader/nodes/node_shader_output_world.c
@@ -29,7 +29,7 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_output_world_in[]= {
+static bNodeSocketTemplate sh_node_output_world_in[] = {
{ SOCK_SHADER, 1, N_("Surface"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_SHADER, 1, N_("Volume"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
@@ -50,7 +50,7 @@ void register_node_type_sh_output_world(bNodeTreeType *ttype)
node_type_gpu(&ntype, NULL);
/* Do not allow muting output node. */
- node_type_internal_connect(&ntype, NULL);
+ node_type_internal_links(&ntype, NULL);
nodeRegisterType(ttype, &ntype);
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_particle_info.c b/source/blender/nodes/shader/nodes/node_shader_particle_info.c
index ddfcb9476f4..c7e31d117cc 100644
--- a/source/blender/nodes/shader/nodes/node_shader_particle_info.c
+++ b/source/blender/nodes/shader/nodes/node_shader_particle_info.c
@@ -28,18 +28,18 @@
#include "../node_shader_util.h"
static bNodeSocketTemplate outputs[] = {
- { SOCK_FLOAT, 0, "Index" },
- { SOCK_FLOAT, 0, "Age" },
- { SOCK_FLOAT, 0, "Lifetime" },
- { SOCK_VECTOR, 0, "Location" },
- #if 0 /* quaternion sockets not yet supported */
- { SOCK_QUATERNION, 0, "Rotation" },
- #endif
- { SOCK_FLOAT, 0, "Size" },
- { SOCK_VECTOR, 0, "Velocity" },
- { SOCK_VECTOR, 0, "Angular Velocity" },
- { -1, 0, "" }
-};
+ { SOCK_FLOAT, 0, "Index" },
+ { SOCK_FLOAT, 0, "Age" },
+ { SOCK_FLOAT, 0, "Lifetime" },
+ { SOCK_VECTOR, 0, "Location" },
+#if 0 /* quaternion sockets not yet supported */
+ { SOCK_QUATERNION, 0, "Rotation" },
+#endif
+ { SOCK_FLOAT, 0, "Size" },
+ { SOCK_VECTOR, 0, "Velocity" },
+ { SOCK_VECTOR, 0, "Angular Velocity" },
+ { -1, 0, "" }
+ };
/* node type definition */
void register_node_type_sh_particle_info(bNodeTreeType *ttype)
diff --git a/source/blender/nodes/shader/nodes/node_shader_rgb.c b/source/blender/nodes/shader/nodes/node_shader_rgb.c
index 5a19c61fe92..f37ff1d511b 100644
--- a/source/blender/nodes/shader/nodes/node_shader_rgb.c
+++ b/source/blender/nodes/shader/nodes/node_shader_rgb.c
@@ -33,7 +33,7 @@
#include "node_shader_util.h"
/* **************** RGB ******************** */
-static bNodeSocketTemplate sh_node_rgb_out[]= {
+static bNodeSocketTemplate sh_node_rgb_out[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_script.c b/source/blender/nodes/shader/nodes/node_shader_script.c
new file mode 100644
index 00000000000..52d39363de6
--- /dev/null
+++ b/source/blender/nodes/shader/nodes/node_shader_script.c
@@ -0,0 +1,85 @@
+/*
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/nodes/shader/nodes/node_shader_script.c
+ * \ingroup shdnodes
+ */
+
+#include "BKE_idprop.h"
+
+#include "node_shader_util.h"
+
+/* **************** Script ******************** */
+
+static void init(bNodeTree *UNUSED(ntree), bNode *node, bNodeTemplate *UNUSED(ntemp))
+{
+ NodeShaderScript *nss = MEM_callocN(sizeof(NodeShaderScript), "shader script node");
+ node->storage = nss;
+}
+
+static void node_free_script(bNode *node)
+{
+ NodeShaderScript *nss = node->storage;
+
+ if (nss) {
+ if (nss->bytecode)
+ MEM_freeN(nss->bytecode);
+
+ MEM_freeN(nss);
+ }
+
+ if (nss->prop) {
+ IDP_FreeProperty(nss->prop);
+ MEM_freeN(nss->prop);
+ }
+}
+
+static void node_copy_script(bNode *orig_node, bNode *new_node)
+{
+ NodeShaderScript *orig_nss = orig_node->storage;
+ NodeShaderScript *new_nss = MEM_dupallocN(orig_nss);
+
+ if(orig_nss->bytecode)
+ new_nss->bytecode = MEM_dupallocN(orig_nss->bytecode);
+
+ if (orig_nss->prop)
+ new_nss->prop = IDP_CopyProperty(orig_nss->prop);
+
+ new_node->storage = new_nss;
+}
+
+void register_node_type_sh_script(bNodeTreeType *ttype)
+{
+ static bNodeType ntype;
+
+ node_type_base(ttype, &ntype, SH_NODE_SCRIPT, "Script", NODE_CLASS_SCRIPT, NODE_OPTIONS);
+ node_type_compatibility(&ntype, NODE_NEW_SHADING);
+ node_type_init(&ntype, init);
+ node_type_storage(&ntype, "NodeShaderScript", node_free_script, node_copy_script);
+
+ nodeRegisterType(ttype, &ntype);
+}
diff --git a/source/blender/nodes/shader/nodes/node_shader_sepcombRGB.c b/source/blender/nodes/shader/nodes/node_shader_sepcombRGB.c
index 55f37b666e7..70fba161de9 100644
--- a/source/blender/nodes/shader/nodes/node_shader_sepcombRGB.c
+++ b/source/blender/nodes/shader/nodes/node_shader_sepcombRGB.c
@@ -33,11 +33,11 @@
#include "node_shader_util.h"
/* **************** SEPARATE RGBA ******************** */
-static bNodeSocketTemplate sh_node_seprgb_in[]= {
+static bNodeSocketTemplate sh_node_seprgb_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 0.8f, 0.8f, 0.8f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_seprgb_out[]= {
+static bNodeSocketTemplate sh_node_seprgb_out[] = {
{ SOCK_FLOAT, 0, N_("R")},
{ SOCK_FLOAT, 0, N_("G")},
{ SOCK_FLOAT, 0, N_("B")},
@@ -73,13 +73,13 @@ void register_node_type_sh_seprgb(bNodeTreeType *ttype)
/* **************** COMBINE RGB ******************** */
-static bNodeSocketTemplate sh_node_combrgb_in[]= {
+static bNodeSocketTemplate sh_node_combrgb_in[] = {
{ SOCK_FLOAT, 1, N_("R"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_UNSIGNED},
{ SOCK_FLOAT, 1, N_("G"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_UNSIGNED},
{ SOCK_FLOAT, 1, N_("B"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_UNSIGNED},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_combrgb_out[]= {
+static bNodeSocketTemplate sh_node_combrgb_out[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_squeeze.c b/source/blender/nodes/shader/nodes/node_shader_squeeze.c
index adab396be02..8073f4b01d2 100644
--- a/source/blender/nodes/shader/nodes/node_shader_squeeze.c
+++ b/source/blender/nodes/shader/nodes/node_shader_squeeze.c
@@ -33,20 +33,19 @@
#include "node_shader_util.h"
/* **************** VALUE SQUEEZE ******************** */
-static bNodeSocketTemplate sh_node_squeeze_in[]= {
- { SOCK_FLOAT, 1, N_("Value"), 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f, PROP_NONE},
- { SOCK_FLOAT, 1, N_("Width"), 1.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f, PROP_NONE},
- { SOCK_FLOAT, 1, N_("Center"), 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f, PROP_NONE},
- { -1, 0, "" }
+static bNodeSocketTemplate sh_node_squeeze_in[] = {
+ { SOCK_FLOAT, 1, N_("Value"), 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f, PROP_NONE},
+ { SOCK_FLOAT, 1, N_("Width"), 1.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f, PROP_NONE},
+ { SOCK_FLOAT, 1, N_("Center"), 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f, PROP_NONE},
+ { -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_squeeze_out[]= {
- { SOCK_FLOAT, 0, N_("Value")},
- { -1, 0, "" }
+static bNodeSocketTemplate sh_node_squeeze_out[] = {
+ { SOCK_FLOAT, 0, N_("Value")},
+ { -1, 0, "" }
};
-static void node_shader_exec_squeeze(void *UNUSED(data), bNode *UNUSED(node), bNodeStack **in,
-bNodeStack **out)
+static void node_shader_exec_squeeze(void *UNUSED(data), bNode *UNUSED(node), bNodeStack **in, bNodeStack **out)
{
float vec[3];
@@ -54,7 +53,7 @@ bNodeStack **out)
nodestack_get_vec(vec+1, SOCK_FLOAT, in[1]);
nodestack_get_vec(vec+2, SOCK_FLOAT, in[2]);
- out[0]->vec[0] = 1.0f / (1.0f + pow(M_E, -((vec[0] - vec[2]) * vec[1])));
+ out[0]->vec[0] = 1.0f / (1.0f + powf(M_E, -((vec[0] - vec[2]) * vec[1])));
}
static int gpu_shader_squeeze(GPUMaterial *mat, bNode *UNUSED(node), GPUNodeStack *in, GPUNodeStack *out)
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_brick.c b/source/blender/nodes/shader/nodes/node_shader_tex_brick.c
index 11f7fb94ae0..66bf0267586 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_brick.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_brick.c
@@ -29,7 +29,7 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_tex_brick_in[]= {
+static bNodeSocketTemplate sh_node_tex_brick_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ SOCK_RGBA, 1, N_("Color1"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_RGBA, 1, N_("Color2"), 0.2f, 0.2f, 0.2f, 1.0f, 0.0f, 1.0f},
@@ -42,7 +42,7 @@ static bNodeSocketTemplate sh_node_tex_brick_in[]= {
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_tex_brick_out[]= {
+static bNodeSocketTemplate sh_node_tex_brick_out[] = {
{ SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Fac"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_checker.c b/source/blender/nodes/shader/nodes/node_shader_tex_checker.c
index 0c1e7dcb995..8a2ae2d40dc 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_checker.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_checker.c
@@ -29,7 +29,7 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_tex_checker_in[]= {
+static bNodeSocketTemplate sh_node_tex_checker_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ SOCK_RGBA, 1, N_("Color1"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_RGBA, 1, N_("Color2"), 0.2f, 0.2f, 0.2f, 1.0f, 0.0f, 1.0f},
@@ -37,7 +37,7 @@ static bNodeSocketTemplate sh_node_tex_checker_in[]= {
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_tex_checker_out[]= {
+static bNodeSocketTemplate sh_node_tex_checker_out[] = {
{ SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Fac"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_coord.c b/source/blender/nodes/shader/nodes/node_shader_tex_coord.c
index 86f71f6f05b..dd717874951 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_coord.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_coord.c
@@ -31,7 +31,7 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_tex_coord_out[]= {
+static bNodeSocketTemplate sh_node_tex_coord_out[] = {
{ SOCK_VECTOR, 0, N_("Generated"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_VECTOR, 0, N_("Normal"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_VECTOR, 0, N_("UV"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
@@ -57,7 +57,7 @@ void register_node_type_sh_tex_coord(bNodeTreeType *ttype)
{
static bNodeType ntype;
- node_type_base(ttype, &ntype, SH_NODE_TEX_COORD, "Texture Coordinate", NODE_CLASS_INPUT, 0);
+ node_type_base(ttype, &ntype, SH_NODE_TEX_COORD, "Texture Coordinate", NODE_CLASS_INPUT, NODE_OPTIONS);
node_type_compatibility(&ntype, NODE_NEW_SHADING);
node_type_socket_templates(&ntype, NULL, sh_node_tex_coord_out);
node_type_size(&ntype, 150, 60, 200);
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_environment.c b/source/blender/nodes/shader/nodes/node_shader_tex_environment.c
index ace0f0c8774..abe8e0190c8 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_environment.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_environment.c
@@ -27,14 +27,16 @@
#include "../node_shader_util.h"
+#include "IMB_colormanagement.h"
+
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_tex_environment_in[]= {
+static bNodeSocketTemplate sh_node_tex_environment_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_tex_environment_out[]= {
+static bNodeSocketTemplate sh_node_tex_environment_out[] = {
{ SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
@@ -59,7 +61,8 @@ static int node_shader_gpu_tex_environment(GPUMaterial *mat, bNode *node, GPUNod
Image *ima= (Image*)node->id;
ImageUser *iuser= NULL;
NodeTexImage *tex = node->storage;
- int ncd = tex->color_space == SHD_COLORSPACE_NONE;
+ int isdata = tex->color_space == SHD_COLORSPACE_NONE;
+ int ret;
if (!ima)
return GPU_stack_link(mat, "node_tex_environment_empty", in, out);
@@ -69,10 +72,18 @@ static int node_shader_gpu_tex_environment(GPUMaterial *mat, bNode *node, GPUNod
node_shader_gpu_tex_mapping(mat, node, in, out);
- if (out[0].link && GPU_material_do_color_management(mat))
- GPU_link(mat, "srgb_to_linearrgb", out[0].link, &out[0].link);
+ ret = GPU_stack_link(mat, "node_tex_environment", in, out, GPU_image(ima, iuser, isdata));
+
+ if (ret) {
+ ImBuf *ibuf = BKE_image_get_ibuf(ima, iuser);
+ if (ibuf && (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA) == 0 &&
+ GPU_material_do_color_management(mat))
+ {
+ GPU_link(mat, "srgb_to_linearrgb", out[0].link, &out[0].link);
+ }
+ }
- return GPU_stack_link(mat, "node_tex_environment", in, out, GPU_image(ima, iuser, ncd));
+ return ret;
}
/* node type definition */
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_gradient.c b/source/blender/nodes/shader/nodes/node_shader_tex_gradient.c
index a7f869155fa..0802ecdea1d 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_gradient.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_gradient.c
@@ -29,12 +29,12 @@
/* **************** BLEND ******************** */
-static bNodeSocketTemplate sh_node_tex_gradient_in[]= {
+static bNodeSocketTemplate sh_node_tex_gradient_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_tex_gradient_out[]= {
+static bNodeSocketTemplate sh_node_tex_gradient_out[] = {
{ SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Fac"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_image.c b/source/blender/nodes/shader/nodes/node_shader_tex_image.c
index d6c757222b9..9b17f76bd47 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_image.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_image.c
@@ -27,14 +27,16 @@
#include "../node_shader_util.h"
+#include "IMB_colormanagement.h"
+
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_tex_image_in[]= {
+static bNodeSocketTemplate sh_node_tex_image_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_tex_image_out[]= {
+static bNodeSocketTemplate sh_node_tex_image_out[] = {
{ SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Alpha"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
@@ -59,7 +61,8 @@ static int node_shader_gpu_tex_image(GPUMaterial *mat, bNode *node, GPUNodeStack
Image *ima= (Image*)node->id;
ImageUser *iuser= NULL;
NodeTexImage *tex = node->storage;
- int ncd = tex->color_space == SHD_COLORSPACE_NONE;
+ int isdata = tex->color_space == SHD_COLORSPACE_NONE;
+ int ret;
if (!ima)
return GPU_stack_link(mat, "node_tex_image_empty", in, out);
@@ -69,10 +72,18 @@ static int node_shader_gpu_tex_image(GPUMaterial *mat, bNode *node, GPUNodeStack
node_shader_gpu_tex_mapping(mat, node, in, out);
- if (out[0].link && GPU_material_do_color_management(mat))
- GPU_link(mat, "srgb_to_linearrgb", out[0].link, &out[0].link);
+ ret = GPU_stack_link(mat, "node_tex_image", in, out, GPU_image(ima, iuser, isdata));
+
+ if (ret) {
+ ImBuf *ibuf = BKE_image_get_ibuf(ima, iuser);
+ if (ibuf && (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA) == 0 &&
+ GPU_material_do_color_management(mat))
+ {
+ GPU_link(mat, "srgb_to_linearrgb", out[0].link, &out[0].link);
+ }
+ }
- return GPU_stack_link(mat, "node_tex_image", in, out, GPU_image(ima, iuser, ncd));
+ return ret;
}
/* node type definition */
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_magic.c b/source/blender/nodes/shader/nodes/node_shader_tex_magic.c
index b9f1b5c1d21..86feabbcc2b 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_magic.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_magic.c
@@ -29,14 +29,14 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_tex_magic_in[]= {
+static bNodeSocketTemplate sh_node_tex_magic_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ SOCK_FLOAT, 1, N_("Scale"), 5.0f, 0.0f, 0.0f, 0.0f, -1000.0f, 1000.0f},
{ SOCK_FLOAT, 1, N_("Distortion"), 1.0f, 0.0f, 0.0f, 0.0f, -1000.0f, 1000.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_tex_magic_out[]= {
+static bNodeSocketTemplate sh_node_tex_magic_out[] = {
{ SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Fac"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_musgrave.c b/source/blender/nodes/shader/nodes/node_shader_tex_musgrave.c
index 60b4f65f0b4..cd4b5743e14 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_musgrave.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_musgrave.c
@@ -29,7 +29,7 @@
/* **************** MUSGRAVE ******************** */
-static bNodeSocketTemplate sh_node_tex_musgrave_in[]= {
+static bNodeSocketTemplate sh_node_tex_musgrave_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ SOCK_FLOAT, 1, N_("Scale"), 5.0f, 0.0f, 0.0f, 0.0f, -1000.0f, 1000.0f},
{ SOCK_FLOAT, 1, N_("Detail"), 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 16.0f},
@@ -40,7 +40,7 @@ static bNodeSocketTemplate sh_node_tex_musgrave_in[]= {
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_tex_musgrave_out[]= {
+static bNodeSocketTemplate sh_node_tex_musgrave_out[] = {
{ SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Fac"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_noise.c b/source/blender/nodes/shader/nodes/node_shader_tex_noise.c
index bd049300048..18788f9e72c 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_noise.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_noise.c
@@ -29,7 +29,7 @@
/* **************** NOISE ******************** */
-static bNodeSocketTemplate sh_node_tex_noise_in[]= {
+static bNodeSocketTemplate sh_node_tex_noise_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ SOCK_FLOAT, 1, N_("Scale"), 5.0f, 0.0f, 0.0f, 0.0f, -1000.0f, 1000.0f},
{ SOCK_FLOAT, 1, N_("Detail"), 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 16.0f},
@@ -37,7 +37,7 @@ static bNodeSocketTemplate sh_node_tex_noise_in[]= {
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_tex_noise_out[]= {
+static bNodeSocketTemplate sh_node_tex_noise_out[] = {
{ SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Fac"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_sky.c b/source/blender/nodes/shader/nodes/node_shader_tex_sky.c
index 977d689ace6..7a1b853a7f4 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_sky.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_sky.c
@@ -29,12 +29,12 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_tex_sky_in[]= {
+static bNodeSocketTemplate sh_node_tex_sky_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_tex_sky_out[]= {
+static bNodeSocketTemplate sh_node_tex_sky_out[] = {
{ SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_voronoi.c b/source/blender/nodes/shader/nodes/node_shader_tex_voronoi.c
index 22baa3853ac..d4cc24687b3 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_voronoi.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_voronoi.c
@@ -29,13 +29,13 @@
/* **************** VORONOI ******************** */
-static bNodeSocketTemplate sh_node_tex_voronoi_in[]= {
+static bNodeSocketTemplate sh_node_tex_voronoi_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ SOCK_FLOAT, 1, N_("Scale"), 5.0f, 0.0f, 0.0f, 0.0f, -1000.0f, 1000.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_tex_voronoi_out[]= {
+static bNodeSocketTemplate sh_node_tex_voronoi_out[] = {
{ SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Fac"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_wave.c b/source/blender/nodes/shader/nodes/node_shader_tex_wave.c
index 8a099521ee9..8b23de0310c 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_wave.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_wave.c
@@ -29,7 +29,7 @@
/* **************** WAVE ******************** */
-static bNodeSocketTemplate sh_node_tex_wave_in[]= {
+static bNodeSocketTemplate sh_node_tex_wave_in[] = {
{ SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ SOCK_FLOAT, 1, N_("Scale"), 5.0f, 0.0f, 0.0f, 0.0f, -1000.0f, 1000.0f},
{ SOCK_FLOAT, 1, N_("Distortion"), 0.0f, 0.0f, 0.0f, 0.0f, -1000.0f, 1000.0f},
@@ -38,7 +38,7 @@ static bNodeSocketTemplate sh_node_tex_wave_in[]= {
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_tex_wave_out[]= {
+static bNodeSocketTemplate sh_node_tex_wave_out[] = {
{ SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 0, N_("Fac"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
diff --git a/source/blender/nodes/shader/nodes/node_shader_texture.c b/source/blender/nodes/shader/nodes/node_shader_texture.c
index 73c3b846fe3..6d1b3ff6dba 100644
--- a/source/blender/nodes/shader/nodes/node_shader_texture.c
+++ b/source/blender/nodes/shader/nodes/node_shader_texture.c
@@ -32,14 +32,16 @@
#include "DNA_texture_types.h"
+#include "IMB_colormanagement.h"
+
#include "node_shader_util.h"
/* **************** TEXTURE ******************** */
-static bNodeSocketTemplate sh_node_texture_in[]= {
+static bNodeSocketTemplate sh_node_texture_in[] = {
{ SOCK_VECTOR, 1, "Vector", 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE}, /* no limit */
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_texture_out[]= {
+static bNodeSocketTemplate sh_node_texture_out[] = {
{ SOCK_FLOAT, 0, N_("Value")},
{ SOCK_RGBA, 0, N_("Color")},
{ SOCK_VECTOR, 0, N_("Normal")},
@@ -52,7 +54,7 @@ static void node_shader_exec_texture(void *data, bNode *node, bNodeStack **in, b
ShadeInput *shi= ((ShaderCallData *)data)->shi;
TexResult texres;
bNodeSocket *sock_vector= node->inputs.first;
- float vec[3], nor[3]={0.0f, 0.0f, 0.0f};
+ float vec[3], nor[3] = {0.0f, 0.0f, 0.0f};
int retval;
short which_output = node->custom1;
@@ -76,8 +78,8 @@ static void node_shader_exec_texture(void *data, bNode *node, bNodeStack **in, b
float *fp= in[0]->data;
float dxt[3], dyt[3];
- dxt[0]= fp[0]; dxt[1]= dxt[2]= 0.0f;
- dyt[0]= fp[1]; dyt[1]= dyt[2]= 0.0f;
+ dxt[0] = fp[0]; dxt[1] = dxt[2] = 0.0f;
+ dyt[0] = fp[1]; dyt[1] = dyt[2] = 0.0f;
retval= multitex_nodes((Tex *)node->id, vec, dxt, dyt, shi->osatex, &texres, thread, which_output, NULL, NULL);
}
else
@@ -96,9 +98,9 @@ static void node_shader_exec_texture(void *data, bNode *node, bNodeStack **in, b
/* intensity and color need some handling */
if (texres.talpha)
- out[0]->vec[0]= texres.ta;
+ out[0]->vec[0] = texres.ta;
else
- out[0]->vec[0]= texres.tin;
+ out[0]->vec[0] = texres.tin;
if ((retval & TEX_RGB) == 0) {
copy_v3_fl(out[1]->vec, out[0]->vec[0]);
@@ -122,8 +124,19 @@ static int gpu_shader_texture(GPUMaterial *mat, bNode *node, GPUNodeStack *in, G
Tex *tex = (Tex*)node->id;
if (tex && tex->type == TEX_IMAGE && tex->ima) {
- GPUNodeLink *texlink = GPU_image(tex->ima, NULL, FALSE);
- return GPU_stack_link(mat, "texture_image", in, out, texlink);
+ GPUNodeLink *texlink = GPU_image(tex->ima, &tex->iuser, FALSE);
+ int ret = GPU_stack_link(mat, "texture_image", in, out, texlink);
+
+ if (ret) {
+ ImBuf *ibuf = BKE_image_get_ibuf(tex->ima, &tex->iuser);
+ if (ibuf && (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA) ==0 &&
+ GPU_material_do_color_management(mat))
+ {
+ GPU_link(mat, "srgb_to_linearrgb", out[1].link, &out[1].link);
+ }
+ }
+
+ return ret;
}
else
return 0;
diff --git a/source/blender/nodes/shader/nodes/node_shader_valToRgb.c b/source/blender/nodes/shader/nodes/node_shader_valToRgb.c
index d3094200f83..182487d343e 100644
--- a/source/blender/nodes/shader/nodes/node_shader_valToRgb.c
+++ b/source/blender/nodes/shader/nodes/node_shader_valToRgb.c
@@ -33,11 +33,11 @@
#include "node_shader_util.h"
/* **************** VALTORGB ******************** */
-static bNodeSocketTemplate sh_node_valtorgb_in[]= {
+static bNodeSocketTemplate sh_node_valtorgb_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_valtorgb_out[]= {
+static bNodeSocketTemplate sh_node_valtorgb_out[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ SOCK_FLOAT, 0, N_("Alpha")},
{ -1, 0, "" }
@@ -53,7 +53,7 @@ static void node_shader_exec_valtorgb(void *UNUSED(data), bNode *node, bNodeStac
nodestack_get_vec(&fac, SOCK_FLOAT, in[0]);
do_colorband(node->storage, fac, out[0]->vec);
- out[1]->vec[0]= out[0]->vec[3];
+ out[1]->vec[0] = out[0]->vec[3];
}
}
@@ -89,11 +89,11 @@ void register_node_type_sh_valtorgb(bNodeTreeType *ttype)
/* **************** RGBTOBW ******************** */
-static bNodeSocketTemplate sh_node_rgbtobw_in[]= {
+static bNodeSocketTemplate sh_node_rgbtobw_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_rgbtobw_out[]= {
+static bNodeSocketTemplate sh_node_rgbtobw_out[] = {
{ SOCK_FLOAT, 0, N_("Val"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_value.c b/source/blender/nodes/shader/nodes/node_shader_value.c
index 8a6c3c87e0d..a3d1e5afec2 100644
--- a/source/blender/nodes/shader/nodes/node_shader_value.c
+++ b/source/blender/nodes/shader/nodes/node_shader_value.c
@@ -33,7 +33,7 @@
#include "node_shader_util.h"
/* **************** VALUE ******************** */
-static bNodeSocketTemplate sh_node_value_out[]= {
+static bNodeSocketTemplate sh_node_value_out[] = {
/* XXX value nodes use the output sockets for buttons, so we need explicit limits here! */
{ SOCK_FLOAT, 0, N_("Value"), 0.0f, 0.0f, 0.0f, 0.0f, -FLT_MAX, FLT_MAX},
{ -1, 0, "" }
@@ -54,7 +54,7 @@ static void node_shader_exec_value(void *UNUSED(data), bNode *node, bNodeStack *
bNodeSocket *sock= node->outputs.first;
float val= ((bNodeSocketValueFloat*)sock->default_value)->value;
- out[0]->vec[0]= val;
+ out[0]->vec[0] = val;
}
static int gpu_shader_value(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
diff --git a/source/blender/nodes/shader/nodes/node_shader_vectMath.c b/source/blender/nodes/shader/nodes/node_shader_vectMath.c
index 007366c6082..2d9f1903c5b 100644
--- a/source/blender/nodes/shader/nodes/node_shader_vectMath.c
+++ b/source/blender/nodes/shader/nodes/node_shader_vectMath.c
@@ -35,16 +35,16 @@
/* **************** VECTOR MATH ******************** */
-static bNodeSocketTemplate sh_node_vect_math_in[]= {
- { SOCK_VECTOR, 1, N_("Vector"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
- { SOCK_VECTOR, 1, N_("Vector"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
- { -1, 0, "" }
+static bNodeSocketTemplate sh_node_vect_math_in[] = {
+ { SOCK_VECTOR, 1, N_("Vector"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
+ { SOCK_VECTOR, 1, N_("Vector"), 0.5f, 0.5f, 0.5f, 1.0f, -10000.0f, 10000.0f, PROP_NONE},
+ { -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_vect_math_out[]= {
- { SOCK_VECTOR, 0, N_("Vector")},
+static bNodeSocketTemplate sh_node_vect_math_out[] = {
+ { SOCK_VECTOR, 0, N_("Vector")},
{ SOCK_FLOAT, 0, N_("Value")},
- { -1, 0, "" }
+ { -1, 0, "" }
};
static void node_shader_exec_vect_math(void *UNUSED(data), bNode *node, bNodeStack **in, bNodeStack **out)
@@ -55,46 +55,46 @@ static void node_shader_exec_vect_math(void *UNUSED(data), bNode *node, bNodeSta
nodestack_get_vec(vec2, SOCK_VECTOR, in[1]);
if (node->custom1 == 0) { /* Add */
- out[0]->vec[0]= vec1[0] + vec2[0];
- out[0]->vec[1]= vec1[1] + vec2[1];
- out[0]->vec[2]= vec1[2] + vec2[2];
+ out[0]->vec[0] = vec1[0] + vec2[0];
+ out[0]->vec[1] = vec1[1] + vec2[1];
+ out[0]->vec[2] = vec1[2] + vec2[2];
- out[1]->vec[0]= (fabs(out[0]->vec[0]) + fabs(out[0]->vec[0]) + fabs(out[0]->vec[0])) / 3;
+ out[1]->vec[0] = (fabs(out[0]->vec[0]) + fabs(out[0]->vec[0]) + fabs(out[0]->vec[0])) / 3;
}
else if (node->custom1 == 1) { /* Subtract */
- out[0]->vec[0]= vec1[0] - vec2[0];
- out[0]->vec[1]= vec1[1] - vec2[1];
- out[0]->vec[2]= vec1[2] - vec2[2];
+ out[0]->vec[0] = vec1[0] - vec2[0];
+ out[0]->vec[1] = vec1[1] - vec2[1];
+ out[0]->vec[2] = vec1[2] - vec2[2];
- out[1]->vec[0]= (fabs(out[0]->vec[0]) + fabs(out[0]->vec[0]) + fabs(out[0]->vec[0])) / 3;
+ out[1]->vec[0] = (fabs(out[0]->vec[0]) + fabs(out[0]->vec[0]) + fabs(out[0]->vec[0])) / 3;
}
else if (node->custom1 == 2) { /* Average */
- out[0]->vec[0]= vec1[0] + vec2[0];
- out[0]->vec[1]= vec1[1] + vec2[1];
- out[0]->vec[2]= vec1[2] + vec2[2];
+ out[0]->vec[0] = vec1[0] + vec2[0];
+ out[0]->vec[1] = vec1[1] + vec2[1];
+ out[0]->vec[2] = vec1[2] + vec2[2];
out[1]->vec[0] = normalize_v3(out[0]->vec );
}
else if (node->custom1 == 3) { /* Dot product */
- out[1]->vec[0]= (vec1[0] * vec2[0]) + (vec1[1] * vec2[1]) + (vec1[2] * vec2[2]);
+ out[1]->vec[0] = (vec1[0] * vec2[0]) + (vec1[1] * vec2[1]) + (vec1[2] * vec2[2]);
}
else if (node->custom1 == 4) { /* Cross product */
- out[0]->vec[0]= (vec1[1] * vec2[2]) - (vec1[2] * vec2[1]);
- out[0]->vec[1]= (vec1[2] * vec2[0]) - (vec1[0] * vec2[2]);
- out[0]->vec[2]= (vec1[0] * vec2[1]) - (vec1[1] * vec2[0]);
+ out[0]->vec[0] = (vec1[1] * vec2[2]) - (vec1[2] * vec2[1]);
+ out[0]->vec[1] = (vec1[2] * vec2[0]) - (vec1[0] * vec2[2]);
+ out[0]->vec[2] = (vec1[0] * vec2[1]) - (vec1[1] * vec2[0]);
out[1]->vec[0] = normalize_v3(out[0]->vec );
}
else if (node->custom1 == 5) { /* Normalize */
if (in[0]->hasinput || !in[1]->hasinput) { /* This one only takes one input, so we've got to choose. */
- out[0]->vec[0]= vec1[0];
- out[0]->vec[1]= vec1[1];
- out[0]->vec[2]= vec1[2];
+ out[0]->vec[0] = vec1[0];
+ out[0]->vec[1] = vec1[1];
+ out[0]->vec[2] = vec1[2];
}
else {
- out[0]->vec[0]= vec2[0];
- out[0]->vec[1]= vec2[1];
- out[0]->vec[2]= vec2[2];
+ out[0]->vec[0] = vec2[0];
+ out[0]->vec[1] = vec2[1];
+ out[0]->vec[2] = vec2[2];
}
out[1]->vec[0] = normalize_v3(out[0]->vec );
diff --git a/source/blender/nodes/shader/nodes/node_shader_volume_isotropic.c b/source/blender/nodes/shader/nodes/node_shader_volume_isotropic.c
index 366f50ab4fc..5451eb303cc 100644
--- a/source/blender/nodes/shader/nodes/node_shader_volume_isotropic.c
+++ b/source/blender/nodes/shader/nodes/node_shader_volume_isotropic.c
@@ -29,13 +29,13 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_volume_isotropic_in[]= {
+static bNodeSocketTemplate sh_node_volume_isotropic_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Density"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_volume_isotropic_out[]= {
+static bNodeSocketTemplate sh_node_volume_isotropic_out[] = {
{ SOCK_SHADER, 0, N_("Volume")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_volume_transparent.c b/source/blender/nodes/shader/nodes/node_shader_volume_transparent.c
index 9d48f613d34..ad7d7fceda3 100644
--- a/source/blender/nodes/shader/nodes/node_shader_volume_transparent.c
+++ b/source/blender/nodes/shader/nodes/node_shader_volume_transparent.c
@@ -29,13 +29,13 @@
/* **************** OUTPUT ******************** */
-static bNodeSocketTemplate sh_node_volume_transparent_in[]= {
+static bNodeSocketTemplate sh_node_volume_transparent_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Density"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate sh_node_volume_transparent_out[]= {
+static bNodeSocketTemplate sh_node_volume_transparent_out[] = {
{ SOCK_SHADER, 0, N_("Volume")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/texture/node_texture_tree.c b/source/blender/nodes/texture/node_texture_tree.c
index 9656d93f1b0..ba94531c259 100644
--- a/source/blender/nodes/texture/node_texture_tree.c
+++ b/source/blender/nodes/texture/node_texture_tree.c
@@ -4,7 +4,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -134,7 +134,7 @@ bNodeTreeType ntreeType_Texture = {
/* update */ update,
/* update_node */ NULL,
/* validate_link */ NULL,
- /* internal_connect */ node_internal_connect_default
+ /* update_internal_links */ node_update_internal_links_default
};
int ntreeTexTagAnimated(bNodeTree *ntree)
@@ -240,19 +240,19 @@ void ntreeTexEndExecTree(bNodeTreeExec *exec, int use_tree_data)
}
int ntreeTexExecTree(
- bNodeTree *nodes,
- TexResult *texres,
- float *co,
- float *dxt, float *dyt,
- int osatex,
- short thread,
- Tex *UNUSED(tex),
- short which_output,
- int cfra,
- int preview,
- ShadeInput *shi,
- MTex *mtex
-) {
+ bNodeTree *nodes,
+ TexResult *texres,
+ float co[3],
+ float dxt[3], float dyt[3],
+ int osatex,
+ const short thread,
+ Tex *UNUSED(tex),
+ short which_output,
+ int cfra,
+ int preview,
+ ShadeInput *shi,
+ MTex *mtex)
+{
TexCallData data;
float *nor = texres->nor;
int retval = TEX_INT;
diff --git a/source/blender/nodes/texture/node_texture_util.c b/source/blender/nodes/texture/node_texture_util.c
index 53f1aa82f60..06473d800d0 100644
--- a/source/blender/nodes/texture/node_texture_util.c
+++ b/source/blender/nodes/texture/node_texture_util.c
@@ -4,7 +4,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -29,7 +29,7 @@
* \ingroup nodes
*/
-
+
/*
* HOW TEXTURE NODES WORK
*
@@ -49,8 +49,6 @@
#include <assert.h>
#include "node_texture_util.h"
-#define PREV_RES 128 /* default preview resolution */
-
static void tex_call_delegate(TexDelegate *dg, float *out, TexParams *params, short thread)
{
if (dg->node->need_exec) {
@@ -114,13 +112,13 @@ void params_from_cdata(TexParams *out, TexCallData *in)
out->mtex = in->mtex;
}
-void tex_do_preview(bNode *node, float *co, float *col)
+void tex_do_preview(bNode *node, const float coord[2], const float col[4])
{
- bNodePreview *preview= node->preview;
+ bNodePreview *preview = node->preview;
if (preview) {
- int xs= ((co[0] + 1.0f)*0.5f)*preview->xsize;
- int ys= ((co[1] + 1.0f)*0.5f)*preview->ysize;
+ int xs = ((coord[0] + 1.0f) * 0.5f) * preview->xsize;
+ int ys = ((coord[1] + 1.0f) * 0.5f) * preview->ysize;
nodeAddToPreview(node, col, xs, ys, 0); /* 0 = no color management */
}
@@ -134,19 +132,19 @@ void tex_output(bNode *node, bNodeStack **in, bNodeStack *out, TexFn texfn, TexC
dg = out->data = MEM_mallocN(sizeof(TexDelegate), "tex delegate");
else
dg = out->data;
-
- dg->cdata= cdata;
+
+ dg->cdata = cdata;
dg->fn = texfn;
dg->node = node;
- memcpy(dg->in, in, MAX_SOCKET * sizeof(bNodeStack*));
+ memcpy(dg->in, in, MAX_SOCKET * sizeof(bNodeStack *));
dg->type = out->sockettype;
}
void ntreeTexCheckCyclics(struct bNodeTree *ntree)
{
bNode *node;
- for (node= ntree->nodes.first; node; node= node->next) {
-
+ for (node = ntree->nodes.first; node; node = node->next) {
+
if (node->type == TEX_NODE_TEXTURE && node->id) {
/* custom2 stops the node from rendering */
if (node->custom1) {
diff --git a/source/blender/nodes/texture/node_texture_util.h b/source/blender/nodes/texture/node_texture_util.h
index e938e6fc419..16dbc2f7bfb 100644
--- a/source/blender/nodes/texture/node_texture_util.h
+++ b/source/blender/nodes/texture/node_texture_util.h
@@ -79,8 +79,10 @@
typedef struct TexCallData {
TexResult *target;
+ /* all float[3] */
float *co;
float *dxt, *dyt;
+
int osatex;
char do_preview;
short thread;
@@ -94,7 +96,7 @@ typedef struct TexCallData {
typedef struct TexParams {
float *co;
float *dxt, *dyt;
- float *previewco;
+ const float *previewco;
int cfra;
int osatex;
@@ -119,7 +121,7 @@ void tex_input_vec(float *out, bNodeStack *in, TexParams *params, short thread);
float tex_input_value(bNodeStack *in, TexParams *params, short thread);
void tex_output(bNode *node, bNodeStack **in, bNodeStack *out, TexFn texfn, TexCallData *data);
-void tex_do_preview(bNode *node, float *coord, float *col);
+void tex_do_preview(bNode *node, const float coord[2], const float col[4]);
void params_from_cdata(TexParams *out, TexCallData *in);
diff --git a/source/blender/nodes/texture/nodes/node_texture_at.c b/source/blender/nodes/texture/nodes/node_texture_at.c
index 9e557705b3f..4c2d276b902 100644
--- a/source/blender/nodes/texture/nodes/node_texture_at.c
+++ b/source/blender/nodes/texture/nodes/node_texture_at.c
@@ -33,12 +33,12 @@
#include "node_texture_util.h"
#include "NOD_texture.h"
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_RGBA, 1, N_("Texture"), 0.0f, 0.0f, 0.0f, 1.0f },
{ SOCK_VECTOR, 1, N_("Coordinates"), 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, PROP_NONE },
{ -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
+static bNodeSocketTemplate outputs[] = {
{ SOCK_RGBA, 0, N_("Texture") },
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/texture/nodes/node_texture_bricks.c b/source/blender/nodes/texture/nodes/node_texture_bricks.c
index f6259962529..b4f81f08e43 100644
--- a/source/blender/nodes/texture/nodes/node_texture_bricks.c
+++ b/source/blender/nodes/texture/nodes/node_texture_bricks.c
@@ -35,7 +35,7 @@
#include <math.h>
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_RGBA, 1, N_("Bricks 1"), 0.596f, 0.282f, 0.0f, 1.0f },
{ SOCK_RGBA, 1, N_("Bricks 2"), 0.632f, 0.504f, 0.05f, 1.0f },
{ SOCK_RGBA, 1, N_("Mortar"), 0.0f, 0.0f, 0.0f, 1.0f },
@@ -45,7 +45,7 @@ static bNodeSocketTemplate inputs[]= {
{ SOCK_FLOAT, 1, N_("Row Height"), 0.25f, 0.0f, 0.0f, 0.0f, 0.001f, 99.0f, PROP_UNSIGNED },
{ -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
+static bNodeSocketTemplate outputs[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ -1, 0, "" }
};
@@ -66,7 +66,7 @@ static float noise(int n) /* fast integer noise */
static void colorfn(float *out, TexParams *p, bNode *node, bNodeStack **in, short thread)
{
- float *co = p->co;
+ const float *co = p->co;
float x = co[0];
float y = co[1];
diff --git a/source/blender/nodes/texture/nodes/node_texture_checker.c b/source/blender/nodes/texture/nodes/node_texture_checker.c
index cd9c3170cf7..1f653d1f7b9 100644
--- a/source/blender/nodes/texture/nodes/node_texture_checker.c
+++ b/source/blender/nodes/texture/nodes/node_texture_checker.c
@@ -34,13 +34,13 @@
#include "NOD_texture.h"
#include <math.h>
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_RGBA, 1, N_("Color1"), 1.0f, 0.0f, 0.0f, 1.0f },
{ SOCK_RGBA, 1, N_("Color2"), 1.0f, 1.0f, 1.0f, 1.0f },
{ SOCK_FLOAT, 1, N_("Size"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 100.0f, PROP_UNSIGNED },
{ -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
+static bNodeSocketTemplate outputs[] = {
{ SOCK_RGBA, 0, N_("Color") },
{ -1, 0, "" }
};
@@ -62,7 +62,7 @@ static void colorfn(float *out, TexParams *p, bNode *UNUSED(node), bNodeStack **
}
else {
tex_input_rgba(out, in[1], p, thread);
- }
+ }
}
static void exec(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
diff --git a/source/blender/nodes/texture/nodes/node_texture_common.c b/source/blender/nodes/texture/nodes/node_texture_common.c
index 1eaf9b2b0fe..41bfd0ae00a 100644
--- a/source/blender/nodes/texture/nodes/node_texture_common.c
+++ b/source/blender/nodes/texture/nodes/node_texture_common.c
@@ -148,128 +148,3 @@ void register_node_type_tex_group(bNodeTreeType *ttype)
nodeRegisterType(ttype, &ntype);
}
-
-
-/**** FOR LOOP ****/
-
-#if 0 /* XXX loop nodes don't work nicely with current trees */
-static void forloop_execute(void *data, int thread, struct bNode *node, void *nodedata, struct bNodeStack **in, struct bNodeStack **out)
-{
- bNodeTreeExec *exec= (bNodeTreeExec*)nodedata;
- bNodeThreadStack *nts;
- int iterations= (int)in[0]->vec[0];
- bNodeSocket *sock;
- bNodeStack *ns;
- int iteration;
-
- /* XXX same behavior as trunk: all nodes inside group are executed.
- * it's stupid, but just makes it work. compo redesign will do this better.
- */
- {
- bNode *inode;
- for (inode=exec->nodetree->nodes.first; inode; inode=inode->next)
- inode->need_exec = 1;
- }
-
- nts = ntreeGetThreadStack(exec, thread);
-
- /* "Iteration" socket */
- sock = exec->nodetree->inputs.first;
- ns = node_get_socket_stack(nts->stack, sock);
-
-// group_copy_inputs(node, in, nts->stack);
- for (iteration=0; iteration < iterations; ++iteration) {
- /* first input contains current iteration counter */
- ns->vec[0] = (float)iteration;
- ns->vec[1]=ns->vec[2]=ns->vec[3] = 0.0f;
-
-// if (iteration > 0)
-// loop_init_iteration(exec->nodetree, nts->stack);
-// ntreeExecThreadNodes(exec, nts, data, thread);
- }
-// loop_copy_outputs(node, in, out, exec->stack);
-
- ntreeReleaseThreadStack(nts);
-}
-
-void register_node_type_tex_forloop(bNodeTreeType *ttype)
-{
- static bNodeType ntype;
-
- node_type_base(ttype, &ntype, NODE_FORLOOP, "For", NODE_CLASS_GROUP, NODE_OPTIONS);
- node_type_socket_templates(&ntype, NULL, NULL);
- node_type_size(&ntype, 120, 60, 200);
- node_type_label(&ntype, node_group_label);
- node_type_init(&ntype, node_forloop_init);
- node_type_valid(&ntype, node_group_valid);
- node_type_template(&ntype, node_forloop_template);
- node_type_update(&ntype, NULL, node_group_verify);
- node_type_tree(&ntype, node_forloop_init_tree, node_loop_update_tree);
- node_type_group_edit(&ntype, node_group_edit_get, node_group_edit_set, node_group_edit_clear);
- node_type_exec_new(&ntype, group_initexec, group_freeexec, forloop_execute);
-
- nodeRegisterType(ttype, &ntype);
-}
-#endif
-
-/**** WHILE LOOP ****/
-
-#if 0 /* XXX loop nodes don't work nicely with current trees */
-static void whileloop_execute(void *data, int thread, struct bNode *node, void *nodedata, struct bNodeStack **in, struct bNodeStack **out)
-{
- bNodeTreeExec *exec= (bNodeTreeExec*)nodedata;
- bNodeThreadStack *nts;
- int condition= (in[0]->vec[0] > 0.0f);
- bNodeSocket *sock;
- bNodeStack *ns;
- int iteration;
-
- /* XXX same behavior as trunk: all nodes inside group are executed.
- * it's stupid, but just makes it work. compo redesign will do this better.
- */
- {
- bNode *inode;
- for (inode=exec->nodetree->nodes.first; inode; inode=inode->next)
- inode->need_exec = 1;
- }
-
- nts = ntreeGetThreadStack(exec, thread);
-
- /* "Condition" socket */
- sock = exec->nodetree->outputs.first;
- ns = node_get_socket_stack(nts->stack, sock);
-
- iteration = 0;
-// group_copy_inputs(node, in, nts->stack);
- while (condition && iteration < node->custom1) {
-// if (iteration > 0)
-// loop_init_iteration(exec->nodetree, nts->stack);
-// ntreeExecThreadNodes(exec, nts, data, thread);
-
- condition = (ns->vec[0] > 0.0f);
- ++iteration;
- }
-// loop_copy_outputs(node, in, out, exec->stack);
-
- ntreeReleaseThreadStack(nts);
-}
-
-void register_node_type_tex_whileloop(bNodeTreeType *ttype)
-{
- static bNodeType ntype;
-
- node_type_base(ttype, &ntype, NODE_WHILELOOP, "While", NODE_CLASS_GROUP, NODE_OPTIONS);
- node_type_socket_templates(&ntype, NULL, NULL);
- node_type_size(&ntype, 120, 60, 200);
- node_type_label(&ntype, node_group_label);
- node_type_init(&ntype, node_whileloop_init);
- node_type_valid(&ntype, node_group_valid);
- node_type_template(&ntype, node_whileloop_template);
- node_type_update(&ntype, NULL, node_group_verify);
- node_type_tree(&ntype, node_whileloop_init_tree, node_loop_update_tree);
- node_type_group_edit(&ntype, node_group_edit_get, node_group_edit_set, node_group_edit_clear);
- node_type_exec_new(&ntype, group_initexec, group_freeexec, whileloop_execute);
-
- nodeRegisterType(ttype, &ntype);
-}
-#endif
diff --git a/source/blender/nodes/texture/nodes/node_texture_compose.c b/source/blender/nodes/texture/nodes/node_texture_compose.c
index 77521190590..25da4f19e52 100644
--- a/source/blender/nodes/texture/nodes/node_texture_compose.c
+++ b/source/blender/nodes/texture/nodes/node_texture_compose.c
@@ -33,14 +33,14 @@
#include "node_texture_util.h"
#include "NOD_texture.h"
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_FLOAT, 1, N_("Red"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_UNSIGNED },
{ SOCK_FLOAT, 1, N_("Green"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_UNSIGNED },
{ SOCK_FLOAT, 1, N_("Blue"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_UNSIGNED },
{ SOCK_FLOAT, 1, N_("Alpha"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_UNSIGNED },
{ -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
+static bNodeSocketTemplate outputs[] = {
{ SOCK_RGBA, 0, N_("Color") },
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/texture/nodes/node_texture_coord.c b/source/blender/nodes/texture/nodes/node_texture_coord.c
index 2add5c820eb..971520ebc38 100644
--- a/source/blender/nodes/texture/nodes/node_texture_coord.c
+++ b/source/blender/nodes/texture/nodes/node_texture_coord.c
@@ -33,7 +33,7 @@
#include "node_texture_util.h"
#include "NOD_texture.h"
-static bNodeSocketTemplate outputs[]= {
+static bNodeSocketTemplate outputs[] = {
{ SOCK_VECTOR, 0, N_("Coordinates") },
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/texture/nodes/node_texture_curves.c b/source/blender/nodes/texture/nodes/node_texture_curves.c
index 6ccb5e1e83f..5980f938938 100644
--- a/source/blender/nodes/texture/nodes/node_texture_curves.c
+++ b/source/blender/nodes/texture/nodes/node_texture_curves.c
@@ -36,7 +36,7 @@
/* **************** CURVE Time ******************** */
/* custom1 = sfra, custom2 = efra */
-static bNodeSocketTemplate time_outputs[]= {
+static bNodeSocketTemplate time_outputs[] = {
{ SOCK_FLOAT, 0, N_("Value") },
{ -1, 0, "" }
};
@@ -83,12 +83,12 @@ void register_node_type_tex_curve_time(bNodeTreeType *ttype)
}
/* **************** CURVE RGB ******************** */
-static bNodeSocketTemplate rgb_inputs[]= {
+static bNodeSocketTemplate rgb_inputs[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate rgb_outputs[]= {
+static bNodeSocketTemplate rgb_outputs[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/texture/nodes/node_texture_decompose.c b/source/blender/nodes/texture/nodes/node_texture_decompose.c
index eae34e2ce47..a2875c31d9e 100644
--- a/source/blender/nodes/texture/nodes/node_texture_decompose.c
+++ b/source/blender/nodes/texture/nodes/node_texture_decompose.c
@@ -34,11 +34,11 @@
#include "NOD_texture.h"
#include <math.h>
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f },
{ -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
+static bNodeSocketTemplate outputs[] = {
{ SOCK_FLOAT, 0, N_("Red") },
{ SOCK_FLOAT, 0, N_("Green") },
{ SOCK_FLOAT, 0, N_("Blue") },
diff --git a/source/blender/nodes/texture/nodes/node_texture_distance.c b/source/blender/nodes/texture/nodes/node_texture_distance.c
index 29f08a0ded0..8c3b1555d5d 100644
--- a/source/blender/nodes/texture/nodes/node_texture_distance.c
+++ b/source/blender/nodes/texture/nodes/node_texture_distance.c
@@ -35,13 +35,13 @@
#include "node_texture_util.h"
#include "NOD_texture.h"
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_VECTOR, 1, N_("Coordinate 1"), 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, PROP_NONE },
{ SOCK_VECTOR, 1, N_("Coordinate 2"), 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, PROP_NONE },
- { -1, 0, "" }
+ { -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
+static bNodeSocketTemplate outputs[] = {
{ SOCK_FLOAT, 0, N_("Value") },
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/texture/nodes/node_texture_hueSatVal.c b/source/blender/nodes/texture/nodes/node_texture_hueSatVal.c
index 6863eab9150..b5e9969a830 100644
--- a/source/blender/nodes/texture/nodes/node_texture_hueSatVal.c
+++ b/source/blender/nodes/texture/nodes/node_texture_hueSatVal.c
@@ -34,7 +34,7 @@
#include "NOD_texture.h"
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_FLOAT, 1, N_("Hue"), 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, PROP_NONE },
{ SOCK_FLOAT, 1, N_("Saturation"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, PROP_FACTOR },
{ SOCK_FLOAT, 1, N_("Value"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, PROP_FACTOR },
@@ -42,7 +42,7 @@ static bNodeSocketTemplate inputs[]= {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f },
{ -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
+static bNodeSocketTemplate outputs[] = {
{ SOCK_RGBA, 0, N_("Color") },
{ -1, 0, "" }
};
@@ -56,14 +56,14 @@ static void do_hue_sat_fac(bNode *UNUSED(node), float *out, float hue, float sat
hsv[0]+= (hue - 0.5f);
if (hsv[0]>1.0f) hsv[0]-=1.0f; else if (hsv[0]<0.0f) hsv[0]+= 1.0f;
hsv[1]*= sat;
- if (hsv[1]>1.0f) hsv[1]= 1.0f; else if (hsv[1]<0.0f) hsv[1]= 0.0f;
+ if (hsv[1]>1.0f) hsv[1] = 1.0f; else if (hsv[1]<0.0f) hsv[1] = 0.0f;
hsv[2]*= val;
- if (hsv[2]>1.0f) hsv[2]= 1.0f; else if (hsv[2]<0.0f) hsv[2]= 0.0f;
+ if (hsv[2]>1.0f) hsv[2] = 1.0f; else if (hsv[2]<0.0f) hsv[2] = 0.0f;
hsv_to_rgb(hsv[0], hsv[1], hsv[2], col, col+1, col+2);
- out[0]= mfac*in[0] + fac*col[0];
- out[1]= mfac*in[1] + fac*col[1];
- out[2]= mfac*in[2] + fac*col[2];
+ out[0] = mfac*in[0] + fac*col[0];
+ out[1] = mfac*in[1] + fac*col[1];
+ out[2] = mfac*in[2] + fac*col[2];
}
else {
copy_v4_v4(out, in);
diff --git a/source/blender/nodes/texture/nodes/node_texture_image.c b/source/blender/nodes/texture/nodes/node_texture_image.c
index 7ce91c37295..f3fdaf0bb64 100644
--- a/source/blender/nodes/texture/nodes/node_texture_image.c
+++ b/source/blender/nodes/texture/nodes/node_texture_image.c
@@ -33,7 +33,7 @@
#include "node_texture_util.h"
#include "NOD_texture.h"
-static bNodeSocketTemplate outputs[]= {
+static bNodeSocketTemplate outputs[] = {
{ SOCK_RGBA, 0, N_("Image")},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/texture/nodes/node_texture_invert.c b/source/blender/nodes/texture/nodes/node_texture_invert.c
index 0339c3f0cf2..9c2963d2dc2 100644
--- a/source/blender/nodes/texture/nodes/node_texture_invert.c
+++ b/source/blender/nodes/texture/nodes/node_texture_invert.c
@@ -34,14 +34,14 @@
#include "NOD_texture.h"
/* **************** INVERT ******************** */
-static bNodeSocketTemplate inputs[]= {
- { SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
- { -1, 0, "" }
+static bNodeSocketTemplate inputs[] = {
+ { SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
- { SOCK_RGBA, 0, N_("Color")},
- { -1, 0, "" }
+static bNodeSocketTemplate outputs[] = {
+ { SOCK_RGBA, 0, N_("Color")},
+ { -1, 0, "" }
};
static void colorfn(float *out, TexParams *p, bNode *UNUSED(node), bNodeStack **in, short thread)
diff --git a/source/blender/nodes/texture/nodes/node_texture_math.c b/source/blender/nodes/texture/nodes/node_texture_math.c
index 36e9cac0827..95d70ccc7d6 100644
--- a/source/blender/nodes/texture/nodes/node_texture_math.c
+++ b/source/blender/nodes/texture/nodes/node_texture_math.c
@@ -35,15 +35,15 @@
/* **************** SCALAR MATH ******************** */
-static bNodeSocketTemplate inputs[]= {
- { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -100.0f, 100.0f, PROP_NONE},
- { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -100.0f, 100.0f, PROP_NONE},
- { -1, 0, "" }
+static bNodeSocketTemplate inputs[] = {
+ { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -100.0f, 100.0f, PROP_NONE},
+ { SOCK_FLOAT, 1, N_("Value"), 0.5f, 0.5f, 0.5f, 1.0f, -100.0f, 100.0f, PROP_NONE},
+ { -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
- { SOCK_FLOAT, 0, N_("Value")},
- { -1, 0, "" }
+static bNodeSocketTemplate outputs[] = {
+ { SOCK_FLOAT, 0, N_("Value")},
+ { -1, 0, "" }
};
static void valuefn(float *out, TexParams *p, bNode *node, bNodeStack **in, short thread)
@@ -112,7 +112,7 @@ static void valuefn(float *out, TexParams *p, bNode *node, bNodeStack **in, shor
{
/* Only raise negative numbers by full integers */
if ( in0 >= 0 ) {
- out[0]= pow(in0, in1);
+ out[0] = pow(in0, in1);
}
else {
float y_mod_1 = fmod(in1, 1);
@@ -178,7 +178,7 @@ static void valuefn(float *out, TexParams *p, bNode *node, bNodeStack **in, shor
fprintf(stderr,
"%s:%d: unhandeld value in switch statement: %d\n",
__FILE__, __LINE__, node->custom1);
- }
+ }
}
static void exec(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
diff --git a/source/blender/nodes/texture/nodes/node_texture_mixRgb.c b/source/blender/nodes/texture/nodes/node_texture_mixRgb.c
index bf6cb7a3262..fe04854c734 100644
--- a/source/blender/nodes/texture/nodes/node_texture_mixRgb.c
+++ b/source/blender/nodes/texture/nodes/node_texture_mixRgb.c
@@ -34,13 +34,13 @@
#include "NOD_texture.h"
/* **************** MIX RGB ******************** */
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_FLOAT, 1, N_("Factor"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR },
{ SOCK_RGBA, 1, N_("Color1"), 0.5f, 0.5f, 0.5f, 1.0f },
{ SOCK_RGBA, 1, N_("Color2"), 0.5f, 0.5f, 0.5f, 1.0f },
{ -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
+static bNodeSocketTemplate outputs[] = {
{ SOCK_RGBA, 0, N_("Color") },
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/texture/nodes/node_texture_output.c b/source/blender/nodes/texture/nodes/node_texture_output.c
index ce22bc00a55..2f5efe8c45e 100644
--- a/source/blender/nodes/texture/nodes/node_texture_output.c
+++ b/source/blender/nodes/texture/nodes/node_texture_output.c
@@ -34,7 +34,7 @@
#include "NOD_texture.h"
/* **************** COMPOSITE ******************** */
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, PROP_DIRECTION},
{ -1, 0, "" }
@@ -65,7 +65,7 @@ static void exec(void *data, bNode *node, bNodeStack **in, bNodeStack **UNUSED(o
tex_input_rgba(&target->tr, in[0], &params, cdata->thread);
target->tin = (target->tr + target->tg + target->tb) / 3.0f;
- target->talpha = 1;
+ target->talpha = TRUE;
if (target->nor) {
if (in[1] && in[1]->hasinput)
@@ -170,7 +170,7 @@ void register_node_type_tex_output(bNodeTreeType *ttype)
node_type_exec(&ntype, exec);
/* Do not allow muting output. */
- node_type_internal_connect(&ntype, NULL);
+ node_type_internal_links(&ntype, NULL);
nodeRegisterType(ttype, &ntype);
}
diff --git a/source/blender/nodes/texture/nodes/node_texture_proc.c b/source/blender/nodes/texture/nodes/node_texture_proc.c
index 102f6e1c428..8876d98b9b2 100644
--- a/source/blender/nodes/texture/nodes/node_texture_proc.c
+++ b/source/blender/nodes/texture/nodes/node_texture_proc.c
@@ -40,12 +40,12 @@
*/
-static bNodeSocketTemplate outputs_both[]= {
+static bNodeSocketTemplate outputs_both[] = {
{ SOCK_RGBA, 0, N_("Color"), 1.0f, 0.0f, 0.0f, 1.0f },
{ SOCK_VECTOR, 0, N_("Normal"), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, PROP_DIRECTION },
{ -1, 0, "" }
};
-static bNodeSocketTemplate outputs_color_only[]= {
+static bNodeSocketTemplate outputs_color_only[] = {
{ SOCK_RGBA, 0, N_("Color") },
{ -1, 0, "" }
};
@@ -57,7 +57,7 @@ static bNodeSocketTemplate outputs_color_only[]= {
{ SOCK_RGBA, 1, "Color 2", 1.0f, 1.0f, 1.0f, 1.0f }
/* Calls multitex and copies the result to the outputs. Called by xxx_exec, which handles inputs. */
-static void do_proc(float *result, TexParams *p, float *col1, float *col2, char is_normal, Tex *tex, short thread)
+static void do_proc(float *result, TexParams *p, const float col1[4], const float col2[4], char is_normal, Tex *tex, const short thread)
{
TexResult texres;
int textype;
@@ -69,7 +69,7 @@ static void do_proc(float *result, TexParams *p, float *col1, float *col2, char
texres.nor = NULL;
textype = multitex_nodes(tex, p->co, p->dxt, p->dyt, p->osatex,
- &texres, thread, 0, p->shi, p->mtex);
+ &texres, thread, 0, p->shi, p->mtex);
if (is_normal)
return;
@@ -83,7 +83,7 @@ static void do_proc(float *result, TexParams *p, float *col1, float *col2, char
}
}
-typedef void (*MapFn) (Tex *tex, bNodeStack **in, TexParams *p, short thread);
+typedef void (*MapFn) (Tex *tex, bNodeStack **in, TexParams *p, const short thread);
static void texfn(
float *result,
@@ -138,7 +138,7 @@ static int count_outputs(bNode *node)
/* --- VORONOI -- */
-static bNodeSocketTemplate voronoi_inputs[]= {
+static bNodeSocketTemplate voronoi_inputs[] = {
COMMON_INPUTS,
{ SOCK_FLOAT, 1, N_("W1"), 1.0f, 0.0f, 0.0f, 0.0f, -2.0f, 2.0f, PROP_NONE },
{ SOCK_FLOAT, 1, N_("W2"), 0.0f, 0.0f, 0.0f, 0.0f, -2.0f, 2.0f, PROP_NONE },
@@ -163,7 +163,7 @@ static void voronoi_map_inputs(Tex *tex, bNodeStack **in, TexParams *p, short th
ProcDef(voronoi)
/* --- BLEND -- */
-static bNodeSocketTemplate blend_inputs[]= {
+static bNodeSocketTemplate blend_inputs[] = {
COMMON_INPUTS,
{ -1, 0, "" }
};
@@ -171,7 +171,7 @@ ProcNoInputs(blend)
ProcDef(blend)
/* -- MAGIC -- */
-static bNodeSocketTemplate magic_inputs[]= {
+static bNodeSocketTemplate magic_inputs[] = {
COMMON_INPUTS,
{ SOCK_FLOAT, 1, N_("Turbulence"), 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 200.0f, PROP_UNSIGNED },
{ -1, 0, "" }
@@ -183,7 +183,7 @@ static void magic_map_inputs(Tex *tex, bNodeStack **in, TexParams *p, short thre
ProcDef(magic)
/* --- MARBLE --- */
-static bNodeSocketTemplate marble_inputs[]= {
+static bNodeSocketTemplate marble_inputs[] = {
COMMON_INPUTS,
{ SOCK_FLOAT, 1, N_("Size"), 0.25f, 0.0f, 0.0f, 0.0f, 0.0001f, 2.0f, PROP_UNSIGNED },
{ SOCK_FLOAT, 1, N_("Turbulence"), 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 200.0f, PROP_UNSIGNED },
@@ -197,7 +197,7 @@ static void marble_map_inputs(Tex *tex, bNodeStack **in, TexParams *p, short thr
ProcDef(marble)
/* --- CLOUDS --- */
-static bNodeSocketTemplate clouds_inputs[]= {
+static bNodeSocketTemplate clouds_inputs[] = {
COMMON_INPUTS,
{ SOCK_FLOAT, 1, N_("Size"), 0.25f, 0.0f, 0.0f, 0.0f, 0.0001f, 2.0f, PROP_UNSIGNED },
{ -1, 0, "" }
@@ -209,7 +209,7 @@ static void clouds_map_inputs(Tex *tex, bNodeStack **in, TexParams *p, short thr
ProcDef(clouds)
/* --- DISTORTED NOISE --- */
-static bNodeSocketTemplate distnoise_inputs[]= {
+static bNodeSocketTemplate distnoise_inputs[] = {
COMMON_INPUTS,
{ SOCK_FLOAT, 1, N_("Size"), 0.25f, 0.0f, 0.0f, 0.0f, 0.0001f, 2.0f, PROP_UNSIGNED },
{ SOCK_FLOAT, 1, N_("Distortion"), 1.00f, 0.0f, 0.0f, 0.0f, 0.0000f, 10.0f, PROP_UNSIGNED },
@@ -223,7 +223,7 @@ static void distnoise_map_inputs(Tex *tex, bNodeStack **in, TexParams *p, short
ProcDef(distnoise)
/* --- WOOD --- */
-static bNodeSocketTemplate wood_inputs[]= {
+static bNodeSocketTemplate wood_inputs[] = {
COMMON_INPUTS,
{ SOCK_FLOAT, 1, N_("Size"), 0.25f, 0.0f, 0.0f, 0.0f, 0.0001f, 2.0f, PROP_UNSIGNED },
{ SOCK_FLOAT, 1, N_("Turbulence"), 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 200.0f, PROP_UNSIGNED },
@@ -237,7 +237,7 @@ static void wood_map_inputs(Tex *tex, bNodeStack **in, TexParams *p, short threa
ProcDef(wood)
/* --- MUSGRAVE --- */
-static bNodeSocketTemplate musgrave_inputs[]= {
+static bNodeSocketTemplate musgrave_inputs[] = {
COMMON_INPUTS,
{ SOCK_FLOAT, 1, N_("H"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0001f, 2.0f, PROP_UNSIGNED },
{ SOCK_FLOAT, 1, N_("Lacunarity"), 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 6.0f, PROP_UNSIGNED },
@@ -258,7 +258,7 @@ static void musgrave_map_inputs(Tex *tex, bNodeStack **in, TexParams *p, short t
ProcDef(musgrave)
/* --- NOISE --- */
-static bNodeSocketTemplate noise_inputs[]= {
+static bNodeSocketTemplate noise_inputs[] = {
COMMON_INPUTS,
{ -1, 0, "" }
};
@@ -266,7 +266,7 @@ ProcNoInputs(noise)
ProcDef(noise)
/* --- STUCCI --- */
-static bNodeSocketTemplate stucci_inputs[]= {
+static bNodeSocketTemplate stucci_inputs[] = {
COMMON_INPUTS,
{ SOCK_FLOAT, 1, N_("Size"), 0.25f, 0.0f, 0.0f, 0.0f, 0.0001f, 2.0f, PROP_UNSIGNED },
{ SOCK_FLOAT, 1, N_("Turbulence"), 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 200.0f, PROP_UNSIGNED },
diff --git a/source/blender/nodes/texture/nodes/node_texture_rotate.c b/source/blender/nodes/texture/nodes/node_texture_rotate.c
index a7832c8c180..1b1d57044a3 100644
--- a/source/blender/nodes/texture/nodes/node_texture_rotate.c
+++ b/source/blender/nodes/texture/nodes/node_texture_rotate.c
@@ -35,19 +35,19 @@
#include "node_texture_util.h"
#include "NOD_texture.h"
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Turns"), 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, PROP_NONE },
{ SOCK_VECTOR, 1, N_("Axis"), 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 1.0f, PROP_DIRECTION },
- { -1, 0, "" }
+ { -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
- { SOCK_RGBA, 0, N_("Color")},
- { -1, 0, "" }
+static bNodeSocketTemplate outputs[] = {
+ { SOCK_RGBA, 0, N_("Color")},
+ { -1, 0, "" }
};
-static void rotate(float new_co[3], float a, float ax[3], float co[3])
+static void rotate(float new_co[3], float a, float ax[3], const float co[3])
{
float para[3];
float perp[3];
diff --git a/source/blender/nodes/texture/nodes/node_texture_scale.c b/source/blender/nodes/texture/nodes/node_texture_scale.c
index 130a21ba84d..56562724fb9 100644
--- a/source/blender/nodes/texture/nodes/node_texture_scale.c
+++ b/source/blender/nodes/texture/nodes/node_texture_scale.c
@@ -33,15 +33,15 @@
#include <math.h>
#include "node_texture_util.h"
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f },
{ SOCK_VECTOR, 1, N_("Scale"), 1.0f, 1.0f, 1.0f, 0.0f, -10.0f, 10.0f, PROP_XYZ },
- { -1, 0, "" }
+ { -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
- { SOCK_RGBA, 0, N_("Color")},
- { -1, 0, "" }
+static bNodeSocketTemplate outputs[] = {
+ { SOCK_RGBA, 0, N_("Color")},
+ { -1, 0, "" }
};
static void colorfn(float *out, TexParams *p, bNode *UNUSED(node), bNodeStack **in, short thread)
diff --git a/source/blender/nodes/texture/nodes/node_texture_texture.c b/source/blender/nodes/texture/nodes/node_texture_texture.c
index 4832f19f2c7..cc7367a7632 100644
--- a/source/blender/nodes/texture/nodes/node_texture_texture.c
+++ b/source/blender/nodes/texture/nodes/node_texture_texture.c
@@ -35,13 +35,13 @@
#include "RE_shader_ext.h"
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_RGBA, 1, N_("Color1"), 1.0f, 1.0f, 1.0f, 1.0f },
{ SOCK_RGBA, 1, N_("Color2"), 0.0f, 0.0f, 0.0f, 1.0f },
{ -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
+static bNodeSocketTemplate outputs[] = {
{ SOCK_RGBA, 0, N_("Color") },
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/texture/nodes/node_texture_translate.c b/source/blender/nodes/texture/nodes/node_texture_translate.c
index 85f857ca2be..a95cb00a47d 100644
--- a/source/blender/nodes/texture/nodes/node_texture_translate.c
+++ b/source/blender/nodes/texture/nodes/node_texture_translate.c
@@ -34,15 +34,15 @@
#include "node_texture_util.h"
#include "NOD_texture.h"
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_VECTOR, 1, N_("Offset"), 0.0f, 0.0f, 0.0f, 0.0f, -10000.0f, 10000.0f, PROP_TRANSLATION },
- { -1, 0, "" }
+ { -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
- { SOCK_RGBA, 0, N_("Color")},
- { -1, 0, "" }
+static bNodeSocketTemplate outputs[] = {
+ { SOCK_RGBA, 0, N_("Color")},
+ { -1, 0, "" }
};
static void colorfn(float *out, TexParams *p, bNode *UNUSED(node), bNodeStack **in, short thread)
diff --git a/source/blender/nodes/texture/nodes/node_texture_valToNor.c b/source/blender/nodes/texture/nodes/node_texture_valToNor.c
index 2d107b87578..bbfc1fa616b 100644
--- a/source/blender/nodes/texture/nodes/node_texture_valToNor.c
+++ b/source/blender/nodes/texture/nodes/node_texture_valToNor.c
@@ -33,23 +33,23 @@
#include "node_texture_util.h"
#include "NOD_texture.h"
-static bNodeSocketTemplate inputs[]= {
+static bNodeSocketTemplate inputs[] = {
{ SOCK_FLOAT, 1, N_("Val"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, PROP_NONE },
{ SOCK_FLOAT, 1, N_("Nabla"), 0.025f, 0.0f, 0.0f, 0.0f, 0.001f, 0.1f, PROP_UNSIGNED },
- { -1, 0, "" }
+ { -1, 0, "" }
};
-static bNodeSocketTemplate outputs[]= {
- { SOCK_VECTOR, 0, N_("Normal") },
- { -1, 0, "" }
+static bNodeSocketTemplate outputs[] = {
+ { SOCK_VECTOR, 0, N_("Normal") },
+ { -1, 0, "" }
};
static void normalfn(float *out, TexParams *p, bNode *UNUSED(node), bNodeStack **in, short thread)
{
float new_co[3];
- float *co = p->co;
+ const float *co = p->co;
- float nabla = tex_input_value(in[1], p, thread);
+ float nabla = tex_input_value(in[1], p, thread);
float val;
float nor[3];
diff --git a/source/blender/nodes/texture/nodes/node_texture_valToRgb.c b/source/blender/nodes/texture/nodes/node_texture_valToRgb.c
index 515613509f6..78635453fc1 100644
--- a/source/blender/nodes/texture/nodes/node_texture_valToRgb.c
+++ b/source/blender/nodes/texture/nodes/node_texture_valToRgb.c
@@ -34,11 +34,11 @@
#include "NOD_texture.h"
/* **************** VALTORGB ******************** */
-static bNodeSocketTemplate valtorgb_in[]= {
+static bNodeSocketTemplate valtorgb_in[] = {
{ SOCK_FLOAT, 1, N_("Fac"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ -1, 0, "" }
};
-static bNodeSocketTemplate valtorgb_out[]= {
+static bNodeSocketTemplate valtorgb_out[] = {
{ SOCK_RGBA, 0, N_("Color")},
{ -1, 0, "" }
};
@@ -77,11 +77,11 @@ void register_node_type_tex_valtorgb(bNodeTreeType *ttype)
}
/* **************** RGBTOBW ******************** */
-static bNodeSocketTemplate rgbtobw_in[]= {
+static bNodeSocketTemplate rgbtobw_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocketTemplate rgbtobw_out[]= {
+static bNodeSocketTemplate rgbtobw_out[] = {
{ SOCK_FLOAT, 0, N_("Val"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/texture/nodes/node_texture_viewer.c b/source/blender/nodes/texture/nodes/node_texture_viewer.c
index bc31bef59d8..5cb8d8c438c 100644
--- a/source/blender/nodes/texture/nodes/node_texture_viewer.c
+++ b/source/blender/nodes/texture/nodes/node_texture_viewer.c
@@ -66,7 +66,7 @@ void register_node_type_tex_viewer(bNodeTreeType *ttype)
node_type_exec(&ntype, exec);
/* Do not allow muting viewer node. */
- node_type_internal_connect(&ntype, NULL);
+ node_type_internal_links(&ntype, NULL);
nodeRegisterType(ttype, &ntype);
}
diff --git a/source/blender/opencl/CMakeLists.txt b/source/blender/opencl/CMakeLists.txt
index 20dcf33d363..b3c76db1bca 100644
--- a/source/blender/opencl/CMakeLists.txt
+++ b/source/blender/opencl/CMakeLists.txt
@@ -1,4 +1,3 @@
-# $Id: CMakeLists.txt 14444 2008-04-16 22:40:48Z hos $
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
diff --git a/source/blender/opencl/intern/OCL_opencl.c b/source/blender/opencl/intern/OCL_opencl.c
index fa22acbc1a2..e3130e16bde 100644
--- a/source/blender/opencl/intern/OCL_opencl.c
+++ b/source/blender/opencl/intern/OCL_opencl.c
@@ -22,14 +22,14 @@
#include "OCL_opencl.h"
-void OCL_init()
+void OCL_init(void)
{
#ifdef _WIN32
- const char *path = "OpenCL.dll";
+ const char *path = "OpenCL.dll";
#elif defined(__APPLE__)
- const char *path = "/Library/Frameworks/OpenCL.framework/OpenCL";
+ const char *path = "/Library/Frameworks/OpenCL.framework/OpenCL";
#else
- const char *path = "libOpenCL.so";
+ const char *path = "libOpenCL.so";
#endif
clewInit(path);
diff --git a/source/blender/python/BPY_extern.h b/source/blender/python/BPY_extern.h
index 83a40ecc068..9bd45d2b759 100644
--- a/source/blender/python/BPY_extern.h
+++ b/source/blender/python/BPY_extern.h
@@ -80,6 +80,7 @@ int BPY_button_exec(struct bContext *C, const char *expr, double *value, const
int BPY_string_exec(struct bContext *C, const char *expr);
void BPY_DECREF(void *pyob_ptr); /* Py_DECREF() */
+void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr);
int BPY_context_member_get(struct bContext *C, const char *member, struct bContextDataResult *result);
void BPY_context_set(struct bContext *C);
void BPY_context_update(struct bContext *C);
diff --git a/source/blender/python/bmesh/bmesh_py_types.c b/source/blender/python/bmesh/bmesh_py_types.c
index d7d9baf35ed..2cae10101d1 100644
--- a/source/blender/python/bmesh/bmesh_py_types.c
+++ b/source/blender/python/bmesh/bmesh_py_types.c
@@ -189,7 +189,7 @@ static int bpy_bm_elem_index_set(BPy_BMElem *self, PyObject *value, void *UNUSED
/* Mesh
* ^^^^ */
-/* doc-strings for all uses of this funcion */
+/* doc-strings for all uses of this function */
PyDoc_STRVAR(bpy_bmvertseq_doc,
"This meshes vert sequence (read-only).\n\n:type: :class:`BMVertSeq`"
@@ -645,7 +645,7 @@ static PyGetSetDef bpy_bmface_getseters[] = {
static PyGetSetDef bpy_bmloop_getseters[] = {
/* generic */
- // flags are available but not used for loops.
+ /* flags are available but not used for loops. */
// {(char *)"select", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_select_doc, (void *)BM_ELEM_SELECT},
// {(char *)"hide", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_hide_doc, (void *)BM_ELEM_HIDDEN},
{(char *)"tag", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_tag_doc, (void *)BM_ELEM_TAG},
@@ -1808,7 +1808,7 @@ static PyObject *bpy_bmfaceseq_new(BPy_BMElemSeq *self, PyObject *args)
f_new = BM_face_create(bm, vert_array, edge_array, vert_seq_len, FALSE);
- if (f_new == NULL) {
+ if (UNLIKELY(f_new == NULL)) {
PyErr_SetString(PyExc_ValueError,
"faces.new(verts): couldn't create the new face, internal error");
goto cleanup;
@@ -2581,7 +2581,7 @@ static PyObject *bpy_bmelemseq_subscript(BPy_BMElemSeq *self, PyObject *key)
/* only get the length for negative values */
Py_ssize_t len = bpy_bmelemseq_length(self);
if (start < 0) start += len;
- if (stop < 0) start += len;
+ if (stop < 0) stop += len;
}
if (stop - start <= 0) {
diff --git a/source/blender/python/bmesh/bmesh_py_types.h b/source/blender/python/bmesh/bmesh_py_types.h
index 947e66bf24e..df5231a4b1b 100644
--- a/source/blender/python/bmesh/bmesh_py_types.h
+++ b/source/blender/python/bmesh/bmesh_py_types.h
@@ -116,7 +116,7 @@ typedef struct BPy_BMElemSeq {
/* if this is a sequence on an existing element,
* loops of faces for eg.
- * If this veriable is set, it will be used */
+ * If this variable is set, it will be used */
/* we hold a reference to this.
* check in case the owner becomes invalid on access */
diff --git a/source/blender/python/bmesh/bmesh_py_types_customdata.c b/source/blender/python/bmesh/bmesh_py_types_customdata.c
index e45a39a0643..1fea12d105c 100644
--- a/source/blender/python/bmesh/bmesh_py_types_customdata.c
+++ b/source/blender/python/bmesh/bmesh_py_types_customdata.c
@@ -685,7 +685,7 @@ static PyObject *bpy_bmlayercollection_subscript(BPy_BMLayerCollection *self, Py
/* only get the length for negative values */
Py_ssize_t len = bpy_bmlayercollection_length(self);
if (start < 0) start += len;
- if (stop < 0) start += len;
+ if (stop < 0) stop += len;
}
if (stop - start <= 0) {
@@ -1079,7 +1079,7 @@ int BPy_BMLayerItem_SetItem(BPy_BMElem *py_ele, BPy_BMLayerItem *py_layer, PyObj
ret = -1;
}
else {
- BLI_strncpy(mstring->s, tmp_val, sizeof(mstring->s));
+ BLI_strncpy(mstring->s, tmp_val, min_ii(PyBytes_Size(py_value), sizeof(mstring->s)));
}
break;
}
diff --git a/source/blender/python/bmesh/bmesh_py_types_meshdata.c b/source/blender/python/bmesh/bmesh_py_types_meshdata.c
index b5fee2a3e8e..8316d33ea38 100644
--- a/source/blender/python/bmesh/bmesh_py_types_meshdata.c
+++ b/source/blender/python/bmesh/bmesh_py_types_meshdata.c
@@ -251,7 +251,7 @@ PyObject *BPy_BMLoopUV_CreatePyObject(struct MLoopUV *mloopuv)
/* Mesh Loop Color
* *************** */
-/* This simply provices a color wrapper for
+/* This simply provides a color wrapper for
* color which uses mathutils callbacks for mathutils.Color
*/
diff --git a/source/blender/python/bmesh/bmesh_py_types_select.c b/source/blender/python/bmesh/bmesh_py_types_select.c
index c3adc8366bd..2ff731559d1 100644
--- a/source/blender/python/bmesh/bmesh_py_types_select.c
+++ b/source/blender/python/bmesh/bmesh_py_types_select.c
@@ -280,7 +280,7 @@ static PyObject *bpy_bmeditselseq_subscript(BPy_BMEditSelSeq *self, PyObject *ke
/* only get the length for negative values */
Py_ssize_t len = bpy_bmeditselseq_length(self);
if (start < 0) start += len;
- if (stop < 0) start += len;
+ if (stop < 0) stop += len;
}
if (stop - start <= 0) {
@@ -387,7 +387,7 @@ void BPy_BM_init_types_select(void)
BPy_BMEditSelSeq_Type.tp_name = "BMEditSelSeq";
BPy_BMEditSelIter_Type.tp_name = "BMEditSelIter";
- BPy_BMEditSelSeq_Type.tp_doc = NULL; // todo
+ BPy_BMEditSelSeq_Type.tp_doc = NULL; /* todo */
BPy_BMEditSelIter_Type.tp_doc = NULL;
BPy_BMEditSelSeq_Type.tp_repr = (reprfunc)NULL;
diff --git a/source/blender/python/generic/idprop_py_api.c b/source/blender/python/generic/idprop_py_api.c
index 06b6192a091..d2890bc046e 100644
--- a/source/blender/python/generic/idprop_py_api.c
+++ b/source/blender/python/generic/idprop_py_api.c
@@ -43,43 +43,39 @@
#include "py_capi_utils.h"
#endif
-extern PyTypeObject BPy_IDArray_Type;
-extern PyTypeObject BPy_IDGroup_Iter_Type;
-extern PyTypeObject BPy_IDGroup_Type;
-
/*********************** ID Property Main Wrapper Stuff ***************/
/* ----------------------------------------------------------------------------
* static conversion functions to avoid duplicate code, no type checking.
*/
-static PyObject *idprop_py_from_idp_string(IDProperty *prop)
+static PyObject *idprop_py_from_idp_string(const IDProperty *prop)
{
if (prop->subtype == IDP_STRING_SUB_BYTE) {
- return PyBytes_FromStringAndSize(IDP_Array(prop), prop->len);
+ return PyBytes_FromStringAndSize(IDP_String(prop), prop->len);
}
else {
#ifdef USE_STRING_COERCE
return PyC_UnicodeFromByteAndSize(IDP_Array(prop), prop->len - 1);
#else
- return PyUnicode_FromStringAndSize(IDP_Array(prop), prop->len - 1);
+ return PyUnicode_FromStringAndSize(IDP_String(prop), prop->len - 1);
#endif
}
}
-static PyObject *idprop_py_from_idp_int(IDProperty *prop)
+static PyObject *idprop_py_from_idp_int(const IDProperty *prop)
{
- return PyLong_FromLong((long)prop->data.val);
+ return PyLong_FromLong((long)IDP_Int(prop));
}
-static PyObject *idprop_py_from_idp_float(IDProperty *prop)
+static PyObject *idprop_py_from_idp_float(const IDProperty *prop)
{
- return PyFloat_FromDouble((double)(*(float *)(&prop->data.val)));
+ return PyFloat_FromDouble((double)IDP_Float(prop));
}
-static PyObject *idprop_py_from_idp_double(IDProperty *prop)
+static PyObject *idprop_py_from_idp_double(const IDProperty *prop)
{
- return PyFloat_FromDouble((*(double *)(&prop->data.val)));
+ return PyFloat_FromDouble(IDP_Double(prop));
}
static PyObject *idprop_py_from_idp_group(ID *id, IDProperty *prop, IDProperty *parent)
@@ -193,7 +189,7 @@ static int BPy_IDGroup_SetData(BPy_IDProperty *self, IDProperty *prop, PyObject
PyErr_SetString(PyExc_TypeError, "expected an int type");
return -1;
}
- prop->data.val = ivalue;
+ IDP_Int(prop) = ivalue;
break;
}
case IDP_FLOAT:
@@ -203,7 +199,7 @@ static int BPy_IDGroup_SetData(BPy_IDProperty *self, IDProperty *prop, PyObject
PyErr_SetString(PyExc_TypeError, "expected a float");
return -1;
}
- *(float *)&self->prop->data.val = fvalue;
+ IDP_Float(self->prop) = fvalue;
break;
}
case IDP_DOUBLE:
@@ -213,7 +209,7 @@ static int BPy_IDGroup_SetData(BPy_IDProperty *self, IDProperty *prop, PyObject
PyErr_SetString(PyExc_TypeError, "expected a float");
return -1;
}
- *(double *)&self->prop->data.val = dvalue;
+ IDP_Double(self->prop) = dvalue;
break;
}
default:
@@ -300,40 +296,34 @@ static PyObject *BPy_IDGroup_Map_GetItem(BPy_IDProperty *self, PyObject *item)
}
/* returns NULL on success, error string on failure */
-static int idp_sequence_type(PyObject *seq)
+static int idp_sequence_type(PyObject *seq_fast)
{
PyObject *item;
int type = IDP_INT;
- Py_ssize_t i, len = PySequence_Size(seq);
+ Py_ssize_t i, len = PySequence_Fast_GET_SIZE(seq_fast);
for (i = 0; i < len; i++) {
- item = PySequence_GetItem(seq, i);
+ item = PySequence_Fast_GET_ITEM(seq_fast, i);
if (PyFloat_Check(item)) {
if (type == IDP_IDPARRAY) { /* mixed dict/int */
- Py_DECREF(item);
return -1;
}
type = IDP_DOUBLE;
}
else if (PyLong_Check(item)) {
if (type == IDP_IDPARRAY) { /* mixed dict/int */
- Py_DECREF(item);
return -1;
}
}
else if (PyMapping_Check(item)) {
if (i != 0 && (type != IDP_IDPARRAY)) { /* mixed dict/int */
- Py_DECREF(item);
return -1;
}
type = IDP_IDPARRAY;
}
else {
- Py_XDECREF(item);
return -1;
}
-
- Py_DECREF(item);
}
return type;
@@ -386,48 +376,61 @@ const char *BPy_IDProperty_Map_ValidateAndCreate(PyObject *name_obj, IDProperty
//prop->subtype = IDP_STRING_SUB_BYTE;
}
else if (PySequence_Check(ob)) {
+ PyObject *ob_seq_fast = PySequence_Fast(ob, "py -> idprop");
PyObject *item;
int i;
- if ((val.array.type = idp_sequence_type(ob)) == -1)
+ if (ob_seq_fast == NULL) {
+ PyErr_Print();
+ PyErr_Clear();
+ return "error converting the sequence";
+ }
+
+ if ((val.array.type = idp_sequence_type(ob_seq_fast)) == -1) {
+ Py_DECREF(ob_seq_fast);
return "only floats, ints and dicts are allowed in ID property arrays";
+ }
/* validate sequence and derive type.
* we assume IDP_INT unless we hit a float
* number; then we assume it's */
- val.array.len = PySequence_Size(ob);
+ val.array.len = PySequence_Fast_GET_SIZE(ob_seq_fast);
switch (val.array.type) {
case IDP_DOUBLE:
prop = IDP_New(IDP_ARRAY, &val, name);
for (i = 0; i < val.array.len; i++) {
- item = PySequence_GetItem(ob, i);
+ item = PySequence_Fast_GET_ITEM(ob_seq_fast, i);
((double *)IDP_Array(prop))[i] = (float)PyFloat_AsDouble(item);
- Py_DECREF(item);
}
break;
case IDP_INT:
prop = IDP_New(IDP_ARRAY, &val, name);
for (i = 0; i < val.array.len; i++) {
- item = PySequence_GetItem(ob, i);
+ item = PySequence_Fast_GET_ITEM(ob_seq_fast, i);
((int *)IDP_Array(prop))[i] = (int)PyLong_AsSsize_t(item);
- Py_DECREF(item);
}
break;
case IDP_IDPARRAY:
prop = IDP_NewIDPArray(name);
for (i = 0; i < val.array.len; i++) {
const char *error;
- item = PySequence_GetItem(ob, i);
+ item = PySequence_Fast_GET_ITEM(ob_seq_fast, i);
error = BPy_IDProperty_Map_ValidateAndCreate(NULL, prop, item);
- Py_DECREF(item);
- if (error)
+ if (error) {
+ Py_DECREF(ob_seq_fast);
return error;
+ }
}
break;
+ default:
+ Py_DECREF(ob_seq_fast);
+ return "internal error with idp array.type";
}
+
+ Py_DECREF(ob_seq_fast);
}
else if (PyMapping_Check(ob)) {
PyObject *keys, *vals, *key, *pval;
@@ -471,7 +474,7 @@ const char *BPy_IDProperty_Map_ValidateAndCreate(PyObject *name_obj, IDProperty
if (group->type == IDP_IDPARRAY) {
IDP_AppendArray(group, prop);
- // IDP_FreeProperty(item); // IDP_AppendArray does a shallow copy (memcpy), only free memory
+ // IDP_FreeProperty(item); /* IDP_AppendArray does a shallow copy (memcpy), only free memory */
MEM_freeN(prop);
}
else {
@@ -802,17 +805,28 @@ static PyObject *BPy_IDGroup_Update(BPy_IDProperty *self, PyObject *value)
PyObject *pkey, *pval;
Py_ssize_t i = 0;
- if (!PyDict_Check(value)) {
+ if (BPy_IDGroup_Check(value)) {
+ BPy_IDProperty *other = (BPy_IDProperty *)value;
+ if (UNLIKELY(self->prop == other->prop)) {
+ Py_RETURN_NONE;
+ }
+
+ /* XXX, possible one is inside the other */
+ IDP_MergeGroup(self->prop, other->prop, TRUE);
+ }
+ else if (PyDict_Check(value)) {
+ while (PyDict_Next(value, &i, &pkey, &pval)) {
+ BPy_IDGroup_Map_SetItem(self, pkey, pval);
+ if (PyErr_Occurred()) return NULL;
+ }
+ }
+ else {
PyErr_Format(PyExc_TypeError,
- "expected a dict not a %.200s",
+ "expected a dict or an IDPropertyGroup type, not a %.200s",
Py_TYPE(value)->tp_name);
return NULL;
}
- while (PyDict_Next(value, &i, &pkey, &pval)) {
- BPy_IDGroup_Map_SetItem(self, pkey, pval);
- if (PyErr_Occurred()) return NULL;
- }
Py_RETURN_NONE;
}
@@ -1416,15 +1430,15 @@ void IDProp_Init_Types(void)
/* --- */
static struct PyModuleDef IDProp_types_module_def = {
- PyModuleDef_HEAD_INIT,
- "idprop.types", /* m_name */
- NULL, /* m_doc */
- 0, /* m_size */
- NULL, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "idprop.types", /* m_name */
+ NULL, /* m_doc */
+ 0, /* m_size */
+ NULL, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
static PyObject *BPyInit_idprop_types(void)
@@ -1483,3 +1497,40 @@ PyObject *BPyInit_idprop(void)
return mod;
}
+
+
+#ifdef DEBUG
+/* -------------------------------------------------------------------- */
+/* debug only function */
+
+void IDP_spit(IDProperty *prop)
+{
+ if (prop) {
+ PyGILState_STATE gilstate;
+ int use_gil = TRUE; /* !PYC_INTERPRETER_ACTIVE; */
+ PyObject *ret_dict;
+ PyObject *ret_str;
+
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
+
+ /* to_dict() */
+ ret_dict = BPy_IDGroup_MapDataToPy(prop);
+ ret_str = PyObject_Repr(ret_dict);
+ Py_DECREF(ret_dict);
+
+ printf("IDProperty: %s\n", _PyUnicode_AsString(ret_str));
+
+ Py_DECREF(ret_str);
+
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
+ }
+ else {
+ printf("IDProperty: <NIL>\n");
+ }
+}
+
+#endif
diff --git a/source/blender/python/generic/idprop_py_api.h b/source/blender/python/generic/idprop_py_api.h
index 99e291f69c0..cb82676c4d9 100644
--- a/source/blender/python/generic/idprop_py_api.h
+++ b/source/blender/python/generic/idprop_py_api.h
@@ -32,6 +32,17 @@ struct ID;
struct IDProperty;
struct BPy_IDGroup_Iter;
+extern PyTypeObject BPy_IDArray_Type;
+extern PyTypeObject BPy_IDGroup_Iter_Type;
+extern PyTypeObject BPy_IDGroup_Type;
+
+#define BPy_IDArray_Check(v) (PyObject_TypeCheck(v, &BPy_IDArray_Type))
+#define BPy_IDArray_CheckExact(v) (Py_TYPE(v) == &BPy_IDArray_Type)
+#define BPy_IDGroup_Iter_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_Iter_Type))
+#define BPy_IDGroup_Iter_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_Iter_Type)
+#define BPy_IDGroup_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_Type))
+#define BPy_IDGroup_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_Type)
+
typedef struct BPy_IDProperty {
PyObject_VAR_HEAD
struct ID *id; /* can be NULL */
diff --git a/source/blender/python/generic/py_capi_utils.c b/source/blender/python/generic/py_capi_utils.c
index 2e4d4e870b8..3b8193c422d 100644
--- a/source/blender/python/generic/py_capi_utils.c
+++ b/source/blender/python/generic/py_capi_utils.c
@@ -450,7 +450,7 @@ PyObject *PyC_UnicodeFromByte(const char *str)
* >> foo = 10
* >> print(__import__("__main__").foo)
*
- * note: this overwrites __main__ which gives problems with nested calles.
+ * note: this overwrites __main__ which gives problems with nested calls.
* be sure to run PyC_MainModule_Backup & PyC_MainModule_Restore if there is
* any chance that python is in the call stack.
****************************************************************************/
@@ -542,7 +542,7 @@ void PyC_RunQuicky(const char *filepath, int n, ...)
if (fp) {
PyGILState_STATE gilstate = PyGILState_Ensure();
- va_list vargs;
+ va_list vargs;
int *sizes = PyMem_MALLOC(sizeof(int) * (n / 2));
int i;
@@ -760,7 +760,6 @@ int PyC_FlagSet_ValueFromID(PyC_FlagSet *item, const char *identifier, int *valu
return 0;
}
-/* 'value' _must_ be a set type, error check before calling */
int PyC_FlagSet_ToBitfield(PyC_FlagSet *items, PyObject *value, int *r_value, const char *error_prefix)
{
/* set of enum items, concatenate all values with OR */
@@ -771,6 +770,13 @@ int PyC_FlagSet_ToBitfield(PyC_FlagSet *items, PyObject *value, int *r_value, co
Py_ssize_t hash = 0;
PyObject *key;
+ if (!PySet_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s expected a set, not %.200s",
+ error_prefix, Py_TYPE(value)->tp_name);
+ return -1;
+ }
+
*r_value = 0;
while (_PySet_NextEntry(value, &pos, &key, &hash)) {
@@ -778,7 +784,7 @@ int PyC_FlagSet_ToBitfield(PyC_FlagSet *items, PyObject *value, int *r_value, co
if (param == NULL) {
PyErr_Format(PyExc_TypeError,
- "%.200s expected a string, not %.200s",
+ "%.200s set must contain strings, not %.200s",
error_prefix, Py_TYPE(key)->tp_name);
return -1;
}
diff --git a/source/blender/python/generic/py_capi_utils.h b/source/blender/python/generic/py_capi_utils.h
index 481cfb17c7a..935a5f9030b 100644
--- a/source/blender/python/generic/py_capi_utils.h
+++ b/source/blender/python/generic/py_capi_utils.h
@@ -69,4 +69,4 @@ int PyC_FlagSet_ValueFromID(PyC_FlagSet *item, const char *identifier, int
int PyC_FlagSet_ToBitfield(PyC_FlagSet *items, PyObject *value, int *r_value, const char *error_prefix);
PyObject *PyC_FlagSet_FromBitfield(PyC_FlagSet *items, int flag);
-#endif // __PY_CAPI_UTILS_H__
+#endif /* __PY_CAPI_UTILS_H__ */
diff --git a/source/blender/python/intern/CMakeLists.txt b/source/blender/python/intern/CMakeLists.txt
index 604166eed3c..61c49027d9a 100644
--- a/source/blender/python/intern/CMakeLists.txt
+++ b/source/blender/python/intern/CMakeLists.txt
@@ -30,12 +30,12 @@ set(INC
../../blenlib
../../blenloader
../../editors/include
+ ../../gpu
../../makesdna
../../makesrna
../../windowmanager
- ../../gpu
- ../../../../intern/guardedalloc
../../../../intern/cycles/blender
+ ../../../../intern/guardedalloc
)
set(INC_SYS
diff --git a/source/blender/python/intern/bpy.c b/source/blender/python/intern/bpy.c
index f2222825c42..ad900343704 100644
--- a/source/blender/python/intern/bpy.c
+++ b/source/blender/python/intern/bpy.c
@@ -171,7 +171,7 @@ static PyObject *bpy_user_resource(PyObject *UNUSED(self), PyObject *args, PyObj
}
PyDoc_STRVAR(bpy_resource_path_doc,
-".. function:: resource_path(type, major=2, minor=57)\n"
+".. function:: resource_path(type, major=bpy.app.version[0], minor=bpy.app.version[1])\n"
"\n"
" Return the base path for storing system files.\n"
"\n"
@@ -278,7 +278,7 @@ void BPy_init_modules(void)
bpy_import_test("bpy_types");
PyModule_AddObject(mod, "data", BPY_rna_module()); /* imports bpy_types by running this */
bpy_import_test("bpy_types");
- PyModule_AddObject(mod, "props", BPY_rna_props());
+ PyModule_AddObject(mod, "props", BPY_rna_props());
/* ops is now a python module that does the conversion from SOME_OT_foo -> some.foo */
PyModule_AddObject(mod, "ops", BPY_operator_module());
PyModule_AddObject(mod, "app", BPY_app_struct());
diff --git a/source/blender/python/intern/bpy_app.c b/source/blender/python/intern/bpy_app.c
index ccce0d8c5ae..a8aa7269b72 100644
--- a/source/blender/python/intern/bpy_app.c
+++ b/source/blender/python/intern/bpy_app.c
@@ -242,6 +242,7 @@ static PyGetSetDef bpy_app_getsets[] = {
{(char *)"debug_ffmpeg", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_FFMPEG},
{(char *)"debug_python", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_PYTHON},
{(char *)"debug_events", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_EVENTS},
+ {(char *)"debug_handlers", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_HANDLERS},
{(char *)"debug_wm", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_WM},
{(char *)"debug_value", bpy_app_debug_value_get, bpy_app_debug_value_set, (char *)bpy_app_debug_value_doc, NULL},
diff --git a/source/blender/python/intern/bpy_app.h b/source/blender/python/intern/bpy_app.h
index 5bf36f04ba0..226bf44a493 100644
--- a/source/blender/python/intern/bpy_app.h
+++ b/source/blender/python/intern/bpy_app.h
@@ -29,4 +29,4 @@
PyObject *BPY_app_struct(void);
-#endif // __BPY_APP_H__
+#endif /* __BPY_APP_H__ */
diff --git a/source/blender/python/intern/bpy_app_ffmpeg.c b/source/blender/python/intern/bpy_app_ffmpeg.c
index 68fd9a99712..5ae2a11710a 100644
--- a/source/blender/python/intern/bpy_app_ffmpeg.c
+++ b/source/blender/python/intern/bpy_app_ffmpeg.c
@@ -77,8 +77,10 @@ static PyObject *make_ffmpeg_info(void)
return NULL;
}
+#if 0 // UNUSED
#define SetIntItem(flag) \
PyStructSequence_SET_ITEM(ffmpeg_info, pos++, PyLong_FromLong(flag))
+#endif
#define SetStrItem(str) \
PyStructSequence_SET_ITEM(ffmpeg_info, pos++, PyUnicode_FromString(str))
#define SetObjItem(obj) \
@@ -118,7 +120,7 @@ static PyObject *make_ffmpeg_info(void)
return NULL;
}
-#undef SetIntItem
+// #undef SetIntItem
#undef SetStrItem
#undef SetObjItem
diff --git a/source/blender/python/intern/bpy_app_ffmpeg.h b/source/blender/python/intern/bpy_app_ffmpeg.h
index cadbb021d31..26d6e13f8f4 100644
--- a/source/blender/python/intern/bpy_app_ffmpeg.h
+++ b/source/blender/python/intern/bpy_app_ffmpeg.h
@@ -29,4 +29,4 @@
PyObject *BPY_app_ffmpeg_struct(void);
-#endif // __BPY_APP_FFMPEG_H__
+#endif /* __BPY_APP_FFMPEG_H__ */
diff --git a/source/blender/python/intern/bpy_app_handlers.c b/source/blender/python/intern/bpy_app_handlers.c
index 4d7f2080bbc..90a0444ceae 100644
--- a/source/blender/python/intern/bpy_app_handlers.c
+++ b/source/blender/python/intern/bpy_app_handlers.c
@@ -284,7 +284,7 @@ void bpy_app_generic_callback(struct Main *UNUSED(main), struct ID *id, void *ar
if (PyList_GET_SIZE(cb_list) > 0) {
PyGILState_STATE gilstate = PyGILState_Ensure();
- PyObject *args = PyTuple_New(1); // save python creating each call
+ PyObject *args = PyTuple_New(1); /* save python creating each call */
PyObject *func;
PyObject *ret;
Py_ssize_t pos;
diff --git a/source/blender/python/intern/bpy_app_handlers.h b/source/blender/python/intern/bpy_app_handlers.h
index 1f1eaf04a8b..40ca43909ed 100644
--- a/source/blender/python/intern/bpy_app_handlers.h
+++ b/source/blender/python/intern/bpy_app_handlers.h
@@ -29,4 +29,4 @@
PyObject *BPY_app_handlers_struct(void);
-#endif // __BPY_APP_HANDLERS_H__
+#endif /* __BPY_APP_HANDLERS_H__ */
diff --git a/source/blender/python/intern/bpy_driver.c b/source/blender/python/intern/bpy_driver.c
index de23b3bf109..9a79616c23b 100644
--- a/source/blender/python/intern/bpy_driver.c
+++ b/source/blender/python/intern/bpy_driver.c
@@ -280,7 +280,7 @@ float BPY_driver_exec(ChannelDriver *driver, const float evaltime)
}
-#if 0 // slow, with this can avoid all Py_CompileString above.
+#if 0 /* slow, with this can avoid all Py_CompileString above. */
/* execute expression to get a value */
retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
#else
diff --git a/source/blender/python/intern/bpy_driver.h b/source/blender/python/intern/bpy_driver.h
index 6d1696d6cdc..1fccec7e1b2 100644
--- a/source/blender/python/intern/bpy_driver.h
+++ b/source/blender/python/intern/bpy_driver.h
@@ -36,4 +36,4 @@ extern PyObject *bpy_pydriver_Dict;
float BPY_driver_exec(struct ChannelDriver *driver, const float evaltime);
void BPY_driver_reset(void);
-#endif // __BPY_DRIVER_H__
+#endif /* __BPY_DRIVER_H__ */
diff --git a/source/blender/python/intern/bpy_interface.c b/source/blender/python/intern/bpy_interface.c
index 9cd0bdd090a..94cbee383ea 100644
--- a/source/blender/python/intern/bpy_interface.c
+++ b/source/blender/python/intern/bpy_interface.c
@@ -53,6 +53,7 @@
#include "BLI_path_util.h"
#include "BLI_fileops.h"
+#include "BLI_listbase.h"
#include "BLI_math_base.h"
#include "BLI_string.h"
#include "BLI_string_utf8.h"
@@ -68,7 +69,7 @@
#include "BPY_extern.h"
-#include "../generic/bpy_internal_import.h" // our own imports
+#include "../generic/bpy_internal_import.h" /* our own imports */
#include "../generic/py_capi_utils.h"
/* inittab initialization functions */
@@ -179,10 +180,10 @@ void BPY_text_free_code(Text *text)
void BPY_modules_update(bContext *C)
{
-#if 0 // slow, this runs all the time poll, draw etc 100's of time a sec.
+#if 0 /* slow, this runs all the time poll, draw etc 100's of time a sec. */
PyObject *mod = PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
PyModule_AddObject(mod, "data", BPY_rna_module());
- PyModule_AddObject(mod, "types", BPY_rna_types()); // atm this does not need updating
+ PyModule_AddObject(mod, "types", BPY_rna_types()); /* atm this does not need updating */
#endif
/* refreshes the main struct */
@@ -250,6 +251,10 @@ void BPY_python_start(int argc, const char **argv)
* an error, this is highly annoying, another stumbling block for devs,
* so use a more relaxed error handler and enforce utf-8 since the rest of
* blender is utf-8 too - campbell */
+
+ /* XXX, update: this is unreliable! 'PYTHONIOENCODING' is ignored in MS-Windows
+ * when dynamically linked, see: [#31555] for details.
+ * Python doesn't expose a good way to set this. */
BLI_setenv("PYTHONIOENCODING", "utf-8:surrogateescape");
/* Python 3.2 now looks for '2.xx/python/include/python3.2d/pyconfig.h' to
@@ -263,16 +268,7 @@ void BPY_python_start(int argc, const char **argv)
Py_Initialize();
-#ifdef WIN32
- /* this is disappointing, its likely a bug in python?
- * for some reason 'PYTHONIOENCODING' is ignored in windows
- * see: [#31555] for details. */
- PyRun_SimpleString("import sys, io\n"
- "sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='surrogateescape', line_buffering=True)\n"
- "sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='surrogateescape', line_buffering=True)\n");
-#endif /* WIN32 */
-
- // PySys_SetArgv(argc, argv); // broken in py3, not a huge deal
+ // PySys_SetArgv(argc, argv); /* broken in py3, not a huge deal */
/* sigh, why do python guys not have a (char **) version anymore? */
{
int i;
@@ -383,6 +379,7 @@ typedef struct {
static int python_script_exec(bContext *C, const char *fn, struct Text *text,
struct ReportList *reports, const short do_jump)
{
+ Main *bmain_old = CTX_data_main(C);
PyObject *main_mod = NULL;
PyObject *py_dict = NULL, *py_result = NULL;
PyGILState_STATE gilstate;
@@ -461,7 +458,11 @@ static int python_script_exec(bContext *C, const char *fn, struct Text *text,
if (!py_result) {
if (text) {
if (do_jump) {
- python_script_error_jump_text(text);
+ /* ensure text is valid before use, the script may have freed its self */
+ Main *bmain_new = CTX_data_main(C);
+ if ((bmain_old == bmain_new) && (BLI_findindex(&bmain_new->text, text) != -1)) {
+ python_script_error_jump_text(text);
+ }
}
}
BPy_errors_to_report(reports);
@@ -509,6 +510,18 @@ void BPY_DECREF(void *pyob_ptr)
PyGILState_Release(gilstate);
}
+void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr)
+{
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+ const int do_invalidate = (Py_REFCNT((PyObject *)pyob_ptr) > 1);
+ Py_DECREF((PyObject *)pyob_ptr);
+ if (do_invalidate) {
+ pyrna_invalidate(pyob_ptr);
+ }
+ PyGILState_Release(gilstate);
+}
+
+
/* return -1 on error, else 0 */
int BPY_button_exec(bContext *C, const char *expr, double *value, const short verbose)
{
@@ -672,6 +685,11 @@ void BPY_modules_load_user(bContext *C)
else {
Py_DECREF(module);
}
+
+ /* check if the script loaded a new file */
+ if (bmain != CTX_data_main(C)) {
+ break;
+ }
}
}
}
@@ -680,11 +698,20 @@ void BPY_modules_load_user(bContext *C)
int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *result)
{
- PyObject *pyctx = (PyObject *)CTX_py_dict_get(C);
- PyObject *item = PyDict_GetItemString(pyctx, member);
+ PyGILState_STATE gilstate;
+ int use_gil = !PYC_INTERPRETER_ACTIVE;
+
+ PyObject *pyctx;
+ PyObject *item;
PointerRNA *ptr = NULL;
int done = FALSE;
+ if (use_gil)
+ gilstate = PyGILState_Ensure();
+
+ pyctx = (PyObject *)CTX_py_dict_get(C);
+ item = PyDict_GetItemString(pyctx, member);
+
if (item == NULL) {
/* pass */
}
@@ -720,7 +747,8 @@ int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *
CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
}
else {
- printf("List item not a valid type\n");
+ printf("PyContext: '%s' list item not a valid type in sequece type '%s'\n",
+ member, Py_TYPE(item)->tp_name);
}
}
@@ -740,6 +768,9 @@ int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *
}
}
+ if (use_gil)
+ PyGILState_Release(gilstate);
+
return done;
}
diff --git a/source/blender/python/intern/bpy_props.c b/source/blender/python/intern/bpy_props.c
index abf609cd235..bd033736865 100644
--- a/source/blender/python/intern/bpy_props.c
+++ b/source/blender/python/intern/bpy_props.c
@@ -75,9 +75,10 @@ static EnumPropertyItem property_flag_enum_items[] = {
static EnumPropertyItem property_subtype_string_items[] = {
{PROP_FILEPATH, "FILE_PATH", 0, "File Path", ""},
{PROP_DIRPATH, "DIR_PATH", 0, "Directory Path", ""},
- {PROP_FILENAME, "FILENAME", 0, "Filename", ""},
+ {PROP_FILENAME, "FILE_NAME", 0, "Filename", ""},
{PROP_BYTESTRING, "BYTE_STRING", 0, "Byte String", ""},
{PROP_TRANSLATE, "TRANSLATE", 0, "Translate", ""},
+ {PROP_PASSWORD, "PASSWORD", 0, "Password", 0},
{PROP_NONE, "NONE", 0, "None", ""},
{0, NULL, 0, NULL, NULL}};
@@ -260,7 +261,7 @@ static int bpy_prop_callback_check(PyObject *py_func, int argcount)
static int bpy_prop_callback_assign(struct PropertyRNA *prop, PyObject *update_cb)
{
/* assume this is already checked for type and arg length */
- if (update_cb) {
+ if (update_cb && update_cb != Py_None) {
PyObject **py_data = MEM_callocN(sizeof(PyObject *) * BPY_DATA_CB_SLOT_SIZE, __func__);
RNA_def_property_update_runtime(prop, (void *)bpy_prop_update_cb);
py_data[BPY_DATA_CB_SLOT_UPDATE] = update_cb;
@@ -309,35 +310,38 @@ static int py_long_as_int(PyObject *py_long, int *r_int)
/* terse macros for error checks shared between all funcs cant use function
* calls because of static strings passed to pyrna_set_to_enum_bitfield */
#define BPY_PROPDEF_CHECK(_func, _property_flag_items) \
- if (id_len >= MAX_IDPROP_NAME) { \
+ if (UNLIKELY(id_len >= MAX_IDPROP_NAME)) { \
PyErr_Format(PyExc_TypeError, \
#_func"(): '%.200s' too long, max length is %d", \
id, MAX_IDPROP_NAME - 1); \
return NULL; \
} \
- if (RNA_def_property_free_identifier(srna, id) == -1) { \
+ if (UNLIKELY(RNA_def_property_free_identifier(srna, id) == -1)) { \
PyErr_Format(PyExc_TypeError, \
#_func"(): '%s' is defined as a non-dynamic type", \
id); \
return NULL; \
} \
- if (pyopts && pyrna_set_to_enum_bitfield(_property_flag_items, \
+ if (UNLIKELY(pyopts && pyrna_set_to_enum_bitfield(_property_flag_items, \
pyopts, \
&opts, \
- #_func"(options={ ...}):")) \
+ #_func"(options={ ...}):"))) \
{ \
return NULL; \
} (void)0
#define BPY_PROPDEF_SUBTYPE_CHECK(_func, _property_flag_items, _subtype) \
BPY_PROPDEF_CHECK(_func, _property_flag_items); \
- if (pysubtype && RNA_enum_value_from_id(_subtype, \
+ if (UNLIKELY(pysubtype && RNA_enum_value_from_id(_subtype, \
pysubtype, \
- &subtype) == 0) \
+ &subtype) == 0)) \
{ \
+ const char *enum_str = BPy_enum_as_string(_subtype); \
PyErr_Format(PyExc_TypeError, \
- #_func"(subtype='%s'): invalid subtype", \
- pysubtype); \
+ #_func"(subtype='%s'): " \
+ "subtype not found in (%s)", \
+ pysubtype, enum_str); \
+ MEM_freeN((void *)enum_str); \
return NULL; \
} (void)0
@@ -360,6 +364,7 @@ static int py_long_as_int(PyObject *py_long, int *r_int)
#define BPY_PROPDEF_UPDATE_DOC \
" :arg update: function to be called when this value is modified,\n" \
" This function must take 2 values (self, context) and return None.\n" \
+" *Warning* there are no safety checks to avoid infinite recursion.\n" \
" :type update: function\n" \
#if 0
@@ -920,7 +925,7 @@ BPY_PROPDEF_NAME_DOC
BPY_PROPDEF_DESC_DOC
" :arg options: Enumerator in ['HIDDEN', 'SKIP_SAVE', 'ANIMATABLE', 'LIBRARY_EDITABLE'].\n"
" :type options: set\n"
-" :arg subtype: Enumerator in ['FILE_PATH', 'DIR_PATH', 'FILENAME', 'NONE'].\n"
+" :arg subtype: Enumerator in ['FILE_PATH', 'DIR_PATH', 'FILE_NAME', 'NONE'].\n"
" :type subtype: string\n"
BPY_PROPDEF_UPDATE_DOC
);
@@ -1510,7 +1515,7 @@ static PyObject *BPy_RemoveProperty(PyObject *self, PyObject *args, PyObject *kw
args = PyTuple_New(0);
ret = BPy_RemoveProperty(self, args, kw);
Py_DECREF(args);
- return ret;
+ return ret;
}
else if (PyTuple_GET_SIZE(args) > 1) {
PyErr_SetString(PyExc_ValueError, "all args must be keywords");
diff --git a/source/blender/python/intern/bpy_rna.c b/source/blender/python/intern/bpy_rna.c
index 8ec8c4c41ba..68b6baadd71 100644
--- a/source/blender/python/intern/bpy_rna.c
+++ b/source/blender/python/intern/bpy_rna.c
@@ -119,13 +119,10 @@ int pyrna_prop_validity_check(BPy_PropertyRNA *self)
return -1;
}
-#if defined(USE_PYRNA_INVALIDATE_GC) || defined(USE_PYRNA_INVALIDATE_WEAKREF)
-static void pyrna_invalidate(BPy_DummyPointerRNA *self)
+void pyrna_invalidate(BPy_DummyPointerRNA *self)
{
- self->ptr.type = NULL; /* this is checked for validity */
- self->ptr.id.data = NULL; /* should not be needed but prevent bad pointer access, just in case */
+ RNA_POINTER_INVALIDATE(&self->ptr);
}
-#endif
#ifdef USE_PYRNA_INVALIDATE_GC
#define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g) + 1))
@@ -337,7 +334,7 @@ static int rna_id_write_error(PointerRNA *ptr, PyObject *key)
}
return FALSE;
}
-#endif // USE_PEDANTIC_WRITE
+#endif /* USE_PEDANTIC_WRITE */
#ifdef USE_PEDANTIC_WRITE
@@ -350,7 +347,7 @@ void pyrna_write_set(int val)
{
rna_disallow_writes = !val;
}
-#else // USE_PEDANTIC_WRITE
+#else /* USE_PEDANTIC_WRITE */
int pyrna_write_check(void)
{
return TRUE;
@@ -359,7 +356,7 @@ void pyrna_write_set(int UNUSED(val))
{
/* nothing */
}
-#endif // USE_PEDANTIC_WRITE
+#endif /* USE_PEDANTIC_WRITE */
static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self);
static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self);
@@ -426,7 +423,7 @@ static int mathutils_rna_vector_set(BaseMathObject *bmo, int subtype)
if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
return -1;
}
-#endif // USE_PEDANTIC_WRITE
+#endif /* USE_PEDANTIC_WRITE */
if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
PyErr_Format(PyExc_AttributeError,
@@ -490,7 +487,7 @@ static int mathutils_rna_vector_set_index(BaseMathObject *bmo, int UNUSED(subtyp
if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
return -1;
}
-#endif // USE_PEDANTIC_WRITE
+#endif /* USE_PEDANTIC_WRITE */
if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
PyErr_Format(PyExc_AttributeError,
@@ -547,7 +544,7 @@ static int mathutils_rna_matrix_set(BaseMathObject *bmo, int UNUSED(subtype))
if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
return -1;
}
-#endif // USE_PEDANTIC_WRITE
+#endif /* USE_PEDANTIC_WRITE */
if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
PyErr_Format(PyExc_AttributeError,
@@ -588,7 +585,7 @@ static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_
return order_fallback;
}
-#endif // USE_MATHUTILS
+#endif /* USE_MATHUTILS */
/* note that PROP_NONE is included as a vector subtype. this is because its handy to
* have x/y access to fcurve keyframes and other fixed size float arrays of length 2-4. */
@@ -672,7 +669,7 @@ PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
PropertyRNA *prop_eul_order = NULL;
short order = pyrna_rotation_euler_order_get(ptr, &prop_eul_order, EULER_ORDER_XYZ);
- ret = Euler_CreatePyObject(NULL, order, Py_NEW, NULL); // TODO, get order from RNA
+ ret = Euler_CreatePyObject(NULL, order, Py_NEW, NULL); /* TODO, get order from RNA */
RNA_property_float_get_array(ptr, prop, ((EulerObject *)ret)->eul);
}
else {
@@ -698,7 +695,7 @@ PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
case PROP_COLOR_GAMMA:
if (len == 3) { /* color */
if (is_thick) {
- ret = Color_CreatePyObject(NULL, Py_NEW, NULL); // TODO, get order from RNA
+ ret = Color_CreatePyObject(NULL, Py_NEW, NULL);
RNA_property_float_get_array(ptr, prop, ((ColorObject *)ret)->col);
}
else {
@@ -722,10 +719,10 @@ PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
ret = pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
}
}
-#else // USE_MATHUTILS
+#else /* USE_MATHUTILS */
(void)ptr;
(void)prop;
-#endif // USE_MATHUTILS
+#endif /* USE_MATHUTILS */
return ret;
}
@@ -834,7 +831,7 @@ static PyObject *pyrna_struct_str(BPy_StructRNA *self)
const char *name;
if (!PYRNA_STRUCT_IS_VALID(self)) {
- return PyUnicode_FromFormat("<bpy_struct, %.200s dead>",
+ return PyUnicode_FromFormat("<bpy_struct, %.200s invalid>",
Py_TYPE(self)->tp_name);
}
@@ -1302,7 +1299,7 @@ static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
val, RNA_struct_identifier(ptr->type),
ptr_name, RNA_property_identifier(prop));
-#if 0 // gives python decoding errors while generating docs :(
+#if 0 /* gives python decoding errors while generating docs :( */
char error_str[256];
BLI_snprintf(error_str, sizeof(error_str),
"RNA Warning: Current value \"%d\" "
@@ -1371,14 +1368,14 @@ PyObject *pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
else {
ret = PyUnicode_FromStringAndSize(buf, buf_len);
}
-#else // USE_STRING_COERCE
+#else /* USE_STRING_COERCE */
if (subtype == PROP_BYTESTRING) {
ret = PyBytes_FromStringAndSize(buf, buf_len);
}
else {
ret = PyUnicode_FromStringAndSize(buf, buf_len);
}
-#endif // USE_STRING_COERCE
+#endif /* USE_STRING_COERCE */
if (buf_fixed != buf) {
MEM_freeN((void *)buf);
}
@@ -1635,12 +1632,12 @@ static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyOb
if (subtype == PROP_TRANSLATE) {
param = IFACE_(param);
}
-#endif // WITH_INTERNATIONAL
+#endif /* WITH_INTERNATIONAL */
}
-#else // USE_STRING_COERCE
+#else /* USE_STRING_COERCE */
param = _PyUnicode_AsString(value);
-#endif // USE_STRING_COERCE
+#endif /* USE_STRING_COERCE */
if (param == NULL) {
if (PyUnicode_Check(value)) {
@@ -1668,7 +1665,7 @@ static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyOb
}
#ifdef USE_STRING_COERCE
Py_XDECREF(value_coerce);
-#endif // USE_STRING_COERCE
+#endif /* USE_STRING_COERCE */
}
break;
}
@@ -1778,10 +1775,21 @@ static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyOb
if (data) {
if (flag & PROP_RNAPTR) {
- if (value == Py_None)
- memset(data, 0, sizeof(PointerRNA));
- else
- *((PointerRNA *)data) = param->ptr;
+ if (flag & PROP_THICK_WRAP) {
+ if (value == Py_None)
+ memset(data, 0, sizeof(PointerRNA));
+ else
+ *((PointerRNA *)data) = param->ptr;
+ }
+ else {
+ /* for function calls, we sometimes want to pass the 'ptr' directly,
+ * watch out that it remains valid!, possibly we could support this later if needed */
+ BLI_assert(value_new == NULL);
+ if (value == Py_None)
+ *((void **)data) = NULL;
+ else
+ *((PointerRNA **)data) = &param->ptr;
+ }
}
else if (value == Py_None) {
*((void **)data) = NULL;
@@ -1995,7 +2003,7 @@ static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, P
return ret;
}
-//---------------sequence-------------------------------------------
+/* ---------------sequence------------------------------------------- */
static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self)
{
PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
@@ -2211,7 +2219,7 @@ static int pyrna_prop_collection_subscript_str_lib_pair_ptr(BPy_PropertyRNA *sel
return -1;
}
- /* lib is either a valid poniter or NULL,
+ /* lib is either a valid pointer or NULL,
* either way can do direct comparison with id.lib */
RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop)
@@ -2420,7 +2428,7 @@ static PyObject *pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject
/* only get the length for negative values */
Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
if (start < 0) start += len;
- if (stop < 0) start += len;
+ if (stop < 0) stop += len;
}
if (stop - start <= 0) {
@@ -2546,7 +2554,7 @@ static int pyrna_prop_collection_ass_subscript(BPy_PropertyRNA *self, PyObject *
/* only get the length for negative values */
Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
if (start < 0) start += len;
- if (stop < 0) start += len;
+ if (stop < 0) stop += len;
}
if (stop - start <= 0) {
@@ -2982,7 +2990,7 @@ static int pyrna_struct_ass_subscript(BPy_StructRNA *self, PyObject *key, PyObje
if (rna_disallow_writes && rna_id_write_error(&self->ptr, key)) {
return -1;
}
-#endif // USE_PEDANTIC_WRITE
+#endif /* USE_PEDANTIC_WRITE */
if (group == NULL) {
PyErr_SetString(PyExc_TypeError, "bpy_struct[key] = val: id properties not supported for this type");
@@ -3441,7 +3449,7 @@ static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
return ret;
}
-//---------------getattr--------------------------------------------
+/* ---------------getattr-------------------------------------------- */
static PyObject *pyrna_struct_getattro(BPy_StructRNA *self, PyObject *pyname)
{
const char *name = _PyUnicode_AsString(pyname);
@@ -3455,7 +3463,7 @@ static PyObject *pyrna_struct_getattro(BPy_StructRNA *self, PyObject *pyname)
PyErr_SetString(PyExc_AttributeError, "bpy_struct: __getattr__ must be a string");
ret = NULL;
}
- else if (name[0] == '_') { // rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups
+ else if (name[0] == '_') { /* rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups */
/* annoying exception, maybe we need to have different types for this... */
if ((strcmp(name, "__getitem__") == 0 || strcmp(name, "__setitem__") == 0) && !RNA_struct_idprops_check(self->ptr.type)) {
PyErr_SetString(PyExc_AttributeError, "bpy_struct: no __getitem__ support for this type");
@@ -3565,7 +3573,7 @@ static int pyrna_struct_pydict_contains(PyObject *self, PyObject *pyname)
}
#endif
-//--------------- setattr-------------------------------------------
+/* --------------- setattr------------------------------------------- */
static int pyrna_is_deferred_prop(const PyObject *value)
{
return PyTuple_CheckExact(value) &&
@@ -3678,7 +3686,7 @@ static int pyrna_struct_setattro(BPy_StructRNA *self, PyObject *pyname, PyObject
if (rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
return -1;
}
-#endif // USE_PEDANTIC_WRITE
+#endif /* USE_PEDANTIC_WRITE */
if (name == NULL) {
PyErr_SetString(PyExc_AttributeError, "bpy_struct: __setattr__ must be a string");
@@ -3829,7 +3837,7 @@ static PyObject *pyrna_prop_collection_getattro(BPy_PropertyRNA *self, PyObject
#endif
}
-//--------------- setattr-------------------------------------------
+/* --------------- setattr------------------------------------------- */
static int pyrna_prop_collection_setattro(BPy_PropertyRNA *self, PyObject *pyname, PyObject *value)
{
const char *name = _PyUnicode_AsString(pyname);
@@ -3840,7 +3848,7 @@ static int pyrna_prop_collection_setattro(BPy_PropertyRNA *self, PyObject *pynam
if (rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
return -1;
}
-#endif // USE_PEDANTIC_WRITE
+#endif /* USE_PEDANTIC_WRITE */
if (name == NULL) {
PyErr_SetString(PyExc_AttributeError, "bpy_prop: __setattr__ must be a string");
@@ -3868,6 +3876,12 @@ static PyObject *pyrna_prop_collection_idprop_add(BPy_PropertyRNA *self)
{
PointerRNA r_ptr;
+#ifdef USE_PEDANTIC_WRITE
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
+ return NULL;
+ }
+#endif /* USE_PEDANTIC_WRITE */
+
RNA_property_collection_add(&self->ptr, self->prop, &r_ptr);
if (!r_ptr.data) {
PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.add(): not supported for this collection");
@@ -3882,6 +3896,12 @@ static PyObject *pyrna_prop_collection_idprop_remove(BPy_PropertyRNA *self, PyOb
{
int key = PyLong_AsLong(value);
+#ifdef USE_PEDANTIC_WRITE
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
+ return NULL;
+ }
+#endif /* USE_PEDANTIC_WRITE */
+
if (key == -1 && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.remove(): expected one int argument");
return NULL;
@@ -3897,6 +3917,12 @@ static PyObject *pyrna_prop_collection_idprop_remove(BPy_PropertyRNA *self, PyOb
static PyObject *pyrna_prop_collection_idprop_clear(BPy_PropertyRNA *self)
{
+#ifdef USE_PEDANTIC_WRITE
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
+ return NULL;
+ }
+#endif /* USE_PEDANTIC_WRITE */
+
RNA_property_collection_clear(&self->ptr, self->prop);
Py_RETURN_NONE;
@@ -3906,6 +3932,12 @@ static PyObject *pyrna_prop_collection_idprop_move(BPy_PropertyRNA *self, PyObje
{
int key = 0, pos = 0;
+#ifdef USE_PEDANTIC_WRITE
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
+ return NULL;
+ }
+#endif /* USE_PEDANTIC_WRITE */
+
if (!PyArg_ParseTuple(args, "ii", &key, &pos)) {
PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.move(): expected two ints as arguments");
return NULL;
@@ -4275,7 +4307,7 @@ static int foreach_parse_args(BPy_PropertyRNA *self, PyObject *args,
foreach_attr_type(self, *attr, raw_type, attr_tot, attr_signed);
*size = RNA_raw_type_sizeof(*raw_type);
-#if 0 // works fine but not strictly needed, we could allow RNA_property_collection_raw_* to do the checks
+#if 0 /* works fine but not strictly needed, we could allow RNA_property_collection_raw_* to do the checks */
if ((*attr_tot) < 1)
*attr_tot = 1;
@@ -4617,7 +4649,7 @@ static struct PyMethodDef pyrna_prop_collection_methods[] = {
static struct PyMethodDef pyrna_prop_collection_idprop_methods[] = {
{"add", (PyCFunction)pyrna_prop_collection_idprop_add, METH_NOARGS, NULL},
{"remove", (PyCFunction)pyrna_prop_collection_idprop_remove, METH_O, NULL},
- {"clear", (PyCFunction)pyrna_prop_collection_idprop_clear, METH_NOARGS, NULL},
+ {"clear", (PyCFunction)pyrna_prop_collection_idprop_clear, METH_NOARGS, NULL},
{"move", (PyCFunction)pyrna_prop_collection_idprop_move, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL}
};
@@ -5564,7 +5596,7 @@ PyTypeObject pyrna_prop_collection_Type = {
NULL, /* getattrfunc tp_getattr; */
NULL, /* setattrfunc tp_setattr; */
NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- NULL, /* subclassed */ /* tp_repr */
+ NULL, /* subclassed */ /* tp_repr */
/* Method suites for standard classes */
@@ -5598,7 +5630,7 @@ PyTypeObject pyrna_prop_collection_Type = {
/*** Assigned meaning in release 2.1 ***/
/*** rich comparisons ***/
- NULL, /* subclassed */ /* richcmpfunc tp_richcompare; */
+ NULL, /* subclassed */ /* richcmpfunc tp_richcompare; */
/*** weak reference enabler ***/
#ifdef USE_WEAKREFS
@@ -5683,7 +5715,7 @@ static PyTypeObject pyrna_prop_collection_idprop_Type = {
/*** Assigned meaning in release 2.1 ***/
/*** rich comparisons ***/
- NULL, /* subclassed */ /* richcmpfunc tp_richcompare; */
+ NULL, /* subclassed */ /* richcmpfunc tp_richcompare; */
/*** weak reference enabler ***/
#ifdef USE_WEAKREFS
@@ -5830,7 +5862,7 @@ PyTypeObject pyrna_prop_collection_iter_Type = {
NULL, /* getattrfunc tp_getattr; */
NULL, /* setattrfunc tp_setattr; */
NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- NULL, /* subclassed */ /* tp_repr */
+ NULL, /* subclassed */ /* tp_repr */
/* Method suites for standard classes */
@@ -5868,7 +5900,7 @@ PyTypeObject pyrna_prop_collection_iter_Type = {
/*** Assigned meaning in release 2.1 ***/
/*** rich comparisons ***/
- NULL, /* subclassed */ /* richcmpfunc tp_richcompare; */
+ NULL, /* subclassed */ /* richcmpfunc tp_richcompare; */
/*** weak reference enabler ***/
#ifdef USE_WEAKREFS
@@ -6044,8 +6076,8 @@ static PyObject *pyrna_srna_ExternalType(StructRNA *srna)
fprintf(stderr, "%s: failed to find 'bpy_types' module\n", __func__);
return NULL;
}
- bpy_types_dict = PyModule_GetDict(bpy_types); // borrow
- Py_DECREF(bpy_types); // fairly safe to assume the dict is kept
+ bpy_types_dict = PyModule_GetDict(bpy_types); /* borrow */
+ Py_DECREF(bpy_types); /* fairly safe to assume the dict is kept */
}
newclass = PyDict_GetItemString(bpy_types_dict, idname);
@@ -6134,7 +6166,7 @@ static PyObject *pyrna_srna_Subtype(StructRNA *srna)
/* srna owns one, and the other is owned by the caller */
pyrna_subtype_set_rna(newclass, srna);
- // XXX, adding this back segfaults blender on load.
+ /* XXX, adding this back segfaults blender on load. */
// Py_DECREF(newclass); /* let srna own */
}
else {
@@ -6291,7 +6323,7 @@ int pyrna_id_FromPyObject(PyObject *obj, ID **id)
void BPY_rna_init(void)
{
-#ifdef USE_MATHUTILS // register mathutils callbacks, ok to run more then once.
+#ifdef USE_MATHUTILS /* register mathutils callbacks, ok to run more then once. */
mathutils_rna_array_cb_index = Mathutils_RegisterCallback(&mathutils_rna_array_cb);
mathutils_rna_matrix_cb_index = Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
#endif
@@ -6375,7 +6407,7 @@ PyObject *BPY_rna_doc(void)
/* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a different type
* the self->ptr and self->prop are always set to the "structs" collection */
-//---------------getattr--------------------------------------------
+/* ---------------getattr-------------------------------------------- */
static PyObject *pyrna_basetype_getattro(BPy_BaseTypeRNA *self, PyObject *pyname)
{
PointerRNA newptr;
@@ -6750,7 +6782,7 @@ static int bpy_class_validate_recursive(PointerRNA *dummyptr, StructRNA *srna, v
PyObject *base_class = RNA_struct_py_type_get(srna);
PyObject *item;
int i, flag, arg_count, func_arg_count;
- const char *py_class_name = ((PyTypeObject *)py_class)->tp_name; // __name__
+ const char *py_class_name = ((PyTypeObject *)py_class)->tp_name; /* __name__ */
if (srna_base) {
if (bpy_class_validate_recursive(dummyptr, srna_base, py_data, have_function) != 0)
@@ -6919,11 +6951,9 @@ static int bpy_class_call(bContext *C, PointerRNA *ptr, FunctionRNA *func, Param
#ifdef USE_PEDANTIC_WRITE
const int is_operator = RNA_struct_is_a(ptr->type, &RNA_Operator);
- const char *func_id = RNA_function_identifier(func);
+ // const char *func_id = RNA_function_identifier(func); /* UNUSED */
/* testing, for correctness, not operator and not draw function */
- const short is_readonly = ((strncmp("draw", func_id, 4) == 0) || /* draw or draw_header */
- /*strstr("render", func_id) ||*/
- !is_operator);
+ const short is_readonly = !(RNA_function_flag(func) & FUNC_ALLOW_WRITE);
#endif
py_class = RNA_struct_py_type_get(ptr->type);
@@ -7211,10 +7241,10 @@ static void bpy_class_free(void *pyob_ptr)
gilstate = PyGILState_Ensure();
- // breaks re-registering classes
+ /* breaks re-registering classes */
// PyDict_Clear(((PyTypeObject *)self)->tp_dict);
- //
- // remove the rna attribute instead.
+
+ /* remove the rna attribute instead. */
PyDict_DelItem(((PyTypeObject *)self)->tp_dict, bpy_intern_str_bl_rna);
if (PyErr_Occurred())
PyErr_Clear();
@@ -7279,7 +7309,7 @@ void pyrna_free_types(void)
void *py_ptr = RNA_struct_py_type_get(srna);
if (py_ptr) {
-#if 0 // XXX - should be able to do this but makes python crash on exit
+#if 0 /* XXX - should be able to do this but makes python crash on exit */
bpy_class_free(py_ptr);
#endif
RNA_struct_py_type_set(srna, NULL);
diff --git a/source/blender/python/intern/bpy_rna.h b/source/blender/python/intern/bpy_rna.h
index 1fb4b116872..880ef4c2185 100644
--- a/source/blender/python/intern/bpy_rna.h
+++ b/source/blender/python/intern/bpy_rna.h
@@ -207,6 +207,7 @@ int pyrna_array_contains_py(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
int pyrna_write_check(void);
void pyrna_write_set(int val);
+void pyrna_invalidate(BPy_DummyPointerRNA *self);
int pyrna_struct_validity_check(BPy_StructRNA *pysrna);
int pyrna_prop_validity_check(BPy_PropertyRNA *self);
diff --git a/source/blender/python/intern/bpy_rna_anim.c b/source/blender/python/intern/bpy_rna_anim.c
index b7a45897668..69839514a12 100644
--- a/source/blender/python/intern/bpy_rna_anim.c
+++ b/source/blender/python/intern/bpy_rna_anim.c
@@ -52,9 +52,6 @@
#include "bpy_util.h"
#include "bpy_rna_anim.h"
-#define TRUE 1
-#define FALSE 0
-
/* for keyframes and drivers */
static int pyrna_struct_anim_args_parse(
PointerRNA *ptr, const char *error_prefix, const char *path,
diff --git a/source/blender/python/intern/bpy_rna_array.c b/source/blender/python/intern/bpy_rna_array.c
index 70815d9f8bf..e66d8f05309 100644
--- a/source/blender/python/intern/bpy_rna_array.c
+++ b/source/blender/python/intern/bpy_rna_array.c
@@ -30,6 +30,8 @@
#include "RNA_types.h"
+#include "BLI_utildefines.h"
+
#include "bpy_rna.h"
#include "BKE_global.h"
#include "MEM_guardedalloc.h"
@@ -664,7 +666,8 @@ PyObject *pyrna_py_from_array_index(BPy_PropertyArrayRNA *self, PointerRNA *ptr,
len = RNA_property_multi_array_length(ptr, prop, arraydim);
if (index >= len || index < 0) {
/* this shouldn't happen because higher level funcs must check for invalid index */
- if (G.debug & G_DEBUG_PYTHON) printf("pyrna_py_from_array_index: invalid index %d for array with length=%d\n", index, len);
+ if (G.debug & G_DEBUG_PYTHON)
+ printf("%s: invalid index %d for array with length=%d\n", __func__, index, len);
PyErr_SetString(PyExc_IndexError, "out of range");
return NULL;
diff --git a/source/blender/python/intern/bpy_traceback.h b/source/blender/python/intern/bpy_traceback.h
index 575f9824379..9ac49c370e4 100644
--- a/source/blender/python/intern/bpy_traceback.h
+++ b/source/blender/python/intern/bpy_traceback.h
@@ -28,4 +28,4 @@
void python_script_error_jump(const char *filepath, int *lineno, int *offset);
-#endif // __BPY_TRACEBACK_H__
+#endif /* __BPY_TRACEBACK_H__ */
diff --git a/source/blender/python/intern/bpy_util.c b/source/blender/python/intern/bpy_util.c
index 01495c793a8..b7994eeccdc 100644
--- a/source/blender/python/intern/bpy_util.c
+++ b/source/blender/python/intern/bpy_util.c
@@ -35,9 +35,11 @@
#include "BKE_report.h"
#include "BKE_context.h"
+#include "BLF_translation.h"
+
#include "../generic/py_capi_utils.h"
-static bContext* __py_context = NULL;
+static bContext *__py_context = NULL;
bContext *BPy_GetContext(void) { return __py_context; }
void BPy_SetContext(bContext *C) { __py_context = C; }
@@ -79,7 +81,7 @@ short BPy_reports_to_error(ReportList *reports, PyObject *exception, const short
short BPy_errors_to_report(ReportList *reports)
{
PyObject *pystring;
- PyObject *pystring_format = NULL; // workaround, see below
+ PyObject *pystring_format = NULL; /* workaround, see below */
char *cstring;
const char *filename;
@@ -98,7 +100,7 @@ short BPy_errors_to_report(ReportList *reports)
pystring = PyC_ExceptionBuffer();
if (pystring == NULL) {
- BKE_report(reports, RPT_ERROR, "unknown py-exception, couldn't convert");
+ BKE_report(reports, RPT_ERROR, "Unknown py-exception, could not convert");
return 0;
}
@@ -108,17 +110,18 @@ short BPy_errors_to_report(ReportList *reports)
cstring = _PyUnicode_AsString(pystring);
-#if 0 // ARG!. workaround for a bug in blenders use of vsnprintf
- BKE_reportf(reports, RPT_ERROR, "%s\nlocation:%s:%d\n", cstring, filename, lineno);
+#if 0 /* ARG!. workaround for a bug in blenders use of vsnprintf */
+ BKE_reportf(reports, RPT_ERROR, "%s\nlocation: %s:%d\n", cstring, filename, lineno);
#else
- pystring_format = PyUnicode_FromFormat("%s\nlocation:%s:%d\n", cstring, filename, lineno);
+ pystring_format = PyUnicode_FromFormat(TIP_("%s\nlocation: %s:%d\n"), cstring, filename, lineno);
cstring = _PyUnicode_AsString(pystring_format);
BKE_report(reports, RPT_ERROR, cstring);
#endif
-
- fprintf(stderr, "%s\nlocation:%s:%d\n", cstring, filename, lineno); // not exactly needed. just for testing
-
+
+ /* not exactly needed. just for testing */
+ fprintf(stderr, TIP_("%s\nlocation: %s:%d\n"), cstring, filename, lineno);
+
Py_DECREF(pystring);
- Py_DECREF(pystring_format); // workaround
+ Py_DECREF(pystring_format); /* workaround */
return 1;
}
diff --git a/source/blender/python/intern/gpu.h b/source/blender/python/intern/gpu.h
index 68e7fa4aa9e..f8c751f7f94 100644
--- a/source/blender/python/intern/gpu.h
+++ b/source/blender/python/intern/gpu.h
@@ -30,7 +30,7 @@
*/
/**
- * Initalizes the gpu Python module.
+ * Initializes the gpu Python module.
*/
PyObject *GPU_initPython(void);
diff --git a/source/blender/python/mathutils/mathutils.c b/source/blender/python/mathutils/mathutils.c
index c08165f9850..a4a4010005a 100644
--- a/source/blender/python/mathutils/mathutils.c
+++ b/source/blender/python/mathutils/mathutils.c
@@ -276,12 +276,12 @@ int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error
}
-//----------------------------------MATRIX FUNCTIONS--------------------
+/* ----------------------------------MATRIX FUNCTIONS-------------------- */
/* Utility functions */
-// LomontRRDCompare4, Ever Faster Float Comparisons by Randy Dillon
+/* LomontRRDCompare4, Ever Faster Float Comparisons by Randy Dillon */
#define SIGNMASK(i) (-(int)(((unsigned int)(i)) >> 31))
int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
diff --git a/source/blender/python/mathutils/mathutils_Color.c b/source/blender/python/mathutils/mathutils_Color.c
index 05fc84eaa87..747a23a719d 100644
--- a/source/blender/python/mathutils/mathutils_Color.c
+++ b/source/blender/python/mathutils/mathutils_Color.c
@@ -35,8 +35,8 @@
#define COLOR_SIZE 3
-//----------------------------------mathutils.Color() -------------------
-//makes a new color for you to play with
+/* ----------------------------------mathutils.Color() ------------------- */
+/* makes a new color for you to play with */
static PyObject *Color_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
float col[3] = {0.0f, 0.0f, 0.0f};
@@ -64,7 +64,7 @@ static PyObject *Color_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return Color_CreatePyObject(col, Py_NEW, type);
}
-//-----------------------------METHODS----------------------------
+/* -----------------------------METHODS---------------------------- */
/* note: BaseMath_ReadCallback must be called beforehand */
static PyObject *Color_ToTupleExt(ColorObject *self, int ndigits)
@@ -113,8 +113,8 @@ static PyObject *Color_deepcopy(ColorObject *self, PyObject *args)
return Color_copy(self);
}
-//----------------------------print object (internal)--------------
-//print the object to screen
+/* ----------------------------print object (internal)-------------- */
+/* print the object to screen */
static PyObject *Color_repr(ColorObject *self)
{
@@ -146,8 +146,8 @@ static PyObject *Color_str(ColorObject *self)
return mathutils_dynstr_to_py(ds); /* frees ds */
}
-//------------------------tp_richcmpr
-//returns -1 exception, 0 false, 1 true
+/* ------------------------tp_richcmpr */
+/* returns -1 exception, 0 false, 1 true */
static PyObject *Color_richcmpr(PyObject *a, PyObject *b, int op)
{
PyObject *res;
@@ -184,15 +184,15 @@ static PyObject *Color_richcmpr(PyObject *a, PyObject *b, int op)
return Py_INCREF(res), res;
}
-//---------------------SEQUENCE PROTOCOLS------------------------
-//----------------------------len(object)------------------------
-//sequence length
+/* ---------------------SEQUENCE PROTOCOLS------------------------ */
+/* ----------------------------len(object)------------------------ */
+/* sequence length */
static int Color_len(ColorObject *UNUSED(self))
{
return COLOR_SIZE;
}
-//----------------------------object[]---------------------------
-//sequence accessor (get)
+/* ----------------------------object[]--------------------------- */
+/* sequence accessor (get) */
static PyObject *Color_item(ColorObject *self, int i)
{
if (i < 0) i = COLOR_SIZE - i;
@@ -210,13 +210,13 @@ static PyObject *Color_item(ColorObject *self, int i)
return PyFloat_FromDouble(self->col[i]);
}
-//----------------------------object[]-------------------------
-//sequence accessor (set)
+/* ----------------------------object[]------------------------- */
+/* sequence accessor (set) */
static int Color_ass_item(ColorObject *self, int i, PyObject *value)
{
float f = PyFloat_AsDouble(value);
- if (f == -1 && PyErr_Occurred()) { // parsed item not a number
+ if (f == -1 && PyErr_Occurred()) { /* parsed item not a number */
PyErr_SetString(PyExc_TypeError,
"color[item] = x: "
"argument not a number");
@@ -238,8 +238,8 @@ static int Color_ass_item(ColorObject *self, int i, PyObject *value)
return 0;
}
-//----------------------------object[z:y]------------------------
-//sequence slice (get)
+/* ----------------------------object[z:y]------------------------ */
+/* sequence slice (get) */
static PyObject *Color_slice(ColorObject *self, int begin, int end)
{
PyObject *tuple;
@@ -260,8 +260,8 @@ static PyObject *Color_slice(ColorObject *self, int begin, int end)
return tuple;
}
-//----------------------------object[z:y]------------------------
-//sequence slice (set)
+/* ----------------------------object[z:y]------------------------ */
+/* sequence slice (set) */
static int Color_ass_slice(ColorObject *self, int begin, int end, PyObject *seq)
{
int i, size;
@@ -361,7 +361,7 @@ static int Color_ass_subscript(ColorObject *self, PyObject *item, PyObject *valu
}
}
-//-----------------PROTCOL DECLARATIONS--------------------------
+/* -----------------PROTCOL DECLARATIONS-------------------------- */
static PySequenceMethods Color_SeqMethods = {
(lenfunc) Color_len, /* sq_length */
(binaryfunc) NULL, /* sq_concat */
@@ -565,7 +565,7 @@ static PyObject *Color_div(PyObject *v1, PyObject *v2)
return NULL;
}
-/* mulplication in-place: obj *= obj */
+/* multiplication in-place: obj *= obj */
static PyObject *Color_imul(PyObject *v1, PyObject *v2)
{
ColorObject *color = (ColorObject *)v1;
@@ -591,7 +591,7 @@ static PyObject *Color_imul(PyObject *v1, PyObject *v2)
return v1;
}
-/* mulplication in-place: obj *= obj */
+/* multiplication in-place: obj *= obj */
static PyObject *Color_idiv(PyObject *v1, PyObject *v2)
{
ColorObject *color = (ColorObject *)v1;
@@ -792,7 +792,7 @@ static PyGetSetDef Color_getseters[] = {
};
-//-----------------------METHOD DEFINITIONS ----------------------
+/* -----------------------METHOD DEFINITIONS ---------------------- */
static struct PyMethodDef Color_methods[] = {
{"copy", (PyCFunction) Color_copy, METH_NOARGS, Color_copy_doc},
{"__copy__", (PyCFunction) Color_copy, METH_NOARGS, Color_copy_doc},
@@ -800,65 +800,65 @@ static struct PyMethodDef Color_methods[] = {
{NULL, NULL, 0, NULL}
};
-//------------------PY_OBECT DEFINITION--------------------------
+/* ------------------PY_OBECT DEFINITION-------------------------- */
PyDoc_STRVAR(color_doc,
"This object gives access to Colors in Blender."
);
PyTypeObject color_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "Color", //tp_name
- sizeof(ColorObject), //tp_basicsize
- 0, //tp_itemsize
- (destructor)BaseMathObject_dealloc, //tp_dealloc
- NULL, //tp_print
- NULL, //tp_getattr
- NULL, //tp_setattr
- NULL, //tp_compare
- (reprfunc) Color_repr, //tp_repr
- &Color_NumMethods, //tp_as_number
- &Color_SeqMethods, //tp_as_sequence
- &Color_AsMapping, //tp_as_mapping
- NULL, //tp_hash
- NULL, //tp_call
- (reprfunc) Color_str, //tp_str
- NULL, //tp_getattro
- NULL, //tp_setattro
- NULL, //tp_as_buffer
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, //tp_flags
- color_doc, //tp_doc
- (traverseproc)BaseMathObject_traverse, //tp_traverse
- (inquiry)BaseMathObject_clear, //tp_clear
- (richcmpfunc)Color_richcmpr, //tp_richcompare
- 0, //tp_weaklistoffset
- NULL, //tp_iter
- NULL, //tp_iternext
- Color_methods, //tp_methods
- NULL, //tp_members
- Color_getseters, //tp_getset
- NULL, //tp_base
- NULL, //tp_dict
- NULL, //tp_descr_get
- NULL, //tp_descr_set
- 0, //tp_dictoffset
- NULL, //tp_init
- NULL, //tp_alloc
- Color_new, //tp_new
- NULL, //tp_free
- NULL, //tp_is_gc
- NULL, //tp_bases
- NULL, //tp_mro
- NULL, //tp_cache
- NULL, //tp_subclasses
- NULL, //tp_weaklist
- NULL //tp_del
+ "Color", /* tp_name */
+ sizeof(ColorObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)BaseMathObject_dealloc, /* tp_dealloc */
+ NULL, /* tp_print */
+ NULL, /* tp_getattr */
+ NULL, /* tp_setattr */
+ NULL, /* tp_compare */
+ (reprfunc) Color_repr, /* tp_repr */
+ &Color_NumMethods, /* tp_as_number */
+ &Color_SeqMethods, /* tp_as_sequence */
+ &Color_AsMapping, /* tp_as_mapping */
+ NULL, /* tp_hash */
+ NULL, /* tp_call */
+ (reprfunc) Color_str, /* tp_str */
+ NULL, /* tp_getattro */
+ NULL, /* tp_setattro */
+ NULL, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ color_doc, /* tp_doc */
+ (traverseproc)BaseMathObject_traverse, /* tp_traverse */
+ (inquiry)BaseMathObject_clear, /* tp_clear */
+ (richcmpfunc)Color_richcmpr, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ NULL, /* tp_iter */
+ NULL, /* tp_iternext */
+ Color_methods, /* tp_methods */
+ NULL, /* tp_members */
+ Color_getseters, /* tp_getset */
+ NULL, /* tp_base */
+ NULL, /* tp_dict */
+ NULL, /* tp_descr_get */
+ NULL, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ NULL, /* tp_init */
+ NULL, /* tp_alloc */
+ Color_new, /* tp_new */
+ NULL, /* tp_free */
+ NULL, /* tp_is_gc */
+ NULL, /* tp_bases */
+ NULL, /* tp_mro */
+ NULL, /* tp_cache */
+ NULL, /* tp_subclasses */
+ NULL, /* tp_weaklist */
+ NULL /* tp_del */
};
-//------------------------Color_CreatePyObject (internal)-------------
-//creates a new color object
+/* ------------------------Color_CreatePyObject (internal)------------- */
+/* creates a new color object */
/* pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
* (i.e. it was allocated elsewhere by MEM_mallocN())
* pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
* (i.e. it must be created here with PyMEM_malloc())*/
-PyObject *Color_CreatePyObject(float *col, int type, PyTypeObject *base_type)
+PyObject *Color_CreatePyObject(float col[3], int type, PyTypeObject *base_type)
{
ColorObject *self;
diff --git a/source/blender/python/mathutils/mathutils_Color.h b/source/blender/python/mathutils/mathutils_Color.h
index eff09c25a99..1c75766c2a9 100644
--- a/source/blender/python/mathutils/mathutils_Color.h
+++ b/source/blender/python/mathutils/mathutils_Color.h
@@ -46,8 +46,8 @@ typedef struct {
* be stored in py_data) or be a wrapper for data allocated through
* blender (stored in blend_data). This is an either/or struct not both*/
-//prototypes
-PyObject *Color_CreatePyObject(float *col, int type, PyTypeObject *base_type);
+/* prototypes */
+PyObject *Color_CreatePyObject(float col[3], int type, PyTypeObject *base_type);
PyObject *Color_CreatePyObject_cb(PyObject *cb_user,
unsigned char cb_type, unsigned char cb_subtype);
diff --git a/source/blender/python/mathutils/mathutils_Euler.c b/source/blender/python/mathutils/mathutils_Euler.c
index 468ef3788c1..3592e1084fb 100644
--- a/source/blender/python/mathutils/mathutils_Euler.c
+++ b/source/blender/python/mathutils/mathutils_Euler.c
@@ -39,8 +39,8 @@
#define EULER_SIZE 3
-//----------------------------------mathutils.Euler() -------------------
-//makes a new euler for you to play with
+/* ----------------------------------mathutils.Euler() ------------------- */
+/* makes a new euler for you to play with */
static PyObject *Euler_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *seq = NULL;
@@ -122,8 +122,8 @@ static PyObject *Euler_ToTupleExt(EulerObject *self, int ndigits)
return ret;
}
-//-----------------------------METHODS----------------------------
-//return a quaternion representation of the euler
+/* -----------------------------METHODS----------------------------
+ * return a quaternion representation of the euler */
PyDoc_STRVAR(Euler_to_quaternion_doc,
".. method:: to_quaternion()\n"
@@ -145,7 +145,7 @@ static PyObject *Euler_to_quaternion(EulerObject *self)
return Quaternion_CreatePyObject(quat, Py_NEW, NULL);
}
-//return a matrix representation of the euler
+/* return a matrix representation of the euler */
PyDoc_STRVAR(Euler_to_matrix_doc,
".. method:: to_matrix()\n"
"\n"
@@ -277,8 +277,8 @@ static PyObject *Euler_make_compatible(EulerObject *self, PyObject *value)
Py_RETURN_NONE;
}
-//----------------------------Euler.rotate()-----------------------
-// return a copy of the euler
+/* ----------------------------Euler.rotate()-----------------------
+ * return a copy of the euler */
PyDoc_STRVAR(Euler_copy_doc,
".. function:: copy()\n"
@@ -305,8 +305,8 @@ static PyObject *Euler_deepcopy(EulerObject *self, PyObject *args)
return Euler_copy(self);
}
-//----------------------------print object (internal)--------------
-//print the object to screen
+/* ----------------------------print object (internal)--------------
+ * print the object to screen */
static PyObject *Euler_repr(EulerObject *self)
{
@@ -374,15 +374,15 @@ static PyObject *Euler_richcmpr(PyObject *a, PyObject *b, int op)
return Py_INCREF(res), res;
}
-//---------------------SEQUENCE PROTOCOLS------------------------
-//----------------------------len(object)------------------------
-//sequence length
+/* ---------------------SEQUENCE PROTOCOLS------------------------ */
+/* ----------------------------len(object)------------------------ */
+/* sequence length */
static int Euler_len(EulerObject *UNUSED(self))
{
return EULER_SIZE;
}
-//----------------------------object[]---------------------------
-//sequence accessor (get)
+/* ----------------------------object[]--------------------------- */
+/* sequence accessor (get) */
static PyObject *Euler_item(EulerObject *self, int i)
{
if (i < 0) i = EULER_SIZE - i;
@@ -400,13 +400,13 @@ static PyObject *Euler_item(EulerObject *self, int i)
return PyFloat_FromDouble(self->eul[i]);
}
-//----------------------------object[]-------------------------
-//sequence accessor (set)
+/* ----------------------------object[]------------------------- */
+/* sequence accessor (set) */
static int Euler_ass_item(EulerObject *self, int i, PyObject *value)
{
float f = PyFloat_AsDouble(value);
- if (f == -1 && PyErr_Occurred()) { // parsed item not a number
+ if (f == -1 && PyErr_Occurred()) { /* parsed item not a number */
PyErr_SetString(PyExc_TypeError,
"euler[attribute] = x: "
"argument not a number");
@@ -429,8 +429,8 @@ static int Euler_ass_item(EulerObject *self, int i, PyObject *value)
return 0;
}
-//----------------------------object[z:y]------------------------
-//sequence slice (get)
+/* ----------------------------object[z:y]------------------------ */
+/* sequence slice (get) */
static PyObject *Euler_slice(EulerObject *self, int begin, int end)
{
PyObject *tuple;
@@ -451,8 +451,8 @@ static PyObject *Euler_slice(EulerObject *self, int begin, int end)
return tuple;
}
-//----------------------------object[z:y]------------------------
-//sequence slice (set)
+/* ----------------------------object[z:y]------------------------ */
+/* sequence slice (set) */
static int Euler_ass_slice(EulerObject *self, int begin, int end, PyObject *seq)
{
int i, size;
@@ -553,7 +553,7 @@ static int Euler_ass_subscript(EulerObject *self, PyObject *item, PyObject *valu
}
}
-//-----------------PROTCOL DECLARATIONS--------------------------
+/* -----------------PROTCOL DECLARATIONS-------------------------- */
static PySequenceMethods Euler_SeqMethods = {
(lenfunc) Euler_len, /* sq_length */
(binaryfunc) NULL, /* sq_concat */
@@ -629,7 +629,7 @@ static PyGetSetDef Euler_getseters[] = {
};
-//-----------------------METHOD DEFINITIONS ----------------------
+/* -----------------------METHOD DEFINITIONS ---------------------- */
static struct PyMethodDef Euler_methods[] = {
{"zero", (PyCFunction) Euler_zero, METH_NOARGS, Euler_zero_doc},
{"to_matrix", (PyCFunction) Euler_to_matrix, METH_NOARGS, Euler_to_matrix_doc},
@@ -643,60 +643,60 @@ static struct PyMethodDef Euler_methods[] = {
{NULL, NULL, 0, NULL}
};
-//------------------PY_OBECT DEFINITION--------------------------
+/* ------------------PY_OBECT DEFINITION-------------------------- */
PyDoc_STRVAR(euler_doc,
"This object gives access to Eulers in Blender."
);
PyTypeObject euler_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "Euler", //tp_name
- sizeof(EulerObject), //tp_basicsize
- 0, //tp_itemsize
- (destructor)BaseMathObject_dealloc, //tp_dealloc
- NULL, //tp_print
- NULL, //tp_getattr
- NULL, //tp_setattr
- NULL, //tp_compare
- (reprfunc) Euler_repr, //tp_repr
- NULL, //tp_as_number
- &Euler_SeqMethods, //tp_as_sequence
- &Euler_AsMapping, //tp_as_mapping
- NULL, //tp_hash
- NULL, //tp_call
- (reprfunc) Euler_str, //tp_str
- NULL, //tp_getattro
- NULL, //tp_setattro
- NULL, //tp_as_buffer
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, //tp_flags
- euler_doc, //tp_doc
- (traverseproc)BaseMathObject_traverse, //tp_traverse
- (inquiry)BaseMathObject_clear, //tp_clear
- (richcmpfunc)Euler_richcmpr, //tp_richcompare
- 0, //tp_weaklistoffset
- NULL, //tp_iter
- NULL, //tp_iternext
- Euler_methods, //tp_methods
- NULL, //tp_members
- Euler_getseters, //tp_getset
- NULL, //tp_base
- NULL, //tp_dict
- NULL, //tp_descr_get
- NULL, //tp_descr_set
- 0, //tp_dictoffset
- NULL, //tp_init
- NULL, //tp_alloc
- Euler_new, //tp_new
- NULL, //tp_free
- NULL, //tp_is_gc
- NULL, //tp_bases
- NULL, //tp_mro
- NULL, //tp_cache
- NULL, //tp_subclasses
- NULL, //tp_weaklist
- NULL //tp_del
+ "Euler", /* tp_name */
+ sizeof(EulerObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)BaseMathObject_dealloc, /* tp_dealloc */
+ NULL, /* tp_print */
+ NULL, /* tp_getattr */
+ NULL, /* tp_setattr */
+ NULL, /* tp_compare */
+ (reprfunc) Euler_repr, /* tp_repr */
+ NULL, /* tp_as_number */
+ &Euler_SeqMethods, /* tp_as_sequence */
+ &Euler_AsMapping, /* tp_as_mapping */
+ NULL, /* tp_hash */
+ NULL, /* tp_call */
+ (reprfunc) Euler_str, /* tp_str */
+ NULL, /* tp_getattro */
+ NULL, /* tp_setattro */
+ NULL, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ euler_doc, /* tp_doc */
+ (traverseproc)BaseMathObject_traverse, /* tp_traverse */
+ (inquiry)BaseMathObject_clear, /* tp_clear */
+ (richcmpfunc)Euler_richcmpr, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ NULL, /* tp_iter */
+ NULL, /* tp_iternext */
+ Euler_methods, /* tp_methods */
+ NULL, /* tp_members */
+ Euler_getseters, /* tp_getset */
+ NULL, /* tp_base */
+ NULL, /* tp_dict */
+ NULL, /* tp_descr_get */
+ NULL, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ NULL, /* tp_init */
+ NULL, /* tp_alloc */
+ Euler_new, /* tp_new */
+ NULL, /* tp_free */
+ NULL, /* tp_is_gc */
+ NULL, /* tp_bases */
+ NULL, /* tp_mro */
+ NULL, /* tp_cache */
+ NULL, /* tp_subclasses */
+ NULL, /* tp_weaklist */
+ NULL /* tp_del */
};
-//------------------------Euler_CreatePyObject (internal)-------------
-//creates a new euler object
+/* ------------------------Euler_CreatePyObject (internal)------------- */
+/* creates a new euler object */
/* pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
* (i.e. it was allocated elsewhere by MEM_mallocN())
* pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
diff --git a/source/blender/python/mathutils/mathutils_Euler.h b/source/blender/python/mathutils/mathutils_Euler.h
index e04d45e4630..69e4c086d03 100644
--- a/source/blender/python/mathutils/mathutils_Euler.h
+++ b/source/blender/python/mathutils/mathutils_Euler.h
@@ -47,7 +47,7 @@ typedef struct {
* be stored in py_data) or be a wrapper for data allocated through
* blender (stored in blend_data). This is an either/or struct not both */
-//prototypes
+/* prototypes */
PyObject *Euler_CreatePyObject(float *eul, const short order, int type, PyTypeObject *base_type);
PyObject *Euler_CreatePyObject_cb(PyObject *cb_user, const short order,
unsigned char cb_type, unsigned char cb_subtype);
diff --git a/source/blender/python/mathutils/mathutils_Matrix.c b/source/blender/python/mathutils/mathutils_Matrix.c
index be519ded88e..b9f0ce9ad96 100644
--- a/source/blender/python/mathutils/mathutils_Matrix.c
+++ b/source/blender/python/mathutils/mathutils_Matrix.c
@@ -182,7 +182,7 @@ static int mathutils_matrix_col_get(BaseMathObject *bmo, int col)
return -1;
/* for 'translation' size will always be '3' even on 4x4 vec */
- num_row = MIN2(self->num_row, ((VectorObject *)bmo)->size);
+ num_row = min_ii(self->num_row, ((VectorObject *)bmo)->size);
for (row = 0; row < num_row; row++) {
bmo->data[row] = MATRIX_ITEM(self, row, col);
@@ -203,7 +203,7 @@ static int mathutils_matrix_col_set(BaseMathObject *bmo, int col)
return -1;
/* for 'translation' size will always be '3' even on 4x4 vec */
- num_row = MIN2(self->num_row, ((VectorObject *)bmo)->size);
+ num_row = min_ii(self->num_row, ((VectorObject *)bmo)->size);
for (row = 0; row < num_row; row++) {
MATRIX_ITEM(self, row, col) = bmo->data[row];
@@ -329,9 +329,9 @@ Mathutils_Callback mathutils_matrix_translation_cb = {
/* matrix column callbacks, this is so you can do matrix.translation = Vector() */
-//----------------------------------mathutils.Matrix() -----------------
-//mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc.
-//create a new matrix type
+/* ----------------------------------mathutils.Matrix() ----------------- */
+/* mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc. */
+/* create a new matrix type */
static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
if (kwds && PyDict_Size(kwds)) {
@@ -384,13 +384,19 @@ static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *matrix__apply_to_copy(PyNoArgsFunction matrix_func, MatrixObject *self)
{
PyObject *ret = Matrix_copy(self);
- PyObject *ret_dummy = matrix_func(ret);
- if (ret_dummy) {
- Py_DECREF(ret_dummy);
- return (PyObject *)ret;
+ if (ret) {
+ PyObject *ret_dummy = matrix_func(ret);
+ if (ret_dummy) {
+ Py_DECREF(ret_dummy);
+ return (PyObject *)ret;
+ }
+ else { /* error */
+ Py_DECREF(ret);
+ return NULL;
+ }
}
- else { /* error */
- Py_DECREF(ret);
+ else {
+ /* copy may fail if the read callback errors out */
return NULL;
}
}
@@ -410,7 +416,7 @@ static void matrix_3x3_as_4x4(float mat[16])
/*-----------------------CLASS-METHODS----------------------------*/
-//mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc.
+/* mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc. */
PyDoc_STRVAR(C_Matrix_Identity_doc,
".. classmethod:: Identity(size)\n"
"\n"
@@ -518,7 +524,7 @@ static PyObject *C_Matrix_Rotation(PyObject *cls, PyObject *args)
const float angle_cos = cosf(angle);
const float angle_sin = sinf(angle);
- //2D rotation matrix
+ /* 2D rotation matrix */
mat[0] = angle_cos;
mat[1] = angle_sin;
mat[2] = -angle_sin;
@@ -532,7 +538,7 @@ static PyObject *C_Matrix_Rotation(PyObject *cls, PyObject *args)
if (matSize == 4) {
matrix_3x3_as_4x4(mat);
}
- //pass to matrix creation
+ /* pass to matrix creation */
return Matrix_CreatePyObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
}
@@ -556,8 +562,8 @@ static PyObject *C_Matrix_Translation(PyObject *cls, PyObject *value)
return Matrix_CreatePyObject(&mat[0][0], 4, 4, Py_NEW, (PyTypeObject *)cls);
}
-//----------------------------------mathutils.Matrix.Scale() -------------
-//mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc.
+/* ----------------------------------mathutils.Matrix.Scale() ------------- */
+/* mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc. */
PyDoc_STRVAR(C_Matrix_Scale_doc,
".. classmethod:: Scale(factor, size, axis)\n"
"\n"
@@ -601,7 +607,7 @@ static PyObject *C_Matrix_Scale(PyObject *cls, PyObject *args)
return NULL;
}
}
- if (vec == NULL) { //scaling along axis
+ if (vec == NULL) { /* scaling along axis */
if (matSize == 2) {
mat[0] = factor;
mat[3] = factor;
@@ -645,11 +651,11 @@ static PyObject *C_Matrix_Scale(PyObject *cls, PyObject *args)
if (matSize == 4) {
matrix_3x3_as_4x4(mat);
}
- //pass to matrix creation
+ /* pass to matrix creation */
return Matrix_CreatePyObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
}
-//----------------------------------mathutils.Matrix.OrthoProjection() ---
-//mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc.
+/* ----------------------------------mathutils.Matrix.OrthoProjection() --- */
+/* mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc. */
PyDoc_STRVAR(C_Matrix_OrthoProjection_doc,
".. classmethod:: OrthoProjection(axis, size)\n"
"\n"
@@ -685,7 +691,7 @@ static PyObject *C_Matrix_OrthoProjection(PyObject *cls, PyObject *args)
return NULL;
}
- if (PyUnicode_Check(axis)) { //ortho projection onto cardinal plane
+ if (PyUnicode_Check(axis)) { /* ortho projection onto cardinal plane */
Py_ssize_t plane_len;
const char *plane = _PyUnicode_AsStringAndSize(axis, &plane_len);
if (matSize == 2) {
@@ -726,7 +732,7 @@ static PyObject *C_Matrix_OrthoProjection(PyObject *cls, PyObject *args)
}
}
else {
- //arbitrary plane
+ /* arbitrary plane */
int vec_size = (matSize == 2 ? 2 : 3);
float tvec[4];
@@ -737,7 +743,7 @@ static PyObject *C_Matrix_OrthoProjection(PyObject *cls, PyObject *args)
return NULL;
}
- //normalize arbitrary axis
+ /* normalize arbitrary axis */
for (x = 0; x < vec_size; x++) {
norm += tvec[x] * tvec[x];
}
@@ -766,7 +772,7 @@ static PyObject *C_Matrix_OrthoProjection(PyObject *cls, PyObject *args)
if (matSize == 4) {
matrix_3x3_as_4x4(mat);
}
- //pass to matrix creation
+ /* pass to matrix creation */
return Matrix_CreatePyObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
}
@@ -869,7 +875,7 @@ static PyObject *C_Matrix_Shear(PyObject *cls, PyObject *args)
if (matSize == 4) {
matrix_3x3_as_4x4(mat);
}
- //pass to matrix creation
+ /* pass to matrix creation */
return Matrix_CreatePyObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
}
@@ -1196,17 +1202,27 @@ static PyObject *Matrix_invert(MatrixObject *self)
if (det != 0) {
/* calculate the classical adjoint */
- if (self->num_col == 2) {
- mat[0] = MATRIX_ITEM(self, 1, 1);
- mat[1] = -MATRIX_ITEM(self, 0, 1);
- mat[2] = -MATRIX_ITEM(self, 1, 0);
- mat[3] = MATRIX_ITEM(self, 0, 0);
- }
- else if (self->num_col == 3) {
- adjoint_m3_m3((float (*)[3])mat, (float (*)[3])self->matrix);
- }
- else if (self->num_col == 4) {
- adjoint_m4_m4((float (*)[4])mat, (float (*)[4])self->matrix);
+ switch (self->num_col) {
+ case 2:
+ {
+ adjoint_m2_m2((float (*)[2])mat, (float (*)[2])self->matrix);
+ break;
+ }
+ case 3:
+ {
+ adjoint_m3_m3((float (*)[3])mat, (float (*)[3])self->matrix);
+ break;
+ }
+ case 4:
+ {
+ adjoint_m4_m4((float (*)[4])mat, (float (*)[4])self->matrix);
+ break;
+ }
+ default:
+ PyErr_Format(PyExc_TypeError,
+ "Matrix invert(ed): size (%d) unsupported",
+ (int)self->num_col);
+ return NULL;
}
/* divide by determinate */
for (x = 0; x < (self->num_col * self->num_row); x++) {
@@ -1236,7 +1252,7 @@ PyDoc_STRVAR(Matrix_inverted_doc,
"\n"
" Return an inverted copy of the matrix.\n"
"\n"
-" :return: the inverted matrix.\n"
+" :return: the inverted matrix.\n"
" :rtype: :class:`Matrix`\n"
"\n"
" .. note:: When the matrix cant be inverted a :exc:`ValueError` exception is raised.\n"
@@ -1246,6 +1262,77 @@ static PyObject *Matrix_inverted(MatrixObject *self)
return matrix__apply_to_copy((PyNoArgsFunction)Matrix_invert, self);
}
+/*---------------------------matrix.adjugate() ---------------------*/
+PyDoc_STRVAR(Matrix_adjugate_doc,
+".. method:: adjugate()\n"
+"\n"
+" Set the matrix to its adjugate.\n"
+"\n"
+" .. note:: When the matrix cant be adjugated a :exc:`ValueError` exception is raised.\n"
+"\n"
+" .. seealso:: <http://en.wikipedia.org/wiki/Adjugate_matrix>\n"
+);
+static PyObject *Matrix_adjugate(MatrixObject *self)
+{
+ if (BaseMath_ReadCallback(self) == -1)
+ return NULL;
+
+ if (self->num_col != self->num_row) {
+ PyErr_SetString(PyExc_TypeError,
+ "Matrix.adjugate(d): "
+ "only square matrices are supported");
+ return NULL;
+ }
+
+ /* calculate the classical adjoint */
+ switch (self->num_col) {
+ case 2:
+ {
+ float mat[2][2];
+ adjoint_m2_m2(mat, (float (*)[2])self->matrix);
+ copy_v4_v4((float *)self->matrix, (float *)mat);
+ break;
+ }
+ case 3:
+ {
+ float mat[3][3];
+ adjoint_m3_m3(mat, (float (*)[3])self->matrix);
+ copy_m3_m3((float (*)[3])self->matrix, mat);
+ break;
+ }
+ case 4:
+ {
+ float mat[4][4];
+ adjoint_m4_m4(mat, (float (*)[4])self->matrix);
+ copy_m4_m4((float (*)[4])self->matrix, mat);
+ break;
+ }
+ default:
+ PyErr_Format(PyExc_TypeError,
+ "Matrix adjugate(d): size (%d) unsupported",
+ (int)self->num_col);
+ return NULL;
+ }
+
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
+}
+
+PyDoc_STRVAR(Matrix_adjugated_doc,
+".. method:: adjugated()\n"
+"\n"
+" Return an adjugated copy of the matrix.\n"
+"\n"
+" :return: the adjugated matrix.\n"
+" :rtype: :class:`Matrix`\n"
+"\n"
+" .. note:: When the matrix cant be adjugated a :exc:`ValueError` exception is raised.\n"
+);
+static PyObject *Matrix_adjugated(MatrixObject *self)
+{
+ return matrix__apply_to_copy((PyNoArgsFunction)Matrix_adjugate, self);
+}
+
PyDoc_STRVAR(Matrix_rotate_doc,
".. method:: rotate(other)\n"
"\n"
@@ -1579,7 +1666,7 @@ static PyObject *Matrix_str(MatrixObject *self)
maxsize[col] = 0;
for (row = 0; row < self->num_row; row++) {
int size = BLI_snprintf(dummy_buf, sizeof(dummy_buf), "%.4f", MATRIX_ITEM(self, row, col));
- maxsize[col] = MAX2(maxsize[col], size);
+ maxsize[col] = max_ii(maxsize[col], size);
}
}
@@ -1875,7 +1962,7 @@ static PyObject *Matrix_sub(PyObject *m1, PyObject *m2)
return Matrix_CreatePyObject(mat, mat1->num_col, mat1->num_row, Py_NEW, Py_TYPE(mat1));
}
/*------------------------obj * obj------------------------------
- * mulplication */
+ * multiplication */
static PyObject *matrix_mul_float(MatrixObject *mat, const float scalar)
{
float tmat[16];
@@ -1921,7 +2008,7 @@ static PyObject *Matrix_mul(PyObject *m1, PyObject *m2)
for (row = 0; row < mat1->num_row; row++) {
double dot = 0.0f;
for (item = 0; item < mat1->num_col; item++) {
- dot += MATRIX_ITEM(mat1, row, item) * MATRIX_ITEM(mat2, item, col);
+ dot += (double)(MATRIX_ITEM(mat1, row, item) * MATRIX_ITEM(mat2, item, col));
}
mat[(col * mat1->num_row) + row] = (float)dot;
}
@@ -2281,6 +2368,8 @@ static struct PyMethodDef Matrix_methods[] = {
{"transposed", (PyCFunction) Matrix_transposed, METH_NOARGS, Matrix_transposed_doc},
{"invert", (PyCFunction) Matrix_invert, METH_NOARGS, Matrix_invert_doc},
{"inverted", (PyCFunction) Matrix_inverted, METH_NOARGS, Matrix_inverted_doc},
+ {"adjugate", (PyCFunction) Matrix_adjugate, METH_NOARGS, Matrix_adjugate_doc},
+ {"adjugated", (PyCFunction) Matrix_adjugated, METH_NOARGS, Matrix_adjugated_doc},
{"to_3x3", (PyCFunction) Matrix_to_3x3, METH_NOARGS, Matrix_to_3x3_doc},
/* TODO. {"resize_3x3", (PyCFunction) Matrix_resize3x3, METH_NOARGS, Matrix_resize3x3_doc}, */
{"to_4x4", (PyCFunction) Matrix_to_4x4, METH_NOARGS, Matrix_to_4x4_doc},
@@ -2335,8 +2424,8 @@ PyTypeObject matrix_Type = {
NULL, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
matrix_doc, /*tp_doc*/
- (traverseproc)BaseMathObject_traverse, //tp_traverse
- (inquiry)BaseMathObject_clear, //tp_clear
+ (traverseproc)BaseMathObject_traverse, /* tp_traverse */
+ (inquiry)BaseMathObject_clear, /*tp_clear*/
(richcmpfunc)Matrix_richcmpr, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
NULL, /*tp_iter*/
@@ -2635,8 +2724,8 @@ PyTypeObject matrix_access_Type = {
NULL, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
NULL, /*tp_doc*/
- (traverseproc)MatrixAccess_traverse, //tp_traverse
- (inquiry)MatrixAccess_clear, //tp_clear
+ (traverseproc)MatrixAccess_traverse,/*tp_traverse*/
+ (inquiry)MatrixAccess_clear, /*tp_clear*/
NULL /* (richcmpfunc)MatrixAccess_richcmpr */ /* TODO*/, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
(getiterfunc)MatrixAccess_iter, /* getiterfunc tp_iter; */
diff --git a/source/blender/python/mathutils/mathutils_Quaternion.c b/source/blender/python/mathutils/mathutils_Quaternion.c
index b595dab494d..b9aba995973 100644
--- a/source/blender/python/mathutils/mathutils_Quaternion.c
+++ b/source/blender/python/mathutils/mathutils_Quaternion.c
@@ -44,7 +44,7 @@ static void quat__axis_angle_sanitize(float axis[3], float *angle);
static PyObject *Quaternion_copy(QuaternionObject *self);
static PyObject *Quaternion_deepcopy(QuaternionObject *self, PyObject *args);
-//-----------------------------METHODS------------------------------
+/* -----------------------------METHODS------------------------------ */
/* note: BaseMath_ReadCallback must be called beforehand */
static PyObject *Quaternion_to_tuple_ext(QuaternionObject *self, int ndigits)
@@ -124,7 +124,7 @@ static PyObject *Quaternion_to_euler(QuaternionObject *self, PyObject *args)
return Euler_CreatePyObject(eul, order, Py_NEW, NULL);
}
-//----------------------------Quaternion.toMatrix()------------------
+
PyDoc_STRVAR(Quaternion_to_matrix_doc,
".. method:: to_matrix()\n"
"\n"
@@ -144,7 +144,6 @@ static PyObject *Quaternion_to_matrix(QuaternionObject *self)
return Matrix_CreatePyObject(mat, 3, 3, Py_NEW, NULL);
}
-//----------------------------Quaternion.toMatrix()------------------
PyDoc_STRVAR(Quaternion_to_axis_angle_doc,
".. method:: to_axis_angle()\n"
"\n"
@@ -176,8 +175,6 @@ static PyObject *Quaternion_to_axis_angle(QuaternionObject *self)
return ret;
}
-
-//----------------------------Quaternion.cross(other)------------------
PyDoc_STRVAR(Quaternion_cross_doc,
".. method:: cross(other)\n"
"\n"
@@ -205,7 +202,6 @@ static PyObject *Quaternion_cross(QuaternionObject *self, PyObject *value)
return Quaternion_CreatePyObject(quat, Py_NEW, Py_TYPE(self));
}
-//----------------------------Quaternion.dot(other)------------------
PyDoc_STRVAR(Quaternion_dot_doc,
".. method:: dot(other)\n"
"\n"
@@ -335,8 +331,8 @@ static PyObject *Quaternion_rotate(QuaternionObject *self, PyObject *value)
Py_RETURN_NONE;
}
-//----------------------------Quaternion.normalize()----------------
-//normalize the axis of rotation of [theta, vector]
+/* ----------------------------Quaternion.normalize()---------------- */
+/* normalize the axis of rotation of [theta, vector] */
PyDoc_STRVAR(Quaternion_normalize_doc,
".. function:: normalize()\n"
"\n"
@@ -365,7 +361,6 @@ static PyObject *Quaternion_normalized(QuaternionObject *self)
return quat__apply_to_copy((PyNoArgsFunction)Quaternion_normalize, self);
}
-//----------------------------Quaternion.invert()------------------
PyDoc_STRVAR(Quaternion_invert_doc,
".. function:: invert()\n"
"\n"
@@ -394,7 +389,6 @@ static PyObject *Quaternion_inverted(QuaternionObject *self)
return quat__apply_to_copy((PyNoArgsFunction)Quaternion_invert, self);
}
-//----------------------------Quaternion.identity()-----------------
PyDoc_STRVAR(Quaternion_identity_doc,
".. function:: identity()\n"
"\n"
@@ -413,7 +407,7 @@ static PyObject *Quaternion_identity(QuaternionObject *self)
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
-//----------------------------Quaternion.negate()-------------------
+
PyDoc_STRVAR(Quaternion_negate_doc,
".. function:: negate()\n"
"\n"
@@ -432,7 +426,7 @@ static PyObject *Quaternion_negate(QuaternionObject *self)
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
-//----------------------------Quaternion.conjugate()----------------
+
PyDoc_STRVAR(Quaternion_conjugate_doc,
".. function:: conjugate()\n"
"\n"
@@ -461,7 +455,6 @@ static PyObject *Quaternion_conjugated(QuaternionObject *self)
return quat__apply_to_copy((PyNoArgsFunction)Quaternion_conjugate, self);
}
-//----------------------------Quaternion.copy()----------------
PyDoc_STRVAR(Quaternion_copy_doc,
".. function:: copy()\n"
"\n"
@@ -487,8 +480,7 @@ static PyObject *Quaternion_deepcopy(QuaternionObject *self, PyObject *args)
return Quaternion_copy(self);
}
-//----------------------------print object (internal)--------------
-//print the object to screen
+/* print the object to screen */
static PyObject *Quaternion_repr(QuaternionObject *self)
{
PyObject *ret, *tuple;
@@ -555,15 +547,15 @@ static PyObject *Quaternion_richcmpr(PyObject *a, PyObject *b, int op)
return Py_INCREF(res), res;
}
-//---------------------SEQUENCE PROTOCOLS------------------------
-//----------------------------len(object)------------------------
-//sequence length
+/* ---------------------SEQUENCE PROTOCOLS------------------------ */
+/* ----------------------------len(object)------------------------ */
+/* sequence length */
static int Quaternion_len(QuaternionObject *UNUSED(self))
{
return QUAT_SIZE;
}
-//----------------------------object[]---------------------------
-//sequence accessor (get)
+/* ----------------------------object[]--------------------------- */
+/* sequence accessor (get) */
static PyObject *Quaternion_item(QuaternionObject *self, int i)
{
if (i < 0) i = QUAT_SIZE - i;
@@ -581,8 +573,8 @@ static PyObject *Quaternion_item(QuaternionObject *self, int i)
return PyFloat_FromDouble(self->quat[i]);
}
-//----------------------------object[]-------------------------
-//sequence accessor (set)
+/* ----------------------------object[]------------------------- */
+/* sequence accessor (set) */
static int Quaternion_ass_item(QuaternionObject *self, int i, PyObject *ob)
{
float scalar = (float)PyFloat_AsDouble(ob);
@@ -608,8 +600,8 @@ static int Quaternion_ass_item(QuaternionObject *self, int i, PyObject *ob)
return 0;
}
-//----------------------------object[z:y]------------------------
-//sequence slice (get)
+/* ----------------------------object[z:y]------------------------ */
+/* sequence slice (get) */
static PyObject *Quaternion_slice(QuaternionObject *self, int begin, int end)
{
PyObject *tuple;
@@ -630,8 +622,8 @@ static PyObject *Quaternion_slice(QuaternionObject *self, int begin, int end)
return tuple;
}
-//----------------------------object[z:y]------------------------
-//sequence slice (set)
+/* ----------------------------object[z:y]------------------------ */
+/* sequence slice (set) */
static int Quaternion_ass_slice(QuaternionObject *self, int begin, int end, PyObject *seq)
{
int i, size;
@@ -734,9 +726,9 @@ static int Quaternion_ass_subscript(QuaternionObject *self, PyObject *item, PyOb
}
}
-//------------------------NUMERIC PROTOCOLS----------------------
-//------------------------obj + obj------------------------------
-//addition
+/* ------------------------NUMERIC PROTOCOLS---------------------- */
+/* ------------------------obj + obj------------------------------ */
+/* addition */
static PyObject *Quaternion_add(PyObject *q1, PyObject *q2)
{
float quat[QUAT_SIZE];
@@ -758,8 +750,8 @@ static PyObject *Quaternion_add(PyObject *q1, PyObject *q2)
add_qt_qtqt(quat, quat1->quat, quat2->quat, 1.0f);
return Quaternion_CreatePyObject(quat, Py_NEW, Py_TYPE(q1));
}
-//------------------------obj - obj------------------------------
-//subtraction
+/* ------------------------obj - obj------------------------------ */
+/* subtraction */
static PyObject *Quaternion_sub(PyObject *q1, PyObject *q2)
{
int x;
@@ -795,8 +787,8 @@ static PyObject *quat_mul_float(QuaternionObject *quat, const float scalar)
return Quaternion_CreatePyObject(tquat, Py_NEW, Py_TYPE(quat));
}
-//------------------------obj * obj------------------------------
-//mulplication
+/*------------------------obj * obj------------------------------
+ * multiplication */
static PyObject *Quaternion_mul(PyObject *q1, PyObject *q2)
{
float quat[QUAT_SIZE], scalar;
@@ -875,7 +867,7 @@ static PyObject *Quaternion_neg(QuaternionObject *self)
}
-//-----------------PROTOCOL DECLARATIONS--------------------------
+/* -----------------PROTOCOL DECLARATIONS-------------------------- */
static PySequenceMethods Quaternion_SeqMethods = {
(lenfunc) Quaternion_len, /* sq_length */
(binaryfunc) NULL, /* sq_concat */
@@ -1060,7 +1052,7 @@ static int Quaternion_axis_vector_set(QuaternionObject *self, PyObject *value, v
return 0;
}
-//----------------------------------mathutils.Quaternion() --------------
+/* ----------------------------------mathutils.Quaternion() -------------- */
static PyObject *Quaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *seq = NULL;
@@ -1140,7 +1132,7 @@ static void quat__axis_angle_sanitize(float axis[3], float *angle)
}
}
-//-----------------------METHOD DEFINITIONS ----------------------
+/* -----------------------METHOD DEFINITIONS ---------------------- */
static struct PyMethodDef Quaternion_methods[] = {
/* in place only */
{"identity", (PyCFunction) Quaternion_identity, METH_NOARGS, Quaternion_identity_doc},
@@ -1190,60 +1182,60 @@ static PyGetSetDef Quaternion_getseters[] = {
{NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
-//------------------PY_OBECT DEFINITION--------------------------
+/* ------------------PY_OBECT DEFINITION-------------------------- */
PyDoc_STRVAR(quaternion_doc,
"This object gives access to Quaternions in Blender."
);
PyTypeObject quaternion_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "Quaternion", //tp_name
- sizeof(QuaternionObject), //tp_basicsize
- 0, //tp_itemsize
- (destructor)BaseMathObject_dealloc, //tp_dealloc
- NULL, //tp_print
- NULL, //tp_getattr
- NULL, //tp_setattr
- NULL, //tp_compare
- (reprfunc) Quaternion_repr, //tp_repr
- &Quaternion_NumMethods, //tp_as_number
- &Quaternion_SeqMethods, //tp_as_sequence
- &Quaternion_AsMapping, //tp_as_mapping
- NULL, //tp_hash
- NULL, //tp_call
- (reprfunc) Quaternion_str, //tp_str
- NULL, //tp_getattro
- NULL, //tp_setattro
- NULL, //tp_as_buffer
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, //tp_flags
- quaternion_doc, //tp_doc
- (traverseproc)BaseMathObject_traverse, //tp_traverse
- (inquiry)BaseMathObject_clear, //tp_clear
- (richcmpfunc)Quaternion_richcmpr, //tp_richcompare
- 0, //tp_weaklistoffset
- NULL, //tp_iter
- NULL, //tp_iternext
- Quaternion_methods, //tp_methods
- NULL, //tp_members
- Quaternion_getseters, //tp_getset
- NULL, //tp_base
- NULL, //tp_dict
- NULL, //tp_descr_get
- NULL, //tp_descr_set
- 0, //tp_dictoffset
- NULL, //tp_init
- NULL, //tp_alloc
- Quaternion_new, //tp_new
- NULL, //tp_free
- NULL, //tp_is_gc
- NULL, //tp_bases
- NULL, //tp_mro
- NULL, //tp_cache
- NULL, //tp_subclasses
- NULL, //tp_weaklist
- NULL, //tp_del
+ "Quaternion", /* tp_name */
+ sizeof(QuaternionObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)BaseMathObject_dealloc, /* tp_dealloc */
+ NULL, /* tp_print */
+ NULL, /* tp_getattr */
+ NULL, /* tp_setattr */
+ NULL, /* tp_compare */
+ (reprfunc) Quaternion_repr, /* tp_repr */
+ &Quaternion_NumMethods, /* tp_as_number */
+ &Quaternion_SeqMethods, /* tp_as_sequence */
+ &Quaternion_AsMapping, /* tp_as_mapping */
+ NULL, /* tp_hash */
+ NULL, /* tp_call */
+ (reprfunc) Quaternion_str, /* tp_str */
+ NULL, /* tp_getattro */
+ NULL, /* tp_setattro */
+ NULL, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ quaternion_doc, /* tp_doc */
+ (traverseproc)BaseMathObject_traverse, /* tp_traverse */
+ (inquiry)BaseMathObject_clear, /* tp_clear */
+ (richcmpfunc)Quaternion_richcmpr, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ NULL, /* tp_iter */
+ NULL, /* tp_iternext */
+ Quaternion_methods, /* tp_methods */
+ NULL, /* tp_members */
+ Quaternion_getseters, /* tp_getset */
+ NULL, /* tp_base */
+ NULL, /* tp_dict */
+ NULL, /* tp_descr_get */
+ NULL, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ NULL, /* tp_init */
+ NULL, /* tp_alloc */
+ Quaternion_new, /* tp_new */
+ NULL, /* tp_free */
+ NULL, /* tp_is_gc */
+ NULL, /* tp_bases */
+ NULL, /* tp_mro */
+ NULL, /* tp_cache */
+ NULL, /* tp_subclasses */
+ NULL, /* tp_weaklist */
+ NULL, /* tp_del */
};
-//------------------------Quaternion_CreatePyObject (internal)-------------
-//creates a new quaternion object
+/* ------------------------Quaternion_CreatePyObject (internal)------------- */
+/* creates a new quaternion object */
/*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
* (i.e. it was allocated elsewhere by MEM_mallocN())
* pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
@@ -1266,7 +1258,7 @@ PyObject *Quaternion_CreatePyObject(float *quat, int type, PyTypeObject *base_ty
}
else if (type == Py_NEW) {
self->quat = PyMem_Malloc(QUAT_SIZE * sizeof(float));
- if (!quat) { //new empty
+ if (!quat) { /* new empty */
unit_qt(self->quat);
}
else {
diff --git a/source/blender/python/mathutils/mathutils_Quaternion.h b/source/blender/python/mathutils/mathutils_Quaternion.h
index 4ffe8488843..b88715096bf 100644
--- a/source/blender/python/mathutils/mathutils_Quaternion.h
+++ b/source/blender/python/mathutils/mathutils_Quaternion.h
@@ -44,7 +44,7 @@ typedef struct {
* be stored in py_data) or be a wrapper for data allocated through
* blender (stored in blend_data). This is an either/or struct not both */
-//prototypes
+/* prototypes */
PyObject *Quaternion_CreatePyObject(float *quat, int type, PyTypeObject *base_type);
PyObject *Quaternion_CreatePyObject_cb(PyObject *cb_user,
unsigned char cb_type, unsigned char cb_subtype);
diff --git a/source/blender/python/mathutils/mathutils_Vector.c b/source/blender/python/mathutils/mathutils_Vector.c
index 74a4cd838d0..06d7f3fec51 100644
--- a/source/blender/python/mathutils/mathutils_Vector.c
+++ b/source/blender/python/mathutils/mathutils_Vector.c
@@ -1100,12 +1100,12 @@ static PyObject *Vector_project(VectorObject *self, PyObject *value)
if (BaseMath_ReadCallback(self) == -1)
return NULL;
- //get dot products
+ /* get dot products */
for (x = 0; x < size; x++) {
dot += (double)(self->vec[x] * tvec[x]);
dot2 += (double)(tvec[x] * tvec[x]);
}
- //projection
+ /* projection */
dot /= dot2;
for (x = 0; x < size; x++) {
vec[x] = (float)dot * tvec[x];
@@ -1530,7 +1530,7 @@ static PyObject *Vector_isub(PyObject *v1, PyObject *v2)
}
/*------------------------obj * obj------------------------------
- * mulplication*/
+ * multiplication */
/* COLUMN VECTOR Multiplication (Matrix X Vector)
@@ -1687,7 +1687,7 @@ static PyObject *Vector_mul(PyObject *v1, PyObject *v2)
return NULL;
}
-/* mulplication in-place: obj *= obj */
+/* multiplication in-place: obj *= obj */
static PyObject *Vector_imul(PyObject *v1, PyObject *v2)
{
VectorObject *vec = (VectorObject *)v1;
@@ -2709,11 +2709,11 @@ static int row_vector_multiplication(float r_vec[MAX_DIMENSIONS], VectorObject *
memcpy(vec_cpy, vec->vec, vec_size * sizeof(float));
r_vec[3] = 1.0f;
- //muliplication
+ /* muliplication */
for (col = 0; col < mat->num_col; col++) {
double dot = 0.0;
for (row = 0; row < mat->num_row; row++) {
- dot += MATRIX_ITEM(mat, row, col) * vec_cpy[row];
+ dot += (double)(MATRIX_ITEM(mat, row, col) * vec_cpy[row]);
}
r_vec[z++] = (float)dot;
}
@@ -2733,7 +2733,7 @@ static PyObject *Vector_negate(VectorObject *self)
negate_vn(self->vec, self->size);
- (void)BaseMath_WriteCallback(self); // already checked for error
+ (void)BaseMath_WriteCallback(self); /* already checked for error */
Py_RETURN_NONE;
}
@@ -2829,10 +2829,10 @@ PyTypeObject vector_Type = {
/*** Assigned meaning in release 2.0 ***/
/* call function for all accessible objects */
- (traverseproc)BaseMathObject_traverse, //tp_traverse
+ (traverseproc)BaseMathObject_traverse, /* tp_traverse */
/* delete references to contained objects */
- (inquiry)BaseMathObject_clear, //tp_clear
+ (inquiry)BaseMathObject_clear, /* tp_clear */
/*** Assigned meaning in release 2.1 ***/
/*** rich comparisons ***/
diff --git a/source/blender/python/mathutils/mathutils_geometry.c b/source/blender/python/mathutils/mathutils_geometry.c
index 19f9aa2dc88..22317636faa 100644
--- a/source/blender/python/mathutils/mathutils_geometry.c
+++ b/source/blender/python/mathutils/mathutils_geometry.c
@@ -46,14 +46,12 @@
#include "BLI_math.h"
#include "BLI_utildefines.h"
-#define SWAP_FLOAT(a, b, tmp) tmp = a; a = b; b = tmp
-
/*-------------------------DOC STRINGS ---------------------------*/
PyDoc_STRVAR(M_Geometry_doc,
"The Blender geometry module"
);
-//---------------------------------INTERSECTION FUNCTIONS--------------------
+/* ---------------------------------INTERSECTION FUNCTIONS-------------------- */
PyDoc_STRVAR(M_Geometry_intersect_ray_tri_doc,
".. function:: intersect_ray_tri(v1, v2, v3, ray, orig, clip=True)\n"
@@ -253,10 +251,6 @@ static PyObject *M_Geometry_intersect_line_line(PyObject *UNUSED(self), PyObject
}
}
-
-
-
-//----------------------------geometry.normal() -------------------
PyDoc_STRVAR(M_Geometry_normal_doc,
".. function:: normal(v1, v2, v3, v4=None)\n"
"\n"
@@ -340,7 +334,7 @@ static PyObject *M_Geometry_normal(PyObject *UNUSED(self), PyObject *args)
return Vector_CreatePyObject(n, 3, Py_NEW, NULL);
}
-//--------------------------------- AREA FUNCTIONS--------------------
+/* --------------------------------- AREA FUNCTIONS-------------------- */
PyDoc_STRVAR(M_Geometry_area_tri_doc,
".. function:: area_tri(v1, v2, v3)\n"
diff --git a/source/blender/python/mathutils/mathutils_noise.c b/source/blender/python/mathutils/mathutils_noise.c
index da32e36dc02..4977663038d 100644
--- a/source/blender/python/mathutils/mathutils_noise.c
+++ b/source/blender/python/mathutils/mathutils_noise.c
@@ -43,6 +43,7 @@
#include "BLI_blenlib.h"
#include "BLI_math.h"
+#include "BLI_noise.h"
#include "BLI_utildefines.h"
#include "MEM_guardedalloc.h"
diff --git a/source/blender/python/mathutils/mathutils_noise.h b/source/blender/python/mathutils/mathutils_noise.h
index f4bec88e59a..2ed3e32f4f1 100644
--- a/source/blender/python/mathutils/mathutils_noise.h
+++ b/source/blender/python/mathutils/mathutils_noise.h
@@ -33,4 +33,4 @@ PyMODINIT_FUNC PyInit_mathutils_noise(void);
PyMODINIT_FUNC PyInit_mathutils_noise_types(void);
PyMODINIT_FUNC PyInit_mathutils_noise_metrics(void);
-#endif // __MATHUTILS_NOISE_H__
+#endif /* __MATHUTILS_NOISE_H__ */
diff --git a/source/blender/python/rna_dump.py b/source/blender/python/rna_dump.py
index 489f011e693..15cc60d997e 100644
--- a/source/blender/python/rna_dump.py
+++ b/source/blender/python/rna_dump.py
@@ -95,7 +95,7 @@ def seek(r, txt, recurs):
if GEN_PATH:
newtxt = txt + '.' + item
- if item == 'rna_type' and VERBOSE_TYPE == False: # just avoid because it spits out loads of data
+ if item == 'rna_type' and VERBOSE_TYPE is False: # just avoid because it spits out loads of data
continue
value = getattr(r, item, None)
@@ -114,7 +114,7 @@ def seek(r, txt, recurs):
except:
length = 0
- if VERBOSE == False and length >= 4:
+ if VERBOSE is False and length >= 4:
for i in (0, length - 1):
if i > 0:
if PRINT_DATA:
diff --git a/source/blender/quicktime/apple/qtkit_export.m b/source/blender/quicktime/apple/qtkit_export.m
index bb87fe21c49..e0858cd5ec2 100644
--- a/source/blender/quicktime/apple/qtkit_export.m
+++ b/source/blender/quicktime/apple/qtkit_export.m
@@ -143,7 +143,7 @@ QuicktimeCodecTypeDesc* quicktime_get_videocodecType_desc(int indexValue)
int quicktime_rnatmpvalue_from_videocodectype(int codecType)
{
int i;
- for (i=0;i<qtVideoCodecCount;i++) {
+ for (i = 0; i < qtVideoCodecCount; i++) {
if (qtVideoCodecList[i].codecType == codecType)
return qtVideoCodecList[i].rnatmpvalue;
}
@@ -154,12 +154,12 @@ int quicktime_rnatmpvalue_from_videocodectype(int codecType)
int quicktime_videocodecType_from_rnatmpvalue(int rnatmpvalue)
{
int i;
- for (i=0;i<qtVideoCodecCount;i++) {
+ for (i = 0; i < qtVideoCodecCount; i++) {
if (qtVideoCodecList[i].rnatmpvalue == rnatmpvalue)
return qtVideoCodecList[i].codecType;
}
- return 0;
+ return 0;
}
/* Audio codec */
@@ -188,7 +188,7 @@ QuicktimeCodecTypeDesc* quicktime_get_audiocodecType_desc(int indexValue)
int quicktime_rnatmpvalue_from_audiocodectype(int codecType)
{
int i;
- for (i=0;i<qtAudioCodecCount;i++) {
+ for (i = 0; i < qtAudioCodecCount; i++) {
if (qtAudioCodecList[i].codecType == codecType)
return qtAudioCodecList[i].rnatmpvalue;
}
@@ -199,12 +199,12 @@ int quicktime_rnatmpvalue_from_audiocodectype(int codecType)
int quicktime_audiocodecType_from_rnatmpvalue(int rnatmpvalue)
{
int i;
- for (i=0;i<qtAudioCodecCount;i++) {
+ for (i = 0; i < qtAudioCodecCount; i++) {
if (qtAudioCodecList[i].rnatmpvalue == rnatmpvalue)
return qtAudioCodecList[i].codecType;
}
- return 0;
+ return 0;
}
@@ -212,7 +212,7 @@ static NSString *stringWithCodecType(int codecType)
{
char str[5];
- *((int*)str) = EndianU32_NtoB(codecType);
+ *((int *)str) = EndianU32_NtoB(codecType);
str[4] = 0;
return [NSString stringWithCString:str encoding:NSASCIIStringEncoding];
@@ -235,7 +235,7 @@ void makeqtstring (RenderData *rd, char *string)
void filepath_qt(char *string, RenderData *rd)
{
- if (string==NULL) return;
+ if (string == NULL) return;
strcpy(string, rd->pic);
BLI_path_abs(string, G.main->name);
@@ -313,8 +313,8 @@ int start_qt(struct Scene *scene, struct RenderData *rd, int rectx, int recty, R
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSError *error;
char name[1024];
- int success= 1;
- OSStatus err=noErr;
+ int success = 1;
+ OSStatus err = noErr;
if(qtexport == NULL) qtexport = MEM_callocN(sizeof(QuicktimeExport), "QuicktimeExport");
@@ -323,7 +323,7 @@ int start_qt(struct Scene *scene, struct RenderData *rd, int rectx, int recty, R
/* Check first if the QuickTime 7.2.1 initToWritableFile: method is available */
if ([[[[QTMovie alloc] init] autorelease] respondsToSelector:@selector(initToWritableFile:error:)] != YES) {
BKE_report(reports, RPT_ERROR, "\nUnable to create quicktime movie, need Quicktime rev 7.2.1 or later");
- success= 0;
+ success = 0;
}
else {
makeqtstring(rd, name);
@@ -543,7 +543,7 @@ int start_qt(struct Scene *scene, struct RenderData *rd, int rectx, int recty, R
if(qtexport->movie == nil) {
BKE_report(reports, RPT_ERROR, "Unable to create quicktime movie.");
- success= 0;
+ success = 0;
if (qtexport->filename) [qtexport->filename release];
qtexport->filename = nil;
if (qtexport->audioFileName) [qtexport->audioFileName release];
@@ -561,19 +561,21 @@ int start_qt(struct Scene *scene, struct RenderData *rd, int rectx, int recty, R
/* specifying the codec attributes : try to retrieve them from render data first*/
if (rd->qtcodecsettings.codecType) {
- qtexport->frameAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
- stringWithCodecType(rd->qtcodecsettings.codecType),
- QTAddImageCodecType,
- [NSNumber numberWithLong:((rd->qtcodecsettings.codecSpatialQuality)*codecLosslessQuality)/100],
- QTAddImageCodecQuality,
- nil];
+ qtexport->frameAttributes = [
+ NSDictionary dictionaryWithObjectsAndKeys:
+ stringWithCodecType(rd->qtcodecsettings.codecType),
+ QTAddImageCodecType,
+ [NSNumber numberWithLong:((rd->qtcodecsettings.codecSpatialQuality)*codecLosslessQuality)/100],
+ QTAddImageCodecQuality,
+ nil];
}
else {
- qtexport->frameAttributes = [NSDictionary dictionaryWithObjectsAndKeys:@"jpeg",
- QTAddImageCodecType,
- [NSNumber numberWithLong:codecHighQuality],
- QTAddImageCodecQuality,
- nil];
+ qtexport->frameAttributes = [
+ NSDictionary dictionaryWithObjectsAndKeys:@"jpeg",
+ QTAddImageCodecType,
+ [NSNumber numberWithLong:codecHighQuality],
+ QTAddImageCodecQuality,
+ nil];
}
[qtexport->frameAttributes retain];
@@ -624,8 +626,8 @@ int append_qt(struct RenderData *rd, int start_frame, int frame, int *pixels, in
return 0;
}
- from_Ptr = (unsigned char*)pixels;
- to_Ptr = (unsigned char*)[blBitmapFormatImage bitmapData];
+ from_Ptr = (unsigned char *)pixels;
+ to_Ptr = (unsigned char *)[blBitmapFormatImage bitmapData];
for (y = 0; y < recty; y++) {
to_i = (recty-y-1)*rectx;
from_i = y*rectx;
@@ -647,7 +649,7 @@ int append_qt(struct RenderData *rd, int start_frame, int frame, int *pixels, in
if (qtexport->audioFile) {
UInt32 audioPacketsConverted;
/* Append audio */
- while (qtexport->audioTotalExportedFrames < qtexport->audioLastFrame) {
+ while (qtexport->audioTotalExportedFrames < qtexport->audioLastFrame) {
qtexport->audioBufferList.mNumberBuffers = 1;
qtexport->audioBufferList.mBuffers[0].mNumberChannels = qtexport->audioOutputFormat.mChannelsPerFrame;
@@ -683,7 +685,7 @@ int append_qt(struct RenderData *rd, int start_frame, int frame, int *pixels, in
}
}
- [pool drain];
+ [pool drain];
return 1;
}
diff --git a/source/blender/quicktime/apple/qtkit_import.m b/source/blender/quicktime/apple/qtkit_import.m
index 75b9056de1b..2e910e38871 100644
--- a/source/blender/quicktime/apple/qtkit_import.m
+++ b/source/blender/quicktime/apple/qtkit_import.m
@@ -71,7 +71,7 @@ void quicktime_init(void)
void quicktime_exit(void)
{
- if(G.have_quicktime) {
+ if (G.have_quicktime) {
free_qtcomponentdata();
}
}
@@ -82,27 +82,30 @@ int anim_is_quicktime (const char *name)
NSAutoreleasePool *pool;
// don't let quicktime movie import handle these
- if( BLI_testextensie(name, ".swf") ||
- BLI_testextensie(name, ".txt") ||
- BLI_testextensie(name, ".mpg") ||
- BLI_testextensie(name, ".avi") || // wouldn't be appropriate ;)
- BLI_testextensie(name, ".mov") || // disabled, suboptimal decoding speed
- BLI_testextensie(name, ".mp4") || // disabled, suboptimal decoding speed
- BLI_testextensie(name, ".m4v") || // disabled, suboptimal decoding speed
- BLI_testextensie(name, ".tga") ||
- BLI_testextensie(name, ".png") ||
- BLI_testextensie(name, ".bmp") ||
- BLI_testextensie(name, ".jpg") ||
- BLI_testextensie(name, ".wav") ||
- BLI_testextensie(name, ".zip") ||
- BLI_testextensie(name, ".mp3")) return 0;
+ if (BLI_testextensie(name, ".swf") ||
+ BLI_testextensie(name, ".txt") ||
+ BLI_testextensie(name, ".mpg") ||
+ BLI_testextensie(name, ".avi") || // wouldn't be appropriate ;)
+ BLI_testextensie(name, ".mov") || // disabled, suboptimal decoding speed
+ BLI_testextensie(name, ".mp4") || // disabled, suboptimal decoding speed
+ BLI_testextensie(name, ".m4v") || // disabled, suboptimal decoding speed
+ BLI_testextensie(name, ".tga") ||
+ BLI_testextensie(name, ".png") ||
+ BLI_testextensie(name, ".bmp") ||
+ BLI_testextensie(name, ".jpg") ||
+ BLI_testextensie(name, ".wav") ||
+ BLI_testextensie(name, ".zip") ||
+ BLI_testextensie(name, ".mp3"))
+ {
+ return 0;
+ }
- if(QTIME_DEBUG) printf("qt: checking as movie: %s\n", name);
+ if (QTIME_DEBUG) printf("qt: checking as movie: %s\n", name);
pool = [[NSAutoreleasePool alloc] init];
- if([QTMovie canInitWithFile:[NSString stringWithCString:name
- encoding:[NSString defaultCStringEncoding]]])
+ if ([QTMovie canInitWithFile:[NSString stringWithCString:name
+ encoding:[NSString defaultCStringEncoding]]])
{
[pool drain];
return true;
@@ -147,7 +150,7 @@ static ImBuf * nsImageToiBuf(NSImage *sourceImage, int width, int height)
uchar *toIBuf = NULL;
int x, y, to_i, from_i;
NSSize bitmapSize;
- NSBitmapImageRep *blBitmapFormatImageRGB,*blBitmapFormatImageRGBA,*bitmapImage=nil;
+ NSBitmapImageRep *blBitmapFormatImageRGB,*blBitmapFormatImageRGBA, *bitmapImage = nil;
NSEnumerator *enumerator;
NSImageRep *representation;
@@ -162,18 +165,18 @@ static ImBuf * nsImageToiBuf(NSImage *sourceImage, int width, int height)
/*Get the bitmap of the image*/
enumerator = [[sourceImage representations] objectEnumerator];
while ((representation = [enumerator nextObject])) {
- if ([representation isKindOfClass:[NSBitmapImageRep class]]) {
- bitmapImage = (NSBitmapImageRep *)representation;
+ if ([representation isKindOfClass:[NSBitmapImageRep class]]) {
+ bitmapImage = (NSBitmapImageRep *)representation;
break;
- }
- }
+ }
+ }
if (bitmapImage == nil) return NULL;
if (([bitmapImage bitsPerPixel] == 32) && (([bitmapImage bitmapFormat] & 0x5) == 0)
&& ![bitmapImage isPlanar]) {
/* Try a fast copy if the image is a meshed RGBA 32bit bitmap*/
- toIBuf = (uchar*)ibuf->rect;
- rasterRGB = (uchar*)[bitmapImage bitmapData];
+ toIBuf = (uchar *)ibuf->rect;
+ rasterRGB = (uchar *)[bitmapImage bitmapData];
for (y = 0; y < height; y++) {
to_i = (height-y-1)*width;
from_i = y*width;
@@ -207,7 +210,7 @@ static ImBuf * nsImageToiBuf(NSImage *sourceImage, int width, int height)
[bitmapImage draw];
[NSGraphicsContext restoreGraphicsState];
- rasterRGB = (uchar*)[blBitmapFormatImageRGB bitmapData];
+ rasterRGB = (uchar *)[blBitmapFormatImageRGB bitmapData];
if (rasterRGB == NULL) {
[blBitmapFormatImageRGB release];
return NULL;
@@ -228,7 +231,7 @@ static ImBuf * nsImageToiBuf(NSImage *sourceImage, int width, int height)
[bitmapImage draw];
[NSGraphicsContext restoreGraphicsState];
- rasterRGBA = (uchar*)[blBitmapFormatImageRGBA bitmapData];
+ rasterRGBA = (uchar *)[blBitmapFormatImageRGBA bitmapData];
if (rasterRGBA == NULL) {
[blBitmapFormatImageRGB release];
[blBitmapFormatImageRGBA release];
@@ -236,7 +239,7 @@ static ImBuf * nsImageToiBuf(NSImage *sourceImage, int width, int height)
}
/*Copy the image to ibuf, flipping it vertically*/
- toIBuf = (uchar*)ibuf->rect;
+ toIBuf = (uchar *)ibuf->rect;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
to_i = (height-y-1)*width + x;
@@ -312,7 +315,7 @@ int startquicktime (struct anim *anim)
pool = [[NSAutoreleasePool alloc] init];
- [QTMovie enterQTKitOnThread];
+ [QTMovie enterQTKitOnThread];
attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithCString:anim->name
@@ -382,7 +385,7 @@ int startquicktime (struct anim *anim)
anim->curposition = 0;
[pool drain];
-
+
return 0;
}
@@ -486,7 +489,7 @@ ImBuf *imb_quicktime_decode(unsigned char *mem, int size, int flags)
[bitmapImage draw];
[NSGraphicsContext restoreGraphicsState];
- rasterRGB = (uchar*)[blBitmapFormatImageRGB bitmapData];
+ rasterRGB = (uchar *)[blBitmapFormatImageRGB bitmapData];
if (rasterRGB == NULL) {
[bitmapImage release];
[blBitmapFormatImageRGB release];
@@ -509,7 +512,7 @@ ImBuf *imb_quicktime_decode(unsigned char *mem, int size, int flags)
[bitmapImage draw];
[NSGraphicsContext restoreGraphicsState];
- rasterRGBA = (uchar*)[blBitmapFormatImageRGBA bitmapData];
+ rasterRGBA = (uchar *)[blBitmapFormatImageRGBA bitmapData];
if (rasterRGBA == NULL) {
[bitmapImage release];
[blBitmapFormatImageRGB release];
@@ -519,7 +522,7 @@ ImBuf *imb_quicktime_decode(unsigned char *mem, int size, int flags)
}
/*Copy the image to ibuf, flipping it vertically*/
- toIBuf = (uchar*)ibuf->rect;
+ toIBuf = (uchar *)ibuf->rect;
for (x = 0; x < bitmapSize.width; x++) {
for (y = 0; y < bitmapSize.height; y++) {
to_i = (bitmapSize.height-y-1)*bitmapSize.width + x;
@@ -543,7 +546,7 @@ ImBuf *imb_quicktime_decode(unsigned char *mem, int size, int flags)
if (ENDIAN_ORDER == B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
/* return successfully */
- return (ibuf);
+ return (ibuf);
}
diff --git a/source/blender/quicktime/apple/quicktime_export.c b/source/blender/quicktime/apple/quicktime_export.c
index 659fd997c1f..1c4ab5a4b0e 100644
--- a/source/blender/quicktime/apple/quicktime_export.c
+++ b/source/blender/quicktime/apple/quicktime_export.c
@@ -105,8 +105,8 @@ typedef struct QuicktimeExport {
PixMapHandle thePixMap;
ImageDescription **anImageDescription;
- ImBuf *ibuf; //imagedata for Quicktime's Gworld
- ImBuf *ibuf2; //copy of renderdata, to be Y-flipped
+ ImBuf *ibuf; /* imagedata for Quicktime's Gworld */
+ ImBuf *ibuf2; /* copy of renderdata, to be Y-flipped */
} QuicktimeExport;
@@ -178,7 +178,7 @@ int quicktime_videocodecType_from_rnatmpvalue(int rnatmpvalue)
return qtVideoCodecList[i].codecType;
}
- return 0;
+ return 0;
}
@@ -218,7 +218,7 @@ static OSErr QT_SaveCodecSettingsToScene(RenderData *rd, ReportList *reports)
/* retreive codecdata from quicktime in a atomcontainer */
myErr = SCGetSettingsAsAtomContainer(qtdata->theComponent, &myContainer);
if (myErr != noErr) {
- BKE_reportf(reports, RPT_ERROR, "Quicktime: SCGetSettingsAsAtomContainer failed\n");
+ BKE_report(reports, RPT_ERROR, "Quicktime: SCGetSettingsAsAtomContainer failed");
goto bail;
}
@@ -238,7 +238,7 @@ static OSErr QT_SaveCodecSettingsToScene(RenderData *rd, ReportList *reports)
GetCodecInfo(&ci, qtdata->gSpatialSettings.codecType, 0);
}
else {
- BKE_reportf(reports, RPT_ERROR, "Quicktime: QT_SaveCodecSettingsToScene failed\n");
+ BKE_report(reports, RPT_ERROR, "Quicktime: QT_SaveCodecSettingsToScene failed");
}
QTUnlockContainer(myContainer);
@@ -268,7 +268,7 @@ static OSErr QT_GetCodecSettingsFromScene(RenderData *rd, ReportList *reports)
if (qcd->cdParms && qcd->cdSize) {
myErr = SCSetSettingsFromAtomContainer((GraphicsExportComponent)qtdata->theComponent, (QTAtomContainer)myHandle);
if (myErr != noErr) {
- BKE_reportf(reports, RPT_ERROR, "Quicktime: SCSetSettingsFromAtomContainer failed\n");
+ BKE_report(reports, RPT_ERROR, "Quicktime: SCSetSettingsFromAtomContainer failed");
goto bail;
}
@@ -278,9 +278,9 @@ static OSErr QT_GetCodecSettingsFromScene(RenderData *rd, ReportList *reports)
SCGetInfo(qtdata->theComponent, scTemporalSettingsType, &qtdata->gTemporalSettings);
- //Fill the render QuicktimeCodecSettigns struct
+ /* Fill the render QuicktimeCodecSettigns struct */
rd->qtcodecsettings.codecTemporalQuality = (qtdata->gTemporalSettings.temporalQuality * 100) / codecLosslessQuality;
- //Do not override scene frame rate (qtdata->gTemporalSettings.framerate)
+ /* Do not override scene frame rate (qtdata->gTemporalSettings.framerate) */
rd->qtcodecsettings.keyFrameRate = qtdata->gTemporalSettings.keyFrameRate;
rd->qtcodecsettings.codecType = qtdata->gSpatialSettings.codecType;
@@ -291,11 +291,11 @@ static OSErr QT_GetCodecSettingsFromScene(RenderData *rd, ReportList *reports)
rd->qtcodecsettings.bitRate = qtdata->aDataRateSetting.dataRate;
rd->qtcodecsettings.minSpatialQuality = (qtdata->aDataRateSetting.minSpatialQuality * 100) / codecLosslessQuality;
rd->qtcodecsettings.minTemporalQuality = (qtdata->aDataRateSetting.minTemporalQuality * 100) / codecLosslessQuality;
- //Frame duration is already known (qtdata->aDataRateSetting.frameDuration)
+ /* Frame duration is already known (qtdata->aDataRateSetting.frameDuration) */
}
else {
- BKE_reportf(reports, RPT_ERROR, "Quicktime: QT_GetCodecSettingsFromScene failed\n");
+ BKE_report(reports, RPT_ERROR, "Quicktime: QT_GetCodecSettingsFromScene failed");
}
bail:
if (myHandle != NULL)
@@ -414,7 +414,7 @@ static void QT_StartAddVideoSamplesToMedia(const Rect *trackFrame, int rectx, in
gTemporalSettings = qtdata->gTemporalSettings;
if (qtdata->gSpatialSettings.codecType == kH264CodecType) {
if (gTemporalSettings.temporalQuality != codecMinQuality) {
- BKE_reportf(reports, RPT_WARNING, "Only minimum quality compression supported for QuickTime H.264.\n");
+ BKE_report(reports, RPT_WARNING, "Only minimum quality compression supported for Quicktime H.264");
gTemporalSettings.temporalQuality = codecMinQuality;
}
}
@@ -443,18 +443,18 @@ static void QT_DoAddVideoSamplesToMedia(int frame, int *pixels, int rectx, int r
Ptr myPtr;
- //copy and flip renderdata
+ /* copy and flip renderdata */
memcpy(qtexport->ibuf2->rect, pixels, 4 * rectx * recty);
IMB_flipy(qtexport->ibuf2);
- //get pointers to parse bitmapdata
+ /* get pointers to parse bitmapdata */
myPtr = GetPixBaseAddr(qtexport->thePixMap);
imageRect = (**qtexport->thePixMap).bounds;
from = (unsigned char *) qtexport->ibuf2->rect;
to = (unsigned char *) myPtr;
- //parse RGBA bitmap into Quicktime's ARGB GWorld
+ /* parse RGBA bitmap into Quicktime's ARGB GWorld */
boxsize = rectx * recty;
for (index = 0; index < boxsize; index++) {
to[0] = from[3];
@@ -564,7 +564,7 @@ int start_qt(struct Scene *scene, struct RenderData *rd, int rectx, int recty, R
/* hack: create an empty file to make FSPathMakeRef() happy */
myFile = open(theFullPath, O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRUSR | S_IWUSR);
if (myFile < 0) {
- BKE_reportf(reports, RPT_ERROR, "error while creating movie file!\n");
+ BKE_report(reports, RPT_ERROR, "Error while creating movie file!");
/* do something? */
}
close(myFile);
@@ -599,7 +599,7 @@ int start_qt(struct Scene *scene, struct RenderData *rd, int rectx, int recty, R
#endif
}
else {
- //printf("Created QuickTime movie: %s\n", name);
+ /* printf("Created QuickTime movie: %s\n", name); */
QT_CreateMyVideoTrack(rectx, recty, reports);
}
@@ -636,7 +636,7 @@ void end_qt(void)
DisposeMovie(qtexport->theMovie);
- //printf("Finished QuickTime movie.\n");
+ /* printf("Finished QuickTime movie.\n"); */
}
#ifdef __APPLE__
@@ -684,15 +684,15 @@ static void check_renderbutton_framerate(RenderData *rd, ReportList *reports)
err = SCSetInfo(qtdata->theComponent, scTemporalSettingsType, &qtdata->gTemporalSettings);
CheckError(err, "SCSetInfo error", reports);
- if (qtdata->gTemporalSettings.frameRate == 1571553) { // 23.98 fps
+ if (qtdata->gTemporalSettings.frameRate == 1571553) { /* 23.98 fps */
qtdata->kVideoTimeScale = 24000;
qtdata->duration = 1001;
}
- else if (qtdata->gTemporalSettings.frameRate == 1964113) { // 29.97 fps
+ else if (qtdata->gTemporalSettings.frameRate == 1964113) { /* 29.97 fps */
qtdata->kVideoTimeScale = 30000;
qtdata->duration = 1001;
}
- else if (qtdata->gTemporalSettings.frameRate == 3928227) { // 59.94 fps
+ else if (qtdata->gTemporalSettings.frameRate == 3928227) { /* 59.94 fps */
qtdata->kVideoTimeScale = 60000;
qtdata->duration = 1001;
}
@@ -714,7 +714,7 @@ void quicktime_verify_image_type(RenderData *rd, ImageFormatData *imf)
rd->qtcodecsettings.codecSpatialQuality = (codecHighQuality * 100) / codecLosslessQuality;
rd->qtcodecsettings.codecTemporalQuality = (codecHighQuality * 100) / codecLosslessQuality;
rd->qtcodecsettings.keyFrameRate = 25;
- rd->qtcodecsettings.bitRate = 5000000; //5 Mbps
+ rd->qtcodecsettings.bitRate = 5000000; /* 5 Mbps */
}
}
}
@@ -804,7 +804,7 @@ static int request_qtcodec_settings(bContext *C, wmOperator *op)
qtdata->aDataRateSetting.minSpatialQuality = (rd->qtcodecsettings.minSpatialQuality * codecLosslessQuality) / 100;
qtdata->aDataRateSetting.minTemporalQuality = (rd->qtcodecsettings.minTemporalQuality * codecLosslessQuality) / 100;
- qtdata->aDataRateSetting.frameDuration = rd->frs_sec;
+ qtdata->aDataRateSetting.frameDuration = rd->frs_sec;
err = SCSetInfo(qtdata->theComponent, scTemporalSettingsType, &qtdata->gTemporalSettings);
CheckError(err, "SCSetInfo1 error", op->reports);
@@ -826,9 +826,9 @@ static int request_qtcodec_settings(bContext *C, wmOperator *op)
SCGetInfo(qtdata->theComponent, scTemporalSettingsType, &qtdata->gTemporalSettings);
- //Fill the render QuicktimeCodecSettings struct
+ /* Fill the render QuicktimeCodecSettings struct */
rd->qtcodecsettings.codecTemporalQuality = (qtdata->gTemporalSettings.temporalQuality * 100) / codecLosslessQuality;
- //Do not override scene frame rate (qtdata->gTemporalSettings.framerate)
+ /* Do not override scene frame rate (qtdata->gTemporalSettings.framerate) */
rd->qtcodecsettings.keyFrameRate = qtdata->gTemporalSettings.keyFrameRate;
rd->qtcodecsettings.codecType = qtdata->gSpatialSettings.codecType;
@@ -839,26 +839,26 @@ static int request_qtcodec_settings(bContext *C, wmOperator *op)
rd->qtcodecsettings.bitRate = qtdata->aDataRateSetting.dataRate;
rd->qtcodecsettings.minSpatialQuality = (qtdata->aDataRateSetting.minSpatialQuality * 100) / codecLosslessQuality;
rd->qtcodecsettings.minTemporalQuality = (qtdata->aDataRateSetting.minTemporalQuality * 100) / codecLosslessQuality;
- //Frame duration is already known (qtdata->aDataRateSetting.frameDuration)
+ /* Frame duration is already known (qtdata->aDataRateSetting.frameDuration) */
QT_SaveCodecSettingsToScene(rd, op->reports);
/* framerate jugglin' */
- if (qtdata->gTemporalSettings.frameRate == 1571553) { // 23.98 fps
+ if (qtdata->gTemporalSettings.frameRate == 1571553) { /* 23.98 fps */
qtdata->kVideoTimeScale = 24000;
qtdata->duration = 1001;
rd->frs_sec = 24;
rd->frs_sec_base = 1.001;
}
- else if (qtdata->gTemporalSettings.frameRate == 1964113) { // 29.97 fps
+ else if (qtdata->gTemporalSettings.frameRate == 1964113) { /* 29.97 fps */
qtdata->kVideoTimeScale = 30000;
qtdata->duration = 1001;
rd->frs_sec = 30;
rd->frs_sec_base = 1.001;
}
- else if (qtdata->gTemporalSettings.frameRate == 3928227) { // 59.94 fps
+ else if (qtdata->gTemporalSettings.frameRate == 3928227) { /* 59.94 fps */
qtdata->kVideoTimeScale = 60000;
qtdata->duration = 1001;
@@ -891,8 +891,8 @@ static int ED_operator_setqtcodec(bContext *C)
}
#if defined(__APPLE__) && defined(GHOST_COCOA)
-//Need to set up a Cocoa NSAutoReleasePool to avoid memory leak
-//And it must be done in an objC file, so use a GHOST_SystemCocoa.mm function for that
+/* Need to set up a Cocoa NSAutoReleasePool to avoid memory leak
+ * And it must be done in an objC file, so use a GHOST_SystemCocoa.mm function for that */
extern int cocoa_request_qtcodec_settings(bContext *C, wmOperator *op);
int fromcocoa_request_qtcodec_settings(bContext *C, wmOperator *op)
diff --git a/source/blender/quicktime/quicktime_export.h b/source/blender/quicktime/quicktime_export.h
index ed896357c90..cef4cb8c2a6 100644
--- a/source/blender/quicktime/quicktime_export.h
+++ b/source/blender/quicktime/quicktime_export.h
@@ -164,6 +164,6 @@ enum {
};
#endif
-#endif //(_WIN32) || (__APPLE__)
+#endif /* (_WIN32) || (__APPLE__) */
-#endif // __QUICKTIME_IMP_H__
+#endif /* __QUICKTIME_IMP_H__ */
diff --git a/source/blender/quicktime/quicktime_import.h b/source/blender/quicktime/quicktime_import.h
index 19bdbb4814c..8fd016a3d74 100644
--- a/source/blender/quicktime/quicktime_import.h
+++ b/source/blender/quicktime/quicktime_import.h
@@ -43,37 +43,35 @@
#include "../imbuf/IMB_imbuf_types.h"
#ifndef USE_QTKIT
-#ifndef __MOVIES__
-#ifdef _WIN32
-#include <Movies.h>
-#elif defined(__APPLE__)
-#define __CARBONSOUND__
-#import <Carbon/Carbon.h>
-#include <QuickTime/Movies.h>
-#endif
-#endif //__MOVIES__
-#endif //USE_QTKIT
+# ifndef __MOVIES__
+# ifdef _WIN32
+# include <Movies.h>
+# elif defined(__APPLE__)
+# define __CARBONSOUND__
+# import <Carbon/Carbon.h>
+# include <QuickTime/Movies.h>
+# endif
+# endif /* __MOVIES__ */
+#endif /* USE_QTKIT */
#ifdef _WIN32
-#ifndef __FIXMATH__
-#include <FixMath.h>
-#endif /* __FIXMATH__ */
+# ifndef __FIXMATH__
+# include <FixMath.h>
+# endif /* __FIXMATH__ */
#endif /* _WIN32 _ */
-
char *get_valid_qtname(const char *name);
-
-// quicktime movie import functions
+/* quicktime movie import functions */
int anim_is_quicktime (const char *name);
int startquicktime (struct anim *anim);
void free_anim_quicktime (struct anim *anim);
ImBuf *qtime_fetchibuf (struct anim *anim, int position);
-// quicktime image import functions
+/* quicktime image import functions */
int imb_is_a_quicktime (char *name);
ImBuf *imb_quicktime_decode(unsigned char *mem, int size, int flags);
-#endif // __QUICKTIME_IMPORT_H__
+#endif /* __QUICKTIME_IMPORT_H__ */
diff --git a/source/blender/render/extern/include/RE_engine.h b/source/blender/render/extern/include/RE_engine.h
index 2376aeca55e..1331c287d7c 100644
--- a/source/blender/render/extern/include/RE_engine.h
+++ b/source/blender/render/extern/include/RE_engine.h
@@ -35,6 +35,8 @@
#include "DNA_listBase.h"
#include "RNA_types.h"
+struct bNode;
+struct bNodeTree;
struct Object;
struct Render;
struct RenderEngine;
@@ -75,6 +77,8 @@ typedef struct RenderEngineType {
void (*view_update)(struct RenderEngine *engine, const struct bContext *context);
void (*view_draw)(struct RenderEngine *engine, const struct bContext *context);
+ void (*update_script_node)(struct RenderEngine *engine, struct bNodeTree *ntree, struct bNode *node);
+
/* RNA integration */
ExtensionRNA ext;
} RenderEngineType;
@@ -94,6 +98,8 @@ typedef struct RenderEngine {
char *text;
int resolution_x, resolution_y;
+
+ struct ReportList *reports;
} RenderEngine;
RenderEngine *RE_engine_create(RenderEngineType *type);
@@ -109,6 +115,7 @@ void RE_engine_end_result(RenderEngine *engine, struct RenderResult *result, int
int RE_engine_test_break(RenderEngine *engine);
void RE_engine_update_stats(RenderEngine *engine, const char *stats, const char *info);
void RE_engine_update_progress(RenderEngine *engine, float progress);
+void RE_engine_update_memory_stats(RenderEngine *engine, float mem_used, float mem_peak);
void RE_engine_report(RenderEngine *engine, int type, const char *msg);
int RE_engine_render(struct Render *re, int do_all);
diff --git a/source/blender/render/extern/include/RE_pipeline.h b/source/blender/render/extern/include/RE_pipeline.h
index b43824d6d5e..984b1a8e651 100644
--- a/source/blender/render/extern/include/RE_pipeline.h
+++ b/source/blender/render/extern/include/RE_pipeline.h
@@ -83,7 +83,7 @@ typedef struct RenderLayer {
/* copy of RenderData */
char name[RE_MAXNAME];
unsigned int lay, lay_zmask, lay_exclude;
- int layflag, passflag, pass_xor;
+ int layflag, passflag, pass_xor;
struct Material *mat_override;
struct Group *light_override;
@@ -148,6 +148,7 @@ typedef struct RenderStats {
double starttime, lastframetime;
const char *infostr, *statstr;
char scene_name[MAX_ID_NAME - 2];
+ float mem_used, mem_peak;
} RenderStats;
/* *********************** API ******************** */
@@ -225,7 +226,7 @@ void RE_PreviewRender(struct Render *re, struct Main *bmain, struct Scene *scene
int RE_ReadRenderResult(struct Scene *scene, struct Scene *scenode);
int RE_WriteRenderResult(struct ReportList *reports, RenderResult *rr, const char *filename, int compress);
-struct RenderResult *RE_MultilayerConvert(void *exrhandle, int rectx, int recty);
+struct RenderResult *RE_MultilayerConvert(void *exrhandle, const char *colorspace, int predivide, int rectx, int recty);
extern const float default_envmap_layout[];
int RE_WriteEnvmapResult(struct ReportList *reports, struct Scene *scene, struct EnvMap *env, const char *relpath, const char imtype, float layout[12]);
@@ -235,7 +236,7 @@ void RE_MergeFullSample(struct Render *re, struct Main *bmain, struct Scene *sce
/* ancient stars function... go away! */
void RE_make_stars(struct Render *re, struct Scene *scenev3d, void (*initfunc)(void),
- void (*vertexfunc)(float*), void (*termfunc)(void));
+ void (*vertexfunc)(float *), void (*termfunc)(void));
/* display and event callbacks */
void RE_display_init_cb (struct Render *re, void *handle, void (*f)(void *handle, RenderResult *rr));
diff --git a/source/blender/render/extern/include/RE_render_ext.h b/source/blender/render/extern/include/RE_render_ext.h
index c07ed42332f..2a9a1becc42 100644
--- a/source/blender/render/extern/include/RE_render_ext.h
+++ b/source/blender/render/extern/include/RE_render_ext.h
@@ -39,10 +39,11 @@
/* called by meshtools */
struct View3D;
struct Scene;
+struct LinkNode;
-void RE_make_sticky(struct Scene *scene, struct View3D *v3d);
-
-/* for radiosity module */
+void RE_make_sticky(struct Scene *scene, struct Object *camera, struct LinkNode *objects);
+
+/* for radiosity module */
struct RadView;
struct RNode;
struct Render;
diff --git a/source/blender/render/extern/include/RE_shader_ext.h b/source/blender/render/extern/include/RE_shader_ext.h
index 26a1b9908b3..10045a8f7e1 100644
--- a/source/blender/render/extern/include/RE_shader_ext.h
+++ b/source/blender/render/extern/include/RE_shader_ext.h
@@ -134,7 +134,7 @@ typedef struct ShadeInput {
int har; /* hardness */
/* texture coordinates */
- float lo[3], gl[3], ref[3], orn[3], winco[3], sticky[3], vcol[4];
+ float lo[3], gl[3], ref[3], orn[3], winco[3], vcol[4];
float refcol[4], displace[3];
float strandco, tang[3], nmapnorm[3], nmaptang[4], stress, winspeed[4];
float duplilo[3], dupliuv[3];
@@ -150,7 +150,6 @@ typedef struct ShadeInput {
float dxno[3], dyno[3], dxview, dyview;
float dxlv[3], dylv[3];
float dxwin[3], dywin[3];
- float dxsticky[3], dysticky[3];
float dxrefract[3], dyrefract[3];
float dxstrand, dystrand;
@@ -192,12 +191,12 @@ struct MTex;
struct ImBuf;
/* this one uses nodes */
-int multitex_ext(struct Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, struct TexResult *texres);
+int multitex_ext(struct Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, struct TexResult *texres);
/* nodes disabled */
-int multitex_ext_safe(struct Tex *tex, float *texvec, struct TexResult *texres);
+int multitex_ext_safe(struct Tex *tex, float texvec[3], struct TexResult *texres);
/* only for internal node usage */
-int multitex_nodes(struct Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, struct TexResult *texres,
- short thread, short which_output, struct ShadeInput *shi, struct MTex *mtex);
+int multitex_nodes(struct Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, struct TexResult *texres,
+ const short thread, short which_output, struct ShadeInput *shi, struct MTex *mtex);
/* shaded view and bake */
struct Render;
diff --git a/source/blender/render/intern/include/envmap.h b/source/blender/render/intern/include/envmap.h
index 24138884cd2..d0f346f7402 100644
--- a/source/blender/render/intern/include/envmap.h
+++ b/source/blender/render/intern/include/envmap.h
@@ -46,7 +46,7 @@ struct Render;
struct TexResult;
void make_envmaps(struct Render *re);
-int envmaptex(struct Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, struct TexResult *texres);
+int envmaptex(struct Tex *tex, const float texvec[3], float dxt[3], float dyt[3], int osatex, struct TexResult *texres);
#endif /* __ENVMAP_H__ */
diff --git a/source/blender/render/intern/include/pointdensity.h b/source/blender/render/intern/include/pointdensity.h
index cc8fabda49c..e0c293e2473 100644
--- a/source/blender/render/intern/include/pointdensity.h
+++ b/source/blender/render/intern/include/pointdensity.h
@@ -43,7 +43,7 @@ struct TexResult;
void cache_pointdensity(struct Render *re, struct Tex *tex);
void make_pointdensities(struct Render *re);
void free_pointdensities(struct Render *re);
-int pointdensitytex(struct Tex *tex, float *texvec, struct TexResult *texres);
+int pointdensitytex(struct Tex *tex, const float texvec[3], struct TexResult *texres);
#endif /* __POINTDENSITY_H__ */
diff --git a/source/blender/render/intern/include/rayobject.h b/source/blender/render/intern/include/rayobject.h
index 7752baadff4..07fc7d7a6ed 100644
--- a/source/blender/render/intern/include/rayobject.h
+++ b/source/blender/render/intern/include/rayobject.h
@@ -104,7 +104,7 @@ RayObject *RE_vlakprimitive_from_vlak(VlakPrimitive *face, struct ObjectInstance
void RE_rayobject_merge_bb(RayObject *ob, float *min, float *max);
/* initializes an hint for optimizing raycast where it is know that a ray will pass by the given BB often the origin point */
-void RE_rayobject_hint_bb(RayObject *r, struct RayHint *hint, float *min, float *max);
+void RE_rayobject_hint_bb(RayObject *r, struct RayHint *hint, float min[3], float max[3]);
/* initializes an hint for optimizing raycast where it is know that a ray will be contained inside the given cone*/
/* void RE_rayobject_hint_cone(RayObject *r, struct RayHint *hint, float *); */
diff --git a/source/blender/render/intern/include/render_result.h b/source/blender/render/intern/include/render_result.h
index 999fb24ba32..5d61417cbaf 100644
--- a/source/blender/render/intern/include/render_result.h
+++ b/source/blender/render/intern/include/render_result.h
@@ -57,7 +57,7 @@ struct RenderResult *render_result_new(struct Render *re,
struct RenderResult *render_result_new_full_sample(struct Render *re,
struct ListBase *lb, struct rcti *partrct, int crop, int savebuffers);
-struct RenderResult *render_result_new_from_exr(void *exrhandle, int rectx, int recty);
+struct RenderResult *render_result_new_from_exr(void *exrhandle, const char *colorspace, int predivide, int rectx, int recty);
/* Merge */
diff --git a/source/blender/render/intern/include/render_types.h b/source/blender/render/intern/include/render_types.h
index 85dbd9356f4..825fe2ff4d0 100644
--- a/source/blender/render/intern/include/render_types.h
+++ b/source/blender/render/intern/include/render_types.h
@@ -120,12 +120,15 @@ struct Render
/* state settings */
short flag, osa, ok, result_ok;
+ /* due to performance issues, getting initialized from color management settings once on Render initialization */
+ short scene_color_manage;
+
/* result of rendering */
RenderResult *result;
/* if render with single-layer option, other rendered layers are stored here */
RenderResult *pushedresult;
/* a list of RenderResults, for fullsample */
- ListBase fullresult;
+ ListBase fullresult;
/* read/write mutex, all internal code that writes to re->result must use a
* write lock, all external code must use a read lock. internal code is assumed
* to not conflict with writes, so no lock used for that */
@@ -142,8 +145,6 @@ struct Render
/* final picture width and height (within disprect) */
int rectx, recty;
- /* real maximum amount of xparts/yparts after correction for minimum */
- int xparts, yparts;
/* real maximum size of parts after correction for minimum
* partx*xparts can be larger than rectx, in that case last part is smaller */
int partx, party;
diff --git a/source/blender/render/intern/include/rendercore.h b/source/blender/render/intern/include/rendercore.h
index 0fbbf52e613..30712250440 100644
--- a/source/blender/render/intern/include/rendercore.h
+++ b/source/blender/render/intern/include/rendercore.h
@@ -62,7 +62,7 @@ typedef struct PixStrMain {
/* ------------------------------------------------------------------------- */
-void calc_view_vector(float *view, float x, float y);
+void calc_view_vector(float view[3], float x, float y);
float mistfactor(float zcor, const float co[3]); /* dist and height, return alpha */
void renderspothalo(struct ShadeInput *shi, float col[4], float alpha);
@@ -95,5 +95,4 @@ extern void init_ao_sphere(struct World *wrld);
extern void init_render_qmcsampler(Render *re);
extern void free_render_qmcsampler(Render *re);
-#endif /* RENDER_EXT_H */
-
+#endif /* __RENDERCORE_H__ */
diff --git a/source/blender/render/intern/include/renderdatabase.h b/source/blender/render/intern/include/renderdatabase.h
index 584e56836fa..5213f14d773 100644
--- a/source/blender/render/intern/include/renderdatabase.h
+++ b/source/blender/render/intern/include/renderdatabase.h
@@ -55,7 +55,6 @@ struct RadFace;
typedef struct VertTableNode {
struct VertRen *vert;
float *rad;
- float *sticky;
float *strand;
float *tangent;
float *stress;
@@ -89,7 +88,7 @@ void free_renderdata_vertnodes(struct VertTableNode *vertnodes);
void free_renderdata_vlaknodes(struct VlakTableNode *vlaknodes);
void project_renderdata(struct Render *re, void (*projectfunc)(const float *, float mat[][4], float *), int do_pano, float xoffs, int do_buckets);
-int clip_render_object(float boundbox[][3], float *bounds, float mat[][4]);
+int clip_render_object(float boundbox[][3], float bounds[4], float mat[][4]);
/* functions are not exported... so wrong names */
@@ -110,7 +109,6 @@ struct ObjectRen *RE_addRenderObject(struct Render *re, struct Object *ob, struc
struct ObjectInstanceRen *RE_addRenderInstance(struct Render *re, struct ObjectRen *obr, struct Object *ob, struct Object *par, int index, int psysindex, float mat[][4], int lay);
void RE_makeRenderInstances(struct Render *re);
-float *RE_vertren_get_sticky(struct ObjectRen *obr, struct VertRen *ver, int verify);
float *RE_vertren_get_stress(struct ObjectRen *obr, struct VertRen *ver, int verify);
float *RE_vertren_get_rad(struct ObjectRen *obr, struct VertRen *ver, int verify);
float *RE_vertren_get_strand(struct ObjectRen *obr, struct VertRen *ver, int verify);
diff --git a/source/blender/render/intern/include/shadbuf.h b/source/blender/render/intern/include/shadbuf.h
index 5cde8e5106a..7c168baada7 100644
--- a/source/blender/render/intern/include/shadbuf.h
+++ b/source/blender/render/intern/include/shadbuf.h
@@ -79,19 +79,19 @@ float ISB_getshadow(ShadeInput *shi, ShadBuf *shb);
/* buffer samples, allocated in camera buffer and pointed to in lampbuffer nodes */
typedef struct ISBSample {
- float zco[3]; /* coordinate in lampview projection */
- short *shadfac; /* initialized zero = full lighted */
- int obi; /* object for face lookup */
- int facenr; /* index in faces list */
+ float zco[3]; /* coordinate in lampview projection */
+ short *shadfac; /* initialized zero = full lighted */
+ int obi; /* object for face lookup */
+ int facenr; /* index in faces list */
} ISBSample;
/* transparent version of buffer sample */
typedef struct ISBSampleA {
- float zco[3]; /* coordinate in lampview projection */
- short *shadfac; /* NULL = full lighted */
- int obi; /* object for face lookup */
- int facenr; /* index in faces list */
- struct ISBSampleA *next; /* in end, we want the first items to align with ISBSample */
+ float zco[3]; /* coordinate in lampview projection */
+ short *shadfac; /* NULL = full lighted */
+ int obi; /* object for face lookup */
+ int facenr; /* index in faces list */
+ struct ISBSampleA *next; /* in end, we want the first items to align with ISBSample */
} ISBSampleA;
/* used for transparent storage only */
diff --git a/source/blender/render/intern/include/shading.h b/source/blender/render/intern/include/shading.h
index a8519d8a7fb..4f6e005d742 100644
--- a/source/blender/render/intern/include/shading.h
+++ b/source/blender/render/intern/include/shading.h
@@ -60,7 +60,7 @@ void shade_material_loop(struct ShadeInput *shi, struct ShadeResult *shr);
void shade_input_set_triangle_i(struct ShadeInput *shi, struct ObjectInstanceRen *obi, struct VlakRen *vlr, short i1, short i2, short i3);
void shade_input_set_triangle(struct ShadeInput *shi, volatile int obi, volatile int facenr, int normal_flip);
void shade_input_copy_triangle(struct ShadeInput *shi, struct ShadeInput *from);
-void shade_input_calc_viewco(struct ShadeInput *shi, float x, float y, float z, float view[3], float *dxyview, float *co, float *dxco, float *dyco);
+void shade_input_calc_viewco(struct ShadeInput *shi, float x, float y, float z, float view[3], float dxyview[2], float co[3], float dxco[3], float dyco[3]);
void shade_input_set_viewco(struct ShadeInput *shi, float x, float y, float sx, float sy, float z);
void shade_input_set_uv(struct ShadeInput *shi);
void shade_input_set_normals(struct ShadeInput *shi);
diff --git a/source/blender/render/intern/include/sunsky.h b/source/blender/render/intern/include/sunsky.h
index 74e42109be5..60fa8aa51ba 100644
--- a/source/blender/render/intern/include/sunsky.h
+++ b/source/blender/render/intern/include/sunsky.h
@@ -43,8 +43,7 @@ typedef struct SunSky {
float perez_Y[5], perez_x[5], perez_y[5];
- /* suggested by glome in
- * http://projects.blender.org/tracker/?func=detail&atid=127&aid=8063&group_id=9*/
+ /* suggested by glome in patch [#8063] */
float horizon_brightness;
float spread;
float sun_brightness;
@@ -69,7 +68,7 @@ typedef struct SunSky {
float atm_BetaRM[3];
} SunSky;
-void InitSunSky(struct SunSky *sunsky, float turb, float *toSun, float horizon_brightness,
+void InitSunSky(struct SunSky *sunsky, float turb, const float toSun[3], float horizon_brightness,
float spread, float sun_brightness, float sun_size, float back_scatter,
float skyblendfac, short skyblendtype, float sky_exposure, float sky_colorspace);
diff --git a/source/blender/render/intern/include/texture.h b/source/blender/render/intern/include/texture.h
index e8f171fe383..4b9fa2d2042 100644
--- a/source/blender/render/intern/include/texture.h
+++ b/source/blender/render/intern/include/texture.h
@@ -76,7 +76,7 @@ void render_realtime_texture(struct ShadeInput *shi, struct Image *ima);
/* imagetexture.h */
-int imagewraposa(struct Tex *tex, struct Image *ima, struct ImBuf *ibuf, const float texvec[3], const float dxt[3], const float dyt[3], struct TexResult *texres);
+int imagewraposa(struct Tex *tex, struct Image *ima, struct ImBuf *ibuf, const float texvec[3], const float dxt[2], const float dyt[2], struct TexResult *texres);
int imagewrap(struct Tex *tex, struct Image *ima, struct ImBuf *ibuf, const float texvec[3], struct TexResult *texres);
void image_sample(struct Image *ima, float fx, float fy, float dx, float dy, float result[4]);
diff --git a/source/blender/render/intern/include/texture_ocean.h b/source/blender/render/intern/include/texture_ocean.h
index 7d4110aadf3..121142aa0b0 100644
--- a/source/blender/render/intern/include/texture_ocean.h
+++ b/source/blender/render/intern/include/texture_ocean.h
@@ -23,4 +23,9 @@
* ***** END GPL LICENSE BLOCK *****
*/
-int ocean_texture(struct Tex *tex, float *texvec, struct TexResult *texres);
+#ifndef __TEXTURE_OCEAN_H__
+#define __TEXTURE_OCEAN_H__
+
+int ocean_texture(struct Tex *tex, const float texvec[2], struct TexResult *texres);
+
+#endif /* __TEXTURE_OCEAN_H__ */
diff --git a/source/blender/render/intern/include/volume_precache.h b/source/blender/render/intern/include/volume_precache.h
index 8e402bc5418..9aa280d8276 100644
--- a/source/blender/render/intern/include/volume_precache.h
+++ b/source/blender/render/intern/include/volume_precache.h
@@ -30,8 +30,8 @@
*/
-void global_bounds_obi(Render *re, ObjectInstanceRen *obi, float *bbmin, float *bbmax);
-int point_inside_volume_objectinstance(Render *re, ObjectInstanceRen *obi, float *co);
+void global_bounds_obi(Render *re, ObjectInstanceRen *obi, float bbmin[3], float bbmax[3]);
+int point_inside_volume_objectinstance(Render *re, ObjectInstanceRen *obi, const float co[3]);
void volume_precache(Render *re);
void free_volume_precache(Render *re);
diff --git a/source/blender/render/intern/raytrace/bvh.h b/source/blender/render/intern/raytrace/bvh.h
index 103c04a590f..47d3a892e84 100644
--- a/source/blender/render/intern/raytrace/bvh.h
+++ b/source/blender/render/intern/raytrace/bvh.h
@@ -91,7 +91,7 @@ static inline int rayobject_bb_intersect_test(const Isect *isec, const float *_b
if (t1x > t2y || t2x < t1y || t1x > t2z || t2x < t1z || t1y > t2z || t2y < t1z) return 0;
if (t2x < 0.0f || t2y < 0.0f || t2z < 0.0f) return 0;
if (t1x > isec->dist || t1y > isec->dist || t1z > isec->dist) return 0;
- RE_RC_COUNT(isec->raycounter->bb.hit);
+ RE_RC_COUNT(isec->raycounter->bb.hit);
return 1;
}
diff --git a/source/blender/render/intern/raytrace/rayobject.cpp b/source/blender/render/intern/raytrace/rayobject.cpp
index 6f14c6153f9..c3babf99d51 100644
--- a/source/blender/render/intern/raytrace/rayobject.cpp
+++ b/source/blender/render/intern/raytrace/rayobject.cpp
@@ -467,7 +467,7 @@ float RE_rayobject_cost(RayObject *r)
/* Bounding Boxes */
-void RE_rayobject_merge_bb(RayObject *r, float *min, float *max)
+void RE_rayobject_merge_bb(RayObject *r, float min[3], float max[3])
{
if (RE_rayobject_isRayFace(r)) {
RayFace *face = (RayFace *) RE_rayobject_align(r);
diff --git a/source/blender/render/intern/raytrace/rayobject_blibvh.cpp b/source/blender/render/intern/raytrace/rayobject_blibvh.cpp
index 2d642a0a0d8..198577f61c6 100644
--- a/source/blender/render/intern/raytrace/rayobject_blibvh.cpp
+++ b/source/blender/render/intern/raytrace/rayobject_blibvh.cpp
@@ -79,7 +79,7 @@ typedef struct BVHObject {
RayObject *RE_rayobject_blibvh_create(int size)
{
BVHObject *obj = (BVHObject *)MEM_callocN(sizeof(BVHObject), "BVHObject");
- assert(RE_rayobject_isAligned(obj)); /* RayObject API assumes real data to be 4-byte aligned */
+ assert(RE_rayobject_isAligned(obj)); /* RayObject API assumes real data to be 4-byte aligned */
obj->rayobj.api = &bvh_api;
obj->bvh = BLI_bvhtree_new(size, 0.0, 4, 6);
@@ -137,7 +137,7 @@ static void RE_rayobject_blibvh_add(RayObject *o, RayObject *ob)
DO_MIN(min_max, obj->bb[0]);
DO_MAX(min_max + 3, obj->bb[1]);
- BLI_bvhtree_insert(obj->bvh, obj->next_leaf - obj->leafs, min_max, 2);
+ BLI_bvhtree_insert(obj->bvh, obj->next_leaf - obj->leafs, min_max, 2);
*(obj->next_leaf++) = ob;
}
diff --git a/source/blender/render/intern/raytrace/rayobject_instance.cpp b/source/blender/render/intern/raytrace/rayobject_instance.cpp
index c3e761ae069..f797f7a4311 100644
--- a/source/blender/render/intern/raytrace/rayobject_instance.cpp
+++ b/source/blender/render/intern/raytrace/rayobject_instance.cpp
@@ -59,7 +59,7 @@ static RayObjectAPI instance_api =
RE_rayobject_instance_free,
RE_rayobject_instance_bb,
RE_rayobject_instance_cost,
- RE_rayobject_instance_hint_bb
+ RE_rayobject_instance_hint_bb
};
typedef struct InstanceRayObject {
diff --git a/source/blender/render/intern/raytrace/rayobject_internal.h b/source/blender/render/intern/raytrace/rayobject_internal.h
index 3f768e5adcb..92ac39909a8 100644
--- a/source/blender/render/intern/raytrace/rayobject_internal.h
+++ b/source/blender/render/intern/raytrace/rayobject_internal.h
@@ -50,7 +50,7 @@ typedef int (*RE_rayobjectcontrol_test_break_callback)(void *data);
typedef struct RayObjectControl {
void *data;
- RE_rayobjectcontrol_test_break_callback test_break;
+ RE_rayobjectcontrol_test_break_callback test_break;
} RayObjectControl;
/* Returns true if for some reason a heavy processing function should stop
@@ -124,9 +124,9 @@ typedef int (*RE_rayobject_raycast_callback)(RayObject *, struct Isect *);
typedef void (*RE_rayobject_add_callback)(RayObject *raytree, RayObject *rayobject);
typedef void (*RE_rayobject_done_callback)(RayObject *);
typedef void (*RE_rayobject_free_callback)(RayObject *);
-typedef void (*RE_rayobject_merge_bb_callback)(RayObject *, float *min, float *max);
+typedef void (*RE_rayobject_merge_bb_callback)(RayObject *, float min[3], float max[3]);
typedef float (*RE_rayobject_cost_callback)(RayObject *);
-typedef void (*RE_rayobject_hint_bb_callback)(RayObject *, struct RayHint *, float *, float *);
+typedef void (*RE_rayobject_hint_bb_callback)(RayObject *, struct RayHint *, float min[3], float max[3]);
typedef struct RayObjectAPI {
RE_rayobject_raycast_callback raycast;
@@ -154,5 +154,4 @@ int RE_rayobject_intersect(RayObject *r, struct Isect *i);
}
#endif
-#endif
-
+#endif /* __RAYOBJECT_INTERNAL_H__ */
diff --git a/source/blender/render/intern/raytrace/rayobject_octree.cpp b/source/blender/render/intern/raytrace/rayobject_octree.cpp
index 5ae716ac942..77e9dc9d8fd 100644
--- a/source/blender/render/intern/raytrace/rayobject_octree.cpp
+++ b/source/blender/render/intern/raytrace/rayobject_octree.cpp
@@ -382,8 +382,12 @@ static void d2dda(Octree *oc, short b1, short b2, short c1, short c2, char *ocfa
while (TRUE) {
- if (x < 0 || y < 0 || x >= oc->ocres || y >= oc->ocres) ;
- else ocface[oc->ocres * x + y] = 1;
+ if (x < 0 || y < 0 || x >= oc->ocres || y >= oc->ocres) {
+ /* pass*/
+ }
+ else {
+ ocface[oc->ocres * x + y] = 1;
+ }
labdao = labda;
if (labdax == labday) {
diff --git a/source/blender/render/intern/raytrace/rayobject_qbvh.cpp b/source/blender/render/intern/raytrace/rayobject_qbvh.cpp
index 16d70297a34..33ce3bd33d5 100644
--- a/source/blender/render/intern/raytrace/rayobject_qbvh.cpp
+++ b/source/blender/render/intern/raytrace/rayobject_qbvh.cpp
@@ -68,7 +68,7 @@ void bvh_done<QBVHTree>(QBVHTree *obj)
//Build and optimize the tree
//TODO do this in 1 pass (half memory usage during building)
- VBVHNode *root = BuildBinaryVBVH<VBVHNode>(arena1, &obj->rayobj.control).transform(obj->builder);
+ VBVHNode *root = BuildBinaryVBVH<VBVHNode>(arena1, &obj->rayobj.control).transform(obj->builder);
if (RE_rayobjectcontrol_test_break(&obj->rayobj.control)) {
BLI_memarena_free(arena1);
diff --git a/source/blender/render/intern/raytrace/rayobject_raycounter.cpp b/source/blender/render/intern/raytrace/rayobject_raycounter.cpp
index 7d86b6cf8cb..5335bf50cbc 100644
--- a/source/blender/render/intern/raytrace/rayobject_raycounter.cpp
+++ b/source/blender/render/intern/raytrace/rayobject_raycounter.cpp
@@ -43,10 +43,10 @@ void RE_RC_INFO(RayCounter *info)
printf("\n");
printf("BB tests: %llu\n", info->bb.test );
printf("BB hits: %llu\n", info->bb.hit );
- printf("\n");
+ printf("\n");
printf("SIMD BB tests: %llu\n", info->simd_bb.test );
printf("SIMD BB hits: %llu\n", info->simd_bb.hit );
- printf("\n");
+ printf("\n");
printf("Primitives tests: %llu\n", info->faces.test );
printf("Primitives hits: %llu\n", info->faces.hit );
printf("------------------------------------\n");
diff --git a/source/blender/render/intern/raytrace/rayobject_rtbuild.cpp b/source/blender/render/intern/raytrace/rayobject_rtbuild.cpp
index ddc84408e26..bae65c492f4 100644
--- a/source/blender/render/intern/raytrace/rayobject_rtbuild.cpp
+++ b/source/blender/render/intern/raytrace/rayobject_rtbuild.cpp
@@ -77,7 +77,7 @@ RTBuilder *rtbuild_create(int size)
for (int i = 0; i < 3; i++) {
builder->sorted_begin[i] = (RTBuilder::Object **)MEM_mallocN(sizeof(RTBuilder::Object *) * size, "RTBuilder.sorted_objects");
builder->sorted_end[i] = builder->sorted_begin[i];
- }
+ }
return builder;
@@ -185,7 +185,7 @@ RTBuilder *rtbuild_get_child(RTBuilder *b, int child, RTBuilder *tmp)
return tmp;
}
-void rtbuild_calc_bb(RTBuilder *b)
+static void rtbuild_calc_bb(RTBuilder *b)
{
if (b->bb[0] == 1.0e30f) {
for (RTBuilder::Object **index = b->sorted_begin[0]; index != b->sorted_end[0]; index++)
@@ -193,7 +193,7 @@ void rtbuild_calc_bb(RTBuilder *b)
}
}
-void rtbuild_merge_bb(RTBuilder *b, float *min, float *max)
+void rtbuild_merge_bb(RTBuilder *b, float min[3], float max[3])
{
rtbuild_calc_bb(b);
DO_MIN(b->bb, min);
@@ -224,7 +224,7 @@ int rtbuild_mean_split(RTBuilder *b, int nchilds, int axis)
Mleafs_per_child = s / nchilds;
mleafs_per_child = Mleafs_per_child / nchilds;
- //split min leafs per child
+ //split min leafs per child
b->child_offset[0] = 0;
for (i = 1; i <= nchilds; i++)
b->child_offset[i] = mleafs_per_child;
@@ -295,7 +295,7 @@ int rtbuild_median_split(RTBuilder *b, float *separators, int nchilds, int axis)
return rtbuild_mean_split(b, nchilds, axis);
return nchilds;
- }
+ }
}
int rtbuild_median_split_largest_axis(RTBuilder *b, int nchilds)
@@ -324,7 +324,7 @@ struct SweepCost {
/* Object Surface Area Heuristic splitter */
int rtbuild_heuristic_object_split(RTBuilder *b, int nchilds)
{
- int size = rtbuild_size(b);
+ int size = rtbuild_size(b);
assert(nchilds == 2);
assert(size > 1);
int baxis = -1, boffset = 0;
@@ -348,12 +348,12 @@ int rtbuild_heuristic_object_split(RTBuilder *b, int nchilds)
sweep[i].cost = obj[i]->cost;
}
else {
- sweep[i].bb[0] = MIN2(obj[i]->bb[0], sweep[i + 1].bb[0]);
- sweep[i].bb[1] = MIN2(obj[i]->bb[1], sweep[i + 1].bb[1]);
- sweep[i].bb[2] = MIN2(obj[i]->bb[2], sweep[i + 1].bb[2]);
- sweep[i].bb[3] = MAX2(obj[i]->bb[3], sweep[i + 1].bb[3]);
- sweep[i].bb[4] = MAX2(obj[i]->bb[4], sweep[i + 1].bb[4]);
- sweep[i].bb[5] = MAX2(obj[i]->bb[5], sweep[i + 1].bb[5]);
+ sweep[i].bb[0] = min_ff(obj[i]->bb[0], sweep[i + 1].bb[0]);
+ sweep[i].bb[1] = min_ff(obj[i]->bb[1], sweep[i + 1].bb[1]);
+ sweep[i].bb[2] = min_ff(obj[i]->bb[2], sweep[i + 1].bb[2]);
+ sweep[i].bb[3] = max_ff(obj[i]->bb[3], sweep[i + 1].bb[3]);
+ sweep[i].bb[4] = max_ff(obj[i]->bb[4], sweep[i + 1].bb[4]);
+ sweep[i].bb[5] = max_ff(obj[i]->bb[5], sweep[i + 1].bb[5]);
sweep[i].cost = obj[i]->cost + sweep[i + 1].cost;
}
// right_cost += obj[i]->cost;
@@ -375,8 +375,8 @@ int rtbuild_heuristic_object_split(RTBuilder *b, int nchilds)
// not using log seems to have no impact on raytracing perf, but
// makes tree construction quicker, left out for now to test (brecht)
- // left_side = bb_area(sweep_left.bb, sweep_left.bb+3)*(sweep_left.cost+logf((float)i));
- // right_side= bb_area(sweep[i].bb, sweep[i].bb+3)*(sweep[i].cost+logf((float)size-i));
+ // left_side = bb_area(sweep_left.bb, sweep_left.bb + 3) * (sweep_left.cost + logf((float)i));
+ // right_side = bb_area(sweep[i].bb, sweep[i].bb + 3) * (sweep[i].cost + logf((float)size - i));
left_side = bb_area(sweep_left.bb, sweep_left.bb + 3) * (sweep_left.cost);
right_side = bb_area(sweep[i].bb, sweep[i].bb + 3) * (sweep[i].cost);
hcost = left_side + right_side;
@@ -429,7 +429,7 @@ int rtbuild_heuristic_object_split(RTBuilder *b, int nchilds)
for (int i = 0; i < 3; i++)
std::stable_partition(b->sorted_begin[i], b->sorted_end[i], selected_node);
- return nchilds;
+ return nchilds;
}
/*
@@ -457,26 +457,26 @@ static void split_leafs(RTBuilder *b, int *nth, int partitions, int split_axis)
/*
* Bounding Box utils
*/
-float bb_volume(float *min, float *max)
+float bb_volume(const float min[3], const float max[3])
{
return (max[0] - min[0]) * (max[1] - min[1]) * (max[2] - min[2]);
}
-float bb_area(float *min, float *max)
+float bb_area(const float min[3], const float max[3])
{
float sub[3], a;
sub[0] = max[0] - min[0];
sub[1] = max[1] - min[1];
sub[2] = max[2] - min[2];
- a = (sub[0] * sub[1] + sub[0] * sub[2] + sub[1] * sub[2]) * 2;
+ a = (sub[0] * sub[1] + sub[0] * sub[2] + sub[1] * sub[2]) * 2.0f;
/* used to have an assert() here on negative results
* however, in this case its likely some overflow or ffast math error.
* so just return 0.0f instead. */
return a < 0.0f ? 0.0f : a;
}
-int bb_largest_axis(float *min, float *max)
+int bb_largest_axis(const float min[3], const float max[3])
{
float sub[3];
@@ -494,10 +494,12 @@ int bb_largest_axis(float *min, float *max)
return 1;
else
return 2;
- }
+ }
}
-int bb_fits_inside(float *outer_min, float *outer_max, float *inner_min, float *inner_max)
+/* only returns 0 if merging inner and outerbox would create a box larger than outer box */
+int bb_fits_inside(const float outer_min[3], const float outer_max[3],
+ const float inner_min[3], const float inner_max[3])
{
int i;
for (i = 0; i < 3; i++)
@@ -506,5 +508,5 @@ int bb_fits_inside(float *outer_min, float *outer_max, float *inner_min, float *
for (i = 0; i < 3; i++)
if (outer_max[i] < inner_max[i]) return 0;
- return 1;
+ return 1;
}
diff --git a/source/blender/render/intern/raytrace/rayobject_rtbuild.h b/source/blender/render/intern/raytrace/rayobject_rtbuild.h
index 22e3d009c07..9e296da144b 100644
--- a/source/blender/render/intern/raytrace/rayobject_rtbuild.h
+++ b/source/blender/render/intern/raytrace/rayobject_rtbuild.h
@@ -86,7 +86,7 @@ RTBuilder *rtbuild_create(int size);
void rtbuild_free(RTBuilder *b);
void rtbuild_add(RTBuilder *b, RayObject *o);
void rtbuild_done(RTBuilder *b, RayObjectControl *c);
-void rtbuild_merge_bb(RTBuilder *b, float *min, float *max);
+void rtbuild_merge_bb(RTBuilder *b, float min[3], float max[3]);
int rtbuild_size(RTBuilder *b);
RayObject *rtbuild_get_primitive(RTBuilder *b, int offset);
@@ -109,13 +109,14 @@ int rtbuild_median_split_largest_axis(RTBuilder *b, int nchilds);
/* bb utils */
-float bb_area(float *min, float *max);
-float bb_volume(float *min, float *max);
-int bb_largest_axis(float *min, float *max);
-int bb_fits_inside(float *outer_min, float *outer_max, float *inner_min, float *inner_max); /* only returns 0 if merging inner and outerbox would create a box larger than outer box */
+float bb_area(const float min[3], const float max[3]);
+float bb_volume(const float min[3], const float max[3]);
+int bb_largest_axis(const float min[3], const float max[3]);
+int bb_fits_inside(const float outer_min[3], const float outer_max[3],
+ const float inner_min[3], const float inner_max[3]);
#ifdef __cplusplus
}
#endif
-#endif
+#endif /* __RAYOBJECT_RTBUILD_H__ */
diff --git a/source/blender/render/intern/raytrace/rayobject_vbvh.cpp b/source/blender/render/intern/raytrace/rayobject_vbvh.cpp
index 9e7075438cb..d03bdb74407 100644
--- a/source/blender/render/intern/raytrace/rayobject_vbvh.cpp
+++ b/source/blender/render/intern/raytrace/rayobject_vbvh.cpp
@@ -112,7 +112,7 @@ void bvh_done<VBVHTree>(VBVHTree *obj)
//Finds the optimal packing of this tree using a given cost model
//TODO this uses quite a lot of memory, find ways to reduce memory usage during building
- OVBVHNode *root = BuildBinaryVBVH<OVBVHNode>(arena2).transform(obj->builder);
+ OVBVHNode *root = BuildBinaryVBVH<OVBVHNode>(arena2).transform(obj->builder);
VBVH_optimalPackSIMD<OVBVHNode, PackCost>(PackCost()).transform(root);
obj->root = Reorganize_VBVH<OVBVHNode>(arena1).transform(root);
@@ -125,7 +125,7 @@ void bvh_done<VBVHTree>(VBVHTree *obj)
obj->builder = NULL;
obj->node_arena = arena1;
- obj->cost = 1.0;
+ obj->cost = 1.0;
}
template<int StackSize>
@@ -152,7 +152,8 @@ void bvh_hint_bb(Tree *tree, LCTSHint *hint, float *UNUSED(min), float *UNUSED(m
}
}
-void bfree(VBVHTree *tree)
+#if 0 /* UNUSED */
+static void bfree(VBVHTree *tree)
{
if (tot_pushup + tot_pushdown + tot_hints + tot_moves) {
if (G.debug & G_DEBUG) {
@@ -169,6 +170,7 @@ void bfree(VBVHTree *tree)
}
bvh_free(tree);
}
+#endif
/* the cast to pointer function is needed to workarround gcc bug: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=11407 */
template<class Tree, int STACK_SIZE>
diff --git a/source/blender/render/intern/raytrace/reorganize.h b/source/blender/render/intern/raytrace/reorganize.h
index a9ed71a76bc..9d9711eee56 100644
--- a/source/blender/render/intern/raytrace/reorganize.h
+++ b/source/blender/render/intern/raytrace/reorganize.h
@@ -75,7 +75,7 @@ void reorganize_find_fittest_parent(Node *tree, Node *node, std::pair<float, Nod
float pcost = bb_area(parent->bb, parent->bb + 3);
cost = std::min(cost, std::make_pair(pcost, parent) );
for (Node *child = parent->child; child; child = child->sibling)
- q.push(child);
+ q.push(child);
}
}
}
@@ -140,7 +140,7 @@ void remove_useless(Node *node, Node **new_node)
(*prev)->sibling = next;
prev = &((*prev)->sibling);
}
- }
+ }
}
if (node->child) {
if (RE_rayobject_isAligned(node->child) && node->child->sibling == 0)
@@ -181,7 +181,7 @@ void pushup(Node *parent)
*prev = child;
prev = &(*prev)->sibling;
child = *prev;
- }
+ }
}
for (Node *child = parent->child; RE_rayobject_isAligned(child) && child; child = child->sibling)
@@ -205,13 +205,13 @@ void pushup_simd(Node *parent)
n += (cn - 1);
append_sibling(child, child->child);
child = child->sibling;
- *prev = child;
+ *prev = child;
}
else {
*prev = child;
prev = &(*prev)->sibling;
child = *prev;
- }
+ }
}
for (Node *child = parent->child; RE_rayobject_isAligned(child) && child; child = child->sibling)
@@ -320,7 +320,7 @@ struct OVBVHNode {
/*
* Reorganize the node based on calculated cut costs
- */
+ */
int best_cutsize;
void set_cut(int cutsize, OVBVHNode ***cut)
{
@@ -357,7 +357,7 @@ struct OVBVHNode {
//Optimize new childs
for (OVBVHNode *child = this->child; child && RE_rayobject_isAligned(child); child = child->sibling)
child->optimize();
- }
+ }
}
};
@@ -431,7 +431,7 @@ struct VBVH_optimalPackSIMD {
current_size -= bt[j][current_size];
}
}
- }
+ }
}
};
@@ -493,6 +493,6 @@ struct VBVH_optimalPackSIMD {
if ((G.debug & G_DEBUG) && first) printf("expected cost = %f (%d)\n", node->cut_cost[0], node->best_cutsize);
node->optimize();
}
- return node;
- }
+ return node;
+ }
};
diff --git a/source/blender/render/intern/raytrace/svbvh.h b/source/blender/render/intern/raytrace/svbvh.h
index a58094e5021..6ec75ebb527 100644
--- a/source/blender/render/intern/raytrace/svbvh.h
+++ b/source/blender/render/intern/raytrace/svbvh.h
@@ -29,12 +29,11 @@
* \ingroup render
*/
-
-#ifdef __SSE__
-
#ifndef __SVBVH_H__
#define __SVBVH_H__
+#ifdef __SSE__
+
#include "bvh.h"
#include "BLI_memarena.h"
#include "BKE_global.h"
@@ -94,10 +93,10 @@ static int svbvh_bb_intersect_test(const Isect *isec, const float *_bb)
RE_RC_COUNT(isec->raycounter->bb.test);
if (t1x > t2y || t2x < t1y || t1x > t2z || t2x < t1z || t1y > t2z || t2y < t1z) return 0;
- if (t2x < 0.0 || t2y < 0.0 || t2z < 0.0) return 0;
+ if (t2x < 0.0f || t2y < 0.0f || t2z < 0.0f) return 0;
if (t1x > isec->dist || t1y > isec->dist || t1z > isec->dist) return 0;
- RE_RC_COUNT(isec->raycounter->bb.hit);
+ RE_RC_COUNT(isec->raycounter->bb.hit);
return 1;
}
@@ -166,16 +165,16 @@ inline void bvh_node_merge_bb<SVBVHNode>(SVBVHNode *node, float min[3], float ma
for (i = 0; i + 4 <= node->nchilds; i += 4) {
float *res = node->child_bb + 6 * i;
for (int j = 0; j < 3; j++) {
- min[j] = minf(res[4 * j + 0],
- minf(res[4 * j + 1],
- minf(res[4 * j + 2],
- minf(res[4 * j + 3], min[j]))));
+ min[j] = min_ff(res[4 * j + 0],
+ min_ff(res[4 * j + 1],
+ min_ff(res[4 * j + 2],
+ min_ff(res[4 * j + 3], min[j]))));
}
for (int j = 0; j < 3; j++) {
- max[j] = maxf(res[4 * (j + 3) + 0],
- maxf(res[4 * (j + 3) + 1],
- maxf(res[4 * (j + 3) + 2],
- maxf(res[4 * (j + 3) + 3], max[j]))));
+ max[j] = max_ff(res[4 * (j + 3) + 0],
+ max_ff(res[4 * (j + 3) + 1],
+ max_ff(res[4 * (j + 3) + 2],
+ max_ff(res[4 * (j + 3) + 3], max[j]))));
}
}
@@ -231,7 +230,7 @@ struct Reorganize_SVBVH {
return node;
}
- void copy_bb(float *bb, const float *old_bb)
+ void copy_bb(float bb[6], const float old_bb[6])
{
std::copy(old_bb, old_bb + 6, bb);
}
@@ -282,7 +281,7 @@ struct Reorganize_SVBVH {
useless_bb += alloc_childs - nchilds;
while (alloc_childs > nchilds) {
- const static float def_bb[6] = { FLT_MAX, FLT_MAX, FLT_MAX, FLT_MIN, FLT_MIN, FLT_MIN };
+ const static float def_bb[6] = {FLT_MAX, FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX};
alloc_childs--;
node->child[alloc_childs] = NULL;
copy_bb(node->child_bb + alloc_childs * 6, def_bb);
@@ -308,10 +307,9 @@ struct Reorganize_SVBVH {
prepare_for_simd(node);
return node;
- }
+ }
};
-#endif
-
-#endif //__SSE__
+#endif /* __SSE__ */
+#endif /* __SVBVH_H__ */
diff --git a/source/blender/render/intern/raytrace/vbvh.h b/source/blender/render/intern/raytrace/vbvh.h
index ec671f95c76..9755bf89668 100644
--- a/source/blender/render/intern/raytrace/vbvh.h
+++ b/source/blender/render/intern/raytrace/vbvh.h
@@ -233,6 +233,6 @@ struct Reorganize_VBVH {
*child_ptr = 0;
return node;
- }
+ }
};
#endif
diff --git a/source/blender/render/intern/source/convertblender.c b/source/blender/render/intern/source/convertblender.c
index 51e5b30a31c..e305f434ebb 100644
--- a/source/blender/render/intern/source/convertblender.c
+++ b/source/blender/render/intern/source/convertblender.c
@@ -41,6 +41,7 @@
#include "BLI_rand.h"
#include "BLI_memarena.h"
#include "BLI_ghash.h"
+#include "BLI_linklist.h"
#include "DNA_armature_types.h"
#include "DNA_camera_types.h"
@@ -123,6 +124,9 @@
/* or for checking vertex normal flips */
#define FLT_EPSILON10 1.19209290e-06F
+/* could enable at some point but for now there are far too many conversions */
+#pragma GCC diagnostic ignored "-Wdouble-promotion"
+
/* ------------------------------------------------------------------------- */
/* Stuff for stars. This sits here because it uses gl-things. Part of
@@ -155,7 +159,7 @@ static HaloRen *initstar(Render *re, ObjectRen *obr, const float vec[3], float h
*/
void RE_make_stars(Render *re, Scene *scenev3d, void (*initfunc)(void),
- void (*vertexfunc)(float*), void (*termfunc)(void))
+ void (*vertexfunc)(float*), void (*termfunc)(void))
{
extern unsigned char hash[512];
ObjectRen *obr= NULL;
@@ -226,7 +230,7 @@ void RE_make_stars(Render *re, Scene *scenev3d, void (*initfunc)(void),
hlfrand = 2.0 * dblrand;
if (initfunc) {
- initfunc();
+ initfunc();
}
if (re) /* add render object for stars */
@@ -363,7 +367,7 @@ static void split_v_renderfaces(ObjectRen *obr, int startvlak, int UNUSED(startv
if (v==0) {
vlr->v1 = RE_vertren_copy(obr, vlr->v1);
- }
+ }
}
}
}
@@ -445,7 +449,7 @@ static void calc_edge_stress(Render *UNUSED(re), ObjectRen *obr, Mesh *me)
}
/* gets tangent from tface or orco */
-static void calc_tangent_vector(ObjectRen *obr, VertexTangent **vtangents, MemArena *arena, VlakRen *vlr, int do_nmap_tangent, int do_tangent)
+static void calc_tangent_vector(ObjectRen *obr, VlakRen *vlr, int do_tangent)
{
MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
@@ -480,12 +484,6 @@ static void calc_tangent_vector(ObjectRen *obr, VertexTangent **vtangents, MemAr
add_v3_v3(tav, tang);
}
- if (do_nmap_tangent) {
- sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
- sum_or_add_vertex_tangent(arena, &vtangents[v2->index], tang, uv2);
- sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
- }
-
if (v4) {
tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, vlr->n, tang);
@@ -497,12 +495,6 @@ static void calc_tangent_vector(ObjectRen *obr, VertexTangent **vtangents, MemAr
tav= RE_vertren_get_tangent(obr, v4, 1);
add_v3_v3(tav, tang);
}
-
- if (do_nmap_tangent) {
- sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
- sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
- sum_or_add_vertex_tangent(arena, &vtangents[v4->index], tang, uv4);
- }
}
}
@@ -567,8 +559,14 @@ static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const
//assert(vert_index>=0 && vert_index<4);
SRenderMeshToTangent * pMesh = (SRenderMeshToTangent *) pContext->m_pUserData;
VlakRen *vlr= RE_findOrAddVlak(pMesh->obr, face_num);
- const float *n= (&vlr->v1)[vert_index]->n;
- copy_v3_v3(fNorm, n);
+
+ if (vlr->flag & ME_SMOOTH) {
+ const float *n = (&vlr->v1)[vert_index]->n;
+ copy_v3_v3(fNorm, n);
+ }
+ else {
+ negate_v3_v3(fNorm, vlr->n);
+ }
}
static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
{
@@ -584,17 +582,8 @@ static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent
static void calc_vertexnormals(Render *UNUSED(re), ObjectRen *obr, int do_tangent, int do_nmap_tangent)
{
- MemArena *arena= NULL;
- VertexTangent **vtangents= NULL;
int a;
- if (do_nmap_tangent) {
- arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "nmap tangent arena");
- BLI_memarena_use_calloc(arena);
-
- vtangents= MEM_callocN(sizeof(VertexTangent*)*obr->totvert, "VertexTangent");
- }
-
/* clear all vertex normals */
for (a=0; a<obr->totvert; a++) {
VertRen *ver= RE_findOrAddVert(obr, a);
@@ -612,10 +601,10 @@ static void calc_vertexnormals(Render *UNUSED(re), ObjectRen *obr, int do_tangen
accumulate_vertex_normals(vlr->v1->n, vlr->v2->n, vlr->v3->n, n4,
vlr->n, vlr->v1->co, vlr->v2->co, vlr->v3->co, c4);
}
- if (do_nmap_tangent || do_tangent) {
+ if (do_tangent) {
/* tangents still need to be calculated for flat faces too */
/* weighting removed, they are not vertexnormals */
- calc_tangent_vector(obr, vtangents, arena, vlr, do_nmap_tangent, do_tangent);
+ calc_tangent_vector(obr, vlr, do_tangent);
}
}
@@ -629,32 +618,6 @@ static void calc_vertexnormals(Render *UNUSED(re), ObjectRen *obr, int do_tangen
if (is_zero_v3(vlr->v3->n)) copy_v3_v3(vlr->v3->n, vlr->n);
if (vlr->v4 && is_zero_v3(vlr->v4->n)) copy_v3_v3(vlr->v4->n, vlr->n);
}
-
- if (do_nmap_tangent) {
- VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
- MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
-
- if (tface) {
- int k=0;
- float *vtang, *ftang= RE_vlakren_get_nmap_tangent(obr, vlr, 1);
-
- vtang= find_vertex_tangent(vtangents[v1->index], tface->uv[0]);
- copy_v3_v3(ftang, vtang);
- normalize_v3(ftang);
- vtang= find_vertex_tangent(vtangents[v2->index], tface->uv[1]);
- copy_v3_v3(ftang+4, vtang);
- normalize_v3(ftang+4);
- vtang= find_vertex_tangent(vtangents[v3->index], tface->uv[2]);
- copy_v3_v3(ftang+8, vtang);
- normalize_v3(ftang+8);
- if (v4) {
- vtang= find_vertex_tangent(vtangents[v4->index], tface->uv[3]);
- copy_v3_v3(ftang+12, vtang);
- normalize_v3(ftang+12);
- }
- for (k=0; k<4; k++) ftang[4*k+3]=1;
- }
- }
}
/* normalize vertex normals */
@@ -674,6 +637,7 @@ static void calc_vertexnormals(Render *UNUSED(re), ObjectRen *obr, int do_tangen
}
}
+ /* normal mapping tangent with mikktspace */
if (do_nmap_tangent != FALSE) {
SRenderMeshToTangent mesh2tangent;
SMikkTSpaceContext sContext;
@@ -695,11 +659,6 @@ static void calc_vertexnormals(Render *UNUSED(re), ObjectRen *obr, int do_tangen
genTangSpaceDefault(&sContext);
}
-
- if (arena)
- BLI_memarena_free(arena);
- if (vtangents)
- MEM_freeN(vtangents);
}
/* ------------------------------------------------------------------------- */
@@ -881,7 +840,7 @@ static void autosmooth(Render *UNUSED(re), ObjectRen *obr, float mat[][4], int d
else
normal_tri_v3(vlr->n, vlr->v3->co, vlr->v2->co, vlr->v1->co);
}
- }
+ }
}
/* ------------------------------------------------------------------------- */
@@ -1569,9 +1528,12 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
int i, a, k, max_k=0, totpart, do_simplify = FALSE, do_surfacecache = FALSE, use_duplimat = FALSE;
int totchild=0;
int seed, path_nbr=0, orco1=0, num;
- int totface, *origindex = 0;
+ int totface;
char **uv_name=0;
+ const int *index_mf_to_mpoly = NULL;
+ const int *index_mp_to_orig = NULL;
+
/* 1. check that everything is ok & updated */
if (psys==NULL)
return 0;
@@ -1612,7 +1574,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
psys->flag |= PSYS_DRAWING;
- rng= rng_new(psys->seed);
+ rng= BLI_rng_new(psys->seed);
totpart=psys->totpart;
@@ -1741,9 +1703,13 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
do_surfacecache = TRUE;
totface= psmd->dm->getNumTessFaces(psmd->dm);
- origindex= psmd->dm->getTessFaceDataArray(psmd->dm, CD_ORIGINDEX);
+ index_mf_to_mpoly = psmd->dm->getTessFaceDataArray(psmd->dm, CD_ORIGINDEX);
+ index_mp_to_orig = psmd->dm->getPolyDataArray(psmd->dm, CD_ORIGINDEX);
+ if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) {
+ index_mf_to_mpoly = index_mp_to_orig = NULL;
+ }
for (a=0; a<totface; a++)
- strandbuf->totbound= MAX2(strandbuf->totbound, (origindex)? origindex[a]: a);
+ strandbuf->totbound = max_ii(strandbuf->totbound, (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, a): a);
strandbuf->totbound++;
strandbuf->bound= MEM_callocN(sizeof(StrandBound)*strandbuf->totbound, "StrandBound");
@@ -1762,7 +1728,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
/* 3. start creating renderable things */
for (a=0, pa=pars; a<totpart+totchild; a++, pa++, seed++) {
- random = rng_getFloat(rng);
+ random = BLI_rng_get_float(rng);
/* setup per particle individual stuff */
if (a<totpart) {
if (pa->flag & PARS_UNEXIST) continue;
@@ -1854,7 +1820,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
do_simplify = psys_render_simplify_params(psys, cpa, simplify);
if (strandbuf) {
- int orignum= (origindex)? origindex[cpa->num]: cpa->num;
+ int orignum = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, cpa->num) : cpa->num;
if (orignum > sbound - strandbuf->bound) {
sbound= strandbuf->bound + orignum;
@@ -1938,7 +1904,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
copy_v3_v3(state.vel, (cache+k)->vel);
}
else
- continue;
+ continue;
if (k > 0)
curlen += len_v3v3((cache+k-1)->co, (cache+k)->co);
@@ -2098,7 +2064,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
if (states)
MEM_freeN(states);
- rng_free(rng);
+ BLI_rng_free(rng);
psys->flag &= ~PSYS_DRAWING;
@@ -2260,14 +2226,6 @@ static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, Ve
if ((texco & TEXCO_ORCO) && (vr->orco)) {
copy_v3_v3(shi->lo, vr->orco);
}
- if (texco & TEXCO_STICKY) {
- float *sticky= RE_vertren_get_sticky(obr, vr, 0);
- if (sticky) {
- shi->sticky[0]= sticky[0];
- shi->sticky[1]= sticky[1];
- shi->sticky[2]= 0.0f;
- }
- }
if (texco & TEXCO_GLOB) {
copy_v3_v3(shi->gl, shi->co);
mul_m4_v3(re->viewinv, shi->gl);
@@ -2374,7 +2332,7 @@ static void displace_render_face(Render *re, ObjectRen *obr, VlakRen *vlr, float
/* Recalculate the face normal - if flipped before, flip now */
if (vlr->v4) {
normal_quad_v3(vlr->n, vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co);
- }
+ }
else {
normal_tri_v3(vlr->n, vlr->v3->co, vlr->v2->co, vlr->v1->co);
}
@@ -2543,7 +2501,7 @@ static int dl_surf_to_renderdata(ObjectRen *obr, DispList *dl, Material **matar,
copy_v3_v3(v1->co, data); data += 3;
if (orco) {
v1->orco= orco; orco+= 3; orcoret++;
- }
+ }
mul_m4_v3(mat, v1->co);
for (v = 1; v < sizev; v++) {
@@ -2551,7 +2509,7 @@ static int dl_surf_to_renderdata(ObjectRen *obr, DispList *dl, Material **matar,
copy_v3_v3(ver->co, data); data += 3;
if (orco) {
ver->orco= orco; orco+= 3; orcoret++;
- }
+ }
mul_m4_v3(mat, ver->co);
}
/* if V-cyclic, add extra vertices at end of the row */
@@ -2561,8 +2519,8 @@ static int dl_surf_to_renderdata(ObjectRen *obr, DispList *dl, Material **matar,
if (orco) {
ver->orco= orco; orco+=3; orcoret++; //orcobase + 3*(u*sizev + 0);
}
- }
- }
+ }
+ }
/* Done before next loop to get corner vert */
if (dl->flag & DL_CYCL_U) nsizev++;
@@ -2615,7 +2573,7 @@ static int dl_surf_to_renderdata(ObjectRen *obr, DispList *dl, Material **matar,
p1++; p2++; p3++; p4++;
}
- }
+ }
/* fix normals for U resp. V cyclic faces */
sizeu--; sizev--; /* dec size for face array */
if (dl->flag & DL_CYCL_V) {
@@ -2936,8 +2894,7 @@ static void init_render_curve(Render *re, ObjectRen *obr, int timeoffset)
vlr->v2= RE_findOrAddVert(obr, startvert+index[1]);
vlr->v3= RE_findOrAddVert(obr, startvert+index[2]);
vlr->v4= NULL;
-
- if (area_tri_v3(vlr->v3->co, vlr->v2->co, vlr->v1->co)>FLT_EPSILON) {
+ if (area_tri_v3(vlr->v3->co, vlr->v2->co, vlr->v1->co)>FLT_EPSILON10) {
normal_tri_v3(tmp, vlr->v3->co, vlr->v2->co, vlr->v1->co);
add_v3_v3(n, tmp);
}
@@ -3249,7 +3206,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int timeoffset)
VlakRen *vlr; //, *vlr1;
VertRen *ver;
Material *ma;
- MSticky *ms = NULL;
DerivedMesh *dm;
CustomDataMask mask;
float xn, yn, zn, imat[3][3], mat[4][4]; //nor[3],
@@ -3282,11 +3238,11 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int timeoffset)
/* normalmaps, test if tangents needed, separated from shading */
if (ma->mode_l & MA_TANGENT_V) {
need_tangent= 1;
- if (me->mtface==NULL)
+ if (me->mtpoly==NULL)
need_orco= 1;
}
if (ma->mode_l & MA_NORMAP_TANG) {
- if (me->mtface==NULL) {
+ if (me->mtpoly==NULL) {
need_orco= 1;
need_tangent= 1;
}
@@ -3297,7 +3253,7 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int timeoffset)
if (re->flag & R_NEED_TANGENT) {
/* exception for tangent space baking */
- if (me->mtface==NULL) {
+ if (me->mtpoly==NULL) {
need_orco= 1;
need_tangent= 1;
}
@@ -3334,8 +3290,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int timeoffset)
if (do_autosmooth && me->totvert==totvert && me->totface==dm->getNumTessFaces(dm))
use_original_normals= TRUE;
- ms = (totvert==me->totvert)?me->msticky:NULL;
-
ma= give_render_material(re, ob, 1);
@@ -3354,16 +3308,11 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int timeoffset)
normalize_v3(ver->n);
negate_v3(ver->n);
}
-
+
if (orco) {
ver->orco= orco;
orco+=3;
}
- if (ms) {
- float *sticky= RE_vertren_get_sticky(obr, ver, 1);
- copy_v2_v2(sticky, ms->co);
- ms++;
- }
}
if (!timeoffset) {
@@ -3631,22 +3580,22 @@ static void area_lamp_vectors(LampRen *lar)
/* corner vectors */
lar->area[0][0]= lar->co[0] - xsize*lar->mat[0][0] - ysize*lar->mat[1][0];
lar->area[0][1]= lar->co[1] - xsize*lar->mat[0][1] - ysize*lar->mat[1][1];
- lar->area[0][2]= lar->co[2] - xsize*lar->mat[0][2] - ysize*lar->mat[1][2];
+ lar->area[0][2]= lar->co[2] - xsize*lar->mat[0][2] - ysize*lar->mat[1][2];
/* corner vectors */
lar->area[1][0]= lar->co[0] - xsize*lar->mat[0][0] + ysize*lar->mat[1][0];
lar->area[1][1]= lar->co[1] - xsize*lar->mat[0][1] + ysize*lar->mat[1][1];
- lar->area[1][2]= lar->co[2] - xsize*lar->mat[0][2] + ysize*lar->mat[1][2];
+ lar->area[1][2]= lar->co[2] - xsize*lar->mat[0][2] + ysize*lar->mat[1][2];
/* corner vectors */
lar->area[2][0]= lar->co[0] + xsize*lar->mat[0][0] + ysize*lar->mat[1][0];
lar->area[2][1]= lar->co[1] + xsize*lar->mat[0][1] + ysize*lar->mat[1][1];
- lar->area[2][2]= lar->co[2] + xsize*lar->mat[0][2] + ysize*lar->mat[1][2];
+ lar->area[2][2]= lar->co[2] + xsize*lar->mat[0][2] + ysize*lar->mat[1][2];
/* corner vectors */
lar->area[3][0]= lar->co[0] + xsize*lar->mat[0][0] - ysize*lar->mat[1][0];
lar->area[3][1]= lar->co[1] + xsize*lar->mat[0][1] - ysize*lar->mat[1][1];
- lar->area[3][2]= lar->co[2] + xsize*lar->mat[0][2] - ysize*lar->mat[1][2];
+ lar->area[3][2]= lar->co[2] + xsize*lar->mat[0][2] - ysize*lar->mat[1][2];
/* only for correction button size, matrix size works on energy */
lar->areasize= lar->dist*lar->dist/(4.0f*xsize*ysize);
}
@@ -3944,6 +3893,9 @@ static void add_lightgroup(Render *re, Group *group, int exclusive)
/* note that 'exclusive' will remove it from the global list */
for (go= group->gobject.first; go; go= go->next) {
go->lampren= NULL;
+
+ if (go->ob->restrictflag & OB_RESTRICT_RENDER)
+ continue;
if (go->ob->lay & re->lay) {
if (go->ob && go->ob->type==OB_LAMP) {
@@ -4118,8 +4070,12 @@ static void set_fullsample_trace_flag(Render *re, ObjectRen *obr)
vlr->flag |= R_FULL_OSA;
}
else if (trace) {
- if (mode & MA_SHLESS);
- else if (vlr->mat->material_type == MA_TYPE_VOLUME);
+ if (mode & MA_SHLESS) {
+ /* pass */
+ }
+ else if (vlr->mat->material_type == MA_TYPE_VOLUME) {
+ /* pass */
+ }
else if ((mode & MA_RAYMIRROR) || ((mode & MA_TRANSP) && (mode & MA_RAYTRANSP))) {
/* for blurry reflect/refract, better to take more samples
* inside the raytrace than as OSA samples */
@@ -4720,10 +4676,12 @@ void RE_Database_Free(Render *re)
static int allow_render_object(Render *re, Object *ob, int nolamps, int onlyselected, Object *actob)
{
/* override not showing object when duplis are used with particles */
- if (ob->transflag & OB_DUPLIPARTS)
- ; /* let particle system(s) handle showing vs. not showing */
- else if ((ob->transflag & OB_DUPLI) && !(ob->transflag & OB_DUPLIFRAMES))
+ if (ob->transflag & OB_DUPLIPARTS) {
+ /* pass */ /* let particle system(s) handle showing vs. not showing */
+ }
+ else if ((ob->transflag & OB_DUPLI) && !(ob->transflag & OB_DUPLIFRAMES)) {
return 0;
+ }
/* don't add non-basic meta objects, ends up having renderobjects with no geometry */
if (ob->type == OB_MBALL && ob!=BKE_mball_basis_find(re->scene, ob))
@@ -4907,7 +4865,7 @@ static void database_init_objects(Render *re, unsigned int renderlay, int nolamp
/* create list of duplis generated by this object, particle
* system need to have render settings set for dupli particles */
dupli_render_particle_set(re, ob, timeoffset, 0, 1);
- lb= object_duplilist(re->scene, ob);
+ lb= object_duplilist(re->scene, ob, TRUE);
dupli_render_particle_set(re, ob, timeoffset, 0, 0);
for (dob= lb->first; dob; dob= dob->next) {
@@ -4941,7 +4899,8 @@ static void database_init_objects(Render *re, unsigned int renderlay, int nolamp
* a dupligroup that has already been created before */
if (dob->type != OB_DUPLIGROUP || (obr=find_dupligroup_dupli(re, obd, 0))) {
mult_m4_m4m4(mat, re->viewmat, dob->mat);
- obi= RE_addRenderInstance(re, NULL, obd, ob, dob->index, 0, mat, obd->lay);
+ /* ob = particle system, use that layer */
+ obi= RE_addRenderInstance(re, NULL, obd, ob, dob->index, 0, mat, ob->lay);
/* fill in instance variables for texturing */
set_dupli_tex_mat(re, obi, dob);
@@ -5242,11 +5201,11 @@ static void speedvector_project(Render *re, float zco[2], const float co[3], con
/* size of 1 pixel mapped to viewplane coords */
float psize;
- psize = BLI_RCT_SIZE_X(&re->viewplane) / (float)re->winx;
+ psize = BLI_rctf_size_x(&re->viewplane) / (float)re->winx;
/* x angle of a pixel */
pixelphix = atan(psize / re->clipsta);
- psize = BLI_RCT_SIZE_Y(&re->viewplane) / (float)re->winy;
+ psize = BLI_rctf_size_y(&re->viewplane) / (float)re->winy;
/* y angle of a pixel */
pixelphiy = atan(psize / re->clipsta);
}
@@ -5342,7 +5301,7 @@ static float *calculate_strandsurface_speedvectors(Render *re, ObjectInstanceRen
calculate_speedvector(vec, 1, winsq, winroot, mesh->co[a], ho, winspeed[a]);
}
- return (float*)winspeed;
+ return (float *)winspeed;
}
return NULL;
@@ -5600,7 +5559,7 @@ void RE_Database_FromScene_Vectors(Render *re, Main *bmain, Scene *sce, unsigned
re->i.infostr= "Calculating next frame vectors";
database_fromscene_vectors(re, sce, lay, +1);
- }
+ }
/* copy away vertex info */
copy_dbase_object_vectors(re, &newtable);
@@ -5814,76 +5773,3 @@ void RE_Database_Baking(Render *re, Main *bmain, Scene *scene, unsigned int lay,
if (re->r.mode & R_SHADOW)
make_occ_tree(re);
}
-
-/* ------------------------------------------------------------------------- */
-/* Sticky texture coords */
-/* ------------------------------------------------------------------------- */
-
-void RE_make_sticky(Scene *scene, View3D *v3d)
-{
- Object *ob;
- Base *base;
- MVert *mvert;
- Mesh *me;
- MSticky *ms;
- Render *re;
- float ho[4], mat[4][4];
- int a;
- Object *camera= NULL;
-
- if (v3d==NULL) {
- printf("Need a 3d view to make sticky\n");
- return;
- }
-
- if (v3d) camera= V3D_CAMERA_LOCAL(v3d);
- if (camera == NULL) camera= scene->camera;
-
- if (camera==NULL) {
- printf("Need camera to make sticky\n");
- return;
- }
- if (scene->obedit) {
- printf("Unable to make sticky in Edit Mode\n");
- return;
- }
-
- re= RE_NewRender("_make sticky_");
- RE_InitState(re, NULL, &scene->r, NULL, scene->r.xsch, scene->r.ysch, NULL);
-
- /* use renderdata and camera to set viewplane */
- RE_SetCamera(re, camera);
-
- /* and set view matrix */
- normalize_m4(camera->obmat);
- invert_m4_m4(mat, camera->obmat);
- RE_SetView(re, mat);
-
- for (base= FIRSTBASE; base; base= base->next) {
- if (TESTBASELIB(v3d, base)) {
- if (base->object->type==OB_MESH) {
- ob= base->object;
-
- me= ob->data;
- mvert= me->mvert;
- if (me->msticky)
- CustomData_free_layer_active(&me->vdata, CD_MSTICKY, me->totvert);
- me->msticky= CustomData_add_layer(&me->vdata, CD_MSTICKY,
- CD_CALLOC, NULL, me->totvert);
-
- BKE_object_where_is_calc(scene, ob);
- mult_m4_m4m4(mat, re->viewmat, ob->obmat);
-
- ms= me->msticky;
- for (a=0; a<me->totvert; a++, ms++, mvert++) {
- copy_v3_v3(ho, mvert->co);
- mul_m4_v3(mat, ho);
- projectverto(ho, re->winmat, ho);
- ms->co[0]= ho[0]/ho[3];
- ms->co[1]= ho[1]/ho[3];
- }
- }
- }
- }
-}
-
diff --git a/source/blender/render/intern/source/envmap.c b/source/blender/render/intern/source/envmap.c
index 03eb21dfa23..28f70211a9c 100644
--- a/source/blender/render/intern/source/envmap.c
+++ b/source/blender/render/intern/source/envmap.c
@@ -76,7 +76,7 @@ static void envmap_split_ima(EnvMap *env, ImBuf *ibuf)
BLI_lock_thread(LOCK_IMAGE);
if (env->cube[1] == NULL) {
- BKE_free_envmapdata(env);
+ BKE_free_envmapdata(env);
dx = ibuf->y;
dx /= 2;
@@ -120,7 +120,7 @@ static void envmap_split_ima(EnvMap *env, ImBuf *ibuf)
IMB_float_from_rect(env->cube[1]);
}
}
- }
+ }
BLI_unlock_thread(LOCK_IMAGE);
}
@@ -148,12 +148,14 @@ static Render *envmap_render_copy(Render *re, EnvMap *env)
envre->r.mode &= ~(R_BORDER | R_PANORAMA | R_ORTHO | R_MBLUR);
envre->r.layers.first = envre->r.layers.last = NULL;
envre->r.filtertype = 0;
- envre->r.xparts = envre->r.yparts = 2;
+ envre->r.tilex = envre->r.xsch / 2;
+ envre->r.tiley = envre->r.ysch / 2;
envre->r.size = 100;
envre->r.yasp = envre->r.xasp = 1;
RE_InitState(envre, NULL, &envre->r, NULL, cuberes, cuberes, NULL);
envre->scene = re->scene; /* unsure about this... */
+ envre->scene_color_manage = re->scene_color_manage;
envre->lay = re->lay;
/* view stuff in env render */
@@ -215,7 +217,7 @@ static void envmap_transmatrix(float mat[][4], int part)
eul[0] = eul[1] = eul[2] = 0.0;
if (part == 0) { /* neg z */
- ;
+ /* pass */
}
else if (part == 1) { /* pos z */
eul[0] = M_PI;
@@ -575,7 +577,7 @@ void make_envmaps(Render *re)
re->display_init(re->dih, re->result);
re->display_clear(re->dch, re->result);
// re->flag |= R_REDRAW_PRV;
- }
+ }
/* restore */
re->r.mode |= trace;
@@ -642,31 +644,31 @@ static int envcube_isect(EnvMap *env, const float vec[3], float answ[2])
/* ------------------------------------------------------------------------- */
-static void set_dxtdyt(float *dxts, float *dyts, float *dxt, float *dyt, int face)
+static void set_dxtdyt(float r_dxt[3], float r_dyt[3], const float dxt[3], const float dyt[3], int face)
{
if (face == 2 || face == 4) {
- dxts[0] = dxt[0];
- dyts[0] = dyt[0];
- dxts[1] = dxt[2];
- dyts[1] = dyt[2];
+ r_dxt[0] = dxt[0];
+ r_dyt[0] = dyt[0];
+ r_dxt[1] = dxt[2];
+ r_dyt[1] = dyt[2];
}
else if (face == 3 || face == 5) {
- dxts[0] = dxt[1];
- dxts[1] = dxt[2];
- dyts[0] = dyt[1];
- dyts[1] = dyt[2];
+ r_dxt[0] = dxt[1];
+ r_dxt[1] = dxt[2];
+ r_dyt[0] = dyt[1];
+ r_dyt[1] = dyt[2];
}
else {
- dxts[0] = dxt[0];
- dyts[0] = dyt[0];
- dxts[1] = dxt[1];
- dyts[1] = dyt[1];
+ r_dxt[0] = dxt[0];
+ r_dyt[0] = dyt[0];
+ r_dxt[1] = dxt[1];
+ r_dyt[1] = dyt[1];
}
}
/* ------------------------------------------------------------------------- */
-int envmaptex(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, TexResult *texres)
+int envmaptex(Tex *tex, const float texvec[3], float dxt[3], float dyt[3], int osatex, TexResult *texres)
{
extern Render R; /* only in this call */
/* texvec should be the already reflected normal */
diff --git a/source/blender/render/intern/source/external_engine.c b/source/blender/render/intern/source/external_engine.c
index 636b3205b23..4ec19fa729f 100644
--- a/source/blender/render/intern/source/external_engine.c
+++ b/source/blender/render/intern/source/external_engine.c
@@ -64,7 +64,7 @@
static RenderEngineType internal_render_type = {
NULL, NULL,
"BLENDER_RENDER", N_("Blender Render"), RE_INTERNAL,
- NULL, NULL, NULL, NULL,
+ NULL, NULL, NULL, NULL, NULL,
{NULL, NULL, NULL}
};
@@ -73,7 +73,7 @@ static RenderEngineType internal_render_type = {
static RenderEngineType internal_game_type = {
NULL, NULL,
"BLENDER_GAME", N_("Blender Game"), RE_INTERNAL | RE_GAME,
- NULL, NULL, NULL, NULL,
+ NULL, NULL, NULL, NULL, NULL,
{NULL, NULL, NULL}
};
@@ -138,7 +138,7 @@ void RE_engine_free(RenderEngine *engine)
{
#ifdef WITH_PYTHON
if (engine->py_instance) {
- BPY_DECREF(engine->py_instance);
+ BPY_DECREF_RNA_INVALIDATE(engine->py_instance);
}
#endif
@@ -290,9 +290,24 @@ void RE_engine_update_progress(RenderEngine *engine, float progress)
}
}
+void RE_engine_update_memory_stats(RenderEngine *engine, float mem_used, float mem_peak)
+{
+ Render *re = engine->re;
+
+ if (re) {
+ re->i.mem_used = mem_used;
+ re->i.mem_peak = mem_peak;
+ }
+}
+
void RE_engine_report(RenderEngine *engine, int type, const char *msg)
{
- BKE_report(engine->re->reports, type, msg);
+ Render *re = engine->re;
+
+ if (re)
+ BKE_report(engine->re->reports, type, msg);
+ else if(engine->reports)
+ BKE_report(engine->reports, type, msg);
}
/* Render */
diff --git a/source/blender/render/intern/source/gammaCorrectionTables.c b/source/blender/render/intern/source/gammaCorrectionTables.c
index 64925e16ae2..8efdf472232 100644
--- a/source/blender/render/intern/source/gammaCorrectionTables.c
+++ b/source/blender/render/intern/source/gammaCorrectionTables.c
@@ -38,7 +38,7 @@
/* result remain identical (ton) */
/* gamma is only used here for correcting adding colors or alpha */
-#define RE_DEFAULT_GAMMA 2.0
+// #define RE_DEFAULT_GAMMA 2.0 // UNUSED
/* This 400 is sort of based on the number of intensity levels needed for */
/* the typical dynamic range of a medium, in this case CRTs. (Foley) */
@@ -107,13 +107,13 @@ void makeGammaTables(float gamma)
color_step = 1.0 / RE_GAMMA_TABLE_SIZE;
inv_color_step = (float) RE_GAMMA_TABLE_SIZE;
- /* We could squeeze out the two range tables to gain some memory. */
+ /* We could squeeze out the two range tables to gain some memory. */
for (i = 0; i < RE_GAMMA_TABLE_SIZE; i++) {
- color_domain_table[i] = i * color_step;
+ color_domain_table[i] = i * color_step;
gamma_range_table[i] = pow(color_domain_table[i],
- valid_gamma);
+ valid_gamma);
inv_gamma_range_table[i] = pow(color_domain_table[i],
- valid_inv_gamma);
+ valid_inv_gamma);
}
/* The end of the table should match 1.0 carefully. In order to avoid */
diff --git a/source/blender/render/intern/source/imagetexture.c b/source/blender/render/intern/source/imagetexture.c
index 7f0484c8ee6..db1454fd82f 100644
--- a/source/blender/render/intern/source/imagetexture.c
+++ b/source/blender/render/intern/source/imagetexture.c
@@ -102,7 +102,7 @@ static void ibuf_get_color(float col[4], struct ImBuf *ibuf, int x, int y)
col[1] = ((float)rect[1])*(1.0f/255.0f);
col[2] = ((float)rect[2])*(1.0f/255.0f);
col[3] = ((float)rect[3])*(1.0f/255.0f);
- }
+ }
}
int imagewrap(Tex *tex, Image *ima, ImBuf *ibuf, const float texvec[3], TexResult *texres)
@@ -150,8 +150,13 @@ int imagewrap(Tex *tex, Image *ima, ImBuf *ibuf, const float texvec[3], TexResul
fx-= xs;
fy-= ys;
- if ( (tex->flag & TEX_CHECKER_ODD)==0) {
- if ((xs+ys) & 1);else return retval;
+ if ( (tex->flag & TEX_CHECKER_ODD) == 0) {
+ if ((xs + ys) & 1) {
+ /* pass */
+ }
+ else {
+ return retval;
+ }
}
if ( (tex->flag & TEX_CHECKER_EVEN)==0) {
if ((xs+ys) & 1) return retval;
@@ -204,7 +209,7 @@ int imagewrap(Tex *tex, Image *ima, ImBuf *ibuf, const float texvec[3], TexResul
if (tex->imaflag & TEX_USEALPHA) {
if ((tex->imaflag & TEX_CALCALPHA) == 0) {
texres->talpha = TRUE;
- }
+ }
}
/* interpolate */
@@ -396,8 +401,8 @@ static float square_rctf(rctf *rf)
{
float x, y;
- x = BLI_RCT_SIZE_X(rf);
- y = BLI_RCT_SIZE_Y(rf);
+ x = BLI_rctf_size_x(rf);
+ y = BLI_rctf_size_y(rf);
return x * y;
}
@@ -405,7 +410,7 @@ static float clipx_rctf(rctf *rf, float x1, float x2)
{
float size;
- size = BLI_RCT_SIZE_X(rf);
+ size = BLI_rctf_size_x(rf);
if (rf->xmin<x1) {
rf->xmin = x1;
@@ -417,8 +422,8 @@ static float clipx_rctf(rctf *rf, float x1, float x2)
rf->xmin = rf->xmax;
return 0.0;
}
- else if (size!=0.0f) {
- return BLI_RCT_SIZE_X(rf) / size;
+ else if (size != 0.0f) {
+ return BLI_rctf_size_x(rf) / size;
}
return 1.0;
}
@@ -427,7 +432,7 @@ static float clipy_rctf(rctf *rf, float y1, float y2)
{
float size;
- size = BLI_RCT_SIZE_Y(rf);
+ size = BLI_rctf_size_y(rf);
if (rf->ymin<y1) {
rf->ymin = y1;
@@ -441,7 +446,7 @@ static float clipy_rctf(rctf *rf, float y1, float y2)
return 0.0;
}
else if (size != 0.0f) {
- return BLI_RCT_SIZE_Y(rf) / size;
+ return BLI_rctf_size_y(rf) / size;
}
return 1.0;
@@ -474,7 +479,9 @@ static void boxsampleclip(struct ImBuf *ibuf, rctf *rf, TexResult *texres)
muly= 1.0;
- if (starty==endy);
+ if (starty==endy) {
+ /* pass */
+ }
else {
if (y==starty) muly= 1.0f-(rf->ymin - y);
if (y==endy) muly= (rf->ymax - y);
@@ -686,7 +693,7 @@ static int ibuf_get_color_clip(float col[4], ImBuf *ibuf, int x, int y, int extf
}
}
else {
- char* rect = (char*)(ibuf->rect + x + y*ibuf->x);
+ char *rect = (char *)(ibuf->rect + x + y*ibuf->x);
col[0] = rect[0]*(1.f/255.f);
col[1] = rect[1]*(1.f/255.f);
col[2] = rect[2]*(1.f/255.f);
@@ -757,39 +764,39 @@ static void area_sample(TexResult *texr, ImBuf *ibuf, float fx, float fy, afdata
/* table of (exp(ar) - exp(a)) / (1 - exp(a)) for r in range [0, 1] and a = -2
* used instead of actual gaussian, otherwise at high texture magnifications circular artifacts are visible */
#define EWA_MAXIDX 255
-static float EWA_WTS[EWA_MAXIDX + 1] =
-{ 1.f, 0.990965f, 0.982f, 0.973105f, 0.96428f, 0.955524f, 0.946836f, 0.938216f, 0.929664f,
- 0.921178f, 0.912759f, 0.904405f, 0.896117f, 0.887893f, 0.879734f, 0.871638f, 0.863605f,
- 0.855636f, 0.847728f, 0.839883f, 0.832098f, 0.824375f, 0.816712f, 0.809108f, 0.801564f,
- 0.794079f, 0.786653f, 0.779284f, 0.771974f, 0.76472f, 0.757523f, 0.750382f, 0.743297f,
- 0.736267f, 0.729292f, 0.722372f, 0.715505f, 0.708693f, 0.701933f, 0.695227f, 0.688572f,
- 0.68197f, 0.67542f, 0.66892f, 0.662471f, 0.656073f, 0.649725f, 0.643426f, 0.637176f,
- 0.630976f, 0.624824f, 0.618719f, 0.612663f, 0.606654f, 0.600691f, 0.594776f, 0.588906f,
- 0.583083f, 0.577305f, 0.571572f, 0.565883f, 0.56024f, 0.55464f, 0.549084f, 0.543572f,
- 0.538102f, 0.532676f, 0.527291f, 0.521949f, 0.516649f, 0.511389f, 0.506171f, 0.500994f,
- 0.495857f, 0.490761f, 0.485704f, 0.480687f, 0.475709f, 0.470769f, 0.465869f, 0.461006f,
- 0.456182f, 0.451395f, 0.446646f, 0.441934f, 0.437258f, 0.432619f, 0.428017f, 0.42345f,
- 0.418919f, 0.414424f, 0.409963f, 0.405538f, 0.401147f, 0.39679f, 0.392467f, 0.388178f,
- 0.383923f, 0.379701f, 0.375511f, 0.371355f, 0.367231f, 0.363139f, 0.359079f, 0.355051f,
- 0.351055f, 0.347089f, 0.343155f, 0.339251f, 0.335378f, 0.331535f, 0.327722f, 0.323939f,
- 0.320186f, 0.316461f, 0.312766f, 0.3091f, 0.305462f, 0.301853f, 0.298272f, 0.294719f,
- 0.291194f, 0.287696f, 0.284226f, 0.280782f, 0.277366f, 0.273976f, 0.270613f, 0.267276f,
- 0.263965f, 0.26068f, 0.257421f, 0.254187f, 0.250979f, 0.247795f, 0.244636f, 0.241502f,
- 0.238393f, 0.235308f, 0.232246f, 0.229209f, 0.226196f, 0.223206f, 0.220239f, 0.217296f,
- 0.214375f, 0.211478f, 0.208603f, 0.20575f, 0.20292f, 0.200112f, 0.197326f, 0.194562f,
- 0.191819f, 0.189097f, 0.186397f, 0.183718f, 0.18106f, 0.178423f, 0.175806f, 0.17321f,
- 0.170634f, 0.168078f, 0.165542f, 0.163026f, 0.16053f, 0.158053f, 0.155595f, 0.153157f,
- 0.150738f, 0.148337f, 0.145955f, 0.143592f, 0.141248f, 0.138921f, 0.136613f, 0.134323f,
- 0.132051f, 0.129797f, 0.12756f, 0.125341f, 0.123139f, 0.120954f, 0.118786f, 0.116635f,
- 0.114501f, 0.112384f, 0.110283f, 0.108199f, 0.106131f, 0.104079f, 0.102043f, 0.100023f,
- 0.0980186f, 0.09603f, 0.094057f, 0.0920994f, 0.0901571f, 0.08823f, 0.0863179f, 0.0844208f,
- 0.0825384f, 0.0806708f, 0.0788178f, 0.0769792f, 0.0751551f, 0.0733451f, 0.0715493f, 0.0697676f,
- 0.0679997f, 0.0662457f, 0.0645054f, 0.0627786f, 0.0610654f, 0.0593655f, 0.0576789f, 0.0560055f,
- 0.0543452f, 0.0526979f, 0.0510634f, 0.0494416f, 0.0478326f, 0.0462361f, 0.0446521f, 0.0430805f,
- 0.0415211f, 0.039974f, 0.0384389f, 0.0369158f, 0.0354046f, 0.0339052f, 0.0324175f, 0.0309415f,
- 0.029477f, 0.0280239f, 0.0265822f, 0.0251517f, 0.0237324f, 0.0223242f, 0.020927f, 0.0195408f,
- 0.0181653f, 0.0168006f, 0.0154466f, 0.0141031f, 0.0127701f, 0.0114476f, 0.0101354f, 0.00883339f,
- 0.00754159f, 0.00625989f, 0.00498819f, 0.00372644f, 0.00247454f, 0.00123242f, 0.f
+static float EWA_WTS[EWA_MAXIDX + 1] = {
+ 1.f, 0.990965f, 0.982f, 0.973105f, 0.96428f, 0.955524f, 0.946836f, 0.938216f, 0.929664f,
+ 0.921178f, 0.912759f, 0.904405f, 0.896117f, 0.887893f, 0.879734f, 0.871638f, 0.863605f,
+ 0.855636f, 0.847728f, 0.839883f, 0.832098f, 0.824375f, 0.816712f, 0.809108f, 0.801564f,
+ 0.794079f, 0.786653f, 0.779284f, 0.771974f, 0.76472f, 0.757523f, 0.750382f, 0.743297f,
+ 0.736267f, 0.729292f, 0.722372f, 0.715505f, 0.708693f, 0.701933f, 0.695227f, 0.688572f,
+ 0.68197f, 0.67542f, 0.66892f, 0.662471f, 0.656073f, 0.649725f, 0.643426f, 0.637176f,
+ 0.630976f, 0.624824f, 0.618719f, 0.612663f, 0.606654f, 0.600691f, 0.594776f, 0.588906f,
+ 0.583083f, 0.577305f, 0.571572f, 0.565883f, 0.56024f, 0.55464f, 0.549084f, 0.543572f,
+ 0.538102f, 0.532676f, 0.527291f, 0.521949f, 0.516649f, 0.511389f, 0.506171f, 0.500994f,
+ 0.495857f, 0.490761f, 0.485704f, 0.480687f, 0.475709f, 0.470769f, 0.465869f, 0.461006f,
+ 0.456182f, 0.451395f, 0.446646f, 0.441934f, 0.437258f, 0.432619f, 0.428017f, 0.42345f,
+ 0.418919f, 0.414424f, 0.409963f, 0.405538f, 0.401147f, 0.39679f, 0.392467f, 0.388178f,
+ 0.383923f, 0.379701f, 0.375511f, 0.371355f, 0.367231f, 0.363139f, 0.359079f, 0.355051f,
+ 0.351055f, 0.347089f, 0.343155f, 0.339251f, 0.335378f, 0.331535f, 0.327722f, 0.323939f,
+ 0.320186f, 0.316461f, 0.312766f, 0.3091f, 0.305462f, 0.301853f, 0.298272f, 0.294719f,
+ 0.291194f, 0.287696f, 0.284226f, 0.280782f, 0.277366f, 0.273976f, 0.270613f, 0.267276f,
+ 0.263965f, 0.26068f, 0.257421f, 0.254187f, 0.250979f, 0.247795f, 0.244636f, 0.241502f,
+ 0.238393f, 0.235308f, 0.232246f, 0.229209f, 0.226196f, 0.223206f, 0.220239f, 0.217296f,
+ 0.214375f, 0.211478f, 0.208603f, 0.20575f, 0.20292f, 0.200112f, 0.197326f, 0.194562f,
+ 0.191819f, 0.189097f, 0.186397f, 0.183718f, 0.18106f, 0.178423f, 0.175806f, 0.17321f,
+ 0.170634f, 0.168078f, 0.165542f, 0.163026f, 0.16053f, 0.158053f, 0.155595f, 0.153157f,
+ 0.150738f, 0.148337f, 0.145955f, 0.143592f, 0.141248f, 0.138921f, 0.136613f, 0.134323f,
+ 0.132051f, 0.129797f, 0.12756f, 0.125341f, 0.123139f, 0.120954f, 0.118786f, 0.116635f,
+ 0.114501f, 0.112384f, 0.110283f, 0.108199f, 0.106131f, 0.104079f, 0.102043f, 0.100023f,
+ 0.0980186f, 0.09603f, 0.094057f, 0.0920994f, 0.0901571f, 0.08823f, 0.0863179f, 0.0844208f,
+ 0.0825384f, 0.0806708f, 0.0788178f, 0.0769792f, 0.0751551f, 0.0733451f, 0.0715493f, 0.0697676f,
+ 0.0679997f, 0.0662457f, 0.0645054f, 0.0627786f, 0.0610654f, 0.0593655f, 0.0576789f, 0.0560055f,
+ 0.0543452f, 0.0526979f, 0.0510634f, 0.0494416f, 0.0478326f, 0.0462361f, 0.0446521f, 0.0430805f,
+ 0.0415211f, 0.039974f, 0.0384389f, 0.0369158f, 0.0354046f, 0.0339052f, 0.0324175f, 0.0309415f,
+ 0.029477f, 0.0280239f, 0.0265822f, 0.0251517f, 0.0237324f, 0.0223242f, 0.020927f, 0.0195408f,
+ 0.0181653f, 0.0168006f, 0.0154466f, 0.0141031f, 0.0127701f, 0.0114476f, 0.0101354f, 0.00883339f,
+ 0.00754159f, 0.00625989f, 0.00498819f, 0.00372644f, 0.00247454f, 0.00123242f, 0.f
};
/* test if a float value is 'nan'
@@ -982,7 +989,7 @@ static void alpha_clip_aniso(ImBuf *ibuf, float minx, float miny, float maxx, fl
alphaclip = clipx_rctf(&rf, 0.0, (float)(ibuf->x));
alphaclip *= clipy_rctf(&rf, 0.0, (float)(ibuf->y));
- alphaclip = maxf(alphaclip, 0.0f);
+ alphaclip = max_ff(alphaclip, 0.0f);
if (alphaclip!=1.0f) {
/* premul it all */
@@ -1004,7 +1011,7 @@ static void image_mipmap_test(Tex *tex, ImBuf *ibuf)
if (ibuf->userflags & IB_MIPMAP_INVALID) {
IMB_remakemipmap(ibuf, tex->imaflag & TEX_GAUSS_MIP);
ibuf->userflags &= ~IB_MIPMAP_INVALID;
- }
+ }
BLI_unlock_thread(LOCK_IMAGE);
}
if (ibuf->mipmap[0] == NULL) {
@@ -1018,7 +1025,7 @@ static void image_mipmap_test(Tex *tex, ImBuf *ibuf)
}
-static int imagewraposa_aniso(Tex *tex, Image *ima, ImBuf *ibuf, const float texvec[3], float dxt[3], float dyt[3], TexResult *texres)
+static int imagewraposa_aniso(Tex *tex, Image *ima, ImBuf *ibuf, const float texvec[3], float dxt[2], float dyt[2], TexResult *texres)
{
TexResult texr;
float fx, fy, minx, maxx, miny, maxy;
@@ -1054,7 +1061,9 @@ static int imagewraposa_aniso(Tex *tex, Image *ima, ImBuf *ibuf, const float tex
if ((ibuf == NULL) || ((ibuf->rect == NULL) && (ibuf->rect_float == NULL))) return retval;
- ima->flag |= IMA_USED_FOR_RENDER;
+ if (ima) {
+ ima->flag |= IMA_USED_FOR_RENDER;
+ }
/* mipmap test */
image_mipmap_test(tex, ibuf);
@@ -1238,8 +1247,8 @@ static int imagewraposa_aniso(Tex *tex, Image *ima, ImBuf *ibuf, const float tex
float fProbes;
a *= ff;
b *= ff;
- a = maxf(a, 1.0f);
- b = maxf(b, 1.0f);
+ a = max_ff(a, 1.0f);
+ b = max_ff(b, 1.0f);
fProbes = 2.f*(a / b) - 1.f;
AFD.iProbes = (int)floorf(fProbes + 0.5f);
AFD.iProbes = MIN2(AFD.iProbes, tex->afmax);
@@ -1255,7 +1264,7 @@ static int imagewraposa_aniso(Tex *tex, Image *ima, ImBuf *ibuf, const float tex
if (ecc > (float)tex->afmax) b = a / (float)tex->afmax;
b *= ff;
}
- maxd = maxf(b, 1e-8f);
+ maxd = max_ff(b, 1e-8f);
levf = ((float)M_LOG2E) * logf(maxd);
curmap = 0;
@@ -1340,8 +1349,8 @@ static int imagewraposa_aniso(Tex *tex, Image *ima, ImBuf *ibuf, const float tex
imp2radangle(A, B, C, F, &a, &b, &th, &ecc);
a *= ff;
b *= ff;
- a = maxf(a, 1.0f);
- b = maxf(b, 1.0f);
+ a = max_ff(a, 1.0f);
+ b = max_ff(b, 1.0f);
fProbes = 2.f*(a / b) - 1.f;
/* no limit to number of Probes here */
AFD.iProbes = (int)floorf(fProbes + 0.5f);
@@ -1410,17 +1419,17 @@ static int imagewraposa_aniso(Tex *tex, Image *ima, ImBuf *ibuf, const float tex
}
-int imagewraposa(Tex *tex, Image *ima, ImBuf *ibuf, const float texvec[3], const float DXT[3], const float DYT[3], TexResult *texres)
+int imagewraposa(Tex *tex, Image *ima, ImBuf *ibuf, const float texvec[3], const float DXT[2], const float DYT[2], TexResult *texres)
{
TexResult texr;
- float fx, fy, minx, maxx, miny, maxy, dx, dy, dxt[3], dyt[3];
+ float fx, fy, minx, maxx, miny, maxy, dx, dy, dxt[2], dyt[2];
float maxd, pixsize, val1, val2, val3;
int curmap, retval, imaprepeat, imapextend;
/* TXF: since dxt/dyt might be modified here and since they might be needed after imagewraposa() call,
* make a local copy here so that original vecs remain untouched */
- copy_v3_v3(dxt, DXT);
- copy_v3_v3(dyt, DYT);
+ copy_v2_v2(dxt, DXT);
+ copy_v2_v2(dyt, DYT);
/* anisotropic filtering */
if (tex->texfilter != TXF_BOX)
@@ -1451,8 +1460,12 @@ int imagewraposa(Tex *tex, Image *ima, ImBuf *ibuf, const float texvec[3], const
image_mipmap_test(tex, ibuf);
if (tex->imaflag & TEX_USEALPHA) {
- if (tex->imaflag & TEX_CALCALPHA);
- else texres->talpha= 1;
+ if (tex->imaflag & TEX_CALCALPHA) {
+ /* pass */
+ }
+ else {
+ texres->talpha = TRUE;
+ }
}
texr.talpha= texres->talpha;
@@ -1548,11 +1561,17 @@ int imagewraposa(Tex *tex, Image *ima, ImBuf *ibuf, const float texvec[3], const
if (boundary==0) {
if ( (tex->flag & TEX_CHECKER_ODD)==0) {
- if ((xs+ys) & 1);
- else return retval;
+ if ((xs + ys) & 1) {
+ /* pass */
+ }
+ else {
+ return retval;
+ }
}
if ( (tex->flag & TEX_CHECKER_EVEN)==0) {
- if ((xs+ys) & 1) return retval;
+ if ((xs + ys) & 1) {
+ return retval;
+ }
}
fx-= xs;
fy-= ys;
@@ -1626,7 +1645,7 @@ int imagewraposa(Tex *tex, Image *ima, ImBuf *ibuf, const float texvec[3], const
dx = minx;
dy = miny;
- maxd = maxf(dx, dy);
+ maxd = max_ff(dx, dy);
if (maxd > 0.5f) maxd = 0.5f;
pixsize = 1.0f / (float) MIN2(ibuf->x, ibuf->y);
diff --git a/source/blender/render/intern/source/initrender.c b/source/blender/render/intern/source/initrender.c
index 66f230a40f5..b2cf8db7995 100644
--- a/source/blender/render/intern/source/initrender.c
+++ b/source/blender/render/intern/source/initrender.c
@@ -555,32 +555,17 @@ void initparts(Render *re, int do_crop)
xmaxb = re->disprect.xmax;
ymaxb = re->disprect.ymax;
- xparts = re->r.xparts;
- yparts = re->r.yparts;
-
- /* mininum part size, but for exr tile saving it was checked already */
- if (!(re->r.scemode & (R_EXR_TILE_FILE | R_FULL_SAMPLE))) {
- if (re->r.mode & R_PANORAMA) {
- if (ceil(re->rectx / (float)xparts) < 8)
- xparts = 1 + re->rectx / 8;
- }
- else
- if (ceil(re->rectx / (float)xparts) < 64)
- xparts = 1 + re->rectx / 64;
-
- if (ceil(re->recty / (float)yparts) < 64)
- yparts = 1 + re->recty / 64;
- }
-
/* part size */
- partx = ceil(re->rectx / (float)xparts);
- party = ceil(re->recty / (float)yparts);
+ partx = min_ii(re->r.tilex, re->rectx);
+ party = min_ii(re->r.tiley, re->recty);
- re->xparts = xparts;
- re->yparts = yparts;
re->partx = partx;
re->party = party;
+ /* part count */
+ xparts = (re->rectx + partx - 1) / partx;
+ yparts = (re->recty + party - 1) / party;
+
/* calculate rotation factor of 1 pixel */
if (re->r.mode & R_PANORAMA)
re->panophi = panorama_pixel_rot(re);
@@ -610,8 +595,8 @@ void initparts(Render *re, int do_crop)
}
else disprect.ymax = ymaxb;
- rectx = BLI_RCT_SIZE_X(&disprect);
- recty = BLI_RCT_SIZE_Y(&disprect);
+ rectx = BLI_rcti_size_x(&disprect);
+ recty = BLI_rcti_size_y(&disprect);
/* so, now can we add this part? */
if (rectx > 0 && recty > 0) {
diff --git a/source/blender/render/intern/source/occlusion.c b/source/blender/render/intern/source/occlusion.c
index 485dd005be7..a7308821843 100644
--- a/source/blender/render/intern/source/occlusion.c
+++ b/source/blender/render/intern/source/occlusion.c
@@ -61,7 +61,6 @@
/* ------------------------- Declarations --------------------------- */
-#define INVALID_INDEX ((int)(~0))
#define INVPI ((float)M_1_PI)
#define TOTCHILD 8
#define CACHE_STEP 3
@@ -185,7 +184,7 @@ static void occ_shade(ShadeSample *ssamp, ObjectInstanceRen *obi, VlakRen *vlr,
if (shi->flippednor)
shade_input_flip_normals(shi);
- madd_v3_v3fl(shi->co, shi->vn, 0.0001f); /* ugly.. */
+ madd_v3_v3fl(shi->co, shi->facenor, -0.0001f); /* ugly.. */
/* not a pretty solution, but fixes common cases */
if (shi->obr->ob && shi->obr->ob->transflag & OB_NEG_SCALE) {
@@ -233,9 +232,9 @@ static void occ_build_shade(Render *re, OcclusionTree *tree)
/* ------------------------- Spherical Harmonics --------------------------- */
/* Use 2nd order SH => 9 coefficients, stored in this order:
-* 0 = (0,0),
-* 1 = (1,-1), 2 = (1,0), 3 = (1,1),
-* 4 = (2,-2), 5 = (2,-1), 6 = (2,0), 7 = (2,1), 8 = (2,2) */
+ * 0 = (0,0),
+ * 1 = (1,-1), 2 = (1,0), 3 = (1,1),
+ * 4 = (2,-2), 5 = (2,-1), 6 = (2,0), 7 = (2,1), 8 = (2,2) */
static void sh_copy(float *shresult, float *sh)
{
@@ -626,9 +625,12 @@ static void occ_build_sh_normalize(OccNode *node)
sh_mul(node->sh, 1.0f / node->area);
for (b = 0; b < TOTCHILD; b++) {
- if (node->childflag & (1 << b)) ;
- else if (node->child[b].node)
+ if (node->childflag & (1 << b)) {
+ /* pass */
+ }
+ else if (node->child[b].node) {
occ_build_sh_normalize(node->child[b].node);
+ }
}
}
@@ -1057,8 +1059,8 @@ static float occ_quad_form_factor(float *p, float *n, float *q0, float *q1, floa
static __m128 sse_approx_acos(__m128 x)
{
/* needs a better approximation than taylor expansion of acos, since that
- * gives big erros for near 1.0 values, sqrt(2*x)*acos(1-x) should work
- * better, see http://www.tom.womack.net/projects/sse-fast-arctrig.html */
+ * gives big erros for near 1.0 values, sqrt(2*x)*acos(1-x) should work
+ * better, see http://www.tom.womack.net/projects/sse-fast-arctrig.html */
return _mm_set_ps1(1.0f);
}
@@ -1128,7 +1130,7 @@ static void normalizef(float *n)
n[0] *= d;
n[1] *= d;
n[2] *= d;
- }
+ }
}
/* TODO: exact duplicate of ff_quad_form_factor() in math_geom.c
@@ -1545,7 +1547,7 @@ static int sample_occ_cache(OcclusionTree *tree, float *co, float *n, int x, int
for (i = 0; i < 4; i++) {
sub_v3_v3v3(d, samples[i]->co, co);
- //dist2= dot_v3v3(d, d);
+ //dist2 = dot_v3v3(d, d);
wz[i] = 1.0f; //(samples[i]->dist2/(1e-4f + dist2));
wn[i] = pow(dot_v3v3(samples[i]->n, n), 32.0f);
diff --git a/source/blender/render/intern/source/pipeline.c b/source/blender/render/intern/source/pipeline.c
index 599d91333e6..7ef3aecad08 100644
--- a/source/blender/render/intern/source/pipeline.c
+++ b/source/blender/render/intern/source/pipeline.c
@@ -203,9 +203,9 @@ RenderLayer *RE_GetRenderLayer(RenderResult *rr, const char *name)
}
}
-RenderResult *RE_MultilayerConvert(void *exrhandle, int rectx, int recty)
+RenderResult *RE_MultilayerConvert(void *exrhandle, const char *colorspace, int predivide, int rectx, int recty)
{
- return render_result_new_from_exr(exrhandle, rectx, recty);
+ return render_result_new_from_exr(exrhandle, colorspace, predivide, rectx, recty);
}
RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
@@ -437,8 +437,8 @@ void RE_InitState(Render *re, Render *source, RenderData *rd, SceneRenderLayer *
re->winy = winy;
if (disprect) {
re->disprect = *disprect;
- re->rectx = BLI_RCT_SIZE_X(disprect);
- re->recty = BLI_RCT_SIZE_Y(disprect);
+ re->rectx = BLI_rcti_size_x(disprect);
+ re->recty = BLI_rcti_size_y(disprect);
}
else {
re->disprect.xmin = re->disprect.ymin = 0;
@@ -499,13 +499,15 @@ void RE_InitState(Render *re, Render *source, RenderData *rd, SceneRenderLayer *
}
/* always call, checks for gamma, gamma tables and jitter too */
- make_sample_tables(re);
+ make_sample_tables(re);
/* if preview render, we try to keep old result */
BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
if (re->r.scemode & R_PREVIEWBUTS) {
- if (re->result && re->result->rectx == re->rectx && re->result->recty == re->recty) ;
+ if (re->result && re->result->rectx == re->rectx && re->result->recty == re->recty) {
+ /* pass */
+ }
else {
render_result_free(re->result);
re->result = NULL;
@@ -654,8 +656,12 @@ static void *do_part_thread(void *pa_v)
}
else if (render_display_draw_enabled(&R)) {
/* on break, don't merge in result for preview renders, looks nicer */
- if (R.test_break(R.tbh) && (R.r.scemode & R_PREVIEWBUTS)) ;
- else render_result_merge(R.result, pa->result);
+ if (R.test_break(R.tbh) && (R.r.scemode & R_PREVIEWBUTS)) {
+ /* pass */
+ }
+ else {
+ render_result_merge(R.result, pa->result);
+ }
}
}
@@ -670,15 +676,16 @@ static void *do_part_thread(void *pa_v)
float panorama_pixel_rot(Render *re)
{
float psize, phi, xfac;
- float borderfac = (float)BLI_RCT_SIZE_X(&re->disprect) / (float)re->winx;
+ float borderfac = (float)BLI_rcti_size_x(&re->disprect) / (float)re->winx;
+ int xparts = (re->rectx + re->partx - 1) / re->partx;
/* size of 1 pixel mapped to viewplane coords */
- psize = BLI_RCT_SIZE_X(&re->viewplane) / (float)re->winx;
+ psize = BLI_rctf_size_x(&re->viewplane) / (float)re->winx;
/* angle of a pixel */
phi = atan(psize / re->clipsta);
/* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
- xfac = borderfac * BLI_RCT_SIZE_X(&re->viewplane) / (float)re->xparts;
+ xfac = borderfac * BLI_rctf_size_x(&re->viewplane) / (float)xparts;
xfac = atan(0.5f * xfac / re->clipsta);
/* and how much the same viewplane angle is wrapped */
psize = 0.5f * phi * ((float)re->partx);
@@ -711,7 +718,7 @@ static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
float phi = panorama_pixel_rot(re);
R.panodxp = (re->winx - (best->disprect.xmin + best->disprect.xmax) ) / 2;
- R.panodxv = (BLI_RCT_SIZE_X(viewplane) * R.panodxp) / (float)(re->winx);
+ R.panodxv = (BLI_rctf_size_x(viewplane) * R.panodxp) / (float)(re->winx);
/* shift viewplane */
R.viewplane.xmin = viewplane->xmin + R.panodxv;
@@ -738,8 +745,8 @@ static RenderPart *find_next_part(Render *re, int minx)
/* find center of rendered parts, image center counts for 1 too */
for (pa = re->parts.first; pa; pa = pa->next) {
if (pa->ready) {
- centx += BLI_RCT_CENTER_X(&pa->disprect);
- centy += BLI_RCT_CENTER_Y(&pa->disprect);
+ centx += BLI_rcti_cent_x(&pa->disprect);
+ centy += BLI_rcti_cent_y(&pa->disprect);
tot++;
}
}
@@ -749,8 +756,8 @@ static RenderPart *find_next_part(Render *re, int minx)
/* closest of the non-rendering parts */
for (pa = re->parts.first; pa; pa = pa->next) {
if (pa->ready == 0 && pa->nr == 0) {
- long long int distx = centx - BLI_RCT_CENTER_X(&pa->disprect);
- long long int disty = centy - BLI_RCT_CENTER_Y(&pa->disprect);
+ long long int distx = centx - BLI_rcti_cent_x(&pa->disprect);
+ long long int disty = centy - BLI_rcti_cent_y(&pa->disprect);
distx = (long long int)sqrt(distx * distx + disty * disty);
if (distx < mindist) {
if (re->r.mode & R_PANORAMA) {
@@ -978,7 +985,7 @@ static void addblur_rect_key(RenderResult *rr, float *rectf, float *rectf1, floa
rf[1] = mfac * rf[1] + blurfac * rf1[1];
rf[2] = mfac * rf[2] + blurfac * rf1[2];
rf[3] = mfac * rf[3] + blurfac * rf1[3];
- }
+ }
}
}
rectf += stride;
@@ -1070,7 +1077,7 @@ static void do_render_blur_3d(Render *re)
/* weak... the display callback wants an active renderlayer pointer... */
re->result->renlay = render_get_active_layer(re, re->result);
- re->display_draw(re->ddh, re->result, NULL);
+ re->display_draw(re->ddh, re->result, NULL);
}
@@ -1387,7 +1394,7 @@ static void render_composit_stats(void *UNUSED(arg), char *str)
static void do_merge_fullsample(Render *re, bNodeTree *ntree)
{
float *rectf, filt[3][3];
- int sample;
+ int x, y, sample;
/* interaction callbacks */
if (ntree) {
@@ -1408,7 +1415,7 @@ static void do_merge_fullsample(Render *re, bNodeTree *ntree)
for (sample = 0; sample < re->r.osa; sample++) {
Render *re1;
RenderResult rres;
- int x, y, mask;
+ int mask;
/* enable full sample print */
R.i.curfsa = sample + 1;
@@ -1471,6 +1478,18 @@ static void do_merge_fullsample(Render *re, bNodeTree *ntree)
if (re->test_break(re->tbh))
break;
}
+
+ /* clamp alpha and RGB to 0..1 and 0..inf, can go outside due to filter */
+ for (y = 0; y < re->recty; y++) {
+ float *rf = rectf + 4 * y * re->rectx;
+
+ for (x = 0; x < re->rectx; x++, rf += 4) {
+ rf[0] = MAX2(rf[0], 0.0f);
+ rf[1] = MAX2(rf[1], 0.0f);
+ rf[2] = MAX2(rf[2], 0.0f);
+ CLAMP(rf[3], 0.0f, 1.0f);
+ }
+ }
/* clear interaction callbacks */
if (ntree) {
@@ -1501,6 +1520,7 @@ void RE_MergeFullSample(Render *re, Main *bmain, Scene *sce, bNodeTree *ntree)
re->main = bmain;
re->scene = sce;
+ re->scene_color_manage = BKE_scene_check_color_management_enabled(sce);
/* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
@@ -1548,7 +1568,7 @@ static void do_render_composite_fields_blur_3d(Render *re)
ntreeFreeCache(ntree);
do_render_fields_blur_3d(re);
- }
+ }
else {
/* ensure new result gets added, like for regular renders */
BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
@@ -1677,9 +1697,14 @@ static void do_render_seq(Render *re)
out = BKE_sequencer_give_ibuf(context, cfra, 0);
- ibuf = IMB_dupImBuf(out);
- IMB_freeImBuf(out);
- BKE_sequencer_imbuf_from_sequencer_space(re->scene, ibuf);
+ if (out) {
+ ibuf = IMB_dupImBuf(out);
+ IMB_freeImBuf(out);
+ BKE_sequencer_imbuf_from_sequencer_space(re->scene, ibuf);
+ }
+ else {
+ ibuf = NULL;
+ }
recurs_depth--;
@@ -1713,6 +1738,9 @@ static void do_render_seq(Render *re)
re->progress(re->prh, (float)(cfra - re->r.sfra) / (re->r.efra - re->r.sfra));
else
re->progress(re->prh, 1.0f);
+
+ /* would mark display buffers as invalid */
+ re->display_draw(re->ddh, re->result, NULL);
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
@@ -1845,7 +1873,7 @@ int RE_is_rendering_allowed(Scene *scene, Object *camera_override, ReportList *r
if (scene->r.border.xmax <= scene->r.border.xmin ||
scene->r.border.ymax <= scene->r.border.ymin)
{
- BKE_report(reports, RPT_ERROR, "No border area selected.");
+ BKE_report(reports, RPT_ERROR, "No border area selected");
return 0;
}
}
@@ -1856,13 +1884,13 @@ int RE_is_rendering_allowed(Scene *scene, Object *camera_override, ReportList *r
render_result_exr_file_path(scene, "", 0, str);
if (BLI_file_is_writable(str) == 0) {
- BKE_report(reports, RPT_ERROR, "Can not save render buffers, check the temp default path");
+ BKE_report(reports, RPT_ERROR, "Cannot save render buffers, check the temp default path");
return 0;
}
/* no fullsample and edge */
if ((scene->r.scemode & R_FULL_SAMPLE) && (scene->r.mode & R_EDGE)) {
- BKE_report(reports, RPT_ERROR, "Full Sample doesn't support Edge Enhance");
+ BKE_report(reports, RPT_ERROR, "Full sample does not support edge enhance");
return 0;
}
@@ -1873,18 +1901,18 @@ int RE_is_rendering_allowed(Scene *scene, Object *camera_override, ReportList *r
if (scene->r.scemode & R_DOCOMP) {
if (scene->use_nodes) {
if (!scene->nodetree) {
- BKE_report(reports, RPT_ERROR, "No Nodetree in Scene");
+ BKE_report(reports, RPT_ERROR, "No node tree in scene");
return 0;
}
if (!check_composite_output(scene)) {
- BKE_report(reports, RPT_ERROR, "No Render Output Node in Scene");
+ BKE_report(reports, RPT_ERROR, "No render output node in scene");
return 0;
}
if (scene->r.scemode & R_FULL_SAMPLE) {
if (composite_needs_render(scene, 0) == 0) {
- BKE_report(reports, RPT_ERROR, "Full Sample AA not supported without 3d rendering");
+ BKE_report(reports, RPT_ERROR, "Full sample AA not supported without 3D rendering");
return 0;
}
}
@@ -1903,7 +1931,7 @@ int RE_is_rendering_allowed(Scene *scene, Object *camera_override, ReportList *r
/* forbidden combinations */
if (scene->r.mode & R_PANORAMA) {
if (scene->r.mode & R_ORTHO) {
- BKE_report(reports, RPT_ERROR, "No Ortho render possible for Panorama");
+ BKE_report(reports, RPT_ERROR, "No ortho render possible for panorama");
return 0;
}
}
@@ -1919,7 +1947,7 @@ int RE_is_rendering_allowed(Scene *scene, Object *camera_override, ReportList *r
if (!(srl->layflag & SCE_LAY_DISABLE))
break;
if (srl == NULL) {
- BKE_report(reports, RPT_ERROR, "All RenderLayers are disabled");
+ BKE_report(reports, RPT_ERROR, "All render layers are disabled");
return 0;
}
@@ -1988,6 +2016,7 @@ static int render_initialize_from_main(Render *re, Main *bmain, Scene *scene, Sc
re->main = bmain;
re->scene = scene;
+ re->scene_color_manage = BKE_scene_check_color_management_enabled(scene);
re->camera_override = camera_override;
re->lay = lay;
@@ -2074,14 +2103,6 @@ void RE_BlenderFrame(Render *re, Main *bmain, Scene *scene, SceneRenderLayer *sr
G.is_rendering = FALSE;
}
-static void colormanage_image_for_write(Scene *scene, ImBuf *ibuf)
-{
- IMB_display_buffer_to_imbuf_rect(ibuf, &scene->view_settings, &scene->display_settings);
-
- if (ibuf)
- imb_freerectfloatImBuf(ibuf);
-}
-
static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovieHandle *mh, const char *name_override)
{
char name[FILE_MAX];
@@ -2099,24 +2120,28 @@ static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovie
/* note; the way it gets 32 bits rects is weak... */
if (ibuf->rect == NULL) {
ibuf->rect = MEM_mapallocN(sizeof(int) * rres.rectx * rres.recty, "temp 32 bits rect");
+ ibuf->mall |= IB_rect;
RE_ResultGet32(re, ibuf->rect);
do_free = TRUE;
}
- colormanage_image_for_write(scene, ibuf);
+
+ IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
+ &scene->display_settings, &scene->r.im_format);
ok = mh->append_movie(&re->r, scene->r.sfra, scene->r.cfra, (int *) ibuf->rect,
ibuf->x, ibuf->y, re->reports);
if (do_free) {
MEM_freeN(ibuf->rect);
ibuf->rect = NULL;
+ ibuf->mall &= ~IB_rect;
}
/* imbuf knows which rects are not part of ibuf */
IMB_freeImBuf(ibuf);
printf("Append frame %d", scene->r.cfra);
- }
+ }
else {
if (name_override)
BLI_strncpy(name, name_override, sizeof(name));
@@ -2131,12 +2156,9 @@ static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovie
}
else {
ImBuf *ibuf = render_result_rect_to_ibuf(&rres, &scene->r);
- int do_colormanagement;
-
- do_colormanagement = !BKE_imtype_supports_float(scene->r.im_format.imtype);
- if (do_colormanagement)
- colormanage_image_for_write(scene, ibuf);
+ IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
+ &scene->display_settings, &scene->r.im_format);
ok = BKE_imbuf_write_stamp(scene, camera, ibuf, name, &scene->r.im_format);
@@ -2155,7 +2177,8 @@ static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovie
BKE_add_image_extension(name, R_IMF_IMTYPE_JPEG90);
ibuf->planes = 24;
- colormanage_image_for_write(scene, ibuf);
+ IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
+ &scene->display_settings, &imf);
BKE_imbuf_write_stamp(scene, camera, ibuf, name, &imf);
printf("\nSaved: %s", name);
@@ -2332,6 +2355,7 @@ void RE_PreviewRender(Render *re, Main *bmain, Scene *sce)
re->main = bmain;
re->scene = sce;
+ re->scene_color_manage = BKE_scene_check_color_management_enabled(sce);
re->lay = sce->lay;
camera = RE_GetCamera(re);
@@ -2376,6 +2400,7 @@ int RE_ReadRenderResult(Scene *scene, Scene *scenode)
re = RE_NewRender(scene->id.name);
RE_InitState(re, NULL, &scene->r, NULL, winx, winy, &disprect);
re->scene = scene;
+ re->scene_color_manage = BKE_scene_check_color_management_enabled(scene);
BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
success = render_result_exr_file_read(re, 0);
@@ -2436,25 +2461,25 @@ void RE_layer_load_from_file(RenderLayer *layer, ReportList *reports, const char
IMB_freeImBuf(ibuf_clip);
}
else {
- BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to allocate clip buffer '%s'\n", filename);
+ BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to allocate clip buffer '%s'", filename);
}
}
else {
- BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: incorrect dimensions for partial copy '%s'\n", filename);
+ BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: incorrect dimensions for partial copy '%s'", filename);
}
}
IMB_freeImBuf(ibuf);
}
else {
- BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'\n", filename);
+ BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'", filename);
}
}
void RE_result_load_from_file(RenderResult *result, ReportList *reports, const char *filename)
{
if (!render_result_exr_file_read_path(result, NULL, filename)) {
- BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'\n", filename);
+ BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'", filename);
return;
}
}
@@ -2501,7 +2526,7 @@ int RE_WriteEnvmapResult(struct ReportList *reports, Scene *scene, EnvMap *env,
return 0;
}
- IMB_display_buffer_to_imbuf_rect(ibuf, &scene->view_settings, &scene->display_settings);
+ IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings, &scene->display_settings, &imf);
/* to save, we first get absolute path */
BLI_strncpy(filepath, relpath, sizeof(filepath));
@@ -2515,7 +2540,7 @@ int RE_WriteEnvmapResult(struct ReportList *reports, Scene *scene, EnvMap *env,
return TRUE;
}
else {
- BKE_report(reports, RPT_ERROR, "Error writing environment map.");
+ BKE_report(reports, RPT_ERROR, "Error writing environment map");
return FALSE;
}
}
diff --git a/source/blender/render/intern/source/pixelshading.c b/source/blender/render/intern/source/pixelshading.c
index 8e6078b18e0..3420648cb52 100644
--- a/source/blender/render/intern/source/pixelshading.c
+++ b/source/blender/render/intern/source/pixelshading.c
@@ -162,7 +162,7 @@ static void render_lighting_halo(HaloRen *har, float col_r[3])
copy_v3_v3(lvrot, lv);
mul_m3_v3(lar->imat, lvrot);
- x = maxf(fabsf(lvrot[0]/lvrot[2]), fabsf(lvrot[1]/lvrot[2]));
+ x = max_ff(fabsf(lvrot[0]/lvrot[2]), fabsf(lvrot[1]/lvrot[2]));
/* 1.0/(sqrt(1+x*x)) is equivalent to cos(atan(x)) */
inpr= 1.0/(sqrt(1.0f+x*x));
@@ -614,7 +614,7 @@ void shadeSkyPixel(float collector[4], float fx, float fy, short thread)
copy_v3_v3(collector, &R.wrld.horr);
collector[3] = 0.0f;
- }
+ }
else {
/* 2. */
diff --git a/source/blender/render/intern/source/pointdensity.c b/source/blender/render/intern/source/pointdensity.c
index 49c2bf1d053..a540cdb85d5 100644
--- a/source/blender/render/intern/source/pointdensity.c
+++ b/source/blender/render/intern/source/pointdensity.c
@@ -36,6 +36,7 @@
#include "BLI_math.h"
#include "BLI_blenlib.h"
+#include "BLI_noise.h"
#include "BLI_kdopbvh.h"
#include "BLI_utildefines.h"
@@ -170,7 +171,7 @@ static void pointdensity_cache_psys(Render *re, PointDensity *pd, Object *ob, Pa
pd->point_data[i*3 + 0] = state.vel[0];
pd->point_data[i*3 + 1] = state.vel[1];
pd->point_data[i*3 + 2] = state.vel[2];
- }
+ }
if (data_used & POINT_DATA_LIFE) {
float pa_time;
@@ -405,7 +406,7 @@ static void init_pointdensityrangedata(PointDensity *pd, PointDensityRangeData *
}
-int pointdensitytex(Tex *tex, float *texvec, TexResult *texres)
+int pointdensitytex(Tex *tex, const float texvec[3], TexResult *texres)
{
int retval = TEX_INT;
PointDensity *pd = tex->pd;
@@ -418,7 +419,7 @@ int pointdensitytex(Tex *tex, float *texvec, TexResult *texres)
texres->tin = 0.0f;
- if ((!pd) || (!pd->point_tree))
+ if ((!pd) || (!pd->point_tree))
return 0;
init_pointdensityrangedata(pd, &pdr, &density, vec, &age,
@@ -481,7 +482,7 @@ int pointdensitytex(Tex *tex, float *texvec, TexResult *texres)
case TEX_PD_COLOR_PARTAGE:
if (pd->coba) {
if (do_colorband(pd->coba, age, col)) {
- texres->talpha= 1;
+ texres->talpha = TRUE;
copy_v3_v3(&texres->tr, col);
texres->tin *= col[3];
texres->ta = texres->tin;
@@ -494,7 +495,7 @@ int pointdensitytex(Tex *tex, float *texvec, TexResult *texres)
if (pd->coba) {
if (do_colorband(pd->coba, speed, col)) {
- texres->talpha= 1;
+ texres->talpha = TRUE;
copy_v3_v3(&texres->tr, col);
texres->tin *= col[3];
texres->ta = texres->tin;
@@ -503,7 +504,7 @@ int pointdensitytex(Tex *tex, float *texvec, TexResult *texres)
break;
}
case TEX_PD_COLOR_PARTVEL:
- texres->talpha= 1;
+ texres->talpha = TRUE;
mul_v3_fl(vec, pd->speed_scale);
copy_v3_v3(&texres->tr, vec);
texres->ta = texres->tin;
diff --git a/source/blender/render/intern/source/rayshade.c b/source/blender/render/intern/source/rayshade.c
index aa35d73f3b5..127e0bc07b9 100644
--- a/source/blender/render/intern/source/rayshade.c
+++ b/source/blender/render/intern/source/rayshade.c
@@ -239,7 +239,7 @@ RayObject* makeraytree_object(Render *re, ObjectInstanceRen *obi)
if (faces == 0)
return NULL;
- //Create Ray cast accelaration structure
+ //Create Ray cast accelaration structure
raytree = RE_rayobject_create( re, re->r.raytrace_structure, faces );
if ( (re->r.raytrace_options & R_RAYTRACE_USE_LOCAL_COORDS) )
vlakprimitive = obr->rayprimitives = (VlakPrimitive*)MEM_callocN(faces*sizeof(VlakPrimitive), "ObjectRen primitives");
@@ -549,7 +549,7 @@ void shade_ray(Isect *is, ShadeInput *shi, ShadeResult *shr)
/* raytrace likes to separate the spec color */
sub_v3_v3v3(shr->diff, shr->combined, shr->spec);
- }
+ }
}
@@ -564,12 +564,12 @@ static int refraction(float refract[3], const float n[3], const float view[3], f
if (dot>0.0f) {
index = 1.0f/index;
fac= 1.0f - (1.0f - dot*dot)*index*index;
- if (fac<= 0.0f) return 0;
+ if (fac <= 0.0f) return 0;
fac= -dot*index + sqrtf(fac);
}
else {
fac= 1.0f - (1.0f - dot*dot)*index*index;
- if (fac<= 0.0f) return 0;
+ if (fac <= 0.0f) return 0;
fac= -dot*index - sqrtf(fac);
}
@@ -632,7 +632,7 @@ static float shade_by_transmission(Isect *is, ShadeInput *shi, ShadeResult *shr)
if (shi->mat->tx_limit <= 0.0f) {
d= 1.0f;
- }
+ }
else {
float p;
@@ -733,7 +733,7 @@ static void traceray(ShadeInput *origshi, ShadeResult *origshr, short depth, con
if (depth>0) {
float fr, fg, fb, f, f1;
- if ((shi.mat->mode_l & MA_TRANSP) && shr.alpha < 1.0f && (shi.mat->mode_l & (MA_ZTRANSP | MA_RAYTRANSP))) {
+ if ((shi.mat->mode_l & MA_TRANSP) && shr.alpha < 1.0f && (shi.mat->mode_l & (MA_ZTRANSP | MA_RAYTRANSP))) {
float nf, f, refract[3], tracol[4];
tracol[0]= shi.r;
@@ -938,7 +938,7 @@ void init_jitter_plane(LampRen *lar)
DP_energy(lar->jitter, fp, tot, lar->area_size, lar->area_sizey);
}
}
- }
+ }
/* create the dithered tables (could just check lamp type!) */
jitter_plane_offset(lar->jitter, lar->jitter+2*tot, tot, lar->area_size, lar->area_sizey, 0.5f, 0.0f);
jitter_plane_offset(lar->jitter, lar->jitter+4*tot, tot, lar->area_size, lar->area_sizey, 0.5f, 0.5f);
@@ -1151,7 +1151,7 @@ static void QMC_sampleHemiCosine(float vec[3], QMCSampler *qsa, int thread, int
QMC_getSample(s, qsa, thread, num);
- phi = s[0]*2.f*M_PI;
+ phi = s[0]*2.f*M_PI;
sqr = s[1]*sqrt(2-s[1]*s[1]);
vec[0] = cos(phi)*sqr;
@@ -1295,7 +1295,7 @@ static void trace_refract(float col[4], ShadeInput *shi, ShadeResult *shr)
max_samples = 1;
- while (samples < max_samples) {
+ while (samples < max_samples) {
if (refraction(v_refract, shi->vn, shi->view, shi->ang)) {
traflag |= RAY_INSIDE;
}
@@ -1515,7 +1515,7 @@ void ray_trace(ShadeInput *shi, ShadeResult *shr)
if (!(shi->combinedflag & SCE_PASS_REFRACT))
sub_v3_v3v3(diff, diff, shr->refr);
- shr->alpha = minf(1.0f, tracol[3]);
+ shr->alpha = min_ff(1.0f, tracol[3]);
}
if (do_mir) {
@@ -1822,7 +1822,7 @@ static float *sphere_sampler(int type, int resol, int thread, int xs, int ys, in
}
return sphere;
- }
+ }
else {
float *sphere;
float *vec1;
@@ -1847,7 +1847,7 @@ static float *sphere_sampler(int type, int resol, int thread, int xs, int ys, in
for (a=0; a<tot; a++, vec+=3, vec1+=3) {
vec1[0]= cost*cosfi*vec[0] - sinfi*vec[1] + sint*cosfi*vec[2];
vec1[1]= cost*sinfi*vec[0] + cosfi*vec[1] + sint*sinfi*vec[2];
- vec1[2]= -sint*vec[0] + cost*vec[2];
+ vec1[2]= -sint*vec[0] + cost*vec[2];
}
}
return sphere;
@@ -1981,7 +1981,7 @@ static void ray_ao_qmc(ShadeInput *shi, float ao[3], float env[3])
samples++;
if (qsa && qsa->type == SAMP_TYPE_HALTON) {
- /* adaptive sampling - consider samples below threshold as in shadow (or vice versa) and exit early */
+ /* adaptive sampling - consider samples below threshold as in shadow (or vice versa) and exit early */
if (adapt_thresh > 0.0f && (samples > max_samples/2) ) {
if (adaptive_sample_contrast_val(samples, prev, fac, adapt_thresh)) {
@@ -2532,7 +2532,7 @@ void ray_shadow(ShadeInput *shi, LampRen *lar, float shadfac[4])
#if 0
/* only when face points away from lamp, in direction of lamp, trace ray and find first exit point */
-static void ray_translucent(ShadeInput *shi, LampRen *lar, float *distfac, float *co)
+static void ray_translucent(ShadeInput *shi, LampRen *lar, float *distfac, float co[3])
{
Isect isec;
float lampco[3];
diff --git a/source/blender/render/intern/source/render_result.c b/source/blender/render/intern/source/render_result.c
index f11f84c9d3b..f8281586038 100644
--- a/source/blender/render/intern/source/render_result.c
+++ b/source/blender/render/intern/source/render_result.c
@@ -422,8 +422,8 @@ RenderResult *render_result_new(Render *re, rcti *partrct, int crop, int savebuf
SceneRenderLayer *srl;
int rectx, recty, nr;
- rectx = BLI_RCT_SIZE_X(partrct);
- recty = BLI_RCT_SIZE_Y(partrct);
+ rectx = BLI_rcti_size_x(partrct);
+ recty = BLI_rcti_size_y(partrct);
if (rectx <= 0 || recty <= 0)
return NULL;
@@ -569,8 +569,8 @@ RenderResult *render_result_new(Render *re, rcti *partrct, int crop, int savebuf
}
/* border render; calculate offset for use in compositor. compo is centralized coords */
- rr->xof = re->disprect.xmin + BLI_RCT_CENTER_X(&re->disprect) - (re->winx / 2);
- rr->yof = re->disprect.ymin + BLI_RCT_CENTER_Y(&re->disprect) - (re->winy / 2);
+ rr->xof = re->disprect.xmin + BLI_rcti_cent_x(&re->disprect) - (re->winx / 2);
+ rr->yof = re->disprect.ymin + BLI_rcti_cent_y(&re->disprect) - (re->winy / 2);
return rr;
}
@@ -627,12 +627,13 @@ static void ml_addpass_cb(void *UNUSED(base), void *lay, const char *str, float
}
/* from imbuf, if a handle was returned we convert this to render result */
-RenderResult *render_result_new_from_exr(void *exrhandle, int rectx, int recty)
+RenderResult *render_result_new_from_exr(void *exrhandle, const char *colorspace, int predivide, int rectx, int recty)
{
RenderResult *rr = MEM_callocN(sizeof(RenderResult), __func__);
RenderLayer *rl;
RenderPass *rpass;
-
+ const char *to_colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_SCENE_LINEAR);
+
rr->rectx = rectx;
rr->recty = recty;
@@ -645,6 +646,11 @@ RenderResult *render_result_new_from_exr(void *exrhandle, int rectx, int recty)
for (rpass = rl->passes.first; rpass; rpass = rpass->next) {
rpass->rectx = rectx;
rpass->recty = recty;
+
+ if (rpass->channels >= 3) {
+ IMB_colormanagement_transform(rpass->rect, rpass->rectx, rpass->recty, rpass->channels,
+ colorspace, to_colorspace, predivide);
+ }
}
}
@@ -780,7 +786,7 @@ int RE_WriteRenderResult(ReportList *reports, RenderResult *rr, const char *file
}
else {
/* TODO, get the error from openexr's exception */
- BKE_report(reports, RPT_ERROR, "Error Writing Render Result, see console");
+ BKE_report(reports, RPT_ERROR, "Error writing render result (see console)");
success = FALSE;
}
IMB_exr_close(exrhandle);
diff --git a/source/blender/render/intern/source/render_texture.c b/source/blender/render/intern/source/render_texture.c
index 6d22d8991b4..c507d6595e0 100644
--- a/source/blender/render/intern/source/render_texture.c
+++ b/source/blender/render/intern/source/render_texture.c
@@ -35,6 +35,7 @@
#include "BLI_blenlib.h"
#include "BLI_math.h"
+#include "BLI_noise.h"
#include "BLI_rand.h"
#include "BLI_utildefines.h"
@@ -98,7 +99,7 @@ static void init_render_texture(Render *re, Tex *tex)
{
/* imap test */
if (tex->ima && ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
- BKE_image_user_frame_calc(&tex->iuser, re->r.cfra, re?re->flag & R_SEC_FIELD:0);
+ BKE_image_user_frame_calc(&tex->iuser, re ? re->r.cfra : 0, re ? re->flag & R_SEC_FIELD:0);
}
else if (tex->type==TEX_ENVMAP) {
@@ -184,7 +185,7 @@ static void tex_normal_derivate(Tex *tex, TexResult *texres)
-static int blend(Tex *tex, float *texvec, TexResult *texres)
+static int blend(Tex *tex, const float texvec[3], TexResult *texres)
{
float x, y, t;
@@ -236,7 +237,7 @@ static int blend(Tex *tex, float *texvec, TexResult *texres)
/* newnoise: all noisebased types now have different noisebases to choose from */
-static int clouds(Tex *tex, float *texvec, TexResult *texres)
+static int clouds(Tex *tex, const float texvec[3], TexResult *texres)
{
int rv = TEX_INT;
@@ -302,7 +303,7 @@ static float tex_tri(float a)
/* computes basic wood intensity value at x,y,z */
static float wood_int(Tex *tex, float x, float y, float z)
{
- float wi=0;
+ float wi = 0;
short wf = tex->noisebasis2; /* wave form: TEX_SIN=0, TEX_SAW=1, TEX_TRI=2 */
short wt = tex->stype; /* wood type: TEX_BAND=0, TEX_RING=1, TEX_BANDNOISE=2, TEX_RINGNOISE=3 */
@@ -331,7 +332,7 @@ static float wood_int(Tex *tex, float x, float y, float z)
return wi;
}
-static int wood(Tex *tex, float *texvec, TexResult *texres)
+static int wood(Tex *tex, const float texvec[3], TexResult *texres)
{
int rv=TEX_INT;
@@ -373,7 +374,7 @@ static float marble_int(Tex *tex, float x, float y, float z)
mi = waveform[wf](mi);
if (mt==TEX_SHARP) {
mi = sqrt(mi);
- }
+ }
else if (mt==TEX_SHARPER) {
mi = sqrt(sqrt(mi));
}
@@ -382,7 +383,7 @@ static float marble_int(Tex *tex, float x, float y, float z)
return mi;
}
-static int marble(Tex *tex, float *texvec, TexResult *texres)
+static int marble(Tex *tex, const float texvec[3], TexResult *texres)
{
int rv=TEX_INT;
@@ -406,7 +407,7 @@ static int marble(Tex *tex, float *texvec, TexResult *texres)
/* ------------------------------------------------------------------------- */
-static int magic(Tex *tex, float *texvec, TexResult *texres)
+static int magic(Tex *tex, const float texvec[3], TexResult *texres)
{
float x, y, z, turb=1.0;
int n;
@@ -482,7 +483,7 @@ static int magic(Tex *tex, float *texvec, TexResult *texres)
/* ------------------------------------------------------------------------- */
/* newnoise: stucci also modified to use different noisebasis */
-static int stucci(Tex *tex, float *texvec, TexResult *texres)
+static int stucci(Tex *tex, const float texvec[3], TexResult *texres)
{
float nor[3], b2, ofs;
int retval= TEX_INT;
@@ -493,7 +494,7 @@ static int stucci(Tex *tex, float *texvec, TexResult *texres)
if (tex->stype) ofs*=(b2*b2);
nor[0] = BLI_gNoise(tex->noisesize, texvec[0]+ofs, texvec[1], texvec[2], (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
- nor[1] = BLI_gNoise(tex->noisesize, texvec[0], texvec[1]+ofs, texvec[2], (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
+ nor[1] = BLI_gNoise(tex->noisesize, texvec[0], texvec[1]+ofs, texvec[2], (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
nor[2] = BLI_gNoise(tex->noisesize, texvec[0], texvec[1], texvec[2]+ofs, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
texres->tin= nor[2];
@@ -524,7 +525,7 @@ static int stucci(Tex *tex, float *texvec, TexResult *texres)
/* ------------------------------------------------------------------------- */
/* newnoise: musgrave terrain noise types */
-static float mg_mFractalOrfBmTex(Tex *tex, float *texvec, TexResult *texres)
+static float mg_mFractalOrfBmTex(Tex *tex, const float texvec[3], TexResult *texres)
{
int rv = TEX_INT;
float (*mgravefunc)(float, float, float, float, float, float, int);
@@ -554,7 +555,7 @@ static float mg_mFractalOrfBmTex(Tex *tex, float *texvec, TexResult *texres)
}
-static float mg_ridgedOrHybridMFTex(Tex *tex, float *texvec, TexResult *texres)
+static float mg_ridgedOrHybridMFTex(Tex *tex, const float texvec[3], TexResult *texres)
{
int rv = TEX_INT;
float (*mgravefunc)(float, float, float, float, float, float, float, float, int);
@@ -585,7 +586,7 @@ static float mg_ridgedOrHybridMFTex(Tex *tex, float *texvec, TexResult *texres)
}
-static float mg_HTerrainTex(Tex *tex, float *texvec, TexResult *texres)
+static float mg_HTerrainTex(Tex *tex, const float texvec[3], TexResult *texres)
{
int rv = TEX_INT;
@@ -610,7 +611,7 @@ static float mg_HTerrainTex(Tex *tex, float *texvec, TexResult *texres)
}
-static float mg_distNoiseTex(Tex *tex, float *texvec, TexResult *texres)
+static float mg_distNoiseTex(Tex *tex, const float texvec[3], TexResult *texres)
{
int rv = TEX_INT;
@@ -639,7 +640,7 @@ static float mg_distNoiseTex(Tex *tex, float *texvec, TexResult *texres)
/* ------------------------------------------------------------------------- */
/* newnoise: Voronoi texture type, probably the slowest, especially with minkovsky, bumpmapping, could be done another way */
-static float voronoiTex(Tex *tex, float *texvec, TexResult *texres)
+static float voronoiTex(Tex *tex, const float texvec[3], TexResult *texres)
{
int rv = TEX_INT;
float da[4], pa[12]; /* distance and point coordinate arrays of 4 nearest neighbors */
@@ -768,7 +769,7 @@ static int cubemap_glob(const float n[3], float x, float y, float z, float *adr1
else {
*adr1 = (y + 1.0f) / 2.0f;
*adr2 = (z + 1.0f) / 2.0f;
- ret= 2;
+ ret= 2;
}
return ret;
}
@@ -823,8 +824,8 @@ static int cubemap(MTex *mtex, VlakRen *vlr, const float n[3], float x, float y,
*adr1 = (y + 1.0f) / 2.0f;
*adr2 = (z + 1.0f) / 2.0f;
ret= 2;
- }
- }
+ }
+ }
else {
return cubemap_glob(n, x, y, z, adr1, adr2);
}
@@ -861,14 +862,14 @@ static int cubemap_ob(Object *ob, const float n[3], float x, float y, float z, f
else {
*adr1 = (y + 1.0f) / 2.0f;
*adr2 = (z + 1.0f) / 2.0f;
- ret= 2;
+ ret= 2;
}
return ret;
}
/* ------------------------------------------------------------------------- */
-static void do_2d_mapping(MTex *mtex, float *t, VlakRen *vlr, const float n[3], float *dxt, float *dyt)
+static void do_2d_mapping(MTex *mtex, float texvec[3], VlakRen *vlr, const float n[3], float dxt[3], float dyt[3])
{
Tex *tex;
Object *ob= NULL;
@@ -884,15 +885,15 @@ static void do_2d_mapping(MTex *mtex, float *t, VlakRen *vlr, const float n[3],
if (R.osa==0) {
if (wrap==MTEX_FLAT) {
- fx = (t[0] + 1.0f) / 2.0f;
- fy = (t[1] + 1.0f) / 2.0f;
+ fx = (texvec[0] + 1.0f) / 2.0f;
+ fy = (texvec[1] + 1.0f) / 2.0f;
}
- else if (wrap==MTEX_TUBE) map_to_tube( &fx, &fy, t[0], t[1], t[2]);
- else if (wrap==MTEX_SPHERE) map_to_sphere(&fx, &fy, t[0], t[1], t[2]);
+ else if (wrap == MTEX_TUBE) map_to_tube( &fx, &fy, texvec[0], texvec[1], texvec[2]);
+ else if (wrap == MTEX_SPHERE) map_to_sphere(&fx, &fy, texvec[0], texvec[1], texvec[2]);
else {
- if (texco==TEXCO_OBJECT) cubemap_ob(ob, n, t[0], t[1], t[2], &fx, &fy);
- else if (texco==TEXCO_GLOB) cubemap_glob(n, t[0], t[1], t[2], &fx, &fy);
- else cubemap(mtex, vlr, n, t[0], t[1], t[2], &fx, &fy);
+ if (texco == TEXCO_OBJECT) cubemap_ob(ob, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
+ else if (texco == TEXCO_GLOB) cubemap_glob(n, texvec[0], texvec[1], texvec[2], &fx, &fy);
+ else cubemap(mtex, vlr, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
}
/* repeat */
@@ -932,14 +933,14 @@ static void do_2d_mapping(MTex *mtex, float *t, VlakRen *vlr, const float n[3],
fy= tex->cropymin+ fy*fac1;
}
- t[0]= fx;
- t[1]= fy;
+ texvec[0]= fx;
+ texvec[1]= fy;
}
else {
if (wrap==MTEX_FLAT) {
- fx= (t[0] + 1.0f) / 2.0f;
- fy= (t[1] + 1.0f) / 2.0f;
+ fx= (texvec[0] + 1.0f) / 2.0f;
+ fy= (texvec[1] + 1.0f) / 2.0f;
dxt[0]/= 2.0f;
dxt[1]/= 2.0f;
dxt[2]/= 2.0f;
@@ -950,29 +951,36 @@ static void do_2d_mapping(MTex *mtex, float *t, VlakRen *vlr, const float n[3],
else if (ELEM(wrap, MTEX_TUBE, MTEX_SPHERE)) {
/* exception: the seam behind (y<0.0) */
ok= 1;
- if (t[1]<=0.0f) {
- fx= t[0]+dxt[0];
- fy= t[0]+dyt[0];
- if (fx>=0.0f && fy>=0.0f && t[0]>=0.0f);
- else if (fx<=0.0f && fy<=0.0f && t[0]<=0.0f);
- else ok= 0;
+ if (texvec[1]<=0.0f) {
+ fx= texvec[0]+dxt[0];
+ fy= texvec[0]+dyt[0];
+ if (fx>=0.0f && fy>=0.0f && texvec[0]>=0.0f) {
+ /* pass */
+ }
+ else if (fx<=0.0f && fy<=0.0f && texvec[0]<=0.0f) {
+ /* pass */
+ }
+ else {
+ ok = 0;
+ }
}
+
if (ok) {
if (wrap==MTEX_TUBE) {
- map_to_tube(area, area+1, t[0], t[1], t[2]);
- map_to_tube(area + 2, area + 3, t[0] + dxt[0], t[1] + dxt[1], t[2] + dxt[2]);
- map_to_tube(area + 4, area + 5, t[0] + dyt[0], t[1] + dyt[1], t[2] + dyt[2]);
+ map_to_tube(area, area+1, texvec[0], texvec[1], texvec[2]);
+ map_to_tube(area + 2, area + 3, texvec[0] + dxt[0], texvec[1] + dxt[1], texvec[2] + dxt[2]);
+ map_to_tube(area + 4, area + 5, texvec[0] + dyt[0], texvec[1] + dyt[1], texvec[2] + dyt[2]);
}
- else {
- map_to_sphere(area, area+1, t[0], t[1], t[2]);
- map_to_sphere(area + 2, area + 3, t[0] + dxt[0], t[1] + dxt[1], t[2] + dxt[2]);
- map_to_sphere(area + 4, area + 5, t[0] + dyt[0], t[1] + dyt[1], t[2] + dyt[2]);
+ else {
+ map_to_sphere(area, area+1, texvec[0], texvec[1], texvec[2]);
+ map_to_sphere(area + 2, area + 3, texvec[0] + dxt[0], texvec[1] + dxt[1], texvec[2] + dxt[2]);
+ map_to_sphere(area + 4, area + 5, texvec[0] + dyt[0], texvec[1] + dyt[1], texvec[2] + dyt[2]);
}
areaflag= 1;
}
else {
- if (wrap==MTEX_TUBE) map_to_tube( &fx, &fy, t[0], t[1], t[2]);
- else map_to_sphere(&fx, &fy, t[0], t[1], t[2]);
+ if (wrap==MTEX_TUBE) map_to_tube( &fx, &fy, texvec[0], texvec[1], texvec[2]);
+ else map_to_sphere(&fx, &fy, texvec[0], texvec[1], texvec[2]);
dxt[0]/= 2.0f;
dxt[1]/= 2.0f;
dyt[0]/= 2.0f;
@@ -981,9 +989,9 @@ static void do_2d_mapping(MTex *mtex, float *t, VlakRen *vlr, const float n[3],
}
else {
- if (texco==TEXCO_OBJECT) proj = cubemap_ob(ob, n, t[0], t[1], t[2], &fx, &fy);
- else if (texco==TEXCO_GLOB) proj = cubemap_glob(n, t[0], t[1], t[2], &fx, &fy);
- else proj = cubemap(mtex, vlr, n, t[0], t[1], t[2], &fx, &fy);
+ if (texco==TEXCO_OBJECT) proj = cubemap_ob(ob, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
+ else if (texco==TEXCO_GLOB) proj = cubemap_glob(n, texvec[0], texvec[1], texvec[2], &fx, &fy);
+ else proj = cubemap(mtex, vlr, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
if (proj==1) {
SWAP(float, dxt[1], dxt[2]);
@@ -1083,117 +1091,117 @@ static void do_2d_mapping(MTex *mtex, float *t, VlakRen *vlr, const float n[3],
dyt[1]*= fac1;
}
- t[0]= fx;
- t[1]= fy;
+ texvec[0]= fx;
+ texvec[1]= fy;
}
}
/* ************************************** */
-static int multitex(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, TexResult *texres, short thread, short which_output)
+static int multitex(Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, TexResult *texres, const short thread, short which_output)
{
float tmpvec[3];
- int retval=0; /* return value, int:0, col:1, nor:2, everything:3 */
+ int retval = 0; /* return value, int:0, col:1, nor:2, everything:3 */
- texres->talpha= 0; /* is set when image texture returns alpha (considered premul) */
+ texres->talpha = FALSE; /* is set when image texture returns alpha (considered premul) */
if (tex->use_nodes && tex->nodetree) {
retval = ntreeTexExecTree(tex->nodetree, texres, texvec, dxt, dyt, osatex, thread,
- tex, which_output, R.r.cfra, (R.r.scemode & R_TEXNODE_PREVIEW) != 0, NULL, NULL);
+ tex, which_output, R.r.cfra, (R.r.scemode & R_TEXNODE_PREVIEW) != 0, NULL, NULL);
}
- else
- switch (tex->type) {
-
- case 0:
- texres->tin= 0.0f;
- return 0;
- case TEX_CLOUDS:
- retval= clouds(tex, texvec, texres);
- break;
- case TEX_WOOD:
- retval= wood(tex, texvec, texres);
- break;
- case TEX_MARBLE:
- retval= marble(tex, texvec, texres);
- break;
- case TEX_MAGIC:
- retval= magic(tex, texvec, texres);
- break;
- case TEX_BLEND:
- retval= blend(tex, texvec, texres);
- break;
- case TEX_STUCCI:
- retval= stucci(tex, texvec, texres);
- break;
- case TEX_NOISE:
- retval= texnoise(tex, texres);
- break;
- case TEX_IMAGE:
- if (osatex) retval= imagewraposa(tex, tex->ima, NULL, texvec, dxt, dyt, texres);
- else retval= imagewrap(tex, tex->ima, NULL, texvec, texres);
- BKE_image_tag_time(tex->ima); /* tag image as having being used */
- break;
- case TEX_ENVMAP:
- retval= envmaptex(tex, texvec, dxt, dyt, osatex, texres);
- break;
- case TEX_MUSGRAVE:
- /* newnoise: musgrave types */
-
- /* ton: added this, for Blender convention reason.
- * artificer: added the use of tmpvec to avoid scaling texvec
- */
- copy_v3_v3(tmpvec, texvec);
- mul_v3_fl(tmpvec, 1.0f/tex->noisesize);
-
- switch (tex->stype) {
- case TEX_MFRACTAL:
- case TEX_FBM:
- retval= mg_mFractalOrfBmTex(tex, tmpvec, texres);
- break;
- case TEX_RIDGEDMF:
- case TEX_HYBRIDMF:
- retval= mg_ridgedOrHybridMFTex(tex, tmpvec, texres);
- break;
- case TEX_HTERRAIN:
- retval= mg_HTerrainTex(tex, tmpvec, texres);
- break;
+ else {
+ switch (tex->type) {
+ case 0:
+ texres->tin= 0.0f;
+ return 0;
+ case TEX_CLOUDS:
+ retval = clouds(tex, texvec, texres);
+ break;
+ case TEX_WOOD:
+ retval = wood(tex, texvec, texres);
+ break;
+ case TEX_MARBLE:
+ retval = marble(tex, texvec, texres);
+ break;
+ case TEX_MAGIC:
+ retval = magic(tex, texvec, texres);
+ break;
+ case TEX_BLEND:
+ retval = blend(tex, texvec, texres);
+ break;
+ case TEX_STUCCI:
+ retval = stucci(tex, texvec, texres);
+ break;
+ case TEX_NOISE:
+ retval = texnoise(tex, texres);
+ break;
+ case TEX_IMAGE:
+ if (osatex) retval = imagewraposa(tex, tex->ima, NULL, texvec, dxt, dyt, texres);
+ else retval = imagewrap(tex, tex->ima, NULL, texvec, texres);
+ BKE_image_tag_time(tex->ima); /* tag image as having being used */
+ break;
+ case TEX_ENVMAP:
+ retval = envmaptex(tex, texvec, dxt, dyt, osatex, texres);
+ break;
+ case TEX_MUSGRAVE:
+ /* newnoise: musgrave types */
+
+ /* ton: added this, for Blender convention reason.
+ * artificer: added the use of tmpvec to avoid scaling texvec
+ */
+ copy_v3_v3(tmpvec, texvec);
+ mul_v3_fl(tmpvec, 1.0f / tex->noisesize);
+
+ switch (tex->stype) {
+ case TEX_MFRACTAL:
+ case TEX_FBM:
+ retval = mg_mFractalOrfBmTex(tex, tmpvec, texres);
+ break;
+ case TEX_RIDGEDMF:
+ case TEX_HYBRIDMF:
+ retval = mg_ridgedOrHybridMFTex(tex, tmpvec, texres);
+ break;
+ case TEX_HTERRAIN:
+ retval = mg_HTerrainTex(tex, tmpvec, texres);
+ break;
+ }
+ break;
+ /* newnoise: voronoi type */
+ case TEX_VORONOI:
+ /* ton: added this, for Blender convention reason.
+ * artificer: added the use of tmpvec to avoid scaling texvec
+ */
+ copy_v3_v3(tmpvec, texvec);
+ mul_v3_fl(tmpvec, 1.0f / tex->noisesize);
+
+ retval = voronoiTex(tex, tmpvec, texres);
+ break;
+ case TEX_DISTNOISE:
+ /* ton: added this, for Blender convention reason.
+ * artificer: added the use of tmpvec to avoid scaling texvec
+ */
+ copy_v3_v3(tmpvec, texvec);
+ mul_v3_fl(tmpvec, 1.0f / tex->noisesize);
+
+ retval = mg_distNoiseTex(tex, tmpvec, texres);
+ break;
+ case TEX_POINTDENSITY:
+ retval = pointdensitytex(tex, texvec, texres);
+ break;
+ case TEX_VOXELDATA:
+ retval = voxeldatatex(tex, texvec, texres);
+ break;
+ case TEX_OCEAN:
+ retval = ocean_texture(tex, texvec, texres);
+ break;
}
- break;
- /* newnoise: voronoi type */
- case TEX_VORONOI:
- /* ton: added this, for Blender convention reason.
- * artificer: added the use of tmpvec to avoid scaling texvec
- */
- copy_v3_v3(tmpvec, texvec);
- mul_v3_fl(tmpvec, 1.0f/tex->noisesize);
-
- retval= voronoiTex(tex, tmpvec, texres);
- break;
- case TEX_DISTNOISE:
- /* ton: added this, for Blender convention reason.
- * artificer: added the use of tmpvec to avoid scaling texvec
- */
- copy_v3_v3(tmpvec, texvec);
- mul_v3_fl(tmpvec, 1.0f/tex->noisesize);
-
- retval= mg_distNoiseTex(tex, tmpvec, texres);
- break;
- case TEX_POINTDENSITY:
- retval= pointdensitytex(tex, texvec, texres);
- break;
- case TEX_VOXELDATA:
- retval= voxeldatatex(tex, texvec, texres);
- break;
- case TEX_OCEAN:
- retval= ocean_texture(tex, texvec, texres);
- break;
}
if (tex->flag & TEX_COLORBAND) {
float col[4];
if (do_colorband(tex->coba, texres->tin, col)) {
- texres->talpha= 1;
+ texres->talpha = TRUE;
texres->tr= col[0];
texres->tg= col[1];
texres->tb= col[2];
@@ -1205,7 +1213,8 @@ static int multitex(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex,
}
/* this is called from the shader and texture nodes */
-int multitex_nodes(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, TexResult *texres, short thread, short which_output, ShadeInput *shi, MTex *mtex)
+int multitex_nodes(Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, TexResult *texres,
+ const short thread, short which_output, ShadeInput *shi, MTex *mtex)
{
if (tex==NULL) {
memset(texres, 0, sizeof(TexResult));
@@ -1221,13 +1230,13 @@ int multitex_nodes(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex,
if (mtex) {
/* we have mtex, use it for 2d mapping images only */
do_2d_mapping(mtex, texvec, shi->vlr, shi->facenor, dxt, dyt);
- rgbnor= multitex(tex, texvec, dxt, dyt, osatex, texres, thread, which_output);
+ rgbnor = multitex(tex, texvec, dxt, dyt, osatex, texres, thread, which_output);
if (mtex->mapto & (MAP_COL+MAP_COLSPEC+MAP_COLMIR)) {
ImBuf *ibuf = BKE_image_get_ibuf(tex->ima, &tex->iuser);
/* don't linearize float buffers, assumed to be linear */
- if (ibuf && !(ibuf->rect_float))
+ if (ibuf && !(ibuf->rect_float) && R.scene_color_manage)
IMB_colormanagement_colorspace_to_scene_linear_v3(&texres->tr, ibuf->rect_colorspace);
}
}
@@ -1253,16 +1262,25 @@ int multitex_nodes(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex,
do_2d_mapping(&localmtex, texvec_l, NULL, NULL, dxt_l, dyt_l);
rgbnor= multitex(tex, texvec_l, dxt_l, dyt_l, osatex, texres, thread, which_output);
+
+ {
+ ImBuf *ibuf = BKE_image_get_ibuf(tex->ima, &tex->iuser);
+
+ /* don't linearize float buffers, assumed to be linear */
+ if (ibuf && !(ibuf->rect_float) && R.scene_color_manage)
+ IMB_colormanagement_colorspace_to_scene_linear_v3(&texres->tr, ibuf->rect_colorspace);
+ }
}
return rgbnor;
}
- else
+ else {
return multitex(tex, texvec, dxt, dyt, osatex, texres, thread, which_output);
+ }
}
/* this is called for surface shading */
-static int multitex_mtex(ShadeInput *shi, MTex *mtex, float *texvec, float *dxt, float *dyt, TexResult *texres)
+static int multitex_mtex(ShadeInput *shi, MTex *mtex, float texvec[3], float dxt[3], float dyt[3], TexResult *texres)
{
Tex *tex = mtex->tex;
@@ -1279,13 +1297,13 @@ static int multitex_mtex(ShadeInput *shi, MTex *mtex, float *texvec, float *dxt,
/* Warning, if the texres's values are not declared zero, check the return value to be sure
* the color values are set before using the r/g/b values, otherwise you may use uninitialized values - Campbell */
-int multitex_ext(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, TexResult *texres)
+int multitex_ext(Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, TexResult *texres)
{
return multitex_nodes(tex, texvec, dxt, dyt, osatex, texres, 0, 0, NULL, NULL);
}
/* extern-tex doesn't support nodes (ntreeBeginExec() can't be called when rendering is going on) */
-int multitex_ext_safe(Tex *tex, float *texvec, TexResult *texres)
+int multitex_ext_safe(Tex *tex, float texvec[3], TexResult *texres)
{
int use_nodes= tex->use_nodes, retval;
@@ -1510,7 +1528,8 @@ float texture_value_blend(float tex, float out, float fact, float facg, int blen
return in;
}
-static void texco_mapping(ShadeInput* shi, Tex* tex, MTex* mtex, float* co, float* dx, float* dy, float* texvec, float* dxt, float* dyt)
+static void texco_mapping(ShadeInput* shi, Tex* tex, MTex* mtex,
+ const float co[3], const float dx[3], const float dy[3], float texvec[3], float dxt[3], float dyt[3])
{
/* new: first swap coords, then map, then trans/scale */
if (tex->type == TEX_IMAGE) {
@@ -1542,10 +1561,10 @@ static void texco_mapping(ShadeInput* shi, Tex* tex, MTex* mtex, float* co, floa
texvec[0] = mtex->size[0]*(texvec[0] - 0.5f) + mtex->ofs[0] + 0.5f;
texvec[1] = mtex->size[1]*(texvec[1] - 0.5f) + mtex->ofs[1] + 0.5f;
if (shi->osatex) {
- dxt[0] = mtex->size[0]*dxt[0];
- dxt[1] = mtex->size[1]*dxt[1];
- dyt[0] = mtex->size[0]*dyt[0];
- dyt[1] = mtex->size[1]*dyt[1];
+ dxt[0] = mtex->size[0] * dxt[0];
+ dxt[1] = mtex->size[1] * dxt[1];
+ dyt[0] = mtex->size[0] * dyt[0];
+ dyt[1] = mtex->size[1] * dyt[1];
}
/* problem: repeat-mirror is not a 'repeat' but 'extend' in imagetexture.c */
@@ -1675,7 +1694,8 @@ static void compatible_bump_uv_derivs(CompatibleBump *compat_bump, ShadeInput *s
}
}
-static int compatible_bump_compute(CompatibleBump *compat_bump, ShadeInput *shi, MTex *mtex, Tex *tex, TexResult *texres, float Tnor, float *co, float *dx, float *dy, float *texvec, float *dxt, float *dyt)
+static int compatible_bump_compute(CompatibleBump *compat_bump, ShadeInput *shi, MTex *mtex, Tex *tex, TexResult *texres,
+ float Tnor, const float co[3], const float dx[3], const float dy[3], float texvec[3], float dxt[3], float dyt[3])
{
TexResult ttexr = {0, 0, 0, 0, 0, texres->talpha, NULL}; /* temp TexResult */
float tco[3], texv[3], cd, ud, vd, du, dv, idu, idv;
@@ -1733,7 +1753,7 @@ static int compatible_bump_compute(CompatibleBump *compat_bump, ShadeInput *shi,
if (mtex->texco == TEXCO_UV) {
/* for the uv case, use the same value for both du/dv,
* since individually scaling the normal derivatives makes them useless... */
- du = minf(du, dv);
+ du = min_ff(du, dv);
idu = (du < 1e-5f) ? bf : (bf/du);
/* +u val */
@@ -1831,7 +1851,9 @@ static void ntap_bump_init(NTapBump *ntap_bump)
memset(ntap_bump, 0, sizeof(*ntap_bump));
}
-static int ntap_bump_compute(NTapBump *ntap_bump, ShadeInput *shi, MTex *mtex, Tex *tex, TexResult *texres, float Tnor, float *co, float *dx, float *dy, float *texvec, float *dxt, float *dyt)
+static int ntap_bump_compute(NTapBump *ntap_bump, ShadeInput *shi, MTex *mtex, Tex *tex, TexResult *texres,
+ float Tnor, const float co[3], const float dx[3], const float dy[3],
+ float texvec[3], float dxt[3], float dyt[3])
{
TexResult ttexr = {0, 0, 0, 0, 0, texres->talpha, NULL}; /* temp TexResult */
@@ -2153,9 +2175,6 @@ void do_material_tex(ShadeInput *shi, Render *re)
co= shi->lo; dx= shi->dxlo; dy= shi->dylo;
}
}
- else if (mtex->texco==TEXCO_STICKY) {
- co= shi->sticky; dx= shi->dxsticky; dy= shi->dysticky;
- }
else if (mtex->texco==TEXCO_OBJECT) {
Object *ob= mtex->object;
if (ob) {
@@ -2260,11 +2279,11 @@ void do_material_tex(ShadeInput *shi, Render *re)
if (texres.nor && !((tex->type==TEX_IMAGE) && (tex->imaflag & TEX_NORMALMAP))) {
if (use_compat_bump) {
rgbnor = compatible_bump_compute(&compat_bump, shi, mtex, tex,
- &texres, Tnor*stencilTin, co, dx, dy, texvec, dxt, dyt);
+ &texres, Tnor*stencilTin, co, dx, dy, texvec, dxt, dyt);
}
else if (use_ntap_bump) {
rgbnor = ntap_bump_compute(&ntap_bump, shi, mtex, tex,
- &texres, Tnor*stencilTin, co, dx, dy, texvec, dxt, dyt);
+ &texres, Tnor*stencilTin, co, dx, dy, texvec, dxt, dyt);
}
else {
texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
@@ -2380,7 +2399,7 @@ void do_material_tex(ShadeInput *shi, Render *re)
ImBuf *ibuf = BKE_image_get_ibuf(ima, &tex->iuser);
/* don't linearize float buffers, assumed to be linear */
- if (ibuf && !(ibuf->rect_float))
+ if (ibuf && !(ibuf->rect_float) && R.scene_color_manage)
IMB_colormanagement_colorspace_to_scene_linear_v3(tcol, ibuf->rect_colorspace);
}
@@ -2448,7 +2467,9 @@ void do_material_tex(ShadeInput *shi, Render *re)
copy_v3_v3(nor, texres.nor);
- if (mtex->normapspace == MTEX_NSPACE_CAMERA);
+ if (mtex->normapspace == MTEX_NSPACE_CAMERA) {
+ /* pass */
+ }
else if (mtex->normapspace == MTEX_NSPACE_WORLD) {
mul_mat3_m4_v3(re->viewmat, nor);
}
@@ -2651,9 +2672,16 @@ void do_volume_tex(ShadeInput *shi, const float *xyz, int mapto_flag, float col_
copy_v3_v3(co, xyz);
if (mtex->texflag & MTEX_OB_DUPLI_ORIG) {
if (shi->obi && shi->obi->duplitexmat)
- mul_m4_v3(shi->obi->duplitexmat, co);
- }
+ mul_m4_v3(shi->obi->duplitexmat, co);
+ }
mul_m4_v3(ob->imat_ren, co);
+
+ if (mtex->texflag & MTEX_MAPTO_BOUNDS && ob->bb) {
+ /* use bb vec[0] as min and bb vec[6] as max */
+ co[0] = (co[0] - ob->bb->vec[0][0]) / (ob->bb->vec[6][0]-ob->bb->vec[0][0]) * 2.0f - 1.0f;
+ co[1] = (co[1] - ob->bb->vec[0][1]) / (ob->bb->vec[6][1]-ob->bb->vec[0][1]) * 2.0f - 1.0f;
+ co[2] = (co[2] - ob->bb->vec[0][2]) / (ob->bb->vec[6][2]-ob->bb->vec[0][2]) * 2.0f - 1.0f;
+ }
}
}
/* not really orco, but 'local' */
@@ -2666,6 +2694,13 @@ void do_volume_tex(ShadeInput *shi, const float *xyz, int mapto_flag, float col_
Object *ob= shi->obi->ob;
copy_v3_v3(co, xyz);
mul_m4_v3(ob->imat_ren, co);
+
+ if (mtex->texflag & MTEX_MAPTO_BOUNDS && ob->bb) {
+ /* use bb vec[0] as min and bb vec[6] as max */
+ co[0] = (co[0] - ob->bb->vec[0][0]) / (ob->bb->vec[6][0]-ob->bb->vec[0][0]) * 2.0f - 1.0f;
+ co[1] = (co[1] - ob->bb->vec[0][1]) / (ob->bb->vec[6][1]-ob->bb->vec[0][1]) * 2.0f - 1.0f;
+ co[2] = (co[2] - ob->bb->vec[0][2]) / (ob->bb->vec[6][2]-ob->bb->vec[0][2]) * 2.0f - 1.0f;
+ }
}
}
else if (mtex->texco==TEXCO_GLOB) {
@@ -2732,6 +2767,12 @@ void do_volume_tex(ShadeInput *shi, const float *xyz, int mapto_flag, float col_
if ((rgbnor & TEX_RGB) == 0) {
copy_v3_v3(tcol, &mtex->r);
}
+ else if (mtex->mapto & MAP_DENSITY) {
+ copy_v3_v3(tcol, &texres.tr);
+ if (texres.talpha) {
+ texres.tin = stencilTin;
+ }
+ }
else {
copy_v3_v3(tcol, &texres.tr);
if (texres.talpha) {
@@ -2760,11 +2801,9 @@ void do_volume_tex(ShadeInput *shi, const float *xyz, int mapto_flag, float col_
/* stencil maps on the texture control slider, not texture intensity value */
/* convert RGB to intensity if intensity info isn't provided */
- if (!(rgbnor & TEX_INT)) {
- if (rgbnor & TEX_RGB) {
- if (texres.talpha) texres.tin = texres.ta;
- else texres.tin = rgb_to_grayscale(&texres.tr);
- }
+ if (rgbnor & TEX_RGB) {
+ if (texres.talpha) texres.tin = texres.ta;
+ else texres.tin = rgb_to_grayscale(&texres.tr);
}
if ((mapto_flag & MAP_EMISSION) && (mtex->mapto & MAP_EMISSION)) {
@@ -2892,7 +2931,7 @@ void do_halo_tex(HaloRen *har, float xn, float yn, float col_r[4])
ImBuf *ibuf = BKE_image_get_ibuf(ima, &mtex->tex->iuser);
/* don't linearize float buffers, assumed to be linear */
- if (ibuf && !(ibuf->rect_float))
+ if (ibuf && !(ibuf->rect_float) && R.scene_color_manage)
IMB_colormanagement_colorspace_to_scene_linear_v3(&texres.tr, ibuf->rect_colorspace);
}
@@ -2927,10 +2966,14 @@ void do_halo_tex(HaloRen *har, float xn, float yn, float col_r[4])
}
if (mtex->mapto & MAP_ALPHA) {
if (rgb) {
- if (texres.talpha) texres.tin= texres.ta;
- else texres.tin = rgb_to_bw(&texres.tr);
+ if (texres.talpha) {
+ texres.tin = texres.ta;
+ }
+ else {
+ texres.tin = rgb_to_bw(&texres.tr);
+ }
}
-
+
col_r[3]*= texres.tin;
}
}
@@ -3043,7 +3086,7 @@ void do_sky_tex(const float rco[3], float lo[3], const float dxyview[2], float h
break;
}
- /* placement */
+ /* placement */
if (mtex->projx) texvec[0]= mtex->size[0]*(co[mtex->projx-1]+mtex->ofs[0]);
else texvec[0]= mtex->size[0]*(mtex->ofs[0]);
@@ -3107,7 +3150,7 @@ void do_sky_tex(const float rco[3], float lo[3], const float dxyview[2], float h
ImBuf *ibuf = BKE_image_get_ibuf(ima, &tex->iuser);
/* don't linearize float buffers, assumed to be linear */
- if (ibuf && !(ibuf->rect_float))
+ if (ibuf && !(ibuf->rect_float) && R.scene_color_manage)
IMB_colormanagement_colorspace_to_scene_linear_v3(tcol, ibuf->rect_colorspace);
}
@@ -3206,7 +3249,7 @@ void do_lamp_tex(LampRen *la, const float lavec[3], ShadeInput *shi, float col_r
}
co= tempvec;
- dx= dxt; dy= dyt;
+ dx= dxt; dy= dyt;
if (shi->osatex) {
copy_v3_v3(dxt, shi->dxlv);
copy_v3_v3(dyt, shi->dylv);
@@ -3321,7 +3364,7 @@ void do_lamp_tex(LampRen *la, const float lavec[3], ShadeInput *shi, float col_r
ImBuf *ibuf = BKE_image_get_ibuf(ima, &tex->iuser);
/* don't linearize float buffers, assumed to be linear */
- if (ibuf && !(ibuf->rect_float))
+ if (ibuf && !(ibuf->rect_float) && R.scene_color_manage)
IMB_colormanagement_colorspace_to_scene_linear_v3(&texres.tr, ibuf->rect_colorspace);
}
diff --git a/source/blender/render/intern/source/rendercore.c b/source/blender/render/intern/source/rendercore.c
index 97a05e6a4c9..9fe2620747c 100644
--- a/source/blender/render/intern/source/rendercore.c
+++ b/source/blender/render/intern/source/rendercore.c
@@ -59,6 +59,7 @@
#include "BKE_main.h"
#include "BKE_node.h"
#include "BKE_texture.h"
+#include "BKE_scene.h"
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -93,7 +94,7 @@ extern struct Render R;
/* x and y are current pixels in rect to be rendered */
/* do not normalize! */
-void calc_view_vector(float *view, float x, float y)
+void calc_view_vector(float view[3], float x, float y)
{
view[2]= -ABS(R.clipsta);
@@ -109,10 +110,10 @@ void calc_view_vector(float *view, float x, float y)
/* move x and y to real viewplane coords */
x = (x / (float)R.winx);
- view[0] = R.viewplane.xmin + x * BLI_RCT_SIZE_X(&R.viewplane);
+ view[0] = R.viewplane.xmin + x * BLI_rctf_size_x(&R.viewplane);
y = (y / (float)R.winy);
- view[1] = R.viewplane.ymin + y * BLI_RCT_SIZE_Y(&R.viewplane);
+ view[1] = R.viewplane.ymin + y * BLI_rctf_size_y(&R.viewplane);
// if (R.flag & R_SEC_FIELD) {
// if (R.r.mode & R_ODDFIELD) view[1]= (y+R.ystart)*R.ycor;
@@ -184,7 +185,8 @@ static void halo_pixelstruct(HaloRen *har, RenderLayer **rlpp, int totsample, in
fullsample= (totsample > 1);
amount= 0;
- accol[0]=accol[1]=accol[2]=accol[3]= 0.0f;
+ accol[0] = accol[1] = accol[2] = accol[3]= 0.0f;
+ col[0] = col[1] = col[2] = col[3]= 0.0f;
flarec= har->flarec;
while (ps) {
@@ -271,23 +273,33 @@ static void halo_tile(RenderPart *pa, RenderLayer *rl)
har= R.sortedhalos[a];
/* layer test, clip halo with y */
- if ((har->lay & lay)==0);
- else if (testrect.ymin > har->maxy);
- else if (testrect.ymax < har->miny);
+ if ((har->lay & lay) == 0) {
+ /* pass */
+ }
+ else if (testrect.ymin > har->maxy) {
+ /* pass */
+ }
+ else if (testrect.ymax < har->miny) {
+ /* pass */
+ }
else {
minx= floor(har->xs-har->rad);
maxx= ceil(har->xs+har->rad);
- if (testrect.xmin > maxx);
- else if (testrect.xmax < minx);
+ if (testrect.xmin > maxx) {
+ /* pass */
+ }
+ else if (testrect.xmax < minx) {
+ /* pass */
+ }
else {
- minx= MAX2(minx, testrect.xmin);
- maxx= MIN2(maxx, testrect.xmax);
+ minx = max_ii(minx, testrect.xmin);
+ maxx = min_ii(maxx, testrect.xmax);
- miny= MAX2(har->miny, testrect.ymin);
- maxy= MIN2(har->maxy, testrect.ymax);
+ miny = max_ii(har->miny, testrect.ymin);
+ maxy = min_ii(har->maxy, testrect.ymax);
for (y=miny; y<maxy; y++) {
int rectofs= (y-disprect.ymin)*pa->rectx + (minx - disprect.xmin);
@@ -660,7 +672,7 @@ int get_sample_layers(RenderPart *pa, RenderLayer *rl, RenderLayer **rlpp)
RenderResult *rr= BLI_findlink(&pa->fullresult, sample);
rlpp[sample]= BLI_findlink(&rr->layers, nr);
- }
+ }
return R.osa;
}
else {
@@ -703,7 +715,7 @@ static void sky_tile(RenderPart *pa, RenderLayer *rl)
addAlphaUnderFloat(pass, col);
}
}
- }
+ }
}
if (y&1)
@@ -761,8 +773,8 @@ static void atm_tile(RenderPart *pa, RenderLayer *rl)
if (*zrect >= 9.9e10f || rgbrect[3]==0.0f) {
continue;
}
-
- if ((lar->sunsky->effect_type & LA_SUN_EFFECT_AP)) {
+
+ if ((lar->sunsky->effect_type & LA_SUN_EFFECT_AP)) {
float tmp_rgb[3];
/* skip if worldspace lamp vector is below horizon */
@@ -917,7 +929,7 @@ static void addps(ListBase *lb, intptr_t *rd, int obi, int facenr, int z, int ma
PixStrMain *psm;
PixStr *ps, *last= NULL;
- if (*rd) {
+ if (*rd) {
ps= (PixStr *)(*rd);
while (ps) {
@@ -980,7 +992,9 @@ static void convert_to_key_alpha(RenderPart *pa, RenderLayer *rl)
float *rectf= rlpp[sample]->rectf;
for (y= pa->rectx*pa->recty; y>0; y--, rectf+=4) {
- if (rectf[3] >= 1.0f);
+ if (rectf[3] >= 1.0f) {
+ /* pass */
+ }
else if (rectf[3] > 0.0f) {
rectf[0] /= rectf[3];
rectf[1] /= rectf[3];
@@ -990,6 +1004,30 @@ static void convert_to_key_alpha(RenderPart *pa, RenderLayer *rl)
}
}
+/* clamp alpha and RGB to 0..1 and 0..inf, can go outside due to filter */
+static void clamp_alpha_rgb_range(RenderPart *pa, RenderLayer *rl)
+{
+ RenderLayer *rlpp[RE_MAX_OSA];
+ int y, sample, totsample;
+
+ totsample= get_sample_layers(pa, rl, rlpp);
+
+ /* not for full sample, there we clamp after compositing */
+ if (totsample > 1)
+ return;
+
+ for (sample= 0; sample<totsample; sample++) {
+ float *rectf= rlpp[sample]->rectf;
+
+ for (y= pa->rectx*pa->recty; y>0; y--, rectf+=4) {
+ rectf[0] = MAX2(rectf[0], 0.0f);
+ rectf[1] = MAX2(rectf[1], 0.0f);
+ rectf[2] = MAX2(rectf[2], 0.0f);
+ CLAMP(rectf[3], 0.0f, 1.0f);
+ }
+ }
+}
+
/* adds only alpha values */
static void edge_enhance_tile(RenderPart *pa, float *rectf, int *rectz)
{
@@ -1270,6 +1308,9 @@ void zbufshadeDA_tile(RenderPart *pa)
if (rl->passflag & SCE_PASS_VECTOR)
reset_sky_speed(pa, rl);
+
+ /* clamp alpha to 0..1 range, can go outside due to filter */
+ clamp_alpha_rgb_range(pa, rl);
/* de-premul alpha */
if (R.r.alphamode & R_ALPHAKEY)
@@ -1542,7 +1583,7 @@ static void shade_sample_sss(ShadeSample *ssamp, Material *mat, ObjectInstanceRe
copy_v3_v3(shi->facenor, nor);
shade_input_set_viewco(shi, x, y, sx, sy, z);
- *area = minf(len_v3(shi->dxco) * len_v3(shi->dyco), 2.0f * orthoarea);
+ *area = min_ff(len_v3(shi->dxco) * len_v3(shi->dyco), 2.0f * orthoarea);
shade_input_set_uv(shi);
shade_input_set_normals(shi);
@@ -1806,16 +1847,23 @@ static void renderhalo_post(RenderResult *rr, float *rectf, HaloRen *har) /* pos
har->miny= miny= haloys - har->rad/R.ycor;
har->maxy= maxy= haloys + har->rad/R.ycor;
- if (maxy<0);
- else if (rr->recty<miny);
+ if (maxy < 0) {
+ /* pass */
+ }
+ else if (rr->recty < miny) {
+ /* pass */
+ }
else {
- minx= floor(haloxs-har->rad);
- maxx= ceil(haloxs+har->rad);
+ minx = floor(haloxs - har->rad);
+ maxx = ceil(haloxs + har->rad);
- if (maxx<0);
- else if (rr->rectx<minx);
+ if (maxx < 0) {
+ /* pass */
+ }
+ else if (rr->rectx < minx) {
+ /* pass */
+ }
else {
-
if (minx<0) minx= 0;
if (maxx>=rr->rectx) maxx= rr->rectx-1;
if (miny<0) miny= 0;
@@ -1965,7 +2013,7 @@ void add_halo_flare(Render *re)
re->display_draw(re->ddh, rr, NULL);
}
- R.r.mode= mode;
+ R.r.mode= mode;
}
/* ************************* bake ************************ */
@@ -2072,7 +2120,9 @@ static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int UNUSED(qua
copy_v3_v3(nor, shi->vn);
- if (R.r.bake_normal_space == R_BAKE_SPACE_CAMERA);
+ if (R.r.bake_normal_space == R_BAKE_SPACE_CAMERA) {
+ /* pass */
+ }
else if (R.r.bake_normal_space == R_BAKE_SPACE_TANGENT) {
float mat[3][3], imat[3][3];
@@ -2175,7 +2225,8 @@ static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int UNUSED(qua
float rgb[3];
copy_v3_v3(rgb, shr.combined);
- IMB_colormanagement_scene_linear_to_colorspace_v3(rgb, bs->rect_colorspace);
+ if (R.scene_color_manage)
+ IMB_colormanagement_scene_linear_to_colorspace_v3(rgb, bs->rect_colorspace);
rgb_float_to_uchar(col, rgb);
}
else {
@@ -2325,10 +2376,28 @@ static void do_bake_shade(void *handle, int x, int y, float u, float v)
v2= vlr->v2->co;
v3= vlr->v3->co;
}
-
- /* renderco */
+
l= 1.0f-u-v;
+
+ /* shrink barycentric coordinates inwards slightly to avoid some issues
+ * where baking selected to active might just miss the other face at the
+ * near the edge of a face */
+ if (bs->actob) {
+ const float eps = 1.0f - 1e-4f;
+ float invsum;
+
+ u = (u - 0.5f)*eps + 0.5f;
+ v = (v - 0.5f)*eps + 0.5f;
+ l = (l - 0.5f)*eps + 0.5f;
+
+ invsum = 1.0f/(u + v + l);
+
+ u *= invsum;
+ v *= invsum;
+ l *= invsum;
+ }
+ /* renderco */
shi->co[0]= l*v3[0]+u*v1[0]+v*v2[0];
shi->co[1]= l*v3[1]+u*v1[1]+v*v2[1];
shi->co[2]= l*v3[2]+u*v1[2]+v*v2[2];
@@ -2424,7 +2493,7 @@ static int get_next_bake_face(BakeShade *bs)
return 0;
}
- BLI_lock_thread(LOCK_CUSTOM1);
+ BLI_lock_thread(LOCK_CUSTOM1);
for (; obi; obi=obi->next, v=0) {
obr= obi->obr;
@@ -2465,11 +2534,13 @@ static int get_next_bake_face(BakeShade *bs)
/* clear image */
if (R.r.bake_flag & R_BAKE_CLEAR)
IMB_rectfill(ibuf, (ibuf->planes == R_IMF_PLANES_RGBA) ? vec_alpha : vec_solid);
-
+
/* might be read by UI to set active image for display */
R.bakebuf= ima;
- }
-
+ }
+
+ ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
+
bs->obi= obi;
bs->vlr= vlr;
@@ -2505,7 +2576,7 @@ static void shade_tface(BakeShade *bs)
/* note, these calls only free/fill contents of zspan struct, not zspan itself */
zbuf_free_span(bs->zspan);
zbuf_alloc_span(bs->zspan, bs->ibuf->x, bs->ibuf->y, R.clipcrop);
- }
+ }
bs->rectx= bs->ibuf->x;
bs->recty= bs->ibuf->y;
@@ -2603,6 +2674,8 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob, short *do_up
Image *ima;
int a, vdone = FALSE, use_mask = FALSE, result = BAKE_RESULT_OK;
+ re->scene_color_manage = BKE_scene_check_color_management_enabled(re->scene);
+
/* initialize render global */
R= *re;
R.bakebuf= NULL;
@@ -2685,7 +2758,6 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob, short *do_up
RE_bake_ibuf_filter(ibuf, (char *)ibuf->userdata, re->r.bake_filter);
ibuf->userflags |= IB_BITMAPDIRTY;
- if (ibuf->rect_float) IMB_rect_from_float(ibuf);
}
}
diff --git a/source/blender/render/intern/source/renderdatabase.c b/source/blender/render/intern/source/renderdatabase.c
index db045284d5b..7a7602dcce2 100644
--- a/source/blender/render/intern/source/renderdatabase.c
+++ b/source/blender/render/intern/source/renderdatabase.c
@@ -97,13 +97,10 @@
* the index */
/* NOTE! the hardcoded table size 256 is used still in code for going quickly over vertices/faces */
-
-#define RE_STICKY_ELEMS 2
#define RE_STRESS_ELEMS 1
#define RE_RAD_ELEMS 4
#define RE_STRAND_ELEMS 1
#define RE_TANGENT_ELEMS 3
-#define RE_STRESS_ELEMS 1
#define RE_WINSPEED_ELEMS 4
#define RE_MTFACE_ELEMS 1
#define RE_MCOL_ELEMS 4
@@ -114,21 +111,6 @@
#define RE_FACE_ELEMS 1
#define RE_NMAP_TANGENT_ELEMS 16
-float *RE_vertren_get_sticky(ObjectRen *obr, VertRen *ver, int verify)
-{
- float *sticky;
- int nr= ver->index>>8;
-
- sticky= obr->vertnodes[nr].sticky;
- if (sticky==NULL) {
- if (verify)
- sticky= obr->vertnodes[nr].sticky= MEM_mallocN(256*RE_STICKY_ELEMS*sizeof(float), "sticky table");
- else
- return NULL;
- }
- return sticky + (ver->index & 255)*RE_STICKY_ELEMS;
-}
-
float *RE_vertren_get_stress(ObjectRen *obr, VertRen *ver, int verify)
{
float *stress;
@@ -218,12 +200,7 @@ VertRen *RE_vertren_copy(ObjectRen *obr, VertRen *ver)
*v1= *ver;
v1->index= index;
-
- fp1= RE_vertren_get_sticky(obr, ver, 0);
- if (fp1) {
- fp2= RE_vertren_get_sticky(obr, v1, 1);
- memcpy(fp2, fp1, RE_STICKY_ELEMS*sizeof(float));
- }
+
fp1= RE_vertren_get_stress(obr, ver, 0);
if (fp1) {
fp2= RE_vertren_get_stress(obr, v1, 1);
@@ -267,7 +244,7 @@ VertRen *RE_findOrAddVert(ObjectRen *obr, int nr)
memset(obr->vertnodes+obr->vertnodeslen, 0, TABLEINITSIZE*sizeof(VertTableNode));
obr->vertnodeslen+=TABLEINITSIZE;
- if (temp) MEM_freeN(temp);
+ if (temp) MEM_freeN(temp);
}
v= obr->vertnodes[a].vert;
@@ -510,7 +487,7 @@ VlakRen *RE_findOrAddVlak(ObjectRen *obr, int nr)
memset(obr->vlaknodes+obr->vlaknodeslen, 0, TABLEINITSIZE*sizeof(VlakTableNode));
obr->vlaknodeslen+=TABLEINITSIZE; /*Does this really need to be power of 2?*/
- if (temp) MEM_freeN(temp);
+ if (temp) MEM_freeN(temp);
}
v= obr->vlaknodes[a].vlak;
@@ -681,7 +658,7 @@ StrandRen *RE_findOrAddStrand(ObjectRen *obr, int nr)
memset(obr->strandnodes+obr->strandnodeslen, 0, TABLEINITSIZE*sizeof(StrandTableNode));
obr->strandnodeslen+=TABLEINITSIZE; /*Does this really need to be power of 2?*/
- if (temp) MEM_freeN(temp);
+ if (temp) MEM_freeN(temp);
}
v= obr->strandnodes[a].strand;
@@ -740,8 +717,6 @@ void free_renderdata_vertnodes(VertTableNode *vertnodes)
if (vertnodes[a].rad)
MEM_freeN(vertnodes[a].rad);
- if (vertnodes[a].sticky)
- MEM_freeN(vertnodes[a].sticky);
if (vertnodes[a].strand)
MEM_freeN(vertnodes[a].strand);
if (vertnodes[a].tangent)
@@ -917,7 +892,7 @@ HaloRen *RE_findOrAddHalo(ObjectRen *obr, int nr)
if (temp) memcpy(obr->bloha, temp, obr->blohalen*sizeof(void*));
memset(&(obr->bloha[obr->blohalen]), 0, TABLEINITSIZE*sizeof(void*));
obr->blohalen+=TABLEINITSIZE; /*Does this really need to be power of 2?*/
- if (temp) MEM_freeN(temp);
+ if (temp) MEM_freeN(temp);
}
h= obr->bloha[a];
@@ -1001,10 +976,13 @@ HaloRen *RE_inithalo(Render *re, ObjectRen *obr, Material *ma,
if (ma->mtex[0]) {
- if ( (ma->mode & MA_HALOTEX) ) har->tex= 1;
- else if (har->mat->septex & (1<<0)); /* only 1 level textures */
+ if (ma->mode & MA_HALOTEX) {
+ har->tex = 1;
+ }
+ else if (har->mat->septex & (1 << 0)) {
+ /* only 1 level textures */
+ }
else {
-
mtex= ma->mtex[0];
copy_v3_v3(texvec, vec);
@@ -1206,6 +1184,7 @@ static int panotestclip(Render *re, int do_pano, float *v)
/* to be used for halos en infos */
float abs4;
short c=0;
+ int xparts = (re->rectx + re->partx - 1) / re->partx;
if (do_pano == FALSE) {
return testclip(v);
@@ -1219,7 +1198,7 @@ static int panotestclip(Render *re, int do_pano, float *v)
if ( v[1]>abs4) c+=4;
else if ( v[1]< -abs4) c+=8;
- abs4*= re->xparts;
+ abs4*= xparts;
if ( v[0]>abs4) c+=2;
else if ( v[0]< -abs4) c+=1;
@@ -1378,40 +1357,42 @@ void RE_makeRenderInstances(Render *re)
re->instancetable= newlist;
}
-int clip_render_object(float boundbox[][3], float *bounds, float winmat[][4])
+int clip_render_object(float boundbox[][3], float bounds[4], float winmat[][4])
{
float mat[4][4], vec[4];
- int a, fl, flag= -1;
+ int a, fl, flag = -1;
copy_m4_m4(mat, winmat);
- for (a=0; a<8; a++) {
+ for (a=0; a < 8; a++) {
vec[0]= (a & 1)? boundbox[0][0]: boundbox[1][0];
vec[1]= (a & 2)? boundbox[0][1]: boundbox[1][1];
vec[2]= (a & 4)? boundbox[0][2]: boundbox[1][2];
vec[3]= 1.0;
mul_m4_v4(mat, vec);
- fl= 0;
+ fl = 0;
if (bounds) {
- if (vec[0] < bounds[0]*vec[3]) fl |= 1;
- else if (vec[0] > bounds[1]*vec[3]) fl |= 2;
+ if (vec[0] < bounds[0] * vec[3]) fl |= 1;
+ else if (vec[0] > bounds[1] * vec[3]) fl |= 2;
- if (vec[1] > bounds[3]*vec[3]) fl |= 4;
- else if (vec[1]< bounds[2]*vec[3]) fl |= 8;
+ if (vec[1] > bounds[3] * vec[3]) fl |= 4;
+ else if (vec[1] < bounds[2] * vec[3]) fl |= 8;
}
else {
- if (vec[0] < -vec[3]) fl |= 1;
- else if (vec[0] > vec[3]) fl |= 2;
+ if (vec[0] < -vec[3]) fl |= 1;
+ else if (vec[0] > vec[3]) fl |= 2;
- if (vec[1] > vec[3]) fl |= 4;
+ if (vec[1] > vec[3]) fl |= 4;
else if (vec[1] < -vec[3]) fl |= 8;
}
- if (vec[2] < -vec[3]) fl |= 16;
- else if (vec[2] > vec[3]) fl |= 32;
+ if (vec[2] < -vec[3]) fl |= 16;
+ else if (vec[2] > vec[3]) fl |= 32;
flag &= fl;
- if (flag==0) return 0;
+ if (flag == 0) {
+ return 0;
+ }
}
return flag;
diff --git a/source/blender/render/intern/source/shadbuf.c b/source/blender/render/intern/source/shadbuf.c
index 2d7a64bad04..c37f48bc329 100644
--- a/source/blender/render/intern/source/shadbuf.c
+++ b/source/blender/render/intern/source/shadbuf.c
@@ -72,6 +72,9 @@
# define ACOMP 3
#endif
+#define RCT_SIZE_X(rct) ((rct)->xmax - (rct)->xmin)
+#define RCT_SIZE_Y(rct) ((rct)->ymax - (rct)->ymin)
+
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
/* only to be used here in this file, it's for speed */
@@ -86,7 +89,7 @@ extern struct Render R;
static void copy_to_ztile(int *rectz, int size, int x1, int y1, int tile, char *r1)
{
- int len4, *rz;
+ int len4, *rz;
int x2, y2;
x2= x1+tile;
@@ -156,9 +159,9 @@ static void make_jitter_weight_tab(Render *re, ShadBuf *shb, short filtertype)
for (jit= shb->jit, a=0; a<tot; a++, jit+=2) {
if (filtertype==LA_SHADBUF_TENT)
- shb->weight[a]= 0.71f - sqrt(jit[0]*jit[0] + jit[1]*jit[1]);
+ shb->weight[a] = 0.71f - sqrtf(jit[0] * jit[0] + jit[1] * jit[1]);
else if (filtertype==LA_SHADBUF_GAUSS)
- shb->weight[a]= RE_filter_value(R_FILTER_GAUSS, 1.8f*sqrt(jit[0]*jit[0] + jit[1]*jit[1]));
+ shb->weight[a] = RE_filter_value(R_FILTER_GAUSS, 1.8f * sqrtf(jit[0] * jit[0] + jit[1] * jit[1]));
else
shb->weight[a]= 1.0f;
@@ -214,15 +217,15 @@ static int compress_deepsamples(DeepSample *dsample, int tot, float epsilon)
if (ds->z == newds->z) {
/* still in same z position, simply check
* visibility difference against epsilon */
- if (!(fabs(newds->v - ds->v) <= epsilon)) {
+ if (!(fabsf(newds->v - ds->v) <= epsilon)) {
break;
}
}
else {
/* compute slopes */
- div= (double)0x7FFFFFFF/((double)ds->z - (double)newds->z);
- min= ((ds->v - epsilon) - newds->v)*div;
- max= ((ds->v + epsilon) - newds->v)*div;
+ div= (double)0x7FFFFFFF / ((double)ds->z - (double)newds->z);
+ min= (double)((ds->v - epsilon) - newds->v) * div;
+ max= (double)((ds->v + epsilon) - newds->v) * div;
/* adapt existing slopes */
if (first) {
@@ -261,8 +264,8 @@ static int compress_deepsamples(DeepSample *dsample, int tot, float epsilon)
}
else {
/* compute visibility at center between slopes at z */
- slope= (slopemin+slopemax)*0.5f;
- v= newds->v + slope*((z - newds->z)/(double)0x7FFFFFFF);
+ slope = (slopemin + slopemax) * 0.5;
+ v = (double)newds->v + slope * ((double)(z - newds->z) / (double)0x7FFFFFFF);
}
newds++;
@@ -525,21 +528,21 @@ static void compress_shadowbuf(ShadBuf *shb, int *rectz, int square)
for (y=0; y<size; y+=16) {
if (y< size/2) miny= y+15-size/2;
- else miny= y-size/2;
+ else miny= y-size/2;
for (x=0; x<size; x+=16) {
/* is tile within spotbundle? */
a= size/2;
if (x< a) minx= x+15-a;
- else minx= x-a;
+ else minx= x-a;
dist= sqrt( (float)(minx*minx+miny*miny) );
if (square==0 && dist>(float)(a+12)) { /* 12, tested with a onlyshadow lamp */
a= 256; verg= 0; /* 0x80000000; */ /* 0x7FFFFFFF; */
rz1= (&verg)+1;
- }
+ }
else {
copy_to_ztile(rectz, size, x, y, 16, rcline);
rz1= (int *)rcline;
@@ -666,8 +669,8 @@ static void shadowbuf_autoclip(Render *re, LampRen *lar)
clipflag[vlr->v2->index]= 1;
clipflag[vlr->v3->index]= 1;
if (vlr->v4) clipflag[vlr->v4->index]= 1;
- }
- }
+ }
+ }
/* calculate min and max */
for (a=0; a< obr->totvert;a++) {
@@ -775,7 +778,7 @@ void makeshadowbuf(Render *re, LampRen *lar)
* transforming from observer view to lamp view, including lamp window matrix */
angle= saacos(lar->spotsi);
- temp= 0.5f*shb->size*cos(angle)/sin(angle);
+ temp = 0.5f * shb->size * cosf(angle) / sinf(angle);
shb->pixsize= (shb->d)/temp;
wsize= shb->pixsize*(shb->size/2.0f);
@@ -853,10 +856,10 @@ void threaded_makeshadowbufs(Render *re)
if (lar->shb)
totthread++;
- totthread= MIN2(totthread, re->r.threads);
+ totthread = min_ii(totthread, re->r.threads);
}
else
- totthread= 1; /* preview render */
+ totthread = 1; /* preview render */
if (totthread <= 1) {
for (lar=re->lampren.first; lar; lar= lar->next) {
@@ -1391,7 +1394,7 @@ float shadow_halo(LampRen *lar, const float p1[3], const float p2[3])
}
}
- labda = minf(labdax, labday);
+ labda = min_ff(labdax, labday);
if (labda==labdao || labda>=1.0f) break;
zf= zf1 + labda*(zf2-zf1);
@@ -1506,7 +1509,7 @@ static void isb_bsp_split_init(ISBBranch *root, MemArena *mem, int level)
root->divider[1]= 0.5f*(root->box.ymin+root->box.ymax);
/* find best splitpoint */
- if (BLI_RCT_SIZE_X(&root->box) > BLI_RCT_SIZE_Y(&root->box))
+ if (RCT_SIZE_X(&root->box) > RCT_SIZE_Y(&root->box))
i = root->index = 0;
else
i = root->index = 1;
@@ -1551,7 +1554,7 @@ static void isb_bsp_split(ISBBranch *root, MemArena *mem)
root->divider[1]/= BSPMAX_SAMPLE;
/* find best splitpoint */
- if (BLI_RCT_SIZE_X(&root->box) > BLI_RCT_SIZE_Y(&root->box))
+ if (RCT_SIZE_X(&root->box) > RCT_SIZE_Y(&root->box))
i = root->index = 0;
else
i = root->index = 1;
@@ -1660,9 +1663,9 @@ static void bspface_init_strand(BSPFace *face)
face->len= face->rc[0]*face->rc[0]+ face->rc[1]*face->rc[1];
- if (face->len!=0.0f) {
- face->radline_end= face->radline/sqrt(face->len);
- face->len= 1.0f/face->len;
+ if (face->len != 0.0f) {
+ face->radline_end = face->radline / sqrtf(face->len);
+ face->len = 1.0f / face->len;
}
}
@@ -1864,7 +1867,7 @@ static void isb_bsp_recalc_box(ISBBranch *root)
init_box(&root->box);
for (a=root->totsamp-1; a>=0; a--)
bound_boxf(&root->box, root->samples[a]->zco);
- }
+ }
}
/* callback function for zbuf clip */
@@ -2037,7 +2040,7 @@ static void isb_bsp_fillfaces(Render *re, LampRen *lar, ISBBranch *root)
if (vlr->v4)
c4= testclip(hoco[3]);
- /* ***** NO WIRE YET */
+ /* ***** NO WIRE YET */
if (ma->material_type == MA_TYPE_WIRE) {
if (vlr->v4)
zbufclipwire(&zspan, i, a+1, vlr->ec, hoco[0], hoco[1], hoco[2], hoco[3], c1, c2, c3, c4);
@@ -2184,7 +2187,7 @@ static int isb_add_samples(RenderPart *pa, ISBBranch *root, MemArena *memarena,
}
if (bsp_err) break;
}
- }
+ }
MEM_freeN(xcos);
MEM_freeN(ycos);
@@ -2391,7 +2394,7 @@ static int isb_add_samples_transp(RenderPart *pa, ISBBranch *root, MemArena *mem
}
if (bsp_err) break;
}
- }
+ }
MEM_freeN(xcos);
MEM_freeN(ycos);
diff --git a/source/blender/render/intern/source/shadeinput.c b/source/blender/render/intern/source/shadeinput.c
index d1d2c66985e..db93a21de2d 100644
--- a/source/blender/render/intern/source/shadeinput.c
+++ b/source/blender/render/intern/source/shadeinput.c
@@ -44,6 +44,7 @@
#include "DNA_material_types.h"
#include "BKE_colortools.h"
+#include "BKE_scene.h"
#include "BKE_node.h"
@@ -86,12 +87,6 @@ extern struct Render R;
*
*/
-#define VECADDISFAC(v1,v3,fac) { \
- *(v1 + 0) += *(v3 + 0) * (fac); \
- *(v1 + 1) += *(v3 + 1) * (fac); \
- *(v1 + 2) += *(v3 + 2) * (fac); \
-} (void)0
-
/* initialize material variables in shadeinput,
* doing inverse gamma correction where applicable */
void shade_input_init_material(ShadeInput *shi)
@@ -120,13 +115,13 @@ void shade_material_loop(ShadeInput *shi, ShadeResult *shr)
shi->depth--;
/* a couple of passes */
- VECADDISFAC(shr->combined, shr_t.combined, fac);
+ madd_v3_v3fl(shr->combined, shr_t.combined, fac);
if (shi->passflag & SCE_PASS_SPEC)
- VECADDISFAC(shr->spec, shr_t.spec, fac);
+ madd_v3_v3fl(shr->spec, shr_t.spec, fac);
if (shi->passflag & SCE_PASS_DIFFUSE)
- VECADDISFAC(shr->diff, shr_t.diff, fac);
+ madd_v3_v3fl(shr->diff, shr_t.diff, fac);
if (shi->passflag & SCE_PASS_SHADOW)
- VECADDISFAC(shr->shad, shr_t.shad, fac);
+ madd_v3_v3fl(shr->shad, shr_t.shad, fac);
negate_v3(shi->vn);
negate_v3(shi->facenor);
@@ -241,7 +236,7 @@ void vlr_set_uv_indices(VlakRen *vlr, int *i1, int *i2, int *i3)
/* 1---2 1---2 0 = orig face, 1 = new face */
/* Update vert nums to point to correct verts of original face */
- if (vlr->flag & R_DIVIDE_24) {
+ if (vlr->flag & R_DIVIDE_24) {
if (vlr->flag & R_FACE_SPLIT) {
(*i1)++; (*i2)++; (*i3)++;
}
@@ -574,10 +569,6 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
shi->dywin[1] = 0.0f;
}
}
-
- if (texco & TEXCO_STICKY) {
- /* not supported */
- }
}
if (shi->do_manage) {
@@ -786,7 +777,7 @@ void shade_input_set_uv(ShadeInput *shi)
CLAMP(shi->u, -2.0f, 1.0f);
CLAMP(shi->v, -2.0f, 1.0f);
}
- }
+ }
}
void shade_input_set_normals(ShadeInput *shi)
@@ -1124,50 +1115,113 @@ void shade_input_set_shade_texco(ShadeInput *shi)
for (i = 0; (tface = RE_vlakren_get_tface(obr, vlr, i, &name, 0)); i++) {
ShadeInputUV *suv = &shi->uv[i];
- float *uv1, *uv2, *uv3;
+ const float *uv1 = tface->uv[j1];
+ const float *uv2 = tface->uv[j2];
+ const float *uv3 = tface->uv[j3];
shi->totuv++;
suv->name = name;
-
- uv1 = tface->uv[j1];
- uv2 = tface->uv[j2];
- uv3 = tface->uv[j3];
- suv->uv[0] = -1.0f + 2.0f * (l * uv3[0] - u * uv1[0] - v * uv2[0]);
- suv->uv[1] = -1.0f + 2.0f * (l * uv3[1] - u * uv1[1] - v * uv2[1]);
- suv->uv[2] = 0.0f; /* texture.c assumes there are 3 coords */
+ if ((shi->mat->mapflag & MA_MAPFLAG_UVPROJECT) && (shi->depth == 0)) {
+ float x = shi->xs;
+ float y = shi->ys;
+
+ float s1[2] = {-1.0f + 2.0f * uv1[0], -1.0f + 2.0f * uv1[1]};
+ float s2[2] = {-1.0f + 2.0f * uv2[0], -1.0f + 2.0f * uv2[1]};
+ float s3[2] = {-1.0f + 2.0f * uv3[0], -1.0f + 2.0f * uv3[1]};
+
+
+ float obwinmat[4][4], winmat[4][4], ho1[4], ho2[4], ho3[4];
+ float Zmulx, Zmuly;
+ float hox, hoy, l, dl, u, v;
+ float s00, s01, s10, s11, detsh;
+
+ /* old globals, localized now */
+ Zmulx = ((float)R.winx) / 2.0f;
+ Zmuly = ((float)R.winy) / 2.0f;
+
+ zbuf_make_winmat(&R, winmat);
+ if (shi->obi->flag & R_TRANSFORMED)
+ mult_m4_m4m4(obwinmat, winmat, obi->mat);
+ else
+ copy_m4_m4(obwinmat, winmat);
+
+ zbuf_render_project(obwinmat, v1->co, ho1);
+ zbuf_render_project(obwinmat, v2->co, ho2);
+ zbuf_render_project(obwinmat, v3->co, ho3);
+
+ s00 = ho3[0] / ho3[3] - ho1[0] / ho1[3];
+ s01 = ho3[1] / ho3[3] - ho1[1] / ho1[3];
+ s10 = ho3[0] / ho3[3] - ho2[0] / ho2[3];
+ s11 = ho3[1] / ho3[3] - ho2[1] / ho2[3];
+
+ detsh = s00 * s11 - s10 * s01;
+ detsh = (detsh != 0.0f) ? 1.0f / detsh : 0.0f;
+ s00 *= detsh; s01 *= detsh;
+ s10 *= detsh; s11 *= detsh;
+
+ /* recalc u and v again */
+ hox = x / Zmulx - 1.0f;
+ hoy = y / Zmuly - 1.0f;
+ u = (hox - ho3[0] / ho3[3]) * s11 - (hoy - ho3[1] / ho3[3]) * s10;
+ v = (hoy - ho3[1] / ho3[3]) * s00 - (hox - ho3[0] / ho3[3]) * s01;
+ l = 1.0f + u + v;
+
+ suv->uv[0] = l * s3[0] - u * s1[0] - v * s2[0];
+ suv->uv[1] = l * s3[1] - u * s1[1] - v * s2[1];
+ suv->uv[2] = 0.0f;
- if (shi->osatex) {
- float duv[2];
-
- dl = shi->dx_u + shi->dx_v;
- duv[0] = shi->dx_u;
- duv[1] = shi->dx_v;
+ if (shi->osatex) {
+ float dxuv[2], dyuv[2];
+ dxuv[0] = s11 / Zmulx;
+ dxuv[1] = -s01 / Zmulx;
+ dyuv[0] = -s10 / Zmuly;
+ dyuv[1] = s00 / Zmuly;
+
+ dl = dxuv[0] + dxuv[1];
+ suv->dxuv[0] = dl * s3[0] - dxuv[0] * s1[0] - dxuv[1] * s2[0];
+ suv->dxuv[1] = dl * s3[1] - dxuv[0] * s1[1] - dxuv[1] * s2[1];
+ dl = dyuv[0] + dyuv[1];
+ suv->dyuv[0] = dl * s3[0] - dyuv[0] * s1[0] - dyuv[1] * s2[0];
+ suv->dyuv[1] = dl * s3[1] - dyuv[0] * s1[1] - dyuv[1] * s2[1];
+ }
+ }
+ else {
- suv->dxuv[0] = 2.0f * (dl * uv3[0] - duv[0] * uv1[0] - duv[1] * uv2[0]);
- suv->dxuv[1] = 2.0f * (dl * uv3[1] - duv[0] * uv1[1] - duv[1] * uv2[1]);
+ suv->uv[0] = -1.0f + 2.0f * (l * uv3[0] - u * uv1[0] - v * uv2[0]);
+ suv->uv[1] = -1.0f + 2.0f * (l * uv3[1] - u * uv1[1] - v * uv2[1]);
+ suv->uv[2] = 0.0f; /* texture.c assumes there are 3 coords */
- dl = shi->dy_u + shi->dy_v;
- duv[0] = shi->dy_u;
- duv[1] = shi->dy_v;
+ if (shi->osatex) {
+ float duv[2];
- suv->dyuv[0] = 2.0f * (dl * uv3[0] - duv[0] * uv1[0] - duv[1] * uv2[0]);
- suv->dyuv[1] = 2.0f * (dl * uv3[1] - duv[0] * uv1[1] - duv[1] * uv2[1]);
- }
+ dl = shi->dx_u + shi->dx_v;
+ duv[0] = shi->dx_u;
+ duv[1] = shi->dx_v;
- if ((mode & MA_FACETEXTURE) && i == obr->actmtface) {
- if ((mode & (MA_VERTEXCOL | MA_VERTEXCOLP)) == 0) {
- shi->vcol[0] = 1.0f;
- shi->vcol[1] = 1.0f;
- shi->vcol[2] = 1.0f;
- shi->vcol[3] = 1.0f;
+ suv->dxuv[0] = 2.0f * (dl * uv3[0] - duv[0] * uv1[0] - duv[1] * uv2[0]);
+ suv->dxuv[1] = 2.0f * (dl * uv3[1] - duv[0] * uv1[1] - duv[1] * uv2[1]);
+
+ dl = shi->dy_u + shi->dy_v;
+ duv[0] = shi->dy_u;
+ duv[1] = shi->dy_v;
+
+ suv->dyuv[0] = 2.0f * (dl * uv3[0] - duv[0] * uv1[0] - duv[1] * uv2[0]);
+ suv->dyuv[1] = 2.0f * (dl * uv3[1] - duv[0] * uv1[1] - duv[1] * uv2[1]);
}
- if (tface->tpage) {
- render_realtime_texture(shi, tface->tpage);
+
+ if ((mode & MA_FACETEXTURE) && i == obr->actmtface) {
+ if ((mode & (MA_VERTEXCOL | MA_VERTEXCOLP)) == 0) {
+ shi->vcol[0] = 1.0f;
+ shi->vcol[1] = 1.0f;
+ shi->vcol[2] = 1.0f;
+ shi->vcol[3] = 1.0f;
+ }
+ if (tface->tpage) {
+ render_realtime_texture(shi, tface->tpage);
+ }
}
}
-
-
}
shi->dupliuv[0] = -1.0f + 2.0f * obi->dupliuv[0];
@@ -1236,70 +1290,6 @@ void shade_input_set_shade_texco(ShadeInput *shi)
shi->dywin[0] = shi->dywin[2] = 0.0f;
}
}
-
- if (texco & TEXCO_STICKY) {
- float *s1, *s2, *s3;
-
- s1 = RE_vertren_get_sticky(obr, v1, 0);
- s2 = RE_vertren_get_sticky(obr, v2, 0);
- s3 = RE_vertren_get_sticky(obr, v3, 0);
-
- if (s1 && s2 && s3) {
- float obwinmat[4][4], winmat[4][4], ho1[4], ho2[4], ho3[4];
- float Zmulx, Zmuly;
- float hox, hoy, l, dl, u, v;
- float s00, s01, s10, s11, detsh;
-
- /* old globals, localized now */
- Zmulx = ((float)R.winx) / 2.0f; Zmuly = ((float)R.winy) / 2.0f;
-
- zbuf_make_winmat(&R, winmat);
- if (shi->obi->flag & R_TRANSFORMED)
- mult_m4_m4m4(obwinmat, winmat, obi->mat);
- else
- copy_m4_m4(obwinmat, winmat);
-
- zbuf_render_project(obwinmat, v1->co, ho1);
- zbuf_render_project(obwinmat, v2->co, ho2);
- zbuf_render_project(obwinmat, v3->co, ho3);
-
- s00 = ho3[0] / ho3[3] - ho1[0] / ho1[3];
- s01 = ho3[1] / ho3[3] - ho1[1] / ho1[3];
- s10 = ho3[0] / ho3[3] - ho2[0] / ho2[3];
- s11 = ho3[1] / ho3[3] - ho2[1] / ho2[3];
-
- detsh = s00 * s11 - s10 * s01;
- detsh = (detsh != 0.0f) ? 1.0f / detsh : 0.0f;
- s00 *= detsh; s01 *= detsh;
- s10 *= detsh; s11 *= detsh;
-
- /* recalc u and v again */
- hox = x / Zmulx - 1.0f;
- hoy = y / Zmuly - 1.0f;
- u = (hox - ho3[0] / ho3[3]) * s11 - (hoy - ho3[1] / ho3[3]) * s10;
- v = (hoy - ho3[1] / ho3[3]) * s00 - (hox - ho3[0] / ho3[3]) * s01;
- l = 1.0f + u + v;
-
- shi->sticky[0] = l * s3[0] - u * s1[0] - v * s2[0];
- shi->sticky[1] = l * s3[1] - u * s1[1] - v * s2[1];
- shi->sticky[2] = 0.0f;
-
- if (shi->osatex) {
- float dxuv[2], dyuv[2];
- dxuv[0] = s11 / Zmulx;
- dxuv[1] = -s01 / Zmulx;
- dyuv[0] = -s10 / Zmuly;
- dyuv[1] = s00 / Zmuly;
-
- dl = dxuv[0] + dxuv[1];
- shi->dxsticky[0] = dl * s3[0] - dxuv[0] * s1[0] - dxuv[1] * s2[0];
- shi->dxsticky[1] = dl * s3[1] - dxuv[0] * s1[1] - dxuv[1] * s2[1];
- dl = dyuv[0] + dyuv[1];
- shi->dysticky[0] = dl * s3[0] - dyuv[0] * s1[0] - dyuv[1] * s2[0];
- shi->dysticky[1] = dl * s3[1] - dyuv[0] * s1[1] - dyuv[1] * s2[1];
- }
- }
- }
}
/* else {
* Note! For raytracing winco is not set,
@@ -1326,12 +1316,7 @@ void shade_input_initialize(ShadeInput *shi, RenderPart *pa, RenderLayer *rl, in
shi->thread = pa->thread;
shi->do_preview = (R.r.scemode & R_MATNODE_PREVIEW) != 0;
- /* OCIO_TODO: for now assume color management is always enabled and vertes colors are in sRGB space
- * probably would be nice to have this things configurable, but for now it should work
- * also probably this flag could be removed (in separated commit) before the release
- * since it's not actually meaningful anymore
- */
- shi->do_manage = TRUE;
+ shi->do_manage = BKE_scene_check_color_management_enabled(R.scene);
shi->lay = rl->lay;
shi->layflag = rl->layflag;
diff --git a/source/blender/render/intern/source/shadeoutput.c b/source/blender/render/intern/source/shadeoutput.c
index 6883710d1be..77602edf955 100644
--- a/source/blender/render/intern/source/shadeoutput.c
+++ b/source/blender/render/intern/source/shadeoutput.c
@@ -57,6 +57,9 @@
#include "shading.h" /* own include */
+/* could enable at some point but for now there are far too many conversions */
+#pragma GCC diagnostic ignored "-Wdouble-promotion"
+
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
/* only to be used here in this file, it's for speed */
@@ -114,7 +117,7 @@ static void fogcolor(const float colf[3], float *rco, float *view)
addAlphaOverFloat(colf, hor);
sub_v3_v3(vec, dview);
- }
+ }
}
#endif
@@ -123,37 +126,52 @@ float mistfactor(float zcor, float const co[3])
{
float fac, hi;
- fac= zcor - R.wrld.miststa; /* zcor is calculated per pixel */
+ fac = zcor - R.wrld.miststa; /* zcor is calculated per pixel */
/* fac= -co[2]-R.wrld.miststa; */
- if (fac>0.0f) {
- if (fac< R.wrld.mistdist) {
+ if (fac > 0.0f) {
+ if (fac < R.wrld.mistdist) {
- fac= (fac/(R.wrld.mistdist));
+ fac = (fac / R.wrld.mistdist);
- if (R.wrld.mistype==0) fac*= fac;
- else if (R.wrld.mistype==1);
- else fac= sqrt(fac);
+ if (R.wrld.mistype == 0) {
+ fac *= fac;
+ }
+ else if (R.wrld.mistype == 1) {
+ /* pass */
+ }
+ else {
+ fac = sqrt(fac);
+ }
}
- else fac= 1.0f;
+ else {
+ fac = 1.0f;
+ }
+ }
+ else {
+ fac = 0.0f;
}
- else fac= 0.0f;
/* height switched off mist */
if (R.wrld.misthi!=0.0f && fac!=0.0f) {
/* at height misthi the mist is completely gone */
- hi= R.viewinv[0][2]*co[0]+R.viewinv[1][2]*co[1]+R.viewinv[2][2]*co[2]+R.viewinv[3][2];
+ hi = R.viewinv[0][2] * co[0] +
+ R.viewinv[1][2] * co[1] +
+ R.viewinv[2][2] * co[2] +
+ R.viewinv[3][2];
- if (hi>R.wrld.misthi) fac= 0.0f;
+ if (hi > R.wrld.misthi) {
+ fac = 0.0f;
+ }
else if (hi>0.0f) {
hi= (R.wrld.misthi-hi)/R.wrld.misthi;
fac*= hi*hi;
}
}
- return (1.0f-fac)* (1.0f-R.wrld.misi);
+ return (1.0f-fac)* (1.0f-R.wrld.misi);
}
static void spothalo(struct LampRen *lar, ShadeInput *shi, float *intens)
@@ -213,7 +231,7 @@ static void spothalo(struct LampRen *lar, ShadeInput *shi, float *intens)
}
}
- /* scale z to make sure volume is normalized */
+ /* scale z to make sure volume is normalized */
nray[2] *= (double)lar->sh_zfac;
/* nray does not need normalization */
@@ -299,8 +317,8 @@ static void spothalo(struct LampRen *lar, ShadeInput *shi, float *intens)
/* calculate t0: is the maximum visible z (when halo is intersected by face) */
if (do_clip) {
- if (use_yco == FALSE) t0 = (maxz - npos[2]) / nray[2];
- else t0 = (maxy - npos[1]) / nray[1];
+ if (use_yco == FALSE) t0 = ((double)maxz - npos[2]) / nray[2];
+ else t0 = ((double)maxy - npos[1]) / nray[1];
if (t0 < t1) return;
if (t0 < t2) t2= t0;
@@ -453,9 +471,10 @@ static float area_lamp_energy(float (*area)[3], const float co[3], const float v
/* cross product */
#define CROSS(dest, a, b) \
- { dest[0]= a[1] * b[2] - a[2] * b[1]; \
- dest[1]= a[2] * b[0] - a[0] * b[2]; \
- dest[2]= a[0] * b[1] - a[1] * b[0]; \
+ { \
+ dest[0]= a[1] * b[2] - a[2] * b[1]; \
+ dest[1]= a[2] * b[0] - a[0] * b[2]; \
+ dest[2]= a[0] * b[1] - a[1] * b[0]; \
} (void)0
CROSS(cross[0], vec[0], vec[1]);
@@ -532,7 +551,7 @@ static float spec(float inp, int hard)
b1= inp*inp;
/* avoid FPE */
- if (b1<0.01f) b1= 0.01f;
+ if (b1<0.01f) b1= 0.01f;
if ((hard & 1)==0) inp= 1.0f;
if (hard & 2) inp*= b1;
@@ -545,7 +564,7 @@ static float spec(float inp, int hard)
b1*= b1;
/* avoid FPE */
- if (b1<0.001f) b1= 0.0f;
+ if (b1<0.001f) b1= 0.0f;
if (hard & 32) inp*= b1;
b1*= b1;
@@ -553,7 +572,7 @@ static float spec(float inp, int hard)
b1*= b1;
if (hard & 128) inp*=b1;
- if (b1<0.001f) b1= 0.0f;
+ if (b1<0.001f) b1= 0.0f;
if (hard & 256) {
b1*= b1;
@@ -811,7 +830,7 @@ static float Minnaert_Diff(float nl, const float n[3], const float v[3], float d
nv = 0.0f;
if (darkness <= 1.0f)
- i = nl * pow(maxf(nv * nl, 0.1f), (darkness - 1.0f) ); /*The Real model*/
+ i = nl * pow(max_ff(nv * nl, 0.1f), (darkness - 1.0f) ); /*The Real model*/
else
i = nl * pow( (1.001f - nv), (darkness - 1.0f) ); /*Nvidia model*/
@@ -1217,7 +1236,7 @@ float lamp_get_visibility(LampRen *lar, const float co[3], float lv[3], float *d
copy_v3_v3(lvrot, lv);
mul_m3_v3(lar->imat, lvrot);
- x = maxf(fabsf(lvrot[0]/lvrot[2]), fabsf(lvrot[1]/lvrot[2]));
+ x = max_ff(fabsf(lvrot[0]/lvrot[2]), fabsf(lvrot[1]/lvrot[2]));
/* 1.0f/(sqrt(1+x*x)) is equivalent to cos(atan(x)) */
inpr= 1.0f/(sqrt(1.0f+x*x));
@@ -1301,7 +1320,7 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
if (lar->mode & LA_TEXTURE) do_lamp_tex(lar, lv, shi, lacol, LA_TEXTURE);
if (lar->mode & LA_SHAD_TEX) do_lamp_tex(lar, lv, shi, lashdw, LA_SHAD_TEX);
- /* tangent case; calculate fake face normal, aligned with lampvector */
+ /* tangent case; calculate fake face normal, aligned with lampvector */
/* note, vnor==vn is used as tangent trigger for buffer shadow */
if (vlr->flag & R_TANGENT) {
float cross[3], nstrand[3], blend;
@@ -1347,11 +1366,13 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
/* inp = dotproduct, is = shader result, i = lamp energy (with shadow), i_noshad = i without shadow */
inp= dot_v3v3(vn, lv);
- /* phong threshold to prevent backfacing faces having artefacts on ray shadow (terminator problem) */
+ /* phong threshold to prevent backfacing faces having artifacts on ray shadow (terminator problem) */
/* this complex construction screams for a nicer implementation! (ton) */
if (R.r.mode & R_SHADOW) {
if (ma->mode & MA_SHADOW) {
- if (lar->type==LA_HEMI || lar->type==LA_AREA);
+ if (lar->type == LA_HEMI || lar->type == LA_AREA) {
+ /* pass */
+ }
else if ((ma->mode & MA_RAYBIAS) && (lar->mode & LA_SHAD_RAY) && (vlr->flag & R_SMOOTH)) {
float thresh= shi->obr->ob->smoothresh;
if (inp>thresh)
@@ -1466,8 +1487,10 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
if (shadfac[3]>0.0f && shi->spec!=0.0f && !(lar->mode & LA_NO_SPEC) && !(lar->mode & LA_ONLYSHADOW)) {
- if (!(passflag & (SCE_PASS_COMBINED|SCE_PASS_SPEC)));
- else if (lar->type==LA_HEMI) {
+ if (!(passflag & (SCE_PASS_COMBINED | SCE_PASS_SPEC))) {
+ /* pass */
+ }
+ else if (lar->type == LA_HEMI) {
float t;
/* hemi uses no spec shaders (yet) */
@@ -1617,7 +1640,7 @@ static void shade_lamp_loop_only_shadow(ShadeInput *shi, ShadeResult *shr)
}
}
- /* quite disputable this... also note it doesn't mirror-raytrace */
+ /* quite disputable this... also note it doesn't mirror-raytrace */
if ((R.wrld.mode & (WO_AMB_OCC|WO_ENV_LIGHT)) && shi->amb!=0.0f) {
float f;
@@ -1825,7 +1848,7 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
}
}
- if (shi->combinedflag & SCE_PASS_SHADOW)
+ if (shi->combinedflag & SCE_PASS_SHADOW)
copy_v3_v3(shr->combined, shr->shad); /* note, no ';' ! */
else
copy_v3_v3(shr->combined, shr->diff);
diff --git a/source/blender/render/intern/source/sss.c b/source/blender/render/intern/source/sss.c
index 69e738e840d..6d0e15ea46e 100644
--- a/source/blender/render/intern/source/sss.c
+++ b/source/blender/render/intern/source/sss.c
@@ -238,7 +238,9 @@ static void approximate_Rd_rgb(ScatterSettings **ss, float rr, float *rd)
float indexf, t, idxf;
int index;
- if (rr > (RD_TABLE_RANGE_2*RD_TABLE_RANGE_2));
+ if (rr > (RD_TABLE_RANGE_2 * RD_TABLE_RANGE_2)) {
+ /* pass */
+ }
else if (rr > RD_TABLE_RANGE) {
rr= sqrt(rr);
indexf= rr*(RD_TABLE_SIZE/RD_TABLE_RANGE_2);
@@ -305,7 +307,7 @@ ScatterSettings *scatter_settings_new(float refl, float radius, float ior, float
ss->Fdr= -1.440f/ior*ior + 0.710f/ior + 0.668f + 0.0636f*ior;
ss->A= (1.0f + ss->Fdr)/(1.0f - ss->Fdr);
ss->ld= radius;
- ss->ro= minf(refl, 0.999f);
+ ss->ro= min_ff(refl, 0.999f);
ss->color= ss->ro*reflfac + (1.0f-reflfac);
ss->alpha_= compute_reduced_albedo(ss);
@@ -379,7 +381,7 @@ static void add_radiance(ScatterTree *tree, float *frontrad, float *backrad, flo
}
}
-static void traverse_octree(ScatterTree *tree, ScatterNode *node, float *co, int self, ScatterResult *result)
+static void traverse_octree(ScatterTree *tree, ScatterNode *node, const float co[3], int self, ScatterResult *result)
{
float sub[3], dist;
int i, index = 0;
@@ -430,7 +432,7 @@ static void traverse_octree(ScatterTree *tree, ScatterNode *node, float *co, int
}
}
-static void compute_radiance(ScatterTree *tree, float *co, float *rad)
+static void compute_radiance(ScatterTree *tree, const float co[3], float *rad)
{
ScatterResult result;
float rdsum[3], backrad[3], backrdsum[3];
diff --git a/source/blender/render/intern/source/strand.c b/source/blender/render/intern/source/strand.c
index dc3225b7f09..2fe8adaa1ee 100644
--- a/source/blender/render/intern/source/strand.c
+++ b/source/blender/render/intern/source/strand.c
@@ -449,6 +449,7 @@ typedef struct StrandPart {
int sample;
int shadow;
float (*jit)[2];
+ int samples;
StrandSegment *segment;
float t[3], s[3];
@@ -545,7 +546,7 @@ static void do_strand_fillac(void *handle, int x, int y, float u, float v, float
bufferz= 0x7FFFFFFF;
if (spart->rectmask) maskz= 0x7FFFFFFF;
- if (*rd) {
+ if (*rd) {
for (ps= (PixStr *)(*rd); ps; ps= ps->next) {
if (mask & ps->mask) {
bufferz= ps->z;
@@ -669,12 +670,8 @@ static void strand_render(Render *re, StrandSegment *sseg, float winmat[][4], St
float dt= p2->t - p1->t;
int a;
- if (re->osa) {
- for (a=0; a<re->osa; a++)
- do_scanconvert_strand(re, spart, zspan, t, dt, p1->zco2, p1->zco1, p2->zco1, p2->zco2, a);
- }
- else
- do_scanconvert_strand(re, spart, zspan, t, dt, p1->zco2, p1->zco1, p2->zco1, p2->zco2, 0);
+ for (a=0; a<spart->samples; a++)
+ do_scanconvert_strand(re, spart, zspan, t, dt, p1->zco2, p1->zco1, p2->zco1, p2->zco2, a);
}
else {
float hoco1[4], hoco2[4];
@@ -786,7 +783,7 @@ void render_strand_segment(Render *re, float winmat[][4], StrandPart *spart, ZSp
}
/* render call to fill in strands */
-int zbuffer_strands_abuf(Render *re, RenderPart *pa, APixstrand *apixbuf, ListBase *apsmbase, unsigned int lay, int UNUSED(negzmask), float winmat[][4], int winx, int winy, int UNUSED(sample), float (*jit)[2], float clipcrop, int shadow, StrandShadeCache *cache)
+int zbuffer_strands_abuf(Render *re, RenderPart *pa, APixstrand *apixbuf, ListBase *apsmbase, unsigned int lay, int UNUSED(negzmask), float winmat[][4], int winx, int winy, int samples, float (*jit)[2], float clipcrop, int shadow, StrandShadeCache *cache)
{
ObjectRen *obr;
ObjectInstanceRen *obi;
@@ -820,6 +817,7 @@ int zbuffer_strands_abuf(Render *re, RenderPart *pa, APixstrand *apixbuf, ListBa
spart.cache= cache;
spart.shadow= shadow;
spart.jit= jit;
+ spart.samples= samples;
zbuf_alloc_span(&zspan, pa->rectx, pa->recty, clipcrop);
diff --git a/source/blender/render/intern/source/sunsky.c b/source/blender/render/intern/source/sunsky.c
index 6a1517e19fb..e4a42fcd675 100644
--- a/source/blender/render/intern/source/sunsky.c
+++ b/source/blender/render/intern/source/sunsky.c
@@ -146,7 +146,7 @@ static float PerezFunction(struct SunSky *sunsky, const float *lam, float theta,
* sun_size, controls sun's size
* back_scatter, controls back scatter light
* */
-void InitSunSky(struct SunSky *sunsky, float turb, float *toSun, float horizon_brightness,
+void InitSunSky(struct SunSky *sunsky, float turb, const float toSun[3], float horizon_brightness,
float spread, float sun_brightness, float sun_size, float back_scatter,
float skyblendfac, short skyblendtype, float sky_exposure, float sky_colorspace)
{
@@ -217,8 +217,7 @@ void InitSunSky(struct SunSky *sunsky, float turb, float *toSun, float horizon_b
sunsky->perez_y[3] = -0.04405f * T - 1.65369f;
sunsky->perez_y[4] = -0.01092f * T + 0.05291f;
- /* suggested by glome in
- * http://projects.blender.org/tracker/?func=detail&atid=127&aid=8063&group_id=9*/
+ /* suggested by glome in patch [#8063] */
sunsky->perez_Y[0] *= sunsky->horizon_brightness;
sunsky->perez_x[0] *= sunsky->horizon_brightness;
sunsky->perez_y[0] *= sunsky->horizon_brightness;
@@ -275,7 +274,7 @@ void GetSkyXYZRadiance(struct SunSky *sunsky, float theta, float phi, float colo
/* Compute xyY values */
x = PerezFunction(sunsky, sunsky->perez_x, theta, gamma, sunsky->zenith_x);
y = PerezFunction(sunsky, sunsky->perez_y, theta, gamma, sunsky->zenith_y);
- Y = 6.666666667e-5f *nfade *hfade *PerezFunction(sunsky, sunsky->perez_Y, theta, gamma, sunsky->zenith_Y);
+ Y = 6.666666667e-5f * nfade * hfade * PerezFunction(sunsky, sunsky->perez_Y, theta, gamma, sunsky->zenith_Y);
if (sunsky->sky_exposure != 0.0f)
Y = 1.0 - exp(Y * sunsky->sky_exposure);
@@ -330,8 +329,8 @@ static void ComputeAttenuatedSunlight(float theta, int turbidity, float fTau[3])
int i;
float fLambda[3];
- fLambda[0] = 0.65f;
- fLambda[1] = 0.57f;
+ fLambda[0] = 0.65f;
+ fLambda[1] = 0.57f;
fLambda[2] = 0.475f;
fAlpha = 1.3f;
diff --git a/source/blender/render/intern/source/texture_ocean.c b/source/blender/render/intern/source/texture_ocean.c
index b2bc635cba7..a7547479093 100644
--- a/source/blender/render/intern/source/texture_ocean.c
+++ b/source/blender/render/intern/source/texture_ocean.c
@@ -55,7 +55,7 @@ extern struct Render R;
/* ***** actual texture sampling ***** */
-int ocean_texture(Tex *tex, float *texvec, TexResult *texres)
+int ocean_texture(Tex *tex, const float texvec[2], TexResult *texres)
{
OceanTex *ot = tex->ot;
ModifierData *md;
diff --git a/source/blender/render/intern/source/volume_precache.c b/source/blender/render/intern/source/volume_precache.c
index 8a92695a15e..8757be740f3 100644
--- a/source/blender/render/intern/source/volume_precache.c
+++ b/source/blender/render/intern/source/volume_precache.c
@@ -92,7 +92,7 @@ static int intersect_outside_volume(RayObject *tree, Isect *isect, float *offset
}
/* Uses ray tracing to check if a point is inside or outside an ObjectInstanceRen */
-static int point_inside_obi(RayObject *tree, ObjectInstanceRen *UNUSED(obi), float *co)
+static int point_inside_obi(RayObject *tree, ObjectInstanceRen *UNUSED(obi), const float co[3])
{
Isect isect= {{0}};
float dir[3] = {0.0f, 0.0f, 1.0f};
@@ -118,7 +118,7 @@ static int point_inside_obi(RayObject *tree, ObjectInstanceRen *UNUSED(obi), flo
}
/* find the bounding box of an objectinstance in global space */
-void global_bounds_obi(Render *re, ObjectInstanceRen *obi, float *bbmin, float *bbmax)
+void global_bounds_obi(Render *re, ObjectInstanceRen *obi, float bbmin[3], float bbmax[3])
{
ObjectRen *obr = obi->obr;
VolumePrecache *vp = obi->volume_precache;
@@ -270,7 +270,7 @@ BLI_INLINE int ms_I(int x, int y, int z, int *n) /* has a pad of 1 voxel surroun
BLI_INLINE int v_I_pad(int x, int y, int z, int *n) /* has a pad of 1 voxel surrounding the core for boundary simulation */
{
/* same ordering to light cache, with padding */
- return z*(n[1]+2)*(n[0]+2) + y*(n[0]+2) + x;
+ return z*(n[1]+2)*(n[0]+2) + y*(n[0]+2) + x;
}
BLI_INLINE int lc_to_ms_I(int x, int y, int z, int *n)
@@ -389,7 +389,7 @@ static void multiple_scattering_diffusion(Render *re, VolumePrecache *vp, Materi
const int j = ms_I(x, y, z, n); //ms index
time= PIL_check_seconds_timer();
- c++;
+ c++;
if (vp->data_r[i] > 0.0f)
sr[j] += vp->data_r[i];
if (vp->data_g[i] > 0.0f)
@@ -826,7 +826,7 @@ void free_volume_precache(Render *re)
BLI_freelistN(&re->volumes);
}
-int point_inside_volume_objectinstance(Render *re, ObjectInstanceRen *obi, float *co)
+int point_inside_volume_objectinstance(Render *re, ObjectInstanceRen *obi, const float co[3])
{
RayObject *tree;
int inside=0;
diff --git a/source/blender/render/intern/source/volumetric.c b/source/blender/render/intern/source/volumetric.c
index 220fcd3e986..fe4cff76093 100644
--- a/source/blender/render/intern/source/volumetric.c
+++ b/source/blender/render/intern/source/volumetric.c
@@ -76,7 +76,7 @@ static float vol_get_shadow(ShadeInput *shi, LampRen *lar, const float co[3])
if (lar->shb) {
float dxco[3] = {0.f, 0.f, 0.f}, dyco[3] = {0.f, 0.f, 0.f};
- visibility = testshadowbuf(&R, lar->shb, co, dxco, dyco, 1.0, 0.0);
+ visibility = testshadowbuf(&R, lar->shb, co, dxco, dyco, 1.0, 0.0);
}
else if (lar->mode & LA_SHAD_RAY) {
/* trace shadow manually, no good lamp api atm */
@@ -205,7 +205,7 @@ static void vol_trace_behind(ShadeInput *shi, VlakRen *vlr, const float co[3], f
else {
shadeSkyView(col_r, co, shi->view, NULL, shi->thread);
shadeSunView(col_r, shi->view);
- }
+ }
}
@@ -221,7 +221,7 @@ static void vol_get_precached_scattering(Render *re, ShadeInput *shi, float scat
/* find sample point in global space bounding box 0.0-1.0 */
global_bounds_obi(re, shi->obi, bbmin, bbmax);
sub_v3_v3v3(dim, bbmax, bbmin);
- mul_v3_m4v3(world_co, re->viewinv, co);
+ mul_v3_m4v3(world_co, re->viewinv, co);
/* sample_co in 0.0-1.0 */
sample_co[0] = (world_co[0] - bbmin[0]) / dim[0];
diff --git a/source/blender/render/intern/source/voxeldata.c b/source/blender/render/intern/source/voxeldata.c
index d73171648fb..b486407c61c 100644
--- a/source/blender/render/intern/source/voxeldata.c
+++ b/source/blender/render/intern/source/voxeldata.c
@@ -227,69 +227,102 @@ static void init_frame_smoke(VoxelData *vd, float cfra)
/* draw code for smoke */
if ((md = (ModifierData *)modifiers_findByType(ob, eModifierType_Smoke))) {
SmokeModifierData *smd = (SmokeModifierData *)md;
-
+ SmokeDomainSettings *sds = smd->domain;
- if (smd->domain && smd->domain->fluid) {
- if (cfra < smd->domain->point_cache[0]->startframe)
+ if (sds && sds->fluid) {
+ if (cfra < sds->point_cache[0]->startframe)
; /* don't show smoke before simulation starts, this could be made an option in the future */
else if (vd->smoked_type == TEX_VD_SMOKEHEAT) {
size_t totRes;
size_t i;
float *heat;
- copy_v3_v3_int(vd->resol, smd->domain->res);
- totRes = vd_resol_size(vd);
+ if (!smoke_has_heat(sds->fluid)) return;
- /* scaling heat values from -2.0-2.0 to 0.0-1.0 */
+ copy_v3_v3_int(vd->resol, sds->res);
+ totRes = vd_resol_size(vd);
vd->dataset = MEM_mapallocN(sizeof(float) * (totRes), "smoke data");
+ /* get heat data */
+ heat = smoke_get_heat(sds->fluid);
-
- heat = smoke_get_heat(smd->domain->fluid);
-
+ /* scale heat values from -2.0-2.0 to 0.0-1.0 */
for (i = 0; i < totRes; i++) {
vd->dataset[i] = (heat[i] + 2.0f) / 4.0f;
}
-
- /* vd->dataset = smoke_get_heat(smd->domain->fluid); */
}
else if (vd->smoked_type == TEX_VD_SMOKEVEL) {
size_t totRes;
size_t i;
float *xvel, *yvel, *zvel;
- copy_v3_v3_int(vd->resol, smd->domain->res);
+ copy_v3_v3_int(vd->resol, sds->res);
totRes = vd_resol_size(vd);
-
- /* scaling heat values from -2.0-2.0 to 0.0-1.0 */
vd->dataset = MEM_mapallocN(sizeof(float) * (totRes), "smoke data");
+ /* get velocity data */
+ xvel = smoke_get_velocity_x(sds->fluid);
+ yvel = smoke_get_velocity_y(sds->fluid);
+ zvel = smoke_get_velocity_z(sds->fluid);
- xvel = smoke_get_velocity_x(smd->domain->fluid);
- yvel = smoke_get_velocity_y(smd->domain->fluid);
- zvel = smoke_get_velocity_z(smd->domain->fluid);
-
+ /* map velocities between 0 and 0.3f */
for (i = 0; i < totRes; i++) {
vd->dataset[i] = sqrt(xvel[i] * xvel[i] + yvel[i] * yvel[i] + zvel[i] * zvel[i]) * 3.0f;
}
}
- else {
+ else if (vd->smoked_type == TEX_VD_SMOKEFLAME) {
size_t totRes;
- float *density;
+ float *flame;
- if (smd->domain->flags & MOD_SMOKE_HIGHRES) {
- smoke_turbulence_get_res(smd->domain->wt, vd->resol);
- density = smoke_turbulence_get_density(smd->domain->wt);
+ if (sds->flags & MOD_SMOKE_HIGHRES) {
+ if (!smoke_turbulence_has_fuel(sds->wt)) return;
+ smoke_turbulence_get_res(sds->wt, vd->resol);
+ flame = smoke_turbulence_get_flame(sds->wt);
}
else {
- copy_v3_v3_int(vd->resol, smd->domain->res);
- density = smoke_get_density(smd->domain->fluid);
+ if (!smoke_has_fuel(sds->fluid)) return;
+ copy_v3_v3_int(vd->resol, sds->res);
+ flame = smoke_get_flame(sds->fluid);
}
- /* TODO: is_vd_res_ok(rvd) doesnt check this resolution */
+ /* always store copy, as smoke internal data can change */
totRes = vd_resol_size(vd);
+ vd->dataset = MEM_mapallocN(sizeof(float)*(totRes), "smoke data");
+ memcpy(vd->dataset, flame, sizeof(float)*totRes);
+ }
+ else {
+ size_t totCells;
+ int depth = 4;
+ vd->data_type = TEX_VD_RGBA_PREMUL;
+
+ /* data resolution */
+ if (sds->flags & MOD_SMOKE_HIGHRES) {
+ smoke_turbulence_get_res(sds->wt, vd->resol);
+ }
+ else {
+ copy_v3_v3_int(vd->resol, sds->res);
+ }
+
+ /* TODO: is_vd_res_ok(rvd) doesnt check this resolution */
+ totCells = vd_resol_size(vd) * depth;
/* always store copy, as smoke internal data can change */
- vd->dataset = MEM_mapallocN(sizeof(float) * (totRes), "smoke data");
- memcpy(vd->dataset, density, sizeof(float) * totRes);
+ vd->dataset = MEM_mapallocN(sizeof(float) * totCells, "smoke data");
+
+ if (sds->flags & MOD_SMOKE_HIGHRES) {
+ if (smoke_turbulence_has_colors(sds->wt)) {
+ smoke_turbulence_get_rgba(sds->wt, vd->dataset, 1);
+ }
+ else {
+ smoke_turbulence_get_rgba_from_density(sds->wt, sds->active_color, vd->dataset, 1);
+ }
+ }
+ else {
+ if (smoke_has_colors(sds->fluid)) {
+ smoke_get_rgba(sds->fluid, vd->dataset, 1);
+ }
+ else {
+ smoke_get_rgba_from_density(sds->fluid, sds->active_color, vd->dataset, 1);
+ }
+ }
} /* end of fluid condition */
}
}
@@ -320,6 +353,8 @@ void cache_voxeldata(Tex *tex, int scene_frame)
MEM_freeN(vd->dataset);
vd->dataset = NULL;
}
+ /* reset data_type */
+ vd->data_type = TEX_VD_INTENSITY;
if (vd->flag & TEX_VD_STILL)
curframe = vd->still_frame;
@@ -379,9 +414,11 @@ void make_voxeldata(struct Render *re)
int voxeldatatex(struct Tex *tex, const float texvec[3], struct TexResult *texres)
{
- int retval = TEX_INT;
- VoxelData *vd = tex->vd;
- float co[3], offset[3] = {0.5, 0.5, 0.5};
+ VoxelData *vd = tex->vd;
+ float co[3], offset[3] = {0.5, 0.5, 0.5}, a;
+ int retval = (vd->data_type == TEX_VD_RGBA_PREMUL) ? TEX_RGB : TEX_INT;
+ int depth = (vd->data_type == TEX_VD_RGBA_PREMUL) ? 4 : 1;
+ int ch;
if (vd->dataset == NULL) {
texres->tin = 0.0f;
@@ -420,31 +457,63 @@ int voxeldatatex(struct Tex *tex, const float texvec[3], struct TexResult *texre
break;
}
}
-
- switch (vd->interp_type) {
- case TEX_VD_NEARESTNEIGHBOR:
- texres->tin = BLI_voxel_sample_nearest(vd->dataset, vd->resol, co);
- break;
- case TEX_VD_LINEAR:
- texres->tin = BLI_voxel_sample_trilinear(vd->dataset, vd->resol, co);
- break;
- case TEX_VD_QUADRATIC:
- texres->tin = BLI_voxel_sample_triquadratic(vd->dataset, vd->resol, co);
- break;
- case TEX_VD_TRICUBIC_CATROM:
- case TEX_VD_TRICUBIC_BSPLINE:
- texres->tin = BLI_voxel_sample_tricubic(vd->dataset, vd->resol, co, (vd->interp_type == TEX_VD_TRICUBIC_BSPLINE));
- break;
+
+ for (ch = 0; ch < depth; ch++) {
+ float *dataset = vd->dataset + ch*vd->resol[0]*vd->resol[1]*vd->resol[2];
+ float *result = &texres->tin;
+
+ if (vd->data_type == TEX_VD_RGBA_PREMUL) {
+ switch (ch) {
+ case 0:
+ result = &texres->tr;
+ break;
+ case 1:
+ result = &texres->tg;
+ break;
+ case 2:
+ result = &texres->tb;
+ break;
+ }
+ }
+
+ switch (vd->interp_type) {
+ case TEX_VD_NEARESTNEIGHBOR:
+ *result = BLI_voxel_sample_nearest(dataset, vd->resol, co);
+ break;
+ case TEX_VD_LINEAR:
+ *result = BLI_voxel_sample_trilinear(dataset, vd->resol, co);
+ break;
+ case TEX_VD_QUADRATIC:
+ *result = BLI_voxel_sample_triquadratic(dataset, vd->resol, co);
+ break;
+ case TEX_VD_TRICUBIC_CATROM:
+ case TEX_VD_TRICUBIC_BSPLINE:
+ *result = BLI_voxel_sample_tricubic(dataset, vd->resol, co, (vd->interp_type == TEX_VD_TRICUBIC_BSPLINE));
+ break;
+ }
}
-
+
+ a = texres->tin;
texres->tin *= vd->int_multiplier;
BRICONT;
- texres->tr = texres->tin;
- texres->tg = texres->tin;
- texres->tb = texres->tin;
+ if (vd->data_type == TEX_VD_RGBA_PREMUL) {
+ /* unmultiply */
+ if (a>0.001f) {
+ texres->tr /= a;
+ texres->tg /= a;
+ texres->tb /= a;
+ }
+ texres->talpha = 1;
+ }
+ else {
+ texres->tr = texres->tin;
+ texres->tg = texres->tin;
+ texres->tb = texres->tin;
+ }
+
texres->ta = texres->tin;
BRICONTRGB;
- return retval;
+ return retval;
}
diff --git a/source/blender/render/intern/source/zbuf.c b/source/blender/render/intern/source/zbuf.c
index bf6962d0087..62bf9ac2005 100644
--- a/source/blender/render/intern/source/zbuf.c
+++ b/source/blender/render/intern/source/zbuf.c
@@ -76,6 +76,9 @@
/* own includes */
#include "zbuf.h"
+/* could enable at some point but for now there are far too many conversions */
+#pragma GCC diagnostic ignored "-Wdouble-promotion"
+
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
/* only to be used here in this file, it's for speed */
@@ -150,7 +153,7 @@ static void zbuf_add_to_span(ZSpan *zspan, const float *v1, const float *v2)
}
else {
dx0 = 0.0f;
- xs0 = minf(minv[0], maxv[0]);
+ xs0 = min_ff(minv[0], maxv[0]);
}
/* empty span */
@@ -409,7 +412,7 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr,
if (apn->p[3]==zvlnr && apn->obi[3]==obi) {apn->mask[3]|= mask; break; }
if (apn->next==NULL) apn->next= addpsA(zspan);
apn= apn->next;
- }
+ }
}
}
zverg+= zxd;
@@ -501,7 +504,7 @@ static void zbuflineAc(ZSpan *zspan, int obi, int zvlnr, const float vec1[3], co
if (apn->p[3]==zvlnr && apn->obi[3]==obi) {apn->mask[3]|= mask; break; }
if (apn->next==0) apn->next= addpsA(zspan);
apn= apn->next;
- }
+ }
}
}
}
@@ -572,7 +575,7 @@ static void zbuflineAc(ZSpan *zspan, int obi, int zvlnr, const float vec1[3], co
if (apn->p[3]==zvlnr) {apn->mask[3]|= mask; break; }
if (apn->next==0) apn->next= addpsA(zspan);
apn= apn->next;
- }
+ }
}
}
}
@@ -1029,7 +1032,7 @@ void zbufsinglewire(ZSpan *zspan, int obi, int zvlnr, const float ho1[4], const
/**
* Fill the z buffer, but invert z order, and add the face index to
- * the corresponing face buffer.
+ * the corresponding face buffer.
*
* This is one of the z buffer fill functions called in zbufclip() and
* zbufwireclip().
@@ -1624,7 +1627,7 @@ static void clippyra(float *labda, float *v1, float *v2, int *b2, int *b3, int a
else {
dw= clipcrop*(v2[3]-v1[3]);
v13= clipcrop*v1[3];
- }
+ }
/* according the original article by Liang&Barsky, for clipping of
* homogeneous coordinates with viewplane, the value of "0" is used instead of "-w" .
* This differs from the other clipping cases (like left or top) and I considered
@@ -1682,7 +1685,7 @@ static void makevertpyra(float *vez, float *labda, float **trias, float *v1, flo
adr[1]= v1[1]+l1*(v2[1]-v1[1]);
adr[2]= v1[2]+l1*(v2[2]-v1[2]);
adr[3]= v1[3]+l1*(v2[3]-v1[3]);
- }
+ }
else trias[*b1]= v1;
(*b1)++;
@@ -2022,7 +2025,7 @@ static void zmask_rect(int *rectz, int *rectp, int xs, int ys, int neg)
EXTEND_PIXEL(row1 + 2);
EXTEND_PIXEL(row2 + 2);
EXTEND_PIXEL(row3 + 2);
- }
+ }
if (tot) {
len++;
curz[0]= (int)(z/(float)tot);
@@ -2038,14 +2041,16 @@ static void zmask_rect(int *rectz, int *rectp, int xs, int ys, int neg)
MEM_freeN(temprectp);
- if (neg); /* z values for negative are already correct */
+ if (neg) {
+ /* z values for negative are already correct */
+ }
else {
/* clear not filled z values */
for (len= xs*ys -1; len>=0; len--) {
if (rectp[len]==0) {
rectz[len] = -0x7FFFFFFF;
rectp[len]= -1; /* env code */
- }
+ }
}
}
}
@@ -2730,7 +2735,7 @@ static void zbuf_fill_in_rgba(ZSpan *zspan, DrawBufPixel *col, float *v1, float
x= sn2-sn1;
while (x>=0) {
- if ( zverg < *rz) {
+ if (zverg < (double)*rz) {
*rz= zverg;
*rp= *col;
}
@@ -3231,7 +3236,7 @@ static void copyto_abufz(RenderPart *pa, int *arectz, int *rectmask, int sample)
*rza= 0x7FFFFFFF;
if (rectmask) *rma= 0x7FFFFFFF;
- if (*rd) {
+ if (*rd) {
/* when there's a sky pixstruct, fill in sky-Z, otherwise solid Z */
for (ps= (PixStr *)(*rd); ps; ps= ps->next) {
if (sample & ps->mask) {
@@ -3515,7 +3520,7 @@ static void add_transp_obindex(RenderLayer *rl, int offset, Object *ob)
RenderPass *rpass;
for (rpass= rl->passes.first; rpass; rpass= rpass->next) {
- if (rpass->passtype == SCE_PASS_INDEXOB||rpass->passtype == SCE_PASS_INDEXMA) {
+ if (rpass->passtype == SCE_PASS_INDEXOB) {
float *fp= rpass->rect + offset;
*fp= (float)ob->index;
break;
@@ -3523,6 +3528,19 @@ static void add_transp_obindex(RenderLayer *rl, int offset, Object *ob)
}
}
+static void add_transp_material_index(RenderLayer *rl, int offset, Material *mat)
+{
+ RenderPass *rpass;
+
+ for (rpass= rl->passes.first; rpass; rpass= rpass->next) {
+ if (rpass->passtype == SCE_PASS_INDEXMA) {
+ float *fp= rpass->rect + offset;
+ *fp= (float)mat->index;
+ break;
+ }
+ }
+}
+
/* ONLY OSA! merge all shaderesult samples to one */
/* target should have been cleared */
static void merge_transp_passes(RenderLayer *rl, ShadeResult *shr)
@@ -3874,7 +3892,7 @@ static int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassf
addAlphaUnderFloat(samp_shr->combined, shr->combined);
- samp_shr->z = minf(samp_shr->z, shr->z);
+ samp_shr->z = min_ff(samp_shr->z, shr->z);
if (addpassflag & SCE_PASS_VECTOR) {
copy_v4_v4(samp_shr->winspeed, shr->winspeed);
@@ -4127,10 +4145,12 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
}
}
if (addpassflag & SCE_PASS_INDEXMA) {
- ObjectRen *obr= R.objectinstance[zrow[totface-1].obi].obr;
- if (obr->ob) {
+ ObjectRen *obr = R.objectinstance[zrow[totface-1].obi].obr;
+ VlakRen *vr = obr->vlaknodes->vlak;
+ Material *mat = vr->mat;
+ if (mat) {
for (a= 0; a<totfullsample; a++)
- add_transp_obindex(rlpp[a], od, obr->ob);
+ add_transp_material_index(rlpp[a], od, mat);
}
}
@@ -4241,7 +4261,7 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
MEM_freeN(APixbufstrand);
if (sscache)
strand_shade_cache_free(sscache);
- freepsA(&apsmbase);
+ freepsA(&apsmbase);
if (R.r.mode & R_SHADOW)
ISB_free(pa);
diff --git a/source/blender/windowmanager/CMakeLists.txt b/source/blender/windowmanager/CMakeLists.txt
index e6782121b69..65a8945f82b 100644
--- a/source/blender/windowmanager/CMakeLists.txt
+++ b/source/blender/windowmanager/CMakeLists.txt
@@ -29,6 +29,7 @@ set(INC
../blenkernel
../blenlib
../blenloader
+ ../compositor
../editors/include
../editors/io
../gpu
@@ -36,7 +37,6 @@ set(INC
../makesdna
../makesrna
../nodes
- ../compositor
../render/extern/include
../../gameengine/BlenderRoutines
../../../intern/elbeem/extern
diff --git a/source/blender/windowmanager/WM_api.h b/source/blender/windowmanager/WM_api.h
index 1d509a87ffe..b9a4e720230 100644
--- a/source/blender/windowmanager/WM_api.h
+++ b/source/blender/windowmanager/WM_api.h
@@ -71,8 +71,18 @@ void WM_init_state_normal_set(void);
void WM_init (struct bContext *C, int argc, const char **argv);
void WM_exit_ext (struct bContext *C, const short do_python);
-void WM_exit (struct bContext *C);
-void WM_main (struct bContext *C);
+
+void WM_exit (struct bContext *C)
+#if defined(__GNUC__) || defined(__clang__)
+__attribute__((noreturn))
+#endif
+;
+
+void WM_main (struct bContext *C)
+#if defined(__GNUC__) || defined(__clang__)
+__attribute__((noreturn))
+#endif
+;
int WM_init_game (struct bContext *C);
void WM_init_splash (struct bContext *C);
@@ -104,8 +114,8 @@ void WM_cursor_set (struct wmWindow *win, int curs);
void WM_cursor_modal (struct wmWindow *win, int curs);
void WM_cursor_restore (struct wmWindow *win);
void WM_cursor_wait (int val);
-void WM_cursor_grab_enable(struct wmWindow *win, int wrap, int hide, int *bounds);
-void WM_cursor_grab_disable(struct wmWindow *win);
+void WM_cursor_grab_enable(struct wmWindow *win, int wrap, int hide, int bounds[4]);
+void WM_cursor_grab_disable(struct wmWindow *win, int mouse_ungrab_xy[2]);
void WM_cursor_time (struct wmWindow *win, int nr);
void *WM_paint_cursor_activate(struct wmWindowManager *wm,
@@ -145,6 +155,7 @@ struct wmEventHandler *WM_event_add_dropbox_handler(ListBase *handlers, ListBase
/* mouse */
void WM_event_add_mousemove(struct bContext *C);
+void WM_event_add_mousemove_window(struct wmWindow *window);
int WM_modal_tweak_exit(struct wmEvent *evt, int tweak_event);
/* notifiers */
@@ -203,6 +214,7 @@ int WM_operator_call_py(struct bContext *C, struct wmOperatorType *ot, short c
void WM_operator_properties_alloc(struct PointerRNA **ptr, struct IDProperty **properties, const char *opstring); /* used for keymap and macro items */
void WM_operator_properties_sanitize(struct PointerRNA *ptr, const short no_context); /* make props context sensitive or not */
+int WM_operator_properties_default(struct PointerRNA *ptr, const int do_update);
void WM_operator_properties_reset(struct wmOperator *op);
void WM_operator_properties_create(struct PointerRNA *ptr, const char *opstring);
void WM_operator_properties_create_ptr(struct PointerRNA *ptr, struct wmOperatorType *ot);
@@ -262,7 +274,7 @@ int WM_gesture_lines_cancel(struct bContext *C, struct wmOperator *op);
int WM_gesture_lasso_invoke(struct bContext *C, struct wmOperator *op, struct wmEvent *event);
int WM_gesture_lasso_modal(struct bContext *C, struct wmOperator *op, struct wmEvent *event);
int WM_gesture_lasso_cancel(struct bContext *C, struct wmOperator *op);
-int (*WM_gesture_lasso_path_to_array(struct bContext *C, struct wmOperator *op, int *mcords_tot))[2];
+const int (*WM_gesture_lasso_path_to_array(struct bContext *C, struct wmOperator *op, int *mcords_tot))[2];
int WM_gesture_straightline_invoke(struct bContext *C, struct wmOperator *op, struct wmEvent *event);
int WM_gesture_straightline_modal(struct bContext *C, struct wmOperator *op, struct wmEvent *event);
int WM_gesture_straightline_cancel(struct bContext *C, struct wmOperator *op);
@@ -346,8 +358,9 @@ void WM_jobs_callbacks(struct wmJob *,
void WM_jobs_start(struct wmWindowManager *wm, struct wmJob *);
void WM_jobs_stop(struct wmWindowManager *wm, void *owner, void *startjob);
void WM_jobs_kill(struct wmWindowManager *wm, void *owner, void (*)(void *, short int *, short int *, float *));
-void WM_jobs_stop_all(struct wmWindowManager *wm);
-
+void WM_jobs_kill_all(struct wmWindowManager *wm);
+ void WM_jobs_kill_all_except(struct wmWindowManager *wm, void *owner);
+
int WM_jobs_has_running(struct wmWindowManager *wm);
/* clipboard */
diff --git a/source/blender/windowmanager/WM_keymap.h b/source/blender/windowmanager/WM_keymap.h
index 5c88babfb47..43369154dbb 100644
--- a/source/blender/windowmanager/WM_keymap.h
+++ b/source/blender/windowmanager/WM_keymap.h
@@ -43,7 +43,7 @@ struct EnumPropertyItem;
wmKeyConfig *WM_keyconfig_new (struct wmWindowManager *wm, const char *idname);
wmKeyConfig *WM_keyconfig_new_user(struct wmWindowManager *wm, const char *idname);
-void WM_keyconfig_remove (struct wmWindowManager *wm, struct wmKeyConfig *keyconf);
+int WM_keyconfig_remove (struct wmWindowManager *wm, struct wmKeyConfig *keyconf);
void WM_keyconfig_free (struct wmKeyConfig *keyconf);
void WM_keyconfig_set_active(struct wmWindowManager *wm, const char *idname);
@@ -63,8 +63,8 @@ wmKeyMapItem *WM_keymap_add_item(struct wmKeyMap *keymap, const char *idname, in
wmKeyMapItem *WM_keymap_add_menu(struct wmKeyMap *keymap, const char *idname, int type,
int val, int modifier, int keymodifier);
-void WM_keymap_remove_item(struct wmKeyMap *keymap, struct wmKeyMapItem *kmi);
-char *WM_keymap_item_to_string(wmKeyMapItem *kmi, char *str, int len);
+int WM_keymap_remove_item(struct wmKeyMap *keymap, struct wmKeyMapItem *kmi);
+char *WM_keymap_item_to_string(wmKeyMapItem *kmi, char *str, int len);
wmKeyMap *WM_keymap_list_find(ListBase *lb, const char *idname, int spaceid, int regionid);
wmKeyMap *WM_keymap_find(struct wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid);
diff --git a/source/blender/windowmanager/WM_types.h b/source/blender/windowmanager/WM_types.h
index f9b22331f37..094df73bbd9 100644
--- a/source/blender/windowmanager/WM_types.h
+++ b/source/blender/windowmanager/WM_types.h
@@ -238,6 +238,7 @@ typedef struct wmNotifier {
#define NC_LOGIC (19<<24)
#define NC_MOVIECLIP (20<<24)
#define NC_MASK (21<<24)
+#define NC_GPENCIL (22<<24)
/* data type, 256 entries is enough, it can overlap */
#define NOTE_DATA 0x00FF0000
@@ -423,7 +424,7 @@ typedef struct wmEvent {
char ascii; /* from ghost, fallback if utf8 isn't set */
char pad;
- /* previous state */
+ /* previous state, used for double click and the 'click' */
short prevtype;
short prevval;
int prevx, prevy;
@@ -434,7 +435,8 @@ typedef struct wmEvent {
short shift, ctrl, alt, oskey; /* oskey is apple or windowskey, value denotes order of pressed */
short keymodifier; /* rawkey modifier */
- short pad1;
+ /* set in case a KM_PRESS went by unhandled */
+ short check_click;
/* keymap item, set by handler (weak?) */
const char *keymap_idname;
@@ -508,7 +510,11 @@ typedef struct wmOperatorType {
* parameters may be provided through operator properties. cannot use
* any interface code or input device state.
* - see defines below for return values */
- int (*exec)(struct bContext *, struct wmOperator *);
+ int (*exec)(struct bContext *, struct wmOperator *)
+#ifdef __GNUC__
+ __attribute__((warn_unused_result))
+#endif
+ ;
/* this callback executes on a running operator whenever as property
* is changed. It can correct its own properties or report errors for
@@ -520,13 +526,25 @@ typedef struct wmOperatorType {
* any further events are handled in modal. if the operation is
* canceled due to some external reason, cancel is called
* - see defines below for return values */
- int (*invoke)(struct bContext *, struct wmOperator *, struct wmEvent *);
+ int (*invoke)(struct bContext *, struct wmOperator *, struct wmEvent *)
+#ifdef __GNUC__
+ __attribute__((warn_unused_result))
+#endif
+ ;
int (*cancel)(struct bContext *, struct wmOperator *);
- int (*modal)(struct bContext *, struct wmOperator *, struct wmEvent *);
+ int (*modal)(struct bContext *, struct wmOperator *, struct wmEvent *)
+#ifdef __GNUC__
+ __attribute__((warn_unused_result))
+#endif
+ ;
/* verify if the operator can be executed in the current context, note
* that the operator might still fail to execute even if this return true */
- int (*poll)(struct bContext *);
+ int (*poll)(struct bContext *)
+#ifdef __GNUC__
+ __attribute__((warn_unused_result))
+#endif
+ ;
/* optional panel for redo and repeat, autogenerated if not set */
void (*ui)(struct bContext *, struct wmOperator *);
@@ -537,8 +555,8 @@ typedef struct wmOperatorType {
/* previous settings - for initializing on re-use */
struct IDProperty *last_properties;
- /* rna property to use for generic invoke functions.
- * menus, enum search... etc */
+ /* Default rna property to use for generic invoke functions.
+ * menus, enum search... etc. Example: Enum 'type' for a Delete menu */
PropertyRNA *prop;
/* struct wmOperatorTypeMacro */
@@ -550,7 +568,11 @@ typedef struct wmOperatorType {
/* only used for operators defined with python
* use to store pointers to python functions */
void *pyop_data;
- int (*pyop_poll)(struct bContext *, struct wmOperatorType *ot);
+ int (*pyop_poll)(struct bContext *, struct wmOperatorType *ot)
+#ifdef __GNUC__
+ __attribute__((warn_unused_result))
+#endif
+ ;
/* RNA integration */
ExtensionRNA ext;
diff --git a/source/blender/windowmanager/intern/wm.c b/source/blender/windowmanager/intern/wm.c
index a34d294461c..8fe387765ce 100644
--- a/source/blender/windowmanager/intern/wm.c
+++ b/source/blender/windowmanager/intern/wm.c
@@ -78,7 +78,7 @@ void WM_operator_free(wmOperator *op)
if (op->py_instance) {
/* do this first in case there are any __del__ functions or
* similar that use properties */
- BPY_DECREF(op->py_instance);
+ BPY_DECREF_RNA_INVALIDATE(op->py_instance);
}
#endif
diff --git a/source/blender/windowmanager/intern/wm_cursors.c b/source/blender/windowmanager/intern/wm_cursors.c
index 6fc6a57ade1..ebde6407a48 100644
--- a/source/blender/windowmanager/intern/wm_cursors.c
+++ b/source/blender/windowmanager/intern/wm_cursors.c
@@ -61,7 +61,7 @@ static GHOST_TStandardCursor convert_cursor(int curs)
case CURSOR_FACESEL: return GHOST_kStandardCursorRightArrow;
case CURSOR_WAIT: return GHOST_kStandardCursorWait;
case CURSOR_EDIT: return GHOST_kStandardCursorCrosshair;
- case CURSOR_HELP:
+ case CURSOR_HELP:
#ifdef __APPLE__
return GHOST_kStandardCursorLeftRight;
#else
@@ -179,7 +179,10 @@ void WM_cursor_wait(int val)
}
}
-void WM_cursor_grab_enable(wmWindow *win, int wrap, int hide, int *bounds)
+/**
+ * \param bounds can be NULL
+ */
+void WM_cursor_grab_enable(wmWindow *win, int wrap, int hide, int bounds[4])
{
/* Only grab cursor when not running debug.
* It helps not to get a stuck WM when hitting a breakpoint
@@ -193,20 +196,20 @@ void WM_cursor_grab_enable(wmWindow *win, int wrap, int hide, int *bounds)
const GHOST_TabletData *tabletdata = GHOST_GetTabletData(win->ghostwin);
/* Note: There is no tabletdata on Windows if no tablet device is connected. */
if (!tabletdata)
- GHOST_SetCursorGrab(win->ghostwin, mode, bounds);
+ GHOST_SetCursorGrab(win->ghostwin, mode, bounds, NULL);
else if (tabletdata->Active == GHOST_kTabletModeNone)
- GHOST_SetCursorGrab(win->ghostwin, mode, bounds);
+ GHOST_SetCursorGrab(win->ghostwin, mode, bounds, NULL);
win->grabcursor = mode;
}
}
}
-void WM_cursor_grab_disable(wmWindow *win)
+void WM_cursor_grab_disable(wmWindow *win, int mouse_ungrab_xy[2])
{
if ((G.debug & G_DEBUG) == 0) {
if (win && win->ghostwin) {
- GHOST_SetCursorGrab(win->ghostwin, GHOST_kGrabDisable, NULL);
+ GHOST_SetCursorGrab(win->ghostwin, GHOST_kGrabDisable, NULL, mouse_ungrab_xy);
win->grabcursor = GHOST_kGrabDisable;
}
}
@@ -314,7 +317,7 @@ void WM_cursor_time(wmWindow *win, int nr)
/* Because defining a cursor mixes declarations and executable code
* each cursor needs it's own scoping block or it would be split up
* over several hundred lines of code. To enforce/document this better
- * I define 2 pretty braindead macros so it's obvious what the extra "[]"
+ * I define 2 pretty brain-dead macros so it's obvious what the extra "[]"
* are for */
#define BEGIN_CURSOR_BLOCK {
@@ -557,7 +560,7 @@ BEGIN_CURSOR_BLOCK
BlenderCursor[BC_CROSSCURSOR] = &CrossCursor;
END_CURSOR_BLOCK
- /********************** EditCross Cursor ***********************/
+ /********************** EditCross Cursor ***********************/
BEGIN_CURSOR_BLOCK
static char editcross_sbm[] = {
0x0e, 0x00, 0x11, 0x00, 0x1d, 0x00, 0x19, 0x03,
@@ -772,7 +775,7 @@ BEGIN_CURSOR_BLOCK
END_CURSOR_BLOCK
- /********************** TextEdit Cursor ***********************/
+ /********************** TextEdit Cursor ***********************/
BEGIN_CURSOR_BLOCK
static char textedit_sbm[] = {
0xe0, 0x03, 0x10, 0x04, 0x60, 0x03, 0x40, 0x01,
@@ -805,7 +808,7 @@ BEGIN_CURSOR_BLOCK
END_CURSOR_BLOCK
- /********************** Paintbrush Cursor ***********************/
+ /********************** Paintbrush Cursor ***********************/
BEGIN_CURSOR_BLOCK
static char paintbrush_sbm[] = {
diff --git a/source/blender/windowmanager/intern/wm_dragdrop.c b/source/blender/windowmanager/intern/wm_dragdrop.c
index bbb2a54887e..0581000e07c 100644
--- a/source/blender/windowmanager/intern/wm_dragdrop.c
+++ b/source/blender/windowmanager/intern/wm_dragdrop.c
@@ -141,7 +141,7 @@ void wm_dropbox_free(void)
BLI_freelistN(&dm->dropboxes);
}
- BLI_freelistN(&dropboxes);
+ BLI_freelistN(&dropboxes);
}
/* *********************************** */
diff --git a/source/blender/windowmanager/intern/wm_event_system.c b/source/blender/windowmanager/intern/wm_event_system.c
index 17f17baba0e..fee94b95a6a 100644
--- a/source/blender/windowmanager/intern/wm_event_system.c
+++ b/source/blender/windowmanager/intern/wm_event_system.c
@@ -255,8 +255,12 @@ void wm_event_do_notifiers(bContext *C)
for (win = wm->windows.first; win; win = win->next) {
/* filter out notifiers */
- if (note->category == NC_SCREEN && note->reference && note->reference != win->screen) ;
- else if (note->category == NC_SCENE && note->reference && note->reference != win->screen->scene) ;
+ if (note->category == NC_SCREEN && note->reference && note->reference != win->screen) {
+ /* pass */
+ }
+ else if (note->category == NC_SCENE && note->reference && note->reference != win->screen->scene) {
+ /* pass */
+ }
else {
ScrArea *sa;
ARegion *ar;
@@ -335,6 +339,11 @@ static int wm_handler_ui_call(bContext *C, wmEventHandler *handler, wmEvent *eve
int is_wheel = ELEM(event->type, WHEELUPMOUSE, WHEELDOWNMOUSE);
int retval;
+ /* UI code doesn't handle return values - it just always returns break.
+ to make the DBL_CLICK conversion work, we just don't send this to UI */
+ if (event->val == KM_DBL_CLICK)
+ return WM_HANDLER_CONTINUE;
+
/* UI is quite aggressive with swallowing events, like scrollwheel */
/* I realize this is not extremely nice code... when UI gets keymaps it can be maybe smarter */
if (do_wheel_ui == FALSE) {
@@ -443,10 +452,10 @@ void WM_event_print(wmEvent *event)
RNA_enum_identifier(event_type_items, event->type, &type_id);
RNA_enum_identifier(event_value_items, event->val, &val_id);
- printf("wmEvent - type:%d/%s, val:%d/%s, "
- "shift:%d, ctrl:%d, alt:%d, oskey:%d, keymodifier:%d, "
- "mouse:(%d,%d), ascii:'%c', utf8:'%.*s', "
- "keymap_idname:%s, pointer:%p\n",
+ printf("wmEvent type:%d / %s, val:%d / %s, \n"
+ " shift:%d, ctrl:%d, alt:%d, oskey:%d, keymodifier:%d, \n"
+ " mouse:(%d,%d), ascii:'%c', utf8:'%.*s', "
+ " keymap_idname:%s, pointer:%p\n",
event->type, type_id, event->val, val_id,
event->shift, event->ctrl, event->alt, event->oskey, event->keymodifier,
event->x, event->y, event->ascii,
@@ -844,7 +853,7 @@ static int wm_operator_invoke(bContext *C, wmOperatorType *ot, wmEvent *event,
WM_operator_last_properties_init(op);
}
- if ((G.debug & G_DEBUG_EVENTS) && event && event->type != MOUSEMOVE) {
+ if ((G.debug & G_DEBUG_HANDLERS) && event && event->type != MOUSEMOVE) {
printf("%s: handle evt %d win %d op %s\n",
__func__, event ? event->type : 0, CTX_wm_screen(C)->subwinactive, ot->idname);
}
@@ -883,8 +892,9 @@ static int wm_operator_invoke(bContext *C, wmOperatorType *ot, wmEvent *event,
wm_operator_reports(C, op, retval, (reports != NULL));
}
- if (retval & OPERATOR_HANDLED)
- ; /* do nothing, wm_operator_exec() has been called somewhere */
+ if (retval & OPERATOR_HANDLED) {
+ /* do nothing, wm_operator_exec() has been called somewhere */
+ }
else if (retval & OPERATOR_FINISHED) {
if (!is_nested_call) { /* not called by py script */
WM_operator_last_properties_store(op);
@@ -1202,7 +1212,7 @@ void WM_event_remove_handlers(bContext *C, ListBase *handlers)
CTX_wm_region_set(C, region);
}
- WM_cursor_grab_disable(CTX_wm_window(C));
+ WM_cursor_grab_disable(CTX_wm_window(C), NULL);
WM_operator_free(handler->op);
}
else if (handler->ui_remove) {
@@ -1271,25 +1281,50 @@ int WM_userdef_event_map(int kmitype)
static void wm_eventemulation(wmEvent *event)
{
+ /* Store last mmb event value to make emulation work when modifier keys are released first. */
static int mmb_emulated = 0; /* this should be in a data structure somwhere */
/* middlemouse emulation */
if (U.flag & USER_TWOBUTTONMOUSE) {
- if (event->type == LEFTMOUSE && (event->alt || mmb_emulated == KM_PRESS)) {
- event->type = MIDDLEMOUSE;
- event->alt = 0;
- mmb_emulated = event->val;
+ if (event->type == LEFTMOUSE) {
+
+ if (event->val == KM_PRESS && event->alt) {
+ event->type = MIDDLEMOUSE;
+ event->alt = 0;
+ mmb_emulated = 1;
+ }
+ else if (event->val == KM_RELEASE) {
+ /* only send middle-mouse release if emulated */
+ if (mmb_emulated) {
+ event->type = MIDDLEMOUSE;
+ event->alt = 0;
+ }
+ mmb_emulated = 0;
+ }
}
+
}
#ifdef __APPLE__
+
/* rightmouse emulation */
if (U.flag & USER_TWOBUTTONMOUSE) {
- if (event->type == LEFTMOUSE && (event->oskey || mmb_emulated == KM_PRESS)) {
- event->type = RIGHTMOUSE;
- event->oskey = 0;
- mmb_emulated = event->val;
+ if (event->type == LEFTMOUSE) {
+
+ if (event->val == KM_PRESS && event->oskey) {
+ event->type = RIGHTMOUSE;
+ event->oskey = 0;
+ mmb_emulated = 1;
+ }
+ else if (event->val == KM_RELEASE) {
+ if (mmb_emulated) {
+ event->oskey = RIGHTMOUSE;
+ event->alt = 0;
+ }
+ mmb_emulated = 0;
+ }
}
+
}
#endif
@@ -1321,7 +1356,12 @@ static int wm_eventmatch(wmEvent *winevent, wmKeyMapItem *kmi)
/* the matching rules */
if (kmitype == KM_TEXTINPUT)
- if (ISTEXTINPUT(winevent->type) && (winevent->ascii || winevent->utf8_buf[0])) return 1;
+ if (winevent->val == KM_PRESS) { // prevent double clicks
+ /* NOT using ISTEXTINPUT anymore because (at least on Windows) some key codes above 255
+ could have printable ascii keys - BUG [#30479] */
+ if (ISKEYBOARD(winevent->type) && (winevent->ascii || winevent->utf8_buf[0])) return 1;
+ }
+
if (kmitype != KM_ANY)
if (winevent->type != kmitype) return 0;
@@ -1338,14 +1378,8 @@ static int wm_eventmatch(wmEvent *winevent, wmKeyMapItem *kmi)
if (kmi->oskey != KM_ANY)
if (winevent->oskey != kmi->oskey && !(winevent->oskey & kmi->oskey)) return 0;
- if (kmi->keymodifier)
- if (winevent->keymodifier != kmi->keymodifier) return 0;
+ if (winevent->keymodifier != kmi->keymodifier) return 0;
- /* key modifiers always check when event has it */
- /* otherwise regular keypresses with keymodifier still work */
- if (winevent->keymodifier)
- if (ISTEXTINPUT(winevent->type))
- if (winevent->keymodifier != kmi->keymodifier) return 0;
return 1;
}
@@ -1365,13 +1399,30 @@ static void wm_event_modalkeymap(const bContext *C, wmOperator *op, wmEvent *eve
for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
if (wm_eventmatch(event, kmi)) {
+ event->prevtype = event->type;
+ event->prevval = event->val;
event->type = EVT_MODAL_MAP;
event->val = kmi->propvalue;
+
+ break;
}
}
}
}
+/* bad hacking event system... better restore event type for checking of KM_CLICK for example */
+/* XXX modal maps could use different method (ton) */
+static void wm_event_modalmap_end(wmEvent *event)
+{
+ if (event->type == EVT_MODAL_MAP) {
+ event->type = event->prevtype;
+ event->prevtype = 0;
+ event->val = event->prevval;
+ event->prevval = 0;
+ }
+
+}
+
/* Warning: this function removes a modal handler, when finished */
static int wm_handler_operator_call(bContext *C, ListBase *handlers, wmEventHandler *handler,
wmEvent *event, PointerRNA *properties)
@@ -1398,7 +1449,8 @@ static int wm_handler_operator_call(bContext *C, ListBase *handlers, wmEventHand
retval = ot->modal(C, op, event);
OPERATOR_RETVAL_CHECK(retval);
-
+ wm_event_modalmap_end(event);
+
/* when this is _not_ the case the modal modifier may have loaded
* a new blend file (demo mode does this), so we have to assume
* the event, operator etc have all been freed. - campbell */
@@ -1432,7 +1484,7 @@ static int wm_handler_operator_call(bContext *C, ListBase *handlers, wmEventHand
/* remove modal handler, operator itself should have been canceled and freed */
if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
- WM_cursor_grab_disable(CTX_wm_window(C));
+ WM_cursor_grab_disable(CTX_wm_window(C), NULL);
BLI_remlink(handlers, handler);
wm_event_free_handler(handler);
@@ -1543,72 +1595,55 @@ static int wm_handler_fileselect_call(bContext *C, ListBase *handlers, wmEventHa
/* needed for uiPupMenuReports */
if (event->val == EVT_FILESELECT_EXEC) {
-#if 0 // use REDALERT now
+ int retval;
- /* a bit weak, might become arg for WM_event_fileselect? */
- /* XXX also extension code in image-save doesnt work for this yet */
- if (RNA_struct_find_property(handler->op->ptr, "check_existing") &&
- RNA_boolean_get(handler->op->ptr, "check_existing"))
- {
- char *path = RNA_string_get_alloc(handler->op->ptr, "filepath", NULL, 0);
- /* this gives ownership to pupmenu */
- uiPupMenuSaveOver(C, handler->op, (path) ? path : "");
- if (path)
- MEM_freeN(path);
- }
- else
-#endif
- {
- int retval;
-
- if (handler->op->type->flag & OPTYPE_UNDO)
- wm->op_undo_depth++;
-
- retval = handler->op->type->exec(C, handler->op);
+ if (handler->op->type->flag & OPTYPE_UNDO)
+ wm->op_undo_depth++;
- /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
- if (handler->op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
- wm->op_undo_depth--;
+ retval = handler->op->type->exec(C, handler->op);
+
+ /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
+ if (handler->op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
+ wm->op_undo_depth--;
- if (retval & OPERATOR_FINISHED)
- if (G.debug & G_DEBUG_WM)
- wm_operator_print(C, handler->op);
+ if (retval & OPERATOR_FINISHED)
+ if (G.debug & G_DEBUG_WM)
+ wm_operator_print(C, handler->op);
- /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
- if (CTX_wm_manager(C) == wm && wm->op_undo_depth == 0)
- if (handler->op->type->flag & OPTYPE_UNDO)
- ED_undo_push_op(C, handler->op);
+ /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
+ if (CTX_wm_manager(C) == wm && wm->op_undo_depth == 0)
+ if (handler->op->type->flag & OPTYPE_UNDO)
+ ED_undo_push_op(C, handler->op);
- if (handler->op->reports->list.first) {
+ if (handler->op->reports->list.first) {
- /* FIXME, temp setting window, this is really bad!
+ /* FIXME, temp setting window, this is really bad!
* only have because lib linking errors need to be seen by users :(
* it can be removed without breaking anything but then no linking errors - campbell */
- wmWindow *win_prev = CTX_wm_window(C);
- ScrArea *area_prev = CTX_wm_area(C);
- ARegion *ar_prev = CTX_wm_region(C);
+ wmWindow *win_prev = CTX_wm_window(C);
+ ScrArea *area_prev = CTX_wm_area(C);
+ ARegion *ar_prev = CTX_wm_region(C);
- if (win_prev == NULL)
- CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
+ if (win_prev == NULL)
+ CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
- handler->op->reports->printlevel = RPT_WARNING;
- uiPupMenuReports(C, handler->op->reports);
+ handler->op->reports->printlevel = RPT_WARNING;
+ uiPupMenuReports(C, handler->op->reports);
- /* XXX - copied from 'wm_operator_finished()' */
- /* add reports to the global list, otherwise they are not seen */
- BLI_movelisttolist(&CTX_wm_reports(C)->list, &handler->op->reports->list);
-
- CTX_wm_window_set(C, win_prev);
- CTX_wm_area_set(C, area_prev);
- CTX_wm_region_set(C, ar_prev);
- }
+ /* XXX - copied from 'wm_operator_finished()' */
+ /* add reports to the global list, otherwise they are not seen */
+ BLI_movelisttolist(&CTX_wm_reports(C)->list, &handler->op->reports->list);
- if (retval & OPERATOR_FINISHED) {
- WM_operator_last_properties_store(handler->op);
- }
+ CTX_wm_window_set(C, win_prev);
+ CTX_wm_area_set(C, area_prev);
+ CTX_wm_region_set(C, ar_prev);
+ }
- WM_operator_free(handler->op);
+ if (retval & OPERATOR_FINISHED) {
+ WM_operator_last_properties_store(handler->op);
}
+
+ WM_operator_free(handler->op);
}
else {
if (handler->op->type->cancel) {
@@ -1667,10 +1702,13 @@ static int wm_action_not_handled(int action)
return action == WM_HANDLER_CONTINUE || action == (WM_HANDLER_BREAK | WM_HANDLER_MODAL);
}
-static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
+static int wm_handlers_do_intern(bContext *C, wmEvent *event, ListBase *handlers)
{
#ifndef NDEBUG
- const int do_debug_handler = (G.debug & G_DEBUG_EVENTS);
+ const int do_debug_handler = (G.debug & G_DEBUG_HANDLERS)
+ /* comment this out to flood the console! (if you really want to test) */
+ && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)
+ ;
#endif
wmWindowManager *wm = CTX_wm_manager(C);
wmEventHandler *handler, *nexthandler;
@@ -1681,13 +1719,6 @@ static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
return action;
}
-#ifndef NDEBUG
- if (do_debug_handler) {
- printf("%s: handling event\n", __func__);
- WM_event_print(event);
- }
-#endif
-
/* modal handlers can get removed in this loop, we keep the loop this way
*
* note: check 'handlers->first' because in rare cases the handlers can be cleared
@@ -1743,11 +1774,10 @@ static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
action |= wm_handler_operator_call(C, handlers, handler, event, kmi->ptr);
if (action & WM_HANDLER_BREAK) {
/* not always_pass here, it denotes removed handler */
-#ifndef NDEBUG
- if (do_debug_handler) {
- printf("%s: handled! '%s'...", __func__, kmi->idname);
- }
-#endif
+
+ if (G.debug & (G_DEBUG_EVENTS | G_DEBUG_HANDLERS))
+ printf("%s: handled! '%s'\n", __func__, kmi->idname);
+
break;
}
else {
@@ -1839,49 +1869,66 @@ static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
}
}
- /* test for CLICK event */
- if (wm_action_not_handled(action) && event->val == KM_RELEASE) {
- wmWindow *win = CTX_wm_window(C);
+ if (action == (WM_HANDLER_BREAK | WM_HANDLER_MODAL))
+ wm_cursor_arrow_move(CTX_wm_window(C), event);
- if (win && win->eventstate->prevtype == event->type && win->eventstate->prevval == KM_PRESS) {
- /* test for double click first,
- * note1: this can be problematic because single click operators can get the
- * double click event but then with old mouse coords which is highly confusing,
- * so check for mouse moves too.
- * note2: the first click event will be handled but still used to create a
- * double click event if clicking again quickly.
- * If no double click events are found it will fallback to a single click.
- * So a double click event can result in 2 successive single click calls
- * if its not handled by the keymap - campbell */
- if ((ABS(event->x - win->eventstate->prevclickx)) <= 2 &&
- (ABS(event->y - win->eventstate->prevclicky)) <= 2 &&
- ((PIL_check_seconds_timer() - win->eventstate->prevclicktime) * 1000 < U.dbl_click_time))
- {
- event->val = KM_DBL_CLICK;
- /* removed this because in cases where we're this is used as a single click
- * event, this will give old coords,
- * since the distance is checked above, using new coords should be ok. */
- // event->x = win->eventstate->prevclickx;
- // event->y = win->eventstate->prevclicky;
- action |= wm_handlers_do(C, event, handlers);
- }
+ return action;
+}
+
+/* this calls handlers twice - to solve (double-)click events */
+static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
+{
+ int action = wm_handlers_do_intern(C, event, handlers);
+
+ /* fileread case */
+ if (CTX_wm_window(C) == NULL)
+ return action;
- if (wm_action_not_handled(action)) {
- event->val = KM_CLICK;
- action |= wm_handlers_do(C, event, handlers);
+ if (!ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) && !ISTIMER(event->type)) {
+
+ /* test for CLICK events */
+ if (wm_action_not_handled(action)) {
+ wmWindow *win = CTX_wm_window(C);
+
+ /* eventstate stores if previous event was a KM_PRESS, in case that
+ * wasn't handled, the KM_RELEASE will become a KM_CLICK */
+
+ if (win && event->val == KM_PRESS) {
+ win->eventstate->check_click = TRUE;
}
+
+ if (win && win->eventstate->prevtype == event->type) {
+
+ if (event->val == KM_RELEASE && win->eventstate->prevval == KM_PRESS && win->eventstate->check_click == TRUE) {
+ event->val = KM_CLICK;
+
+ if (G.debug & (G_DEBUG_HANDLERS)) {
+ printf("%s: handling CLICK\n", __func__);
+ }
+ action |= wm_handlers_do_intern(C, event, handlers);
- /* revert value if not handled */
- if (wm_action_not_handled(action)) {
- event->val = KM_RELEASE;
+ event->val = KM_RELEASE;
+ }
+ else if (event->val == KM_DBL_CLICK) {
+ event->val = KM_PRESS;
+ action |= wm_handlers_do_intern(C, event, handlers);
+
+ /* revert value if not handled */
+ if (wm_action_not_handled(action)) {
+ event->val = KM_DBL_CLICK;
+ }
+ }
}
}
+ else {
+ wmWindow *win = CTX_wm_window(C);
+
+ if (win)
+ win->eventstate->check_click = 0;
+ }
}
- if (action == (WM_HANDLER_BREAK | WM_HANDLER_MODAL))
- wm_cursor_arrow_move(CTX_wm_window(C), event);
-
return action;
}
@@ -2021,23 +2068,26 @@ void wm_event_do_handlers(bContext *C)
Scene *scene = win->screen->scene;
if (scene) {
- int playing = sound_scene_playing(win->screen->scene);
+ int is_playing_sound = sound_scene_playing(win->screen->scene);
- if (playing != -1) {
+ if (is_playing_sound != -1) {
+ int is_playing_screen;
CTX_wm_window_set(C, win);
CTX_wm_screen_set(C, win->screen);
CTX_data_scene_set(C, scene);
- if (((playing == 1) && (!ED_screen_animation_playing(wm))) ||
- ((playing == 0) && (ED_screen_animation_playing(wm))))
+ is_playing_screen = (ED_screen_animation_playing(wm) != NULL);
+
+ if (((is_playing_sound == 1) && (is_playing_screen == 0)) ||
+ ((is_playing_sound == 0) && (is_playing_screen == 1)))
{
ED_screen_animation_play(C, -1, 1);
}
- if (playing == 0) {
- float time = sound_sync_scene(scene);
+ if (is_playing_sound == 0) {
+ const float time = sound_sync_scene(scene);
if (finite(time)) {
- int ncfra = sound_sync_scene(scene) * (float)FPS + 0.5f;
+ int ncfra = time * (float)FPS + 0.5f;
if (ncfra != scene->r.cfra) {
scene->r.cfra = ncfra;
ED_update_for_newframe(CTX_data_main(C), scene, 1);
@@ -2056,10 +2106,13 @@ void wm_event_do_handlers(bContext *C)
while ( (event = win->queue.first) ) {
int action = WM_HANDLER_CONTINUE;
- if ((G.debug & G_DEBUG_EVENTS) && event && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
- printf("%s: pass on evt %d val %d\n", __func__, event->type, event->val);
+#ifdef DEBUG
+ if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS) && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
+ printf("\n%s: Handling event\n", __func__);
+ WM_event_print(event);
}
-
+#endif
+
wm_eventemulation(event);
CTX_wm_window_set(C, win);
@@ -2172,40 +2225,6 @@ void wm_event_do_handlers(bContext *C)
}
}
- /* store last event for this window */
- /* mousemove and timer events don't overwrite last type */
- if (!ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) && !ISTIMER(event->type)) {
- if (wm_action_not_handled(action)) {
- if (win->eventstate->prevtype == event->type) {
- /* set click time on first click (press -> release) */
- if (win->eventstate->prevval == KM_PRESS && event->val == KM_RELEASE) {
- win->eventstate->prevclicktime = PIL_check_seconds_timer();
- win->eventstate->prevclickx = event->x;
- win->eventstate->prevclicky = event->y;
- }
- }
- else {
- /* reset click time if event type not the same */
- win->eventstate->prevclicktime = 0;
- }
-
- win->eventstate->prevval = event->val;
- win->eventstate->prevtype = event->type;
- }
- else if (event->val == KM_CLICK) { /* keep click for double click later */
- win->eventstate->prevtype = event->type;
- win->eventstate->prevval = event->val;
- win->eventstate->prevclicktime = PIL_check_seconds_timer();
- win->eventstate->prevclickx = event->x;
- win->eventstate->prevclicky = event->y;
- }
- else { /* reset if not */
- win->eventstate->prevtype = -1;
- win->eventstate->prevval = 0;
- win->eventstate->prevclicktime = 0;
- }
- }
-
/* unlink and free here, blender-quit then frees all */
BLI_remlink(&win->queue, event);
wm_event_free(event);
@@ -2469,6 +2488,11 @@ void WM_event_add_mousemove(bContext *C)
window->addmousemove = 1;
}
+void WM_event_add_mousemove_window(wmWindow *window)
+{
+ window->addmousemove = 1;
+}
+
/* for modal callbacks, check configuration for how to interpret exit with tweaks */
int WM_modal_tweak_exit(wmEvent *evt, int tweak_event)
{
@@ -2609,7 +2633,7 @@ static void update_tablet_data(wmWindow *win, wmEvent *event)
event->custom = EVT_DATA_TABLET;
event->customdata = wmtab;
event->customdatafree = 1;
- }
+ }
}
/* adds customdata to event */
@@ -2732,8 +2756,6 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
update_tablet_data(win, &event);
wm_event_add(win, &event);
-
- //printf("sending MOUSEMOVE %d %d\n", event.x, event.y);
/* also add to other window if event is there, this makes overdraws disappear nicely */
/* it remaps mousecoord to other window in event */
@@ -2774,7 +2796,9 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
event.x = evt->x = cx;
event.y = evt->y = (win->sizey - 1) - cy;
}
-
+
+ event.val = 0;
+
/* Use prevx/prevy so we can calculate the delta later */
event.prevx = event.x - pd->deltaX;
event.prevy = event.y - (-pd->deltaY);
@@ -2788,7 +2812,8 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
case GHOST_kEventButtonUp:
{
GHOST_TEventButtonData *bd = customdata;
-
+
+ /* get value and type from ghost */
event.val = (type == GHOST_kEventButtonDown) ? KM_PRESS : KM_RELEASE;
if (bd->button == GHOST_kButtonMaskLeft)
@@ -2802,6 +2827,14 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
else
event.type = MIDDLEMOUSE;
+ /* copy previous state to prev event state (two old!) */
+ evt->prevval = evt->val;
+ evt->prevtype = evt->type;
+
+ /* copy to event state */
+ evt->val = event.val;
+ evt->type = event.type;
+
if (win->active == 0) {
int cx, cy;
@@ -2812,6 +2845,23 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
event.y = evt->y = cy;
}
+ /* double click test */
+ if (event.type == evt->prevtype && event.val == KM_PRESS) {
+ if ((ABS(event.x - evt->prevclickx)) <= 2 &&
+ (ABS(event.y - evt->prevclicky)) <= 2 &&
+ ((PIL_check_seconds_timer() - evt->prevclicktime) * 1000 < U.dbl_click_time))
+ {
+ if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS) )
+ printf("%s Send double click\n", __func__);
+ event.val = KM_DBL_CLICK;
+ }
+ }
+ if (event.val == KM_PRESS) {
+ evt->prevclicktime = PIL_check_seconds_timer();
+ evt->prevclickx = event.x;
+ evt->prevclicky = event.y;
+ }
+
/* add to other window if event is there (not to both!) */
owin = wm_event_cursor_other_windows(wm, win, &event);
if (owin) {
@@ -2842,6 +2892,14 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
memcpy(event.utf8_buf, kd->utf8_buf, sizeof(event.utf8_buf)); /* might be not null terminated*/
event.val = (type == GHOST_kEventKeyDown) ? KM_PRESS : KM_RELEASE;
+ /* copy previous state to prev event state (two old!) */
+ evt->prevval = evt->val;
+ evt->prevtype = evt->type;
+
+ /* copy to event state */
+ evt->val = event.val;
+ evt->type = event.type;
+
/* exclude arrow keys, esc, etc from text input */
if (type == GHOST_kEventKeyUp) {
event.ascii = '\0';
@@ -2867,28 +2925,28 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
}
}
- /* modifiers */
+ /* modifiers assign to eventstate, so next event gets the modifer (makes modifier key events work) */
/* assigning both first and second is strange - campbell */
switch (event.type) {
case LEFTSHIFTKEY: case RIGHTSHIFTKEY:
- event.shift = evt->shift = (event.val == KM_PRESS) ?
- ((evt->ctrl || evt->alt || evt->oskey) ? (KM_MOD_FIRST | KM_MOD_SECOND) : KM_MOD_FIRST) :
- FALSE;
+ evt->shift = (event.val == KM_PRESS) ?
+ ((evt->ctrl || evt->alt || evt->oskey) ? (KM_MOD_FIRST | KM_MOD_SECOND) : KM_MOD_FIRST) :
+ FALSE;
break;
case LEFTCTRLKEY: case RIGHTCTRLKEY:
- event.ctrl = evt->ctrl = (event.val == KM_PRESS) ?
- ((evt->shift || evt->alt || evt->oskey) ? (KM_MOD_FIRST | KM_MOD_SECOND) : KM_MOD_FIRST) :
- FALSE;
+ evt->ctrl = (event.val == KM_PRESS) ?
+ ((evt->shift || evt->alt || evt->oskey) ? (KM_MOD_FIRST | KM_MOD_SECOND) : KM_MOD_FIRST) :
+ FALSE;
break;
case LEFTALTKEY: case RIGHTALTKEY:
- event.alt = evt->alt = (event.val == KM_PRESS) ?
- ((evt->ctrl || evt->shift || evt->oskey) ? (KM_MOD_FIRST | KM_MOD_SECOND) : KM_MOD_FIRST) :
- FALSE;
+ evt->alt = (event.val == KM_PRESS) ?
+ ((evt->ctrl || evt->shift || evt->oskey) ? (KM_MOD_FIRST | KM_MOD_SECOND) : KM_MOD_FIRST) :
+ FALSE;
break;
case OSKEY:
- event.oskey = evt->oskey = (event.val == KM_PRESS) ?
- ((evt->ctrl || evt->alt || evt->shift) ? (KM_MOD_FIRST | KM_MOD_SECOND) : KM_MOD_FIRST) :
- FALSE;
+ evt->oskey = (event.val == KM_PRESS) ?
+ ((evt->ctrl || evt->alt || evt->shift) ? (KM_MOD_FIRST | KM_MOD_SECOND) : KM_MOD_FIRST) :
+ FALSE;
break;
default:
if (event.val == KM_PRESS && event.keymodifier == 0)
@@ -2898,12 +2956,24 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
break;
}
- /* this case happens on some systems that on holding a key pressed,
- * generate press events without release, we still want to keep the
- * modifier in win->eventstate, but for the press event of the same
- * key we don't want the key modifier */
+ /* double click test */
+ /* if previous event was same type, and previous was release, and now it presses... */
+ if (event.type == evt->prevtype && evt->prevval == KM_RELEASE && event.val == KM_PRESS) {
+ if ((ABS(event.x - evt->prevclickx)) <= 2 &&
+ (ABS(event.y - evt->prevclicky)) <= 2 &&
+ ((PIL_check_seconds_timer() - evt->prevclicktime) * 1000 < U.dbl_click_time))
+ {
+ if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS) )
+ printf("%s Send double click\n", __func__);
+ evt->val = event.val = KM_DBL_CLICK;
+ }
+ }
+
+ /* this case happens on holding a key pressed, it should not generate
+ * press events events with the same key as modifier */
if (event.keymodifier == event.type)
event.keymodifier = 0;
+
/* this case happened with an external numpad, it's not really clear
* why, but it's also impossible to map a key modifier to an unknwon
* key, so it shouldn't harm */
@@ -2911,9 +2981,16 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
event.keymodifier = 0;
/* if test_break set, it catches this. XXX Keep global for now? */
- if (event.type == ESCKEY)
+ if (event.type == ESCKEY && event.val == KM_PRESS)
G.is_break = TRUE;
+ /* double click test - only for press */
+ if (event.val == KM_PRESS) {
+ evt->prevclicktime = PIL_check_seconds_timer();
+ evt->prevclickx = event.x;
+ evt->prevclicky = event.y;
+ }
+
wm_event_add(win, &event);
break;
@@ -2938,6 +3015,8 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
event.type = TIMER;
event.custom = EVT_DATA_TIMER;
event.customdata = customdata;
+ event.val = 0;
+ event.keymodifier = 0;
wm_event_add(win, &event);
break;
@@ -2946,10 +3025,12 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
case GHOST_kEventNDOFMotion:
{
event.type = NDOF_MOTION;
+ event.val = 0;
attach_ndof_data(&event, customdata);
wm_event_add(win, &event);
- //printf("sending NDOF_MOTION, prev = %d %d\n", event.x, event.y);
+ if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS) )
+ printf("%s sending NDOF_MOTION, prev = %d %d\n", __func__, event.x, event.y);
break;
}
@@ -2991,7 +3072,4 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
}
- /* Handy when debugging checking events */
- /* WM_event_print(&event); */
-
}
diff --git a/source/blender/windowmanager/intern/wm_files.c b/source/blender/windowmanager/intern/wm_files.c
index eb6fabd03c6..6124b03778d 100644
--- a/source/blender/windowmanager/intern/wm_files.c
+++ b/source/blender/windowmanager/intern/wm_files.c
@@ -56,6 +56,7 @@
#include "BLI_blenlib.h"
#include "BLI_linklist.h"
#include "BLI_utildefines.h"
+#include "BLI_threads.h"
#include "BLI_callbacks.h"
#include "BLF_translation.h"
@@ -143,7 +144,7 @@ static void wm_window_match_init(bContext *C, ListBase *wmlist)
/* code copied from wm_init_exit.c */
for (wm = wmlist->first; wm; wm = wm->id.next) {
- WM_jobs_stop_all(wm);
+ WM_jobs_kill_all(wm);
for (win = wm->windows.first; win; win = win->next) {
@@ -189,9 +190,12 @@ static void wm_window_match_do(bContext *C, ListBase *oldwmlist)
/* cases 1 and 2 */
if (oldwmlist->first == NULL) {
- if (G.main->wm.first) ; /* nothing todo */
- else
+ if (G.main->wm.first) {
+ /* nothing todo */
+ }
+ else {
wm_add_default(C);
+ }
}
else {
/* cases 3 and 4 */
@@ -446,9 +450,8 @@ void WM_file_read(bContext *C, const char *filepath, ReportList *reports)
if (sce->r.engine[0] &&
BLI_findstring(&R_engines, sce->r.engine, offsetof(RenderEngineType, idname)) == NULL)
{
- BKE_reportf(reports, RPT_WARNING,
- "Engine not available: '%s' for scene: %s, "
- "an addon may need to be installed or enabled",
+ BKE_reportf(reports, RPT_ERROR, "Engine '%s' not available for scene '%s' "
+ "(an addon may need to be installed or enabled)",
sce->r.engine, sce->id.name + 2);
}
}
@@ -461,17 +464,17 @@ void WM_file_read(bContext *C, const char *filepath, ReportList *reports)
else if (retval == BKE_READ_EXOTIC_OK_OTHER)
BKE_write_undo(C, "Import file");
else if (retval == BKE_READ_EXOTIC_FAIL_OPEN) {
- BKE_reportf(reports, RPT_ERROR, IFACE_("Can't read file: \"%s\", %s."), filepath,
- errno ? strerror(errno) : IFACE_("Unable to open the file"));
+ BKE_reportf(reports, RPT_ERROR, "Cannot read file '%s': %s", filepath,
+ errno ? strerror(errno) : TIP_("unable to open the file"));
}
else if (retval == BKE_READ_EXOTIC_FAIL_FORMAT) {
- BKE_reportf(reports, RPT_ERROR, IFACE_("File format is not supported in file: \"%s\"."), filepath);
+ BKE_reportf(reports, RPT_ERROR, "File format is not supported in file '%s'", filepath);
}
else if (retval == BKE_READ_EXOTIC_FAIL_PATH) {
- BKE_reportf(reports, RPT_ERROR, IFACE_("File path invalid: \"%s\"."), filepath);
+ BKE_reportf(reports, RPT_ERROR, "File path '%s' invalid", filepath);
}
else {
- BKE_reportf(reports, RPT_ERROR, IFACE_("Unknown error loading: \"%s\"."), filepath);
+ BKE_reportf(reports, RPT_ERROR, "Unknown error loading '%s'", filepath);
BLI_assert(!"invalid 'retval'");
}
@@ -712,7 +715,7 @@ static ImBuf *blend_file_thumb(Scene *scene, bScreen *screen, int **thumb_pt)
IB_rect, FALSE, FALSE, err_out);
}
- if (ibuf) {
+ if (ibuf) {
float aspect = (scene->r.xsch * scene->r.xasp) / (scene->r.ysch * scene->r.yasp);
/* dirty oversampling */
@@ -787,14 +790,14 @@ int WM_file_write(bContext *C, const char *target, int fileflags, ReportList *re
/* send the OnSave event */
for (li = G.main->library.first; li; li = li->id.next) {
if (BLI_path_cmp(li->filepath, filepath) == 0) {
- BKE_reportf(reports, RPT_ERROR, "Can't overwrite used library '%.240s'", filepath);
+ BKE_reportf(reports, RPT_ERROR, "Cannot overwrite used library '%.240s'", filepath);
return -1;
}
}
/* blend file thumbnail */
/* save before exit_editmode, otherwise derivedmeshes for shared data corrupt #27765) */
- if (U.flag & USER_SAVE_PREVIEWS) {
+ if ((U.flag & USER_SAVE_PREVIEWS) && BLI_thread_is_main()) {
ibuf_thumb = blend_file_thumb(CTX_data_scene(C), CTX_wm_screen(C), &thumb);
}
diff --git a/source/blender/windowmanager/intern/wm_gesture.c b/source/blender/windowmanager/intern/wm_gesture.c
index 2928ba024e5..b3ffb80243a 100644
--- a/source/blender/windowmanager/intern/wm_gesture.c
+++ b/source/blender/windowmanager/intern/wm_gesture.c
@@ -130,8 +130,8 @@ int wm_gesture_evaluate(wmGesture *gesture)
{
if (gesture->type == WM_GESTURE_TWEAK) {
rcti *rect = gesture->customdata;
- int dx = BLI_RCT_SIZE_X(rect);
- int dy = BLI_RCT_SIZE_Y(rect);
+ int dx = BLI_rcti_size_x(rect);
+ int dy = BLI_rcti_size_y(rect);
if (ABS(dx) + ABS(dy) > U.tweak_threshold) {
int theta = (int)floor(4.0f * atan2f((float)dy, (float)dx) / (float)M_PI + 0.5f);
int val = EVT_GESTURE_W;
diff --git a/source/blender/windowmanager/intern/wm_init_exit.c b/source/blender/windowmanager/intern/wm_init_exit.c
index 908f7e27f0b..c9f0bbffc63 100644
--- a/source/blender/windowmanager/intern/wm_init_exit.c
+++ b/source/blender/windowmanager/intern/wm_init_exit.c
@@ -32,8 +32,8 @@
#include <stdio.h>
#include <string.h>
-#if WIN32
-#include <Windows.h>
+#ifdef WIN32
+# include <Windows.h>
#endif
#include "MEM_guardedalloc.h"
@@ -47,6 +47,10 @@
#include "DNA_userdef_types.h"
#include "DNA_windowmanager_types.h"
+#include "BLI_listbase.h"
+#include "BLI_string.h"
+#include "BLI_utildefines.h"
+
#include "BKE_blender.h"
#include "BKE_context.h"
#include "BKE_screen.h"
@@ -66,10 +70,6 @@
#include "BKE_material.h" /* clear_matcopybuf */
#include "BKE_tracking.h" /* free tracking clipboard */
-#include "BLI_listbase.h"
-#include "BLI_string.h"
-#include "BLI_utildefines.h"
-
#include "RE_engine.h"
#include "RE_pipeline.h" /* RE_ free stuff */
@@ -114,8 +114,6 @@
#include "BKE_sound.h"
#include "COM_compositor.h"
-#include "IMB_colormanagement.h"
-
static void wm_init_reports(bContext *C)
{
BKE_reports_init(CTX_wm_reports(C), RPT_STORE);
@@ -150,9 +148,6 @@ void WM_init(bContext *C, int argc, const char **argv)
BLF_init(11, U.dpi); /* Please update source/gamengine/GamePlayer/GPG_ghost.cpp if you change this */
BLF_lang_init();
- /* initialize color management stuff */
- IMB_colormanagement_init();
-
/* get the default database, plus a wm */
WM_homefile_read(C, NULL, G.factory_startup);
@@ -307,7 +302,7 @@ int WM_init_game(bContext *C)
else {
ReportTimerInfo *rti;
- BKE_report(&wm->reports, RPT_ERROR, "No valid 3D View found. Game auto start is not possible.");
+ BKE_report(&wm->reports, RPT_ERROR, "No valid 3D View found, game auto start is not possible");
/* After adding the report to the global list, reset the report timer. */
WM_event_remove_timer(wm, NULL, wm->reports.reporttimer);
@@ -340,7 +335,7 @@ extern void free_anim_copybuf(void);
extern void free_anim_drivers_copybuf(void);
extern void free_fmodifiers_copybuf(void);
-#if WIN32
+#ifdef WIN32
/* Read console events until there is a key event. Also returns on any error. */
static void wait_for_console_key(void)
{
@@ -371,15 +366,13 @@ void WM_exit_ext(bContext *C, const short do_python)
sound_exit();
- IMB_colormanagement_exit();
-
/* first wrap up running stuff, we assume only the active WM is running */
/* modal handlers are on window level freed, others too? */
/* note; same code copied in wm_files.c */
if (C && wm) {
wmWindow *win;
- WM_jobs_stop_all(wm);
+ WM_jobs_kill_all(wm);
for (win = wm->windows.first; win; win = win->next) {
@@ -430,6 +423,7 @@ void WM_exit_ext(bContext *C, const short do_python)
#ifdef WITH_INTERNATIONAL
BLF_free_unifont();
+ BLF_lang_free();
#endif
ANIM_keyingset_infos_exit();
diff --git a/source/blender/windowmanager/intern/wm_jobs.c b/source/blender/windowmanager/intern/wm_jobs.c
index e3d6b0f73e1..42d721327b6 100644
--- a/source/blender/windowmanager/intern/wm_jobs.c
+++ b/source/blender/windowmanager/intern/wm_jobs.c
@@ -360,7 +360,7 @@ void WM_jobs_start(wmWindowManager *wm, wmJob *wm_job)
}
}
-/* stop job, free data completely */
+/* stop job, end thread, free data completely */
static void wm_jobs_kill_job(wmWindowManager *wm, wmJob *wm_job)
{
if (wm_job->running) {
@@ -385,7 +385,8 @@ static void wm_jobs_kill_job(wmWindowManager *wm, wmJob *wm_job)
}
-void WM_jobs_stop_all(wmWindowManager *wm)
+/* wait until every job ended */
+void WM_jobs_kill_all(wmWindowManager *wm)
{
wmJob *wm_job;
@@ -394,6 +395,18 @@ void WM_jobs_stop_all(wmWindowManager *wm)
}
+/* wait until every job ended, except for one owner (used in undo to keep screen job alive) */
+void WM_jobs_kill_all_except(wmWindowManager *wm, void *owner)
+{
+ wmJob *wm_job;
+
+ for (wm_job = wm->jobs.first; wm_job; wm_job = wm_job->next) {
+ if (wm_job->owner != owner)
+ wm_jobs_kill_job(wm, wm_job);
+ }
+}
+
+
/* signal job(s) from this owner or callback to stop, timer is required to get handled */
void WM_jobs_stop(wmWindowManager *wm, void *owner, void *startjob)
{
@@ -466,7 +479,7 @@ void wm_jobs_timer(const bContext *C, wmWindowManager *wm, wmTimer *wt)
if (wm_job->flag & WM_JOB_PROGRESS)
WM_event_add_notifier(C, NC_WM | ND_JOB, NULL);
wm_job->do_update = FALSE;
- }
+ }
if (wm_job->ready) {
if (wm_job->endjob)
@@ -492,7 +505,11 @@ void wm_jobs_timer(const bContext *C, wmWindowManager *wm, wmTimer *wt)
WM_event_add_notifier(C, wm_job->endnote, NULL);
WM_event_add_notifier(C, NC_WM | ND_JOB, NULL);
-
+
+ /* so the info header updates on job end even if the mouse doesn't move.
+ * a rather annoying/obscure bug, see [#32537] (second reply) */
+ WM_event_add_mousemove_window(wm_job->win);
+
/* new job added for wm_job? */
if (wm_job->customdata) {
// printf("job restarted with new data %s\n", wm_job->name);
diff --git a/source/blender/windowmanager/intern/wm_keymap.c b/source/blender/windowmanager/intern/wm_keymap.c
index eb6da146a73..7aa2b403897 100644
--- a/source/blender/windowmanager/intern/wm_keymap.c
+++ b/source/blender/windowmanager/intern/wm_keymap.c
@@ -190,9 +190,9 @@ wmKeyConfig *WM_keyconfig_new_user(wmWindowManager *wm, const char *idname)
return keyconf;
}
-void WM_keyconfig_remove(wmWindowManager *wm, wmKeyConfig *keyconf)
+int WM_keyconfig_remove(wmWindowManager *wm, wmKeyConfig *keyconf)
{
- if (keyconf) {
+ if (BLI_findindex(&wm->keyconfigs, keyconf) != -1) {
if (strncmp(U.keyconfigstr, keyconf->idname, sizeof(U.keyconfigstr)) == 0) {
BLI_strncpy(U.keyconfigstr, wm->defaultconf->idname, sizeof(U.keyconfigstr));
WM_keyconfig_update_tag(NULL, NULL);
@@ -200,6 +200,11 @@ void WM_keyconfig_remove(wmWindowManager *wm, wmKeyConfig *keyconf)
BLI_remlink(&wm->keyconfigs, keyconf);
WM_keyconfig_free(keyconf);
+
+ return TRUE;
+ }
+ else {
+ return FALSE;
}
}
@@ -381,7 +386,7 @@ wmKeyMapItem *WM_keymap_add_menu(wmKeyMap *keymap, const char *idname, int type,
return kmi;
}
-void WM_keymap_remove_item(wmKeyMap *keymap, wmKeyMapItem *kmi)
+int WM_keymap_remove_item(wmKeyMap *keymap, wmKeyMapItem *kmi)
{
if (BLI_findindex(&keymap->items, kmi) != -1) {
if (kmi->ptr) {
@@ -391,6 +396,10 @@ void WM_keymap_remove_item(wmKeyMap *keymap, wmKeyMapItem *kmi)
BLI_freelinkN(&keymap->items, kmi);
WM_keyconfig_update_tag(keymap, kmi);
+ return TRUE;
+ }
+ else {
+ return FALSE;
}
}
@@ -816,7 +825,7 @@ char *WM_keymap_item_to_string(wmKeyMapItem *kmi, char *str, int len)
static wmKeyMapItem *wm_keymap_item_find_handlers(
const bContext *C, ListBase *handlers, const char *opname, int UNUSED(opcontext),
- IDProperty *properties, int compare_props, int hotkey, wmKeyMap **keymap_r)
+ IDProperty *properties, int is_strict, int hotkey, wmKeyMap **keymap_r)
{
wmWindowManager *wm = CTX_wm_manager(C);
wmEventHandler *handler;
@@ -834,9 +843,22 @@ static wmKeyMapItem *wm_keymap_item_find_handlers(
if (hotkey)
if (!ISHOTKEY(kmi->type))
continue;
-
- if (compare_props) {
- if (kmi->ptr && IDP_EqualsProperties(properties, kmi->ptr->data)) {
+
+ if (properties) {
+
+ /* example of debugging keymaps */
+#if 0
+ if (kmi->ptr) {
+ if (strcmp("MESH_OT_rip_move", opname) == 0) {
+ printf("OPERATOR\n");
+ IDP_spit(properties);
+ printf("KEYMAP\n");
+ IDP_spit(kmi->ptr->data);
+ }
+ }
+#endif
+
+ if (kmi->ptr && IDP_EqualsProperties_ex(properties, kmi->ptr->data, is_strict)) {
if (keymap_r) *keymap_r = keymap;
return kmi;
}
@@ -857,7 +879,7 @@ static wmKeyMapItem *wm_keymap_item_find_handlers(
static wmKeyMapItem *wm_keymap_item_find_props(
const bContext *C, const char *opname, int opcontext,
- IDProperty *properties, int compare_props, int hotkey, wmKeyMap **keymap_r)
+ IDProperty *properties, int is_strict, int hotkey, wmKeyMap **keymap_r)
{
wmWindow *win = CTX_wm_window(C);
ScrArea *sa = CTX_wm_area(C);
@@ -866,11 +888,10 @@ static wmKeyMapItem *wm_keymap_item_find_props(
/* look into multiple handler lists to find the item */
if (win)
- found = wm_keymap_item_find_handlers(C, &win->handlers, opname, opcontext, properties, compare_props, hotkey, keymap_r);
-
+ found = wm_keymap_item_find_handlers(C, &win->handlers, opname, opcontext, properties, is_strict, hotkey, keymap_r);
if (sa && found == NULL)
- found = wm_keymap_item_find_handlers(C, &sa->handlers, opname, opcontext, properties, compare_props, hotkey, keymap_r);
+ found = wm_keymap_item_find_handlers(C, &sa->handlers, opname, opcontext, properties, is_strict, hotkey, keymap_r);
if (found == NULL) {
if (ELEM(opcontext, WM_OP_EXEC_REGION_WIN, WM_OP_INVOKE_REGION_WIN)) {
@@ -879,7 +900,7 @@ static wmKeyMapItem *wm_keymap_item_find_props(
ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
if (ar)
- found = wm_keymap_item_find_handlers(C, &ar->handlers, opname, opcontext, properties, compare_props, hotkey, keymap_r);
+ found = wm_keymap_item_find_handlers(C, &ar->handlers, opname, opcontext, properties, is_strict, hotkey, keymap_r);
}
}
else if (ELEM(opcontext, WM_OP_EXEC_REGION_CHANNELS, WM_OP_INVOKE_REGION_CHANNELS)) {
@@ -887,32 +908,48 @@ static wmKeyMapItem *wm_keymap_item_find_props(
ar = BKE_area_find_region_type(sa, RGN_TYPE_CHANNELS);
if (ar)
- found = wm_keymap_item_find_handlers(C, &ar->handlers, opname, opcontext, properties, compare_props, hotkey, keymap_r);
+ found = wm_keymap_item_find_handlers(C, &ar->handlers, opname, opcontext, properties, is_strict, hotkey, keymap_r);
}
else if (ELEM(opcontext, WM_OP_EXEC_REGION_PREVIEW, WM_OP_INVOKE_REGION_PREVIEW)) {
if (!(ar && ar->regiontype == RGN_TYPE_PREVIEW))
ar = BKE_area_find_region_type(sa, RGN_TYPE_PREVIEW);
if (ar)
- found = wm_keymap_item_find_handlers(C, &ar->handlers, opname, opcontext, properties, compare_props, hotkey, keymap_r);
+ found = wm_keymap_item_find_handlers(C, &ar->handlers, opname, opcontext, properties, is_strict, hotkey, keymap_r);
}
else {
if (ar)
- found = wm_keymap_item_find_handlers(C, &ar->handlers, opname, opcontext, properties, compare_props, hotkey, keymap_r);
+ found = wm_keymap_item_find_handlers(C, &ar->handlers, opname, opcontext, properties, is_strict, hotkey, keymap_r);
}
}
-
+
return found;
}
static wmKeyMapItem *wm_keymap_item_find(
const bContext *C, const char *opname, int opcontext,
- IDProperty *properties, const short hotkey, const short sloppy, wmKeyMap **keymap_r)
+ IDProperty *properties, const short hotkey, const short UNUSED(sloppy), wmKeyMap **keymap_r)
{
wmKeyMapItem *found = wm_keymap_item_find_props(C, opname, opcontext, properties, 1, hotkey, keymap_r);
- if (!found && sloppy)
- found = wm_keymap_item_find_props(C, opname, opcontext, NULL, 0, hotkey, keymap_r);
+ if (!found && properties) {
+ wmOperatorType *ot = WM_operatortype_find(opname, TRUE);
+ if (ot) {
+ /* make a copy of the properties and set any unset props
+ * to their default values, so the ID property compare function succeeds */
+ PointerRNA opptr;
+ IDProperty *properties_default = IDP_CopyProperty(properties);
+
+ RNA_pointer_create(NULL, ot->srna, properties_default, &opptr);
+
+ if (WM_operator_properties_default(&opptr, TRUE)) {
+ found = wm_keymap_item_find_props(C, opname, opcontext, properties_default, 0, hotkey, keymap_r);
+ }
+
+ IDP_FreeProperty(properties_default);
+ MEM_freeN(properties_default);
+ }
+ }
return found;
}
diff --git a/source/blender/windowmanager/intern/wm_operators.c b/source/blender/windowmanager/intern/wm_operators.c
index 313fc0a819e..2ef33aa5964 100644
--- a/source/blender/windowmanager/intern/wm_operators.c
+++ b/source/blender/windowmanager/intern/wm_operators.c
@@ -79,6 +79,7 @@
#include "BIF_glutil.h" /* for paint cursor */
#include "BLF_api.h"
+#include "IMB_colormanagement.h"
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -618,6 +619,42 @@ void WM_operator_properties_sanitize(PointerRNA *ptr, const short no_context)
RNA_STRUCT_END;
}
+
+/** set all props to their default,
+ * \param do_update Only update un-initialized props.
+ *
+ * \note, theres nothing spesific to operators here.
+ * this could be made a general function.
+ */
+int WM_operator_properties_default(PointerRNA *ptr, const int do_update)
+{
+ int is_change = FALSE;
+ RNA_STRUCT_BEGIN(ptr, prop)
+ {
+ switch (RNA_property_type(prop)) {
+ case PROP_POINTER:
+ {
+ StructRNA *ptype = RNA_property_pointer_type(ptr, prop);
+ if (ptype != &RNA_Struct) {
+ PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
+ is_change |= WM_operator_properties_default(&opptr, do_update);
+ }
+ break;
+ }
+ default:
+ if ((do_update == FALSE) || (RNA_property_is_set(ptr, prop) == FALSE)) {
+ if (RNA_property_reset(ptr, prop, -1)) {
+ is_change = 1;
+ }
+ }
+ break;
+ }
+ }
+ RNA_STRUCT_END;
+
+ return is_change;
+}
+
/* remove all props without PROP_SKIP_SAVE */
void WM_operator_properties_reset(wmOperator *op)
{
@@ -673,6 +710,8 @@ int WM_menu_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
else {
pup = uiPupMenuBegin(C, RNA_struct_ui_name(op->type->srna), ICON_NONE);
layout = uiPupMenuLayout(pup);
+ /* set this so the default execution context is the same as submenus */
+ uiLayoutSetOperatorContext(layout, WM_OP_INVOKE_REGION_WIN);
uiItemsFullEnumO(layout, op->type->idname, RNA_property_identifier(prop), op->ptr->data, WM_OP_EXEC_REGION_WIN, 0);
uiPupMenuEnd(C, pup);
}
@@ -744,7 +783,7 @@ static uiBlock *wm_enum_search_menu(bContext *C, ARegion *ar, void *arg_op)
wmOperator *op = (wmOperator *)arg_op;
block = uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
- uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_RET_1 | UI_BLOCK_MOVEMOUSE_QUIT);
+ uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
#if 0 /* ok, this isn't so easy... */
uiDefBut(block, LABEL, 0, RNA_struct_ui_name(op->type->srna), 10, 10, 180, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
@@ -806,7 +845,7 @@ int WM_operator_filesel(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
{
if (RNA_struct_property_is_set(op->ptr, "filepath")) {
return WM_operator_call_notest(C, op); /* call exec direct */
- }
+ }
else {
WM_event_add_fileselect(C, op);
return OPERATOR_RUNNING_MODAL;
@@ -856,6 +895,8 @@ void WM_operator_properties_filesel(wmOperatorType *ot, int filter, short type,
RNA_def_collection_runtime(ot->srna, "files", &RNA_OperatorFileListElement, "Files", "");
if (action == FILE_SAVE) {
+ /* note, this is only used to check if we should highlight the filename area red when the
+ * filepath is an existing file. */
prop = RNA_def_boolean(ot->srna, "check_existing", 1, "Check Existing", "Check and warn on overwriting existing files");
RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}
@@ -992,7 +1033,7 @@ static uiBlock *wm_block_create_redo(bContext *C, ARegion *ar, void *arg_op)
block = uiBeginBlock(C, ar, __func__, UI_EMBOSS);
uiBlockClearFlag(block, UI_BLOCK_LOOP);
- uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_RET_1 | UI_BLOCK_MOVEMOUSE_QUIT);
+ uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
/* if register is not enabled, the operator gets freed on OPERATOR_FINISHED
* ui_apply_but_funcs_after calls ED_undo_operator_repeate_cb and crashes */
@@ -1070,7 +1111,7 @@ static uiBlock *wm_block_dialog_create(bContext *C, ARegion *ar, void *userData)
/* intentionally don't use 'UI_BLOCK_MOVEMOUSE_QUIT', some dialogs have many items
* where quitting by accident is very annoying */
- uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_RET_1);
+ uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN);
layout = uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, style);
@@ -1111,7 +1152,7 @@ static uiBlock *wm_operator_ui_create(bContext *C, ARegion *ar, void *userData)
block = uiBeginBlock(C, ar, __func__, UI_EMBOSS);
uiBlockClearFlag(block, UI_BLOCK_LOOP);
- uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_RET_1 | UI_BLOCK_MOVEMOUSE_QUIT);
+ uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
layout = uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, style);
@@ -1161,7 +1202,7 @@ int WM_operator_props_popup(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
if ((op->type->flag & OPTYPE_REGISTER) == 0) {
BKE_reportf(op->reports, RPT_ERROR,
- "Operator '%s' does not have register enabled, incorrect invoke function.", op->type->idname);
+ "Operator '%s' does not have register enabled, incorrect invoke function", op->type->idname);
return OPERATOR_CANCELLED;
}
@@ -1192,11 +1233,12 @@ int WM_operator_redo_popup(bContext *C, wmOperator *op)
{
/* CTX_wm_reports(C) because operator is on stack, not active in event system */
if ((op->type->flag & OPTYPE_REGISTER) == 0) {
- BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "Operator redo '%s' does not have register enabled, incorrect invoke function.", op->type->idname);
+ BKE_reportf(CTX_wm_reports(C), RPT_ERROR,
+ "Operator redo '%s' does not have register enabled, incorrect invoke function", op->type->idname);
return OPERATOR_CANCELLED;
}
if (op->type->poll && op->type->poll(C) == 0) {
- BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "Operator redo '%s': wrong context.", op->type->idname);
+ BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "Operator redo '%s': wrong context", op->type->idname);
return OPERATOR_CANCELLED;
}
@@ -1213,7 +1255,7 @@ static int wm_debug_menu_exec(bContext *C, wmOperator *op)
ED_screen_refresh(CTX_wm_manager(C), CTX_wm_window(C));
WM_event_add_notifier(C, NC_WINDOW, NULL);
- return OPERATOR_FINISHED;
+ return OPERATOR_FINISHED;
}
static int wm_debug_menu_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
@@ -1232,7 +1274,7 @@ static void WM_OT_debug_menu(wmOperatorType *ot)
ot->exec = wm_debug_menu_exec;
ot->poll = WM_operator_winactive;
- RNA_def_int(ot->srna, "debug_value", 0, -10000, 10000, "Debug Value", "", INT_MIN, INT_MAX);
+ RNA_def_int(ot->srna, "debug_value", 0, SHRT_MIN, SHRT_MAX, "Debug Value", "", -10000, 10000);
}
@@ -1315,10 +1357,14 @@ static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(ar
BLF_size(style->widgetlabel.uifont_id, style->widgetlabel.points, U.dpi);
ver_width = (int)BLF_width(style->widgetlabel.uifont_id, version_buf) + 5;
rev_width = (int)BLF_width(style->widgetlabel.uifont_id, revision_buf) + 5;
-#endif //WITH_BUILDINFO
+#endif /* WITH_BUILDINFO */
block = uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
- uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN);
+
+ /* note on UI_BLOCK_NO_WIN_CLIP, the window size is not always synchronized
+ * with the OS when the splash shows, window clipping in this case gives
+ * ugly results and clipping the splash isn't useful anyway, just disable it [#32938] */
+ uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_NO_WIN_CLIP);
but = uiDefBut(block, BUT_IMAGE, 0, "", 0, 10, 501, 282, ibuf, 0.0, 0.0, 0, 0, ""); /* button owns the imbuf now */
uiButSetFunc(but, wm_block_splash_close, block, NULL);
@@ -1327,7 +1373,7 @@ static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(ar
#ifdef WITH_BUILDINFO
uiDefBut(block, LABEL, 0, version_buf, 494 - ver_width, 282 - 24, ver_width, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
uiDefBut(block, LABEL, 0, revision_buf, 494 - rev_width, 282 - 36, rev_width, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
-#endif //WITH_BUILDINFO
+#endif /* WITH_BUILDINFO */
layout = uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 10, 2, 480, 110, style);
@@ -1457,7 +1503,7 @@ static uiBlock *wm_block_search_menu(bContext *C, ARegion *ar, void *UNUSED(arg_
uiBut *but;
block = uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
- uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_RET_1 | UI_BLOCK_MOVEMOUSE_QUIT);
+ uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 10, 9 * UI_UNIT_X, UI_UNIT_Y, 0, 0, "");
uiButSetSearchFunc(but, operator_search_cb, NULL, operator_call_cb, NULL);
@@ -1499,12 +1545,12 @@ static int wm_search_menu_poll(bContext *C)
else {
ScrArea *sa = CTX_wm_area(C);
if (sa) {
- if (sa->spacetype == SPACE_CONSOLE) return 0; // XXX - so we can use the shortcut in the console
- if (sa->spacetype == SPACE_TEXT) return 0; // XXX - so we can use the spacebar in the text editor
+ if (sa->spacetype == SPACE_CONSOLE) return 0; /* XXX - so we can use the shortcut in the console */
+ if (sa->spacetype == SPACE_TEXT) return 0; /* XXX - so we can use the spacebar in the text editor */
}
else {
Object *editob = CTX_data_edit_object(C);
- if (editob && editob->type == OB_FONT) return 0; // XXX - so we can use the spacebar for entering text
+ if (editob && editob->type == OB_FONT) return 0; /* XXX - so we can use the spacebar for entering text */
}
}
return 1;
@@ -1713,7 +1759,7 @@ static int wm_link_append_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(ev
{
if (RNA_struct_property_is_set(op->ptr, "filepath")) {
return WM_operator_call_notest(C, op);
- }
+ }
else {
/* XXX TODO solve where to get last linked library from */
if (G.lib[0] != '\0') {
@@ -1838,6 +1884,7 @@ static int wm_link_append_exec(bContext *C, wmOperator *op)
/* mark all library linked objects to be updated */
recalc_all_library_objects(bmain);
+ IMB_colormanagement_check_file_config(bmain);
/* append, rather than linking */
if ((flag & FILE_LINK) == 0) {
@@ -2108,7 +2155,6 @@ static void WM_OT_save_as_mainfile(wmOperatorType *ot)
static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
{
char name[FILE_MAX];
- int check_existing = 1;
int ret;
/* cancel if no active window */
@@ -2128,13 +2174,9 @@ static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(
untitled(name);
RNA_string_set(op->ptr, "filepath", name);
-
- if (RNA_struct_find_property(op->ptr, "check_existing"))
- if (RNA_boolean_get(op->ptr, "check_existing") == 0)
- check_existing = 0;
-
+
if (G.save_over) {
- if (check_existing && BLI_exists(name)) {
+ if (BLI_exists(name)) {
uiPupMenuSaveOver(C, op, name);
ret = OPERATOR_RUNNING_MODAL;
}
@@ -2181,7 +2223,7 @@ static int wm_exit_blender_op(bContext *C, wmOperator *op)
{
WM_operator_free(op);
- WM_exit(C);
+ WM_exit(C);
return OPERATOR_FINISHED;
}
@@ -2279,16 +2321,18 @@ static int border_apply_rect(wmOperator *op)
/* operator arguments and storage. */
- RNA_int_set(op->ptr, "xmin", MIN2(rect->xmin, rect->xmax));
- RNA_int_set(op->ptr, "ymin", MIN2(rect->ymin, rect->ymax));
- RNA_int_set(op->ptr, "xmax", MAX2(rect->xmin, rect->xmax));
- RNA_int_set(op->ptr, "ymax", MAX2(rect->ymin, rect->ymax));
+ RNA_int_set(op->ptr, "xmin", min_ii(rect->xmin, rect->xmax));
+ RNA_int_set(op->ptr, "ymin", min_ii(rect->ymin, rect->ymax));
+ RNA_int_set(op->ptr, "xmax", max_ii(rect->xmin, rect->xmax));
+ RNA_int_set(op->ptr, "ymax", max_ii(rect->ymin, rect->ymax));
return 1;
}
static int border_apply(bContext *C, wmOperator *op, int gesture_mode)
{
+ int retval;
+
if (!border_apply_rect(op))
return 0;
@@ -2296,7 +2340,9 @@ static int border_apply(bContext *C, wmOperator *op, int gesture_mode)
if (RNA_struct_find_property(op->ptr, "gesture_mode") )
RNA_int_set(op->ptr, "gesture_mode", gesture_mode);
- op->type->exec(C, op);
+ retval = op->type->exec(C, op);
+ OPERATOR_RETVAL_CHECK(retval);
+
return 1;
}
@@ -2422,8 +2468,11 @@ static void gesture_circle_apply(bContext *C, wmOperator *op)
RNA_int_set(op->ptr, "y", rect->ymin);
RNA_int_set(op->ptr, "radius", rect->xmax);
- if (op->type->exec)
- op->type->exec(C, op);
+ if (op->type->exec) {
+ int retval;
+ retval = op->type->exec(C, op);
+ OPERATOR_RETVAL_CHECK(retval);
+ }
#ifdef GESTURE_MEMORY
circle_select_size = rect->xmax;
#endif
@@ -2643,8 +2692,10 @@ static void gesture_lasso_apply(bContext *C, wmOperator *op)
wm_gesture_end(C, op);
- if (op->type->exec)
- op->type->exec(C, op);
+ if (op->type->exec) {
+ int retval = op->type->exec(C, op);
+ OPERATOR_RETVAL_CHECK(retval);
+ }
}
int WM_gesture_lasso_modal(bContext *C, wmOperator *op, wmEvent *event)
@@ -2727,7 +2778,7 @@ int WM_gesture_lines_cancel(bContext *C, wmOperator *op)
*
* caller must free.
*/
-int (*WM_gesture_lasso_path_to_array(bContext *UNUSED(C), wmOperator *op, int *mcords_tot))[2]
+const int (*WM_gesture_lasso_path_to_array(bContext *UNUSED(C), wmOperator *op, int *mcords_tot))[2]
{
PropertyRNA *prop = RNA_struct_find_property(op->ptr, "path");
int (*mcords)[2] = NULL;
@@ -2757,7 +2808,8 @@ int (*WM_gesture_lasso_path_to_array(bContext *UNUSED(C), wmOperator *op, int *m
*mcords_tot = 0;
}
- return mcords;
+ /* cast for 'const' */
+ return (const int (*)[2])mcords;
}
#if 0
@@ -2812,8 +2864,10 @@ static int straightline_apply(bContext *C, wmOperator *op)
RNA_int_set(op->ptr, "xend", rect->xmax);
RNA_int_set(op->ptr, "yend", rect->ymax);
- if (op->type->exec)
- op->type->exec(C, op);
+ if (op->type->exec) {
+ int retval = op->type->exec(C, op);
+ OPERATOR_RETVAL_CHECK(retval);
+ }
return 1;
}
@@ -3115,7 +3169,7 @@ static int radial_control_get_path(PointerRNA *ctx_ptr, wmOperator *op,
/* check flags */
if ((flags & RC_PROP_REQUIRE_BOOL) && (flags & RC_PROP_REQUIRE_FLOAT)) {
- BKE_reportf(op->reports, RPT_ERROR, "Property can't be both boolean and float");
+ BKE_report(op->reports, RPT_ERROR, "Property cannot be both boolean and float");
return 0;
}
@@ -3138,7 +3192,7 @@ static int radial_control_get_path(PointerRNA *ctx_ptr, wmOperator *op,
if (flags & RC_PROP_ALLOW_MISSING)
return 1;
else {
- BKE_reportf(op->reports, RPT_ERROR, "Couldn't resolve path %s", name);
+ BKE_reportf(op->reports, RPT_ERROR, "Could not resolve path '%s'", name);
return 0;
}
}
@@ -3151,8 +3205,7 @@ static int radial_control_get_path(PointerRNA *ctx_ptr, wmOperator *op,
((flags & RC_PROP_REQUIRE_FLOAT) && prop_type != PROP_FLOAT))
{
MEM_freeN(str);
- BKE_reportf(op->reports, RPT_ERROR,
- "Property from path %s is not a float", name);
+ BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' is not a float", name);
return 0;
}
}
@@ -3160,8 +3213,7 @@ static int radial_control_get_path(PointerRNA *ctx_ptr, wmOperator *op,
/* check property's array length */
if (*r_prop && (len = RNA_property_array_length(r_ptr, *r_prop)) != req_length) {
MEM_freeN(str);
- BKE_reportf(op->reports, RPT_ERROR,
- "Property from path %s has length %d instead of %d",
+ BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' has length %d instead of %d",
name, len, req_length);
return 0;
}
@@ -3229,8 +3281,7 @@ static int radial_control_get_properties(bContext *C, wmOperator *op)
else if (rc->image_id_ptr.data) {
/* extra check, pointer must be to an ID */
if (!RNA_struct_is_ID(rc->image_id_ptr.type)) {
- BKE_report(op->reports, RPT_ERROR,
- "Pointer from path image_id is not an ID");
+ BKE_report(op->reports, RPT_ERROR, "Pointer from path image_id is not an ID");
return 0;
}
}
@@ -3471,7 +3522,7 @@ static int redraw_timer_exec(bContext *C, wmOperator *op)
if (type == 0) {
if (ar)
ED_region_do_draw(C, ar);
- }
+ }
else if (type == 1) {
wmWindow *win = CTX_wm_window(C);
@@ -3844,7 +3895,7 @@ static void gesture_border_modal_keymap(wmKeyConfig *keyconf)
WM_modalkeymap_assign(keymap, "VIEW3D_OT_clip_border");
WM_modalkeymap_assign(keymap, "VIEW3D_OT_render_border");
WM_modalkeymap_assign(keymap, "VIEW3D_OT_select_border");
- WM_modalkeymap_assign(keymap, "VIEW3D_OT_zoom_border"); // XXX TODO: zoom border should perhaps map rightmouse to zoom out instead of in+cancel
+ WM_modalkeymap_assign(keymap, "VIEW3D_OT_zoom_border"); /* XXX TODO: zoom border should perhaps map rightmouse to zoom out instead of in+cancel */
}
/* zoom to border modal operators */
diff --git a/source/blender/windowmanager/intern/wm_playanim.c b/source/blender/windowmanager/intern/wm_playanim.c
index bff40faf1d1..96bbedfee1b 100644
--- a/source/blender/windowmanager/intern/wm_playanim.c
+++ b/source/blender/windowmanager/intern/wm_playanim.c
@@ -89,6 +89,8 @@ typedef struct PlayState {
short stopped;
short go;
+ int fstep;
+
/* current picture */
struct PlayAnimPict *picture;
@@ -213,7 +215,6 @@ typedef struct PlayAnimPict {
static struct ListBase picsbase = {NULL, NULL};
static int fromdisk = FALSE;
-static int fstep = 1;
static float zoomx = 1.0, zoomy = 1.0;
static double ptottime = 0.0, swaptime = 0.04;
@@ -229,7 +230,7 @@ static int pupdate_time(void)
return (ptottime < 0);
}
-static void playanim_toscreen(PlayAnimPict *picture, struct ImBuf *ibuf, int fontid)
+static void playanim_toscreen(PlayAnimPict *picture, struct ImBuf *ibuf, int fontid, int fstep)
{
if (ibuf == NULL) {
@@ -287,7 +288,7 @@ static void build_pict_list(char *first, int totframes, int fstep, int fontid)
int pic;
ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
if (ibuf) {
- playanim_toscreen(NULL, ibuf, fontid);
+ playanim_toscreen(NULL, ibuf, fontid, fstep);
IMB_freeImBuf(ibuf);
}
@@ -390,7 +391,7 @@ static void build_pict_list(char *first, int totframes, int fstep, int fontid)
ibuf = IMB_loadiffname(picture->name, picture->IB_flags, NULL);
}
if (ibuf) {
- playanim_toscreen(picture, ibuf, fontid);
+ playanim_toscreen(picture, ibuf, fontid, fstep);
IMB_freeImBuf(ibuf);
}
pupdate_time();
@@ -446,34 +447,34 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr ps_void)
if (val) ps->pingpong = !ps->pingpong;
break;
case GHOST_kKeyNumpad1:
- if (val) swaptime = fstep / 60.0;
+ if (val) swaptime = ps->fstep / 60.0;
break;
case GHOST_kKeyNumpad2:
- if (val) swaptime = fstep / 50.0;
+ if (val) swaptime = ps->fstep / 50.0;
break;
case GHOST_kKeyNumpad3:
- if (val) swaptime = fstep / 30.0;
+ if (val) swaptime = ps->fstep / 30.0;
break;
case GHOST_kKeyNumpad4:
if (g_WS.qual & WS_QUAL_SHIFT)
- swaptime = fstep / 24.0;
+ swaptime = ps->fstep / 24.0;
else
- swaptime = fstep / 25.0;
+ swaptime = ps->fstep / 25.0;
break;
case GHOST_kKeyNumpad5:
- if (val) swaptime = fstep / 20.0;
+ if (val) swaptime = ps->fstep / 20.0;
break;
case GHOST_kKeyNumpad6:
- if (val) swaptime = fstep / 15.0;
+ if (val) swaptime = ps->fstep / 15.0;
break;
case GHOST_kKeyNumpad7:
- if (val) swaptime = fstep / 12.0;
+ if (val) swaptime = ps->fstep / 12.0;
break;
case GHOST_kKeyNumpad8:
- if (val) swaptime = fstep / 10.0;
+ if (val) swaptime = ps->fstep / 10.0;
break;
case GHOST_kKeyNumpad9:
- if (val) swaptime = fstep / 6.0;
+ if (val) swaptime = ps->fstep / 6.0;
break;
case GHOST_kKeyLeftArrow:
if (val) {
@@ -531,10 +532,10 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr ps_void)
if (val) {
if (g_WS.qual & WS_QUAL_SHIFT) {
if (ps->curframe_ibuf)
- printf(" Name: %s | Speed: %.2f frames/s\n", ps->curframe_ibuf->name, fstep / swaptime);
+ printf(" Name: %s | Speed: %.2f frames/s\n", ps->curframe_ibuf->name, ps->fstep / swaptime);
}
else {
- swaptime = fstep / 5.0;
+ swaptime = ps->fstep / 5.0;
}
}
break;
@@ -589,8 +590,8 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr ps_void)
break;
case GHOST_kKeyNumpadPlus:
if (val == 0) break;
- zoomx += 2.0;
- zoomy += 2.0;
+ zoomx += 2.0f;
+ zoomy += 2.0f;
/* no break??? - is this intentional? - campbell XXX25 */
case GHOST_kKeyNumpadMinus:
{
@@ -598,8 +599,8 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr ps_void)
/* int ofsx, ofsy; */ /* UNUSED */
if (val == 0) break;
- if (zoomx > 1.0) zoomx -= 1.0;
- if (zoomy > 1.0) zoomy -= 1.0;
+ if (zoomx > 1.0f) zoomx -= 1.0f;
+ if (zoomy > 1.0f) zoomy -= 1.0f;
// playanim_window_get_position(&ofsx, &ofsy);
playanim_window_get_size(&sizex, &sizey);
/* ofsx += sizex / 2; */ /* UNUSED */
@@ -664,10 +665,10 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr ps_void)
zoomx = (float) sizex / ps->ibufx;
zoomy = (float) sizey / ps->ibufy;
- zoomx = floor(zoomx + 0.5);
- zoomy = floor(zoomy + 0.5);
- if (zoomx < 1.0) zoomx = 1.0;
- if (zoomy < 1.0) zoomy = 1.0;
+ zoomx = floor(zoomx + 0.5f);
+ zoomy = floor(zoomy + 0.5f);
+ if (zoomx < 1.0f) zoomx = 1.0f;
+ if (zoomy < 1.0f) zoomy = 1.0f;
sizex = zoomx * ps->ibufx;
sizey = zoomy * ps->ibufy;
@@ -675,7 +676,7 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr ps_void)
glPixelZoom(zoomx, zoomy);
glEnable(GL_DITHER);
ptottime = 0.0;
- playanim_toscreen(ps->picture, ps->curframe_ibuf, ps->fontid);
+ playanim_toscreen(ps->picture, ps->curframe_ibuf, ps->fontid, ps->fstep);
break;
}
@@ -713,14 +714,6 @@ static void playanim_window_open(const char *title, int posx, int posy, int size
inital_state,
GHOST_kDrawingContextTypeOpenGL,
FALSE /* no stereo */, FALSE);
-
- //if (ghostwin) {
- //if (win) {
- // GHOST_SetWindowUserData(ghostwin, win);
- //} else {
- // GHOST_DisposeWindow(g_WS.ghost_system, ghostwin);
- //}
- //}
}
@@ -755,6 +748,8 @@ void WM_main_playanim(int argc, const char **argv)
ps.picture = NULL;
/* resetmap = FALSE */
+ ps.fstep = 1;
+
ps.fontid = -1;
while (argc > 1) {
@@ -802,8 +797,8 @@ void WM_main_playanim(int argc, const char **argv)
argv++;
break;
case 'j':
- fstep = MIN2(MAXFRAME, MAX2(1, atoi(argv[2])));
- swaptime *= fstep;
+ ps.fstep = MIN2(MAXFRAME, MAX2(1, atoi(argv[2])));
+ swaptime *= ps.fstep;
argc--;
argv++;
break;
@@ -902,11 +897,11 @@ void WM_main_playanim(int argc, const char **argv)
efra = MAXFRAME;
}
- build_pict_list(filepath, (efra - sfra) + 1, fstep, ps.fontid);
+ build_pict_list(filepath, (efra - sfra) + 1, ps.fstep, ps.fontid);
for (i = 2; i < argc; i++) {
BLI_strncpy(filepath, argv[i], sizeof(filepath));
- build_pict_list(filepath, (efra - sfra) + 1, fstep, ps.fontid);
+ build_pict_list(filepath, (efra - sfra) + 1, ps.fstep, ps.fontid);
}
IMB_freeImBuf(ibuf);
@@ -978,7 +973,7 @@ void WM_main_playanim(int argc, const char **argv)
while (pupdate_time()) PIL_sleep_ms(1);
ptottime -= swaptime;
- playanim_toscreen(ps.picture, ibuf, ps.fontid);
+ playanim_toscreen(ps.picture, ibuf, ps.fontid, ps.fstep);
} /* else deleten */
else {
printf("error: can't play this image type\n");
diff --git a/source/blender/windowmanager/intern/wm_subwindow.c b/source/blender/windowmanager/intern/wm_subwindow.c
index adf54af240b..8533494ae96 100644
--- a/source/blender/windowmanager/intern/wm_subwindow.c
+++ b/source/blender/windowmanager/intern/wm_subwindow.c
@@ -116,8 +116,8 @@ void wm_subwindow_getsize(wmWindow *win, int swinid, int *x, int *y)
wmSubWindow *swin = swin_from_swinid(win, swinid);
if (swin) {
- *x = BLI_RCT_SIZE_X(&swin->winrct) + 1;
- *y = BLI_RCT_SIZE_Y(&swin->winrct) + 1;
+ *x = BLI_rcti_size_x(&swin->winrct) + 1;
+ *y = BLI_rcti_size_y(&swin->winrct) + 1;
}
}
@@ -163,10 +163,6 @@ int wm_subwindow_open(wmWindow *win, rcti *winrct)
win->curswin = swin = MEM_callocN(sizeof(wmSubWindow), "swinopen");
BLI_addtail(&win->subwindows, swin);
- if (G.debug & G_DEBUG_EVENTS) {
- printf("%s: swin %d added\n", __func__, freewinid);
- }
-
swin->swinid = freewinid;
swin->winrct = *winrct;
@@ -192,7 +188,7 @@ void wm_subwindow_close(wmWindow *win, int swinid)
wm_subwindow_free(swin);
BLI_remlink(&win->subwindows, swin);
MEM_freeN(swin);
- }
+ }
else {
printf("%s: Internal error, bad winid: %d\n", __func__, swinid);
}
@@ -256,13 +252,13 @@ void wmSubWindowScissorSet(wmWindow *win, int swinid, rcti *srct)
win->curswin = _curswin;
_curwindow = win;
- width = BLI_RCT_SIZE_X(&_curswin->winrct) + 1;
- height = BLI_RCT_SIZE_Y(&_curswin->winrct) + 1;
+ width = BLI_rcti_size_x(&_curswin->winrct) + 1;
+ height = BLI_rcti_size_y(&_curswin->winrct) + 1;
glViewport(_curswin->winrct.xmin, _curswin->winrct.ymin, width, height);
if (srct) {
- width = BLI_RCT_SIZE_X(srct) + 1;
- height = BLI_RCT_SIZE_Y(srct) + 1;
+ width = BLI_rcti_size_x(srct) + 1;
+ height = BLI_rcti_size_y(srct) + 1;
glScissor(srct->xmin, srct->ymin, width, height);
}
else
@@ -398,7 +394,7 @@ int WM_framebuffer_to_index(unsigned int col)
return col & 0xFFFFFF;
default: // 18 bits...
return ((col & 0xFC0000) >> 6) + ((col & 0xFC00) >> 4) + ((col & 0xFC) >> 2);
- }
+ }
}
diff --git a/source/blender/windowmanager/intern/wm_window.c b/source/blender/windowmanager/intern/wm_window.c
index 59c8235faf0..616567e8184 100644
--- a/source/blender/windowmanager/intern/wm_window.c
+++ b/source/blender/windowmanager/intern/wm_window.c
@@ -164,7 +164,7 @@ void wm_window_free(bContext *C, wmWindowManager *wm, wmWindow *win)
if (CTX_wm_window(C) == win)
CTX_wm_window_set(C, NULL);
- }
+ }
/* always set drawable and active to NULL,
* prevents non-drawable state of main windows (bugs #22967 and #25071, possibly #22477 too) */
@@ -300,11 +300,9 @@ void wm_window_close(bContext *C, wmWindowManager *wm, wmWindow *win)
void wm_window_title(wmWindowManager *wm, wmWindow *win)
{
- /* handle the 'temp' window, only set title when not set before */
if (win->screen && win->screen->temp) {
- char *title = GHOST_GetTitle(win->ghostwin);
- if (title == NULL || title[0] == 0)
- GHOST_SetTitle(win->ghostwin, "Blender");
+ /* nothing to do for 'temp' windows,
+ * because WM_window_open_temp always sets window title */
}
else {
@@ -416,6 +414,10 @@ void wm_window_add_ghostwindows(wmWindowManager *wm)
win->posy = wm_init_state.start_y;
win->sizex = wm_init_state.size_x;
win->sizey = wm_init_state.size_y;
+
+ /* we can't properly resize a maximized window */
+ win->windowstate = GHOST_kWindowStateNormal;
+
wm_init_state.override_flag &= ~WIN_OVERRIDE_GEOM;
}
@@ -458,8 +460,8 @@ wmWindow *WM_window_open(bContext *C, rcti *rect)
win->posx = rect->xmin;
win->posy = rect->ymin;
- win->sizex = BLI_RCT_SIZE_X(rect);
- win->sizey = BLI_RCT_SIZE_Y(rect);
+ win->sizex = BLI_rcti_size_x(rect);
+ win->sizey = BLI_rcti_size_y(rect);
win->drawmethod = -1;
win->drawdata = NULL;
@@ -494,8 +496,8 @@ void WM_window_open_temp(bContext *C, rcti *position, int type)
win->posy = position->ymin;
}
- win->sizex = BLI_RCT_SIZE_X(position);
- win->sizey = BLI_RCT_SIZE_Y(position);
+ win->sizex = BLI_rcti_size_x(position);
+ win->sizey = BLI_rcti_size_y(position);
if (win->ghostwin) {
wm_window_set_size(win, win->sizex, win->sizey);
@@ -650,7 +652,7 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr C_void_ptr
else if (!GHOST_ValidWindow(g_system, ghostwin)) {
/* XXX - should be checked, why are we getting an event here, and */
/* what is it? */
- puts("<!> event has invalid window");
+ puts("<!> event has invalid window");
return 1;
}
else {
@@ -933,7 +935,7 @@ static int wm_window_timer(const bContext *C)
wt->delta = time - wt->ltime;
wt->duration += wt->delta;
wt->ltime = time;
- wt->ntime = wt->stime + wt->timestep *ceil(wt->duration / wt->timestep);
+ wt->ntime = wt->stime + wt->timestep * ceil(wt->duration / wt->timestep);
if (wt->event_type == TIMERJOBS)
wm_jobs_timer(C, wm, wt);
@@ -943,6 +945,8 @@ static int wm_window_timer(const bContext *C)
wmEvent event = *(win->eventstate);
event.type = wt->event_type;
+ event.val = 0;
+ event.keymodifier = 0;
event.custom = EVT_DATA_TIMER;
event.customdata = wt;
wm_event_add(win, &event);
@@ -1003,7 +1007,7 @@ void wm_ghost_init(bContext *C)
g_system = GHOST_CreateSystem();
GHOST_AddEventConsumer(g_system, consumer);
- }
+ }
}
void wm_ghost_exit(void)
@@ -1078,7 +1082,7 @@ char *WM_clipboard_text_get(int selection)
return NULL;
/* always convert from \r\n to \n */
- newbuf = MEM_callocN(strlen(buf) + 1, "WM_clipboard_text_get");
+ newbuf = MEM_callocN(strlen(buf) + 1, __func__);
for (p = buf, p2 = newbuf; *p; p++) {
if (*p != '\r')
diff --git a/source/blender/windowmanager/wm_event_system.h b/source/blender/windowmanager/wm_event_system.h
index a33d37ac50e..2d0dd2ef911 100644
--- a/source/blender/windowmanager/wm_event_system.h
+++ b/source/blender/windowmanager/wm_event_system.h
@@ -32,10 +32,10 @@
#define __WM_EVENT_SYSTEM_H__
/* return value of handler-operator call */
-#define WM_HANDLER_CONTINUE 0
-#define WM_HANDLER_BREAK 1
-#define WM_HANDLER_HANDLED 2
-#define WM_HANDLER_MODAL 4 /* MODAL|BREAK means unhandled */
+#define WM_HANDLER_CONTINUE 0
+#define WM_HANDLER_BREAK 1
+#define WM_HANDLER_HANDLED 2
+#define WM_HANDLER_MODAL 4 /* MODAL|BREAK means unhandled */
struct ScrArea;
struct ARegion;
@@ -44,40 +44,40 @@ struct ARegion;
typedef struct wmEventHandler {
struct wmEventHandler *next, *prev;
-
- int type, flag; /* type default=0, rest is custom */
-
+
+ int type, flag; /* type default=0, rest is custom */
+
/* keymap handler */
- wmKeyMap *keymap; /* pointer to builtin/custom keymaps */
- rcti *bblocal, *bbwin; /* optional local and windowspace bb */
-
+ wmKeyMap *keymap; /* pointer to builtin/custom keymaps */
+ rcti *bblocal, *bbwin; /* optional local and windowspace bb */
+
/* modal operator handler */
- wmOperator *op; /* for derived/modal handlers */
- struct ScrArea *op_area; /* for derived/modal handlers */
- struct ARegion *op_region; /* for derived/modal handlers */
+ wmOperator *op; /* for derived/modal handlers */
+ struct ScrArea *op_area; /* for derived/modal handlers */
+ struct ARegion *op_region; /* for derived/modal handlers */
/* ui handler */
- wmUIHandlerFunc ui_handle; /* callback receiving events */
- wmUIHandlerRemoveFunc ui_remove; /* callback when handler is removed */
- void *ui_userdata; /* user data pointer */
- struct ScrArea *ui_area; /* for derived/modal handlers */
- struct ARegion *ui_region; /* for derived/modal handlers */
- struct ARegion *ui_menu; /* for derived/modal handlers */
-
+ wmUIHandlerFunc ui_handle; /* callback receiving events */
+ wmUIHandlerRemoveFunc ui_remove; /* callback when handler is removed */
+ void *ui_userdata; /* user data pointer */
+ struct ScrArea *ui_area; /* for derived/modal handlers */
+ struct ARegion *ui_region; /* for derived/modal handlers */
+ struct ARegion *ui_menu; /* for derived/modal handlers */
+
/* fileselect handler re-uses modal operator data */
- struct bScreen *filescreen; /* screen it started in, to validate exec */
-
+ struct bScreen *filescreen; /* screen it started in, to validate exec */
+
/* drop box handler */
ListBase *dropboxes;
-
+
} wmEventHandler;
/* handler flag */
/* after this handler all others are ignored */
-#define WM_HANDLER_BLOCKING 1
+#define WM_HANDLER_BLOCKING 1
/* handler tagged to be freed in wm_handlers_do() */
-#define WM_HANDLER_DO_FREE 2
+#define WM_HANDLER_DO_FREE 2
@@ -89,23 +89,23 @@ enum {
/* wm_event_system.c */
-void wm_event_free_all (wmWindow *win);
-void wm_event_free (wmEvent *event);
-void wm_event_free_handler (wmEventHandler *handler);
+void wm_event_free_all (wmWindow *win);
+void wm_event_free (wmEvent *event);
+void wm_event_free_handler (wmEventHandler *handler);
- /* goes over entire hierarchy: events -> window -> screen -> area -> region */
-void wm_event_do_handlers (bContext *C);
+ /* goes over entire hierarchy: events -> window -> screen -> area -> region */
+void wm_event_do_handlers (bContext *C);
-void wm_event_add_ghostevent (wmWindowManager *wm, wmWindow *win, int type, int time, void *customdata);
+void wm_event_add_ghostevent (wmWindowManager *wm, wmWindow *win, int type, int time, void *customdata);
-void wm_event_do_notifiers (bContext *C);
+void wm_event_do_notifiers (bContext *C);
/* wm_keymap.c */
/* wm_dropbox.c */
-void wm_dropbox_free(void);
-void wm_drags_check_ops(bContext *C, wmEvent *event);
-void wm_drags_draw(bContext *C, wmWindow *win, rcti *rect);
+void wm_dropbox_free(void);
+void wm_drags_check_ops(bContext *C, wmEvent *event);
+void wm_drags_draw(bContext *C, wmWindow *win, rcti *rect);
#endif /* __WM_EVENT_SYSTEM_H__ */
diff --git a/source/blender/windowmanager/wm_event_types.h b/source/blender/windowmanager/wm_event_types.h
index 95a8a7db635..ca0e9659a22 100644
--- a/source/blender/windowmanager/wm_event_types.h
+++ b/source/blender/windowmanager/wm_event_types.h
@@ -285,8 +285,9 @@ enum {
/* for event checks */
/* only used for KM_TEXTINPUT, so assume that we want all user-inputtable ascii codes included */
+ /* UNUSED - see wm_eventmatch - BUG [#30479]
#define ISTEXTINPUT(event) (event >= ' ' && event <= 255)
-
+ */
/* test whether the event is a key on the keyboard */
#define ISKEYBOARD(event) (event >= ' ' && event <= 320)
diff --git a/source/blenderplayer/CMakeLists.txt b/source/blenderplayer/CMakeLists.txt
index 04d4be05034..828b7f5066c 100644
--- a/source/blenderplayer/CMakeLists.txt
+++ b/source/blenderplayer/CMakeLists.txt
@@ -148,6 +148,7 @@ endif()
extern_recastnavigation
bf_intern_raskter
bf_intern_opencolorio
+ bf_intern_opennl
)
if(WITH_MOD_CLOTH_ELTOPO)
@@ -169,10 +170,6 @@ endif()
list(APPEND BLENDER_SORTED_LIBS extern_colamd)
- if(WITH_MOD_DECIMATE)
- list(APPEND BLENDER_SORTED_LIBS bf_intern_decimate)
- endif()
-
if(WITH_MOD_BOOLEAN)
list(APPEND BLENDER_SORTED_LIBS bf_intern_bsp)
list(APPEND BLENDER_SORTED_LIBS bf_intern_moto)
diff --git a/source/blenderplayer/bad_level_call_stubs/stubs.c b/source/blenderplayer/bad_level_call_stubs/stubs.c
index c6383b471f7..238f3468a41 100644
--- a/source/blenderplayer/bad_level_call_stubs/stubs.c
+++ b/source/blenderplayer/bad_level_call_stubs/stubs.c
@@ -60,7 +60,6 @@ struct Image;
struct ImageUser;
struct KeyingSet;
struct KeyingSetInfo;
-struct LOD_Decimation_Info;
struct MCol;
struct MTex;
struct Main;
@@ -76,6 +75,7 @@ struct Nurb;
struct Object;
struct PBVHNode;
struct PyObject;
+struct Quadric;
struct Render;
struct RenderEngine;
struct RenderEngineType;
@@ -134,6 +134,13 @@ int BLI_smallhash_count(struct SmallHash *hash) { return 0; }
void *BLI_smallhash_iternext(struct SmallHashIter *iter, uintptr_t *key) { return NULL; }
void *BLI_smallhash_iternew(struct SmallHash *hash, struct SmallHashIter *iter, uintptr_t *key) { return NULL; }
+void BLI_quadric_from_v3_dist(struct Quadric *q, const float v[3], const float offset) {}
+void BLI_quadric_add_qu_qu(struct Quadric *a, const struct Quadric *b) {}
+void BLI_quadric_add_qu_ququ(struct Quadric *r, const struct Quadric *a, const struct Quadric *b) {}
+void BLI_quadric_mul(struct Quadric *a, const float scalar) {}
+float BLI_quadric_evaluate(const struct Quadric *q, const float v[3]) {return 0.0f;}
+int BLI_quadric_optimize(const struct Quadric *q, float v[3]) {return 0;}
+
float *RE_RenderLayerGetPass(struct RenderLayer *rl, int passtype) {return (float *) NULL;}
float RE_filter_value(int type, float x) {return 0.0f;}
struct RenderLayer *RE_GetRenderLayer(struct RenderResult *rr, const char *name) {return (struct RenderLayer *)NULL;}
@@ -191,7 +198,7 @@ struct MenuType *WM_menutype_find(const char *idname, int quiet) {return (struct
void WM_operator_stack_clear(struct bContext *C) {}
void WM_autosave_init(struct bContext *C) {}
-void WM_jobs_stop_all(struct wmWindowManager *wm) {}
+void WM_jobs_kill_all_except(struct wmWindowManager *wm) {}
char *WM_clipboard_text_get(int selection) {return (char*)0;}
void WM_clipboard_text_set(char *buf, int selection) {}
@@ -297,6 +304,7 @@ struct BGpic *ED_view3D_background_image_new(struct View3D *v3d) {return (struct
void ED_view3D_background_image_remove(struct View3D *v3d, struct BGpic *bgpic) {}
void ED_view3D_background_image_clear(struct View3D *v3d) {}
void ED_view3d_update_viewmat(struct Scene *scene, struct View3D *v3d, struct ARegion *ar, float viewmat[][4], float winmat[][4]) {}
+float ED_view3d_grid_scale(struct Scene *scene, struct View3D *v3d, const char **grid_unit) {return 0.0f;}
void view3d_apply_mat4(float mat[][4], float *ofs, float *quat, float *dist) {}
int text_file_modified(struct Text *text) {return 0;}
void ED_node_shader_default(struct Material *ma) {}
diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt
index 3356091b97f..c06669c3ac2 100644
--- a/source/creator/CMakeLists.txt
+++ b/source/creator/CMakeLists.txt
@@ -636,7 +636,7 @@ elseif(WIN32)
if(WITH_OPENIMAGEIO)
if(NOT MINGW)
- set_lib_path(OIIOBIN "openimageio")
+ set(OIIOBIN ${LIBDIR}/openimageio)
install(
FILES
${OIIOBIN}/bin/OpenImageIO.dll
@@ -646,13 +646,19 @@ elseif(WIN32)
endif()
if(WITH_OPENCOLORIO)
+ set(OCIOBIN ${LIBDIR}/opencolorio/bin)
if(NOT MINGW)
- set_lib_path(OCIOBIN "opencolorio/bin")
install(
FILES
${OCIOBIN}/OpenColorIO.dll
DESTINATION ${TARGETDIR}
)
+ else()
+ install(
+ FILES
+ ${OCIOBIN}/libOpenColorIO.dll
+ DESTINATION ${TARGETDIR}
+ )
endif()
endif()
@@ -730,7 +736,7 @@ elseif(APPLE)
)
endif()
-
+
# install blenderplayer bundle - copy of blender.app above. re-using macros et al
# note we are using OSX Bundle as base and copying Blender dummy bundle on top of it
if(WITH_GAMEENGINE AND WITH_PLAYER)
@@ -772,6 +778,7 @@ elseif(APPLE)
endif()
endif()
+
endif()
# -----------------------------------------------------------------------------
@@ -883,7 +890,6 @@ endif()
bf_imbuf_dds
bf_collada
bf_intern_bsp
- bf_intern_decimate
bf_intern_elbeem
bf_intern_memutil
bf_intern_guardedalloc
diff --git a/source/creator/creator.c b/source/creator/creator.c
index ab9541cf299..ca3deaf70a4 100644
--- a/source/creator/creator.c
+++ b/source/creator/creator.c
@@ -1128,6 +1128,7 @@ static void setupArguments(bContext *C, bArgs *ba, SYS_SystemHandle *syshandle)
#endif
BLI_argsAdd(ba, 1, NULL, "--debug-python", "\n\tEnable debug messages for python", debug_mode_generic, (void *)G_DEBUG_PYTHON);
BLI_argsAdd(ba, 1, NULL, "--debug-events", "\n\tEnable debug messages for the event system", debug_mode_generic, (void *)G_DEBUG_EVENTS);
+ BLI_argsAdd(ba, 1, NULL, "--debug-handlers", "\n\tEnable debug messages for event handling", debug_mode_generic, (void *)G_DEBUG_HANDLERS);
BLI_argsAdd(ba, 1, NULL, "--debug-wm", "\n\tEnable debug messages for the window manager", debug_mode_generic, (void *)G_DEBUG_WM);
BLI_argsAdd(ba, 1, NULL, "--debug-all", "\n\tEnable all debug messages (excludes libmv)", debug_mode_generic, (void *)G_DEBUG_ALL);
diff --git a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp b/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
index 3a06fe979e1..6807f531f0a 100644
--- a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
+++ b/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
@@ -35,9 +35,9 @@
#include <stdlib.h>
#include <stdio.h>
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// don't show stl-warnings
-#pragma warning (disable:4786)
+#ifdef _MSC_VER
+ /* don't show stl-warnings */
+# pragma warning (disable:4786)
#endif
#include "GL/glew.h"
@@ -69,37 +69,33 @@
#include "Value.h"
-
-#ifdef __cplusplus
extern "C" {
-#endif
- /***/
-#include "DNA_view3d_types.h"
-#include "DNA_screen_types.h"
-#include "DNA_userdef_types.h"
-#include "DNA_windowmanager_types.h"
-#include "BKE_global.h"
-#include "BKE_report.h"
-
-#include "MEM_guardedalloc.h"
-
-/* #include "BKE_screen.h" */ /* cant include this because of 'new' function name */
-extern float BKE_screen_view3d_zoom_to_fac(float camzoom);
-
-#include "BKE_main.h"
-#include "BLI_blenlib.h"
-#include "BLO_readfile.h"
-#include "DNA_scene_types.h"
-#include "BKE_ipo.h"
- /***/
-
-#include "BKE_context.h"
-#include "../../blender/windowmanager/WM_types.h"
-#include "../../blender/windowmanager/wm_window.h"
-#include "../../blender/windowmanager/wm_event_system.h"
-#ifdef __cplusplus
+ #include "DNA_view3d_types.h"
+ #include "DNA_screen_types.h"
+ #include "DNA_userdef_types.h"
+ #include "DNA_scene_types.h"
+ #include "DNA_windowmanager_types.h"
+
+ #include "BKE_global.h"
+ #include "BKE_report.h"
+ #include "BKE_ipo.h"
+ #include "BKE_main.h"
+ #include "BKE_context.h"
+
+ /* avoid c++ conflict with 'new' */
+ #define new _new
+ #include "BKE_screen.h"
+ #undef new
+
+ #include "MEM_guardedalloc.h"
+
+ #include "BLI_blenlib.h"
+ #include "BLO_readfile.h"
+
+ #include "../../blender/windowmanager/WM_types.h"
+ #include "../../blender/windowmanager/wm_window.h"
+ #include "../../blender/windowmanager/wm_event_system.h"
}
-#endif
#ifdef WITH_AUDASPACE
# include "AUD_C-API.h"
@@ -125,8 +121,8 @@ static BlendFileData *load_game_data(char *filename)
return bfd;
}
-int BL_KetsjiNextFrame(KX_KetsjiEngine *ketsjiengine, bContext *C, wmWindow *win, Scene *scene, ARegion *ar,
- KX_BlenderKeyboardDevice* keyboarddevice, KX_BlenderMouseDevice* mousedevice, int draw_letterbox)
+static int BL_KetsjiNextFrame(KX_KetsjiEngine *ketsjiengine, bContext *C, wmWindow *win, Scene *scene, ARegion *ar,
+ KX_BlenderKeyboardDevice* keyboarddevice, KX_BlenderMouseDevice* mousedevice, int draw_letterbox)
{
int exitrequested;
@@ -143,7 +139,7 @@ int BL_KetsjiNextFrame(KX_KetsjiEngine *ketsjiengine, bContext *C, wmWindow *win
// itself is unaware of the extra space, so we clear the whole region for it.
glClearColor(scene->gm.framing.col[0], scene->gm.framing.col[1], scene->gm.framing.col[2], 1.0f);
glViewport(ar->winrct.xmin, ar->winrct.ymin,
- BLI_RCT_SIZE_X(&ar->winrct), BLI_RCT_SIZE_Y(&ar->winrct));
+ BLI_rcti_size_x(&ar->winrct), BLI_rcti_size_y(&ar->winrct));
glClear(GL_COLOR_BUFFER_BIT);
}
@@ -198,7 +194,7 @@ struct BL_KetsjiNextFrameState {
int draw_letterbox;
} ketsjinextframestate;
-int BL_KetsjiPyNextFrame(void *state0)
+static int BL_KetsjiPyNextFrame(void *state0)
{
BL_KetsjiNextFrameState *state = (BL_KetsjiNextFrameState *) state0;
return BL_KetsjiNextFrame(
@@ -552,7 +548,7 @@ extern "C" void StartKetsjiShell(struct bContext *C, struct ARegion *ar, rcti *c
ketsjinextframestate.draw_letterbox = draw_letterbox;
pynextframestate.state = &ketsjinextframestate;
- pynextframestate.func = &BL_KetsjiPyNextFrame;
+ pynextframestate.func = &BL_KetsjiPyNextFrame;
printf("Yielding control to Python script '%s'...\n", python_main);
PyRun_SimpleString(python_code);
printf("Exit Python script '%s'\n", python_main);
@@ -590,7 +586,7 @@ extern "C" void StartKetsjiShell(struct bContext *C, struct ARegion *ar, rcti *c
const Py_ssize_t numitems= PyList_GET_SIZE(gameLogic_keys_new);
Py_ssize_t listIndex;
for (listIndex=0; listIndex < numitems; listIndex++) {
- PyObject* item = PyList_GET_ITEM(gameLogic_keys_new, listIndex);
+ PyObject *item = PyList_GET_ITEM(gameLogic_keys_new, listIndex);
if (!PySequence_Contains(gameLogic_keys, item)) {
PyDict_DelItem( PyModule_GetDict(gameLogic), item);
}
diff --git a/source/gameengine/BlenderRoutines/CMakeLists.txt b/source/gameengine/BlenderRoutines/CMakeLists.txt
index 96b56768b8f..a053e069153 100644
--- a/source/gameengine/BlenderRoutines/CMakeLists.txt
+++ b/source/gameengine/BlenderRoutines/CMakeLists.txt
@@ -23,16 +23,16 @@ set(INC
../../blender/makesdna
../../blender/makesrna
../../blender/windowmanager
- ../../../extern/bullet2/src
../../../intern/container
../../../intern/guardedalloc
../../../intern/moto/include
../../../intern/string
- ${GLEW_INCLUDE_PATH}
)
set(INC_SYS
+ ../../../extern/bullet2/src
${PTHREADS_INCLUDE_DIRS}
+ ${GLEW_INCLUDE_PATH}
)
set(SRC
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp
index 6236923d973..346d2017ef0 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp
+++ b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp
@@ -33,6 +33,7 @@
#include "KX_BlenderCanvas.h"
#include "DNA_screen_types.h"
#include <stdio.h>
+#include <assert.h>
KX_BlenderCanvas::KX_BlenderCanvas(struct wmWindow *win, RAS_Rect &rect, struct ARegion *ar) :
@@ -44,6 +45,8 @@ m_frame_rect(rect)
// area boundaries needed for mouse coordinates in Letterbox framing mode
m_area_left = ar->winrct.xmin;
m_area_top = ar->winrct.ymax;
+
+ glGetIntegerv(GL_VIEWPORT, (GLint *)m_viewport);
}
KX_BlenderCanvas::~KX_BlenderCanvas()
@@ -53,7 +56,7 @@ KX_BlenderCanvas::~KX_BlenderCanvas()
void KX_BlenderCanvas::Init()
{
glDepthFunc(GL_LEQUAL);
-}
+}
void KX_BlenderCanvas::SwapBuffers()
@@ -116,14 +119,14 @@ int KX_BlenderCanvas::GetHeight(
int KX_BlenderCanvas::GetMouseX(int x)
{
- float left = GetWindowArea().GetLeft();
- return float(x - (left - m_area_left));
+ int left = GetWindowArea().GetLeft();
+ return x - (left - m_area_left);
}
int KX_BlenderCanvas::GetMouseY(int y)
{
- float top = GetWindowArea().GetTop();
- return float(y - (m_area_top - top));
+ int top = GetWindowArea().GetTop();
+ return y - (m_area_top - top);
}
float KX_BlenderCanvas::GetMouseNormalizedX(int x)
@@ -143,7 +146,7 @@ KX_BlenderCanvas::
GetWindowArea(
) {
return m_area_rect;
-}
+}
void
KX_BlenderCanvas::
@@ -166,10 +169,31 @@ SetViewPort(
m_area_rect.SetRight(minx + x2);
m_area_rect.SetTop(miny + y2);
+ m_viewport[0] = minx+x1;
+ m_viewport[1] = miny+y1;
+ m_viewport[2] = vp_width;
+ m_viewport[3] = vp_height;
+
glViewport(minx + x1, miny + y1, vp_width, vp_height);
glScissor(minx + x1, miny + y1, vp_width, vp_height);
}
+ const int*
+KX_BlenderCanvas::
+GetViewPort() {
+#ifdef DEBUG
+ // If we're in a debug build, we might as well make sure our values don't differ
+ // from what the gpu thinks we have. This could lead to nasty, hard to find bugs.
+ int viewport[4];
+ glGetIntegerv(GL_VIEWPORT, viewport);
+ assert(viewport[0] == m_viewport[0]);
+ assert(viewport[1] == m_viewport[1]);
+ assert(viewport[2] == m_viewport[2]);
+ assert(viewport[3] == m_viewport[3]);
+#endif
+
+ return m_viewport;
+}
void KX_BlenderCanvas::SetMouseState(RAS_MouseState mousestate)
{
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h
index ee7997abb39..244394a115d 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h
@@ -61,6 +61,7 @@ private:
/** Rect that defines the area used for rendering,
relative to the context */
RAS_Rect m_displayarea;
+ int m_viewport[4];
public:
/* Construct a new canvas.
@@ -150,6 +151,8 @@ public:
int x1, int y1,
int x2, int y2
);
+ const int*
+ GetViewPort();
void
SetMouseState(
@@ -189,8 +192,8 @@ private:
struct wmWindow* m_win;
RAS_Rect m_frame_rect;
RAS_Rect m_area_rect;
- short m_area_left;
- short m_area_top;
+ int m_area_left;
+ int m_area_top;
#ifdef WITH_CXX_GUARDEDALLOC
@@ -198,5 +201,4 @@ private:
#endif
};
-#endif // __KX_BLENDERCANVAS_H__
-
+#endif /* __KX_BLENDERCANVAS_H__ */
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp b/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp
index 19a84acf027..7c4c759e361 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp
+++ b/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp
@@ -91,7 +91,7 @@ void BL_SwapBuffers(wmWindow *win)
wm_window_swap_buffers(win);
}
-void DisableForText()
+static void DisableForText()
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); /* needed for texture fonts otherwise they render as wireframe */
@@ -153,7 +153,7 @@ void BL_print_game_line(int fontid, const char* text, int size, int dpi, float*
}
void BL_print_gamedebug_line(const char* text, int xco, int yco, int width, int height)
-{
+{
/* gl prepping */
DisableForText();
glDisable(GL_DEPTH_TEST);
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderGL.h b/source/gameengine/BlenderRoutines/KX_BlenderGL.h
index 3b89538df47..7ba612b19cf 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderGL.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderGL.h
@@ -34,7 +34,7 @@
#ifdef __cplusplus
extern "C" {
-#endif //__cplusplus
+#endif /* __cplusplus */
struct wmWindow;
struct ARegion;
@@ -58,7 +58,6 @@ void BL_print_gamedebug_line_padded(const char* text, int xco, int yco, int widt
#ifdef __cplusplus
}
-#endif //__cplusplus
-
-#endif //__KX_BLENDERGL_H__
+#endif /* __cplusplus */
+#endif /* __KX_BLENDERGL_H__ */
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h b/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h
index 43870d9030d..2a96d4c5216 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h
@@ -32,8 +32,8 @@
#ifndef __KX_BLENDERINPUTDEVICE_H__
#define __KX_BLENDERINPUTDEVICE_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning(disable : 4786) // shut off 255 char limit debug template warning
+#ifdef _MSC_VER
+# pragma warning(disable:4786) // shut off 255 char limit debug template warning
#endif
#include <map>
@@ -48,8 +48,9 @@
#endif
/**
- Base Class for Blender specific inputdevices. Blender specific inputdevices are used when the gameengine is running in embedded mode instead of standalone mode.
-*/
+ * Base Class for Blender specific inputdevices.
+ * Blender specific inputdevices are used when the gameengine is running in embedded mode instead of standalone mode.
+ */
class BL_BlenderInputDevice : public SCA_IInputDevice
{
public:
@@ -75,5 +76,5 @@ public:
MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_BlenderInputDevice")
#endif
};
-#endif //__KX_BLENDERINPUTDEVICE_H__
+#endif /* __KX_BLENDERINPUTDEVICE_H__ */
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp b/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp
index 54c60096812..f4e325eabb8 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp
+++ b/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp
@@ -30,9 +30,9 @@
*/
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// annoying warnings about truncated STL debug info
-#pragma warning (disable :4786)
+#ifdef _MSC_VER
+ /* annoying warnings about truncated STL debug info */
+# pragma warning (disable:4786)
#endif
#include "KX_BlenderKeyboardDevice.h"
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h b/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h
index e9140efce01..dec70203ecb 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h
@@ -59,5 +59,4 @@ private:
#endif
};
-#endif //__KX_BLENDERKEYBOARDDEVICE_H__
-
+#endif /* __KX_BLENDERKEYBOARDDEVICE_H__ */
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp b/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp
index 5cd2038163c..aa2392ded08 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp
+++ b/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp
@@ -29,10 +29,9 @@
* \ingroup blroutines
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// annoying warnings about truncated STL debug info
-#pragma warning (disable :4786)
+#ifdef _MSC_VER
+ /* annoying warnings about truncated STL debug info */
+# pragma warning (disable:4786)
#endif
#include "KX_BlenderMouseDevice.h"
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h b/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h
index 0571cafd7a1..8746da83a81 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h
@@ -55,5 +55,4 @@ public:
#endif
};
-#endif //__KX_BLENDERMOUSEDEVICE_H__
-
+#endif /* __KX_BLENDERMOUSEDEVICE_H__ */
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp
index c4daecc9958..e32239b148d 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp
+++ b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp
@@ -58,7 +58,7 @@ unsigned int KX_BlenderRenderTools::m_numgllights;
KX_BlenderRenderTools::KX_BlenderRenderTools()
{
- glGetIntegerv(GL_MAX_LIGHTS, (GLint*) &m_numgllights);
+ glGetIntegerv(GL_MAX_LIGHTS, (GLint *) &m_numgllights);
if (m_numgllights < 8)
m_numgllights = 8;
}
@@ -164,11 +164,11 @@ bool KX_BlenderRenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* resu
left = (dir.cross(resultnormal)).safe_normalized();
// for the up vector, we take the 'resultnormal' returned by the physics
- double maat[16]={
- left[0], left[1], left[2], 0,
- dir[0], dir[1], dir[2], 0,
- resultnormal[0],resultnormal[1],resultnormal[2], 0,
- 0, 0, 0, 1};
+ double maat[16] = {left[0], left[1], left[2], 0,
+ dir[0], dir[1], dir[2], 0,
+ resultnormal[0], resultnormal[1], resultnormal[2], 0,
+ 0, 0, 0, 1};
+
glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
//glMultMatrixd(oglmatrix);
glMultMatrixd(maat);
@@ -227,16 +227,17 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat
left *= size[0];
dir *= size[1];
up *= size[2];
- double maat[16]={
- left[0], left[1],left[2], 0,
- dir[0], dir[1],dir[2],0,
- up[0],up[1],up[2],0,
- 0,0,0,1};
- glTranslated(objpos[0],objpos[1],objpos[2]);
- glMultMatrixd(maat);
-
- } else
- {
+
+ double maat[16] = {left[0], left[1], left[2], 0,
+ dir[0], dir[1], dir[2], 0,
+ up[0], up[1], up[2], 0,
+ 0, 0, 0, 1};
+
+ glTranslated(objpos[0],objpos[1],objpos[2]);
+ glMultMatrixd(maat);
+
+ }
+ else {
if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
{
// shadow must be cast to the ground, physics system needed here!
@@ -344,7 +345,7 @@ void KX_BlenderRenderTools::PopMatrix()
int KX_BlenderRenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
{
- // taken from blender source, incompatibility between Blender Object / GameObject
+ // taken from blender source, incompatibility between Blender Object / GameObject
KX_Scene* kxscene = (KX_Scene*)m_auxilaryClientInfo;
float glviewmat[16];
unsigned int count;
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h
index a229c9f34e6..7195524ceae 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h
@@ -32,9 +32,9 @@
#ifndef __KX_BLENDERRENDERTOOLS_H__
#define __KX_BLENDERRENDERTOOLS_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// don't show stl-warnings
-#pragma warning (disable:4786)
+#ifdef _MSC_VER
+ /* don't show stl-warnings */
+# pragma warning (disable:4786)
#endif
#include "RAS_IRenderTools.h"
@@ -62,7 +62,7 @@ class KX_BlenderRenderTools : public RAS_IRenderTools
public:
KX_BlenderRenderTools();
- virtual ~KX_BlenderRenderTools();
+ virtual ~KX_BlenderRenderTools();
void EndFrame(RAS_IRasterizer* rasty);
void BeginFrame(RAS_IRasterizer* rasty);
@@ -72,26 +72,26 @@ public:
void ProcessLighting(RAS_IRasterizer *rasty, bool uselights, const MT_Transform& viewmat);
void RenderText3D(int fontid,
- const char* text,
- int size,
- int dpi,
- float* color,
- double* mat,
- float aspect);
+ const char* text,
+ int size,
+ int dpi,
+ float* color,
+ double* mat,
+ float aspect);
void RenderText2D(RAS_TEXT_RENDER_MODE mode,
- const char* text,
- int xco,
- int yco,
- int width,
- int height);
+ const char* text,
+ int xco,
+ int yco,
+ int width,
+ int height);
void RenderText(int mode,
- class RAS_IPolyMaterial* polymat,
- float v1[3],
- float v2[3],
- float v3[3],
- float v4[3],
- int glattrib);
+ class RAS_IPolyMaterial* polymat,
+ float v1[3],
+ float v2[3],
+ float v3[3],
+ float v4[3],
+ int glattrib);
void applyTransform(RAS_IRasterizer* rasty, double* oglmatrix, int objectdrawmode);
int applyLights(int objectlayer, const MT_Transform& viewmat);
@@ -112,7 +112,4 @@ public:
#endif
};
-#endif //__KX_BLENDERRENDERTOOLS_H__
-
-
-
+#endif /* __KX_BLENDERRENDERTOOLS_H__ */
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp b/source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp
index d7d8c5121a2..0582e79d269 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp
+++ b/source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp
@@ -32,9 +32,9 @@
#include "KX_ISystem.h"
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable :4786)
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
+#endif
#ifdef WIN32
#include <windows.h>
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderSystem.h b/source/gameengine/BlenderRoutines/KX_BlenderSystem.h
index a8e033ed47b..0867ef2421f 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderSystem.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderSystem.h
@@ -53,5 +53,4 @@ public:
#endif
};
-#endif //__KX_BLENDERSYSTEM_H__
-
+#endif /* __KX_BLENDERSYSTEM_H__ */
diff --git a/source/gameengine/CMakeLists.txt b/source/gameengine/CMakeLists.txt
index a205ccbdc12..aae7e93cc91 100644
--- a/source/gameengine/CMakeLists.txt
+++ b/source/gameengine/CMakeLists.txt
@@ -25,7 +25,7 @@
# there are too many inter-includes so best define here
if(WITH_PYTHON)
- blender_include_dirs("${PYTHON_INCLUDE_DIRS}")
+ blender_include_dirs_sys("${PYTHON_INCLUDE_DIRS}")
add_definitions(-DWITH_PYTHON)
endif()
diff --git a/source/gameengine/Converter/BL_ActionActuator.cpp b/source/gameengine/Converter/BL_ActionActuator.cpp
index 92d04115f10..0bd09146f3a 100644
--- a/source/gameengine/Converter/BL_ActionActuator.cpp
+++ b/source/gameengine/Converter/BL_ActionActuator.cpp
@@ -96,7 +96,7 @@ BL_ActionActuator::BL_ActionActuator(SCA_IObject* gameobj,
m_userpose(NULL),
m_action(action),
m_propname(propname),
- m_framepropname(framepropname)
+ m_framepropname(framepropname)
{
if (!end_reset)
m_flag |= ACT_FLAG_CONTINUE;
@@ -140,8 +140,7 @@ void BL_ActionActuator::SetLocalTime(float curtime)
// Handle wrap around
if (m_localtime < min(m_startframe, m_endframe) || m_localtime > max(m_startframe, m_endframe))
{
- switch(m_playtype)
- {
+ switch (m_playtype) {
case ACT_ACTION_PLAY:
// Clamp
m_localtime = m_endframe;
@@ -196,8 +195,7 @@ bool BL_ActionActuator::Update(double curtime, bool frame)
return false;
// Convert our playtype to one that BL_Action likes
- switch(m_playtype)
- {
+ switch (m_playtype) {
case ACT_ACTION_LOOP_END:
case ACT_ACTION_LOOP_STOP:
playtype = BL_Action::ACT_MODE_LOOP;
@@ -299,7 +297,7 @@ bool BL_ActionActuator::Update(double curtime, bool frame)
m_flag |= ACT_FLAG_ATTEMPT_PLAY;
}
else if ((m_flag & ACT_FLAG_ACTIVE) && bNegativeEvent)
- {
+ {
m_flag &= ~ACT_FLAG_ATTEMPT_PLAY;
m_localtime = obj->GetActionFrame(m_layer);
bAction *curr_action = obj->GetCurrentAction(m_layer);
@@ -312,8 +310,7 @@ bool BL_ActionActuator::Update(double curtime, bool frame)
return false;
}
- switch(m_playtype)
- {
+ switch (m_playtype) {
case ACT_ACTION_LOOP_STOP:
obj->StopAction(m_layer); // Stop the action after getting the frame
@@ -347,7 +344,7 @@ bool BL_ActionActuator::Update(double curtime, bool frame)
/* Python functions */
/* ------------------------------------------------------------------------- */
-PyObject* BL_ActionActuator::PyGetChannel(PyObject* value)
+PyObject *BL_ActionActuator::PyGetChannel(PyObject *value)
{
PyErr_SetString(PyExc_NotImplementedError, "BL_ActionActuator.getChannel() no longer works, please use BL_ArmatureObject.channels instead");
return NULL;
@@ -492,9 +489,9 @@ KX_PYMETHODDEF_DOC(BL_ActionActuator, setChannel,
// for some reason loc.setValue(pchan->loc) fails
if (pchan) {
- pchan->loc[0]= loc[0]; pchan->loc[1]= loc[1]; pchan->loc[2]= loc[2];
- pchan->size[0]= size[0]; pchan->size[1]= size[1]; pchan->size[2]= size[2];
- pchan->quat[0]= quat[3]; pchan->quat[1]= quat[0]; pchan->quat[2]= quat[1]; pchan->quat[3]= quat[2]; /* notice xyzw -> wxyz is intentional */
+ pchan->loc[0] = loc[0]; pchan->loc[1] = loc[1]; pchan->loc[2] = loc[2];
+ pchan->size[0] = size[0]; pchan->size[1] = size[1]; pchan->size[2] = size[2];
+ pchan->quat[0] = quat[3]; pchan->quat[1] = quat[0]; pchan->quat[2] = quat[1]; pchan->quat[3] = quat[2]; /* notice xyzw -> wxyz is intentional */
}
}
@@ -555,15 +552,15 @@ PyAttributeDef BL_ActionActuator::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* BL_ActionActuator::pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ActionActuator::pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
+ BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
return PyUnicode_FromString(self->GetAction() ? self->GetAction()->id.name+2 : "");
}
int BL_ActionActuator::pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
+ BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
if (!PyUnicode_Check(value))
{
@@ -589,13 +586,13 @@ int BL_ActionActuator::pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF
}
-PyObject* BL_ActionActuator::pyattr_get_channel_names(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ActionActuator::pyattr_get_channel_names(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
PyErr_SetString(PyExc_NotImplementedError, "BL_ActionActuator.channelNames no longer works, please use BL_ArmatureObject.channels instead");
return NULL;
#if 0 // XXX To be removed in a later version (first removed in 2.64)
- BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
+ BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
PyObject *ret= PyList_New(0);
PyObject *item;
@@ -620,15 +617,15 @@ PyObject* BL_ActionActuator::pyattr_get_channel_names(void *self_v, const KX_PYA
#endif
}
-PyObject* BL_ActionActuator::pyattr_get_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ActionActuator::pyattr_get_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
+ BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
return PyBool_FromLong(self->m_flag & ACT_FLAG_CONTINUE);
}
int BL_ActionActuator::pyattr_set_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
+ BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
if (PyObject_IsTrue(value))
self->m_flag |= ACT_FLAG_CONTINUE;
@@ -638,15 +635,15 @@ int BL_ActionActuator::pyattr_set_use_continue(void *self_v, const KX_PYATTRIBUT
return PY_SET_ATTR_SUCCESS;
}
-PyObject* BL_ActionActuator::pyattr_get_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ActionActuator::pyattr_get_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
+ BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
return PyFloat_FromDouble(((KX_GameObject*)self->m_gameobj)->GetActionFrame(self->m_layer));
}
int BL_ActionActuator::pyattr_set_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
+ BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
((KX_GameObject*)self->m_gameobj)->SetActionFrame(self->m_layer, PyFloat_AsDouble(value));
diff --git a/source/gameengine/Converter/BL_ActionActuator.h b/source/gameengine/Converter/BL_ActionActuator.h
index 640a9a9ccb7..46075ea933d 100644
--- a/source/gameengine/Converter/BL_ActionActuator.h
+++ b/source/gameengine/Converter/BL_ActionActuator.h
@@ -108,7 +108,7 @@ public:
return 1;
}
}
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
protected:
MT_Point3 m_lastpos;
diff --git a/source/gameengine/Converter/BL_ArmatureActuator.cpp b/source/gameengine/Converter/BL_ArmatureActuator.cpp
index 3f4a261a972..f0c4b3d32bb 100644
--- a/source/gameengine/Converter/BL_ArmatureActuator.cpp
+++ b/source/gameengine/Converter/BL_ArmatureActuator.cpp
@@ -146,7 +146,7 @@ void BL_ArmatureActuator::FindConstraint()
bool BL_ArmatureActuator::Update(double curtime, bool frame)
{
// the only role of this actuator is to ensure that the armature pose will be evaluated
- bool result = false;
+ bool result = false;
bool bNegativeEvent = IsNegativeEvent();
RemoveAllEvents();
@@ -227,11 +227,11 @@ PyAttributeDef BL_ArmatureActuator::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* BL_ArmatureActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ArmatureActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
BL_ArmatureActuator* actuator = static_cast<BL_ArmatureActuator*>(self);
KX_GameObject *target = (!strcmp(attrdef->m_name, "target")) ? actuator->m_gametarget : actuator->m_gamesubtarget;
- if (!target)
+ if (!target)
Py_RETURN_NONE;
else
return target->GetProxy();
@@ -247,7 +247,7 @@ int BL_ArmatureActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBU
return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
if (target != NULL)
- target->UnregisterActuator(actuator);
+ target->UnregisterActuator(actuator);
target = gameobj;
@@ -257,11 +257,11 @@ int BL_ArmatureActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBU
return PY_SET_ATTR_SUCCESS;
}
-PyObject* BL_ArmatureActuator::pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ArmatureActuator::pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
BL_ArmatureActuator* actuator = static_cast<BL_ArmatureActuator*>(self);
BL_ArmatureConstraint* constraint = actuator->m_constraint;
- if (!constraint)
+ if (!constraint)
Py_RETURN_NONE;
else
return constraint->GetProxy();
diff --git a/source/gameengine/Converter/BL_ArmatureActuator.h b/source/gameengine/Converter/BL_ArmatureActuator.h
index 638640c27ce..ba02c5aa362 100644
--- a/source/gameengine/Converter/BL_ArmatureActuator.h
+++ b/source/gameengine/Converter/BL_ArmatureActuator.h
@@ -49,13 +49,13 @@ class BL_ArmatureActuator : public SCA_IActuator
Py_Header
public:
BL_ArmatureActuator(SCA_IObject* gameobj,
- int type,
- const char *posechannel,
- const char *constraintname,
- KX_GameObject* targetobj,
- KX_GameObject* subtargetobj,
- float weight,
- float influence);
+ int type,
+ const char *posechannel,
+ const char *constraintname,
+ KX_GameObject* targetobj,
+ KX_GameObject* subtargetobj,
+ float weight,
+ float influence);
virtual ~BL_ArmatureActuator();
@@ -73,11 +73,11 @@ public:
#ifdef WITH_PYTHON
/* These are used to get and set m_target */
- static PyObject* pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
private:
// identify the constraint that this actuator controls
@@ -93,6 +93,4 @@ private:
int m_type;
};
-#endif //__BL_ARMATUREACTUATOR_H__
-
-
+#endif /* __BL_ARMATUREACTUATOR_H__ */
diff --git a/source/gameengine/Converter/BL_ArmatureChannel.cpp b/source/gameengine/Converter/BL_ArmatureChannel.cpp
index 7344aa9378e..7cf895255ba 100644
--- a/source/gameengine/Converter/BL_ArmatureChannel.cpp
+++ b/source/gameengine/Converter/BL_ArmatureChannel.cpp
@@ -62,7 +62,7 @@ PyTypeObject BL_ArmatureChannel::Type = {
py_base_new
};
-PyObject* BL_ArmatureChannel::py_repr(void)
+PyObject *BL_ArmatureChannel::py_repr(void)
{
return PyUnicode_FromString(m_posechannel->name);
}
@@ -104,8 +104,8 @@ PyMethodDef BL_ArmatureChannel::Methods[] = {
PyAttributeDef BL_ArmatureChannel::Attributes[] = {
// Keep these attributes in order of BCA_ defines!!! used by py_attr_getattr and py_attr_setattr
- KX_PYATTRIBUTE_RO_FUNCTION("bone",BL_ArmatureChannel,py_attr_getattr),
- KX_PYATTRIBUTE_RO_FUNCTION("parent",BL_ArmatureChannel,py_attr_getattr),
+ KX_PYATTRIBUTE_RO_FUNCTION("bone",BL_ArmatureChannel,py_attr_getattr),
+ KX_PYATTRIBUTE_RO_FUNCTION("parent",BL_ArmatureChannel,py_attr_getattr),
{ NULL } //Sentinel
};
@@ -147,9 +147,9 @@ PyAttributeDef BL_ArmatureChannel::AttributesPtr[] = {
{ NULL } //Sentinel
};
-PyObject* BL_ArmatureChannel::py_attr_getattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ArmatureChannel::py_attr_getattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
- BL_ArmatureChannel* self= static_cast<BL_ArmatureChannel*>(self_v);
+ BL_ArmatureChannel* self = static_cast<BL_ArmatureChannel*>(self_v);
bPoseChannel* channel = self->m_posechannel;
int attr_order = attrdef-Attributes;
@@ -177,7 +177,7 @@ PyObject* BL_ArmatureChannel::py_attr_getattr(void *self_v, const struct KX_PYAT
int BL_ArmatureChannel::py_attr_setattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- BL_ArmatureChannel* self= static_cast<BL_ArmatureChannel*>(self_v);
+ BL_ArmatureChannel* self = static_cast<BL_ArmatureChannel*>(self_v);
bPoseChannel* channel = self->m_posechannel;
int attr_order = attrdef-Attributes;
@@ -200,7 +200,7 @@ int BL_ArmatureChannel::py_attr_setattr(void *self_v, const struct KX_PYATTRIBUT
return PY_SET_ATTR_FAIL;
}
-PyObject* BL_ArmatureChannel::py_attr_get_joint_rotation(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ArmatureChannel::py_attr_get_joint_rotation(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
bPoseChannel* pchan = static_cast<bPoseChannel*>(self_v);
// decompose the pose matrix in euler rotation
@@ -223,7 +223,7 @@ PyObject* BL_ArmatureChannel::py_attr_get_joint_rotation(void *self_v, const str
}
// remove the rest pose to get the joint movement
transpose_m3(rest_mat);
- mul_m3_m3m3(joint_mat, rest_mat, pose_mat);
+ mul_m3_m3m3(joint_mat, rest_mat, pose_mat);
joints[0] = joints[1] = joints[2] = 0.f;
// returns a 3 element list that gives corresponding joint
int flag = 0;
@@ -300,7 +300,7 @@ PyObject* BL_ArmatureChannel::py_attr_get_joint_rotation(void *self_v, const str
int BL_ArmatureChannel::py_attr_set_joint_rotation(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- BL_ArmatureChannel* self= static_cast<BL_ArmatureChannel*>(self_v);
+ BL_ArmatureChannel* self = static_cast<BL_ArmatureChannel*>(self_v);
bPoseChannel* pchan = self->m_posechannel;
PyObject *item;
float joints[3];
@@ -455,12 +455,12 @@ PyObject *BL_ArmatureBone::py_bone_get_children(void *self, const struct KX_PYAT
Bone* bone = reinterpret_cast<Bone*>(self);
Bone* child;
int count = 0;
- for (child=(Bone*)bone->childbase.first; child; child=(Bone*)child->next)
+ for (child = (Bone *)bone->childbase.first; child; child = child->next)
count++;
- PyObject* childrenlist = PyList_New(count);
+ PyObject *childrenlist = PyList_New(count);
- for (count = 0, child=(Bone*)bone->childbase.first; child; child=(Bone*)child->next, ++count)
+ for (count = 0, child = (Bone *)bone->childbase.first; child; child = child->next, ++count)
PyList_SET_ITEM(childrenlist,count,NewProxyPlus_Ext(NULL,&Type,child,false));
return childrenlist;
diff --git a/source/gameengine/Converter/BL_ArmatureChannel.h b/source/gameengine/Converter/BL_ArmatureChannel.h
index cd38ee2d531..51114c5df30 100644
--- a/source/gameengine/Converter/BL_ArmatureChannel.h
+++ b/source/gameengine/Converter/BL_ArmatureChannel.h
@@ -62,13 +62,13 @@ public:
#ifdef WITH_PYTHON
// Python access
- virtual PyObject* py_repr(void);
+ virtual PyObject *py_repr(void);
- static PyObject* py_attr_getattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *py_attr_getattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
static int py_attr_setattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* py_attr_get_joint_rotation(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *py_attr_get_joint_rotation(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
static int py_attr_set_joint_rotation(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
/* this is a factory class to access bBone data field in the GE.
@@ -93,6 +93,4 @@ public:
};
-
-#endif //__BL_ARMATURECHANNEL_H__
-
+#endif /* __BL_ARMATURECHANNEL_H__ */
diff --git a/source/gameengine/Converter/BL_ArmatureConstraint.cpp b/source/gameengine/Converter/BL_ArmatureConstraint.cpp
index 7939d6e9235..b8ad117a220 100644
--- a/source/gameengine/Converter/BL_ArmatureConstraint.cpp
+++ b/source/gameengine/Converter/BL_ArmatureConstraint.cpp
@@ -61,7 +61,7 @@ PyTypeObject BL_ArmatureConstraint::Type = {
py_base_new
};
-PyObject* BL_ArmatureConstraint::py_repr(void)
+PyObject *BL_ArmatureConstraint::py_repr(void)
{
return PyUnicode_FromString(m_name);
}
@@ -267,8 +267,8 @@ PyMethodDef BL_ArmatureConstraint::Methods[] = {
PyAttributeDef BL_ArmatureConstraint::Attributes[] = {
// Keep these attributes in order of BCA_ defines!!! used by py_attr_getattr and py_attr_setattr
- KX_PYATTRIBUTE_RO_FUNCTION("type",BL_ArmatureConstraint,py_attr_getattr),
- KX_PYATTRIBUTE_RO_FUNCTION("name",BL_ArmatureConstraint,py_attr_getattr),
+ KX_PYATTRIBUTE_RO_FUNCTION("type",BL_ArmatureConstraint,py_attr_getattr),
+ KX_PYATTRIBUTE_RO_FUNCTION("name",BL_ArmatureConstraint,py_attr_getattr),
KX_PYATTRIBUTE_RW_FUNCTION("enforce",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr),
KX_PYATTRIBUTE_RW_FUNCTION("headtail",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr),
KX_PYATTRIBUTE_RO_FUNCTION("lin_error",BL_ArmatureConstraint,py_attr_getattr),
@@ -286,9 +286,9 @@ PyAttributeDef BL_ArmatureConstraint::Attributes[] = {
};
-PyObject* BL_ArmatureConstraint::py_attr_getattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ArmatureConstraint::py_attr_getattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
- BL_ArmatureConstraint* self= static_cast<BL_ArmatureConstraint*>(self_v);
+ BL_ArmatureConstraint* self = static_cast<BL_ArmatureConstraint*>(self_v);
bConstraint* constraint = self->m_constraint;
bKinematicConstraint* ikconstraint = (constraint && constraint->type == CONSTRAINT_TYPE_KINEMATIC) ? (bKinematicConstraint*)constraint->data : NULL;
int attr_order = attrdef-Attributes;
@@ -312,12 +312,12 @@ PyObject* BL_ArmatureConstraint::py_attr_getattr(void *self_v, const struct KX_P
case BCA_ROTERROR:
return PyFloat_FromDouble(constraint->rot_error);
case BCA_TARGET:
- if (!self->m_target)
+ if (!self->m_target)
Py_RETURN_NONE;
else
return self->m_target->GetProxy();
case BCA_SUBTARGET:
- if (!self->m_subtarget)
+ if (!self->m_subtarget)
Py_RETURN_NONE;
else
return self->m_subtarget->GetProxy();
@@ -353,7 +353,7 @@ PyObject* BL_ArmatureConstraint::py_attr_getattr(void *self_v, const struct KX_P
int BL_ArmatureConstraint::py_attr_setattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- BL_ArmatureConstraint* self= static_cast<BL_ArmatureConstraint*>(self_v);
+ BL_ArmatureConstraint* self = static_cast<BL_ArmatureConstraint*>(self_v);
bConstraint* constraint = self->m_constraint;
bKinematicConstraint* ikconstraint = (constraint && constraint->type == CONSTRAINT_TYPE_KINEMATIC) ? (bKinematicConstraint*)constraint->data : NULL;
int attr_order = attrdef-Attributes;
diff --git a/source/gameengine/Converter/BL_ArmatureConstraint.h b/source/gameengine/Converter/BL_ArmatureConstraint.h
index 0d79bb1cfa7..98c2954baf4 100644
--- a/source/gameengine/Converter/BL_ArmatureConstraint.h
+++ b/source/gameengine/Converter/BL_ArmatureConstraint.h
@@ -115,12 +115,11 @@ public:
#ifdef WITH_PYTHON
// Python access
- virtual PyObject* py_repr(void);
+ virtual PyObject *py_repr(void);
- static PyObject* py_attr_getattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *py_attr_getattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
static int py_attr_setattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif //__BL_ARMATURECONSTRAINT_H__
-
+#endif /* __BL_ARMATURECONSTRAINT_H__ */
diff --git a/source/gameengine/Converter/BL_ArmatureObject.cpp b/source/gameengine/Converter/BL_ArmatureObject.cpp
index 7174a563efa..ed97b9ff73f 100644
--- a/source/gameengine/Converter/BL_ArmatureObject.cpp
+++ b/source/gameengine/Converter/BL_ArmatureObject.cpp
@@ -105,7 +105,7 @@ void game_copy_pose(bPose **dst, bPose *src, int copy_constraint)
for (; pchan; pchan=pchan->next, outpchan=outpchan->next)
BLI_ghash_insert(ghash, pchan, outpchan);
- for (pchan=(bPoseChannel*)out->chanbase.first; pchan; pchan=(bPoseChannel*)pchan->next) {
+ for (pchan = (bPoseChannel*)out->chanbase.first; pchan; pchan = pchan->next) {
pchan->parent= (bPoseChannel*)BLI_ghash_lookup(ghash, pchan->parent);
pchan->child= (bPoseChannel*)BLI_ghash_lookup(ghash, pchan->child);
@@ -186,7 +186,10 @@ void game_blend_poses(bPose *dst, bPose *src, float srcweight/*, short mode*/)
if (schan->rotmode)
dchan->eul[i] = (dchan->eul[i]*dstweight) + (schan->eul[i]*srcweight);
}
- for (dcon= (bConstraint*)dchan->constraints.first, scon= (bConstraint*)schan->constraints.first; dcon && scon; dcon= (bConstraint*)dcon->next, scon= (bConstraint*)scon->next) {
+ for (dcon= (bConstraint *)dchan->constraints.first, scon= (bConstraint *)schan->constraints.first;
+ dcon && scon;
+ dcon = dcon->next, scon = scon->next)
+ {
/* no 'add' option for constraint blending */
dcon->enforce= dcon->enforce*(1.0f-srcweight) + scon->enforce*srcweight;
}
@@ -282,8 +285,8 @@ void BL_ArmatureObject::LoadConstraints(KX_BlenderSceneConverter* converter)
KX_GameObject* gamesubtarget;
// and locate the constraint
- for (pchan = (bPoseChannel*)m_pose->chanbase.first; pchan; pchan=(bPoseChannel*)pchan->next) {
- for (pcon = (bConstraint*)pchan->constraints.first; pcon; pcon=(bConstraint*)pcon->next) {
+ for (pchan = (bPoseChannel *)m_pose->chanbase.first; pchan; pchan = pchan->next) {
+ for (pcon = (bConstraint *)pchan->constraints.first; pcon; pcon = pcon->next) {
if (pcon->flag & CONSTRAINT_DISABLE)
continue;
// which constraint should we support?
@@ -315,7 +318,7 @@ void BL_ArmatureObject::LoadConstraints(KX_BlenderSceneConverter* converter)
}
if (target->next != NULL) {
// secondary target
- target = (bConstraintTarget*)target->next;
+ target = target->next;
if (target->tar && target->tar != m_objArma) {
// only track external object
blendtarget = target->tar;
@@ -430,7 +433,7 @@ void BL_ArmatureObject::ProcessReplica()
m_pose = NULL;
m_framePose = NULL;
- game_copy_pose(&m_pose, pose, 1);
+ game_copy_pose(&m_pose, pose, 1);
}
void BL_ArmatureObject::ReParentLogic()
@@ -521,7 +524,7 @@ bool BL_ArmatureObject::SetActiveAction(BL_ActionActuator *act, short priority,
SetPose(m_framePose);
if (m_activeAct && (m_activeAct!=act))
/* Reset the blend timer since this new action cancels the old one */
- m_activeAct->SetBlendTime(0.0);
+ m_activeAct->SetBlendTime(0.0);
}
m_activeAct = act;
m_activePriority = priority;
@@ -648,12 +651,12 @@ PyAttributeDef BL_ArmatureObject::Attributes[] = {
{NULL} //Sentinel
};
-PyObject* BL_ArmatureObject::pyattr_get_constraints(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ArmatureObject::pyattr_get_constraints(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
return KX_PythonSeq_CreatePyObject((static_cast<BL_ArmatureObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_CONSTRAINTS);
}
-PyObject* BL_ArmatureObject::pyattr_get_channels(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ArmatureObject::pyattr_get_channels(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
BL_ArmatureObject* self = static_cast<BL_ArmatureObject*>(self_v);
self->LoadChannels(); // make sure we have the channels
diff --git a/source/gameengine/Converter/BL_ArmatureObject.h b/source/gameengine/Converter/BL_ArmatureObject.h
index 6274e770409..445b9af1b10 100644
--- a/source/gameengine/Converter/BL_ArmatureObject.h
+++ b/source/gameengine/Converter/BL_ArmatureObject.h
@@ -116,11 +116,11 @@ public:
#ifdef WITH_PYTHON
// PYTHON
- static PyObject* pyattr_get_constraints(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_channels(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_constraints(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_channels(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
KX_PYMETHOD_DOC_NOARGS(BL_ArmatureObject, update);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
protected:
/* list element: BL_ArmatureConstraint. Use SG_DListHead to have automatic list replication */
@@ -152,6 +152,4 @@ void game_blend_poses(struct bPose *dst, struct bPose *src, float srcweight/*, s
void game_copy_pose(struct bPose **dst, struct bPose *src, int copy_con);
void game_free_pose(struct bPose *pose);
-
-#endif
-
+#endif /* __BL_ARMATUREOBJECT_H__ */
diff --git a/source/gameengine/Converter/BL_BlenderDataConversion.cpp b/source/gameengine/Converter/BL_BlenderDataConversion.cpp
index 84ad12477d0..58ae415e9d3 100644
--- a/source/gameengine/Converter/BL_BlenderDataConversion.cpp
+++ b/source/gameengine/Converter/BL_BlenderDataConversion.cpp
@@ -30,8 +30,8 @@
* \ingroup bgeconv
*/
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
#endif
#include <math.h>
@@ -216,7 +216,7 @@ static std::map<int, SCA_IInputDevice::KX_EnumInputs> create_translate_table()
// SYSTEM
-#if 0
+#if 0
/* **** XXX **** */
m[KEYBD ] = SCA_IInputDevice::KX_KEYBD;
m[RAWKEYBD ] = SCA_IInputDevice::KX_RAWKEYBD;
@@ -229,7 +229,7 @@ static std::map<int, SCA_IInputDevice::KX_EnumInputs> create_translate_table()
m[WINQUIT ] = SCA_IInputDevice::KX_WINQUIT;
m[Q_FIRSTTIME ] = SCA_IInputDevice::KX_Q_FIRSTTIME;
/* **** XXX **** */
-#endif
+#endif
// standard keyboard
@@ -433,8 +433,7 @@ static void GetRGB(short type,
unsigned int &c3)
{
unsigned int color = 0xFFFFFFFFL;
- switch(type)
- {
+ switch (type) {
case 0: // vertex colors
{
if (mmcol) {
@@ -447,7 +446,7 @@ static void GetRGB(short type,
else { // backup white
c0 = KX_rgbaint2uint_new(color);
c1 = KX_rgbaint2uint_new(color);
- c2 = KX_rgbaint2uint_new(color);
+ c2 = KX_rgbaint2uint_new(color);
if (mface->v4)
c3 = KX_rgbaint2uint_new( color );
}
@@ -469,7 +468,7 @@ static void GetRGB(short type,
}
c0 = KX_rgbaint2uint_new(color);
c1 = KX_rgbaint2uint_new(color);
- c2 = KX_rgbaint2uint_new(color);
+ c2 = KX_rgbaint2uint_new(color);
if (mface->v4)
c3 = KX_rgbaint2uint_new(color);
} break;
@@ -478,7 +477,7 @@ static void GetRGB(short type,
{
c0 = KX_rgbaint2uint_new(color);
c1 = KX_rgbaint2uint_new(color);
- c2 = KX_rgbaint2uint_new(color);
+ c2 = KX_rgbaint2uint_new(color);
if (mface->v4)
c3 = KX_rgbaint2uint_new(color);
} break;
@@ -491,7 +490,7 @@ typedef struct MTF_localLayer {
} MTF_localLayer;
// ------------------------------------
-bool ConvertMaterial(
+static bool ConvertMaterial(
BL_Material *material,
Material *mat,
MTFace* tface,
@@ -627,7 +626,7 @@ bool ConvertMaterial(
if (!material->cubemap[i]->cube[0])
BL_Texture::SplitEnvMap(material->cubemap[i]);
- material->texname[i]= material->cubemap[i]->ima->id.name;
+ material->texname[i] = material->cubemap[i]->ima->id.name;
material->mapping[i].mapping |= USEENV;
}
}
@@ -677,7 +676,7 @@ bool ConvertMaterial(
material->mapping[i].projplane[2] = mttmp->projz;
/// --------------------------------
- switch( mttmp->blendtype ) {
+ switch (mttmp->blendtype) {
case MTEX_BLEND:
material->blend_mode[i] = BLEND_MIX;
break;
@@ -701,7 +700,7 @@ bool ConvertMaterial(
// above one tex the switches here
// are not used
- switch(valid_index) {
+ switch (valid_index) {
case 0:
material->IdMode = DEFAULT_BLENDER;
break;
@@ -778,7 +777,7 @@ bool ConvertMaterial(
const char *uvName = "", *uv2Name = "";
- uv2[0]= uv2[1]= uv2[2]= uv2[3]= MT_Point2(0.0f, 0.0f);
+ uv2[0] = uv2[1] = uv2[2] = uv2[3] = MT_Point2(0.0f, 0.0f);
/* No material, what to do? let's see what is in the UV and set the material accordingly
* light and visible is always on */
@@ -799,7 +798,7 @@ bool ConvertMaterial(
material->alphablend = GEMAT_SOLID;
material->tile = 0;
- uv[0]= uv[1]= uv[2]= uv[3]= MT_Point2(0.0f, 0.0f);
+ uv[0] = uv[1] = uv[2] = uv[3] = MT_Point2(0.0f, 0.0f);
}
if (validmat && validface) {
@@ -1150,7 +1149,7 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, KX_Scene* scene,
rgb0 = KX_rgbaint2uint_new(color);
rgb1 = KX_rgbaint2uint_new(color);
- rgb2 = KX_rgbaint2uint_new(color);
+ rgb2 = KX_rgbaint2uint_new(color);
if (mface->v4)
rgb3 = KX_rgbaint2uint_new(color);
@@ -1390,32 +1389,30 @@ static float my_boundbox_mesh(Mesh *me, float *loc, float *size)
}
if (me->totvert) {
- loc[0]= (min[0]+max[0])/2.0f;
- loc[1]= (min[1]+max[1])/2.0f;
- loc[2]= (min[2]+max[2])/2.0f;
+ loc[0] = (min[0] + max[0]) / 2.0f;
+ loc[1] = (min[1] + max[1]) / 2.0f;
+ loc[2] = (min[2] + max[2]) / 2.0f;
- size[0]= (max[0]-min[0])/2.0f;
- size[1]= (max[1]-min[1])/2.0f;
- size[2]= (max[2]-min[2])/2.0f;
+ size[0] = (max[0] - min[0]) / 2.0f;
+ size[1] = (max[1] - min[1]) / 2.0f;
+ size[2] = (max[2] - min[2]) / 2.0f;
}
else {
- loc[0]= loc[1]= loc[2]= 0.0f;
- size[0]= size[1]= size[2]= 0.0f;
+ loc[0] = loc[1] = loc[2] = 0.0f;
+ size[0] = size[1] = size[2] = 0.0f;
}
- bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= loc[0]-size[0];
- bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= loc[0]+size[0];
+ bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = loc[0]-size[0];
+ bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = loc[0]+size[0];
- bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= loc[1]-size[1];
- bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= loc[1]+size[1];
+ bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = loc[1]-size[1];
+ bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = loc[1]+size[1];
- bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= loc[2]-size[2];
- bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= loc[2]+size[2];
+ bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = loc[2]-size[2];
+ bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = loc[2]+size[2];
return sqrt(radius);
}
-
-
static void my_tex_space_mesh(Mesh *me)
@@ -1438,12 +1435,12 @@ static void my_tex_space_mesh(Mesh *me)
minmax_v3v3_v3(min, max, fp);
}
if (kb->totelem) {
- loc[0]= (min[0]+max[0])/2.0f; loc[1]= (min[1]+max[1])/2.0f; loc[2]= (min[2]+max[2])/2.0f;
- size[0]= (max[0]-min[0])/2.0f; size[1]= (max[1]-min[1])/2.0f; size[2]= (max[2]-min[2])/2.0f;
+ loc[0] = (min[0]+max[0])/2.0f; loc[1] = (min[1]+max[1])/2.0f; loc[2] = (min[2]+max[2])/2.0f;
+ size[0] = (max[0]-min[0])/2.0f; size[1] = (max[1]-min[1])/2.0f; size[2] = (max[2]-min[2])/2.0f;
}
else {
- loc[0]= loc[1]= loc[2]= 0.0;
- size[0]= size[1]= size[2]= 0.0;
+ loc[0] = loc[1] = loc[2] = 0.0;
+ size[0] = size[1] = size[2] = 0.0;
}
}
@@ -1451,19 +1448,19 @@ static void my_tex_space_mesh(Mesh *me)
copy_v3_v3(me->loc, loc);
copy_v3_v3(me->size, size);
- me->rot[0]= me->rot[1]= me->rot[2]= 0.0f;
+ me->rot[0] = me->rot[1] = me->rot[2] = 0.0f;
if (me->size[0] == 0.0f) me->size[0] = 1.0f;
- else if (me->size[0] > 0.0f && me->size[0]< 0.00001f) me->size[0]= 0.00001f;
- else if (me->size[0] < 0.0f && me->size[0]> -0.00001f) me->size[0]= -0.00001f;
+ else if (me->size[0] > 0.0f && me->size[0]< 0.00001f) me->size[0] = 0.00001f;
+ else if (me->size[0] < 0.0f && me->size[0]> -0.00001f) me->size[0] = -0.00001f;
- if (me->size[1] == 0.0f) me->size[1]= 1.0f;
- else if (me->size[1] > 0.0f && me->size[1]< 0.00001f) me->size[1]= 0.00001f;
- else if (me->size[1] < 0.0f && me->size[1]> -0.00001f) me->size[1]= -0.00001f;
+ if (me->size[1] == 0.0f) me->size[1] = 1.0f;
+ else if (me->size[1] > 0.0f && me->size[1]< 0.00001f) me->size[1] = 0.00001f;
+ else if (me->size[1] < 0.0f && me->size[1]> -0.00001f) me->size[1] = -0.00001f;
- if (me->size[2] == 0.0f) me->size[2]= 1.0f;
- else if (me->size[2] > 0.0f && me->size[2]< 0.00001f) me->size[2]= 0.00001f;
- else if (me->size[2] < 0.0f && me->size[2]> -0.00001f) me->size[2]= -0.00001f;
+ if (me->size[2] == 0.0f) me->size[2] = 1.0f;
+ else if (me->size[2] > 0.0f && me->size[2]< 0.00001f) me->size[2] = 0.00001f;
+ else if (me->size[2] < 0.0f && me->size[2]> -0.00001f) me->size[2] = -0.00001f;
}
}
@@ -1480,13 +1477,13 @@ static void my_get_local_bounds(Object *ob, DerivedMesh *dm, float *center, floa
float min_r[3], max_r[3];
INIT_MINMAX(min_r, max_r);
dm->getMinMax(dm, min_r, max_r);
- size[0]= 0.5f*fabsf(max_r[0] - min_r[0]);
- size[1]= 0.5f*fabsf(max_r[1] - min_r[1]);
- size[2]= 0.5f*fabsf(max_r[2] - min_r[2]);
+ size[0] = 0.5f * fabsf(max_r[0] - min_r[0]);
+ size[1] = 0.5f * fabsf(max_r[1] - min_r[1]);
+ size[2] = 0.5f * fabsf(max_r[2] - min_r[2]);
- center[0]= 0.5f*(max_r[0] + min_r[0]);
- center[1]= 0.5f*(max_r[1] + min_r[1]);
- center[2]= 0.5f*(max_r[2] + min_r[2]);
+ center[0] = 0.5f * (max_r[0] + min_r[0]);
+ center[1] = 0.5f * (max_r[1] + min_r[1]);
+ center[2] = 0.5f * (max_r[2] + min_r[2]);
return;
} else
{
@@ -1500,11 +1497,11 @@ static void my_get_local_bounds(Object *ob, DerivedMesh *dm, float *center, floa
break;
case OB_CURVE:
case OB_SURF:
- center[0]= center[1]= center[2]= 0.0;
+ center[0] = center[1] = center[2] = 0.0;
size[0] = size[1]=size[2]=0.0;
break;
case OB_FONT:
- center[0]= center[1]= center[2]= 0.0;
+ center[0] = center[1] = center[2] = 0.0;
size[0] = size[1]=size[2]=1.0;
break;
case OB_MBALL:
@@ -1514,15 +1511,15 @@ static void my_get_local_bounds(Object *ob, DerivedMesh *dm, float *center, floa
if (bb==NULL)
{
- center[0]= center[1]= center[2]= 0.0;
- size[0] = size[1]=size[2]=1.0;
+ center[0] = center[1] = center[2] = 0.0;
+ size[0] = size[1] = size[2] = 1.0;
}
else
{
size[0] = 0.5f * fabsf(bb->vec[0][0] - bb->vec[4][0]);
size[1] = 0.5f * fabsf(bb->vec[0][1] - bb->vec[2][1]);
size[2] = 0.5f * fabsf(bb->vec[0][2] - bb->vec[1][2]);
-
+
center[0] = 0.5f * (bb->vec[0][0] + bb->vec[4][0]);
center[1] = 0.5f * (bb->vec[0][1] + bb->vec[2][1]);
center[2] = 0.5f * (bb->vec[0][2] + bb->vec[1][2]);
@@ -1535,14 +1532,14 @@ static void my_get_local_bounds(Object *ob, DerivedMesh *dm, float *center, floa
//////////////////////////////////////////////////////
-void BL_CreateGraphicObjectNew(KX_GameObject* gameobj,
- const MT_Point3& localAabbMin,
- const MT_Point3& localAabbMax,
- KX_Scene* kxscene,
- bool isActive,
- e_PhysicsEngine physics_engine)
+static void BL_CreateGraphicObjectNew(KX_GameObject* gameobj,
+ const MT_Point3& localAabbMin,
+ const MT_Point3& localAabbMax,
+ KX_Scene* kxscene,
+ bool isActive,
+ e_PhysicsEngine physics_engine)
{
- if (gameobj->GetMeshCount() > 0)
+ if (gameobj->GetMeshCount() > 0)
{
switch (physics_engine)
{
@@ -1574,28 +1571,36 @@ void BL_CreateGraphicObjectNew(KX_GameObject* gameobj,
}
}
-void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
- struct Object* blenderobject,
- RAS_MeshObject* meshobj,
- KX_Scene* kxscene,
- int activeLayerBitInfo,
- e_PhysicsEngine physics_engine,
- KX_BlenderSceneConverter *converter,
- bool processCompoundChildren
- )
-
+static void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
+ struct Object* blenderobject,
+ RAS_MeshObject* meshobj,
+ KX_Scene* kxscene,
+ int activeLayerBitInfo,
+ e_PhysicsEngine physics_engine,
+ KX_BlenderSceneConverter *converter,
+ bool processCompoundChildren
+ )
+
{
//SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
//int userigidbody = SYS_GetCommandLineInt(syshandle,"norigidbody",0);
//bool bRigidBody = (userigidbody == 0);
// object has physics representation?
- if (!(blenderobject->gameflag & OB_COLLISION))
+ if (!(blenderobject->gameflag & OB_COLLISION)) {
+ // Respond to all collisions so that Near sensors work on No Collision
+ // objects.
+ gameobj->SetUserCollisionGroup(0xff);
+ gameobj->SetUserCollisionMask(0xff);
return;
+ }
+
+ gameobj->SetUserCollisionGroup(blenderobject->col_group);
+ gameobj->SetUserCollisionMask(blenderobject->col_mask);
// get Root Parent of blenderobject
struct Object* parent= blenderobject->parent;
- while(parent && parent->parent) {
+ while (parent && parent->parent) {
parent= parent->parent;
}
@@ -1694,7 +1699,7 @@ void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
objprop.m_soft_numclusteriterations= blenderobject->bsoft->numclusteriterations; /* number of iterations to refine collision clusters*/
//objprop.m_soft_welding = blenderobject->bsoft->welding; /* welding */
/* disable welding: it doesn't bring any additional stability and it breaks the relation between soft body collision shape and graphic mesh */
- objprop.m_soft_welding = 0.f;
+ objprop.m_soft_welding = 0.f;
objprop.m_margin = blenderobject->bsoft->margin;
objprop.m_contactProcessingThreshold = 0.f;
} else
@@ -1929,8 +1934,7 @@ static KX_GameObject *gameobject_from_blenderobject(
KX_GameObject *gameobj = NULL;
Scene *blenderscene = kxscene->GetBlenderScene();
- switch(ob->type)
- {
+ switch (ob->type) {
case OB_LAMP:
{
KX_LightObject* gamelight = gamelight_from_blamp(ob, static_cast<Lamp*>(ob->data), ob->lay, kxscene, rendertools, converter);
@@ -2086,7 +2090,7 @@ struct parentChildLink {
#include "DNA_constraint_types.h"
//XXX #include "BIF_editconstraint.h"
-bPoseChannel *get_active_posechannel2 (Object *ob)
+static bPoseChannel *get_active_posechannel2 (Object *ob)
{
bArmature *arm= (bArmature*)ob->data;
bPoseChannel *pchan;
@@ -2100,7 +2104,7 @@ bPoseChannel *get_active_posechannel2 (Object *ob)
return NULL;
}
-ListBase *get_active_constraints2(Object *ob)
+static ListBase *get_active_constraints2(Object *ob)
{
if (!ob)
return NULL;
@@ -2119,8 +2123,7 @@ ListBase *get_active_constraints2(Object *ob)
return NULL;
}
-
-void RBJconstraints(Object *ob)//not used
+static void UNUSED_FUNCTION(RBJconstraints)(Object *ob)//not used
{
ListBase *conlist;
bConstraint *curcon;
@@ -2141,7 +2144,8 @@ void RBJconstraints(Object *ob)//not used
#include "KX_IPhysicsController.h"
#include "PHY_DynamicTypes.h"
-KX_IPhysicsController* getPhId(CListValue* sumolist,STR_String busc) {//not used
+#if 0 /* UNUSED */
+static KX_IPhysicsController* getPhId(CListValue* sumolist,STR_String busc) {//not used
for (int j=0;j<sumolist->GetCount();j++)
{
@@ -2151,10 +2155,10 @@ KX_IPhysicsController* getPhId(CListValue* sumolist,STR_String busc) {//not used
}
return 0;
-
}
+#endif
-KX_GameObject* getGameOb(STR_String busc,CListValue* sumolist)
+static KX_GameObject* getGameOb(STR_String busc,CListValue* sumolist)
{
for (int j=0;j<sumolist->GetCount();j++)
@@ -2617,7 +2621,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
KX_SlowParentRelation * slow_parent_relation = KX_SlowParentRelation::New(blenderchild->sf);
pcit->m_gamechildnode->SetParentRelation(slow_parent_relation);
break;
- }
+ }
case PARBONE:
{
// parent this to a bone
@@ -2741,7 +2745,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
}
- }
+ }
// create physics joints
for (i=0;i<sumolist->GetCount();i++)
@@ -2825,7 +2829,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
kxscene->GetPhysicsEnvironment()->setConstraintParam(constraintId,dof,1,-1);
}
dofbit<<=1;
- }
+ }
}
else if (dat->type == PHY_LINEHINGE_CONSTRAINT)
{
diff --git a/source/gameengine/Converter/BL_BlenderDataConversion.h b/source/gameengine/Converter/BL_BlenderDataConversion.h
index e6c35c20f4c..2a7efaac898 100644
--- a/source/gameengine/Converter/BL_BlenderDataConversion.h
+++ b/source/gameengine/Converter/BL_BlenderDataConversion.h
@@ -52,5 +52,4 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
SCA_IInputDevice::KX_EnumInputs ConvertKeyCode(int key_code);
-#endif // __BL_BLENDERDATACONVERSION_H__
-
+#endif /* __BL_BLENDERDATACONVERSION_H__ */
diff --git a/source/gameengine/Converter/BL_DeformableGameObject.h b/source/gameengine/Converter/BL_DeformableGameObject.h
index 61477fb1cac..95e3b7c517d 100644
--- a/source/gameengine/Converter/BL_DeformableGameObject.h
+++ b/source/gameengine/Converter/BL_DeformableGameObject.h
@@ -32,9 +32,9 @@
#ifndef __BL_DEFORMABLEGAMEOBJECT_H__
#define __BL_DEFORMABLEGAMEOBJECT_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
+#endif
#include "DNA_mesh_types.h"
#include "KX_GameObject.h"
@@ -89,7 +89,7 @@ public:
public:
-protected:
+protected:
RAS_Deformer *m_pDeformer;
@@ -104,5 +104,4 @@ protected:
#endif
};
-#endif
-
+#endif /* __BL_DEFORMABLEGAMEOBJECT_H__ */
diff --git a/source/gameengine/Converter/BL_MeshDeformer.cpp b/source/gameengine/Converter/BL_MeshDeformer.cpp
index c9371b9df50..911ff245ab4 100644
--- a/source/gameengine/Converter/BL_MeshDeformer.cpp
+++ b/source/gameengine/Converter/BL_MeshDeformer.cpp
@@ -30,11 +30,10 @@
* \ingroup bgeconv
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// This warning tells us about truncation of __long__ stl-generated names.
-// It can occasionally cause DevStudio to have internal compiler warnings.
-#pragma warning( disable : 4786 )
+#ifdef _MSC_VER
+ /* This warning tells us about truncation of __long__ stl-generated names.
+ * It can occasionally cause DevStudio to have internal compiler warnings. */
+# pragma warning( disable:4786 )
#endif
#include "RAS_IPolygonMaterial.h"
@@ -84,7 +83,7 @@ bool BL_MeshDeformer::Apply(RAS_IPolyMaterial*)
}
BL_MeshDeformer::~BL_MeshDeformer()
-{
+{
if (m_transverts)
delete [] m_transverts;
if (m_transnors)
@@ -155,27 +154,27 @@ void BL_MeshDeformer::RecalcNormals()
v4 = &it.vertex[it.index[i+3]];
co4 = m_transverts[v4->getOrigIndex()];
- n1[0]= co1[0]-co3[0];
- n1[1]= co1[1]-co3[1];
- n1[2]= co1[2]-co3[2];
+ n1[0] = co1[0] - co3[0];
+ n1[1] = co1[1] - co3[1];
+ n1[2] = co1[2] - co3[2];
- n2[0]= co2[0]-co4[0];
- n2[1]= co2[1]-co4[1];
- n2[2]= co2[2]-co4[2];
+ n2[0] = co2[0] - co4[0];
+ n2[1] = co2[1] - co4[1];
+ n2[2] = co2[2] - co4[2];
}
else {
- n1[0]= co1[0]-co2[0];
- n2[0]= co2[0]-co3[0];
- n1[1]= co1[1]-co2[1];
+ n1[0] = co1[0] - co2[0];
+ n2[0] = co2[0] - co3[0];
+ n1[1] = co1[1] - co2[1];
- n2[1]= co2[1]-co3[1];
- n1[2]= co1[2]-co2[2];
- n2[2]= co2[2]-co3[2];
+ n2[1] = co2[1] - co3[1];
+ n1[2] = co1[2] - co2[2];
+ n2[2] = co2[2] - co3[2];
}
- fnor[0]= n1[1]*n2[2] - n1[2]*n2[1];
- fnor[1]= n1[2]*n2[0] - n1[0]*n2[2];
- fnor[2]= n1[0]*n2[1] - n1[1]*n2[0];
+ fnor[0] = n1[1] * n2[2] - n1[2] * n2[1];
+ fnor[1] = n1[2] * n2[0] - n1[0] * n2[2];
+ fnor[2] = n1[0] * n2[1] - n1[1] * n2[0];
normalize_v3(fnor);
/* add to vertices for smooth normals */
diff --git a/source/gameengine/Converter/BL_MeshDeformer.h b/source/gameengine/Converter/BL_MeshDeformer.h
index c84d31c72cd..6e84cdf03f8 100644
--- a/source/gameengine/Converter/BL_MeshDeformer.h
+++ b/source/gameengine/Converter/BL_MeshDeformer.h
@@ -38,9 +38,9 @@
#include "MT_Point3.h"
#include <stdlib.h>
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
+#endif
class BL_DeformableGameObject;
@@ -70,7 +70,7 @@ public:
virtual RAS_Deformer* GetReplica() {return NULL;}
virtual void ProcessReplica();
struct Mesh* GetMesh() { return m_bmesh; }
- virtual class RAS_MeshObject* GetRasMesh() { return (RAS_MeshObject*)m_pMeshObject; }
+ virtual class RAS_MeshObject* GetRasMesh() { return m_pMeshObject; }
virtual float (* GetTransVerts(int *tot))[3] { *tot= m_tvtot; return m_transverts; }
// virtual void InitDeform(double time) {}
diff --git a/source/gameengine/Converter/BL_ModifierDeformer.cpp b/source/gameengine/Converter/BL_ModifierDeformer.cpp
index c1c94c25108..53755deefe1 100644
--- a/source/gameengine/Converter/BL_ModifierDeformer.cpp
+++ b/source/gameengine/Converter/BL_ModifierDeformer.cpp
@@ -29,10 +29,9 @@
* \ingroup bgeconv
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
+#endif
#include "MEM_guardedalloc.h"
#include "BL_ModifierDeformer.h"
@@ -42,7 +41,6 @@
#include "RAS_MeshObject.h"
#include "PHY_IGraphicController.h"
-//#include "BL_ArmatureController.h"
#include "DNA_armature_types.h"
#include "DNA_action_types.h"
#include "DNA_key_types.h"
@@ -65,7 +63,6 @@ extern "C"{
#include "BKE_lattice.h"
#include "BKE_modifier.h"
}
-
#include "BLI_blenlib.h"
#include "BLI_math.h"
@@ -113,7 +110,7 @@ bool BL_ModifierDeformer::HasCompatibleDeformer(Object *ob)
if ((ob->gameflag & OB_SOFT_BODY) != 0)
return false;
ModifierData* md;
- for (md = (ModifierData*)ob->modifiers.first; md; md = (ModifierData*)md->next) {
+ for (md = (ModifierData *)ob->modifiers.first; md; md = md->next) {
if (modifier_dependsOnTime(md))
continue;
if (!(md->mode & eModifierMode_Realtime))
@@ -175,7 +172,7 @@ bool BL_ModifierDeformer::Update(void)
* It may not be the case here because of replace mesh actuator */
Mesh *oldmesh = (Mesh*)blendobj->data;
blendobj->data = m_bmesh;
- /* execute the modifiers */
+ /* execute the modifiers */
DerivedMesh *dm = mesh_create_derived_no_virtual(m_scene, blendobj, m_transverts, CD_MASK_MESH);
/* restore object data */
blendobj->data = oldmesh;
diff --git a/source/gameengine/Converter/BL_ModifierDeformer.h b/source/gameengine/Converter/BL_ModifierDeformer.h
index b4827b1bee4..4efe4ca5bfc 100644
--- a/source/gameengine/Converter/BL_ModifierDeformer.h
+++ b/source/gameengine/Converter/BL_ModifierDeformer.h
@@ -32,9 +32,9 @@
#ifndef __BL_MODIFIERDEFORMER_H__
#define __BL_MODIFIERDEFORMER_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
+#endif
#include "BL_ShapeDeformer.h"
#include "BL_DeformableGameObject.h"
@@ -51,33 +51,34 @@ public:
BL_ModifierDeformer(BL_DeformableGameObject *gameobj,
- Scene *scene,
- Object *bmeshobj,
- RAS_MeshObject *mesh)
- :
- BL_ShapeDeformer(gameobj,bmeshobj, mesh),
- m_lastModifierUpdate(-1),
- m_scene(scene),
- m_dm(NULL)
+ Scene *scene,
+ Object *bmeshobj,
+ RAS_MeshObject *mesh)
+ :
+ BL_ShapeDeformer(gameobj,bmeshobj, mesh),
+ m_lastModifierUpdate(-1),
+ m_scene(scene),
+ m_dm(NULL)
{
m_recalcNormal = false;
- };
+ }
/* this second constructor is needed for making a mesh deformable on the fly. */
BL_ModifierDeformer(BL_DeformableGameObject *gameobj,
- struct Scene *scene,
- struct Object *bmeshobj_old,
- struct Object *bmeshobj_new,
- class RAS_MeshObject *mesh,
- bool release_object,
- BL_ArmatureObject* arma = NULL)
- :
- BL_ShapeDeformer(gameobj, bmeshobj_old, bmeshobj_new, mesh, release_object, false, arma),
- m_lastModifierUpdate(-1),
- m_scene(scene),
- m_dm(NULL)
+ struct Scene *scene,
+ struct Object *bmeshobj_old,
+ struct Object *bmeshobj_new,
+ class RAS_MeshObject *mesh,
+ bool release_object,
+ BL_ArmatureObject* arma = NULL)
+ :
+ BL_ShapeDeformer(gameobj, bmeshobj_old, bmeshobj_new, mesh, release_object, false, arma),
+ m_lastModifierUpdate(-1),
+ m_scene(scene),
+ m_dm(NULL)
{
- };
+ /* pass */
+ }
virtual void ProcessReplica();
virtual RAS_Deformer *GetReplica();
@@ -111,5 +112,4 @@ protected:
#endif
};
-#endif
-
+#endif /* __BL_MODIFIERDEFORMER_H__ */
diff --git a/source/gameengine/Converter/BL_ShapeActionActuator.cpp b/source/gameengine/Converter/BL_ShapeActionActuator.cpp
index c339e10f673..d8b4f6aaf1c 100644
--- a/source/gameengine/Converter/BL_ShapeActionActuator.cpp
+++ b/source/gameengine/Converter/BL_ShapeActionActuator.cpp
@@ -83,7 +83,7 @@ BL_ShapeActionActuator::BL_ShapeActionActuator(SCA_IObject* gameobj,
m_playtype(playtype),
m_priority(priority),
m_action(action),
- m_framepropname(framepropname),
+ m_framepropname(framepropname),
m_propname(propname)
{
m_idptr = new PointerRNA();
@@ -526,15 +526,15 @@ PyAttributeDef BL_ShapeActionActuator::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* BL_ShapeActionActuator::pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *BL_ShapeActionActuator::pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- BL_ShapeActionActuator* self= static_cast<BL_ShapeActionActuator*>(self_v);
+ BL_ShapeActionActuator* self = static_cast<BL_ShapeActionActuator*>(self_v);
return PyUnicode_FromString(self->GetAction() ? self->GetAction()->id.name+2 : "");
}
int BL_ShapeActionActuator::pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- BL_ShapeActionActuator* self= static_cast<BL_ShapeActionActuator*>(self_v);
+ BL_ShapeActionActuator* self = static_cast<BL_ShapeActionActuator*>(self_v);
/* exact copy of BL_ActionActuator's function from here down */
if (!PyUnicode_Check(value))
{
diff --git a/source/gameengine/Converter/BL_ShapeActionActuator.h b/source/gameengine/Converter/BL_ShapeActionActuator.h
index b88631c89d6..f72275b79cf 100644
--- a/source/gameengine/Converter/BL_ShapeActionActuator.h
+++ b/source/gameengine/Converter/BL_ShapeActionActuator.h
@@ -108,7 +108,7 @@ public:
}
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
protected:
@@ -141,5 +141,4 @@ protected:
struct PointerRNA *m_idptr;
};
-#endif
-
+#endif /* __BL_SHAPEACTIONACTUATOR_H__ */
diff --git a/source/gameengine/Converter/BL_ShapeDeformer.cpp b/source/gameengine/Converter/BL_ShapeDeformer.cpp
index b93d731c5e6..f262532e7e2 100644
--- a/source/gameengine/Converter/BL_ShapeDeformer.cpp
+++ b/source/gameengine/Converter/BL_ShapeDeformer.cpp
@@ -29,10 +29,9 @@
* \ingroup bgeconv
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
+#endif
#include "MEM_guardedalloc.h"
#include "BL_ShapeDeformer.h"
@@ -41,7 +40,6 @@
#include "RAS_IPolygonMaterial.h"
#include "RAS_MeshObject.h"
-//#include "BL_ArmatureController.h"
#include "DNA_anim_types.h"
#include "DNA_armature_types.h"
#include "DNA_action_types.h"
@@ -60,7 +58,6 @@ extern "C"{
#include "BKE_lattice.h"
#include "BKE_animsys.h"
}
-
#include "BLI_blenlib.h"
#include "BLI_math.h"
@@ -173,7 +170,7 @@ bool BL_ShapeDeformer::Update(void)
/* store verts locally */
VerifyStorage();
- do_rel_key(0, m_bmesh->totvert, m_bmesh->totvert, (char *)(float *)m_transverts, m_bmesh->key, NULL, 0); /* last arg is ignored */
+ BKE_key_evaluate_relative(0, m_bmesh->totvert, m_bmesh->totvert, (char *)(float *)m_transverts, m_bmesh->key, NULL, 0); /* last arg is ignored */
m_bDynamic = true;
}
diff --git a/source/gameengine/Converter/BL_ShapeDeformer.h b/source/gameengine/Converter/BL_ShapeDeformer.h
index efc1b546666..60f27c85e4f 100644
--- a/source/gameengine/Converter/BL_ShapeDeformer.h
+++ b/source/gameengine/Converter/BL_ShapeDeformer.h
@@ -32,9 +32,9 @@
#ifndef __BL_SHAPEDEFORMER_H__
#define __BL_SHAPEDEFORMER_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
+#endif
#include "BL_SkinDeformer.h"
#include "BL_DeformableGameObject.h"
@@ -73,7 +73,7 @@ public:
};
protected:
- bool m_useShapeDrivers;
+ bool m_useShapeDrivers;
double m_lastShapeUpdate;
struct Key* m_key;
diff --git a/source/gameengine/Converter/BL_SkinDeformer.cpp b/source/gameengine/Converter/BL_SkinDeformer.cpp
index 47cba81798d..e068a91bf7e 100644
--- a/source/gameengine/Converter/BL_SkinDeformer.cpp
+++ b/source/gameengine/Converter/BL_SkinDeformer.cpp
@@ -29,10 +29,9 @@
* \ingroup bgeconv
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
+#endif
// Eigen3 stuff used for BGEDeformVerts
#include <Eigen/Core>
@@ -67,12 +66,12 @@ extern "C"{
#define __NLA_DEFNORMALS
//#undef __NLA_DEFNORMALS
-short get_deformflags(struct Object *bmeshobj)
+static short get_deformflags(struct Object *bmeshobj)
{
short flags = ARM_DEF_VGROUP;
ModifierData *md;
- for (md = (ModifierData*)bmeshobj->modifiers.first; md; md = (ModifierData*)md->next)
+ for (md = (ModifierData *)bmeshobj->modifiers.first; md; md = md->next)
{
if (md->type == eModifierType_Armature)
{
@@ -85,9 +84,9 @@ short get_deformflags(struct Object *bmeshobj)
}
BL_SkinDeformer::BL_SkinDeformer(BL_DeformableGameObject *gameobj,
- struct Object *bmeshobj,
- class RAS_MeshObject *mesh,
- BL_ArmatureObject* arma)
+ struct Object *bmeshobj,
+ class RAS_MeshObject *mesh,
+ BL_ArmatureObject* arma)
: //
BL_MeshDeformer(gameobj, bmeshobj, mesh),
m_armobj(arma),
@@ -110,7 +109,7 @@ BL_SkinDeformer::BL_SkinDeformer(
class RAS_MeshObject *mesh,
bool release_object,
bool recalc_normal,
- BL_ArmatureObject* arma) :
+ BL_ArmatureObject* arma) :
BL_MeshDeformer(gameobj, bmeshobj_old, mesh),
m_armobj(arma),
m_lastArmaUpdate(-1),
@@ -249,7 +248,7 @@ void BL_SkinDeformer::BGEDeformVerts()
int i;
for (i=0, dg=(bDeformGroup*)m_objMesh->defbase.first;
dg;
- ++i, dg=(bDeformGroup*)dg->next)
+ ++i, dg = dg->next)
{
m_dfnrToPC[i] = BKE_pose_channel_find_name(par_arma->pose, dg->name);
@@ -327,7 +326,7 @@ void BL_SkinDeformer::BGEDeformVerts()
bool BL_SkinDeformer::UpdateInternal(bool shape_applied)
{
/* See if the armature has been updated for this frame */
- if (PoseUpdated()) {
+ if (PoseUpdated()) {
if (!shape_applied) {
/* store verts locally */
diff --git a/source/gameengine/Converter/BL_SkinDeformer.h b/source/gameengine/Converter/BL_SkinDeformer.h
index 48c3c3e6186..7495deb2257 100644
--- a/source/gameengine/Converter/BL_SkinDeformer.h
+++ b/source/gameengine/Converter/BL_SkinDeformer.h
@@ -32,9 +32,9 @@
#ifndef __BL_SKINDEFORMER_H__
#define __BL_SKINDEFORMER_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
+#endif /* WIN32 */
#include "CTR_HashedPtr.h"
#include "BL_MeshDeformer.h"
@@ -56,18 +56,18 @@ public:
void SetArmature (class BL_ArmatureObject *armobj);
BL_SkinDeformer(BL_DeformableGameObject *gameobj,
- struct Object *bmeshobj,
- class RAS_MeshObject *mesh,
- BL_ArmatureObject* arma = NULL);
+ struct Object *bmeshobj,
+ class RAS_MeshObject *mesh,
+ BL_ArmatureObject* arma = NULL);
/* this second constructor is needed for making a mesh deformable on the fly. */
BL_SkinDeformer(BL_DeformableGameObject *gameobj,
- struct Object *bmeshobj_old,
- struct Object *bmeshobj_new,
- class RAS_MeshObject *mesh,
- bool release_object,
- bool recalc_normal,
- BL_ArmatureObject* arma = NULL);
+ struct Object *bmeshobj_old,
+ struct Object *bmeshobj_new,
+ class RAS_MeshObject *mesh,
+ bool release_object,
+ bool recalc_normal,
+ BL_ArmatureObject* arma = NULL);
virtual RAS_Deformer *GetReplica();
virtual void ProcessReplica();
@@ -120,5 +120,4 @@ protected:
#endif
};
-#endif
-
+#endif /* __BL_SKINDEFORMER_H__ */
diff --git a/source/gameengine/Converter/BlenderWorldInfo.cpp b/source/gameengine/Converter/BlenderWorldInfo.cpp
index fc3b75c49ad..25da8155867 100644
--- a/source/gameengine/Converter/BlenderWorldInfo.cpp
+++ b/source/gameengine/Converter/BlenderWorldInfo.cpp
@@ -199,7 +199,7 @@ void BlenderWorldInfo::setBackColor(float r, float g, float b)
m_backgroundcolor[2] = b;
}
- void
+ void
BlenderWorldInfo::setMistStart(
float d
) {
@@ -215,7 +215,7 @@ BlenderWorldInfo::setMistDistance(
}
- void
+ void
BlenderWorldInfo::setMistColorRed(
float d
) {
@@ -231,7 +231,7 @@ BlenderWorldInfo::setMistColorGreen(
}
- void
+ void
BlenderWorldInfo::setMistColorBlue(
float d
) {
diff --git a/source/gameengine/Converter/BlenderWorldInfo.h b/source/gameengine/Converter/BlenderWorldInfo.h
index e00eb99e73f..30de5e89269 100644
--- a/source/gameengine/Converter/BlenderWorldInfo.h
+++ b/source/gameengine/Converter/BlenderWorldInfo.h
@@ -73,27 +73,27 @@ public:
float g,
float b
);
- void
+ void
setMistStart(
float d
);
- void
+ void
setMistDistance(
float d
);
- void
+ void
setMistColorRed(
float d
);
- void
+ void
setMistColorGreen(
float d
);
- void
+ void
setMistColorBlue(
float d
);
@@ -104,5 +104,4 @@ public:
#endif
};
-#endif //__BLENDERWORLDINFO_H__
-
+#endif /* __BLENDERWORLDINFO_H__ */
diff --git a/source/gameengine/Converter/CMakeLists.txt b/source/gameengine/Converter/CMakeLists.txt
index 1826f1ad25b..7b801fd4ffb 100644
--- a/source/gameengine/Converter/CMakeLists.txt
+++ b/source/gameengine/Converter/CMakeLists.txt
@@ -49,16 +49,15 @@ set(INC
../../blender/makesdna
../../blender/makesrna
../../blender/windowmanager
- ../../../extern/bullet2/src
- ../../../extern/Eigen3
../../../intern/container
../../../intern/guardedalloc
../../../intern/moto/include
../../../intern/string
- ../../../extern/recastnavigation/Detour/Include
)
set(INC_SYS
+ ../../../extern/recastnavigation/Detour/Include
+ ../../../extern/Eigen3
${PTHREADS_INCLUDE_DIRS}
)
@@ -110,6 +109,9 @@ set(SRC
)
if(WITH_BULLET)
+ list(APPEND INC_SYS
+ ../../../extern/bullet2/src
+ )
add_definitions(-DUSE_BULLET)
endif()
diff --git a/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp b/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp
index f020aab4d50..1e1bc738301 100644
--- a/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp
+++ b/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp
@@ -52,7 +52,7 @@ BL_InterpolatorList::BL_InterpolatorList(bAction *action)
if (action==NULL)
return;
- for (FCurve *fcu= (FCurve *)action->curves.first; fcu; fcu= (FCurve *)fcu->next) {
+ for (FCurve *fcu = (FCurve *)action->curves.first; fcu; fcu = fcu->next) {
if (fcu->rna_path) {
BL_ScalarInterpolator *new_ipo = new BL_ScalarInterpolator(fcu);
//assert(new_ipo);
@@ -78,5 +78,5 @@ KX_IScalarInterpolator *BL_InterpolatorList::GetScalarInterpolator(const char *r
return *i;
}
return NULL;
-}
+}
diff --git a/source/gameengine/Converter/KX_BlenderScalarInterpolator.h b/source/gameengine/Converter/KX_BlenderScalarInterpolator.h
index bc5a6eeef85..d828910233f 100644
--- a/source/gameengine/Converter/KX_BlenderScalarInterpolator.h
+++ b/source/gameengine/Converter/KX_BlenderScalarInterpolator.h
@@ -65,7 +65,7 @@ public:
BL_InterpolatorList(struct bAction *action);
~BL_InterpolatorList();
- KX_IScalarInterpolator *GetScalarInterpolator(const char *rna_path, int array_index);
+ KX_IScalarInterpolator *GetScalarInterpolator(const char *rna_path, int array_index);
#ifdef WITH_CXX_GUARDEDALLOC
@@ -73,5 +73,4 @@ public:
#endif
};
-#endif //__KX_BLENDERSCALARINTERPOLATOR_H__
-
+#endif /* __KX_BLENDERSCALARINTERPOLATOR_H__ */
diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp
index 1c3352454a2..30a4209965e 100644
--- a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp
+++ b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp
@@ -29,9 +29,8 @@
* \ingroup bgeconv
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786) // suppress stl-MSVC debug info warning
+#ifdef _MSC_VER
+# pragma warning (disable:4786) /* suppress stl-MSVC debug info warning */
#endif
#include "KX_Scene.h"
@@ -160,7 +159,7 @@ KX_BlenderSceneConverter::~KX_BlenderSceneConverter()
while (itmat != m_materials.end()) {
delete (*itmat).second;
itmat++;
- }
+ }
vector<pair<KX_Scene*,RAS_MeshObject*> >::iterator itm = m_meshobjects.begin();
@@ -201,7 +200,7 @@ bool KX_BlenderSceneConverter::TryAndLoadNewFile()
// if not, clear the newfilename
else
{
- m_newfilename = "";
+ m_newfilename = "";
}
*/
return result;
@@ -335,7 +334,7 @@ void KX_BlenderSceneConverter::ConvertScene(class KX_Scene* destinationscene,
ccdPhysEnv->setDebugMode(btIDebugDraw::DBG_DrawWireframe|btIDebugDraw::DBG_DrawAabb|btIDebugDraw::DBG_DrawContactPoints|btIDebugDraw::DBG_DrawText|btIDebugDraw::DBG_DrawConstraintLimits|btIDebugDraw::DBG_DrawConstraints);
//todo: get a button in blender ?
- //disable / enable debug drawing (contact points, aabb's etc)
+ //disable / enable debug drawing (contact points, aabb's etc)
//ccdPhysEnv->setDebugMode(1);
destinationscene->SetPhysicsEnvironment(ccdPhysEnv);
break;
@@ -689,7 +688,7 @@ void KX_BlenderSceneConverter::ResetPhysicsObjectsAnimationIpo(bool clearIpo)
void KX_BlenderSceneConverter::resetNoneDynamicObjectToIpo()
{
- if (addInitFromFrame) {
+ if (addInitFromFrame) {
KX_SceneList* scenes = m_ketsjiEngine->CurrentScenes();
int numScenes = scenes->size();
if (numScenes>=0) {
@@ -704,7 +703,7 @@ void KX_BlenderSceneConverter::resetNoneDynamicObjectToIpo()
if (blenderobject->type==OB_ARMATURE)
continue;
float eu[3];
- mat4_to_eul(eu,blenderobject->obmat);
+ mat4_to_eul(eu,blenderobject->obmat);
MT_Point3 pos = MT_Point3(
blenderobject->obmat[3][0],
blenderobject->obmat[3][1],
@@ -779,8 +778,8 @@ void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
//const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
const MT_Matrix3x3& orn = gameObj->NodeGetWorldOrientation();
- float eulerAngles[3];
- float eulerAnglesOld[3] = {0.0f, 0.0f, 0.0f};
+ float eulerAngles[3];
+ float eulerAnglesOld[3] = {0.0f, 0.0f, 0.0f};
float tmat[3][3];
// XXX animato
@@ -819,13 +818,13 @@ void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
if (icu_rz) icu_rz->ipo = IPO_LIN;
}
- if (icu_rx) eulerAnglesOld[0]= eval_icu( icu_rx, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
- if (icu_ry) eulerAnglesOld[1]= eval_icu( icu_ry, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
- if (icu_rz) eulerAnglesOld[2]= eval_icu( icu_rz, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
+ if (icu_rx) eulerAnglesOld[0] = eval_icu( icu_rx, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
+ if (icu_ry) eulerAnglesOld[1] = eval_icu( icu_ry, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
+ if (icu_rz) eulerAnglesOld[2] = eval_icu( icu_rz, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
// orn.getValue((float *)tmat); // uses the wrong ordering, cant use this
- for (int r=0;r<3;r++)
- for (int c=0;c<3;c++)
+ for (int r = 0; r < 3; r++)
+ for (int c = 0; c < 3; c++)
tmat[r][c] = orn[c][r];
// mat3_to_eul( eulerAngles,tmat); // better to use Mat3ToCompatibleEul
@@ -945,7 +944,7 @@ static void load_datablocks(Main *main_newlib, BlendHandle *bpy_openlib, const c
int i=0;
LinkNode *n= names;
- while(n) {
+ while (n) {
BLO_library_append_named_part(main_tmp, &bpy_openlib, (char *)n->link, idcode);
n= (LinkNode *)n->next;
i++;
@@ -984,7 +983,7 @@ bool KX_BlenderSceneConverter::LinkBlendFile(BlendHandle *bpy_openlib, const cha
}
main_newlib= (Main *)MEM_callocN( sizeof(Main), "BgeMain");
- BKE_reports_init(&reports, RPT_STORE);
+ BKE_reports_init(&reports, RPT_STORE);
load_datablocks(main_newlib, bpy_openlib, path, idcode);
@@ -1000,11 +999,11 @@ bool KX_BlenderSceneConverter::LinkBlendFile(BlendHandle *bpy_openlib, const cha
BLO_blendhandle_close(bpy_openlib);
BKE_reports_clear(&reports);
- /* done linking */
+ /* done linking */
/* needed for lookups*/
GetMainDynamic().push_back(main_newlib);
- strncpy(main_newlib->name, path, sizeof(main_newlib->name));
+ strncpy(main_newlib->name, path, sizeof(main_newlib->name));
if (idcode==ID_ME) {
@@ -1028,7 +1027,7 @@ bool KX_BlenderSceneConverter::LinkBlendFile(BlendHandle *bpy_openlib, const cha
scene_merge->GetLogicManager()->RegisterActionName(action->name+2, action);
}
}
- else if (idcode==ID_SCE) {
+ else if (idcode==ID_SCE) {
/* Merge all new linked in scene into the existing one */
ID *scene;
for (scene= (ID *)main_newlib->scene.first; scene; scene= (ID *)scene->next ) {
@@ -1117,7 +1116,7 @@ bool KX_BlenderSceneConverter::FreeBlendFile(struct Main *maggie)
{
RAS_MeshObject *meshobj= (RAS_MeshObject *) *mapStringToMeshes.at(i);
if (meshobj && IS_TAGGED(meshobj->GetMesh()))
- {
+ {
STR_HashedString mn = meshobj->GetName();
mapStringToMeshes.remove(mn);
m_map_mesh_to_gamemesh.remove(CHashedPtr(meshobj->GetMesh()));
@@ -1171,7 +1170,7 @@ bool KX_BlenderSceneConverter::FreeBlendFile(struct Main *maggie)
else {
/* free the mesh, we could be referecing a linked one! */
int mesh_index= gameobj->GetMeshCount();
- while(mesh_index--) {
+ while (mesh_index--) {
mesh= gameobj->GetMesh(mesh_index);
if (IS_TAGGED(mesh->GetMesh())) {
gameobj->RemoveMeshes(); /* XXX - slack, should only remove meshes that are library items but mostly objects only have 1 mesh */
@@ -1255,7 +1254,7 @@ bool KX_BlenderSceneConverter::FreeBlendFile(struct Main *maggie)
RAS_IPolyMaterial *mat= (*polymit).second;
Material *bmat= NULL;
- /* Why do we need to check for RAS_BLENDERMAT if both are cast to a (PyObject*)? - Campbell */
+ /* Why do we need to check for RAS_BLENDERMAT if both are cast to a (PyObject *)? - Campbell */
if (mat->GetFlag() & RAS_BLENDERMAT) {
KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(mat);
bmat= bl_mat->GetBlenderMaterial();
@@ -1280,7 +1279,7 @@ bool KX_BlenderSceneConverter::FreeBlendFile(struct Main *maggie)
RAS_IPolyMaterial *mat= (*polymit).second;
Material *bmat= NULL;
- /* Why do we need to check for RAS_BLENDERMAT if both are cast to a (PyObject*)? - Campbell */
+ /* Why do we need to check for RAS_BLENDERMAT if both are cast to a (PyObject *)? - Campbell */
if (mat->GetFlag() & RAS_BLENDERMAT) {
KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(mat);
bmat= bl_mat->GetBlenderMaterial();
@@ -1451,14 +1450,12 @@ RAS_MeshObject *KX_BlenderSceneConverter::ConvertMeshSpecial(KX_Scene* kx_scene,
BLI_remlink(&m_maggie->mat, mat_new);
BLI_addtail(&maggie->mat, mat_new);
- mesh->mat[i]= mat_new;
+ mesh->mat[i] = mat_new;
/* the same material may be used twice */
- for (int j=i+1; j<mesh->totcol; j++)
- {
- if (mesh->mat[j]==mat_old)
- {
- mesh->mat[j]= mat_new;
+ for (int j = i + 1; j < mesh->totcol; j++) {
+ if (mesh->mat[j] == mat_old) {
+ mesh->mat[j] = mat_new;
mat_new->id.us++;
mat_old->id.us--;
}
diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.h b/source/gameengine/Converter/KX_BlenderSceneConverter.h
index b51c2f21ca7..34a1117a0eb 100644
--- a/source/gameengine/Converter/KX_BlenderSceneConverter.h
+++ b/source/gameengine/Converter/KX_BlenderSceneConverter.h
@@ -165,11 +165,11 @@ public:
printf("\t m_materials: %d\n", (int)m_materials.size());
printf("\nMappings...\n");
- printf("\t m_map_blender_to_gameobject: %d\n", (int)m_map_blender_to_gameobject.size());
- printf("\t m_map_mesh_to_gamemesh: %d\n", (int)m_map_mesh_to_gamemesh.size());
- printf("\t m_map_blender_to_gameactuator: %d\n", (int)m_map_blender_to_gameactuator.size());
- printf("\t m_map_blender_to_gamecontroller: %d\n", (int)m_map_blender_to_gamecontroller.size());
- printf("\t m_map_blender_to_gameAdtList: %d\n", (int)m_map_blender_to_gameAdtList.size());
+ printf("\t m_map_blender_to_gameobject: %d\n", m_map_blender_to_gameobject.size());
+ printf("\t m_map_mesh_to_gamemesh: %d\n", m_map_mesh_to_gamemesh.size());
+ printf("\t m_map_blender_to_gameactuator: %d\n", m_map_blender_to_gameactuator.size());
+ printf("\t m_map_blender_to_gamecontroller: %d\n", m_map_blender_to_gamecontroller.size());
+ printf("\t m_map_blender_to_gameAdtList: %d\n", m_map_blender_to_gameAdtList.size());
#ifdef WITH_CXX_GUARDEDALLOC
MEM_printmemlist_pydict();
@@ -196,5 +196,4 @@ public:
#endif
};
-#endif //__KX_BLENDERSCENECONVERTER_H__
-
+#endif /* __KX_BLENDERSCENECONVERTER_H__ */
diff --git a/source/gameengine/Converter/KX_ConvertActuators.cpp b/source/gameengine/Converter/KX_ConvertActuators.cpp
index 9caa6bbf579..24d321730eb 100644
--- a/source/gameengine/Converter/KX_ConvertActuators.cpp
+++ b/source/gameengine/Converter/KX_ConvertActuators.cpp
@@ -30,10 +30,9 @@
* \ingroup bgeconv
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
+#endif
#include <math.h>
@@ -105,22 +104,25 @@
#include "BL_BlenderDataConversion.h"
/**
- * KX_BLENDERTRUNC needed to round 'almost' zero values to zero, else velocities etc. are incorrectly set
+ * KX_flt_trunc needed to round 'almost' zero values to zero, else velocities etc. are incorrectly set
*/
-#define KX_BLENDERTRUNC(x) (( x < 0.0001f && x > -0.0001f ) ? 0.0f : x)
+BLI_INLINE float KX_flt_trunc(const float x)
+{
+ return ( x < 0.0001f && x > -0.0001f ) ? 0.0f : x;
+}
void BL_ConvertActuators(const char* maggiename,
- struct Object* blenderobject,
- KX_GameObject* gameobj,
- SCA_LogicManager* logicmgr,
- KX_Scene* scene,
- KX_KetsjiEngine* ketsjiEngine,
- int activeLayerBitInfo,
- bool isInActiveLayer,
- RAS_IRenderTools* rendertools,
- KX_BlenderSceneConverter* converter
- )
+ struct Object* blenderobject,
+ KX_GameObject* gameobj,
+ SCA_LogicManager* logicmgr,
+ KX_Scene* scene,
+ KX_KetsjiEngine* ketsjiEngine,
+ int activeLayerBitInfo,
+ bool isInActiveLayer,
+ RAS_IRenderTools* rendertools,
+ KX_BlenderSceneConverter* converter
+ )
{
int uniqueint = 0;
@@ -134,7 +136,7 @@ void BL_ConvertActuators(const char* maggiename,
}
gameobj->ReserveActuator(actcount);
bact = (bActuator*) blenderobject->actuators.first;
- while(bact)
+ while (bact)
{
STR_String uniquename = bact->name;
STR_String& objectname = gameobj->GetName();
@@ -146,20 +148,23 @@ void BL_ConvertActuators(const char* maggiename,
{
bObjectActuator* obact = (bObjectActuator*) bact->data;
KX_GameObject* obref = NULL;
- MT_Vector3 forcevec(KX_BLENDERTRUNC(obact->forceloc[0]),
- KX_BLENDERTRUNC(obact->forceloc[1]),
- KX_BLENDERTRUNC(obact->forceloc[2]));
- MT_Vector3 torquevec(obact->forcerot[0],obact->forcerot[1],obact->forcerot[2]);
- MT_Vector3 dlocvec ( KX_BLENDERTRUNC(obact->dloc[0]),
- KX_BLENDERTRUNC(obact->dloc[1]),
- KX_BLENDERTRUNC(obact->dloc[2]));
- MT_Vector3 drotvec ( KX_BLENDERTRUNC(obact->drot[0]),obact->drot[1],obact->drot[2]);
- MT_Vector3 linvelvec ( KX_BLENDERTRUNC(obact->linearvelocity[0]),
- KX_BLENDERTRUNC(obact->linearvelocity[1]),
- KX_BLENDERTRUNC(obact->linearvelocity[2]));
- MT_Vector3 angvelvec ( KX_BLENDERTRUNC(obact->angularvelocity[0]),
- KX_BLENDERTRUNC(obact->angularvelocity[1]),
- KX_BLENDERTRUNC(obact->angularvelocity[2]));
+ MT_Vector3 forcevec(KX_flt_trunc(obact->forceloc[0]),
+ KX_flt_trunc(obact->forceloc[1]),
+ KX_flt_trunc(obact->forceloc[2]));
+ MT_Vector3 torquevec(obact->forcerot[0],
+ obact->forcerot[1],
+ obact->forcerot[2]);
+ MT_Vector3 dlocvec(KX_flt_trunc(obact->dloc[0]),
+ KX_flt_trunc(obact->dloc[1]),
+ KX_flt_trunc(obact->dloc[2]));
+ MT_Vector3 drotvec(KX_flt_trunc(obact->drot[0]),
+ obact->drot[1],obact->drot[2]);
+ MT_Vector3 linvelvec(KX_flt_trunc(obact->linearvelocity[0]),
+ KX_flt_trunc(obact->linearvelocity[1]),
+ KX_flt_trunc(obact->linearvelocity[2]));
+ MT_Vector3 angvelvec(KX_flt_trunc(obact->angularvelocity[0]),
+ KX_flt_trunc(obact->angularvelocity[1]),
+ KX_flt_trunc(obact->angularvelocity[2]));
short damping = obact->damping;
/* Blender uses a bit vector internally for the local-flags. In */
@@ -181,17 +186,17 @@ void BL_ConvertActuators(const char* maggiename,
obref = converter->FindGameObject(obact->reference);
}
- KX_ObjectActuator* tmpbaseact = new KX_ObjectActuator(gameobj,
- obref,
- forcevec.getValue(),
- torquevec.getValue(),
- dlocvec.getValue(),
- drotvec.getValue(),
- linvelvec.getValue(),
- angvelvec.getValue(),
- damping,
- bitLocalFlag
- );
+ KX_ObjectActuator* tmpbaseact = new KX_ObjectActuator(
+ gameobj,
+ obref,
+ forcevec.getValue(),
+ torquevec.getValue(),
+ dlocvec.getValue(),
+ drotvec.getValue(),
+ linvelvec.getValue(),
+ angvelvec.getValue(),
+ damping,
+ bitLocalFlag);
baseact = tmpbaseact;
break;
}
@@ -210,22 +215,22 @@ void BL_ConvertActuators(const char* maggiename,
if (actact->flag & ACT_IPOCHILD) ipo_flags |= BL_Action::ACT_IPOFLAG_CHILD;
BL_ActionActuator* tmpbaseact = new BL_ActionActuator(
- gameobj,
- propname,
- propframe,
- actact->sta,
- actact->end,
- actact->act,
- actact->type, // + 1, because Blender starts to count at zero,
- actact->blendin,
- actact->priority,
- actact->layer,
- actact->layer_weight,
- ipo_flags,
- actact->end_reset,
- actact->stridelength
- // Ketsji at 1, because zero is reserved for "NoDef"
- );
+ gameobj,
+ propname,
+ propframe,
+ actact->sta,
+ actact->end,
+ actact->act,
+ actact->type, // + 1, because Blender starts to count at zero,
+ actact->blendin,
+ actact->priority,
+ actact->layer,
+ actact->layer_weight,
+ ipo_flags,
+ actact->end_reset,
+ actact->stridelength
+ // Ketsji at 1, because zero is reserved for "NoDef"
+ );
baseact= tmpbaseact;
break;
}
@@ -237,18 +242,17 @@ void BL_ConvertActuators(const char* maggiename,
STR_String propframe = (actact->frameProp ? actact->frameProp : "");
BL_ShapeActionActuator* tmpbaseact = new BL_ShapeActionActuator(
- gameobj,
- propname,
- propframe,
- actact->sta,
- actact->end,
- actact->act,
- actact->type, // + 1, because Blender starts to count at zero,
- actact->blendin,
- actact->priority,
- actact->stridelength
- // Ketsji at 1, because zero is reserved for "NoDef"
- );
+ gameobj,
+ propname,
+ propframe,
+ actact->sta,
+ actact->end,
+ actact->act,
+ actact->type, // + 1, because Blender starts to count at zero,
+ actact->blendin,
+ actact->priority,
+ actact->stridelength);
+ // Ketsji at 1, because zero is reserved for "NoDef"
baseact= tmpbaseact;
break;
}
@@ -267,17 +271,17 @@ void BL_ConvertActuators(const char* maggiename,
bool ipo_add = (ipoact->flag & ACT_IPOADD);
KX_IpoActuator* tmpbaseact = new KX_IpoActuator(
- gameobj,
- propname ,
- frameProp,
- ipoact->sta,
- ipoact->end,
- ipochild,
- ipoact->type + 1, // + 1, because Blender starts to count at zero,
- // Ketsji at 1, because zero is reserved for "NoDef"
- ipo_as_force,
- ipo_add,
- local);
+ gameobj,
+ propname ,
+ frameProp,
+ ipoact->sta,
+ ipoact->end,
+ ipochild,
+ ipoact->type + 1, // + 1, because Blender starts to count at zero,
+ // Ketsji at 1, because zero is reserved for "NoDef"
+ ipo_as_force,
+ ipo_add,
+ local);
baseact = tmpbaseact;
break;
}
@@ -293,14 +297,14 @@ void BL_ConvertActuators(const char* maggiename,
/* visifac, fac and axis are not copied from the struct... */
/* that's some internal state... */
- KX_CameraActuator *tmpcamact
- = new KX_CameraActuator(gameobj,
- tmpgob,
- camact->height,
- camact->min,
- camact->max,
- camact->axis,
- camact->damping);
+ KX_CameraActuator *tmpcamact = new KX_CameraActuator(
+ gameobj,
+ tmpgob,
+ camact->height,
+ camact->min,
+ camact->max,
+ camact->axis,
+ camact->damping);
baseact = tmpcamact;
}
break;
@@ -333,14 +337,13 @@ void BL_ConvertActuators(const char* maggiename,
? (char*) msgAct->body
: "");
- KX_NetworkMessageActuator *tmpmsgact =
- new KX_NetworkMessageActuator(
- gameobj, // actuator controlling object
- scene->GetNetworkScene(), // needed for replication
- toPropName,
- subject,
- bodyType,
- body);
+ KX_NetworkMessageActuator *tmpmsgact = new KX_NetworkMessageActuator(
+ gameobj, // actuator controlling object
+ scene->GetNetworkScene(), // needed for replication
+ toPropName,
+ subject,
+ bodyType,
+ body);
baseact = tmpmsgact;
break;
}
@@ -355,7 +358,7 @@ void BL_ConvertActuators(const char* maggiename,
KX_SoundActuator::KX_SOUNDACT_TYPE
soundActuatorType = KX_SoundActuator::KX_SOUNDACT_NODEF;
- switch(soundact->type) {
+ switch (soundact->type) {
case ACT_SND_PLAY_STOP_SOUND:
soundActuatorType = KX_SoundActuator::KX_SOUNDACT_PLAYSTOP;
break;
@@ -457,11 +460,11 @@ void BL_ConvertActuators(const char* maggiename,
destinationObj = converter->FindGameObject(propact->ob);
SCA_PropertyActuator* tmppropact = new SCA_PropertyActuator(
- gameobj,
- destinationObj,
- propact->name,
- propact->value,
- propact->type+1); // + 1 because Ketsji Logic starts
+ gameobj,
+ destinationObj,
+ propact->name,
+ propact->value,
+ propact->type + 1); // + 1 because Ketsji Logic starts
// with 0 for KX_ACT_PROP_NODEF
baseact = tmppropact;
break;
@@ -491,18 +494,16 @@ void BL_ConvertActuators(const char* maggiename,
}
}
- KX_SCA_AddObjectActuator* tmpaddact =
- new KX_SCA_AddObjectActuator(
- gameobj,
- originalval,
- editobact->time,
- scene,
- editobact->linVelocity,
- (editobact->localflag & ACT_EDOB_LOCAL_LINV)!=0,
- editobact->angVelocity,
- (editobact->localflag & ACT_EDOB_LOCAL_ANGV)!=0
- );
-
+ KX_SCA_AddObjectActuator* tmpaddact = new KX_SCA_AddObjectActuator(
+ gameobj,
+ originalval,
+ editobact->time,
+ scene,
+ editobact->linVelocity,
+ (editobact->localflag & ACT_EDOB_LOCAL_LINV) != 0,
+ editobact->angVelocity,
+ (editobact->localflag & ACT_EDOB_LOCAL_ANGV) != 0);
+
//editobact->ob to gameobj
baseact = tmpaddact;
}
@@ -519,23 +520,20 @@ void BL_ConvertActuators(const char* maggiename,
RAS_MeshObject *tmpmesh = NULL;
if (editobact->me)
tmpmesh = BL_ConvertMesh(
- editobact->me,
- blenderobject,
- scene,
- converter
- );
+ editobact->me,
+ blenderobject,
+ scene,
+ converter
+ );
- KX_SCA_ReplaceMeshActuator* tmpreplaceact
- = new KX_SCA_ReplaceMeshActuator(
- gameobj,
- tmpmesh,
- scene,
- (editobact->flag & ACT_EDOB_REPLACE_MESH_NOGFX)==0,
- (editobact->flag & ACT_EDOB_REPLACE_MESH_PHYS)!=0
-
- );
-
- baseact = tmpreplaceact;
+ KX_SCA_ReplaceMeshActuator* tmpreplaceact = new KX_SCA_ReplaceMeshActuator(
+ gameobj,
+ tmpmesh,
+ scene,
+ (editobact->flag & ACT_EDOB_REPLACE_MESH_NOGFX) == 0,
+ (editobact->flag & ACT_EDOB_REPLACE_MESH_PHYS) != 0);
+
+ baseact = tmpreplaceact;
}
break;
case ACT_EDOB_TRACK_TO:
@@ -544,25 +542,23 @@ void BL_ConvertActuators(const char* maggiename,
if (editobact->ob)
originalval = converter->FindGameObject(editobact->ob);
- KX_TrackToActuator* tmptrackact
- = new KX_TrackToActuator(gameobj,
- originalval,
- editobact->time,
- editobact->flag,
- blenderobject->trackflag,
- blenderobject->upflag
- );
- baseact = tmptrackact;
+ KX_TrackToActuator* tmptrackact = new KX_TrackToActuator(
+ gameobj,
+ originalval,
+ editobact->time,
+ editobact->flag,
+ blenderobject->trackflag,
+ blenderobject->upflag);
+ baseact = tmptrackact;
break;
}
case ACT_EDOB_DYNAMICS:
{
- KX_SCA_DynamicActuator* tmpdynact
- = new KX_SCA_DynamicActuator(gameobj,
- editobact->dyn_operation,
- editobact->mass
- );
- baseact = tmpdynact;
+ KX_SCA_DynamicActuator* tmpdynact = new KX_SCA_DynamicActuator(
+ gameobj,
+ editobact->dyn_operation,
+ editobact->mass);
+ baseact = tmpdynact;
}
}
break;
@@ -694,17 +690,17 @@ void BL_ConvertActuators(const char* maggiename,
; /* error */
}
}
- KX_ConstraintActuator *tmpconact
- = new KX_ConstraintActuator(gameobj,
- conact->damp,
- conact->rotdamp,
- min,
- max,
- conact->maxrot,
- locrot,
- conact->time,
- conact->flag,
- prop);
+ KX_ConstraintActuator *tmpconact = new KX_ConstraintActuator(
+ gameobj,
+ conact->damp,
+ conact->rotdamp,
+ min,
+ max,
+ conact->maxrot,
+ locrot,
+ conact->time,
+ conact->flag,
+ prop);
baseact = tmpconact;
break;
}
@@ -777,13 +773,14 @@ void BL_ConvertActuators(const char* maggiename,
default:
; /* flag error */
}
- tmpsceneact = new KX_SceneActuator(gameobj,
- mode,
- scene,
- ketsjiEngine,
- nextSceneName,
- cam);
- baseact = tmpsceneact;
+ tmpsceneact = new KX_SceneActuator(
+ gameobj,
+ mode,
+ scene,
+ ketsjiEngine,
+ nextSceneName,
+ cam);
+ baseact = tmpsceneact;
break;
}
case ACT_GAME:
@@ -832,13 +829,14 @@ void BL_ConvertActuators(const char* maggiename,
default:
; /* flag error */
}
- tmpgameact = new KX_GameActuator(gameobj,
- mode,
- filename,
- loadinganimationname,
- scene,
- ketsjiEngine);
- baseact = tmpgameact;
+ tmpgameact = new KX_GameActuator(
+ gameobj,
+ mode,
+ filename,
+ loadinganimationname,
+ scene,
+ ketsjiEngine);
+ baseact = tmpgameact;
break;
}
@@ -903,14 +901,15 @@ void BL_ConvertActuators(const char* maggiename,
modeArg = SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL;
break;
default:
- ; /* error */
+ ; /* error */
}
- tmprandomact = new SCA_RandomActuator(gameobj,
- seedArg,
- modeArg,
- paraArg1,
- paraArg2,
- randAct->propname);
+ tmprandomact = new SCA_RandomActuator(
+ gameobj,
+ seedArg,
+ modeArg,
+ paraArg1,
+ paraArg2,
+ randAct->propname);
baseact = tmprandomact;
}
break;
@@ -947,8 +946,7 @@ void BL_ConvertActuators(const char* maggiename,
SCA_2DFilterActuator *tmp = NULL;
RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode;
- switch(_2dfilter->type)
- {
+ switch (_2dfilter->type) {
case ACT_2DFILTER_MOTIONBLUR:
filtermode = RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR;
break;
@@ -999,8 +997,9 @@ void BL_ConvertActuators(const char* maggiename,
break;
}
- tmp = new SCA_2DFilterActuator(gameobj, filtermode, _2dfilter->flag,
- _2dfilter->float_arg,_2dfilter->int_arg,ketsjiEngine->GetRasterizer(),scene);
+ tmp = new SCA_2DFilterActuator(gameobj, filtermode, _2dfilter->flag,
+ _2dfilter->float_arg, _2dfilter->int_arg,
+ ketsjiEngine->GetRasterizer(), scene);
if (_2dfilter->text)
{
@@ -1026,8 +1025,7 @@ void BL_ConvertActuators(const char* maggiename,
bool ghost = true;
KX_GameObject *tmpgob = NULL;
- switch(parAct->type)
- {
+ switch (parAct->type) {
case ACT_PARENT_SET:
mode = KX_ParentActuator::KX_PARENT_SET;
tmpgob = converter->FindGameObject(parAct->ob);
@@ -1055,7 +1053,15 @@ void BL_ConvertActuators(const char* maggiename,
bArmatureActuator* armAct = (bArmatureActuator*) bact->data;
KX_GameObject *tmpgob = converter->FindGameObject(armAct->target);
KX_GameObject *subgob = converter->FindGameObject(armAct->subtarget);
- BL_ArmatureActuator* tmparmact = new BL_ArmatureActuator(gameobj, armAct->type, armAct->posechannel, armAct->constraint, tmpgob, subgob, armAct->weight, armAct->influence);
+ BL_ArmatureActuator* tmparmact = new BL_ArmatureActuator(
+ gameobj,
+ armAct->type,
+ armAct->posechannel,
+ armAct->constraint,
+ tmpgob,
+ subgob,
+ armAct->weight,
+ armAct->influence);
baseact = tmparmact;
break;
}
@@ -1073,8 +1079,7 @@ void BL_ConvertActuators(const char* maggiename,
KX_GameObject *targetob = converter->FindGameObject(stAct->target);
int mode = KX_SteeringActuator::KX_STEERING_NODEF;
- switch(stAct->type)
- {
+ switch (stAct->type) {
case ACT_STEERING_SEEK:
mode = KX_SteeringActuator::KX_STEERING_SEEK;
break;
diff --git a/source/gameengine/Converter/KX_ConvertActuators.h b/source/gameengine/Converter/KX_ConvertActuators.h
index b7c890458cc..385d274bf89 100644
--- a/source/gameengine/Converter/KX_ConvertActuators.h
+++ b/source/gameengine/Converter/KX_ConvertActuators.h
@@ -33,16 +33,14 @@
#define __KX_CONVERTACTUATORS_H__
void BL_ConvertActuators(const char* maggiename,
- struct Object* blenderobject,
- class KX_GameObject* gameobj,
- class SCA_LogicManager* logicmgr,
- class KX_Scene* scene,
- class KX_KetsjiEngine* ketsjiEngine,
- int activeLayerBitInfo,
- bool isInActiveLayer,
- class RAS_IRenderTools* rendertools,
- class KX_BlenderSceneConverter* converter);
-
-
-#endif //__KX_CONVERTACTUATORS_H__
+ struct Object* blenderobject,
+ class KX_GameObject* gameobj,
+ class SCA_LogicManager* logicmgr,
+ class KX_Scene* scene,
+ class KX_KetsjiEngine* ketsjiEngine,
+ int activeLayerBitInfo,
+ bool isInActiveLayer,
+ class RAS_IRenderTools* rendertools,
+ class KX_BlenderSceneConverter* converter);
+#endif /* __KX_CONVERTACTUATORS_H__ */
diff --git a/source/gameengine/Converter/KX_ConvertControllers.cpp b/source/gameengine/Converter/KX_ConvertControllers.cpp
index 81778928c2e..769abd01ce0 100644
--- a/source/gameengine/Converter/KX_ConvertControllers.cpp
+++ b/source/gameengine/Converter/KX_ConvertControllers.cpp
@@ -69,7 +69,7 @@
static void
LinkControllerToActuators(
SCA_IController *game_controller,
- bController* bcontr,
+ bController* bcontr,
SCA_LogicManager* logicmgr,
KX_BlenderSceneConverter* converter
) {
@@ -110,8 +110,7 @@ void BL_ConvertControllers(
while (bcontr)
{
SCA_IController* gamecontroller = NULL;
- switch(bcontr->type)
- {
+ switch (bcontr->type) {
case CONT_LOGIC_AND:
{
gamecontroller = new SCA_ANDController(gameobj);
diff --git a/source/gameengine/Converter/KX_ConvertControllers.h b/source/gameengine/Converter/KX_ConvertControllers.h
index d1d52f866ec..817a49e1b2f 100644
--- a/source/gameengine/Converter/KX_ConvertControllers.h
+++ b/source/gameengine/Converter/KX_ConvertControllers.h
@@ -43,6 +43,4 @@ void BL_ConvertControllers(
class KX_BlenderSceneConverter* converter
);
-
-#endif //__KX_CONVERTCONTROLLERS_H__
-
+#endif /* __KX_CONVERTCONTROLLERS_H__ */
diff --git a/source/gameengine/Converter/KX_ConvertProperties.cpp b/source/gameengine/Converter/KX_ConvertProperties.cpp
index faa7780bac0..7222c673322 100644
--- a/source/gameengine/Converter/KX_ConvertProperties.cpp
+++ b/source/gameengine/Converter/KX_ConvertProperties.cpp
@@ -67,15 +67,14 @@ void BL_ConvertProperties(Object* object,KX_GameObject* gameobj,SCA_TimeEventMan
{
bProperty* prop = (bProperty*)object->prop.first;
- CValue* propval;
+ CValue* propval;
bool show_debug_info;
- while(prop)
- {
-
+
+ while (prop) {
propval = NULL;
show_debug_info = bool (prop->flag & PROP_DEBUG);
- switch(prop->type) {
+ switch (prop->type) {
case GPROP_BOOL:
{
propval = new CBoolValue((bool)(prop->data != 0));
@@ -177,14 +176,14 @@ void BL_ConvertTextProperty(Object* object, KX_FontObject* fontobj,SCA_TimeEvent
{
CValue* tprop = fontobj->GetProperty("Text");
if (!tprop) return;
- bProperty* prop = get_ob_property(object, "Text");
+ bProperty* prop = BKE_bproperty_object_get(object, "Text");
if (!prop) return;
Curve *curve = static_cast<Curve *>(object->data);
STR_String str = curve->str;
CValue* propval = NULL;
- switch(prop->type) {
+ switch (prop->type) {
case GPROP_BOOL:
{
int value = atoi(str);
diff --git a/source/gameengine/Converter/KX_ConvertProperties.h b/source/gameengine/Converter/KX_ConvertProperties.h
index 345af3bfa74..8f96cc21af6 100644
--- a/source/gameengine/Converter/KX_ConvertProperties.h
+++ b/source/gameengine/Converter/KX_ConvertProperties.h
@@ -38,5 +38,4 @@ void BL_ConvertProperties(struct Object* object,
class SCA_IScene* scene,
bool isInActiveLayer);
-#endif //__KX_CONVERTPROPERTIES_H__
-
+#endif /* __KX_CONVERTPROPERTIES_H__ */
diff --git a/source/gameengine/Converter/KX_ConvertSensors.cpp b/source/gameengine/Converter/KX_ConvertSensors.cpp
index 9f155a6ebc3..538f9e2c833 100644
--- a/source/gameengine/Converter/KX_ConvertSensors.cpp
+++ b/source/gameengine/Converter/KX_ConvertSensors.cpp
@@ -33,17 +33,17 @@
#include <stdio.h>
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
+#endif
#include "wm_event_types.h"
#include "KX_BlenderSceneConverter.h"
#include "KX_ConvertSensors.h"
/* This little block needed for linking to Blender... */
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#include "BLI_winstuff.h"
+#ifdef _MSC_VER
+# include "BLI_winstuff.h"
#endif
#include "DNA_object_types.h"
@@ -118,8 +118,8 @@ void BL_ConvertSensors(struct Object* blenderobject,
}
gameobj->ReserveSensor(count);
sens = (bSensor*)blenderobject->sensors.first;
- while(sens)
- {
+
+ while (sens) {
SCA_ISensor* gamesensor=NULL;
/* All sensors have a pulse toggle, frequency, and invert field. */
/* These are extracted here, and set when the sensor is added to the */
@@ -183,7 +183,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
if (gameobj->GetPhysicsController())
- {
+ {
gamesensor = new KX_TouchSensor(eventmgr,
gameobj,
bFindMaterial,
@@ -209,7 +209,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
}
bool bFindMaterial = true;
if (gameobj->GetPhysicsController())
- {
+ {
gamesensor = new KX_TouchSensor(eventmgr,
gameobj,
bFindMaterial,
@@ -224,7 +224,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
KX_NetworkEventManager* eventmgr = (KX_NetworkEventManager*)
logicmgr->FindEventManager(SCA_EventManager::NETWORK_EVENTMGR);
if (eventmgr) {
- bMessageSensor* msgSens = (bMessageSensor*) sens->data;
+ bMessageSensor* msgSens = (bMessageSensor*) sens->data;
/* Get our NetworkScene */
NG_NetworkScene *NetworkScene = kxscene->GetNetworkScene();
@@ -247,7 +247,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::TOUCH_EVENTMGR);
if (eventmgr)
{
- STR_String nearpropertyname;
+ STR_String nearpropertyname;
bNearSensor* blendernearsensor = (bNearSensor*)sens->data;
if (blendernearsensor->name)
{
@@ -311,7 +311,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
}
case SENS_MOUSE:
{
- int keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_NODEF;
+ int keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_NODEF;
int trackfocus = 0;
bMouseSensor *bmouse = (bMouseSensor *)sens->data;
@@ -398,7 +398,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
/* Better do an explicit conversion here! (was implicit */
/* before...) */
- switch(blenderpropsensor->type) {
+ switch (blenderpropsensor->type) {
case SENS_PROP_EQUAL:
propchecktype = SCA_PropertySensor::KX_PROPSENSOR_EQUAL;
break;
@@ -573,8 +573,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
int hatf =0;
int prec =0;
- switch(bjoy->type)
- {
+ switch (bjoy->type) {
case SENS_JOY_AXIS:
axis = bjoy->axis;
axisf = bjoy->axisf;
@@ -633,13 +632,13 @@ void BL_ConvertSensors(struct Object* blenderobject,
uniqueval->Release();
/* Conversion succeeded, so we can set the generic props here. */
- gamesensor->SetPulseMode(pos_pulsemode,
- neg_pulsemode,
- frequency);
+ gamesensor->SetPulseMode(pos_pulsemode,
+ neg_pulsemode,
+ frequency);
gamesensor->SetInvert(invert);
gamesensor->SetLevel(level);
gamesensor->SetTap(tap);
- gamesensor->SetName(sens->name);
+ gamesensor->SetName(sens->name);
gameobj->AddSensor(gamesensor);
diff --git a/source/gameengine/Converter/KX_ConvertSensors.h b/source/gameengine/Converter/KX_ConvertSensors.h
index 0694815c77e..56248721a37 100644
--- a/source/gameengine/Converter/KX_ConvertSensors.h
+++ b/source/gameengine/Converter/KX_ConvertSensors.h
@@ -42,5 +42,4 @@ void BL_ConvertSensors(struct Object* blenderobject,
class RAS_ICanvas* canvas,
class KX_BlenderSceneConverter* converter);
-#endif //__KX_CONVERTSENSORS_H__
-
+#endif /* __KX_CONVERTSENSORS_H__ */
diff --git a/source/gameengine/Converter/KX_IpoConvert.cpp b/source/gameengine/Converter/KX_IpoConvert.cpp
index 309959b4324..a81d52f6698 100644
--- a/source/gameengine/Converter/KX_IpoConvert.cpp
+++ b/source/gameengine/Converter/KX_IpoConvert.cpp
@@ -29,10 +29,9 @@
* \ingroup bgeconv
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// don't show stl-warnings
-#pragma warning (disable:4786)
+#ifdef _MSC_VER
+ /* don't show stl-warnings */
+# pragma warning (disable:4786)
#endif
#include "BKE_material.h" /* give_current_material */
@@ -76,12 +75,12 @@ static BL_InterpolatorList *GetAdtList(struct bAction *for_act, KX_BlenderSceneC
{
BL_InterpolatorList *adtList= converter->FindInterpolatorList(for_act);
- if (!adtList) {
+ if (!adtList) {
adtList = new BL_InterpolatorList(for_act);
converter->RegisterInterpolatorList(adtList, for_act);
}
- return adtList;
+ return adtList;
}
SG_Controller *BL_CreateIPO(struct bAction *action, KX_GameObject* gameobj, KX_BlenderSceneConverter *converter)
@@ -97,7 +96,7 @@ SG_Controller *BL_CreateIPO(struct bAction *action, KX_GameObject* gameobj, KX_B
const char *rotmode, *drotmode;
- switch(blenderobject->rotmode) {
+ switch (blenderobject->rotmode) {
case ROT_MODE_AXISANGLE:
rotmode = "rotation_axis_angle";
drotmode = "delta_rotation_axis_angle";
@@ -441,7 +440,7 @@ static void ConvertMaterialIpos(
}
interpolator= new KX_ScalarInterpolator(&ipocontr->m_ref, sinterp);
ipocontr->AddInterpolator(interpolator);
- }
+ }
if ((sinterp = adtList->GetScalarInterpolator("emit", 0))) {
if (!ipocontr) {
@@ -452,7 +451,7 @@ static void ConvertMaterialIpos(
interpolator= new KX_ScalarInterpolator(&ipocontr->m_emit, sinterp);
ipocontr->AddInterpolator(interpolator);
}
- }
+ }
}
void BL_ConvertMaterialIpos(
diff --git a/source/gameengine/Converter/KX_IpoConvert.h b/source/gameengine/Converter/KX_IpoConvert.h
index 7bb2df978f6..861a2ba66f2 100644
--- a/source/gameengine/Converter/KX_IpoConvert.h
+++ b/source/gameengine/Converter/KX_IpoConvert.h
@@ -66,5 +66,4 @@ void BL_ConvertMaterialIpos(struct Object* blenderobject,
class KX_BlenderSceneConverter *converter);
-#endif //__KX_IPOCONVERT_H__
-
+#endif /* __KX_IPOCONVERT_H__ */
diff --git a/source/gameengine/Converter/KX_SoftBodyDeformer.cpp b/source/gameengine/Converter/KX_SoftBodyDeformer.cpp
index e3c12c2b966..72d0c8733f2 100644
--- a/source/gameengine/Converter/KX_SoftBodyDeformer.cpp
+++ b/source/gameengine/Converter/KX_SoftBodyDeformer.cpp
@@ -30,8 +30,8 @@
*/
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
#endif //WIN32
#include "MT_assert.h"
diff --git a/source/gameengine/Converter/KX_SoftBodyDeformer.h b/source/gameengine/Converter/KX_SoftBodyDeformer.h
index d692d45eb18..d7bc088e1c0 100644
--- a/source/gameengine/Converter/KX_SoftBodyDeformer.h
+++ b/source/gameengine/Converter/KX_SoftBodyDeformer.h
@@ -32,9 +32,9 @@
#ifndef __KX_SOFTBODYDEFORMER_H__
#define __KX_SOFTBODYDEFORMER_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
+#endif
#include "RAS_Deformer.h"
#include "BL_DeformableGameObject.h"
diff --git a/source/gameengine/Expressions/BoolValue.cpp b/source/gameengine/Expressions/BoolValue.cpp
index 40997a25be1..ee913877c96 100644
--- a/source/gameengine/Expressions/BoolValue.cpp
+++ b/source/gameengine/Expressions/BoolValue.cpp
@@ -104,39 +104,37 @@ this object
{
CValue *ret;
- switch(dtype)
- {
- case VALUE_EMPTY_TYPE:
- case VALUE_BOOL_TYPE:
+ switch (dtype) {
+ case VALUE_EMPTY_TYPE:
+ case VALUE_BOOL_TYPE:
{
- switch(op)
- {
- case VALUE_AND_OPERATOR:
+ switch (op) {
+ case VALUE_AND_OPERATOR:
{
ret = new CBoolValue (((CBoolValue *) val)->GetBool() && m_bool);
break;
}
- case VALUE_OR_OPERATOR:
+ case VALUE_OR_OPERATOR:
{
ret = new CBoolValue (((CBoolValue *) val)->GetBool() || m_bool);
break;
}
- case VALUE_EQL_OPERATOR:
+ case VALUE_EQL_OPERATOR:
{
ret = new CBoolValue (((CBoolValue *) val)->GetBool() == m_bool);
break;
}
- case VALUE_NEQ_OPERATOR:
+ case VALUE_NEQ_OPERATOR:
{
ret = new CBoolValue (((CBoolValue *) val)->GetBool() != m_bool);
break;
}
- case VALUE_NOT_OPERATOR:
+ case VALUE_NOT_OPERATOR:
{
return new CBoolValue (!m_bool);
break;
}
- default:
+ default:
{
ret = new CErrorValue(val->GetText() + op2str(op) +
"[operator not allowed on booleans]");
@@ -145,16 +143,15 @@ this object
}
break;
}
- case VALUE_STRING_TYPE:
+ case VALUE_STRING_TYPE:
{
- switch(op)
- {
- case VALUE_ADD_OPERATOR:
+ switch (op) {
+ case VALUE_ADD_OPERATOR:
{
ret = new CStringValue(val->GetText() + GetText(),"");
break;
}
- default:
+ default:
{
ret = new CErrorValue(val->GetText() + op2str(op) + "[Only + allowed on boolean and string]");
break;
@@ -162,8 +159,8 @@ this object
}
break;
}
- default:
- ret = new CErrorValue("[type mismatch]" + op2str(op) + GetText());
+ default:
+ ret = new CErrorValue("[type mismatch]" + op2str(op) + GetText());
}
return ret;
@@ -205,7 +202,7 @@ CValue* CBoolValue::GetReplica()
}
#ifdef WITH_PYTHON
-PyObject* CBoolValue::ConvertValueToPython()
+PyObject *CBoolValue::ConvertValueToPython()
{
return PyBool_FromLong(m_bool != 0);
}
diff --git a/source/gameengine/Expressions/BoolValue.h b/source/gameengine/Expressions/BoolValue.h
index 09e931ea661..b88c839a58e 100644
--- a/source/gameengine/Expressions/BoolValue.h
+++ b/source/gameengine/Expressions/BoolValue.h
@@ -29,7 +29,7 @@
class CBoolValue : public CPropValue
{
- //PLUGIN_DECLARE_SERIAL(CBoolValue,CValue)
+ //PLUGIN_DECLARE_SERIAL(CBoolValue,CValue)
public:
static const STR_String sTrueString;
@@ -61,5 +61,4 @@ private:
#endif
};
-#endif // !defined __BOOLVALUE_H__
-
+#endif /* __BOOLVALUE_H__ */
diff --git a/source/gameengine/Expressions/ConstExpr.h b/source/gameengine/Expressions/ConstExpr.h
index 86d411cef26..768f2bbd10e 100644
--- a/source/gameengine/Expressions/ConstExpr.h
+++ b/source/gameengine/Expressions/ConstExpr.h
@@ -51,5 +51,4 @@ private:
#endif
};
-#endif // !defined(AFX_CONSTEXPR_H__061ECFC3_BE87_11D1_A51C_00A02472FC58__INCLUDED_)
-
+#endif /* __CONSTEXPR_H__ */
diff --git a/source/gameengine/Expressions/EXP_C-Api.cpp b/source/gameengine/Expressions/EXP_C-Api.cpp
index 763d115a840..2822fd8f6de 100644
--- a/source/gameengine/Expressions/EXP_C-Api.cpp
+++ b/source/gameengine/Expressions/EXP_C-Api.cpp
@@ -102,8 +102,8 @@ int EXP_IsValid(EXP_ValueHandle inval)
/* assign property 'propval' to 'destinationval' */
void EXP_SetProperty(EXP_ValueHandle destinationval,
- const char* propname,
- EXP_ValueHandle propval)
+ const char *propname,
+ EXP_ValueHandle propval)
{
((CValue*) destinationval)->SetProperty(propname,(CValue*)propval);
}
diff --git a/source/gameengine/Expressions/EXP_C-Api.h b/source/gameengine/Expressions/EXP_C-Api.h
index 6be1e57481c..d73b0a209d4 100644
--- a/source/gameengine/Expressions/EXP_C-Api.h
+++ b/source/gameengine/Expressions/EXP_C-Api.h
@@ -53,7 +53,7 @@ extern void EXP_ReleaseValue(EXP_ValueHandle);
extern int EXP_IsValid(EXP_ValueHandle);
/* assign property 'propval' to 'destinationval' */
-extern void EXP_SetProperty(EXP_ValueHandle propval,EXP_ValueHandle destinationval);
+extern void EXP_SetProperty(EXP_ValueHandle destinationval, const char *propname, EXP_ValueHandle propval);
/* returns NULL if property doesn't exist */
extern EXP_ValueHandle EXP_GetProperty(EXP_ValueHandle inval,const char* propname);
@@ -64,5 +64,4 @@ const char* EXP_GetText(EXP_ValueHandle);
}
#endif
-#endif //__EXP_C_API_H__
-
+#endif /* __EXP_C_API_H__ */
diff --git a/source/gameengine/Expressions/EmptyValue.h b/source/gameengine/Expressions/EmptyValue.h
index 54920359f3f..8eccb97e0f5 100644
--- a/source/gameengine/Expressions/EmptyValue.h
+++ b/source/gameengine/Expressions/EmptyValue.h
@@ -45,5 +45,4 @@ public:
#endif
};
-#endif // !defined __EMPTYVALUE_H__
-
+#endif /* __EMPTYVALUE_H__ */
diff --git a/source/gameengine/Expressions/ErrorValue.h b/source/gameengine/Expressions/ErrorValue.h
index 12bc7c7ffcb..0095528254e 100644
--- a/source/gameengine/Expressions/ErrorValue.h
+++ b/source/gameengine/Expressions/ErrorValue.h
@@ -43,5 +43,4 @@ private:
#endif
};
-#endif // !defined __ERRORVALUE_H__
-
+#endif /* __ERRORVALUE_H__ */
diff --git a/source/gameengine/Expressions/Expression.h b/source/gameengine/Expressions/Expression.h
index 5f5db505331..d1b7eda43f0 100644
--- a/source/gameengine/Expressions/Expression.h
+++ b/source/gameengine/Expressions/Expression.h
@@ -146,5 +146,4 @@ protected:
#endif
};
-#endif // !defined __EXPRESSION_H__
-
+#endif /* __EXPRESSION_H__ */
diff --git a/source/gameengine/Expressions/FloatValue.cpp b/source/gameengine/Expressions/FloatValue.cpp
index 403338573e2..b7d7f528155 100644
--- a/source/gameengine/Expressions/FloatValue.cpp
+++ b/source/gameengine/Expressions/FloatValue.cpp
@@ -120,138 +120,134 @@ ret: a new object containing the result of applying operator op to val and
{
CValue *ret;
- switch(dtype)
- {
- case VALUE_INT_TYPE:
+ switch (dtype) {
+ case VALUE_INT_TYPE:
{
- switch (op)
- {
- case VALUE_MOD_OPERATOR:
- ret = new CFloatValue(fmod(((CIntValue *) val)->GetInt(), m_float));
- break;
- case VALUE_ADD_OPERATOR:
- ret = new CFloatValue(((CIntValue *) val)->GetInt() + m_float);
- break;
- case VALUE_SUB_OPERATOR:
- ret = new CFloatValue(((CIntValue *) val)->GetInt() - m_float);
- break;
- case VALUE_MUL_OPERATOR:
- ret = new CFloatValue(((CIntValue *) val)->GetInt() * m_float);
- break;
- case VALUE_DIV_OPERATOR:
- if (m_float == 0)
- ret = new CErrorValue("Division by zero");
- else
- ret = new CFloatValue (((CIntValue *) val)->GetInt() / m_float);
- break;
- case VALUE_EQL_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() == m_float);
- break;
- case VALUE_NEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() != m_float);
- break;
- case VALUE_GRE_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() > m_float);
- break;
- case VALUE_LES_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() < m_float);
- break;
- case VALUE_GEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() >= m_float);
- break;
- case VALUE_LEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() <= m_float);
- break;
- default:
- ret = new CErrorValue("illegal operator. please send a bug report.");
- break;
+ switch (op) {
+ case VALUE_MOD_OPERATOR:
+ ret = new CFloatValue(fmod(((CIntValue *) val)->GetInt(), m_float));
+ break;
+ case VALUE_ADD_OPERATOR:
+ ret = new CFloatValue(((CIntValue *) val)->GetInt() + m_float);
+ break;
+ case VALUE_SUB_OPERATOR:
+ ret = new CFloatValue(((CIntValue *) val)->GetInt() - m_float);
+ break;
+ case VALUE_MUL_OPERATOR:
+ ret = new CFloatValue(((CIntValue *) val)->GetInt() * m_float);
+ break;
+ case VALUE_DIV_OPERATOR:
+ if (m_float == 0)
+ ret = new CErrorValue("Division by zero");
+ else
+ ret = new CFloatValue (((CIntValue *) val)->GetInt() / m_float);
+ break;
+ case VALUE_EQL_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() == m_float);
+ break;
+ case VALUE_NEQ_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() != m_float);
+ break;
+ case VALUE_GRE_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() > m_float);
+ break;
+ case VALUE_LES_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() < m_float);
+ break;
+ case VALUE_GEQ_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() >= m_float);
+ break;
+ case VALUE_LEQ_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() <= m_float);
+ break;
+ default:
+ ret = new CErrorValue("illegal operator. please send a bug report.");
+ break;
}
break;
}
- case VALUE_EMPTY_TYPE:
- case VALUE_FLOAT_TYPE:
+ case VALUE_EMPTY_TYPE:
+ case VALUE_FLOAT_TYPE:
{
- switch (op)
- {
- case VALUE_MOD_OPERATOR:
- ret = new CFloatValue(fmod(((CFloatValue *) val)->GetFloat(), m_float));
- break;
- case VALUE_ADD_OPERATOR:
- ret = new CFloatValue(((CFloatValue *) val)->GetFloat() + m_float);
- break;
- case VALUE_SUB_OPERATOR:
- ret = new CFloatValue(((CFloatValue *) val)->GetFloat() - m_float);
- break;
- case VALUE_MUL_OPERATOR:
- ret = new CFloatValue(((CFloatValue *) val)->GetFloat() * m_float);
- break;
- case VALUE_DIV_OPERATOR:
- if (m_float == 0)
- ret = new CErrorValue("Division by zero");
- else
- ret = new CFloatValue (((CFloatValue *) val)->GetFloat() / m_float);
- break;
- case VALUE_EQL_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() == m_float);
- break;
- case VALUE_NEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() != m_float);
- break;
- case VALUE_GRE_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() > m_float);
- break;
- case VALUE_LES_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() < m_float);
- break;
- case VALUE_GEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() >= m_float);
- break;
- case VALUE_LEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() <= m_float);
- break;
- case VALUE_NEG_OPERATOR:
- ret = new CFloatValue (-m_float);
- break;
- case VALUE_POS_OPERATOR:
- ret = new CFloatValue (m_float);
- break;
-
- default:
- ret = new CErrorValue("illegal operator. please send a bug report.");
- break;
+ switch (op) {
+ case VALUE_MOD_OPERATOR:
+ ret = new CFloatValue(fmod(((CFloatValue *) val)->GetFloat(), m_float));
+ break;
+ case VALUE_ADD_OPERATOR:
+ ret = new CFloatValue(((CFloatValue *) val)->GetFloat() + m_float);
+ break;
+ case VALUE_SUB_OPERATOR:
+ ret = new CFloatValue(((CFloatValue *) val)->GetFloat() - m_float);
+ break;
+ case VALUE_MUL_OPERATOR:
+ ret = new CFloatValue(((CFloatValue *) val)->GetFloat() * m_float);
+ break;
+ case VALUE_DIV_OPERATOR:
+ if (m_float == 0)
+ ret = new CErrorValue("Division by zero");
+ else
+ ret = new CFloatValue (((CFloatValue *) val)->GetFloat() / m_float);
+ break;
+ case VALUE_EQL_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() == m_float);
+ break;
+ case VALUE_NEQ_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() != m_float);
+ break;
+ case VALUE_GRE_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() > m_float);
+ break;
+ case VALUE_LES_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() < m_float);
+ break;
+ case VALUE_GEQ_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() >= m_float);
+ break;
+ case VALUE_LEQ_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() <= m_float);
+ break;
+ case VALUE_NEG_OPERATOR:
+ ret = new CFloatValue (-m_float);
+ break;
+ case VALUE_POS_OPERATOR:
+ ret = new CFloatValue (m_float);
+ break;
+
+ default:
+ ret = new CErrorValue("illegal operator. please send a bug report.");
+ break;
}
break;
}
- case VALUE_STRING_TYPE:
+ case VALUE_STRING_TYPE:
{
- switch(op)
- {
- case VALUE_ADD_OPERATOR:
- ret = new CStringValue(val->GetText() + GetText(),"");
- break;
- case VALUE_EQL_OPERATOR:
- case VALUE_NEQ_OPERATOR:
- case VALUE_GRE_OPERATOR:
- case VALUE_LES_OPERATOR:
- case VALUE_GEQ_OPERATOR:
- case VALUE_LEQ_OPERATOR:
- ret = new CErrorValue("[Cannot compare string with float]" + op2str(op) + GetText());
- break;
- default:
- ret = new CErrorValue("[operator not allowed on strings]" + op2str(op) + GetText());
- break;
+ switch (op) {
+ case VALUE_ADD_OPERATOR:
+ ret = new CStringValue(val->GetText() + GetText(),"");
+ break;
+ case VALUE_EQL_OPERATOR:
+ case VALUE_NEQ_OPERATOR:
+ case VALUE_GRE_OPERATOR:
+ case VALUE_LES_OPERATOR:
+ case VALUE_GEQ_OPERATOR:
+ case VALUE_LEQ_OPERATOR:
+ ret = new CErrorValue("[Cannot compare string with float]" + op2str(op) + GetText());
+ break;
+ default:
+ ret = new CErrorValue("[operator not allowed on strings]" + op2str(op) + GetText());
+ break;
}
break;
}
- case VALUE_BOOL_TYPE:
- ret = new CErrorValue("[operator not valid on boolean and float]" + op2str(op) + GetText());
- break;
- case VALUE_ERROR_TYPE:
- ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
- break;
- default:
- ret = new CErrorValue("illegal type. contact your dealer (if any)");
- break;
+ case VALUE_BOOL_TYPE:
+ ret = new CErrorValue("[operator not valid on boolean and float]" + op2str(op) + GetText());
+ break;
+ case VALUE_ERROR_TYPE:
+ ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
+ break;
+ default:
+ ret = new CErrorValue("illegal type. contact your dealer (if any)");
+ break;
}
return ret;
}
@@ -314,7 +310,7 @@ CValue* CFloatValue::GetReplica()
#ifdef WITH_PYTHON
-PyObject* CFloatValue::ConvertValueToPython()
+PyObject *CFloatValue::ConvertValueToPython()
{
return PyFloat_FromDouble(m_float);
}
diff --git a/source/gameengine/Expressions/FloatValue.h b/source/gameengine/Expressions/FloatValue.h
index 59311e5d373..bc6a2d052d4 100644
--- a/source/gameengine/Expressions/FloatValue.h
+++ b/source/gameengine/Expressions/FloatValue.h
@@ -54,5 +54,4 @@ protected:
#endif
};
-#endif // !defined __FLOATVALUE_H__
-
+#endif /* __FLOATVALUE_H__ */
diff --git a/source/gameengine/Expressions/IdentifierExpr.h b/source/gameengine/Expressions/IdentifierExpr.h
index 58e75c4b02e..26eb3691378 100644
--- a/source/gameengine/Expressions/IdentifierExpr.h
+++ b/source/gameengine/Expressions/IdentifierExpr.h
@@ -56,5 +56,4 @@ public:
#endif
};
-#endif //__IDENTIFIEREXPR_H__
-
+#endif /* __IDENTIFIEREXPR_H__ */
diff --git a/source/gameengine/Expressions/IfExpr.h b/source/gameengine/Expressions/IfExpr.h
index f8ed81168d0..80e35471d82 100644
--- a/source/gameengine/Expressions/IfExpr.h
+++ b/source/gameengine/Expressions/IfExpr.h
@@ -16,12 +16,8 @@
* \ingroup expressions
*/
-#if !defined(AFX_IFEXPR_H__1F691841_C5C7_11D1_A863_0000B4542BD8__INCLUDED_)
-#define AFX_IFEXPR_H__1F691841_C5C7_11D1_A863_0000B4542BD8__INCLUDED_
-
-#if defined(_MSC_VER) && _MSC_VER >= 1000
-#pragma once
-#endif // _MSC_VER >= 1000
+#ifndef __IFEXPR_H__
+#define __IFEXPR_H__
#include "Expression.h"
@@ -55,5 +51,4 @@ public:
#endif
};
-#endif // !defined(AFX_IFEXPR_H__1F691841_C5C7_11D1_A863_0000B4542BD8__INCLUDED_)
-
+#endif /* __IFEXPR_H__ */
diff --git a/source/gameengine/Expressions/InputParser.cpp b/source/gameengine/Expressions/InputParser.cpp
index 58837235d30..0a5af4a18ea 100644
--- a/source/gameengine/Expressions/InputParser.cpp
+++ b/source/gameengine/Expressions/InputParser.cpp
@@ -187,11 +187,10 @@ void CParser::NextSym()
// sets the global variable cellcoord to the kind of operator
errmsg = NULL;
- while(ch == ' ' || ch == 0x9)
+ while (ch == ' ' || ch == 0x9)
NextCh();
- switch(ch)
- {
+ switch (ch) {
case '(':
sym = lbracksym; NextCh();
break;
@@ -359,7 +358,7 @@ STR_String CParser::Symbol2Str(int s)
{
// returns a string representation of of symbol s,
// for use in Term when generating an error
- switch(s) {
+ switch (s) {
case errorsym: return "error";
case lbracksym: return "(";
case rbracksym: return ")";
@@ -394,7 +393,7 @@ int CParser::Priority(int optorkind)
{
// returns the priority of an operator
// higher number means higher priority
- switch(optorkind) {
+ switch (optorkind) {
case OPor: return 1;
case OPand: return 2;
case OPgreater:
@@ -426,102 +425,103 @@ CExpression *CParser::Ex(int i)
opkind2 = opkind;
NextSym();
e2 = Ex(i + 1);
- switch(opkind2) {
- case OPmodulus: e1 = new COperator2Expr(VALUE_MOD_OPERATOR,e1, e2); break;
- case OPplus: e1 = new COperator2Expr(VALUE_ADD_OPERATOR,e1, e2); break;
- case OPminus: e1 = new COperator2Expr(VALUE_SUB_OPERATOR,e1, e2); break;
- case OPtimes: e1 = new COperator2Expr(VALUE_MUL_OPERATOR,e1, e2); break;
- case OPdivide: e1 = new COperator2Expr(VALUE_DIV_OPERATOR,e1, e2); break;
- case OPand: e1 = new COperator2Expr(VALUE_AND_OPERATOR,e1, e2); break;
- case OPor: e1 = new COperator2Expr(VALUE_OR_OPERATOR,e1, e2); break;
- case OPequal: e1 = new COperator2Expr(VALUE_EQL_OPERATOR,e1, e2); break;
- case OPunequal: e1 = new COperator2Expr(VALUE_NEQ_OPERATOR,e1, e2); break;
- case OPgreater: e1 = new COperator2Expr(VALUE_GRE_OPERATOR,e1, e2); break;
- case OPless: e1 = new COperator2Expr(VALUE_LES_OPERATOR,e1, e2); break;
- case OPgreaterequal: e1 = new COperator2Expr(VALUE_GEQ_OPERATOR,e1, e2); break;
- case OPlessequal: e1 = new COperator2Expr(VALUE_LEQ_OPERATOR,e1, e2); break;
- default: MT_assert(false); break; // should not happen
+ switch (opkind2) {
+ case OPmodulus: e1 = new COperator2Expr(VALUE_MOD_OPERATOR,e1, e2); break;
+ case OPplus: e1 = new COperator2Expr(VALUE_ADD_OPERATOR,e1, e2); break;
+ case OPminus: e1 = new COperator2Expr(VALUE_SUB_OPERATOR,e1, e2); break;
+ case OPtimes: e1 = new COperator2Expr(VALUE_MUL_OPERATOR,e1, e2); break;
+ case OPdivide: e1 = new COperator2Expr(VALUE_DIV_OPERATOR,e1, e2); break;
+ case OPand: e1 = new COperator2Expr(VALUE_AND_OPERATOR,e1, e2); break;
+ case OPor: e1 = new COperator2Expr(VALUE_OR_OPERATOR,e1, e2); break;
+ case OPequal: e1 = new COperator2Expr(VALUE_EQL_OPERATOR,e1, e2); break;
+ case OPunequal: e1 = new COperator2Expr(VALUE_NEQ_OPERATOR,e1, e2); break;
+ case OPgreater: e1 = new COperator2Expr(VALUE_GRE_OPERATOR,e1, e2); break;
+ case OPless: e1 = new COperator2Expr(VALUE_LES_OPERATOR,e1, e2); break;
+ case OPgreaterequal: e1 = new COperator2Expr(VALUE_GEQ_OPERATOR,e1, e2); break;
+ case OPlessequal: e1 = new COperator2Expr(VALUE_LEQ_OPERATOR,e1, e2); break;
+ default: MT_assert(false); break; // should not happen
}
}
} else if (i == NUM_PRIORITY) {
- if ((sym == opsym)
- && ( (opkind == OPminus) || (opkind == OPnot) || (opkind == OPplus) )
- )
+ if ((sym == opsym)
+ && ( (opkind == OPminus) || (opkind == OPnot) || (opkind == OPplus) )
+ )
{
NextSym();
- switch(opkind) {
- /* +1 is also a valid number! */
- case OPplus: e1 = new COperator1Expr(VALUE_POS_OPERATOR, Ex(NUM_PRIORITY)); break;
- case OPminus: e1 = new COperator1Expr(VALUE_NEG_OPERATOR, Ex(NUM_PRIORITY)); break;
- case OPnot: e1 = new COperator1Expr(VALUE_NOT_OPERATOR, Ex(NUM_PRIORITY)); break;
- default: {
- // should not happen
- e1 = Error("operator +, - or ! expected");
- }
+ switch (opkind) {
+ /* +1 is also a valid number! */
+ case OPplus: e1 = new COperator1Expr(VALUE_POS_OPERATOR, Ex(NUM_PRIORITY)); break;
+ case OPminus: e1 = new COperator1Expr(VALUE_NEG_OPERATOR, Ex(NUM_PRIORITY)); break;
+ case OPnot: e1 = new COperator1Expr(VALUE_NOT_OPERATOR, Ex(NUM_PRIORITY)); break;
+ default:
+ {
+ // should not happen
+ e1 = Error("operator +, - or ! expected");
+ }
}
}
else {
- switch(sym) {
- case constsym: {
- switch(constkind) {
- case booltype:
- e1 = new CConstExpr(new CBoolValue(boolvalue));
- break;
- case inttype:
- {
- cInt temp;
- temp = strtoll(const_as_string, NULL, 10); /* atoi is for int only */
- e1 = new CConstExpr(new CIntValue(temp));
- break;
- }
- case floattype:
- {
- double temp;
- temp = atof(const_as_string);
- e1 = new CConstExpr(new CFloatValue(temp));
- break;
+ switch (sym) {
+ case constsym: {
+ switch (constkind) {
+ case booltype:
+ e1 = new CConstExpr(new CBoolValue(boolvalue));
+ break;
+ case inttype:
+ {
+ cInt temp;
+ temp = strtoll(const_as_string, NULL, 10); /* atoi is for int only */
+ e1 = new CConstExpr(new CIntValue(temp));
+ break;
+ }
+ case floattype:
+ {
+ double temp;
+ temp = atof(const_as_string);
+ e1 = new CConstExpr(new CFloatValue(temp));
+ break;
+ }
+ case stringtype:
+ e1 = new CConstExpr(new CStringValue(const_as_string,""));
+ break;
+ default :
+ MT_assert(false);
+ break;
}
- case stringtype:
- e1 = new CConstExpr(new CStringValue(const_as_string,""));
- break;
- default :
- MT_assert(false);
+ NextSym();
break;
}
- NextSym();
- break;
- }
- case lbracksym:
- NextSym();
- e1 = Ex(1);
- Term(rbracksym);
- break;
- case ifsym:
- {
- CExpression *e3;
- NextSym();
- Term(lbracksym);
- e1 = Ex(1);
- Term(commasym);
- e2 = Ex(1);
- if (sym == commasym) {
+ case lbracksym:
NextSym();
- e3 = Ex(1);
- } else {
- e3 = new CConstExpr(new CEmptyValue());
+ e1 = Ex(1);
+ Term(rbracksym);
+ break;
+ case ifsym:
+ {
+ CExpression *e3;
+ NextSym();
+ Term(lbracksym);
+ e1 = Ex(1);
+ Term(commasym);
+ e2 = Ex(1);
+ if (sym == commasym) {
+ NextSym();
+ e3 = Ex(1);
+ } else {
+ e3 = new CConstExpr(new CEmptyValue());
+ }
+ Term(rbracksym);
+ e1 = new CIfExpr(e1, e2, e3);
+ break;
}
- Term(rbracksym);
- e1 = new CIfExpr(e1, e2, e3);
- break;
- }
- case idsym:
+ case idsym:
{
e1 = new CIdentifierExpr(const_as_string,m_identifierContext);
NextSym();
break;
}
- case errorsym:
+ case errorsym:
{
MT_assert(!e1);
STR_String errtext="[no info]";
@@ -530,7 +530,7 @@ CExpression *CParser::Ex(int i)
CValue* errmsgval = errmsg->Calculate();
errtext=errmsgval->GetText();
errmsgval->Release();
-
+
//e1 = Error(errmsg->Calculate()->GetText());//new CConstExpr(errmsg->Calculate());
if ( !(errmsg->Release()) )
@@ -543,13 +543,13 @@ CExpression *CParser::Ex(int i)
}
e1 = Error(errtext);
- break;
+ break;
}
- default:
- NextSym();
- //return Error("Expression expected");
- MT_assert(!e1);
- e1 = Error("Expression expected");
+ default:
+ NextSym();
+ //return Error("Expression expected");
+ MT_assert(!e1);
+ e1 = Error("Expression expected");
}
}
}
@@ -573,7 +573,7 @@ CExpression* CParser::ProcessText
text = intext;
- chcount = 0;
+ chcount = 0;
if (text.Length() == 0) {
return NULL;
}
diff --git a/source/gameengine/Expressions/IntValue.cpp b/source/gameengine/Expressions/IntValue.cpp
index 2d427440620..cb6bc556bab 100644
--- a/source/gameengine/Expressions/IntValue.cpp
+++ b/source/gameengine/Expressions/IntValue.cpp
@@ -108,165 +108,160 @@ object and val
}
}
-
-
-CValue* CIntValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
/*
-pre: the type of val is dtype
-ret: a new object containing the result of applying operator op to val and
-this object
-*/
+ * pre: the type of val is dtype
+ * ret: a new object containing the result of applying operator op to val and
+ * this object
+ */
+CValue* CIntValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
{
CValue *ret;
- switch(dtype) {
- case VALUE_EMPTY_TYPE:
- case VALUE_INT_TYPE:
+ switch (dtype) {
+ case VALUE_EMPTY_TYPE:
+ case VALUE_INT_TYPE:
{
switch (op) {
- case VALUE_MOD_OPERATOR:
- ret = new CIntValue (((CIntValue *) val)->GetInt() % m_int);
- break;
- case VALUE_ADD_OPERATOR:
- ret = new CIntValue (((CIntValue *) val)->GetInt() + m_int);
- break;
- case VALUE_SUB_OPERATOR:
- ret = new CIntValue (((CIntValue *) val)->GetInt() - m_int);
- break;
- case VALUE_MUL_OPERATOR:
- ret = new CIntValue (((CIntValue *) val)->GetInt() * m_int);
- break;
- case VALUE_DIV_OPERATOR:
- if (m_int == 0)
- {
- if (val->GetNumber() == 0)
- {
- ret = new CErrorValue("Not a Number");
- } else
- {
- ret = new CErrorValue("Division by zero");
+ case VALUE_MOD_OPERATOR:
+ ret = new CIntValue (((CIntValue *) val)->GetInt() % m_int);
+ break;
+ case VALUE_ADD_OPERATOR:
+ ret = new CIntValue (((CIntValue *) val)->GetInt() + m_int);
+ break;
+ case VALUE_SUB_OPERATOR:
+ ret = new CIntValue (((CIntValue *) val)->GetInt() - m_int);
+ break;
+ case VALUE_MUL_OPERATOR:
+ ret = new CIntValue (((CIntValue *) val)->GetInt() * m_int);
+ break;
+ case VALUE_DIV_OPERATOR:
+ if (m_int == 0) {
+ if (val->GetNumber() == 0) {
+ ret = new CErrorValue("Not a Number");
+ }
+ else {
+ ret = new CErrorValue("Division by zero");
+ }
}
- }
- else
- ret = new CIntValue (((CIntValue *) val)->GetInt() / m_int);
- break;
- case VALUE_EQL_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() == m_int);
- break;
- case VALUE_NEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() != m_int);
- break;
- case VALUE_GRE_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() > m_int);
- break;
- case VALUE_LES_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() < m_int);
- break;
- case VALUE_GEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() >= m_int);
- break;
- case VALUE_LEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() <= m_int);
- break;
- case VALUE_NEG_OPERATOR:
- ret = new CIntValue (-m_int);
- break;
- case VALUE_POS_OPERATOR:
- ret = new CIntValue (m_int);
- break;
- default:
- ret = new CErrorValue("illegal operator. please send a bug report.");
- break;
+ else
+ ret = new CIntValue (((CIntValue *) val)->GetInt() / m_int);
+ break;
+ case VALUE_EQL_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() == m_int);
+ break;
+ case VALUE_NEQ_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() != m_int);
+ break;
+ case VALUE_GRE_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() > m_int);
+ break;
+ case VALUE_LES_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() < m_int);
+ break;
+ case VALUE_GEQ_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() >= m_int);
+ break;
+ case VALUE_LEQ_OPERATOR:
+ ret = new CBoolValue(((CIntValue *) val)->GetInt() <= m_int);
+ break;
+ case VALUE_NEG_OPERATOR:
+ ret = new CIntValue (-m_int);
+ break;
+ case VALUE_POS_OPERATOR:
+ ret = new CIntValue (m_int);
+ break;
+ default:
+ ret = new CErrorValue("illegal operator. please send a bug report.");
+ break;
}
break;
}
- case VALUE_FLOAT_TYPE:
+ case VALUE_FLOAT_TYPE:
{
switch (op) {
- case VALUE_MOD_OPERATOR:
- ret = new CFloatValue(fmod(((CFloatValue *) val)->GetFloat(), m_int));
- break;
- case VALUE_ADD_OPERATOR:
- ret = new CFloatValue (((CFloatValue *) val)->GetFloat() + m_int);
- break;
- case VALUE_SUB_OPERATOR:
- ret = new CFloatValue (((CFloatValue *) val)->GetFloat() - m_int);
- break;
- case VALUE_MUL_OPERATOR:
- ret = new CFloatValue (((CFloatValue *) val)->GetFloat() * m_int);
- break;
- case VALUE_DIV_OPERATOR:
- if (m_int == 0)
- ret = new CErrorValue("Division by zero");
- else
- ret = new CFloatValue (((CFloatValue *) val)->GetFloat() / m_int);
- break;
- case VALUE_EQL_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() == m_int);
- break;
- case VALUE_NEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() != m_int);
- break;
- case VALUE_GRE_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() > m_int);
- break;
- case VALUE_LES_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() < m_int);
- break;
- case VALUE_GEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() >= m_int);
- break;
- case VALUE_LEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() <= m_int);
- break;
- default:
- ret = new CErrorValue("illegal operator. please send a bug report.");
- break;
+ case VALUE_MOD_OPERATOR:
+ ret = new CFloatValue(fmod(((CFloatValue *) val)->GetFloat(), m_int));
+ break;
+ case VALUE_ADD_OPERATOR:
+ ret = new CFloatValue (((CFloatValue *) val)->GetFloat() + m_int);
+ break;
+ case VALUE_SUB_OPERATOR:
+ ret = new CFloatValue (((CFloatValue *) val)->GetFloat() - m_int);
+ break;
+ case VALUE_MUL_OPERATOR:
+ ret = new CFloatValue (((CFloatValue *) val)->GetFloat() * m_int);
+ break;
+ case VALUE_DIV_OPERATOR:
+ if (m_int == 0)
+ ret = new CErrorValue("Division by zero");
+ else
+ ret = new CFloatValue (((CFloatValue *) val)->GetFloat() / m_int);
+ break;
+ case VALUE_EQL_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() == m_int);
+ break;
+ case VALUE_NEQ_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() != m_int);
+ break;
+ case VALUE_GRE_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() > m_int);
+ break;
+ case VALUE_LES_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() < m_int);
+ break;
+ case VALUE_GEQ_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() >= m_int);
+ break;
+ case VALUE_LEQ_OPERATOR:
+ ret = new CBoolValue(((CFloatValue *) val)->GetFloat() <= m_int);
+ break;
+ default:
+ ret = new CErrorValue("illegal operator. please send a bug report.");
+ break;
}
break;
}
- case VALUE_STRING_TYPE:
+ case VALUE_STRING_TYPE:
{
- switch(op) {
- case VALUE_ADD_OPERATOR:
- ret = new CStringValue(val->GetText() + GetText(),"");
- break;
- case VALUE_EQL_OPERATOR:
- case VALUE_NEQ_OPERATOR:
- case VALUE_GRE_OPERATOR:
- case VALUE_LES_OPERATOR:
- case VALUE_GEQ_OPERATOR:
- case VALUE_LEQ_OPERATOR:
- ret = new CErrorValue("[Cannot compare string with integer]" + op2str(op) + GetText());
- break;
- default:
- ret = new CErrorValue("[operator not allowed on strings]" + op2str(op) + GetText());
- break;
+ switch (op) {
+ case VALUE_ADD_OPERATOR:
+ ret = new CStringValue(val->GetText() + GetText(),"");
+ break;
+ case VALUE_EQL_OPERATOR:
+ case VALUE_NEQ_OPERATOR:
+ case VALUE_GRE_OPERATOR:
+ case VALUE_LES_OPERATOR:
+ case VALUE_GEQ_OPERATOR:
+ case VALUE_LEQ_OPERATOR:
+ ret = new CErrorValue("[Cannot compare string with integer]" + op2str(op) + GetText());
+ break;
+ default:
+ ret = new CErrorValue("[operator not allowed on strings]" + op2str(op) + GetText());
+ break;
}
break;
}
- case VALUE_BOOL_TYPE:
- ret = new CErrorValue("[operator not valid on boolean and integer]" + op2str(op) + GetText());
- break;
- /*
+ case VALUE_BOOL_TYPE:
+ ret = new CErrorValue("[operator not valid on boolean and integer]" + op2str(op) + GetText());
+ break;
+#if 0
case VALUE_EMPTY_TYPE:
{
- switch(op) {
-
- case VALUE_ADD_OPERATOR:
- ret = new CIntValue (m_int);
- break;
- case VALUE_SUB_OPERATOR:
- ret = new CIntValue (-m_int);
- break;
- default:
- {
- ret = new CErrorValue(op2str(op) + GetText());
- }
- }
- break;
- }
- */
+ switch (op) {
+ case VALUE_ADD_OPERATOR:
+ ret = new CIntValue (m_int);
+ break;
+ case VALUE_SUB_OPERATOR:
+ ret = new CIntValue (-m_int);
+ break;
+ default:
+ {
+ ret = new CErrorValue(op2str(op) + GetText());
+ }
+ }
+ break;
+ }
+#endif
case VALUE_ERROR_TYPE:
ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
break;
@@ -326,7 +321,7 @@ void CIntValue::SetValue(CValue* newval)
#ifdef WITH_PYTHON
-PyObject* CIntValue::ConvertValueToPython()
+PyObject *CIntValue::ConvertValueToPython()
{
if ((m_int > INT_MIN) && (m_int < INT_MAX))
return PyLong_FromSsize_t(m_int);
diff --git a/source/gameengine/Expressions/IntValue.h b/source/gameengine/Expressions/IntValue.h
index e728467cc4e..8411b09693c 100644
--- a/source/gameengine/Expressions/IntValue.h
+++ b/source/gameengine/Expressions/IntValue.h
@@ -69,5 +69,4 @@ private:
#endif
};
-#endif // !defined __INTVALUE_H__
-
+#endif /* __INTVALUE_H__ */
diff --git a/source/gameengine/Expressions/KX_HashedPtr.h b/source/gameengine/Expressions/KX_HashedPtr.h
index ffc6ff647d5..d822af38c44 100644
--- a/source/gameengine/Expressions/KX_HashedPtr.h
+++ b/source/gameengine/Expressions/KX_HashedPtr.h
@@ -50,7 +50,7 @@ public:
inline friend bool operator ==( const CHashedPtr & rhs,const CHashedPtr & lhs)
{
return rhs.m_valptr == lhs.m_valptr;
- }
+ }
#ifdef WITH_CXX_GUARDEDALLOC
@@ -58,5 +58,4 @@ public:
#endif
};
-#endif //__KX_HASHEDPTR_H__
-
+#endif /* __KX_HASHEDPTR_H__ */
diff --git a/source/gameengine/Expressions/KX_Python.h b/source/gameengine/Expressions/KX_Python.h
index 4a7ce4d3fb7..62dd9a13dd4 100644
--- a/source/gameengine/Expressions/KX_Python.h
+++ b/source/gameengine/Expressions/KX_Python.h
@@ -79,5 +79,4 @@
#undef toupper
#endif
-#endif // __KX_PYTHON_H__
-
+#endif /* __KX_PYTHON_H__ */
diff --git a/source/gameengine/Expressions/ListValue.cpp b/source/gameengine/Expressions/ListValue.cpp
index f43625a7821..8cff5a01c0e 100644
--- a/source/gameengine/Expressions/ListValue.cpp
+++ b/source/gameengine/Expressions/ListValue.cpp
@@ -278,7 +278,7 @@ bool CListValue::IsModified()
/* Python interface ---------------------------------------------------- */
/* --------------------------------------------------------------------- */
-Py_ssize_t listvalue_bufferlen(PyObject* self)
+static Py_ssize_t listvalue_bufferlen(PyObject *self)
{
CListValue *list= static_cast<CListValue *>(BGE_PROXY_REF(self));
if (list==NULL)
@@ -287,7 +287,7 @@ Py_ssize_t listvalue_bufferlen(PyObject* self)
return (Py_ssize_t)list->GetCount();
}
-PyObject* listvalue_buffer_item(PyObject* self, Py_ssize_t index)
+static PyObject *listvalue_buffer_item(PyObject *self, Py_ssize_t index)
{
CListValue *list= static_cast<CListValue *>(BGE_PROXY_REF(self));
CValue *cval;
@@ -309,14 +309,44 @@ PyObject* listvalue_buffer_item(PyObject* self, Py_ssize_t index)
cval= list->GetValue(index);
- PyObject* pyobj = cval->ConvertValueToPython();
+ PyObject *pyobj = cval->ConvertValueToPython();
if (pyobj)
return pyobj;
else
return cval->GetProxy();
}
-PyObject* listvalue_mapping_subscript(PyObject* self, PyObject* pyindex)
+
+/* just slice it into a python list... */
+static PyObject *listvalue_buffer_slice(CListValue *list, Py_ssize_t start, Py_ssize_t stop)
+{
+ PyObject *newlist;
+ Py_ssize_t i, j;
+
+ /* caller needs to validate negative index */
+#if 0
+ Py_ssize_t len = list->GetCount();
+
+ if (start > len) start = len;
+ if (stop > len) stop = len;
+#endif
+
+ newlist = PyList_New(stop - start);
+ if (!newlist)
+ return NULL;
+
+ for (i = start, j = 0; i < stop; i++, j++) {
+ PyObject *pyobj = list->GetValue(i)->ConvertValueToPython();
+ if (!pyobj) {
+ pyobj = list->GetValue(i)->GetProxy();
+ }
+ PyList_SET_ITEM(newlist, j, pyobj);
+ }
+ return newlist;
+}
+
+
+static PyObject *listvalue_mapping_subscript(PyObject *self, PyObject *key)
{
CListValue *list= static_cast<CListValue *>(BGE_PROXY_REF(self));
if (list==NULL) {
@@ -324,67 +354,45 @@ PyObject* listvalue_mapping_subscript(PyObject* self, PyObject* pyindex)
return NULL;
}
- if (PyUnicode_Check(pyindex))
- {
- CValue *item = ((CListValue*) list)->FindValue(_PyUnicode_AsString(pyindex));
+ if (PyUnicode_Check(key)) {
+ CValue *item = ((CListValue*) list)->FindValue(_PyUnicode_AsString(key));
if (item) {
- PyObject* pyobj = item->ConvertValueToPython();
+ PyObject *pyobj = item->ConvertValueToPython();
if (pyobj)
return pyobj;
else
return item->GetProxy();
}
}
- else if (PyLong_Check(pyindex))
- {
- int index = PyLong_AsSsize_t(pyindex);
+ else if (PyIndex_Check(key)) {
+ int index = PyLong_AsSsize_t(key);
return listvalue_buffer_item(self, index); /* wont add a ref */
}
+ else if (PySlice_Check(key)) {
+ Py_ssize_t start, stop, step, slicelength;
- PyErr_Format(PyExc_KeyError,
- "CList[key]: '%R' key not in list", pyindex);
- return NULL;
-}
-
+ if (PySlice_GetIndicesEx(key, list->GetCount(), &start, &stop, &step, &slicelength) < 0)
+ return NULL;
-/* just slice it into a python list... */
-PyObject* listvalue_buffer_slice(PyObject* self,Py_ssize_t ilow, Py_ssize_t ihigh)
-{
- CListValue *list= static_cast<CListValue *>(BGE_PROXY_REF(self));
- if (list==NULL) {
- PyErr_SetString(PyExc_SystemError, "val = CList[i:j], "BGE_PROXY_ERROR_MSG);
- return NULL;
+ if (slicelength <= 0) {
+ return PyList_New(0);
+ }
+ else if (step == 1) {
+ return listvalue_buffer_slice(list, start, stop);
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "CList[slice]: slice steps not supported");
+ return NULL;
+ }
}
-
- int i, j;
- PyObject *newlist;
-
- if (ilow < 0) ilow = 0;
- int n = ((CListValue*) list)->GetCount();
-
- if (ihigh >= n)
- ihigh = n;
- if (ihigh < ilow)
- ihigh = ilow;
-
- newlist = PyList_New(ihigh - ilow);
- if (!newlist)
- return NULL;
-
- for (i = ilow, j = 0; i < ihigh; i++, j++)
- {
- PyObject* pyobj = list->GetValue(i)->ConvertValueToPython();
- if (!pyobj)
- pyobj = list->GetValue(i)->GetProxy();
- PyList_SET_ITEM(newlist, i, pyobj);
- }
- return newlist;
+ PyErr_Format(PyExc_KeyError,
+ "CList[key]: '%R' key not in list", key);
+ return NULL;
}
-
/* clist + list, return a list that python owns */
-static PyObject *listvalue_buffer_concat(PyObject * self, PyObject * other)
+static PyObject *listvalue_buffer_concat(PyObject *self, PyObject *other)
{
CListValue *listval= static_cast<CListValue *>(BGE_PROXY_REF(self));
Py_ssize_t i, numitems, numitems_orig;
@@ -460,9 +468,9 @@ static PyObject *listvalue_buffer_concat(PyObject * self, PyObject * other)
static int listvalue_buffer_contains(PyObject *self_v, PyObject *value)
{
- CListValue *self= static_cast<CListValue *>(BGE_PROXY_REF(self_v));
+ CListValue *self = static_cast<CListValue *>(BGE_PROXY_REF(self_v));
- if (self==NULL) {
+ if (self == NULL) {
PyErr_SetString(PyExc_SystemError, "val in CList, "BGE_PROXY_ERROR_MSG);
return -1;
}
@@ -560,7 +568,7 @@ PyAttributeDef CListValue::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* CListValue::Pyappend(PyObject* value)
+PyObject *CListValue::Pyappend(PyObject *value)
{
CValue* objval = ConvertPythonToValue(value, "CList.append(i): CValueList, ");
@@ -577,15 +585,15 @@ PyObject* CListValue::Pyappend(PyObject* value)
Py_RETURN_NONE;
}
-PyObject* CListValue::Pyreverse()
+PyObject *CListValue::Pyreverse()
{
std::reverse(m_pValueArray.begin(),m_pValueArray.end());
Py_RETURN_NONE;
}
-PyObject* CListValue::Pyindex(PyObject *value)
+PyObject *CListValue::Pyindex(PyObject *value)
{
- PyObject* result = NULL;
+ PyObject *result = NULL;
CValue* checkobj = ConvertPythonToValue(value, "val = cList[i]: CValueList, ");
if (checkobj==NULL)
@@ -612,7 +620,7 @@ PyObject* CListValue::Pyindex(PyObject *value)
-PyObject* CListValue::Pycount(PyObject* value)
+PyObject *CListValue::Pycount(PyObject *value)
{
int numfound = 0;
@@ -638,17 +646,17 @@ PyObject* CListValue::Pycount(PyObject* value)
}
/* Matches python dict.get(key, [default]) */
-PyObject* CListValue::Pyget(PyObject *args)
+PyObject *CListValue::Pyget(PyObject *args)
{
char *key;
- PyObject* def = Py_None;
+ PyObject *def = Py_None;
if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
return NULL;
CValue *item = FindValue((const char *)key);
if (item) {
- PyObject* pyobj = item->ConvertValueToPython();
+ PyObject *pyobj = item->ConvertValueToPython();
if (pyobj)
return pyobj;
else
@@ -659,7 +667,7 @@ PyObject* CListValue::Pyget(PyObject *args)
}
-PyObject* CListValue::Pyfrom_id(PyObject* value)
+PyObject *CListValue::Pyfrom_id(PyObject *value)
{
uintptr_t id= (uintptr_t)PyLong_AsVoidPtr(value);
diff --git a/source/gameengine/Expressions/ListValue.h b/source/gameengine/Expressions/ListValue.h
index 4d104a4bd3a..5240c54ae4e 100644
--- a/source/gameengine/Expressions/ListValue.h
+++ b/source/gameengine/Expressions/ListValue.h
@@ -64,7 +64,7 @@ public:
bool CheckEqual(CValue* first,CValue* second);
#ifdef WITH_PYTHON
- virtual PyObject* py_repr(void) {
+ virtual PyObject *py_repr(void) {
PyObject *py_proxy= this->GetProxy();
PyObject *py_list= PySequence_List(py_proxy);
PyObject *py_string= PyObject_Repr(py_list);
@@ -87,5 +87,5 @@ private:
bool m_bReleaseContents;
};
-#endif // !defined __LISTVALUE_H__
+#endif /* __LISTVALUE_H__ */
diff --git a/source/gameengine/Expressions/Operator1Expr.h b/source/gameengine/Expressions/Operator1Expr.h
index 13a1b16500a..3dd76f773f2 100644
--- a/source/gameengine/Expressions/Operator1Expr.h
+++ b/source/gameengine/Expressions/Operator1Expr.h
@@ -16,8 +16,8 @@
* \ingroup expressions
*/
-#if !defined(AFX_OPERATOR1EXPR_H__A1653901_BF41_11D1_A51C_00A02472FC58__INCLUDED_)
-#define AFX_OPERATOR1EXPR_H__A1653901_BF41_11D1_A51C_00A02472FC58__INCLUDED_
+#ifndef __OPERATOR1EXPR_H__
+#define __OPERATOR1EXPR_H__
#include "Expression.h"
@@ -56,5 +56,4 @@ private:
#endif
};
-#endif // !defined(AFX_OPERATOR1EXPR_H__A1653901_BF41_11D1_A51C_00A02472FC58__INCLUDED_)
-
+#endif /* __OPERATOR1EXPR_H__ */
diff --git a/source/gameengine/Expressions/Operator2Expr.cpp b/source/gameengine/Expressions/Operator2Expr.cpp
index 2224b0ff5e8..d0240b5ec75 100644
--- a/source/gameengine/Expressions/Operator2Expr.cpp
+++ b/source/gameengine/Expressions/Operator2Expr.cpp
@@ -102,7 +102,7 @@ and m_rhs
m_cached_calculate = ffleft->Calc(m_op,ffright);
- //if (m_cached_calculate)
+ //if (m_cached_calculate)
// m_cached_calculate->Action(CValue::SETOWNEREXPR,&CVoidValue(this,false,CValue::STACKVALUE));
ffleft->Release();
@@ -163,7 +163,7 @@ bool COperator2Expr::IsInside(float x, float y, float z,bool bBorderInclude)
}
}
- return inside;
+ return inside;
}
@@ -241,7 +241,7 @@ CExpression* COperator2Expr::CheckLink(std::vector<CBrokenLinkInfo*>& brokenlink
if (m_rhs)
return Release(m_rhs->AddRef());
-/
+/
*/
return Release();
diff --git a/source/gameengine/Expressions/Operator2Expr.h b/source/gameengine/Expressions/Operator2Expr.h
index 23272930131..8c30b7cd634 100644
--- a/source/gameengine/Expressions/Operator2Expr.h
+++ b/source/gameengine/Expressions/Operator2Expr.h
@@ -62,5 +62,5 @@ private:
#endif
};
-#endif // !defined __OPERATOR2EXPR_H__
+#endif /* __OPERATOR2EXPR_H__ */
diff --git a/source/gameengine/Expressions/PyObjectPlus.cpp b/source/gameengine/Expressions/PyObjectPlus.cpp
index a35cb4f9f69..bb1d0a31c1f 100644
--- a/source/gameengine/Expressions/PyObjectPlus.cpp
+++ b/source/gameengine/Expressions/PyObjectPlus.cpp
@@ -145,7 +145,7 @@ PyObject *PyObjectPlus::py_base_repr(PyObject *self) // This should be the ent
}
-PyObject * PyObjectPlus::py_base_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
+PyObject *PyObjectPlus::py_base_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyTypeObject *base_type;
PyObjectPlus_Proxy *base = NULL;
@@ -170,7 +170,7 @@ PyObject * PyObjectPlus::py_base_new(PyTypeObject *type, PyObject *args, PyObjec
*
* */
base_type= Py_TYPE(base);
- while(base_type && !BGE_PROXY_CHECK_TYPE(base_type))
+ while (base_type && !BGE_PROXY_CHECK_TYPE(base_type))
base_type= base_type->tp_base;
if (base_type==NULL || !BGE_PROXY_CHECK_TYPE(base_type)) {
@@ -270,7 +270,7 @@ PyAttributeDef PyObjectPlus::Attributes[] = {
-PyObject* PyObjectPlus::pyattr_get_invalid(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *PyObjectPlus::pyattr_get_invalid(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
return PyBool_FromLong(self_v ? 0:1);
}
@@ -303,7 +303,7 @@ PyObject *PyObjectPlus::py_get_attrdef(PyObject *self_py, const PyAttributeDef *
ptr += attrdef->m_offset;
if (attrdef->m_length > 1)
{
- PyObject* resultlist = PyList_New(attrdef->m_length);
+ PyObject *resultlist = PyList_New(attrdef->m_length);
for (unsigned int i=0; i<attrdef->m_length; i++)
{
switch (attrdef->m_type) {
@@ -420,7 +420,7 @@ PyObject *PyObjectPlus::py_get_attrdef(PyObject *self_py, const PyAttributeDef *
#ifdef USE_MATHUTILS
return Vector_CreatePyObject(val, attrdef->m_imax, Py_NEW, NULL);
#else
- PyObject* resultlist = PyList_New(attrdef->m_imax);
+ PyObject *resultlist = PyList_New(attrdef->m_imax);
for (unsigned int i=0; i<attrdef->m_imax; i++)
{
PyList_SET_ITEM(resultlist,i,PyFloat_FromDouble(val[i]));
@@ -437,10 +437,10 @@ PyObject *PyObjectPlus::py_get_attrdef(PyObject *self_py, const PyAttributeDef *
#ifdef USE_MATHUTILS
return Matrix_CreatePyObject(val, attrdef->m_imin, attrdef->m_imax, Py_WRAP, NULL);
#else
- PyObject* collist = PyList_New(attrdef->m_imin);
+ PyObject *collist = PyList_New(attrdef->m_imin);
for (unsigned int i=0; i<attrdef->m_imin; i++)
{
- PyObject* col = PyList_New(attrdef->m_imax);
+ PyObject *col = PyList_New(attrdef->m_imax);
for (unsigned int j=0; j<attrdef->m_imax; j++)
{
PyList_SET_ITEM(col,j,PyFloat_FromDouble(val[j]));
@@ -460,7 +460,7 @@ PyObject *PyObjectPlus::py_get_attrdef(PyObject *self_py, const PyAttributeDef *
val->getValue(fval);
return Vector_CreatePyObject(fval, 3, Py_NEW, NULL);
#else
- PyObject* resultlist = PyList_New(3);
+ PyObject *resultlist = PyList_New(3);
for (unsigned int i=0; i<3; i++)
{
PyList_SET_ITEM(resultlist,i,PyFloat_FromDouble((*val)[i]));
@@ -1100,7 +1100,7 @@ int PyObjectPlus::py_set_attrdef(PyObject *self_py, PyObject *value, const PyAtt
}
if (undoBuffer)
free(undoBuffer);
- return 0;
+ return 0;
}
@@ -1139,7 +1139,7 @@ PyObject *PyObjectPlus::NewProxyPlus_Ext(PyObjectPlus *self, PyTypeObject *tp, v
if (!self)
{
// in case of proxy without reference to game object
- PyObject* proxy = reinterpret_cast<PyObject *>PyObject_NEW( PyObjectPlus_Proxy, tp);
+ PyObject *proxy = reinterpret_cast<PyObject *>PyObject_NEW( PyObjectPlus_Proxy, tp);
BGE_PROXY_PYREF(proxy) = false;
BGE_PROXY_PYOWNS(proxy) = py_owns;
BGE_PROXY_REF(proxy) = NULL;
@@ -1198,8 +1198,7 @@ void PyObjectPlus::ClearDeprecationWarning()
WarnLink *wlink_next;
WarnLink *wlink = GetDeprecationWarningLinkFirst();
- while(wlink)
- {
+ while (wlink) {
wlink->warn_done= false; /* no need to NULL the link, its cleared before adding to the list next time round */
wlink_next= reinterpret_cast<WarnLink *>(wlink->link);
wlink->link= NULL;
diff --git a/source/gameengine/Expressions/PyObjectPlus.h b/source/gameengine/Expressions/PyObjectPlus.h
index f74ed7db8f7..83b7c8c8771 100644
--- a/source/gameengine/Expressions/PyObjectPlus.h
+++ b/source/gameengine/Expressions/PyObjectPlus.h
@@ -190,9 +190,9 @@ public: \
* macro is one that also requires a documentation string
*/
#define KX_PYMETHOD(class_name, method_name) \
- PyObject* Py##method_name(PyObject* args, PyObject* kwds); \
- static PyObject* \
- sPy##method_name(PyObject* self, PyObject* args, PyObject* kwds) { \
+ PyObject *Py##method_name(PyObject *args, PyObject *kwds); \
+ static PyObject * \
+ sPy##method_name(PyObject *self, PyObject *args, PyObject *kwds) { \
if(BGE_PROXY_REF(self)==NULL) { \
PyErr_SetString(PyExc_RuntimeError, \
#class_name "." #method_name "() - " \
@@ -203,9 +203,9 @@ public: \
} \
#define KX_PYMETHOD_VARARGS(class_name, method_name) \
- PyObject* Py##method_name(PyObject* args); \
+ PyObject *Py##method_name(PyObject *args); \
static PyObject* \
- sPy##method_name(PyObject* self, PyObject* args) { \
+ sPy##method_name(PyObject *self, PyObject *args) { \
if(BGE_PROXY_REF(self)==NULL) { \
PyErr_SetString(PyExc_RuntimeError, \
#class_name "." #method_name "() - " \
@@ -215,9 +215,9 @@ public: \
} \
#define KX_PYMETHOD_NOARGS(class_name, method_name) \
- PyObject* Py##method_name(); \
+ PyObject *Py##method_name(); \
static PyObject* \
- sPy##method_name(PyObject* self) { \
+ sPy##method_name(PyObject *self) { \
if(BGE_PROXY_REF(self)==NULL) { \
PyErr_SetString(PyExc_RuntimeError, \
#class_name "." #method_name "() - " \
@@ -227,9 +227,9 @@ public: \
} \
#define KX_PYMETHOD_O(class_name, method_name) \
- PyObject* Py##method_name(PyObject* value); \
+ PyObject *Py##method_name(PyObject *value); \
static PyObject* \
- sPy##method_name(PyObject* self, PyObject* value) { \
+ sPy##method_name(PyObject *self, PyObject *value) { \
if(BGE_PROXY_REF(self)==NULL) { \
PyErr_SetString(PyExc_RuntimeError, \
#class_name "." #method_name "(value) - " \
@@ -239,9 +239,9 @@ public: \
} \
#define KX_PYMETHOD_DOC(class_name, method_name) \
- PyObject* Py##method_name(PyObject* args, PyObject* kwds); \
+ PyObject *Py##method_name(PyObject *args, PyObject *kwds); \
static PyObject* \
- sPy##method_name(PyObject* self, PyObject* args, PyObject* kwds) { \
+ sPy##method_name(PyObject *self, PyObject *args, PyObject *kwds) { \
if(BGE_PROXY_REF(self)==NULL) { \
PyErr_SetString(PyExc_RuntimeError, \
#class_name "." #method_name "(...) - " \
@@ -252,9 +252,9 @@ public: \
static const char method_name##_doc[]; \
#define KX_PYMETHOD_DOC_VARARGS(class_name, method_name) \
- PyObject* Py##method_name(PyObject* args); \
+ PyObject *Py##method_name(PyObject *args); \
static PyObject* \
- sPy##method_name(PyObject* self, PyObject* args) { \
+ sPy##method_name(PyObject *self, PyObject *args) { \
if(BGE_PROXY_REF(self)==NULL) { \
PyErr_SetString(PyExc_RuntimeError, \
#class_name "." #method_name "(...) - " \
@@ -266,9 +266,9 @@ public: \
static const char method_name##_doc[]; \
#define KX_PYMETHOD_DOC_O(class_name, method_name) \
- PyObject* Py##method_name(PyObject* value); \
- static PyObject* \
- sPy##method_name(PyObject* self, PyObject* value) { \
+ PyObject *Py##method_name(PyObject *value); \
+ static PyObject * \
+ sPy##method_name(PyObject *self, PyObject *value) { \
if(BGE_PROXY_REF(self)==NULL) { \
PyErr_SetString(PyExc_RuntimeError, \
#class_name "." #method_name "(value) - " \
@@ -280,9 +280,9 @@ public: \
static const char method_name##_doc[]; \
#define KX_PYMETHOD_DOC_NOARGS(class_name, method_name) \
- PyObject* Py##method_name(); \
- static PyObject* \
- sPy##method_name(PyObject* self) { \
+ PyObject *Py##method_name(); \
+ static PyObject * \
+ sPy##method_name(PyObject *self) { \
if(BGE_PROXY_REF(self)==NULL) { \
PyErr_SetString(PyExc_RuntimeError, \
#class_name "." #method_name "() - " \
@@ -315,19 +315,19 @@ public: \
*/
#define KX_PYMETHODDEF_DOC(class_name, method_name, doc_string) \
const char class_name::method_name##_doc[] = doc_string; \
-PyObject* class_name::Py##method_name(PyObject* args, PyObject* kwds)
+PyObject *class_name::Py##method_name(PyObject *args, PyObject *kwds)
#define KX_PYMETHODDEF_DOC_VARARGS(class_name, method_name, doc_string) \
const char class_name::method_name##_doc[] = doc_string; \
-PyObject* class_name::Py##method_name(PyObject* args)
+PyObject *class_name::Py##method_name(PyObject *args)
#define KX_PYMETHODDEF_DOC_O(class_name, method_name, doc_string) \
const char class_name::method_name##_doc[] = doc_string; \
-PyObject* class_name::Py##method_name(PyObject* value)
+PyObject *class_name::Py##method_name(PyObject *value)
#define KX_PYMETHODDEF_DOC_NOARGS(class_name, method_name, doc_string) \
const char class_name::method_name##_doc[] = doc_string; \
-PyObject* class_name::Py##method_name()
+PyObject *class_name::Py##method_name()
/**
* Attribute management
@@ -354,7 +354,7 @@ enum KX_PYATTRIBUTE_ACCESS {
struct KX_PYATTRIBUTE_DEF;
typedef int (*KX_PYATTRIBUTE_CHECK_FUNCTION)(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
typedef int (*KX_PYATTRIBUTE_SET_FUNCTION)(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-typedef PyObject* (*KX_PYATTRIBUTE_GET_FUNCTION)(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+typedef PyObject *(*KX_PYATTRIBUTE_GET_FUNCTION)(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
typedef struct KX_PYATTRIBUTE_DEF {
const char *m_name; // name of the python attribute
@@ -548,7 +548,7 @@ public: \
#define Py_HeaderPtr \
public: \
-#endif // WITH_CXX_GUARDEDALLOC
+#endif /* WITH_CXX_GUARDEDALLOC */
#endif
@@ -633,4 +633,4 @@ public:
PyObject *PyUnicode_From_STR_String(const STR_String& str);
#endif
-#endif // __PYOBJECTPLUS_H__
+#endif /* __PYOBJECTPLUS_H__ */
diff --git a/source/gameengine/Expressions/StringValue.cpp b/source/gameengine/Expressions/StringValue.cpp
index 2e29a39222b..166125bc906 100644
--- a/source/gameengine/Expressions/StringValue.cpp
+++ b/source/gameengine/Expressions/StringValue.cpp
@@ -77,33 +77,34 @@ CValue* CStringValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue
ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
else
ret = new CStringValue(val->GetText() + GetText(),"");
- } else {
-
+ }
+ else {
if (dtype == VALUE_STRING_TYPE || dtype == VALUE_EMPTY_TYPE) {
- switch(op) {
- case VALUE_EQL_OPERATOR:
- ret = new CBoolValue(val->GetText() == GetText());
- break;
- case VALUE_NEQ_OPERATOR:
- ret = new CBoolValue(val->GetText() != GetText());
- break;
- case VALUE_GRE_OPERATOR:
- ret = new CBoolValue(val->GetText() > GetText());
- break;
- case VALUE_LES_OPERATOR:
- ret = new CBoolValue(val->GetText() < GetText());
- break;
- case VALUE_GEQ_OPERATOR:
- ret = new CBoolValue(val->GetText() >= GetText());
- break;
- case VALUE_LEQ_OPERATOR:
- ret = new CBoolValue(val->GetText() <= GetText());
- break;
- default:
- ret = new CErrorValue(val->GetText() + op2str(op) + "[operator not allowed on strings]");
- break;
+ switch (op) {
+ case VALUE_EQL_OPERATOR:
+ ret = new CBoolValue(val->GetText() == GetText());
+ break;
+ case VALUE_NEQ_OPERATOR:
+ ret = new CBoolValue(val->GetText() != GetText());
+ break;
+ case VALUE_GRE_OPERATOR:
+ ret = new CBoolValue(val->GetText() > GetText());
+ break;
+ case VALUE_LES_OPERATOR:
+ ret = new CBoolValue(val->GetText() < GetText());
+ break;
+ case VALUE_GEQ_OPERATOR:
+ ret = new CBoolValue(val->GetText() >= GetText());
+ break;
+ case VALUE_LEQ_OPERATOR:
+ ret = new CBoolValue(val->GetText() <= GetText());
+ break;
+ default:
+ ret = new CErrorValue(val->GetText() + op2str(op) + "[operator not allowed on strings]");
+ break;
}
- } else {
+ }
+ else {
ret = new CErrorValue(val->GetText() + op2str(op) + "[operator not allowed on strings]");
}
}
diff --git a/source/gameengine/Expressions/StringValue.h b/source/gameengine/Expressions/StringValue.h
index e37b4638a1e..22d433455ec 100644
--- a/source/gameengine/Expressions/StringValue.h
+++ b/source/gameengine/Expressions/StringValue.h
@@ -25,7 +25,7 @@ class CStringValue : public CPropValue
{
- //PLUGIN_DECLARE_SERIAL(CStringValue,CValue)
+ //PLUGIN_DECLARE_SERIAL(CStringValue,CValue)
public:
/// Construction / destruction
CStringValue();
@@ -45,7 +45,7 @@ public:
virtual PyObject* ConvertValueToPython() {
return PyUnicode_From_STR_String(m_strString);
}
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
private:
// data member
@@ -57,5 +57,4 @@ private:
#endif
};
-#endif
-
+#endif /* __STRINGVALUE_H__ */
diff --git a/source/gameengine/Expressions/Value.cpp b/source/gameengine/Expressions/Value.cpp
index 6507cc32cf1..bcfb7e92d71 100644
--- a/source/gameengine/Expressions/Value.cpp
+++ b/source/gameengine/Expressions/Value.cpp
@@ -340,7 +340,7 @@ vector<STR_String> CValue::GetPropertyNames()
// Clear all properties
//
void CValue::ClearProperties()
-{
+{
// Check if we have any properties
if (m_pNamedPropertyArray == NULL)
return;
@@ -530,13 +530,13 @@ PyAttributeDef CValue::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject * CValue::pyattr_get_name(void * self_v, const KX_PYATTRIBUTE_DEF * attrdef)
+PyObject *CValue::pyattr_get_name(void * self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
CValue * self = static_cast<CValue *> (self_v);
return PyUnicode_From_STR_String(self->GetName());
}
-CValue* CValue::ConvertPythonToValue(PyObject* pyobj, const char *error_prefix)
+CValue* CValue::ConvertPythonToValue(PyObject *pyobj, const char *error_prefix)
{
CValue* vallie = NULL;
@@ -551,7 +551,7 @@ CValue* CValue::ConvertPythonToValue(PyObject* pyobj, const char *error_prefix)
Py_ssize_t numitems = PyList_GET_SIZE(pyobj);
for (i=0;i<numitems;i++)
{
- PyObject* listitem = PyList_GetItem(pyobj,i); /* borrowed ref */
+ PyObject *listitem = PyList_GetItem(pyobj,i); /* borrowed ref */
CValue* listitemval = ConvertPythonToValue(listitem, error_prefix);
if (listitemval)
{
@@ -597,7 +597,7 @@ CValue* CValue::ConvertPythonToValue(PyObject* pyobj, const char *error_prefix)
}
-PyObject* CValue::ConvertKeysToPython(void)
+PyObject *CValue::ConvertKeysToPython(void)
{
if (m_pNamedPropertyArray)
{
@@ -636,5 +636,5 @@ void CValue::SetColorOperator(VALUE_OPERATOR op)
void CValue::SetValue(CValue* newval)
{
// no one should get here
- assertd(newval->GetNumber() == 10121969);
+ assertd(newval->GetNumber() == 10121969);
}
diff --git a/source/gameengine/Expressions/Value.h b/source/gameengine/Expressions/Value.h
index e3b52e80ba6..c4af3255f4a 100644
--- a/source/gameengine/Expressions/Value.h
+++ b/source/gameengine/Expressions/Value.h
@@ -16,13 +16,13 @@
* \ingroup expressions
*/
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786)
-#endif //WIN32
-
#ifndef __VALUE_H__
#define __VALUE_H__
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
+#endif
+
#include <map> // array functionality for the propertylist
#include "STR_String.h" // STR_String class
@@ -53,14 +53,6 @@ using namespace std;
#define assertd(exp) ((void)NULL)
#endif
-
-#ifndef USE_PRAGMA_ONCE
-#ifdef WIN32
- #pragma once
-
-#endif //WIN32
-#endif
-
enum VALUE_OPERATOR {
VALUE_MOD_OPERATOR, // %
@@ -218,22 +210,22 @@ public:
CValue();
#ifdef WITH_PYTHON
- //static PyObject* PyMake(PyObject*,PyObject*);
+ //static PyObject *PyMake(PyObject *, PyObject *);
virtual PyObject *py_repr(void)
{
return PyUnicode_From_STR_String(GetText());
}
- virtual PyObject* ConvertValueToPython() {
+ virtual PyObject *ConvertValueToPython() {
return NULL;
}
- virtual CValue* ConvertPythonToValue(PyObject* pyobj, const char *error_prefix);
+ virtual CValue *ConvertPythonToValue(PyObject *pyobj, const char *error_prefix);
- static PyObject * pyattr_get_name(void * self, const KX_PYATTRIBUTE_DEF * attrdef);
+ static PyObject *pyattr_get_name(void * self, const KX_PYATTRIBUTE_DEF * attrdef);
- virtual PyObject* ConvertKeysToPython( void );
-#endif // WITH_PYTHON
+ virtual PyObject *ConvertKeysToPython( void );
+#endif /* WITH_PYTHON */
@@ -250,13 +242,13 @@ public:
};
/// Reference Counting
- int GetRefCount()
+ int GetRefCount()
{
return m_refcount;
}
// Add a reference to this value
- CValue* AddRef()
+ CValue *AddRef()
{
// Increase global reference count, used to see at the end of the program
// if all CValue-derived classes have been dereferenced to 0
@@ -269,7 +261,7 @@ public:
}
// Release a reference to this value (when reference count reaches 0, the value is removed from the heap)
- int Release()
+ int Release()
{
// Decrease global reference count, used to see at the end of the program
// if all CValue-derived classes have been dereferenced to 0
@@ -354,16 +346,16 @@ public:
virtual void SetCustomFlag2(bool bCustomFlag) { m_ValFlags.CustomFlag2 = bCustomFlag;}
virtual bool IsCustomFlag2() { return m_ValFlags.CustomFlag2;}
-protected:
+protected:
virtual void DisableRefCount(); // Disable reference counting for this value
- //virtual void AddDataToReplica(CValue* replica);
+ //virtual void AddDataToReplica(CValue* replica);
virtual ~CValue();
private:
- // Member variables
+ // Member variables
std::map<STR_String,CValue*>* m_pNamedPropertyArray; // Properties for user/game etc
ValueFlags m_ValFlags; // Frequently used flags in a bitfield (low memoryusage)
- int m_refcount; // Reference Counter
- static double m_sZeroVec[3];
+ int m_refcount; // Reference Counter
+ static double m_sZeroVec[3];
};
@@ -439,5 +431,4 @@ protected:
#endif
};
-#endif // !defined _VALUEBASECLASS_H
-
+#endif /* __VALUE_H__ */
diff --git a/source/gameengine/Expressions/VectorValue.cpp b/source/gameengine/Expressions/VectorValue.cpp
index 65f5d7d3d22..612de658ce9 100644
--- a/source/gameengine/Expressions/VectorValue.cpp
+++ b/source/gameengine/Expressions/VectorValue.cpp
@@ -15,8 +15,8 @@
*
*/
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786)
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
#endif
#include "Value.h"
@@ -96,61 +96,60 @@ CValue* CVectorValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue
{
CValue *ret = NULL;
- switch(op)
- {
- case VALUE_ADD_OPERATOR:
+ switch (op) {
+ case VALUE_ADD_OPERATOR:
{
switch (dtype)
{
- case VALUE_EMPTY_TYPE:
- case VALUE_VECTOR_TYPE:
+ case VALUE_EMPTY_TYPE:
+ case VALUE_VECTOR_TYPE:
{
ret = new CVectorValue(
- val->GetVector3()[KX_X] + GetVector3()[KX_X],
- val->GetVector3()[KX_Y] + GetVector3()[KX_Y],
- val->GetVector3()[KX_Z] + GetVector3()[KX_Z],
- CValue::HEAPVALUE);
+ val->GetVector3()[KX_X] + GetVector3()[KX_X],
+ val->GetVector3()[KX_Y] + GetVector3()[KX_Y],
+ val->GetVector3()[KX_Z] + GetVector3()[KX_Z],
+ CValue::HEAPVALUE);
ret->SetName(GetName());
break;
}
-
- default:
- ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
+
+ default:
+ ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
}
break;
}
- case VALUE_MUL_OPERATOR:
+ case VALUE_MUL_OPERATOR:
{
switch (dtype)
{
- case VALUE_EMPTY_TYPE:
- case VALUE_VECTOR_TYPE:
+ case VALUE_EMPTY_TYPE:
+ case VALUE_VECTOR_TYPE:
{
//MT_Vector3 supports 'scaling' by another vector, instead of using general transform, Gino?
//ret = new CVectorValue(val->GetVector3().Scaled(GetVector3()),GetName());
break;
}
- case VALUE_FLOAT_TYPE:
+ case VALUE_FLOAT_TYPE:
{
ret = new CVectorValue(
- val->GetVector3()[KX_X] * GetVector3()[KX_X],
- val->GetVector3()[KX_Y] * GetVector3()[KX_Y],
- val->GetVector3()[KX_Z] * GetVector3()[KX_Z],
- CValue::HEAPVALUE);
+ val->GetVector3()[KX_X] * GetVector3()[KX_X],
+ val->GetVector3()[KX_Y] * GetVector3()[KX_Y],
+ val->GetVector3()[KX_Z] * GetVector3()[KX_Z],
+ CValue::HEAPVALUE);
ret->SetName(GetName());
break;
}
-
- default:
- ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
+
+ default:
+ ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
}
break;
}
-
- default:
- ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
+
+ default:
+ ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
}
diff --git a/source/gameengine/Expressions/VectorValue.h b/source/gameengine/Expressions/VectorValue.h
index b7afa61d4dd..9b9f9612810 100644
--- a/source/gameengine/Expressions/VectorValue.h
+++ b/source/gameengine/Expressions/VectorValue.h
@@ -90,5 +90,4 @@ protected:
#endif
};
-#endif // !defined __VECTORVALUE_H__
-
+#endif /* __VECTORVALUE_H__ */
diff --git a/source/gameengine/Expressions/VoidValue.h b/source/gameengine/Expressions/VoidValue.h
index a1a82f8aa65..e97278b3142 100644
--- a/source/gameengine/Expressions/VoidValue.h
+++ b/source/gameengine/Expressions/VoidValue.h
@@ -78,4 +78,3 @@ public:
};
#endif /* __VOIDVALUE_H__ */
-
diff --git a/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp b/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp
index 48fa3257d20..8b343be8226 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp
+++ b/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp
@@ -51,11 +51,11 @@ SCA_Joystick::SCA_Joystick(short int index)
m_istrig_button(0),
m_istrig_hat(0)
{
- for (int i=0; i<JOYAXIS_MAX; i++)
- m_axis_array[i]= 0;
+ for (int i=0; i < JOYAXIS_MAX; i++)
+ m_axis_array[i] = 0;
- for (int i=0; i<JOYHAT_MAX; i++)
- m_hat_array[i]= 0;
+ for (int i=0; i < JOYHAT_MAX; i++)
+ m_hat_array[i] = 0;
#ifdef WITH_SDL
m_private = new PrivateData();
@@ -88,9 +88,9 @@ SCA_Joystick *SCA_Joystick::GetInstance( short int joyindex )
if (m_refCount == 0)
{
int i;
- // The video subsystem is required for joystick input to work. However,
- // when GHOST is running under SDL, video is initialized elsewhere.
- // Do this once only.
+ /* The video subsystem is required for joystick input to work. However,
+ * when GHOST is running under SDL, video is initialized elsewhere.
+ * Do this once only. */
# ifdef WITH_GHOST_SDL
if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1 ) {
# else
@@ -127,12 +127,12 @@ void SCA_Joystick::ReleaseInstance()
m_instance[i]->DestroyJoystickDevice();
delete m_instance[i];
}
- m_instance[i]= NULL;
+ m_instance[i] = NULL;
}
- // The video subsystem is required for joystick input to work. However,
- // when GHOST is running under SDL, video is freed elsewhere.
- // Do this once only.
+ /* The video subsystem is required for joystick input to work. However,
+ * when GHOST is running under SDL, video is freed elsewhere.
+ * Do this once only. */
# ifdef WITH_GHOST_SDL
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
# else
@@ -241,10 +241,10 @@ bool SCA_Joystick::CreateJoystickDevice(void)
#else /* WITH_SDL */
if (m_isinit == false) {
if (m_joyindex>=m_joynum) {
- // don't print a message, because this is done anyway
+ /* don't print a message, because this is done anyway */
//ECHO("Joystick-Error: " << SDL_NumJoysticks() << " avaiable joystick(s)");
- // Need this so python args can return empty lists
+ /* Need this so python args can return empty lists */
m_axismax = m_buttonmax = m_hatmax = 0;
return false;
}
@@ -256,17 +256,17 @@ bool SCA_Joystick::CreateJoystickDevice(void)
ECHO("Joystick " << m_joyindex << " initialized");
/* must run after being initialized */
- m_axismax = SDL_JoystickNumAxes(m_private->m_joystick);
- m_buttonmax = SDL_JoystickNumButtons(m_private->m_joystick);
- m_hatmax = SDL_JoystickNumHats(m_private->m_joystick);
-
- if (m_axismax > JOYAXIS_MAX) m_axismax= JOYAXIS_MAX; /* very unlikely */
- else if (m_axismax < 0) m_axismax = 0;
+ m_axismax = SDL_JoystickNumAxes(m_private->m_joystick);
+ m_buttonmax = SDL_JoystickNumButtons(m_private->m_joystick);
+ m_hatmax = SDL_JoystickNumHats(m_private->m_joystick);
+
+ if (m_axismax > JOYAXIS_MAX) m_axismax = JOYAXIS_MAX; /* very unlikely */
+ else if (m_axismax < 0) m_axismax = 0;
- if (m_hatmax > JOYHAT_MAX) m_hatmax= JOYHAT_MAX; /* very unlikely */
- else if (m_hatmax<0) m_hatmax= 0;
+ if (m_hatmax > JOYHAT_MAX) m_hatmax = JOYHAT_MAX; /* very unlikely */
+ else if (m_hatmax < 0) m_hatmax = 0;
- if (m_buttonmax<0) m_buttonmax= 0;
+ if (m_buttonmax < 0) m_buttonmax = 0;
}
return true;
@@ -307,16 +307,16 @@ int SCA_Joystick::pGetAxis(int axisnum, int udlr)
int SCA_Joystick::pAxisTest(int axisnum)
{
#ifdef WITH_SDL
- short i1= m_axis_array[(axisnum*2)];
- short i2= m_axis_array[(axisnum*2)+1];
+ short i1 = m_axis_array[(axisnum * 2)];
+ short i2 = m_axis_array[(axisnum * 2) + 1];
- /* long winded way to do
- * return maxf(absf(i1), absf(i2))
- * avoid abs from math.h */
+ /* long winded way to do:
+ * return max_ff(absf(i1), absf(i2))
+ * ...avoid abs from math.h */
if (i1 < 0) i1 = -i1;
if (i2 < 0) i2 = -i2;
if (i1 <i2) return i2;
- else return i1;
+ else return i1;
#else /* WITH_SDL */
return 0;
#endif /* WITH_SDL */
diff --git a/source/gameengine/GameLogic/Joystick/SCA_Joystick.h b/source/gameengine/GameLogic/Joystick/SCA_Joystick.h
index 685cc3fcc48..912484a2fe5 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_Joystick.h
+++ b/source/gameengine/GameLogic/Joystick/SCA_Joystick.h
@@ -65,7 +65,7 @@ class SCA_Joystick
/**
*support for JOYHAT_MAX hats (each is a direction)
*/
- int m_hat_array[JOYHAT_MAX];
+ int m_hat_array[JOYHAT_MAX];
/**
* Precision or range of the axes
diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp b/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
index efe76c3eb46..f50137cfcf6 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
+++ b/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
@@ -43,7 +43,7 @@ void SCA_Joystick::OnAxisMotion(SDL_Event* sdl_event)
if (sdl_event->jaxis.axis >= JOYAXIS_MAX)
return;
- m_axis_array[sdl_event->jaxis.axis]= sdl_event->jaxis.value;
+ m_axis_array[sdl_event->jaxis.axis] = sdl_event->jaxis.value;
m_istrig_axis = 1;
}
@@ -53,7 +53,7 @@ void SCA_Joystick::OnHatMotion(SDL_Event* sdl_event)
if (sdl_event->jhat.hat >= JOYHAT_MAX)
return;
- m_hat_array[sdl_event->jhat.hat]= sdl_event->jhat.value;
+ m_hat_array[sdl_event->jhat.hat] = sdl_event->jhat.value;
m_istrig_hat = 1;
}
@@ -89,8 +89,7 @@ void SCA_Joystick::HandleEvents(void)
SCA_Joystick::m_instance[i]->OnNothing(&sdl_event);
}
- while(SDL_PollEvent(&sdl_event))
- {
+ while (SDL_PollEvent(&sdl_event)) {
/* Note! m_instance[sdl_event.jaxis.which]
* will segfault if over JOYINDEX_MAX, not too nice but what are the chances? */
@@ -100,28 +99,27 @@ void SCA_Joystick::HandleEvents(void)
/* Note!, if you manage to press and release a button within 1 logic tick
* it wont work as it should */
- switch(sdl_event.type)
- {
- case SDL_JOYAXISMOTION:
- SCA_Joystick::m_instance[sdl_event.jaxis.which]->OnAxisMotion(&sdl_event);
- break;
- case SDL_JOYHATMOTION:
- SCA_Joystick::m_instance[sdl_event.jhat.which]->OnHatMotion(&sdl_event);
- break;
- case SDL_JOYBUTTONUP:
- SCA_Joystick::m_instance[sdl_event.jbutton.which]->OnButtonUp(&sdl_event);
- break;
- case SDL_JOYBUTTONDOWN:
- SCA_Joystick::m_instance[sdl_event.jbutton.which]->OnButtonDown(&sdl_event);
- break;
+ switch (sdl_event.type) {
+ case SDL_JOYAXISMOTION:
+ SCA_Joystick::m_instance[sdl_event.jaxis.which]->OnAxisMotion(&sdl_event);
+ break;
+ case SDL_JOYHATMOTION:
+ SCA_Joystick::m_instance[sdl_event.jhat.which]->OnHatMotion(&sdl_event);
+ break;
+ case SDL_JOYBUTTONUP:
+ SCA_Joystick::m_instance[sdl_event.jbutton.which]->OnButtonUp(&sdl_event);
+ break;
+ case SDL_JOYBUTTONDOWN:
+ SCA_Joystick::m_instance[sdl_event.jbutton.which]->OnButtonDown(&sdl_event);
+ break;
#if 0 /* Not used yet */
- case SDL_JOYBALLMOTION:
- SCA_Joystick::m_instance[sdl_event.jball.which]->OnBallMotion(&sdl_event);
- break;
+ case SDL_JOYBALLMOTION:
+ SCA_Joystick::m_instance[sdl_event.jball.which]->OnBallMotion(&sdl_event);
+ break;
#endif
- default:
- printf("SCA_Joystick::HandleEvents, Unknown SDL event, this should not happen\n");
- break;
+ default:
+ printf("SCA_Joystick::HandleEvents, Unknown SDL event, this should not happen\n");
+ break;
}
}
}
diff --git a/source/gameengine/GameLogic/SCA_ANDController.h b/source/gameengine/GameLogic/SCA_ANDController.h
index ccc3f9be3af..ff152d6d2fb 100644
--- a/source/gameengine/GameLogic/SCA_ANDController.h
+++ b/source/gameengine/GameLogic/SCA_ANDController.h
@@ -48,5 +48,4 @@ public:
virtual void Trigger(SCA_LogicManager* logicmgr);
};
-#endif //__SCA_ANDCONTROLLER_H__
-
+#endif /* __SCA_ANDCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_ActuatorEventManager.h b/source/gameengine/GameLogic/SCA_ActuatorEventManager.h
index dee9ea4e8ba..997be1145db 100644
--- a/source/gameengine/GameLogic/SCA_ActuatorEventManager.h
+++ b/source/gameengine/GameLogic/SCA_ActuatorEventManager.h
@@ -53,5 +53,4 @@ public:
#endif
};
-#endif //__SCA_ACTUATOREVENTMANAGER_H__
-
+#endif /* __SCA_ACTUATOREVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_ActuatorSensor.h b/source/gameengine/GameLogic/SCA_ActuatorSensor.h
index 894dc2162cf..6005bd3ac6c 100644
--- a/source/gameengine/GameLogic/SCA_ActuatorSensor.h
+++ b/source/gameengine/GameLogic/SCA_ActuatorSensor.h
@@ -64,7 +64,7 @@ public:
static int CheckActuator(void *self, const PyAttributeDef*);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif
+#endif /* __SCA_ACTUATORSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_AlwaysEventManager.h b/source/gameengine/GameLogic/SCA_AlwaysEventManager.h
index cf4063fba1f..47293c75726 100644
--- a/source/gameengine/GameLogic/SCA_AlwaysEventManager.h
+++ b/source/gameengine/GameLogic/SCA_AlwaysEventManager.h
@@ -47,5 +47,4 @@ public:
#endif
};
-#endif //__SCA_ALWAYSEVENTMANAGER_H__
-
+#endif /* __SCA_ALWAYSEVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp b/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp
index 6b697f4f15b..1a6a82a33eb 100644
--- a/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp
@@ -32,11 +32,10 @@
* \ingroup gamelogic
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// This warning tells us about truncation of __long__ stl-generated names.
-// It can occasionally cause DevStudio to have internal compiler warnings.
-#pragma warning( disable : 4786 )
+#ifdef _MSC_VER
+ /* This warning tells us about truncation of __long__ stl-generated names.
+ * It can occasionally cause DevStudio to have internal compiler warnings. */
+# pragma warning( disable:4786 )
#endif
#include "SCA_AlwaysSensor.h"
diff --git a/source/gameengine/GameLogic/SCA_AlwaysSensor.h b/source/gameengine/GameLogic/SCA_AlwaysSensor.h
index d0963fd0ea1..e0ab4279b1c 100644
--- a/source/gameengine/GameLogic/SCA_AlwaysSensor.h
+++ b/source/gameengine/GameLogic/SCA_AlwaysSensor.h
@@ -50,5 +50,4 @@ public:
virtual void Init();
};
-#endif //__SCA_ALWAYSSENSOR_H__
-
+#endif /* __SCA_ALWAYSSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_BasicEventManager.h b/source/gameengine/GameLogic/SCA_BasicEventManager.h
index 24206e46a61..a015233454b 100644
--- a/source/gameengine/GameLogic/SCA_BasicEventManager.h
+++ b/source/gameengine/GameLogic/SCA_BasicEventManager.h
@@ -54,5 +54,4 @@ public:
#endif
};
-#endif //__SCA_BASICEVENTMANAGER_H__
-
+#endif /* __SCA_BASICEVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_DelaySensor.cpp b/source/gameengine/GameLogic/SCA_DelaySensor.cpp
index f2bcd67e652..af751cffc2e 100644
--- a/source/gameengine/GameLogic/SCA_DelaySensor.cpp
+++ b/source/gameengine/GameLogic/SCA_DelaySensor.cpp
@@ -32,11 +32,10 @@
* \ingroup gamelogic
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// This warning tells us about truncation of __long__ stl-generated names.
-// It can occasionally cause DevStudio to have internal compiler warnings.
-#pragma warning( disable : 4786 )
+#ifdef _MSC_VER
+ /* This warning tells us about truncation of __long__ stl-generated names.
+ * It can occasionally cause DevStudio to have internal compiler warnings. */
+# pragma warning( disable:4786 )
#endif
#include <stddef.h>
diff --git a/source/gameengine/GameLogic/SCA_DelaySensor.h b/source/gameengine/GameLogic/SCA_DelaySensor.h
index 2c408921f27..b516cd8360e 100644
--- a/source/gameengine/GameLogic/SCA_DelaySensor.h
+++ b/source/gameengine/GameLogic/SCA_DelaySensor.h
@@ -65,5 +65,4 @@ public:
};
-#endif //__KX_ALWAYSSENSOR
-
+#endif /* __SCA_DELAYSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_ExpressionController.h b/source/gameengine/GameLogic/SCA_ExpressionController.h
index 06edc83ab96..c16944ccde1 100644
--- a/source/gameengine/GameLogic/SCA_ExpressionController.h
+++ b/source/gameengine/GameLogic/SCA_ExpressionController.h
@@ -63,5 +63,4 @@ public:
#endif
};
-#endif //__SCA_EXPRESSIONCONTROLLER_H__
-
+#endif /* __SCA_EXPRESSIONCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_IActuator.h b/source/gameengine/GameLogic/SCA_IActuator.h
index 801483bb882..090df1e75e2 100644
--- a/source/gameengine/GameLogic/SCA_IActuator.h
+++ b/source/gameengine/GameLogic/SCA_IActuator.h
@@ -164,5 +164,4 @@ public:
#endif
};
-#endif //__SCA_IACTUATOR_H__
-
+#endif /* __SCA_IACTUATOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_IController.cpp b/source/gameengine/GameLogic/SCA_IController.cpp
index 3fda542410a..57f7dd64287 100644
--- a/source/gameengine/GameLogic/SCA_IController.cpp
+++ b/source/gameengine/GameLogic/SCA_IController.cpp
@@ -238,19 +238,19 @@ PyAttributeDef SCA_IController::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* SCA_IController::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_IController::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_IController* self= static_cast<SCA_IController*>(self_v);
+ SCA_IController* self = static_cast<SCA_IController*>(self_v);
return PyLong_FromSsize_t(self->m_statemask);
}
-PyObject* SCA_IController::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_IController::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- return KX_PythonSeq_CreatePyObject((static_cast<SCA_IController*>(self_v))->m_proxy, KX_PYGENSEQ_CONT_TYPE_SENSORS);
+ return KX_PythonSeq_CreatePyObject((static_cast<SCA_IController*>(self_v))->m_proxy, KX_PYGENSEQ_CONT_TYPE_SENSORS);
}
-PyObject* SCA_IController::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_IController::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- return KX_PythonSeq_CreatePyObject((static_cast<SCA_IController*>(self_v))->m_proxy, KX_PYGENSEQ_CONT_TYPE_ACTUATORS);
+ return KX_PythonSeq_CreatePyObject((static_cast<SCA_IController*>(self_v))->m_proxy, KX_PYGENSEQ_CONT_TYPE_ACTUATORS);
}
#endif // WITH_PYTHON
diff --git a/source/gameengine/GameLogic/SCA_IController.h b/source/gameengine/GameLogic/SCA_IController.h
index 656c4299dff..1bc6b60bf1e 100644
--- a/source/gameengine/GameLogic/SCA_IController.h
+++ b/source/gameengine/GameLogic/SCA_IController.h
@@ -106,8 +106,7 @@ public:
static PyObject* pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static PyObject* pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static PyObject* pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif
-
+#endif /* __SCA_ICONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_IInputDevice.cpp b/source/gameengine/GameLogic/SCA_IInputDevice.cpp
index 16626b05526..f4fce034c87 100644
--- a/source/gameengine/GameLogic/SCA_IInputDevice.cpp
+++ b/source/gameengine/GameLogic/SCA_IInputDevice.cpp
@@ -45,7 +45,7 @@ SCA_IInputDevice::SCA_IInputDevice()
SCA_IInputDevice::~SCA_IInputDevice()
{
-}
+}
void SCA_IInputDevice::HookEscape()
{
@@ -134,6 +134,6 @@ void SCA_IInputDevice::NextFrame()
break;
default:
; /* error */
- }
+ }
}
}
diff --git a/source/gameengine/GameLogic/SCA_IInputDevice.h b/source/gameengine/GameLogic/SCA_IInputDevice.h
index 0382a2efd21..1a403f40955 100644
--- a/source/gameengine/GameLogic/SCA_IInputDevice.h
+++ b/source/gameengine/GameLogic/SCA_IInputDevice.h
@@ -69,7 +69,7 @@ class SCA_IInputDevice
public:
SCA_IInputDevice();
- virtual ~SCA_IInputDevice();
+ virtual ~SCA_IInputDevice();
enum KX_EnumInputs {
@@ -120,17 +120,17 @@ public:
KX_RETKEY = 13,
KX_SPACEKEY = 32,
KX_PADASTERKEY = 42,
- KX_COMMAKEY = 44,
- KX_MINUSKEY = 45,
+ KX_COMMAKEY = 44,
+ KX_MINUSKEY = 45,
KX_PERIODKEY = 46,
KX_ZEROKEY = 48,
KX_ONEKEY, // =49
- KX_TWOKEY,
+ KX_TWOKEY,
KX_THREEKEY,
- KX_FOURKEY,
- KX_FIVEKEY,
- KX_SIXKEY,
+ KX_FOURKEY,
+ KX_FIVEKEY,
+ KX_SIXKEY,
KX_SEVENKEY,
KX_EIGHTKEY,
KX_NINEKEY, // = 57
@@ -167,17 +167,17 @@ public:
KX_CAPSLOCKKEY, // 123
KX_LEFTCTRLKEY, // 124
- KX_LEFTALTKEY,
- KX_RIGHTALTKEY,
- KX_RIGHTCTRLKEY,
- KX_RIGHTSHIFTKEY,
+ KX_LEFTALTKEY,
+ KX_RIGHTALTKEY,
+ KX_RIGHTCTRLKEY,
+ KX_RIGHTSHIFTKEY,
KX_LEFTSHIFTKEY,// 129
KX_ESCKEY, // 130
KX_TABKEY, //131
- KX_LINEFEEDKEY, // 132
+ KX_LINEFEEDKEY, // 132
KX_BACKSPACEKEY,
KX_DELKEY,
KX_SEMICOLONKEY, // 135
@@ -188,13 +188,13 @@ public:
KX_SLASHKEY, //138
KX_BACKSLASHKEY,
- KX_EQUALKEY,
- KX_LEFTBRACKETKEY,
+ KX_EQUALKEY,
+ KX_LEFTBRACKETKEY,
KX_RIGHTBRACKETKEY, // 142
KX_LEFTARROWKEY, // 145
KX_DOWNARROWKEY,
- KX_RIGHTARROWKEY,
+ KX_RIGHTARROWKEY,
KX_UPARROWKEY, // 148
KX_PAD2 ,
@@ -320,5 +320,5 @@ public:
#endif
};
-#endif //__SCA_IINPUTDEVICE_H__
+#endif /* __SCA_IINPUTDEVICE_H__ */
diff --git a/source/gameengine/GameLogic/SCA_ILogicBrick.cpp b/source/gameengine/GameLogic/SCA_ILogicBrick.cpp
index 018a939f68d..ab0e6c5edcb 100644
--- a/source/gameengine/GameLogic/SCA_ILogicBrick.cpp
+++ b/source/gameengine/GameLogic/SCA_ILogicBrick.cpp
@@ -231,9 +231,9 @@ int SCA_ILogicBrick::CheckProperty(void *self, const PyAttributeDef *attrdef)
}
/*Attribute functions */
-PyObject* SCA_ILogicBrick::pyattr_get_owner(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_ILogicBrick::pyattr_get_owner(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_ILogicBrick* self= static_cast<SCA_ILogicBrick*>(self_v);
+ SCA_ILogicBrick* self = static_cast<SCA_ILogicBrick*>(self_v);
CValue* parent = self->GetParent();
if (parent)
@@ -254,9 +254,9 @@ bool SCA_ILogicBrick::PyArgToBool(int boolArg)
}
}
-PyObject* SCA_ILogicBrick::BoolToPyArg(bool boolarg)
+PyObject *SCA_ILogicBrick::BoolToPyArg(bool boolarg)
{
- return PyLong_FromSsize_t(boolarg? KX_TRUE: KX_FALSE);
+ return PyLong_FromSsize_t(boolarg? KX_TRUE: KX_FALSE);
}
#endif // WITH_PYTHON
diff --git a/source/gameengine/GameLogic/SCA_ILogicBrick.h b/source/gameengine/GameLogic/SCA_ILogicBrick.h
index b505353c7cd..dc0aa4ce331 100644
--- a/source/gameengine/GameLogic/SCA_ILogicBrick.h
+++ b/source/gameengine/GameLogic/SCA_ILogicBrick.h
@@ -157,11 +157,10 @@ protected:
bool PyArgToBool(int boolArg);
/** Convert a a c++ value to KX_TRUE, KX_FALSE in Python. */
- PyObject* BoolToPyArg(bool);
+ PyObject *BoolToPyArg(bool);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif
-
+#endif /* __SCA_ILOGICBRICK_H__ */
diff --git a/source/gameengine/GameLogic/SCA_IObject.cpp b/source/gameengine/GameLogic/SCA_IObject.cpp
index b90952b2092..ab9e2781001 100644
--- a/source/gameengine/GameLogic/SCA_IObject.cpp
+++ b/source/gameengine/GameLogic/SCA_IObject.cpp
@@ -224,7 +224,7 @@ SCA_IController* SCA_IObject::FindController(const STR_String& controllername)
{
foundcontroller = (*itc);
break;
- }
+ }
}
return foundcontroller;
}
diff --git a/source/gameengine/GameLogic/SCA_IObject.h b/source/gameengine/GameLogic/SCA_IObject.h
index 0e657794195..0189af00322 100644
--- a/source/gameengine/GameLogic/SCA_IObject.h
+++ b/source/gameengine/GameLogic/SCA_IObject.h
@@ -43,7 +43,7 @@ class SCA_IController;
class SCA_IActuator;
#ifdef WITH_PYTHON
-template<class T> T PyVecTo(PyObject*);
+template<class T> T PyVecTo(PyObject *);
#endif
typedef std::vector<SCA_ISensor *> SCA_SensorList;
@@ -213,7 +213,7 @@ public:
*/
unsigned int GetState(void) { return m_state; }
-// const class MT_Point3& ConvertPythonPylist(PyObject* pylist);
+// const class MT_Point3& ConvertPythonPylist(PyObject *pylist);
virtual int GetGameObjectType() {return -1;}
@@ -225,5 +225,4 @@ public:
};
-#endif //__SCA_IOBJECT_H__
-
+#endif /* __SCA_IOBJECT_H__ */
diff --git a/source/gameengine/GameLogic/SCA_IScene.h b/source/gameengine/GameLogic/SCA_IScene.h
index a399e313082..997266976ad 100644
--- a/source/gameengine/GameLogic/SCA_IScene.h
+++ b/source/gameengine/GameLogic/SCA_IScene.h
@@ -78,5 +78,4 @@ public:
#endif
};
-#endif //__SCA_ISCENE_H__
-
+#endif /* __SCA_ISCENE_H__ */
diff --git a/source/gameengine/GameLogic/SCA_ISensor.cpp b/source/gameengine/GameLogic/SCA_ISensor.cpp
index 76b9a8df00f..bfb78abef04 100644
--- a/source/gameengine/GameLogic/SCA_ISensor.cpp
+++ b/source/gameengine/GameLogic/SCA_ISensor.cpp
@@ -248,7 +248,7 @@ void SCA_ISensor::Activate(class SCA_LogicManager* logicmgr)
if (result) {
// the sensor triggered this frame
if (m_state || !m_tap) {
- ActivateControllers(logicmgr);
+ ActivateControllers(logicmgr);
// reset these counters so that pulse are synchronized with transition
m_pos_ticks = 0;
m_neg_ticks = 0;
@@ -380,24 +380,24 @@ PyAttributeDef SCA_ISensor::Attributes[] = {
};
-PyObject* SCA_ISensor::pyattr_get_triggered(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_ISensor::pyattr_get_triggered(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_ISensor* self= static_cast<SCA_ISensor*>(self_v);
+ SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
int retval = 0;
if (SCA_PythonController::m_sCurrentController)
retval = SCA_PythonController::m_sCurrentController->IsTriggered(self);
return PyLong_FromSsize_t(retval);
}
-PyObject* SCA_ISensor::pyattr_get_positive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_ISensor::pyattr_get_positive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_ISensor* self= static_cast<SCA_ISensor*>(self_v);
+ SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
return PyLong_FromSsize_t(self->GetState());
}
-PyObject* SCA_ISensor::pyattr_get_status(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_ISensor::pyattr_get_status(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_ISensor* self= static_cast<SCA_ISensor*>(self_v);
+ SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
int status = 0;
if (self->GetState())
{
@@ -417,21 +417,21 @@ PyObject* SCA_ISensor::pyattr_get_status(void *self_v, const KX_PYATTRIBUTE_DEF
return PyLong_FromSsize_t(status);
}
-PyObject* SCA_ISensor::pyattr_get_posTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_ISensor::pyattr_get_posTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_ISensor* self= static_cast<SCA_ISensor*>(self_v);
+ SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
return PyLong_FromLong(self->GetPosTicks());
}
-PyObject* SCA_ISensor::pyattr_get_negTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_ISensor::pyattr_get_negTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_ISensor* self= static_cast<SCA_ISensor*>(self_v);
+ SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
return PyLong_FromLong(self->GetNegTicks());
}
int SCA_ISensor::pyattr_check_level(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_ISensor* self= static_cast<SCA_ISensor*>(self_v);
+ SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
if (self->m_level)
self->m_tap = false;
return 0;
@@ -439,7 +439,7 @@ int SCA_ISensor::pyattr_check_level(void *self_v, const KX_PYATTRIBUTE_DEF *attr
int SCA_ISensor::pyattr_check_tap(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_ISensor* self= static_cast<SCA_ISensor*>(self_v);
+ SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
if (self->m_tap)
self->m_level = false;
return 0;
diff --git a/source/gameengine/GameLogic/SCA_ISensor.h b/source/gameengine/GameLogic/SCA_ISensor.h
index 3bb29f3f0a2..091aa675741 100644
--- a/source/gameengine/GameLogic/SCA_ISensor.h
+++ b/source/gameengine/GameLogic/SCA_ISensor.h
@@ -212,8 +212,7 @@ public:
KX_SENSOR_JUST_DEACTIVATED
};
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif //__SCA_ISENSOR_H__
-
+#endif /* __SCA_ISENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_JoystickSensor.cpp b/source/gameengine/GameLogic/SCA_JoystickSensor.cpp
index 2c6beb79fd3..0c4dcae16f7 100644
--- a/source/gameengine/GameLogic/SCA_JoystickSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_JoystickSensor.cpp
@@ -60,7 +60,7 @@ SCA_JoystickSensor::SCA_JoystickSensor(class SCA_JoystickManager* eventmgr,
m_joymode(joymode),
m_joyindex(joyindex),
m_bAllEvents(allevents)
-{
+{
/*
std::cout << " axis " << m_axis << std::endl;
std::cout << " axis flag " << m_axisf << std::endl;
@@ -113,21 +113,21 @@ bool SCA_JoystickSensor::Evaluate()
return false;
m_reset = false;
- switch(m_joymode)
- {
- case KX_JOYSENSORMODE_AXIS:
+
+ switch (m_joymode) {
+ case KX_JOYSENSORMODE_AXIS:
{
- /* what is what!
- m_axisf == JOYAXIS_RIGHT, JOYAXIS_UP, JOYAXIS_DOWN, JOYAXIS_LEFT
- m_axisf == 1 == up
- m_axisf == 2 == left
- m_axisf == 3 == down
-
- numberof== m_axis (1-4), range is half of JOYAXIS_MAX since
- it assumes the axis joysticks are axis parirs (0,1), (2,3), etc
- also note that this starts at 1 where functions its used
- with expect a zero index.
- */
+ /* what is what!
+ * m_axisf == JOYAXIS_RIGHT, JOYAXIS_UP, JOYAXIS_DOWN, JOYAXIS_LEFT
+ * m_axisf == 1 == up
+ * m_axisf == 2 == left
+ * m_axisf == 3 == down
+ *
+ * numberof== m_axis (1-4), range is half of JOYAXIS_MAX since
+ * it assumes the axis joysticks are axis parirs (0,1), (2,3), etc
+ * also note that this starts at 1 where functions its used
+ * with expect a zero index.
+ */
if (!js->IsTrigAxis() && !reset) /* No events from SDL? - don't bother */
return false;
@@ -159,7 +159,7 @@ bool SCA_JoystickSensor::Evaluate()
}
break;
}
- case KX_JOYSENSORMODE_AXIS_SINGLE:
+ case KX_JOYSENSORMODE_AXIS_SINGLE:
{
/* Like KX_JOYSENSORMODE_AXIS but don't pair up axis */
if (!js->IsTrigAxis() && !reset) /* No events from SDL? - don't bother */
@@ -179,12 +179,12 @@ bool SCA_JoystickSensor::Evaluate()
}
break;
}
-
- case KX_JOYSENSORMODE_BUTTON:
+
+ case KX_JOYSENSORMODE_BUTTON:
{
- /* what is what!
- m_button = the actual button in question
- */
+ /* what is what!
+ * m_button = the actual button in question
+ */
if (!js->IsTrigButton() && !reset) /* No events from SDL? - don't bother */
return false;
@@ -200,12 +200,12 @@ bool SCA_JoystickSensor::Evaluate()
}
break;
}
- case KX_JOYSENSORMODE_HAT:
+ case KX_JOYSENSORMODE_HAT:
{
- /* what is what!
- numberof = m_hat -- max 4
- direction= m_hatf -- max 12
- */
+ /* what is what!
+ * numberof = m_hat -- max 4
+ * direction= m_hatf -- max 12
+ */
if (!js->IsTrigHat() && !reset) /* No events from SDL? - don't bother */
return false;
@@ -222,18 +222,19 @@ bool SCA_JoystickSensor::Evaluate()
}
break;
}
- /* test for ball anyone ?*/
- default:
- printf("Error invalid switch statement\n");
- break;
+ /* test for ball anyone ?*/
+ default:
+ printf("Error invalid switch statement\n");
+ break;
}
- /* if not all events are enabled, only send a positive pulse when
+ /* if not all events are enabled, only send a positive pulse when
* the button state changes */
if (!m_bAllEvents) {
if (m_istrig_prev == m_istrig) {
result = false;
- } else {
+ }
+ else {
m_istrig_prev = m_istrig;
}
}
@@ -308,7 +309,7 @@ PyAttributeDef SCA_JoystickSensor::Attributes[] = {
const char SCA_JoystickSensor::GetButtonActiveList_doc[] =
"getButtonActiveList\n"
"\tReturns a list containing the indices of the button currently pressed.\n";
-PyObject* SCA_JoystickSensor::PyGetButtonActiveList( )
+PyObject *SCA_JoystickSensor::PyGetButtonActiveList( )
{
SCA_Joystick *joy = ((SCA_JoystickManager *)m_eventmgr)->GetJoystickDevice(m_joyindex);
PyObject *ls = PyList_New(0);
@@ -331,7 +332,7 @@ PyObject* SCA_JoystickSensor::PyGetButtonActiveList( )
const char SCA_JoystickSensor::GetButtonStatus_doc[] =
"getButtonStatus(buttonIndex)\n"
"\tReturns a bool of the current pressed state of the specified button.\n";
-PyObject* SCA_JoystickSensor::PyGetButtonStatus( PyObject* args )
+PyObject *SCA_JoystickSensor::PyGetButtonStatus( PyObject *args )
{
SCA_Joystick *joy = ((SCA_JoystickManager *)m_eventmgr)->GetJoystickDevice(m_joyindex);
int index;
@@ -345,24 +346,24 @@ PyObject* SCA_JoystickSensor::PyGetButtonStatus( PyObject* args )
return PyBool_FromLong(0);
}
-PyObject* SCA_JoystickSensor::pyattr_get_axis_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_JoystickSensor::pyattr_get_axis_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_JoystickSensor* self= static_cast<SCA_JoystickSensor*>(self_v);
+ SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
int axis_index= joy->GetNumberOfAxes();
PyObject *list= PyList_New(axis_index);
- while(axis_index--) {
+ while (axis_index--) {
PyList_SET_ITEM(list, axis_index, PyLong_FromSsize_t(joy->GetAxisPosition(axis_index)));
}
return list;
}
-PyObject* SCA_JoystickSensor::pyattr_get_axis_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_JoystickSensor::pyattr_get_axis_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_JoystickSensor* self= static_cast<SCA_JoystickSensor*>(self_v);
+ SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
if (self->m_joymode != KX_JOYSENSORMODE_AXIS_SINGLE) {
@@ -373,53 +374,53 @@ PyObject* SCA_JoystickSensor::pyattr_get_axis_single(void *self_v, const KX_PYAT
return PyLong_FromSsize_t(joy->GetAxisPosition(self->m_axis-1));
}
-PyObject* SCA_JoystickSensor::pyattr_get_hat_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_JoystickSensor::pyattr_get_hat_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_JoystickSensor* self= static_cast<SCA_JoystickSensor*>(self_v);
+ SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
int hat_index= joy->GetNumberOfHats();
PyObject *list= PyList_New(hat_index);
- while(hat_index--) {
+ while (hat_index--) {
PyList_SET_ITEM(list, hat_index, PyLong_FromSsize_t(joy->GetHat(hat_index)));
}
return list;
}
-PyObject* SCA_JoystickSensor::pyattr_get_hat_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_JoystickSensor::pyattr_get_hat_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_JoystickSensor* self= static_cast<SCA_JoystickSensor*>(self_v);
+ SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
return PyLong_FromSsize_t(joy->GetHat(self->m_hat-1));
}
-PyObject* SCA_JoystickSensor::pyattr_get_num_axis(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_JoystickSensor::pyattr_get_num_axis(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_JoystickSensor* self= static_cast<SCA_JoystickSensor*>(self_v);
+ SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
return PyLong_FromSsize_t( joy ? joy->GetNumberOfAxes() : 0 );
}
-PyObject* SCA_JoystickSensor::pyattr_get_num_buttons(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_JoystickSensor::pyattr_get_num_buttons(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_JoystickSensor* self= static_cast<SCA_JoystickSensor*>(self_v);
+ SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
return PyLong_FromSsize_t( joy ? joy->GetNumberOfButtons() : 0 );
}
-PyObject* SCA_JoystickSensor::pyattr_get_num_hats(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_JoystickSensor::pyattr_get_num_hats(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_JoystickSensor* self= static_cast<SCA_JoystickSensor*>(self_v);
+ SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
return PyLong_FromSsize_t( joy ? joy->GetNumberOfHats() : 0 );
}
-PyObject* SCA_JoystickSensor::pyattr_get_connected(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_JoystickSensor::pyattr_get_connected(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_JoystickSensor* self= static_cast<SCA_JoystickSensor*>(self_v);
+ SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
return PyBool_FromLong( joy ? joy->Connected() : 0 );
}
diff --git a/source/gameengine/GameLogic/SCA_JoystickSensor.h b/source/gameengine/GameLogic/SCA_JoystickSensor.h
index 5dc35faf244..6c6dc019a5e 100644
--- a/source/gameengine/GameLogic/SCA_JoystickSensor.h
+++ b/source/gameengine/GameLogic/SCA_JoystickSensor.h
@@ -30,11 +30,11 @@
*/
-#ifndef __JOYSENSOR_H_
-#define __JOYSENSOR_H
+#ifndef __JOYSENSOR_H__
+#define __JOYSENSOR_H__
#include "SCA_ISensor.h"
-#include "./Joystick/SCA_JoystickDefines.h"
+#include "Joystick/SCA_JoystickDefines.h"
class SCA_JoystickSensor :public SCA_ISensor
{
@@ -161,8 +161,8 @@ public:
return 0;
}
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif
+#endif /* __JOYSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_KeyboardManager.h b/source/gameengine/GameLogic/SCA_KeyboardManager.h
index 2d9ad45833f..cd1cbf4adee 100644
--- a/source/gameengine/GameLogic/SCA_KeyboardManager.h
+++ b/source/gameengine/GameLogic/SCA_KeyboardManager.h
@@ -54,7 +54,7 @@ public:
bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode);
- virtual void NextFrame();
+ virtual void NextFrame();
SCA_IInputDevice* GetInputDevice();
@@ -63,5 +63,4 @@ public:
#endif
};
-#endif //__SCA_KEYBOARDMANAGER_H__
-
+#endif /* __SCA_KEYBOARDMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp b/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp
index 5208252ceae..b3346270b61 100644
--- a/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp
@@ -225,37 +225,37 @@ bool SCA_KeyboardSensor::Evaluate()
*/
if (m_qual > 0) {
const SCA_InputEvent & qualevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) m_qual);
- switch(qualevent.m_status) {
- case SCA_InputEvent::KX_NO_INPUTSTATUS:
- qual = false;
- break;
- case SCA_InputEvent::KX_JUSTRELEASED:
- qual_change = true;
- qual = false;
- break;
- case SCA_InputEvent::KX_JUSTACTIVATED:
- qual_change = true;
- case SCA_InputEvent::KX_ACTIVE:
- /* do nothing */
- break;
+ switch (qualevent.m_status) {
+ case SCA_InputEvent::KX_NO_INPUTSTATUS:
+ qual = false;
+ break;
+ case SCA_InputEvent::KX_JUSTRELEASED:
+ qual_change = true;
+ qual = false;
+ break;
+ case SCA_InputEvent::KX_JUSTACTIVATED:
+ qual_change = true;
+ case SCA_InputEvent::KX_ACTIVE:
+ /* do nothing */
+ break;
}
}
if (m_qual2 > 0 && qual==true) {
const SCA_InputEvent & qualevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) m_qual2);
/* copy of above */
- switch(qualevent.m_status) {
- case SCA_InputEvent::KX_NO_INPUTSTATUS:
- qual = false;
- break;
- case SCA_InputEvent::KX_JUSTRELEASED:
- qual_change = true;
- qual = false;
- break;
- case SCA_InputEvent::KX_JUSTACTIVATED:
- qual_change = true;
- case SCA_InputEvent::KX_ACTIVE:
- /* do nothing */
- break;
+ switch (qualevent.m_status) {
+ case SCA_InputEvent::KX_NO_INPUTSTATUS:
+ qual = false;
+ break;
+ case SCA_InputEvent::KX_JUSTRELEASED:
+ qual_change = true;
+ qual = false;
+ break;
+ case SCA_InputEvent::KX_JUSTACTIVATED:
+ qual_change = true;
+ case SCA_InputEvent::KX_ACTIVE:
+ /* do nothing */
+ break;
}
}
/* done reading qualifiers */
@@ -351,12 +351,12 @@ void SCA_KeyboardSensor::AddToTargetProp(int keyIndex)
CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
GetParent()->SetProperty(m_targetprop, newstringprop);
newstringprop->Release();
- }
+ }
} else {
/* append */
char pchar = ToCharacter(keyIndex, IsShifted());
STR_String newprop = tprop->GetText() + pchar;
- CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
+ CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
GetParent()->SetProperty(m_targetprop, newstringprop);
newstringprop->Release();
}
@@ -365,7 +365,7 @@ void SCA_KeyboardSensor::AddToTargetProp(int keyIndex)
/* Make a new property. Deletes can be ignored. */
char pchar = ToCharacter(keyIndex, IsShifted());
STR_String newprop = pchar;
- CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
+ CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
GetParent()->SetProperty(m_targetprop, newstringprop);
newstringprop->Release();
}
@@ -376,7 +376,7 @@ void SCA_KeyboardSensor::AddToTargetProp(int keyIndex)
/**
* Tests whether shift is pressed
- */
+ */
bool SCA_KeyboardSensor::IsShifted(void)
{
SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)m_eventmgr)->GetInputDevice();
@@ -391,9 +391,10 @@ bool SCA_KeyboardSensor::IsShifted(void)
== SCA_InputEvent::KX_JUSTACTIVATED)
) {
return true;
- } else {
+ }
+ else {
return false;
- }
+ }
}
void SCA_KeyboardSensor::LogKeystrokes(void)
@@ -494,25 +495,25 @@ PyAttributeDef SCA_KeyboardSensor::Attributes[] = {
};
-PyObject* SCA_KeyboardSensor::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_KeyboardSensor::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_KeyboardSensor* self= static_cast<SCA_KeyboardSensor*>(self_v);
+ SCA_KeyboardSensor* self = static_cast<SCA_KeyboardSensor*>(self_v);
SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)self->m_eventmgr)->GetInputDevice();
- PyObject* resultlist = PyList_New(0);
+ PyObject *resultlist = PyList_New(0);
for (int i=SCA_IInputDevice::KX_BEGINKEY ; i<= SCA_IInputDevice::KX_ENDKEY;i++)
{
const SCA_InputEvent & inevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) i);
if (inevent.m_status != SCA_InputEvent::KX_NO_INPUTSTATUS)
{
- PyObject* keypair = PyList_New(2);
+ PyObject *keypair = PyList_New(2);
PyList_SET_ITEM(keypair,0,PyLong_FromSsize_t(i));
PyList_SET_ITEM(keypair,1,PyLong_FromSsize_t(inevent.m_status));
PyList_Append(resultlist,keypair);
}
- }
+ }
return resultlist;
}
@@ -655,7 +656,7 @@ bool IsPrintable(int keyIndex)
/**
* Tests whether this is a delete key.
- */
+ */
bool IsDelete(int keyIndex)
{
if ( (keyIndex == SCA_IInputDevice::KX_DELKEY)
diff --git a/source/gameengine/GameLogic/SCA_KeyboardSensor.h b/source/gameengine/GameLogic/SCA_KeyboardSensor.h
index c059aba305b..c6610d0284e 100644
--- a/source/gameengine/GameLogic/SCA_KeyboardSensor.h
+++ b/source/gameengine/GameLogic/SCA_KeyboardSensor.h
@@ -134,11 +134,8 @@ bool IsPrintable(int keyIndex);
/**
* Tests whether this is a delete key.
- */
+ */
bool IsDelete(int keyIndex);
-#endif //__SCA_KEYBOARDSENSOR_H__
-
-
-
+#endif /* __SCA_KEYBOARDSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_LogicManager.h b/source/gameengine/GameLogic/SCA_LogicManager.h
index 817f3a1c22a..690930196b3 100644
--- a/source/gameengine/GameLogic/SCA_LogicManager.h
+++ b/source/gameengine/GameLogic/SCA_LogicManager.h
@@ -31,8 +31,8 @@
#ifndef __SCA_LOGICMANAGER_H__
#define __SCA_LOGICMANAGER_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786)
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
#endif
#include <vector>
@@ -151,5 +151,4 @@ public:
#endif
};
-#endif //__SCA_LOGICMANAGER_H__
-
+#endif /* __SCA_LOGICMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_MouseManager.cpp b/source/gameengine/GameLogic/SCA_MouseManager.cpp
index a067b9c4d5b..6d05b862c2d 100644
--- a/source/gameengine/GameLogic/SCA_MouseManager.cpp
+++ b/source/gameengine/GameLogic/SCA_MouseManager.cpp
@@ -34,10 +34,10 @@
*/
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// This warning tells us about truncation of __long__ stl-generated names.
-// It can occasionally cause DevStudio to have internal compiler warnings.
-#pragma warning( disable : 4786 )
+#ifdef _MSC_VER
+ /* This warning tells us about truncation of __long__ stl-generated names.
+ * It can occasionally cause DevStudio to have internal compiler warnings. */
+# pragma warning( disable:4786 )
#endif
#include "BoolValue.h"
diff --git a/source/gameengine/GameLogic/SCA_MouseManager.h b/source/gameengine/GameLogic/SCA_MouseManager.h
index 60edb2816cb..a57e52070a7 100644
--- a/source/gameengine/GameLogic/SCA_MouseManager.h
+++ b/source/gameengine/GameLogic/SCA_MouseManager.h
@@ -63,7 +63,7 @@ public:
* mouse related events. Can also flag mouse movement.
*/
bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode);
- virtual void NextFrame();
+ virtual void NextFrame();
SCA_IInputDevice* GetInputDevice();
@@ -72,5 +72,4 @@ public:
#endif
};
-#endif //__SCA_MOUSEMANAGER_H__
-
+#endif /* __SCA_MOUSEMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_MouseSensor.cpp b/source/gameengine/GameLogic/SCA_MouseSensor.cpp
index f4ee54c56a6..51e0bc6550b 100644
--- a/source/gameengine/GameLogic/SCA_MouseSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_MouseSensor.cpp
@@ -156,7 +156,7 @@ bool SCA_MouseSensor::Evaluate()
case KX_MOUSESENSORMODE_WHEELDOWN:
{
const SCA_InputEvent& mevent = mousedev->GetEventValue(m_hotkey);
- switch (mevent.m_status) {
+ switch (mevent.m_status) {
case SCA_InputEvent::KX_JUSTACTIVATED:
m_val = 1;
result = true;
@@ -189,15 +189,15 @@ bool SCA_MouseSensor::Evaluate()
const SCA_InputEvent& eventY = mousedev->GetEventValue(SCA_IInputDevice::KX_MOUSEY);
if (eventX.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- eventY.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- eventX.m_status == SCA_InputEvent::KX_ACTIVE ||
- eventY.m_status == SCA_InputEvent::KX_ACTIVE)
+ eventY.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
+ eventX.m_status == SCA_InputEvent::KX_ACTIVE ||
+ eventY.m_status == SCA_InputEvent::KX_ACTIVE)
{
m_val = 1;
result = true;
}
else if (eventX.m_status == SCA_InputEvent::KX_JUSTRELEASED ||
- eventY.m_status == SCA_InputEvent::KX_JUSTRELEASED )
+ eventY.m_status == SCA_InputEvent::KX_JUSTRELEASED )
{
m_val = 0;
result = true;
diff --git a/source/gameengine/GameLogic/SCA_MouseSensor.h b/source/gameengine/GameLogic/SCA_MouseSensor.h
index d4eff371d4a..8d05a548681 100644
--- a/source/gameengine/GameLogic/SCA_MouseSensor.h
+++ b/source/gameengine/GameLogic/SCA_MouseSensor.h
@@ -117,5 +117,4 @@ class SCA_MouseSensor : public SCA_ISensor
#endif
};
-#endif //__SCA_MOUSESENSOR_H__
-
+#endif /* __SCA_MOUSESENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_NANDController.h b/source/gameengine/GameLogic/SCA_NANDController.h
index 040df7f0ade..a3f02908dd2 100644
--- a/source/gameengine/GameLogic/SCA_NANDController.h
+++ b/source/gameengine/GameLogic/SCA_NANDController.h
@@ -49,5 +49,4 @@ public:
/* --------------------------------------------------------------------- */
};
-#endif //__SCA_NANDCONTROLLER_H__
-
+#endif /* __SCA_NANDCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_NORController.h b/source/gameengine/GameLogic/SCA_NORController.h
index 1630f8055ec..ec8159de8d1 100644
--- a/source/gameengine/GameLogic/SCA_NORController.h
+++ b/source/gameengine/GameLogic/SCA_NORController.h
@@ -45,5 +45,4 @@ public:
virtual void Trigger(SCA_LogicManager* logicmgr);
};
-#endif //__SCA_NORCONTROLLER_H__
-
+#endif /* __SCA_NORCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_ORController.h b/source/gameengine/GameLogic/SCA_ORController.h
index 9a4e4c7398d..9499c893c72 100644
--- a/source/gameengine/GameLogic/SCA_ORController.h
+++ b/source/gameengine/GameLogic/SCA_ORController.h
@@ -46,5 +46,4 @@ public:
virtual void Trigger(SCA_LogicManager* logicmgr);
};
-#endif //__SCA_ORCONTROLLER_H__
-
+#endif /* __SCA_ORCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_PropertyActuator.cpp b/source/gameengine/GameLogic/SCA_PropertyActuator.cpp
index 31f988fe4b9..0eab6187d07 100644
--- a/source/gameengine/GameLogic/SCA_PropertyActuator.cpp
+++ b/source/gameengine/GameLogic/SCA_PropertyActuator.cpp
@@ -173,7 +173,7 @@ isValid(
SCA_PropertyActuator::KX_ACT_PROP_MODE mode
) {
- bool res = false;
+ bool res = false;
res = ((mode > KX_ACT_PROP_NODEF) && (mode < KX_ACT_PROP_MAX));
return res;
}
diff --git a/source/gameengine/GameLogic/SCA_PropertyActuator.h b/source/gameengine/GameLogic/SCA_PropertyActuator.h
index e465098131e..83a6d05df1b 100644
--- a/source/gameengine/GameLogic/SCA_PropertyActuator.h
+++ b/source/gameengine/GameLogic/SCA_PropertyActuator.h
@@ -86,5 +86,4 @@ public:
};
-#endif //__KX_PROPERTYACTUATOR_DOC
-
+#endif /* __KX_PROPERTYACTUATOR_DOC */
diff --git a/source/gameengine/GameLogic/SCA_PropertyEventManager.h b/source/gameengine/GameLogic/SCA_PropertyEventManager.h
index 7a4ec750484..554fe686df2 100644
--- a/source/gameengine/GameLogic/SCA_PropertyEventManager.h
+++ b/source/gameengine/GameLogic/SCA_PropertyEventManager.h
@@ -52,5 +52,4 @@ public:
#endif
};
-#endif //__SCA_PROPERTYEVENTMANAGER_H__
-
+#endif /* __SCA_PROPERTYEVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_PythonController.cpp b/source/gameengine/GameLogic/SCA_PythonController.cpp
index ab7f57a5454..ece9d7b6c8f 100644
--- a/source/gameengine/GameLogic/SCA_PythonController.cpp
+++ b/source/gameengine/GameLogic/SCA_PythonController.cpp
@@ -179,7 +179,7 @@ int SCA_PythonController::IsTriggered(class SCA_ISensor* sensor)
#ifdef WITH_PYTHON
/* warning, self is not the SCA_PythonController, its a PyObjectPlus_Proxy */
-PyObject* SCA_PythonController::sPyGetCurrentController(PyObject *self)
+PyObject *SCA_PythonController::sPyGetCurrentController(PyObject *self)
{
if (m_sCurrentController==NULL)
{
@@ -271,7 +271,7 @@ void SCA_PythonController::ErrorPrint(const char *error_msg)
}
bool SCA_PythonController::Compile()
-{
+{
//printf("py script modified '%s'\n", m_scriptName.Ptr());
m_bModified= false;
@@ -374,66 +374,65 @@ void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
m_sCurrentLogicManager = logicmgr;
PyObject *excdict= NULL;
- PyObject* resultobj= NULL;
-
- switch(m_mode) {
- case SCA_PYEXEC_SCRIPT:
- {
- if (m_bModified)
- if (Compile()==false) // sets m_bModified to false
+ PyObject *resultobj= NULL;
+
+ switch (m_mode) {
+ case SCA_PYEXEC_SCRIPT:
+ {
+ if (m_bModified)
+ if (Compile()==false) // sets m_bModified to false
+ return;
+ if (!m_bytecode)
return;
- if (!m_bytecode)
- return;
-
- /*
- * This part here with excdict is a temporary patch
- * to avoid python/gameengine crashes when python
- * inadvertently holds references to game objects
- * in global variables.
- *
- * The idea is always make a fresh dictionary, and
- * destroy it right after it is used to make sure
- * python won't hold any gameobject references.
- *
- * Note that the PyDict_Clear _is_ necessary before
- * the Py_DECREF() because it is possible for the
- * variables inside the dictionary to hold references
- * to the dictionary (ie. generate a cycle), so we
- * break it by hand, then DECREF (which in this case
- * should always ensure excdict is cleared).
- */
-
- excdict= PyDict_Copy(m_pythondictionary);
-
- resultobj = PyEval_EvalCode((PyObject *)m_bytecode, excdict, excdict);
-
- /* PyRun_SimpleString(m_scriptText.Ptr()); */
- break;
- }
- case SCA_PYEXEC_MODULE:
- {
- if (m_bModified || m_debug)
- if (Import()==false) // sets m_bModified to false
+
+ /*
+ * This part here with excdict is a temporary patch
+ * to avoid python/gameengine crashes when python
+ * inadvertently holds references to game objects
+ * in global variables.
+ *
+ * The idea is always make a fresh dictionary, and
+ * destroy it right after it is used to make sure
+ * python won't hold any gameobject references.
+ *
+ * Note that the PyDict_Clear _is_ necessary before
+ * the Py_DECREF() because it is possible for the
+ * variables inside the dictionary to hold references
+ * to the dictionary (ie. generate a cycle), so we
+ * break it by hand, then DECREF (which in this case
+ * should always ensure excdict is cleared).
+ */
+
+ excdict= PyDict_Copy(m_pythondictionary);
+
+ resultobj = PyEval_EvalCode((PyObject *)m_bytecode, excdict, excdict);
+
+ /* PyRun_SimpleString(m_scriptText.Ptr()); */
+ break;
+ }
+ case SCA_PYEXEC_MODULE:
+ {
+ if (m_bModified || m_debug)
+ if (Import()==false) // sets m_bModified to false
+ return;
+ if (!m_function)
return;
- if (!m_function)
- return;
-
- PyObject *args= NULL;
-
- if (m_function_argc==1) {
- args = PyTuple_New(1);
- PyTuple_SET_ITEM(args, 0, GetProxy());
+
+ PyObject *args= NULL;
+
+ if (m_function_argc==1) {
+ args = PyTuple_New(1);
+ PyTuple_SET_ITEM(args, 0, GetProxy());
+ }
+
+ resultobj = PyObject_CallObject(m_function, args);
+ Py_XDECREF(args);
+ break;
}
-
- resultobj = PyObject_CallObject(m_function, args);
- Py_XDECREF(args);
- break;
- }
-
+
} /* end switch */
-
-
-
+
+
/* Free the return value and print the error */
if (resultobj)
Py_DECREF(resultobj);
@@ -447,13 +446,13 @@ void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
// This doesn't appear to be needed anymore
//PyDict_Clear(excdict);
Py_DECREF(excdict);
- }
+ }
m_triggeredSensors.clear();
m_sCurrentController = NULL;
}
-PyObject* SCA_PythonController::PyActivate(PyObject *value)
+PyObject *SCA_PythonController::PyActivate(PyObject *value)
{
if (m_sCurrentController != this) {
PyErr_SetString(PyExc_SystemError, "Cannot add an actuator from a non-active controller");
@@ -468,7 +467,7 @@ PyObject* SCA_PythonController::PyActivate(PyObject *value)
Py_RETURN_NONE;
}
-PyObject* SCA_PythonController::PyDeActivate(PyObject *value)
+PyObject *SCA_PythonController::PyDeActivate(PyObject *value)
{
if (m_sCurrentController != this) {
PyErr_SetString(PyExc_SystemError, "Cannot add an actuator from a non-active controller");
@@ -483,12 +482,12 @@ PyObject* SCA_PythonController::PyDeActivate(PyObject *value)
Py_RETURN_NONE;
}
-PyObject* SCA_PythonController::pyattr_get_script(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_PythonController::pyattr_get_script(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- //SCA_PythonController* self= static_cast<SCA_PythonController*>(static_cast<SCA_IController*>(static_cast<SCA_ILogicBrick*>(static_cast<CValue*>(static_cast<PyObjectPlus*>(self_v)))));
+ //SCA_PythonController* self = static_cast<SCA_PythonController*>(static_cast<SCA_IController*>(static_cast<SCA_ILogicBrick*>(static_cast<CValue*>(static_cast<PyObjectPlus*>(self_v)))));
// static_cast<void *>(dynamic_cast<Derived *>(obj)) - static_cast<void *>(obj)
- SCA_PythonController* self= static_cast<SCA_PythonController*>(self_v);
+ SCA_PythonController* self = static_cast<SCA_PythonController*>(self_v);
return PyUnicode_From_STR_String(self->m_scriptText);
}
@@ -496,7 +495,7 @@ PyObject* SCA_PythonController::pyattr_get_script(void *self_v, const KX_PYATTRI
int SCA_PythonController::pyattr_set_script(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- SCA_PythonController* self= static_cast<SCA_PythonController*>(self_v);
+ SCA_PythonController* self = static_cast<SCA_PythonController*>(self_v);
const char *scriptArg = _PyUnicode_AsString(value);
diff --git a/source/gameengine/GameLogic/SCA_PythonController.h b/source/gameengine/GameLogic/SCA_PythonController.h
index ccdb82aa722..f1f10d22711 100644
--- a/source/gameengine/GameLogic/SCA_PythonController.h
+++ b/source/gameengine/GameLogic/SCA_PythonController.h
@@ -74,7 +74,7 @@ class SCA_PythonController : public SCA_IController
//for debugging
//virtual CValue* AddRef();
- //virtual int Release(); // Release a reference to this value (when reference count reaches 0, the value is removed from the heap)
+ //virtual int Release(); // Release a reference to this value (when reference count reaches 0, the value is removed from the heap)
SCA_PythonController(SCA_IObject* gameobj, int mode);
virtual ~SCA_PythonController();
@@ -96,11 +96,11 @@ class SCA_PythonController : public SCA_IController
void ErrorPrint(const char *error_msg);
#ifdef WITH_PYTHON
- static const char* sPyGetCurrentController__doc__;
- static PyObject* sPyGetCurrentController(PyObject* self);
- static const char* sPyAddActiveActuator__doc__;
- static PyObject* sPyAddActiveActuator(PyObject* self,
- PyObject* args);
+ static const char *sPyGetCurrentController__doc__;
+ static PyObject *sPyGetCurrentController(PyObject *self);
+ static const char *sPyAddActiveActuator__doc__;
+ static PyObject *sPyAddActiveActuator(PyObject *self,
+ PyObject *args);
static SCA_IActuator* LinkedActuatorFromPy(PyObject *value);
@@ -115,5 +115,4 @@ class SCA_PythonController : public SCA_IController
#endif
};
-#endif //__SCA_PYTHONCONTROLLER_H__
-
+#endif /* __SCA_PYTHONCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_PythonKeyboard.cpp b/source/gameengine/GameLogic/SCA_PythonKeyboard.cpp
index f83b23f510c..42cda9433b8 100644
--- a/source/gameengine/GameLogic/SCA_PythonKeyboard.cpp
+++ b/source/gameengine/GameLogic/SCA_PythonKeyboard.cpp
@@ -58,13 +58,13 @@ SCA_PythonKeyboard::~SCA_PythonKeyboard()
/* ------------------------------------------------------------------------- */
/* clipboard */
-static PyObject* gPyGetClipboard(PyObject* args, PyObject* kwds)
+static PyObject *gPyGetClipboard(PyObject *args, PyObject *kwds)
{
char *buf = (char *)GHOST_getClipboard(0);
return PyUnicode_FromString(buf?buf:"");
}
-static PyObject* gPySetClipboard(PyObject* args, PyObject* value)
+static PyObject *gPySetClipboard(PyObject *args, PyObject *value)
{
char* buf;
if (!PyArg_ParseTuple(value,"s:setClipboard",&buf))
@@ -109,7 +109,7 @@ PyAttributeDef SCA_PythonKeyboard::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* SCA_PythonKeyboard::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_PythonKeyboard::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
SCA_PythonKeyboard* self = static_cast<SCA_PythonKeyboard*>(self_v);
@@ -123,7 +123,7 @@ PyObject* SCA_PythonKeyboard::pyattr_get_events(void *self_v, const KX_PYATTRIBU
return self->m_event_dict;
}
-PyObject* SCA_PythonKeyboard::pyattr_get_active_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_PythonKeyboard::pyattr_get_active_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
SCA_PythonKeyboard* self = static_cast<SCA_PythonKeyboard*>(self_v);
diff --git a/source/gameengine/GameLogic/SCA_PythonKeyboard.h b/source/gameengine/GameLogic/SCA_PythonKeyboard.h
index df5e46f8c28..53068f38e6a 100644
--- a/source/gameengine/GameLogic/SCA_PythonKeyboard.h
+++ b/source/gameengine/GameLogic/SCA_PythonKeyboard.h
@@ -35,7 +35,7 @@ class SCA_PythonKeyboard : public PyObjectPlus
private:
class SCA_IInputDevice *m_keyboard;
#ifdef WITH_PYTHON
- PyObject* m_event_dict;
+ PyObject *m_event_dict;
#endif
public:
SCA_PythonKeyboard(class SCA_IInputDevice* keyboard);
@@ -47,5 +47,4 @@ public:
#endif
};
-#endif //__SCA_PYTHONKEYBOARD_H__
-
+#endif /* __SCA_PYTHONKEYBOARD_H__ */
diff --git a/source/gameengine/GameLogic/SCA_PythonMouse.cpp b/source/gameengine/GameLogic/SCA_PythonMouse.cpp
index cdbeaba2235..0806bda072b 100644
--- a/source/gameengine/GameLogic/SCA_PythonMouse.cpp
+++ b/source/gameengine/GameLogic/SCA_PythonMouse.cpp
@@ -90,9 +90,9 @@ PyAttributeDef SCA_PythonMouse::Attributes[] = {
KX_PYATTRIBUTE_RW_FUNCTION("position", SCA_PythonMouse, pyattr_get_position, pyattr_set_position),
KX_PYATTRIBUTE_RW_FUNCTION("visible", SCA_PythonMouse, pyattr_get_visible, pyattr_set_visible),
{ NULL } //Sentinel
-};
+};
-PyObject* SCA_PythonMouse::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_PythonMouse::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
SCA_PythonMouse* self = static_cast<SCA_PythonMouse*>(self_v);
@@ -106,7 +106,7 @@ PyObject* SCA_PythonMouse::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_
return self->m_event_dict;
}
-PyObject* SCA_PythonMouse::pyattr_get_active_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_PythonMouse::pyattr_get_active_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
SCA_PythonMouse* self = static_cast<SCA_PythonMouse*>(self_v);
@@ -123,7 +123,7 @@ PyObject* SCA_PythonMouse::pyattr_get_active_events(void *self_v, const KX_PYATT
return self->m_event_dict;
}
-PyObject* SCA_PythonMouse::pyattr_get_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_PythonMouse::pyattr_get_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
SCA_PythonMouse* self = static_cast<SCA_PythonMouse*>(self_v);
const SCA_InputEvent & xevent = self->m_mouse->GetEventValue(SCA_IInputDevice::KX_MOUSEX);
@@ -134,7 +134,7 @@ PyObject* SCA_PythonMouse::pyattr_get_position(void *self_v, const KX_PYATTRIBUT
x_coord = self->m_canvas->GetMouseNormalizedX(xevent.m_eventval);
y_coord = self->m_canvas->GetMouseNormalizedY(yevent.m_eventval);
- PyObject* ret = PyTuple_New(2);
+ PyObject *ret = PyTuple_New(2);
PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(x_coord));
PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(y_coord));
@@ -158,7 +158,7 @@ int SCA_PythonMouse::pyattr_set_position(void *self_v, const KX_PYATTRIBUTE_DEF
return PY_SET_ATTR_SUCCESS;
}
-PyObject* SCA_PythonMouse::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_PythonMouse::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
SCA_PythonMouse* self = static_cast<SCA_PythonMouse*>(self_v);
diff --git a/source/gameengine/GameLogic/SCA_PythonMouse.h b/source/gameengine/GameLogic/SCA_PythonMouse.h
index 1313d55005f..bc6e65f07a8 100644
--- a/source/gameengine/GameLogic/SCA_PythonMouse.h
+++ b/source/gameengine/GameLogic/SCA_PythonMouse.h
@@ -36,7 +36,7 @@ private:
class SCA_IInputDevice *m_mouse;
class RAS_ICanvas *m_canvas;
#ifdef WITH_PYTHON
- PyObject* m_event_dict;
+ PyObject *m_event_dict;
#endif
public:
SCA_PythonMouse(class SCA_IInputDevice* mouse, class RAS_ICanvas* canvas);
@@ -47,14 +47,13 @@ public:
#ifdef WITH_PYTHON
KX_PYMETHOD_DOC(SCA_PythonMouse, show);
- static PyObject* pyattr_get_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_active_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_position(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_position(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject* value);
- static PyObject* pyattr_get_visible(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_visible(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject* value);
+ static PyObject *pyattr_get_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_active_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_position(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static int pyattr_set_position(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
+ static PyObject *pyattr_get_visible(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static int pyattr_set_visible(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
#endif
};
-#endif //__SCA_PYTHONMOUSE_H__
-
+#endif /* __SCA_PYTHONMOUSE_H__ */
diff --git a/source/gameengine/GameLogic/SCA_RandomActuator.cpp b/source/gameengine/GameLogic/SCA_RandomActuator.cpp
index c727eebd015..2d51a45fe55 100644
--- a/source/gameengine/GameLogic/SCA_RandomActuator.cpp
+++ b/source/gameengine/GameLogic/SCA_RandomActuator.cpp
@@ -48,13 +48,13 @@
/* ------------------------------------------------------------------------- */
SCA_RandomActuator::SCA_RandomActuator(SCA_IObject *gameobj,
- long seed,
- SCA_RandomActuator::KX_RANDOMACT_MODE mode,
- float para1,
- float para2,
- const STR_String &propName)
- : SCA_IActuator(gameobj, KX_ACT_RANDOM),
- m_propname(propName),
+ long seed,
+ SCA_RandomActuator::KX_RANDOMACT_MODE mode,
+ float para1,
+ float para2,
+ const STR_String &propName)
+ : SCA_IActuator(gameobj, KX_ACT_RANDOM),
+ m_propname(propName),
m_parameter1(para1),
m_parameter2(para2),
m_distribution(mode)
@@ -161,7 +161,7 @@ bool SCA_RandomActuator::Update()
while (b >= a) {
b = b * m_base->DrawFloat();
res++;
- };
+ };
tmpval = new CIntValue(res);
}
break;
@@ -196,33 +196,30 @@ bool SCA_RandomActuator::Update()
*/
tmpval = new CFloatValue(m_parameter1);
- } else {
- /*
-
- 070301 - nzc
- Now, with seed != 0, we will most assuredly get some
- sensible values. The termination condition states two
- things:
- 1. s >= 0 is not allowed: to prevent the distro from
- getting a bias towards high values. This is a small
- correction, really, and might also be left out.
- 2. s == 0 is not allowed: to prevent a division by zero
- when renormalising the drawn value to the desired
- distribution shape. As a side effect, the distro will
- never yield the exact mean.
- I am not sure whether this is consistent, since the error
- cause by #2 is of the same magnitude as the one
- prevented by #1. The error introduced into the SD will be
- improved, though. By how much? Hard to say... If you like
- the maths, feel free to analyse. Be aware that this is
- one of the really old standard algorithms. I think the
- original came in Fortran, was translated to Pascal, and
- then someone came up with the C code. My guess it that
- this will be quite sufficient here.
-
+ }
+ else {
+ /* 070301 - nzc
+ * Now, with seed != 0, we will most assuredly get some
+ * sensible values. The termination condition states two
+ * things:
+ * 1. s >= 0 is not allowed: to prevent the distro from
+ * getting a bias towards high values. This is a small
+ * correction, really, and might also be left out.
+ * 2. s == 0 is not allowed: to prevent a division by zero
+ * when renormalising the drawn value to the desired
+ * distribution shape. As a side effect, the distro will
+ * never yield the exact mean.
+ * I am not sure whether this is consistent, since the error
+ * cause by #2 is of the same magnitude as the one
+ * prevented by #1. The error introduced into the SD will be
+ * improved, though. By how much? Hard to say... If you like
+ * the maths, feel free to analyse. Be aware that this is
+ * one of the really old standard algorithms. I think the
+ * original came in Fortran, was translated to Pascal, and
+ * then someone came up with the C code. My guess it that
+ * this will be quite sufficient here.
*/
- do
- {
+ do {
x = 2.0 * m_base->DrawFloat() - 1.0;
y = 2.0 * m_base->DrawFloat() - 1.0;
s = x*x + y*y;
@@ -361,9 +358,9 @@ PyAttributeDef SCA_RandomActuator::Attributes[] = {
KX_PYATTRIBUTE_STRING_RW_CHECK("propName",0,MAX_PROP_NAME,false,SCA_RandomActuator,m_propname,CheckProperty),
KX_PYATTRIBUTE_RW_FUNCTION("seed",SCA_RandomActuator,pyattr_get_seed,pyattr_set_seed),
{ NULL } //Sentinel
-};
+};
-PyObject* SCA_RandomActuator::pyattr_get_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_RandomActuator::pyattr_get_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
SCA_RandomActuator* act = static_cast<SCA_RandomActuator*>(self);
return PyLong_FromSsize_t(act->m_base->GetSeed());
@@ -420,7 +417,7 @@ KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setBoolBernouilli,
}
m_distribution = KX_RANDOMACT_BOOL_BERNOUILLI;
- m_parameter1 = paraArg;
+ m_parameter1 = paraArg;
enforceConstraints();
Py_RETURN_NONE;
}
@@ -473,7 +470,7 @@ KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setIntPoisson,
}
m_distribution = KX_RANDOMACT_INT_POISSON;
- m_parameter1 = paraArg;
+ m_parameter1 = paraArg;
enforceConstraints();
Py_RETURN_NONE;
}
@@ -489,7 +486,7 @@ KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setFloatConst,
}
m_distribution = KX_RANDOMACT_FLOAT_CONST;
- m_parameter1 = paraArg;
+ m_parameter1 = paraArg;
enforceConstraints();
Py_RETURN_NONE;
}
@@ -544,7 +541,7 @@ KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setFloatNegativeExponential,
}
m_distribution = KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL;
- m_parameter1 = paraArg;
+ m_parameter1 = paraArg;
enforceConstraints();
Py_RETURN_NONE;
}
diff --git a/source/gameengine/GameLogic/SCA_RandomActuator.h b/source/gameengine/GameLogic/SCA_RandomActuator.h
index 522663651e0..32b29fc4f43 100644
--- a/source/gameengine/GameLogic/SCA_RandomActuator.h
+++ b/source/gameengine/GameLogic/SCA_RandomActuator.h
@@ -67,10 +67,10 @@ class SCA_RandomActuator : public SCA_IActuator
KX_RANDOMACT_NODEF,
KX_RANDOMACT_BOOL_CONST,
KX_RANDOMACT_BOOL_UNIFORM,
- KX_RANDOMACT_BOOL_BERNOUILLI,
+ KX_RANDOMACT_BOOL_BERNOUILLI,
KX_RANDOMACT_INT_CONST,
KX_RANDOMACT_INT_UNIFORM,
- KX_RANDOMACT_INT_POISSON,
+ KX_RANDOMACT_INT_POISSON,
KX_RANDOMACT_FLOAT_CONST,
KX_RANDOMACT_FLOAT_UNIFORM,
KX_RANDOMACT_FLOAT_NORMAL,
@@ -98,7 +98,7 @@ class SCA_RandomActuator : public SCA_IActuator
/* Python interface ---------------------------------------------------- */
/* --------------------------------------------------------------------- */
- static PyObject* pyattr_get_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setBoolConst);
@@ -112,7 +112,7 @@ class SCA_RandomActuator : public SCA_IActuator
KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setFloatNormal);
KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setFloatNegativeExponential);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
}; /* end of class KX_EditObjectActuator : public SCA_PropertyActuator */
diff --git a/source/gameengine/GameLogic/SCA_RandomEventManager.h b/source/gameengine/GameLogic/SCA_RandomEventManager.h
index b46899b1355..2d83c5fcdca 100644
--- a/source/gameengine/GameLogic/SCA_RandomEventManager.h
+++ b/source/gameengine/GameLogic/SCA_RandomEventManager.h
@@ -51,5 +51,4 @@ public:
#endif
};
-#endif //__SCA_RANDOMEVENTMANAGER_H__
-
+#endif /* __SCA_RANDOMEVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_RandomSensor.cpp b/source/gameengine/GameLogic/SCA_RandomSensor.cpp
index 3b37507dcf3..7199ee6cf22 100644
--- a/source/gameengine/GameLogic/SCA_RandomSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_RandomSensor.cpp
@@ -165,15 +165,15 @@ PyAttributeDef SCA_RandomSensor::Attributes[] = {
{NULL} //Sentinel
};
-PyObject* SCA_RandomSensor::pyattr_get_seed(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *SCA_RandomSensor::pyattr_get_seed(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- SCA_RandomSensor* self= static_cast<SCA_RandomSensor*>(self_v);
+ SCA_RandomSensor* self = static_cast<SCA_RandomSensor*>(self_v);
return PyLong_FromSsize_t(self->m_basegenerator->GetSeed());
}
int SCA_RandomSensor::pyattr_set_seed(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- SCA_RandomSensor* self= static_cast<SCA_RandomSensor*>(self_v);
+ SCA_RandomSensor* self = static_cast<SCA_RandomSensor*>(self_v);
if (!PyLong_Check(value)) {
PyErr_SetString(PyExc_TypeError, "sensor.seed = int: Random Sensor, expected an integer");
return PY_SET_ATTR_FAIL;
diff --git a/source/gameengine/GameLogic/SCA_RandomSensor.h b/source/gameengine/GameLogic/SCA_RandomSensor.h
index 008445ef878..628562b77e6 100644
--- a/source/gameengine/GameLogic/SCA_RandomSensor.h
+++ b/source/gameengine/GameLogic/SCA_RandomSensor.h
@@ -68,5 +68,4 @@ public:
#endif
};
-#endif //__SCA_RANDOMSENSOR_H__
-
+#endif /* __SCA_RANDOMSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_TimeEventManager.cpp b/source/gameengine/GameLogic/SCA_TimeEventManager.cpp
index e28f00abba2..5aa6fdc8625 100644
--- a/source/gameengine/GameLogic/SCA_TimeEventManager.cpp
+++ b/source/gameengine/GameLogic/SCA_TimeEventManager.cpp
@@ -29,11 +29,10 @@
* \ingroup gamelogic
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// This warning tells us about truncation of __long__ stl-generated names.
-// It can occasionally cause DevStudio to have internal compiler warnings.
-#pragma warning( disable : 4786 )
+#ifdef _MSC_VER
+ /* This warning tells us about truncation of __long__ stl-generated names.
+ * It can occasionally cause DevStudio to have internal compiler warnings. */
+# pragma warning(disable:4786)
#endif
#include "SCA_TimeEventManager.h"
@@ -54,7 +53,7 @@ SCA_TimeEventManager::~SCA_TimeEventManager()
!(it == m_timevalues.end()); ++it)
{
(*it)->Release();
- }
+ }
}
diff --git a/source/gameengine/GameLogic/SCA_TimeEventManager.h b/source/gameengine/GameLogic/SCA_TimeEventManager.h
index 092cf016370..4c929dca23c 100644
--- a/source/gameengine/GameLogic/SCA_TimeEventManager.h
+++ b/source/gameengine/GameLogic/SCA_TimeEventManager.h
@@ -59,5 +59,4 @@ public:
#endif
};
-#endif //__SCA_TIMEEVENTMANAGER_H__
-
+#endif /* __SCA_TIMEEVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_XNORController.h b/source/gameengine/GameLogic/SCA_XNORController.h
index 5ef4dc67cf2..c257b71273e 100644
--- a/source/gameengine/GameLogic/SCA_XNORController.h
+++ b/source/gameengine/GameLogic/SCA_XNORController.h
@@ -50,5 +50,4 @@ public:
};
-#endif //__SCA_XNORCONTROLLER_H__
-
+#endif /* __SCA_XNORCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_XORController.h b/source/gameengine/GameLogic/SCA_XORController.h
index 56cd2440863..c64a3380ede 100644
--- a/source/gameengine/GameLogic/SCA_XORController.h
+++ b/source/gameengine/GameLogic/SCA_XORController.h
@@ -45,5 +45,4 @@ public:
virtual void Trigger(SCA_LogicManager* logicmgr);
};
-#endif //__SCA_XORCONTROLLER_H__
-
+#endif /* __SCA_XORCONTROLLER_H__ */
diff --git a/source/gameengine/GamePlayer/CMakeLists.txt b/source/gameengine/GamePlayer/CMakeLists.txt
index cdf3f826ea9..e1a26668d11 100644
--- a/source/gameengine/GamePlayer/CMakeLists.txt
+++ b/source/gameengine/GamePlayer/CMakeLists.txt
@@ -26,6 +26,6 @@
add_subdirectory(common)
add_subdirectory(ghost)
-if(WITH_WEBPLUGIN)
+if(WITH_WEBPLUGIN)
add_subdirectory(xembed)
endif()
diff --git a/source/gameengine/GamePlayer/common/GPC_Canvas.cpp b/source/gameengine/GamePlayer/common/GPC_Canvas.cpp
index f4224b9e255..b5c1c29238a 100644
--- a/source/gameengine/GamePlayer/common/GPC_Canvas.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_Canvas.cpp
@@ -57,6 +57,8 @@ GPC_Canvas::GPC_Canvas(
m_displayarea.m_y1 = 0;
m_displayarea.m_x2 = width;
m_displayarea.m_y2 = height;
+
+ glGetIntegerv(GL_VIEWPORT, (GLint*)m_viewport);
}
@@ -99,7 +101,7 @@ void GPC_Canvas::Resize(int width, int height)
void GPC_Canvas::EndFrame()
{
if (m_bannersEnabled)
- DrawAllBanners();
+ DrawAllBanners();
}
@@ -121,11 +123,31 @@ void GPC_Canvas::SetViewPort(int x1, int y1, int x2, int y2)
* whole canvas/rendertools mess.
*/
glEnable(GL_SCISSOR_TEST);
+
+ m_viewport[0] = x1;
+ m_viewport[1] = y1;
+ m_viewport[2] = x2-x1 + 1;
+ m_viewport[3] = y2-y1 + 1;
glViewport(x1,y1,x2-x1 + 1,y2-y1 + 1);
glScissor(x1,y1,x2-x1 + 1,y2-y1 + 1);
};
+const int *GPC_Canvas::GetViewPort()
+{
+#ifdef DEBUG
+ // If we're in a debug build, we might as well make sure our values don't differ
+ // from what the gpu thinks we have. This could lead to nasty, hard to find bugs.
+ int viewport[4];
+ glGetIntegerv(GL_VIEWPORT, viewport);
+ assert(viewport[0] == m_viewport[0]);
+ assert(viewport[1] == m_viewport[1]);
+ assert(viewport[2] == m_viewport[2]);
+ assert(viewport[3] == m_viewport[3]);
+#endif
+
+ return m_viewport;
+}
void GPC_Canvas::ClearBuffer(
int type
diff --git a/source/gameengine/GamePlayer/common/GPC_Canvas.h b/source/gameengine/GamePlayer/common/GPC_Canvas.h
index 25a50fbcac3..ec5375c0e13 100644
--- a/source/gameengine/GamePlayer/common/GPC_Canvas.h
+++ b/source/gameengine/GamePlayer/common/GPC_Canvas.h
@@ -38,7 +38,7 @@
#ifdef WIN32
#pragma warning (disable:4786) // suppress stl-MSVC debug info warning
#include <windows.h>
-#endif // WIN32
+#endif /* WIN32 */
#include "GL/glew.h"
@@ -90,6 +90,8 @@ protected:
* relative to the context */
RAS_Rect m_displayarea;
+ int m_viewport[4];
+
/** Storage for the banners to display. */
TBannerMap m_banners;
/** State of banner display. */
@@ -153,6 +155,7 @@ public:
);
void SetViewPort(int x1, int y1, int x2, int y2);
+ const int *GetViewPort();
void ClearColor(float r, float g, float b, float a);
@@ -163,7 +166,7 @@ public:
void SetMouseState(RAS_MouseState mousestate)
{
- // not yet
+ // not yet
}
void SetMousePosition(int x, int y)
@@ -250,7 +253,7 @@ protected:
int oldWriteMask;
};
- void
+ void
PushRenderState(
CanvasRenderState & render_state
);
@@ -270,5 +273,4 @@ protected:
static TBannerId s_bannerId;
};
-#endif // __GPC_CANVAS_H__
-
+#endif /* __GPC_CANVAS_H__ */
diff --git a/source/gameengine/GamePlayer/common/GPC_Engine.h b/source/gameengine/GamePlayer/common/GPC_Engine.h
index 60f0d2af199..6247bd630bb 100644
--- a/source/gameengine/GamePlayer/common/GPC_Engine.h
+++ b/source/gameengine/GamePlayer/common/GPC_Engine.h
@@ -121,5 +121,4 @@ private:
};
-#endif // __GPC_ENGINE_H__
-
+#endif /* __GPC_ENGINE_H__ */
diff --git a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h b/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h
index 63e051dd1d4..c082bc1b82f 100644
--- a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h
+++ b/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h
@@ -33,8 +33,8 @@
#define __GPC_KEYBOARDDEVICE_H__
#ifdef WIN32
-#pragma warning (disable : 4786)
-#endif // WIN32
+#pragma warning (disable:4786)
+#endif /* WIN32 */
#include "SCA_IInputDevice.h"
@@ -87,5 +87,4 @@ public:
virtual void HookEscape();
};
-#endif // _GPC_KEYBOARDDEVICE_H
-
+#endif /* __GPC_KEYBOARDDEVICE_H__ */
diff --git a/source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp b/source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp
index a38bba7788b..e38a9e3d6cb 100644
--- a/source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp
@@ -67,7 +67,8 @@ void GPC_MouseDevice::NextFrame()
for (int mouseevent= KX_BEGINMOUSE; mouseevent< KX_ENDMOUSEBUTTONS; mouseevent++) {
SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][mouseevent];
if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- oldevent.m_status == SCA_InputEvent::KX_ACTIVE) {
+ oldevent.m_status == SCA_InputEvent::KX_ACTIVE)
+ {
m_eventStatusTables[m_currentTable][mouseevent] = oldevent;
m_eventStatusTables[m_currentTable][mouseevent].m_status = SCA_InputEvent::KX_ACTIVE;
}
@@ -76,7 +77,8 @@ void GPC_MouseDevice::NextFrame()
SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][mousemove];
m_eventStatusTables[m_currentTable][mousemove] = oldevent;
if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- oldevent.m_status == SCA_InputEvent::KX_ACTIVE) {
+ oldevent.m_status == SCA_InputEvent::KX_ACTIVE)
+ {
m_eventStatusTables[m_currentTable][mousemove].m_status = SCA_InputEvent::KX_JUSTRELEASED;
}
else {
diff --git a/source/gameengine/GamePlayer/common/GPC_MouseDevice.h b/source/gameengine/GamePlayer/common/GPC_MouseDevice.h
index 2db1b1ec34c..b092fbd21dd 100644
--- a/source/gameengine/GamePlayer/common/GPC_MouseDevice.h
+++ b/source/gameengine/GamePlayer/common/GPC_MouseDevice.h
@@ -33,8 +33,8 @@
#define __GPC_MOUSEDEVICE_H__
#ifdef WIN32
-#pragma warning (disable : 4786)
-#endif // WIN32
+#pragma warning (disable:4786)
+#endif /* WIN32 */
#include "SCA_IInputDevice.h"
@@ -102,5 +102,4 @@ protected:
virtual bool ConvertEvent(KX_EnumInputs kxevent, int eventval);
};
-#endif // __GPC_MOUSEDEVICE_H__
-
+#endif /* __GPC_MOUSEDEVICE_H__ */
diff --git a/source/gameengine/GamePlayer/common/GPC_RawImage.cpp b/source/gameengine/GamePlayer/common/GPC_RawImage.cpp
index 9f129c1cdfb..c0d66541800 100644
--- a/source/gameengine/GamePlayer/common/GPC_RawImage.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_RawImage.cpp
@@ -89,7 +89,7 @@ bool GPC_RawImage::Load(
// Put original in upper left corner
// Add vertical offset
- dst += offsetY * dstBytesWidth;
+ dst += offsetY * dstBytesWidth;
// Add horizontal offset
dst += offsetX * 4;
for (int row = 0; row < numRows; row++)
diff --git a/source/gameengine/GamePlayer/common/GPC_RawImage.h b/source/gameengine/GamePlayer/common/GPC_RawImage.h
index 4d3f45597f8..afff59484b9 100644
--- a/source/gameengine/GamePlayer/common/GPC_RawImage.h
+++ b/source/gameengine/GamePlayer/common/GPC_RawImage.h
@@ -117,5 +117,4 @@ protected:
int m_height;
};
-#endif // __GPC_RAWIMAGE_H__
-
+#endif /* __GPC_RAWIMAGE_H__ */
diff --git a/source/gameengine/GamePlayer/common/GPC_RawLoadDotBlendArray.cpp b/source/gameengine/GamePlayer/common/GPC_RawLoadDotBlendArray.cpp
index adf0bcd8e57..c4022d69153 100644
--- a/source/gameengine/GamePlayer/common/GPC_RawLoadDotBlendArray.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_RawLoadDotBlendArray.cpp
@@ -38,7 +38,8 @@ void GetRawLoadingAnimation(unsigned char **data, int *dataSize)
{
// create an array that will automatically be deleted when)
// we're outta this scope
- static unsigned char load_blend[]= { 66, 76, 69, 78, 68, 70,
+ static unsigned char load_blend[] = {
+ 66, 76, 69, 78, 68, 70,
73, 10, 0, 2, 21, 0, 0, 2, 22, 0, 0, 0, 0, 0, 0,
2, 30, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
65, 25, 242, 2, 0, 2, 29, 253, 0, 0, 0, 4, 160, 249, 227,
diff --git a/source/gameengine/GamePlayer/common/GPC_RawLoadDotBlendArray.h b/source/gameengine/GamePlayer/common/GPC_RawLoadDotBlendArray.h
index 6f15276ab83..d5c1b210454 100644
--- a/source/gameengine/GamePlayer/common/GPC_RawLoadDotBlendArray.h
+++ b/source/gameengine/GamePlayer/common/GPC_RawLoadDotBlendArray.h
@@ -34,5 +34,4 @@
void GetRawLoadingAnimation(unsigned char **data, int *dataSize);
-#endif // __GPC_RAWLOADDOTBLENDARRAY_H__
-
+#endif /* __GPC_RAWLOADDOTBLENDARRAY_H__ */
diff --git a/source/gameengine/GamePlayer/common/GPC_RawLogoArrays.cpp b/source/gameengine/GamePlayer/common/GPC_RawLogoArrays.cpp
index 2471b528eac..2f58e9a692f 100644
--- a/source/gameengine/GamePlayer/common/GPC_RawLogoArrays.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_RawLogoArrays.cpp
@@ -38,7 +38,8 @@ void GetRawBlenderLogo(unsigned char **data, int *width, int *height)
{
// create an array that will automatically be deleted when)
// we're outta this scope
- static unsigned char logo_blender_raw[]= { 0, 0, 0, 0, 0,
+ static unsigned char logo_blender_raw[] = {
+ 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -1041,7 +1042,8 @@ void GetRawBlender3DLogo(unsigned char **data, int *width, int *height)
{
// create an array that will automatically be deleted when)
// we're outta this scope
- static unsigned char logo_blender3d_raw[]= {255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255,
+ static unsigned char logo_blender3d_raw[] = {
+ 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255,
255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255,
255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0,
255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255,
diff --git a/source/gameengine/GamePlayer/common/GPC_RawLogoArrays.h b/source/gameengine/GamePlayer/common/GPC_RawLogoArrays.h
index ade00020353..bb5c5e220a3 100644
--- a/source/gameengine/GamePlayer/common/GPC_RawLogoArrays.h
+++ b/source/gameengine/GamePlayer/common/GPC_RawLogoArrays.h
@@ -38,5 +38,4 @@ void GetRawBlender3DLogo(unsigned char **data, int *width, int *height);
void GetRawNaNLogo(unsigned char **data, int *width, int *height);
#endif
-#endif // __GPC_RAWLOGOARRAYS_H__
-
+#endif /* __GPC_RAWLOGOARRAYS_H__ */
diff --git a/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp b/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp
index 749e7748e19..dfc866526eb 100644
--- a/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp
@@ -173,11 +173,11 @@ bool GPC_RenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, vo
left = (dir.cross(resultnormal)).safe_normalized();
// for the up vector, we take the 'resultnormal' returned by the physics
- double maat[16]={
- left[0], left[1], left[2], 0,
- dir[0], dir[1], dir[2], 0,
- resultnormal[0],resultnormal[1],resultnormal[2], 0,
- 0, 0, 0, 1};
+ double maat[16] = {left[0], left[1], left[2], 0,
+ dir[0], dir[1], dir[2], 0,
+ resultnormal[0], resultnormal[1], resultnormal[2], 0,
+ 0, 0, 0, 1};
+
glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
//glMultMatrixd(oglmatrix);
glMultMatrixd(maat);
@@ -236,16 +236,16 @@ void GPC_RenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,in
left *= size[0];
dir *= size[1];
up *= size[2];
- double maat[16]={
- left[0], left[1],left[2], 0,
- dir[0], dir[1],dir[2],0,
- up[0],up[1],up[2],0,
- 0,0,0,1};
- glTranslated(objpos[0],objpos[1],objpos[2]);
- glMultMatrixd(maat);
-
- } else
- {
+
+ double maat[16] = {left[0], left[1], left[2], 0,
+ dir[0], dir[1], dir[2], 0,
+ up[0], up[1], up[2], 0,
+ 0, 0, 0, 1};
+
+ glTranslated(objpos[0],objpos[1],objpos[2]);
+ glMultMatrixd(maat);
+ }
+ else {
if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
{
// shadow must be cast to the ground, physics system needed here!
@@ -359,7 +359,8 @@ void GPC_RenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
glGetIntegerv(GL_LIGHTING, (GLint*)&light);
glDisable(GL_LIGHTING);
-
+ glDisable(GL_DEPTH_TEST);
+
// Set up viewing settings
glMatrixMode(GL_PROJECTION);
glPushMatrix();
@@ -442,7 +443,7 @@ void GPC_RenderTools::PopMatrix()
int GPC_RenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
{
- // taken from blender source, incompatibility between Blender Object / GameObject
+ // taken from blender source, incompatibility between Blender Object / GameObject
KX_Scene* kxscene = (KX_Scene*)m_auxilaryClientInfo;
float glviewmat[16];
unsigned int count;
diff --git a/source/gameengine/GamePlayer/common/GPC_RenderTools.h b/source/gameengine/GamePlayer/common/GPC_RenderTools.h
index 166a931beab..1030c09548a 100644
--- a/source/gameengine/GamePlayer/common/GPC_RenderTools.h
+++ b/source/gameengine/GamePlayer/common/GPC_RenderTools.h
@@ -36,7 +36,7 @@
// don't show stl-warnings
#pragma warning (disable:4786)
#include <windows.h>
-#endif // WIN32
+#endif /* WIN32 */
#include "RAS_IRenderTools.h"
@@ -106,7 +106,4 @@ public:
virtual void SetClientObject(RAS_IRasterizer *rasty, void* obj);
};
-#endif // __GPC_RENDERTOOLS_H__
-
-
-
+#endif /* __GPC_RENDERTOOLS_H__ */
diff --git a/source/gameengine/GamePlayer/common/GPC_System.h b/source/gameengine/GamePlayer/common/GPC_System.h
index 03bb7743637..4169064179e 100644
--- a/source/gameengine/GamePlayer/common/GPC_System.h
+++ b/source/gameengine/GamePlayer/common/GPC_System.h
@@ -59,5 +59,4 @@ public:
// NG_NetworkDeviceInterface* m_ndi;
};
-#endif // __GPC_SYSTEM_H__
-
+#endif /* __GPC_SYSTEM_H__ */
diff --git a/source/gameengine/GamePlayer/common/bmfont.cpp b/source/gameengine/GamePlayer/common/bmfont.cpp
index 4c1c6ae5604..fe6f2187138 100644
--- a/source/gameengine/GamePlayer/common/bmfont.cpp
+++ b/source/gameengine/GamePlayer/common/bmfont.cpp
@@ -104,13 +104,13 @@ void readBitmapFontVersion0(ImBuf * ibuf, unsigned char * rect, int step)
ysize = (bytes + (ibuf->x - 1)) / ibuf->x;
if (ysize < ibuf->y) {
- // we're first going to copy all data into a liniar buffer.
+ // we're first going to copy all data into a linear buffer.
// step can be 4 or 1 bytes, and the data is not sequential because
// the bitmap was flipped vertically.
buffer = (unsigned char*)MEM_mallocN(bytes, "readBitmapFontVersion0:buffer");
- index = 0;
+ index = 0;
for (i = 0; i < bytes; i++) {
buffer[i] = rect[index];
index += step;
diff --git a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp b/source/gameengine/GamePlayer/ghost/GPG_Application.cpp
index 21de7011eda..40b52c3212a 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp
+++ b/source/gameengine/GamePlayer/ghost/GPG_Application.cpp
@@ -479,7 +479,7 @@ bool GPG_Application::processEvent(GHOST_IEvent* event)
// // first check if we want to exit
// m_exitRequested = m_ketsjiengine->GetExitCode();
- //
+ //
// // kick the engine
// bool renderFrame = m_ketsjiengine->NextFrame();
// if (renderFrame)
@@ -546,7 +546,7 @@ bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode)
return false;
// SYS_WriteCommandLineInt(syshandle, "fixedtime", 0);
- // SYS_WriteCommandLineInt(syshandle, "vertexarrays",1);
+ // SYS_WriteCommandLineInt(syshandle, "vertexarrays",1);
GameData *gm= &m_startScene->gm;
bool properties = (SYS_GetCommandLineInt(syshandle, "show_properties", 0) != 0);
bool profile = (SYS_GetCommandLineInt(syshandle, "show_profile", 0) != 0);
@@ -576,7 +576,7 @@ bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode)
m_canvas->Init();
if (gm->flag & GAME_SHOW_MOUSE)
- m_canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
+ m_canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
m_rendertools = new GPC_RenderTools();
if (!m_rendertools)
@@ -681,7 +681,7 @@ bool GPG_Application::startEngine(void)
// Temporary hack to disable banner display for NaN approved content.
/*
- m_canvas->SetBannerDisplayEnabled(true);
+ m_canvas->SetBannerDisplayEnabled(true);
Camera* cam;
cam = (Camera*)scene->camera->data;
if (cam) {
@@ -730,7 +730,7 @@ bool GPG_Application::startEngine(void)
// Set the GameLogic.globalDict from marshal'd data, so we can
// load new blend files and keep data in GameLogic.globalDict
loadGamePythonConfig(m_pyGlobalDictString, m_pyGlobalDictString_Length);
-#endif
+#endif
m_sceneconverter->ConvertScene(
startscene,
m_rendertools,
diff --git a/source/gameengine/GamePlayer/ghost/GPG_Canvas.h b/source/gameengine/GamePlayer/ghost/GPG_Canvas.h
index d931f605a64..440fd2bba27 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_Canvas.h
+++ b/source/gameengine/GamePlayer/ghost/GPG_Canvas.h
@@ -33,8 +33,8 @@
#define __GPG_CANVAS_H__
#ifdef WIN32
-#pragma warning (disable : 4786)
-#endif // WIN32
+#pragma warning (disable:4786)
+#endif /* WIN32 */
#include "GPC_Canvas.h"
@@ -66,5 +66,4 @@ public:
void EndDraw() {};
};
-#endif // __GPG_CANVAS_H__
-
+#endif /* __GPG_CANVAS_H__ */
diff --git a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp b/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp
index b31803b761e..e8d3441e4ce 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp
+++ b/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp
@@ -72,7 +72,7 @@ GPG_KeyboardDevice::GPG_KeyboardDevice(void)
m_reverseKeyTranslateTable[GHOST_kKey7 ] = KX_SEVENKEY ;
m_reverseKeyTranslateTable[GHOST_kKey8 ] = KX_EIGHTKEY ;
m_reverseKeyTranslateTable[GHOST_kKey9 ] = KX_NINEKEY ;
-
+
// Middle keyboard area keys
m_reverseKeyTranslateTable[GHOST_kKeyPause ] = KX_PAUSEKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyInsert ] = KX_INSERTKEY ;
@@ -81,7 +81,7 @@ GPG_KeyboardDevice::GPG_KeyboardDevice(void)
m_reverseKeyTranslateTable[GHOST_kKeyEnd ] = KX_ENDKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyUpPage ] = KX_PAGEUPKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyDownPage ] = KX_PAGEDOWNKEY ;
-
+
// Arrow keys
m_reverseKeyTranslateTable[GHOST_kKeyUpArrow ] = KX_UPARROWKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyDownArrow ] = KX_DOWNARROWKEY ;
@@ -108,19 +108,19 @@ GPG_KeyboardDevice::GPG_KeyboardDevice(void)
m_reverseKeyTranslateTable[GHOST_kKeyF17 ] = KX_F17KEY ;
m_reverseKeyTranslateTable[GHOST_kKeyF18 ] = KX_F18KEY ;
m_reverseKeyTranslateTable[GHOST_kKeyF19 ] = KX_F19KEY ;
-
+
// Numpad keys
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad0 ] = KX_PAD0 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad1 ] = KX_PAD1 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad2 ] = KX_PAD2 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad3 ] = KX_PAD3 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad4 ] = KX_PAD4 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad5 ] = KX_PAD5 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad6 ] = KX_PAD6 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad7 ] = KX_PAD7 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad8 ] = KX_PAD8 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad9 ] = KX_PAD9 ;
+ m_reverseKeyTranslateTable[GHOST_kKeyNumpad0 ] = KX_PAD0 ;
+ m_reverseKeyTranslateTable[GHOST_kKeyNumpad1 ] = KX_PAD1 ;
+ m_reverseKeyTranslateTable[GHOST_kKeyNumpad2 ] = KX_PAD2 ;
+ m_reverseKeyTranslateTable[GHOST_kKeyNumpad3 ] = KX_PAD3 ;
+ m_reverseKeyTranslateTable[GHOST_kKeyNumpad4 ] = KX_PAD4 ;
+ m_reverseKeyTranslateTable[GHOST_kKeyNumpad5 ] = KX_PAD5 ;
+ m_reverseKeyTranslateTable[GHOST_kKeyNumpad6 ] = KX_PAD6 ;
+ m_reverseKeyTranslateTable[GHOST_kKeyNumpad7 ] = KX_PAD7 ;
+ m_reverseKeyTranslateTable[GHOST_kKeyNumpad8 ] = KX_PAD8 ;
+ m_reverseKeyTranslateTable[GHOST_kKeyNumpad9 ] = KX_PAD9 ;
m_reverseKeyTranslateTable[GHOST_kKeyNumpadAsterisk ] = KX_PADASTERKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyNumpadPlus ] = KX_PADPLUSKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyNumpadPeriod ] = KX_PADPERIOD ;
@@ -133,7 +133,7 @@ GPG_KeyboardDevice::GPG_KeyboardDevice(void)
m_reverseKeyTranslateTable[GHOST_kKeyEsc ] = KX_ESCKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyTab ] = KX_TABKEY ;
m_reverseKeyTranslateTable[GHOST_kKeySpace ] = KX_SPACEKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyEnter ] = KX_RETKEY ;
+ m_reverseKeyTranslateTable[GHOST_kKeyEnter ] = KX_RETKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyBackSpace ] = KX_BACKSPACEKEY ;
m_reverseKeyTranslateTable[GHOST_kKeySemicolon ] = KX_SEMICOLONKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyPeriod ] = KX_PERIODKEY ;
@@ -141,19 +141,19 @@ GPG_KeyboardDevice::GPG_KeyboardDevice(void)
m_reverseKeyTranslateTable[GHOST_kKeyQuote ] = KX_QUOTEKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyAccentGrave ] = KX_ACCENTGRAVEKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyMinus ] = KX_MINUSKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeySlash ] = KX_SLASHKEY ;
+ m_reverseKeyTranslateTable[GHOST_kKeySlash ] = KX_SLASHKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyBackslash ] = KX_BACKSLASHKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyEqual ] = KX_EQUALKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyLeftBracket ] = KX_LEFTBRACKETKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyRightBracket ] = KX_RIGHTBRACKETKEY ;
+ m_reverseKeyTranslateTable[GHOST_kKeyLeftBracket ] = KX_LEFTBRACKETKEY ;
+ m_reverseKeyTranslateTable[GHOST_kKeyRightBracket ] = KX_RIGHTBRACKETKEY ;
// Modifier keys.
- m_reverseKeyTranslateTable[GHOST_kKeyLeftControl ] = KX_LEFTCTRLKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyRightControl ] = KX_RIGHTCTRLKEY ;
+ m_reverseKeyTranslateTable[GHOST_kKeyLeftControl ] = KX_LEFTCTRLKEY ;
+ m_reverseKeyTranslateTable[GHOST_kKeyRightControl ] = KX_RIGHTCTRLKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyLeftAlt ] = KX_LEFTALTKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyRightAlt ] = KX_RIGHTALTKEY ;
m_reverseKeyTranslateTable[GHOST_kKeyLeftShift ] = KX_LEFTSHIFTKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyRightShift ] = KX_RIGHTSHIFTKEY ;
+ m_reverseKeyTranslateTable[GHOST_kKeyRightShift ] = KX_RIGHTSHIFTKEY ;
}
diff --git a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h b/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h
index 8d72a621b6a..ff8d56db40a 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h
+++ b/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h
@@ -34,8 +34,8 @@
#define __GPG_KEYBOARDDEVICE_H__
#ifdef WIN32
-#pragma warning (disable : 4786)
-#endif // WIN32
+#pragma warning (disable:4786)
+#endif /* WIN32 */
#include "GHOST_Types.h"
#include "GPC_KeyboardDevice.h"
@@ -53,5 +53,4 @@ public:
virtual ~GPG_KeyboardDevice(void);
};
-#endif //__GPG_KEYBOARDDEVICE_H__
-
+#endif /* __GPG_KEYBOARDDEVICE_H__ */
diff --git a/source/gameengine/GamePlayer/ghost/GPG_System.h b/source/gameengine/GamePlayer/ghost/GPG_System.h
index 796ad0c2b8c..d68fc812dd3 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_System.h
+++ b/source/gameengine/GamePlayer/ghost/GPG_System.h
@@ -35,7 +35,7 @@
#ifdef WIN32
#pragma warning (disable:4786) // suppress stl-MSVC debug info warning
-#endif // WIN32
+#endif /* WIN32 */
#include "GPC_System.h"
@@ -51,5 +51,4 @@ public:
virtual double GetTimeInSeconds();
};
-#endif // __GPG_SYSTEM_H__
-
+#endif /* __GPG_SYSTEM_H__ */
diff --git a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp b/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
index d8b07fd50d9..725c23c60e3 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
+++ b/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
@@ -57,10 +57,10 @@ extern "C"
{
#endif // __cplusplus
#include "MEM_guardedalloc.h"
-#include "BKE_blender.h"
-#include "BKE_global.h"
-#include "BKE_icons.h"
-#include "BKE_node.h"
+#include "BKE_blender.h"
+#include "BKE_global.h"
+#include "BKE_icons.h"
+#include "BKE_node.h"
#include "BKE_report.h"
#include "BKE_library.h"
#include "BLI_threads.h"
@@ -119,11 +119,11 @@ static void mem_error_cb(const char *errorStr)
#ifdef WIN32
typedef enum {
- SCREEN_SAVER_MODE_NONE = 0,
- SCREEN_SAVER_MODE_PREVIEW,
- SCREEN_SAVER_MODE_SAVER,
- SCREEN_SAVER_MODE_CONFIGURATION,
- SCREEN_SAVER_MODE_PASSWORD,
+ SCREEN_SAVER_MODE_NONE = 0,
+ SCREEN_SAVER_MODE_PREVIEW,
+ SCREEN_SAVER_MODE_SAVER,
+ SCREEN_SAVER_MODE_CONFIGURATION,
+ SCREEN_SAVER_MODE_PASSWORD,
} ScreenSaverMode;
static ScreenSaverMode scr_saver_mode = SCREEN_SAVER_MODE_NONE;
@@ -223,7 +223,7 @@ void usage(const char* program, bool isBlenderPlayer)
printf(" --Optional parameters--\n");
printf(" angle = field of view in degrees\n");
printf(" tilt = tilt angle in degrees\n");
- printf(" warpdata = a file to use for warping the image (absolute path)\n");
+ printf(" warpdata = a file to use for warping the image (absolute path)\n");
printf(" mode: fisheye (Fisheye)\n");
printf(" truncatedfront (Front-Truncated)\n");
printf(" truncatedrear (Rear-Truncated)\n");
@@ -1016,12 +1016,12 @@ int main(int argc, char** argv)
gpg_nextframestate.app = &app;
gpg_nextframestate.gs = &gs;
pynextframestate.state = &gpg_nextframestate;
- pynextframestate.func = &GPG_PyNextFrame;
+ pynextframestate.func = &GPG_PyNextFrame;
printf("Yielding control to Python script '%s'...\n", python_main);
PyRun_SimpleString(python_code);
printf("Exit Python script '%s'\n", python_main);
-#endif // WITH_PYTHON
+#endif // WITH_PYTHON
MEM_freeN(python_code);
}
else {
@@ -1064,6 +1064,7 @@ int main(int argc, char** argv)
#ifdef WITH_INTERNATIONAL
BLF_free_unifont();
+ BLF_lang_free();
#endif
IMB_exit();
diff --git a/source/gameengine/Ketsji/BL_Action.cpp b/source/gameengine/Ketsji/BL_Action.cpp
index a21c3965be9..5b7a2313f43 100644
--- a/source/gameengine/Ketsji/BL_Action.cpp
+++ b/source/gameengine/Ketsji/BL_Action.cpp
@@ -352,29 +352,27 @@ void BL_Action::Update(float curtime)
}
// Handle wrap around
- if (m_localtime < min(m_startframe, m_endframe) || m_localtime > max(m_startframe, m_endframe))
- {
- switch(m_playmode)
- {
- case ACT_MODE_PLAY:
- // Clamp
- m_localtime = m_endframe;
- m_done = true;
- break;
- case ACT_MODE_LOOP:
- // Put the time back to the beginning
- m_localtime = m_startframe;
- m_starttime = curtime;
- break;
- case ACT_MODE_PING_PONG:
- // Swap the start and end frames
- float temp = m_startframe;
- m_startframe = m_endframe;
- m_endframe = temp;
-
- m_starttime = curtime;
-
- break;
+ if (m_localtime < min(m_startframe, m_endframe) || m_localtime > max(m_startframe, m_endframe)) {
+ switch (m_playmode) {
+ case ACT_MODE_PLAY:
+ // Clamp
+ m_localtime = m_endframe;
+ m_done = true;
+ break;
+ case ACT_MODE_LOOP:
+ // Put the time back to the beginning
+ m_localtime = m_startframe;
+ m_starttime = curtime;
+ break;
+ case ACT_MODE_PING_PONG:
+ // Swap the start and end frames
+ float temp = m_startframe;
+ m_startframe = m_endframe;
+ m_endframe = temp;
+
+ m_starttime = curtime;
+
+ break;
}
}
diff --git a/source/gameengine/Ketsji/BL_Action.h b/source/gameengine/Ketsji/BL_Action.h
index ab2adf7fe34..370bbf51d72 100644
--- a/source/gameengine/Ketsji/BL_Action.h
+++ b/source/gameengine/Ketsji/BL_Action.h
@@ -136,5 +136,4 @@ public:
#endif
};
-#endif //BL_ACTION
-
+#endif /* BL_ACTION */
diff --git a/source/gameengine/Ketsji/BL_ActionManager.h b/source/gameengine/Ketsji/BL_ActionManager.h
index dbdaa6652ad..600e7b6621e 100644
--- a/source/gameengine/Ketsji/BL_ActionManager.h
+++ b/source/gameengine/Ketsji/BL_ActionManager.h
@@ -98,5 +98,4 @@ public:
#endif
};
-#endif //BL_ACTIONMANAGER
-
+#endif /* BL_ACTIONMANAGER */
diff --git a/source/gameengine/Ketsji/BL_BlenderShader.cpp b/source/gameengine/Ketsji/BL_BlenderShader.cpp
index 122d692b599..23bfd7a111b 100644
--- a/source/gameengine/Ketsji/BL_BlenderShader.cpp
+++ b/source/gameengine/Ketsji/BL_BlenderShader.cpp
@@ -6,6 +6,8 @@
#include "DNA_material_types.h"
#include "DNA_scene_types.h"
+#include "BLI_utildefines.h"
+
#include "BKE_global.h"
#include "BKE_main.h"
#include "BKE_DerivedMesh.h"
@@ -143,9 +145,9 @@ void BL_BlenderShader::Update(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty )
viewinv.getValue((float*)viewinvmat);
if (ms.m_bObjectColor)
- ms.m_RGBAcolor.getValue((float*)obcol);
+ ms.m_RGBAcolor.getValue((float *)obcol);
else
- obcol[0]= obcol[1]= obcol[2]= obcol[3]= 1.0f;
+ obcol[0] = obcol[1] = obcol[2] = obcol[3] = 1.0f;
float auto_bump_scale = ms.m_pDerivedMesh!=0 ? ms.m_pDerivedMesh->auto_bump_scale : 1.0f;
GPU_material_bind_uniforms(gpumat, obmat, viewmat, viewinvmat, obcol, auto_bump_scale);
diff --git a/source/gameengine/Ketsji/BL_BlenderShader.h b/source/gameengine/Ketsji/BL_BlenderShader.h
index f23dbfdf3a5..626c65baadd 100644
--- a/source/gameengine/Ketsji/BL_BlenderShader.h
+++ b/source/gameengine/Ketsji/BL_BlenderShader.h
@@ -101,4 +101,4 @@ public:
#endif
};
-#endif//__BL_BLENDERSHADER_H__
+#endif /* __BL_BLENDERSHADER_H__ */
diff --git a/source/gameengine/Ketsji/BL_Shader.cpp b/source/gameengine/Ketsji/BL_Shader.cpp
index c0fca88c426..fb8e7beb157 100644
--- a/source/gameengine/Ketsji/BL_Shader.cpp
+++ b/source/gameengine/Ketsji/BL_Shader.cpp
@@ -52,51 +52,70 @@ void BL_Uniform::Apply(class BL_Shader *shader)
#ifdef SORT_UNIFORMS
MT_assert(mType > UNI_NONE && mType < UNI_MAX && mData);
- if (!mDirty)
+ if (!mDirty)
return;
- switch(mType)
- {
- case UNI_FLOAT: {
+ switch (mType) {
+ case UNI_FLOAT:
+ {
float *f = (float*)mData;
glUniform1fARB(mLoc,(GLfloat)*f);
- }break;
- case UNI_INT: {
+ break;
+ }
+ case UNI_INT:
+ {
int *f = (int*)mData;
glUniform1iARB(mLoc, (GLint)*f);
- }break;
- case UNI_FLOAT2: {
+ break;
+ }
+ case UNI_FLOAT2:
+ {
float *f = (float*)mData;
glUniform2fvARB(mLoc,1, (GLfloat*)f);
- }break;
- case UNI_FLOAT3: {
+ break;
+ }
+ case UNI_FLOAT3:
+ {
float *f = (float*)mData;
glUniform3fvARB(mLoc,1,(GLfloat*)f);
- }break;
- case UNI_FLOAT4: {
+ break;
+ }
+ case UNI_FLOAT4:
+ {
float *f = (float*)mData;
glUniform4fvARB(mLoc,1,(GLfloat*)f);
- }break;
- case UNI_INT2: {
+ break;
+ }
+ case UNI_INT2:
+ {
int *f = (int*)mData;
glUniform2ivARB(mLoc,1,(GLint*)f);
- }break;
- case UNI_INT3: {
+ break;
+ }
+ case UNI_INT3:
+ {
int *f = (int*)mData;
glUniform3ivARB(mLoc,1,(GLint*)f);
- }break;
- case UNI_INT4: {
+ break;
+ }
+ case UNI_INT4:
+ {
int *f = (int*)mData;
glUniform4ivARB(mLoc,1,(GLint*)f);
- }break;
- case UNI_MAT4: {
+ break;
+ }
+ case UNI_MAT4:
+ {
float *f = (float*)mData;
glUniformMatrix4fvARB(mLoc, 1, mTranspose?GL_TRUE:GL_FALSE,(GLfloat*)f);
- }break;
- case UNI_MAT3: {
+ break;
+ }
+ case UNI_MAT3:
+ {
float *f = (float*)mData;
glUniformMatrix3fvARB(mLoc, 1, mTranspose?GL_TRUE:GL_FALSE,(GLfloat*)f);
- }break;
+ break;
+ }
}
mDirty = false;
#endif
@@ -157,7 +176,7 @@ BL_Shader::~BL_Shader()
void BL_Shader::ClearUniforms()
{
BL_UniformVec::iterator it = mUniforms.begin();
- while(it != mUniforms.end()) {
+ while (it != mUniforms.end()) {
delete (*it);
it++;
}
@@ -165,7 +184,7 @@ void BL_Shader::ClearUniforms()
BL_UniformVecDef::iterator itp = mPreDef.begin();
- while(itp != mPreDef.end()) {
+ while (itp != mPreDef.end()) {
delete (*itp);
itp++;
}
@@ -178,7 +197,7 @@ BL_Uniform *BL_Shader::FindUniform(const int location)
{
#ifdef SORT_UNIFORMS
BL_UniformVec::iterator it = mUniforms.begin();
- while(it != mUniforms.end()) {
+ while (it != mUniforms.end()) {
if ((*it)->GetLocation() == location)
return (*it);
it++;
@@ -431,7 +450,7 @@ void BL_Shader::SetProg(bool enable)
glUseProgramObjectARB(mShader);
}
else {
- glUseProgramObjectARB(0);
+ glUseProgramObjectARB(0);
}
}
}
@@ -613,7 +632,7 @@ void BL_Shader::SetUniform(int uniform, const MT_Tuple3& vec)
GLEW_ARB_vertex_shader &&
GLEW_ARB_shader_objects
)
- {
+ {
float value[3];
vec.getValue(value);
glUniform3fvARB(uniform, 1, value);
@@ -931,7 +950,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform1f, "setUniform1f(name, fx)" )
{
#ifdef SORT_UNIFORMS
SetUniformfv(loc, BL_Uniform::UNI_FLOAT, &value, sizeof(float));
-#else
+#else
SetUniform( loc, (float)value );
#endif
}
@@ -947,7 +966,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform2f, "setUniform2f(name, fx, fy)")
Py_RETURN_NONE;
}
const char *uniform="";
- float array[2]={ 0,0 };
+ float array[2] = {0, 0};
if (PyArg_ParseTuple(args, "sff:setUniform2f", &uniform, &array[0],&array[1] ))
{
int loc = GetUniformLocation(uniform);
@@ -971,7 +990,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform3f, "setUniform3f(name, fx,fy,fz) ")
Py_RETURN_NONE;
}
const char *uniform="";
- float array[3]={0,0,0};
+ float array[3] = {0, 0, 0};
if (PyArg_ParseTuple(args, "sfff:setUniform3f", &uniform, &array[0],&array[1],&array[2]))
{
int loc = GetUniformLocation(uniform);
@@ -996,7 +1015,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform4f, "setUniform4f(name, fx,fy,fz, fw) "
Py_RETURN_NONE;
}
const char *uniform="";
- float array[4]={0,0,0,0};
+ float array[4] = {0, 0, 0, 0};
if (PyArg_ParseTuple(args, "sffff:setUniform4f", &uniform, &array[0],&array[1],&array[2], &array[3]))
{
int loc = GetUniformLocation(uniform);
@@ -1044,7 +1063,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform2i, "setUniform2i(name, ix, iy)")
Py_RETURN_NONE;
}
const char *uniform="";
- int array[2]={ 0,0 };
+ int array[2] = {0, 0};
if (PyArg_ParseTuple(args, "sii:setUniform2i", &uniform, &array[0],&array[1] ))
{
int loc = GetUniformLocation(uniform);
@@ -1069,7 +1088,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform3i, "setUniform3i(name, ix,iy,iz) ")
}
const char *uniform="";
- int array[3]={0,0,0};
+ int array[3] = {0, 0, 0};
if (PyArg_ParseTuple(args, "siii:setUniform3i", &uniform, &array[0],&array[1],&array[2]))
{
int loc = GetUniformLocation(uniform);
@@ -1092,7 +1111,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform4i, "setUniform4i(name, ix,iy,iz, iw) "
Py_RETURN_NONE;
}
const char *uniform="";
- int array[4]={0,0,0, 0};
+ int array[4] = {0, 0, 0, 0};
if (PyArg_ParseTuple(args, "siiii:setUniform4i", &uniform, &array[0],&array[1],&array[2], &array[3] ))
{
int loc = GetUniformLocation(uniform);
@@ -1134,7 +1153,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformfv, "setUniformfv( float (list2 or list
Py_DECREF(item);
}
- switch(list_size)
+ switch (list_size)
{
case 2:
{
@@ -1142,7 +1161,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformfv, "setUniformfv( float (list2 or list
#ifdef SORT_UNIFORMS
SetUniformfv(loc, BL_Uniform::UNI_FLOAT2, array2, sizeof(float)*2);
#else
- SetUniform(loc, array2, 2);
+ SetUniform(loc, array2, 2);
#endif
Py_RETURN_NONE;
} break;
@@ -1152,7 +1171,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformfv, "setUniformfv( float (list2 or list
#ifdef SORT_UNIFORMS
SetUniformfv(loc, BL_Uniform::UNI_FLOAT3, array3, sizeof(float)*3);
#else
- SetUniform(loc, array3, 3);
+ SetUniform(loc, array3, 3);
#endif
Py_RETURN_NONE;
}break;
@@ -1162,7 +1181,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformfv, "setUniformfv( float (list2 or list
#ifdef SORT_UNIFORMS
SetUniformfv(loc, BL_Uniform::UNI_FLOAT4, array4, sizeof(float)*4);
#else
- SetUniform(loc, array4, 4);
+ SetUniform(loc, array4, 4);
#endif
Py_RETURN_NONE;
}break;
@@ -1218,7 +1237,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformiv, "setUniformiv( uniform_name, (list2
/* Sanity checks done! */
- switch(list_size)
+ switch (list_size)
{
case 2:
{
@@ -1226,7 +1245,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformiv, "setUniformiv( uniform_name, (list2
#ifdef SORT_UNIFORMS
SetUniformiv(loc, BL_Uniform::UNI_INT2, array2, sizeof(int)*2);
#else
- SetUniform(loc, array2, 2);
+ SetUniform(loc, array2, 2);
#endif
Py_RETURN_NONE;
} break;
@@ -1237,7 +1256,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformiv, "setUniformiv( uniform_name, (list2
SetUniformiv(loc, BL_Uniform::UNI_INT3, array3, sizeof(int)*3);
#else
- SetUniform(loc, array3, 3);
+ SetUniform(loc, array3, 3);
#endif
Py_RETURN_NONE;
}break;
@@ -1248,7 +1267,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformiv, "setUniformiv( uniform_name, (list2
SetUniformiv(loc, BL_Uniform::UNI_INT4, array4, sizeof(int)*4);
#else
- SetUniform(loc, array4, 4);
+ SetUniform(loc, array4, 4);
#endif
Py_RETURN_NONE;
}break;
@@ -1394,15 +1413,14 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformDef, "setUniformDef(name, enum)" )
{
bool defined = false;
BL_UniformVecDef::iterator it = mPreDef.begin();
- while(it != mPreDef.end()) {
+ while (it != mPreDef.end()) {
if ((*it)->mLoc == loc) {
defined = true;
break;
}
it++;
}
- if (defined)
- {
+ if (defined) {
Py_RETURN_NONE;
}
diff --git a/source/gameengine/Ketsji/BL_Shader.h b/source/gameengine/Ketsji/BL_Shader.h
index 2bb094f12ee..82476873b85 100644
--- a/source/gameengine/Ketsji/BL_Shader.h
+++ b/source/gameengine/Ketsji/BL_Shader.h
@@ -222,7 +222,7 @@ public:
// Python interface
#ifdef WITH_PYTHON
- virtual PyObject* py_repr(void) { return PyUnicode_FromFormat("BL_Shader\n\tvertex shader:%s\n\n\tfragment shader%s\n\n", vertProg, fragProg); }
+ virtual PyObject *py_repr(void) { return PyUnicode_FromFormat("BL_Shader\n\tvertex shader:%s\n\n\tfragment shader%s\n\n", vertProg, fragProg); }
// -----------------------------------
KX_PYMETHOD_DOC(BL_Shader, setSource);
@@ -252,4 +252,4 @@ public:
#endif
};
-#endif//__BL_SHADER_H__
+#endif /* __BL_SHADER_H__ */
diff --git a/source/gameengine/Ketsji/BL_Texture.cpp b/source/gameengine/Ketsji/BL_Texture.cpp
index b8cc4ebeff9..26523df8db3 100644
--- a/source/gameengine/Ketsji/BL_Texture.cpp
+++ b/source/gameengine/Ketsji/BL_Texture.cpp
@@ -47,7 +47,7 @@ static int power_of_2_min_i(int num)
{
while (!is_power_of_2_i(num))
num= num&(num-1);
- return num;
+ return num;
}
// Place holder for a full texture manager
@@ -427,7 +427,7 @@ void BL_Texture::DisableAllTextures()
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
- glDisable(GL_TEXTURE_2D);
+ glDisable(GL_TEXTURE_2D);
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
glDisable(GL_TEXTURE_GEN_R);
@@ -447,14 +447,14 @@ void BL_Texture::ActivateTexture()
if (mType == GL_TEXTURE_CUBE_MAP_ARB && GLEW_ARB_texture_cube_map)
{
- glBindTexture( GL_TEXTURE_CUBE_MAP_ARB, mTexture );
+ glBindTexture( GL_TEXTURE_CUBE_MAP_ARB, mTexture );
glEnable(GL_TEXTURE_CUBE_MAP_ARB);
}
else {
if (GLEW_ARB_texture_cube_map )
glDisable(GL_TEXTURE_CUBE_MAP_ARB);
- glBindTexture( GL_TEXTURE_2D, mTexture );
+ glBindTexture( GL_TEXTURE_2D, mTexture );
glEnable(GL_TEXTURE_2D);
}
}
@@ -562,7 +562,7 @@ void BL_Texture::setTexEnv(BL_Material *mat, bool modulate)
using_alpha = true;
}
- switch( mat->blend_mode[mUnit] ) {
+ switch (mat->blend_mode[mUnit]) {
case BLEND_MIX:
{
// ------------------------------
@@ -659,7 +659,7 @@ void my_envmap_split_ima(EnvMap *env, ImBuf *ibuf)
{
int dx, part;
- my_free_envmapdata(env);
+ my_free_envmapdata(env);
dx= ibuf->y;
dx/= 2;
@@ -670,7 +670,7 @@ void my_envmap_split_ima(EnvMap *env, ImBuf *ibuf)
}
else {
for (part=0; part<6; part++) {
- env->cube[part]= IMB_allocImBuf(dx, dx, 24, IB_rect);
+ env->cube[part] = IMB_allocImBuf(dx, dx, 24, IB_rect);
}
IMB_rectcpy(env->cube[0], ibuf,
0, 0, 0, 0, dx, dx);
@@ -698,7 +698,7 @@ void my_free_envmapdata(EnvMap *env)
ImBuf *ibuf= env->cube[part];
if (ibuf) {
IMB_freeImBuf(ibuf);
- env->cube[part]= NULL;
+ env->cube[part] = NULL;
}
}
env->ok= 0;
diff --git a/source/gameengine/Ketsji/BL_Texture.h b/source/gameengine/Ketsji/BL_Texture.h
index a6bd354d260..cd18ef93822 100644
--- a/source/gameengine/Ketsji/BL_Texture.h
+++ b/source/gameengine/Ketsji/BL_Texture.h
@@ -79,4 +79,4 @@ public:
#endif
};
-#endif//__BL_TEXTURE_H__
+#endif /* __BL_TEXTURE_H__ */
diff --git a/source/gameengine/Ketsji/CMakeLists.txt b/source/gameengine/Ketsji/CMakeLists.txt
index 269311b7e00..4778a6ef9b9 100644
--- a/source/gameengine/Ketsji/CMakeLists.txt
+++ b/source/gameengine/Ketsji/CMakeLists.txt
@@ -74,6 +74,7 @@ set(SRC
KX_Camera.cpp
KX_CameraActuator.cpp
KX_CameraIpoSGController.cpp
+ KX_CharacterWrapper.cpp
KX_ConstraintActuator.cpp
KX_ConstraintWrapper.cpp
KX_ConvertPhysicsObjects.cpp
@@ -149,6 +150,7 @@ set(SRC
KX_Camera.h
KX_CameraActuator.h
KX_CameraIpoSGController.h
+ KX_CharacterWrapper.h
KX_ClientObjectInfo.h
KX_ConstraintActuator.h
KX_ConstraintWrapper.h
@@ -248,9 +250,11 @@ endif()
if(WITH_BULLET)
list(APPEND INC
- ../../../extern/bullet2/src
../Physics/Bullet
)
+ list(APPEND INC
+ ../../../extern/bullet2/src
+ )
add_definitions(-DUSE_BULLET)
endif()
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h
index 3202785ee81..9a13b6d53e2 100644
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h
+++ b/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h
@@ -52,5 +52,4 @@ public:
return m_ndi; }
};
-#endif //__KX_NETWORKEVENTMANAGER_H__
-
+#endif /* __KX_NETWORKEVENTMANAGER_H__ */
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h
index 980e1cda6dc..325a7be9bd7 100644
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h
+++ b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h
@@ -69,5 +69,4 @@ public:
};
-#endif //__KX_NETWORKMESSAGEACTUATOR_H__
-
+#endif /* __KX_NETWORKMESSAGEACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
index a69f02baa57..6260596159d 100644
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
+++ b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
@@ -38,7 +38,7 @@
#include "NG_NetworkMessage.h"
#include "NG_NetworkScene.h"
#include "NG_NetworkObject.h"
-#include "SCA_IObject.h"
+#include "SCA_IObject.h"
#include "InputParser.h"
#include "ListValue.h"
#include "StringValue.h"
@@ -201,7 +201,7 @@ PyAttributeDef KX_NetworkMessageSensor::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_NetworkMessageSensor::pyattr_get_bodies(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_NetworkMessageSensor::pyattr_get_bodies(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_NetworkMessageSensor *self = static_cast<KX_NetworkMessageSensor*>(self_v);
if (self->m_BodyList) {
@@ -211,7 +211,7 @@ PyObject* KX_NetworkMessageSensor::pyattr_get_bodies(void *self_v, const KX_PYAT
}
}
-PyObject* KX_NetworkMessageSensor::pyattr_get_subjects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_NetworkMessageSensor::pyattr_get_subjects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_NetworkMessageSensor *self = static_cast<KX_NetworkMessageSensor*>(self_v);
if (self->m_SubjectList) {
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h
index 66f723d072c..a1f0692b7b3 100644
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h
+++ b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h
@@ -80,12 +80,11 @@ public:
/* ------------------------------------------------------------- */
/* attributes */
- static PyObject* pyattr_get_bodies(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject* pyattr_get_bodies(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static PyObject* pyattr_get_subjects(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif //__KX_NETWORKMESSAGESENSOR_H__
-
+#endif /* __KX_NETWORKMESSAGESENSOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_ArmatureSensor.cpp b/source/gameengine/Ketsji/KX_ArmatureSensor.cpp
index f72d9c1dee6..523f3ceeaea 100644
--- a/source/gameengine/Ketsji/KX_ArmatureSensor.cpp
+++ b/source/gameengine/Ketsji/KX_ArmatureSensor.cpp
@@ -86,7 +86,7 @@ void KX_ArmatureSensor::FindConstraint()
/* this constraint is not valid, can't use it */
break;
m_constraint = pcon;
- break;
+ break;
}
}
break;
@@ -193,13 +193,13 @@ PyAttributeDef KX_ArmatureSensor::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_ArmatureSensor::pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_ArmatureSensor::pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_ArmatureSensor* sensor = static_cast<KX_ArmatureSensor*>(self);
if (sensor->m_gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) {
BL_ArmatureObject* armobj = (BL_ArmatureObject*)sensor->m_gameobj;
BL_ArmatureConstraint* constraint = armobj->GetConstraint(sensor->m_posechannel, sensor->m_constraintname);
- if (constraint)
+ if (constraint)
return constraint->GetProxy();
}
Py_RETURN_NONE;
diff --git a/source/gameengine/Ketsji/KX_ArmatureSensor.h b/source/gameengine/Ketsji/KX_ArmatureSensor.h
index 9c3faa355a6..b3ea905d198 100644
--- a/source/gameengine/Ketsji/KX_ArmatureSensor.h
+++ b/source/gameengine/Ketsji/KX_ArmatureSensor.h
@@ -72,9 +72,9 @@ public:
/* --------------------------------------------------------------------- */
/* Python interface ---------------------------------------------------- */
/* --------------------------------------------------------------------- */
- static PyObject* pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
private:
struct bConstraint* m_constraint;
diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp b/source/gameengine/Ketsji/KX_BlenderMaterial.cpp
index b602ba447ad..2154beeb205 100644
--- a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp
+++ b/source/gameengine/Ketsji/KX_BlenderMaterial.cpp
@@ -165,11 +165,11 @@ void KX_BlenderMaterial::InitTextures()
continue;
}
if (!mTextures[i].InitCubeMap(i, mMaterial->cubemap[i] ) )
- spit("unable to initialize image("<<i<<") in "<<
- mMaterial->matname<< ", image will not be available");
- }
- // If we're using glsl materials, the textures are handled by bf_gpu, so don't load them twice!
- // However, if we're using a custom shader, then we still need to load the textures ourselves.
+ spit("unable to initialize image("<<i<<") in "<<
+ mMaterial->matname<< ", image will not be available");
+ }
+ /* If we're using glsl materials, the textures are handled by bf_gpu, so don't load them twice!
+ * However, if we're using a custom shader, then we still need to load the textures ourselves. */
else if (!mMaterial->glslmat || mShader) {
if ( mMaterial->img[i] ) {
if ( ! mTextures[i].InitFromImage(i, mMaterial->img[i], (mMaterial->flag[i] &MIPMAP)!=0 ))
@@ -412,7 +412,7 @@ KX_BlenderMaterial::ActivatShaders(
if ((mMaterial->ras_mode &WIRE) ||
(rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
- {
+ {
if (mMaterial->ras_mode &WIRE)
rasty->SetCullFace(false);
rasty->SetLines(true);
@@ -457,7 +457,7 @@ KX_BlenderMaterial::ActivateBlenderShaders(
if ((mMaterial->ras_mode &WIRE) ||
(rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
- {
+ {
if (mMaterial->ras_mode &WIRE)
rasty->SetCullFace(false);
rasty->SetLines(true);
@@ -506,7 +506,7 @@ KX_BlenderMaterial::ActivateMat(
if ((mMaterial->ras_mode &WIRE) ||
(rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
- {
+ {
if (mMaterial->ras_mode &WIRE)
rasty->SetCullFace(false);
rasty->SetLines(true);
@@ -614,7 +614,7 @@ void KX_BlenderMaterial::ActivatGLMaterials( RAS_IRasterizer* rasty )const
mMaterial->matcolor[2]*mMaterial->ref+mMaterial->emit,
1.0f);
- rasty->SetEmissive(
+ rasty->SetEmissive(
mMaterial->matcolor[0]*mMaterial->emit,
mMaterial->matcolor[1]*mMaterial->emit,
mMaterial->matcolor[2]*mMaterial->emit,
@@ -726,7 +726,7 @@ void KX_BlenderMaterial::setObjectMatrixData(int i, RAS_IRasterizer *ras)
GLenum plane = GL_EYE_PLANE;
// figure plane gen
- float proj[4]= {0.f,0.f,0.f,0.f};
+ float proj[4] = {0.f,0.f,0.f,0.f};
GetProjPlane(mMaterial, i, 0, proj);
glTexGenfv(GL_S, plane, proj);
@@ -835,29 +835,29 @@ PyTypeObject KX_BlenderMaterial::Type = {
py_base_new
};
-PyObject* KX_BlenderMaterial::pyattr_get_shader(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_BlenderMaterial::pyattr_get_shader(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_BlenderMaterial* self= static_cast<KX_BlenderMaterial*>(self_v);
+ KX_BlenderMaterial* self = static_cast<KX_BlenderMaterial*>(self_v);
return self->PygetShader(NULL, NULL);
}
-PyObject* KX_BlenderMaterial::pyattr_get_materialIndex(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_BlenderMaterial::pyattr_get_materialIndex(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_BlenderMaterial* self= static_cast<KX_BlenderMaterial*>(self_v);
+ KX_BlenderMaterial* self = static_cast<KX_BlenderMaterial*>(self_v);
return PyLong_FromSsize_t(self->GetMaterialIndex());
}
-PyObject* KX_BlenderMaterial::pyattr_get_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_BlenderMaterial::pyattr_get_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_BlenderMaterial* self= static_cast<KX_BlenderMaterial*>(self_v);
+ KX_BlenderMaterial* self = static_cast<KX_BlenderMaterial*>(self_v);
unsigned int* bfunc = self->getBlendFunc();
return Py_BuildValue("(ll)", (long int)bfunc[0], (long int)bfunc[1]);
}
int KX_BlenderMaterial::pyattr_set_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_BlenderMaterial* self= static_cast<KX_BlenderMaterial*>(self_v);
- PyObject* obj = self->PysetBlending(value, NULL);
+ KX_BlenderMaterial* self = static_cast<KX_BlenderMaterial*>(self_v);
+ PyObject *obj = self->PysetBlending(value, NULL);
if (obj)
{
Py_DECREF(obj);
diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.h b/source/gameengine/Ketsji/KX_BlenderMaterial.h
index 8fc86ef9cf2..1653669ebcc 100644
--- a/source/gameengine/Ketsji/KX_BlenderMaterial.h
+++ b/source/gameengine/Ketsji/KX_BlenderMaterial.h
@@ -106,11 +106,11 @@ public:
#ifdef WITH_PYTHON
// --------------------------------
- virtual PyObject* py_repr(void) { return PyUnicode_From_STR_String(mMaterial->matname); }
+ virtual PyObject *py_repr(void) { return PyUnicode_From_STR_String(mMaterial->matname); }
- static PyObject* pyattr_get_shader(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_materialIndex(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_shader(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_materialIndex(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
KX_PYMETHOD_DOC(KX_BlenderMaterial, getShader);
@@ -119,7 +119,7 @@ public:
KX_PYMETHOD_DOC(KX_BlenderMaterial, setTexture);
KX_PYMETHOD_DOC(KX_BlenderMaterial, setBlending);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
// --------------------------------
// pre calculate to avoid pops/lag at startup
diff --git a/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp b/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp
index b974886f60a..20c41b95dd3 100644
--- a/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp
+++ b/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp
@@ -269,7 +269,7 @@ void KX_BulletPhysicsController::AddCompoundChild(KX_IPhysicsController* chil
rootScale[2] = 1.0/rootScale[2];
// relative scale = child_scale/parent_scale
btVector3 relativeScale = childShape->getLocalScaling()*rootScale;
- btMatrix3x3 rootRotInverse = rootTrans.getBasis().transpose();
+ btMatrix3x3 rootRotInverse = rootTrans.getBasis().transpose();
// relative pos = parent_rot^-1 * ((parent_pos-child_pos)/parent_scale)
btVector3 relativePos = rootRotInverse*((childTrans.getOrigin()-rootTrans.getOrigin())*rootScale);
// relative rot = parent_rot^-1 * child_rot
diff --git a/source/gameengine/Ketsji/KX_BulletPhysicsController.h b/source/gameengine/Ketsji/KX_BulletPhysicsController.h
index 71e806686ca..4813b39a34e 100644
--- a/source/gameengine/Ketsji/KX_BulletPhysicsController.h
+++ b/source/gameengine/Ketsji/KX_BulletPhysicsController.h
@@ -96,5 +96,4 @@ public:
#endif
};
-#endif //__KX_BULLETPHYSICSCONTROLLER_H__
-
+#endif /* __KX_BULLETPHYSICSCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_Camera.cpp b/source/gameengine/Ketsji/KX_Camera.cpp
index ac17adaf052..39b0a24865e 100644
--- a/source/gameengine/Ketsji/KX_Camera.cpp
+++ b/source/gameengine/Ketsji/KX_Camera.cpp
@@ -38,19 +38,19 @@
#include "KX_Python.h"
#include "KX_PyMath.h"
KX_Camera::KX_Camera(void* sgReplicationInfo,
- SG_Callbacks callbacks,
- const RAS_CameraData& camdata,
- bool frustum_culling,
- bool delete_node)
- :
- KX_GameObject(sgReplicationInfo,callbacks),
- m_camdata(camdata),
- m_dirty(true),
- m_normalized(false),
- m_frustum_culling(frustum_culling),
- m_set_projection_matrix(false),
- m_set_frustum_center(false),
- m_delete_node(delete_node)
+ SG_Callbacks callbacks,
+ const RAS_CameraData& camdata,
+ bool frustum_culling,
+ bool delete_node)
+ :
+ KX_GameObject(sgReplicationInfo,callbacks),
+ m_camdata(camdata),
+ m_dirty(true),
+ m_normalized(false),
+ m_frustum_culling(frustum_culling),
+ m_set_projection_matrix(false),
+ m_set_frustum_center(false),
+ m_delete_node(delete_node)
{
// setting a name would be nice...
m_name = "cam";
@@ -67,7 +67,7 @@ KX_Camera::~KX_Camera()
delete m_pSGNode;
m_pSGNode = NULL;
}
-}
+}
CValue* KX_Camera::GetReplica()
@@ -119,7 +119,7 @@ const MT_Point3 KX_Camera::GetCameraLocation() const
//MT_Transform trans;
//trans.setBasis(NodeGetWorldOrientation());
- return NodeGetWorldPosition();
+ return NodeGetWorldPosition();
}
@@ -712,15 +712,15 @@ KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, setOnTop,
Py_RETURN_NONE;
}
-PyObject* KX_Camera::pyattr_get_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
return PyBool_FromLong(self->m_camdata.m_perspective);
}
int KX_Camera::pyattr_set_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
int param = PyObject_IsTrue( value );
if (param == -1) {
PyErr_SetString(PyExc_AttributeError, "camera.perspective = bool: KX_Camera, expected True/False or 0/1");
@@ -732,15 +732,15 @@ int KX_Camera::pyattr_set_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *at
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_Camera::pyattr_get_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
return PyFloat_FromDouble(self->m_camdata.m_lens);
}
int KX_Camera::pyattr_set_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
float param = PyFloat_AsDouble(value);
if (param == -1) {
PyErr_SetString(PyExc_AttributeError, "camera.lens = float: KX_Camera, expected a float greater then zero");
@@ -752,15 +752,15 @@ int KX_Camera::pyattr_set_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef,
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_Camera::pyattr_get_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
return PyFloat_FromDouble(self->m_camdata.m_scale);
}
int KX_Camera::pyattr_set_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
float param = PyFloat_AsDouble(value);
if (param == -1) {
PyErr_SetString(PyExc_AttributeError, "camera.ortho_scale = float: KX_Camera, expected a float greater then zero");
@@ -772,15 +772,15 @@ int KX_Camera::pyattr_set_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *at
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_Camera::pyattr_get_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
return PyFloat_FromDouble(self->m_camdata.m_clipstart);
}
int KX_Camera::pyattr_set_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
float param = PyFloat_AsDouble(value);
if (param == -1) {
PyErr_SetString(PyExc_AttributeError, "camera.near = float: KX_Camera, expected a float greater then zero");
@@ -792,15 +792,15 @@ int KX_Camera::pyattr_set_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef,
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_Camera::pyattr_get_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
return PyFloat_FromDouble(self->m_camdata.m_clipend);
}
int KX_Camera::pyattr_set_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
float param = PyFloat_AsDouble(value);
if (param == -1) {
PyErr_SetString(PyExc_AttributeError, "camera.far = float: KX_Camera, expected a float greater then zero");
@@ -813,15 +813,15 @@ int KX_Camera::pyattr_set_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, P
}
-PyObject* KX_Camera::pyattr_get_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
return PyBool_FromLong(self->GetViewport());
}
int KX_Camera::pyattr_set_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
int param = PyObject_IsTrue( value );
if (param == -1) {
PyErr_SetString(PyExc_AttributeError, "camera.useViewport = bool: KX_Camera, expected True or False");
@@ -832,15 +832,15 @@ int KX_Camera::pyattr_set_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *a
}
-PyObject* KX_Camera::pyattr_get_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
return PyObjectFrom(self->GetProjectionMatrix());
}
int KX_Camera::pyattr_set_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
MT_Matrix4x4 mat;
if (!PyMatTo(value, mat))
return PY_SET_ATTR_FAIL;
@@ -849,34 +849,34 @@ int KX_Camera::pyattr_set_projection_matrix(void *self_v, const KX_PYATTRIBUTE_D
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_Camera::pyattr_get_modelview_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_modelview_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
return PyObjectFrom(self->GetModelviewMatrix());
}
-PyObject* KX_Camera::pyattr_get_camera_to_world(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_camera_to_world(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
return PyObjectFrom(self->GetCameraToWorld());
}
-PyObject* KX_Camera::pyattr_get_world_to_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_world_to_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Camera* self= static_cast<KX_Camera*>(self_v);
+ KX_Camera* self = static_cast<KX_Camera*>(self_v);
return PyObjectFrom(self->GetWorldToCamera());
}
-PyObject* KX_Camera::pyattr_get_INSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_INSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{ return PyLong_FromSsize_t(INSIDE); }
-PyObject* KX_Camera::pyattr_get_OUTSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_OUTSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{ return PyLong_FromSsize_t(OUTSIDE); }
-PyObject* KX_Camera::pyattr_get_INTERSECT(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Camera::pyattr_get_INTERSECT(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{ return PyLong_FromSsize_t(INTERSECT); }
-bool ConvertPythonToCamera(PyObject * value, KX_Camera **object, bool py_none_ok, const char *error_prefix)
+bool ConvertPythonToCamera(PyObject *value, KX_Camera **object, bool py_none_ok, const char *error_prefix)
{
if (value==NULL) {
PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
@@ -956,7 +956,7 @@ KX_PYMETHODDEF_DOC_O(KX_Camera, getScreenPosition,
}
}
- GLint viewport[4];
+ const GLint *viewport;
GLdouble win[3];
GLdouble modelmatrix[16];
GLdouble projmatrix[16];
@@ -967,7 +967,7 @@ KX_PYMETHODDEF_DOC_O(KX_Camera, getScreenPosition,
m_modelmatrix.getValue(modelmatrix);
m_projmatrix.getValue(projmatrix);
- glGetIntegerv(GL_VIEWPORT, viewport);
+ viewport = KX_GetActiveEngine()->GetCanvas()->GetViewPort();
gluProject(vect[0], vect[1], vect[2], modelmatrix, projmatrix, viewport, &win[0], &win[1], &win[2]);
@@ -976,7 +976,7 @@ KX_PYMETHODDEF_DOC_O(KX_Camera, getScreenPosition,
vect[1] = 1.0 - vect[1]; //to follow Blender window coordinate system (Top-Down)
- PyObject* ret = PyTuple_New(2);
+ PyObject *ret = PyTuple_New(2);
if (ret) {
PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(vect[0]));
PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(vect[1]));
@@ -999,7 +999,7 @@ KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenVect,
MT_Vector3 vect;
MT_Point3 campos, screenpos;
- GLint viewport[4];
+ const GLint *viewport;
GLdouble win[3];
GLdouble modelmatrix[16];
GLdouble projmatrix[16];
@@ -1010,7 +1010,7 @@ KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenVect,
m_modelmatrix.getValue(modelmatrix);
m_projmatrix.getValue(projmatrix);
- glGetIntegerv(GL_VIEWPORT, viewport);
+ viewport = KX_GetActiveEngine()->GetCanvas()->GetViewPort();
vect[0] = x * viewport[2];
vect[1] = y * viewport[3];
@@ -1040,7 +1040,7 @@ KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenRay,
if (!PyArg_ParseTuple(args,"ddd|s:getScreenRay",&x,&y,&dist,&propName))
return NULL;
- PyObject* argValue = PyTuple_New(2);
+ PyObject *argValue = PyTuple_New(2);
PyTuple_SET_ITEM(argValue, 0, PyFloat_FromDouble(x));
PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(y));
@@ -1065,7 +1065,7 @@ KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenRay,
if (propName)
PyTuple_SET_ITEM(argValue, 2, PyUnicode_FromString(propName));
- PyObject* ret= this->PyrayCastTo(argValue,NULL);
+ PyObject *ret= this->PyrayCastTo(argValue,NULL);
Py_DECREF(argValue);
return ret;
}
diff --git a/source/gameengine/Ketsji/KX_Camera.h b/source/gameengine/Ketsji/KX_Camera.h
index 7481b2eb7f0..f615fefc223 100644
--- a/source/gameengine/Ketsji/KX_Camera.h
+++ b/source/gameengine/Ketsji/KX_Camera.h
@@ -45,7 +45,7 @@
#ifdef WITH_PYTHON
/* utility conversion function */
-bool ConvertPythonToCamera(PyObject * value, KX_Camera **object, bool py_none_ok, const char *error_prefix);
+bool ConvertPythonToCamera(PyObject *value, KX_Camera **object, bool py_none_ok, const char *error_prefix);
#endif
class KX_Camera : public KX_GameObject
@@ -120,7 +120,7 @@ protected:
/**
* whether the camera should delete the node itself (only for shadow camera)
*/
- bool m_delete_node;
+ bool m_delete_node;
/**
* Extracts the camera clip frames from the projection and world-to-camera matrices.
@@ -156,7 +156,7 @@ public:
* instance allocated on the heap. Ownership of the new
* object belongs with the caller.
*/
- virtual CValue*
+ virtual CValue*
GetReplica(
);
virtual void ProcessReplica();
@@ -286,8 +286,8 @@ public:
KX_PYMETHOD_DOC_NOARGS(KX_Camera, getCameraToWorld);
KX_PYMETHOD_DOC_NOARGS(KX_Camera, getWorldToCamera);
- KX_PYMETHOD_DOC_VARARGS(KX_Camera, setViewport);
- KX_PYMETHOD_DOC_NOARGS(KX_Camera, setOnTop);
+ KX_PYMETHOD_DOC_VARARGS(KX_Camera, setViewport);
+ KX_PYMETHOD_DOC_NOARGS(KX_Camera, setOnTop);
KX_PYMETHOD_DOC_O(KX_Camera, getScreenPosition);
KX_PYMETHOD_DOC_VARARGS(KX_Camera, getScreenVect);
@@ -321,5 +321,4 @@ public:
#endif
};
-#endif //__KX_CAMERA_H__
-
+#endif /* __KX_CAMERA_H__ */
diff --git a/source/gameengine/Ketsji/KX_CameraActuator.cpp b/source/gameengine/Ketsji/KX_CameraActuator.cpp
index 4c63afa7f3e..a37b1b0c396 100644
--- a/source/gameengine/Ketsji/KX_CameraActuator.cpp
+++ b/source/gameengine/Ketsji/KX_CameraActuator.cpp
@@ -143,9 +143,9 @@ static void Kx_VecUpMat3(float vec[3], float mat[][3], short axis)
}
if (axis==3) {
cox= 0; coy= 1; coz= 2; /* Y op -Z tr */
- vec[0]= -vec[0];
- vec[1]= -vec[1];
- vec[2]= -vec[2];
+ vec[0] = -vec[0];
+ vec[1] = -vec[1];
+ vec[2] = -vec[2];
}
if (axis==4) {
cox= 1; coy= 0; coz= 2; /* */
@@ -154,9 +154,9 @@ static void Kx_VecUpMat3(float vec[3], float mat[][3], short axis)
cox= 2; coy= 1; coz= 0; /* Y up X tr */
}
- mat[coz][0]= vec[0];
- mat[coz][1]= vec[1];
- mat[coz][2]= vec[2];
+ mat[coz][0] = vec[0];
+ mat[coz][1] = vec[1];
+ mat[coz][2] = vec[2];
if (normalize_v3((float *)mat[coz]) == 0.f) {
/* this is a very abnormal situation: the camera has reach the object center exactly
* We will choose a completely arbitrary direction */
@@ -281,13 +281,13 @@ bool KX_CameraActuator::Update(double curtime, bool frame)
assert(0);
break;
}
-
+
inp = fp1[0]*fp2[0] + fp1[1]*fp2[1] + fp1[2]*fp2[2];
fac = (-1.0f + inp) * m_damping;
- from[0]+= fac*fp1[0];
- from[1]+= fac*fp1[1];
- from[2]+= fac*fp1[2];
+ from[0] += fac * fp1[0];
+ from[1] += fac * fp1[1];
+ from[2] += fac * fp1[2];
/* alleen alstie ervoor ligt: cross testen en loodrechte bijtellen */
if (inp < 0.0f) {
@@ -303,9 +303,9 @@ bool KX_CameraActuator::Update(double curtime, bool frame)
/* CONSTRAINT 5: minimum / maximum afstand */
- rc[0]= (lookat[0]-from[0]);
- rc[1]= (lookat[1]-from[1]);
- rc[2]= (lookat[2]-from[2]);
+ rc[0] = (lookat[0]-from[0]);
+ rc[1] = (lookat[1]-from[1]);
+ rc[2] = (lookat[2]-from[2]);
distsq = rc[0]*rc[0] + rc[1]*rc[1] + rc[2]*rc[2];
if (distsq > maxdistsq) {
@@ -325,9 +325,9 @@ bool KX_CameraActuator::Update(double curtime, bool frame)
/* CONSTRAINT 7: track to schaduw */
- rc[0]= (lookat[0]-from[0]);
- rc[1]= (lookat[1]-from[1]);
- rc[2]= (lookat[2]-from[2]);
+ rc[0] = (lookat[0]-from[0]);
+ rc[1] = (lookat[1]-from[1]);
+ rc[2] = (lookat[2]-from[2]);
Kx_VecUpMat3(rc, mat, 3); /* y up Track -z */
@@ -337,9 +337,9 @@ bool KX_CameraActuator::Update(double curtime, bool frame)
obj->NodeSetLocalPosition(from);
- actormat[0][0]= mat[0][0]; actormat[0][1]= mat[1][0]; actormat[0][2]= mat[2][0];
- actormat[1][0]= mat[0][1]; actormat[1][1]= mat[1][1]; actormat[1][2]= mat[2][1];
- actormat[2][0]= mat[0][2]; actormat[2][1]= mat[1][2]; actormat[2][2]= mat[2][2];
+ actormat[0][0] = mat[0][0]; actormat[0][1] = mat[1][0]; actormat[0][2] = mat[2][0];
+ actormat[1][0] = mat[0][1]; actormat[1][1] = mat[1][1]; actormat[1][2] = mat[2][1];
+ actormat[2][0] = mat[0][2]; actormat[2][1] = mat[1][2]; actormat[2][2] = mat[2][2];
obj->NodeSetLocalOrientation(actormat);
return true;
@@ -394,9 +394,9 @@ PyAttributeDef KX_CameraActuator::Attributes[] = {
{NULL}
};
-PyObject* KX_CameraActuator::pyattr_get_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_CameraActuator::pyattr_get_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_CameraActuator* self= static_cast<KX_CameraActuator*>(self_v);
+ KX_CameraActuator* self = static_cast<KX_CameraActuator*>(self_v);
if (self->m_ob==NULL)
Py_RETURN_NONE;
else
@@ -405,14 +405,14 @@ PyObject* KX_CameraActuator::pyattr_get_object(void *self_v, const KX_PYATTRIBUT
int KX_CameraActuator::pyattr_set_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_CameraActuator* self= static_cast<KX_CameraActuator*>(self_v);
+ KX_CameraActuator* self = static_cast<KX_CameraActuator*>(self_v);
KX_GameObject *gameobj;
if (!ConvertPythonToGameObject(value, &gameobj, true, "actuator.object = value: KX_CameraActuator"))
return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
if (self->m_ob)
- self->m_ob->UnregisterActuator(self);
+ self->m_ob->UnregisterActuator(self);
if ((self->m_ob = (SCA_IObject*)gameobj))
self->m_ob->RegisterActuator(self);
diff --git a/source/gameengine/Ketsji/KX_CameraActuator.h b/source/gameengine/Ketsji/KX_CameraActuator.h
index c67174d2830..fb0a7d88dd9 100644
--- a/source/gameengine/Ketsji/KX_CameraActuator.h
+++ b/source/gameengine/Ketsji/KX_CameraActuator.h
@@ -131,9 +131,8 @@ private :
static PyObject* pyattr_get_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif //__KX_CAMERAACTUATOR_H__
-
+#endif /* __KX_CAMERAACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_CameraIpoSGController.h b/source/gameengine/Ketsji/KX_CameraIpoSGController.h
index 06058760332..1f6f211622c 100644
--- a/source/gameengine/Ketsji/KX_CameraIpoSGController.h
+++ b/source/gameengine/Ketsji/KX_CameraIpoSGController.h
@@ -77,13 +77,13 @@ public:
m_ipotime = time;
m_modified = true;
}
- void SetModifyLens(bool modify) {
+ void SetModifyLens(bool modify) {
m_modify_lens = modify;
}
- void SetModifyClipEnd(bool modify) {
+ void SetModifyClipEnd(bool modify) {
m_modify_clipend = modify;
}
- void SetModifyClipStart(bool modify) {
+ void SetModifyClipStart(bool modify) {
m_modify_clipstart = modify;
}
void AddInterpolator(KX_IInterpolator* interp);
@@ -94,5 +94,4 @@ public:
#endif
};
-#endif // __KX_CAMERAIPOSGCONTROLLER_H__
-
+#endif /* __KX_CAMERAIPOSGCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_CharacterWrapper.cpp b/source/gameengine/Ketsji/KX_CharacterWrapper.cpp
new file mode 100644
index 00000000000..ce208f3a75f
--- /dev/null
+++ b/source/gameengine/Ketsji/KX_CharacterWrapper.cpp
@@ -0,0 +1,94 @@
+/** \file gameengine/Ketsji/KX_CharacterWrapper.cpp
+ * \ingroup ketsji
+ */
+
+
+#include "KX_CharacterWrapper.h"
+#include "PHY_ICharacter.h"
+
+KX_CharacterWrapper::KX_CharacterWrapper(PHY_ICharacter* character) :
+ PyObjectPlus(),
+ m_character(character)
+{
+}
+
+KX_CharacterWrapper::~KX_CharacterWrapper()
+{
+ if (m_character)
+ delete m_character; // We're responsible for the character object!
+}
+
+#ifdef WITH_PYTHON
+
+PyTypeObject KX_CharacterWrapper::Type = {
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "KX_CharacterWrapper",
+ sizeof(PyObjectPlus_Proxy),
+ 0,
+ py_base_dealloc,
+ 0,
+ 0,
+ 0,
+ 0,
+ py_base_repr,
+ 0,0,0,0,0,0,0,0,0,
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
+ 0,0,0,0,0,0,0,
+ Methods,
+ 0,
+ 0,
+ &PyObjectPlus::Type,
+ 0,0,0,0,0,0,
+ py_base_new
+};
+
+PyAttributeDef KX_CharacterWrapper::Attributes[] = {
+ KX_PYATTRIBUTE_RO_FUNCTION("onGround", KX_CharacterWrapper, pyattr_get_onground),
+ KX_PYATTRIBUTE_RW_FUNCTION("gravity", KX_CharacterWrapper, pyattr_get_gravity, pyattr_set_gravity),
+ { NULL } //Sentinel
+};
+
+PyObject *KX_CharacterWrapper::pyattr_get_onground(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+{
+ KX_CharacterWrapper* self = static_cast<KX_CharacterWrapper*>(self_v);
+
+ return PyBool_FromLong(self->m_character->OnGround());
+}
+
+PyObject *KX_CharacterWrapper::pyattr_get_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+{
+ KX_CharacterWrapper* self = static_cast<KX_CharacterWrapper*>(self_v);
+
+ return PyFloat_FromDouble(self->m_character->GetGravity());
+}
+
+int KX_CharacterWrapper::pyattr_set_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
+{
+ KX_CharacterWrapper* self = static_cast<KX_CharacterWrapper*>(self_v);
+ double param = PyFloat_AsDouble(value);
+
+ if (param == -1)
+ {
+ PyErr_SetString(PyExc_ValueError, "KX_CharacterWrapper.gravity: expected a float");
+ return PY_SET_ATTR_FAIL;
+ }
+
+ self->m_character->SetGravity((float)param);
+ return PY_SET_ATTR_SUCCESS;
+}
+
+PyMethodDef KX_CharacterWrapper::Methods[] = {
+ KX_PYMETHODTABLE_NOARGS(KX_CharacterWrapper, jump),
+ {NULL,NULL} //Sentinel
+};
+
+KX_PYMETHODDEF_DOC_NOARGS(KX_CharacterWrapper, jump,
+ "jump()\n"
+ "makes the character jump.\n")
+{
+ m_character->Jump();
+
+ Py_RETURN_NONE;
+}
+
+#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_CharacterWrapper.h b/source/gameengine/Ketsji/KX_CharacterWrapper.h
new file mode 100644
index 00000000000..cc99aba99f6
--- /dev/null
+++ b/source/gameengine/Ketsji/KX_CharacterWrapper.h
@@ -0,0 +1,35 @@
+
+/** \file KX_CharacterWrapper.h
+ * \ingroup ketsji
+ */
+
+#ifndef __KX_CHARACTERWRAPPER_H__
+#define __KX_CHARACTERWRAPPER_H__
+
+#include "Value.h"
+#include "PHY_DynamicTypes.h"
+class PHY_ICharacter;
+
+
+///Python interface to character physics
+class KX_CharacterWrapper : public PyObjectPlus
+{
+ Py_Header
+
+public:
+ KX_CharacterWrapper(PHY_ICharacter* character);
+ virtual ~KX_CharacterWrapper();
+#ifdef WITH_PYTHON
+ KX_PYMETHOD_DOC_NOARGS(KX_CharacterWrapper, jump);
+
+ static PyObject* pyattr_get_onground(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+
+ static PyObject* pyattr_get_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static int pyattr_set_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
+#endif // WITH_PYTHON
+
+private:
+ PHY_ICharacter* m_character;
+};
+
+#endif //__KX_CHARACTERWRAPPER_H__
diff --git a/source/gameengine/Ketsji/KX_ClientObjectInfo.h b/source/gameengine/Ketsji/KX_ClientObjectInfo.h
index 6fd1271160a..e947eb4be6d 100644
--- a/source/gameengine/Ketsji/KX_ClientObjectInfo.h
+++ b/source/gameengine/Ketsji/KX_ClientObjectInfo.h
@@ -84,5 +84,4 @@ public:
#endif
};
-#endif //__KX_CLIENTOBJECTINFO_H__
-
+#endif /* __KX_CLIENTOBJECTINFO_H__ */
diff --git a/source/gameengine/Ketsji/KX_ConstraintActuator.cpp b/source/gameengine/Ketsji/KX_ConstraintActuator.cpp
index 322d6e60071..3caa4d35565 100644
--- a/source/gameengine/Ketsji/KX_ConstraintActuator.cpp
+++ b/source/gameengine/Ketsji/KX_ConstraintActuator.cpp
@@ -166,7 +166,7 @@ bool KX_ConstraintActuator::NeedRayCast(KX_ClientObjectInfo* client)
bool KX_ConstraintActuator::Update(double curtime, bool frame)
{
- bool result = false;
+ bool result = false;
bool bNegativeEvent = IsNegativeEvent();
RemoveAllEvents();
@@ -462,7 +462,7 @@ bool KX_ConstraintActuator::Update(double curtime, bool frame)
// we expect a hit object
if (!m_hitObject)
result = false;
- if (result)
+ if (result)
{
MT_Vector3 newnormal = callback.m_hitNormal;
// compute new position & orientation
@@ -619,7 +619,7 @@ int KX_ConstraintActuator::pyattr_check_direction(void *self, const struct KX_PY
return 1;
}
act->m_refDirVector = dir/len;
- return 0;
+ return 0;
}
#endif
diff --git a/source/gameengine/Ketsji/KX_ConstraintActuator.h b/source/gameengine/Ketsji/KX_ConstraintActuator.h
index f491aedba74..edb2e5e0180 100644
--- a/source/gameengine/Ketsji/KX_ConstraintActuator.h
+++ b/source/gameengine/Ketsji/KX_ConstraintActuator.h
@@ -43,7 +43,7 @@ class KX_GameObject;
class KX_ConstraintActuator : public SCA_IActuator
{
Py_Header
-protected:
+protected:
// Damp time (int),
int m_posDampTime;
int m_rotDampTime;
@@ -145,5 +145,4 @@ protected:
};
-#endif //__KX_CONSTRAINTACTUATOR_H__
-
+#endif /* __KX_CONSTRAINTACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp b/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp
index df6b08974dd..662db974ee8 100644
--- a/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp
+++ b/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp
@@ -50,13 +50,13 @@ KX_ConstraintWrapper::~KX_ConstraintWrapper()
#ifdef WITH_PYTHON
-PyObject* KX_ConstraintWrapper::PyGetConstraintId()
+PyObject *KX_ConstraintWrapper::PyGetConstraintId()
{
return PyLong_FromSsize_t(m_constraintId);
}
-PyObject* KX_ConstraintWrapper::PyGetParam(PyObject* args, PyObject* kwds)
+PyObject *KX_ConstraintWrapper::PyGetParam(PyObject *args, PyObject *kwds)
{
int dof;
float value;
@@ -69,7 +69,7 @@ PyObject* KX_ConstraintWrapper::PyGetParam(PyObject* args, PyObject* kwds)
}
-PyObject* KX_ConstraintWrapper::PySetParam(PyObject* args, PyObject* kwds)
+PyObject *KX_ConstraintWrapper::PySetParam(PyObject *args, PyObject *kwds)
{
int dof;
float minLimit,maxLimit;
@@ -117,9 +117,9 @@ PyAttributeDef KX_ConstraintWrapper::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_ConstraintWrapper::pyattr_get_constraintId(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_ConstraintWrapper::pyattr_get_constraintId(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_ConstraintWrapper* self= static_cast<KX_ConstraintWrapper*>(self_v);
+ KX_ConstraintWrapper* self = static_cast<KX_ConstraintWrapper*>(self_v);
return self->PyGetConstraintId();
}
diff --git a/source/gameengine/Ketsji/KX_ConstraintWrapper.h b/source/gameengine/Ketsji/KX_ConstraintWrapper.h
index a92ae83e7f0..eafc45b5a70 100644
--- a/source/gameengine/Ketsji/KX_ConstraintWrapper.h
+++ b/source/gameengine/Ketsji/KX_ConstraintWrapper.h
@@ -48,7 +48,7 @@ public:
KX_PYMETHOD(KX_ConstraintWrapper,SetParam);
KX_PYMETHOD(KX_ConstraintWrapper,GetParam);
- static PyObject* pyattr_get_constraintId(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_constraintId(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
#endif
private:
@@ -57,5 +57,4 @@ private:
PHY_IPhysicsEnvironment* m_physenv;
};
-#endif //__KX_CONSTRAINTWRAPPER_H__
-
+#endif /* __KX_CONSTRAINTWRAPPER_H__ */
diff --git a/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h b/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h
index 0f1ce403881..e71037d08a0 100644
--- a/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h
+++ b/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h
@@ -159,4 +159,4 @@ void KX_ClearBulletSharedShapes();
bool KX_ReInstanceBulletShapeFromMesh(KX_GameObject *gameobj, KX_GameObject *from_gameobj, RAS_MeshObject* from_meshobj);
#endif
-#endif //__KX_CONVERTPHYSICSOBJECT_H__
+#endif /* __KX_CONVERTPHYSICSOBJECT_H__ */
diff --git a/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp b/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp
index f1038c04499..ff3c46cb8ab 100644
--- a/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp
+++ b/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp
@@ -29,8 +29,8 @@
* \ingroup ketsji
*/
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
#endif
#include "MT_assert.h"
@@ -54,6 +54,7 @@
#include "KX_MotionState.h" // bridge between motionstate and scenegraph node
extern "C"{
+ #include "BLI_utildefines.h"
#include "BKE_DerivedMesh.h"
}
@@ -282,7 +283,7 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
relativeRot.getValue(rot);
shapeInfo->m_childTrans.getBasis().setFromOpenGLSubMatrix(rot);
- parentShapeInfo->AddShape(shapeInfo);
+ parentShapeInfo->AddShape(shapeInfo);
compoundShape->addChildShape(shapeInfo->m_childTrans,bm);
//do some recalc?
//recalc inertia for rigidbody
@@ -439,7 +440,7 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
{
env->addCcdPhysicsController( physicscontroller);
}
- physicscontroller->setNewClientInfo(gameobj->getClientInfo());
+ physicscontroller->setNewClientInfo(gameobj->getClientInfo());
{
btRigidBody* rbody = physicscontroller->GetRigidBody();
diff --git a/source/gameengine/Ketsji/KX_Dome.cpp b/source/gameengine/Ketsji/KX_Dome.cpp
index 44c9cb1dab8..fca407f6398 100644
--- a/source/gameengine/Ketsji/KX_Dome.cpp
+++ b/source/gameengine/Ketsji/KX_Dome.cpp
@@ -90,12 +90,11 @@ KX_Dome::KX_Dome (
}
//setting the viewport size
- GLuint viewport[4]={0};
- glGetIntegerv(GL_VIEWPORT,(GLint *)viewport);
+ const int *viewport = m_canvas->GetViewPort();
SetViewPort(viewport);
- switch(m_mode) {
+ switch (m_mode) {
case DOME_FISHEYE:
if (m_angle <= 180) {
cubetop.resize(1);
@@ -178,7 +177,7 @@ KX_Dome::~KX_Dome (void)
glDeleteLists(dlistId, (GLsizei) m_numimages);
}
-void KX_Dome::SetViewPort(GLuint viewport[4])
+void KX_Dome::SetViewPort(const int viewport[4])
{
if (canvaswidth != m_viewport.GetWidth() || canvasheight != m_viewport.GetHeight())
{
@@ -592,7 +591,7 @@ void KX_Dome::CreateMeshDome180(void)
cubebottom[0].u[2] = 0.0;
cubebottom[0].v[2] = 0.0;
- nfacesbottom = 1;
+ nfacesbottom = 1;
/* Left face - two triangles */
@@ -682,12 +681,12 @@ void KX_Dome::CreateMeshDome180(void)
cubetop.resize(4*nfacestop);
SplitFace(cubetop,&nfacestop);
cubebottom.resize(4*nfacesbottom);
- SplitFace(cubebottom,&nfacesbottom);
+ SplitFace(cubebottom,&nfacesbottom);
cubeleft.resize(4*nfacesleft);
SplitFace(cubeleft,&nfacesleft);
cuberight.resize(4*nfacesright);
SplitFace(cuberight,&nfacesright);
- }
+ }
// Turn into a hemisphere
for (j=0;j<3;j++) {
@@ -763,13 +762,13 @@ void KX_Dome::CreateMeshDome250(void)
cubefront[0].verts[1][0] = 1.0;
cubefront[0].verts[1][1] = 1.0;
- cubefront[0].verts[1][2] = 1.0;
+ cubefront[0].verts[1][2] = 1.0;
cubefront[0].u[1] = uv_ratio;
cubefront[0].v[1] = uv_ratio;
cubefront[0].verts[2][0] =-1.0;
cubefront[0].verts[2][1] = 1.0;
- cubefront[0].verts[2][2] = 1.0;
+ cubefront[0].verts[2][2] = 1.0;
cubefront[0].u[2] = 0.0;
cubefront[0].v[2] = uv_ratio;
@@ -782,13 +781,13 @@ void KX_Dome::CreateMeshDome250(void)
cubefront[1].verts[1][0] =-1.0;
cubefront[1].verts[1][1] = 1.0;
- cubefront[1].verts[1][2] =-1.0;
+ cubefront[1].verts[1][2] =-1.0;
cubefront[1].u[1] = 0.0;
cubefront[1].v[1] = 0.0;
cubefront[1].verts[2][0] = 1.0;
cubefront[1].verts[2][1] = 1.0;
- cubefront[1].verts[2][2] =-1.0;
+ cubefront[1].verts[2][2] =-1.0;
cubefront[1].u[2] = uv_ratio;
cubefront[1].v[2] = 0.0;
@@ -803,13 +802,13 @@ void KX_Dome::CreateMeshDome250(void)
cubeleft[0].verts[1][0] =-1.0;
cubeleft[0].verts[1][1] =-verts_height;
- cubeleft[0].verts[1][2] = 1.0;
+ cubeleft[0].verts[1][2] = 1.0;
cubeleft[0].u[1] = uv_base;
cubeleft[0].v[1] = uv_ratio;
cubeleft[0].verts[2][0] =-1.0;
cubeleft[0].verts[2][1] =-verts_height;
- cubeleft[0].verts[2][2] =-1.0;
+ cubeleft[0].verts[2][2] =-1.0;
cubeleft[0].u[2] = uv_base;
cubeleft[0].v[2] = 0.0;
@@ -822,13 +821,13 @@ void KX_Dome::CreateMeshDome250(void)
cubeleft[1].verts[1][0] =-1.0;
cubeleft[1].verts[1][1] = 1.0;
- cubeleft[1].verts[1][2] =-1.0;
+ cubeleft[1].verts[1][2] =-1.0;
cubeleft[1].u[1] = uv_ratio;
cubeleft[1].v[1] = 0.0;
cubeleft[1].verts[2][0] =-1.0;
cubeleft[1].verts[2][1] = 1.0;
- cubeleft[1].verts[2][2] = 1.0;
+ cubeleft[1].verts[2][2] = 1.0;
cubeleft[1].u[2] = uv_ratio;
cubeleft[1].v[2] = uv_ratio;
@@ -843,13 +842,13 @@ void KX_Dome::CreateMeshDome250(void)
cuberight[0].verts[1][0] = 1.0;
cuberight[0].verts[1][1] =-verts_height;
- cuberight[0].verts[1][2] =-1.0;
+ cuberight[0].verts[1][2] =-1.0;
cuberight[0].u[1] = uv_height;
cuberight[0].v[1] = 0.0;
cuberight[0].verts[2][0] = 1.0;
cuberight[0].verts[2][1] =-verts_height;
- cuberight[0].verts[2][2] = 1.0;
+ cuberight[0].verts[2][2] = 1.0;
cuberight[0].u[2] = uv_height;
cuberight[0].v[2] = uv_ratio;
@@ -862,13 +861,13 @@ void KX_Dome::CreateMeshDome250(void)
cuberight[1].verts[1][0] = 1.0;
cuberight[1].verts[1][1] = 1.0;
- cuberight[1].verts[1][2] = 1.0;
+ cuberight[1].verts[1][2] = 1.0;
cuberight[1].u[1] = 0.0;
cuberight[1].v[1] = uv_ratio;
cuberight[1].verts[2][0] = 1.0;
cuberight[1].verts[2][1] = 1.0;
- cuberight[1].verts[2][2] =-1.0;
+ cuberight[1].verts[2][2] =-1.0;
cuberight[1].u[2] = 0.0;
cuberight[1].v[2] = 0.0;
@@ -883,13 +882,13 @@ void KX_Dome::CreateMeshDome250(void)
cubetop[0].verts[1][0] = 1.0;
cubetop[0].verts[1][1] =-verts_height;
- cubetop[0].verts[1][2] = 1.0;
+ cubetop[0].verts[1][2] = 1.0;
cubetop[0].u[1] = uv_ratio;
cubetop[0].v[1] = uv_height;
cubetop[0].verts[2][0] =-1.0;
cubetop[0].verts[2][1] =-verts_height;
- cubetop[0].verts[2][2] = 1.0;
+ cubetop[0].verts[2][2] = 1.0;
cubetop[0].u[2] = 0.0;
cubetop[0].v[2] = uv_height;
@@ -902,13 +901,13 @@ void KX_Dome::CreateMeshDome250(void)
cubetop[1].verts[1][0] =-1.0;
cubetop[1].verts[1][1] = 1.0;
- cubetop[1].verts[1][2] = 1.0;
+ cubetop[1].verts[1][2] = 1.0;
cubetop[1].u[1] = 0.0;
cubetop[1].v[1] = 0.0;
cubetop[1].verts[2][0] = 1.0;
cubetop[1].verts[2][1] = 1.0;
- cubetop[1].verts[2][2] = 1.0;
+ cubetop[1].verts[2][2] = 1.0;
cubetop[1].u[2] = uv_ratio;
cubetop[1].v[2] = 0.0;
@@ -923,13 +922,13 @@ void KX_Dome::CreateMeshDome250(void)
cubebottom[0].verts[1][0] = 1.0;
cubebottom[0].verts[1][1] = 1.0;
- cubebottom[0].verts[1][2] =-1.0;
+ cubebottom[0].verts[1][2] =-1.0;
cubebottom[0].u[1] = uv_ratio;
cubebottom[0].v[1] = uv_ratio;
cubebottom[0].verts[2][0] =-1.0;
cubebottom[0].verts[2][1] = 1.0;
- cubebottom[0].verts[2][2] =-1.0;
+ cubebottom[0].verts[2][2] =-1.0;
cubebottom[0].u[2] = 0.0;
cubebottom[0].v[2] = uv_ratio;
@@ -942,13 +941,13 @@ void KX_Dome::CreateMeshDome250(void)
cubebottom[1].verts[1][0] =-1.0;
cubebottom[1].verts[1][1] =-verts_height;
- cubebottom[1].verts[1][2] =-1.0;
+ cubebottom[1].verts[1][2] =-1.0;
cubebottom[1].u[1] = 0.0;
cubebottom[1].v[1] = uv_base;
cubebottom[1].verts[2][0] = 1.0;
cubebottom[1].verts[2][1] =-verts_height;
- cubebottom[1].verts[2][2] =-1.0;
+ cubebottom[1].verts[2][2] =-1.0;
cubebottom[1].u[2] = uv_ratio;
cubebottom[1].v[2] = uv_base;
@@ -963,7 +962,7 @@ void KX_Dome::CreateMeshDome250(void)
cubetop.resize(4*nfacestop);
SplitFace(cubetop,&nfacestop);
cubebottom.resize(4*nfacesbottom);
- SplitFace(cubebottom,&nfacesbottom);
+ SplitFace(cubebottom,&nfacesbottom);
cubeleft.resize(4*nfacesleft);
SplitFace(cubeleft,&nfacesleft);
cuberight.resize(4*nfacesright);
@@ -986,13 +985,13 @@ void KX_Dome::CreateMeshDome250(void)
//flatten onto xz plane
for (i=0;i<nfacesfront;i++)
- FlattenDome(cubefront[i].verts);
+ FlattenDome(cubefront[i].verts);
for (i=0;i<nfacestop;i++)
FlattenDome(cubetop[i].verts);
for (i=0;i<nfacesbottom;i++)
FlattenDome(cubebottom[i].verts);
for (i=0;i<nfacesleft;i++)
- FlattenDome(cubeleft[i].verts);
+ FlattenDome(cubeleft[i].verts);
for (i=0;i<nfacesright;i++)
FlattenDome(cuberight[i].verts);
}
@@ -1417,7 +1416,7 @@ void KX_Dome::SplitFace(vector <DomeFace>& face, int *nfaces)
face[n2+2].u[2] = (face[i].u[2] + face[i].u[0]) /2;
face[n2+2].v[0] = (face[i].v[0] + face[i].v[1]) /2;
face[n2+2].v[1] = (face[i].v[1] + face[i].v[2]) /2;
- face[n2+2].v[2] = (face[i].v[2] + face[i].v[0]) /2;
+ face[n2+2].v[2] = (face[i].v[2] + face[i].v[0]) /2;
//face[i].verts[0] = face[i].verts[0];
face[i].verts[1] = (face[i].verts[0] + face[i].verts[1]) /2;
@@ -1427,7 +1426,7 @@ void KX_Dome::SplitFace(vector <DomeFace>& face, int *nfaces)
face[i].u[2] = (face[i].u[0] + face[i].u[2]) /2;
//face[i].v[0] = face[i].v[0];
face[i].v[1] = (face[i].v[0] + face[i].v[1]) /2;
- face[i].v[2] = (face[i].v[0] + face[i].v[2]) /2;
+ face[i].v[2] = (face[i].v[0] + face[i].v[2]) /2;
n2 += 3; // number of faces
}
@@ -1621,7 +1620,7 @@ void KX_Dome::Draw(void)
glScissor(0,0,warp.imagesize, warp.imagesize);
}
- switch(m_mode) {
+ switch (m_mode) {
case DOME_FISHEYE:
DrawDomeFisheye();
break;
@@ -1858,7 +1857,7 @@ void KX_Dome::DrawDomeFisheye(void)
glBindTexture(GL_TEXTURE_2D, domefacesId[0]);
GLDrawTriangles(cubetop, nfacestop);
- // bottom triangle
+ // bottom triangle
glBindTexture(GL_TEXTURE_2D, domefacesId[1]);
GLDrawTriangles(cubebottom, nfacesbottom);
diff --git a/source/gameengine/Ketsji/KX_Dome.h b/source/gameengine/Ketsji/KX_Dome.h
index 24177af5d60..17eec3a5fcb 100644
--- a/source/gameengine/Ketsji/KX_Dome.h
+++ b/source/gameengine/Ketsji/KX_Dome.h
@@ -119,7 +119,7 @@ public:
void RenderDomeFrame(KX_Scene* scene, KX_Camera* cam, int i);
void BindImages(int i);
- void SetViewPort(GLuint viewport[4]);
+ void SetViewPort(const int viewport[4]);
void CalculateFrustum(KX_Camera* cam);
void RotateCamera(KX_Camera* cam, int i);
diff --git a/source/gameengine/Ketsji/KX_EmptyObject.h b/source/gameengine/Ketsji/KX_EmptyObject.h
index b99f44c38c5..63a0782a544 100644
--- a/source/gameengine/Ketsji/KX_EmptyObject.h
+++ b/source/gameengine/Ketsji/KX_EmptyObject.h
@@ -47,5 +47,4 @@ public:
#endif
};
-#endif //__KX_EMPTYOBJECT_H__
-
+#endif /* __KX_EMPTYOBJECT_H__ */
diff --git a/source/gameengine/Ketsji/KX_FontObject.cpp b/source/gameengine/Ketsji/KX_FontObject.cpp
index 931eac7a974..138124f9b1a 100644
--- a/source/gameengine/Ketsji/KX_FontObject.cpp
+++ b/source/gameengine/Ketsji/KX_FontObject.cpp
@@ -52,7 +52,7 @@ extern "C" {
/* proptotype */
int GetFontId(VFont *font);
-std::vector<STR_String> split_string(STR_String str)
+static std::vector<STR_String> split_string(STR_String str)
{
std::vector<STR_String> text = std::vector<STR_String>();
@@ -73,10 +73,10 @@ std::vector<STR_String> split_string(STR_String str)
return text;
}
-KX_FontObject::KX_FontObject( void* sgReplicationInfo,
- SG_Callbacks callbacks,
- RAS_IRenderTools* rendertools,
- Object *ob):
+KX_FontObject::KX_FontObject(void* sgReplicationInfo,
+ SG_Callbacks callbacks,
+ RAS_IRenderTools* rendertools,
+ Object *ob):
KX_GameObject(sgReplicationInfo, callbacks),
m_object(ob),
m_dpi(72),
@@ -252,9 +252,9 @@ PyAttributeDef KX_FontObject::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_FontObject::pyattr_get_text(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_FontObject::pyattr_get_text(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_FontObject* self= static_cast<KX_FontObject*>(self_v);
+ KX_FontObject* self = static_cast<KX_FontObject*>(self_v);
STR_String str = STR_String();
for (int i=0; i<self->m_text.size(); ++i)
{
@@ -267,7 +267,7 @@ PyObject* KX_FontObject::pyattr_get_text(void *self_v, const KX_PYATTRIBUTE_DEF
int KX_FontObject::pyattr_set_text(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_FontObject* self= static_cast<KX_FontObject*>(self_v);
+ KX_FontObject* self = static_cast<KX_FontObject*>(self_v);
if (!PyUnicode_Check(value))
return PY_SET_ATTR_FAIL;
char* chars = _PyUnicode_AsString(value);
diff --git a/source/gameengine/Ketsji/KX_FontObject.h b/source/gameengine/Ketsji/KX_FontObject.h
index ae8b4166238..ac22de6fb6f 100644
--- a/source/gameengine/Ketsji/KX_FontObject.h
+++ b/source/gameengine/Ketsji/KX_FontObject.h
@@ -76,4 +76,4 @@ protected:
};
-#endif //__KX_FONTOBJECT_H__
+#endif /* __KX_FONTOBJECT_H__ */
diff --git a/source/gameengine/Ketsji/KX_GameObject.cpp b/source/gameengine/Ketsji/KX_GameObject.cpp
index 3818cef7d6e..a669f4346ea 100644
--- a/source/gameengine/Ketsji/KX_GameObject.cpp
+++ b/source/gameengine/Ketsji/KX_GameObject.cpp
@@ -30,6 +30,11 @@
* \ingroup ketsji
*/
+#ifdef _MSC_VER
+ /* This warning tells us about truncation of __long__ stl-generated names.
+ * It can occasionally cause DevStudio to have internal compiler warnings. */
+# pragma warning( disable:4786 )
+#endif
#if defined(_WIN64) && !defined(FREE_WINDOWS64)
typedef unsigned __int64 uint_ptr;
@@ -37,13 +42,6 @@ typedef unsigned __int64 uint_ptr;
typedef unsigned long uint_ptr;
#endif
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// This warning tells us about truncation of __long__ stl-generated names.
-// It can occasionally cause DevStudio to have internal compiler warnings.
-#pragma warning( disable : 4786 )
-#endif
-
-
#define KX_INERTIA_INFINITE 10000
#include "RAS_IPolygonMaterial.h"
#include "KX_BlenderMaterial.h"
@@ -109,6 +107,8 @@ KX_GameObject::KX_GameObject(
m_xray(false),
m_pHitObject(NULL),
m_pObstacleSimulation(NULL),
+ m_pInstanceObjects(NULL),
+ m_pDupliGroupObject(NULL),
m_actionManager(NULL),
m_isDeformable(false)
#ifdef WITH_PYTHON
@@ -168,6 +168,16 @@ KX_GameObject::~KX_GameObject()
KX_GetActiveScene()->RemoveAnimatedObject(this);
delete m_actionManager;
}
+
+ if (m_pDupliGroupObject)
+ {
+ m_pDupliGroupObject->Release();
+ }
+
+ if (m_pInstanceObjects)
+ {
+ m_pInstanceObjects->Release();
+ }
#ifdef WITH_PYTHON
if (m_attr_dict) {
PyDict_Clear(m_attr_dict); /* in case of circular refs or other weird cases */
@@ -218,17 +228,57 @@ STR_String& KX_GameObject::GetName()
}
-
+/* Set the name of the value */
void KX_GameObject::SetName(const char *name)
{
m_name = name;
-}; // Set the name of the value
+}
KX_IPhysicsController* KX_GameObject::GetPhysicsController()
{
return m_pPhysicsController1;
}
+KX_GameObject* KX_GameObject::GetDupliGroupObject()
+{
+ return m_pDupliGroupObject;
+}
+
+CListValue* KX_GameObject::GetInstanceObjects()
+{
+ return m_pInstanceObjects;
+}
+
+void KX_GameObject::AddInstanceObjects(KX_GameObject* obj)
+{
+ if (!m_pInstanceObjects)
+ m_pInstanceObjects = new CListValue();
+
+ obj->AddRef();
+ m_pInstanceObjects->Add(obj);
+}
+
+void KX_GameObject::RemoveInstanceObject(KX_GameObject* obj)
+{
+ assert(m_pInstanceObjects);
+ m_pInstanceObjects->RemoveValue(obj);
+ obj->Release();
+}
+
+void KX_GameObject::RemoveDupliGroupObject()
+{
+ if (m_pDupliGroupObject) {
+ m_pDupliGroupObject->Release();
+ m_pDupliGroupObject = NULL;
+ }
+}
+
+void KX_GameObject::SetDupliGroupObject(KX_GameObject* obj)
+{
+ obj->AddRef();
+ m_pDupliGroupObject = obj;
+}
+
KX_GameObject* KX_GameObject::GetParent()
{
KX_GameObject* result = NULL;
@@ -362,7 +412,7 @@ BL_ActionManager* KX_GameObject::GetActionManager()
{
// We only want to create an action manager if we need it
if (!m_actionManager)
- {
+ {
KX_GetActiveScene()->AddAnimatedObject(this);
m_actionManager = new BL_ActionManager(this);
}
@@ -481,6 +531,19 @@ void KX_GameObject::ActivateGraphicController(bool recurse)
}
}
+void KX_GameObject::SetUserCollisionGroup(short group)
+{
+ m_userCollisionGroup = group;
+}
+void KX_GameObject::SetUserCollisionMask(short mask)
+{
+ m_userCollisionMask = mask;
+}
+
+bool KX_GameObject::CheckCollision(KX_GameObject* other)
+{
+ return this->m_userCollisionGroup & other->m_userCollisionMask;
+}
CValue* KX_GameObject::GetReplica()
{
@@ -690,7 +753,7 @@ void KX_GameObject::SynchronizeTransformFunc(SG_IObject* node, void* gameobj, vo
void KX_GameObject::SetDebugColor(unsigned int bgra)
{
for (size_t i=0;i<m_meshes.size();i++)
- m_meshes[i]->DebugColor(bgra);
+ m_meshes[i]->DebugColor(bgra);
}
@@ -701,8 +764,8 @@ void KX_GameObject::ResetDebugColor()
}
void KX_GameObject::InitIPO(bool ipo_as_force,
- bool ipo_add,
- bool ipo_local)
+ bool ipo_add,
+ bool ipo_local)
{
SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
@@ -939,7 +1002,7 @@ void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
vect /= len;
orimat = GetSGNode()->GetWorldOrientation();
switch (axis)
- {
+ {
case 0: //x axis
ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); //pivot axis
if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON) //is the vector parallel to the pivot?
@@ -1041,7 +1104,7 @@ MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
return locvel;
}
}
- return velocity;
+ return velocity;
}
MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
@@ -1060,7 +1123,7 @@ MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
return locvel;
}
}
- return velocity;
+ return velocity;
}
MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
@@ -1377,8 +1440,8 @@ static unsigned char mathutils_kxgameob_vector_cb_index= -1; /* index for our ca
static int mathutils_kxgameob_generic_check(BaseMathObject *bmo)
{
- KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
- if (self==NULL)
+ KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
+ if (self == NULL)
return -1;
return 0;
@@ -1386,13 +1449,13 @@ static int mathutils_kxgameob_generic_check(BaseMathObject *bmo)
static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype)
{
- KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
- if (self==NULL)
+ KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
+ if (self == NULL)
return -1;
#define PHYS_ERR(attr) PyErr_SetString(PyExc_AttributeError, "KX_GameObject." attr ", is missing a physics controller")
- switch(subtype) {
+ switch (subtype) {
case MATHUTILS_VEC_CB_POS_LOCAL:
self->NodeGetLocalPosition().getValue(bmo->data);
break;
@@ -1438,11 +1501,11 @@ static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype)
static int mathutils_kxgameob_vector_set(BaseMathObject *bmo, int subtype)
{
- KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
- if (self==NULL)
+ KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
+ if (self == NULL)
return -1;
- switch(subtype) {
+ switch (subtype) {
case MATHUTILS_VEC_CB_POS_LOCAL:
self->NodeSetLocalPosition(MT_Point3(bmo->data));
self->NodeUpdateGS(0.f);
@@ -1497,7 +1560,7 @@ static int mathutils_kxgameob_vector_set_index(BaseMathObject *bmo, int subtype,
if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
return -1;
- bmo->data[index]= f;
+ bmo->data[index] = f;
return mathutils_kxgameob_vector_set(bmo, subtype);
}
@@ -1517,11 +1580,11 @@ static unsigned char mathutils_kxgameob_matrix_cb_index= -1; /* index for our ca
static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype)
{
- KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
- if (self==NULL)
+ KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
+ if (self == NULL)
return -1;
- switch(subtype) {
+ switch (subtype) {
case MATHUTILS_MAT_CB_ORI_LOCAL:
self->NodeGetLocalOrientation().getValue3x3(bmo->data);
break;
@@ -1536,12 +1599,12 @@ static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype)
static int mathutils_kxgameob_matrix_set(BaseMathObject *bmo, int subtype)
{
- KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
- if (self==NULL)
+ KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
+ if (self == NULL)
return -1;
MT_Matrix3x3 mat3x3;
- switch(subtype) {
+ switch (subtype) {
case MATHUTILS_MAT_CB_ORI_LOCAL:
mat3x3.setValue3x3(bmo->data);
self->NodeSetLocalOrientation(mat3x3);
@@ -1629,6 +1692,9 @@ PyMethodDef KX_GameObject::Methods[] = {
PyAttributeDef KX_GameObject::Attributes[] = {
KX_PYATTRIBUTE_RO_FUNCTION("name", KX_GameObject, pyattr_get_name),
KX_PYATTRIBUTE_RO_FUNCTION("parent", KX_GameObject, pyattr_get_parent),
+ KX_PYATTRIBUTE_RO_FUNCTION("group_children", KX_GameObject, pyattr_get_group_children),
+ KX_PYATTRIBUTE_RO_FUNCTION("group_parent", KX_GameObject, pyattr_get_group_parent),
+ KX_PYATTRIBUTE_RO_FUNCTION("scene", KX_GameObject, pyattr_get_scene),
KX_PYATTRIBUTE_RO_FUNCTION("life", KX_GameObject, pyattr_get_life),
KX_PYATTRIBUTE_RW_FUNCTION("mass", KX_GameObject, pyattr_get_mass, pyattr_set_mass),
KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMin", KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min),
@@ -1668,7 +1734,7 @@ PyAttributeDef KX_GameObject::Attributes[] = {
{NULL} //Sentinel
};
-PyObject* KX_GameObject::PyReplaceMesh(PyObject* args)
+PyObject *KX_GameObject::PyReplaceMesh(PyObject *args)
{
KX_Scene *scene = KX_GetActiveScene();
@@ -1686,7 +1752,7 @@ PyObject* KX_GameObject::PyReplaceMesh(PyObject* args)
Py_RETURN_NONE;
}
-PyObject* KX_GameObject::PyEndObject()
+PyObject *KX_GameObject::PyEndObject()
{
SG_Node* node = this->GetSGNode();
KX_Scene* scene = static_cast<KX_Scene*>(node->GetSGClientInfo());
@@ -1697,7 +1763,7 @@ PyObject* KX_GameObject::PyEndObject()
}
-PyObject* KX_GameObject::PyReinstancePhysicsMesh(PyObject* args)
+PyObject *KX_GameObject::PyReinstancePhysicsMesh(PyObject *args)
{
KX_GameObject *gameobj= NULL;
RAS_MeshObject *mesh= NULL;
@@ -1721,19 +1787,19 @@ PyObject* KX_GameObject::PyReinstancePhysicsMesh(PyObject* args)
static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
{
- KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
const char *attr_str= _PyUnicode_AsString(item);
CValue* resultattr;
- PyObject* pyconvert;
+ PyObject *pyconvert;
- if (self==NULL) {
+ if (self == NULL) {
PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, "BGE_PROXY_ERROR_MSG);
return NULL;
}
/* first see if the attributes a string and try get the cvalue attribute */
if (attr_str && (resultattr=self->GetProperty(attr_str))) {
- pyconvert = resultattr->ConvertValueToPython();
+ pyconvert = resultattr->ConvertValueToPython();
return pyconvert ? pyconvert:resultattr->GetProxy();
}
/* no CValue attribute, try get the python only m_attr_dict attribute */
@@ -1755,12 +1821,12 @@ static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
{
- KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
const char *attr_str= _PyUnicode_AsString(key);
if (attr_str==NULL)
PyErr_Clear();
- if (self==NULL) {
+ if (self == NULL) {
PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, "BGE_PROXY_ERROR_MSG);
return -1;
}
@@ -1843,9 +1909,9 @@ static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
static int Seq_Contains(PyObject *self_v, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
- if (self==NULL) {
+ if (self == NULL) {
PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, "BGE_PROXY_ERROR_MSG);
return -1;
}
@@ -1907,15 +1973,15 @@ PyTypeObject KX_GameObject::Type = {
py_base_new
};
-PyObject* KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyUnicode_From_STR_String(self->GetName());
}
-PyObject* KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
KX_GameObject* parent = self->GetParent();
if (parent) {
parent->Release(); /* self->GetParent() AddRef's */
@@ -1924,9 +1990,40 @@ PyObject* KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DE
Py_RETURN_NONE;
}
-PyObject* KX_GameObject::pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_group_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+{
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
+ CListValue* instances = self->GetInstanceObjects();
+ if (instances) {
+ return instances->GetProxy();
+ }
+ Py_RETURN_NONE;
+}
+
+PyObject* KX_GameObject::pyattr_get_scene(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+{
+ KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
+ SG_Node *node = self->GetSGNode();
+ KX_Scene *scene = static_cast<KX_Scene *>(node->GetSGClientInfo());
+ if (scene) {
+ return scene->GetProxy();
+ }
+ Py_RETURN_NONE;
+}
+
+PyObject *KX_GameObject::pyattr_get_group_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* pivot = self->GetDupliGroupObject();
+ if (pivot) {
+ return pivot->GetProxy();
+ }
+ Py_RETURN_NONE;
+}
+
+PyObject *KX_GameObject::pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+{
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
CValue *life = self->GetProperty("::timebomb");
if (life)
@@ -1937,16 +2034,16 @@ PyObject* KX_GameObject::pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF
Py_RETURN_NONE;
}
-PyObject* KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
KX_IPhysicsController *spc = self->GetPhysicsController();
return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0);
}
int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
KX_IPhysicsController *spc = self->GetPhysicsController();
MT_Scalar val = PyFloat_AsDouble(value);
if (val < 0.0) { /* also accounts for non float */
@@ -1960,16 +2057,16 @@ int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrd
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
KX_IPhysicsController *spc = self->GetPhysicsController();
return PyFloat_FromDouble(spc ? spc->GetLinVelocityMin() : 0.0f);
}
int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
KX_IPhysicsController *spc = self->GetPhysicsController();
MT_Scalar val = PyFloat_AsDouble(value);
if (val < 0.0) { /* also accounts for non float */
@@ -1983,16 +2080,16 @@ int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
KX_IPhysicsController *spc = self->GetPhysicsController();
return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
}
int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
KX_IPhysicsController *spc = self->GetPhysicsController();
MT_Scalar val = PyFloat_AsDouble(value);
if (val < 0.0) { /* also accounts for non float */
@@ -2007,15 +2104,15 @@ int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF
}
-PyObject* KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyBool_FromLong(self->GetVisible());
}
int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
int param = PyObject_IsTrue( value );
if (param == -1) {
PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
@@ -2027,19 +2124,19 @@ int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *at
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
#ifdef USE_MATHUTILS
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL);
#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyObjectFrom(self->NodeGetWorldPosition());
#endif
}
int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
MT_Point3 pos;
if (!PyVecTo(value, pos))
return PY_SET_ATTR_FAIL;
@@ -2049,19 +2146,19 @@ int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_D
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
-#ifdef USE_MATHUTILS
+#ifdef USE_MATHUTILS
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL);
-#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+#else
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyObjectFrom(self->NodeGetLocalPosition());
#endif
}
int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
MT_Point3 pos;
if (!PyVecTo(value, pos))
return PY_SET_ATTR_FAIL;
@@ -2071,31 +2168,31 @@ int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_D
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
#ifdef USE_MATHUTILS
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL);
#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
if (self->GetPhysicsController())
return PyObjectFrom(self->GetPhysicsController()->GetLocalInertia());
return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
#endif
}
-PyObject* KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
#ifdef USE_MATHUTILS
return Matrix_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL);
#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyObjectFrom(self->NodeGetWorldOrientation());
#endif
}
int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
/* if value is not a sequence PyOrientationTo makes an error */
MT_Matrix3x3 rot;
@@ -2108,19 +2205,19 @@ int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUT
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
#ifdef USE_MATHUTILS
return Matrix_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL);
#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyObjectFrom(self->NodeGetLocalOrientation());
#endif
}
int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
/* if value is not a sequence PyOrientationTo makes an error */
MT_Matrix3x3 rot;
@@ -2132,19 +2229,19 @@ int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUT
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
#ifdef USE_MATHUTILS
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL);
#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyObjectFrom(self->NodeGetWorldScaling());
#endif
}
int KX_GameObject::pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
MT_Vector3 scale;
if (!PyVecTo(value, scale))
return PY_SET_ATTR_FAIL;
@@ -2154,19 +2251,19 @@ int KX_GameObject::pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DE
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
#ifdef USE_MATHUTILS
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL);
#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyObjectFrom(self->NodeGetLocalScaling());
#endif
}
int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
MT_Vector3 scale;
if (!PyVecTo(value, scale))
return PY_SET_ATTR_FAIL;
@@ -2176,7 +2273,7 @@ int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DE
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
@@ -2222,7 +2319,7 @@ int KX_GameObject::pyattr_set_localTransform(void *self_v, const KX_PYATTRIBUTE_
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
@@ -2256,19 +2353,19 @@ int KX_GameObject::pyattr_set_worldTransform(void *self_v, const KX_PYATTRIBUTE_
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
#ifdef USE_MATHUTILS
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_GLOBAL);
#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyObjectFrom(GetLinearVelocity(false));
#endif
}
int KX_GameObject::pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
MT_Vector3 velocity;
if (!PyVecTo(value, velocity))
return PY_SET_ATTR_FAIL;
@@ -2278,19 +2375,19 @@ int KX_GameObject::pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRI
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
#ifdef USE_MATHUTILS
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_LOCAL);
#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyObjectFrom(GetLinearVelocity(true));
#endif
}
int KX_GameObject::pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
MT_Vector3 velocity;
if (!PyVecTo(value, velocity))
return PY_SET_ATTR_FAIL;
@@ -2300,19 +2397,19 @@ int KX_GameObject::pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRI
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
#ifdef USE_MATHUTILS
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_GLOBAL);
#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyObjectFrom(GetAngularVelocity(false));
#endif
}
int KX_GameObject::pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
MT_Vector3 velocity;
if (!PyVecTo(value, velocity))
return PY_SET_ATTR_FAIL;
@@ -2322,19 +2419,19 @@ int KX_GameObject::pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTR
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
#ifdef USE_MATHUTILS
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_LOCAL);
#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyObjectFrom(GetAngularVelocity(true));
#endif
}
int KX_GameObject::pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
MT_Vector3 velocity;
if (!PyVecTo(value, velocity))
return PY_SET_ATTR_FAIL;
@@ -2345,9 +2442,9 @@ int KX_GameObject::pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTR
}
-PyObject* KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
SG_Node* sg_parent;
if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) {
return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
@@ -2358,7 +2455,7 @@ PyObject* KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUT
int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
if (self->GetSGNode()) {
MT_Scalar val = PyFloat_AsDouble(value);
SG_Node *sg_parent= self->GetSGNode()->GetSGParent();
@@ -2372,9 +2469,9 @@ int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
int state = 0;
state |= self->GetState();
return PyLong_FromSsize_t(state);
@@ -2382,7 +2479,7 @@ PyObject* KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF
int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
int state_i = PyLong_AsSsize_t(value);
unsigned int state = 0;
@@ -2400,9 +2497,9 @@ int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attr
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
PyObject *meshes= PyList_New(self->m_meshes.size());
int i;
@@ -2415,19 +2512,19 @@ PyObject* KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DE
return meshes;
}
-PyObject* KX_GameObject::pyattr_get_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
#ifdef USE_MATHUTILS
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 4, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_OBJECT_COLOR);
#else
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return PyObjectFrom(self->GetObjectColor());
#endif
}
int KX_GameObject::pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
MT_Vector4 obcolor;
if (!PyVecTo(value, obcolor))
return PY_SET_ATTR_FAIL;
@@ -2437,37 +2534,37 @@ int KX_GameObject::pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *at
}
/* These are experimental! */
-PyObject* KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_SENSORS);
}
-PyObject* KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_CONTROLLERS);
}
-PyObject* KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_ACTUATORS);
}
/* End experimental */
-PyObject* KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return self->GetChildren()->NewProxy(true);
}
-PyObject* KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
return self->GetChildrenRecursive()->NewProxy(true);
}
-PyObject* KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
+ KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
if (self->m_attr_dict==NULL)
self->m_attr_dict= PyDict_New();
@@ -2476,10 +2573,10 @@ PyObject* KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_
return self->m_attr_dict;
}
-PyObject* KX_GameObject::PyApplyForce(PyObject* args)
+PyObject *KX_GameObject::PyApplyForce(PyObject *args)
{
int local = 0;
- PyObject* pyvect;
+ PyObject *pyvect;
if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
MT_Vector3 force;
@@ -2491,10 +2588,10 @@ PyObject* KX_GameObject::PyApplyForce(PyObject* args)
return NULL;
}
-PyObject* KX_GameObject::PyApplyTorque(PyObject* args)
+PyObject *KX_GameObject::PyApplyTorque(PyObject *args)
{
int local = 0;
- PyObject* pyvect;
+ PyObject *pyvect;
if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
MT_Vector3 torque;
@@ -2506,10 +2603,10 @@ PyObject* KX_GameObject::PyApplyTorque(PyObject* args)
return NULL;
}
-PyObject* KX_GameObject::PyApplyRotation(PyObject* args)
+PyObject *KX_GameObject::PyApplyRotation(PyObject *args)
{
int local = 0;
- PyObject* pyvect;
+ PyObject *pyvect;
if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
MT_Vector3 rotation;
@@ -2521,10 +2618,10 @@ PyObject* KX_GameObject::PyApplyRotation(PyObject* args)
return NULL;
}
-PyObject* KX_GameObject::PyApplyMovement(PyObject* args)
+PyObject *KX_GameObject::PyApplyMovement(PyObject *args)
{
int local = 0;
- PyObject* pyvect;
+ PyObject *pyvect;
if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
MT_Vector3 movement;
@@ -2536,7 +2633,7 @@ PyObject* KX_GameObject::PyApplyMovement(PyObject* args)
return NULL;
}
-PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* args)
+PyObject *KX_GameObject::PyGetLinearVelocity(PyObject *args)
{
// only can get the velocity if we have a physics object connected to us...
int local = 0;
@@ -2550,10 +2647,10 @@ PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* args)
}
}
-PyObject* KX_GameObject::PySetLinearVelocity(PyObject* args)
+PyObject *KX_GameObject::PySetLinearVelocity(PyObject *args)
{
int local = 0;
- PyObject* pyvect;
+ PyObject *pyvect;
if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
MT_Vector3 velocity;
@@ -2565,7 +2662,7 @@ PyObject* KX_GameObject::PySetLinearVelocity(PyObject* args)
return NULL;
}
-PyObject* KX_GameObject::PyGetAngularVelocity(PyObject* args)
+PyObject *KX_GameObject::PyGetAngularVelocity(PyObject *args)
{
// only can get the velocity if we have a physics object connected to us...
int local = 0;
@@ -2579,10 +2676,10 @@ PyObject* KX_GameObject::PyGetAngularVelocity(PyObject* args)
}
}
-PyObject* KX_GameObject::PySetAngularVelocity(PyObject* args)
+PyObject *KX_GameObject::PySetAngularVelocity(PyObject *args)
{
int local = 0;
- PyObject* pyvect;
+ PyObject *pyvect;
if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
MT_Vector3 velocity;
@@ -2594,7 +2691,7 @@ PyObject* KX_GameObject::PySetAngularVelocity(PyObject* args)
return NULL;
}
-PyObject* KX_GameObject::PySetVisible(PyObject* args)
+PyObject *KX_GameObject::PySetVisible(PyObject *args)
{
int visible, recursive = 0;
if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
@@ -2606,7 +2703,7 @@ PyObject* KX_GameObject::PySetVisible(PyObject* args)
}
-PyObject* KX_GameObject::PySetOcclusion(PyObject* args)
+PyObject *KX_GameObject::PySetOcclusion(PyObject *args)
{
int occlusion, recursive = 0;
if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive))
@@ -2616,11 +2713,11 @@ PyObject* KX_GameObject::PySetOcclusion(PyObject* args)
Py_RETURN_NONE;
}
-PyObject* KX_GameObject::PyGetVelocity(PyObject* args)
+PyObject *KX_GameObject::PyGetVelocity(PyObject *args)
{
// only can get the velocity if we have a physics object connected to us...
MT_Point3 point(0.0,0.0,0.0);
- PyObject* pypos = NULL;
+ PyObject *pypos = NULL;
if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point)))
return NULL;
@@ -2634,7 +2731,7 @@ PyObject* KX_GameObject::PyGetVelocity(PyObject* args)
}
}
-PyObject* KX_GameObject::PyGetReactionForce()
+PyObject *KX_GameObject::PyGetReactionForce()
{
// only can get the velocity if we have a physics object connected to us...
@@ -2651,7 +2748,7 @@ PyObject* KX_GameObject::PyGetReactionForce()
-PyObject* KX_GameObject::PyEnableRigidBody()
+PyObject *KX_GameObject::PyEnableRigidBody()
{
if (GetPhysicsController())
GetPhysicsController()->setRigidBody(true);
@@ -2661,7 +2758,7 @@ PyObject* KX_GameObject::PyEnableRigidBody()
-PyObject* KX_GameObject::PyDisableRigidBody()
+PyObject *KX_GameObject::PyDisableRigidBody()
{
if (GetPhysicsController())
GetPhysicsController()->setRigidBody(false);
@@ -2670,10 +2767,10 @@ PyObject* KX_GameObject::PyDisableRigidBody()
}
-PyObject* KX_GameObject::PySetParent(PyObject* args)
+PyObject *KX_GameObject::PySetParent(PyObject *args)
{
KX_Scene *scene = KX_GetActiveScene();
- PyObject* pyobj;
+ PyObject *pyobj;
KX_GameObject *obj;
int addToCompound=1, ghost=1;
@@ -2687,7 +2784,7 @@ PyObject* KX_GameObject::PySetParent(PyObject* args)
Py_RETURN_NONE;
}
-PyObject* KX_GameObject::PyRemoveParent()
+PyObject *KX_GameObject::PyRemoveParent()
{
KX_Scene *scene = KX_GetActiveScene();
@@ -2696,7 +2793,7 @@ PyObject* KX_GameObject::PyRemoveParent()
}
-PyObject* KX_GameObject::PySetCollisionMargin(PyObject* value)
+PyObject *KX_GameObject::PySetCollisionMargin(PyObject *value)
{
float collisionMargin = PyFloat_AsDouble(value);
@@ -2716,10 +2813,10 @@ PyObject* KX_GameObject::PySetCollisionMargin(PyObject* value)
-PyObject* KX_GameObject::PyApplyImpulse(PyObject* args)
+PyObject *KX_GameObject::PyApplyImpulse(PyObject *args)
{
- PyObject* pyattach;
- PyObject* pyimpulse;
+ PyObject *pyattach;
+ PyObject *pyimpulse;
if (!m_pPhysicsController1) {
PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
@@ -2743,7 +2840,7 @@ PyObject* KX_GameObject::PyApplyImpulse(PyObject* args)
-PyObject* KX_GameObject::PySuspendDynamics()
+PyObject *KX_GameObject::PySuspendDynamics()
{
SuspendDynamics();
Py_RETURN_NONE;
@@ -2751,16 +2848,16 @@ PyObject* KX_GameObject::PySuspendDynamics()
-PyObject* KX_GameObject::PyRestoreDynamics()
+PyObject *KX_GameObject::PyRestoreDynamics()
{
RestoreDynamics();
Py_RETURN_NONE;
}
-PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* args)
+PyObject *KX_GameObject::PyAlignAxisToVect(PyObject *args)
{
- PyObject* pyvect;
+ PyObject *pyvect;
int axis = 2; //z axis is the default
float fac = 1.0f;
@@ -2780,7 +2877,7 @@ PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* args)
return NULL;
}
-PyObject* KX_GameObject::PyGetAxisVect(PyObject* value)
+PyObject *KX_GameObject::PyGetAxisVect(PyObject *value)
{
MT_Vector3 vect;
if (PyVecTo(value, vect))
@@ -2791,7 +2888,7 @@ PyObject* KX_GameObject::PyGetAxisVect(PyObject* value)
}
-PyObject* KX_GameObject::PyGetPhysicsId()
+PyObject *KX_GameObject::PyGetPhysicsId()
{
KX_IPhysicsController* ctrl = GetPhysicsController();
uint_ptr physid=0;
@@ -2802,7 +2899,7 @@ PyObject* KX_GameObject::PyGetPhysicsId()
return PyLong_FromSsize_t((long)physid);
}
-PyObject* KX_GameObject::PyGetPropertyNames()
+PyObject *KX_GameObject::PyGetPropertyNames()
{
PyObject *list= ConvertKeysToPython();
@@ -2932,7 +3029,7 @@ KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
" other = 3-tuple or object reference")
{
MT_Point3 toPoint;
- PyObject* pyarg;
+ PyObject *pyarg;
float dist = 0.0f;
char *propName = NULL;
@@ -3050,8 +3147,8 @@ KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
{
MT_Point3 toPoint;
MT_Point3 fromPoint;
- PyObject* pyto;
- PyObject* pyfrom = NULL;
+ PyObject *pyto;
+ PyObject *pyfrom = NULL;
float dist = 0.0f;
char *propName = NULL;
KX_GameObject *other;
@@ -3125,7 +3222,7 @@ KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
if (m_pHitObject)
{
- PyObject* returnValue = (poly==2) ? PyTuple_New(5) : (poly) ? PyTuple_New(4) : PyTuple_New(3);
+ PyObject *returnValue = (poly == 2) ? PyTuple_New(5) : (poly) ? PyTuple_New(4) : PyTuple_New(3);
if (returnValue) { // unlikely this would ever fail, if it does python sets an error
PyTuple_SET_ITEM(returnValue, 0, m_pHitObject->GetProxy());
PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint));
@@ -3301,11 +3398,11 @@ KX_PYMETHODDEF_DOC(KX_GameObject, isPlayingAction,
/* Matches python dict.get(key, [default]) */
-PyObject* KX_GameObject::Pyget(PyObject *args)
+PyObject *KX_GameObject::Pyget(PyObject *args)
{
PyObject *key;
- PyObject* def = Py_None;
- PyObject* ret;
+ PyObject *def = Py_None;
+ PyObject *ret;
if (!PyArg_ParseTuple(args, "O|O:get", &key, &def))
return NULL;
@@ -3331,7 +3428,7 @@ PyObject* KX_GameObject::Pyget(PyObject *args)
return def;
}
-bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok, const char *error_prefix)
+bool ConvertPythonToGameObject(PyObject *value, KX_GameObject **object, bool py_none_ok, const char *error_prefix)
{
if (value==NULL) {
PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
diff --git a/source/gameengine/Ketsji/KX_GameObject.h b/source/gameengine/Ketsji/KX_GameObject.h
index 2b0d13ff2f7..d5ae13eb702 100644
--- a/source/gameengine/Ketsji/KX_GameObject.h
+++ b/source/gameengine/Ketsji/KX_GameObject.h
@@ -33,9 +33,9 @@
#ifndef __KX_GAMEOBJECT_H__
#define __KX_GAMEOBJECT_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// get rid of this stupid "warning 'this' used in initialiser list", generated by VC when including Solid/Sumo
-#pragma warning (disable : 4355)
+#ifdef _MSC_VER
+ /* get rid of this stupid "warning 'this' used in initialiser list", generated by VC when including Solid/Sumo */
+# pragma warning (disable:4355)
#endif
#include <stddef.h>
@@ -68,7 +68,7 @@ struct bAction;
#ifdef WITH_PYTHON
/* utility conversion function */
-bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok, const char *error_prefix);
+bool ConvertPythonToGameObject(PyObject *value, KX_GameObject **object, bool py_none_ok, const char *error_prefix);
#endif
#ifdef USE_MATHUTILS
@@ -98,6 +98,10 @@ protected:
bool m_bIsNegativeScaling;
MT_Vector4 m_objectColor;
+ // Bit fields for user control over physics collisions
+ short m_userCollisionGroup;
+ short m_userCollisionMask;
+
// visible = user setting
// culled = while rendering, depending on camera
bool m_bVisible;
@@ -116,9 +120,11 @@ protected:
KX_ObstacleSimulation* m_pObstacleSimulation;
+ CListValue* m_pInstanceObjects;
+ KX_GameObject* m_pDupliGroupObject;
// The action manager is used to play/stop/update actions
- BL_ActionManager* m_actionManager;
+ BL_ActionManager* m_actionManager;
BL_ActionManager* GetActionManager();
@@ -159,7 +165,7 @@ public:
* side effect of storing the result internally. The
* memory for the matrix remains the property of this class.
*/
- double*
+ double *
GetOpenGLMatrix(
);
@@ -170,7 +176,7 @@ public:
* memory for the returned matrix.
*/
- MT_CmMatrix4x4*
+ MT_CmMatrix4x4 *
GetOpenGLMatrixPtr(
) {
return &m_OpenGL_4x4Matrix;
@@ -193,21 +199,48 @@ public:
* object. It is the responsibility of the caller to decrement
* the reference count when you have finished with it.
*/
- KX_GameObject*
+ KX_GameObject*
GetParent(
);
/**
* Sets the parent of this object to a game object
- */
+ */
void SetParent(KX_Scene *scene, KX_GameObject *obj, bool addToCompound=true, bool ghost=true);
/**
* Removes the parent of this object to a game object
- */
+ */
void RemoveParent(KX_Scene *scene);
/*********************************
+ * group reference API
+ *********************************/
+
+ KX_GameObject*
+ GetDupliGroupObject(
+ );
+
+ CListValue*
+ GetInstanceObjects(
+ );
+
+ void
+ SetDupliGroupObject(KX_GameObject*
+ );
+
+ void
+ AddInstanceObjects(KX_GameObject*
+ );
+
+ void
+ RemoveDupliGroupObject(
+ );
+
+ void
+ RemoveInstanceObject(KX_GameObject*
+ );
+ /*********************************
* Animation API
*********************************/
@@ -292,7 +325,7 @@ public:
/**
* Inherited from CValue -- does nothing!
*/
- CValue*
+ CValue*
Calc(
VALUE_OPERATOR op,
CValue *val
@@ -301,7 +334,7 @@ public:
/**
* Inherited from CValue -- does nothing!
*/
- CValue*
+ CValue*
CalcFinal(
VALUE_DATA_TYPE dtype,
VALUE_OPERATOR op,
@@ -312,7 +345,7 @@ public:
* Inherited from CValue -- does nothing!
*/
const
- STR_String &
+ STR_String &
GetText(
);
@@ -331,14 +364,14 @@ public:
/**
* Inherited from CValue -- returns the name of this object.
*/
- STR_String&
+ STR_String&
GetName(
);
/**
* Inherited from CValue -- set the name of this object.
*/
- void
+ void
SetName(
const char *name
);
@@ -348,7 +381,7 @@ public:
* instance allocated on the heap. Ownership of the new
* object belongs with the caller.
*/
- virtual CValue*
+ virtual CValue*
GetReplica(
);
@@ -356,7 +389,7 @@ public:
* Inherited from CValue -- Makes sure any internal
* data owned by this class is deep copied. Called internally
*/
- virtual void
+ virtual void
ProcessReplica();
/**
@@ -379,7 +412,7 @@ public:
/**
* Return the mass of the object
*/
- MT_Scalar
+ MT_Scalar
GetMass();
/**
@@ -410,7 +443,7 @@ public:
* Quick'n'dirty obcolor ipo stuff
*/
- void
+ void
SetObjectColor(
const MT_Vector4& rgbavec
);
@@ -465,6 +498,13 @@ public:
*/
void ActivateGraphicController(bool recurse);
+ void SetUserCollisionGroup(short filter);
+ void SetUserCollisionMask(short mask);
+ /**
+ * Extra broadphase check for user controllable collisions
+ */
+ bool CheckCollision(KX_GameObject *other);
+
/**
* \section Coordinate system manipulation functions
*/
@@ -482,7 +522,7 @@ public:
// adapt local position so that world position is set to desired position
void NodeSetWorldPosition(const MT_Point3& trans);
- void
+ void
NodeUpdateGS(
double time
);
@@ -504,7 +544,7 @@ public:
return m_pSGNode;
}
- const SG_Node* GetSGNode( ) const
+ const SG_Node* GetSGNode( ) const
{
return m_pSGNode;
}
@@ -581,48 +621,48 @@ public:
* place.
*/
- void
+ void
ApplyForce(
const MT_Vector3& force, bool local
);
- void
+ void
ApplyTorque(
const MT_Vector3& torque,
bool local
);
- void
+ void
ApplyRotation(
const MT_Vector3& drot,
bool local
);
- void
+ void
ApplyMovement(
const MT_Vector3& dloc,
bool local
);
- void
+ void
addLinearVelocity(
const MT_Vector3& lin_vel,
bool local
);
- void
+ void
setLinearVelocity(
const MT_Vector3& lin_vel,
bool local
);
- void
+ void
setAngularVelocity(
const MT_Vector3& ang_vel,
bool local
);
- /**
+ /**
* Update the physics object transform based upon the current SG_Node
* position.
*/
@@ -642,7 +682,7 @@ public:
/**
* Function to set IPO option at start of IPO
*/
- void
+ void
InitIPO(
bool ipo_as_force,
bool ipo_add,
@@ -652,7 +692,7 @@ public:
/**
* Odd function to update an ipo. ???
*/
- void
+ void
UpdateIPO(
float curframetime,
bool recurse
@@ -676,20 +716,20 @@ public:
* \section Mesh accessor functions.
*/
- /**
+ /**
* Update buckets to indicate that there is a new
* user of this object's meshes.
*/
- void
+ void
AddMeshUser(
);
- /**
+ /**
* Update buckets with data about the mesh after
* creating or duplicating the object, changing
* visibility, object color, .. .
*/
- void
+ void
UpdateBuckets(
bool recursive
);
@@ -699,7 +739,7 @@ public:
* and remove from the bucketing system.
* Don't think this actually deletes any of the meshes.
*/
- void
+ void
RemoveMeshes(
);
@@ -709,7 +749,7 @@ public:
* Make sure you call RemoveMeshes() before deleting the
* mesh though,
*/
- void
+ void
AddMesh(
RAS_MeshObject* mesh
) {
@@ -719,7 +759,7 @@ public:
/**
* Pick out a mesh associated with the integer 'num'.
*/
- RAS_MeshObject*
+ RAS_MeshObject*
GetMesh(
int num
) const {
@@ -730,17 +770,17 @@ public:
* Return the number of meshes currently associated with this
* game object.
*/
- int
+ int
GetMeshCount(
) const {
return m_meshes.size();
}
- /**
+ /**
* Set the debug color of the meshes associated with this
* class. Does this still work?
*/
- void
+ void
SetDebugColor(
unsigned int bgra
);
@@ -748,7 +788,7 @@ public:
/**
* Reset the debug color of meshes associated with this class.
*/
- void
+ void
ResetDebugColor(
);
@@ -855,7 +895,7 @@ public:
m_bSuspendDynamics = true;
}
- void RestoreDynamics(void) {
+ void RestoreDynamics(void) {
if (!m_bSuspendDynamics)
{
return;
@@ -887,7 +927,7 @@ public:
/**
* \section Python interface functions.
*/
- virtual PyObject* py_repr(void)
+ virtual PyObject *py_repr(void)
{
return PyUnicode_From_STR_String(GetName());
}
@@ -949,6 +989,10 @@ public:
static PyObject* pyattr_get_name(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static PyObject* pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject* pyattr_get_group_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject* pyattr_get_group_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject* pyattr_get_scene(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+
static PyObject* pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static PyObject* pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
@@ -983,7 +1027,7 @@ public:
static PyObject* pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
static PyObject* pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
+ static int pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
static PyObject* pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
static PyObject* pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
@@ -1008,5 +1052,4 @@ public:
-#endif //__KX_GAMEOBJECT_H__
-
+#endif /* __KX_GAMEOBJECT_H__ */
diff --git a/source/gameengine/Ketsji/KX_IInterpolator.h b/source/gameengine/Ketsji/KX_IInterpolator.h
index 6ca44e1f6e5..6c0bf2d85cc 100644
--- a/source/gameengine/Ketsji/KX_IInterpolator.h
+++ b/source/gameengine/Ketsji/KX_IInterpolator.h
@@ -38,7 +38,7 @@
#include "MEM_guardedalloc.h"
#endif
-class KX_IInterpolator {
+class KX_IInterpolator {
public:
virtual ~KX_IInterpolator() {}
diff --git a/source/gameengine/Ketsji/KX_IPOTransform.h b/source/gameengine/Ketsji/KX_IPOTransform.h
index 43019f3e54a..a68292bf9df 100644
--- a/source/gameengine/Ketsji/KX_IPOTransform.h
+++ b/source/gameengine/Ketsji/KX_IPOTransform.h
@@ -48,8 +48,8 @@ public:
MT_Transform GetTransform() const {
return MT_Transform(m_position + m_deltaPosition,
- MT_Matrix3x3(m_eulerAngles + m_deltaEulerAngles,
- m_scaling + m_deltaScaling));
+ MT_Matrix3x3(m_eulerAngles + m_deltaEulerAngles,
+ m_scaling + m_deltaScaling));
}
MT_Point3& GetPosition() { return m_position; }
diff --git a/source/gameengine/Ketsji/KX_IPO_SGController.cpp b/source/gameengine/Ketsji/KX_IPO_SGController.cpp
index 950e3c88a9e..c5e11195547 100644
--- a/source/gameengine/Ketsji/KX_IPO_SGController.cpp
+++ b/source/gameengine/Ketsji/KX_IPO_SGController.cpp
@@ -37,10 +37,10 @@ typedef unsigned __int64 uint_ptr;
typedef unsigned long uint_ptr;
#endif
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// This warning tells us about truncation of __long__ stl-generated names.
-// It can occasionally cause DevStudio to have internal compiler warnings.
-#pragma warning( disable : 4786 )
+#ifdef _MSC_VER
+ /* This warning tells us about truncation of __long__ stl-generated names.
+ * It can occasionally cause DevStudio to have internal compiler warnings. */
+# pragma warning(disable:4786)
#endif
#include "KX_IPO_SGController.h"
@@ -52,7 +52,7 @@ typedef unsigned long uint_ptr;
// All objects should start on frame 1! Will we ever need an object to
// start on another frame, the 1.0 should change.
-KX_IpoSGController::KX_IpoSGController()
+KX_IpoSGController::KX_IpoSGController()
: m_ipo_as_force(false),
m_ipo_add(false),
m_ipo_local(false),
diff --git a/source/gameengine/Ketsji/KX_IPO_SGController.h b/source/gameengine/Ketsji/KX_IPO_SGController.h
index 266b89ff969..cecfa9804db 100644
--- a/source/gameengine/Ketsji/KX_IPO_SGController.h
+++ b/source/gameengine/Ketsji/KX_IPO_SGController.h
@@ -126,6 +126,4 @@ public:
#endif
};
-#endif //__KX_IPO_SGCONTROLLER_H__
-
-
+#endif /* __KX_IPO_SGCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_IPhysicsController.h b/source/gameengine/Ketsji/KX_IPhysicsController.h
index dd34549c1fb..280b1816a1e 100644
--- a/source/gameengine/Ketsji/KX_IPhysicsController.h
+++ b/source/gameengine/Ketsji/KX_IPhysicsController.h
@@ -145,5 +145,4 @@ public:
#endif
};
-#endif //__KX_IPHYSICSCONTROLLER_H__
-
+#endif /* __KX_IPHYSICSCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_IScalarInterpolator.h b/source/gameengine/Ketsji/KX_IScalarInterpolator.h
index 2b5aefccfe7..1e822c49c6d 100644
--- a/source/gameengine/Ketsji/KX_IScalarInterpolator.h
+++ b/source/gameengine/Ketsji/KX_IScalarInterpolator.h
@@ -36,7 +36,7 @@
#include "MEM_guardedalloc.h"
#endif
-class KX_IScalarInterpolator {
+class KX_IScalarInterpolator {
public:
virtual ~KX_IScalarInterpolator() {}
diff --git a/source/gameengine/Ketsji/KX_ISceneConverter.h b/source/gameengine/Ketsji/KX_ISceneConverter.h
index 919ae1d6de5..18fb336dbe0 100644
--- a/source/gameengine/Ketsji/KX_ISceneConverter.h
+++ b/source/gameengine/Ketsji/KX_ISceneConverter.h
@@ -93,5 +93,4 @@ public:
#endif
};
-#endif //__KX_ISCENECONVERTER_H__
-
+#endif /* __KX_ISCENECONVERTER_H__ */
diff --git a/source/gameengine/Ketsji/KX_IpoActuator.cpp b/source/gameengine/Ketsji/KX_IpoActuator.cpp
index 5599f3e31c6..1597d7f8809 100644
--- a/source/gameengine/Ketsji/KX_IpoActuator.cpp
+++ b/source/gameengine/Ketsji/KX_IpoActuator.cpp
@@ -182,7 +182,7 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
m_bIpoPlaying = true;
bIpoStart = true;
}
- }
+ }
switch ((IpoActType)m_type)
{
@@ -254,7 +254,7 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
result = false;
if (bIpoStart)
- ((KX_GameObject*)GetParent())->InitIPO(m_ipo_as_force, m_ipo_add, m_ipo_local);
+ ((KX_GameObject*)GetParent())->InitIPO(m_ipo_as_force, m_ipo_add, m_ipo_local);
((KX_GameObject*)GetParent())->UpdateIPO(m_localtime,m_recurse);
break;
}
@@ -309,7 +309,7 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
bIpoStart = true;
}
else
- {
+ {
/* Perform clamping */
m_localtime=m_endframe;
result = false;
@@ -453,15 +453,15 @@ PyAttributeDef KX_IpoActuator::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_IpoActuator::pyattr_get_frame_start(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_IpoActuator::pyattr_get_frame_start(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_IpoActuator* self= static_cast<KX_IpoActuator*>(self_v);
+ KX_IpoActuator* self = static_cast<KX_IpoActuator*>(self_v);
return PyFloat_FromDouble(self->m_startframe);
}
int KX_IpoActuator::pyattr_set_frame_start(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_IpoActuator* self= static_cast<KX_IpoActuator*>(self_v);
+ KX_IpoActuator* self = static_cast<KX_IpoActuator*>(self_v);
float param = PyFloat_AsDouble(value);
if (PyErr_Occurred()) {
@@ -474,15 +474,15 @@ int KX_IpoActuator::pyattr_set_frame_start(void *self_v, const KX_PYATTRIBUTE_DE
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_IpoActuator::pyattr_get_frame_end(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_IpoActuator::pyattr_get_frame_end(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_IpoActuator* self= static_cast<KX_IpoActuator*>(self_v);
+ KX_IpoActuator* self = static_cast<KX_IpoActuator*>(self_v);
return PyFloat_FromDouble(self->m_endframe);
}
int KX_IpoActuator::pyattr_set_frame_end(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_IpoActuator* self= static_cast<KX_IpoActuator*>(self_v);
+ KX_IpoActuator* self = static_cast<KX_IpoActuator*>(self_v);
float param = PyFloat_AsDouble(value);
if (PyErr_Occurred()) {
diff --git a/source/gameengine/Ketsji/KX_IpoActuator.h b/source/gameengine/Ketsji/KX_IpoActuator.h
index 58cdfc28742..1c2f4e49b72 100644
--- a/source/gameengine/Ketsji/KX_IpoActuator.h
+++ b/source/gameengine/Ketsji/KX_IpoActuator.h
@@ -150,5 +150,4 @@ public:
};
-#endif //__KX_IPOACTUATOR_H__
-
+#endif /* __KX_IPOACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp b/source/gameengine/Ketsji/KX_KetsjiEngine.cpp
index a560b606f5b..0ab7b9ec9e5 100644
--- a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp
+++ b/source/gameengine/Ketsji/KX_KetsjiEngine.cpp
@@ -30,10 +30,9 @@
* \ingroup ketsji
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
+#endif
#include <iostream>
#include <stdio.h>
@@ -46,7 +45,6 @@
#include "BoolValue.h"
#include "FloatValue.h"
-#define KX_NUM_ITERATIONS 4
#include "RAS_BucketManager.h"
#include "RAS_Rect.h"
#include "RAS_IRasterizer.h"
@@ -253,7 +251,7 @@ void KX_KetsjiEngine::SetRasterizer(RAS_IRasterizer* rasterizer)
* At the moment the bge.logic module is imported into 'pythondictionary' after this function is called.
* if this function ever changes to assign a copy, make sure the game logic module is imported into this dictionary before hand.
*/
-void KX_KetsjiEngine::SetPyNamespace(PyObject* pythondictionary)
+void KX_KetsjiEngine::SetPyNamespace(PyObject *pythondictionary)
{
MT_assert(pythondictionary);
m_pythondictionary = pythondictionary;
@@ -275,8 +273,7 @@ void KX_KetsjiEngine::InitDome(short res, short mode, short angle, float resbuf,
void KX_KetsjiEngine::RenderDome()
{
- GLuint viewport[4]={0};
- glGetIntegerv(GL_VIEWPORT,(GLint *)viewport);
+ const GLint *viewport = m_canvas->GetViewPort();
m_dome->SetViewPort(viewport);
@@ -337,8 +334,7 @@ void KX_KetsjiEngine::RenderDome()
// Draw the scene once for each camera with an enabled viewport
list<KX_Camera*>::iterator it = cameras->begin();
- while(it != cameras->end())
- {
+ while (it != cameras->end()) {
if ((*it)->GetViewport())
{
if (scene->IsClearingZBuffer())
@@ -361,7 +357,7 @@ void KX_KetsjiEngine::RenderDome()
// no FlushDebugLines
}
m_dome->BindImages(i);
- }
+ }
m_canvas->EndFrame();//XXX do we really need that?
@@ -391,7 +387,7 @@ void KX_KetsjiEngine::RenderDome()
// Draw Callback for the last scene
#ifdef WITH_PYTHON
scene->RunDrawingCallbacks(scene->GetPostDrawCB());
-#endif
+#endif
EndFrame();
}
@@ -477,7 +473,7 @@ void KX_KetsjiEngine::ClearFrame()
SetBackGround(firstscene->GetWorldInfo());
m_canvas->SetViewPort(clearvp.GetLeft(), clearvp.GetBottom(),
- clearvp.GetRight(), clearvp.GetTop());
+ clearvp.GetRight(), clearvp.GetTop());
m_rasterizer->ClearColorBuffer();
}
}
@@ -498,7 +494,7 @@ bool KX_KetsjiEngine::BeginFrame()
}
return false;
-}
+}
void KX_KetsjiEngine::EndFrame()
@@ -641,7 +637,7 @@ else
scene->GetPhysicsEnvironment()->endFrame();
// Update scenegraph after physics step. This maps physics calculations
- // into node positions.
+ // into node positions.
//m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
//SG_SetActiveStage(SG_STAGE_PHYSICS1_UPDATE);
//scene->UpdateParents(m_frameTime);
@@ -692,7 +688,7 @@ else
if (m_animation_record)
- {
+ {
m_sceneconverter->WritePhysicsObjectToAnimationIpo(++m_currentFrame);
}
@@ -725,7 +721,7 @@ else
bool bUseAsyncLogicBricks= false;//true;
if (bUseAsyncLogicBricks)
- {
+ {
// Logic update sub frame: this will let some logic bricks run at the
// full frame rate.
for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); ++sceneit)
@@ -756,7 +752,7 @@ else
m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
scene->GetPhysicsEnvironment()->proceedDeltaTime(m_clockTime,timestep,timestep);
// Update scenegraph after physics step. This maps physics calculations
- // into node positions.
+ // into node positions.
m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
SG_SetActiveStage(SG_STAGE_PHYSICS2);
scene->UpdateParents(m_clockTime);
@@ -892,8 +888,7 @@ void KX_KetsjiEngine::Render()
// Draw the scene once for each camera with an enabled viewport
list<KX_Camera*>::iterator it = cameras->begin();
- while(it != cameras->end())
- {
+ while (it != cameras->end()) {
if ((*it)->GetViewport())
{
if (scene->IsClearingZBuffer())
@@ -938,12 +933,11 @@ void KX_KetsjiEngine::Render()
//RenderFrame(scene);
RenderFrame(scene, cam);
- list<class KX_Camera*>* cameras = scene->GetCameras();
+ list<class KX_Camera*>* cameras = scene->GetCameras();
// Draw the scene once for each camera with an enabled viewport
list<KX_Camera*>::iterator it = cameras->begin();
- while(it != cameras->end())
- {
+ while (it != cameras->end()) {
if ((*it)->GetViewport())
{
if (scene->IsClearingZBuffer())
@@ -1013,7 +1007,7 @@ void KX_KetsjiEngine::SetBackGround(KX_WorldInfo* wi)
if (wi->hasWorld())
{
if (m_drawingmode == RAS_IRasterizer::KX_TEXTURED)
- {
+ {
m_rasterizer->SetBackColor(
wi->getBackColorRed(),
wi->getBackColorGreen(),
@@ -1038,7 +1032,7 @@ void KX_KetsjiEngine::SetWorldSettings(KX_WorldInfo* wi)
);
if (m_drawingmode >= RAS_IRasterizer::KX_SOLID)
- {
+ {
if (wi->hasMist())
{
m_rasterizer->SetFog(
@@ -1203,11 +1197,11 @@ void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
GetSceneViewport(scene, cam, area, viewport);
// store the computed viewport in the scene
- scene->SetSceneViewport(viewport);
+ scene->SetSceneViewport(viewport);
// set the viewport for this frame and scene
m_canvas->SetViewPort(viewport.GetLeft(), viewport.GetBottom(),
- viewport.GetRight(), viewport.GetTop());
+ viewport.GetRight(), viewport.GetTop());
// see KX_BlenderMaterial::Activate
//m_rasterizer->SetAmbient();
@@ -1330,8 +1324,7 @@ void KX_KetsjiEngine::RenderFonts(KX_Scene* scene)
list<class KX_FontObject*>* fonts = scene->GetFonts();
list<KX_FontObject*>::iterator it = fonts->begin();
- while(it != fonts->end())
- {
+ while (it != fonts->end()) {
(*it)->DrawText();
++it;
}
@@ -1348,7 +1341,7 @@ void KX_KetsjiEngine::PostRenderScene(KX_Scene* scene)
m_rasterizer->FlushDebugShapes();
scene->Render2DFilters(m_canvas);
#ifdef WITH_PYTHON
- scene->RunDrawingCallbacks(scene->GetPostDrawCB());
+ scene->RunDrawingCallbacks(scene->GetPostDrawCB());
#endif
}
@@ -1368,10 +1361,10 @@ void KX_KetsjiEngine::StopEngine()
{
KX_Scene* scene = *sceneit;
m_sceneconverter->RemoveScene(scene);
- }
+ }
m_scenes.clear();
- // cleanup all the stuff
+ // cleanup all the stuff
m_rasterizer->Exit();
}
}
@@ -1443,8 +1436,17 @@ void KX_KetsjiEngine::PostProcessScene(KX_Scene* scene)
void KX_KetsjiEngine::RenderDebugProperties()
{
STR_String debugtxt;
- int xcoord = 10; // mmmm, these constants were taken from blender source
- int ycoord = 14; // to 'mimic' behavior
+ int title_xmargin = -7;
+ int title_y_top_margin = 4;
+ int title_y_bottom_margin = 2;
+
+ int const_xindent = 4;
+ int const_ysize = 14;
+
+ int xcoord = 12; // mmmm, these constants were taken from blender source
+ int ycoord = 17; // to 'mimic' behavior
+
+ int profile_indent = 64;
float tottime = m_logger->GetAverage();
if (tottime < 1e-6f) {
@@ -1455,43 +1457,88 @@ void KX_KetsjiEngine::RenderDebugProperties()
RAS_Rect viewport;
m_canvas->SetViewPort(0, 0, int(m_canvas->GetWidth()), int(m_canvas->GetHeight()));
+ if (m_show_framerate || m_show_profile) {
+ /* Title for profiling("Profile") */
+ debugtxt.Format("Profile");
+ m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
+ debugtxt.Ptr(),
+ xcoord + const_xindent + title_xmargin, // Adds the constant x indent (0 for now) to the title x margin
+ ycoord,
+ m_canvas->GetWidth() /* RdV, TODO ?? */,
+ m_canvas->GetHeight() /* RdV, TODO ?? */);
+
+ // Increase the indent by default increase
+ ycoord += const_ysize;
+ // Add the title indent afterwards
+ ycoord += title_y_bottom_margin;
+ }
+
/* Framerate display */
if (m_show_framerate) {
- debugtxt.Format("swap : %.3f (%.3f frames per second)", tottime, 1.0/tottime);
+ debugtxt.Format("Frametime :");
m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
debugtxt.Ptr(),
- xcoord,
+ xcoord + const_xindent,
ycoord,
- m_canvas->GetWidth() /* RdV, TODO ?? */,
+ m_canvas->GetWidth() /* RdV, TODO ?? */,
m_canvas->GetHeight() /* RdV, TODO ?? */);
- ycoord += 14;
+
+ debugtxt.Format("%5.1fms (%5.1f fps)", tottime * 1000.f, 1.0/tottime);
+ m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
+ debugtxt.Ptr(),
+ xcoord + const_xindent + profile_indent,
+ ycoord,
+ m_canvas->GetWidth() /* RdV, TODO ?? */,
+ m_canvas->GetHeight() /* RdV, TODO ?? */);
+ // Increase the indent by default increase
+ ycoord += const_ysize;
}
- /* Profile and framerate display */
+ /* Profile display */
if (m_show_profile)
- {
+ {
for (int j = tc_first; j < tc_numCategories; j++)
{
debugtxt.Format(m_profileLabels[j]);
m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
debugtxt.Ptr(),
- xcoord,ycoord,
+ xcoord + const_xindent,
+ ycoord,
m_canvas->GetWidth(),
m_canvas->GetHeight());
+
double time = m_logger->GetAverage((KX_TimeCategory)j);
- debugtxt.Format("%.3fms (%2.2f %%)", time*1000.f, time/tottime * 100.f);
+
+ debugtxt.Format("%5.2fms (%2d%%)", time*1000.f, (int)(time/tottime * 100.f));
m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
debugtxt.Ptr(),
- xcoord + 60, ycoord,
+ xcoord + const_xindent + profile_indent, ycoord,
m_canvas->GetWidth(),
m_canvas->GetHeight());
- ycoord += 14;
+ ycoord += const_ysize;
}
}
+ // Add the ymargin for titles below the other section of debug info
+ ycoord += title_y_top_margin;
/* Property display*/
if (m_show_debug_properties && m_propertiesPresent)
{
+
+ /* Title for debugging("Debug properties") */
+ debugtxt.Format("Debug Properties");
+ m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
+ debugtxt.Ptr(),
+ xcoord + const_xindent + title_xmargin, // Adds the constant x indent (0 for now) to the title x margin
+ ycoord,
+ m_canvas->GetWidth() /* RdV, TODO ?? */,
+ m_canvas->GetHeight() /* RdV, TODO ?? */);
+
+ // Increase the indent by default increase
+ ycoord += const_ysize;
+ // Add the title indent afterwards
+ ycoord += title_y_bottom_margin;
+
KX_SceneList::iterator sceneit;
for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
{
@@ -1526,11 +1573,11 @@ void KX_KetsjiEngine::RenderDebugProperties()
}
m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
debugtxt.Ptr(),
- xcoord,
+ xcoord + const_xindent,
ycoord,
m_canvas->GetWidth(),
m_canvas->GetHeight());
- ycoord += 14;
+ ycoord += const_ysize;
}
else
{
@@ -1538,14 +1585,14 @@ void KX_KetsjiEngine::RenderDebugProperties()
if (propval)
{
STR_String text = propval->GetText();
- debugtxt = objname + "." + propname + " = " + text;
+ debugtxt = objname + ": '" + propname + "' = " + text;
m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
debugtxt.Ptr(),
- xcoord,
+ xcoord + const_xindent,
ycoord,
m_canvas->GetWidth(),
m_canvas->GetHeight());
- ycoord += 14;
+ ycoord += const_ysize;
}
}
}
@@ -1556,7 +1603,7 @@ void KX_KetsjiEngine::RenderDebugProperties()
KX_SceneList* KX_KetsjiEngine::CurrentScenes()
{
- return &m_scenes;
+ return &m_scenes;
}
@@ -1572,7 +1619,7 @@ KX_Scene* KX_KetsjiEngine::FindScene(const STR_String& scenename)
sceneit++;
}
- return ((sceneit == m_scenes.end()) ? NULL : *sceneit);
+ return ((sceneit == m_scenes.end()) ? NULL : *sceneit);
}
@@ -1635,7 +1682,7 @@ void KX_KetsjiEngine::RemoveScheduledScenes()
m_scenes.erase(sceneit);
break;
}
- }
+ }
}
m_removingScenes.clear();
}
@@ -1737,7 +1784,7 @@ void KX_KetsjiEngine::ReplaceScheduledScenes()
}
}
m_replace_scenes.clear();
- }
+ }
}
@@ -1910,7 +1957,7 @@ void KX_KetsjiEngine::SceneListsChanged(void)
while ((sceneit != m_scenes.end()) && (!m_propertiesPresent))
{
KX_Scene* scene = *sceneit;
- vector<SCA_DebugProp*>& debugproplist = scene->GetDebugProperties();
+ vector<SCA_DebugProp*>& debugproplist = scene->GetDebugProperties();
m_propertiesPresent = !debugproplist.empty();
sceneit++;
}
diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.h b/source/gameengine/Ketsji/KX_KetsjiEngine.h
index b3bef016b0f..972594bd90f 100644
--- a/source/gameengine/Ketsji/KX_KetsjiEngine.h
+++ b/source/gameengine/Ketsji/KX_KetsjiEngine.h
@@ -98,7 +98,7 @@ private:
/* The current list of scenes. */
KX_SceneList m_scenes;
/* State variable recording the presence of object debug info in the current scene list. */
- bool m_propertiesPresent;
+ bool m_propertiesPresent;
bool m_bInitialized;
int m_activecam;
@@ -136,7 +136,7 @@ private:
int m_drawingmode;
float m_cameraZoom;
- bool m_overrideCam;
+ bool m_overrideCam;
STR_String m_overrideSceneName;
bool m_overrideCamUseOrtho;
@@ -220,7 +220,7 @@ public:
void SetRenderTools(RAS_IRenderTools* rendertools);
void SetRasterizer(RAS_IRasterizer* rasterizer);
#ifdef WITH_PYTHON
- void SetPyNamespace(PyObject* pythondictionary);
+ void SetPyNamespace(PyObject *pythondictionary);
PyObject* GetPyNamespace() { return m_pythondictionary; }
#endif
void SetSceneConverter(KX_ISceneConverter* sceneconverter);
@@ -415,7 +415,7 @@ public:
KX_Scene* CreateScene(const STR_String& scenename);
KX_Scene* CreateScene(Scene *scene);
- GlobalSettings* GetGlobalSettings(void);
+ GlobalSettings* GetGlobalSettings(void);
void SetGlobalSettings(GlobalSettings* gs);
protected:
@@ -447,6 +447,4 @@ protected:
#endif
};
-#endif //__KX_KETSJIENGINE_H__
-
-
+#endif /* __KX_KETSJIENGINE_H__ */
diff --git a/source/gameengine/Ketsji/KX_Light.cpp b/source/gameengine/Ketsji/KX_Light.cpp
index f5aa1bb3c75..a4e90cb1e83 100644
--- a/source/gameengine/Ketsji/KX_Light.cpp
+++ b/source/gameengine/Ketsji/KX_Light.cpp
@@ -29,8 +29,8 @@
* \ingroup ketsji
*/
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
#endif
#include <stdio.h>
@@ -50,9 +50,9 @@
#include "GPU_material.h"
KX_LightObject::KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,
- class RAS_IRenderTools* rendertools,
- const RAS_LightObject& lightobj,
- bool glsl)
+ class RAS_IRenderTools* rendertools,
+ const RAS_LightObject& lightobj,
+ bool glsl)
: KX_GameObject(sgReplicationInfo,callbacks),
m_rendertools(rendertools)
{
@@ -126,14 +126,14 @@ bool KX_LightObject::ApplyLight(KX_Scene *kxscene, int oblayer, int slot)
vec[0] = worldmatrix(0,2);
vec[1] = worldmatrix(1,2);
vec[2] = worldmatrix(2,2);
- //vec[0]= base->object->obmat[2][0];
- //vec[1]= base->object->obmat[2][1];
- //vec[2]= base->object->obmat[2][2];
- vec[3]= 0.0;
+ //vec[0] = base->object->obmat[2][0];
+ //vec[1] = base->object->obmat[2][1];
+ //vec[2] = base->object->obmat[2][2];
+ vec[3] = 0.0;
glLightfv((GLenum)(GL_LIGHT0+slot), GL_POSITION, vec);
}
else {
- //vec[3]= 1.0;
+ //vec[3] = 1.0;
glLightfv((GLenum)(GL_LIGHT0+slot), GL_POSITION, vec);
glLightf((GLenum)(GL_LIGHT0+slot), GL_CONSTANT_ATTENUATION, 1.0);
glLightf((GLenum)(GL_LIGHT0+slot), GL_LINEAR_ATTENUATION, m_lightobj.m_att1/m_lightobj.m_distance);
@@ -145,9 +145,9 @@ bool KX_LightObject::ApplyLight(KX_Scene *kxscene, int oblayer, int slot)
vec[0] = -worldmatrix(0,2);
vec[1] = -worldmatrix(1,2);
vec[2] = -worldmatrix(2,2);
- //vec[0]= -base->object->obmat[2][0];
- //vec[1]= -base->object->obmat[2][1];
- //vec[2]= -base->object->obmat[2][2];
+ //vec[0] = -base->object->obmat[2][0];
+ //vec[1] = -base->object->obmat[2][1];
+ //vec[2] = -base->object->obmat[2][2];
glLightfv((GLenum)(GL_LIGHT0+slot), GL_SPOT_DIRECTION, vec);
glLightf((GLenum)(GL_LIGHT0+slot), GL_SPOT_CUTOFF, m_lightobj.m_spotsize / 2.0f);
glLightf((GLenum)(GL_LIGHT0+slot), GL_SPOT_EXPONENT, 128.0f * m_lightobj.m_spotblend);
@@ -161,10 +161,10 @@ bool KX_LightObject::ApplyLight(KX_Scene *kxscene, int oblayer, int slot)
vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
}
else {
- vec[0]= m_lightobj.m_energy*m_lightobj.m_red;
- vec[1]= m_lightobj.m_energy*m_lightobj.m_green;
- vec[2]= m_lightobj.m_energy*m_lightobj.m_blue;
- vec[3]= 1.0;
+ vec[0] = m_lightobj.m_energy*m_lightobj.m_red;
+ vec[1] = m_lightobj.m_energy*m_lightobj.m_green;
+ vec[2] = m_lightobj.m_energy*m_lightobj.m_blue;
+ vec[3] = 1.0;
}
glLightfv((GLenum)(GL_LIGHT0+slot), GL_DIFFUSE, vec);
@@ -173,10 +173,10 @@ bool KX_LightObject::ApplyLight(KX_Scene *kxscene, int oblayer, int slot)
vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
}
else if (m_lightobj.m_nodiffuse) {
- vec[0]= m_lightobj.m_energy*m_lightobj.m_red;
- vec[1]= m_lightobj.m_energy*m_lightobj.m_green;
- vec[2]= m_lightobj.m_energy*m_lightobj.m_blue;
- vec[3]= 1.0;
+ vec[0] = m_lightobj.m_energy*m_lightobj.m_red;
+ vec[1] = m_lightobj.m_energy*m_lightobj.m_green;
+ vec[2] = m_lightobj.m_energy*m_lightobj.m_blue;
+ vec[3] = 1.0;
}
glLightfv((GLenum)(GL_LIGHT0+slot), GL_SPECULAR, vec);
@@ -344,7 +344,7 @@ PyAttributeDef KX_LightObject::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_LightObject::pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_LightObject::pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
return Py_BuildValue("[fff]", self->m_lightobj.m_red, self->m_lightobj.m_green, self->m_lightobj.m_blue);
@@ -365,9 +365,9 @@ int KX_LightObject::pyattr_set_color(void *self_v, const KX_PYATTRIBUTE_DEF *att
return PY_SET_ATTR_FAIL;
}
-PyObject* KX_LightObject::pyattr_get_typeconst(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_LightObject::pyattr_get_typeconst(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- PyObject* retvalue;
+ PyObject *retvalue;
const char* type = attrdef->m_name;
@@ -387,13 +387,13 @@ PyObject* KX_LightObject::pyattr_get_typeconst(void *self_v, const KX_PYATTRIBUT
return retvalue;
}
-PyObject* KX_LightObject::pyattr_get_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_LightObject::pyattr_get_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
return PyLong_FromSsize_t(self->m_lightobj.m_type);
}
-int KX_LightObject::pyattr_set_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject* value)
+int KX_LightObject::pyattr_set_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
int val = PyLong_AsSsize_t(value);
@@ -402,7 +402,7 @@ int KX_LightObject::pyattr_set_type(void* self_v, const KX_PYATTRIBUTE_DEF *attr
return PY_SET_ATTR_FAIL;
}
- switch(val) {
+ switch (val) {
case 0:
self->m_lightobj.m_type = self->m_lightobj.LIGHT_SPOT;
break;
diff --git a/source/gameengine/Ketsji/KX_Light.h b/source/gameengine/Ketsji/KX_Light.h
index 9fe13f471ba..52f076c772a 100644
--- a/source/gameengine/Ketsji/KX_Light.h
+++ b/source/gameengine/Ketsji/KX_Light.h
@@ -76,12 +76,11 @@ public:
#ifdef WITH_PYTHON
/* attributes */
static PyObject* pyattr_get_color(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_color(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject* value);
+ static int pyattr_set_color(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
static PyObject* pyattr_get_typeconst(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static PyObject* pyattr_get_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject* value);
+ static int pyattr_set_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
#endif
};
-#endif //__KX_LIGHT_H__
-
+#endif /* __KX_LIGHT_H__ */
diff --git a/source/gameengine/Ketsji/KX_LightIpoSGController.h b/source/gameengine/Ketsji/KX_LightIpoSGController.h
index 3a3a9677b04..c82fe7bcad5 100644
--- a/source/gameengine/Ketsji/KX_LightIpoSGController.h
+++ b/source/gameengine/Ketsji/KX_LightIpoSGController.h
@@ -74,15 +74,15 @@ public:
m_modified = true;
}
- void SetModifyEnergy(bool modify) {
+ void SetModifyEnergy(bool modify) {
m_modify_energy = modify;
}
- void SetModifyColor(bool modify) {
+ void SetModifyColor(bool modify) {
m_modify_color = modify;
}
- void SetModifyDist(bool modify) {
+ void SetModifyDist(bool modify) {
m_modify_dist = modify;
}
@@ -102,5 +102,4 @@ public:
#endif
};
-#endif // __KX_LIGHTIPOSGCONTROLLER_H__
-
+#endif /* __KX_LIGHTIPOSGCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_MaterialIpoController.h b/source/gameengine/Ketsji/KX_MaterialIpoController.h
index ee5546641c2..a7e9c2cc1c5 100644
--- a/source/gameengine/Ketsji/KX_MaterialIpoController.h
+++ b/source/gameengine/Ketsji/KX_MaterialIpoController.h
@@ -62,7 +62,4 @@ public:
#endif
};
-
-
-
-#endif//__KX_MATERIALIPOCONTROLLER_H__
+#endif /* __KX_MATERIALIPOCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_MeshProxy.cpp b/source/gameengine/Ketsji/KX_MeshProxy.cpp
index f1a9a93c2db..87c366046ad 100644
--- a/source/gameengine/Ketsji/KX_MeshProxy.cpp
+++ b/source/gameengine/Ketsji/KX_MeshProxy.cpp
@@ -105,7 +105,7 @@ KX_MeshProxy::~KX_MeshProxy()
// stuff for cvalue related things
CValue* KX_MeshProxy::Calc(VALUE_OPERATOR op, CValue *val) { return NULL;}
-CValue* KX_MeshProxy::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) { return NULL;}
+CValue* KX_MeshProxy::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) { return NULL;}
const STR_String & KX_MeshProxy::GetText() {return m_meshobj->GetName();};
double KX_MeshProxy::GetNumber() { return -1;}
@@ -116,7 +116,7 @@ CValue* KX_MeshProxy::GetReplica() { return NULL;}
// stuff for python integration
-PyObject* KX_MeshProxy::PyGetMaterialName(PyObject* args, PyObject* kwds)
+PyObject *KX_MeshProxy::PyGetMaterialName(PyObject *args, PyObject *kwds)
{
int matid= 1;
STR_String matname;
@@ -134,7 +134,7 @@ PyObject* KX_MeshProxy::PyGetMaterialName(PyObject* args, PyObject* kwds)
}
-PyObject* KX_MeshProxy::PyGetTextureName(PyObject* args, PyObject* kwds)
+PyObject *KX_MeshProxy::PyGetTextureName(PyObject *args, PyObject *kwds)
{
int matid= 1;
STR_String matname;
@@ -151,7 +151,7 @@ PyObject* KX_MeshProxy::PyGetTextureName(PyObject* args, PyObject* kwds)
}
-PyObject* KX_MeshProxy::PyGetVertexArrayLength(PyObject* args, PyObject* kwds)
+PyObject *KX_MeshProxy::PyGetVertexArrayLength(PyObject *args, PyObject *kwds)
{
int matid= 0;
int length = 0;
@@ -174,7 +174,7 @@ PyObject* KX_MeshProxy::PyGetVertexArrayLength(PyObject* args, PyObject* kwds)
}
-PyObject* KX_MeshProxy::PyGetVertex(PyObject* args, PyObject* kwds)
+PyObject *KX_MeshProxy::PyGetVertex(PyObject *args, PyObject *kwds)
{
int vertexindex;
int matindex;
@@ -192,10 +192,10 @@ PyObject* KX_MeshProxy::PyGetVertex(PyObject* args, PyObject* kwds)
return (new KX_VertexProxy(this, vertex))->NewProxy(true);
}
-PyObject* KX_MeshProxy::PyGetPolygon(PyObject* args, PyObject* kwds)
+PyObject *KX_MeshProxy::PyGetPolygon(PyObject *args, PyObject *kwds)
{
int polyindex= 1;
- PyObject* polyob = NULL;
+ PyObject *polyob = NULL;
if (!PyArg_ParseTuple(args,"i:getPolygon",&polyindex))
return NULL;
@@ -218,9 +218,9 @@ PyObject* KX_MeshProxy::PyGetPolygon(PyObject* args, PyObject* kwds)
return polyob;
}
-PyObject* KX_MeshProxy::pyattr_get_materials(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_MeshProxy::pyattr_get_materials(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_MeshProxy* self= static_cast<KX_MeshProxy*>(self_v);
+ KX_MeshProxy* self = static_cast<KX_MeshProxy*>(self_v);
int tot= self->m_meshobj->NumMaterials();
int i;
@@ -233,17 +233,17 @@ PyObject* KX_MeshProxy::pyattr_get_materials(void *self_v, const KX_PYATTRIBUTE_
for (i=0; i<tot; mit++, i++) {
RAS_IPolyMaterial *polymat = mit->m_bucket->GetPolyMaterial();
- /* Why do we need to check for RAS_BLENDERMAT if both are cast to a (PyObject*)? - Campbell */
+ /* Why do we need to check for RAS_BLENDERMAT if both are cast to a (PyObject *)? - Campbell */
if (polymat->GetFlag() & RAS_BLENDERMAT)
{
KX_BlenderMaterial *mat = static_cast<KX_BlenderMaterial*>(polymat);
PyList_SET_ITEM(materials, i, mat->GetProxy());
}
- else {
+ else {
KX_PolygonMaterial *mat = static_cast<KX_PolygonMaterial*>(polymat);
PyList_SET_ITEM(materials, i, mat->GetProxy());
}
- }
+ }
return materials;
}
@@ -260,7 +260,7 @@ PyObject * KX_MeshProxy::pyattr_get_numPolygons(void * selfv, const KX_PYATTRIBU
}
/* a close copy of ConvertPythonToGameObject but for meshes */
-bool ConvertPythonToMesh(PyObject * value, RAS_MeshObject **object, bool py_none_ok, const char *error_prefix)
+bool ConvertPythonToMesh(PyObject *value, RAS_MeshObject **object, bool py_none_ok, const char *error_prefix)
{
if (value==NULL) {
PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
@@ -297,7 +297,7 @@ bool ConvertPythonToMesh(PyObject * value, RAS_MeshObject **object, bool py_none
if (kx_mesh==NULL) {
PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
return false;
- }
+ }
*object = kx_mesh->GetMesh();
return true;
diff --git a/source/gameengine/Ketsji/KX_MeshProxy.h b/source/gameengine/Ketsji/KX_MeshProxy.h
index 58b5c87e494..98e73aa626f 100644
--- a/source/gameengine/Ketsji/KX_MeshProxy.h
+++ b/source/gameengine/Ketsji/KX_MeshProxy.h
@@ -37,7 +37,7 @@
#include "SCA_IObject.h"
/* utility conversion function */
-bool ConvertPythonToMesh(PyObject * value, class RAS_MeshObject **object, bool py_none_ok, const char *error_prefix);
+bool ConvertPythonToMesh(PyObject *value, class RAS_MeshObject **object, bool py_none_ok, const char *error_prefix);
class KX_MeshProxy : public CValue
{
@@ -73,11 +73,10 @@ public:
KX_PYMETHOD(KX_MeshProxy,GetPolygon);
static PyObject* pyattr_get_materials(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject * pyattr_get_numMaterials(void * self, const KX_PYATTRIBUTE_DEF * attrdef);
- static PyObject * pyattr_get_numPolygons(void * self, const KX_PYATTRIBUTE_DEF * attrdef);
+ static PyObject *pyattr_get_numMaterials(void * self, const KX_PYATTRIBUTE_DEF * attrdef);
+ static PyObject *pyattr_get_numPolygons(void * self, const KX_PYATTRIBUTE_DEF * attrdef);
};
-#endif // WITH_PYTHON
-
-#endif //__KX_MESHPROXY_H__
+#endif /* WITH_PYTHON */
+#endif /* __KX_MESHPROXY_H__ */
diff --git a/source/gameengine/Ketsji/KX_MotionState.h b/source/gameengine/Ketsji/KX_MotionState.h
index 3bead93cbda..116e62f408f 100644
--- a/source/gameengine/Ketsji/KX_MotionState.h
+++ b/source/gameengine/Ketsji/KX_MotionState.h
@@ -62,5 +62,4 @@ public:
#endif
};
-#endif //__KX_MOTIONSTATE_H__
-
+#endif /* __KX_MOTIONSTATE_H__ */
diff --git a/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp b/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp
index bfee124d443..9368bc6458f 100644
--- a/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp
+++ b/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp
@@ -30,11 +30,10 @@
* \ingroup ketsji
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// This warning tells us about truncation of __long__ stl-generated names.
-// It can occasionally cause DevStudio to have internal compiler warnings.
-#pragma warning( disable : 4786 )
+#ifdef _MSC_VER
+ /* This warning tells us about truncation of __long__ stl-generated names.
+ * It can occasionally cause DevStudio to have internal compiler warnings. */
+# pragma warning(disable:4786)
#endif
#include "MT_Point3.h"
@@ -60,14 +59,14 @@
/* ------------------------------------------------------------------------- */
KX_MouseFocusSensor::KX_MouseFocusSensor(SCA_MouseManager* eventmgr,
- int startx,
- int starty,
- short int mousemode,
- int focusmode,
- bool bTouchPulse,
- KX_Scene* kxscene,
- KX_KetsjiEngine *kxengine,
- SCA_IObject* gameobj)
+ int startx,
+ int starty,
+ short int mousemode,
+ int focusmode,
+ bool bTouchPulse,
+ KX_Scene* kxscene,
+ KX_KetsjiEngine *kxengine,
+ SCA_IObject* gameobj)
: SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj),
m_focusmode(focusmode),
m_bTouchPulse(bTouchPulse),
@@ -142,7 +141,7 @@ bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, KX_RayCast* r
KX_GameObject* hitKXObj = client_info->m_gameobject;
/* Is this me? In the ray test, there are a lot of extra checks
- * for aliasing artefacts from self-hits. That doesn't happen
+ * for aliasing artifacts from self-hits. That doesn't happen
* here, so a simple test suffices. Or does the camera also get
* self-hits? (No, and the raysensor shouldn't do it either, since
* self-hits are excluded by setting the correct ignore-object.)
@@ -239,7 +238,7 @@ bool KX_MouseFocusSensor::ParentObjectHasFocusCamera(KX_Camera *cam)
/* build the from and to point in normalized device coordinates
* Normalized device coordinates are [-1,1] in x, y, z
- *
+ *
* The actual z coordinates used don't have to be exact just infront and
* behind of the near and far clip planes.
*/
@@ -309,8 +308,7 @@ bool KX_MouseFocusSensor::ParentObjectHasFocus()
list<class KX_Camera*>* cameras = m_kxscene->GetCameras();
list<KX_Camera*>::iterator it = cameras->begin();
- while(it != cameras->end())
- {
+ while (it != cameras->end()) {
if (((*it) != cam) && (*it)->GetViewport())
if (ParentObjectHasFocusCamera(*it))
return true;
@@ -392,30 +390,30 @@ PyAttributeDef KX_MouseFocusSensor::Attributes[] = {
};
/* Attributes */
-PyObject* KX_MouseFocusSensor::pyattr_get_ray_source(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_MouseFocusSensor::pyattr_get_ray_source(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
+ KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
return PyObjectFrom(self->RaySource());
}
-PyObject* KX_MouseFocusSensor::pyattr_get_ray_target(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_MouseFocusSensor::pyattr_get_ray_target(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
+ KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
return PyObjectFrom(self->RayTarget());
}
-PyObject* KX_MouseFocusSensor::pyattr_get_ray_direction(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_MouseFocusSensor::pyattr_get_ray_direction(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
+ KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
MT_Vector3 dir = self->RayTarget() - self->RaySource();
if (MT_fuzzyZero(dir)) dir.setValue(0,0,0);
else dir.normalize();
return PyObjectFrom(dir);
}
-PyObject* KX_MouseFocusSensor::pyattr_get_hit_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_MouseFocusSensor::pyattr_get_hit_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
+ KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
if (self->m_hitObject)
return self->m_hitObject->GetProxy();
@@ -423,21 +421,21 @@ PyObject* KX_MouseFocusSensor::pyattr_get_hit_object(void *self_v, const KX_PYAT
Py_RETURN_NONE;
}
-PyObject* KX_MouseFocusSensor::pyattr_get_hit_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_MouseFocusSensor::pyattr_get_hit_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
+ KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
return PyObjectFrom(self->HitPosition());
}
-PyObject* KX_MouseFocusSensor::pyattr_get_hit_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_MouseFocusSensor::pyattr_get_hit_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
+ KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
return PyObjectFrom(self->HitNormal());
}
-PyObject* KX_MouseFocusSensor::pyattr_get_hit_uv(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_MouseFocusSensor::pyattr_get_hit_uv(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
+ KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
return PyObjectFrom(self->HitUV());
}
diff --git a/source/gameengine/Ketsji/KX_MouseFocusSensor.h b/source/gameengine/Ketsji/KX_MouseFocusSensor.h
index db9e3697492..1f7809831e7 100644
--- a/source/gameengine/Ketsji/KX_MouseFocusSensor.h
+++ b/source/gameengine/Ketsji/KX_MouseFocusSensor.h
@@ -111,7 +111,7 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
static PyObject* pyattr_get_hit_normal(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static PyObject* pyattr_get_hit_uv(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
/* --------------------------------------------------------------------- */
SCA_IObject* m_hitObject;
@@ -151,27 +151,27 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
/**
* (in game world coordinates) the place where the object was hit.
*/
- MT_Point3 m_hitPosition;
+ MT_Point3 m_hitPosition;
/**
* (in game world coordinates) the position to which to shoot the ray.
*/
- MT_Point3 m_prevTargetPoint;
+ MT_Point3 m_prevTargetPoint;
/**
* (in game world coordinates) the position from which to shoot the ray.
*/
- MT_Point3 m_prevSourcePoint;
-
+ MT_Point3 m_prevSourcePoint;
+
/**
* (in game world coordinates) the face normal of the vertex where
* the object was hit. */
- MT_Vector3 m_hitNormal;
+ MT_Vector3 m_hitNormal;
/**
* UV texture coordinate of the hit point if any, (0,0) otherwise
*/
- MT_Vector2 m_hitUV;
+ MT_Vector2 m_hitUV;
/**
* The KX scene that holds the camera. The camera position
@@ -183,5 +183,4 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
KX_KetsjiEngine* m_kxengine;
};
-#endif //__KX_MOUSESENSOR
-
+#endif /* __KX_MOUSESENSOR */
diff --git a/source/gameengine/Ketsji/KX_NavMeshObject.cpp b/source/gameengine/Ketsji/KX_NavMeshObject.cpp
index 35058e5fe5d..33656e9fd52 100644
--- a/source/gameengine/Ketsji/KX_NavMeshObject.cpp
+++ b/source/gameengine/Ketsji/KX_NavMeshObject.cpp
@@ -210,7 +210,7 @@ bool KX_NavMeshObject::BuildVertIndArrays(float *&vertices, int& nverts,
{
//detailed mesh vertex
memcpy(dvertices+3*(newIdx-nverts), allVerts+3*vi, 3*sizeof(float));
- }
+ }
}
}
@@ -245,11 +245,11 @@ bool KX_NavMeshObject::BuildVertIndArrays(float *&vertices, int& nverts,
{
memset(vert, 0, 3*sizeof(float)); //vertex isn't in any poly, set dummy zero coordinates
}
- vert+=3;
+ vert+=3;
}
//create tris
- polys = (unsigned short*)MEM_callocN(sizeof(unsigned short)*3*2*npolys, "BuildVertIndArrays polys");
+ polys = (unsigned short *)MEM_callocN(sizeof(unsigned short)*3*2*npolys, "BuildVertIndArrays polys");
memset(polys, 0xff, sizeof(unsigned short)*3*2*npolys);
unsigned short *poly = polys;
RAS_Polygon* raspoly;
@@ -258,10 +258,10 @@ bool KX_NavMeshObject::BuildVertIndArrays(float *&vertices, int& nverts,
raspoly = meshobj->GetPolygon(p);
for (int v=0; v<raspoly->VertexCount()-2; v++)
{
- poly[0]= raspoly->GetVertex(0)->getOrigIndex();
+ poly[0] = raspoly->GetVertex(0)->getOrigIndex();
for (size_t i=1; i<3; i++)
{
- poly[i]= raspoly->GetVertex(v+i)->getOrigIndex();
+ poly[i] = raspoly->GetVertex(v+i)->getOrigIndex();
}
poly += 6;
}
@@ -294,7 +294,7 @@ bool KX_NavMeshObject::BuildNavMesh()
float *vertices = NULL, *dvertices = NULL;
unsigned short *polys = NULL, *dtris = NULL, *dmeshes = NULL;
- int nverts = 0, npolys = 0, ndvertsuniq = 0, ndtris = 0;
+ int nverts = 0, npolys = 0, ndvertsuniq = 0, ndtris = 0;
int vertsPerPoly = 0;
if (!BuildVertIndArrays(vertices, nverts, polys, npolys,
dmeshes, dvertices, ndvertsuniq, dtris, ndtris, vertsPerPoly )
@@ -446,11 +446,11 @@ bool KX_NavMeshObject::BuildNavMesh()
dtl.nverts = dmeshes[i*4+1];
dtl.tbase = dmeshes[i*4+2];
dtl.ntris = dmeshes[i*4+3];
- }
+ }
}
m_navMesh = new dtStatNavMesh;
- m_navMesh->init(data, dataSize, true);
+ m_navMesh->init(data, dataSize, true);
delete [] vertices;
@@ -487,7 +487,7 @@ void KX_NavMeshObject::DrawNavMesh(NavMeshRenderMode renderMode)
const dtStatPoly* poly = m_navMesh->getPoly(pi);
for (int i = 0, j = (int)poly->nv-1; i < (int)poly->nv; j = i++)
- {
+ {
if (poly->n[j] && renderMode==RM_WALLS)
continue;
const float* vif = m_navMesh->getVertex(poly->v[i]);
@@ -564,7 +564,7 @@ int KX_NavMeshObject::FindPath(const MT_Point3& from, const MT_Point3& to, float
if (!m_navMesh)
return 0;
MT_Point3 localfrom = TransformToLocalCoords(from);
- MT_Point3 localto = TransformToLocalCoords(to);
+ MT_Point3 localto = TransformToLocalCoords(to);
float spos[3], epos[3];
localfrom.getValue(spos); flipAxes(spos);
localto.getValue(epos); flipAxes(epos);
@@ -598,7 +598,7 @@ float KX_NavMeshObject::Raycast(const MT_Point3& from, const MT_Point3& to)
if (!m_navMesh)
return 0.f;
MT_Point3 localfrom = TransformToLocalCoords(from);
- MT_Point3 localto = TransformToLocalCoords(to);
+ MT_Point3 localto = TransformToLocalCoords(to);
float spos[3], epos[3];
localfrom.getValue(spos); flipAxes(spos);
localto.getValue(epos); flipAxes(epos);
diff --git a/source/gameengine/Ketsji/KX_NavMeshObject.h b/source/gameengine/Ketsji/KX_NavMeshObject.h
index db35a011c16..1599361b334 100644
--- a/source/gameengine/Ketsji/KX_NavMeshObject.h
+++ b/source/gameengine/Ketsji/KX_NavMeshObject.h
@@ -74,8 +74,7 @@ public:
KX_PYMETHOD_DOC(KX_NavMeshObject, raycast);
KX_PYMETHOD_DOC(KX_NavMeshObject, draw);
KX_PYMETHOD_DOC_NOARGS(KX_NavMeshObject, rebuild);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif //__KX_NAVMESHOBJECT_H__
-
+#endif /* __KX_NAVMESHOBJECT_H__ */
diff --git a/source/gameengine/Ketsji/KX_NearSensor.h b/source/gameengine/Ketsji/KX_NearSensor.h
index 82f523283ed..ef6e15f602f 100644
--- a/source/gameengine/Ketsji/KX_NearSensor.h
+++ b/source/gameengine/Ketsji/KX_NearSensor.h
@@ -100,9 +100,8 @@ public:
return 0;
}
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif //__KX_NEARSENSOR_H__
-
+#endif /* __KX_NEARSENSOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_ObColorIpoSGController.h b/source/gameengine/Ketsji/KX_ObColorIpoSGController.h
index 9a9b3dac098..a7b0b2c4ffc 100644
--- a/source/gameengine/Ketsji/KX_ObColorIpoSGController.h
+++ b/source/gameengine/Ketsji/KX_ObColorIpoSGController.h
@@ -77,5 +77,4 @@ public:
#endif
};
-#endif // __KX_OBCOLORIPOSGCONTROLLER_H__
-
+#endif /* __KX_OBCOLORIPOSGCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_ObjectActuator.cpp b/source/gameengine/Ketsji/KX_ObjectActuator.cpp
index a3f098c3b1f..2999550fb8f 100644
--- a/source/gameengine/Ketsji/KX_ObjectActuator.cpp
+++ b/source/gameengine/Ketsji/KX_ObjectActuator.cpp
@@ -114,7 +114,14 @@ bool KX_ObjectActuator::Update()
(m_bitLocalFlag.AngularVelocity) != 0
);
m_active_combined_velocity = false;
- }
+ }
+
+ // Explicitly stop the movement if we're using a character (apply movement is a little different for characters)
+ if (parent->GetPhysicsController()->IsCharacter()) {
+ MT_Vector3 vec(0.0, 0.0, 0.0);
+ parent->ApplyMovement(vec, true);
+ }
+
m_linear_damping_active = false;
m_angular_damping_active = false;
m_error_accumulator.setValue(0.0,0.0,0.0);
@@ -389,8 +396,8 @@ static unsigned char mathutils_kxobactu_vector_cb_index = -1; /* index for our c
static int mathutils_obactu_generic_check(BaseMathObject *bmo)
{
- KX_ObjectActuator* self= static_cast<KX_ObjectActuator*>BGE_PROXY_REF(bmo->cb_user);
- if (self==NULL)
+ KX_ObjectActuator* self = static_cast<KX_ObjectActuator*>BGE_PROXY_REF(bmo->cb_user);
+ if (self == NULL)
return -1;
return 0;
@@ -398,11 +405,11 @@ static int mathutils_obactu_generic_check(BaseMathObject *bmo)
static int mathutils_obactu_vector_get(BaseMathObject *bmo, int subtype)
{
- KX_ObjectActuator* self= static_cast<KX_ObjectActuator*>BGE_PROXY_REF(bmo->cb_user);
- if (self==NULL)
+ KX_ObjectActuator* self = static_cast<KX_ObjectActuator*>BGE_PROXY_REF(bmo->cb_user);
+ if (self == NULL)
return -1;
- switch(subtype) {
+ switch (subtype) {
case MATHUTILS_VEC_CB_LINV:
self->m_linear_velocity.getValue(bmo->data);
break;
@@ -416,11 +423,11 @@ static int mathutils_obactu_vector_get(BaseMathObject *bmo, int subtype)
static int mathutils_obactu_vector_set(BaseMathObject *bmo, int subtype)
{
- KX_ObjectActuator* self= static_cast<KX_ObjectActuator*>BGE_PROXY_REF(bmo->cb_user);
- if (self==NULL)
+ KX_ObjectActuator* self = static_cast<KX_ObjectActuator*>BGE_PROXY_REF(bmo->cb_user);
+ if (self == NULL)
return -1;
- switch(subtype) {
+ switch (subtype) {
case MATHUTILS_VEC_CB_LINV:
self->m_linear_velocity.setValue(bmo->data);
break;
@@ -442,13 +449,13 @@ static int mathutils_obactu_vector_get_index(BaseMathObject *bmo, int subtype, i
static int mathutils_obactu_vector_set_index(BaseMathObject *bmo, int subtype, int index)
{
- float f= bmo->data[index];
+ float f = bmo->data[index];
/* lazy, avoid repeteing the case statement */
if (mathutils_obactu_vector_get(bmo, subtype) == -1)
return -1;
- bmo->data[index]= f;
+ bmo->data[index] = f;
return mathutils_obactu_vector_set(bmo, subtype);
}
@@ -460,14 +467,14 @@ Mathutils_Callback mathutils_obactu_vector_cb = {
mathutils_obactu_vector_set_index
};
-PyObject* KX_ObjectActuator::pyattr_get_linV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_ObjectActuator::pyattr_get_linV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxobactu_vector_cb_index, MATHUTILS_VEC_CB_LINV);
}
int KX_ObjectActuator::pyattr_set_linV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_ObjectActuator* self= static_cast<KX_ObjectActuator*>(self_v);
+ KX_ObjectActuator* self = static_cast<KX_ObjectActuator*>(self_v);
if (!PyVecTo(value, self->m_linear_velocity))
return PY_SET_ATTR_FAIL;
@@ -476,14 +483,14 @@ int KX_ObjectActuator::pyattr_set_linV(void *self_v, const KX_PYATTRIBUTE_DEF *a
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_ObjectActuator::pyattr_get_angV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_ObjectActuator::pyattr_get_angV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxobactu_vector_cb_index, MATHUTILS_VEC_CB_ANGV);
}
int KX_ObjectActuator::pyattr_set_angV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_ObjectActuator* self= static_cast<KX_ObjectActuator*>(self_v);
+ KX_ObjectActuator* self = static_cast<KX_ObjectActuator*>(self_v);
if (!PyVecTo(value, self->m_angular_velocity))
return PY_SET_ATTR_FAIL;
@@ -501,7 +508,7 @@ void KX_ObjectActuator_Mathutils_Callback_Init(void)
#endif // USE_MATHUTILS
-PyObject* KX_ObjectActuator::pyattr_get_forceLimitX(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_ObjectActuator::pyattr_get_forceLimitX(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
PyObject *retVal = PyList_New(3);
@@ -517,7 +524,7 @@ int KX_ObjectActuator::pyattr_set_forceLimitX(void *self_v, const KX_PYATTRIBUTE
{
KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
- PyObject* seq = PySequence_Fast(value, "");
+ PyObject *seq = PySequence_Fast(value, "");
if (seq && PySequence_Fast_GET_SIZE(seq) == 3)
{
self->m_drot[0] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0));
@@ -537,7 +544,7 @@ int KX_ObjectActuator::pyattr_set_forceLimitX(void *self_v, const KX_PYATTRIBUTE
return PY_SET_ATTR_FAIL;
}
-PyObject* KX_ObjectActuator::pyattr_get_forceLimitY(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_ObjectActuator::pyattr_get_forceLimitY(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
PyObject *retVal = PyList_New(3);
@@ -553,7 +560,7 @@ int KX_ObjectActuator::pyattr_set_forceLimitY(void *self_v, const KX_PYATTRIBUTE
{
KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
- PyObject* seq = PySequence_Fast(value, "");
+ PyObject *seq = PySequence_Fast(value, "");
if (seq && PySequence_Fast_GET_SIZE(seq) == 3)
{
self->m_drot[1] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0));
@@ -573,7 +580,7 @@ int KX_ObjectActuator::pyattr_set_forceLimitY(void *self_v, const KX_PYATTRIBUTE
return PY_SET_ATTR_FAIL;
}
-PyObject* KX_ObjectActuator::pyattr_get_forceLimitZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_ObjectActuator::pyattr_get_forceLimitZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
PyObject *retVal = PyList_New(3);
@@ -589,7 +596,7 @@ int KX_ObjectActuator::pyattr_set_forceLimitZ(void *self_v, const KX_PYATTRIBUTE
{
KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
- PyObject* seq = PySequence_Fast(value, "");
+ PyObject *seq = PySequence_Fast(value, "");
if (seq && PySequence_Fast_GET_SIZE(seq) == 3)
{
self->m_drot[2] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0));
@@ -609,7 +616,7 @@ int KX_ObjectActuator::pyattr_set_forceLimitZ(void *self_v, const KX_PYATTRIBUTE
return PY_SET_ATTR_FAIL;
}
-PyObject* KX_ObjectActuator::pyattr_get_reference(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_ObjectActuator::pyattr_get_reference(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_ObjectActuator* actuator = static_cast<KX_ObjectActuator*>(self);
if (!actuator->m_reference)
@@ -632,7 +639,7 @@ int KX_ObjectActuator::pyattr_set_reference(void *self, const struct KX_PYATTRIB
if (refOb==NULL) {
actuator->m_reference= NULL;
}
- else {
+ else {
actuator->m_reference = refOb;
actuator->m_reference->RegisterActuator(actuator);
}
diff --git a/source/gameengine/Ketsji/KX_ObjectActuator.h b/source/gameengine/Ketsji/KX_ObjectActuator.h
index 397234488b7..b0efee550af 100644
--- a/source/gameengine/Ketsji/KX_ObjectActuator.h
+++ b/source/gameengine/Ketsji/KX_ObjectActuator.h
@@ -218,9 +218,8 @@ public:
return 0;
}
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif //__KX_OBJECTACTUATOR_H__
-
+#endif /* __KX_OBJECTACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_ObstacleSimulation.cpp b/source/gameengine/Ketsji/KX_ObstacleSimulation.cpp
index a942f87856c..99d9fc7f9ee 100644
--- a/source/gameengine/Ketsji/KX_ObstacleSimulation.cpp
+++ b/source/gameengine/Ketsji/KX_ObstacleSimulation.cpp
@@ -257,7 +257,7 @@ void KX_ObstacleSimulation::AddObstacleForObj(KX_GameObject* gameobj)
}
void KX_ObstacleSimulation::AddObstaclesForNavMesh(KX_NavMeshObject* navmeshobj)
-{
+{
dtStatNavMesh* navmesh = navmeshobj->GetNavMesh();
if (navmesh)
{
@@ -267,7 +267,7 @@ void KX_ObstacleSimulation::AddObstaclesForNavMesh(KX_NavMeshObject* navmeshobj)
const dtStatPoly* poly = navmesh->getPoly(pi);
for (int i = 0, j = (int)poly->nv-1; i < (int)poly->nv; j = i++)
- {
+ {
if (poly->n[j]) continue;
const float* vj = navmesh->getVertex(poly->v[j]);
const float* vi = navmesh->getVertex(poly->v[i]);
@@ -364,9 +364,9 @@ void KX_ObstacleSimulation::DrawObstacles()
else if (m_obstacles[i]->m_shape==KX_OBSTACLE_CIRCLE)
{
KX_RasterizerDrawDebugCircle(m_obstacles[i]->m_pos, m_obstacles[i]->m_rad, bluecolor,
- normal, SECTORS_NUM);
+ normal, SECTORS_NUM);
}
- }
+ }
}
static MT_Point3 nearestPointToObstacle(MT_Point3& pos ,KX_Obstacle* obstacle)
@@ -424,7 +424,7 @@ KX_ObstacleSimulationTOI::KX_ObstacleSimulationTOI(MT_Scalar levelHeight, bool e
void KX_ObstacleSimulationTOI::AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- MT_Vector3& velocity, MT_Scalar maxDeltaSpeed, MT_Scalar maxDeltaAngle)
+ MT_Vector3& velocity, MT_Scalar maxDeltaSpeed, MT_Scalar maxDeltaAngle)
{
int nobs = m_obstacles.size();
int obstidx = std::find(m_obstacles.begin(), m_obstacles.end(), activeObst) - m_obstacles.begin();
@@ -446,7 +446,7 @@ void KX_ObstacleSimulationTOI::AdjustObstacleVelocity(KX_Obstacle* activeObst, K
vadd(vel, activeObst->vel, dv);
velocity.x() = vel[0];
- velocity.y() = vel[1];
+ velocity.y() = vel[1];
}
///////////*********TOI_rays**********/////////////////
@@ -642,7 +642,7 @@ static void processSamples(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavM
for (int n = 0; n < nspos; ++n)
{
float vcand[2];
- vcpy(vcand, &spos[n*2]);
+ vcpy(vcand, &spos[n*2]);
// Find min time of impact and exit amongst all obstacles.
float tmin = maxToi;
diff --git a/source/gameengine/Ketsji/KX_ObstacleSimulation.h b/source/gameengine/Ketsji/KX_ObstacleSimulation.h
index 5b359fc031e..50589b5bc69 100644
--- a/source/gameengine/Ketsji/KX_ObstacleSimulation.h
+++ b/source/gameengine/Ketsji/KX_ObstacleSimulation.h
@@ -34,13 +34,13 @@ class KX_GameObject;
class KX_NavMeshObject;
enum KX_OBSTACLE_TYPE
-{
+{
KX_OBSTACLE_OBJ,
KX_OBSTACLE_NAV_MESH,
};
enum KX_OBSTACLE_SHAPE
-{
+{
KX_OBSTACLE_CIRCLE,
KX_OBSTACLE_SEGMENT,
};
@@ -86,9 +86,9 @@ public:
void DestroyObstacleForObj(KX_GameObject* gameobj);
void AddObstaclesForNavMesh(KX_NavMeshObject* navmesh);
KX_Obstacle* GetObstacle(KX_GameObject* gameobj);
- void UpdateObstacles();
+ void UpdateObstacles();
virtual void AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- MT_Vector3& velocity, MT_Scalar maxDeltaSpeed,MT_Scalar maxDeltaAngle);
+ MT_Vector3& velocity, MT_Scalar maxDeltaSpeed,MT_Scalar maxDeltaAngle);
};
class KX_ObstacleSimulationTOI: public KX_ObstacleSimulation
diff --git a/source/gameengine/Ketsji/KX_ParentActuator.cpp b/source/gameengine/Ketsji/KX_ParentActuator.cpp
index 5058af18d15..6926fdb1d4c 100644
--- a/source/gameengine/Ketsji/KX_ParentActuator.cpp
+++ b/source/gameengine/Ketsji/KX_ParentActuator.cpp
@@ -172,10 +172,10 @@ PyAttributeDef KX_ParentActuator::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_ParentActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_ParentActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_ParentActuator* actuator = static_cast<KX_ParentActuator*>(self);
- if (!actuator->m_ob)
+ if (!actuator->m_ob)
Py_RETURN_NONE;
else
return actuator->m_ob->GetProxy();
@@ -190,7 +190,7 @@ int KX_ParentActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBUTE
return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
if (actuator->m_ob != NULL)
- actuator->m_ob->UnregisterActuator(actuator);
+ actuator->m_ob->UnregisterActuator(actuator);
actuator->m_ob = (SCA_IObject*) gameobj;
diff --git a/source/gameengine/Ketsji/KX_ParentActuator.h b/source/gameengine/Ketsji/KX_ParentActuator.h
index 6191b889da3..40baac6b2b2 100644
--- a/source/gameengine/Ketsji/KX_ParentActuator.h
+++ b/source/gameengine/Ketsji/KX_ParentActuator.h
@@ -81,12 +81,11 @@ public:
/* --------------------------------------------------------------------- */
/* These are used to get and set m_ob */
- static PyObject* pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
}; /* end of class KX_ParentActuator : public SCA_PropertyActuator */
-#endif
-
+#endif /* __KX_PARENTACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_PhysicsEngineEnums.h b/source/gameengine/Ketsji/KX_PhysicsEngineEnums.h
index 5cebedf8c30..ca99c2e7526 100644
--- a/source/gameengine/Ketsji/KX_PhysicsEngineEnums.h
+++ b/source/gameengine/Ketsji/KX_PhysicsEngineEnums.h
@@ -39,5 +39,4 @@ enum e_PhysicsEngine
UseBullet = 5,
};
-#endif //__KX_PHYSICSENGINEENUMS_H__
-
+#endif /* __KX_PHYSICSENGINEENUMS_H__ */
diff --git a/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp b/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp
index 225a1628b3b..f18c35c0c78 100644
--- a/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp
+++ b/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp
@@ -51,7 +51,7 @@ KX_PhysicsObjectWrapper::~KX_PhysicsObjectWrapper()
#ifdef WITH_PYTHON
-PyObject* KX_PhysicsObjectWrapper::PySetPosition(PyObject* args)
+PyObject *KX_PhysicsObjectWrapper::PySetPosition(PyObject *args)
{
float x,y,z;
if (PyArg_ParseTuple(args,"fff:setPosition",&x,&y,&z))
@@ -65,7 +65,7 @@ PyObject* KX_PhysicsObjectWrapper::PySetPosition(PyObject* args)
}
-PyObject* KX_PhysicsObjectWrapper::PySetLinearVelocity(PyObject* args)
+PyObject *KX_PhysicsObjectWrapper::PySetLinearVelocity(PyObject *args)
{
float x,y,z;
int local;
@@ -79,7 +79,7 @@ PyObject* KX_PhysicsObjectWrapper::PySetLinearVelocity(PyObject* args)
Py_RETURN_NONE;
}
-PyObject* KX_PhysicsObjectWrapper::PySetAngularVelocity(PyObject* args)
+PyObject *KX_PhysicsObjectWrapper::PySetAngularVelocity(PyObject *args)
{
float x,y,z;
int local;
@@ -93,7 +93,7 @@ PyObject* KX_PhysicsObjectWrapper::PySetAngularVelocity(PyObject* args)
Py_RETURN_NONE;
}
-PyObject* KX_PhysicsObjectWrapper::PySetActive(PyObject* args)
+PyObject* KX_PhysicsObjectWrapper::PySetActive(PyObject *args)
{
int active;
if (PyArg_ParseTuple(args,"i:setActive",&active))
diff --git a/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.h b/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.h
index a074ff9a3bd..171416c5e8f 100644
--- a/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.h
+++ b/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.h
@@ -49,12 +49,11 @@ public:
KX_PYMETHOD_VARARGS(KX_PhysicsObjectWrapper,SetAngularVelocity);
KX_PYMETHOD_VARARGS(KX_PhysicsObjectWrapper,SetActive);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
private:
class PHY_IPhysicsController* m_ctrl;
PHY_IPhysicsEnvironment* m_physenv;
};
-#endif //__KX_PHYSICSOBJECTWRAPPER_H__
-
+#endif /* __KX_PHYSICSOBJECTWRAPPER_H__ */
diff --git a/source/gameengine/Ketsji/KX_PhysicsPropertiesobsolete.h b/source/gameengine/Ketsji/KX_PhysicsPropertiesobsolete.h
index 86ba2500763..ee685edb9c1 100644
--- a/source/gameengine/Ketsji/KX_PhysicsPropertiesobsolete.h
+++ b/source/gameengine/Ketsji/KX_PhysicsPropertiesobsolete.h
@@ -58,5 +58,4 @@ struct KX_MaterialProps {
bool m_fh_normal; // Should the object slide off slopes?
};
-#endif //__KX_PHYSICSPROPERTIESOBSOLETE_H__
-
+#endif /* __KX_PHYSICSPROPERTIESOBSOLETE_H__ */
diff --git a/source/gameengine/Ketsji/KX_PolyProxy.cpp b/source/gameengine/Ketsji/KX_PolyProxy.cpp
index 85c88337d60..465e91ffb32 100644
--- a/source/gameengine/Ketsji/KX_PolyProxy.cpp
+++ b/source/gameengine/Ketsji/KX_PolyProxy.cpp
@@ -102,7 +102,7 @@ KX_PolyProxy::~KX_PolyProxy()
// stuff for cvalue related things
CValue* KX_PolyProxy::Calc(VALUE_OPERATOR, CValue *) { return NULL;}
-CValue* KX_PolyProxy::CalcFinal(VALUE_DATA_TYPE, VALUE_OPERATOR, CValue *) { return NULL;}
+CValue* KX_PolyProxy::CalcFinal(VALUE_DATA_TYPE, VALUE_OPERATOR, CValue *) { return NULL;}
STR_String sPolyName="polygone";
const STR_String & KX_PolyProxy::GetText() {return sPolyName;};
double KX_PolyProxy::GetNumber() { return -1;}
@@ -112,54 +112,54 @@ CValue* KX_PolyProxy::GetReplica() { return NULL;}
// stuff for python integration
-PyObject* KX_PolyProxy::pyattr_get_material_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolyProxy::pyattr_get_material_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolyProxy* self= static_cast<KX_PolyProxy*>(self_v);
+ KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
return self->PygetMaterialName();
}
-PyObject* KX_PolyProxy::pyattr_get_texture_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolyProxy::pyattr_get_texture_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolyProxy* self= static_cast<KX_PolyProxy*>(self_v);
+ KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
return self->PygetTextureName();
}
-PyObject* KX_PolyProxy::pyattr_get_material(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolyProxy::pyattr_get_material(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolyProxy* self= static_cast<KX_PolyProxy*>(self_v);
+ KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
return self->PygetMaterial();
}
-PyObject* KX_PolyProxy::pyattr_get_material_id(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolyProxy::pyattr_get_material_id(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolyProxy* self= static_cast<KX_PolyProxy*>(self_v);
+ KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
return self->PygetMaterialIndex();
}
-PyObject* KX_PolyProxy::pyattr_get_v1(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolyProxy::pyattr_get_v1(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolyProxy* self= static_cast<KX_PolyProxy*>(self_v);
+ KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
return PyLong_FromSsize_t(self->m_polygon->GetVertexOffsetAbs(self->m_mesh, 0));
}
-PyObject* KX_PolyProxy::pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolyProxy::pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolyProxy* self= static_cast<KX_PolyProxy*>(self_v);
+ KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
return PyLong_FromSsize_t(self->m_polygon->GetVertexOffsetAbs(self->m_mesh, 1));
}
-PyObject* KX_PolyProxy::pyattr_get_v3(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolyProxy::pyattr_get_v3(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolyProxy* self= static_cast<KX_PolyProxy*>(self_v);
+ KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
return PyLong_FromSsize_t(self->m_polygon->GetVertexOffsetAbs(self->m_mesh, 2));
}
-PyObject* KX_PolyProxy::pyattr_get_v4(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolyProxy::pyattr_get_v4(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolyProxy* self= static_cast<KX_PolyProxy*>(self_v);
+ KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
if (3 < self->m_polygon->VertexCount())
{
@@ -168,15 +168,15 @@ PyObject* KX_PolyProxy::pyattr_get_v4(void *self_v, const KX_PYATTRIBUTE_DEF *at
return PyLong_FromSsize_t(0);
}
-PyObject* KX_PolyProxy::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolyProxy::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolyProxy* self= static_cast<KX_PolyProxy*>(self_v);
+ KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
return self->PyisVisible();
}
-PyObject* KX_PolyProxy::pyattr_get_collide(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolyProxy::pyattr_get_collide(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolyProxy* self= static_cast<KX_PolyProxy*>(self_v);
+ KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
return self->PyisCollider();
}
diff --git a/source/gameengine/Ketsji/KX_PolyProxy.h b/source/gameengine/Ketsji/KX_PolyProxy.h
index 83c3bff0ee2..f02aa90998e 100644
--- a/source/gameengine/Ketsji/KX_PolyProxy.h
+++ b/source/gameengine/Ketsji/KX_PolyProxy.h
@@ -57,16 +57,16 @@ public:
// stuff for python integration
- static PyObject* pyattr_get_material_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_texture_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_material(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_material_id(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_v1(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_v3(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_v4(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_collide(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_material_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_texture_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_material(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_material_id(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_v1(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_v3(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_v4(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_collide(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMaterialIndex)
KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getNumVertex)
@@ -80,7 +80,6 @@ public:
};
-#endif // WITH_PYTHON
-
-#endif //__KX_POLYPROXY
+#endif /* WITH_PYTHON */
+#endif /* __KX_POLYPROXY */
diff --git a/source/gameengine/Ketsji/KX_PolygonMaterial.cpp b/source/gameengine/Ketsji/KX_PolygonMaterial.cpp
index 2e39190f4f9..36c94dc997b 100644
--- a/source/gameengine/Ketsji/KX_PolygonMaterial.cpp
+++ b/source/gameengine/Ketsji/KX_PolygonMaterial.cpp
@@ -143,7 +143,7 @@ bool KX_PolygonMaterial::Activate(RAS_IRasterizer* rasty, TCachingInfo& cachingI
{
PyObject *pyRasty = PyCapsule_New((void*)rasty, KX_POLYGONMATERIAL_CAPSULE_ID, NULL); /* new reference */
PyObject *pyCachingInfo = PyCapsule_New((void*) &cachingInfo, KX_POLYGONMATERIAL_CAPSULE_ID, NULL); /* new reference */
- PyObject *ret = PyObject_CallMethod(m_pymaterial, (char *)"activate", (char *)"(NNO)", pyRasty, pyCachingInfo, (PyObject*) this->m_proxy);
+ PyObject *ret = PyObject_CallMethod(m_pymaterial, (char *)"activate", (char *)"(NNO)", pyRasty, pyCachingInfo, (PyObject *) this->m_proxy);
if (ret)
{
bool value = PyLong_AsSsize_t(ret);
@@ -252,7 +252,7 @@ PyAttributeDef KX_PolygonMaterial::Attributes[] = {
KX_PYATTRIBUTE_INT_RW("tile", INT_MIN, INT_MAX, true, KX_PolygonMaterial, m_tile),
KX_PYATTRIBUTE_INT_RW("tilexrep", INT_MIN, INT_MAX, true, KX_PolygonMaterial, m_tilexrep),
KX_PYATTRIBUTE_INT_RW("tileyrep", INT_MIN, INT_MAX, true, KX_PolygonMaterial, m_tileyrep),
- KX_PYATTRIBUTE_INT_RW("drawingmode", INT_MIN, INT_MAX, true, KX_PolygonMaterial, m_drawingmode),
+ KX_PYATTRIBUTE_INT_RW("drawingmode", INT_MIN, INT_MAX, true, KX_PolygonMaterial, m_drawingmode),
//KX_PYATTRIBUTE_INT_RW("lightlayer", INT_MIN, INT_MAX, true, KX_PolygonMaterial, m_lightlayer),
KX_PYATTRIBUTE_BOOL_RW("transparent", KX_PolygonMaterial, m_alpha),
@@ -262,7 +262,7 @@ PyAttributeDef KX_PolygonMaterial::Attributes[] = {
KX_PYATTRIBUTE_FLOAT_RW("specularity", 0.0f, 1000.0f, KX_PolygonMaterial, m_specularity),
KX_PYATTRIBUTE_RW_FUNCTION("diffuse", KX_PolygonMaterial, pyattr_get_diffuse, pyattr_set_diffuse),
- KX_PYATTRIBUTE_RW_FUNCTION("specular",KX_PolygonMaterial, pyattr_get_specular, pyattr_set_specular),
+ KX_PYATTRIBUTE_RW_FUNCTION("specular",KX_PolygonMaterial, pyattr_get_specular, pyattr_set_specular),
KX_PYATTRIBUTE_RO_FUNCTION("tface", KX_PolygonMaterial, pyattr_get_tface), /* How the heck is this even useful??? - Campbell */
KX_PYATTRIBUTE_RO_FUNCTION("gl_texture", KX_PolygonMaterial, pyattr_get_gl_texture), /* could be called 'bindcode' */
@@ -355,28 +355,28 @@ KX_PYMETHODDEF_DOC(KX_PolygonMaterial, activate, "activate(rasty, cachingInfo)")
return NULL;
}
-PyObject* KX_PolygonMaterial::pyattr_get_texture(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolygonMaterial::pyattr_get_texture(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolygonMaterial* self= static_cast<KX_PolygonMaterial*>(self_v);
+ KX_PolygonMaterial* self = static_cast<KX_PolygonMaterial*>(self_v);
return PyUnicode_From_STR_String(self->m_texturename);
}
-PyObject* KX_PolygonMaterial::pyattr_get_material(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolygonMaterial::pyattr_get_material(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolygonMaterial* self= static_cast<KX_PolygonMaterial*>(self_v);
+ KX_PolygonMaterial* self = static_cast<KX_PolygonMaterial*>(self_v);
return PyUnicode_From_STR_String(self->m_materialname);
}
/* this does not seem useful */
-PyObject* KX_PolygonMaterial::pyattr_get_tface(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolygonMaterial::pyattr_get_tface(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolygonMaterial* self= static_cast<KX_PolygonMaterial*>(self_v);
+ KX_PolygonMaterial* self = static_cast<KX_PolygonMaterial*>(self_v);
return PyCapsule_New(&self->m_tface, KX_POLYGONMATERIAL_CAPSULE_ID, NULL);
}
-PyObject* KX_PolygonMaterial::pyattr_get_gl_texture(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolygonMaterial::pyattr_get_gl_texture(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolygonMaterial* self= static_cast<KX_PolygonMaterial*>(self_v);
+ KX_PolygonMaterial* self = static_cast<KX_PolygonMaterial*>(self_v);
int bindcode= 0;
if (self->m_tface.tpage)
bindcode= self->m_tface.tpage->bindcode;
@@ -385,15 +385,15 @@ PyObject* KX_PolygonMaterial::pyattr_get_gl_texture(void *self_v, const KX_PYATT
}
-PyObject* KX_PolygonMaterial::pyattr_get_diffuse(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolygonMaterial::pyattr_get_diffuse(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolygonMaterial* self= static_cast<KX_PolygonMaterial*>(self_v);
+ KX_PolygonMaterial* self = static_cast<KX_PolygonMaterial*>(self_v);
return PyObjectFrom(self->m_diffuse);
}
int KX_PolygonMaterial::pyattr_set_diffuse(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_PolygonMaterial* self= static_cast<KX_PolygonMaterial*>(self_v);
+ KX_PolygonMaterial* self = static_cast<KX_PolygonMaterial*>(self_v);
MT_Vector3 vec;
if (!PyVecTo(value, vec))
@@ -403,15 +403,15 @@ int KX_PolygonMaterial::pyattr_set_diffuse(void *self_v, const KX_PYATTRIBUTE_DE
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_PolygonMaterial::pyattr_get_specular(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_PolygonMaterial::pyattr_get_specular(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_PolygonMaterial* self= static_cast<KX_PolygonMaterial*>(self_v);
+ KX_PolygonMaterial* self = static_cast<KX_PolygonMaterial*>(self_v);
return PyObjectFrom(self->m_specular);
}
int KX_PolygonMaterial::pyattr_set_specular(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_PolygonMaterial* self= static_cast<KX_PolygonMaterial*>(self_v);
+ KX_PolygonMaterial* self = static_cast<KX_PolygonMaterial*>(self_v);
MT_Vector3 vec;
if (!PyVecTo(value, vec))
diff --git a/source/gameengine/Ketsji/KX_PolygonMaterial.h b/source/gameengine/Ketsji/KX_PolygonMaterial.h
index f7ad3973212..89bfb4ff9fb 100644
--- a/source/gameengine/Ketsji/KX_PolygonMaterial.h
+++ b/source/gameengine/Ketsji/KX_PolygonMaterial.h
@@ -137,7 +137,7 @@ public:
KX_PYMETHOD_DOC(KX_PolygonMaterial, setCustomMaterial);
KX_PYMETHOD_DOC(KX_PolygonMaterial, loadProgram);
- virtual PyObject* py_repr(void) { return PyUnicode_FromString(m_material ? ((ID *)m_material)->name+2 : ""); }
+ virtual PyObject *py_repr(void) { return PyUnicode_FromString(m_material ? ((ID *)m_material)->name+2 : ""); }
static PyObject* pyattr_get_texture(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static PyObject* pyattr_get_material(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
@@ -145,13 +145,12 @@ public:
static PyObject* pyattr_get_tface(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static PyObject* pyattr_get_gl_texture(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_diffuse(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject* pyattr_get_diffuse(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_diffuse(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_specular(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject* pyattr_get_specular(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_specular(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
#endif
};
-#endif // __KX_POLYGONMATERIAL_H__
-
+#endif /* __KX_POLYGONMATERIAL_H__ */
diff --git a/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp b/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
index 556d451cf66..4475ac8ec96 100644
--- a/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
+++ b/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
@@ -33,12 +33,15 @@
#include "PHY_IPhysicsEnvironment.h"
#include "KX_ConstraintWrapper.h"
#include "KX_VehicleWrapper.h"
+#include "KX_CharacterWrapper.h"
#include "KX_PhysicsObjectWrapper.h"
#include "PHY_IPhysicsController.h"
#include "PHY_IVehicle.h"
#include "PHY_DynamicTypes.h"
#include "MT_Matrix3x3.h"
+#include "KX_GameObject.h" // ConvertPythonToGameObject()
+
#include "PyObjectPlus.h"
#ifdef USE_BULLET
@@ -81,6 +84,7 @@ static char gPySetSolverType__doc__[] = "setSolverType(int solverType) Very expe
static char gPyCreateConstraint__doc__[] = "createConstraint(ob1,ob2,float restLength,float restitution,float damping)";
static char gPyGetVehicleConstraint__doc__[] = "getVehicleConstraint(int constraintId)";
+static char gPyGetCharacter__doc__[] = "getCharacter(KX_GameObject obj)";
static char gPyRemoveConstraint__doc__[] = "removeConstraint(int constraintId)";
static char gPyGetAppliedImpulse__doc__[] = "getAppliedImpulse(int constraintId)";
@@ -89,9 +93,9 @@ static char gPyGetAppliedImpulse__doc__[] = "getAppliedImpulse(int constraintId)
-static PyObject* gPySetGravity(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetGravity(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
float x,y,z;
if (PyArg_ParseTuple(args,"fff",&x,&y,&z))
@@ -106,9 +110,9 @@ static PyObject* gPySetGravity(PyObject* self,
Py_RETURN_NONE;
}
-static PyObject* gPySetDebugMode(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetDebugMode(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
int mode;
if (PyArg_ParseTuple(args,"i",&mode))
@@ -129,9 +133,9 @@ static PyObject* gPySetDebugMode(PyObject* self,
-static PyObject* gPySetNumTimeSubSteps(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetNumTimeSubSteps(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
int substep;
if (PyArg_ParseTuple(args,"i",&substep))
@@ -148,9 +152,9 @@ static PyObject* gPySetNumTimeSubSteps(PyObject* self,
}
-static PyObject* gPySetNumIterations(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetNumIterations(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
int iter;
if (PyArg_ParseTuple(args,"i",&iter))
@@ -167,9 +171,9 @@ static PyObject* gPySetNumIterations(PyObject* self,
}
-static PyObject* gPySetDeactivationTime(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetDeactivationTime(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
float deactive_time;
if (PyArg_ParseTuple(args,"f",&deactive_time))
@@ -186,9 +190,9 @@ static PyObject* gPySetDeactivationTime(PyObject* self,
}
-static PyObject* gPySetDeactivationLinearTreshold(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetDeactivationLinearTreshold(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
float linearDeactivationTreshold;
if (PyArg_ParseTuple(args,"f",&linearDeactivationTreshold))
@@ -205,9 +209,9 @@ static PyObject* gPySetDeactivationLinearTreshold(PyObject* self,
}
-static PyObject* gPySetDeactivationAngularTreshold(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetDeactivationAngularTreshold(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
float angularDeactivationTreshold;
if (PyArg_ParseTuple(args,"f",&angularDeactivationTreshold))
@@ -223,9 +227,9 @@ static PyObject* gPySetDeactivationAngularTreshold(PyObject* self,
Py_RETURN_NONE;
}
-static PyObject* gPySetContactBreakingTreshold(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetContactBreakingTreshold(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
float contactBreakingTreshold;
if (PyArg_ParseTuple(args,"f",&contactBreakingTreshold))
@@ -242,9 +246,9 @@ static PyObject* gPySetContactBreakingTreshold(PyObject* self,
}
-static PyObject* gPySetCcdMode(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetCcdMode(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
float ccdMode;
if (PyArg_ParseTuple(args,"f",&ccdMode))
@@ -260,9 +264,9 @@ static PyObject* gPySetCcdMode(PyObject* self,
Py_RETURN_NONE;
}
-static PyObject* gPySetSorConstant(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetSorConstant(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
float sor;
if (PyArg_ParseTuple(args,"f",&sor))
@@ -278,9 +282,9 @@ static PyObject* gPySetSorConstant(PyObject* self,
Py_RETURN_NONE;
}
-static PyObject* gPySetSolverTau(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetSolverTau(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
float tau;
if (PyArg_ParseTuple(args,"f",&tau))
@@ -297,9 +301,9 @@ static PyObject* gPySetSolverTau(PyObject* self,
}
-static PyObject* gPySetSolverDamping(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetSolverDamping(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
float damping;
if (PyArg_ParseTuple(args,"f",&damping))
@@ -315,9 +319,9 @@ static PyObject* gPySetSolverDamping(PyObject* self,
Py_RETURN_NONE;
}
-static PyObject* gPySetLinearAirDamping(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetLinearAirDamping(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
float damping;
if (PyArg_ParseTuple(args,"f",&damping))
@@ -334,9 +338,9 @@ static PyObject* gPySetLinearAirDamping(PyObject* self,
}
-static PyObject* gPySetUseEpa(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetUseEpa(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
int epa;
if (PyArg_ParseTuple(args,"i",&epa))
@@ -351,9 +355,9 @@ static PyObject* gPySetUseEpa(PyObject* self,
}
Py_RETURN_NONE;
}
-static PyObject* gPySetSolverType(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPySetSolverType(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
int solverType;
if (PyArg_ParseTuple(args,"i",&solverType))
@@ -371,9 +375,9 @@ static PyObject* gPySetSolverType(PyObject* self,
-static PyObject* gPyGetVehicleConstraint(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPyGetVehicleConstraint(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
#if defined(_WIN64)
__int64 constraintid;
@@ -402,10 +406,37 @@ static PyObject* gPyGetVehicleConstraint(PyObject* self,
Py_RETURN_NONE;
}
+static PyObject* gPyGetCharacter(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
+{
+ PyObject* pyob;
+ KX_GameObject *ob;
+
+ if (!PyArg_ParseTuple(args,"O", &pyob))
+ return NULL;
-static PyObject* gPyCreateConstraint(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+ if (!ConvertPythonToGameObject(pyob, &ob, false, "bge.constraints.getCharacter(value)"))
+ return NULL;
+
+ if (PHY_GetActiveEnvironment())
+ {
+
+ PHY_ICharacter* character= PHY_GetActiveEnvironment()->getCharacterController(ob);
+ if (character)
+ {
+ KX_CharacterWrapper* pyWrapper = new KX_CharacterWrapper(character);
+ return pyWrapper->NewProxy(true);
+ }
+
+ }
+
+ Py_RETURN_NONE;
+}
+
+static PyObject *gPyCreateConstraint(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
/* FIXME - physicsid is a long being cast to a pointer, should at least use PyCapsule */
#if defined(_WIN64)
@@ -435,7 +466,7 @@ static PyObject* gPyCreateConstraint(PyObject* self,
#else
success = PyArg_ParseTuple(args,"llifff",&physicsid,&physicsid2,&constrainttype,
&pivotX,&pivotY,&pivotZ);
-#endif
+#endif
}
else if (len == 9)
{
@@ -521,9 +552,9 @@ static PyObject* gPyCreateConstraint(PyObject* self,
-static PyObject* gPyGetAppliedImpulse(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPyGetAppliedImpulse(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
float appliedImpulse = 0.f;
@@ -548,9 +579,9 @@ static PyObject* gPyGetAppliedImpulse(PyObject* self,
}
-static PyObject* gPyRemoveConstraint(PyObject* self,
- PyObject* args,
- PyObject* kwds)
+static PyObject *gPyRemoveConstraint(PyObject *self,
+ PyObject *args,
+ PyObject *kwds)
{
#if defined(_WIN64)
__int64 constraintid;
@@ -572,7 +603,7 @@ static PyObject* gPyRemoveConstraint(PyObject* self,
Py_RETURN_NONE;
}
-static PyObject* gPyExportBulletFile(PyObject*, PyObject* args)
+static PyObject *gPyExportBulletFile(PyObject *, PyObject *args)
{
char* filename;
if (!PyArg_ParseTuple(args,"s:exportBulletFile",&filename))
@@ -631,6 +662,9 @@ static struct PyMethodDef physicsconstraints_methods[] = {
{"getVehicleConstraint",(PyCFunction) gPyGetVehicleConstraint,
METH_VARARGS, (const char *)gPyGetVehicleConstraint__doc__},
+ {"getCharacter",(PyCFunction) gPyGetCharacter,
+ METH_VARARGS, (const char *)gPyGetCharacter__doc__},
+
{"removeConstraint",(PyCFunction) gPyRemoveConstraint,
METH_VARARGS, (const char *)gPyRemoveConstraint__doc__},
{"getAppliedImpulse",(PyCFunction) gPyGetAppliedImpulse,
@@ -655,13 +689,13 @@ static struct PyModuleDef PhysicsConstraints_module_def = {
0, /* m_free */
};
-PyObject* initPythonConstraintBinding()
+PyObject *initPythonConstraintBinding()
{
- PyObject* ErrorObject;
- PyObject* m;
- PyObject* d;
- PyObject* item;
+ PyObject *ErrorObject;
+ PyObject *m;
+ PyObject *d;
+ PyObject *item;
/* Use existing module where possible
* be careful not to init any runtime vars after this */
@@ -716,10 +750,11 @@ PyObject* initPythonConstraintBinding()
return d;
}
-
-void KX_RemovePythonConstraintBinding()
+#if 0
+static void KX_RemovePythonConstraintBinding()
{
}
+#endif
void PHY_SetActiveEnvironment(class PHY_IPhysicsEnvironment* env)
{
diff --git a/source/gameengine/Ketsji/KX_PyConstraintBinding.h b/source/gameengine/Ketsji/KX_PyConstraintBinding.h
index 69a6e333cee..b4a520ce71b 100644
--- a/source/gameengine/Ketsji/KX_PyConstraintBinding.h
+++ b/source/gameengine/Ketsji/KX_PyConstraintBinding.h
@@ -39,7 +39,6 @@
PyObject* initPythonConstraintBinding();
void PHY_SetActiveEnvironment(class PHY_IPhysicsEnvironment* env);
PHY_IPhysicsEnvironment* PHY_GetActiveEnvironment();
-#endif // WITH_PYTHON
-
-#endif //__KX_PYCONSTRAINTBINDING_H__
+#endif /* WITH_PYTHON */
+#endif /* __KX_PYCONSTRAINTBINDING_H__ */
diff --git a/source/gameengine/Ketsji/KX_PyMath.cpp b/source/gameengine/Ketsji/KX_PyMath.cpp
index f459b806d2f..804e8de2ad1 100644
--- a/source/gameengine/Ketsji/KX_PyMath.cpp
+++ b/source/gameengine/Ketsji/KX_PyMath.cpp
@@ -31,9 +31,9 @@
*/
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
+#endif
#ifdef WITH_PYTHON
@@ -47,7 +47,7 @@
#include "KX_Python.h"
#include "KX_PyMath.h"
-bool PyOrientationTo(PyObject* pyval, MT_Matrix3x3 &rot, const char *error_prefix)
+bool PyOrientationTo(PyObject *pyval, MT_Matrix3x3 &rot, const char *error_prefix)
{
int size= PySequence_Size(pyval);
@@ -80,22 +80,22 @@ bool PyOrientationTo(PyObject* pyval, MT_Matrix3x3 &rot, const char *error_prefi
return false;
}
-bool PyQuatTo(PyObject* pyval, MT_Quaternion &qrot)
+bool PyQuatTo(PyObject *pyval, MT_Quaternion &qrot)
{
if (!PyVecTo(pyval, qrot))
return false;
/* annoying!, Blender/Mathutils have the W axis first! */
- MT_Scalar w= qrot[0]; /* from python, this is actually the W */
- qrot[0]= qrot[1];
- qrot[1]= qrot[2];
- qrot[2]= qrot[3];
- qrot[3]= w;
+ MT_Scalar w = qrot[0]; /* from python, this is actually the W */
+ qrot[0] = qrot[1];
+ qrot[1] = qrot[2];
+ qrot[2] = qrot[3];
+ qrot[3] = w;
return true;
}
-PyObject* PyObjectFrom(const MT_Matrix4x4 &mat)
+PyObject *PyObjectFrom(const MT_Matrix4x4 &mat)
{
#ifdef USE_MATHUTILS
float fmat[16];
@@ -119,7 +119,7 @@ PyObject* PyObjectFrom(const MT_Matrix4x4 &mat)
#endif
}
-PyObject* PyObjectFrom(const MT_Matrix3x3 &mat)
+PyObject *PyObjectFrom(const MT_Matrix3x3 &mat)
{
#ifdef USE_MATHUTILS
float fmat[9];
@@ -143,7 +143,7 @@ PyObject* PyObjectFrom(const MT_Matrix3x3 &mat)
}
#ifdef USE_MATHUTILS
-PyObject* PyObjectFrom(const MT_Quaternion &qrot)
+PyObject *PyObjectFrom(const MT_Quaternion &qrot)
{
/* NOTE, were re-ordering here for Mathutils compat */
float fvec[4];
@@ -152,7 +152,7 @@ PyObject* PyObjectFrom(const MT_Quaternion &qrot)
}
#endif
-PyObject* PyObjectFrom(const MT_Tuple4 &vec)
+PyObject *PyObjectFrom(const MT_Tuple4 &vec)
{
#ifdef USE_MATHUTILS
float fvec[4];
@@ -168,7 +168,7 @@ PyObject* PyObjectFrom(const MT_Tuple4 &vec)
#endif
}
-PyObject* PyObjectFrom(const MT_Tuple3 &vec)
+PyObject *PyObjectFrom(const MT_Tuple3 &vec)
{
#ifdef USE_MATHUTILS
float fvec[3];
@@ -180,10 +180,10 @@ PyObject* PyObjectFrom(const MT_Tuple3 &vec)
PyList_SET_ITEM(list, 1, PyFloat_FromDouble(vec[1]));
PyList_SET_ITEM(list, 2, PyFloat_FromDouble(vec[2]));
return list;
-#endif
+#endif
}
-PyObject* PyObjectFrom(const MT_Tuple2 &vec)
+PyObject *PyObjectFrom(const MT_Tuple2 &vec)
{
#ifdef USE_MATHUTILS
float fvec[2];
diff --git a/source/gameengine/Ketsji/KX_PyMath.h b/source/gameengine/Ketsji/KX_PyMath.h
index aec871d7700..159506946e8 100644
--- a/source/gameengine/Ketsji/KX_PyMath.h
+++ b/source/gameengine/Ketsji/KX_PyMath.h
@@ -61,7 +61,7 @@ inline unsigned int Size(const MT_Tuple4&) { return 4; }
* Converts the given python matrix (column-major) to an MT class (row-major).
*/
template<class T>
-bool PyMatTo(PyObject* pymat, T& mat)
+bool PyMatTo(PyObject *pymat, T& mat)
{
bool noerror = true;
mat.setIdentity();
@@ -133,7 +133,7 @@ bool PyMatTo(PyObject* pymat, T& mat)
* Converts a python sequence to a MT class.
*/
template<class T>
-bool PyVecTo(PyObject* pyval, T& vec)
+bool PyVecTo(PyObject *pyval, T& vec)
{
#ifdef USE_MATHUTILS
/* no need for BaseMath_ReadCallback() here, reading the sequences will do this */
@@ -235,42 +235,42 @@ bool PyVecTo(PyObject* pyval, T& vec)
}
-bool PyQuatTo(PyObject* pyval, MT_Quaternion &qrot);
+bool PyQuatTo(PyObject *pyval, MT_Quaternion &qrot);
-bool PyOrientationTo(PyObject* pyval, MT_Matrix3x3 &mat, const char *error_prefix);
+bool PyOrientationTo(PyObject *pyval, MT_Matrix3x3 &mat, const char *error_prefix);
/**
* Converts an MT_Matrix4x4 to a python object.
*/
-PyObject* PyObjectFrom(const MT_Matrix4x4 &mat);
+PyObject *PyObjectFrom(const MT_Matrix4x4 &mat);
/**
* Converts an MT_Matrix3x3 to a python object.
*/
-PyObject* PyObjectFrom(const MT_Matrix3x3 &mat);
+PyObject *PyObjectFrom(const MT_Matrix3x3 &mat);
/**
* Converts an MT_Tuple2 to a python object.
*/
-PyObject* PyObjectFrom(const MT_Tuple2 &vec);
+PyObject *PyObjectFrom(const MT_Tuple2 &vec);
/**
* Converts an MT_Tuple3 to a python object
*/
-PyObject* PyObjectFrom(const MT_Tuple3 &vec);
+PyObject *PyObjectFrom(const MT_Tuple3 &vec);
#ifdef USE_MATHUTILS
/**
* Converts an MT_Quaternion to a python object.
*/
-PyObject* PyObjectFrom(const MT_Quaternion &qrot);
+PyObject *PyObjectFrom(const MT_Quaternion &qrot);
#endif
/**
* Converts an MT_Tuple4 to a python object.
*/
-PyObject* PyObjectFrom(const MT_Tuple4 &pos);
+PyObject *PyObjectFrom(const MT_Tuple4 &pos);
#endif
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
diff --git a/source/gameengine/Ketsji/KX_PythonInit.cpp b/source/gameengine/Ketsji/KX_PythonInit.cpp
index 7d29a20d1a2..7f6655861f1 100644
--- a/source/gameengine/Ketsji/KX_PythonInit.cpp
+++ b/source/gameengine/Ketsji/KX_PythonInit.cpp
@@ -30,54 +30,48 @@
* \ingroup ketsji
*/
-
#include "GL/glew.h"
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
-#endif //WIN32
-
-#ifdef WITH_PYTHON
-
-#ifdef _POSIX_C_SOURCE
-#undef _POSIX_C_SOURCE
-#endif
-
-#ifdef _XOPEN_SOURCE
-#undef _XOPEN_SOURCE
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
#endif
-#if defined(__sun) || defined(sun)
-#if defined(_XPG4)
-#undef _XPG4
-#endif
-#endif
-
-#include <Python.h>
+#ifdef WITH_PYTHON
+# ifdef _POSIX_C_SOURCE
+# undef _POSIX_C_SOURCE
+# endif
+# ifdef _XOPEN_SOURCE
+# undef _XOPEN_SOURCE
+# endif
+# if defined(__sun) || defined(sun)
+# if defined(_XPG4)
+# undef _XPG4
+# endif
+# endif
+# include <Python.h>
extern "C" {
- #include "bpy_internal_import.h" /* from the blender python api, but we want to import text too! */
- #include "py_capi_utils.h"
- #include "mathutils.h" // 'mathutils' module copied here so the blenderlayer can use.
- #include "bgl.h"
- #include "blf_py_api.h"
+ # include "bpy_internal_import.h" /* from the blender python api, but we want to import text too! */
+ # include "py_capi_utils.h"
+ # include "mathutils.h" // 'mathutils' module copied here so the blenderlayer can use.
+ # include "bgl.h"
+ # include "blf_py_api.h"
- #include "marshal.h" /* python header for loading/saving dicts */
+ # include "marshal.h" /* python header for loading/saving dicts */
}
-
#include "AUD_PyInit.h"
-#endif
+#endif /* WITH_PYTHON */
#include "KX_PythonInit.h"
// directory header for py function getBlendFileList
#ifndef WIN32
- #include <dirent.h>
- #include <stdlib.h>
+# include <dirent.h>
+# include <stdlib.h>
#else
- #include <io.h>
- #include "BLI_winstuff.h"
+# include <io.h>
+# include "BLI_winstuff.h"
#endif
//python physics binding
@@ -186,8 +180,8 @@ void KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,cons
gp_Rasterizer->DrawDebugLine(from,to,color);
}
-void KX_RasterizerDrawDebugCircle(const MT_Vector3& center, const MT_Scalar radius, const MT_Vector3& color,
- const MT_Vector3& normal, int nsector)
+void KX_RasterizerDrawDebugCircle(const MT_Vector3& center, const MT_Scalar radius, const MT_Vector3& color,
+ const MT_Vector3& normal, int nsector)
{
if (gp_Rasterizer)
gp_Rasterizer->DrawDebugCircle(center, radius, color, normal, nsector);
@@ -210,15 +204,15 @@ static PyObject *gp_OrigPythonSysModules= NULL;
#include "SCA_PythonController.h"
// List of methods defined in the module
-static PyObject* ErrorObject;
+static PyObject *ErrorObject;
static const char *gPyGetRandomFloat_doc="getRandomFloat returns a random floating point value in the range [0..1]";
-static PyObject* gPyGetRandomFloat(PyObject*)
+static PyObject *gPyGetRandomFloat(PyObject *)
{
return PyFloat_FromDouble(MT_random());
}
-static PyObject* gPySetGravity(PyObject*, PyObject* value)
+static PyObject *gPySetGravity(PyObject *, PyObject *value)
{
MT_Vector3 vec;
if (!PyVecTo(value, vec))
@@ -240,7 +234,7 @@ file to make a full path name (doesn't change during the game, even if you load\
other .blend).\n\
The function also converts the directory separator to the local file system format.";
-static PyObject* gPyExpandPath(PyObject*, PyObject* args)
+static PyObject *gPyExpandPath(PyObject *, PyObject *args)
{
char expanded[FILE_MAX];
char* filename;
@@ -257,7 +251,7 @@ static char gPyStartGame_doc[] =
"startGame(blend)\n\
Loads the blend file";
-static PyObject* gPyStartGame(PyObject*, PyObject* args)
+static PyObject *gPyStartGame(PyObject *, PyObject *args)
{
char* blendfile;
@@ -274,7 +268,7 @@ static char gPyEndGame_doc[] =
"endGame()\n\
Ends the current game";
-static PyObject* gPyEndGame(PyObject*)
+static PyObject *gPyEndGame(PyObject *)
{
gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_QUIT_GAME);
@@ -287,7 +281,7 @@ static char gPyRestartGame_doc[] =
"restartGame()\n\
Restarts the current game by reloading the .blend file";
-static PyObject* gPyRestartGame(PyObject*)
+static PyObject *gPyRestartGame(PyObject *)
{
gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_RESTART_GAME);
gp_KetsjiEngine->SetNameNextGame(gp_GamePythonPath);
@@ -299,7 +293,7 @@ static char gPySaveGlobalDict_doc[] =
"saveGlobalDict()\n"
"Saves bge.logic.globalDict to a file";
-static PyObject* gPySaveGlobalDict(PyObject*)
+static PyObject *gPySaveGlobalDict(PyObject *)
{
char marshal_path[512];
char *marshal_buffer = NULL;
@@ -336,7 +330,7 @@ static char gPyLoadGlobalDict_doc[] =
"LoadGlobalDict()\n"
"Loads bge.logic.globalDict from a file";
-static PyObject* gPyLoadGlobalDict(PyObject*)
+static PyObject *gPyLoadGlobalDict(PyObject *)
{
char marshal_path[512];
char *marshal_buffer = NULL;
@@ -381,7 +375,7 @@ body = Message body\
to = Name of object to send the message to\
from = Name of object to send the string from";
-static PyObject* gPySendMessage(PyObject*, PyObject* args)
+static PyObject *gPySendMessage(PyObject *, PyObject *args)
{
char* subject;
char* body = (char *)"";
@@ -397,9 +391,9 @@ static PyObject* gPySendMessage(PyObject*, PyObject* args)
}
// this gets a pointer to an array filled with floats
-static PyObject* gPyGetSpectrum(PyObject*)
+static PyObject *gPyGetSpectrum(PyObject *)
{
- PyObject* resultlist = PyList_New(512);
+ PyObject *resultlist = PyList_New(512);
for (int index = 0; index < 512; index++)
{
@@ -409,7 +403,7 @@ static PyObject* gPyGetSpectrum(PyObject*)
return resultlist;
}
-static PyObject* gPySetLogicTicRate(PyObject*, PyObject* args)
+static PyObject *gPySetLogicTicRate(PyObject *, PyObject *args)
{
float ticrate;
if (!PyArg_ParseTuple(args, "f:setLogicTicRate", &ticrate))
@@ -419,12 +413,12 @@ static PyObject* gPySetLogicTicRate(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject* gPyGetLogicTicRate(PyObject*)
+static PyObject *gPyGetLogicTicRate(PyObject *)
{
return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate());
}
-static PyObject* gPySetExitKey(PyObject*, PyObject* args)
+static PyObject *gPySetExitKey(PyObject *, PyObject *args)
{
short exitkey;
if (!PyArg_ParseTuple(args, "h:setExitKey", &exitkey))
@@ -433,12 +427,12 @@ static PyObject* gPySetExitKey(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject* gPyGetExitKey(PyObject*)
+static PyObject *gPyGetExitKey(PyObject *)
{
return PyLong_FromSsize_t(KX_KetsjiEngine::GetExitKey());
}
-static PyObject* gPySetMaxLogicFrame(PyObject*, PyObject* args)
+static PyObject *gPySetMaxLogicFrame(PyObject *, PyObject *args)
{
int frame;
if (!PyArg_ParseTuple(args, "i:setMaxLogicFrame", &frame))
@@ -448,12 +442,12 @@ static PyObject* gPySetMaxLogicFrame(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject* gPyGetMaxLogicFrame(PyObject*)
+static PyObject *gPyGetMaxLogicFrame(PyObject *)
{
return PyLong_FromSsize_t(KX_KetsjiEngine::GetMaxLogicFrame());
}
-static PyObject* gPySetMaxPhysicsFrame(PyObject*, PyObject* args)
+static PyObject *gPySetMaxPhysicsFrame(PyObject *, PyObject *args)
{
int frame;
if (!PyArg_ParseTuple(args, "i:setMaxPhysicsFrame", &frame))
@@ -463,12 +457,12 @@ static PyObject* gPySetMaxPhysicsFrame(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject* gPyGetMaxPhysicsFrame(PyObject*)
+static PyObject *gPyGetMaxPhysicsFrame(PyObject *)
{
return PyLong_FromSsize_t(KX_KetsjiEngine::GetMaxPhysicsFrame());
}
-static PyObject* gPySetPhysicsTicRate(PyObject*, PyObject* args)
+static PyObject *gPySetPhysicsTicRate(PyObject *, PyObject *args)
{
float ticrate;
if (!PyArg_ParseTuple(args, "f:setPhysicsTicRate", &ticrate))
@@ -478,7 +472,7 @@ static PyObject* gPySetPhysicsTicRate(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
#if 0 // unused
-static PyObject* gPySetPhysicsDebug(PyObject*, PyObject* args)
+static PyObject *gPySetPhysicsDebug(PyObject *, PyObject *args)
{
int debugMode;
if (!PyArg_ParseTuple(args, "i:setPhysicsDebug", &debugMode))
@@ -490,21 +484,21 @@ static PyObject* gPySetPhysicsDebug(PyObject*, PyObject* args)
#endif
-static PyObject* gPyGetPhysicsTicRate(PyObject*)
+static PyObject *gPyGetPhysicsTicRate(PyObject *)
{
return PyFloat_FromDouble(PHY_GetActiveEnvironment()->getFixedTimeStep());
}
-static PyObject* gPyGetAverageFrameRate(PyObject*)
+static PyObject *gPyGetAverageFrameRate(PyObject *)
{
return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate());
}
-static PyObject* gPyGetBlendFileList(PyObject*, PyObject* args)
+static PyObject *gPyGetBlendFileList(PyObject *, PyObject *args)
{
char cpath[sizeof(gp_GamePythonPath)];
char *searchpath = NULL;
- PyObject* list, *value;
+ PyObject *list, *value;
DIR *dp;
struct dirent *dirp;
@@ -545,7 +539,7 @@ static char gPyAddScene_doc[] =
adds a scene to the game engine\n\
name = Name of the scene\n\
overlay = Overlay or underlay";
-static PyObject* gPyAddScene(PyObject*, PyObject* args)
+static PyObject *gPyAddScene(PyObject *, PyObject *args)
{
char* name;
int overlay = 1;
@@ -561,7 +555,7 @@ static PyObject* gPyAddScene(PyObject*, PyObject* args)
static const char *gPyGetCurrentScene_doc =
"getCurrentScene()\n"
"Gets a reference to the current scene.\n";
-static PyObject* gPyGetCurrentScene(PyObject* self)
+static PyObject *gPyGetCurrentScene(PyObject *self)
{
return gp_KetsjiScene->GetProxy();
}
@@ -569,10 +563,10 @@ static PyObject* gPyGetCurrentScene(PyObject* self)
static const char *gPyGetSceneList_doc =
"getSceneList()\n"
"Return a list of converted scenes.\n";
-static PyObject* gPyGetSceneList(PyObject* self)
+static PyObject *gPyGetSceneList(PyObject *self)
{
KX_KetsjiEngine* m_engine = KX_GetActiveEngine();
- PyObject* list;
+ PyObject *list;
KX_SceneList* scenes = m_engine->CurrentScenes();
int numScenes = scenes->size();
int i;
@@ -665,7 +659,7 @@ static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
Py_RETURN_NONE;
}
-static PyObject *gLibLoad(PyObject*, PyObject* args, PyObject* kwds)
+static PyObject *gLibLoad(PyObject *, PyObject *args, PyObject *kwds)
{
KX_Scene *kx_scene= gp_KetsjiScene;
char *path;
@@ -721,7 +715,7 @@ static PyObject *gLibLoad(PyObject*, PyObject* args, PyObject* kwds)
Py_RETURN_FALSE;
}
-static PyObject *gLibNew(PyObject*, PyObject* args)
+static PyObject *gLibNew(PyObject *, PyObject *args)
{
KX_Scene *kx_scene= gp_KetsjiScene;
char *path;
@@ -779,7 +773,7 @@ static PyObject *gLibNew(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject *gLibFree(PyObject*, PyObject* args)
+static PyObject *gLibFree(PyObject *, PyObject *args)
{
KX_Scene *kx_scene= gp_KetsjiScene;
char *path;
@@ -796,7 +790,7 @@ static PyObject *gLibFree(PyObject*, PyObject* args)
}
}
-static PyObject *gLibList(PyObject*, PyObject* args)
+static PyObject *gLibList(PyObject *, PyObject *args)
{
vector<Main*> &dynMaggie = gp_KetsjiScene->GetSceneConverter()->GetMainDynamic();
int i= 0;
@@ -866,14 +860,14 @@ static struct PyMethodDef game_methods[] = {
{NULL, (PyCFunction) NULL, 0, NULL }
};
-static PyObject* gPyGetWindowHeight(PyObject*, PyObject* args)
+static PyObject *gPyGetWindowHeight(PyObject *, PyObject *args)
{
return PyLong_FromSsize_t((gp_Canvas ? gp_Canvas->GetHeight() : 0));
}
-static PyObject* gPyGetWindowWidth(PyObject*, PyObject* args)
+static PyObject *gPyGetWindowWidth(PyObject *, PyObject *args)
{
return PyLong_FromSsize_t((gp_Canvas ? gp_Canvas->GetWidth() : 0));
}
@@ -883,7 +877,7 @@ static PyObject* gPyGetWindowWidth(PyObject*, PyObject* args)
// temporarility visibility thing, will be moved to rasterizer/renderer later
bool gUseVisibilityTemp = false;
-static PyObject* gPyEnableVisibility(PyObject*, PyObject* args)
+static PyObject *gPyEnableVisibility(PyObject *, PyObject *args)
{
int visible;
if (!PyArg_ParseTuple(args,"i:enableVisibility",&visible))
@@ -895,7 +889,7 @@ static PyObject* gPyEnableVisibility(PyObject*, PyObject* args)
-static PyObject* gPyShowMouse(PyObject*, PyObject* args)
+static PyObject *gPyShowMouse(PyObject *, PyObject *args)
{
int visible;
if (!PyArg_ParseTuple(args,"i:showMouse",&visible))
@@ -916,7 +910,7 @@ static PyObject* gPyShowMouse(PyObject*, PyObject* args)
-static PyObject* gPySetMousePosition(PyObject*, PyObject* args)
+static PyObject *gPySetMousePosition(PyObject *, PyObject *args)
{
int x,y;
if (!PyArg_ParseTuple(args,"ii:setMousePosition",&x,&y))
@@ -928,7 +922,7 @@ static PyObject* gPySetMousePosition(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject* gPySetEyeSeparation(PyObject*, PyObject* args)
+static PyObject *gPySetEyeSeparation(PyObject *, PyObject *args)
{
float sep;
if (!PyArg_ParseTuple(args, "f:setEyeSeparation", &sep))
@@ -944,7 +938,7 @@ static PyObject* gPySetEyeSeparation(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject* gPyGetEyeSeparation(PyObject*)
+static PyObject *gPyGetEyeSeparation(PyObject *)
{
if (!gp_Rasterizer) {
PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getEyeSeparation(), Rasterizer not available");
@@ -954,7 +948,7 @@ static PyObject* gPyGetEyeSeparation(PyObject*)
return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
}
-static PyObject* gPySetFocalLength(PyObject*, PyObject* args)
+static PyObject *gPySetFocalLength(PyObject *, PyObject *args)
{
float focus;
if (!PyArg_ParseTuple(args, "f:setFocalLength", &focus))
@@ -970,7 +964,7 @@ static PyObject* gPySetFocalLength(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject* gPyGetFocalLength(PyObject*, PyObject*, PyObject*)
+static PyObject *gPyGetFocalLength(PyObject *, PyObject *, PyObject *)
{
if (!gp_Rasterizer) {
PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getFocalLength(), Rasterizer not available");
@@ -982,7 +976,7 @@ static PyObject* gPyGetFocalLength(PyObject*, PyObject*, PyObject*)
Py_RETURN_NONE;
}
-static PyObject* gPySetBackgroundColor(PyObject*, PyObject* value)
+static PyObject *gPySetBackgroundColor(PyObject *, PyObject *value)
{
MT_Vector4 vec;
@@ -1003,7 +997,7 @@ static PyObject* gPySetBackgroundColor(PyObject*, PyObject* value)
-static PyObject* gPySetMistColor(PyObject*, PyObject* value)
+static PyObject *gPySetMistColor(PyObject *, PyObject *value)
{
MT_Vector3 vec;
@@ -1013,25 +1007,25 @@ static PyObject* gPySetMistColor(PyObject*, PyObject* value)
if (!gp_Rasterizer) {
PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistColor(color), Rasterizer not available");
return NULL;
- }
+ }
gp_Rasterizer->SetFogColor((float)vec[0], (float)vec[1], (float)vec[2]);
Py_RETURN_NONE;
}
-static PyObject* gPyDisableMist(PyObject*)
+static PyObject *gPyDisableMist(PyObject *)
{
if (!gp_Rasterizer) {
PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistColor(color), Rasterizer not available");
return NULL;
- }
+ }
gp_Rasterizer->DisableFog();
Py_RETURN_NONE;
}
-static PyObject* gPySetMistStart(PyObject*, PyObject* args)
+static PyObject *gPySetMistStart(PyObject *, PyObject *args)
{
float miststart;
@@ -1050,7 +1044,7 @@ static PyObject* gPySetMistStart(PyObject*, PyObject* args)
-static PyObject* gPySetMistEnd(PyObject*, PyObject* args)
+static PyObject *gPySetMistEnd(PyObject *, PyObject *args)
{
float mistend;
@@ -1068,7 +1062,7 @@ static PyObject* gPySetMistEnd(PyObject*, PyObject* args)
}
-static PyObject* gPySetAmbientColor(PyObject*, PyObject* value)
+static PyObject *gPySetAmbientColor(PyObject *, PyObject *value)
{
MT_Vector3 vec;
@@ -1078,7 +1072,7 @@ static PyObject* gPySetAmbientColor(PyObject*, PyObject* value)
if (!gp_Rasterizer) {
PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setAmbientColor(color), Rasterizer not available");
return NULL;
- }
+ }
gp_Rasterizer->SetAmbientColor((float)vec[0], (float)vec[1], (float)vec[2]);
Py_RETURN_NONE;
@@ -1087,7 +1081,7 @@ static PyObject* gPySetAmbientColor(PyObject*, PyObject* value)
-static PyObject* gPyMakeScreenshot(PyObject*, PyObject* args)
+static PyObject *gPyMakeScreenshot(PyObject *, PyObject *args)
{
char* filename;
if (!PyArg_ParseTuple(args,"s:makeScreenshot",&filename))
@@ -1101,7 +1095,7 @@ static PyObject* gPyMakeScreenshot(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject* gPyEnableMotionBlur(PyObject*, PyObject* args)
+static PyObject *gPyEnableMotionBlur(PyObject *, PyObject *args)
{
float motionblurvalue;
if (!PyArg_ParseTuple(args,"f:enableMotionBlur",&motionblurvalue))
@@ -1117,7 +1111,7 @@ static PyObject* gPyEnableMotionBlur(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject* gPyDisableMotionBlur(PyObject*)
+static PyObject *gPyDisableMotionBlur(PyObject *)
{
if (!gp_Rasterizer) {
PyErr_SetString(PyExc_RuntimeError, "Rasterizer.disableMotionBlur(), Rasterizer not available");
@@ -1147,9 +1141,9 @@ static int getGLSLSettingFlag(const char *setting)
return -1;
}
-static PyObject* gPySetGLSLMaterialSetting(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject *gPySetGLSLMaterialSetting(PyObject *,
+ PyObject *args,
+ PyObject *)
{
GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
char *setting;
@@ -1190,9 +1184,9 @@ static PyObject* gPySetGLSLMaterialSetting(PyObject*,
Py_RETURN_NONE;
}
-static PyObject* gPyGetGLSLMaterialSetting(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject *gPyGetGLSLMaterialSetting(PyObject *,
+ PyObject *args,
+ PyObject *)
{
GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
char *setting;
@@ -1216,9 +1210,9 @@ static PyObject* gPyGetGLSLMaterialSetting(PyObject*,
#define KX_BLENDER_MULTITEX_MATERIAL 1
#define KX_BLENDER_GLSL_MATERIAL 2
-static PyObject* gPySetMaterialType(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject *gPySetMaterialType(PyObject *,
+ PyObject *args,
+ PyObject *)
{
GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
int type;
@@ -1240,7 +1234,7 @@ static PyObject* gPySetMaterialType(PyObject*,
Py_RETURN_NONE;
}
-static PyObject* gPyGetMaterialType(PyObject*)
+static PyObject *gPyGetMaterialType(PyObject *)
{
GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
int flag;
@@ -1255,7 +1249,7 @@ static PyObject* gPyGetMaterialType(PyObject*)
return PyLong_FromSsize_t(flag);
}
-static PyObject* gPySetAnisotropicFiltering(PyObject*, PyObject* args)
+static PyObject *gPySetAnisotropicFiltering(PyObject *, PyObject *args)
{
short level;
@@ -1272,16 +1266,16 @@ static PyObject* gPySetAnisotropicFiltering(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject* gPyGetAnisotropicFiltering(PyObject*, PyObject* args)
+static PyObject *gPyGetAnisotropicFiltering(PyObject *, PyObject *args)
{
return PyLong_FromLong(gp_Rasterizer->GetAnisotropicFiltering());
}
-static PyObject* gPyDrawLine(PyObject*, PyObject* args)
+static PyObject *gPyDrawLine(PyObject *, PyObject *args)
{
- PyObject* ob_from;
- PyObject* ob_to;
- PyObject* ob_color;
+ PyObject *ob_from;
+ PyObject *ob_to;
+ PyObject *ob_color;
if (!gp_Rasterizer) {
PyErr_SetString(PyExc_RuntimeError, "Rasterizer.drawLine(obFrom, obTo, color): Rasterizer not available");
@@ -1306,7 +1300,7 @@ static PyObject* gPyDrawLine(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-static PyObject* gPySetWindowSize(PyObject*, PyObject* args)
+static PyObject *gPySetWindowSize(PyObject *, PyObject *args)
{
int width, height;
if (!PyArg_ParseTuple(args, "ii:resize", &width, &height))
@@ -1317,48 +1311,47 @@ static PyObject* gPySetWindowSize(PyObject*, PyObject* args)
}
static struct PyMethodDef rasterizer_methods[] = {
- {"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
- METH_VARARGS, "getWindowWidth doc"},
- {"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
- METH_VARARGS, "getWindowHeight doc"},
- {"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
- METH_VARARGS, "make Screenshot doc"},
- {"enableVisibility",(PyCFunction) gPyEnableVisibility,
- METH_VARARGS, "enableVisibility doc"},
+ {"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
+ METH_VARARGS, "getWindowWidth doc"},
+ {"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
+ METH_VARARGS, "getWindowHeight doc"},
+ {"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
+ METH_VARARGS, "make Screenshot doc"},
+ {"enableVisibility",(PyCFunction) gPyEnableVisibility,
+ METH_VARARGS, "enableVisibility doc"},
{"showMouse",(PyCFunction) gPyShowMouse,
- METH_VARARGS, "showMouse(bool visible)"},
- {"setMousePosition",(PyCFunction) gPySetMousePosition,
- METH_VARARGS, "setMousePosition(int x,int y)"},
- {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_O,"set Background Color (rgb)"},
+ METH_VARARGS, "showMouse(bool visible)"},
+ {"setMousePosition",(PyCFunction) gPySetMousePosition,
+ METH_VARARGS, "setMousePosition(int x,int y)"},
+ {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_O,"set Background Color (rgb)"},
{"setAmbientColor",(PyCFunction)gPySetAmbientColor,METH_O,"set Ambient Color (rgb)"},
- {"disableMist",(PyCFunction)gPyDisableMist,METH_NOARGS,"turn off mist"},
- {"setMistColor",(PyCFunction)gPySetMistColor,METH_O,"set Mist Color (rgb)"},
- {"setMistStart",(PyCFunction)gPySetMistStart,METH_VARARGS,"set Mist Start(rgb)"},
- {"setMistEnd",(PyCFunction)gPySetMistEnd,METH_VARARGS,"set Mist End(rgb)"},
- {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"},
- {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_NOARGS,"disable motion blur"},
-
-
- {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"},
- {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_NOARGS, "get the eye separation for stereo mode"},
- {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
- {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
- {"setMaterialMode",(PyCFunction) gPySetMaterialType,
- METH_VARARGS, "set the material mode to use for OpenGL rendering"},
- {"getMaterialMode",(PyCFunction) gPyGetMaterialType,
- METH_NOARGS, "get the material mode being used for OpenGL rendering"},
- {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
- METH_VARARGS, "set the state of a GLSL material setting"},
- {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
- METH_VARARGS, "get the state of a GLSL material setting"},
- {"setAnisotropicFiltering", (PyCFunction) gPySetAnisotropicFiltering,
- METH_VARARGS, "set the anisotropic filtering level (must be one of 1, 2, 4, 8, 16)"},
- {"getAnisotropicFiltering", (PyCFunction) gPyGetAnisotropicFiltering,
- METH_VARARGS, "get the anisotropic filtering level"},
- {"drawLine", (PyCFunction) gPyDrawLine,
- METH_VARARGS, "draw a line on the screen"},
- {"setWindowSize", (PyCFunction) gPySetWindowSize, METH_VARARGS, ""},
- { NULL, (PyCFunction) NULL, 0, NULL }
+ {"disableMist",(PyCFunction)gPyDisableMist,METH_NOARGS,"turn off mist"},
+ {"setMistColor",(PyCFunction)gPySetMistColor,METH_O,"set Mist Color (rgb)"},
+ {"setMistStart",(PyCFunction)gPySetMistStart,METH_VARARGS,"set Mist Start(rgb)"},
+ {"setMistEnd",(PyCFunction)gPySetMistEnd,METH_VARARGS,"set Mist End(rgb)"},
+ {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"},
+ {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_NOARGS,"disable motion blur"},
+
+ {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"},
+ {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_NOARGS, "get the eye separation for stereo mode"},
+ {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
+ {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
+ {"setMaterialMode",(PyCFunction) gPySetMaterialType,
+ METH_VARARGS, "set the material mode to use for OpenGL rendering"},
+ {"getMaterialMode",(PyCFunction) gPyGetMaterialType,
+ METH_NOARGS, "get the material mode being used for OpenGL rendering"},
+ {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
+ METH_VARARGS, "set the state of a GLSL material setting"},
+ {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
+ METH_VARARGS, "get the state of a GLSL material setting"},
+ {"setAnisotropicFiltering", (PyCFunction) gPySetAnisotropicFiltering,
+ METH_VARARGS, "set the anisotropic filtering level (must be one of 1, 2, 4, 8, 16)"},
+ {"getAnisotropicFiltering", (PyCFunction) gPyGetAnisotropicFiltering,
+ METH_VARARGS, "get the anisotropic filtering level"},
+ {"drawLine", (PyCFunction) gPyDrawLine,
+ METH_VARARGS, "draw a line on the screen"},
+ {"setWindowSize", (PyCFunction) gPySetWindowSize, METH_VARARGS, ""},
+ { NULL, (PyCFunction) NULL, 0, NULL }
};
// Initialization function for the module (*must* be called initGameLogic)
@@ -1383,11 +1376,11 @@ static struct PyModuleDef GameLogic_module_def = {
0, /* m_free */
};
-PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook
+PyObject *initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook
{
- PyObject* m;
- PyObject* d;
- PyObject* item; /* temp PyObject* storage */
+ PyObject *m;
+ PyObject *d;
+ PyObject *item; /* temp PyObject *storage */
gp_KetsjiEngine = engine;
gp_KetsjiScene = scene;
@@ -1405,7 +1398,7 @@ PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack
}
else {
PyErr_Clear();
- // Create the module and add the functions
+ // Create the module and add the functions
m = PyModule_Create(&GameLogic_module_def);
PyDict_SetItemString(PySys_GetObject("modules"), GameLogic_module_def.m_name, m);
}
@@ -1802,7 +1795,7 @@ static void initPySysObjects(Main *maggie)
Library *lib= (Library *)maggie->library.first;
- while(lib) {
+ while (lib) {
/* lib->name wont work in some cases (on win32),
* even when expanding with gp_GamePythonPath, using lib->filename is less trouble */
initPySysObjects__append(sys_path, lib->filepath);
@@ -1832,7 +1825,7 @@ static void restorePySysObjects(void)
PyDict_Clear(sys_mods);
PyDict_Update(sys_mods, gp_OrigPythonSysModules);
Py_DECREF(gp_OrigPythonSysModules);
- gp_OrigPythonSysModules= NULL;
+ gp_OrigPythonSysModules= NULL;
// fprintf(stderr, "\nRestore Path: %d ", PyList_GET_SIZE(sys_path));
@@ -1850,7 +1843,7 @@ void removeImportMain(struct Main *maggie)
}
// Copied from bpy_interface.c
-static struct _inittab bge_internal_modules[]= {
+static struct _inittab bge_internal_modules[] = {
{(char *)"mathutils", PyInit_mathutils},
{(char *)"bgl", BPyInit_bgl},
{(char *)"blf", BPyInit_blf},
@@ -1862,7 +1855,7 @@ static struct _inittab bge_internal_modules[]= {
* Python is not initialized.
* see bpy_interface.c's BPY_python_start() which shares the same functionality in blender.
*/
-PyObject* initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie, int argc, char** argv)
+PyObject *initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie, int argc, char** argv)
{
/* Yet another gotcha in the py api
* Cant run PySys_SetArgv more then once because this adds the
@@ -1935,7 +1928,7 @@ PyObject* initGamePlayerPythonScripting(const STR_String& progname, TPythonSecur
}
void exitGamePlayerPythonScripting()
-{
+{
/* Clean up the Python mouse and keyboard */
delete gp_PythonKeyboard;
gp_PythonKeyboard = NULL;
@@ -1956,7 +1949,7 @@ void exitGamePlayerPythonScripting()
/**
* Python is already initialized.
*/
-PyObject* initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie)
+PyObject *initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie)
{
#if 0 // XXX TODO Py3
STR_String pname = progname;
@@ -1998,9 +1991,10 @@ void exitGamePythonScripting()
/* similar to the above functions except it sets up the namespace
* and other more general things */
-void setupGamePython(KX_KetsjiEngine* ketsjiengine, KX_Scene* startscene, Main *blenderdata, PyObject * pyGlobalDict, PyObject **gameLogic, PyObject **gameLogic_keys, int argc, char** argv)
+void setupGamePython(KX_KetsjiEngine* ketsjiengine, KX_Scene *startscene, Main *blenderdata,
+ PyObject *pyGlobalDict, PyObject **gameLogic, PyObject **gameLogic_keys, int argc, char** argv)
{
- PyObject* dictionaryobject;
+ PyObject *dictionaryobject;
if (argv) /* player only */
dictionaryobject= initGamePlayerPythonScripting("Ketsji", psl_Lowest, blenderdata, argc, argv);
@@ -2053,15 +2047,15 @@ static struct PyModuleDef Rasterizer_module_def = {
0, /* m_free */
};
-PyObject* initRasterizer(RAS_IRasterizer* rasty,RAS_ICanvas* canvas)
+PyObject *initRasterizer(RAS_IRasterizer* rasty,RAS_ICanvas* canvas)
{
gp_Canvas = canvas;
gp_Rasterizer = rasty;
- PyObject* m;
- PyObject* d;
- PyObject* item;
+ PyObject *m;
+ PyObject *d;
+ PyObject *item;
/* Use existing module where possible
* be careful not to init any runtime vars after this */
@@ -2114,9 +2108,9 @@ static char gPyEventToString_doc[] =
"EventToString(event) - Take a valid event from the GameKeys module or Keyboard Sensor and return a name"
;
-static PyObject* gPyEventToString(PyObject*, PyObject* value)
+static PyObject *gPyEventToString(PyObject *, PyObject *value)
{
- PyObject* mod, *dict, *key, *val, *ret = NULL;
+ PyObject *mod, *dict, *key, *val, *ret = NULL;
Py_ssize_t pos = 0;
mod = PyImport_ImportModule( "GameKeys" );
@@ -2144,7 +2138,7 @@ static char gPyEventToCharacter_doc[] =
"EventToCharacter(event, is_shift) - Take a valid event from the GameKeys module or Keyboard Sensor and return a character"
;
-static PyObject* gPyEventToCharacter(PyObject*, PyObject* args)
+static PyObject *gPyEventToCharacter(PyObject *, PyObject *args)
{
int event, shift;
if (!PyArg_ParseTuple(args,"ii:EventToCharacter", &event, &shift))
@@ -2179,11 +2173,11 @@ static struct PyModuleDef GameKeys_module_def = {
0, /* m_free */
};
-PyObject* initGameKeys()
+PyObject *initGameKeys()
{
- PyObject* m;
- PyObject* d;
- PyObject* item;
+ PyObject *m;
+ PyObject *d;
+ PyObject *item;
/* Use existing module where possible */
m = PyImport_ImportModule( "GameKeys" );
@@ -2231,24 +2225,24 @@ PyObject* initGameKeys()
KX_MACRO_addTypesToDict(d, YKEY, SCA_IInputDevice::KX_YKEY);
KX_MACRO_addTypesToDict(d, ZKEY, SCA_IInputDevice::KX_ZKEY);
- KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY);
- KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY);
- KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY);
+ KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY);
+ KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY);
+ KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY);
KX_MACRO_addTypesToDict(d, THREEKEY, SCA_IInputDevice::KX_THREEKEY);
- KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY);
- KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY);
- KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY);
+ KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY);
+ KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY);
+ KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY);
KX_MACRO_addTypesToDict(d, SEVENKEY, SCA_IInputDevice::KX_SEVENKEY);
KX_MACRO_addTypesToDict(d, EIGHTKEY, SCA_IInputDevice::KX_EIGHTKEY);
- KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY);
+ KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY);
KX_MACRO_addTypesToDict(d, CAPSLOCKKEY, SCA_IInputDevice::KX_CAPSLOCKKEY);
- KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY);
- KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY);
- KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY);
- KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY);
- KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY);
+ KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY);
+ KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY);
+ KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY);
+ KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY);
+ KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY);
KX_MACRO_addTypesToDict(d, LEFTSHIFTKEY, SCA_IInputDevice::KX_LEFTSHIFTKEY);
KX_MACRO_addTypesToDict(d, ESCKEY, SCA_IInputDevice::KX_ESCKEY);
@@ -2256,25 +2250,25 @@ PyObject* initGameKeys()
KX_MACRO_addTypesToDict(d, RETKEY, SCA_IInputDevice::KX_RETKEY);
KX_MACRO_addTypesToDict(d, ENTERKEY, SCA_IInputDevice::KX_RETKEY);
KX_MACRO_addTypesToDict(d, SPACEKEY, SCA_IInputDevice::KX_SPACEKEY);
- KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY);
+ KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY);
KX_MACRO_addTypesToDict(d, BACKSPACEKEY, SCA_IInputDevice::KX_BACKSPACEKEY);
KX_MACRO_addTypesToDict(d, DELKEY, SCA_IInputDevice::KX_DELKEY);
KX_MACRO_addTypesToDict(d, SEMICOLONKEY, SCA_IInputDevice::KX_SEMICOLONKEY);
- KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY);
- KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY);
- KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY);
- KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY);
- KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY);
- KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY);
+ KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY);
+ KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY);
+ KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY);
+ KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY);
+ KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY);
+ KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY);
KX_MACRO_addTypesToDict(d, BACKSLASHKEY, SCA_IInputDevice::KX_BACKSLASHKEY);
- KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY);
- KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY);
- KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY);
+ KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY);
+ KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY);
+ KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY);
KX_MACRO_addTypesToDict(d, LEFTARROWKEY, SCA_IInputDevice::KX_LEFTARROWKEY);
KX_MACRO_addTypesToDict(d, DOWNARROWKEY, SCA_IInputDevice::KX_DOWNARROWKEY);
- KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY);
- KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY);
+ KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY);
+ KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY);
KX_MACRO_addTypesToDict(d, PAD2 , SCA_IInputDevice::KX_PAD2);
KX_MACRO_addTypesToDict(d, PAD4 , SCA_IInputDevice::KX_PAD4);
@@ -2347,14 +2341,14 @@ PyObject* initGameKeys()
int saveGamePythonConfig( char **marshal_buffer)
{
int marshal_length = 0;
- PyObject* gameLogic = PyImport_ImportModule("GameLogic");
+ PyObject *gameLogic = PyImport_ImportModule("GameLogic");
if (gameLogic) {
- PyObject* pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module
+ PyObject *pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module
if (pyGlobalDict) {
-#ifdef Py_MARSHAL_VERSION
- PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString( pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5
+#ifdef Py_MARSHAL_VERSION
+ PyObject *pyGlobalDictMarshal = PyMarshal_WriteObjectToString( pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5
#else
- PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString( pyGlobalDict );
+ PyObject *pyGlobalDictMarshal = PyMarshal_WriteObjectToString( pyGlobalDict );
#endif
if (pyGlobalDictMarshal) {
// for testing only
@@ -2384,12 +2378,12 @@ int loadGamePythonConfig(char *marshal_buffer, int marshal_length)
{
/* Restore the dict */
if (marshal_buffer) {
- PyObject* gameLogic = PyImport_ImportModule("GameLogic");
+ PyObject *gameLogic = PyImport_ImportModule("GameLogic");
if (gameLogic) {
- PyObject* pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length);
+ PyObject *pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length);
if (pyGlobalDict) {
- PyObject* pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module.
+ PyObject *pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module.
if (pyGlobalDict_orig) {
PyDict_Clear(pyGlobalDict_orig);
PyDict_Update(pyGlobalDict_orig, pyGlobalDict);
@@ -2405,10 +2399,11 @@ int loadGamePythonConfig(char *marshal_buffer, int marshal_length)
PyErr_Clear();
printf("Error could not marshall string\n");
}
- } else {
+ }
+ else {
PyErr_Clear();
printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n");
- }
+ }
}
return 0;
}
diff --git a/source/gameengine/Ketsji/KX_PythonInit.h b/source/gameengine/Ketsji/KX_PythonInit.h
index 1500dd97ae1..859c31adcd3 100644
--- a/source/gameengine/Ketsji/KX_PythonInit.h
+++ b/source/gameengine/Ketsji/KX_PythonInit.h
@@ -52,7 +52,8 @@ void exitGamePlayerPythonScripting();
PyObject* initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level, struct Main *maggie);
void exitGamePythonScripting();
-void setupGamePython(KX_KetsjiEngine* ketsjiengine, KX_Scene* startscene, Main *blenderdata, PyObject *pyGlobalDict, PyObject **gameLogic, PyObject **gameLogic_keys, int argc, char** argv);
+void setupGamePython(KX_KetsjiEngine *ketsjiengine, KX_Scene *startscene, Main *blenderdata,
+ PyObject *pyGlobalDict, PyObject **gameLogic, PyObject **gameLogic_keys, int argc, char** argv);
void setGamePythonPath(const char *path);
void resetGamePythonPath();
@@ -72,11 +73,12 @@ class KX_Scene* KX_GetActiveScene();
class KX_KetsjiEngine* KX_GetActiveEngine();
typedef int (*PyNextFrameFunc)(void *);
+
struct PyNextFrameState {
- //state: can be either a GPG_NextFrameState or a BL_KetsjiNextFrameState
- void *state;
- //func: can be either GPG_PyNextFrame or BL_KetsjiPyNextFrame
- PyNextFrameFunc func;
+ /** can be either a GPG_NextFrameState or a BL_KetsjiNextFrameState */
+ void *state;
+ /** can be either GPG_PyNextFrame or BL_KetsjiPyNextFrame */
+ PyNextFrameFunc func;
};
extern struct PyNextFrameState pynextframestate;
@@ -84,8 +86,7 @@ extern struct PyNextFrameState pynextframestate;
void KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color);
void KX_RasterizerDrawDebugCircle(const MT_Vector3& center, const MT_Scalar radius, const MT_Vector3& color,
- const MT_Vector3& normal, int nsector);
-
+ const MT_Vector3& normal, int nsector);
-#endif //__KX_PYTHONINIT_H__
+#endif /* __KX_PYTHONINIT_H__ */
diff --git a/source/gameengine/Ketsji/KX_PythonInitTypes.cpp b/source/gameengine/Ketsji/KX_PythonInitTypes.cpp
index 3033c534e84..805b9ce2fc2 100644
--- a/source/gameengine/Ketsji/KX_PythonInitTypes.cpp
+++ b/source/gameengine/Ketsji/KX_PythonInitTypes.cpp
@@ -29,14 +29,10 @@
* \ingroup ketsji
*/
-
-
-
-#ifndef _adr_py_init_types_h_ // only process once,
-#define _adr_py_init_types_h_ // even if multiply included
-
#ifdef WITH_PYTHON
+#include "KX_PythonInitTypes.h"
+
/* Only for Class::Parents */
#include "BL_BlenderShader.h"
#include "BL_ShapeActionActuator.h"
@@ -46,6 +42,7 @@
#include "BL_ArmatureChannel.h"
#include "KX_BlenderMaterial.h"
#include "KX_CameraActuator.h"
+#include "KX_CharacterWrapper.h"
#include "KX_ConstraintActuator.h"
#include "KX_ConstraintWrapper.h"
#include "KX_GameActuator.h"
@@ -166,7 +163,7 @@ static void PyType_Ready_ADD(PyObject *dict, PyTypeObject *tp, PyAttributeDef *a
void initPyTypes(void)
{
-
+
/*
* initPyObjectPlusType(BL_ActionActuator::Parents);
* .....
@@ -193,6 +190,7 @@ void initPyTypes(void)
PyType_Ready_Attr(dict, KX_BlenderMaterial, init_getset);
PyType_Ready_Attr(dict, KX_Camera, init_getset);
PyType_Ready_Attr(dict, KX_CameraActuator, init_getset);
+ PyType_Ready_Attr(dict, KX_CharacterWrapper, init_getset);
PyType_Ready_Attr(dict, KX_ConstraintActuator, init_getset);
PyType_Ready_Attr(dict, KX_ConstraintWrapper, init_getset);
PyType_Ready_Attr(dict, KX_GameActuator, init_getset);
@@ -266,5 +264,3 @@ void initPyTypes(void)
}
#endif // WITH_PYTHON
-
-#endif
diff --git a/source/gameengine/Ketsji/KX_PythonInitTypes.h b/source/gameengine/Ketsji/KX_PythonInitTypes.h
index a06fe46a0ea..d8ee4f75fdd 100644
--- a/source/gameengine/Ketsji/KX_PythonInitTypes.h
+++ b/source/gameengine/Ketsji/KX_PythonInitTypes.h
@@ -29,11 +29,11 @@
* \ingroup ketsji
*/
-#ifndef _adr_py_init_types_h_ // only process once,
-#define _adr_py_init_types_h_ // even if multiply included
+#ifndef __KX_PYTHON_INIT_TYPES__
+#define __KX_PYTHON_INIT_TYPES__
#ifdef WITH_PYTHON
void initPyTypes(void);
#endif
-#endif
+#endif /* __KX_PYTHON_INIT_TYPES__ */
diff --git a/source/gameengine/Ketsji/KX_PythonMain.cpp b/source/gameengine/Ketsji/KX_PythonMain.cpp
index d926dff0bf5..740bb102fd9 100644
--- a/source/gameengine/Ketsji/KX_PythonMain.cpp
+++ b/source/gameengine/Ketsji/KX_PythonMain.cpp
@@ -1,6 +1,4 @@
-/*
- * $Id: KX_PythonMain.cpp 37750 2011-06-27 09:27:56Z sjoerd $
- *
+/*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
@@ -17,15 +15,11 @@
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
+ * Contributor(s): Benoit Bolsee
*
* ***** END GPL LICENSE BLOCK *****
*/
+
/** \file gameengine/Ketsji/KX_PythonMain.cpp
* \ingroup ketsji
*/
diff --git a/source/gameengine/Ketsji/KX_PythonMain.h b/source/gameengine/Ketsji/KX_PythonMain.h
index 1460ea2ca96..e638fa9094e 100644
--- a/source/gameengine/Ketsji/KX_PythonMain.h
+++ b/source/gameengine/Ketsji/KX_PythonMain.h
@@ -1,6 +1,4 @@
-/*
- * $Id: KX_PythonMain.h 37750 2011-06-27 09:27:56Z sjoerd $
- *
+/*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
@@ -31,11 +29,12 @@
* \ingroup ketsji
*/
-#ifndef __KX_PYTHON_MAIN
-#define __KX_PYTHON_MAIN
+#ifndef __KX_PYTHON_MAIN__
+#define __KX_PYTHON_MAIN__
#include "BKE_main.h"
#include "DNA_scene_types.h"
extern "C" char *KX_GetPythonMain(struct Scene* scene);
extern "C" char *KX_GetPythonCode(struct Main *main, char *python_main);
-#endif
+
+#endif /* __KX_PYTHON_MAIN__ */
diff --git a/source/gameengine/Ketsji/KX_PythonSeq.cpp b/source/gameengine/Ketsji/KX_PythonSeq.cpp
index 6eadc0cbef3..6b4d88709e8 100644
--- a/source/gameengine/Ketsji/KX_PythonSeq.cpp
+++ b/source/gameengine/Ketsji/KX_PythonSeq.cpp
@@ -69,38 +69,38 @@ static void KX_PythonSeq_dealloc(KX_PythonSeq * self)
PyObject_GC_Del(self);
}
-static Py_ssize_t KX_PythonSeq_len( PyObject * self )
+static Py_ssize_t KX_PythonSeq_len( PyObject *self )
{
PyObjectPlus *self_plus= BGE_PROXY_REF(((KX_PythonSeq *)self)->base);
-
+
if (self_plus==NULL) {
PyErr_SetString(PyExc_SystemError, "len(seq): "BGE_PROXY_ERROR_MSG);
return -1;
}
- switch(((KX_PythonSeq *)self)->type) {
- case KX_PYGENSEQ_CONT_TYPE_SENSORS:
- return ((SCA_IController *)self_plus)->GetLinkedSensors().size();
- case KX_PYGENSEQ_CONT_TYPE_ACTUATORS:
- return ((SCA_IController *)self_plus)->GetLinkedActuators().size();
- case KX_PYGENSEQ_OB_TYPE_SENSORS:
- return ((KX_GameObject *)self_plus)->GetSensors().size();
- case KX_PYGENSEQ_OB_TYPE_CONTROLLERS:
- return ((KX_GameObject *)self_plus)->GetControllers().size();
- case KX_PYGENSEQ_OB_TYPE_ACTUATORS:
- return ((KX_GameObject *)self_plus)->GetActuators().size();
- case KX_PYGENSEQ_OB_TYPE_CONSTRAINTS:
- return ((BL_ArmatureObject *)self_plus)->GetConstraintNumber();
- case KX_PYGENSEQ_OB_TYPE_CHANNELS:
- return ((BL_ArmatureObject *)self_plus)->GetChannelNumber();
- default:
- /* Should never happen */
- PyErr_SetString(PyExc_SystemError, "invalid type, internal error");
- return -1;
+ switch (((KX_PythonSeq *)self)->type) {
+ case KX_PYGENSEQ_CONT_TYPE_SENSORS:
+ return ((SCA_IController *)self_plus)->GetLinkedSensors().size();
+ case KX_PYGENSEQ_CONT_TYPE_ACTUATORS:
+ return ((SCA_IController *)self_plus)->GetLinkedActuators().size();
+ case KX_PYGENSEQ_OB_TYPE_SENSORS:
+ return ((KX_GameObject *)self_plus)->GetSensors().size();
+ case KX_PYGENSEQ_OB_TYPE_CONTROLLERS:
+ return ((KX_GameObject *)self_plus)->GetControllers().size();
+ case KX_PYGENSEQ_OB_TYPE_ACTUATORS:
+ return ((KX_GameObject *)self_plus)->GetActuators().size();
+ case KX_PYGENSEQ_OB_TYPE_CONSTRAINTS:
+ return ((BL_ArmatureObject *)self_plus)->GetConstraintNumber();
+ case KX_PYGENSEQ_OB_TYPE_CHANNELS:
+ return ((BL_ArmatureObject *)self_plus)->GetChannelNumber();
+ default:
+ /* Should never happen */
+ PyErr_SetString(PyExc_SystemError, "invalid type, internal error");
+ return -1;
}
}
-static PyObject *KX_PythonSeq_getIndex(PyObject* self, int index)
+static PyObject *KX_PythonSeq_getIndex(PyObject *self, int index)
{
PyObjectPlus *self_plus= BGE_PROXY_REF(((KX_PythonSeq *)self)->base);
@@ -109,7 +109,7 @@ static PyObject *KX_PythonSeq_getIndex(PyObject* self, int index)
return NULL;
}
- switch(((KX_PythonSeq *)self)->type) {
+ switch (((KX_PythonSeq *)self)->type) {
case KX_PYGENSEQ_CONT_TYPE_SENSORS:
{
vector<SCA_ISensor*>& linkedsensors = ((SCA_IController *)self_plus)->GetLinkedSensors();
@@ -193,7 +193,7 @@ static PyObjectPlus * KX_PythonSeq_subscript__internal(PyObject *self, const cha
{
PyObjectPlus *self_plus= BGE_PROXY_REF(((KX_PythonSeq *)self)->base);
- switch(((KX_PythonSeq *)self)->type) {
+ switch (((KX_PythonSeq *)self)->type) {
case KX_PYGENSEQ_CONT_TYPE_SENSORS:
{
vector<SCA_ISensor*>& linkedsensors = ((SCA_IController *)self_plus)->GetLinkedSensors();
@@ -264,7 +264,7 @@ static PyObjectPlus * KX_PythonSeq_subscript__internal(PyObject *self, const cha
}
-static PyObject * KX_PythonSeq_subscript(PyObject * self, PyObject *key)
+static PyObject * KX_PythonSeq_subscript(PyObject *self, PyObject *key)
{
PyObjectPlus *self_plus= BGE_PROXY_REF(((KX_PythonSeq *)self)->base);
@@ -314,10 +314,10 @@ static int KX_PythonSeq_contains(PyObject *self, PyObject *key)
}
/* Matches python dict.get(key, [default]) */
-PyObject* KX_PythonSeq_get(PyObject * self, PyObject *args)
+static PyObject *KX_PythonSeq_get(PyObject *self, PyObject *args)
{
char *key;
- PyObject* def = Py_None;
+ PyObject *def = Py_None;
PyObjectPlus* ret_plus;
if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
@@ -396,7 +396,7 @@ static PyObject *KX_PythonSeq_nextIter(KX_PythonSeq *self)
static int KX_PythonSeq_compare( KX_PythonSeq * a, KX_PythonSeq * b )
{
- return ( a->type == b->type && a->base == b->base) ? 0 : -1;
+ return ( a->type == b->type && a->base == b->base) ? 0 : -1;
}
static PyObject *KX_PythonSeq_richcmp(PyObject *a, PyObject *b, int op)
diff --git a/source/gameengine/Ketsji/KX_PythonSeq.h b/source/gameengine/Ketsji/KX_PythonSeq.h
index 47a01737cdb..568d59119c0 100644
--- a/source/gameengine/Ketsji/KX_PythonSeq.h
+++ b/source/gameengine/Ketsji/KX_PythonSeq.h
@@ -30,8 +30,8 @@
* \brief Readonly sequence wrapper for lookups on logic bricks
*/
-#ifndef _adr_py_seq_h_ // only process once,
-#define _adr_py_seq_h_ // even if multiply included
+#ifndef __KX_PYTHONSEQ_H__
+#define __KX_PYTHONSEQ_H__
#ifdef WITH_PYTHON
@@ -63,6 +63,6 @@ typedef struct {
PyObject *KX_PythonSeq_CreatePyObject(PyObject *base, short type);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
-#endif // _adr_py_seq_h_
+#endif /* __KX_PYTHONSEQ_H__ */
diff --git a/source/gameengine/Ketsji/KX_RadarSensor.cpp b/source/gameengine/Ketsji/KX_RadarSensor.cpp
index 74009f51078..04d67fc73e1 100644
--- a/source/gameengine/Ketsji/KX_RadarSensor.cpp
+++ b/source/gameengine/Ketsji/KX_RadarSensor.cpp
@@ -217,9 +217,9 @@ PyAttributeDef KX_RadarSensor::Attributes[] = {
{NULL} //Sentinel
};
-PyObject* KX_RadarSensor::pyattr_get_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_RadarSensor::pyattr_get_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_RadarSensor* self= static_cast<KX_RadarSensor*>(self_v);
+ KX_RadarSensor* self = static_cast<KX_RadarSensor*>(self_v);
// The original angle from the gui was converted, so we recalculate the value here to maintain
// consistency between Python and the gui
diff --git a/source/gameengine/Ketsji/KX_RadarSensor.h b/source/gameengine/Ketsji/KX_RadarSensor.h
index 2de58f8b3a0..6a2d50ffa3a 100644
--- a/source/gameengine/Ketsji/KX_RadarSensor.h
+++ b/source/gameengine/Ketsji/KX_RadarSensor.h
@@ -97,5 +97,4 @@ public:
#endif
};
-#endif //__KX_RADARSENSOR_H__
-
+#endif /* __KX_RADARSENSOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_RayCast.cpp b/source/gameengine/Ketsji/KX_RayCast.cpp
index 459600f2e34..2a6b7d122b5 100644
--- a/source/gameengine/Ketsji/KX_RayCast.cpp
+++ b/source/gameengine/Ketsji/KX_RayCast.cpp
@@ -76,9 +76,9 @@ bool KX_RayCast::RayTest(PHY_IPhysicsEnvironment* physics_environment, const MT_
PHY_IPhysicsController* hit_controller;
- while((hit_controller = physics_environment->rayTest(callback,
- frompoint.x(),frompoint.y(),frompoint.z(),
- topoint.x(),topoint.y(),topoint.z())) != NULL)
+ while ((hit_controller = physics_environment->rayTest(callback,
+ frompoint.x(),frompoint.y(),frompoint.z(),
+ topoint.x(),topoint.y(),topoint.z())) != NULL)
{
KX_ClientObjectInfo* info = static_cast<KX_ClientObjectInfo*>(hit_controller->getNewClientInfo());
diff --git a/source/gameengine/Ketsji/KX_RayEventManager.h b/source/gameengine/Ketsji/KX_RayEventManager.h
index f795495d1c9..07506b9e32b 100644
--- a/source/gameengine/Ketsji/KX_RayEventManager.h
+++ b/source/gameengine/Ketsji/KX_RayEventManager.h
@@ -50,5 +50,4 @@ public:
#endif
};
-#endif //__KX_RAYEVENTMANAGER_H__
-
+#endif /* __KX_RAYEVENTMANAGER_H__ */
diff --git a/source/gameengine/Ketsji/KX_RaySensor.cpp b/source/gameengine/Ketsji/KX_RaySensor.cpp
index 58ca847b617..14786e8429e 100644
--- a/source/gameengine/Ketsji/KX_RaySensor.cpp
+++ b/source/gameengine/Ketsji/KX_RaySensor.cpp
@@ -361,7 +361,7 @@ PyAttributeDef KX_RaySensor::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_RaySensor::pyattr_get_hitobject(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_RaySensor::pyattr_get_hitobject(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_RaySensor* self = static_cast<KX_RaySensor*>(self_v);
if (self->m_hitObject)
diff --git a/source/gameengine/Ketsji/KX_RaySensor.h b/source/gameengine/Ketsji/KX_RaySensor.h
index f5d1c72d098..9d40fb55747 100644
--- a/source/gameengine/Ketsji/KX_RaySensor.h
+++ b/source/gameengine/Ketsji/KX_RaySensor.h
@@ -94,11 +94,10 @@ public:
#ifdef WITH_PYTHON
/* Attributes */
- static PyObject* pyattr_get_hitobject(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_hitobject(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif //__KX_RAYSENSOR_H__
-
+#endif /* __KX_RAYSENSOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
index 841feda5237..d850168afdf 100644
--- a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
@@ -203,10 +203,10 @@ PyAttributeDef KX_SCA_AddObjectActuator::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_SCA_AddObjectActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SCA_AddObjectActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SCA_AddObjectActuator* actuator = static_cast<KX_SCA_AddObjectActuator*>(self);
- if (!actuator->m_OriginalObject)
+ if (!actuator->m_OriginalObject)
Py_RETURN_NONE;
else
return actuator->m_OriginalObject->GetProxy();
@@ -221,7 +221,7 @@ int KX_SCA_AddObjectActuator::pyattr_set_object(void *self, const struct KX_PYAT
return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
if (actuator->m_OriginalObject != NULL)
- actuator->m_OriginalObject->UnregisterActuator(actuator);
+ actuator->m_OriginalObject->UnregisterActuator(actuator);
actuator->m_OriginalObject = (SCA_IObject*)gameobj;
@@ -231,7 +231,7 @@ int KX_SCA_AddObjectActuator::pyattr_set_object(void *self, const struct KX_PYAT
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_SCA_AddObjectActuator::pyattr_get_objectLastCreated(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SCA_AddObjectActuator::pyattr_get_objectLastCreated(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SCA_AddObjectActuator* actuator = static_cast<KX_SCA_AddObjectActuator*>(self);
if (!actuator->m_lastCreatedObject)
@@ -240,7 +240,7 @@ PyObject* KX_SCA_AddObjectActuator::pyattr_get_objectLastCreated(void *self, con
return actuator->m_lastCreatedObject->GetProxy();
}
-PyObject* KX_SCA_AddObjectActuator::PyInstantAddObject()
+PyObject *KX_SCA_AddObjectActuator::PyInstantAddObject()
{
InstantAddObject();
@@ -253,7 +253,7 @@ void KX_SCA_AddObjectActuator::InstantAddObject()
{
if (m_OriginalObject)
{
- // Add an identical object, with properties inherited from the original object
+ // Add an identical object, with properties inherited from the original object
// Now it needs to be added to the current scene.
SCA_IObject* replica = m_scene->AddReplicaObject(m_OriginalObject,GetParent(),m_timeProp );
KX_GameObject * game_obj = static_cast<KX_GameObject *>(replica);
diff --git a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h
index f49f2473036..976f3c58d68 100644
--- a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h
+++ b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h
@@ -50,7 +50,7 @@ class KX_SCA_AddObjectActuator : public SCA_IActuator
/// Time field: lifetime of the new object
int m_timeProp;
- /// Original object reference (object to replicate)
+ /// Original object reference (object to replicate)
SCA_IObject* m_OriginalObject;
/// Object will be added to the following scene
@@ -112,7 +112,7 @@ public:
virtual bool
Update();
- SCA_IObject*
+ SCA_IObject *
GetLastCreatedObject(
) const;
@@ -122,13 +122,12 @@ public:
KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,InstantAddObject);
- static PyObject* pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_objectLastCreated(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_objectLastCreated(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
}; /* end of class KX_SCA_AddObjectActuator : public KX_EditObjectActuator */
-#endif
-
+#endif /* __KX_SCA_ADDOBJECTACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp b/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp
index f408b2cd7c9..5dc67a4cff3 100644
--- a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp
@@ -119,14 +119,14 @@ bool KX_SCA_DynamicActuator::Update()
switch (m_dyn_operation)
{
- case 0:
- obj->RestoreDynamics();
+ case 0:
+ obj->RestoreDynamics();
break;
case 1:
obj->SuspendDynamics();
break;
case 2:
- controller->setRigidBody(true);
+ controller->setRigidBody(true);
break;
case 3:
controller->setRigidBody(false);
diff --git a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
index ffe5556cfe6..b105256836b 100644
--- a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
@@ -87,7 +87,7 @@ PyAttributeDef KX_SCA_ReplaceMeshActuator::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_SCA_ReplaceMeshActuator::pyattr_get_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SCA_ReplaceMeshActuator::pyattr_get_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SCA_ReplaceMeshActuator* actuator = static_cast<KX_SCA_ReplaceMeshActuator*>(self);
if (!actuator->m_mesh)
diff --git a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h
index 6db16a0e1b6..4370b5d4a4f 100644
--- a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h
+++ b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h
@@ -84,14 +84,13 @@ class KX_SCA_ReplaceMeshActuator : public SCA_IActuator
m_scene= val;
};
- static PyObject* pyattr_get_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
KX_PYMETHOD_DOC(KX_SCA_ReplaceMeshActuator,instantReplaceMesh);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif
-
+#endif /* __KX_SCA_REPLACEMESHACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
index 13200696ffb..19b9d13087d 100644
--- a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
+++ b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
@@ -51,14 +51,14 @@ KX_BoneParentRelation::
New(Bone* bone
) {
return new KX_BoneParentRelation(bone);
-}
+}
bool
KX_BoneParentRelation::
UpdateChildCoordinates(
SG_Spatial * child,
const SG_Spatial * parent,
- bool& parentUpdated
+ bool& parentUpdated
) {
MT_assert(child != NULL);
@@ -71,7 +71,7 @@ UpdateChildCoordinates(
// we don't know if the armature has been updated or not, assume yes
parentUpdated = true;
- // the childs world locations which we will update.
+ // the childs world locations which we will update.
MT_Vector3 child_w_scale;
MT_Point3 child_w_pos;
diff --git a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h
index 76fefdebe08..6f4fd482198 100644
--- a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h
+++ b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h
@@ -57,7 +57,7 @@ public :
static
KX_BoneParentRelation *
New(Bone* bone
- );
+ );
/**
* Updates the childs world coordinates relative to the parent's
diff --git a/source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp b/source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp
index 699b267496d..e80de76861e 100644
--- a/source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp
+++ b/source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp
@@ -45,14 +45,14 @@ KX_NormalParentRelation::
New(
) {
return new KX_NormalParentRelation();
-}
+}
bool
KX_NormalParentRelation::
UpdateChildCoordinates(
SG_Spatial * child,
const SG_Spatial * parent,
- bool& parentUpdated
+ bool& parentUpdated
) {
MT_assert(child != NULL);
@@ -67,7 +67,7 @@ UpdateChildCoordinates(
return true; //false;
}
else {
- // the childs world locations which we will update.
+ // the childs world locations which we will update.
const MT_Vector3 & p_world_scale = parent->GetWorldScaling();
const MT_Point3 & p_world_pos = parent->GetWorldPosition();
const MT_Matrix3x3 & p_world_rotation = parent->GetWorldOrientation();
@@ -121,7 +121,7 @@ KX_VertexParentRelation::
UpdateChildCoordinates(
SG_Spatial * child,
const SG_Spatial * parent,
- bool& parentUpdated
+ bool& parentUpdated
) {
MT_assert(child != NULL);
@@ -176,7 +176,7 @@ New(
MT_Scalar relaxation
) {
return new KX_SlowParentRelation(relaxation);
-}
+}
/**
* Method inherited from KX_ParentRelation
@@ -187,7 +187,7 @@ KX_SlowParentRelation::
UpdateChildCoordinates(
SG_Spatial * child,
const SG_Spatial * parent,
- bool& parentUpdated
+ bool& parentUpdated
) {
MT_assert(child != NULL);
@@ -198,7 +198,7 @@ UpdateChildCoordinates(
const MT_Point3 & child_pos = child->GetLocalPosition();
const MT_Matrix3x3 & child_rotation = child->GetLocalOrientation();
- // the childs world locations which we will update.
+ // the childs world locations which we will update.
MT_Vector3 child_w_scale;
MT_Point3 child_w_pos;
@@ -230,7 +230,7 @@ UpdateChildCoordinates(
child_w_scale = child->GetWorldScaling();
child_w_pos = child->GetWorldPosition();
- child_w_rotation = child->GetWorldOrientation();
+ child_w_rotation = child->GetWorldOrientation();
// now 'interpolate' the normal coordinates with the last
// world coordinates to get the new world coordinates.
diff --git a/source/gameengine/Ketsji/KX_SG_NodeRelationships.h b/source/gameengine/Ketsji/KX_SG_NodeRelationships.h
index b5ab5302910..5d777f5028f 100644
--- a/source/gameengine/Ketsji/KX_SG_NodeRelationships.h
+++ b/source/gameengine/Ketsji/KX_SG_NodeRelationships.h
@@ -57,7 +57,7 @@ public :
static
KX_NormalParentRelation *
New(
- );
+ );
/**
* Method inherited from KX_ParentRelation
@@ -67,7 +67,7 @@ public :
UpdateChildCoordinates(
SG_Spatial * child,
const SG_Spatial * parent,
- bool& parentUpdated
+ bool& parentUpdated
);
/**
@@ -106,7 +106,7 @@ public :
static
KX_VertexParentRelation *
New(
- );
+ );
/**
* Method inherited from KX_ParentRelation
@@ -116,7 +116,7 @@ public :
UpdateChildCoordinates(
SG_Spatial * child,
const SG_Spatial * parent,
- bool& parentUpdated
+ bool& parentUpdated
);
/**
@@ -162,7 +162,7 @@ public :
KX_SlowParentRelation *
New(
MT_Scalar relaxation
- );
+ );
/**
* Method inherited from KX_ParentRelation
@@ -172,7 +172,7 @@ public :
UpdateChildCoordinates(
SG_Spatial * child,
const SG_Spatial * parent,
- bool& parentUpdated
+ bool& parentUpdated
);
/**
diff --git a/source/gameengine/Ketsji/KX_Scene.cpp b/source/gameengine/Ketsji/KX_Scene.cpp
index c1afed82b02..96b4a21a36c 100644
--- a/source/gameengine/Ketsji/KX_Scene.cpp
+++ b/source/gameengine/Ketsji/KX_Scene.cpp
@@ -31,9 +31,9 @@
*/
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable : 4786)
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
+#endif
#include "KX_Scene.h"
#include "KX_PythonInit.h"
@@ -98,7 +98,7 @@
#include <stdio.h>
-void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
+static void *KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
{
KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
@@ -108,7 +108,7 @@ void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
return (void*)replica;
}
-void* KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
+static void *KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
{
((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
@@ -368,7 +368,7 @@ void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
const RAS_FrameSettings& KX_Scene::GetFramingType() const
{
return m_frame_settings;
-};
+};
@@ -441,7 +441,7 @@ void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
{
- KX_GameObject* orgobj = (KX_GameObject*)gameobj;
+ KX_GameObject* orgobj = (KX_GameObject*)gameobj;
if (NewRemoveObject(orgobj) != 0)
{
// object is not yet deleted because a reference is hanging somewhere.
@@ -769,6 +769,13 @@ void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
// we can now add the graphic controller to the physic engine
replica->ActivateGraphicController(true);
+ // set references for dupli-group
+ // groupobj holds a list of all objects, that belongs to this group
+ groupobj->AddInstanceObjects(replica);
+
+ // every object gets the reference to its dupli-group object
+ replica->SetDupliGroupObject(groupobj);
+
// done with replica
replica->Release();
}
@@ -1017,6 +1024,20 @@ int KX_Scene::NewRemoveObject(class CValue* gameobj)
m_timemgr->RemoveTimeProperty(propval);
}
}
+
+ // if the object is the dupligroup proxy, you have to cleanup all m_pDupliGroupObject's in all
+ // instances refering to this group
+ if (newobj->GetInstanceObjects()) {
+ for (int i = 0; i < newobj->GetInstanceObjects()->GetCount(); i++) {
+ KX_GameObject* instance = (KX_GameObject*)newobj->GetInstanceObjects()->GetValue(i);
+ instance->RemoveDupliGroupObject();
+ }
+ }
+
+ // if this object was part of a group, make sure to remove it from that group's instance list
+ KX_GameObject* group = newobj->GetDupliGroupObject();
+ if (group)
+ group->RemoveInstanceObject(newobj);
newobj->RemoveMeshes();
ret = 1;
@@ -1072,7 +1093,7 @@ void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj, bool use_gfx, bool u
}
if (use_gfx && mesh != NULL)
- {
+ {
gameobj->RemoveMeshes();
gameobj->AddMesh(mesh);
@@ -1233,9 +1254,9 @@ KX_FontObject* KX_Scene::FindFont(KX_FontObject* font)
{
list<KX_FontObject*>::iterator it = m_fonts.begin();
- while ( (it != m_fonts.end())
- && ((*it) != font) ) {
- ++it;
+ while ((it != m_fonts.end()) && ((*it) != font))
+ {
+ ++it;
}
return ((it == m_fonts.end()) ? NULL : (*it));
@@ -1247,9 +1268,7 @@ KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
{
list<KX_Camera*>::iterator it = m_cameras.begin();
- while ( (it != m_cameras.end())
- && ((*it) != cam) )
- {
+ while ((it != m_cameras.end()) && ((*it) != cam)) {
it++;
}
@@ -1261,9 +1280,7 @@ KX_Camera* KX_Scene::FindCamera(STR_String& name)
{
list<KX_Camera*>::iterator it = m_cameras.begin();
- while ( (it != m_cameras.end())
- && ((*it)->GetName() != name) )
- {
+ while ((it != m_cameras.end()) && ((*it)->GetName() != name)) {
it++;
}
@@ -1278,7 +1295,7 @@ void KX_Scene::AddCamera(KX_Camera* cam)
KX_Camera* KX_Scene::GetActiveCamera()
-{
+{
// NULL if not defined
return m_active_camera;
}
@@ -1481,7 +1498,15 @@ void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int
planes[4].setValue(cplanes[2].getValue()); // top
planes[5].setValue(cplanes[3].getValue()); // bottom
CullingInfo info(layer);
- dbvt_culling = m_physicsEnvironment->cullingTest(PhysicsCullingCallback,&info,planes,5,m_dbvt_occlusion_res);
+
+ double mvmat[16] = {0};
+ cam->GetModelviewMatrix().getValue(mvmat);
+ double pmat[16] = {0};
+ cam->GetProjectionMatrix().getValue(pmat);
+
+ dbvt_culling = m_physicsEnvironment->cullingTest(PhysicsCullingCallback,&info,planes,5,m_dbvt_occlusion_res,
+ KX_GetActiveEngine()->GetCanvas()->GetViewPort(),
+ mvmat, pmat);
}
if (!dbvt_culling) {
// the physics engine couldn't help us, do it the hard way
@@ -1610,8 +1635,8 @@ RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool
void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
- class RAS_IRasterizer* rasty,
- class RAS_IRenderTools* rendertools)
+ class RAS_IRasterizer* rasty,
+ class RAS_IRenderTools* rendertools)
{
m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
KX_BlenderMaterial::EndFrame();
@@ -1634,16 +1659,17 @@ void KX_Scene::UpdateObjectActivity(void)
* Manhattan distance. */
MT_Point3 obpos = ob->NodeGetWorldPosition();
- if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
- || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
- || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
- {
+ if ((fabs(camloc[0] - obpos[0]) > m_activity_box_radius) ||
+ (fabs(camloc[1] - obpos[1]) > m_activity_box_radius) ||
+ (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
+ {
ob->Suspend();
- } else {
+ }
+ else {
ob->Resume();
}
}
- }
+ }
}
}
@@ -1944,15 +1970,15 @@ void KX_Scene::Render2DFilters(RAS_ICanvas* canvas)
#ifdef WITH_PYTHON
-void KX_Scene::RunDrawingCallbacks(PyObject* cb_list)
+void KX_Scene::RunDrawingCallbacks(PyObject *cb_list)
{
Py_ssize_t len;
if (cb_list && (len=PyList_GET_SIZE(cb_list)))
{
- PyObject* args= PyTuple_New(0); // save python creating each call
- PyObject* func;
- PyObject* ret;
+ PyObject *args = PyTuple_New(0); // save python creating each call
+ PyObject *func;
+ PyObject *ret;
// Iterate the list and run the callbacks
for (Py_ssize_t pos=0; pos < len; pos++)
@@ -2017,11 +2043,11 @@ PyMethodDef KX_Scene::Methods[] = {
};
static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
{
- KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
+ KX_Scene* self = static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
const char *attr_str= _PyUnicode_AsString(item);
- PyObject* pyconvert;
+ PyObject *pyconvert;
- if (self==NULL) {
+ if (self == NULL) {
PyErr_SetString(PyExc_SystemError, "val = scene[key]: KX_Scene, "BGE_PROXY_ERROR_MSG);
return NULL;
}
@@ -2043,12 +2069,12 @@ static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
{
- KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
+ KX_Scene* self = static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
const char *attr_str= _PyUnicode_AsString(key);
if (attr_str==NULL)
PyErr_Clear();
- if (self==NULL) {
+ if (self == NULL) {
PyErr_SetString(PyExc_SystemError, "scene[key] = value: KX_Scene, "BGE_PROXY_ERROR_MSG);
return -1;
}
@@ -2090,9 +2116,9 @@ static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
static int Seq_Contains(PyObject *self_v, PyObject *value)
{
- KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
+ KX_Scene* self = static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
- if (self==NULL) {
+ if (self == NULL) {
PyErr_SetString(PyExc_SystemError, "val in scene: KX_Scene, "BGE_PROXY_ERROR_MSG);
return -1;
}
@@ -2104,56 +2130,56 @@ static int Seq_Contains(PyObject *self_v, PyObject *value)
}
PyMappingMethods KX_Scene::Mapping = {
- (lenfunc)NULL , /*inquiry mp_length */
- (binaryfunc)Map_GetItem, /*binaryfunc mp_subscript */
- (objobjargproc)Map_SetItem, /*objobjargproc mp_ass_subscript */
+ (lenfunc)NULL, /* inquiry mp_length */
+ (binaryfunc)Map_GetItem, /* binaryfunc mp_subscript */
+ (objobjargproc)Map_SetItem, /* objobjargproc mp_ass_subscript */
};
PySequenceMethods KX_Scene::Sequence = {
- NULL, /* Cant set the len otherwise it can evaluate as false */
- NULL, /* sq_concat */
- NULL, /* sq_repeat */
- NULL, /* sq_item */
- NULL, /* sq_slice */
- NULL, /* sq_ass_item */
- NULL, /* sq_ass_slice */
- (objobjproc)Seq_Contains, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
+ NULL, /* Cant set the len otherwise it can evaluate as false */
+ NULL, /* sq_concat */
+ NULL, /* sq_repeat */
+ NULL, /* sq_item */
+ NULL, /* sq_slice */
+ NULL, /* sq_ass_item */
+ NULL, /* sq_ass_slice */
+ (objobjproc)Seq_Contains, /* sq_contains */
+ (binaryfunc) NULL, /* sq_inplace_concat */
+ (ssizeargfunc) NULL, /* sq_inplace_repeat */
};
-PyObject* KX_Scene::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Scene::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Scene* self= static_cast<KX_Scene*>(self_v);
+ KX_Scene* self = static_cast<KX_Scene*>(self_v);
return PyUnicode_From_STR_String(self->GetName());
}
-PyObject* KX_Scene::pyattr_get_objects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Scene::pyattr_get_objects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Scene* self= static_cast<KX_Scene*>(self_v);
+ KX_Scene* self = static_cast<KX_Scene*>(self_v);
return self->GetObjectList()->GetProxy();
}
-PyObject* KX_Scene::pyattr_get_objects_inactive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Scene::pyattr_get_objects_inactive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Scene* self= static_cast<KX_Scene*>(self_v);
+ KX_Scene* self = static_cast<KX_Scene*>(self_v);
return self->GetInactiveList()->GetProxy();
}
-PyObject* KX_Scene::pyattr_get_lights(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Scene::pyattr_get_lights(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Scene* self= static_cast<KX_Scene*>(self_v);
+ KX_Scene* self = static_cast<KX_Scene*>(self_v);
return self->GetLightList()->GetProxy();
}
-PyObject* KX_Scene::pyattr_get_cameras(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Scene::pyattr_get_cameras(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
/* With refcounts in this case...
* the new CListValue is owned by python, so its possible python holds onto it longer then the BGE
* however this is the same with "scene.objects + []", when you make a copy by adding lists.
*/
- KX_Scene* self= static_cast<KX_Scene*>(self_v);
+ KX_Scene* self = static_cast<KX_Scene*>(self_v);
CListValue* clist = new CListValue();
/* return self->GetCameras()->GetProxy(); */
@@ -2167,9 +2193,9 @@ PyObject* KX_Scene::pyattr_get_cameras(void *self_v, const KX_PYATTRIBUTE_DEF *a
return clist->NewProxy(true);
}
-PyObject* KX_Scene::pyattr_get_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Scene::pyattr_get_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_Scene* self= static_cast<KX_Scene*>(self_v);
+ KX_Scene* self = static_cast<KX_Scene*>(self_v);
KX_Camera* cam= self->GetActiveCamera();
if (cam)
return self->GetActiveCamera()->GetProxy();
@@ -2180,7 +2206,7 @@ PyObject* KX_Scene::pyattr_get_active_camera(void *self_v, const KX_PYATTRIBUTE_
int KX_Scene::pyattr_set_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_Scene* self= static_cast<KX_Scene*>(self_v);
+ KX_Scene* self = static_cast<KX_Scene*>(self_v);
KX_Camera *camOb;
if (!ConvertPythonToCamera(value, &camOb, false, "scene.active_camera = value: KX_Scene"))
@@ -2190,7 +2216,7 @@ int KX_Scene::pyattr_set_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *a
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_Scene::pyattr_get_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Scene::pyattr_get_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_Scene* self = static_cast<KX_Scene*>(self_v);
@@ -2200,7 +2226,7 @@ PyObject* KX_Scene::pyattr_get_drawing_callback_pre(void *self_v, const KX_PYATT
return self->m_draw_call_pre;
}
-PyObject* KX_Scene::pyattr_get_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_Scene::pyattr_get_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
KX_Scene* self = static_cast<KX_Scene*>(self_v);
@@ -2354,8 +2380,8 @@ KX_PYMETHODDEF_DOC(KX_Scene, drawObstacleSimulation,
KX_PYMETHODDEF_DOC(KX_Scene, get, "")
{
PyObject *key;
- PyObject* def = Py_None;
- PyObject* ret;
+ PyObject *def = Py_None;
+ PyObject *ret;
if (!PyArg_ParseTuple(args, "O|O:get", &key, &def))
return NULL;
diff --git a/source/gameengine/Ketsji/KX_Scene.h b/source/gameengine/Ketsji/KX_Scene.h
index f8480753395..c2e468e6da6 100644
--- a/source/gameengine/Ketsji/KX_Scene.h
+++ b/source/gameengine/Ketsji/KX_Scene.h
@@ -237,7 +237,7 @@ protected:
/**
* The execution priority of replicated object actuators?
- */
+ */
int m_ueberExecutionPriority;
/**
@@ -295,7 +295,7 @@ protected:
KX_ObstacleSimulation* m_obstacleSimulation;
-public:
+public:
KX_Scene(class SCA_IInputDevice* keyboarddevice,
class SCA_IInputDevice* mousedevice,
class NG_NetworkDeviceInterface* ndi,
@@ -303,7 +303,7 @@ public:
struct Scene* scene,
class RAS_ICanvas* canvas);
- virtual
+ virtual
~KX_Scene();
RAS_BucketManager* GetBucketManager();
@@ -349,11 +349,11 @@ public:
void LogicUpdateFrame(double curtime, bool frame);
void UpdateAnimations(double curtime);
- void
+ void
LogicEndFrame(
);
- CListValue*
+ CListValue*
GetTempObjectList(
);
@@ -361,23 +361,23 @@ public:
GetObjectList(
);
- CListValue*
+ CListValue*
GetInactiveList(
);
- CListValue*
+ CListValue*
GetRootParentList(
);
- CListValue*
+ CListValue*
GetLightList(
);
- SCA_LogicManager*
+ SCA_LogicManager *
GetLogicManager(
);
- SCA_TimeEventManager*
+ SCA_TimeEventManager *
GetTimeEventManager(
);
@@ -426,7 +426,7 @@ public:
);
/** Find the currently active camera. */
- KX_Camera*
+ KX_Camera*
GetActiveCamera(
);
@@ -435,7 +435,7 @@ public:
* camera is not present in the camera list, it will be added
*/
- void
+ void
SetActiveCamera(
class KX_Camera*
);
@@ -453,7 +453,7 @@ public:
* Activates new desired canvas width set at design time.
* \param width The new desired width.
*/
- void
+ void
SetCanvasDesignWidth(
unsigned int width
);
@@ -461,7 +461,7 @@ public:
* Activates new desired canvas height set at design time.
* \param width The new desired height.
*/
- void
+ void
SetCanvasDesignHeight(
unsigned int height
);
@@ -469,7 +469,7 @@ public:
* Returns the current desired canvas width set at design time.
* \return The desired width.
*/
- unsigned int
+ unsigned int
GetCanvasDesignWidth(
void
) const;
@@ -478,7 +478,7 @@ public:
* Returns the current desired canvas height set at design time.
* \return The desired height.
*/
- unsigned int
+ unsigned int
GetCanvasDesignHeight(
void
) const;
@@ -617,7 +617,7 @@ public:
static PyObject* pyattr_get_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_drawing_callback_post(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- virtual PyObject* py_repr(void) { return PyUnicode_From_STR_String(GetName()); }
+ virtual PyObject *py_repr(void) { return PyUnicode_From_STR_String(GetName()); }
/* getitem/setitem */
static PyMappingMethods Mapping;
@@ -626,10 +626,10 @@ public:
/**
* Run the registered python drawing functions.
*/
- void RunDrawingCallbacks(PyObject* cb_list);
+ void RunDrawingCallbacks(PyObject *cb_list);
- PyObject* GetPreDrawCB() { return m_draw_call_pre; }
- PyObject* GetPostDrawCB() { return m_draw_call_post; }
+ PyObject *GetPreDrawCB() { return m_draw_call_pre; }
+ PyObject *GetPostDrawCB() { return m_draw_call_post; }
#endif
/**
@@ -665,5 +665,4 @@ public:
typedef std::vector<KX_Scene*> KX_SceneList;
-#endif //__KX_SCENE_H__
-
+#endif /* __KX_SCENE_H__ */
diff --git a/source/gameengine/Ketsji/KX_SceneActuator.cpp b/source/gameengine/Ketsji/KX_SceneActuator.cpp
index 781c1fdab87..83b57dee7c1 100644
--- a/source/gameengine/Ketsji/KX_SceneActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SceneActuator.cpp
@@ -256,7 +256,7 @@ PyAttributeDef KX_SceneActuator::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_SceneActuator::pyattr_get_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SceneActuator::pyattr_get_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SceneActuator* actuator = static_cast<KX_SceneActuator*>(self);
if (!actuator->m_camera)
@@ -279,7 +279,7 @@ int KX_SceneActuator::pyattr_set_camera(void *self, const struct KX_PYATTRIBUTE_
if (camOb==NULL) {
actuator->m_camera= NULL;
}
- else {
+ else {
actuator->m_camera = camOb;
actuator->m_camera->RegisterActuator(actuator);
}
diff --git a/source/gameengine/Ketsji/KX_SceneActuator.h b/source/gameengine/Ketsji/KX_SceneActuator.h
index 8e157544e2e..389e9208ef3 100644
--- a/source/gameengine/Ketsji/KX_SceneActuator.h
+++ b/source/gameengine/Ketsji/KX_SceneActuator.h
@@ -99,12 +99,11 @@ class KX_SceneActuator : public SCA_IActuator
/* Python interface ---------------------------------------------------- */
/* --------------------------------------------------------------------- */
- static PyObject* pyattr_get_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
}; /* end of class KXSceneActuator */
#endif
-
diff --git a/source/gameengine/Ketsji/KX_SoundActuator.cpp b/source/gameengine/Ketsji/KX_SoundActuator.cpp
index db91cea9074..f76f94aa81d 100644
--- a/source/gameengine/Ketsji/KX_SoundActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SoundActuator.cpp
@@ -325,15 +325,14 @@ KX_PYMETHODDEF_DOC_NOARGS(KX_SoundActuator, startSound,
"startSound()\n"
"\tStarts the sound.\n")
{
- switch(m_handle.isNull() ? AUD_STATUS_INVALID : m_handle->getStatus())
- {
- case AUD_STATUS_PLAYING:
- break;
- case AUD_STATUS_PAUSED:
- m_handle->resume();
- break;
- default:
- play();
+ switch (m_handle.isNull() ? AUD_STATUS_INVALID : m_handle->getStatus()) {
+ case AUD_STATUS_PLAYING:
+ break;
+ case AUD_STATUS_PAUSED:
+ m_handle->resume();
+ break;
+ default:
+ play();
}
Py_RETURN_NONE;
}
@@ -358,7 +357,7 @@ KX_PYMETHODDEF_DOC_NOARGS(KX_SoundActuator, stopSound,
}
/* Atribute setting and getting -------------------------------------------- */
-PyObject* KX_SoundActuator::pyattr_get_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SoundActuator::pyattr_get_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
const char* prop = attrdef->m_name;
@@ -392,11 +391,11 @@ PyObject* KX_SoundActuator::pyattr_get_3d_property(void *self, const struct KX_P
Py_RETURN_NONE;
}
- PyObject* result = PyFloat_FromDouble(result_value);
+ PyObject *result = PyFloat_FromDouble(result_value);
return result;
}
-PyObject* KX_SoundActuator::pyattr_get_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SoundActuator::pyattr_get_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
float position = 0.0;
@@ -404,32 +403,32 @@ PyObject* KX_SoundActuator::pyattr_get_audposition(void *self, const struct KX_P
if (!actuator->m_handle.isNull())
position = actuator->m_handle->getPosition();
- PyObject* result = PyFloat_FromDouble(position);
+ PyObject *result = PyFloat_FromDouble(position);
return result;
}
-PyObject* KX_SoundActuator::pyattr_get_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SoundActuator::pyattr_get_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
float gain = actuator->m_volume;
- PyObject* result = PyFloat_FromDouble(gain);
+ PyObject *result = PyFloat_FromDouble(gain);
return result;
}
-PyObject* KX_SoundActuator::pyattr_get_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SoundActuator::pyattr_get_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
float pitch = actuator->m_pitch;
- PyObject* result = PyFloat_FromDouble(pitch);
+ PyObject *result = PyFloat_FromDouble(pitch);
return result;
}
-PyObject* KX_SoundActuator::pyattr_get_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SoundActuator::pyattr_get_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
if (!actuator->m_sound.isNull())
@@ -542,7 +541,7 @@ int KX_SoundActuator::pyattr_set_pitch(void *self, const struct KX_PYATTRIBUTE_D
int KX_SoundActuator::pyattr_set_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- PyObject* sound = NULL;
+ PyObject *sound = NULL;
KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
if (!PyArg_Parse(value, "O", &sound))
return PY_SET_ATTR_FAIL;
diff --git a/source/gameengine/Ketsji/KX_SoundActuator.h b/source/gameengine/Ketsji/KX_SoundActuator.h
index dbdb17d0da5..1ce44e942e8 100644
--- a/source/gameengine/Ketsji/KX_SoundActuator.h
+++ b/source/gameengine/Ketsji/KX_SoundActuator.h
@@ -115,16 +115,15 @@ public:
static int pyattr_set_type(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
static int pyattr_set_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_type(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_type(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
};
-#endif //__KX_SOUNDACTUATOR_H__
-
+#endif /* __KX_SOUNDACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_SteeringActuator.cpp b/source/gameengine/Ketsji/KX_SteeringActuator.cpp
index 16b9285386a..2fa72c04a20 100644
--- a/source/gameengine/Ketsji/KX_SteeringActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SteeringActuator.cpp
@@ -253,7 +253,7 @@ bool KX_SteeringActuator::Update(double curtime, bool frame)
static const MT_Vector3 PATH_COLOR(1,0,0);
m_navmesh->DrawPath(m_path, m_pathLen, PATH_COLOR);
}
- }
+ }
}
break;
@@ -285,7 +285,7 @@ bool KX_SteeringActuator::Update(double curtime, bool frame)
//temporary solution: set 2D steering velocity directly to obj
//correct way is to apply physical force
MT_Vector3 curvel = obj->GetLinearVelocity();
- newvel.z() = curvel.z();
+ newvel.z() = curvel.z();
obj->setLinearVelocity(newvel, false);
}
else
@@ -356,8 +356,8 @@ static bool getNavmeshNormal(dtStatNavMesh* navmesh, const MT_Vector3& pos, MT_V
{
static const float polyPickExt[3] = {2, 4, 2};
float spos[3];
- pos.getValue(spos);
- flipAxes(spos);
+ pos.getValue(spos);
+ flipAxes(spos);
dtStatPolyRef sPolyRef = navmesh->findNearestPoly(spos, polyPickExt);
if (sPolyRef == 0)
return false;
@@ -382,7 +382,7 @@ static bool getNavmeshNormal(dtStatNavMesh* navmesh, const MT_Vector3& pos, MT_V
{
distMin = dist;
idxMin = i;
- }
+ }
}
if (idxMin>=0)
@@ -416,7 +416,7 @@ void KX_SteeringActuator::HandleActorFace(MT_Vector3& velocity)
KX_GameObject* curobj = (KX_GameObject*) GetParent();
MT_Vector3 dir = m_facingMode==0 ? curobj->NodeGetLocalOrientation().getColumn(1) : velocity;
if (dir.fuzzyZero())
- return;
+ return;
dir.normalize();
MT_Vector3 up(0,0,1);
MT_Vector3 left;
@@ -431,7 +431,7 @@ void KX_SteeringActuator::HandleActorFace(MT_Vector3& velocity)
{
left = (dir.cross(up)).safe_normalized();
- dir = (-left.cross(normal)).safe_normalized();
+ dir = (-left.cross(normal)).safe_normalized();
up = normal;
}
}
@@ -495,7 +495,7 @@ void KX_SteeringActuator::HandleActorFace(MT_Vector3& velocity)
MT_Point3 localpos;
localpos = curobj->GetSGNode()->GetLocalPosition();
MT_Matrix3x3 parentmatinv;
- parentmatinv = parentObject->NodeGetWorldOrientation ().inverse ();
+ parentmatinv = parentObject->NodeGetWorldOrientation ().inverse ();
mat = parentmatinv * mat;
mat = m_parentlocalmat * mat;
curobj->NodeSetLocalOrientation(mat);
@@ -551,16 +551,16 @@ PyAttributeDef KX_SteeringActuator::Attributes[] = {
KX_PYATTRIBUTE_FLOAT_RW("turnspeed", 0.0f, 720.0f, KX_SteeringActuator, m_turnspeed),
KX_PYATTRIBUTE_BOOL_RW("selfterminated", KX_SteeringActuator, m_isSelfTerminated),
KX_PYATTRIBUTE_BOOL_RW("enableVisualization", KX_SteeringActuator, m_enableVisualization),
- KX_PYATTRIBUTE_RO_FUNCTION("steeringVec", KX_SteeringActuator, pyattr_get_steeringVec),
+ KX_PYATTRIBUTE_RO_FUNCTION("steeringVec", KX_SteeringActuator, pyattr_get_steeringVec),
KX_PYATTRIBUTE_SHORT_RW("facingMode", 0, 6, true, KX_SteeringActuator, m_facingMode),
KX_PYATTRIBUTE_INT_RW("pathUpdatePeriod", -1, 100000, true, KX_SteeringActuator, m_pathUpdatePeriod),
{ NULL } //Sentinel
};
-PyObject* KX_SteeringActuator::pyattr_get_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SteeringActuator::pyattr_get_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SteeringActuator* actuator = static_cast<KX_SteeringActuator*>(self);
- if (!actuator->m_target)
+ if (!actuator->m_target)
Py_RETURN_NONE;
else
return actuator->m_target->GetProxy();
@@ -575,7 +575,7 @@ int KX_SteeringActuator::pyattr_set_target(void *self, const struct KX_PYATTRIBU
return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
if (actuator->m_target != NULL)
- actuator->m_target->UnregisterActuator(actuator);
+ actuator->m_target->UnregisterActuator(actuator);
actuator->m_target = (KX_GameObject*) gameobj;
@@ -585,10 +585,10 @@ int KX_SteeringActuator::pyattr_set_target(void *self, const struct KX_PYATTRIBU
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_SteeringActuator::pyattr_get_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SteeringActuator::pyattr_get_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SteeringActuator* actuator = static_cast<KX_SteeringActuator*>(self);
- if (!actuator->m_navmesh)
+ if (!actuator->m_navmesh)
Py_RETURN_NONE;
else
return actuator->m_navmesh->GetProxy();
@@ -609,7 +609,7 @@ int KX_SteeringActuator::pyattr_set_navmesh(void *self, const struct KX_PYATTRIB
}
if (actuator->m_navmesh != NULL)
- actuator->m_navmesh->UnregisterActuator(actuator);
+ actuator->m_navmesh->UnregisterActuator(actuator);
actuator->m_navmesh = static_cast<KX_NavMeshObject*>(gameobj);
@@ -619,7 +619,7 @@ int KX_SteeringActuator::pyattr_set_navmesh(void *self, const struct KX_PYATTRIB
return PY_SET_ATTR_SUCCESS;
}
-PyObject* KX_SteeringActuator::pyattr_get_steeringVec(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_SteeringActuator::pyattr_get_steeringVec(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_SteeringActuator* actuator = static_cast<KX_SteeringActuator*>(self);
const MT_Vector3& steeringVec = actuator->GetSteeringVec();
diff --git a/source/gameengine/Ketsji/KX_SteeringActuator.h b/source/gameengine/Ketsji/KX_SteeringActuator.h
index c22a636cd95..1e8ac9a54f0 100644
--- a/source/gameengine/Ketsji/KX_SteeringActuator.h
+++ b/source/gameengine/Ketsji/KX_SteeringActuator.h
@@ -82,7 +82,7 @@ public:
KX_GameObject *navmesh,
float distance,
float velocity,
- float acceleration,
+ float acceleration,
float turnspeed,
bool isSelfTerminated,
int pathUpdatePeriod,
@@ -107,16 +107,15 @@ public:
/* --------------------------------------------------------------------- */
/* These are used to get and set m_target */
- static PyObject* pyattr_get_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_steeringVec(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static int pyattr_set_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
+ static PyObject *pyattr_get_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static int pyattr_set_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
+ static PyObject *pyattr_get_steeringVec(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
}; /* end of class KX_SteeringActuator : public SCA_PropertyActuator */
-#endif
-
+#endif /* __KX_STEERINGACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_TimeCategoryLogger.h b/source/gameengine/Ketsji/KX_TimeCategoryLogger.h
index ea780739695..e097454fca7 100644
--- a/source/gameengine/Ketsji/KX_TimeCategoryLogger.h
+++ b/source/gameengine/Ketsji/KX_TimeCategoryLogger.h
@@ -32,8 +32,8 @@
#ifndef __KX_TIMECATEGORYLOGGER_H__
#define __KX_TIMECATEGORYLOGGER_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786) // suppress stl-MSVC debug info warning
+#ifdef _MSC_VER
+# pragma warning (disable:4786) /* suppress stl-MSVC debug info warning */
#endif
#include <map>
@@ -133,5 +133,4 @@ protected:
#endif
};
-#endif // __KX_TIMECATEGORYLOGGER_H__
-
+#endif /* __KX_TIMECATEGORYLOGGER_H__ */
diff --git a/source/gameengine/Ketsji/KX_TimeLogger.h b/source/gameengine/Ketsji/KX_TimeLogger.h
index 83c934ea81b..59d7bdc84e3 100644
--- a/source/gameengine/Ketsji/KX_TimeLogger.h
+++ b/source/gameengine/Ketsji/KX_TimeLogger.h
@@ -32,14 +32,14 @@
#ifndef __KX_TIMELOGGER_H__
#define __KX_TIMELOGGER_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786) // suppress stl-MSVC debug info warning
+#ifdef _MSC_VER
+# pragma warning (disable:4786) /* suppress stl-MSVC debug info warning */
#endif
#include <deque>
#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
+# include "MEM_guardedalloc.h"
#endif
/**
@@ -111,5 +111,4 @@ protected:
#endif
};
-#endif // __KX_TIMELOGGER_H__
-
+#endif /* __KX_TIMELOGGER_H__ */
diff --git a/source/gameengine/Ketsji/KX_TouchEventManager.h b/source/gameengine/Ketsji/KX_TouchEventManager.h
index d9a0164fd05..63e9d15959e 100644
--- a/source/gameengine/Ketsji/KX_TouchEventManager.h
+++ b/source/gameengine/Ketsji/KX_TouchEventManager.h
@@ -85,5 +85,4 @@ public:
#endif
};
-#endif //__KX_TOUCHEVENTMANAGER_H__
-
+#endif /* __KX_TOUCHEVENTMANAGER_H__ */
diff --git a/source/gameengine/Ketsji/KX_TouchSensor.cpp b/source/gameengine/Ketsji/KX_TouchSensor.cpp
index d7bcf1306a1..36e0bf692f1 100644
--- a/source/gameengine/Ketsji/KX_TouchSensor.cpp
+++ b/source/gameengine/Ketsji/KX_TouchSensor.cpp
@@ -331,9 +331,9 @@ PyAttributeDef KX_TouchSensor::Attributes[] = {
/* Python API */
-PyObject* KX_TouchSensor::pyattr_get_object_hit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_TouchSensor::pyattr_get_object_hit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_TouchSensor* self= static_cast<KX_TouchSensor*>(self_v);
+ KX_TouchSensor* self = static_cast<KX_TouchSensor*>(self_v);
if (self->m_hitObject)
return self->m_hitObject->GetProxy();
@@ -341,9 +341,9 @@ PyObject* KX_TouchSensor::pyattr_get_object_hit(void *self_v, const KX_PYATTRIBU
Py_RETURN_NONE;
}
-PyObject* KX_TouchSensor::pyattr_get_object_hit_list(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_TouchSensor::pyattr_get_object_hit_list(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_TouchSensor* self= static_cast<KX_TouchSensor*>(self_v);
+ KX_TouchSensor* self = static_cast<KX_TouchSensor*>(self_v);
return self->m_colliders->GetProxy();
}
diff --git a/source/gameengine/Ketsji/KX_TouchSensor.h b/source/gameengine/Ketsji/KX_TouchSensor.h
index d739144d70d..6bd606db8eb 100644
--- a/source/gameengine/Ketsji/KX_TouchSensor.h
+++ b/source/gameengine/Ketsji/KX_TouchSensor.h
@@ -56,7 +56,7 @@ protected:
/**
* The sensor should only look for objects with this property.
*/
- STR_String m_touchedpropname;
+ STR_String m_touchedpropname;
bool m_bFindMaterial;
bool m_bTouchPulse; /* changes in the colliding objects trigger pulses */
@@ -134,5 +134,4 @@ public:
};
-#endif //__KX_TOUCHSENSOR_H__
-
+#endif /* __KX_TOUCHSENSOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_TrackToActuator.cpp b/source/gameengine/Ketsji/KX_TrackToActuator.cpp
index 99732130f83..1597948bafe 100644
--- a/source/gameengine/Ketsji/KX_TrackToActuator.cpp
+++ b/source/gameengine/Ketsji/KX_TrackToActuator.cpp
@@ -90,7 +90,7 @@ KX_TrackToActuator::KX_TrackToActuator(SCA_IObject *gameobj,
/* old function from Blender */
-MT_Matrix3x3 EulToMat3(float *eul)
+static MT_Matrix3x3 EulToMat3(float eul[3])
{
MT_Matrix3x3 mat;
float ci, cj, ch, si, sj, sh, cc, cs, sc, ss;
@@ -122,7 +122,7 @@ MT_Matrix3x3 EulToMat3(float *eul)
/* old function from Blender */
-void Mat3ToEulOld(MT_Matrix3x3 mat, float eul[3])
+static void Mat3ToEulOld(MT_Matrix3x3 mat, float eul[3])
{
const float cy = sqrtf(mat[0][0] * mat[0][0] + mat[0][1] * mat[0][1]);
@@ -141,7 +141,7 @@ void Mat3ToEulOld(MT_Matrix3x3 mat, float eul[3])
/* old function from Blender */
-void compatible_eulFast(float *eul, float *oldrot)
+static void compatible_eulFast(float *eul, float *oldrot)
{
float dx, dy, dz;
@@ -164,9 +164,9 @@ void compatible_eulFast(float *eul, float *oldrot)
-MT_Matrix3x3 matrix3x3_interpol(MT_Matrix3x3 oldmat, MT_Matrix3x3 mat, int m_time)
+static MT_Matrix3x3 matrix3x3_interpol(MT_Matrix3x3 oldmat, MT_Matrix3x3 mat, int m_time)
{
- float eul[3], oldeul[3];
+ float eul[3], oldeul[3];
Mat3ToEulOld(oldmat, oldeul);
Mat3ToEulOld(mat, eul);
@@ -238,7 +238,7 @@ void KX_TrackToActuator::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
bool KX_TrackToActuator::Update(double curtime, bool frame)
{
- bool result = false;
+ bool result = false;
bool bNegativeEvent = IsNegativeEvent();
RemoveAllEvents();
@@ -395,7 +395,7 @@ bool KX_TrackToActuator::Update(double curtime, bool frame)
localpos = curobj->GetSGNode()->GetLocalPosition();
// Get the inverse of the parent matrix
MT_Matrix3x3 parentmatinv;
- parentmatinv = m_parentobj->NodeGetWorldOrientation ().inverse ();
+ parentmatinv = m_parentobj->NodeGetWorldOrientation ().inverse ();
// transform the local coordinate system into the parents system
mat = parentmatinv * mat;
// append the initial parent local rotation matrix
@@ -458,10 +458,10 @@ PyAttributeDef KX_TrackToActuator::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_TrackToActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_TrackToActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
{
KX_TrackToActuator* actuator = static_cast<KX_TrackToActuator*>(self);
- if (!actuator->m_object)
+ if (!actuator->m_object)
Py_RETURN_NONE;
else
return actuator->m_object->GetProxy();
@@ -476,7 +476,7 @@ int KX_TrackToActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBUT
return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
if (actuator->m_object != NULL)
- actuator->m_object->UnregisterActuator(actuator);
+ actuator->m_object->UnregisterActuator(actuator);
actuator->m_object = (SCA_IObject*) gameobj;
diff --git a/source/gameengine/Ketsji/KX_TrackToActuator.h b/source/gameengine/Ketsji/KX_TrackToActuator.h
index fb2ced2a415..f5f5c4c2836 100644
--- a/source/gameengine/Ketsji/KX_TrackToActuator.h
+++ b/source/gameengine/Ketsji/KX_TrackToActuator.h
@@ -74,12 +74,11 @@ class KX_TrackToActuator : public SCA_IActuator
/* Python part */
/* These are used to get and set m_ob */
- static PyObject* pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
+ static PyObject *pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
+ static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
}; /* end of class KX_TrackToActuator : public KX_EditObjectActuator */
-#endif
-
+#endif /* __KX_TRACKTOACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_VehicleWrapper.cpp b/source/gameengine/Ketsji/KX_VehicleWrapper.cpp
index 1c03df80dc1..b5d6f11a2d5 100644
--- a/source/gameengine/Ketsji/KX_VehicleWrapper.cpp
+++ b/source/gameengine/Ketsji/KX_VehicleWrapper.cpp
@@ -34,11 +34,11 @@ KX_VehicleWrapper::~KX_VehicleWrapper()
#ifdef WITH_PYTHON
-PyObject* KX_VehicleWrapper::PyAddWheel(PyObject* args)
+PyObject *KX_VehicleWrapper::PyAddWheel(PyObject *args)
{
- PyObject* pylistPos,*pylistDir,*pylistAxleDir;
- PyObject* wheelGameObject;
+ PyObject *pylistPos,*pylistDir,*pylistAxleDir;
+ PyObject *wheelGameObject;
float suspensionRestLength,wheelRadius;
int hasSteering;
@@ -83,7 +83,7 @@ PyObject* KX_VehicleWrapper::PyAddWheel(PyObject* args)
-PyObject* KX_VehicleWrapper::PyGetWheelPosition(PyObject* args)
+PyObject *KX_VehicleWrapper::PyGetWheelPosition(PyObject *args)
{
int wheelIndex;
@@ -98,7 +98,7 @@ PyObject* KX_VehicleWrapper::PyGetWheelPosition(PyObject* args)
return NULL;
}
-PyObject* KX_VehicleWrapper::PyGetWheelRotation(PyObject* args)
+PyObject *KX_VehicleWrapper::PyGetWheelRotation(PyObject *args)
{
int wheelIndex;
if (PyArg_ParseTuple(args,"i:getWheelRotation",&wheelIndex))
@@ -108,7 +108,7 @@ PyObject* KX_VehicleWrapper::PyGetWheelRotation(PyObject* args)
return NULL;
}
-PyObject* KX_VehicleWrapper::PyGetWheelOrientationQuaternion(PyObject* args)
+PyObject *KX_VehicleWrapper::PyGetWheelOrientationQuaternion(PyObject *args)
{
int wheelIndex;
if (PyArg_ParseTuple(args,"i:getWheelOrientationQuaternion",&wheelIndex))
@@ -124,20 +124,20 @@ PyObject* KX_VehicleWrapper::PyGetWheelOrientationQuaternion(PyObject* args)
}
-PyObject* KX_VehicleWrapper::PyGetNumWheels(PyObject* args)
+PyObject *KX_VehicleWrapper::PyGetNumWheels(PyObject *args)
{
return PyLong_FromSsize_t(m_vehicle->GetNumWheels());
}
-PyObject* KX_VehicleWrapper::PyGetConstraintId(PyObject* args)
+PyObject *KX_VehicleWrapper::PyGetConstraintId(PyObject *args)
{
return PyLong_FromSsize_t(m_vehicle->GetUserConstraintId());
}
-PyObject* KX_VehicleWrapper::PyApplyEngineForce(PyObject* args)
+PyObject *KX_VehicleWrapper::PyApplyEngineForce(PyObject *args)
{
float force;
int wheelIndex;
@@ -153,7 +153,7 @@ PyObject* KX_VehicleWrapper::PyApplyEngineForce(PyObject* args)
Py_RETURN_NONE;
}
-PyObject* KX_VehicleWrapper::PySetTyreFriction(PyObject* args)
+PyObject *KX_VehicleWrapper::PySetTyreFriction(PyObject *args)
{
float wheelFriction;
int wheelIndex;
@@ -168,7 +168,7 @@ PyObject* KX_VehicleWrapper::PySetTyreFriction(PyObject* args)
Py_RETURN_NONE;
}
-PyObject* KX_VehicleWrapper::PySetSuspensionStiffness(PyObject* args)
+PyObject *KX_VehicleWrapper::PySetSuspensionStiffness(PyObject *args)
{
float suspensionStiffness;
int wheelIndex;
@@ -183,7 +183,7 @@ PyObject* KX_VehicleWrapper::PySetSuspensionStiffness(PyObject* args)
Py_RETURN_NONE;
}
-PyObject* KX_VehicleWrapper::PySetSuspensionDamping(PyObject* args)
+PyObject *KX_VehicleWrapper::PySetSuspensionDamping(PyObject *args)
{
float suspensionDamping;
int wheelIndex;
@@ -197,7 +197,7 @@ PyObject* KX_VehicleWrapper::PySetSuspensionDamping(PyObject* args)
Py_RETURN_NONE;
}
-PyObject* KX_VehicleWrapper::PySetSuspensionCompression(PyObject* args)
+PyObject *KX_VehicleWrapper::PySetSuspensionCompression(PyObject *args)
{
float suspensionCompression;
int wheelIndex;
@@ -211,7 +211,7 @@ PyObject* KX_VehicleWrapper::PySetSuspensionCompression(PyObject* args)
Py_RETURN_NONE;
}
-PyObject* KX_VehicleWrapper::PySetRollInfluence(PyObject* args)
+PyObject *KX_VehicleWrapper::PySetRollInfluence(PyObject *args)
{
float rollInfluence;
int wheelIndex;
@@ -227,7 +227,7 @@ PyObject* KX_VehicleWrapper::PySetRollInfluence(PyObject* args)
}
-PyObject* KX_VehicleWrapper::PyApplyBraking(PyObject* args)
+PyObject *KX_VehicleWrapper::PyApplyBraking(PyObject *args)
{
float braking;
int wheelIndex;
@@ -245,7 +245,7 @@ PyObject* KX_VehicleWrapper::PyApplyBraking(PyObject* args)
-PyObject* KX_VehicleWrapper::PySetSteeringValue(PyObject* args)
+PyObject *KX_VehicleWrapper::PySetSteeringValue(PyObject *args)
{
float steeringValue;
int wheelIndex;
@@ -261,7 +261,7 @@ PyObject* KX_VehicleWrapper::PySetSteeringValue(PyObject* args)
}
-PyObject* KX_VehicleWrapper::PyGetConstraintType(PyObject* args)
+PyObject *KX_VehicleWrapper::PyGetConstraintType(PyObject *args)
{
return PyLong_FromSsize_t(m_vehicle->GetUserConstraintType());
}
diff --git a/source/gameengine/Ketsji/KX_VehicleWrapper.h b/source/gameengine/Ketsji/KX_VehicleWrapper.h
index 3684019277c..ccd666e84f3 100644
--- a/source/gameengine/Ketsji/KX_VehicleWrapper.h
+++ b/source/gameengine/Ketsji/KX_VehicleWrapper.h
@@ -52,11 +52,11 @@ public:
KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetSuspensionCompression);
KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetRollInfluence);
-#endif // WITH_PYTHON
+#endif /* WITH_PYTHON */
private:
PHY_IVehicle* m_vehicle;
PHY_IPhysicsEnvironment* m_physenv;
};
-#endif //__KX_VEHICLEWRAPPER_H__
+#endif /* __KX_VEHICLEWRAPPER_H__ */
diff --git a/source/gameengine/Ketsji/KX_VertexProxy.cpp b/source/gameengine/Ketsji/KX_VertexProxy.cpp
index d489c015273..dabb79b357d 100644
--- a/source/gameengine/Ketsji/KX_VertexProxy.cpp
+++ b/source/gameengine/Ketsji/KX_VertexProxy.cpp
@@ -101,102 +101,102 @@ PyAttributeDef KX_VertexProxy::Attributes[] = {
{ NULL } //Sentinel
};
-PyObject* KX_VertexProxy::pyattr_get_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyFloat_FromDouble(self->m_vertex->getXYZ()[0]);
}
-PyObject* KX_VertexProxy::pyattr_get_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyFloat_FromDouble(self->m_vertex->getXYZ()[1]);
}
-PyObject* KX_VertexProxy::pyattr_get_z(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_z(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyFloat_FromDouble(self->m_vertex->getXYZ()[2]);
}
-PyObject* KX_VertexProxy::pyattr_get_r(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_r(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyFloat_FromDouble(self->m_vertex->getRGBA()[0]/255.0);
}
-PyObject* KX_VertexProxy::pyattr_get_g(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_g(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyFloat_FromDouble(self->m_vertex->getRGBA()[1]/255.0);
}
-PyObject* KX_VertexProxy::pyattr_get_b(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_b(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyFloat_FromDouble(self->m_vertex->getRGBA()[2]/255.0);
}
-PyObject* KX_VertexProxy::pyattr_get_a(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_a(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyFloat_FromDouble(self->m_vertex->getRGBA()[3]/255.0);
}
-PyObject* KX_VertexProxy::pyattr_get_u(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_u(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyFloat_FromDouble(self->m_vertex->getUV1()[0]);
}
-PyObject* KX_VertexProxy::pyattr_get_v(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_v(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyFloat_FromDouble(self->m_vertex->getUV1()[1]);
}
-PyObject* KX_VertexProxy::pyattr_get_u2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_u2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyFloat_FromDouble(self->m_vertex->getUV2()[0]);
}
-PyObject* KX_VertexProxy::pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyFloat_FromDouble(self->m_vertex->getUV2()[1]);
}
-PyObject* KX_VertexProxy::pyattr_get_XYZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_XYZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyObjectFrom(MT_Vector3(self->m_vertex->getXYZ()));
}
-PyObject* KX_VertexProxy::pyattr_get_UV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_UV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyObjectFrom(MT_Point2(self->m_vertex->getUV1()));
}
-PyObject* KX_VertexProxy::pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
const unsigned char *colp = self->m_vertex->getRGBA();
MT_Vector4 color(colp[0], colp[1], colp[2], colp[3]);
color /= 255.0;
return PyObjectFrom(color);
}
-PyObject* KX_VertexProxy::pyattr_get_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
+PyObject *KX_VertexProxy::pyattr_get_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
return PyObjectFrom(MT_Vector3(self->m_vertex->getNormal()));
}
int KX_VertexProxy::pyattr_set_x(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PyFloat_Check(value))
{
float val = PyFloat_AsDouble(value);
@@ -211,7 +211,7 @@ int KX_VertexProxy::pyattr_set_x(void *self_v, const struct KX_PYATTRIBUTE_DEF *
int KX_VertexProxy::pyattr_set_y(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PyFloat_Check(value))
{
float val = PyFloat_AsDouble(value);
@@ -226,7 +226,7 @@ int KX_VertexProxy::pyattr_set_y(void *self_v, const struct KX_PYATTRIBUTE_DEF *
int KX_VertexProxy::pyattr_set_z(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PyFloat_Check(value))
{
float val = PyFloat_AsDouble(value);
@@ -241,7 +241,7 @@ int KX_VertexProxy::pyattr_set_z(void *self_v, const struct KX_PYATTRIBUTE_DEF *
int KX_VertexProxy::pyattr_set_u(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PyFloat_Check(value))
{
float val = PyFloat_AsDouble(value);
@@ -256,7 +256,7 @@ int KX_VertexProxy::pyattr_set_u(void *self_v, const struct KX_PYATTRIBUTE_DEF *
int KX_VertexProxy::pyattr_set_v(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PyFloat_Check(value))
{
float val = PyFloat_AsDouble(value);
@@ -271,7 +271,7 @@ int KX_VertexProxy::pyattr_set_v(void *self_v, const struct KX_PYATTRIBUTE_DEF *
int KX_VertexProxy::pyattr_set_u2(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PyFloat_Check(value))
{
float val = PyFloat_AsDouble(value);
@@ -286,7 +286,7 @@ int KX_VertexProxy::pyattr_set_u2(void *self_v, const struct KX_PYATTRIBUTE_DEF
int KX_VertexProxy::pyattr_set_v2(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PyFloat_Check(value))
{
float val = PyFloat_AsDouble(value);
@@ -301,7 +301,7 @@ int KX_VertexProxy::pyattr_set_v2(void *self_v, const struct KX_PYATTRIBUTE_DEF
int KX_VertexProxy::pyattr_set_r(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PyFloat_Check(value))
{
float val = PyFloat_AsDouble(value);
@@ -318,7 +318,7 @@ int KX_VertexProxy::pyattr_set_r(void *self_v, const struct KX_PYATTRIBUTE_DEF *
int KX_VertexProxy::pyattr_set_g(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PyFloat_Check(value))
{
float val = PyFloat_AsDouble(value);
@@ -335,7 +335,7 @@ int KX_VertexProxy::pyattr_set_g(void *self_v, const struct KX_PYATTRIBUTE_DEF *
int KX_VertexProxy::pyattr_set_b(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PyFloat_Check(value))
{
float val = PyFloat_AsDouble(value);
@@ -352,7 +352,7 @@ int KX_VertexProxy::pyattr_set_b(void *self_v, const struct KX_PYATTRIBUTE_DEF *
int KX_VertexProxy::pyattr_set_a(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PyFloat_Check(value))
{
float val = PyFloat_AsDouble(value);
@@ -369,7 +369,7 @@ int KX_VertexProxy::pyattr_set_a(void *self_v, const struct KX_PYATTRIBUTE_DEF *
int KX_VertexProxy::pyattr_set_XYZ(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PySequence_Check(value))
{
MT_Point3 vec;
@@ -385,7 +385,7 @@ int KX_VertexProxy::pyattr_set_XYZ(void *self_v, const struct KX_PYATTRIBUTE_DEF
int KX_VertexProxy::pyattr_set_UV(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PySequence_Check(value))
{
MT_Point2 vec;
@@ -401,7 +401,7 @@ int KX_VertexProxy::pyattr_set_UV(void *self_v, const struct KX_PYATTRIBUTE_DEF
int KX_VertexProxy::pyattr_set_color(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PySequence_Check(value))
{
MT_Vector4 vec;
@@ -417,7 +417,7 @@ int KX_VertexProxy::pyattr_set_color(void *self_v, const struct KX_PYATTRIBUTE_D
int KX_VertexProxy::pyattr_set_normal(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
+ KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
if (PySequence_Check(value))
{
MT_Vector3 vec;
@@ -459,12 +459,12 @@ CValue* KX_VertexProxy::GetReplica() { return NULL;}
// stuff for python integration
-PyObject* KX_VertexProxy::PyGetXYZ()
+PyObject *KX_VertexProxy::PyGetXYZ()
{
return PyObjectFrom(MT_Point3(m_vertex->getXYZ()));
}
-PyObject* KX_VertexProxy::PySetXYZ(PyObject* value)
+PyObject *KX_VertexProxy::PySetXYZ(PyObject *value)
{
MT_Point3 vec;
if (!PyVecTo(value, vec))
@@ -475,12 +475,12 @@ PyObject* KX_VertexProxy::PySetXYZ(PyObject* value)
Py_RETURN_NONE;
}
-PyObject* KX_VertexProxy::PyGetNormal()
+PyObject *KX_VertexProxy::PyGetNormal()
{
return PyObjectFrom(MT_Vector3(m_vertex->getNormal()));
}
-PyObject* KX_VertexProxy::PySetNormal(PyObject* value)
+PyObject *KX_VertexProxy::PySetNormal(PyObject *value)
{
MT_Vector3 vec;
if (!PyVecTo(value, vec))
@@ -492,13 +492,13 @@ PyObject* KX_VertexProxy::PySetNormal(PyObject* value)
}
-PyObject* KX_VertexProxy::PyGetRGBA()
+PyObject *KX_VertexProxy::PyGetRGBA()
{
int *rgba = (int *) m_vertex->getRGBA();
return PyLong_FromSsize_t(*rgba);
}
-PyObject* KX_VertexProxy::PySetRGBA(PyObject* value)
+PyObject *KX_VertexProxy::PySetRGBA(PyObject *value)
{
if (PyLong_Check(value)) {
int rgba = PyLong_AsSsize_t(value);
@@ -521,12 +521,12 @@ PyObject* KX_VertexProxy::PySetRGBA(PyObject* value)
}
-PyObject* KX_VertexProxy::PyGetUV()
+PyObject *KX_VertexProxy::PyGetUV()
{
return PyObjectFrom(MT_Vector2(m_vertex->getUV1()));
}
-PyObject* KX_VertexProxy::PySetUV(PyObject* value)
+PyObject *KX_VertexProxy::PySetUV(PyObject *value)
{
MT_Point2 vec;
if (!PyVecTo(value, vec))
@@ -537,17 +537,17 @@ PyObject* KX_VertexProxy::PySetUV(PyObject* value)
Py_RETURN_NONE;
}
-PyObject* KX_VertexProxy::PyGetUV2()
+PyObject *KX_VertexProxy::PyGetUV2()
{
return PyObjectFrom(MT_Vector2(m_vertex->getUV2()));
}
-PyObject* KX_VertexProxy::PySetUV2(PyObject* args)
+PyObject *KX_VertexProxy::PySetUV2(PyObject *args)
{
MT_Point2 vec;
unsigned int unit= RAS_TexVert::SECOND_UV;
- PyObject* list= NULL;
+ PyObject *list = NULL;
if (!PyArg_ParseTuple(args, "O|i:setUV2", &list, &unit))
return NULL;
diff --git a/source/gameengine/Ketsji/KX_VertexProxy.h b/source/gameengine/Ketsji/KX_VertexProxy.h
index 3084e5fac93..6e193d35b4c 100644
--- a/source/gameengine/Ketsji/KX_VertexProxy.h
+++ b/source/gameengine/Ketsji/KX_VertexProxy.h
@@ -59,21 +59,21 @@ public:
// stuff for python integration
- static PyObject* pyattr_get_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_z(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_r(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_g(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_b(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_a(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_u(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_v(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_u2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_XYZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_UV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_z(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_r(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_g(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_b(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_a(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_u(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_v(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_u2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_XYZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_UV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
+ static PyObject *pyattr_get_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
static int pyattr_set_x(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
static int pyattr_set_y(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
static int pyattr_set_z(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
@@ -105,7 +105,6 @@ public:
};
-#endif // WITH_PYTHON
-
-#endif //__KX_VERTEXPROXY_H__
+#endif /* WITH_PYTHON */
+#endif /* __KX_VERTEXPROXY_H__ */
diff --git a/source/gameengine/Ketsji/KX_WorldInfo.h b/source/gameengine/Ketsji/KX_WorldInfo.h
index 5b35ca2ec54..a64ca5c191e 100644
--- a/source/gameengine/Ketsji/KX_WorldInfo.h
+++ b/source/gameengine/Ketsji/KX_WorldInfo.h
@@ -74,5 +74,4 @@ public:
#endif
};
-#endif //__KX_WORLDINFO_H__
-
+#endif /* __KX_WORLDINFO_H__ */
diff --git a/source/gameengine/Ketsji/KX_WorldIpoController.h b/source/gameengine/Ketsji/KX_WorldIpoController.h
index 409b1fec321..63983b3129b 100644
--- a/source/gameengine/Ketsji/KX_WorldIpoController.h
+++ b/source/gameengine/Ketsji/KX_WorldIpoController.h
@@ -72,15 +72,15 @@ public:
m_modified = true;
}
- void SetModifyMistStart(bool modify) {
+ void SetModifyMistStart(bool modify) {
m_modify_mist_start = modify;
}
- void SetModifyMistColor(bool modify) {
+ void SetModifyMistColor(bool modify) {
m_modify_mist_color = modify;
}
- void SetModifyMistDist(bool modify) {
+ void SetModifyMistDist(bool modify) {
m_modify_mist_dist = modify;
}
@@ -100,5 +100,4 @@ public:
#endif
};
-#endif // __KX_WORLDIPOCONTROLLER_H__
-
+#endif /* __KX_WORLDIPOCONTROLLER_H__ */
diff --git a/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h b/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h
index 92ba6100359..7581486c80a 100644
--- a/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h
+++ b/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h
@@ -36,7 +36,7 @@
#include "NG_NetworkDeviceInterface.h"
class NG_LoopBackNetworkDeviceInterface : public NG_NetworkDeviceInterface
-{
+{
std::deque<NG_NetworkMessage*> m_messages[2];
int m_currentQueue;
@@ -60,5 +60,4 @@ public:
virtual std::vector<NG_NetworkMessage*> RetrieveNetworkMessages();
};
-#endif //__NG_LOOPBACKNETWORKDEVICEINTERFACE_H__
-
+#endif /* __NG_LOOPBACKNETWORKDEVICEINTERFACE_H__ */
diff --git a/source/gameengine/Network/NG_NetworkDeviceInterface.h b/source/gameengine/Network/NG_NetworkDeviceInterface.h
index 8f903cc64fa..48edbdfc7fe 100644
--- a/source/gameengine/Network/NG_NetworkDeviceInterface.h
+++ b/source/gameengine/Network/NG_NetworkDeviceInterface.h
@@ -79,5 +79,4 @@ public:
#endif
};
-#endif //__NG_NETWORKDEVICEINTERFACE_H__
-
+#endif /* __NG_NETWORKDEVICEINTERFACE_H__ */
diff --git a/source/gameengine/Network/NG_NetworkMessage.h b/source/gameengine/Network/NG_NetworkMessage.h
index 25e7fd97596..5185849f8d7 100644
--- a/source/gameengine/Network/NG_NetworkMessage.h
+++ b/source/gameengine/Network/NG_NetworkMessage.h
@@ -135,5 +135,4 @@ public:
#endif
};
-#endif //__NG_NETWORKMESSAGE_H__
-
+#endif /* __NG_NETWORKMESSAGE_H__ */
diff --git a/source/gameengine/Network/NG_NetworkObject.h b/source/gameengine/Network/NG_NetworkObject.h
index b9858cd8d43..54459cad55d 100644
--- a/source/gameengine/Network/NG_NetworkObject.h
+++ b/source/gameengine/Network/NG_NetworkObject.h
@@ -52,5 +52,4 @@ public:
#endif
};
-#endif //__NG_NETWORKOBJECT_H__
-
+#endif /* __NG_NETWORKOBJECT_H__ */
diff --git a/source/gameengine/Network/NG_NetworkScene.h b/source/gameengine/Network/NG_NetworkScene.h
index 41ac8ead5e4..10dad210128 100644
--- a/source/gameengine/Network/NG_NetworkScene.h
+++ b/source/gameengine/Network/NG_NetworkScene.h
@@ -51,7 +51,7 @@ class NG_NetworkDeviceInterface;
class NG_NetworkScene
{
- class NG_NetworkDeviceInterface *m_networkdevice;
+ class NG_NetworkDeviceInterface *m_networkdevice;
CTR_Map<STR_HashedString, class NG_NetworkObject *> m_networkObjects;
// CTR_Maps used as a 'Bloom' filter
@@ -107,7 +107,7 @@ protected:
* Releases messages for the given message map.
* \param map Message map with messages.
*/
- void ClearMessageMap(TMessageMap& map);
+ void ClearMessageMap(TMessageMap& map);
#ifdef WITH_CXX_GUARDEDALLOC
@@ -115,5 +115,4 @@ protected:
#endif
};
-#endif //__NG_NETWORKSCENE_H__
-
+#endif /* __NG_NETWORKSCENE_H__ */
diff --git a/source/gameengine/Physics/Bullet/CMakeLists.txt b/source/gameengine/Physics/Bullet/CMakeLists.txt
index cdae3cc5526..43b1bfe7468 100644
--- a/source/gameengine/Physics/Bullet/CMakeLists.txt
+++ b/source/gameengine/Physics/Bullet/CMakeLists.txt
@@ -37,7 +37,6 @@ set(INC
../../../blender/blenkernel
../../../blender/blenlib
../../../blender/makesdna
- ../../../../extern/bullet2/src
../../../../intern/container
../../../../intern/guardedalloc
../../../../intern/moto/include
@@ -45,6 +44,7 @@ set(INC
)
set(INC_SYS
+ ../../../../extern/bullet2/src
${GLEW_INCLUDE_PATH}
${PYTHON_INCLUDE_DIRS}
)
diff --git a/source/gameengine/Physics/Bullet/CcdGraphicController.h b/source/gameengine/Physics/Bullet/CcdGraphicController.h
index 60ff475832b..72eb699ce5b 100644
--- a/source/gameengine/Physics/Bullet/CcdGraphicController.h
+++ b/source/gameengine/Physics/Bullet/CcdGraphicController.h
@@ -33,7 +33,7 @@ class CcdPhysicsEnvironment;
class btCollisionObject;
///CcdGraphicController is a graphic object that supports view frustrum culling and occlusion
-class CcdGraphicController : public PHY_IGraphicController
+class CcdGraphicController : public PHY_IGraphicController
{
public:
CcdGraphicController(CcdPhysicsEnvironment* phyEnv, PHY_IMotionState* motionState);
@@ -87,4 +87,4 @@ private:
#endif
};
-#endif //BULLET2_PHYSICSCONTROLLER_H
+#endif /* BULLET2_PHYSICSCONTROLLER_H */
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
index ed2b9cfcb0b..8d587cf39f6 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
@@ -46,9 +46,11 @@ subject to the following restrictions:
#include "DNA_meshdata_types.h"
extern "C"{
-#include "BKE_cdderivedmesh.h"
+ #include "BLI_utildefines.h"
+ #include "BKE_cdderivedmesh.h"
}
+
class BP_Proxy;
///todo: fill all the empty CcdPhysicsController methods, hook them up to the btRigidBody class
@@ -215,8 +217,7 @@ bool CcdPhysicsController::CreateSoftbody()
btSoftBody* psb = 0;
btSoftBodyWorldInfo& worldInfo = m_cci.m_physicsEnv->getDynamicsWorld()->getWorldInfo();
- if (m_cci.m_collisionShape->getShapeType() == CONVEX_HULL_SHAPE_PROXYTYPE)
- {
+ if (m_cci.m_collisionShape->getShapeType() == CONVEX_HULL_SHAPE_PROXYTYPE) {
btConvexHullShape* convexHull = (btConvexHullShape* )m_cci.m_collisionShape;
{
int nvertices = convexHull->getNumPoints();
@@ -224,26 +225,25 @@ bool CcdPhysicsController::CreateSoftbody()
HullDesc hdsc(QF_TRIANGLES,nvertices,vertices);
HullResult hres;
- HullLibrary hlib;/*??*/
+ HullLibrary hlib; /*??*/
hdsc.mMaxVertices=nvertices;
hlib.CreateConvexHull(hdsc,hres);
- psb=new btSoftBody(&worldInfo,(int)hres.mNumOutputVertices,
- &hres.m_OutputVertices[0],0);
- for (int i=0;i<(int)hres.mNumFaces;++i)
- {
- const int idx[]={ hres.m_Indices[i*3+0],
- hres.m_Indices[i*3+1],
- hres.m_Indices[i*3+2]};
- if (idx[0]<idx[1]) psb->appendLink( idx[0],idx[1]);
- if (idx[1]<idx[2]) psb->appendLink( idx[1],idx[2]);
- if (idx[2]<idx[0]) psb->appendLink( idx[2],idx[0]);
- psb->appendFace(idx[0],idx[1],idx[2]);
+ psb = new btSoftBody(&worldInfo, (int)hres.mNumOutputVertices,
+ &hres.m_OutputVertices[0], 0);
+ for (int i = 0; i < (int)hres.mNumFaces; ++i) {
+ const unsigned int idx[3] = {hres.m_Indices[i * 3 + 0],
+ hres.m_Indices[i * 3 + 1],
+ hres.m_Indices[i * 3 + 2]};
+ if (idx[0] < idx[1]) psb->appendLink(idx[0], idx[1]);
+ if (idx[1] < idx[2]) psb->appendLink(idx[1], idx[2]);
+ if (idx[2] < idx[0]) psb->appendLink(idx[2], idx[0]);
+ psb->appendFace(idx[0], idx[1], idx[2]);
}
hlib.ReleaseResult(hres);
}
- } else
- {
+ }
+ else {
int numtris = 0;
if (m_cci.m_collisionShape->getShapeType() ==SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE)
{
@@ -787,7 +787,7 @@ void CcdPhysicsController::PostProcessReplica(class PHY_IMotionState* motionsta
if (oldbody->getActivationState() == DISABLE_DEACTIVATION)
body->setActivationState(DISABLE_DEACTIVATION);
}
- }
+ }
// sensor object are added when needed
if (!m_cci.m_bSensor)
m_cci.m_physicsEnv->addCcdPhysicsController(this);
@@ -806,7 +806,7 @@ void CcdPhysicsController::PostProcessReplica(class PHY_IMotionState* motionsta
m_sumoObj = new SM_Object(
orgsumoobject->getShapeHandle(),
- orgsumoobject->getMaterialProps(),
+ orgsumoobject->getMaterialProps(),
orgsumoobject->getShapeProps(),
dynaparent);
@@ -895,18 +895,22 @@ void CcdPhysicsController::RelativeTranslate(float dlocX,float dlocY,float dloc
return;
}
- // btRigidBody* body = GetRigidBody(); // not used anymore
-
btVector3 dloc(dlocX,dlocY,dlocZ);
btTransform xform = m_object->getWorldTransform();
if (local)
- {
dloc = xform.getBasis()*dloc;
+
+ if (m_characterController)
+ {
+ m_characterController->setWalkDirection(dloc/GetPhysicsEnvironment()->getNumTimeSubSteps());
}
+ else
+ {
- xform.setOrigin(xform.getOrigin() + dloc);
- SetCenterOfMassTransform(xform);
+ xform.setOrigin(xform.getOrigin() + dloc);
+ SetCenterOfMassTransform(xform);
+ }
}
}
@@ -1142,7 +1146,7 @@ void CcdPhysicsController::ApplyForce(float forceX,float forceY,float forceZ,bo
btTransform xform = m_object->getWorldTransform();
if (local)
- {
+ {
force = xform.getBasis()*force;
}
btRigidBody* body = GetRigidBody();
@@ -1498,9 +1502,15 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
MFace *mface = dm->getTessFaceArray(dm);
numpolys = dm->getNumTessFaces(dm);
numverts = dm->getNumVerts(dm);
- int* index = (int*)dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
MTFace *tface = (MTFace *)dm->getTessFaceDataArray(dm, CD_MTFACE);
+ /* double lookup */
+ const int *index_mf_to_mpoly = (const int *)dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ const int *index_mp_to_orig = (const int *)dm->getPolyDataArray(dm, CD_ORIGINDEX);
+ if ((index_mf_to_mpoly && index_mp_to_orig) == false) {
+ index_mf_to_mpoly = index_mp_to_orig = NULL;
+ }
+
m_shapeType = (polytope) ? PHY_SHAPE_POLYTOPE : PHY_SHAPE_MESH;
/* Convert blender geometry into bullet mesh, need these vars for mapping */
@@ -1513,15 +1523,16 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
for (int p2=0; p2<numpolys; p2++)
{
MFace* mf = &mface[p2];
- RAS_Polygon* poly = meshobj->GetPolygon((index)? index[p2]: p2);
+ const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2;
+ RAS_Polygon* poly = meshobj->GetPolygon(origi);
// only add polygons that have the collision flag set
if (poly->IsCollider())
{
- if (vert_tag_array[mf->v1]==false) {vert_tag_array[mf->v1]= true;tot_bt_verts++;}
- if (vert_tag_array[mf->v2]==false) {vert_tag_array[mf->v2]= true;tot_bt_verts++;}
- if (vert_tag_array[mf->v3]==false) {vert_tag_array[mf->v3]= true;tot_bt_verts++;}
- if (mf->v4 && vert_tag_array[mf->v4]==false) {vert_tag_array[mf->v4]= true;tot_bt_verts++;}
+ if (vert_tag_array[mf->v1] == false) {vert_tag_array[mf->v1] = true; tot_bt_verts++;}
+ if (vert_tag_array[mf->v2] == false) {vert_tag_array[mf->v2] = true; tot_bt_verts++;}
+ if (vert_tag_array[mf->v3] == false) {vert_tag_array[mf->v3] = true; tot_bt_verts++;}
+ if (mf->v4 && vert_tag_array[mf->v4] == false) {vert_tag_array[mf->v4] = true; tot_bt_verts++;}
}
}
@@ -1532,7 +1543,8 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
for (int p2=0; p2<numpolys; p2++)
{
MFace* mf = &mface[p2];
- RAS_Polygon* poly= meshobj->GetPolygon((index)? index[p2]: p2);
+ const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2;
+ RAS_Polygon* poly= meshobj->GetPolygon(origi);
// only add polygons that have the collisionflag set
if (poly->IsCollider())
@@ -1540,7 +1552,7 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
if (vert_tag_array[mf->v1]==true)
{
const float* vtx = mvert[mf->v1].co;
- vert_tag_array[mf->v1]= false;
+ vert_tag_array[mf->v1] = false;
*bt++ = vtx[0];
*bt++ = vtx[1];
*bt++ = vtx[2];
@@ -1548,7 +1560,7 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
if (vert_tag_array[mf->v2]==true)
{
const float* vtx = mvert[mf->v2].co;
- vert_tag_array[mf->v2]= false;
+ vert_tag_array[mf->v2] = false;
*bt++ = vtx[0];
*bt++ = vtx[1];
*bt++ = vtx[2];
@@ -1556,7 +1568,7 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
if (vert_tag_array[mf->v3]==true)
{
const float* vtx = mvert[mf->v3].co;
- vert_tag_array[mf->v3]= false;
+ vert_tag_array[mf->v3] = false;
*bt++ = vtx[0];
*bt++ = vtx[1];
*bt++ = vtx[2];
@@ -1564,7 +1576,7 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
if (mf->v4 && vert_tag_array[mf->v4]==true)
{
const float* vtx = mvert[mf->v4].co;
- vert_tag_array[mf->v4]= false;
+ vert_tag_array[mf->v4] = false;
*bt++ = vtx[0];
*bt++ = vtx[1];
*bt++ = vtx[2];
@@ -1580,19 +1592,20 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
for (int p2=0; p2<numpolys; p2++)
{
MFace* mf = &mface[p2];
- RAS_Polygon* poly= meshobj->GetPolygon((index)? index[p2]: p2);
+ const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2;
+ RAS_Polygon* poly= meshobj->GetPolygon(origi);
// only add polygons that have the collision flag set
if (poly->IsCollider())
{
if (vert_tag_array[mf->v1]==false)
- {vert_tag_array[mf->v1]= true;vert_remap_array[mf->v1]= tot_bt_verts;tot_bt_verts++;}
+ {vert_tag_array[mf->v1] = true;vert_remap_array[mf->v1] = tot_bt_verts;tot_bt_verts++;}
if (vert_tag_array[mf->v2]==false)
- {vert_tag_array[mf->v2]= true;vert_remap_array[mf->v2]= tot_bt_verts;tot_bt_verts++;}
+ {vert_tag_array[mf->v2] = true;vert_remap_array[mf->v2] = tot_bt_verts;tot_bt_verts++;}
if (vert_tag_array[mf->v3]==false)
- {vert_tag_array[mf->v3]= true;vert_remap_array[mf->v3]= tot_bt_verts;tot_bt_verts++;}
+ {vert_tag_array[mf->v3] = true;vert_remap_array[mf->v3] = tot_bt_verts;tot_bt_verts++;}
if (mf->v4 && vert_tag_array[mf->v4]==false)
- {vert_tag_array[mf->v4]= true;vert_remap_array[mf->v4]= tot_bt_verts;tot_bt_verts++;}
+ {vert_tag_array[mf->v4] = true;vert_remap_array[mf->v4] = tot_bt_verts;tot_bt_verts++;}
tot_bt_tris += (mf->v4 ? 2:1); /* a quad or a tri */
}
}
@@ -1617,7 +1630,8 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
{
MFace* mf = &mface[p2];
MTFace* tf = (tface) ? &tface[p2] : NULL;
- RAS_Polygon* poly= meshobj->GetPolygon((index)? index[p2]: p2);
+ const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2;
+ RAS_Polygon* poly= meshobj->GetPolygon(origi);
// only add polygons that have the collisionflag set
if (poly->IsCollider())
@@ -1627,9 +1641,9 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
MVert *v3= &mvert[mf->v3];
// the face indices
- tri_pt[0]= vert_remap_array[mf->v1];
- tri_pt[1]= vert_remap_array[mf->v2];
- tri_pt[2]= vert_remap_array[mf->v3];
+ tri_pt[0] = vert_remap_array[mf->v1];
+ tri_pt[1] = vert_remap_array[mf->v2];
+ tri_pt[2] = vert_remap_array[mf->v3];
tri_pt= tri_pt+3;
if (tf)
{
@@ -1643,25 +1657,25 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
}
// m_polygonIndexArray
- *poly_index_pt= (index)? index[p2]: p2;
+ *poly_index_pt = origi;
poly_index_pt++;
// the vertex location
if (vert_tag_array[mf->v1]==true) { /* *** v1 *** */
- vert_tag_array[mf->v1]= false;
+ vert_tag_array[mf->v1] = false;
*bt++ = v1->co[0];
*bt++ = v1->co[1];
*bt++ = v1->co[2];
}
if (vert_tag_array[mf->v2]==true) { /* *** v2 *** */
- vert_tag_array[mf->v2]= false;
+ vert_tag_array[mf->v2] = false;
*bt++ = v2->co[0];
*bt++ = v2->co[1];
*bt++ = v2->co[2];
}
if (vert_tag_array[mf->v3]==true) { /* *** v3 *** */
- vert_tag_array[mf->v3]= false;
- *bt++ = v3->co[0];
+ vert_tag_array[mf->v3] = false;
+ *bt++ = v3->co[0];
*bt++ = v3->co[1];
*bt++ = v3->co[2];
}
@@ -1670,9 +1684,9 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
{
MVert *v4= &mvert[mf->v4];
- tri_pt[0]= vert_remap_array[mf->v1];
- tri_pt[1]= vert_remap_array[mf->v3];
- tri_pt[2]= vert_remap_array[mf->v4];
+ tri_pt[0] = vert_remap_array[mf->v1];
+ tri_pt[1] = vert_remap_array[mf->v3];
+ tri_pt[2] = vert_remap_array[mf->v4];
tri_pt= tri_pt+3;
if (tf)
{
@@ -1686,14 +1700,14 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, DerivedMesh* dm,
}
// m_polygonIndexArray
- *poly_index_pt= (index)? index[p2]: p2;
+ *poly_index_pt = origi;
poly_index_pt++;
// the vertex location
- if (vert_tag_array[mf->v4]==true) { /* *** v4 *** */
- vert_tag_array[mf->v4]= false;
+ if (vert_tag_array[mf->v4] == true) { /* *** v4 *** */
+ vert_tag_array[mf->v4] = false;
*bt++ = v4->co[0];
- *bt++ = v4->co[1];
+ *bt++ = v4->co[1];
*bt++ = v4->co[2];
}
}
@@ -1798,7 +1812,13 @@ bool CcdShapeConstructionInfo::UpdateMesh(class KX_GameObject* gameobj, class RA
MFace *mface = dm->getTessFaceArray(dm);
numpolys = dm->getNumTessFaces(dm);
numverts = dm->getNumVerts(dm);
- int* index = (int*)dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+
+ /* double lookup */
+ const int *index_mf_to_mpoly = (const int *)dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
+ const int *index_mp_to_orig = (const int *)dm->getPolyDataArray(dm, CD_ORIGINDEX);
+ if ((index_mf_to_mpoly && index_mp_to_orig) == false) {
+ index_mf_to_mpoly = index_mp_to_orig = NULL;
+ }
MFace *mf;
MVert *mv;
@@ -1830,8 +1850,8 @@ bool CcdShapeConstructionInfo::UpdateMesh(class KX_GameObject* gameobj, class RA
if (vert_tag_array[v_orig]==false)
{
- vert_tag_array[v_orig]= true;
- vert_remap_array[v_orig]= tot_bt_verts;
+ vert_tag_array[v_orig] = true;
+ vert_remap_array[v_orig] = tot_bt_verts;
tot_bt_verts++;
}
}
@@ -1854,7 +1874,7 @@ bool CcdShapeConstructionInfo::UpdateMesh(class KX_GameObject* gameobj, class RA
{
if (tf->mode & TF_DYNAMIC)
{
- int origi = (index)? index[i]: i;
+ int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, i) : i;
if (mf->v4) {
fv_pt= quad_verts;
@@ -1878,7 +1898,7 @@ bool CcdShapeConstructionInfo::UpdateMesh(class KX_GameObject* gameobj, class RA
*bt++ = mv->co[1];
*bt++ = mv->co[2];
- vert_tag_array[v_orig]= false;
+ vert_tag_array[v_orig] = false;
}
*tri_pt++ = vert_remap_array[v_orig];
uv_pt->uv[0] = tf->uv[*fv_pt][0];
@@ -1913,7 +1933,7 @@ bool CcdShapeConstructionInfo::UpdateMesh(class KX_GameObject* gameobj, class RA
}
for (mf= mface, i=0; i < numpolys; mf++, i++) {
- int origi = (index)? index[i]: i;
+ int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, i) : i;
if (mf->v4) {
fv_pt= quad_verts;
@@ -1939,7 +1959,7 @@ bool CcdShapeConstructionInfo::UpdateMesh(class KX_GameObject* gameobj, class RA
/* transverts are only used for deformed RAS_Meshes, the RAS_TexVert data
* is too hard to get at, see below for details */
- float (*transverts)[3]= NULL;
+ float (*transverts)[3] = NULL;
int transverts_tot= 0; /* with deformed meshes - should always be greater then the max orginal index, or we get crashes */
if (deformer) {
@@ -1969,8 +1989,8 @@ bool CcdShapeConstructionInfo::UpdateMesh(class KX_GameObject* gameobj, class RA
v_orig= poly->GetVertex(i)->getOrigIndex();
if (vert_tag_array[v_orig]==false)
{
- vert_tag_array[v_orig]= true;
- vert_remap_array[v_orig]= tot_bt_verts;
+ vert_tag_array[v_orig] = true;
+ vert_remap_array[v_orig] = tot_bt_verts;
tot_bt_verts++;
}
}
@@ -2023,14 +2043,14 @@ bool CcdShapeConstructionInfo::UpdateMesh(class KX_GameObject* gameobj, class RA
*bt++ = xyz[2];
}
- vert_tag_array[v_orig]= false;
+ vert_tag_array[v_orig] = false;
}
*tri_pt++ = vert_remap_array[v_orig];
}
}
- m_polygonIndexArray[p]= p; /* dumb counting */
+ m_polygonIndexArray[p] = p; /* dumb counting */
}
}
@@ -2089,7 +2109,7 @@ bool CcdShapeConstructionInfo::SetProxy(CcdShapeConstructionInfo* shapeInfo)
btCollisionShape* CcdShapeConstructionInfo::CreateBulletShape(btScalar margin, bool useGimpact, bool useBvh)
{
btCollisionShape* collisionShape = 0;
- btCompoundShape* compoundShape = 0;
+ btCompoundShape* compoundShape = 0;
if (m_shapeType == PHY_SHAPE_PROXY && m_shapeProxy != NULL)
return m_shapeProxy->CreateBulletShape(margin, useGimpact, useBvh);
@@ -2138,7 +2158,7 @@ btCollisionShape* CcdShapeConstructionInfo::CreateBulletShape(btScalar margin, b
// One possible optimization is to use directly the btBvhTriangleMeshShape when the scale is 1,1,1
// and btScaledBvhTriangleMeshShape otherwise.
if (useGimpact)
- {
+ {
btTriangleIndexVertexArray* indexVertexArrays = new btTriangleIndexVertexArray(
m_polygonIndexArray.size(),
&m_triFaceArray[0],
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.h b/source/gameengine/Physics/Bullet/CcdPhysicsController.h
index 94dc796df23..6df5c85f5c0 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsController.h
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsController.h
@@ -171,7 +171,7 @@ public:
btVector3 m_halfExtend;
btTransform m_childTrans;
btVector3 m_childScale;
- void* m_userData;
+ void* m_userData;
btAlignedObjectArray<btScalar> m_vertexArray; // Contains both vertex array for polytope shape and
// triangle array for concave mesh shape. Each vertex is 3 consecutive values
// In this case a triangle is made of 3 consecutive points
@@ -397,7 +397,7 @@ class btCollisionObject;
class btSoftBody;
///CcdPhysicsController is a physics object that supports continuous collision detection and time of impact based physics resolution.
-class CcdPhysicsController : public PHY_IPhysicsController
+class CcdPhysicsController : public PHY_IPhysicsController
{
protected:
btCollisionObject* m_object;
@@ -665,4 +665,4 @@ class DefaultMotionState : public PHY_IMotionState
};
-#endif //__CCDPHYSICSCONTROLLER_H__
+#endif /* __CCDPHYSICSCONTROLLER_H__ */
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
index 5d28bf47401..486411d7e35 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
@@ -37,6 +37,7 @@ subject to the following restrictions:
#include "PHY_IMotionState.h"
+#include "PHY_ICharacter.h"
#include "KX_GameObject.h"
#include "RAS_MeshObject.h"
#include "RAS_Polygon.h"
@@ -57,7 +58,6 @@ btRaycastVehicle::btVehicleTuning gTuning;
#include "LinearMath/btAabbUtil2.h"
#include "MT_Matrix4x4.h"
#include "MT_Vector3.h"
-#include "GL/glew.h"
#ifdef WIN32
void DrawRasterizerLine(const float* from,const float* to,int color);
@@ -267,6 +267,36 @@ public:
};
#endif //NEW_BULLET_VEHICLE_SUPPORT
+class CharacterWrapper : public PHY_ICharacter
+{
+private:
+ btKinematicCharacterController* m_controller;
+
+public:
+ CharacterWrapper(btKinematicCharacterController* cont)
+ : m_controller(cont)
+ {}
+
+ virtual void Jump()
+ {
+ m_controller->jump();
+ }
+
+ virtual bool OnGround()
+ {
+ return m_controller->onGround();
+ }
+
+ virtual float GetGravity()
+ {
+ return m_controller->getGravity();
+ }
+ virtual void SetGravity(float gravity)
+ {
+ m_controller->setGravity(gravity);
+ }
+};
+
class CcdOverlapFilterCallBack : public btOverlapFilterCallback
{
private:
@@ -303,13 +333,13 @@ static void DrawAabb(btIDebugDraw* debugDrawer,const btVector3& from,const btVec
{
for (j=0;j<3;j++)
{
- pa = btVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1],
+ pa = btVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1],
edgecoord[2]*halfExtents[2]);
pa+=center;
int othercoord = j%3;
edgecoord[othercoord]*=-1.f;
- pb = btVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1],
+ pb = btVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1],
edgecoord[2]*halfExtents[2]);
pb+=center;
@@ -484,9 +514,8 @@ void CcdPhysicsEnvironment::updateCcdPhysicsController(CcdPhysicsController* ctr
body->getCollisionShape()->calculateLocalInertia(newMass, inertia);
body->setMassProps(newMass, inertia);
m_dynamicsWorld->addRigidBody(body, newCollisionGroup, newCollisionMask);
- }
- else
- {
+ }
+ else {
m_dynamicsWorld->addCollisionObject(obj, newCollisionGroup, newCollisionMask);
}
}
@@ -605,7 +634,7 @@ bool CcdPhysicsEnvironment::proceedDeltaTime(double curTime,float timeStep,float
float subStep = timeStep / float(m_numTimeSubSteps);
i = m_dynamicsWorld->stepSimulation(interval,25,subStep);//perform always a full simulation step
-//uncomment next line to see where Bullet spend its time (printf in console)
+//uncomment next line to see where Bullet spend its time (printf in console)
//CProfileManager::dumpAll();
processFhSprings(curTime,i*subStep);
@@ -1080,11 +1109,11 @@ static bool GetHitTriangle(btCollisionShape* shape, CcdShapeConstructionInfo* sh
const btVector3& meshScaling = shape->getLocalScaling();
for (int j=2;j>=0;j--)
{
- int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j];
+ int graphicsindex = (indicestype == PHY_SHORT) ? ((unsigned short *)gfxbase)[j] : gfxbase[j];
btScalar* graphicsbase = (btScalar*)(vertexbase+graphicsindex*stride);
- triangle[j] = btVector3(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ());
+ triangle[j] = btVector3(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ());
}
meshInterface->unLockReadOnlyVertexBase(0);
return true;
@@ -1248,7 +1277,7 @@ PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallbac
result.m_hitNormal[1] = rayCallback.m_hitNormalWorld.getY();
result.m_hitNormal[2] = rayCallback.m_hitNormalWorld.getZ();
filterCallback.reportHit(&result);
- }
+ }
return result.m_controller;
@@ -1310,22 +1339,19 @@ struct OcclusionBuffer
m[14] = btScalar(m1[ 2]*m2[12]+m1[ 6]*m2[13]+m1[10]*m2[14]+m1[14]*m2[15]);
m[15] = btScalar(m1[ 3]*m2[12]+m1[ 7]*m2[13]+m1[11]*m2[14]+m1[15]*m2[15]);
}
- void setup(int size)
+ void setup(int size, const int *view, double modelview[16], double projection[16])
{
m_initialized=false;
m_occlusion=false;
// compute the size of the buffer
- GLint v[4];
- GLdouble m[16],p[16];
int maxsize;
double ratio;
- glGetIntegerv(GL_VIEWPORT,v);
- maxsize = (v[2] > v[3]) ? v[2] : v[3];
+ maxsize = (view[2] > view[3]) ? view[2] : view[3];
assert(maxsize > 0);
ratio = 1.0/(2*maxsize);
// ensure even number
- m_sizes[0] = 2*((int)(size*v[2]*ratio+0.5));
- m_sizes[1] = 2*((int)(size*v[3]*ratio+0.5));
+ m_sizes[0] = 2*((int)(size*view[2]*ratio+0.5));
+ m_sizes[1] = 2*((int)(size*view[3]*ratio+0.5));
m_scales[0]=btScalar(m_sizes[0]/2);
m_scales[1]=btScalar(m_sizes[1]/2);
m_offsets[0]=m_scales[0]+0.5f;
@@ -1333,10 +1359,8 @@ struct OcclusionBuffer
// prepare matrix
// at this time of the rendering, the modelview matrix is the
// world to camera transformation and the projection matrix is
- // camera to clip transformation. combine both so that
- glGetDoublev(GL_MODELVIEW_MATRIX,m);
- glGetDoublev(GL_PROJECTION_MATRIX,p);
- CMmat4mul(m_wtc,p,m);
+ // camera to clip transformation. combine both so that
+ CMmat4mul(m_wtc, projection, modelview);
}
void initialize()
{
@@ -1391,7 +1415,7 @@ struct OcclusionBuffer
static bool project(btVector4* p,int n)
{
for (int i=0;i<n;++i)
- {
+ {
p[i][2]=1/p[i][3];
p[i][0]*=p[i][2];
p[i][1]*=p[i][2];
@@ -1524,8 +1548,8 @@ struct OcclusionBuffer
return(true);
}
}
- } else if (width == 1)
- {
+ }
+ else if (width == 1) {
// Degenerated in at least 2 vertical lines
// The algorithm below doesn't work when face has a single pixel width
// We cannot use general formulas because the plane is degenerated.
@@ -1536,16 +1560,16 @@ struct OcclusionBuffer
if (y[0] > y[1]) { ytmp=y[1];y[1]=y[0];y[0]=ytmp;ztmp=z[1];z[1]=z[0];z[0]=ztmp; }
if (y[0] > y[2]) { ytmp=y[2];y[2]=y[0];y[0]=ytmp;ztmp=z[2];z[2]=z[0];z[0]=ztmp; }
if (y[1] > y[2]) { ytmp=y[2];y[2]=y[1];y[1]=ytmp;ztmp=z[2];z[2]=z[1];z[1]=ztmp; }
- int dy[]={ y[0]-y[1],
- y[1]-y[2],
- y[2]-y[0]};
+ int dy[] = {y[0] - y[1],
+ y[1] - y[2],
+ y[2] - y[0]};
btScalar dzy[3];
- dzy[0] = (dy[0]) ? (z[0]-z[1])/dy[0] : btScalar(0.f);
- dzy[1] = (dy[1]) ? (z[1]-z[2])/dy[1] : btScalar(0.f);
- dzy[2] = (dy[2]) ? (z[2]-z[0])/dy[2] : btScalar(0.f);
- btScalar v[3] = { dzy[0]*(miy-y[0])+z[0],
- dzy[1]*(miy-y[1])+z[1],
- dzy[2]*(miy-y[2])+z[2] };
+ dzy[0] = (dy[0]) ? (z[0] - z[1]) / dy[0] : btScalar(0.f);
+ dzy[1] = (dy[1]) ? (z[1] - z[2]) / dy[1] : btScalar(0.f);
+ dzy[2] = (dy[2]) ? (z[2] - z[0]) / dy[2] : btScalar(0.f);
+ btScalar v[3] = {dzy[0] * (miy - y[0]) + z[0],
+ dzy[1] * (miy - y[1]) + z[1],
+ dzy[2] * (miy - y[2]) + z[2]};
dy[0] = y[1]-y[0];
dy[1] = y[0]-y[1];
dy[2] = y[2]-y[0];
@@ -1573,16 +1597,16 @@ struct OcclusionBuffer
if (x[0] > x[1]) { xtmp=x[1];x[1]=x[0];x[0]=xtmp;ztmp=z[1];z[1]=z[0];z[0]=ztmp; }
if (x[0] > x[2]) { xtmp=x[2];x[2]=x[0];x[0]=xtmp;ztmp=z[2];z[2]=z[0];z[0]=ztmp; }
if (x[1] > x[2]) { xtmp=x[2];x[2]=x[1];x[1]=xtmp;ztmp=z[2];z[2]=z[1];z[1]=ztmp; }
- int dx[]={ x[0]-x[1],
- x[1]-x[2],
- x[2]-x[0]};
+ int dx[] = {x[0] - x[1],
+ x[1] - x[2],
+ x[2] - x[0]};
btScalar dzx[3];
dzx[0] = (dx[0]) ? (z[0]-z[1])/dx[0] : btScalar(0.f);
dzx[1] = (dx[1]) ? (z[1]-z[2])/dx[1] : btScalar(0.f);
dzx[2] = (dx[2]) ? (z[2]-z[0])/dx[2] : btScalar(0.f);
- btScalar v[3] = { dzx[0]*(mix-x[0])+z[0],
- dzx[1]*(mix-x[1])+z[1],
- dzx[2]*(mix-x[2])+z[2] };
+ btScalar v[3] = {dzx[0] * (mix - x[0]) + z[0],
+ dzx[1] * (mix - x[1]) + z[1],
+ dzx[2] * (mix - x[2]) + z[2]};
dx[0] = x[1]-x[0];
dx[1] = x[0]-x[1];
dx[2] = x[2]-x[0];
@@ -1599,24 +1623,24 @@ struct OcclusionBuffer
v[0] += dzx[0]; v[1] += dzx[1]; v[2] += dzx[2];
dx[0]--; dx[1]++, dx[2]--;
}
- } else
- {
+ }
+ else {
// general case
- const int dx[]={ y[0]-y[1],
- y[1]-y[2],
- y[2]-y[0]};
- const int dy[]={ x[1]-x[0]-dx[0]*width,
- x[2]-x[1]-dx[1]*width,
- x[0]-x[2]-dx[2]*width};
- const int a=x[2]*y[0]+x[0]*y[1]-x[2]*y[1]-x[0]*y[2]+x[1]*y[2]-x[1]*y[0];
- const btScalar ia=1/(btScalar)a;
- const btScalar dzx=ia*(y[2]*(z[1]-z[0])+y[1]*(z[0]-z[2])+y[0]*(z[2]-z[1]));
- const btScalar dzy=ia*(x[2]*(z[0]-z[1])+x[0]*(z[1]-z[2])+x[1]*(z[2]-z[0]))-(dzx*width);
- int c[]={ miy*x[1]+mix*y[0]-x[1]*y[0]-mix*y[1]+x[0]*y[1]-miy*x[0],
- miy*x[2]+mix*y[1]-x[2]*y[1]-mix*y[2]+x[1]*y[2]-miy*x[1],
- miy*x[0]+mix*y[2]-x[0]*y[2]-mix*y[0]+x[2]*y[0]-miy*x[2]};
- btScalar v=ia*((z[2]*c[0])+(z[0]*c[1])+(z[1]*c[2]));
- btScalar* scan=&m_buffer[miy*m_sizes[0]];
+ const int dx[] = {y[0] - y[1],
+ y[1] - y[2],
+ y[2] - y[0]};
+ const int dy[] = {x[1] - x[0] - dx[0] * width,
+ x[2] - x[1] - dx[1] * width,
+ x[0] - x[2] - dx[2] * width};
+ const int a = x[2] * y[0] + x[0] * y[1] - x[2] * y[1] - x[0] * y[2] + x[1] * y[2] - x[1] * y[0];
+ const btScalar ia = 1 / (btScalar)a;
+ const btScalar dzx = ia*(y[2]*(z[1]-z[0])+y[1]*(z[0]-z[2])+y[0]*(z[2]-z[1]));
+ const btScalar dzy = ia*(x[2]*(z[0]-z[1])+x[0]*(z[1]-z[2])+x[1]*(z[2]-z[0]))-(dzx*width);
+ int c[] = {miy*x[1]+mix*y[0]-x[1]*y[0]-mix*y[1]+x[0]*y[1]-miy*x[0],
+ miy*x[2]+mix*y[1]-x[2]*y[1]-mix*y[2]+x[1]*y[2]-miy*x[1],
+ miy*x[0]+mix*y[2]-x[0]*y[2]-mix*y[0]+x[2]*y[0]-miy*x[2]};
+ btScalar v = ia*((z[2]*c[0])+(z[0]*c[1])+(z[1]*c[2]));
+ btScalar *scan = &m_buffer[miy*m_sizes[0]];
for (int iy=miy;iy<mxy;++iy)
{
for (int ix=mix;ix<mxx;++ix)
@@ -1674,7 +1698,7 @@ struct OcclusionBuffer
const float* c,
const float* d,
const float face)
- {
+ {
btVector4 p[4];
transformM(a,p[0]);
transformM(b,p[1]);
@@ -1703,18 +1727,18 @@ struct OcclusionBuffer
// the box is clipped, it's probably a large box, don't waste our time to check
if ((x[i][2]+x[i][3])<=0) return(true);
}
- static const int d[]={ 1,0,3,2,
- 4,5,6,7,
- 4,7,3,0,
- 6,5,1,2,
- 7,6,2,3,
- 5,4,0,1};
+ static const int d[] = {1,0,3,2,
+ 4,5,6,7,
+ 4,7,3,0,
+ 6,5,1,2,
+ 7,6,2,3,
+ 5,4,0,1};
for (unsigned int i=0;i<(sizeof(d)/sizeof(d[0]));)
{
- const btVector4 p[]={ x[d[i++]],
- x[d[i++]],
- x[d[i++]],
- x[d[i++]]};
+ const btVector4 p[] = {x[d[i++]],
+ x[d[i++]],
+ x[d[i++]],
+ x[d[i++]]};
if (clipDraw<4,QueryOCL>(p,1.f,0.f))
return(true);
}
@@ -1744,7 +1768,7 @@ struct DbvtCullingCallback : btDbvt::ICollide
Process(node);
}
void Process(const btDbvtNode* leaf)
- {
+ {
btBroadphaseProxy* proxy=(btBroadphaseProxy*)leaf->data;
// the client object is a graphic controller
CcdGraphicController* ctrl = static_cast<CcdGraphicController*>(proxy->m_clientObject);
@@ -1796,7 +1820,7 @@ struct DbvtCullingCallback : btDbvt::ICollide
};
static OcclusionBuffer gOcb;
-bool CcdPhysicsEnvironment::cullingTest(PHY_CullingCallback callback, void* userData, PHY__Vector4 *planes, int nplanes, int occlusionRes)
+bool CcdPhysicsEnvironment::cullingTest(PHY_CullingCallback callback, void* userData, PHY__Vector4 *planes, int nplanes, int occlusionRes, const int *viewport, double modelview[16], double projection[16])
{
if (!m_cullingTree)
return false;
@@ -1813,15 +1837,15 @@ bool CcdPhysicsEnvironment::cullingTest(PHY_CullingCallback callback, void* user
// if occlusionRes != 0 => occlusion culling
if (occlusionRes)
{
- gOcb.setup(occlusionRes);
+ gOcb.setup(occlusionRes, viewport, modelview, projection);
dispatcher.m_ocb = &gOcb;
// occlusion culling, the direction of the view is taken from the first plan which MUST be the near plane
btDbvt::collideOCL(m_cullingTree->m_sets[1].m_root,planes_n,planes_o,planes_n[0],nplanes,dispatcher);
- btDbvt::collideOCL(m_cullingTree->m_sets[0].m_root,planes_n,planes_o,planes_n[0],nplanes,dispatcher);
+ btDbvt::collideOCL(m_cullingTree->m_sets[0].m_root,planes_n,planes_o,planes_n[0],nplanes,dispatcher);
}
else {
btDbvt::collideKDOP(m_cullingTree->m_sets[1].m_root,planes_n,planes_o,nplanes,dispatcher);
- btDbvt::collideKDOP(m_cullingTree->m_sets[0].m_root,planes_n,planes_o,nplanes,dispatcher);
+ btDbvt::collideKDOP(m_cullingTree->m_sets[0].m_root,planes_n,planes_o,nplanes,dispatcher);
}
return true;
}
@@ -1973,8 +1997,8 @@ void CcdPhysicsEnvironment::setConstraintParam(int constraintId,int param,float
btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint;
int transMotorIndex = param-6;
btTranslationalLimitMotor* transMotor = genCons->getTranslationalLimitMotor();
- transMotor->m_targetVelocity[transMotorIndex]= value0;
- transMotor->m_maxMotorForce[transMotorIndex]=value1;
+ transMotor->m_targetVelocity[transMotorIndex] = value0;
+ transMotor->m_maxMotorForce[transMotorIndex] = value1;
transMotor->m_enableMotor[transMotorIndex] = (value1>0.f);
break;
}
@@ -2215,10 +2239,29 @@ bool CcdOverlapFilterCallBack::needBroadphaseCollision(btBroadphaseProxy* proxy0
{
btCollisionObject *colObj0, *colObj1;
CcdPhysicsController *sensorCtrl, *objCtrl;
+
+ KX_GameObject *kxObj0 = KX_GameObject::GetClientObject(
+ (KX_ClientObjectInfo*)
+ ((CcdPhysicsController*)
+ (((btCollisionObject*)proxy0->m_clientObject)->getUserPointer()))
+ ->getNewClientInfo());
+ KX_GameObject *kxObj1 = KX_GameObject::GetClientObject(
+ (KX_ClientObjectInfo*)
+ ((CcdPhysicsController*)
+ (((btCollisionObject*)proxy1->m_clientObject)->getUserPointer()))
+ ->getNewClientInfo());
+
+ // First check the filters. Note that this is called during scene
+ // conversion, so we can't assume the KX_GameObject instances exist. This
+ // may make some objects erroneously collide on the first frame, but the
+ // alternative is to have them erroneously miss.
bool collides;
- // first check the filters
collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
+ if (kxObj0 && kxObj1) {
+ collides = collides && kxObj0->CheckCollision(kxObj1);
+ collides = collides && kxObj1->CheckCollision(kxObj0);
+ }
if (!collides)
return false;
@@ -2273,6 +2316,15 @@ PHY_IVehicle* CcdPhysicsEnvironment::getVehicleConstraint(int constraintId)
#endif //NEW_BULLET_VEHICLE_SUPPORT
+PHY_ICharacter* CcdPhysicsEnvironment::getCharacterController(KX_GameObject *ob)
+{
+ CcdPhysicsController* controller = (CcdPhysicsController*)ob->GetPhysicsController()->GetUserData();
+ if (controller->GetCharacterController())
+ return new CharacterWrapper(controller->GetCharacterController());
+
+ return NULL;
+}
+
int currentController = 0;
int numController = 0;
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
index c499a1ef75c..18ce0550498 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
@@ -115,6 +115,11 @@ protected:
virtual void setLinearAirDamping(float damping);
virtual void setUseEpa(bool epa);
+ int getNumTimeSubSteps()
+ {
+ return m_numTimeSubSteps;
+ }
+
virtual void beginFrame();
virtual void endFrame() {}
/// Perform an integration step of duration 'timeStep'.
@@ -178,12 +183,14 @@ protected:
{
return 0;
}
-#endif //NEW_BULLET_VEHICLE_SUPPORT
+#endif /* NEW_BULLET_VEHICLE_SUPPORT */
+ // Character physics wrapper
+ virtual PHY_ICharacter* getCharacterController(class KX_GameObject* ob);
btTypedConstraint* getConstraintById(int constraintId);
virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
- virtual bool cullingTest(PHY_CullingCallback callback, void* userData, PHY__Vector4* planes, int nplanes, int occlusionRes);
+ virtual bool cullingTest(PHY_CullingCallback callback, void* userData, PHY__Vector4* planes, int nplanes, int occlusionRes, const int *viewport, double modelview[16], double projection[16]);
//Methods for gamelogic collision/physics callbacks
@@ -292,4 +299,4 @@ protected:
#endif
};
-#endif //__CCDPHYSICSENVIRONMENT_H__
+#endif /* __CCDPHYSICSENVIRONMENT_H__ */
diff --git a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
index 9c109168b18..233c4412d9e 100644
--- a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
+++ b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
@@ -72,8 +72,14 @@ public:
return 0;
}
+ // Character physics wrapper
+ virtual PHY_ICharacter* getCharacterController(class KX_GameObject* ob)
+ {
+ return 0;
+ }
+
virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
- virtual bool cullingTest(PHY_CullingCallback callback, void* userData, PHY__Vector4* planes, int nplanes, int occlusionRes) { return false; }
+ virtual bool cullingTest(PHY_CullingCallback callback, void* userData, PHY__Vector4* planes, int nplanes, int occlusionRes, const int *viewport, double modelview[16], double projection[16]) { return false; }
//gamelogic callbacks
@@ -102,5 +108,4 @@ public:
#endif
};
-#endif //__DUMMYPHYSICSENVIRONMENT_H__
-
+#endif /* __DUMMYPHYSICSENVIRONMENT_H__ */
diff --git a/source/gameengine/Physics/common/CMakeLists.txt b/source/gameengine/Physics/common/CMakeLists.txt
index ceb7a8ba548..400e475f8a2 100644
--- a/source/gameengine/Physics/common/CMakeLists.txt
+++ b/source/gameengine/Physics/common/CMakeLists.txt
@@ -41,6 +41,7 @@ set(SRC
PHY_IVehicle.cpp
PHY_DynamicTypes.h
+ PHY_ICharacter.h
PHY_IController.h
PHY_IGraphicController.h
PHY_IMotionState.h
diff --git a/source/gameengine/Physics/common/PHY_DynamicTypes.h b/source/gameengine/Physics/common/PHY_DynamicTypes.h
index 69bbc7745e0..0fe2533cf93 100644
--- a/source/gameengine/Physics/common/PHY_DynamicTypes.h
+++ b/source/gameengine/Physics/common/PHY_DynamicTypes.h
@@ -32,11 +32,11 @@ struct PHY__Vector2
operator const float* () const
{
return &m_vec[0];
- }
+ }
operator float* ()
{
return &m_vec[0];
- }
+ }
};
struct PHY__Vector3
@@ -46,11 +46,11 @@ struct PHY__Vector3
operator const float* () const
{
return &m_vec[0];
- }
+ }
operator float* ()
{
return &m_vec[0];
- }
+ }
};
struct PHY__Vector4
@@ -75,11 +75,11 @@ struct PHY__Vector4
operator const float* () const
{
return &m_vec[0];
- }
+ }
operator float* ()
{
return &m_vec[0];
- }
+ }
};
//typedef float PHY__Vector3[4];
@@ -151,4 +151,4 @@ typedef enum PHY_ShapeType {
typedef float PHY_Vector3[3];
-#endif //__PHY_DYNAMICTYPES_H__
+#endif /* __PHY_DYNAMICTYPES_H__ */
diff --git a/source/gameengine/Physics/common/PHY_ICharacter.h b/source/gameengine/Physics/common/PHY_ICharacter.h
new file mode 100644
index 00000000000..e2fc5e45125
--- /dev/null
+++ b/source/gameengine/Physics/common/PHY_ICharacter.h
@@ -0,0 +1,30 @@
+
+/** \file PHY_ICharacter.h
+ * \ingroup phys
+ */
+
+#ifndef __PHY_ICHARACTER_H__
+#define __PHY_ICHARACTER_H__
+
+//PHY_ICharacter provides a generic interface for "character" controllers
+
+#ifdef WITH_CXX_GUARDEDALLOC
+#include "MEM_guardedalloc.h"
+#endif
+
+class PHY_ICharacter
+{
+public:
+
+ virtual void Jump()= 0;
+ virtual bool OnGround()= 0;
+
+ virtual float GetGravity()= 0;
+ virtual void SetGravity(float gravity)= 0;
+
+#ifdef WITH_CXX_GUARDEDALLOC
+ MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_ICharacter")
+#endif
+};
+
+#endif //__PHY_ICHARACTER_H__
diff --git a/source/gameengine/Physics/common/PHY_IController.h b/source/gameengine/Physics/common/PHY_IController.h
index 239ac3366e1..003c4edf598 100644
--- a/source/gameengine/Physics/common/PHY_IController.h
+++ b/source/gameengine/Physics/common/PHY_IController.h
@@ -45,7 +45,7 @@ class PHY_IPhysicsEnvironment;
controlled by the physics engine. This includes the physics objects
and the graphics object for view frustrum and occlusion culling.
*/
-class PHY_IController
+class PHY_IController
{
public:
virtual ~PHY_IController();
@@ -60,5 +60,4 @@ class PHY_IController
#endif
};
-#endif //__PHY_ICONTROLLER_H__
-
+#endif /* __PHY_ICONTROLLER_H__ */
diff --git a/source/gameengine/Physics/common/PHY_IGraphicController.h b/source/gameengine/Physics/common/PHY_IGraphicController.h
index af337188818..cb13eda4f18 100644
--- a/source/gameengine/Physics/common/PHY_IGraphicController.h
+++ b/source/gameengine/Physics/common/PHY_IGraphicController.h
@@ -58,5 +58,4 @@ class PHY_IGraphicController : public PHY_IController
#endif
};
-#endif //__PHY_IGRAPHICCONTROLLER_H__
-
+#endif /* __PHY_IGRAPHICCONTROLLER_H__ */
diff --git a/source/gameengine/Physics/common/PHY_IMotionState.h b/source/gameengine/Physics/common/PHY_IMotionState.h
index 2eb2a9f39cf..ccf7cf74724 100644
--- a/source/gameengine/Physics/common/PHY_IMotionState.h
+++ b/source/gameengine/Physics/common/PHY_IMotionState.h
@@ -43,7 +43,7 @@
class PHY_IMotionState
{
- public:
+ public:
virtual ~PHY_IMotionState();
virtual void getWorldPosition(float& posX,float& posY,float& posZ)=0;
@@ -65,5 +65,4 @@ class PHY_IMotionState
#endif
};
-#endif //__PHY_IMOTIONSTATE_H__
-
+#endif /* __PHY_IMOTIONSTATE_H__ */
diff --git a/source/gameengine/Physics/common/PHY_IPhysicsController.h b/source/gameengine/Physics/common/PHY_IPhysicsController.h
index 7eea2a183a1..bc7671abe80 100644
--- a/source/gameengine/Physics/common/PHY_IPhysicsController.h
+++ b/source/gameengine/Physics/common/PHY_IPhysicsController.h
@@ -108,5 +108,4 @@ class PHY_IPhysicsController : public PHY_IController
#endif
};
-#endif //__PHY_IPHYSICSCONTROLLER_H__
-
+#endif /* __PHY_IPHYSICSCONTROLLER_H__ */
diff --git a/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h b/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
index 30d63e6695d..077d225903c 100644
--- a/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
+++ b/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
@@ -40,6 +40,7 @@
#endif
class PHY_IVehicle;
+class PHY_ICharacter;
class RAS_MeshObject;
class PHY_IPhysicsController;
@@ -48,7 +49,7 @@ class PHY_IPhysicsController;
*/
struct PHY_RayCastResult
{
- PHY_IPhysicsController* m_controller;
+ PHY_IPhysicsController* m_controller;
PHY__Vector3 m_hitPoint;
PHY__Vector3 m_hitNormal;
const RAS_MeshObject* m_meshObject; // !=NULL for mesh object (only for Bullet controllers)
@@ -156,12 +157,15 @@ class PHY_IPhysicsEnvironment
//complex constraint for vehicles
virtual PHY_IVehicle* getVehicleConstraint(int constraintId) =0;
+ // Character physics wrapper
+ virtual PHY_ICharacter* getCharacterController(class KX_GameObject* ob) =0;
+
virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ)=0;
//culling based on physical broad phase
// the plane number must be set as follow: near, far, left, right, top, botton
// the near plane must be the first one and must always be present, it is used to get the direction of the view
- virtual bool cullingTest(PHY_CullingCallback callback, void *userData, PHY__Vector4* planeNormals, int planeNumber, int occlusionRes) = 0;
+ virtual bool cullingTest(PHY_CullingCallback callback, void *userData, PHY__Vector4* planeNormals, int planeNumber, int occlusionRes, const int *viewport, double modelview[16], double projection[16]) = 0;
//Methods for gamelogic collision/physics callbacks
//todo:
@@ -185,5 +189,4 @@ class PHY_IPhysicsEnvironment
#endif
};
-#endif //__PHY_IPHYSICSENVIRONMENT_H__
-
+#endif /* __PHY_IPHYSICSENVIRONMENT_H__ */
diff --git a/source/gameengine/Physics/common/PHY_IVehicle.h b/source/gameengine/Physics/common/PHY_IVehicle.h
index 731e22d9f0f..ecf7a87c40f 100644
--- a/source/gameengine/Physics/common/PHY_IVehicle.h
+++ b/source/gameengine/Physics/common/PHY_IVehicle.h
@@ -66,4 +66,4 @@ public:
#endif
};
-#endif //__PHY_IVEHICLE_H__
+#endif /* __PHY_IVEHICLE_H__ */
diff --git a/source/gameengine/Physics/common/PHY_Pro.h b/source/gameengine/Physics/common/PHY_Pro.h
index b930177d3a8..7c5d9c9638e 100644
--- a/source/gameengine/Physics/common/PHY_Pro.h
+++ b/source/gameengine/Physics/common/PHY_Pro.h
@@ -62,5 +62,4 @@ struct PHY_MaterialProps {
bool m_fh_normal; // Should the object slide off slopes?
};
-#endif //__PHY_PRO_H__
-
+#endif /* __PHY_PRO_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp b/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp
index 06251cd2282..cf869e71945 100644
--- a/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp
+++ b/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp
@@ -110,7 +110,7 @@ void RAS_2DFilterManager::PrintShaderErrors(unsigned int shader, const char *tas
unsigned int RAS_2DFilterManager::CreateShaderProgram(const char* shadersource)
{
- GLuint program = 0;
+ GLuint program = 0;
GLuint fShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER);
GLint success;
@@ -153,8 +153,7 @@ unsigned int RAS_2DFilterManager::CreateShaderProgram(const char* shadersource)
unsigned int RAS_2DFilterManager::CreateShaderProgram(int filtermode)
{
- switch(filtermode)
- {
+ switch (filtermode) {
case RAS_2DFILTER_BLUR:
return CreateShaderProgram(BlurFragmentShader);
case RAS_2DFILTER_SHARPEN:
@@ -398,8 +397,7 @@ void RAS_2DFilterManager::RenderFilters(RAS_ICanvas* canvas)
if (num_filters <= 0)
return;
- GLuint viewport[4]={0};
- glGetIntegerv(GL_VIEWPORT,(GLint *)viewport);
+ const GLint *viewport = canvas->GetViewPort();
RAS_Rect rect = canvas->GetWindowArea();
int rect_width = rect.GetWidth()+1, rect_height = rect.GetHeight()+1;
@@ -469,7 +467,7 @@ void RAS_2DFilterManager::RenderFilters(RAS_ICanvas* canvas)
glEnable(GL_DEPTH_TEST);
glViewport(viewport[0],viewport[1],viewport[2],viewport[3]);
- EndShaderProgram();
+ EndShaderProgram();
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.cpp b/source/gameengine/Rasterizer/RAS_BucketManager.cpp
index 90587bb9739..f24e3397801 100644
--- a/source/gameengine/Rasterizer/RAS_BucketManager.cpp
+++ b/source/gameengine/Rasterizer/RAS_BucketManager.cpp
@@ -29,13 +29,11 @@
* \ingroup bgerast
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// don't show these anoying STL warnings
-#pragma warning (disable:4786)
+#ifdef _MSC_VER
+ /* don't show these anoying STL warnings */
+# pragma warning (disable:4786)
#endif
-#include "CTR_Map.h"
#include "RAS_MaterialBucket.h"
#include "STR_HashedString.h"
#include "RAS_MeshObject.h"
@@ -130,7 +128,7 @@ void RAS_BucketManager::OrderBuckets(const MT_Transform& cameratrans, BucketList
RAS_MaterialBucket* bucket = *bit;
RAS_MeshSlot* ms;
// remove the mesh slot form the list, it culls them automatically for next frame
- while((ms = bucket->GetNextActiveMeshSlot())) {
+ while ((ms = bucket->GetNextActiveMeshSlot())) {
slots[i++].set(ms, bucket, pnorm);
}
}
@@ -157,7 +155,7 @@ void RAS_BucketManager::RenderAlphaBuckets(
for (sit=slots.begin(); sit!=slots.end(); ++sit) {
rendertools->SetClientObject(rasty, sit->m_ms->m_clientObj);
- while(sit->m_bucket->ActivateMaterial(cameratrans, rasty, rendertools))
+ while (sit->m_bucket->ActivateMaterial(cameratrans, rasty, rendertools))
sit->m_bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *(sit->m_ms));
// make this mesh slot culled automatically for next frame
@@ -180,8 +178,7 @@ void RAS_BucketManager::RenderSolidBuckets(
RAS_MaterialBucket* bucket = *bit;
RAS_MeshSlot* ms;
// remove the mesh slot form the list, it culls them automatically for next frame
- while((ms = bucket->GetNextActiveMeshSlot()))
- {
+ while ((ms = bucket->GetNextActiveMeshSlot())) {
rendertools->SetClientObject(rasty, ms->m_clientObj);
while (bucket->ActivateMaterial(cameratrans, rasty, rendertools))
bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *ms);
@@ -220,7 +217,7 @@ void RAS_BucketManager::RenderSolidBuckets(
for (sit=slots.begin(); sit!=slots.end(); ++sit) {
rendertools->SetClientObject(rasty, sit->m_ms->m_clientObj);
- while(sit->m_bucket->ActivateMaterial(cameratrans, rasty, rendertools))
+ while (sit->m_bucket->ActivateMaterial(cameratrans, rasty, rendertools))
sit->m_bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *(sit->m_ms));
}
#endif
@@ -232,8 +229,8 @@ void RAS_BucketManager::Renderbuckets(
/* beginning each frame, clear (texture/material) caching information */
rasty->ClearCachingInfo();
- RenderSolidBuckets(cameratrans, rasty, rendertools);
- RenderAlphaBuckets(cameratrans, rasty, rendertools);
+ RenderSolidBuckets(cameratrans, rasty, rendertools);
+ RenderAlphaBuckets(cameratrans, rasty, rendertools);
rendertools->SetClientObject(rasty, NULL);
}
diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.h b/source/gameengine/Rasterizer/RAS_BucketManager.h
index 2650bc9f722..78125a7bbb3 100644
--- a/source/gameengine/Rasterizer/RAS_BucketManager.h
+++ b/source/gameengine/Rasterizer/RAS_BucketManager.h
@@ -34,7 +34,6 @@
#include "MT_Transform.h"
#include "RAS_MaterialBucket.h"
-#include "CTR_Map.h"
#include <vector>
@@ -90,5 +89,4 @@ private:
#endif
};
-#endif //__RAS_BUCKETMANAGER_H__
-
+#endif /* __RAS_BUCKETMANAGER_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_CameraData.h b/source/gameengine/Rasterizer/RAS_CameraData.h
index 4a70df6e505..7a6bb541a1a 100644
--- a/source/gameengine/Rasterizer/RAS_CameraData.h
+++ b/source/gameengine/Rasterizer/RAS_CameraData.h
@@ -71,5 +71,4 @@ struct RAS_CameraData
}
};
-#endif //__RAS_CAMERADATA_H__
-
+#endif /* __RAS_CAMERADATA_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_Deformer.h b/source/gameengine/Rasterizer/RAS_Deformer.h
index 51c4da3c49d..058f2304f3d 100644
--- a/source/gameengine/Rasterizer/RAS_Deformer.h
+++ b/source/gameengine/Rasterizer/RAS_Deformer.h
@@ -32,9 +32,9 @@
#ifndef __RAS_DEFORMER_H__
#define __RAS_DEFORMER_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
-#endif //WIN32
+#ifdef _MSC_VER
+# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
+#endif
#include <stdlib.h>
#include "CTR_Map.h"
@@ -91,7 +91,7 @@ public:
protected:
class RAS_MeshObject *m_pMesh;
- bool m_bDynamic;
+ bool m_bDynamic;
#ifdef WITH_CXX_GUARDEDALLOC
diff --git a/source/gameengine/Rasterizer/RAS_FramingManager.cpp b/source/gameengine/Rasterizer/RAS_FramingManager.cpp
index 1cd110f8cc6..53d9b64ab0e 100644
--- a/source/gameengine/Rasterizer/RAS_FramingManager.cpp
+++ b/source/gameengine/Rasterizer/RAS_FramingManager.cpp
@@ -43,7 +43,7 @@ ComputeDefaultFrustum(
const short sensor_fit,
const float design_aspect_ratio,
RAS_FrameFrustum & frustum
-) {
+) {
float halfSize;
float sizeX;
float sizeY;
@@ -202,7 +202,7 @@ ComputeViewport(
{
ComputeBestFitViewRect(
availableViewport,
- design_aspect_ratio,
+ design_aspect_ratio,
viewport
);
@@ -260,7 +260,7 @@ ComputeFrustum(
RAS_Rect vt;
ComputeBestFitViewRect(
availableViewport,
- design_aspect_ratio,
+ design_aspect_ratio,
vt
);
@@ -277,13 +277,13 @@ ComputeFrustum(
frustum.y2 *= y_scale;
break;
- }
+ }
case RAS_FrameSettings::e_frame_scale :
case RAS_FrameSettings::e_frame_bars:
default :
break;
}
-}
+}
void
RAS_FramingManager::
@@ -330,7 +330,7 @@ RAS_FramingManager::
RAS_Rect vt;
ComputeBestFitViewRect(
availableViewport,
- design_aspect_ratio,
+ design_aspect_ratio,
vt
);
@@ -347,7 +347,7 @@ RAS_FramingManager::
frustum.y2 *= y_scale;
break;
- }
+ }
case RAS_FrameSettings::e_frame_scale :
case RAS_FrameSettings::e_frame_bars:
default :
diff --git a/source/gameengine/Rasterizer/RAS_FramingManager.h b/source/gameengine/Rasterizer/RAS_FramingManager.h
index dd640bc6839..122f0ca46ec 100644
--- a/source/gameengine/Rasterizer/RAS_FramingManager.h
+++ b/source/gameengine/Rasterizer/RAS_FramingManager.h
@@ -109,7 +109,7 @@ public :
*/
const
- RAS_FrameType &
+ RAS_FrameType &
FrameType(
) const {
return m_frame_type;
@@ -143,13 +143,13 @@ public :
unsigned int
DesignAspectWidth(
) const {
- return m_design_aspect_width;
+ return m_design_aspect_width;
};
unsigned int
DesignAspectHeight(
) const {
- return m_design_aspect_height;
+ return m_design_aspect_height;
};
private :
@@ -262,7 +262,7 @@ public :
const short sensor_fit,
const float design_aspect_ratio,
RAS_FrameFrustum & frustum
- );
+ );
static
void
diff --git a/source/gameengine/Rasterizer/RAS_ICanvas.h b/source/gameengine/Rasterizer/RAS_ICanvas.h
index 713a06845ac..53195d79768 100644
--- a/source/gameengine/Rasterizer/RAS_ICanvas.h
+++ b/source/gameengine/Rasterizer/RAS_ICanvas.h
@@ -180,6 +180,13 @@ public:
int x2, int y2
) = 0;
+ /**
+ * Get the visible viewport
+ */
+ virtual
+ const int*
+ GetViewPort() = 0;
+
virtual
void
SetMouseState(
@@ -224,5 +231,4 @@ protected:
#endif
};
-#endif //__RAS_ICANVAS_H__
-
+#endif /* __RAS_ICANVAS_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
index 4af1753c2da..ddadd97b567 100644
--- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
+++ b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
@@ -254,12 +254,18 @@ bool RAS_IPolyMaterial::UsesLighting(RAS_IRasterizer *rasty) const
{
bool dolights = false;
- if (m_flag & RAS_BLENDERMAT)
- dolights = (m_flag &RAS_MULTILIGHT)!=0;
- else if (rasty->GetDrawingMode() < RAS_IRasterizer::KX_SOLID);
- else if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW);
- else
+ if (m_flag & RAS_BLENDERMAT) {
+ dolights = (m_flag & RAS_MULTILIGHT) != 0;
+ }
+ else if (rasty->GetDrawingMode() < RAS_IRasterizer::KX_SOLID) {
+ /* pass */
+ }
+ else if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW) {
+ /* pass */
+ }
+ else {
dolights = m_light;
+ }
return dolights;
}
diff --git a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h
index 169bc6e4ee6..9fffc8bebc9 100644
--- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h
+++ b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h
@@ -202,5 +202,4 @@ inline bool operator < ( const RAS_IPolyMaterial & lhs, const RAS_IPolyMaterial
return lhs.Less(rhs);
}
-#endif //__RAS_IPOLYGONMATERIAL_H__
-
+#endif /* __RAS_IPOLYGONMATERIAL_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_IRasterizer.h b/source/gameengine/Rasterizer/RAS_IRasterizer.h
index 7749c4af9d6..e6948025999 100644
--- a/source/gameengine/Rasterizer/RAS_IRasterizer.h
+++ b/source/gameengine/Rasterizer/RAS_IRasterizer.h
@@ -32,8 +32,8 @@
#ifndef __RAS_IRASTERIZER_H__
#define __RAS_IRASTERIZER_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786)
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
#endif
#include "STR_HashedString.h"
@@ -301,7 +301,7 @@ public:
virtual int GetDrawingMode()=0;
/**
* Sets face culling
- */
+ */
virtual void SetCullFace(bool enable)=0;
/**
* Sets wireframe mode.
@@ -423,6 +423,4 @@ public:
#endif
};
-#endif //__RAS_IRASTERIZER_H__
-
-
+#endif /* __RAS_IRASTERIZER_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_IRenderTools.h b/source/gameengine/Rasterizer/RAS_IRenderTools.h
index c02bc5e7a44..bccda634222 100644
--- a/source/gameengine/Rasterizer/RAS_IRenderTools.h
+++ b/source/gameengine/Rasterizer/RAS_IRenderTools.h
@@ -72,18 +72,18 @@ public:
{
};
- virtual
+ virtual
~RAS_IRenderTools(
) {};
virtual
- void
+ void
BeginFrame(
RAS_IRasterizer* rasty
)=0;
virtual
- void
+ void
EndFrame(
RAS_IRasterizer* rasty
)=0;
@@ -94,7 +94,7 @@ public:
// so must be renamed to 'applyTransform' or something
virtual
- void
+ void
applyTransform(
class RAS_IRasterizer* rasty,
double* oglmatrix,
@@ -112,7 +112,7 @@ public:
* \param aspect A scaling factor to compensate for the size.
*/
virtual
- void
+ void
RenderText3D(int fontid,
const char* text,
int size,
@@ -133,7 +133,7 @@ public:
* \param height Height of the canvas to draw to.
*/
virtual
- void
+ void
RenderText2D(
RAS_TEXT_RENDER_MODE mode,
const char* text,
@@ -145,7 +145,7 @@ public:
// 3d text, mapped on polygon
virtual
- void
+ void
RenderText(
int mode,
RAS_IPolyMaterial* polymat,
@@ -156,8 +156,8 @@ public:
int glattrib
)=0;
- virtual
- void
+ virtual
+ void
ProcessLighting(
RAS_IRasterizer *rasty,
bool uselights,
@@ -165,35 +165,35 @@ public:
)=0;
virtual
- void
+ void
SetClientObject(
RAS_IRasterizer* rasty,
void* obj
);
- void
+ void
SetAuxilaryClientInfo(
void* inf
);
virtual
- void
+ void
PushMatrix(
)=0;
virtual
- void
+ void
PopMatrix(
)=0;
virtual
- void
+ void
AddLight(
struct RAS_LightObject* lightobject
);
virtual
- void
+ void
RemoveLight(
struct RAS_LightObject* lightobject
);
@@ -208,7 +208,4 @@ public:
#endif
};
-#endif //__RAS_IRENDERTOOLS_H__
-
-
-
+#endif /* __RAS_IRENDERTOOLS_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_LightObject.h b/source/gameengine/Rasterizer/RAS_LightObject.h
index ddf360683cd..79818def5f0 100644
--- a/source/gameengine/Rasterizer/RAS_LightObject.h
+++ b/source/gameengine/Rasterizer/RAS_LightObject.h
@@ -64,5 +64,4 @@ struct RAS_LightObject
bool m_nospecular;
};
-#endif //__RAS_LIGHTOBJECT_H__
-
+#endif /* __RAS_LIGHTOBJECT_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp b/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp
index a18adfd8986..9fb47117f1d 100644
--- a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp
+++ b/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp
@@ -32,8 +32,8 @@
#include "RAS_MaterialBucket.h"
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786)
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
#endif
#ifdef WIN32
@@ -73,7 +73,7 @@ RAS_MeshSlot::~RAS_MeshSlot()
#ifdef USE_SPLIT
Split(true);
- while(m_joinedSlots.size())
+ while (m_joinedSlots.size())
m_joinedSlots.front()->Split(true);
#endif
@@ -147,7 +147,7 @@ void RAS_MeshSlot::begin(RAS_MeshSlot::iterator& it)
int startvertex, endvertex;
int startindex, endindex;
- it.array = (m_displayArrays.size() > 0)? m_displayArrays[m_startarray]: NULL;
+ it.array = m_displayArrays.empty() ? NULL : m_displayArrays[m_startarray];
if (it.array == NULL || it.array->m_index.size() == 0 || it.array->m_vertex.size() == 0) {
it.array = NULL;
@@ -368,7 +368,7 @@ bool RAS_MeshSlot::Join(RAS_MeshSlot *target, MT_Scalar distance)
size_t i;
// verify if we can join
- if (m_joinSlot || m_joinedSlots.size() || target->m_joinSlot)
+ if (m_joinSlot || (m_joinedSlots.empty() == false) || target->m_joinSlot)
return false;
if (!Equals(target))
@@ -393,7 +393,7 @@ bool RAS_MeshSlot::Join(RAS_MeshSlot *target, MT_Scalar distance)
target->m_joinedSlots.push_back(this);
MT_Matrix4x4 ntransform = m_joinInvTransform.transposed();
- ntransform[0][3]= ntransform[1][3]= ntransform[2][3]= 0.0f;
+ ntransform[0][3] = ntransform[1][3] = ntransform[2][3] = 0.0f;
for (begin(mit); !end(mit); next(mit))
for (i=mit.startvertex; i<mit.endvertex; i++)
@@ -461,7 +461,7 @@ bool RAS_MeshSlot::Split(bool force)
abort();
}
- if (target->m_displayArrays.size()) {
+ if (target->m_displayArrays.empty() == false) {
target->m_endvertex = target->m_displayArrays.back()->m_vertex.size();
target->m_endindex = target->m_displayArrays.back()->m_index.size();
}
@@ -471,7 +471,7 @@ bool RAS_MeshSlot::Split(bool force)
}
MT_Matrix4x4 ntransform = m_joinInvTransform.inverse().transposed();
- ntransform[0][3]= ntransform[1][3]= ntransform[2][3]= 0.0f;
+ ntransform[0][3] = ntransform[1][3] = ntransform[2][3] = 0.0f;
for (begin(mit); !end(mit); next(mit))
for (i=mit.startvertex; i<mit.endvertex; i++)
@@ -489,7 +489,7 @@ bool RAS_MeshSlot::Split(bool force)
}
-#ifdef USE_SPLIT
+#ifdef USE_SPLIT
bool RAS_MeshSlot::IsCulled()
{
if (m_joinSlot)
@@ -502,7 +502,7 @@ bool RAS_MeshSlot::IsCulled()
return false;
return true;
}
-#endif
+#endif
/* material bucket sorting */
@@ -531,12 +531,12 @@ RAS_IPolyMaterial* RAS_MaterialBucket::GetPolyMaterial() const
}
bool RAS_MaterialBucket::IsAlpha() const
-{
+{
return (m_material->IsAlpha());
}
bool RAS_MaterialBucket::IsZSort() const
-{
+{
return (m_material->IsZSort());
}
diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.h b/source/gameengine/Rasterizer/RAS_MaterialBucket.h
index 295f2510313..16ecffb9a32 100644
--- a/source/gameengine/Rasterizer/RAS_MaterialBucket.h
+++ b/source/gameengine/Rasterizer/RAS_MaterialBucket.h
@@ -254,4 +254,4 @@ private:
#endif
};
-#endif //__RAS_MATERIAL_BUCKET
+#endif /* __RAS_MATERIAL_BUCKET */
diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.cpp b/source/gameengine/Rasterizer/RAS_MeshObject.cpp
index 25afefbcc5a..2ccb9453b3d 100644
--- a/source/gameengine/Rasterizer/RAS_MeshObject.cpp
+++ b/source/gameengine/Rasterizer/RAS_MeshObject.cpp
@@ -173,7 +173,7 @@ const STR_String& RAS_MeshObject::GetMaterialName(unsigned int matid)
RAS_MeshMaterial* RAS_MeshObject::GetMeshMaterial(unsigned int matid)
{
- if (m_materials.size() > 0 && (matid < m_materials.size()))
+ if ((m_materials.empty() == false) && (matid < m_materials.size()))
{
list<RAS_MeshMaterial>::iterator it = m_materials.begin();
while (matid--) ++it;
@@ -584,7 +584,7 @@ void RAS_MeshObject::CheckWeightCache(Object* obj)
if (!m_mesh->key)
return;
- for (kbindex=0, kb= (KeyBlock*)m_mesh->key->block.first; kb; kb= (KeyBlock*)kb->next, kbindex++)
+ for (kbindex = 0, kb = (KeyBlock *)m_mesh->key->block.first; kb; kb = kb->next, kbindex++)
{
// first check the cases where the weight must be cleared
if (kb->vgroup[0] == 0 ||
@@ -608,7 +608,7 @@ void RAS_MeshObject::CheckWeightCache(Object* obj)
weights= (float*)MEM_mallocN(totvert*sizeof(float), "weights");
for (i=0; i < totvert; i++, dv++) {
- weights[i]= defvert_find_weight(dv, defindex);
+ weights[i] = defvert_find_weight(dv, defindex);
}
kb->weights = weights;
diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.h b/source/gameengine/Rasterizer/RAS_MeshObject.h
index eb8655c8b1f..281eae8734a 100644
--- a/source/gameengine/Rasterizer/RAS_MeshObject.h
+++ b/source/gameengine/Rasterizer/RAS_MeshObject.h
@@ -32,9 +32,9 @@
#ifndef __RAS_MESHOBJECT_H__
#define __RAS_MESHOBJECT_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-// disable the STL warnings ("debug information length > 255")
-#pragma warning (disable:4786)
+#ifdef _MSC_VER
+ /* disable the STL warnings ("debug information length > 255") */
+# pragma warning (disable:4786)
#endif
#include <vector>
@@ -177,5 +177,4 @@ public:
#endif
};
-#endif //__RAS_MESHOBJECT_H__
-
+#endif /* __RAS_MESHOBJECT_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_ObjectColor.h b/source/gameengine/Rasterizer/RAS_ObjectColor.h
index f8fbe69e97b..77feffccffc 100644
--- a/source/gameengine/Rasterizer/RAS_ObjectColor.h
+++ b/source/gameengine/Rasterizer/RAS_ObjectColor.h
@@ -38,5 +38,4 @@ struct RAS_ObjectColor {
float m_blue;
};
-#endif //__RAS_OBJECTCOLOR_H__
-
+#endif /* __RAS_OBJECTCOLOR_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h
index 6319be6ce4a..eaefd5c13fa 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h
@@ -32,7 +32,7 @@
#ifndef __RAS_EROSION2DFILTER_H__
#define __RAS_EROSION2DFILTER_H__
-const char * ErosionFragmentShader=STRINGIFY(
+const char * ErosionFragmentShader = STRINGIFY(
uniform sampler2D bgl_RenderedTexture;
uniform vec2 bgl_TextureCoordinateOffset[9];
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
index 1f411a09586..d74aa134779 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
@@ -124,7 +124,7 @@ void RAS_ListRasterizer::RemoveListSlot(RAS_ListSlot* list)
{
if (list->m_flag & LIST_DERIVEDMESH) {
RAS_DerivedMeshLists::iterator it = mDerivedMeshLists.begin();
- while(it != mDerivedMeshLists.end()) {
+ while (it != mDerivedMeshLists.end()) {
RAS_ListSlots *slots = it->second;
if (slots->size() > list->m_matnr && slots->at(list->m_matnr) == list) {
(*slots)[list->m_matnr] = NULL;
@@ -145,7 +145,7 @@ void RAS_ListRasterizer::RemoveListSlot(RAS_ListSlot* list)
}
} else {
RAS_ArrayLists::iterator it = mArrayLists.begin();
- while(it != mArrayLists.end()) {
+ while (it != mArrayLists.end()) {
if (it->second == list) {
mArrayLists.erase(it);
break;
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
index b769fc4b703..22a700c7d2b 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
@@ -52,7 +52,10 @@
#include "DNA_material_types.h"
#include "DNA_scene_types.h"
-#include "BKE_DerivedMesh.h"
+extern "C"{
+ #include "BLI_utildefines.h"
+ #include "BKE_DerivedMesh.h"
+}
#ifndef M_PI
#define M_PI 3.14159265358979323846
@@ -239,10 +242,10 @@ void RAS_OpenGLRasterizer::DisplayFog()
glFogf(GL_FOG_DENSITY, 0.1f);
glFogf(GL_FOG_START, m_fogstart);
glFogf(GL_FOG_END, m_fogstart + m_fogdist);
- params[0]= m_fogr;
- params[1]= m_fogg;
- params[2]= m_fogb;
- params[3]= 0.0;
+ params[0] = m_fogr;
+ params[1] = m_fogg;
+ params[2] = m_fogb;
+ params[3] = 0.0;
glFogfv(GL_FOG_COLOR, params);
glEnable(GL_FOG);
}
@@ -359,7 +362,7 @@ void RAS_OpenGLRasterizer::ClearCachingInfo(void)
void RAS_OpenGLRasterizer::FlushDebugShapes()
{
- if (!m_debugShapes.size())
+ if (m_debugShapes.empty())
return;
// DrawDebugLines
@@ -438,7 +441,7 @@ void RAS_OpenGLRasterizer::EndFrame()
glDisable(GL_MULTISAMPLE_ARB);
m_2DCanvas->EndFrame();
-}
+}
void RAS_OpenGLRasterizer::SetRenderArea()
{
@@ -447,8 +450,7 @@ void RAS_OpenGLRasterizer::SetRenderArea()
switch (m_stereomode)
{
case RAS_STEREO_ABOVEBELOW:
- switch(m_curreye)
- {
+ switch (m_curreye) {
case RAS_STEREO_LEFTEYE:
// upper half of window
area.SetLeft(0);
@@ -716,53 +718,53 @@ void RAS_OpenGLRasterizer::TexCoord(const RAS_TexVert &tv)
glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
continue;
}
- switch(m_texco[unit]) {
- case RAS_TEXCO_ORCO:
- case RAS_TEXCO_GLOB:
- glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getXYZ());
- break;
- case RAS_TEXCO_UV1:
- glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV1());
- break;
- case RAS_TEXCO_NORM:
- glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getNormal());
- break;
- case RAS_TEXTANGENT:
- glMultiTexCoord4fvARB(GL_TEXTURE0_ARB+unit, tv.getTangent());
- break;
- case RAS_TEXCO_UV2:
- glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
- break;
- default:
- break;
+ switch (m_texco[unit]) {
+ case RAS_TEXCO_ORCO:
+ case RAS_TEXCO_GLOB:
+ glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getXYZ());
+ break;
+ case RAS_TEXCO_UV1:
+ glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV1());
+ break;
+ case RAS_TEXCO_NORM:
+ glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getNormal());
+ break;
+ case RAS_TEXTANGENT:
+ glMultiTexCoord4fvARB(GL_TEXTURE0_ARB+unit, tv.getTangent());
+ break;
+ case RAS_TEXCO_UV2:
+ glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
+ break;
+ default:
+ break;
}
}
}
if (GLEW_ARB_vertex_program) {
for (unit=0; unit<m_attrib_num; unit++) {
- switch(m_attrib[unit]) {
- case RAS_TEXCO_ORCO:
- case RAS_TEXCO_GLOB:
- glVertexAttrib3fvARB(unit, tv.getXYZ());
- break;
- case RAS_TEXCO_UV1:
- glVertexAttrib2fvARB(unit, tv.getUV1());
- break;
- case RAS_TEXCO_NORM:
- glVertexAttrib3fvARB(unit, tv.getNormal());
- break;
- case RAS_TEXTANGENT:
- glVertexAttrib4fvARB(unit, tv.getTangent());
- break;
- case RAS_TEXCO_UV2:
- glVertexAttrib2fvARB(unit, tv.getUV2());
- break;
- case RAS_TEXCO_VCOL:
- glVertexAttrib4ubvARB(unit, tv.getRGBA());
- break;
- default:
- break;
+ switch (m_attrib[unit]) {
+ case RAS_TEXCO_ORCO:
+ case RAS_TEXCO_GLOB:
+ glVertexAttrib3fvARB(unit, tv.getXYZ());
+ break;
+ case RAS_TEXCO_UV1:
+ glVertexAttrib2fvARB(unit, tv.getUV1());
+ break;
+ case RAS_TEXCO_NORM:
+ glVertexAttrib3fvARB(unit, tv.getNormal());
+ break;
+ case RAS_TEXTANGENT:
+ glVertexAttrib4fvARB(unit, tv.getTangent());
+ break;
+ case RAS_TEXCO_UV2:
+ glVertexAttrib2fvARB(unit, tv.getUV2());
+ break;
+ case RAS_TEXCO_VCOL:
+ glVertexAttrib4ubvARB(unit, tv.getRGBA());
+ break;
+ default:
+ break;
}
}
}
@@ -975,7 +977,7 @@ void RAS_OpenGLRasterizer::SetProjectionMatrix(const MT_Matrix4x4 & mat)
/* Get into argument. Looks a bit dodgy, but it's ok. */
mat.getValue(matrix);
/* Internally, MT_Matrix4x4 uses doubles (MT_Scalar). */
- glLoadMatrixd(matrix);
+ glLoadMatrixd(matrix);
m_camortho= (mat[3][3] != 0.0);
}
@@ -1007,8 +1009,7 @@ MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix(
near_div_focallength = frustnear / m_focallength;
offset = 0.5f * m_eyeseparation * near_div_focallength;
- switch(m_curreye)
- {
+ switch (m_curreye) {
case RAS_STEREO_LEFTEYE:
left += offset;
right += offset;
@@ -1078,8 +1079,7 @@ void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat,
// vector between eyes
eyeline = viewDir.cross(viewupVec);
- switch(m_curreye)
- {
+ switch (m_curreye) {
case RAS_STEREO_LEFTEYE:
{
// translate to left by half the eye distance
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h
index e5eba249175..88bb0be531b 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h
@@ -32,8 +32,8 @@
#ifndef __RAS_OPENGLRASTERIZER_H__
#define __RAS_OPENGLRASTERIZER_H__
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786)
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
#endif
#include "MT_CmMatrix4x4.h"
@@ -278,7 +278,7 @@ public:
line.m_type = OglDebugShape::CIRCLE;
line.m_pos= center;
line.m_param = normal;
- line.m_color = color;
+ line.m_color = color;
line.m_param2.x() = radius;
line.m_param2.y() = (float) nsector;
m_debugShapes.push_back(line);
@@ -322,6 +322,4 @@ public:
#endif
};
-#endif //__RAS_OPENGLRASTERIZER_H__
-
-
+#endif /* __RAS_OPENGLRASTERIZER_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp
index a36229c35d1..076acb0d153 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp
@@ -246,8 +246,7 @@ void RAS_VAOpenGLRasterizer::TexCoordPtr(const RAS_TexVert *tv)
glTexCoordPointer(2, GL_FLOAT, sizeof(RAS_TexVert), tv->getUV2());
continue;
}
- switch(m_texco[unit])
- {
+ switch (m_texco[unit]) {
case RAS_TEXCO_ORCO:
case RAS_TEXCO_GLOB:
glTexCoordPointer(3, GL_FLOAT, sizeof(RAS_TexVert),tv->getXYZ());
@@ -274,7 +273,7 @@ void RAS_VAOpenGLRasterizer::TexCoordPtr(const RAS_TexVert *tv)
if (GLEW_ARB_vertex_program) {
for (unit=0; unit<m_attrib_num; unit++) {
- switch(m_attrib[unit]) {
+ switch (m_attrib[unit]) {
case RAS_TEXCO_ORCO:
case RAS_TEXCO_GLOB:
glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getXYZ());
@@ -330,8 +329,7 @@ void RAS_VAOpenGLRasterizer::EnableTextures(bool enable)
for (unit=0; unit<texco_num; unit++) {
glClientActiveTextureARB(GL_TEXTURE0_ARB+unit);
- switch(texco[unit])
- {
+ switch (texco[unit]) {
case RAS_TEXCO_ORCO:
case RAS_TEXCO_GLOB:
case RAS_TEXCO_UV1:
@@ -358,7 +356,7 @@ void RAS_VAOpenGLRasterizer::EnableTextures(bool enable)
if (GLEW_ARB_vertex_program) {
for (unit=0; unit<attrib_num; unit++) {
- switch(attrib[unit]) {
+ switch (attrib[unit]) {
case RAS_TEXCO_ORCO:
case RAS_TEXCO_GLOB:
case RAS_TEXCO_UV1:
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h
index e881192171f..6b159db05ed 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h
@@ -67,5 +67,4 @@ private:
#endif
};
-#endif //__RAS_VAOPENGLRASTERIZER_H__
-
+#endif /* __RAS_VAOPENGLRASTERIZER_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_Polygon.cpp b/source/gameengine/Rasterizer/RAS_Polygon.cpp
index a6912c0997d..74544a80efa 100644
--- a/source/gameengine/Rasterizer/RAS_Polygon.cpp
+++ b/source/gameengine/Rasterizer/RAS_Polygon.cpp
@@ -29,9 +29,8 @@
* \ingroup bgerast
*/
-
-#if defined(WIN32) && !defined(FREE_WINDOWS)
-#pragma warning (disable:4786)
+#ifdef _MSC_VER
+# pragma warning (disable:4786)
#endif
#include "RAS_Polygon.h"
@@ -41,7 +40,7 @@ RAS_Polygon::RAS_Polygon(RAS_MaterialBucket* bucket, RAS_DisplayArray *darray, i
{
m_bucket = bucket;
m_darray = darray;
- m_offset[0]= m_offset[1]= m_offset[2]= m_offset[3]= 0;
+ m_offset[0] = m_offset[1] = m_offset[2] = m_offset[3] = 0;
m_numvert = numvert;
// m_edgecode = 255;
diff --git a/source/gameengine/Rasterizer/RAS_Rect.h b/source/gameengine/Rasterizer/RAS_Rect.h
index cb5f7d47457..fc99c9159db 100644
--- a/source/gameengine/Rasterizer/RAS_Rect.h
+++ b/source/gameengine/Rasterizer/RAS_Rect.h
@@ -101,5 +101,4 @@ public:
#endif
};
-#endif // __RAS_RECT_H__
-
+#endif /* __RAS_RECT_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_TexMatrix.h b/source/gameengine/Rasterizer/RAS_TexMatrix.h
index 44ae1b0eb5d..a2dd291d016 100644
--- a/source/gameengine/Rasterizer/RAS_TexMatrix.h
+++ b/source/gameengine/Rasterizer/RAS_TexMatrix.h
@@ -39,5 +39,4 @@
void RAS_CalcTexMatrix(RAS_TexVert p[3],MT_Point3& origin,MT_Vector3& udir,MT_Vector3& vdir);
-#endif //__RAS_TEXMATRIX_H__
-
+#endif /* __RAS_TEXMATRIX_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_TexVert.cpp b/source/gameengine/Rasterizer/RAS_TexVert.cpp
index f74aa24232b..b60fae73e2a 100644
--- a/source/gameengine/Rasterizer/RAS_TexVert.cpp
+++ b/source/gameengine/Rasterizer/RAS_TexVert.cpp
@@ -77,7 +77,7 @@ void RAS_TexVert::SetXYZ(const MT_Point3& xyz)
void RAS_TexVert::SetXYZ(const float *xyz)
{
- m_localxyz[0]= xyz[0]; m_localxyz[1]= xyz[1]; m_localxyz[2]= xyz[2];
+ m_localxyz[0] = xyz[0]; m_localxyz[1] = xyz[1]; m_localxyz[2] = xyz[2];
}
void RAS_TexVert::SetUV(const MT_Point2& uv)
diff --git a/source/gameengine/Rasterizer/RAS_TexVert.h b/source/gameengine/Rasterizer/RAS_TexVert.h
index 15059a9cf12..889769da5ed 100644
--- a/source/gameengine/Rasterizer/RAS_TexVert.h
+++ b/source/gameengine/Rasterizer/RAS_TexVert.h
@@ -148,5 +148,4 @@ public:
#endif
};
-#endif //__RAS_TEXVERT_H__
-
+#endif /* __RAS_TEXVERT_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_texmatrix.cpp b/source/gameengine/Rasterizer/RAS_texmatrix.cpp
index 4399265c380..d335a38171f 100644
--- a/source/gameengine/Rasterizer/RAS_texmatrix.cpp
+++ b/source/gameengine/Rasterizer/RAS_texmatrix.cpp
@@ -93,10 +93,10 @@ int main()
MT_Point2 puv0={0,0};
MT_Point3 pxyz0 (0,0,128);
- MT_Scalar puv1[2]={1,0};
+ MT_Scalar puv1[2] = {1,0};
MT_Point3 pxyz1(128,0,128);
- MT_Scalar puv2[2]={1,1};
+ MT_Scalar puv2[2] = {1,1};
MT_Point3 pxyz2(128,0,0);
RAS_TexVert p0(pxyz0,puv0);
diff --git a/source/gameengine/SceneGraph/SG_Controller.h b/source/gameengine/SceneGraph/SG_Controller.h
index d82738dbb86..a173633e13c 100644
--- a/source/gameengine/SceneGraph/SG_Controller.h
+++ b/source/gameengine/SceneGraph/SG_Controller.h
@@ -53,7 +53,7 @@ public:
) {};
virtual
- bool
+ bool
Update(
double time
)=0;
@@ -69,13 +69,13 @@ public:
);
virtual
- void
+ void
SetSimulatedTime(
double time
)=0;
- virtual
- SG_Controller*
+ virtual
+ SG_Controller*
GetReplica(
class SG_Node* destnode
)=0;
@@ -121,5 +121,4 @@ protected:
#endif
};
-#endif //__SG_CONTROLLER_H__
-
+#endif /* __SG_CONTROLLER_H__ */
diff --git a/source/gameengine/SceneGraph/SG_DList.h b/source/gameengine/SceneGraph/SG_DList.h
index be1c1fda2f2..90153f14c07 100644
--- a/source/gameengine/SceneGraph/SG_DList.h
+++ b/source/gameengine/SceneGraph/SG_DList.h
@@ -248,5 +248,4 @@ public:
};
-#endif //__SG_DLIST_H__
-
+#endif /* __SG_DLIST_H__ */
diff --git a/source/gameengine/SceneGraph/SG_IObject.cpp b/source/gameengine/SceneGraph/SG_IObject.cpp
index afd647c2a2a..9ae32a89ff8 100644
--- a/source/gameengine/SceneGraph/SG_IObject.cpp
+++ b/source/gameengine/SceneGraph/SG_IObject.cpp
@@ -70,7 +70,7 @@ AddSGController(
m_SGcontrollers.push_back(cont);
}
- void
+ void
SG_IObject::
RemoveSGController(
SG_Controller* cont
diff --git a/source/gameengine/SceneGraph/SG_IObject.h b/source/gameengine/SceneGraph/SG_IObject.h
index c36c984f3d3..885eb8e1e90 100644
--- a/source/gameengine/SceneGraph/SG_IObject.h
+++ b/source/gameengine/SceneGraph/SG_IObject.h
@@ -174,7 +174,7 @@ public:
* this object is deleted.
*/
- void
+ void
AddSGController(
SG_Controller* cont
);
@@ -196,7 +196,7 @@ public:
* leaks.
*/
- void
+ void
RemoveAllControllers(
);
@@ -233,7 +233,7 @@ public:
* This may be NULL.
*/
- inline const void* GetSGClientObject() const
+ inline const void* GetSGClientObject() const
{
return m_SGclientObject;
}
@@ -280,7 +280,7 @@ public:
void SetControllerTime(double time);
virtual
- void
+ void
Destruct(
) = 0;
@@ -371,5 +371,4 @@ protected :
#endif
};
-#endif //__SG_IOBJECT_H__
-
+#endif /* __SG_IOBJECT_H__ */
diff --git a/source/gameengine/SceneGraph/SG_Node.cpp b/source/gameengine/SceneGraph/SG_Node.cpp
index 33af9f16d7c..04d9a306fc4 100644
--- a/source/gameengine/SceneGraph/SG_Node.cpp
+++ b/source/gameengine/SceneGraph/SG_Node.cpp
@@ -143,7 +143,7 @@ Destruct()
}
const
- SG_Node*
+ SG_Node *
SG_Node::
GetRootSGParent(
) const {
diff --git a/source/gameengine/SceneGraph/SG_Node.h b/source/gameengine/SceneGraph/SG_Node.h
index 1d0c0e592e6..bde64f21305 100644
--- a/source/gameengine/SceneGraph/SG_Node.h
+++ b/source/gameengine/SceneGraph/SG_Node.h
@@ -63,7 +63,7 @@ public:
* make a deep copy.
*/
- void
+ void
AddChild(
SG_Node* child
);
@@ -75,7 +75,7 @@ public:
* If the node was not a child of this object no action is performed.
*/
- void
+ void
RemoveChild(
SG_Node* child
);
@@ -149,7 +149,7 @@ public:
* Disconnect this node from it's parent
*/
- void
+ void
DisconnectFromParent(
);
@@ -182,12 +182,12 @@ public:
- /**
+ /**
* Update the spatial data of this node. Iterate through
* the children of this node and update their world data.
*/
- void
+ void
UpdateWorldData(
double time,
bool parentUpdated=false
@@ -198,7 +198,7 @@ public:
* the children nodes and update their simulated time.
*/
- void
+ void
SetSimulatedTime(
double time,
bool recurse
@@ -244,17 +244,17 @@ public:
* Node replication functions.
*/
- SG_Node*
+ SG_Node*
GetSGReplica(
);
- void
+ void
Destruct(
);
private:
- void
+ void
ProcessSGReplica(
SG_Node** replica
);
@@ -275,5 +275,4 @@ private:
#endif
};
-#endif //__SG_NODE_H__
-
+#endif /* __SG_NODE_H__ */
diff --git a/source/gameengine/SceneGraph/SG_ParentRelation.h b/source/gameengine/SceneGraph/SG_ParentRelation.h
index 4478ed11bc1..6e314996456 100644
--- a/source/gameengine/SceneGraph/SG_ParentRelation.h
+++ b/source/gameengine/SceneGraph/SG_ParentRelation.h
@@ -118,7 +118,7 @@ protected :
*/
SG_ParentRelation(
- ) {
+ ) {
};
/**
diff --git a/source/gameengine/SceneGraph/SG_QList.h b/source/gameengine/SceneGraph/SG_QList.h
index bcc56f05615..663f29ebd88 100644
--- a/source/gameengine/SceneGraph/SG_QList.h
+++ b/source/gameengine/SceneGraph/SG_QList.h
@@ -161,5 +161,4 @@ public:
#endif
};
-#endif //__SG_QLIST_H__
-
+#endif /* __SG_QLIST_H__ */
diff --git a/source/gameengine/SceneGraph/SG_Spatial.cpp b/source/gameengine/SceneGraph/SG_Spatial.cpp
index f8c4b5165ee..f30c80da434 100644
--- a/source/gameengine/SceneGraph/SG_Spatial.cpp
+++ b/source/gameengine/SceneGraph/SG_Spatial.cpp
@@ -103,7 +103,7 @@ SetParentRelation(
/**
* Update Spatial Data.
- * Calculates WorldTransform., (either doing itsself or using the linked SGControllers)
+ * Calculates WorldTransform., (either doing its self or using the linked SGControllers)
*/
@@ -161,8 +161,8 @@ RelativeTranslate(
}
}
SetModified();
-}
-
+}
+
/**
* Scaling methods.
diff --git a/source/gameengine/SceneGraph/SG_Spatial.h b/source/gameengine/SceneGraph/SG_Spatial.h
index e456851d183..aa917fa70db 100644
--- a/source/gameengine/SceneGraph/SG_Spatial.h
+++ b/source/gameengine/SceneGraph/SG_Spatial.h
@@ -137,7 +137,7 @@ public:
}
- void
+ void
RelativeRotate(
const MT_Matrix3x3& rot,
bool local
@@ -178,12 +178,12 @@ public:
m_worldScaling = scale;
}
- const MT_Point3& GetLocalPosition() const
+ const MT_Point3& GetLocalPosition() const
{
return m_localPosition;
}
- const MT_Matrix3x3& GetLocalOrientation() const
+ const MT_Matrix3x3& GetLocalOrientation() const
{
return m_localRotation;
}
@@ -193,17 +193,17 @@ public:
return m_localScaling;
}
- const MT_Point3& GetWorldPosition() const
+ const MT_Point3& GetWorldPosition() const
{
return m_worldPosition;
}
- const MT_Matrix3x3& GetWorldOrientation() const
+ const MT_Matrix3x3& GetWorldOrientation() const
{
return m_worldRotation;
}
- const MT_Vector3& GetWorldScaling() const
+ const MT_Vector3& GetWorldScaling() const
{
return m_worldScaling;
}
@@ -291,5 +291,4 @@ protected:
#endif
};
-#endif //__SG_SPATIAL_H__
-
+#endif /* __SG_SPATIAL_H__ */
diff --git a/source/gameengine/SceneGraph/SG_Tree.cpp b/source/gameengine/SceneGraph/SG_Tree.cpp
index 0f8264985de..99f68ef625a 100644
--- a/source/gameengine/SceneGraph/SG_Tree.cpp
+++ b/source/gameengine/SceneGraph/SG_Tree.cpp
@@ -236,7 +236,7 @@ void SG_TreeFactory::Add(SG_Tree* tree)
SG_Tree* SG_TreeFactory::MakeTreeDown(SG_BBox &bbox)
{
- if (m_objects.size() == 0)
+ if (m_objects.empty())
return NULL;
if (m_objects.size() == 1)
return *m_objects.begin();
diff --git a/source/gameengine/VideoTexture/BlendType.h b/source/gameengine/VideoTexture/BlendType.h
index 0131cc61c44..e19aadc49d2 100644
--- a/source/gameengine/VideoTexture/BlendType.h
+++ b/source/gameengine/VideoTexture/BlendType.h
@@ -37,7 +37,7 @@ public:
BlendType (const char * name) : m_name(name) {}
/// check blender type and return pointer to contained object or NULL (if type is not valid)
- PyObj * checkType (PyObject * obj)
+ PyObj *checkType(PyObject *obj)
{
// if pointer to type isn't set
if (m_objType == NULL)
@@ -55,17 +55,18 @@ public:
return NULL;
// return pointer to object, this class can only be used for KX object =>
// the Py object is actually a proxy
- return (PyObj*)BGE_PROXY_REF(obj);
+ return (PyObj *)BGE_PROXY_REF(obj);
}
/// parse arguments to get object
- PyObj * parseArg (PyObject * args)
+ PyObj *parseArg(PyObject *args)
{
// parse arguments
- PyObject * obj;
- if (PyArg_ParseTuple(args, "O", &obj))
+ PyObject *obj;
+ if (PyArg_ParseTuple(args, "O", &obj)) {
// if successfully parsed, return pointer to object
return checkType(obj);
+ }
// otherwise return NULL
return NULL;
}
@@ -74,7 +75,7 @@ protected:
/// name of Python type
const char * m_name;
/// pointer to Python type
- PyTypeObject * m_objType;
+ PyTypeObject *m_objType;
};
diff --git a/source/gameengine/VideoTexture/FilterBase.cpp b/source/gameengine/VideoTexture/FilterBase.cpp
index 90ea8436ffe..6ec5e237ac2 100644
--- a/source/gameengine/VideoTexture/FilterBase.cpp
+++ b/source/gameengine/VideoTexture/FilterBase.cpp
@@ -90,10 +90,10 @@ PyTypeList pyFilterTypes;
// object allocation
-PyObject * Filter_allocNew (PyTypeObject * type, PyObject * args, PyObject * kwds)
+PyObject *Filter_allocNew (PyTypeObject *type, PyObject *args, PyObject *kwds)
{
// allocate object
- PyFilter * self = reinterpret_cast<PyFilter*>(type->tp_alloc(type, 0));
+ PyFilter *self = reinterpret_cast<PyFilter*>(type->tp_alloc(type, 0));
// initialize object structure
self->m_filter = NULL;
// return allocated object
@@ -101,7 +101,7 @@ PyObject * Filter_allocNew (PyTypeObject * type, PyObject * args, PyObject * kwd
}
// object deallocation
-void Filter_dealloc (PyFilter * self)
+void Filter_dealloc (PyFilter *self)
{
// release object attributes
if (self->m_filter != NULL)
@@ -114,7 +114,7 @@ void Filter_dealloc (PyFilter * self)
// get previous pixel filter object
-PyObject * Filter_getPrevious (PyFilter * self, void * closure)
+PyObject *Filter_getPrevious (PyFilter *self, void *closure)
{
// if filter object is available
if (self->m_filter != NULL)
@@ -135,7 +135,7 @@ PyObject * Filter_getPrevious (PyFilter * self, void * closure)
// set previous pixel filter object
-int Filter_setPrevious (PyFilter * self, PyObject * value, void * closure)
+int Filter_setPrevious (PyFilter *self, PyObject *value, void *closure)
{
// if filter object is available
if (self->m_filter != NULL)
diff --git a/source/gameengine/VideoTexture/FilterBase.h b/source/gameengine/VideoTexture/FilterBase.h
index 63561c25ffa..98bc495375a 100644
--- a/source/gameengine/VideoTexture/FilterBase.h
+++ b/source/gameengine/VideoTexture/FilterBase.h
@@ -95,6 +95,10 @@ protected:
virtual unsigned int filter (unsigned int * src, short x, short y,
short * size, unsigned int pixSize, unsigned int val = 0)
{ return val; }
+ /// filter pixel, source float buffer
+ virtual unsigned int filter (float * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val = 0)
+ { return val; }
/// get source pixel size
virtual unsigned int getPixelSize (void) { return 1; }
@@ -118,9 +122,9 @@ extern PyTypeList pyFilterTypes;
// functions for python interface
// object initialization
-template <class T> static int Filter_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+template <class T> static int Filter_init (PyObject *pySelf, PyObject *args, PyObject *kwds)
{
- PyFilter * self = reinterpret_cast<PyFilter*>(pySelf);
+ PyFilter *self = reinterpret_cast<PyFilter*>(pySelf);
// create filter object
if (self->m_filter != NULL) delete self->m_filter;
self->m_filter = new T();
@@ -129,14 +133,14 @@ template <class T> static int Filter_init (PyObject * pySelf, PyObject * args, P
}
// object allocation
-PyObject * Filter_allocNew (PyTypeObject * type, PyObject * args, PyObject * kwds);
+PyObject *Filter_allocNew(PyTypeObject *type, PyObject *args, PyObject *kwds);
// object deallocation
-void Filter_dealloc (PyFilter * self);
+void Filter_dealloc(PyFilter *self);
// get previous pixel filter object
-PyObject * Filter_getPrevious (PyFilter * self, void * closure);
+PyObject *Filter_getPrevious(PyFilter *self, void *closure);
// set previous pixel filter object
-int Filter_setPrevious (PyFilter * self, PyObject * value, void * closure);
+int Filter_setPrevious(PyFilter *self, PyObject *value, void *closure);
#endif
diff --git a/source/gameengine/VideoTexture/FilterBlueScreen.cpp b/source/gameengine/VideoTexture/FilterBlueScreen.cpp
index 02a6a8f0344..8559e8f87f4 100644
--- a/source/gameengine/VideoTexture/FilterBlueScreen.cpp
+++ b/source/gameengine/VideoTexture/FilterBlueScreen.cpp
@@ -66,21 +66,21 @@ void FilterBlueScreen::setLimits (unsigned short minLimit, unsigned short maxLim
// cast Filter pointer to FilterBlueScreen
-inline FilterBlueScreen * getFilter (PyFilter * self)
+inline FilterBlueScreen * getFilter (PyFilter *self)
{ return static_cast<FilterBlueScreen*>(self->m_filter); }
// python methods and get/sets
// get color
-static PyObject * getColor (PyFilter * self, void * closure)
+static PyObject *getColor (PyFilter *self, void *closure)
{
return Py_BuildValue("[BBB]", getFilter(self)->getColor()[0],
getFilter(self)->getColor()[1], getFilter(self)->getColor()[2]);
}
// set color
-static int setColor (PyFilter * self, PyObject * value, void * closure)
+static int setColor (PyFilter *self, PyObject *value, void *closure)
{
// check validity of parameter
if (value == NULL || !PySequence_Check(value) || PySequence_Size(value) != 3
@@ -100,14 +100,14 @@ static int setColor (PyFilter * self, PyObject * value, void * closure)
}
// get limits
-static PyObject * getLimits (PyFilter * self, void * closure)
+static PyObject *getLimits (PyFilter *self, void *closure)
{
return Py_BuildValue("[II]", getFilter(self)->getLimits()[0],
getFilter(self)->getLimits()[1]);
}
// set limit
-static int setLimits (PyFilter * self, PyObject * value, void * closure)
+static int setLimits (PyFilter *self, PyObject *value, void *closure)
{
// check validity of parameter
if (value == NULL || !PySequence_Check(value) || PySequence_Size(value) != 2
diff --git a/source/gameengine/VideoTexture/FilterColor.cpp b/source/gameengine/VideoTexture/FilterColor.cpp
index ed75b4f8da8..35a6414f383 100644
--- a/source/gameengine/VideoTexture/FilterColor.cpp
+++ b/source/gameengine/VideoTexture/FilterColor.cpp
@@ -108,14 +108,14 @@ void FilterColor::setMatrix (ColorMatrix & mat)
// cast Filter pointer to FilterColor
-inline FilterColor * getFilterColor (PyFilter * self)
+inline FilterColor * getFilterColor (PyFilter *self)
{ return static_cast<FilterColor*>(self->m_filter); }
// python methods and get/sets
// get color matrix
-static PyObject * getMatrix (PyFilter * self, void * closure)
+static PyObject *getMatrix (PyFilter *self, void *closure)
{
ColorMatrix & mat = getFilterColor(self)->getMatrix();
return Py_BuildValue("((hhhhh)(hhhhh)(hhhhh)(hhhhh))",
@@ -126,7 +126,7 @@ static PyObject * getMatrix (PyFilter * self, void * closure)
}
// set color matrix
-static int setMatrix (PyFilter * self, PyObject * value, void * closure)
+static int setMatrix (PyFilter *self, PyObject *value, void *closure)
{
// matrix to store items
ColorMatrix mat;
@@ -243,14 +243,14 @@ void FilterLevel::setLevels (ColorLevel & lev)
// cast Filter pointer to FilterLevel
-inline FilterLevel * getFilterLevel (PyFilter * self)
+inline FilterLevel * getFilterLevel (PyFilter *self)
{ return static_cast<FilterLevel*>(self->m_filter); }
// python methods and get/sets
// get color levels
-static PyObject * getLevels (PyFilter * self, void * closure)
+static PyObject *getLevels (PyFilter *self, void *closure)
{
ColorLevel & lev = getFilterLevel(self)->getLevels();
return Py_BuildValue("((HH)(HH)(HH)(HH))",
@@ -259,7 +259,7 @@ static PyObject * getLevels (PyFilter * self, void * closure)
}
// set color levels
-static int setLevels (PyFilter * self, PyObject * value, void * closure)
+static int setLevels (PyFilter *self, PyObject *value, void *closure)
{
// matrix to store items
ColorLevel lev;
diff --git a/source/gameengine/VideoTexture/FilterNormal.cpp b/source/gameengine/VideoTexture/FilterNormal.cpp
index dda1a493291..03c500a7e14 100644
--- a/source/gameengine/VideoTexture/FilterNormal.cpp
+++ b/source/gameengine/VideoTexture/FilterNormal.cpp
@@ -59,20 +59,20 @@ void FilterNormal::setDepth (float depth)
// cast Filter pointer to FilterNormal
-inline FilterNormal * getFilter (PyFilter * self)
+inline FilterNormal * getFilter (PyFilter *self)
{ return static_cast<FilterNormal*>(self->m_filter); }
// python methods and get/sets
// get index of color used to calculate normal
-static PyObject * getColor (PyFilter * self, void * closure)
+static PyObject *getColor (PyFilter *self, void *closure)
{
return Py_BuildValue("H", getFilter(self)->getColor());
}
// set index of color used to calculate normal
-static int setColor (PyFilter * self, PyObject * value, void * closure)
+static int setColor (PyFilter *self, PyObject *value, void *closure)
{
// check validity of parameter
if (value == NULL || !PyLong_Check(value))
@@ -88,13 +88,13 @@ static int setColor (PyFilter * self, PyObject * value, void * closure)
// get depth
-static PyObject * getDepth (PyFilter * self, void * closure)
+static PyObject *getDepth (PyFilter *self, void *closure)
{
return Py_BuildValue("f", getFilter(self)->getDepth());
}
// set depth
-static int setDepth (PyFilter * self, PyObject * value, void * closure)
+static int setDepth (PyFilter *self, PyObject *value, void *closure)
{
// check validity of parameter
if (value)
diff --git a/source/gameengine/VideoTexture/FilterSource.h b/source/gameengine/VideoTexture/FilterSource.h
index a4900e8c148..cb9e22a133d 100644
--- a/source/gameengine/VideoTexture/FilterSource.h
+++ b/source/gameengine/VideoTexture/FilterSource.h
@@ -31,7 +31,6 @@ http://www.gnu.org/copyleft/lesser.txt.
#include "FilterBase.h"
-
/// class for RGB24 conversion
class FilterRGB24 : public FilterBase
{
@@ -97,6 +96,65 @@ protected:
{ VT_RGBA(val,src[2],src[1],src[0],0xFF); return val; }
};
+/// class for Z_buffer conversion
+class FilterZZZA : public FilterBase
+{
+public:
+ /// constructor
+ FilterZZZA (void) {}
+ /// destructor
+ virtual ~FilterZZZA (void) {}
+
+ /// get source pixel size
+ virtual unsigned int getPixelSize (void) { return 1; }
+
+protected:
+ /// filter pixel, source float buffer
+ virtual unsigned int filter (float * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val)
+ {
+ // calculate gray value
+ // convert float to unsigned char
+ unsigned int depth = int(src[0] * 255);
+ // return depth scale value
+ VT_R(val) = depth;
+ VT_G(val) = depth;
+ VT_B(val) = depth;
+ VT_A(val) = 0xFF;
+
+ return val;
+ }
+};
+
+
+/// class for Z_buffer conversion
+class FilterDEPTH : public FilterBase
+{
+public:
+ /// constructor
+ FilterDEPTH (void) {}
+ /// destructor
+ virtual ~FilterDEPTH (void) {}
+
+ /// get source pixel size
+ virtual unsigned int getPixelSize (void) { return 1; }
+
+protected:
+ /// filter pixel, source float buffer
+ virtual unsigned int filter (float * src, short x, short y,
+ short * size, unsigned int pixSize, unsigned int val)
+ {
+ /* Copy the float value straight away
+ * The user can retrieve the original float value by using
+ * 'F' mode in BGL buffer */
+ memcpy(&val, src, sizeof (unsigned int));
+ return val;
+ }
+};
+
+
+
+
/// class for YV12 conversion
class FilterYV12 : public FilterBase
{
diff --git a/source/gameengine/VideoTexture/ImageBase.cpp b/source/gameengine/VideoTexture/ImageBase.cpp
index 54c1939ce6b..de54d8e8940 100644
--- a/source/gameengine/VideoTexture/ImageBase.cpp
+++ b/source/gameengine/VideoTexture/ImageBase.cpp
@@ -49,6 +49,8 @@ extern "C" {
// constructor
ImageBase::ImageBase (bool staticSrc) : m_image(NULL), m_imgSize(0),
m_avail(false), m_scale(false), m_scaleChange(false), m_flip(false),
+m_zbuff(false),
+m_depth(false),
m_staticSources(staticSrc), m_pyfilter(NULL)
{
m_size[0] = m_size[1] = 0;
@@ -128,7 +130,7 @@ PyImage * ImageBase::getSource (const char * id)
// set source object
-bool ImageBase::setSource (const char * id, PyImage * source)
+bool ImageBase::setSource (const char * id, PyImage *source)
{
// find source
ImageSourceList::iterator src = findSource(id);
@@ -315,7 +317,7 @@ bool ImageSource::is (const char * id)
// set source object
-void ImageSource::setSource (PyImage * source)
+void ImageSource::setSource (PyImage *source)
{
// reference new source
if (source != NULL) Py_INCREF(source);
@@ -358,10 +360,10 @@ PyTypeList pyImageTypes;
// functions for python interface
// object allocation
-PyObject * Image_allocNew (PyTypeObject * type, PyObject * args, PyObject * kwds)
+PyObject *Image_allocNew (PyTypeObject *type, PyObject *args, PyObject *kwds)
{
// allocate object
- PyImage * self = reinterpret_cast<PyImage*>(type->tp_alloc(type, 0));
+ PyImage *self = reinterpret_cast<PyImage*>(type->tp_alloc(type, 0));
// initialize object structure
self->m_image = NULL;
// return allocated object
@@ -369,7 +371,7 @@ PyObject * Image_allocNew (PyTypeObject * type, PyObject * args, PyObject * kwds
}
// object deallocation
-void Image_dealloc (PyImage * self)
+void Image_dealloc (PyImage *self)
{
// release object attributes
if (self->m_image != NULL)
@@ -388,7 +390,7 @@ void Image_dealloc (PyImage * self)
}
// get image data
-PyObject * Image_getImage (PyImage * self, char * mode)
+PyObject *Image_getImage (PyImage *self, char * mode)
{
try
{
@@ -402,6 +404,18 @@ PyObject * Image_getImage (PyImage * self, char * mode)
{
buffer = BGL_MakeBuffer( GL_BYTE, 1, &dimensions, image);
}
+ else if (!strcasecmp(mode, "F"))
+ {
+ // this mode returns the image as an array of float.
+ // This makes sense ONLY for the depth buffer:
+ // source = VideoTexture.ImageViewport()
+ // source.depth = True
+ // depth = VideoTexture.imageToArray(source, 'F')
+
+ // adapt dimension from byte to float
+ dimensions /= sizeof(float);
+ buffer = BGL_MakeBuffer( GL_FLOAT, 1, &dimensions, image);
+ }
else
{
int i, c, ncolor, pixels;
@@ -463,7 +477,7 @@ PyObject * Image_getImage (PyImage * self, char * mode)
}
}
}
- return (PyObject*)buffer;
+ return (PyObject *)buffer;
}
}
catch (Exception & exp)
@@ -475,28 +489,28 @@ PyObject * Image_getImage (PyImage * self, char * mode)
}
// get image size
-PyObject * Image_getSize (PyImage * self, void * closure)
+PyObject *Image_getSize (PyImage *self, void *closure)
{
return Py_BuildValue("(hh)", self->m_image->getSize()[0],
self->m_image->getSize()[1]);
}
// refresh image
-PyObject * Image_refresh (PyImage * self)
+PyObject *Image_refresh (PyImage *self)
{
self->m_image->refresh();
Py_RETURN_NONE;
}
// get scale
-PyObject * Image_getScale (PyImage * self, void * closure)
+PyObject *Image_getScale (PyImage *self, void *closure)
{
if (self->m_image != NULL && self->m_image->getScale()) Py_RETURN_TRUE;
else Py_RETURN_FALSE;
}
// set scale
-int Image_setScale (PyImage * self, PyObject * value, void * closure)
+int Image_setScale (PyImage *self, PyObject *value, void *closure)
{
// check parameter, report failure
if (value == NULL || !PyBool_Check(value))
@@ -511,14 +525,14 @@ int Image_setScale (PyImage * self, PyObject * value, void * closure)
}
// get flip
-PyObject * Image_getFlip (PyImage * self, void * closure)
+PyObject *Image_getFlip (PyImage *self, void *closure)
{
if (self->m_image != NULL && self->m_image->getFlip()) Py_RETURN_TRUE;
else Py_RETURN_FALSE;
}
// set flip
-int Image_setFlip (PyImage * self, PyObject * value, void * closure)
+int Image_setFlip (PyImage *self, PyObject *value, void *closure)
{
// check parameter, report failure
if (value == NULL || !PyBool_Check(value))
@@ -532,9 +546,55 @@ int Image_setFlip (PyImage * self, PyObject * value, void * closure)
return 0;
}
+// get zbuff
+PyObject * Image_getZbuff (PyImage * self, void * closure)
+{
+ if (self->m_image != NULL && self->m_image->getZbuff()) Py_RETURN_TRUE;
+ else Py_RETURN_FALSE;
+}
+
+// set zbuff
+int Image_setZbuff (PyImage * self, PyObject * value, void * closure)
+{
+ // check parameter, report failure
+ if (value == NULL || !PyBool_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a bool");
+ return -1;
+ }
+ // set scale
+ if (self->m_image != NULL) self->m_image->setZbuff(value == Py_True);
+ // success
+ return 0;
+}
+
+// get depth
+PyObject * Image_getDepth (PyImage * self, void * closure)
+{
+ if (self->m_image != NULL && self->m_image->getDepth()) Py_RETURN_TRUE;
+ else Py_RETURN_FALSE;
+}
+
+// set depth
+int Image_setDepth (PyImage * self, PyObject * value, void * closure)
+{
+ // check parameter, report failure
+ if (value == NULL || !PyBool_Check(value))
+ {
+ PyErr_SetString(PyExc_TypeError, "The value must be a bool");
+ return -1;
+ }
+ // set scale
+ if (self->m_image != NULL) self->m_image->setDepth(value == Py_True);
+ // success
+ return 0;
+}
+
+
+
// get filter source object
-PyObject * Image_getSource (PyImage * self, PyObject * args)
+PyObject *Image_getSource (PyImage *self, PyObject *args)
{
// get arguments
char * id;
@@ -543,7 +603,7 @@ PyObject * Image_getSource (PyImage * self, PyObject * args)
if (self->m_image != NULL)
{
// get source object
- PyObject * src = reinterpret_cast<PyObject*>(self->m_image->getSource(id));
+ PyObject *src = reinterpret_cast<PyObject*>(self->m_image->getSource(id));
// if source is available
if (src != NULL)
{
@@ -558,11 +618,11 @@ PyObject * Image_getSource (PyImage * self, PyObject * args)
// set filter source object
-PyObject * Image_setSource (PyImage * self, PyObject * args)
+PyObject *Image_setSource (PyImage *self, PyObject *args)
{
// get arguments
char * id;
- PyObject * obj;
+ PyObject *obj;
if (!PyArg_ParseTuple(args, "sO:setSource", &id, &obj))
return NULL;
if (self->m_image != NULL)
@@ -593,7 +653,7 @@ PyObject * Image_setSource (PyImage * self, PyObject * args)
// get pixel filter object
-PyObject * Image_getFilter (PyImage * self, void * closure)
+PyObject *Image_getFilter (PyImage *self, void *closure)
{
// if image object is available
if (self->m_image != NULL)
@@ -614,7 +674,7 @@ PyObject * Image_getFilter (PyImage * self, void * closure)
// set pixel filter object
-int Image_setFilter (PyImage * self, PyObject * value, void * closure)
+int Image_setFilter (PyImage *self, PyObject *value, void *closure)
{
// if image object is available
if (self->m_image != NULL)
@@ -632,7 +692,7 @@ int Image_setFilter (PyImage * self, PyObject * value, void * closure)
// return success
return 0;
}
-PyObject * Image_valid(PyImage * self, void * closure)
+PyObject *Image_valid(PyImage *self, void *closure)
{
if (self->m_image->isImageAvailable())
{
@@ -644,7 +704,7 @@ PyObject * Image_valid(PyImage * self, void * closure)
}
}
-int Image_getbuffer(PyImage *self, Py_buffer *view, int flags)
+static int Image_getbuffer(PyImage *self, Py_buffer *view, int flags)
{
unsigned int * image;
int ret;
@@ -674,7 +734,7 @@ int Image_getbuffer(PyImage *self, Py_buffer *view, int flags)
self->m_image->m_exports++;
return 0;
}
- ret = PyBuffer_FillInfo(view, (PyObject*)self, image, self->m_image->getBuffSize(), 0, flags);
+ ret = PyBuffer_FillInfo(view, (PyObject *)self, image, self->m_image->getBuffSize(), 0, flags);
if (ret >= 0)
self->m_image->m_exports++;
return ret;
@@ -684,14 +744,14 @@ error:
// The bug is fixed in Python SVN 77916, as soon as the python revision used by Blender is
// updated, you can simply return -1 and set the error
static char* buf = (char *)"";
- ret = PyBuffer_FillInfo(view, (PyObject*)self, buf, 0, 0, flags);
+ ret = PyBuffer_FillInfo(view, (PyObject *)self, buf, 0, 0, flags);
if (ret >= 0)
self->m_image->m_exports++;
return ret;
}
-void Image_releaseBuffer(PyImage *self, Py_buffer *buffer)
+static void Image_releaseBuffer(PyImage *self, Py_buffer *buffer)
{
self->m_image->m_exports--;
}
diff --git a/source/gameengine/VideoTexture/ImageBase.h b/source/gameengine/VideoTexture/ImageBase.h
index 6c38b107a4d..a9f25f61406 100644
--- a/source/gameengine/VideoTexture/ImageBase.h
+++ b/source/gameengine/VideoTexture/ImageBase.h
@@ -78,11 +78,19 @@ public:
bool getFlip (void) { return m_flip; }
/// set vertical flip
void setFlip (bool flip) { m_flip = flip; }
+ /// get Z buffer
+ bool getZbuff (void) { return m_zbuff; }
+ /// set Z buffer
+ void setZbuff (bool zbuff) { m_zbuff = zbuff; }
+ /// get depth
+ bool getDepth (void) { return m_depth; }
+ /// set depth
+ void setDepth (bool depth) { m_depth = depth; }
/// get source object
PyImage * getSource (const char * id);
/// set source object, return true, if source was set
- bool setSource (const char * id, PyImage * source);
+ bool setSource (const char * id, PyImage *source);
/// get pixel filter
PyFilter * getFilter (void) { return m_pyfilter; }
@@ -111,6 +119,10 @@ protected:
bool m_scaleChange;
/// flip image vertically
bool m_flip;
+ /// use the Z buffer as a texture
+ bool m_zbuff;
+ /// extract the Z buffer with unisgned int precision
+ bool m_depth;
/// source image list
ImageSourceList m_sources;
@@ -276,7 +288,7 @@ public:
/// get source object
PyImage * getSource (void) { return m_source; }
/// set source object
- void setSource (PyImage * source);
+ void setSource (PyImage *source);
/// get image from source
unsigned int * getImage (double ts=-1.0);
@@ -312,9 +324,9 @@ extern PyTypeList pyImageTypes;
// functions for python interface
// object initialization
-template <class T> static int Image_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+template <class T> static int Image_init (PyObject *pySelf, PyObject *args, PyObject *kwds)
{
- PyImage * self = reinterpret_cast<PyImage*>(pySelf);
+ PyImage *self = reinterpret_cast<PyImage*>(pySelf);
// create source object
if (self->m_image != NULL) delete self->m_image;
self->m_image = new T();
@@ -323,37 +335,45 @@ template <class T> static int Image_init (PyObject * pySelf, PyObject * args, Py
}
// object allocation
-PyObject * Image_allocNew (PyTypeObject * type, PyObject * args, PyObject * kwds);
+PyObject *Image_allocNew (PyTypeObject *type, PyObject *args, PyObject *kwds);
// object deallocation
-void Image_dealloc (PyImage * self);
+void Image_dealloc (PyImage *self);
// get image data
-PyObject * Image_getImage (PyImage * self, char * mode);
+PyObject *Image_getImage (PyImage *self, char * mode);
// get image size
-PyObject * Image_getSize (PyImage * self, void * closure);
+PyObject *Image_getSize (PyImage *self, void *closure);
// refresh image - invalidate current content
-PyObject * Image_refresh (PyImage * self);
+PyObject *Image_refresh (PyImage *self);
// get scale
-PyObject * Image_getScale (PyImage * self, void * closure);
+PyObject *Image_getScale (PyImage *self, void *closure);
// set scale
-int Image_setScale (PyImage * self, PyObject * value, void * closure);
+int Image_setScale (PyImage *self, PyObject *value, void *closure);
// get flip
-PyObject * Image_getFlip (PyImage * self, void * closure);
+PyObject *Image_getFlip (PyImage *self, void *closure);
// set flip
-int Image_setFlip (PyImage * self, PyObject * value, void * closure);
+int Image_setFlip (PyImage *self, PyObject *value, void *closure);
// get filter source object
-PyObject * Image_getSource (PyImage * self, PyObject * args);
+PyObject *Image_getSource (PyImage *self, PyObject *args);
// set filter source object
-PyObject * Image_setSource (PyImage * self, PyObject * args);
-
+PyObject *Image_setSource (PyImage *self, PyObject *args);
+// get Z buffer
+PyObject * Image_getZbuff (PyImage * self, void * closure);
+// set Z buffer
+int Image_setZbuff (PyImage * self, PyObject * value, void * closure);
+// get depth
+PyObject * Image_getDepth (PyImage * self, void * closure);
+// set depth
+int Image_setDepth (PyImage * self, PyObject * value, void * closure);
+
// get pixel filter object
-PyObject * Image_getFilter (PyImage * self, void * closure);
+PyObject *Image_getFilter (PyImage *self, void *closure);
// set pixel filter object
-int Image_setFilter (PyImage * self, PyObject * value, void * closure);
+int Image_setFilter (PyImage *self, PyObject *value, void *closure);
// check if a buffer can be extracted
-PyObject * Image_valid(PyImage * self, void * closure);
+PyObject *Image_valid(PyImage *self, void *closure);
// for buffer access to PyImage objects
extern PyBufferProcs imageBufferProcs;
diff --git a/source/gameengine/VideoTexture/ImageBuff.cpp b/source/gameengine/VideoTexture/ImageBuff.cpp
index 17513d20a39..eec0bccbe56 100644
--- a/source/gameengine/VideoTexture/ImageBuff.cpp
+++ b/source/gameengine/VideoTexture/ImageBuff.cpp
@@ -47,7 +47,7 @@ FilterRGB24 defFilter;
// forward declaration;
extern PyTypeObject ImageBuffType;
-static int ImageBuff_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+static int ImageBuff_init (PyObject *pySelf, PyObject *args, PyObject *kwds)
{
short width = -1;
short height = -1;
@@ -55,7 +55,7 @@ static int ImageBuff_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
PyObject *py_scale = Py_False;
ImageBuff *image;
- PyImage * self = reinterpret_cast<PyImage*>(pySelf);
+ PyImage *self = reinterpret_cast<PyImage*>(pySelf);
// create source object
if (self->m_image != NULL)
delete self->m_image;
@@ -190,7 +190,7 @@ void ImageBuff::plot (ImageBuff* img, short x, short y, short mode)
// cast Image pointer to ImageBuff
-inline ImageBuff * getImageBuff (PyImage * self)
+inline ImageBuff * getImageBuff (PyImage *self)
{ return static_cast<ImageBuff*>(self->m_image); }
@@ -245,7 +245,7 @@ static bool testBGLBuffer(Buffer* buffer, int width, int height, unsigned int pi
// load image
-static PyObject * load (PyImage * self, PyObject * args)
+static PyObject *load(PyImage *self, PyObject *args)
{
// parameters: string image buffer, its size, width, height
Py_buffer buffer;
@@ -306,10 +306,10 @@ static PyObject * load (PyImage * self, PyObject * args)
}
if (PyErr_Occurred())
return NULL;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-static PyObject * plot (PyImage * self, PyObject * args)
+static PyObject *plot (PyImage *self, PyObject *args)
{
PyImage * other;
Buffer* bglBuffer;
@@ -332,7 +332,7 @@ static PyObject * plot (PyImage * self, PyObject * args)
PyBuffer_Release(&buffer);
if (PyErr_Occurred())
return NULL;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyErr_Clear();
// try the other format
@@ -354,7 +354,7 @@ static PyObject * plot (PyImage * self, PyObject * args)
}
if (PyErr_Occurred())
return NULL;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
// methods structure
diff --git a/source/gameengine/VideoTexture/ImageMix.cpp b/source/gameengine/VideoTexture/ImageMix.cpp
index cd8c6683a7f..f09454a517b 100644
--- a/source/gameengine/VideoTexture/ImageMix.cpp
+++ b/source/gameengine/VideoTexture/ImageMix.cpp
@@ -101,14 +101,14 @@ void ImageMix::calcImage (unsigned int texId, double ts)
// cast Image pointer to ImageMix
-inline ImageMix * getImageMix (PyImage * self)
+inline ImageMix * getImageMix (PyImage *self)
{ return static_cast<ImageMix*>(self->m_image); }
// python methods
// get source weight
-PyObject * getWeight (PyImage * self, PyObject * args)
+static PyObject *getWeight (PyImage *self, PyObject *args)
{
// weight
short weight = 0;
@@ -125,7 +125,7 @@ PyObject * getWeight (PyImage * self, PyObject * args)
// set source weight
-PyObject * setWeight (PyImage * self, PyObject * args)
+static PyObject *setWeight (PyImage *self, PyObject *args)
{
// get arguments
char * id;
diff --git a/source/gameengine/VideoTexture/ImageRender.cpp b/source/gameengine/VideoTexture/ImageRender.cpp
index c8763671dd1..85857165403 100644
--- a/source/gameengine/VideoTexture/ImageRender.cpp
+++ b/source/gameengine/VideoTexture/ImageRender.cpp
@@ -277,7 +277,7 @@ void ImageRender::Render()
// cast Image pointer to ImageRender
-inline ImageRender * getImageRender (PyImage * self)
+inline ImageRender * getImageRender (PyImage *self)
{ return static_cast<ImageRender*>(self->m_image); }
@@ -290,10 +290,10 @@ BlendType<KX_Camera> cameraType ("KX_Camera");
// object initialization
-static int ImageRender_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+static int ImageRender_init (PyObject *pySelf, PyObject *args, PyObject *kwds)
{
// parameters - scene object
- PyObject * scene;
+ PyObject *scene;
// camera object
PyObject * camera;
// parameter keywords
@@ -317,7 +317,7 @@ static int ImageRender_init (PyObject * pySelf, PyObject * args, PyObject * kwds
if (cameraPtr == NULL) THRWEXCP(CameraInvalid, S_OK);
// get pointer to image structure
- PyImage * self = reinterpret_cast<PyImage*>(pySelf);
+ PyImage *self = reinterpret_cast<PyImage*>(pySelf);
// create source object
if (self->m_image != NULL) delete self->m_image;
self->m_image = new ImageRender(scenePtr, cameraPtr);
@@ -333,7 +333,7 @@ static int ImageRender_init (PyObject * pySelf, PyObject * args, PyObject * kwds
// get background color
-PyObject * getBackground (PyImage * self, void * closure)
+static PyObject *getBackground (PyImage *self, void *closure)
{
return Py_BuildValue("[BBBB]",
getImageRender(self)->getBackground(0),
@@ -343,7 +343,7 @@ PyObject * getBackground (PyImage * self, void * closure)
}
// set color
-static int setBackground (PyImage * self, PyObject * value, void * closure)
+static int setBackground (PyImage *self, PyObject *value, void *closure)
{
// check validity of parameter
if (value == NULL || !PySequence_Check(value) || PySequence_Size(value) != 4
@@ -385,6 +385,8 @@ static PyGetSetDef imageRenderGetSets[] =
{(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
{(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
{(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
+ {(char*)"zbuff", (getter)Image_getZbuff, (setter)Image_setZbuff, (char*)"use depth buffer as texture", NULL},
+ {(char*)"depth", (getter)Image_getDepth, (setter)Image_setDepth, (char*)"get depth information from z-buffer using unsigned int precision", NULL},
{(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
{NULL}
};
@@ -434,14 +436,14 @@ PyTypeObject ImageRenderType =
};
// object initialization
-static int ImageMirror_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+static int ImageMirror_init (PyObject *pySelf, PyObject *args, PyObject *kwds)
{
// parameters - scene object
- PyObject * scene;
+ PyObject *scene;
// reference object for mirror
- PyObject * observer;
+ PyObject *observer;
// object holding the mirror
- PyObject * mirror;
+ PyObject *mirror;
// material of the mirror
short materialID = 0;
// parameter keywords
@@ -490,7 +492,7 @@ static int ImageMirror_init (PyObject * pySelf, PyObject * args, PyObject * kwds
THRWEXCP(MaterialNotAvail, S_OK);
// get pointer to image structure
- PyImage * self = reinterpret_cast<PyImage*>(pySelf);
+ PyImage *self = reinterpret_cast<PyImage*>(pySelf);
// create source object
if (self->m_image != NULL)
@@ -510,13 +512,13 @@ static int ImageMirror_init (PyObject * pySelf, PyObject * args, PyObject * kwds
}
// get background color
-PyObject * getClip (PyImage * self, void * closure)
+static PyObject *getClip (PyImage *self, void *closure)
{
return PyFloat_FromDouble(getImageRender(self)->getClip());
}
// set clip
-static int setClip (PyImage * self, PyObject * value, void * closure)
+static int setClip (PyImage *self, PyObject *value, void *closure)
{
// check validity of parameter
double clip;
@@ -547,6 +549,8 @@ static PyGetSetDef imageMirrorGetSets[] =
{(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
{(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
{(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
+ {(char*)"zbuff", (getter)Image_getZbuff, (setter)Image_setZbuff, (char*)"use depth buffer as texture", NULL},
+ {(char*)"depth", (getter)Image_getDepth, (setter)Image_setDepth, (char*)"get depth information from z-buffer using unsigned int precision", NULL},
{(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
{NULL}
};
diff --git a/source/gameengine/VideoTexture/ImageViewport.cpp b/source/gameengine/VideoTexture/ImageViewport.cpp
index a780fdcc38c..af44e394fce 100644
--- a/source/gameengine/VideoTexture/ImageViewport.cpp
+++ b/source/gameengine/VideoTexture/ImageViewport.cpp
@@ -50,6 +50,8 @@ ImageViewport::ImageViewport (void) : m_alpha(false), m_texInit(false)
//glGetIntegerv(GL_VIEWPORT, m_viewport);
// create buffer for viewport image
+ // Warning: this buffer is also used to get the depth buffer as an array of
+ // float (1 float = 4 bytes per pixel)
m_viewportImage = new BYTE [4 * getViewportSize()[0] * getViewportSize()[1]];
// set attributes
setWhole(false);
@@ -57,7 +59,9 @@ ImageViewport::ImageViewport (void) : m_alpha(false), m_texInit(false)
// destructor
ImageViewport::~ImageViewport (void)
-{ delete [] m_viewportImage; }
+{
+ delete [] m_viewportImage;
+}
// use whole viewport to capture image
@@ -123,15 +127,14 @@ void ImageViewport::calcImage (unsigned int texId, double ts)
// reset image
init(m_capSize[0], m_capSize[1]);
// if texture wasn't initialized
- if (!m_texInit)
- {
+ if (!m_texInit) {
// initialize it
loadTexture(texId, m_image, m_size);
m_texInit = true;
}
// if texture can be directly created
if (texId != 0 && m_pyfilter == NULL && m_capSize[0] == calcSize(m_capSize[0])
- && m_capSize[1] == calcSize(m_capSize[1]) && !m_flip)
+ && m_capSize[1] == calcSize(m_capSize[1]) && !m_flip && !m_zbuff && !m_depth)
{
// just copy current viewport to texture
glBindTexture(GL_TEXTURE_2D, texId);
@@ -140,24 +143,47 @@ void ImageViewport::calcImage (unsigned int texId, double ts)
m_avail = false;
}
// otherwise copy viewport to buffer, if image is not available
- else if (!m_avail)
- {
- // get frame buffer data
- if (m_alpha)
- {
- glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1], GL_RGBA,
- GL_UNSIGNED_BYTE, m_viewportImage);
+ else if (!m_avail) {
+ if (m_zbuff) {
+ // Use read pixels with the depth buffer
+ // *** misusing m_viewportImage here, but since it has the correct size
+ // (4 bytes per pixel = size of float) and we just need it to apply
+ // the filter, it's ok
+ glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1],
+ GL_DEPTH_COMPONENT, GL_FLOAT, m_viewportImage);
// filter loaded data
- FilterRGBA32 filt;
- filterImage(filt, m_viewportImage, m_capSize);
+ FilterZZZA filt;
+ filterImage(filt, (float *)m_viewportImage, m_capSize);
}
- else
- {
- glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1], GL_RGB,
- GL_UNSIGNED_BYTE, m_viewportImage);
- // filter loaded data
- FilterRGB24 filt;
- filterImage(filt, m_viewportImage, m_capSize);
+ else {
+
+ if (m_depth) {
+ // Use read pixels with the depth buffer
+ // See warning above about m_viewportImage.
+ glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1],
+ GL_DEPTH_COMPONENT, GL_FLOAT, m_viewportImage);
+ // filter loaded data
+ FilterDEPTH filt;
+ filterImage(filt, (float *)m_viewportImage, m_capSize);
+ }
+ else {
+
+ // get frame buffer data
+ if (m_alpha) {
+ glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1], GL_RGBA,
+ GL_UNSIGNED_BYTE, m_viewportImage);
+ // filter loaded data
+ FilterRGBA32 filt;
+ filterImage(filt, m_viewportImage, m_capSize);
+ }
+ else {
+ glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1], GL_RGB,
+ GL_UNSIGNED_BYTE, m_viewportImage);
+ // filter loaded data
+ FilterRGB24 filt;
+ filterImage(filt, m_viewportImage, m_capSize);
+ }
+ }
}
}
}
@@ -165,7 +191,7 @@ void ImageViewport::calcImage (unsigned int texId, double ts)
// cast Image pointer to ImageViewport
-inline ImageViewport * getImageViewport (PyImage * self)
+inline ImageViewport * getImageViewport (PyImage *self)
{ return static_cast<ImageViewport*>(self->m_image); }
@@ -173,14 +199,14 @@ inline ImageViewport * getImageViewport (PyImage * self)
// get whole
-PyObject * ImageViewport_getWhole (PyImage * self, void * closure)
+PyObject *ImageViewport_getWhole (PyImage *self, void *closure)
{
if (self->m_image != NULL && getImageViewport(self)->getWhole()) Py_RETURN_TRUE;
else Py_RETURN_FALSE;
}
// set whole
-int ImageViewport_setWhole (PyImage * self, PyObject * value, void * closure)
+int ImageViewport_setWhole (PyImage *self, PyObject *value, void *closure)
{
// check parameter, report failure
if (value == NULL || !PyBool_Check(value))
@@ -203,14 +229,14 @@ int ImageViewport_setWhole (PyImage * self, PyObject * value, void * closure)
}
// get alpha
-PyObject * ImageViewport_getAlpha (PyImage * self, void * closure)
+PyObject *ImageViewport_getAlpha (PyImage *self, void *closure)
{
if (self->m_image != NULL && getImageViewport(self)->getAlpha()) Py_RETURN_TRUE;
else Py_RETURN_FALSE;
}
// set whole
-int ImageViewport_setAlpha (PyImage * self, PyObject * value, void * closure)
+int ImageViewport_setAlpha (PyImage *self, PyObject *value, void *closure)
{
// check parameter, report failure
if (value == NULL || !PyBool_Check(value))
@@ -226,14 +252,14 @@ int ImageViewport_setAlpha (PyImage * self, PyObject * value, void * closure)
// get position
-static PyObject * ImageViewport_getPosition (PyImage * self, void * closure)
+static PyObject *ImageViewport_getPosition (PyImage *self, void *closure)
{
return Py_BuildValue("(ii)", getImageViewport(self)->getPosition()[0],
getImageViewport(self)->getPosition()[1]);
}
// set position
-static int ImageViewport_setPosition (PyImage * self, PyObject * value, void * closure)
+static int ImageViewport_setPosition (PyImage *self, PyObject *value, void *closure)
{
// check validity of parameter
if (value == NULL || !PySequence_Check(value) || PySequence_Size(value) != 2
@@ -254,14 +280,14 @@ static int ImageViewport_setPosition (PyImage * self, PyObject * value, void * c
}
// get capture size
-PyObject * ImageViewport_getCaptureSize (PyImage * self, void * closure)
+PyObject *ImageViewport_getCaptureSize (PyImage *self, void *closure)
{
return Py_BuildValue("(ii)", getImageViewport(self)->getCaptureSize()[0],
getImageViewport(self)->getCaptureSize()[1]);
}
// set capture size
-int ImageViewport_setCaptureSize (PyImage * self, PyObject * value, void * closure)
+int ImageViewport_setCaptureSize (PyImage *self, PyObject *value, void *closure)
{
// check validity of parameter
if (value == NULL || !PySequence_Check(value) || PySequence_Size(value) != 2
@@ -310,6 +336,8 @@ static PyGetSetDef imageViewportGetSets[] =
{(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
{(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
{(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
+ {(char*)"zbuff", (getter)Image_getZbuff, (setter)Image_setZbuff, (char*)"use depth buffer as texture", NULL},
+ {(char*)"depth", (getter)Image_getDepth, (setter)Image_setDepth, (char*)"get depth information from z-buffer as array of float", NULL},
{(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
{NULL}
};
diff --git a/source/gameengine/VideoTexture/ImageViewport.h b/source/gameengine/VideoTexture/ImageViewport.h
index ccc58a41605..198655c6ebf 100644
--- a/source/gameengine/VideoTexture/ImageViewport.h
+++ b/source/gameengine/VideoTexture/ImageViewport.h
@@ -91,12 +91,12 @@ protected:
GLint * getViewportSize (void) { return m_viewport + 2; }
};
-PyObject * ImageViewport_getCaptureSize (PyImage * self, void * closure);
-int ImageViewport_setCaptureSize (PyImage * self, PyObject * value, void * closure);
-PyObject * ImageViewport_getWhole (PyImage * self, void * closure);
-int ImageViewport_setWhole (PyImage * self, PyObject * value, void * closure);
-PyObject * ImageViewport_getAlpha (PyImage * self, void * closure);
-int ImageViewport_setAlpha (PyImage * self, PyObject * value, void * closure);
+PyObject *ImageViewport_getCaptureSize (PyImage *self, void *closure);
+int ImageViewport_setCaptureSize (PyImage *self, PyObject *value, void *closure);
+PyObject *ImageViewport_getWhole (PyImage *self, void *closure);
+int ImageViewport_setWhole (PyImage *self, PyObject *value, void *closure);
+PyObject *ImageViewport_getAlpha (PyImage *self, void *closure);
+int ImageViewport_setAlpha (PyImage *self, PyObject *value, void *closure);
#endif
diff --git a/source/gameengine/VideoTexture/PyTypeList.cpp b/source/gameengine/VideoTexture/PyTypeList.cpp
index ed53e8bd1f1..9fe98544961 100644
--- a/source/gameengine/VideoTexture/PyTypeList.cpp
+++ b/source/gameengine/VideoTexture/PyTypeList.cpp
@@ -41,7 +41,7 @@ PyTypeList::~PyTypeList()
}
/// check, if type is in list
-bool PyTypeList::in (PyTypeObject * type)
+bool PyTypeList::in (PyTypeObject *type)
{
// if list exists
if (m_list.get() != NULL)
@@ -54,7 +54,7 @@ bool PyTypeList::in (PyTypeObject * type)
}
/// add type to list
-void PyTypeList::add (PyTypeObject * type, const char * name)
+void PyTypeList::add (PyTypeObject *type, const char * name)
{
// if list doesn't exist, create it
if (m_list.get() == NULL)
@@ -78,7 +78,7 @@ bool PyTypeList::ready (void)
}
/// register types to module
-void PyTypeList::reg (PyObject * module)
+void PyTypeList::reg(PyObject *module)
{
// if list exists
if (m_list.get() != NULL)
@@ -88,6 +88,6 @@ void PyTypeList::reg (PyObject * module)
// increase ref count
Py_INCREF((*it)->getType());
// add type to module
- PyModule_AddObject(module, (char*)(*it)->getName(), (PyObject*)(*it)->getType());
+ PyModule_AddObject(module, (char*)(*it)->getName(), (PyObject *)(*it)->getType());
}
}
diff --git a/source/gameengine/VideoTexture/PyTypeList.h b/source/gameengine/VideoTexture/PyTypeList.h
index aa1df0ce54b..4872b3c3d5c 100644
--- a/source/gameengine/VideoTexture/PyTypeList.h
+++ b/source/gameengine/VideoTexture/PyTypeList.h
@@ -49,16 +49,16 @@ public:
~PyTypeList();
/// check, if type is in list
- bool in (PyTypeObject * type);
+ bool in (PyTypeObject *type);
/// add type to list
- void add (PyTypeObject * type, const char * name);
+ void add (PyTypeObject *type, const char * name);
/// prepare types
bool ready (void);
/// register types to module
- void reg (PyObject * module);
+ void reg(PyObject *module);
protected:
/// pointer to list of types
@@ -71,21 +71,21 @@ class PyTypeListItem
{
public:
/// constructor adds type into list
- PyTypeListItem (PyTypeObject * type, const char * name)
+ PyTypeListItem (PyTypeObject *type, const char * name)
: m_type(type), m_name(name)
{ }
/// does type match
- PyTypeObject * getType (void) { return m_type; }
+ PyTypeObject *getType (void) { return m_type; }
/// get name of type
const char * getName (void) { return m_name; }
protected:
/// pointer to type object
- PyTypeObject * m_type;
+ PyTypeObject *m_type;
/// name of type
- const char * m_name;
+ const char *m_name;
};
diff --git a/source/gameengine/VideoTexture/Texture.cpp b/source/gameengine/VideoTexture/Texture.cpp
index a21300018eb..f58d17f949c 100644
--- a/source/gameengine/VideoTexture/Texture.cpp
+++ b/source/gameengine/VideoTexture/Texture.cpp
@@ -108,7 +108,7 @@ RAS_IPolyMaterial * getMaterial (PyObject *obj, short matID)
}
// get pointer to a lamp
-KX_LightObject * getLamp(PyObject *obj)
+static KX_LightObject *getLamp(PyObject *obj)
{
// if object is available
if (obj == NULL) return NULL;
@@ -119,7 +119,7 @@ KX_LightObject * getLamp(PyObject *obj)
// get material ID
-short getMaterialID(PyObject * obj, const char *name)
+short getMaterialID(PyObject *obj, const char *name)
{
// search for material
for (short matID = 0;; ++matID)
@@ -147,7 +147,7 @@ short getMaterialID(PyObject * obj, const char *name)
// Texture object allocation
-PyObject * Texture_new (PyTypeObject *type, PyObject *args, PyObject *kwds)
+static PyObject *Texture_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
// allocate object
Texture * self = reinterpret_cast<Texture*>(type->tp_alloc(type, 0));
@@ -167,22 +167,22 @@ PyObject * Texture_new (PyTypeObject *type, PyObject *args, PyObject *kwds)
// forward declaration
-PyObject * Texture_close(Texture * self);
-int Texture_setSource (Texture * self, PyObject * value, void * closure);
+PyObject *Texture_close(Texture * self);
+int Texture_setSource (Texture * self, PyObject *value, void *closure);
// Texture object deallocation
-void Texture_dealloc (Texture * self)
+static void Texture_dealloc(Texture *self)
{
// release renderer
Py_XDECREF(self->m_source);
// close texture
- PyObject* ret = Texture_close(self);
+ PyObject *ret = Texture_close(self);
Py_DECREF(ret);
// release scaled image buffer
delete [] self->m_scaledImg;
// release object
- Py_TYPE((PyObject *)self)->tp_free((PyObject*)self);
+ Py_TYPE((PyObject *)self)->tp_free((PyObject *)self);
}
@@ -190,10 +190,10 @@ ExceptionID MaterialNotAvail;
ExpDesc MaterialNotAvailDesc (MaterialNotAvail, "Texture material is not available");
// Texture object initialization
-int Texture_init (Texture *self, PyObject *args, PyObject *kwds)
+static int Texture_init(Texture *self, PyObject *args, PyObject *kwds)
{
// parameters - game object with video texture
- PyObject * obj = NULL;
+ PyObject *obj = NULL;
// material ID
short matID = 0;
// texture ID
@@ -275,7 +275,7 @@ int Texture_init (Texture *self, PyObject *args, PyObject *kwds)
// close added texture
-PyObject * Texture_close(Texture * self)
+PyObject *Texture_close(Texture * self)
{
// restore texture
if (self->m_orgSaved)
@@ -298,10 +298,10 @@ PyObject * Texture_close(Texture * self)
// refresh texture
-PyObject * Texture_refresh (Texture * self, PyObject * args)
+static PyObject *Texture_refresh(Texture *self, PyObject *args)
{
// get parameter - refresh source
- PyObject * param;
+ PyObject *param;
double ts = -1.0;
if (!PyArg_ParseTuple(args, "O|d:refresh", &param, &ts) || !PyBool_Check(param))
@@ -390,14 +390,14 @@ PyObject * Texture_refresh (Texture * self, PyObject * args)
}
// get OpenGL Bind Id
-PyObject * Texture_getBindId (Texture * self, void * closure)
+static PyObject *Texture_getBindId(Texture *self, void *closure)
{
unsigned int id = self->m_actTex;
return Py_BuildValue("h", id);
}
// get mipmap value
-PyObject * Texture_getMipmap (Texture * self, void * closure)
+static PyObject *Texture_getMipmap(Texture *self, void *closure)
{
// return true if flag is set, otherwise false
if (self->m_mipmap) Py_RETURN_TRUE;
@@ -405,7 +405,7 @@ PyObject * Texture_getMipmap (Texture * self, void * closure)
}
// set mipmap value
-int Texture_setMipmap (Texture * self, PyObject * value, void * closure)
+static int Texture_setMipmap(Texture *self, PyObject *value, void *closure)
{
// check parameter, report failure
if (value == NULL || !PyBool_Check(value))
@@ -421,7 +421,7 @@ int Texture_setMipmap (Texture * self, PyObject * value, void * closure)
// get source object
-PyObject * Texture_getSource (Texture * self, PyObject * value, void * closure)
+static PyObject *Texture_getSource(Texture *self, PyObject *value, void *closure)
{
// if source exists
if (self->m_source != NULL)
@@ -435,7 +435,7 @@ PyObject * Texture_getSource (Texture * self, PyObject * value, void * closure)
// set source object
-int Texture_setSource (Texture * self, PyObject * value, void * closure)
+int Texture_setSource (Texture * self, PyObject *value, void *closure)
{
// check new value
if (value == NULL || !pyImageTypes.in(Py_TYPE(value)))
diff --git a/source/gameengine/VideoTexture/Texture.h b/source/gameengine/VideoTexture/Texture.h
index ad5b7b9fb44..cc265725b29 100644
--- a/source/gameengine/VideoTexture/Texture.h
+++ b/source/gameengine/VideoTexture/Texture.h
@@ -78,14 +78,14 @@ struct Texture
extern PyTypeObject TextureType;
// load texture
-void loadTexture (unsigned int texId, unsigned int * texture, short * size,
- bool mipmap = false);
+void loadTexture(unsigned int texId, unsigned int *texture, short *size,
+ bool mipmap = false);
// get material
-RAS_IPolyMaterial * getMaterial (PyObject *obj, short matID);
+RAS_IPolyMaterial *getMaterial(PyObject *obj, short matID);
// get material ID
-short getMaterialID (PyObject * obj, const char *name);
+short getMaterialID(PyObject *obj, const char *name);
// Exceptions
extern ExceptionID MaterialNotAvail;
diff --git a/source/gameengine/VideoTexture/VideoBase.cpp b/source/gameengine/VideoTexture/VideoBase.cpp
index 6662df8d7d1..1eb2e830d37 100644
--- a/source/gameengine/VideoTexture/VideoBase.cpp
+++ b/source/gameengine/VideoTexture/VideoBase.cpp
@@ -116,24 +116,24 @@ void Video_open (VideoBase * self, char * file, short captureID)
// play video
-PyObject * Video_play (PyImage * self)
+PyObject *Video_play(PyImage *self)
{ if (getVideo(self)->play()) Py_RETURN_TRUE; else Py_RETURN_FALSE; }
// pause video
-PyObject * Video_pause (PyImage * self)
+PyObject *Video_pause(PyImage *self)
{ if (getVideo(self)->pause()) Py_RETURN_TRUE; else Py_RETURN_FALSE; }
-PyObject * Video_stop (PyImage * self)
+PyObject *Video_stop(PyImage *self)
{ if (getVideo(self)->stop()) Py_RETURN_TRUE; else Py_RETURN_FALSE; }
// get status
-PyObject * Video_getStatus (PyImage * self, void * closure)
+PyObject *Video_getStatus(PyImage *self, void *closure)
{
return Py_BuildValue("h", getVideo(self)->getStatus());
}
// refresh video
-PyObject * Video_refresh (PyImage * self)
+PyObject *Video_refresh(PyImage *self)
{
getVideo(self)->refresh();
return Video_getStatus(self, NULL);
@@ -141,19 +141,20 @@ PyObject * Video_refresh (PyImage * self)
// get range
-PyObject * Video_getRange (PyImage * self, void * closure)
+PyObject *Video_getRange(PyImage *self, void *closure)
{
return Py_BuildValue("[ff]", getVideo(self)->getRange()[0],
getVideo(self)->getRange()[1]);
}
// set range
-int Video_setRange (PyImage * self, PyObject * value, void * closure)
+int Video_setRange(PyImage *self, PyObject *value, void *closure)
{
// check validity of parameter
- if (value == NULL || !PySequence_Check(value) || PySequence_Size(value) != 2
- || !PyFloat_Check(PySequence_Fast_GET_ITEM(value, 0))
- || !PyFloat_Check(PySequence_Fast_GET_ITEM(value, 1)))
+ if (value == NULL || !PySequence_Check(value) || PySequence_Size(value) != 2 ||
+ /* XXX - this is incorrect if the sequence is not a list/tuple! */
+ !PyFloat_Check(PySequence_Fast_GET_ITEM(value, 0)) ||
+ !PyFloat_Check(PySequence_Fast_GET_ITEM(value, 1)))
{
PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 2 float");
return -1;
@@ -166,11 +167,11 @@ int Video_setRange (PyImage * self, PyObject * value, void * closure)
}
// get repeat
-PyObject * Video_getRepeat (PyImage * self, void * closure)
+PyObject *Video_getRepeat (PyImage *self, void *closure)
{ return Py_BuildValue("h", getVideo(self)->getRepeat()); }
// set repeat
-int Video_setRepeat (PyImage * self, PyObject * value, void * closure)
+int Video_setRepeat(PyImage *self, PyObject *value, void *closure)
{
// check validity of parameter
if (value == NULL || !PyLong_Check(value))
@@ -185,11 +186,11 @@ int Video_setRepeat (PyImage * self, PyObject * value, void * closure)
}
// get frame rate
-PyObject * Video_getFrameRate (PyImage * self, void * closure)
+PyObject *Video_getFrameRate (PyImage *self, void *closure)
{ return Py_BuildValue("f", double(getVideo(self)->getFrameRate())); }
// set frame rate
-int Video_setFrameRate (PyImage * self, PyObject * value, void * closure)
+int Video_setFrameRate(PyImage *self, PyObject *value, void *closure)
{
// check validity of parameter
if (value == NULL || !PyFloat_Check(value))
diff --git a/source/gameengine/VideoTexture/VideoBase.h b/source/gameengine/VideoTexture/VideoBase.h
index e221d876358..4cf913d755d 100644
--- a/source/gameengine/VideoTexture/VideoBase.h
+++ b/source/gameengine/VideoTexture/VideoBase.h
@@ -164,14 +164,14 @@ protected:
// cast Image pointer to Video
-inline VideoBase * getVideo (PyImage * self)
+inline VideoBase *getVideo(PyImage *self)
{ return static_cast<VideoBase*>(self->m_image); }
extern ExceptionID SourceVideoCreation;
// object initialization
-template <class T> void Video_init (PyImage * self)
+template <class T> void Video_init(PyImage *self)
{
// create source video object
if (self->m_image != NULL) delete self->m_image;
@@ -182,18 +182,18 @@ template <class T> void Video_init (PyImage * self)
// video functions
-void Video_open (VideoBase * self, char * file, short captureID);
-PyObject * Video_play (PyImage * self);
-PyObject * Video_pause (PyImage * self);
-PyObject * Video_stop (PyImage * self);
-PyObject * Video_refresh (PyImage * self);
-PyObject * Video_getStatus (PyImage * self, void * closure);
-PyObject * Video_getRange (PyImage * self, void * closure);
-int Video_setRange (PyImage * self, PyObject * value, void * closure);
-PyObject * Video_getRepeat (PyImage * self, void * closure);
-int Video_setRepeat (PyImage * self, PyObject * value, void * closure);
-PyObject * Video_getFrameRate (PyImage * self, void * closure);
-int Video_setFrameRate (PyImage * self, PyObject * value, void * closure);
+void Video_open(VideoBase * self, char * file, short captureID);
+PyObject *Video_play(PyImage *self);
+PyObject *Video_pause(PyImage *self);
+PyObject *Video_stop(PyImage *self);
+PyObject *Video_refresh(PyImage *self);
+PyObject *Video_getStatus(PyImage *self, void *closure);
+PyObject *Video_getRange(PyImage *self, void *closure);
+int Video_setRange(PyImage *self, PyObject *value, void *closure);
+PyObject *Video_getRepeat(PyImage *self, void *closure);
+int Video_setRepeat(PyImage *self, PyObject *value, void *closure);
+PyObject *Video_getFrameRate(PyImage *self, void *closure);
+int Video_setFrameRate(PyImage *self, PyObject *value, void *closure);
#endif
diff --git a/source/gameengine/VideoTexture/VideoFFmpeg.cpp b/source/gameengine/VideoTexture/VideoFFmpeg.cpp
index 1ba944aa955..3f42d5c4fed 100644
--- a/source/gameengine/VideoTexture/VideoFFmpeg.cpp
+++ b/source/gameengine/VideoTexture/VideoFFmpeg.cpp
@@ -485,13 +485,13 @@ void VideoFFmpeg::stopCache()
av_free(frame->frame);
delete frame;
}
- while((packet = (CachePacket *)m_packetCacheBase.first) != NULL)
+ while ((packet = (CachePacket *)m_packetCacheBase.first) != NULL)
{
BLI_remlink(&m_packetCacheBase, packet);
av_free_packet(&packet->packet);
delete packet;
}
- while((packet = (CachePacket *)m_packetCacheFree.first) != NULL)
+ while ((packet = (CachePacket *)m_packetCacheFree.first) != NULL)
{
BLI_remlink(&m_packetCacheFree, packet);
delete packet;
@@ -524,7 +524,7 @@ void VideoFFmpeg::openFile (char * filename)
if (m_codecCtx->gop_size)
m_preseek = (m_codecCtx->gop_size < 25) ? m_codecCtx->gop_size+1 : 25;
- else if (m_codecCtx->has_b_frames)
+ else if (m_codecCtx->has_b_frames)
m_preseek = 25; // should determine gopsize
else
m_preseek = 0;
@@ -921,7 +921,7 @@ AVFrame *VideoFFmpeg::grabFrame(long position)
&& m_preseek
&& position - (m_curPosition + 1) < m_preseek)
{
- while(av_read_frame(m_formatCtx, &packet)>=0)
+ while (av_read_frame(m_formatCtx, &packet)>=0)
{
if (packet.stream_index == m_videoStream)
{
@@ -996,7 +996,7 @@ AVFrame *VideoFFmpeg::grabFrame(long position)
// find the correct frame, in case of streaming and no cache, it means just
// return the next frame. This is not quite correct, may need more work
- while(av_read_frame(m_formatCtx, &packet)>=0)
+ while (av_read_frame(m_formatCtx, &packet) >= 0)
{
if (packet.stream_index == m_videoStream)
{
@@ -1076,14 +1076,14 @@ AVFrame *VideoFFmpeg::grabFrame(long position)
// cast Image pointer to VideoFFmpeg
-inline VideoFFmpeg * getVideoFFmpeg (PyImage * self)
+inline VideoFFmpeg * getVideoFFmpeg (PyImage *self)
{ return static_cast<VideoFFmpeg*>(self->m_image); }
// object initialization
-static int VideoFFmpeg_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+static int VideoFFmpeg_init (PyObject *pySelf, PyObject *args, PyObject *kwds)
{
- PyImage * self = reinterpret_cast<PyImage*>(pySelf);
+ PyImage *self = reinterpret_cast<PyImage*>(pySelf);
// parameters - video source
// file name or format type for capture (only for Linux: video4linux or dv1394)
char * file = NULL;
@@ -1123,13 +1123,13 @@ static int VideoFFmpeg_init (PyObject * pySelf, PyObject * args, PyObject * kwds
return 0;
}
-PyObject * VideoFFmpeg_getPreseek (PyImage *self, void * closure)
+static PyObject *VideoFFmpeg_getPreseek(PyImage *self, void *closure)
{
return Py_BuildValue("h", getFFmpeg(self)->getPreseek());
}
// set range
-int VideoFFmpeg_setPreseek (PyImage * self, PyObject * value, void * closure)
+static int VideoFFmpeg_setPreseek(PyImage *self, PyObject *value, void *closure)
{
// check validity of parameter
if (value == NULL || !PyLong_Check(value))
@@ -1144,7 +1144,7 @@ int VideoFFmpeg_setPreseek (PyImage * self, PyObject * value, void * closure)
}
// get deinterlace
-PyObject * VideoFFmpeg_getDeinterlace (PyImage * self, void * closure)
+static PyObject *VideoFFmpeg_getDeinterlace(PyImage *self, void *closure)
{
if (getFFmpeg(self)->getDeinterlace())
Py_RETURN_TRUE;
@@ -1153,7 +1153,7 @@ PyObject * VideoFFmpeg_getDeinterlace (PyImage * self, void * closure)
}
// set flip
-int VideoFFmpeg_setDeinterlace (PyImage * self, PyObject * value, void * closure)
+static int VideoFFmpeg_setDeinterlace(PyImage *self, PyObject *value, void *closure)
{
// check parameter, report failure
if (value == NULL || !PyBool_Check(value))
@@ -1239,9 +1239,9 @@ PyTypeObject VideoFFmpegType =
};
// object initialization
-static int ImageFFmpeg_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
+static int ImageFFmpeg_init (PyObject *pySelf, PyObject *args, PyObject *kwds)
{
- PyImage * self = reinterpret_cast<PyImage*>(pySelf);
+ PyImage *self = reinterpret_cast<PyImage*>(pySelf);
// parameters - video source
// file name or format type for capture (only for Linux: video4linux or dv1394)
char * file = NULL;
@@ -1269,7 +1269,7 @@ static int ImageFFmpeg_init (PyObject * pySelf, PyObject * args, PyObject * kwds
return 0;
}
-PyObject * Image_reload (PyImage * self, PyObject *args)
+static PyObject *Image_reload(PyImage *self, PyObject *args)
{
char * newname = NULL;
if (!PyArg_ParseTuple(args, "|s:reload", &newname))
diff --git a/source/gameengine/VideoTexture/VideoFFmpeg.h b/source/gameengine/VideoTexture/VideoFFmpeg.h
index e63032e0c66..d5b575851ee 100644
--- a/source/gameengine/VideoTexture/VideoFFmpeg.h
+++ b/source/gameengine/VideoTexture/VideoFFmpeg.h
@@ -204,11 +204,11 @@ private:
static void *cacheThread(void *);
};
-inline VideoFFmpeg * getFFmpeg (PyImage * self)
+inline VideoFFmpeg *getFFmpeg(PyImage *self)
{
return static_cast<VideoFFmpeg*>(self->m_image);
}
-#endif //WITH_FFMPEG
+#endif /* WITH_FFMPEG */
-#endif
+#endif /* __VIDEOFFMPEG_H__ */
diff --git a/source/gameengine/VideoTexture/blendVideoTex.cpp b/source/gameengine/VideoTexture/blendVideoTex.cpp
index 627da57baac..dd9d83c043f 100644
--- a/source/gameengine/VideoTexture/blendVideoTex.cpp
+++ b/source/gameengine/VideoTexture/blendVideoTex.cpp
@@ -26,6 +26,8 @@ http://www.gnu.org/copyleft/lesser.txt.
#include "PyObjectPlus.h"
+#include "KX_PythonInit.h"
+
#include <RAS_GLExtensionManager.h>
#include <RAS_IPolygonMaterial.h>
@@ -46,10 +48,10 @@ http://www.gnu.org/copyleft/lesser.txt.
// get material id
-static PyObject * getMaterialID (PyObject *self, PyObject *args)
+static PyObject *getMaterialID (PyObject *self, PyObject *args)
{
// parameters - game object with video texture
- PyObject * obj = NULL;
+ PyObject *obj = NULL;
// material name
char * matName;
@@ -70,13 +72,13 @@ static PyObject * getMaterialID (PyObject *self, PyObject *args)
// get last error description
-static PyObject * getLastError (PyObject *self, PyObject *args)
+static PyObject *getLastError (PyObject *self, PyObject *args)
{
return PyUnicode_FromString(Exception::m_lastError.c_str());
}
// set log file
-static PyObject * setLogFile (PyObject *self, PyObject *args)
+static PyObject *setLogFile (PyObject *self, PyObject *args)
{
// get parameters
if (!PyArg_ParseTuple(args, "s:setLogFile", &Exception::m_logFile))
@@ -87,10 +89,10 @@ static PyObject * setLogFile (PyObject *self, PyObject *args)
// image to numpy array
-static PyObject * imageToArray (PyObject * self, PyObject *args)
+static PyObject *imageToArray(PyObject *self, PyObject *args)
{
// parameter is Image object
- PyObject * pyImg;
+ PyObject *pyImg;
char *mode = NULL;
if (!PyArg_ParseTuple(args, "O|s:imageToArray", &pyImg, &mode) || !pyImageTypes.in(Py_TYPE(pyImg)))
{
@@ -168,9 +170,9 @@ static struct PyModuleDef VideoTexture_module_def = {
0, /* m_free */
};
-PyObject* initVideoTexture(void)
+PyObject *initVideoTexture(void)
{
- PyObject * m;
+ PyObject *m;
// initialize GL extensions
//bgl::InitExtensions(0);
@@ -208,7 +210,7 @@ PyObject* initVideoTexture(void)
pyFilterTypes.reg(m);
Py_INCREF(&TextureType);
- PyModule_AddObject(m, (char*)"Texture", (PyObject*)&TextureType);
+ PyModule_AddObject(m, (char*)"Texture", (PyObject *)&TextureType);
PyModule_AddIntConstant(m, (char*)"SOURCE_ERROR", SourceError);
PyModule_AddIntConstant(m, (char*)"SOURCE_EMPTY", SourceEmpty);
PyModule_AddIntConstant(m, (char*)"SOURCE_READY", SourceReady);
diff --git a/source/tests/CMakeLists.txt b/source/tests/CMakeLists.txt
index 2bad58699a8..dd84882bea3 100644
--- a/source/tests/CMakeLists.txt
+++ b/source/tests/CMakeLists.txt
@@ -27,11 +27,11 @@ set(TEST_SRC_DIR ${CMAKE_SOURCE_DIR}/../lib/tests)
set(TEST_OUT_DIR ${CMAKE_BINARY_DIR}/tests)
# ugh, any better way to do this on testing only?
-execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${TEST_OUT_DIR})
+execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${TEST_OUT_DIR})
-#~ if(NOT IS_DIRECTORY ${TEST_SRC_DIR})
-#~ message(FATAL_ERROR "CMake test directory not found!")
-#~ endif()
+#~ if(NOT IS_DIRECTORY ${TEST_SRC_DIR})
+#~ message(FATAL_ERROR "CMake test directory not found!")
+#~ endif()
# all calls to blender use this
if(APPLE)
diff --git a/source/tests/batch_import.py b/source/tests/batch_import.py
index 5c228c014ca..177ab8ea0b0 100644
--- a/source/tests/batch_import.py
+++ b/source/tests/batch_import.py
@@ -63,12 +63,12 @@ def clear_scene():
def batch_import(operator="",
- path="",
- save_path="",
- match="",
- start=0,
- end=sys.maxsize,
- ):
+ path="",
+ save_path="",
+ match="",
+ start=0,
+ end=sys.maxsize,
+ ):
import addon_utils
_reset_all = addon_utils.reset_all # XXX, hack
diff --git a/source/tests/bl_load_addons.py b/source/tests/bl_load_addons.py
index 21a0101d684..5d9ac750362 100644
--- a/source/tests/bl_load_addons.py
+++ b/source/tests/bl_load_addons.py
@@ -36,7 +36,7 @@ def reload_addons(do_reload=True, do_reverse=True):
for mod_name in list(addons.keys()):
addon_utils.disable(mod_name)
- assert(bool(addons) == False)
+ assert(bool(addons) is False)
# Run twice each time.
for i in (0, 1):
diff --git a/source/tests/bl_load_py_modules.py b/source/tests/bl_load_py_modules.py
index 619cad67cb8..b634b4c4385 100644
--- a/source/tests/bl_load_py_modules.py
+++ b/source/tests/bl_load_py_modules.py
@@ -49,7 +49,7 @@ def load_addons():
for mod_name in list(addons.keys()):
addon_utils.disable(mod_name)
- assert(bool(addons) == False)
+ assert(bool(addons) is False)
for mod in modules:
mod_name = mod.__name__
diff --git a/source/tests/bl_mesh_modifiers.py b/source/tests/bl_mesh_modifiers.py
index 390679800f6..92fae25df16 100644
--- a/source/tests/bl_mesh_modifiers.py
+++ b/source/tests/bl_mesh_modifiers.py
@@ -846,7 +846,7 @@ if __name__ == "__main__":
@persistent
def load_handler(dummy):
print("Load Handler:", bpy.data.filepath)
- if load_handler.first == False:
+ if load_handler.first is False:
bpy.app.handlers.scene_update_post.remove(load_handler)
try:
main()
diff --git a/source/tests/bl_rna_wiki_reference.py b/source/tests/bl_rna_wiki_reference.py
index 2018c4327a3..cfe7f22f7dd 100644
--- a/source/tests/bl_rna_wiki_reference.py
+++ b/source/tests/bl_rna_wiki_reference.py
@@ -21,38 +21,71 @@
# Use for validating our wiki interlinking.
# ./blender.bin --background -noaudio --python source/tests/bl_rna_wiki_reference.py
#
-# 1) test_lookup_coverage() -- ensure that we have lookups for _every_ RNA path
-# 2) test_urls() -- ensure all the URL's are correct
-# 3) test_language_coverage() -- ensure language lookup table is complete
+# 1) test_data() -- ensure the data we have is correct format
+# 2) test_lookup_coverage() -- ensure that we have lookups for _every_ RNA path
+# 3) test_urls() -- ensure all the URL's are correct
+# 4) test_language_coverage() -- ensure language lookup table is complete
#
import bpy
-# a stripped down version of api_dump() in rna_info_dump.py
+def test_data():
+ import rna_wiki_reference
+
+ assert(isinstance(rna_wiki_reference.url_manual_mapping, tuple))
+ for i, value in enumerate(rna_wiki_reference.url_manual_mapping):
+ try:
+ assert(len(value) == 2)
+ assert(isinstance(value[0], str))
+ assert(isinstance(value[1], str))
+ except:
+ print("Expected a tuple of 2 strings, instead item %d is a %s: %r" % (i, type(value), value))
+ import traceback
+ traceback.print_exc()
+ raise
+
+# a stripped down version of api_dump() in rna_info_dump.py
def test_lookup_coverage():
def rna_ids():
-
import rna_info
struct = rna_info.BuildRNAInfo()[0]
for struct_id, v in sorted(struct.items()):
props = [(prop.identifier, prop) for prop in v.properties]
+ struct_path = "bpy.types.%s" % struct_id[1]
for prop_id, prop in props:
- yield "bpy.types.%s.%s" % (struct_id[1], prop_id)
+ yield (struct_path, "%s.%s" % (struct_path, prop_id))
for submod_id in dir(bpy.ops):
+ op_path = "bpy.ops.%s" % submod_id
for op_id in dir(getattr(bpy.ops, submod_id)):
- yield "bpy.ops.%s.%s" % (submod_id, op_id)
+ yield (op_path, "%s.%s" % (op_path, op_id))
# check coverage
from bl_operators import wm
- for rna_id in rna_ids():
+ set_group_all = set()
+ set_group_doc = set()
+
+ for rna_group, rna_id in rna_ids():
url = wm.WM_OT_doc_view_manual._lookup_rna_url(rna_id, verbose=False)
print(rna_id, "->", url)
+ set_group_all.add(rna_group)
+ if url is not None:
+ set_group_doc.add(rna_group)
+
+ # finally report undocumented groups
+ print("")
+ print("---------------------")
+ print("Undocumented Sections")
+
+ for rna_group in sorted(set_group_all):
+ if rna_group not in set_group_doc:
+ print("%s.*" % rna_group)
+
def test_urls():
pass # TODO
@@ -63,6 +96,7 @@ def test_language_coverage():
def main():
+ test_data()
test_lookup_coverage()
test_language_coverage()
diff --git a/source/tests/bl_run_operators.py b/source/tests/bl_run_operators.py
index 53cc37bc02b..f792b83a8cd 100644
--- a/source/tests/bl_run_operators.py
+++ b/source/tests/bl_run_operators.py
@@ -44,7 +44,7 @@ op_blacklist = (
"help.operator_cheat_sheet",
"wm.keyconfig_test", # just annoying - but harmless
"wm.memory_statistics", # another annoying one
- # "mesh.vertex_color_remove", #crashes! fixme
+ "console.*", # just annoying - but harmless
)
@@ -61,7 +61,7 @@ def filter_op_list(operators):
operators[:] = [op for op in operators if is_op_ok(op[0])]
-def run_ops(operators, setup_func=None):
+def run_ops(operators, setup_func=None, reset=True):
print("\ncontext:", setup_func.__name__)
# first invoke
for op_id, op in operators:
@@ -70,7 +70,8 @@ def run_ops(operators, setup_func=None):
sys.stdout.flush() # in case of crash
# disable will get blender in a bad state and crash easy!
- bpy.ops.wm.read_factory_settings()
+ if reset:
+ bpy.ops.wm.read_factory_settings()
setup_func()
@@ -82,6 +83,12 @@ def run_ops(operators, setup_func=None):
#traceback.print_exc()
pass
+ if not operators:
+ # run test
+ if reset:
+ bpy.ops.wm.read_factory_settings()
+ setup_func()
+
# contexts
def ctx_clear_scene(): # copied from batch_import.py
@@ -99,7 +106,23 @@ def ctx_clear_scene(): # copied from batch_import.py
def ctx_editmode_mesh():
bpy.ops.object.mode_set(mode='EDIT')
+
+
+def ctx_editmode_mesh_extra():
bpy.ops.object.vertex_group_add()
+ bpy.ops.object.shape_key_add(from_mix=False)
+ bpy.ops.object.shape_key_add(from_mix=True)
+ bpy.ops.mesh.uv_texture_add()
+ bpy.ops.mesh.vertex_color_add()
+ bpy.ops.object.material_slot_add()
+ # editmode last!
+ bpy.ops.object.mode_set(mode='EDIT')
+
+
+def ctx_editmode_mesh_empty():
+ bpy.ops.object.mode_set(mode='EDIT')
+ bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.mesh.delete()
def ctx_editmode_curves():
@@ -107,6 +130,12 @@ def ctx_editmode_curves():
bpy.ops.object.mode_set(mode='EDIT')
+def ctx_editmode_curves_empty():
+ bpy.ops.curve.primitive_nurbs_circle_add()
+ bpy.ops.object.mode_set(mode='EDIT')
+ bpy.ops.curve.delete(type='ALL')
+
+
def ctx_editmode_surface():
bpy.ops.surface.primitive_nurbs_surface_torus_add()
bpy.ops.object.mode_set(mode='EDIT')
@@ -127,6 +156,13 @@ def ctx_editmode_armature():
bpy.ops.object.mode_set(mode='EDIT')
+def ctx_editmode_armature_empty():
+ bpy.ops.object.armature_add()
+ bpy.ops.object.mode_set(mode='EDIT')
+ bpy.ops.armature.select_all(action='SELECT')
+ bpy.ops.armature.delete()
+
+
def ctx_editmode_lattice():
bpy.ops.object.add(type='LATTICE')
bpy.ops.object.mode_set(mode='EDIT')
@@ -137,10 +173,28 @@ def ctx_object_empty():
bpy.ops.object.add(type='EMPTY')
-def ctx_weightpaint():
+def ctx_object_pose():
+ bpy.ops.object.armature_add()
+ bpy.ops.object.mode_set(mode='POSE')
+ bpy.ops.pose.select_all(action='SELECT')
+
+
+def ctx_object_paint_weight():
bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
+def ctx_object_paint_vertex():
+ bpy.ops.object.mode_set(mode='VERTEX_PAINT')
+
+
+def ctx_object_paint_sculpt():
+ bpy.ops.object.mode_set(mode='SCULPT')
+
+
+def ctx_object_paint_texture():
+ bpy.ops.object.mode_set(mode='TEXTURE_PAINT')
+
+
def bpy_check_type_duplicates():
# non essential sanity check
bl_types = dir(bpy.types)
@@ -179,20 +233,38 @@ def main():
#import random
#random.shuffle(operators)
- # Run the operator tests in different contexts
- run_ops(operators, setup_func=lambda: None)
- run_ops(operators, setup_func=ctx_editmode_surface)
- run_ops(operators, setup_func=ctx_object_empty)
- run_ops(operators, setup_func=ctx_editmode_armature)
- run_ops(operators, setup_func=ctx_editmode_mesh)
- run_ops(operators, setup_func=ctx_clear_scene)
- run_ops(operators, setup_func=ctx_editmode_curves)
- run_ops(operators, setup_func=ctx_editmode_mball)
- run_ops(operators, setup_func=ctx_editmode_text)
- run_ops(operators, setup_func=ctx_weightpaint)
- run_ops(operators, setup_func=ctx_editmode_lattice)
-
- print("finished")
+ # 2 passes, first just run setup_func to make sure they are ok
+ for operators_test in ((), operators):
+ # Run the operator tests in different contexts
+ run_ops(operators_test, setup_func=lambda: None)
+ run_ops(operators_test, setup_func=ctx_clear_scene)
+ # object modes
+ run_ops(operators_test, setup_func=ctx_object_empty)
+ run_ops(operators_test, setup_func=ctx_object_pose)
+ run_ops(operators_test, setup_func=ctx_object_paint_weight)
+ run_ops(operators_test, setup_func=ctx_object_paint_vertex)
+ run_ops(operators_test, setup_func=ctx_object_paint_sculpt)
+ run_ops(operators_test, setup_func=ctx_object_paint_texture)
+ # mesh
+ run_ops(operators_test, setup_func=ctx_editmode_mesh)
+ run_ops(operators_test, setup_func=ctx_editmode_mesh_extra)
+ run_ops(operators_test, setup_func=ctx_editmode_mesh_empty)
+ # armature
+ run_ops(operators_test, setup_func=ctx_editmode_armature)
+ run_ops(operators_test, setup_func=ctx_editmode_armature_empty)
+ # curves
+ run_ops(operators_test, setup_func=ctx_editmode_curves)
+ run_ops(operators_test, setup_func=ctx_editmode_curves_empty)
+ run_ops(operators_test, setup_func=ctx_editmode_surface)
+ # other
+ run_ops(operators_test, setup_func=ctx_editmode_mball)
+ run_ops(operators_test, setup_func=ctx_editmode_text)
+ run_ops(operators_test, setup_func=ctx_editmode_lattice)
+
+ if not operators_test:
+ print("All setup functions run fine!")
+
+ print("Finished %r" % __file__)
if __name__ == "__main__":
main()
diff --git a/source/tests/bl_test.py b/source/tests/bl_test.py
index cfe91356444..0cb322a21b1 100644
--- a/source/tests/bl_test.py
+++ b/source/tests/bl_test.py
@@ -145,7 +145,7 @@ def main():
if write_blend is not None:
print(" Writing Blend: %s" % write_blend)
- bpy.ops.wm.save_mainfile(filepath=write_blend, check_existing=False)
+ bpy.ops.wm.save_mainfile('EXEC_DEFAULT', filepath=write_blend)
print(" Result: '%s'" % str(result))
if not result:
diff --git a/source/tests/rna_array.py b/source/tests/rna_array.py
index 06b4735cc0d..a2241dff108 100644
--- a/source/tests/rna_array.py
+++ b/source/tests/rna_array.py
@@ -98,14 +98,14 @@ class TestArray(unittest.TestCase):
for arr, rand_func in zip((test.farr, test.iarr, test.barr), (rand_float, rand_int, rand_bool)):
for i in range(len(arr)):
val= rand_func()
- arr[i]= val
+ arr[i] = val
self.assertEqual(arr[i], val)
# float prop should accept also int
for i in range(len(test.farr)):
val= rand_int()
- test.farr[i]= val
+ test.farr[i] = val
self.assertEqual(test.farr[i], float(val))
#
@@ -115,7 +115,7 @@ class TestArray(unittest.TestCase):
arr[4] = 1.0
def assign_bad_type(arr):
- arr[1]= "123"
+ arr[1] = "123"
for arr in [test.farr, test.iarr, test.barr]:
self.assertRaises(IndexError, assign_bad_index, arr)
@@ -183,7 +183,7 @@ class TestMArray(unittest.TestCase):
rval= make_random_2d_array((4, 5), func)
for i in range(3):
- getattr(test, arr)[i]= rval
+ getattr(test, arr)[i] = rval
self.assertEqual(prop_to_list(getattr(test, arr)[i]), rval)
# arr[i][j] = x
@@ -194,13 +194,13 @@ class TestMArray(unittest.TestCase):
for i in range(3):
for j in range(4):
- arr[i][j]= rval
+ arr[i][j] = rval
self.assertEqual(prop_to_list(arr[i][j]), rval)
def test_assign_item_fail(self):
def assign_wrong_size(arr, i, rval):
- getattr(test, arr)[i]= rval
+ getattr(test, arr)[i] = rval
# assign wrong size at level 2
for arr, func in zip(("fmarr", "imarr", "bmarr"), (rand_float, rand_int, rand_bool)):